Index: branches/Mars_McMismatchStudy/.rootrc
===================================================================
--- branches/Mars_McMismatchStudy/.rootrc	(revision 17960)
+++ branches/Mars_McMismatchStudy/.rootrc	(revision 17960)
@@ -0,0 +1,61 @@
+#############################################################################
+#                                                                           #
+# 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
+Root.Html.ViewCVS:           http://www.astro.uni-wuerzburg.de/viewcvs/
+
+
+#############################################################################
+#                                                                           #
+# Some default changes                                                      #
+#                                                                           #
+#############################################################################
+
+#Canvas.HighLightColor:  3
+#Canvas.MoveOpaque:      0
+#Canvas.ResizeOpaque:    0
+Canvas.ShowEventStatus: Yes
+#Canvas.ShowToolBar:     Yes
+#Canvas.ShowEditor:      Yes
+#Canvas.AutoExec:        No
Index: branches/Mars_McMismatchStudy/Changelog
===================================================================
--- branches/Mars_McMismatchStudy/Changelog	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog	(revision 17960)
@@ -0,0 +1,8 @@
+Please use the svn feature to document your changes.
+
+Please make sure that you document the correct change for any file
+like it was done before in the Changelog files.
+
+Comments should be very precise and must fit to the change commited for
+the particular file. Do not submit submit several files at once 
+if the changes have nothing to do with each other.
Index: branches/Mars_McMismatchStudy/Changelog.02
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.02	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.02	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/Changelog.03
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.03	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.03	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/Changelog.04
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.04	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.04	(revision 17960)
@@ -0,0 +1,10965 @@
+ 
+Please  do  not write behind the end of line tag so that it is  possible
+to   send  a   Changelog   file  to  a  line  printer  directly.  Thanks.
+
+For your entries please follow EXACTLY this style:
+
+_yyyy/mm/dd:_[Your Name]
+_
+___*_filename:
+_____-_description
+_
+___*_filename2, filename3:
+_____-_description
+_
+_
+_
+
+While an underscore is a placeholder for a white-space or an empty line.
+
+
+                                                 -*-*- END OF LINE -*-*-
+
+
+ 2004/12/27 Thomas Bretz
+
+   * macros/CCDataCheck.C:
+     - fixed some warnings: Wrong data access operator
+
+   * manalysis/MCerPhotPix.h:
+     - added to possibility to reset the core-flag
+
+   * mcalib/MCalibColorSet.[h,cc]:
+     - moved some common code to a new function CheckAndSet for
+       simplicity of the color decoding
+     - added an include for stdlib.h (needed for some compilers and atoi)
+
+   * mcalib/MCalibrationIntensityChargeCam.cc:
+     - fixed a warning about a invalid escape sequence -- seems that
+       not all compilers do display this warning...
+     - corrected order of includes
+
+   * mfbase/MFEventSelector2.[h,cc]:
+     - some cosmetic fixes
+     - some adpations to standard output (eg. Separator() instead of ***)
+     - added a check whether 'filter' inherits from MFilter
+     - fixed the return of ReadDistribution
+     - made comments for data members in cleass header 'one line'
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - added fNameGeomCam for parameter list access
+     - added fNameCerPhotEvt for parameter list access
+     - fixed a typo in an output
+     - NO change to ANY algorithm!
+     - changed class version from 1 to 2
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added a rule to replace .raw by .root in MWriteRootFile
+
+   * mranforest/MRanForestCalc.[h,cc]:
+     - fixed missing data member initialization in constructor
+     - added ReadEnv which is able to read a random forest from a file
+     - added an owner flag for the random forest tree
+
+
+
+ 2004/12/22 Markus Gaug
+
+    * mraw/MRawEvtHeader.[h,cc]:
+      - added some new Getter-functions for the calibration conf. 
+        pattern
+ 
+    * mcalib/MCalibrationChargeCalc.[h,cc],
+      mcalib/MCalibrationRelTimeCalc.[h,cc],
+      mcalib/MCalibrationColorSteer.cc:
+      - use the new functions
+
+    * mhcalib/MHCalibrationCam.[h,cc],
+      mhcalib/MHCalibrationRelTimeCam.[h,cc],
+      mhcalib/MHCalibrationChargeCam.[h,cc]:
+      - centralize the decision about the probability limit to be 
+        taken inside these classes.
+ 
+    * mhcalib/MHCalibrationPix.cc
+      - fix a bug in the calculation of outliers. Standard analyses  
+        not affected!
+
+
+
+ 2004/12/22 Eva Domingo
+
+    * mtemp/mifae/library/MImageParDisp.[cc,h]
+      - Container for the estimated distance to source position DISP.
+
+    * mtemp/mifae/library/MDisp.[cc,h]
+      - Container holding the parameters used for the DISP expression.
+        The current DISP parameterization is defined in MDisp::Calc.
+
+    * mtemp/mifae/library/MDispCalc.[cc,h]
+      - Task calculating DISP with the expression and parameter values
+        stored in MDisp. Training and test matrix of variables to be 
+        used in the DISP optimization are also defined within 
+        MDispCalc::InitMapping.
+
+    * mtemp/mifae/library/MHDisp.[cc,h]
+      - Container for the histograms to judge the quality of the DISP 
+        estimate. MHDisp::GetChi2 returns the value of the quantity 
+        requested to be minimized by Minuit, which is defined and 
+        computed in MHDisp::Fill and MHDisp::Finalize. 
+        MHDisp::GetSkymapXY returns the reconstructed map of source 
+        positions. MHDisp::SetSelectedPos function to choose the 
+        selection method of the DISP source position solution.
+
+    * mtemp/mifae/library/MFDisp.[cc,h]
+      - Filter to select a sample of events to do the DISP optimization.
+       Use MFDisp::SetCuts function.
+
+    * mtemp/mifae/library/MFindDisp.[cc,h]
+      - Main class for DISP optimization:
+         ::DefineTrainMatrix, ::DefineTestMatrix, ::DefineTrainTestMatrix
+        generate the training and test samples (in the form of matrices)
+        from the input file.
+	 ::FindParams is the function steering the optimization (over the
+        training sample), calling Minuit, passing the fcn function to be 
+        minimize and defining the event loop to be executed in each step.
+	 ::TestParams tests the quality of the DISP estimate using the 
+        test matrix sample
+
+    * mtemp/mifae/macros/OptimizeDisp.C
+      - macro for estimating the DISP parameter: create training and test
+        matrix; optimize DISP; test quality optimization; calculate DISP
+        and construct skymap for an input file.
+
+    * mtemp/mifae/library/Makefile, mtemp/mifae/library/IFAELinkDef.h
+      - include DISP classes.
+
+
+
+ 2004/12/22: Eva Domingo (for Wolfgang Wittek)
+
+   * mfbase/MFEventSelector2.[h,cc]:
+     - the 'original' distribution, a subsample of which wants
+       to be selected, now can be determined with some previous
+       selection cuts. When determing the 'original' distribution
+       in PreProcess() not only the 'read' object but also the 
+       'filter' object (with the name "FilterSelector2") of the 
+       current event loop is used.
+
+
+
+ 2004/12/22: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/MRanForestPD.C:
+     - added parentheses in the expressions inside the calls to
+       AddColumn() regarding the scaled Width and Length, otherwise
+       they are not interpreted correctly. However, there is no
+       difference in the outcome: the "scaling" seems to be done
+       internally by RF in any case... 
+
+
+
+ 2004/12/17: Markus Gaug
+
+   * mcalib/MCalibColorSet.cc:
+     - added missing runs where run number does not appear any more in 
+       project-name and is not yet set in the digital modules.
+
+   * mcalib/MCalibrationIntensityCam.[h,cc],
+     mcalib/MCalibrationIntensityChargeCam.[h,cc],
+     mcalib/MCalibrationIntensityRelTimeCam.[h,cc]:
+     - added some new functions to display the results of the intensity
+       calibration
+
+
+
+ 2004/12/17: Thomas Bretz
+
+   * showplot.cc:
+     - added the error debug-level to some output
+
+   * mcalib/MCalibColorSet.cc:
+     - replaced arbitrary number for run type by correct enum
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed DrawClonePad such that
+       + before cloning we change into the pad (necessary for 
+         GetDrawOption)
+       + removed SetSelectedPad (seems not necessary at all)
+       + SetBit(kCanDelete) for all cloned object
+       + copy bits kMustCleanup, kCannotPick and kNoContextMenu
+       + oldc is not const anymore (cd()!)
+
+   * mhbase/MH3.[h,cc]:
+     - removed fNameProfX, fNameProfY - didn't work with a more accurate
+       scheme to get the handle to the profile histograms
+     - moved most code from Draw to Paint so that a more accurate handling
+       of read pads containing these histograms is possible
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - moved most code from Draw to Paint so that a more accurate handling
+       of read pads containing these histograms is possible
+
+   * mhflux/MHEffectiveOnTime.[h,cc]:
+     - removed fNameProj* - didn't work with a more accurate
+       scheme to get the handle to the profile histograms
+     - set no option for default AppendPad (istead of "fit" which 
+       didn't work for saved files - for unknown reasons)
+
+
+
+ 2004/12/16: Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.h
+     - set the class number up from 1 to 2
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - another bugfix for the low-gain extraction
+
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+     - fixed bug in display of the averaged cams.
+
+
+
+ 2004/12/15: Thomas Bretz (important bugfixes for callisto)
+
+   * callisto.rc:
+     - fixed wrong names in comments
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed naming of the two MPedCalcFromLoGain
+     - set correct pedestal container for extractor
+
+   * msignal/MArrivalTimeCam.h:
+     - added Reset() function
+
+   * msignal/MExtractTime.cc:
+     - replaced parts of the common PreProcess by new function PreProcessStd
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - removed Clear() in Process() -- this is automatically done by 
+       Reset()
+
+   * msignal/MExtractedSignalCam.h:
+     - added Reset() function
+
+   * msignal/MExtractor.[h,cc]:
+     - moved some common parts of PreProcess to new function PreProcessStd
+       this fixed the problem that searching for fPedestals was
+       overwritten in MExtractTime
+
+   * macros/readrep.C:
+     - added the missing '.' dot to MTime in a comment
+
+   * mhbase/MH3.cc:
+     - draw profile by default not in blue but in the same color as the
+       histogram. Use 'BLUE' option to get the old behaviour
+     - fixed handling of 'same' option
+     - propagate title of axis to profile histogram
+
+
+
+ 2004/12/15: Abelardo Moralejo
+
+   * mmc/MMcConfigRunHeader.h
+     - added data member fPmtTimeJitter, sigma of gaussian of the time
+       jitter introduced in the time of each photoelectron.
+
+
+
+ 2004/12/14: Markus Gaug
+
+   * msignal/MExtractor.[h,cc]
+     - add possibility to set pedestal pointer from outside
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - make modification of extraction window only for case of now 
+       high-gain saturation.
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - fixed some smaller bugs for special cases
+
+   * mcalib/MCalibrationIntensityChargeCam.[h,cc]
+     - implemented automatic plotting of Razmik plot and others
+
+
+
+ 2004/12/14: Markus Gaug and Abelardo Moralejo
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - adjusted the offset from peak search window to extraction window
+       such that they start at the same slice for the case: 
+       fOffsetFromWindow=0. This was the original intention of the 
+       extractor and had been lost at some place. Instead, the default 
+       (fOffsetFromWindow=1) did before correspond to an offset of 2 
+       slices which gave wrong results for the calibration and further
+       default settings. 
+     - Changed one comparison: (Byte_t - Byte_t) > 0 to (Byte_t > Byte_t)
+       since the first mode is always true (a negative "byte" simply gives 
+       256-difference. The version before could have lead to crashes from 
+       time to time.
+
+
+
+ 2004/12/12: Abelardo Moralejo
+
+  * mpoitning/MPointingPosCalc.cc
+    - Changed recently added sanity check in PreProcess so that it is 
+      done only for real data files and not for MC. Corrected typo in
+      warning.
+
+
+
+ 2004/12/09: Markus Gaug
+  
+   * mhcalib/MHCalibrationPix.[h,cc]
+     - fixed a bug in Reset(), fSaturation was not resetted before. 
+       Affects only intensity calibraion.
+   * mhcalib/MHGausEvents.cc
+     - fixed bug in Reset(), histogram ranges were not reset before.
+       Affects only intensity calibraion.
+
+
+
+ 2004/12/09: Thomas Bretz
+
+  * mbadpixels/MBadPixelsTreat.cc:
+    - set default in constructor to UseInterpolation, ProcessPedestalEvt
+      and ProcessTimes which is the callisto default
+    - enhanced comments in output
+
+
+
+ 2004/12/08: Thomas Bretz
+
+  * mraw/MRawRunHeader.cc:
+    - changed maximum allowed format version from 4 to 5
+
+  * mraw/MRawEvtHeader.[h,cc]:
+    - added correct decoding of the 200ns information as proposed by
+      Florian to DecodeTime
+
+   * callisto.cc:
+     - more fixes to make calibration of signal (Y) work again
+
+   * callisto.rc:
+     - adapted to changes in callisto
+     - changed such that the digital filter is used as a default
+
+   * mcalib/MCalibrateData.cc:
+     - allow calibration of Mean and Rms from different input
+       containers
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - removed SetNoiseCalculation -- now in its correct location
+     - added a second MPedCalcFromLoGain
+     - some more default setup
+     - added some new tabs with histograms
+     - ProcessFile now takes too input containers
+
+   * mjobs/MJCalibration.cc:
+     - set rel-time-calibration kTRUE by default
+     - removed SetNoiseCalculation -- now in its correct location
+     - enhanced writing extractors
+
+   * mjobs/MJPedestal.[h,cc]: 
+     - if cloning extractor - don't use name
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - some minor changes to output
+     - fixed order or arguments of FindObject
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - handle SetNoiseCalculation when calculating noise!
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - some minor changes to output
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - some minor changes to output
+     - do not write fNameWeightsFile
+     - do not write fWeightsSet
+     - do not write fRandomIter
+
+   * mpointing/MPointingPosCalc.cc:
+     - added a sanity check in Process
+
+
+
+ 2004/12/06: Abelardo Moralejo
+
+  * macros/starmc.C
+    - Added container MConcentration to output. Added MPointingPosCalc
+      to tasklist, and MPointingPos to output.
+
+  * mtemp/mpadova/macros/resize.C
+    - Added containers MConcentration and MPointingPos to output.
+
+
+
+ 2004/12/06: Thomas Bretz
+
+  * mpedestal/MPedCalcPedRun.cc:
+    - fixed bug which I introdued on friday (PostProcess was
+      defined twice)
+
+   * macros/RanForest.C:
+     - replaced kGAMMA by MMcEvt::kGAMMA
+
+   * mhist/MHCamEvent.[h,cc]:
+     - allow to set name for MGeomCam
+
+   * mjobs/MJCalibration.cc:
+     - removed some obsolete comments
+     - reset SetNoiseCalculation for both extractors
+     - do not allow 'wrong' time&charge calibration (without
+       extractors cam)
+     - removed kTimeAndCharge flag because it is obsolete (nowhere used)
+       and not correctly handled at all
+
+   * callisto.cc, star.cc:
+     - added '--debug-mem' option
+
+   * callisto.rc:
+     - changed such to make it work with the new double-pedestal-loop
+       callisto
+     - default extractor now is Digital Filter
+
+
+
+
+ 2004/12/02: Thomas Bretz
+
+   * mbase/MLog.cc:
+     - fixed some warning about a missing return if __REENTRANT is not
+       defined (like in MAC OS X)
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]:
+     - added possibility to set fPedestals directly by pointer
+     - unfolded some Form statements
+
+   * callisto.cc:
+     - changed callisto to support second pedestal loop -- WORK IN PROGRESS
+
+   * mbase/MParContainer.[h,cc]:
+     - moved code from GetDescriptor to a static function GetDescriptor
+      
+   * mbase/MStatusDisplay.cc:
+     - removed a oboslete debug output
+
+   * mbase/MTaskEnv.h:
+     - made ReadEnv public
+
+   * mcalib/MCalibrationChargeCam.[h,cc]:
+     - changed some returned TArrayF* to TArrayF
+
+   * mimage/MImgCleanStd.cc:
+     - changed point of output of name of MPedPhotCam
+
+   * mjobs/MJCalibration.cc:
+     - don't use MParList to hand ExtractorCam over
+     - some changes to the structur for Writing (only consmetics)
+
+   * mjobs/MJPedestal.[h,cc]:
+     - ordered includes correctly
+     - for the moment removed fNameExtractorCam -- simplifies thing a lot
+     - make a clone of the extractor given by the user - for sanity
+     - correct handling of the allocated memory for fExtractor
+     - replaced counts/slice by cts/slice for space reasons
+     - changed name of new tabs for space reasons
+     - added possibility to CheckEnv to set extractor from resource-file
+     - outsourced some code to SetupExtractor
+     - given a name to MFillH
+     - changed handling of SetNoiseCalculation which is now set correctly all
+       the time
+     - Writing must still be checked!!!
+
+   * mjobs/MJob.[h,cc]:
+     - allow WriteContainer to use any TObject
+     - added Getter-functions for the TEnv stuff
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - allow setting of fPedestalIn by pointer directly
+     - fixed handling of fPedestalIn accordingly
+     - changed some arguments from pointer to reference
+     - changed some accesses to TArrays from At to []-operator
+     - shortened and enhanced output
+     - fixed place and type of screen output
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - removed GetSlice -> replaced by a array with a copy of the data
+     - changed some loops to pointer arithmetic for speed reasons
+       in this case
+
+   * mpedestal/MPedCalcPedRun.[h,cc]:
+     - changed handling of first pedestal run for simplicity
+     - replaced some Form calls
+     - changed direct handling of single bits to correct enums
+     - fixed wrong 'all' in output
+     - simplified output
+     - fixed some stuff in the output
+
+   * mpedestal/MPedestalCam.[h,cc]:
+     - fixed the Copy function - WITHOUT this fix the calibration could
+       not have worked properly at all.
+     - changed some function names to Mars standrad names
+     - removed some obsolete loops - replaced by ForEach
+     - changed some TArrayF* returnes to TArrayF
+
+   * msignal/MExtractTime.cc, msignal/MExtractTimeAndCharge.cc,
+     msignal/MExtractTimeAndChargeDigitalFilter.cc, 
+     msignal/MExtractor.cc
+     - fixed some wrong debug levels in output
+     - some simplification and shortening to output
+
+
+
+
+ 2004/12/02: Markus Gaug
+ 
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - replaced CallPostProcess by public member function Finalize()
+
+
+
+ 2004/12/02: Thomas Bretz
+
+   * msignal/MExtractTime.cc, msignal/MExtractTimeAndCharge.cc,
+     msignal/MExtractor.cc:
+     - removed obsolete output after FindCreateObj
+
+   * msignal/MExtractor.h:
+     - don't write fNoiseCalculation to file
+
+
+
+ 2004/12/01: Markus Gaug and Thomas Schweizer
+ 
+   * mpedestal/MPedCalcFromLoGain.cc
+     - introduce a check which does not allow the last slice of the 
+       check window to be smaller than the last slice of the 
+       extraction window.
+
+
+
+ 2004/12/01: Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]:
+     - introduced a random iterator for the "pedestal" calculation of 
+       the amplitude spline.
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - fixed bug in the loop over the weights which can cause a call to 
+       an array index out of range. Since MArrays are used, this call 
+       could simply produce a segmentation violation (or not), at any 
+       place. This bug was there since the beginning, but should have 
+       happened only in very rare cases.
+
+
+
+ 2004/11/30: Thomas Bretz
+ 
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - InitArrays: added missing return statement
+
+
+
+ 2004/11/30: Markus Gaug
+
+   * macros/calibration.C
+     - new version incorporating the possibility to calculate the 
+       extractor resolution
+
+   * msignal/cosmics_weights_logaintest.dat
+   * msignal/cosmics_weights4_logaintest.dat
+   * msignal/calibration_weights_UV_logaintest.dat
+     - High-low-gain inverted weights files for the TDAS-Extractor 
+       nr. 29, 31, 33. Only to be used for the TDAS-test. The correct 
+       low-gain weights are already included in the "cosmics_weights.dat",
+       "cosmics_weights4.dat" and "calibration_weights_UV.dat".
+
+   * mjobs/MJCalibration.cc
+     - updated to new version of MPedCalcPedRun (only important for 
+       intensity calibration)
+     - installed the new possible handling of two MPedestalCam's - one 
+       for the signal extractor and another one (with the extractor 
+       resolution) for MCalibrationChargeCalc.
+      
+   * msignal/MExtractTimeAndCharge.cc
+     - fixed bug for very high saturating signals setting the low-gain 
+       range wrong. 
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added variable containing the name of the requested MPedestalCam
+
+   * mpedestal/MPedestalCam.[h,cc]
+     - added in Copy-function call to MParContainer::Copy
+     - removed now obsolete ReCalc()-function
+
+   * mpedestal/MExtractPedestal.cc
+     - added reading of ExtractWindow in ReadEnv
+
+   * callisto.rc
+     - updated pedestal initializations
+
+
+
+ 2004/11/30: Wolfgang Wittek
+
+   * mtemp/PaddingExample.C
+     - example macro for the padding
+
+
+
+ 2004/11/29: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - implemented the possibility to extract the pedestal with a 
+       signal extractor. In order to do so, two new commands have to
+       be executed: 
+       1) MJPedestal::SetExtractorResolution()
+       2) MJPedestal::SetPedestals(MPedestalCam& )
+       In the second case, a fully filled PedestalCam has to be 
+       given, which will remained unchanged, however. This cam is 
+       used only to subtract the (AB-noise corrected) pedestals with
+       the signal extractor. 
+     
+       The newly created pedestal Cam can be retrieved via: 
+       MJPedestal::GetPedestals()
+       (like in the other cases as well). 
+    
+       The name of the extractor-filled pedestal cam can be set with:
+       MJPedestal::SetNameExtractorCam()
+
+
+
+ 2004/11/28: Markus Gaug
+
+   * mpedestal/MPedestalPix.cc
+     - removed (fPedestal>=0) in the IsValid() function since now, there 
+       can be valid pedestal Pix's with negative "pedestal".
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractTime.cc
+     - add a check for the pointers fSignal and fArrTime to be initialized
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - fixed documentation of data members
+     - Introduced setter and getter for name of weights file
+     - modified way to use the NoiseCalculation(). Now more compatible
+       with MPedCalcFromLoGain
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - fixed a bug which affects the extractor used with:
+       SetRange(hifirst,hilast,lofirst,lolast) where hilast is bigger
+       than the number of high-gain samples minus 1 (e.g. 14 in case of 
+       MAGIC). While other extractors treat this case by setting a 
+       steering variable ("fHiLoLast") in the ReInit(), this
+       extractor allocates this variable dynamically. However, the 
+       setting in ReInit() was also kept such that in the case that the 
+       peak-search-window did NOT exceed the number of high-gain samples, 
+       the part of the low-gain samples corresponding to fHILoLast was 
+       still extracted. This behaviour is corrected now, I hope it 
+       does not affect any current analysis!
+
+   * mbase/MStatusDisplay.[h,cc]
+     - added GetterFunction for one dedicated pad in the status display.
+       The pad gets resized to normal size, then. 
+
+
+
+ 2004/11/26: Markus Gaug
+
+   * mbase/MRunIter.[h,cc]
+     - fixed the missing initialization of kIsStandardFile to kFALSE. 
+ 
+   * msignal/MExtractTimeAndChargeSpline.h
+     - added Getter Functions for the variables fRiseTime and fFallTime     
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.h
+   * msignal/MExtractFixedWindowPeakSearch.h
+     - added Getter Functions for the variables fWindowSizeHiGain and 
+       fWindowSizeLoGain
+
+   * mpedestal/MHPedestalPix.[h,cc]
+     - removed 
+
+   * mcalib/MCalibrationPix.h
+     - added two new Getters
+
+   * mpedestal/MHPedestalCam.[h,cc]
+     - moved to directory mhcalib. 
+       I'm sorry for this moving around of classes. The important reason
+       is that this class derives from another class in mhcalib/, namely 
+       MHCalibrationCam. It ocurred that compiling this class in a 
+       job-class (e.g. MJPedestalCam), the Cint-Compiler got completely 
+       confused when a TArray or an MArray is part of MHPedestalCam. 
+       Then, the ClassName()'s of some OTHER classes got overwritten. 
+       This happens with a no other data-members and functions except 
+       for a TArray or and MArray. 
+       I have tried different versions of root, always compiling 
+       everything from the beginning, but only this moving solved the 
+       problem (see also a bugreport in mantis).
+     - added a direct calculation of mean's and RMS's stored in the 
+       "LoGain"-variables of MCalibrationPedCam
+
+   * mcalib/MCalibrationPedCam.cc
+     - added new flags in the GetPixelContent called the "low-gain" 
+       entries (s.a.)
+
+   * mcalib/MCalibColorSteer.[h,cc]
+     - removed pointer to MRawRunHeader
+  
+   * mpedestal/MExtractPedestal.[h,cc]
+     - new base class for pedestal extractor.
+     - incorporates possibility to have an incoming pedestal Container 
+       and an outgoing
+     - incorporates possibility to extract pedestals from an extractor
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - derives from MExtractPedestal now 
+     - Add two functions looking for the pedestal bit in the trigger
+       pattern
+     - Add the possibility to skip an event if: 
+       a) the run is not a pedestal run or
+       b) the trigger bit is set to pedestal
+     These modifications allow to use this class for interlaced pedestal
+     events.
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+     - derives from MExtractPedestal now 
+
+   * manalysis/Makefile
+     - removed inclusion of directory mhcalib/
+
+
+
+ 2004/11/23: Markus Gaug
+ 
+   * mbadpixels/MBadPixelsCam.[h,cc]
+     - improved the Print() function such that the individual pixels 
+       matching a certain badness-criterion are listed.
+
+   * mpedestal/MPedestalPix.[h,cc]
+   * mpedestal/MPedestalCam.[h,cc]
+     - introduced Copy-function
+
+
+
+ 2004/11/23: Raquel de los Reyes
+
+   * mbase/MRunIter.[h,cc]
+     - changed the format of the read file to allow the processing of
+       standard F0/F1 (pedestal/calibration) files.
+     - Included a Set function.
+
+
+
+ 2004/11/22: Markus Gaug
+
+   * mcalib/MCalibrationPix.h
+     - new data member fHiGainRms and fLoGainRms requested by Florian  
+       a long time ago to be used for the data check.
+     - set the version number from 1 to 2.
+
+   * mcalib/MCalibrationChargeCam.cc
+     - introduced new flag in GetPixelContent which returns the RMS  
+       divided by mean, to be called by MJCalibration in the datacheck.
+
+   * mhcalib/MHGausEvents.h
+     - new function GetHistRms() returning the RMS of the histogram
+
+   * mhcalib/MHCalibrationCam.cc
+     - stores the histogram RMS in MCalibrationPix in function 
+       FitHiGainHists and FitLoGainHists
+
+   * mjobs/MJCalibration.cc
+     - display in the datacheck the RMS per Mean instead of the reduced
+       sigma per mean which is anyhow reflected by the number of photo-
+       electrons.
+     - put a class MPedCalcPedRun in the tasklist for the intensity 
+       calibration (does not affect normal calibration).
+
+
+
+ 2004/11/22: Marcos Lopez
+
+   * mhist/MHFindSignificance.h:
+     - fixed the return type of some getter functions. Some was returning 
+       Float_t instead of Int_t and other Float_t instead of Double_t.
+     - added more getter functions.
+
+
+
+ 2004/11/22: Markus Gaug
+ 
+   * mcalib/MCalibColorSet.cc
+     - added runs 44768, 44976 and 45368 as blue runs
+     - added patch to work until the lecture of the .run files is 
+       synchronized with this class: All calibration runs are assumed 
+       to be 10Led_UV. This has to be removed immediately when the 
+       synchronization is done and serves especially the data-check.  
+
+
+
+ 2004/11/22: Thomas Bretz
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - added check for \015 character in filename
+
+
+
+ 2004/11/22: Abelardo Moralejo
+
+   * mfbase/MFEventSelector2.cc
+     - Fixed error in Process: calls to Select and SelectProb were 
+       exchanged.
+     - Added example to documentation on how to use the "probability"
+       option.
+
+   * mfbase/MFEventSelector.h
+     - Fixed typo in comment
+
+   * mfilter/MFSize.[h,cc]
+     - removed class. The same kind of filtering can now be done, in  
+       a more versatile way, with MFEventSelector2
+
+   * mfilter/Makefile, FilterLinkDef.h
+     - removed class MFSize
+
+   * mtemp/mpadova/macros/resize.C
+     - Now the class MFEventSelector2 is used instead of the removed
+       MFSize. Behaviour is the same. Default probabilities have been 
+       slightly changed (but this is just an example).
+
+
+
+ 2004/11/18: Hendrik Bartko
+
+   * msignal/MC_weights_2GSamples.dat:
+     - new weights file for MC simulations of the 2 GSamples FADCs
+
+
+
+ 2004/11/18: Wolfgang Wittek
+
+   * mbadpixels/MHBadPixels.[h,cc]
+     - include 'fCam' to set the size of MPedPhotCam;
+       why is the size of MPedPhotCam equal to 0 ???
+     - use "UseCurrentStyle()" when drawing a histogram
+     - in SetupFill() the binnings of the histograms may be changed 
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]
+     - print name of MPedPhotCam container in PreProcess
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - use iterator for looping over MCerPhotPix
+     - use "UseCurrentStyle()" when drawing a histogram
+     - in SetupFill() the binnings of the histograms may be changed 
+     - plot also Theta versus phi
+
+   * macros/ONOFFAnalysis.C
+     - replaced part of the code by calls to 
+                - MMakePadHistograms
+                - and to new member functions of MPad
+
+   * manalysis/MMakePadHistograms.[h,cc]
+     - new class; it generates histograms which are needed for the 
+       padding 
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h
+     - add MMakePadHistograms
+
+   * manalysis/MPad.[h,cc]
+     - add member function ReadPadHistograms()  
+
+   * mfilter/MFSelBasic.[h,cc], mfilter/MFSelStandard.[h,cc],
+     mfilter/MFSelFinal.[h,cc]:
+     - move printout of cut values from SetCuts() to PreProcess()
+
+   * mimage/MImgCleanStd.[h,cc]
+     - print name of MPedPhotCam container in PreProcess()
+
+
+
+ 2004/11/18: Thomas Bretz
+
+   * mjobs/MJPedestal.cc:
+     - fixed a bug in the handling of kUsePed which caused the MTaskEnv
+       to be set incorrectly
+
+   * mfbase/MFEventSelector2.[h,cc]:
+     - added possibility to set a propability distribution
+
+   * mgeom/MGeomCam.[h,cc]:
+     - enhanced the Print function
+     - fixed the Clone function for the class being MGeomCam
+     - made InitGeometry public to support unsupported geometries
+
+   * mgeom/MGeomPix.h:
+     - added Copy function
+
+   * mhbase/MH3.[h,cc]:
+     - added a constructor taking a TH1 as argument
+
+
+
+ 2004/11/18: Markus Gaug
+
+   * msignal/MExtractor.[h,cc]
+     - introduce possibility to choose name of MExtractedSignalCam. Need
+       access to different MExtractedSignalCams for comparative extractor
+       studies. Analogues to MPedestalCam in MPedCalcFromLoGain. Default 
+       is "MExtractedSignalCam", like before. 
+     - set version number by one higher because of new data member 
+       "fNameSignalCam"
+
+   * msignal/MExtractTime.[h,cc]
+     - introduce possibility to choose name of MArrivalTimeCam. Need
+       access to different MArrivalTimeCams for comparative extractor
+       studies. Analogues to MPedestalCam in MPedCalcFromLoGain. Default 
+       is "MArrivalTimeCam", like before. 
+     - set version number by one higher because of new data member 
+       "fNameTimeCam"
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - initialize MExtractedSignalCam with the name chosen in the base 
+       class.
+
+
+ 2004/11/17: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Added getter method for fMuonCphFraction
+
+
+
+ 2004/11/17: Raquel de los Reyes
+
+   * mhist/MHFindSignificance.cc
+     - commented the creation of a canvas in the DrawFit function. Now it is 
+       allowed the option of display the result in a canvas, previously 
+       created, or in a new one if it doesn't exit.
+
+
+
+ 2004/11/16: Markus Gaug
+
+   * mcalib/MCalibrationRelTimeCalc.cc
+     - make pixels with deviating time resolution unreliable instead of 
+       unsuitable. This should take out 1 or 2 more unsuitable pixels. 
+
+   * mcalib/MCalibColorSet.cc
+     - introduce treatment of the case that one file in between the 
+       sequence of calibration runs is a pedestal file (run type == 1)
+       and return kCONTINUE in the process. As this task is at the 
+       beginning of the tasklist, the calibration tasks will be skipped
+       for these events. This treats now an interlaced pedestal run. 
+       Next will follow an interleaved pedestal event and finally an 
+       interleaved data event.
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - adapt the histogram ranges slightly because I have found high 
+       intensity calibration events creating non desired overflows.
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - fixed a bug in the setting of the window which set always the
+       default before.
+
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - updated numbers to the currently installed pin diode
+
+
+
+ 2004/11/16: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Added comment regarding change in version 4.
+
+   * mmc/MMcFadcHeader.hxx
+     - Added data member fNoiseGainFluctuations. Updated class version
+       to 6
+
+   * mmc/MMcTrigHeader.hxx
+     - Added data members fGainFluctuations and fNoiseGainFluctuations.
+       Will contain same values as the corresponding members in the
+       MMcFadcHeader of MC camera files. We just put them in both 
+       headers because the fluctuations affect both the trigger 
+       signal and the FADC signal.
+
+
+
+ 2004/11/16: Markus Gaug
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - give as argument to UpdateBlindPixelMethod() and 
+       UpdateFFactorMethod() the transmission of the plexiglass and the 
+       its rel. variance. 
+       This divides the normalization factor by those numbers and fixes a 
+       bug in the absolute normalization.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - give the new arguments to MCalibrationQEPix
+
+
+
+ 2004/11/15: Thomas Bretz
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - reset logging stream to CORRECT one after redirection
+     - do not redirect the logging stream if no output file is
+       selected
+
+   * mhist/MHHadronness.cc:
+     - fixed a type in the class description
+
+   * mjobs/MJCalibration.cc:
+     - do not write miracle appearance files by MCalivrationChargeCalc
+
+
+
+ 2004/11/13: Hendrik Bartko
+
+   * msignal/cosmics_weights.dat:
+     - implemented low gain weights from pulpo data
+
+   * msignal/cosmics_weights4.dat:
+     - implemented low gain weights from pulpo data
+
+
+
+ 2004/11/12: Thomas Bretz
+
+   * mraw/MRawEvtData.[h,cc]:
+     - fixed a bug in the initialisation of the arrays (in both
+       cases - hi- and lo-gain - the number of hi gain samples were
+       used
+     - do not try to read lo gains if poslo==NULL
+     - changed return type of GetNum[Hi,Lo]GainSamples from
+       Byte_t to UShort_t to support up to 65535 samples
+
+   * mraw/MRawRunHeader.cc:
+     - updated Print()
+
+
+
+ 2004/11/11: Markus Gaug
+
+   * mcalib/MCalibrationBlindPix.[h,cc]
+     - introduced new data member: fAreaErr which is not zero for the
+       third blind pixel
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrationBlindCamThreeNewStyle.[h,cc]
+     - new class describing the blind pixel camera with three blind 
+       pixels.
+
+   * mjobs/MJCalibration.cc
+     - fixed a typo in the draw command of the blind pixel 
+       (MHCalibrationChargeChargeBlindCam -> MHCalibrationChargeBlindCam)
+     - introduced the new blind pixels initialization
+
+   * msignal/MExtractBlindPixel.cc
+     - added MRawEvtData2 to BranchList
+
+
+
+ 2004/11/11: Thomas Bretz
+
+   * callisto.cc:
+     - fixed a typo in the screen output
+     - added setting of input path to second call to MJPedestal
+       to get the extraction window from the calibration file
+
+   * mastro/MAstroCamera.cc:
+     - made a simple simplification
+
+   * mmuon/MMuonSearchParCalc.cc:
+     - changed some log-output to be standard
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - Updated fTitle
+     - Fixed AddToBranchList entries
+     - invented a new function (ResetArrays)
+     - added a return value to SetCheckRange
+     - added a return value to SetCheckRange
+     - changed arguments of SetExtractWindow to UShort_t which is more
+       intuitive
+     - changed arguments of SetExtractWindow to UShort_t which is more
+       intuitive
+     - changed some log-output to be more standard
+     - changed return type of GetSlice to UShort_t
+     - fixed names of resources to fit variable names
+     - implemented Print()
+     - changed types of default to UShort_t
+     - changed derivement from MExtractor to MTask
+
+   * mraw/MRawRead.cc:
+     - fixed a bug which caused the special pixel indices to be 2,3,4,...
+       instead of 0,1,2,3,...
+
+   * msignal/MExtractor.[h,cc]:
+     - changed non intuitive default argument of SetNoiseCalculation
+       from kFALSE to kTRUE
+
+   * mjobs/MJCalibrateSignal.cc:
+     - automatically get correct range for pedestal extraction 
+       (MPedCalcFromLoGain) from Signal Extractor
+
+   * mjobs/MJPedestal.cc:
+     - simplified a complicated if-else-construction towards a
+       correct setting of ranges also for the calibration of the signal.
+     - added reading of extraction window from calibration file
+       (ReadCalibration)
+     - made sure that in the case of an extractor from a calibration file
+       the extraction window for pedestals is correctly set
+     - set SetPedestalUpdate(kFALSE) as default for MPedCalcFromLoGain
+
+   * mbase/MEvtLoop.cc:
+     - updated a comment
+
+   * msignal/MExtractor.cc:
+     - added printing hi-gain samples
+
+
+
+ 2004/11/10: Abelardo Moralejo
+
+   * mhist/MHHadronness.cc
+     - Changed upper limit of hadronness histograms from 1. to 1.0001.
+       Before, events with hadronness=1 were put in the overflow bin,
+       and they were not counted in the calculation of hadron efficiency
+       or of the quality factors that were displayed in the plots and 
+       on the text messages. At high energies the underestimation of Q
+       could be as large as a 20%.
+
+
+
+ 2004/11/10: Markus Gaug
+
+   * mhcalib/MHCalibrationRelTimeCam.cc
+     - reduced nr of bins from 900 to 200 which is sufficient. 
+       Apparently, Nadia had got some problems with the high memory 
+       needed. 
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - updated the effective number of slices (CAN be used for a rude 
+       pedestal RMS estimation) from 2.5 to 4. (e.g. in case of 6 slices 
+       used by the weights file) after getting the equivalent result 
+       from Hendrik. This should approximate the real pedestal RMS to a 
+       relatively good precision although still the extensive test with 
+       the noise calculation from the extractor directly is missing.
+     - subtract the pedestal right at the beginning instead of twice 
+       during execution of the filter.
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - added treatment of IsNoiseCalculation() for the "integral" 
+       method.
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - added treatment of IsNoiseCalculation().
+
+
+
+ 2004/11/10: Abelardo Moralejo
+
+   * mfbase/MFEventSelector2.cc
+     - Added some comments in class description.
+
+
+
+ 2004/11/09: Abelardo Moralejo
+
+   * mfilter/MFSize.cc
+     - Eliminated allocation of histogram fProb in constructor. Now
+       it has to be supplied by the user.
+
+
+
+ 2004/11/09: Hendrik Bartko
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - implemented an unbiased application of the digital filter in the
+       case of MExtractor::IsNoiseCalibration() is true. Thereby the
+       weights are quasi randomly chosen and applied to the first slices
+       available in the set range
+
+   * msignal/MC_weights.dat
+    - new weights file using 6 slices for the digital filter, especially
+      made for MC pulses
+
+
+
+ 2004/11/09: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - implemented the possibility to use the extractor to calculate the 
+       pedestals. Now, there are three possibilities: 
+
+       1) SetUseData(): will use MPedCalcFromLoGain together with a data
+                        file (and possibly a signal extractor to 
+                        determine the ranges)
+       2) SetUsePedRun(): will use MPedCalcPedRun together with a 
+                          pedestal run (and possibly a signal extractor
+                          to determine the ranges)
+       3) SetUseExtractor(): Will use the extractor itself and checks 
+                          that the flag IsNoiseCalculation() is set.
+
+   * msignal/MExtractor.[h,cc] 
+     - introduced flag "fNoiseCalculation" to be used by the 
+       deriving classes to calculate the noise from a fixed window in 
+       time.
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+     - corrected the documentation of the indiv. functions
+     - some cosmetic changes
+
+   * mpedestal/MPedCalcPedRun.cc
+     - previously the variable fNumLoGainSize was automatically set to
+       2 in case that it was initialized to 0. This is a bugfix, since 
+       the default uses 0 slices (see e.g. MJPedestal) for the low-gain.
+       The effect is rather small since the ped. RMS PER SLICE does not 
+       change so much by going up 2 slices, maybe 1-2% depending on the 
+       extraction window. The smaller the window, the bigger the 
+       relative error.
+
+
+
+ 2004/11/08: Abelardo Moralejo
+
+   * mpedestal/MPedPhotCalc.cc
+     - In ReInit: removed check of whether file is MC file. Now fSumx
+       and fSumx2 are initialized also for MC files. This is needed to
+       run some parts of the calibration over pedestal and calibration 
+       MC files.
+
+
+
+ 2004/11/06: Abelardo Moralejo
+
+   * mbase/MTask.cc
+     - Fixed typo in PrintSkipped: "%5.1f" instead of wrong "5.1f", 
+       which resulted in the percentage of skipped events not being
+       displayed.
+
+   * mimage/MHillasCalc.cc
+     - Changed, in constructor, initialization of size of fErrors from
+       6 to 7, since there are 6 error codes (+ succesful operation)
+       for the Hillas calculations. 
+     - Changed in PostProcess calls to TestBit by calls to TestFlag. 
+       With TestBit, return value was always false and statistics of 
+       the Hillas calculations were never shown!
+
+
+
+ 2004/11/04: Markus Gaug
+
+   * macros/calibration.C
+     - updated comments
+
+
+
+ 2004/11/04: Abelardo Moralejo
+
+   * mmc/MMcConfigRunHeader.h
+     - Added member fMirrorFraction to keep the active fraction of the
+       mirror dish set in the camera simulation. Added Getter & Setter.
+       Added some comments. Update class version to 4.
+
+   * mmc/MMcRunHeader.[hxx,cxx]
+     - Removed member fTelesTheta, fTelesPhi. They make no sense since
+       telescope orientation can change from event to event in MC too.
+       Added getter and setter for fShowerThetaMin and fShowerThetaMax.
+
+   * mmontecarlo/MMcCollectionAreaCalc.[h,cc]
+     - Changed consistency check on MMcRunHeader.fTelesTheta to check
+       on fShowerThetaMin and fShowerThetaMax
+
+   * mfileio/MReadMarsFile.cc
+     - Removed obsolete check of old MC files, which needed the removed
+       data member MMcRunHeader.fTelesTheta.
+
+
+
+ 2004/11/04: Markus Gaug
+
+   * mjobs/MJPedestal.cc
+     - adapted to changes in MPedCalcFromLoGain
+
+
+
+ 2004/11/04: Nepomuk Otte
+
+   * mpedestal/MPedCalFromLoGain
+     - Class interface changed s. MPedCalcFromLoGain.cc
+     - It can now be searched for a signal in all slices 0..29 prior
+       pedestal extraction. This is recommended to do.
+
+
+
+ 2004/11/02: Abelardo Moralejo
+
+   * mfilter/MFSize.[h,cc]
+     - added. A filter to modify the Size spectrum of a sample through
+       cutting out events as a function of their Size.
+
+   * mfilter/Makefile, FilterLinkDef.h 
+     - added new class MFSize.
+
+   * mtemp/mpadova/macros/resize.C
+     - Added. Example of how to use the new filter.
+
+
+
+ 2004/11/01: Markus Gaug
+
+   * msignal/MExtractTimeAndChageDigitalFilter.cc
+     - delete the pointer to derivativelo and derivativehi at the end of 
+       the function
+     - reduce the effective number of high-gain samples (used for the 
+       calculation of the pedestal RMS in the calibration) from 6. to 
+       2.5
+
+
+
+ 2004/11/01: Markus Meyer and Keiichi Mase
+
+   * mmuon/MMuonCalibParCalc.[h,cc]
+     - changed according to Thomas Bretz's suggestion.
+       The main part of the calculation is moved from MMuonCalibPar to 
+       MMuonCalibParCalc.
+     - changed. The function of the UseCleanForWidth is removed since we found 
+       that we should get the Arc Width with uncleaned images.
+
+   * mmuon/MMuonCalibPar.[h,cc]
+     - changed according to Thomas Bretz's suggestion as written above.
+
+   * mmuon/MMuonSearchPar.[h,cc]
+     - changed according to Thomas Bretz's suggestion.
+       The pointer of the funciotn is changed to the reference.
+
+
+
+ 2004/11/01: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/RanForestPD.C
+     - Just some cleaning up of old (commented) code.
+
+
+
+ 2004/11/01: David Paneque
+
+   * mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.cc
+     - Condition to assume a constant background in the fit 
+       of the ON and OFF data is softened: 
+	  1) Bins with zero content are allowed (if they are less than 10%
+	  of the total number of bins used). Yet their error is set to 
+	  a huge number 10E19; which means that they are not taken into account 
+	  in the fit.
+	  2) Maximum number of bins with low content (less than 9) is increased 
+	  from 5% to 20%. The error of these bins is set to 3.
+
+       The motivation of these changes is to allow the fitting procedures also 
+       in those cases where the background rejection is that large that very few 
+       events remain in the background region of the alpha plot. This situation 
+       is occuring quite often when using the Random Forest and SPECIALLY, when 
+       making large SIZE cuts.
+
+
+
+ 2004/10/30: Markus Gaug
+
+   * msignal/MExtractor.h
+   * msignal/MExtractTime.h
+     - set the version number by 1 higher due to the changes on 12.10.
+
+
+
+ 2004/10/29: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/RanForestPD.C
+     - corrected an error which made a few hadrons get into the gamma
+       training sample.
+
+
+
+ 2004/10/28: Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed a bug which caused all files to be added and processed
+       twice
+
+   * mmuon/MMuonCalibParCalc.cc, mmuon/MMuonSearchParCalc.cc:
+     - changed output in PreProcess to fit standards
+
+   * mmuon/MMuonCalibPar.cc:
+     - changed title and axis-title of histograms to fit the Mars
+       titles better
+
+
+
+ 2004/10/26: Abelardo Moralejo
+
+   * mmc/MMcEvt.[hxx,cxx], MMcFadcHeader.hxx
+     - added new data members fFadcTimeJitter and fGainFluctuations for 
+       new camera simulation options. Updated class versions to 4 and 5 
+       respectively
+
+
+
+ 2004/10/22: Thomas Bretz
+
+   * callisto.cc, star.cc:
+     - commented out some checks which became obsolete with some new 
+       features. I'll think of a more convinient check in the future
+
+   * mbase/MDirIter.[h,cc]:
+     - added MakeRegexp which is used instead of TRegexp::MakeWildcard
+       to support better handling of regular expressions
+
+   * mbase/MRunIter.cc:
+     - a small simplification
+
+   * mbase/MStatusDisplay.cc:
+     - fixed a bug in CloseWindow (never use a data member after you 
+       delete 'this')
+
+   * mbase/MTaskEnv.cc:
+     - call ReadEnv also if task is the 'external' one
+
+   * mcalib/MCalibrateRelTimes.cc:
+     - check for unsuitability for run AND event
+
+   * mhist/MHCamera.cc:
+     - fixed the cases in which GetBinError returned NaN
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - implemented reading raw-data
+     - implemented new scheme to setup MDirIter by MSequence
+
+   * mjobs/MJCalibration.[h,cc]:
+     - fixed workaround
+     - implemented new scheme to setup MDirIter by MSequence
+
+   * mjobs/MJPedestal.cc:
+     - implemented new scheme to setup MDirIter by MSequence
+
+   * mjobs/MSequence.[h,cc]:
+     - changed SetupCalls to new scheme allowing to set the file type id
+
+   * mmain/MEventDisplay.cc:
+     - fixed a crash if file is invalid
+
+   * mraw/MRawFileRead.[h,cc]:
+     - replaced default name MRawFileRead by MRead to support MJ*
+     - added IsFileValid
+
+   * msignal/MExtractTime.cc:
+     - fixed call to base ReInit (return value was ignored)
+
+   * msignal/MExtractTimeAndCharge.[h,cc]:
+     - fixed some output
+     - added Print
+     - fixed call to base ReInit (return value was ignored)
+     - set Version Number to 1
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - added Print
+
+
+
+ 2004/10/21: Thomas Bretz
+
+   * star.cc:
+     - added a missing 'return -1'
+
+   * mbase/MLog.cc:
+     - expanded path before opening ofstream
+
+   * mfbase/MF.cc:
+     - added a comment
+
+   * mhbase/MH3.cc:
+     - fixed behaviour of projections in status-display
+
+   * mhflux/MHAlpha.cc:
+     - fixed TLatex output
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - replaced cut in L/D by D/W (which is more physical)
+
+
+
+ 2004/10/21: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - fixed a bug occurring in the case that the colour changes in one 
+       same MRunIter. Returns now kFALSE instead of kCONTINUE
+
+
+
+ 2004/10/20: Thomas Bretz
+
+   * msignal/MExtractTimeFastSpline.cc:
+     - fixed a compiler warning: Unused variable
+
+   * mjob/MJPedestal.cc:
+     - added "DisableOutput" as a resource option
+
+   * mbase/MArrayF.h:
+     - added a new Reset(Float_t) member function
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - enrolled some if-else blocks
+     - fixed includes
+     - enhanced error handling when a file is read
+     - moved output from PostProcess to PreProcess
+     - fixed and enhanced ReadEnv
+
+   * mjob/MJCalibrateSignal.cc:
+     - enabled variance display for tabs showing signal
+
+   * mhist/MHCamera.cc:
+     - fixed returning GetBinError for kProfile mode switched on
+
+   * mbase/MDirIter.cc:
+     - fixed a bug in the Sort function: AddDirectory was incorrectly used
+
+
+ 2004/10/20: Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - fixed a small bug concerning the way the second derivatives are 
+       calculated. The effect is less than 1% on the time resolution
+
+   * msignal/MExtractTimeFastSpline.cc
+     - comment the search for the half maximum and use the maximum again. 
+       The half maximum fails sometimes by 0.5 slices which seems to be 
+       some intrinsic behavior of the calibration pulses. 
+       The maximum seems to be OK, though. 
+
+
+
+ 2004/10/19: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - adapted to latest version of Camera simulation, which for stereo
+       configurations creates one MMcConfigRunHeader per telescope,
+       instead of a single one, as it used to be. So now we add the
+       serial number when looking for the container in ReInit.
+
+
+
+ 2004/10/12: Markus Gaug 
+
+   * msignal/MExtractor.h, msignal/MExtractTime.h
+     - put fOffSetLoGain from MExtractTime to MExtractor. Like this, it 
+       is accessible for all extractor classes.
+
+
+
+ 2004/10/12: Abelardo Moralejo
+
+   * mmc/Mdefine.h
+     - Removed #define FADC_SLICES (was duplicated)
+
+   * mmc/MTriggerDefine.h, MFadcDefine.h
+     - Changed names of a few #defines used by the camera simulation 
+       code, to make their meanings clearer.
+
+
+
+ 2004/10/12: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - fixed documentation of data members
+     - implemented option kNoStorage for neither reading nor writing 
+       the F0-files to disk.
+
+   * mjobs/MJCalibration.[h,cc]
+     - implemented option SetTimeAndCharge() in order to use the 
+       extractor deriving from MExtractTimeAndCharge, like e.g. the 
+       digital filter.
+
+   * mhcalib/MHCalibrationCam.cc
+     - fixed a bug in the binning of the low-gain events, affected 
+       the relative times in case of high-gain saturation.
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - fix the range for the low-gain extraction dynamically by 
+       using the calculated time of the high-gain extraction. This 
+       should solve the problem reported by Nuria for the extractors
+       deriving from this class.   
+
+
+
+ 2004/10/11: Markus Gaug
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - calculate addtionally to the usual pedestal the ABOffset, like 
+       in MPedCalcFromLoGain. 
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]
+     - fixed class documentation and some last bugs.
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.[h,cc]
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - the combined extractor class sliding window and highest integral
+       with pedestal-AB-flag corrected, to be used for the TDAS-extractor
+
+
+
+ 2004/10/08: Markus Meyer and Keiichi Mase
+ 
+   * mmuon/MMuonSearchPar.[h,cc], mmuon/MMuonCalibPar.[h,cc],
+     - changed according to Thomas's suggestion. The main changes are the
+       followings;
+        1. The parameter name is changed in order to make the name self
+           descriptive.
+        2. The version come back to 1.
+        3. The TH1 objects are changed to pointers.
+        4. The fixed value of the pre cuts now can be set by yourself.
+
+   * mmuon/MMuonSearchParCalc.[h,cc], mmuon/MMuonCalibParCalc.[h,cc],
+     - added. In principle, you can work out, but these classes has to be
+       checked by Thomas. Therefore, remind that this class may be changed.
+
+
+
+ 2004/10/08: R. DelosReyes
+
+  * mbase/MRunIter.h
+    - changed the name of the Sort() function name by SortRuns() 
+      to avoid conflicts with the Sort() function in the MDirIter class.
+
+
+
+ 2004/10/07: Markus Gaug
+
+  * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+    - uncommented the Clone() function (which otherwise causes 150MB to 
+      be cloned). It is from now on working exactly equal like in 
+      MHCalibrationChargeCam which behaved fine until now. 
+
+  * mpedestal/MPedCalcFromLoGain.cc
+    - fixed the case that a window size of 1. is handed over which 
+      previously set the window size to the next smaller even number, 
+      which is 0. Now, it sets it to 2. This makes this class usable 
+      together with the amplitude spline.
+       
+  * msignal/MExtractTimeAndChargeSpline.[h,cc]
+    - combined extractor: MExtractTimeFastSpline 
+      and MExtractAmplitudeSpline, to be used like Hendrik's filter, 
+      i.e. in combination with: MJCalibration::SetTimeAndCharge()
+
+
+
+ 2004/10/06: Hendrik Bartko
+
+  * msignal/cosmics_weights4.dat
+    - new weights file using 4 slices for the digital filter
+
+
+
+ 2004/10/05: Markus Gaug
+   
+  * mcalib/MCalibrationChargePix.[h,cc]
+  * mcalib/MCalibrationChargeCalc.cc
+    - after talking with Florian, we reduced the electronic noise for the 
+      low-gain pedestal calculation from 1.5 to 1.0, independent from
+      inner or outer pixels. 
+    - additionally found a small bug in the calculation of the low-gain 
+      pedestal RMS which amounts to about the same size as the difference 
+      in the assumed electronic noise.
+
+  * mcalib/MCalibrationChargeCalc.cc
+    - fixed small bug for the case that multiple colours are found, but 
+      no intensity calibration is used.
+
+  * msignal/MExtractTimeAndCharge.cc
+    - fixed small bug in the calculation of the low-gain AB flag.
+
+  * mcalib/MCalibrateData.cc
+    - fixed bug nr. ID 144
+
+
+
+ 2004/10/05: Thomas Bretz
+
+   * mjobs/MJStar.cc:
+     - removed rate cut from eventloop because its highly untested and
+       unstable
+
+   * macros/tar.C:
+     - removed mtemp-directory from tarball
+
+   * macros/rootlogon.C, macros/dohtml.C:
+     - added mmuon
+     - added mtrigger
+     - added mhflux
+
+
+
+ 2004/10/05: Markus Meyer and Keiichi Mase
+ 
+   * mmuon/MMuonSearchPar.[h,cc], mmuon/MMuonCalibPar.[h,cc],
+     mmuon/Makfile, mmuon/MuonLinkDef.h, mmuon/MuonIncl.h:
+     - added: Finally our muon classes are merged and commited.
+       These are container classes and will not work only by themselves.
+       After Thomas's check, we will commit the task classes, then
+       you can use it.
+
+
+ 2004/10/04: Markus Gaug 
+ 
+   * mjobs/MJPedestal.h
+     - added function SetPedContainerName() 
+
+
+
+ 2004/10/04: Hendrik Bartko
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - fixed a bug in the weights calculation
+
+
+
+ 2004/10/01: Thomas Bretz
+
+   * mcalib/MCalibrationChargeCalc.cc, 
+     mcalib/MCalibrationRelTimeCalc.cc,
+     mhcalib/MHCalibrationChargeCam.cc.
+     mhcalib/MHCalibrationRelTimeCam.cc:
+     - changed some output to fit into a standard 80-col
+       console
+
+   * mhist/MHCamEvent.[h,cc]:
+     - added the option to count 'above threshold'
+       (former MHTrigger)
+
+   * mhist/MHCamEventRot.[h,cc]:
+     - added the option to count 'above threshold'
+
+   * mhist/MHCamera.[h,cc]:
+     - fixed filling of thresholded events (CntCamContent)
+       such that it takes the 'used'flag into account
+
+   * mjobs/MJStar.cc:
+     - added plots showing how often a pixel survived image 
+       cleaning and the corresponding derotated 2D plot
+
+   * mjobs/MJCalibrateSignal.cc:
+     - display in all plots in which we expect a stable value
+       the variance instead of the rms
+
+   * mjobs/MJPedestal.cc, mjobs/MJCalibration.cc:
+     - fixed usage of raw-data files and AddDatRuns
+
+   * mjobs/MJob.cc:
+     - fixed a typo in an output
+
+   * callisto.cc:
+     - removed "-mc" option (now autodetected)
+       --> to be done in the other jobs, too
+
+   * mfileio/MRead.[h,cc], mfileio/MReadMarsFile.[h,cc],
+     mfileio/MReadTree.[h,cc], mjobs/MJCalibrateSignal.[h,cc],
+     mraw/MRawFileRead.[h,cc]:
+     - implemented IsFileValid as a first step to file auto-detection
+
+
+
+ 2004/09/30: Hendrik Bartko, Markus Gaug
+
+   * msignal/MExtractFixedWindowSpline.cc
+     - corrected a small bug for the case that the high-gain extraction 
+       window ranges into the low-gain
+
+   * mjobs/MJPedestal.cc
+     - use MPedCalcFromLoGain if IsUseData() is set
+
+
+
+ 2004/09/29: Hendrik Bartko, Diego Tescaro, Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - Hendriks digital filter finally implemented
+
+   * msignal/cosmics_weights.root msignal/calibration_weights_UV.root
+     - needed weights for the digital filter
+
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - added MExtractTimeAndChargeDigitalFilter and 
+       MExtractTimeAndCharge
+
+   * msignal/MExtractTime.h
+     - made PreProcess, ReInit and Process protected
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - added variable abflag in function FindTimeAndChargeHiGain and 
+       FindTimeAndChargeLoGain
+
+
+
+ 2004/09/29: Thomas Bretz
+
+   * mhist/MHEvent.[h,cc]:
+     - enhanced display
+
+   * mmain/MEventDisplay.cc:
+     - adapted to changes in MEventDisplay
+
+
+
+ 2004/09/28: Thomas Bretz
+
+   * mbase/MGMap.h:
+     - added Clear() function
+
+   * mfileio/MReadReports.[h,cc]:
+     - added GetReader member function
+
+   * mhbase/MBinning.h:
+     - set a default for a constructor argument
+
+   * mhbase/MH.cc:
+     - do not treat errors when enhancing histograms
+       if errors are not set
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - changed conditions for fit:
+       + 5% - 95%  --->  60% - 99%
+       + start value 200Hz
+       + ok if chi2<3*NDF
+     - resturn chi2 as result of fit
+     - changed some text output in pads
+
+   * mhflux/MHFalseSource.cc:
+     - made work without MPointingPos
+     - fixed crash if star-display is used
+     - fixed dissapearing alpha plot
+
+   * mhist/MHCamEvent.[h,cc]:
+     - removed rms histogram
+     - enhanced display
+     - fixed handling of title
+
+   * mhist/MHCamera.[h,cc]:
+     - simplified projection functions a bit
+     - simplified profile functions a bit
+     - added default for binning
+     - added binning to Profiles
+
+   * mimage/MConcentration.c:
+     - fixed author list
+
+   * mimage/MHHillas.cc:
+     - display size as logy
+
+   * mimage/MHHillasExt.cc, mimage/MHHillasSrc.cc:
+     - fixed binnings
+     - removed obsolete pad->Update in Draw
+
+   * mimage/MHImagePar.cc:
+     - fixed setting of log-scale
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed histogram titles and axis titles
+
+   * mjobs/MJStar.cc:
+     - added EventRate cut which cuts out events with extremely
+       changing rates
+
+   * mmain/MEventDisplay.cc:
+     - unlock event display
+
+   * msignal/MArrivalTime.cc:
+     - fixed GetPixelContent
+
+   * mastro/MAstroCamera.cc:
+     - replaced "unknown" by "n/a"
+
+   * mbase/MDirIter.[h,cc]:
+     - added Sort function (not yet fully tested)
+
+   * mgeom/MGeomCam.cc:
+     - removed automatic setting of ReadyToSave in constructor
+       PLEASE contact me if you have trouble with this
+
+   * mraw/MRawFileRead.cc:
+     - SetReadyToSave for run-header after reading
+
+   * msignal/MExtractSlidingWindow.cc:
+     - fixed ReInit-output
+
+
+
+ 2004/09/28: Raquel de los Reyes
+
+   * mbase/MRunIter.cc
+     - Changes in the AddRun function to read the old and the new DAQ 
+       numbering format. Changes took place between runs 35487 and 
+       00035488 (2004_08_30)
+
+
+
+ 2004/09/27: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/plotnoise.C
+     - Added. Macro to compare the piled-up signals for many pixels and
+       events together, intended to check the noise fluctuations.
+
+
+
+ 2004/09/23: Markus Gaug
+ 
+   * mhcalib/MHCalibration*Cam.[h,cc]
+     - replaced the TObjArrays by TOrdCollections because the TObjArrays
+       do not enter the streamer. In case, the histograms want to be 
+       stored, need to use an TOrdCollection, instead, like in the 
+       MCalibration*Cam classes. 
+     - simplified the naming of the histograms somewhat
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - added enum DataType_t to set in which MRawEvtData container the 
+       blind pixel is found. The container of the blind pixel has changed 
+       from MRawEvtData to MRawEvtData2
+
+   * mcalib/MCalibrationBlindCam.[h,cc]
+     - added function SetPulserColor which was only available in 
+       MCalibrationBlindPix. 
+
+   * mcalib/MCalibrationChargeBlindCam.[h,cc]
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - removed the two classes since obsolete
+
+   * mcalib/MCalibrationCam.h
+     - make SetPulserColor virtual
+
+   * mcalib/MCalibrationQECam.[h,cc]
+     - added new functions to display cornings vs. quantum efficiencies
+
+   * mcalib/MCalibrationQEPix.cc
+     - changed transmission probability of plexiglass from 0.96 to 0.92
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - added a CallPostProcess() function in order to avoid setting 
+       back the fPreProcessed flag which otherwise impedes the linearity
+       calibration to be performed
+
+   * mhcalib/MHGausEvents.[h,cc]
+     - added function SimulateGausEvents()
+
+
+
+ 2004/09/23: Abelardo Moralejo
+   * mtemp/mpadova/macros/area.C, RanForestPD.C, gammarate.C
+     - Added
+
+   * macros/starmc.C
+     - Added some missing RunHeaders in the output
+
+
+
+ 2004/09/19: Thomas Bretz
+
+   * mbadpixels/MBadPixlesCam.[h,cc]:
+     - added Reset-function. This makes sure, that the event-wise
+       bad pixels determined by MBadPIxelsCalc are deleted after
+       one execution of the event-loop and don't remain for all
+       following data
+
+   * mpointing/MPointingPos.cc, mreport/MReportDrive.cc:
+     - initialize the variables in the constructor
+
+
+
+ 2004/09/17: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - introduced two flags to avoid storage of containers or to 
+       store also the histogram containers. Default is like it always
+       was. 
+
+
+
+ 2004/09/17: Thomas Bretz
+
+   * mhcalib/MH*.[h,cc]:
+     - redone some changes from yesterday - for unknown reason they
+       were lost
+
+   * mbase/MTask.cc:
+     - make sure that the correct number of executions is returned
+       counter which cannot be reset properly)
+     - added GetNumExecutionsTotal
+
+   * mdata/MDataArray.cc:
+     - some changes to Print-output
+
+   * mfbase/MF.[h,cc]:
+     - added GetRule
+
+   * mfileio/MReadTree.cc:
+     - some improvements to output
+
+   * mhbase/MHMatrix.cc:
+     - some improvements in Print
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - calculate the significance also from the first bins
+     - added Copy
+     - added print
+
+   * mhflux/MHAlpha.[h,cc]:
+     - added some fFit.Print to keep track of what's going on
+     - give a name to the function, no name results in weired
+       behaviour of the whole system. root people were already informed
+
+   * mhflux/MHFalseSource.cc:
+     - made lines of 2D-Gauss smaller
+
+   * star.cc:
+     - fixed handling of commandline arguments in batch mode
+
+   * mhist/MHEvent.[h,cc], mmain/MEventDisplay.cc:
+     - remove non working signal/ped rms
+
+
+
+ 2004/09/16: Abelardo Moralejo
+
+     WARNING: Today 16/9, between 19.00 and 20.00 aprox, I accidentally 
+     removed and/or changed some classes in mbase/ while updating the 
+     camera simulation code in the CVS. I have put back everything to
+     its original status as soon as I realized this. I am sorry! You 
+     may have encountered compilation problems if you downloaded Mars 
+     during that period. Everything should be OK now, please report
+     otherwise.
+
+
+
+ 2004/09/16: Markus Gaug
+
+   * mhcalib/MHCalibrationChargeBlindPix.cc
+   * mhcalib/MHGausEvents.cc
+     - added call to gROOT->GetListOfFunctions->Remove(f) in destructor
+
+   * mhcalib/MHCalibrationBlindCam.[h,cc]
+     - re-installed the Clone-function. Without, DrawClone() does not 
+       Clone()
+
+
+
+ 2004/09/16: Thomas Bretz
+
+   * mimage/MHillasCalc.[h,cc]
+     - removed obsolete PrintSkipped
+
+   * mhbase/MH.cc, mfilter/MFDeltaT.cc:
+     - Form %5.1 when printing statistics
+
+   * mfilter/MFDeltaT.cc:
+     - enhaced filter criterias
+
+   * mbase/MTime.h:
+     - added IsMidnight
+
+   * mbase/MTask.cc:
+     - changed setw(3) to Form %5.1f
+
+   * mjobs/MJCalibration.[h,cc]:
+     - set default to 'nice' data-check display
+     - removed obsolete FindColor
+
+   * mjobs/MJPedestal.cc:
+     - enhanced output
+
+   * mjobs/MJob.cc:
+     - small changes to output
+
+   * mhflux, mhflux/Makefile, mhflux/FluxLinkDef.h mhflux/FluxIncl.h:
+     - added
+
+   * mhist/MHFalseSource.[h,cc], mhist/MHAlpha.[h,cc], 
+     mhist/MHEffectiveOnTime.[h,cc]:
+     - moved to mhflux
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added
+
+   * Makefile:
+     - added mhflux
+
+   * mhist/MHEffOnTimeTime.[h,cc], mhist/MHEffOnTimeTheta.[h,cc],
+     mhist/MHEffOnTime.[h,cc], mhist/MHTimeDiffTime.[h,cc],
+     mhist/MHTimeDiffTheta.[h,cc], mhist/MHFalseSource.[h,cc], 
+     mhist/MHAlpha.[h,cc], mhist/MHEffectiveOnTime.[h,cc]:
+     - removed
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHEffectiveOnTime
+     - removed MHAlpha
+     - removed MHFalseSource
+     - removed MHFlux (temporary until adapted to MHEffectiveOnTime)
+     - removed MHEffOnTimeTime  (use MHEffectiveOnTime instead)
+     - removed MHEffOnTimeTheta (use MHEffectiveOnTime instead)
+     - removed MHEffOnTime      (use MHEffectiveOnTime instead)
+     - removed MHTimeDiffTime   (use MHEffectiveOnTime instead)
+     - removed MHTimeDiffTheta  (use MHEffectiveOnTime instead)
+     * If you need help to get MHEffectiveOnTIme working please ask me!
+
+   * star.rc:
+     - use scaled image cleaning by default
+
+   * mmontecarlo/MMcCollectionAreaCalc.cc:
+     - fixed some possible crashes
+
+   * mhflux/MAlphaFitter.h:
+     - remove function from global list
+
+   * mhflux/MHFalseSource.cc:
+     - added a 2D Gauss-Fit
+
+   * mimage/MHillasSrc.[h,cc]:
+     - fixed a bug in the output of DCA (wrong units)
+
+   * mhcalib/MHCalibrationChargeBlindCam.[h,cc],
+     mhcalib/MHCalibrationChargeBlindPix.cc,
+     mhcalib/MHCalibrationChargeCam.[h,cc],
+     mhcalib/MHCalibrationChargePINDiode.[h,cc],
+     mhcalib/MHCalibrationRelTimeCam.[h,cc],
+     mhcalib/MHGausEvents.[h,cc]:
+     - took out the Clone-functions. Everything here seems to be
+       a lot more stable without. I guess it is due to the change
+       away from the TClonesArrays which makes the automatic
+       streamed cloning work fine.
+     - moved the removing of TF1 from the destructor to the 
+       allocation of the objects. It seems that already before the
+       destructor can remove the objects from these list 'shit happens'
+
+
+
+ 2004/09/15: Thomas Bretz
+
+   * callisto.rc:
+     - added new line for intensity calibration
+     - fixed MJPedestalY.ExtractPedestal.PedestalUpdate (should be 'no')
+     
+   * mbase/MEvtLoop.cc:
+     - changed such that returning kCONTINUE in MTaskList::Process
+     is allowed
+
+   * mbase/MTaskList.cc:
+     - changed to return kCONTINUE if Task returned kCONTINUE
+
+   * mcalib/MCalibrate.cc, mcalib/MCalibrationChargeCalc.cc:
+     - cosmetics to output
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - added an output/skip in case more than 90% of all pixels have
+       been skipped
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - fixed to read the MJCalibration output
+     - simplified reading container
+
+   * mjobs/MJCalibration.[h,cc]:
+     - simplified writing container
+
+   * mjobs/MJob.[h,cc]:
+     - added WriteContainer
+     - added ReadContainer
+
+   * mpedestal/MPedCalcFromLoGain.cc:
+     - initialize default number of dump events (500)
+     - log status of task in PreProcess
+
+   * mimage/MHillasSrcCalc.cc:
+     - fixed
+     - THE USE OF THIS TASK IS DEPRICATED. PLEASE USE MHillasCalc INSTEAD!!!
+
+   * mimage/MHillas.cc:
+     - enhanced Paint
+
+
+
+ 2004/09/15: Markus Gaug
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - replaced TArrays by MArrays
+     - added Copy function
+
+   * mcalib/MCalibration*Cam.[h,cc]
+     - replace TObjArray by TOrdCollection, otherwise the streamer does not work
+
+   * mimage/MHillasCalc.[h,cc]
+     - move PrintSkipped(int,const char*) to PrintSkipped(UInt_t, const char*)
+       otherwise always warnings about hidden function from MTask
+  
+   * mjobs/MJCalibration.cc
+     - data check plot for the rel. time calibration
+
+   * mhcalib/MHCalibrationCam.cc
+     - set MBadPixelsPix::kLoGainNotFitted only if High-Gain Saturation
+       had occurred. 
+
+   * mhcalib/MHCalibrationChargeCam.cc
+   * mcalib/MCalibrationChargeCalc.cc
+     - simply calls to IntensityCam somewhat
+
+   * mcalib/MCalibrationBlindCam.[h,cc]
+     - added function GetFluxInsidePlexiglass() and variances
+
+
+
+ 2004/09/15: Abelardo Moralejo
+
+   * macros/starmc.C, mccalibrate.C, starmc2.C
+     - adapted to changes in MHillasCalc from August 23. The macros
+       did no longer work, but only today did someone report it... 
+       Sorry!
+
+
+
+ 2004/09/14: Antonio Stamerra
+
+   * mtrigger/MTriggerIPR.h:
+     - added "=" to (idx >= gsNTrigPix) in GetPixelContent
+
+   * macros/readIPR.C:
+     - new macro to read and display the IPRs
+
+   * macro/dohtml.C:
+     - added readIPR
+		
+
+
+
+ 2004/09/14: Markus Gaug
+
+   * mcalib/MCalibChargeCalc.[h,cc]
+     - added IntensityBadPixelsCam and IntensityQECam
+
+   * mhcalib/MHCalibration*Cam.[h,cc]
+   * mcalib/MCalibColorSteer.[h,cc]
+     - added MBadpixelsIntenstiyCam
+
+   * mbadpixels/MBadPixelsIntensityCam.[h,cc]
+   * mcalib/MCalibrationIntensity*Cam.[h,cc]
+   * mcalib/MCalibration*Cam.[h,cc]
+     - replace TClonesArray by TObjArray
+
+   * mjobs/MJCalibration.cc
+     - took out FindColor() which is now taken care of by 
+       MCalibColorSet
+     - introduced MBadPixelsIntensityCam
+
+   * mhcalib/MHGausEvents.cc
+     - some changes in Draw for the case that there is no histogram
+
+   * manalysis/MHPedestalPix.[h,cc]
+   * manalysis/MHPedestalCam.[h,cc]
+     - moved to mpedestal/
+
+   * mpedestal/PedestalLinkDef.h
+   * msignal/SignalLinkDef.h
+     - replaced some '++' by '+'s.
+
+   * mhbase/MH.cc
+     - removed an infinite loop created some hours before.
+
+   * mhcalib/MHGausEvents.[h,cc]
+     - put fEventFrequency back from MHCalibraionPix.
+     - always delete fHPowerProbability, if existing. 
+ 
+   * mhcalib/MHCalibrationPix.[h,cc]
+     - take out fEventFrequency
+
+
+
+ 2004/09/14: Thomas Bretz
+
+   * mbase/MFilter.[h,cc]:
+     - added PrintSkipped
+
+   * mbase/MTask.[h,cc]:
+     - added PrintSkipped
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFDeltaT
+
+   * mhbase/MFillH.[h,cc]:
+     - added forwarding of number of executions
+
+   * mhbase/MH.[h,cc]:
+     - simplified the new Projection functions
+     - added PrintSkipped
+     - increased ClassDef version number to 2
+
+   * mhcalib/HCalibLinkDef.h:
+     - removed second + from MHGausEvents
+
+   * mjobs/MJCalibration.cc:
+     - fixed a comment
+
+   * mjobs/MJStar.cc:
+     - added MFDeltaT
+
+   * mpedestal/MPedCalcFromLoGain.cc: 
+     - fixed a typo in a comment
+
+
+ 
+ 2004/09/13: Antonio Stamerra
+
+   * mtrigger/MTrigger*.h:
+     - removed inheritance from MCamEvent (except MTriggerIPR).
+     - Added Get... functions to retrieve the data members
+
+   * mreport/MReportTrigger.[h,cc]
+     - added fTriggerTable, fL1(L2)Triggertable to the data members
+
+
+
+ 2004/09/13: Markus Gaug 
+  
+   * mjobs/MJCalibration.[h,cc]
+     - added MCalibrationIntensityBlindCam
+     - replaced MCalibrationChargeBlindCam by MCalibrationBlindCam
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - added Copy function
+
+   * mcalib/MCalibrationIntensityBlindCam.[h,cc]
+     - new class for Intensity calibration
+
+   * mcalib/MCalibrationBlindCam.[h,cc]
+   * mcalib/MCalibrationBlindPix.[h,cc]
+     - new containers based on MCalibrationCam and MCalibrationPix. 
+     - similiar to MCalibrationChargePix and MCalibrationChargeCam, but 
+       slightly different data members. In order not to get confused with
+       already stored data, this is for the moment a second, equivalent 
+       class. 
+  
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added Intenisty Calibration for blind pixel
+     - take new MCalibrationBlindCam instead of MCalibrationChargeBlindCam
+
+   * mcalib/MCalibrationCam.cc
+   * mcalib/MCalibrationChargeCam.cc
+   * mcalib/MCalibrationQECam.cc
+   * mcalib/MCalibrationRelTimeCam.cc
+     - initialize fAverageBadPixels in derived classes
+
+   * mhcalib/MHCalibrationChargeBlindCam.[h,cc]
+   * mhcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - derive class from MHCalibrationCam now and treat pointers 
+       like done in MHCalibrationChargeCam
+     - implement Intensity Calibration
+     - write results to MCalibrationBlindCam instead of 
+       MCalibrationChargeBlindCam 
+
+   * mhcalib/MHCalibrationCam.h
+     - took out the "->" for all pointers
+     - introduce new steering flags: 
+       kLoGain, kOscillations, kAverageing, kSizeCheck
+
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+     - wrote a ReadEnv function
+
+   * mbase/MFilter.[h,cc]:
+     - added PrintSkipped
+
+   * mbase/MTask.[h,cc]:
+     - added PrintSkipped
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFDeltaT
+
+   * mhbase/MFillH.[h,cc]:
+     - added forwarding of number of executions
+
+   * mhbase/MH.[h,cc]:
+     - simplified the new Projecttion functions
+     - added PrintSkipped
+     - increased ClassDef version number to 2
+
+   * mhcalib/HCalibLinkDef.h:
+     - removed second + from MHGausEvents
+
+   * mjobs/MJCalibration.cc:
+     - fixed a comment
+
+   * mjobs/MJStar.cc:
+     - added MFDeltaT
+
+   * mpedestal/MPedCalcFromLoGain.cc: 
+     - fixed a typo in a comment
+
+
+
+ 2004/09/13: Thomas Bretz
+
+   * merpp.cc:
+     - added MTrigger* containers to output
+
+   * mastro/MAstro.[h,cc]:
+     - added member function GetDistOnPlain
+
+   * mbase/MDirIter.[h,cc]:
+     - renamed Check to CheckEntry
+
+   * mbase/MMath.[h,c]:
+     - added functions for parabolic interpolation
+
+   * mbase/MStatusArray.[h,cc]:
+     - added functions to access contents
+
+   * mhbase/MBinning.[h,cc]:
+     - added RemoveFirstEdge
+     - added RemoveLastEdge
+     - removed some obsolete const-casts
+
+   * mhbase/MH.[h,cc]:
+     - added RemoveFirstBin
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - fixed number of bins
+     - remove first edge when finalizing
+     - added plots for lambda and NDF
+
+   * mjobs/MJStar.cc:
+     - removed a duplicate line
+
+   * mpointing/MPointing.[h,cc]:
+     - added support for TVector3
+     - added ClassDef and ClassImp for AltAz
+     - added ClassDef and ClassImp for ZdAz
+
+   * mpointing/MSrcPosFromModel.[h,cc]:
+     - changed to directly calculate the source position 
+       from a pointing model
+
+   * mpointing/PointingLinkDef.h:
+     - added AltAz
+     - added ZdAz
+     
+   * mreport/MReportTrigger.[h,cc]:
+     - removed '!' from data members
+     - increased ClassDef to 2
+
+   * mstarcam/MStarCamTrans.cc:
+     - added a single line of comment
+
+   * mtrigger/MTrigger*.[h,cc]:
+     - updated class description and title
+
+   * mcalib/MCalibrationCam.h:
+     - removed -> from fPixels, fAverageArea/Sectors
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - small changes to output
+     - simplification of an if-else block
+
+   * mcalib/MCalibrationIntensityCam.cc:
+     - removed double deletion of fCams - caused a crash
+
+   * mcalib/MCalibrationIntensityCam.h:
+     - removed -> from fCams
+
+   * mcalib/MCalibration*.h:
+     - removed some obsolete (empty) destructors
+
+   * mastro/MVector3.[h,cc]:
+     - added from MAstroCatalog
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - removed MVector3
+
+   * mastro/Makefile:
+     - added MVector3
+
+
+
+ 2004/09/11: Markus Gaug
+ 
+   * mbase/MArray.[h,cc]
+     - moved function StripZeros(TArrayD &arr) to MArrayD
+     - moved function StripZeros(TArrayF &arr) to MArrayF
+
+   * mbase/MArrayD.[h,cc]
+     - new function StripZeros() 
+
+   * mbase/MArrayF.[h,cc]
+   * mbase/Makefile
+   * mbase/BaseLinkDef.h
+     - new class analogously to MArrayD
+
+   * mhbase/MH.[h,cc]
+     - added functions ProjectArray(MArrayD,...) 
+       and ProjectArray(MArrayF,...)
+
+   * mtools/MFFT.[h,cc]
+     - added functions:
+	  MArrayF* PowerSpectrumDensity(const MArrayI *array);  
+	  MArrayF* PowerSpectrumDensity(const MArrayF *array);
+	  MArrayD* PowerSpectrumDensity(const MArrayD *array);
+
+   * mhcalib/MHGausEvents.[h,cc]
+     - made fEvents an MArrayF
+
+   * mhcalib/MHCalibrationPix.[h,cc]
+     - changed function name SetSaturated to AddSaturated
+
+   * mhcalib/MHCalibrationChargeCam.cc
+   * mhcalib/MHCalibrationRelTimeCam.cc
+     - take cloning of averaged sectors out of the Clone() function
+
+   * mbadpixels/MBadPixelsIntensityCam.[h,cc]
+   * mbadpixels/Makefile
+   * mbadpixels/BadPixelsLinkDef.h
+     - new class for the intensity calibration
+
+
+
+ 2004/09/10: Markus Gaug
+
+   * mhcalib/
+   * mcalib/
+     moved all MHCalibration* classes to new directory mhcalib/
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+     - New base function InitHiGainArrays and InitLoGainArrays
+       Initializing the histograms in a standard way
+     - ReadEnv: added NBins, First and Last
+
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+   * mhcalib/MHCalibrationTestCam.[h,cc]
+   * mhcalib/MHCalibrationTestTimeCam.[h,cc]
+     - use new functions InitHiGainArrays and InitLoGainArrays
+ 
+   * mhcalib/MHCalibrationRelTimePix.[h,cc]
+   * mhcalib/MHCalibrationTestPix.[h,cc]
+   * mhcalib/MHCalibrationTestTimePix.[h,cc]
+     - removed
+
+
+
+ 2004/09/10: Antonio Stamerra
+
+   * mreport/MReportTrigger.[h,cc]:
+     - updated to read IPRs and to fill MTrigger{xxx} containers
+
+   * mreport/Makefile:
+     - added include for mtrigger   
+
+   * Makefile:
+     - added mtrigger directory
+
+   * NEWS:
+     - updated
+
+
+
+ 2004/09/10: Thomas Bretz
+
+   * mhist/MHCamera.cc:
+     - removed some obsolete const_casts
+     - fixed an (un)signed comparison warning
+
+   * mbase/MArray*.h:
+     - added const &operator[](UInt_t i) const
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - changed to support variable bin-sizes in time to keep
+       the statistic per bin constant
+
+   * mhbase/MBinning.[h,cc]:
+     - added function to enhance the number of bins by one
+
+   * mbase/MTime.[h,cc]:
+     - added function to add one NanoSecond
+
+   * mjobs/MJStar.cc:
+     - removed Histogram of effective on-time vs time
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - added MHEffectiveOnTime
+
+   * mhbase/MH3.[h,cc]:
+     - fixed a bug in SetupFill which was introduced when I allowed
+       set the axis titles from the object title
+     - added support for unique-profile names
+
+   * Makefile:
+     - added new dir mhcalib
+
+   * mhcalib/HCalibIncl.h:
+     - added - was missing
+
+   * mcalib/CalibLinkDef.h:
+     - fixed some typos
+
+
+
+ 2004/09/09: Markus Gaug
+ 
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - initialize bins directly here. Remove MHCalibraitonChargeHiGainPix
+       and MHCalibrationChargeLoGainPix classes
+
+   * mcalib/MHCalibrationChargeHiGainPix.[h,cc]
+   * mcalib/MHCalibrationChargeLoGainPix.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - removed first two classes
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - make default for GetNumUnsuitable and GetNumUnreliable
+
+   * mcalib/MCalibrationIntensityCam.[h,cc]
+   * mcalib/MCalibrationIntensityChargeCam.[h,cc]
+   * mcalib/MCalibrationIntensityQECam.[h,cc]
+   * mcalib/MCalibrationIntensityRelTimeCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new classes for the intensity calibration. First is base class, 
+       other derive from it.
+
+   * mcalib/MHGausEvents.[h,cc]
+   * mcalib/MHCalibrationPix.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - put typical calibration members into new base class MHCalibrationPix
+       and leave only typical Gaussian behaviour members in MHGausEvents.
+     - all MHCalibration*Pix classes derive now from MHCalibrationPix
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - operators return MHCalibrationPix instead of MHGausEvents
+     - new function ResetHists() needed by MCalibColorSteer
+     - removed TArrayI *Overflow.
+       
+   * mcalib/MCalibColorSet.[h,cc]
+     - finished
+
+   * mcalib/MCalibColorSteer.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new task to be executed before the calibration tasks. Steers the 
+       occurrance of multiple intensities and the new *Intensity* 
+       containers
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]
+   * mcalib/MHCalibrationRelTimePix.[h,cc]
+   * mcalib/MHCalibrationTestPix.[h,cc]
+   * mcalib/MHCalibrationTestTimePix.[h,cc]
+   * manalysis/MHPedestalPix.[h,cc]
+     - derive from MHCalibrationPix
+     - new functions Reset()
+
+   * mcalib/MHCalibrationChargeCam.cc
+   * mcalib/MHCalibrationRelTimeCam.cc
+   * mcalib/MHCalibrationTestCam.cc
+   * mcalib/MHCalibrationTestTimeCam.cc
+     - able to recognize an *Intensity*Cam if in MParList
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - able to recognize an *Intensity*Cam if in MParList
+     - set pulser pattern accordingly in Process from MRawEvtHeader     
+     - add switches to perform types of checks or not
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - able to recognize an *Intensity*Cam if in MParList
+
+   * mjobs/MJCalibration.[h,cc] 
+     - fixed flags
+     - included intensity calibration (MJCalibration::SetIntensity())
+       (default is standard calibration like before)
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractTimeHighestIntegral.cc
+   * msignal/MExtractSlidingWindow.cc
+   * msignal/MExtractPINDiode.cc
+   * msignal/MExtractFixedWindow.cc
+   * msignal/MExtractFixedWindowSpline.cc
+   * msignal/MExtractBlindPixel.cc
+   * msignal/MExtractAmplitudeSpline.cc
+     - removed some possible bugs in the case that no LoGain is 
+       available at all.
+
+
+
+ 2004/09/09: Thomas Bretz
+
+   * mhvstime/MHPixVsTime.[h,cc], mhvstime/MHVsTime.[h,cc],
+     mhvstime/MHSectorVsTime.[h,cc], mhbase/MH3.[h,cc]:
+     - changed such that the axis titles can be set via the 
+       title or (if available) a MBinning
+
+   * mhbase/MBinning.cc:
+     - added HasTitle
+
+   * mjobs/MJPedestal.cc:
+     - added lost UseData again to CheckEnvLocal
+
+   * mjobs/MJStar.cc:
+     - fixed handling of Axis titles of histograms
+
+   * mjobs/Makefile:
+     - added path to mhvstime
+
+   * manalysis/MParameters.[h,cc]:
+     - added Print() functions
+
+   * mfileio/MReadReports.[h,cc], mfileio/MReadTree.[h,cc]:
+     - moved setting of StreamId from MReadReports To MReadTree
+
+   * mhbase/MH.cc:
+     - workaround all the this which are reset in TAxis::Set
+  
+   * mfileio/MReadRflFile.[h,cc]:
+     - added missing abstract functions
+
+   * star.cc, callisto.cc, mjobs/MJStar.[h,cc], 
+     mjobs/MJCalibrateSignal.[h,cc]:
+     - added option to process monte carlo files
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - added a histogram taking the on-time vs time
+     - fixed handling of Draw/Project/Paint
+
+
+
+ 2004/09/08: Thomas Bretz
+ 
+   * mbadpixels/MBadPixelsCam.[h,cc], mbase/MParContainer.[h,cc],
+     mhvstime/MHPixVsTime.cc, mhvstime/MHSectorVsTime.cc:
+     - replaces ifstream by istream in AsciiRead
+
+   * mbase/MTime.[h,cc]:
+     - fixed comment about SetTimeFormat
+     - added AsciiRead
+     - added AsciiWrite
+     - added Minus1ns
+
+   * mfileio/MWriteAsciiFile.cc:
+     - write all containers if one has its SetReadyToSaveFlag set
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - for MEffectiveOnTime fit the whole projection instead
+       of using the sum of the theta-bins
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - replaces ifstream by istream in AsciiRead
+     - fixed to support MStatusDisplay
+     - do not fill the same time twice
+     - added support for error bars
+
+   * mjobs/MJStar.cc:
+     - replaced MReadMarsFile by MReadReports
+     - added MEventRateCalc and corresponding histogram
+     - added MHEffectiveOnTime
+
+
+
+ 2004/09/07: Thomas Bretz
+
+   * merpp.cc:
+     - added lost update-option
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed a compiler error geom.ClassName() --> geom
+
+   * mraw/MRawRunHeader.cc:
+     - added 'header' option to Print-function
+
+   * msql/MSQLServer.[h,cc]:
+     - added new onstructors taking TEnv as argument
+
+   * macros/sql/*.C:
+     - updated to use sql.rc
+
+   * macros/sql/sql.rc:
+     - added
+
+   * mcalib/MCalib*.[h,cc]:
+     - simplified the includes a little bit to accelerate compiling
+       and maybe to secure everything from compiler bugs a bit more
+
+   * callisto.cc, star.cc:
+     - do not allow implicit batch-mode
+
+   * showlog.cc:
+     - removed an unused variable
+
+   * manalysis/MEventRateCalc.[h,cc]:
+     - started implementing a corrsponding time
+
+   * manalysis/MParameters.[h,cc], manalysis/AnalysisLinkDef.h:
+     - added MParameterDerr
+
+   * mbadpixels/MHBadPixels.[h,cc]:
+     - removed obsolete fPedPhotCam
+
+   * mbase/MTime.[h,cc]:
+     - added AddMilliSeconds
+     - added SetMean
+
+
+
+
+ 2004/09/07: Markus Gaug
+
+   * mcalib/MHGausEvents.[h,cc]
+     - added function IsOnlyUnderflow()
+
+   * mcalib/MHCalibrationCam.[h,cc]
+   * mcalib/MHCalibrationChargeCam.cc
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - added bool kLoGain which is set if number of LoGain Slices in 
+       MRawRunHeader is not 0. This excludes the low gain calculations 
+       in case that there is no lowgain at all. 
+
+   * mcalib/MCalibrationQECamMagic.cc
+     - implemented Nicola's solution for the compiling problem of the 
+       TArrayD's 
+
+   * mcalib/MCalibColorSet.cc
+     - implemented intensity recognition
+
+   * mhist/MHCamera.[h,cc]
+     - included functions AddCamContent(MArrayD...) and 
+       SetCamContent(MArrayD... )
+
+
+
+ 2004/09/06: Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - read camera geometry from calib-file
+
+   * mjobs/MJCalibration.[h,cc]:
+     - write camera geometry to calib-file
+
+   * macros/sql/filldotraw.C, macros/sql/fillcalib.C:
+     - added
+
+   * macros/sql/filldot*.C
+     - fixed some comments
+
+   * mpointing/MPointingPosCalc.cc:
+     - removed some obsolete comments
+
+
+
+ 2004/09/05: Markus Gaug
+
+   * mcalib/MCalibColorSet.[h,cc]
+     - finished setting of the asumed pulse pattern
+
+
+
+ 2004/09/03: Markus Gaug
+
+   * mcalib/MCalibrationChargeBlindCamTwoNewStyle.cc
+     - small modification in QE of new blind pixel
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - new functions:
+       GetAveragedConvFADC2PhotPerArea,  
+       GetAveragedConvFADC2PhotPerSector, 
+       GetAveragedArrivalTimeMeanPerArea,  
+       GetAveragedArrivalTimeMeanPerSector, 
+       GetAveragedArrivalTimeRmsPerArea,  
+       GetAveragedArrivalTimeRmsPerSector, 
+       to be used by the data check.
+
+   * mcalib/MCalibrationChargePix.cc
+     - found small bug concerning the MBadPixelpix::kChargeSigmaNotValid
+       pixels which are recovered since last week. 
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - fixed UpdateCombinedMethod, removed AddAverageCombinedQEs
+
+   * mcalib/MCalibrationQECam.[h,cc]
+     - new array with cornings, not included in the I/O
+     - added copy function
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrationQECamMagic.[h,cc]
+   * htmldoc/images/Cornings.gif
+     - new class derived from MCalibrationQECam which intialized the 
+       cornings for the Magic camera
+
+
+
+ 2004/09/03: Wolfgang Wittek
+
+   * mbadpixels/MHBadPixels.[h,cc]
+     - new class; histograms for bad pixels
+
+   * mbadpixels/Makefile, mbaspixels/BadPixelsLinkdef.h
+     - MHBadPixels added
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - remove MSigmabar stuff
+
+   * mhist/Makefile, mhist/HistLinkdef.h
+     - MHSigmaTheta added
+   
+   * manalysis/Makefile, manalysis/AnalysisLinkdef.h
+     - remove MPedestalWorkaround and MSourcePosFromStarPos
+     - add MPad
+
+   * manalysis/MPad.[h,cc]
+     - remove *BlindPixel* stuff
+     - remove MSigmabar stuff
+
+
+
+ 2004/09/03: Thomas Bretz
+
+   * manalysis/MCameraData.[h,cc], mimage/MImgCleanStd.[h,cc]:
+     - implemeted cleaning in absolute number of photons
+     - moved output of setup of image cleaning to PreProcess
+ 
+   * mhbase/MBinning.[h,cc]:
+     - added const-qualifier to Apply
+
+   * mhist/MHAlpha.cc:
+     - let TLatex use NDC coordinates
+
+   * mimage/MHHillasSrc.cc:
+     - cosmetics
+
+   * mreport/MReportDrive.[h,cc]:
+     - added Print member function
+
+   * mpointing/MSrcPosFromModel.cc:
+     - removed an obsolete include
+
+   * mraw/MRawEvtHeader.h:
+     - added SetCalibrationPattern as a workaround for the runs
+       which don't have the correct pattern set
+
+   * mcalib/MCalibColorSet.[h,cc]:
+     - added as a workaround for the runs which don't have the
+       correct pattern set
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - added MCalibColorSet
+
+
+
+ 2004/09/02: Thomas Bretz
+
+   * star.cc:
+     - fixed treatment of batch-mode
+
+   * mbase/MParContainer.h:
+     - added a comment
+
+   * mbase/MParList.[h,cc]:
+     - added FindTaskListWithTask
+
+   * mbase/MTaskList.[h,cc]:
+     - added sanity checks in AddToList
+     - added FindTaskList
+
+   * mhbase/MH3.[h,cc]:
+     - moved some drawing code from Draw to Paint
+     - added possibility to set logarithmic axis manually
+     - fixed a bug which caused MH3s in MFillH::Finalize to disappear
+
+   * mhist/MHAlpha.cc:
+     - paint significance and othe rinformations
+     - unified fit in Finalize and Paint
+     - replaced significance calculation by Li/Ma
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - added option to average data
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added MPointingPosCalc for "Drive"
+
+   * mmain/MEventDisplay.cc:
+     - fixed some problems with the display
+
+   * msignal/MArrivalTime.[h,cc]:
+     - added Print()
+
+   * manalysis/MEventRateCalc.[h,cc]:
+     - added the difference in time between two events into the output
+     - made setup more flexible
+
+   * mbase/MContinue.cc:
+     - fixed a bug which caused a problem if MContinue was not in the
+       main tasklist
+
+   * mimage/MHImagePar.[h,cc], mimage/MHNewImagePar.[h,cc]:
+     - added Paint function to support logarithmic y-axis scles
+
+
+
+ 2004/09/01: Thomas Bretz
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - do not add a container which is already in the list
+     - replaced fNameCont by fTitle in MRootFileBranch
+
+   * mgeom/MGeomPix.[h,cc]:
+     - declared tan(30)
+     - added GetL member function
+
+   * mhist/MHAlpha.cc:
+     - added a logging output
+
+   * mhist/MHFalseSource.[h,cc]:
+     - shift by MSrcPosCam introduced
+     - fixed on-off plot
+     - fixed changed return value MHillasSrc::Calc
+     - as a workaround for some crashes removed SetBit(kCanDelete)
+       of catalog
+
+   * mimage/MHHillasSrc.cc, mimage/MHillasSrc.cc:
+     - some small fixes to new plots
+     - some cosmetics to the code
+
+   * mimage/MHillas.cc, mimage/MHillasExt.cc, 
+     mimage/MImagePar.cc, mimage/MImgCleanStd.cc,
+     mimage/MNewImagePar.cc:
+     - removed obsolete include of fstream
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - added new class MPointingPosFromModel
+     
+   * mpointing/MPointingPosFromModel.[h,cc]:
+     - added
+
+
+
+ 2004/08/31: Daniel Mazin
+
+   * manalysis/MSigmabarCalc.h:
+     - added function SetNamePedPhotCam to set the name of the 
+       MPedPhotCam container
+
+
+
+ 2004/08/31: Thomas Bretz
+
+   * star.cc:
+     - implemented batch- and quit-mode
+
+   * mastro/MAstroCatalog.h:
+     - implemented default argument for magnitude in MVector3
+       setters
+
+   * mbase/MDirIter.cc:
+     - fixed a typo
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed a typo
+
+   * mimage/MHHillasSrc.[h,cc], mimage/MHillasSrc.[h,cc]:
+     - added DCA and DCADelta as discussed with the ETH people
+     - incrementes version number of MHillasSrc
+     - changed return type of MHillasSrc::Calc from Bool_t to Int_t
+
+   * mimage/MHillasCalc.cc:
+     - changed to support error code 6
+
+   * mpointing/MPointingPos.h:
+     - added Getter for ZdA7Az in rad
+
+   * mpointing/MPointingPosCalc.cc:
+     - fixed a bug which converted Ra/Dec wrongly to rad
+
+   * mmain/MEventDisplay.cc:
+     - switched on usage of context menu in constructor
+
+
+
+ 2004/08/30: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc
+   * mcalib/MCalibrationTestCalc.cc
+   * mcalib/MCalibrationRelTimeCalc.cc
+   * mcalib/MHCalibrationTestCam.cc
+   * mcalib/MHCalibrationTestTimeCam.cc
+     - exchanged all arrays by TArray's
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+   * mcalib/MHCalibrationRelTimeCam.[h,cc]
+     - exchanged all arrays by MArray's
+
+
+
+ 2004/08/30: Thomas Bretz
+
+   * showlog.cc, showplot.cc:
+     - enhanced functionality
+
+   * callisto.cc, mjobs/MSequence.cc:
+     - enhanced comments
+
+
+
+ 2004/08/29: Markus Gaug
+ 
+   * mbadpixels/MBadPixelsPix.[h,cc] 
+   * mbadpixels/MBadPixelsCam.cc
+   * mjobs/MJCalibration.cc 
+     - introduced new calibration bits: kHiGainOverFlow 
+       and kLoGainOverFlow being filled when the calibration histograms 
+       overflow. Will cause an kUnsuitableRun afterwards. 
+     - added in datacheck-display of MJCalibration
+
+   * mcalib/MHCalibrationChargeHiGainPix.[h,cc]
+   * mcalib/MHCalibrationChargeLoGainPix.[h,cc]
+     - default lower histogram limit moved to -100.5
+
+   * mcalib/MHCalibrationCam.h
+   * mcalib/MHCalibrationChargeCam.cc
+     - make TArrayI out of fOverFlowHiGain and fOverFlowLoGain
+
+   * mjobs/MJCalibration.[h,cc]
+     - finished datacheck display with the arrival times.
+
+
+
+ 2004/08/27: Florian Goebel
+
+   * mpedestal/MPedestalPix.h
+     - correct calculation of error of RMS
+
+
+
+ 2004/08/27: Hendrik Bartko
+
+   * msignal/MExtractTime.cc
+     - check that the pixel has a low gain before calculating the time 
+       for the low gain in case of a saturated high gain.
+
+
+
+ 2004/08/27: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - adapted to possible use of MPedCalcFromLoGain
+
+   * mjobs/MJPedestal.h
+     - added function SetUseData() and IsUseData()
+
+   * mcalib/MCalibrationQEPix.cc
+     - changed initialization of fNorm... variables from 1. to -1. 
+       Like this, an accidental not-filling of MCalibrationQECam will
+       be recognized easier.
+
+   * mcalib/MCalibrationChargeCalc.cc
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - change treatment of pixels with kSigmaNotValid
+
+   * mpedestal/MPedestalCam.cc
+     - added functions GetAveragedPedPerArea  
+                       GetAveragedPedPerSector
+                       GetAveragedRmsPerArea  
+                       GetAveragedRmsPerSector
+       to be used for the datacheck.
+
+     - fixed a small bug in the calculation of the PedestalRms Error 
+       in GetPixelContent()
+
+   * macros/bootcampstandardanalysis.C 
+   * macros/mccalibrate.C 
+   * macros/pedphotcalc.C
+   * macros/starmc.C:
+     - replace MCalibrate by MCalibrateData
+
+   * mjobs/MJCalibration.h
+     - re-added function SetInput which had been removed recently 
+       (probably by accident)
+
+   * mjobs/MJCalibration.cc
+     - return kTRUE in function FindColor() if the colour has already 
+       been set (e.g. by the macro).
+
+   * mcalib/MHGausEvents.cc
+     - removed one call to fHPowerProbability->SetDirectory(0) which was
+       at a completely wrong place in CreateEventXaxis(). Probably a 
+       slip of the emacs-pen.
+ 
+   * mcalib/MJExtractSignal.cc
+     - replace MCalibrate by MCalibrateData
+
+
+
+ 2004/08/27: Thomas Bretz
+
+   * Makefile:
+     - added comments how to link statically
+     - added star again
+
+   * callisto.cc: 
+     - fixed some output
+     - fixed batch mode
+
+   * mbadpixels/Makefile:
+     - added a comment
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MArrayI
+
+   * mbase/MArrayI.[h,cc]:
+     - added
+
+   * mbase/MArrayD.cc:
+     - fixed some comments
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - unified CalibratePedestal and CalibrateData. Calling GetConvFactor twice
+       took a lot of time.
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJPedestal.cc, MJCalibration.cc:
+     - added two empty lines to output if finished
+     - added a sanity check around the call to CheckEnv
+
+   * mpedestal/MPedPhotCam.cc:
+     - use faster MArrays in ReCalc
+     - accelerated GetPixelContent
+
+   * msignal/MExtractTimeFastSpline.cc:
+     - accelerated a bit by defining
+          Float_t higainklo = fHiGainSecondDeriv[klo];
+          Float_t higainkhi = fHiGainSecondDeriv[khi];
+       instead of accesing the arrays many times inside the loops.
+       Somebody should do the same for logain.
+
+   * mraw/MRawEvtData.cc:
+     - fixed a bug in InitArrays
+
+   * showlog.cc:
+     - added some more functionality
+
+   * star.cc:
+     - changed to use new MJStar
+
+   * mfileio/MChain.cc:
+     - added namespace
+
+   * mfileio/MReadTree.cc:
+     - added a call to ResetTree as first call in PreProcess. Using
+       MReadReports with a tree missing in the file mysteriously
+       crashed because TChain::fTreeNumber was set already by
+       a root-miracle.
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MJStar
+
+   * mjobs/MJCalibrateSignal.cc:
+     - replaced MReadMarsFile by MReadReports
+
+   * mmain/MEventDisplay.cc:
+     - fixed reading of resource file
+
+   * mbase/MStatusDisplay.cc:
+     - made Reset() batch-mode safe
+
+   * mcalib/MCalibrateData.cc:
+     - simplified a calculation
+
+   * mfileio/MReadReports.[h,cc]:
+     - implemented GetEntries()
+     - implemented GetFileName()
+     - changed kHasMaster from BIT(15) to BIT(14)
+     - fixed a bug in AddTree which caused the Master-Bit to be
+       set for the wrong object
+
+   * mfileio/MReadTree.cc:
+     - return 0 entries if entrie==TChain::kBigNumber
+
+   * msignal/MExtractFixedWindow.cc:
+     - updated output to fitz into a std 80-col console
+
+   * mars.rc, star.rc:
+     - added
+
+
+
+ 2004/08/26: Wolfgang Wittek
+
+   * mstarcam/MStarCamTrans.[h,cc]
+     - include optical aberration when plotting the grid
+
+   * mtemp/MTelAxisFromStars.[h,cc]
+     - add member functions SetPointingPosition and SetSourcePosition
+
+
+
+ 2004/08/26: Markus Gaug
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - derived from MJob
+     - removed obsolete code (which has been moved to MJob)
+
+   * macros/calibration.C
+     - adapt code to changes done in MJob
+
+
+
+ 2004/08/26: Thomas Bretz
+
+   * mbase/MMath.cc:
+     - changed calculation of sign of SignificanceLiMaSigned due to
+       bug #131
+
+   * readdaq.cc, readraw.cc:
+     - updated to support MRawEvtData2
+     
+   * mraw/MRawEvtData.[h,cc], mraw/MRawFileRead.cc, 
+     mraw/MRawFileWrite.[h,cc], mraw/MRawRead.[h,cc], 
+     mraw/MRawSocketRead.cc:
+     - updated to support negative pixel ids
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - increased max format version to 4
+     - added GetNumNormalPixels
+     - added GetNumSpecialPixels
+     - added GetMinPixId
+     - added GetMaxPixId
+
+   * merpp.cc: 
+     - added a new option --auto-time to get the time range for 
+       cc and/or caco data from the run header of the raw data
+
+   * callisto.cc: 
+     - some additional checks
+     - more comments
+
+   * mfileio/MReadReports.h:
+     - overwrote GetFileName - otherwise CINT refuses to create an object
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - added an primitive interpolation of arrival times which
+       tries to keep the random arrival time for pixels without
+       signal
+     - fixed a bug which could cause a crash
+     - added more control over the pedestal treatment
+
+
+
+ 2004/08/25: Thomas Bretz
+
+   * callisto.cc:
+     - updated handling of command line parameters
+     - added MJPedestal in second loop
+     - changed MJ* to support new MJob base class
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MJob
+
+   * mjobs/MJob.[h,cc]:
+     - added
+
+   * mjobs/MJCalibrateSignal.[h,cc], mjobs/MJCalibrateSignal.[h,cc],
+     mjobs/MJCalibration.[h,cc], mjobs/MJPedestal.[h,cc]:
+     - derived from MJob
+     - removed obsolete code (which has been moved to MJob)
+
+   * mjobs/MSequence.[h,cc]:
+     - use MDirIter::GetEntries in SetupRuns
+     - implemented raw-file mode
+     - added GetNum*Runs
+
+   * callisto.rc:
+     - fixed
+
+   * showlog.cc, mbase/MTime.cc, mreport/MReportFileReadCC.cc:
+     - some fixes for gcc 2.95.3
+
+   * mbase/MEvtLoop.cc:
+     - allow prefix argument in ReadEnv
+
+   * mbase/MLog.cc:
+     - added options for log-file and html-file
+
+   * mbase/MTaskEnv.[h,cc]:
+     - added comment
+     - implemented dummy/skip-mode
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed non existance check from reading extractors (MTaskEnv dummy mode!)
+     - small changed to output
+
+   * mjobs/MJCalibration.cc:
+     - added a cast for gcc 2.95.3
+     - allow dummy mode MTaskEnvs
+
+   * mjobs/MJPedestal.[h,cc]:
+     - implemented CheckEnv
+
+   * msignal/MExtractTime.cc:
+     - fixed Print()-output
+
+   * msignal/MExtractTimeFastSpline.[h,cc]:
+     - added ReadEnv
+     - added Print
+
+
+
+ 2004/08/25: Wolfgang Wittek
+
+   * mpointing/MPointingPos.h
+     - add member function GetHa()
+
+
+
+ 2004/08/24: Thomas Bretz
+
+   * Makefile:
+     - added callisto
+     - added showplot
+     - removed star
+     - removed status
+
+   * merpp.cc:
+     - updated Usage()
+     - use some new feature or MArgs
+
+   * callisto.cc:
+     - a new program to calculate the calibration
+
+   * callisto.rc:
+     - resource file for callisto
+
+   * showplot.cc:
+     - a new program to show data check plots from a file
+
+   * mbase/MArgs.[h,cc]:
+     - added Get*AndRemove with a default argument
+
+   * mbase/MDirIter.[h,cc]:
+     - added Add(MDirIter &)
+
+   * mbase/MEvtLoop.cc:
+     - check for the existance of the resource file
+
+   * mbase/MLog.[h,cc]:
+     - added Usage()
+
+   * mbase/MTaskEnv.cc:
+     - added output in ReInit
+
+   * mjobs/MJCalibration.cc, mjobs/MJPedestal.cc:
+     - added Overwrite option
+     - maintained CheckEnv
+     - added InputPath
+
+   * mjobs/MSequence.cc:
+     - added return value to Setup*
+     - added comments
+
+   * mmain/MEventDisplay.cc:
+     - added tab for cleaning data
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]:
+     - added ReadEnv
+     - for consistency renamed fWindowSize* to f*WindowSize
+
+   * msignal/MExtractTimeHighestIntegral.[h,cc]:
+     - added ReadEnv
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - do not write to a log file if logging is not enabled
+     - replaced some arrays by TArrays
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MJCalibrateSignal
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - added
+
+   * msignal/MExtractFixedWindow.[h,cc], msignal/MExtractFixedWindowPeakSearch.[h,cc],
+     msignal/MExtractSlidingWindow.[h,cc], msignal/MExtractTime.[h,cc],
+     msignal/MExtractTimeAndCharge.[h,cc], msignal/MExtractTimeHighestIntegral.[h,cc]
+     msignal/MExtractor.[h,cc]:
+     - added Print
+     - added ReadEnv
+     - changed version number to 1
+
+
+
+ 2004/08/23: Wolfgang Wittek
+
+    * mtemp/MTelAxisFromStars.[h,cc]
+      - replace MStarLocalCam by MStarCam
+      - replace MStarLocalPos by MStarPos
+
+    * mtemp/MHTelAxisFromStars.[h,cc]
+      - replace MStarLocalCam by MStarCam
+      - replace MStarLocalPos by MStarPos
+
+    * mstarcam/MStarPos.[h,cc]
+      - remove data members containing 'CG' ('correlated Gauss');
+        put results from uncorrelated and correlated Gauss fit 
+        into the same area
+
+    * mtemp/MFindStars.h[cc]
+      - changes due to the changes in MStarPos
+      - remove fit with fixed correlation
+
+    * mtemp/MSourceDirections.[h,cc]
+      - changes due to the changes in MStarPos
+
+    * mtemp/findTelAxisFromStars.C
+      - changes due to changes in MTelAxisFromStars and MFindStars
+
+
+
+ 2004/08/23: Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - changed missleading ProcessRMS to ProcessPedestal
+
+   * mfileio/MReadTree.h:
+     - added AddFiles(MDirIter&) which is overloaded by another function
+       which resulted in some trouble
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - added cd() member function
+
+   * mimage/MHHillas.[h,cc]:
+     - added display of camera on top of MeanXY-plot
+
+   * mraw/MRawSocketRead.h:
+     - added GetFileName()
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added new data member fNumIslands
+     - added new functions (CalcIsland/CalcIslands to calculate islands)
+     - added new member function to sort pixels by index
+     - added island index in GetPixelContent
+     - increased version number
+
+   * manalysis/MCerPhotPix.[h,cc]:
+     - added fIdxIsland data member
+     - overloaded Compare function to be able to sort by pixel index
+     - increased version number
+
+   * mhist/MHEvent.[h,cc]:
+     - added new option for island index
+     - added kEvtCleaningData
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - added island calculation after image cleaning
+     - fixed some output to be consistent
+     - added ReadEnv
+     - updated StreamPrimitive
+     - added new cleaning method (probability cleaning)
+
+   * mimage/Makefile:
+     - added mhist
+
+   * mmain/MEventDisplay.cc:
+     - added display of island index
+     - changed to support files with calibrated data, too
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - implemented the possibility to set a maximum number of points
+
+   * mbase/MParContainer.h:
+     - changed StreamPrimitive to public
+
+   * mcalib/MMcCalibrationCalc.[h,cc]:
+     - added fPar data member (MImagePar) to get number of 
+       saturating hi gain pixels
+
+   * mimage/Makefile, mimage/ImageLinkDef.h:
+     - added MImagePar
+     - added MHImagePar
+
+   * mimage/MConcentration.[h,cc]:
+     - removed obsolete destructor
+
+   * mimage/MHillas.[h,cc]:
+     - added a check for island index to calculation
+
+   * mimage/MHillasCalc.cc:
+     - added option kCalcImagePar
+     - added option kCalcHillasSrc
+     - added Print function
+     - added StreamPrimitive function
+     - added resource support (ReadEnv)
+
+   * mimage/MHillasExt.[h,cc]:
+     - added a check for island index to calculation
+     - replaced for-loop by iterator
+
+   * mimage/MHillasSrc.[h,cc]:
+     - changed argument to Calc from pointer to reference
+
+   * mimage/MHillasSrcCalc.[h,cc]:
+     - fixed StreamPrimitive
+     - added some const-qualifiers to data members
+     - adapted to change in MHillasSrc
+
+   * mimage/MNewImagePar.[h,cc]:
+     - moved saturating pixels to new class MImagePar
+     - added a check for island index to calculation
+     - increased version number
+
+   * mpointing/MSrcPosCam.h:
+     - made StreamPrimitive public
+
+   * msignal/MArrivalTime.h:
+     - removed operator()
+     - added operator[] const
+
+   * manalysis/MCameraData.[h,cc]:
+     - added algorithm for 'Probability cleaning'
+
+   * mbase/MMath.[h,cc]:
+     - added GaussProb
+
+   * mjobs/MSequence.h:
+     - added IsValid
+
+
+
+ 2004/08/20: Thomas Bretz
+
+   * mjobs/MSequence.[h,cc]:
+     - added path-option to SetupRuns
+
+   * mjobs/MJCalibration.cc, mjobs/MJExtractSignal.cc, MJPedestal.cc:
+     - changed file "UPDATE" to "RECREATE"
+ 
+   * macros/sql/filldotrbk.C:
+     - removed obsolete output
+
+   * macros/sql/filldotrun.C:
+     - removed obsolete output
+     - updated to support ExcludedFDA-table
+
+   * mbase/MParList.[h,cc]:
+     - added FindTask-member function
+
+   * mcalib/MHCalibrationChargeBlindCam.cc:
+     - fixed a 'comparison between signed and unsigned'
+
+   * mfileio/MRead.h:
+     - added GetFileName()
+     - removed const-qualifier from CheckAndWrite
+
+   * mfileio/MReadMarsFile.cc:
+     - changed some logiing output
+
+   * mfileio/MWriteAsciiFile.[h,cc], mfileio/MWriteFile.[h,cc]:
+     - removed const-qualifier from CheckAndWrite
+     
+   * mfileio/MWriteRootFile.[h,cc]:
+     - simplified the constructor by adding Init() function
+     - added ReInit function to support file splitting
+     - added file splitting support (GetNewFileName, ChangeFile)
+     - added new constructor for file splitting
+     - made gsDef* a static member
+     - slight changed to PreProcess to support file-splitting
+     - if file-spliiting is enabled return always kTRUE in IsFileOpen
+     - added many new outputs in case of possible problems
+
+   * mraw/MRawFileRead.[h,cc]:
+     - changed return type of GetFileName()
+
+   * mraw/MRawFileWrite.[h,cc]:
+     - removed obsolete pParList data member
+     - by default write all events to the 'Events' tree
+
+   * msql/MSQLServer.[h,cc]:
+     - enhanced Query function
+
+
+
+ 2004/08/19: Marcos Lopez
+
+   * mjobs/MJCalibration.cc:
+     - In the function FindColor(), when looking for the calibration color in 
+       the calibration file name, ignore the case, to deal with colors
+       written in capital letters.
+
+
+
+ 2004/08/19: Thomas Bretz
+
+   * mastro/MTransCelLocCam.[h,cc]:
+     - renamed to MStarCamTrans and moved to mstarcam
+
+   * mastro/Makefile, mastro/AstroLinkDef.h:
+     - removed MTransCelLocCam
+
+   * mstarcam/Makefile, mstarcam/AstroLinkDef.h:
+   - cleaned up includes in Makefile
+   - added MStarCamTrans
+
+
+
+ 2004/08/19: Robert Wagner
+
+   * mtemp/MFindStars.[cc,h], mastro/MAstroCamera.cc,
+     mtemp/MSourceDirections.[cc,h]
+     - Changes to reflect the change of name of MStarPos, MStarCam
+
+
+
+ 2004/08/18: Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.[h,cc]:
+     - implemented function to calculate max cluster sizes
+
+   * macros/sql/filldotrbk.C, macros/sql/filldotrun.C:
+     - added return value
+
+   * mjobs/MJCalibration.cc:
+     - simplified FindColor by 1000% for later move to a new location
+
+   * mpedestal/MPedCalcFromLoGain.cc:
+     - output the range only if it has changed
+
+
+
+ 2004/08/18: Wolfgang Wittek
+
+   * mastro/MTransCelLocCam.[h,cc]
+     - new class; allows to calculate for any point (X, Y) in the 
+       camera the local (celestial) coordinates if the local 
+       (celestial) coordinates are known for some fixed point (X0, Y0) 
+       in the camera
+     - for given local (celestial) coordinates of the camera center,
+       the meber function PlotGrid draws the lines of constant theta 
+       and phi (and of constant dec and hourangle) onto the camera 
+       plane 
+
+   * mastro/Makefile, mastro/AstroLinkDef.h
+     - MTransCelLocCam added
+
+   * macros/testMTrans.C
+     - macro to test the class MTransCelLocCam
+
+
+
+ 2004/08/17: Markus Gaug
+ 
+   * msignal/MExtractBlindPixel.[h,cc]
+     - remove fModified which is taken care of in MJCalibration by the 
+       correct initialization
+
+   * mcalib/MCalibrationChargeBlindCam.[h,cc]
+     - now a base class for different types of blind pixels cams. 
+     - moved fBlindPixels away from pointer, analogue to MGeomCam
+
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+     - updated to new call to GetNumBlindPixels()
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrationChargeBlindCamOneOldStyle.[h,cc]
+   * mcalib/MCalibrationChargeBlindCamTwoNewStye.[h,cc]
+     - new classes deriving from and intializing 
+       MCalibrationChargeBlindCam 
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+     - derive from MCalibrationPix instead of MCalibrationChargePix
+     - create possibility to intialize QE's, etc. from outside
+     - fix default to previous behaviour such that old code can still 
+       run on old files without changes
+     - create copy function
+
+   * macros/calibration.C
+     - updated macro to use of MCalibrationTestCam
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - comment the static variable gkNumPulserColors
+     - take the pulser color enum and gkNumPulserColors out of the streamer
+     - set the version nr from 3 to 4
+     - Simplify a piece of the code dealing with the ForEach macro
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - removed Init() function which is already fulfilled by the Init() 
+       function of MCalibrationCam
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - some changes to the output
+     - call to MCalibrationChargeBlindCam->IsValid() removed
+
+   * mbadpixels/MBadPixelsCam.cc
+     - included kDeviatingNumPhots in GetPixelContent()
+
+   * mjobs/MJCalibration.[h,cc]
+     - some small modifications in the data-check display, discussed 
+       with Florian
+     - found that the MFillH for the MHCalibrationChargeBlindCam had 
+       been replaced to MHCalibrationChargeBlindPix -> redone
+     - adapted InitBlindPixel() to new classes initializing the right 
+       MCalibrationChargeBlindCam's
+
+   * mcalib/MCalibrationTestPix.[h,cc]
+   * mcalib/MCalibrationTestCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new container class to store results of MCalibrationTestCalc
+       and MHCalibrationTestCam
+
+   * mcalib/MCalibrationTestCalc.[h,cc]
+     - adapted to use of MCalibrationTestCam
+
+   * mcalib/MHCalibrationTestCam.[h,cc]
+     - adapted to use of MCalibrationTestCam
+
+
+
+ 2004/08/17: Thomas Bretz
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - unrolled some if-else statements to accelerate the algorithm a
+       bit (it is just the bottelneck of calibrating the signal)
+     - made sure that code which in not needed is not executed in
+       this case
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - unrolled if-else statements in GetPixelContent
+
+   * mcalib/MHCalibrationChargeBlindPix.cc:
+     - commented out unsused variable
+
+   * mjobs/MJCalibration.cc:
+     - some more output when writing the file
+
+   * mjobs/MJPedestal.[h,cc]:
+     - added more resources
+     - added fMaxEvents
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - fixed behaviour or fABFlags in case the array is empty
+     - changed Char_t data member to Byte_t according to change
+       in MRawEvtData
+
+   * mraw/MRawEvtData.[h,cc]:
+     - changed TArrayC data member to MArrayB to get rid of a memory
+       leak which resulted in huge memory usage when reading
+       MRawEvtData
+     - changed version number from 4 to 5
+     - changed size of fABFlag array to a more reasonable size
+       (maxid/8+1)
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - implemeted Getter for calibration pattern
+
+   * mhbase/MHMatrix.[h,cc], mranforest/MRanTree.cc,
+     mtools/MHSimmulatedAnnealing.h, mtools/MSimmulatedAnnealing.h:
+     - changed to compile with root-4.00/08
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - changed SetDumpEvents to SetNumEventsDump to fit roots naming
+       convention
+     - fixed crashes in case nothing has beendone
+     - do not process abflag if it is not existing
+     - for the moment do no call to ReCalc in Process
+     - added some const-qualifiers
+
+   * mhist/MHCamera.h:
+     - changed the definition of FetMinimum/GetMaximum such that
+       it compiles with root 4.00/08
+
+
+
+ 2004/08/17: Robert Wagner
+
+   * mstarcam, mstarcam/Makefile, mstarcam/StarcamLinkDef.h,   
+     mstarcam/StarcamIncl.h, macros/dohtml.C, macros/rootlogon.C
+     - Added directory mstarcam for holding all classes related to
+       studies of stars
+
+   * mstarcam/MStarPos.[cc,h], mstarcam/MStarCam.[cc,h],
+     mstarcam/StarcamLinkDef.h, mstarcam/Makefile, Makefile
+     - moved mtemp/MStarLocalPos.[cc,h], mtemp/MStarLocalCam.[cc,h]
+
+   * mastro/MAstroCamera.cc, mtemp/MFindStars.[cc,h],
+     mtemp/MSourceDirections.[cc,h]
+     - changed references to MStarLocalPos to MStarPos
+
+
+
+ 2004/08/16: Thomas Bretz
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - change to support also 'No calibration of data'
+     - removed obsolete dependancie on *'FromData' containers
+
+   * mcalib/MCalibrateData.[h,cc], mbadpixels/MBadPixelsCalc.[h,cc]:
+     - added member function ReadEnv
+
+   * mbase/MTime.[h,cc]:
+     - added new member function SetStringFmt
+
+   * mcalib/MHCalibrationChargeBlindPix.cc:
+     - removed unused variable
+
+   * mcalib/MHCalibrationChargeBlindPix.cc:
+     - removed unused variable
+
+
+
+ 2004/08/16: Markus Gaug
+ 
+   * mcalib/MHCalibrationCam.cc
+     - add a criterion to stop the Finalize() if both fHiGainArray 
+       and fLoGainArray have not been expanded. 
+     - replace two gLog by *fLog
+     - add the pulser color (needed for the datacheck histograms)
+     - some modifications in the data-check display, discussed with Florian
+
+   * mjobs/MJCalibration.[h,cc]
+     - some small modifications in the data-check display, discussed 
+       with Florian
+
+   * mcalib/MHGausEvents.[h,cc]
+     - make fSaturated Int_t and set to 0 in the Clean() function
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+     - remove the Clean() function
+
+   * mbadpixels/MBadPixelsPix.h
+   * mbadpixels/MBadPixelsCam.cc
+     - new functions GetUnsuitableCalibration() and 
+       GetUnreliableCalibration() to denote the reason for unsuitability
+       and unreliability. 
+     - in GetPixelContent flags 6 and 7.
+     - will be used for the datacheck display
+
+
+
+ 2004/08/14: Markus Gaug
+
+   * msignal/MExtractor.cc:
+     - documented data members
+     - included default for SetNamePedContainer()
+
+   * mjobs/MJPedestal.[h,cc]
+     - some small modifications in the data-check display, discussed 
+       with Florian
+
+
+
+ 2004/08/13: Thomas Bretz
+ 
+   * macros/readraw.C:
+     - updated to get it working with MC data
+
+   * mbase/MTaskEnv.cc:
+     - fixed a typo
+
+   * mcalib/MCalibrationChargeCalc.[h,cc], 
+     mcalib/MHCalibrationCam.[h,cc]:
+     - added ReadEnv
+     - changed some output slightly to match into a typical
+       80-column console
+
+   * mjobs/MJCalibration.[h,cc]:
+     - changed to support Sequences
+     - added SetEnv
+     - added possibility to change extractors from a resource file
+     - put MBadPixelsMerge into the tasklist - for strange reasons
+       it was missing
+
+   * mjobs/MJPedestal.[h,cc]:
+     - fixed the output name for sequences
+     - added possibility to set output from resource file
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - changed handling of sanity check for setup 
+     - removed obsolete variables
+     - changed output slightly to fit into a typical 80-column
+       console
+     - added some sanity checks to PostProcess
+     - added some info-output to PostProcess
+     - calculate a mean number of total events
+     - call ReCalc to calc mean values of sectors and areas
+
+   * mpedestal/MPedCalcPedRun.[h,cc]:
+     - changed to use ReCalc instead of doing the calculation itself
+       for convinience I left the old code as a comment inside -
+       will be removed later
+
+   * mpedestal/MPedPhotCam.[h,cc]:
+     - slight changes in ReCalc
+
+   * mpedestal/MPedestalCam.[h,cc]:
+     - added ReCalc function (maily taken from PedPhotCamReCalc)
+
+   * mpedestal/MPedestalPix.h:
+     - added Getter for fNumEvents
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - started adding support for calibration pattern. Please don't
+       take the current implementation to serious
+
+
+
+ 2004/08/12: Hendrik Bartko
+
+   * msignal/MExtractor.cc:
+     - corrected the setting of AddSerialNumber for Find(Create)Object
+
+   * msignal/MExtractTime.cc:
+     - corrected the setting of AddSerialNumber for FindObject
+
+   * mbadpixels/MBadPixelsCalc.cc
+     - corrected the setting of AddSerialNumber for FindObject
+
+   * mbadpixels/MBadPixelsTreat.cc
+     - corrected the setting of AddSerialNumber for FindObject
+
+   * mimage/MImgCleanStd.cc
+     - corrected the setting of AddSerialNumber for FindObject
+
+
+
+  2004/08/12: Markus Gaug
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - Set the method from outside
+     - unified the defaults to new blind pixels
+
+   * mjobs/MJCalibration.[h,cc]
+     - implementation of MHCalibrationChargeCam
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - adapt Draw() and DrawLegend() for the datacheck display
+
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+     - new member function fFitFunc, can be set from outside and is 
+       further passed onto the MHCalibrationChargeBlindPix's
+
+   * mcalib/MHCalibrationChargeCalc.[h,cc]
+     - improved readability of output
+     - set default fPheErrLimit to 4.5 sigma
+
+   * mcalib/MCalibrateData.[h,cc]
+     - give defaults to the Setter functions
+     - change default calibration mode from blindpixel to ffactor
+     - change exclusion of bad pixels from unsuitable run to unsuitable.
+     - some cosmetic changes
+     - remove fNumHiGainFADCSamples and fNumLoGainFADCSamples as 
+       data members    
+     - remove fConversionHiLo which is not used in the class
+     - write a StreamPrimitive()
+
+
+  2004/08/12: Thomas Bretz
+
+   * mreport/MReportFileReadCC.cc:
+     - fixed a bug in CheckFileHeader which caused a condition to
+       be wrongly evaluated
+
+   * mbase/MStatusDisplay.cc:
+     - small modification to postscript output
+
+   * showlog.cc:
+     - added
+
+   * Makefile:
+     - added showlog
+
+   * macros/sql/filldotrbk.C, macros/sql/filldotrun.C:
+     - update of comments
+
+   * mbase/MEvtLoop.cc:
+     - first interprete environment for fLog
+
+   * mbase/MEvtLoop.[h,cc], mbase/MParContainer.[h,cc],
+     mbase/MParList.[h,cc], mbase/MTaskList.[h,cc],
+     mfileio/MRead.[h,cc], mhbase/MHMatrix.[h,cc],
+     mpedestal/MPedCalcFromLoGain.[h,cc],
+     mpedestal/MPedCalcFromPedRun.[h,cc],
+     msignal/MExtractor.[h,cc]:
+     - changed type of ReadEnv from Bool_t to Int_t
+
+   * mbase/MLog.cc:
+     - fixed ReadEnv
+
+   * mbase/MParContainer.[h,cc]:
+     - added TestEnv
+
+   * mbase/MParList.cc, mbase/MTaskList.cc:
+     - moved some code to MParContainer::TestEnv
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MTaskEnv
+
+   * mhist/MHCamera.cc:
+     - removed some output (Draw function don't write something
+       to the console) - it is displayed anyhow
+     - added some SetBorderMode(0)
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MSequence
+
+   * mjobs/MJPedestal.[h,cc]:
+     - changed to allow a sequence as input
+     - changed to allow setting up the extractor from a TEnv
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - moved a common block of code to a new Calc function
+     - fixed ReadEnv
+
+   * mpedestal/MPedCalcPedRun.cc, msignal/MExtractor.cc:
+     - fixed ReadEnv
+
+   * mraw/MRawCrateData.cc:
+     - updated Print()
+
+   * mraw/MRawFileRead.h:
+     - added default to first constructor argument
+
+
+
+
+  2004/08/12: Hendrik Bartko
+
+   * msignal/MExtractor.[h,cc]:
+     - add SetNamePedContainer to set the name of the pedestal
+       container
+
+   * msignal/MExtractTime.[h,cc]:
+     - add SetNamePedContainer to set the name of the pedestal
+       container
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]
+     - add SetNamePedPhotContainer to set the name of the pedphot
+       container
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]
+     - add SetNamePedPhotContainer to set the name of the pedphot
+       container
+
+   * mimage/MImgCleanStd.[h,cc]
+     - add SetNamePedPhotContainer to set the name of the pedphot
+       container
+
+
+
+  2004/08/12 : Wolfgang Wittek
+
+   * manalysis/MSourcPosFromStarPos.[h,cc]
+     - replace MMcEvt by MPointingPos
+
+   * manalysis/MSigmabarCalc.[h,cc]
+     - replace MMcEvt by MPointingPos
+
+   * manalysis/MSigmabar.[h,cc]
+     - in member function Calc() return fSigmabarInner,
+       not fSigmabar
+     - update comments
+     - sigmabar is the sqrt of the average (pedRMS^2/area)
+
+   * manalysis/MPad.[h,cc]
+     - replace MMcEvt by MPointingPos
+     - remove bugs
+
+   * mfilter/MFSelBasic.[h,cc]
+     - replace MMcEvt by MPointingPos
+
+   * mfilter/Makefile
+     - add -I../mpointing
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - replace MMcEvt by MPointingPos     
+     - replace 'MCerPhotPix cerpix' by 'MCerPhotPix &cerpix'
+     - add plot "Sigmabar(Outer) versus Theta"
+
+   * macros/ONOFFAnalysis.C
+     - Job A : got the padding working, work in progress
+
+
+
+ 2004/08/11: Hendrik Bartko
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - add SetPedestalType to choose whether to calibrate the pedestal 
+       for each run or each event
+     - add EnablePedestalType to enable to calibrate the pedestal for 
+       each run or each event
+     - add DisablePedestalType to disable to calibrate the pedestal for 
+       each run or each event
+     - add TestFlag test whether to do the run and / or event pedestal
+       calculation
+     - add SetNamePedADCRunContainer to change name of pedestal input 
+       container for run pedestals
+     - add SetNamePedADCEventContainer to change name of pedestal input 
+       container for event pedestals
+     - add SetNamePedPhotRunContainer to change name of pedestal output 
+       container for run pedestals
+     - add SetNamePedPhotEventContainer to change name of pedestal output 
+       container for run pedestals
+     - add CalibratePedestal, function to calibrate the chosen pedestal 
+     - added the calibration types kFlatCharge, kDummy as in MCalibrate
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - in MBadPixelsCalc::Process() called the MPedPhotCam::ReCalc to
+       calculate the mean values of the pedestal and RMS for the areas
+       and sectors of the camera.
+
+
+
+ 2004/08/10: Thomas Bretz
+
+   * mreport/MReportFileReadCC.[h,cc]:
+     - added
+
+   * mreport/Makefile, mreport/ReportsLinkDef.h:
+     - added MReportFileReadCC
+
+   * mreport/MReport*.[h,cc]:
+     - prpagate file version number to all Interpreters
+
+   * merpp.cc:
+     - added new commandline options to support different CC files
+     - changed help-output
+     - temporarily removed SQL option
+
+   * readraw.cc:
+     - a small fix (a '.' was missing)
+
+   * mraw/MRawEvtData.cc:
+     - fixed bug in Print
+
+   * manalysis/MGeomApply.cc:
+     - changed to Init all MCamEvents in the parlist
+
+   * mbase/MParList.[h,cc]:
+     - added a cast operator to TIterator*
+     - check whether a automatic created class inherits from MParConatiner
+
+   * mgui/MCamEvent.[h,cc]:
+     - added Init
+     - added InitSize
+
+   * mmc/MMcTrig.cxx:
+     - added a new option to Print()
+
+   * mraw/MRawEvtData.[h,cc], mraw/MRawEvtHeader.[h,cc],
+     mraw/MRawFileRead.cc, mraw/MRawSocketRead.cc
+     - changed Init() to InitRead()
+
+   * msignal/MArrivalTime.[h,cc]:
+     - changed argument of InitSize according to MCamEvent
+
+   * msql/MSQLServer.[h,cc]:
+     - small changes to interface
+
+   * mimage/MHillasCalc.[h,cc]:
+     - changed names of TString data members
+
+
+
+ 2004/08/10: Robert Wagner
+
+   * mreport/MReportCamera.[h,cc]
+     - added function InterpreteHOT which interprete the HOT* part of 
+       the report. The variable HVs_modified_by_HOT_Pixels is 
+       extracted, but not yet written in the corresponding MARS
+       parameter container 
+
+
+
+ 2004/08/10: Markus Gaug
+
+   * mcalib/MCalibrationTestCalc.[h,cc]
+     - added calculation and output of maximum not-interpolatable 
+       cluster.
+
+   * macros/bootcampstandardanalysis.C 
+     - added MBadPixelsTreat
+
+
+   * mcalib/MCalibrate.cc
+     - implemented different way to calculate error of signal 
+       in method kFlatCharge (as discussed with Keiichi).
+
+
+
+ 2004/08/10: Florian Goebel
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+     - add SetPedContainerName() to change name
+       of output container
+     - fix bug affecting behaviour when running twice
+       over the same run
+     - change format of "Format"
+     - change default value for fgMaxHiGainVar to 40
+
+
+
+ 2004/08/10: Nadia Tonello
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]
+     - replaced flag SetSloppyTreatment() with SetHardTreatment() 
+       Now the default behaviour consists on treating only the 
+       unsuitable pixels, and not also the ureliable, as it was 
+       before. If you want to keep on treating both unsuitable and
+       unreliable pixels, please set the new flag on in your macro. 
+
+   * mjobs/MJExtractCalibTest.cc
+     - removed line containing SetSloppyTreatment()
+
+
+
+ 2004/08/10: Thomas Bretz
+
+   * mpedestal/MPedestalPix.[h,cc]:
+     - as discussed removed fValid
+
+   * mpedestal/MPedCalcFromPedRun.[h,cc], 
+     mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - removed dependancy on MBadPixelsCam
+
+   * mastro/MAstro.[h,cc]:
+     - implemented GetMoonPeriod
+     - implemented GetMoonPhase
+
+   * mbase/MTime.cc:
+     - Fixed a floating point problem in Set(&tv)
+     - added GetDateOfSunrise
+
+
+
+ 2004/08/09: Markus Gaug
+
+   * mcalib/MHGausEvents.[h,cc]
+     - added function IsOnlyOverflow()
+
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+     - put default arguments in the Clone() and the Draw() function 
+       (needed by e.g. TObject::DrawClone())
+     - added name and title to the class (was forgotten)
+
+   * mjobs/MJPedestal.[h,cc]
+     - set the possibility to have the datacheck display with the 
+       function SetDataCheckDisplay()
+
+
+
+  2004/08/09: Wolfgang Wittek
+
+   * mtemp/MStarLocalCam.[h,cc], mtemp/MStarLocalPos.[h,cc]
+     - new variables added for the fit of a 2dim Gaussian with 
+       correlations
+     - the corresponding Set and Get functions were added
+     - the Paint function was extended correspondingly
+
+   * mtemp/MTelAxisFromStars.[h,cc]
+     - new class (task) which determines the source position from star 
+       positions in the camera
+   
+   * mtemp/MHTelAxisFromStars.[h,cc]
+     - new class (container); produce plots for MTelAxisFromStars
+
+   * mtemp/MSkyCamTrans.[h,cc]
+     - new class (task) ; container holding the parameters for the 
+       transformation from sky coordinates (projected onto the camera) 
+       to camera coordinates
+
+   * mtemp/Makefile, mtemp/TempLinkDef.h
+     - MTelAxisFRomStars  added
+     - MHTelAxisFromStars added
+     - MSkyCamTrans       added
+
+   * mtemp/findTelAxisFromStars.C
+     - new macro: extended version of findstars.C 
+       (in mtemp/mifae/macros/)
+     - call to MTelAxcisFromStars and MHTelAxisFromStars
+       was added
+
+   * mtemp/MFindStars.[h,cc]
+     - add correlated Gauss fit
+
+
+
+ 2004/08/06: Markus Gaug
+ 
+   * mcalib/MCalibrationTestCalc.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new class to retrieve the results of MHCalbirationTestCam 
+     - outputs the results of the bad pixels interpolation and the 
+       new relative flat-fielding of the camera.
+
+   * mjobs/MJExtractCalibTest.cc
+     - uncomment (and use) the interpolation of bad pixels
+     - use the class MCalibrationTestCalc
+
+   * mcalib/MHCalibrationChargeLoGainPix.cc
+     - increase the default upper histogram limits for the 
+       large extraction windows.
+
+   * msignal/MExtractor.cc
+     - fixed a bug in one possible output using Form() 
+       which produced a segm.violation in that case.
+
+   * mcalib/MHCalibrationTestCam.cc
+     - adapt class for the interpolation of pixels.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - fixed a small bug in the calculation of average number of 
+       photo-electrons
+
+
+ 2004/08/06: Nadia Tonello
+
+   * mimage/MImgCleanStd.cc:
+     - in the Process, the Step3 (that checks the boundary pixels) 
+       is skipped when no action is espected, i.e. if lvl1 <= lvl2.
+       This will accelerate the cleaning process in such cases.
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]:
+     - removed dependence on MSigmabar 
+
+
+
+ 2004/08/05: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - changed return type of AddObject to Bool_t
+     - changed Reading member function to use AddObject
+
+   * msignal/MArrivalTime.h:
+     - Added missing ClassDef
+
+   * mhist/MHEvent.h:
+     - Removed strange MCameraSignal
+
+
+
+ 2004/08/05: Robert Wagner
+
+   * mastro/MAstroCatalog.[h,cc]
+     - Added MAstroCatalog::AddObject, functionality to insert single
+       objects manually; needed for mtemp/mmpi/MSourceDirections
+
+
+
+ 2004/08/05: Thomas Bretz
+
+   * manalysis/MGeomApply.cc, mimage/MCameraSmooth.[h,cc]:
+     - removed dependancy on MBlindPixel
+
+   * macros/sql/readrbk.C, msql/MSQLServer.cc:
+     - fixed some memory leaks - the result of TSQLServer::Query
+       must be deleted
+
+   * mbase/MTaskInteractive.cc:
+     - added some comments
+
+   * mmain/MBrowser.cc:
+     - fixed a bug which caused '/data/MAGIC' not to be shown in
+       the dir-list
+
+   * mmc/MMcEvt.hxx:
+     - added some more particle ids
+
+   * msql/MSQLServer.[h,cc]:
+     - some improvements to the user interface
+
+   * macros/sql/filldotrun.C:
+     - added
+
+
+
+ 2004/08/04: Markus Gaug
+
+   * msignal/MExtractFixedWindowSpline.cc
+     - replaced delete's of the array by a delete [].
+
+   * mjobs/MJCalibration.cc
+     - replaced default time extractor by MExtractTimeFastSpline
+
+   * mbadpixels/MBadPixelsPix.cc
+     - updated the class description
+
+
+
+ 2004/08/04: Thomas Bretz
+
+   * manalysis/MBlindPixels.[h,cc], manalysis/MBlindPixelCalc.[h,cc], 
+     manalysis/MBlindPixelCalc2.[h,cc]:
+     - as discussed some weeks ago the classes have been removed
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed the MBlind* entries
+
+   * star.cc, mmain/MEventDisplay.cc, mmain/MOnlineDisplay.cc, 
+     mmain/MAnalysis.cc, mfileio/MCT1ReadPreProc.[h,cc]:
+     - removed usage of MBlind*
+     - MBadPixel* TO BE ADDED
+
+   * merpp.cc:
+     - moved interpretation of command line options to MLog
+     - added a check for unknown options
+
+   * manalysis/MCameraData.[h,cc]:
+     - added some comments
+     - fixed some errors in the documentation
+     - changed ClassDef to 1
+     - changed the new algorithms such that any number of different
+       pixel-sizes are supported
+     - small modifications to the sanity checks
+
+   * mbadpixels/MBadPixelsTreat.h:
+     - fixed the argument type of SetNumMinNeighbors
+
+   * mbase/MArgs.cc:
+     - comment updated
+
+   * mbase/MEvtLoop.cc:
+     - added reading and writing of fLog environment
+
+   * mbase/MLog.[h,cc]:
+     - added Reading and writing Environment (ReadEnv, WriteEnv)
+     - added a function to setup MLog from command line arguments
+
+   * mbase/MTaskInteractive.[h,cc]:
+     - added an example
+
+   * mbase/MTime.cc:
+     - added a warning for the SetTimeFormat usage
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - some updates to the old comments
+     - NEW COMMENTS FOR SCALED CLEANING STILL MISSING!
+     - implemented scaled image cleaning
+     - replaced usage of MSigmabar by MPedPhotCam for democratic cleaning
+
+   * manalysisct1, manalysisct1/Makefile, 
+     manalysisct1/AnalysisCT1LinkDef.h:
+     - new
+
+   * manalysis/MCT1*, mfileio/structures.h, mfileio/MCT1Read*.[h,cc]:
+     - moved to new directory manalysisct1
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - updated
+     - removed MPad because long time ago changed discuseed were not made
+       (it doesn't compile anymore, because MBlindPixels is missing now)
+
+   * mfileio/Makefile, mfileio/FileIOLinkDef.h:
+     - updated
+
+   * mbase/MLog.cc:
+     - added missing kMustCleanup bit of fPlugins
+
+   * mbadpixels/MBadPixelsPix.h:
+     - added easier access to the information whether a pixel is unsuitable
+       or unreliable
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - added SloppyTreatment
+
+
+
+ 2004/08/03: Hendrik Bartko
+
+   * manalysis/MCameraData.[h,cc]
+     - Added new function CalcCleaningLevel2 to take into account that
+       the pedestal RMS does not scale with the inverse square root of
+       the pixel area for the calculation of the cleaning levels.
+     - Added new function CalcCleaningLevelDemocratic. It calculates
+       the cleaning levels for the democratic image cleaning directly
+       from the average values of MPedPhotCam instead of using 
+       MSigmabar.
+
+
+
+ 2004/08/03: Thomas Bretz
+
+   * macros/sql:
+     - new directory
+
+   * macros/sql/readrbk.C:
+     - new macro
+
+   * mjobs/MJExtractSignal.cc:
+     - fixed missing initialisation of fExtractor, fExtractorTime
+
+
+
+ 2004/07/30: Robert Wagner
+
+   * mastro/MAstroCamera.[h,cc]
+     - Added method FillStarList() which fills a TList with objects
+       of type MStarLocalPos for all stars found from the catalog
+       matching specified criteria (FOV, magnitude limit, position)
+     - Lines involving MStarLocalPos have been commented out for
+       the time being since MStarLocalPos is not part of standard
+       MARS yet!
+
+   * mtemp/MStarLocalPos.[h,cc]
+     - Added handling of the minuit error matrix elements to
+       MStarLocalPos::MSetFitValues
+     - Added member variables to hold error matrix elements
+     - Added getters for error matrix elements
+     - Expected star position is painted by Paint, too.
+     - Error matrix elements are printed by Print, too.
+
+
+
+ 2004/07/28: Javi Lopez
+
+   * mhist/MHCamera.[h,cc]
+     - Added new argument to CntCamContent() funtion to select to count
+       the events above or bellow a certain discriminator level.
+
+
+
+ 2004/07/20: Florian Goebel
+
+   * mpedestal/MPedestalPix.[h,cc]
+     - added: 
+      + fPedestalABoffset: difference between pedestal mean of odd slices
+                           and the total pedestal mean (fPedestal)                
+      + fNumEvents:        number of times, the Process was executed          
+                           (to estimate the error of pedestal)
+
+   * mpedestal/MPedestalCam.cc
+     - calculate error using pixel vise fNumEvents
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+   * mpedestal/Makefile
+   * mpedestal/PedestalLinkDef.h
+     - added class which calculates pedestal values from the low gain
+       slices of a data run
+     - it also calculates the ABoffset values and fills MPedestalPix
+       accordingly
+
+   * macros/ScanPulseABPed.C
+     - macro plotting the pulse shape using MPedCalcFromLoGain
+       and correcting for the AB 150 MHz clock noise.
+
+   * msignal/MExtractSignalABcorr.[h,cc]
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - example for signal extractor class similar to MExtractSignal 
+       correcting for ABoffset which allows to use odd number of slices
+
+   * macros/ScanExtractSignalABCorr.C
+     - macro using MExtractSignalABcorr
+
+
+
+ 2004/07/16: Markus Gaug
+
+   * msignal/MExtractFixedWindowSpline.cc
+     - replace the delete's by delete [].
+
+   * mcalib/MHCalibrationChargeCam.cc
+     - remove some obsolete commented code
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - derive only from MHGausEvents and not additionally from 
+       MHCalibrationChargePix
+     - Additional setter for MCalibrationChargeBlindPix, used by 
+       MHCalibrationChargeBlindCam
+     - Getter for fSinglePheCut
+     - adapted Draw for the "datacheck" option
+     - use variable histogram range depending on whether amplitude
+       or integral has been extracted
+
+   * mcalib/MCalibrationChargeBlindCam.[h,cc]
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - two new classes for the treatment of various blind pixels in the 
+       camera
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - adapted to use of various blind pixels
+
+
+
+ 2004/07/15: Markus Gaug
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - hard coded the reference lines for the DataCheck Display. 
+       Should be faster and easier to read than the TArrayF's. 
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - removed obsolete pointer to MEvtTime
+     - fixed bug in calculation of RMS for FFactor of inner pixels
+       in case that the fit does not converge. 
+     - introduced blind pixel and PIN Diode result flags for later
+       output or storage in DB.
+
+
+
+ 2004/07/14: Hendrik Bartko
+
+   * mpedestal/MPedPhotCam.[h,cc]
+     - added average areas and sectors (in analogy MPedestalCam)
+     - added new function InitAreas(const UInt_t i)
+     - added new function InitSectors(const UInt_t i)
+     - added new function GetNumAreas()
+     - added new function GetNumSectors()
+     - added new function ReCalc, computes the average values for the
+       sectors from all pixels which are not marked 
+       MBadPixelsPix::kUnsuitableRun
+
+   * mpedestal/MPedPhotPix.[h,cc]
+     - added a variable for the number of events from which the 
+       pedestals are computed
+
+   * manalysis/MGeomApply.cc
+     - changed initialization of MPedPhotCam
+
+   * msignal/MExtractTimeHighestIntegral.cc
+     - implemented the time calculation respective to the zero FADC
+       time sample, not respective to the first sample of the chosen
+       range
+
+   * msignal/MArrivalTimeCalc2.cc
+     - implemented the time calculation respective to the zero FADC
+       time sample, not respective to the first sample of the chosen
+       range
+
+
+
+ 2004/07/14: Markus Gaug
+
+   * msignal/MExtractedSignalBlindPixel.[h,cc]
+     - added new function GetNumBlindPixels()
+     - added more comments
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - adapted to new configuration of now three blind pixels
+     - runs with run number smaller than 31693 are treated in the old way
+     - runs with run number higher than 31693 have no more NSB filter, 
+       but possibility to choose between integral or amplitude (with spline) 
+       extraction. Default is amplitude.
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - use the variable fPixId to design an ID to the class. 
+       Later, a new class MHCalibrationChargeBlindCam can host 
+       the different blind pixels as individual 
+       MHCalibrationChargeBlindPix. 
+     - Default ID is 0 which is also default in MExtractedSignalBlindPix
+     - for current code, nothing has thus changed so far...
+
+   * msignal/MExtractAmplitudeSpline.cc
+     - fixed a bug causing a segmentation violation in the destructor 
+       (array dimension was not respected correctly)
+
+   * mcalib/MHGausEvents.cc
+     - removed an inconsistency in the naming of fHPowerProbability which 
+       can cause a memory leak (I hope, this was the cause of some of the 
+       leaks we had, but I'm not sure).
+     - removed the setting of fPixId to -1 in the Clear()
+
+
+
+ 2004/06/30: Thomas Bretz
+
+   * mbase/MEvtLoop.[h,cc]:
+     - overwrite ReadEnv with a new function taking the
+       name of the setup file as argument
+
+   * mjobs/MJPedestal.[h,cc]:
+     - added setup file name as argument to 
+
+   * mjobs/MJPedestal.[h,cc]:
+     - implemented a new data member fEnv
+     - implemented new setter SetEnv
+     - some small changes towards setup files
+     - some simplifications to line drawing
+
+   * msignal/MExtractor.[h,cc]:
+     - added ReadEnv member function
+     - removed obsolete virtual qualifiers in header
+     - simplified usage of Form()
+
+   * mraw/MRawFileWrite.[h,cc]:
+     - moved writing of RunHeaders from PreProcess to new ReInit
+
+
+
+ 2004/06/29: Thomas Bretz
+
+   * mpedestal/MPedCalcFromData.[h,cc]
+     - changed data member names according to coding rules
+
+
+
+ 2004/06/25: Pepe Flix
+
+   * mpedestal/MPedCalcFromData.[h,cc]
+     - added class to evaluate pedestal mean/RMS from real data events.
+       Low Gain samples used when no switch to LG happened.
+
+   * macros/PedCalcFromData.C
+     - added macro that uses the class to evaluate pedestals from real
+       data.
+
+
+
+ 2004/06/23: Markus Gaug
+
+   * macros/calibration.C
+     - added flag to skip the testing
+     - added calibration of pedestal files and creation of F2-files.
+
+   * macros/bootcampstandardanalysis.C
+     - updated to use MJExtractSignal
+
+   * mcalib/MHGausEvents.cc
+     - give a unique name to fHPowerProbability, otherwise 
+       MH::ProjectArray will use an existing one. 
+ 
+
+
+ 2004/06/18: Markus Gaug
+
+   * manalysis/MHPedestalCam.[h,cc]
+     - use flag to choose if one wants to re-normalize the histogram 
+       results
+
+   * mhist/MHCamera.[h,cc]
+     - added one argument to CntCamContent to tell if event above or 
+       below threshold have to be counted. Default is above, like before
+     - added one argument to Projection and ProjectionS giving the number 
+       of bins as argument (default 50 like before)
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - replaced extraction of mean number of photo-electrons and mean 
+       F-Factor by a Gauss fit (instead of mean and RMS). Set the 
+       limit for deviating F-Factor from 3.5 to 4.5. This should reduce 
+       the number of uncalibrated pixels below 50 again (which was not 
+       the case in the last weeks). 
+
+   * mcalib/MHGausEvents.h
+     - make DrawEvents() public
+
+   * mcalib/MHCalibrationChargeLoGainPix.cc
+     - upper histogram limit lowered for the better visibility in the 
+       data check.
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - adapted Draw for the datacheck
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - adapted for various blind pixels
+     - adapted Draw for the datacheck
+
+   * msignal/MExtractor.[h,cc]
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+   * msignal/MExtractFixedWindowSpline.[h,cc]
+     - made sum in FindSignal() float which is now the variable used by 
+       the majority of the extractors.
+
+   * msignal/MExtractAmplitudeSpline.[h,cc]
+     - new extractor calculating the amplitude using a spline. 
+
+   * mcalib/MCalibrationPix.[h,cc]
+   * mcalib/MCalibrationChargePix.[h,cc]
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added debug flags and output on debug
+
+   * mbadpixels/MBadPixelsCam.cc
+     - enlarged the Print-function
+
+
+
+ 2004/06/17: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - adapted display for the datacheck
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - new function Draw for the datacheck
+     - new clone function for the DrawClone
+  
+   * mcalib/MHCalibrationCam.h
+     - make clone function virtual
+
+   * mjobs/MJCalibration.cc
+     - adapted display for the datacheck    
+  
+   * mcalib/MHGausEvents.h
+     - two new getters for fFirst and fLast
+
+   * mhist/MHCamera.h
+     - make SetUsed() and Fill(x,w) public. It is now possible to use the 
+       Fill-function together with the SetUsed(idx), when no 
+       SetCamContent(...) is available. 
+       Previously, only a Fill(x,y,w) was public, with x and y positions 
+       in the camera. 
+
+  * mjobs/MJPedestal.[h,cc]
+    - updated the data-check display
+
+
+
+ 2004/06/12: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+   * mcalib/MMcCalibrationCalc.[h,cc]
+     - Fixed mistake in the calibration which occurred only when 
+       different light collection efficiency was simulated for outer 
+       pixels.
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Adapted to the possibility of having different light collection
+       efficiencies in inner and outer pixels. For now we assume that the
+       dependence with incidence angle on the camera plane is the same
+       for both types of pixels.
+
+
+
+ 2004/06/12: Markus Gaug
+
+   * msignal/MExtractFixedWindow.cc 
+     - output the number and exact range of extraction to *fLog in the 
+       ReInit(), like it is done by MPedCalcPedRun
+
+   * macros/bootcampstandardanalysis.C
+     - exchanged MArrivalTimeCalc2 in 4th loop by timeext (defined 
+       in the beginning)
+
+
+
+ 2004/06/11: Markus Gaug
+
+   * mpedestals/MPedCalcPedRun.cc
+     - set the default upper range to 29, because otherwise the extraction
+       window will be made too small in case that more than 14 "high-gain" 
+       slices shall be extracted. This is a bugfix! It calculated wrong 
+       pedestals in case that the user says: SetRange(a,b), where b is 
+       bigger than 14 in combination with SetWindowSize(x) where x is bigger 
+       than 14 as well (instead of : SetRange(a,b,c,d), where 
+       everything went fine). However, the intention of the last months 
+       changes was to allow exactly also the first possibility. 
+
+   * mjobs/MJCalibration.cc
+     - put run 27474 in list of unavailable runs (see runbook)
+
+
+
+ 2004/06/08: Markus Gaug
+
+   * mhist/MHCamera.cc
+     - reduce number of default bins in AzimuthProfile
+     - use MatchSector in AzimuthProfile, like in RadialProfile
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - fix lower limit for deviation F-Factor to 1.1. This discarts a 
+       smaller number of especially outer pixels in some runs taken with
+       the CT1 pulser box.
+
+
+
+ 2004/06/07: Markus Gaug
+
+   * mcalib/MHCalibrationCam.h
+     - add a function GetSize()
+
+   * msignal/MExtractTimeFastSpline.cc
+     - fixed a bug introduced on 1.6. and accelerate it a bit. 
+
+
+
+ 2004/06/04: Markus Gaug
+
+   * mcalib/MHGausEvents.cc
+     - some small modifications in the way the axes are drawn and their
+       titles are drawn.
+
+
+
+ 2004/06/03: Martin Merck
+
+   * msignal/MArrivalTimeCam.h
+   * msignal/MArrivalTime.h
+   * msignal/MArrivalTimePix.h
+   * msignal/MExtractedSignalCam.h
+   * msignal/MExtractedSignalPix.h
+   * msignal/MExtractedSignalPINDiode.h
+   * msignal/MExtractedSignalBlindPixel.h
+     - Set version in ClassDef to 1 for the streamer.
+
+   * msignal/SignalLinkDef.h
+     - Added a + at the pragma for MExtractedSignalCam and 
+       MExtractedSignalPix for consistency.
+
+   * msjobs/MExtractSignal.[h,cc]
+     - Added methods to set the Extractor and TimeExtractor to be
+       used when extracting the signal.
+
+
+ 
+ 2004/06/03: Markus Gaug
+
+   * mhist/MHCamera.[h,cc]
+   * mjobs/MJCalibration.cc
+     - added functions AzimuthProfile and DrawAzimuthProfile, same 
+       like the RadialProfile functions, only with azimuth instead of 
+       radius.
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - replace fNumHiGainFADCSlices and fNumLoGainFADCSlices by a 
+       TArrayF and increment ClassDef by 1 for the streamer.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - found a small bug making a difference in the number of valid 
+       pixels with the blind PIxel method and the ffactor method. Now
+       fixed. (The difference was usually a couple of pixels)
+
+   * msignal/MExtractTime.h
+     - make members protected instead of private in order to allow 
+       classes to derive from it
+
+   * msignal/MExtractFixedWindow.cc
+     - added some documentation
+
+   * msignal/MExtractFixedWindowSpline.[h,cc]
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - new fast spline signal extractor
+
+
+ 
+ 2004/06/02: Antonio Stamerra
+
+   * mtrigger/*:
+     - added directory and new classes to correctly handle the 
+	trigger-report string from report file. 
+	Not yet into the Makefile.
+
+
+
+ 2004/06/01: Thomas Bretz
+
+   * mbase/MLog.[h,cc]:
+     - some changes to Lock/UnLock of mutices. Necessary for Cosy.
+
+
+
+ 2004/06/01: Abelardo Moralejo
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - Added variable fLowGainPeakShift and setter. It allows to shift
+       the integration window for low gain with respect to the one of
+       the high gain. By default its value is 0 (corresponding to a 
+       total delay of 15 slices) so that default behaviour of the
+       extractor is the same as before.
+
+
+
+ 2004/06/01: Markus Gaug
+ 
+   * mjobs/MJCalibration.cc
+     - small change in the way the "full display" is displayed
+
+   * mcalib/MHCalibrationChargeBlindPix.cc
+   * mcalib/MHCalibrationChargePix.cc
+     - replace Draw(opt) by Draw(). This make the histograms reappear 
+       again, although I have no idea why. A printout of the opt gives 
+       always empty. 
+
+   * mcalib/MCalibrationQEPix.cc
+     - put Eckarts transmission of the plexiglass into the class 
+       documentation
+
+   * msignal/MExtractTimeFastSpline.cc
+     - fixed some smaller bugs affecting a small part of the signals
+
+
+ 2004/05/31: Hendrik Bartko
+
+   * msignal/MArrivalTimeCalc2.cc
+     - fixed a bug in pointer arithmetics found by Florian.
+
+
+
+ 2004/05/31: Raquel de los Reyes
+
+   * macros/DAQDataCheck.C
+     - committed the macro to check the raw data and display the quality
+       plots.
+
+
+
+ 2004/05/30: Markus Gaug
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - added more documentation (plots)
+     - separated calls for light guides eff. , QE, and coll. eff.
+   
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - fixed a small bug in the calculation of the error on the number 
+       of photons with the F-Factor method, did not include the division
+       by number of pixels for the precision of the QE. This does not 
+       affect the general analysis. 
+
+   * mjobs/MJCalibration.cc
+     - added runnumber 26924 to list of runs without clear colour in 
+       the file name. 
+
+
+
+ 2004/05/28: Markus Gaug
+
+   * macros/calibration.C
+     - make the macro compilable with possibility to run it in batch 
+       mode. 
+
+   * msignal/MExtractor.cc
+     - put an additional check in case that the number of FADC slices 
+       in the run header is smaller or equal to 0.
+
+
+
+ 2004/05/27: Javier Rico
+
+   * mbase/MDirIter.h 
+     - remove unneeded ResetIter method (Reset does all the job)
+
+   * mjobs/MJCalibration.cc
+     - change call to the removed MDirIter::ResetIter for Reset
+	
+
+
+ 2004/05/27: Markus Gaug
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - put some protection against zero-division in fitFuncMichele
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+     - set flag to distinguish between coated and un-coated blind pixel
+     - increase ClassDef number by one.
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - set a global variable CollEfficiency and LightguidesEfficiency. 
+       The more precise result for the QE calculated with 
+       the F-Factor method differs now by about 5% (while the statistical
+       error remains around 20%). 
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - write the number of photons directy into MCalibrationChargeCam. 
+       These numbers would otherwise have to be assembled by different 
+       parts in separate code. 
+
+
+
+ 2004/05/27: Thomas Bretz
+ 
+   * mastro/MAstroCatalog.cc
+     - removed a statement after '#endif'
+
+   * mastro/MAstroCamera.h
+     - removed obsolete empty function which (believing the Changelog)
+       are not there at all!
+
+   * mbase/MDirIter.[h,cc]:
+     - moved code of Reset() funtion to source file
+     - added more comments to Reset function
+
+
+
+ 2004/05/26: Martin Merck
+
+   * mbase/MDirIter.cc
+     - changed MatchFilter to allow for filenames containing a '+'
+       character.
+
+
+
+ 2004/05/26: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - set MCalibrationChargeBlindPix and MCalibrationChargePINDiode as 
+       data members and store them in the output of WriteResult()
+
+   * mcalib/MCalibrationQEPix.cc
+   * mcalib/MCalibrationChargeCalc.cc
+     - several small bugs fixed concerning calibration with the blind
+       pixel or the PIN Diode
+
+   * mjobs/MGCamDisplays.[h,cc]
+   * mhist/MHCamera.[h,cc]
+     - put the last function (CamDraw) of MGCamDisplays into MHCamera
+       and removed MGCamDisplays.
+
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - don't derive from MGCamDisplays any more.
+
+   * msignal/MExtractBlindPixel.cc
+     - adjusted some default numbers for the current blind pixel
+
+   * msignal/MExtractedSignalBlindPixel.[h,cc]
+     - set extracted signal from UInt_t to Int_t (sometimes, less
+       than 0)
+
+   * mcalib/MCalibrationCam.h
+   * mcalib/MHCalibrationCam.h
+     - make destructors virtual. 
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - create a copy contructor
+
+
+
+ 2004/05/26: Javier Rico
+
+   * mbase/MDirIter.h
+     - Add method to reset the internal TIter iterator 
+
+   * mjobs/MJCalibration.cc
+     - In FindColorReset method, reset the file iterator before looping
+
+   * mimage/MNewImagePar.cc
+     - Add output lines in Print(const MGeomCam &geom) method for 
+       fInnerLeakage1, fInnerLeakage2 and fInnerSize
+
+
+
+ 2004/05/25: Raquel de los Reyes and Thomas Bretz
+
+   * mjobs/MJCalibration.cc
+     - uncommented the line to read .raw files.
+
+   * mraw/MRawFileRead.cc
+     - changed the PreProcess and Process functions to allow the analysis
+       of .raw files.
+
+   * mfileio/MReadReports.cc
+     - changed the Process function to read the updated root files.
+
+
+
+ 2004/05/25: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - add possibility to switch on and off the blind pixel or pin diode
+       calibration
+     - fixed a small bug in reading the MCalibrationRelTimeCam when the
+       times calibration has been switched off.
+
+   * mjobs/MExtractSignal.[h,cc]
+     - made changes in MProcessFileP such that it fits with the new 
+       calibration. THIS IS ONLY A TEMPORARY SOLUTION. PEDESTALS AND 
+       DATA FILES MUST BE TREATED EQUALLY! OTHERWISE THERE IS NOT 
+       MATCHING FOR THE HIT CLEANING!!!
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - implement switch to use or not the cosmics filter
+
+ 
+   * mcalib/MHCalibrationTestPix.cc
+     - enlarged the dynamic range of the histograms for the high-int. 
+       pulses
+
+
+
+ 2004/05/24: Javier Rico
+
+   * mpedestal/MPedPhotCalc.cc
+     - Correct a bug that made pedestals be assigned to the wrong pixel
+
+   * mimage/MNewImagePar.[h,cc]
+     - add getters and output lines in Print() method for 
+       fInnerLeakage1, fInnerLeakage2 and fInnerSize
+
+
+
+ 2004/05/24: Markus Gaug
+
+   * mcalib/MCalibrationChargePix.cc
+     - reduce limit in number of phe's from 5 to 1. since some pulses 
+       have less than 5 phe's now.
+
+   * mcalib/MHCalibrationTestCam.[h,cc]
+     - number of photons/area are now stored in TArray's in order to 
+       retrieve them easier in later processing from stored files.
+
+   * mcalib/MCalibrationCam.cc
+     - initialize AverageAreas and AverageSectors with the number of 
+       aidx and sector as SetPixId()
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - small modification in the Print()
+     - introduce data members to store the average number of photons by 
+       the three methods
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - calculate the limits for acceptance of number of photo-electrons
+       for the calculation of the mean by normal mean instead of weighted 
+       mean. There were too many outliers still present in the weighted
+       mean such to modify the result by a sizeable amount.
+     - do not discard unreliable pixels any more in calculation of 
+       mean number of phe.s In some runs, there is simply too many of 
+       them in order to get reliable results.
+
+   * mpedestals/MPedCalcPedRun.cc
+     - put a condition if number of pixels in area index or in sector 
+       is zero, don't calculate av. pedestal and av. pedRMS of this part.
+
+
+
+ 2004/05/22: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - replaced the TString GetOutputFile() functions by const char* 
+       GetOutputFile(). This apparenty caused a memory leak which is now 
+       removed.
+
+   * mcalib/MCalibrationChargePix.cc
+     - fixed bug calculating the reduced sigma for low-gain events: 
+       the electronics Ped.RMS was taken from Hi-gain pedestal events and 
+       too high. It is now divided by the factor 10. conversion between 
+       both samples, but this value is probably too optimistic. Needs 
+       more detailed studies, but does not exclude as many pixels as 
+       before. 
+
+   * mcalib/MHCalibrationChargePix.h
+   * mcalib/MHGausEvents.h
+     - put fSaturated from MHCalibrationChargePix into MHGausEvents
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+   * mcalib/MHCalibrationCam.h
+     - put fNumHiGainSaturated and fNumLoGainSaturated from 
+       MHCalibrationChargeCam into MHCalibrationCam
+
+   * mcalib/MHCalibrationRelTimeCam.[h,cc]
+     - set flags fSaturated in order to distinguish if the hi-gain or 
+       the low-gain time has been extracted. 
+
+   * mcalib/MHCalibrationCam.cc
+     - remove cloning of all pixels on the Clone() function. This caused 
+       the need for three times more memory during runtime than now. It 
+       should not affect the current macros.
+
+   * macros/calibration.C
+     - added a debug switch with which you can print out Object
+       Allocation (like suggested by TBretz).
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - replaced the relative limit for acceptance of the time resolution 
+       by an absolute limit
+     - set up output statistics logging (data written into DB)
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - moved limit for acceptance of number of phe;s from 5 to 8
+     - set up output statistics logging (data written into DB)
+
+   * mjobs/MJCalibration.cc
+     - set up output statistics logging (data written into DB)
+
+
+
+ 2004/05/22: Abelardo Moralejo
+
+   * macros/calibrate_data.C
+     - removed wrong call to MPedCalcPedRun::SetExtractor, which does
+       not exist (should use MJPedestal like calibration.C, instead of 
+       a normal loop)
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - changed name of variable fOffsetFromPeak to fOffsetFromWindow
+       to avoid confusion.
+     - introduced initialization to 0 of startslice and sat in FindPeak
+     - changed initialization of maxsumhi in Process from 0 to -1e6
+
+
+
+ 2004/05/20: Raquel de los Reyes
+ 
+   * mraw/MRawRead.h
+   * mraw/Makefile
+   * msql/Makefile
+     - changed the inheritance of MRawRead class from MTask to MRead to
+       implement the AddFiles(MDirIter &) function in MRawFileRead class.
+
+   * mraw/MRawFileRead.[h,cc]
+     - implemented a second argument to the AddFile function and skip 
+       adding NULL files in the constructor.
+
+   * mjobs/MJPedestal.cc
+     - uncommented the line to allow the analysis of .raw files.
+
+
+
+ 2004/05/20: Markus Gaug
+ 
+   * mjobs/MJPedestal.cc
+     - put MGeomCamMagic into the plist (MGeomApply complained not to 
+       find the GeomCam(
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - fixed a bug affecting signals with late arrival times which use 
+       the variable fHiLoLast. 
+     - set back fgOffsetFromPeak from peak to 1 (instead of 2). Abelardo 
+       explained that this variable is not strictly the offset from the 
+       peak but the offset from the peak search window. 
+
+
+
+ 2004/05/19: Markus Gaug
+ 
+   * mcalib/MCalibrationChargeCam.cc
+     - replaced a small bug in Print() which gave a segmentation 
+       violation	
+
+   * mjobs/MJCalibration.cc
+     - use cosmics filter only for CT1 pulser runs
+
+
+
+ 2004/05/19: Abelardo Moralejo
+
+   * mbase/MGMap.cc
+     - replaced rint by TMath::Nint() (my Mac did not recognize the 
+       former)
+
+
+
+ 2004/05/19: Abelardo Moralejo
+
+   * macros/starmc2.C
+     - added third argument in adding MPointingPos to the output:
+       write.AddContainer("MPointingPos",  "Events", kFALSE);
+       If not exisiting in the input file, it is simply ignored.
+
+
+
+ 2004/05/15: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - changed Form to MString for thread safty
+     - fixed a bug which caused the construtor to crash in batch-mode
+     - added option argument to PaintImg
+
+   * mbase/MGMap.[h,cc]:
+     - added many new static member function to draw figures
+
+   * mbase/MParContainer.cc:
+     - changed Form to MString for thread safty
+
+   * mbase/MString.[h,cc]:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MString
+
+
+
+ 2004/05/15: Markus Gaug
+
+   * msignal/MArrivalTimePix.h
+   * msignal/MArrivalTimeCam.cc
+     - introduced functin GetHiGainSaturation() in MArrivalTimePix.h
+     - added type in GetPixelContent() which asks for Hi-Gain saturation
+       and return the hi-gain time or the low-gain time, correspondingly.
+
+   * mbase/MGMap.cc
+     - fixed two bugs which did not complile under gcc 3.3.x introduced
+       by TB.
+
+
+
+ 2004/05/12: Markus Gaug
+
+   * msignal/MExtractTime.[h,cc]
+     - introduced intrinsic delay of low-gain, as measured by Florian. 
+
+   * mjobs/MJCalibration.cc
+   * mjobs/MJExtractCalibTest.cc
+     - fixed some errors in the storage of the rel. times.
+
+   * mjobs/MJExtractCalibTest.cc
+     - put the cosmics filter which was forgotten
+
+   * mcalib/MCalibrate.h
+     - changed default from Blindpixel to Ffactor     
+
+
+
+ 2004/05/12: Thomas Bretz
+
+   * mona.cc:
+     - changed names
+
+   * macros/sumcurrents.C:
+     - changed units from nA to \\mu A
+
+   *: mastro/MAstroCamera.[h,cc]:
+     - added '=' Draw option
+     - use fMapG directly
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - added support to read and write a compressed catalog
+     - changed TExMap to new MGMap
+     - added support for HeasarcPPM catalog
+     - added PaintImg to paint catalog into a bitmap (used in
+       starguider software)
+     - don't clone MObservatory copy the contents
+     - changed type of dx and dy in DrawLine from Double to Int
+     - fixed drawig of the tooltip corresponding to the grid
+       (some were missing, some were existing twice)
+     - Now AddPrimitives takes fLimMag into account
+
+   * mhbase/MFillH.cc:
+     - added a const-qualifier
+
+   * mhist/MHCamera.cc:
+     - fixed a bug which caused SetPalette in the constructor to crash
+
+   * mbase/MGMap.[h,cc]:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MGMap
+
+
+
+ 2004/05/11: Thomas Bretz
+
+   * mraw/MRawEvtHeader.cc:
+     - added a check whether the file has finished or not after
+     reading the first bytes.
+
+
+
+ 2004/05/10: Marcos Lopez
+
+   * mmontecarlo/MMcEnergyEst.cc: 
+     - In static void fcn(...), fixed the following bugs which caused a
+       "segmentation violation":
+     - Replace: MTaskList *tlist  = evtloop->GetTaskList()
+       by:      MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList")
+     - And get the pointer *eval to MParamterD("MFitResult"), after 
+       the excution of the Eventloop and not before it (since that object is 
+       created when calling the PreProcess).
+
+
+
+ 2004/05/10: Thomas Bretz
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - changed return type of ReadEvt from int to Int_t
+     - Enhanced output in case of invalid time
+
+   * mraw/MRawRead.cc:
+     - fixed the return type of ReadEvt (was bool instead of int)
+       which confused merpp completely in case of invalid times
+
+
+
+ 2004/05/10: Markus Gaug
+
+   * macros/calibrate_data.C
+     - updated setting of arr. time extractor
+
+
+
+ 2004/05/09: Thomas Bretz
+
+   * Makefile:
+     - added workaround for Mac to create so- and dynlib-object
+
+   * Makefile.conf.darwin:
+     - added necessary option to create both kind of files
+
+   * Makefile.conf.linux:
+     - changed the options to create so-object only
+
+   * Makefile.rules:
+     - added DYLIB to rmbin
+
+   * mraw/MRawEvtData.cc:
+     - changed some output
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - skip the rest of the header if the time is invalid. Otherwise
+       merpps force-mode will corrupt the data when further processing
+     - implemented GetNumBytes returning the size of the header
+
+
+
+ 2004/05/08: Thomas Bretz
+
+   * mona.cc:
+     - some changes to make it work again
+
+   * mraw/MRawSocketRead.cc:
+     - fixed the sync with what DAQ sends
+
+
+
+ 2004/05/07: Markus Gaug
+
+   * mcalib/MHCalibrationChargeHiGainPix.cc
+   * mcalib/MHCalibrationChargeLoGainPix.cc
+     - take out half of the bins for the hists in order to save memory  
+
+   * mjobs/MExtractCalibTest.cc
+     - include write-out of the containers in the loop
+
+   * mjobs/MJCalibration.cc
+     - take runs 20660 and 20661 into the list of known runs with colour
+       green.
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - make the arrays fSum and fSum2 doubles. This is necessary since 
+       rounding errors of the floats introduced significant errors in the 
+       RMS! 
+     - introduced one condition about possible window sizes of 0.
+
+
+
+ 2004/05/06: Markus Gaug
+
+   * htmldoc/images/PedestalStudyInner.gif
+   * htmldoc/images/PedestalStudyOuter.gif
+     - two gifs used for the documentation of MPedCalcPedRun  
+
+   * mpedestal/MPedCalcPedRun.cc
+     - updated documentation
+
+   * macros/pedestalstudies.C
+     - updated to the latest version of MPedCalcPedRun
+
+   * macros/bootcampstandardanalysis.C
+     - updated to the latest changes in the ArrivalTime Extraction
+
+
+
+ 2004/05/05: Markus Gaug
+
+   * mcalib/MHGausEvents.cc
+     - removed some warning saying "Cannot create Fourier spectrum"
+
+   * mcalib/MCalibrationChargePix.cc
+     - loosened the limits somewhat for calibration with the low-gain
+     - introduced different electronic noise for inner and outer pixels
+       (like seen in the data)
+
+   * mpedestal/MPedCalcPedRun.cc
+     - fixed a small inconsistency in case that the range goes out of 
+       the high-gain samples and reaches into the low-gain samples. In 
+       that case, the last slice of the high-gain was not taken (but the 
+       window size correctly)
+ 
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - included setters for the time extractor
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - set default of fgPheErrLimit from 4 sigma to 5.
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MHCalibrationTestTimeCam.[h,cc]
+   * mcalib/MHCalibrationTestTimeCam.[h,cc]
+     - analogue to MHCalibrationTestCam, two classes to test the 
+       output of the calibration.
+
+   * mcalib/MHCalibrationCam.cc
+     - in InitHists, exclude only pixels with kUnsuitableRun, instead of 
+       all (IsBad())
+
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+   * msignal/MExtractTimeFastSpline.[h,cc]
+     - new fast spline extractor for the equally spaced time slices. 
+       Searches for the position of the half maximum between maximum and 
+       pedestal. About 6 times faster than MArrivalTimeCalc
+
+   * mjobs/MJCalibration.cc
+     - changed names of the MHCameras to contain run name
+
+
+
+ 2004/05/04: Raquel de los Reyes
+ 
+   * mbase/MRunIter.[h,cc]
+     - Added a flag and a set function to read .raw files. 
+       The default option is set to read .root files.
+
+
+
+ 2004/05/04: Javier Rico
+ 
+   * mcalib/MCalibrate.cc
+     - when calibrating using kNONE, weight by the pixel area
+
+
+
+ 2004/05/04: Thomas Bretz
+ 
+   * macros/MagicHillas.C, macros/comprob.C, macros/derotatedc.C, 
+     macros/dohtml.C, macros/evtrate.C, macros/merpp.C, 
+     macros/pixfirerate.C, macros/pixsatrate.C, macros/plot.C, 
+     macros/plot2.C, macros/pointing.C, macros/readMagic.C, 
+     macros/rootlogon.C, macros/runbook.C, macros/sectorvstime.C, 
+     macros/star.C, macros/sumcurrents.C, macros/tar.C, 
+     macros/testenv.C, macros/weights.C:
+     - updated documentation
+
+   * mastro/MAstroCamera.[h,cc]:
+     - added member function to read MC .def files for mirror geometry
+     - added GetDiffZdAz
+
+   * mastro/MObservatory.[h,cc]:
+     - added Copy-member function
+
+   * mbase/MLog.[h,cc]:
+     - updated handling of mutices
+     - added a new mutex to lock the stream
+
+   * mhist/MHCamera.[h,cc]:
+     - added functionality to linear deform the camera display
+       (to correct for abberation)
+
+   * mtools/MFFT.cc:
+     - added more documentation
+
+   * mbase/MTime.[h,cc]:
+     - renamed overloaded Set-function to SetMjd. There were some
+       trouble with the interpreter and the new naming is more
+       intuitive.
+
+
+
+ 2004/05/04: Markus Gaug
+ 
+   * mcalib/MHCalibrationChargeBlindPix.cc
+     - intialized the 2 vectors differently, now they don't give 
+       warnings any more.
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractFixedWindow.cc
+     - put one initialization to 0 into the MExtractor
+
+   * mastro/MAstroCatalog.h
+     - make AlignCoordinates() protected, in order to compile
+
+   * mcalib/MHGausEvents.cc
+     - took out fEvents(0) and fHGausHist() from constructor
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractPINDiode.cc
+     - fixed StreamPrimitive
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - deriving from MExtractor, possibility to filter NSB events
+
+ 
+
+ 2004/05/03: Thomas Bretz
+
+   * mbase/MRunIter.cc:
+     - AddRuns(char*) added some const-qualifiers
+     - replaced deprecated if-else-if by continue- and return-
+       constructions
+
+
+
+ 2004/05/03: Javier Lopez
+ 
+   * mbadpixels/MBadPixelsPix.[h,cc]
+     - put another enum for hardware malfunctionning. Started to be 
+       filled with kHVNotNominal
+
+
+
+ 2004/05/03: Markus Gaug
+
+   * mcalib/MHCalibrationBlindPix.[h,cc]
+     - removed a "->" behind the comment
+     - Create a TVector in Draw only if the array is not zero
+
+   * mraw/MRawEvtPixelIter.cc
+     - corrected bug in GetIdxMaxLoGainSamples() which looped over 
+       one slice too much 
+	end = fLoGainPos + fNumLoGainSamples + 1 replaced by:
+	end = fLoGainPos + fNumLoGainSamples
+
+   * msignal/MTimeExtractor.[h,cc]
+   * msignal/MExtractTime.[h,cc]
+     - changed name for alphabetical display in dox
+
+   * mjobs/MJCalibration.[h,cc]
+   * msignal/MExtractTimeSpline.h
+   * msignal/MExtractTimeHighestIntegral.h
+     - changed name of base class to MExtractTime
+
+   * mcalib/MCalibrationCam.[h,cc]
+   * mcalib/MCalibrationChargeCam.[h,cc]
+   * mcalib/MCalibrationRelTimeCam.[h,cc]
+     - put the number of unsuitable and unreliable pixels in the base
+       class
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - fixed a bug calculating the average time resolution
+ 
+   * mpedestals/MPedestalPix.[h,cc]
+     - add a dedicated fValid flag in order to be able to discard pixels 	 
+       from outside (e.g. from MBadPixelsCam)
+
+   * mpedestals/MPedCalcPedRun.[h,cc]
+     - catch badpixels cam from parameter list, if existing and set 
+       corresponding pixels to not valid in MPedestalPix
+
+   * mjobs/MGCamDisplays.[h,cc]
+   * mhist/MHCamera.[h,cc]
+     - put DrawProjection and DrawRadialProfile in MHCamera
+
+   * macros/dohtml.C
+     - include directory mfit and macros calibration.C and 
+       bootcampstandardanalysis.C
+     - take out pixvstime.C which does not exist
+
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+   * msignal/MExtractor.[h,cc]
+   * msignal/MExtractPINDiode.[h,cc]
+   * msignal/MExtractTime.[h,cc]
+     - set number of slices not in base class, but in derived one. 
+       Like this, extractors setting their signal in other containers 
+       don't have a conflict with the ReInit() in MExtractor.
+
+
+
+ 2004/05/01: Thomas Bretz
+
+   * macros/rootlogon.C:
+     - ignore MARSSYS if libmars.so is found in the current path
+
+   * mastro/MObservatory.cc:
+     - small change to coordinates
+
+   * mbase/MLog.[h,cc]:
+     - enhanced output in case of problem with mutices
+
+   * mtemp/TempIncl.h, mtemp/TemlLinkDef.h:
+     - removed everything
+
+   * Makefile*, */Makefile
+     - changed all to support mtemp/mifae and similar
+
+
+
+ 2004/05/01: Abelardo Moralejo
+
+   * mmain/MEventDisplay.cc
+     - changed back integration range for MC to 0-14 slices to avoid 
+       confusions.
+
+
+
+ 2004/05/01: Markus Gaug
+
+   * macros/dohtml.C
+     - include directory mpedestal
+
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+   * msignal/MExtractor.[h,cc]
+     - include the possibility to set the range for the hi-gain outside
+       the range of MRawEvtPixelIter::GetNumHiGainSamples() and to take 
+       the "low-gain" slices instead. This is necessary for the March 
+       data!
+
+   * mjobs/MJCalibration.[h,cc]
+     - accept arrival time extractors deriving from MTimeExtractor
+
+
+
+ 2004/04/30: Thomas Bretz
+
+   * mastro/MAstroCamera.[h,cc]:
+     - removed obsolete TList data member (use a argument in
+       GetStarList instead)
+
+   * mbase/MTime.h:
+     - added 'istream &operator<<(istream &in, MTime &t)'
+
+   * mbase/BaseLinkDef.h:
+     - added new operator
+
+
+
+ 2004/04/30: Daniela Dorner
+  
+   * macros/pointing.C
+     - implemented plot: Control Deviation vs Time
+     - rearranged plots
+
+
+
+ 2004/04/30: Markus Gaug
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - new class to treat rel. times after fits
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - search for outliers in the total F-Factor and set a flag in 
+       MBadPixelsPix
+
+   * mcalib/MCalibrationRelTimeCam.h
+     - new TArrayIs to store number of unsuitable and unreliable pixels
+   
+
+   * mbadpixels/MBadPixelsPix.h
+     - two new flags added: kDeviatingFFactor and kDeviationTimeResolution
+  
+   * mcalib/MHCalibrationRelTimePix.[h,cc]
+     - take out commented part of code related to re-normalization
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - retrieve the used run numbers in order to store them in teh 
+       histogram titles to help transparency of the displays
+
+   * mcalib/MHCalibrationRelTimeCam.[h,cc]
+     - Getter and Setter for the reference pixel
+
+   * mcalib/MCalibrate.cc
+     - make error of nphot to be taken from square root of absolute 
+       number of photons instead of number of photons, otherwise 
+       NaN's are obtained
+
+   * msignal/MExtractPINDiode.[h,cc]
+     - now deriving from MExtractor
+
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+   * msignal/MExtractTimeSpline.[h,cc]
+   * msignal/MExtractTimeHighestIntegral.[h,cc]
+     - replacements for MArrivalTimeCalc and MArrivalTimeCalc2
+
+   * mjobs/MJCalibration.[h,cc]
+     - Set time extractor by pointer 
+
+
+
+ 2004/04/29: Thomas Bretz
+
+   * mbase/MTask.cc:
+     - fixed behaviour of GetNumExecutions. Because of a root bug
+       Count returns a number which is to high by 1.
+
+
+
+ 2004/04/29: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Added minor comment (explanation of fPassPhotCone).
+
+   * mmc/MMcRunHeader.[hxx,cxx]
+     - Removed obsolete parameters fSourceOffsetTheta, fSourceOffsetPhi
+     - Updated class version to 5.
+
+
+
+ 2004/04/29: Nadia Tonello
+
+   * mbadpixels/MBadPixelsTreat.h
+     - changed enums {.. BIT(1), ... BIT(2), ... BIT(3) } in {1,2,3}
+       to have the right behaviour of the flags (and of SetProcessRMS)
+
+   * manalysis/MCT1PointingCorrCalc.[h,cc]
+     - added pointing correction for 1ES1959
+
+
+
+ 2004/04/29: Markus Gaug
+
+   * msignal/MArrivalTimePix.[h,cc]
+     - removed flag fLoGainUsed which is not used at all
+
+   * msignal/MTimeExtractor.[h,cc]
+     - new base class for arrival time extractors
+   
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+   * msignal/MExtractTimeSpline.[h,cc]
+     - replacement of MArrivalTimeCalc, derived from MTimeExtractor
+
+
+   * msignal/MExtractor.h
+     - make SetRange virtual
+     - check for range w.r.t. ranges given in the run header in ReInit
+
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - overload the SetRange() function in order to do the necessary 
+       checks of the range there. Slight differences in every extractor
+       because of the floating windows.
+
+
+   * mpedestals/MPedCalcPedRun.[h,cc]
+     - add the possibility to set ranges and extraction windows. Default
+       is what has always been
+
+
+   * mjobs/MJPedestals.[h,cc]
+     - add the possibility to set a signal extractor which gives the 
+       extraction ranges to MPedCalcPedRun
+     - derive from MHCamDisplays
+
+   * mcalib/MCalibrationChargeCam.cc
+     - updated the Print() a little
+
+
+ 2004/04/29: Javier Rico
+
+   * mbase/MRunIter.cc
+     - Remove AddRuns(const char*,const char*) dependence on length of 
+       first character chain
+
+	
+ 2004/04/28: Javier Rico
+
+   * mbase/MRunIter.[h,cc]
+     - include function to read runs specified in a character chain
+       with the format, e.g., run1,run2-run3,run4-run5,...
+
+
+
+ 2004/04/28: Abelardo Moralejo
+
+   * macros/starmc.C
+     - adapted to change in MC calibration: replaced 
+       MMcCalibrationCalc::GetHist by GetHistADC2PhotEl and 
+       GetHistPhot2PhotEl.
+
+
+
+ 2004/04/28: Markus Gaug
+ 
+   * mjobs/MGCamDisplays.cc
+   * mjobs/MJCalibration.cc
+     - introduced new "fit" flag in DrawProjection allowing to draw 
+       two separate pad with the (fitted) histograms for inner and 
+       outer pixels. This is displayed by MJCalibration if the 
+       kNormalDisplay option is chosen (default).
+
+   * mjobs/MJCalibration.h
+     - took out the const of GetBadPixels() in order to allow compilation
+       of macros/bootcampstandardanalysis.C. This will change again soon 
+       when mjobs/MJExtraction is updated and used there. 
+
+   * msignal/MArrivalTimeCalc.[h,cc]
+     - remove the ReInit() which calls to an MGeomCam which is later not 
+       used
+
+   * macros/calibrate_data.C
+     - fixed a bug in loop 3 taking the default QE Cam instead of the 
+       one filled by MJCalibration 
+
+   * msignal/MExtractor.[h,cc]
+     - new base class for signal extractors
+
+   * msignal/Makefile	
+   * msignal/SignalLinkDef.h	
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidindWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - replacements for MExtractSignal, MExtractSignal2, MExtractSignal3
+
+   * macros/calibration.C
+   * macros/calibrate_data.C
+   * macros/pedphotcalc.C
+   * macros/bootcampstandardanalysis.C
+     - adapted to new extractors
+
+   * mbadpixels/MBadPixelsPix.h
+     - set back the old definition of IsOK(), namely no information 
+       available
+
+
+
+ 2004/04/27: Raquel de los Reyes
+
+   * mhvstime/MHVsTime.cc
+     - added a line in the Fill function to avoid empty time events.
+
+
+
+ 2004/04/27: Abelardo Moralejo
+
+   * mcalib/MMcCalibrationCalc.[h,cc]
+     - added histogram which stores the conversion of photons before 
+       the plexiglas to photoelectrons hitting first dynode.
+
+   * macros/mccalibrate.C
+     - added MPointingPosCalc to the tasklist to create and fill an 
+       MPointingPos object, and later write it to the Events tree of 
+       the calibrated MC files. Added some comments and simplified
+       some lines. One more histogram from MMcCalibrationCalc (see
+       above) is now written to the output.
+
+   * macros/starmc2.C
+     - added the writing of MPointingPos to output star file.
+
+
+
+ 2004/04/27: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - put the three camera drawing facilities into a separate base 
+       class MGCamDisplays
+
+   * mjobs/MGCamDisplays.[h,cc]
+   * mjobs/Makefile
+   * mjobs/JobsLinkDef.h
+     - camera drawing facilities: CamDraw, DrawProjection and 
+       DrawRadialProfile, used by all jobs
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+   * mjobs/Makefile
+   * mjobs/MJobsLinkDef.h
+     - new class to test the calibration results
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - set unsuitable pixels to excluded in MCalibrationChargePix, which 
+       will not display them in the status display
+
+   * mjobs/MJCalibration.cc
+     - take out display of previously excluded pixels 
+
+   * mbadpixels/MBadPixelsCam.cc
+     - set val to 1 in case that GetPixelContent is true, before display 
+       was not correct
+
+   * macros/calibration.C
+     - added the test class MJExtractCalibTest
+
+
+
+ 2004/04/27: Abelardo Moralejo
+
+   * mhistmc/MHMcCollectionArea.[h,cc]
+     - Added fMCAreaRadius and setter to allow changing the radius of
+       the circular area in which MC events are produced. Useful for
+       instance for stereo configuration studies. By default it is 300 m
+       as was assumed before.
+
+
+
+ 2004/04/26: Markus Gaug
+
+   * mcalib/MHCalibrationTestPix.[h,cc]
+   * mcalib/MHCalibrationTestCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - two new histogram classes to perform claibraion checks, will be 
+       especially useful for the data-check.
+
+   * mcalib/MCalibrationQEPix.cc
+     - found a bug in the setting of validity flags of colours. This 
+       made the QE used for calibration uncorrect by about a factor 1.5 
+       for the outer pixels if only one colour is used for calibration.
+
+   * mjobs/MJCalibration.[h,cc]
+     - moved colour finder from the macros into this class with the 
+       function FindColor()
+     - had to add ~MJCalibration() {} because otherwise, I get a 
+       segmentation violation in the destructor, the debugger says in 
+       some TString. Maybe it's because of the GetDescriptor() in  
+       ~MParContainer() ?
+
+   * macros/calibration.C
+   * macros/calibrate_data.C
+   * macros/pedphotcalc.C
+   * macros/bootcampstandardanalysis.C
+     - removed function FindColor()
+
+   * mcalib/MCalibrationCam.h
+     - make Init() and InitSize() virtual
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - introduce two TArrayI's for the number of uncalibrated and 
+       unreliable pixels.
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - calculate and store the above numbers.
+
+   * mbadpixels/MBadPixelsPix.[h,cc]
+   * mbadpixels/MBadPixelsCam.cc
+     - removed bits: kHiGainNotCalibrated and kLoGainNotCalibrated
+     - added bits: kDeviatingFFactor, kConversionHiLoNotValid
+     - removed functions: IsCalibrationResultOK() 
+	and IsCalibrationSignalOK()
+     - changed function IsOK() such that it returns false only if 
+       the pixels is not suitable (run or evt)
+
+   * mcalib/MCalibrate.cc
+   * mcalib/MCalibrateRelTime.cc
+     - exchanged query for IsCalibrationResultOK() to 
+       IsUnsuitableRun(MBadPixelsPix::kUnsuitableRun). This includes 
+       now the oscillating pixels (which are sometimes many!!)
+
+   * mcalib/MHCalibrationRelTimePix.cc
+     - commented re-normalization to ns in Renorm()
+     - introduced Getter to fFADCSliceWidth
+
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - renorm to ns in GetPixelsContent()
+     --> now, calibration in MCalibrateRelTimes is consistent
+
+
+
+ 2004/04/26: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - changed from 1 to 10 the "dummy" value of conversion high to low 
+       gain for old camera 0.6 files. Usually these files have no low 
+       gain at all, but there was a patched version of the program 
+       which did have low gain (with a gain 10 lower than hg).
+
+
+
+ 2004/04/25: Abelardo Moralejo
+
+   * mbadpixels/MBadPixelsTreat.cc
+     - Change in line 204:    if ((*fBadPixels)[i].IsBad()) by
+       if ((*fBadPixels)[j].IsBad())   The way it was done, it never
+       worked, because the check on whether the neighbour pixels
+       were OK was performed on the same pixel to be treated (i), which 
+       is obviously not OK. The same problem fixed in the interpolation 
+       of pedestals. Amazingly, this error would have shown up in any
+       test of the class.... I assume it must have been commited 
+       completely untested.
+
+     - In InterpolateSignal: moved division of summed charge over 
+       number of pixels : put it after the check of the number of 
+       valid neighbours to avoid division by 0.
+
+
+
+ 2004/04/23: Markus Gaug
+
+   * mcalib/MHCalibrationCam.cc
+     - fixed a bug in the ReInit() for the number of average events in 
+       each area index and sector
+
+
+ 2004/04/23: Thomas Bretz
+
+   * */Makefile:
+     - added some more mpedestal
+
+   * mreport/MReportRun.cc:
+     - changed to work with the latest version of report-files
+       --> This will make it incompatible with older report files
+           (for this use older Mars versions for merpping)
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added combo-box to surf through tabs in MARS-tab
+
+
+
+ 2004/04/22: Nadia Tonello
+
+   * mcalib/MCalibrateData.cc
+     - changed request for MBadPixelsPix::IsCalibrationResultOK() for 
+       MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun)
+
+
+
+ 2004/04/22: Thomas Bretz
+
+   * mhist/MHCamera.[h,cc]:
+     - implemented SetUsed
+
+   * merpp.cc:
+     - added "-ff" and interleave mode - both not execcively tested yet
+
+   * mhbase/MFillH.cc:
+     - added a missing 'endl'
+
+   * mraw/MRawCrateData.[h,cc], mraw/MRawEvtData.[h,cc],
+     mraw/MRawEvtHeader.[h,cc]
+     - added SkipEvt (the number of skipped bytes is untested)
+
+   * mraw/MRawEvtHeader.[h,cc]
+     - return kCONTINUE if time is invalid
+
+   * mraw/MRawFileRead.[h,cc]:
+     - implemented AddFile feature - first draft!
+     - added feature to skip events
+
+   * mraw/MRawFileWrite.h:
+     - changed default compression level corresponding to merpp to 2
+
+   * mraw/MRawRead.[h,cc]:
+     - added fForceMode flag to be able to suppress event errors
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - changes such that the pedestal interpolation is now done
+       only in ReInit. If you need the old behaviour call
+       SetProcessRMS()
+
+   Another step towards less mess:
+   
+   * MMcPedestalCopy.[h,cc], MMcPedestalNSBAdd.[h,cc],
+     MPedPhotCalc.[h,cc], MPedPhotCam.[h,cc], MPedPhotPix.[h,cc],
+     MPedCalcPedRun.[h,cc], MPedestalCam.[h,cc],
+     MPedestalPix.[h,cc]:
+     - moved from manalysis to mpedestal
+
+   * mpedestal/Makefile, mpedestal/PedestalLinkDef.h,
+     mpedestal/PedestalIncl.h:
+     - added
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h,
+     manalysis/AnalysisIncl.h:
+     - removed files above
+
+   * mbadpixels/Makefile:
+     - added mpedestals
+
+   * Makefile:
+     - added mpedestals
+
+
+ 2004/04/22: Antonio Stamerra
+
+   * mmain/MEventDisplay.cc
+     - Added new tab "Trigger" adding a new MHEvent (evt9), 
+	filled through the MMcTriggerLvl2 container.
+	A new MFillH task for evt9 and MMcTriggerLvl2Calc task 
+	have been added. 
+
+   * mhist/MHEvent.[h,cc]
+     - Added new event type kEvtTrigPix
+
+   * manalysis/MMcTriggerLvl2.[h,cc]
+     - The class now inherits from MCamEvent
+     - Added the methods GetPixelContent and DrawPixelContent (from MCamEvent)
+     - Added the method IsPixelInTrigger that returns kTRUE if a pixels 
+	is in the trigger region
+
+   * manalysis/MMcTriggerLvl2Calc.[h,cc]
+     - Added the methods CheckRunType and ReInit to check if the file is MC.
+
+   * mhistmc/Makefile
+     - Added the include for mgui
+
+
+ 2004/04/22: Markus Gaug
+
+   * mcalib/MCalibrate.[h,cc]
+     - introduced flat-fielding of charges for the muon calibration, 
+       accessible with SetCalibrationMode(kFlatCharge)
+
+   * manalysis/MPedCalcPedRun.cc
+     - added a SetReadyToSave() at the end of PostProcess
+   
+   * mjobs/Makefile
+     - added include of mraw
+
+   * mjobs/MJCalibration.cc
+     - added MRawFileRead for option SetDataCheck()
+
+   * mjobs/MJPedestal.cc
+     - added MRawFileRead for option SetDataCheck()
+
+
+ 2004/04/21: Thomas Bretz
+
+   * mbase/MTask.cc,  mbase/MTaskList.cc:
+     - let MTask in list fTaskProcess to be used as a counter
+
+   * mdata/MDataChain.[h,cc]:
+     - added some treatments for combinations of +/- signs
+
+   * mfbase/MFilterList.[h,cc]:
+     - added a new constructor to simplyfy filter-inversions
+
+   * mfileio/MReadReports.cc:
+     - added comment
+
+   * mhbase/MBinning.[h,cc]:
+     - added new constructor to simplify calls in macros
+
+   * mhbase/MFillH.[h,cc]:
+     - added fDrawOption to be used in MStatusDisplay
+
+   * mhist/MHFalseSource.cc:
+     - added comment
+
+
+
+ 2004/04/20: Thomas Bretz
+
+   * macros/derotatedc.C
+     - added tutorial macro plotting derotated dc currents
+
+   * mhist/MHCamEventRot.[h,cc]:
+     - added histogram to be filled with derotated MCamEvents
+
+
+
+ 2004/04/18: Abelardo Moralejo
+
+   * mgeom/MGeomCam.h
+     - Update class version to 4 (necessary after M. Gaug's change 
+       of the type of member fMaxRadius.
+
+
+
+ 2004/04/16: Abelardo Moralejo
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - Added fAverageQE. Same role as gkDefaultAverageQE, but can be 
+       changed via SetAverageQE. Made public GetAverageQE and 
+       GetAverageQERelVar (this changes needed for MC).
+
+   * mcalib/MMcCalibrationCalc.[h,cc]
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Adapted to M. Gaug's changes in calibration classes. Behaviour
+       has been tested to be the same as before those changes. Now the
+       conversion factor from ADC counts to photoelectrons, and the
+       average QE (photons->photoelectrons) are calculated independently 
+       (and later combined by MCalibrate to obtain the conversion 
+       ADC->photons).
+
+   * mmain/MEventDisplay.cc, macros/mccalibrate.C, starmc.C
+     - Added call to MExtractSignal::SetSaturationLimit(240)  Affects 
+       only MC display. This was necessary because if electronic noise
+       is simulated in the FADC, sometimes saturated slices look not
+       saturated due to negative fluctuations, so it is better to set 
+       the saturation limit at a safe value (240 ADC counts). Changed 
+       signal integration range (only for MC), now from slices 5 to 10.
+
+   * msignal/MExtractSignal3.[h,cc]
+     - Changed name of function SetRange for the more adecquate 
+       "SetWindows". No change in behaviour of the function.
+
+
+
+ 2004/04/16: Markus Gaug
+
+   * msignal/MExtractSignal.cc
+     - commited proposed larger default window from fgLast = 10 to 
+       fgLast = 14, because in March the pulses have moved to later 
+       arrival times.
+     - removed some inconsistency with slice numbering in FindSignal() 
+       from pixel.GetHiGainSamples()+fHiGainFirst-1 to 
+       pixel.GetHiGainSamples()+fHiGainFirst and also for the low gain
+
+   * msignal/MExtractSignal2.cc
+     - committed the proposed smaller window egdes from fgFirst=0 to 
+       fgFirst = 3, because in March some of the high-gain pulses reach 
+       into the "low-gain samples" and mislead thus sliding window to 
+       be maximized on the tail of the high-gain pulse.
+
+   * mcalib/MHPedestalPix.cc
+     - fixed a bug which made normalization to values per slice not happen
+
+   * macros/pedestalstudies.C
+     - fixed and documented
+
+
+
+ 2004/04/15: Markus Gaug
+
+   * macros/calibration.C
+     - added a function FindColor() to extract the colour by filename, 
+       works if there is indeed a colour or if the run nubmer is smaller 
+       than 20000 -> take ct1
+
+   * macros/bootcampstandardanalysis.C
+   * macros/pedphotcalc.C
+   * macros/calibrate_data.C
+     - updated the macro to the cvs-standard used at the Udine bootcamp
+
+   * mcalib/MCalibrateRelTimes.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new class to calibrate the relative times
+
+   * manalysis/MGeomApply.cc
+     - added MArrivalTime::Init()
+
+   * msignal/MArrivalTime.[h,cc]
+     - added array fDataErr
+ 
+   * macros/rootlogon.C
+     - added directories mbadpixels and mjobs
+
+   * mcalib/MCalibrationQEPix.cc 
+     - set the fAvNorm variables to 1 in Clean()
+
+   * manalysis/MPedPhotCalc.[h,cc]
+     - included possibility to use an MBadPixelsCam
+
+
+
+ 2004/04/14: Thomas Bretz
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - fixed a bug which caused a missing last pixel (in most cases
+       Index 576)
+
+   * manalysis/MCerPhotPix.cc:
+     - fixed output in Print
+
+   * macros/mccalibrate.C, mmain/MEventDisplay.cc:
+     - added missing SetCalibrationMethod
+
+   * mbadpixels/MBadPixelsCam.[h,cc]:
+     - added copy constructor
+
+   * mbadpixels/MBadPixelsMerge.cc:
+     - added comments
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added new run-type (kRTPointRun=7)
+
+   * mmain/MEventDisplay.cc:
+     - fixed the broken cleaning levels
+
+
+
+ 2004/04/14: Markus Gaug
+  
+   * mcalib/MCalibrationQEPix.cc
+     - found a bug in the calculation of the error, fixed
+
+   * macros/mccalibrate.C, mmain/MEventDisplay.cc:
+     - replaced SetCalibrationMethod by SetCalibrationMode
+
+   * htmldoc/images/CalibClasses.gif
+   * htmldoc/images/RelTimeClasses.gif
+     - two schemes used in the class descriptions
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - included function GetAverageAreas() and GetAverageSectors() like 
+       in MCalibrationCam
+
+   * mjobs/MJCalibration.[h,cc]
+     - included calibration of rel.Times, to be chosen with a flag 
+       RelTimeCalibration()
+     - signal extractor and arrival time extractor can be chosen by 
+       flags as well (see Class description)
+
+
+   * mbadpixels/MBadPixelsCam.cc
+     - add two new types in GetPixelContent, add documentation of 
+       GetPixelContent
+
+   * msignal/MArrivalTimeCalc2.cc
+     - commented the warning for pixels with lowgain saturation
+
+
+
+ 2004/04/13: Markus Gaug
+
+   * macros/dohtml.C
+     - included directory mbadpixels
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - add functions GetHiLoMeansDivided(), GetHiLoSigmasDivided() and 
+       errors
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - removed hi-vs.Lo histograms (come into a separate MIntensityCam) 
+     - updated GetPixelContents
+     - updated class documentation
+
+   * mgeom/MGeomMirror.h
+     - include <TVector3.h>, otherwise it does not compile on my machine  
+
+   * mjobs/MJPedestals.cc
+   * mjobs/MJCalibration.cc
+     - replaced MBadPixelsMerge by MParList.AddToList(fBadPixels) until 
+       bug in MBadPixelsMerge is resolved (see bugtracker).
+
+   * mcalib/MHCalibrationChargePINDiode.cc
+     - return in Draw() if histogram is empty (otherwise segm. violation 
+       in eventloop
+
+   * msignal/MExtractedSignalCam.cc
+     - intialize variables by default to 0. 
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - pointer to fSig is not stored, somehow, when running MJCalibration
+       Don't know why. Removed and stored some variables instead
+
+   * mjobs/MJCalibration.[h,cc]
+     - updated documentation, updated QE Cam
+     - set the pulser colour (now obligatory)
+     - set the possibility to choose different displays
+ 
+   * mcalib/MCalibrationChargeCalc.cc
+     - set the pulser colour (now obligatory)
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - put GetRSigmaPerCharge into this class
+
+
+
+ 2004/04/13: Thomas Bretz
+
+   * mastro/MAstroCamera.cc, mastro/MAstroCatalog.[h,cc]:
+     - enhanced comments
+     - added some new features
+     
+   * mbase/MAGIC.h:
+     - removed some empty lines
+     
+   * mfileio/MWriteRootFile.cc:
+     - fixed a compiler warning
+     
+   * mgeom/MGeomCorsikaCT.h:
+     - removed obsolete include of TArrayF
+
+   * mgeom/MGeomMirror.[h,cc]:
+     - replaced fReflector by *fReflector
+
+   * mmain/MGDisplayAdc.cc:
+     - fixed a bug which caused the wrong histogram entry to be
+       displayed
+
+
+
+ 2004/04/10: Markus Gaug
+  
+   * macros/dohtml.C
+     - included directory mjobs
+
+   * mjobs/MJCalibration.[h,cc]
+     - added and updated documentation (not yet ready)
+
+   * htmldoc/images/CalibClasses.gif
+     - scheme of the calibration classes, used for documentation in 
+       MJCalibration.cc
+
+
+
+ 2004/04/10: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc], mastro/MAstroCamera.[h,cc]:
+     - added comments
+
+   * macros/starfield.C:
+     - added
+
+   * mastro/Makefile, mastro/AstroLinkDef.h
+     - added MAstroCamera
+
+
+
+ 2004/04/09: Markus Gaug
+
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]	
+   * mcalib/MHCalibrationChargeCam.[h,cc]	
+   * mcalib/MHCalibrationChargeCalc.[h,cc]	
+     - put abs. time consistency check from MCalibrationChargeCalc into 
+       MHCalibrationChargePINDiode and MHCalibrationChargeCam
+
+   * mcalib/MHCalibrationCam.[h,cc]	
+   * mcalib/MHCalibrationChargeCalc.[h,cc]	
+     - number of used FADC slices also stored in MHCalibrationCam, 
+       MHCalibrationChargeCalc needs no pointer to the signal extractors
+       any more -> removed
+
+   * mcalib/MCalibrationChargePINDiode.[h,cc]	
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]	
+   * mcalib/MCalibrationCam.[h,cc]	
+     - put a default pulser color kNONE
+
+   * manalysis/MPedestalCam.[h,cc]
+   * manalysis/MPedCalcPedRun.[h,cc]
+   * manalysis/MGeomApply.cc
+     - added average pixels in the way like it is done in MCalibrationCam
+
+
+
+ 2004/04/08: Thomas Bretz
+
+   * mfbase/MF.cc:
+     - optimized output
+
+   * mfbase/MFilterList.cc:
+     - added some comments
+
+   * mfileio/MReadMarsFile.[h,cc], mfileio/MReadTree.[h,cc]:
+     - added SortFiled-option -- RAQUEL, this is for you!
+
+   * mfileio/MWriteRootFile.cc:
+     - class AddSerialNumber in AddContainer
+
+   * mhist/MHFalseSource.[h,cc]:
+     - optimized setting of hist maximum
+     - added more source dependant cuts
+     - changed display layout
+     - scale number of entries to correct for different acceptance
+       (not perfect, but the best I can currently do)
+
+   * mimage/MHHillasExt.[h,cc]:
+     - added new histogram for fMaxDist
+
+   * mimage/MHNewImagePar.[h,cc]:
+     - added new histograms for Used/CoreArea
+
+   * mimage/MHillasCalc.cc:
+     - optimized output
+
+   * mimage/MHillasExt.cc:
+     - fMaxDist got a sign
+
+   * mimage/MNewImagePar.[h,cc]:
+     - enhanced comments
+     - added new Print() member function
+
+   * macros/readCT1.C, macros/readMagic.C, mmain/MEventDisplay.cc:
+     - forward geomcam to newimgepar.Print()
+
+
+
+ 2004/04/08: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+   * mcalib/MCalibrationChargeCam.[h,cc]
+   * mcalib/MCalibrationChargePix.[h,cc]
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - put calculation of photon fluxes with the three methods into 
+       MCalibrationChargeCalc
+     - reorganized calculations in a better readable way (hopefully!)
+
+   * mbase/MAGIC.h
+   * mcalib/MCalibrationCam.[h,cc]
+   * mcalib/MCalibrationQECam.[h,cc]
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - put PulserColor_t away from MAGIC.h into MCalibrationCam
+     - full implementation of the QE-calibration from MCalibrationQEPix
+
+   * msignal/MExtractBlindPixel.cc
+     - removed warning about low-gain saturation of Blind pixel
+
+   * mcalib/MCalibrate.[h,cc]
+   * mcalib/MCalibrateData.[h,cc]
+   * mcalib/MMcCalibrationCalc.[h,cc]
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - conversion factors now separated into FADC2phe and then into 
+       call to average Quantum efficiency. 
+
+
+ 2004/04/07: Markus Gaug
+
+   * mcalib/MHGausEvents.[h,cc]
+     - added fBlackout events
+
+
+
+ 2004/04/06: Thomas Bretz
+
+   * mcalib/MCalibrationCam.[h,cc]:
+     - simplified call to initialization by new function Init()
+
+   * mcalib/MH*.cc:
+     - fixed some warnings (comparision between signed and unsigned)
+
+   * manalysis/MGeomApply.cc:
+     - use new Init-funtion of MCalibrationCam
+
+   * mastro/MAstro.cc:
+     - some fixes to the conversion functions
+
+   * mastro/MAstroCamera.[h,cc]:
+     - added comments
+     - changed argument type of AddPrimitives
+     
+   * mastro/MAstroCatalog.[h,cc]:
+     - many changes to make it possible to overlay the
+       catalog on top of a 2D histogram
+     
+   * mbase/MEvtLoop.cc:
+     - fixed estimation of run-time
+
+   * mbase/MMath.[h,cc]:
+     - added member functions for signed significances
+
+   * mbase/MParContainer.cc:
+     - changed GetterMethod() to support double reference data mebers
+
+   * mbase/MStatusDisplay.cc:
+     - removed some obsolete debug outputs
+
+   * mbase/MTask.[h,cc]:
+     - removed fNumExecutions, fStopwatch already counts the calls
+     - slight chagnes to output of PrintStatistics
+
+   * mbase/MTaskList.[h,cc]:
+     - slight chagnes to output of PrintStatistics
+     
+   * mbase/MTime.cc:
+     - removed +TwoPi from GetGmst
+
+   * mcamera/MCameraAUX.h, mcamera/MCameraHV.h, mcamera/MCameraLV.h,
+     mcamera/MCameraLid.h, mcamera/MCameraLids.h,
+     mcamera/MCameraPowerSupply.h:
+     - added missing Getter functions
+
+   * mcamera/MCameraHV.h:
+     - removed obsolete data-meber fMean
+
+   * mdata/DataLinkDef.h:
+     - added MDataFormula
+
+   * mdata/MDataChain.cc, mdata/Makefile:
+     - enhanced dosumentation
+     - implemented use of multi argument functions
+     - added ^-operator
+
+   * mdata/MDataList.[h,cc]:
+     - added ^-operator
+     - enhanced IsValid
+
+   * mfbase/MFilterList.cc:
+     - changed a warn-output to inf
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added getter returning index corresponding to XY
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added getter IsInside
+
+   * mhist/MHCamera.cc:
+     - Return 0 in GetMean if no entries
+
+   * mhist/MHFalseSource.[h,cc]:
+     - removed conversion stuff (mm/deg) 
+     - slight change to calculation of significance
+     - added dist-cuts
+     - added histogram showing number of entries
+     - added display of catalog
+
+   * mhist/MHStarMap.cc:
+     - added comment
+     
+   * mimage/MHillasExt.[h,cc]:
+     - changed class version to 3
+     - added new data-member fMaxDist
+     
+   * mimage/MNewImagePar.[h,cc]:
+     - added new data member fUsedArea and fCoreArea
+
+   * mmc/MMcConfigRunHeader.h:
+     - readded GetMirrors (WHY WAS IT GONE?)
+
+   * mpointing/MPointingPos.[h,cc]
+     - implemented Getter to get coordinates in rad
+     
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - fixed direction of rotation
+     - for the moment do use fTime
+
+
+
+ 2004/04/06: Markus Gaug
+ 
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - change names of the GetLoGain*() functions to 
+       GetConvertedLoGain*() for better clarity
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - updated and enlarged documentation
+
+   * mcalib/MHCalibrationChargeCam.cc
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - set the arrays by use of memset
+     - initialize TObjArrays with the Init-Function
+
+
+ 2004/04/05: Markus Gaug
+
+   * msignal/MExtractedSignalPINDiode.h
+     - new function GetLastUsedSlice()
+
+   * mcalib/MCalibrationChargeCalc.[h,cc],
+   * mcalib/MCalibrationChargeCam.cc:
+     - holds also pointers to MExtractedSignalPINDiode and 
+       MExtractedSignalBlindPixel and does the checks inside the task 
+       (instead of inside the containers)
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc],
+   * mcalib/MCalibrationChargePINDiode.[h,cc]:
+     - updated and enlarged documentation
+
+   * mcalib/MHCalibrationChargePINDiode.cc
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - rename Setter for fMeanVar from SetMeanErr() to SetMeanVar()
+     - rename arrays of fAverageSigmaErr to AverageSigmaVar
+
+   * mcalib/MCalibrationPix.[h,cc]
+   * mcalib/MCalibrationChargePix.[h,cc]
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - add Getters to the relative variance
+
+   * mcalib/MHGausEvents.[h,cc]
+   * mcalib/MCalibrationPix.[h,cc]
+   * mcalib/MHCalibrationCam.cc
+     - add to Pickup also Blackout events
+
+
+ 2004/04/05: Nadia Tonello
+
+   * mbadpixels/MBadPixelsTreat.cc
+     - In Unmap(): replaced SetPixelUnused with SetPixelUnmapped 
+
+
+
+ 2004/04/02: Markus Gaug
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationCam.[h,cc],
+     mcalib/MCalibrationQEPix.[h,cc], mcalib/MCalibrationQECam.[h,cc],
+     mcalib/MCalibrationRelTimeCam.[h,cc],
+     mcalib/MCalibrationRelTimePix.[h,cc]:
+     - updated and enlarged documentation
+
+   * mcalib/MHGausEvents.[h,cc], mcalib/MHPedestalPix.[h,cc],
+     mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationChargeHiGainPix.[h,cc],
+     mcalib/MHCalibrationChargeLoGainPix.[h,cc],
+     mcalib/MHCalibrationChargeBlindPix.[h,cc],
+     mcalib/MHCalibrationChargePINDiode.[h,cc]:
+     - put fPixId, fPickup, fPickupLimt, CountPickup(), RepeatFit() and 
+       ChangeHistId() into MHGausEvents (before in the derived classes)
+     - put fChargeNbins, fChargeFirst, fChargeLast, 
+
+   * mcalib/MHCalibrationRelTimePix.[h,cc]:
+     - put fRelTimeNbins, fRelTimeFirst, fRelTimeLast together 
+       into MHGausEvents as fNbins, fFirst and fLast
+
+   * mcalib/MHCalibrationRelTimePix.[h,cc]:
+     - remove Renormalization to time slices. Need to think about 
+       more direct way to implement
+
+   * mcalib/MHPedestalCam.[h,cc], mcalib/MHCalibrationCam.[h,cc],
+     mcalib/MHCalibrationChargeCam.[h,cc],
+     mcalib/MHCalibrationRelTimeCam.[h,cc]:
+     - put most of the functionality into the base class MHCalibrationCam
+     - derived classes overload the functions SetupHists, ReInitHists, 
+       FillHists, FinalizeHists and FinalizeBadPixels. 
+     - functions FitHiGainArrays, FitLoGainArrays, FitHiGainHists, 
+       FitLoGainHists and InitHists can be used from base class. 
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationRelTimePix.[h,cc]:
+     - put most of the functionality into the base class MCalibrationPix
+     - other two classes derive now from MCalibrationPix
+
+   * mcalib/MCalibrationCam.[h,cc], mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationRelTimeCam.[h,cc]:
+     - put most of the functionality into the base class MCalibrationCam
+     - other two classes derive now from MCalibrationCam
+     - calls to MCalibration*Cam[i] now have to cast!
+
+   * mcalib/MCalibrate.cc, mcalib/MCalibrateData.cc,
+   * mcalib/MMcCalibrateCalc.cc, manalysis/MMcCalibrationUpdate.cc,
+   * mcalib/MCalibrationChargeCalc.cc:
+     - cast calls to MCalibration*Cam[i]
+
+   * manalysis/MGeomApply.cc
+     - add initialization MCalibrationRelTimeCam
+     - add intialization of average pixels
+
+
+
+ 2004/04/02: Abelardo Moralejo
+
+   * msignal/MExtractSignal3.[h,cc]
+     - added. Alternative method for signal extraction. Uses sliding 
+       window from event to event, but a common window for all pixels 
+       in an event.
+
+   * msignal/Makefile, SignalLinkDef.h
+     - added MExtractSignal3.
+
+
+
+ 2004/04/02: Markus Gaug
+
+   * mbadpixels/MBadPixelsPix.h
+     - added kRelTimeNotFitted and kRelTimeOscillating to Calibration_t 
+       enum
+ 
+   * mcalib/MCalibrationCam.[h,cc], mcalib/MCalibrationPix.[h,cc],
+     mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - two new base classes for general calibration storage containers,
+       contain average pixel storage functionality
+
+   * mcalib/MCalibrationRelTimeCam.[h,cc],
+     mcalib/MCalibrationRelTimePix.[h,cc]:
+     - new storage container for the rel. time calibration results, derive
+       from MCalibrationPix, MCalibrationCam
+
+
+
+ 2004/04/01: Markus Gaug
+
+   * msignal/MArrivalTimeCalc.[h,cc]
+     - set fSaturationLimit as a variable with default (instead of 0xff)
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargeCalc.cc, manalysis/MGeomApply.cc:
+     - add average pixels per sector
+
+   * mcalib/MHGausEvents.[h,cc], mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationRelTimePix.[h,cc]:
+     - moved BypassFit() function to MHGausEvents
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]:
+     - updated and enlarged documentation
+     - derives now from mcalib/MHCalibrationCam
+
+   * mcalib/MCalibrationChargePix.[h,cc]:
+     - removed flag kLoGainSaturation, because it is already in MBadPixelsPix
+
+   * mcalib/MCalibrationCam.[h,cc], mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - new base class for all MHCalibration*Cam object, contains the average
+       pixel functionality
+
+
+
+ 2004/03/31: Markus Gaug
+
+   * mcalib/MHCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCalc.cc, manalysis/MGeomApply.cc:
+     - make the average pixel independent on camera geometry, i.e.
+       one average pixel per MGeomPix::Aidx
+
+
+
+ 2004/03/31: Abelardo Moralejo
+
+   * mmc/MMcConfigRunHeader.[h,cc]
+     - updated to current version (3) in camera program. Added member
+       fLightCollectionFactorOuter so that we can store the data on 
+       the simulatedlight collection efficiency (light guides + 
+       plexiglas +...) as a function of incidence angle for outer and 
+       inner pixels independently. Added getters for this information
+       on light collection efficiency.
+
+
+
+ 2004/03/30: Markus Gaug
+ 
+   * mcalib/MHGausEvents.[h,cc],
+     mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationChargeHiGainPix.[h,cc],
+     mcalib/MHCalibrationChargeLoGainPix.[h,cc],
+     mcalib/MHCalibrationChargeBlindPix.[h,cc],
+     mcalib/MHCalibrationChargePINDiode.[h,cc],
+     mcalib/MHCalibrationRelTimeCam.[h,cc],
+     mcalib/MHCalibrationRelTimePix.[h,cc],
+     mcalib/MHPedestalPix.[h,cc],
+     mcalib/MHPedestalCam.[h,cc]:
+     - updated and enlarged documentation
+
+
+
+ 2004/03/30: Abelardo Moralejo
+
+   * mmc/MMcFadcHeader.hxx
+     - updated to current version (4) in camera program.
+
+
+
+ 2004/03/29: Markus Gaug
+  
+   * manalysis/MSourcePosFromStarPos.cc
+     - replaced fabs(ival) by TMath::Abs(ival)
+
+   * mbadpixels/MBadPixelsPix.h
+     - adopt treatment of UnCalibrated_t like the one in Unsuitable_t 
+
+   * mbadpixels/MBadPixelsPix.cc
+     - put some documentation in the header
+
+   * mcalib/MHCalibrationChargeCam.cc
+     mcalib/MCalibrationChargeCam.cc
+     mbadpixels/MBadPixelsCam.cc
+     - adopt to new style in MBadPixelsPix.h
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     mcalib/MCalibrationChargePix.[h,cc]
+     - move consistency checks from Pix to Calc
+
+   * mcalib/MHGausEvents.[h,cc]
+     - fixed axes for event and fourier spectrum Draw
+
+   * mcalib/MHCalibrationChargePix.[h,cc] 
+     mcalib/MHCalibrationChargeCam.[h,cc] 
+     - moved definition of pulser frequency to MHCalibrationChargeCam
+
+
+
+ 2004/03/24: Thomas Bretz
+
+   * mbase/MMath.cc:
+     - now SignificanceLiMa returns 0 in case sum==0
+
+
+
+ 2004/03/23: Thomas Bretz
+
+   * mbase/MContinue.cc, mhbase/MH.cc:
+     - changed a warning message to an inf-message
+
+   * mfileio/MReadTree.cc:
+     - added an additional logging message when adding files to a
+       chain successfully.
+
+   * mbase/MProgressBar.cc:
+     - fixed initial size
+
+   * mastro/MAstro.[h,cc]:
+     - changed the code for the rotation angle back to its original
+       shape. The definition I tried to introduced was already
+       correctly implemented (assuming that sin is the x-component
+       of the vector I had it wrong in my mind twice, using
+       atan2(y,x) everywhere I did recognize it...)
+
+   * mreport/MReport.cc:
+     - fixed a bug which caused a crash when the time is not valid
+
+   * mhist/MHStarMap.cc, mpointing/MSrcPosCalc.cc:
+     - fixed: v.Roatete() must be v=v.Rotate()
+     - MHStarMap no waorks also without MSrcPosCam, MPointingPos
+       or MObservatory (leaving out the corresponding translations)
+
+
+
+ 2004/03/22: Markus Gaug
+
+   * mfileio/Makefile, mimage/Makefile
+     - mpointing included
+
+
+
+ 2004/03/22: Thomas Bretz
+ 
+   * mpointing/MSrcPosCalc.[h,cc], MSrcPosCam.[h,cc]: 
+     - added
+     
+   * mastro/MAstro.[h,cc]:
+     - added code to calculate rotationangle previously in MObservatory
+     - changed definition of rotation angle such, that it is now 
+       180deg if Ra and Az grid is parallel
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - fixes and enhancements to the display (such as misscalculated
+       number of grid lines, title display, etc)
+     - enhancements to the output
+     - generalized creation of grid - for further usage
+
+   * mastro/MAstroSky2Local.[h,cc]:
+     - replaced calculation of rotation angle by the function in
+       MAstro
+
+   * mastro/MObservatory.[h,cc]:
+     - small changes to Print output
+     - moved code for calculation of rotation angle to MAstro
+
+   * mbase/MEvtLoop.cc:
+     - do not output number of events per second if no events processed
+     
+   * mbase/MParList.cc:
+     - updated some comments
+     
+   * mfileio/MCT1ReadAscii.cc, mfileio/MCT1ReadPreProc.cc,
+     mfileio/MReadRflFile.cc, mraw/MRawFileRead.cc,
+     mreport/MReportFileRead.cc:
+     - output error string if file cannot be opened
+     
+   * mfileio/MReadTree.cc:
+     - output name of chain which is scanned
+
+   * mimage/MConcentration.cc:
+     - replaced loop by iterator
+     - removed obsolete (unused) variables
+     
+   * mimage/MHNewImagePar.[h,cc]:
+     - fixed display colors
+
+   * mpointing/MPointingPos.[h,cc]:
+     - added member function to calculate rotation angle
+     - added comments
+
+   * mpointing/Makefile:
+     - added include MAstro
+
+   * manalysis/MSrcPosCam.[h,cc]:
+     - moved to mpointing
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - added: Derotates a star in the camera into MSrcPosCam
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - added MSrcPosCam
+     - added MSrcPosCalc
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MSrcPosCam
+
+   * mmain/Makefile:
+     - added include for mpointing
+
+   * manalysis/AnalysisIncl.h:
+     - removed TVector2
+
+   * mbase/MParContainer.h:
+     - added new abstract virtual member function SetVariables
+       (to be used in fits)
+     - addeed some text to class description
+
+   * mdata/MData.cc:
+     - added comment
+     
+   * mdata/MDataArray.[h,cc], mdata/MDataElement.h,
+     mdata/MDataList.[h,cc], mdata/MDataMember.h,
+     mfbase/MFDataMember.[h,cc], mfbase/MFilterList.[h,cc]:
+     - added SetVariables
+
+   * mdata/MDataChain.[h,cc]:
+     - added support for indexed variables [i]
+     - added SetVariables
+
+   * mdata/MDataValue.[h,cc]: 
+     - added support for variable values (through SetVariables)
+     - added support for an index
+     - added SetVariables
+
+   * mfbase/MF.[h,cc]:
+     - removed support for {}. This case is now detected
+       automatically
+     - added SetVariables
+     - added support for expressiond like 
+       "MHillas.fLength<2*MHillas.fWidth"
+
+   * mfbase/MFDataChain.[h,cc]:
+     - added fCond data member
+     - addednew constructor to support fCond
+     - added support for new condition type
+     - adapted Print and GetRule
+
+   * mimage/MNewImagePar.[h,cc]:
+     - added some comments
+
+   * mhist/MHStarMap.[h,cc]: 
+     - fixed to use the correct MPointingPos instead of the
+       deprecated MMcEvt. Use MPointingPosCalc to copy the
+       pointing position from MMcEvt to MPointingPos
+
+   * mbase/MMath.[h,cc]:
+     - added, which currently only implements calculation of
+       significance and Li/Ma significance
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MMath
+
+
+
+ 2004/03/19: Markus Gaug
+
+   * mcalib/MHCalibrationChargePix.cc
+     - added some style to the default Draw in order to see the 
+       label and axis titles better
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - store and display more information on the average pxiels
+
+   * mcalib/MCalibrationCam.cc
+     - the GetPixelContent flag were not correct any more, fixed them 
+       
+   * macros/calibration.C
+     - fixed GetPixelContent flags
+     - draw radial profile of the variables
+
+   * mjobs/MJCalibration.cc
+     - fixed GetPixelContent flags
+     - introduced RadialProfile for some displays
+     - removed some not so important displays
+
+   * manalysis/MGeomApply.cc
+     - included MCalibrationQECam to be initialized
+
+   * mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationQEPix.[h,cc]:
+     - replace DefinePixId by SetPixId
+   
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added MCalibrationQECam
+     - cleaned the code up a little
+     - give more information at the end
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - took out fNumLoGainSampels whihc is not needed any more because 
+       conversion is only done in the getters
+     - Canceled function ApplyLoGainConversion (for same reason)
+
+   * msignal/MExtractSignal2.cc
+     - remove uncommented piece of code
+
+   * msignal/MExtractSignal.cc, msignal/MExtractSignal2.cc:
+     - remove warning about pixel with low gain saturation, 
+       now in MBadPixelsPix
+
+   * mbadpixels/MBadPixelsPix.[h,cc], mcalib/MCalibrationChargeCam.cc:
+     - added new flag: kDeviatingNumPhes
+
+   * mcalib/MCalibrationChargePix.cc
+     - check for mean arr. time in last bin replaced by check in last 
+       two bins
+
+   * mcalib/MCalibrationChargePix.[h,cc], 
+     mcalib/MCalibrationChargeCam.cc,
+     mcalib/MHCalibrationChargeCam.cc:
+     - removed flag kHiGainFitted, kLoGainFitted, since they are
+       available from MBadPixelsPix
+
+   * macros/calibration.C, macros/calibrate_data.C
+     - a few flags from MCalibrationChargeCam::GetPixelContent were wrong, 
+       corrected them
+
+
+
+ 2004/03/18: Raquel de los Reyes
+
+   * macros/DAQDataCheck.C
+     - macro to check the data from the DAQ system (.raw files).
+
+
+
+ 2004/03/18: Thomas Bretz
+ 
+   * manalysis/AnalysisIncl.h:
+     - added TVector2
+
+   * manalysis/MSrcPosCam.[h,cc]:
+     - added Getter/Setter using TVector2
+
+   * mhbase/MH.cc:
+     - fixed GetMinimumGT for TH2 and TH3
+
+   * mpointing/MPointingPos.h:
+     - added Getter/Setter for Ra/Dec
+
+   * mpointing/MPointingPosCalc.cc:
+     - fill Ra/Dec into MPointingPos
+
+
+
+ 2004/03/18: Markus Gaug
+
+   * mgeom/MGeomCam.[h,cc]
+     - replace fMaxRadius by a TArrayF of pixel area types
+     - new TArrayF fMinRadius of each pixel area type
+     - backward compatibility should be given, 
+       call to GetMaxRadius() returns the value for the whole camera
+       (which corresponds to the previous value for the Magic camera)
+
+   * mimage/MConcentration.cc
+     - fixed on flog to fLog in order to compile
+
+
+
+ 2004/03/17: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - some simplifications and changes
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - some simplifications and changes
+
+   * mastro/MAstroSky2Local.[h,cc]:
+     - rotation matrix from sky to local coordinates
+     - added
+
+   * mastro/Makefile, mastro/AstroLinkDef.h:
+     - MAstroSky2Local added
+
+   * mraw/MRawEvtPixelIter.cc:
+     - GetIdxMaxLoGainSample(const Byte_t lofirst) const
+       accelerated and fixed (the first slice was compared to itself
+       and the last slice was not taken into account)
+
+   * manalysis/MCerPhotAnal2.cc:
+     - fixed a bug in the new treatment of lo-gains
+
+   * mhvstime/MHPixVsTime.cc:
+     - fixed missing initialization of fTypeErr in constructor
+
+   * mimage/MHillas.[h,cc]:
+     - implemented member function which returns MeanX/Y as TVector2
+
+   * mimage/ImageIncl.h:
+     - added TVector2
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - fixed a bug in AddPixels which - in some special circumstances -
+       cutted pixels with high pixel indices
+
+
+
+ 2004/03/17: Antonio Stamerra
+
+   * macros/datatrigcheck.C
+     - added macro for time and trigger data-checking
+
+
+
+ 2004/03/17: Abelardo Moralejo
+
+   * manalysis/MSourcePosfromStarPos.cc
+     - added cast fabs((Double_t)ival), line 703. Otherwise it does not
+       compile.
+
+   * macros/starmc.C
+     - added parameter accepted_fraction to select fraction of events 
+       to be processed (useful to make smaller outputs).
+
+
+
+ 2004/03/17: Wolfgang Wittek
+
+   * manalysis/MSigmabar.[h,cc]
+     - correct calculation of sector, which was wrong 
+
+
+
+ 2004/03/16: Markus Gaug
+ 
+   * mhist/MHCamera.[h,cc]
+     - added function RadialProfile which returns a TProfile of the 
+       value along the radius from the camera center
+
+
+
+ 2004/03/16: Oscar Blanch Bigas
+
+   * mimage/MConcentration.[h,cc]
+     - new class for Concentration stuff.
+     - It computes and stores Concentration 1-8
+
+   * mimage/MNewImagePar.[h,cc]
+     - New Concentration stuff is moved to MConcentration.
+
+   * mimage/MHillasCalc.[h,cc], Makefile, ImageLinkDef.h
+     - Modifications needed to support and compile new 
+       MConcentration class.
+
+
+
+ 2004/03/16: Thomas Bretz
+
+   * mjobs/MJ*.[h,cc]
+     - removed some obsolete comments
+     - removed projections from Directory (SetDirectory(0))
+
+
+
+ 2004/03/16: Wolfgang Wittek
+
+   * manalysis/MSigmabar.[h,cc]
+     - calculate sigmabar as mean of individual pedestalRMS
+       instead of            sqrt of mean pedestalRMS^2
+
+
+
+ 2004/03/16: Oscar Blanch
+
+   * mimage/MNewImagePar.[h,cc]
+     - New variables members added: fInnerSize, fInnerLeakage[1,2],
+       fConc[3-8].
+     - It is only ready for Magic Camera geometry. It has to be done
+       MGeomCam base.
+     - The version ahs not been updated since it was done on the 
+       2004/03/10 by Abelardo.
+
+
+
+ 2004/03/15: Markus Gaug 
+
+   * mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCalc.cc:
+   - conversion from hi- to logain now not applied until the value is 
+     exported outside the class. This is necessary for the error 
+     propagation in the F-Factor method: In the calculation of the 
+     number of Phe, the conversion factors cancel out and do not 
+     enlarge the errors 
+   - pixels with number of phe's outside the range defined by 
+     fPheFFactorRelErrLimit are not any more declared as: 
+     MCalibrationChargePix::IsFFactorMethodValid() == kFALSE , 
+     but instead as:
+     MBadPixelsPix::IsSuitableRun(MBadPixelsPix::kUnreliableRun) == kTRUE,
+     Like this, everybody is allowed to calibrate pixels which give 
+     no reasonable results in the calibration without bothering that
+     too many pixels fall out. Enjoy!
+   - In that procedure, the classes passed _internally_ from calculation
+     of sigmas to calculation of variances which saves all the useless 
+     square rooting.
+   - took out pointers to MCalibrationChargeBlindPix and 
+     MCalibrationChargePINDiode in MCalibrationChargeCam.
+
+
+
+ 2004/03/15: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - added getter function for fZFirstInteraction
+
+
+
+ 2004/03/15: Wolfgang Wittek
+
+   * mastro/MObservatory.[h,cc]
+     - remove bugs in RotationAngle(theta, phi, sin, cos)
+       replaced
+         cos = sinl + cosl*cosp /denom;
+       by
+         cos = (sinl - cosl*cosp) /denom;
+
+
+
+ 2004/03/15: Thomas Bretz
+
+   * mastro/MObservatory.[h,cc]:
+     - implemented RotationAngle(ra, dec, time)
+
+   * mbase/MTask.[h,cc]:
+     - implemented usage of a TStopwatch to retriev time consumtion
+       informations
+     - changed PrintStatistics not to print classes having no
+       Process() function
+
+   * mbase/MTaskList.[h,cc], mfileio/MReadReports.[h,cc]:
+     - changed PrintStatistics according to changes in MTask
+
+   * mraw/MRawEvtHeader.cc:
+     - added a comment to Fill member function
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added fLut.Set to FixSize and resize fLut by a factor of 2
+       instead of +1 which acelerates creation of all pixels a lot
+
+   * mbadpixels/MBadPixelsPix.cc:
+     - fixed a typo
+
+   * mfilter/MFSoftwareTrigger.cc:
+     - made statistics output meaning independant of usage of filter!
+
+   * mhbase/MFill.[h,cc]:
+     - added possibility to give tab a different name
+
+   * mhist/MHCamera.cc:
+     - fixed a bug when determin scale for same-option
+
+   * mjobs/MJCalibration.cc:
+     - changed tab names for MFillH
+
+   * mjobs/MJExtactSignal.cc:
+     - added MRawEvtHeader to output
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed displayed year
+     - read and store MStatusArray to and from files
+
+   * mfileio/MReadTree.cc:
+     - enhanced output
+
+   * mmain/MCameraDisplay.cc, mmain/MEventDisplay.[h,cc]:
+     - added preliminary mode to display F1/F2/F3-files
+
+   * mbase/MStatusArray.[h,cc]:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MStatusArray
+
+   * mhits/MHCamera.[h,cc], mgui/MHexagon.[h,cc]:
+     - improved drawing MHCamera with 'same' option
+
+
+
+ 2004/03/13: Markus Gaug 
+
+   * mcalib/MCalibrationChargeCalc.cc, mcalib/MCalibrationChargeCam.cc,
+     mcalib/MCalibrationChargePix.[h,cc], 
+     mcalib/MHCalibrationChargeCam.cc,
+     mcalib/MHCalibrationChargeLoGainPix.cc:
+     - fixed Low Gain calibration
+
+   * mcalib/MHGausEvents.cc:
+     - changed default fit prob. limit from 0.005 to 0.001
+
+   * mbadpixels/MBadPixelsPix.h :
+     - IsCalibrationResultOK does not ask for FitOK any more
+
+   * mcalib/MHCalibrationChargeCam.cc:
+     - replaced Rel. Err. Limit for outliers in Phe's from 5 sigma to 7
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - function GetIdxMaxLoGainSamples can be called optionally with 
+       offset (because first "loGain" samples are often in reality 
+       hiGain with high values.
+
+
+
+ 2004/03/12: Sebastian Raducci
+
+   * manalysis/Makefile
+     - added mastro in the include directories
+
+
+
+ 2004/03/12: Thomas Bretz
+
+   * merpp.cc:
+     - added 'force' option
+
+   * manalysis/MCerPhotAnal2.cc:
+     - extract pedestal and pedestal rms from lo-gain if hi-gain not
+       above a certain athreshold 
+
+   * mastro/MAstroCatalog.[h,c]:
+     - added text argument to DrawStar
+
+   * mbase/MStatusDisplay.cc:
+     - some small changes to output of SaveAsPS
+
+   * mfilter/MFCosmics.cc:
+     - changed output of filter statistics
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - fixed some problems with the code - now it should work like
+       expected
+     - added a new member function to be able to change the number
+       of required neighbors
+
+
+
+ 2004/03/12: Wolfgang Wittek
+
+   * manalysis/Makefile
+     - include 'mastro'
+
+   * manalysis/MSourcePosfromStarPos.[h,cc]
+     - include MObservatory.h
+     - call member function Rotationangle() of MObservatory
+
+
+
+ 2004/03/12: Markus Gaug
+
+   * mjobs/MJCalibration.cc
+     - updated call in displays to the corr. Cams.
+
+   * macros/calibrate_data.C
+     - macro to study calibrate and study data used in Munich and IFAE
+
+
+
+ 2004/03/12: Antonio Stamerra
+
+   * mraw/MRawEvtHeader.[h,cc]
+     - Added the method GetTriggerID() to decode the trigger pattern.
+
+
+
+ 2004/03/11: Abelardo Moralejo
+
+   * mimage/MHillasCalc.cc
+     - Added some printout in PostProcess, to better express the reasons
+       for which the reconstruction of some events did not succeed.
+
+
+
+ 2004/03/11: Thomas Bretz
+
+   * status.cc:
+     - updated
+
+   * manalysis/MCerPhotAnal2.cc:
+     - removed an obsolete debug output
+
+   * mhist/MHCamera.[h,cc]:
+     - added same-option to camera display
+
+  * mbadpixels/MBadPixelsCalc.[h,cc], mbadpixels/MBadPixelsTreat.[h,cc]:
+     - implemented functionality of MBlindPixelsCalc2
+
+   * mbadpixels/MBadPixelsCam.[h,cc], mbadpixels/MBadPixelsPix.[h,cc],
+     mbadpixels/MMcBadPixelsSet.cc, mcalib/MCalibrationChargeCalc.cc,
+     mcalib/MCalibrationChargePix.cc, mcalib/MHCalibrationChargeCam.cc:
+     - replaced several Set/GetUnsuitable* by a single member function
+
+
+
+ 2004/03/11: Markus Gaug
+
+   * mbadpixels/MBadPixelsPix.h
+     - removed bits about validity of calibration methods
+     - IsCalibrationResultOK asks also from IsSuitableRun
+
+   * mbadpixels/MBadPixelsCam.cc
+     - updated GetPixelContent
+     - added Print function
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargePix.h, mcalib/MCalibrationChargeCalc.cc:
+     - removed pointers to MGeomCam and MBadPixelsCam in MCalibrationChargeCam
+     - use two loops over pixels in order to determine mean flux of phe;s to 
+       discard pixels far outside the normal distribution
+
+   * mcalib/MCalibrate.cc
+     - added case that no MBadPixelsCam is available.
+
+   * mcalib/MHCalibrationChargeCam.cc
+     - adapted to new MBadPixelsPix::SetUnsuitable function
+
+
+ 2004/03/10: Abelardo Moralejo
+
+   * manalysis/MCerPhotPix.[h,cc]
+     - Added member fIsHGSaturated, and setter/getter functions. 
+       Updated class version to 4.
+
+   * mcalib/MCalibrate.cc, MCalibrateData.cc
+     - Added setting of MCerPhotPix.fIsHGSaturated if one or more HG
+       slices saturate.
+
+   * mimage/MNewImagePar.[h,cc]
+     - Added member fNumHGSaturatedPixels to count the number of pixels 
+       in which high gain saturates. Added getter funciton for it. 
+       Updated class version to 3.
+
+
+
+ 2004/03/10: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc,
+     mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc]:
+     - calculation of conversion factor with F-Factor method from 
+       same mean number of photons, derived from weighted mean number 
+       of photo-electrons from inner and outer pixels, respectively
+
+   * mjobs/MJPedestal.cc, mjobs/MJCalibration.cc, macros/calibration.C:
+     - fixed the projections (did only display inner pixels up to now)
+
+   * macros/calibration.C
+     - small bug fixed in display of rel. arrival times
+       ( used MArrivalTimeCam instead of MHCalibrationRelTimeCam)
+
+   * mbadpixels/MBadPixelsCam.cc
+     - replaced some InitSize(idx) by InitSize(idx+1) in order not to crash
+       to program when reading from an ascii-file.
+
+   * mbadpixels/MBadPixelsCalc.cc
+     - replaced one SetUnsuitableRun(....) by the new version without 
+       argument.
+
+
+
+ 2004/03/10: Thomas Bretz
+
+   * mfilter/MFSoftwareTrigger.[h,cc]:
+     - changed to support also a predifined number of NN
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - many enhancements
+     - many speed improvements
+
+   * mbadpixels/MBadPixelsPix.[h,cc]:
+     - fixed
+
+
+
+ 2004/03/10: Ester Aliu
+
+   * mtemp/MIslands.[h,cc]
+     - New MParContainer to hold information about islands
+       (number of islands, pixels in each Island, Signal/Noise of
+	each Island).
+
+   * mtemp/MIslandCalc.[h,cc]
+     - New MTask to count and characterize Islands.
+
+
+
+ 2004/03/09: Thomas Bretz
+
+   * Makefile.rules:
+     - replaced *.o by $(...) for building archives
+
+   * mjobs/MJCalibration.cc:
+     - exchanged  apply  and merge task
+
+   * mjobs/MJCalibration.h, mjobs/MJExtractSignal.h, mjobs/MJPedestal.h:
+     - fixed some const-qualifiers
+
+   * mcalib/MHCalibrationChargeBlindPix.cc, 
+     mcalib/MHCalibrationChargeCam.cc,
+     mcalib/MHCalibrationChargePINDiode.cc
+     - removed some obsolete output when calling FindCreateObj
+     - changed some 'not found' output messages to be 'Mars-compliant'
+     - replaced some gLog by *fLog
+
+
+
+ 2004/03/08: Markus Gaug
+   
+   * mbadpixels/MBadPixelsPix.h
+     - small modifications for better readability
+     - remove Getters for calibration methods
+     - added flag "UnReliableRun" in fInfo[0]
+
+   * mcalib/MHCalibrationChargeCam.cc, mcalib/MCalibrationChargePix.cc:
+     - fill MBadPixelsPix with UnReliableRun or UnSuitableRun when 
+       calibration does not succeed.
+
+   * mcalib/MCalibrationChargeCam.cc
+     - displaying saturation also for not-valid pixels in GetPixelContent
+
+   * msignal/MExtractedSignalCam.[h,cc], msignal/MExtractSignal.[h,cc],
+     msignal/MExtractSignal2.[h,cc], mananlysis/MHPedestalCam.cc,
+     mcalib/MCalibrationChargeCalc.[h,cc]:
+     - in SetUsedFADCSlices, also the window (hi-and logain) is set. 
+       This because MExtractSignal2 set the whole window which was much 
+       bigger than the actually used one. This bug is now removed.
+
+
+
+ 2004/03/08: Thomas Bretz
+
+   * merpp.cc:
+     - fixed a bug in the screen output
+
+   * mgeom/MGeomMirror.cc:
+     - added comment
+
+   * mmc/MMcConfigRunHeader.h:
+     - added member function GetMirrors
+
+
+
+ 2004/03/08: Abelardo Moralejo
+
+   * macros/starmc.C, starmcstereo.C, mccalibrate.C 
+      - adapted to m. Gaug's changes: now one MBadPixelsCam containers is 
+        added for each telescope to the parameter list.
+
+   * mmain/MEventDisplay.cc, Makefile
+     - added MBadPixelsCam to par list, and mbadpixels/ to includes.
+       Necessary due to changes in MCalibrate.
+
+
+
+ 2004/03/06: Markus Gaug
+
+   * macros/calibration.C
+     - adapted call to MHCamera::ProjectionS to the new version
+
+   * mcalib/Makefile
+     - include directory mbadpixels
+
+   * manalysis/Makefile
+     - include directory mbadpixels
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - include MBadPixelsCam
+     - remove exclusion of pixels from ascii-file
+       (now accessible from MBadPixelsCam)
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - include MBadPixelsCam
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - include MBadPixelsCam
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - include MBadPixelsCam
+     - include one additional MBadPixelsPix for the average inner and 
+       outer pixel, respectively
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+     - make fSaturated and fPickup a Float_t (for average pixel)
+
+   * mbadpixels/MBadPixelsPix.h
+     - include the CalibrationType_t infos
+     - exchange "SetUnsuitable" by "SetUnsuitableRun"
+
+   * mbadpixels/MBadPixelsCam.cc, mbadpixels/MMcBadPixelsSet.cc:
+     - exchange "SetUnsuitable" by "SetUnsuitableRun"
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - exchange "SetUnsuitable" by "SetUnsuitableEvt"
+
+   * manalysis/MGeomApply.cc
+     - remove obsolete MArrivalTime
+     - add MBadPixelsCam
+
+   * mcalib/MCalibrate.[h,cc], mcalib/MCalibrateData.[h,cc]
+     - implemented calls to MBadPixelsCam
+
+   * macros/calibration.C, macros/bootcampstandardanalysis.C,
+     macros/pedphotcalc.C
+     - implemented calls to MBadPixelsCam
+
+   * mjobs/MJCalibration.cc
+     - call to MBadPixelsCam
+
+
+
+ 2004/03/05: Nadia Tonello
+
+   * manalysis/MBlindPixelsCalc2.[h,cc], manalysis/AnalysisLinkDef.h,
+     manalysis/Makefile
+     - Temporary class added (will be included in mbadpixels/ soon)
+     - All the functions of MBlindPixelCalc are kept(with small improvements)
+     - New function added: SetCheckPedestalRms
+
+   * manalysis/MCerPhotPix.h
+     - Status Unmapped added (not include the pixel in the cleaned image)
+
+   * mimage/MImgCleanStd.cc 
+     - Checks for Unmapped status added 
+
+   * mastro/MAstroCatalog.cc, msql/MSQLServer.cc:
+     - include <stdlib.h> to solve compilation error
+
+
+
+ 2004/03/05: Sebastian Raducci
+
+   * msignal/MArrivalTimeCalc.cc
+     - fixed a little bug (exchanged a - with a + in the Calc() method)
+
+
+
+ 2004/03/05: Markus Gaug
+
+   * mcalib/MCalibraitonChargeCalc.cc
+     - remove some runheader line: 
+	if (runheader->IsMonteCarloRun())
+            return kTRUE;
+       which gave always true since this week, don't know why.
+     - added some information in class description
+
+
+
+ 2004/03/04: Sebastian Raducci
+  
+   * msignal/MArrivalTimeCalc.cc
+     - fixed a memory leak (the spline was not deleted...)
+
+
+
+ 2004/03/04: Thomas Bretz
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added new data member fNumAreas
+     - added new function CalcNumAreas
+     - increased class version to 3
+
+   * mgeom/MGeomCamMagic.cc:
+     - added setting of area index
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added fAidx data member
+     - added getter function fAidx
+     - increased class version to 3
+
+   * macros/sectorvstime.C:
+     - added example of how to plot the evolution of a sector vs time
+
+   * mhist/MHVsTime.[h,cc], mhist/MHPixVsTime.[h,cc]:
+     - moved to mhvstime
+
+   * mhvstime/MHSectorVsTime.[h,cc]:
+     - added
+
+   * Makefile:
+     - added mhvstime
+
+   * mhvstime/Makefile, mhvstime/HVsTimeLinkDef.h, 
+     mhvstime/HVsTimeIncl.h:
+     - added
+
+   * mhist/Makefile, mhist/HistLinkDef.h, 
+     - removed MHVsTime
+     - removed MHPixVsTime
+
+   * macros/rootlogon.C, macros/dohtml.C:
+     - added new directory mhvstime
+
+   * msignal/MExtractSignal.cc, msignal/MExtractSignal2.cc:
+     - changes such, that it doesn't crash if signal has no lo-gain
+       (This might still give wrong results!)
+
+   * macros/dohtml.C:
+     - added pixvstime.C
+     - added sectorvstime.C
+
+   * manalysis/MMcCalibrationUpdate.cc:
+     - some changes on file consistency check done by Abelardo,
+       he may comment on it
+
+   * mhist/MHCamera.[h,cc]:
+     - changed to support also dividing the camera in pixels area indices
+
+   * mhist/MHEvent.cc:
+     - minor change
+
+   * mjobs/MJPedestal.cc:
+     - adapted to changes in MHCamera
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - added preliminary catalog
+
+   * mastro/Makefile, mastro/AstroLinkDef.h:
+     - added MAstroCatalog
+
+
+
+ 2004/03/03: Thomas Bretz
+
+   * mgeom/MGeomCam.cc:
+     - give a name and title also if the default constructor is used
+
+   * mgeom/MGeomMirror.[h,cc]:
+     - added member function GetReflection
+     - added persistent data member fReflector
+
+   * mjobs/MJCalibration.cc, mjobs/MJExtractSignal.cc, mjobs/MJPedestal.cc:
+     - fixed a typo in the output
+
+   * mraw/MRawFileWrite.cc:
+     - added the missing '.' to MRawRunHeader. Because of the design of
+       MReadTree this is backward compatible
+
+   * mraw/MRawRunHeader.h:
+     - removed last change from Abelardo. '>255' is the correct 
+       check for MC files following the definition that all MC files
+       have run types >255 which was made in the past. 
+
+   * manalysis/MCerPhotAnal.[h,cc], manalysis/MCerPhotAnal2.[h,cc]:
+     - created ReInit member function to hold all code (moved from
+       PreProcess) accessing the run header. The run header is not
+       available in PreProcess. That it was working before was only
+       by chance, because the run type is initialized with 65535 which
+       is != 255 but not >255.
+
+
+
+ 2004/03/03: Sebastian Raducci
+
+   * msignal/MArrivalTimeCalc.cc
+     - The calculation of the arrival times is made only when needed
+       (when the HalfMax is over the pedestal)
+
+   * mtools/MCubicSpline.cc
+     - Commented out an annoying warn
+
+
+
+ 2004/03/03: Abelardo Moralejo
+
+   * mraw/MRawRunHeader.h
+     - Replaced
+         Bool_t IsMonteCarloRun() const { return fRunType>0x00ff; }  by
+         Bool_t IsMonteCarloRun() const { return (fRunType==0x0100); }
+     since the latter is the exact translation of what the function
+     intends to do. I do not know why, but the display of real data 
+     did not work with the upper line!
+
+   * mgeom/MGeomCam.cc
+     - Undid yesterday change! I do not know why, display completely 
+       fails after that change, both for old and new camera files. 
+       Put back fPixels[i] = new MGeomPix; in constructor.
+
+
+
+ 2004/03/02: Abelardo Moralejo
+
+   * mmc/MMcCorsikaRunHeader.[h,cc]
+     - Added operator [] to get references to the objects in 
+       TObjArray fTelescopes.
+     - Added Print() function.
+     - Added GetNumCT() function.
+     - Replaced
+          fTelescopes[i]= new MGeomCorsikaCT;   
+       by
+          MGeomCorsikaCT* dummy = new  MGeomCorsikaCT();
+          fTelescopes.Add(dummy);
+
+   * mgeom/MGeomCorsikaCT.[h,cc]
+     - Added getter functions for telescope coordinates.
+     - Added Print() function.
+
+   * mgeom/MGeomCam.cc  => NOTE: this change was undone later!
+     - Replaced
+          fPixels[i] = new MGeomPix;   
+       by
+          MGeomPix* dummy = new MGeomPix();
+          fPixels.Add(dummy);
+
+
+
+ 2004/03/02: Thomas Bretz
+
+   * mcalib/MCalibrateData.cc:
+     - removed usage of MGeomCam (you have MGeomApply for this!)
+
+
+
+ 2004/03/01: Nadia Tonello
+
+   * manalysis/MCerPhotEvt.cc
+     - TObject *MCerPhotEvtIter::Next() now returns Used pixels 
+	only if fUsedonly=kTRUE, otherwise it returns all the pixels 
+	in the array  
+ 
+
+
+ 2004/03/01: Sebastian Raducci
+
+   * msignal/MArrivalTimeCalc.[cc,h]
+     - now the arrival time is at the half max of the spline:
+       half max = (maximum - pedestal)/2
+   
+   * mmain/MEventDisplay.cc
+     - fixed an include (from MArrivalTime.h to MArrivalTimeCam.h)
+
+
+
+ 2004/03/01: Wolfgang Wittek
+  
+   * mhist/MHStarMap.[h,cc]
+     - remove bugs
+     - change GetRotationAngle() such that it can be called from outside
+
+
+
+ 2004/03/01: Thomas Bretz
+
+   * Makefile:
+     - enhanced all calls to subsequent makes by '-f Makefile' to
+       make sure the correct Makefile is called
+
+   * merpp.cc:
+     - enhanced interpretation of time
+     - fixed a bug in determin the file-type
+
+   * mbase/MTime.[h,cc]:
+     - added GetGmst() member function
+
+   * mastro/MAstro.[h,cc]:
+     - added Coordinate2Angle
+     - added AngularDistance
+     - implemented UT2GMST
+     - replaced defined by TMath::Pi()
+
+   * mastro/MObservatory.[h,cc]:
+     - added data members for sin-/cos-component of latitude
+     - added calculation of rotation angle
+
+   * mhist/MHStarMap.[h,cc]:
+     - changes to use MObservatory member function
+
+   * manalysis/MCerPhotAnal.cc, manalysis/MCerPhotAnal2.cc,
+     manalysis/MCerPhotCalc.cc, manalysis/MMcCalibrationUpdate.cc,
+     manalysis/MMcPedestalCopy.cc, manalysis/MMcPedestalNSBAdd.cc,
+     manalysis/MPedCalcPedRun.cc, manalysis/MPedPhotCalc.cc,
+     mcalib/MCalibrationChargeCalc.cc, mcalib/MMcCalibrationCalc.cc
+     - changed to use IsMonteCarloRun() now
+
+   * manalysis/MMcCalibrationUpdate.cc:
+     - unified output to log-stream
+     - replaced sqrt by TMath::Sqrt
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - unified output to log-stream
+     - removed .Data() from TString where obsolete
+     - fixed memory leak using gSystem->ExpandPathName
+
+   * mpointing/MPointingPosCalc.cc, mraw/MRawFileWrite.cc:
+     - adde class name to used kRT*/kTT* enums
+
+   * mraw/MRawEvtHeader.h:
+     - made enum data member of class
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - made kMagicNumber and kMaxFormatVersion a static data
+       member of the class
+     - added IsMonteCarloRun member function
+
+
+
+ 2004/02/27: Markus Gaug
+   
+   * mjobs/MJPedestal.cc, mjobs/MJCalibration.cc, macros/calibration.C:
+     - put in call to MHCamera::Projection the name of the calling 
+       class, otherwise the projected hsitogram will be overwritten by 
+       an empyt one.
+
+   * mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationHiGainChargePix.[h,cc],
+     mcalib/MHCalibrationLoGainChargePix.[h,cc]:
+     - histogram name setting and title setting moved to constructor, 
+       Functions Init and ChangeHistId derive directly from 
+       MHcalibrationChargePix
+
+   * mcalib/MHCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCalc.[h,cc]:
+     - introduced "average inner" and "average outer" higain and logain 
+       pixels.
+
+
+
+ 2004/02/27: Raducci Sebastian 
+
+   * mhist/Makefile
+     - added mastro in the include list
+
+
+
+ 2004/02/27: Abelardo Moralejo
+
+   * mmain/MEventDisplay.cc
+     - replaced in fill8 obsolete MArrivalTime with MArrivalTimeCam.
+     - Updated display of MC data: removed MCerPhotCalc, and replaced 
+       it by MExtractSignal+MMcCalibrationUpdate+MCalibrate. Now
+       MPedPhotCam is filled and all the camera display tabs are shown 
+       correctly (most were not working for MC events since a while 
+       ago).
+
+   * mmain/Makefile
+     - Added mcalib to list of include directories.
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Added member variable Bool_t fOuterPixelsScaling, which is 
+       kTRUE by default. If set to kFALSE, MCalibrationCam is filled 
+       such that MCerPhotEvt will later be filled with the signal as it 
+       is, not corrected for the (possibly) different gain of the outer 
+       pixels electronic chain. This option was necessary to allow for
+       the change in the camera display (see above).
+
+   * macros/starmc.C
+     - added (optional) division of output into two, for use as train 
+       and test samples in g/h separation studies.
+
+
+
+ 2004/02/26: Hendrik Bartko
+
+   * macros/dohtml.C
+     - included the path msignals/
+
+
+
+ 2004/02/26: Abelardo Moralejo
+
+   * macros/starmcstereo.C
+     - changed filters to divide data between train and test sample for
+       gamma hadron separation studies. Now we use the modulus operator
+       applied to (Corsika) event number:
+         MF filter1("{MMcEvt;1.fEvtNumber%2}<0.5");
+         MF filter2("{MMcEvt;1.fEvtNumber%2}>0.5");
+     - cleaned up a bit the way the CT coordinates are fed to the task
+       MStereoCalc.
+     - Changed default FADC integration range (center range to adapt to 
+       new camera).
+
+
+
+ 2004/02/26: Thomas Bretz
+
+   * mhist/MHCamera.cc:
+     - fixed a function description
+
+   * mreport/MReport.cc, mreport/MReportFileRead.cc:
+     - introduced return case -1
+
+   * Makefile.rules:
+     - remove all dependancy files when calling 'rmdep'
+
+   * mbase/MAGIC.h, mmc/MMcEvt.hxx:
+     - moved ParticleId_t to MMcEvt
+     - implemented MMcEvt::GetParticleName
+     - implemented MMcEvt::GetEnergyStr
+
+   * mfilter/MFGeomag.cc, mfilter/MFParticleId.cc, mhist/MHCompProb.cc,
+     mhist/MHEvent.cc, mhist/MHHadronness.cc, 
+     mmontecarlo/MMcTriggerRateCalc.cc, mranforest/MHRanForest.cc:
+     - fixed usage of ParticleId_t
+
+   * msignal/Makefile:
+     - removed obsolete includes
+
+   * mastro/Makefile, mastro/AstroLinkDef.h, mastro/MAstro.[h,cc],
+     mastro/MObservatory.[h,cc]:
+     - added
+
+   * mbase/MAstro.[h,cc]:
+     - removed
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - removed MAstro
+
+   * Makefile:
+     - added mastro
+     - added msql
+     - added mfbase
+
+   * mtemp/MObservatory.[h,cc], mtemp/MObservatoryLocation.[h,cc]:
+     - removed
+
+   * merpp.cc:
+     - added Sql support
+     
+   * mraw/MRawFileRead.h:
+     - added GetFileName
+
+   * msql/Makefile, msql/SqlLinkDef.h, msql/SqlIncl.h, 
+     MSQLServer.[h,cc], MSqlInsertRun.[h,cc]:
+     - added
+
+   * mfilter/MF.[h,cc], mfilter/MFDataChain.[h,cc], 
+     mfilter/MFDataMember.[h,cc], mfilter/MFEventSelector.[h,cc],
+     mfilter/MFEventSelector2.[h,cc], mfilter/MFRealTimePeriod.[h,cc]:
+       - moved to mfbase
+
+   * mfbase/Makefile, mfbase/FBaseLinkDef.h, mfbase/FBaseIncl.h:
+     - added
+
+   * merpp.cc:
+     - implemented control of gDebug (root debugging)
+
+   * mfileio/MWriteAsciiFile.[h,cc], mfileio/MWriteFile.[h,cc],
+     mfileio/MWriteRootFile.[h,cc]:
+     - implemented CheckAndWrite return value
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed updating already existing branches (eg concatenating report
+       files)
+
+   * macros/dohtml.C, macros/rootlogon.C:
+     - added mastro
+     - added mfbase
+     - added msql
+
+   * mraw/MRawEvtHeader.h:
+     - implemented GetNumTrigLvl1
+     - implemented GetNumTrigLvl2
+
+
+
+ 2004/02/25: Markus Gaug
+
+   * mcalib/MExtractBlindPixel.[h,cc],
+     mcalib/MExtractPINDiode.[h,cc],
+     mcalib/MExtractedSignalBlindPixel.[h,cc],
+     mcalib/MExtractedSignalPINDiode.[h,cc],
+     mcalib/Makefile, msignal/Makefile, mcalib/CalibLinkDef.h,
+     msignal/SignalLinkDef.h:
+     - moved blindpixel and PINdiode extractors to msignal
+
+
+   * mcalib/MCalibrationQECam.[h,cc], mcalib/MCalibrationQEPix.[h,cc]:
+     - two new classes to hold the quantum efficieny information of the 
+       calibration
+
+   * msignal/MArrivalTimeCalc.[h,cc]
+     - fill now MArrivalTimePix instead of MArrivalTime
+
+   * mcalib/MHCalibrationChargeCam.cc
+     - display only valid pixels for the corr. values in GetPixelContent
+
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - is now filled from MArrivalTimeCam instead of MArrivalTime
+
+   * macros/calibration.C
+     - divided into two macros: calibration.C using the MJPedestal
+       standard procedure and   pedestalstudies.C using the old
+       procedures
+    
+   * macros/pedestalstudies.C
+     - new macro containing the first previous part of calibration.C
+
+   * mcalib/MCalibrationChargeBlindPix.h,
+     mcalib/MCalibrationChargePINDiode.h, mbase/MAGIC.h,
+     mjobs/MJCalibration.cc:
+     - definition of PulserColot_t in MAGIC.h. 
+
+
+
+ 2004/02/25: Hendrik Bartko
+  
+   * macros/rootlogon.C
+     - set the include path also to msignals/
+
+   * manalysis/MExtractSignal.[h,cc], manalysis/MExtractSignal2.[h,cc],
+     manalysis/MExtractedSignalCam.[h,cc],
+     manalysis/MExtractedSignalPix.[h,cc],
+     manalysis/MArrivalTime.[h,cc], manalysis/MArrivalTimeCalc.[h,cc],
+     manalysis/MArrivalTimeCalc2.[h,cc]:
+     - removed
+     
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:			
+     - removed classes mentioned above
+
+   * msignal/MExtractSignal.[h,cc], msignal/MExtractSignal2.[h,cc],
+     msignal/MExtractedSignalCam.[h,cc],
+     msignal/MExtractedSignalPix.[h,cc],
+     msignal/MArrivalTime.[h,cc], msignal/MArrivalTimeCalc.[h,cc],
+     msignal/MArrivalTimeCalc2.[h,cc]:
+     - added
+
+   * msignal/Makefile, msignal/AnalysisLinkDef.h:			
+     - added classes mentioned above
+     
+   * mfilter/Makefile, mcalib/Makefile, mjobs/Makefile, mmain/Makefile:
+     - added include msignal
+    
+
+
+
+ 2004/02/25: Wolfgang Wittek
+  
+   * mcalib/MCalibrateData.[h,cc]
+     - initialize size for MPedPhotCam
+
+
+
+ 2004/02/24: Wolfgang Wittek
+
+   * manalysis/MSourcPosfromStarPos.[h,cc]
+     - change member function SetSourceAndStarPosition() to expect sky
+       coordinates in the standard units
+     - generalize to more than 1 star
+     - the class is not yet fully tested
+
+   * mfilter/MFSelBasic.[h,cc]
+     - change default values of cuts
+
+
+
+ 2004/02/24: Markus Gaug
+
+   * mjobs/MJCalibration.cc, macros/calibration.C,
+     macros/bootcampstandardanalysis.C, macros/pedphotcalc.C:
+     - added MCalibrationChargeBlindPix to plist
+     - added new filling of histograms with MFillH
+     - changed SetPulserColor to MCalibrationChargeBlindPix and 
+       MCalibrationChargePINDiode
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]:
+     - receives a pointer to MCalibrationChargePINDiode which is filled 
+       with the results and told to calculate the fluxes in the 
+       Finalize function
+     - is filled via MFillH from MExtractBlindPixel
+     - SetPulserColor directly in this class
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+     - new storage container of the blind pxiel resutls, replaces 
+       MCalibrationBlindPix
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]:
+     - does not fill the histograms any more, but does ony the 
+       calculations in the postprocess. No pointer to MExtractPINDidoe
+       or MExtractBlindPixel any more.
+
+   * mcalib/MCalibrationChargePix.cc
+     - discovered an error in the calculation of phe's in 
+       CalcFFactorMethod(). The average QE was applied twice. 
+       This error had been introduced on 13/02/04
+     - loosened criterium convFFactorRelErrLimit from 0.1 to 0.2
+     - CalcFFactor asks for IsChargeValid before calculating anything
+
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - added function SetFluxOutsidePlexiglassAvailable
+     - SetPulserColor directly in this class
+
+   * mcalib/MCalibrationChargeCam.cc
+     - removed function SetPulserColor from here 
+
+   * mcalib/MCalibrationPINDiode.[h,cc], mcalib/MHCalibrationConfig.h,
+     mcalib/MHCalibrationPINDiode.[h,cc],
+     mcalib/MCalibrationBlindPix.[h,cc],
+     mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - removed since obsolote 
+
+   * mcalib/MHCalibrationChargePix.cc
+     - make fPickup an Int_t
+
+   * mcalib/MCalibrate.cc
+     - test validity of every calibration method before retrieving
+       conversion factors
+
+   * mcalib/MHGausEvents.[h,cc]
+     - add possibility to set fit ranges in call to FitGaus
+     - make function CreateXaxis protected 
+
+
+
+ 2004/02/23: Markus Gaug
+
+   * mraw/MRawEvtPixelIter.h
+     - include GetNumHiGainSamples and GetNumLoGainSamples
+
+   * mcalib/MExtractedSignalBlindPixel.h, 
+     mcalib/MExtractBlindPixel.[h,cc]:
+     - included storage of pedestal
+
+   * mcalib/MHGausEvents.[h,cc]
+     - make the fit functions protected
+
+
+
+ 2004/02/22: Markus Gaug
+
+   * mfilter/MFCosmics.[h,cc]
+     - fMaxNumEmpty changed from absolute number to relative number of 
+       pixels
+
+   * mcalib/MHGausEvents.h
+     - remove the "->" from the pointers which are initialized only 
+       in certain cases. The streamer did not work in case that 
+       MFGausFit was left at the NULL pointer.
+
+
+
+ 2004/02/21: Markus Gaug
+
+   * manalysis/MExtractedSignalPix.[h,cc]
+     - changed variable fIsLoGainUsed to fLoGainUsed
+     - added function GetNumHiGainSaturated()
+
+
+ 2004/02/20: Markus Gaug
+
+   * mcalib/MHCalibrationChargeHiGainPix.[h,cc], mcalib/Makefile,
+     mcalib/MHCalibrationChargeLoGainPix.[h,cc],
+     mcalib/CalibLinkDef.h
+     - new class to replace MHCalibrationPixel, 
+       based on MHCalibrationChargePix
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargePix.[h,cc]
+     mcalib/MCalibrationChargePINDiode.[h,cc]
+     mcalib/MCalibrationCalc.[h,cc], mcalib/MCalibrationCam.[h,cc],
+     mcalib/MCalibrationPINDiode.[h,cc]:
+     - added the "charge" versions, remove the old ones. The histograms 
+       should be filled in the MH... versions independently of 
+       MCalibrationChargeCalc. This is fully realized for the PIN Didoe 
+       now and will later be so for the pixels and the blind pixel. 
+
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]
+     - receives a pointer to MCalibrationChargePINDiode which is filled 
+       with the results and told to calculate the fluxes in the 
+       Finalize function
+
+   * mcalib/MCalibrate.[h,cc], mcalib/MCalibrateData.[h,cc],
+     mcalib/MMcCalibrationCalc.[h,cc], mjobs/MJCalibration.[h,cc],
+     manalysis/MMcCalibrationUpdate.[h,cc],
+     mjobs/MJExtractSignal.[h,cc], manalysis/MGeomApply.cc,
+     mcalib/Makefile, mcalib/CalibLinkDef.h, macros/calibration.C,
+     macros/bootcampstandardanalysis.C,
+     macros/pedphotcalc.C:
+    - replace MCalibrationCam by MCalibrationChargeCam
+    - replace MCalibrationCalc by MCalibrationChargeCalc
+
+
+
+ 2004/02/19: Markus Gaug
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationCam.cc,
+     mcalib/MCalibrate.cc, mcalib/MCalibrateDate.cc,
+     manalysis/MMcCalibrationUpdate.cc:
+     - standardized naming of variables containing "Error", this also affected 
+       the calling functions MCalibrate, MMcCalibrationUpdate and MCalibrateData
+
+   * mcalib/MCalibrationCam.cc, mcalib/MCalibrationPix.cc,
+     mcalib/MCalibrationCalc.cc, mcalib/MCalibrate.cc,
+     mcalib/MCalibrateData.cc, mcalib/MCalibrationConfig.h:
+     - took out some configuration numbers and put them directly into 
+       the class
+     - remove completely MCalibrationConfig.h
+
+
+
+ 2004/02/19: Abelardo Moralejo
+
+   * mhist/MHEvent.[h,cc]:
+     - Changed names of Event "types" to make them more descriptive.
+       Former kEvtSignal is now called kEvtSignalDensity, and indicates
+       pixel content scaled by area. Added kEvtSignalRaw, which 
+       corresponds to pixel content (with no scaling) in whatever units
+       (this depends on how the MHEvent object is filled!). The default
+       constructor initializes type=kEvtSignalRaw.
+
+   * mmain/MEventDisplay.cc
+     - Changed filling of evt1 and evt2. Now they are filled with raw 
+       content of MCerPhotEvt. Since in MEventDisplay, MCerPhotEvt is
+       still filled uncalibrated (hence in ADC counts), this means that 
+       what will be now shown in Mars' camera display is now the signal 
+       in each pixel without scaling with pixel area. Given that the 
+       default flat fielding is such that equal light density 
+       corresponds to equal absolute signal (in ADC counts), this is 
+       more reasonable, and allows to check for instance how the 
+       relative pixel gains are adjusted by looking at calibration 
+       events. To be FIXED: there is however an "inconsistency" in 
+       MEventDisplay, and it is that MCerPhotEvt is still used to keep
+       uncalibrated signals. To be replaced by MExtractedSignalCam?
+
+
+
+ 2004/02/19: Thomas Bretz
+
+   * manalysis/MCerPhotEvt.h:
+     - added operator= to MCerPhotEvtIter -- is this correct?
+
+   * mhist/MHCamera.[h,cc]:
+     - added member function to calculate minimum content and 
+       maximum content for a single sector
+     - Added possibility to get a projection for a single sector.
+     - GetMinimum/GetMaximum now only takes used pixels into account
+       (you can request all pixels using a different member function)
+     - fixed projection (projection only took pixels with contents!=0
+       instead of 'used' pixels
+     - Don't call Sumw2() anymore for projection
+
+   * mjobs/MJPedestal.cc:
+     - added MPedestalCam to output again - MPedestalCam was fixed
+       yesterday
+     - Added Histograms for the two camera halves
+
+
+
+ 2004/02/18: Markus Gaug
+
+    * macros/calibration.C
+      - fixed a buggy display of the F-Factor method
+
+    * mcalib/MCalibrationCalc.cc
+      - calculate the F-Factor method already in the post-Process
+
+    * mcalib/MCalibrationPix.h
+      - move CalcFFactorMethod to public
+
+
+
+ 2004/02/18: Abelardo Moralejo
+
+    * mtools/MCubicSpline.cc
+      - in Init, corrected initialization of arrays temp and ysd, which
+	was done with n-1 elements instead of n.
+
+    * mgui/MHexagon.cc
+      - added comment explaining the algorithm.
+      - changed explicit values of Sin and Cos 60 degrees by const
+	variables (more readable).
+
+
+
+ 2004/02/18: Hendrik Bartko
+
+   * msignal/:
+     - removed the backup files *~
+     - removed the object files *.o
+     - removed the files SignalCint.*
+
+    * mgui/MHexagon.cc
+      - added comment explaining the algorithm.
+
+
+
+ 2004/02/18: Thomas Bretz
+
+   * manalysis/MPedestalCam.[h,cc]:
+     - Changed order of derivements - seems to be VERY important!
+     - changed GetSize from UInt_t to Int_t which is the type
+       of TClonesArray::GetSize() !
+
+   * mfileio/MReadReports.cc:
+     - skip trees with no entries
+
+   * mgui/MCamEvent.cc:
+     - added a comment
+
+   * mhbase/MFillH.cc:
+     - in case SetupFill returns kFALSE and kCanSkip is set
+       Skip task
+
+   * mraw/MRawFileRead.cc:
+     - don't print warning in case of none executions
+
+   * manalysis/MArrivalTimeCalc2.cc:
+     - added some const-qualifiers
+
+
+
+ 2004/02/17: Raquel de los Reyes
+
+   * macros/CCDataCheck.C
+     - Added some improvements in the plots.
+
+
+
+ 2004/02/17: Abelardo Moralejo
+
+   * macros/readrfl.C
+     - Added missing gPad->cd(1), otherwise the display of events was
+       not updated.
+
+   * mgui/MHexagon.cc
+     - DistanceToPrimitive(Float_t px, Float_t py) Changed check of
+       whether px,py is inside the pixel or not. Previous algorithm 
+       was just an approximation.
+
+
+
+ 2004/02/17: Raquel de los Reyes
+
+   * mcamera/MCameraHV.h
+     - Now it derives from a MCamEvent class and implemented the
+       GetPixContent() and DrawPixelContent() functions. Added the 
+       GetMean function to get the mean HV settings of the camera.
+
+   * macros/CCDataCheck.C
+     - Added the HV settings plots.
+
+
+
+ 2004/02/17: Hendrik Bartko
+
+   * msignal:
+     - new: directory for all signal and time extraction classes
+
+   * msignal/MArrivalTimeCam.[h,cc], manalysis/Makefile, 
+     msignal/AnalysisLinkDef.h, MGeomApply.cc:
+     - new: Storage Container for the ArrivalTime in the camera
+   
+   * msignal/MArrivalTimePix.[h,cc], manalysis/Makefile, 
+     msignal/AnalysisLinkDef.h:
+     - new: Storage Container for ArrivalTime information of one pixel
+
+   * msignal/Makefile, SignalCint.[h,cc], SignalDep.d, SignalIncl.h, 
+     SignalLinkDef.h
+     - auxiliary files for msignal directory
+
+   * manalysis/MArrivalTimeCalc2.[h,cc]:
+     - added functionality to compute error of the extracted ArrivalTime
+     - calculated ArrivalTime is stored in MArrivalTimeCam
+
+   * manalysis/MGeomApply.cc
+     - geometry is applied to MArrivalTimeCam
+
+   * Makefile:
+     - directory msignal is included
+
+
+
+ 2004/02/17: Sebastian Raducci
+
+  * mtools/MCubicSpline.[h,cc]
+    - little corrections in minimums evalustion methods
+    - changed constructors (they require the fadc slices to be const)
+
+  * macros/spline.C
+    - changed according to the MCubicSpline new constructors 
+
+  * manalysis/MArrivalTimeCalc.[h,cc]
+    - changed to use the MCubicSpline class intead of the TSpline class
+    - warning: now the arrival time is again the maximum of the spline,
+      soon it will be changed to half maximum
+
+
+
+ 2004/02/17: Wolfgang Wittek
+
+  * manalysis/MSourcPosfromStarPos.[h,cc]
+    - new class; calculates the position of the source in the camera from
+                 the position of a star in the camera and puts it into
+                 MSrcPosCam
+
+
+
+ 2004/02/16: Abelardo Moralejo
+
+   * mcalib/MMcCalibrationCalc.cc
+     - Fixed two typos in screen output.
+
+
+
+ 2004/02/16: Markus Gaug
+
+   * mcalib/MCalibrationPix.cc
+     - documentation from David's email added
+     - EffectiveQE decreased from 0.2 to 0.18 (see documentation)
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - added MExtractBlindPixel and MExtractedSignalBlindPixel
+
+   * mcalib/MExtractBlindPixel.[h,cc]
+     - new signal extractor for the Blind Pixel
+
+   * mcalib/MExtractedSignalBlindPixel.[h,cc]
+     - new container for the extracted signal of the BlindPixel
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - does not extract signal from Blind Pixel any more, searches 
+       for MExtractedSignalBlindPixel and fills the hists from there
+  
+   * macros/calibration.C, macros/bootcampstandardanalysis.C,
+     macros/pedphotcalc.C, mjobs/MJCalibration.cc:
+     - introduce the blind pixel and PIN diode extraction in the macro
+
+   * manalysis/MPedestalCam.h 
+     - changed type of fTotalEntries from ULong_t to UInt_t 
+     - fixed documentation of fTotalEntries
+
+   * manalysis/MPedCalcPedRun.h 
+     - changed type of fNumSamplesTot from ULong_t to UInt_t 
+
+   * mcalib/MHGausEvents.h
+     - changed type of fCurrentSize from ULong_t to UInt_t 
+    
+   * mcalib/MCalibrationConfig.h
+     - removed gkConversionHiLo and gkConversionHiLoErr which is now
+       directly in the class MCalibrationPix 
+
+
+
+ 2004/02/16: Thomas Bretz
+
+   * manalysis/AnalysisLinkDef.h:
+     - added missing MCerPhotEvtIter
+
+   * merpp.cc:
+     - added possible usage of database
+
+   * star.cc:
+     - moved source code into new class MJStar - preliminary
+
+   * manalysis/MCerPhotPix.cc:
+     - updated class header
+     - fixed Print-output
+
+   * mbase/MAGIC.h:
+     - removed definition of MLog
+
+   * mbase/MArgs.h:
+     - removed include of MAGIC.h
+
+   * mbase/MLog.h:
+     - added extern definition of gLog
+
+   * mbase/MParContainer.[h,cc]:
+     - move body of constructors to source file
+
+   * mcalib/MCalibrate.cc, mcalib/MCalibrateData.cc,
+     mraw/MRawCrateArray.cc, mraw/MRawCrateData.cc,
+     mraw/MRawEvtData.cc, mraw/MRawEvtHeader.cc, mraw/MRawRead.cc,
+     mraw/MRawEvtPixelIter.cc, mraw/MRawFileWrite.cc:
+     - fixed documentation header
+
+   * mcalib/MMcCalibrationCalc.[h,cc]:
+     - fixed documentation header
+     - fixed usage of FindCreateObj and FindObject
+     - removed data member to count entries (use histogram instead)
+     - use TH1 function Integral instead of doing it manually
+
+   * mfilter/MFCosmics.cc:
+     - fixed documentation
+
+   * mimage/MHillas.cc, mimage/MImgCleanStd.cc,
+     mimage/MNewImagePar.[h,cc]:
+     - replaced for-loops by Iterators
+
+   * mraw/MRawFileRead.cc, mraw/MRawSocketRead.cc:
+     - fixed documentation header
+     - check return value of MRawRunHeader::ReadEvt
+
+   * mraw/mraw/MRawRunHeader.[h,cc]:
+     - fixed documentation header
+     - added return value to MRawRunHeader::ReadEvt
+     - added constant number for max format version - preliminary 
+       (should by a static data member)
+
+   * mcalib/MHCalibrationPINDiode.cc:
+     - do not delete pointers in the destructor which are already
+       deleted in the base class
+     - reset histograms in Clear()
+
+   * mcalib/MHCalibrationPixel.cc:
+     - after deletion of instances in Clear() initialize pointer to NULL
+
+   * mcalib/MCalibrationCalc.cc, mcalib/MHCalibrationBlindPixel.cc:
+     - fixed usage of logging stream output levels
+
+   * manalysis/MPedCalcPedRun.[h,cc]:
+     - removed obsolete fSignals
+
+     - removed obsolete fNumPixels
+
+   * manalysis/MPedestalCam.h:
+     - added '->' to fArray
+
+   * mfileio/MWriteRootFile.cc:
+     - changed some output to make debugging easier
+
+   * mjobs/MJCalibration.cc:
+     - fixed a bug in drawing
+
+   * mjobs/MJExtractSignal.cc:
+     - removed MPedestalCam from MWriteRootFile output.
+       When creating the branch it crashes - reason unknown I'll
+       investigate further
+
+
+
+ 2004/02/16: Markus Gaug
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h, macros/calibration.C:
+     - added MHCalibrationRelTimePix
+
+   * mcalib/MHCalibrationRelTimePix.[h,cc],
+     mcalib/MHCalibrationRelTimeCam.[h,cc]:
+     - new classes to fit and display the relative arrival times. 
+     - filled from MArrivalTime	
+     - need: MFillH("MHCalibrationRelTimeCam","MArrivalTime")
+
+   * manalysis/MCalibrationCalc.cc
+     - take out all uncommented code referring to the relative arrival time
+
+   * manalysis/MArrivalTime.h 
+     - changed function GetNumPixels to GetSize
+
+   * macros/bootcampstandardanalysis.C, macros/pedphotcalc.C
+     - included cosmics rejection which was in MCalibrationCalc before
+
+
+
+ 2004/02/14: Markus Gaug
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - added MHCalibrationChargePINDiode
+
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]
+     - new class to fill the PIN Diode histograms. Derives from 
+       MHCalibrationChargePix and is filled with MFillH from the 
+       container MExtractedSignalPINDiode. 
+       Will replace MHCalibrationPINDiode entirely soon.
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+     - new base class for the calibration charges histogram pixel. 
+       Derives from MH and can be filled with the MH with the MH 
+       functions. 
+
+   * mcalib/MExtractPINDiode.[h,cc]
+     - new signal extractor for the PIN Diode
+
+   * mcalib/MExtractedSignalPINDiode.[h,cc]
+     - new container for the extracted signal of the PIN Diode
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - remove the PIN Diode signal extraction 
+
+   * manalysis/MHPedestalPix.[h,cc]
+     - new version of MHPedestalPixel, deriving from MHGausEvents.
+
+   * manalysis/MHPedestalPixel.[h,cc]
+     - old version removed, since obsolete (and erroneous)
+
+   * manalysis/MHPedestalCam.[h,cc]
+     - histogramming part of MPedestalCam now in own class 
+
+   * manalysis/MPedestalPix.h
+     - removed include of MHPedestalPixel
+
+   * macros/calibration.C 
+     - changed pedestal displays accordingly
+
+   * mjobs/MJPedestal.h
+     - class TCanvas included (did not compile otherwise)
+
+   * mhbase/MH.cc
+     - included call to FindGoodLimits(..) in CutEdges()
+     - axe from pointer to reference
+     - "CutEdges" renamed to "StripZeros"
+ 
+   * manalysis/MHPedestalPixel.cc, mcalib/MHCalibrationPixel.cc,
+     mcalib/MHCalibrationBlindPixel.cc:
+     - "CutEdges" renamed to "StripZeros"
+
+   * mcalib/MHGausEvent.[h,cc], mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - replaced by the improved version: MHGausEvents.[h,cc]
+
+
+
+ 2004/02/14: Thomas Bretz
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added 'Iterator' facility, this will replace some for-loops
+       in the near future
+     
+   * mbase/MTime.[h,cc]:
+     - added a more powerfull interface to get and interprete the
+       MTime contents as string
+     - added a new constructor
+
+   * mreport/MReportTrigger.h:
+     - fixed GetPixContent
+
+   * mtools/MCubicCoeff.cc, mtools/MCubicSpline.[h,cc]:
+     - many small changes to simple details (like order of includes)
+     - some speed improvements
+     - many small simplifications
+     - changed parts of the code to be more C++ like (eg Iterators
+       instead of for-loops)
+     - disentangles some if-cases
+     - replaced some math.h function by TMath::
+     - removed data-member fN (obsolete with iterators)
+
+
+
+ 2004/02/13: Wolfgang Wittek
+
+   * mcalib/MCalibrateData.[h,cc]
+     - new class; 
+       like MCalibrate, but in ReInit it fills the MPedPhot container
+       using informations from MPedestal, MExtracteSignalCam and 
+       MCalibrationCam
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h
+     - added MCalibrateData
+
+   * manalysis/MPedestalWorkaround.[h,cc]
+     - create MMcEvt container and fill with theta = 10.0
+     - set pedestalRMS = 0. if it is > 10.0
+
+   * manalysis/MSupercuts.[h,cc]
+     - change default values of parameters
+
+   * manalysis/MSupercutsCalc.[h,cc]
+     - change dNOMLOGSIZE from 4.1 to 5.0
+
+   * mhist/MHBlindPixels.[h,cc]
+     - change MPedestalCam to MPedPhotCam
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - automatic binning for pixel number doesn't work
+       use default binning
+
+
+
+ 2004/02/13: Markus Gaug
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - added variables gkAverageQE, gkAverageQEErr, and fAverageQE, 
+       fAverageQEErr
+     - gkAverageQE initializes to 0.2 (according to David)
+     - gkAverageQEErr initializes to 0.02 (dito)
+     - added new member function: SetAverageQE
+     - call to GetMeanConversionFFactorMethod returns: 
+       fMeanConversionFFactorMethod/fAverageQE. 
+     - call to GetErrorConversionFFactorMethod returns: 
+       errors of fMeanConversionFFactorMethod and fAverageQEErr added 
+       quadratically
+
+   * mcalib/Makefile
+     - split into two parts one comment line 
+
+
+ 2004/02/13: Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.[h.cc]:
+     - added for new bad pixel treatment
+
+   * mbadpixels/Makefile, mbadpixels/BadPixelsLinkDef.h:
+     - added MBadPixelsTreat
+
+   * merpp.cc:
+     - changed the name of the "DC" tree to "Currents" to make
+       MReportRead work correctly with this tree
+
+   * mbase/MTime.[h,cc]:
+     - Changed UpDMagicTime to support nanosec instead of millisec
+     - exchanged Reset() by Clear() not to clear the yy/mm/dd 
+       information away in an eventloop
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - implemented decoding of the time-stamp for raw-data files
+       with version>2. Thanks to Marcos.
+
+   * mraw/MRawRead.[h,c]:
+     - pipe file version number to MRawEvtHeader::ReadEvt
+     - create fake time for file-version<3
+
+   * macros/readMagic.C:
+     - changed to use MInteractiveTask
+
+   * mbase/MPrint.cc:
+     - fixed debugging level of some output
+     
+   * mhist/MHCamera.[h,cc]:
+     - fixed handling in AddNotify (necessayr due to change of
+       inheritance from MCamEvent)
+     - replaced cout by gLog
+     - added fNotify to list of cleanups
+
+   * mhist/MHEvent.cc, mjobs/MJCalibration.cc,
+     mjobs/MJPedestal.cc:
+     - fixed usage of AddNotify
+
+   * mfileio/MReadReports.cc:
+     - use a different way to determin whether the tree is a valid tree,
+       skip invalid trees
+       
+   * mfileio/MReadTree.cc:
+     - added another sanity check at the beginning of PreProcess
+     
+   * mhbase/MFillH.[h,cc]:
+     - added bit kCanSkip which skips MFillH in case the necessary container
+       wasn't found.
+     - cd into the corresponding canvas before filling the MH
+
+
+
+ 2004/02/12: Markus Gaug
+ 
+   * mbase/MArray.[h,cc]:
+     - changed name of StripZeros
+
+   * mcalib/MHGausEvent.cc:
+     - corrected call to StripZeros
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - implemented dummy for combined method
+
+   * mcalib/MCalibrate.[h,cc]
+     - implemented a dummy for calibration factor 1. (requested by
+       Javier Rico)
+     - implemented combined method
+     - check for valid methods moved to ReInit
+
+   * mcalib/MCalibrationCalc.cc
+     - removed initialization of non-used nsamples
+
+   * mcalib/MHCalibrationPixel.[h,cc], mcalib/MCalibrationPix.[h,cc],
+     mcalib/MCalibrationCalc.[h,cc]
+     macros/calibration.C
+     - implemented new histograms: 
+       HSinglePheFADCSlices and HPedestalFADCSlices
+       They are filled with the FADC slice values of either a s.phe. 
+       event or a pedestal event. The decision is taken with the 
+       variable: MCalibrationCalc::fBlindPixelSinglePheCut, to be set 
+       with a setter 
+
+   * mtools/MFFT.[h,cc]
+     - PowerSpectrumDensity of TArrayI implemented
+
+
+
+ 2004/02/12: Thomas Bretz
+ 
+   * mbase/MArray.[h,cc]:
+     - changed argument of CutEdges from pointer to reference
+
+   * mgeom/MGeomPix.h:
+     - fixed calculation of area of pixel. It was too big for a 
+       factor of 2
+
+   * mjobs/MJCalibration.cc:
+     - slight change of name of a MHCamera
+
+   * manalysis/MExtractSignal.cc:
+     - slight change to the creation of the satpixels list
+     
+   * mcalib/MHCalibrationBlindPixel.cc, mcalib/MHCalibrationPixel.cc,
+     mcalib/MHGausEvent.cc:
+     - corrected call to ProjectArray
+     - corrected call to CutEdges
+     
+   * mfilter/MFCosmics.[h,cc]:
+     - small fixes to logging output
+     - small simplification to return statement
+     - declared CosmicsRejection const
+
+   * mhbase/MH.[h,cc]:
+     - changed argument of ProjectArray from pointer to reference
+     - added missing calcualtion of minimum
+     - removed obsolete SetEntries
+     - changed SetDirectory from NULL to gROOT
+
+
+
+ 2004/02/12: Javier L�ez
+
+   * macros/pointspreadfunction.C
+     - added new macro that fits with a 2D gaussian the DC spot for an 
+       star. It gives you the RMS of the PSF and the center of the star,
+       very useful for misspointing studies.
+
+
+
+ 2004/02/11: Hendrik Bartko
+
+   * manalysis/MExtractSignal2.cc:
+     - introduced a validity check for the set-function of the window 
+       size (even number of slices, WindowSize < NumberSlices)
+
+   * manalysis/MArrivalTimeCalc2.[h,cc], manalysis/Makefile, 
+     manalysis/AnalysisLinkDef.h:
+     - new: introduced the calculation of the arrival time as the signal 
+       weighted mean of the time slices in the maximum window
+
+
+
+ 2004/02/11: Markus Gaug
+
+   * mcalib/MCalibrationCalc.cc:
+     - the blind pixel signal extractor introduced one week ago, counted 
+       one FADC slice too little, thus the normalization w.r.t. pedestals 
+       was wrong. Now corrected.
+
+   * manalysis/MExtractSignal.cc, manalysis/MExtractSignal2.cc:
+     - when "WARNING - Lo Gain saturated" occurs, display also the
+       corr. pixel numbers.
+
+   * mbase/MArray.[h,cc]:
+     - introduced function to cut array edges with zeros. 
+       (Thomas, should we keep it there or move it to another class? )
+
+   * mcalib/MCalibrationCalc.[h,cc]:
+     - new function SetBlindPixelRange to set start and end of FADC slices 
+       used for the blind pixel signal extraction. 
+     - remove fEvents which are not necessary any more after the shift 
+       to MFCosmics.
+
+   * mcalib/MHCalibration(Blind)Pixel.[h,cc]:
+     - show the fourier spectrum now with axes in frequency [Hz] instead 
+       of inverted events. 
+
+   * mcalib/MHGausEvent.[h,cc], mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - new base class for all kind of events with variables having a 
+       Gaussian distribution. Will serve as base class for the 
+       existing and new calibration histogram classes. 
+
+
+
+ 2004/02/11: Abelardo Moralejo
+
+   * mmain/MEventDisplay.cc
+     - Switched order of MMcPedestalCopy and MCerPhotCalc in tasklist:
+       MMcPedestalCopy must be executed earlier!
+
+
+
+ 2004/02/10: Raquel de los Reyes
+
+   * mhist/MHPixVsTime.[h,cc]:
+     - Added a default draw function and replaced the TGraph object 
+       by a pointer to a TGraph object.
+
+   * mreport/MReportTrigger.h:
+     - Now it dereives from a MCamEvent class and implemented the
+       GetPixContent() and DrawPixelContent() functions.
+
+   * maccros/CCDataCheck.C:
+     - An update of the previous macro. New plots: subsystems status and
+       macrocells trigger.
+
+
+
+ 2004/02/10: Markus Gaug
+
+   * mcalib/MCalibrationCam.cc:
+     - fixed documentation
+
+   * mhbase/MH.[h,cc]:
+     - new function ProjectArray
+
+   * mcalib/MHCalibrationPixel.[h,cc],
+     mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - use ProjectArray from MH to plot the projection of the fourier 
+       spectrum
+
+   * mfilter/MFCosmics.[h,cc], mfilter/Makefile,
+     mfilter/FilterLinkDef.h:
+     - new filter removing cosmics, the same as in MCalibrationCalc
+       where it was removed now. 
+       Call: MFCosmics cosmics; 
+             MContinue cont(&cosmics); 
+             tlist.AddToList(&cont);
+
+   * mcalib/MCalibrationCalc.[h,cc]:
+     - removed cosmics rejection from there
+ 
+   * macros/calibration.C, mjobs/MJCalibration.cc:
+     - changed cosmics rejection to the filter algorithm
+
+
+
+ 2004/02/09: Markus Gaug
+
+   * mcalib/MCalibrationBlindPix.[h,cc]:
+     - added histogram to display the average in FADC slices of all 
+       single and double phe events
+
+   * mcalib/MCalibrationCalc.cc:
+     - fill histograms of single-phe events with higain and logain
+       sampls
+
+   * mcalib/MCalibrationCam.[h,cc], mcalib/MCalibrationCalc.cc,
+     mcalib/MCalibrationConfig.h:
+     - take all pixel areas out of MGeomPix::GetA(), remove all previous
+       areas 
+     - calculate photon fluxes from blind pixel and PIN diode, use 
+       area only to fill the conversion factors in MCalibrationPix 
+
+
+   * mcalib/MJCalibration.cc:
+     - display of number of photons for Blindpixel and PIN Diode Method 
+       changed to display of photon flux which is the actually 
+       calculated quantity
+
+
+
+ 2004/02/09: Thomas Bretz
+
+   * mbadpixels/*:
+     - added
+
+   * Makefile:
+     - added MBadPixels
+
+   * manalysis/MGeomApply.cc:
+     - fixed class description
+
+   * mjobs/MJCalibration.[h,cc], mjobs/MJExtractSignal.[h,cc]:
+     - added bad pixel treatment
+
+   * mjobs/MJPedestal.[h,cc]:
+     - reorganized order of functions
+     - removed a nonsense scrren output (some BLABABLA or so)
+
+   * mjobs/Makefile:
+     - added include for mbadpixels
+
+   * mmain/MBrowser.cc:
+     - do not call construtor of TGTReeLBEntry if pic0=0
+
+
+
+ 2004/02/09: Raquel de los Reyes
+
+   * mcamera/MCameraLids.h, mreport/MReportCamera.h
+     - Added the "Get" functions to access the private data 
+       members of the class.
+
+
+
+ 2004/02/09: Markus Gaug
+
+   * MMcCalibrationUpdate.cc, MCalibrate.cc, MCalibrationPix.cc,
+     MCalibrationPix.h:
+     - replace MCalibrationPix->IsChargeFitValid() by IsChargeValid()
+       because we can calibrate with the histogram mean and RMS even 
+       if the fit is not OK. Thus, there is a question: IsFitted() and 
+       IsChargeValid(), i.e. does the charge make any sense? 
+
+   * MCalibrationCam.cc, MCalibrationConfig.h, MCalibrationCalc.cc:
+     - found serious bug in calculation of conversion factors for the 
+       outer pixels: 
+       GetMeanConversionBlindPixelMethod and 
+       GetMeanConversionPINDiodeMethod 
+       did not correct for the area of the outer pixel, this did only 
+       MCalibrationCam::GetPixelContent which is not used by MCalibrate
+
+
+
+ 2004/02/06: Markus Gaug
+
+   * mgeom/MGeomCam.h 
+     - replaced in Comment of fPixRatio: 
+       "ratio between size of pixel idx and pixel 0" by
+       "ratio between size of pixel 0 and pixel idx" 
+
+   * manalysis/MPedestalCam.cc
+     - catch calls to MHPedestalPixel in case that they are not filled 
+       This led previous calls to segmentation violations
+     - remove include of MHExtractedSignalPix
+ 
+   * manalysis/MHExtractedSignalPix.[h,cc]
+     - is everything in MHPedestalPixel, so removed it again
+
+   * mjobs/MJPedestal.cc
+     - put the projections into Display()
+     - correct the input of Display (0: pedestal, 1: pedestalerror, 
+                                     2: pedRMS, 3: pedRMSerror)
+
+   * manalysis/MHPedestalPixel.cc
+     - increased number of bins in for charges plot
+
+   * mtools/MFFT.[h,cc]
+     - possibility to have PSD directly from TArray
+
+   * mjobs/MJCalibration.[h,cc]
+     - fixed displays
+     - replaced MExtractSignal by MExtractSignal2
+
+   * mcalib/MHCalibrationPixel.[h,cc], mcalib/MHCalibrationBlindPixel.[h,cc],
+     mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationBlindPix.[h,cc],
+     mcalib/MCalibrationPINDiode.[h,cc], mcalib/MHCalibrationPINDiode.[h,cc]:
+     - remove histograms MHChargevsN..., now keep TArrays directly
+     - check for oscillations for all pixels (and you will not trust 
+       your eyes when you look at the results :-((((
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - remove ArrivalTime -> go to separate class
+     - remove BlindPixel and PIN Diode overflow, now handled directly 
+       inside the corr. classes. 
+     - remove SkipTimeFits -> go the arrival time class
+
+   * mcalib/MCalibrationCam.h
+     - new getters for number of photons
+     - removed timeslicewidth -> go the corr. time containers
+
+   * mcalib/MCalibrationCam.cc
+     - removed times of GetPixelContent
+     - added OscillationChecks in GetPixelContent
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - remove calpix.SkipTimeFits which is now obsolet
+
+   * macros/calibration.C
+     - all previous changes now in this macro.
+     - (NB: Thomas, du brauchst in MJCalibration nicht mehr aendern, 
+       das ging diesmal in einem Aufwasch)
+
+
+
+ 2004/02/06: Thomas Bretz
+
+   * mhist/MHPixVsTime.[h,cc]:
+     - changed such that you can set the name of the time container now 
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added GetMaxPixId()
+
+   * mraw/MRawEvtData.cc:
+     - fixed wrong size calculation for fABflags
+
+
+
+ 2004/02/06: Oscar Blanch
+
+   * mmc/MFadcDefine.h && mmc/MMcFadcHeader.cxx
+     - We cahnged the name (and values) of the global variable
+        MFADC_RESPONSE_AMPLITUDE to  MFADC_RESPONSE_INTEGRAL
+
+
+
+ 2004/02/05: Markus Gaug
+
+   * mcalib/MHCalibrationPixel.[h,cc]
+     - put an NDF limit for the fit
+     - removed all TStrings and replace them by Form(..)
+     - Check for nan's of all returned fit values
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationCam.cc:
+     - reshuffled HiLoGainConversion, calculation of F-Factor method, 
+     - calculation of total F-Factor of the readout.
+
+   * mcalib/MCalibrationCam.cc
+     - include relative times to display with GetPixelContent
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - flag to skip Hi-Lo Calibration
+     - Hi-LO Graph not filled any more after overflow of ChargevsN
+     - fill the blind pixel differently from the rest of pixels
+
+   * mcalib/MCalibrate.cc:
+     - call to const MCalibrationPix &pix replaced by MCalibrationPix &pix
+
+   * manalysis/MArrivalTimeCalc.cc
+     - default step width 100 ps. 
+     - look for half maximum (at rising edge)
+
+   * manalysis/MExtractSignal.[h,cc]
+     - removed uncommented code (arrival time)
+     - set start byte back by one like it was before TB's changes 
+       (does not affect the calculation of number of FADC slices)
+
+   * manalysis/MExtractSignal2.[h,cc]
+     - removed uncommented code (arrival time)
+
+   * manalysis/MHPedestalPixel.[h,cc]
+     - is now filled with total pedestals (not per slice), but results are 
+       renormalized to values per slice (this is not to screw up with the 
+       pedestal RMS and the derived uncertainties)
+     - new function Renorm(nslices)
+
+   * manalysis/MPedestalCam.[h,cc]
+     - introduced function Clone() (like proposed by TB)
+     - call to MHPedestalPixel operator() not const any more
+     - take out lots of uncommented code 
+     - found bug in initialization of hists. SetupFill is called in 
+       PreProcess, therefore, TObjArray is not yet enlarged there. 
+       Now, InitUseHists is called in Fill
+     - MHPedestalPixel is now filled with total pedestals (not per slice), 
+	but results are 
+       renormalized to values per slice (this is not to screw up with the 
+       pedestal RMS and the derived uncertainties)
+
+   * manalysis/MPedCalcPedRun.cc
+     - added author
+     - split calculation of RMS into two steps to make it more clear to 
+       the user
+
+   * macros/calibration.C
+     - found bug introduced two days ago, namely calculating pedestlas with 
+       MExtractSignal2 which is now fixed
+     - Skip HiLoConversionCalibration
+
+
+
+ 2004/02/05: Abelardo Moralejo
+
+   * macros/starmc2.C
+     - added 3rd argument, "kFALSE", to call of MWriteRootFile::Add
+       for both MMcEvt and MMcRunHeader since these containers are
+       not present in real data. Name of macro is no longer adequate if
+       we will use it for calibrated real data (to be changed if so).
+
+
+
+ 2004/02/05: Sebastian Raducci
+
+   * mtools/MCubicSpline.[h,cc]
+     - added
+     - this class will take the place of the TSpline class to 
+       calculate arrival times
+
+   * mtools/MCubicCoeff.[h,cc]
+     - added
+     - this class is used by MCubicSpline to store coefficients
+
+   * macros/spline.C
+     - added
+     - test macro. Shows how to use the MCubicSpline class
+     - it could be used to test the methods of the Spline class
+
+
+
+ 2004/02/05: Thomas Bretz
+
+   * mmain/MBrowser.cc:
+     - fixed a double deletion of a TGLayoutHints
+
+
+
+ 2004/02/04: Markus Gaug
+
+   * mmain/MBrowser.cc:
+     - corrected TGTReeLBEntry for TGTreeLBEntry
+
+
+
+ 2004/02/04: Thomas Bretz
+ 
+   * manalysis/MExtractSignal2.cc:
+     - don't allow odd numbers for the window size
+
+   * mfilter/MFilterList.cc:
+     - corrected a wrong logging message
+
+   * mmain/MBrowser.cc:
+     - added '/data/MAGIC' as shortcut in the combo box
+     
+   * mraw/MRawEvtPixelIter.cc:
+     - optimized calculation of MaxIdx
+
+
+
+ 2004/02/04: Abelardo Moralejo
+
+  * macros/starmc2.C
+    - removed unnecessary variables BinsHigh, BinsLow
+
+
+
+ 2004/02/04: Markus Gaug
+
+  * manalysis/MPedestalCam.[h,cc], manalysis/MPedestalPix.[h,cc],
+    manalysis/MPedCalcPedRun.[h,cc], manalysis/MHPedestalPixel.[h,cc],
+    macros/calibration.C:
+    - histograms are now filled with MFillH as proposed and coded by 
+      Thomas Bretz. Some modifications had to be done, however. 
+    - Class to hold MHPedestalPixel is still MPedestalCam
+    - MPedCalcPedRun does nothing any more (except from what is was 
+      doing before)
+
+  * manalysis/MExtractSignal.cc
+    - remove uncommented code
+
+  * mcalib/MCalibrationCalc.[h,cc]
+    - modified way to handle histogram overflow: Now flags are set and 
+      ChargevsN histogram is not tried to be filled subsequently
+
+
+
+ 2004/02/03: Markus Gaug
+ 
+   * manalysis/MHExtractedSignalPix.[h,cc]
+     - added Thomas B. modified version of MHPedestalPixel. Later will 
+       remove MHPedestalPixel
+
+   * manalysis/MCalibrationPix.[h,cc], manalysis/MHCalibrationPixel.[h,cc],
+     manalysis/MCalibrationCam.cc, macros/calibration.C:
+     - now split completely absolute and relative times. Absolute 
+       times are not fitted, but their histogram mean and rms are 
+       returned.
+
+
+
+ 2004/02/03: Thomas Bretz
+
+   * mfileio/MReadTree.cc:
+     - fixed handling of -1 entries in AddFile: root 3.10/02 crashed
+
+   * manalysis/MExtractSignal.[h,cc]:
+     - moved code to extract the signal from Process to
+       new member function FindSignal, I left the arrival time 
+       extraction as commented-out code in the code just as a 
+       demonstration to do this very fast.
+
+
+
+ 2004/02/02: Markus Gaug
+
+  * manalysis/MPedCalcPedRun.cc
+    - corrected formulae in Class description
+
+  * mcalib/MCalibration.[h,cc], mcalib/MHCalibration.[h,cc],
+    manalysis/MMcCalibrationUpdate.cc:
+    - calculate relative times and absolute times. Fit only 
+      the relative ones. 
+
+
+
+ 2004/02/02: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc, MMcPedestalCopy.cc
+     - removed file type check (MC or data) from PreProcess since now
+       run headers are not yet known at that point.
+
+   * mcalib/MMcCalibrationCalc.cc
+     - same as above.
+
+   * NEWS
+     - updated.
+
+
+
+ 2004/02/02: Thomas Bretz
+
+   * manalysis/MExtractSignal2.[h,cc]:
+     - added new task which takes a given number of slices with the
+       highest integral content as signal.
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - added MExtractSignal2
+
+
+
+ 2004/01/30: Abelardo Moralejo
+
+   * macros/starmc.C
+     - changed default FADC integration range (more adequate for coming
+       camera version).
+
+   * macros/mccalibrate.C, starmc2.C
+     - added. First macro transforms input files from camera simulation
+       into files with pixel data already calibrated in photons. The 
+       second reads in an already calibrated data file and produces an 
+       output file with Hillas parameters. Both together do the same as
+       starmc.C, but it is convenient to have files containing 
+       calibrated pixel information.
+
+
+
+ 2004/01/30: Thomas Bretz
+ 
+   * mbase/MDirIter.h:
+     - added GetNumEntries
+
+   * mhist/MHEvent.cc:
+     - added a dynamic_cast from MParContainer to MCamEvent to get the
+       correct pointer to the correct base-class.
+
+   * mbase/MStatusDisplay.cc:
+     - In EventInfo check whether gPad==0
+     
+   * mfileio/MReadMarsFile.cc:
+     - removed reading RunHeaders from PreProcess, this resulted
+       in strange behaviour of writing RunHeaders
+     - fixed consistency check for RunType accordingly
+
+   * mfilter/MFilterList.cc:
+     - do not skip adding filter if only a filter with the same name 
+       exists
+       
+   * mraw/MRawFileRead.cc:
+     - added an output message if run header is not accessible
+     
+   * mraw/MRawRunHeader.[h,cc]:
+     - initialize fRunType to new enum kRTNone
+
+   * mfilter/MFGeomag.cc:
+     - set fResult to kFALSE at the beginning of Process
+     - according to this removed setting fResult=kFALSE before return
+     - replaced some float by Float_t
+     - added some const-qualifiers
+     - replaced (rig<0.5/pr*R*(r2-r1)+r1) by (rig-r1)*pr<rnd
+       with rnd = R * (r2-r1)/2 to make sure that we cannot
+       devide by 0
+
+   * manalysis/MPedCalcPedRun.cc:
+     - added some comments
+
+   * Makefile:
+     - added mjobs
+
+   * mjobs/*:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MRunIter
+
+   * mbase/MRunIter.[h,cc]:
+     - added
+
+
+
+ 2004/01/30: Markus Gaug
+
+   * manalysis/MPedestalCam.h
+     - added function IsUsedHists()
+
+   * manalysis/MPedestalCam.cc
+     - modified GetPixelContent
+
+   * manalysis/MPedestalCam.cc, manalysis/MPedCalcPedRun.cc:
+     - include storage of number of used FADC slices to compare later 
+       the pedestal per slice ( and sigma per slice)
+     - return relative differences in GetPixelContent
+
+   * mcalib/MCalibrationCalc.[h,cc], mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - fBlindPixelId and fPINDiodeId now like in PedestalCam
+     - fill Blind Pixel with information about its fitted pedestal if 
+       available
+     - initialize charges histogram with a bigger range
+     - use pedestal information to constrain the pedestal fit ranges
+
+   * manalysis/MHPedestalPixel.cc
+     - initialize charges histogram with a bigger range
+
+   * macros/calibration.C
+     - SetRange of MExtractSignal to 1,14 (see emails of yesterday)
+     - apply new GetPixelContents of MPedestalCam (more calculations 
+       and displays of errors, correction for different FADC slice 
+       number)
+
+   * manalysis/MExtractSignal.cc
+     - not access to MArrivalTime any more. The same information is 
+       stored in MRawEvt->GetPixelContent(...)
+
+   * manalysis/MCalibrationCalc.cc
+     - retrieve default arrival time from MRawEvt 
+
+   * manalysis/MCalibrationBlindPix.cc, manalysis/MCalibrationPix.cc
+     - check for NaN's in fit results
+
+
+
+ 2004/01/29: Abelardo Moralejo
+
+   * mfileio/MWriteFile.h
+     - added missing declaration of ReInit
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - added call to MCalibrationCam::SetBlindPixelMethodValid(kTRUE) 
+       to adapt to recent changes in MCalibrate.
+
+
+
+ 2004/01/29: Thomas Bretz
+
+   * manalysis/MArrivalTime.h, manalysis/MCameraData.h,
+     manalysis/MCerPhotEvt.h, manalysis/MExtractSignalCam.h,
+     manalysis/MPedPhotCam.h, manalysis/MPedestalCam.h,
+     mcalib/MCalibrationCam.h, mcamera/MCameraDC.h,
+     mraw/MRawEvtData.h, mreflector/MRflEvtData.h:
+     - split derivement into MParContainer and MCamEvent
+
+   * manalysis/MExtractSignalCam.[h,cc]:
+     - removed obsolete MExtractSignal::ReInit
+     - added -> to fArray
+
+   * mbase/MParList.h:
+     - added a new bit kIsProcessing
+     
+   * mbase/MTaskList.cc:
+     - fixed the handling of kDoNotReset and the bahaviour of
+       SetReadyToSave, such that it is possible to write all
+       headers 
+
+   * mfileio/MWriteFile.cc:
+     - added ReInit which also calls CheckAndWrite
+     
+   * mgui/MCamEvent.h:
+     - does not derive from MParContainer anymore
+
+
+
+ 2004/01/29: Markus Gaug
+
+   * mcalib/MCalibrationCalc.[h,cc], mcalib/MCalibrationCam.[h,cc], 
+     mcalib/MCalibrationConfig.h
+     - put gkCalibrationBlindPixelId and gkCalibrationPINDiodeId 
+       directly into the corresponding classes.
+
+
+
+ 2004/01/29: Nicola Galante
+
+   * mhistmc/MHMcTriggerLvl2.[h,cc]:
+     - In method MHMcTriggerLvl2::GetHistByName(const TString name) 
+       added string checking to return also 
+       fHistCellPseudoSize, fHistCellPseudoSizeNorm
+       and fHistCellPseudoSizeEnergy.
+     - Added inline functions GetHistCellPseudoSize() and 
+       GetHistCellPseudoSizeNorm().
+
+
+
+ 2004/01/28: Javier Rico
+
+   * mcalib/MCalibrate.[h.cc]
+     - include possibility to select the calibration method to be used
+
+
+
+ 2004/01/28: Markus Gaug
+
+   * mcalib/MCalibrate.[h.cc]
+     - corrected Int_t ReInit() to Bool_t ReInit(MParList *pList)
+
+   * mcalib/MCalibrationCalc.[h,cc], mcalib/MCalibrationCam.[h,cc]:
+     - included flags to indicate if Blind Pixel Method or PIn Diode 
+       method was OK. Up to now, program stopped, if one of the two 
+       methods was chosen but not able to being executed.
+
+   * manalysis/MArrivalTimeCalc.cc, manalysis/MExtractSignals.cc,
+     manalysis/MGeomApply.cc:
+     - put all missing InitSize(npixels) into MGeomApply	 
+
+   * manalysis/MPedCalcPedRun.[h,cc], manalysis/MPedestalCam.[h,cc],
+     manalysis/MPedestalPix.[h,cc], manalysis/MHPedestalPixel.[h,cc],
+     manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - include possibility to fit the pedestals with Gaussian. 
+     - old methods are not affected. 
+     - add new method with MPedCalcPedRun::SetUseHists()
+
+
+
+ 2004/01/28: Abelardo Moralejo
+
+   * mcalib/MMcCalibration.cc
+     - fixed wrong variable type in call to TH1F constructor (number of
+       bins is now integer), which resulted in a compilation warning.
+
+
+
+ 2004/01/28: Thomas Bretz
+
+   * manalysis/MPedestalCam.cc:
+     - removed unwanted CheckBound from operators. CheckBounds is ONLY
+       ment for really old MC files and will be removed in the future
+       anyhow.
+
+   * mcalib/MHCalibrationPixel.h:
+     - removed obsolete include of MFFT 
+
+   * manalysis/MCerPhotAnal.cc, manalysis/MCerPhotCalc.cc,
+     manalysis/MPedestalCam.[h,cc]:
+     - removed use of obsolete MPedestalCam::CheckBounds. This was
+       a workaround for a 'bug' in very old camera files, which is not
+       necessary anymore.
+
+   * manalysis/MCerPhotAnal2.[h,cc]:
+     - replaced MPedestalCam by MPedPhotCam
+     
+   * manalysis/MExtractSignal.cc:
+     - some small simplification to the signal extraction
+     - removed some obsolete variables
+     - replaced for by while
+     - removed obsolete casts
+     
+   * mmain/MEventDisplay.cc:
+     - gave names to the filters
+     - removed adding MHCamera to fList because it was deleted twice
+
+   * mhist/MHCamera.cc:
+     - fixed usage of fPainter in Paint() - title was not updated 
+       correctly
+
+
+
+ 2004/01/28: Sebastian Raducci
+
+   * manalysis/MArrivalTime.[h,cc]:
+     - removed all the code relative to the cluster evaluation
+
+
+
+ 2004/01/27: Markus Gaug
+ 
+   * manalysis/MPedestalPix.cc:
+     - initialize default values to 0 instead of -1.
+
+   * manalysis/MPedestalCam.[h,cc]:
+     - include CheckBounds, also in operator[]
+
+   * mcalib/MCalibrationCam.[h,cc]:
+     - apparently, there was a reference to InitSize(UInt_t i) instead 
+       of InitSize(Int_t i), where compiler complained, now changed
+ 
+   * mcalib/MHCalibration*, mcalib/MCalibration*:
+     - fixed all Clear()'s, Reset()'s, direct intializers
+
+
+
+ 2004/01/27: Thomas Bretz
+
+   * mdata/MDataChain.cc:
+     - added '%' to supported operators
+
+
+
+ 2004/01/26: Nicola Galante
+
+   * manalysis/MMcTriggerLvl2.[cc,h]:
+
+     - Defined some static constants to avoid ugly "magic numbers"
+       in arrays: gsNCells, gsNTrigPixels,
+       gsNPixInCell, gsNLutInCell, gsNPixInLut, fNumPixCell.
+     - Added method 
+       MMcTriggerLvl2::GetCellCompactPixel(int cell, MGeomCam *fCam)
+       which computes compact pixels into a given L2T macrocell.
+     - Added method 
+       MMcTriggerLvl2::CalcBiggerCellPseudoSize() 
+       which computes fCellPseudoSize, the maximum Pseudo Size into L2T 
+       macrocells
+     - Added method 
+       MMcTriggerLvl2::GetCellPseudoSize() const 
+       which returns fCellPseudoSize
+     - Added method 
+       MMcTriggerLvl2::IsPixelInCell(Int_t pixel, Int_t cell),
+       which controls whether a pixel belongs to a given L2T cell.
+     - Added method 
+       MMcTriggerLvl2::GetMaxCell() const 
+       which returns fMaxCell, the cell with the maximum 
+       fCellPseudoSize.
+
+
+
+ 2004/01/26: Markus Gaug, Michele Doro
+
+   * manalysis/MArrivalTime.[h,cc], manalysis/MArrivalTimeCalc.[h,cc]:
+     - moved calculation of arrival time from MArrivalTime to 
+       MArrivalTimeCalc. MArrivalTime does not do any Process-job
+       anymore
+     - TSpline5 now on stack. 
+     - function to set the stepsize
+
+   * mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - force mu_{0} in Blind Pixel Fit to be around 0 in fKPoisson4
+     - implement combined Polya fit and Michele's back-scattered electron
+       fit 
+
+   * mcalib/MHCalibrationPixel.[h,cc], mcalib/MCalibrationPix.cc,
+     mcalib/MCalibrationPINDiode.cc:
+     - combine FitChargeHiGain and FitChargeLoGain into one function
+
+   * macros/calibration.C
+     - improve double gauss fit a bit
+
+
+
+ 2004/01/26: Thomas Bretz
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - removed member function GetNumPixels. For more details see mantis.
+
+   * manalysis/MArrivalTime.[h,cc]:
+     - reorganized includes
+     - fixed InitSize and ClearArray (now Reset) to fit MParContainer
+       definition
+     - for the moment removed usage of fPixelChecked - THIS WILL CRASH YOUR
+       PROGRAM
+
+   * manalysis/MArrivalTimeCalc.[h,cc]:
+     - reorganized includes
+     - removed many obsolete code, exspecially copy&paste relicts!
+     - fixed usage of InitSize
+     - removed CleanArray. Reset() is called automatically before Process()
+
+   * manalysis/MExtractedSignalCam.[h,cc]:
+     - added SetLogStream
+     - removed obsolete include MGeomCam
+     - replaced PrintOut by Print
+     - added const-qualifiers to all Getters
+     - fixed documentation
+     
+   * manalysis/MExtractedSignalPix.[h,cc]:
+     - replaced PrintOut by Print
+     - fixed documentation
+
+   * manalysis/MEventRateCalc.cc, manalysis/MPedCalcPedRun.cc:
+     - replaced memset by Reset()
+
+
+
+ 2004/01/24: Abelardo Moralejo
+
+   * macros/starmcstereo.C
+     - Added. Example of how to run the analysis chain for MC files
+       containing simulation of stereo systems of 2 telescopes.
+
+   * mcalib/MCalibrate.cc
+     - Added check that value of signal from MExtractedSignalPix is not
+       the default (error) value. In such a case, the signal in 
+       MCerPhotEvt is now set to 0. Before, all pixels got very high
+       values in MCerPhotEvt in case the MRawEvtData object for the
+       event was missing in the file. This happened in MC files, in 
+       which in some circumstances an event is written without the
+       pixel information (for instance, when running stereo simulations
+       the pixel data is missing for non-triggered telescopes, but the
+       event headers are present).
+
+
+
+ 2004/01/23: Markus Gaug
+
+   * manalysis/MExtractSignal.[h,cc], manalysis/MExtractedSignalPix.[h,cc],
+     manalysis/MArrivalTime.[h,cc], mcalib/MCalibrationBlindPix.h,
+     mcalib/MHCalibrationBlindPixel.[h,cc], mcalib/MCalibrationPINDiode.h,
+     mcalib/MHCalibrationPINDiode.[h,cc], mcalib/MCalibrationPix.[h,cc],
+     mcalib/MHCalibrationPixel.[h,cc], mcalib/MCalibrationCalc.[h,cc]:
+     - use MArrivalTime for Storage (or calculation) of time
+       in MExtractSignal
+     - pass from TH1I histos to TH1F for times
+
+   * mcalib/MCalibrationBlindPix.h, mcalib/MHCalibrationBlindPixel.[h,cc],
+     mcalib/MCalibrationPix.[h,cc], mcalib/MHCalibrationPixel.[h,cc],
+     mcalib/MCalibrationCalc.[h,cc]:
+     - clean up  setters 
+     - pass to bit-fields for all flags
+
+   * mcalib/MCalibrationCam.cc
+     - exclude Blind Pixel from Camera display
+     - do not fill &val when return kFALSE
+
+   * macros/calibration.C
+     - include functions to exclude the blind pixel, 
+       calculation of times and quality checks
+
+
+
+ 2004/01/23: Abelardo Moralejo
+
+   * mcalib/MCalibrate.cc, manalysis/MExtractSignal.cc
+     - Added support (using AddSerialNumber) for stereo MC files.
+
+
+
+ 2004/01/23: Thomas Bretz
+
+   * mbase/MAstro.cc:
+     - Fixed calculation of MJD. In Ymd2Mjd a plus should be a minus.
+
+   * mreport/MReport*.[h,cc]:
+     - changed all classes to return Int_t instead of Bool_t in 
+       InterpreteBody
+     - changed MReportFileRead such, that a wrong line results in
+       skipping the line instead of abort reading.
+
+   * manalysis/MExtractSignal.cc:
+     - do not print information for each pixel - it's too much.
+     
+   * mbase/MStatusDisplay.cc:
+     - when reading a status display do not display tabs with
+       the same name than one which is already existing.
+       
+   * mcalib/MCalibrate.cc:
+     - directly store pointer to pixel when setting saturation flag
+     
+   * mcamera/MCameraDC.cc:
+     - fixed some comments
+     
+   * mhist/MHCamEvent.cc:
+     - fixed a crash when no geometry was available
+
+   * mhist/MHCamera.[h,cc]:
+     - removed obsolete member function SetPix
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added EventInfo member function
+     - implemented preliminary redirection of GetObjectInfo to
+       StatusLine2 -> An own status line for this is missing
+
+   * manalysis/MExtractSignal.[h,cc]:
+     - implemented StreamPrimitive
+     - changed deafults to be static const data members
+     
+   * manalysis/MGeomApply.[h,cc]:
+     - implemented StreamPrimitive
+
+
+
+ 2004/01/23: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.[h,cc] 
+     - Added check to guarantee that the FADC simulation parameters of
+       all read files (those used for calibration and those analyzed) 
+       are the same.
+     - Added missing support for analysis of stereo files.
+
+   * mcalib/MMcCalibrationCalc.cc
+     - Removed obsolete FIXME comment.
+     - Added missing support for analysis of stereo files.
+
+
+ 2004/01/23: Raquel de los Reyes
+
+   * macros/CCDataCheck.C
+     - Added the temperature distribution of the optical links
+       and the plots of the LV power supplies.
+   * mcamera/MCameraLV.h
+     - Added the "Get" functions to access the private data 
+       members of the class.
+
+
+ 2004/01/22: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Now ratio of high to low gain is taken from MCalibrationCam if
+       it existed previously in the parameter list, instead of being
+       read again from the MMcFadcHeader. Removed Setter function for
+       fADC2PhInner, no longer necessary. Fixed error regarding the 
+       pedestal conversion to photons (did not read conversion factor
+       from preexisting MCalibrationCam object).
+
+   * mcalib/MMcCalibrationCalc.cc
+     - Changed parameters of the histogram, and also the quantity being 
+       histogrammed. Check that input data come from a noiseless camera
+       file before proceeding to do the calibration. Introduced lower
+       size in cut for calibration. Now rhe calibration constant is not
+       calculated from the mean of photons/ADC counts, but from the peak
+       of the histogram.
+
+   * macros/starmc.C
+     - Introduced new scheme. Now there are two loops over two different
+       sets of files. First loop calculates the calibration constants,
+       second one does the analysis. Introduced comments. Now the 
+       histogram used in the light calibration is written to the output
+       file.
+
+
+
+ 2004/01/22: Thomas Bretz
+
+   * mcalib/MCalibrate.[h,cc], mcalib/MCalibrationCam.[h,cc],
+     mcalib/MCalibrationBlindPix.[h,cc], mcalib/MCalibrationCalc.[h,cc],
+     mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationPINDiode.[h,cc],
+     mcalib/MCalibrationBlindPixel.[h,cc], 
+     mcalib/MHCalibrationPixel.[h,cc], mcalib/MMcCalibrationCalc.[h,cc],
+     mcalib/MHCalibrationBlindPixel.[h,cc], 
+     mcalib/MHCalibrationPINDiode.[h,cc]:
+     - cleaned up includes
+
+
+
+ 2004/01/22: Raquel de los Reyes
+
+   * macros/CCDataCheck.C
+     - macro to check the data from the central control (.rep files).
+
+
+
+ 2004/01/22: Markus Gaug
+
+   * macros/calibration.C
+     - made MStatusDisplay 3 bit smaller
+
+   * manalysis/MExtractSignal.cc
+     - put fSignals->SetUsedFADCSlices into PreProcess
+
+   * manalysis/MPedCalcPedRun.cc
+     - calculate PedRMS as RMS of the sums, later renormalized to units 
+       of RMS/slice (eliminate the wrong effect of odd and even slices)
+
+   * mcalib/MCalibrationCalc.cc
+     - if bit SkipBlindPixelFit is set, now number of photons outside 
+       plexiglass is not intended to be calculated any more (previous
+       bug)
+     - exclude excluded pixels in eventloop
+	
+   * mcalib/MHCalibrationBlindPixel.[h,cc]
+     - move functions to pointer again (otherwise, Clone will give 
+       strange results)
+
+
+
+ 2004/01/21: Abelardo Moralejo
+
+   * mcalib/MMcCalibrationCalc.[h,cc]
+     - Added. First version of the task intended to calculate the
+       conversion factors from ADC counts to photons in the MC. It has
+       a different aim than the recently renamed class 
+       "MMcCalibrationUpdate" (which takes care that the correct 
+       pedestals and conversion factors are supplied to each event, but 
+       does not really calculate anything).
+
+   * mcalib/Makefile, CalibLinkDef.h
+     - Added new class MMcCalibrationCalc
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Now the container MCalibrationCam is not created or modified if
+       it is found that one such container already exists in the 
+       Parameter list (from a previous calibration).
+
+
+
+ 2004/01/21: Thomas Bretz
+
+   * mraw/MRawRead.cc:
+     - restore the fake time for all runs (current time stamp in
+       the data seems to be toally nonsense)
+ 
+   * mraw/MRawEvtHeader.cc:
+     - removed decoding of real time (current time stamp in the data
+       seems to be toally nonsense)
+
+
+
+ 2004/01/21: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Uncommented 6 Getter functions (those regarding the number of 
+       photons surviving the different stages of simulation).
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Added (see below).
+
+   * manalysis/MMcCalibrationCalc.[h,cc]
+     - Removed: changed name of this class to MMcCalibrationUpdate, 
+       which is more representative of what it really does. Moved 
+       the filling of the MCalibrationCam container from Process to 
+       ReInit, since it does not change on an event by event basis.
+       Simplified PreProcess (MCalibrationCam was searched for twice).
+       Updated class description and comments.
+
+   * manalysis/Makefile, AnalysisLinkDef.h
+     - Adapted to change above
+
+   * macros/starmc.C
+     - Adapted to change above. Changed also task instance name from 
+       mccalibcalc to mccalibupdate.
+
+
+
+ 2004/01/21: Raquel de los Reyes
+
+   * mreport/MReportCC.h, mreport/MReportTrigger.h, mcamera/MCameraHV.h 
+     and mcamera/MCameraCalibration.h
+     - Added the "Get" functions (e.g GetStatus() for fStatus) to access 
+       the private data members of the class.
+
+
+
+ 2004/01/20: Thomas Hengstebeck
+
+   * mranforest/MRanForestCalc.[h,cc]
+     - Added member functions Grow (training of RF) and Fill (reading in
+       trained forest from file) which simplify macros. 
+       One just needs to call them instead of using MRanForestGrow and 
+       MRanForestFill (and the related training and fill loops) in a
+       macro.
+
+
+
+ 2004/01/20: Abelardo moralejo
+
+   * manalysis/MMcCalibrationCalc.cc
+     - removed call to MCalibrationPix::SetPedestal, which was not 
+       needed.
+
+
+
+ 2004/01/20: Thomas Bretz
+
+   * Makefile:
+     - replaced 'make' by '$(MAKE)'
+     
+   * Makefile.rules:
+     - added Makefile itself to dependencies
+     
+   * mbase/MTask.cc:
+     - added comment about ReInit
+
+   * mhbase/MH.cc:
+     - do not clear pad in DrawClone if 'same' option given
+
+   * mhist/MHVsTime.cc:
+     - evaluate 'same' option
+
+   * mfileio/MReadCurrents.[h,cc]:
+     - obsolete, removed
+
+   * manalysis/MCerPhotEvt.cc, manalysis/MCerPhotPix.cc:
+     - added some comments
+
+
+
+ 2004/01/20: Abelardo moralejo
+
+  * mcalib/MHCalibrationPINDiode.cc
+    - Added call to SetDirecory(0) for histograms fHErrCharge, 
+      fHPCharge, fHPTime.
+
+  * manalysis/MCerPhotPix.h: 
+    - Changed position of declaration of fIsSaturated to be the last 
+      private variable. Otherwise, since in the constructor it is 
+      initialized in the last place, a warning is displayed upon
+      compilation in some systems.
+
+
+
+ 2004/01/20: Markus Gaug
+  * mcalib/Makefile, manalysis/Makefile:
+    - include directory ../mtools
+ 
+  * mtools/MFFT.[h,cc]
+    - class inherits from TObject now
+
+
+
+ 2004/01/19: Markus Gaug
+
+  * mcalib/MHCalibrationBlindPixel.[h,cc]
+    - fixed a bug in fFitLegend due to which program crashed by calls 
+      to DrawClone
+    - Modified way to change the fit function
+
+  * mcalib/MHCalibrationPixel.[h,cc]
+    - reordered function calls
+    - removed SetupFill
+
+  * mcalib/MHCalibrationPINDiode.h
+    - reordered function calls
+
+  * mcalib/MCalibrationPix.[h,cc]
+    - limits to define fFitValid now as variables in class
+
+  * mcalib/MCalibrationCam.[h,cc]
+    - reordered function calls
+    - incorporate option to exclude pixels 
+
+  * mcalib/MCalibrationBlindPix.h
+    - Modified way to change the fit function
+
+  * mcalib/MCalibrationCalc.[h,cc]
+    - Modified way to change the fit function
+    - incorporate option to exclude pixels from configuration file
+
+  * macros/calibration.C
+    - Modified way to change the fit function
+    - incorporate option to exclude pixels from configuration file
+
+
+
+ 2004/01/19: Javier Rico
+
+   * manalysis/MPedCalcPedRun.cc, manalysis/MPedPhotCalc.cc
+     - Added documentation of member functions
+
+
+
+ 2004/01/19: Abelardo Moralejo
+
+   * manalysis/MCerPhotPix.[h,cc]
+     - Added fIsSaturated to flag whether low gain of the pixel is
+       saturated. Added corresponding getter and setter functions.
+       Updated ClassDef to version 2.
+
+   * mcalib/MCalibrate.cc
+     - Set the new saturation flag of MCerPhotPix to kTRUE if at least 
+       one low gain FADC slice is saturated.
+
+   * mimage/MNewImagePar.[h,cc]
+     - Added new member variable fNumSaturatedPixels to count how many
+       pixels were saturated. Updated ClassDef to version 2.
+
+
+
+ 2004/01/19: Thomas Bretz
+
+   * manalysis/MPedPhotCalc.[cc,h]:
+     - fixed order of includes
+     - removed obsolete forward declarations
+     - removed obsolete data member fNumPixels (stored already twice in
+       the two TArrayF)
+     - fixed some small bugs in the documentation
+
+   * manalysis/MPedCalcPedRun.cc:
+     - updated my eMail address
+
+
+
+ 2004/01/19: Javier Rico
+
+   * macros/dohtml.C, NEWS
+     - include some missing info
+
+
+
+ 2004/01/19: Abelardo Moralejo
+
+   * manalysis/MExtractedSignalPix.h
+     - added GetNumLoGainSaturated()
+
+
+
+ 2004/01/19: Markus Gaug
+
+   * macros/dohtml.C
+     - include calibration.C
+	
+   * manalysis/MExtractSignal.cc
+     - warning of logain saturation now only once per event (out of loop)
+
+   * mcalib/MCalibrationCalc.cc, mcalib/MCalibrationPix.[h,cc]
+     - new Flag fExcluded to indicate if pixel has been excluded from 
+       further analysis
+
+
+
+ 2004/01/16: Javier Rico & Pepe Flix
+
+   * manalysis/MPedPhotCalc.[cc,h]
+     - added
+     - new class for the evaluation of pedestals in units of photons
+       using the extracted signal from pedestal runs and calibration
+       constants defined in MCalibrate
+
+   * manalysis/AnalysisLinkDef.h,  manalysis/Makefile
+     - added entries for MPedPhotCalc
+
+   * macros/pedphotcalc.C
+     - added
+     - example on how to use MPedPhotCalc task
+
+
+
+ 2004/01/16: Markus Gaug
+
+   * mcalib/MCalibrationFits.h 
+     - removed and incorporated in MHCalibrationBlindPixel.h
+
+   * mcalib/MHCalibrationBlindPixel.[h,cc], mcalib/MHCalibrationConfig.h,
+     mcalib/MCalibrationBlindPix.h:
+     - incorporate Fit functions
+     - fixed a bug due to which DrawClone crashed when class was used 
+       in a compiled macro
+
+   * mcalib/MCalibrationCalc.cc, mcalib/MCalibrationPix.cc,
+     mcalib/MCalibrationBlindPix.cc, mcalib/MCalibrationPINDiode.cc,
+     mcalib/MCalibrationCam.cc, mcalib/MHCalibrationBlindPixel.cc,
+     mcalib/MHCalibrationPixel.cc:
+     - fixed the warns and errs in fLog's
+
+
+
+ 2004/01/16: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationCalc.cc
+     - TMath::Max() is no longer used because it did not compile in some 
+       systems for unkown reasons. I replaced it by a safer (and may be 
+       slower) code.
+     - Added calpix.SetFitValid();
+
+   * mhist/MHEvent.cc
+     - In MHEvent::Fill, fixed: second parameter of SetCamContent must 
+       be 1 in case of RMS:
+        case kEvtPedestalRMS:
+           fHist->SetCamContent(*(MCamEvent*)par, 1);
+
+
+
+ 2004/01/15: Abelardo Moralejo
+
+   * macros/starmc.C
+     - Added. Version of star showing new chain to get Hillas 
+       parameters (with Size calibrated in photons) from MC files.
+
+
+
+ 2004/01/15: Javier Rico
+	
+   * manalysis/MPedCalcPedRun.[h,cc]
+     - optimize the running time
+     - add (some) documentation
+     - correct treatment for the case of several input files 
+
+   * macros/pedvsevent.C
+     - added
+     - draw pedestal mean and rms vs event# for input pixel# and run 
+       file, and compares them to the global pedestal mean and rms 
+
+
+
+ 2004/01/15: Raquel de los Reyes
+
+   * mhist/MHCamEvent.cc, mhist/MHCamera.cc
+     - changed the MHCamEvent::SetupFill and MHCamera::GetBinError
+       functions to compute the estimation of the error of the
+       mean. It can be done calling to the function
+       MCamEvent::SetBit(MHCamera::kVariance) in the macro
+
+
+
+ 2004/01/15: Markus Gaug
+
+   * mhist/MHCamera.[h,cc]
+     - incorporate Thomas's changes
+     - replace void CreateProjection() by TH1D *Projection(const char*)
+
+   * macros/calibration.C
+     - replace MHCamera->Draw("proj") by MHCamera->Projection()
+     - produce better fits to the projection
+
+   * manalysis/MSimulatedAnnealing.[h,cc], 
+     mhist/MHSimulatedAnnealing.[h,cc]:
+     - moved to directory mtools
+     - MSimulatedAnnealing now inherits from TObject
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h,
+     mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MSimulatedAnnealing
+     - removed MHSimulatedAnnealing
+
+   * mtools/Makefile, mtools/AnalysisLinkDef.h:
+     - added MSimulatedAnnealing
+     - added MHSimulatedAnnealing
+
+
+
+ 2004/01/15: Thomas Bretz
+
+   * manalysis/AnalysisLinkDef.h:
+     - removed MCurrents
+
+   * mhist/MHCamera.[h,cc]:
+     - added member function Projection
+     - removed fYproj
+
+   * mreport/MReport*.*:
+     - added more comments
+
+
+
+ 2004/01/14: Markus Gaug
+  
+   * mtools/MFFT.[h,cc]
+     - new class to perform Fast Fourier Transforms
+
+   * mtools/Makefile
+   * mtools/ToolsLinkDef.h
+     - include MFFT
+
+   * manalysis/MExtractedSignalCam.h
+     - removed variables fNumHiGainSamples and fNumLoGainSamples
+     - function SetNumUsedFADCSlices replaced by SetUsedFADCSlices
+
+   * manalysis/MExtractSignal.cc
+     - updated call to SetUsedFADCSlices
+
+
+
+ 2004/01/14: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationCalc.cc:
+     - set pedestal rms per FADC slice to 0.01 counts in case it is 0.
+       This can happen (depending on camera simulation parameters), and
+       rms = 0 later resulted in the pixel being eliminated in the 
+       image cleaning.
+
+
+
+ 2004/01/14: Thomas Bretz
+
+   * Makefile:
+     - replaced old style Makefile.depend by directory specific
+       dependancy files
+       
+   * Makefile.rules:
+     - changed obsolete '.cc.o' style to newer style '%.o: %.c'
+     - added rule to make dependency files
+     - added rule to remove dependancy files.
+     - added rmdep as prerequisite to clean
+     - include dependency file
+
+   * mbase/Makefile, mcalib/Makefile, mcamera/Makefile,
+     mdata/Makefile, mfileio/Makefile, mfilter/Makefile,
+     mgeom/Makefile, mgui/Makefile, mhbase/Makefile, 
+     mhist/Makefile, mhistmc/Makefile, mimage/Makefile,
+     mmain/Makefile, mmc/Makefile, mmontecarlo/Makefile,
+     mpointing/Makefile, mranforest/Makefile, mraw/Makefile,
+     mreflector/Makefile, mreport/Makefile, mtemp/Makefile,
+     mtools/Makefile:
+     - removed clean-rule, use the one in Makefile.rules instead
+
+   * mreport/Makefile, mreport/ReportLinkDef.h:
+     - added MReportHelp
+
+   * mreport/MReportFileRead.cc:
+     - moved code from MReportHelp to new file
+     - removed usage of MReport class completely
+
+   * mfilter/MFGeomag.[h,cc]:
+     - fixed a bug which causes MFGeomag to fail if MARSSYS is not set
+     - changed the second loop from 0->1151 to 1152->2304
+     - removed dummy arrays used for reading
+     - output filename in case of 'file not found'
+     - removed obsolete data members
+     - removed obsolete Init function
+     - removed forbidden underscore from member variable
+     - changed wrong 0/1 in allocation of fResult into kFALSE/TRUE
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added new member function Open
+     - added new menu entry kFileOpen
+     - changed UpdatePSheader algorithm (the old one was much too slow)
+
+   * manalysis/MCurrents.[h,cc]:
+     - removed (old outdated)
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MCurrents
+
+
+
+ 2004/01/14: Wolfgang Wittek
+
+   * macros/ONOFFAnalysis.C:
+     - current version
+
+   * mhist/MHSigmaTheta.[h,cc]:
+     - replace MPedestalCam by MPedPhotCam
+
+   * manalysis/MPad.[h,cc], manalysus/MSigmabar.[h,cc],
+     manalysus/MSigmabarCalc.[h,cc], manalysus/MCT1PadONOFF.[h,cc],
+     manalysus/MCT1PadSchweizer.[h,cc], manalysus/MPadding.[h,cc]:
+     - replace MPedestalCam by MPedPhotCam
+
+   * manalysis/MPedPhotPix.[h,cc]
+     - uncomment SetRms()
+
+
+
+ 2004/01/13: Markus Gaug
+ 
+   * manalysis/MExtractSignal.h
+     - seems that the reduced light intensity of the CT1 Pulser
+       results in broader pulses -> Set Default time slices to [3,10]
+
+   * mhist/MHCamera.cc
+     - make Stat Window in option 'proj' bigger
+     - add comment line at beginning of Draw()
+
+   * mcalib/MHCalibrationBlindPixel.[h.cc]
+     - add Function DrawClone()
+     - fix bug in calculation of integral (GetIntegral("width"))
+     - restrict parameters tighter
+     - declare fit as not valid, if less than 100 events 
+       in single photo-electron peak
+
+   * mcalib/MCalibrationFits.h, mcalib/MHCalibrationBlindPixel.[h.cc]
+     - fit now with fixed normalization
+
+   * mcalib/MHCalibrationPixel.[h.cc]
+     - new function IsEmpty()
+     - Time fit accepted if ChiSquare less than 30. (instead of 20.)
+
+   * mcalib/MCalibrationPix.[h.cc]
+     - F-Factor corrected and added error
+     - Histograms not fitted if they are empty
+     - rejection criteria of fitted charges now > 5 PedRMS (instead 3)
+
+   * mcalib/MCalibrationCam.cc
+     - Square Root of Reduced Sigmas not taken, if they are < 0.
+     - Reduced Sigma / Charge squared replaced by reduced sigma / charge
+
+   * mcalib/MCalibrationCalc.cc
+     - Blind Pixel is not additionally treated as normal pixel any more
+     - Blind Pixel Draw replaced by DrawClone
+
+   * macros/calibration.C
+     - took out some unused code
+     - some default axis labelling corrected
+
+
+
+ 2004/01/13: Abelardo Moralejo
+
+   * manalysis/MMcPedestalCopy.cc
+     - added check of whether input file is a MC file before executing 
+       the PreProcess.
+
+
+
+ 2004/01/13: Wolfgang Wittek
+
+   * macros/ONOFFAnalysis.C, macros/ONAnalysis.C:
+     - change macro to handle also MC events with finite sigmabar
+
+   * manalysis/MPadOn.[h,cc]:
+     - deleted, is replaced by MPad
+
+   * manalysis/MPadOnOFF.[h,cc]:
+     - deleted, is replaced by MPad
+
+   * manalysis/MPad.[h,cc]:
+     - new class, replacing MPadON and MPadONOFF
+     - handle also MC events with finite sigmabar
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - replace MPadON and MPadONOFF by MPad
+
+
+
+ 2004/01/13: Thomas Bretz
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - implemented new member function GetRunTypeStr
+
+   * Changelog.03: 
+     - added (contains entries of 2003)
+
+   * Changelog:
+     - removed entries of 2003
+
+   * mfilter/MFGeomag.cc:
+     - simplified open/close of input files
+
+   * manalysis/MEventRate.[h,cc], manalysis/MEventRateCalc.cc:
+     - added some comments
+     - added new member function GetError
+
+   * Makefile:
+     - updated 'make dox' output for convinience
+
+   * macros/dohtml.C:
+     - do not print Info's
+     - added mcamera
+     - added mpointing
+     - added mreport
+
+   * mreport/MReportCurrents.cc, mreport/MReportDAQ.cc:
+     - removed some obsolete comments (these comments confused THtml)
+
+   * manalysis/MCameraData.[h,cc], mfileio/MCT1ReadAscii.[h,cc],
+     mfileio/MCT1ReadPreProc.[h,cc], mfilter/MFCT1SelBasic.cc,
+     mfilter/MFSelBasic.cc, mhist/MHCamera.cc, mhist/MHEvent.[h,cc],
+     mimage/MImgCleanStd.[h,cc], mimage/MImgCleanTGB.[h,cc],
+     mmain/MAnalysis.cc, mmain/MEventDisplay.cc:
+     - replaced MPedestalCam by MPedPhotCam
+     - removed some obsolete includes
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MLogPlugin
+     - added MLogHtml
+
+   * mbase/MLog.[h,cc]:
+     - added use of plugins
+
+   * mbase/MLogPlugin.[h,cc], mbase/MLogHtml.[h,cc]:
+     - added
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added a Save-As dialog
+
+
+
+ 2004/01/12: Thomas Bretz
+
+   * macros/rootlogon.C:
+     - added mcamera to include path
+     - added mpointing to include path
+     - added mreport to include path
+     
+   * mbase/MLog.cc:
+     - updated my eMail address
+     
+   * mbase/MParContainer.h:
+     - added Read member function
+     
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed size of ps-paper
+     - added a user defined bottom line to the ps-files
+     - added name (currently unused)
+     - added title (used as possible bottom line in ps-file)
+     
+   * mraw/MRawRunHeader.cc:
+     - added some comments
+
+   * status.cc:
+     - set name of input as bottom line of status display
+
+
+
+ 2004/01/12: Abelardo Moralejo
+
+   * mimage/MStereoPar.cc
+     - fixed mistake: now fSourceY = scale1*hillas1.GetMeanY() + ...
+       instead of         fSourceY = scale2*hillas1.GetMeanY() + ...
+       Bug had no effect unless scale1 != scale2 (-> telescopes of 
+       different size).
+
+
+
+ 2004/01/12: Markus Gaug
+
+   * manalysis/MExtractSignal.[h,cc]
+     - take out some uncommented code 
+     - replace logainshift by two independent variables: 
+       logainfirst, logainlast
+     - because in most data, maximum occurs in slice 4, shift default 
+       from slices 4-9 to slices 3-8.
+
+   * manalysis/MExtractedSignalPix.[h,cc]
+     - took out some uncommented code
+     - new initializers: instead of -1. now 99999.9
+
+
+
+ 2004/01/09: Markus Gaug
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - take out 1-dim histos because we can use 
+       the projections in MHCamera (s.b.)
+
+   * mcalib/MHCalibrationBlindPixel.h
+     - make the fit by default quiet
+
+   * mcalib/MHCalibrationPixel.[h,cc]
+   * mcalib/MCalibrationPix.[h,cc]
+     - Ranges of time slices stored independently for HiGain and LoGain
+       in order to allow consecutive checks
+
+   * mhist/MHCamera.[h.cc]
+     - add the possibility to call a Draw("proj") which will 
+       draw a Y-Projection of the histogram
+
+   * macros/calibration.C
+     - apply the drawing of the projections and fit them
+
+   * mcalib/MCalibrationCalc.cc
+     - catch the possibility of a calibration file, 
+       unintendedly being a pedestal or cosmic file. 
+       Program now exits with an error before doing the fits
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - fixed a bug in calculation of fFitValid. 
+       before, a call to IsFitValid() always returned false
+
+
+
+ 2004/01/09: Javier Lpez
+
+   * macros/bootcampstandardanalysis.C
+     - added new macro that holds the main scheleton discussed in the 
+       december bootcamp in Wuerzburg. It runs first over a pedestal
+       run, then over a calibration run, again over the pedestal run
+       to compute de pedestal in number of photons and finally over a
+       data run to calibrate the data.
+
+
+
+ 2004/01/06: Sebastian Raducci
+   
+   * manalysis/MArrivalTime.[h,cc]
+     - added new method to calculate photon arrival times. It uses the
+       TSpline5 Root Class to interpolate the Fadc Slices. The time is
+       the abscissa value of the absolute maximum of the interpolation
+     - added new method to find clusters with similar arrival times.
+       For now it's a preliminary version. It simply search for adiacent
+       pixels having the same arrival time (color).
+
+   * manalysis/MArrivalTimeCalc.[h,cc]
+     - modified the Process() method according to the changes in the
+       Arrival Time Cointainer
+
+   * mmain/MEventDisplay.cc
+     - added new tab in the camera event display to show the arrival
+       time. This arrival time is calculated with the spline method
+     - the old Arrival Time pad now it's called Max Slice Idx, because
+       it's only the index of the slice with the max content.
+   
+   * mhist/MHEvent.[h,cc]
+     - added new fType in te enumeration to handle the arrival time
+       histos
Index: branches/Mars_McMismatchStudy/Changelog.05
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.05	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.05	(revision 17960)
@@ -0,0 +1,8414 @@
+Please  do  not write behind the end of line tag so that it is  possible
+to   send  a   Changelog   file  to  a  line  printer  directly.  Thanks.
+
+For your entries please follow EXACTLY this style:
+
+_yyyy/mm/dd_[Your Name]
+_
+___*_filename:
+_____-_description
+_
+___*_filename2, filename3:
+_____-_description
+_
+_
+_
+
+While an underscore is a placeholder for a white-space or an empty line.
+
+                                                 -*-*- END OF LINE -*-*-
+
+ 2005/12/21 Thomas Bretz
+
+   * mbase/MEnv.cc:
+     - enhanced grey levels to eight
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - allow to open a new tab from the file menu
+
+   * mbase/MTime.[h,cc]:
+     - added algorithm to calculate week
+
+
+
+ 2005/12/20 Daniela Dorner
+
+   * datacenter/macros/checkfilesavail.C:
+     - fixed bug
+
+
+
+ 2005/12/14 Daniela Dorner
+
+   * datacenter/scripts/copyscript:
+     - fixed bug
+
+
+
+ 2005/12/13 Daniela Dorner
+
+   * datacenter/scripts/copyscript:
+     - added updating of catalogfile
+
+
+
+ 2005/12/12 Daniela Dorner
+
+   * datacenter/scripts/rmlocks:
+     - fixed condition for removing lock-file
+
+   * datacenter/scripts/dowebplots:
+     - improved new procedure
+     - added removing of old files
+     - added documentation
+
+   * datacenter/scripts/linkmc:
+     - improved handling of directories
+     - added new mode
+     - added documentation
+     - simplyfied check for C and P link
+
+
+
+ 2005/12/12 Thomas Bretz
+
+   * mbase/MEnv.[h,cc]:
+     - added new Setter functions
+     - added a Clone function (TEnv cannot be streamed)
+     - added a data member to store the filename because fRcName cannot
+       be accessed
+
+   * mbase/MTime.[h,cc]:
+     - added Getter DayofYear()
+     - added Getter Week()
+     - added Getter IsLeapYear()
+
+   * mjobs/MDataSet.cc:
+     - simplified reading the catlog file by using TString::Tokenize
+
+   * mtools/MCalendar.[h,cc]:
+     - added
+
+
+
+ 2005/12/06 Daniela Dorner
+
+   * datacenter/scripts/linkmc:
+     - added (script to link the mc-files into a YYYY/MM/DD structure)
+
+   * datacenter/scripts/mcsequences: 
+     - added (script to write sequencefiles for the mc)
+
+   * datacenter/scripts/processmcsequences: 
+     - added (script to run callisto and star for the mc)
+
+
+
+ 2005/12/06 Thomas Bretz
+
+   * mbase/MEnv.[h,cc]:
+     - added new function to get fillstyle by name
+     - added new function to get attributes of a TPave
+
+   * mbase/MTime.cc:
+     - fixed layout of a comment
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added a function to calc upper limits
+     - exchaged some GetListOfFunctions()-Remove() with SetName
+
+   * mcamera/Makefile, mcamera/CameraLinkDef.h:
+     - added MCameraTD, MCameraTH and MCameraRecTemp
+
+   * showplot.cc:
+     - fixed a bug which caused trouble if only a filename was given
+
+   * mastro/MAstro.h:
+     - added conversion constant to convert parsec to meter
+
+   * mcamera/MCameraHV.h:
+     - only layout changes
+
+   * mcamera/MCameraRecTemp.[h,cc], mcamera/MCameraTD.[h,cc],
+     mcamera/MCameraTH.[h,cc]:
+     - removed weired obsolste operators (which won't work at all)
+     - fixed calculation of max and min value
+     - replaced the nonsense TArrayS by TArrayC because the contents is
+       just a byte
+
+   * mreport/MReportCC.cc:
+     - fixed the 
+
+   * ganymed.cc:
+     - fixed compilation of path to datasets
+
+
+
+ 2005/12/01 Thomas Bretz
+
+   * readdaq.cc:
+     - allow different file names
+
+   * mbase/MLog.[h,cc]:
+     - replaced preprocessor directive by const data member
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - implemeted a fix reading the pixel assignment table between
+       RunNumber 53300 and RunNumber 68754. Three pixelassignments were
+       wrong.
+
+   * mbase/MDirIter.cc:
+     - removed special treatment of ?-character
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added new class
+
+   * mimage/MHillas.cc:
+     - changed atan2-output in Print to same convention as used
+       in MGeomCam
+
+   * mjobs/MJCalibrateSignal.cc:
+     - modified replacement rule for output file names
+
+   * mbase/MStatusDisplay.cc:
+     - fixed initial size
+     - automatically call SetFrameBorderMode for each new canvas
+
+   * mjobs/MSequence.cc:
+     - updated rule used to build file names
+
+   * mgui/MCamEvent.[h,cc]:
+     - implemented new member function GetCameraRMS
+     - implemented new member function GetCameraStat
+
+   * mraw/MRawFileRead.[h,cc]:
+     - implemented new I/O scheme
+
+
+
+ 2005/11/30 Thomas Bretz
+
+   * showplot.cc:
+     - fixed some warnings
+
+   * mmc/MMcFadcHeader.[hxx,cxx]:
+     - added class description in the correct style
+     - derived from MCamEvent
+     - increased Class Version
+     - added GetPixelContent
+
+   * mmc/Makefile:
+     - added mgui 
+
+   * datacenter/macros/plotdb.C:
+     - call SetFrameBorderMode for each new pad
+
+
+
+ 2005/11/29 Thomas Bretz
+
+   * mmain/MEventDisplay.cc:
+     - added a MContinue to be setup by mars.rc to the tasklist to
+       allow to choose events
+
+   * mars.rc:
+     - added an example how to use the new cut
+
+
+
+ 2005/11/28 Thomas Bretz
+
+   * callisto.cc, ganymed.cc, mars.cc, merpp.cc, readdaq.cc, 
+     readraw.cc, showlog.cc, showplot.cc, sponde.cc, star.cc:
+     - fixed a bug in displaying the startup message which prevented
+       the compilation date from beeing displayed
+     - added abbreviations for calling some programs (see NEWS)
+
+   * mastro/MAstro.[h,cc]:
+     - added function to calc date of easter
+
+   * mbase/MEnv.[h,cc]:
+     - added function to support some attributes (TAtt*)
+
+   * mbase/MTime.[h,cc]:
+     - added support for locales in Set/GetStringFmt
+     - added function to calc date of easter
+
+   * mjobs/MJCut.cc:
+     - output is called "Hadronness" not "MHadronness"
+
+   * mjtrain/MJTrainDisp.cc, mjtrain/MJTrainEnergy.cc:
+     - fixed bug which caused the traincuts to be ignored
+
+
+
+ 2005/11/25 Thomas Bretz
+
+   * datacenter/macros/fillsignal.C:
+     - added filling of PulsePos used for seeting the extractor window
+
+   * datacenter/macros/plotdb.C:
+     - added new tabs for new columns
+
+   * mcamera/CameraLinkDef.h, mcamera/Makefile:
+     - added new classes MCameraTH, MCameraTD and MCameraRecTemp
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]:
+     - added some const-qualifiers
+
+   * mreport/MReportCC.[h,cc]:
+     - updated to allow reading new CC reports 
+
+   * merpp.cc:
+     - added contentent of new CC report to CC output tree
+
+
+
+ 2005/11/25 Daniel Mazin (2005/11/02)
+
+   * mreflector/MRflEvtHeader.h
+     - added parameters first interaction point, telescope phi and theta,
+       fitted quantities from CORSIKA (number of particles in the shower 
+       maximum, t0, tmax, chi2), fraction of electrons, muons and other 
+       particles. Added getters and setters.
+
+   * mfileio/MReadRflFile.cc
+     - filled in the variables above
+
+
+
+ 2005/11/25 A. Moralejo (2005/10/14)
+
+   * mreflector/MRflEvtHeader.h
+     - added parameters: energy, versor of primary's momentum and core 
+       position on ground. Added getters and setters.
+
+   * mfileio/MReadRflFile.cc
+     - filled in the variables above
+
+
+
+ 2005/11/25 Toni Coarasa (09/09/2005)
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     fixed a bug in the calculation of the high-gain times:
+     They were all shifted by the same amount "fHiGainFirst". This
+     caused an offset in the order of the position of the left border of
+     the extraction window in the times calculated from high-gain and 
+     from low-gain. The bug was there since 30.1.2005.
+
+
+
+ 2005/11/25 Daniela Dorner
+
+   * datacenter/scripts/runcallisto, runstar, runganymed:
+     - removed some not-needed logging outpu
+
+   * datacenter/scripts/dowebplots:
+     - changed algorithm to create gifs/pngs from the root files
+
+   * datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/macros/checkfilesavail.C:
+     - fixed problem with manually inserted sequences
+
+   * datacenter/scripts/movingrawfiles, movingsubsystemfiles:
+     - added (scripts to move files from old (LP) to new structure (DC)
+
+   * datacenter/macros/fillsignal.C, setupdb.C:
+     - added 2 new columns (fPulsePosCheckMean, fPulsePosCheckRms)
+
+
+
+ 2005/11/22 Thomas Bretz
+
+   * macros/train/traindisp.C:
+     - added a comment
+
+   * mdata/MDataFormula.cc:
+     - fixed along outstanding bug. Because TFormula had no name
+       some axis tick marks disappeared randomly
+     - fixed a typo (Add instead of Remove)
+
+   * mfbase/MFEventSelector.cc:
+     - also reset fSelRatio if totalnumber of events from file.
+
+   * mranforest/MHRanForestGini.[h,cc]:
+     - added a TPaveText containing text information to output
+
+   * mranforest/MRanForest.[h,cc]:
+     - replaced type of fClassify by Bool_t
+     - improved handling of allocated memory (still to be checked
+       further)
+     - added Print function
+
+   * mranforest/MRanForestCalc.[h,cc]:
+     - added another training type
+     - added some comments
+     - set version number to 1 to allow writing it to ganymed output
+     - added Print function
+     - Use GetEntriesFast and UncheckedAt in Process for
+       single tree forests
+
+   * mranforest/MRanTree.[h,cc]:
+     - replaced type of fClassify by Bool_t
+     - added Getter for fClassify
+
+   * mjtrain/MJTrainDisp.cc, mjtrain/MJTrainEnegry.cc:
+     - renamed TrainSingleRF to TrainRegression
+
+   * mjtrain/MJTrainDisp.cc:
+     - replaced training variable (hypot(dist,dca)) by dist
+
+   * mjtrain/MJTrainRanForest.cc:
+     - added some comment
+     - adde more log output to WriteDisplay
+
+   * mjtrain/MJTrainSeparation.cc:
+     - updated output
+     - made it work properly
+
+   * mjobs/MJCut.cc:
+     - added ClacDisp task to output
+
+   * mjobs/MJPedestal.cc:
+     - removed an obsolete include
+
+
+
+ 2005/11/21 Thomas Bretz
+
+   * mjtrain/*, macros/train/*.C:
+     - added new class to train the random forest
+
+   * Makefile:
+     - added mjtrain
+
+   * macros/dohtml.C, macros/rootlogon.C:
+     - added mjoptim and mjtrain
+
+   * mbase/MParList.[h,cc]:
+     - fixed copy constructor (it was crashing due to the
+       non-initialized lists)
+
+   * mhbase/MBinning.[h,cc]:
+     - renamed SetEdges to SetEdgesLin (SetEdges now is just and
+       abbreviation)
+     - added a check for the number of bins to all SetEdges*
+
+   * mhbase/MH3.cc:
+     - enable grid
+
+   * mhbase/MHMatrix.[h,cc]:
+     - new member function Addcolumns taking a TCollection
+
+   * mhist/MHHadronness.cc:
+     - align hadronnes into [0,1]
+
+   * mjobs/MDataSet.[h,cc]:
+     - call SetOwner for fSequencesOn and fSequencesOff
+     - added Copy member function
+
+   * mjobs/MJCut.[h,cc]:
+     - added new TaskEnv "CalcDisp" for a disp estimator
+
+   * mjoptim/MJOptimizeDisp.cc:
+     - fixed typo in a title
+     - added a new histogram showing theta-sq versus size
+
+   * mranforest/MHRanForestGini.[h,cc]:
+     - revised to display more information
+     - exchanged pointers to TGraph by objects
+
+   * mranforest/MRanForest.[h,cc]:
+     - replaced some weired copy of the train matrix by a direct access
+     - revised output
+     - pipe error/resolution to tree
+
+   * mranforest/MRanForestCalc.[h,cc]:
+     - copied code from MRFEnergyEst
+     - allow to set a name for the output container
+     - set numtry to 0 (auto)
+     - set ndsize to 1 (there is no auto mode)
+     - introduced variable for number of obsolete parameters
+
+   * mranforest/MRanTree.h:
+     - new data member to store resolution/error
+
+   * mranforest/Makefile, mranforest/RanForestLinkDef.h:
+     - removed MRFEnergyEst 
+     - added MRanForestCalc
+
+   * mtools/MTFillMatrix.[h,cc]:
+     - added the possibility to use PreCuts befre filling the matrix
+     - added ReadEnv
+
+   * ganymed.rc, ganymed_onoff.rc:
+     - changed to new cuts trained with 1ES1218 and Crab-data
+       for maximum sigma*log10(excess)
+     - added new lines for CalcDisp
+
+
+
+ 2005/11/18 Thomas Bretz
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - fixed a problem with using X more than once in the formula
+
+   * ganymed.cc:
+     - improved UsageInfo
+
+   * macros/optim/optimdisp.C, macros/optim/optimenergy.C:
+     - added some  more examples
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - updated authors
+
+   * mbase/BaseIncl.h:
+     - added TArrayD
+
+   * mbase/MLogHtml.cc:
+     - added some includes suggested by Ching-Cheng
+
+   * mbase/MMath.[h,cc]:
+     - added some function for the analytical result of special fits
+
+   * mfilter/MFEnergySlope.[h,cc]:
+     - some updated to make it better fit into Mars
+     - upadted the user interface
+
+   * mhflux/MHEnergyEst.[h,cc]:
+     - updated to let everything fit what is commonly used. This
+       was just discussed with Abelardo
+     - some updates to the plots
+
+   * mjobs/MDataSet.cc:
+     - added some includes suggested by Ching-Cheng
+     - upadted some output
+     - remove whitespaces from read TString
+
+   * mmc/MMcCorsikaRunHeader.h:
+     - added new Getter
+
+   * mranforest/MRanForest.cc:
+     - some updates to Grow-output
+
+
+
+ 2005/11/16 Daniela Dorner
+
+   * datacenter/scripts/doqualityplots:
+     - added (putting output of plotdb.C) in the web 
+
+   * datacenter/macros/plotdb.C:
+     - return 0 in case of failure and 1 in case macro finished without
+       problem
+
+
+
+ 2005/11/16 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - added new plot for camera inhomgeneity
+
+
+
+ 2005/11/16 Daniela Dorner
+
+   * datacenter/macros/fillstar.C, setupdb.C:
+     - added new variable fInhomogeneity
+
+
+
+ 2005/11/15 Thomas Bretz
+
+   * macros/optim/optimdisp.C, macros/optim/optimenergy.C,
+     macros/optim/rfenergyest.C, macros/optim/optimwobble.C:
+     - added some more comments
+     - updated
+
+   * mtools/MTFillMatrix.[h,cc]:
+     - added the possibility to use PreCuts like in MJOptim
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - implemented long awaiting E^2dN/dE plot
+     - updated displaying result (formula)
+
+   * msql/MSQLServer.[h,cc]:
+     - added output of database name to GetName
+
+
+
+ 2005/11/14 Daniela Dorner
+
+   * datacenter/macros/insertsequence.C:
+     - added possibility to set source name in sequence file
+
+
+
+ 2005/11/14 Thomas Bretz
+
+   * MRFEnergyEst.[h,cc]:
+     - changed to allow for new regression method
+
+   * MRanForest.[h,cc]:
+     - taken TH's implementation of the RF regression 
+       + updated includes
+       + added fUserVal
+       + removed ReadRF, WriteRF -- obsolete
+
+   * MRanForestGrow.[h,cc]:
+     - took out setting up the growing of the forest from this task
+       (currently it is done by MRanForest directly)
+     - adapted to changes in other classes as TH did.
+
+   * MRanTree.[h,cc]:
+     - changes taken from TH
+       + added copy-constructor
+       + upadted to allow regression
+
+   * Makefile, RanForestLinkDef.h:
+     - took out MRanForestCalc and MRanForestFill temporarily
+
+   * macros/optim/rfenergyest.C:
+     - added
+
+   * mhbase/MHMatrix.[h,cc]:
+     - added new constructor taking a TMatrix and a MDataArray as
+       argument
+
+
+
+ 2005/11/12 Daniela Dorner
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed typo (be careful: due to this typo the values for 
+       L2TriggerTable in the DB and in the sequence files may be wrong)
+     - fixed bug introduced on 29th sept
+
+   * datacenter/scripts/rmlocks:
+     - fixed condition for removing lock-file
+
+   * datacenter/macros/filldotrun.C:
+     - added new arehucas version
+
+   * datacenter/macros/fillsignal.C,setupdb.C:
+     - added new variable (fPulsePosMean, fPulsePosRms)
+
+
+
+ 2005/11/10 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - added SignalInner/Outer
+     - set background color to White
+
+   * mhflux/MHEnergyEst.cc:
+     - added some comments
+
+   * mpointing/MSrcPosCorrect.[h,cc]:
+     - allow overwriting of dx,dy from resource file
+
+   * mreport/MReportTrigger.cc:
+     - fixed a typo of the indentation (two commands in one line)
+
+   * mjobs/MDataSet.cc:
+     - fixed reading the source catalog. Only as many chars
+       as the requested source name had were compared
+
+   * mjobs/MJCut.cc:
+     - print out the source coordinates in addition to its name
+
+   * mpointing/MPointingPos.[h,cc]:
+     - added Print function
+
+   * ganymed_onoff.rc:
+     - let the exponential fit fit all the background (decoupled
+       sclae and background-fit reagion)
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - changed the background fit in the case of a ThetaSq function
+       from a polynomial to a exponential
+
+
+
+ 2005/10/11 Thomas Bretz
+
+   * mbase/MMath.cc:
+     - fixed a typo in SignificanceLiMaExc
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added a comment 
+     - increased ClassDef
+
+   * mhflux/MHAlpha.cc:
+     - correctly use SignificanceExc for bins instead of Significance
+
+
+
+ 2005/10/11 Daniela Dorner
+
+   * datacenter/macros/setupdb.C:
+     - added column in Ganymed
+
+
+
+ 2005/10/10 Thomas Bretz
+
+   * mbase/MMath.[h,cc]:
+     - added new function SignificanceLiMaExc
+
+   * mbase/MTime.[h,cc]:
+     - added new Setter SetAxisTime
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - fixed some format in output
+
+   * mhcalib/MHCalibrationCam.cc:
+     - fixed a typo
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added new data member fSiginificanceExc
+
+
+
+ 2005/10/01 Thomas Bretz
+
+   * mjobs/MDataSet.[h,cc]:
+     - implemented two new options for constructor allowing to
+       change the default path to image data and sequence files
+     - fixed some typos
+
+   * mjobs/MSequence.[h,cc]:
+     - implemented new light condition "day" for completeness
+
+   * ganymed.cc:
+     - implemented two new options --ind and --ins
+
+   * datacenter/scripts/runganymed:
+     - added new option --ind= to ./ganymed
+
+
+
+ 2005/10/01
+
+   * RELEASE 0.9.4.2
+
+
+
+ 2005/09/30 Thomas Bretz
+
+   * callisto.rc, callisto_MarApr05.rc:
+     - replaced ScaleFactor by FileNameScale
+
+   * callisto_Dec04Jan05.rc:
+     - changed ScaleFactor from 0.919 to 0.852
+
+   * datacenter/macros/fillstar.C:
+     - new reference values for caluclating PSF
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - added new option to read additional ScaleFactors from File
+
+   * mjobs/MJStar.cc:
+     - set maxima/minima for rms and currents plot
+     _ really display rms (former display was incorrectly Pedestal
+       instead of its rms
+
+   * mjobs/MJCalibration.cc:
+     - fixed a small bug in the display of unsuitable pixels. 
+       (LoGainBlackout haven't been displayed, and previously excluded
+        pixels were wrong)
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - small simplifications in GetPixelContent
+
+   * mmuon/MHMuonPar.cc:
+     - new reference line for 100%
+
+   * mpointing/MPointingDevCalc.cc:
+     - reset counter in PreProcess
+
+   * resources/calibration.rc:
+     - new file
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - implemented a new treatment of "no-signal". If a pixel
+       presumably contains no signal as detected by the arrival time
+       interpolation its interpolated signal is overwritten with
+       a gaus. The gaus mean and rms are taken from the corresponding
+       MPedPhotCams
+
+
+
+ 2005/09/29 Daniela Dorner
+
+   * datacenter/macros/insertsequence.C:
+     - added (macro to insert manually changed sequences into the DB)
+
+   * datacenter/scripts/insertsequences:
+     - added (script to call insertsequence.C)
+
+   * datacenter/scripts/rmlock:
+     - added (script to remove lockfiles after 13 hours)
+
+
+
+ 2005/09/27 Thomas Bretz
+
+   * mbase/MTime.[h,cc]:
+     - added function GetMoonPhase
+     - added function GetMoonPeriod
+     - added function GetMagicPeriod
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]:
+     - fixed some wrong text alignment in output (therfor added
+       new member function)
+
+   * mmuon/MHMuonPar.[h,cc]:
+     - commented out old obsolete member function
+     - updated reference lines
+
+   * mmuon/MHSingleMuon.[h,cc]:
+     - if(abs(x-m)<x0) instead of if(x0<x-m && x0>x+m)
+     - changed the binning of the time histogram such that 
+       there is a bin symmetric to 0
+     - reduced the start value sigma from 0.3 to 0.2
+     - added new member function CalcSize
+
+   * mmuon/MMuonSearchPar.[h,cc]:
+     - adapted some variable names to standard
+     - increased version number due to new variables in header
+     - added corresponding comment
+
+   * mmuon/MMuonCalibParCalc.cc:
+     - replaced wrong calculation of size via integral by
+       new member function CalcSize
+
+   * datacenter/macros/fillstar.C:
+     - updated reference values
+
+
+
+ 2005/09/26 Markus Meyer
+
+   * mmuon/MMuonSearchPar.[cc,h]:
+     - Mean arrival time of core Pixels is calculated
+
+   * mmuon/MHSingleMuon.[cc,h]:
+     - new histogram fHistTime (TH1), which contents difference
+       of the arrival time between Mean arrival time of the core
+       pixels and every pixel in the margin around the circle.
+       The histogram is fitted by an gaussian distribution.
+     - fHistPhi is now a TProfile
+     - fHistPhi is only filled with pixels with an arrival time  
+       of < 2 sigma difference to the fitted mean value
+
+   * mmuon/MMuonSetup.cc:
+     - fThresholdArcPhi is changed to 5 phe
+   
+   * mmuon/MHMuonPar.cc:
+     - for the reference values to MC, the integral over the mean
+       values of the different radius bins is taken again
+
+
+
+ 2005/09/22 Daniela Dorner
+
+   * datacenter/macros/fillsignal.C, setupdb.C:
+     - added new value (fMeanSignalInner/Outer)
+
+   * datacenter/macros/fillcalib.C, setupdb.C:
+     - changed precision of fArrTimeRmsInnser/Outer
+
+
+
+ 2005/09/22 Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.cc:
+     - implemented a new treatment for the time information developed
+       by S.Ruegamer, this should give much better response than the
+       old very primitive algorithm. This is especially important
+       for bad pixels due to bright stars as Ceta-Tauri
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added new member function SeorNeighbors which sorts the neighboring
+       pixels clockwise
+     - call SortNeighbors in InitGeometry so that we always get a geometry
+       with clockwise sorted pixels.
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - new values for the spark-event-cut
+
+   * macros/optim/optimonoff.C:
+     - some typos fixed
+
+   * mjobs/MJSpectrum.cc:
+     - required missing MEnergyEst from ganymed.root... fixed.
+
+   * mreport/MReportStarguider.cc:
+     - made aware of new format 20050829-0
+
+   * msignal/MSignalCam.cc:
+     - added a check for unmapped pixels to case 6 and 7 in
+       GetPixelContent
+
+
+
+ 2005/09/21 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - changed some resolution values
+
+   * datacenter/macros/fillsignal.C:
+     - started support to fill mean interpolated signal into DB
+
+   * mfileio/MWriteRootFile.cc:
+     - added a FIXME comment
+
+   * mhvstime/MHSectorVsTime.h:
+     - added new function GetGraph
+     - increased version number (increase was forgotten some time ago)
+
+   * mimage/MImgCleanStd.cc:
+     - added some comments
+     - replaced IsPixelUsed/Core(int) by [int].IsPixelUsed/Core for
+       acceleration (some obsolete range checks are skipped)
+     - now the core status is explicily set in any case
+     - removed an obsolete range check in the ring cleaning
+     - the range checks became obsolete because with the new format
+       all pixels must exist.
+
+   * mjobs/MDataSet.cc:
+     - sort the sequence numbers instead of the file names (the file
+       name sort might be biased due to different paths)
+
+   * mjobs/MJob.[h,cc]:
+     - new static functions: SortArray
+
+   * mjobs/MSequence.cc:
+     - sort run-numbers as the sequences are sorted in MDataSet
+
+
+
+ 2005/09/20 Daniela Dorner
+
+   * datacenter/scripts/runganymed:
+     - removed writing of summary file
+
+
+
+ 2005/09/16 Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.cc:
+     - removed obsolete artificial add of missing (zero supressed)
+       pixels
+     - removed obsolete MArrayD which stored the result of the
+       interpolation but was never used
+
+   * mcalib/MCalibrateData.cc :
+     - removed an obsolete calibConv=-1 in case the pixel is unsuitable
+       (UpdateConversionFactors)
+     - improved warning output in case the conv factor is out-of-range
+
+   * mcalib/MCalibrateRelTimes.cc:
+     - reordered the algorithm for the time calibration to make it faster
+     - replaced if(IsLoGainUsed()) by the new function GetArrivalTime in
+       MArrivalTimePix
+
+   * msignal/MArrivalTimePix.h:
+     - new getter function GetArrivalTime returning the arrival time
+       depending on the flag IsLoGainUsed()
+
+   * msignal/MSignalPix.h:
+     - removed '!' from fRing data member to allow the status unmapped
+       to be stored after the badpixel treatment
+     - increased version number
+     - removed some obsolete comments
+     - added Copy() member function
+
+   * mgeom/MGeomCam.[h,cc], mgeom/MGeomPix.h:
+     - new member function GetAngle
+
+   * mhvstime/MHSectorVsTime.[h,cc]:
+     - updated comments
+     - increased version number
+     - added new member function GetGraph
+
+   * msignal/MSignalPix.cc:
+     - updated comments
+     - updated Print()
+
+
+
+ 2005/09/16 Daniela Dorner
+
+   * datacenter/macros/filldotrun.C:
+     - added new arehucas version
+
+
+
+ 2005/09/12 Thomas Bretz
+
+   * callisto.cc:
+     - exchanged order of random and peak-search extracted pedestal in the
+       call of job4 (MJCalibrateSignal). It wasn't exchanged correctly when 
+       the order of pedestal calculation was exchanged.
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - replaced return kFALSE in Processing by return kERROR to allow
+       the automatic analysis to detect this kind of fatal errors
+
+   * mbadpixels/MBadPixelsTreat.cc:
+     - fixed abug in the treatment of times. The indices of the neighbors
+       have never been requested but the index of the loop (0-5) instead.
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - a simple improvement to the usage of DrawClonePad.
+
+   * mgui/MCamEvent.[h,cc]:
+     - new member function GetCameraMean
+
+   * mhflux/MHThreshold.h:
+     - fixed a typo in a comment
+
+   * mhvstime/MHSectorVsTime.cc:
+     - fixed a typo in the gsDefName
+
+   * mjobs/MDataSet.cc, mjobs/MSequence.cc:
+     - stop the loop evaluating sequence/run numbers is seqeunce in NaN
+
+   * mjobs/MJCut.cc:
+     - expand path-name to allow ~ in path name
+
+   * mpedestal/MPedPhotCam.cc, msignal/MSignalCam.cc:
+     - replaced sqrt(pixratio) by PixRatioSqrt
+
+   * msignal/MSignalCam.h:
+     - changed order of functions
+
+
+
+ 2005/09/12 Daniela Dorner
+
+   * datacenter/scripts/copyscript:
+     - fixed small bug in change of 2005/08/29
+
+
+
+ 2005/09/09 Thomas Bretz
+
+   * mgeom/MGeomPix.cc:
+     - fixed a problem with incorrectly set bits for outermost
+       pixels (introduced with the latest changes)
+
+   * mgeom/MGeomCam.[h,cc]:
+     - removed some obsolete comments
+
+
+
+ 2005/09/09 Daniela Dorner
+
+   * datacenter/scripts/runcallisto:
+     - fixed problem in handling of filenames
+
+
+
+ 2005/09/06 Thomas Bretz
+
+   * Makefile.conf.general:
+     - added libASImage
+
+   * mgeom/MGeomCam.[h,cc]:
+     - clone the whole container in any case not only if it is 
+       different from MGeomCam
+     - unified the non-default and default constructor
+
+   * mgeom/MGeomPix.[h,cc]:
+     - initialize neighbors with empty values in constructor
+     - added some more default arguments
+
+   * mhist/MHCamera.[h,cc]:
+     - implemented new Draw-options "nopal", "abscontent"
+     - implemented more accurate handling of transparency
+     - new flags kNoScale and kNoUnused
+     - changed private stuff to protected
+
+   * mtools/Makefile, mtools/ToolsLinkDef.h:
+     - added new "tool" MagicJam
+
+   * mtools/MagicJam.[h,cc]:
+     - added
+
+   * mtools/jam/*.jam:
+     - games for Magic Jam
+
+
+
+ 2005/08/29 Daniela Dorner
+
+   * datacenter/scripts/insertdatasets, 
+     datacenter/macros/insertdataset.C:
+     - added handling of the new fiels fComment in the table DataSets
+
+   * datacenter/macros/setupdb.C:
+     - adapted to changes in the table DataSets
+
+   * datacenter/scripts/copyscript:
+     - added copying of the file to the directory 
+       /magic/datacenter/totape 
+
+   * datacenter/scripts/fillganymed:
+     - small bugfixes
+
+   * datacenter/macros/fillstar.C:
+     - fixed bug in change of 25.7.
+
+
+
+ 2005/08/28 Daniela Dorner
+
+   * datacenter/scripts/dodatacheck:
+     - added 'find-todofile-algorithm' to this script to accelerate the 
+       process of datacheck
+     - changed call of filldotraw.C
+
+   * datacenter/macros/getdolist.C:
+     - added fDataCheckDone for the option to get many todofiles to 
+       accelerate the process of datacheck
+
+   * datacenter/macros/filldotrun.C:
+     - added check: if a run is a testrun, the flag for datacheck is 
+       set to 'not to be done'
+
+   * datacenter/macros/filldotraw.C:
+     - removed database name from the queries
+
+   * datacenter/macros/setupdb.C:
+     - adapted to changes in the table MagicNumber
+     - adapted to changes concerning ganymed in the DB 
+
+   * datacenter/macros/fillganymed.C:
+     - adapted to the new table Ganymed in the DB
+
+   * datacenter/scripts/fillganymed:
+     - added (script to fill the information of the ganymed*.root 
+       files into the db)
+
+
+
+ 2005/08/27 Daniela Dorner
+
+   * datacenter/scripts/dowebplots:
+     - excluded files from lapalma for this check, as there's a big 
+       amount of files (this would cause problems with the array in 
+       shell)
+
+   * datacenter/scripts/dodatacheck:
+     - fixed bug in finding rawfile and date of rawfile
+
+
+
+ 2005/08/26 Daniela Dorner
+
+   * datacenter/scripts/dowebplots:
+     - added some logging 
+     - improved algorithm
+
+
+
+ 2005/08/25 Daniela Dorner
+
+   * datacenter/scripts/dowebplots:
+     - added (script to produce the plots for the websites out of the 
+       rootfiles)
+
+
+
+ 2005/08/24 Thomas Bretz
+
+   * macros/tutorials/threshold.C:
+     - added new example how to calculate the threshold
+
+   * mhflux/MHThreshold.cc:
+     - updated some comments
+
+
+
+ 2005/08/22 Thomas Bretz
+
+   * mgeom/MGeomPix.h, mgeom/MGeomCam.[h,cc]:
+     - added new function GetDist returning the distance between two
+       pixels
+
+   * mhist/MHCamera.h:
+     - added new function (also to context menu) SetMinMax
+
+   * mhist/MHEvent.[h,cc]:
+     - added the possibility to set min and max values for the displayed
+       data
+     - added a new option to display the arrival time after cleaning
+
+   * mmain/MEventDisplay.cc:
+     - added the arrival time after cleaning to display
+     - set the min value in some displays to 0
+
+   * msignal/MSignalCam.cc:
+     - added the possibility to return the arrival time after cleaning
+
+
+
+ 2005/08/18
+
+   * RELEASE 0.9.4.1
+
+
+
+ 2005/08/17 Thomas Bretz
+
+   * mcalib/MCalibCalcFromPast.[h,cc]:
+     - reset the number of events fNumEvents in ReInit, because
+       the corresponding histograms get also reset. This prevents
+       the calibration from analysing partly filled histograms
+     - the number of cases in which the fChargeCalc->Finalize fails
+       are counted and written to the console
+     - In PostProcess all histograms and fChargeCalc are reset to 
+       prevent the finalization of the histograms to fit partly filled
+       histograms and fail.
+
+   * mcalib/MCalibrationChargeCalc.h:
+     - added a member function ResetNumProcessed so that MCalibCalcFromPast
+       can 'switch off' the finalization in PostProcess
+
+   * mhcalib/MHCalibrationCam.cc, mhcalib/MHCalibrationChargeCam.cc,
+     mhcalib/MHCalibrationPulseTimeCam.cc:
+     - shortened some console output
+
+
+
+ 2005/08/16 Thomas Bretz
+
+   * ganymed.cc:
+     - fixed a typo in Usage()
+
+   * mjobs/MDataSet.cc:
+     - fixed a typo in some output
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - fixed some comments
+
+   * macros/dohtml.C:
+     - updated
+
+   * mhflux/MHDisp.cc:
+     - some small fixes to let the code not crash in on-only more
+       (still doesn't give reasonable results... maybe a fit to the 
+        background would do it)
+
+   * mhflux/MHFalseSource.cc:
+     - removed some obsolete comment
+     - set initial marker color of stars in star display
+
+   * mjobs/MJCut.cc:
+     - added a small fix to get the correct parlist in on-only mode
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - fixed source position handling in on-only mode
+
+
+
+ 2005/08/11 Daniela Dorner
+
+   * datacenter/scripts/makecallistolinks:
+     - fixed path
+
+   * datacenter/scripts/runcallisto:
+     - improved locking
+
+   * datacenter/macros/getdolist.C:
+     - included removing of file for the case, that there's something 
+       strange happening in the shell script
+
+
+
+ 2005/08/08 Daniela Dorner
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed some bugs
+     - added deleting of sequences
+
+   * datacenter/macros/resetallruns.C:
+     - fixed small bug
+
+   * datacenter/macros/fillstar.C:
+     - fixed bug
+
+   * datacenter/scripts/dodatacheck:
+     - fixed logging of sinope
+
+
+
+ 2005/08/05
+
+   * RELEASE 0.9.4
+
+
+
+ 2005/08/05 Daniela Dorner
+
+   * datacenter/macros/setupdb.C:
+     - exchanged in the table RunProcessStatus the column fFillDotRaw 
+       by the column fDataCheckDone
+
+   * steps.rc:
+     - adapted to the needs of the new step fDataCheckDone in the table
+       RunProcessStatus
+
+   * datacenter/scripts/dodatacheck:
+     - added (script to do datacheck including filldotraw.C, sinope, 
+       fillsinope.C, resetcolumn.C)
+
+   * datacenter/macros/filldotraw.C:
+     - adapted to the needs the new script dodatacheck
+
+   * datacenter/macros/fillsinope.C:
+     - adapted paths to the needs the new script dodatacheck
+     - removed test stuff
+
+   * datacenter/macros/getdolist.C:
+     - added if clause to reduce the number of runs for datacheck
+       (arrays in shell scripts are limited)
+     - added logging output
+
+   * datacenter/scripts/buildsequenceentries, fillcallisto, 
+     checkfilesforsequenceavail, checkstardone, correcttime, 
+     filesondisk, fillstar, insertdatasets, runganymed, runstar, 
+     doexclusions, writesequencefiles, runcallisto:
+     - fixed typo and logging
+
+
+
+ 2005/08/05 Thomas Bretz
+
+   * mpointing/MSrcPocCam.[h,cc]:
+     - fixed a bug which caused problems if now source position was
+       defined in the dataset.
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - added new base class TAttMarker
+     - added new data mebers MAttLine for the two line types
+     - some simplification to the atoi/atof stuff
+     - added new helper class MAttLine
+     - increased class version to 2
+
+
+
+ 2005/08/04 Daniela Dorner
+
+   * datacenter/scripts/makecallistolinks:
+     - added (script to make the links for the correct callisto.rc in 
+       case when callisto_Dec04Jan05.rc is needed)
+
+   * datacenter/macros/writesequencefile.C:
+     - added writing of ZdMin and ZdMax to the sequencefile
+
+   * sinope.cc
+     - added printing of Usage() in case of missing arguments
+     - added option --outf to make it possible to give the filename 
+       (needed for automation of datacheck)
+     - added output in txt-file in case of no events (needed for the 
+       evaluation of runs with no interlaced events)
+     - small changes in output
+
+   * datacenter/macros/setupdb.C:
+     - added new table (DataCheck)
+
+   * datacenter/macros/fillsinope.C:
+     - added (macro to read in the sinope*.txt files and fill the 
+       information into the DB)
+
+   * datacenter/macros/filldotraw.C:
+     - added (was before in the directory macros/sql/)
+     - made some changes to include it into the automation 
+       added function make it possible to call the macro not only 
+       with the filename but also with the runnumber
+
+   * macros/sql/*:
+     - removed (all macros are now in the datacenter directory)
+
+
+
+ 2005/08/02 Thomas Bretz
+
+   * mjobs/MJStar.cc:
+     - changed the muon cuts back after a discussion with Markus. I
+       made a mistake interpreting the meaning of the cuts.
+
+
+
+ 2005/08/03 Daniela Dorner
+
+   * datacenter/macros/getdolist.C:
+     - added if-clause to distinguish between steps that need one todo
+       file and steps that need one todo file per sequence/dataset (i.e.
+       callisto, star, ganymed) and added writing of these files
+
+   * datacenter/scripts/runcallisto, runganymed, runstar:
+     - adapted scripts to the changes in getdolist.C (removed lines to 
+       divide todo file, changed getting of todo file)
+
+   * datacenter/scripts/runcallisto:
+     - added if-clause for the choosing of the correct callisto.rc 
+       (needed due to the new callist_MarApr05.rc which is applied 
+       between sequence 49736 and 53315
+
+
+
+ 2005/08/02 Daniela Dorner
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed bug, added some logging output and comments
+
+
+
+ 2005/08/02 Thomas Bretz
+
+   * callisto.rc, callisto_Dec04Jan05.rc:
+     - new ScaleFactor (1% difference)
+
+   * callisto_MarApr05.rc:
+     - new file, identical to callisto.rc but scale factor 5% different
+
+   * mhflux/MHPhi.[h,cc]:
+     - some small improvements
+     - commented code for further improvement
+
+   * mjobs/MJCut.cc:
+     - implemented MHPhi for wobble mode
+
+   * mjobs/MJStar.cc:
+     - repleced maximum deviation (45) in first muon cut by 35
+       it is done anyhow in a later step and doesn't change in between
+
+   * datacenter/macros/fillstar.C:
+     - now get muon data from MHMuonPar directly
+
+   * mmuon/MHMuonPar.[h,cc]:
+     - implemented the function to get the reference values
+     - updated psf reference line
+     - implemented calib reference line
+
+
+
+ 2005/08/01 Thomas Bretz
+
+   * mhflux/MHPhi.[h,cc]:
+     - added
+
+   * mhflux/Makefile, mhflux/FluxLinkDef.h:
+     - added MHPhi
+
+
+
+ 2005/07/31 Daniela Dorner
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed bug in the new sequence-build algorithm (-> 2005/07/22): 
+       completely re-wrote the function CheckSequence() to make sure, 
+       that sequences which are not changed are not inserted once again
+
+
+
+ 2005/07/30 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - added function to make a directory
+
+   * datacenter/scripts/buildsequenceentries, checkstardone, copyscript,
+     checkfilesforsequenceavail, correcttime, doexclusions, filesondisk,
+     fillcallisto, fillstar, insertdatasets, runcallisto, runganymed, 
+     runstar, writesequencefiles:
+     - replaced making of directories by the function
+
+   * datacenter/macros/setupdb.C:
+     - added column fTest in table Source to make building datasets 
+       easier
+     - fixed small bug
+
+   * datacenter/macros/getdolist.C:
+     - fixed small bug
+
+   * datacenter/macros/filldotrun.C:
+     - inserted the two new arehucas version from July 2005
+
+
+
+ 2005/07/29 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - added four more general paths to the sourcefile to make it 
+       easier to use the software for different users, paths and setups
+
+   * datacenter/scripts/buildsequenceentries, checkstardone, 
+     checkfilesforsequenceavail, correcttime, doexclusions, filesondisk,
+     fillcallisto, fillstar, insertdatasets, runcallisto, runganymed, 
+     runstar, writesequencefiles:
+     - adapted this scripts to the usage of the paths
+
+   * datacenter/macros/buildsequenceentries.C, findcacofiles.C, 
+     getdolist.C, writesequencefile.C:
+     - adapted this macros to the usage of the paths
+
+   * datacenter/macros/buildsequenceentries.C, createdataset.C, 
+     resetcolumn.C:
+     - fixed documentation of this macros
+
+
+
+ 2005/07/27 Markus Meyer, Daniela Dorner
+
+   * datacenter/macros/fillstar.C:
+     - implemented new algorithm and new values for the calculation 
+       of the muon parameter in the database
+
+
+
+ 2005/07/28 Thomas Bretz
+
+   * mastro/MAstro.cc:
+     - fixed a bug in Deg2Hms reported by Abelardo. It gave wrong
+       results by 1./2pi
+
+
+
+ 2005/07/27 Markus Meyer, Thomas Bretz
+
+   * mmuon/MHSingleMuon.[h,cc]:
+     - added third (constant) parameter to arc width gaus fit
+     - replaced nonsense GetMaximumBin as start value for fit
+       by GetMaximum
+     - replaced TH1F for fHistWidth by TProfile
+
+   * mmuon/MMuonSetup.cc:
+     - set new threshold for arc width plot to 2
+
+   * star.rc:
+     - replaced default for arc width threshold
+
+
+
+ 2005/07/27 Thomas Bretz
+
+   * mhflux/MAlphaFitter.cc:
+     - added a line at the cut value to PaintResults
+
+   * mhflux/MHDisp.cc:
+     - replaced GetCosDelta/GetSinDelta by new GetNormAxis
+
+   * mhist/MHRate.cc:
+     - replaced some warn by err
+
+   * mimage/MHillas.[h,cc]:
+     - added new member function GetNormAxis
+
+
+
+ 2005/07/26 Daniela Dorner
+
+   * datacenter/macros/fillsignal.C, setupdb.C:
+     - changed format of variables fMeanPedRmsInner and fMeadPedRmsOuter
+       from float(5,1) to float(6,2)
+
+
+
+ 2005/07/26 Thomas Bretz
+
+   * mhflux/MHDisp.cc:
+     - improved scaling for significance plot, so that significances
+     similar to the ThetaSq plot come out
+
+   * mhvstime/MHSectorVsTime.[h,cc]:
+     - implemented the possibility to set a minimum/maximum from outside
+
+   * mjobs/MJStar.cc:
+     - added a plot of the pedestal rms vs time
+     - set minimum and maximum for dc currents vs time
+
+   * mpedestal/MPedPhotCam.cc:
+     - added a sanity in GetPixelContent for the index
+
+
+
+ 2005/07/25 Daniela Dorner
+
+   * datacenter/macros/fillstar.C, setupdb.C:
+     - changed format of variable fMeanNumberIsland from float(5,1) to 
+       float(6,2)
+
+
+
+ 2005/07/25 Thomas Bretz
+
+   * mastro/MAstroSky2Local.[h,cc]:
+     - allow setting a pointing deviation when calculating the rotation angle
+
+   * mhflux/MHDisp.[h,cc]:
+     - added pot for a significance map
+     - changed alignment range from 0.33/0.47 to 0.325/0.475
+     - added fDeviation to calculation of Rotatio angle
+     - removed some obsolete code
+
+   * mpointing/MPointingPos.[h,cc]:
+     - added option to calculate Rotation angle using MPointingDev 
+
+   * ganymed_onoff.rc, ganymed_wobble.rc:
+     - added example for MPointingDevCalc
+
+   * mjobs/MDataSet.cc:
+     - fixed an endless loop when a sequence is added twice
+
+   * mjobs/MSequence.cc:
+     - fixed an endless loop when a run is added twice
+
+   * mjobs/MJPedestal.cc:
+     - CheckEnv doesn't return kERROR, test for kFALSE instead
+
+   * mpointing/MPointingDev.h:
+     - added fDevX
+     - added fDevY
+
+   * mpointing/MPointingDevCalc.cc:
+     - call SetDevXY instead of the starguider calibration in zd/az
+
+   * mpointing/MSrcPosCalc.cc:
+     - added the DevXY to the source position if fDeviation!=NULL
+
+
+
+ 2005/07/22 Daniela Dorner
+
+   * sinope.cc:
+     - added option to select only data or only calibration events for 
+       the datacheck
+
+   * datacenter/scripts/runstar, runcallisto:
+     - increased number of processes to ensure, that the runtime of a 
+       process doesn't exeed 12 hours
+
+   * datacenter/scripts/runganymed:
+     - removed second execution of ganymed
+
+   * datacenter/scripts/:
+     - small change in all scripts to make it easier to adapt scripts 
+       for a different user
+
+   * datacenter/macros/buildsequenceentries.C:
+     - implemented new algorithm to build sequences: instead of 
+       checking the conditions of the runs after grouping them together
+       the condition are taken into account for grouping the runs
+       Attention: some sequences will change with this new algorithm! 
+
+
+
+ 2005/07/22 Thomas Bretz
+
+   * macros/tutorials/extendcam.C, macros/tutorials/hft.C:
+     - some updates. Replaced MCerPhotEvt by MSignalCam
+
+   * mhflux/MHDisp.cc:
+     - some more fixes to allow no-smearing
+
+   * mhft/MGeomCamMagicEnhance.cc:
+     - replaced GetPixById by the id itself
+
+   * mimage/MImgCleanStd.cc:
+     - do not check for the pedestal container if absolute cleaning
+       has been chosen
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed obsolete comments
+
+   * mreport/MReport.[h,cc]:
+     - added some conversions for wrong version numbers
+
+   * mreport/MReportCamera.cc:
+     - fixed a problem reading files with gkActiveLoadControlVersNum
+     - added a fix for report files before 200407070
+
+   * mhvstime/MHSectorVsTime.[h,cc]:
+     - added example to class reference
+     - fixed possible crash in SetName and SetTitle
+     - set default style to kFullDotMedium
+     - removed seconds from default axis labels
+     - changed default time labels size to 0.033
+     - moved Draw code to Paint as in MHVsTime
+     - fixed wrong return of kCONTINUE in Fill
+
+   * mhvstime/MHVsTime.cc:
+     - removed seconds from default axis labels
+   
+   * mjobs/MJStar.cc:
+     - added Starguider info to output
+     - added MHSectorVsTime to display mean DC current
+     - allow skipping MHPointing for very old files without
+       starguider reports
+
+   * mpointing/MHPointing.[h,cc]:
+     - allow skipping MHPointing for very old files without
+       starguider reports
+     - removed displaying nominal Az
+
+   * mjobs/MJCut.cc:
+     - implemented pointing correction by starguider
+
+   * mpointing/MPointingDevCalc.cc:
+     - some minor updates
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - implemented usage of pointing deviation -- still in progress!
+
+   * mpointing/MSrcPosCorrect.[h,cc]:
+     - inverted sign of pointing correction for anti-source
+     - write telescope axis to parlist
+
+   * ganymed_wobble.rc:
+     - added setup for polynom order 1
+
+
+
+ 2005/07/21 Thomas Bretz
+
+   * mastro/MAstro.[h,cc]:
+     - added new member function GetDevAbs
+
+   * mcamera/MCameraAUX.[h,cc]:
+     - added new data members for counting house temperatures
+     - increased class version number to 2
+
+   * mcamera/MCameraHV.[h,cc]:
+     - added new data members for HV settings file name
+     - increased class version number to 2
+
+   * mhflux/MHDisp.cc:
+     - fixed handling of non-smearing
+     - fixed calculation of number of entries for the two wobble
+       histograms
+
+   * mjobs/MJStar.cc:
+     - gave a new name to the task writing the Muon-tree
+
+   * mpointing/MHPointing.cc:
+     - do not check the abs deviation but check both deviations
+       independantly whether they make sense.
+     - Plot only hour and minutes
+
+   * mpointing/MPointingPosCalc.h:
+     - fixed wrong #ifndef
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - new class MPointingDev
+     - new class MPointingDevCalc
+
+   * mpointing/PointingIncl.h:
+     - removed TVector2
+
+   * mreport/MReportCamera.[h,cc]:
+     - added interpretation CHTEMP and HVFIl valid since
+       arehcas version 200507190 (incl)
+
+   * mreport/MReportDrive.cc:
+     - moved code from GetErrorAbs to MAstro
+
+   * mreport/MReportStarguider.[h,cc]:
+     - moved code from GetDevAbs to MAstro
+     - added new getter returning a TVector2
+
+   * ganymed_onoff.rc, ganymed_wobble.rc:
+     - added
+
+   * ganymed.rc: 
+     - updated
+
+
+
+ 2005/07/19 Thomas Bretz
+
+   * mjobs/MJCut.cc:
+     - write MSrcPosCam to output
+     - write MSrcPosAnti to output
+     - removed MEnergyEst from output
+     - added MSrcPosCorrect to tasklist
+
+   * mjobs/MJSpectrum.cc:
+     - removed MSrcPosCalc from tasklist for refilling
+     - removed hillas calculation from tasklist for refilling 
+       (both need a better concept in MJCut: not writing to
+        results file, but to summary file)
+
+   * mjobs/MJStar.cc:
+     - removed MSrcPosCalc from tasklist (better this is always done
+       correctly in MJCut)
+     - added Starguider information to output
+     - replaced Rate historams by new histogram MHRate
+     - added new histogram MHPointing
+
+   * mpointing/MSrcPosCorrect.cc:
+     - write new optical axis to parameter list
+     - print a message if a correction is introduced for this run
+
+   * mreport/MReportStarguider.[h,cc]:
+     - added GetDevAbs
+
+   * mhist/MHRate.[h,cc]:
+     - added
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - added MHRate
+
+   * mpointing/MHPointing.[h,cc]:
+     - added
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - added MHPointing
+
+   * mcalib/MCalibrationCam.[h,cc]:
+     - moved code of static function GetPulserColorStr into source file.
+       Hopefully this 'repairs' a strange message some people got linking
+       mars: `.gnu.linkonce.t._ZN15MCalibrationCam17GetPulserColorStrENS_13PulserColor_tE' referenced in section `.rodata' of mcalib/CalibCint.o: defined in discarded section `.gnu.linkonce.t._ZN15MCalibrationCam17GetPulserColorStrENS_13PulserColor_tE' of mcalib/CalibCint.o
+       which was mainly annoying.
+
+   * mfbase/MF.cc:
+     - changed order and handling in ReadEnv. This allows to overwrite
+       already set resources in sponde (eg. MFMagicCuts.ThetaCut)
+
+   * mhbase/MH.cc:
+     - first draft of a new palette introduced by Pepe (I got it from
+       Hendrik)
+
+
+
+ 2005/07/16 Thomas Bretz
+
+   * macros/dohtml.C:
+     - some updates to the macro section
+
+   * mcalib/MCalibrationCam.h:
+     - added new member function GetPulserColorStr to convert
+       pulser color into string
+
+   * mcalib/MCalibrationPattern.h:
+     - added new member function GetPulserColorStr to return
+       pulser color a string
+
+   * mcalib/MCalibrationPatternDecode.cc:
+     - fixed a typo in a comment
+
+   * mhflux/MHThetaSq.cc:
+     - set default number of bins to 75
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - updated support for automatic weights. All cases should now
+       be handled as accurate as possible.
+
+   * msignal/MC_calibration_weights_UV46.dat,
+     msignal/MC_cosmics_weights46.dat:
+     - new files
+
+
+
+ 2005/07/14 Thomas Bretz
+
+   * mbadpixels/MBadPixelCam.[h,cc]:
+     - added new function GetNumSuitable
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - simplified FinalizeUnsuitablePixels()
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - when finalizing of unsuitable pixels fails return kERROR in
+       Process
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - simplified counting unreliable pixels
+
+   * mfilter/MFMagicCuts.[h,cc]:
+     - replaced the m3long cut. m3long now is used to determin which
+       origin might be the correct impact of the shower. This gives
+       not so steep theta plots and the 2D plot can be done at the
+       same time.
+     - The sign of Disp stored in the paremeter list is now correctly
+       aligned along the major axis of the shower. >0 for along major
+       axis, <0 otherwise.
+     - comment have been updated.
+     - some old code had been removed
+
+   * mhflux/MHDisp.[h,cc]:
+     - updated with a more appropriate calculation of a background model
+
+
+
+ 2005/07/13 Abelardo Moralejo (2005/07/12)
+
+   * manalysis/MGeomApply.cc
+     - Now, if the MGeomApply task has a serial number >0 (indicating 
+       most likely a specific telescope in a multi-telescope file), then 
+       apply the geometry only to objects with the same serial number. 
+       This is important for stereo setups in which the telescopes have 
+       cameras with different numbers of pixels. If the MGeomApply task 
+       has serial number 0 (default), it will apply the geometry to all 
+       found objects as it used to do.
+
+   * manalysis/MMcCalibrationUpdate.cc, mpedestal/MMcPedestalCopy.cc
+     - Now the PreProcess adds the serial number also to MRawRunHeader
+       and MMcRunHeader, since in stereo MC files produced with the 
+       current camera simulation at CVS there is one such container per 
+       telescope. There is no difference in behaviour for single 
+       telescope files. Old MC stereo files will no longer be readable.
+
+   * mimage/MNewImagePar.cc
+     - Made calculation of "Inner size" valid also for camera geometries
+       other than MAGIC standard one. The calculation of "inner leakage"
+       is now made only for MAGIC standard geometry (there is no easy 
+       fix for that, but having fInnerSize and MHillas.fSize, the inner 
+       leakage is a completely unnecessary parameter). Added a comment on
+       a possible fix for the calculation of fConc.
+
+   * mcalib/MMcCalibrationCalc.[h,cc]
+     - Added member fMinSize and setter for it. It is the minimum 
+       (uncalibrated) size of events to be used in the calibration. 
+       Previously it was fixed at 1000 ADC counts, but the value depends
+       on the extractor used, so it must be possible to change it.
+     - Add the serial number to MRawRunHeader and MMcConfigRunHeader 
+       (now there is one per telescope in stereo files).
+     - Moved the creation of histograms from the constructor to the
+       PreProcess, otherwise the serial number is not added to the 
+       histogram name.
+     - In PostProcess, set the average QE for area 0 (inner pixels) in
+       MCalibrationQECam object, to be used later by MCalibrateData.
+   
+   * macros/starmcstereo.C
+     - Big update. Adapted to all changes above. Now not only relative, but
+       also absolute calibration (=SIZE in phes) is made.
+
+  * mcalib/MCalibrateData.cc
+    - In PreProcess, changed initialization of fRenormFactor. Formerly 
+      it was fixed to MCalibrationQEPix::gkDefaultAverageQE. Now we check
+      first if there is a valid average QE for inner pixels in 
+      MCalibrationQECam, and if so, we inititalize fRenormFactor with it. 
+      Else, the default gkDefaultAverageQE is taken. fRenormFactor is
+      used to convert back from photons to "equivalent inner pixel phes"
+      in the (now default) case of calibrating in phes.
+
+
+
+ 2005/07/13 Raquel de los Reyes (2005/07/12)
+
+   * merpp.cc
+     - Added the container MCameraActiveLoad to the rootified central
+       control files
+
+   * mreport/MReportCC.[h,cc]
+     - Changes in the InterpreteBody to write the variable UPS status and
+       the Time difference between GPS and rubidium clock. 
+
+  * mreport/MReportCamera.cc
+     - Changes in the InterpreteCamera and InterpreteBody functions to allow
+       the data merpping from 2005_06_30.
+
+
+
+ 2005/07/13 Abelardo Moralejo (2005/07/12)
+
+   * macros/starmcstereo.C
+     - Fixed error which made some objects to be written twice in the
+       _test_ output file.
+
+
+
+ 2005/07/13 Patricia Liebing (2005/07/06)
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+    - include new flag (kLoGainBlackout) into the "uncalibrated"
+      pixel classification (see docu from 28/06/2005 Markus Gaug)
+
+   * mbadpixels/MBadPixelsPix.[cc.h], mcalib/MCalibrationChargeCalc.cc
+     - included flag kLoGainBlackout for unsuitable pixels w/
+       corresponding docu/printout (see MHCalibrationChargeCam.cc)
+ 
+   * mhcalib/MHCalibrationPulseTimeCam.cc, MHCalibrationCam.cc
+     - add Pixel ID to Debug printout statements 
+
+   * mjobs/MJCalibration.cc
+     - include new display for kLoGainBlackout unsuitable pixels
+
+
+
+ 2005/07/13 Antonio Stamerra (2005/07/04)
+
+   * manalysis/MMcTriggerLvl2Calc.cc
+     - the checks written on ReInit for MC have been moved to PreProcess()
+     - kFALSE substituted with kSKIP in the check for the standard MAGIC 
+       geometry
+
+
+
+ 2005/07/13 Abelardo Moralejo (2005/07/01)
+
+   * macros/starmc.C
+     - Set two different cleaning tasks for the calibration loop and 
+       for the second (analysis) loop. Otherwise, some pixels were 
+       cleaned out in the first loop (we do not want this) if the 
+       absolute method was chosen.
+
+
+
+ 2005/07/13 Abelardo Moralejo (2005/06/30)
+
+   * mmc/MTriggerDefine.h
+     - Added TRIGGER_PIXELS_4, a provisional number of trigger pixels
+       for the MGeomCamMagic1183 geometry.
+
+   * mgeom/MGeomCamMagic1183.[h,cc]
+     - added. Possible design for a MAGIC-II camera. Preliminary 
+       version, not yet ready to use.
+
+
+
+ 2005/07/13 Abelardo Moralejo (2005/06/29)
+
+   * mgeom/MGeomCamMagic1183.[h,cc]
+     - added. Possible design for a MAGIC-II camera
+
+   * mgeom/Makefile, GeomLinkDef.h
+     - added new class above.
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/28)
+
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+     - set the fPickupLimit and fBlackoutLimit for the low-gain arrays
+       to a 3.5 instead of the default used in MHCalibrationPix (5.0).
+     - use a new criterium to exclude bad pixels: If the high-gain was
+       saturated and the blackout-events in the low-gain exceed the 
+       fNumLoGainBlackoutLimit, the pixel is declared unsuitable.
+       This excludes those pixels which have a saturating high-gain 
+       channel, but the low-gain switch does not switch often enough 
+       to make the distribution reliable.
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/23)
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - fix a bug counting the number of saturated events. Up to now, the 
+       number of saturated slices was counted (which is one for a not too
+       high number), but for some (pathological) pixels, many more slices
+       saturated and produced wrong limits.
+     - make the PickupLimit und BlackoutLimit for the low-gain explicitely
+       smaller. The too large limits caused a failed fit for some channels
+       which resulted in wrong calibration constants. (M. Gaug)
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/22)
+
+   * mjobs/MJPedestal.cc
+     - change order of reading local environmnet variables in lines 1044 
+       to 1068. Reason: The lines:
+            if (fExtractor==tenv.GetTask())
+               return kTRUE;
+       yielded sometimes a return before the rest of the env-variables 
+       could be read in. This affected ONLY the reading of the pedestal
+       reference file and the bad pixels file name. (M. Gaug)
+     - Added "decode" task (MTriggerPatternDecode) task to the list also 
+       for MC runs.
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - fixed the setting of unreliability for saturated events where the 
+       high-gain signal was not stable over time. Now, saturation is 
+       asked for before (like in the high-gain fitted-case). (M. Gaug)
+     - fixed a small bug in the precise setting of the histogram ranges. 
+       May have introduced a bias of typically 1 FADC cnt in the mean 
+       fitted signal (< 0.5%).
+
+   * mbadpixels/MBadPixelsPix.[h,cc]
+     - took out the un-used bad pixels information in function: 
+       GetUnsuitableCalLevel(). 
+     - debugged the class-documentation
+
+   * mcalib/MCalibrationIntensityChargeCam.cc
+     - a very small fix in the axis title from N_phe to N_{phe}
+     - fixed one bug in the draw-functions of this class. Not (yet) used by 
+       standard calibration.
+     - +some undocumented changes
+
+  * mjobs/MJCalibration.cc
+    - changed order in tasklist between MCalibColorSet and 
+      MPedCalcFromPedRun. Caused crashes in the intensity calibrations. 
+      Does not affect ordinary calibration since MPedCalcFromPedRun is 
+      then not in the tasklist anyhow. 
+    - changed order of MHCalibrationChargeCam and MCalibrationRelTimeCalc. 
+      This wrong order caused MCalibrationRelTimeCalc to print out 
+      unreliable pixels which were not set by the rel. time calibration. 
+      This caused some confusion in the reading of the output because of
+      the un-logical order of flag settings and posterior output.
+    - set the error of the hi-logain intercalibration constants
+      as the real error on the mean instead of the sigma.
+    - took out the those bad pixel-informations which are not used
+      any more in the "Defect" - display. (M. Gaug)
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/21)
+
+   * mhcalib/MHCalibrationChargePix.h
+     - take out one un-necessary 'virtual'-declaration for the Draw-
+       function
+
+   * mhcalib/MHGausEvents.cc
+     - fixed a small bug in the non-standard display with options.
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/19)
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - set fgOffsetLoGain from 1.7 to 1.39. This is the correct time
+       shift between high-gain and low-gain. Affects only very detailed
+       timing studies.
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - set fOffsetLoGain from 1.7 to 1.4 which corrects now exactly for 
+       the arrival time difference between low-gain and high-gain pulses.
+       This wrong number could have had some effect on image cleanings
+       using the time information. (M. Gaug)
+ 
+   * mcalib/MCalibrationBlindCam.[h,cc]
+     - remove obsolete Copy-function
+
+   * mcalib/MCalibConstPix.h, mcalib/MCalibConstCam.h
+     - introduce Copy-functions
+     - set class index to 1 (was 0)
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - introduce Copy() function.
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/18)
+
+   * mpedestal/MPedestalCam.cc
+     - modify Print() function to print out also the event-by-event
+       averaged results.
+
+   * mpedestal/MExtractPedestal.[h,cc]
+     - new flag fUseSpecialPixels (set to kFALSE per default)
+     - new data member: fNameRawEvtData which can be set from outside 
+       (e.g. to "MRawEvtData2"). 
+     - with these two changes, the special pixels can be extracted. 
+       Difference to previous version: if flag fUseSpecialPixels is set, 
+       * the area and sector averages are not calculated.
+       * the MPedestalCam will get initialized to 
+         MRawRunHeader->GetNumSpecialPixels(). 
+     - fix a bug in the calculation of the event-by-event averaged 
+       pedestal RMS (one total number of areas or sectors was not taken 
+       into account). 
+     - make local variables in the calculation of rms and mean doubles
+       instead of floats.
+
+   * mpedestal/MPedCalcPedRun.cc
+     - do not calculate the area and sector averages in case flag
+       fUseSpecialPixels is set.
+     - check for existence of pointer fRawEvt in PostProcess.
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - implement possibility to set reference number of photo-electrons from 
+       outside (stored in fExternalNumPhes).
+
+   * mcalib/MCalibrateData.[h,cc], mcalib/MCalibCalcFromPast.cc, 
+     mjobs/MJCalibrateSignal.cc:
+     - write calibration constants now in separate 
+       MCalibrationIntensityConstCam. This is necessary since with the 
+       introduction of the averageing of mean photo-electrons, the 
+       MCalibrationIntensityChargeCam does not hold the correct conv. 
+       factors any more. 
+
+   * mcalib/MCalibrateData.[h,cc]
+     - get also pointers to the IntensityCams and use them if exist 
+       (previously, only the first calibration cam was used together 
+       with the updatecam.)
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/17)
+
+   * mcalib/MCalibrationIntensityCam.[h,cc]
+     - take out some un-used or commented code (variables fOffsets and
+       fSlopes). These data members were not in the streamter either.
+     - put some of the most-used code from the .cc file into the .h file
+     - add new function: SetCam().
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/15)
+
+   * mcalib/MCalibrationIntensityConstCam.[h,cc]
+     - new class to store the actual applied conversion factors (now with 
+       averaged photo-electrons not in the MCalibrationIntensityChargeCam
+       any more).
+
+   * mjobs/MJCalibration.cc
+     - set the correct (statistical) error of the inter-calibraiton factor
+       into MCalibrationChargePix::SetConversionHiLoErr() and the 
+       sigma of the distribution
+       into MCalibrationChargePix::SetConversionHiLoSigma().
+     - In MCalibrationChargePix, the mean conversion error is used for the 
+       statistical error of the conversion factor.
+     - In CalibrateData, the sigma is used for the statistical error of the
+       converted signal to equiv. high-gain charges.
+
+   * mcalib/MCalibCalcFromPast.[h,cc]
+     - implement the mean photo-electron averageing for a desired number of 
+       calibration updates.
+
+   * mcalib/MCalibrateData.cc
+     - use MCalibrationChargePix::GetConversionHiLoSigma() to calculate the
+       error (was previously MCalibrationChargePix::GetConversionHiLoErr(). 
+
+  * callisto.cc
+    - calculate first fixed window pedestal in MJPedestalY2, 
+      then sliding window pedestal in MJPedestalY3 (order reversed).
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/14)
+
+   * mcalib/MCalibrationHiLoPix.[h,cc]
+     - store also results from profile fits.
+     - increades class version
+
+   * mhcalib/MHCalibrationHiLoPix.[h,cc], mhcalib/MHCalibrationHiLoCam.[h,cc]
+    - added TProfiles for every pixel filled with the high-gain signal
+      vs. low-gain signal which can be fitted to extract gain and 
+      offset.
+
+   * mhcalib/Makefile, mhcalib/HCalibLinkDef.h
+     - added MHCalibrationHiLoPix
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/10)
+
+   * mcalib/MCalibrationRelTimeCalc.cc
+     - print out forgotten successfully calibrated pixels
+     - small change in spacing of one output
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+     - introduce max. number of events, the rest gets skipped before the 
+       next ReInit() is called. Default: 4096
+       Reason: The calibration causes too many un-reliable pixels if more 
+               than about 5000 events are treated (@500 Hz) because of the
+               mode hopping of the VCSels. However, in the past, some 
+               calibration runs have been taken (erroneously) with more 
+               than 5000 events, especially the intensity scans where  
+               a good precision is needed.
+    - increased version number
+    - introduce a Getter for the fAverageAreaNum array.
+    - re-normalize the area-averaged sigmas to the equivalent number per 
+      pixel also for the intensity calibration.
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+    - divide errors in stat. and syst. errors. Both can be retrieved
+      now, depending on the study, one wants to make.
+
+  * mcalib/MCalibrationChargeCalc.[h,cc]
+    - set a limit to the number of un-suitable and un-reliables pixels
+      for the run to succeed: 0.1 unsuitables and 0.3 un-reliables
+    - set UseExtractorRes to kTRUE, will raise the number of 
+      photo-electrons for the spline extractor by 1-2% (correctly).
+    - re-normalize the pedestal RMS of the event-by-event averaged 
+      area events to the sqrt of the number of used pixels.
+    - re-normalize the sigma of the event-by-event averaged area events
+      by 1/F-Factor.
+    - introduce switch to choose if un-reliables should be used for the
+      calculation of mean number of phes (default: kTRUE).
+    - print out the number of high-gain saturated pixels.
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/10) 
+
+  * mjobs/MJCalibrateSignal.[h,cc]
+    - skip also the PIN Diode events from the data calibration.
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/06) 
+
+   * mhcalib/MHGausEvents.[h,cc]
+     - put small functions into header file to speed up calculations a bit.
+
+   * mcalib/MCalibrationRelTimeCalc.cc
+     - introduce flags to steer the setting of unreliability like done 
+       in MCalibrationChargeCalc. Can be steered from the conf-file.
+
+   * mbadpixels/MBadPixelsIntensityCam.[h,cc]
+     - implement two Get and Draw-functions to display bad pixels over 
+       time like in the mcalib/MCalibrationIntensityChargeCam
+
+
+
+ 2005/07/13 Markus Gaug (2005/06/03) 
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc
+     -  fill arrays only if IsOscillations() was asked. This is a speed 
+        bug and could cause important memory leaks. It does not affect the 
+        outcome of an analysis, however.
+
+
+
+ 2005/07/13 Thomas Bretz
+
+   * mbase/MTaskInteractive.[h,cc]:
+     - fixed a bug with calling ReInit... PostProcess was called instead.
+     - added the missing initialisation of fReInit in constructor
+
+   * sinope.cc:
+     - removed plotting the tasklist statistics twice
+     - replaced DrawClone by DrawCopy (DrawClone gave problems)
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - fixed the ThetaSq function. It was wrongly defined as
+       exp(-((x-c)/s)^2) instead of exp(-1/2*((x-c)/s))
+     - Set start value for corresponding fit back to same value
+       as for a standard gauss-fit.
+
+
+
+ 2005/07/12 Daniela Dorner
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed bug, that was caused by changes in TExMap in root_v4.04.02
+
+
+
+ 2005/07/12 Daniela Dorner
+
+   * automatic-exclusions.rc:
+     - added two automatic exclusions
+
+   * datacenter/macros/findcacofiles.C:
+     - adapted query to ensure, that only existing caco-files are 
+       searched
+
+   * datacenter/macros/getdolist.C:
+     - changed query to make sure, that new data is processed first
+
+   * datacenter/macros/resetallruns.C:
+     - changed query to allow manual interaction in RunProcessStatus
+
+   * datacenter/scripts/runganymed:
+     - fixed bug in choice of rc-file
+
+
+
+ 2005/07/12 Thomas Bretz
+
+   * mhist/MHEvent.[h,cc]:
+     - added MTime to output
+
+   * mastro/MAstroCatalog.cc:
+     - added a fix which avoided reproducing the gui elements after
+       reading from file
+
+   * mbase/BaseIncl.h:
+     - added TVector3
+
+   * mbase/MMath.[h,cc]:
+     - added Sgn function
+     - moved include of TVector3 to source file
+
+   * mimage/MHillasExt.cc:
+     - included TVector2
+
+   * mjobs/MJCut.cc:
+     - write Disp to output
+     - write MTime to output
+     - changed handling of source position (MSrcPosCalc)
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - allow to switch off source pos calculation
+
+
+
+ 2005/07/11 Thomas Bretz
+
+   * callisto.cc, ganymed.cc, mars.cc, showlog.cc,
+     showplot.cc, sponde.cc, mimage/MImgCleanStd.cc:
+     - fixed some typos
+
+   * mastro/MAstro.[h,cc]:
+     - added new member function GetStringDeg and GetStringHor
+
+   * mastro/MAstroCatalog.cc:
+     - don't display empty ":  " in tooltip for sources without name
+
+   * mbase/MParContainer.cc, mbase/MTask.cc:
+     - fixed usage of a ?:-operator
+
+   * mbase/MString.h:
+     - added two new constructors
+
+   * mjobs/MDataSet.cc:
+     - made sure that all files read later are sorted correctly.
+       This is necessary to ensure correct reading of subsystem
+       data.
+     - skipped adding a sequence twice
+
+     - print effective on time only in debug mode
+     
+   * mjobs/MSequence.cc:
+     - skipped adding a run twice
+
+   * mpointing/MSrcPosCalc.cc:
+     - reformatted the comments
+     - add MTime and MPointingPos to branch list
+     - fTime and fObservatory are now presearched in PreProcess
+       to allow usage in macros having no RunHeaders (if they are
+       not found no warning is printed!)
+     - added sanity checks for these pointers in Process
+
+
+
+ 2005/07/08 Thomas Bretz
+
+   * showplot.cc:
+     - implemented the possibility to open a root interpreter
+
+   * mbase/MMath.cc:
+     - added sanity checks in GaussProb
+
+   * mimage/MHillasExt.[h,cc]:
+     - fixed some units
+     - added Paint
+
+   * mimage/MNewImagePar.cc:
+     - fixed Print output
+
+   * mmain/MEventDisplay.cc:
+     - print a separator between two events
+     - Draw MHillasExt, too
+
+   * mmuon/MMuonCalibPar.cc, mmuon/MMuonSearchPar.cc:
+     - fixed Print output
+
+   * mimage/MHillas.cc:
+     - implemented plotting a estimate of disp
+     - fixed some units in output
+     - fixed the special case in which the shower is symmetric to
+       the axis
+
+   * mimage/MHillasCalc.cc:
+     - skipped printing the removed case 4 from MHillas::Calc
+
+   * mbase/MStatusDisplay.cc:
+     - fixed wrong "save as" in "open" dialog
+
+   * mbase/MTaskInteractive.[h,cc]:
+     - added ReInit
+
+   * mhflux/MAlphaFitter.cc:
+     - fixed the standard polynom order (0 instead of 1) for
+       difference histogram
+     - changed default start velue for gauss sigma in case of kThetaSq
+
+   * mhflux/MHAlpha.cc, mhflux/MHCollectionArea.cc, 
+     mhflux/MHEffectiveOnTime.cc, mhflux/MHThetaSq.cc,
+     mjobs/MJCut.cc:
+     - enhanced zenith angle range
+
+   * mhflux/MHFalseSource.h:
+     - made GetCatalog protected
+     - made SetOffData virtual
+
+   * mhflux/MHThreshold.cc:
+     - enabled Sumw2
+
+   * mjobs/MJCut.cc:
+     - removed BinningEnergyEst
+
+   * mpointing/MPointingPos.h:
+     - added copy constructor
+
+   * mpointing/MSrcPosCorrect.cc:
+     - added a comment
+
+   * mranforest/MRFEnergyEst.[h,cc]:
+     - now stores the mean energy of the bins in the forest
+     - implemented several interpolation methods
+
+
+
+ 2005/06/28 Thomas Bretz
+
+   * mfilter/MFMagicCuts.[h,cc]:
+     - first full implementation... updates to come.
+
+   * mhbase/MH.[h,cc]:
+     - added new member function to set several palettes
+
+   * mhflux/MHDisp.[h,cc]:
+     - fixed z-axis dscription
+     - rotate filling off data by 180 deg.
+     - implemented subtracting off-data from on-data
+     - set different palettes
+
+   * mhflux/MMcSpectrumWeight.[h,cc]:
+     - implemented additional weight for zenith-angle- and size-bins
+
+
+
+ 2005/06/27 Thomas Bretz
+
+   * macros/optim/optimenergy.C:
+     - changed algorithm from Simplex to Migrad
+     - fixed a typo (RunDisp)
+
+   * mhflux/FluxLinkDef.h, mhflux/Makefile:
+     - added new class for threshold calculation
+
+   * mhflux/MHCollectionArea.cc:
+     - replaced BinningEnergy by BinningEnergyEst
+
+   * mimage/MHHillasSrc.cc:
+     - set minimum of fAlpha, fCosDA and fDCADelta to 0
+
+   * mjobs/MDataSet.cc:
+     - improved reading source position
+
+   * mranforest/MRanForest.[h,cc]:
+     - implemented a value describing the forest (eg. corresponding
+       energy)
+     - increased ClassVersion
+
+   * mtrigger/MFTriggerPattern.cc, mtrigger/MTriggerPattern.cc,
+     mtrigger/MTriggerPatternDecode.cc
+     - improved dox (thx to Nicola)
+
+   * mjobs/MJStar.cc:
+     - implemented a new write task which only writes the effective
+       on time. This is necessary otherwise for example the image
+       cleaning could skip effective on-time events.
+
+
+
+ 2005/06/17 Thomas Bretz
+
+   * mbase/MArgs.[h,cc]:
+     - handle possible char \015 in arguments
+
+   * mdata/MDataArray.h:
+     - added Print function to //*MENU*
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added new Option for Scale: Fixed
+     - fixed typo in IsEnvDefined for Signalfunction
+
+   * mhist/MHCamera.cc:
+     - plot profile in deg instead of mm
+
+   * mjobs/MDataSet.[h,cc]
+     - changed error handling when reading source catalog
+
+   * mjobs/MJCut.cc:
+     - added MImagePar to output
+     - take new error handling into account when reading source catalog
+
+   * mjobs/MJSpectrum.cc:
+     - print energy estimator
+     - removed the double minus displaying the fitted spectrum 
+
+   * mjoptim/MJOptimizeDisp.cc, mjoptim/MJOptimizeEnergy.cc:
+     - print rule when optimization has finished
+
+   * mmain/MBrowser.cc:
+     - replaced old path with new path to datacenter
+
+   * mranforest/MRFEnergyEst.[h,cc]:
+     - store binning in new data member fBinning to avoid many calles
+       to atof
+
+
+
+ 2005/06/15 Daniela Dorner
+
+   * datacenter/macros/createdataset.C:
+     - added function to read in input from txt-file
+
+   * datacenter/macros/insertdataset.C:
+     - fixed bug -> no new sourcenames can be inserted by this macro
+
+   * datacenter/macros/writesequencefile.C:
+     - fixed small bug in logging-output
+
+
+
+ 2005/06/13 Daniela Dorner
+
+   * datacenter/macros/createdataset.C:
+     - added (macro to write simple datasetfile)
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed bug introduced 12.5.2005
+
+   * datacenter/scripts/copyscript:
+     - fixed bug
+
+
+
+ 2005/06/13 Thomas Bretz
+
+   * mcalib/MCalibrationHiLoCam.h:
+     - added Print to //*MENU*
+
+   * mhflux/MHThetaSq.[h,cc]:
+     - added resources for fNumBinsSignal and fNumBinsTotal
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - implemented weighting in theta, so we get better statistics
+     - improved output
+     - added plotting other spectras
+ 
+   * Makefile:
+     - added new directory mjoptim
+
+   * manalysis/MEnergyEstimate.[h,cc]:
+     - derives now from a new more genral class MParameterCalc
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - added new class MParamterCalc
+
+   * manalysis/MParameterCalc.[h,cc]:
+     - added new class MParamterCalc
+
+   * mbase/MLog.cc:
+     - do not display 'underline' if fIsNull output
+
+   * mhbase/MBinning.cc:
+     - removed some obsolete comments fixed old stylish SetBinningCos
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - background fit can now be switched off
+     - removed some obsolete comments
+     - adapted Print output
+     - added new option to change signal function type 
+     - adde new Strategy option: kGaussSigma
+
+   * mhflux/MHAlpha.[h,cc]:
+     - output the gauss sigma to the parameter list
+
+   * mhflux/MHThetaSq.h:
+     - mase InitMapping public (used in MJOptimizeDisp)
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - removed MJOptimize*
+
+   * mjobs/MJOptimize.[h,cc]:
+     - allow minimization of something else than MinimizationValue
+
+   * mjobs/MJOptimizeEnergy.[h,cc]:
+     - added class description with example
+     - added weighting task to RunEnergy (untested)
+
+   * mtools/MChisqEval.[h,cc]:
+     - added comments
+     - print result in Postprocess
+     - allow to give a different name to the result
+
+   * mjobs/MJOptimize*:
+     - finally moved to new dir mjoptim
+     - new class MJOptimizeDisp
+
+
+
+ 2005/06/10 Daniela Dorner
+
+   * datacenter/scripts/copyscript:
+     - adapt script to new machine
+
+
+
+ 2005/06/10 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - set minimum and maximum also for ZA graph
+
+   * mdata/MDataChain.cc:
+     - fixed a possible crash to to NULL-acess in GetDataMember
+
+   * mhbase/MBinning.[h,cc]:
+     - added a new binning type "asin" which is used for the
+       ZA binning
+
+   * mhflux/MAlphaFitter.cc:
+     - allow polynom order 1
+     - improved result line in PaintResult
+
+   * mhflux/MHAlpha.cc:
+     - call PaintResult also in DrawAll
+
+   * mhflux/MHCollectionArea.cc:
+     - removede nonsense A_{eff} from plot
+
+   * mhflux/MHDisp.cc:
+     - fixed a possible crash if fSrcPos==NULL
+
+   * mhflux/MHAlpha.cc, mhflux/MHCollectionArea.cc, 
+     mhflux/MHEffectiveOnTime.cc, mhflux/MHEnergyEst.cc,
+     mjobs/MJCut.cc:
+     - replaced SetEdgesCos by new SetEdgesASin (set the correct binning)
+       the old binning was not well aligned with the MC binning
+
+   * mhflux/MMcSpectrumWeight.[h,cc]:
+     - added the possibility to set ZA-weights
+       (Could be improved calculating correst sine-weights)
+
+   * mimage/MHVsSize.cc:
+     - fixed. Conc1 was incorrectly scaled
+
+   * mjobs/MDataSet.h:
+     - added getter for TLists
+
+   * mjobs/MJCut.cc:
+     - in non-wobble mode the hcalc2 had been wrrornously added 
+       to the tasklist -> removed
+       
+   * mjobs/MJOptimize.h:
+     - added a comment for EnableTestTrain
+
+   * mpointing/MSrcPosCam.[h,cc]:
+     - implemented Add member function
+
+   * mranforest/MRFEnergyEst.[h,cc]:
+     - fixed a problem with the removal of the last columns
+     - implemented debug-mode
+     - interpolate energy in logarithmic grid
+     - removed Test function completely
+     - added ReadEnv
+
+   * mranforest/MRanTree.[h,cc]:
+     - replaced some TMatrixFRow by TMatrixFRow_const
+
+   * mpointing/MSrcPosCorrect.[h,cc]:
+     - added
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - added MSrcPosCorrect
+
+   * mhflux/MHDisp.cc:
+     - fixed the scaling of the abs-limit of m3l above which 
+       we assume that the 3rd moment is a good measurement for the
+       correct disp point
+
+
+
+ 2005/06/08 Daniela Dorner
+
+   * datacenter/scripts/checkstardone:
+     - fixed bug 
+     - added check 
+
+   * datacenter/scripts/runstar, runcallisto, runganymed:
+     - added -v4 to commandlines
+
+
+
+ 2005/06/07 Daniela Dorner
+
+   * datacenter/scripts/runstar, runcallisto:
+     - fixed bug in filenumber calculation
+
+
+
+ 2005/06/06 Daniela Dorner
+
+   * datacenter/scripts/runganymed:
+     - fixed bug in second commandline
+
+
+
+ 2005/06/03 Thomas Bretz
+
+   * ganymed.cc:
+     - fixed the wrong printout of ganymed
+
+   * mars.cc:
+     - allow to open a file via commandline
+
+   * mars.rc:
+     - added some more comments
+
+   * mcalib/MCalibrateRelTimes.cc:
+     - removed obsolete comments
+
+   * mmain/MEventDisplay.cc:
+     - implemented muon analysis
+     - fixed a crash caused by the DF
+
+   * mmain/Makefile:
+     - added -I../mmuon
+
+   * mmuon/MMuonCalibPar.cc:
+     - updated Print output
+
+   * mmuon/MMuonSearchPar.[h,cc]:
+     - updated print output
+     - added Paint function
+
+   * mranforest/MRFEnergyEst.h:
+     - fixed thw wrong data types in setters
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - don't try to find automatic weights without template file name
+
+   * mjobs/MJStar.cc:
+     - set bit MFillH::kDoNotDisplay for fillmuon
+
+   * mmuon/MHSingleMuon.[h,cc]:
+     - store function in hist
+     - added Paint member function
+
+
+
+ 2005/06/03
+
+   * RELEASE 0.9.3
+
+
+
+ 2005/06/03 Thomas Bretz
+
+   * mjobs/hilocalib_sp1.root, mjobs/hilocalib_sp1_mc.root:
+     - updated
+
+   * callisto.rc:
+     - MJPedestalY2.MaxEvents: 2000 replaced by 5000 as in
+       callisto_Dec04Jan05.txt
+
+   * manalysis/MMultiDimDistCalc.h:
+     - changes to layout
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - improved sanity checks
+
+   * mbase/MEvtLoop.cc:
+     - fixed a bug which could cause Eventloop to crahs if
+       parlist was not initialized
+
+   * mdata/MDataArray.[h,cc]:
+     - added copy constructor
+
+   * mhbase/MFillH.cc:
+     - made sure that no constructor can crash due to NULL pointers
+
+   * mhbase/MHMatrix.[h,cc]:
+     - first check in AddColumn if the column is available. Afterwards
+       check whether it can be added
+     - added new interfaced to single rows
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - slight change to screen output
+
+   * mjobs/MJPedestal.cc:
+     - slight change to screen output
+
+   * mpedestal/MPedCalcPedRun.cc:
+     - fixed a bug which caused MC files not to work treat them now
+       as pedestal files (always)
+
+   * mranforest/MRFEnergyEst.[h,cc]:
+     - improved the code and the interface
+
+   * mranforest/MRanForestGrow.[h,cc]:
+     - derives now from MRead to be able to use the bar in the
+       display
+
+   * mtools/MTFillMatrix.[h,cc]:
+     - allow to fill a single matrix with all events
+
+   * datacenter/macros/plotdb.C:
+     - display values versus Mean of ZdMin and ZdMax instead of ZdMin
+
+
+
+ 2005/06/02 Markus Gaug (2005/06/01)
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - lower fgPheErrLowerLimit from 9.0 to 6.0. This is necessary to 
+       exclude 2 very ringing pixels in September which - when kept - 
+       destroy the image cleaning around them. 
+
+
+
+ 2005/06/02 Markus Gaug (2005/05/31)
+
+   * mjobs/MJCalibration.cc
+     - The MFTriggerPattern filters out all events taken with the 
+       CT1-pulser and data format version greater than 4. 
+       Demand now that the filter is put into the task list only if the 
+       calibration colour is not kCT1. 
+
+
+
+ 2005/06/02 Markus Gaug (2005/05/26)
+
+   * mpedestal/MPedCalcPedRun.cc
+     - fixed bug in recognition of pedestal bit - affects only intensity
+       calibration.
+
+   * mhcalib/MHCalibrationChargeCam.cc, 
+     mhcalib/MHCalibrationRelTimeCam.cc:
+     - do not draw to status display if histogram is empty. This 
+       caused some error messages from root. 
+
+
+
+ 2005/06/02 Thomas Bretz
+
+   * callisto.cc:
+     - made "-raw" the default
+     - switched bad pixel check on for MJPedestalC2
+
+   * callisto_Dec04Jan05.rc:
+     - reduced MJPedestalY2.ExtractWinRight from 4.0 to 2.0
+
+   * mhflux/MHThetaSq.[h,cc]:
+     - added missing InitMapping
+
+   * mjobs/MJCalib.cc:
+     - set default for fDataFlag to kIsUseRawData
+
+   * mjobs/MJOptimizeCuts.cc:
+     - added some sanity checks if CreateHistNew couldn't create
+       the histogram
+
+   * mjobs/MJPedestal.[h,cc]:
+     - implemented a possible deadpixel check
+
+   * star.rc:
+     - added a missing template line
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]:
+     - changed to allow different upper and lower cuts in pedestal
+       variance
+
+   * mfilter/MFCosmics.cc:
+     - allpix were not increased correctly if a saturated pixel
+       was skipped
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed name of "Interp'd" to something more accurate
+
+   * msignal/MExtractFixedWindow.cc:;
+     - removed case 12 for logain resolution as it is in bcn cvs
+       but nowhere documented
+
+   * callisto.rc:
+     - added new template line for dead pixel check
+     - added correction factor determined from Muon analysis
+
+   * callisto_Dec04Jan05.rc
+     - added correction factor determined from Muon analysis
+     
+   * mhflux/MMcSpectrumWeight.cc:
+     - small change to output
+
+
+
+ 2005/06/01 Thomas Bretz
+
+   * mjobs/MJOptimize.[h,cc]:
+     - moved code for cut optimization to MJOptimizeCuts
+     - moved code for energy optimization to MJOptimizeEnergy
+
+   * mjobs/MJOptimizeCuts.[h,cc], mjobs/MJOptimizeEnergy.[h,cc]:
+     - added
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJOptimizeCuts
+     - added MJOptimizeEnergy
+
+   * showplot.cc:
+     - set window name to input file name
+
+   * mcalib/MCalibColorSet.cc:
+     - changed order of checks so that an explicit color is 
+       prior to any automatic detection.
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - implemented setting a possible additional scale factor
+       (for MC it is always reset to 1)
+
+   * mfilter/MFCosmics.cc:
+     - don't count saturated hi-gain pixels at all. It should
+       not be necessary, because such pixels should have a value
+       high enough in the high-gains but it seems sometimes they don't
+
+   * mhflux/MHAlpha.[h,cc]:
+     - changed some orders in header
+     - made some private data members protected
+     - Call GetVal() if fMap[0]<0. This is necessary if the fill
+       value is calculated on-the-fly (like ThetaSq)
+     - made InitMapping virtual
+
+   * mhflux/MHDisp.cc:
+     - removed 'Get-Entries' workarund
+     - changed the function integartion for the significance
+
+   * mhflux/MHThetaSq.[h,cc]:
+     - overwrite InitMapping because ThetaSq should be read from
+       the parlist always
+
+   * mimage/MHHillas.cc:
+     - set histogram minimum of Delta to 0
+
+   * mpedestal/MPedPhotCam.cc:
+     - check for unsuitable pixels when calculating the means not
+       only for the UnsuitableRun ones
+
+   * msignal/MExtractor.cc:
+     - replaced wrong %2d by %2f
+
+
+
+ 2005/06/01 Daniela Dorner
+
+   * datacenter/scripts/runcallisto:
+     - added writing html-logs
+     - added --auto-time-stop for merpping(ccupdate)
+
+   * datacenter/scripts/runganymed:
+     - added writing html-logs
+     - added second execution of ganymed
+     - adapted to correct usage of config-files
+     - fixed bug
+
+   * datacenter/scripts/runstar:
+     - added writing html-logs
+     - minor change in logpath
+
+
+
+ 2005/05/31 Daniela Dorner
+
+   * datacenter/macros/fillstar.C, plotdb.C:
+     - added two new parameters
+
+   * datacenter/macros/setupdb.C:
+     - adapted to changes in DB (added two columns)
+
+
+
+ 2005/05/31 Thomas Bretz
+
+   * mfileio/MReadReports.[h,cc]:
+     - changed such that it can force prereading of the first event of 
+       a sequence after PreProcess
+
+   * mfileio/MReadTree.h:
+     - added some comment about the new bits used in MReadReports
+
+   * mhflux/MHDisp.cc:
+     - changed fit limit from 1.1 to 1.0
+     - fixed access to wrong axis
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - fixed a bug which caused the first bin of the histograms
+       vs time to disapear in PostProcess, which gave wrong results
+       on the screen. The output and all following programs not
+       directly accessing the histograms haven't been affected
+
+   * mjobs/MJCalib.cc:
+     - HasEnv for boolean type resources is obsolete and has been
+       removed
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed MPointingPosInterpolate
+     - adapted usage of MReadReports to changes
+
+   * mjobs/MJCut.cc, mjobs/MJStar.cc:
+     - adapted usage of MReadReports to changes
+     - made Drive-tree a 'required' tree
+
+   * mjobs/MJStar.cc:
+     - removed "Events" from setting up rate and effective on time
+       tasks to tlist2. It is obsolete because calibration events
+       don't enter star at all.
+
+   * mpointing/MPointingPosCalc.[h,cc]:
+     - assume that the run-type is real-data if Process is called before
+       ReInit
+
+   * merpp.cc:
+     - new options: --auto-time-start --auto-time-stop
+
+   * mbadpixels/MBadPixelsTreat.cc:
+     - removed the checks in the algorithm whether the current pixel
+       is NULL. MSignalCam doesn't support zero supression anymore.
+       GetPixById has been replaced by the []-operator
+
+
+
+ 2005/05/30 Thomas Bretz
+
+   * msql/MSQLServer.cc:
+     - added possibility to setup SelectDatabase from resource file
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]:
+     - implemented the possibility to use the check routine
+       from outside
+     - check now returns kFALSE if more than 50% of all
+       pixels are marked as unsuitable
+
+   * mhflux/FluxLinkDef.h, mhflux/Makefile:
+     - added MHDisp
+     - added MMcSpectrumWeight
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - allow finding of Off-plot for derived classes  - like in MHAlpha
+     - get source position from MSourcePos if existing
+     - changed some data members from private to protected
+
+   * mhflux/MHDisp.[h,cc]:
+     - added
+
+   * mjobs/MJCut.[h,cc]:
+     - implemented new option (HistNameFS) to allow using a different
+       False Source Plot
+
+   * mpedestal/MPedPhotCam.[h,cc]:
+     - added a copy constructor to allow conversion from MPedestalCam
+
+   * mpointing/MSrcPosCam.[h,cc]:
+     - added copy constructor
+
+
+
+ 2005/05/30 Daniela Dorner
+
+   * datacenter/scripts/buildsequenceentries, checkstardone, correcttime, 
+       doexclusions, fillcallisto, insertdatasets, runganymed, 
+       checkfilesforsequenceavail, copyscript, filesondisk, fillstar
+       runcallisto, runstar, writesequencefiles:
+     - moved two variables from the scripts to the sourcefile
+
+   * datacenter/scripts/runganymed: 
+     - changed # of processes
+
+   * datacenter/macros/buildsequenceentries.C, filldotrbk.C, fillstar.C,
+       insertcacofile.C, plotdb.C, setstatus.C, checkfileavail.C,
+       doexclusions.C, filldotrun.C, findcacofiles.C, insertdataset.C, 
+       resetallruns.C, setupdb.C, checkstardone., fillcalib.C, 
+       fillsignal.C, getdolist.C, insertdate.C, resetcolumn.C, 
+       writesequencefile.C: 
+     - adapted the macros to the changes in msql/MSQLServer.cc
+
+   * datacenter/macros/fillstar.C:
+     - adapted the functions for the myon parameter after the bugfixes 
+       in the calibration
+
+
+
+ 2005/05/27 Daniela Dorner
+
+   * datacenter/macros/plotdb.C:
+     - changed binning of fConvFactorInner
+     - added plot vs ZdMin
+
+   * datacenter/macros/resetcolumn.C:
+     - added (macro to reset value in the DB)
+
+   * datacenter/scripts/runganymed:
+     - removed command line option for ganymed, which is default now
+
+
+
+ 2005/05/27 Javier Rico (2005/05/26)
+
+   * mbadpixels/MBadPixelsCam.cc
+     - fixed small bug in the Print() function (one line was printed out 
+       at a wrong place). (M. Gaug)
+
+
+
+ 2005/05/27 Javier Rico (2005/05/24)
+
+   * mhcalib/MHCalibrationHiLoCam.cc
+     - do not write Arrays if flag kOscillations is not set. 
+       (this was actually a bug since it caused a huge usage for large 
+       amounts of data). (M. Gaug)
+
+   * mcalib/MCalibColorSet.cc
+     - set colour already in the ReInit(), needed by the digital filter 
+       later. (M. Gaug)
+ 
+   * mjobs/MJCalibration.cc
+     - forgot to merge hi-lo calibration factors for intensity calibration.
+       (M. Gaug)
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+     - do not Finalize histograms if a flag kReset is set. Caused wrong 
+       result in last run of intensity calibration. (M. Gaug)
+
+   * msignal/MC_calibration_weights_UV.dat
+     - Removed. It was confusing to have this file since it was just a 
+       copy of calibration_weights_UV.dat. For MC calibration you can 
+       just use the same weights files as for real data. (A. Moralejo)
+
+   * msignal/calibration_weights_blue46.dat
+     - added missing weights file (M. Gaug)
+
+
+
+ 2005/05/27 Markus Gaug (2005/05/21)
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - allow setting of extractor resolution in CalcReducedSigma()
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - implement usage of extractor resolution (only if UseExtractorRes
+       is set).
+
+
+
+ 2005/05/27 Thomas Bretz
+
+   * Makefile:
+     - removed mmontecarlo directory
+
+   * mmontecarlo/MMcEnergyEst.[h,cc], 
+     mmontecarlo/MMcTimeGenerate.[h,cc],
+     mmontecarlo/MMcWeightEnergySpecCalc.[h,cc]:
+     - removed
+
+   * sponde.rc:
+     - added new line for weighted spectral index
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]:
+     - added an option to perform the checks also in PostProcess
+
+   * mhbase/MFillH.h:
+     - added default argument to SetWeight
+
+   * mhbase/MH3.h:
+     - added Sumw2() member function
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - added TLatex output to plots
+     - added some Getter
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - implemented the possibility to weight the monte carlo spectrum
+       to a new index or function. More details can be found
+       in MMcSpectrumWeight
+     - slightly changed the plot comparing the size distributions
+     - scale the comparsison plots by the resulting spectrum
+
+   * mjobs/MJob.[h,cc]:
+     - added a member function to check ReadEnv of a single
+       container
+
+   * mjobs/Makefile:
+     - added -I../mmc
+
+   * mmc/MMcEvt.[hxx,cxx], mmc/McEvtBasic.[hxx,cxx]:
+     - changed the inheritance: MMcEvt now derives from MMcEvtBasic
+       so that both classes are interchangable
+     - increased both class versions
+     - chaged the default partictle in MMcEvtBasic from
+       kGAMMA to kUNDEFINED
+     - added new particle type: kUNDEFINED
+
+   * mhflux/MMcSpectrumWeight.[h,cc]:
+     - added
+
+   * callisto_Dec04Jan05.rc:
+     - commented MJPedestalC1.ExtractSignal.FallTimeHiGain 
+       because it is the dfeault now
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - changed default of fgFallTimeHiGain to 0.5
+
+   * mimage/MHillasSrc.h:
+     - added copy constructor and Copy function
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - implemented reading of automatic weights file following an
+       idea of Markus G.
+
+   * mjobs/MJPedestal.cc:
+     - fixed the reading of the resource file fopr the extractor
+       (reading the extractor from file can overwrite the seetings)
+
+   * msignal/MC_weights46.dat:
+     - updated from BCN cvs
+
+   * msignal/Makefile:
+     - added -I../mcalib
+
+   * callisto.rc:
+     - updated comments
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - same small changes to layout
+     - mainly unrolled Form-statements
+
+   * msignal/MExtractFixedWindow.cc:
+     - added case 12 and a default for logain setting the
+       extractor resolution (partly taken from bcn cvs)
+
+
+
+ 2005/05/25 Thomas Bretz
+
+   * callisto.cc, ganymed.cc, mars.cc, merpp.cc, readdaq.cc,
+     readraw.cc, sponde.cc, star.cc:
+     - made the output about the root version clearer
+
+   * mbase/MEvtLoop.cc:
+     - call CallProcess instead of Process for the mail tasklist
+       (this makes sure that all counters are correct) This should
+       NOT be done for Pre/PostProcess
+
+   * mbase/MStatusDisplay.cc:
+     - fixed a possible crash if padsave==NULL
+     - fixed the missing first tab in postscript files
+
+   * mbase/MTask.cc:
+     - initialize fNumExec0 with 0 (this was the reason why the
+       missing CallProcess in MEvtLoop didn't seem to have any effect
+       on the possible printing of the statistics
+
+   * mhflux/MAlphaFitter.cc:
+     - improved output
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - added some eMail from Wolfgang about treating the calibration
+       events to the class description
+     - removed some debug output in Paint()
+
+   * mhflux/MHThetaSq.cc:
+     - replaced \\theta by \\vartheta
+
+   * mhvstime/MHPixVsTime.cc:
+     - fixed a bug found by marcos: the error bars weren't retrieved
+       correctly (instead of fTypeErr fType was requested)
+
+   * mjobs/MJStar.cc:
+     - do not use calibration events for rate and effective-on-time
+       calculation
+
+   * mjobs/MJob.cc:
+     - added some debug output to ExpandPath
+
+   * msignal/MExtractTime.h, msignal/MExtractTimeAndCharge.h,
+     msignal/MExtractor.h:
+     - added Print() to //*MENU*
+
+
+
+ 2005/05/25 Daniela Dorner
+
+   * datacenter/macros/fillcalib.C, setupdb.C:
+     - changed presicion of parameter
+
+   * datacenter/macros/plotdb.C:
+     - added (macro to plot quality paramter from the DB)
+
+
+
+ 2005/05/24 Daniela Dorner
+
+   * datacenter/macros/fillstar.C:
+     - added new parameters
+
+   * datacenter/macros/setupdb.C:
+     - added variables for the new parameters
+
+
+
+ 2005/05/23 Daniela Dorner
+
+   * datacenter/scripts/fillstar:
+     - fixed bug in path
+
+   * datacenter/macros/fillstar.C, fillcalib.C, fillsignal.C:
+     - added check
+
+   * datacenter/macros/fillcalib.C, setupdb.C:
+     - adapted variables for the conversion factor
+
+
+
+ 2005/05/20 Thomas Bretz
+
+   * RELEASE 0.9.2
+
+
+
+ 2005/05/20 Daniela Dorner
+
+   * datacenter/scripts/insertdatasets,checkstardone:
+     - adapted paths for release
+
+   * datacenter/macros/fillstar.C:
+     - adapted functions to calculate psf and the ratio
+
+   * datacenter/scripts/runganymed:
+     - adapted ganymed command
+
+
+
+ 2005/05/20 Thomas Bretz
+   
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - increased log-gain window from 6 to 8 according to an
+       UNDOCUMENTED change in the bcn cvs
+
+   * mhcalib/MHCalibrationChargePINDiode.cc:
+     - removed a check in fill according to an UDOCUMENTED change
+       in the bcn cvs
+
+   * mhcalib/MHCalibrationChargePINDiode.cc:
+     - use a dynamic_cast for the Fill-argument
+
+   * mjobs/MJCalibration.cc:
+     - shortened output line telling file name of hi-/lo-gain
+       calibration
+
+   * mjobs/MJPedestal.[h,cc]:
+     - moved code for PulsePosCheck into own function
+     - put also code for pixel check into this function
+     - added a sanity check for fExtractor at some places
+
+   * msignal/MExtractor.cc:
+     - added output of pedestal container - if available - in Print()
+     - improved format of Print() output
+
+   * mbase/MEvtLoop.[h,cc]:
+     - removed the obsolete (it was never been used) argument from
+       PreProcess
+     - replaced the second obsolete argument in Eventloop by a flag
+       whether statistics should be printer or not: default=kTRUE
+     - Print statistics automatically in Eventloop if tasklists
+       Process has ever been touched.
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibration.cc, MJCalibrateSignal.cc,
+     mjobs/MJCut.cc, mjobs/MJOptimize.cc, mjobs/MJPedestal.cc,
+     mjobs/MJSpectrum.cc, mjobs/MJStar.cc:
+     - removed call to PrintStatistics - no done automatically in 
+       MEvtLoop
+
+   * mpedestal/MExtractPedestal.cc:
+     - removed InitArrays after ReInit of fExtractor. It is done there
+       automatically
+
+   * mjobs/MJCalibrateSignal.cc:
+     - don't add pinext and bldext to tasklist if not necessary
+       (UNDOCUMENTED change from bcn cvs)
+
+   * callisto.rc, callisto_Dec04Jan05.rc: 
+     - replaced wrong MaxHiGainVar by MaxSignalVar (was nowehere 
+       really used)
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc:
+     - some simplifications to the access of histograms after the loop
+       has finished. There is no need to search for them in the parameter
+       list.
+
+   * mjobs/MJCut.cc:
+     - fixed the file-path when writing the status display and an
+       output path was given.
+
+   * mjobs/hilocalib_sp1.root:
+     - new intercalibration constants due to the latest bug-fixes
+
+   * manalysis/MCameraData.[h,cc]:
+     - removed all stuff depending on MSigmabar
+
+   * manalysis/MSigmabar*
+     - removed
+
+
+
+ 2005/05/20 Markus Gaug (2005/05/19) 
+
+   * mjobs/MJPedestal.cc:
+    - fixed an important bug in the setting of the incoming pedestal 
+      pointer to the signal extractor. This bug caused the pedestals not
+      to be subtracted correctly in the calibration afterwards. The 
+      effect was about 10% too high conversion factors for the digital 
+      filter and the spline and more than 40% for the sliding window. 
+      The bug existed since end of February! (Markus G.)
+
+
+
+ 2005/05/20 Markus Gaug (2005/05/18) 
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - issue a warning if no colour has been set until the PostProcess.
+       (happens to old MC files).
+
+
+
+ 2005/05/19 Markus Meyer
+
+   * mmuon/MHMuonPar.cc:
+     - add a second integral in the function paint, which is 
+       plotted in the MStatusDisplay
+
+
+
+ 2005/05/19 Daniela Dorner
+
+   * datacenter/macros/fillstar.C:
+     - add new parameter
+
+   * datacenter/macros/setupdb.C:
+     - adapted to new column in db
+
+   * callisto_Dec04Jan05.rc:
+     - set value for MJPedestalY2.MaxEvents from 2000 to 5000 to get 
+       better statistics for the calculation of the mean pulse time
+       of the cosmisc
+
+   * datacenter/scripts/runganymed:
+     - fixed bug in path
+
+
+
+ 2005/05/19 Thomas Bretz
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - simplified a really cryptical use of the ?:-operator when
+       the fLoGainFirst is calculated
+     - fixed a bug introduced in the calculation of the derivatives
+
+   * mmain/MEventDisplay.cc:
+     - removed MC trigger display
+
+   * mbase/MTaskList.[h,cc]:
+     - member function to use MTaskList in a TIter
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - improved the output line plotted into the histogram
+     - implemented getter for fSigInt
+     - start integration in first bin not in underflow bin
+     - added 'background' option for scaling
+
+   * mhflux/MHAlpha.[h,cc]:
+     - added some comments
+     - improved DistancetoPrimitive
+
+   * mhflux/MHThetaSq.[h,cc]:
+     - derives the binning now from the cut value or the MAlphaFitter
+
+   * mjobs/MJStar.cc:
+     - moved weather data histogram back to the end - otherwise
+       MEventRate is not initialized before
+
+
+
+ 2005/05/18 Thomas Bretz
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - added missing fIntensQE to list of initialization in
+       constructor
+
+   * mcalib/MCalibrateData.cc:
+     - fixed a bug which caused kNo to be ignored
+     - removed a second check for the size of the badpixelcam
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed the obsolete second adding of filhil and filpul to
+       the tasklist
+
+   * mjobs/MJCalibration.cc:
+     - do not display result or statistics if no execution has taken
+       place
+
+   * mjobs/MJStar.cc:
+     - moved processing of CC-branch to the beginning of the tasklist
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]:
+     - introduced some small changes to the validity range of
+       some variables
+     - determin the higher bound above which no search is done
+       analog to the lower bound using the fall-time
+     - CalcIntegral[Hi,Lo]Gain now returns sum. No need for a reference
+     - fixed calling Integral[HI,Lo]Gain in cases we are at the edge of
+       the valid range -- at a lot of position in the code random memory 
+       above or below the arrays have been accessed.
+     - improved the numercila stability of CalcIntegral[Hi,Lo]Gain
+       more by calculating the number of steps from the rise and fall time.
+       this should at least give consistent results on the same machine!
+
+   * mbase/MContinue.cc:
+     - fixed a namimg problem of the filter when it is added to
+       the tasklist and has the same name as MContinue
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - for some sceen output the manipulator (inf) was missing
+
+   * msignal/MExtractPINDiode.cc, mcalib/MCalibrationChargeCalc.cc,
+     mcalib/MCalibrationChargeCam.cc:
+     - fixed a problem with the fit (it always tried to display
+       the fit-function somewhere)
+
+
+
+ 2005/05/17 Thomas Bretz
+ 
+   * callisto.rc, callisto_Dec04Jan05.rc:
+     - added new comments diescribing setup of MFCosmics
+
+   * mfilter/MFCosmics.[h,cc]:
+     - skip bad pixels using MBadPixelsCam
+     - implemented a check in PostProcess about the fraction
+       of events which survived or were rejected
+     - added ReadEnv for setup
+
+   * mfilter/Makefile:
+     - added mbadpixels
+     - removed mmain and manalysis
+
+   * mhcalib/MHCalibrationChargeCam.h:
+     - removed numbers from data member descrition -- too much
+       to maintain
+
+   * mhcalib/MHCalibrationChargePINDiode.h:
+     - incremented version number (undocumented from bcn)
+
+   * mjobs/MJCalibration.cc:
+     - reorganized some TText output (undocumented from bcn)
+     - overwrite the default of MaxNumberEmptyPixels by 0.05
+       (undocumented from bcn)
+     - print tasklist statistics also if eventloop returned
+       KFALSE
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - changed fgLoGainStartShift from -2.8 to -1.8 
+       (undocumented from bcn)
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.h:
+     - increased version number from 0 to 1 (undocumented from bcn)
+
+
+
+ 2005/05/17 Markus Gaug (2005/05/16)
+
+   * msignal/MExtractor.[h,cc]
+     - introduce two new variables: fResolutionPerPheHiGain and 
+       fResolutionPerPheLoGain, to be set by deriving extractors. 
+     - set version number one higher.
+
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractTimeAndChargeSlidingWindow.[h,cc]
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - set the variables fResolutionPerPheHiGain and 
+       fResolutionPerPheLoGain
+
+   * msignal/MExtractPINDiode.[h,cc]
+     - adapt to current PIN Diode signal, fit signal with Gaussian
+     - set version number up by one.
+     
+   * msignal/MExtractedSignalPINDiode.[h,cc]
+     - set new data member fExtractedChi2
+     - set version number up by one.
+
+   * mhcalib/MHCalibrationChargePINDiode.cc
+     - adapt one function to newly used names.
+     - adapt signal tests.
+
+   * mjobs/MJPedestal.[h,cc]
+     - read MBadPixelsCam together with extractor, if exisiting 
+       (necessary for bad pixels exclusion in pulse position search).
+
+   * mjobs/MJCalibration.[h,cc]
+     - use MFCosmics in any case (not only for CT1-pulses) and apply 
+       a quality criteria depending on number of rejected events: 
+       MaxExcludedEvents (default: 50%). 
+
+
+
+ 2005/05/17 Daniela Dorner
+
+   * datacenter/macros/setupdb.C
+     - adapted to new column in datasetstatus-table
+
+   * datacenter/macros/checkstardone.C
+     - added (macro to check if star has been done for a sequence)
+
+   * datacenter/scripts/checkstardone
+     - added (script that executes checkstardone.C for all datasets
+
+   * datacenter/scripts/checkfilesforsequenceavail, fillcallisto, 
+     fillstar
+     - fixed bug
+
+   * datacenter/scripts/buildsequenceentries, doexclusions,
+     writesequencefiles
+     - adapted paths
+
+   * datacenter/scripts/insertdataset
+     - added logging
+
+   * datacenter/scripts/runganymed
+     - added (script to run ganymed automatically for datasets)
+
+   * datacenter/scripts/runcallisto
+     - adapted paths
+     - fixed bug
+
+   * datacenter/scripts/runstar
+     - adapted paths
+     - fixed bug
+
+   * steps.rc
+     - adapted resource file to needs of the new table in db
+
+
+
+ 2005/05/13 Daniela Dorner
+
+   * datacenter/macros/insertdataset.C
+     - added (macro, that inserts dataset into db)
+
+   * datacenter/macros/setupdb.C
+     - adapted to new table in db
+
+   * datacenter/scripts/insertdatasets
+     - added (script, that inserts datasets into db)
+
+   * datacenter/scripts/sourcefile
+     - added (file with commands and variables, that are needed by all
+       scripts)
+
+   * datacenter/scripts/buildsequenceentries, checkfilesforsequenceavail
+                        copyscript, correcttime, doexclusions, 
+                        filesondisk, fillcallisto, fillstar, runcallisto
+                        runstar, writesequencefiles
+     - adapted scripts to the usage of the sourcefile
+
+   * datacenter/macros/fillcalib.C:
+     - changed name of histogram according to change of Markus
+     - removed debugoutput
+
+
+
+ 2005/05/13 Thomas Bretz
+
+   * mreport/MReportCC.cc:
+     - fixed reading of rep-files for versions newer than V200404070 
+
+   * mpointing/MSrcPosCalc.cc
+     - took a bugfix from Wolfgang to Loc0LocToCam and implemented it
+       Wolfgang: the results are changed only minimally
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - integration ranges were shifted by 0.2 FADC slices to the right. 
+       Fixed in the new algorithm according to Markus' change.
+
+   * mcalib/MCalibrationChargeCalc.h:
+     - Incremented ClassVersion number by 1
+   
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - removed a commented debug output
+
+   * mjobs/MJCalibration.cc
+     - new undocumented adjust of "Unsuitable"- and "Unreliable"-displays 
+       for new exclusion criteria taken from bcn
+
+   * manalysis/MEventRateCalc.cc:
+     - some fixes. In some cases the event rate wasn't calculated
+       anymore
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - fixed a bug when checking whether the check should be done
+       or not (>0 was missing)
+
+   * mhist/Makefile:
+     - added MHWeather
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - implemented new function the set minimum
+
+   * mjobs/MJStar.cc:
+     - read weather data (CC tree)
+     - set minimum of rate-display to 0
+     - display weather data for non-MC files
+
+   * mmuon/MHSingleMuon.cc:
+     - slight change to a comment
+
+   * callisto.rc:
+     - added new possible setup
+
+   * callisto_Dec04Jan05.rc
+     - added new possible setup
+     - use default for MJCalibration.ExtractSignal.LoGainSwitch
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - exclude unsuitable pixels from mean/rms calculation
+     - changed the lower bound for the second mean loop from
+       0.5 to 0.66
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - added case 102 returning the global unsuitable status
+       of an event
+
+   * mhist/MHCamEvent.h:
+     - added default 0 to SetThreshold
+
+   * mjobs/MJCalibrateSignal.cc:
+     - use new case 102 for unsuitable display
+     - enable counting (to get the correct display also with
+       profile option switched on)
+
+   * mraw/MRawRunHeader.cc:
+     - after displaying millions of hex numbers switch back to dec
+
+
+
+ 2005/05/13 Markus Gaug (2005/05/12)
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - set default extraction range in the high gain to 4.
+     - set default weights file to cosmics_weights46.dat
+
+   * mhcalib/MHCalibrationHiLoCam.cc
+     - set Oscillations to kFALSE
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - set default for fNumHiGainSaturationLimit to 0.15
+
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - put MHCalibrationHiLoCam and MHCalibrationPulseTimeCam directly 
+       into tasklist if needed. Otherwise, it does not read the 
+       resources from the config. file.
+
+
+ 2005/05/11 Markus Gaug (2005/05/11)
+
+   * mjobs/MJPedestal.cc
+     - adjust the fit ranges for the histogramming with moon data slightly.
+
+   * mcalib/MCalibrationChargeCam.cc, mcalib/MCalibrationChargeCalc.cc
+     - make a distinction between newly excluded pixels (by calibration)
+       and previously excluded pixels in the displays and print-functions
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - introduce the check for fluctuating arrival times.
+     - set charge limit to from 2.5 to 4.5
+     - introduce asymmetric exclusion due to "deviating number of phes":
+       Default: -9.0 +4.5
+     - make deviating number of phes unsuitable (see David's findings).
+   
+   * mbadpixels/MBadPixelsPix.h 
+     - add kDeviatingNumPhes to function GetUnsuitableCalLevel()
+
+
+
+ 2005/05/13 Daniela Dorner
+
+   * datacenter/scripts/runstar
+     - fixed bug in the calculation of the number of to-do-files
+
+   * datacenter/scripts/runcallisto
+     - fixed bug in the calculation of the number of to-do-files
+
+
+
+ 2005/05/12 Daniela Dorner
+
+   * datacenter/macros/fillcalib.C:
+     - removed debugoutput
+
+   * datacenter/macros/fillstar.C:
+     - added (macro to read parameters from the star*.root files and
+       fill them into the db)
+
+   * datacenter/macros/setupdb.C:
+     - added new table 'Star'
+
+   * datacenter/macros/buildsequenceentries.C:
+     - added delete-query for new table 'Star' in the delete function
+
+   * datacenter/scripts/runstar
+     - changed number of processes
+
+   * datacenter/scripts/runcallisto
+     - changed number of processes
+
+   * datacenter/scripts/fillstar
+     - added (script to run macro fillstar.C automatically)
+
+
+
+ 2005/05/12 Thomas Bretz
+
+   * mcalib/MCalibrationChargeCam.cc:
+     - fixed a bug in FinalizeArrivalTime which caused Form() to hang
+
+   * mmuon/MHMounPar.[h,cc]
+     - added a line showing a reference shape
+
+   * star.rc:
+     - added setup strings for software trigger
+
+   * mbase/MContinue.cc:
+     - allow setup of already set filters in ReadEnv. They must not
+       necessarily be already in the tasklist
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - shortened a lot of Form() calls to reduce the risk of
+       memory corruption
+
+   * mjobs/MJCalibration.cc:
+     - some cosmetics to text in pad
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - a fix to MRawRunHeader because the definition of the
+       raw-data format has changed. fProjectName and fSourceName
+       has no trailig \0 anymore by default
+     - incremented ClassVersion by 1
+
+
+
+ 2005/05/12 Markus Meyer
+
+   * mmuon/MHMounPar.[h,cc]
+     - added function Paint. This function integrates the TProfile
+       ArcWidth/Radius Vs. Radius between certain values and shows
+       the result in the Status Display
+
+   * mmjobs/MJStar.cc
+     - changed the default values for the final muon cuts
+     
+   * star.rc
+     - changed the default values for the final muon cuts
+
+
+
+ 2005/05/11 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - fixed year of copyright
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - undocumented change from BCN: a new resource has been implemented
+       in ReadEnv (NumEventsDump)
+
+   * mjobs/MJob.[h,cc]:
+     - added new static member function which can be used
+       to overwrite relative paths with a default
+
+
+
+ 2005/05/11 Abelardo Moralejo (2005/05/11)
+
+   * mjobs/MJPedestal.cc
+     - Fixed use of MFTriggerPattern: first, added it to the tasklist
+       (was missing); second, added to tasklist MTriggerPatternDecode
+       before MFTriggerPattern. This was the reason for the problems
+       reported by T. Coarasa on May 9. I do not know why the behaviour
+       of the previous version depended on compiler, but this seemed to 
+       be the case...
+
+
+
+ 2005/05/11 Markus Gaug (2005/05/11)
+
+   * mjobs/MJCalibration.cc
+     - display in Tab "Conv" in the 3rd column the conversion to equiv. 
+       phes instead of Cherenkov photons. 
+   
+   * mjobs/calibrationref.rc,  mjobs/calibrationref_Nov04.rc,
+     mjobs/calibrationref_Dec04.rc:
+     - add reference lines for the conv. to equiv. phes.
+
+   * mcalib/MCalibrationChargeCam.cc, mcalib/MCalibrationChargeCalc.cc:
+     - make a distinction between newly excluded pixels (by calibration)
+       and previously excluded pixels in the displays and print-functions
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - introduce the check for fluctuating arrival times.
+     - set charge limit to from 2.5 to 4.5
+
+
+
+ 2005/05/10 Markus Gaug (2005/05/10)
+
+   * mhcalib/MHCalibrationHiLoCam.cc
+     - ask for averageing and do not fill the arrays per pixel any more. 
+       This caused too much memory usage for the calculation of the 
+       high-gain low-gain inter-calibration constants.
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - store number of saturated events in the results container.
+     - set version number by one higher (due to new data member).
+ 
+   * mhcalib/MHCalibrationChargeCam.cc
+     - store number of saturated events in the results container.
+     - allow reading of NumHiGainSaturationLimit and 
+       NumLoGainSaturationLimit in ReadEnv
+     - set saturation limit from 5% to 8.5%
+
+   * mbadpixels/MBadPixelsPix.h
+     - introduce new bits: kDeadPedestalRms, kPreviouslyExcluded, 
+       kFluctuatingArrivalTimes
+
+   * mbadpixels/MBadPixelsCam.cc
+     - set bit kPreviouslyExcluded in the AsciiRead-Function
+     - include three new bits in the Print() function
+
+   * mjobs/MJCalibration.cc
+     - display excluded pixels from DeadPedestalRms in Defect-Tab.
+     - display correct error of the RMS/Mean charge diagramm.
+
+   * mcalib/MCalibrationChargeCam.cc
+     - calculate the error of RMS/Mean values in GetPixelContent Nr.33
+
+
+
+ 2005/05/11 Hendrik Bartko (2005/05/09)
+
+   * msignal/MC_weights46.dat
+     - updated weights file for digital filter with dedicated MC weights
+       with 4 slices for the high gain and 6 slices for the low gain
+
+
+
+ 2005/05/10 Daniela Dorner
+
+   * datacenter/macros/fillcalib.C:
+     - added some parameters (reading from calib*.root and inserting
+       into db)
+
+   * datacenter/macros/setupdb.C:
+     - adapted macro to the new columns in the calibration db
+
+   * datacenter/macros/fillsignal.C:
+     - fixed typo
+
+
+
+ 2005/05/10 Markus Meyer
+
+   * mmuon/*:
+     - update of the class documentation
+     
+   * mmuon/*:
+     - commented out the ArcLength and Estimpact (will be not 
+       calculated for the moment)
+
+
+
+ 2005/05/10 Thomas Bretz
+
+   * mreport/MReportStarguider.cc:
+     - introduced the correct version which marked the fix of the
+       units of the nominal position
+
+   * callisto.rc:
+     - introduced a new line for new option in MCalibColorFromPast
+
+   * ganymed.cc:
+     - removed option "--full-display" -> now default
+
+   * manalysis/MEnergyEstimate.cc:
+     - print the rule a bit earlier in PreProcess
+
+   * mfilter/MFDeltaT.cc:
+     - fixed a typo in the output
+
+   * mhflux/MAlphaFitter.cc:
+     - some improvements to output
+
+   * mjobs/MJCut.cc:
+     - added ThetaSquared to output
+
+   * mjobs/MJStar.cc:
+     - fixed bug in copying of OriginalMC tree
+
+   * mmuon/MMuonCalibParCalc.cc:
+     - removed obsolete setting of ReadyToSave
+
+   * mjobs/MJSpectrum.cc:
+     - made sure the correct type of MHAlpha is used
+
+
+
+ 2005/05/10 Markus Gaug (2005/05/09)
+
+   * mjobs/hilocalib_sp1.root
+   * mjobs/hilocalib_sp1_mc.root
+     - new hi-lo intercalibration files with the fixed spline extractor.
+
+   * mjobs/hilocalib_df46_mc.root
+     - new hi-lo intercalibration files from MC with the left out -O5 
+       option. (The real data files had already the correct executable).
+
+
+
+ 2005/05/10 Hendrik Bartko (2005/05/09)
+
+   * msignal/MC_weights46.dat
+     - NEW weights file for digital filter with dedicated MC weights
+       with 4 slices for the high gain and 6 slices for the low gain
+
+
+
+ 2005/05/10 Markus Gaug (2005/05/08)
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+     - introduce parameters fLowerFitLimit and fHigherFitLimit to 
+       tell explicitly from outside to fit functions in a certain 
+       range. If both are 0. (default), the histogram limits define 
+       the fit limits (as before).
+
+
+
+ 2005/05/10 Abelardo Moralejo (2005/05/07)
+
+   * mcalib/MMcCalibrationCalc.cc
+     - in Process, fixed wrong estimate of true number of "equivalent 
+       photoelectrons" (correctedphotel). This worked roughly OK as long
+       as the file used for calibration was a (noiselesss) gamma file,
+       because most light is contained in the inner camera and the
+       problem was related to the light going into the outer pixels. So
+       results are not much affected, unless one uses for calibration 
+       a file with events having a lot of light in the outer camera.
+       Thomas Hengstebeck noticed this problem when he used a file of MC 
+       calibration pulses in mccalibrate.C
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Added possibility to set the hi to lo gain conversion factor. 
+       Until now the factor was simply the ratio of pulse areas as read
+       from MMcFadcHeader. This of course is not the factor to be applied 
+       to the extracted signals unless the extractor integrates the full 
+       pulse in both high and low gain. The factor depends then on the
+       extractor, and the user has to find out what its value is.
+       Set as default calibration type kPhe.
+
+   * macros/mccalibrate.C, starmc.C
+     - Added the setting of the hi to lo gain conversion factor (see 
+       above). For now it has to be calculated by the user. However, it
+       is strongly recommended from now on to use always callisto for the
+       calibration of real data, and not these macros. These are kept 
+       just for checking purposes, mostly by "experts".
+
+
+
+ 2005/05/10 Robert Wagner (2005/05/06)
+
+   * mreport/MReportStarguider.[h,cc]:
+     - Bugfix: Sequence of extracting fDevZd and fDevAz (switched)
+
+
+
+ 2005/05/10 Markus Gaug (2005/05/05)
+
+   * mcalib/MCalibCalcFromPast.[h,cc]
+     - introduce flag "fUpdateWithFFactorMethod" which allows to use the
+       entire results obtained with the F-Factor method (including a new 
+       number of mean photo-electrons). This possibility is switched on 
+       (only) if somewhere in the callisto.rc file the following line is 
+       written:
+         MJCalibrateSignal.MCalibCalcFromPast.UpdateWithFFactorMethod: yes
+       (Default is still the old way of adjusting the relative extracted 
+       charges w.r.t. the mean charge over the inner camera).
+
+
+
+ 2005/05/10 Markus Gaug (2005/05/02)
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - added new function MergeHiLoConversionFactors
+
+   * mcalib/MCalibColorSteer.[h,cc]
+     - introduce copying of hi-lo calibration factors from one cam to 
+       the next in intensity calibration.
+     - added storage of averageing histograms of flag fHistStorage is
+       set
+
+   * mcalib/MCalibrationIntensityCam.[h,cc]
+     - introduce place for storage of averageing histograms (if wanted).
+
+
+
+ 2005/05/09 Markus Meyer
+
+   * mmuon/MHSingleMuon.cc
+     - changed the default value for the binning of fHistPhi
+     - changed the start parameter for the gaussian fit for the
+       calculation of ArcWidth
+
+
+
+ 2005/05/09 Thomas Bretz
+
+   * callisto.cc, ganymed.cc, mars.cc, merpp.cc, readdaq.cc,
+     readraw.cc, showplot.cc, sinope.cc, sponde.cc, star.cc:
+     - changed order of initialization such that a real NULL 
+       output is possible
+     - changed TApplication name from upper to lower case
+     - in some applications replaced manual setup of gLog with
+       gLog.Setup
+
+   * showlog.cc:
+     - improved alorithm
+
+   * showplot.cc:
+     - implemented Print options
+
+   * mbase/MLog.[h,cc]:
+     - fixed a bug which caused output in NULL output
+     - added Getter IsNullOutput
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - implemented PDF and SVG printing
+     - moved "Save As Something" to new submenu
+     - fixed and improved printing
+     - implemented PrintDialog for printing
+     - implemented printing of log (untested)
+     - allow saving by extension (line Print() in root): SaveAs
+
+   * mfileio/MWriteRootFile.h:
+     - replaced BIT(17) by BIT(23) to improve compatibility with
+       root 4.04/00 and upcomming versions
+
+   * mhflux/Makefile, mjobs/MJCut.cc:
+     - replaced MTheta by MThetaSq to get rid of a problem
+       with the automatic naming of the binning (BinningTheta)
+
+   * mhist/MHCamera.[h,cc]:
+     - fixed a workaround (it has been fixed in root 4.04/00)
+     - allow setting the palette through the Draw-option. This allows
+       storage of the palette
+     - removed fColor. The palette is now diretly set though gStyle in
+       Paint
+
+   * mjobs/MJOptimize.cc:
+     - restore null output correctly after eventloop
+
+   * mjobs/MJSpectrum.cc:
+     - renamed Hist and HistOff to HistE and HistEOff
+     - added binnings M3Long and Conc1
+
+
+
+ 2005/05/06 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - fixed constructor to work with newer root versions
+       (gClient!=NULL)
+
+   * mfileio/MWriteRootFile.h:
+     - added a comment about BITs used by root
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - use 1e-10 instead of 0 in TPad::Divide
+
+
+
+ 2005/05/06 Daniela Dorner
+
+   * datacenter/scripts/copyscript:
+     - added command to ensure the correct permissions of the files
+       on disk
+
+
+
+ 2005/05/04 Markus Meyer
+
+   * mjobs/MJStar.cc:
+     - added cut in ArcWidth (final cuts for muons)
+     
+   * star.rc:
+     - added cut in ArcWidth
+     
+   * mmuon/MHSingleMuon.h
+     - added a Getter for fHistWidth
+
+
+
+ 2005/05/04 Thomas Bretz
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed a possible infinite loop when compiling the new
+       file name as suggested by Abelardo
+
+   * mhflux/MHAlpha.cc:
+     - search for fName+"Off" instead of ClassName()+"Off"
+
+   * mjobs/MJSpectrum.cc:
+     - scale the displayed zd-plots by their maximum as the 
+       histograms are scaled before
+
+   * mjobs/MJStar.cc:
+     - implemented writing of the muon parameters. This takes another
+       5% of the time (in total 15-20% for muon analysis). It enlarges
+       the file size by roughly 15% (a test file was enlarged from
+       5.1M to 5.9M)
+
+   * mmuon/MMuonCalibPar.cc:
+     - set default of ArcPhi to an invalid value = -1
+
+   * mreport/MReportDrive.cc:
+     - fixed a typo in the comments
+
+
+
+ 2005/05/03 Thomas Bretz
+
+   * mjobs/MJCut.cc:
+     - added histogram <Fake->'OnTime' for MC
+
+   * mpointing/MSrcPosCalc.cc:
+     - removed dependancy on MTime for MC
+
+   * star.cc:
+     - addde possibility to switch off  muon analysis
+
+   * star.rc:
+     - added parameters for muon analysis
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - fixed a typo in a comment
+
+   * mjobs/MJStar.[h,cc]:
+     - added possibility to switch off muon analysis
+
+   * mjobs/Makefile:
+     - added -I../mmuon
+
+   * mjobs/MJCut.cc, mjobs/MJSpectrum.cc:
+     - renamed MHAlpha to Hist (to have a common naming for all options)
+     - renamed MHAlphaOff to HistOff
+
+
+
+ 2005/05/02 Thomas Bretz
+
+   * ganymed.rc:
+     - updated to the latest changes
+
+   * mhflux/MHAlpha.[h,cc]:
+     - made a base class with the necessary interface to derived classes
+       to support other variables like dca or theta
+
+   * mjobs/MJCut.[h,cc]:
+     - added support for MHAlpha derived classes
+     - made MHTheta the default
+
+   * mhflux/MHTheta.[h,cc]:
+     - added
+
+   * mhflux/Makefile, mhflux/FluxLinkDef.h:
+     - added MHTheta
+
+
+
+ 2005/04/29 Thomas Bretz
+
+   * manalysis/MEventRateCalc.cc:
+     - fixed jumps when a new run is initiated
+     - set as time a time which represents the starting point
+       of the calculation interval in all cases
+
+   * star.rc, mmuon/MMuonCalibParCalc.cc, mmuon/MMuonSetup.[h,cc]:
+     - fixed wrong units of thresholds for muon analysis
+
+   * mmuon/MHSingleMuon.cc:
+     - removed obsolete conversion factor in error calculation
+     - FindeCreateObj called for MMuonSetup
+     - get NDF from fit
+     - optimized FindRangeAboveThreshold
+     - handle special case when arcphi is 360deg
+
+   * star.cc:
+     - replaced ProcessFile by Process
+
+   * mjobs/MJSpectrum.cc:
+     - renamed second MHAlpha tab to MHAlphaOn to be able to
+       access each tab uniquely
+     - fixed a bug calling SetStats which could cause crashes
+
+   * mjobs/MJStar.[h,cc]:
+     - preliminary implementation of the muon analysis
+     - reanamed ProcessFile to Process
+
+
+
+ 2005/04/28 Thomas Bretz
+
+   * manalysis/MMultiDimDistCalc.[h,cc]:
+     - replaced MHadronness by MParameterD
+
+   * mhflux/MHEnergyEst.cc:
+     - removed obsolete include of MEnergyEst
+
+   * mmuon/MHMuonPar.cc:
+     - fixed a type in an axis label
+
+
+
+ 2005/04/27 Thomas Bretz
+
+   * Makefile:
+     - added mmuon
+     - remobed mstarcam
+
+   * callisto.cc, ganymed.cc, star.cc:
+     - renamed ProcessFile to Process
+
+   * star.rc:
+     - added some muon parameters
+
+   * mastro/MAstroCamera.[h,cc]:
+     - temporarily removed interface to MStarPos
+
+   * mbase/MStatusArray.h:
+     - added default constructor
+
+   * mcalib/MCalibColorSet.cc:
+     - added runs 39942, 39944, 44834, 39941, 39943 and 44833
+       (undocumented change from the BCN cvs)
+
+   * mjobs/MJCalib.[h,cc], mjobs/MJCalibTest.[h,cc],
+     mjobs/MJCalibrateSignal.[h,cc], mjobs/MJCalibration.[h,cc],
+     mjobs/MJCut.[h,cc], mjobs/MJPedestal.[h,cc]:
+     - removed support for MRunIter (use the setter of MSequence
+       instead) -- this makes the code a lot easier to maintain
+     - removed support for autodetection if the output already exists --
+       this makes the code a lot easier to maintain
+     - renamed ProcessFile to Process - which was missleading
+
+   * mmuon/MHMuonPar.[h,cc]:
+     - changes to axis labels etc.
+
+   * mmuon/MMuonCalibPar.[h,cc]:
+     - removed the histograms and all obsolete variables
+     - removed obsolete SetUseUnmap (this cannot happen 
+       by definition of Unmap)
+
+   * mmuon/MMuonCalibParCalc.[h,cc]:
+     - moved the code for calculation the parameters to new class
+       MHSingleMuon
+
+   * mmuon/MMuonSearchPar.[h,cc]:
+     - replaced arbitrary fir by minuit (faster and more accurate)
+     - removed precalculation of muon center - makes fit worse
+
+   * mmuon/MMuonSearchParCalc.[h,cc]:
+     - fixes to comments
+     - fixes to includes
+
+   * mmuon/MMuonSetup.[h,cc]:
+     - binnings removed (replaces by MBinning)
+
+   * mmuon/Makefile, mmuon/MuonLinkDef.h:
+     - added MHSingleMuon
+
+   * msignal/MExtractTimeAndchargeSpline.cc:
+     - fixed a bug found by Abelardo which could cause different
+       results with different compiler optimiztaion options due
+       to rounding errors.
+
+
+
+ 2005/04/25 Thomas Bretz
+
+   * ganymed.cc:
+     - changed policy of writing the resulting events to the result file
+
+   * sponde.cc:
+     - added commandline option to use all monte carlos
+     - added command line option to read the MCs more accurate
+
+   * sponde.rc:
+     - added
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added some code to get Tab by name
+     - fixed a typo in a status line output
+
+   * mhbase/MH.[h,cc], mhbase/MH3.[h,cc], mhflux/MHFalseSource.h,
+     mhist/MHCamEvent.[h,cc], mhist/MHCamEventRot.h,
+     mhist/MHEvent.h, mhist/MHStarMap.h, mhist/MHTriggerLvl0.[h,cc],
+     mhistmc/MHMcTriggerLvl2.[h,cc], mhvstime/MHPixVsTime.[h,cc],
+     mhvstime/MHSectorVsTime.[h,cc], mimage/MHHillas.[h,cc],
+     mimage/MHHillasExt.[h,cc], mimage/MHHillasSrc.[h,cc],
+     mimage/MHImagePar.[h,cc], mimage/MHNewImagePar.[h,cc]:
+     - changed GetHistByName to be const-qualified to be compatible
+       with FindObject
+     - added some FindObject function to call GetHistByName
+
+   * mhflux/MHAlpha.[h,cc]:
+     - changed such, that it can be forced to display the excess
+       events versus size
+
+   * mjobs/MJCut.[h,cc]:
+     - display number of excess events versus Size per default
+     - removed energy estimator
+
+   * mjobs/MJOptimize.cc:
+     - display number of excess events verss size after optimization
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - implemented setting up energy estimator
+     - replaced some gLog by fLog
+     - display comparison of image parameters
+
+
+
+ 2005/04/22 Thomas Bretz
+
+   * mbase/MStatusArray.[h,cc]:
+     - switch off adding histograms to gDirectory in newly
+       overwritten Read-function
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - implemented member function GetHistSel
+     - don't display full statistics
+     - fixed a possible crash in Paint
+
+
+
+ 2005/04/22 Markus Meyer
+
+    * mmuon/MMuonSetup[.h.cc]: 
+      - new container class for muon parameters
+        which are not changing from event to event
+        (setup parameters for the analysis). These
+        parameters were stored in MMuonCalibPar before
+      
+    * mmuon/MMuonCalibPar[.h.cc]:
+      - changed MCerPhotEvt and MCerphotPix to MSignalCam
+        and MSignalPix to read the new format
+      - removed the setup parameters (stored now in 
+        MMuonSetup)
+      - removed all the sanity checks
+      - removed pre-cuts
+      - cuts in process, to save only muon-like events
+      
+    * mmuon/MMuonCalibParCalc[.h.cc]:
+      - changed MCerPhotEvt and MCerphotPix to MSignalCam
+        and MSignalPix to read the new format
+      - removed pre-cuts
+      
+    * mmuon/MMuonSearchPar[.h.cc]:
+      - changed MCerPhotEvt and MCerphotPix to MSignalCam
+        and MSignalPix to read the new format
+      - 
+	
+    * mmuon/MMuonSearchParCalc[.h.cc]:
+      - changed MCerPhotEvt and MCerphotPix to MSignalCam
+        and MSignalPix to read the new format
+	
+    * mmuon/MHMuonPar[.h.cc]:
+      - new histgram class, plots different muon 
+        parameters
+
+
+
+ 2005/04/21 Daniela Dorner
+
+   * datacenter/scripts/runcallisto: 
+     - fixed choice of todofile
+     
+   * datacenter/scripts/copyscript:
+     - adapted some paths
+     
+   * datacenter/macros/filldotrun.C:
+     - added 6 new arehucas versions
+     
+   * datacenter/scripts/writesequencefile:
+     - added make path for sequencefiles
+
+
+
+ 2005/04/21 Thomas Bretz
+
+   * mhcalib/MHCalibrationRelTimeCam.cc:
+     - fixed usage of a uninitialized pointer
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc:
+     - fixed usage of MFTriggerPattern
+
+   * mtrigger/MFTriggerPattern.[h,cc]:
+     - allow to set default from outside in case no pattern
+       could be decoded
+
+
+
+ 2005/04/20 Thomas Bretz
+
+   * callisto.cc:
+     - added a comment which shows how to correctly skip job2 if
+       extractor doesn't inherit from MExtractTimeAndCharge, but...
+       // This could skip job2 if extractor doesn't inherit from
+       // MExtractTimeand Charge... but this is not necessary.
+       // We only get the same pedestal twice (which we want to have
+       // anyhow. A switch when using the result of job2 later is also
+       // not necessary, because without running job2 it is identical
+       // with job1
+
+   * mjobs/MSequence.cc:
+     - use the sequence number'd directories in case of calibrated data
+       and image files instead of the date.
+
+   * mhflux/MAlphaFitter.cc:
+     - copy also results in Copy()
+
+   * mjobs/MJOptimize.cc:
+     - print result of optimization in case MAlphaFitter is used
+     - store results back in initial MAlphaFitter
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - implemented a faster simple mode weighting the read spectrum
+       with the theta-probability
+
+
+
+ 2005/04/20 Daniel Mazin (2005/04/18)
+
+   * mreport/MReportCamera.[h,cc]
+     - added necessary changes to include Active Load and Central Pixel 
+       info from Camera reports
+   
+   * mcamera/MCameraActiveLoad.[h,cc]
+     - added to store Active Load info from the Camera reports
+
+   * mcamera/MCameraCentralPix.[h,cc]
+     - added to store Central Pixel info from the Camera reports
+
+   * mcamera/Makefile 
+   * mcamera/CameraLinkDef.h 
+     - added MCameraActiveLoad and MCameraCentralPix classes
+
+
+
+ 2005/04/20 Markus Gaug (2005/04/15)
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - added new function CopyHiLoConversionFactors
+
+
+
+ 2005/04/20 Markus Gaug (2005/04/14)
+
+   * mcalib/MCalibColorSteer.[h,cc]
+     - fixed a bug in the recognition of the calibration bit pattern. 
+       Concerns only intensity calibration.
+
+   * mcalib/MCalibrationRelTimeCalc.cc
+     - return kTRUE instaed of kFALSE in case that the Process() has 
+       never been executed.
+
+   * mjobs/MJCalibration.cc
+     - add a filter against PIN Diode events since some of the recent 
+       calibration runs have been taken with Pin Diode.
+
+
+
+ 2005/04/12 Markus Gaug
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - added a storage place for the run number
+
+   * mcalib/MCalibCalcFromCalc.[h,cc]
+     - store the run number in the individual MCalibrationCams 
+
+
+
+ 2005/04/19 Thomas Bretz
+
+   * mjobs/MJCut.cc:
+     - fixed a problem when not enabling "--res"
+
+   * mimage/MHVsSize.[h,cc]:
+     - added more displayed variables
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - added
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJSpectrum
+
+   * Makefile:
+     - added sponde.cc
+
+   * sponde.cc:
+     - added
+
+   * mhbase/MBinning.h:
+     - added Print() to //*MENU*
+
+   * mhflux/MAlphaFitter.cc:
+     - do not set inf-flag in Print()
+
+   * mhflux/MHAlpha.[h,cc]:
+     - set all-flag for printing MAlphaFitter("result")
+     - added Getter for excess histogram
+
+   * mjobs/MDataSet.[h,cc]:
+     - allow to initialize a TChain from this dataset
+
+   * mjobs/MJCut.cc:
+     - moved energy estimator back before Cut0 otherwise the
+       EnergyEst container is missing in summary file
+
+   * mhflux/MHCollectionArea.cc:
+     - draw efficiency into third pad
+
+
+
+ 2005/04/18 Thomas Bretz
+
+   * manalysis/MCompProbCalc.cc, mbadpixels/MBadPixelsCalc.cc,
+     mbadpixels/MBadPixelsTreat.cc:
+     - some fixes to documentation (THtml complained about missing
+       classes)
+
+   * mbase/MStatusArray.[h,cc]:
+     - implemented some functions to print contents of StatusArray
+       and/or tab/canvas.
+
+   * mhbase/MFillH.cc:
+     - remove fH from ListOfPrimitives before adding Clone in
+       PostProcess
+
+   * mhbase/MH.[h,cc]:
+     - implemented new member function RemoveFromPad (necessary
+       if a class should support same-option)
+
+   * mimage/MHHillas.cc, mimage/MHHillasExt.cc, mimage/MHHillasSrc.cc,
+     mimage/MHImagePar.cc, mimage/MHNewImagePar.cc, mimage/MHVsSize.cc:
+     - fixed naming in case of same-option in Draw
+     - remove previous histograms from pad in case of same-option
+
+   * mjobs/MJCut.[h,cc]:
+     - write all binnings in WriteResult
+     - write MHillasExt to output
+     - BinningWidth, BinningLength and BinningDist added
+
+   * mjobs/MJOptimize.[h,cc]:
+     - fixed a typo in output
+     - allow to exchange Test-/Train-Sample
+
+   * ganymed.cc:
+     - implemented "-mc" option to allow cutting MC samples
+
+   * showlog.cc:
+     - implemented real treatment of debug-levels
+     - return 1 instead of 0 in cae of normal finish
+
+   * manalysis/MEnergyEstimate.h, mbase/MContinue.h,
+     mhflux/MAlphaFitter.h:
+     - added Print() to context //*MENU*
+
+   * manalysis/MMatrixLoop.cc:
+     - fixed returning of number of entries if using split mode
+
+   * mbase/MContinue.cc:
+     - implemented Print() function
+
+   * mbase/MParContainer.[h,cc]:
+     - in Read set name of object to argument name if argument!=NULL
+     - reordered some checks for Method calls
+
+   * mdata/MDataFormula.cc:
+     - fixed a problem with the replacement if using [?] for
+       fits
+
+   * mfbase/MFEventSelector2.cc:
+     - replaced some +=1 and -=1 by ++ and --
+
+   * mfileio/MReadMarsFile.cc:
+     - fixed a bug which caused Preprocess to crahs if instatiated
+       with default constructor
+
+   * mhbase/MH.cc, mhflux/MHEffectiveOnTime.cc:
+     - use dynamic_cast if getting "stats"
+
+   * mhflux/MAlphaFitter.cc:
+     - small updates to output
+
+   * mhflux/MHEnergyEst.cc:
+     - fixed all axis lables
+     - implemented fit of resolution
+     - initialize fBias=0 in SetupFill
+     - enhances Print() output
+
+   * mjobs/MJCalibrateSignal.cc:
+     - moved all tasks for interleaved calibration events to
+       a third tasklist
+
+   * mjobs/MJCut.[h,cc]:
+     - implemented correct treatment of MC files
+     - write resulting events to result file if no filename set
+     - moved energy estimator behind cuts
+
+   * mjobs/MJOptimize.cc:
+     - changed RunEnergy such, that it can correctly treat
+       MC files written by ganymed using wobble-mode
+
+   * mbase/MStatusDisplay.cc:
+     - fixed a possible crash in GetFullPad
+
+   * mhbase/MBinning.[h,cc]:
+     - implemented Copy Constructor
+
+   * mhflux/MHCollectionArea.h:
+     - call CalcEfficiency in Finalize
+
+   * mhflux/MHEnergyEst.[h,cc]:
+     - implemented GetWeights
+
+   * mimage/MHHillas.cc, mimage/MHHillasExt.cc, mimage/MHHillasSrc.cc,
+     mimage/MHImagePar.cc, mimage/MHNewImagePar.cc, mimage/MHVsSize.cc:
+     - remove histograms from global directory if name was changed
+       in Draw
+
+   * mimage/MHVsSize.cc:
+     - exhanged the arguments of TMath::Sign
+
+
+
+ 2005/04/14 Thomas Bretz
+
+   * Release 0.9.1
+
+
+
+ 2005/04/14 Thomas Bretz
+
+   * mjobs/MJCut.cc:
+     - added MPointingPos to output
+
+
+
+ 2005/04/13 Thomas Bretz
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - implemented new Image types which can be written
+
+   * mhbase/MBinning.[h,cc]:
+     - added some more constructors which can set the binning directly
+
+   * mhflux/MHEnergyEst.h:
+     - added getter for fHEnergy
+
+   * mhflux/FluxLinkDef.h, mhflux/Makefile:
+     - added MHCollectionArea
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - added
+
+
+
+ 2005/04/13 Daniela Dorner
+
+   * datacenter/macros/fillcalib.C:
+     - added update
+   
+   * datacenter/scripts/copyscript
+     - fixed bug / changed path
+   
+   * datacenter/macros/setupdb.C
+     - added table
+
+
+
+ 2005/04/12 Daniela Dorner
+
+   * datacenter/macros, datacenter/scripts:
+     - added
+   
+   * datacenter/macros/buildsequenceentries.C, 
+     datacenter/macros/checkfileavail.C, 
+     datacenter/macros/doexclusions.C, 
+     datacenter/macros/fillcalib.C, 
+     datacenter/macros/filldotrbk.C, 
+     datacenter/macros/filldotrun.C, 
+     datacenter/macros/fillsignal.C, 
+     datacenter/macros/findcacofiles.C, 
+     datacenter/macros/getdolist.C, 
+     datacenter/macros/insertcacofile.C, 
+     datacenter/macros/insertdate.C, 
+     datacenter/macros/resetallruns.C, 
+     datacenter/macros/setstatus.C, 
+     datacenter/macros/setupdb.C, 
+     datacenter/macros/writesequencefile.C, 
+     datacenter/scripts/buildsequenceentries
+     - added macros to do the automatic procedures in the datacenter
+     
+   * datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/copyscript, 
+     datacenter/scripts/correcttime, 
+     datacenter/scripts/doexclusions, 
+     datacenter/scripts/filesondisk, 
+     datacenter/scripts/fillcallisto, 
+     datacenter/scripts/runcallisto, 
+     datacenter/scripts/runstar, 
+     datacenter/scripts/writesequencefiles
+     - added scripts to do the automatic procedures in the datacenter
+
+   * automatic-exclusions.rc, steps.rc
+     - added rc files for the automatic procedures
+
+
+
+ 2005/04/12 Thomas Bretz
+
+   * Makefile:
+     - for the moment remove mhistmc from compilation
+
+   * ganymed.cc:
+     - return 2 when detecting wrong commandline argument
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - removed MEnergyEst (replaced by a simple MParameterD)
+
+   * manalysis/MEnergyEstimate.[h,cc]:
+     - replaced MEnergyEst by MParameterD
+     - implemented Print() function
+     - updated ClassVersion from 0 to 1 to allow storage of 
+       energy estimator
+
+   * mbase/MStatusArray.[h,cc]:
+     - overloaded DisplayIn to allow displaying a single tab
+     - added some output if ObjectInCanvas not found
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - enhanced Read() and Display() with the possibility to only
+       read or display a single tab
+
+   * mcalib/MCalibrateData.cc:
+     - enhancements to logging output
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - some fixes to format of logging output
+
+   * mfbase/MF.[h,cc]:
+     - changed kAllowEmpty from a bit to the new datamember fAllowEmpty.
+       This was necessary to allow storage of MF into files
+     - changed ClassVersion from 0 to 1
+
+   * mhbase/MBinning.cc:
+     - fixed SetEdgesRaw (lin, log, etc was ignored)
+
+   * mhflux/MHAlpha.[h,cc]:
+     - replaced MEnergyEst by MParameterD
+     - renamed Theta to ExcessTheta
+     - renamed Energy to ExcessEnergy
+     - renamed Size to ExcessSize
+     - renamed Time to ExcessTime
+
+   * mhflux/MHEnergyEst.[h,cc]:
+     - replaced MEnergyEst by MParameterD
+     - implemented Print() function
+     - some fixes to displaying the histograms. This makes sure,
+       that no crashes happen, but unluckily it works correctly only
+       with root 4.02/00
+
+   * mjobs/MJOptimize.[h,cc]:
+     - implemented a AddPreCut taking a MFilter as argument
+     - SetBit(kCanDelete) for all internal PreCuts
+     - Print the result of the energy estimation after it was done
+
+   * mranforest/MRFEnergyEst.[h,cc]:
+     - replaced MEnergyEst by MParameterD
+
+   * mfileio/MReadTree.cc:
+     - shortened the output a bit when siwtching to the next file
+
+
+
+ 2005/04/11 Thomas Bretz
+ 
+   * manalysis/MMatrixLoop.[h,cc]:
+     - implement option to divide matrix into two samples
+
+   * mhflux/MHEnergyEst.cc:
+     - changed to display projection of enegry resolution
+     - fixed to use correct minimization value
+
+   * mjobs/MJOptimize.[h,cc]:
+     - implemented option to divide sample into test/train
+
+   * mcalib/MCalibCalcFromPast.cc, mcalib/MCalibColorSteer.cc,
+     mcalib/MCalibrationChargeCalc.cc, mhcalib/MHCalibrationCam.cc:
+     - small updates to log-output
+
+   * mhflux/MAlphaFitter.cc:
+     - output scale-factor
+
+   * mhist/MHCamera.cc:
+     - as a workaround for a severe problem in gStyle->SetPalette
+       when using the deep blue sea I have switched off this
+       Platte for the moment
+
+
+
+ 2005/04/08 Markus Gaug (2005/04/07)
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - UNDOCUMENTED CHANGE: Do not call histlo.CreateFourierSpectrum()
+       if IsOscillations()
+
+   * mjobs/MJCalibrateSignal.cc:
+     - UNDOCUMENTED CHANGE: Set SetOscillations(kFALSE) for
+       hchacam, hbndcam, hrelcam
+
+   * mhcalib/MHCalibrationRelTimeCam.cc:
+     - fill array only if IsOscillations() is true. This is the case in 
+       all classes deriving from MHCalibrationCam, except for this one! 
+       The effect was that the interlaced calib. events occupied more 
+       and more memory becoming slower and slower because the option: 
+       SetOscillations(kFALSE) was not treated correctly. 
+
+   * mjobs/pedestalref_Dec04.rc
+     - update the reference lines in the display according to the spline
+       extractor.
+
+   * mjobs/MJCalibration.cc
+     - clarify a mis-leading histogram title
+
+   * callisto_Dec04Jan05.rc:
+     - UNDOCUMENTED CHANGE: use the pedestref_Dec04.rc as reference
+       file.
+
+
+
+ 2005/04/08 Thomas Bretz
+
+   * mhbase/MH3.cc:
+     - replaced all Float-histograms by double histograms. This
+       is backward compatible with I/O and has the advantage, that
+       we are compatible with most other double histograms used in
+       Mars
+
+   * mhflux/MHEnergyEst.cc:
+     - made the energy binning the same than in all other classes
+
+   * mreport/MReportStarguider.[h,cc]:
+     - implemented new values from new starguider report as defined
+       in TDAS00-07 V7.1
+     - Fixed the formerly wrong unit of fDevAz and fDevZd (unit now
+       is arcmin)
+
+   * mjobs/MJCalibrateSignal.cc:
+     - first replaced contmc by a new filter Markus G. used, but
+       after a discussion with Abelardo it turned out, that the 
+       original filter does a better job, becuase it takes both
+       (level 1 trigger and minimum number of phes) conditions
+       used in the MC into account.
+
+   * mjobs/MJCut.cc:
+     - added a plot: Effective-On-Time versus Theta used to produce
+       a spectrum
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed condition IsUseBlindPixel() and IsUsePINDiode from
+       setting filter and applied it to the corresponding task
+
+   * mjobs/MDataSet.cc:
+     - fixed a bug using the default paths
+
+
+
+ 2005/04/07 Thomas Bretz
+
+   * mpointing/MSrcPosCalc.cc:
+     - also skip Process if fSourcePos==NULL, this happens in real
+       data, too, if no pointing correction is done.
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - removed MParameterI, MParameterD, MParameterDerr
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MParameterI, MParameterD, MParameterDerr
+
+   * mbase/MParList.cc:
+     - if a container is rejected due to wrong inheritance its
+       inheritance is mentioned in the error message
+
+   * mhbase/HBaseLinkDef.h, mhbase/Makefile:
+     - removed MWeight
+
+   * mhbase/MWeight.[h,cc]:
+     - removed, replaced by MParameterD
+
+   * mhbase/MFillH.[h,cc], mmontecarlo/MMcWeightEnergySpecCalc.[h,cc]:
+     - replaced MWeight by MParameterD
+
+   * mjobs/MJStar.cc:
+     - fixed the wrong axis title in the histogram showing the rate
+
+   * manalysis/MParameters.[h,cc]:
+     - moved to mbase
+
+   * mbase/MParameters.[h,cc]:
+     - inherit MParameterDerr from MParameterD
+     - changed class version of MParameterDerr from 1 to 2
+
+   * mfbase/MFEventSelector2.cc:
+     - fixed that in SelectProb the wrong bin was chosen
+
+
+
+ 2005/04/07 Markus Gaug (2005/04/06)
+
+   * mjobs/calibrationref_Dec04.rc
+   * callisto_Dec04Jan05.rc
+     - update the reference lines in the display according to the spline
+       extractor.
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - move fgHiGainFirst from 2 to 0. This is important for the Dec. und 
+       January data where the calib. pulse position changes much.
+
+   * mjobs/MJCalib.cc
+   * mjobs/MJCalibration.cc
+     - move fDevice and functions IsUseBlindPixel() and 
+       IsUsePINDiode() into the base class.
+
+   * mjobs/MJCalibrateSignal.cc
+     - do not apply the modified extraction window to the interlaced
+       calibration events. This is a bugfix especially for the 
+       December and January data.
+     - extract and fit blind pixel and pin diode only if flag 
+       IsUseBlindPixel() or IsUsePINDiode() is set.
+
+
+
+ 2005/04/07 Markus Gaug (2005/04/03)
+  
+   * mcalib/MCalibrateData.cc
+     - made one warning more understandable.
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - moved fgOffsetFromLogain from -1.8 to -2.8. This corrects only an 
+       defective extraction of the MC at low-gain signals lower than 90 
+       phes.
+
+
+
+ 2005/04/07 Markus Gaug (2005/04/01)
+ 
+   * mpedestal/MExtractPedestal.[h,cc]
+     - use the standard way to define the default for fNumEventsDump
+     - added missing "NumDump" in ReadEnv
+
+   * callisto_*.rc
+     - correct the default of the number of events used in 
+       pedestal calculation (NumEventsDump).
+     - added missing lines for setting of parameters for the 
+       MJCalibrateSignal.PedCalcFromExtractRndm.*
+       (CORRECTED SOME BUGS IN THIS LINES)
+     - Replaced NumEventsDump by NumDump
+
+
+
+ 2005/04/05 Thomas Bretz
+
+   * mjobs/MSequence.cc:
+     - fixed a bug in SetupDatRuns. P was setup instead of D
+
+   * star.cc, mjobs/MJStar.cc:
+     - fixed wrong setup of data-files
+
+   * mjobs/pedestalref_Feb05.rc, mjobs/hilocalib_sp1.root,
+     mjobs/hilocalib_sp1_mc.root:
+     - added
+
+   * mimage/MHillasCalc.[h,cc]:
+     - implemented missing ReadEnv - DON'T KNOW WHERE IT WAS! argh...
+
+   * mmc/MMcCorsikaRunHeader.h:
+     - added Getter for fWobbleMode
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - added detection of MC files and setting of source position 
+       according to wobble mode flag in MMcCorsikaRunHeader
+     - fixed a bug in ReadEnv (wrong return statement) found
+       by Abelardo. Correct handling of floating point numbers
+       in the source position (12.5) was affected.
+
+
+
+ 2005/04/04 Thomas Bretz
+
+   * callisto.cc, sinope.cc, mjobs/MDataSet.[h,cc], mjobs/MJCalibTest.cc,
+     mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc,
+     mjobs/MSequence.[h,cc]
+     - changed setup procedure for paths to allow using standard 
+       paths everywhere
+     - fixed to use new correct datacenter standard paths
+     - made sure, that the sequences in a dataset are sorted by
+       their number to ensure the correct synchronization
+
+   * mhflux/MHAlpha.cc:
+     - display correct error (excess/significance)
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJPedestal.cc:
+     - removed MPointingPosCalc from Tasklist
+
+   * mjobs/MJStar.cc:
+    - added MPointingPosCalc to tasklist for "Events" in case of MC
+
+   * ganymed.cc, mjobs/MJCut.[h,cc]:
+     - implemented an option to enhance the display
+     - do not display FS plot in wobble mode
+     - made sure files are not written when they should not be written
+
+   * mhflux/MHAlpha.[h,cc]:
+     - let FitEnergyBins return the mean of the significance of
+       all Energy Bins
+
+   * mimage/MHHillasExt.cc, mimage/MHHillasSrc.cc, 
+     mimage/MHImagePar.cc, mimage/MHNewImagePar.cc:
+     - implemented or fixed implementation of "same" Draw-option
+     - slightly modified binning for Dist in MHHillasSrc
+
+   * mjobs/MJCalibrateSignal.cc:
+     - do not plot pulse time twice
+
+   * mjobs/MJOptimize.cc:
+     - print all parameters in minuit after they have been
+       setup
+
+
+
+ 2005/04/01 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - switched on bad pixel detection for a pedestal level
+       which is more than 5 times the variance
+
+   * mfbase/MF.cc:
+     - when fixing the "Inverted" bit in ReadEnv don't print a 
+       message on the screen
+
+   * mhflux/MHAlpha.cc:
+     - plot correct errors
+     - do not plot the point if its significance is not greater 1
+
+
+
+ 2005/03/29 Markus Gaug
+
+   * mcalib/MCalibColorSet.cc:
+     - added runs 34814, 34815, 45493, 45502, 45525, 45537 and 45548
+
+
+
+ 2005/03/29 Thomas Bretz
+
+   * ganymed.cc:
+     - implemented cmdline option for wobble and no-wobble to overwrite
+       dataset
+     - added cmdline option to print dataset
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added some memory leak analysis to eventloop
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added third part to status bar which displays the current
+       memory usage
+     - added some more sizes to menu bar
+     - replaced SetStatusLine1/2 by calling a common SetStatusLine
+     - added a delete to CloseWindow() to be able to close a 
+       static window. REMARK: This gives a hell of warnings in
+       valgrind but it is currently the only option to get this working
+       which is really annoying
+
+   * mhbase/MH.cc:
+     - small simplification
+
+   * mhbase/MHMatrix.cc:
+     - replaced IsValid() by a check for the number of Rows, this
+       was necessary because in root 4.02/00 all matrices seems
+       to be valid
+
+   * mhflux/MHAlpha.cc:
+     - changed the number of default bins in energy
+     - make sure that the Alpha plot for off-data is displayed with
+       a minimum at 0
+     - fixed TPad::Divide for root 4.02/00
+
+   * mhflux/MHEnergyEst.cc:
+     - use the mean abs of the resolution as fit value
+     - some fixed to graphics
+     - fixed the TPad::Divide for root 4.02/00
+     - for the moment removed the pad added to the list of cleanups
+       to get rid of the crashes
+
+   * mhflux/MHFalseSource.cc:
+     - fixed for root 4.02/00 which seaqrches in the current pad
+       for the histogram when calling Project3D
+     - fixed the TPad::Divide for root 4.02/00
+
+   * mhist/MHHadronness.[h,cc]:
+     - use MParameterD instead of MHadronness
+
+   * mimage/ImageLinkDef.h, mimage/Makefile:
+     - added MHVsSize
+
+   * mimage/MHHillas.cc:
+     - implemented 'same' for Center-histogram
+
+   * mhflux/FluxLinkDef.h, mhflux/Makefile:
+     - added MHEnergyEst
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added significancetimes log10(excess) as fit option
+
+   * mjobs/MDataSet.[h,cc]:
+     - added wobble-mode option
+
+   * mjobs/MJCut.cc:
+     - changed default binning for energy
+     - added MHillasSrcAnti optionally to the output
+     - added MHVsSize to the tabs which are shown
+
+   * mjobs/MJOptimize.[h,cc]:
+     - added dummy parameters to FixParameter for compatibility
+       with SetParemeter
+     - replaced MFSupercuts by MFMagicCuts
+     - use Energy in MHAlpha instead of size
+
+   * mbase/MFilter.[h,cc]:
+     - implemented ReadEnv to treat "Inverted"
+
+   * mfbase/MF.[h,cc], mfilter/MFSupercuts.cc:
+     - treat "inverted" with MFilter::ReadEnv
+
+   * manalysis/MCompProbCalc.[h,cc], mranforest/MRanForestCalc.[h,cc]:
+     - replaced MHadronness by MParameterD
+
+   * mdata/MDataFormula.[h,cc]:
+     - removed comments from SetVariables
+     - replaced GetExpFormula by GetTitle
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - MHadronness removed
+
+   * mfilter/MFMagicCuts.[h,cc]:
+     - added
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFMagicCuts
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - removed MJExtractSignal
+
+   * mfbase/MF.cc:
+     - fixed a problem with double-inversion in ReadEnv
+
+   * mpointing/MSrcPosCalc.cc:
+     - removed an output line which showed only an empty container
+
+
+
+ 2005/03/24 Thomas Bretz
+
+   * callisto.cc, ganymed.cc, mars.cc, merpp.cc, readdaq.cc,
+     readraw.cc, showlog.cc, showplot.cc, sinope.cc, star.cc:
+     - replaced all returns of -1 by return 2
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MEnergyEst (container)
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - implemented new fit result options
+
+
+
+ 2005/03/23 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - fix a bug in the time fine adjustment
+
+   * mjobs/hilocalib_*_mc.root
+     - high-gain low-gain intercalibration constants for the MC.
+
+   * mjobs/MJCalibration.cc
+     - use the MC- intercalibration files for MC.
+
+
+
+ 2005/03/23 Thomas Bretz
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - fixed a possible crash in DrawDataCheckPixel() if 
+       pix.GetGraphEvents() returns NULL
+
+
+
+ 2005/03/23 Thomas Bretz
+
+   * Release 0.9
+
+
+
+ 2005/03/23 Thomas Bretz
+
+   * ganymed.cc:
+     - implemented wobble-mode option
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - fixed a problem in wobble mode (number of on- minus number
+       of off-entries where calculated as 0)
+     - added some additional resource options for scaling
+     - added some missing const-qualifiers
+
+   * mhflux/MHAlpha.cc:
+     - some cosmetic change to output
+
+   * mjobs/MDataSet.[h,cc]:
+     - added the possibility to add a source name for wobble mode
+       (preliminary)
+     - added reading from *.edb catalog
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibrateSignal.cc,
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc:
+     - replaced iter.Print("all") by iter.Print()
+
+   * mjobs/MJCut.[h,cc]:
+     - implemented wobble mode
+     - implemented getting source position
+
+   * mjobs/MJStar.cc:
+     - switched off calculation of MConcentration
+     - implemented the new debug option for files (was still missing
+       in MJStar)
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - always writa the anti-source position into the parameter list, too
+     - implemented wobble mode (exchange source and anti-source position)
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJOptimize
+
+   * mfilter/MFSupercuts.[h,cc]:
+     - added
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFSupercuts
+     - removed MFAlpha
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MEnergyEst
+     - removed MEnergyEstParam
+     - removed MEnergyEstParamDanielMkn421
+     - removed MSupercuts
+     - removed MSupercutsCalc
+     - removed MFindSupercuts
+     - removed MMinuitInterface
+     - removed MFiltercutsCalc
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHEnergyTime
+     - removed MHEnergyTheta
+     - removed MHAlphaEnergyTime
+     - removed MHAlphaEnergyTheta
+     - removed MHThetabarTime
+     - removed MHThetabarTheta
+     - removed MHGamma
+     - removed MHSigmaPixel
+     - removed MHSigmabarTheta
+     - removed MHOnSubtraction
+     - removed MHFindSignificance
+     - removed MHCT1Supercuts
+
+   * mhflux/Makefile, mhflux/HistLinkDef.h:
+     - added MHEnergyEst
+
+
+
+ 2005/03/22 Thomas Bretz
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibrateSignal.cc,
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc:
+     - added a possibility to print the files which are 
+       searched/found if the files doesn't match the sequence
+
+   * mjobs/MJPedestal.cc:
+     - undocumented(!) change, changed fgExtractWinLeft
+       from 3.5 to 2.5
+
+   * mimage/MHillas.cc:
+     - fixed a bug which took unused pixels into account
+       introduced errornously with the last change to MSignalCam
+
+
+
+ 2005/03/21 Thomas Bretz
+
+   * mfbase/MFDataChain.cc:
+     - fixed a bug in GetDataMember if fData is not valid
+
+   * mhbase/MH3.cc:
+     - moved drawing histograms back to Draw. This fixes a
+       problem with root 4.02/00. Reading/Writing should be
+       no problem if the names of the profiles are well known.
+     - with this fix 'same' is currently NOT supported
+
+   * mimage/ImageLinkDef.h, mimage/Makefile:
+     - added MNewImagepar2
+     - added MHCewImagePar2
+   
+   * mimage/MNewImagePar2.[h,cc], mimage/MHNewImagePar2.[h,cc]:
+     - added new classes calculating and displaying the length
+     of the border line of a shower
+
+   * mimage/MHImagePar.cc:
+     - fixed a problem with root 4.02/00 when setting the margin
+       in Divide to 0 by setting it to 1e-10
+
+   * mimage/MHNewImagePar.[h,cc]:
+     - fixed to display Areas in deg^2
+
+   * mimage/MHillas.cc, mimage/MHillasExt.cc, mimage/MHillasSrc.cc,
+     mimage/MImagePar.cc, mimage/MNewImagePar.cc
+     - a small fix to Print()
+
+   * mimage/MHillasCalc.[h,cc]:
+     - added MNewImagePar2 to supported image parameters
+
+   * mjobs/MJStar.cc:
+     - replaced MCerPhotEvt by MSignalCam
+
+   * msignal/cosmics_weights46.dat, msignal/calibration_weightsUV46.dat,
+     mjobs/hilocalib_df46.root:
+     - added new intercalibration file for digital filter 4sl higain
+       and 6sl logian
+
+  * mbase/MLogHtml.cc:
+     - fixed a bug in Underline which cause a crash if fOut==NULL
+     - output a message if file cannot be opened
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - for some output there was a replacement of pix.GetPixId()
+       by hist.GetName() <undocumented>
+
+   * mimage/MHillas.[h,cc]:
+     - added new member function GetBorderLine returning the border
+       line correspondig to an ellipse with axis lnegth and width
+     - added new member function GetArea returning the area
+       correspondig to an ellipse with axis lnegth and width
+
+
+
+ 2005/03/19 Markus Gaug
+ 
+   * mjobs/hilocalib_df46.root
+     - added new intercalibration file for digital filter 4sl higain 
+       and 6 slices logain
+
+   * mjobs/MJCalibration.cc
+      - exchanged intercalibration file from hilocalib_df_4.root to  
+        hilocalib_df46.root
+      - do not apply hi-gain lo-gain intercalibration for MC files.
+
+   * mjobs/MJPedestal.cc
+     - exchanged two (Int_t)'s by TMath::Nint().
+     - undocumented(!) change to the calculation of the extraction
+       range (PulsePosCheck)
+
+   * callisto.rc
+     - exchanged default weights file for Digital filter from
+       cosmics_weights4.dat to cosmics_weights46.dat and from 
+       calibration_weights_UV4.dat to calibration_weights_UV46.dat!
+       This change is absolutely necessary, given the new results from 
+       Nuria about the signal resolution in the low gain which gets worse
+       than the intrinsic Poisson jitter above 350 phes. Also the time
+       resolution is too bad. This was not known before we had the  
+       correct low-gain MC pulse.
+
+
+
+ 2005/03/18 Thomas Bretz
+
+   * Makefile:
+     - removed mone from list of compiled programs
+
+   * mars.cc:
+     - replaced the MARS display by the Camera Display directly
+
+   * manalysis/MCameraData.[h,cc], mcalib/MCalibrateData.[h,cc],
+     mbadpixels/MBadPixelsTreat.[h,cc], mcalib/MCalibrateRelTimes.[h,cc],
+     mimage/MCameraSmooth.[h,cc], mimage/MConcentration.[h,cc],
+     mimage/MHillas.[h,cc], mimage/MHillasExt.[h,cc], 
+     mimage/MImgCleanStd.[h,cc], mimage/MNewImagePar.[h,cc],
+     mimage/MImagePar.[h,cc], MNewImagePar.[h,cc],
+     mjobs/MJCalibTest.cc, mhcalib/MHCalibrationTestCam.[h,cc],
+     mpedestal/MPedPhotCalc.[h,cc], mjobs/MJCalibrateSignal.cc:
+     - removed dependancy on MArrivalTime, information now
+       found in MSignalCam
+     - replaced MCerPhotEvt by MSignalCam
+     - it was renamed because it will be completely incompatible
+       anyhow
+
+   * mjobs/MJCalibrateSignal.cc:
+     - use new MSignalCam type to display pulse position of cosmics
+
+   * mcalib/MCalibrateData.cc:
+     - calculate number of saturated pixels
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - removed possibility for zero-supression. Now the index
+       is identical with the position in the array
+     - renamed and moved to msignal/MSignalCam.[h,cc]
+
+   * manalysis/MCerPhotPix.cc:
+     - removed obsolete values
+     - added arrival time
+     - renamed and moved to msignal/MSignalPix.[h,cc]
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - some cosmetic changes and small fixed from the Munich cvs
+       (undocumented)
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed bug in RecursiveRemove which caused crashed with real
+       data
+
+   * mhft/MGeomCamMagicEnhance.cc, mhft/MHexagonalFTCalc.cc:
+     - updated, but untested
+
+   * mhist/MHCamEvent.[h,cc]:
+     - some fixes in Draw to get a correct display in root 4.02/00
+       (at least on 64-bit systems)
+     - removed kSqrtVariance it is included in kProfile now
+
+   * mhist/MHCamera.[h,cc]:
+     - removed sqrtvariance option which is included in profile now
+     - the profile now uses the new array fBinEntries to display
+       a more accurate profile
+
+   * mhist/MHEvent.cc:
+     - set to type 6 for arrival times
+
+   * mimage/MHillasCalc.cc:
+     - updated text for error=1
+
+   * mimage/MImagePar.cc:
+     - copy number of saturated pixels from MSignalCam
+
+   * mjobs/MJStar.cc:
+     - enhanced title of some histogram
+
+   * mjobs/MSequence.cc:
+     - updated path to fit data center (D.Dorner)
+
+   * mmain/MEventDisplay.cc:
+     - display Arrival Time from MSignalCam now
+
+   * msignal/MArrivalTimeCam.cc:
+     - implemented a new case 6 which is identical with the 
+       default case AND arrival time from MSignalCam
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h,
+     manalysis/:
+     - removed MCerPhotEvt
+     - removed MCerPHotPix
+     - removed MCerPhotAnal
+     - removed MCerPhotAnal2
+     - removed MCerPhotCalc
+
+   * mimage/Makefile, manalysis/ImageLinkDef.h:
+     - removed MHillasSrcCalc
+
+   * manalysis/MSupercutsCalc.cc:
+     - removed an obsolete include
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHSigmaTheta
+
+   * mmain/Makefile, mmain/HistLinkDef.h:
+     - removed MDataCheck
+     - removed Mars
+     - removed MAnalysis
+     - removed MMonteCarlo
+     - removed MGDisplayAdc
+     - removed MOnlineDisplay
+     - removed MOnlineDump
+
+   * msignal/Makefile, msignal/HistLinkDef.h, msignal/:
+     - added MSignalCam
+     - added MSignalPix
+     - added MSignalCalc
+
+   * msql/Makefile, msql/SqlLinkDef.h:
+     - removed MSqlInsertRun
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - removed MFSelBasic
+     - removed MFSelStandard
+     - removed MFSelFinal
+
+
+
+ 2005/03/17 Thomas Bretz
+
+   * callisto.cc:
+     - added new option moon
+     - use light condition from MSequence to determin light condition
+       automatically
+
+   * mjobs/MJPedestal.h:
+     - allow setting SetUseHists also to kFALSE
+
+   * mjobs/MSequence.[h,cc]:
+     - added fLightCondition
+
+   * mcalib/MCalibrateData.cc:
+     - undocumented change from Markus Gaug
+
+   * mfilter/MFCT1SelBasic.[h,cc], mfilter/MFCT1SelStandard.[h,cc],
+     mfilter/MFCT1SelFinal.[h,cc]:
+     - moved to manalysisct1
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - removed MFCT1SelBasic
+     - removed MFCT1SelStandard
+     - removed MFCT1SelFinal
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MPad
+     - removed MMakePadHistograms
+     - removed MSigmabar
+     - removed MSigmabarParam
+     - removed MSigmabarCalc
+
+   * mimage/Makefile, mimage/ImageLinkDef.h:
+     - removed MImgCleanTGB
+
+   * mmontecarlo/Makefile, mmontecarlo/MonteCarloLinkDef.h
+     - removed MMcEnergyEst
+     - removed MMcTimeGenerate
+
+   * msignal/Makefile, msignal/SignalLinkDef.h:
+     - removed MArrivalTime
+     - removed MArrivalTimeCalc
+     - removed MArrivalTimeCalc2
+
+   * mjobs/MJCalibration.cc:
+     - followed some undocumented changes from the other cvs
+
+
+
+ 2005/03/16 Thomas Bretz
+
+   * callisto.cc:
+     - set changed extractor in MJCalibrateSignal from MJPedestal
+     - don't process 'range finding' for MonteCarlo data
+
+   * callisto.rc:
+     - removed obsolete Modified* option
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - removed obsolete flag for ModifiedExtractWin
+     - allow also NULL for SetExtractor
+     - rearanged the too MWriteRootFile instantiations otherwise
+       callisto crashes in MWriteRootFile::ChangeFile
+     - removed some obsolete comments about an old MC workaround
+
+   * mdata/MDataChain.cc:
+     - fixe to allow sign after e (eg. 1e-3, 1e+5 instead of 1e3, 1e5)
+
+   * mcalib/MCalibColorSet.cc, mcalib/MCalibrationChargeCalc.cc,
+     mhcalib/MHCalibrationCam.cc:
+     - undocummented change
+
+
+
+ 2005/03/16 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - fixed a bug in the reading of the resource file (reading of the 
+       MExtractTimeAndCharge resources was skipped).
+
+   * mcalib/MCalibrateData.cc
+     - for the case that the high-gain saturates, but the low-gain signal
+       could not be extracted successfully, take the high-gain signal,
+       multiplied by 1.5 (before, 0 was taken erroneously).
+
+   * msignal/MExtractTimeAndCharge.cc
+     - catch one potential case for memory leaks in the low-gain 
+       calculation. Extract low-gain only if the remaining extraction 
+       window is not smaller than the number of slices needed by the 
+       signal extractor. 
+     - set the default fgLoGainStartShift to -3.5
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - adjust fLoGainStartShift by one slice, after findings from MC.
+
+
+
+ 2005/03/15 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.h
+     - take fRandomIter out of the streamer. 
+     - take fRiseTimeLoGain and fFallTimeLoGain into the streamer.
+     - raise version number to 4
+
+   * mjobs/MJCalibration.cc
+     - set default to kFALSE for PIN Diode or Blind Pixel calibration 
+       (was kTRUE by error).
+
+
+
+ 2005/03/15 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - added the fExtractor data member
+     - added a destructor deleting it
+     - only read extractor from file if not set by user
+     - user fExtractor as extractor1
+     - do not delete extractor1 if set by user
+     - added member function to set extractor
+
+   * mjobs/MJPedestal.cc:
+     - removed MFEventSelector workaround again
+     - do not write pedy file anymore
+
+   * callisto.cc:
+     - MJCalibrateSignal now takes the signal extractor directly
+       instead of taking the long way round a new file
+
+   * mpedestal/MExtractPedestal.cc:
+     - ReInit extractor correctly. Now the workaround should be
+       really obsolete
+
+   * mbase/MGMenu.[h,cc]:
+     - make fix fix also compile root 3.10.02
+
+
+
+ 2005/03/14 Thomas Bretz
+
+   * mbase/MGMenu.h:
+     - added a fix for root 4.02.00
+
+
+
+ 2005/03/14 Markus Gaug
+
+   * mcalib/MCalibrateData.cc
+     - catch the case that now high-gain low-gian intercalibration const.
+       is available.
+
+   * mjobs/MJPedestal.cc
+     - modify option for pedy*.root: from UPDATE to RECREATE
+
+
+
+ 2005/03/11 Markus Gaug
+
+   * callisto.rc
+     - changed default weights for DF to cosmics_weights4.dat. (This has 
+       turned out to be the most stable set of weights). 
+
+   * mjobs/MJCalibration.cc
+     - some cosmetic changes in the output
+     - in case of WriteHists(), do not overwrite existing signal*.root 
+       file, but append histograms (bugfix!)
+
+
+
+ 2005/03/10 Toni Coarasa (With Nadia's and Alessandro's inside)
+
+   * mjobs/MJCut.cc
+     - inclusion of (TString) to avoid compiler error under 2.95.3
+
+   * sinope.cc
+     - inclusion of <errno.h> to avoid compiler error under 2.95.3
+
+
+
+ 2005/03/10 Markus Gaug
+
+   * msignal/MExtractTimeAndCharge.cc
+     - set fgLoGainStartShift to -4.0
+     - put a check to avoid a dynamic low-gain range < 0 (should not 
+       occur with current extractors, but one never knows...)
+
+   * msignal/MExtractor.[h,cc]
+     - introduced Clear()-function, used in SetRange()
+
+   * mjobs/MJCalibrateSignal.cc
+     - changed order of initialization of the 2 MWriteRootFiles whereupon
+       the crash goes away. Have to revise the /dev/null work-around 
+       in MWriteRootFile!
+
+
+
+ 2005/03/09 Markus Gaug
+  
+   * msignal/MExtractTimeAndCharge.cc
+     - catch a (very unprobable) case in which the low-gain range could 
+       be negative
+
+   * mjobs/MJCalibrateSignal.cc
+     - modify writing of MCalibrationPulseTimeCam to disk in order to 
+       avoid program crash in the destructor of MJCalibrateSignal
+
+   * mhcalib/MHGausEvents.h
+     - take fGraphEvents, fGraphPowerSpectrum, fHPowerProbability and 
+       fPowerSpectrum out of the streamer.
+     - intialize fFlags to 0
+
+
+
+ 2005/03/09 Thomas Hengstebeck
+
+   * mranforest/MRFEnergyEst.cc
+     - changed call of min, max functions to TMath::Min() and 
+       TMath::Max() to avoid compilation problems with some gcc
+       versions
+     - changed check of energy rule (last col of MHMatrix) so, that 
+       any rule containing "fEnergy" is accepted.
+
+
+
+ 2005/03/08 Markus Gaug
+
+   * mhcalib/MHPedestalCam.[h,cc]
+     - introduce new parameter "fFitStart" to decide from outside where
+       to start fitting the pedestals.
+
+
+
+ 2005/03/07 Markus Gaug
+
+   * mjobs/hilocalib_df6.root
+   * mjobs/hilocalib_sp2.root
+     - two files with the high-gain vs. logain intercalibration results.
+       for Digital filter and September data and Spline and December 
+       data.
+
+   * callisto.rc
+     - allow setting the variables ExtractWinLeft and ExtractWinRight.
+
+   * mhcalib/MHCalibrationHiLoCam.h
+   * mhcalib/MHCalibrationCam.h
+   * mhcalib/MHGausEvents.h
+     - put the Draw-functions into the *MENU*
+
+   * mjobs/MJCalibration.[h,cc]
+     - introduced reading of hi-vs.logain calibration file
+
+   * mjobs/MJPedestal.[h,cc]
+     - modified range setting according Thomas S. suggestions
+
+   * msignal/MArrivalTime.[h,cc]
+     - took out some commented code which will not be used any more
+     - improve Print() function
+
+
+
+ 2005/03/05 Markus Gaug
+  
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]
+     - removed the obsolete parts of "kMaximum" and "kHalfMaximum" in the
+       code which were still persistent
+     - set default extraction type to integral (instead of amplitude)
+     - set version number to 3
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - added new function GetAvergedConvFADC2PhePerArea for the datacheck
+
+   * mjobs/MJPedestal.[h,cc]
+     - added function WriteExtractor which writes the extractor with the
+       new ranges to disk if fPulsePosCheck has been selected.
+
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - added functionality to read the updated extractor from 
+       MJPedestalY2 (with the new extraction ranges).
+
+
+
+ 2005/03/04 Abelardo Moralejo
+
+   * mmc/MFadcDefine.h
+     - Changed constant SUBBINS from 5 to 500. This defines the 
+       resolution of the analog signal simulation in the camera MC. 
+       The time step is the duration of one FADC slice divided by 
+       SUBBINS. The change was necessary to implement correctly the PMT 
+       time jitter.
+
+
+
+ 2005/03/03 Markus Gaug
+
+   * mjobs/pedestalref.rc
+   * mjobs/calibrationref.rc
+   * mjobs/calibrationref_Nov04.rc
+     - added documentation
+
+   * mjobs/signalref.rc
+     - added
+
+   * mjobs/MJPedestal.cc
+     - re-added MFEventSelector which had been removed by TB on the
+       15.2.2005.
+     - added pulse position selector, as decided at the Berlin soft-
+       ware meeting.
+
+   * callisto.cc
+     - added SetPulsePosCheck() in MJPedestalY2
+   
+   * mjobs/MJCalibrateSignal.cc
+     - updated pulse pos. calculator, can be switched off now.
+
+   * mjobs/MJCalib.[h,cc]
+     - added flag fPulsePosCheck
+
+
+
+ 2005/03/02 Markus Gaug
+
+   * mjobs/MJCalib.[h,cc]
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - put the storage types in the base class
+
+   * mbadpixels/MBadPixelsCam.cc
+     - add some output in case that AsciiRead does not work
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - speed integration up a little bit.
+
+   * callisto.rc
+     - adapt the low-gain stretch for the different pulse form for 
+       calibration and cosmics pulses (only applied if spline is used).
+
+
+
+ 2005/02/25 Markus Gaug
+
+   * mhcalib/MHCalibrationHiLoCam.[h,cc]
+     - fixed bug in inter-calibration hi-logain for arrival times.
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]
+     - fixed the situation where the maximum bin is already found in the
+       low-gain samples.
+
+   * mjobs/MJCalibration.cc
+     - write the MPedestalCams also to disk (needed for data-check).
+
+
+
+ 2005/02/25 Abelardo Moralejo
+
+   * msignal/MC_calibration_weights_UV.dat
+     - Added. Weights file for using the digital filter on MC 
+       calibration files. For the moment the weights are the same as in
+       the file calibration_weights_UV.dat, only that high and low gain
+       have both the same weights because for the moment the MC pulse
+       shape is the same in both gain branches.
+
+
+
+ 2005/02/24 Markus Gaug
+
+   * mjobs/MJCalibrateSignal.cc
+     - include display of pulse times (calculated in the post-process)
+     - include the possibility for the pixel check (like in MJCalibration)
+
+   * mhcalib/MHCalibrationHiLoCam.cc
+     - set default range up to 30.
+
+   * mhcalib/MHCalibrationChargeBlindPix.h
+     - take the TVectors out of the streamer, to be exectuable with 
+       root.04.02
+
+
+
+ 2005/02/24 Thomas Hengstebeck
+
+   * macros/RFEnergyEst.C
+     - new macro to show the usage of RFEnergyEst class.
+
+
+
+ 2005/02/24 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/resize.C
+     - moved MSrcPosCam output container from RunHeaders to Events tree.
+
+
+
+ 2005/02/18 Marcos Lopez 
+
+   * mflux/
+     - new directory to store the flux related classes.
+  
+   * mflux/MHadAlphaCut.{h,cc}
+     - container to store the optimal hadronness and alpha cut for each bin in
+       estimated energy and theta.
+
+   * mflux/MFHadAlpha.{h,cc}
+     - filter to apply the hadronness and alpha cuts stored in
+       MHadAlphaCut. It can be selected to apply only alpha, only hadronness 
+       cut or both.  
+
+
+
+ 2005/02/18 Markus Gaug 
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]
+     - new class to histogram the arrival time of cosmics above a certain
+       threshold.
+   
+   * mcalib/MCalibrationPulseTimeCam.[h,cc]
+     - new class container with results of MHCalibrationPulseTimeCam
+
+   * mjobs/MJCalibrateSignal.cc
+     - include MCalibrationPulseTimeCam to display
+
+
+
+ 2005/02/18 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - switch off TH1::AddDirectory during DrawClonePad
+
+   * mjobs/MSequence.[h,cc]:
+     - added some code (still commented) for later use, 
+       allowing to setup a different filename for each runfile
+     - added SetNight member function
+     - added Add*Runs member function
+     - with this changes MSequence can replace MRunIter now
+     - allow requesting of standard path from outside 
+       (GetStandardPath)
+
+   * Makefile:
+     - added sinope
+
+   * sinope.cc:
+     - added (small tool to check contents of run for datacenter)
+
+   * callisto.cc:
+     - added background information about Callisto
+
+   * ganymed.cc:
+     - added background information about Ganymed
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed special MC code. The MC files now have a lo-gain
+       switch and we can extract the pedestal rms from lo-gain
+     - don't print statistics if nothing was executed
+     - fixed display. The displayed pedestal RMS was the one
+       caluclated with a extractor but not at random position
+       (This only effects the display, the algorithm was ok)
+
+
+
+ 2005/02/17 Markus Gaug
+
+   * mjobs/MJCalibTest.cc
+     - removed bug treating the MC calibration files uncorrectly
+     - added Pixel-Check treatment
+
+   * mjobs/MJCalibration.cc
+     - added Pixel-Check treatment
+
+   * callisto.rc
+     - added pixel-check option
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - calculate high-gain signal even if saturation occurs
+
+
+
+ 2005/02/17 Thomas Bretz
+
+   * mjobs/MJStar.cc:
+     - fixed some missing containers in case of MC files
+
+   * callisto.cc:
+     - removed obsolete second check for kModeC
+
+   * mars.rc:
+     - added a lot of option to be able to use a 
+       different signal extractor looking into uncalibrated
+       data
+
+   * manalysis/MCameraData.[h,cc]:
+     - added Print() member function
+
+   * manalysis/MCerPhotAnal2.[h,cc]:
+     - switched off writing into MCerPhotEvt
+
+   * mdata/MDataChain.[h,cc]:
+     - added code to handle priorities of operators correctly
+
+   * mhist/MHEvent.cc:
+     - fixed display for MPedestalRMS
+
+   * mjobs/MJCalib.cc:
+     - fixed treatment of PixelCheck resource
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added some comments about Monte Carlo
+     - added MMcFadcHeader to output
+
+   * mjobs/MJPedestal.cc: 
+     - do not allow 'UseData' for Monte Carlos. Reason is given as 
+       comment in the code
+
+   * mmain/MEventDisplay.[h,cc]:
+     - changed such, that mars.cc allows to set the used extractor
+     - removed the obsolete cam.root, ped.root option
+
+   * mmain/MCameraDisplay.cc:
+     - adapted to change in MEventDisplay
+
+
+
+
+ 2005/02/16 Javier Rico
+
+   * mhistmc/MHMcUnfoldCoeff.[cc,h], mhistmc/Makefile, 
+     mhistmc/HistMcLinkDef.h
+     - Added container class holding the histograms of the coefficients
+       for the (iterative) unfolding.
+
+   * mmontecarlo/MMcUnfoldCoeffCalc.[cc,h], mmontecarlo/Makefile, 
+     mmontecarlo/MonteCarloLinkDef.h
+     - Added task class to compute the coefficients for the (iterative) 
+       unfolding.	
+
+   * macros/unfoldCoeff.C
+     - added macro that computes the effective areas and coefficients
+       from a MC input file (with OriginalMC tree and MEnergyEst
+       branch containing the energy estimator). This may be used 
+       as layout for spectrum computation program.
+
+
+
+ 2005/02/16 Markus Gaug
+
+   * mdata/MDataChain.cc
+     - replaced ROOT version check for the compiler from 4.02.00 to 
+       4.01.00
+
+   * mranforest/MRFEnergyEst.cc
+     - include "TVector.h", otherwise this class does not compile
+       in newer root versions
+
+   * msignal/MExtractTimeAndCharge.cc
+     - initialize fLoGainStartShift correctly if read from conf. file 
+       and modified fOffsetLoGain exists.
+
+   * msignal/*weights*.dat
+     - new weights with the uniform pedestal RMS. (Please use these!)
+
+   * msignal/pulpo_weights*.dat
+     - new weights with the pulpo-pulse form and without NSB!!
+
+
+
+ 2005/02/16 Thomas Hengstebeck
+
+   * mranforest/MRFEnergyEst.[h,cc]
+     - added RF class for energy estimation
+
+   * mranforest/MRFEnergyEst.cc
+     - changed calculation of estimated energy, now interpolated values
+       are returned                                                                        	
+
+
+
+ 2005/02/16 Abelardo Moralejo
+
+   * macros/starmc2.C:
+     - Changed the way in which the "OriginalMC" tree is copied from
+       the input to the output file. Now we ise the new procedure
+       MWriteRootFile::AddCopySource
+
+   * mhistmc/MHMcCollectionArea.cc
+     - Changed default fName to "MHMcCollectionArea"
+
+   * mtemp/mpadova/macros/resize.C
+     - Changed weights
+
+
+
+ 2005/02/16 Thomas Bretz
+
+   * mbase/MEvtLoop.cc:
+     - fixed a typo
+
+   * mbase/MParList.cc, mfileio/MReadMarsFile.cc,
+     mfileio/MReadTree.cc, mfileio/MWriteRootFile.cc,
+     mjobs/MJStar.cc:
+     - optimized size of some output
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - fixed CopySource option for single-file case
+
+   * mhist/MHCamEvent.cc:
+     - replaced the warn in SetupFill by an inf
+
+   * mhcalib/MHCalibrationCam.cc, mhcalib/MHCalibrationHiLoCam.cc,
+     mhcalib/MHCalibrationChargePINDiode.cc:
+     - removed obsolete output after a failed FindCreateObj (the
+       function itself does the output in case of failure)
+
+   * mhcalib/MHCalibrationCam.cc:
+     - replaced 'err' by 'warn' for under-/overflow in lo-gain pixel,
+       it doesn't result in an fatal error (abort)
+
+   * mranforest/MRanForestCalc.cc:
+     - added a missing debug level to some output
+
+   * mranforest/MRFEnergyEst.[h,cc]: 
+     - cleaned up includes
+
+   * callisto.cc, ganymed.cc, star.cc:
+     - implemented enhanced handling of resource debugging
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MEnv
+
+   * mbase/MEnv.[h,cc]:
+     - added
+
+   * mjobs/MJob.[h,cc]:
+     - added new function to allow distribution of extranl MEnv
+     - replaced Bool_t by Int_t for fEnvDebug
+
+   * mjobs/MJPedestal.cc:
+     - adapted to changes of EnvDebug
+
+
+
+ 2005/02/15 Abelardo Moralejo
+
+   * macros/mccalibrate.C
+     - fixed small bug
+
+   * mmontecarlo/MMcCollectionAreaCalc.[h,cc] 
+   * mhistmc/MHMcCollectionArea.[h,cc]
+     - Changed the way of calculating final effective area for data 
+       analysis. The new approach requires the use of MC files produced
+       with the current CVS version of camera. We now make use of the
+       true total number of produced MC events, and allow for the 
+       setting of a "tentative" differential gamma spectrum to be used 
+       in the calculation of effective areas. 
+       Removed unused constructor argument "input" in 
+       MMcCollectionAreaCalc.
+
+   * macros/collarea.C
+     - Adapted to the new way of calculating effective areas.
+
+
+
+ 2005/02/15 Thomas Bretz
+
+   * callisto.rc:
+     - replaced mutal exclusive options (Integral, Amplitude) by
+       a one-line resource
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - replaced mutal exclusive options (Integral, Amplitude) by
+       a one-line resource "ExtractionType" (old code still works)
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added new variables to store information about islands
+       and removed pixels - PRELIMINARY
+     - increased class version number
+
+   * mfilter/MFSoftwareTrigger.cc:
+     - optimized output in PostProcess
+
+   * mimage/MHImagePar.[h,cc]:
+     - added new histograms for new variables in MCerPhotEvt
+
+   * mimage/MImagePar.[h,cc]:
+     - added new data members for the new image parameters
+     - increased class version
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - adapted image cleaning to calculate the new image
+       parameters
+     - added a flag to keep single core pixels
+
+   * manalysis/MMatrixLoop.[h,cc], mfileio/MReadReports.[h,cc],
+     mfileio/MReadRflFile.[h,cc], mfileio/MReadTree.[h,cc],
+     mraw/MRawFileRead.[h,cc], mraw/MRawSocketRead.h:
+     - renamed GetFileName to GetFullFileName
+
+   * mbase/MInputStreamID.h:
+     - added new member function HasStreamId
+
+   * mbase/MParContainer.[h,cc]:
+     - added a static list to keep track of all created
+       TMathodCall objects
+
+   * mbase/MTask.cc:
+     - enhanced PrintStatistics
+
+   * mfileio/MRead.[h,cc]:
+     - new abstract function GetFullFileName
+     - added implementatio of GetFileName based on GetFullFileName
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - moved open of a new file to new common member function
+       OpenFile
+     - allow to use an already existing file also when using rules
+     - added a new option which can be used to copy an existing
+       tree (without any change) from the old file into the new file.
+       (in principal you can also do this for some of its branches only)
+       This is done by AddCopySource
+
+   * mjobs/MJCalibrateSignal.cc:
+     - in case of MonteCarlo files write an independant tree
+       'MonteCarlo' for 'MMcEvtBasic'
+
+   * mjobs/MJStar.cc:
+     - copy tree 'MonteCarlo' from old into new files
+
+   * mjobs/MJPedestal.cc:
+     - removed wrong use of MFEventSelector
+
+   * mpedestal/MExtractPedestal.cc:
+     - made sure that fExtractor is correctly pre- and 
+       postprocessed.
+
+   * mbase/MTask.cc:
+     - don't preprocess a task if it has been preprocessed already
+
+   * mraw/MRawFileWrite.cc:
+     - if display is set write output to status line
+
+   * mfileio/MReadTree.cc, mfileio/MReadMarsFile.cc:
+     - moved code to display filename in status display from
+       MReadMarsFile::Notify to MReadTree::Notify
+
+
+
+ 2005/02/15 Markus Gaug
+
+   * mjobs/MJCalib.h
+     - added GetDataFlag(), otherwise code does not compile!
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - moved default saturation limit for number of high-gain events from 
+       0.02 to 0.05. 
+
+   * msignal/MExtractTimeAndCharge.cc
+     - lowered default low-gain switch from 150 to 120. (for calibration 
+       events which saturate more than 5% of the events).
+
+   * mjobs/MJCalib.[h,cc]
+     - include possibility to display pixels distributions for test
+       reasons
+
+
+
+ 2005/02/14 Thomas Bretz
+
+   * callisto.cc, ganymed.cc, star.cc:  
+     - added some more information to '--help' output
+     - replaced MSequences by MDataSet
+     - implemented new debugging options (maybe not perfect yet)
+       --print-files and --print-found
+
+   * mjobs/MJCut.[h,cc]: 
+     - replaced MSequences by MDataSet
+     - write MEnergyEst
+     - recalculate MHillasSrc
+     - made sure both MWriteRootFile have different names
+     - don't use "same" option if no off-data
+
+   * mjobs/MSequences.[h,cc]: 
+     - removed
+
+   * mjobs/MDataSet.[h,cc]: 
+     - added
+
+   * manalysis/MEventRateCalc.[h,cc]:
+     - added a fix which make sure, that the rate is not influenced
+       too much by the start of data taking
+     - fixed setting of mean time corresponding to rate-interval
+
+   * mraw/MRawFileRead.[h,cc]:
+     - calculate total number of events from all files in PreProcess
+
+   * mcalib/MCalibConstCam.cc:
+     - added case 2 to GetPixelContent
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed redirection of stream with interleaved calibration infos
+     - changed 'Arrival Time' to 'Calibrated Arrival Time'
+     - display interpolated signal in equivalent photoelectrons to
+       to get rid of scaling effects which makes it difficult to see 
+       details of the structure of the inner pixels in the histogram.
+       With this you can immediatly see whether the relative number
+       of phe in the outer pixels is equiv. to the inner pixels.
+     - the same for the calibration factor - with the same argument
+     - adapted to change in MWriteRootFile
+     - use MReadMarsFile for Monte Carlo flag set
+
+   * mhist/MHCamera.cc:
+     - changed drawing such, that NaN is not displayed anymore
+
+   * Makefile:   
+     - added new program ganymed
+
+   * mfileio/MWriteRootFile.[h,cc]:  
+     - added possibility to use UPDATE mode with rules (dangerous!)
+       as discussed with Abelardo, Daniel M. and Thomas S.
+
+   * mjobs/MJStar.cc:
+     - adapted to change in MWriteRootFile
+     - added software trigger (still untuned) as suggested by
+       Thomas S.
+     - added calculation of source position before calculation
+       of image parameters
+     - added MPointingPos to Events-Tree
+     - removed MPointingPos from Drive-Tree
+     - renamed sub-tasklists to something more intuitive
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJCut.cc
+
+   * mraw/MRawFileRead.cc:
+     - return kERROR if ReInit fails
+
+   * mfilter/MFSoftwareTrigger.[h,cc]:  
+     - updated to allow using time coincidence
+     - changed default values
+     - added a pattern independant trigger algorithm
+
+   * mbase/MDirIter.cc:
+     - implemented option 'dbg' in Print()
+
+   * mjobs/MJCalib.h:
+     - added a getter for data-flag (should be renamed
+       to 'datatype' soon)
+
+
+
+ 2005/02/12 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/wobblemap.C
+     - Added. Macro to do some studies on wobble mode data.
+
+   * macros/mccalibrate.C
+     - Added option to divide the output in a train and a test sample.
+       Included in output new container MMcEvtBasic (if found in input 
+       files) for later use in effective areas calculations.
+
+   * macros/starmc2.C
+     - Added writing out of new container MMcEvtBasic. Removed 
+       possibility of splitting output in train and test samples, since
+       this has now to be done in mccalibrate.C to make possible that 
+       the tree OriginalMC containing MMcEvtBasic has all the original
+       MC events (and only those) from which the events present in the
+       Events tree derive.
+
+   * macros/starmc.C
+     - Changed a couple of wrong "." by "->" in function calls. Changed
+       default tail cuts.
+
+
+
+ 2005/02/12 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - change default rise time to 0.5 and default fall time to 1.5
+
+   * callisto.rc
+     - made intitializations of extractors more explicit
+
+   * mpedestal/MExtractPedestal.cc
+     - make check for even number of slices in the case of "fundamental"
+       pedestal calc.
+ 
+   * mcalib/MCalibrationChargeCalc.cc
+     - take out some commented code
+
+   * mjobs/MJCalib.h
+     - removed GetDataFlag()
+
+
+
+ 2005/02/12 Abelardo Moralejo
+
+   * mmc/MMcTrig.hxx 
+     - Added getter GetNumFirstLevel. This is necessary if that data
+       member is to be used for instance in MF filters. There was 
+       already a getter, but it is called GetFirstLevel and hence not
+       recognized.
+
+
+
+ 2005/02/11 Abelardo Moralejo
+
+   * mmc/MMcEvtBasic.[h,cc]:
+     - New class. Contains 5 very basic MC parameters which we intend
+       to save for all generated Corsika events. This is needed for
+       proper effective area calculations.
+
+   * mmc/Makefile, McLinkDef.h
+     - Added new class above.
+
+
+
+ 2005/02/11 Thomas Bretz
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - added the possibility to write to an already existing file.
+      This doesn't affect the old behaviour, but using this new feature
+      might still have problems.
+
+   * mfileio/MReadReports.cc: 
+     - fixed column-level in PrintStatistics
+
+   * mjobs/MJCalibrateSignal.cc:
+     - keep MMcRunHeader in the output
+
+
+
+ 2005/02/10 Abelardo Moralejo 
+
+   * macros/mccalibrate.C 
+     - Added possibility to calibrate in photons or photoelectrons
+
+   * macros/starmc2.C
+     - Added comment about value of cleaning levels
+
+
+
+ 2005/02/10 Markus Gaug 
+ 
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrate.[h,cc] 
+     - removed mcalib/MCalibrate.* because it has been replaced by 
+       MCalibrateData
+
+   * mmain/MEventDisplay.cc
+     - replaced MCalibrate by MCalibrateData
+
+   * mhcalib/MHCalibrationCam.cc
+     - replaced warning about empty histogram from red (err) by 
+       yellow (warn).
+
+   * mcalib/MCalibColorSet.cc
+     - return kTRUE in case of MC-file
+
+   * msignal/MExtractTimaAndChargeSpline.[h,cc]
+     - make sure that all variables are set correctly independent on 
+       the order of their initialization by the user
+
+
+
+ 2005/02/10 Thomas Bretz
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added new member functions (GetNeighbors) to get all pixels
+       around a given pixel with a given radius
+
+   * mars.rc:
+     - use same values for image cleaning as default in star
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - added the possibility to set the Source position from
+       a resource file
+
+   * mjobs/MJStar.cc:
+     - write MMcRunHeader to RunHeaders
+
+   * mfileio/MWriteRootFile.cc:
+     - removed an obsolete line
+     - removed a debug line which should not be there
+
+   * mimage/MHillas.h:
+     - added new Getter GetDist0 returning the distance to the 
+       camera center
+
+   * mhflux/MHFalseSource.cc:
+     - the scaling in Paint() was nonsense in case we are looking
+       at on/off-data. Fixed.
+
+
+
+ 2005/02/10 Abelardo Moralejo 
+
+   * manalysis/MMcCalibrationUpdate.h
+     - Added comment on new member fSignalType. Sorry for compilation
+       problems... I forgot to commit the header yesterday, but M. Gaug 
+       did it.
+
+   * macros/starmc.C
+     - Cleaned up a little bit, made the option to choose between 
+       calibration in photons or phe- easier to set.
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Added getter and setter for fSignalType. Set fSignalType=kPhot as
+       default for consistency with MCalibrateData.
+
+
+
+ 2005/02/09 Abelardo Moralejo 
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - Updated to make the MC calibration in phe- work
+
+   * macros/starmc.C
+     - same as above. Now default is calibration in phe-
+
+   * mraw/MRawEvtHeader.h
+     - Added setter for the trigger pattern, absolutely needed for 
+       creating proper MC root files.
+
+
+
+ 2005/02/09 Markus Gaug 
+
+   * manalysis/MMcCalibrationUpdate.h
+     - added missing declaration of fSignalType
+
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/badpixels_0_559.rc
+   * callisto.rc
+     - allow exclusion of bad pixels from the beginning (default is 
+       Pixel 0 and 559).
+     - removed some obsolete includes
+     - took out data member fPedestalHist from MJPedestal.h which removes 
+       the crash, however I don't understand why it caused the crash!!! 
+       There seem to be problems with memory usage either in callisto.cc 
+       or in this class!!
+       (valgrind shows several memory leaks in the TG... classes).
+  
+   * mjobs/MJCalibration.cc
+     - write display and containers also in case of failure of eventloop
+
+   * mhcalib/MHGausEvents.cc
+     - make default display window 600x600
+
+   * mcalib/MCalibrationQECamMagic.cc
+     - updated five pixels
+
+   * mpedestal/MExtractPedestal.[h,cc]
+   * mpedestal/MPedCalcPedRun.cc
+   * mpedestal/MPedCalcFromLoGain.cc
+     - included possibility for intermediate pedestal cam (not yet used)
+
+   * msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc
+     - initialize the bad events counters to 0 also in constructor 
+     - release the limit for bad events a bit
+
+   * mcalib/MCalibrationTestCam.h
+     - take out include of TArrayI (already in base class)
+
+   * mcalib/MCalibrateData.h
+     - make default argument for SetSignalType kPhe.
+
+   * mjobs/MJCalibrateSignalFromOuside.[h,cc]
+     - removed
+
+
+
+ 2005/02/08 Markus Gaug 
+ 
+   * mhcalib/MHCalibrationCam.cc
+   * mcalib/MCalibrationChargeCalc.cc
+     - replaced GetNumExecutions()==0 condition by GetNumExecution() < 1 
+
+
+
+ 2005/02/08 Thomas Bretz
+
+   * mpointing/MPointingPosInterpolate.cc:
+     - use debug option in addition to switch off output from internal
+       eventloop. It is confusing having this output inside another
+       eventloop.
+     - updated missing connections in class description
+
+   * msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc:
+     - made sure that output of PostProcess fits into 80col boundary
+
+   * mimage/MHillas.cc:
+     - removed an obsolete call to TLine::Paint() in Paint.
+
+
+
+ 2005/02/07 Thomas Bretz
+
+   * mbase/MFilter.cc:
+     - use paranthesis around ClassName in GetRule
+
+   * mdata/MDataFormula.h:
+     - fixed a wrong comment in variable description
+
+   * mhist/MHCamEvent.[h,cc], mhist/MHCamera.[h,cc],
+     mjobs/MJCalibrateSignal.cc, 
+     mjobs/MJCalibrateSignalFromOutside.cc:
+     - to make sure there are no missunderstandings we have to
+       replace all occurances of 'Variance' by 'SqrtVariance'
+       (it was not my decision)
+
+   * mastro/MAstro.[h,cc]:
+     - added new function Angle2Coordinate
+
+   * mbase/MTaskEnv.[h,cc]:
+     - fixed a bug which caused the resource task to be ignored
+       if the default task was '<dummy>'
+
+   * mhbase/MH3.cc:
+     - fixed a bug in Paint (use GetListOfPrimitives->FindObject
+       instead of FindObject) which caused the histogram to
+       be put a lot of times into the pad.
+
+   * mjobs/MJCalib.[h,cc]:
+     - derived MJCalib from MJob in order to be able to move
+       common code from derived classes into the base-class
+     - implemented CheckEnvLocal to handle the resource 'DataType'
+     - changed publicity of some variables and functions
+       to allow setting file type from outside
+     - added new function to set data-type for use in callisto.cc
+
+   * mjobs/MJCalibTest.[h,cc], mjobs/MJCalibrateSignal.[h,cc],
+     mjobs/MJCalibration.[h,cc], mjobs/MJPedestal.[h,cc]:
+     - removed double inheritance, replaced by single inheritance
+       from MJCalib
+     - replaced code to handle the resource 'DataType' by the 
+       common code in the base class
+     - put reading of reference file into a new member function
+       to make source code reading resource file simpler and to
+       be able to write a function description about it (simple
+       copy&past)
+
+   * callisto.cc:
+     - added option for file-type
+
+   * mjobs/MJOptimize.[h,cc], mjobs/MSequences.[h,cc],
+     mjobs/MJCut.[h,cc], ganymed.[cc,rc], mhflux/MHEnergyEst.[h,cc]:
+     - added to repository, but not yet to Makefile because
+       there is still some work to be done. But whoever is
+       interested in the new classes/program may already use it.
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added option to choose the minimization value
+
+   * mhflux/MHAlpha.cc:
+     - replaced significance by minimization value
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - use E-Option when fitting to improve error calculation
+       by using Minos technique
+
+
+
+ 2005/02/04 Markus Gaug
+
+   * mjobs/MJCalibration.cc
+     - found a "the `impossible' happened" when running callisto with 
+       a pure signal extractor --> MExtractTimeFastSpline has some 
+       problems with the management of the internal arrays. Replaced it 
+       by MExtractTimeHighestIntegral as default which is as good. 
+
+   * callisto.rc
+     - use MExtractTimeAndChargeDigitalFilterPeakSearch as default 
+       instead of MExtractTimeAndChargeDigitalFilter. This extractor is 
+       now tested and checks for the positions of the pulse within the
+       DAQ-window.
+
+
+
+ 2005/02/04 Thomas Bretz
+
+   * Makefile.rules:
+     - fixed creation of main MDep.d
+
+   * callisto.cc, merpp.cc, showlog.cc, showplot.cc, star.cc:
+     - added commandline option --version
+
+   * mbase/MFilter.cc:
+     - changed default for 'GetRule'
+
+   * mbase/MParContainer.cc:
+     - simplified GetNewObject
+
+   * mfbase/MF.cc:
+     - if no conditional sign is found try to create
+       MFilter-object
+
+   * mraw/MRawEvtData.cc:
+     - fixed the initialization of fABFlags in case maxid==0 which
+       is the default. This caused MRawEvtPixelIter::HasABFlag
+       to do unallowed access to memory for old root-files without
+       the AB flag, because it assumed (due to size==1) that the
+       data contains the ab flag
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - removed some obsolete debug comments
+     - simplified HasABFlag
+
+   * manalysis/MCerPhotPix.h:
+     - removed the `!` again. It gave problems with the Mars
+       display. We agreed that this is a minor problem because
+       the structure of MCerPhot* will chnage soon in any case.
+
+
+
+ 2005/02/04 Abelardo Moralejo
+
+   * macros/starmc2.C
+     - added to output missing container MConcentration.
+
+
+
+ 2005/02/03 Thomas Bretz
+
+   * mfbase/MFilterList.[h,cc]:
+     - added new function AddToList(TCollection&)
+
+   * mhbase/MFillH.cc:
+     - print a warning if 'same'-option given without 
+       a corresponding existing tab
+
+   * mhflux/MHAlpha.[h,cc]:
+     - made time bins settable by user
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed ReInit and a warning output when writing to memory
+
+
+
+ 2005/02/03 Markus Gaug
+
+   * mcalib/MCalibColorSet.[h,cc]
+     - implement possibility to set colour explicitely (e.g. for MC).
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - intialize fTimeShiftHiGain and fTimeShiftLoGain by default.
+ 
+   * mjobs/MJPedestal.cc
+     - in case, extractor is used, put the extractor into the tasklist, 
+       otherwise ranges do not get initialized correctly (wrong memory 
+       usage!). Use an event selector, however to not skip the Process.
+       This is as fast as before and now safe for any kind of extractor
+  
+   * mcalib/MCalibrationCam.h
+   * mcalib/MCalibrationTestCam.h
+   * mcalib/MCalibrationTestCam.cc
+     - initialize a missing array in InitAverageAreas
+ 
+   * mraw/MRawEvtHeader.h
+     - introduced Setter() of cal. pattern for Abelardo
+
+
+
+ 2005/02/02 Markus Gaug
+
+   * mcalib/MCalibrationChargeCam.cc
+     - fixed small bug in the display of mean charges when low-gain was
+       used.
+
+   * msignal/MExtractor.cc
+     - print the missing overlap between high-gain and low-gain
+       in the Print() function
+     - remove setting of fHiLoLast in PreProcess, otherwise cloned 
+       extractors do not work any more with windows exceeding the 
+       high-gain range.
+
+   * mhcalib/MHCalibrationTestCam.[h,cc]
+   * mhcalib/MHCalibrationTestTimeCam.[h,cc]
+     - set proper probability limits for the fits
+
+   * mcalib/MCalibrateData.cc
+     - catch the case in which no interlaced cal. events are being sent
+       by the pulser box.
+
+   * mjobs/MJCalib.[h,cc]
+     - put the data type enum in a new base class
+
+   * mjobs/MJCalibTest.[h,cc]
+     - re-name old class MJExtractCalibTest to MJCalibTest and make it 
+       compatible with the sequence-files.
+   
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - removed
+
+   * mjobs/MJCalibrateSignal.cc
+     - put a compiler warning about the default cal. to photo-electrons
+
+   * callisto.cc
+     - add new flag "--use-test" to enable the MJCalibTest facility
+       (default: not used)
+
+
+
+ 2005/02/01 Raquel de los Reyes
+
+   * mjobs/MSequence.h
+     - Added "Get" functions for the TArrays variables.
+
+
+
+ 2005/02/01 Markus Gaug
+  
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJCalibrateSignal.[h,cc]
+   * callisto.rc
+     - put enum for data type. Can now set the data type (mc, raw, root)
+       without running the data check.
+
+   * mhcalib/MHCalibrationCam.cc
+     - return kTRUE in PostProcess if GetNumExecutions is 0
+   
+   * mcalib/MCalibrationChargeCalc.cc
+     - return kTRUE in PostProcess if GetNumExecutions is 0
+
+
+
+ 2005/02/01 Daniel Mazin
+
+   * MPointingPosInterpolate.cc:
+     - fixed bug to match the units of Ra and Decl in MPointingPos
+     - fixed bug in handling of events with times outside of times from 
+       MDrive tree
+
+
+
+ 2005/02/01 Thomas Bretz
+
+   * showplot.cc:
+     - another fix to make the batch mode working (you can use the batch
+       mode to convert a root-file into another format)
+
+
+
+ 2005/01/31 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - fixed handling of batch mode in GetCanvas(const TString &name)
+     - don't skip already existing tabs in Display()
+
+
+
+ 2005/01/31 Raquel de los Reyes
+
+   * mjobs/MSequence.h
+     - Added "Get" functions for some of the sequence.txt file 
+       parameters.
+
+
+
+ 2005/01/31 Markus Gaug 
+ 
+   * mjobs/MJob.[h,cc]
+   * mjobs/MJCalibrateSignal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+     - move file type enum to base class
+
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - allow also for direct setting of an MRunIter (not used in
+       callisto).
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - test also for pulser strength changes additionally to changes in 
+       colour.
+
+
+
+ 2005/01/31 Abelardo Moralejo
+
+   * mpointing/MSrcPosCalc.cc
+     - Create only one instance of MAstroSky2Local for the 
+       transformations, instead of two identical ones, as it was before.
+
+
+
+ 2005/01/30 Markus Gaug 
+ 
+   * mjobs/MJCalibration.cc
+   * mjobs/MJPedestal.cc
+   * mjobs/calibrationref_Nov04.rc
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+     - updated correct display of reference lines
+
+
+
+ 2005/01/29 Markus Gaug 
+    
+   * msignal/MExtractFixedWindowSpline.[h,cc]
+     - fixed a bug occurring with overlapping windows between high-gain
+       and low-gain
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - take out call to fSignals->Clear() which is already done in 
+       MTaskList.
+
+   * msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.[h,cc]
+     - new extractor reducing the bias and solving the problem with the 
+       jumping pulse readout.
+
+
+
+ 2005/01/28 Abelardo Moralejo
+
+   * mpointing/MSrcPosCalc.cc
+     - updated. Make it work as desired: obtain for each event the x,y 
+       position on the camera of a source whose celestial coordinates 
+       (J2000) have been set by the user in the container "MSourcePos" 
+       of type MPointingPos, added to the parameter list. If the 
+       container MSourcePos is not found, the center of the camera (or 
+       other fixed position x,y set in the parameter list by the user - 
+       in MSrcPosCam) is used as source position for all the events in 
+       the loop.
+
+
+
+ 2005/01/28 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed that extract1,2,3 haven't been deleted if loop failed.
+     - print tasklist also if loop failed.
+     - added a undefined task (MTaskEnv "FinalFantasy") as last task to
+       the event processing tasklist
+
+   * callisto.rc:
+     - added comments about "FinalFantasy" into call
+     - added comment for obsolete resources as discussed yesterday
+       evening: TimeUpperLimit
+
+   * mbase/MMath.[h,cc], manalysis/MCerPhotPix.[h,cc], 
+     mpedestal/MPedPhotPix.h:
+     - replaced TruncatePrecision by ReducePrecision (its simply a better
+       name)
+
+   * mbase/MParList.cc:
+     - added a check to make 200%(!) sure that the container added
+       to the list is a MParContainer (everything else could crash
+       almost everything in Mars!)
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.[h,cc],
+     mjobs/MJPedestal.cc:
+     - simplified the code in the WriteResult functions by using
+       the new WriteContainer in MJob
+     - removed the TObjArray from the MParList! It is NOT a MParContainer
+       there are a lot of circumstance how this can crash Mars. I don't
+       know why the compiler allowed for this.
+     - unified WriteResult and WriteHists
+     - split GetOutputFile into two functions for simplification
+
+   * mjobs/MJCalibration.h:
+     - copy the extractorcam name when copying the contents
+
+   * mjobs/MJob.[h,cc]:
+     - new member function WriteContainer to simplify code in derived
+       classes
+
+   * mpointing/MSrcPosCalc.[h,cc]
+     - fixed the header according to Abelardo's changes
+     - added the initialization of the pointers to the constructor
+
+
+
+ 2005/01/28 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - introduce a security check for the time fine adjustment in case, 
+       it is too large.
+
+   * mcalib/MCalibConstCam.[h,cc]
+   * mcalib/MCalibConstPix.h
+     - new classes to allow display of changing cal. constants with the
+       interlaced cal. events
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - removed stopping of PostProcess in case that the evtloop is
+       finished with interlaced cal. events
+
+   * mcalib/MCalibrateData.[h,cc]
+     - fill MCalibConstCam with update results (once per calib. consts
+       update == every 10 sec.)
+     - introduce check for size of calibration constant. In case, it is 
+       completetly out of range, set the MBadPixelsPix::IsUnsuitableRun
+
+   * mjobs/MJCalibrateSignal.cc:
+     - display one MHCamera more with changing conv. factors (only for
+       interlaced cal. events)
+
+   * mpedestal/MPedCalcFromLoGain.cc
+     - set default for MExtractWinFirst from 15 to 17 because of the 
+       late cosmics signals in December
+
+
+ 2005/01/28 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/trainsubsample.C
+     - added # of events to be written in the output (instead of 
+       fraction of total). Moved MSrcPosCam in output from RunHeaders
+       to Events tree.
+
+
+
+ 2005/01/27 Daniel Mazin and Markus Gaug
+
+   * mcalib/MCalibrateData.[h,cc]
+     - derive this class from MCamEvent in order to be able to display
+       evolution of conversion factors in case of interlaced cal. 
+       events
+
+   * mpointing/MInterpolatePointingPos.[h,cc]
+     - new class to interpolate pointing positions, adapted from a class 
+       by Marcos Lopez 
+
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - enabled the calibration of data with interlaced calibration events     
+
+   * msignal/MArrivalTime.[h,cc]
+   * mcalib/MCalibrateRelTime.cc
+     - removed Error of calibrated arrival time, as agreed on the last 
+       software calibration meeting yesterday
+
+   * mjobs/MJCalibrateSignal.cc
+     - add display to show histogramming of conversion factors
+     - modify default calibration to equiv. photo-electrons
+     - allow for setting of MC, Raw or Root-file type in callisto.rc
+
+   * callisto.rc
+     - updated conf. file
+
+
+ 2005/01/27 Thomas Bretz
+
+   * callisto.cc:
+     - don't display starting pedestals when calibrating the signal
+
+   * callisto.rc:
+     - added some comments
+
+   * star.rc:
+     - according to Daniel M. we have agreed to change the default
+       cleaning level to adapt it roughly to the new pedestal
+
+   * manalysis/MCerPhotPix.[h,cc], mpedestal/MPedPhotPix.h:
+     - as agreed in the current calibration meeting we truncate the
+       precision of the stored floating point values to roughly 0.5%
+       to gain storage space in the calibrated data (the gzip
+       algorithm compresses this stuff nicely - we gain roughly 15%)
+
+   * mhflux/MHFalseSource.cc, mjobs/MJCalibration.cc, mjobs/MJStar.cc:
+     - added a comment
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed title of unsuitable plot
+     - removed plot for calibrated fundamental pedestal as agreed in the
+       current calibration meeting (we may change this to an option)
+
+   * mjobs/MJPedestal.[h,cc]:
+     - changed the name of the "PedDiff" plot to be consistent with the
+       other tab-name
+     - changed the options for the display
+     - removed the dependancy of fDisplayType and the SetDataCheck
+       option
+     - added option kDisplayNone
+     - renamed enums from k*Display to kDisplay*
+
+   * mhist/MHCamEvent.cc:
+     - trying to get rid of the Err_%p workaround.
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added some '!' signs in the comment line. This is quick hack
+       to gain I/O speed and storage space. We will soon have new
+       containers for the calibrated data and image cleaning
+       information.
+     - changed version number to 6
+
+   * mhist/MHCamera.cc:
+     - added member function SetAllUsed
+
+
+
+ 2005/01/26 Abelardo Moralejo
+
+   * macros/mccalibrate.C
+     - removed creation and writing out of MSrcPosCam. It is more 
+       flexible to add it in starmc2.C if needed (for wobble mode for
+       instance).
+
+   * mtemp/mpadova/macros/RanForestDISP.C
+     - added possibility to set the number of hadrons read in for the 
+       training. Added some missing containers to output.
+     - Fixed rule concerning the DISP, by adding parentheses. Remember
+       that MHMatrix::AddColumn  does not respect the usual precedence
+       of operations!
+
+   * mtemp/mpadova/macros/resize.C
+     - added to output missing container MRawEvtHeader
+
+   * macros/starmc2.C
+     - added missing container MImagePar. Added possibility to set the
+       source position on the camera (for the wobble mode).
+
+
+
+ 2005/01/25 Abelardo Moralejo
+
+   * macros/starmc2.C
+     - modified to allow double (train / test) output, for g/h 
+       separation studies. Added several missing containers to output.
+
+
+
+ 2005/01/25 Thomas Bretz
+
+   * mcalib/MCalibrationIntensityChargeCam.cc:
+     - fixed a lot of 'default argument'-warnings to make to code
+       compile
+
+   * mbase/MParContainer.[h,cc]:
+     - moved the empty Reset() function into the source file and
+       added a lot of comments
+     - implemented new helper-functions: GetNewObject
+
+   * mbase/MContinue.[h,cc]:
+     - allow to use MFilter-classes as filter in ReadEnv
+
+   * mbase/MTaskEnv.cc:
+     - replaced some code by GetNewObject
+
+   * mhbase/MFillH.cc:
+     - handle DrawOption "same" to be able to draw to the same pad
+
+   * mhbase/MH.[h,cc]:
+     - added same-argument to DrawSame
+
+   * mhbase/MH3.cc:
+     - removed some obsolete comments
+     - remove own drawing options before calling fHist->Draw
+
+   * mimage/MHHillas.cc, mimage/MHImagePar.cc:
+     - first try of implementing 'same' drawing option
+
+
+
+ 2005/01/25 Markus Gaug
+
+   * mcalib/MCalibrationPattern.[h,cc]
+   * mcalib/MCalibrationPatternDecode.[h,cc]
+     - New Decoder task for the calibration pattern from the 
+       digital modules
+ 
+   * mraw/MRawEvtHeader.[h,cc]
+     - remove decoding from this class   
+
+   * mcalib/MCalibrationIntensityHiLoCam.[h,cc]
+     - remove, because one needs anyhow much more than one data file
+       to get a reasonable conversion factor
+
+   * mcalib/MCalibCalcFromPast.[h,cc]
+     - remove MCalibrationIntensityHiLoCam
+
+   * mbadpixels/MBadPixelsPix.h
+   * mbadpixels/MBadPixelsCam.cc
+     - changed one function name to GetUnsuitableCalLevel()
+
+   * mjobs/MJCalibration.cc
+     - replace all Y-titles with units "FADC counts" by "FADC cnts" and 
+       "FADC slices" by "FADC sl.", otherwise they range out of the 
+       canvas.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - ensure to set the color correctly in MCalibrationBlindCam
+
+   * callisto.rc
+     - put space for 
+       MJCalibrateSignal.ExtractSignal.HiGainFirst:     2
+       MJCalibrateSignal.ExtractSignal.HiGainLast:     16
+
+
+ 2005/01/24 Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - Adapted to changes in MCalibrateData from 2005/01/16: moved 
+       qepix.SetAvNormFFactor(1.)  from Process() to ReInit(). Due to 
+       this, for the last week you may have found trouble running 
+       starmc.C and mccalibrate.C.
+
+
+
+ 2005/01/24 Thomas Bretz
+
+   * callisto.cc:
+     - removed non-existing option from output
+
+   * manalysis/MEnergyEstimate.[h,cc]:
+     - added ReadEnv member function
+
+   * mbase/MContinue.[h,cc]:
+     - implementes AllowEmpty option to support doing nothing 
+       defined in resource file
+     - added a first draft to allow usage of class-filters instead of 
+       rules
+
+   * mbase/MMath.[h,cc]:
+     - implemented a function suggested by Florian Goebel which reduces
+       the precision of a float to ~0.5% which is usefull for data
+       compression by gzip
+
+   * mdata/MDataChain.[h,cc]:
+     - implemented ReadEnv member function
+
+   * mfbase/MF.cc:
+     - a small enhancement to the output in ReadEnv
+
+   * mhbase/MH3.cc:
+     - fixed call to FindObject in Paint which caused a profile to be
+       displayed incorrectly in case it was read from a file
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - removed old obsolete unsused Significance functions
+     - implemented ReadEnv member function
+     - set false source binning only if BinningFalseSource is not default
+     - check parlist for BinningAlpha
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc, 
+     mjobs/MJPedestal.cc:
+     - added an additional check and output if output-file could
+       not be opened
+
+   * mjobs/MJob.h:
+     - added some Getter
+
+   * mhbase/MBinning.[h,cc].
+     - added nen member functions
+       + SetEdgesRaw
+       + ReadEnv
+       + Print
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added new member function ReadEnv
+
+   * mhflux/MHAlpha.cc:
+     - fixed a problem when fitting without off-data
+
+   * mbase/MStatusDisplay.cc:
+     - implemented a further fix in DrawClonePad to make sure
+       that the X-stuff doesn't get confused while still
+       GetDrawOption returns the correct value
+
+
+
+ 2005/01/24 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - introduced security check for the times fine-tuning to catch 
+       outliers because of deviating pulse forms.
+
+   * msignal/MExtractTime.cc
+   * msignal/MExtractor.cc
+     - lowered default high-gain saturation limit to 250
+     - removed Clear() for two results containers at beginning of Process()
+
+   * msignal/MExtractor.h
+     - Take fHiLoLast into the Clone()
+
+   * msignal/MExtractedSignalPix.cc
+     - change sign of default initializer to negative.
+
+
+
+ 2005/01/23 Markus Gaug
+  
+   * mhcalib/MHCalibrationHiLoCam.[h,cc]
+     - updated to new logain switch setting in MExtractTimeAndCharge
+     - extract also high-gain vs. low-gain time difference
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+     - updated reading of conf. values in ReadEnv
+
+   * mhcalib/MCalibrationHiLoCam.[h,cc]
+   * mhcalib/MCalibrationHiLoPix.[h,cc]
+   * mhcalib/MCalibrationIntensityHiLoCam.[h,cc]
+     - updated accordingly
+
+   * mbadpixels/MBadPixelsCam.cc
+     - removed some bugs in the Print() function
+
+
+
+ 2005/01/22 Markus Gaug
+
+   * mhcalib/MHCalibrationRelTimeCam.cc
+     - display in the averaged times display the event-by-event averaged
+       absolute arrival times instead of the rel. ones which do not make 
+       much sense.
+
+   * mhcalib/MHCalibrationTestTimeCam.[h,cc]
+   * mhcalib/MHCalibrationTestCam.[h,cc]
+     - update to the latest changes in analysis chain.
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - update to the latest changes in analysis chain.
+    
+   * mjobs/MJCalibration.cc
+     - replace title of that times-averageing Tab from "RelTimes" by 
+       "Times".
+
+   * macros/calibration.C
+     - update to changes in MJExtractCalibTest
+
+
+
+ 2005/01/21 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - use the max. bin content for low-gain extraction
+   
+   * callisto.rc
+     - add place for LoGainSwitch
+
+
+
+ 2005/01/21 Florian Goebel
+
+   * mfbase/MF.cc:
+     - include a (TString) cast to make it compilable with gcc2.95.3
+
+
+
+ 2005/01/21 Thomas Bretz
+
+   * mpointing/MSrcPosFromModel.cc:
+     - fixed crash in Process if no pointing model available
+
+   * mpointing/MPointingPosCalc.h:
+     - added missing initialization of data members
+
+   * mastro/MObservatory.[h,cc]:
+     - added ReadEnv member function
+
+   * mbase/MTaskEnv.h:
+     - added (=0) default to SetDefault
+
+
+
+ 2005/01/20 Markus Gaug
+
+   * mcalib/MCalibrationIntensityChargeCam.[h,cc] 
+     - added function to display fluctuations of a variable
+
+   * mcalib/MCalibrationPix.cc
+     - fixed small bug in High-gain mean error.
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - introduced high-gain maximum limit before extracting the low-gain
+
+
+
+ 2005/01/20 Thomas Bretz
+
+   * mbase/MContinue.[h,cc]:
+     - added ReadEnv member function to support resource files
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added a second arguemtn to reading of the resource file by name
+     - added some checks when reding the resource file and the
+       parameter list hasn't been setup
+
+   * mbase/MParList.cc:
+     - removed an obsolete output from ReadEnv
+
+   * mfbase/MF.[h,cc]:
+     - added ReadEnv member function to support resource files
+     - added kAllowEpty flag to support skipping by resource files
+
+   * mfbase/MFilterList.cc:
+     - added a comment
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - fixed Write to be compatible with root 4.02/00
+     - worked around a problem with reading the DrawOption correctly
+       from a stored status display
+
+
+
+ 2005/01/19 Thomas Bretz
+ 
+   * mbase/MMath.cc:
+     - added a comment to SignificanceLiMa, made by Daniel Mazin
+     - also check for b==0
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - fixed significance calculation in case of on-off data
+     - added fScaleFactor
+
+   * mhflux/MHAlpha.[h,cc], mhflux/MHFalseSource.cc:
+     - handle scale factor in case of on-off observations
+
+   * mjobs/MJPedestal.cc:
+     - aligned screen output to 80col rule
+
+   * mtrigger/MFTriggerPattern.[h,cc]:
+     - assigned correct integers to enum
+     - made sure that the enum is correctly handled in all function by
+       applying a r-value to the condition
+
+
+
+ 2005/01/19 Abelardo Moralejo
+
+   * mtrigger/MFTriggerPattern.[cc,h]
+     - Changed Bool_t arguments of all setters to new type Prescale_t
+       defined by N. Galante (see below)
+
+
+
+ 2005/01/19 Nicola Galante
+
+   * mtrigger/MFTriggerPattern.[cc,h]
+     - added in header enum Prescale_t { kUnPrescaled = kFALSE, 
+       kPrescaled   = kTRUE }; 
+
+     - fixed a bug in Process, both fMaskRequiredUnprescaled and
+       fMaskRequiredPrescaled are checked simultaneously.
+
+
+
+ 2005/01/18 Markus Gaug
+
+   * mcalib/MCalibColorSet.cc
+     - fixed the remaining day of data without colour in project name
+       neither in digital modules bits.
+
+   * mpedestal/MPedCalcPedRun.[h,cc] 
+     - catch the continuous light runs with MRawRunHeader::fRunType 
+       == kRTCalibration to be recognized as effective pedestal runs.
+
+
+ 2005/01/18 Thomas Bretz
+
+   * mbase/MMath.cc:
+     - added a check for s==0 in SignificanceLiMa, because otherwise the 
+       result is NaN
+
+   * mfbase/MF.cc:
+     - removed an obsolete debugging output from the latest changes
+
+   * mhflux/MHAlpha.cc:
+     - reset fHTime, too
+
+
+
+ 2005/01/18 Nicola Galante
+
+   * mtrigger/MFTriggerPattern.cc:
+     - added parentesis to ensure bitwise operators priority
+       with respect to logical operators.
+
+
+ 2005/01/17 Thomas Bretz
+ 
+   * manalysis/MEnergyEstimate.[h,cc]:
+     - changed to be more general. Energy is now estimated from a rule
+       (MDataChain) The default behaviour is still the same as before
+       to copy the energy from MMcEvt
+
+   * mbase/MTask.cc:
+     - changed to write out the descriptor istead of the task-name only
+       in Pre/PostProcess
+
+   * mhbase/MH.cc:
+     - initialize fSerialNumber and fNumExecutions in constructor
+
+   * mhflux/MHFalseSource.cc:
+     - according to a suggestion by Markus Mayer I have changed
+       \\sigma_{max}=f to S_{max}=f\\sigma
+
+   * mjobs/MJCalibrateSignal.cc:
+     - as discussed with Markus and Abelardo fixed the MFTriggerPattern
+       call.
+
+   * mtrigger/MFTriggerPattern.cc, mtrigger/MTriggerPattern.cc,
+     mtrigger/MTriggerPatternDecode.cc:
+     - added some comment about file version
+
+   * mbase/MFilter.h:
+     - implemented new virtual function GetDataMember like in MData
+
+   * mbase/MTask.[h,cc]:
+     - when filter is added ass GetDataMember to branch list (should be
+       obsolete, because filter is in the tasklist, but it should not hurt)
+
+   * mfbase/MF.[h,cc], mfbase/MFDataChain.[h,cc], mfbase/MFDataMember.[h,cc],
+     mfbase/MFilterList.[h,cc]:
+     - implemented new function GetDataMember
+
+
+
+ 2005/01/17 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - remove a situation where the high-gain signal can be 0.
+
+   * mtrigger/MTriggerPattern.h
+     - fixed a bug in defining the trigger bit pattern (Have to start
+       from 0 instead of 1)
+
+   * mjobs/MJPedestal.cc
+   * mjobs/MJCalibrateSignal.cc
+     - fixed default extraction ranges.
+
+   * callisto.rc
+     - fixed default weights files for pedestal extraction for cosmcis
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - removed program exit on occurrance of multiple colours without 
+       intensity calibration
+
+
+
+ 2005/01/17 Nadia Tonello and Markus Gaug
+
+   * mcalib/MCalibrationChargeCam.cc
+     - some fit improvements in the function GetAveragedConvFADC2PhotPerArea
+
+
+
+ 2005/01/16 Markus Gaug
+
+   * mhcalib/MHCalibrationCam.[h,cc], mhcalib/MHCalibrationRelTimeCam.[h,cc],
+     mhcalib/MHCalibrationChargeCam.[h,cc]
+     - put overflow management and results camera initialization into 
+       base class
+ 
+   * mcalib/MCalibrateData.[h,cc]
+     - added possibility to re-normalize signal to equiv. photo-electrons
+       ( SetSignalType(MCalibrateData::kPhe) ). 
+       Default is old version in photons
+     - speed up Process by storing pre-calculated calibration constants
+       in arrays (needed 40% of CPU time of the eventloop before, now: 23%) 
+     - added new pointer to different MCalibrationChargeCam used for 
+       updates
+     - added possibility to update the conversion factors using the 
+       MCalibrationChargeCam stored in fCalibUpdate. 
+     - added Print() function
+
+   * mcalib/MCalibCalcFromPast.[h,cc]
+     - committed final version, now also in the Makefile
+
+   * mjobs/MJCalibrateSignalFromOutside.[h,cc], macros/calibration.C
+     - committed final version, now able to calibrate interlaced cal. 
+       events.
+
+
+
+ 2005/01/14 Hendrik Bartko
+
+   * msignal/calibration_weights_UV.dat
+     - fixed a small bug in the noise autocorrelation of the AB-noise
+
+   * msignal/calibration_weights_blue.dat	
+     - new weights file for blue calibration pulses
+
+   * cosmics_weights.dat
+     - fixed a small bug in the noise autocorrelation of the AB-noise
+
+
+
+ 2005/01/14 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - added a small acceleration of the program, tested by Hendrik and
+       me.
+
+   * mpedestal/MPedCalcFromLoGain.cc
+     - fixed one warning output which was not a real warning.
+
+   * mcalib/MCalibrationChargeCam.cc
+     - improved the function to calculate a mean conversion factor over 
+       the whole camera including a fit to the values.
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - undo some changes introduced by TB on 2/12/04 which had made the 
+       use of interlaced pedestal events impossible again. 
+     - Use now the new class MTriggerPattern directly to recognize an 
+       interlaced pedestal event.     
+
+
+
+ 2005/01/14 Thomas Bretz
+ 
+   * callisto.cc:
+     - fixed a typo in output
+
+   * manalysis/MGeomApply.cc:
+     - removed some old code already in comments
+     - added possibility to switch off automatic processing (used
+       if two different geometries around)
+
+   * manalysis/MMultiDimDistCalc.cc, mhbase/MHMatrix.[h,cc],
+     mranforest/MRanForestCalc.cc, mtools/MHSimulatedAnnealing.[h,cc],
+     mtools/MSimulatedAnnealing.h:
+     - added include of TVector because in newer root version it is 
+       not included from TMatrix anymore
+
+   * mbase/BaseLinkDef.h, mbase/MMath.[h,cc]:
+     - to stick to the convention of TMath in newer root versions MMath
+       changed from a class to a namespace
+
+   * mbase/MEvtLoop.[h,cc]:
+     - to support newer root version added a second Write-function
+       with a const qualifier.
+
+   * mdata/MDataChain.cc:
+     - changed access to TMath for newer root versions
+
+   * mfileio/MChain.[h,cc]:
+     - implemented a workaround for teh changed LoadTree definition
+       in newer root-versions
+
+   * mfileio/MReadTree.cc:
+     - fixed a bug in CheckBranchSize caused some warning to be
+       displayed
+
+   * mhflux/MHAlpha.cc:
+     - removed check for fResult in PostProcess (it is always there)
+
+   * msignal/MExtractTimeFastSpline.cc:
+     - fixed delete --> delete[]
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - slight change to some output
+
+   * mbase/MTaskEnv.h:
+     - set name of default task when pointer is given
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed handling of extraction range for various cases
+     - fixed handling in case no arrival times are calculated
+
+   * mjobs/MJCalibration.cc:
+     - write at least a default arrival time calibration container
+       to make further processing easier
+
+   * mjobs/MJPedestal.[h,cc]:
+     - fixed handling of extraction range for various cases
+
+
+
+ 2005/01/14 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/trainsubsample.C, RanForestDISP.C
+     - added. Two macros used in the analysis of real wobble mode data.
+
+
+
+ 2005/01/14 Daniela Dorner
+
+   * macros/sql/filldotrun.C
+     - added new arehucas-verions and changed code accordingly
+
+
+
+ 2005/01/13 Abelardo Moralejo
+
+   * macros/starmc.C
+     - Added (commented) lines for the case of gamma MC source off-axis 
+       (wobble mode). Changed default extractor to 
+       MExtractFixedWindowPeakSearch.
+
+
+
+ 2005/01/13 Raquel de los Reyes
+
+   * callisto.rc
+     - introduced several configuration lines 
+       (format: "class".DataCheck: No) to allow callisto 
+       to run with rawfiles. Necessary for the datacheck.
+
+
+
+ 2005/01/13 Markus Gaug
+
+   * mcalib/MCalibColorSet.cc
+     - fixed runs 45605-45609
+
+   * msignal/MExtractor.h
+     - take out the variable fHiLoLast from the streamer. Will be 
+       initialized in the ReInit(), if needed
+
+   * msignal/MExtractor.cc
+     - Initialized fHiLoLast to 0. Otherwise, a second eventloop with 
+       the same extractor may have that variable set to a certain 
+       value, even if not desired. The ReInit() fixes fHiLoLast, if 
+       different from 0.
+
+   * mpedestal/MExtractPedestal.cc
+   * mpedestal/MPedCalcPedRun.cc
+   * mpedestal/MPedCalcFromLoGain.cc
+     - fix the output of the print to the correct value for the case 
+       that the extractor is used.
+
+
+ 2005/01/13 Thomas Bretz
+
+   * callisto.rc:
+     - fixed some typos
+
+   * mbase/MLog.cc:
+     - unset DEBUG defined unintentionally
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - removed printing Weights in InitArrays, because otherwise
+       the output of a full data calibration is totally crowded
+       with numbers. Having the weights-file name on the display
+       is perfectly enough.
+
+
+
+ 2005/01/12 Markus Gaug
+
+   * mcalib/MCalibrationIntensityRelTimeCam.cc
+     - added fit to improve averageing of the obtained results
+
+
+
+ 2005/01/12 Thomas Bretz
+
+   * manalysis/MMatrixLoop.cc:
+     - changed name to MRead because it now derives from MRead
+
+   * mbase/MEvtLoop.[h,cc]:
+     - implemented an option not to cascade the status display to the
+       parameter list in PreProcess
+
+   * mhflux/MHAlpha.cc:
+     - changed name of "Significance" to "MinimizationValue"
+     - return -significance to have a value being minimized
+
+   * mhist/MHCamera.cc:
+     - fixed output of text in legend
+
+   * mhist/MHEvent.[h,cc]:
+     - implemented new options for calibrated pedestals
+
+   * mmain/MEventDisplay.cc:
+     - fixed to support latest changes in MJCalibrateSignal
+
+   * mpedestal/MPedPhotCam.cc:
+     - added new options in GetPixelContent (4 and 5) to support
+       a correct camera display
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed display of calibrated pedestal and pedestal rms
+     - changed order of plots. Now all interpolated values 
+       (means all calibrated values which are bad-pixel treated)
+       are displayed behind the unsuitable pixels.
+
+   * mjobs/MJ*.cc:
+     - corrected all wrong %06d to %08d to fit the number of
+       digits in run-numbers
+
+
+
+ 2005/01/11 Abelardo Moralejo
+
+   * mjobs/Makefile
+     - added missing include -I ../mtrigger
+
+
+
+ 2005/01/11 Thomas Bretz
+
+   * callisto.cc, callisto.rc:
+     - changed such, that all three kinds of pedestals are calcualted 
+       (usefull for studies)
+
+   * manalysis/MMatrixLoop.[h,cc]:
+     - derived from MRead
+     - implemented some basic functions from MRead
+
+   * mfilter/MFCosmics.[h,cc]:
+     - allow setting of name of MPedestalCam
+
+   * mhbase/MBinning.[h,cc]:
+     - added SetEdges taking MParList as input
+
+   * mhflux/MHAlpha.cc:
+     - use new function from MBinning
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - changed to calculate all three kinds of pedestals
+     - added filters for trigger pattern and illuminated events
+
+   * mjobs/MJPedestal.cc:
+     - give different names to tabs with different pedestals
+
+   * mjobs/MJStar.cc:
+     - on request changed used pedestal from "FromExtractor" to
+       "FromExtractorRndm"
+
+   * mtrigger/MTriggerPattern.h:
+     - added Reset function
+
+   * mtrigger/MTriggerPatternDecode.[h,cc]:
+     - added using file format version number
+
+
+
+ 2005/01/11 Markus Gaug
+
+   * mbadpixels/MBadPixelsPix.cc
+     - updated documentation
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - make pixels with deviating number of phes unreliable instead of 
+       unsuitable (this was already thought so, but missed to modify
+       at one place).
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+     - add possible flag 'kInterlaced': default: kFALSE (like before)
+     - added pointer to MRawEvtHeader to deny cosmics events in case
+       of 'interlaced' flag is set. No changes for 'normal' calibration
+
+
+
+ 2005/01/10 Benjamin Riegel
+ 
+   * mreport/MReportStarguider.cc, mreport/MReportStarguider.h
+     - added two classes for implementing starguider-data 
+ 
+   * mreport/ReportLinkDef.h
+     - added class MReportStarguider to be linked:
+       #pragma link C++ class MReportStarguider+;
+     
+   * mreport/Makefile
+     - added file MReportStarguider.cc
+   
+   * merpp.cc
+     - added two containers ( MReportStarguider, MTimeStarguider ) and
+       added MReportStarguider to the list:
+       w->AddContainer("MReportStarguider",  "Starguider");
+       w->AddContainer("MTimeStarguider",    "Starguider");
+       r->AddToList("MReportStarguider");
+       
+       
+       
+ 2005/01/10 Markus Gaug
+
+   * mcalib/MCalibColorSet.cc
+     - return kFALSE for CL-run instead of kTRUE
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - stop program in case that multiple colours are found in same file
+       without intensity calibration
+
+   * mbadpixels/MBadPixelsPix.h
+     - added two new possible UnCalibrated_t flags for the hi-lo 
+       calibration
+
+   * macros/calibration.C
+     - add the calls to:
+	  MArray::Class()->IgnoreTObjectStreamer();
+	  MParContainer::Class()->IgnoreTObjectStreamer();
+       in main.
+
+   * msignal/MExtractor.h
+     - added Getter for fOffsetLoGain (was still missing)
+
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+     - remove pixels with histogram overflow only if their percentage 
+       passes a certain limit (default: 0.5%). Before, every overflow 
+       lead to an unsuitable pixel.
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - implemented changes suggested by T.B. to speed up calculations
+     - take fNameWeightsFile into the streamer, otherwise the Clone() 
+       will always create an extractor with cosmic's weights. 
+     - set fOffsetLoGain to a slighly higher value. The DF seems to 
+       have a different offset since it uses different pulse shapes 
+       and thus sightly different time definitions.
+
+
+
+ 2005/01/10 Thomas Bretz
+
+   * mhvstime/MHVsTime.cc:
+     - fixed a compiler error for gcc 2.95.3, see Mantis bug # 157
+
+   * callisto.cc:
+     - changed such, that the calculated pedestal is not random
+       anymore
+     - added code to calculate the pedestal also with randomization,
+       but this code is for the moment commented out.
+
+   * callisto.rc:
+     - fixed naming of pedestal calculation
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - added a second check which compares the pedestal rms with
+       the variance of the pedestal rms in the same sector
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - changed to calculate the pedestal from extractor without 
+       randomization
+     - added code to calculate the pedestal also with randomization,
+       but this code is for the moment commented out.
+
+   * mjobs/MJCalibration.cc:
+     - made sure that pedcam always has the correct name
+       (FIXME? Print a warning if it has the wrong name)
+
+   * mjobs/MJPedestal.[h,cc]:
+     - changed such, that it allows the calculation of pedestals
+       in three different ways (fundamental, fromextractor, 
+       fromextractorrndm)
+     - therefor removed SetExtractorResolution and added
+       + void SetExtractionFundamental()
+       + void SetExtractionWithExtractorRndm()
+       + void SetExtractionWithExtractor()
+
+   * mjobs/MJStar.cc:
+     - changed/fixed the input name of the MPedPhotCam used in the
+       image cleaning
+
+   * mraw/MRawFileRead.[h,cc]:
+     - changed return type of OpenNextFile
+     - in some cases return kERROR in OpenNextFile to abort the Processing
+       with an error
+
+   * mraw/MRawRunHeader.cc:
+     - call a wrong file format version ERROR now
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - make sure that resetted values are returned if fit failed
+     - set default scaling too kOffRegion
+
+   * mhflux/MHAlpha.cc:
+     - some small fixes to handling of MHAlphaOff
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - implemented possible usage of MHFalsSourceOff for On-Off-Analysis
+     - updated display accordingly
+     - updated fit accordingly
+     - removed catalog temporarily from plots until I found the
+       reason for the strange crashes
+
+   * mbadpixels/MBadPixelCalc.[h,cc]:
+     - implemented the possibility to check the pedestal rms against the
+       variance of the pedstal rms, too. The option is curretly switched
+       off.
+     - enahanced informal output in PreProcess
+
+   * mbase/MTaskList.cc:
+     - a little change to some output
+
+
+
+ 2005/01/10 Wolfgang Wittek
+
+   * mfbase/MFEventSelector2.cc
+     - check whether filter exists before calling 
+       filter->CallPreProcess(parlist)
+
+
+
+ 2005/01/08 Markus Gaug
+
+   * mhcalib/MHCalibrationHiLoCam.[h,cc]
+   * mcalib/MCalibrationHiLoCam.[h,cc]
+   * mcalib/MCalibrationHiLoPix.[h,cc]
+   * mcalib/MIntensityCalibrationHiLoCam.[h,cc]
+   * mhcalib/Makefile, mcalib/Makefile, mhcalib/HCalibLinkDef.h, 
+     mcalib/CalibLinkDef.h
+     - new classes for calibration of conversion high-gain vs. low-gain 
+
+   * msignal/MExtractedSignalPix.[h,cc]
+     - added data member fChisquare, set to -1. by Clear() and Reset()
+     - raised version number by 1
+
+   * msignal/MExtractedSignalCam.[h,cc]
+     - added data member fNdf, set to -1 by default
+     - new function: GetProb(const Int_t pixidx) to be called to 
+       calculate the joint probability of Chisquare of pixel "pixidx"
+       and fNdf
+     - added documentation of data members
+     - raised version number by 1
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - strengthened default histogram limits a bit, should accelerate
+       the calibration by 20%.
+
+   * mjobs/MJCalibrateSignalFromOutside.cc
+     - fixed two lines to compile MCalibrateData with the recent changes
+       by TB
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - fixed two bugs introduced yesterday by TB.
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - adopt part of TB's speed accelerations into these classes
+
+   * msignal/MExtractTimeAndCharge.cc
+     - fix the low-gain extraction window for the case that the high-gain
+       is saturated. Was skipped so far.
+
+
+
+ 2005/01/07 Markus Gaug
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - catch the case that more than 90% of the pixels have saturated 
+       signals and fix the extraction window from the occurrance of 
+       saturation, then. Important for high-intensity calibration events.
+
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractTime.cc
+   * msignal/MExtractTimeAndCharge.cc
+     - added some documentation
+
+   * msignal/MExtractTime.[h,cc]  
+     - moved the empty function FindTimeHiGain() and FindTimeLoGain() to
+       the header-file.
+      
+
+
+
+ 2005/01/07 Abelardo Moralejo
+
+   * mbase/MLog.h
+     - Added #include "TSystem.h", otherwise gSystem is not recognized
+       in Mac OSX.
+
+   * manalysis/MMakePadHistograms.cc
+     - Changed badcalc.SetNamePedPhotContainer to 
+       badcalc.SetNamePedPhotCam
+
+
+
+ 2005/01/07 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCalc.[h,cc], macros/ONOFFAnalaysis.C:
+     - replaced PedPhotContainer by PedPhotCam for consistency
+   
+   * mbase/MLog.[h,cc]:
+     - return *this in Seperator()
+
+   * mbase/MPrint.[h,cc]:
+     - use new separator manipulator in PreProcess
+     - fixed a type: separator instead of seperator
+
+   * mfileio/MReadTree.[h,cc]:
+     - added a check for branch->IsAutoDelete() in Notify()
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - added new option 'fRandomCalculation' be used to switch on-/off-
+       randomization in extractors, the default should be like before
+     - added Process() calling Calc()
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc], mpedestal/MPedCalcPedRun.[h,cc]:
+     - renamed Process() to Calc()
+
+   * Makefile:
+     - removed macros/calibration.C, which seems to have been
+       unintantionally introduced.
+
+   * manalysis/Makefile:
+     - removed unintantionally introduced wrong include
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - a small acceleration discussed with Hendrik by replacing a
+       counter in a loop by pointer arithmetics
+
+   * mraw/MRawEvtPixelIter.cc:
+     - fixed a bug in GetMaxIdxHiLoGain which caused the loop to
+       read one byte behind the end of the array
+     - fixed HasLoGain() which really did weired things, means accessing
+       sometimes memory somewhere. This could theoretically result
+       in assigning the wrong lo-gains to the wrong pixels.
+
+   * mtrigger/MTriggerPattern.[h,cc], mtrigger/MTriggerPatternDecode.[h,cc],
+     mtrigger/MFTriggerPattern.[h,cc]:
+     - added
+
+   * mtrigger/Makefile, mtrigger/TriggerLinkDef.h:
+     - added MTriggerPattern, MTriggerPatternDecode and MFTriggerPattern
+
+   * manalysis/MEnergyEstParam.h:
+     - added a new function SetVariables calling SetCoeff
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - removed data members for container names
+     - added new lists for container names
+     - allow to calibrate more than one pedestal container at the same
+       time
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed accordingly
+
+
+
+ 2005/01/05 Thomas Bretz
+
+   * mcalib/MCalibrationBlindPix.cc, mcalib/MCalibrationChargeCalc.cc,
+     mhcalib/MHCalibrationRelTimeCam.cc:
+     - made some output lines fit into convinience window of 80 col
+
+   * mhist/MHCamEvent.cc:
+     - make sure that x-axis has correct title
+
+   * msignal/MArrivalTimePix.cc:
+     - init error to -1 which is a obviously non valid value
+     - fixed IsValid() which gave wrong results
+
+   * msignal/MExtractTimeAndCharge.cc, msignal/MExtractedSignalPix.cc:
+     - made sure that LoGain is flagged non-valid if no lo-gain exists
+     - push time back at the edge of the allowed limits if outside
+
+   * mbase/MGList.[h,cc]:
+     - introduced new functions Delete and DeletePictures
+     - SetBit(kMustCleanup) in constructor. Otherwise it is not
+       correctly removed from ListOfCleanups
+
+   * mbase/MLog.cc:
+     - SetBit(kMustCleanup) if adding a plugin to make sure it is cleaned
+       from the list
+
+   * mbase/MParContainer.[h,cc]:
+     - replaced return type of GetDescriptor by TString. The old version
+       was terribly wrong! The returned memory wasn't removed as soon
+       as the function returned.
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - for security (thread safty) replaced all Form() by MString::Form()
+     - implemented a more secure scheme of Closing (Clone()) this was
+       a hint given by valgrind
+     - set kMustCleanup for all new object in ClonePad not only kCanDelete
+     - fixed some lines in pulldown-menus
+     - add TPads to ListOfCleanups in ClonePad (workaround!)
+
+   * mbase/MString.[h,cc]:
+     - implemented a new static Form() function returning a copy of
+       the result
+
+   * mbase/MTask.[h,cc]:
+     - replaced return type of GetDescriptor by TString. The old version
+       was terribly wrong! The returned memory wasn't removed as soon
+       as the function returned. 
+     - Made GetDescriptor thread safe using MString::Form
+
+   * mfileio/MWriteRootFile.cc:
+     - Use GetDescriptor().Data() when using any kind of printf function
+
+   * mhbase/MFillH.cc:
+     - replaced string concatenation in all constructors by a Form 
+       (also suggested by valgrind)
+
+   * mhcalib/MHCalibrationRelTimeCam.cc:
+     - made some output fit into 80col boundary
+
+
+
+
+ 2005/01/03 Thomas Bretz (HAPPY NEW YEAR)
+
+   * mfht:
+     - added new directory for hexagonal fourier transformation
+
+   * mfht/HftIncl.h, mhft/HftLinkDef.h, mhft/MGeomCamMagicXT.[h,cc],
+     mhft/MGeomCamMagicEnhance.[h,cc], mhft/MHexgaonalFT.[h,cc], 
+     mhft/MHexagonalFreqSpace.[h,cc], mhft/MHexagonalFTCalc.[h,cc],
+     mhft/Makefile:
+     - added
+
+   * macros/extendcam.C: 
+     - added: tutorial for MGeomCamExtend
+
+   * macros/hft.C: 
+     - added: tutorial for MHexgonalFTCalc
+
+   * macros/dohtml.C: 
+     - updated
+
+   * macros/rootlogon.C: 
+     - updated
+
+   * Makefile:
+     - mhft added
+
+   * mbase/MParContainer.cc, mbase/MLog.cc:
+     - added a pre-compiler option for destructor debugging
+
+   * mbase/MTaskList.[h,cc]:
+     - added new function Replace
+
+   * mdata/MDataChain.cc, mfbase/MF.cc:
+     - shortened some output
+
+   * mdata/MDataArray.[h,cc]:
+     - added new function FindRule
+
+   * mfileio/MReadTree.[h,cc]:
+     - enhanced functionality to be able to read a TTree stored in memory
+       instead of a file. Therefor introduced fTree which is now the pointer
+       used and replaced fChain where TTree and TChain have common behaviour.
+       Where they behave uncommon new code for the new case has been added.
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - enhanced functionality to be able to write a TTree into memory
+       instead of a file. This were maily bugfixes for the case fOut==0, which
+       must be handled correctly. Becarefull a tree filles without a file
+       is not deleted automatically!
+    
+   * mhbase/MBinning.h:
+     - added copy constructor
+     - fixed buggy SetEdges(MBinning&) which didn't work
+
+   * mhbase/MHMatrix.cc:
+     - when adding a new rule check first if the same rule already exists
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added new functionality to support on-off analysis
+     - didn't touch existing code
+
+   * mhflux/MHAlpha.[h,cc]:
+     - added new functionality to support on-off analysis
+     - replaced Fit() calls by newer function calls
+     - added DrawAll - PRELIMINARY
+     - fixed a bug when projecting - may be the reson for some strange
+       crashes
+
+   * mcalib/MCalibColorSet.cc:
+     - fixed a stupid bug introduced last year, which caused MCalibColorSet
+       in some circumstances to stop the eventloop when it shouldn't
+
+   * mjobs/MSequence.cc:
+     - expand path names
+ 
Index: branches/Mars_McMismatchStudy/Changelog.06
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.06	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.06	(revision 17960)
@@ -0,0 +1,4465 @@
+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 -*-*-
+ 2006/12/14 Daniela Dorner
+ 
+   * datacenter/macros/filloptical.php:
+     - implemented filling of Tuorla data
+
+   * datacenter/db/opticaldata.php, datacenter/db/magicdefs.php:
+     - implemented telescope and band
+
+
+
+ 2006/12/13 Thomas Bretz, Daniela Dorner, Stefan Ruegamer
+ 
+   * datacenter/scripts/movingrawfiles:
+     - added check if the number of rawfiles in the database matches the
+       number of rawfiles in the fromlapalma/RAW/-folder. If not, the
+       files won't be copied. Workaround for the case that the .finished
+       file has arrived but the number of transfered files is wrong.
+     - added warning in case that there are non-rawfiles in the
+       fromlapalma/RAW/-folder
+
+
+
+ 2006/12/13 Daniela Dorner
+
+   * scripts/preparemc:
+     - removed function makedir
+     - improved structure in output directory (setup, sequence and 
+       dataset directory)
+     - improved algorithm to get date from directory name
+     - removed setting of root environment variables
+     - adapted comments
+   
+   * scripts/dospectrum:
+     - added (script to produce ganymed.rc files with different sets of
+       cuts and to run ganymed and sponde for these sets)
+   
+   * scripts/processsequence:
+     - added function checkreturncode
+     - improved logging in case of an error
+   
+   * datacenter/macros/buildsequenceentries.C
+     - included errno.h (with new compiler it didn't compile anymore)
+     - changed name of object (was same like for TPRexexp)
+
+   * datacenter/scripts/checktransfer:
+     - added check if there are temporary files 
+
+
+
+ 2006/12/12 Thomas Bretz
+
+   * mjobs/MSequence.cc:
+     - fixed a bug in SetupRuns introduced yesterday which made the
+       setup fail if SetupRuns were called more than once.
+
+   * mfileio/MReadTree.[h,cc]:
+     - added function returning the number of files in the chain
+
+   * mfileio/MReadMarsFile.cc:
+     - added a check which correlates the number of entries in
+       RunHeaders with the number of files
+
+
+
+ 2006/12/11 Thomas Bretz
+
+   * mbase/MParContainer.cc, mbase/MParList.cc:
+     - some improvements to log-output
+
+   * mextralgo/MExtralgoDigitalFilter.cc:
+     - default for "out-of-range" is now -2
+
+   * mpedestal/MHPedestalCor.cc:
+     - small fix (the used range was one slice to brought)
+
+   * mjobs/MJCalibration.cc, mjobs/MJCalibrateSignal.cc, mjobs/MJStar.cc:
+     - improved output in case of no files found
+
+   * mjobs/MJPedestal.cc, mjobs/MJCalibTest.cc, mjobs/MJCalibration.cc,
+     mjobs/MJCalibrateSignal.cc, mjobs/MJStar.cc:
+     - moved output in case of invalid number of runs for a sequence
+       to MSequence
+     - stop execution if no or not all files were found
+
+   * mjobs/MSequence.cc:
+     - added some output and return an error if the number of requested
+       files doesn't match the number of files found.
+
+   * mjobs/MDataSet.cc:
+     - when Setting up dat-runs fails now an error is returned
+
+   * mjobs/MJSpectrum.cc, mjobs/MJCut.cc:
+     - if the number of files set from a sequence doesn't match the number
+       of files found stop execution
+
+   * mjoptim/MJOptimize.cc, mjtrain/MJTrainDisp.cc, mjtrain/MJTrainEnergy.cc:
+     - stop execution if number of requested and found files mismatch
+
+   * mjoptim/MJOptimizeCuts.cc, mjoptim/MJOptimizeDisp.cc,
+     mjoptim/MJOptimizeEnergy.cc:
+     - added more informative log output
+
+
+
+ 2006/12/04 Thomas Bretz
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - fixed a typo in a console message
+
+
+
+ 2006/11/16 Daniela Dorner
+
+   * datacenter/macros/filloptical.C:
+     - added errorhandling if insert of query failes
+
+   * datacenter/tools/fillobjects.C, datacenter/tools/fillobjects2.C:
+     - exchanged update by insert 
+
+   * datacenter/scripts/copyscript:
+     - added filling of optical information into database and moving 
+       of optical data files into the datacenter structure
+
+
+
+ 2006/11/03 Thomas Bretz
+
+   * datacenter/macros/plotoptical.C, datacenter/macros/plotdb.C,
+     datacenter/macros/plotrundb.C:
+     - improved grouping
+     - added comments
+
+   * mjobs/MJCalibrateSignal.cc:
+     - do not write MPedestalFundamental -- this only wasts space
+     - do not calibrate and bad-pixel treat it anymore
+
+
+
+ 2006/11/02 Daniela Dorner
+
+   * datacenter/db/plotdb.php:
+     - exchanged pulldown for plot-option by radio buttons
+
+   * scripts/preparemc:
+     - updated setting of root-version (/opt/root_v5.12.00f)
+     - updated mcpath (/magic/montecarlo/rawfiles)
+     - removed usage of sourcefile
+
+
+
+ 2006/11/02 Thomas Bretz
+
+   * datacenter/macros/fillstar.C:
+     - changed such that no muon rates below 0 are entered into the DB
+
+   * mhcalib/MHCalibrationCam.cc:
+     - reformatted and improved output
+     - do not complain about empty lo-gain histograms (BTW:
+       it should complain if the histogram should not be empty!)
+
+   * mranforest/MHRanForestGini.cc, mranforest/MRanForest.cc,
+     mranforest/MRanForestCalc.cc, mranforest/MRanTree.cc:
+     - small changes to output
+     - changes to comments
+
+   * datacenter/macros/plotstat.C:
+     - changed division of pad, we have already too much periods
+
+   * mfilter/MFCosmics.cc:
+     - do not take invalid pixels into account
+
+   * mmain/MEventDisplay.cc:
+     - removed obsolete include of MExtractSignal
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - in a possible case that the hi-gain etraction failed but the
+       lo-gain should be extracted we start one slice in front
+       of the lowest possible hi-gain time.
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - removed obsolete SignalStartBin data members
+     - set last hi-gain extraction slace from 15 to 16
+
+   * mcalib/MCalibCalcFromPast.[h,cc]:
+     - some changes to the log-output
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - reformatted some output
+
+   * mraw/MRawRunHeader.cc:
+     - reset setfill in output stream
+
+   * mimage/MNewImagePar.cc:
+     - do not take unmapped pixels into account
+     - do not start with d=max_radius^2 but with FLT_MAX
+
+
+
+ 2006/11/01 Daniela Dorner
+
+   * datacenter/db/builddatasets.php:
+     - added more warnings (inhomogeneity, number of identified and 
+       correlated stars)
+     - fixed bug in query getting the next datasetnumber
+     - implemented stop of inserting in case of failure of one query
+     - added init values for some limits
+     - changed fDataSetName from varchar(12) to varchar(20)
+     - enlarged space behind +/- menu items
+     - improved output for missing fRealSourceKEY
+     - removed fMaxHumidity and fArrTimeMeanInner from Init
+     - added and adapted init values for fPSF, fMeanPedRms, 
+       fMeanNumberIslands, fRation, relative ontime, fMuonRate, 
+       fPulsePos
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed bug introduced with change on 27.10.2006 (in query ')' was 
+       missing
+
+   * datacenter/scripts/writedatasetfiles:
+     - added (script that executes writedatasetfile.C)
+
+   * datacenter/scripts/sourcefile:
+     - added error-code variable for Fdatasetfilewritten
+
+   * steps.rc:
+     - added new column DataSetProcessStatus.fDataSetFileWritten
+
+   * datacenter/db/sequinfo-aio.php:
+     - changed init: fPSF, fMeanPedRmsInner and fLinks now switched on
+       by default
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/sequinfo-aio.php,
+     datacenter/db/sequinfo-aio.php, datacenter/db/builddatasets.php:
+     - emphasis menu item 'Menu'
+
+   * datacenter/db/index-footer.html:
+     - adapted link to validator-img file
+
+   * datacenter/db/menu.php:
+     - changed menu label of fStartTime from StartTime to ProcessTime 
+       to avoid confusions
+
+   * datacenter/db/menu.php, datacenter/db/magicdefs.php:
+     - removed fWobble (website was not working due to that) 
+     - implemented a min and a max limit for the relative ontime
+     - removed limit for arrival time
+
+   * datacenter/db/include.php:
+     - changed code to determin the colour of an table entry to 
+       provide the possibility to set different limits for one value
+
+
+
+ 2006/11/01 Thomas Bretz
+
+   * datacenter/macros/plotdb.C, datacenter/macros/plotoptical.C:
+     - a lot of changes starting to unify the different plot macros
+     - use the new function to get the joins automatically
+     - further improved grouping
+
+   * datacenter/macros/plotrundb.C:
+     - added
+
+   * msql/MSQLServer.[h,cc]:
+     - implemented a new function returning the primary key of a table
+     - added a new function to return the joins automatically
+       necessary to do a query
+     - changed the call to GetTables and GetColumns
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - added a DrawNicePlot feature like for MHAlpha
+
+   * mmain/MEventDisplay.cc:
+     - added MPedestalSubtract
+     - new default size
+
+   * mbase/MLogHtml.cc:
+     - improved colors
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - reformatted some output
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - when filling the histograms only fill signals which are
+       valid
+     - do not count the number of lo-gain saturation slices, just
+       check whether it is saturating or not
+     - for the moment we do not take the fTimeLower/UpperLimit into
+       account. It is enough if the extracted time is within the
+       extraction range (TO BE IMPROVED!)
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - improved output
+     - do not check th elo-gain if hi-gain is already above saturation
+       limit.
+
+   * mhcalib/MHCalibrationRelTimeCam.cc:
+     - extended first bin from -4.975 to -9.975
+     - correctly handle validity and saturation of the pixels
+     - allow the reference pixel to be set from the resource file
+
+   * mhcalib/MHGausEvents.h:
+     - exclude empty histograms in IsOnlyUnderflow and IsOnlyOverflow
+
+   * msignal/MExtractTimeAndCharge.[h,cc]:
+     - added a new function which give an estimate for the arrival time
+       in case of saturation
+     - allow the arrival time to be a minimum of -1 before replacing
+       it by a random value
+     - in case of saturation use a polynomial of second order to
+       get a better estimation of the arrival time
+
+
+
+
+ 2006/10/31 Daniela Dorner
+
+   * datacenter/db/menu.php
+     - added PrintStarRangeMenu (inputs to query range for the 
+       timestamp when Star has been done)
+     - changed PrintFailedMenu (ReturnCode and FailedCode were labeled
+       wrongly)
+
+   * datacenter/db/magicdefs.php
+     - added fRunTimeLimit 
+     - shortened alias of fSkyBrightnessMed
+
+   * datacenter/db/builddatasets.php
+     - added (website to build datasets)
+
+   * datacenter/db/include.php
+     - exchanged \" by ' 
+     - added function CheckBox2 for $_POST
+     - added argument $form to function PrintMagicTable ($form 
+       indicates if a second <form> and the according checkboxes and 
+       inputs for $_POST are needed)
+     - added checkboxes in function PrintMagicTable for 2 additional 
+       columns needed in builddatasets.php 
+
+   * datacenter/db/culminating.php, datacenter/db/datacheck.php,
+     datacenter/db/datasetinfo.php, datacenter/db/datasetinfo-aio.php,
+     datacenter/db/dbstatus.php, datacenter/db/findoffdata.php, 
+     datacenter/db/index.php, datacenter/db/opticaldata.php, 
+     datacenter/db/printtable.php, datacenter/db/querycal.php, 
+     datacenter/db/querymc.php, datacenter/db/queryrbk.php, 
+     datacenter/db/queryseq.php, datacenter/db/querystar.php,
+     datacenter/db/runinfo-aio.php, datacenter/db/runinfo.php, 
+     datacenter/db/sequinfo-aio.php, datacenter/db/sequinfo.php, 
+     datacenter/db/sources.php, datacenter/db/statusrps.php, 
+     datacenter/db/statussps.php, datacenter/db/statussbs.php:
+     - changed call of function PrintMagicTable according to changes
+       in include.php
+
+
+
+ 2006/10/31 Thomas Bretz
+
+   * datacenter/macros/writedatasetfile.C:
+     - added
+
+
+
+ 2006/10/30 Thomas Bretz
+
+   * mbase/MMath.[h,cc]:
+     - added a new function to calculate the intersection point of
+       two lines
+
+   * mgui/MHexagon.[h,cc]:
+     - added function to calculate the intersection of two hexagons
+
+
+
+ 2006/10/30 Daniela Dorner
+
+   * datacenter/scripts/runcallisto:
+     - added output of commandline to runlog
+     - in case of missing cacofile the output and return value was wrong
+     - added printprocesslog in case of missing cacofile
+     - added filename to output of printprocesslog in case of failing
+       merppupdate
+
+   * datacenter/scripts/runstar:
+     - added output of commandline to runlog
+     - added staging of callistofiles
+
+   * datacenter/scripts/jobmanager:
+     - bugfix for the change of 25.10.2006 (reset of 
+       nothingtodosleeptime was missing)
+
+
+
+ 2006/10/27 Daniela Dorner
+
+   * datacenter/db/menu.js:
+     - exchanged names of functions show() and hide()(were named the 
+       wrong way round)
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php
+     datacenter/db/datasetinfo-aio.php:
+     - enlarged space behind +/- menu items
+
+
+
+ 2006/10/27 Thomas Bretz
+
+   * datacenter/macros/buildsequenceentries.C:
+     - included a fix for 0000-00-00 times in the run-database
+
+   * datacenter/macros/plotdb.C:
+     - implemented a possibility to show average values with RMS
+
+   * mjtrain/MJTrainSeparation.cc:
+     - do not print observation time statistics if observation time is
+       zero
+
+   * datacenter/macros/fillstar.C:
+     - do not fill arbitrary negative value
+
+   * mfbase/MF.cc:
+     - fixed a compiler warning about a comment
+
+   * mranforest/MRanForestCalc.cc:
+     - removed the appearance of an obsolete error message
+     - the printing of weights is now done less often
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - added a comment line
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - added reading and usage of "CalcHadronness" when processing 
+       the MCs
+     - added a plot for the Cut efficiency
+
+
+
+ 2006/10/26 Daniela Dorner
+
+   * datacenter/scripts/setup:
+     - updated root version 
+
+
+
+ 2006/10/25 Thomas Bretz
+
+   * mjtrain/MJTrainSeparation.cc:
+     - print filename into output
+     
+   * mbadpixels/MBadPixelsCam.cc:
+     - turned the warning when merging an empty cam into an info
+
+   * mextralgo/MExtralgoDigitalFilter.cc:
+     - removed some old comments, added some new ones
+
+   * mextralgo/MExtralgoSpline.[h,cc]:
+     - added some sanity checks to make sure that the spline
+       can be initialized and is initialized
+     - changed the default extraction position for noise extraction to be
+       in the middle of a 5 slice long spline
+
+   * msignal/MExtractTimeAndCharge.[h,cc]:
+     - removed a lot of old comment and added some new ones
+     - changed the behaviour of the determination of the start position
+       to extract the lo-gains
+     - added a spline interpolation to estimate the rrival time
+       of saturating hi-gains
+     - decreased the random range to the maximum extraction range
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc],
+     msignal/MExtractTimeAndChargeSpline.[h,cc]:
+     - removed a lot of comments, added some new ones
+     - removed fraRandomIter (replaced by a real random number)
+     - replaced some if-conditions by switch
+     - init the arrays to the maximum possible size
+
+
+
+ 2006/10/25 Daniela Dorner
+
+   * datacenter/scripts/jobmanager, datacenter/scripts/setup:
+     - added longer sleeping, when there is nothing to do for any script
+
+   * datacenter/db/plot.php, datacenter/db/plotdb.php, 
+     datacenter/db/plotinclude.php:
+     - added (websites to plot values from the db)
+
+   * datacenter/db/menu.js:
+     - added functions for plotdb menu
+
+   * datacenter/db/index-header.html, datacenter/db/index.html:
+     - added plotdb website
+
+
+
+ 2006/10/24 Thomas Bretz
+
+   * Makefile:
+     - added mextralgo directory
+
+   * mextralgo/MExtralgoDigitalFilter.[h,cc]:
+     - added code to calculate chisq
+     - some small changes to calculating the weights
+
+   * mextralgo/MExtralgoSpline.[h,cc]:
+     - removed the random iterator, use a random number instead
+     - removed obsolete variable fResolution
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc,
+     mjobs/MJPedestal.cc:
+     - introduced new MPedestalSubtract
+     - changed the range for the pedestal extraction window
+       (the window should be the same as the extractor search
+        window, even if it need not to be used in the case of
+        the random extractor)
+
+   * mpedestal/MExtractPedestal.[h,cc], mpedestal/MPedCalcPedRun.[h,cc],
+     mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - removed a lot of obsolte code
+     - unified and moved a lot of code to the base class
+     - moved code used only in a single derived class to this class
+     - changed and simplified the range check for the windows
+     - removed memcpy stuff, instead use the output of MExtractPedestal
+     - get the window size automatically from a possible extractor
+     - simplified InitBlindPixel
+
+   * mpedestal/Makefile, mpedestal/PedestalLinkDef.h:
+     - added MHPedestalCor
+     - added MPedestalSubtract
+     - added MPedestalSubtractedEvt
+     - removed MPedCalcFromData
+
+   * mpedestal/MHPedestalCor.[h,cc], mpedestal/MPedestalSubtract.[h,cc],
+     mpedestal/MPedestalSubtractEct.[h,cc]:
+     - added
+
+   * mpedestal/MPedCalcFromData.[h,cc]:
+     - removed
+
+   * msignal/MExtractTime.[h,cc]:
+     - commented out some code which will become obsolete soon
+     - improved Print() function
+
+   * msignal/MExtractTimeAndCharge.[h,cc]:
+     - redesign to use the new extraction interface
+     - changed from hi/lo-gain to one sample by using 
+       MPedestalSubtractedEvt
+     - changed the lo-gain star shift default to -6.0
+     - moved the determination of saturation and maxima into 
+       MPedestalSubtractedEvt
+     - improved Print() function
+     - removed obsolete data members
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - changed to use the new MExtralgo class instead of its own
+       algorithm
+     - now read a third column from the weights files
+     - improved Print() function
+     - removed obsolete data members
+     - added data member for pulse shape
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]:
+     - changed to use the new MExtralgo class instead of its own
+       algorithm
+     - changed rise-time from 0.5 to 0.7 and fall time from 0.5 to 1.0
+     - removed obsolete data members
+     - removed fRandomIter
+
+   * msignal/MExtractedSignalPix.h:
+     - changed some comments
+
+   * msignal/MExtractor.cc:
+     - changed default saturation limit from 250 to 245 to be
+       more than two times the ab-offset away from 255
+     - small changes to the range checks
+     - updated Print() function
+     - removed fHiLoLast data member
+
+   * msignal/Makefile:
+     - added mextralgo as include directory
+
+   * msignal/calibration_weights_UV46.dat, msignal/cosmics_weights46.dat:
+     - added third column (now contains zeros)
+
+   * msignal/MExtractBlindPixel.cc:
+     - replaced self allocated arrays by MArrays
+     - added data member fHiLoLast (for the moment)
+
+   * msignal/MExtractPINDiode.cc:
+     - removed printing of fHiLoLast (it wasn't used anyhow
+
+   * mjobs/pedestalref.rc. mjobs/pedestalref_Dec04.rc:
+     - changed the maximum displayed for the pedestal from 16 to 20
+       to match also newer data
+
+   * msignal/SignalIncl.h:
+     - removed obsolete includes
+
+   * msignal/MExtractBlindPixel.[h,cc]:
+     - changed according to the other changes
+     - removed a lot of obsolete variables
+     - changed interface to set blind pixel indices
+     - now directly use the spline extractor class
+
+   * mflux/MFHadAlpha.[h,cc], MHadAlphaCut.[h,cc]:
+     - removed obsolete classes
+
+
+
+ 2006/10/23 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - optimized log-output
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - added some comments
+
+   * mcalib/MCalibrationChargeCalc.cc, mhcalib/MHCalibrationCam.cc,
+     mcalib/MCalibrationChargePix.cc:
+     - changed format of a lot of output
+
+   * mfbase/MFDataPhrase.cc:
+     - added output of a newline in the constructor
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - count saturation only once (count the number of events not
+       the total number of saturating slices)
+     - changed format of a lot of output
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - simple optimization to algorithm, do not consider pixels
+       above saturation limit at all
+
+   * mbadpixels/MBadPixelsCam.[h,cc], mbadpixels/MBadPixelsIntensityCam.h:
+     - removed the run-option from the ascii input files
+     - allow merging a smaller into a larger camera
+
+   * mjobs/badpixels_0_559.rc:
+     - adapted
+
+   * mdata/MDataPhrase.cc:
+     - when checking for the matrices we have to start from the beginning
+       of our phrase
+
+
+
+ 2006/10/23
+
+   * RELEASE 0.10.3
+
+
+
+ 2006/10/23 Thomas Bretz
+
+   * msignal/MExtractTime.cc:
+     - removed setting of unsused extraction range to MArrivalTimeCam
+
+   * msignal/MArrivalTimeCam.[h,cc]:
+     - increased class version by 1
+     - added some comments
+
+
+
+ 2006/10/20 Thomas Bretz
+
+   * datacenter/macros/plotoptical.C:
+     - improved with more interesting values
+
+   * mastro/MAstro.h:
+     - added new constant for conversion from and into hours
+
+   * mbadpixels/MBadPixelsIntensityCam.[h,cc],
+     mcalib/MCalibrationIntensityCam.[h,cc]:
+     - added a RemoveOldCam member function
+     - commented out unused GetCam functions
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - removed some obsolete output in the case FindCreateObj fains
+     - if a new cam is added to the intensity cam list the old
+       cam is deleted now which fixes the bigges memory leak in callisto
+
+   * mcalib/MCalibrationChargeCalc.[h,cc], 
+     mcalib/MCalibrationRelTimeCalc.[h,cc]:
+     - removed fOutputPath and fOutputFile
+
+   * mjobs/MJCalibration.cc, mjobs/MJCalibrateSignal.cc:
+     - removed reference to SetOutputFile
+
+
+
+ 2006/10/20 Daniela Dorner
+
+   * datacenter/tools/fillobjects.php, datacenter/tools/fillobjects2.C:
+     - added (macro to fill information about objects in optical DB)
+
+   * datacenter/macros/filloptical.C:
+     - added check to avoid filling invalid data
+     - added zd (retrieve ra,dec from table Object and fill zd into 
+       table OpticalData)
+
+
+
+ 2006/10/19 Thomas Bretz
+
+   * mpedestal/MHPedestalCam.[h,cc]:
+     - removed (due to inheritance it belongs to mhcalib)
+
+   * mbase/MArrayD.h, marrayF.h:
+     - added GetSum() member function
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - replaced the AdHoc number of effective integration slices
+       by an average of the correct number, averaged over all
+       possible set of weights. This also gives correct numbers
+       for the lo-gains which were totally wrong before.
+
+   * datacenter/macros/plotdb.C:
+     - updated the bin width of the histograms
+
+   * mbadpixels/MBadPixelsTreat.cc, mcalib/MCalibrateData.cc,
+     mcalib/MCalibrationChargeCalc.cc, mfilter/MFCosmics.cc,
+     mhcalib/MHCalibrationHiLoCam.cc:
+     - added some comments
+
+   * mcalib/MCalibrationHiLoPix.h:
+     - commented out the unused function GetOffsetPerSlice
+
+   * msignal/MArrivalTimeCam.[h,cc]:
+     - removed unused data members
+
+   * mfileio/MReadTree.cc:
+     - changed some output text
+
+   * mfileio/MWriteRootFile.cc:
+     - added a fix to allow paths containing a tilde
+
+   * datacenter/macros/plotoptical.C:
+     - added
+
+   * mhalpha/MHAlpha.[h,cc]:
+     - added the DrawNicePlot feature
+
+
+
+ 2006/10/19 Daniela Dorner
+
+   * datacenter/db/opticaldata.php:
+     - added (website to display data from KVA)
+
+   * datacenter/db/magicdefs.php:
+     - added values for opticaldata.php
+
+   * datacenter/macros/filloptical.C:
+     - added (macro to read *.instr files from KVA and fill the values
+       into the database)
+
+   * datacenter/scripts/copyscript:
+     - adapted search for dates to the existance of the new directory
+       optical
+
+   * datacenter/macros/setupdb.C:
+     - added columns (fRunStop, fPulsePosOffMed, fPulsePosOffDev, 
+       fHiLoGainRationMed, fHiLoGainRatioDev)
+
+
+
+ 2006/10/18 Thomas Bretz
+
+   * mmuon/MHSingleMuon.cc:
+     - removed some debug stuff errornously introduced yesterday
+
+
+
+ 2006/10/18 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - added makedir for lockpath and listpath
+
+   * datacenter/scripts/jobmanager:
+     - removed makedir for lockpath and listpath
+     - bugfix (continue if condor_q gives an error)
+     - reduced number of condor_q calls per loop from 3 to 1 
+     - combined two if-clauses
+     - added comments
+     - moved getstatus to beginning of loop and moved sleep behind 
+       getstatus to avoid unneed waiting and calling of condor_q
+     - replaced -gt by -ge and -lt by -le, to make sure that logging 
+       output makes sense
+
+   * datacenter/scripts/setup:
+     - updated default values for jobmanager
+
+   * datacenter/db/menu.php, datacenter/db/magicdefs.php:
+     - implemented Observation Mode flag
+
+   * datacenter/db/menu.php:
+     - implemented Observation Mode flag for SequInfo2 and RunInfo2
+     - removed ManuallyChanged from SequInfo2 (not needed anymore with 
+       new sequence building algorithm
+     - added fRunStop to the SequInfo menu
+
+   * datacenter/db/culminating.php, datacenter/db/datasetinfo-aio.php, 
+     datacenter/db/datasetinfo.php, datacenter/db/include.php,
+     datacenter/db/index.php, datacenter/db/magicdefs.php, 
+     datacenter/db/querymc.php, datacenter/db/queryseq.php, 
+     datacenter/db/runinfo-aio.php, datacenter/db/runinfo.php,
+     datacenter/db/sequinfo-aio.php, datacenter/db/sequinfo.php,
+     datacenter/db/statusrps.php, datacenter/db/statussbs.php
+     datacenter/db/statussps.php:
+     - bugfix (order by was not working for runs/sequences/datasets
+       when doing group by)
+
+   * datacenter/db/include.php, datacenter/db/magicdefs.php, 
+     datacenter/db/printtable.php:
+     - bugfix (order by was not working on printtable.php)
+
+
+
+ 2006/10/17 Thomas Bretz
+
+   * mdata/MDataPhrase.cc:
+     - updated comments
+     - only add the missing functions to TDataPrimitives when not
+       yet done. Everything else would leak memory
+
+   * mhbase/MH3.[h,cc], mhvstime/MHVsTime.[h,cc]:
+     - exchanged the MDataChain by MDataPhrase
+     - therefore changed the datamember from MDataChain* to MData*
+       (this change is not necessarily backward compatible)
+     - increased class version number by one
+
+   * mraw/MRawRunHeader.h:
+     - added getter for fObservationMode
+
+   * callisto.cc, ganymed.cc, merpp.cc, readdaq.cc, readraw.cc,
+     showplot.cc, sinope.cc, star.cc, rootlogon.C
+     - enabled error redirection
+
+   * mbase/MLog.[h,cc]:
+     - added code to allow redirection of root error handler to 
+       out own error handler
+
+   * mdata/MDataPhrase.cc:
+     - improved output in case of failure
+
+   * manalysis/MFiltercutsCalc.[h,cc], mbase/MContinue.cc,
+     mjoptim/MJOptimize.cc, mjtrain/MJTrainRanForest.cc,
+     mtools/MTFillMatrix.cc:
+     - replaced MFDataChain by MFDataPhrase
+
+   * mfbase/FBaseLinkDef.h, mfbase/Makefile:
+     - added new class MFDataPhrase
+
+   * mfbase/MF.[h,cc]:
+     - replaced all the parsing stuff by the usage of MFDataPhrase
+
+   * mfbase/MFDataPhrase.[h,cc]:
+     - added
+
+   * mhist/MHRate.cc:
+     - removed an obsolete debugging "Y"
+
+   * sinope.cc, manalysis/MMcTriggerLvl2.cc, mastro/MAstroCamera.cc,
+     mastro/MAstroCatalog.cc, mbase/MLog.cc, mcalib/MCalibrationBlindPix.cc,
+     mcalib/MCalibrationChargeCalc.cc, mcalib/MCalibrationChargeCam.cc,
+     mcalib/MCalibrationIntensityChargeCam.cc, mfbase/MFEventSelector2.cc,
+     mhbase/MBinning.cc, mhbase/MH.cc, mhcalib/MHCalibrationHiLoCam.cc,
+     mhflux/MHFalseSource.cc, mhflux/MHThetaSqN.cc, mhist/MHCamera.[h,cc],
+     mimage/MNewImagePar2.cc, mmuon/MHSingleMuon.cc, 
+     mpedestal/MPedCalcFromData.cc
+     - fixed warnings about shadows of parameters
+
+   * datacenter/macros/insertdataset.C, datacenter/macros/insertdate.C,
+     datacenter/macros/insertsequence.C:
+     - updated to use MSQLMagic
+
+   * macros/checkaclic.C:
+     - added (allows to check whether all macros compile)
+
+   * macros/dohtml.C:
+     - added extralgo
+     - added new macros
+
+   * mjobs/MJStar.cc:
+     - removed some obsolete includes
+
+   * macros/optim/optimonoff.C:
+     - updated start values to our current best values
+     - updated scale region
+
+   * macros/tutorials/threshold.C:
+     - updated start values to our current best values
+
+
+
+ 2006/10/17 Markus Meyer
+
+   * mtools/MRolke.[h,cc]:
+     - added: a modification of TRolke from root_v5.12.00b. There is
+       now a new function, called LogFactorial() which enables to
+       calculate confidence intervals even for a large number of
+       events (larger than 170). 
+
+   * mtools/Makefile:
+     - added: MRolke.cc 
+
+   * mtools/ToolsLinkDef.h:
+     - added: MRolke+ 
+
+
+
+ 2006/10/17 Stefan Ruegamer
+
+   * datacenter/scripts/processmcsequences
+     - fixed a bug preventing the script from finding the sequence
+       files, fixed a typo and added the star command to the logfile
+
+
+
+ 2006/10/17 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - bugfix (intgrep returned not only the number)
+
+   * datacenter/scripts/checktransfer:
+     - removed not needed output
+
+   * datacenter/scripts/budb:
+     - added (script making backup of databases)
+
+   * datacenter/tools/sps-bu:
+     - added (script updating SequenceProcessStatus)
+
+   * datacenter/macros/checkfileavail.C:
+     - Form() did not work for sequences with many runs 
+
+
+
+ 2006/10/16 Thomas Bretz
+
+   * mextralgo/MExtralgoDigitalFilter.[h,cc]:
+     - Changed the extraction algorithm such that extraction of signal
+       and time is iterated and should be as consistent as possible
+       at the end of the algorithm.
+     - changed the final offset in the calculation of the arrival time
+       to match as best as it can so far.
+     - Updates to the still preliminary calculation of the weights
+ 
+   * manalysis/MEnergyEstimate.cc, mdata/MDataList.cc,
+     mdata/MDataMember.cc, mhbase/MHMatrix.cc,
+     manalysis/MMultiDimDistCalc.cc, mfit/MTFitLoop.cc:
+     - updated comment to refer to MDataPhrase instead of MDataChain
+
+   * manalysis/MParameterCalc.[h,cc], manalysis/MCompProbCalc.cc,
+     mtools/MChisqEval.cc, mhist/MHCompProb.cc, mdata/MDataArray.cc,
+     mhbase/MFillH.cc, mfileio/MWriteAsciiFile.cc, 
+     mfbase/MFDataChain.cc:
+     - replaced the usage of MDataChain by MDataPhrase
+
+   * mbase/MMath.cc:
+     - small update to SolvePol3 which is more accurate in the number 
+       of different solutions
+
+   * mdata/DataLinkDef.h, mdata/Makefile:
+     - added MDataPhrase
+
+   * mhbase/MH.cc:
+     - further improvement to the calculation of binomial
+       errors, the sale factors were not correctly taken into account
+
+   * mdata/MDataPhrase.[h,cc]:
+     - added
+
+
+
+ 2006/10/15 Thomas Bretz
+
+   * mbase/MEnv.[h,cc]:
+     - implmenetd the possibility to check whether the given resource
+       file eists
+
+   * star.cc, ganymed.c, callisto.cc:
+     - implemented an error if the resource file doesn't exist
+       (returns 0xfe)
+
+
+
+ 2006/10/15
+
+   * RELEASE 0.10.2
+
+
+
+ 2006/10/15 Thomas Bretz
+
+   * mtemp/MVP*:
+     - removed
+
+
+
+ 2006/10/14 Thomas Bretz
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed that in case of wobble sources always the project
+       and/or source name of the first run was assigned instead of
+       the new generaliyed wobble-source/-project name
+
+   * datacenter/scripts/dbchk:
+     - added some more checks
+
+   * datacenter/scripts/sourcefile:
+     - fixed the intgrep (didn't work with the colors in filldotraw)
+
+   * mastro/AstroIncl.h:
+     - added TArrayD
+
+   * mastro/MAstro.[h,cc]:
+     - added some functions around the sun and the moon
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - check the epoch in Xephem catalog as numbe rnot as string
+     - added GetVisibilityCurve member function
+     - overwrote FindObject
+     - added MarkObject
+
+   * mastro/MObservatory.[h,cc]:
+     - added Tuorla observatory
+     - added member function to calculate sunrise and -set
+
+   * mbase/MTime.h:
+     - added a function to return Julian Date
+
+   * mhflux/MHCollectionArea.cc:
+     - some update in comments
+
+   * mhist/MHCamera.h:
+     - fixed a warning with root 5.13/04
+
+   * mmc/MMcRunHeader.cxx:
+     - initalize fImpactMax to -1
+
+   * macros/starvisday.C, macros/starvisyear.C:
+     - added
+
+
+
+ 2006/10/13 Daniela Dorner
+
+   * datacenter/scripts/findnotseqruns:
+     - added (script to find not sequenced runs)
+
+   * datacenter/scripts/findnewstars:
+     - added (script to find sequences where star has been done)
+
+   * datacenter/tools/resetdataset:
+     - added (script to reset dataset)
+
+
+
+ 2006/10/13 Thomas Bretz
+
+   * datacenter/macros/filldotraw.C:
+     - allow inserting missing runs
+
+   * msql/MSQLMagic.[h,cc]:
+     - added functions to request the value not only key and name
+
+
+
+ 2006/10/12 Daniela Dorner
+
+   * datacenter/tools:
+     - added (directory for tools not used regulary)
+
+   * datacenter/tools/findnotanymoresequencedruns, 
+     datacenter/tools/comparesequences:
+     - added (scripts for sequence building tests)
+
+   * datacenter/scripts/dunotseqruns:
+     - added (script to check disk usage of not sequenced runs)
+
+   * datacenter/scripts/checklogs:
+     - added comment
+
+
+
+ 2006/10/11
+
+   * RELEASE 0.10.1
+
+
+
+ 2006/10/11 Thomas Bretz
+
+   * mhbase/MH.[h,cc]:
+     - added a function to calculate binomial errors including weights
+       (this was added in root 5.13/04, but necessary for older versions)
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - added Sumw2() to the constructor so that the weights array gets
+       correctly initialize
+     - replaced the calculation of the binomial errors by the
+       corresponding root-function and the new MH function
+     - made sure that in all histogram operations the errors are
+       properly propagated
+     - let ReInit determine fMcRadius from MMcRunHeader
+     - execute check for corsika version even if the HistAll is extern
+
+   * mhflux/MHEnergyEst.cc, mhflux/MHThreshold.cc
+     - fixed the order in the constructor such that the Sumw2() does
+       correctly initialize the weights array
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - a minor code reordering
+
+   * mjobs/MJSpectrum.cc:
+     - made sure that the histogram with the corsika spectrum has
+       the errors initialized and thus takes the weights correctly
+       into account
+     - corresponding to this changed some draw option to get the
+       same plots (hist) as before
+     - added a lot of comments to the code
+     - when the zenith angle weights are applied to the MC distribution
+       make sure that also the errors are correctly treated.
+
+   * mcalib/MCalibrationTestCalc.cc:
+     - enrolled some Form-statement
+
+   * mhflux/MAlphaFitter.cc:
+     - fixed a typo in a comment
+
+   * mbase/MLogHtml.cc:
+     - fixed a bug which caused the output to be totally corrupted
+
+   * datacenter/macros/writesequencefile.C:
+     - implemented again that the 1000 pedestal events are taken which
+       are next to the calibration run
+
+
+
+ 2006/10/10 Thomas Bretz
+
+   * datacenter/macros/writesequencefile.C:
+     - fixed a possible crash in GetName
+     - improved output in case of failure
+
+
+
+ 2006/10/10 Daniela Dorner
+
+   * datacenter/db/menu.php:
+     - included 'only offdata' and 'incl. offdata' checkbox for 
+       sequenceinfo
+
+   * datacenter/db/runinfo.php, datacenter/db/runinfo-aio.php:
+     - changed name of column for case of group-by
+
+   * datacenter/db/index.html:
+     - added remark
+
+   * datacenter/db/sources.php:
+     - fixed bug (test-sources checkbox didn't work properly)
+
+
+
+ 2006/10/10
+
+   * RELEASE 0.10
+
+
+
+ 2006/10/10 Thomas Bretz
+
+   * mjobs/MJCalibration.cc:
+     - fixed the scaling and layout in the 'Defect' tab
+
+
+
+ 2006/10/09 Daniela Dorner
+
+   * scripts/processsequence:
+     - removed exit
+     - removed unneccessary lines
+
+
+
+ 2006/10/09 Thomas Bretz
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - fixed a bug which caused the spectra to be normalized at 1GeV
+       by default instead of the integral
+     - allow the MC slope to be -1. With the current code this should
+       not be a problem anymore.
+     - improved some comments
+
+   * mbase/MMath.cc, mbase/MAGIC.cc:
+     - removed the NamespaceImp macro again, it gives problems when
+       compiling which are not yet understood
+
+   * Makefile:
+     - fixed a type in rmcondor
+
+   * mars-config:
+     - changed "--mars-ver" to "--version" as in root-config
+
+   * sponde_onoff.rc:
+     - added a reference to MMcSpectrumWeight::ReadEnv
+
+   * .rootrc:
+     - added a line for THtml (which is for the next root release)
+
+
+
+ 2006/10/08 Thomas Bretz
+
+   * mhflux/MHalpha.cc:
+     - fixed a problem (maybe with the new root version) that on-
+       and off-data was shown in black and could not be distinguished
+       anymore
+
+   * ganymed.rc, ganymed:onoff.rc, ganymed_wobble.rc:
+     - some further update
+
+   * mcalib/MCalibrationHiLoCam.[h,cc]:
+     - broke down a long Form() chain into single Form()'s
+
+   * mhcalib/MHPedestalPix.cc, mhcalib/MHGausEvents.[h,cc], 
+     mhcalib/MHCalibrationChargeBlindPix.cc, 
+     mhcalib/MHCalibrationPix.cc:
+     - replaced IsNaN by !IsFinite (which includes IsNaN)
+     - changed some protected data members of the base class
+       into private data members
+
+   * mhflux/MAlphaFitter.cc, mhflux/MHEnergyEst.cc, mhist/MHCamera.cc,
+     mhist/MHHadronness.cc, mhvstime/MHPixVsTime.cc, 
+     mhvstime/MHSectorVsTime.cc, mranforest/MRanForest.cc:
+     - replaced IsNaN by !IsFinite (which includes IsNaN)
+
+   * mhcalib/MHGausEvents.cc:
+     - removed a memory leak by removing the functions creating the
+       axes
+
+   * mcalib/MMcCalibrationCalc.cc, mmc/MMcConfigRunHeader.h:
+     - return and use a const-reference to the TArrayF's
+
+   * mimage/MHHillas.cc:
+     - fixed a problem which could cause the change in the DrawOption
+       of the Center-hist to raise a seg-fault.
+
+   * mbase/MMath.cc, mbase/MAGIC.cc:
+     - added the NamespaceImp macro to allow creation of the documentation
+       by THtml (according to the source code of TMath)
+
+
+
+ 2006/10/07 Thomas Bretz
+
+   * Makefile.conf.general:
+     - removed ROOTVER definition ROOT_RELEASE can be used instead
+
+   * callisto.cc:
+     - exchanged some checks to get a more reasonable output
+
+   * callisto.rc, callisto_Dec04Jan05.rc:
+     - removed some obsolete resources for simplicity
+
+   * callisto.cc, ganymed.cc, mars.cc, merpp.cc, readdaq.cc, readreaw.cc,
+     showlog.cc, showplot.cc, sinope.cc, star.cc
+     - added the new root version check
+     - replaced ROOTVER by ROOT_RELEASE
+
+   * sinope.cc:
+     - adapted Usage() to fit the other executables
+
+   * mbase/MAGIC.h:
+     - added new namespace MARS with a new function CheckRootVer
+
+   * mbase/MAGIC.cc:
+     - added 
+
+   * mbase/MEvtLoop.cc, mbase/MStatusDisplay.cc:
+     - replaced ROOTVER by ROOT_RELEASE
+
+   * mbase/Makefile:
+     - added new MAGIC.cc
+
+   * mbase/BaseLinkDef.h:
+     - added namespace MAGIC.cc
+
+   * mhcalib/MHGausEvent.cc:
+     - disallow also non finite results
+
+   * Makefile:
+     - added new exectuable mars.config
+
+   * mars-config.cc:
+     - added
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - updates some output
+     - added RelTimeResolutionLimit to ReadEnv
+
+
+
+ 2006/10/07 Daniela Dorner, Thomas Bretz
+
+   * datacenter/scripts/runganymed:
+     - added sequencepath to ganymed command
+
+   * datacenter/macros/buildsequenceentries.C:
+     - restricted regular expression for wobble sources
+     - fixed bug (larger sequences were misinterpreted as identical 
+       sequences)
+
+   * resources/sequences.rc:
+     - added 2 regions were interleaved pedestal run are allowed
+
+
+
+ 2006/10/06 Daniela Dorner
+
+   * scripts/processsequence:
+     - implemented command line options
+     - improved logging
+     - implemented checks
+     - removed sourcefile
+
+   * datacenter/scripts/makecallistolinks:
+     - table was missing
+
+   * datacenter/scripts/rmlocks:
+     - reduced output
+
+   * datacenter/db/menu.php:
+     - implemented 1000 and 2000 for number of results pulldown
+
+
+
+ 2006/10/05 Stefan Ruegamer
+
+   * mraw/MRawRunHeaders.cc:
+     - updated swap assignments for the swapped pixels 54-55
+       (runnumber > 88669)
+
+
+
+ 2006/10/04 Stefan Ruegamer
+
+   * mraw/MRawRunHeaders.cc:
+     - updated swap assignments for the swapped pixels 161-162,
+       210-263 (runnumber <= 101789) and 54-55 (runnumber <= 102511)
+
+
+
+
+ 2006/10/02 Thomas Bretz
+
+   * callisto.rc, callisto_Dec04Jan05.rc:
+     - fixed some names of some resources (all commented out anyhow)
+
+   * mdata/MDataElement.cc:
+     - if the column given is the constructor is negative the 
+       name of the matrix is supposed to contain also the column index
+
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]:
+     - improved the output in case of under- and overflows
+     - added const-qualifier to CheckOverflow
+
+   * mreport/MReport.cc:
+     - allow the milliseconds to be 1000 (this is a bug which affects
+       the camera reports in very rare cases)
+     - improved output
+
+   * mjobs/MJCalibration.cc:
+     - added two plots the extracted signal and the extracted arrival
+     time
+
+
+
+ 2006/10/01 Thomas Bretz
+
+   * mextralgo/MExtralgoSpline.[h,cc]:
+     - changed from the old fashined search algorithm to a completely
+       analytical approach. Still with a lot of comments containing
+       the old code
+
+   * mbase/MMath.[h,cc]:
+     - added new function to solve polynomial equations up to the
+       thirs order.
+
+
+
+ 2006/09/29 Thomas Bretz
+
+   * ganymed_wobble.rc:
+     - use the same spark cuts as in ganymed_onoff.rc. Seems to be
+       unintentional that they were different.
+
+   * macros/train/trainenergy.C:
+     - fixed an oddity because there was artificial path
+     - added some comments
+
+
+
+ 2006/09/28 Stefan Ruegamer
+
+   * mraw/MRawRunHeaders.cc:
+     - added swap assignments for the swapped pixels 119-120, 161-162,
+       210-263 and 54-55 in the corresponding run range
+
+
+
+ 2006/09/28 Daniela Dorner
+
+   * datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/runcallisto, datacenter/scripts/runganymed:
+     - improved processlog
+
+   * datacenter/scripts/sourcefile:
+     - improved processlog
+     - exchange function finish by code in fuction makedir
+
+   * datacenter/scripts/setup, datacenter/scripts/linkmc, 
+     datacenter/scripts/mcsequences, 
+     datacenter/scripts/processmcsequences:
+     - moved mcpath to setup
+     - updated mcpath
+
+   * datacenter/scripts/checktransfer:
+     - also check transfer of subsystem files
+     - added comments
+
+
+
+ 2006/09/28 Thomas Bretz
+
+   * mfilter/MFMagicCuts.[h,cc]:
+     - implemented a hadronness cut as an option
+     - updated class reference
+     - fixed abug introduced 14.7.2005 which caused the M3Long of the
+       anti source to be not properly evaluated in case of optimization.
+
+   * ganymed_onoff.rc, ganymed_wobble.rc:
+     - updated with comments how to use random forest
+
+   * datacenter/macros/buildsequenceentries.C:
+     - updated with a completely redesigned algorithm and completly
+       redisigned code
+
+   * datacenter/macros/writesequencefile.C:
+     - the new simplified version doesn't take the number of pedestal 
+       events anymore into account.
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed the tab with the calibrated arrival times. It never
+       gave any useful information
+
+   * mgeom/Makefile, mgeom/GeomLinkDef.h:
+     - took out all currently unused cameras from compilation
+
+   * mjobs/MJCut.cc:
+     - updated the confusing error message printed to the log-stream
+       in case of a failure of FillSrcPosCam
+
+   * callisto.cc:
+     - fixed small bug in PrintFiles
+
+   * datacenter/macros/plotdb.C:
+     - updated comments
+     - fixed a problem with empty TGraphs
+     - added new tabs for Hi-/Lo-Gain offsets and calibration
+     - incrased the range for the PSF
+     - reordered the tabs
+     - chnaged the binning for the relative effective on time
+     - removed the tab with the number of muons after cuts
+     - allow a dataset as last argument
+
+   * mraw/MRawRunHeader.h:
+     - added new member function IsValid
+
+   * mfileio/MReadMarsFile.cc:
+     - improved output in case something is wrong with the run-header
+
+
+
+ 2006/09/27 Daniela Dorner
+
+   * datacenter/scripts/setup, datacenter/scripts/sourcefile:
+     - fixed sourcing of setup
+
+   * datacenter/db/culminating.php, datacenter/db/datacheck.php,
+     datacenter/db/datasetinfo-aio.php, datacenter/db/datasetinfo.php,
+     datacenter/db/dbstatus.php, datacenter/db/include.php,
+     datacenter/db/index.php, datacenter/db/printtable.php,
+     datacenter/db/querycal.php, datacenter/db/querymc.php,
+     datacenter/db/queryrbk.php, datacenter/db/queryseq.php,
+     datacenter/db/querystar.php, datacenter/db/runinfo-aio.php,
+     datacenter/db/runinfo.php, datacenter/db/statusrps.php,
+     datacenter/db/statussbs.php, datacenter/db/statussps.php: 
+     - fixed calling of PrintMagicTable
+
+   * datacenter/macros/checkfileavail.C:
+     - fixed bug
+
+
+
+ 2006/09/26 Thomas Bretz
+
+   * mbase/MMath.h:
+     - added new function ModF
+
+   * mhist/MHRate.cc, mhist/MHWeather.cc, mhvstime/MHPixVsTime.cc,
+     mhvstime/MHSectorVsTime.cc, mhvstime/MHVsTime.cc,
+     mpointing/MHPointing.cc:
+     - made the update of the axis ranges work again
+
+
+
+ 2006/09/26 Daniela Dorner
+
+   * datacenter/scripts/zipscript:
+     - remove write permission after zip
+
+
+
+ 2006/09/25 Daniela Dorner
+
+   * datacenter/scripts/mcsequences:
+     - fixed overwriting of sequencefiles
+
+   * datacenter/scripts/linkmc:
+     - fixed typo
+
+
+
+ 2006/09/20 Daniela Dorner
+
+   * datacenter/scripts/zipscript, datacenter/scripts/checktransfer:
+     - added
+
+
+
+ 2006/09/19 Daniela Dorner
+
+   * datacenter/db/datasetinfo-aio.php, datacenter/db/runinfo-aio.php, 
+     datacenter/db/sequinfo-aio.php, datacenter/db/menu.php,
+     datacenter/db/menu.js:
+     - status menu was displayed wrongly after query 
+
+
+
+ 2006/08/30 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - removed setzero
+     - restructured
+
+   * datacenter/scripts/setup:
+     - fixed bug
+
+   * datacenter/scripts/jobmanager:
+     - replaced setzero
+     - removed nail 
+     - improved logging
+
+   * datacenter/macros/filldotrun.C:
+     - enhanced return-values 
+
+   * datacenter/macros/insertdataset.C:
+     - fixed return-values in case of error
+
+   * datacenter/macros/insertdataset.C, 
+     datacenter/scripts/insertdatasets:
+     - implemented return value for 'exists already in db'
+
+
+
+ 2006/08/29 Thomas Bretz
+
+   * resources/sequences.rc:
+     - updated
+
+
+
+ 2006/08/29 Daniela Dorner
+
+   * datacenter/scripts/buildsequenceentries:
+     - fixed logpath
+
+   * datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed,
+     datacenter/scripts/fillstar:
+     - changed logpath
+
+   * datacenter/scripts/insertdatasets:
+     - improved logging
+
+   * datacenter/scripts/filesondisk:
+     - reduced output
+
+   * datacenter/scripts/checklogs:
+     - added (mails WARNs and ERRORs to $erradrs)
+
+   * datacenter/scripts/rmlocks:
+     - improved logging
+     - took removing out (reason: 12 hour limitation of condor is not 
+       working; instead mail)
+
+   * datacenter/scripts/sourcefile:
+     - improved logging in setstatus
+     - implemented alias intgrep
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/copyscript, 
+     datacenter/scripts/dodatacheck, datacenter/scripts/doexclusions,
+     datacenter/scripts/doqualityplots, datacenter/scripts/filesondisk,
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed,
+     datacenter/scripts/fillstar, datacenter/scripts/insertdatasets,
+     datacenter/scripts/insertsequences, 
+     datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/writesequencefiles:
+     - implemented usage of alias intgrep
+
+
+
+ 2006/08/28 Thomas Bretz
+
+   * msql/MSQLMagic.cc:
+     - replaced DELETE by DELETE FROM
+
+   * mbase/MTime.h:
+     - if name is given in the constructor it is tried to use
+       it as SqlDateTime.
+
+
+
+ 2006/08/25 Daniela Hoehne
+
+   * datacenter/scripts/setup: 
+     - implemented new path for runlogs
+
+   * datacenter/scripts/buildsequenceentries, datacenter/scripts/
+     checkfilesforsequenceavail, datacenter/scripts/checkstardone,  
+     datacenter/scripts/copyscript, datacenter/scripts/correcttime,
+     datacenter/scripts/dodatacheck, datacenter/scripts/doexclusions,
+     datacenter/scripts/doqualityplots, datacenter/scripts/dowebplots,
+     datacenter/scripts/filesondisk, datacenter/scripts/fillcallisto,
+     datacenter/scripts/fillganymed, datacenter/scripts/fillstar,
+     datacenter/scripts/insertdatasets, datacenter/scripts/insertsequences,
+     datacenter/scripts/linkmc, datacenter/scripts/makecallistolinks,
+     datacenter/scripts/runcallisto, datacenter/scripts/runganymed,
+     datacenter/scripts/runstar, datacenter/scripts/processmcsequences,
+     datacenter/scripts/mcsequences:
+     - improved logging (changed runlogpath)
+
+   * datacenter/scripts/checkstardone, datacenter/scripts/insertdatasets,
+     datacenter/scripts/insertsequences:
+     - changed logging outpath
+
+
+
+ 2006/08/25 Daniela Dorner
+
+   * datacenter/scripts/jobmanager, datacenter/scripts/sourcefile, 
+     datacenter/scripts/scriptlauncher: 
+     - improved logging
+     - implemented usage of printprocesslog
+
+   * datacenter/scripts/jobmanager: 
+     - improved usage of resources
+
+   * datacenter/scripts/scriptlauncher: 
+     - improved errorhandling
+
+   * datacenter/scripts/sourcefile: 
+     - implemented function and paths for processlog
+
+   * datacenter/scripts/copyscript, datacenter/scripts/insertdatasets, 
+     datacenter/scripts/doqualityplots, datacenter/scripts/dowebplots, 
+     datacenter/scripts/linkmc, datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/mcsequences, 
+     datacenter/scripts/insertsequences,
+     datacenter/scripts/processmcsequences: 
+     - implemented usage of finish
+     - improved logging
+
+   * datacenter/scripts/doexclusions: 
+     - implemented check=1 (was still missing)
+
+   * datacenter/scripts/correcttime, 
+     datacenter/scripts/insertsequences,
+     datacenter/scripts/makecallistolinks: 
+     - improved logging
+     - fixed bugs
+
+   * datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/filesondisk, datacenter/scripts/runcallisto: 
+     - improved logging
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/copyscript, 
+     datacenter/scripts/correcttime, datacenter/scripts/dodatacheck, 
+     datacenter/scripts/doexclusions, datacenter/scripts/doqualityplots, 
+     datacenter/scripts/insertdatasets, datacenter/scripts/dowebplots, 
+     datacenter/scripts/filesondisk, datacenter/scripts/fillcallisto, 
+     datacenter/scripts/fillstar, datacenter/scripts/fillganymed, 
+     datacenter/scripts/insertsequences, datacenter/scripts/jobmanager, 
+     datacenter/scripts/linkmc, datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/mcsequences, datacenter/scripts/movingrawfiles, 
+     datacenter/scripts/rmlock, datacenter/scripts/processmcsequences, 
+     datacenter/scripts/runstar, datacenter/scripts/runcallisto, 
+     datacenter/scripts/runganymed, datacenter/scripts/webupdate-star,
+     datacenter/scripts/webupdate-callisto, 
+     datacenter/scripts/webupdate-sinope, datacenter/scripts/sourcefile, 
+     datacenter/scripts/webupdate-ganymed,
+     datacenter/scripts/writesequencefiles: 
+     - implemented usage of printprocesslog
+     - fixed runlogpath
+
+   * datacenter/scripts/webupdate-callisto, 
+     datacenter/scripts/webupdate-ganymed, 
+     datacenter/scripts/webupdate-sinope, 
+     datacenter/scripts/webupdate-star: 
+     - added logging
+
+
+
+ 2006/08/25 Thomas Bretz
+
+   * msignal/MExtractTimeAndChargeSpline.h:
+     - changed fgLoGainOffset from 1.39 to 1.3 according to an extensive
+       test in the test-database
+
+   * resources/sequences.rc:
+     - resource file how to build sequences... added.
+
+   * msql/MSQLMagic.[h,cc]:
+     - added
+
+   * msql/MSQLServer.[h,cc]:
+     - added copy constructor
+     - allow fServ to be NULL (added sanity checks)
+     - Implemented Exec-command
+
+   * msql/Makefile, msql/SqlLinkDef.h:
+     - added MSQLMagic
+
+   * mbase/MLog.[h,cc]:
+     - added new member function Intro()
+
+   * mextralgo, mextralgo/Makefile, mextralgo/ExtralgoLinkDef.h,
+     mextralgo/MExtralgoDigitalFilter.[h,cc], 
+     mextralgo/MExtralgoSpline.[h,cc]:.
+     - added
+
+
+
+ 2006/08/24 Thomas Bretz
+
+   * manalysis/Makfile, manalysis/AnalysisLinkDef.h:
+     - took MCompProbCalc out
+
+   * mhist/Makfile, mhist/HistLinkDef.h:
+     - took MHCompProb out
+
+
+
+ 2006/08/24 Daniela Dorner
+
+   * datacenter/scripts/sourcefile: 
+     - implemented new functions to get information from the database
+     - fixed bug in naming of variable
+
+   * datacenter/scripts/jobmanager: 
+     - implemented usage of getstatus
+     - fixed bug in naming of variable
+
+   * datacenter/scripts/runcallisto, datacenter/scripts/runstar, 
+     datacenter/scripts/runganymed, datacenter/scripts/dodatacheck: 
+     - implemented usage of gettodo
+     - removed for-loop to process several primaries
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/correcttime, 
+     datacenter/scripts/doexclusions, datacenter/scripts/fillcallisto, 
+     datacenter/scripts/fillganymed, datacenter/scripts/fillstar, 
+     datacenter/scripts/writesequencefiles: 
+     - implemented usage of new getdolist function
+
+
+
+ 2006/08/23 Thomas Bretz
+
+   * mtools/MCalendar.cc:
+     - simplified DrawTTF as suggested in the root bug tracker
+
+
+
+ 2006/08/22 Daniela Dorner
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/copyscript, 
+     datacenter/scripts/correcttime, datacenter/scripts/dodatacheck, 
+     datacenter/scripts/doexclusions, datacenter/scripts/doqualityplots, 
+     datacenter/scripts/dowebplots, datacenter/scripts/filesondisk, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed, 
+     datacenter/scripts/fillstar, datacenter/scripts/insertdatasets, 
+     datacenter/scripts/insertsequences, datacenter/scripts/linkmc, 
+     datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/mcsequences, datacenter/scripts/movingrawfiles, 
+     datacenter/scripts/processmcsequences, datacenter/scripts/rmlocks, 
+     datacenter/scripts/runcallisto, datacenter/scripts/runganymed, 
+     datacenter/scripts/runstar, datacenter/scripts/writesequencefiles, 
+     datacenter/scripts/sourcefile: 
+     - implemented possibility to run several tests by one user 
+       (relative path for Mars version)
+
+   * datacenter/scripts/sourcefile: 
+     - included webpath
+     - added comments
+     - added variables and functions for jobmanager
+     - removed changing variables 
+     - added addresses
+     - implemented functions to get todolist via shell
+     - improved logging
+     - replaced setstatus, implemented new function not calling root
+       but directly using shell and mysql to speed up the setting of 
+       the status
+
+   * datacenter/scripts/jobmanager: 
+     - added (script to controll the amount of callisto, star, ganymed
+       and datacheck running)
+     - reduced logging output
+     - implemented gettodo
+     - implemented possibility to run several tests by one user 
+       (relative path for Mars version)
+     - moved setup from jobsourcefile to sourcefile
+     - added locking for gettodo
+     - make sure that lists- and lock-directory are available
+
+   * datacenter/scripts/setup: 
+     - added (file to store setup variables, which might be changed)
+     - new root version
+
+   * datacenter/scripts/copyscript: 
+     - removed addresses
+     - fixed typo
+
+   * datacenter/scripts/run.condor: 
+     - added (file used to submit scripts to condor, used by jobmanager
+       and script launcher)
+
+   * steps.rc: 
+     - fixed typo
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/correcttime, 
+     datacenter/scripts/dodatacheck, datacenter/scripts/doexclusions, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed, 
+     datacenter/scripts/fillstar, datacenter/scripts/runcallisto, 
+     datacenter/scripts/runganymed, datacenter/scripts/runstar, 
+     datacenter/scripts/writesequencefiles:
+     - implemented usage of gettodo instead of getdolist (faster)
+
+   * datacenter/scripts/dodatacheck, datacenter/scripts/runcallisto,
+     datacenter/scripts/runganymed, datacenter/scripts/runstar: 
+     - improved logging and comments
+     - adapted find-to-do-file-algorithm 
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/correcttime,
+     datacenter/scripts/doexclusions, datacenter/scripts/fillcallisto,
+     datacenter/scripts/fillganymed, datacenter/scripts/fillstar,
+     datacenter/scripts/makecallistolinks,
+     datacenter/scripts/writesequencefiles:
+     - improved logging and comments
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/correcttime, 
+     datacenter/scripts/dodatacheck, datacenter/scripts/doexclusions, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed, 
+     datacenter/scripts/fillstar, datacenter/scripts/runcallisto, 
+     datacenter/scripts/runganymed, datacenter/scripts/runstar,
+     datacenter/scripts/writesequencefiles: 
+     - remove todofile when it has been read 
+
+   * datacenter/scripts/scriptlauncher: 
+     - added (script to start submit other scripts to condor)
+     - make sure that lists- and lock-directory are available
+
+   * datacenter/scripts/webupdate-callisto, 
+     datacenter/scripts/webupdate-star, 
+     datacenter/scripts/webupdate-sinope,
+     datacenter/scripts/webupdate-ganymed: 
+     - added 
+
+
+
+ 2006/08/22 Thomas Bretz
+
+   * Makefile, Makefile.rules:
+     - let condor wait until all jobs are finished and then
+       link everything
+
+   * mbadpixels/MBadPixelsCam.[h,cc]:
+     - added a simple function GetNumUnsuitable which can be used
+       as a rule eg. in a filter.
+
+
+
+ 2006/08/21 Thomas Bretz
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - there are three cases in which the digital filter algorithm
+       cannot run to the end (eg. division by zero). For this cases
+       more correct return values are set.
+     - made sure that the fHiGainFirst is not added a second time
+       through fTimeShiftHiGain
+     - made sure that the case is handled correctly in which the sliding
+       DF either couldn't slide at all or the maximum is below zero
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]:
+     - made sure that dsum is always set correctly
+
+   * msignal/Makefile, msignal/SignalLinkDef.h:
+     - took out the following classes from make:
+       + MExtractFixedWindow
+       + MExtractSlidingWindow
+       + MExtractFixedWindowPeakSearch
+       + MExtractFixedWindowSpline
+       + MExtractAmplitudeSpline
+       + MExtrcatTimeSpline
+       + MExtractTimeFastSpline
+       + MExtractTimeHighestIntegral
+       + MExtractTimeAndChargeSlidingWindow
+       + MExtractTimeAndChargeDigitalFilterPeakSearch
+
+   * mjobs/MJCalibration.cc, mjobs/MJCalibTest.cc:
+     - replaced default extractor by our default spline extractor
+
+   * mbase/MMath.[h,cc]:
+     - added the possibility in GetMedianDev to retrieve the
+       intermediate median
+     - updated comments
+
+   * mhflux/MHEnergyEst.cc:
+     - replaces old Form() by MString::Format
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - mark an extracted signal as invalid if more than 6 logain
+       slices have saturated
+
+
+
+ 2006/08/20 Thomas Bretz
+
+   * mtools/MCalendar.cc:
+     - fixed the font-size issue (which I don't understand at all -
+       bug report submitted)
+
+   * macros/tutorials/calendar.C:
+     - changed the font name to a font supported by root
+
+
+
+ 2006/08/19 Thomas Bretz
+
+   * mastro/MAstroCatalog.cc:
+     - replaced all ifstream by MZlib to allow reading gzip
+       compressed catalogs
+
+   * mbase/MString.[h,cc]:
+     - changed function Form() 
+     - renamed old function Form() to Format()
+
+   * mastro/MAstroCatalog.cc, mbase/MParContainer.cc,
+     mbase/MStatusDisplay.cc, mbase/MTask.cc, mpointing/MHSrcPosCam.cc
+     mpointing/MPointingPos.cc, mbase/MEvtLoop.cc:
+     - replaced MString::Form by new function name MString::Format
+
+   * macros/tutorials/calendar.C, macros/tutorials/calendar.rc,
+     macros/tutorials/holidays.rc:
+     - added
+
+   * mtools/MCalendar.[h,cc]:
+     - added some dead code
+     - changed the default a little bit
+     - added fOrientation to allow changing the orientation
+     - added code to paint a clock for the change from summer- to
+       winter-time and vice versa
+     - removed the direct dependance on the word "Easter" to
+       display the easter holidays
+     - added the possibility to restrict the display of some contents
+       to only some week days (eg to display "KW35" only on mondays)
+     - some updated to drawing the image
+     - improved the ResetLayout and SetDefaultLayout if called from
+       the context menu
+
+
+
+ 2006/08/18 Thomas Bretz
+
+   * mcalib/MCalibrateData.cc, mhcalib/MHCalibrationChargeCam.cc,
+     mhcalib/MHCalibrationHiLoCam.cc:
+     - replaced obsolste GetNumHiGainSaturated()>0 by IsHiGainSaturated()
+
+
+
+ 2006/08/17 Thomas Bretz
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - added a missing flush
+
+   * msignal/MExtractor.cc:
+     - small update to output
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - mark the lo-gains only as valid if they are really extracted
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - in hi-gain extraction fmax was initialized with -9999, but after
+       the loop a invalid value of fmax<0 was not checked. Changed
+       initialization to 0
+
+
+
+ 2006/08/16 Thomas Bretz
+
+   * Makefile.conf.general:
+     - fixed usage of substitutions
+
+   * mmc/MMcConfigRunHeader.[h,cc]:
+     - added fParaboloidFocal
+     - increased class version by 1
+     - updated comments
+
+   * mmc/MMcEvt.[hxx,cxx]:
+     - added fEventReuse
+     - increased class version by 1
+     - updates to comments
+
+   * mmc/MMcEvtBasic.h:
+     - replaced private by protected
+
+   * mmc/MMcFadcHeader.hxx:
+     - updates to comments
+     - update to global ifdef
+
+   * mmc/MMcRunHeader.[hxx,cxx]:
+     - added fRandomPointingConeSemiAngle
+     - increased class version by 1
+     - upadted comments
+     - removed empty destructor
+
+   * mmc/MMcTrig.hxx:
+     - updated preprocessor directives
+
+   * mmc/MMcTrigHeader.[hxx,cxx]:
+     - updated comments
+     - removed empty destructor
+     - updated preprocessor directives
+
+   * mmc/MTriggerDefine.h, mmc/Mdefine.h:
+     - updated preprocessor directives
+
+   * manalysis/MMcCalibrationUpdate.cc, 
+     mhcalib/MHCalibrationRelTimeCam.cc:
+     - replaced IsLoGainUsed by IsHiGainSaturated
+
+   * mcalib/MCalibrateData.cc:
+     - changed the algorithm which takes either the hi- or the lo-gain
+       such that it gives more reliable results in case of saturation
+       and/or problems with the extraction and if no reliable
+       result is possible the pixel is set unsuitable
+
+   * mcalib/MCalibrateRelTimes.cc:
+     - removed the usage of MSignalPix::SetLoGainUsed
+     - set the pixel to unsuitable if the arrival time could not
+       be extracted
+
+   * mfilter/MFCosmics.cc, mhcalib/MHCalibrationChargeCam.cc:
+     - replaced GetNumHiGainSaturated()>0 by IsHiGainSaturated()
+
+   * mhist/MHCamera.cc: 
+     - removed obsolete MMath::GaussProb from GetMedianDev
+
+   * msignal/MArrivalTimeCam.cc:
+     - replaced IsValid by IsArrivalTimeValid
+     - replaces Is[Hi,Lo]GainValid by 
+       Is[Hi,Lo]GainValid && !Is[Hi,Lo]GainSaturated in
+       GetPixelContent
+     - added a check for saturation in case of getting the delay
+     - do not restrict the range of the returned delays anymore
+
+   * msignal/MArrivalTimePix.[h,cc]:
+     - improved GetArrivalTime to take the hi-gain saturation
+       better into account
+     - added a new function IsArrivalTimeValid
+     - removed obsolete function IsValid and IsLoGainUsed
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - added a check to not set fMaxBinContent in case the extraction
+       would happen in the first or last slice similar to the
+       digital filter. This became necessary because otherwise the
+       spline extractor sometimes extracts nonsens values
+
+   * msignal/MExtractedSignalCam.cc:
+     - replaced IsValid by more accurate functions
+     - take saturation in GetPixelContent into account
+
+   * msignal/MExtractedSignalPix.[h,cc]:
+     - removed obsolete function IsValid and IsLoGainUsed
+     - added functions Is[Hi,Lo]GainSaturated
+
+   * msignal/MSignalCam.cc:
+     - removed cases 10 and 11 in GetPixelContent
+   
+   * msignal/MSignalPix.[h,cc]:
+     - removed obsolete LoGainUsed references
+
+
+
+ 2006/08/15 Daniela Dorner
+
+   * datacenter/macros/filldotrun.C:
+     - implemented new arehucas version
+
+   * datacenter/db/culminating.php, datacenter/db/datacheck.php, 
+     datacenter/db/datasetinfo.php, datacenter/db/dbstatus.php, 
+     datacenter/db/index.php, datacenter/db/printtable.php, 
+     datacenter/db/querycal.php, datacenter/db/queryrbk.php, 
+     datacenter/db/queryseq.php, datacenter/db/querystar.php, 
+     datacenter/db/runinfo.php, datacenter/db/sequence.php, 
+     datacenter/db/sequinfo.php, datacenter/db/statusrps.php, 
+     datacenter/db/statussbs.php, datacenter/db/statussps.php: 
+     - moved some code to functions (mainly menu)
+
+   * datacenter/db/findoffdata.php:
+     - moved some code to functions (mainly menu)
+     - implemented zd-range fields
+     - improved limits functionality
+     - added some limit fields
+     - added new field for limits
+
+   * datacenter/db/include.php:
+     - implemented function to print or not print submitted query 
+       (PrintSubmittedQuery(..))
+     - removed not needed argument of function RemoveSortBy()
+     - implemented new algorithms for enhanced colour coding for limits 
+       in PrintMagicTable()
+     - sort by first desc
+
+   * datacenter/db/index-header.html:
+     - shortened menu (removed old websites)
+     - fixed link
+
+   * datacenter/db/index.html:
+     - added new websites
+     - added link to error coding
+     - fixed link
+
+   * datacenter/db/magicdefs.php:
+     - changed limits arrays for enhanced algorithms 
+     - added variables for starguider, new limit fields, zd range
+
+   * datacenter/db/sources.php:
+     - fixed bug (display of test sources)
+     - moved some code to functions (mainly menu)
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php, 
+     datacenter/db/datasetinfo-aio.php:
+     - added (website unifying other websites, so that only one website
+       for runs, one for sequences and one for datasets is needed)
+
+   * datacenter/db/menu.php:
+     - added (containing functions for parts of the menu) 
+
+   * datacenter/db/menu.js: 
+     - added (script for diplaying/hiding parts of the menu)
+
+
+
+ 2006/08/09 Thomas Bretz
+
+   * mbase/MMath.cc:
+     - changed MedianDev to support 68% division instead of 0.5%
+
+   * datacenter/macros/fillsignal.C:
+     - adapted to use Median for Pulse Offset and Gain
+
+
+
+ 2006/08/08 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - added some comments
+
+   * mhist/MHEvent.cc: 
+     - replaced GetTheta() by GetTelescopeTheta()
+
+   * msignal/MExtractedSignalCam.cc:
+     - some update to returning the hi-/lo-gain ratio
+
+   * mbase/MMath.[h,cc]:
+     - new functions MedianDev
+
+   * mhist/MHCamera.[h,cc]:
+     - new function GetMedian
+     - new function GetMedianDev
+
+
+
+ 2006/08/08 Daniela Dorner
+
+   * datacenter/scripts/copyscript:
+     - updated address list of people who are informed about changes in 
+       the catalog file
+     - improved output to mail
+     - updated search of newer catalogfiles 
+     - addapted to change in md5sum
+     - fixed typo
+
+   * steps.rc:
+     - made interpretable for shell
+     - set Default to check for fSequenceFileWritten, so that manually 
+       inserted sequences can't be resettet
+
+   * datacenter/scripts/makecallistolinks:
+     - removed reason2
+
+
+
+ 2006/08/06 Thomas Bretz
+
+   * datacenter/macros/checkstardone.C, 
+     datacenter/macros/checkfileavail.C,
+     datacenter/macros/filldotraw.C:
+     - fixed. res was still not correctly deleted
+
+
+
+ 2006/08/05 Thomas Bretz
+
+   * datacente/macros/fillsignal.C:
+     - still searched for tabs DiffHi and DiffLo... fixed.
+     - added a missing comma in the sql query
+
+   * mbase/MLog.cc, mbase/MLogHtml.cc:
+     - switched off buffering for ofstreams
+     - fixed length argument for the case </> are replaced by html-code
+
+   * datacenter/macros/checkstardone.C:
+     - fixed. was completely broken, didn't even compile.
+
+
+
+ 2006/08/04 Thomas Bretz
+
+   * mhvstime/MHVsTime.cc:
+     - fixed a bug which made the argument of SetMinimum be ignored
+
+   * mpointing/MHPointing.cc:
+     - changed position of SetMinimum and SetMaximum
+
+   * msignal/MArrivalTimeCam.[h,cc]:
+     - added new options in GetPixelContent
+     - added some new member functions
+
+   * msignal/MExtractedSignalCam.[h,cc]:
+     - added new options in GetPixelContent
+     - added some new member functions
+
+   * msignal/MExtractedSignalPix.h:
+     - added some new member function
+     - added some comments
+
+   * msql/MSQLServer.cc:
+     - allow to setup different password for differend users and different
+       users for different databases in sql.rc
+
+   * mcalib/MCalibrateRelTimes.cc:
+     - implemented a workaround to mark pixels bad for extraction of
+       hi- and lo-gain failed. (Before MCalibrateData just assigned
+       a weird value)
+
+   * msignal/MArrivalTimePix.h:
+     - added some member functions
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - added some comments which contain future code
+     - invalidate hi- and lo-gain if both could not be extracted properly
+       (FIXME: We need a cut on the number of unsuitable pixels per event)
+     - changed handling of sathi to make the detection of hi-gain
+       saturation work properly
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - changed fgLoGainOffset from 1.05 to 0.95 (comming out of the
+       latest plots)
+     - fixed assignment of sat in hi-gain extraction to make sure
+       the the satuartion information can be returned properly
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - changed fgLoGainStartShift according to BCN cvs to -2.4 (FIXME
+       this should be checked!)
+     - adapted handling of sat in hi-gain extraction to changes
+       above
+
+   * mjobs/MJCalibrateSignal.cc:
+     - replaced the hi-/lo-gain pulse plots by plots showing the
+       hi-/lo-gain intercalibration and the hi-/lo-gain offset
+
+   * datacenter/macros/fillsignal.C:
+     - changed according to the changes
+
+   * mraw/MRawFileRead.cc:
+     - rais an error if a requested file could not be opened
+
+   * mbase/MParContainer.cc:
+     - added some comments
+
+
+
+ 2006/08/03 Thomas Bretz
+
+   * mbase/MTask.cc:
+     - do not print number of executions if it is (UInt_t)-1
+
+   * mfileio/MReadReports.cc:
+     - do not allocate a MTime container anymore. This can be done
+       by root automatically which has the advantage that we don't
+       have to care about its deletion
+     - added some more debug output, just in case...
+
+   * mfileio/MReadTree.cc:
+     - fixed a typo in a comment
+
+   * mhist/MHRate.cc, mhist/MHWeather.cc, mhvstime/MHSectorVsTime.cc,
+     mhvstime/MHVsTime.cc:
+     - changed position of SetMinimum and SetMaximum
+
+   * mimage/MHHillas.[h,cc]
+     - made the Center-Histogram in the case only one is displayed 
+       one with palette
+
+
+
+ 2006/08/03 Markus Meyer
+
+   * resources/calibration.rc, calibration_spline.rc
+     - update of correction factors
+
+   * datacenter/macros/fillstar.C
+     - update of reference values for muon analysis
+
+
+
+ 2006/08/02 Daniela Dorner
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/copyscript, 
+     datacenter/scripts/correcttime, datacenter/scripts/dodatacheck, 
+     datacenter/scripts/doexclusions, datacenter/scripts/doqualityplots, 
+     datacenter/scripts/dowebplots, datacenter/scripts/filesondisk, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed, 
+     datacenter/scripts/fillstar, datacenter/scripts/insertdatasets, 
+     datacenter/scripts/insertsequences, datacenter/scripts/linkmc, 
+     datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/mcsequences, datacenter/scripts/movingrawfiles, 
+     datacenter/scripts/processmcsequences, datacenter/scripts/rmlocks, 
+     datacenter/scripts/runcallisto, datacenter/scripts/runganymed, 
+     datacenter/scripts/runstar, datacenter/scripts/sourcefile, 
+     datacenter/scripts/writesequencefiles: 
+     - replaced $USER by `whoami`
+
+   * datacenter/scripts/dowebplots:
+     - write output (ps, png files) to $datapath and not $webdir to 
+       speed up the webupdate
+
+
+
+ 2006/08/02 Thomas Bretz
+
+   * mhist/MHCamEvent.cc:
+     - removed some obsolete includes
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - reformatted position of a parenthesis
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - changed default lo-gain offset to new value 1.05 which was
+       determined plotting arrival time vs. signal height.
+     - added fHiGainFirst to time (as it is in the spline extractor)
+
+   * msignal/MSignalCam.cc:
+     - after extesive tests using the arrival time vs signal height
+       histograms, new threshold levels (independent of the pixel size)
+       have been determined for the pulse positions
+       (50phe for pulse, hi-gain and 320phe for lo-gain)
+
+   * datacenter/macros/fillsignal.C:
+     - changed to support new information about pulse positions
+
+
+
+ 2006/08/01 Thomas Bretz
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - hand over the hi-lo-gain conversion factors to the new 
+       MCalibrationChargeCam if reinitialized
+
+   * mcalib/MCalibrateData.cc:
+     - removed obsolete use of zenith angle (which actually was never used)
+     - fixed a bug which caused the renorm factor being initialized from
+       default instead of the QECam always (which didn't make any difference
+       because also the QECam contains the default value)
+
+   * mcalib/MCalibrateRelTimes.[h,cc]:
+     - store also the information whether lo-gain was used or not in
+       MSignalCam
+     - removed some comments from header
+
+   * mcalib/MCalibrationQEPix.[h,cc]:
+     - removed obsolete use of zenith angle (which actually was never used)
+
+   * mhist/MHCamera.cc:
+     - fixed wrong cast (from this to TProfile instead of TH1D)
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added tabs for hi-/lo-gain pulse position
+
+   * mjobs/MJCalibration.cc:
+     - removed obsolete use of zenith angle (which actually was never used)
+       for MCalibrationQEPix
+
+   * msignal/MArrivalTimePix.h:
+     - added Copy member function
+
+   * msignal/MExtractedSignalPix.cc:
+     - small code layout
+
+   * msignal/MSignalPix.[h,cc]:
+     - added new (non I/O) member fLoGainUsed
+
+   * msignal/MSignalCam.cc:
+     - added cases 10 and 11 to GetPixelContent
+     - added some more comments
+
+
+
+ 2006/07/31 Thomas Bretz
+
+   * showplot.cc:
+     - added new options to write bmp and xml files
+     - added new options for the display size
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed the constructor to allow starting with a different size
+     - added new member functions to change the display or canvas size
+     - fixed setting of sizes
+
+
+
+ 2006/07/30 Thomas Bretz
+
+   * macros/starfield.C:
+     - updated to use resources/mirrors.def by default
+
+   * mhist/MHCamera.[h,cc]:
+     - replaced SavePrimitive(ofstream&) by SavePrimitive(ostream&)
+     - if necessary let SavePrimitive(ofstream&) call 
+       SavePrimitive(ostream&)
+
+   * mgui/MHexagon.[h,cc]:
+     - special solution for SavePrimitive because it calls a function
+       from the base class which also needs ofstream or ostream
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - switched on writing bmp and xml (I still found no program able
+       to read this bmp, but they are written)
+     - removed check for writing images in batch mode for root
+       >= 5.12/00. It is working now.
+     - calculate kB and MB correctly by dividing by 1000 instead of
+       1024 (would be kiB and MiB)
+     - removed some unused parameters from function declaration
+     - fixed some warnings about local overwrites of variable names
+     - fixed a deprecated conversion from string constant to `char*
+
+
+
+ 2006/07/29 Thomas Bretz
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - changed the fit such that initial values are calculated
+       automatically now instead of using build in values. This
+       makes the fit more indepedant of the underlaying rates.
+       With a test of ~350 sequences in the test database it could
+       be shown that the new fit gives the same result +/-1sek.
+       The highest deviation was +5s the lowest -10s.
+     - the number of the first bin used in the fit became a variable
+     - A limit of 15kHz was set for the rate
+     - sanity checkes for lambda==0 added (possible division by zero)
+     - increased class version number by one
+     - made functions derived from MH private
+     - to fit the resulting "gammas" use fFirstBin=1 and fNumEvents=120
+
+
+
+ 2006/07/28 Daniela Dorner
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/copyscript, 
+     datacenter/scripts/correcttime, datacenter/scripts/dodatacheck, 
+     datacenter/scripts/doexclusions, datacenter/scripts/doqualityplots, 
+     datacenter/scripts/dowebplots, datacenter/scripts/filesondisk, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed, 
+     datacenter/scripts/fillstar, datacenter/scripts/insertdatasets, 
+     datacenter/scripts/insertsequences, datacenter/scripts/linkmc, 
+     datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/mcsequences, datacenter/scripts/movingrawfiles, 
+     datacenter/scripts/processmcsequences, datacenter/scripts/rmlocks, 
+     datacenter/scripts/runcallisto, datacenter/scripts/runganymed, 
+     datacenter/scripts/runstar, datacenter/scripts/sourcefile, 
+     datacenter/scripts/writesequencefiles: 
+     - replaced username by $USER
+
+
+
+ 2006/07/27 Thomas Bretz
+
+   * datacenter/macros/buildsequenceentries.C:
+     - removed some obsolete output
+     - logging output redone
+     - added some missing delete of TSQLResults
+     - fixed some overwrite of local variables
+     - added more comments
+     - moved code building the blocks to its own function
+     - simplified buildblocks
+
+
+
+ 2006/07/27 Daniela Dorner
+
+   * datacenter/scripts/buildsequenceentries:
+     - fixed bug in name of logfile (introduced on 2006/02/03)
+
+
+
+ 2006/07/26 Daniela Dorner
+
+   * datacenter/scripts/movingrawfiles:
+     - changed machine
+     - added logging
+     - added launching of filesondisk, when files have been moved
+
+   * datacenter/scripts/filesondisk:
+     - added logging
+
+
+
+ 2006/07/26 Thomas Bretz
+
+   * merpp.cc:
+     - files with the extension .raw.gz were not found. fixed. This
+       is necessary because raw-files must be merpped before they can
+       be displayed with the mars-gui.
+
+   * star.cc:
+     - fixed some misalignment when the title is printed
+
+   * datacenter/macros/fillsinope.C:
+     - removed some obsolete comments
+
+   * mbase/MContinue.h:
+     - some reformatting
+
+   * mreport/MReportStarguider.h:
+     - added enum for states
+     - added IsMonitoring member function
+
+   * msignal/MArrivalTimeCam.cc:
+     - fixed a problem which gave errors when compiling (introduced
+       with the latest change)
+
+   * manalysis/MEventRateCalc.[h,cc], manalysis/MGeomApply.[h,cc],
+     manalysis/MMultiDimDistCalc.[h,cc], mbadpixels/MBadPixelsTreat.[h,cc],
+     mbase/MEvtLoop.[h,cc], mbase/MParContainer.[h,cc], mbase/MParList.[h,cc],
+     mbase/MTask.[h,cc], mbase/MTaskList.[h,cc], mcalib/MCalibrateData.[h,cc],
+     mdata/MDataArray.[h,cc], mfbase/MF.[h,cc], mfbase/MFDataChain.[h,cc],
+     mfbase/MFDataChain.[h,cc], mfbase/MFDataMember.[h,cc],
+     mfbase/MFilterList.[h,cc], mfileio/MReadTree.[h,cc], 
+     mfileio/MWriteRootFile.[h,cc], mfilter/MFParticleId.[h,cc],
+     mfilter/MFTriggerLvl1.[h,cc], mfilter/MFTriggerLvl2.[h,cc],
+     mhbase/MBinning.[h,cc], mhbase/MFillH.[h,cc], mhbase/MH3.[h,cc],
+     mhbase/MHMatrix.[h,cc], mimage/MHillasCalc.[h,cc],
+     mimage/MImgCleanStd.[h,cc], mimage/MImgCleanTGB.[h,cc],
+     mpointing/MSrcPosCam.[h,cc], msignal/MExtractFixedWindow.[h,cc],
+     msignal/MExtractSignal.[h,cc], msignal/MExtractSignalABcorr.[h,cc],
+     msignal/MExtractor.[h,cc], mtools/MChisqEval.[h,cc]
+     - replaced StreamPrimitive(ofstream&) by StreamPrimitive(ostream&)
+     - replaced SavePrimitive(ofstream&) by SavePrimitive(ostream&)
+     - if necessary let SavePrimitive(ofstream&) call 
+       SavePrimitive(ostream&)
+
+   * mbadpixels/MBadPixelsCam.cc, mbadpixels/MBadPixelsIntensityCam.cc,
+     mbase/MEvtLoop.cc, mbase/MLog.cc, mbase/MParList.cc, mbase/MTaskList.cc,
+     mcalib/MCalibConstCam.cc, mcalib/MCalibrationBlindCam.cc,
+     mcalib/MCalibrationCam.cc, mcalib/MCalibrationIntensityCam.cc,
+     mcalib/MCalibrationIntensityConstCam.cc, mdata/MDataArray.cc,
+     mdata/MDataFormula.cc, mdata/MDataList.cc, mfbase/MFilterList.cc,
+     mgeom/MGeomCam.cc, mhcalib/MHCalibrationCam.cc, mmain/MMonteCarlo.cc,
+     mpedestal/MPedPhotCam.cc, mpedestal/MPedestalCam.cc,
+     mreport/MReportFileRead.cc, msignal/MArrivalTimeCam.cc,
+     msignal/MExtractedSignalCam.cc, msignal/MSignalCam.cc:
+     - replaced ForEach by R__FOR_EACH
+
+   * mbase/MAGIC.h:
+     - define R__FOR_EACH macro if not yet defined
+
+   * mbase/MEvtLoop.cc:
+     - removed usage of copy-constructor of TEnv
+
+   * mbase/MString.h:
+     - exclude some of the member function from CINT (gives problem
+       with CINT)
+
+   * mfbase/MFEventSelector.[h,cc]:
+     - removed StreamPrimitive (it was empty anyhow)
+
+   * mranforest/MRanTree.cc:
+     - moved includes for TVector and TMatrix to header
+     - replaced TMatrixRow by TMatrixFRow_const in TreeHad
+
+   * msignal/Makefile, msignal/SignalLinkDef.h:
+     - removed MExtractSignal
+     - removed MExtractSignal2
+     - removed MExtractSignal3
+     - removed MExtractSignalABcorr
+
+   * mbase/MArgs.cc, mbase/MContinue.cc, mbase/MEnv.cc, mbase/MGMap.[h,cc],
+     mbase/MGTask.h, mbase/MLogManip.h, mbase/MLogPlugin.h
+     mbase/MParContainer.cc, mbase/MParList.cc, mbase/MParameters.cc,
+     mbase/MSearch.cc, mbase/MStatusArray.h, mbase/MTask.cc,
+     mbase/MTaskList.[h,cc]:
+     - removed some unused parameters from function declaration
+
+   * mbase/MArray.h, mbase/MArrayB.h, mbase/MArrayD.h, mbase/MArrayF.h,
+     mbase/MArrayI.h, mbase/MArrayS.h, mbase/MDirIter.h, mbase/MLog.[h,cc],
+     mbase/MReadSocket.h, mbase/MTask.cc, mbase/MTaskList.[h,cc],
+     mbase/MTime.h:
+     - added explicit initialization of base class to copy ctor
+
+   * mbase/MDirIter.[h,cc], mbase/MLog.[h,cc], mbase/MRunIter.cc,
+     mbase/MZlib.cc:
+     - fixed some warnings about local overwrites of variable names
+
+   * mbase/MTaskList.[h,cc]:
+     - removed unsused second argument from CheckAddListTo
+     - allow 0 as the type argument which just keeps the input steam id
+       of the task
+
+   * mjobs/MSequence.cc:
+     - fixed a deprecated conversion from string constant to `char*
+
+   * mfbase/MFilterList.cc:
+     - improved warn output
+
+   * msignal/MArrivalTimeCalc2.cc, msignal/MArrivalTimePix.[h,cc],
+     msignal/MExtractFixedWindowPeakSearch.cc, msignal/MExtractSignal.cc,
+     msignal/MExtractSignal2.cc, msignal/MExtractSignal3.cc,
+     msignal/MExtractSignalABcorr.cc, msignal/MExtractTime.cc,
+     msignal/MExtractTimeAndCharge.cc, msignal/MExtractor.cc,
+     msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc:
+     - removed first obsolete argument from SetGainSaturation
+
+    * msignal/MExtractedSignalCam.[h,cc]:
+      - removed obsolete fNdf
+      - increased class version
+
+    * msignal/MExtractedSignalPix.[h,cc]:
+      - removed obsolete fIsLoGainUsed
+      - removed obsolete fChisquare
+      - increased class version
+      - removed obsolete first argument from SetGainSaturation
+
+
+
+ 2006/07/23 Thomas Bretz
+ 
+   * datacenter/scripts/copyscript:
+     - only try to insert the contents of runbook files which
+       contain the regexp \\\.rbk$ instead of .rbk It might be
+       that in a script it should be \.rbk$ rather than \\\.rbk$
+       (to be tested)
+
+
+
+ 2006/07/22 Thomas Bretz
+
+   * datacenter/scripts/runstar:
+     - added -r to sort ToDo-files such that the newest sequences
+       are processed first
+
+
+
+ 2006/07/21 Daniela Dorner
+
+   * datacenter/scripts/checkfilesforsequavail:
+     - fixed bug in path
+
+
+
+ 2006/07/19 Thomas Bretz
+
+   * msignal/MArrivalTimeCam.cc:
+     - added case 7 and 2 in GetPixelContent
+
+
+
+ 2006/07/13 Thomas Bretz
+
+   * mastro/MAstroCatalog.h:
+     - implemented new member function GetNumStars
+
+   * mbase/MGMap.[h,cc]:
+     - implemented new member function DrawHexagon
+
+
+
+ 2006/07/11 Thomas Bretz
+
+   * mbase/MStatusArray.cc, mdata/MDataChain.cc, mdata/MDataFormula.cc,
+     mhflux/MMcSpectrumWeight.cc, mimage/MHillasExt.cc, mjobs/MJCut.cc,
+     msignal/MExtractTimeAndChargeDigitalFilter.cc,
+     mranforest/MRanForestCalc.cc:
+     - fixed some compiler warning of the kind
+         ambiguous overload for `Bool_t ? const char[14] : const TString &'
+       to make gcc 2.95.3 happy (used to get cosy working with the
+       latest Mars version)
+
+   * mbase/MZlib.[h,cc]:
+     - added some preprocessor statements which allow compilation with
+       gcc 2.95.3
+
+   * mastro/MAstroCamera.cc:
+     - removed path from include
+
+   * mastro/Makefile: 
+     - added directory for MHCamera
+
+   * mhflux/MHThetaSqN.cc:
+     - removed the const-qualifier from the static_cast when setting
+       tghe MParameterD
+
+
+
+ 2006/07/06 Thomas Bretz
+
+   * Makefile.conf.linux:
+     - removed options -Wstrict-prototypes -Wmissing-prototypes
+       obsolete for C++
+
+   * mastro/MAstro.h, mgui/MCamEvent.h:
+     - added virtual destructor to make gcc 4.1 happy
+
+   * mfilter/MFMagicCuts.cc, mtools/MagicJam.cc:
+     - added includes to make gcc 4.1 happy
+
+   * mranforest/MRanForestCalc.cc:
+     - added include for the compilation with root 5.10/00
+
+
+
+ 2006/07/05 Thomas Bretz
+
+   * datacenter/macros/checkfileavail.C,
+     datacenter/macros/checkstardone.C, 
+     datacenter/macros/doexclusions.C, 
+     datacenter/macros/filldotraw.C,
+     datacenter/macros/fillganymed.C,
+     datacenter/macros/fillsignal.C,
+     datacenter/macros/fillstar.C,
+     datacenter/macros/setupdb.C:
+     - make sure that 'res' is correctly deleted
+
+   * datacenter/macros/doexclusions.C:
+     - fixed some variable name overrides
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added the possibility to DrawResult()
+
+   * mhflux/MHAlpha.[h,cc]:
+     - added new output container (Bin) which contains the number
+       of the bin the event was assigned to
+     - fixed drawing the significance in DrawAll
+
+
+
+ 2006/07/04 Daniela Dorner
+
+   * datacenter/scripts/copyscript:
+     - removed not needed if-clause (was used to copy subsystemfiles to 
+       /magic/datacenter/totape)
+
+
+
+ 2006/07/03 Thomas Bretz
+
+   * mhflux/MHThetaSqN.[h,cc]:
+     - added counter and output some statistics afterwards
+
+
+
+ 2006/06/29 Thomas Bretz
+
+   * mmain/MEventDisplay.cc:
+     - added decoding of calibration pattern
+
+   * mbase/MContinue.cc:
+     - small change to some output
+
+   * mmc/MMcTrig.hxx, mmc/MMcTrigHeader.hxx:
+     - increased version number 
+
+   * mmc/Mdefine.h:
+     - increased CAMERA_PIXELS from 3500 to 3800
+
+
+
+ 2006/06/28 Daniela Dorner
+
+   * datacenter/macros/setupdb.C:
+     - added new columns 
+     - changed name columns
+
+
+
+ 2006/06/28 Thomas Bretz
+
+   * datacenter/macros/fillstar.C:
+     - added number of correlated stars
+
+   * datacenter/macros/plotdb.C:
+     - added number of correlated stars
+     - changed name of database column
+
+   * callisto.cc, mbadpixels/MBadPixelsCalc.cc, 
+     mjtrain/MJTrainSeparation.cc:
+     - small improvement to log-output
+
+   * tpoint/gui.C:
+     - added some SetFrameBorderMode and SetBorderMode
+
+
+
+ 2006/06/27 Thomas Bretz
+
+   * mhflux/MHAlpha.cc:
+     - added a small change to prevent DrawAll from opening a new
+       canvas if called with the option "No new canvas" and no
+       fDisplay
+
+
+
+ 2006/06/26 Thomas Bretz
+
+   * mjobs/MJCut.[h,cc]:
+     - added error codes for some fatal errors
+
+   * ganymed.cc:
+     - pipe error codes to shell
+
+
+
+ 2006/05/29 Thomas Bretz
+
+   * mbase/MEnv.cc:
+     - included THashList for compatibility with root 5.10/00
+
+   * mdata/MDataArray.[h,cc]:
+     - included TVector in header for compatibility with root 5.10/00
+
+   * mgui/MHexagon.cc:
+     - changed argument of PaintFillArea from Float_t to Double_t
+       for compatibility with root 5.10/00
+
+   * mhbase/MHMatrix.[h,cc]:
+     - added some #ifdef for compatibility with root 5.10/00
+     - included TVector in the header for compatibility with
+       root 5.10/00
+
+   * mjtrain/MJTrainDisp.cc:
+     - added the possibility to set weights
+     - added new histogram to show avg psf versus energy
+
+   * mjtrain/MJTrainRanForest.cc:
+     - included TFile for compatibility with root 5.10/00
+
+   * mranforest/MRanForest.[h,cc]:
+     - included TMatrix and TVector in header for compatibilty
+       with root 5.10/00
+
+   * mtools/MHSimulatedAnnealing.[h,cc]:
+     - included TMatrix and TVector in header for compatibilty
+       with root 5.10/00
+
+
+
+ 2006/05/24
+
+   * RELEASE 0.9.6
+
+
+
+ 2006/05/24 Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.cc:
+     - another small improvement, set fMaxArrivalTimeDiff to 0.9
+
+   * mjobs/MJPedestal.cc:
+     - switched off error in case of "pulse is too much to the left"
+     - the extraction window is not changed anymore
+
+   * mhflux/MAlphaFitter.cc:
+     - made new background fit more robust by improving the start
+       values
+
+   * mhflux/MHAlpha.[h,cc]:
+     - preliminary implementation showing automatically all sizebins in
+       the status display
+
+   * mpointing/MPointingDevCalc.[h,cc]:
+     - if the mispointing is set to 0 due to missing mispointing
+       information also the starguider calibration is reset.
+     - in the case the latest report is older than a default (currently
+       one minute) and the current report will be skip the starguider
+       correction and calibration will be reset.
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - updated 
+
+   * mmc/MMcRunHeader.hxx:
+     - added new getter for ShowerPhiMin and ShowerPhiMax
+
+
+
+ 2006/05/23 Daniela Dorner
+
+   * scripts/processsequence:
+     - added (script to run callisto, merppupdate and star for 1 
+       sequence)
+
+   * scripts/preparemc:
+     - added (script to create montecarlo sequence and datasetfiles)
+
+
+
+ 2006/05/23 Thomas Bretz
+
+   * mranforest/MRanTree.cc:
+     - should be if(!Finite) instead of if(Finite)
+
+   * mhbase/MH3.cc:
+     - fixed a problem which arouse in root 4.04/02g namely that
+       is the draw-option is " " nothing is displayed. Therefore
+       all " " are removed before the histogram is drawn
+
+   * mhist/MHCamera.cc:
+     - when the azimuthal profile was produced the binning was optimized
+       with the OptimizeLimits. This doesn't make sense because it 
+       changed the alignment of the bins with the 60deg boundaries
+
+   * mreport/MReportStarguider.cc:
+     - fixed a typo in a comment and removed an obsolete one
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - instead of setting the arrival time to a value at the border of
+       the meaningful range a random number is assigned in the case
+       of an arrival time extracted outside the fadc range. This
+       avoids possible unfortuante coincidences in arrival times.
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - added new data member fMaxArrivalTimeDiff, which is the maximum
+       arrival time difference allowed for the badpixel algorithm
+       to determin whether a pixels belongs to a shower
+     - changed the old value (0.5) to 1.0 as suggested by Stefan
+       due to a recent study on the fraction of pixels surviving the
+       image cleaning
+
+   * callisto.rc, callisto_Dec04Jan05.rc, callisto_MarApr05.rc:
+     - added comment to show usage of new option
+
+
+
+ 2006/05/22 Daniela Dorner
+
+   * datacenter/scripts/makecallistolinks:
+     - fixed bug
+
+
+
+ 2006/05/22 Thomas Bretz
+
+   * mranforest/MRanTree.cc:
+     - replaced some arbitrary small and large values by FLT_MAX in
+       FindBestSpllit*
+     - replaced in FindBestSpllit* a sanity check for rld and rrd (do
+       not divide by zero) by a check whether the result (crit) is finite
+
+   * mcamera/MCameraRecTemp.[h,cc]:
+     - implemented new data member for validity
+     - increased class version by 1
+
+   * mpointing/MHPointing.[h,cc]:
+     - implemented new TGraph for number of correlated stars
+     - increased class version by 1
+
+   * mpointing/MPointingDevCalc.cc:
+     - if the report is empty assume no pointing deviation and also
+       reset the starguider calibration
+
+   * mpointing/MPointingPos.cc:
+     - slight modifications to comment
+
+   * mreport/MReport.cc:
+     - introduced new fake version to support new starguider format
+
+   * mreport/MReportCC.[h,cc]:
+     - improved handling of receiver boar com-errors and RecTemp section
+
+   * mreport/MReportStarguider.[h,cc]:
+     - implemented changes in the starguider reports around 9th May
+     - added new data member for number of correlated stars
+     - increased class version by 1
+
+
+
+ 2006/05/21 Thomas Bretz
+
+   * mfileio/MReadTree.cc:
+     - show all added files only in debug modes or if wildcards are used
+
+   * mfilter/MFEnergySlope.[h,cc]:
+     - added a third constructor which also allows to set fMcEnergyMin
+
+   * mjtrain/MJTrainSeparation.[h,cc]:
+     - updated text output
+     - improved result display
+     - added possibility to set weights and/or pre/post-tasks for
+       train or test only
+
+   * mranforest/MRanForest.cc:
+     - commented out an obsolete check to check whether TMath::Sort
+       has sorted correctly
+     - added some comments
+
+
+
+ 2006/05/20 Thomas Bretz
+
+   * mreport/MReportCC.cc:
+     - fixed a typo in InterpreteTD which was introduced yesterday
+
+
+
+ 2006/05/19 Thomas Bretz
+
+   * mbase/MMath.h:
+     - added default to second argument of GaussProb
+
+   * mcamera/MCameraTD.[h,cc], mcamera/MCameraTH.[h,cc]:
+     - added a data member fIsValid giving the status of the arrays
+       in case the CC reports contained nonsense (mainly for files 
+       before summer 2005)
+     - increased class version by 1
+
+   * mhflux/MHAlpha.h:
+     - made SetOffData virtual
+
+   * mreport/MReport.cc:
+     - small changes to some comments
+
+   * mreport/MReportCC.[h,cc]:
+     - better handling of problems with the TH and TD part of the 
+       CC-REPORT for files older than 200507190 and 200412210 
+       respectively
+
+   * mreport/MReportFileReadCC.cc:
+     - always output the file format version
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - implemented fitting of the off-data for background determination
+     - the result values are not yet accessible
+     - increased class version by 1
+
+   * mhflux/MHThetaSqN.[h,cc]:
+     - some improvements regarding the treatment of the signal-regions
+     - allow to set a different cut-level for off-cuts
+
+
+
+ 2006/05/18 Thomas Bretz
+
+   * mhflux/MAlphaFitter.h:
+     - added Getter for ScaleMode
+
+   * mhflux/MHAlpha.[h,cc]:
+     - made fHillas data member protected
+     - increased size of fMap
+
+   * mhflux/MHThetaSq.[h,cc]:
+     - removed obsolete data-member fThetaSq
+
+   * mjtrain/MJTrainRanForest.cc, mranforest/MRanForestCalc.cc:
+     - fixed a typo in a comment
+
+   * mranforest/MRanTree.cc:
+     - added a lot of comments in the code
+
+   * callisto.cc:
+     - fixed typo in output
+
+   * mhflux/MHThreshold.cc:
+     - enabled grids
+     - slightly improved calculation of shown threshold
+
+   * mhflux/MHThetaSqN.[h,cc]:
+     - added
+
+   * mhflux/Makefile, mhflux/FluxLinkDef.h:
+     - added MHThetaSqN
+
+
+
+ 2006/05/18 Daniela Dorner
+
+   * resources/calibration.rc, resources/calibration_spline.rc:
+     - added values for current and following periods
+
+
+
+ 2006/05/05
+
+   * RELEASE 0.9.5.1
+
+
+
+ 2006/05/05 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - updated with new tabs for the starguider data
+
+   * mhflux/MHEnergyEst.cc:
+     - print the result to the all-logstream
+     - changed the fit range not to take the overflow into account
+
+   * mranforest/MRanForest.[h,cc]:
+     - Use the default Reset() instead of Reset(0)
+     - changed output while training
+     - replaced a lot of TArrays by MArrays
+     - at some points replaced gRandom->Rndm by gRandom->Integer
+     - removed some obsolete arguments from ModifyDataSort
+     - In CreateDataSort isort need not to be initialized, it is
+       done by TMath::Sort anyhow
+     - a small simplification to ModifyDataSort
+     - added some const-qualifiers in funciton calls
+
+   * mranforest/MRanTree.[h,cc]:
+     - replaced a lot of TArrays by MArrays
+     - removed some obsolete calls to Reset(0) after the instatization
+       of the array
+     - small acceleration of the averaging when calculating fBestSplit[k]
+     - at some points replaced gRandom->Rndm by gRandom->Integer
+     - directly give mean[kbuild] and square[kbuild] as an argument
+       to FindBestSplit
+     - removed the obsolste dereferencing from the call to FindBestSplit
+     - added some const-qualifiers in funciton calls
+     - make a copy of tclasspop in BuildTree to be able to give the
+       array as a const qualified reference. It is not used at any other
+       place
+     - in TreeHad first get the pointers to the vector with the data to
+       get rid of the range check done by root. This has also the advantage
+       that all TreeHad member function can be unified into a single
+       member function
+
+   * mhflux/MAlphaFitter.cc:
+     - fixed a problem with the fit which could cause infinite loops
+       in the case of off-data. This did in no means effect the result,
+       just the performance.
+
+   * mhbase/MH3.cc:
+     - convert the options ToLower case first before checking
+
+   * mjtrain/MJTrainRanForest.[h,cc]:
+     - added AddPar member function
+     - added fPreTasks and fPostTasks
+     - added fEnableWeights
+     - added member functions suporting setting pre- and posttasks
+       and weights
+
+   * mtools/MTFillMatrix.h:
+     - added new member function to clear the fPreCuts, fPreTasks and
+       fPostTasks lists
+
+   * mjtrain/MJTrainEnergy.cc: 
+     - implemented usage of weights
+
+   * mjtrain/MJTrainSeparation.[h,cc]:
+     - implemented the usage of weights
+     - implemented a random source position to train with wobble 
+       data
+     - added some more output
+     - added an option to switch between classification and regression
+     - added th epossibility to change the MC flux
+
+   * mjtrain/Makefile:
+     - added include path for mpointing and mimage
+
+
+
+ 2006/05/04 Thomas Bretz
+
+   * mbase/MTaskList.[h,cc]:
+     - added new member function AddToListBefore(TList&) and
+       AddToListAfter(TList&)
+     - added corresponding RemoveFromList(TList&)
+
+   * mhflux/MMcSpectrumWeight.[h,cc]:
+     - added new member functions CalcSpecNew and CalcSpecOld to
+       evaluate the spectrum at a given energy
+     - added a new data member which allows to set an energy
+       at which the normalization is calculated instead of
+       the integral
+
+   * mpointing/MSrcPosRndm.[h,cc]:
+     - added new option which allows to create a random wobble
+       source position
+
+
+
+ 2006/05/03 Daniela Dorner
+
+   * datacenter/macros/setupdb.C:
+     - changed type of sourcename and projectname according to new 
+       format
+
+
+
+ 2006/05/03 Thomas Bretz
+
+   * Makefile.rules:
+     - added new option zdiff
+
+   * mbase/MTaskList.[h,cc]:
+     - overwrite member function AddToList with a TList-reference
+       as argument
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - added the missing //! behind the fMcEvt data member
+     - increased class version number
+     - removed obsolete fEnergy data member
+
+   * mranforest/MRanForest.cc:
+     - added to the output whether weights are set
+
+   * mraw/MRawRunHeader.cc:
+     - removed an obsolete Print() which enetered for debugging
+
+   * mimage/MHNewImagePar.cc:
+     - the plots for CocCOG and ConcCore had the same color... fixed
+
+   * mranforest/MRanForestCalc.[h,cc]:
+     - allow to set weights for each event
+
+   * mtools/MTFillMatrix.[h,cc]:
+     - implemented the possibility to set pre- and post-tasks
+       executed in the eventloop
+
+
+
+
+ 2006/05/02 Thomas Bretz
+
+   * mraw/MRawRunHeader.cc:
+     - fixed the typo in the output
+
+   * mpointing/MHPointing.cc, datacenter/macros/fillstar.C:
+     - fixed a typo in the name of the plot Skybrightness
+
+
+
+ 2006/04/30 Thomas Bretz
+
+   * mjtrain/MJTrainSeparation.[h,cc]:
+     - new option to switch between regression and classification
+     - fixed the auto training (still far from working well)
+     - improved result plots
+
+   * mbase/MMath.cc:
+     - fixed SignificanceLiMa such that it allows basically zero
+       signal- and/or background events
+
+
+
+ 2006/04/27 Thomas Bretz
+
+   * datacenter/macros/fillstar.C:
+     - replaced the mean by the median
+
+
+
+ 2006/04/26 Daniela Dorner
+
+   * datacenter/macros/fillstar.C, datacenter/macros/setupdb.C:
+     - added four new columns to the table Star
+
+
+
+ 2006/04/24 Thomas Bretz
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - some fixes to the comments describing random forest
+
+
+
+ 2006/04/23 Thomas Bretz
+
+   * mhist/MHHadronness.cc:
+     - do not reset the two hadronness-histograms in SetupFill
+       otherwise MJTrainSeparation cannot work correctly
+
+   * mjtrain/MJTrainSeparation.cc:
+     - added a Plot of Hadronness versus Size for MC events
+
+
+
+ 2006/04/22 Thomas Bretz
+
+   * mraw/MRawRunHeader.cc:
+     - some small changes, mainly output and comments
+
+   * mhflux/MHAlpha.[h,cc]:
+     - show also the integrated number of excess events in the 
+       plot versus energy/size and show the correct error.
+
+   * mtools/MJSpectrum.cc:
+     - added accelerator for executing the tasklist as in MJCut
+
+   * macros/train/trainseparation.C:
+     - fixed a typo
+
+   * mjtrain/MJTrainSeparation.h:
+     - added missing initialization of fAutoTrain
+     - fixed an error in EnablAutoTrain (was always set to kTRUE)
+
+
+
+ 2006/04/21 Daniel Hoehne
+
+   * datacenter/scripts/doqualityplots, datacenter/scripts/dowebplots:
+     - fixed bug in usage of pstoimg
+
+
+
+ 2006/04/13 Thomas Bretz
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - adapted to new DAQ format version 6
+     - increased class version number
+
+   * mtools/MTFillMatrix.cc:
+     - added accelerator for executing the tasklist as in MJCut
+
+   * mfilter/MFEnergySlope.cc:
+     - small update to output
+
+   * mfbase/MFilterList.[h,cc]:
+     - fixed a really old problem that the contents of the list never
+       got ReInit. Hopefully this never had bad sideeffects.
+
+   * macros/train/trainenergy.C:
+     - added another comment how to change the spectral slope of the
+       monte carlo spectrum
+
+
+
+ 2006/04/13 Thomas Bretz
+
+   * mreport/MReport.cc:
+     - added new fake arehucas versions to fix a problem with the 
+       starguider reports
+
+   * mreport/MReportFileRead.cc:
+     - increased informations in warning output
+
+   * mreport/MReportStarguider.cc:
+     - fixed a problem with the starguider reports between 6.3.2006 and
+       19.3.2006
+
+
+
+ 2006/04/13 Daniel Hoehne
+
+   * datacenter/db/findoffdata.php:
+     - implemented query for the inhomogeneity
+
+   * datacenter/db/runinfo.php:
+     - added checkboxes for start time, failed time and error codes
+
+   * datacenter/db/datacheck.php:
+     - fixed bug in StatusMenus for DataCheck and RawFile
+
+
+
+ 2006/04/12 Daniela Dorner, Daniel Hoehne
+
+   * datacenter/scripts/makecallistolinks:
+     - fixed bug
+
+
+
+ 2006/04/12 Thomas Bretz
+
+   * datacenter/macros/filldotraw.C:
+     - allow to access gzipped raw-files
+
+
+
+ 2006/04/11 Thomas Bretz
+
+   * mastro/MAstro.h:
+     - added conversion Parsec2Lighyear
+
+   * mbase/MLogHtml.cc:
+     - added a fix to display < and > correctly
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - commented out obsolete fEnergy parameter
+
+   * mjobs/MJSpectrum.cc:
+     - fill a second collection area plot after trigger
+
+   * mjoptim/MJOptimize.cc:
+     - improve speed of optimization by switching of timing and
+       reset in eventloop
+
+   * mmc/MFadcHeader.h:
+     - changed MFADC_CHANNELS from 3500 to 3800 according to Abelardo
+
+   * mmc/MMcFadcHeader.hxx:
+     - increaded version number from 7 to 8
+
+
+
+ 2006/04/11 Daniel Hoehne, Daniela Dorner
+
+   * datacenter/scripts/dodatacheck:
+     - fixed bug in finding raw-files
+
+
+
+ 2006/04/10 Daniel Hoehne
+
+   * datacenter/macros/filldotrun.C:
+     - implemented new arehucas version
+
+
+
+ 2006/04/07 Daniel Hoehne, Daniela Dorner
+
+   * datacenter/macros/filldotrun.C, buildsequenceentries.C, setupdb.C:
+     - implemented new arehucas version
+
+
+
+ 2006/04/06 Daniela Dorner
+
+   * datacenter/scripts/makecallistolinks:
+     - fixed bug in resetting
+
+   * datacenter/db/tabs.php:
+     - changed tabs for wobble
+
+
+
+ 2006/04/05 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - added new tab with the effective on-time relative to the
+       observation time
+
+   * sponde_onoff.rc:
+     - added
+
+
+
+ 2006/04/04 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - if no dataset and no time-interval is given only sequences with
+       an effective on-time above five minutes are plotted anymore
+
+
+
+ 2006/03/21 Daniela Dorner
+
+   * datacenter/db/ganymed.php, datacenter/db/tabs.php:
+     - included different tabs for on/off and wobble
+
+   * datacenter/db/ganymed.php:
+     - added zd angle range and observation period
+
+   * datacenter/db/sequence.php:
+     - added rel. ontime
+
+
+
+ 2006/03/20 Thomas Bretz
+
+   * mraw/MRawRunHeader.cc:
+     - if the pixels to be swaped are both not found, assume they are
+       intentially not mapped. Changed the Error to a Warning
+
+   * mhflux/MHDisp.[h,cc]:
+     - made the scale region a parameter which can be changed from
+       within the display
+     - allow the scale parameters to be setup from the resource-file
+     - changed the source-region which is cut out in wobble mode from
+       +/-15deg to +/-25deg which better fits what we get from MHPhi
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - added example how to change the new scale parameters in MHDisp
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - implemented the strategy for optimization which is suggested
+       by the Berlin people for weak sources "weaksource"
+
+   * mhflux/MHPhi.[h,cc]:
+     - moved the AppendPad for the text-paint into all sub-pads which
+       need it. Otherwise they are not always properly updated.
+
+
+
+ 2006/03/16 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - small bugfix in logging
+
+   * datacenter/db/tabs.php:
+     - added new tab for ganymed
+
+
+
+ 2006/03/15 Stefan Ruegamer
+
+   * manalysis/MCameraData.cc
+     - inserted an image cleaning based on the time information
+     of the shower (CalcCleaningArrivalTime)
+
+   * manalysis/MCameraData.h
+     - made entry for "CalcCleaningArrivalTime"
+
+   * mimage/MImgCleanStd.cc
+     - created entries for the new image cleaning named "Time"
+
+   * mimage/MImgCleanStd.h
+     - inserted entry "kTime"
+
+
+
+ 2006/03/14 Daniela Dorner
+
+   * datacenter/scripts/makecallistolinks:
+     - fixed bug
+
+   * steps.rc:
+     - added fFillGanymed to influences of fGanymed
+
+
+
+ 2006/03/14 Thomas Bretz
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - skip the fit not only if the integral is empty but
+       also if the first bin is empty
+     - changed upper limit to 95% according to a study from
+       David Paneque
+     - replaced the fit with the exponential used in the BCN Mars
+       version
+     - use the correct number of entries
+     - use a likelihood fit
+     - calculate the fit quality from the probability
+     - ignore the fit quality for the theta-plot
+
+   * mimage/MHNewImagePar.cc:
+     - fixed the handling of the "same" option in Draw/Paint
+
+   * mpointing/MPointingDev.h:
+     - fDx and fDy initialized in the constructor
+
+   * mbase/MTask.[h,cc]:
+     - removed the kDontCount option. Instead don't use the TStopwatch
+       counter anymore. By this the class to TStopwatch can be
+       suppressed completely if kDontTime is set.
+
+   * mbase/MContinue.cc, mbase/MTaskEnv.cc, mfbase/MF.cc, 
+     mfbase/MFilterList.[h,cc]:
+     - pipe the accelerator flag to the filter or task
+
+   * mjobs/MJCut.cc:
+     - also accelerate the reading task
+
+
+
+ 2006/03/13
+
+   * RELEASE 0.9.5
+
+
+
+ 2006/03/13 Thomas Bretz
+
+   * ganymed.rc:
+     - changed smearing to half of our PSF 0.06
+     - added new examples for setting the starguider calibration
+
+   * ganymed_onoff.rc
+     - changed smearing to half of our PSF 0.06
+     - switched the new feature for a random source position on
+     - added new examples for setting the starguider calibration
+
+   * ganymed_wobble.rc:
+     - changed smearing to half of our PSF 0.06
+     - added new examples for setting the starguider calibration
+     - added example how to control the phi plot
+
+   * mhflux/MHPhi.[h,cc]:
+     - many improvements to the algorithm, it now takes also
+       inhomgeneities into account
+     - restructured the display, display more histograms
+     - increased class version to 2
+
+   * mjobs/MJCut.cc:
+     - enabled acceleration for first and second loop
+
+   * mpointing/MPointingDevCalc.[h,cc]:
+     - allowed to set the starguider offset calibration from the
+       resource file
+
+   * callisto_Dec04Jan05.rc:
+     - replaced Calibration scale factor by usage of
+       resources/calibration_spline.rc
+
+
+
+ 2006/03/13 Markus Meyer
+
+   * ganymed_wobble.rc,ganymed_onoff.rc,ganymed.rc:
+     - changed cuts:
+       wobble: average values from optimisation of 3 Crab 
+               sample (01/05,10/05,12/05), done by Karsten
+       onoff : cuts from 1218 (01/05, highest significance)
+       theta is now 0.22 for both.
+
+
+
+ 2006/03/13 Daniel Hoehne
+
+   * ganymed_wobble.rc,ganymed_onoff.rc,ganymed.rc:
+     - implemented qualitycut in log10(conc) vs. log10(size)
+
+
+
+ 2006/03/13 Markus Meyer
+
+   * resources/calibration_spline.C:
+     - more comments
+
+
+
+ 2006/03/10 Markus Meyer
+
+   * resources/calibration.C:
+     - update from p27 to p39 (spline excluded, still p33 data missing)
+
+
+
+ 2006/03/10 Markus Meyer
+
+   * resources/calibration_spline.C:
+     - correction coefficients for spline data for each period
+
+
+
+ 2006/03/10 Daniel Hoehne
+
+   * datacenter/scripts/insertsequences:
+     - fixed bug
+
+
+
+ 2006/03/09 Daniel Hoehne
+
+   * ganymed_wobble.rc:
+     - changed parameters 1 to 5 in Cut1 to actual values
+
+
+
+ 2006/03/08 Thomas Bretz
+
+   * readdaq.cc, mraw/MRawFileRead.[h,cc], mraw/MRawRunHeader.cc:
+     - added new force-option to foirce output of run-header
+
+
+
+ 2006/03/08 Daniela Dorner
+
+   * datacenter/script/movingrawfiles: 
+     - added moving of files, that are transferred via internet
+     - added removing of empty directories
+
+   * datacenter/db/ganymed.php: 
+     - added links to ganymedplots
+     - added links to sequence.php (instead of links to starfiles)
+     - fixed bug in query
+
+   * datacenter/db/sequence.php: 
+     - added links to plots from callisto and star
+     - fixed bug in query
+
+   * datacenter/db/sequinfo.php: 
+     - added links to sequence.php 
+
+   * datacenter/db/datasetinfo.php: 
+     - added links to ganymed.php 
+
+   * datacenter/db/tabs.php: 
+     - added (includefile for names of tabs of statusdisplays)
+
+
+
+ 2006/03/07 Thomas Bretz
+ 
+   * mcalib/MCalibrateData.cc:
+     - take the bad pixel information into account when calculating the
+       number of saturating pixels!
+
+
+
+ 2006/03/06 Thomas Bretz
+
+   * showplot.cc:
+     - fixed the position were the first argument is converted
+       to lower case. Until this fix no upper case could be used
+       in file names
+
+   * datacenter/macros/plotdb.C:
+     - print also average and RMS of all data.
+
+
+
+ 2006/03/06 Daniela Dorner
+
+   * datacenter/db/ganymed.php: 
+     - added sequences + links to star-plots of sequences
+     - improved layout
+
+   * datacenter/script/makecallistolinks: 
+     - changed condition, when to make the link: only, if the link is 
+       not yet existing, it is done
+     - added resetting of db: if link is done, callisto is resetted
+
+   * datacenter/macros/resetcolumn.C: 
+     - added failure columns to the resetting
+
+
+
+ 2006/03/04 Daniela Dorner
+
+   * callisto.cc: 
+     - changed return values to improve the failure handling in the db
+
+   * datacenter/script/makecallistolinks: 
+     - added 'Pulse is too much to the left, cannot go below 0!' as 
+       reason to use callisto_Dec04Jan05.rc 
+
+   * datacenter/script/dowebplots: 
+     - reduced number of files to be updated by a limitation in 
+       modification time
+
+   * datacenter/db/ganymed.php: 
+     - added plots
+     - effontime s->h
+
+
+
+ 2006/03/03 Thomas Bretz
+
+   * mjobs/MJCut.cc:
+     - added RemoveFromList for srcposrndm in off-data loop
+
+   * mpointing/MSrcPosRndm.[h,cc]:
+     - fixed the scaling. MSrcPosCam has to be in mm
+
+   * ganymed.rc:
+     - added line and comments with new resource 
+
+
+
+ 2006/03/03 Daniel Hoehne
+
+   * callisto_MarApr05.rc:
+     - changed pulse position check ExtractWinLeft to 4.0 and
+       ExtractWinRight to 4.5
+
+
+
+ 2006/03/02 Thomas Bretz
+
+   * callisto.cc:
+     - get result value from pulse pos check
+
+   * mjobs/MJCut.[h,cc]:
+     - added the usage of the new class MSrcPosRndm
+     - added new resource to switch random source position on
+
+   * mjobs/MJPedestal.[h,cc]:
+     - changed return code of Process to int to be able to return
+       the pulse pos check result.
+
+   * mpointing/PointingLinkDef.h, mpointing/Makefile:
+     - added MSrcPosRndm
+
+   * mpointing/MSrcPosRndm.[h,cc]:
+     - added
+
+   * mpointing/MHSrcPosCam.h:
+     - addedn non const getter for fHist
+
+
+
+ 2006/03/02 Daniela Dorner
+
+   * datacenter/db/querymc.php: 
+     - fixed small bug
+
+   * datacenter/db/dowebplots: 
+     - added option -p to the script, to be able to call the script
+       for different programs independently
+     - fixed find
+
+
+
+ 2006/03/01 Daniela Dorner
+
+   * datacenter/db/datacheck.php, datasetinfo.php, sequinfo.php: 
+     - included failure handling columns
+
+
+
+ 2006/03/01 Thomas Bretz
+
+   * mastro/MAstro.cc, mbase/MTime.cc:
+     - added a comment in GetMagicPeriod
+
+   * mpointing/MPointingPos.cc:
+     - added new member function GetString
+     - moved code from Print to GetString
+     - added new function IsInitialized()
+
+   * mjtrain/MJTrain*.[h,cc]:
+     - added data members to change RF setup
+
+   * mpointing/MPointingDevCalc.h, mpointing/MPointingPosCalc.h:
+     - added missing AddToBranchList
+
+   * mpointing/MHSrcPosCam.[h,cc]:
+     - added
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - added MHSrcPosCam
+
+   * mbase/MTask.[h,cc]:
+     - implemented a new data-meber fAccelerator which allows
+       to switch off counting and timing analysis which can be very
+       time-consuming in some circumstances
+
+   * mbase/MTaskList.[h,cc]:
+     - implemented the usabe of MTask::fAccelerator to switch off
+       resetting of all parameter containers which can be very
+       time-consuming
+
+   * mimage/MImagePar.cc:
+     - updated how the units are printed in Print()
+
+   * mjobs/MJCut.cc:
+     - added a new loop to fill the source position of the on-data
+     - the acceleration of the two main loops are disabled because
+       they are not yet tested.
+
+   * datacenter/macros/plotstat.C:
+     - the periods were wrong by one -- fixed.
+
+
+
+ 2006/02/28 Daniela Dorner
+
+   * datacenter/scripts/insertdatasets:
+     - made sure, that backupfiles of the editor are not taken into 
+       account, when dataset files are searched
+
+   * datacenter/db/*.php:
+     - moved user, host and pw of database to the include file 
+       db.php
+
+   * datacenter/db/index.html:
+     - fixed links
+
+   * datacenter/db/querymc.php,magicdefs.php:
+     - added some variables 
+
+   * datacenter/db/runinfo.php,sequinfo.php:
+     - bugfix (incl. TestSources)
+
+   * datacenter/db/sequinfo.php:
+     - changed init values
+
+   * datacenter/db/sequinfo.php, findoffdata.php, magicdefs.php:
+     - added value (relative ontime)
+
+   * datacenter/db/dbstatus.php:
+     - fixed bug
+
+   * datacenter/db/queryrbk.php:
+     - added query field 'Night', to query all entries of one night
+       from the runbook
+
+   * datacenter/db/index-header.html:
+     - added links
+
+
+
+ 2006/02/27 Thomas Bretz
+
+   * macros/optim/optimwobble.C:
+     - fixed a typo (SetThetaCut instead SetAlphaCut), and added the
+       standard Disp-parametrization
+
+   * mhflux/MHEffectiveOnTime.[h,cc]:
+     - added showing the axis range of the time evolution histogram
+
+   * showplot.cc:
+     - fixed a warning in the Hash-switch.
+
+   * mbase/MEnv.cc:
+     - replaced casts in switch by an appended U
+
+   * macros/train/trainseparation.C:
+     - replaced outdated MTTrainRFSeparate by MJTrainSeparation
+
+   * mastro/MAstro.h:
+     - added conversion constants for pc-m and pc-ly
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - fixed typo in comment
+
+   * mimage/MImagePar.h:
+     - minor changes to layout
+
+   * mimage/MHNewImagePar.[h,cc], mimage/MNewImagePar.[h,cc]:
+     - added new image parameters fConcCOG and fConcCore
+     - increased class version of MNewImagePar
+
+   * mimage/MHillasExt.cc:
+     - added some comments
+     - removed an obsolete TMath::Abs around "dist"
+
+   * mranforest/MRanForest.[h,cc]:
+     - the initialization of fTreeHad was done at the wrong moment
+     - replaced a cast int(x+.5) by TMath::Nint
+     - added some additional warning output
+     - added "!" to fTreeHad - it is only for temporary storage used
+       in the histogram classes
+
+   * mranforest/MRanForestGrow.h:
+     - added GetForest
+
+   * mjtrain/MJTrainSeparation.[h,cc]:
+     - added some code for upcomming automatic event selection
+
+   * datacenter/macros/plotstat.C:
+     - improved macro description
+     - added arguments to main function
+
+   * macros/plot/mucal.C:
+     - added
+
+
+
+ 2006/02/25 Daniela Dorner
+
+   * datacenter/scripts/checkfilesforsequavail, checkstardone, 
+     writesequencefiles, buildsequenceentries, dodatacheck, doexclusions,
+     fillcallisto, fillganymed, fillstar,
+     datacenter/macros/writesequencefile.C, filldotraw.C, fillsinope.C
+     buildsequenceentries.C, resetcolumn.C, doexclusions.C, fillcalib.C
+     fillsignal.C, fillganymed.C, fillstar.C: 
+     - implemented, that a missing connection to the database doesn't 
+       cause an failure entry in the database, so that the step is 
+       retried in this case
+     - updated documentation
+
+
+
+ 2006/02/25 Thomas Bretz
+
+   * datacenter/macros/plotstat.C:
+     - added
+
+
+
+ 2006/02/24 Markus Meyer
+
+   * resources/calibration.rc: 
+     - update of correction values for the calibration constants
+       (P31 - P39, without P36!(problems with spline))
+
+
+
+ 2006/02/24 Daniela Dorner
+
+   * datacenter/db/datacheck.php, datasetinfo.php, dbstatus.php,
+     findoffdata.php, include.php, magicdefs.php, runinfo.php, 
+     sequinfo.php, statusrps.php, statussbs.php, statussps.php: 
+     - included failure handling columns
+
+   * datacenter/db/findoffdata.php: 
+     - added DT
+
+   * datacenter/db/statusrps.php: 
+     - fixed bug
+
+   * datacenter/db/sequinfo.php: 
+     - reduced width of menu
+
+   * datacenter/scripts/copyscript: 
+     - added makedir for oldcatalogpath
+
+
+
+ 2006/02/23 Thomas Bretz
+
+   * mjobs/MJSpectrum.cc:
+     - fixed plot for Eý.dN/dE. The spectrum was multiplied with two
+       times the bin-width instead of the absolute energy
+
+
+
+ 2006/02/22 Daniela Dorner
+
+   * datacenter/db/querymc.php: 
+     - added (website to query montecarlo database - first version)
+
+   * datacenter/db/magicdefs.php: 
+     - added some values of montecarlo database
+
+
+
+ 2006/02/17 Daniela Dorner
+
+   * datacenter/scripts/copyscript: 
+     - fixed path length
+
+   * datacenter/macros/fillsources.C: 
+     - added (macro to read source information from catalog files and 
+       insert it into the database)
+
+   * datacenter/db/ganymed.php: 
+     - improved output
+
+   * datacenter/db/index.html: 
+     - added ganymed.php
+     - removed old link
+
+
+
+ 2006/02/17 Thomas Bretz
+
+   * showplot.cc:
+     - fixed path inflation in case of ganymed
+
+   * mjobs/MDataSet.cc:
+     - return kFALSE if requested source wasn't found in catalog
+
+   * mjobs/MJCut.cc:
+     - reformatted output of source to fit in one line
+
+   * mpointing/MPointingPos.[h,cc]:
+     - output source name (title) in Print() if set
+
+
+
+ 2006/02/16 Daniela Dorner
+
+   * datacenter/scripts/checkstardone: 
+     - small improvement in sequence handling
+     - improved logging
+
+   * datacenter/scripts/sourcefile: 
+     - small bugfixes in setstatus function
+
+   * datacenter/scripts/runganymed: 
+     - small bugfix 
+
+   * datacenter/scripts/copyscript: 
+     - fixed path length
+
+   * datacenter/db/ganymed.php: 
+     - added (website to query results for sources/datasets)
+
+
+
+ 2006/02/15 Daniela Dorner
+
+   * datacenter/db/findoffdata.php: 
+     - implemented possibility to query range of dates for 'stardone'
+
+
+
+ 2006/02/15 Daniel Hoehne
+
+   * datacenter/db/magicdefs.php, querycal.php, sequinfo.php:
+     - implemented query for mean signal inner/outer and mean pulsepos
+   * datacenter/db/sequence.php:
+     - implemented query for mean signal inner/outer, mean pulsepos
+       and inhomogeneity
+
+
+
+ 2006/02/15 Daniela Dorner, Daniel Hoehne
+
+   * datacenter/scripts/writesequencefiles,doexclusion,correcttime: 
+     - fixed small bug
+
+
+
+ 2006/02/14 Daniela Dorner, Daniel Hoehne
+
+   * datacenter/scripts/sourcefile: 
+     - fixed small bugs
+
+   * datacenter/scripts/movingrawfiles: 
+     - changed back to moving files without zipping
+
+   * datacenter/scripts/doqualityplots: 
+     - added running of plotdb.C for each datasetfile
+
+   * datacenter/macros/getdolist.C: 
+     - implemented limitation for number of todo files for 
+       SequenceProcessStatus 
+
+   * datacenter/macros/checkfileavail.C,checkstardone.C: 
+     - changed return code in case that files are not available
+
+   * datacenter/scripts/checkfilesforsequavail,checkstardone,sourcefile:
+     - adapted to changed return code in macros
+
+   * datacenter/db/magicdefs.php, querystar.php, sequinfo.php:
+     - implemented query for inhomogeneity
+
+
+
+ 2006/02/13
+
+   * RELEASE 0.9.4.3
+
+
+
+ 2006/02/13 Thomas Bretz
+
+   * callisto.rc:
+     - changed pulse position check ExtractWinLeft to 4.0 and
+       ExtractWinRight to 4.5
+
+   * callisto_Dec04Jan05.rc:
+     - changed pulse position check ExtractWinLeft to 3.0 and
+       ExtractWinRight left at 2.5
+
+
+
+ 2006/02/10 Thomas Bretz
+
+   * mastro/MAstro.cc:
+     - allow for more year in the algorithm calculating easter
+
+   * mcamera/MCameraDC.h, mcamera/MCameraHV.h, mcamera/MCameraTD.h,
+     mcamera/MCameraTH.h:
+     - added a sanity check in GetPixelContent
+
+   * mraw/MRawRunHeader.cc:
+     - fixed output (correct kiB instead of kB)
+
+   * Makefile, Makefile.rules:
+     - implemented the possibility to spread Make through condor
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - new draw-options to rotate the grid and the stars
+
+   * mimage/MHHillas.cc:
+     - set minimum of fDelte to 0 instead of fDistC
+
+   * msignal/MExtractTimeAndChargeSpline.h:
+     - replaced the casts in SetRiseTimeHiGain and StFallTimeHiGain by
+       TMath::NInt
+
+   * mjobs/MDataSet.h:
+     - implemented new functions to check whether the dataset contains
+       a dedicated sequence
+
+   * datacenter/macros/plotdb.C:
+     - implemented the possibility to draw sequences of a dataset in
+       several colors
+
+
+
+ 2006/02/09 Thomas Bretz
+
+   * mreport/MReport.cc:
+     - invented new fake CC report file version 200509300 for a change
+       in the starguider format (the already implemented last values
+       dissapeared again!) which is not noticed in the format version.
+
+   * mreport/MReportCC.cc, mreport/MReportStarguider.cc:
+     - fixed support for ver 200510250
+
+   * mjobs/MJSpectrum.cc:
+     - added fit of un-unfolded spectrum
+
+
+
+ 2006/02/08 Daniela Dorner
+
+   * datacenter/scripts/sourcefile: 
+     - implemented function checklock
+     - bugfix for failure code
+
+   * datacenter/scripts/buildsequenceentries, checkfilesforsequenceavail,
+     checkstardone, doexclusions, fillcallisto, fillganymed, fillstar, 
+     makecallistolinks, runcallisto, runganymed, runstar, 
+     writesequencefiles: 
+     - implemented usage of function checklock
+
+   * datacenter/scripts/copyscript, doqualityplots, dowebplots, 
+     insertsequences, linkmc: 
+     - implemented usage of function checklock
+     - implemented variable $program
+
+   * datacenter/scripts/dodatacheck: 
+     - implemented usage of function checklock
+     - implemented variable $lockfile
+
+   * datacenter/scripts/insertdatasets, mcsequences, processmcsequences: 
+     - implemented usage of function checklock
+     - implemented variables $lockfile and $program
+
+   * datacenter/macros/doexclusions.C, fillganymed.C: 
+     - fixed bug
+
+   * datacenter/macros/fillsinope.C, setstatus.C: 
+     - improved documentation
+
+   * datacenter/scripts/filesondisk: 
+     - implemented finding of zipped files
+
+
+
+ 2006/02/08 Thomas Bretz
+
+   * datacenter/macros/plotdb.C: 
+     - some minor changes to the layout
+
+
+
+ 2006/02/07 Daniela Dorner
+
+   * datacenter/scripts/makecallistolinks: 
+     - fixed bug
+
+   * datacenter/db: 
+     - added (directory with db-websites) 
+
+
+
+ 2006/02/07 Daniela Dorner, Daniel Hoehne
+
+   * datacenter/scripts/sourcefile: 
+     - added failure code variables
+     - changed calling of setstatus.C accordingly
+
+   * datacenter/scripts/buildsequenceentries, checkfilesforsequenceavail, 
+     checkstardone, correcttime, dodatacheck, doexclusions, fillcallisto, 
+     fillganymed, fillstar, runcallisto, runganymed, runstar, 
+     writesequencefiles: 
+     - implemented failure variable
+
+   * datacenter/macros/getdolist.C, setstatus.C, setupdb.C: 
+     - added new/changed columns (fReturnCode, fFailedCode, 
+       fFailedCodeAdd)
+
+
+
+ 2006/02/06 Daniela Dorner
+
+   * datacenter/scripts/fillstar, macros/setstatus.C, getdolist.C: 
+     - fixed bugs
+
+
+
+ 2006/02/03 Daniela Dorner
+
+   * datacenter/scripts/sourcefile: 
+     - implemented two new functions: getdolist, finish
+     - implemented usage of function finish in other functions
+
+   * datacenter/scripts/movingrawfiles: 
+     - implemented zipping of rawfiles
+
+   * datacenter/scripts/buildsequenceentries, checkfilesforsequenceavail,
+     checkstardone, copyscript, correcttime, dodatacheck, doexclusions, 
+     fillcallisto, fillganymed, fillstar, insertdatasets, 
+     makecallistolinks, processmcsequences, runcallisto, runganymed, 
+     runstar, writesequencefiles: 
+     - replaced corresponding pieces of code by the functions getdolist
+       and finish
+     - moved variable $date to function getdolist
+     - improved logging
+     - generalized variables $lockfile and $todofile
+
+
+ 2006/02/03 Daniela Dorner, Daniel Hoehne
+
+   * datacenter/scripts/sourcefile: 
+     - fixed small bugs
+
+   * datacenter/scripts/runcallisto: 
+     - small bugfix
+     - improved logging
+
+   * datacenter/scripts/insertdatasets: 
+     - removed not needed variable
+
+   * datacenter/macros/getdolist.C: 
+     - small bugfix
+
+
+
+ 2006/02/02 Daniela Dorner
+
+   * datacenter/scripts/linkmc: 
+     - changed numbering of P and C run in linking
+
+   * datacenter/scripts/sourcefile: 
+     - moved to root-version root_v4.04.02g
+
+
+
+ 2006/02/01 Daniel Hoehne
+
+   * datacenter/scripts/buildsequenceentries, checkfilesforsequenceavail, 
+     checkstardone, correcttime, dodatacheck, doexclusions, fillcallisto, 
+     fillganymed, fillstar, writesequencefiles: 
+     - adapted usage of function setstatus
+
+
+
+ 2006/01/31 Daniela Dorner
+
+   * datacenter/macros/setstatus.C, getdolist.C: 
+     - adapted macros to changes in new columns (fFailedCode, 
+       fFailedComment)
+
+   * datacenter/macros/setstatus.C: 
+     - added "noreset" for column fStartTime (is needed so that runtime 
+       is available in case of failure)
+
+   * datacenter/macros/setupdb.C: 
+     - added new columns
+
+   * datacenter/scripts/runcallisto, runganymed, runstar: 
+     - implemented failure handling 
+
+   * datacenter/scripts/sourcefile: 
+     - implemented new functions to set status values
+
+
+
+ 2006/01/30 Daniel Hoehne
+
+   * datacenter/scripts/buildsequenceentries, checkfilesforsequenceavail, 
+     checkstardone, correcttime, dodatacheck, doexclusions, fillcallisto, 
+     fillganymed, fillstar, runcallisto, runganymed, runstar, sourcefile, 
+     writesequencefiles: 
+     - added function setstatus in sourcefile
+     - changed calling of setstatus.C in setstatus
+     - implemented variable $program to generalize usage of setstatus
+     - replaced corresponding piece of code by function setstatus
+     - fixed some typos
+
+
+
+ 2006/01/30 Daniela Dorner
+
+   * datacenter/macros/setstatus.C, getdolist.C: 
+     - adapted macros to the improvement of failure handling in the 
+       automatic analysis (added columns fFailed, fStartTime, 
+       fFailedTime)
+
+
+
+ 2006/01/27 Thomas Bretz
+
+   * mjobs/MDataSet.cc:
+     - improved a warning output
+
+
+
+ 2006/01/23 Thomas Bretz                             
+
+   * mbase/MTime.cc:
+     - removed a sanity check in GetStringFmt. It work's quite nice
+       in the DC but crashes on my Laptop (which is not so important)
+
+
+
+ 2006/01/10 Daniela Dorner
+
+   * datacenter/macros/*.C, datacenter/script: 
+     - updated and added documentation
+     - improved logging
+     - fixed small bugs
Index: branches/Mars_McMismatchStudy/Changelog.07
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.07	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.07	(revision 17960)
@@ -0,0 +1,4524 @@
+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 -*-*-
+
+ 2007/12/28 Daniela Dorner
+
+   * datacenter/db/builddatasets.php:
+     - added warning in case of different dt of on sequences
+     - added comments
+
+
+
+ 2007/12/21 Daniela Dorner
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/menu.php, 
+     datacenter/db/runinfo-aio.php: 
+     - implemented link to runbook of the according night
+
+
+
+ 2007/12/20 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - changed the scale of Unsuitable01
+
+
+
+ 2007/12/19 Thomas Bretz
+
+   * callisto.cc:
+     - commented out the obsolete unsused code for moon observations
+
+   * mbase/MStatusDisplay.cc:
+     - added (obsolete?) initialization of fBar suggested by valgrind
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - replaced some floats in sums by doubles
+
+   * mextralgo/MExtralgoSpline.[h,cc]:
+     - fixed some typos in a comment
+     - removed the first and obsolete argument (sat) from the
+       Extract member function
+     - initialize x1 and x2 in GetMax as suggested by valgrind
+       (should not be necessary)
+
+   * mhcalib/HCalibLinkDef.h, mhcalib/Makefile:
+     - removed obsolete MHPedestal class
+
+   * mjobs/MJCalibrateSignal.cc:
+     - resorted includes, removed obsolete ones
+
+   * mjobs/MJPedestal.[h,cc]:
+     - resorted includes, removed obsolete ones
+     - removed obsolete fIsUseHists and corresponding code
+
+   * mjobs/MSequence.cc:
+     - allow also NoMoon in addition to No_Moon (which was anyhow
+       printed if Print was called)
+
+   * mpedestal/MExtractPedestal.cc:
+     - replaced a float in a sum-loop by a double
+
+   * mpedestal/MPedestalCam.[h,cc]:
+     - tiny change to Print function
+     - some improvements to comments
+
+   * mpedestal/MPedestalSubtract.cc:
+     - removed an obsolete cast in memcpy
+     - fixed a bug (the *src-ptr was not increased when no pedestal
+       was given)
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - removed the first argument from call to the Extracy function
+
+
+
+ 2007/12/18 Daniela Dorner
+
+   * datacenter/db/showplots-seq.php, datacenter/db/showplots-ds.php, 
+     datacenter/db/showplots.php, datacenter/db/plotinclude.php: 
+     - implemented function to print home- and help-link
+     - adapted home- and help-link
+
+   * datacenter/db/index-header.html: 
+     - adapted links (H->Home, Docu->Help)
+
+
+
+ 2007/12/17 Daniela Dorner
+
+   * datacenter/db/showplots-seq.php: 
+     - updated length of fields for sequence number range
+
+   * datacenter/db/culminating.php: 
+     - fixed bug (, was missing in call of PrintSubmittedQuery)
+
+   * datacenter/db/statussbs.php: 
+     - fixed bug (link Sequ was wrong, removed fExcludedFDAKEY)
+
+   * datacenter/db/sequinfo-aio.php: 
+     - change in link to runs: before all runs in the range between 
+       fSequenceFirst and fSequenceLast were included in the link, now
+       only the runs belonging to the sequence are displayed
+
+
+
+ 2007/12/14 Daniela Dorner
+
+   * datacenter/db/ganymed.php: 
+     - updated tab numbers for plots Hist and FS
+
+   * datacenter/db/menu.php: 
+     - removed TestFlag from Sequence Menu, as all runs in sequences 
+       are no_test
+     - rearranged Sequence Menu (3x3 instead of 3x4)
+
+   * datacenter/db/index-header.html: 
+     - adapted links to home of db and docu (are poitingin to wiki now)
+
+   * datacenter/db/index.html: 
+     - installed redirect to wiki db website
+
+
+
+ 2007/12/14 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.h:
+     - add Print to conext menu
+
+   * mjobs/MJCalibrateSignal.cc:
+     - add sequence to the output file
+
+   * mjobs/MJCalibration.[h,cc]:
+     - implemented a minimum number of required calibration events
+     - set a proper name to the extractor extracted pedetsl cam before
+       writing to the output file
+     - add sequence to the output file
+
+   * mjobs/MJPedestal.[h,cc]:
+     - removed member function SetMinEvents
+
+   * mjobs/MJStar.cc:
+     - added fSequence to the output file
+     - The pre-Muon cut now also containes a cut on the RelTimeSigma
+       this accelerates the muon processing even more by excluding
+       non-muons as early as possible
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - added a new data meber fCounter to count the processed
+       pedestal events
+
+   * mpedestal/MPedCalcFromLoGain.cc, mpedestal/MPedCalcPedRun.cc:
+     - count the processed pedestal events
+
+   * mpedestal/MPedestalCam.[h,cc]:
+     - added data member fNumEvents to store the number of processed
+       events
+     - improved Print
+     - added Print to context menu
+     - commented out obsolete GetPedestalMin/Max
+     - increased version number by 1
+
+
+
+ 2007/12/13 Thomas Bretz
+
+   * callisto.rc, callisto_Dec04Jan05.rc, callisto_mux.rc:
+      - added comments for the new MinEvents resource
+
+   * mhflux/MHAlpha.cc:
+     - for convinience the minimum of the time- and theta-plot
+       is set to 0
+
+   * mjobs/MJPedestal.[h,cc]:
+     - added a new data member which is used to require a minimum
+       of processed events
+
+   * mtrigger/MFTriggerPattern.[h,cc]:
+     - new functions for processing the sum-trigger flag
+
+   * mtrigger/MTriggerPattern.[h,cc]:
+     - a new bit implemented for the sum-trigger
+
+   * datacenter/compmux:
+     - removed this BINARY. There is no way and it doesn't make any sense
+       (except in a few exceptional cases) to put binaries into the cvs
+
+
+
+ 2007/12/11 Daniela Dorner
+
+   * datacenter/db/tabs.php: 
+     - updated tab names for sequence.php and ganymed.php
+
+
+
+ 2007/12/11 Stefan Ruegamer
+
+   * datacenter/scripts/cutslices
+     - added this script which is used to remove the switching noise out
+       of mux data
+     - removed a bug which prevents correct checking of compmux and mv
+
+   * datacenter/compmux
+     - added this macro
+
+
+
+ 2007/12/10 Thomas Bretz
+
+   * mfileio/MReadReports.cc: 
+     - due to a tiny misconception the last event in trees was skipped
+       simply because no time-stamp for a next event followed...
+       fixed.
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added a new member function FixScale() to fix the scale 
+
+   * mhflux/MHAlpha.cc:
+     - replaced the check whether the significance is >1 by a check
+       whether it is >0. 0 means calculation failed. So all
+       valid data points are shown. If no significance could 
+       be calculated (negative flux) the data point is omitted.
+     - fixed a few drawing problems, which sometimes suppressed the
+       time-histogram even if it contained valid data (this only
+       affected very very short sequences - with a single time bin)
+
+   * mjobs/MDataSet.[h,cc]:
+     - implemented a possibility to use put the sequence inside the
+       dataset file
+     - improved comments
+     - allow to exclude runs from within the dataset file
+
+   * mjobs/MSequence.[h,cc]:
+     - added a new data member to store excluded runs. This is
+       needed to be able to store everything correctly later.
+     - improved comments
+     - added possibility to exclude previously set runs
+     - added a few member functions to check which runs are contained
+     - comment out some currently obsolete member function
+     - allow to read the resources of a sequence file prefixed
+       this is used in the new option of MDataSet
+     - increased class version number accordingly
+
+
+
+ 2007/12/10 Stefan Ruegamer
+
+   * steps.rc
+     - added fCompmux
+     - removed MCRunProcessStatus.Primary: fMCRunNumber and
+       MCSequenceProcessingStatus.Primary: fMCSequenceFirst because
+       these were interfering with $primary
+
+   * datacenter/script/sourcefile
+     - added FCompmux
+
+
+
+ 2007/12/03 Thomas Bretz
+
+   * mdata/MData.h:
+     - added Print to context menu
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added new member functions to apply scaling to off-data
+
+   * mhflux/MHAlpha.[h,cc]:
+     - added new member functions to apply scaling to off-data
+     - added a public member function which allows to reinitiate
+       fitting
+
+   * mhist/MHCamera.cc:
+     - replaced a loop to reset the used pixels by a call
+       to fUsed.Reset()
+
+   * mmuon/MHSingleMuon.[h,cc]:
+     - keep mean and rms of relative arrival time of the fit
+     - increased class Version accordingly
+
+   * mmuon/MMuonCalibPar.[h,cc]:
+     - keep mean and rms of relative arrival time of the fit
+     - increased class Version accordingly
+
+   * mmuon/MMuonCalibParCalc.cc:
+     - copy result of arrival time fit from histogram to storage
+       container
+
+
+
+ 2007/11/28 Daniela Dorner
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php, 
+     datacenter/db/builddatasets.php, datacenter/db/findoffdata.php: 
+     - bugfix (ZdRange was not chosen if fZDMin was 0)
+     - changed <, > to <=, >= in ZDRange query
+
+
+
+ 2007/11/27 Thomas Bretz
+
+   * ganymed.cc:
+     - changed layout of header
+     - expand path name
+
+   * sponde.cc:
+     - expand path names
+     - fixed wrong output
+     - print untouched only if debug-level >= 2
+
+   * mbase/MLog.cc, mbase/MLogHtml.cc:
+     - added some comments
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added option kWeakSourceLogExcess
+
+   * mjtrain/MJTrainDisp.h:
+     - replaces SetTrainParameter by a more flexible SetTrainFunc
+
+   * mpointing/MPointingDevCalc.cc:
+     - added some more comments
+
+
+
+ 2007/10/27 Thomas Bretz
+
+   * mastro/MAstro.[h,cc]:
+     - added new member functio Mjd2Yymmdd and Yymmmdd2Mjd
+
+   * mastro/MAstroSky2Local.cc:
+     - fixed a typo within a comment
+
+   * mbase/MTime.[h,cc]:
+     - added a member function to set a corsika time
+
+   * mimage/MImgCleanStd.h:
+     - added a setter to set post-clean type
+
+   * mmc/MMcEvtBasic.[h,cc]:
+     - made GetParticleName a static member function usable from
+       the outside
+
+   * mpointing/MPointingDevCalc.cc:
+     - added another comment
+
+   * mreflector/MRflEvtHeader.[h,cc]:
+     - added Print function
+
+   * resources/starguider00000001.txt:
+     - fixed comment
+
+   * resources/starguider00089180.txt:
+     - added comment
+
+
+
+ 2007/10/17 Daniel Hoehne
+
+   * datacenter/scripts/mcsequences:
+     - included sql query and update/insert sequence information
+       in MCDB
+     - small bugfixes: corrected grep for epoch and mode
+
+
+
+ 2007/10/16 Daniel Hoehne
+
+   * datacenter/scripts/mcsequences:
+     - bugfix: Now a sequence is written for every folder and
+       particle mode
+
+
+
+ 2007/10/15 Daniel Hoehne
+
+   * datacenter/macros/fillcamera.C:
+     - included more parameters to fill into MCDB
+     - introduced discrimination of P/C and D files
+     - included linking of camera files
+
+   * datacenter/scripts/fillcamera:
+     - added
+
+   * datacenter/scripts/mcsequences:
+     - included handling of more than two P/C runs per rawfile
+       directory
+     - building sequences based on rawfile dirs and MC epochs
+
+   * datacenter/scripts/processmcsequences:
+     - included MC epochs for finding the right callisto.rc
+
+   * mmc/MMcCorsikaRunHeader.h:
+     - included GetViewConeAngle[Inner,Outer], 
+       GetAtmosphericModel
+
+
+
+ 2007/10/13 Thomas Bretz
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added new member functions GetDirections and GetNeighbor
+
+   * mgeom/MGeomCamDwarf.cc:
+     - fixed counting of pixels
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added enumfor direction
+     - added new member function GetDirection
+
+   * mhist/MHCamera.cc:
+     - make sure that fGeomCam is correctly duplicated. The standard
+       clone fails if the MGeomCam clone has been overwritten
+     - added "text" option to Draw
+
+   * mtools/MagicReversi.[h,cc]:
+     - moved GetDirection and GetNeighbor to MGeomCam
+
+
+
+ 2007/10/10 Thomas Bretz
+
+   * mtools/MagicDomino.[h,cc], mtools/MagicReversi.[h,cc],
+     mtools/MagicShow.[h,cc], mtools/MagicSnake.[h,cc],
+      mtools/MineSweeper.[h,cc]:
+     - added a constructor supporting any MGeomCam
+
+   * mtools/MagicJam.h:
+     - removed some new function from the context menu
+
+
+
+ 2007/10/08 Thomas Bretz
+
+   * macros/tutorials/mirrordelay.C:
+     - some layout improvements
+
+   * mhist/MHCamera.cc:
+     - the scale displayed in deg was rounded... removed rounding.
+
+
+
+ 2007/10/07 Thomas Bretz
+
+   * datacenter/macros/plotoptical.C:
+     - do not display the Tuorla points anymore
+
+   * datacenter/macros/plotdb.C, datacenter/macros/plotoptical.C,
+     datacenter/macros/plotrundb.C:
+     - fixed group by (seems it had trouble with the newer sql server)
+
+
+
+ 2007/10/05 Thomas Bretz
+
+   * sponde.rc, sponde_onoff.rc:
+     - fixed a bug. Must be Spectrum now instead of MJSpectrum
+
+   * mbase/MReadSocket.cc:
+     - do not create an explicit TDatime instance
+
+   * mjobs/MJSpectrum.cc:
+     - fixed a problem with writing the Dataset to the file
+
+   * mpointing/MPointingDevCalc.cc:
+     - added a comment about AMC focussing
+
+   * mtools/MCalendar.[h,cc]:
+     - made DrawImage a static function
+
+
+
+ 2007/09/17 Thomas Bretz
+
+   * mbase/MEvtLoop.cc, mbase/MStatusDisplay.cc, mjobs/MJSpectrum.cc:
+     - do not create an instance of TDatime if not necessary
+
+   * mbase/MStatusDisplay.cc, mfileio/MReadTree.cc:
+     - improvements in inf debugging levels
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - removed a double brace in an output
+     - more acurrately print the new formula/slope when set
+
+   * mjobs/MJSpectrum.cc:
+     - improved output in case of an error
+     - added text to describe the two example spectra
+     - write MC dataset to output
+
+
+
+ 2007/09/12 Markus Meyer
+
+   * resources/calibration_spline.rc:
+     - update of the correction factors from the muon 
+       calibration for the MUX data
+
+
+
+ 2007/09/07 Thomas Bretz
+
+   * mbase/MEvtLoop.cc:
+     - added a newline before the "Instantiated" message
+
+   * mbase/MLog.cc, mbase/MLogManip.h:
+     - added a green level inf2 and inf3 (4 and 5)
+     - shifted the blue dbg level to 6
+
+   * mbase/MParList.cc, mbase/MTaskList.cc, mfileio/MReadTree.cc,
+     mjobs/MDataSet.cc, mjobs/MSequence.cc, mraw/MRawRunHeader.cc:
+     - made use of the new inf-levels. This gives a shorter, thus
+       more readable, output at normal circumstances
+
+   * mjobs/MJSpectrum.cc:
+     - added a comment
+
+   * mpedestal/MExtractPedestal.cc, msignal/MExtractor.cc:
+     - improved output in case of non matching windows
+
+
+
+ 2007/09/06 Daniela Dorner
+
+   * datacenter/db/resetseq.php: 
+     - added IP addresses
+     - added project name and start time to list
+     - added color coding
+     - improved output
+     - added mars version to output
+
+
+
+ 2007/09/06 Stefan Ruegamer
+
+   * datacenter/scripts/copyscript
+     - updated server from apollo to dc09
+     
+   * datacenter/scripts/movingrawfiles_OK
+     - set execute permissions
+
+
+
+ 2007/09/05 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - updated some ranges
+
+   * callisto.cc, star.cc, ganymed.cc, sponde.cc:
+     - updated to allow --rc=
+     - moved execution of jobs into individual block if not already done
+
+   * mbase/MEnv.[h,cc]:
+     - added new member function TakeEnv to take resources from MArgs
+
+   * mpedestal/MExtractPedestal.cc:
+     - made sure that the program doesn't (sould not?) crash whenever
+       a lower bound is given which is much too large
+
+   * mpointing/MPointingDevCalc.cc:
+     - added comments from the runbook about mirror focussing
+       beginning of August
+
+
+
+ 2007/09/05 Daniela Dorner
+
+   * datacenter/db/resetseq.php: 
+     - added (website to reset sequences in the database)
+
+   * datacenter/db/index.html: 
+     - added link to resetseq.php
+
+
+
+ 2007/09/03 Thomas Bretz
+
+   * RELEASE 2.0
+
+
+
+ 2007/09/03 Thomas Bretz
+
+   * mbase/MEnv.cc:
+     - made the path of the including file the base directory for
+       the includes
+     - replaced "not touched" by "untouched"
+
+   * mjobs/MJSpectrum.cc: 
+     - added "Disp" tab
+
+   * mpointing/MPointingDevCalc.[h,cc]:
+     - added a lot of comments
+     - allow to set different pointing models depending on the runnumber
+     - changed default for non working starguider to 0/0
+
+   * macros/traindisp.C, macros/trainenergy.C:
+     - added some comments
+     - fixed some comments
+
+   * ganymed.rc, ganymed_onoff.rc ganymed_wobble.rc:
+     - updated with the updated starguider calibrations
+
+   * resources/starguider*.txt:
+     - updated
+
+
+
+ 2007/09/02 Thomas Bretz
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - tiny changes
+
+   * mastro/MAstroCatalog.cc:
+     - sanity check in Paint for !fRaDec.IsValid
+
+   * mastro/MVector3.h:
+     - added a getter for validity
+
+   * mpointing/MPointing.[h,cc]:
+     - added fPx/fPy and fDx/fDy
+     - added enum for adressing the array
+     - added getter for new variables
+     - improved output in Load (only print if valid)
+
+   * mpointing/MPointingDev.h:
+     - changed units of fDev* from mm to deg
+     - added setter for fDevX/Y
+
+   * mpointing/MSrcPosCalc.cc:
+     - convert GetDevXY from deg to mm
+
+   * star_mux.rc:
+     - added (one bin less for fitting the effective on-time)
+
+
+
+ 2007/08/31 Thomas Bretz
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - changed default values for starguider 
+     - changed quality cuts (more efficiency at higher energy/sizes, 
+       better spark suppression)
+     - added default for the starguider-calibrations
+     - added more examples how to use CalcDisp
+
+   * ganymed.cc:
+     - added new command-line option "--dataset"
+
+   * mbase/MParContainer.[h,cc]:
+     - added a lot of comments
+     - allow an empty prefix in GetEnvValue
+     - added GetEnvValue2
+
+   * mjobs/MDataSet.[h,cc]:
+     - added and updated comments
+     - moved code from constructor to Init
+     - added new constructor
+     - added support for collections of datasets in one file
+     - wobble mode is now set or unset automatically if not overwritten
+     - IsValid now also check if OnSequences are defined
+
+   * mjobs/MJCut.cc:
+     - improved the check after adding sequences for the first loop
+
+
+
+ 2007/08/31 Stefan Ruegamer
+
+   * datacenter/scripts/runstar
+     - added linking of different star.rc files according the data type
+
+
+
+ 2007/08/30 Thomas Bretz
+
+   * sponde.cc:
+     - changed window name from sequence to ganymed-file
+
+   * mdata/MDataMember.cc, mpointing/MSrcPosCorrect.cc:
+     - fixed a typo in the comment
+
+   * mfilter/MFEvtNumber.cc:
+     - call TTree::SetEstimate as suggested by the class description
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - fixed some comments
+     - further improved  Print-output
+
+   * mjobs/MJCut.cc:
+     - fixed a typo in the output
+
+   * mpointing/MPointing.cc:
+     - added possibility to add comments starting with #
+
+   * mraw/MRawRunHeader.cc:
+     - fixed a small problem in the Print-output
+
+
+
+ 2007/08/28 Thomas Bretz
+
+   * mbase/MEnv.[h,cc]:
+     - added handling an Include-resource. Note, that there is no
+       check for recursions, they can crash your program.
+
+   * sponde.cc:
+     - check for batch mode and no output file
+     - changed title
+     - moved HasWritePermission to MJSpectrum.cc
+
+   * mdata/MDataPhrase.cc:
+     - fixed a bug which caused a variable (eg. [0]) at the beginning
+       of a line not be detected correctly
+
+   * mhbase/MHn.cc:
+     - added some comments
+
+   * mhflux/MHDisp.[h,cc]:
+     - changed axis titles from x/y to dx/dy
+     - changed cutting out a part of the cake into stamping a hole
+       at the source position (currently with a fix PSF!)
+     - for the moment display everything in Wobble-mode (to be fixed!)
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - some cosmetics to output
+
+   * mjobs/MJCut.cc:
+     - check if output file is writeable (necessary in on/off mode
+       to detect that incident before filling the source plot)
+
+   * mjobs/MJob.cc:
+     - added a comment
+     - fixed a bug in HasWritePermission (it must be fOverwrite not
+       !fOverwrite)
+
+   * mjobs/MJSpectrum.cc:
+     - replaced #cdot by a dot (it seems it is not supported anymore??)
+     - set a proper display name
+     - print an error message if writing the result failed
+
+   * mjtrain/MJTrainDisp.[h,cc]:
+     - a further small step to unify all MJOptim classes
+     - let the user change the theta-cut for the displayed efficiency
+
+   * macros/train/traindisp.C:
+     - added comment about new SetThetaCut
+
+   * mjtrain/MJTrainEnergy.[h,cc]
+     - a further small step to unify all MJOptim classes
+     - removed obsolete columns for Impact and TelescopeTheta
+       (MHEnergyEst doesn't read from the matrix here)
+     - set palette
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - replaced CalcXYinCamera by MAstro::GetDistOnPlain. It has the
+       same accuracy and is not remarkably slower
+
+   * mpointing/MSrcPosCorrect.[h,cc]:
+     - changed comments
+     - made sure that any possible anti-source position in the camera
+       is handled correctly (maybe we should move it before
+       MSrcPosCalc and skip the anti-source here???)
+
+
+
+
+ 2007/08/27 Markus Meyer
+
+   * mmuon/MHMuonPar.cc:
+     - Reference lines changed
+
+
+
+ 2007/08/27 Thomas Bretz
+
+   * resources/starguider00000001.txt, resources/starguider0085240.txt,
+     resources/starguider00089180.txt:
+     - added more starguider calibration files
+
+   * resources/starguider.txt:
+     - removed obsolete old one
+
+
+
+ 2007/08/26 Thomas Bretz
+
+   * mranforest/MRFEnergyEst.[h,cc]:
+     - removed obsolete files
+
+
+
+ 2007/08/25 Thomas Bretz
+
+   * sponde.cc:
+     - check for write permissionbefore job is started
+
+   * sponde.rc, sponde_onoff.rc:
+     - cosmetics to comment
+
+   * macros/train/traindisp.C:
+     - better order of comments
+
+   * manalysis/MParameterCalc.[h,cc]:
+     - print name of output container
+     - allow setting name of output container from resource file
+
+   * mbase/MStatusDisplay.cc:
+     - added sanity check for batch mode in SetProgressBarPosition
+
+   * mfbase/MFDataPhrase.[h,cc]:
+     - initialize new data member fDefault in constructors
+     - increased class version number by one
+
+   * mhbase/MH.cc:
+     - do not divide by zero in SetBinomialErrors
+
+   * mhbase/MH3.[h,cc]:
+     - automatically set more log labels and suppress exponent
+
+   * mhbase/MHn.cc:
+     - set margin between new tabs in Divide to a small value
+
+   * mhflux/MHCollectionArea.cc:
+     - new default energy binning based on the typical simulation range
+
+   * mhflux/MHEnergyEst.cc:
+     - new default energy binning based on the typical simulation range
+     - set the impact binning to one bis as a default for speed
+       reasons. It is normally not used at all
+     - added two blue lines at the zero-bias level for convinience
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - small cosmetics to Print-output
+
+   * mjobs/MJCut.cc:
+     - renamed the instances of the Calc* tasks
+     - store all three taskenvs
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - handle a CalcDisp-task gotten from ganymed properly
+     - do not reexecute CalcHaronness for data
+     - renamed the instances of the Calc* tasks
+
+   * msql/MSQLMagic.cc, msql/MSQLServer.cc:
+     - delete created TSQLRow. They are not deleted automatically
+
+
+
+ 2007/08/24 Thomas Bretz
+
+   * mdata/MDataMember.cc:
+     - added a sanity check in GetValue()
+
+   * mdata/MDataPhrase.[h,cc]:
+     - Allow to use MDataPhrase also with variables x,y,z and t
+     - Allow evaluation of the function with given x,y,z,t 
+
+   * mjobs/MJSpectrum.h:
+     - commented IntermediateLoop, was unused
+
+   * mjoptim/MJOptimize.cc:
+     - added two comments
+
+   * mjtrain/MJTrainDisp.cc:
+     - added new MHn to display more information about the test
+     - improved result-histogram
+     - added PreTasks, PostTasks and TestTasks to testing tasklist
+     - some fixes if the user closed the display
+
+   * mjtrain/MJTrainEnergy.cc
+     - added new MHn to display more information about the test
+     - allow to set fTrainParameter and fResultFunction from
+       outside, this allows to train on whatever you like
+     - added TestTasks to testing tasklist
+     - added new member functions to set Train parameter and
+       evaluation function: SetTrainLog/Log and SetTrainFunc
+
+   * mranforest/MRanForestCalc.[h,cc]:
+     - changed evaluatio function-type from TF1 to MDataPhrase
+
+   * mraw/MRawEvtData.cc:
+     - initialize fNumBytesPerSample with 1
+
+   * mraw/MRawRunHeader.[h,cc]
+     - set default FADC type to 1 (Siegen)
+     - it turned out that we use 1/2 and not 0/1 as expected
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - updated some comments
+     - added new CutT
+
+   * sponde.rc, sponde_onoff.rc:
+     - updated with thousands of comments
+     - adapted to new sponde respources
+     - added examples for missing resources
+     - added a new energy estimation formula which can be used instead
+       of using the random forest
+
+   * macros/optim/optimonoff.C, macros/optim/optimwobble.C:
+     - updated with the latest cuts and some comments
+
+   * macros/train/traindisp.C:
+     - updated with the latest knowledge and cuts
+     - updated with more examples
+
+   * mfbase/MFDataPhrase.[h,cc]:
+     - added a default value which can be used if no phrase is setup
+     - allow to use a constrcutor without phrase but name and title
+
+   * mjobs/MJCut.cc:
+     - removed SetAllowEmpty from CutT
+     - initialize CutT with no phrase instead of an empty one
+
+   * mjobs/MJSpectrum.h:
+     - removed obsolete function definition for IntermediateLoop
+
+   * mranforest/MRanForestCalc.cc:
+     - if weights are used output the sum of the weights for control
+       purpose
+
+   * datacenter/macros/plotdb.C, datacenter/macros/plotoptical.C,
+     datacenter/macros/plotrundb.C:
+     - delete TSQLRow if allocated
+
+
+
+ 2007/08/23 Thomas Bretz
+
+   * mhbase/MH3.[h,cc]:
+     - added new data members fBins, allowing to set bins from the outside
+     - removed obsolete SetColors
+     - set palette automatically if it is a 2D histogram (more flexible
+       solution pending)
+
+   * mhbase/MHn.cc:
+     - added comments
+     - allow setting of binning without parlist
+     - added functions to set Scale, Log, AutoRange and Sumw2
+     - delete obsolete pads, if any
+
+   * mjoptim/MJOptimizeBase.h:
+     - added new data meber fTestTasks to be executed only for testing
+     - added comments
+
+   * mjtrain/MJTrainRanForest.cc:
+     - removed obsolete code already in comments
+
+   * mranforest/MRanForestCalc.[h,cc]:
+     - added the possibility to set a function which converts the
+       result of the rf. eg "pow(10, x)"
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - replaced fNumSignificantBits by fFadcResolution for compatibility
+     - replaced fFreqSampling by fSamplingFrequency for compatibility
+     - increased ClassVersion to 9
+
+   * mraw/MRawEvtData.cc:
+     - initialize fNumBytesPerSample to 1 to make it compatible with reading
+       old MC files.
+
+   * mjobs/MJSpectrum.cc:
+     - added control plot for the residual of Energy
+     - fixed the "Overflow-Bug". It was a loop from o to <n, while histogram
+       bins are from 1 to ==n
+
+
+
+ 2007/08/22 Thomas Bretz
+
+   * mbase/MEnv.cc:
+     - changed title print out for untouched resources
+
+   * mhbase/HBaseLinkDef.h, mhbase/Makefile:
+     - added new class MHn
+
+   * mhbase/MH.[h,cc]
+     - changed start bin to search for GetRange
+     - added GetRangeX and GetRangeY member functions
+     - added GetRangeUserX and GetRangeUserY member functions
+     - added default to SetPalette
+
+   * mhbase/MH3.[h,cc]:
+     - chnaged to tokenize the name allowing to have different
+       Binning names for all axes
+     - added a style bit which allow to auto scale an axis if the
+       histogram is finally filled
+     - replaced 9999 with -1 in ProfileX/Y
+     - moved SetLog from Paint to Draw
+     - increased class version
+
+   * mhflux/MAlphaFitter.cc, mhflux/MHAlpha.cc, mhflux/MHCollectionArea.cc,
+     mhflux/MHEffectiveOnTime.cc, mhflux/MHEnergyEst.cc,
+     mreflector/MHReflector.cc:
+     - replaced 9999 with -1 in ProjectionX/Y/Z
+     - replaced 9999 with -1 in ProfileX/Y
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - tiny change to output of Print
+
+   * mjobs/MJCut.cc:
+     - added a new Tab CuT displaying VsSize a second time, but with a 
+       user definable cut "CutT" applied
+
+   * mjobs/MSequence.[h,cc]:
+     - added "Comment" to resources
+     - increased class version nimber
+
+   * mmuon/MHMuonPar.cc:
+     - enable all grids
+
+   * mimage/MNewImagePar.cc:
+     - Set fConcCOG to 0 if smaller 0. This produces at least a defined
+       value (-inf) when the logarithm is calculated, which is better
+       than an undefined one (NaN).
+
+
+
+ 2007/08/22 Markus Meyer
+
+   * datacenter/macros/fillstar.C
+     - changed reference values for muon analysis according to
+       the large muon sample with old image cleaning (Mars-1.2) and 
+       smaller integration region (0.75 to 1.2)
+
+   * resources/calibration.rc
+     - changed correction coefficients due to new reference values
+
+   * resources/calibration_spline.rc
+     - changed correction coefficients for MUX
+
+   * mmuon/MHMuonPar.cc
+     - changed FHistBraod from ArcWidth/Radius vs. Radius to 
+       ArcWidth vs. Radius
+
+   * datacenter/macros/fillstar.C
+     - changed reference values for muon analysis again according to
+       the large muon sample with time image cleaning (for new release) 
+       with integration region 0.75 to 1.2
+
+
+
+ 2007/08/22 Stefan Ruegamer
+
+   * datacenter/scripts/runcallisto
+     - modified staging of files
+
+   * datacenter/scripts/runstar
+     - corrected server and added logfile entry for staging of files
+
+
+
+ 2007/08/21 Thomas Bretz
+
+   * mpointing/MHSrcPosCam.[h,cc]:
+     - we now buffer the events instead of average them. This removes
+       strange (fake) events near the camera center in wobble mode
+
+
+
+ 2007/08/21 Markus Meyer
+
+   * datacenter/macros/fillstar.C
+     - changed reference values for muon analysis according to
+       the large muon sample with time image cleaning and smaller 
+       integration region (0.8 to 1.2)
+
+   * mmuon/MHMuonPar.cc
+     - changed fgIntegralLoLim from 0.7 to 0.8
+
+
+
+ 2007/08/21 Stefan Ruegamer
+
+   * datacenter/scripts/movingrawfiles_OK
+     - removed rmdir -p option
+     
+   * datacenter/scripts/runcallisto
+     - added staging of files
+
+
+
+ 2007/08/20 Stefan Ruegamer
+
+   * datacenter/scripts/setup
+     - changed number of allowed processes
+
+   * datacenter/scripts/movingrawfiles
+     - changed login server from apollo to dc09
+     - removed lines for moving files from fromlapalma as the transfer
+       is not working anymore with finished files
+     - added comment
+
+   * datacenter/scripts/movingrawfiles_OK
+     - script for moving files according to the new "_OK" structure in
+       the fromlapalma folder
+       
+   * datacenter/scripts/checkmd5sum
+     - added automatic detection of the L number
+     - added check for already existing output files
+     - added description
+     
+   * resources/calibration_spline.rc
+     - added factors for period 56 and 57 (same value as for 55)
+
+
+
+ 2007/08/20 Thomas Bretz
+
+   * .rootrc:
+     - added some comments about defaults
+     - set the ShowEventStatus for the canvases to yes as default
+
+   * sponde.cc:
+     - removed the refill option (it was just a dummy)
+     - removed the accurate option. It didn't give more accurate 
+       results at all
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added an update option to SetProgressBarPosition
+
+   * mhflux/MMcSpectrumWeight.[h,cc]:
+     - allow to give a container name to GetFormula*
+     - changed default for spectral slope from -9 to -99
+     - allow to give integral range to GetSpec*Integral
+     - added a new member function CompeleteEnergySpectrum which completes
+       a simulated spectrum starting at an energy fEnergyMin down to
+       an energy emin.
+     - added two options ("new" and "old") to Print function
+     - do not stop anymore if lower energy boundary changes
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - cleaned the code in general
+     - removed fRefill (was not used in the code at all)
+     - added MJSpectrum to global ListOfCleanups to handle
+       the display more properly
+     - removed reading of the first (it was the second!) 
+       MMcCorsikaRunHeader. It is now read for each file individually
+     - The read monte carlo events are now weighted with the mc
+       production area (events per area)
+     - incomplete (to lower energies) spectra are completed
+     - removed accurate mode, it was not more accurate
+     - we fit the spectrum now from the first to the last bin
+     - for comparison crab and 1553 are plotted
+     - changed the processing such that first the MCs are processed
+       and then the spectrum is refilled
+     - now the MC distribution from OriginalMC is read only once
+     - added new tab showing the basic event distribution
+
+   * callisto.cc, star.cc, ganymed.cc, sponde.cc, mars.cc, showplot.cc:
+     - some improvements in case of wrong number of arguments
+
+
+
+ 2007/08/19 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - fixed the fix of the strange crashes. Now fBatch is added to
+       the ListOfCleanups instead of removing the newly created canvas
+       from the global list of canvases
+
+   * mimage/MHHillas.cc, mimage/MHHillasExt.cc, mimage/MHHillasSrc.cc,
+     mimage/MHImagePar.cc, mimage/MHNewImagePar.cc:
+     - enables a lot of grids
+
+   * mhbase/MBinning.[h,cc]:
+     - addec constructor with a TArrayD
+
+   * mhbase/MH.[h,cc]:
+     - added two new member functions GetRange and GetRangeUser
+
+   * mjoptim/MJOptimizeDisp.[h,cc]:
+     - added new option UseThetaSq
+
+   * mjoptim/MJOptimizeEnergy.[h,cc]:
+     - added possibility to use also logarithmic fits
+
+   * mmc/MMcCorsikaRunHeader.cc:
+     - improved Print function
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - initialize rise and fall time as suggested by valgrind
+
+   * mtools/MChisqEval.[h,cc]:
+     - implemented the possibility to use weights
+
+
+
+
+ 2007/08/18 Thomas Bretz
+
+   * sponde.cc:
+     - added new option --force-theta
+
+   * mbase/MEnv.[h,cc], mjobs/MSequence.[h,cc], mjobs/MDataSet.[h,cc]:
+     - GetName noe returns only the filename not the whole path. The
+       old behaviour made it impossible to access the container from
+       the file.
+     - GetRcName now returns the whole path/name.
+     - Print now outputs also path and file-name
+
+   * mfileio/MReadTree.cc, mfileio/MWriteRootFile.cc:
+     - fixed typos in comments
+
+   * mhflux/MHCollectionArea.cc:
+     - reset fCorsikaVersion to 0 in PreProcess
+     - print old and new Cosika version if mismatch is found
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - replaced the %.16f by %.16e. This is more accurate in cases
+       with high exponents
+     - added some sample/test code to weight the Zenith Angle
+       according to the sin-distribution produced by Corsika.
+       Currently not in use
+
+   * mjobs/MJSpectrum.cc:
+     - removed the simple/accurate mode. There is now reason why
+       the previous "accurate"-mode should be more accurate at all.
+       It is only slower
+     - Reading the OriginalMC tree now is done such that the
+       events are properly weighted by the production area. This
+       allowes to use different impact paramters from dfferent files.
+     - a check has been implemented which compared the zenith angle
+       distribution of the data and the resulting monte carlo data.
+       Execution of the program can be forced with a new option.
+     - write more information to output file.
+     - added a new tab showing the vent distribution without weights
+
+
+
+ 2007/08/17 Thomas Bretz
+
+   * sponde.cc:
+     - removed switch for simple and accurate mode
+
+   * mbase/MMath.cc:
+     - fixed a problem in LiMaExc which could result in NaN
+       (if signal and background is 0)
+
+   * mbase/MStatusDisplay.cc:
+     - remove canvases in batch-mode from the global list of canvases,
+       this could result in crahses if two canvases in the display
+       had the same name
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - output the maximum impact found in Finalize
+
+   * mhflux/MHEnergyEst.cc:
+     - made the y-axis in the Eest vs Emc plot logarithmic
+
+
+
+ 2007/08/16 Markus Meyer
+
+   * resources/calibration.rc:
+     - update of muon calibration factors for the periods 41 to 50
+
+
+
+ 2007/08/15 Thomas Bretz
+
+   * mhflux/MHEnergyEst.cc:
+     - exchanged x- and y-contents of Eest vs Emc hist. It turned out
+       that it was wrong.
+
+   * mjobs/MDataSet.[h,cc]:
+     - added member functions AddFiles filling a MDirIter
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - updated the disp-parametrization after fixing the lo-gain bug
+     - fixed a bug in the quality cuts (all showers with saturating
+       hi-gains were removed)
+
+   * mhbase/MH3.cc:
+     - allow to split the histogram name and the binning name
+     - set a different line color in case of the "same" option
+
+   * mjobs/MJCut.cc:
+     - show distribution of observation time for on and off data
+
+   * mjoptim/MJOptimizeCuts.cc, mjoptim/MJOptimizeDisp.cc,
+     mjoptim/MJOptimizeEnergy.cc:
+     - added display to output 
+
+   * macros/optim/optimenergy.C, macros/optim/optimonoff.C,
+     macros/optim/optimwobble.C:
+     - added example how to write output file
+
+
+
+ 2007/08/13 Thomas Bretz
+
+   * mjobs/MJSpectrum.cc:
+     - fixed reading of Binning* from ganymed*.file 
+
+
+
+ 2007/08/11 Thomas Bretz
+
+   * mhflux/MHAlpha.cc:
+     - on special request omega has been removed from the nice plot
+
+
+
+ 2007/08/10 Thomas Bretz
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - fSaturationLimit must be multiplied with GetScale() not with
+       GetMax()... grmpf.
+
+   * mjobs/MJCut.cc:
+     - fixed a bug which caused nonsense effective on-time values
+       for real data since three weeks.
+
+
+
+ 2007/08/06 Thomas Bretz
+
+   * mcalib/CalibLinkDef.h, mcalib/Makefile:
+     - removed obsolete MMcCalibrationCalc
+
+   * mhbase/MH.[h,cc]:
+     - adde ApplyBinning member functions for two- and three-dim hists
+
+   * mimage/MHHillasExt.[h,cc]:
+     - removed plot for max dist
+     - added plot for SlopeL
+     - increased class version number
+
+   * mjobs/MJCut.cc:
+     - added BinningSlope to list of binnings
+     - added BinningM3Trans to list of binnings
+     - added BinningM3Asym to list of binnings
+     - removed BinningMaxDist from list of binnings
+
+   * mjtrain/MJTrainDisp.cc:
+     - renamed TrainDist to Train 
+
+   * mpointing/MHSrcPosCam.cc:
+     - changed default palette from glow1 to pretty
+
+   * mpointing/MSrcPosCam.h:
+     - added a function to return the distance to the camera center
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - updated binnings
+     - replaced old spark-cut by a new one
+
+   * mfilter/MFMagicCuts.[h,cc]:
+     - increased version number to 2
+
+   * mjobs/MJStar.cc:
+     - replaced the old spark-cut with a new one
+
+   * mimage/MHVsSize.cc:
+     - changes some comments
+
+   * mmuon/MHSingleMuon.cc:
+     - skip the "error estimation" step. It is just a multiplication
+       with a fixed value. This doesn't influence enaything. And the
+       absolute avlue of the error is not used at all.
+
+
+
+ 2007/08/03 Thomas Bretz
+
+   * macros/optim/optimdisp.C:
+     - adapted to new parametrization
+
+   * mjtrain/MJTrainDisp.[h,cc]:
+     - some small fixes and changes.
+     - added code (as comment) for training a ghostbuster
+
+
+
+ 2007/08/02 Thomas Bretz
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - made it compile again
+
+
+
+ 2007/07/29 Thomas Bretz
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - reordered pre-cuts
+     - removed conc1-spark cut
+     - changed cut coefficients to new algorithm
+
+   * mars.rc, star.rc:
+     - switched to use new image cleaning
+
+
+
+ 2007/07/28 Thomas Bretz
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - added CutQ 
+     - added some checks for the Zenith angle distribution
+
+
+
+ 2007/07/26 Daniela Dorner
+
+   * scripts/dospectrum: 
+     - bugfix (variable for outpath for ganymed was wrong)
+
+
+
+ 2007/07/26 Thomas Bretz
+
+   * mfilter/MFMagicCuts.cc:
+     - implemented new disp-parametrization
+     - implemented new ghostbusting
+     - implemented possibility to use an external ghostbuster
+     - implemented possibility to use an external disp calculator
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - implemented the cleaning in a recursive way. It should be
+       a little bit faster
+     - implemented post-cleaning using timing information
+     - implemented new options how to treat the removed single 
+       core pixels
+
+   * mjobs/MJCut.cc:
+     - write an external ghostbuster to the output file if available
+
+   * mjtrain/MJTrainEnergy.cc, mjtrain/MJTrainSeparation.cc:
+     - set display name of MRanForestCalc as title instead of name
+
+   * mranforest/MRanForestCalc.cc:
+     - set fTitle as eventloop name instead of fName
+
+   * mimage/MNewImagePar.[h,cc]:
+     - removed the fInner-stuff. It was never good for anything
+       only for space- and time-consumption
+     - increased class-version number by one
+
+
+
+ 2007/07/25 Thomas Bretz
+
+   * scripts/merppupdate:
+     - small fixes
+
+
+
+ 2007/07/24 Thomas Bretz
+
+   * mbase/MEvtLoop.cc:
+     - removed the "Status Display" in front of the window name
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - initialized some more variables in the constructor as suggested
+       by valgrind
+
+   * mjobs/MJCut.cc:
+     - reset number of off-source positions in on-/off-mode to one
+
+   * mjobs/MJob.[h,cc]:
+     - added many comments
+     - simplified the functions for setting a new resource file
+     - replaced some repeated code by new function CombinePath
+     - added new member function HasWritePermission
+
+   * mjoptim/MJOptimize.cc:
+     - set title as window title of eventloop
+
+   * mjoptim/MJOptimizeCuts.cc:
+     - stop if filter is set and it is not MFMagicCuts
+
+   * mjoptim/MJOptimizeCuts.cc, mjoptim/MJOptimizeDisp.cc,
+     mjoptim/MJOptimizeEnergy.cc:
+     - set window title of status display
+
+   * mjtrain/MJTrainDisp.cc, mjtrain/MJTrainEnergy.cc, 
+     mjtrain/MJTrainSeparation.cc:
+     - set window title of status display
+     - check for write permission of the output file
+
+   * mjtrain/MJTrainDisp.[h,cc]:
+     - implemented new plots showing the result in a more
+       convinient way
+     - allow to set a different result value than dist
+
+   * mranforest/MRanForest.[h,cc]:
+     - improvement to output when training. Moved code to a
+       new member function
+
+   * mranforest/MRanForestCalc.cc:
+     - set window title of status display
+   
+   * mtools/MTFillMatrix.[h,cc]:
+     - implemented setting name and title in the constructor
+     - set window title when wvent loop is started to title
+
+
+
+ 2007/07/19 Thomas Bretz
+
+   * mjobs/MJCut.cc:
+     - added a sanity check for one off-position in on/off-mode
+
+   * mjoptim/MJOptimize.[h,cc]:
+     - moved the functions and data-members to set cuts etc to new
+       base class
+     - added setting of pre- and post-tasks to reading the data
+
+   * mjoptim/Makefile, mjoptim/OptimLinkDef.h:
+     - added new MJOptimizeBase
+
+   * mjtrain/MJTrainDisp.cc, mjtrain/MJTrainEnergy.cc,
+     mjtrain/MJTrainSeparation.cc:
+     - changed to use fDebug and WriteDisplay from the new base class
+
+   * mjtrain/MJTrainRanForest.[h,cc]:
+     - moved all data members and setting of pre-/posttasks/-cuts
+       to new base class
+
+   * mjtrain/Makefile:
+     - added include of mjoptim for new base class
+
+   * mjoptim/MJOptimizeBase.[h,cc]:
+     - new base class for optimization and training classes
+
+
+
+
+ 2007/07/18 Thomas Bretz
+
+   * mpointing/MPointingDevCalc.cc:
+     - changed limit for starguide calibration from 87751 to 85240
+
+   * mbase/MContinue.cc:
+     - changed some debug output
+     - fixed a bug if the filter already decided to be skiped
+
+   * mbase/MEvtLoop.cc:
+     - changed RecursiveRemove to use the newly implemented scheme
+
+   * mbase/MParContainer.[h,cc], mbase/MParList.[h,cc],
+     mbase/MTask.[h,cc], mbase/MTaskList.[h,cc]:
+     - improved debug output
+     - added RecursiveRemove member function
+     - removed screen output from Remove function
+     - call RecursiveRemove when something is removed from the list
+
+   * mbase/MStatusDisplay.h:
+     - aaded a new enum kLastElement
+
+   * mbase/MTask.cc:
+     - set kMustCleanup for fFilter
+
+   * mbase/MTaskList.cc:
+     - added debugg code
+
+   * mfileio/MWriteRootFile.cc:
+     - always set kMustCleanup when a TFile is created
+     - make sure RecursiveRemove is called in the correct way
+
+   * mmain/MEventDisplay.h:
+     - fixed the starting index for the first gui element
+
+   * msignal/MExtractor.cc:
+     - added some initializations in the constructor suggested by 
+       valgrind
+
+   * mcalib/MCalibrateData.cc:
+     - improved output
+
+
+
+ 2007/07/17 Thomas Bretz
+
+   * mjobs/MDataSet.cc:
+     - fixed a typo
+
+
+
+ 2007/07/17 Daniela Dorner
+
+   * scripts/dospectrum:
+     - added comments
+     - adapted variables to changes in preparemc
+     - new path for condor submit and dag files (the new condor path in 
+       Mars) 
+
+   * scripts/preparemc:
+     - added comments
+     - added checks
+
+   * condor:
+     - added (directory to store condor submit files)
+
+   * condor/processds.submit:
+     - added (condor submit file to run ganymed for a dataset, used in
+       scripts/dospectrum)
+
+   * condor/processsponde.submit:
+     - added (condor submit file to run sponde for a dataset, used in
+       scripts/dospectrum)
+
+
+
+ 2007/07/15 Thomas Bretz
+
+   * mdata/MDataPhrase.[h,cc]:
+     - fixed a problem with predefined variables (such as used for
+       disp optimization [0])
+     - added a debug member function GetRuleRaw()
+
+   * mhflux/MHAlpha.[h,cc]:
+     - allow to set the watermark from the DrawNice menu entry
+
+   * mjobs/MDataSet.cc:
+     - allow to set the default sequence- and data-path from
+       the dataset file
+
+   * mjobs/MJCut.cc:
+     - set the number of random off-source position for the on-data
+     - fixed a "&", should have been a logical And
+     - make sure that even for MCs the source position is always
+       calculated (this is necessary for more than one wobble position)
+
+   * mjoptim/MJOptimizeDisp.cc:
+     - fixed a typo which made the optimtrain.C fail (kDegToRad does
+       not exist)
+
+   * mjtrain/MJTrainEnergy.cc:
+     - some cosmetics: changed kRad2Deg to TMath::RadToDeg()
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - added a random off-source position calculation to make the
+       more-than-one-off-source-position analysis symmetric in case of
+       on-source 
+     - added lots of comments
+
+
+
+ 2007/07/14 Thomas Bretz
+
+   * mpedestal/MPedestalSubtract.[h,cc]:
+     - fixed the buggy Memcpy function introduced with the last change
+       07/06/17 ;( Fortunately this bug was only effectingt the MC data.
+       The MUX and old FADC data got copied correctly because they are
+       stored in the hi-gain array only, so that the number of hi-gain
+       samples returned in Process is 30/80.
+
+   * mpedestal/MExtractPedestal.cc:
+     - some cosmetics
+
+   * mfilter/MFMagicCuts.cc:
+     - changed some comments
+
+   * mjobs/MJCut.cc:
+     - some cosmetics. Simplified the setting of the scale factor
+
+   * macros/train/traindisp.C, macros/train/trainenergy.C, 
+     macros/train/trainseparation.C:
+     - added some more helpfull comment
+
+
+
+ 2007/07/03 Thomas Bretz
+
+   * mmain/MEventDisplay.[h,cc]:
+     - changed default size
+     - added two butons to switch of the display of the image
+       parameters
+
+
+
+ 2007/06/30 Thomas Bretz
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - when splitting the extraction of the maximum position and the
+       maximum value into two functions (after the last release)
+       an error in extracting the time of a saturating lo-gain pixel
+       was introduced. fixed.
+
+   * resources/starguider.txt:
+     - starguider calbration file added
+
+
+
+ 2007/06/29 Daniela Dorner
+
+   * datacenter/db/sources.php:
+     - fixed bug (test-sources where displayed although 'incl. test 
+       sources was not checked)
+     - added input field for source name (regular expressions)
+     - adapted link for source name from sequinfo.php to 
+       sequinfo-aio.php
+
+   * datacenter/db/menu.php, datacenter/db/builddatasets.php:
+     - moved init of limits (setting of know values) from 
+       builddatasets.php to menu.php (function InitFindOffData), so that
+       the values are also available in sequinfo-aio.php
+
+   * scripts/dospectrum:
+     - completely new version using condor dag
+
+   * scripts/preparemc:
+     - new version
+     - adapted path
+     - giving mars not needed anymore
+     - adapted to 8 digit run numbers for MC
+
+
+
+ 2007/06/29 Thomas Bretz
+
+   * mimage/MHillasExt.[h,cc]:
+     - added new timing parameters fSlopeTrans and fSlopeLong
+     - removed never used parameter fMaxDist
+     - increased accordingly the class version number by 1
+     - replaced the old calculation of the third moments by a
+       numerically more accurate one, by avoiding to calculate
+       to many differences too often.
+
+   * mfilter/MFMagicCuts.[h,cc]:
+     - added the usage of the new SlopeLong parameter for ghostbusting
+
+   * mjobs/MJStar.cc:
+     - preselect events for muon analysis not only by size but also
+       by fConcCOG.
+
+   * mmuon/MMuonSearchPar.[h,cc]:
+     - added a new member function to return the dist (sqrt(x^2+y^2))
+     - to create outliers which are outling as much as possible we
+       let the fit change x and y to infinity.
+
+   * mmuon/MHSingleMuon.cc:
+     - adapted the histogram binning from Siegen slices to ns.
+     - adapted the par limits for the fit to ns
+     - adapted the starting value for the rms to ns
+     - removed the fit range, it was anyhow identical to the histogram 
+     - changed the condition of the pixel index into a condition
+       of the pixel size
+
+   * scripts/merppupdate:
+     - the second argument was silently ignored
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - updates to the latest changes
+
+
+
+ 2007/06/28 Thomas Bretz
+
+   * mars.cc:
+     - added new options to use a sequence file instead of a run
+
+   * mhbase/MFillH.h:
+     - added new member function to reset weights
+
+   * mmain/MEventDisplay.[h,cc]:
+     - added path argument to allow to give an input path
+     - added to allow to setup a sequence file for reading
+
+   * mmain/Makefile:
+     - added inlcude of mjobs for MSequence
+
+   * mbadpixels/MBadPixelsTreat.cc:
+     - we assume now that the maximum arrival time difference 
+       is calibrated already in nanoseconds
+
+   * mcalib/MCalibrateRelTimes.[h,cc]:
+     - the arrival time is now converted from slices into nanoseconds
+
+   * mfilter/MFSoftwareTrigger.cc:
+     - the arrival time is now assumed to be in nanoseconds.
+       the default is changed accordingly from 0.5 to 1.7
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed axis label of PulsePos plot (now in nanosec)
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - allow to set a tasklist as callback to now which n-th 
+       pass of the same task list it is
+
+   * mbase/MTaskList.[h,cc]:
+     - added some code to allow the execution of one task list more
+       than once. This is for example necessary to process three
+       different off-source regions.
+
+   * mjobs/MJCut.[h,cc]:
+     - use the new feature in MTaskList to setup a tasklist 
+       processing the off-source calculation tasklist more than once
+     - added a new data meber fNumOffSourcePos
+     - added a new resource option NumOffSourcePositions
+     - added a new CutQ before Cut0 which takes place before all
+       source posisiton dependant stuff
+
+   * ganymed_onoff.rc:
+     - renamed Cut0 to CutQ
+
+
+
+ 2007/06/27 Thomas Bretz
+
+   * mfilter/MFMagicCuts.cc:
+     - added the missing include of MHillas.h 
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed obsolete MHFadcCam
+     - removed obsolete MHFadcPix
+
+   * msignal/MExtractPINDiode.cc:
+     - commented out some non-compiling code which is not used at all.
+
+   * Makefile:
+     - removed compmux program which entered by chance
+
+
+
+ 2007/06/26 Thomas Bretz
+
+   * mmain/Makefile:
+     - added inlclude path for mfilter
+
+   * mmain/MEventDisplay.cc:
+     - added MFEvtNumber to choose selected preselected events
+
+
+
+ 2007/06/25 Daniel Hoehne
+
+   * datacenter/scripts/linkmc:
+     - implemented execution of fillcamera.C, now first a mc camera file
+       is linked and then fillcamera.C runs for this file
+
+   * datacenter/macros/fillcamera.C:
+     - bugfix: the macro doesn't giva a seg-fault anymore
+       (thanks to Thomas)
+     - arranged the structure more clearly
+
+
+
+ 2007/06/23 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - fixed some Print output
+
+   * mhflux/MHAlpha.cc:
+     - added the missing include of MHillas.h 
+     - removed the obsolete ClassImp(MAlphaFitter)
+
+   * mhflux/MHFalseSource.cc, mimage/MHillasSrc.cc:
+     - added the missing include MHillas.h
+
+   * mimage/MHHillasSrc.cc, mimage/MHillasSrc.h:
+     - removed obsolete include of MHillas.h
+
+   * mpointing/MPointingDevCalc.[h,cc]:
+     - added the real starguider calibration using a pointing model
+       for the strguider. The dates for which the model is valid
+       can still be tuned.
+
+   * mpointing/MSrcPosCalc.cc, mreport/MReportStarguider.cc:
+     - added some comment
+
+
+
+ 2007/06/23 Thomas Bretz
+
+   * mpointing/MPointing.cc:
+     - improved output
+
+
+
+ 2007/06/23 Daniela Dorner
+
+   * datacenter/db/index.html:
+     - added link to showplots-seq.php
+     - added link to builddatasets.php
+
+   * datacenter/db/showplots-seq.php:
+     - added (analog to shoeplots-ds, but instead of dataset number a 
+       sequence range and/or a source name can be chosen)
+
+   * datacenter/db/plotinclude.php:
+     - added function to print pull-down menu for type in showplots*.php
+
+   * datacenter/db/showplots.php:
+     - moved getting of plotname out of if-clauses
+
+   * datacenter/db/showplots-ds.php:
+     - added check if datasetfile is existing
+
+   * datacenter/db/showplots-ds.php, datacenter/db/showplots.php:
+     - added comments
+     - added home-button
+     - added reset-button
+     - changed choosing of type from input field to pull-down menu and 
+       implemented function for this pulldown
+
+
+
+ 2007/06/22 Thomas Bretz
+
+   * mhflux/MHThetaSqN.cc:
+     - fixed optimization (it just didn't work)
+
+   * mpointing/MPointing.[h,cc]:
+     - added some checks in Load
+     - fixed a problem with the constructors (the pointers MUST be
+       initialized to 0)
+     - renamed fNumPar to fgNumPar
+     - Load and Save now return kTRUE or kFALSE
+
+
+
+ 2007/06/22 Daniela Dorner
+
+   * datacenter/db/builddatasets.php:
+     - fixed typo
+
+
+
+ 2007/06/21 Thomas Bretz
+
+   * mjobs/MJCut.cc:
+     - fixed a problem with the Wobble MCs (the could not be processed
+       anymore because they needed MTime for MHSrcPos)
+
+
+
+ 2007/06/20 Thomas Bretz
+
+   * msql/MSQLMagic.[h,cc]:
+     - added a new function InsertUpdate
+
+
+
+ 2007/06/20 Daniela Dorner
+
+   * datacenter/db/showplots.php:
+     - implemented different number of tabs for muxdata for 
+       signal*.root
+
+
+
+ 2007/06/19 Thomas Bretz
+
+   * callisto.rc, callisto_Dec04Jan05.rc:
+     - changed the default values (commented out anyhow) to the real
+       values.
+       
+   * mbase/MEnv.h:
+     - allow printing contents from the context menu
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - replaced kDeviatingTimeResolution by new
+       kDeviatingRelTimeResolution
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - automatically scale the saturation limit to the fadc range
+
+   * mjobs/MJCalibrateSignal.cc:
+     - save resource file into signal*.root file
+     - added some code (still commented) for saving the calibration
+       results
+     - do not fill the bad-pixel plots with MCs
+
+   * mjobs/MJCalibration.cc, mjobs/MJStar.cc, mjobs/MJCut.cc,
+     mjobs/MJSpectrum.cc:
+     - save resource file into signal*.root file
+
+   * mjobs/MJPedestal.cc:
+     - clarified output for "mean pulse time" further
+
+   * mjobs/MJob.cc:
+     - made write container more flexible to allow easier calles
+       if fPathOut contains the file name already
+
+   * mpedestal/MExtractPedestal.cc:
+     - automatically scale the maximum variation and the 
+       maximum value to fit the FADC range
+
+   * msignal/MExtractor.cc:
+     - removed the reset of the saturation limit. Maybe the user 
+       wants to switch off saturation detection.
+     - removed a lot of old code (in comments)
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - scale the saturation limit from the maximum of
+       the FADC range to 256
+     - use the maximum value of the raw position as the input for
+       half the signal height in GetSaturationTime again
+     - calculate maxposhi only if needed
+     - calculate maxrawlo only if needed
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - implemented new format version 9
+     - increased version number by one
+     - added some comments in the header
+     - added a function returning the maximum value of the FADC
+     - changed the GetScale from a calculation to a switch 
+       (faster and easier to understand)
+
+   * callisto_mux.rc:
+     - replaced saturation and lower signal limit in
+       MJPedestalY2.MHCalibrationPulseTimeCam by the defaults
+
+   * mbase/MMath.[h,cc]:
+     - added a function to do a InterpolParab assuming that the
+       x-coordinates are -1, 0, 1
+
+
+
+ 2007/06/18 Thomas Bretz
+
+   * mbadpixels/Makefile:
+     - added include of mraw
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - added some comments
+     - check for MRawRunHeader
+     - calculate max time difference from time in ns
+
+   * callisto.rc callisto_mux.rc, callisto_Dec04Jan05.rc:
+     - changed old value for time difference to 3.0
+     - use the default value (3.0) in all files
+
+   * mbadpixels/MBadPixelsPix.h, mbadpixels/MBadPixelsCam.cc,
+     mcalib/MCalibrationChargeCalc.cc:
+     - renamed kFluctuatingArrivalTimes to kDeviatingAbsTimeResolution
+
+   * mbase/MMath.cc: 
+     - improved (according to the numerical recipes) the calculation
+       of the one value solution. This should also accelerate 
+       execution a bit
+
+
+
+ 2007/06/17 Thomas Bretz
+
+   * mpedestal/MExtractPedestal.[h,cc],
+     mpedestal/MPedestalSubtract.cc,
+     mpedestal/MPedestalSubtractedEvt.[h,cc]:
+     - changed USample_t finally from Byte_t to UShort_t
+     - adapted Memcpy accordingly
+
+   * mraw/MRawEvtData.[h,cc]:
+     - increased class version to 7
+     - added fNumBytesPerSample for simplification
+     - take fNumBytesPerSample into account
+     - changed draw and print option accordingly
+     - changed reading of pixel information (in fact it is a 
+       simplification allowed by the flexible storage format)
+     - added a private GetSample  member function to be used in
+       data access for drawing a pixel
+     - added returning of the scale (2^((numbytes-1)*8))
+     - FIXME: GetPixelContent must be reimplemented!
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - changed according to changes in MRawEvtData to support 
+       flexible daza format
+     - removed a lot of old, obsolete and unsused member functions
+
+   * msignal/MSignalCalc.cc, mpedestal/MHPedestalCor.cc:
+     - changed to use USample_t instead of Byte_t
+     - ToBeFIXED! The saturation limits are still around 2^8
+
+   * callisto_mux.rc:
+     - removed obsolete LoGainSwitch statement
+
+
+
+ 2007/06/16 Thomas Bretz
+
+   * mbase/MGList.cc:
+     - added some sanity checks
+
+   * mbase/MMath.cc:
+     - don't start caluclation if x<mean in GaussProb
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - added new data member for the absulte max signal fMaxSignalAbs
+     - replaced Byte_t for a sample by USample_t set in the header
+       to Byte_t
+     - in the case of random pedestal calculation the MaxPos is 
+       not calculated anymore
+     - scale the pedestal and pedestalrms according to the sample
+       size in the data (the scale is retrieved from the run-header)
+
+   * mpedestal/MPedestalSubtract.[h,cc]:
+     - replaced build-in memcpy by a new Memcpy function which is more
+       flexible depending on the input data format
+     - scale the signal into the range 0-256 according to the
+       scale given by the event header
+     - replaced Byte_t by USample_t
+
+   * mpedestal/MPedestalSubtractedEvt.[h,cc]:
+     - replaced Byte_t by USample_t and set it accordingly to Byte_t
+
+   * mraw/MRawRunHeader.h:
+     - added returning of the scale (2^((numbytes-1)*8))
+
+
+
+ 2007/06/15 Thomas Bretz
+
+   * mpedestal/MPedestalSubtractedEvt.cc:
+     - fixed a bug in the determination of the maximum slice. Only 
+       each second slice was checked. This has been introduced with
+       the last change four weeks ago.
+
+
+
+ 2007/06/15 Daniela Dorner
+
+   * datacenter/db/index-footer.html:
+     - adapted path of validator picture
+
+   * scripts/processsequence:
+     - added sequence number (get it from sequence file) to path name
+       in case only a sequence file is given
+     - added two new command line options: the callisto and star rc can
+       be given now 
+
+
+
+ 2007/06/14 Daniela Dorner
+
+   * scripts/processsequence:
+     - bugfix (getting of runno didn't work in case the outpath 
+       contained a _)
+
+
+
+ 2007/06/13 Thomas Bretz
+
+   * mimage/MImgCleanStd.cc:
+     - print name of MPedPhotCam only if used
+
+
+
+ 2007/06/13 Daniela Dorner
+
+   * datacenter/db/plotdb.php:
+     - enlarged inputs for Set1 and Set2 to 150 (was too short for all
+       sequences of one dataset)
+
+   * datacenter/db/showplots.php:
+     - implemented variable for number of tabs (calib*.root, 
+       signal*.root and star*.root) to simplify future changes
+     - adapted number of tabs for signal*.root
+
+
+
+ 2007/06/12 Thomas Bretz
+
+   * mbase/MTime.[h,cc]:
+     - added new constant kDaySec
+     - use kDaySec where possible
+     - added second argument to SetUnixTime and allow using it ;-)
+     - use SetUnixTime in Set(timeval)
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - made sure that Draw doesn't crash if the hi-gains
+       have saturated but the lo-gains don't exist
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]:
+     - replaced type of SaturationLimit and LowerSignalLimit by UInt_t
+     - accordingly increased class version number
+
+
+
+ 2007/06/12 Daniela Dorner
+
+   * datacenter/db/ganymed.php:
+     - added comment
+
+   * datacenter/db/tabs.php:
+     - corrected tabs for ganymed for wobble
+
+
+
+ 2007/06/11 Thomas Bretz
+
+   * sponde.cc:
+     - added check for validity of resource file
+
+   * mbase/MMath.cc:
+     - small speed improvement to calclation of three solutions
+       for the third order pol.
+     - for a second order pol. set x1 and x2 if it has only one 
+       solution
+
+   * mbase/MMath.h:
+     - speed improvement using ::cbrt instead of pow(x, 1/3)
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - improved output
+
+   * mextralgo/MExtralgoSpline.cc:
+     - speed improvement by using a look up table for often used
+       and identical coefficients
+     - use MMath::SolvePol2 to get the null-points of the first
+       derivative (EvalDerivEq0)
+     - removed a lot of old an obsolete comments
+     - fixed the newly introduced EvlInteg(int, int) -- must
+       return 0 explicitly if a==b
+     - fixed the upward search
+
+
+
+ 2007/05/25 Thomas Bretz
+
+   * callisto.cc, star.cc:
+     - removed obsolete check whether config file exists
+
+   * sponde.cc:
+     - aded check for validity of config file (returns 0xfe if not)
+
+   * mbase/MEnv.[h,cc]:
+     - removed obsolete fName workaround
+     - made sure that also ~ paths are correctly expanded and used
+
+   * mjobs/MJob.cc:
+     - one more sanity check if MEnv is not valid
+
+   * Makefile:
+     - first compile the programs source code and then link the library
+       this make it much faster to debug the code of the program sources.
+
+
+
+ 2007/05/22 Daniel Hoehne
+
+   * datacenter/macros/fillcamera.C:
+     - added (macro to fill mc parameters into the db)
+
+
+
+ 2007/05/22 Thomas Bretz
+
+   * mmuon/MMuonSearchPar.cc:
+     - tiny speed improvement in the fit function
+
+
+
+ 2007/05/22 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - adapted the function finish to avoid removing of non existing 
+       files in case the variable lockfile is empty 
+
+   * steps.rc:
+     - fixed typo
+
+   * datacenter/scripts/checkscriptrunning:
+     - added (script to check if a script is runnning, including 
+       command line option, to allow for several jobmanagers and 
+       zipscripts of one Mars Version) 
+
+
+
+ 2007/05/21 Daniela Dorner
+
+   * datacenter/db/showplots-ds.php:
+     - also off-sequences are plottet now
+     - by plotting the link to the plot in colour, it is marked, whether
+       a on sequence (green) or a off sequence is plotted
+
+
+
+ 2007/05/21 Daniel Hoehne
+
+   * datacenter/tools/resetdataset:
+     - re-implemented fAllFilesAvail=NULL
+
+   * datacenter/macros/fillstar.C:
+     - bugfix: for sparkrate='inf', now 0.00 is filled into the db
+
+
+
+ 2007/05/21 Thomas Bretz
+
+   * msignal/MSignalPix.h:
+     - added missing arrival time in Copy function
+     - added copy constructor
+
+   * msignal/MSignalCam.[h,cc]:
+     - added a function to compare cleanigngs of two objects
+     - added a function to compare the islands in two objects
+     - adde Copy function
+
+   * mjobs/MJStar.cc:
+     - added MHEffictiveOnTime to parlist to get access from the
+       resource file
+
+   * mjobs/Makefile:
+     - added include of mhflux
+
+
+
+ 2007/05/18 Daniela Dorner
+
+   * datacenter/scripts/runcorsika:
+     - added (script to run corsika automatically)
+
+   * datacenter/scripts/runreflector:
+     - added (script to run reflector automatically)
+
+   * datacenter/scripts/runcamera:
+     - added (script to run camera automatically)
+
+   * datacenter/scripts/jobmanager:
+     - added possibility to start separate jobmanager for the MC 
+       processing by giving 'mc' as command line option
+
+   * datacenter/scripts/setup:
+     - added setting for MC production steps
+
+   * datacenter/scripts/sourcefile:
+     - added fail codes for MC production steps
+
+   * steps.rc:
+     - added settings for MC production steps
+     - removed timer table information (this was only neede by the 
+       macro getdolist.C in case of day-wise processing of data)
+
+
+
+ 2007/05/17 Thomas Bretz
+
+   * metralgo/MExtralgoSpline.h:
+     - improved the speed of the integration by simplifying the evaluated
+       term. It has been checked that the result is identical.
+
+
+
+ 2007/05/17 Daniela Dorner
+
+   * scripts/processsequence:
+     - added -v5 to all commands
+
+   * datacenter/scripts/sourcefile:
+     - adapted in function makedir if-clause to avoid removing of non 
+       existing files in case todofile is empty or todfile or lockfile is
+       missing
+
+   * datacenter/scripts/runcallisto, datacenter/scripts/runganymed
+     datacenter/scripts/runstar:
+     - adapted comment (was still about old way to get from the database 
+       what has to be done) 
+
+
+
+ 2007/05/16 Daniel Hoehne
+
+   * datacenter/tools/resetdataset:
+     - several bugfixes (mainly typos, for wobble datasets there was one 
+       colon too much due to no off sequences)
+
+
+
+ 2007/05/16 Thomas Bretz
+
+   * callisto.cc:
+     - switch of storage of job2 only in movie mode
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - do not write the interlaced containers anymore
+       they have no real meaning if only the ones of the last
+       calibration are written
+     - removed obsolete references to MCalibrationPulseTimeCam
+     - changed default writingmode for the signal file to UPDATE
+
+   * mjobs/MJCalibration.cc, mjobs/MJCut.cc:
+     - write display by adding it to the array
+
+   * mjobs/MJPedestal.[h,cc]:
+     - added const qualifier to argument of DisplayResult
+     - removed obsolete WriteResult
+     - added a new function WritePulsePos
+     - call WritePulsePos if PulsePosCheck is enabled
+
+   * mjobs/MJob.[h,cc]:
+     - removed automatic writing of fDisplay from WriteContainer
+     - added a new function WriteDisplay
+
+   * mhcalib/MHCalibrationChargeCam.cc, mpedestal/MExtractPedestal.cc,
+     msignal/MExtractBlindPixel.cc, msignal/MSignalCalc.cc:
+     - replaced GetMax by GetMaxPos
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - use new GetMax returning position and height at once
+
+   * mpedestal/MPedestalSubtractedEvt.[h,cc]:
+     - devided the old function GetMax into GetMax and GetRawMax
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - GetSaturationTime now uses the real maximum as reference not 
+       the maximum of the raw-date
+     - adapted the use of GetMax
+
+   * mextralgo/MExtralgoSpline.h:
+     - added a function which allows the outside world to access the
+       spline
+     - removed Align from EvalInteg, it is done in EvalPrimitive already
+
+   * macros/test/extralgospline.C:
+   - added a macro to test the spline
+
+
+
+ 2007/05/14 Stefan Ruegamer
+
+   * datacenter/scripts/checkmd5sum
+     - added this script which makes an md5sum check of files that have
+       been copied from tape to the directory
+       /magic/datacenter/fromtape. This script will run later auto-
+       matically before movingrawfiles.
+
+
+
+ 2007/05/14 Daniela Dorner
+
+   * datacenter/scripts/checkfilesforsequenceavail:
+     - added missing 'set -C'
+
+   * scripts/processsequence:
+     - added option (now callisto rc can be giving in a command line 
+       option)
+
+
+
+ 2007/05/14 Daniel Hoehne
+
+   * datacenter/db/menu.php, magicdefs.php, querycal.php:
+     - implemented new columns fUnsuitableMax and fDeadMax
+
+
+
+ 2007/05/14 Thomas Bretz
+
+   * RELEASE 1.2
+
+
+
+ 2007/05/14 Thomas Bretz
+
+   * callisto_mux.rc:
+     - cleanup of some comments
+
+   * mjobs/MJCalibration.cc:
+     - fixed the unintentionally removed setting of pedestal 
+       for MPedestalSubtract
+
+   * mpedestal/MPedestalSubtract.cc:
+     - improved output for debugging purpose
+
+   * msignal/MExtractor.[h,cc]:
+     - according to the last changes the version number has been 
+       increased to 9
+
+   * mcalib/MCalibrationCam.cc:
+     - added code to GetPixelContent from MCalibrationPedCam
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - removed obsolete MCalibrationPedCam
+
+   * mhcalib/MHPedestalCam.cc:
+     - Removed references to MCalibrationPedCam use a MCalibrationCam
+       with the name MCalibrationPedCam instead
+
+   * mjobs/MJCalibration.cc:
+     - changed background color in Defects to be able to read
+       the yellow text color
+
+   * mjobs/MJPedestal.cc:
+     - removed obsolete include of MCalibrationPedCam
+
+   * mcalib/MCalibrationPulseTimeCam.[h,cc]:
+     - removed some obsolete Add functions already contained in 
+       the base class
+
+   * mcalib/MCalibrationIntensityBlindCam.[h,cc],
+     mcalib/MCalibrationIntensityQECam.[h,cc],
+     mcalib/MCalibrationIntensityTestCam.[h,cc]:
+     - removed
+
+
+
+ 2007/05/11 Daniela Dorner
+
+   * scripts/processsequence:
+     - added information about the created paths to the output of 
+       Usage()
+     - adapted regular expressions
+     - bugfix in getting date for cc and caco file
+     - bugfix (subsystempath was missing)
+     - exit instead of break, if cc or caco file is missing
+     - merpplogdirectory is created after finding of files now
+     - improved logging
+
+   * datacenter/scripts/setup:
+     - adapted number of processes
+     - removed datacheck
+
+
+
+ 2007/05/11 Thomas Bretz
+
+   * mcalib/MCalibrationChargeCalc.cc, mhcalib/MHPedestalCam.cc,
+     msignal/MExtractBlindPixel.cc:
+     - replaced the call to GetTotalEntries by the product
+       of the number of slices with the number of events of the
+       individual pixel
+
+   * mpedestal/MExtractPedestal.[h,cc], mpedestal/MPedCalcPedRun.[h,cc],
+     mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - unified the summing part of Process() into a new function
+       CalcPixel in the base class
+     - in MPedCalcPedRun individual pixels could be skipped due to 
+       high variations, but it was still divided by the number of events
+       procesed. This let to a pedestal which was a tiny amount too
+       small and gave an small positive offset of the randomly extracted
+       pedestal.
+     - unified the loops over the individual pixels to calculate the
+       pixel-, area-, and sector-defaults for the whole camera into
+       the base-class
+     - moved fNumEventsUsed into the base-class and removed obsolete
+       fUsedEvents
+     - removed obsolete fTotalCounter, use the product of the number
+       of slices and the number of events stored in each individual
+       pixel instead
+     - added some sanity checks not to calculate average and/or rms
+       values if the statistics is too low (division by zero)
+     - for calculating min and/or max values at most places now
+       an int is used. This increases the range for further
+       upgrade to 16bit samples.
+
+   * mpedestal/MPedestalCam.[h,cc]:
+     - removed obsolete fTotalEntries and replaced by fNumSlices
+       because the number of total entries depends on the number of
+       events used for each individual pixel
+     - adapted GetPixelContent accordingly
+     - increased class version to 2
+
+   * manalysis/MCameraData.cc:
+     - added include of TArrayI (previously included from MPedestalCam)
+
+   * mcalib/MCalibrationChargeCam.cc, mcalib/MCalibrationRelTimeCam.cc:
+     - fixed GetPixelContant to give more proper output
+     - reformatted GetPIxelContent code
+     - added const-qualifiers
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibrateSignal.cc,
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc,
+     mpedestal/MExtractPedestal.[h,cc], msignal/MExtractor.[h,cc],
+     msignal/MExtractBlindPixel.cc, msignal/MExtractPINDiode.cc:
+     - removed data members fPedestal and fPedestalsIn respectively,
+       and all referencing functions because it was never used at all
+
+   * mextralgo/MExtralgoDigitalFilter.[h,cc], 
+     mextralgo/MExtralgoSpline.cc
+     msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - made the noise extraction completely random and automatic
+     - gave the noise extraction completely into the hand of 
+       the extractors
+
+
+
+ 2007/05/10 Daniela Dorner
+
+   * datacenter/scripts/runcallisto:
+     - bugfix (typo in getting date for finding cc and cacofile)
+
+   * scripts/merppupdate:
+     - added (script to merpp update already calibrated files) 
+     - added possibility to give outpath and regular expression for 
+       filename as command line options
+
+
+
+ 2007/05/10 Thomas Bretz
+
+   * callisto.rc, callisto_Dec04Jan05.rc, callisto_MarApr05.rc:
+     - cleanup of some comments
+
+   * mbase/MMath.cc:
+     - removed the usage of a storage space for the index in
+       GetMedianDev because the index is reacalculated anyhow
+
+   * mbase/MStatusArray.cc:
+     - if several objects of the same name (but different class 
+       types) are in a pad we don't stop searching if an object
+       with the right name has been found
+
+   * mcalib/MCalibrateData.cc, mcalib/MCalibrationChargeCalc.cc,
+     mcalib/MCalibrationRelTimeCalc.cc:
+     - updated output
+
+   * mhist/MHCamera.[h,cc]
+     - added two new member functions to count the number of bins
+       above or below a threshold
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added a new Tab to show the time development of the unsuitable
+       pixels
+     - added a new tab showing the eveloution of the number of
+       dead pixels
+
+   * mjobs/MJCalibration.cc:
+     - updated texts in bad pixel display
+
+   * datacenter/macros/fillsignal.C:
+     - replaced CalcUnsuitable by the new members of MHCamera
+     - also fill the maximum number of unsuitable pixels
+     - and fill the maximum number of dead pixels
+
+   * mfilter/MFSoftwareTrigger.cc, mhcalib/MHCalibrationTestCam.cc,
+     mimage/MCameraSmooth.cc:
+     - removed obsolete calls to GetPixById
+
+   * msignal/MSignalCam.[h,cc]:
+     - removed obolete function to access the MSignalPix'
+     - removed obsolete GetPixById
+     - added new function returning the number of unmapped pixels
+     - a little code cleanup
+
+
+
+
+ 2007/05/09 Daniela Dorner
+
+   * scripts/makemovie:
+     - added comment
+     - removed not needed lines
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checklogs, datacenter/scripts/checkstardone, 
+     datacenter/scripts/checktransfer, datacenter/scripts/copyscript, 
+     datacenter/scripts/correcttime, datacenter/scripts/dodatacheck, 
+     datacenter/scripts/doexclusions, datacenter/scripts/doqualityplots, 
+     datacenter/scripts/dowebplots, datacenter/scripts/filesondisk, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed, 
+     datacenter/scripts/fillstar, datacenter/scripts/findnewstars, 
+     datacenter/scripts/findnotseqruns, 
+     datacenter/scripts/insertdatasets, 
+     datacenter/scripts/insertsequences, datacenter/scripts/jobmanager, 
+     datacenter/scripts/linkmc, datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/mcsequences, 
+     datacenter/scripts/movingsubsystemfiles, 
+     datacenter/scripts/processmcsequences, datacenter/scripts/rmlocks, 
+     datacenter/scripts/runcallisto, datacenter/scripts/runganymed, 
+     datacenter/scripts/runstar, datacenter/scripts/scriptlauncher, 
+     datacenter/scripts/setup, datacenter/scripts/sourcefile, 
+     datacenter/scripts/webupdate-callisto, 
+     datacenter/scripts/webupdate-ganymed, 
+     datacenter/scripts/webupdate-sinope, 
+     datacenter/scripts/webupdate-star, 
+     datacenter/scripts/writedatasetfiles, 
+     datacenter/scripts/writesequencefiles, 
+     datacenter/scripts/zipscript: 
+     - change time for 'Software-Developement' 
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/correcttime, 
+     datacenter/scripts/dodatacheck, datacenter/scripts/doexclusions, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillganymed,
+     datacenter/scripts/fillstar, datacenter/scripts/runcallisto, 
+     datacenter/scripts/runganymed, datacenter/scripts/runstar, 
+     datacenter/scripts/writedatasetfiles, 
+     datacenter/scripts/writesequencefiles:
+     - removed variable needed only for setstatusroot
+     - adapted variable needed for setstatus
+     - adapted comment
+
+   * datacenter/scripts/writedatasetfiles:
+     - added missing 'setstatus "start"'
+
+   * datacenter/scripts/correcttime:
+     - improved regular expressions
+
+   * datacenter/macros/findcacofiles.C:
+     - added algorithm for searching missing caco files and inserting 
+       the according runnumber to the database
+     - adapted comment
+
+   * datacenter/scripts/filesondisk:
+     - removed algorithm for finding missing caco files (done by 
+       findcacofiles.C no)
+     - adapted comment
+     - added removing of files conaining the run lists
+
+   * datacenter/scripts/zipscript:
+     - added possibility to start several zipscripts giving a commanline 
+       option
+     - added locking of callisto
+     - removed not needed lines
+     - removed old code
+     - fixed bug (filename for chmod was wrong)
+
+   * datacenter/scripts/runcallisto:
+     - added locking of sequence for zipping
+     - reduced find for cc and caco file to the directory of the date, 
+       where the files are stored (date taken from callisto filename)
+     - improved regular expressions
+
+   * steps.rc:
+     - added fNotZipping to Needs of fCallisto to allow for the locking 
+       of callistos by the zipscript
+
+   * datacenter/scripts/sourcefile:
+     - removed functions setstatusroot and getdolistroot
+     - renamed variable in setstatus 
+     - added function sendquery 
+     - adapted if-clause to avoid removing of non existing files in 
+       case todofile is empty
+
+   * datacenter/scripts/scriptlauncher:
+     - fixed bug (in case condor_submit failed, the scriptlauncher was 
+       waiting for the not submitted job, until it was killed)
+
+   * datacenter/scripts/jobmanager:
+     - added algorithm to increase sleeping time in case condor failed 
+       several times in a row
+
+   * datacenter/scripts/setup:
+     - renamed errorsleeptime for usage in algorithm in jobmanager
+
+   * datacenter/scripts/dodatacheck:
+     - added query for date to reduce the find to the directory of the
+       date, where the rawfile is stored
+     - removed not needed lines
+
+   * datacenter/scripts/dodatacheck, datacenter/scripts/doqualityplots, 
+     datacenter/scripts/dowebplots, datacenter/scripts/linkmc, 
+     datacenter/scripts/movingsubsystemfiles, 
+     datacenter/scripts/runcallisto, datacenter/scripts/sourcefile, 
+     scripts/dospectrum, scripts/makemovie, scripts/processsequence:
+     - changed indentation to 3 spaces, where it was different
+
+   * datacenter/scripts/copyscript:
+     - added sort and uniq to find for dates
+     - removed not needed lines
+     - adapted find for catalogue files such that only the directories
+       of the last 31 days are searched with find and not the whole 
+       central control path
+
+   * datacenter/db/sequinfo.php:
+     - show ranges menu on first loading of page
+
+   * datacenter/db/menu.js:
+     - adapted functions to show ranges menu on first loading of the 
+       page and hide it, when a query is done
+     - commented functions
+
+   * scripts/processsequence:
+     - restricted find for cacofile to directory of date
+
+   * scripts/merppupdate:
+     - added (script to do merpp update for already calibrated files)
+
+
+
+ 2007/05/09 Thomas Bretz
+
+   * callisto.rc, callisto_Dec04Jan05.rc, callisto_MarApr05.rc,
+     callisto_mux.rc:
+     - changed ArrTimeRmsLimit in all cases to default 5.0
+       because of the new meaning
+
+   * showplot.cc:
+     - changed that it closes automatically if the file cannot
+       be read
+
+   * datacenter/macros/fillstar.C:
+     - commented the output of the query
+
+   * datacenter/macros/plotdb.C:
+     - adapted ranges to MUX data values
+     - added plots for new unsuitable columns
+
+   * mbadpixels/MBadPixelsPix.h:
+     - added a new member function IsUncalibrated
+     - further adapted the usuitable levels
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]:
+     - changed the meaning of ArrTimeRmsLimit such that it is now
+       the deviation from the average rms expressed in significance
+       levels
+     - the new check is done similar to the check for the relative
+       arrival time (to be unified!)
+     - removed FinalizeArrivalTimes
+     - removed calibration levels for first and last bin, this 
+       has to be redone more properly taken the extractor properties
+       into account
+     - some updates to the output
+     - some simplifications to the code
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - when calculating the median check for UnsuitableRun not
+       unsuitable in general
+     - small changes to output
+     - calculate upper and lower limits only once
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - added fMinimum and fMaximum data members similar to 
+       MHSectorVsTime
+     - to be unified with MHSectorVsTime
+     - fixed draw/paint
+     - increased version number
+
+   * mjobs/MJCalibration.cc:
+     - removed the bad pixel levels for first and last bins
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc], 
+     mextralgo/MExtralgoSpline.cc:
+     - changed to allow setup of the extraction type and the 
+       relative or absolute height for arrival
+     - if the height is set < 0 and extraction type is set to
+       relative integral the maximum is used instead of the leading edge.
+     - accordingly increased version number by one
+
+   * mjobs/Makefile:
+     - added mextralgo to includes
+
+
+
+ 2007/05/08 Daniel Hoehne
+
+   * datacenter/macros/fillsignal.C:
+     - implemented new variables fUnsuitable50 and fUnsuitable01
+
+   * datacenter/db/menu.php, magicdefs.php, querycal.php:
+     - implemented new columns fUnsuitable50 and fUnsuitable01
+
+
+
+ 2007/05/04 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJStar.cc:
+     - removed writing MBadPixelsCam. It now gives trouble 
+       because the etReadyToSave flag is set at an unproper time.
+       It is not used anyhow.
+
+   * datacenter/macros/fillsignal.C:
+     - small simplification
+
+
+
+ 2007/05/04 Daniela Dorner
+
+   * scripts/makemovie:
+     - added (script to produce movies) 
+
+
+
+ 2007/05/03 Daniel Hoehne
+
+   * datacenter/macros/fillsignal.C:
+     - fixed bug which made fillsignal fail for the new MUX data:
+       for sequences > 200000 hilooff and hilocal are not needed anymore
+
+
+
+ 2007/04/28 Daniela Dorner
+
+   * datacenter/scripts/dowebplots, datacenter/scripts/doqualityplots:
+     - moved temporary directory for pstoimg to /tmp
+
+   * datacenter/scripts/copyscript:
+     - moved file with diff for magic_favorites to /tmp
+
+   * datacenter/db/plotdb.php, datacenter/db/plotinclude.php, 
+     datacenter/db/menu.js  :
+     - implemented possibility to plot datasets by inserting dataset 
+       number as Set1
+
+   * datacenter/db/plot.php:
+     - implemented variables for colours
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php, 
+     datacenter/db/include.php, datacenter/db/datasetinfo-aio.php, 
+     datacenter/db/ganymed.php, datacenter/db/sequence.php:
+     - removed header and footer for print version
+
+   * datacenter/db/runinfo-aio.php:
+     - fixed small bug
+
+   * datacenter/db/magicdefs.php:
+     - added fMEanPUlsePosInner to alias
+
+   * datacenter/db/ganymed.php:
+     - added observation mode
+
+
+
+ 2007/04/27 Daniela Dorner
+
+   * datacenter/scripts/jobmanager:
+     - improved logging
+
+   * datacenter/scripts/scriptlauncher:
+     - redirect of error messages of condor_submit to errorlogfile
+     - in case condor_submit does not work (i.e. pid empty) an error 
+       message is written to the processlogfile
+
+   * datacenter/db/showplots-ds.php:
+     - adapted maxwidth of input field
+
+   * datacenter/db/plotdb.php, datacenter/db/plotinclude.php, 
+     datacenter/db/menu.js  :
+     - implemented possibility to give range for 2 additional values
+     - implemented possibility to give only upper or lower limit
+     - fixed bug, that ranges are not accepted before plotting once
+
+
+
+ 2007/04/27
+
+   * RELEASE 1.1
+
+
+
+ 2007/04/27 Daniel Hoehne
+
+   * datacenter/scripts/runcallisto:
+     - modified the ccfile and cacofile search to not find ccfiles
+       twice if one runnumber is part of a higher runnumber (as 23456
+       and 223456)
+
+
+
+ 2007/04/27 Thomas Bretz
+
+   * mcalib/CalibLinkDef.h, mcalib/Makefile:
+     - removed obsolete MCalibrationIntensityCam 
+     - removed obsolete MCalibrationIntensityChargeCam 
+
+   * mcalib/MCalibCalcFromPast.[h,cc], mcalib/MCalibColorSteer.[h,cc],
+     mcalib/MCalibrateData.[h,cc], mhcalib/MHCalibrationChargeCam.[h,cc]:
+     - removed obsolete MCalibrationIntensityChargeCam and replaced by
+       MCalibrationChargeCam
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]:
+     - removed obsolete MCalibrationIntensityChargeCam and replaced by
+       MCalibrationChargeCam
+     - to realize the difference between continous and single calibration
+       a new data member fContinousCalibration has been introduced
+     - consequently increased version number to 6
+     - do not set any exclusion in ReInit. it is nonsense not to fill 
+       histograms which might give (or give not) correct result,
+       if the checks are all executed anyhow
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - do not set any exclusion in ReInit and if a pixel is unsuitable.
+       it is nonsense not to fill histograms which might give (or give
+       not) correct result, if the checks are all executed anyhow
+     - switched on the check for outliers
+     - outliers are now set unsuitable rather than unreliable
+     - some code simplification of the checks
+
+   * mcalib/MCalibrationChargeCam.cc:
+     - added a comment in the Clear member function
+
+   * mcalib/MCalibrationRelTimeCam.cc:
+     - some fixes of looong Form statements
+     - a small cosmetic change to GetPixelContent
+     - replaced the old check of the average time resolution by
+       a more accurate check using the median and deviation
+
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]:
+     - removed data member fReferencePixel and corresponding code
+     - use the median of pixels with area index 0 as reference instead of
+       an artificial pixel
+
+   * mhcalib/MHCalibrationCam.[h,cc]:
+     - finally removed all dependencies on the intensity cams and replaced
+       them by the direct cam
+     - if the lo-gain histogram is empty this is not a reason for an 
+       uncalibrated pixel. At least in case of extracted properties (charge
+       and time) it is ok.  
+
+   * mjobs/MJCalibration.[h,cc]:
+     - let MCalibrationRelTimeCalc run after MCalibrationChargeCalc
+       otherwise almost all unsuitable pixels have deviating
+       relative arrival resolution.
+     - added new level for deviating time reolution to plot of bad pixels
+     - changed reference lines for timr resolution plots
+     - removed data member fRefTimeOffsetInner, it is now 0 by definition
+
+   * mjobs/MJCalibrateSignal.cc:
+     - finally removed all dependencies of Intensity cams
+     - enable ContinousCalibration in MCalibrationChargeCalc instead
+     - switched on interleaved relative time calibration
+
+   * mbadpixels/MBadPixelsPix.h:
+     - adapted to new unsuitable flag kDeviatingTimeResolution
+
+   * callisto_mux.rc:
+     - removed the obsolete resource statement about the level
+       for the relative arrival time check.
+
+   * mjobs/calibrationref.rc, mjobs/calibrationref_Dec04.rc,
+     mjobs/calibrationref_Nov04.rc, resources/calibrationref_mux.rc:
+     - changed time resolution references accordingly
+
+   * resources/calibration_spline.rc:
+     - added muon calibration factors up to period 55... to be corrected.
+
+   * mjobs/MJCut.[h,cc]:
+     - reanimated the use of an energy estimator in ganymed for the
+       purpose of having it as additional cut value if looking
+       for events after cuts
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - added a corresponding example
+
+
+
+ 2007/04/26 Thomas Bretz
+
+   * mjobs/MJPedestal.cc:
+     - inverted the default of the CalibFilter for the case of no
+       pattern available as the filter was inverted 4.3.07.
+
+   * callisto.rc:
+     - fixed typos in examples for movie encoding
+
+
+
+ 2007/04/25 Daniel Hoehne
+
+   * datacenter/scripts/runcallisto:
+     - removed obsolete option -raw from command line for callisto
+
+
+
+ 2007/04/25 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - removed obsolete code from Print() which tried to align the
+       output
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - increased the shown binning range further
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - unimportant changes
+
+   * mjobs/MJPedestal.cc:
+     - changed a comment
+
+   * mpedestal/MPedestalSubtractedEvt.h:
+     - fixed a bug of preset upper limits. The last slice is
+       fNumSamples-1 not fNumSamples
+
+
+
+ 2007/04/24 Thomas Bretz
+
+   * callisto_Dec04Jan05.rc, callisto_MarApr05.rc, callisto_mux.rc:
+     - fixed typos in examples for movie encoding
+
+   * mjobs/MJCalib.h, mjobs/MJPedestal.cc:
+     - missing commit from yesterday :-(
+
+   * mmovie/MMovieWrite.cc:
+     - changed resource Filename according to the other resources
+       to FileName
+
+   * ganymed.cc:
+     - enable dataset mc-mode if "-mc" is specified
+     - removed obsolete call to EnableMonteCarloMode
+     - removed EnableWobbleMode but use the setting of the dataset
+       instead
+
+   * mjobs/MDataSet.[h,cc]:
+     - renamed fIsWobbleMode to fWobbleMode
+     - added setter for fWobbleMode
+     - added fMonteCarlo which determins the default paths to be used 
+       if not overwritten
+     - replaced the static variables for the paths by member functions
+       which depend on the new fWobbleMode data member
+     - some simple reordering inthe constructor was necessary
+     - increased class version number accordingly to 2
+
+   * mjobs/MJCut.[h,cc]:
+     - repaired On-only mode
+     - removed data member fIsMonteCarlo, use the data-set getter instead
+     - removed data member fIsWobbleMode, use the data-set getter instead
+
+   * sponde.cc:
+     - print a warning if MC dataset doens't contain "MonteCarlo: Yes"
+
+   * mjobs/MJCalibrateSignal.cc:
+     - do not write signal*.root in movie mode
+
+
+
+ 2007/04/23 Thomas Bretz
+
+   * callisto.cc, star.cc:
+     - removed "-raw" and "-root" option
+     - replaced inflating sequence path by new InflatePath
+       function
+     - removed MJCalib::kUse* usage, use MSequence::IsMonteCarlo
+       instead
+
+   * mhcalib/MHCalibrationChargeBlindCam.cc,
+     mhcalib/MHCalibrationHiLoCam.cc, 
+     mhcalib/MHCalibrationPulseTimeCam.cc:
+     - removed obsolete include of MCalibrationIntensityCam
+
+   * mhcalib/MHPedestalCam.cc:
+     - removed obsolete usage of fIntensCam
+
+   * mhist/MHEvent.cc:
+     - replacedcompilation of description string by new 
+       MMcEvt::GetDescription memeber function
+
+   * mjobs/MJCalib.[h,cc]:
+     - removed fDataFlag and corresponding member functions and 
+       handling
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibrateSignal.cc,
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc, mjobs/MJStar.[h,cc]:
+     - replaced IsUseRawData and IsUseRootData by 
+       MSequence::IsMonteCarlo
+     - use fSequence to determin whether it is MC sequence or not
+
+   * mjobs/MJCalibrateSignal.cc:
+     - renamed movie encoding task list
+     - do not write output files if encoding movie
+
+   * mjobs/MSequence.[h,cc]:
+     - removed "merpp"-path
+     - monte carlo files now always have 8digits run numbers
+     - added new resource "MonteCarlo"
+     - added new static member function InflatePath
+     - increased version number to 2
+
+   * mmc/MMcEvt.[hxx,cxx]:
+     - added new member function GetDescription
+
+   * mmovie/MMovieWrite.[h,cc]:
+     - added a sanity check for strange rms values
+     - search for MMcEvt in the parlist and improve output
+       in case of monte carlo data
+     - fixed some typos in the comments of ReadEnv
+
+   * mmovie/Makefile:
+     - added mmc search path 
+
+   * mraw/MRawRunHeader.cc:
+     - set new defaults of fTelescopeNumber, fCameraVersion,
+       fFreqSampling and fNumSignificantBits for old MC data
+
+
+
+ 2007/04/23 Daniela Dorner
+
+   * datacenter/scripts/linkmc:
+     - removed workaround for 5-digit runnumbers
+
+   * datacenter/scripts/mcsequences:
+     - added line 'MonteCarlo: Yes' to output to sequence file
+
+   * datacenter/scripts/runganymed:
+     - adapted chosing of ganymed rc-file
+     - added output of ganymed command line
+
+
+
+ 2007/04/20 Daniel Hoehne
+
+   * datacenter/macros/filldotrun.C:
+     - implemented new Arehucas version
+
+
+
+ 2007/04/20 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.cc, mbadpixels/MBadPixelsPix.cc: 
+     - propagate option in Clear member function
+     - the default is now to keep the previously excluded flag and
+       set the unsuitable-run flag accordingly
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - if the lower limit for the measured number of phe is calculated 
+       to be less than one phe it is artificially reset to one phe
+
+   * mhist/MHCamEvent.cc:
+     - call SetFrameBorder(0) for all subpads explicitly 
+
+   * mhist/MHCamera.cc:
+     - removed the obsolete definition of kItemsLegend
+
+   * mbadpixels/MBadPixelsIntensityCam.cc, mcalib/MCalibrationIntensityCam.cc:
+     - removed obsolete reference in comment to MCalibrationINtensityQECam
+
+   * mcalib/CalibLinkDef.h, mcalib/Makefile:
+     - removed obsolete MCalibrationIntensityQECam
+     - removed obsolete MCalibrationIntensityBlindCam
+     - removed obsolete MCalibrationIntensityRelTimeCam
+     - removed obsolete MCalibrationIntensityTestCam
+
+   * mcalib/MCalibCalcFromPast.[h,cc], mcalib/MCalibColorSteer.[h,cc],
+     mcalib/MCalibrateData.[h,cc]:
+     - replaced data member fIntensQE by fQECam
+     - removed references to obsolete MCalibrationIntensityQECam
+     - added some comments
+     - replaced obsolete reference to MCalibrationIntensityBlindCam
+       by reference to MCalibrationBlindCam
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]:
+     - replaced references to fIntensQE by direct access to fQECam
+     - adde some comments
+     - removed data member fIntensQECam
+     - replaced obsoilete reference to MCalibrationIntensityBlindCam
+       by reference to MCalibrationBlindCam
+
+   * mjobs/MJCalibrateSignal.cc, mhcalib/MHCalibrationChargeBlindCam.cc:
+     - removed obsolete references to MCalibrationIntensityQECam
+     - removed obsolete references to MCalibrationIntensityBlindCam
+
+   * mbase/MTask.cc:
+     - added some unexecuted code to debug which taks are processed
+
+   * mcalib/MCalibCalcFromPast.cc, mcalib/MCalibrationIntensityCam.cc,
+     mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.h
+     - removed obsolete MCalibrationIntensityRelTimeCam
+
+   * mcalib/MCalibColorSteer.[h,cc], mcalib/MCalibrationRelTimeCalc.[h,cc],
+     mhcalib/MHCalibrationRelTimeCam.cc:
+     - replaced obsolete reference to MCalibrationIntensityRelTimeCam
+       by referencing MCalibrationRelTimeCam
+
+   * mhcalib/MHCalibrationChargeBlindCam.cc:
+     - replaced obsolete reference to MCalibrationIntensityBlindCam
+       by referencing MCalibrationBlindCam
+
+   * mhcalib/MHCalibrationHiLoCam.cc:
+     - replaced obsolete reference to MCalibrationIntensityHiLoCam
+       by referencing MCalibrationHiLoCam
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc
+     - replaced obsolete reference to MCalibrationIntensityPulseTimeCam
+       by referencing MCalibrationPulseTimeCam
+
+   * mcalib/MCalibrationTestCalc.cc
+     - replaced obsolete reference to MCalibrationIntensityTestCam
+       by referencing MCalibrationTestCam
+
+
+
+ 2007/04/12 Daniela Dorner
+
+   * datacenter/db/showplots-ds.php:
+     - added (script to plot all plots of a data set)
+
+   * datacenter/db/showplots.php:
+     - added 'previous' and 'next' button
+
+   * datacenter/db/plotinclude.php, datacenter/db/showplots.php:
+     - moved two function from showplots.php to plotinclude.php, as they
+       are also used in showplots-ds.php
+
+   * datacenter/db/builddatasets.php, datacenter/db/datasetinfo-aio.php
+     datacenter/db/indes-header.html, datacenter/db/indes.html, 
+     datacenter/db/menu.js, datacenter/db/reference.html, 
+     datacenter/db/regexp.html, datacenter/db/runinfo-aio.html, 
+     datacenter/db/sequinfo-aio.html:
+     - adapted paths of images and mars.css
+
+   * datacenter/db/index.html:
+     - added link to showplots-ds.php
+
+
+
+ 2007/04/18 Thomas Bretz
+
+   * Makefile:
+     - added suffixes .hxx and .cxx
+     - added new subdir mmovie
+
+   * mjobs/Makefile:
+     - added path to mmovie
+
+   * mmovie/MMoviePrepare.[h,cc]:
+     - changed access to MCalibrateData to access to MCalibConstCam
+
+   * mmovie/MMovieWrite.cc:
+     - fixed some typos in comments
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed dependenca on obsolete MCalibrationIntensityConstCam
+
+   * mjobs/MJCalibration.[h,cc]:
+     - for simplification removed all dependencies of unused intensity
+       calibration
+
+   * callisto.rc, callisto_Dec04Jan05.rc, callisto_MarApr05.rc,
+     callisto_mux.rc:
+     - removed line for switching on intensity calibration
+     - added expample lines for movie encoding
+
+   * mbadpixels/BadPixelsLinkDef.h, mbadpixels/Makefile:
+     - removed obsolete MBadPixelsIntensityCam
+
+   * mcalib/MCalibCalcFromPast.[h.cc]:
+     - do not store fIntensRelTime (it is not used at all) as data member
+
+   * mcalib/MCalibColorSteer.[h,cc], mcalib/MCalibCalcFromPast.[h.cc]:
+     - instead of creating of a new MBadPixelsCam into the intensity array
+       clear the information of the old one (FIXME: DO NOT CLEAR PREV EXCL!)
+                                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+   * mcalib/MCalibrationTestCalc.[h,cc]:
+     - removed empty Process function
+
+   * mcalib/MCalibColorSteer.[h,cc], mcalib/MCalibCalcFromPast.[h.cc],
+     mcalib/MCalibrationChargeCalc.[h,cc], mcalib/MCalibrationTestCalc.[h,cc],
+     mcalib/MCalibrationRelTimeCalc.[h,cc], mhcalib/MHCalibrationCam.[h,cc],
+     mhcalib/MHCalibrationChargeCam.cc, mhcalib/MHCalibrationHiLoCam.cc,
+     mhcalib/MHCalibrationPulseTimeCam.cc, mhcalib/MHCalibrationRelTimeCam.cc,
+     mhcalib/MHPedestalCam.cc:
+     - removed obsolete references to MBadPixelsIntensityCam, replaced
+       by MBadPixelsCam
+
+   * mhcalib/MHCalibrationCam.cc:
+     - set reason for uncalibrated pixels by SetUncalibrated
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed obsolete references to MBadPixelsIntensityCam
+     - removed MBadPixelsMerge, instead use the given MBadPixelsCam as 
+       starting point. THIS ALSO REMOVES SUPPORT FOR PREV. EXCLUDED PIXELS
+       (TO BE FIXED)
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFEvtNumber
+
+   * mfilter/MFEvtNumber.[h,cc]:
+     - added
+
+
+
+ 2007/04/17 Stefan Ruegamer
+
+   * datacenter/scripts/filesondisk:
+     - modified the ccfile search to not find ccfiles twice if one
+       runnumber is part of a higher runnumber (as 23456 and 223456)
+
+   * datacenter/scripts/movingrawfiles:
+     - added moving of rawfiles from the directory /magic/datacenter/
+       fromtape/rawdata/muxdata, which is the default rawfile folder of
+       the new muxtapes, to /magic/datacenter/fromtape/rawdata
+
+   * datacenter/scripts/runcallisto:
+     - added condition for the linking of the .rc-file for muxdata
+
+   * datacenter/scripts/makecallistolinks:
+     - commented reason2 out
+
+
+
+ 2007/04/17 Thomas Bretz
+
+   * mcalib/CalibLinkDef.h, mcalib/Makefile:
+     - removed obsolete MCalibrationIntensityConstCam
+
+   * mcalib/MCalibCalcFromPast.[h,cc]:
+     - removed obsolete depedency on MCalibrationIntensityConstCam
+
+   * mcalib/MCalibConstCam.[h,cc]:
+     - added a possibility to veto bad pixels in GetPixelContent by
+       setting a MBadPixelsCam
+     - removed obsolete fRunNumber
+     - increased class version number by 1
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - removed obsolete dependency on MCalibrationIntensityConstCam
+     - removed some obsolete comments with code from old pedestal
+       treatment
+
+
+
+ 2007/04/15 Thomas Bretz
+
+   * callisto.cc:
+     - added an option to write a movie
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - added the code to write a movie
+     - added new option (fIsMovieMode) to switch it on and off
+
+   * mmovie/MMovieData.h:
+     - added data member fMedianPedestalRms
+
+   * mmovie/MMoviePrepare.[h,cc]:
+     - added calculation of median pedestal rms
+
+   * mmovie/MMovieWrite.[h,cc]:
+     - added comments
+     - added return value to SetPalette
+     - delete palette entries after usage
+     - get median pedestal rms from MMovieData
+
+
+
+ 2007/04/12 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - added if-clause to avoid removing of non existing files
+
+   * datacenter/db/db.php:
+     - adapted host
+
+   * datacenter/db/plotdb.php:
+     - adapted usage of function GetQuery
+
+   * datacenter/db/plotinclude.php:
+     - added init of variables
+
+   * datacenter/db/runinfo-aio.php:
+     - adapted building of query for the case, that fRunMin=0
+
+   * datacenter/macros/filloptical.C:
+     - adapted such, that files from telescopes in Tuorla can also be 
+       handeled
+     - return 3 in case the coordinates of an object are not available 
+       in the database
+
+   * datacenter/scripts/copyscript:
+     - added case for return code 3 for filloptical.C
+
+   * datacenter/macros/setupdb.C:
+     - added table OpticalData
+
+   * datacenter/tools/fillobjects.C:
+     - added comment
+
+   * datacenter/tools/fillobjects2.C:
+     - adapted comment
+     - adapted reading to new format of file (different object name 
+       convention)
+
+   * datacenter/resources/TeVsources.txt:
+     - added (file containing the positions of the objects observed by 
+       the Tuorla Observatory and KVA)
+
+   * datacenter/resources/good_compstars.txt:
+     - added (file containing the magnitudes and colour of the objects 
+       observed by the Tuorla Observatory and KVA)
+
+   * datacenter/resources/compstars.txt:
+     - added (like good_compstars, but containing more data, which 
+       has been left out in the other file, as it is not accurate 
+       enough)
+
+
+
+ 2007/04/12 Thomas Bretz
+
+   * mmovie/MMoviePrepare.[h,cc], mmovie/MMovieData.[h,cc],
+     mmovie/MMovieWrite.[h,cc], mmovie/Makefile, mmovie/MovieLinkDef.h,
+     movie/MovieIncl.h:
+     - added
+
+   * mbase/MArrayB.h, mbase/MArrayD.h, mbase/MArrayF.h, mbase/MArrayI.h,
+     mbase/MArrayS.h:
+     - added Reset() member function or improved performance of it
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - fixed the alignment in an output
+
+   * mhbase/MBinning.h:
+     - added operator[] member function
+
+   * mhist/MHCamera.cc:
+     - changed such that it is allowed to use palettes with a different
+       number of contours.
+     - fixed the number of ticks written on the axis to 25
+     - use MBinnig to calculate the legend color boxes
+     - fixed a minor bug in the assignment of the color levels, which
+       gave visibly wrong result if the transition between two colors
+       was important but was not noticable in normal circumstances
+
+   * mjobs/MDataSet.h, mjobs/MSequence.h:
+     - increased class version to 1 to make it writable
+     - added Print to the context menu
+
+   * mgeom/MGeomCam.[h,cc]:
+     - removed fNumSectors
+     - removed fNumAreas
+     - added fNumPixInSector
+     - added fNumPixWithAidx
+     - changed CalcSectors and CalcArea to fill new data members
+     - fixed a bug in the range check of GetMaxRadius and GetMinRadius
+       (the range was to wide by 1 at the upper edge)
+     - increased class version from 4 to 5
+
+
+
+ 2007/04/11 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added a lot of comments
+     - added some code for future use
+
+   * mcalib/MCalibCalcFromPast.cc:
+     - if update of calibration constants via MCalibrateData fails an
+       error is raised
+
+   * mcalib/MCalibrateData.cc:
+     - if update of calibration constants done set the ReadyToSaveFlag
+       accordingly
+
+
+
+ 2007/04/04 Thomas Bretz
+
+   * mbase/MLogHtml.cc:
+     - the closing parenthesis was missing for setting to green color
+
+
+
+ 2007/04/03 Thomas Bretz
+
+   * mjobs/MDataSet.cc:
+     - added processing of RunTime and Name resource
+
+   * mgeom/MGeomCamDwarf.cc:
+     - removed an unused variable
+
+   * msignal/MSignalPix.h, msignal/MSignalCam.h:
+     - commented out obsolete AddNumPhotons and Scale
+     - removed ReducePrecision from setting of arrival time because
+       it gave artefacts.
+
+
+
+ 2007/03/29 Thomas Bretz
+
+   * mgeom/MGeomCam.cc, mgeom/MGeomPix.h:
+     - added new member function to return distance to coordinate
+       origin
+
+   * mgeom/MGeomCamDwarf.[h,cc]:
+     - added
+
+   * mgeom/Makefile, mgeom/GeomLinkDef.h:
+     - added MGeomCamDwarf
+
+
+
+ 2007/03/28 Thomas Bretz
+
+   * mraw/MRawRunHeader.cc:
+     - added Getter for fFreqSampling
+
+   * mpointing/MHSrcPosCam.[h,cc]:
+     - added different binning for wobble mode
+     - added circle for wobble mode
+
+   * mjobs/MJCut.cc:
+     - store run- and event-number via MParameterCalc in output files
+     - show histogram of source positions also in wobble mode
+
+   * mbase/MEnv.h:
+     - added member function to touch a resource returning whether 
+       it has contents or not
+
+   * mars.rc:
+     - added examples for MUX data
+     - fixed the other examples
+     - changed default cleaning to 8.5/4.0 absolute
+
+   * macros/readIPR.C:
+     - simplified
+
+
+
+ 2007/03/21 Stefan Ruegamer
+
+   * datacenter/scripts/runcallisto:
+     - removed entries for callisto_MarApr05.rc (outdated)
+
+   * datacenter/scripts/makecallistolinks:
+     - updated reason1 because the old reason has been removed in the
+       Mars Version 1.0, resulting in no more calibration with spline
+       if DF fails
+     - added reason2 to run spline after an other error
+
+
+
+ 2007/03/20 Daniel Hoehne
+
+   * datacenter/db/db.php, datacenter/scripts/budb,
+     datacenter/scripts/dbchk, datacenter/scripts/dunotseqruns,
+     datacenter/scripts/findnewstars,
+     datacenter/scripts/findnotseqruns, datacenter/scripts/sourcefile,
+     datacenter/tools/comparesequences, datacenter/tools/resetdataset,
+     sql.rc:
+     - changed the host from hercules to vela
+
+
+
+ 2007/03/17 Thomas Bretz
+
+   * mbase/MTime.[h,cc]:
+     - added new memeber function to set unix times
+
+
+
+ 2007/03/09 Thomas Bretz
+
+   * mjoptim/MJOptimizeCuts.cc:
+     - implemented printing of input file also in RunOnOffCore
+
+
+
+ 2007/03/08 Markus Meyer
+
+   * mpointing/MPointingDevCalc.h:
+     - changed fNumMinStars from 8 to n (in SetNumMinStars)
+
+
+
+ 2007/03/06 Stefan Ruegamer
+
+   * mraw/MRawRunHeader.cc:
+     - added SwapAssignment for pixels 428 and 429
+
+
+
+ 2007/03/05 Thomas Bretz
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - added a default for the extrator resolution in case no predefined
+       value is set
+
+   * mjobs/MJCalib.[h,cc], mjobs/MJCalibration.cc:
+     - removed HiLoCalibration option
+
+   * mjobs/MJCalibration.cc:
+     - use extractor to determine hi-/lo-calibration
+
+   * mjobs/MJPedestal.cc:
+     - do only insist on pedestal events if an extractor without
+       lo-gains is set
+
+   * callisto.rc, callisto_Dec04Jan05.rc:
+     - removed references to HiLoCalibration
+
+   * callisto_mux.rc, resources/calibrationref_mux.rc, 
+     resources/pedestalref_mux.rc:
+     - added new resource files for MUX data
+
+   * mjobs/MSequence.cc:
+     - another fix to make sure that there is a / between dir and filename
+
+   * mpedestal/MExtractPedestal.cc:
+     - why if fRawData initialized twice? Removed.
+     - Reset check window without extractor and without lo-gains
+
+
+
+
+ 2007/03/04 Thomas Bretz
+
+   * mhcalib/MHCalibrationChargeBlindCam.cc,
+     mhcalib/MHCalibrationChargeBlindPix.[h,cc]:
+     - commented out references to MRawEvtPixelIter::GetNum*Samples
+
+   * mhcalib/MHCalibrationRelTimeCam.cc:
+     - updated header
+
+   * mjobs/MJCalibrateSignal.cc:
+     - updated header
+     - removed references to MHCalibrationPulseTimeCam
+     - added a check to make sure that extractor1 is initialized
+     - use new SetRangeFromExtractor function for pedestal
+       extraction range
+     - added a new filter to check for pedestal events, used for
+       pedestal extraction in cases w/o lo-gains and to remove
+       pedestal events from further analysis
+     - fill and display hi-/lo-gain histogram only if lo-gain exists
+
+   * mjobs/MJPedestal.cc:
+     - replaced fSequence.GetName by GetFileName
+     - check for availability of lo-gain in pulse pos check
+     - Add MHCalibrationPulseTime to parlist to allow resources
+       file setup
+     - to fill the MHCalibrationPulseTimeCam deny calibration- and
+       pedestal-events
+     - use a pedestal filter to deny calibration events
+     - use new SetRangeFromExtractor function for pedestal
+       extraction range
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - removed an obsolete return
+
+   * mpedestal/MPedCalcFromLoGain.cc:
+     - if event does not contain lo-gains do not start extraction
+       at lo-gain offset
+
+   * mpedestal/MPedestalSubtractedEvt.[h,cc]:
+     - changed variable naming in GetSaturation from sathi to sat
+     - changed limit in GetMax from Byte_t to UInt_t 
+
+   * msignal/MExtractBlindPixel.cc, msignal/MExtractTimeAndCharge.cc:
+     - changed max argument in GetMax from Int_t to UInt_t
+
+   * msignal/MExtractTimeAndCharge.[h,cc]:
+     - changed fLoGainSwitch from Byte_t to UInt_t
+     - increased class version accordingly to 4
+
+   * mmain/MEventDisplay.cc:
+     - took out the display of the slice with the max index
+     - handle pedestal subtraction more accurate
+
+   * mraw/MRawEvtData.cc:
+     - added number of bytes per sample to GetNumBytes()
+     - removed contents of GetPixelContent... depricated
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - updated comments
+     - removed all functions returning informations about single
+       pixels (should be done through MPedestalSubtractedEvt
+       instead)
+
+   * mhist/MHEvent.cc:
+     - removed KMaxIdx...depricated.
+
+   * msignal/MExtractor.[h,cc]:
+     - changed type of fSaturationLimit from Byte_t to UInt_t
+     - increased class version number accordingly to 8
+     - only reset fSaturationLimit if it is above 0xff and
+       no lo-gain available
+
+   * msignal/MSignalCalc.[h,cc]:
+     - changed to use MPedestalSubtractedEvt instead of MRawEvtData
+     - make handling of data without lo-gains possible
+
+   * mhcalib/MHCalibrationChargeCam.[h,cc]:
+     - changed to use pedestal subtracted evt instead of the raw evt
+       for determination of the arrival time
+
+   * mhcalib/MHCalibrationCam.[h,cc]:
+     - made IsLoGain autodetecting in case fRunHeader is available
+
+   * msignal/MExtractPINDiode.cc:
+     - use MRawRunHeader's GetNumSamplesHi/LoGain
+
+
+
+ 2007/03/03 Thomas Bretz
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - changed the default of RelTimeResolutionLimit from 1.0 to 0.05
+
+   * mhcalib/MHCalibrationChargeCam.cc,
+     mhcalib/MHCalibrationPulseTimeCam.cc,
+      mhcalib/MHCalibrationRelTimeCam.cc:
+     - added f*RefCharge to Copy function
+     - added range to calls of GetIdxMaxHi/LoGainSample
+     - reworked and simplified DrawDataCheckPixel
+     - reworked and simplified DrawReferenceLine
+     - fixed call to ReadEnv of base class in ReadEnv
+
+   * mhcalib/MHCalibrationRelTimeCam.cc:
+     - commented filling of lo-gain arrays out.
+
+   * mpedestal/MExtractPedestal.[h,cc],
+     mpedestal/MPedCalcFromLoGain.h, mpedestal/MPedCalcPedRun.h:
+     - added the SetRangeFromExtractor function
+
+   * msignal/MExtractBlindPixel.cc,  msignal/MSignalCalc.cc:
+     - use GetNumSamplesHiGain of MRawRunHeader instead of 
+       MRawEvtPixelIter's
+
+   * msignal/MSignalCalc.[h,cc]:
+     - slightly changed handling of MC run, changed hi-/lo-gain
+       calibration from 10 to 11.3
+
+   * msignal/MExtractTime.cc:
+     - don't print lo-gain properties if n/a
+
+   * msignal/MExtractor.[h,cc]:
+     - reset logain range and saturation limit if no logains available
+     - added HasLoGain member function
+     - don't print lo-gain attributes in Print if no logains
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - reset fLoGainSwitch if logains are not available
+     - use MRawRunHeader's GetNumSamplesHi/LoGain
+     - do not use MRawEvtPixelIter to determin availability of lo-gains
+       use number of lo-gain samples to extract instead.
+     - don't print lo-gain properties if n/a
+
+
+
+ 2007/03/02 Thomas Bretz
+
+   * mraw/MRawRunHeader.h:
+     - added GetNumBytesPerSample() member function
+
+   * mraw/MRawRead.cc:
+     - splitted ReadPixel and setting ab-flag into function calls
+     - fixed skipping pixels if bps>1
+
+   * mraw/MRawEvtData.[h,cc]:
+     - removed last argument from AddPixel
+     - split reading pixel data and setting ab-flag into two functions
+     - increased version number from 5 to 6
+     - adapted Print function
+     - adapted Draw function
+     - adapted ReadPixel function
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]:
+     - made sure that Process is not executed in case of MC files
+     - minor changes to includes
+
+   * mextralgo/MExtralgoSpline.h:
+     - removed obsolete include iostream
+
+
+
+ 2007/03/01 Thomas Bretz
+
+   * mmain/MEventDisplay.cc:
+     - didn't show callisto output anymore because of missing fundametal
+       pedestal
+
+   * mbadpixels/MBadPixelsTreat.cc:
+     - added more informative output
+
+   * mhcalib/MHCalibrationCam.[h,cc], mhcalib/MHCalibrationChargeCam.cc,
+     mhcalib/MHCalibrationChargePix.h, mhcalib/MHCalibrationRelTimeCam.cc,
+     mhcalib/MHCalibrationChargeCam.h, mhcalib/MHCalibrationChargePINDiode.h,
+     mhcalib/MHCalibrationPulseTimeCam.cc, mhcalib/MHCalibrationTestCam.cc,
+     mhcalib/MHCalibrationTestTimeCam.cc, mhcalib/MHGausEvents.h,
+     mhcalib/MHCalibrationChargeBlindCam.cc, mhcalib/MHPedestalCam.cc,
+     - replaced SetNbins/First/Last by SetBinning
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - improved output in case arrival time is out of range
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - the values can only have discrete valuesno need to set a bin-width
+       different from 1
+     - set binning automatically by using the number of samples
+     - fixed ReadEnv
+     - directly use maxpos, no cast necessary
+
+   * mraw/MRawRunHeader.h:
+     - added new member function GetNumSamples
+
+   * mpedestal/MPedCalcFromLoGain.cc:
+     - fixed ReadEnv
+
+   * mraw/MRawCrateData.cc,  mraw/MRawEvtHeader.cc:
+     - implemented reading new mux format 8
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - implemented reading of new file format 8
+     - added new data members fNumBytesPerSample, fFreqSampling
+       and fNumSignificantBits
+     - increased file format version from 5 to 6
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - made aware of handling the new and old format
+     - added range to GetIdxMax*
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]:
+     - removed obsolete data members fSumhiarea and fSumhisector
+     - replaced the usage of MRawEvtData by MPedestalSubtractedEvt
+     - according to this the lower signal limit has been decresed
+       by 15
+     - changed "saturation" limit accordingly from 254 to 245
+
+   * mpedestal/MPedestalsubtractedEvt.h:
+     - added a shortcut for GetSaturation
+
+   * mjobs/MJPedestal.cc:
+     - first subtract pedestal and then fill MHCalibrationPulseTimeCam
+     - fill MHCalibrationPulseTimeCam with MPedestalSubtracted
+
+
+
+ 2007/02/28 Thomas Bretz
+
+   * macros/tutorials/mirrordelay.C:
+     - fixed the formula for the spherical mirror
+     - fixed the calculation of the time-delay
+
+   * mastro/MObservatory.[h,cc]:
+     - added constructors and functions to set the observatory location
+       manually
+
+   * mbase/MTime.[h,cc]:
+     - added constructor to construct MTime by date
+     - added AsDouble for new root streamers (allowing to view MTime in 
+       a TBrowser)
+     - added GetRootDatime to return TDatime object
+
+   * mcalib/MCalibrateData.cc:
+     - added more meaningful output in case a conversion factor exceeds a limit
+
+   * datacenter/macros/plotdb.C:
+     - added plot for spark rate
+
+
+
+ 2007/02/26 Daniela Dorner
+
+   * datacenter/db/builddatasets.php, datacenter/db/findoffdata.php, 
+     datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php, 
+     datacenter/db/include.php, datacenter/db/menu.php, :
+     - bugfix: the stopdate was not choses properly in case of reset 
+       when there was no data past midnight
+     - a new function (GetStopDate) has been implemented
+     - bugfix in PrintNightRange (table Sequences was used in all cases)
+
+
+
+ 2007/02/26 Daniel Hoehne
+
+   * datacenter/macros/fillstar.C:
+     - bugfixes: included MHCamera.h, corrected two typos (missing ";" and
+       a surplus "s" in the variable "sparkrate")
+
+   * datacenter/db/magicdefs.php, menu.php:
+     - added fSparkRate
+
+
+
+ 2007/02/16
+
+   * RELEASE 1.0
+
+
+
+ 2007/02/16 Thomas Bretz
+
+   * macros/starvisyear.C:
+     - changed default observator to magic
+     - fixed some typos in comments
+
+   * mastro/MAstro.[h,cc]:
+     - added a new function to estimate the time of culmination
+     - fixed the conversion factors RadToHor and HorToRad (wrong by 15/24)
+
+   * mastro/MObservatory.cc:
+     - fixed the Print() output
+
+   * mbase/MMath.h:
+     - removed conversion factor to and from Hours
+
+   * mjobs/MSequence.cc: 
+     - added a / behind the date (for the output in case of failure)
+
+   * mmc/MMcFadcHeader.[hxx,cxx]:
+     - added fElecNoiseName for compatibility with camera program
+     - increased ClassVersion by 1
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - increased class version by 1 for compatibility with output
+       of newer camera versions
+
+   * resources/sequences.rc:
+     - changed the sequence.rc file to support new MUX data
+
+
+
+ 2007/02/15 Thomas Bretz
+
+   * macros/tutorials/mirrordelay.C:
+     - added a macro plotting the delay between a spherical and a 
+       parabolic mirror
+
+   * mjobs/MJStar.cc:
+     - implemented new plots for IPR vs. Time and DT
+
+
+
+ 2007/02/13 Thomas Bretz
+
+   * resources/hilocalib.rc, resources/hilocalib_sp1.rc:
+     - added new resource files for hi-/lo-gain calibration.
+
+   * resources/hiloconv-*.root:
+     - added hi-/lo-gain calibration constants
+
+   * callisto_Dec04Jan05.rc:
+     - changed input file name for hi-/lo-gain calibration constants
+
+   * mreflector/MHReflector.[h,cc]:
+     - added histogram class for reflected photons
+
+   * mreflector/Makefile, mreflector/ReflectorLinkDef.h
+     - added MHReflector and necessary include paths
+
+   * mbase/MLog.h:
+     - fixed a bug in Separator which could cause a crash if the contents 
+       are too long
+
+   * manalysis/MParameterCalc.cc:
+     - check for HasValidRule instead of IsValid in ReadEnv
+
+   * mdata/MDataPhrase.h:
+     - added HasValidRule member function
+
+   * mfileio/MReadRflFile.[h,cc]:
+     - allow also reading of gzip-compressed files
+     - output more header information
+     - don't use a const qualified TString with gSystem->ExpandPathName
+
+   * mjobs/MJPedestal.cc:
+     - readin bad pixels from ascii file later
+
+   * mmc/MMcEvtBasic.h:
+     - added a static member function GetEnergyStr to convert 
+       GeV into MeV and TeV
+
+   * mpointing/MPointingDevCalc.h:
+     - increased size of fSkip by one
+
+   * mextralgo/MExtralgoSpline.h:
+     - fixed acompiler warning
+
+
+
+ 2007/02/09 Daniel Hoehne
+
+   * datacenter/scripts/linkmc
+     - adapted to new montecarlo directory structure (/magic/montecarlo
+       instead of /montecarlo)
+
+
+
+ 2007/02/09 Thomas Bretz
+
+   * star.rc:
+     - added new options 
+     - reordering
+
+   * mbase/MStatusDisplay.cc:
+     - updated from 2006 to 2007
+
+   * mfbase/MFDataPhrase.cc:
+     - fixed ReadEnv to correctly return true/false
+
+   * mjobs/MJStar.cc:
+     - added new tabs "Spakless" and "Sparks" dividing the average
+       signal tab into two distributions by a SparkCut
+     - replaced all MF by MFDataPhrase
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed the extraction range used in the lo-gains from the
+       hi-gain range to the lo-gain range
+
+   * datacenter/macros/fillstar.C:
+     - added filling the spark rate into the database
+     - the rate after cleaning is now without sparks!
+
+
+
+ 2007/02/06 Thomas Bretz
+
+   * mpointing/MPointingDevCalc.cc:
+     - included check for monitoring flag
+
+   * mextralgo/MExtralgoSpline.[h,cc]:
+     - implemented the possibility to determine the pulse width at
+       maxheight/2
+
+
+
+ 2007/02/04 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - added if-clause to avoid that a script is aborted in case a macro
+       doesn't compile, return code is set to 1 in this case
+
+
+
+ 2007/02/04 Thomas Bretz
+
+   * mjobs/MJCalibration.cc:
+     - implemented Hi-/Lo-Gain calibration for MCs
+
+   * mjobs/MJPedestal.cc:
+     - removed intermediate pedestalstorage from code (its
+       result is not used at all)
+
+   * datacenter/macros/fillsignal.C:
+     - replaced GetMediandev by GetDev
+
+   * callisto.rc, callisto_Dec04Jan05.rc:
+     - changed ExtractWinLeft/Right according to new scheme
+
+   * mhcalib/MHCalibrationChargeCam.[h,cc]:
+     - removed obsolete data members fFirstHiGain, etc and
+       replaced by storage of fSignal
+     - made sure that the average extracted signal position
+       is at least one slice away from the edges of the
+       extraction window
+
+   * mjobs/MJPedestal.cc:
+     - reworked the pulse position check. It now better takes
+       the properties of the extractors into account.
+       Still to be done: relation between pulse position and
+       extraction window!
+
+   * msignal/MExtractBlindPixel.[h,cc],
+     msignal/MExtractPINDiode.[h,cc]:
+     - fixed arguments type of SetRange
+
+   * msignal/MExtractTime.cc:
+     - removed old obsolete code already in comments
+
+   * msignal/MExtractTimeAndCharge.h:
+     - added getter for LoGainStartShift
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc],
+     msignal/MExtractTimeAndChargeSpline.[h,cc],
+     msignal/MExtractedSignalCam.[h,cc], msignal/MExtractor.[h,cc]:
+     - changed the type of LoGainFirst from byte to int
+     - if necessary increased class version
+
+   * mpedestal/MExtractPedestal.cc:
+     - improved output
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - fixed a %3.1 instead of %3.1f
+
+
+
+ 2007/02/03 Thomas Bretz
+
+   * mhist/MHCamEvent.[h,cc]:
+     - added Draw function to context menu
+     - added GetHist member functions
+     - added possibility to display the relative error
+
+   * mjobs/MJCalibration.cc:
+     - read the hi-/lo-gain calibration constants from a MHCamEvent
+       which is stored in a root file given in resources/hilocalib.rc
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - improved the estimation in GetSaturationTime for the cases in
+       which the saturating pulse is so early, that an normal
+       interpolation is not appropriate.
+
+   * callisto_DecJan04.rc:
+     - set fall- and rise-time for spline artificially to 0.5
+
+   * mhbase/MFillH.cc:
+     - added comments
+
+   * mpedestal/MExtractPedestal.[h,cc], 
+     mpedestal/MPedCalcFromLoGain.cc, mpedestal/MPedCalcPedRun.cc:
+     - fixed the range check.In case of the lo-gain extraction
+       the range could infact leak out of the fadc slices
+
+   * msignal/MExtractTimeAndCharge.[h,cc]:
+     - added somecomments
+     - forbid the lo-gain signal to be negative
+     - increased version number for compatibility with last release
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - set the correct numbers for rise- and fall-time as default
+
+   * mbase/MStatusArray.[h,cc]:
+     - improved workaround in Read() and Write() for the Reset
+       of the kCanDelete bit in TH1
+
+   * mjobs/MJCalibration.cc, mjobs/MJCalibrateSignal.cc:
+     - commented out obsolete references to *HiLoCam
+
+   * mhcalib/Makefile, mcalib/Makefile, mhcalib/HCalibLinkDef.h,
+     mcalib/CalibLinkDef.h:
+     - removed *HiLoCam s
+
+
+
+ 2007/02/02 Thomas Bretz
+
+   * mreflector/MRflSinglePhoton.[h,cc], mreflector/MRflEvtData.[h,cc]:
+     - added new Fill functions allowing to fill photons versus 
+       a z-value, e.g. energy.
+
+
+
+ 2007/02/01 Thomas Bretz
+
+   * mhist/MHCamEvent.[h,cc]:
+     - allow to set a histogram for display from external
+
+   * mhist/MHCamera.[h,cc]:
+     - added functions to calc Median/Dev
+     - fixed adding a MHCamera with AddCamContent. It now takes also
+       the errors and binentries correctly into account
+     - simplified Reset() using TArray::Reset()
+
+   * mhvstime/MHSectorVsTime.[h,cc]:
+     - added option to use median/dev instead of mean/rms
+     - switched Grid on
+
+   * mjobs/MSequence.cc, mjobs/MDataSet.cc:
+     - small improvements to splitting number rows
+     - handle possible tabs correctly
+
+   * mbase/MStatusArray.[h,cc]:
+     - improved handling in Read(). We make sure now that Read doesn't
+       produce a memory leak
+
+   * mhist/MHCamera.[h,cc]:
+     - overwrote Clone function to make sure that a cloned MHCamera
+       is never added to the current directory
+
+   * mcamera/MCameraTH.h:
+     - added a workaround to get rid of the obsolete discriminator thresholds
+       for the non-trigger pixels
+
+   * mreport/MReportCC.cc:
+     - added a sanity \o-Terminator to the dicriminator threshold extraction
+
+
+
+
+ 2007/01/30 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.[h,cc]:
+     - added function to return the uncalibrated and unsuitable
+       pixels as TArrayC (to be used in MHCamera)
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - added a FIXME-comment
+
+   * mhist/MHCamEvent.[h,cc]:
+     - added an option to change the kind of error which is displayed
+     - consequently increased version number by 1
+
+   * mhist/MHCamera.[h,cc]:
+     - added a new bit to allow the error to be switched between 
+       mean and spread
+
+   * mjobs/MJStar.cc, mjobs/MJCalibrateSignal.cc:
+     - adapted to changes in error display
+
+
+
+ 2007/01/27 Thomas Bretz
+
+   * manalysis/MMcCalibrationUpdate.cc:
+     - fixed a typo in a comment
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - commented out some obsolete currently unused code
+
+   * mdata/MDataPhrase.cc:
+     - added a sanity check
+
+   * mpedestal/MMcPedestalCopy.cc:
+     - Changed output to fit the structure used in all other classes
+
+   * mmain/MEventDisplay.cc:
+     - made sure that MPedestalSubtract dies the right thing
+     - removed badpixel calculation and treatment until a better
+       solution was found.
+
+   * mfbase/MFDataPhrase.cc:
+     - fixed a "comparison is always true" warning
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.h:
+     - increased class version number to 3 to account for the removal
+       of the fTimeShift data members since last release
+
+
+
+ 2007/01/27 Daniela Dorner
+
+   * datacenter/db/showplots.php:
+     - added (tool to click through the calib, signal and star plots of
+       one sequence) 
+
+   * datacenter/db/index.html:
+     - added link to new plot tool 
+
+   * datacenter/db/ganymed.php:
+     - added fDataSetName, removed fWobble
+     - removed mininmum value of 100 for dataset range
+
+   * datacenter/db/builddatasets.php:
+     - added fIsoInLimit2 and fIMCLimit2 in Init
+     - added check on observation mode
+
+
+
+ 2007/01/26 Thomas Bretz
+
+   * mpedestal/MExtractPedestal.cc:
+     - fixed a bug which caused the pedestal to be set to 0 if the
+       AB-flag is invalid
+
+
+
+ 2007/01/25 Thomas Bretz
+
+   * mreflector/MRflSinglePhoton.h:
+     - added copy constructor
+     - added a function to fill a TH2
+
+   * mreflector/MRflEvtData.[h,cc]:
+     - added copy costructor
+     - added Clone function
+     - added a function to fill a TH2
+
+
+
+ 2007/01/24 Thomas Bretz
+
+   * mhflux/MHCollectionArea.cc:
+     - fixed a typo in the last change
+
+
+
+ 2007/01/24 Daniel Hoehne
+
+   * msignal/*.dat:
+     - inserted missing third column (0) in all weights files
+
+
+
+ 2007/01/18 Thomas Bretz
+
+   * mhflux/MHCollectionArea.cc:
+     - another fix for the error calculation of the collection area.
+       The totalarea was inluded in the error calculation as it would
+       be a wait, but actually it is not.
+
+
+
+ 2007/01/16 Thomas Bretz
+
+   * mfileio/MReadMarsFile.cc:
+     - fixed two "comparison between signed and unsigned integer" warnings
+
+   * mhbase/MFillH.cc:
+     - small update to comments
+
+   * mimage/MHHillasExt.cc:
+     - call SetDirectory(NULL) after SetName
+
+   * mjobs/MSequence.[h,cc]:
+     - commented out obsolete GetFileNames
+
+   * msignal/MExtractor.[h,cc]: 
+     - Some small updates
+     - removed code from Process function
+     - increased version number to 7
+
+   * msignal/MExtractedSignalPix.h:
+     - some simple reordering in the class header
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - simplified the checks in SetWindowSize
+
+   * msignal/MC_cosmics_weights46.dat, msignal/MC_weights46.dat:
+     - added third column with zeros
+
+
+
+ 2007/01/16 Daniela Dorner
+
+   * datacenter/db/menu.php, datacenter/db/datasetinfo-aio.php,
+     datacenter/db/magicdefs.php:
+     - implemented new variables for datasets
+
+
+
+ 2007/01/15 Thomas Bretz
+
+   * mpedestal/MPedestalSubtract.cc:
+     - added a sanity check tomake sure that the pixel array has the
+       correct size when filled
+     - made sure the the number of pixels in the camera nd not the 
+       number of connected pixels is used to initialize the size of
+       the arrays.
+
+   * mpedestal/MPedestalSubtractedEvt.[h,cc]:
+     - allow the initialization of nuber of pixels and samples
+       independanly.
+
+
+ 2007/01/15 Daniela Dorner
+
+   * datacenter/db/sources.php, datacenter/db/sequinfo-aio.php, 
+     datacenter/db/runinfo-aio.php, datacenter/db/printtable.php,
+     datacenter/db/plotdb.php, datacenter/db/menu.php, 
+     datacenter/db/findoffdata.php, datacenter/db/builddatasets.php, 
+     datacenter/db/datasetinfo.php:
+     - fixed bug in init of $_GET
+
+
+
+ 2007/01/12 Stefan Ruegamer
+
+   * datacenter/macros/writedatasetfile.C:
+     - addded #include <errno.h>
+
+
+
+ 2007/01/11 Thomas Bretz
+
+   * mbase/MLogManip.cc:
+     - removed the obsolete include of MLog.h
+
+   * mbase/MLogManip.h:
+     - encapsulated an include in ifdefs
+
+   * mhcalib/MHCalibrationCam.cc, mhcalib/MHCalibrationChargeCam.cc:
+     - updated log-output
+
+   * mhflux/MHEnergyEst.cc:
+     - replaced difficult to see green by blue
+
+   * mjobs/MDataSet.[h,cc]:
+     - added datat members for path of sequences and path of data files
+       to be able to store overwritten defaults 
+     - check completeness of dataset files
+     - store a MSequence object in the list instead of the name and dir
+       (this is necessary to have all important information for a dataset
+        file, including the sequence number! - available)
+     - some changes to the output
+     - allow to print a perfect copy of the read dataset file to the console
+       just from the contents of the object
+
+   * mjobs/MJStar.cc:
+     - updated to use MSequence::GetFileName instead of MSequence:GetName
+
+   * mjobs/MSequence.[h,cc]:
+     - keep filename and datapath in header, this has some advantages
+       for sanity checks
+     - many improvements of sanity checking in case of missing or
+       unaccessible files
+     - Fixed "lightConditions" (was "LightCondition")
+     - Fixed "No_Moon"         (was "NoMoon")
+     - allow to set the data path as second argument in the constructor
+     - implemented a check whether the sequence file is complete
+
+   * mjobs/MJCut.[h,cc]:
+     - added some code (still commented out) to display the excess rate
+     - with the other changes we can now store the original dataset in
+       the output
+
+   * mjoptim/MJOptimize.cc:
+     - Keep the sequence files in the file list instead of just the
+       filename and the directory
+
+   * mjtrain/MJTrainDisp.cc:
+     - use return value of MDataSet::AddFilesOn/Off for a sanity check
+
+   * mjobs/MJob.[h,cc]:
+     - removed obsolete fPathData and stuff
+
+   * callisto.cc, star.cc:
+     - removed obsolete calls to MJob::SetPathData
+
+   * callisto.rc, star.rc:
+     - removed obsolete examples for "PathData"-resource
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibrateSignal.cc, 
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc, mjobs/MJStar.cc:
+     - removed obsolete reference to fPathData
+
+
+
+ 2007/01/11 Daniela Dorner
+
+   * datacenter/db/builddatasets.php:
+     - implemented username (the one who inserts the dataset has to give
+       his/her username now)
+     - fixed password query in case user inserted something wrong
+     - implemented check, if on-sequences have different observations 
+       modes 
+     - implemented check, if user has chosen one sequences as on and off
+     - adapted text of password prompt
+
+   * datacenter/db/builddatasets.php, datasetinfo-aio.php, 
+     runinfo-aio.php, sequinfo-aio.php:
+     - minor changes in formatting
+     - added 'alt' for +/- images
+
+   * datacenter/db/menu.js:
+     - added 'alt' for +/- images
+
+
+
+ 2007/01/10 Thomas Bretz
+
+   * mhbase/MH.cc:
+     - fixed a bug in SetBinomialErrors. The errors of the two
+       histograms were exchanged in the calculation
+
+   * mbase/MEnv.[h,cc]:
+     - added new member function GetNumUntouched
+
Index: branches/Mars_McMismatchStudy/Changelog.08
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.08	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.08	(revision 17960)
@@ -0,0 +1,3091 @@
+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 -*-*-
+
+ 2008/12/23 Stefan Ruegamer
+
+   * datacenter/scripts/movingrawfiles
+     - corrected moving of zipped rawfiles
+
+   * datacenter/scripts/dodatacheck
+     - added the new linearity run (_N_-files)
+
+   * test 4
+   
+
+
+ 2008/12/22 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C:
+     - implemented SuperArehucas version 081214-0
+
+
+
+ 2008/12/22 Stefan Ruegamer
+
+   * datacenter/macros/doexclusions.C
+     - added telescope number where missing
+
+   * datacenter/scripts/movingrawfiles
+     - added moving of zipped rawfiles
+
+
+
+ 2008/12/21 Thomas Bretz
+
+   * Makefile.rules:
+     - removed $(ROOTSYS) from the call to rootcint. It should
+       be in th epath anyway
+
+   * mars-config.cc, mbase/MZlib.cc:
+     - included string.h
+
+   * showlog.cc, manalysis/MGeomApply.cc, mbase/MAGIC.cc, 
+     mbase/MMath.cc, mbase/MProgressBar.cc, mbase/MSearch.cc,
+     mdata/MDataElement.cc, mfileio/MReadScanFile.cc,
+     mhbase/MH3.cc, mjobs/MSequenceSQL.cc,
+     mpointing/MPointingDevCalc.cc, msql/MSQLMagic.cc:
+     - included stdlib.h
+
+   * mastro/MAstro.h, mhbase/MHn.h:
+     - fixed the naming of some veriables in the definition
+
+   * mbase/MGMap.cc, mtools/MagicJam.cc:
+     - inlcude climits
+
+   * mbase/MStatusDisplay.cc:
+     - implemented a workaround against root's buffer overflows
+     - switched of root's own handling by resetting
+       kShowEventStatus
+
+   * mhbase/MH.[h,cc]:
+     - added a workaround for the buffor overflow in 
+       TH1::GetObjectInfo and TProfile::GetObjectInfo
+
+   * mhist/MHCamera.cc:
+     - implemented a workaround for the buffer overflow in root's
+       GetObjectInfo
+
+   * msql/MSQLServer.[h,cc]:
+     - replaced GetPrimaryKey by GetPrimaryKeys
+
+
+
+ 2008/12/19 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C:
+     - implemented SuperArehucas version 081204-0 incl. sumtrigger 
+       flag
+
+   * datacenter/db/magicdefs.php, datacenter/db/menu.php:
+     - implemented sumtrigger flag (in runinfo and sequinfo menus)
+
+
+
+ 2008/12/09 Thomas Bretz
+
+   * datacenter/macros/buildsequenceentries.C:
+     - propagate the condition to get the sequences of one day
+       to the subsequent splitting of the block to decreasde 
+       strange results in case of incosistency in the db (for example
+       if Arehucas write nonsense run numbers)
+
+
+
+ 2008/12/02 Daniela Dorner
+
+   * datacenter/db/showplots.php:
+     - bugfix: added removing of spaces in seq-string
+     - changed number of star-tabs from 19 to 20 (temporary)
+
+
+
+ 2008/12/02 Thomas Bretz
+
+   * mbase/MStatusDisplay.[h,cc], mbase/MEvtLoop.cc:
+     - added Pause and Single Step option
+
+   * mcorsika/MCorsikaEvtHeader.[h,cc], mcorsika/MCorsikaRead.[h,cc],
+     mcorsika/MCorsikaRunHeader.[h,cc]:
+     - moved filling of run header from first event header to
+       MCorsikaRunHeader
+
+   * mfileio/MWriteRootFile.cc:
+     - improved a check in the constructor if no filename is given
+
+   * mhbase/MH.cc:
+     - make SetBinning also work for TProfile2D
+
+   * mhist/MHCamera.[h,cc]:
+     - added functions to return the number of used pixels
+
+   * mjobs/MDataSet.cc, mjobs/MSequence.cc:
+     - improved by using new GetEnvValue3
+
+   * mbase/MParContainer.[h,cc]:
+     - added new member function GetEnvValue3 which is more flexible
+       in the number of leading zeroes within a resource name
+
+
+
+ 2008/12/01 Daniela Dorner
+
+   * datacenter/scripts/runcorsika:
+     - removed not needed query
+
+   * datacenter/scripts/sourcefile:
+     - added check if script is executed with the full path
+     - added check if rc-files are existing
+
+   * datacenter/db/menu.php:
+     - removed not needed lines
+
+   * datacenter/db/include.php:
+     - valign='top' for queryrbk.php
+
+   * datacenter/db/queryrbk.php:
+     - added print button
+
+
+
+ 2008/11/28 Thomas Bretz
+
+   * mjobs/MJSpectrum.cc:
+     - fixed a problem in FormFlux which did not handle the nagative slope
+       correctly
+     - Changed the title of the Spectrum histogram to make the fit
+       result fit better
+     - added a histogram showing the readin source position of the MCs
+
+   * mcorsika/CorsikaLinkDef.h, mcorsika/Makefile, 
+     mcorsika/MCorsikaEvtHeader.[h,cc], mcorsika/MCorsikaRead.[h,cc],
+     mcorsika/MCorsikaRunHeader.[h,cc]:
+     - addedcc MCorsikaRunHeader.h
+
+
+
+ 2008/11/27 Thomas Bretz
+
+   * mbase/MContinue.[h,cc]:
+     - updated ClassVersion number according to last change
+
+   * mraw/MRawFilesRead.cc:
+     - fixed a bug when errno==0
+
+   * mjobs/MJStar.cc:
+     - in case of sum trigger skip only events with only sum-trigger not
+       all events with sum-trigger for effective on time calculation
+
+   * datacenter/plotdb.C:
+     - fixed a problem with the order in the select if case of Groups
+     - removed automatic Postscript storage
+     - added some plots about currents
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added new run-type "Linearity"
+
+
+
+ 2008/11/24 Daniela Dorner
+
+   * datacenter/scripts/runcorsika:
+     - changed fAzimuth* to 180-fAzimuth* (different coordinate system
+       of CORSIKA
+
+
+
+ 2008/11/21 Daniela Dorner
+
+   * datacenter/db/showplots.php:
+     - adapted number of tabs
+
+
+
+ 2008/11/18 Daniela Dorner
+
+   * datacenter/scripts/runcamera:
+     - redirect output from camera program to scriptlog
+     - changed expected return code (Julian has adapted reflector to 
+       return something in case of successful completion of the 
+       program)
+     - fixed logging
+     - adapted redirect to delete old logging output in case of 
+       restarting
+
+   * datacenter/scripts/runcorsika:
+     - adapted redirect to delete old logging output in case of 
+       restarting
+
+   * datacenter/scripts/runcamera:
+     - redirect output from camera program to scriptlog
+     - own failed variable
+     - changed misleading variable name
+
+   * datacenter/scripts/setup, datacenter/scripts/runcorsika:
+     - moved FLUPRO to setup
+
+
+
+ 2008/11/18 Stefan Ruegamer
+
+   * datacenter/scripts/read_lapalma_tapes
+     - added this script which is used to read raw file tapes sent from
+       La Palma; executed by root on phoenix (because he should know
+       about the free disc space status)
+
+   * datacenter/scripts/checkmd5sum
+     - prevented date echo on the executing shell
+
+   * datacenter/scripts/checktransfer
+     - removed check for .finished files (.finished are no longer used)
+
+
+
+ 2008/11/16 Daniela Dorner
+
+   * datacenter/db/menu.php, datacenter/db/sequinfo-aio.php:
+     - added option to query only sumtrigger data
+
+
+
+ 2008/11/14 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - added variable for sql.rc
+     - simplified code of two for-loops
+
+   * datacenter/scripts/setup:
+     - fixed typo
+
+   * datacenter/scripts/runcorsika:
+     - fixed query
+     - fixed logging
+
+
+
+ 2008/11/13 Daniela Dorner
+
+   * datacenter/scripts/runcorsika:
+     - added that maximum viewcone is queried from the database
+     - added that number of reuses for shower is queried from the 
+       database
+     - added that mirror diameter is queried from the database
+     - added that starting altitude is queried from the database
+     - changed fImpactParameter to fImpactMax
+
+
+
+ 2008/11/12 Daniela Dorner
+
+   * datacenter/db/menu.js, datacenter/db/include.php:
+     - added feature to remove lines for table ('-' button at beginning 
+       of each line) and button to get all lines back ('+' at top of 
+       the column)
+
+
+
+ 2008/11/12 Thomas Bretz
+
+   * datacenter/macros/plotstat.C:
+     - added descriptions for the tabs
+     - added legend to all tabs
+     - added beginning and end of period to all tabs
+
+   * mastro/MAstro.[h,cc]:
+     - added new member function GetMoonPeriodMjd
+     - added new member function GetMagicPeriodStart
+
+   * mbase/MTime.[h,cc]:
+     - added new member function SetMoonPeriod
+     - added new member function SetMagicPeriodStart
+
+   * callisto.rc, callisto_Dec04Jan05.rc, callisto_MarApr05.rc,
+     callisto_mux.rc:
+     - adapted number of max events for extraction of
+       pedestals from data runs and set the number of events
+       used for pedestal extraction instead.
+
+   * callisto_mux.rc:
+     - adapted valued for pulse position dtermination to fit better
+       the MUX data (especially get rid of a bias towards higher
+       values from saturating pixels)
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]:
+     - added member function GetNumEvents
+     - changed number of required pixels to 3
+     - made sure that the number of required pixels is correctly 
+       applied
+
+   * mjobs/MJPedestal.[h,cc]:
+     - added new data members to better describe the number of required
+       and aimed events for pulse position and pedestal extraction
+     - changed the filters for the pedestal and pulse position
+       in a way that not more than the requested events will be
+       extracted
+     - added a MContinue which will stop the lop if the pedestal and
+       pulse position extraction has been finished
+     - added more precise checks after the loop to check if enough events
+       were found
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - set fCounter already in Process
+
+   * mpedestal/MExtractPedestal.[h,cc], mpedestal/MPedCalcPedRun.[h,cc],
+     mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - changed type of Calc from Int_t to void
+
+   * mbase/MContinue.[h,cc]:
+     - allow to use MContinue also to return something else in Process()
+       than just kCONTNUE
+
+   * mfbase/MFilterList.h:
+     - added member function GetNumEntries to get the number of
+       list elements
+
+   * mhcalib/MHGausEvents.h:
+     - added member function GetEntries
+
+   * mjobs/MJStar.cc:
+     - only plot the source position in the case of Monte Carlos
+       otherwise it is always 0/0 anyway
+
+   * mraw/MRawRunHeader.cc:
+     - be more precise when printing the run number
+
+   * mtrigger/MTriggerPattern.[h,cc]:
+     - added a Print function to be able to use MPrint
+
+
+
+ 2008/11/11 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - removed obsolete code of rot128
+     - Increased size of ListBox in MARS tab
+
+   * mgeom/MGeomCamDwarf.h:
+     - changed to have the APD camera layout as default
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - removed MMcTriggerLvl2
+     - removed MMcTriggerLvl2Calc
+
+   * mhbase/MH.[h,cc], mhbase/MH3.[h,cc], mhbase/MHArray.[h,cc],
+     mhbase/MHMatrix.[h,cc], mhbase/MHn.[h,cc],
+     mhcalib/MHCalibrationCam.[h,cc], mhist/MHRate.[h,cc],
+     mhcalib/MHCalibrationChargePINDiode.[h,cc], mhflux/MHAlpha.[h,cc],
+     mhflux/MHCollectionArea.[h,cc], mhflux/MHDisp.[h,cc],
+     mhflux/MHEffectiveOnTime.[h,cc], mhflux/MHEnergyEst.[h,cc],
+     mhflux/MHFalseSource.[h,cc], mhflux/MHPhi.[h,cc],
+     mhflux/MHThetaSqN.[h,cc], mhflux/MHThreshold.[h,cc],
+     mhist/MHCamEvent.[h,cc], mhist/MHCamEventRot.[h,cc],
+     mhist/MHEvent.[h,cc], mhist/MHHadronness.[h,cc], 
+     mhist/MHStarMap.[h,cc], mhist/MHTriggerLvl0.[h,cc],
+     mhist/MHWeather.[h,cc], mhvstime/MHPixVsTime.[h,cc],
+     mhvstime/MHSectorVsTime.[h,cc], mhvstime/MHVsTime.[h,cc],
+     mimage/MHHillas.[h,cc], mimage/MHHillasExt.[h,cc],
+     mimage/MHHillasSrc.[h,cc], mimage/MHImagePar.[h,cc],
+     mimage/MHNewImagePar.[h,cc], mimage/MHNewImagePar2.[h,cc],
+     mimage/MHVsSize.[h,cc], mbadpixels/MHBadPixels.[h,cc],
+     mmuon/MHMuonPar.[h,cc], mmuon/MHSingleMuon.[h,cc],
+     mpedestal/MHPedestalCor.[h,cc], mpointing/MHPointing.[h,cc],
+     mranforest/MHRanForest.[h,cc], mranforest/MHRanForestGini.[h,cc], 
+     mreflector/MHReflector.[h,cc]:
+     - changed return type of Fill from bool to int
+     - fixed return value where necessary
+
+   * mhbase/MFillH.cc:
+     - return Int from Fill instead of Bool
+
+
+
+ 2008/11/11 Thomas Bretz, Daniela Dorner
+
+   * datacenter/db/tabs.php:
+     - new script (by chance with the name of an existing sctipt) 
+       plotting the tabs of status displays
+       the old script is not needed anymore and is therefore 
+       overwritten
+
+   * datacenter/db/tabs.js:
+     - added (js for tabs.php)
+
+   * datacenter/db/tabs.css:
+     - added (layout for tabs.php)
+
+
+
+ 2008/11/11 Daniela Dorner
+
+   * datacenter/db/tabs.php:
+     - fixed path for ganymed
+     - added plotdb for ganymed
+
+   * datacenter/db/datasetinfo-aio.php:
+     - added link for plotdb for ganymed
+
+   * datacenter/db/datasetinfo-aio.php, datacenter/db/sequinfo-aio.php:, 
+     datacenter/db/index-header.html:
+     - uncommented link to ganymed.php and sequences.php, as these 
+       scripts are not yet updated to new data structure
+
+   * datacenter/db/datasetinfo-aio.php, datacenter/db/sequinfo-aio.php:
+     - implemented link to new tabs.php
+
+   * datacenter/db/plotinclude.php:
+     - implemented new files names for showplots*.php
+
+   * datacenter/db/runinfo-aio.php:
+     - ranges are now expanded when page is loaded
+
+   * datacenter/scripts/budb, datacenter/scripts/fillcamera,
+     datacenter/scripts/mcsequences:
+     - exchanged vela by variable for host
+
+   * datacenter/scripts/dowebplots:
+     - removed sequence/dataset number from file name of csv file
+     - removed general rsync of callisto/star/ganymed at the end of the
+       script, as --delete was not working in the intended way and 
+       the single directories are rsynced anyhow
+
+
+
+ 2008/10/29 Thomas Bretz
+
+   * mpointing/MSrcPosCalc.cc:
+     - return kERROR instead of kFALSE if source position is too far
+       away from the camera center
+     - DeltaPhi replaced by Angle to take declination into account
+
+   * mreport/MReport.cc:
+     - fixed a typo (200805190 instead of 200605190)
+
+
+
+ 2008/10/23 Daniel Hoehne-Moench
+
+   * datacenter/macros/fillcamera.C:
+     - added and changed some parameters
+
+   * datacenter/scripts/fillcamera:
+     - rewritten
+
+
+
+ 2008/10/14 Thomas Bretz
+
+   * mjobs/MJPedestal.cc:
+     - for extracting the pulse position we have to allow sum events 
+       but require level 1 trigger instead of disallowing sum-events
+
+
+
+ 2008/10/13 Thomas Bretz
+ 
+   * callisto.cc, ganymed.cc, mars.cc, merpp.cc, readdaq.cc, 
+     readraw.cc, showlog.cc, showplot.cc, sinope.cc,
+     sponde.cc, star.cc:
+     - adapted to changes in MArgs
+
+   * mbase/MArgs.[h,cc]:
+     - interprete all options after -- as arguments
+     - moved removing of root options to a new member function
+
+   * mhist/MHEvent.cc:
+     - removed the obsolete M before the run id
+
+   * mjobs/MJMerpp.cc:
+     - fixed a bug which caused RunHedears to be merpped as RunHeader
+
+   * mraw/MRawRunHeader.cc:
+     - only use the event-number fix after run 326152, which is
+       more accurate
+
+   * mreport/MReport.cc:
+     - implemented a new version fix, namely 200809300
+
+   * mreport/MReportCC.cc:
+     - implemented interpretation of new format 200809030
+
+
+
+ 2008/10/13 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C:
+     - implemented SuperArehucas version 080912-0
+
+
+
+ 2008/09/16 Stefan Ruegamer
+
+   * datacenter/scripts/budb:
+     - redirection to a not existing file changed for the finish command
+
+   * datacenter/scripts/checkmd5sum:
+     - script is now executed specifying the tape number in the command
+       line
+     - added several outputs to the logfile
+     - removed phoenix login, the script is being executed now via
+       read_lapalma_tapes from phoenix
+     - added check for empty md5 files
+
+   * datacenter/scripts/runstar:
+     - corrected staging of files, _E-files are no longer existing
+
+
+
+ 2008/09/05 Daniela Dorner
+
+   * datacenter/scripts/sourcfile:
+     - fixed bug (setstatus was not working for datasets and runs)
+
+
+
+ 2008/08/27 Daniela Dorner
+
+   * datacenter/scripts/fillganymed:
+     - fixed bug in getting the dataset number (removed telescope 
+       number)
+
+   * datacenter/scripts/copyscript:
+     - fixed bug in find for optical files
+     - added some logging
+
+
+
+ 2008/08/25 Daniela Dorner
+
+   * datacenter/macros/filloptical.C:
+     - added different return values in case of not matching lines
+     - added new columns (ellipticity and position angle)
+
+   * datacenter/macros/fillobjects.C, datacenter/macros/fillobjects2.C:
+     - InsertUpdate instead of Insert now
+
+   * resources/TeVsources.txt, resources/good_compstars_R.txt:
+     - added new sources
+
+   * datacenter/scripts/copyscript:
+     - implemented new return values
+     - improved find for optical files
+
+   * datacenter/scripts/dbchk:
+     - adapted check for consistency between sequencefiles and content 
+       of database: now only done for sequences where the file is 
+       already written
+
+
+
+ 2008/08/22 Daniela Dorner
+
+   * datacenter/scripts/scriptlauncher:
+     - fixed bug in starting scripts with command line options
+
+   * datacenter/scripts/dowebplots:
+     - fixed bug (showplot was not executed in the mars directory)
+     - moved all general rsyncs to the end of the script
+
+
+
+ 2008/08/21 Daniela Dorner
+
+   * datacenter/db/plotdb.php:
+     - changed input field from 6 to 8 digits
+
+   * datacenter/scripts/dbchk:
+     - added check if something on nightly basis failed
+
+   * datacenter/scripts/dowebplots:
+     - fixed sequencepath in rsync
+
+   * datacenter/scripts/jobmanager:
+     - changed choosing of jobmanager (data or mc) from if to case
+     - implemented case-statement for the choice of the queueing 
+       system (condor and sun grid engine implemented up to now)
+     - implemented commands for sun grid engine 
+
+   * datacenter/scripts/jobmanager, datacenter/scripts/setup:
+     - moved defining of array scripts and pnoswe(ek) from sourcefile 
+       to jobmanager
+     - fixed problem with mc jobmanager pnos
+
+   * datacenter/scripts/setup:
+     - implemented definition of queueing system
+     - exchanged camera version
+
+   * datacenter/scripts/sourcefile:
+     - host is retrieved from sql.rc now
+
+   * datacenter/scripts/runcorsika, datacenter/scripts/runreflector, 
+     datacenter/scripts/runcamera, datacenter/scripts/setup:
+     - moved defining of detectorpath from scripts to sourcefile 
+
+   * datacenter/scripts/runcorsika, datacenter/scripts/setup:
+     - implemented variable for path of Mmcs
+
+   * datacenter/scripts/runcorsika:
+     - exchanged 'operator' in inputcard by `whoami`
+     - implemented usage of function for new datastructure
+
+   * resources/steps.rc:
+     - added line for primaries for MCRunProcessingStatus
+
+
+
+ 2008/08/15 Daniela Dorner
+
+   * datacenter/macros/plotdb.C, datacenter/macros/plotoptical.C,
+     datacenter/macros/plotstat.C, datacenter/macros/plotusage.C:
+     - added call plot*(TString path) needed for the script 
+       dowebplots
+     - added path to output file
+
+   * datacenter/macros/plotdb.C:
+     - added path to call plotdb(dataset)
+
+   * datacenter/macros/plotoptical.C:
+     - added path to call plotoptical(source)
+
+   * datacenter/macros/plotstat.C:
+     - fixed bug in query
+
+   * datacenter/macros/plotusage.C:
+     - adapted comment
+     - removed not needed calls
+
+   * datacenter/scripts/doqualityplots, 
+     datacenter/scripts/webupdate-star, 
+     datacenter/scripts/webupdate-sinope, 
+     datacenter/scripts/webupdate-callisto,
+     datacenter/scripts/webupdate-ganymed:
+     - deleted (not needed anymore, done by dowebplots now)
+
+   * datacenter/scripts/dowebplots:
+     - rewritten completely: script now handles not only creating 
+       web plots for ganymed, star and callisto, but also plotdb, 
+       plotusage, plotstat and plotoptical
+     - implemented steering via DB for ganymed, star and callisto to 
+       make sure that all plots are produced
+     - added rsync to this script
+     - via command line options it is possible to choose which plots 
+       should be produced
+     - redirect of the root error (used to output mean values) to 
+       txt files in the webdirectory
+     - added writing of csv file (read by tabs.php)
+
+   * datacenter/scripts/run.condor:
+     - added 'Arguments' (needed to submit dowebplots including
+       command line opticon to condor) 
+
+   * datacenter/scripts/scriptlauncher:
+     - removed makedir of $listpath and $lockpath (done in setup
+       already)
+     - exchanged algorithm to loop over scripts to allow for scripts
+       with command line option
+
+   * datacenter/scripts/sourcefile, datacenter/scripts/jobmanager:
+     - moved definition of $column from sourcefile to jobmanager
+       to allow for usage of the function getstatus by other scripts
+       than the jobmanager
+
+   * datacenter/scripts/sourcefile:
+     - removed definition of webpath (already defined in setup)
+     - removed making of $listpath (not needed anymore)
+     - added fail code for dowebplots (27)
+     - additional if-clause in the getstatus function to allow 
+       for using it even if no column is defined
+     - removed not needed 'numproc=0'
+
+   * resources/steps.rc:
+     - added steps for webplots (fWebCalib, fWebStar, fWebGanymed, 
+       fWebPlotDBGanymed)
+
+
+
+ 2008/08/14 Daniela Dorner
+
+   * datacenter/macros/plotusage.C:
+     - added (macro to plot condor usage from DB)
+
+
+
+ 2008/08/13 Daniela Dorner
+
+   * datacenter/scripts/setup:
+     - removed listpath (not used anymore)
+     - removed commented, not needed lines
+
+
+
+ 2008/08/13 Stefan Ruegamer
+
+   * datacenter/scripts/webupdate-star:
+     - added option to prevent melibea-Q-files from being rsynced
+
+
+
+ 2008/08/12 Stefan Ruegamer
+
+   * datacenter/script/checkmd5sum:
+     - fixed the check for raw files
+     - added a check for the nunmber of checked files
+
+   * datacenter/scripts/webupdate-callisto,
+     datacenter/scripts/webupdate-star:
+     - fixed the --exclude option so Y and I file do no longer get
+       synced
+
+   * datacenter/script/zipscript:
+     - added check if the raw file is no longer existing (happens when
+       multiple zipscripts are started)
+     - added check for the case that the sequence number is 0
+     - fixed some echos
+     - added telescope number for the db update query
+
+
+
+ 2008/08/08 Daniela Dorner
+
+   * datacenter/db/magicdefs.php:
+     - fixed sorting for sequences
+
+   * datacenter/scripts/checkstardone, 
+     datacenter/scripts/writedatasetfiles:
+     - fixed bug in getting the dataset number (removed telescope 
+       number)
+
+
+
+ 2008/08/07 Daniela Dorner
+
+   * datacenter/scripts/runganymed:
+     - removed telescope number
+
+   * datacenter/scripts/checkstardone:
+     - added dataset number to output
+
+   * datacenter/db/runinfo-aio.php, datacenter/db/sequinfo-aio.php
+     datacenter/db/magicdefs.php:
+     - improved sorting with combination of (file-,) run/sequ- and 
+       telescope number
+
+
+
+ 2008/08/07 Thomas Bretz
+
+   * datacenter/macros/buildsequenceentries.C:
+     - fixed a problem with the check whether a sequence already
+       exists. It was always belived that the sequence doesn't exist.
+
+
+
+ 2008/08/07 Stefan Ruegamer
+
+   * datacenter/scripts/makecallistolinks
+     - added a condition to prevent the linking of the old Dec04Jan05.rc
+       for mux data
+
+   * datacenter/scripts/cutslices
+     - changed checklock to checklock continue to prevent the program 
+       from exiting if a lock file already exists
+
+
+
+ 2008/08/06 Daniela Dorner
+
+   * datacenter/db/sequinfo.php, datacenter/db/sequinfo-aio.php,
+     datacenter/db/sequence.php, datacenter/db/runinfo.php,
+     datacenter/db/runinfo-aio.php, datacenter/db/resetseq.php,
+     datacenter/db/plotinclude.php, datacenter/db/magicdefs.php,
+     datacenter/db/ganymed.php, datacenter/db/findoffdata.php,
+     datacenter/db/dbstatus.php, datacenter/db/datasetinfo-aio.php,
+     datacenter/db/datasetinfo.php, datacenter/db/datacheck.php,
+     datacenter/db/builddatasets.php:
+     - changed syntax of left join to 'using(columnname)'
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php,
+     datacenter/db/magicdefs.php, datacenter/db/builddatasets.php
+     datacenter/db/dbstatus.php, datacenter/db/findoffdata.php,
+     datacenter/db/plotinclude.php, datacenter/db/resetseq.php,
+     datacenter/db/sequence.php, datacenter/db/sequinfo.php:
+     - implemented telescope number
+
+   * datacenter/db/runinfo-aio.php:
+     - moved pulldown for number of results
+
+   * datacenter/db/resetseq.php:
+     - removed unknown ip adresses, added names to known ip adresses
+
+   * datacenter/db/menu.php:
+     - changed width input field for sequence number in run menu from 
+       6 to 8
+
+
+
+ 2008/08/06 Thomas Bretz
+
+   * mfileio/MReadTree.cc:
+     - removed some debug out
+
+
+
+ 2008/08/06 Stefan Ruegamer
+
+   * callisto_mux.rc
+     - changed the extractor window from 15 64 to 0 49
+
+   * datacenter/scripts/setup
+     - commented the lines containing cutslices out
+
+
+
+ 2008/08/05 Stefan Ruegamer
+
+   * datacenter/scripts/movingrawfiles:
+     - added checks for owner of the file
+     - adapted the script to the different pathes
+       
+   * datacenter/scripts/zipscript:
+     - added telno and fileno so it works with the new files
+     - added the telno to the calzip-lock file
+
+   * datacenter/scripts/runcallisto:
+     - added the telno to the calzip-lock file
+     - removed the link to callisto_mux_new.rc, it is no longer needed
+
+
+
+ 2008/08/05 Thomas Bretz
+
+   * datacenter/macros/fillstar.C:
+     - fixed the case of invalid effective on times
+     - fixed the regular expression to find the MSequence in old files
+     - added information about the dc currents
+
+   * datacenter/macros/fillcondor.C:
+     - added
+
+
+
+ 2008/08/05 Daniela Dorner
+
+   * datacenter/tools/resetpriorities:
+     - added (script to reset priorities in the tables RunProcessStatus,
+       SequenceProcessStatus and DataSetProcessStatus)
+
+   * datacenter/scripts/makecallistolinks:
+     - removed not needed output
+
+   * datacenter/scripts/sourcefile:
+     - fixed bug in query of setstatus 
+     - improved if-clause to avoid unneccessary output
+
+   * datacenter/db/menu.php:
+     - changed width input fields for ranges from 6 to 8
+
+   * datacenter/scripts/condorstatistic:
+     - fixed logging output
+
+   * datacenter/scripts/dbchk:
+     - added checking of consistency with table SequenceProcessStatus
+
+   * resources/steps.rc:
+     - fixed primaries of DataSetProcessStatus
+
+
+
+ 2008/08/04 Daniela Dorner
+
+   * datacenter/scripts/runstar:
+     - removed linking of rc-files and command line argument --config
+       (usage of star_mux.rc  not needed anymore)
+
+
+
+ 2008/08/04 Thomas Bretz
+
+   * RELEASE V2.1.1
+
+
+
+ 2008/08/04 Stefan Ruegamer
+
+   * datacenter/scripts/setup:
+     - added compux/cutslices to the jobmanager queue
+ 
+   * datacenter/scripts/movingrawfiles:
+     - modified the regex for finding the run number such that it
+       satisfies the new raw file convention
+     - the script now searches for files in /magic and /data, so
+       movingrawfiles2 is obsolete
+
+   * datacenter/scripts/cutslices:
+     - adapted the script for jobmanager use
+     - included some more checks
+
+
+
+ 2008/08/04 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added a filter against very bright events cleaning the 
+       bad pixel plot
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - slightly tightened the spark cut in length vs size
+
+   * ganymed_wobble.rc:
+     - now uses the default (still 3) for the number of wobble
+       positions
+
+   * mbase/MParEmulated.[h,cc]:
+     - some improvements to support collection (still not finished)
+
+   * mraw/MRawRunHeader.cc:
+     - Implemented a fix for run-numbers between 1001348 and 1001396 
+       which were incorrectly assigned by the cc.
+     - changed order of fix and check
+
+   * resources/calibration_spline.rc:
+     - updated muon calibration constants for the periods 51-57, 
+       58-63 and 67-
+
+
+
+ 2008/08/04 Daniela Dorner
+
+   * datacenter/scripts/setup:
+     - changed order of scripts (now: ganymed, star, callisto)
+     - adapted number of allowed processes (more CPUs available now)
+     - commented mc jobmanager stuff out, as it is not yet working
+       completely
+
+
+
+ 2008/08/03 Daniela Dorner
+
+   * datacenter/scripts/runcamera, datacenter/scripts/runcorsika, 
+     datacenter/scripts/runreflector:
+     - removed primvar
+
+   * datacenter/scripts/condorstatistics:
+     - added (script calling the macro fillcondor.C to fill condor
+       statistics to the database, tars the condor-statistic files
+       afterwards)
+
+   * datacenter/scripts/dowebplots:
+     - added converting from ps to pdf and removing of ps
+
+
+
+ 2008/08/02 Thomas Bretz
+
+   * datacenter/scripts/dbchk:
+     - if the regular expression in sed doesn't find anything
+       nothing is replaced (this case is now handled)
+
+   * mjobs/MJPedestal.cc:
+     - removed the obsolete shift variable in PosePosCheck
+     - do not allow lo-gain starts < 0
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - changed lo-gain stat sift to -1.0 (which is the valie which
+       in use anyway)
+
+   * msignal/MExtractTimeAndCharge.h:
+    - do not add the lo-gain offset wehen setting the start-shift
+
+   * msignal/MExtractor.cc:
+     - make sure Print() prints the class description 
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - if the MC camera files are new enough the source position on the
+       camera is now calculated from the stored telescope and shower
+       orientation
+
+
+
+ 2008/08/01 Thomas Bretz
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - added starguider calibration 328198
+
+   * resources/starguider00328198.txt:
+     - added
+
+   * datacenter/macros/plotdb.C:
+     - added fMedNumPheInner/outer
+     - added fRelChargeRmsOuter
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added %%title%% as a possibility in the filename
+     - added some code to write an XML instead of a csv file
+       (still not in-use)
+
+   * mjobs/MJCut.cc, mjobs/MJSpectrum.cc:
+     - replaced RunNumber by FileId
+
+
+
+ 2008/07/31 Daniela Dorner
+
+   * resources/steps.rc:
+     - added missing influences and needs for DataSetProcessStatus
+
+   * datacenter/scripts/checkstardone:
+     - removed breaks
+     - removed not needed variables
+     - changed dataset from string to int in call of macro
+
+   * datacenter/scripts/budb:
+     - added output how to create database MyMagic
+     - added removing of logfiles
+     - some small inprovements
+
+
+
+ 2008/07/31 Thomas Bretz
+
+   * merpp.cc:
+     - fixed merpping a single report file
+     - Strip the dir name from MJMerpp's name
+
+   * mreports/MReportCamera.cc:
+     - also allow empty HV Settings file names
+
+   * datacenter/macros/checkstardone.C:
+     - fixed the query
+     - fixed a typo
+
+   * datacenter/macros/fillcalib.C:
+     - changed ouput
+     - get seq-number from sequence instead of file-name
+     - added telescope number
+     - added fRelChargeRmsInner/Outer
+     - added fMedNumPheInner/Outer
+     - don't user TEnv anymore
+
+   * datacenter/macros/fillsignal.C
+     - get seq-number from sequence instead of file-name
+     - added telescope number
+
+   * datacenter/macros/fillstar.C:
+     - changed ouput
+     - get seq-number from sequence instead of file-name
+     - added telescope number
+     - added fTotOnTime
+
+   * callisto.rc, callisto_Dec04Jan05.rc, callisto_mux.rc:
+     - removed obsolete reference to ExtractTime
+
+
+
+ 2008/07/30 Thomas Bretz
+
+   * mjobs/MSequence.cc:
+     - fixed a typo in the new Read function
+
+
+
+ 2008/07/30 Daniela Dorner
+
+   * resources/steps.rc:
+     - added 
+     - adapted to new data structure
+
+   * steps.rc:
+     - removed
+
+   * datacenter/macros/setupdb.C, datacenter/macros/setstatus.C, 
+     datacenter/macros/getdolist.C:
+     - removed
+
+   * datacenter/db/datacheck.php, datacenter/db/datasetinfo.php, 
+     datacenter/db/magicdefs.php, datacenter/db/menu.php, 
+     datacenter/db/resetseq.php, datacenter/db/runinfo.php, 
+     datacenter/db/sequinfo.php, datacenter/macros/resetcolumn.C:
+     - removed fFailedCodeAdd
+     - changed fFailedCode to fProgramId
+
+   * datacenter/scripts/sourcefile:
+     - adapted path of steps.rc
+     - added new additional primaries to functions setstatus, getstatus
+       gettodo and getdolist
+     - merged function gettodo and getdolist
+     - removed todofile
+     - removed fFailedCodeAdd
+     - changed fFailedCode to fProgramId
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/doexclusions, 
+     datacenter/scripts/fillcallisto, datacenter/scripts/fillstar, 
+     datacenter/scripts/fillganymed, 
+     datacenter/scripts/writedatasetfiles, 
+     datacenter/scripts/writesequencefiles:
+     - implemented usage of getodo (new merged function)
+     - removed todofile
+     - removed primval
+
+   * datacenter/scripts/runcallisto, datacenter/scripts/dodatacheck, 
+     datacenter/scripts/runganymed, datacenter/scripts/runstar:
+     - implemented usage of getodo (new merged function)
+     - removed primval
+
+   * datacenter/scripts/checkstardone
+     - removed comadd
+
+   * datacenter/scripts/runcallisto
+     - append output of stage.C instead of overwriting logfile
+
+   * datacenter/macros/resetcolumn.C:
+     - added return 0 and output, as this macro is not yes adapted to 
+       the new data structure for MAGIC II
+
+   * datacenter/scripts/makecallistolinks:
+     - exchanged grepping for reason by db-query (return code 13)
+     - exchanged call of resetcolumn.C by direct db-query
+
+
+
+ 2008/07/29 Stefan Ruegamer
+
+   * datacenter/scripts/zipscript
+     - modified the regex for finding the run number such that it
+       satisfies the new raw file convention
+
+
+
+ 2008/07/28 Daniela Dorner
+
+   * datacenter/scripts/correcttime, datacenter/scripts/cutslices, 
+     datacenter/scripts/dodatacheck:
+     - added exit and output, as these scripts are not adapted to the 
+       new data structure for MAGIC II
+
+   * datacenter/scripts/dbchk:
+     - added outputs to processlog 
+
+   * datacenter/scripts/doexclusions, 
+     datacenter/scripts/writesequencefiles,
+     datacenter/scripts/buildsequenceentries:
+     - added telescope number 1 to call of macro
+
+   * datacenter/scripts/sourcefile:
+     - added priority  
+
+
+
+ 2008/07/27 Thomas Bretz
+
+   * merpp.cc:
+     - added include of TClass to work with root 5.20
+
+   * mbase/MParEmulated.[h,cc]:
+     - for root 5.20/00 we have to use TVirtualStreamer instead
+       of TStremaer
+
+   * mbase/MStatusDisplay.cc:
+     - the workaround had to be fixed because since we don't change
+       gPad for printing anymore all following line and text drawings
+       reffered to the wrong gPad
+
+   * datacenter/scripts/doqualityplots, datacenter/scripts/dowebplots:
+     - also antialias text 
+     - save as interlaced png
+
+   * mbase/MThread.h:
+     - use a reinterpret_cast when returning the Thresd's result
+       (this gave a correct warning on 32bit systems)
+
+   * mhbase/MH3.h:
+     - when available return the histogram title as title (without axis)
+     - implemented GetFullTitle member function to return the full title
+
+
+
+ 2008/07/25 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - expand path name for csv files
+
+   * mfileio/MReadFiles.cc:
+     - print a warning if no file was added
+
+   * mfileio/MReadTree.cc:
+     - updated warning if no file was added
+     
+   * mfileio/MReadScanFile.[h,cc]:
+     - for safety add a postprocessing removing the contents
+       from the list
+     - also removing the contents from the list before filling
+
+   * mhbase/MH3.cc:
+     - fixed an output
+
+   * mtools/MTFillMatrix.[h,cc]:
+     - added a maximum number the eventloop is running over
+
+   * mjobs/MSequence.cc:
+     - replaced gFile by gDirectory
+
+
+
+ 2008/07/23 Thomas Bretz
+
+   * showplot.cc:
+     - allow to read more than one file
+
+   * datacenter/macros/stage.C:
+     - changed the return type to int
+
+   * mbase/MStatusArray.cc:
+     - added a check for the key in read to supress the root error
+       on the console
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - stop update timer in destructor
+     - added new member function GetNumTabs
+     - we don't need to switch to batchmore when painting canvases
+       anymore
+     - removed an obsolete cout
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed again the wrong names of the tasklists
+
+   * mjobs/MSequence.[h,cc]:
+     - set default telescope to 1 so that reading old sequence files
+       gives valid sequences.
+     - overwrote Read to allow reading also old sequences which
+       have no default name in the files
+     - removed output of "DataPath" from Print
+
+   * msql/MSQLMagic.[h,cc]:
+     - added a second InsertUpdate
+     - added ExistRow
+
+   * datacenter/scripts/runcallisto:
+     - adapted to all other changes
+     - removed merpping of caco-files
+
+
+
+ 2008/07/22 Thomas Bretz
+
+   * mbase/MTime.cc:
+     - do not check the return value of mktime (this would
+       fail for dates before 1970)
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJStar.cc:
+     - distinguish between data-runs and mc-runs for the rate plot
+     - named the tasklist for pedestal and calib extraction
+
+   * mjobs/MJMerpp.cc:
+     - precheck the accessibility of all files if a sequence
+       is processed
+
+   * mjobs/MSequence.cc:
+     - the file number is three digits
+     - the Tag for data runs is DatRuns not DataRuns
+
+   * mfileio/Makefile, mfileio/FileIOLinkDef.h:
+     - added MReadFiles
+     - added MReadScanFile
+
+   * mfileio/MReadFiles.[h,cc], mfileio/MReadScanFile.[h,cc]:
+     - added
+
+   * mfileio/MreadRflFile.[h,cc]:
+     - derived from MReadFiles (untested)
+
+   * datacenter/macros/checkfileavail.C:
+     - fixed a type (TSQLRow instead of TSQlRow)
+     - added a missing ;
+
+   * mfileio/MReadTree.[h,cc]:
+     - added some includes
+     - added the IsOwned member function to make sure we don't
+       spoil memory when out pointers are deleted in the destructor
+     - removed some really obsolete workarounds
+     - added a member function to add friends
+     - don't allocate memory in AddFile
+     - implemented the possibility to process also friends
+     - implemented the possibility to read branches from unknown
+       "vendors", i.e. branches for which the class is not available
+       in the dictionary
+     - added a list to hold all parameter containers to be able to 
+       call SetReadyToSave more easily than previously
+
+   * mbase/MParEmulated.[h,cc]:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MParEmulated
+
+   * mbase/MParameters.h:
+     - added functions to get the pointer to the values. Handle this
+       with care.
+
+   * mbase/MParConatiner.h:
+     - made GetterMethod virtual to allow MParEmulated to overwrite it
+     - made fgListMethodCall protected to allow MParEmulated to
+       add its new TMethodCalls
+
+   * datacenter/macros/checkfileavail.C:
+     - removed dependence on caco-files.
+     - fixed query
+     - output query in case of failure
+
+   * datacenter/scripts/checkfilesforsequenceavail:
+     - fixed to use new checkfileavail.C
+
+   * mcalib/MCalibrateData.cc:
+     - removed the fixed scale factor for MCs. It is now left open,
+       thus it can be changed from the callisto resource file
+
+   * mdata/MDataMember.cc:
+     - small improvement to error output
+
+   * mfileio/MWriteRootFile.cc:
+     - small change to log-level
+
+   * mbase/MTaskList.cc:
+     - in case of an unknown return value stop event loop
+
+   * mfileio/MRead.cc:
+     - use gSystem->BaseName to get file name
+
+
+
+ 2008/07/21 Thomas Bretz
+
+   * mbase/MParContainer.[h,cc]:
+     - adde new static ember functions GetClass
+
+   * mbase/MParList.[h,cc], mbase/MStatusArray.[h,cc],
+     mreport/MReportHelp.cc:
+     - use new GetClass function
+
+
+
+ 2008/07/20 Thomas Bretz
+
+   * callisto.cc, star.cc, mjobs/MDataSet.cc, mjobs/MJCalibrateSignal.cc,
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc, mjoptim/MJOptimize.cc,
+     mmain/MEventDisplay.cc:
+     - replaced Setup*Runs by GetRuns
+
+   * datacenter/macros/buildsequenceentries.C:
+     - output if something is deleted
+
+   * datacenter/macros/plotdb.C:
+     - added kGroupByDay option
+     - some small changes
+     - made group by work with "as"
+     - made use of TEnv obsolete
+
+   * datacenter/macros/plotrundb.C:
+     - added telescope number as otpion
+
+   * datacenter/scripts/checkfilesforsequenceavail:
+     - added telescope number 1 to call of checkfileavail.C
+
+   * mbase/MTime.cc:
+     - made SetSqlDateTime more flexible
+
+   * mjobs/MJMerpp.[h,cc]:
+     - added (basically the code from merpp.cc)
+     - enhanced with the possibility to merpp a whole sequence
+
+   * merpp.cc:
+     - use new MJMerpp
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJMerpp
+
+   * datacenter/macros/checkfileavail.C, datacenter/macros/checkstardone.C:
+     - reduced queries to a single query
+     - take sequence number as argumenet instead of filename
+
+   * datacenter/scripts/checkstardone:
+     - adapted to changes in checkstardone.C
+
+   * mjobs/MSequence.[h,cc]:
+     - a lot of rework to the file-interface
+     - included subsystem (cc) files
+     - some renaming to some functions
+     - improved the interface to the database
+     - unified the Setup*Runs into GetRuns
+     - when inflating a sequence name allow to use [tel:]squence now
+
+   * mjobs/MSequenceSQL.[h,cc]:
+     - adapted to changes in MSequence
+
+   * datacenter/macros/stage.C
+     - added
+
+   * mjobs/MJStar.cc:
+     - changed displayed title according to the other jobs
+     - changed Setup*Runs to GetRuns
+     - unified output when finished
+     - make sure the weight for the rate tab is not 0
+     - read the currents now from the camera instead of the currents tree
+
+
+
+ 2008/07/19 Thomas Bretz
+
+   * datacenter/macros/buildsequenceentries.C:
+     - Use the GetId also in the constructor of Rule
+     - fixed reading of the sections in the sequences.rc
+
+   * datacenter/macros/writesequencefile.C:
+     - included iostream
+
+   * mjobs/MSequence.[h,cc]:
+     - updates some comments
+     - simplified the comparison functions
+     - calculate fPeriod automatically in any case 
+       (do not read from file)
+     - added X for excluded to AddFile
+     - use AddFile in ExludeFile
+     - removed incorrect calles to MJob::SortArray
+     - call SortArrays correctly in AddFile
+     - changed default for telescope from 1 to 0 in SQL constructor
+     - allow to set a default path from within the sequence file
+       (in most cases this won't help much)
+
+   * mjobs/MSequenceSQL.[h,cc]:
+     - if telescope number is 0 check whether an unambiguous
+       sequence with this number exists. If existing set the
+       telescope number accordingly
+     - changed default for telescope in constructor to 0 accordingly
+
+
+
+ 2008/07/18 Thomas Bretz
+
+   * mbase/MTime.cc:
+     - GetStringFmt was taking the daylight saving time into account
+       (hopefully this fix is not too much dependent on the kernel)
+
+   * mjobs/MSequence.cc:
+     - added some preliminary code for comparing two sequences
+     - fixed output in Print (the "s" was missing in LightConditions)
+     - do not write the "Run[0-]*" line for anything else than
+       the "Runs" (needs more fixes)
+
+   * mjobs/MSequenceSQL.cc:
+     - added a sanity check
+
+
+
+ 2008/07/17 Thomas Bretz
+
+   * mjobs/MSequence.[h,cc]:
+     - added fTelescope data member
+     - increased class version number accordingly
+     - added return value to WriteFile
+
+   * mjobs/MSequenceSQL.cc:
+     - added TelescopeNumber to where-clause
+     - get fFileNumber from RunData
+     - use File-Id to order files
+     - added telescope number to all constructors
+
+   * automatic-exclusions.rc:
+     - moved as exclusions.rc to resources and updated contents
+       to new doeclusion.C
+
+   * ganymed.cc:
+     - updated Usage output
+     - added new option to change meximum file size
+
+   * merpp.cc:
+     - merpp also MCameraDC from cc-report
+
+   * datacenter/macros/fillsignal.C:
+     - replaces WARNING by ERROR if an error is returned
+
+   * datacenter/macros/writesequencefile.C:
+     - completely redone using new MSequenceSQL
+
+   * mcamera/MCameraDC.[h,cc]:
+     - added the Interprete member function
+     - made MReportCamera and MReportCurrents friends clases
+     - added fStatus
+     - increased class version accordingly
+
+   * mjobs/MJCalibration.cc, mjobs/MJPedestal.cc:
+     - tiny changes to output
+
+   * mreport/MReportCamera.[h,cc]:
+     - removed fStatusDC
+     - removed gkActiveLoadControlVersNum
+     - added interpretation of DC
+     - increased class version by one
+
+   * mreport/MReportCurrents.cc:
+     - moved interpretation of DCs to MCameraDC
+
+   * resources/sequences.rc:
+     - changed some comments
+     - added telescope number to rules
+
+   * datacenter/macros/buildsequenceentries.C:
+     - the building is now based on the file-id (run*1000+file)
+       and it is only done for a single telescope
+     - added telescope number as srgument
+     - added fPriority to SequenceProcessStatus
+     - added fTelescopeNumber to the Sequence table
+     - the sequence number is still idetical to the first run-number
+     - changed reading of resource file such that the telescope
+       number can be given for each subsection
+
+   * datacenter/macros/doexclusions.C:
+     - many simplifications
+     - use telescope number as argument
+     - simplified and improved
+
+   * datacenter/macros/filldotrun.C:
+     - some changes to output
+     - skip comment line at the beginning
+     - skip the line with the telescope number
+     - removed ISNULL from telescope/run/file check
+     - added fPriority to RunProcessStatus
+     - added telescope und file number to RunData and RunProcessStatus
+
+   * datacenter/macros/resetallruns.C:
+     - adapted to new ten:run/file scheme and the new contents
+       of the input file
+
+   * datacenter/scripts/filesondisk:
+     - improved regular expressions to find runs
+     - commmented out caco files
+     - write telescope run and file-number to the file
+     - some simplification
+
+
+
+ 2008/07/16 Thomas Bretz
+
+   * msql/MSQLMagic.[h,cc]:
+     - the wehere clause can now be omitted in Update
+
+
+
+ 2008/07/14 Thomas Bretz
+
+   * datacenter/macros/fillsignal.C:
+     - moved sql.rc to constructor of MSQLMagic
+
+   * datacenter/macros/plotstat.C:
+     - improved beauty of the SQL queries
+     - join by telescope number, run number and file number
+
+   * mbase/MString.[h,cc]:
+     - removed everything except Format which is then identical to
+       newwer root versions TString::Format
+
+   * mastro/MAstro.cc, mastro/MAstroCatalog.cc:
+     - replaced MString::Print by MString::Format
+
+   * mbase/MTime.cc:
+     - In SetSqlDateTime allow also to set dates without time
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - removed MRunIter
+
+   * mfileio/MWriteRootFile.cc:
+     - sow in status line if a tree has been finally copied
+
+   * mhist/MHEvent.cc:
+     - replaced GetRunNumber by GetStringID
+
+   * mjobs/MJCalibrateSignal.cc:
+     - Replaced RunNumber by FileId in trogger pattern display
+     - do not allow to divide by 0
+
+   * mjobs/MJExtractSignal.cc, mjobs/MJCalibTest.cc:
+     - removed obsolete include of MDirIter
+
+   * mjobs/MJPedestal.cc, mjobs/MJCalibration.cc:
+     - replaced MRunIter by MDirIter
+
+   * mjobs/MSequence.[h,cc]:
+     - moved code to compile (inflate) a run filename or a its path
+       to new static function such that they can be accessed from the outside
+
+   * star.cc, callisto.cc, mjobs/MSequence.[h,cc], mmain/MEventDisplay.cc
+     - renamed InflatePath to InflateSeq
+
+   * mpedestal/MPedCalcPedRun.cc:
+     - when checking the runnumber check also for the telescope number
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added new function GetStringID
+
+   * mraw/RawLinkDef.h, mraw/Makefile:
+     - removed MRawSocketRead
+
+   * mpointing/MHSrcPosCam.[h,cc]:
+     - fixed ouput in case a container is not found
+     - made it work for monte carlos, too
+     - use weight when filling histogram
+     - changed circle line styles
+     - changed default in constructor to wobble=kTRUE
+
+
+
+ 2008/07/08 Daniel Hoehne
+
+   * datacenter/db/menu.php, datacenter/db/magicdefs.php:
+     - added new columns (fRateTrigEvts, fRateSumEvts, fRatePedEvts,
+       fRatePedTrigEvts, fRateCalEvts, fRateNullEvts, fRateUnknownEvts,
+       fRatioCalEvents, fPulsePosCalib, fAvgWindSpeed, fAvgTemperature,
+       fAvgHumidity, fAvgTempSky, fAvgCloudiness, fRmsCloudiness)
+
+
+
+ 2008/07/05 Thomas Bretz
+
+   * datacenter/macros/fillcamera.C, datacenter/macros/findcacofiles.C:
+     - changed JOIN to use USING
+     - removed dependence on TEnv
+     - some improvement to includes
+
+   * datacenter/macros/filldotrbk.C, datacenter/macros/fillganymed.C,
+     datacenter/macros/filloptical.C, datacenter/macros/fillsignal.C,
+     datacenter/macros/fillsources.C, datacenter/macros/fillstar.C,
+     datacenter/macros/getdolist.C, datacenter/macros/insertcacofile.C,
+     datacenter/macros/insertdataset.C, datacenter/macros/plotoptical.C,
+     datacenter/macros/plotrundb.C, datacenter/macros/plotstat.C,
+     datacenter/macros/resetallruns.C,
+     datacenter/macros/writedatasetfile.C:
+     - removed dependence on TEnv
+     - some improvement to includes
+
+   * datacenter/macros/filldotrun.C:
+     - make it fail for everything except Magic 1
+     - removed dependence on TEnv
+     - some improvement to includes
+
+   * datacenter/macros/plotoptical.C:
+     - removed MPlot, use MPlot from plotdb instead
+
+   * datacenter/macros/setstatus.C:
+     - some improvement to includes
+
+   * mbase/MTime.[h,cc]:
+     - added function returning day of sunrise as MTime
+
+   * mhflux/MHAlpha.cc:
+     - use BinError instead of BinContents to decide whether the
+       excess time is plotted or not
+
+   * mimage/MHHillas.cc:
+     - changed title of "Center"
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added new class MSequenceSQL
+
+   * mjobs/MSequenceSQL.[h,cc]:
+     - added
+
+   * mjobs/MSequence.[h,cc]:
+     - replaced ReadLightCondition by the more flexible GetLightCondition
+     - added a new constrcutor constructing a MSequence from the database
+     - fixed the output in the comments in Print()
+     - The day and night was printed in a different format than 
+       expected when readin a sequence
+     - fLightCondition and the f*RunsSub were missing in the copy-
+       constructor
+
+   * mjobs/Makefile:
+     - added include of msql
+
+   * msql/MSQLMagic.[h,cc]:
+     - added a comment to ExistStr and allow to set an additional
+       where-clause
+
+   * msql/MSQLServer.cc:
+     - allow to init MSQLServer either by an url or from a named
+       resource file
+     - changed JOIN to use USING
+     - if doing an automatic join join _all_ primaries
+
+   * mtools/MCalendar.cc:
+     - added include of TObjArray needed in newer root versions
+
+
+
+ 2008/07/03 Thomas Bretz
+
+   * datacenter/macros/filldotrun.C:
+     - Replaced MSQKServer by MSQLMagic
+     - this made local functions obsolete
+     - added new format 20080519 including telescope- and file-number
+     - simplified the if-clauses testing for version numbers (due to
+       the initial check only some version numbers allowed anyway)
+     - check for the combination of telescope-, run- and file-number 
+       to be unique.
+
+   * datacenter/macros/plotrundb.C:
+     - use MPlot from plotdb
+     - removed obsolete DataCheck plots
+     - plot only range of dates which makes sense
+
+
+
+ 2008/07/01 Thomas Bretz
+
+   * ganymed.cc:
+     - removed the checks for the accessability of the files. They
+       are checked in the corresponding classes instead
+
+   * sponde.cc:
+     - display only the base name of the ganymed file, not the
+       full path
+
+   * mbase/MMath.[h,cc]:
+     - added a new member function ErrorExc
+     - Let SignificanceExc (former SignificanceLiMaExc) use ErrorExc
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - replaced fSignificanceExc by fErrorExcess
+     - calculate the error instead of the significance (otherwise we
+       get infinity at 0)
+     - also store a negative number of excess events
+     - replaced all -1 in ProjectionZ calls by the histogram limits
+       (including under- and overflows) This is necessary to get
+       root 5.20/00 working
+     - increased class version number according to the changes
+
+   * mjobs/MDataSet.[h,cc], mjobs/MSequence.[h,cc]:
+     - removed wrong usage of fName and fTitle, introduced new data
+       members instead
+     - initialize fName and fTitle in the constructors correctly
+     - always store the full qualified path name
+     - introduced new member functions GetBaseName and GetFilePath
+     - give the ostream as an argument to Print
+     - added new member function WriteFile to directly Print to
+       an fostream
+     - do not print empty values in Print
+     - increased class version number accordingly
+     - removed GetName and GetRcName accordingly
+
+   * mjobs/MDataSet.cc:
+     - set the dataset number to an invalid status if the file could
+       not be accessed
+
+   * mjobs/MJCut.cc:
+     - replaced GetName for the dataset by GetBaseName
+     - make sure the summary file is not created if not requested
+     - do not use pointers to MWriteRootFile to make sure the instances
+       always get deleted
+
+   * mjobs/MJSpectrum.cc:
+     - fixed a bug in the check for the existence of the excess time
+     - replaced GetName for the dataset by GetBaseName
+     - Write the full path name to the ganymed.root into the file
+     - fixed typos in determine
+
+   * mpointing/MPointingDevCalc.cc:
+     - initialize fNsb* members also in PreProcess as correctly 
+       suggested by valgrind
+
+   * mjobs/MJCalibration.[h,cc]:
+     - made the drawing of the bad pixel explanation more automatic
+     - some simplifications to the function drawing all the result tabs
+     - make sure to do the projection without name. Some root versions
+       don't like several plots with the same name in one tab
+     - removed several misleading drawing of number of outliers etc
+     - added setting of min and max to FixDataCheckHist
+     - simplified DisplayDoubleProjection (also unified in code with
+       MJPedestal)
+     - removed all the obsolste and confusing projections of the 
+       individual sectors and camera halves
+
+   * mjobs/MJPedestal.[h,cc]:
+     - make sure to do the projection without name. Some root versions
+       don't like several plots with the same name in one tab
+     - use the unified DisplayDoubleProjection from MJCalibration
+     - removed all the obsolste and confusing projections of the 
+       individual sectors and camera halves
+
+   * mhflux/MHAlpha.cc:
+     - replaced EventsExcess/SignificanceExc by just ErrorEvents
+     - for the moment do not propagate Excesses<=0 to the pads 
+       (not to spoil the logarithmic display, this still needs a fix)
+     - replaced -1 in ProjectionZ by the bin numbers (including
+       under- and overflow bins), otherwise it won't work with
+       root 5.20/00
+     - propagate all result to the timing histogram (it is not
+       logarithmic anyway)
+     - made Paint also work with the new implementation of ProjectionZ
+       via Project3D in root 5.20/00 (it won't reuse the correct
+       histogram from the pad :( )
+     - replaced kFullDotMedium by 0 (no marker) where appropriate
+     - changed the rule not to display the time-histogram
+
+
+
+ 2008/06/30 Thomas Bretz
+
+   * datacenter/macros/fillstar.C:
+     - check whether graphs are empty in a more accurate way
+
+   * datacenter/macros/plotdb.C:
+     - fixed some axis title
+     - increased range of fRatePedTrigEvts
+
+   * msql/MSQLMagic.cc:
+     - added ' around the where clause in UpdateInsert to allowe
+       also for times etc
+
+   * callisto.cc:
+     - removed test-option (it was never used anyway and should
+       be reprogrammed properly)
+
+   * datacenter/macros/plotdb.C, mbase/MStatusDisplay.h, mbase/MTime.h:
+     - removed unused argument
+
+   * mbadpixels/MBadPixelsPix.h:
+     - added static functions to get names and numbers of unsuitable
+       and unreliable levels
+
+   * mbase/MMath.cc:
+     - made MedianDevImp working properly with a template
+
+   * mhcalib/HCalibLinkDef.h, mhcalib/Makefile:
+     - removed MHCalibrationTestCam
+     - removed MHCalibrationTestTimeCam
+
+   * mhcalib/MHCalibrationCam.cc:
+     - removed an obsolete TPad in Draw()
+     - removed some obsolete kCanDelete in Drwa()
+
+   * mhcalib/MHCalibrationChargeCam.cc:
+     - changed some colors to work properly also in root 5.20/00
+
+   * mhflux/MHThreshold.cc:
+     - made Smooth work with root 5.20/00 (to be checked)
+
+   * mhist/MHCamera.[h,cc]:
+     - fixed defaults in Profile and Projection function to match code
+     - fixed some comments
+     - replaced InheritsFrom arguments by TClass statics
+
+   * mjobs/JobsLinkDef.h:
+     - removed MJCalibTest
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/Makefile:
+     - removed obsolete include of MParameterCalc
+
+   * mranforest/MRanForest.cc:
+     - added a cast in BinarySearch to make it work with the template
+       of root 5.20/00
+
+   * mtools/MCalendar.h:
+     - fixed *MENU option
+
+   * mtools/MagicJam.h:
+     - added the Smooth function of root 5.20/00 to be removed from
+       the context menu
+
+
+
+ 2008/06/21 Thomas Bretz
+
+   * callisto.cc, star.cc, ganymed.cc, sponde.cc:
+     - set the display name to a more convinient name
+
+   * datacenter/macros/plotdb.C:
+     - some improvement in setting axis titles and titles
+       automatically from the sql column names
+     - moved the Muon cut to a SetCondition call
+     - renamed some functions
+
+   * mbase/MStatusDisplay.h:
+     - overwrote SetTitle with a function allowing to set a title
+       only if no title set so far
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc, 
+     mjobs/MJPedestal.cc:
+     - set a proper display title and set it only if not already set
+
+   * mjobs/MJPedestal.cc:
+     - changed some filter names to more convinient names
+
+
+
+ 2008/06/20 Thomas Bretz
+
+   * macros/dohtml.C:
+     - added missing mmovie directory
+
+   * mhflux/MHEnergyEst.cc:
+     - changed the fit range to adapt to the new plot
+     - exchanged the two plots on the right to have the correct plot
+       near the 1D histogram
+     - fixed the title of the plot in the top right
+     - call SetNoExponent and SetMoreLoglabels
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - outsources producing the spectral function as string to
+       a new static function FormFlux
+
+   * mpointing/MPointingDevCalc.cc:
+     - added some info
+
+
+
+ 2008/06/19 Thomas Bretz
+
+   * mjobs/MJSpectrum.cc:
+     - small improvement to output
+     - handle underflow bin of effective on-time more accurate
+     - reddid the formattig of the spectral fit
+
+   * mbase/MMath.[h,cc]:
+     - added Format member function
+
+   * datacenter/macros/plotstat.C:
+     - fixed some axis titles
+
+
+
+ 2008/06/19 Thomas Bretz
+
+   * RELEASE 2.1
+
+
+
+ 2008/06/19 Thomas Bretz
+
+   * mraw/MRawRunHeader.cc:
+     - fixed that the line reading the fNumEventsRead vanished 
+
+
+
+ 2008/06/18 Thomas Bretz
+
+   * datacenter/macros/buildsequenceentries.C:
+     - replaced the old calculation of the run-time of one sequence
+       by a more sophisticated using the TIMEDIFF function
+
+   * mjobs/MJStar.cc:
+     - Use File id instead of run number
+     - fixed the units in the display (phe not \\gamma)
+
+   * mjobs/MSequence.[h,cc]:
+     - reorganized header
+     - implemented new scheme including file numbers
+     - increased class version number accordingly
+     - removed some obsolete old, never used, functions and comments
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - renamed RunID to TypeID
+     - return 0 in RunLength if one of the times is invalid
+
+   * Makefile:
+     - removed sinope
+
+
+
+ 2008/06/17 Daniel Hoehne
+
+   * datacenter/macros/fillcamera.C:
+     - added and changed some parameters
+
+   * datacenter/scripts/mcsequences:
+     - added database interaction. Now sequences are built by querying
+       the relevant parameters in the MC database
+
+   * datacenter/scripts/runmccallisto, datacenter/scripts/runmcstar:
+     - added
+
+   * datacenter/scripts/sourcefile:
+     - added failed codes for runmccallisto and runmcstar
+
+
+
+ 2008/06/17 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - SetSelectedPad to 0 before calling DrawClone of TGraph
+     - small reordering of the tabs
+     - removed tab with absolute effective on time
+
+   * mbase/MLog.cc:
+     - make sure that the correct output level is restored after root
+       called the error handler
+
+   * mbase/MStatusDisplay.cc:
+     - Changed backround color to white (_not_ kWhite)
+     - made a sunken border around the canvas
+     - SetFrameBorderMode(0) per default
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added some consistency checks
+     - make the bug fix for the wrong number of events also for
+       V10 and V11
+     - added Getters for RunID and FileID used to idetify
+       the runs more clever than run-number and file-number
+
+
+
+ 2008/06/14 Thomas Bretz
+
+   * merpp.cc:
+     - replaced MRawFileWrite by MWriteRootFile
+
+   * showplot.cc:
+     - added new options to write tiff files
+     - added new options to write csv files
+     - some code simplification
+
+   * datacenter/macros/plotdb.C:
+     - set the title (without axis descriptions) as Tab-title
+     - set FrameBorderMode to 0 for canvas
+
+   * mbase/MStatusArray.[h,cc]:
+     - added a copy constructor taking MStatusDislay as an argument
+     - set gLog to all in Print()
+
+   * mhbase/MFillH.[h,cc]:
+     - allow to set a title in SetNameTab which is used as tab title
+     - therefore added new data member fTitleTab
+     - increased class version by 1
+
+   * mraw/MRawRead.cc:
+     - set ReadyToSave for raw data to be able to use MWriteRootFile
+       in merpp
+
+   * mraw/Makefile, mraw/RawLinkDef.h:
+     - removed MRawFileWrite
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added the tif file format
+     - added the csv file format
+     - fixed the bmp and xml menu entries
+     - added again to list of specials to allow for access from the
+       interpreter
+     - added title to AddTab. The title is stored as canvas title
+     - added some warpper to access FindobjectInCanvas and Print
+       from the MStatusDisplay to gain access from the interpreter
+     - Removed obsolete DrawClonePad wrapper in Display and
+       added title
+     - added FillArray to add all canvases to a temporary MStatusArray
+     - removed obsolete CanvasSetFillColor
+     - use mktemp in UpdatePSHeader
+     - some code cleanup. Moved some common code from the SaveAs function
+       to the new InitWrite* functions
+     - implemented %%tab%% and %%name%%
+     - added a workround (MyCanvas) to get the title and footer in the 
+       ps-files also in root 5.18
+     - removed cloning of the canvases whereever possible.Gave problems
+       in root 5.18 (not yet understood)
+     - changed color mode of postscrip files from rgb to cmyk
+     - UpdatePSHeader not long needed in root >=5.12
+     - reorganized header file
+
+   * mreport/MReportCC.[h,cc]:
+     - removed obsolete fRecTemp
+     - call Copy() in the correct direction
+
+   * mreport/MReportFileRead.[h,cc]:
+     - use a C++ cast instead of a C-cast
+     - add containers to parameter list _before_ calling SetupReading
+     - removed some obsolete comments in the header
+
+   * mjobs/MJStar.cc:
+     - we need to read the new "Rec" tree
+     - and we need to fill from the Rec _and_ CC tree (could give a bias
+       if the rate on both trees would once be identical anymore)
+
+   * mhist/MHCamEvent.cc:
+     - allocate fSum in constructor to allow filling from two different 
+       tasks
+
+
+
+ 2008/06/14 Thomas Bretz
+
+   * mtrigger/MFTriggerPattern.cc:
+     - improved documentation
+
+   * mars.cc, mbase/MStatusDisplay.cc:
+     - changed the M in MARS to "Modular"
+     - rpelaced year in copyright by current year
+
+   * datacenter/macros/plotdb.C:
+     - increased range for the rate of the calibration events
+     - added "RatioCal" tab
+
+   * datacenter/macros/fillstar.C:
+     - fill NULL also if TGraph is empty
+
+   * mastro/MAstro.cc:
+     - included math.h for darwin
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed the named of the MFTriggerPattern
+
+   * merpp.cc:
+     - added new option --only, --rep-run, --rep-file, --header-run,
+       --header-file, --telescope
+     - moved Receiver information from tree CC to tree Rec
+
+   * mbase/MStatusDisplay.cc:
+     - replaced MTime by TDatime
+
+   * mcamera/MCameraRecTemp.[h,cc], mcamera/MCameraTD.[h,cc],
+     mcamera/MCameraTH.[h,cc], mreport/MReportCC.[h,cc]:
+     - moved interpretation of sub-parts of the reports from 
+       MReportCC to the corresponding MCamera* classes
+
+   * mreport/MReport.[h,cc]:
+     - added Copy member function to copy time and state
+     - added CheckTag member function
+     - Implemented skipping of the Telescope number in the reports
+       for version >=200805190
+
+   * mreport/MReportCC.[h,cc]:
+     - access Receiver infomations via new class MReportRec
+       even for old file formats
+     - skip this block in new formats
+     - moved CheckTag to base class
+
+   * mreport/MReportCamera.[h,cc]:
+     - removed CheckTag
+
+   * mreport/MReportFileRead.[h,cc]:
+     - don't check for the number of lines anymore but for -1 instead
+     - changed fNumLine from ULong to Long to allow a negative
+       return value. We don't expect so many lines in a file anyway,
+       do we?
+
+   * mreport/MReportFileReadCC.[h,cc]:
+     - splitted CheckFileHeader into several subfunction
+     - added checks and reading of telescope number and file number
+
+   * mreport/MReportRun.[h,cc]:
+     - added file number from new format
+
+   * mreport/Makefile, mreport/ReportLinkDef.h:
+     - added MReportRec
+
+   * mreport/MReportRec.[h,cc]:
+     - added
+
+   * mhist/MHCamera.cc:
+     - fixed a bug in the profile and projection functions namely that
+       the default was not correctly treated because char* was 
+       compared with char*
+
+   * mbase/MLog.cc, mbase/MMath.cc, mbase/MParContainer.cc,
+     mcalib/MCalibrateData.cc, mcalib/MCalibrationPulseTimeCam.cc,
+     mhbase/MBinning.h, mhbase/MH.cc, mhbase/MHMatrix.cc,
+     mhbase/MHn.cc, mhcalib/MHCalibrationChargeCam.cc, mhflux/MHDisp.cc,
+     mimage/MCameraSmooth.cc, mimage/MConcentration.cc,
+     mjobs/MJCalibration.cc, mjoptim/MJOptimize.cc,
+     mjtrain/MJTrainSeparation.cc, mmuon/MMuonSearchPar.cc,
+     mreport/MReportCurrents.cc, mreport/MReportRun.cc,
+     mtools/MChisqEval.cc:
+     - fixed some cast-away constness warnings
+     - fixed some shadow declarations
+
+   * mhbase/MH.[h,cc]:
+     - removed an old obsolete workaround (ProjectionX/Y)
+
+   * mimage/Makefile, mimage/ImageLinkDef.h:
+     - removed MCameraSmooth
+
+   * mbase/MAGIC.h:
+     - added a new namespace UTF8 with double char characters
+
+   * mbase/BaseLinkDef.h:
+     - added the new namespace UTF8
+ 
+   * mimage/MNewImagePar.cc, mpointing/MPointing.cc,
+     datacenter/macros/fillstar.C:
+     - some characters replaced by the new UTF8 characters
+
+
+
+ 2008/06/13 Thomas Bretz
+
+   * datacenter/macros/fillcalib.C:
+     - fixed a bug introduced by the usage of InserUpdate
+
+   * datacenter/macros/fillsignal.C:
+     - fixed a type (the wrong number was printed to the console)
+
+   * mjobs/MJCalibrateSignal.cc:
+     - let all calibration triggered events pass to calibration
+
+   * mtrigger/MFTriggerPattern.[h,cc]:
+     - count a bit more to increase the printed amout of 
+       information at the end
+
+
+
+ 2008/06/12 Thomas Bretz
+
+   * resources/starguider00267253.txt, resources/starguider00291104.txt:
+     - added
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - added preliminary pointing models
+
+   * mpointing/MPointingDevCalc.cc:
+     - updated comments
+
+   * mraw/MRawCrateData.[h,cc], mraw/MRawEvtHeader.[h,cc],
+     mraw/MRawRunHeader.[h,cc]:
+     - renamed reading the old format to ReadEvtOld
+     - implemented reading format>10
+     - added the header size as new argument to ReadEvt
+
+   * mraw/MRawEvtHeader.cc:
+     - made the argument to DecodeTime const
+     - fixed the return value in ReadEvtOld. kCONTINUE could
+       never be returned
+
+   * mraw/MRawRead.cc:
+     - gives header size for format>10 to ReadEvt
+     - if EvtHeader could not be read correctly return kFALSE
+     - let MRawCrateData::ReadEvt check end-of-file
+
+   * merpp.cc:
+     - improved explanation for -ff option
+
+   * readdaq.cc:
+     - added -ff option
+     - added an option to call MReadRawFiles::SetForceMode
+
+   * mbase/MTime.[h,cc]:
+     - added new member function SetBinary to easy processing
+       of the time from the new run header
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - for the integral (Nm) we have to count also events in under and
+       overflow bins
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc, 
+     mjobs/MJPedestal.cc:
+     - call MRawFileRead::SetForceMode to get the (corrected)
+       old behaviour back (not to stop if an event time is
+       broken but to skip the event)
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - the number of events in format version V9 seems to be
+       to high by one. We correct for this.
+     - added new data members for the header sizes
+     - new data member for the file number
+     - increased cize of fSourceEpochChar
+     - consequently increased class version number by 1
+
+   * datacenter/macros/plotdb.C:
+     - improved some titles
+     - added the new rates
+     - added the new values from the star-files
+
+   * mbase/MStatusDisplay.cc:
+     - removing the canvases from the global list didn't work
+       because some RecursiveRemovs rely on gROOT->FindObject to work
+       (adding them to another list didn't work either)
+
+   * mhflux/MHEnergyEst.cc:
+     - renamed the "Resolution" Histogram accordingly.
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added a histogram showing the arrival time of 
+       extracted interleaved calibration events
+
+   * mraw/MRawEvtData.[h,cc]:
+     - fixed the Draw function. It was broken since the latest changes
+     - added fNumBytesPerSample to the Copy-function
+     - fixed the GetSample-function
+     - added a new member funtion to return the maximu possible
+
+   * mars.rc:
+     - changed the default for the MUX spline to the 50 sl window
+
+   * msignal/MSignalCalc.cc:
+     - scale the pedestal correctly with the scale
+
+   * mjobs/MJStar.cc:
+     - allow filling of pyrometer information to be skipped
+
+   * mhist/MHWeather.cc:
+     - show also colored labels
+
+   * Makefile:
+     - it seems the libmars.so looses read permissions for group
+       and others when it is  moved. Now they are set manually
+
+   * datacenter/fillsignal.C, datacenter/macros/fillstar.C:
+     - added filling of calibration pulse position
+     - use more often NULL in case of no entries. This is less
+       biasing in case of averaging of values
+
+    * macros/tutorials/readrfl.C:
+      - print run header
+      - print event header
+      - skip empty events
+
+   * mhist/MHEvent.cc:
+     - removed the pointing from the histogram names. It's 
+       simply obsolete
+
+   * mjobs/MJSpectrum.[h,cc]: 
+     - removed the kolmogorov test from output
+     - added a new tab showing the energy resolution
+     - therefore added a new BinningImpact to the list of binnings
+     - store the ganymed file's file name in the output
+
+   * mmain/MEventDisplay.cc:
+     - skip events without data in the loop not in the code.
+       This ensures that no task can crash due to this
+       when processing MCs
+
+   * msql/MSQLMagic.[h,cc]:
+     - fixed InsertUpdate. The primary key was not inserted 
+       if Insert was called
+
+
+
+ 2008/06/11 Thomas Bretz
+
+   * mhflux/MHEnergyEst.[h,cc]:
+     - finally replaced fResolution by more correct histograms
+     - some code cleanup in projecting, profiling and drawing
+     - increased class version number by one
+
+   * mbase/MStatusDisplay.cc:
+     - remove the embedded canvas from the global list to prevent
+       global access to it
+
+   * mhbase/MH3.cc:
+     - fixed a bug if in a 2D constructor a 1D profile was created
+
+   * mreport/MReportPyrometer.cc:
+     - tiny changes to the comments
+
+
+
+ 2008/06/10 Thomas Bretz
+
+   * mreport/MReportPyrometer.[h,cc]:
+     - added
+
+   * mreport/Makefile, mreport/ReportLinkDef.h:
+     - added MReportPyrometer
+
+   * mreport/MReportRun.cc:
+     - removed obsolete include of MAstro
+
+   * merpp.cc:
+     - added Pyrometer information
+
+   * mfileio/MWriteRootFile.h:
+     - added new member function AddTree to add a container with the
+       corresponding time-stamp
+
+   * mjobs/MCalibrateSignal.cc, mjobs/MJStar.cc:
+     - replaced some AddContainer by the new AddTree
+     - added Pyrometer information to in- and output, respectively
+
+   * datacenter/macros/fillstar.C:
+     - added new columns fAvgHumidity, fAvgCloudiness, fRmsCloudiness
+       and fAvgTempSky
+
+   * mhist/MHWeather.[h,cc]:
+     - removed the display of the solar radiation which was 
+       never working
+     - added display of the pyrometer data to the display
+     - reorganized display
+
+   * mjobs/MJStar.cc:
+     - added filling of the weather data also from the pyrometer branch
+
+
+
+ 2008/06/09 Thomas Bretz
+
+   * mbase/MArgs.[h,cc]:
+     - for convinience store the full command line as Title
+     - replaced *fArgv by fArgv
+
+   * mbase/MObjLookup.cc:
+     - replaced C-style cast by reinterpret_cast
+
+   * datacenter/macros/fillcalib.C, datacenter/macros/fillstar.C:
+     - removed usage of Nint (obsolete... Form does rounding)
+
+   * datacenter/macros/fillsignal.C:
+     - removed usage of Nint (obsolete... Form does rounding)
+     - added new columns to get trigger rates from TrigPat tab
+     - fixed some small bugs lately introduced
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - fixed a typo in ReInit
+
+
+
+ 2008/06/06 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - added average temperature and wind speed 
+     - reviewed some ranges
+
+   * mhbase/MH3.cc:
+     - in the 2D case with labels and boxes use blue line color
+
+   * mhflux/MHEffectiveOnTime.[h,cc]:
+     - added a new data member fTotalTime counting the total run-time
+       from the run-headers
+     - added the new data member to the display
+     - increased class version number accordingly
+
+   * mjobs/MJCalibrateSignal.cc:
+     - let sum-trigger events pass to get calibrated
+     - improved DefineLabel table for trigger patterns
+     - added MTriggerPattern to output
+
+   * mjobs/MJStar.cc:
+     - added a new tab "Rate" showing the remaining rates per run and
+       trigger pattern after image cleaning
+     - let only event with Lvl1 trigger pass to effective on-time
+       calculation
+     - changed title in plot of avg dc currents and pedestal rms
+
+   * mtrigger/MFTriggerPattern.[h,cc]:
+     - added a counter counting the trigger decision
+     - print the result in the PostProcess
+
+
+
+ 2008/06/06 Thomas Bretz
+
+   * datacenter/macros/fillstar.C:
+     - added windspeed and temperature
+
+   * datacenter/macros/fillcalib.C, datacenter/macros/fillsignal.C,
+     datacenter/macros/fillstar.C:
+     - use MSQLMagic instead of MSQLServer
+
+   * datacenter/macros/plotdb.C:
+     - added wind speed and temperature
+
+   * datacenter/macros/plotstat.C:
+     - added a plot showing the observation time per exposure (based on
+       the source key)
+
+   * mbase/MStatusDisplay.cc:
+     - fixed the SaveAs. A wrong version was comitted
+
+   * mextralgo/MExtralgoSpline.h:
+     - added the missing inclusion of TMath (root 5.18)
+
+
+
+ 2008/06/03 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - added missing inclusion of TMath (root 5.18)
+     - initialize gClient in batch mode to repair broken
+       batch-mode in root 5.18. Fortunately this doesn't
+       break root 5.12
+     - added a SaveAs(const char *c, const Option_t *o)
+       based on the new SaveAs from TGObject
+
+   * mcalib/MCalibrationChargePix.[h,cc],
+     mextralgo/MExtralgoDigitalFilter.[h,cc]:
+     - moved some code to source file to prevent TMath inclusion in
+       header (root 5.18)
+
+   * mcalib/MCalibrationChargeCam.cc, 
+     mcalib/MCalibrationChargePINDiode.cc:
+     - added the missing inclusion of TMath (root 5.18)
+
+   * mgeom/MGeomCam.[h,cc]:
+     - for sanity (a bug in root < 5.18) filling fPixels is now 
+       done via AddAt. This "repairs" the functionality of the
+       Streamer which before didn't store any contants of fPixels
+       nor read any contents.
+     - Removed the custom Clone function. It is now obsolete,
+       because it works through the fixed Streamer
+     - a Copy-member function has been implemented
+     - a custom Streamer has been implemented allowing to read
+       files containing MGeomCamMagic written with root 5.12 
+       with root 5.18
+     - A member function containing the workaround has been implemented
+     - Print got an option ("simple")
+
+   * mgeom/GeomLinkDef.h:
+     - suppress root-Streamer
+
+   * manalysis/MGeomApply.cc:
+     - added the newly necessary call to the StreamerWorkaround
+
+   * mgeom/MGeomPix.[h,cc]:
+     - because with the IgnoreTObjectStreamer set for MParContainer
+       the bits for the outer rings cannot be stored. This was no
+       problem before because in reality they have never been written
+       or read. To store the bits a new data-member fUserBits
+       has been introduced.
+     - accordingly all calles to set or remove the bits have been
+       changed to use fUserBits instead
+     - the class version number has been increased due to the new
+       data member
+     - improved Print-output
+
+
+
+ 2008/06/02 Thomas Bretz
+
+   * mars.cc, sinope.cc:
+     - added include of TClass for TIgnoreStreamer (root 5.18)
+
+   * manalysis/MEventRate.[h,cc]:
+     - moved GetError to source file and included TMath (root 5.18)
+
+   * manalysis/MMultiDimDistCalc.cc, mdata/MDataList.cc:
+     - included math.h (root 5.18)
+
+   * mastro/MAstro.[h,cc], mastro/MVector3.[h,cc], mbase/MRunIter.[h,cc],
+     mbase/MTime.[h,cc], mdata/MDataPhrase.[h,cc], mgeom/MGeomPix.[h,cc],
+     mhcalib/MHCalibrationChargeBlindPix.[h,cc],
+     mhflux/MHCollectionArea.[h,cc], mhft/MHexagonFreqSpace.[h,cc],
+     mimage/MHillas.[h,cc], mmuon/MMuonSearchPar..[h,cc],
+     mpedestal/MPedestalPix.[h,cc], mpointing/MPointingDev.[h,cc],
+     mpointing/MSrcPosCam.[h,cc], mpointing/MPointingPos.[h,cc],
+     mpointing/MPointing.[h,cc]:
+     - moved some code to source file to prevent TMath inclusion in
+       header (root 5.18)
+
+   * mbase/MEnv.cc:
+     - added missing include TObjArray (root 5.18)
+     - removed obsolete EmarkerStyles (root 5.18)
+
+   * mbase/MDirIter.cc:
+     - added missing include TList (root 5.18)
+
+   * mastro/MAstroCatalog.cc, mhist/MHHadronness.cc, mhist/MHWeather.cc,
+     mhvstime/MHPixVsTime.cc, mhvstime/MHVsTime.cc, 
+     mpointing/MHPointing.cc, mranforest/MHRanForest.cc,
+     mranforest/MHRanForestGini.cc, mranforest/MRanForest.cc,
+     mreflector/MHReflector.cc:
+     - added missing inlcude TH1 (root 5.18)
+
+   * mbase/MFilter.cc, mbase/MGMap.cc, mbase/MTask.cc,
+     mcalib/MCalibrationBlindPix.cc, mdata/MDataChain.cc,
+     mfilter/MFEnergySlope.cc, mgeom/MGeomMirror.cc,
+     mgui/MCamEvent.cc, mhbase/MBinning.cc, mhbase/MHMatrix.cc,
+     mhcalib/MHCalibrationPix.cc, mhcalib/MHGausEvents.cc,
+     mhflux/MHEnergyEst.cc, mhist/MHCamEventRot.cc,
+     mhist/MHHadronness.cc, mranforest/MHRanForest.cc,
+     mreflector/MRflEvtHeader.cc, mreflector/MRflSinglePhoton.cc,
+     msql/MSQLServer.cc, mtools/MSimulatedAnnealing.cc,
+     mtools/MTFillMatrix.cc, mcalib/MCalibrationPix.cc,
+     mcalib/MCalibrationQEPix.cc, manalysis/MParameterCalc.cc, 
+     mcalib/MCalibrationTestCalc.cc, mdata/MDataArray.cc, 
+     mgeom/MGeomCamDwarf.cc, mhbase/MH3.cc, mtools/MagicJam.cc,
+     mhcalib/MHCalibrationRelTimeCam.cc, mhft/MGeomCamMagicXT.cc, 
+     mranforest/MRanForestCalc.cc, mtools/MagicDomino.cc,
+     mhflux/MHThreshold.cc, mimage/MStereoPar.cc,
+     mfilter/MFCosmics.cc, mpedestal/MPedestalCam.cc:
+     - added missing include of TMath (root 5.18)
+
+   * mbase/MGTask.cc, mdata/MDataChain.cc, mhbase/MHArray.cc,
+     mjobs/MJCut.cc, mjoptim/MJOptimizeCuts.cc, mmc/MMcEvt.cxx:
+     - added missing include of TClass (root 5.18)
+
+   * mhbase/MH3.cc:
+     - added missing include of THashList (root 5.18)
+
+   * mcalib/MCalibrationChargeCalc.[h,cc], msignal/MExtractor.[h,cc],
+     mpedestal/MPedestalSubtract.[h,cc], msignal/MExtractTime.[h,cc]:
+     - for convinience (rootcint of 5.18) changed "static const TString"
+       to "static const char *"
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - Use TString::Data() for second argument in TF1 constructor.
+       Otherwise it is ambiguous in root 5.18
+
+   * mhbase/MH.cc:
+     - adde missing includes of TColor, TMath and TClass (root 5.18)
+     - implemented a workaround which always uses the correct
+       CreateGradientColorTable (root 5.18)
+
+   * Makefile:
+     - linking of the shared object is now done in /tmp
+     - replaced = by := where possible
+
+   * mjobs/MJCalibrateSignal.cc:
+     - do not invert contcoscal, that's wrong
+
+   * mmovie/MMovieWrite.cc:
+     - added a #if-directive to use either gStyle or TColor
+       for CreateGradientColorTable depending on root-version
+
+   * mimage/MStereoPar.[h,cc], mimage/MStereoCal.[h,cc]:
+     - replaced Monate Carlo container by MPointingPos
+     - made every algorithm unique
+
+
+
+ 2008/06/01 Thomas Bretz
+
+   * callisto.cc, star.cc:
+     - renamed new option to "--null-dev" (clashes with MLog options)
+
+   * mbase/MContinue.cc:
+     - improved output
+
+   * mbase/MTaskList.cc:
+     - fixed broken FindTaskList
+
+
+
+ 2008/05/31 Thomas Bretz
+
+   * callisto.cc, star.cc:
+     - added new option "--null" to suppress run-wise output files
+
+   * mjobs/MJob.h:
+     - added new data-member fNullOut to flag suppression of
+       run-wise output files
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJStar.cc:
+     - use new option HasNullOut from base class
+
+   * mbase/MClone.cc:
+     - fixed Init (still had a constructor like initializer)
+
+   * mtrigger/MFTriggerPattern.h:
+     - included missing MTripperPattern
+
+   * mtrigger/MFTriggerPattern.cc:
+     - removed default arguments
+     - exchanged ^ by ~ 
+     - fixed a few typos in function names
+
+
+
+ 2008/05/27 Stefan Ruegamer
+
+   * datacenter/scripts/filesondisk
+     - changed the search for raw files to not search in hidden folders
+
+
+
+ 2008/05/25 Thomas Bretz
+
+   * mtrigger/MTriggerPattern.cc:
+     - fixed a typo in a comment 
+
+   * mtrigger/MFTriggerPattern.[h,cc]:
+     - some code cleanup (mainly unified all the Require and Deny 
+       functions into one)
+     - added a DenyAll member function
+     - added Allow member functions including an AllowAll member function
+
+   * mjobs/MJPedestal.cc:
+     - To choose pedestals we now deny all other trigger bits except the
+       pedestal bit and in the case of data runs we deny all bits
+       except trigger lvl1 and trigger lvl2
+
+   * mjobs/MJCalibration.cc:
+     - In addition to denial of prescaled calibration events we
+       deny any bit in the unprescaled pattern but allow only
+       calibration events
+
+   * mjobs/MJCalibrateSignal.cc:
+     - Instead of the denial of only calibration and pedestal events,
+       we now deny any bit in the pattern, but allow Trigger Lvl1
+       and Trigger Lvl2 events to choose cosmics
+     - Instead of the denial of only lvl1 and lvl2 events,
+       we now deny any bit in the pattern, but allow pedestal
+       events to choose pedestals
+     - Instead of requiring only calibration events,
+       we now deny any bit in the pattern, but require the calibration
+       bit to choose calibration events
+
+   * mbase/MClone.[h,cc]:
+     - instead of cloning the object again and again we now clone
+       it once and then just copy the contents. A new option has
+       been introduced to switch back to the old behaviour
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed the argument of GetEmbeddedCanvas from a pointer 
+       to a reference
+
+   * macros/rootlogon.C:
+     - switched on optimization (-O3) for ACLIC
+
+
+
+ 2008/05/24 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed the obsolete fconsmics (what the hell did it do...
+       it removed the largest events?)
+     - added a cosmics trigger for calibration events instead
+
+
+
+
+ 2008/05/20 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added a MH3-histogram to be filled. It contains the
+       rate of the trigger pattern per run.
+     - the filter selecting the calibration or pedestal
+       events has been renamed from ftp to fcalped
+     - the MContinue rejecting these events has been renamed
+       from conttp to contcalped
+     - the filter selecting the pedestal events have been 
+       renamed from ftp2 to fped
+     - In the case of MUX data (no lo-gain) this filter
+       is now also rejecting lvl1 and lvl2 triggered events
+     - the ftp2-filter for the pedestal extraction tasks and
+       the corresponding histogram fillers is obsolete
+     - the previouls "PedestalFilter" is obsolete.  
+     - it doesn't make sense not to extract the signal (filter
+       of teskenv1, taskenv2 and taskenv3) but process the 
+       rest of the tasklist
+     - the pedestal extraction (as the calibration was already)
+       has been moved to its own tasklist with the corresponding
+       filter applied.
+     - tlist3 has been renamed to tlist4
+     - contped has been removed from the tasklist
+
+   * mhbase/MH3.cc:
+     - fixed a bug introduced with the lables (it must be !(x&y) 
+       instead of !x&y
+
+   * mjobs/MDataSet.cc:
+     - shortened a line of output to fit into 80 characters
+
+
+
+ 2008/05/19 Thomas Bretz
+
+   * Makefile.conf.general, Makefile.conf.linux:
+     - distinguish between := (eval once) and = (eval every access)
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MObjLookup
+
+   * mbase/MObjLookup.[h,cc]:
+     - added
+
+   * mbase/MEvtLoop.cc:
+     - set progress bar position to 0 before PreProcessing
+
+   * mdata/MDataMember.[h,cc]:
+     - added a member function to get a string
+
+   * mfilter/MFCosmics.cc:
+     - fixed a typo in a comment
+
+   * mhbase/MH.[h,cc]:
+     - improved SetBinning for newer root-versions
+     - improved SetBinning to correctly support axis with labels
+       (keeps the binning unchanged)
+
+   * mhbas/MH3.[h,cc], mhbase/MHn.[h,cc]:
+     - support for axis labels was added.
+     - a possibility to set an additional weight has been added
+     - the version number has been increased accordingly
+
+   * mjobs/MJPedestal.cc:
+     - deny level1 and level2 triggers choosing pedestal events
+
+   * mraw/MRawRunHeader.h:
+     - added a member function returning the RunLength (stop-start)
+
+   * mtrigger/MTriggerPattern.[h,cc]:
+     - wrapped some comments
+     - improved comments
+
+
+
+ 2008/05/15 Thomas Bretz
+
+   * mfilter/MFMagicCuts.[h,cc]:
+     - fixed a few typos in comments and in the output
+     - added an option kAreaLin with a linear cut in area for special
+       studies
+
+   * mbase/MStatusDisplay.cc:
+     - if no MStatusArray is found, keys which store a TCanvas object
+       are displayed instead if available
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]:
+     - the extraction range to get the maximum is now determined
+       automatically from the MExtractedSignalCam
+
+   * mpedestal/MPedestalSubtract.cc, msignal/MExtractTimeAndCharge.cc:
+     - raise an error if there is a mismatch in the number of samples
+
+
+
+
+ 2008/05/14 Thomas Bretz
+
+   * mhbase/MH3.[h,cc], mhbase/MHn.[h,cc]:
+     - enhanced to allow direct filling of Profile histograms
+
+   * mjobs/MDataSet.h:
+     - fixed a bug in Print() causing an infinite loop
+
+   * mjtrain/MJTrainDisp.cc, mjtrain/MJTrainSeparation.cc:
+     - write the dataset(s) to the output file
+
+   * mjtrain/MJTrainEnergy.cc
+     - write the dataset to the output file
+     - added new plots to show the resolution versus several different
+       parameters
+
+   * mpedestal/MPedestalSubtract.[h,cc]:
+     - added an additional check to compate the number of hi-/lo-gain
+       slices in the run- and event-header
+
+   * mpointing/MPointingDevCalc.cc:
+     - added the 14th Jan 08 to the list of new pointing models
+
+
+
+ 2008/05/07 Stefan Ruegamer
+
+   * datacenter/scripts/checkmd5sum
+     - implemented check of files from /magic and /data
+
+   * datacenter/scripts/checktransfer
+     - changed the search for temporary zipfiles to not search in hidden
+       directories
+
+   * datacenter/scripts/movingrawfiles2
+     - movingrawfiles to move raw files from /data/fromtape
+
+   * datacenter/scripts/runcallisto
+     - changed default callisto.rc to callisto_mux_new.rc
+
+   * datacenter/scripts/zipscript
+     - changed the script due to the fact that /magic/data/rawfiles is
+       now a link
+     - changed the find to not search in hidden directories
+     - added the -n option to ssh
+
+   * resources/calibration_spline.rc
+     - added calibration factors for periods 62-66 but these are not
+       newly calculated, simply pasted from previous periods!
+
+
+
+ 2008/04/08 Thomas Bretz
+
+   * mreport/MReportDrive.cc:
+     - implemented changes of Version 20080220
+
+
+
+ 2008/03/19 Thomas Bretz
+
+   * mjobs/MJSpectrum.cc:
+     - fixed a bug introduced yesterday. The overflow bin was not
+       correctly referenced
+
+
+
+ 2008/03/18 Thomas Bretz
+
+   * sponde.cc:
+     - added new option "--force-runtime"
+
+   * mbase/MEnv.h:
+     - added WriteFile to context menu
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - added a new option to force using the runtime instead of the 
+       effective observation time (this might bw wrong for very
+       short datasets)
+     - added a check if the effective observation time is out of
+       the histogram range... print a warning if so and include
+       the overflow bins into the eff. obs time
+     - added an estimated sensitivity curve for high and low za
+       to the spectrum plots
+     - added description text for 1553 and crab spectrum
+     - write out the MC events after cuts including their weights
+     - do not fit at 1TeV but 500GeV instead
+
+   * mjobs/MJob.cc:
+     - check in WriteContainer whether the file is already open
+
+   * mpointing/MPointingDevCalc.cc:
+     - added some more comments
+
+   * mhflux/MMcSpectrumWeight.[h,cc]:
+     - added the possibility to extend a spectrum by "fake" statistics
+
+
+
+ 2008/03/14 Daniel Hoehne
+
+   * datacenter/macros/filldotrun.C:
+     - inserted new arehucas version
+
+
+
+ 2008/03/04 Thomas Bretz
+
+   * condor/program.submit, condor/macro.submit, condor/script.submit:
+     - added
+
+
+
+ 2008/03/03 Thomas Bretz
+
+   * mhflux/MHAlpha.[h,cc]:
+     - allow to project individual bins in DrawNicePlot
+
+
+
+ 2008/02/24 Thomas Bretz
+
+   * mbase/MLog.h:
+     - added a getter for the OutputLevel (for debugging)
+
+   * mpointing/MPointing.h:
+     - added a memberfunction to calculate the Abs-value
+
+   * mpointing/PointingLinkDef.h:
+     - added RaDec
+
+
+
+ 2008/02/21 Daniela Dorner
+
+   * datacenter/db/builddatasets.php:
+     - display 'Remark' only in case of errors
+
+
+
+ 2008/02/08 Stefan Ruegamer
+
+   * datacenter/scripts/checkmd5sum
+     - added check to prevent that checksums of files not read from tape
+       enter the .lapalma file
+
+   * datacenter/scripts/dbchk
+     - added check for crashed runs, sequences and datasets
+     - corrected bugs in find command and $dir-loops
+     - adapted to the automatic concept and added it to the cronjobs
+
+
+
+ 2008/02/01 Stefan Ruegamer
+
+   * datacenter/macros/filldotrun.C
+     - added default entry for fCompmux for new runs
+
+   * datacenter/macros/checkfileavail.C
+     - added checking of fCompmux
+
+
+
+ 2008/02/01 Daniel Hoehne
+
+   * datacenter/db/runinfo-aio.php:
+     - fixed 'bug' with query. Now runs are displayed in ascending order
+
+
+
+ 2008/01/31 Thomas Bretz
+
+   * mbase/MThread.[h,cc]:
+     - imported from Cosy
+
+   * mbase/Makefile:
+     - added MThread
+
+   * mbase/BaseLinkDef.h:
+     - added MThread
+
+
+
+ 2008/01/27 Thomas Bretz
+
+   * .rootrc:
+     - updated with the correct path to the ViewCVS
+
+
+
+ 2008/01/24 Thomas Bretz
+
+   * mpointing/MPointing.cc:
+     - added ClassImp for RaDec
+
+   * mpointing/MPointing.h:
+     - added code for classes AltAz and RaDec deriving from TVector2
+       not to be used in Mars and Cosy
+
+
+
+ 2008/01/24 Daniel Hoehne
+
+   * scripts/preparemc:
+     - adapted to new rawfile/camera structure in /magic/montecarlo
+
+
+
+ 2008/01/14 Thomas Bretz
+
+   * mpointing/MPointing.h:
+     - added enumeration operator[]
+
+
+
+ 2008/01/11 Thomas Bretz
+
+   * mbase/MLog.cc:
+     - correctly use delete[] instead of delete for fGuiLInes as 
+       suggested by valgrind.
+
+
+
+ 2008/01/09 Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - removed obsolete fRawHeader
+
+   * mpointing/MSrcPosCam.[h,cc]:
+     - added Paint member function
+
+   * mpointing/MSrcPosRndm.[h,cc]:
+     - also produce a antio source position for wobble observations
+
+   * mraw/MRawRunHeader.cc, mjobs/MJCalibration.cc, 
+     mpedestal/MPedestalCam.cc:
+     - some cosmetics
Index: branches/Mars_McMismatchStudy/Changelog.09
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.09	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.09	(revision 17960)
@@ -0,0 +1,3092 @@
+                                                 -*-*- END OF LINE -*-*-
+
+ 2009/12/23 Thomas Bretz
+
+   * macros/dohtml.C:
+     - added missing paths
+
+
+
+ 2009/12/23 Thomas Bretz
+
+   * Release 2.4
+
+
+
+ 2009/12/23 Thomas Bretz
+
+   * mbase/MStatusArray.[h,cc]:
+     - implemented a special treatment for TGraphs in RecursiveRemove 
+       to make sure that the fHistogram pointer doesn't get deleted
+       twice.
+     - implemented a small fix to make sure an object which is more than
+       once in a list of primitives gets really removed.
+
+   * resources/calibration_spline.rc:
+     - updated calibration constants of period 62, 63, 72-75
+     - added more dummy constants
+
+
+
+ 2009/12/21 Thomas Bretz
+
+   * mjobs/MJCalibration.cc:
+     - allow unprescaled Calibration instead of requiring it (needed
+       for MCs)
+     - changed the default for "no pattern" so that events with file
+       format <5 are correctly treated. This might result in a small 
+       bias in the case newer files miss the calibration pattern, but
+       that's unavoidable
+
+   * mtrigger/MTriggerPatternDecode.cc:
+     - decode trigger pattern for files older than format version 5
+       according to the file type
+
+   * resources/calibration_spline.rc:
+     - added dummy periods up to 89
+
+   * mmc/MMcFadcHeader.hxx:
+     - changed version to 10 (got a warning for newer MCs)
+
+
+
+ 2009/12/16 Stefan Ruegamer
+
+   * datacenter/scripts/read_lapalma-tapes
+     - important output is now also written to shell
+
+
+
+ 2009/12/11
+  
+   * mfileio/FileIOLinkDef.h, mfileio/Makefile:
+     - removed MReadRflFile
+
+
+
+ 2009/12/10 Thomas Bretz
+
+   * ceres.rc:
+     - added line for new option
+
+   * mhflux/MAlphaFitter.cc:
+     - added "Sensitivity" to output
+     - prevent zero or negative divisor
+
+   * msim/MSimMMCS.h:
+     - removed pointers from i/o
+
+   * msimcamera/MSimCamera.h:
+     - fixed a typo in a comment
+
+   * msimcamera/MSimRandomPhotons.[h,cc]:
+     - changed to allow simulation of a nsb spectrum
+
+   * mjobs/MJSimulation.cc:
+     - added cone transmission
+     - plotted cone transmission
+
+   * resmc/night-sky-la-palma.txt
+     - added
+
+
+
+ 2009/12/01 Thomas Bretz
+
+   * mastro/MObservatory.cc:
+     - set fObservatoryKey when a new location is set.
+       Be careful, it is not overwritten if a location is set
+       manually (long, lat)
+
+   * mcorsika/MCorsikaEvtHeader.cc:
+     - initialize fX and fY with 0
+
+
+
+ 2009/10/26 Thomas Bretz
+
+   * Makefile:
+     - moved definition of OSTYPE to Makefile.conf.general
+     - removed mreflector 
+
+   * Makefile.conf.general:
+     - added definition of OSTYPE
+
+   * callisto.cc:
+     - added option for test mode
+
+   * ceres.rc:
+     - fixed a typo 
+     - added a line for the cone transmission
+
+   * condor/program.submit:
+     - Out shell be Output 
+     - Log is now set automatically by condor
+
+   * mastro/MAstroCatalog.cc:
+     - added a trailing / to the default path
+
+   * mbase/MAGIC.cc:
+     - added a warning when using root versions which contain a projection
+        bug which doesn't allow to reuse plotted histograms as expected
+
+   * mbase/MEnv.h:
+     - added a default to GetValue
+
+   * mbase/MLut.cc:
+     - added a validity check for the line data
+
+   * mbase/MParSpline.[h,cc]:
+     - added RecursiveRemove 
+     - added destructor
+
+   * mbase/MSpline3.[h,cc]:
+     - renamed overloaded Integral to avoid confusions in the interpreter
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - tiny cosmetics (a/=b instead of a=a/b)
+
+   * mcorsika/MCorsikaRead.h, mdata/MDataMember.h,
+     mhbase/MFillH.h, msim/MSimMMCS.h:
+     - excluded pointers from I/O, this causes some (the last) event 
+       to be stored, which could be quite large
+
+   * mfilter/MFSoftwareTrigger.cc:
+     - added some informal output to the log-stream
+
+   * mhbase/MH3.cc:
+     - added a sanity if when deleting fHist
+
+   * mhbase/MHn.[h,cc]:
+     - added RecursiveRemove
+
+   * mhist/MHCamEvent.cc:
+     - check for fSum in RecursiveRemove
+
+   * mjobs/MJCalibration.cc:
+     - write commandline to output
+
+   * mpointing/MPointingDevCalc.cc:
+     - added new pointing informations
+
+   * msimcamera/MSimAPD.cc:
+     - added the 3600 cell APD type
+
+   * msimcamera/MSimBundlePhotons.cc:
+     - improved a comment
+
+   * msimcamera/MSimExcessNoise.[h,cc]:
+     - changed size of excess noise to be variable
+
+   * msimcamera/MSimTrigger.cc:
+     - print some information if electronics is "switched off"
+
+   * msimreflector/MReflector.cc:
+     - improved a comment
+
+   * mbase/MStatusArray.[h,cc]:
+     - tried to improved stability by a completely self made deletion
+       scheme for the canvases
+
+   * mgeom/MGeomPix.h:
+     - replaced tan(60)/2 by sin(60)
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - added test mode to allow calibration of calibration files
+
+   * Makefile, */Makefile:
+     - brought includes in the correct order
+
+   * msimcamera/MSimRandomPhotons.cc:
+     - added the Cone transmission
+     - added a lot of comments
+
+
+
+ 2009/09/11 Daniela Dorner
+
+   * datacenter/db/include.php:
+     - implemented Select-all functionality for builddatasets.php
+     - improved function for 'Next/Prev/First/Last' links: regexp 
+       instead of selfmade building of link
+     - added removing of fNumStart from link in function GetClearedURL()
+     - added removing of DisplaySelected=inverse from link in function 
+       GetClearedURL()
+     - implemented 'Display Not-Selected Sequences' Button
+     - changed text on buttons
+
+   * datacenter/db/builddatasets.php:
+     - added possibility to update data set in database: update queries,
+       interface to select data set, check if user is the same
+     - bugfix: changed some $_SESSION back to $_GET (selection in the 
+       menu were treated wrongly)
+     - commented resetting of 'name' and 'comment' out
+     - implemented 'Display Not-Selected Sequences' Button
+     - changed text on buttons
+     - changed column 'Links' to the same like in sequinfo-aio.php
+     - implemented possibility to choose data set number for data set
+       file 
+
+   * datacenter/db/menu.js:
+     - implemented function for Select-all functionality
+
+
+
+ 2009/09/08 Daniela Dorner
+
+   * datacenter/db/include.php:
+     - exchanged ON/Off checkboxes with ON/Off/Not radio-buttons for 
+       builddatasets.php
+     - bugfix for display of total number of displayed results
+     - added button for displaying all not-selected sequences (also for
+       builddatasets.php)
+
+   * datacenter/db/builddatasets.php:
+     - adapted to usage of radio buttons
+     - adapted to usage of 'Display Not-Selected Sequences' button
+     - improvement of WARN and ERROR messages
+     - bugfix for observation mode display in data set summary
+     - added remark that pressing 'Get Data Set' button is neccessary
+
+
+
+ 2009/08/31 Daniela Dorner
+
+   * datacenter/scripts/setup:
+     - removed 
+
+   * datacenter/scripts/sourcefile:
+     - small fix in function makedir()
+
+   * datacenter/scripts/fillmcdb:
+     - added (script to add run in mc db (cta))
+
+   * datacenter/scripts/runsimtel:
+     - added (script to run corsika and simtelarray for cta)
+
+   * datacenter/scripts/runchimp:
+     - added (script to run coverter from simtel to mars format for cta)
+
+   * datacenter/scripts/runctastar:
+     - added (script to run star (macro) for cta)
+
+   * datacenter/scripts/runstereo:
+     - added (script to macro to calculate stereo parameters for cta)
+
+
+
+ 2009/08/21 Daniela Dorner
+
+   * datacenter/db/menu.php:
+     - added functions needed for mcinfo.php
+
+   * datacenter/db/menu.php, datacenter/db/magicdefs.php:
+     - added limit for cloudiness
+
+   * datacenter/db/sequinfo-aio.php:
+     - removed $_GET from some functions
+
+   * datacenter/db/db.php, datacenter/db/datasetinfo.php, 
+     datacenter/db/dbstatus.php, datacenter/db/findoffdata.php, 
+     datacenter/db/index.html, datacenter/db/index.php, 
+     datacenter/db/querycal.php, datacenter/db/queryseq.php, 
+     datacenter/db/querystar.php, datacenter/db/runinfo.php, 
+     datacenter/db/sequinfo.php, datacenter/db/statusrps.php, 
+     datacenter/db/statussps.php:
+     - removed 
+
+
+
+ 2009/08/20 Daniela Dorner
+
+   * datacenter/db/include.php:
+     - implemented 'First' and 'Last' links for the table, moved 
+       creation of link into function ReplaceInUri()
+     - added display of total number of results (without LIMIT) at end 
+       of table
+     - changed CheckBox2() to use SESSION variables
+     - added new buttons for builddatasets.php in PrintMagicTable() 
+       (above and below the table in case form with POST is used), 
+       function PrintDisplaySequencesButtons()
+     - added function GetClearedURL() to ensure that variables for 
+       insert, display of selected sequences and download of files, are
+       removed in the case POST and not GET is used (needed only for
+       additional buttons in builddatasets.php)
+     - removed $_GET from some functions
+
+   * datacenter/db/menu.php:
+     - removed $_GET from Init functions
+     - moved init-function of builddatasets.php here: 
+       InitBuildDataSets()
+     - adapted init of builddatasets
+     - added init of fOnlySum
+     - fixed typo in init of fProposalName
+     - changed input of Star-Done Range from 10 to 19 digits
+
+   * datacenter/db/ctamcinfo.php, datacenter/db/magicdefs.php, 
+     datacenter/db/mcdefs.php, datacenter/db/ctadefs.php:
+     - removed $_GET from some functions
+
+   * datacenter/db/builddatasets.php:
+     - changed from $_GET and $_POST to $_SESSION to avoid interaction
+       problems between GET and POST
+     - provide possibility to select sequences from several pages 
+       (Next/SortBy/...)
+     - new buttons: 'Display Selected/All Sequences', 'Get Dataset File'
+     - bugfix in download of txt-File
+     - removed $_GET from some functions
+     - added user management
+     - updated and enhanced lower part (information about data set)
+
+   * datacenter/db/builddatasets.php, datacenter/db/ctamcinfo.php, 
+     datacenter/db/datacheck.php, datacenter/db/datasetinfo.php,
+     datacenter/db/datasetinfo-aio.php, datacenter/db/dbstatus.php,
+     datacenter/db/findoffdata.php, datacenter/db/index.php,
+     datacenter/db/mcinfo.php, datacenter/db/opticaldata.php,
+     datacenter/db/printtable.php, datacenter/db/querycal.php,
+     datacenter/db/querymc.php, datacenter/db/queryrbk.php,
+     datacenter/db/queryseq.php, datacenter/db/querystar.php,
+     datacenter/db/runinfo.php, datacenter/db/runinfo-aio.php,
+     datacenter/db/sequinfo.php, datacenter/db/sequinfo-aio.php,
+     datacenter/db/sources.php, datacenter/db/statusrps.php,
+     datacenter/db/statussbs.php, datacenter/db/statussps.php:
+     - changes needed for 'Last' link and display of total number of 
+       results
+
+
+
+ 2009/08/18 Thomas Bretz
+
+   * Makefile:
+     - replaced $OSTYPE by a call to "uname -s" converted to lower
+       case for compatibility
+
+   * mjobs/MJob.cc:
+     - output the name of the resource file in SetupEnv for convinience
+
+   * mjobs/MJCut.cc:
+     - write command line to output
+
+   * mbase/MEvtLoop.cc:
+     - improved some output
+
+
+
+ 2009/08/14 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - function getstatus: return 0, if variable $numprocs is empty
+     - moved call of getdbinfo() to function getstepinfo where possible
+     - enhanced function getstepinfo: implemented retrieving variable
+       NodeRestricted from steps.rc
+       In steps.rc a line 'Table.Column.NodeRestricted: yes' has to be
+       added when a step has to be executed on a certain node (stored 
+       in the database in MCRunProcessStatus.fProductionHostKEY)
+
+   * datacenter/scripts/jobmanager:
+     - implemented possibility to send certain jobs to certain nodes
+       of the cluster (currently implemented only for sun grid engine)
+     - fix for greping the scriptname from the qstat output (needed
+       for scripts with commandline option)
+     - bugfix: pass environment variable AUTOMATIONSETUP to sun grid
+       engine
+     - pass environment variable AUTOMATIONSETUP also in the case of 
+       condor (macro $automationsetup)
+
+   * datacenter/scripts/setup.isdc.cta:
+     - added analysis scripts for jobmanager
+     - added variables concerning the cluster: number of nodes and 
+       excluded nodes (needed in the jobmanager for the changes 
+       above)
+
+   * datacenter/scripts/run.condor:
+     - added definition of environment variable using macro 
+       $automationsetup
+
+
+
+ 2009/08/14 Daniel Hoehne-Moench
+
+   * datacenter/scripts/mcsequences:
+     - included display of azimuth range in sequence file
+     - changed sequencing to one sequence per mc run
+
+
+
+ 2009/08/13 Thomas Bretz
+
+   * mbase/Margs.cc:
+     - fixed a problem returning 0 instead of "" for TString
+
+   * mbase/MLut.h, mbase/MStatusArray.h:
+     - added new overloads for Print to make it compile with newer root
+       versions without warning
+
+   * msimreflector/MReflector.cc:
+     - replaced ForEach to make it compile with newer root versions
+
+   * mtrigger/MTriggerPatternDecode.cc:
+     - removed some accidental debug output
+
+
+
+ 2009/08/13 Daniela Dorner
+
+   * datacenter/scripts/setup.isdc.cta, 
+     datacenter/scripts/setup.wue.magic.data, 
+     datacenter/scripts/setup.wue.magic.mc:
+     - added (setup files with different default settings for usage with
+       $AUTOMATIONSETUP)
+
+   * datacenter/scripts/sourcefile:
+     - moved variables for resourcefiles steps.rc and sql.rc to setup.*
+     - removed function cont()
+     - added check if setup.* is existing
+
+   * datacenter/scripts/jobmanager:
+     - removed command line options (done now via environment variable
+       $AUTOMATIONSETUP)
+     - moved arrays $scripts, $scriptscolname, $pnosweek, $pnoswe to
+       setup.*
+
+
+
+ 2009/08/12 Daniela Dorner
+
+   * datacenter/scripts/jobmanager:
+     - improved logging (new layout and more information)
+     - moved sleep to end of loop (function nextscript())
+
+
+
+ 2009/08/12 Daniel Hoehne-Moench
+   * datacenter/macros/filldotrun.C:
+     - inserted Arehucas versions 090625-0, 0907[02,06,31]-0 including
+       the new columns L3TriggerRate, L3TriggerTable, WheelPos1,
+       WheelPos2, Cycle, PI, WorkingGroup and Proposal
+     - implemented MAGIC 2 run file handling
+     - removed readout of columns by ReadToDelim(); now the columns are
+       filled into an TObjArray
+
+
+
+ 2009/08/11 Daniela Dorner
+
+   * datacenter/db/menu.php:
+     - added mc function (corsika production)
+
+   * datacenter/db/magicdefs.php:
+     - added $timelimits array
+
+   * datacenter/db/include.php:
+     - added usage of $timelimits array in function StatusQuery(), i.e.
+       provides possibility to set different values for time after 
+       which job is marked as 'crashef' for diffent steps
+
+   * datacenter/db/builddatasets.php, datacenter/db/datacheck.php, 
+     datacenter/db/datasetinfo-aio.php, datacenter/db/datasetinfo.php, 
+     datacenter/db/dbstatus.php, datacenter/db/findoffdata.php, 
+     datacenter/db/runinfo-aio.php, datacenter/db/runinfo.php, 
+     datacenter/db/sequinfo-aio.php, datacenter/db/sequinfo.php, 
+     datacenter/db/statusrps.php, datacenter/db/statussbs.php, 
+     datacenter/db/statussps.php, datacenter/db/ctamcinfo.php:
+     - added $timelimits to function StatusQuery()
+
+   * datacenter/db/ctamcinfo.php:
+     - bugfix: combining of normal and status group-by is possible now
+     - added # of events and # of kilo-events in 'group-by'
+
+   * datacenter/db/ctadefs.php:
+     - changed time limit for corsika from 30 to 48 hours
+     - added # of events and # of kilo-events for 'group-by'
+
+   * datacenter/db/mcinfo.php:
+     - added (interface to monitor mc production (up to now only test
+       version for corsika))
+
+   * datacenter/db/mcdefs.php:
+     - added (definition of variables for mc production)
+
+
+
+ 2009/08/03 Daniel Hoehne-Moench, Stefan Ruegamer
+
+   * datacenter/db/menu.php, magicdefs.php:
+     - added new columns L3TriggerTable, WheelPos1, WheelPos2 as well as
+       the KEY tables Cycle, PI, WorkingGroup and Proposal
+
+
+
+ 2009/08/03 Daniela Dorner
+
+   * datacenter/db/menu.php:
+     - bugfix: query for NightRange field only date from database
+
+
+
+ 2009/07/29 Thomas Bretz
+
+   * callisto.cc, ceres.cc, ganymed.cc, sponde.cc, star.cc:
+     - pipe command line to job
+
+   * mbase/MArgs.[h,cc]:
+     - added getter for command line
+
+   * mjobs/MJCalibration.cc, mjobs/MJSpectrum.cc,
+     mjobs/MJStar.cc, mjobs/MJCalibrateSignal.cc:
+     - write command line to output
+
+   * mjobs/MJob.[h,cc]:
+     - added data member to store the command line
+
+   * mtrigger/MTriggerPattern.h:
+     - added efault argumtn to Print()
+
+   * mjobs/MJStar.cc:
+     - added a sanity check for empty sequences
+     - write MCorsikaEvtHeader and MCorsikaRunHeader to output
+
+   * mjobs/MJSimulation.cc:
+     - use a MParameterCalc to calculate and later store the
+       incident angle
+
+
+
+ 2009/07/28 Thomas Bretz
+
+   * mjobs/MJCalibration.cc:
+     - we have to allow all kind of triggers together with a 
+       calibration trigger, otherwise we never have enough 
+       calibration events if the trigger signals haven't been
+       switched off (prescaled)
+
+   * mtrigger/MTriggerPatternDecode.cc:
+     - when we move L1TPU to L1 as a workaround we now really "move"
+       the bit instead of just copy it (this is better for filters
+       like "deny all")
+
+
+
+ 2009/07/04 Daniela Dorner
+
+   * datacenter/db/ctamcinfo.php, datacenter/db/ctadefs.php, 
+     datacenter/db/menu.php, datacenter/scripts/jobmanager:
+     - changed fCorsikaSimtelArray to fCorsikaSimTelarray
+
+
+
+ 2009/07/02 Thomas Bretz
+
+   * manalysis/MGeomApply.cc:
+     - cosmetics to a comment
+
+   * melectronics/ElectronicsLinkDef.h, melectronics/Makefile:
+     - removed MPulseShape
+
+   * mhbase/MHMatrix.cc:
+     - improved memeory managment when matrix size is growing
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added MCorsikaRunHeader and MCorsikaEvtHeader to output
+       for completeness
+
+   * mjobs/MJCalibration.cc:
+     - improved the filter for the trigger pattern
+
+
+
+ 2009/07/01 Thomas Bretz
+
+   * mreport/MReportDrive.cc:
+     - fixed typo in version number
+
+   * mjobs/MJob.cc:
+     - improved check for write permissions
+
+   * mfileio/MWriteRootFile.cc:
+     - option should not only contain "memory" it should be identical
+       to "memory"
+
+
+
+ 2009/06/28 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C
+     - fixed typo in Arehucas Version: 090661-0 -> 090616-0
+
+
+
+ 2009/06/26 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C
+     - inserted Arehucas version 090616-0
+
+   * datacenter/macros/fillcamera.C:
+     - changed number of digits for thetamin, thetamax, pmin, pmax
+     - fPhiMin (pmin) and fPhiMax (pmax) are now filled into 
+       MyMagicMonteCarlo
+
+
+
+ 2009/06/22 Daniela Dorner
+
+   * datacenter/db/showplots.php, datacenter/db/showplots-ds.php, 
+     datacenter/db/showplots-seq.php:
+     - additional information on the sequence is displayed on mouse-over
+       on the path of the file
+
+   * datacenter/db/plotinclude.php:
+     - implemented function for mouse-over in showplots*.php
+
+   * datacenter/db/showplots.php:
+     - adapted layout of menu to new feature
+
+
+
+ 2009/06/20 Thomas Bretz
+
+   * mbase/MLut.[h,cc]:
+     - renamed Default to DefaultCol
+     - added DefaultRow
+     - added Print
+     - added some const qualifiers
+
+   * mbase/MParList.cc:
+     - make sure a parlist is not added to itself
+     - improved some debug output
+
+   * melectronics/MAvalanchePhotoDiode.[h,cc]:
+     - keep a time-stamp fTime
+     - added functions to "relax/evolve" the apd over a given time
+
+   * mgeom/MGeomCamDwarf.cc:
+     - fixed a broken comment
+
+   * mjobs/MJPedestal.cc:
+     - improved output in case of error
+
+   * mjobs/MJSimulation.cc:
+     - implemented a PreCut (to gain processing time)
+     - implemented the correct type id in the file name
+
+   * mpedestal/MPedCalcPedRun.cc:
+     - check for the run-number only if real data
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added GetRuntypeChar
+     - fixed a bug which returned the runtype instead of the
+       telescopenumber
+
+   * mreport/MReport.cc:
+     - added a new report version number 200905170 (preliminray!)
+
+   * mreport/MReportDrive.cc:
+     - added a fix for the starguider sttaus in the report
+
+   * msimcamera/MSimAPD.cc:
+     - instead of a full initialization of the APD before each event
+       we now only simulate a time evolution which is needed to relax
+       a cell to one permille error. This is much faster.
+
+   * msimcamera/MSimTrigger.[h,cc]:
+     - allow switching off of the electronics trigger
+     - replaced the real coincidence by better and faster algorithm
+     - the new algorithm also supports multiplicity triggers
+     - therefore added fMinMultiplicity
+     - updated the handling and ouput in case of empty coincidence maps
+
+   * mtrigger/MTriggerPattern.h:
+     - added some information in the bit description
+
+   * mtrigger/MTriggerPatternDecode.cc:
+     - fixed the decoding for runs for which L1TPU was connected
+       instead of L1
+
+   * megom/MGeomCamFact.[h,cc]:
+     - added
+
+   * megom/Makefile, mgeom/GeomLinkDef.h:
+     - added MGeomCamFact
+
+
+
+ 2009/06/18 Daniela Dorner
+
+   * mjobs/MDataSet.h:
+     - fixed typo in comment
+
+
+
+ 2009/06/16 Daniela Dorner
+
+   * datacenter/db/plotinclude.php, datacenter/db/plotdb.php:
+     - implemented feature to query/plot only data of one source (with
+       regular expressions)
+
+
+
+ 2009/06/12 Daniela Dorner
+
+   * datacenter/db/include.php:
+     - adapted path of plus.png and minus.png
+
+   * datacenter/db/index-footer.html:
+     - adapted footer
+
+   * datacenter/db/menu.php:
+     - added functions for CTA MC
+
+   * datacenter/db/ctadefs.php:
+     - added (analog file to magicdefs.php for CTA)
+
+   * datacenter/db/ctamcinfo.php:
+     - added (website to display info about produced CTA MC)
+
+   * macros/starvisyear.C:
+     - added includes for compiling
+
+   * datacenter/scripts/sourcefile:
+     - replaced case- by if-statement in checklock()
+     - added more information to the output to the lockfile
+     - added processlog in makedir()
+     - improved processlog output and layout of queries
+     - added option to query only jobs for one node
+
+   * datacenter/scripts/jobmanager:
+     - added option for production of cta mc
+
+   * datacenter/scripts/jobmanager, datacenter/scripts/setup:
+     - added $totalmax which can overwrite $pnototal[$hour]
+
+
+
+ 2009/06/09 Daniela Dorner
+
+   * mbase/MSpline3.cc:
+     - added include of TMath
+
+
+
+ 2009/06/05 Stefan Ruegamer, Daniel Hoehne-Moench
+
+   * Mars-2.3/datacenter/macros/filldotrun.C
+     - inserted Arehucas versions 090522-0 and 090525-0
+
+
+
+ 2009/05/15 Thomas Bretz
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - fixed names for Hadronness Cut
+
+
+
+ 2009/05/15 Thomas Bretz
+
+   * ganymed.rc, ganymed_wobble.rc, ganymed_onoff.rc:
+     - fixed names for Hadronness Cut
+
+
+
+ 2009/05/10 Thomas Bretz
+
+   * ceres.cc:
+     - added usage of sequence files
+     - added new options for pedestal and calibration mode
+
+   * mbase/MDirIter.[h,cc]:
+     - added AddFile member function
+
+   * mbase/MArgs.[h,cc]:
+     - added member function to remove an argument from the list
+
+   * mgeom/MGeomPix.h:
+     - added Getter for Width in x and y
+
+   * mjobs/MJSimulation.[h,cc]:
+     - added fOperationMode
+     - added use of sequence
+     - name ceres file according to sequence number
+     - changes to the binnings 
+
+   * mjobs/MSequence.[h,cc]:
+     - unified the usual and the default constructor
+     - don't output default values in Print
+     - added kCorsika files
+
+
+
+ 2009/04/29 Thomas Bretz
+
+   * msimcamera/Makefile:
+     - added -I../msimreflector
+
+
+
+ 2009/04/28 Thomas Bretz
+
+   * mjobs/MJStar.cc:
+     - allow to run thru even if discriminator threshold are missing
+
+
+
+ 2009/04/26 Thomas Bretz
+
+   * mraw/MRawFileRead.cc:
+     - added consistency check for two consecutive headers
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added copy constructor
+     - added member function for conistency check
+
+
+
+ 2009/04/16 Thomas Bretz
+
+   * mbase/MEvtLoop.cc:
+     - make sure that no negative values for the estimated time
+       is shown
+
+   * mcorsika/MCorsikaEvtHeader.cc:
+     - calculate impact in the telescope dish plane and not on the
+       ground
+
+   * mhflux/MHCollectionArea.cc:
+     - initialize more variables in the constructor as suggested
+       by valgrind
+
+   * mpointing/MHPointing.cc:
+     - set the maximum such that both axis are scaled correctly
+
+   * msimcamera/MSimBundlePhotons.cc:
+     - added some more output
+
+   * resmc/dwarf-pde-gapd.txt:
+     - used new curve from ETH
+     - extrapolated curve on both ends linearily
+
+   * resmc/dwarf-reflectivity.txt:
+     - extrapolated linearily to 980 nm
+
+   * resmc/magic-pde.txt:
+     - set to 0 at 900nm
+
+   * resmc/magic-reflectivity.txt:
+     - extrpolated to 900nm
+
+   * msimcamera/MSimReadout.cc:
+     - small improvement to sanity check to allow having less channels
+       than pixels
+
+   * mreport/MReport.cc:
+     - added once more a fix for a wrong Arehucas version
+
+   * mbase/MSpline3.[h,cc]:
+     - added functions to return the analytical integral
+       of the spline
+
+   * mjobs/MJSimulation.[h,cc]:
+     - replaced the 2D histogram with the impact on ground with
+       a 1D histogram with the impact perpendicular to Alt/Az
+     - Use a MParSline instead of MPulseShape
+     - Use MParSplines as input for MSimAbsorption
+     - increased the number of bins for the threshold histogram
+     - adapted BinningImpact
+     - added another histogram for the event distribution after cleaning
+     - changed the default number of the NSB to fit the new input
+       definition
+     - added histogram for MNewImagePar
+     - added tab "Info2"
+     - added all MHPhotonEvent to the paremeter list to allow access 
+       of the ReadEnv
+
+   * msim/MSimAbsorption.[h,cc]:
+     - moved the spline code to MParSpline
+     - use MParSpline as new input
+
+   * msimcamera/MSimCalibrationSignal.[h,cc], msimcamera/MSimCamera.[h,cc],
+     msimcamera/MSimGeomCam.[h,cc]:
+     - replaces MPulseShape by MParSpline
+
+   * msimcamera/MSimRandomPhotons.[h,cc]:
+     - scale NSB rates like it is done in Eckart's paper
+     - write rates to an output container
+
+   * ceres.rc:
+     - adapted
+
+   * msimcamera/MSimAPD.[h,cc]:
+     - take the acidental rate from a container
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MParSpline
+
+   * mbase/MParSpline.[h,cc]:
+     - added
+
+   * msim/MSimAtmosphere.cc:
+     - fixed a bug which caused the aerosol coefficient to be
+       incorrectly initialized
+
+
+
+ 2009/04/01 Thomas Bretz
+
+   * Makefile.conf.linux:
+     - removed accidental '-g'
+
+   * Makefile.conf.linux:
+     - removed -Wconversion (produces too much output on newer
+       compilers)
+
+   * ceres.rc, mjobs/MJSimulation.cc:
+     - added a cut "Cut" after image parameter calculation
+     - updated noise numbers
+
+   * resmc/dwarf-pde-gapd.txt:
+     - upadted with a more reliable curve from theeth meeting page
+       (linear extrapolate below 350nm)
+
+
+
+ 2009/03/30 Thomas Bretz
+
+   * manalysis/MMcCalibrationUpdate.cc:
+     - fixed a conditional which prevented the display from
+       correctly process raw data
+
+   * mgeom/MGeomCamSquare.cc:
+     - shifted pixels to be centered around 0
+
+   * msimcamera/MSimCamera.cc:
+     - added an additional sanity check
+
+   * mhbase/MH.cc:
+     - added "temp" to palette
+
+
+
+ 2009/03/27 Stefan Ruegamer
+
+   * datacenter/scripts/checkstardone
+     - added missing ;; for the case-switching
+
+
+
+ 2009/03/24 Stefan Ruegamer
+
+   * mhflux/MHAlpha.cc
+     - changed in DrawAll the line color of on-off to blue
+
+
+
+ 2009/03/23 Thomas Bretz
+
+   * resources/starguider01000534.txt:
+     - added
+
+   * mbase/MStatusDisplay.cc:
+     - if no MStatusArray is found now all object are drawn
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - trees to be copied can now be made optional
+
+   * mhbase/MH.cc:
+     - included TProfile2D for newer root versions
+
+   * mjobs/MJCalibrateSignal.cc:
+     - made the copy of "OriginalMC" optional. Now it also works
+       for non-ceres (original MMCS) files again which don't 
+       have this tree.
+
+
+
+ 2009/03/19 Daniel Hoehne-Moench
+
+   * datacenter/scropts/mcsequences:
+     - bugfix: replaced $user by $us
+     - bugfix: fPriority is now inserted into the correct table
+
+
+
+ 2009/03/16 Thomas Bretz
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - added new starguider calibration since 1000534
+
+   * datacenter/macros/plotdb.C, datacenter/macros/plotrundb.C:
+     - added option to set ds-number in datset
+
+   * mgeom/MGeomCamMagic.cc:
+     - fixed layout of the MII camera
+
+   * mpointing/MPointingDevCalc.cc:
+     - updated informations
+
+
+
+ 2009/03/16 Daniel Hoehne-Moench
+
+   * datacenter/scripts/fillcamera
+     - bugfix: the first line was moved by a tabulator
+
+
+
+ 2009/03/16 Stefan Ruegamer
+
+   * datacenter/scripts/makecallistolinks
+     - added >/dev/null in line 68 to prevent the mails to dc@astro
+     - removed the -v for the ln
+
+   * datacenter/scripts/sourcefile
+     - added printprocesslog for rm -v in the finish function (mails)
+
+
+
+ 2009/03/15 Thomas Bretz
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added member function to get the total sensitive area of the
+       camera
+
+   * mgeom/MGeomCamMagic.cc:
+     - included TMath for newer root versions
+
+
+
+ 2009/03/07 Thomas Bretz
+
+   * RELEASE V2.3
+
+
+
+ 2009/03/06 Thomas Bretz
+
+   * datacenter/macros/plotrundb.C datacenter/macros/fillstar.C:
+     - added RunDataCheck access
+
+   * mreflector/MRflEventData.cc:
+     - replaced DistanceToPrimitive by IsInside
+
+
+
+ 2009/03/05 Thomas Bretz
+
+   * mreport/MReportCamera.cc:
+     - fixed a problem if the HVFIL section is empty
+
+   * merpp.cc:
+     - added --dev-null option to Usage output
+
+   * mjobs/MJMerpp.[h,cc]:
+     - fixed operation in --dev-null mode
+
+
+
+ 2009/03/04 Thomas Bretz
+
+   * datacenter/macros/plotdb.C:
+     - updated some binnings
+
+   * datacenter/macros/fillganymed.C:
+     - use the primary also when inserting
+
+   * mgeom/GeomLinkDef.h:
+     - added MGeomCamMagicII
+
+   * mgeom/MGeom.[h,cc]:
+     - added option to set position
+     - removed DistanceToPrimitive, use IsInside instead
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added a virtual function to CreateNN
+     - added a workaround after reading by calling CreateNN
+       because with the last changes the pixel indices get lost
+
+   * mgeom/MGeomCamCT1.[h,cc]:
+     - now derives from MGeomCamDwarf
+     - accordingly increased version number
+
+   * mgeom/MGeomCamDwarf.[h,cc]:
+     - removed Clone -> now in MGeomCam
+
+   * mgeom/MGeomCamMagic.[h,cc]:
+     - added MGeomCamMagicII <preliminary>
+
+   * mgeom/MGeomCamSquare.[h,cc]:
+     - removed creation of next neighbors -> now automatic
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added rotation angle in terms of cos(phi) and sin(phi)
+     - rotate in PaintPrimitive
+     - adapted IsInside accordingly
+
+   * mgeom/MGeomRectangle.[h,cc]:
+     - if only width is given assume a square
+     - make sure that the box is correctly painted for all root versions
+     - fixed distance to farthest point
+
+   * mgui/MHexagon.[h,cc]:
+     - removed obsolete dependence on MGeomPix
+
+   * mhist/MHCamera.cc, mtools/MagicJam.cc:
+     - replaced DistanceToPrimitive by IsInside
+
+   * mjobs/MJSimulation.cc:
+     - replaced accidental _I_ in file names by _Y_
+
+   * mreport/MReportCC.[h,cc]:
+     - added version >=200809030
+     - improved modularity of code
+
+
+
+ 2009/03/03 Thomas Bretz
+
+   * ceres.rc:
+     - added some more infomation
+     - updated paths
+
+   * mcorsika/MCorsikaRunHeader.[h,cc]:
+     - added atmospheric layers
+     - added interpretation of new XSCATT/YSCATT in newer corsikas
+
+   * msim/MSimAtmosphere.[h,cc]:
+     - changed path
+     - MAtmosphere doesn't search for any files per default anymore
+     - changed atmopsheric layers to the ones fitted by Corsika
+     - added possibility to change input files to ReadEnv
+
+   * msimcamera/MSimCalibrationSignal.cc:
+     - don't create a camera geometry yourself
+     
+   * resmc/atmosphere-aerosols.txt, resmc/atmosphere-ozone.txt,
+     resmc/ct1-pde.txt, resmc/dwarf-apdmap.txt, resmc/dwarf-cones.txt,
+     resmc/dwarf-pde-gapd.txt, resmc/dwarf-reflectivity.txt,
+     resmc/dwarf-reflector.txt, resmc/magic-cones-inner.txt,
+     resmc/magic-pde.txt, resmc/magic-reflectivity.txt,
+     resmc/magic-reflector-chessboard.txt, resmc/magic-reflector.txt,
+     resmc/magic-trigger-1NN.txt, resmc/magic-trigger-2NN.txt,
+     resmc/magic-trigger-3NN.txt, resmc/magic-trigger-4NN.txt:
+     - added
+
+   * mhist/Makefile:
+     - removed accidental MHQuality
+
+   * mhist/MHCamera.cc:
+     - fixed a warning when calling DistancetoPrimitive
+
+   * mgeom/MGeomCamSquare.cc:
+     - accidentaly used Double_t instead of Short_t when calling
+       SetNeighbors
+     - changed number of pixels from UInt_t to Short_t. It doesn't make
+       sense to support more pixels than we can store as index for
+       neighbors
+
+   * Makefile:
+     - added mreflector to resolve unresolved symbols
+
+
+
+ 2009/03/02 Daniela Dorner
+
+   * datacenter/db/plotdb.php:
+     - adapted width of table
+
+
+
+ 2009/03/02 Thomas Bretz
+
+   * mgeom/MGeomCam.[h,cc], msimreflector/MMirror.h,
+     msimreflector/MMirrorDisk.[h,cc], msimreflector/MMirrorHex.[h,cc],
+     msimreflector/MMirrorSquare.[h,cc], msimreflector/MReflector.[h,cc]:
+     - added GetA member function
+
+   * manalysis/MCameraData.cc, mbadpixels/MBadPixelsCalc.cc,
+     mbadpixels/MBadPixelsCam.cc, mbadpixels/MBadPixelsTreat.cc,
+     mcalib/MCalibrationCam.cc, mcalib/MCalibrationChargeCalc.cc,
+     mcalib/MCalibrationChargeCam.cc, mcalib/MCalibrationPulseTimeCam.cc,
+     mcalib/MCalibrationRelTimeCalc.cc, mcalib/MCalibrationRelTimeCam.cc,
+     mcalib/MCalibrationTestCalc.cc, mcalib/MCalibrationTestCam.cc,
+     mcorsika/MCorsikaEvtHeader.cc, mfilter/MFSoftwareTrigger.cc,
+     mgeom/MGeomCam.cc, mhcalib/MHCalibrationCam.cc,
+     mhcalib/MHCalibrationChargeCam.cc,  msignal/MSignalCam.cc,
+     mhcalib/MHCalibrationPulseTimeCam.cc, mpointing/MPointingPos.h, 
+     mhcalib/MHCalibrationRelTimeCam.cc, mhft/MHexagonalFTCalc.cc,
+     mhist/MHCamera.cc, mimage/MHillas.cc, mimage/MNewImagePar.cc,
+     mjobs/MJCut.cc, mjobs/MJSimulation.cc, mpedestal/MPedPhotCam.cc, 
+     mpedestal/MExtractPedestal.cc, mpedestal/MPedestalCam.cc, 
+     msimcamera/MSimGeomCam.cc, msimcamera/MSimRandomPhotons.cc:
+     - replaced MGeomPix by MGeom
+
+   * mjobs/MJStar.cc:
+     - added BinningDist
+     - converted Muon cuts from mm to deg
+
+   * mhflux/MHCollectionArea.cc:
+     - fixed a problem that a plot disappeared in old files
+
+   * mmuon/MMuonSearchPar.cc:
+     - switched off the check in Paint (this works only for MAGIC :( )
+
+   * datacenter/macros/fillganymed.C:
+     - simplified by using MSQLMagic instead of MSQLServer
+
+
+
+ 2009/03/01 Thomas Bretz
+
+   * ganymed.rc, ganymed_onoff.rc, ganymed_wobble.rc:
+     - added pointing model 328198
+
+   * mbase/MSpline3.h:
+     - added a cast to make it compile with root 5.18
+
+   * melectronics/MPulseShape.cc:
+     - included TH1 to make it compile with root 5.18
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - convert MString::Format to Data() 
+     - added type SignificanceSqrtExcess
+
+   * mhflux/MHFalseSource.cc, mjobs/MJSpectrum.cc:
+     - convert MString::Format to Data() 
+
+   * mhist/MHCamera.cc:
+     - changed some const TString to const char to resolve 
+       ambiguity in root 5.18 in TF1 constructor
+
+   * msim/MHPhotonEvent.cc:
+     - use TMath::Abs instead of abs 
+
+   * msim/MSimPointingPos.[h,cc]:
+     - moved getter and setter to source file to avoid including of
+       TMath
+
+   * mgeom/MGeom.[h,cc]:
+     - added
+
+   * mgeom/MGeomRectangle.[h,cc]:
+     - added
+
+   * mgeom/MGeomCamSquare.[h,cc]:
+     - added
+
+   * mgeom/Makefile, mgeom/GeomLinkDef.h:
+     - added MGeom
+     - added MGeomRectangle
+     - added MGeomCamSquare
+
+   * Makefile.rules:
+     - removed dependance on ROOTSYS from rmkdepend. It should be in 
+       the path anyway as rootcint
+
+   * ceres.rc:
+     - added an example of setting the APD type
+
+   * mbadpixels/MBadPixelsCam.[h,cc], mbadpixels/MBadPixelsTreat.cc,
+     mcalib/MCalibrationChargeCalc.cc, mcalib/MCalibrationTestCalc.cc,
+     mfilter/MFSoftwareTrigger.cc:
+     - replaced references to MGeomPix by references to MGeom
+
+   * mbase/MStatusDisplay.cc:
+     - evaluate the return code of fwrite as suggested by newer 
+       gcc versions
+     - set a paranthesis as suggested by a warning 
+
+   * mgeom/MGeomCam.[h,cc]:
+     - adapted to the changes in MGeomPix/MGeom
+     - added SetAt function for external setup
+     - added Copy constructor
+
+   * mgeom/MGeomCamCT1.cc, mgeom/MGeomCamDwarf.cc, 
+     mgeom/MGeomCamMagic.cc, mhft/MHexagonFreqSpace.cc,
+     mimage/MHillas.cc, mimage/MHillasExt.cc,
+     mimage/MImgCleanStd.[h,cc], mimage/MNewImagePar.cc,
+     mimage/MNewImagePar2.cc, mmuon/MHSingleMuon.cc,
+     msignal/MSignalCam.cc, mtools/MagicJam.cc,
+     
+     - adapted to the changes in MGeomPix/MGeom
+     - use SetAt for setup
+
+   * mgeom/MGeomPix.cc:
+     - moved most of the code to new base class MGeom
+     - now derives from MGeom
+     - increased version number accordingly
+
+   * mhbase/MBinning.cc:
+     - replaced a Int_t by UInt_t as suggested by a warning
+
+   * mhbase/MH.cc:
+     - added a const_cast for GetObjectInfo (should be const,
+       but isn't)
+
+   * mhbase/MHMatrix.cc, mhflux/MHAlpha.cc, mhflux/MHThetaSq.cc,
+     mhflux/MHThetaSqN.cc, mhist/MHCamEventRot.cc, hvstime/MHVsTime.cc,
+     mjobs/MJStar.cc, mraw/MRawEvtHeader.cc:
+     - added paranthesis as suggested by a warning
+
+   * mhft/MGeomCamMagicXT.[h,cc]:
+     - replaced by deriving from MGeomCamDwarf
+
+   * mhist/MHCamera.cc:
+     - adapted to the changes in MGeomPix/MGeom
+     - use SetAt for setup
+     - use new PaintPrimitive to skip the usage of MHexagon
+
+   * mmc/MMcTrigHeader.hxx:
+     - fixed wrong condition in SetTrigger
+
+   * msimcamera/MSimAPD.[h,cc]:
+     - added a possibility to switch between the 50mu and 100mu
+       Diodes
+
+   * mtools/MagicCivilization.[h,cc], mtools/MagicDomino.[h,cc],
+     mtools/MagicReversi.[h,cc], mtools/MagicShow.[h,cc],
+     mtools/MagicSnake.[h,cc], mtools/MineSweeper.[h,cc],
+     - adapted to the changes in MGeomPix/MGeom, therefore restructered
+       the code to get rid of MHexagon
+
+   *  mmovie/MMovieWrite.cc:
+     - allow to switch off timing via preprocessor directive
+     - replaced MGeomPix by MGeom
+     - slightly changed palette
+     - evaluate return of fwrite
+
+   * mbase/MQuaternion.h, msim/MPhotonData.h:
+     - added a workaround for sqrt in root 5.18/00
+
+
+
+ 2009/02/26 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C:
+     - implemented new SuperArehucas version
+
+
+
+ 2009/02/23 Thomas Bretz
+
+   * mcorsika/MCorsikaRunHeader.cc:
+     - switched off the impact max workaround - it doesn't work
+     - initialize fImpact Max
+     - print also number of used ATMEXT
+
+   * mhbase/MH.cc:
+     - improved setting of binning from the parameter list in the
+       n-D case
+
+   * mhbase/MH3.cc:
+     - imporved output
+
+   * mhflux/MHCollectionArea.cc:
+     - also collect the maximum impact while running for a nicer
+       behaviour of the plots
+
+   * mhflux/MHThreshold.cc:
+     - allow setting of a dedicated Threshold binning
+
+   * mimage/MHHillasExt.cc:
+     - converted slope binning to deg
+
+   * mjobs/MJSimulation.cc:
+     - write MMcCorsikaRunHeader
+     - changed binnings
+     - added new binning
+     - now display the signal unscaled
+     - show threshold and collection area only for data runs
+
+   * msim/MSimMMCS.cc:
+     - make setting of directions depending on view-cone option
+
+   * msim/MSimPointingPos.[h,cc]:
+     - added class description
+     - removed obsolete fPointingCorsika
+     - improved output
+     - added option for homogenous distribution
+
+   * mmuon/MMuonCalibParCalc.cc:
+     - converted cuts from mm to deg so they will work also for other
+       geometries
+
+
+
+ 2009/02/20 Thomas Bretz
+
+   * mmuon/MHMuonPar.[h,cc]:
+     - updated class version number after fMm2Deg got removed
+
+   * mpointing/MHSrcPosCam.cc:
+     - fixed the fill style of the ellipse to produce correct ps-files
+
+
+
+ 2009/02/19 Daniela Dorner
+
+   * datacenter/scripts/buildsequenceentries, 
+     datacenter/scripts/checkfilesforsequenceavail, 
+     datacenter/scripts/checkstardone, datacenter/scripts/correcttime,
+     datacenter/scripts/dbchk, datacenter/scripts/dodatacheck,
+     datacenter/scripts/doexclusions, datacenter/scripts/fillcallisto, 
+     datacenter/scripts/fillcamera, datacenter/scripts/fillganymed, 
+     datacenter/scripts/fillstar, datacenter/scripts/insertdatasets, 
+     datacenter/scripts/makecallistolinks, 
+     datacenter/scripts/mcsequences, datacenter/scripts/movingrawfiles, 
+     datacenter/scripts/movingrawfiles_OK, datacenter/scripts/runcamera,
+     datacenter/scripts/runcorsika, datacenter/scripts/runreflector,
+     datacenter/scripts/sourcefile, 
+     datacenter/scripts/writedatasetfiles, 
+     datacenter/scripts/writesequencefiles:
+     - removed scriptlog
+
+   * datacenter/scripts/jobmanager: 
+     - fixed typo
+
+
+
+ 2009/02/19 Thomas Bretz
+
+   * mcorsika/MCorsikaRunHeader.[h,cc]:
+     - reformatted output
+     - added "Options" to output
+     - made Has const
+     - added a workaround to get the maximum simulated impact
+       although it is not officially stored in the file
+
+   * msim/MHPhotonEvent.cc:
+     - improved automatic binning
+
+   * msim/MPhotonData.[h,cc]:
+     - added GetCosW2
+     - added GetSinW2
+     - added GetSinW
+
+   * msim/MSimAbsorption.cc:
+     - don't check wavelength range when theta should be used
+
+   * msimcamera/MSimAPD.cc:
+     - check for uninitialized indices
+
+   * msim/MPhotonEvent.[h,cc]:
+     - moved the code for MyClonesArray to the source file
+     - improved a lot the reading speed by reading larger blocks
+       of data from the file at once
+     - improved memory handling. This ensures that even the largest
+       events don't fill the memory forever and the allocated memory
+       is free'd again after some time
+
+   * msimreflector/MSimReflector.cc:
+     - Use the new Resize function of MPhotonEvent to make sure
+       that the memory is not allocated forever.
+
+   * mimage/MHHillas.cc, mimage/MMHillas.Ext.cc, mimage/MHHillasSrc.cc:
+     - converted default binning from mm to deg
+
+   * mraw/MRawRunHeader.cc:
+     - print less when values doen't have any meaning
+
+   * msim/MSimAtmosphere.[h,cc]:
+     - added
+
+   * msim/SimLinkDef.h, msim/Makefile:
+     - added MSimAtmosphere
+
+   * mjobs/MJSimulation.cc:
+     - added simulation of atmosphere
+     - clean isolated pixels away before calculating image parameters
+     - don't clean calibration runs
+     - correct displayed az by magnetic field
+     - added auto range for the 2D histograms
+     - set automatic binning for dist
+     - added tab with histogram for trigger area and threshold
+
+   * readcorsika.cc:
+     - implemented -ff option
+
+   * mcorsika/MCorsikaRunHeader.cc:
+     - improved Print output
+
+   * mimage/MImgCleanStd.cc:
+     - fixed the checks for the cleaning parameters there 
+       where some wrong conditions
+
+   * msim/MSimMMCS.cc:
+     - fixed typo in a comment
+
+   * ceres.rc:
+     - added units for psf
+     - some small updates
+
+   * msimreflector/MSimReflector.cc:
+     - convert units of psf from mm to cm
+     - Use MPointingPos instead of PointingCorsika, ARRANG already
+       rotates all vectors accrodingly
+
+   * msim/MSimPointingPos.cc:
+     - don't write PoinitingCorsika anymore. ARRANg already includes
+       the rotation
+
+   * mgeom/MGeomCamMagic.[h,cc]:
+     - added a constructor which allows to set the focal distance
+
+   * msimcamera/MSimAPD.cc, msimcamera/MSimGeomCam.cc,
+     msimcamera/MSimRandomPhotons.cc, msimreflector/MSimReflector.cc:
+     - don't create an object if MGeomCam not found, try "MGeomCam"
+       as default instead
+
+   * mhflux/MHCollectionArea.[h,cc]:
+     - added MMcRunHeader to data members to be able to check
+       the maximum impact in Finalize for the case the maximum
+       impect is collected "on-line" from the events
+     - if the event distribution comes just from the spectrum fill
+       the distribution event by event to get correct errors
+     - romved some old obsolete code
+
+   * msim/MSimMMCS.[h,cc]:
+     - added MMcRunHeader to data members to allow to collect the
+       maximum impact from the events
+
+
+
+ 2009/02/18 Thomas Bretz
+
+   * datacenter/scripts/runcorsika:
+     - added a comment
+
+   * mbase/MParList.cc:
+     - when adding a TCollectionn only add MParContainers
+
+   * mcorsika/MCorsikaRunHeader.[h,cc]:
+     - added reading of Atmospheric coefficients
+     - added reading of Cherenkov Flag
+     - added corsika's Earth Radius
+
+   * melectronics/MDigitalSignal.[h,cc]:
+     - added and initialized an index to allow to "connect"
+       the digital signal to a channel
+
+   * mjtrain/MJTrainSeparation.cc:
+     - replaced kGreen by kBlue
+
+   * mmain/MEventDisplay.cc:
+     - added a type==3 which is for ceres-reflector files
+
+   * mmain/Makefile:
+     - added -I../mcorsika
+     - added -I../msim
+     - added -I../msimcamera
+
+   * msim/MHPhotonEvent.[h,cc]:
+     - set the binning more automatically from the run-headers
+       where possible
+     - added RadEnv
+     - added Clear function for external access
+
+   * msim/MSimAbsorption.cc:
+     - addec const-qualifier for photon
+
+   * msimcamera/MSimGeomCam.cc:
+     - allow usage also without pulse and pulse position (for display)
+
+   * msimcamera/MSimSignalCam.cc:
+     - allow usage also without TriggerPos
+     - added a check whether MSignalCam was correctly initialized
+
+
+
+ 2009/02/16 Thomas Bretz
+
+   * mimage/MHHillas.cc, mimage/MHHillasExt.cc, mimage/MHHillasSrc.cc,
+     mimage/MHImagePar.cc:
+     - replaced green by blue for better readability on projectors
+
+   * mbase/MEnv.[h,cc]:
+     - added the option of a default name to allow i/o more similar
+       to MParContainer
+     - improved Print()
+
+   * ceres.cc, callisto.cc, star.cc, ganymed.cc, sponde.cc:
+     - make use of the new default name of MEnv
+
+   * mjobs/MJSpectrum.cc:
+     - read and write ganymed.rc
+
+   * mbase/MParList.cc:
+     - if adding a TObjArray add only MParContainers (for sanity)
+
+   * mjobs/MJob.cc:
+     - when reading read also TObjects
+
+   * mjobs/MJSpectrum.cc:
+     - now read the ganymed.rc and write it to the output
+
+   * mhflux/MHEffectiveOnTime.h:
+     - increased class version by 1
+
+   * mhflux/MHAlpha.cc:
+     - removed erronornously comittet SetSumw2
+     - don't output the numbe rof excess events vs time
+
+
+
+ 2009/02/15 Thomas Bretz
+
+   * ceres.rc:
+     - added the MAGIC I high gain pulse as example
+
+   * sponde.cc:
+     - redirect root error handler
+     - added new option to force on-time fit
+
+   * datacenter/scripts/runcorsika:
+     - added a comment
+     - remove empty dat file after corsika finished
+
+   * mbase/MLog.cc:
+     - added several more log-levels to handling root's error handler
+
+   * mbase/MPrint.cc:
+     - flush buffer before printing
+     - set output level to all
+
+   * melectronics/MPulseShape.h:
+     - let clone also clone the spline
+
+   * mfileio/MWriteRootFile.cc:
+     - don't output title if empty
+
+   * mhflux/MHEffectiveOnTime.[h,cc]:
+     - added new data mebers to store the result of the overall-fit
+       which is now done in Finalize
+     - output the results of the effective on-time fit as inf2
+     - increased clas version accordingly
+
+   * mjobs/MJSimulation.[h,cc]:
+     - simplified setting up the file structure
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - added the possibility to force a new on-time fit.
+     - a MHEffectiveOnTime histogram is now always displayed 
+       for manual cross checks
+
+   * mjobs/MJStar.cc:
+     - added MSrcPosCam for Monte Carlos to output
+
+   * mpointing/MSrcPosCalc.cc:
+     - ignore the WobbleMode from the MMcCorsikaRunHeader 
+       if it is a ceres file
+
+   * msim/MPhotonEvent.[h,cc]:
+     - added function GetTimeFirst
+     - added function GetTimeLast
+     - added function GetTimeMedianDev
+     - added fLength to MPhotonStatistics
+
+   * msimcamera/MSimGeomCam.cc:
+     - make use of the new functions
+     - set length to statistics container
+
+   * mpointing/MHSrcPosCam.[h,cc], mpointing/MSrcPosRndm.[h,cc],
+     mfilter/MFMagicCuts.[h,cc], mmuon/MHMuonPar.[h,cc],
+     mhflux/MHThetaSqN.[h,cc]:
+     - support changing geometries (conversion factors) reading
+       a new geometry from a run header
+
+   * mimage/MHVsSize.[h,cc], mimage/MHNewImagePar.[h,cc],
+     mimage/MHHillasSrc.[h,cc], mimage/MHHillasExt.[h,cc],
+     mimage/MHHillas.[h,cc], mimage/MNewImagePar2.[h,cc]:
+     - removed option to set conversion factor manually
+     - support changing geometries (conversion factors) reading
+       a new geometry from a run header
+     - increased class version by one
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - replaced Form by MString::Format
+
+     - made sure that nobody is mixing different energy-range monte
+       carlos and normalizes by integral (to be implemented)
+
+   * manalysis/MMcCalibrationUpdate.cc:
+     - switched off file Ceres files (this might only be temporary
+       but it makes the display work quite well even without
+       calibrated units.
+
+   * mjobs/MJCalibrateSignal.cc:
+     - updated the rule to allow for file names without the leading date
+
+   * mjobs/MJSpectrum.[h,cc]:
+     - set the kMustCleanup bit for sanity
+     - replaced a lot of Form by MString::Format
+     - moved the getting of the right Alpha-histogram to GetHAlpha
+     - the tlist2 doesn't neet to replace anything because all previous
+       tasklists added to the list have been removed again
+     - "DataType" already in parlist? Don't add a second one
+     - replaced some gLog by fLog
+     - make sure that the "Done." message is printed even in case
+       no output is written at the end
+
+   * ceres.rc:
+     - added some more info
+
+   * datacenter/scripts/runcorsika:
+     - added magnetic field Azimuth direction (ARRANG), currently
+       at ~ -7deg at La Palma
+
+   * mbase/MLog.cc:
+     - finallyadded a really stupid hack/workaround to suppress these
+       annoying errors in case of a log-scale set too early
+
+   * mbase/MTask.[h,cc]:
+     - Replaced OverwritesProcess by Overwrites
+
+   * mcorsika/MCorsikaEvtHeader.cc:
+     - fixed particle momentum coordinate system
+
+   * mcorsika/MCorsikaRunHeader.[h,cc]:
+     - added magnetic field values
+     - improved output
+
+   * mjobs/MJSimulation.cc:
+     - updated height scale
+     - use MPhotonStatistics.fLength
+     - plot median dev of photon arrival times
+
+   * mmc/MMcRunHeader.hxx:
+     - added a getter IsCeres
+     - added a setter for the Corsika Version
+
+   * mpedestal/MMcPedestalCopy.cc:
+     - use the new IsCeres
+
+   * msim/MSimMMCS.[h,cc]:
+     - use the telescope pointing in telescope coordinates for MMcEvt
+     - correct the shower direction by the magnetic field azimuth
+     - set corsika program version
+
+   * msim/MSimPointingPos.[h,cc]:
+     - splitted the output into coordinated in the corsika frame
+       (module the magnetic field) and the poiting direction in
+       telescope coordinates
+     - added possibility to "observe" in off-target mode
+
+   * msimreflector/MSimReflector.cc:
+     - use new pointing direction in the corsika frame
+
+
+
+
+ 2009/02/13 Thomas Bretz
+
+   * mcorsika/MCorsikaEvtHeader.h:
+     - added some comments on the coordinate system
+
+   * ceres.rc:
+     - added some comments 
+     - setup a psf for the dwarf mirror
+
+   * mcorsika/MCorsikaRunHeader.h:
+     - added some comments
+
+   * mjobs/MJSimulation.cc:
+     - added some histogram titles
+     - fixed the x, y coordinates of the impact histogram
+     - write "ElectronicNoise"
+
+   * mjobs/MJStar.cc:
+     - don't force writing of containers which are not filles by ceres
+     - updated rule to support files without date
+
+   * mpedestal/MPedestalPix.[h,cc]:
+     - added Print() function
+
+   * mraw/MRawFileRead.cc:
+     - added a comment
+
+   * msim/MPhotonData.h:
+     - added comments about coordinate system
+
+   * msimcamera/MSimGeomCam.cc:
+     - when looking for the pixels convert from ceres-coordinates
+       to GeomCam camera-coordinates
+
+   * msimreflector/MMirror.h:
+     - added Setter for SigmaPSF
+
+   * msimreflector/MMirrorDisk.cc, msimreflector/MMirrorHex.cc,
+     msimreflector/MMirrorSquare.cc:
+     - now start counting in ReadM with 0
+
+   * msimreflector/MReflector.[h,cc]:
+     - added some documentation
+     - added function to set psf of all mirrors
+     - added psf optional to input file
+     - remove already evaluated tokens from TObjArray
+     - added reading of a default psf from the input file
+
+   * mjobs/MSequence.cc:
+     - fixed a bug in GetArrays which could cause seg-faults
+     - added a sanity check
+
+
+
+ 2009/02/12 Thomas Bretz
+
+   * datacenter/macros/fillsources.C:
+     - updated
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - added some comments
+     - renamed GetNewFileName to SubstituteName
+     - made SubstituteName static
+
+   * mhist/MHCamera.cc:
+     - fixed the number in the legend (was wrong since last update)
+
+   * mjobs/MDataSet.cc:
+     - replaced From by MString::Format
+
+   * mjobs/MJSimulation.cc:
+     - a lot of things were renamed
+     - the refelctor can now be set from the setup file
+     - changed the binning for the event width
+     - removed plot "CamShadow"
+     - changed rules for file names
+
+   * ceres.rc:
+     - updated according to the changes in MJSimulation
+
+   * mjobs/MSequence.cc:
+     - replaced use of Form by MString::Format
+     - allow non-setting of fNight
+     - don't print period if -1
+
+   * mmain/MEventDisplay.cc:
+     - decode trigger pattern for display 
+
+   * mmain/Makefile:
+     - included mtrigger
+
+   * msim/MHPhotonEvent.cc:
+     - search Reflector instead of MReflector
+
+   * msim/MSimAbsorption.cc:
+     - added some info output
+
+   * msimcamera/MSimAPD.[h,cc]:
+     - added an option to set the geom cam name. Can be used to skip 
+       this task
+
+   * msimcamera/MSimCamera.[h,cc]:
+     - allow to set BaselineGain from resource file
+
+   * msimreflector/MSimReflector.cc:
+     - removed CamShadow container
+     - search Reflector instead of MReflector
+
+   * Makefile:
+     - removed mreflector
+
+   * mcalib/MCalibrationPatternDecode.cc:
+     - in case of pattern==0 and MCs set the color to CT1. This is
+       a workaround because the bits don't allow to set is explicitly
+     - removed the check for the kCT1Pulser bit. It can never be true
+     - consequently removed the kCT1Pulser bit
+
+  * mpedestal/MMcPedestalCopy.[h,cc]:
+    - fixed for MUX MCs (the pedestal has to be scaled)
+    - added option to process ceres data
+
+
+
+ 2009/02/11 Thomas Bretz
+
+   * mcalib/MCalibColorSet.[h,cc]:
+     - removed some obsolete break statements
+     - removed obsolete gkMCRunLimit
+     - fixed setting of signal strength for extremely old
+       runs (I think we don't have them anyway)
+
+   * mcalib/MCalibrateData.cc:
+     - improved output
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - stop if no valid pulser colors have been found
+
+   * mcorsika/MCorsikaRunHeader.h:
+     - some cosmetics
+     - added some getter
+
+   * mhist/MHEvent.[h,cc]:
+     - some improvements to output
+     - implemented display for trigger pattern
+
+   * mtrigger/MTriggerPattern.[h,cc]:
+     - added Copy-function
+
+   * mhist/Makefile:
+     - added -I../mtrigger
+
+   * mmc/MMcEvtBasic.[h,cc]:
+     - moved the getter returning a TString to the source file
+     - replaced Form by MString::Format
+
+   * mraw/MRawRunHeader.cc:
+     - initialize fSourceEpochChar[1]
+     - initialize fNumEventsRead
+     - suppress more output which has not been initialized
+     - removed run-type from SetRunInfo
+     - added new function SetRunType
+     - use strncpy instead of memcpy
+     - replaced const char[] arguments by TString
+
+   * msimreflector/MReflector.[h,cc]:
+     - added Print
+     - added a circle around the mirror showing fMaxR
+
+   * mastro/MAstro.cc:
+     - updated some typos in comments
+
+   * mbase/MEnv.cc:
+     - replaced Form by MString::Format
+
+   * mbase/MTask.cc:
+     - made the total number of executions really count the total 
+       number
+
+   * mcalib/MCalibrationPatternDecode.cc:
+     - some cosmetics
+     - corrected the use of a wrong FindCreateObj
+
+   * mcorsika/MCorsikaRead.cc:
+     - added a comment
+
+   * mfileio/MWriteRootFile.cc:
+     - improved output
+     - improved the copy of a tree (now done without unpacking)
+     - made sure that copied trees are shown in the summary
+     - made sure that the copied trees are nevertheless deleted
+
+   * mfilter/MFDeltaT.cc:
+     - adapted to change in GetNumExecutions
+
+   * mhbase/MFillH.cc:
+     - set the number of executions (as it is in MTask) before the
+       execution
+
+   * mhbase/MH.cc:
+     - improved the statistics output
+
+   * mhist/MHCamera.[h,cc]:
+     - don't create an own pad anymore
+     - removed SetRange
+     - SetRange now done via MH::SetPadRange
+     - some sanity checks if fGeomCam is set
+     - some adaptions to the new layout scheme without
+       an own pad
+     - Changed DrawProjection to a more commonly usable scheme
+     - Removed all dependencies from MGeomCamMagic
+     - start the gaus fit with the maximum not the integral
+
+   * mjobs/MJCalibrateSignal.cc:
+     - If the input files contain an OriginalMC tree 
+       copy it
+     - consequently we make the MMcEvtBasic from the 
+       parameter-list optional
+     - fixed the rule (MC files with .root as extension could not 
+       be processed)
+
+   * mjobs/MJCalibration.[h,cc], mjobs/MJPedestal.[h,cc]:
+     - Use MHCamera::CamDraw more extensively
+     - replace use of Form by MString::Format
+
+   * mjobs/MJSimulation.cc:
+     - added an option to switch the cmaera electronics off
+     - write some more containers to output file (for easy access)
+     - set the MC bit in the header
+     - now use MSimMMCS to "fake" the correct file structure
+     - added three new writers to write the MMcEvtBasic information
+     - added a display of the most important things
+
+   * mmain/MEventDisplay.cc:
+     - don't change into the not more existing pad of a MHCamera
+
+   * msimcamera/MSimCalibrationSignal.cc:
+     - adapted GetNumExecution
+     - SetReadyToSave for the run header
+     - jitter the number of emitted photons
+     - corrected the emitted trigger positon
+     - (re)set calibration pattern
+
+   * mbase/MLut.[h,cc]:
+     - added overload of Delete() function
+     - added IsDefault
+     - added SetDefault
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed output in OpenFile
+
+   * mjobs/MSequence.cc:
+     - allow the "Night" resource to be empty
+
+   * msimcamera/MSimBundlePhotons.cc:
+     - some small improvements in case of empty maps
+
+   * msimcamera/MSimReadout.[h,cc]:
+     - reset gain. Use the new fConversionFactor instead
+     - removed some setting of fRunHeader
+
+   * msimcamera/MSimTrigger.[h,cc]:
+     - on useer request now offset and gain can be used to 
+       convert the signal back into units of phe
+     - added possibility to use empty lookup tables
+     - added debug output
+
+   * msimcamera/MSimCamera.[h,cc]:
+     - outsourced the pedestal and gain numbers into ReInit
+     - use an MPedestalCam for Electronic Noise and Gain
+     - allow to switch ob whether the gain is applied to the 
+       electronic noise or not
+     - SetPhotElfromShower
+
+   * msim/Makefile. msim/SimLinkDef.h:
+     - added MSimMMCS
+
+   * msim/MSimMMCS.[h,cc]:
+     - added
+
+   * msimcamera/Makefile:
+     - added -I../mpedestal
+
+   * ceres.rc:
+     - added
+
+   * msimreflector/MMirrorSquare.cc, msimreflector/MMirrorHex.cc,
+     msimreflector/MMirrorDisk.cc:
+     - changed the grey colors
+
+   * msimreflector/MMirrorHex.cc:
+     - fixed bugs in CanHit and HasHit
+
+
+
+ 2009/02/10 Thomas Bretz
+
+   * manalysis/MMcTriggerLvl2Calc.cc:
+     - removed obsolete include of MmcRunHeader
+
+   * mbase/MSpline3.[h,cc]:
+     - improved the available constructors
+     - added some comments for future use
+     - added default constructor
+     - added GetHistogram()
+
+   * mcorsika/MCorsikaRunHeader.[h,cc]:
+     - added fImpactMax
+     - added some Getters
+
+   * melectronics/MPulseShape.[h,cc]:
+     - set class version to 1 to make it storable
+     - set a title for the splines
+     - implemented Paint function
+
+   * mhbase/MH.[h,cc]:
+     - added SetPadRange
+
+   * mhist/MHCamEvent.[h,cc]:
+     - Init the geometry in ReInit thus it can work with a geometry stored in a file
+     - Make sure that histogranms already drawn properly to a pad are found in Paint
+     - added RecursiveRemove for sanity
+
+   * mmc/MMcCorsikaRunHeader.h:
+     - added SetSpectrum
+
+   * mmc/MMcEvt.hxx:
+     - added SetEvtNumber
+     - added SetPhotElfromShower
+
+   * mmc/MMcEvtBasic.[h,cc]:
+     - added operator=
+
+   * mmc/MMcRunHeader.[hxx, cxx]:
+     - set default for the versions to UShort_t(-1)
+     - added some comments 
+     - added SetNumSimulatedShowers
+     - added SetImpactMax
+
+   * mraw/MRawRunHeader.cc:
+     - suppress some information in header if not valid
+
+   * msignal/MSignalCalc.cc:
+     - if (!fPedestal) we should return kTRUE not kFALSE
+
+   * msimreflector/MMirror.[h,cc], msimreflector/MMirrorDisk.[h,cc],
+     msimreflector/MMirrorHex.[h,cc], msimreflector/MMirrorSquare.[h,cc],
+     msimreflector/MReflector.[h,cc],
+     - added Print
+     - some cosmetics in header
+     - set class version to 1 to make it storable
+
+   * mtools/MagicJam.cc:
+     - updated
+
+
+
+ 2009/02/10 Daniela Dorner
+
+   * datacenter/db/tabs.php:
+     - if csv-file doesn't exist, only logs are displayed now
+
+
+
+ 2009/02/08 Thomas Bretz
+
+   * Makefile.conf.linux:
+     - added -Winit-self
+
+   * msimcamera/MSimCalibrationSignal.[h,cc]:
+     - account for the pulse shape/width
+     - make number of photons settable
+     - make time jitter settable
+     - renamned fNumEntries to fNumEvents
+     - don't set daq event number (should be set by the "daq")
+     - set trigger pattern
+     - print number of events in PreProcess
+
+   * msimreflector/MSimReflector.[h,cc]:
+     - made the detector margin settable
+
+   * datacenter/macros/insertcacofile.C, datacenter/macros/insertsequence.C:
+     - print an error and exit
+
+   * macros/optim/optimdisp.C:
+     - set the default values as default
+     - added a short summary what a good strategy for optimization is
+
+   * mastro/MAstro.cc:
+     - replaced Form by MString::Form
+
+   * mcorsika/MCorsikaEvtHeader.[h,cc], mcorsika/MCorsikaRunHeader.[h,cc]:
+     - moved fParticleID from event header to run header
+     - increased Class Version accordingly
+     - added an error if more than one observation levels are read
+
+   * mhcalib/MHGausEvents.cc:
+     - replaced Form by MString::Form
+     - handle the creating of the TF1 fExpFit a bit more "root-safe"
+
+   * mhist/MHCamEvent.[h,cc]:
+     - added a new option to collect the maximum or minimum contents
+
+   * mhist/MHCamera.[h,cc]:
+     - added new functions SetMax/MinCamContent
+
+   * mraw/MRawEvtHeader.cc:
+     - initialize the data members in constructor
+
+   * mraw/MRawEvtHeader.h:
+     - removed bits for trigger type they were never used
+
+   * mraw/MRawRunHeader.cc:
+     - tiny cosmetics
+
+   * msim/MHPhotonEvent.[h,cc]:
+     - added a histogram to display the height
+     - don't fill kNightSky photons
+
+   * msim/MPhotonData.h:
+     - added getter for fProductionHeight
+
+   * msim/MPhotonEvent.h:
+     - commented IsValid (was not used anyhow)
+
+   * msimcamera/MSimGeomCam.[h,cc]:
+     - added one sample to the window to allow for time jitter of one sample
+     - make the code for the window indentical to MSimCalibrationSignal
+
+   * msimcamera/MSimReadout.[h,cc]:
+     - Set the daq event number (readout number)
+
+   * msimcamera/MSimTrigger.[h,cc]:
+     - added comments
+     - made the signal length settable
+     - made the coincidence time settable
+     - removed setting of the daq event number (should be done by the "daq")
+     - changed the trigger output from all to inf/inf2
+
+   * msimcamera/Makefile:
+     - added -I../mtrigger
+
+   * mjobs/MJSimulation.[h,cc]:
+     - added new mode to force the use of the trigger "electronics"
+     - moved setup of the fadc to the resource file
+     - added a new histogram to show the maximum signal in all pixels
+     - automatically setup the range of the TrigPos histogram
+     - don't show all histograms in all run conditions
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added ReadEnv for a setup from a resource file in ceres
+
+   * msimcamera/MSimAPD.cc:
+     - added a sanity check if ReInit has not been called
+
+
+
+ 2009/02/07 Thomas Bretz
+
+   * sponde.rc:
+     - fixed a typo
+
+   * datacenter/scripts/runcorsika:
+     - added a comment
+
+   * mbase/MContinue.h:
+     - changed a comment
+
+   * mbase/MEnv.h, mbase/MMath.cc:
+     - Do not assign a temporary TString to const char *
+
+   * mcamera/MCameraCentralPix.[h,cc]:
+     - changed fDC from Float_t to Int_t 
+
+   * mhflux/MHCollectionArea.cc, mhflux/MHDisp.cc, mhflux/MHEnergyEst.cc,
+     mhflux/MHFalseSource.cc, mhflux/MHThreshold.cc, mhbase/MFillH.cc,
+     mastro/MAstroCamera.cc, mastro/MAstroCatalog.cc, mbase/MContinue.cc,
+     mbase/MFilter.cc, mbase/MLog.cc, mbase/MParContainer.cc, mhbase/MH.cc,
+     mbase/MParEmulated.cc, mbase/MStatusDisplay.cc, mbase/MTime.cc,
+     mhbase/MH3.cc, mhbase/MHn.cc,mhflux/MHAlpha.cc, mhist/MHCamera.cc,
+     mhflux/MHEffectiveOnTime.cc, mmuon/MHMuonPar.cc, mmovie/MMovieWrite.cc,
+     mhflux/MHFalseSource.cc, mhist/MHCamEvent.cc, 
+     mmain/MEventDisplay.cc, mreflector/MHReflector.cc:
+     - use MString::Format instead of Form
+
+   * msim/MHPhotonEvent.cc:
+     - don't fill kNightSky primaries
+
+   * msim/MPhotonEvent.[h,cc]:
+     - return the number of non NightSky photons
+
+   * msimcamera/MSimPSF.cc:
+     - changed default for fSigma from 1 to -1
+
+   * mbase/MContinue.cc:
+     - changed default title
+
+   * mfileio/MWriteRootFile.cc:
+     - set kMustCleanup bit, otherwise it is not correctly deleted from
+       the list of cleanups
+
+   * mhbase/MH3.[h,cc]:
+     - added RecursiveRemove
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - moved code to source file
+     - improved setting of a new fFunc
+
+   * mhflux/MHAlpha.[h,cc], mhvstime/MHSectorVsTime.[h,cc]
+     - added RecursiveRemove
+
+   * mjobs/MJSimulation.cc:
+     - added MSimPSF
+     - Show only the non NightSky photons in the size plot
+     - changed the binning of BinningEvtWidth
+
+
+
+ 2009/02/06 Daniela Dorner
+
+   * datacenter/db/include.php:
+     - adapted status-query
+
+
+
+ 2009/02/05 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C:
+     - implemented new SuperArehucas version
+
+
+
+ 2009/02/03 Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - searches now all catalogs also in the datacenter default path if
+       the file could not be found
+
+   * mbase/MStatusDisplay.cc:
+     - also print information about added tabs in batch mode
+
+   * mcorsika/MCorsikaEvtHeader.h:
+     - fixed a comment
+
+   * mfileio/MWriteRootFile.cc:
+     - added some more log-output
+     - open a new /dev/null only if none with the same title already exists
+     - added some comments
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - Don't call PaintText if FitH failed (as suggested by valgrind)
+
+   * mjobs/MJStar.cc, mjobs/MJCalibrateSignal.cc:
+     - added a title to all MWriteRootFile
+
+   * mreport/MReportCC.cc:
+     - added more comments
+     - improved log-output
+
+
+
+ 2009/02/03 Daniela Dorner
+
+   * datacenter/db/plotdb.php:
+     - sequence as default when startup
+
+   * datacenter/db/plotdb.php, datacenter/db/plot.php:
+     - added possibility to set size of plot
+
+
+
+ 2009/02/03 Stefan Ruegamer
+
+   * datacenter/scripts/budb:
+     - added getdbsetup
+
+
+
+ 2009/02/02 Thomas Bretz
+
+   * mcamera/MCameraCentralPix.[h,cc]:
+     - added data member fDC
+     - increased class version number accordingly
+
+   * mreport/MReportCC.cc:
+     - improved debug output
+     - remove minus from the third argument in SCHEDULE
+
+   * mreport/MReportCamera.[h,cc]:
+     - fixed for ver>=200812140
+     - added InterpretePSSEN
+     - added InterpreteLIQ
+
+   * msimcamera/MSimCamera.cc:
+     - added a time-shift uniformly according to the bin-width
+
+
+
+ 2009/01/30 Thomas Bretz
+
+   * RELEASE V2.2
+
+
+ 2009/02/02 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJStar.cc:
+     - fixed the regular expresssion
+
+
+
+ 2009/01/30 Thomas Bretz
+
+   * datacenter/macros/fillcmt.C:
+     - added
+
+   * datacenter/macros/plotstat.C:
+     - extended loop to show all periods again
+
+   * msim/MPhotonData.cc:
+     - don't change the sign of the cosines. The direction of the
+       particle doesn't neet to be changed
+
+   * msimreflector/MSimReflector.cc:
+     - change the rotation matrix to fit the change in MPhotonData
+
+
+
+ 2009/01/29 Thomas Bretz
+
+   * melectronics/MPulseShape.cc:
+     - changed spline range from -25/25 to -8/8
+
+   * mhflux/MAlphaFitter.cc, mhflux/MHAlpha.cc, mhflux/MHDisp.cc:
+     - for sanity (thread safety) replaced Form by MString::Format
+
+   * mhflux/MHDisp.cc:
+     - initialize fHalf as suggested by valgrind
+
+   * datacenter/macros/plotdb.C:
+     - updated comments
+
+   * resources/calibration_spline.rc:
+     - updated
+
+
+
+ 2009/01/27 Thomas Bretz
+
+  * macros/rootlogon.C:
+     - added new subdirectories
+
+   * melectronics/MAnalogSignal.[h,cc]:
+     - added the posssibility to add a pulse from a TF1
+     - removed the printout if out of range
+     - returns whether the range had to be adapted
+     - changed the Discriminate function to allow for giving a start
+       and end time of the search
+     - imporved the fining of the falling and rising edge
+     - removed the printout in Discriminate
+
+   * msimcamera/MSimCamera.[h,cc]:
+     - moved the pulse shape specific code into a new class MPulseShape
+     - Fixed the range of the digitization
+
+   * melectronics/MPulseShape.[h,cc]:
+     - added
+
+   * melectronics/Makefile, melectronics/ElectronicsLinkDef.h:
+     - added MPulseShape
+
+   * msimcamera/MSimGeomCam.[h,cc]:
+     - Fixed the time window for random photons (Maybe move to a later
+       step in the analysis?)
+
+   * msimcamera/MSimReadout.cc:
+     - call SetReadyToSave for the run-header
+     - added some debug output in case of failure
+
+   * msimcamera/MSimSignalCam.[h,cc]:
+     - subtract the trigger position of any
+
+   * msimcamera/MSimTrigger.cc:
+     - some changes to the debug output
+
+   * mjobs/MJSimulation.[h,cc]:
+     - added
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJSimulation
+
+   * ceres.cc, showlog.cc, callisto.cc, star.cc, ganymed.cc, sponde.cc:
+     - added parenthesis suggested by compiler
+
+   * mbase/MParEnv.cc:
+     - included TClass for newwer root versions
+
+   * msimreflector/MReflector.cc:
+     - fixed return if read file was not existing
+
+   * msimrelfector/MSimReflector.cc:
+     - added sanity check if reflector is valid
+
+   * datacenter/macros/insertdataset.C:
+     - added fPriority
+
+   * datacenter/macros/plotoptical.C:
+     - write a root-file as the other plot-macros do
+
+   * mreflector/MHReflector.cc:
+     - added some SetDirectory(NULL), although this class is a candidate
+       for removal
+
+   * mjobs/MJCut.cc, mjobs/MJCalibrateSignal.cc:
+     - make the CheckEnv fail if kFALSE is returned
+
+
+
+ 2009/01/26 Thomas Bretz
+
+   * Makefile:
+     - added mcorsika, msim, msimreflector, msimcamera and
+       msimelectronics
+     - added readcorsika
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MParEnv
+
+   * mbase/MParEnv.[h,cc]:
+     - added
+
+   * mbase/MParameters.[h,cc]:
+     - added ReadEnv to all classes
+
+   * mbase/MParList.cc:
+     - return the container within MParEnv if MParEnv found 
+
+   * mbase/MParContainer.cc:
+     - fixed a typo
+
+   * manalysis/MEventRateCalc.cc:
+     - added a comment
+
+   * melectronics/MAnalogChannels.[h,cc]:
+     - made the GetNum* unsigned
+     - added new member functions to just initialize one size
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added a possibility to just init the number of pixels
+
+   * msimcamera/MSimReadout.[h,cc]:
+     - get the number of output channels from the camera geometry
+     - initialize the runheader in ReInit
+     - initialize the data arrays from the run-header in reinit
+
+   * mimage/MHHillas.cc:
+     - the default binning is not scales by 0.9 anymore
+
+   * mmc/MMcEvtBasic.h:
+     - added new type "artificial" 
+
+   * mraw/MRawRunHeader.cc:
+     - set header size in constructor to 0
+
+   * msimcamera/MSimCalibrationSignal.[h,cc]:
+     - we need fEvt and fTrigger always
+     - renamed ReInit to CallReInit
+     - set photon primary type
+     - set number of photons from 50 to 5
+
+   * msimcamera/MSimRandomPhotons.cc:
+     - explicitly set weight to 1
+
+   * mjobs/Makefile:
+     - added msim, msimreflector, msimcamera and mcorsika
+
+
+
+ 2009/01/25 Thomas Bretz
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MLut
+
+   * mbase/MLut.[h,cc]:
+     - added
+
+   * msimcamera/MSimCamera.[h,cc], msimcamera/MSimTrigger.[h,cc],
+     msimcamera/MSimRadout.[h,cc], msimcamera/SimCameraLinkDef.h,
+     msimcamera/Makefile, msimcamera/MSimCalibrationSignal.[h,cc],
+     msimcamera/SimCameraIncl,h:
+     - added
+
+   * mjobs/MJob.cc:
+     - included TClass for newer root versions
+
+   * mreflector/MRflEvtData.cc:
+     - repaced a use of MHexagon by a direct use of MGeomCam
+
+   * melectronics/MAvalanchePhotoDiode.[h,cc]:
+     - added some getters
+     - remobved some obsolete comment
+     - set entries to 1 by default
+
+   * mgeom/MGeomCam.[h,cc]:
+     - split the Get[Max,Min]Radius into two member functions
+     - added the HitDetector based on the maximum radius calculated
+
+   * mgeom/MGeomCamDwarf.[h,cc], mgeom/MGeomCamMagic.[h,cc]:
+     - removed overloading of the new HitDetector
+
+   * mgeom/MGeomPix.[h,cc]:
+     - reset fUserBits in constructor according to a suggestion by valgrind
+     - added GetT member function
+
+   * mjobs/MJSpectrum.cc:
+     - replaced some Form calls for sanity by MString::Format
+     - check the result of CheckEnv
+
+   * mjobs/MJStar.cc:
+     - check the result of CheckEnv
+
+   * mjobs/MJob.cc:
+     - fixed a typo in the name for the seed value resource
+
+   * mraw/MRawRunHeader.h:
+     - added a getter for run type point run
+
+   * msignal/MSignalCalc.cc:
+     - don't execute Process at all if fPedestal==NULL
+
+   * msignal/MSignalCam.cc:
+     - aded case 10 and 11 to GetPixelContent
+
+   * msim/MHPhotonEvent.cc:
+     - replaced case 4 by using the traversal distance in the 0-pixel
+
+   * msimcamera/MSimSignalCam.cc:
+     - set pixel only to used if contents>0
+
+   * msimcamera/MSimTrigger.[h,cc]:
+     - added ReadEnv for setup from a resource file
+     - compress the trigger list after deleting slots
+     - initialize descriminator threshold with -1
+     - check for the validity of the discr. th in PreProcess
+
+   * msimreflector/MReflector.[h,cc]:
+     - store file name in title
+     - added ReadEnv for setup from a resource file
+
+   * msimreflector/MSimReflector.[h,cc]:
+     - changed copyright notice
+     - added fDetectorMargin
+
+
+
+
+ 2009/01/24 Thomas Bretz
+
+   * mbase/MMath.cc:
+     - added two explicit conversion to make it compile on my Ubuntu
+     - Replaced some Form by MString::Format
+     - included MString
+
+
+
+ 2009/01/23 Daniela Dorner
+
+   * datacenter/db/showplots-ds.php, datacenter/db/tabs.php, 
+     datacenter/db/plot.php:
+     - adapted path to new web file structure
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php:
+     - added option to group by date (year, month, night): pulldown in
+       menu and adapted query
+
+   * datacenter/db/sequinfo-aio.php, datacenter/db/runinfo-aio.php
+     datacenter/db/datasetinfo-aio.php:
+     - enabled possibility to combine all group-bys 
+
+   * datacenter/db/datasetinfo-aio.php:
+     - enhances information printed in table in case of group-by
+
+   * datacenter/db/include.php:
+     - adapted pulldown of status-group-by
+
+   * datacenter/db/menu.php:
+     - added pulldown for sumtrigger-flag to sequinfo-menu
+     - added function to print pulldown for group-by date
+
+
+
+ 2009/01/23 Thomas Bretz
+
+   * mcorsika/MCorsikaEvtHeader.[h,cc], msim/MPhotonData.[h,cc],
+     msimcamera/MSimExcessNoise.cc, msimreflector/MMirrorDisk.cc,
+     msimreflector/MMirrorHex.cc, msimreflector/MMirrorSquare.[h,cc],
+     msimreflector/MReflector.cc, msimreflector/MSimReflector.cc,
+     melectronics/MAnalogSignal.cc:
+     - moved code which needs TMath to source file
+     - included TMath for newer root versions
+     - included TObjArray for newer root versions
+
+   * msimcamera/MSimAPD.[h,cc], msimcamera/MSimBundlePhotons.[h,cc], 
+     msimcamera/MSimRandomPhotons.[h,cc]:
+     - added
+
+   * melectronics/Makefile, melectronics/MAnalogChannels.[h,cc],
+     melectronics/ElectronicsIncl.h, melectronics/ElectronicsLinkDef.h, 
+     melectronics/MDigitalSignal.[h,cc],  
+     melectronics/MAnalogSignal.[h,cc], 
+     melectronics/MAvalanchePhotoDiode.[h,cc]:
+     - added
+
+   * msim/M*.cc, msimreflector/M*.cc, msimcamera/M*.cc:
+     - changed copyright notice
+
+   * mjobs/MJob.[h,cc]:
+     - for convinience replaced GetEnvValue by GetEnvValue2
+     - added initialization of the random number generator
+
+   * ceres.cc, mcorsika/CorsikaIncl.h:
+     - added
+
+
+
+ 2009/01/22 Thomas Bretz
+
+   * mraw/MRawRunHeader.h:
+     - added new functions to access the runtype
+
+   * msim/MPhotonData.cc:
+     - removed some obsolete comments
+
+   * msim/MPhotonEvent.[h,cc]
+     - added some comments
+     - added new member function GetFirst and GetLast
+     - UnSort the array after reading new data
+     - removed some old obsolete code
+     - added new meber function Sort and IsSorted
+
+   * msimreflector/MSimReflector.cc:
+     - force sorting of the array
+
+  * msimcamera/MSimPSF.[h,cc], msimcamera/MSimGeomCam.[h,cc], 
+    msimcamera/MSimExcessNoise.[h,cc], msimcamera/MSimSignalCam.[h,cc]:
+    - added
+
+
+
+ 2009/01/21 Thomas Bretz
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MQuaternion
+     - added MReflection
+
+   * mbase/MQuaternion.[h,cc], mbase/MReflection.[h,cc]:
+     - added
+
+   * mbase/MArrayI.[h,cc]:
+     - added a few new functions (ReSort, Add, Find and AddUniq)
+
+   * mbase/MMath.cc:
+     - replaced delete by delete[] where appropriate
+
+   * mgeom/MGeomCam.h:
+     - added new virtual functions HitFrame and HitDetector
+     - included MQuaternion
+
+   * mgeom/MGeomCamDwarf.[h,cc], mgeom/MGeomCamMagic.[h,cc]:
+     - added new functions HitFrame and HitDetector:
+
+   * msim/MHPhotonEvent.cc:
+     - removed the reference to MCamera
+
+   * mgeom/MGeomPix.[h,cc], mgui/MHexagon.[h,cc]:
+     - moved DistanceToPrimitive from MHexagon to MGeomPix
+     - moved the funtions to calculate overlapping areas 
+       also, but they are still in a comment
+
+   * mgui/MHexagon.[h,cc]:
+     - started implementing a rotation angle
+     - added data meber fPhi
+     - increased class version number
+
+   * mhist/MHCamera.cc, mtools/MagicJam.cc:
+     - we don't have to use a MHexagon anymore caluclating 
+       DistanceToPrimitive
+
+   * msimreflector/MMirror.[h,cc], msimreflector/MMirrorSquare.[h,cc],
+     msimreflector/MMirrorHex.[h,cc], msimreflector/MMirrorDisk.[h,cc],
+     msimreflector/MReflector.[h,cc], msimreflector/MSimReflector.[h,cc],
+     msimreflector/Makefile, msimreflector/SimReflectorLinkDef.h, 
+     msimreflector/SimReflectorIncl.h:
+     - added
+
+
+
+ 2009/01/21 Stefan Ruegamer
+
+   * datacenter/scripts/read_lapalma-tapes:
+     - added check of the tape slot when exporting the tapes
+
+
+
+ 2009/01/20 Thomas Bretz
+
+   * mjobs/MJob.h:
+     - added Esc member function
+
+   * msim/MPhotonData.[h,cc], msim/MPhotonEvent.[h,cc], 
+     msim/MSimAbsorption.[h,cc], msim/MSimPointingPos.[h,cc],
+     MHPhotonEvent.[h,cc], msim/Makefile, msim/SimIncl.h 
+     msim/SimLinkDef.h:
+     - added
+
+
+ 2009/01/19 Thomas Bretz
+
+   * mfileio/MWriteRootFile.cc:
+     - simplified how the rules are evaluated using TPregexp
+     - by this the rules got more powerful
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJStar.cc:
+     - changed ols style rule to new style
+
+
+
+ 2009/01/18 Thomas Bretz
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MSpline3
+
+   * mcorsika/MCorsikaEvtHeader.cc:
+     - some little cosmetics
+
+   * mcorsika/MCorsikaEvtHeader.h:
+     - added some missing getters
+
+   * mcorsika/MCorsikaRunHeader.cc:
+     - removed some obsolete comments
+     - reordered some comments
+
+   * mextralgo/MExtralgoSpline.h:
+     - changed default in GetIntegral from true to false
+
+   * mraw/MRawEvtHeader.h:
+     - added Setter for DAQEventNumber
+
+   * mraw/MRawRunHeader.cc:
+     - start pixel hardware indices with 1 not with 0
+
+
+
+ 2009/01/17 Thomas Bretz
+
+  * mbase/MMath.[h,cc]:
+     - added a new function RndmExp which should be a tiny bit faster than
+       root's own implementation because it ises Rndm() instead of Uniform()
+
+   * mextralgo/ExtralgoIncl.h:
+     - added MArrayF
+
+   * mextralgo/MExtralgoSpline.[h,cc]:
+     - divided FindY into FindYup and FindYdn to avoid an obsolete if-clause
+     - added a new member function to return the integral function of the
+       spline. This is useful to init a new spline and use it for 
+       producing the proper random distribution.
+
+   * mpedestal/MPedestalSubtractedEvt.[h,cc]:
+     - added Print() function
+
+   * mraw/MRawEvtData.[h,cc]:
+     - added a member function to Reset the arrays
+     - added member function to set the pixel indices
+     - Improved the new Set function
+
+  * readcorsika.cc:
+    - added
+
+
+
+ 2009/01/16 Daniel Hoehne-Moench
+
+   * datacenter/scripts/mcsequences:
+     - implemented sumtrigger -> modes, fTriggerFlagKEY
+     - fPriority(MCSequenceProcessStatus) is now filled into the mcdb
+
+   * datacenter/scripts/fillmccallisto, fillmcstar:
+     - bugfix: changed argument of $primaries from [$s+$s] to [$s]
+
+   * datacenter/macros/fillcamera.C:
+     - changed NumPheFromDNSB to float(7,3)
+     - fPriority(MCRunProcessStatus) is now filled into the mcdb
+
+   * datacenter/macros/fillmccalib.C:
+     - minor changes, bugfix (wrong column name for mcdb)
+
+   * datacenter/macros/fillmcsignal.C:
+     - definition of some parameters changed according to fillsignal.C
+     - minor changes, deleted unnecessary code
+     - implemented if clause for HiLo-Parameters. Instead of 
+       seqno<200000 the fAmplFadcKEY is queried in the mcdb for each
+       sequence. For MUX MCs the HiLo-Parameters are not calculated.
+
+
+
+ 2009/01/15 Thomas Bretz
+
+   * callisto.cc:
+     - cosmetics to output
+
+   * mcorsika/MCorsikaRunHeader.cc:
+     - cosmetics (removed a ;;)
+
+   * mhist/MHEvent.[h,cc]:
+     - ReInit to allow the change of the camera geoemtry in ReInit
+
+
+
+ 2009/01/15 Stefan Ruegamer
+
+   * datacenter/scripts/dodatacheck:
+     - removed the _E in the find command; files from 2008/06/04 on do
+       not have it any more
+
+
+
+ 2009/01/14 Daniel Hoehne-Moench
+
+   * datacenter/scripts/sourcefile:
+     - extended errorcoding on mc run process status
+
+   * datacenter/scripts/runmccallisto, runmcstar:
+     - deleted unnecessary lines, adapted to primary structure
+
+   * datacenter/macros/fillmcsignal.C, fillmccalib.C, fillmcstar.C:
+     - added
+
+   * datacenter/scripts/fillmccallisto, fillmcstar:
+     - added
+
+
+
+ 2009/01/14 Thomas Bretz
+
+   * readraw.cc:
+     - check first whether the file exist before adding the extension
+
+   * mbase/MMath.[h,cc]:
+     - added function to Re-sort an array
+
+   * mfileio/MReadMarsFile.cc, mfileio/MWriteRootFile.cc:
+     - Improved output
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed a problem which prevented to open more than one /dev/null
+       devices independantly
+
+   * mgeom/MGeomCam.cc:
+     - cosmetics
+
+   * mgeom/MGeomCamDwarf.h:
+     - fixed a typo in an ifdef
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added funtion to return positon as TVector2
+     - slightly improved the algorithm to check IsInside
+     - fixed the conditional signs for the orientation of pixels
+       in GetDirection
+
+   * mmain/MEventDisplay.cc:
+     - Give different names to the MPedestalSubtract tasks
+     - fixed buttons
+     - call AddGeometryTags after ReInit to allow reading new geometries in
+       ReInit
+
+   * mmc/MMcEvtBasic.h:
+     - added a new primary type kNightSky
+
+   * mraw/MRawEvtPixelIter.h:
+     - replaced type of the number of bytes by UInt_t
+
+   * mraw/MRawRunHeader.h:
+     - allow to validate the magic-number from outside (for MCs)
+
+   * datacenter/scripts/runcorsika:
+     - added a lot of comments
+     - reordered values in input card
+     - switched off a lot of obsolete output
+     - changed the Magnetic field to a value corresponding to the location of
+       MAGIC at 2200m height valid for January 2009. (The old value never took
+       place there?!) The value was taken from www.noaa.gov/geomagmodels
+
+
+
+ 2009/01/12 Daniel Hoehne-Moench
+
+   * datacenter/db/menu.php:
+     - bugfix: now the SumTriggerFlag is correctly displayed in the web
+       interface
+
+
+
+ 2009/01/09 Daniel Hoehne-Moench
+
+   * datacenter/macros/fillcamera.C
+     - implemented new variables: zbinmin, zbinmax, number of 
+       sumtriggers, sum trigger flag
+     - bugfix: for P and C runs the mirror fraction and the impact
+       parameter had unreasonable values (negative) which were filled
+       into the mcdb, now->0
+
+   * datacenter/scripts/fillcamera, mcsequences:
+     - implemented call of getdbsetup
+
+
+
+ 2009/01/09 Stefan Ruegamer
+
+   * datacenter/scripts/buildsequenceentries
+     - corrected IFS argument
+
+
+
+ 2009/01/08 Stefan Ruegamer
+
+   * datacenter/scripts/filesondisk
+     - added S and N runs
+
+
+
+ 2009/01/07 Daniel Hoehne-Moench
+
+   * datacenter/macros/filldotrun.C:
+     - updated column counting numbers
+     - included a check for the number of columns in the runfiles
+   
+   * datacenter/macros/buildsequenceentries.C:
+     - implemented SumTriggerFlagKEY for sequence building
+
+
+
+ 2009/01/06 Thomas Bretz
+
+   * mbase/MArrayB.h, mbase/MArrayD.h, mbase/MArrayF.h,
+     mbase/MArrayI.h, mbase/MArrayS.h:
+     - removed GetSize
+
+   * mbase/MArrayF.h:
+     - added Add()
+     - added AddClipped
+
+  * mbase/MMath.[h,cc]:
+     - implemented ReSort
+
+   * mcorsika/MCorsikaEvtHeader.cc:
+     - removed obsolete comments
+
+   * mcorsika/MCorsikaRead.cc:
+     - cosmetics
+
+   * mcorsika/MCorsikaRunHeader.[h,cc]:
+     - added comments about file contents
+     - added fWavelengthMin/Max
+
+   * mextralgo/MExtralgoSpline.[h,cc]:
+     - renamed SearchY to SearchYdn
+     - fixed a problem in SearchYup (must be ++i instead of i++)
+       (this is relatively unimportant because it was only used
+        in the determination of the pulse width which we never
+        really used)
+     - added a sanity/range-check to SearchYup and SearchYdn
+     - added a comment
+     - changed the order of arguments in EvalDeriv1
+     - changed the order of arguments in EvalDeriv2
+     - accelerated EvalDeriv1 (one multiplication less)
+     - added Deriv1 function 
+     - made SearchYup and SearchYdn public
+
+   * mjobs/MDataSet.cc:
+     - removed an obsolete return statement
+
+   * mraw/MRawEvtData.[h,cc]:
+     - changed pointer in AddPixel to reference
+     - added a Set function
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added a lot of fixes for wrong run numbers written by Arehucas
+     - added a fix for strange file numbers written by Arehucas
+     - added functions as monta carlo interface to set contents
+
+   * msignal/MSignalCam.cc:
+     - defined a case 9
+
+
+
+ 2009/01/05 Thomas Bretz
+
+   * mhbase/MH.h:
+     - commited missing changes from last year
+
+   * merpp.cc:
+     - fixed a description
+
+   * sponde.cc:
+     - added "Multiple dataset at once"
+
+   * star.cc:
+     - removed obsolete -ff option from output
+
+   * mbase/MTime.[h,cc]:
+     - added GetBinary
+     - added WriteBinary
+
+   * mbase/MEvtLoop.cc:
+     - display paused status in status line
+     - improved pause handling
Index: branches/Mars_McMismatchStudy/Changelog.10
===================================================================
--- branches/Mars_McMismatchStudy/Changelog.10	(revision 17960)
+++ branches/Mars_McMismatchStudy/Changelog.10	(revision 17960)
@@ -0,0 +1,1460 @@
+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 -*-*-
+
+ 2010/11/29 Reiner Rohlfs
+
+   * msim/MPhotonData.cc:
+     - Use all data if telescope array is not defined
+
+   * msim/MPhotonEvent.[h,cc]:
+     - remove following methods:
+         Int_t ReadCorsikaEvt(MCorsikaFormat *fInFormat, Int_t i);
+         Int_t ReadCorsikaEvt(istream &fin, Int_t i);
+     - replace those methods by
+         Int_t ReadEventIoEvt(MCorsikaFormat *fInFormat);
+         Int_t ReadCorsikaEvt(Float_t * data, Int_t numEvents, Int_t arrayIdx);
+ 
+   * mcorsika/MCorsikaRunHeader.h mcorsika/MCorsikaRunHeader.cc
+     - Split method ReadEvtEnd() into two functions:
+        ReadEvtEnd() and ReadEventHeader()
+
+   * mcorsika/MCorsikaEvtHeader.[h,cc]:
+     - method ReadEvt does not read data from file by itself, but gets
+       buffer as input
+     - test that number of reuse of same shour is not greater than 20
+     - method ReadEvtEnd does not seek to the EVTE block and does not
+       read the Bloch header any more.
+
+   * mcorsika/MCorsikaFormat.[h,cc]:
+     - remove following methods:
+       SeekNextBlock(), UnreadLastHeader(), UnreadLastData(), StorePos(),
+       ResetPos(), Rewind(), GetNextEvent(), GetCurrPos(),
+       NextEventObject() and NextPhotonObject()
+     - new method: NextBlock() 
+
+   * mcorsika/MCorsikaRead.[h,cc]:
+     - new design of program flow. It is now determined by the order of
+       the data blocks in the input file.
+     - Depending on the variables fTelescopeIdx and fArrayIdx, only data
+       of the requested telescope and array are stored in the output
+       file.
+       
+   * readcorsika.cc:     
+     - two new command line arguments: -A=arrayNo and -T=telescopeNo  
+       The values of these parameters are store in the MCorsikaRead -
+       class.
+
+
+ 2010/11/22 Thomas Bretz
+
+   * Makefile.rules:
+     - use -C option of make instead of cd
+
+   * msimreflector/MSimRays.cc:
+     - added some comments
+     - fixed timing for a point source
+
+   * mbase/MStatusDisplay.cc:
+     - display canvas title in status line
+
+   * mhbase/MH3.[h,cc]:
+     - added scaling for fourth (time) axis
+
+
+
+ 2010/11/03 Daniela Dorner
+
+   * datacenter/scripts/copyoutput:
+     - changed query so that only successfully processed files are 
+       copied
+     - removed logging output to use script in cronjob in Dortmund
+
+
+
+ 2010/10/28 Thomas Bretz
+
+   * mjobs/MJCuts.cc:
+     - improved debug output in WriteResults
+
+   * mjobs/MJob.cc:
+     - imporved searching for an open file in WriteContainer
+
+
+
+ 2010/10/28 Daniela Dorner
+
+   * datacenter/scripts/writemcsequencefile:
+     - bug fix (every run was listed several times)
+
+
+
+ 2010/10/27 Daniela Dorner
+
+   * datacenter/scripts/jobmanager:
+     - imlemented new algorithm / rewritten 
+     - queries status of queue less often
+     - one can select algorithm to determine number of jobs to be 
+       submitted
+     - one can submit more than one job at the same time
+     - no waiting time between scripts, but only between loops number of 
+       jobs
+     - number of jobs for steps is not given absolute anymore, but in a
+       ratio
+     - maximum number of jobs for one step can be given
+
+   * datacenter/scripts/setup.phido.fact.mc, 
+     datacenter/scripts/setup.wue.fact.mc:
+     - adapted variables for settings of jobmanager to implement the new
+       algorithm
+
+   * datacenter/scripts/runstar_mc, datacenter/scripts/runcallisto_mc
+     datacenter/scripts/runceres, datacenter/scripts/runcorsika, 
+     datacenter/scripts/sourcefile:
+     - implemented usage of lock in db instead of function checklock 
+       which uses lock-file
+     - in sourcefile: adapted function setstatus to take care of locking
+
+   * datacenter/scripts/run.condor:
+     - adapted to allow submission of several jobs with one submit
+
+   * datacenter/scripts/copyoutput:
+     - included output of info if nothing has to be copied
+
+
+
+ 2010/10/19 Daniela Dorner
+
+   * datacenter/scripts/insertmc:
+     - added reminder to start writemcsequencefile
+
+   * datacenter/scripts/writemcsequencefile:
+     - added check if there are runs in the DB
+
+
+
+ 2010/10/18 Daniela Dorner
+
+   * datacenter/db/menu.php, datacenter/db/mcdefs.php:
+     - added number of events to include the difference between number 
+       of showers and number of events introduced by implementing
+       fNumReUseShowers
+
+   * datacenter/db/include.php, datacenter/db/mcinfo.php:
+     - added 'done and avail' to status pull-down
+     - added 'done and avail' to status group-by
+
+   * datacenter/scripts/insertmc:
+     - added fAvailable
+     - new values for numfile with CSCAT 20
+
+   * datacenter/scripts/jobmanager:
+     - updated setting for pbs
+
+   * datacenter/scripts/setup.phido.fact.mc:
+     - added setup for copying
+
+   * datacenter/scripts/copyoutput:
+     - added (script to copy output from one site to the main site, 
+       currently working and used for copying corsika files from 
+       Dortmund to Wuerzburg
+
+
+
+ 2010/10/06 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - updated status queries to implemented new DB columns fAvailable 
+       and fProcessingSiteKEY for the status tables to allow for storing
+       the information where the process is/was running and whether it 
+       is already available in the main data center, i.e. whether it has
+       been already copied 
+       This ensures that the next step is only started when the job is
+       done AND the file is available
+
+   * datacenter/scripts/setup.wue.fact.mc, 
+     datacenter/scripts/setup.phido.fact.mc:
+     - implemented variables for the processing and main data center 
+       site
+
+
+
+ 2010/10/05 Daniela Dorner
+
+   * datacenter/scripts/jobmanager:
+     - implemented pbs as third queueing system: implemented variable
+       $SOURCEFILEPATH as pbs copies script locally; implemented 
+       walltime and mem
+
+   * datacenter/scripts/setup.phido.fact.mc:
+     - added (setup file for cluster in Dortmund); includes array for 
+       walltime and mem
+
+   * datacenter/scripts/runcorsika, datacenter/scripts/sourcefile:
+     - implemented variable $SOURCEFILEPATH
+
+   * datacenter/db/menu.php, datacenter/db/mcdefs.php, 
+     datacenter/scripts/runcorsika, datacenter/scripts/insertmc:
+     - implemented fNumReUseShowers (parameter how often a shower is 
+       reused in Corsika)
+
+
+
+ 2010/09/30 Thomas Bretz
+
+   * msimreflector/MMirrorSquare.[h,cc]:
+     - implemented WriteM
+
+   * mcorsika/MCorsikaEvtHeader.cc, mcorsika/MCorsikaFormat.[h,cc],
+     mcorsika/MCorsikaRunHeader.cc:
+     - fixed a problem with reading the RUNE section in corsikas 
+       raw format
+
+   * readcorsika.cc:
+     - speed up reading by ot printing the single photons if debug
+       level less than 3
+
+   * msim/MPhotonEvent.cc:
+     - don't loop over all (mostly empty) slots in Print()
+
+   * msimcamera/MSimRandomPhotons.[h,cc]:
+     - changed again the checks to also allow pedestal and calibration
+       runs to be produced without having a MCorsikaRunHeader available
+
+
+
+ 2010/09/29 Thomas Bretz
+
+   * msimreflector/MMirrorHex.[h,cc]:
+     - implemented WriteM
+     - implemented new class MMirrorHex90
+
+   * msimreflector/SimReflectorLinkDef.h:
+     - added MMirrorHex90
+
+   * msimreflector/MMirrorDisk.[h,cc]:
+     - implemented WriteM
+
+   * msimreflector/MReflector.[h,cc]:
+     - added function to write a file with a reflector definition
+
+   * msimreflector/MMirror.h:
+     - added virtual WriteM
+     - added several Getter for Z, Nx, Ny, Nz and Shape
+
+
+
+ 2010/09/28 Thomas Bretz
+
+   * mcorsika/MCorsikaFormat.[h,cc]:
+     - added Read function to allow MCorsikaRead to read
+       object 1203
+     - added Rewind function to allow MCorsikaRead to jump back
+       in file
+     - added a lot of debug output
+     - make GetNextEvent read one telescope data from one array after
+       the other
+
+   * mcorsika/MCorsikaEvtHeader.h:
+     - added AddXY which allows MCorsikaRead to add the telescope 
+       position to the showers impact parameter
+
+   * mcorsika/MCorsikaRead.[h,cc]:
+     - commented out obsolete use of fIn
+     - added reading of telescope positions (object 1201) in 
+       eventio format
+     - added number of telescopes to the calculation of the 
+       total number of events
+     - added a working ReadEvent for eventio format
+     - added ReadEnv to be able to set the requested telscope index
+     - added new data members to hold the telescope positions   
+     - removed obsolete OpenStream
+     - added member function to set telescope index
+
+   * msim/MHPhotonEvent.cc:
+     - changed the number of bins to an odd value to get a bin at zero 
+       for the 2D histograms
+
+
+
+ 2010/09/24 Thomas Bretz
+
+   * mcorsika/MCorsikaEvtHeader.cc:
+     - store impact parameters persistent for further use (because in
+       eventio format the header is not repeated this is needed)
+
+   * mcorsika/MCorsikaFormat.[h,cc]:
+     - adapted to be able to read all telescopes and all reused shower
+       events in eventio
+     - a lot of cosmetics
+     - many more comments
+     - PRELIMINARY
+
+   * mcorsika/MCorsikaRead.[h,cc]:
+     - implemented variable for selection of the telescope in eventio format
+     - implemented eventio format (PRELIMINARY)
+
+   * msim/MPhotonData.[h,cc], msim/MPhotonEvent.[h,cc]:
+     - implemented function to calculate mean event time
+     - implemented function to simulate the wavelength (lambda^-2)
+     - implemented function to shift all photons by a certain xy
+     - adapted ReadCorsikaEvt to changes in MCorsikaFormat
+
+
+
+ 2010/09/24 Daniela Dorner
+
+   * datacenter/scripts/insertmc:
+     - fixed typo
+
+
+
+ 2010/09/22 Thomas Bretz
+
+   * mjobs/MJSimulation.cc:
+     - slight improvement of debug output
+     - call SetAllowEmpty for the three ContEmpty filters
+     - changed binning of camera histograms
+
+   * msimcamera/MSimRandomPhotons.cc:
+     - improved output in case of failure
+
+   * readcorsika.cc:
+     - added RunHeaders
+     - fixed usage-info
+
+   * mbase/MContinue.cc:
+     - no need to call MTask::GetFilter(), GetFilter() is enough
+
+   * mfbase/MF.cc:
+     - accept = as a conditional sign
+     - make sure the return code of the evaluated filter is corectly returned
+
+   * msim/MHPhotonEvent.cc:
+     - implemented types 6-8
+
+   * mcorsika/MCorsikaEvtHeader.[h,cc]:
+     - added fNumReuse
+     - added member functions to increase and reset the number of reusages
+     - increased class version number accordingly
+
+   * mcorsika/MCorsikaRead.[h,cc]:
+     - count the number of showers (events) times its reusage
+       for fNumTotalEvents
+     - adapted ReadEvent to re-usage of showers (still needs to be tested for
+       EventIO)
+     - Fixed return type (should be Int_t) of ReadEvent
+     - take the number of reusages in PostProcess into account
+
+   * mcorsika/MCorsikaRunHeader.[h,cc]:
+     - added total number of reusages fNumReuse
+     - increased class version number accordingly
+
+   * mmc/MMcEvt.hxx:
+     - added setter for the reuse counter
+
+   * msim/MPhotonData.[h,cc]:
+     - removed fNumPhotons (we allow 1-photon bunches only anyway and MMCS
+       doesn't even distribute this number)
+     - increased class version number accordingly
+
+   * msim/MSimMMCS.cc:
+     - correctly propagate the number of events (number of showers times reusage)
+     - propagate counter for reusage to MMcEvt
+
+   * msim/MPhotonEvent.[h,cc]:
+     - added functions to calculate mean x and mean y
+     - propagate re-usage counter through ReadEvent
+
+   * mcorsika/MCorsikaFormat.[h,cc]:
+     - a few clean-ups to the code
+     - added standard file header
+     - a few minor simplifications
+     - replaced local logging stream with gLog
+     - added some empty comments
+
+
+
+ 2010/09/21 Thomas Bretz
+
+   * mjobs/MJSimulation.cc:
+     - correctly propagated run-number to the file-name
+     - fixed a problem with the tab-title in the ps-files
+     - fixed the histogram size for the camera (should be 5 instead
+       of 3,  I hope)
+     - fixed the tab-title for the MedDev tab
+     - do not write image-files in dev-null mode
+
+
+
+ 2010/09/14 Daniela Dorner
+
+   * datacenter/scripts/runcorsika:
+     - removed STEPFC from inputcard as anyhow default of 1 was used 
+       instead of 0.1 
+
+
+
+ 2010/09/06 Thomas Bretz
+
+   * msimreflector/MSimRays.cc:
+     - included TMath for newer root versions
+
+
+
+ 2010/09/03 Daniela Dorner
+
+   * datacenter/scripts/insertmc:
+     - added new standard setup runs
+
+   * datacenter/scripts/runceres:
+     - fixed queries for change from file based to run based processing
+
+   * datacenter/scripts/runcallisto_mc:
+     - changed setup path: implemented ceres setup, as different 
+       callisto.rc are needed for different ceres setup
+
+
+
+ 2010/08/31 Thomas Bretz
+
+   * msimcamera/MSimRandomPhotons.[h,cc]:
+     - improved the range checks. All ranges are now aligned on the
+       range of simulated wavlengths
+
+
+
+ 2010/08/30 Daniela Dorner
+
+   * datacenter/db/mcdefs.php:
+     - adapted joins for processing of ceres on run basis
+
+   * datacenter/scripts/insertmc:
+     - bugfix for insert of rows for new ceres key(s)
+
+
+
+ 2010/08/30 Thomas Bretz
+
+   * mhist/MHCamera.cc:
+     - added options to display contents as int and float
+
+   * mgeom/MGeomCamFACT.cc:
+     - changed default distance from 4.8887 to 4.90
+
+   * mbase/MLut.cc:
+     - added possibility to have comment (ignored) lines
+
+   * msim/MHPhotonEvent.cc:
+     - fixed Type==5
+
+   * msimreflector/MSimRays.[h,cc]:
+     - added
+
+   * msimreflector/SimReflectorLinkDef.h
+     - added MSimRays
+
+   * msimreflector/Makefile
+     - added MSimRays
+
+
+
+ 2010/08/27 Daniela Dorner
+
+   * datacenter/scripts/insertmc:
+     - updated some default values
+
+   * datacenter/scripts/runceres, datacenter/scripts/insertmc, 
+     resources/step_fact.rc:
+     - changed processing of ceres from file- to run-basis
+
+
+
+ 2010/08/26 Daniela Dorner
+
+   * datacenter/db/mcinfo.php:
+     - implemented status 'crashed' also for display of list of runs
+
+   * datacenter/db/mcdefs.php, datacenter/db/menu.php:
+     - implemented CeresSetupKEY for mcinfo.php
+
+
+
+ 2010/08/26 Reiner Rohlfs
+
+   * mcorsika/MCorsikaFormat.[h,cc]
+     - fixed a problem in comparing fRunePos with position 0
+
+
+
+ 2010/08/25 Thomas Bretz
+
+   * mjtrain/MJTrainCuts.cc:
+     - fixed the SetDrawOption for the 2D histogram
+
+
+
+ 2010/08/24 Thomas Bretz
+
+   * mjtrain/MJTrainCuts.cc:
+     - removed the SetDrawOption from the 1D histogram
+
+
+
+ 2010/08/24 Reiner Rohlfs
+
+   * mcorsika/MCorsikaFormat.[h,cc]
+     - in method MCorsikaFormatEventIO::SeekEvtEnd() the RUNE block
+       is first searched at the end of the file. It it is not found
+       the whole file is scanned for the RUNE block. Once it is 
+       found it can be accessed directly at the next call of this
+       function.
+
+
+
+ 2010/08/20 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - bugfix in query for influenced steps
+
+
+
+ 2010/08/19 Thomas Bretz
+
+   * mjobs/MSequence.cc:
+     - fixed treatment of file number 0 in InflateFileName and
+       PrintRuns
+
+
+
+ 2010/08/17 Thomas Bretz
+
+   * resmc/fact-trigger-sum.txt, resmc/fact-trigger-all.txt, 
+     macros/fact/fact_trigger.C:
+     - added
+
+
+
+ 2010/08/17 Daniela Dorner
+
+   * datacenter/scripts/insertmc:
+     - added (script to insert mc runs and sequences to the FACT MC DB)
+
+
+
+ 2010/08/16 Thomas Bretz
+
+   * mgeom/GeomLinkDef.h, mgeom/Makefile:
+     - added MGeomCamFACT
+
+   * mgeom/MGeomCamFACT.[h,cc]:
+     - added
+
+   * mgeom/MGeomCamDwarf.[h,cc], mgeom/MGeomPix.[h,cc]:
+     - moved CalcXY to MGeomPix
+     - removed obsolete includes
+
+   * mgeom/MGeomCamFact.cc:
+     - removed obsolete includes
+
+   * mranforest/MRanForestCalc.h:
+     - added new function Train which either calls TrainRegression
+       or TrainSingleRF
+
+   * mranforest/MHRanForestGini.cc:
+     - improved display
+
+   * mfileio/MReadMarsFile.cc:
+     - evaluate return code of fRun->Process()
+     - print return code in case of failure
+
+   * mjoptim/MJOptimizeBase.[h,cc]:
+     - improved existing comments
+     - added a full class description
+     - print a warning if TRandom is used a random number generator
+
+   * mtools/MTFillMatrix.cc:
+     - improved handling of negative number of events
+
+   * mjtrain/MJTrainSeparation.cc:
+     - added names to test- and train-dataset for storage
+
+   * mjtrain/TrainLinkDef.h, mjtrain/Makefile:
+     - added MJTrainCuts
+
+   * macros/train/traincuts.C:
+     - added
+
+   * mpointing/MPointingDevCalc.cc:
+     - added a comment about the last lut update
+
+
+
+ 2010/08/13 Thomas Bretz
+
+   * mimage/MHHillasExt.[h,cc]:
+     - added new histograms to display new variables
+     - increased class version number
+
+   * mimage/MHillasExt.cc:
+     - fixed claculation of the weighted time spreads
+     - fixed a bug in the calculation of the third moments!
+
+   * mhist/MHHadronness.cc:
+     - fixed min/max of the intgral histogram
+
+   * mfbase/MFEventSelector.cc:
+     - if the number of events to be selected is negative select all events
+
+   * mhbase/MHn.[h,cc]:
+     - fixed the complex display for five histograms
+
+   * mhbase/MHn.[h,cc], mhbase/MH3.[h,cc]:
+     - implemented a TProfile3D
+     - implemented an option to skip reset of the histograms in a new
+       eventloop
+
+   * mhbase/MH3.[h,cc]:
+     - moved the addition weight to a new data meber fWeight
+     - increased class version number
+
+
+
+ 2010/08/13 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - implemented faster queries for the dependencies of the steps
+     - simplified code
+     - introduced new level for printprocesslog: DEBUG
+
+   * resources/steps_fact.rc:
+     - adapted to change in queries in sourcefile
+
+
+
+ 2010/08/12 Thomas Bretz
+
+   * mimage/MHillasExt.[h,cc]:
+     - added Getter for fSlope*
+     - added new data members to Print() output
+     - adapted Set() member function
+     - fixed code for calculating weighted spreads
+     - added new data members to Clear function
+
+   * mimage/MHHillas.cc, mimage/MHHillasExt.cc, mimage/MHNewImagePar.cc,
+     mimage/MHVsSize.cc, mimage/MHHillasSrc.cc, mimage/MHImagePar.cc,
+     mhcalib/MHGausEvents.cc, mhflux/MHThetaSq.cc,  mhflux/MHAlpha.cc,
+     mhflux/MHFalseSource.cc, mhflux/MHEffectiveOnTime.cc,
+     mhflux/MHCollectionArea.cc, mhflux/MHThetaSqN.cc, mhflux/MHDisp.cc,
+     mhflux/MHThreshold.cc, mhflux/MHEnergyEst.cc, mjtrain/MJTrainDisp.cc,
+     mtools/MHSimulatedAnnealing.cc, mmuon/MHSingleMuon.cc,
+     mmuon/MHMuonPar.cc, mpointing/MHSrcPosCam.cc, 
+     mpedestal/MHPedestalCor.cc, mhist/MHCamEventRot.cc, 
+     mhist/MHStarMap.cc, mjobs/MJSpectrum.cc, mbadpixels/MHBadPixels.cc,
+     mfbase/MFEventSelector2.cc, mhbase/MBinning.cc, mhbase/MH.[h,cc], 
+     mhbase/MH3.cc, mhbase/MHMatrix.cc, msim/MHPhotonEvent.cc:
+     - changes MH::SetBinning and similar functions to take references 
+       instead of pointers
+     - for the time being wrappers are kept not to break macros
+
+
+
+ 2010/08/11 Thomas Bretz
+
+   * mhbase/MH3.[h,cc]:
+     - added another type to be able to setup a standard profile and
+       one which display the spread as error
+     - improved/fixed error calculation/display
+
+   * mimage/MHillasExt.[h,cc]:
+     - added new data members fTimeSpread and fTimeSpreadWeighted
+     - added new data members fSlopeSpread and fSlopeSpreadWeighted
+     - implemented code to calculate the time spreads and slope spreads
+     - increased class version id by 1
+
+   * mjtrain/TrainLinkDef.h:
+     - added MJTrainImpact
+
+   * mjtrain/MJTrainImpact.[h,cc]:
+     - added
+
+   * mjtrain/MJTrainEnergy.h:
+     - added SetTrainExpSize member function
+
+   * mjtrain/MJTrainDisp.cc:
+     - made the display of the cut-lines a bit more flexible
+     - slightly changed the meaning of the plots
+
+
+
+ 2010/08/10 Thomas Bretz
+
+   * msim/MPhotonData.cc:
+     - fixed two warnings in FillEventIO (implicit conversion
+       from float to int)
+
+   * mhbase/MHn.[h,cc]:
+     - added SetConversion to allow for setting a conversion function
+
+   * mhbase/MH3.[h,cc]:
+     - added conversion function for displaying the histogram
+     - added new data member fConversion
+     - added new member functions Convert and SetConversion
+     - implemented conversion before displaying
+
+   * mjtrain/MJTrainEnergy.cc:
+     - display resolution directly (sqrt)
+     - changed default binning
+     - don't use build in conversion from mm to degree but 
+       MGeomCam.fConvMm2Deg instead.
+
+   * Makefile.rules:
+     - replaced cvs by svn in diff
+
+   * mjtrain/MJTrainDisp.cc:
+     - don't use build in conversion from mm to degree but 
+       MGeomCam.fConvMm2Deg instead.
+
+
+
+ 2010/08/06 Thomas Bretz
+
+   * msimcamera/MSimCamera.[h,cc]:
+     - added the possibility to set an overall baseline, baseline-noise
+       and gain.
+
+   * ceres.rc:
+     - added entries for the new values
+
+
+
+ 2010/07/28 Daniela Dorner
+
+   * datacenter/db/menu.php:
+     - updated initial parameter selection for mcinfo.php
+     - changed table for GetMin/Max to CeresInfo
+
+   * datacenter/db/mcinfo.php:
+     - bugfix for removing WHERE or AND at end of queries
+     - added fStopTime to status-column in case of failure
+     - bugfix for correct joins in case of group-by
+
+   * datacenter/db/mcdefs.php:
+     - updated runtime of ceres
+     - updated joins for status tables
+
+   * datacenter/scripts/insertmc:
+     - added (script to add runs to the database)
+
+   * datacenter/scripts/runcorsika:
+     - added check if 'END OF FILE' is contained in logfile
+     - added check if file number > 999 and change filename if it is
+
+   * datacenter/scripts/setup.wue.fact.mc:
+     - removed cprun
+     - added callisto and star in scripts-array
+
+   * datacenter/scripts/sourcefile:
+     - removed variables for fProgramId
+
+   * resources/steps_fact.rc:
+     - added missing needs
+
+
+
+ 2010/07/23 Reiner Rohlfs
+
+   * mcorsika/MCorsikaFormat.[h,cc]
+     - new files
+       All the differences between EventIo files and coriska files
+       are implemented in these files.
+
+   * mcoriska/MCorsikaRead.[h,cc]
+     - the file handler fIn is replaced by the MCorsikaFormat class.
+     - every access to the input file is replaces by calling 
+       methods of MCorsikaFormat.
+
+   * mcoriska/MCorsikaRunHeader.[h,cc]
+     - the file handler fIn is replaced by the MCorsikaFormat class.
+     - every access to the input file is replaces by calling 
+       methods of MCorsikaFormat.
+
+   * mcoriska/MCorsikaEvtHeader.[h,cc]
+     - the file handler fIn is replaced by the MCorsikaFormat class.
+     - every access to the input file is replaces by calling 
+       methods of MCorsikaFormat.
+
+   * msim/MPhotonEvent.cc
+     - method ReadCorsikaEvt distinguish between Corsika and EventIo
+       input files and calls either FillEventIO() or FillCorsika().
+
+   * msim/MPhotonData.[h,cc]
+     - new method: FillEventIO, which is similar as FillCorsika
+
+
+ 2010/07/09 Thomas Bretz
+
+   * mpointing/MSrcPosCam.[h,cc]:
+     - now the particle position is stored in any case in the headers
+       so in case we have a view cone we must keep the position fixed
+     - added the fix for the MC monte carlos (for them X needs to
+       change its sign due to a bug in the reflector program)
+
+   * mars.rc, star.rc:
+     - changed time contraint in cleaning from aboslute values
+       to relative values (units now ns/deg)
+
+   * mimage/MImgCleanStd.cc:
+     - changed time contraint in cleaning from aboslute values
+       to relative values (units now ns/deg)
+
+
+
+ 2010/07/07 Daniela Dorner
+
+   * datacenter/scripts/runceres:
+     - fixed typo
+
+
+
+ 2010/07/06 Daniela Dorner
+
+   * datacenter/scripts/runstar_mc:
+     - fixed typo
+     - added inpath to command line
+
+
+
+ 2010/07/05 Daniela Dorner
+
+   * datacenter/scripts/runceres:
+     - added path for C and P run (was not the same like for D run)
+
+   * datacenter/scripts/sourcefile:
+     - fixed joins in subquerypart()
+
+   * datacenter/scripts/runcallisto_mc:
+     - added inpath to command line
+
+   * datacenter/db/mcinfo.php:
+     - removed FailMenu
+     - fixed bug (group by did not work in case statusvalue was not 
+       selected)
+
+   * datacenter/db/mcdefs.php:
+     - removed FailMenu columns
+
+
+
+ 2010/07/05 Thomas Bretz
+
+   * mraw/MRawRunHeader.h:
+     - added missing SetFileNumber
+
+   * mjobs/MSequence.cc:
+     - added the missing file number to teh MC file names
+
+   * msimcamera/MSimCalibrationSignal.h:
+     - changed virtual file name from 000000 to 000001 to force file
+       number to be 1.
+
+   * mjobs/MJSimulation.[h,cc]:
+     - added run-number to ceres.root filename
+
+
+
+ 2010/07/02 Daniela Dorner
+
+   * datacenter/scripts/runcorsika:
+     - removed $com
+     - updated logging
+
+   * datacenter/scripts/runceres:
+     - fixed path
+     - added error handling
+
+   * resources/steps_fact.rc:
+     - update joins to new scheme to include further steps in the chain
+
+   * datacenter/scripts/sourcefile:
+     - adapted queries to new scheme of joins
+
+   * datacenter/scripts/runstar_mc:
+     - added (script to run star for mc) 
+
+
+
+ 2010/07/02 Daniela Dorner, Christian Farnier
+
+   * datacenter/scripts/runcallisto_mc:
+     - added (script to callibrate mc) 
+
+
+
+ 2010/06/30 Daniela Dorner
+
+   * datacenter/db/mcinfo.php:
+     - added output to step column in case job is running
+     - fixed typo
+
+   * datacenter/scripts/runcorsika:
+     - small bugfix (new version of 'cut' gives error for '-c 0-4')
+
+   * datacenter/scripts/runceres:
+     - added (script to run telescope simulation of file basis)
+
+   * datacenter/scripts/setup.wue.magic.data,
+     datacenter/scripts/setup.wue.magic.mc,
+     datacenter/scripts/setup.wue.fact.mc:
+     - added condorpath
+
+   * datacenter/scripts/jobmanager,
+     datacenter/scripts/scriptlauncher:
+     - implemented condorpath
+
+   * datacenter/scripts/sourcefile:
+     - changed log and error file name for jobmanager
+
+   * resources/steps_fact.rc:
+     - fixed typo
+
+
+
+ 2010/06/29 Daniela Dorner
+
+   * datacenter/db/mcinfo.php:
+     - added duration to step column in case of 'failed' and 'done'
+
+
+
+ 2010/06/28 Daniela Dorner
+
+   * datacenter/db/include.php:
+     - adapted status query for new db layout
+
+   * datacenter/db/menu.php:
+     - added and exchanged menu points and init elements for the new
+       layout of the FACT mc db
+     - bugfix that menu items can be switched off
+
+   * datacenter/db/mcinfo.php:
+     - adapted the queries for the new layout of the FACT mc db 
+       (different table names, structures and content)
+     - adapted query for the status group by
+
+   * datacenter/db/mcdefs.php:
+     - adapted the arrays for the new layout of the FACT mc db 
+
+
+
+ 2010/06/28 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - Status displays where stored as MStatusArray instead of
+       MStatusDisplay
+     - Read now also can read other StatusDisplays if a key is found in
+       the file
+
+
+
+ 2010/06/25 Thomas Bretz
+
+   * mjobs/MJSimulation.[h,cc]:
+     - added data member fRunNumber
+     - changed the rules to create the output file names
+     - set default run-numbers for different run-ytpes
+     - apply run-number 
+     - added IntendedPulsePosition to output
+
+   * mraw/MRawRunHeader.h:
+     - added SetFileNumber member function
+
+
+
+ 2010/06/24 Thomas Bretz
+
+   * mgeom/MGeomCam.h:
+     - call constructor of base class in copy-constructor
+
+   * mhbase/MH.h:
+     - remove argument name where obsolete
+
+   * mjobs/MJSimulation.cc:
+     - fixed some axis labels
+
+   * msimreflector/MMirrorDisk.cc:
+     - changed interpretation from file from radius to diameter
+
+   * ceres.cc:
+     - added option --run-number
+
+   * showplot.cc:
+     - set default palette to pretty palette
+
+   * mcorsika/MCorsikaRunHeader.h:
+     - added getter for ViewConeInnerAngle
+
+   * mmc/MMcCorsikaRunHeader.h:
+     - added HasViewCone
+     - added SetViewCone
+
+   * mmc/MMcEvt.[hxx,cxx], mmc/MMcEvtBasic.[h,cc]:
+     - moved fPhi and fTheta from MMcEvt to MMcEvtBasic
+     - increased class version number accordingly
+     - moved setter
+     - moved getter
+     - adapted Clean()
+     - adapter copy-constructor
+
+   * mpointing/MPointingDevCalc.cc:
+     - added some comments
+
+   * msim/MSimMMCS.cc:
+     - transfer view cone data
+     - set run-info (run/file-number) according to new scheme
+     - always set MMcEvt::fPhi/fTheta to particle direction
+
+
+
+ 2010/06/24 Daniela Dorner
+
+   * datacenter/scripts/sourcefile, resources/steps_fact.rc:
+     - bugfixes: changed joins to get correct queries for all cases
+
+   * datacenter/scripts/setup.wue.fact.mc:
+     - changed path for setup files
+     - added runceres to jobmanager settings
+
+
+
+ 2010/06/22 Daniela Dorner
+
+   * datacenter/scripts/writemcsequencefile:
+     - improved logging
+
+   * datacenter/scripts/sourcefile:
+     - adapted greps in rc-files to grep only lines which are no 
+       comments
+
+
+
+ 2010/06/17 Daniela Dorner
+
+   * resources/steps_fact.rc:
+     - removed step CPRun
+     - split 'Joins' to 'Joins' and 'SpecialJoins' depending on 
+       whether the join is with a different table
+
+   * datacenter/scripts/sourcefile:
+     - bugfix in query
+     - included new type of join from steps.rc
+     - added comments
+
+
+
+ 2010/06/16 Daniela Dorner
+
+   * resources/steps_fact.rc:
+     - removed step CPRun
+     - added step SequenceFile
+
+   * datacenter/scripts/setup.wue.fact.mc:
+     - added path for mc sequences
+
+   * datacenter/scripts/writemcsequencefile:
+     - added (script to write mc sequencefiles)
+
+
+
+ 2010/06/15 Daniela Dorner
+
+   * resources/steps_fact.rc:
+     - added (file containing the dependencies for the steps of the 
+       automatic production of MC for FACT)
+
+
+
+ 2010/06/14 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - bugfix in query
+
+   * datacenter/scripts/runcorsika:
+     - added output of command to processlog
+
+   * datacenter/scripts/setup.wue.fact.mc:
+     - changed setup to be used by user montecarlo to reproduce some 
+       corsikas
+
+
+
+ 2010/06/11 Daniela Dorner
+
+   * datacenter/scripts/sourcefile:
+     - changed functions and queries to new db layout
+     - added functions to get values from steps.rc
+     - new function for part of query which is identical for the 
+       functions getstatus() and gettodo()
+     - removed $reset (was only needed for MerppUpdate)
+     - improved and added comments
+
+   * datacenter/scripts/jobmanager:
+     - implemented changes for new db layout
+     - fix in function nextscript(): wrong variable was used
+
+   * datacenter/scripts/runcorsika:
+     - implemented changes for new db layout
+     - merged uncommitted changes of Thomas Bretz 
+     - Observatory values and atmosphere now read from DB
+     - implemented new seeds
+     - removed $reused
+     - wavelength range now read from DB
+
+   * datacenter/scripts/setup.wue.fact.mc:
+     - added (setup for fact mc production)
+
+
+
+ 2010/06/11 Stefan Ruegamer
+
+   * mjobs/MJSpectrum.cc
+     - corrected the flux of the published MAGIC spectrum
+
+
+
+ 2010/06/03 Thomas Bretz
+
+   * mranforest/MRanForestCalc.cc:
+     - added stdlib.h to make Dominik happy ;)
+
+
+
+ 2010/05/05 Thomas Bretz
+
+   * mastro/MAstro.cc:
+     - fixed AngularDistance (called a non existing function and
+       the compiler didn't complain)
+
+   * mbase/MParContainer.[h,cc]:
+     - added static function Overwrites (previously in MTask)
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - allow writing a MStatusDisplay without writing a MStatusArray
+       (therefore added SeveAsPlainRoot)
+     - improved reading of files just containing canvases and objects
+
+   * mbase/MTask.[h,cc]:
+     - moved code from Overwrites to a static function in MParContainer
+
+   * msimcamera/MSimCalibrationSignal.cc:
+     - changed distribution of signal from Gauss to Poissonian
+
+   * showplot.cc:
+     - removed nonsense "-q" option
+
+   * mbase/MStatusArray.[h,cc]:
+     - fixed/improved (once again) deleting of the array
+
+   * mbase/MStatusDisplay.cc:
+     - removed the MAstroCatalog workaround - is it still necessary?
+       (needs testing)
+     - added UpdateMemory every here and there to get the memory
+       consumption is more circumstances
+
+
+
+ 2010/04/22 Thomas Bretz
+
+   * showplot.cc:
+     - added --debug-mem option
+
+   * mbase/MParSpline.cc, mhbase/MH3.cc, mhbase/MHn.cc,
+     mhflux/MHAlpha.cc, mhist/MHCamEvent.cc:
+     - added missing call to the RecursiveRemove of the base class
+
+   * mfileio/MReadTree.cc:
+     - In the case Notify failed since about two years accidentaly
+       kTRUE instead of kERROR was returned
+
+   * mfileio/MWriteRootFile.cc:
+     - added some more debug output
+
+   * mhflux/MAlphaFitter.cc:
+     - Return if fit failed
+
+   * mhflux/MHPhi.cc:
+     - avoid inf and nan when producing histogram (the divisor could
+       have been zero in case of the inetgral of an empty histogram)
+
+
+
+ 2010/04/21 Thomas Bretz
+
+   * macros/rootlogon.C:
+     - a small fix which gets rid of the annoying error about an
+       unlocked mutex when starting the MStatusDisplay in the
+       interpreter. It makes sure that fGThreadFactory gets initialized
+       from the main thread.
+
+   * mbase/MStatusDisplay.cc:
+     - added a console output if TryLock fails
+     - the return value of TString::Index was misinterpreted
+
+   * mmuon/MHSingleMuon.cc:
+     - removed another reference to gMinuit
+
+   * msimcamera/MSimRandomPhotons.cc:
+     - re-did the output
+     - choose the other rate f2 instead of f1
+
+   * msimcamera/MSimTrigger.[h,cc]:
+     - keep the index of the trigger channel which finnaly issued
+       the trigger and propagate it to the event header
+
+   * mraw/MrawEvtHeader.h:
+     - implementd setter for fNumTriggerLvl1
+
+
+
+ 2010/04/20 Thomas Bretz
+
+   * mfileio/MReadTree.cc:
+     - no error was returned anymore when Notify() failed. Fixed.
+
+
+
+ 2010/04/19 Thomas Bretz
+
+   * mbase/MStatusArray.cc:
+     - added a workaround to prevent crashes in case of double
+       deleteion of the fHistogram in TGraphs
+
+   * mcorsika/MCorsikaEvtHeader.cc:
+     - replaced special characters by UTF8 characters
+
+   * mgeom/MGeom.[h,cc]:
+     - implemented function to return the distance squared
+
+   * mjobs/MJSimulation.cc:
+     - display degree symbol correctly in plots
+     - added artificial star-files to output
+     - for the moment the output of the reflector files is suppressed
+
+   * mmuon/MHSingleMuon.cc:
+     - catch if the fit failed
+     - replaced use of gMinuit by direct access to the function
+
+   * mpointing/MPointing.cc:
+     - replaced deg-symbol by UTF8 character
+
+   * mpointing/MPointingDevCalc.cc:
+     - added more information
+
+   * msignal/MSignalCam.[h,cc]:
+     - made the data members describing the image persistent.
+       they are not guranteed to have correct contents. Use
+       MNewImagePar instead.
+     - increased class version number accordingly
+
+   * msimreflector/MMirrorHex.h:
+     - added Getter for fD
+
+
+
+ 2010/04/13 Daniela Dorner
+
+   * datacenter/db/builddatasets.php:
+     - updated check for observation mode: allowed 'N/A', as there is 
+       else an error for old data
+
+
+
+ 2010/04/13 Thomas Bretz
+
+   * msim/MHPhotonEvent.cc:
+     - automatic binning for case 3
+     - new case 5
+
+   * msim/MHPhotonEvent.h:
+     - this can be a huge memory consumption and we don't need double
+       precision (range) accordingly changed all TH*D to TH*F.
+       consequently increased class version number
+
+
+
+ 2010/03/30 Thomas Bretz
+
+   * Makefile.conf.general:
+     - moved ARCHDEFS from DEFINES to CXXFLAGS otherwise it might get
+       ignored
+
+   * mbase/MQuaternion.h:
+     - added member-function to normalize vector part of quaternion
+
+   * mbase/MTime.cc:
+     - issue an error if __LINUX__ is not set
+
+   * mjobs/MJSimulation.cc:
+     - set name of reflector explicitly to "Reflector"
+
+   * msimreflector/MMirror.h:
+     - added member function to set z position (for optimization purpose)
+     - added SimPSF(TVector3&)
+
+   * msimreflector/MSimReflector.[h,cc]:
+     - added name of reflector as data member 
+
+   * melectronics/MAvalanchePhotoDiode.cc:
+     - scale the crosstalk probability as the height of the emitted
+       signal with the recovery time.
+
+   * mhflux/MHEnergyEst.cc:
+     - added a workaround to get rid of some root-warnings
+
+   * mjtrain/MJTrainEnergy.cc:
+     - improved axis labels
+
+   * mpointing/MPointingDevCalc.cc:
+     - added some more comments
+
+   * msimreflector/MMirror.[h,cc]:
+     - added fShape to allow for parabolic mirrors
+
+   * msimreflector/MReflector.cc:
+     - implemented the option of parabolic mirrors into the
+       reflector defintion file
+
+   * msimreflector/MSimReflector.[h,cc]:
+     - implemented (and fixed) the calculation of the reflection at
+       parabolic surfaces
+     - implemented the possibility to switch off the early check for
+       "photon can hit the camera" (fDetectorMargin<0)
+     - added setter for fDetectorMargin
+
+
+
+
+ 2010/03/01 Stefan Ruegamer
+
+   * resources/hilocalib.rc:
+     - added df factors for p23-25, using the same as for p22. Sequences
+       are not running with df in these periods, therefore the correct
+       factors cannot be determined, and it doesn't matter anyway.
+
+   * datacenter/read_lapalma-tapes:
+     - added automationsetup before movingrawfiles
+
+
+
+ 2010/02/23 Thomas Bretz
+
+   * mbase/MAGIC.cc:
+     - projections are supposed to work again in root 5.26 
+       (not tested yet)
+
+   * mbase/MGMap.cc, mbase/MObjLookup.cc:
+     - key and val are Long64 in newer root versions
+
+   * mdata/MDataPhrase.cc:
+     - need inclusion of TFormulaPrimitive in root 5.26
+
+   * mhflux/MMcSpectrumWeight.cc:
+     - root 5.26 has a different calling convention for TH1::Intgeral
+
+   * mjobs/MJob.cc:
+     - added a suggested parenthesis
+
+   * mjtrain/MJTrainDisp.cc:
+     - cast the MH3 histogram correctly to a TH2
+
+
+
+ 2010/02/22 Daniela Dorner
+
+   * datacenter/db/menu.php:
+     - added ObsLevel and download link column for cta pages
+
+   * datacenter/db/ctadefs.php:
+     - added observation level
+
+   * datacenter/db/ctamcinfo.php:
+     - added column with download link for the files
+
+   * datacenter/db/builddatasets.php, datacenter/db/ctamcinfo.php, 
+     datacenter/db/culminating.php, datacenter/db/datacheck.php, 
+     datacenter/db/datasetinfo-aio.php, datacenter/db/ganymed.php, 
+     datacenter/db/include.php, datacenter/db/mcinfo.php, 
+     datacenter/db/opticaldata.php, datacenter/db/printtable.php, 
+     datacenter/db/queryrbk.php, datacenter/db/runinfo-aio.php, 
+     datacenter/db/sequence.php, datacenter/db/sequinfo-aio.php, 
+     datacenter/db/sources.php, datacenter/db/statussbs.php:
+     - bugfix for get.txt
+
+   * datacenter/db/datasetinfo-aio.php:
+     - bugfix calling PrintPage()
+
+
+
+ 2010/02/01 Daniela Dorner
+
+   * datacenter/scripts/fillmcdb:
+     - added observation level
+
+   * datacenter/scripts/sourcefile:
+     - added comment concerning $0 problem
+     - added 'ERROR' in processlog message of makedir
+
+
+
+ 2010/02/04 Stefan Ruegamer
+
+   * mraw/MRawRunHeader.cc
+     - changed GetTypeID()!=fTelescopeNumber*10U+5U to GetTypeID()!=5U
+       so that the new 5xxxxxx sequences can be processed
+     - adapted error message
+     - inserted Domino calibration run
+
+   * mraw/MRawRunHeader.cc
+     - inserted Domino calibration run
+
+
+
+ 2010/02/01 Daniela Dorner
+
+   * datacenter/scripts/runsimtel
+     - fixes typo
+     - replaced path in disk-check by variable
+
+
+
+ 2010/01/15 Stefan Ruegamer
+
+   * datacenter/scripts/dowebplots, jobmanager
+     - if-condition if [ "$numproc" = "" ] now correctly checks for "0"
+
+   * datacenter/scripts/scriptlauncher
+     - added automationsetup variable in condor command
+
+   * datacenter/macros/buildsequenceentries.C
+     - where necessary changed Int to Long to account for the high value
+       of the stereo runs
+
+   * resources/sequences.rc
+     - added two transition conditions for the calibration scripts
+       10Led_UV_PEDANDCAL_1kHz and 10LED_UV
Index: branches/Mars_McMismatchStudy/MIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/MIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/MIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/MLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/MLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/MLinkDef.h	(revision 17960)
@@ -0,0 +1,70 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+// ==========================================================
+
+// I/O
+#pragma link C++ namespace Huffman+;
+#pragma link C++ class Checksum+;
+#pragma link C++ namespace FITS+;
+#pragma link C++ struct FITS::Compression+;
+#pragma link C++ enum FITS::CompressionProcess_t+;
+#pragma link C++ enum FITS::RowOrdering_t+;
+#pragma link C++ class izstream+;
+#pragma link C++ class fits+;
+#pragma link C++ class ofits+;
+#pragma link C++ class zfits+;
+#pragma link C++ class zofits+;
+#pragma link C++ class factfits+;
+#pragma link C++ class factofits+;
+
+// mcore
+#pragma link C++ class DrsCalibrateTime+;
+#pragma link C++ class PixelMap+;
+#pragma link C++ class PixelMapEntry+;
+#pragma link C++ class BiasMap+;
+#pragma link C++ class BiasMapEntry+;
+#pragma link C++ class Interpolator2D+;
+
+// ======================== libnova =========================
+
+#pragma link C++ global LN_SOLAR_STANDART_HORIZON;
+
+#pragma link C++ struct ln_lnlat_posn;
+#pragma link C++ struct ln_hrz_posn;
+#pragma link C++ struct ln_equ_posn;
+
+// angular_separation
+#pragma link C++ function ln_get_angular_separation;
+
+// transform
+#pragma link C++ function ln_get_hrz_from_equ;
+
+// rise_set
+#pragma link C++ struct ln_rst_time;
+
+// solar
+#pragma link C++ function ln_get_solar_rst;
+#pragma link C++ function ln_get_solar_rst_horizon;
+#pragma link C++ function ln_get_solar_equ_coords;
+
+// lunar
+#pragma link C++ function ln_get_lunar_equ_coords;
+#pragma link C++ function ln_get_lunar_equ_coords_prec;
+#pragma link C++ function ln_get_lunar_disk;
+#pragma link C++ function ln_get_lunar_sdiam;
+#pragma link C++ function ln_get_lunar_phase;
+#pragma link C++ function ln_get_lunar_rst;
+#pragma link C++ function ln_get_lunar_earth_dist;
+
+// Nova wrapper
+#pragma link C++ namespace Nova;
+#pragma link C++ struct Nova::ZdAzPosn;
+#pragma link C++ struct Nova::HrzPosn;
+#pragma link C++ struct Nova::RaDecPosn;
+#pragma link C++ struct Nova::EquPosn;
+
+#endif
Index: branches/Mars_McMismatchStudy/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile	(revision 17960)
@@ -0,0 +1,196 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+# @maintitle
+
+# @code
+
+#
+#  please change all system depend values in the 
+#  config.mk.${OSTYPE} file 
+#
+#
+
+include Makefile.conf.general
+include Makefile.conf.$(OSTYPE)
+
+#
+#PROGRAMS = readraw merpp mars test mona status
+PROGRAMS := readdaq readraw readcorsika ceres merpp callisto star ganymed sponde showlog showplot mars mars-config
+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 \
+          mcorsika \
+	  mdrs \
+          mfbase \
+          mfilter \
+          mdata \
+          mhbase \
+          mhvstime \
+          mhist \
+          manalysis \
+          mextralgo \
+          msignal \
+          mbadpixels \
+          mhcalib \
+          mhflux \
+	  mcalib \
+          mpedestal \
+          mfileio \
+          mgeom \
+	  melectronics \
+	  msim \
+	  msimreflector \
+	  msimcamera \
+          msql \
+          mimage \
+          mhft \
+          mmc \
+          mraw \
+          mcamera \
+	  mtrigger \
+          mpointing \
+          mreport \
+          mgui \
+          mranforest \
+          mjobs \
+          mjoptim \
+          mjtrain \
+          mmovie \
+          mtools \
+          mmuon
+
+LIBNOVA_PATH := `which libnovaconfig`
+
+ifeq ($(shell basename "$(LIBNOVA_PATH)X"), libnovaconfigX)
+#SUBDIRS += libnova
+LIBNOVA = -lnova
+endif
+
+#LIBRARIES = $(SUBDIRS:%=lib/lib%.a)
+LIBRARIES := $(SUBDIRS:=.a)
+CONDOR    := $(SUBDIRS:=.condor)
+SGE       := $(SUBDIRS:=.sge)
+MRPROPERS := $(SUBDIRS:=.mrproper)
+CLEANERS  := $(SUBDIRS:=.clean)
+LIBS      := $(SOLIB)
+
+#------------------------------------------------------------------------------
+.SUFFIXES: .c .cc .h .o .cxx .hxx .gch
+
+SRCFILES = \
+	   mcore/factofits.h \
+	   mcore/factfits.h \
+	   mcore/DrsCalib.h \
+	   mcore/PixelMap.h \
+	   mcore/Interpolator2D.h \
+	   mcore/nova.h
+
+############################################################
+RNDMNAME:=$(shell mktemp)
+
+all: $(SOLIB) $(PROGRAMS)
+	@echo " Done. "
+	@echo " "
+
+static: LIBS=$(SUBDIRS:=/*.o) $(OBJS)
+#static: rmlib $(LIBRARIES) $(PROGRAMS)
+static: $(LIBRARIES) $(PROGRAMS)
+	@echo " Done. "
+	@echo " "
+
+include Makefile.rules
+
+#
+# Use $(CXX) -v ... for a more verbose output
+#
+# ROOTGLIBS must be there - why? How can I link the libraries?
+$(SOLIB): $(LIBRARIES) $(OBJS) $(HEADERS)
+	@echo " Linking shared object $@ ..."
+	$(LINKER) $(CXXFLAGS) $(SOFLAG) $(OBJS) $(SUBDIRS:=/*.o) $(ROOTGLIBS) $(LIBNOVA) -o ${RNDMNAME}
+	mv ${RNDMNAME} $@
+	chmod go+r $@
+
+# This is a special workaround to create the shared object (bundle, plugin)
+# for root and the dynlib (to be linked with the executable) on Mac OSX
+ifneq ($(OSTYPE),darwin)
+$(PROGRAMS): $(PROGRAMS:=.o) $(SOLIB)
+	@echo " Linking $@ ..." 
+	$(LINKER) $(CXXFLAGS) $@.o $(MARS_LIB) $(SOLIB) $(ROOTGLIBS) -o $@
+
+# Use this to link the programs statically - for gprof
+#$(PROGRAMS): $(OBJS) $(HEADERS) $(PROGRAMS:=.o)
+#	@echo " Linking $@ ..." 
+#	$(CXX) $(CXXFLAGS) $(ROOTGLIBS) $(OBJS) $(SUBDIRS:=/*.o) $@.o $(MARS_LIB) -o $@
+else
+$(DYLIB): $(LIBRARIES) $(OBJS) $(HEADERS)
+	@echo " Linking dylib $(DYLIB) ..."
+	$(LINKER) $(CXXFLAGS) $(DYFLAG) $(OBJS) $(SUBDIRS:=/*.o) $(ROOTGLIBS) -o $@
+
+$(PROGRAMS): $(PROGRAMS:=.o) $(DYLIB)
+	@echo " Linking mac executable $@ ..." 
+	$(LINKER) $(CXXFLAGS) $(ROOTGLIBS) $(DYLIB) $@.o $(MARS_LIB) -o $@
+endif
+
+rmcondor:
+	rm -f .makecondor.log
+
+condor:	rmcondor $(CONDOR)
+	echo Waiting for jobs to finish...
+	condor_wait .makecondor.log
+	rm .makecondor.log
+	make -j2 $(PROGRAMS)
+#	find -name "*/.makecondor.*"
+#	find -maxdepth 2 -name ".makecondor.*" -exec echo {}\\\; cat {}\\\; echo {}\\\; \;
+
+sge:	$(SGE)
+	make -j16 $(PROGRAMS)
+
+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: branches/Mars_McMismatchStudy/Makefile.conf.darwin
===================================================================
--- branches/Mars_McMismatchStudy/Makefile.conf.darwin	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile.conf.darwin	(revision 17960)
@@ -0,0 +1,48 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+# @maintitle
+
+# @code
+
+# compilers
+
+CC       = gcc
+CXX      = g++
+F77      = f77
+AR       = ar -src
+
+#
+#  ----->>>   settings for compilation
+#
+OPTIM    = -O -Wall -Wpointer-arith -Wcast-align -Wconversion -Woverloaded-virtual
+# ggc 3.2: removed -fnonnull-objects -Wtraditional -Wnested-externs
+DEBUG    = 
+ARCHDEF  = -D__LINUX__
+
+# For Mac OSX we need to kind of shared objects. One which can be plugged
+# into root (bundle) and one which can be linked to the executables (dynlib)
+SOFLAG   = -bundle -flat_namespace -Xlinker -bind_at_load
+DYFLAG   = -dynamiclib -single_module -flat_namespace
+
+DYLIB    = $(SOLIB:.so=.dylib)
+
+# For debugging information use '-g'
+# For producing gmon.out use    '-pg'
+
+#MARS_LIB = -Llib $(SUBDIRS:%=-l%) $(MARSLIBS)
+MARS_LIB = -Llib $(MARSLIBS)
+INCLUDES = -I. $(SUBDIRS:%=-I%)
+
+# uncomment this for quiet compilation
+
+.SILENT:
+
+# @endcode
+##EOF
+
+
Index: branches/Mars_McMismatchStudy/Makefile.conf.general
===================================================================
--- branches/Mars_McMismatchStudy/Makefile.conf.general	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile.conf.general	(revision 17960)
@@ -0,0 +1,30 @@
+#
+#  ----->>>   root libraries
+#
+
+ROOTLIBS   := $(shell root-config --libs) -lASImage -lMinuit -lHistPainter -lThread
+ROOTGLIBS  := $(shell root-config --glibs) -lASImage -lMinuit -lHistPainter -lThread
+ROOTCFLAGS := $(shell root-config --cflags)
+
+SVN_REVISION := -DREVISION=\"$(shell svnversion -n .)\"
+
+#
+#  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"
+#
+OSTYPE   = $(shell uname -s | tr '[:upper:]' '[:lower:]')
+
+DEFINES	 := -DMARSVER=\"\<cvs\>\" -DPACKAGE_VERSION=\"2.4\" -D__MARS__ $(MARSDEFINES) -DHAVE_ZLIB -DPACKAGE_NAME=\"MARS\ CheObs\" ${SVN_REVISION}
+
+CXXFLAGS = $(ROOTCFLAGS) $(INCLUDES) $(OPTIM) $(DEBUG) $(ARCHDEF) $(DEFINES)
+CFLAGS   = $(CXXFLAGS) $(MARSFLAGS)
+FFLAGS   = $(CXXFLAGS)
+
+HEADERS  = $(subst .cxx,.hxx,$(subst .cc,.h,$(SRCFILES)))
+OBJS     = $(subst .cxx,.o,  $(subst .cc,.o,$(SRCFILES))) $(CINT)Cint.o
Index: branches/Mars_McMismatchStudy/Makefile.conf.linux
===================================================================
--- branches/Mars_McMismatchStudy/Makefile.conf.linux	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile.conf.linux	(revision 17960)
@@ -0,0 +1,41 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+
+# compilers
+
+ifeq ($(shell which colorgcc), )
+CC       := gcc
+CXX      := g++
+else
+CC       := colorgcc
+CXX      := colorgcc
+endif
+
+LINKER   := g++
+F77      := f77
+AR       := ar -rc
+
+#
+#  ----->>>   settings for compilation
+#
+OPTIM    := -O5 -std=c++0x -Wall -Winit-self -fPIC -Wpointer-arith -Wcast-align -Woverloaded-virtual
+# ggc 4.3: removed -Wshadow -fnonnull-objects -Wtraditional -Wnested-externs -Wconversion
+DEBUG    :=
+ARCHDEF  := -D__LINUX__
+SOFLAG   := -shared
+
+# For debugging information use '-g'
+# For producing gmon.out use    '-pg' (needs static linking)
+
+#MARS_LIB = -Llib $(SUBDIRS:%=-l%) $(MARSLIBS)
+MARS_LIB := -Llib $(MARSLIBS)
+INCLUDES  = -I. $(SUBDIRS:%=-I%)
+
+# uncomment this for quiet compilation
+
+.SILENT:
Index: branches/Mars_McMismatchStudy/Makefile.conf.linux-gnu
===================================================================
--- branches/Mars_McMismatchStudy/Makefile.conf.linux-gnu	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile.conf.linux-gnu	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/Makefile.conf.osf1
===================================================================
--- branches/Mars_McMismatchStudy/Makefile.conf.osf1	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile.conf.osf1	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/Makefile.conf.osf5.1
===================================================================
--- branches/Mars_McMismatchStudy/Makefile.conf.osf5.1	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile.conf.osf5.1	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/Makefile.rules
===================================================================
--- branches/Mars_McMismatchStudy/Makefile.rules	(revision 17960)
+++ branches/Mars_McMismatchStudy/Makefile.rules	(revision 17960)
@@ -0,0 +1,113 @@
+include $(CINT)Dep.d
+
+$(MRPROPERS):
+	@echo " Doing Mr.Proper in $(@:.mrproper=)"
+	(cd $(@:.mrproper=); ($(MAKE) -f Makefile mrproper > /dev/null); cd ..;) 
+
+$(CONDOR):
+	@echo " Starting make in $(@:.condor=) via condor"
+	(echo universe=vanilla; \
+         echo executable=/bin/bash; \
+         echo arguments=-c make; \
+         echo log=../.makecondor.log;    \
+         echo initialdir=$(@:.condor=); \
+         echo getenv=true;     \
+         echo notification=never; \
+         echo queue) | condor_submit > /dev/null
+#	(cd $(@:.condor=); (condor_run $(MAKE) &); cd ..;)
+#         echo output=.makecondor.out; \
+#         echo error=.makecondor.err;  \
+
+$(SGE):
+	@echo " Starting make in $(@:.sge=) via sge"
+	(cd $(@:.sge=); qsub -N $@ -sync y -b yes -q test -cwd /bin/bash -l -c make; cd ..;)
+
+$(CLEANERS):
+	@echo "Cleaning $(@:.clean=):"
+	(cd $(@:.clean=); $(MAKE) -f Makefile clean; cd ..;) 
+
+$(LIBRARIES):
+	@echo " Calling make in $(@:.a=)"
+	$(MAKE) -C $* -f Makefile all
+
+$(LIB): $(OBJS) $(CINT)Cint.o
+	@echo " - Building Library $(LIB)"
+	$(CXX) $(CXXFLAGS) $(DYNLIB) $(OBJS) $(CINT)Cint.o -o $(LIB)
+	@echo " "
+
+$(CINT)Cint.cc: $(HEADERS) $(CINT)LinkDef.h
+	@echo " - Generating dictionary $(CINT)Cint.cc"
+	rootcint -f $(CINT)Cint.cc \
+	-c $(INCLUDES) $(DEFINES) $(HEADERS) $(CINT)Incl.h $(CINT)LinkDef.h 
+
+%.d:
+	@echo " - Generating dependencies" $@
+	rmkdepend -f- -Y -w 3000 -- $(INCLUDES) -- $(SRCFILES) -- $(PROGRAMS:=.cc) 2> /dev/null | \
+        sed 's/^\(.*\).o:/$@ \1.o:/' > $@
+	echo "$@: Makefile" >> $@
+
+%.o:	%.cxx
+	@echo " - Compiling" $<
+	$(CXX) $(CXXFLAGS) -c $< -o $@
+
+%.o:	%.cc
+	@echo " - Compiling" $<
+	$(CXX) $(CXXFLAGS) -c $< -o $@
+
+%.o:	 %.c
+	@echo " - Compiling" $<
+	$(CC) $(CFLAGS) -c $< -o $@
+
+#
+# The cleaning facility
+#
+
+rmcint:	
+	@echo " Removing cint-stuff..."
+	@rm -f *Cint.*
+
+rmlib:	
+	@echo " Removing libraries..."
+	@echo " "
+	@rm -f lib/lib*.a lib*.a
+
+rmobjs:	
+	@echo " Removing object files..."
+	@rm -f *.o
+
+rmdep:	
+	@echo " Removing dependency files..."
+	@rm -f *Dep.d */*Dep.d
+
+rmcore:	
+	@echo " Removing core files..."
+	@rm -f core*
+
+rmbin:	
+	@echo " Removing binary files..."
+	@rm -f $(PROGRAMS) $(SOLIB) $(DYLIB) so_locations
+
+rmbak:
+	@echo " Removing backup files..."
+	@rm -f *~ kk.kk *.bak .#* .*~
+
+rmbakmac:
+	@echo " Removing backup files in macros"
+	@rm -f macros/*~
+
+rmhtml:
+	@echo " Removing htmldoc-tree"
+	rm -rf htmldoc/examples
+	rm -rf htmldoc/src
+	ls htmldoc/* | grep "htmldoc/" | grep -v images | grep -v CVS | xargs rm -f
+
+clean:	rmcint rmobjs rmdep rmcore rmlib
+
+cflags: 
+	@echo $(INCLUDES) $(CXXFLAGS)
+
+diff:
+	@svn diff | grep -v "^? " > mars.diff
+
+#zdiff:
+#	@cvs -z9 diff | grep -v "^? " > mars.diff
Index: branches/Mars_McMismatchStudy/NEWS
===================================================================
--- branches/Mars_McMismatchStudy/NEWS	(revision 17960)
+++ branches/Mars_McMismatchStudy/NEWS	(revision 17960)
@@ -0,0 +1,3523 @@
+                                                               -*-*- END -*-*-
+
+== <cvs> ==
+
+ ;general:
+
+   * On some systems (version of make?) the __LINUX__ definition was not set
+     when compiling. This lead to MTime(-1) not working properly. Fixed.
+
+   * The status display is now able to write a plain root file which means
+     that the MStatusArray container is omitted and the TCanvas are written
+     to the file directly. This allows to write files which are accessible
+     from a plain root (without MARS) if no MARS objects are contained
+     in the TCanvas'. In turn the reading of files which contains 
+     objects and TCanvas' but no MStatusArray object has been improved.
+
+   * MMcEvt.fPhi and MMcEvt.fTheta have been moved to its base class
+     MMcEvtBasic. Consequently, the direction of the primary shower
+     is not lost in the OriginalMC tree anymore
+
+   * Added a new class MJTrainImpact to estimate the impact parameter by use
+     of a random forest
+
+   * Changed MH::SetBinning and similar functions to take references instead
+     of pointers. Except for SetBinning(TH1&, const TH1&), which was renamed
+     to CopyBinning(const TH1&, TH1&) wrapper functions are provided so that
+     old macros should still work.
+     WARNING: These wrappers might be removed in future releases.
+
+   * A new class MJTrainCuts is available. It provides a way to graphically
+     analyse the cuts performed by a random forest. In addition the graphical
+     output can also be used to understand or find classical cuts. For more
+     details read the class description and look at macros/train/traincuts.C
+
+   * Implemented the pixel layout of the FACT camera into MGeomCamFACT
+
+   * Added a macro (macros/fact/fact_trigger.C) to display the FACT camera
+     and the trigger layout.
+
+ ;ceres:
+
+   * Allow for individual mirrors with parabolic shape (for details see
+     MReflector::ReadFile)
+
+   * As an additional output artificial star-files are written. They
+     contain star output compatible output based on the signal as
+     in the artificial callisto output files.
+
+   * The trigger channel which issued the trigger is now stored in
+     MRawEvtHeader::fNumTriggerLvl1
+
+   * The number of photons in the calibration signal is now distributed
+     by a possonian instead of a Gauss.
+
+   * implemented new file-naming scheme (corsika run-number is new
+     tranfered to the ceres output as file-number). Therefore a new option
+     has been implemented to set an artificial run-number:
+        ---run-number=12345
+
+   * The baseline, the baseline noise and the gain (multiplicator to the
+     pulse) are now accessible from the outside. The new values are:
+        MSimCamera.DefaultOffset
+        MSimCamera.DefaultNoise
+        MSimCamera.DefaultGain
+
+   * Added the FACT trigger layout: resmc/fact-trigger-sum.txt contains the
+     mapping of the regular patches, resmc/fact-trigger-all.txt the mapping
+     of all patches.
+
+   * Added reading of re-used corsika showers (only supported if MMCS is used)
+
+   * Added new mirror type MMirrorHex90 (MMirrorHex rotated by 90deg)
+
+ ;star:
+
+   * The time constraint in the image cleaning is now scaled with the
+     pixel distance. Consequently, the value given is not absolute in
+     ns anymore, but in ns/deg. This means that the values for MAGIC
+     have to be scaled by a factor of 10.
+
+   * Star now calculates new timing parameters, namely:
+
+   ** MHillasExt.fTimeSpread: 
+      This is the time spread (rms) around the mean of the arrival times.
+      It is calulated as 
+         <math>\sqrt{\sum{(t_i-<t>)^2}/n}</math>
+   ** MHillasExt.fTimeSpreadWeighted: 
+      This is the weighted time spread (rms) around the weighted mean of the arrival times.
+      It is calulated as 
+         <math>\frac{1}{\sum{w_i}}\sqrt{\sum{w_i(t_i-<wt>)^2}}}</math>
+   ** MHillasExt.fSlopeSpread: 
+      This is the time spread (rms) around the slope of the arrival times.
+      It is calulated as 
+         <math>\sqrt{\sum{(t_i-slope*(\cos\delta*x_i+\sin\delta*y_i)-<dt>)^2}/n}</math>
+   ** MHillasExt.fSlopeSpreadWeighted: 
+      This is the weighted time spread (rms) around the slope of the arrival times.
+      It is calulated as 
+         <math>\frac{1}{\sum{w_i}}\sqrt{\sum{w_i*(t_i-slope*(\cos\delta*x_i+\sin\delta*y_i)-<dt>)^2}</math>
+
+ ;trainenergy.C:
+
+   * The rsolution is not displayed anymore as resolution squared
+
+ ;automatic processing:
+
+   * jobmanger: 
+       - new algorithm
+       - implemented pbs as a third queueing system (for PhiDo)
+
+   * moved lock from file to database
+
+   * insertmc: script to insert montecarlo runs and sequences to the database
+     (to be used until webinterface is available)
+
+   * implemented possibility of having more than one processing site: One site
+     is the main site, where all output is collected and stored. The output 
+     from the other sites has to be copied there. 
+     So far used for FACT MC production in Dortmund (PhiDo). 
+
+   * runcorsika: removed STEPFC from inputcard as anyhow default of 1 was used 
+     instead of 0.1 
+
+   * processlog: new output level DEBUG
+
+   * changed database structure and joins in queries to allow for direct 
+     joining of tables with different primaries. This makes checkavail-script
+     unnecassary. 
+
+   * database: added new features to mcinfo.php (MC webinterface to display 
+     FACT MC)
+
+
+
+== Version 2.4 (2009/12/23) ==
+
+ ;general:
+
+   * Added a new palette "temp" to MH::SetPalette which should resample
+     a temperature
+
+   * Added consistency check for two consecutive runs
+
+   * Since ~1006246 (preliminary) the L1 signal (which is L1 after L2)
+     has been disconnected and the L1 (L1TPU) has directly been connected
+     to another bit in the trigger pattern. This has been fixed by an
+     update of the decoding. Both bits are now or'ed together.
+
+   * Added a new camera layout MGeomCamFact which is the "four rectangular
+     pixels ordered in a hexagonal geometry" layout
+
+   * All programs now store the command line as TNamed "CommandLine"
+
+   * the environment variable OSTYPE should now be obsolete. Instead
+     the output of "uname -s" converted to lower cases is used
+
+   * The Makefiles should now detect the OSTYPE automatically using
+     uname. This should make the setting of OSTYPE obsolete
+
+ ;showplot:
+
+   * If a file without a MStatusArray is opened all object (not just
+     canvases) found in the file are drawn. Note that this may result
+     in empty tabs.
+
+ ;ceres:
+
+   * The night sky noise is now scaled with the sensitive area and
+     is given in units per square centimeter
+
+   * The night-sky noise now also takes the cones transmission
+     into account
+
+   * The night sky noise can now be calculated from a night-sky
+     spctrum
+
+   * A transmission curve for the cones can now be given
+
+   * Added the possibility to add a cut after the image parameter
+     calculation (''Cut'')
+
+   * updated the PDE of the GAPDs with a more reliable curve from
+     the meeting page (linear extrapolate below 350nm)
+
+   * The impact distribution in the event distrbutions is now 
+     perpendicular to Alt/Az and the histogram is displayed in 1D
+
+   * The GAPD PDE has been updated
+
+   * PDEs and mirror reflectivities have been linearily extrapolated
+     to match the wavelegth range between 290nm and 900nm
+
+   * There is no default pulse shape anymoe it must be given in 
+     the resource file
+
+   * Fixed a bug which caused the aerosol coefficient to be incorrectly
+     initialized. The effect might be random but seems to be small.
+
+   * Now accepts sequence files as input
+
+   * creation of pedestal and calibration files is now steered by
+     --mode (see ceres help)
+
+   * Instead of initializing the whole G-APD chip (all cells) before 
+     each event (which is rather time consuming) a time evolution before
+     each event is now simulated which is enough to recovere every cell
+     to 99.999% of its response taking the background rate into account.
+     This is in total about a factor of ten faster and should not be
+     less accurate because under normal conditions the recovering cells
+     and the newly hitten cells will hardly be identical (due to
+     statistical reasons)
+
+   * improved the trigger algorithm which is now faster and allows easily 
+     for multiplicity triggers
+
+   * The PDC flag in the file name is now correctly written
+
+   * A "PreCut" has been added which can be used after reading the events
+     to select them even before any calculation is done.
+
+ ;merpp:
+
+   * The new drive reports which contain also the status of the starguider
+     are now implemented, but the starting date (17/05/09) is preliminary.
+
+ ;callisto:
+
+   * Fixed a bug which prevented MAGIC Monte Carlo file from being
+     calibrated (ceres files worked)
+
+   * updated (Muon) calibration constants of period 62, 63, 72-75
+
+ ;star:
+
+   * allow to run thru even if discriminator threshold are missing
+     (they are not used for analysis so far anyway)
+
+ ;ganymed:
+
+   * added new starguider calibration for sequences since 1000534
+
+ ;database:
+
+   * added possiblity to query/plot data from certain source (with 
+     regular expressions) in plotdb.php
+
+   * new feature in showplots*.php: on mouse-over additional information
+     on the sequence is displayed
+
+   * tables on database website have also 'Last' link now
+
+   * new version of builddatasets.php with more comfortable sequence 
+     selection
+   
+   * new features in builddatasets.php: 
+     - user management 
+     - 'Get Data Set File' button 
+     - 'Display Selected Sequences' button
+     - 'Display Not Selected Sequences' button
+     - 'Select all' buttons
+
+   * builddatasets.php: added possibility to update data sets in the 
+     database
+
+   * added limit for cloudiness for sequences in the tab 'Limits'
+
+ ;automation:
+
+   * jobmanager can be used more flexible now: via environnent variable
+     $AUTOMATIONSETUP more than one jobmanager per user can be started
+     using the same MARS version
+     Usage: export AUTOMATIONSETUP=mysetup ; /fullpath/jobmanager
+     and provide a file Mars/datacenter/scripts/setup.mysetup
+
+
+
+== Version 2.3 (2009/03/07) ==
+
+ ;SUGGESTION
+
+   * There is no need to re-run any data because no change took place which
+     could have an effect on the output. However, if you want a 
+     meaningful SrcPos plot for your MCs in sponde you must re-process
+     star for your MCs first.
+
+ ;REMARK
+
+   * File produced with this release containing a camera geometry (which 
+     are basically all files were produced as default) will not be readable
+     by older releases.
+
+ ;general
+
+   * fixed a few small bugs which could cause the display to crash in ganymed
+     and sponde
+
+   * in sequence file the date can now be omittet. In this case the
+     leading date with the underscore is missing in the expected filename
+
+   * the geometry class now also supports other geometries than just hexagons
+
+ ;automation
+
+   * added magnetic field Azimuth direction (ARRANG), currently
+     at ~ -7deg at La Palma
+
+ ;database
+
+   * plotdb.php: added default (sequences) for startup, added possibility
+     to set size of plot
+
+   * added a new table ''RunDataCheck'' which containes the rates after
+     image cleaning for every run which succeeded star. It can be 
+     plotted using ''plotrundb.C''
+
+ ;merpp
+
+   * added support for Arehucas Version >= 200812140
+
+   * added support for Arehucas Version >= 200809030
+
+ ;mars
+
+   * The display now also displays the trigger pattern
+
+   * The display can now display ceres reflector (_R_) files
+
+ ;ceres
+
+   * added a uniformly distributed one-bin time jitter for the start of the
+     digitization. Otherwise the first photon would be digitized always with
+     the same alignment to the bins
+
+   * Added a plot showing the production height of the photons
+
+   * Moved the particle id from the event header to the run header
+
+   * Added the possibility to simulate a psf on the camera plane (MSimPSF)
+
+   * Added a new plot ''SignalMax'' showing the maximum entry into the pixels
+
+   * Added many new options to control the tasks. For deatils see ''ceres.rc''
+
+   * Removed obsolete plots in pedestal and calibration mode
+
+   * Removed the non-NightSky photons from the plots where they are just
+     disturbing
+
+   * Added a trigger pattern to the output (Ped, Cal or Lvl1)
+
+   * The daq event number now represents the readout number
+
+   * The camera ''electronics'' can now be ''switched off''
+
+   * A new tab ''Info'' now display basic things like the reflector
+     layout
+
+   * Improved reading speed for corsika files
+
+   * Improved memory handling (if a large ampount of memory was needed
+     for a single event all further events were stored in the same 
+     memory and it was never freed, so the program took this memory
+     until the end)
+
+   * Converted the code from MMCS' reflector program to MSimAtmosphere
+     (instead of the tables build in for MAGIC Winter and Summer 
+     atmosphere we use the values written by Corsika fitted to the
+     tabulated atmosphere given as input)
+
+   * For caluclating the displayed image parameters in ceres a basic
+     image cleaning removing isolated pixels is now done.
+
+   * The magnetic field direction (ARRANG) is now taken into account
+
+   * Added plot for the energy threshold after trigger ''Threshold''
+
+   * Added plot for the effective collection area after trigger ''TrigArea''
+
+ ;star
+
+   * Now outputs MSrcPosCam for Monte Carlos in the Events tree.
+
+   * The definition of fConcCore has slightly changed. The numbers
+     might decrease a little bit (the effect should be rather small)
+
+ ;ganymed
+ 
+   * added pointing model 328198
+
+ ;sponde
+
+   * The SrcPos plot for your MCs was so far meaningless because it just
+     displayes the MSrcPosCam data from the input star-files. Unfortunately,
+     this containes was never written to the star-files yet.
+
+   * A new Tab 'OnTime' is available which is an effective on-time
+     fit as in star but for all data. This is mainly for manual cross-check
+     of the effective on-time
+
+   * In some circumstances it might be necessary to re-calculate the 
+     eff. on-time from the fit in the new tab, e.g. when a zenith distance
+     cut was made in ganymed. This can now be forced by ''--force-ontimefit''
+
+   * now reads the ''ganymed.rc'' from the ''ganymed.root'' and writes
+     it to its own output file (for convinience)
+
+
+
+== Version 2.2 (2009/01/30) ==
+
+ ;SUGGESTION
+
+   * This release doesn't contain a major change which is expected to
+     change your results. Nevertheless there are small changes to
+     the calibration which can effect at least the first few hundred
+     events in any (mainly MUX and even more SUM) sequence a little bit.
+     So it is recommended although not necessary to reset your sequences
+     in the database before further processing.
+
+ ;NEW
+
+   * A first implementation of a Monte Carlo simulation program
+     (ceres - Camera Electronics and REflector  Simulation) has been 
+     implemented. It can simulate a full telescope already including
+     a complete reflector simulation and a flexible trigger and readout
+     simulation. Currently, no perfect setup is implemented and
+     especially the output of the program (data structure) should
+     be considered alpha state. Also the user interface is not yet
+     ready.
+
+ ;general
+
+   * All command line options after -- are now interpreted as 
+     arguments (usually everything which doesn't start with a minus)
+     rather than options (usually everything which starts with a
+     minus). This allows to use file names starting with a -
+
+   * In all resource files you can now initialize the random number
+     generator. For details see: MJob::InitRandomNumberGenerator
+
+   * added a new program called ''readcorsika''. It's purpose is (in analogy
+     to readraw and readdaq) to read a Corsika output file (for now
+     only cherenkov output is supported) and print its contents in a 
+     human readable form. It can also write the contents of this file
+     into a root-file.
+
+   * The calculation of the maximum distance to the origin in a MGeomCam
+     has been improved (edges might be further away than the sides).
+     This is just a tiny change but it might change the appearance of
+     the radial profiles a little bit.
+
+   * The default binning of the center-of-gravity plot has slightly been 
+     increased
+
+ ;Database
+
+   * Added informations about the DC currents (fMinCurrents, fMedCurrents
+     and fMaxCurrents). The values are retrieved from the plots showing
+     the average DC currents of all pixels versus time.
+
+   * Websites with tables have now the opportunity to remove lines 
+     ('-' button at beginning of each line) and get all lines back 
+     ('+' at top of the column)
+
+   * Websites: added option to query only sequences containing sumtrigger 
+     events
+
+   * Websites: added option to group by date (year, month, night) for runs
+     and sequences and enabled that combining of different group-bys, 
+     e.g. status, date and source is possible
+
+ ;automatic analyis
+
+   * Rewritten producing plots in the web. 
+     New plots, namely the output of plotoptical.C (extinction curve from 
+     KVA), plotstat.C (status of the automatic analysis (percentage of 
+     processed, analysed data etc.)) and plotusage.C (statistics of the 
+     condor usage in the data center) has been are available now next to the 
+     plots of plotdb.C
+     Mean values from the plots (output of the macro) are provided in a 
+     txt file now. 
+     The creation of the plots for callisto, star and ganymed in the web is 
+     now steered via database. Consequently the plots are faster and 
+     reliable up-to-date. 
+     For all plots, a new layout is available facilitating the browsing 
+     through the plots and providing additional information on the 
+     displayed values. (tabs.php) These plots are linked from the DB 
+     websites and the wiki. 
+
+ ;statusdisplay
+
+   * The ''Loop'' entry in the menu bar now contains an option to pause
+     the loop and to process single events.
+
+ ;merpp
+
+   * Fixed merpping of raw-files (the runheader tree got the name RunHeader
+     instead of RunHeaders)
+
+   * Now allows to merpp files newer than 2008/09/03.
+
+   * Added fixes for wrong (wrong or double) run- and file-numbers
+     written by Arehucas. For deatils see MRawRunHeader::FixRunNumbers
+
+ ;callisto
+
+   * Extracting the pulse position for the pulse position check events
+     with sum trigger were denied. This decreased the statistics
+     extremely and therefor the resulting puse position was calculated
+     quite weak. Now sum events pass the calculation if and only if they
+     have also a level 1 trigger.
+
+   * the extraction of pedestal events and pulse position from the
+     first data events is now more automatic and makes sure that 
+     a more precise number of events is extracted independent of
+     the ratio with which pedestal events or events with signals
+     are contained in the data.
+
+   * Updated Muon calibration constants for all MUX data (teh changes were
+     all smaller than 5%)
+
+ ;star
+
+   * For the calculation of the effective on time all sum-triggered events
+     were skipped. Now all Level1-triggeres events will pass. This might
+     result in a slight inaccuracy of the effective on time.
+
+ ;ganymed
+
+   * If the source position is more than 1deg away from the camera
+     center an error is raised now.
+
+   * Hopefully fixed the bug ''ganymed crashes when resized''
+
+ ;sponde
+
+    * Fixed a problem which causes the fitted spectral slope to be displayed
+      incorrectly. If you use MJSpectrum::FormFlux in your macros make
+      sure that the parameter 0 of your fit is negative.
+
+    * Added a histogram showing the read source position of your MCs
+
+
+
+== Version 2.1.1 (2008/08/04) ==
+
+ ;Database
+
+   * Added the median number of photo electrons from the calibration
+     pulses to the db (fMedNumPheInner, fMedNumPheOuter) and the relative
+     error of their raw counts (fRelChargeRmsInner, fRelChargeRmsOuter)
+
+   * Added fTotOnTime, which is the on-time as given by the run-headers
+     (in contradiction to fAbsOnTime which comes from CC)
+
+   * Added new primaries for the new data structure (Magic II): for the 
+     tables dealing with sequences (SequenceBuild Status, Sequences, 
+     SequenceProcessStatus, Calibration, Star and DataSetSequenceProcessing) 
+     this is the telescope number (fTelescopeNumber) for the tables dealing 
+     with runs (RunData and RunProcessStatus) this is in addition the file 
+     number (fFileNumber)
+
+   * Added column fPriority to the status tables to be able to steer the order
+     in which the data is processed. As default the run, sequence and dataset
+     number are used. 
+
+ ;automatic analyis
+
+   * Adapted scripts to the new data structure: They can handle now different
+     telescopes (getting the information as usual from the database). 
+     The paths for Magic 2 are not yet implemented. 
+
+ ;general
+
+   * should work now with root 5.20/00 (please note that root 5.20/00
+     we encounter crahses in the status display which are ot yet
+     understood)
+
+   * Sequences and Datasets are now stored as "MDataSet" and "MSequence"
+     instead of the base name of the file. This makes them easier to 
+     access from the code
+
+   * Default Monte Carlo names in MSequence do not require the _E at
+     the end anymore
+
+   * where abrrevating a sequence file with a sequence number is possible
+     also "telescope:sequence" is now accepted, e.g.:
+        star 2:2000123 --out=output
+     see the programs' help for more details.
+
+   * sequences (MSequence or MSequenceSQL) can now directly be retrieved
+     from the database. See the constructors for more details.
+
+   * MReadTree now supports friends
+
+   * MReadTree can now read also files not written by MARS and store
+     the data encapsulated in emulated MParContainers
+
+   * added a new starguider calibration valid since 15.1.08
+
+ ;showplot
+
+   * showplot can now read more than one file at once. This is especially
+     inetersting if reading files containing pure canvases
+
+ ;merpp
+
+   * we merpp the dc currents now also from the camera reports (they have
+     just a lower rate than the current reports, 0.1Hz instead of 1Hz)
+
+   * In the automatic analysis we omit merpping of the currents from the 
+     caco files and use the lower rate camera reports from the cc files
+     instead
+
+   * merpp has been redisigned to allow merpping of the cc-reports
+     of a whole sequence. This allows to design a very simple analysis:
+        mkdir output
+        ./callisto 100776 --out=output
+        ./merpp 100776 output
+        ./star 100776 --ind=output --out=output
+     Instead of the sequence number also sequence files are accepted.
+
+   * Implemented a fix for run-numbers between 1001348 and 1001396 
+     which were incorrectly assigned by the cc.
+
+
+ ;callisto
+
+   * added a filter again which was was removed in the last release.
+     it removed the most brightest events. This should not change
+     any analysis result because these events are so bright that
+     they cannot be analysed anyway, but the bad-pixel plots doesn't
+     show outliers.
+
+   * updated muon calibration constants for the periods 51-57, 
+     58-63 and 67-
+
+ ;star
+
+   * The camera currents are now displayed with the rate of the camera
+     reports instead of the caco reports
+
+ ;ganymed
+
+   * if mc camera files are new enough (>=8) the source position in the
+     camera is now calculated from the stored telscope and shower
+     orientation (Note, that this might not be suitable in all cases
+     depending on the aim of the study. These case still needs
+     implementation)
+
+
+
+== Version 2.1 (2008/06/18) ==
+
+ ;Database
+
+   * introduced average temperature and wind speed from star-files
+
+   * introduced average values from Pyrometer (mainly Cloudiness)
+
+   * introduced the ratio of accepted calibration events in the
+     calibration run
+
+   * introduced the average rates of the different trigger pattern,
+     e.g. the rate of pedestal and calibration events, from the signal-file
+
+ ;general
+
+   * fixed GroupBy options in plot*.C macros
+
+   * only display KVA points (not the Tuorla points) in plotoptical.C
+
+   * all programs now allow to add resources to the ones from the resource
+     file or overwrite them from the command line. This can be done like this
+          ganymed --config=ganymed.rc --rc=Cut1.Param1:0.25 --rc=Cut1.Param3:5.5
+     if something seems to be wrong you can debug what the program is doing
+     using the option --debug-env=3
+
+   * increased the diversity of debug levels. That also means that with -v3
+     you get now less output, i.e. only the output which is important for
+     an analysis. To get more output which helps for debugging try 4, 5 and 6.
+
+   * fixed a problem in the task synchronizing the reading of the reports
+     and the data stream. The effect was that in some circumstances the last
+     events of some trees could have been skipped. Since this is only a
+     very tiny part of the data no severe effect to your analysis results 
+     is expected (an exception might be very short, i.e. singel runs, 
+     datasets).
+
+   * Dataset file now allow to include the sequence file directly within
+     the dataset file and also allow to exclude single runs from the dataset.
+     (for more details see Class reference of MDataSet)
+  
+   * Sequence files now allow for excluding runs from the analysis
+     (for more details see Class reference of MSequence)
+
+   * added code to process the sum-trigger flag
+
+   * the histogram classes MH3 and MHn now support profile histograms
+
+   * the histogram classes MH3 and MHn now support labels at the axis
+
+   * the Random Forest Train-classes (MJTRain*) now store the used datasets
+     in the output file
+
+   * the MFMagicCuts have a new option to allow a linear area cut (for
+     special studies)
+
+   * The liniking of the shared object is now done into a file defined
+     by 'mktemp'. This should be a local file system which accelerates
+     liniking a lot.
+
+   * The code has been prepared for compilation with root 5.18/00d
+
+   * The MHEnergyEst histogram now shows the distribution of 
+     (Eest-Emc)/Est and the distributions (Eest-Emc)/Eest vs. Eest
+     and (Eest-Emc)/Emc vs Emc.
+
+   * fixed mars (event display) for merpped raw-data and MC data
+
+   * adapted the synatx of sequence files to allow for the new run/file
+     scheme. For more details see class description of MSequence
+
+ ;showplot
+
+   * Added support for tiff files
+
+   * Added support for csv files (tables containing tab number, 
+     name and title)
+
+   * Tabs now can have a title which is displayed in the postscript file
+
+   * When multiple file are written at once (e.g. pngs from a display)
+     it is now possible to use the tab name and or tab number in the
+     file name. For details see showplos's help.
+
+ ;merpp
+
+   * Implemented cc file version 2008-02-20/0
+
+   * Implemented cc file version 2008-05-19/0
+
+   * With new options merpping can be restricted (in addition to the
+     run-number) also by telescope and file number. 
+        For details see "merpp --help"
+
+   * Implemented raw data format 11 (the most important change, except
+     from plenty of changes in the format definition, is the addition
+     of the file-number in the header) If nobody makes a mistake this
+     format should have the advantage that it is by definition forward
+     compatible, so old programs will be able to read newer formats.
+
+   * Added Pyrometer information to default output (stored in a new Tree
+     Pyrometer, needs a complete new merpp, i.e. new calibration)
+
+   * Merpping (also update) can now be restricted to one single report.
+     For example: 
+     If you want to update an old file with Pyrometer information call 
+        merpp --only=Pyrometer --update
+
+ ;callisto
+
+    * in the pedestal processing now at least 50 processed events are
+      required for succeeding.
+
+    * the signal and calib files now contain also the sequence information
+
+    * the two MPedestalCam in the calib file now have proper names
+      to distinguish them from each other (MPedestalCam, MPedestalExtracted)
+
+    * Both pedestal cams now contain the number of events processed
+
+    * In Mars V2.0 the extraction of the fundamental pedestal was broken, 
+      i.e. for the extraction of the calibration pulses basically the average
+      over all events of the first slice instead of all slices was used.
+      Since pedestal and calibration constants are continously recalculated
+      this only effected the very first events of every sequence.
+
+    * For the extraction of the position of the maximum sample now the
+      extraction range is set automatically to the extraction window,
+      before the whole accessible range was used.
+
+    * If the number of samples in the events and the number of samples
+      in the run-header disagrees now an error is raised (this can 
+      happen in not well simulated Monte Carlo files)
+
+    * In the case of MUX-data pedestal events with the lvl1 trigger flag
+      could survive into the pedestal calculation -- fixed.
+
+    * Tab "TrigPat" added showing the distribution of the trigger pattern
+      as found in the run-files (normalized with the run length)
+
+    * The selection of events from the trigger pattern has been improved.
+      If the trigger pattern is corrupted events won't pass anymore.
+
+    * Added a new command line option --dev-null to suppress output of
+      Y-files (this is useful for test cases)
+
+    * added a new tab "CalPos" showing the arrival time of extracted
+      interleaved calibration events
+
+    * Using the new --test switch you can now calibrate the calibration
+      file
+
+ ;star
+
+    * the star file now contains also the sequence information
+
+    * Added a new command line option --dev-null to suppress output of
+      I-files (this is useful for test cases)
+
+    * Tab "Rate" added showing the distribution of the trigger pattern
+      (should only be Trig (Lvl1/Lvl2) and Sum (Sum only)) as found in
+      the Y-files (normalized with the run length)
+
+    * The effective on-time calculation doesn't use events with only
+      sum-trigger anymore
+
+    * The data in the MHWeather tab has been reorganized. The never 
+      working solar radiation has been removed and the data from
+      the pyrometer (cloudiness, air and sky temperature) is 
+      displayed in addition.
+
+ ;ganymed/sponde
+
+    * Now data points are even shown correctly if they have error bars larger
+      than one sigma. Points with null or negative significances are omitted.
+
+    * DrawNicePlot now allows to set a projection range
+
+    * Updates pointing models. One is applied after the implementation
+      of the new LUTS in August, the other one is applied after the
+      next major change of the pointing model in October. Note that
+      these models are preliminary and give wrong results below Zd=65deg
+
+ ;sponde
+
+    * fixed resource files ('''Spectrum''' instead of '''MJSpectrum''')
+
+    * a new option "--force-runtime" is available. In case of very short
+      datasets (for light-curves) which are in the order of a few
+      minutes the calculated effective on-time is not very acurate because
+      it is quantizised in the order of a minute. Therefore you can switch
+      to using the real run-time instead (remakrt: this ignores any
+      dead-time!)
+
+    * a more analytical way is used to "fill" Monte Carlos into regions 
+      of impact parameters which have not been simulated because the
+      trigger efficiency is assumed to be 0.
+
+    * estimated sensitivity curves for hi and lo zenith angles are shown
+      scaled to the correct observation time and collection area
+                                          
+    * the Monte Carlo events after cuts are now written to the output file
+      if an output file given
+
+
+
+ *** Version 2.0 (2007/09/03)
+
+   - database: the position used for the pulse pos check was missing 
+     in the callisto output and could thus not be filled into the DB.
+     Also the old values seemed not exactly the PulsePos used for 
+     teh check.
+
+   - general: Resource file now allow an Include-Resource, i.e. you can
+     read a resource file with default settings, include it in your
+     resource file and overwrite the settings in your file. More than
+     one include file is allowed. Inclusions can be iterative.
+        Include: mydefaults.rc yourdefaults.rc
+     The resources in the first file have higher priority than the
+     second file.
+
+   - general: Now the output files (calib*.root, etc) also contain the
+     resource file (to check it open it in the TBrowser and choose Print()
+     from the context menu)
+
+   - general: Dataset files now allow to overwrite the default path
+     to search for sequence and data files. Note, that the program
+     option and individual resources will overwrite it. For example:
+        SequencePath: /magic/montecarlo/sequences
+        DataPath:     /magic/montecarlo/star
+
+   - general: Fixed a problem with variables in MDataPhrase. It seems
+     that only optimdisp (didn't work) was effected.
+
+   - general: Some improvements to the optim and train processing. For
+     example the ststud window now got a proper title.
+
+   - general: The "Status Display: " was removed from the window title
+     within an Eventloop.
+
+   - general: added a new flexible histogram-class (MHn) which can be used
+     for example in testing after optimizations or training to produce
+     user defined histograms.
+
+   - general: The Random Forest now allows attaching an evaluation
+     function which is applied to its output. This allows to train
+     on whatever you like (eg. train on log10(energy), but return
+     energy)
+
+   - general: The Random Forest training of energy (trainenergy.c) and
+     disp (traindisp.C) has been improved by more graphical output to
+     judge the result. 
+
+   - general: The training of energy (trainenergy.C) has been improved
+     a lot by training on a different quantity than energy. It gives
+     a result which is highly independant of the source spectrum
+     and shows lower bias than all other options.
+
+   - general: Dataset files are allowed to contain collections of
+     datasets. For more details see the class reference of MDataSet.
+
+   - general: The default WobbleMode in a datset file now (if not
+     overwritten) is "auto", i.e. wobble mode is set if the dataset
+     doesn't contain off-sequences.
+
+   - merpp: Merpp can read file format version 9 now. Please realize
+     that for file format version 9 the extraction range is different
+     and must be set to 0/49 instead of 15/64 in callisto_mux.rc until
+     the first and last 15 slices have been removed from all MUX data.
+
+   - mars: Similar to writing movies you can now select events which
+     should be displayed in your display. Therefore add the following
+     lines to your mars.rc:
+         MFEvtNumber.FileName: ganymed00223552.root
+         MFEvtNumber.Selector: ThetaSquared.fVal<0.04 && DataType.fVal>0.5
+     The input file can be a ganymed-file after (ganymed*.root) or
+     before (ganymed*-summary.root) file. For example to select all events
+     from your on sample after cuts (excluding the ThetaSq cut) use
+         MFEvtNumber.Selector: DataType.fVal>0.5
+     To show all events from your on-sample after quality cuts
+     use the summary file instead.
+
+   - mars: new ways to call mars are implemented. Instead
+     of calling
+         mars filename.root
+     you can now also use
+         mars sequence.txt
+     or
+         mars sequence.txt inputpath
+     or replace sequence.txt by the sequence number if the default
+     sequence file should be used.
+
+   - mars: The default size has been increased
+
+   - mars: There are two new heckboxes which allow to switch off
+     the calculated image parameters
+
+   - callisto: was broken for MCs... fixed.
+
+   - callisto: improved calculation of spline coefficients a lot. This
+     leads to a further improvement of the event rate calibrating MUX
+     data of about 15% (175evt/s instead of 150evt/s)
+
+   - callisto: finally the raw data we read is now real 16bit (with
+     10bit precision) for MUX data and not a stripped 8bit number
+     anymore. Due to scaling of the numbers (without precision loss
+     into an [0-256[ range, the final numbers for pedestal, pedestalrms
+     and extacted signal don't change. However, at all places where
+     raw data is directly accessed (eg. saturation and variation 
+     limits in the signal- and pedestal-extraction) the numbers
+     refer still to the data's 16bit range.
+
+   - callisto: The maximum arrival time difference used in the bad
+     pixel treatment is now in units of nanoseconds, which leads to 3.0ns
+     for both, old FADC and MUX-FADC, data.
+
+   - callisto: Be aware that callisto is now calibrating the arrival time
+     in nanoseconds rather than time slices. Also all following tasks
+     have been changed to assume ns units now. If you star data 
+     calibrated with an older version it might be necessary to adapt 
+     some timimng parameters (Muon Analysis and MFSoftwareTrigger)
+     to obtain optimal results. The plot in the PulsePos tab 
+     will now be in ns, too. This might also mean that the Muon
+     analysis in star might not work as perfect as expected as long
+     as old files read in.
+
+   - callisto: The calibration constants of earlier updates got lost
+     somehow. All constants have been updated.
+
+   - star: The PSF is now determined from the profile of the ArcWidth
+     instead of arcwidth/radius. The old way gave to much weight
+     to the bins with low statistics. The reference lines have been
+     updated.
+
+   - star: For speed reasons events suitable for the muon analysis 
+     are now also preselected by fConcCOG<0.1 which seems to be a very
+     good preselector for muons.
+
+   - star: is now calculating a new timing parameter the Slope along
+     the major and minor axis of the shower. Therefore a numerical
+     solution of a line-fit is used. To use MHillasExt.fSlopeLong
+     and MHillasExt.fSlopeTrans don't forget to multiply it with
+     the sign stored in MHillasSrc.fCosDeltaAlpha as usual.
+
+   - star: The parameters fInnerSize, fInnerLeakage1 and fInnerLeakage2
+     have been removed from MNewImagePar. They have never been good for
+     anything.
+
+   - star: Implemented a new recursive algorithm which is supposed to be
+     faster. Also implemented new cleaning oiptions, which are: 
+        + CleanLevel0:  
+          The cleaning level above single core pixels can be kept
+        + KeepIsolatedPixels:
+          Define whether single core pixels should be kept
+        + TimeLevel1:
+          The coincidence window in nanoseconds to single used neighbors
+        + TimeLevel2:
+          The coincidence window in nanoseconds to two used neighbors
+        + PostCleanType:
+          MOde in which a time dependent post cleaning should be applied
+           0: No post cleaning
+           1: Require for each used pixels at least one used neighbor
+              within a time-window of CleanLevel1
+           2: Require for each used pixels at least two used neighbor
+              within a time-window of CleanLevel2
+           3: Require first two and second one used neighbor
+              within a time-window of CleanLevel1 and fCleanLevel2 
+              respectively
+        + RecoverIsolatedPixels:
+          - recoveres isolated core pixels if they have a used neighbor
+
+   - mars/star: The new default cleaning is:
+      + CleanLevel1: 6.0
+      + CleanLevel2: 3.0
+      + CleanTime1:  1.75
+      + CleanTime2:  1.75
+      + PostCleanType: 3
+
+   - star/ganymed: The old spark-cuts have been replaced by new ones.
+     These new spark cuts have been cross checked with the sequences
+     84720 (before splitter), 101041 (after splitter) and 223539 (new
+     FADCs). In all cases they seperate pretty well, but of course not
+     perfect. Monte Carlos have suggested to tighten the cuts a little
+     bit further at low sizes. This has been done.
+
+   - ganymed: IMPORTANT - The spark cuts have been changed to match
+     all available data more or less well. This might mean that for 
+     YOUR data there are still sparks visible. 
+     Whenever you do an analysis you have to make sure that NO sparks
+     survive your cuts!
+
+   - ganymed: The old hadronness and size cuts have gotten new indices
+     (10, 11). The old indices 8 and 9 now mean an additional condition
+     for ghostbusting based on the formula (dist-c[9])*c[8]-slope.
+     If you want to switch off this cut just move the line far away enough,
+     e.g. by setting c[9] to -500. Please update your ganymed.rc files
+     accordingly!
+     The unit of c[9] is deg. It is the dist at which your cut will
+     cross the slope==0. The unit of the slope is ns/deg. So if
+     you readin files calibrated with an older Mars-version you
+     have to adapt the default value for c[9] to the FADCs:
+        - Multiply by two for the MUX    FADCs    (run number > 200.000)
+        - Multiply by 0.3 for the Siegen FADCs    (run number < 200.000)
+        - Multiply by  42 for the meaning of life (run number = 200.000)
+
+   - ganymed: The old Cut0 is now called CutQ and is calculated before
+     the source position is caluclated. If you need a quality cut
+     including source dependant data (be very carefull with this!)
+     you have to use Cut0 instead.
+
+   - ganymed: now properly supports three off regions in wobble mode.
+     It will be the default from now on in ganymed_wobble.rc. To change
+     the number of off-regions use
+         NumOffSourcePositions: 1
+     in your ganymed.rc. Also by default no off-theta cut will be done
+     anymore so that you will get a background level higher than the
+     signal level in your ThetaSq plot for ThetaSq>0.2.
+     Due to this be carefull changing the scaling mode away from 
+     "None". You will underestimate your signal if your scale interval
+     is not properly set.
+     (Rem: ThetaSqN is no longer needed)
+
+   - ganymed: is now storing the events of all (on- and off-)
+     source positions even in the case of more than one off-source
+     position. This should allow sponde to work properly and the
+     energy estimation is done correctly in all cases (without any
+     "nearest position" trick)
+
+   - ganymed: From 85340 (19.3.2006) on a real starguider calibration
+     with a real pointing model for the starguider is done, calibrated
+     with more than thousand tpoints taken from this date on.
+
+   - ganymed: was broken for Wobble-MCs... fixed.
+
+   - ganymed: The default cuts (MFMagicCuts) and the disp-parametrization
+     has changed. Note that your old ganymed.rc will be incompatible
+     with the new algorithms! Please check the ganymed.rc files and
+     the class description of MFMagicCuts for more information.
+     It is recommended at the moment to use identical Disp-Parametrizations
+     for on/off- and wobble-mode. If cuts are optimized only
+     the Area-Cut (parameters 2,3,4) and the theta-sq cut (parameter 1)
+     should be optimized. All other values should be kept as they are.
+     If you want to do an anylsis without timing a parameters, you can
+     switch off the timing cuts by seeting parameter 7 to a very small
+     value (eg. -99). To remove the slope parameter from the disp
+     paremtrization set parameter 8 to 0.
+
+   - ganymed: The distribution of observation time versus zenith
+     angle is now shown for off- AND on-data.
+
+   - ganymed: The contents of the source position plot are no longer
+     averaged, thus a lot of (fake) events between the two wobble 
+     positions have disappeared.
+
+   - ganymed: There is a new tab "CutT" it contains the VsSize plots
+     with the CutT, whihc is defined in ganymed.rc, applied. It
+     is resonable to use your theta-cut for it, to see if there is
+     something strange (sparks!) in your signal-region.
+
+   - ganymed: To choose a dataset from a collection in a dataset file
+     use the new command line option "--dataset=12345"
+
+   - optim, sponde: should now properly support three off-regions.
+     Just produce your ganymed summary files with three off-regions.
+     optim and sponde will automatically get all off events from
+     all off-regions from this file. Please do not forget to
+     set the scaling in optimwobble.C properly:
+        fit.SetScaleUser(1./3);
+     it is not yet read in automatically (will follow soon).
+     In the case of fixed Scale you can also use
+        cuts.SetThetaCut(MFMagicCuts::kOn);
+     no off-cut needed.
+     Be carefull in case of three off-regions when switching on
+     scale mode. Make sure that the scale interval is set correctly.
+
+   - sponde: sponde.rc and sponde_onoff.rc are now idetical
+
+   - sponde: the resouce files have been rewritten with a lot of
+     comments and a well working parametrization for an energy estimator
+
+   - sponde: In the estimated energy versus monte carlo energy plot the
+     contents where exchanged.... fixed.
+
+   - sponde: the so called "accurate"-mode has been removed. It didn't
+     give any improvement in accuracy, only decreased execution speed.
+
+   - sponde: the so called "simple"-mode has been removed. It didn't
+     give any improvement in simple.
+
+   - sponde: the so called "refill"-mode has been removed. It was anyhow
+     not implemented.
+
+   - sponde: now checks whether the theta distribution of your on-data
+     and the theta-distribution of your Monte Carlo sample (after
+     weighting) fits. If it doesn't fit properly (eg. the Monte Carlo
+     sample is incomplete) execution is stopped. Execution can be forced
+     using the new option --force-theta. Use this option with care!
+
+   - sponde: Proper collection areas can now be constructed also from
+     Monte Carlo samples generated with different maximum impact
+     parameters. Note that in previous version you neither got 
+     a warning or failure, nor was there any obvious sign that the
+     collection area was overestimated due to usage of files with 
+     different maximum impact parameters.
+
+   - sponde: If MC files with different lower energy limits are used
+     the primary MC spectrum is artificially completed down to the
+     lowest energy used at all. WARNING: that this gives correct 
+     collection areas ONLY if none of the events in this region would
+     survive your cuts at all.
+
+   - sponde: the output file now contains more information about
+     the spectrum (eg. the full 2D collection area histogram).
+     Note, that this information can only be written to the file
+     if it is stored automatically via command line argument.
+     If you only store the status display from within the display
+     the information is lost.
+
+   - sponde: added a new tab "Disp". It shows the residual of the disp
+     (Disp-Dist) versus several parameters and it is meant to judge the
+     quality of the disp estimator. In the ideal case the residual is zero
+     and doesn't depend on any variable. The tab is displayed after
+     CutQ and Cut0.
+
+   - sponde: added a new tab "Energy". It shows the residual of the
+     energy (lg(estimated energy)-lg(monte carlo energy)) versus
+     several parameters and it is meant to judge the quality of the
+     energy estimator. In the ideal case the residual is zero
+     and doesn't depend on any variable. In reality even a good estimator
+     can show residuals versus Monte Carlo energy. The tab is displayed
+     after all cuts.
+
+   - sponde: added a new tab "EventDist" showing the unweighted real
+     absolute number of events of your sample after cuts. This tells
+     you how many events with this energy you had in your MC files.
+     The same information you get from the error bars of the weighted
+     histograms, but this is less intuitive.
+
+   - sponde: The spectrum plots now show the crab- and 1553-spectrum
+     for comparison. It is not meant to show these curves in
+     publications, they are only for production.
+
+   - sponde: The OriginalMC tree with the events produced by corsika 
+     is now processed only once
+
+   - sponde: Finally fixed most annoying bug, which has effected the
+     last bin of the collection area. It was the problem that binnings
+     of root histograms are from 1 to n (included) but there was a C-like
+     loop in sponde from 0 to n (excluded). Now the loop also includes
+     correctly under- and overflow-bins. The worse thing with this is,
+     that for the events in the highest bin not only the bin-content
+     was wrong, but also the weights applied to these events, which could
+     in pricipal effect also other parts of the distribution (eg. due
+     to energy estimation). Fortunately it effected only a few events
+     in most cases.
+
+
+
+ *** Version 1.2 (2007/05/14)
+
+   - database: The database now has two new values Unsuitable50 and
+     Unsuitable01. They express the number of pixels which are
+     unsuitable for more than 50%, respectively more than 1%, of
+     all calibrated event. It is a more accurate number than the
+     previously used numbers, because they only take the first
+     calibration (ignoring the interleaved calibrations) into account.
+
+   - database: The database now has two other new values UnsuitableMax and
+     DeadMax. They express the maximum number of pixels which were
+     unsuitable, respectively dead, during the sequence. Because
+     of high pedestal rms (cars passing) a few events with very high
+     numbers of unsuitable pixels can happen. Not to suffer from this
+     effect we don't take the highest 0.1% of the numbers into account.
+
+   - general: fixed a bug which caused callisto and star to stop working
+     properly because the callisto output was currupted
+
+   - general: a script called scripts/makemovie has been added which
+     simplified the process of producing several movies from a single
+     sequence with different setup.
+
+   - callisto: Some more code cleanup. Started to remove old obsolete
+     code from cvs.
+
+   - callisto: The extraction of the pedestal with the extractor was
+     not random. It seems that extracting at one position is still biased
+     (for example in the first or last slices we could still suffer from
+     switching noise) Now it is completely random.
+
+   - callisto: In MPedCalcPedRun (which is the pedestal extraction from
+     pedestal files) individual pixels could be skipped due to high
+     variations. This was already the case for the pedestal extraction
+     from the lo-gains since the beginning and properly handled
+     there, but was introduced in the extraction from the pedestal files
+     a while ago. To calculate the average value it was still divided
+     by the number of events procesed not by the number of summands
+     really summed. This let to a pedestal which was a tiny amount too
+     small (for a few piels in the order of 0.1%). This led to an slightly
+     positive offset of the randomly extracted pedestal for a few pixels.
+     I doubt that this has a big effect on the result, because the effect
+     on the individual numbers is quite small. Due to this it is suggested
+     that you rerun your calibration to make sure you are without any
+     avoidable bias.
+
+   - callisto: the ArrTimeRmsLimit is now is a check of the deviation from
+     the median rms of the absolute arrival time and expressed in significance
+     levels. This replaces the old meaning of an abolute upper limit. An
+     absolute upper limit doesn't make much sense, because in our data 
+     all arrival times are shifted at the same time (in fact it might be
+     a shift of the artificial trigger w.r.t. to the light flash).
+
+   - callisto: Added a new tab "BadPixTm" which shows the time evolution
+     of the number of unsuitable pixels over the whole sequence. This
+     is usefull mainly to judge if an intermediate calibration had
+     problems.
+
+   - callisto: Added a new tab "DeadPixTm" which shows the time evolution
+     of the number of dead pixels over the whole sequence. Dead pixels 
+     in this context are unmapped pixels, i.e. pixels which could not
+     be interpolated, and thus are ignored in the further analysis.
+
+   - callisto: It is now possible to use the position of the maximum
+     of the spline as arrival time instead of the leading edge even
+     when using the integral for the signal. Therefor set the extraction
+     type to kIntegralRel ("IntegralRelative") and the relative height
+     ("HeightTm") to -1:
+       MJPedestalC1.ExtractSignal.ExtractionType: IntegralRelative
+       MJPedestalC1.ExtractSignal.HeightTm: -1
+
+
+
+
+ *** Version  1.1 (2007/04/27)
+
+   - general: The new class MGeomCamDwarf contains the camera geometry
+     for our prefered Dwarf camera and can be used to create general
+     geometries of roundish or hexagonal cameras.
+
+   - mars: The default cleaning is now abolute 8.5/4.0.
+
+   - mars: The resource file mars.rc now contains examples for MUX data
+
+   - merpp: Implemented file format version 8 (MUX FADC data). The 16-bit
+     data containing only 10-bit information is still cooked down to
+     8-bit, by cutting away the lowest 8-bit.
+
+   - merpp: When reading raw data the data is now stored in a single
+     array. The lo-gain array is obsolete. The interface stays the same.
+
+   - callisto: To process the new MUX data use the resource file
+        callisto_mux.rc
+
+   - callisto: The -root and -raw options to read merpped raw data have
+     been removed
+
+   - callisto: If the -mc option is given the sequence-name can now be
+     replaced by the MC sequence number
+
+   - callisto: If the sequence file contains "MonteCarlo: Yes" the
+     -mc option can now be omitted
+
+   - callisto: Started further simplification by removing obsolete
+     dependancies on MCalibIntensity*Cams.
+
+   - callisto: removed unsused intensity calibration from MJCalibration
+     for further simplification
+
+   - callisto: for simplification removed references to
+     MBadPixelsIntensityCam, MCalibrationIntensityQECam, 
+     MCalibrationIntensityRelTimeCam, MCalibrationIntensityTestCam, 
+     MCalibrationIntensityChargeCam, and MCalibrationIntensityBlindCam
+     (this should at minimum change nothing at all, and at maximum
+      improve thing if these containers where somewhere not handled
+      properly)
+
+   - callisto: Added the option to write an event movie. Please use
+     this option with care (huge files) but exessively to understand
+     our events. For further documentation please refer to the
+     IACT wiki
+     (currently at http://www.astro.uni.wuerzburg.de/mediawiki-1.9.0)
+
+   - callisto: Improved binning for the pulse position check histogram
+
+   - callisto: The code calculating the pulse position checknow takes
+     the pedestal into account
+
+   - callisto: The arrival time is now stored with full precision this
+     helps to get rid of artefacts in histograms. For the signal this
+     is not necessray because it is displayed in log-scale anyhow
+
+   - callisto: Fixed a problem with internal exclusions. Pixels which
+     have once been marked as unsuitable didn't get the necessary
+     histograms filled anymore to be rechecked with each interleaved
+     calibration.
+
+   - callisto: The relative arrival time resolution (the rms of the
+     relative arrival time offset) is now checked against its
+     median and the median deviation, instead of the average 
+     plus an absolute offset.
+
+   - callisto: The relative arrival time offset is now calculated
+     w.r.t. its median not w.r.t. to an artificial reference pixel.
+
+   - callisto: The relative time calibration now marks pixels with
+     outlaying offset as unsuitable
+
+   - callisto: The interleaved relative time calibration has been switched
+     on. The advantage is that pixels which are marked as outliers
+     now can recover. An improvement over time is not expected, because
+     the relative time calibration seems stable.
+
+   - ganymed: If the dataset file containes "MonteCarlo: Yes" the "-mc"
+     option can now be omitted.
+
+   - ganymed: If either the dataset file containes "MonteCarlo: Yes" 
+     or the option "-mc" is specified as default the monte carlo datacenter
+     paths (/magic/montecarlo/...) are used if not overwritten in the
+     dataset file.
+
+   - ganymed: The output files now contain run- and event-number for all
+     events, accessible as RunNumber.fVal and EvtNumber.fVal
+
+   - ganymed: Added a plot showing the source position in the camera also
+     for wobble mode
+
+   - ganymed: In addition to the existing task which can be setup to
+     be executed after Cut1 a final task called "EstimateEnergy"
+     has been added, executed before writing the final output
+     (ganymed00000000.root). The task setup in all three cases
+     can be choosen individually. (For all three(!) cases you 
+     can for example choose MRanForestCalc. For examples see all
+     sponde*.rc and all ganymed*rc)
+
+   - ganymed: If a container "MEstimatedEnergy" is found in the 
+     parameter list (eg. because it was setup by MEstimateEnergy)
+     it will be written to the output file.
+
+
+
+ *** Version  1.0 (2007/02/16)
+
+   - database: Website to plot values from the database has been added. 
+
+   - database: The rate of spark events as found by star is now kept
+     and the rate after cleaning is now with spark events subtracted
+
+   - general: The changes to the interpretation of phrases lead to
+     a problem with the access of MHMatrix objects (eg. "M[0]")... fixed.
+
+   - general: Added example files how you can create your own calendar
+      (eg. as christmas present) with Mars. Just run
+           root macros/tutorials/calendar.C
+
+   - general: Added a possibility to display grouped data in the plotdb.C
+     macro (and similar macros). This allows to plot hourly, nightly,
+     weekly, monthly and yearly averages. 
+     For more details see the plotall function of the macro
+
+   - general: fixed the error display of the camera display. It showed
+     wrong results.
+
+   - general: fixed a memory leak when reading many MStatusDisplays
+
+   - general: added a macro (macros/tutorials/mirrordelay.C) plotting the delay
+     between a spherical and a parabolic mirror
+
+   - callisto: We have a new pulse position check which takes the properties
+     of the extractor automatically into account. So no need to set 
+     ExtractWinLeft/Right anymore. Again a check for pulses too much to the
+     left is done. If possible the lo-gain extraction start and hi-gain
+     extraction end is changed accordingly. If no proper extraction range
+     can be set (hi-gain too much to the left) an error is raised.
+
+   - callisto: New swapped pixels have been found and corrected
+
+   - callisto: Redone the signal extraction this includes:
+     + Unified the algorithms to extract the pedestal for all pedestal
+       extractions done
+     + Unification of hi- and lo-gain into one array
+     + Unification of hi- and lo-gain extraction for Spline and
+       Digital Filter (means now exactly the same algorithm is used,
+       not a copy-and-pasted one)
+     + Store pedestal subtracted data in a common place
+     + Improved extraction algorithms. If the algorithms search a 
+       maximum but don't find one they don't return the maximum anymore
+     + Improved the extraction such that a information for signal
+       and time which is consistent is returned
+     + replaced the numerical spline with a (not slower) analytical
+       solution
+     + Lowered the saturation limit from 250 to 245 to make sure that
+       we are far away in all pixels from problems with the clock-noise
+     + The start of the lo-gain extraction is calculated from the hi-gain
+       arrival time. In case of saturation an estimation is used.
+     + the hi-gain window was extended to slice 16. This allows extraction
+       of very late pulses in single pixels or of huge hadron showers.
+     + Now uses the lo-gain extraction range for pedestal extraction,
+       not the hi-gain range in the lo-gain
+
+   - callisto: New hi-/lo-gain calibration constants have been produced
+     for all periods from the statistic of the whole period. They are
+     now used automatically depending on the periods. The old constants
+     where deviation in avarega about 2%-3%. The constants are very
+     stable from period to period (<<1%) except for exchanged channels.
+     In a few cases the constants used so far were off by 1%-2% (maybe
+     temperature effects?)
+
+   - callisto: To gain obsolete space we do not write the 
+     MPedestalFundamental anymore. Also calibration and bad pixel
+     treatment is not done for it anymore because it has never been used.
+
+   - callisto: Fixed a bug in the seuqence handling which caused the
+     light condition to be ignored
+
+   - star: Added two new tabs "Sparkless" and "Sparks" these tabs show
+     basically the same as "Cleaned" but the distribution devided into
+     the events fullfilling a spark cut or being rejected by it.
+     This cut can be changed from star.rc (see example inside) by
+     the "SparkCut" directive
+
+   - star: Star displays now the average individual pixel-rate (IPR) versus
+     time and the average discriminator threshold (DT) of all pixels.
+
+   - optim: fixed a problem with the optim-macros which was due to a bug
+     in the new phrase parsing
+
+   - ganymed: To get a nice FalseSource plot (instead of the all-information
+     debug plot displayed as a standard plot) use the context menu
+     somewhere between the two upper plots, click on "DrawNicePlot"
+     and enjoy the result. (It is the same context menu which contains
+     the other options)
+     PLEASE ALWAYS USE THIS PLOT FOR ANY KIND OF PRESENTATION!
+
+   - ganymed/optim/train: The cut program, trainings- and optimization
+     macros could run with less files found than expected from the
+     sequence-files. No the execution is stopped in this case.
+
+   - ganymed: now stores the dataset in the output file with all information
+     contained (as sequence number, sequence path, data path) so that the
+     used dataset file can be recreated complete from the output
+
+   - sponde: now also allows the uasge of random forest
+
+   - sponde: added a plot showing the cut efficiency
+
+   - sponde: Using root versions < 5.13/04 still resulted in wrong binomial
+     errors (eg. effecting the collection area) because the errors of the
+     two histograms were swapped in the calculation, which makes a difference
+     in the case the histograms contains weighted events. Aditionally the
+     totalarea was incorrectly taken into account, which results in too small
+     errors, which makes a difference at low statistics were the errors
+     or the collection area dominate.
+
+
+
+ *** Version  0.10.3 (2006/10/23)
+
+   - database: Implemented ObservationMode flag in websites.
+
+   - database: For sequences there is now also the stoptime available on the
+     websites. 
+
+   - database: Removed ManuallyChanged flag from sequence-info websites, 
+     as it is not needed anymore with the new sequence building algorithm.
+
+   - general: MRolke.[cc,h]: Modification of TRolke from root_v5.12.00b.
+     Class for calculation of confidence intervals (upper limits). 
+     Use model 3 or 4 for upper limit calculation for MAGIC observations.
+     Please read the class instruction of TRolke for more information.
+
+   - general: The programs now return 0xfe if the requested resource file
+     doesn't exist.
+
+   - general: Errors comming from root itself are now not output to
+     stderr anymore but to our default (colored) log-stream.
+
+   - general: Changed the interface to TFormula such that now everything
+     is parsed by TFormula, which should allow to use phrases even
+     without paranthesis correctly parsed.
+
+   - callisto: replaced the AdHoc number of effective integration slices
+     in the digital filter  by an average of the correct number, averaged
+     over all possible set of weights. This also gives correct numbers
+     for the lo-gains which were totally wrong before.
+
+   - callisto: drastically reduced memory consumption by not storing
+     all intermediate calibration results in memory anymore (we might
+     write them into a file in the future)
+
+   - ganymed: To get a nice Theta-Sq plot (instead of the all-information
+     debug plot displayed as a standard plot) use the context menu
+     somewhere between the two upper plots, click on "DrawNicePlot"
+     and enjoy the result. (It is the same context menu which contains
+     the "DrawAll" option)
+     PLEASE ALWAYS USE THIS PLOT FOR ANY KIND OF PRESENTATION!
+
+
+
+ *** Version  0.10.2 (2006/10/15)
+
+   - general: changed the building of the sequence files such, that
+     the source-/project name in case of wobble-sources is not the
+     source/project of the first data run anymore but the new generalized
+     wobble source/project
+
+   - general: Added some functions to MAstro to calculate sun and
+     moon properties
+
+   - general: Added two new macros (starvisday.C and starvisyear.C)
+     which allow to plot the visibility of several stars in one day
+     or of one star along one year
+
+
+
+ *** Version  0.10.1 (2006/10/11)
+
+   - general: HTML logging output was distorted... fixed.
+
+   - general: Changed the writing of the sequencefiles such that only
+     as many pedestal files as giving at least 1000 pedestal events which
+     are nearby the first calibration run are used as pedestal runs
+
+   - sponde: In the calculation of the collection area(s) and the 
+     distribution for MOnte Carlo and estimated energy the error
+     calculation was wrong because root didn't take the errors
+     properly into account... fixed.
+
+
+
+ *** Version  0.10 (2006/10/10)
+
+   - general: all executables now check consistency of the root version
+     installed with the root version used for compilation. The return
+     code in this case is 255.
+
+   - general: The algorithm to build seqeunces has been redesigned
+     completly. It is now more flexible in terms of a resource file
+     resources/sequences.rc which can be used to partly overwrite
+     the default algorithm and defined the important part of the
+     algorithm. It also takes correctly into account several ways
+     of taking wobble-data. Currently the new algorithm doesn't take
+     the number of pedestal events anymore into account (so a sequence
+     could have much less than 1000 pedestal events and data runs are
+     no-more used instead)
+
+   - general: a lot of small changes to make the code compatible with
+     root 5.12/00 and gcc 4.1
+
+   - general: Fixed some warnings thrown if more warnings are switched
+     on in the compiler
+
+   - general: Added a function to MMath which returns the Median of
+     the distribution abs(y[i]-median) but at 68:32 division instead 
+     of 50:50, which is somehow the median counterpart of the rms.
+
+   - general: MAstroCatalog allows now to read calatog files (as bsc5)
+     even if they are compressed with gzip (recommended compression
+     is with "-1")
+
+   - showplot:
+     + batch mode creation of image files now works with root 5.12/00
+     + added support for writing bmp (though it never produces
+       bmp which can be read by programs like xv or gimp)
+     + added support for xml
+     + added new option to start the display with a different size, by
+        --display-width=nnn or --display-height=nnn
+     + added options to define the canvas size when the display is started
+        --canvas-width=nnn or --canvas-height=nnn
+       the option can also be used for batch-mode conversion
+     + added an option which automatically fits the display size to the
+       desktop-size: --auto-size
+
+   - merpp: didn't recognize files with the extension .raw.gz - fixed.
+
+   - merpp: allow the reports to have 1000ms due to a bug in the camera
+     program.
+
+   - callisto: New swapped pixels have been found and corrected. For
+     details see MRawRunHeader::FixAssignment()
+
+   - callisto: Callisto now raises an error if one of the input files could
+     not be opened.
+
+   - callisto: In some rare cases it could happen that in the signal
+     extraction of the digital filter the extractor returned nonsense
+     results due a wrong initializion of a variable (this happens in
+     cases in which the extracted signal is exactly zero or the
+     digital filter couldn't slide because of a too small extraction
+     window, which could happen in the lo-gain extraction)
+
+   - callisto: The lo-gains have been marked as valid in some cases 
+     when they got not extracted at all (deltsumlo=deltatimelo=0) because
+     the allowed extraction range (fLoGainLast-fLoGainFirst) was
+     smaller than the number of slices (fLoGainWindowSize) needed
+     by the lo-gain extractor
+
+   - callisto: Updated absolute calibration constants (muon calibration)
+
+   - callisto: fixed a bug which caused the hi-gain saturation not
+     to be handled properly in the spline (the position of the
+     saturation was calculated incorrectly)
+
+   - callisto: fixed a bug which gave weird results if hi- _and_
+     lo-gain could not be extracted properly. In some cases hi-
+     and lo-gain have not been extracted at all and the random result
+     got calibrated. In other cases the hi-gain was saturating and the
+     lo-gain has not been extracted. For this a completly arbitraty
+     scale factor was applied to the result from extracting the
+     charge of the saturating hi-gain.
+
+   - callisto: improves handling of extracted signal if lo- and/or
+     hi-gain could not be extracted properly. If no appropriate
+     calibration of either the signal or the arrival time is possible
+     the pixel is now markes as unsuitable instead of estimated.
+
+   - callisto: Fixed a problem in the spline extraction which gave
+     weird results if the signal was extracted from the first (and
+     highest) slice (as a workaround extraction from the first
+     slice has been forbidden)
+
+   - callisto: Fixed a bug regarding the use of the QE which doesn't
+     effect the result because the default is used anyhow.
+     (The bug was there since 14/07/2005)
+
+   - callisto: Changed the default for fgLoGainStartShift to -2.4
+
+   - callisto: Fixed a bug which caused all hi-/lo-gain calibration
+     factors to be always 10 for all pixels as soon as the first
+     calibration update has happend.
+
+   - callisto: Fixed the hi-/lo-gain offset for the Digital Filter. It
+     was off by more than one slice (which gives wrong values for
+     pixels which have saturated the hi-gain) This was a problem
+     mainly for timing studies, not so much for the automatic standard
+     analysis. Also the values for the Spline have been changed slightly:
+        + Digital Filter from 1.70 to 0.95
+        + Spline         from 1.39 to 1.30
+     The numbers were sorted out by an extensive test in the
+     test-database.
+
+   - callisto: Removed the tab showing the average calibrated arrival
+     time. It never gave useful information.
+
+   - callisto: Now tab "HiLoCal" which shows the ratio between hi- and
+     lo-gain pulse for data pulses if hi- and lo-gain have saturated
+     and both were extracted because the hi-gain was above the 
+     LoGainSwitch.
+
+   - callisto: Now tab "HiLoOff" which shows the offset between hi- and
+     lo-gain pulse position (after application of LoGainOffset, which
+     means in the ideal case it is 0) for data pulses if hi- and lo-gain
+     have saturated and both were extracted because the hi-gain was above
+     the LoGainSwitch.
+
+   - callisto: After extensive tests a new threshold level for determination
+     of the pulse position has been found at 50phe. This is due to the
+     fact that for lower pulses the arrival time changes its average
+     behaviour dramatically. It tends to the average of the extraction
+     range and starts sticking to non-floating point numbers (5, 6, 7, ...)
+
+   - callisto: Added two more plots to the calibration part. The average
+     extracted signal and the average extracted arrival time as
+     extracted by the signal extractor (This can help debugging problems
+     because it doesn't involve a fit)
+
+   - star: changed the fit for the effective on time such that initial
+     values are calculated automatically now instead of using build
+     in values. This makes the fit more indepedant of the underlaying
+     rates. With a test of ~350 sequences in the test database it could
+     be shown that the new fit gives the same result +/-1sek.
+     The highest deviation was +5s the lowest -10s. You can now control
+     the bahaviour with two resource values:
+        MHEffectiveOnTime.FistBin:   3
+        MHEffectiveOnTime.NumEvents: 12000
+     Use FirstBin=1 and NumEvents=120 to fit the effective on time
+     from the resulting gamma candidates
+
+   - star: The Center histogram in MHHillas is now by default displayed
+     with the colz draw-option
+
+   - ganymed: now produces valid error codes if failed
+
+   - ganymed: MFMagicCuts now supports a hadronness cut. Switch it on
+     with the option "hadronness" instead of "area" or "both" if
+     you want to use both cuts. The hadronness cut includes a fixed
+     cut in hadronness (index 8) and a fixed cut in size (index 9).
+
+   - ganymed: MFMagicCuts: fixed abug introduced 2005/7/14 which caused
+     the M3Long of the anti source to be not properly evaluated 
+     (actually is was evaluated as a unique random number) in case
+     of optimization with anti-theta cut switched on. This might have
+     lead to improper, but not necessarily wrong, optimization results.
+
+   - ganymed: ganymed_onoff.rc, ganymed_wobble.rc - updated with comments
+     how to use random forest
+
+   - ganymed: use the same spark cuts as in ganymed_wobble.rc as in
+     ganymed_onoff.rc. Seems to be unintentional that they were different.
+
+   - sponde: Since the introduction of the possibility to define a
+     normalization energy instead of using the integral the default
+     was not using the integral anymore but a normalization energy of
+     1GeV. It is now the integral again.
+
+   - sponde: Fixed a problem in the weighting which did not allow
+     a MC slope of -1.
+
+
+
+ *** Version  0.9.6 (2006/05/24)
+
+   - general: changed the binning of the azimuthal profile of the camera
+     such that it is aligned with the 60deg boundaries.
+     
+   - merpp: better handling of problems with the TH, TD part of the 
+     CC-REPORT for files older than 200507190 and 200412210 
+     respectively
+
+   - merpp: improved handling of RECEIVERS-COM-ERROR in CC-REPORT
+
+   - merpp: implementd latest changes in starguider reports (sinc 9th May)
+
+   - callisto: if an arrival time is extracted outside the fadc range is
+     was set to the boundary before. Now a random number is assigned
+     instead to avoid unfortunate coincidences of arrival times just
+     by this arbitrary value.
+
+   - callisto: added a new option to callisto.rc which allows
+     to set the maximum arrival time difference allowed for the 
+     badpixel algorithm to determin whether a pixels belongs to a shower:
+       MJCalibrateSignal.MBadPixelsTreat.MaxArrivalTimeDiff: 0.9
+
+   - callisto: changed the old value (0.5) for MaxArrivalTimeDiff 
+     to 0.9 as suggested by Stefan due to a recent study on the fraction
+     of pixels surviving the image cleaning
+
+   - callisto: switched off error in case of "pulse is too much to the left"
+
+   - callisto: The extraction window is not adapted anymore. This means that
+     the pulse is extracted from the full range. The draw-back is that the
+     background (pedestal) will become slightly higher. Switching on/off
+     the PulsePosCheck in the callisto.rc only effects filling the
+     histograms.
+     WARNING: If the pulse is too much to the left data is calibrated!
+     Check the PulsePosCheck-PulsePosition AND the Inhomogeneity parameter
+     in the database to make sure that your data is valid!
+
+   - star: Show also the number of stars correlated correctly by the
+     starguider
+
+   - ganymed: implemented a new class (MHThetaSqN) which allows to use more
+     than one off-source region in wobble-mode. To use it add the following to
+     your ganymed_wobble.rc:
+      + MJCut.NameHist: MHThetaSqN            (switch the new feature on)
+      + MHThetaSqN.NumOffSourcePos: 3         (define number of off-regions)
+      + MHThetaSqN.DoOffCut: Yes,No           (switch on/off the off-cut)
+      + Cut1.ThetaCut: None                 
+      + MHThetaSqN.SignificanceCutLevel: 2.0  (increase off-cut by 2.0/1.7)
+
+   - ganymed: in the case the latest report is older than a default (currently
+       one minute) and the current report will be skip the starguider
+       correction and calibration will be reset. The maximum age can be
+       setup from ganymed.rc by (minutes):
+         MPointingDevCalc.MaxAge: 1.5
+
+   - ganymed: A first implementation showing all size-bins for the theta-sq
+     resp. alpha-plots in a single tab automatically
+
+
+
+ *** Version  0.9.5.1 (2006/05/05)
+
+   - general: Added a new option "zdiff" to the Makefile which runs
+     "cvs diff" as "make diff" would do, but with compression
+
+   - general: accelerated MTFillMatrix (used for eample in all training
+     and optimization macros) by skipping some obsolete calles in the
+     eventloop the first and second loop could be accelerated by ~20%
+
+   - general: Added a missing feature in the MFilterList class which
+     prevented MFEnergySlope from working correctly in trainenergy.C
+
+   - general: Accelerated the random forest training and usage a bit
+
+   - merpp: Adapted to new raw data file format version 6
+
+   - merpp: fixed a problem with reading the starguider reports 
+     after 6.3.2006
+
+   - callisto: At some times six pixels had to be exchanged manually in the
+     data. If the pixels to be swaped are both not found, an error was raised
+     and calibration was stopped. Now it is assumed they are intentially not
+     mapped and the Error has been changed to a Warning.
+
+   - star: Added new image cleaning based on the arrival time of the shower.
+     The new cleaning can be accessed using the parameter "Time" instead of
+     the the old one (like "Absolute) in the star.rc-file.
+     Recommended parameters:
+      + MImgCleanStd.CleanLevel1:  8.2
+      + MImgCleanStd.CleanLevel2:  5
+      + MImgCleanStd.CleanRings:   2
+      + MImgCleanStd.KeepSinglePixels: No
+
+   - star: Simplified the calculation of the effective on time. By letting
+     the fit start in the third bin the result should become more stable.
+     The fit quality is now ignored for the theta-plot which is not used
+     in the analysis later. Still better pre-cut which, for example,
+     remove events triggered by car-light (rate changing on a short
+     time-scale) are missing.
+
+   - macros: optimonoff.C, optimwobble.C: implemented a new strategy
+     for optimization (kWeakSource) which is suggested by the Berlin
+     people for weak sources.
+
+   - macros: plotdb.C: 
+       + if no dataset and no time-interval is given only sequences with
+         an effective on-time above five minutes are plotted anymore
+       + added a new tab "RelTime" displaying the relative on-time
+         (effective on-time divided by the observation time)
+
+   - macros: optim*.C: by skipping some obsolete calles in the eventloop
+     the optimization became a lot faster
+
+   - ganymed: In the second loop the MHNewImagePar histograms disapeared.
+     To display them just delete the pads displayed on top.
+
+   - ganymed: fixed a bug which could cause strange behaviour in wobble
+     mode if no starguider information was available due to an incorrect
+     initialization of the starguider calibration
+
+   - ganymed: The scale region in the False Source Plot (MHDisp) can now
+     be changed from within the plot. It can also be setup from the
+     resource file using:
+       + MHDisp.fScaleMin: 0.325
+       + MHDisp.fScaleMax: 0.475
+
+   - ganymed, showplot: Fixed a problem with the fit to the off-data
+     (HistOff) which could cause a time lag or an inifinite loop.
+     The bug did not effect the results at all.
+
+   - sponde: Added a new tab showing the effective collection area after
+     trigger (including the software trigger)
+
+   - sponde: MMcSpectrumWeight has a new option which allows to define
+     the scaling factor not by the integral of the events but at
+     a defined energy:
+        e.g. MMcSpectrumWeight.NormEnergy: 200
+
+   - MTFillMatrix, sponde: by skipping some obsolete calles in the
+     eventloops the loop could be accelerated by ~20%
+
+
+
+ *** Version  0.9.5 (2006/03/13)
+
+   - macros: fixed a typo optimwoble.C (SetThetaCut instead SetAlphaCut)
+     and added the standard Disp-parametrization
+
+   - macros: added a new macro datacenter/macros/plotstat.C allowing
+     to plot statistics about the data processing
+
+   - macros: added a new macro to plot the muon correction coefficients
+     versus period (macros/plot/mucal.C)
+
+   - showplot: path inflation for ganymed files was broken
+
+   - callisto: Fixed an important bug. When the number of saturating pixels
+     were calculated the bad pixel information already available from the
+     calibration was ignored. This yields wrong values in case pixels
+     are broken and saturate all the time or randomly.
+
+   - callisto: Updated Muon calibration constants. Spline data now also uses
+     different values for different periods
+
+   - star: The time-evolution shown in the effective on-time plot now displays
+     the axis range (if there are no holes it should be similar to the
+     effective on-time)
+
+   - star: Added two new image parameters:
+       + MNewImagePar.fConcCOG: The ratio of the equivalent signals of
+         the three pixels next to the center of gravity and the size
+       + MNewImagePar.fConcCore: The ratio of the signals of all
+         pixels inside or touching the ellipse and the size
+
+   - ganymed: now stops in requested source isn't found in catalog file
+
+   - ganymed: Many improvements to the phi-plot in wobble mode:
+      + with a template the ideal background is displayed
+      + a possible camera inhomogeneity is taken into account
+      + the anti theta cut is better supported
+      + the phi cut is automatically calculated from the theta cut
+     See the examples in ganymed_wobble.rc for more details.
+
+   - ganymed: fixed plot for E^2*dN/dE. The spectrum was multiplied with two
+     times the bin-width instead of the absolute energy
+
+   - ganymed: New cuts for on/off and wobble mode
+
+   - ganymed: The smearing of the False Source plot has been increased 
+     to 0.06
+
+   - ganymed: The starguider calibration can now be changed from the 
+     resource file.
+      See the examples in ganymed*.rc for more details.
+
+   - ganymed: added a new option for on-/off-observations
+       MJCut.RandomSourcePosition
+     If switched on the distribution of observation time of the source
+     position in the camera is calculated from the on-data and randomly
+     applied with this distrbution to the off-data.
+
+   - ganymed: by skipping some obsolete calles in the eventloop the
+     first and second loop could be accelerated by ~20%
+
+   - ganymed: The default in ganymed_onoff.rc is now to determin the source
+     position in the off-data randomly according to its distribution in the
+     on-data.
+
+
+
+ *** Version  0.9.4.3 (2006/02/13)
+
+   - general: Fixed a bug in most of the programs which prevented the
+     compile date in the startup message to be displayed
+
+   - general: Simplified program calls. The following abbreviations 
+     are now possible:
+        showlog callisto 55599
+        showplot signal 55599
+        star 55599
+        callisto 55999
+        ganymed 2
+     In this cases the corrsponding root-, log-, sequence- or dataset-
+     filename is automatically compiled using the default datacenter
+     paths ("/magic/*")
+
+   - general: Fixed a long outstanding bug which made axis tick marks
+     disappear if MDataFormula was used (eg. abs(x))
+
+   - general: Updated MMath with new functions to calculate the results of
+     a exponential, logarithmic and powerlaw fits analytically.
+
+   - general: Updated some macros with comments:
+      + macros/optim/optimdisp.C
+      + macros/optim/optimenergy.C
+      + macros/optim/optimwobble.C:
+
+   - general: MTFillMatrix (the class to fill one or two MHMatrix from
+     files) now allows adding a pre-cut like in the optimization. E.g. this
+     is useful to perform g/h-separation cuts before training the random
+     forest.
+
+   - general: Between the rund 53300 and 68754 the pixels 553-558 were not 
+     correctly assigned in the raw data assignement table. A fix to correct 
+     the assignment tabel have been implemented.
+
+   - general: MAstroCatalog now allows rotating of the sky-grid and stars
+     by 90, 180 and 270 deg.
+
+   - general: the macro plotdb.C now allows to highlight sequences belonging
+     to a datset. For more details see the descritions in the macro.
+
+   - StatusDisplay: Fixed the algorithm to calculate the size ratio
+     of the display, it gave wrong results espacially for big sizes.
+     Now the embedded canvas should always have a ratio width/height=3/2.
+     The "Size" options have been updated with values fitting the 3/2 
+     size ratio.
+
+   - RanForest:
+      + Updated the random forest classes to support also the
+        regression method implemented by Thomas H.
+      + added new tutorial macro how to train the random forest
+        for energy estimation (macros/optim/rfenergyest.C)
+      + new classes to train the random forest (still in development)
+        mjtrain/MJTrainEnergy, mjtrain/MJTrainDisp, mjtrain/MJTrainSeparation
+      + new tutorial macros for random forest training in macros/train
+        trainenergy.C, traindisp.C, trainseparation.C
+
+   - mars: now allows to setup a cut in the resource file mars.rc to choose
+     the events to be displayed, eg:
+       Cut.Condition: {0} && {1}
+       Cut.0: MHillas.fSize>100
+       Cut.1: MHillas.fSize<900
+
+   - merpp: Made aware of the new .rep format 200510250. This includes
+     interpretation of the Receiver Board Temperatures (MCameraRecTemp),
+     the discriminator thresholds (MCameraTD) and the disciminator
+     delays (MCameraTD). All of them come with the CC report and are therefor
+     written to the CC tree.
+
+   - callisto: fixed a bug in the calculation of the arrival times in
+     the Digital Filter. They were all shifted by the same amount
+     fHiGainFirst. This caused an offset in the order of the position of
+     the left border of the extraction window in the times calculated
+     from high-gain and from low-gain. The bug effected only the absolute
+     arrival times. The bug was there since 30.1.2005.
+
+   - callisto: Changed the ExtractionWindow for the pulse position check
+     such that the camera inhomogeneity becomes as less as possible and
+     comparable to the pulso position check switched off. More details
+     on the study will be given at our result web-page.
+
+   - ganymed: ganymed.rc, ganymed_onoff.rc:
+     changed to new cuts trained with 1ES1218 and Crab-data
+     for maximum sigma*log10(excess)
+
+   - ganymed: In addition to the Hadronness calculator (CalcHadronness)
+     a new option was implemented to estimate Disp (CalcDisp)
+
+   - ganymed: Implemented two new options which allow
+     to overwrite the default path to search for the sequence files
+       --ins=/magic/sequences
+     and where to search for the image data
+       --ind=/magic/data/star
+
+   - ganymed: MSrcPosCorrect now allows overwriting of the misfocussing
+     dx/dy from the resource file by 
+       MSrcPosCorrect.Dx
+       MSrcPosCorrect.Dy
+
+   - ganymed: fixed reading the source catalog. Only as many chars
+     as the requested source name had were compared (If a source
+     "1ES1218" and "1ES1218+304" were in the catalog and "1ES1218+304"
+     were requested it could happen that the coordinates of
+     "1ES1218" were read) The source coordinates are now printed
+     in addition to its name to the logging output.
+
+   - ganymed: changed the background fit in the case of a ThetaSq function
+     from a polynomial to a exponential, this should give a big improvement
+     for on-only analysis'
+
+   - ganymed/sponde: Calculation of the error of single size-/energy-
+     bins now uses Li/Ma (5) instead of LiMa (17)
+
+   - sponde: Added a plot E^2*dN/dE
+
+   - sponde: The energy estimator plot should now show values like
+     they are commonly used.
+
+   - sponde: Now MMcSpectrumWeight also excepts formulas with two X
+     (a powerlaw with cutoff didn't work before)
+
+
+
+ *** Version  0.9.4.2 (2005/10/01)
+
+   - general: added new tutorial macro macros/tutorials/threshold.C:
+     how to calculate the threshold
+
+   - general: added a new game. Start it from the interpreter with
+        MagicJam j; (other games are: MineSweeper, MagicSnake, MagicDomino
+                     and MagicReversi)
+
+   - general: neighbor pixels in MGeoms are now sorted clockwise
+
+   - merpp: made aware of new format 20050829-0
+
+   - callisto: New scale factors from muon analysis, stored in new 
+     resource file resources/calibration.rc
+
+   - callisto: MBadPixelsCalc now raises an error instead of simply stopping
+     the eventloop if something went wrong. This is necessary for the
+     automatic processing
+
+   - callisto: Implemented a new treatment for the time information 
+     developed by S.Ruegamer, this should give much better response than
+     the old very primitive algorithm. This is especially important
+     for bad pixels due to bright stars as Ceta-Tauri (btw: the old
+     treatment was buggy! As neighbor pixels to interpolate the 
+     arrival times always the pixels 0 to 5 were taken)
+
+   - callisto: In addition to the new treatment of arrival times the
+     decision of the treatment whether a pixel contains shower
+     information or not is used to improve the signal interpolation
+     further. Previously interpolated pixels showed a non-zero signal
+     do the peak searching signal extractors. Having a signal pixel
+     beside raised the signal above the cleaning level. Thus the
+     pixel survived cleaning to often but with a too low mean signal.
+     By replacing empty pixels with a gaus (mean and rms from the
+     corresponding Area entries in MPedPhotCam) this effect can
+     be supressed.
+
+   - callisto: The status "unmapped" (for pixel which cannot be interpolated)
+     got lost when the events were stored by the calibration... fixed.
+     (This was no problem for normal image cleaning because the pixel 
+      content was artificially set to 0 not surviving standard cleaning
+      algorithm)
+
+   - callisto: Fixed a bug which caused the random and peak-search pedestal
+     extracted with an extractor to be exchanged for the first (roughly)
+     500 events (*Extractor and *ExtractorRndm). 
+     (They were simply exchanged in callisto.cc) This bug might have been
+     introduced in Mars 0.9.4 when the order of calculation of the two
+     types of pedestal in callisto got exchanged. The bug only effects
+     the first seconds of data of each sequence.
+
+   - star: Taking the arrival time of Muons into account the calculation
+     of the parameters could be made independant of the noise 
+     (pedestal rms). The dependance was due to the bias of the peak search
+     extractor. Now only a ZA dependamcy is left which is not yet fully
+     understood.
+
+   - ganymed: The sequences were still not sorted correctly in any case, 
+     because they were sorted by the full qualified path name. Now they
+     are sorted by their sequence number.
+
+   - ganymed: new values for the spark-event-cut
+
+   - sponde: required missing MEnergyEst from ganymed.root... fixed.
+
+
+
+ *** Version 0.9.4.1 (2005/08/18)
+
+   - callisto: fixed some problems with the calibration in case of
+     inteleaved events. Therefor the final and some intermediate
+     fits are skipped which would take place on partly filled #
+     histograms and gave wrong results or failed completely.
+
+   - callisto: If the intermediate finalization of the histograms
+     calculating the mean charge of the calibration signal fails
+     it is counted now and printed in PostProcess of MCalibCalcFromPast.
+
+   - ganymed: Fixed some bugs which caused problems in On-only mode.
+     Still the false source plot doesn't give reasonable results.
+
+
+
+ *** Version 0.9.4 (2005/08/05)
+
+   - general: Fixed the ZA binning. It did not correctly fit the
+     MC binning
+
+   - general: Added a class to correct for the missfocussing in
+     April (MSrcPosCorrect)
+
+   - general: Random Forest energy estimator should now work properly
+
+   - general: MHCamera now displays the profiles in deg instead of mm
+
+   - general: MH::SetPalette offers a lot of new palettes
+
+   - general: MHillas - the case of CorrXY==0 is now handled properly
+
+   - general: implemented the possibility to change the line and
+     marker style of a sky-grid drawn by MAstroCatalog
+
+   - general: Runs in sequences and datasets are now automatically 
+     ordered (it is assumed that the order of their filenames correctly
+     represents the order of observations) to ensure correct reading
+     of the subsystem data
+
+   - general: Runs cannot be added to a sequence twice anymore. Also
+     Sequences cannot be added twice anymore to a dataset.
+
+   - general: fixed a bug in MAstro::Deg2Hms reported by Abelardo. 
+              It gave wrong results by 1./2pi
+
+   - showplot: got a new option to start a root interpreter, too
+
+   - mars: now displays a rough estimate of Disp and the third moment
+
+   - mars: now displays the event time MTime if available
+
+   - mars: show muon parameters graphically
+
+   - mars: now the file to open can be given as commandline
+     argument
+
+   - merpp: Added support for new arehucas version >= 200507190
+     implementing values for three temperature sensors in the
+     counting house (MCameraAUX) and the name of the HV settings file
+     (MCameraHV).
+
+   - merrp: Also fixed some problems with wrong versions numbers stated
+     by arehucas and implemented some fixed for old versions (<200407070)
+
+   - callisto: MCalibrationHiLoCam can now be printed from its context
+     menu, eg in the TBrowser
+
+   - callisto: fixed logain offset (fgOffsetLoGain) from 1.7 to
+       - 1.39 (MExtractTimeAndChargeSpline) 
+       - 1.40 (MExtractTimeAndChargeDigitalFilter)
+     This is important mainly for timing studies.
+
+   - callisto: Changed limits in MHCalibrationChargeCalc from
+       - -100.125 to -98   (fgChargeHiGainFirst)
+       - 1899.875 to 1902. (fgChargeHiGainLast)
+       - -100.25  to -99   (fgChargeLoGainFirst)
+       - 899.75   to 901.  (fgChargeLoGainLast)
+     Introduced new limits:
+       - fgNumLoGainBlackoutLimit: 0.05
+       - fgLoGainBlackoutLimit: 3.5
+       - fgLoGainPickupLimit: 3.5
+
+   - callisto: The handling of automatic weights for the digital filter 
+     has been improved. There are now new calibration weights special
+     for Monte Carlo calibrations.
+
+   - callisto: Updated Muon scale with latest results (1% difference
+     for most data, 5% for Mar/Apr'05)
+
+   - callisto: use a new criterium to exclude bad pixels: If the high-gain
+     was saturated and the blackout-events in the low-gain exceed the 
+     fNumLoGainBlackoutLimit, the pixel is declared unsuitable.
+     This excludes those pixels which have a saturating high-gain 
+     channel, but the low-gain switch does not switch often enough 
+     to make the distribution reliable.
+
+   - callisto: fix a bug counting the number of saturated events. Up to now,
+     the number of saturated slices was counted (which is one for a not too
+     high number), but for some (pathological) pixels, many more slices
+     saturated and produced wrong limits.
+
+   - callisto: New options in in callisto.rc for MCalibrationRelTimeCalc:
+     + MCalibrationRelTimeCam.CheckFitResults: Yes
+     + MCalibrationRelTimeCam.CheckDeviatingBehavior: Yes
+     + MCalibrationRelTimeCam.CheckHistOverflow: Yes
+     + MCalibrationRelTimeCam.CheckOscillations: Yes
+
+   - callisto: introduce max. number of events for intercalibration, 
+     the rest gets skipped. Default: 4096
+     The calibration causes too many un-reliable pixels if more 
+     than about 5000 events are treated (@500 Hz) because of the
+     mode hopping of the VCSels. However, in the past, some 
+     calibration runs have been taken (erroneously) with more 
+     than 5000 events, especially the intensity scans where  
+     a good precision is needed.
+
+   - callisto: Set UseExtractorRes to kTRUE, will raise the number of 
+     photo-electrons for the spline extractor by 1-2% (correctly).
+
+   - callisto: The intercalibration is now done using a full f-factor
+     method instead of a simple update. This makes things slower but
+     more reliable in terms of gain-fluctuations and sudden VCSEL gain
+     changes.
+
+   - callisto: MPedestalY3 now uses the same extraction range as the data
+     as calculated by MPedestalY2
+
+   - callisto: A check of the fraction of allowed unsuitable (10%) and
+     unreliable (30%) pixels has been addded when the conversion is 
+     calculated from interleaved events
+
+   - star: fixed a bug which caused MEffectiveOnTime containers not to
+     be written. In the worst case they were skipped almost all, in the
+     best case they were all ok. It depends on how often the new value
+     was assigned just with an event which was skipped later by another
+     task
+
+   - star: new histograms MHPointing and MHRate
+
+   - star: New tab (Currents) displaying the time evolution of the mean 
+           DC currents
+
+   - star: New tab (MeanRms) displaying the time volution of the mean
+           Pedestal Rms
+
+   - star: Output now contains MReportStarguider
+
+   - star: Improved muon analysis. Due to the absense of a constant
+           for the gaus fit for arc width and the fact that the arcwidth
+           plot was a histogram instead of a profile the resulting psf
+           became pedestal rms dependant
+
+   - ganymed: added new plot (MHPhi) for wobble mode as described in
+     http://www.astro.uni-wuerzburg.de/results/ringmethod/
+
+   - ganymed: corrects now (correctly?) for the misspointing in 
+              May/April 05
+
+   - ganymed: Two new default templates for ganymed.rc are avilable:
+              ganymed_onoff.rc and ganymed_wobble.rc
+
+   - ganymed: The first version of MFMagicCuts has been released
+
+   - ganymed: the Conc1 plot was incorrectly scaled in MHVsSize
+
+   - ganymed, sponde: There are two new options to determin the number
+     of bins for the signal region (NumBinsSignal) and the number of
+     total bins (NumBinsTotal) in the MHThetaSq histogram
+
+   - ganymed: optimized palettes for MHDisp
+
+   - ganymed: Fixed an important bug when using ThetaSq as fit function:
+     The result for the sigma of the gauss(sqrt(x)) fit was a factor
+     sqrt(2) to large
+
+   - ganymed: The false source plot (MHDisp) is now based on Disp
+     and a background model determined in the first loop is
+     subtracted
+
+   - ganymed: MFMagicCuts are now available in the cvs. The correct
+     solution for the disp ambiguity problem is now calculated using
+     the third moment. The third moment cut therefor is skipped.
+
+   - ganymed: Output now contains "Disp [MParameterD]" which sign is
+     already determined by the third moment along the major axis and
+     so its actual sign is aligned along the major axis of the shower.
+
+   - ganymed: If starguider data is available it is taken into account
+     when calculating the source position. This is especially important
+     for wobble data at high zenith angles and culmination data.
+
+   - ganymed: If available the starguider data is taken into account as
+     good as it is possible without a starguider calibration. To switch
+     it off add
+        MPointingDevCalc.MaxAbsDev: -1
+     to your ganymed.rc
+
+   - sponde: the zenith angle distribution is now weighted instead of
+     choosen by default. This gurantees higher statistics in the highest
+     and lowest energy bins. To switch this behaviour off use...
+
+   - sponde: now automatically displays the energy threshold
+
+
+
+ *** Version 0.9.3 (2005/06/03)
+
+   - general: MMcEvt now derived from MMcEvtBasic which should 
+     have no influence on compatibility with older camera files
+
+   - general: Implemented a new option to MReadReports which allows
+     to force reading of the first event of some trees (eg. Drive-tree)
+     before any other tree.
+
+   - general: Made a fix to MPointingPosCalc which assumes that the
+     run-type is real-data if Process is called before ReInit, such
+     that also the very first Drive-events in a run are treated 
+     correctly.
+
+   - shoplot now displays the filename in the title bar of the window
+
+   - merpp: new options: --auto-time-start --auto-time-stop which
+     allow to cut updating with slow-control at the start- or 
+     (previousle --auto-time only allowed: and) stop-time of
+     the run stored in the runheader.
+
+   - callisto: changed default of fgFallTimeHiGain in 
+     MExtractTimeAndChargeSpline from 1.5 to 0.5. 0.5 was
+     already set as default in callisto_Dec04Jan05.rc
+
+   - callisto: the digital filter (MExtractTimeAndChargeDigitalFilter)
+     now changes the filename for new weights automatically for
+     cosmics, MC and for different calibration colors.
+
+   - callisto: a problem with the order of some code cause the
+     name of the weights file in MPedestalY2 to be ignored.
+     Wrongly the calibration_UV weights were used instead
+     of the cosmics weights set in callisto.rc.
+
+   - callisto: should allow ct1 pulser data when the color is
+     explicitly set also for pretty new runs
+
+   - callisto: a new option (MCalibrateData.ScaleFactor) allows
+     to introduce an additional scale factor (should be around 1)
+     to adapt for slight deviations in different extractors from
+     the MC calibration. For MC calibrations the scale factor
+     is fixed to 1
+
+   - callisto: MFCosmics should handle very high signals a bit
+     more accurate now
+
+   - callisto: when calculating the mean pedestal rms for different
+     pixel sizes or sectors also kUnsuitableEvt is now taken into
+     account - not only kUnsuitableRun
+
+   - callisto: '-raw' option is now the default
+   
+   - callisto: A dead pixel check has been implemented in MJPedestalC2.
+     This has the advantage that mean values in the calibration (eg
+     arrival times) are calculated more accuratly.
+
+   - callisto: In the resource file callisto_Dec04Jan05.rc
+     MJPedestalY2.ExtractWinRight has been reduced from 4.0 to 2.0
+
+   - callisto: new Hi-/Lo-Gain intercalibration constants
+     hilocalib_sp1.root and hilocalib_sp1_mc.root
+
+   - callisto: changed default for MJPedestalY2.MaxEvents
+     from 2000 to 5000 like in callisto_Dec04Jan05.txt
+
+   - callisto: in MCalibrationChargeCalc the limit fgPheErrLowerLimit
+     has changed from 9.0 to 6.0. This is necessary to exclude two very
+     ringing pixels in September which - when kept - destroy the image
+     cleaning around them (Markus G.)
+
+   - callisto: (!) The Muon analysis of all data taken so far has
+     suggested that different extractors give slightly different
+     absolute results after calibration, due to there different
+     handling of the calibration- and cosmics pulse shape. Although
+     the over all calibration seems to be a bit to pesimistic (or 
+     the MC seems to be a little bit - 3-5% - too much attenuated).
+     There for correction factors have been introduced which correct
+     the calibration constants by
+         0.956937799 for Digital Filter (callisto.rc)
+     and
+         0.904159132 for Spline (callisto_Dec04Jan05.rc)
+     calibration. The main advantage is, that both data types can
+     be easily analysed together and compared to the same MC sample.
+     The factors are choosen such, that the reference is now a 
+     Monte Carlo sample calibrated with Digital Filter (callisto.rc)
+
+   - star: fixed a bug which caused the first bin of the histograms
+     vs time to disapear in PostProcess. This gave wrong results
+     on the screen. The output and all following programs not
+     directly accessing the histograms haven't been affected
+
+   - star, ganymed: Made sure that always the first Drive-tree event
+     is read and Processed before the first data event was read.
+
+   - ganymed: implemented the possibility to replace the standard 
+     false source plot with a different one. For example: If
+     you want to use a Disp based FS plot use the resource:
+       NameHistFS: MHDisp
+     For details about the requirements of these plots look
+     at the corresponding classes
+
+   - MJOptimize: For On/Off and Wobble optimization MJOptimize
+     has been replaced by MJOptimizeCuts. To use MHThetaSq instead
+     of MHAlpha call MJOptimizeCuts("MHThetaSq"). Make sure in this
+     case MAlphaFitter is setup correctly. For On-Only optimization
+     MJOptimize has been Replaced by MJOptimizeCuts, too. Call
+     RunOn() instead of Run(). For energy estimation MJOptimize
+     has been replaced by MJOptimizeEnergy
+
+   - sponde: The input MC spectrum can now be weighted to fake a
+     different spectrum. This is done via MMcSpectrumWeight. For
+     more details see the class description and sponde.rc
+
+   - sponde: The paremeter comparsion plots are not scaled by
+     their entries anymore. Instead the MC plot is scaled by using
+     the result spectrum of the analysis. If the input MC spectrum
+     and the result spectrum has different slopes the absolut 
+     normalization is normally wrong.
+
+
+
+ *** Version 0.9.2 (2005/05/20)
+
+   - general: Changed the default paths for calibrated data and image
+     files. (The implemented access to these files doesn't yet exist)
+
+   - general: support for MRunIter has been removed from the job classes
+     (use the setter functions of MSeqeunce instead)
+
+   - general: ProcessFile has been renamed to Process in all job classes,
+     because ProcessFile is missleading
+
+   - general: The storage of the palette in MHCamera is now possible
+
+   - general: new bits describing unsuitable and unreliable pixels have
+     been introduced in MBadPixelsPix: kPreviouslyExcluded, 
+     kDeadPedestalRms, kFluctuatingArrivalTimes
+
+   - general: fixed reading of CC-REPORTS (weather data) for Arehucas file
+     versions newer than V200404070 
+
+   - general: support for cc file versions newer than V200504130. Added
+     support for active loads (MCameraActiveLoad) and central pixel
+     (MCameraCentralPixel)
+
+   - general: added new histograms for image parameters versus size
+     (MHVsSize)
+
+   - general: The eventloop now automatically calls PrintStatistics
+
+   - Status Display: Improved support for printing:
+     + A default can now be set in .rootrc (for more details see 
+       MStatusDisplay::PrintPS)
+     + A print dialog is opened so that printer and command line
+       can be canged
+
+   - showlog: improved such that it handles different verbosity levels
+     more accurate now. This mean you can suppress output when
+     using showlog.
+
+   - showplot: improved
+     + The new graphics formats have been implemented 
+       (pdf, svg, png, jpg and xpm)
+     + Implemented an interface for printing. Because you can change
+       the printing command from the command line you can use all
+       the nice postscript tool. To print a booklet for example call: 
+       showplot -b --print --print-cmd="cat %f" filename.root | lpr
+       showplot -b --print --print-cmd="psbook %f | psnup -2 | lpr" filename.root
+       showplot -b --null --print --print-cmd="psbook %f" filename.root > book.ps
+
+   - callisto: fixed a bug in the recognition of the calibration bit
+     pattern. Concerns only intensity calibration. (The strength of the 
+     intensity has been updated in some cases)
+
+   - callisto: add a filter against PIN Diode events when running over
+     calibration runs since some of the recent calibration runs have
+     been taken with Pin Diode.
+
+   - callisto: added support for the runs 39942, 39944, 44834, 39941,
+     39943, 44833 in the calibration (MCalibColorSet)
+
+   - callisto: MJCalibration.MHCalibrationChargeCam.ProbLimit has
+     been set to 1e-18 in callisto_Dec04_Jan05.rc
+
+   - callisto: in callisto_Dec04Jan05.rc: set value for 
+     MJPedestalY2.MaxEvents from 2000 to 5000 to get better 
+     statistics for the calculation of the mean pulse time 
+     of the cosmisc
+       
+   - callisto: the charge limit in the calibration has been raised 
+     from 2.5 to 4.5
+
+   - callisto: new setup read from callisto.rc
+     + MCalibCalcFromPast.fNumEventsDump
+     + MHCalibrationChargeCam.NumHiGainSaturationLimit
+     + MHCalibrationChargeCam.NumLoGainSaturationLimit
+
+   - callisto: MExtractTimeAndChargeSpline extractor:
+     + The integration ranges were shifted by 0.2 FADC slices to the right. 
+     + unreliable handling of floating point values caused different
+       results on different platform or with different compiler options:
+       The new algorithm is numerically exact and more accurate because
+       it doesn't calculate the integration position by multiple times
+       adding the step-size (which results in numerical uncertanties
+       exspecially if multiplied with large numbers)
+     + A lot of fixes have been introduced which effects integrating the
+       spline at the edges of the valid range. In this case any memory
+       was randomly accessed. This behaviour can be tested replacing
+       all MArrayF by TArrayF which perform a range check (but of course
+       they are a lot slower)
+     ! No result obtained with the Spline before can be trusted! Due to
+       random memory access it might by completely random!
+
+   - callisto: set new defaults in MExtractTimeAndChargeDigitalFilter:
+     + extraction range in the high gain to 4.
+     + weights file to cosmics_weights46.dat
+
+   - callisto:
+     + introduce the check for fluctuating arrival times.
+     + set charge limit to from 2.5 to 4.5
+     + introduce asymmetric exclusion due to "deviating number of phes":
+       Default: -9.0 +4.5
+     + make deviating number of phes unsuitable (see David's findings).
+
+   - callisto: fixed the display of unsuitable pixels. The old change
+     to a real profile in MHCamera broke it.
+
+   - callisto: The cosmics filter is used in MJCalibration now 
+     independant of the pulser color (formaly it was used only for 
+     CT1-pulser data). The threshold of number of max empty pixels 
+     has been raised from 2% to 5% in MJCalibration. The maximum
+     fraction of rejected event is 50% otherwise the calibration has
+     failed. The filter now ignores unsuitable pixels.
+     Setup the filter from callisto.rc using "ContCosmics"
+     (see MFCosmics::ReadEnv)
+
+   - callisto: changed default for fgOffsetFromLogain back
+     from -2.8 to -1.8 in digital filter. 
+
+   - callisto: for the common extractors 
+      + MExtractFixedWindow
+      * MExtractTimeAndChargeSlidingWindow
+      * MExtractTimeAndChargeSpline
+      * MExtractTimeAndChargeDigitalFilter
+     the hi- and lo-gain reolution is stored in fResolutionPerPheHiGain
+     and fResolutionPerPheLoGain
+
+   - callisto: Updated the hi-/lo-gain intercalibration constants
+     hilocalib_sp1.root, hilocalib_df46_mc.root, hilocalib_df4.root, 
+     hilocalib_df6.root
+
+   - callisto: The default lo-gain extraction window for the
+     MExtractTimeAndChargeSlidingWindow extractor has been increased 
+     from 6 to 8 to take the stretch of the pusle into account
+
+   - callisto (!!!): fixed an important bug in the setting of the 
+     incoming pedestal pointer to the signal extractor extracting
+     pedestals. This bug caused the pedestals not to be subtracted 
+     correctly in the calibration afterwards. The effect was about 10% 
+     too high conversion factors for the digital filter and the spline
+     and more than 40% for the sliding window. 
+     The bug existed since end of February! (Markus G.)
+
+   - star: added muon support to star. A new tab "MHMuonPar" is
+     displayed. The lower right plot is an estimate of the point spread
+     function. A reference value is displayed. To get the real PSF
+     you must compare with MC. The setup for the muon analysis
+     is done in star.rc. More informations can be found in
+     MHSingleMuon and MHCalibParCalc
+
+   - star: The weather data is now displayed in star
+
+   - star: MEventRateCalc handles the calculation of the event rate more
+     accurate now in case of the start of a new run inside a sequence
+
+   - ganymed: a bug in MSrcPosCalc has been fixed (The changes were taken
+     from a bugfix of Wolfgang to Loc0LocToCam; Wolfgang: the results are
+     changed only minimally
+
+   - ganymed: (MJCut and MJOptimize) now displayes the number of 
+     excess events versus size. The energy estimation is done in
+     MJSpectrum (sponde)
+
+   - ganymed: got support for using other variables than Alpha, eg. Theta.
+     Therefor you need a class deriving from MHAlpha which supports
+     this variable (one is already existing: MHTheta, which is now the
+     default in ganymed). It is setup through ganymed.rc
+
+   - added a full featured spectrum program (sponde) which reads
+     ganymed output and monte carlos and compiles a spectrum
+
+
+
+ *** Version 0.9.1 (2005/04/14)
+
+   - Fix bug on the arrival time reconstruction when using Digital
+     Filter (in some marginal cases (10%) times were reconstructed shifted
+     by 0.2 slices)
+
+   - all executables now return 2 where in previous versions -1 has
+     been returned (gave problems with shell-scripts)
+
+   - the Hi-/Lo-Gain intercalibration for monte carlo files is now
+     also done with a intercalibration input file
+
+   - a bug in the time fine adjustment of the digital filter has been fixed
+
+   - a lot of small fixes to calling TPad::Divide with a margin==0
+
+   - MStatusDisplay now shows the memory usage
+
+   - added a memory leak statistic after the eventloop
+
+   - MHadronness replaced by MParameterD
+
+   - MEnergyEst replaced by MParameterD
+
+   - wobble mode can now be switched on from the data-set
+
+   - switched on bad pixel detection for a pedestal level
+     which is more than 5 times the variance
+
+   - Fixed default paths to be correct for the new data center
+
+   - Fixed handling of drive data. The pointing position in now
+     copied to MPointingPos inside star for real and MC events
+
+   - made sure, that the sequences in a dataset are sorted by
+     their number to ensure the correct synchronization
+
+   - added all resource files necessary to handle spline extraction
+     of signal for the late 2004 and the early 2005 data
+
+   - update the reference lines for the december data
+
+   - changed default for fgHiGainFirst from 2 to 0 in spline extractor
+     This is important for the Dec. and Jan. data where the calibration
+     pulse position changes much.
+
+   - changed default for fgOffsetFromLogain from -1.8 to -2.8 in digital
+     filter. This corrects only an defective extraction of the MC at 
+     low-gain signals lower than 90 phes.
+
+   - fixed some slowdown in calibrating data with interleaved events from
+     Jan and Dec. As a workaround made the pretty palette the default. 
+     The inverse Deep Blue Sea has a bug which slows down long calibration
+     runs a lot.
+
+   - implemented new values from new starguider report as defined
+     in TDAS00-07 V7.1 (eg SkyBrighness)
+
+   - Fixed the formerly wrong unit of azimuth and zenith angle deviation
+     in starguider report (If you merpp the same reports with this version
+     you'll get the correct units (arcmin) but a different result
+     than with old versions (wrong units))
+
+   - Now the status display can also write PNG, JPEG and XPM (other file
+     formats are still unsupported by root)
+
+   - added a lot of scripts and macros in directory datacenter used
+     for automatic processing
+
+
+
+ *** Version 0.9 (2005/03/23)
+   
+   - Calibration is now done autmatically into photo-electrons like 
+     decided by the Collaboration Board
+ 
+   - Reference lines in the display can be read from resource file
+
+   - Interlaced calibration events can be handled by callisto 
+
+   - Hi-Gain vs. Lo-Gain calibration constants can be calculated
+     and applied in callisto.
+
+   - class MJCalibTest can be called by callisto
+
+   - callisto can now run with three data types: rawdata, rootdata, MC
+
+   - added two classes mreport/MReportStarguider.cc and 
+     mreport/MReportStarguider.h for implementing starguider-data
+     
+   - the output of merpp-update now contains starguider information:
+     MReportStarguider and MTimeStarguider
+   
+   - Fixed bug in MHHadronness.cc which made that the displayed Q-factor 
+     values were lower than they should. This was more visible for high
+     energy (Size) events.
+
+   - Made MExtractTimeAndChargeDigitalFilter the default for callisto
+
+   - added a new loop to callisto to support the correct extraction of 
+     the pedestal and pedestal rms through the signal extractor
+
+   - added class to perform fourier tranformation of a hexagonal structure
+     (MHexagonalFT)
+
+   - added class to perform fourier tranformation of a hexagonal structure
+     in a tasklist (MHexagonalFTCalc) example: hft.C
+
+   - added class to enhance the MCerPhotEvt from the Magic camera geometry
+     MGeomCamMagic to a enhanced geometry MGeomCamMagicXT having only
+     small pixels, example: extendcam.C
+
+   - added possibility to write data to memory (TTree) using MWriteRootFile
+
+   - added possibility to read a TTree stored only in memory by MReadTree
+
+   - new classes to deal with the interleaved calibration events:
+     MTriggerPattern, MTriggerPatternDecode and MFTriggerPattern
+
+   - implemented filters to callisto to skip calibration events
+
+   - changed callisto to calculate three kinds of pedestals and pedestal rms:
+     + fundamental pedestal (MPedPhotFundamental): extracted directly from
+       the slices by statistics                              
+     + pedestal from extractor (MPedPhotFromExtractor): extracted with the
+       signal extractor without randomization
+     + random pedestal from extractor (MPedPhotFromExtractorRndm): extracted
+       with the signal extractor with randomization (extraction window is 
+       randomly fixed)
+     The three kind of pedestal is not yet implemented (for speed reasons) as
+     long as nobody really needs it:
+     + pedestal from extractor with randomizatiuon (MPedPhotFromExtractorRndm): 
+       extracted with the signal extractor with randomization
+
+    - callisto now finds the pulse position in the data automatically
+
+    - implemented data reduction in calibrated data by reducing the precision
+      of the stored floating point values (pedestal, rms and signal) to
+      roughly 0.5%
+
+    - fixed showplot to make file format conversion (eg. converting a
+      status display stored in a root file into a postscript file) in
+      batch mode possible:
+      showplot -b --save-as-ps[=outfile.ps] infile.root
+
+    - Allow class names as part of filter rules, eg
+      (MFSupercuts) && (MHillas.fSize>100)
+
+    - fixed a lot of stuff to allow all programs to process MonteCarlo
+      camera files.
+
+    - enhanced possibility to debug reading of resource file
+
+    - MDataChain should handle priorities of operator more 
+      accurate now
+
+    - completely revised the container in which the signal is stored
+      MCerPhotEvt/Pix, MArrivalTime --> MSignalCam/Pix
+       * the new implementation is faster and
+       * needs less storage space
+
+    - FIRST version which can process Monte Carlos through the 
+      whole chain of programs (callisto, star, etc)
+
+    - implemented new image parameters for the border length of
+      the shower image (MNewImagePar2)
+
+    - implemented wobble-mode in ganymed
+
+    - new class (MJOptimize) taking care of all optimization processes
+
+
+
+ *** Version 0.8.6 (2004/10/05)
+
+   - New combined signal and time extractor 
+     MExtractTimeAndChargeDigitalFilter
+
+   - The Report for the trigger section in the CC run summary has been
+     updated, and now the IPRs (Individual Pixel Rates) are available.
+
+   - new macros for database interaction: filldotrun.C, filldotrbk.C
+
+   - added new program which can convert colored output which was redirected
+     into a file back into colored text (for example to display it with
+     more): showlog
+
+   - added new program to display an MStatusArray of plots (stored with
+     MStatusDisplay) from a file: showplot
+
+   - Added support for Sequences (MSequence). Sequences are blocks of run
+     files containing the same calibration and belonging to the same 
+     source
+
+   - Added a new task (MTaskEnv) which can be used in setup files to switch
+     between different tasks (for example to choose a signal extractor)
+
+   - Implemented automatic file splitting in MWriteRootFile
+
+   - After image cleaning an island index is assigned to all used pixels.
+     The index corresponds to the order of the islands in size.
+
+   - added a cleaning which takes signal height _and_ arrival time into
+     account: probability cleaning (for more details see MImgCleanStd)
+
+   - added a cleaning which takes takes the absolute number of photons
+     times the area ratio as cleaning level 
+     (for more details see MImgCleanStd)
+
+   - Changed calculation of image parameters such, that it can be done
+     for all used pixels or the pixels with a defined island index only
+
+   - implemented new image parameters displaying the number of islands,
+     saturated hi-gain and lo-gain pixels (MImagePar, MHImagePar)
+
+   - event display in executable changed to support also calibrated files
+     (done with MJCalibrateSignal)
+
+   - added program doing the calibration and the signal extraction
+     and signal calibration: callisto Most part of the setup is done
+     by a resource file: callisto.rc
+
+   - implemented support for pixels with negative IDs (Raw file format
+     version 4)
+
+   - implemented an new option in merpp (--auto-time) to get the time
+     range for cc and/or caco data from the run header of the raw data
+
+   - New star-program (star and MJStar). Taking calibrated data from
+     callisto/MJCalibrateSignal as input. The setup is done through
+     a resource file: star.rc
+
+   - Added possibility to setup the eventloop in the mars-executable
+     Camera Display by a resource file: mars.rc
+
+   - The the mars-executable Camera Display can now also read
+     calibrated data files written by callisto/MJCalibrateSignal
+
+   - Added a new class which can calculate the source position in
+     the camera from a pointing model known to be correct and
+     the pointing model used for observations (MSrcPosFromModel)
+
+   - added a new version of the class calculating the effective on-time
+     MHEffectiveOnTime. It unifies the old classes MHEffOnTime, 
+     MHEffOnTimeTime, MHEffOnTimeTheta, MHTimeDiff, MHTimeDiffTime and
+     MHTimeDiffTheta.
+
+   - added the possibility to count how often a signal is above (or 
+     below) a certain threshold in MHCamEvent and MHCamEventRot (this
+     can replace MHTriggerLvl0)
+
+   - added ore convinient ways to set the axis-titles of your histograms
+     in your macro to some MH-classes like: MH3, MHVsTime, MHSectorVsTime,
+     MHPixVsTime, MHVsTime, MHCamEvent and MHCamEventRot
+
+
+
+ *** Version 0.8.5 (2004/08/06)
+ 
+   - new Signal Extractors: MExtractFixedWindowSpline 
+     and MExtractAmplitudeSpline
+
+   - implementes interleave in merpp to be able to merpp parts of a file
+
+   - implemented force-functionality to merpp
+
+   - star display to display star catalogs (MAstroCatalog)
+
+   - star display to 'mirror' stars to the camera (MAstroCamera)
+
+   - implemented a new cleaning option which allows cleaning scaled with
+     the real ratio of the rms depending on the pixel size, not only the
+     square root of the pixelsize (MImgCleanStd, MCameraData)
+
+   - removed obsolete MBlind* classes
+
+   - Signal extractor taking the AB flag into account implemented (this makes
+     an odd number of slices for signal extraction possible
+     (MExtractSignalABcorr)
+
+   - implemented a class extracting the pedestal from the raw-data (events)
+     itself using empty lo-gain (MpedCalcFromLoGain)
+
+   - Added mean values to MPedPhotCam
+
+   - Added Makefile for Darwin (this OS is NOT officially supported!)
+
+
+
+ *** Version 0.8.4 (2004/04/19)
+
+   - new fast arrival time extractor using cubic splines: 
+     MExtractTimeFastSpline
+
+   - implementes multi-argument support in MDataChain
+     ("pow(a, b)")
+
+   - implemented double reference support in MDataChain
+     ("MCameraLV.fPowerSupplyA.fVoltagePos5V")
+
+   - added support in MF for expressiond like 
+     "MHillas.fWidth<2*<MHillas.fLength"
+
+   - MDataChain is now able to support variables like [0], [1], ...
+     which can be used in fit functions as parameters. The interface
+     is implemented through the new virtual function 
+     MParContainer::SetVariables
+
+   - added new class MArrivalTimeCam/MArrivalTimePix:
+     Storage containers to hold the ArrivalTime of the camera/pixel
+
+   - added new classes for the calibration of relative arrival times:
+     MCalibrationRelTimePix and MCalibrationRelTimeCam
+  
+   - added new classes to extract the signal of the blind pixel and the 
+     PIN Diode separately: MExtractBlindPixel and MExtractPINDiode
+
+   - added new classes for the bad-pixels treatment (MBadPixels*)
+     which are more powerfull than the old ones (MBlindPixel*)
+     and will replace them.
+
+   - added filter against cosmics: MFCosmics
+
+   - added new class MArrivalTimeCalc2:
+     Calculates the arrival time as the signal weighted mean of the time 
+     slices in the maximum window
+
+   - added a new macro call pointspreadfucntion.C that fits with a 2D 
+     gaussian the DC spot for an star. It gives you the RMS of
+     the PSF and the center of the star, very useful for misspointing 
+     studies.
+
+   - added support for multi-telescope camera files. Added classes 
+     MStereoCalc and MStereoPar, classes to calculate and store shower
+     parameters calculated from the data of two telescopes, for the MC
+     studies regarding the MAGIC clone.
+
+   - added MMcCalibrationCalc, MMcCalibrationUpdate, classes to obtain
+     MC data calibrated in photons instead of ADC counts.
+
+   - added three macros to show the calibration and analysis chain of 
+     MC data. The macro starmc.C does both calibration and analysis, producing
+     an output containing Hillas parameters for each event. The macro 
+     mccalibrate.C does just the calibration and writes out a file containing
+     pixel information in photons instead of FADC data. The macro starmc2.C
+     reads in such a file and produces an output with Hillas parameters.
+
+   - added MPedPhotCalc to compute pedestals in units of photons, see
+     macro pedphotcalc.C
+
+   - added all class to perform the calibration, see macro calibration.C
+
+   - added class MFFT to perform Fast Fourier Transforms
+
+   - added class MSimulatedAnnealing to perform simulated annealing 
+     minimizations
+
+   - added new macro bootcampstandardanalysis.C which holds the skeleton
+     of the analysis chain discussed in the december bootcamp. 
+
+   - added support for DAQ raw data file format V2
+
+   - implemented an arbitrary time stamp for the events from raw-data
+     files with file version<3. It is calculated from the run number, 
+     the date of start and the FADC clock tick from the first module
+
+   - implemented the correct decoding of the event time-stamp
+     coming from the DAQ for raw-data files with file-version>2
+
+   - added a new classes storing the pedestals in units of photons: 
+     MPedPhotPix, MPedPhotCam
+
+   - added support for DC current files from the camera control
+
+   - added support for start- and stop-time when merpping report files
+
+   - added MReportCC storing the weather data from the CC-REPORT
+
+   - added class to fill trainings and test matrices (MTFillMatrix)
+
+   - added a filter performing a software trigger (MFSoftwareTrigger)
+
+   - Added classes to perform parts of the standard analysis (Jobs):
+     + MJPedestals
+     + MJCalibration
+     + MJExtractSignal
+     Note: All of them are preliminary!
+
+   - Added Iterator to iterate over files giving only the run-number
+
+   - Added class (MHSectorVsTime) and example (sectorvstime.C) to plot
+     the evolution of a sector vs time
+
+
+
+ *** Version 0.8.3 (2003/12/05)
+
+   - adapted Random Forest classes to allow the use with MC
+     multi-telescope files which can be produced with the coming
+     camera version 0.7.
+
+   - added classes to read and interprete central control report files
+     (Directory: mreport, Base-Class: MReport, Reader: MReportFileRead, ...)
+
+   - enhanced merpp (the executable) to support .raw and .rep files.
+
+   - added classes for light calibration (MCalibration* and 
+     MHCalibration*) by Markus Gaug. Further work has to be and will
+     be done soon.
+
+   - Added a preliminary 'synchronizer' (MReadReports) which will 
+     replace MReadMarsFile as soon as it is finished.
+
+   - Added a tutorial macro demonstrating how report files are merpped
+     and how they can be read from the root file in the correct order
+     of time (readrep.C)
+
+   - Added a generalized histogram (similar to MH3) called MVsTime
+     which allows to plot variables (or rules - MDataChain - of
+     variables) vs time. For an example have a look at tempvstime.C.
+
+   - Changed the name of the event trees:
+       + Events    --> Events
+       + PedEvents --> Pedestals
+       + CalEvents --> Calibration
+
+  - changed name of MTime in the event trees from MRawEvtTime to MTime
+
+  - added displaying the sector indices to the mars event display
+
+  - Magic Online Analysis (MOnA) implemented in a first version
+    (see mona.cc, MOnlineDump and MOnlineDisplay)
+
+  - added classes to calculate event rate
+    (preliminary: MEventRateCalc, MEventRate)
+
+  - added new executable 'readdaq' to read *.raw files from the DAQ directly
+
+  - added classes dealing with the telescope pointing position (MPointing*)
+
+  - implemented the 'final' Mars time stamp based on some experiences with
+    the new 'Synchonizer'
+
+
+
+ *** Version 0.8.2 (2003/11/10)
+
+   - accelerated standard analysis by a factor of 6-8 ...
+     + doing precalculations in MGeomCam for the pixel area ratio
+     + creating a look up table for the single pixels in MCerPhotEvt
+
+   - added task to calculates weights in case you want to 'change'
+     the energy spectrum of a monte carlo file 
+     (MMcWeightEnergySpecCalc - Great work from Marcos Lopez Moya)
+
+   - added a new executable star which implements the
+     star.C macro as precompiled executable. Currently a flexible
+     setup is not possible, but a 'input card' setup will follow.
+
+   - Starting to implement Multi-Telescope-Support based on the 
+     upcomming camera version 0.7. The base for a general support
+     is implemented and the star-functionality is proven to work.
+
+   - Replaced Event-Display in and Camera-Display in the Mars GUI
+     executable by a more convinient display base on MStatusDisplay.
+
+   - fixed the algorithm for the blind pixel treatment (MBlindPixelCalc)
+
+
+
+ *** Version 0.8.1 (2003/10/20)
+   
+   - added signal subtraction for pure on data by means of fitting
+     the background in the off region or by performing a combined
+     signal/background fit. Provides necessary histograms for
+     obtaining energy spectra and a light curve.
+
+   - added classes to perform and study the selection of the 
+     2nd Level Trigger on MC data (example in triglvl2.C macro)
+
+   - added pedestal calculation
+
+   - implemented "democratic cleaning" (tail cut value proportional 
+     to pixel area) according to Wolfgang's suggestion.
+
+   - added Sigmabar treatment (calculation and basic histogramming)
+
+   - added basic routines to apply padding
+
+   - added first implementation of MARS-based source visibility plotter
+     (needs to be linked against slalib, preliminary version)
+
+   - enhanced functionality of data chains: random numbers, conversion
+     functions and access to MHMatrix objects
+   
+   - fixed some bugs in the CT1 Preproc file reader, which gave wrong
+     numbers under certain circumstances (runs with 0 events included)
+
+   - fixed a bug in the general filter MF (didn't work on some systems
+     at all)
+   
+   - fixed a bug in chaining files, which caused the analysis to crash or
+     ignore files
+
+   - implemented more geometry classes describing the parameters used
+     to simulate the PMT camera
+
+   - added new Monte Carlo classes containing the setup of the different
+     programs in the MC chain.
+
+   - added a (preliminary) general task to evaluate chi-square of a given
+     parameter in an eventloop.
+
+   - first implementation of a container describing the observatory
+     location (Long, Lat, etc)
+   
+   - added Random Forest - method for g/h-separation
+
+   - made compatible with the latest PRO version of root (3.04/02 and 3.05/07)
+     (this means, that it is compiling, but not yet fully tested)
+
+   - added a new status display which can show the present status
+     of histograms while an eventloop is running (MStatusDisplay,
+     an example can be found at status.C)
+
+   - reorganized directories:
+     classes describing the image              --> mimage
+     classes containing Monte Carlo Histograms --> mhistmc
+     classes for Random Forest method          --> mranforest
+
+   - added (event-)weights to fill histograms
+
+   - colors in logging output to screen
+
+   - changes to the Image Parameter declaration:
+       + moved fConc, fConc1 from MHillasSrc to MNewImagePar
+       + moved fNumUsedPix, fNumCorePix from MHillas to MNewImagePar
+       + MHillasExt now derives from MParContainer instead of MHillas
+     --> Files written with the old definition are more or less unreadable
+
+   - reading of reflector files
+
+   - display data from reflector files in the camera
+
+   - implemented currents (and display them in the camera)
+
+   - logarithmic scale in camera
+
+   - added class to iterate through directory contents (MDirIter)
+
+
+
+ *** Version 0.8 (2002/11/18)
+
+   - added all subdirectories as Include-Paths for ACLIC (s. rootlogon.C)
+
+   - corrected 48(!) wrong entries in the Next Neighbor table of the
+     Magic Camera (all in the inner part of the outer ring, mostly 
+     missing a single NN)
+
+   - Fixed a bug in the table describing the Next Neighbours of the
+     CT1 camera (a pixel 127 doesn't exist and the pixel 126 didn't
+     have any neighbour)
+
+   - changed trigrate.C: now it calculates the pure NSB triggers from
+     a camera file (generated with no showers), so there is no need
+     to introduce them by hand in the BgR array (for more details
+     please ask Abelardo)
+
+   - added MHHadronness (and MHadronness) as a general facility to evaluate
+     the quality of a gamma-hadron seperation method
+
+   - changed MWriteAsciiFile to accept rules (MDataChain)
+
+   - Calls to MWriteAsciiFile::AddContainer and MWriteAsciiFile::AddRule
+     must be replaced by calles to MWriteAsciiFile::AddColumn and
+     MWriteAsciiFile::AddColumns. Be carefull, the arguments have slightly
+     changed.
+
+   - Implemented generalized event-matrices (one row per event)
+     (MHMatrix)
+
+   - implemented the one dimensional composite probabilities
+     (MHCompProb, MCompProbCalc, comprob.C)
+
+   - implemented the Multidimensional Distances (Next Neighbours, Kernel)
+     (MMultiDimDistCalc, multidimdist.C, multidimdist2.C, MHMatrix)
+
+   - Added a camera display displaying the pixel numbers to the
+     event display gui.
+
+   - Added Monte Carlo Informations to event display gui
+
+   - Changed the camera display to display the pixel numbering
+   
+   - Added three buttons to the camera display to change the palette
+
+   - Added the number of used and core pixels after image cleaning
+     to MHillas
+
+   - Changed the algorithm used in MHillas according to TDAS 02-03
+
+   - Changed the Alpha range according to TDAS 02-03 to [-90°,90°]
+
+   - Changed the algorithm used in MHillasSrc according to TDAS 02-03
+
+   - Added fCosDeltaAlpha to MHillasSrc
+
+   - The numbers of photons used to calculate fConc and fConc1 in
+     MHillasExt are now scaled with the pixel size, so that one get
+     a four times smaller value for the bigger pixels in the outer ring.
+
+   - added new task to smooth the camera contents (MCameraSmooth)
+
+   - added possibility to use interpolated pixel values for blind pixels
+     instead of removing it completely from the analysis
+
+   - Implemented the possibility to save the whole eventloop with
+     its setup to a file. This information can be read and from
+     it you can (re)create a Macro. See MEvtLoop::Read, MEvtLoop::Write
+     and MEvtLoop::MakeMacro. If you find something not working, please
+     report - this stuff is still in a beta phase.
+
+   - MBlindPixelCalc set all Ceta-Tauri pixels to unused not only for the
+     file having crab starfield, but also for all following files - fixed
+
+   - MTaskList::PrintStatistics can now be instructud to print also the
+     title, too: use PrintStatistics(0, kTRUE)
+
+   - Changed the image cleaning so that pixels with to many 'used'
+     neighbors are left used (to get rid of 'holes' in events)
+
+   - Introduced more output to the camera displays
+
+   - Added an array of histograms (eg one hist per run), MHArray
+
+   - Added a _preliminary_ version of the reader for CT1 PreProc files
+     (MCT1ReadPreProc)
+
+   - Fixed the error calculation of MHMCollectionArea and MHMcIntRate
+     (thanks to Raquel)
+
+   - added the first energy estimator (MEnergyEstParam, estimate.C,
+     estfit.C) using a parametrization
+
+   - Added some new Monte Carlo paremeter containers used to store
+     setup information from the MC chain (MMcConfigRunHeader, 
+     MMcCorsikaRunHeader, MGeomPMT, MGeomMirror)
+
+
+
+ *** Version 0.7 (2002/04/30)
+ 
+   - added a bugfix to MCerPhotCalc. In older camera versions (<=40)
+     the pedestal mean value was saved incorrectly. For files from
+     this versions we substract 0.5 from the pedestal mean.
+     WARNING: This may effect your results, so don't wonder...
+
+   - First implementation of an algorithm using only triggered events
+     for the collection area calculation
+
+   - Ascii Output can now also be used for parameter containers which
+     doesn't overload MParCointainer::AsciiWrite
+
+   - The Ascii Output is now also capable of writing single data members
+     of one container
+
+   - You are now able to change the order of the values written to the
+     ascii file
+
+   - You can now specify a conversion factor for each data member written
+     to an ascii file. This may be usefull to change the units of the 
+     data member (eg. degrees instead of millimeters in case of the 
+     hillas parameters)
+
+   - Replaced old MHillas by a new structure which allows you to extend
+     the parameters stored in MHillas very easily:
+     see MHillas and MHillasExt
+
+   - Added classes to handle source dependancy of image parameters:
+     see MHillasSrc
+
+   - Added container (MBinning) to have a standard input for the binning
+     in different histograms (eg. the Energy bins should be the same in
+     all histograms)
+
+   - Changed Hillas histograms from mm to deg
+
+   - Added the flexible binning to the hillas histograms
+
+   - Added a filter for the alpha parameter (MFAlpha)
+
+   - It is now possible to write single data members of a class object to
+     an output stream instead of the whole container only
+
+   - Added a generalized filter for a data member:
+     MFDataMember filter("MHillas.fWidth", '<', 0.5);
+
+   - Added a generalized Filter parser for more difficult filter rules
+     MF filter("MHillas.fWidth<0.5 && MHillas.fLength>0.5");
+
+   - Added new Monte Carlo histograms:
+     MHMcEnergyImpact and MHMcEfficiency
+
+   - Added many new histograms needed for the flux calculation.
+
+   - Added a generalized histograms which can fill and show up to three
+     data members in either a one-, two- or three-dimensional histogram, eg:
+     MH3 mh3("MHillas.fWidth", "MHillas.fLength");
+
+   - Added:
+       * calculation of <Theta> as a function of Theta (MHThetabarTheta)
+       * calculation of <Theta> as a function of time (MHThetabarTime)
+     they are needed in the flux calculation in 
+     order to select for a given bin in Theta (or time) the appropriate 
+     effective collection area, which is assumed to be given as a function 
+     of Theta and the true energy
+
+   - Added calculation of the migration matrix in the energy 
+     (MHMcEnergyMigration):
+     the migration matrix describes the migration from the true (E_true)
+     to the estimated energy (E_est); it is needed to determine the
+     distribution of E_true from the measured distribution of E_est 
+     by unfolding
+
+   - changed the color palette in the camera display to DeapSea.
+
+
+
+ *** Version 0.6 (2002/01/15)
+
+   - Introduce the option of disable pixels (MBlindPixels and
+     MBlindPixelCalc) for the analysis (eg MHillasCalc) to be 
+     able to deal with Star Field NSB.
+
+   - Fixed a bug in the pedestals substraction
+
+   - Introduced verbosity levels
+
+   - Introduced a task (MReadMarsFile) which reads the RunHeader tree, too.
+
+   - Fixed several bugs in MFTriggerLvl1 which caused to filter not to
+     work correctly (thanks to Abelardo)
+
+   - Introduced correct treatment of the diffuse Night Sky Background 
+     and NSB (MMcPedestalNSB)
+
+   - Corrected treatment of the electronic noise (MMcPedestalCopy)
+
+   - Introduced MMcRunHeaders which contains monte carlo run informations
+
+   - Added a 'Print'-Task (MPrint) which calls the Print function
+     of a parameter container for each event
+
+   - Removed MHtml (was replaced by THtml of root 3.02) in dohtml.C
+
+   - changes to be more efficient with root 3.02/06
+
+   - root 3.02/06 fixes:
+     + the memory leak when reading MRawEvtData
+     + loosing more time than necessary to update the progress bar
+
+   - MWriteAsciiFile is now capable of writing more than one container
+     in a line. For example: To be able to write Monte Carlo and 
+     Hillas values (energy and alpha) in one line.
+
+
+
+ *** Version 0.5 (2001/11/06)
+
+   - Added new GUI functionality (Analysis)
+
+   - Added a camera display to be able to display events in the camera
+     together with the calculated hillas ellipse
+
+   - Added a 'Clone'-Task (MClone) which can clone a parameter container
+     object at any state of the analysis, so that the output are several
+     states
+
+   - Fixed a bug in the collection area error calculation 
+     (Thanks to Ciro and Abelardo)
+
+   - Fixed a bug which causes merpp to crash in some environments
+
+   - Implemented auto enabling scheme for Branches to speed up reading
+     a lot (see MReadTree and MTask)
+
+   - Fixed a bug in the Histogram classes which caused histograms to
+     be written to a file by MWriteRootFile without request
+
+   - changed the object I/O from the old stylish root I/O to the new
+     'auto evolution scheme' This was done only for classes which are not
+     yet used in Monte Carlo files, so that these files are still readable.
+
+   - Added support for a progress bar in MEvtLoop and MReadTree 
+     (see the Analysis Window in Mars for an example)
+
+   - Fixed a bug in the package creation which disturbed the conversion
+     between a mars version unpacked from a tar file and the repository.
+
+   - Changed the code to writer merpped (converted into root format)
+     raw files, to get faster (around 10%)
+
+
+
+ *** Version 0.4 (2001/09/20)
+
+    - This release is made to compile on a root version >= 3.00
+
+    - Fixed a bug which causes MReadTree to read the first file only
+
+    - Added a task to compute the trigger rate (MMcTriggerRateCalc)
+ 
+    - Added a task to write a container to an Ascii file (MWriteAsciiFile)
+
+    - Added a task to write several container to a root file (MWriteRootFile)
+    
+    - Added calculation of the Enegry Threshold (MMcThresholdCalc)
+    
+    - Added calculation of the collection area (MMcCollectionAreaCalc)
+    
+    - fixed some bugs in the Hillas calculation
+    
+    - added filters to be able to control the task execution dependent on
+      a parameter (for example: the number of level 1 triggers in a MC-file)
+
+
+
+ *** Version 0.3 (2001/04/23)
+	
+    - Many demo macros added    
+  
+    - MCT1ReadAscii is now able to handle more than one file (s. ::AddFile)
+    
+    - Hillas Calculation added
+    
+    - Standard image cleaning available
+    
+    - MReadTree is now able to handle more than one file
+      (Remark: of the same structure)
+    
+    - Now we are able to display events in a first version of the
+      Camera event display. To do this we must run the macro 
+      "macros/readCT1.C" to read data from CT1. 
+
+
+
+ *** Version 0.2 (2001/01/24)
+ 
+    - First Implementation of a Gui to read the raw data. Start the
+      gui with the command mars. 
+
+
+
+ *** Version 0.1 (2000/12/20)
+ 
+    - First official release 0.1
+    
+    - Changes:
+    
+       + changed calling style of MRawPixelIterator from do...while to 
+         while-loop
Index: branches/Mars_McMismatchStudy/callisto.cc
===================================================================
--- branches/Mars_McMismatchStudy/callisto.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/callisto.cc	(revision 17960)
@@ -0,0 +1,668 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MSequence.h"
+#include "MJPedestal.h"
+#include "MJCalibration.h"
+#include "MJCalibrateSignal.h"
+#include "MJCalibTest.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "========================================================" << endl;
+    gLog << "                 Callisto - MARS V" << MARSVER            << endl;
+    gLog << "    MARS -- CALibrate LIght Signals and Time Offsets"     << endl;
+    gLog << "      Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " callisto [-c] [-y] [options] sequence.txt|[tel:]number" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   sequence.txt:             ASCII file defining a sequence of runs" << endl;
+    gLog << "   number:                   The sequence number (using file in the datacenter)" << endl;
+    gLog << "                             For more details see MSequence" << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Operation Modes:" << endl;
+    gLog << "   -c                        Calculate the calibration constants" << endl;
+    gLog << "   -y                        Extract and calibrate signal" << endl << endl;
+    gLog << " Data Type (exclusive):" << endl;
+    gLog << "   -mc                       Input root-files are monte carlo files" << endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file and" << endl;
+    gLog << "                             command line" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << "   --rc=Name:option          Set or overwrite a resource of the resource file." << endl;
+    gLog << "                             (Note, that this option can be used multiple times." << endl;
+    gLog << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   --ind=path                Path where to search for the data files" << endl;
+    gLog << "                             [default=standard path in datacenter]" << endl;
+    gLog << "   --iny=path                Path where to search for the calibration files" << endl;
+    gLog << "                             [default=local path or output path of Mode-C]" << endl;
+    gLog << "   --outc=path               Path to write Mode-C result to   [def=local path]" << endl;
+    gLog << "   --outy=path               Path to write Mode-Y result to   [def=local path]" << endl;
+    gLog << "   --out=path                Path to write the all results to [def=local path]" << endl;
+    gLog << "                             (overwrites --outc and --outy)" << endl;
+    gLog << "   --path=path               Path to write the all results to [def=local path]" << endl;
+    gLog << "                             (overwrites --iny, --outc and --outy)" << endl;
+    gLog << "   --dev-null                Suppress output of Y-files (for test purpose)" << endl;
+    gLog << "   --print-seq               Print Sequence information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequence" << endl;
+    gLog << "   --print-found             Print Files found from Sequence" << endl;
+//    gLog << "   --use-test                Apply calibration constants to same calibration" << endl;
+//    gLog << "                             file (for testing, calibration mode only)" << endl;
+    gLog << "   --movie                   Write a movie in addition to Mode-Y (this might " << endl;
+    gLog << "                             stop the eventloop before all evts are processed)" << endl;
+    gLog << "   --test                    Use this to calibrate the callibration files" << endl;
+    gLog << "                             instead of the data files (for test purposes)" << endl;
+//    gLog << "   --moon                    Force using pedestal fits instead of calculated RMS" << endl;
+    gLog << "   --config=callisto.rc      Resource file [default=callisto.rc]" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << " Setup of the two jobs run by callisto (MJPedestal and MJCalibration)" << endl;
+    gLog << " can be done with the resource file. See MJPedestal and MJCalibration" << endl;
+    gLog << " especially CheckEnv() for more details.   Command line options might" << endl;
+    gLog << " be overwritten by the resource file." << endl << endl;
+    gLog << " If running in Mode-C and Mode-Y --iny= is obsolete,  instead --outc=" << endl;
+    gLog << " is used." << endl << endl;
+    gLog << " Using  --iny=,  --outc=,  --outy=,  --out=  or --path= automatically" << endl;
+    gLog << " enables the corresponding modes.  In this case  -c/-y are obsolete." << endl << endl;
+    gLog << "Description:" << endl;
+    gLog << " callisto will calculate pedestals  from  pedestal-files defined in a" << endl;
+    gLog << " sequence-file.  This pedestals are used to calculate the calibration" << endl;
+    gLog << " constants. These constants are stored in a so called calibration-file" << endl;
+    gLog << " together with some datacheck plots  which can be viewed using either" << endl;
+    gLog << " showplot or MStatusDisplay in the interpreter.  A description  of  a" << endl;
+    gLog << " sequence-file can be found in the class reference of MSequence." << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Callisto is a large,  icy,  dark-colored,  low-density outer moon of" << endl;
+    gLog << " Jupiter that is scarred with  impact craters  and  ejecta.  It has a" << endl;
+    gLog << " diameter of about 4800km, the second-largest moon of Jupiter;  it is" << endl;
+    gLog << " roughly the size of  Mercury.  Callisto has the largest-known impact" << endl;
+    gLog << " crater in the Solar System, Valhalla, which has a bright patch 600km" << endl;
+    gLog << " across  and  rings that go out  to almost  3000km.  Callisto  orbits" << endl;
+    gLog << " Jupiter at a mean distance of 1,883,000km. Its mass is 1.1e23 kg. It" << endl;
+    gLog << " takes Callisto  16.7 days to orbit  Jupiter  in a synchronous orbit." << endl;
+    gLog << " Jupiter's moon Callisto was discovered independently by  Galileo and" << endl;
+    gLog << " S.Marius in 1610." << endl << endl;
+    gLog << "Example:" << endl;
+    gLog << " callisto -f --outc=mycal/ --outy=mysignal/ --log sequence02345.txt" << endl;
+    gLog << endl;
+}
+
+static void PrintFiles(const MSequence &seq, const TString &kInpathD, Bool_t showall)
+{
+    const char *prep = showall ? "Found" : "Scheduled";
+
+    MDirIter Next1, Next2, Next3;
+    seq.GetRuns(Next1, MSequence::kRawPed, kInpathD);
+    seq.GetRuns(Next2, MSequence::kRawCal, kInpathD);
+    seq.GetRuns(Next3, MSequence::kRawDat, kInpathD);
+
+    gLog << all;
+    gLog.Separator(Form("%s Pedestal Files", prep));
+    Next1.Print(showall?"all":"");
+    gLog << endl;
+    gLog.Separator(Form("%s Calibration Files", prep));
+    Next2.Print(showall?"all":"");
+    gLog << endl;
+    gLog.Separator(Form("%s Data Files", prep));
+    Next3.Print(showall?"all":"");
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    const TString kConfig     = arg.GetStringAndRemove("--config=", "callisto.rc");
+
+    const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+    const Bool_t  kPrintFiles = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kPrintFound = arg.HasOnlyAndRemove("--print-found");
+//    const Bool_t  kUseTest    = arg.HasOnlyAndRemove("--use-test");
+    const Bool_t  kMovie      = arg.HasOnlyAndRemove("--movie");
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+    const Bool_t  kNullOut    = arg.HasOnlyAndRemove("--dev-null");
+    const Bool_t  kTestMode   = arg.HasOnlyAndRemove("--test");
+//          Bool_t  kMoon       = arg.HasOnlyAndRemove("--moon");
+    Int_t kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit       = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+    //const Bool_t  kForceExec  = arg.HasOnlyAndRemove("-ff");
+
+    const TString kInpathD    = arg.GetStringAndRemove("--ind=",  "");
+          TString kInpathY    = arg.GetStringAndRemove("--iny=",  "");
+          TString kOutpathY   = arg.GetStringAndRemove("--outy=", "");
+          TString kOutpathC   = arg.GetStringAndRemove("--outc=", "");
+    const TString kOutpath    = arg.GetStringAndRemove("--out=",  "");
+    const TString kPath       = arg.GetStringAndRemove("--path=", "");
+
+          Bool_t  kModeC      = arg.HasOnlyAndRemove("-c");
+          Bool_t  kModeY      = arg.HasOnlyAndRemove("-y");
+    const Bool_t  kIsMC       = arg.HasOnlyAndRemove("-mc");
+
+    if (!kInpathY.IsNull() || !kOutpathY.IsNull() || !kOutpath.IsNull() || !kPath.IsNull())
+        kModeY = kTRUE;
+    if (!kOutpathC.IsNull() || !kOutpath.IsNull() || !kPath.IsNull())
+        kModeC = kTRUE;
+
+    //
+    // check for the right usage of the program (number of arguments)
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        gLog << warn << "WARNING - Wrong number of arguments..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // Now we access/read the resource file. This will remove all
+    // --rc= from the list of arguments.
+    //
+    MEnv env(kConfig, "callisto.rc");
+    if (!env.IsValid())
+    {
+        gLog << err << "ERROR - Reading resource file " << kConfig << "." << endl;
+        return 0xfe;
+    }
+
+    // And move the resource options from the command line to the MEnv
+    if (!env.TakeEnv(arg, kDebugEnv>2))
+        return 0xfd;
+
+    //
+    // check for the right usage of the program (number of options)
+    //
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 2;
+    }
+
+    if (!kModeC && !kModeY /*&& !kUseTest*/)
+    {
+        gLog << err << "Neither calibration (-c), signal extraction (-y) or test-mode (--use-test)" << endl;
+        gLog <<        "specified! You can also give the operation mode by the options defining the" << endl;
+        gLog <<        "output path --outc, --outy or --out." << endl;
+        Usage();
+        return 2;
+    }
+    if (!kModeY && kMovie)
+    {
+        gLog << err << "Signal extraction mode (-y) not switched on but movie requested." << endl;
+        Usage();
+        return 2;
+    }
+
+    if ((kModeC/* || kUseTest*/) && kOutpathC.IsNull())
+        kOutpathC = ".";
+    if (kModeY)
+    {
+        if (kInpathY.IsNull())
+            kInpathY = ".";
+        if (kOutpathY.IsNull())
+            kOutpathY = ".";
+    }
+    if (!kOutpath.IsNull())
+    {
+        kOutpathC = kOutpath;
+        kOutpathY = kOutpath;
+    }
+    if (!kPath.IsNull())
+    {
+        kOutpathC = kOutpath;
+        kOutpathY = kOutpath;
+        kInpathY  = kOutpath;
+    }
+
+    if (kModeC && kModeY)
+        kInpathY = kOutpathC;
+
+    //
+    // Setup sequence file and check for its existance
+    //
+    TString kSequence = arg.GetArgumentStr(0);
+
+    if (!MSequence::InflateSeq(kSequence, kIsMC))
+        return 3;
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Setup sequence and check its validity
+    //
+    MSequence seq(kSequence, kInpathD);
+    if (!seq.IsMonteCarlo())
+        seq.SetMonteCarlo(kIsMC);
+    if (kPrintSeq)
+    {
+        gLog << all;
+        gLog.Separator(kSequence);
+        seq.Print();
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Sequence read but not valid!" << endl << endl;
+        return 5;
+    }
+
+    //
+    // Process print options
+    //
+    if (kPrintFiles)
+        PrintFiles(seq, kInpathD, kFALSE);
+    if (kPrintFound)
+        PrintFiles(seq, kInpathD, kTRUE);
+
+//    if (seq.HasMoon())
+//        kMoon = kTRUE;
+
+
+    /*
+    //
+    // Check for existance of all files
+    //
+    MDirIter iter;
+    const Int_t n0 = seq.SetupAllRuns(iter, kInpathD, "[DPC]");
+    const Int_t n1 = seq.GetNumAllRuns();
+    if (n0 != n1)
+    {
+        if (kForceExec)
+            gLog << warn << "WARNING";
+        else
+            gLog << err << "ERROR";
+        gLog << " - " << n1 << " files in sequence defined, but " << n0 << " found in ";
+        gLog << (kInpathD.IsNull() ? "<defaultpath>" : kInpathD.Data()) << endl;
+        if (!kForceExec)
+            return 2;
+    }
+
+    if (kPrintOnly)
+        return 0;
+  */
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    // FIXME: Remove all non-root arguments and options from argc, argv
+
+    TApplication app("callisto", &argc, argv);
+    if ((!gROOT->IsBatch() && !gClient) || (gROOT->IsBatch() && !kBatch))
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(Form("-- Callisto: %s --", kSequence.Data()));
+
+    if (kModeC/* || kUseTest*/)
+    {
+        //
+        // Calculate pedestal for pedestal-calculation and calibration
+        //
+        MJPedestal job1(Form("MJPedestalC1 #%d", seq.GetSequence()));
+        job1.SetNoStorage();
+        job1.SetSequence(seq);
+        job1.SetEnv(&env);
+        job1.SetEnvDebug(kDebugEnv);
+        job1.SetDisplay(d);
+        job1.SetOverwrite(kOverwrite);
+//        job1.SetUseHists(kMoon);
+
+
+        job1.SetExtractionFundamental();
+        // job1.SetPathOut(kOutpathC); // not yet needed
+        // job1.SetPathIn(kInpathC);   // DO NOT CALL IT. IT WOULD READ THE XEXTRACTOR FROM calib-file
+
+        if (!job1.Process())
+        {
+            gLog << err << "Calculation of pedestal failed." << endl << endl;
+            return 6;
+        }
+
+        if (!job1.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Calculate pedestal and pedestal resolution
+        //
+        MJPedestal job2(Form("MJPedestalC2 #%d", seq.GetSequence()));
+        job2.SetNoStorage();
+        job2.SetSequence(seq);
+        job2.SetEnv(&env);
+        job2.SetEnvDebug(kDebugEnv);
+        job2.SetDisplay(d);;
+        job2.SetOverwrite(kOverwrite);
+//        job2.SetUseHists(kMoon);
+        job2.SetDeadPixelCheck();
+        // job1.SetPathOut(kOutpathC); // not yet needed
+        // job1.SetPathIn(kInpathC);   // DO NOT CALL IT. IT WOULD READ THE XEXTRACTOR FROM calib-file
+
+        //job2.SetExtractorResolution();
+        job2.SetExtractionWithExtractorRndm();
+        job2.SetExtractor(job1.GetExtractor());
+        job2.SetPedestals(job1.GetPedestalCam());
+        job2.SetBadPixels(job1.GetBadPixels());
+
+        // Please check the Changelog of 2005/04/20 about further deatils of the next comment
+        //if (job1.GetExtractor().InheritsFrom("MExtractTimeAndCharge"))
+        if (!job2.Process())
+        {
+            gLog << err << "Calculation of pedestal resolution failed." << endl << endl;
+            return 7;
+        }
+
+        if (!job2.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Do calibration
+        //
+        MJCalibration job3(Form("MJCalibration #%d", seq.GetSequence()));
+        job3.SetSequence(seq);
+        job3.SetEnv(&env);
+        job3.SetEnvDebug(kDebugEnv);
+        job3.SetDisplay(d);
+        job3.SetOverwrite(kOverwrite);
+        job3.SetPathOut(kOutpathC);
+        job3.SetCommandLine(MArgs::GetCommandLine(argc, argv));
+        // job2.SetPathIn(kInpathC); // not yet needed
+
+        job3.SetBadPixels(job2.GetBadPixels());
+        job3.SetExtractor(job2.GetExtractor());
+        job3.SetExtractorCam(job2.GetPedestalCam());
+
+        if (!job3.Process(job1.GetPedestalCam()))
+        {
+            gLog << err << "Calculation of calibration failed." << endl << endl;
+            return 8;
+        }
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job3.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+/*
+        if (kUseTest)
+        {
+            MJCalibTest job4(Form("MJCalibTest #%d", seq.GetSequence()));
+            job4.SetBadPixels(job2.GetBadPixels());
+            job4.SetSequence(seq);
+            job4.SetEnv(&env);
+            job4.SetEnvDebug(kDebugEnv);
+            job4.SetDisplay(d);;
+            job4.SetOverwrite(kOverwrite);
+            job4.SetPathOut(kOutpathC);
+
+            if (!job4.Process(job1.GetPedestalCam()))
+            {
+                gLog << err << "Calibration of calibration failed." << endl << endl;
+                return 9;
+            }
+
+            if (kDebugEnv>0)
+                env.PrintUntouched();
+
+            if (!job4.GetDisplay())
+            {
+                gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+                return 1;
+            }
+        }*/
+    }
+
+    if (kModeY)
+    {
+        d->Reset();
+
+        //
+        // Calculate starting pedestal for data extraction
+        //
+        MJPedestal job1(Form("MJPedestalY1 #%d", seq.GetSequence()));
+        job1.SetNoStorage();
+        job1.SetSequence(seq);
+        job1.SetEnv(&env);
+        job1.SetEnvDebug(kDebugEnv);
+        job1.SetDisplay(d);
+        job1.SetNoDisplay();
+        job1.SetOverwrite(kOverwrite);
+        job1.SetPathIn(kInpathY);   // --> READ Extractor from calib-file
+        //job1.SetPathOut(kOutpathY);   // not yet needed
+        job1.SetUseData();
+        job1.SetExtractionFundamental();
+
+        if (!job1.Process())
+        {
+            gLog << err << "Calculation of fundamental pedestal failed." << endl << endl;
+            return 10;
+        }
+
+        if (!job1.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Calculate pedestal and pedestal resolution
+        //
+        MJPedestal job2(Form("MJPedestalY2 #%d", seq.GetSequence()));
+        job2.SetNoStorage(kMovie);
+        job2.SetSequence(seq);
+        job2.SetEnv(&env);
+        job2.SetEnvDebug(kDebugEnv);
+        job2.SetDisplay(d);
+        job2.SetNoDisplay();
+        job2.SetOverwrite(kOverwrite);
+        job2.SetPathIn(kInpathY);
+        job2.SetPulsePosCheck(!seq.IsMonteCarlo());
+        job2.SetPathOut(kOutpathY); // for updating the extractor
+
+        job2.SetUseData();
+        job2.SetExtractionWithExtractorRndm();
+        job2.SetExtractor(job1.GetExtractor());
+        job2.SetPedestals(job1.GetPedestalCam());
+        job2.SetBadPixels(job1.GetBadPixels());
+//        job2.SetUseHists(kMoon);
+
+        // Please check the Changelog of 2005/04/20 about further deatils of the next comment
+        //if (job1.GetExtractor().InheritsFrom("MExtractTimeAndCharge"))
+        const Int_t rc = job2.Process();
+        if (rc<=0)
+        {
+            // rc==0:  Error
+            // rc==-1: too much to the left
+            // rc==-2: too much to the right
+            // rc==-3: too much to the right (beyond limits)
+
+            gLog << err << "Calculation of pedestal from extractor (random) failed." << endl << endl;
+
+            //error coding for the automatic analysis (to be filled into the database)
+            switch (rc)
+            {
+            case 0:
+                return 11;
+            case -1:
+                return 12;
+            case -2:
+                return 13;
+            case -3:
+                return 14;
+            }
+            return 2;
+        }
+
+        if (!job2.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Calculate pedestal and pedestal resolution
+        //
+        MJPedestal job3(Form("MJPedestalY3 #%d", seq.GetSequence()));
+        job3.SetNoStorage();
+        job3.SetSequence(seq);
+        job3.SetEnv(&env);
+        job3.SetEnvDebug(kDebugEnv);
+        job3.SetDisplay(d);
+        job3.SetNoDisplay();
+        job3.SetOverwrite(kOverwrite);
+        job3.SetPathIn(kInpathY);
+        // job1.SetPathOut(kOutpathC); // not yet needed
+        // job1.SetPathIn(kInpathC);   // not yet needed
+
+        job3.SetUseData();
+        job3.SetExtractionWithExtractor();
+        job3.SetExtractor(job2.GetExtractor());
+        job3.SetPedestals(job1.GetPedestalCam());
+        job3.SetBadPixels(job1.GetBadPixels());
+//        job3.SetUseHists(kMoon);
+
+        if (!job3.Process())
+        {
+            gLog << err << "Calculation of pedestal from extractor failed." << endl << endl;
+            return 15;
+        }
+
+        if (!job3.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Extract signal and calibrate it
+        //
+        MJCalibrateSignal job4(Form("MJCalibrateSignal #%d", seq.GetSequence()));
+        job4.SetSequence(seq);
+        job4.SetDisplay(d);;
+        job4.SetEnv(&env);
+        job4.SetEnvDebug(kDebugEnv);
+        job4.SetOverwrite(kOverwrite);
+        job4.SetPathIn(kInpathY);
+        job4.SetPathOut(kOutpathY);
+        job4.SetMovieMode(kMovie);
+        job4.SetNullOut(kNullOut);
+        job4.SetCommandLine(MArgs::GetCommandLine(argc, argv));
+        job4.SetTestMode(kTestMode);
+        if (!seq.IsMonteCarlo())
+            job4.SetExtractor(job2.GetExtractor());
+
+        // Where to search for calibration files
+        if (!job4.Process(job1.GetPedestalCam(), job3.GetPedestalCam(), job2.GetPedestalCam()))
+            return 16;
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job4.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
+
Index: branches/Mars_McMismatchStudy/callisto.rc
===================================================================
--- branches/Mars_McMismatchStudy/callisto.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/callisto.rc	(revision 17960)
@@ -0,0 +1,458 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                             Calibration
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJPedestal output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathOut: .
+#MJPedestalC2.PathOut: .
+#MJPedestalC1.BadPixelsFile: mjobs/badpixels_0_559.rc
+#MJPedestalC1.ReferenceFile: mjobs/pedestalref.rc
+#MJPedestalC2.ReferenceFile: mjobs/pedestalref.rc
+MJCalibration.ReferenceFile: mjobs/calibrationref_Nov04.rc
+MJCalibration.MHCalibrationRelTimeCam.ReferenceFile: mjobs/calibrationref_Nov04.rc
+MJCalibration.MHCalibrationChargeCam.ReferenceFile: mjobs/calibrationref_Nov04.rc
+
+# -------------------------------------------------------------------------
+# Use this to define where the calibration output is stored. The filename
+# is created from the sequence number. If nothing is specified '.' is
+# assumed. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJCalibration.PathOut: calped
+
+# -------------------------------------------------------------------------
+# Define here which signal extractor you are going to use for the
+# whole calibration chain
+# -------------------------------------------------------------------------
+MJPedestalC1.ExtractSignal: MExtractTimeAndChargeDigitalFilter
+# -------------------------------------------------------------------------
+# Define here an extractor which can be used for the December 04 data.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal: MExtractTimeAndChargeSpline, MExtractTimeAndChargeDigitalFilterPeakSearch, MExtractTimeAndChargeSlidingWindow
+# -------------------------------------------------------------------------
+# Define here parameters valid for all extractors above
+# The actual defaults used depend on the extractor in use.
+# For details see the corresponding source code
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.HiGainFirst:         0
+#MJPedestalC1.ExtractSignal.HiGainLast:         15
+#MJPedestalC1.ExtractSignal.LoGainFirst:         3
+#MJPedestalC1.ExtractSignal.LoGainLast:         14
+#MJPedestalC1.ExtractSignal.SaturationLimit:   250
+#MJPedestalC1.ExtractSignal.OffsetLoGain:      0.95
+#MJPedestalC1.ExtractSignal.LoGainSwitch:      120
+#MJPedestalC1.ExtractSignal.LoGainStartShift: -2.5
+# -------------------------------------------------------------------------
+# Define here parameters valid for the spline:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.Resolution:        0.05
+#MJPedestalC1.ExtractSignal.RiseTimeHiGain:    0.5
+#MJPedestalC1.ExtractSignal.FallTimeHiGain:    1.5
+#MJPedestalC1.ExtractSignal.LoGainStretch:     1.5
+#MJPedestalC1.ExtractSignal.ExtractionType: Integral <default>
+#MJPedestalC1.ExtractSignal.ExtractionType: Amplitude
+
+# -------------------------------------------------------------------------
+# In the case of the Digital filter you have to overwrite the default
+# weights file depending on what you are extracting
+# -------------------------------------------------------------------------
+MJPedestalC2.ExtractSignal.WeightsFile:          msignal/calibration_weights_UV46.dat
+MJPedestalY2.ExtractSignal.WeightsFile:          msignal/cosmics_weights46.dat
+MJPedestalY3.ExtractSignal.WeightsFile:          msignal/cosmics_weights46.dat
+MJCalibration.ExtractSignal.WeightsFile:         msignal/calibration_weights_UV46.dat
+MJCalibrateSignal.ExtractSignal.WeightsFile:     msignal/cosmics_weights46.dat
+MJCalibrateSignal.ExtractInterlaced.WeightsFile: msignal/calibration_weights_UV46.dat
+
+#MJPedestalC2.ExtractSignal.AutomaticWeightsFile:          On
+#MJPedestalY2.ExtractSignal.AutomaticWeightsFile:          On
+#MJPedestalY3.ExtractSignal.AutomaticWeightsFile:          On
+#MJCalibration.ExtractSignal.AutomaticWeightsFile:         On
+#MJCalibrateSignal.ExtractSignal.AutomaticWeightsFile:     On
+#MJCalibrateSignal.ExtractInterlaced.AutomaticWeightsFile: On
+
+# -------------------------------------------------------------------------
+# Configure MJCalibration
+# -------------------------------------------------------------------------
+
+# Switch on relative time calibration
+#MJCalibration.RelTimeCalibration: Yes
+# Type of used data format: raw, root, mc
+#MJCalibration.DataType: Root
+# Type of displayed plots: Full,DataCheck,Normal
+#MJCalibration.Display: datacheck
+# Write additinal debug output
+#MJCalibration.Debug: No
+# Use blind pixel
+#MJCalibration.UseBlindPixel: No
+# Use pin diode
+#MJCalibration.UsePINDiode: No
+# Use pixel check option
+#MJCalibration.PixelCheck: Yes
+#MJCalibTest.PixelCheck: Yes
+
+# -------------------------------------------------------------------------
+# Individual events check for calibration results
+# -------------------------------------------------------------------------
+
+#ContCosmics.MaxEmptyPixels:      0.2
+#ContCosmics.MaxExcludedFraction: 1
+#ContCosmics.MinAcceptedFraction: 0
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcPedRun use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinLast:      6
+#MJPedestalC1.ExtractPedestal.MaxSignalVar: 300
+
+#MJPedestalC2.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcFromLoGain use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC1.ExtractPedestal.MaxSignalVar:     40
+
+#MJPedestalC2.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC2.ExtractPedestal.MaxSignalVar:     40
+
+# -------------------------------------------------------------------------
+# Configure MJPedestalC1 and MJPedestalC2
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalC1.DataType: Root
+#MJPedestalC2.DataType: Root
+#MJPedestalC3.DataType: Root
+# Type of displayed plots: Full,DataCheck,None
+#MJPedestalC1.Display: datacheck
+#MJPedestalC2.Display: datacheck
+#MJPedestalC3.Display: datacheck
+# Maximum number of event processed in the loop
+#MJPedestalC1.MaxEvents: 1000
+#MJPedestalC2.MaxEvents: 1000
+# Allow to overwrite existing files with the output file
+#MJPedestalC1.AllowOverwrite: No
+#MJPedestalC2.AllowOverwrite: No
+# Use data runs from the sequence instead of calibration runs
+#MJPedestalC1.UseData: No
+#MJPedestalC2.UseData: No
+# Switch off DeadPixelCheck with "No"
+#MJPedestalY2.DeadPixelCheck: yes
+
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the software low-gain switch in the
+# calibration
+# -------------------------------------------------------------------------
+MJCalibration.ExtractSignal.LoGainSwitch:     170
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the higain-vs. logain intercalibration
+# -------------------------------------------------------------------------
+#MJCalibration.HiLoCalibFile:    mjobs/hilocalib_df46.root
+
+# -------------------------------------------------------------------------
+# Use this to change the behaviour of the calibration
+# -------------------------------------------------------------------------
+# Type if you set a colour explicitely from outside (TEST purposes!!)
+#MJCalibration.MCalibColorSet.ExplicitColor: green,blue,uv,ct1
+
+#MJCalibration.MCalibrationChargeCalc.ArrTimeRmsLimit:    5.0
+#MJCalibration.MCalibrationChargeCalc.ChargeLimit:        2.5
+#MJCalibration.MCalibrationChargeCalc.ChargeErrLimit:     0
+#MJCalibration.MCalibrationChargeCalc.ChargeRelErrLimit:  1
+#MJCalibration.MCalibrationChargeCalc.Debug:              no
+
+#MJCalibration.MCalibrationChargeCalc.FFactorErrLimit:    4.5
+#MJCalibration.MCalibrationChargeCalc.LambdaErrLimit:     0.2
+#MJCalibration.MCalibrationChargeCalc.LambdaCheckLimit:   0.5
+#MJCalibration.MCalibrationChargeCalc.PheErrLowerLimit:   9.0
+#MJCalibration.MCalibrationChargeCalc.PheErrUpperLimit:   5.5
+
+#MJCalibration.MHCalibrationChargeCam.Debug:        no
+#MJCalibration.MHCalibrationChargeCam.LoGain:       yes
+#MJCalibration.MHCalibrationChargeCam.Oscillations: yes
+#MJCalibration.MHCalibrationChargeCam.SizeCheck:    yes
+#MJCalibration.MHCalibrationChargeCam.Averageing:   yes
+#MJCalibration.MHCalibrationChargeCam.HiGainNbins:  500
+#MJCalibration.MHCalibrationChargeCam.HiGainFirst:  -98.
+#MJCalibration.MHCalibrationChargeCam.HiGainLast:   1902.
+#MJCalibration.MHCalibrationChargeCam.LoGainNbins:   500
+#MJCalibration.MHCalibrationChargeCam.LoGainFirst:  -99.
+#MJCalibration.MHCalibrationChargeCam.LoGainLast:   901.
+#MJCalibration.MHCalibrationChargeCam.TimeLowerLimit: 1. 
+#MJCalibration.MHCalibrationChargeCam.TimeUpperLimit: 3. 
+#MJCalibration.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibration.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibration.MHCalibrationChargeCam.ProbLimit:     0.00000001
+#MJCalibration.MHCalibrationChargeCam.OverflowLimit: 0.005
+#MJCalibration.MHCalibrationChargeCam.PulserFrequency: 500
+
+#MJCalibration.MHCalibrationRelTimeCam.Debug:          no
+#MJCalibration.MHCalibrationRelTimeCam.LoGain:         no
+#MJCalibration.MHCalibrationRelTimeCam.Oscillations:   yes
+#MJCalibration.MHCalibrationRelTimeCam.SizeCheck:      yes
+#MJCalibration.MHCalibrationRelTimeCam.Averageing:     yes
+#MJCalibration.MHCalibrationRelTimeCam.Nbins:          210
+#MJCalibration.MHCalibrationRelTimeCam.First:           -5.
+#MJCalibration.MHCalibrationRelTimeCam.Last:            10.
+#MJCalibration.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibration.MHCalibrationRelTimeCam.ProbLimit:       0.00001
+#MJCalibration.MHCalibrationRelTimeCam.OverflowLimit:   0.005
+#MJCalibration.MHCalibrationRelTimeCam.PulserFrequency: 500
+
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                            Signal extraction
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use a OutputPath if you want to write the results to a file
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.PathOut:  .
+#MJPedestalY1.PathOut:        .
+#MJPedestalY2.PathOut:        .
+#MJPedestalY3.PathOut:        .
+#MJCalibrateSignal.PathIn:   .
+
+# -------------------------------------------------------------------------
+# If you want to change the behaviour of the pedestal extraction...
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalY1.DataType: Root
+#MJPedestalY2.DataType: Root
+#MJPedestalY3.DataType: Root
+#MJPedestalY1.UseData: Yes
+#MJPedestalY2.UseData: Yes
+#MJPedestalY3.UseData: Yes
+#MJPedestalY1.MinEvents: 50
+#MJPedestalY2.MinEvents: 50
+#MJPedestalY3.MinEvents: 50
+
+MJPedestalY1.MaxEvents:   1000
+MJPedestalY2.MaxEvents:  10000
+MJPedestalY3.MaxEvents:   1000
+
+MJPedestalY1.MaxPedestals: 500
+MJPedestalY2.MaxPedestals: 500
+MJPedestalY3.MaxPedestals: 500
+
+# -------------------------------------------------------------------------
+# When the starting pedestal is extracted from the first events of
+# the data run also the average pulse position of these events
+# is determined. If the pulse position check is switched on (default)
+# the extraction window of the hi- and lo-gain extractor for the
+# determined average pulse position is not allowed to exceed the
+# extractors search region. In this scenario we assume that the
+# start of the extraction window is at least similar to the
+# rising edge of the pulse.
+# To make sure that the search region and the extraction window
+# does not touch increase the values.
+# -------------------------------------------------------------------------
+#MJPedestalY2.PulsePosCheck: yes
+#MJPedestalY2.ExtractWinLeft:  0.0
+#MJPedestalY2.ExtractWinRight: 0.0
+
+
+# -------------------------------------------------------------------------
+# Define the Pulse Position check parameters:
+# -------------------------------------------------------------------------
+#MJPedestalY2.MHCalibrationPulseTimeCam.SaturationLimit:  245
+#MJPedestalY2.MHCalibrationPulseTimeCam.LowerSignalLimit:  85
+#MJPedestalY2.MHCalibrationPulseTimeCam.NumPixelsRequired:  3
+#MJPedestalY2.PixelCheck: no
+
+#MJPedestalY.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalY.ExtractPedestal.PedestalUpdate:   no
+
+# -------------------------------------------------------------------------
+# Setup pedestal extractor for running through data
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MPedCalcFundamental.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFundamental.NumDump:          500
+#MJCalibrateSignal.MPedCalcFundamental.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFundamental.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFundamental.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFundamental.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractor.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractor.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFromExtractor.MaxSignalVar:      40
+
+# -------------------------------------------------------------------------
+# Configure the interlaced calibration updates
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateWithFFactorMethod: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumEventsDump: 500
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateNumPhes: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumPhesDump: 10
+#MJCalibrateSignal.MCalibrationChargeCalc.Debug: no
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the signal extractor
+# -------------------------------------------------------------------------
+MJCalibrateSignal.ExtractSignal.LoGainSwitch:    150
+#MJCalibrateSignal.ExtractSignal.LoGainStretch:     1.5
+#MJCalibrateSignal.ExtractInterlaced.LoGainStretch: 1.5
+
+# -------------------------------------------------------------------------
+# Setup calibration of data
+# -------------------------------------------------------------------------
+# Type of used data format: raw,root,MC
+#MJCalibrateSignal.DataType: Root
+# Type if you set a colour explicitely from outside (only TESTS!!!)
+#MJCalibrateSignal.MCalibColorSet.ExpicitColor: green,blue,uv,ct1
+#MJCalibrateSignal.MCalibrateData.PedestalFlag: Event
+#MJCalibrateSignal.MCalibrateData.ScaleFactor: 1
+MJCalibrateSignal.MCalibrateData.FileNameScale: resources/calibration.rc
+#MJCalibrateSignal.MCalibrateData.CalibrationMode: Default
+#MJCalibrateSignal.MCalibrateData.CalibConvMinLimit: 0.01
+#MJCalibrateSignal.MCalibrateData.CalibConvMaxLimit: 5.
+#MJCalibrateSignal.Interlaced: yes
+#MJCalibrateSignal.RelTimesUpdate: yes
+
+# -------------------------------------------------------------------------
+# Setup level for determining of bad pixels
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevel:         3.0
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevelVariance: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.NumMinNeighbors:    3
+#MJCalibrateSignal.MBadPixelsTreat.MaxArrivalTimeDiff: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.UseInterpolation:   yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalEvt: yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalRun: no
+#MJCalibrateSignal.MBadPixelsTreat.ProcessTimes:       yes
+#MJCalibrateSignal.MBadPixelsTreat.UseCentralPixel:    no
+#MJCalibrateSignal.MBadPixelsTreat.HardTreatment:      no
+
+# -------------------------------------------------------------------------
+# Setup interlaced calibration events histogramming
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationChargeCam.Debug:        no
+#MJCalibrateSignal.MHCalibrationChargeCam.LoGain:       yes
+MJCalibrateSignal.MHCalibrationChargeCam.Oscillations:  no
+#MJCalibrateSignal.MHCalibrationChargeCam.SizeCheck:    yes
+#MJCalibrateSignal.MHCalibrationChargeCam.Averageing:   yes
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainNbins:  500
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainFirst:  -98.
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainLast:   1902.
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainLast:   1899.5
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainNbins:   250
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainFirst:   -98
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainLast:    902
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeLowerLimit: 1. 
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeUpperLimit: 3. 
+#MJCalibrateSignal.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibrateSignal.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibrateSignal.MHCalibrationChargeCam.ProbLimit:    0.0001
+#MJCalibrateSignal.MHCalibrationChargeCam.OverflowLimit: 0.005
+MJCalibrateSignal.MHCalibrationChargeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# Setup relative time interlaced calibration
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Debug:           no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.LoGain:          no
+MJCalibrateSignal.MHCalibrationRelTimeCam.Oscillations:    no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.SizeCheck:       yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Averageing:      yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Nbins:           210
+#MJCalibrateSignal.MHCalibrationRelTimeCam.First:           -5.
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Last:            10.
+#MJCalibrateSignal.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibrateSignal.MHCalibrationRelTimeCam.ProbLimit:       0.00001
+#MJCalibrateSignal.MHCalibrationRelTimeCam.OverflowLimit:   0.005
+MJCalibrateSignal.MHCalibrationRelTimeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# Resource for movie encoding. For more details see IACT wiki
+# -------------------------------------------------------------------------
+#MMoviePrepare.FirstSlice: 0
+#MMoviePrepare.LastSlice:  15
+#MovieFilter.Condition: MMovieData.fMax>5*MMovieData.fMedianPedestalRms
+#MImgCleanStd.CleanLevel1: 8.0
+#MImgCleanStd.CleanLevel2: 4.5
+#MFEvtNumber.FileName: ganymed00001218.root
+#MFEvtNumber.Selector: ThetaSquared.fVal<0.04 && DataType.fVal>0.5
+#MMovieWrite.TargetLength: 5
+#MMovieWrite.NumEvents: 10
+#MMovieWrite.Threshold: 3
+#MMovieWrite.Filename: movie.mpg
+
+# -------------------------------------------------------------------------
+# This is a special option for the datacheck. A task executed as last
+# task in the event processing task list - in the standard software it
+# is skipped
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.FinalFantasy: MHCamFlorian
Index: branches/Mars_McMismatchStudy/callisto_Dec04Jan05.rc
===================================================================
--- branches/Mars_McMismatchStudy/callisto_Dec04Jan05.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/callisto_Dec04Jan05.rc	(revision 17960)
@@ -0,0 +1,483 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                             Calibration
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJPedestal output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathOut: .
+#MJPedestalC2.PathOut: .
+
+# -------------------------------------------------------------------------
+# Use this if you want to modify the exclusion of pixels from the beginning
+# (default: Pixel 0 and 559)
+# -------------------------------------------------------------------------
+MJPedestalC1.BadPixelsFile: mjobs/badpixels_0_559.rc
+
+# -------------------------------------------------------------------------
+# Use this if you want to modify files containing information about the 
+# reference lines in the status display
+# -------------------------------------------------------------------------
+MJPedestalC1.ReferenceFile: mjobs/pedestalref_Dec04.rc
+MJPedestalC2.ReferenceFile: mjobs/pedestalref_Dec04.rc
+MJCalibration.ReferenceFile: mjobs/calibrationref_Dec04.rc
+MJCalibration.MHCalibrationRelTimeCam.ReferenceFile: mjobs/calibrationref_Dec04.rc
+MJCalibration.MHCalibrationChargeCam.ReferenceFile: mjobs/calibrationref_Dec04.rc
+
+# -------------------------------------------------------------------------
+# Use this to define where the calibration output is stored. The filename
+# is created from the sequence number. If nothing is specified '.' is
+# assumed. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJCalibration.PathOut: calped
+
+# -------------------------------------------------------------------------
+# Use this to define where the program should search for the pedestal
+# and calibration files defined in the sequence. To use the local
+# directory use '.' If nothing is specified the default path in the
+# datacenter is used. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathData:   /data/MAGIC/Period016/
+#MJPedestalC2.PathData:   /data/MAGIC/Period016/
+#MJCalibration.PathData:  /data/MAGIC/Period016/
+
+# -------------------------------------------------------------------------
+# Define here which signal extractor you are going to use for the
+# whole calibration chain
+# -------------------------------------------------------------------------
+MJPedestalC1.ExtractSignal: MExtractTimeAndChargeSpline
+# -------------------------------------------------------------------------
+# Possibilities for a different extractor
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal: MExtractTimeAndChargeDigitalFilter, MExtractTimeAndChargeDigitalFilterPeakSearch, MExtractTimeAndChargeSlidingWindow
+# -------------------------------------------------------------------------
+# Define here parameters valid for all extractors above
+# The actual defaults used depend on the extractor in use.
+# For details see the corresponding source code
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.HiGainFirst:         0
+#MJPedestalC1.ExtractSignal.HiGainLast:         15
+#MJPedestalC1.ExtractSignal.LoGainFirst:         3
+#MJPedestalC1.ExtractSignal.LoGainLast:         14
+#MJPedestalC1.ExtractSignal.SaturationLimit:   250
+#MJPedestalC1.ExtractSignal.OffsetLoGain:      1.3
+#MJPedestalC1.ExtractSignal.LoGainSwitch:      120
+#MJPedestalC1.ExtractSignal.LoGainStartShift: -2.5
+# -------------------------------------------------------------------------
+# Define here parameters valid for the spline:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.Resolution:        0.05
+MJPedestalC1.ExtractSignal.RiseTimeHiGain:    0.5
+MJPedestalC1.ExtractSignal.FallTimeHiGain:    0.5
+#MJPedestalC1.ExtractSignal.LoGainStretch:     1.5
+#MJPedestalC1.ExtractSignal.ExtractionType: Integral <default>
+#MJPedestalC1.ExtractSignal.ExtractionType: Amplitude
+
+# -------------------------------------------------------------------------
+# In the case of the Digital filter you have to overwrite the default
+# weights file depending on what you are extracting
+# -------------------------------------------------------------------------
+#MJPedestalC2.ExtractSignal.WeightsFile:          msignal/calibration_weights_UV4.dat
+#MJPedestalY2.ExtractSignal.WeightsFile:          msignal/cosmics_weights4.dat
+#MJPedestalY3.ExtractSignal.WeightsFile:          msignal/cosmics_weights4.dat
+#MJCalibration.ExtractSignal.WeightsFile:         msignal/calibration_weights_UV4.dat
+#MJCalibrateSignal.ExtractSignal.WeightsFile:     msignal/cosmics_weights4.dat
+#MJCalibrateSignal.ExtractInterlaced.WeightsFile: msignal/calibration_weights_UV4.dat
+#MJCalibrateSignal.ExtractSignal.LoGainStretch:     1.5
+#MJCalibrateSignal.ExtractInterlaced.LoGainStretch: 1.5
+
+# -------------------------------------------------------------------------
+# Configure MJCalibration
+# -------------------------------------------------------------------------
+
+# Switch on relative time calibration
+#MJCalibration.RelTimeCalibration: Yes
+# Set color to be used
+#MJCalibration.Color:
+# Type of used data format: raw, root, mc
+#MJCalibration.DataType: Root
+# Type of displayed plots: Full,DataCheck,Normal
+#MJCalibration.Display: datacheck
+# Write additinal debug output
+#MJCalibration.Debug: No
+# Use blind pixel
+#MJCalibration.UseBlindPixel: No
+# Use pin diode
+#MJCalibration.UsePINDiode: No
+# Use pixel check option
+#MJCalibration.PixelCheck: No
+#MJCalibTest.PixelCheck: No
+
+# -------------------------------------------------------------------------
+# Individual events check for calibration results
+# -------------------------------------------------------------------------
+
+#ContCosmics.MaxEmptyPixels:      0.2
+#ContCosmics.MaxExcludedFraction: 1
+#ContCosmics.MinAcceptedFraction: 0
+
+# -------------------------------------------------------------------------
+# In case of MOON DATA, uncomment the following lines:
+# (better: call callisto with option "-moon")
+# -------------------------------------------------------------------------
+#MJPedestalC1.UseHists: yes
+#MJPedestalC2.UseHists: yes
+#MJPedestalY1.UseHists: yes
+#MJPedestalY2.UseHists: yes
+#MJPedestalY3.UseHists: yes
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcPedRun use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:      0
+#MJPedestalC1.ExtractPedestal.CheckWinLast:      29
+#MJPedestalC1.ExtractPedestal.MaxSignalVar:      40
+
+#MJPedestalC2.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:      0
+#MJPedestalC2.ExtractPedestal.CheckWinLast:      29
+#MJPedestalC2.ExtractPedestal.MaxSignalVar:      40
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcFromLoGain use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:      0
+#MJPedestalC1.ExtractPedestal.CheckWinLast:      29
+#MJPedestalC1.ExtractPedestal.MaxSignalVar:      40
+
+#MJPedestalC2.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:      0
+#MJPedestalC2.ExtractPedestal.CheckWinLast:      29
+#MJPedestalC2.ExtractPedestal.MaxSignalVar:      40
+
+# -------------------------------------------------------------------------
+# Configure MJPedestalC1 and MJPedestalC2
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalC1.DataType: Root
+#MJPedestalC2.DataType: Root
+#MJPedestalC3.DataType: Root
+# Type of displayed plots: Full,DataCheck,None
+#MJPedestalC1.Display: datacheck
+#MJPedestalC2.Display: datacheck
+#MJPedestalC3.Display: datacheck
+# Maximum number of event processed in the loop
+#MJPedestalC1.MaxEvents: 1000
+#MJPedestalC2.MaxEvents: 1000
+# Allow to overwrite existing files with the output file
+#MJPedestalC1.AllowOverwrite: No
+#MJPedestalC2.AllowOverwrite: No
+# Use data runs from the sequence instead of calibration runs
+#MJPedestalC1.UseData: No
+#MJPedestalC2.UseData: No
+
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the software low-gain switch
+# -------------------------------------------------------------------------
+#MJCalibration.ExtractSignal.LoGainSwitch:     150
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the higain-vs. logain intercalibration
+# -------------------------------------------------------------------------
+MJCalibration.HiLoCalibFile:    resources/hilocalib_sp1.rc
+
+# -------------------------------------------------------------------------
+# Use this to change the behaviour of the calibration
+# -------------------------------------------------------------------------
+# Type if you set a colour explicitely from outside (only for MC!!!)
+#MJCalibration.MCalibColorSet.ExplicitColor: green,blue,uv,ct1
+
+#MJCalibration.MCalibrationChargeCalc.ArrTimeRmsLimit:    5.0
+#MJCalibration.MCalibrationChargeCalc.ChargeLimit:        2.5
+#MJCalibration.MCalibrationChargeCalc.ChargeErrLimit:     0
+#MJCalibration.MCalibrationChargeCalc.ChargeRelErrLimit:  1
+#MJCalibration.MCalibrationChargeCalc.Debug:              no
+
+#MJCalibration.MCalibrationChargeCalc.FFactorErrLimit:    4.5
+#MJCalibration.MCalibrationChargeCalc.LambdaErrLimit:     0.2
+#MJCalibration.MCalibrationChargeCalc.LambdaCheckLimit:   0.5
+#MJCalibration.MCalibrationChargeCalc.PheErrLowerLimit:   9.0
+#MJCalibration.MCalibrationChargeCalc.PheErrUpperLimit:   5.5
+
+#MJCalibration.MHCalibrationChargeCam.Debug:           no
+#MJCalibration.MHCalibrationChargeCam.LoGain:          yes
+#MJCalibration.MHCalibrationChargeCam.Oscillations:    yes
+#MJCalibration.MHCalibrationChargeCam.SizeCheck:       yes
+#MJCalibration.MHCalibrationChargeCam.Averageing:      yes
+#MJCalibration.MHCalibrationChargeCam.HiGainNbins:     500
+#MJCalibration.MHCalibrationChargeCam.HiGainFirst:     -100.125
+#MJCalibration.MHCalibrationChargeCam.HiGainLast:      1899.875
+#MJCalibration.MHCalibrationChargeCam.LoGainNbins:     500
+#MJCalibration.MHCalibrationChargeCam.LoGainFirst:     -100.25
+#MJCalibration.MHCalibrationChargeCam.LoGainLast:      899.75
+#MJCalibration.MHCalibrationChargeCam.TimeLowerLimit:  1. 
+#MJCalibration.MHCalibrationChargeCam.TimeUpperLimit:  3. 
+#MJCalibration.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibration.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+MJCalibration.MHCalibrationChargeCam.ProbLimit:        1.0E-18
+#MJCalibration.MHCalibrationChargeCam.OverflowLimit:   0.005
+#MJCalibration.MHCalibrationChargeCam.PulserFrequency: 500
+
+#MJCalibration.MHCalibrationRelTimeCam.Debug:           no
+#MJCalibration.MHCalibrationRelTimeCam.LoGain:          no
+#MJCalibration.MHCalibrationRelTimeCam.Oscillations:    yes
+#MJCalibration.MHCalibrationRelTimeCam.SizeCheck:       yes
+#MJCalibration.MHCalibrationRelTimeCam.Averageing:      yes
+#MJCalibration.MHCalibrationRelTimeCam.Nbins:           300
+#MJCalibration.MHCalibrationRelTimeCam.First:           -4.975
+#MJCalibration.MHCalibrationRelTimeCam.Last:            10.025
+#MJCalibration.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibration.MHCalibrationRelTimeCam.ProbLimit:       0.00001
+#MJCalibration.MHCalibrationRelTimeCam.OverflowLimit:   0.005
+#MJCalibration.MHCalibrationRelTimeCam.PulserFrequency: 500
+
+ 
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                            Signal extraction
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use a OutputPath if you want to write the results to a file
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.PathOut:  .
+#MJPedestalY1.PathOut:        .
+#MJPedestalY2.PathOut:        .
+#MJPedestalY3.PathOut:        .
+#MJPedestalY1.PathData:      /data/MAGIC/Period016/
+#MJPedestalY2.PathData:      /data/MAGIC/Period016/
+#MJPedestalY3.PathData:      /data/MAGIC/Period016/
+#MJCalibrateSignal.PathData: /data/MAGIC/Period016/
+#MJCalibrateSignal.PathIn:   .
+
+# -------------------------------------------------------------------------
+# If you want to change the behaviour of the pedestal extraction...
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalY1.DataType: Root
+#MJPedestalY2.DataType: Root
+#MJPedestalY3.DataType: Root
+#MJPedestalY1.UseData: Yes
+#MJPedestalY2.UseData: Yes
+#MJPedestalY3.UseData: Yes
+#MJPedestalY1.MinEvents: 50
+#MJPedestalY2.MinEvents: 50
+#MJPedestalY3.MinEvents: 50
+
+MJPedestalY1.MaxEvents:   1000
+MJPedestalY2.MaxEvents:  10000
+MJPedestalY3.MaxEvents:   1000
+
+MJPedestalY1.MaxPedestals: 500
+MJPedestalY2.MaxPedestals: 500
+MJPedestalY3.MaxPedestals: 500
+
+# -------------------------------------------------------------------------
+# When the starting pedestal is extracted from the first events of
+# the data run also the average pulse position of these events
+# is determined. If the pulse position check is switched on (default)
+# the extraction window of the hi- and lo-gain extractor for the
+# determined average pulse position is not allowed to exceed the
+# extractors search region. In this scenario we assume that the
+# start of the extraction window is at least similar to the
+# rising edge of the pulse.
+# To make sure that the search region and the extraction window
+# does not touch increase the values.
+# -------------------------------------------------------------------------
+#MJPedestalY2.PulsePosCheck: yes
+#MJPedestalY2.ExtractWinLeft:  0.0 
+#MJPedestalY2.ExtractWinRight: 0.0
+
+# -------------------------------------------------------------------------
+# Define the Pulse Position check parameters:
+# -------------------------------------------------------------------------
+#MJPedestalY2.MHCalibrationPulseTimeCam.SaturationLimit:  245
+#MJPedestalY2.MHCalibrationPulseTimeCam.LowerSignalLimit:  85
+#MJPedestalY2.MHCalibrationPulseTimeCam.NumPixelsRequired:  2
+#MJPedestalY2.PixelCheck: no
+
+#MJPedestalY.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalY.ExtractPedestal.PedestalUpdate:   no
+
+# -------------------------------------------------------------------------
+# Setup pedestal extractor for running through data
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MPedCalcFundamental.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFundamental.NumDump:          500
+#MJCalibrateSignal.MPedCalcFundamental.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFundamental.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFundamental.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinLast:      29
+#MJCalibrateSignal.MPedCalcFundamental.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinLast:      29
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractor.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractor.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinLast:      29
+#MJCalibrateSignal.MPedCalcFromExtractor.MaxSignalVar:      40
+
+# -------------------------------------------------------------------------
+# Configure the interlaced calibration updates
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateWithFFactorMethod: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumEventsDump: 500
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateNumPhes: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumPhesDump: 10
+#MJCalibrateSignal.MCalibrationChargeCalc.Debug: no
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the signal extractor
+# -------------------------------------------------------------------------
+MJCalibrateSignal.ExtractSignal.LoGainSwitch:    150
+
+# -------------------------------------------------------------------------
+# Setup calibration of data
+# -------------------------------------------------------------------------
+# Type of used data format: raw,root,MC
+#MJCalibrateSignal.DataType: Root
+# Type if you set a colour explicitely from outside (only for MC!!!)
+#MJCalibrateSignal.MCalibColorSet.ExpicitColor: green,blue,uv,ct1
+#MJCalibrateSignal.MCalibrateData.PedestalFlag: Event
+#MJCalibrateSignal.MCalibrateData.ScaleFactor: 0.85182358
+MJCalibrateSignal.MCalibrateData.FileNameScale: resources/calibration_spline.rc
+#MJCalibrateSignal.MCalibrateData.CalibrationMode: Default
+#MJCalibrateSignal.MCalibrateData.CalibConvMinLimit: 0.01
+#MJCalibrateSignal.MCalibrateData.CalibConvMaxLimit: 5.
+#MJCalibrateSignal.Interlaced: yes
+#MJCalibrateSignal.RelTimesUpdate: yes
+
+# -------------------------------------------------------------------------
+# Setup level for determining of bad pixels
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevel:         3.0
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevelVariance: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.NumMinNeighbors:    3
+#MJCalibrateSignal.MBadPixelsTreat.MaxArrivalTimeDiff: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.UseInterpolation:   yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalEvt: yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalRun: no
+#MJCalibrateSignal.MBadPixelsTreat.ProcessTimes:       yes
+#MJCalibrateSignal.MBadPixelsTreat.UseCentralPixel:    no
+#MJCalibrateSignal.MBadPixelsTreat.HardTreatment:      no
+
+# -------------------------------------------------------------------------
+# Setup interlaced calibration events histogramming
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationChargeCam.Debug:           no
+#MJCalibrateSignal.MHCalibrationChargeCam.LoGain:          yes
+MJCalibrateSignal.MHCalibrationChargeCam.Oscillations:    no
+#MJCalibrateSignal.MHCalibrationChargeCam.SizeCheck:       yes
+#MJCalibrateSignal.MHCalibrationChargeCam.Averageing:      yes
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainNbins:     500
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainFirst:     -100.5
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainLast:      1899.5
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainNbins:     250
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainFirst:     -98
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainLast:      902
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeLowerLimit:  1. 
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeUpperLimit:  3. 
+#MJCalibrateSignal.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibrateSignal.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibrateSignal.MHCalibrationChargeCam.ProbLimit:       0.0001
+#MJCalibrateSignal.MHCalibrationChargeCam.OverflowLimit:   0.005
+MJCalibrateSignal.MHCalibrationChargeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# Setup relative time interlaced calibration
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Debug:           no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.LoGain:          no
+MJCalibrateSignal.MHCalibrationRelTimeCam.Oscillations:    no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.SizeCheck:       yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Averageing:      yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Nbins:           300
+#MJCalibrateSignal.MHCalibrationRelTimeCam.First:           -4.975
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Last:            10.025
+#MJCalibrateSignal.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibrateSignal.MHCalibrationRelTimeCam.ProbLimit:       0.00001
+#MJCalibrateSignal.MHCalibrationRelTimeCam.OverflowLimit:   0.005
+MJCalibrateSignal.MHCalibrationRelTimeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# Resource for movie encoding. For more details see IACT wiki
+# -------------------------------------------------------------------------
+#MMoviePrepare.FirstSlice: 0
+#MMoviePrepare.LastSlice:  15
+#MovieFilter.Condition: MMovieData.fMax>5*MMovieData.fMedianPedestalRms
+#MImgCleanStd.CleanLevel1: 8.0
+#MImgCleanStd.CleanLevel2: 4.5
+#MFEvtNumber.FileName: ganymed00001218.root
+#MFEvtNumber.Selector: ThetaSquared.fVal<0.04 && DataType.fVal>0.5
+#MMovieWrite.TargetLength: 5
+#MMovieWrite.NumEvents: 500
+#MMovieWrite.Threshold: 3
+#MMovieWrite.FileName: filename.mpg
+
+# -------------------------------------------------------------------------
+# This is a special option for the datacheck. A task executed as last
+# task in the event processing task list - in the standard software it
+# is skipped
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.FinalFantasy: MHCamFlorian
Index: branches/Mars_McMismatchStudy/callisto_MarApr05.rc
===================================================================
--- branches/Mars_McMismatchStudy/callisto_MarApr05.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/callisto_MarApr05.rc	(revision 17960)
@@ -0,0 +1,485 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                             Calibration
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJPedestal output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathOut: .
+#MJPedestalC2.PathOut: .
+#MJPedestalC1.BadPixelsFile: mjobs/badpixels_0_559.rc
+#MJPedestalC1.ReferenceFile: mjobs/pedestalref.rc
+#MJPedestalC2.ReferenceFile: mjobs/pedestalref.rc
+MJCalibration.ReferenceFile: mjobs/calibrationref_Nov04.rc
+MJCalibration.MHCalibrationRelTimeCam.ReferenceFile: mjobs/calibrationref_Nov04.rc
+MJCalibration.MHCalibrationChargeCam.ReferenceFile: mjobs/calibrationref_Nov04.rc
+
+# -------------------------------------------------------------------------
+# Use this to define where the calibration output is stored. The filename
+# is created from the sequence number. If nothing is specified '.' is
+# assumed. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJCalibration.PathOut: calped
+
+# -------------------------------------------------------------------------
+# Use this to define where the program should search for the pedestal
+# and calibration files defined in the sequence. To use the local
+# directory use '.' If nothing is specified the default path in the
+# datacenter is used. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathData:   /data/MAGIC/Period016/
+#MJPedestalC2.PathData:   /data/MAGIC/Period016/
+#MJCalibration.PathData:  /data/MAGIC/Period016/
+
+# -------------------------------------------------------------------------
+# Define here which signal extractor you are going to use for the
+# whole calibration chain
+# -------------------------------------------------------------------------
+MJPedestalC1.ExtractSignal: MExtractTimeAndChargeDigitalFilter
+# -------------------------------------------------------------------------
+# Define here an extractor which can be used for the December 04 data.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal: MExtractTimeAndChargeSpline, MExtractTimeAndChargeDigitalFilterPeakSearch, MExtractTimeAndChargeSlidingWindow
+# -------------------------------------------------------------------------
+# Define here parameters valid for all extractors above
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.HiGainFirst:         0
+#MJPedestalC1.ExtractSignal.HiGainLast:         15
+#MJPedestalC1.ExtractSignal.LoGainFirst:         3
+#MJPedestalC1.ExtractSignal.LoGainLast:         14
+#MJPedestalC1.ExtractSignal.SaturationLimit:   250
+#MJPedestalC1.ExtractSignal.OffsetLoGain:     1.51
+#MJPedestalC1.ExtractSignal.LoGainSwitch:      150
+#MJPedestalC1.ExtractSignal.LoGainStartShift: -2.8
+# -------------------------------------------------------------------------
+# Define here parameters valid for the spline:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.Resolution:        0.05
+#MJPedestalC1.ExtractSignal.RiseTimeHiGain:    0.5
+#MJPedestalC1.ExtractSignal.FallTimeHiGain:    1.5
+#MJPedestalC1.ExtractSignal.LoGainStretch:     1.5
+#MJPedestalC1.ExtractSignal.ExtractionType: Integral <default>
+#MJPedestalC1.ExtractSignal.ExtractionType: Amplitude
+# -------------------------------------------------------------------------
+# Define here parameters valid for the sliding window:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.HiGainWindowSize:     6
+#MJPedestalC1.ExtractSignal.LoGainWindowSize:     6
+# -------------------------------------------------------------------------
+# Define here parameters valid for the digital filter with peak search:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.OffsetLeftFromPeak:   3
+#MJPedestalC1.ExtractSignal.OffsetRightFromPeak:  3
+#MJPedestalC1.ExtractSignal.PeakSearchWindowSize: 2
+#MJPedestalC1.ExtractSignal.HiGainFailureLimit:  10
+#MJPedestalC1.ExtractSignal.LoGainFailureLimit:  25
+
+# -------------------------------------------------------------------------
+# In the case of the Digital filter you have to overwrite the default
+# weights file depending on what you are extracting
+# -------------------------------------------------------------------------
+MJPedestalC2.ExtractSignal.WeightsFile:          msignal/calibration_weights_UV46.dat
+MJPedestalY2.ExtractSignal.WeightsFile:          msignal/cosmics_weights46.dat
+MJPedestalY3.ExtractSignal.WeightsFile:          msignal/cosmics_weights46.dat
+MJCalibration.ExtractSignal.WeightsFile:         msignal/calibration_weights_UV46.dat
+MJCalibrateSignal.ExtractSignal.WeightsFile:     msignal/cosmics_weights46.dat
+MJCalibrateSignal.ExtractInterlaced.WeightsFile: msignal/calibration_weights_UV46.dat
+
+#MJPedestalC2.ExtractSignal.AutomaticWeightsFile:          On
+#MJPedestalY2.ExtractSignal.AutomaticWeightsFile:          On
+#MJPedestalY3.ExtractSignal.AutomaticWeightsFile:          On
+#MJCalibration.ExtractSignal.AutomaticWeightsFile:         On
+#MJCalibrateSignal.ExtractSignal.AutomaticWeightsFile:     On
+#MJCalibrateSignal.ExtractInterlaced.AutomaticWeightsFile: On
+
+# -------------------------------------------------------------------------
+# Configure MJCalibration
+# -------------------------------------------------------------------------
+
+# Switch on relative time calibration
+#MJCalibration.RelTimeCalibration: Yes
+# Type of used data format: raw, root, mc
+#MJCalibration.DataType: Root
+# Type of displayed plots: Full,DataCheck,Normal
+#MJCalibration.Display: datacheck
+# Write additinal debug output
+#MJCalibration.Debug: No
+# Use blind pixel
+#MJCalibration.UseBlindPixel: No
+# Use pin diode
+#MJCalibration.UsePINDiode: No
+# Use pixel check option
+#MJCalibration.PixelCheck: Yes
+#MJCalibTest.PixelCheck: Yes
+
+# -------------------------------------------------------------------------
+# Individual events check for calibration results
+# -------------------------------------------------------------------------
+
+#ContCosmics.MaxEmptyPixels:      0.2
+#ContCosmics.MaxExcludedFraction: 1
+#ContCosmics.MinAcceptedFraction: 0
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcPedRun use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinSize:     29
+
+#MJPedestalC2.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcFromLoGain use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC1.ExtractPedestal.MaxSignalVar:     40
+
+#MJPedestalC2.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC2.ExtractPedestal.MaxSignalVar:     40
+
+# -------------------------------------------------------------------------
+# Configure MJPedestalC1 and MJPedestalC2
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalC1.DataType: Root
+#MJPedestalC2.DataType: Root
+#MJPedestalC3.DataType: Root
+# Type of displayed plots: Full,DataCheck,None
+#MJPedestalC1.Display: datacheck
+#MJPedestalC2.Display: datacheck
+#MJPedestalC3.Display: datacheck
+# Maximum number of event processed in the loop
+#MJPedestalC1.MaxEvents: 1000
+#MJPedestalC2.MaxEvents: 1000
+# Allow to overwrite existing files with the output file
+#MJPedestalC1.AllowOverwrite: No
+#MJPedestalC2.AllowOverwrite: No
+# Use data runs from the sequence instead of calibration runs
+#MJPedestalC1.UseData: No
+#MJPedestalC2.UseData: No
+# Switch off DeadPixelCheck with "No"
+#MJPedestalY2.DeadPixelCheck: yes
+
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the software low-gain switch in the
+# calibration
+# -------------------------------------------------------------------------
+MJCalibration.ExtractSignal.LoGainSwitch:     170
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the higain-vs. logain intercalibration
+# -------------------------------------------------------------------------
+#MJCalibration.HiLoCalibFile:    mjobs/hilocalib_df46.root
+#MJCalibration.HiLoCalibration:  yes
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the time extractor for the calibration
+# and automatically the data extraction
+# -------------------------------------------------------------------------
+#MJCalibration.ExtractTime: <dummy>
+#MJCalibration.ExtractTime: MExtractTimeFastSpline
+#MJCalibration.ExtractTime.HiGainFirst:       0
+#MJCalibration.ExtractTime.HiGainLast:        7
+#MJCalibration.ExtractTime.LoGainFirst:       3
+#MJCalibration.ExtractTime.LoGainLast:        8
+#MJCalibration.ExtractTime.WindowSizeHiGain:  6
+#MJCalibration.ExtractTime.WindowSizeLoGain:  6
+#MJCalibration.ExtractTime.OffsetLoGain:    1.51
+
+# -------------------------------------------------------------------------
+# Use this to change the behaviour of the calibration
+# -------------------------------------------------------------------------
+# Type if you set a colour explicitely from outside (TEST purposes!!)
+#MJCalibration.MCalibColorSet.ExplicitColor: green,blue,uv,ct1
+
+#MJCalibration.MCalibrationChargeCalc.ArrTimeRmsLimit:    5.0
+#MJCalibration.MCalibrationChargeCalc.ChargeLimit:        2.5
+#MJCalibration.MCalibrationChargeCalc.ChargeErrLimit:     0
+#MJCalibration.MCalibrationChargeCalc.ChargeRelErrLimit:  1
+#MJCalibration.MCalibrationChargeCalc.Debug:              no
+
+#MJCalibration.MCalibrationChargeCalc.FFactorErrLimit:    4.5
+#MJCalibration.MCalibrationChargeCalc.LambdaErrLimit:     0.2
+#MJCalibration.MCalibrationChargeCalc.LambdaCheckLimit:   0.5
+#MJCalibration.MCalibrationChargeCalc.PheErrLowerLimit:   9.0
+#MJCalibration.MCalibrationChargeCalc.PheErrUpperLimit:   5.5
+
+#MJCalibration.MHCalibrationChargeCam.Debug:        no
+#MJCalibration.MHCalibrationChargeCam.LoGain:       yes
+#MJCalibration.MHCalibrationChargeCam.Oscillations: yes
+#MJCalibration.MHCalibrationChargeCam.SizeCheck:    yes
+#MJCalibration.MHCalibrationChargeCam.Averageing:   yes
+#MJCalibration.MHCalibrationChargeCam.HiGainNbins:  500
+#MJCalibration.MHCalibrationChargeCam.HiGainFirst:  -98.
+#MJCalibration.MHCalibrationChargeCam.HiGainLast:   1902.
+#MJCalibration.MHCalibrationChargeCam.LoGainNbins:   500
+#MJCalibration.MHCalibrationChargeCam.LoGainFirst:  -99.
+#MJCalibration.MHCalibrationChargeCam.LoGainLast:   901.
+#MJCalibration.MHCalibrationChargeCam.TimeLowerLimit: 1. 
+#MJCalibration.MHCalibrationChargeCam.TimeUpperLimit: 3. 
+#MJCalibration.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibration.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibration.MHCalibrationChargeCam.ProbLimit:     0.00000001
+#MJCalibration.MHCalibrationChargeCam.OverflowLimit: 0.005
+#MJCalibration.MHCalibrationChargeCam.PulserFrequency: 500
+
+
+#MJCalibration.MHCalibrationRelTimeCam.Debug:        no
+#MJCalibration.MHCalibrationRelTimeCam.LoGain:       no
+#MJCalibration.MHCalibrationRelTimeCam.Oscillations:  yes
+#MJCalibration.MHCalibrationRelTimeCam.SizeCheck:    yes
+#MJCalibration.MHCalibrationRelTimeCam.Averageing:   yes
+#MJCalibration.MHCalibrationRelTimeCam.HiGainNbins:  210
+#MJCalibration.MHCalibrationRelTimeCam.HiGainFirst:  -5.
+#MJCalibration.MHCalibrationRelTimeCam.HiGainLast:   10.
+#MJCalibration.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibration.MHCalibrationRelTimeCam.ProbLimit:    0.00001
+#MJCalibration.MHCalibrationRelTimeCam.OverflowLimit: 0.005
+#MJCalibration.MHCalibrationRelTimeCam.PulserFrequency: 500
+
+ 
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                            Signal extraction
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use a OutputPath if you want to write the results to a file
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.PathOut:  .
+#MJPedestalY1.PathOut:        .
+#MJPedestalY2.PathOut:        .
+#MJPedestalY3.PathOut:        .
+#MJPedestalY1.PathData:      /data/MAGIC/Period016/
+#MJPedestalY2.PathData:      /data/MAGIC/Period016/
+#MJPedestalY3.PathData:      /data/MAGIC/Period016/
+#MJCalibrateSignal.PathData: /data/MAGIC/Period016/
+#MJCalibrateSignal.PathIn:   .
+
+# -------------------------------------------------------------------------
+# If you want to change the behaviour of the pedestal extraction...
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalY1.DataType: Root
+#MJPedestalY2.DataType: Root
+#MJPedestalY3.DataType: Root
+#MJPedestalY1.UseData: Yes
+#MJPedestalY2.UseData: Yes
+#MJPedestalY3.UseData: Yes
+
+MJPedestalY1.MaxEvents:   1000
+MJPedestalY2.MaxEvents:  10000
+MJPedestalY3.MaxEvents:   1000
+
+MJPedestalY1.MaxPedestals: 500
+MJPedestalY2.MaxPedestals: 500
+MJPedestalY3.MaxPedestals: 500
+
+# -------------------------------------------------------------------------
+# Use Pulse Position check to define the extraction ranges for the data?
+# -------------------------------------------------------------------------
+#MJPedestalY2.PulsePosCheck: yes
+#MJPedestalY2.ExtractWinLeft:  0.0
+#MJPedestalY2.ExtractWinRight: 0.5
+
+# -------------------------------------------------------------------------
+# Define the Pulse Position check parameters:
+# -------------------------------------------------------------------------
+#MJPedestalY2.MHCalibrationPulseTimeCam.SaturationLimit:  255
+#MJPedestalY2.MHCalibrationPulseTimeCam.LowerSignalLimit: 100
+#MJPedestalY2.MHCalibrationPulseTimeCam.NumPixelsRequired: 2
+#MJPedestalY2.PixelCheck: no
+
+#MJPedestalY.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalY.ExtractPedestal.PedestalUpdate:   no
+
+# -------------------------------------------------------------------------
+# Setup pedestal extractor for running through data
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MPedCalcFundamental.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFundamental.NumDump:          500
+#MJCalibrateSignal.MPedCalcFundamental.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFundamental.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFundamental.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFundamental.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractor.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractor.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFromExtractor.MaxSignalVar:      40
+
+# -------------------------------------------------------------------------
+# Configure the interlaced calibration updates
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateWithFFactorMethod: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumEventsDump: 500
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateNumPhes: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumPhesDump: 10
+#MJCalibrateSignal.MCalibrationChargeCalc.Debug: no
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the signal extractor
+# -------------------------------------------------------------------------
+MJCalibrateSignal.ExtractSignal.LoGainSwitch:    150
+#MJCalibrateSignal.ExtractSignal.LoGainStretch:     1.5
+#MJCalibrateSignal.ExtractInterlaced.LoGainStretch: 1.5
+
+# -------------------------------------------------------------------------
+# Setup calibration of data
+# -------------------------------------------------------------------------
+# Type of used data format: raw,root,MC
+#MJCalibrateSignal.DataType: Root
+# Type if you set a colour explicitely from outside (only TESTS!!!)
+#MJCalibrateSignal.MCalibColorSet.ExpicitColor: green,blue,uv,ct1
+#MJCalibrateSignal.MCalibrateData.PedestalFlag: Event
+#MJCalibrateSignal.MCalibrateData.ScaleFactor: 1
+MJCalibrateSignal.MCalibrateData.FileNameScale: resources/calibration.rc
+#MJCalibrateSignal.MCalibrateData.CalibrationMode: Default
+#MJCalibrateSignal.MCalibrateData.CalibConvMinLimit: 0.01
+#MJCalibrateSignal.MCalibrateData.CalibConvMaxLimit: 5.
+#MJCalibrateSignal.Interlaced: yes
+#MJCalibrateSignal.RelTimesUpdate: yes
+
+# -------------------------------------------------------------------------
+# Setup level for determining of bad pixels
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevel:         3.0
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevelVariance: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.NumMinNeighbors:    3
+#MJCalibrateSignal.MBadPixelsTreat.MaxArrivalTimeDiff: 1.0
+#MJCalibrateSignal.MBadPixelsTreat.UseInterpolation:   yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalEvt: yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalRun: no
+#MJCalibrateSignal.MBadPixelsTreat.ProcessTimes:       yes
+#MJCalibrateSignal.MBadPixelsTreat.UseCentralPixel:    no
+#MJCalibrateSignal.MBadPixelsTreat.HardTreatment:      no
+
+# -------------------------------------------------------------------------
+# Setup interlaced calibration events histogramming
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationChargeCam.Debug:        no
+#MJCalibrateSignal.MHCalibrationChargeCam.LoGain:       yes
+MJCalibrateSignal.MHCalibrationChargeCam.Oscillations:  no
+#MJCalibrateSignal.MHCalibrationChargeCam.SizeCheck:    yes
+#MJCalibrateSignal.MHCalibrationChargeCam.Averageing:   yes
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainNbins:  500
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainFirst:  -98.
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainLast:   1902.
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainLast:   1899.5
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainNbins:   250
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainFirst:   -98
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainLast:    902
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeLowerLimit: 1. 
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeUpperLimit: 3. 
+#MJCalibrateSignal.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibrateSignal.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibrateSignal.MHCalibrationChargeCam.ProbLimit:    0.0001
+#MJCalibrateSignal.MHCalibrationChargeCam.OverflowLimit: 0.005
+MJCalibrateSignal.MHCalibrationChargeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# Setup relative time interlaced calibration
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Debug:        no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.LoGain:       no
+MJCalibrateSignal.MHCalibrationRelTimeCam.Oscillations:  no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.SizeCheck:    yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Averageing:   yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.HiGainNbins:  210
+#MJCalibrateSignal.MHCalibrationRelTimeCam.HiGainFirst:  -5.
+#MJCalibrateSignal.MHCalibrationRelTimeCam.HiGainLast:   10.
+#MJCalibrateSignal.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibrateSignal.MHCalibrationRelTimeCam.ProbLimit:    0.00001
+#MJCalibrateSignal.MHCalibrationRelTimeCam.OverflowLimit: 0.005
+MJCalibrateSignal.MHCalibrationRelTimeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# Resource for movie encoding. For more details see IACT wiki
+# -------------------------------------------------------------------------
+#MMoviePrepare.FirstSlice: 0
+#MMoviePrepare.LastSlice:  15
+#MovieFilter.Condition: MMovieData.fMax>5*MMovieData.fMedianPedestalRms
+#MImgCleanStd.CleanLevel1: 8.0
+#MImgCleanStd.CleanLevel2: 4.5
+#MFEvtNumber.FileName: ganymed00001218.root
+#MFEvtNumber.Selector: ThetaSquared.fVal<0.04 && DataType.fVal>0.5
+#MMovieWrite.TargetLength: 5
+#MMovieWrite.NumEvents: 500
+#MMovieWrite.Threshold: 3
+#MMovieWrite.FileName: filename.mpg
+
+# -------------------------------------------------------------------------
+# This is a special option for the datacheck. A task executed as last
+# task in the event processing task list - in the standard software it
+# is skipped
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.FinalFantasy: MHCamFlorian
Index: branches/Mars_McMismatchStudy/callisto_mux.rc
===================================================================
--- branches/Mars_McMismatchStudy/callisto_mux.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/callisto_mux.rc	(revision 17960)
@@ -0,0 +1,479 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                             Calibration
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJPedestal output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathOut: .
+#MJPedestalC2.PathOut: .
+
+# -------------------------------------------------------------------------
+# Use this if you want to modify the exclusion of pixels from the beginning
+# (default: Pixel 0 and 559)
+# -------------------------------------------------------------------------
+MJPedestalC1.BadPixelsFile: mjobs/badpixels_0_559.rc
+
+# -------------------------------------------------------------------------
+# Use this if you want to modify files containing information about the 
+# reference lines in the status display
+# -------------------------------------------------------------------------
+MJPedestalC1.ReferenceFile: resources/pedestalref_mux.rc
+MJPedestalC2.ReferenceFile: resources/pedestalref_mux.rc
+MJCalibration.ReferenceFile: resources/calibrationref_mux.rc
+MJCalibration.MHCalibrationRelTimeCam.ReferenceFile: resources/calibrationref_mux.rc
+MJCalibration.MHCalibrationChargeCam.ReferenceFile: resources/calibrationref_mux.rc
+
+# -------------------------------------------------------------------------
+# Use this to define where the calibration output is stored. The filename
+# is created from the sequence number. If nothing is specified '.' is
+# assumed. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJCalibration.PathOut: calped
+
+# -------------------------------------------------------------------------
+# Use this to define where the program should search for the pedestal
+# and calibration files defined in the sequence. To use the local
+# directory use '.' If nothing is specified the default path in the
+# datacenter is used. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathData:   /data/MAGIC/Period016/
+#MJPedestalC2.PathData:   /data/MAGIC/Period016/
+#MJCalibration.PathData:  /data/MAGIC/Period016/
+
+# -------------------------------------------------------------------------
+# Define here which signal extractor you are going to use for the
+# whole calibration chain
+# -------------------------------------------------------------------------
+MJPedestalC1.ExtractSignal: MExtractTimeAndChargeSpline
+# -------------------------------------------------------------------------
+# Possibilities for a different extractor
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal: MExtractTimeAndChargeDigitalFilter, MExtractTimeAndChargeDigitalFilterPeakSearch, MExtractTimeAndChargeSlidingWindow
+# -------------------------------------------------------------------------
+# Define here parameters valid for all extractors above
+# The actual defaults used depend on the extractor in use.
+# For details see the corresponding source code
+# -------------------------------------------------------------------------
+MJPedestalC1.ExtractSignal.HiGainFirst:         0
+MJPedestalC1.ExtractSignal.HiGainLast:         49
+#MJPedestalC1.ExtractSignal.LoGainFirst:         0
+#MJPedestalC1.ExtractSignal.LoGainLast:          0
+MJPedestalC1.ExtractSignal.SaturationLimit:   252
+#MJPedestalC1.ExtractSignal.OffsetLoGain:     1.51
+#MJPedestalC1.ExtractSignal.LoGainSwitch:      150
+#MJPedestalC1.ExtractSignal.LoGainStartShift: -2.8
+# -------------------------------------------------------------------------
+# Define here parameters valid for the spline:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.Resolution:        0.05
+MJPedestalC1.ExtractSignal.RiseTimeHiGain:    4.0
+MJPedestalC1.ExtractSignal.FallTimeHiGain:    5.0
+#MJPedestalC1.ExtractSignal.LoGainStretch:     1.5
+#MJPedestalC1.ExtractSignal.ExtractionType: Integral <default>
+#MJPedestalC1.ExtractSignal.ExtractionType: Amplitude
+
+# -------------------------------------------------------------------------
+# In the case of the Digital filter you have to overwrite the default
+# weights file depending on what you are extracting
+# -------------------------------------------------------------------------
+#MJPedestalC2.ExtractSignal.WeightsFile:          msignal/calibration_weights_UV4.dat
+#MJPedestalY2.ExtractSignal.WeightsFile:          msignal/cosmics_weights4.dat
+#MJPedestalY3.ExtractSignal.WeightsFile:          msignal/cosmics_weights4.dat
+#MJCalibration.ExtractSignal.WeightsFile:         msignal/calibration_weights_UV4.dat
+#MJCalibrateSignal.ExtractSignal.WeightsFile:     msignal/cosmics_weights4.dat
+#MJCalibrateSignal.ExtractInterlaced.WeightsFile: msignal/calibration_weights_UV4.dat
+#MJCalibrateSignal.ExtractSignal.LoGainStretch:     1.5
+#MJCalibrateSignal.ExtractInterlaced.LoGainStretch: 1.5
+
+# -------------------------------------------------------------------------
+# Configure MJCalibration
+# -------------------------------------------------------------------------
+
+# Switch on relative time calibration
+#MJCalibration.RelTimeCalibration: Yes
+# Set color to be used
+#MJCalibration.Color:
+# Type of used data format: raw, root, mc
+#MJCalibration.DataType: Root
+# Type of displayed plots: Full,DataCheck,Normal
+#MJCalibration.Display: datacheck
+# Write additinal debug output
+#MJCalibration.Debug: No
+# Use blind pixel
+#MJCalibration.UseBlindPixel: No
+# Use pin diode
+#MJCalibration.UsePINDiode: No
+# Use pixel check option
+#MJCalibration.PixelCheck: No
+#MJCalibTest.PixelCheck: No
+
+# -------------------------------------------------------------------------
+# Individual events check for calibration results
+# -------------------------------------------------------------------------
+
+#ContCosmics.MaxEmptyPixels:      0.2
+#ContCosmics.MaxExcludedFraction: 1
+#ContCosmics.MinAcceptedFraction: 0
+
+# -------------------------------------------------------------------------
+# In case of MOON DATA, uncomment the following lines:
+# (better: call callisto with option "-moon")
+# -------------------------------------------------------------------------
+#MJPedestalC1.UseHists: yes
+#MJPedestalC2.UseHists: yes
+#MJPedestalY1.UseHists: yes
+#MJPedestalY2.UseHists: yes
+#MJPedestalY3.UseHists: yes
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcPedRun use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinSize:     29
+
+#MJPedestalC2.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcFromLoGain use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC1.ExtractPedestal.MaxSignalVar:     40
+
+#MJPedestalC2.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC2.ExtractPedestal.MaxSignalVar:     40
+
+# -------------------------------------------------------------------------
+# Configure MJPedestalC1 and MJPedestalC2
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalC1.DataType: Root
+#MJPedestalC2.DataType: Root
+#MJPedestalC3.DataType: Root
+# Type of displayed plots: Full,DataCheck,None
+#MJPedestalC1.Display: datacheck
+#MJPedestalC2.Display: datacheck
+#MJPedestalC3.Display: datacheck
+# Maximum number of event processed in the loop
+#MJPedestalC1.MaxEvents: 1000
+#MJPedestalC2.MaxEvents: 1000
+# Allow to overwrite existing files with the output file
+#MJPedestalC1.AllowOverwrite: No
+#MJPedestalC2.AllowOverwrite: No
+# Use data runs from the sequence instead of calibration runs
+#MJPedestalC1.UseData: No
+#MJPedestalC2.UseData: No
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the software low-gain switch
+# -------------------------------------------------------------------------
+#MJCalibration.ExtractSignal.LoGainSwitch:     150
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the higain-vs. logain intercalibration
+# -------------------------------------------------------------------------
+#MJCalibration.HiLoCalibFile:    resources/hilocalib_sp1.rc
+
+# -------------------------------------------------------------------------
+# Use this to change the behaviour of the calibration
+# -------------------------------------------------------------------------
+# Type if you set a colour explicitely from outside (only for MC!!!)
+#MJCalibration.MCalibColorSet.ExplicitColor: green,blue,uv,ct1
+
+#MJCalibration.MCalibrationChargeCalc.ArrTimeRmsLimit:    5.0
+#MJCalibration.MCalibrationChargeCalc.ChargeLimit:        2.5
+#MJCalibration.MCalibrationChargeCalc.ChargeErrLimit:     0
+#MJCalibration.MCalibrationChargeCalc.ChargeRelErrLimit:  1
+#MJCalibration.MCalibrationChargeCalc.Debug:              no
+
+#MJCalibration.MCalibrationChargeCalc.FFactorErrLimit:    4.5
+#MJCalibration.MCalibrationChargeCalc.LambdaErrLimit:     0.2
+#MJCalibration.MCalibrationChargeCalc.LambdaCheckLimit:   0.5
+#MJCalibration.MCalibrationChargeCalc.PheErrLowerLimit:   9.0
+#MJCalibration.MCalibrationChargeCalc.PheErrUpperLimit:   5.5
+
+#MJCalibration.MHCalibrationChargeCam.Debug:           no
+#MJCalibration.MHCalibrationChargeCam.LoGain:          yes
+#MJCalibration.MHCalibrationChargeCam.Oscillations:    yes
+#MJCalibration.MHCalibrationChargeCam.SizeCheck:       yes
+#MJCalibration.MHCalibrationChargeCam.Averageing:      yes
+MJCalibration.MHCalibrationChargeCam.HiGainNbins:     800
+MJCalibration.MHCalibrationChargeCam.HiGainFirst:     -0.5
+MJCalibration.MHCalibrationChargeCam.HiGainLast:      3999.5
+#MJCalibration.MHCalibrationChargeCam.LoGainNbins:     500
+#MJCalibration.MHCalibrationChargeCam.LoGainFirst:     -100.25
+#MJCalibration.MHCalibrationChargeCam.LoGainLast:      899.75
+#MJCalibration.MHCalibrationChargeCam.TimeLowerLimit:  1. 
+#MJCalibration.MHCalibrationChargeCam.TimeUpperLimit:  3. 
+#MJCalibration.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibration.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+MJCalibration.MHCalibrationChargeCam.ProbLimit:        1.0E-18
+#MJCalibration.MHCalibrationChargeCam.OverflowLimit:   0.005
+#MJCalibration.MHCalibrationChargeCam.PulserFrequency: 500
+
+#MJCalibration.MHCalibrationRelTimeCam.Debug:           no
+#MJCalibration.MHCalibrationRelTimeCam.LoGain:          no
+#MJCalibration.MHCalibrationRelTimeCam.Oscillations:    yes
+#MJCalibration.MHCalibrationRelTimeCam.SizeCheck:       yes
+#MJCalibration.MHCalibrationRelTimeCam.Averageing:      yes
+MJCalibration.MHCalibrationRelTimeCam.Nbins:           751
+MJCalibration.MHCalibrationRelTimeCam.First:           -60
+MJCalibration.MHCalibrationRelTimeCam.Last:             60
+#MJCalibration.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibration.MHCalibrationRelTimeCam.ProbLimit:       0.00001
+#MJCalibration.MHCalibrationRelTimeCam.OverflowLimit:   0.005
+#MJCalibration.MHCalibrationRelTimeCam.PulserFrequency: 500
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                            Signal extraction
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use a OutputPath if you want to write the results to a file
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.PathOut:  .
+#MJPedestalY1.PathOut:        .
+#MJPedestalY2.PathOut:        .
+#MJPedestalY3.PathOut:        .
+#MJPedestalY1.PathData:      /data/MAGIC/Period016/
+#MJPedestalY2.PathData:      /data/MAGIC/Period016/
+#MJPedestalY3.PathData:      /data/MAGIC/Period016/
+#MJCalibrateSignal.PathData: /data/MAGIC/Period016/
+#MJCalibrateSignal.PathIn:   .
+
+# -------------------------------------------------------------------------
+# If you want to change the behaviour of the pedestal extraction...
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalY1.DataType: Root
+#MJPedestalY2.DataType: Root
+#MJPedestalY3.DataType: Root
+#MJPedestalY1.UseData: Yes
+#MJPedestalY2.UseData: Yes
+#MJPedestalY3.UseData: Yes
+#MJPedestalY1.MinEvents: 50
+#MJPedestalY2.MinEvents: 50
+#MJPedestalY3.MinEvents: 50
+
+MJPedestalY1.MaxEvents:  50000
+MJPedestalY2.MaxEvents: 100000
+MJPedestalY3.MaxEvents:  50000
+
+MJPedestalY1.MaxPedestals: 500
+MJPedestalY2.MaxPedestals: 500
+MJPedestalY3.MaxPedestals: 500
+
+# -------------------------------------------------------------------------
+# When the starting pedestal is extracted from the first events of
+# the data run also the average pulse position of these events
+# is determined. If the pulse position check is switched on (default)
+# the extraction window of the hi- and lo-gain extractor for the
+# determined average pulse position is not allowed to exceed the
+# extractors search region. In this scenario we assume that the
+# start of the extraction window is at least similar to the
+# rising edge of the pulse.
+# To make sure that the search region and the extraction window
+# does not touch increase the values.
+# -------------------------------------------------------------------------
+#MJPedestalY2.PulsePosCheck: yes
+#MJPedestalY2.ExtractWinLeft:  0.0 
+#MJPedestalY2.ExtractWinRight: 0.0
+
+# -------------------------------------------------------------------------
+# Define the Pulse Position check parameters:
+# -------------------------------------------------------------------------
+MJPedestalY2.MHCalibrationPulseTimeCam.SaturationLimit:  200
+MJPedestalY2.MHCalibrationPulseTimeCam.LowerSignalLimit:  35
+#MJPedestalY2.MHCalibrationPulseTimeCam.NumPixelsRequired:  3
+#MJPedestalY2.PixelCheck: no
+
+#MJPedestalY.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalY.ExtractPedestal.PedestalUpdate:   no
+
+# -------------------------------------------------------------------------
+# Setup pedestal extractor for running through data
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MPedCalcFundamental.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFundamental.NumDump:          500
+#MJCalibrateSignal.MPedCalcFundamental.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFundamental.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFundamental.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFundamental.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFromExtractorRndm.MaxSignalVar:      40
+
+#MJCalibrateSignal.MPedCalcFromExtractor.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractor.NumDump:          500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumEventsDump:    500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumAreasDump:     500
+#MJCalibrateSignal.MPedCalcFromExtractor.NumSectorsDump:   500
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinFirst:   17
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinSize:     6
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinFirst:      0
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinSize:      29
+#MJCalibrateSignal.MPedCalcFromExtractor.MaxSignalVar:      40
+
+# -------------------------------------------------------------------------
+# Configure the interlaced calibration updates
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateWithFFactorMethod: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumEventsDump: 500
+#MJCalibrateSignal.MCalibCalcFromPast.UpdateNumPhes: yes
+#MJCalibrateSignal.MCalibCalcFromPast.NumPhesDump: 10
+#MJCalibrateSignal.MCalibrationChargeCalc.Debug: no
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the signal extractor
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.ExtractSignal.LoGainSwitch:    150
+
+# -------------------------------------------------------------------------
+# Setup calibration of data
+# -------------------------------------------------------------------------
+# Type of used data format: raw,root,MC
+#MJCalibrateSignal.DataType: Root
+# Type if you set a colour explicitely from outside (only for MC!!!)
+#MJCalibrateSignal.MCalibColorSet.ExpicitColor: green,blue,uv,ct1
+#MJCalibrateSignal.MCalibrateData.PedestalFlag: Event
+#MJCalibrateSignal.MCalibrateData.ScaleFactor: 0.85182358
+MJCalibrateSignal.MCalibrateData.FileNameScale: resources/calibration_spline.rc
+#MJCalibrateSignal.MCalibrateData.CalibrationMode: Default
+#MJCalibrateSignal.MCalibrateData.CalibConvMinLimit: 0.01
+#MJCalibrateSignal.MCalibrateData.CalibConvMaxLimit: 5.
+#MJCalibrateSignal.Interlaced: yes
+#MJCalibrateSignal.RelTimesUpdate: yes
+
+# -------------------------------------------------------------------------
+# Setup level for determining of bad pixels
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevel:         3.0
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevelVariance: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.NumMinNeighbors:    3
+#MJCalibrateSignal.MBadPixelsTreat.MaxArrivalTimeDiff: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.UseInterpolation:   yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalEvt: yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalRun: no
+#MJCalibrateSignal.MBadPixelsTreat.ProcessTimes:       yes
+#MJCalibrateSignal.MBadPixelsTreat.UseCentralPixel:    no
+#MJCalibrateSignal.MBadPixelsTreat.HardTreatment:      no
+
+# -------------------------------------------------------------------------
+# Setup interlaced calibration events histogramming
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationChargeCam.Debug:           no
+#MJCalibrateSignal.MHCalibrationChargeCam.LoGain:          yes
+MJCalibrateSignal.MHCalibrationChargeCam.Oscillations:    no
+#MJCalibrateSignal.MHCalibrationChargeCam.SizeCheck:       yes
+#MJCalibrateSignal.MHCalibrationChargeCam.Averageing:      yes
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainNbins:     500
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainFirst:     -100.5
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainLast:      1899.5
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainNbins:     800
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainFirst:     -0.5
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainLast:      3999.5
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeLowerLimit:  1. 
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeUpperLimit:  3. 
+#MJCalibrateSignal.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibrateSignal.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibrateSignal.MHCalibrationChargeCam.ProbLimit:       0.0001
+#MJCalibrateSignal.MHCalibrationChargeCam.OverflowLimit:   0.005
+MJCalibrateSignal.MHCalibrationChargeCam.PulserFrequency: 25
+
+# -------------------------------------------------------------------------
+# Setup relative time interlaced calibration
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Debug:           no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.LoGain:          no
+MJCalibrateSignal.MHCalibrationRelTimeCam.Oscillations:    no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.SizeCheck:       yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Averageing:      yes
+MJCalibrateSignal.MHCalibrationRelTimeCam.Nbins:           751
+MJCalibrateSignal.MHCalibrationRelTimeCam.First:           -60
+MJCalibrateSignal.MHCalibrationRelTimeCam.Last:             60
+#MJCalibrateSignal.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibrateSignal.MHCalibrationRelTimeCam.ProbLimit:       0.00001
+#MJCalibrateSignal.MHCalibrationRelTimeCam.OverflowLimit:   0.005
+MJCalibrateSignal.MHCalibrationRelTimeCam.PulserFrequency: 25
+
+# -------------------------------------------------------------------------
+# Resource for movie encoding. For more details see IACT wiki
+# -------------------------------------------------------------------------
+#MMoviePrepare.FirstSlice: 10
+#MMoviePrepare.LastSlice:  50
+#MovieFilter.Condition: MMovieData.fMax>5*MMovieData.fMedianPedestalRms
+#MImgCleanStd.CleanLevel1: 8.0
+#MImgCleanStd.CleanLevel2: 4.5
+#MFEvtNumber.FileName: ganymed00001218.root
+#MFEvtNumber.Selector: ThetaSquared.fVal<0.04 && DataType.fVal>0.5
+#MMovieWrite.TargetLength: 5
+#MMovieWrite.NumEvents: 500
+#MMovieWrite.Threshold: 3
+#MMovieWrite.FileName: filename.mpg
+
+# -------------------------------------------------------------------------
+# This is a special option for the datacheck. A task executed as last
+# task in the event processing task list - in the standard software it
+# is skipped
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.FinalFantasy: MHCamFlorian
Index: branches/Mars_McMismatchStudy/ceres.cc
===================================================================
--- branches/Mars_McMismatchStudy/ceres.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/ceres.cc	(revision 17960)
@@ -0,0 +1,394 @@
+#include <TClass.h>
+#include <TSystem.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include <TVector2.h>
+
+#include "MArray.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStatusDisplay.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MDirIter.h"
+
+#include "MJSimulation.h"
+
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "====================================================" << endl;
+    gLog << "                Ceres - MARS V" << MARSVER           << endl;
+    gLog << " MARS - Camera Electronics and REflector Simulation" << endl;
+    gLog << "    Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "====================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   ceres [options] [inputfiles|sequence.txt]" << endl << endl;
+    gLog << "     inputfiles              MMCS (CORSIKA) binary (cherenkov) files, wildcards allowed." << endl;
+    gLog << "     sequence.txt            A sequence file." << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file and" << endl;
+    gLog << "                              command line" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << "   --rc=Name:option          Set or overwrite a resource of the resource file." << endl;
+    gLog << "                             (Note, that this option can be used multiple times)" << endl;
+    gLog << endl;
+    gLog << " Output options:" << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   -ff                       Force reading of file even if problems occur" << endl;
+    gLog << "   --out=path                Path to write the all results to [def=local path]" << endl;
+    gLog << "   --ind=path                Input path of Corsika files if sequence used" << endl;
+    gLog << "                              [def=standard path in datacenter]" << endl;
+    gLog << "   --outf=filename           Output filename. Combines all input files into" << endl;
+    gLog << "                              one output file. (Note that the output file will" << endl;
+    gLog << "                              contain only the headers corresponding to the" << endl;
+    gLog << "                              first input file)" << endl;
+    gLog << "   --dev-null                Suppress output of files (for test purpose)" << endl;
+    gLog << "   --print-seq               Print Sequence information [sequence only]" << endl;
+    gLog << "   --print-files             Print Files taken from Sequence" << endl;
+    gLog << "   --print-found             Print Files found from Sequence" << endl;
+    gLog << "   --config=ceres.rc         Resource file [default=reflector.rc]" << endl;
+    gLog << endl;
+    gLog << "   --mode=pedestal           Execution mode. Produce either pedestals," << endl;
+    gLog << "   --mode=calibration        calibration data (no input files required) or" << endl;
+    gLog << "   --mode=data               process data files [default]" << endl << endl;
+    gLog << "   --run-number=#            Optionally set the run number of the run to simulate" << endl;
+    gLog << "   --fits                    Write FITS output files instead of root files." << endl << endl;
+    gLog << endl;
+//    gLog << "     -f:  force reading of runheader" << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Ceres,  formal designation 1 Ceres, is the smallest identified dwarf planet in" << endl;
+    gLog << " the Solar System  and the only one in the asteroid belt.  It was discovered on" << endl;
+    gLog << " January 1,  1801,  by Giuseppe Piazzi,  and  is named after  the Roman goddess" << endl;
+    gLog << " Ceres, the goddess of growing plants, the harvest, and of motherly love." << endl;
+    gLog << " With a diameter  of about 950km,  Ceres is by far the largest and most massive" << endl;
+    gLog << " body  in the asteroid belt,  and  contains  a third of  the belt's total mass." << endl;
+    gLog << " Recent observations  have revealed that it is spherical,  unlike the irregular" << endl;
+    gLog << " shapes of smaller bodies with lower gravity.  The surface of Ceres is probably" << endl;
+    gLog << " made of a mixture of water ice  and various hydrated minerals  like carbonates" << endl;
+    gLog << " and clays. Ceres appears to be differentiated into a rocky core and ice mantle." << endl;
+    gLog << " It may harbour an ocean of liquid water underneath its surface, which makes it" << endl;
+    gLog << " a potential target in the search for extraterrestrial life." << endl;
+    gLog << " Ceres' apparent magnitude  ranges from  6.7 to 9.3,  hence at its brightest is" << endl;
+    gLog << " still too dim to be seen with the naked eye. On Sept. 27, 2007,  NASA launched" << endl;
+    gLog << " the Dawn space probe to explore Vesta and Ceres." << endl << endl;
+    gLog << "Example:" << endl;
+    gLog << " ceres -f --out=outpath/ cer000001 cer000002" << endl;
+    gLog << endl;
+}
+
+static void PrintFiles(const MArgs &arg, Bool_t allopt)
+{
+    const char *prep = allopt ? "Found" : "Scheduled";
+
+    gLog << all;
+    gLog.Separator(Form("%s Data Files", prep));
+    for (int i=0; i<arg.GetNumArguments(); i++)
+        if (!allopt || gSystem->AccessPathName(arg.GetArgumentStr(i), kFileExists)==0)
+            gLog << arg.GetArgumentStr(i) << endl;
+    gLog << endl;
+}
+
+
+static void PrintFiles(const MSequence &seq, const TString &kInpathD, Bool_t allopt)
+{
+    const char *prep = allopt ? "Found" : "Scheduled";
+
+    MDirIter Next;
+    seq.GetRuns(Next, MSequence::kCorsika, kInpathD);
+
+    gLog << all;
+    gLog.Separator(Form("%s Data Files", prep));
+    Next.Print(allopt?"all":"");
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+    //const Int_t   kCompLvl   = arg.GetIntAndRemove("--comp=", 1);
+    const Bool_t  kForce      = arg.HasOnlyAndRemove("-ff");
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+    const Bool_t  kNullOut    = arg.HasOnlyAndRemove("--dev-null");
+    Int_t kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+    const Bool_t  kPrintFiles = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kPrintFound = arg.HasOnlyAndRemove("--print-found");
+
+    const Bool_t  kQuit       = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+
+    const TString kConfig     = arg.GetStringAndRemove("--config=", "ceres.rc");
+    const TString kInpath     = arg.GetStringAndRemove("--ind=", "");
+    const TString kOutpath    = arg.GetStringAndRemove("--out=", ".");
+    const TString kOutfile    = arg.GetStringAndRemove("--outf=", "");
+
+    const Int_t   kRunNumber  = arg.GetIntAndRemove("--run-number=", -1);
+
+    const TString kOpMode     = arg.GetStringAndRemove("--mode=", "data");
+    const Bool_t  kFitsFile   = arg.HasOnlyAndRemove("--fits");
+
+    Int_t opmode = -1;
+    if (TString("data").BeginsWith(kOpMode, TString::kIgnoreCase))
+        opmode = MJSimulation::kModeData;
+    if (TString("pointrun").BeginsWith(kOpMode, TString::kIgnoreCase))
+        opmode = MJSimulation::kModePointRun;
+    if (TString("pedestal").BeginsWith(kOpMode, TString::kIgnoreCase))
+        opmode = MJSimulation::kModePed;
+    if (TString("calibration").BeginsWith(kOpMode, TString::kIgnoreCase))
+        opmode = MJSimulation::kModeCal;
+
+    if (opmode<0)
+    {
+        gLog << err << "ERROR - Wrong mode specified..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // check for the right usage of the program (number of arguments)
+    if (arg.GetNumArguments()<1 && opmode==MJSimulation::kModeData)
+    {
+        gLog << warn << "WARNING - Wrong number of arguments..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // for compatibility with the first version of ceres
+    //
+    if (arg.GetNumArguments()==1 && opmode==MJSimulation::kModeData)
+    {
+        if (arg.GetArgumentStr(0)=="pedestal")
+        {
+            opmode = MJSimulation::kModePed;
+            arg.RemoveArgument(0);
+        }
+        if (arg.GetArgumentStr(0)=="calibration")
+        {
+            opmode = MJSimulation::kModeCal;
+            arg.RemoveArgument(0);
+        }
+    }
+
+    if (arg.GetNumArguments()>0 && opmode!=MJSimulation::kModeData)
+    {
+        gLog << warn << "WARNING - No arguments allowed in this mode..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // Now we access/read the resource file. This will remove all
+    // --rc= from the list of arguments.
+    //
+    MEnv env(kConfig, "ceres.rc");
+    if (!env.IsValid())
+    {
+        gLog << err << "ERROR - Reading resource file " << kConfig << "." << endl;
+        return 0xfe;
+    }
+
+    // And move the resource options from the command line to the MEnv
+    if (!env.TakeEnv(arg, kDebugEnv>2))
+        return 0xfd;
+
+    //
+    // check for the right usage of the program (number of options)
+    //
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 2;
+    }
+
+    //
+    // Setup sequence file and check for its existance
+    //
+    TString kSequence = arg.GetNumArguments()==1 ? arg.GetArgumentStr(0) : "";
+
+    //
+    // Check if the first argument (if any) is a sequence file or not
+    //
+    if (!kSequence.EndsWith(".txt"))
+        kSequence = "";
+
+    //
+    // Something special for datacenter access
+    //
+    if (!kSequence.IsNull() && !MSequence::InflateSeq(kSequence, kTRUE))
+        return 2;
+
+    //
+    // Setup sequence and check its validity
+    //
+    MSequence seq(kSequence, kInpath);
+    if (!kSequence.IsNull())
+    {
+        if (kPrintSeq)
+        {
+            gLog << all;
+            gLog.Separator(kSequence);
+            seq.Print();
+            gLog << endl;
+        }
+        if (seq.IsValid() && !seq.IsMonteCarlo())
+        {
+            gLog << err << "Sequence is not a Monte Carlo Sequence." << endl << endl;
+            return 2;
+        }
+        if (!seq.IsValid())
+        {
+            gLog << err << "Sequence read but not valid!" << endl << endl;
+            return 2;
+        }
+
+        //
+        // Process print options
+        //
+        if (kPrintFiles)
+            PrintFiles(seq, kInpath, kFALSE);
+        if (kPrintFound)
+            PrintFiles(seq, kInpath, kTRUE);
+    }
+    else
+    {
+        if (kPrintFiles)
+            PrintFiles(arg, kFALSE);
+        if (kPrintFound)
+            PrintFiles(arg, kTRUE);
+    }
+
+    //
+    // Initialize root
+    //
+    TVector2::Class()->IgnoreTObjectStreamer();
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("ceres", &argc, argv);
+    if ((!gROOT->IsBatch() && !gClient) || (gROOT->IsBatch() && !kBatch))
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(seq.IsValid() ? Form("-- Ceres: %s --", kSequence.Data()) : "-- Ceres --");
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Do star in a block (debug mem)
+    //
+    {
+        MJSimulation job(seq.IsValid() ? Form("Ceres #%d", seq.GetSequence()) : "Ceres");
+        //job.SetSequence(seq);
+        job.SetEnv(&env);
+        job.SetEnvDebug(kDebugEnv);
+        job.SetDisplay(d);;
+        job.SetOverwrite(kOverwrite);
+        job.SetPathOut(kOutpath);
+        job.SetFileOut(kOutfile);
+        job.SetNullOut(kNullOut);
+        job.SetForceMode(kForce);
+        job.SetWriteFitsFile(kFitsFile);
+        job.SetMode(opmode);
+        job.SetCommandLine(MArgs::GetCommandLine(argc, argv));
+        job.SetRunNumber(kRunNumber);
+
+        // job.SetPathIn(kInpath); // not yet needed
+
+        if (!job.Process(arg, seq))
+        {
+            gLog << err << "Calculation of ceres failed." << endl << endl;
+            return 2;
+        }
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/ceres.rc
===================================================================
--- branches/Mars_McMismatchStudy/ceres.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/ceres.rc	(revision 17960)
@@ -0,0 +1,235 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/fact/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/fact/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: resmc/fact/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/fact/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 4
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           resmc/fact/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    resmc/fact/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       resmc/fact/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            resmc/fact/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+#MSimRandomPhotons.FrequencyNSB:   0.025
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/fact/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: resmc/fact/fact-trigger-sum.txt
+
+# DiscriminatorThreshold is 9*offset(-1850)+21*gain(22.375)=16180.125
+MSimTrigger.DiscriminatorThreshold: -16180.125
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 25
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: resmc/fact/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:         300
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+MSimCamera.DefaultOffset: -1850.0
+MSimCamera.DefaultNoise:    2.8125
+MSimCamera.DefaultGain:    22.375
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.ACFudgeFactor: 0.3367
+MSimCamera.ACTimeConstant: 20
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/condor/macro.submit
===================================================================
--- branches/Mars_McMismatchStudy/condor/macro.submit	(revision 17960)
+++ branches/Mars_McMismatchStudy/condor/macro.submit	(revision 17960)
@@ -0,0 +1,13 @@
+Executable    = $ENV(ROOTSYS)/bin/root
+Arguments     = -b -q $(macro).C(\"$(args)\")
+
+Output        = $(out).log
+Error         = $(err).err
+
+Universe      = vanilla
+copy_to_spool = false
+getenv        = True
+Log           = /tmp/delme.log
+notification  = Error
+
+Queue
Index: branches/Mars_McMismatchStudy/condor/processds.submit
===================================================================
--- branches/Mars_McMismatchStudy/condor/processds.submit	(revision 17960)
+++ branches/Mars_McMismatchStudy/condor/processds.submit	(revision 17960)
@@ -0,0 +1,12 @@
+copy_to_spool = false
+Executable    = ./ganymed
+Arguments     = -b -f -v5 --config=$(rc) $(add) --n=$(num) --out=$(path)$(out) --log=$(path)$(out)/ganymed$(num).log $(path)/datasets/dataset$(ds).txt
+Universe      = vanilla
+Log           = /tmp/condor.log
+Error         = $(path)/logs/condor-ds.error
+Output        = $(path)/logs/condor-ds.out
+notification  = Error
+getenv = True
+
+Queue 
+
Index: branches/Mars_McMismatchStudy/condor/processsponde.submit
===================================================================
--- branches/Mars_McMismatchStudy/condor/processsponde.submit	(revision 17960)
+++ branches/Mars_McMismatchStudy/condor/processsponde.submit	(revision 17960)
@@ -0,0 +1,12 @@
+copy_to_spool = false
+Executable    = ./sponde
+Arguments     = -b -f -v5 --config=$(rc) --log=$(out)/sponde$(spondenum).log $(out)/ganymed$(num).root $(mcds) $(out)/sponde$(spondenum).root 
+Universe      = vanilla
+Log           = /tmp/condor.log
+Error         = $(path)/logs/condor-sponde.error
+Output        = $(path)/logs/condor-sponde.out
+notification  = Error
+getenv = True
+
+Queue 
+
Index: branches/Mars_McMismatchStudy/condor/program.submit
===================================================================
--- branches/Mars_McMismatchStudy/condor/program.submit	(revision 17960)
+++ branches/Mars_McMismatchStudy/condor/program.submit	(revision 17960)
@@ -0,0 +1,14 @@
+Executable    = ./$(prg)
+Arguments     = $(args)
+
+Output        = $(out)
+Error         = $(err)
+
+Universe      = vanilla
+copy_to_spool = false
+getenv        = True
+#Log           = /tmp/dag.log
+#Log           = $(out)
+notification  = Error
+
+Queue
Index: branches/Mars_McMismatchStudy/condor/script.submit
===================================================================
--- branches/Mars_McMismatchStudy/condor/script.submit	(revision 17960)
+++ branches/Mars_McMismatchStudy/condor/script.submit	(revision 17960)
@@ -0,0 +1,13 @@
+Executable    = $(script)
+Arguments     = -v -i -c $(arg)
+
+Out           = $(out)
+Error         = $(err)
+
+Universe      = vanilla
+copy_to_spool = false
+Log           = /tmp/delme.log
+notification  = Error
+getenv        = True
+
+Queue
Index: branches/Mars_McMismatchStudy/datacenter/db/builddatasets.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/builddatasets.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/builddatasets.php	(revision 17960)
@@ -0,0 +1,1025 @@
+<?php
+
+    function PrintDataSetFile()
+    {
+        if (empty($_SESSION["AnalysisNumber"]))
+            printf("AnalysisNumber: 1\n\n");
+        else
+            printf("AnalysisNumber: %s\n\n", $_SESSION["AnalysisNumber"]);
+        printf("SeqencesOn: %s \n", $_SESSION["sequon"]);
+        if ($_SESSION["sequoff"]!="")
+            printf("SeqencesOff: %s \n\n", $_SESSION["sequoff"]);
+        else
+            printf("\n");
+
+        printf("SourceName: %s \n", $_SESSION["realsourcename"]);
+        printf("Catalog: /magic/datacenter/setup/magic_favorites_dc.edb \n");
+        if ($_SESSION["sequoff"]==" ")
+            printf("WobbleMode: On \n\n");
+        printf("RunTime: %s \n", $_SESSION["runtime"]);
+        printf("Name: %s \n", $_SESSION["name"]);
+        printf("Comment: %s \n", $_SESSION["comment"]);
+    }
+
+    function CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $db_id)
+    {
+        $fromtable="Sequences";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0)
+        {
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+            //--------------------------------------------------
+            $query0 .= "SUM(fRunTime)/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
+            //--------------------------------------------------
+            $query0 .= " SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "', ";
+            $query0 .= " Min(fZenithDistanceMin) as '" . $alias["Min(fZenithDistanceMin)"] . "', ";
+            $query0 .= " Max(fZenithDistanceMax) as '" . $alias["Max(fZenithDistanceMax)"] . "', ";
+            $query0 .= " COUNT(*) as '# Sequ' ";
+        }
+        else
+        {
+            if ($statusgroups>0)
+            {
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .= " (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval 12 hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+
+                $query0 .= " COUNT(*) as '# Sequ'";
+
+            }
+            else
+            {
+                $query0 .= " " . $fromtable . ".fSequenceFirst as '" . $alias["fSequenceFirst"] . "' ";
+                if (!empty($_GET["fLinks"]))
+                {
+                    $query0 .= ", CONCAT('<A&ws;HREF=\"tabs.php?t=calib&n=', fSequenceFirst, '\">cal</A>'";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"tabs.php?t=signal&n=', fSequenceFirst, '\">sig</A>'";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"tabs.php?t=star&n=', fSequenceFirst, '\">star</A>'";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sequences/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/sequence', LPAD(CONCAT(Sequences.fSequenceFirst , '.txt'), 12,'0') , '\">', 'f </A>' ";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"queryrbk.php?fNight=', date_format(adddate(fRunStart, interval +13 HOUR), '%Y-%m-%d') , '&amp;fDate=2\">rbk</A>') ";
+                    $query0 .= " as 'Links'";
+                }
+
+                foreach ($_GET as $key => $element)
+                    if ($_GET[$key]=="On")
+                        if ($key!="fLinks" && $key!="fOff" && $key!="fOnlyOff" && $key!="fNumStart")
+                            if (!(ereg("^DSSeq[0-9]*$", $key)))
+                                if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                                    $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+            }
+        }
+
+        $query0 .= " FROM " . $fromtable;
+
+        $query0 .= " LEFT JOIN SequenceProcessStatus USING(fSequenceFirst,fTelescopeNumber) ";
+        $query0 .= " LEFT JOIN Calibration USING(fSequenceFirst,fTelescopeNumber) ";
+        $query0 .= " LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) ";
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty(GetJoin($fromtable,$key)))
+                $query0 .= GetJoin($fromtable,$key);
+
+        if (($_SESSION["DisplaySelected"]!="yes"
+             || ($_SESSION["sequon"]=="" && $_SESSION["sequoff"]==""))
+            && (empty($_SESSION["DataSetSelection"]) || $_SESSION["DataSetAcknowledged"]=="yes"))
+        {
+            if ($_GET["fTest"]!="On")
+            {
+                if ($_GET["fSourceName"]!="On")
+                    $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
+                $query0 .= " WHERE fTest='no'";
+            }
+
+            if ($_GET["fOff"]=="Off")
+            {
+                if (strpos($query0, " WHERE ")==FALSE)
+                    $query0 .= " WHERE ";
+                else
+                    $query0 .= " AND ";
+
+                $query0 .= " NOT (fSourceName like '%Off%')";
+            }
+
+            if ($_GET["fOnlyOff"]=="On")
+            {
+                if (strpos($query0, " WHERE ")==FALSE)
+                    $query0 .= " WHERE ";
+                else
+                    $query0 .= " AND ";
+
+                $query0 .= " fSourceName like '%Off%'";
+            }
+
+            foreach ($checkwhere as $key => $element)
+            {
+                if (empty($element) || $element<=0)
+                    continue;
+
+                if (strpos($query0, " WHERE ")==FALSE)
+                    $query0 .= " WHERE ";
+                else
+                    if ($element!=-1)
+                        if (strrpos($query0, " AND ")!=strlen($query0)-5)
+                            $query0 .= " AND ";
+
+                if ($element!=-1)
+                    $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+            }
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+
+            $query0 .= StatusQuery("fSequenceFileWritten", $needs, $timelimits);
+            $query0 .= StatusQuery("fAllFilesAvail", $needs, $timelimits);
+            $query0 .= StatusQuery("fCallisto", $needs, $timelimits);
+            $query0 .= StatusQuery("fFillCallisto", $needs, $timelimits);
+            $query0 .= StatusQuery("fStar", $needs, $timelimits);
+            $query0 .= StatusQuery("fFillStar", $needs, $timelimits);
+
+            if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
+                $query0 .= "Sequences.fSequenceFirst BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+            else
+                $query0 = substr($query0, 0, -4);
+
+            if ((!empty($_GET["fZDMin"]) || $_GET["fZDMin"]==0) && !empty($_GET["fZDMax"]))
+                $query0 .= "AND (fZenithDistanceMin >= " . $_GET["fZDMin"] . " AND fZenithDistanceMax <= " . $_GET["fZDMax"] . ") ";
+
+            if (!empty($_GET["fSourceN"]))
+                $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+            if (!empty($_GET["fStartDate"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $startdate=substr($_GET["fStartDate"], 0, 10);
+                if ($startdate=="0000-00-00")
+                    $query0 .=" fRunStart >= '" . $startdate . " 00:00:00' ";
+                else
+                    $query0 .= " fRunStart >= ADDDATE('" . $startdate . " 13:00:00', INTERVAL -1 DAY) ";
+            }
+
+            if (!empty($_GET["fStopDate"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $stopdate=substr($_GET["fStopDate"], 0, 10);
+                $query0 .= " fRunStart < '" . $stopdate . " 13:00:00' ";
+            }
+
+            if (!empty($_GET["fStarStart"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $starstart=substr($_GET["fStarStart"], 0, 10);
+                $query0 .=" fStar >= '" . $starstart . " 00:00:00' ";
+            }
+
+            if (!empty($_GET["fStarStop"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $starstop=substr($_GET["fStarStop"], 0, 10);
+                $query0 .= " fStar < '" . $starstop . " 23:59:59' ";
+            }
+
+            if ($_SESSION["DisplaySelected"]=="inverse")
+            {
+                $displsequ=str_replace("  ", " ", $_SESSION["sequon"].$_SESSION["sequoff"]);
+                $displsequ=ereg_replace("^ ", "(", $displsequ);
+                $displsequ=ereg_replace("$", ")", $displsequ);
+                $displsequ=str_replace(" ",  ",", $displsequ);
+
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $query0 .= " fSequenceFirst NOT IN " . $displsequ;
+            }
+
+            if ($groups>0)
+            {
+                $query0 .= " GROUP BY ";
+                $num = $groups;
+                foreach ($checkgroup as $key => $element)
+                    if ($element==-1)
+                    {
+                        $query0 .= GetCheck($fromtable,$key);
+                        if ($num-->1)
+                            $query0 .= ", ";
+                    }
+            }
+
+            if ($statusgroups>0)
+            {
+                $query0 .= " GROUP BY ";
+                $num = $statusgroups;
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                    {
+                        $query0 .= $alias[$key];
+                        if ($num-->1)
+                            $query0 .= ", ";
+                    }
+            }
+
+        }
+        else
+        {
+            if (empty($_SESSION["DataSetSelection"]) || $_SESSION["DataSetAcknowledged"]=="yes")
+            {
+                $displsequ=str_replace("  ", " ", $_SESSION["sequon"].$_SESSION["sequoff"]);
+                $displsequ=ereg_replace("^ ", "(", $displsequ);
+                $displsequ=ereg_replace("$", ")", $displsequ);
+                $displsequ=str_replace(" ",  ",", $displsequ);
+            }
+            else
+            {
+                //get on sequences
+                $query1 = "SELECT fSequenceFirst FROM DataSetSequenceMapping WHERE fOnOff=1 AND fDataSetNumber=".$_SESSION["SelectedDataSet"];
+                $result1 = mysql_query($query1, $db_id);
+                while ($row = mysql_fetch_assoc($result1))
+                {
+                    $_SESSION["DSSeq".$row["fSequenceFirst"]]="ON";
+                    $onseq.=" " . $row["fSequenceFirst"];
+                }
+                mysql_free_result($result1);
+                //get off sequences
+                $query1 = "SELECT fSequenceFirst FROM DataSetSequenceMapping WHERE fOnOff=2 AND fDataSetNumber=".$_SESSION["SelectedDataSet"];
+                $result1 = mysql_query($query1, $db_id);
+                while ($row = mysql_fetch_assoc($result1))
+                {
+                    $_SESSION["DSSeq".$row["fSequenceFirst"]]="Off";
+                    $offseq.=" " . $row["fSequenceFirst"];
+                }
+                mysql_free_result($result1);
+
+                $displsequ=str_replace("  ", " ", $onseq.$offseq);
+                $displsequ=ereg_replace("^ ", "(", $displsequ);
+                $displsequ=ereg_replace("$", ")", $displsequ);
+                $displsequ=str_replace(" ",  ",", $displsequ);
+
+                if ($_SESSION["DataSetSelection"]=="UpdateDataSet")
+                {
+                    //get values of old data set from db
+                    $queryold  = "SELECT fUserKEY, fComment, fDataSetName FROM DataSets WHERE fDataSetNumber=".$_SESSION["SelectedDataSet"];
+                    $resultold = mysql_query($queryold);
+                    $rowold = mysql_fetch_assoc($resultold);
+                    $_SESSION["olduser"] = $rowold["fUserKEY"];
+                    $_SESSION["comment"] = $rowold["fComment"];
+                    $_SESSION["name"] = $rowold["fDataSetName"];
+                    mysql_free_result($resultold);
+                }
+                $_SESSION["DisplaySelected"]="yes";
+            }
+
+            $query0 .= "WHERE fSequenceFirst IN " . $displsequ;
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable,$val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fSortBy"]) && $groups==0 && $statusgroups==0)
+            $query0 .= " ORDER BY Sequences.fSequenceFirst DESC ";
+
+        if (empty($_GET["fNumStart"]))
+            $start=0;
+        else
+            $start=$_GET["fNumStart"];
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $start . ", " . $_GET["fNumResults"];
+
+            return $query0;
+    }
+
+    function PrintForm($host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias)
+    {
+        printf("<center>\n");
+        printf("<form action='builddatasets.php' METHOD='GET'>\n");
+        printf("<input id='sh' type='hidden' name='fShowHide' value='");
+        if (!empty($_GET["fShowHide"]))
+            printf("%s", $_GET["fShowHide"]);
+        else
+            printf("1000000010");//display Ranges
+        printf("'>\n");
+        printf("<img id='allbutton' src='minus.png' alt='-' onclick='showhide(\"all\")'> <b>Menu</b>&nbsp;&nbsp;&nbsp;&nbsp;\n");
+        printf("&nbsp;&nbsp;<img id='infobutton'   src='plus.png' alt='+' onClick='showhide(\"info\");showhide(\"info2\")'> SequInfo   \n");
+        printf("&nbsp;&nbsp;<img id='statbutton'   src='plus.png' alt='+' onClick='showhide(\"stat\");showhide(\"fail\")'>  StatusInfo \n");
+        printf("&nbsp;&nbsp;<img id='calbutton'    src='plus.png' alt='+' onClick='showhide(\"cal\")'>                      CalInfo    \n");
+        printf("&nbsp;&nbsp;<img id='starbutton'   src='plus.png' alt='+' onClick='showhide(\"star\")'>                     StarInfo   \n");
+        printf("&nbsp;&nbsp;<img id='limitsbutton' src='plus.png' alt='+' onClick='showhide(\"limits\")'>                   Limits     \n");
+        printf("&nbsp;&nbsp;<img id='rangesbutton' src='plus.png' alt='+' onClick='showhide(\"ranges\")'>                   Ranges     \n");
+
+        printf(" <div id='all' style='display:block'>");
+
+        PrintSequInfo2Menu($host,$user,$pw,$db);
+        PrintSequInfoMenu();
+        PrintSequStatMenu();
+        PrintFailMenu();
+        PrintCalMenu();
+        PrintStarMenu();
+        PrintLimitsMenu($limitsmean, $limitsmin, $limitsmax, $alias, "");
+
+        printf(" <div id='ranges' style='display:none'>");
+        PrintZdRangeMenu($host,$user,$pw,$db);
+        PrintSequRangeMenu($host,$user,$pw,$db);
+        printf("<p>");
+        PrintSourceMenu($host,$user,$pw,$db);
+        PrintNightRangeMenu($host,$user,$pw,$db, "Sequences");
+        PrintStarRangeMenu($host,$user,$pw,$db);
+        printf("<p>");
+        printf("</div>");
+
+        printf("</div>");
+        printf(" <P>\n");
+
+        PrintNumResPullDown();
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        PrintButtons("builddatasets.php");
+
+//        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function InsertUpdateDataSet($values, $dataset)
+    {
+        if ($_SESSION["DataSetSelection"]=="UpdateDataSet")
+            $insquery[0]="UPDATE DataSets SET ";
+        else
+            $insquery[0]="INSERT DataSets SET fDataSetNumber=" . $dataset . ", fUserKEY=" . $_SESSION["user"] . ", ";
+        $insquery[0].=" fComment='" . $_SESSION["comment"] . "', fObservationModeKEY=" . $_SESSION["obsmode"];
+        $insquery[0].=", fDataSetName='" . $_SESSION["name"] . "', fSourceKEY= " . $_SESSION["realsourcekey"];
+        $insquery[0].=", fRunStart='" . $values["Min(fRunStart)"]["on"];
+        $insquery[0].="', fRunStop='" . $values["Max(fRunStop)"]["on"];
+        $insquery[0].="', fZenithDistanceMin=" . $values["Min(fZenithDistanceMin)"]["on"];
+        $insquery[0].=", fZenithDistanceMax=" . $values["Max(fZenithDistanceMax)"]["on"];
+        $insquery[0].=", fRunTime=" . $_SESSION["runtime"];
+        if ($_SESSION["DataSetSelection"]=="UpdateDataSet")
+        {
+            $insquery[0].=" WHERE fDataSetNumber=" . $_SESSION["SelectedDataSet"];
+
+            $insquery[1]="UPDATE DataSetProcessStatus SET fDataSetInserted=Now(), fDataSetFileWritten=NULL, ";
+            $insquery[1].=" fStarFilesAvail=NULL, fGanymed=NULL, fFillGanymed=NULL, fWebGanymed=NULL, ";
+            $insquery[1].=" fWebPlotDBGanymed=NULL, fStartTime=NULL, fFailedTime=NULL, fProgramId=NULL, ";
+            $insquery[1].=" fReturnCode=NULL WHERE fDataSetNumber=" . $_SESSION["SelectedDataSet"];
+
+            $insquery[2]=" DELETE FROM DataSetSequenceMapping WHERE fDataSetNumber=" . $_SESSION["SelectedDataSet"];
+            $i=3;
+        }
+        else
+        {
+            $insquery[1]="INSERT DataSetProcessStatus SET fDataSetNumber=" . $dataset . ", fDataSetInserted=Now()";
+            $i=2;
+        }
+        foreach(explode(" ", trim($_SESSION["sequon"])) as $key => $sequ)
+        {
+            $insquery[$i]="INSERT DataSetSequenceMapping SET fDataSetNumber=";
+            if ($_SESSION["DataSetSelection"]=="UpdateDataSet")
+                $insquery[$i].=$_SESSION["SelectedDataSet"];
+            else
+                $insquery[$i].=$dataset;
+            $insquery[$i].=", fSequenceFirst=" . $sequ . ", fOnOff=1";
+            $i=$i+1;
+        }
+        if (!empty($off))
+        {
+            foreach(explode(" ", trim($_SESSION["sequoff"])) as $key => $sequ)
+            {
+                $insquery[$i]="INSERT DataSetSequenceMapping SET fDataSetNumber=";
+                if ($_SESSION["DataSetSelection"]=="UpdateDataSet")
+                    $insquery[$i].=$_SESSION["SelectedDataSet"];
+                else
+                    $insquery[$i].=$dataset;
+                $insquery[$i].=", fSequenceFirst=" . $sequ . ", fOnOff=2";
+                $i=$i+1;
+            }
+        }
+        // insert
+        if (!empty($_SESSION["insert"]) && $numerr==0)
+        {
+            printf("<br><br>\n");
+            foreach($insquery as $num => $q)
+            {
+                printf("Executed Query #%s: %s<br>\n", $num, $q);
+                $insresult=mysql_query($q);
+                if (mysql_errno()>0)
+                    printf("&nbsp; Errorno: %s <br>\n", mysql_errno());
+                if (mysql_error()!="")
+                    printf("&nbsp; Errormsg: %s <br>\n", mysql_error());
+                if (mysql_info()!="")
+                    printf("&nbsp; Info: %s <br>\n", mysql_info());
+                printf("&nbsp; Affected Rows: %s <br><br>\n", mysql_affected_rows());
+                mysql_free_result($insresult);
+                if (mysql_errno()>0)
+                {
+                    printf("ERROR => stop inserting. <br><br>\n");
+                    break;
+                }
+            }
+            // reset after insert
+            unset($_SESSION["insert"]);
+//            unset($_SESSION["name"]);
+//            unset($_SESSION["comment"]);
+        }
+        else
+            if ($_SESSION["DataSetSelection"]=="UpdateDataSet")
+                printf("<input type='button' value='Update Data Set in DB' onClick='self.location.href=\"%s&insert=yes\"'>&nbsp;&nbsp;&nbsp;\n", GetClearedURL());
+            else
+                printf("<input type='button' value='Insert Data Set in DB' onClick='self.location.href=\"%s&insert=yes\"'>&nbsp;&nbsp;&nbsp;\n", GetClearedURL());
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs)
+    {
+        $db_id = mysql_pconnect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $db_id);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+            {
+                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $result1, "yes");
+
+                if (!(empty($_SESSION["sequon"]) && empty($_SESSION["sequoff"]))
+                   && (empty($_SESSION["olduser"]) || $_SESSION["olduser"]==$_SESSION["user"]))
+                {
+                    printf("<div align='left'>\n");
+                    printf("Remark: To store your selection, you have to press 'Update Selection'<br> \n");
+                    printf("<br>\n");
+
+                    printf("<u>Your Data Set:</u> <br>\n");
+
+                    $on=str_replace(" ", ",", trim($_SESSION["sequon"]));
+                    $off=str_replace(" ", ",", trim($_SESSION["sequoff"]));
+
+                    //set observation mode
+                    if ($_SESSION["sequoff"]=="")
+                        $obsmode="Wobble";
+                    else
+                        $obsmode="On";
+
+                    //get key from db for insert query
+                    $query   = "SELECT fObservationModeKEY FROM ObservationMode WHERE fObservationModeName='".$obsmode."'";
+                    $result  = mysql_query($query);
+                    $row = mysql_fetch_assoc($result);
+                    $_SESSION["obsmode"] = $row["fObservationModeKEY"];
+                    mysql_free_result($result);
+
+                    $values=array("Sum(fRunTime)/60"         => $runtime,
+                                  "Min(fRunTime)/60"         => $runtimemin,
+                                  "Max(fUnsuitableInner)"    => $unsuitablemax,
+                                  "Max(fUnreliableInner)"    => $unreliablemax,
+                                  "Max(fIsolatedInner)"      => $isolatedmax,
+                                  "Max(fIsolatedMaxCluster)" => $imcmax,
+                                  "Max(fArrTimeMeanInner)"   => $arrtimemax,
+                                  "Min(fArrTimeMeanInner)"   => $arrtimemin,
+                                  "Max(fArrTimeRmsInner)"    => $arrtimermsmax,
+                                  "Avg(fMeanPedRmsInner)"    => $pedrmsmean,
+                                  "Std(fMeanPedRmsInner)"    => $pedrmsrms,
+                                  "Min(fMeanPedRmsInner)"    => $pedrmsmin,
+                                  "Max(fMeanPedRmsInner)"    => $pedrmsmax,
+                                  "Min(fPulsePosMean)"       => $pulseposmin,
+                                  "Max(fPulsePosMean)"       => $pulseposmax,
+                                  "Max(fPulsePosRms)"        => $pulseposrmsmax,
+                                  "Max(fMaxHumidity)"        => $hummax,
+                                  "Max(fInhomogeneity)"      => $inhommax,
+                                  "Avg(fInhomogeneity)"      => $inhommean,
+                                  "Std(fInhomogeneity)"      => $inhomrms,
+                                  "Min(fMeanNumberIslands)"  => $numislmin,
+                                  "Max(fMeanNumberIslands)"  => $numislmax,
+                                  "Avg(fDataRate)"           => $clratemean,
+                                  "Min(fDataRate)"           => $clratemin,
+                                  "Max(fDataRate)"           => $clratemax,
+                                  "Min(fMuonRate)"           => $muonratemin,
+                                  "Max(fMuonRate)"           => $muonratemax,
+                                  "Min(fMuonNumber)"         => $muonnumbermin,
+                                  "Avg(fPSF)"                => $psfmean,
+                                  "Std(fPSF)"                => $psfrms,
+                                  "Min(fPSF)"                => $psfmin,
+                                  "Max(fPSF)"                => $psfmax,
+                                  "Min(fEffOnTime/fRunTime)" => $relontimemin,
+                                  "Max(fEffOnTime/fRunTime)" => $relontimemax,
+                                  "Min(fBrightnessMed)"      => $brightmin,
+                                  "Max(fBrightnessMed)"      => $brightmax,
+                                  "Min(fNumStarsMed)"        => $idstarsmin,
+                                  "Max(fNumStarsMed)"        => $idstarsmax,
+                                  "Min(fNumStarsCorMed)"     => $corstarsmin,
+                                  "Max(fNumStarsCorMed)"     => $corstarsmax,
+                                  "Min(fZenithDistanceMin)"  => $zdmin,
+                                  "Max(fZenithDistanceMax)"  => $zdmax,
+                                  "Min(fRunStart)"           => $starttime,
+                                  "Max(fRunStop)"            => $stoptime,
+                                 );
+                    //get runtimes of dataset
+                    function GetSequenceValues($db_id, $sequences, $txt, &$values)
+                    {
+                        $query="SELECT COUNT(*) ";
+                        foreach($values as $name => $varname)
+                            $query.=", " . $name;
+                        $query.=" FROM Sequences ";
+                        $query.=" LEFT JOIN Calibration USING(fSequenceFirst,fTelescopeNumber) ";
+                        $query.=" LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) ";
+                        $query.=" WHERE Sequences.fSequenceFirst IN (" . $sequences . ")";
+                        $result = mysql_query($query, $db_id);
+                        $row = mysql_fetch_assoc($result);
+                        foreach($values as $name => $varname)
+                            $values[$name][$txt]=$row[$name];
+                        mysql_free_result($result);
+                    }
+
+                    //get next dataset#
+                    $query="SELECT fDataSetNumber+1 FROM DataSets ORDER BY fDataSetNumber DESC LIMIT 0,1";
+                    $result = mysql_query($query, $db_id);
+                    $row = mysql_fetch_assoc($result);
+                    $dataset=$row["fDataSetNumber+1"];
+                    if (empty($dataset))
+                        $dataset=1;
+                    mysql_free_result($result);
+
+                    //get sourcenames
+                    function GetSources($db_id, $sequences)
+                    {
+                        $query="SELECT fSourceName FROM Source LEFT JOIN Sequences USING(fSourceKEY) ";
+                        $query.="WHERE fSequenceFirst IN (" . $sequences . ") GROUP BY fSourceName";
+                        $result = mysql_query($query, $db_id);
+                        while ($row = mysql_fetch_assoc($result))
+                            $sources.=" " . $row["fSourceName"];
+                        mysql_free_result($result);
+                        return $sources;
+                    }
+                    $sourceson=GetSources($db_id, $on);
+                    $sourcesoff=GetSources($db_id, $off);
+
+                    //get sourcename for dataset
+                    $son=str_replace(" ", "','", trim($sourceson));
+                    $query="SELECT fRealSourceKEY, Count(*), fSourceName FROM Source where fSourceName IN ('" . $son . "') GROUP BY fRealSourceKEY";
+                    $result = mysql_query($query, $db_id);
+                    $row = mysql_fetch_assoc($result);
+                    $numsources=$row["Count(*)"];
+                    $numrealkeys=mysql_num_rows($result);
+                    $_SESSION["realsourcekey"]=$row["fRealSourceKEY"];
+                    $_SESSION["realsourcename"]=$row["fSourceName"];
+                    mysql_free_result($result);
+                    //printf("found %s sources with real sourcekey %s", $numsources, $realsourcekey);
+                    //printf("found %s keys", $numrealkeys);
+
+                    //check observationmode for on-sequences
+                    $query="SELECT fObservationModeKEY FROM Sequences where fSequenceFirst IN (" . $on . ") GROUP BY fObservationModeKEY";
+                    $result = mysql_query($query, $db_id);
+                    $row = mysql_fetch_assoc($result);
+                    $obskey=$row["fObservationModeKEY"];
+                    $numobskeys=mysql_num_rows($result);
+                    mysql_free_result($result);
+
+                    //check dt for on-sequences
+                    $query="SELECT fDiscriminatorThresholdTableKEY FROM Sequences where fSequenceFirst IN (" . $on . ") GROUP BY fDiscriminatorThresholdTableKEY";
+                    $result = mysql_query($query, $db_id);
+                    $numdtkeys=mysql_num_rows($result);
+                    mysql_free_result($result);
+
+
+                    //set limit
+                    $runtimelimit=5;
+                    $unsuitablemaxlimit=15;
+                    $isolatedlimit=0;
+                    $imclimit=0;
+                    $pedrmsrms=0.09;
+                    $scalelimit=1.3;
+                    $inhomlimit=13;
+                    $numstarslimit=20;
+                    $numstarscorlimit=10;
+
+
+                    //check values for infos, warnings and errors
+                    $numerr=0;
+                    if (!empty($on))
+                    {
+                        $color=array("INFO"  => "#000000",
+                                     "WARN"  => "#FF9900",
+                                     "ERROR" => "#FF0000");
+                        printf("<div align='left'><font><ul>\n");
+                        $vals=array("on", "off");
+                        foreach($vals as $num => $val)
+                        {
+                            if (empty(${$val}))
+                                continue;
+                            //get information from the database
+                            GetSequenceValues($db_id, ${$val}, $val, $values);
+
+                            if ($values["Min(fNumStarsCorMed)"][$val]<$numstarscorlimit)
+                                printf("<li style='color:%s'>%s: At least one of your %s-sequences has less than %s correlated stars (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $numstarscorlimit, $values["Min(fNumStarsCorMed)"][$val]);
+                            if ($values["Min(fNumStarsMed)"][$val]<$numstarslimit)
+                                printf("<li style='color:%s'>%s: At least one of your %s-sequences has less than %s identified stars (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $numstarslimit, $values["Min(fNumStarsMed)"][$val]);
+                            if ($values["Min(fRunTime)/60"][$val]<$runtimelimit)
+                                printf("<li style='color:%s'>%s: At least one of your %s-sequences is shorter than %s min (%s min). </li>\n",
+                                       $color["INFO"], "INFO", $val, $runtimelimit, $values["Min(fRunTime)/60"][$val]);
+                            if ($values["Max(fInhomogeneity)"][$val]>$inhomlimit)
+                                printf("<li style='color:%s'>%s: At least one of your %s-sequences has an inhomogeneity larger than %s (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $inhomlimit, $values["Max(fInhomogeneity)"][$val]);
+                            if ($values["Max(fUnsuitableInner)"][$val]>$unsuitablemaxlimit)
+                                printf("<li style='color:%s'>%s: At least one of your %s-sequences has more than %s unsuitable inner pixel (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $unsuitablemaxlimit, $values["Max(fUnsuitableInner)"][$val]);
+                            if ($values["Max(fIsolatedInner)"][$val]>$isolatedlimit)
+                                printf("<li style='color:%s'>%s: At least one of your %s-sequences has more than %s isolated inner pixel (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $isolatedlimit, $values["Max(fIsolatedInner)"][$val]);
+                            if ($values["Max(fIsolatedMaxCluster)"][$val]>$imclimit)
+                                printf("<li style='color:%s'>%s: At least one of your %s-sequences has more than %s isolated max cluster (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $imclimit, $values["Max(fIsolatedMaxCluster)"][$val]);
+                        }
+                        //check selected dataset for errors
+                        if (!empty($on) && $values["Max(fMeanPedRmsInner)"]["on"]>$values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms)
+                            printf("<li style='color:%s'>%s: At least one of your on-sequences has a PedRms larger than %s (%s).</li>\n",
+                                   $color["WARN"], "WARN", $values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms, $values["Max(fMeanPedRmsInner)"]["on"]);
+                        if (!empty($off) && $values["Max(fMeanPedRmsInner)"]["off"]>$values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms)
+                            printf("<li style='color:%s'>%s: At least one of your off-sequences has a PedRms larger than %s (%s). </li>\n",
+                                   $color["WARN"], "WARN", $values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms, $values["Max(fMeanPedRmsInner)"]["off"]);
+                        if (!empty($off) && $values["Min(fMeanPedRmsInner)"]["off"]<$values["Avg(fMeanPedRmsInner)"]["on"]-$pedrmsrms)
+                            printf("<li style='color:%s'>%s: At least one of your off-sequences has a PedRms smaller than %s (%s). </li>\n",
+                                   $color["WARN"], "WARN", $values["Avg(fMeanPedRmsInner)"]["on"]-$pedrmsrms, $values["Min(fMeanPedRmsInner)"]["off"]);
+                        $scale=$values["Sum(fRunTime)/60"]["on"]/$values["Sum(fRunTime)/60"]["off"];
+                        if ($scale > $scalelimit)
+                            printf("<li style='color:%s'>%s: Your scale factor is larger than %s (%0.2f). Try to find more offdata! </li>\n",
+                                   $color["WARN"], "WARN", $scalelimit, $scale);
+                        $doubleseq=0;
+                        foreach(explode(" ", $_SESSION["sequon"]) as $n => $s)
+                        {
+                            if (ereg($s, $_SESSION["sequoff"]))
+                                $doubleseq++;
+                        }
+                        //$obskey >1 makes sure that fObservationMode is not N/A (old data)
+                        if ($obskey!=$_SESSION["obsmode"] && $obskey>1)
+                        {
+                            printf("<li style='color:%s'>%s: You have a mistake in your observation mode. </li>\n",
+                                   $color["ERROR"], "ERROR");
+                            $numerr=$numerr+1;
+                        }
+                        if ($doubleseq>0)
+                        {
+                            printf("<li style='color:%s'>%s: You have selected sequences (%s) as On AND Off. </li>\n",
+                                   $color["ERROR"], "ERROR", $doubleseq);
+                            $numerr=$numerr+1;
+                        }
+                        if ($numrealkeys>1)
+                        {
+                            printf("<li style='color:%s'>%s: You have selected more than one (%s) on source. </li>\n",
+                                   $color["ERROR"], "ERROR", $numrealkeys);
+                            $numerr=$numerr+1;
+                        }
+                        if ($numobskeys>1)
+                        {
+                            printf("<li style='color:%s'>%s: You have selected more than one (%s) different observation modes in your on sequences. </li>\n",
+                                   $color["ERROR"], "WARN", $numobskeys);
+                            //$numerr=$numerr+1;
+                        }     
+                        if ($numdtkeys>1)
+                        {
+                            printf("<li style='color:%s'>%s: Your selected on sequences have more than one (%s) different discriminator threshold tables. </li>\n",
+                                   $color["ERROR"], "WARN", $numdtkeys);
+                        }
+                        if (empty($_SESSION["realsourcekey"]))
+                        {
+                            printf("<li style='color:%s'>%s: The source you selected does not have a real sourcekey, yet. Please insert fRealSourceKEY in the DB for %s (contact: datacenter@astro.uni-wuerzburg.de). </li>\n",
+                                   $color["ERROR"], "ERROR", $sourceson);
+                            $numerr=$numerr+1;
+                        }
+                        if (empty($_SESSION["name"]))
+                        {
+                            printf("<li style='color:%s'>%s: You have to choose a name. </li>\n",
+                                   $color["ERROR"], "ERROR");
+                            $numerr=$numerr+1;
+                        }
+                        if (empty($_SESSION["comment"]))
+                        {
+                            printf("<li style='color:%s'>%s: You have to comment your data set. </li>\n",
+                                   $color["ERROR"], "ERROR");
+                            $numerr=$numerr+1;
+                        }
+                        printf("</ul></font>\n");
+                        printf("</div>");
+
+                        //set runtime in session (has to be after calling GetSequenceValues())
+                        $_SESSION["runtime"]  = $values["Sum(fRunTime)/60"]["on"];
+                        $_SESSION["zdmin"]    = $values["Min(fZenithDistanceMin)"]["on"];
+                        $_SESSION["zdmax"]    = $values["Max(fZenithDistanceMax)"]["on"];
+                        $_SESSION["meanrate"] = $values["Avg(fDataRate)"]["on"];
+                        $_SESSION["psfmean"]  = $values["Avg(fPSF)"]["on"];
+                        $_SESSION["psfmin"]   = $values["Min(fPSF)"]["on"];
+                        $_SESSION["psfmax"]   = $values["Max(fPSF)"]["on"];
+
+                        printf("SequencesOn: %s<br>\n", $_SESSION["sequon"]);
+                        if ($_SESSION["sequoff"]!="")
+                            printf("SequencesOff: %s<br>\n", $_SESSION["sequoff"]);
+
+                        printf("Observation mode: %s <br>\n", $obsmode);
+                        printf("RunTime: %s min <br>\n", $_SESSION["runtime"]);
+                        printf("Mean Rate after cleaning: %s Hz <br>\n", $_SESSION["meanrate"]);
+                        printf("Zd: %s - %s deg <br>\n", $_SESSION["zdmin"], $_SESSION["zdmax"]);
+                        printf("PSF: %s (%s - %s) mm <br>\n", $_SESSION["psfmean"], $_SESSION["psfmin"], $_SESSION["psfmax"]);
+
+                        //user name
+                        printf("User name: %s <br><br>\n", $_SERVER['PHP_AUTH_USER']);
+
+                        // data set name and comment: to be inserted by the user
+                        printf("Data set number: &nbsp;<input name='AnalysisNumber' type='text' size='8' maxlength='8' value='%s'> (only used for data set file) <br>\n", $_SESSION["AnalysisNumber"]);
+                        printf("Data set name: &nbsp;<input name='name' type='text' size='20' maxlength='20' value='%s'><br>\n", $_SESSION["name"]);
+                        printf("Comment: &nbsp;<input name='comment' type='text' size='50' maxlength='255' value='%s'><br><br>\n", $_SESSION["comment"]);
+
+
+                        //PrintUpdateDataSetButton() has to be called before InsertUpdateDataSet()
+                        //   to ensure that there are no problem with insert and $_SESSION["insert"]
+
+                        //allow 'insert/get dataset' in case no error is found
+                        if ($numerr!=0)
+                        {
+                            printf("Remark: Only data sets without errors can be inserted.<br>");
+                            printf("<font color='red'>Your data set has %s error(s).</font><br><br>", $numerr);
+                            PrintUpdateDataSetButton();
+                        }
+                        else
+                        {
+                            PrintUpdateDataSetButton();
+
+                            if ($_SERVER['PHP_AUTH_USER']=="MAGIC")
+                                printf("<br><br>\n Remark: As user MAGIC you are not allowed to insert data sets into the database. For an own account, please contact datacenter@astro.uni-wuerzburg.de <br><br>\n");
+                            else
+                                InsertUpdateDataSet($values, $dataset);
+
+                            printf("<input type='button' value='Get Data Set File' onClick='self.location.href=\"%s&fSendTxt=2\"'>&nbsp;&nbsp;&nbsp;\n", GetClearedURL());
+                        }
+
+
+                        //print table with more information on dataset
+                        printf("<br><br><br>\n");
+                        printf("<table><tr><td colspan='2'><b>More Information on Your Data Set:<b></td></tr>");
+                        printf("<tr><td>Next DataSet# in DB: </td><td>%s</td></tr>", $dataset);
+                        printf("<tr><td>DataSet# for data set file: </td><td>%s</td></tr>", empty($_SESSION["AnalysisNumber"])?"1":$_SESSION["AnalysisNumber"]);
+                        printf("<tr><td valign='top'>SequencesOn:</td><td> %s</td></tr>", $_SESSION["sequon"]);
+                        if ($_SESSION["sequoff"]!="")
+                        {
+                            printf("<tr><td valign='top'>SequencesOff:</td><td> %s</td></tr>", $_SESSION["sequoff"]);
+                            printf("<tr><td>Scale factor (On/Off): </td><td>%0.2f</td></tr>", $scale);
+                        }
+                        printf("<tr><td>SourcenamesOn [%s]: </td><td>%s</td></tr>", str_word_count($sourceson, 0, "1234567890+"), $sourceson);
+                        if ($_SESSION["sequoff"]!="")
+                            printf("<tr><td>SourcenamesOff [%s]: </td><td>%s</td></tr>", str_word_count($sourcesoff, 0, "1234567890+"), $sourcesoff);
+                        printf("</table>\n");
+
+                        printf("<table border='1'>\n");
+                        printf("<tr><td>Value</td><td>On</td>");
+                        if (!empty($off))
+                            printf("<td>Off</td></tr>\n");
+                        foreach($values as $name => $varname)
+                        {
+                            printf("<tr><td>%s</td>\n", $name);
+                            foreach($vals as $num => $val)
+                                if (!empty(${$val}))
+                                    printf("<td>%s</td>\n", $varname[$val]);
+                            printf("</tr>\n");
+                        }
+                        printf("</table>\n");
+                    }
+                }
+                else
+                {
+                    if ($_SESSION["user"]!=$_SESSION["olduser"] && !empty($_SESSION["olduser"]))
+                        printf("Remark: You (userkey %s) are not allowed to change data set # %d (created by userkey %s).<br> \n",
+                               $_SESSION["user"], $_SESSION["SelectedDataSet"], $_SESSION["olduser"]);
+                    else
+                    {
+                        printf("<input type='submit' value='Store Selection'><br><br>\n");
+                        printf("Remark: To store your selection for the data set, you have to press 'Store Selection'<br> \n");
+                    }
+
+                }
+
+                printf("</div>\n");
+                printf("</td>\n");
+                printf("</tr>\n");
+
+                printf("</form>\n");
+            }
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "");
+    }
+
+    include ("include.php");
+    include ("menu.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+//    $debug="yes";
+    session_start();
+    if ($debug)
+    {
+        echo "GET: ";
+        print_r($_GET);
+        echo " <br>";
+
+        echo "POST: ";
+        print_r($_POST);
+        echo " <br>";
+    }
+
+    // set values given by $_GET
+    foreach ($_GET as $element => $value)
+        $_SESSION[$element]=$value;
+
+    // unset values in case of 'Reset'
+    if (empty($_GET))
+        foreach($_SESSION as $element => $value)
+            unset($_SESSION[$element]);
+
+    // set values given by $_POST
+    if (!empty($_POST))
+        foreach ($_POST as $element => $value)
+            $_SESSION[$element]=$value;
+    else
+        unset($_SESSION["SelectAllSequForDS"]);
+
+    if ($debug)
+        print_r($_SESSION);
+    /*
+    if ($_SESSION["DisplaySelected"]=="yes")
+    {
+        unset($_SESSION["fNumStart"]);
+        $_GET["fNumStart"]=0;
+    }
+    */
+    $_SESSION["sequon"]="";
+    $_SESSION["sequoff"]="";
+    foreach($_SESSION as $key => $val)
+    {
+        if ($val=="ON" && ereg("^DSSeq[0-9]*$", $key))
+            $_SESSION["sequon"].=str_replace("DSSeq", " ", $key);
+
+        if ($val=="Off" && ereg("^DSSeq[0-9]*$", $key))
+            $_SESSION["sequoff"].=str_replace("DSSeq", " ", $key);
+
+        if ($val=="Not" && ereg("^DSSeq[0-9]*$", $key))
+            unset($_SESSION[$key]);
+    }
+    if (empty($_SESSION["sequon"]) && empty($_SESSION["sequoff"]))
+        unset($_SESSION["DisplaySelected"]);
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!isset($_SERVER['PHP_AUTH_USER']))
+    {
+        header('WWW-Authenticate: Basic realm="Build Datasets"');
+        header('HTTP/1.0 401 Unauthorized');
+        return;
+    }
+    else
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error:<br>");
+            printf("%s<br>", mysql_error());
+            die("");
+        }
+
+        $userquery   = "SELECT fUserName, fPassword, fUserKEY FROM " . $db . ".User ORDER BY fUserKEY";
+        $userresult  = mysql_query($userquery);
+        if (!$userresult)
+            echo "query failed";
+        $validuser="no";
+        while ($userrow = mysql_fetch_assoc($userresult))
+        {
+//            echo crypt($_SERVER['PHP_AUTH_PW']). "<br>";
+//            echo "with crypt: " . crypt($_SERVER['PHP_AUTH_PW'], $userrow["fPassword"]) . " for user " . $userrow["fUserName"]. "<br>";
+            if (crypt($_SERVER['PHP_AUTH_PW'], $userrow["fPassword"])==$userrow["fPassword"]
+                && $_SERVER['PHP_AUTH_USER']==$userrow["fUserName"])
+            {
+                $validuser="yes";
+                $_SESSION["user"]=$userrow["fUserKEY"];
+            }
+        }
+        mysql_free_result($userresult);
+        if ($validuser=="no")
+        {
+            printf("<br>Password or username incorrect<br>");
+            return;
+        }
+    }
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-Type: application/octet");
+        switch($_GET["fSendTxt"])
+        {
+        case 1:
+            header("Content-Disposition: attachment; filename=query-result.txt");
+            PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+            break;
+        case 2:
+            header("Content-Disposition: attachment; filename=dataset_".str_replace(" ", "_", $_SESSION["name"]).".txt");
+            PrintDataSetFile();
+        }
+        unset($_SESSION["fSendTxt"]);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+        InitBuildDataSets($first);
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias);
+
+        if ($environment==0)
+        {
+            printf("No query submitted yet.<br><br>\n");
+            printf("Either query above, or you have also the option to start with an already existing data set: <br>\n");
+            printf("Dataset: &nbsp;<input name='SelectedDataSet' type='text' size='8' maxlength='8' value='%s'><br><br>\n", $_SESSION["SelectedDataSet"]);
+            printf("How do you want to process this data set? <br>\n");
+            printf("<input type='radio' name='DataSetSelection' value='SelectSequences' %s>Use data set as starting point.<br>\n",
+                   $_SESSION["DataSetSelection"]=="SelectSequences"?"checked":"");
+            printf("<input type='radio' name='DataSetSelection' value='UpdateDataSet' %s>Update data set in database.<br><br>\n",
+                   $_SESSION["DataSetSelection"]=="UpdateDataSet"?"checked":"");
+            printf("<input type='submit' value='Query'><br>\n");
+            printf("</form>\n");
+        }
+        else
+        {
+            printf("</form>\n");
+            if (empty($_SESSION["DataSetSelection"]) && !empty($_SESSION["SelectedDataSet"]))
+            {
+                printf("Remark: You have inserted a data set number (%s), but not selected what you want to do with it. <br>\n",
+                       $_SESSION["SelectedDataSet"]);
+                printf("Please press 'Reset'. Then to choose a data set and what you want to do with it or simply 'Query Table' to start a new data set.<br>\n");
+            }
+            else
+            {
+
+                if (empty($_GET["fPrintTable"]))
+                    PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+                else
+                    PrintPage("2", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+            }
+        }
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    if (!empty($_SESSION["DataSetSelection"]))
+        $_SESSION["DataSetAcknowledged"]="yes";
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/ctadefs.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/ctadefs.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/ctadefs.php	(revision 17960)
@@ -0,0 +1,147 @@
+<?php
+
+$needs = array
+    (
+     "fCorsikaSimTelarray"   => "MCRunProcessStatus.fMCRunNumber",
+     "fChimp"                => "MCRunProcessStatus.fCorsikaSimTelarray",
+     "fCTAStar"              => "MCRunProcessStatus.fChimp",
+     "fStereoB"              => "MCRunProcessStatus.fCTAStar",
+     "fStereoC"              => "MCRunProcessStatus.fCTAStar",
+     "fStereoG"              => "MCRunProcessStatus.fCTAStar",
+     );
+
+
+$timelimits = array
+    (
+     "fCorsikaSimTelarray"   => "48",
+     "fChimp"                => "4",
+     "fCTAStar"              => "2",
+     "fStereoB"              => "1",
+     "fStereoC"              => "1",
+     "fStereoG"              => "1",
+     );
+
+
+$checkwhere = array
+    (
+     "fParticleTypeName"  => CheckWhere("fParticleTypeKEY"),
+    );
+
+$checkgroup = array
+    (
+     "fParticleTypeName"  => CheckGroup("fParticleTypeKEY"),
+    );
+
+
+$checkstatusgroup = array
+    (
+     "fCorsikaSimTelarray" => CheckStatusGroup("fCorsikaSimTelarrayStatus"),
+     "fChimp"              => CheckStatusGroup("fChimpStatus"),
+     "fCTAStar"            => CheckStatusGroup("fCTAStarStatus"),
+     "fStereoB"            => CheckStatusGroup("fStereoBStatus"),
+     "fStereoC"            => CheckStatusGroup("fStereoCStatus"),
+     "fStereoG"            => CheckStatusGroup("fStereoGStatus"),
+    );
+
+
+
+$alias = array
+    (
+//     "fRunNumber"                       => "Run#",
+     "Run#"                     => "Run#",
+     "fNumEvents"               => "#Evts",
+     "fObsLevel"                => "ObsLev<br>[m]",
+     "SUM(fNumEvents)"          => "Evts",
+     "SUM(fNumEvents) DIV 1000" => "kEvts",
+     "fParticleTypeName"        => "Particle",
+     "fCorsikaSimTelarray"      => "CorsikaSimtel",
+     "fChimp"                   => "Chimp",
+     "fCTAStar"                 => "Star",
+     "fStereoB"                 => "StereoB",
+     "fStereoC"                 => "StereoC",
+     "fStereoG"                 => "StereoG",
+     "fStartTime"               => "Process",
+     "fFailedTime"              => "Failed",
+     "fReturnCode"              => "Ret<br>Code",
+     "fProgramId"               => "Prgr<br>Id",
+    );
+
+
+$rightalign = array
+    (
+//     $alias["fRunNumber"]                => "1",
+     $alias["fNumEvents"]                => "1",
+     $alias["fObsLevel"]                 => "1",
+     $alias["SUM(fNumEvents) DIV 1000"]  => "1",
+     "Time"                              => "1",
+     "Runs"                              => "1",
+     "Evts"                              => "1",
+);
+
+function GetCheck($fromtable, $val)
+{
+    $checks = array
+        (
+         "fParticleTypeName"                 => $fromtable . ".fParticleTypeKEY",
+        );
+
+    $check="";
+    if (!empty($checks[$val]))
+        $check=$checks[$val];
+    return $check;
+}
+
+
+function GetTable($fromtable, $val)
+{
+    $tables = array
+        (
+         "fNumEvents"                        => $fromtable . ".fNumEvents",
+         "fMCRunNumber"                      => "MCRunData.fMCRunNumber",
+         "fRawFileAvail"                     => "RunProcessStatus.fRawFileAvail",
+         "SUM(fRunTime)/3600"                => "'Time [h]'",
+         "SUM(fNumEvents)"                   => "'Evts'",
+         "fStartTime"                        => "fStartTime",
+         "fFailedTime"                       => "fFailedTime",
+         "fReturnCode"                       => "fReturnCode",
+         "fProgramId"                        => "fProgramId",
+         "fParticleTypeName"                 => "ParticleType.fParticleTypeName",
+        );
+
+    $table="";
+    if (!empty($tables[$val]))
+        $table=$tables[$val];
+    if ($val=="Tel:Run/File")
+        $table="'Tel:Run/File'";
+    if ($val=="Tel:Sequ")
+        $table="CONCAT('M', Sequences.fTelescopeNumber, ':', LPAD(Sequences.fSequenceFirst, 8, '0'))";
+    if ($val=="NumRuns")
+        $table="'# Runs'";
+    if ($val=="NumSequ")
+        $table="'# Sequ'";
+    if ($val=="NumDS")
+        $table="'# Datasets'";
+    if ($val=="NumDays")
+        $table="'# days'";
+    if (empty($table))
+        $table=$val;
+    return $table;
+}
+
+
+function GetJoin($fromtable, $val)
+{
+    $joins = array
+        (
+         "fParticleTypeName"                => " LEFT JOIN ParticleType                USING(fParticleTypeKEY) ",
+        );
+
+
+    $join="";
+    if (!empty($joins[$val]))
+        $join=$joins[$val];
+    return $join;
+}
+
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/ctamcinfo.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/ctamcinfo.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/ctamcinfo.php	(revision 17960)
@@ -0,0 +1,347 @@
+<?php
+{
+    function CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits)
+    {
+        $fromtable="MCRunData";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0 || $statusgroups>0)
+        {
+            if ($groups>0)
+            {
+                foreach ($checkgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+                /*
+                 //--------------------------------------------------
+                 //$query0 .= " TIMEDIFF(fRunStop, fRunStart), ";
+                 // Only available in MySQL>4.1.1
+                 $query0 .= "SUM(if(TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)<0, " .
+                 "TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)+24*60*60, " .
+                 "TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)))/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
+                 //--------------------------------------------------
+                 $query0 .= " SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "', ";
+                 $query0 .= " Min(fZenithDistance) as '" . $alias["Min(fZenithDistance)"] . "', ";
+                 $query0 .= " Max(fZenithDistance) as '" . $alias["Max(fZenithDistance)"] . "', ";
+                 */
+            }
+            if ($statusgroups>0)
+            {
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .= " (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval " . $timelimits[$key] . " hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+                //                        $query0 .= " (if(IsNull(" . $key . "), 'not done' ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+
+//                $query0 .= " count(*) as '# Runs'";
+
+            }
+            $query0 .= " COUNT(*) as '# Runs' ";
+            $query0 .= ", SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "' ";
+            $query0 .= ", SUM(fNumEvents) DIV 1000 as '" . $alias["SUM(fNumEvents) DIV 1000"] . "' ";
+        }
+        else
+        {
+            $query0 .= " MCRunData.fMCRunNumber as 'Run' ";
+//                $query0 .= " Concat(RunData.fTelescopeNumber,':', RunData.fRunNumber,':', RunData.fFileNumber) as 'Run' ";
+//                $query0 .= " Concat('M', RunData.fTelescopeNumber,':', LPAD(RunData.fRunNumber,8, ' '),'/', LPAD(RunData.fFileNumber, 3, ' ')) as 'Tel:Run/File' ";
+
+            if (empty($_GET["fSendTxt"]) && !empty($_GET["fLinks"]))
+            {
+                $query0 .= ", CONCAT('<A&ws;HREF=\"http://cluster.isdc.unige.ch/cta/compute-0-', fProductionHostKEY , '/simtel/cta-ultra3/0.0deg/Data/', LCASE(fParticleTypeName), '_20deg_90deg_run', LPAD(MCRunData.fMCRunNumber, 6,'0'), '___cta-ultra3_desert.simtel.gz\">simtel.gz</A> <A&ws;HREF=\"http://cluster.isdc.unige.ch/cta/compute-0-', fProductionHostKEY , '/chimp/cta-ultra3/0.0deg/Data/', LCASE(fParticleTypeName), '_20deg_90deg_run', LPAD(MCRunData.fMCRunNumber, 6,'0'), '___cta-ultra3_desert.root\">root</A>') ";
+                $query0 .= " as 'Download'";
+            }
+
+            foreach ($_GET as $key => $element)
+                if ($key!="fLinks" && $_GET[$key]=="On" && $key!="fTest")
+                    if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                        $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM MCRunData ";
+
+        $query0 .= " LEFT JOIN MCRunProcessStatus USING(fMCRunNumber) ";
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty($joins[$key]))
+                $query0 .= GetJoin($fromtable,$key);
+
+        /*
+        if ($_GET["fTest"]!="On")
+        {
+            if ($_GET["fSourceName"]!="On")
+                $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
+            $query0 .= " WHERE fTest='no'";
+        }
+        */
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)// this if clause doesn't work
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= StatusQuery("fCorsikaSimTelarray", $needs, $timelimits);
+        $query0 .= StatusQuery("fChimp", $needs, $timelimits);
+        $query0 .= StatusQuery("fCTAStar", $needs, $timelimits);
+        $query0 .= StatusQuery("fStereoB", $needs, $timelimits);
+        $query0 .= StatusQuery("fStereoC", $needs, $timelimits);
+        $query0 .= StatusQuery("fStereoG", $needs, $timelimits);
+
+        if ((!empty($_GET["fRunMin"]) || $_GET["fRunMin"]=="0") && !empty($_GET["fRunMax"]))
+            $query0 .= "MCRunData.fMCRunNumber BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+
+//        if ((!empty($_GET["fZDMin"]) || $_GET["fZDMin"]==0) && !empty($_GET["fZDMax"]))
+//            $query0 .= "AND fZenithDistance BETWEEN " . $_GET["fZDMin"] . " AND  " . $_GET["fZDMax"] . " ";
+
+/*
+        if (!empty($_GET["fDate"]))
+            $query0 .= " AND fRunStart REGEXP \"^" . $_GET["fDate"] . "\" ";
+*/
+
+        /*
+        if (!empty($_GET["fSourceN"]))
+            $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+        if (!empty($_GET["fStartDate"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0)
+                $query0 .= " AND ";
+
+            $startdate=substr($_GET["fStartDate"], 0, 10);
+            if ($startdate=="0000-00-00")
+                $query0 .=" fRunStart >= '" . $startdate . " 00:00:00' ";
+            else
+                $query0 .= " fRunStart >= ADDDATE('" . $startdate . " 13:00:00', INTERVAL -1 DAY) ";
+        }
+
+        if (!empty($_GET["fStopDate"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0)
+                $query0 .= " AND ";
+
+            $stopdate=substr($_GET["fStopDate"], 0, 10);
+            $query0 .= " fRunStart < '" . $stopdate . " 13:00:00' ";
+        }
+
+        if (!empty($_GET["fSequenceNo"]) || $_GET["fSequenceNo"]=="0")
+        {
+            if (strpos(strrev($query0), " DNA ")!=0)
+                $query0 .= " AND ";
+
+            $query0 .= " fSequenceFirst = '" . $_GET["fSequenceNo"] . "' ";
+        }
+        */
+
+        //remove WHERE or AND in the end of the query
+        $query0=ereg_replace(" WHERE \$", " ", $query0);
+        $query0=ereg_replace(" AND \$", " ", $query0);
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable,$key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if ($statusgroups>0)
+        {
+//            $query0 .= " GROUP BY ";
+            if (strpos($query0, " GROUP BY ")==FALSE)
+                $query0 .= " GROUP BY ";
+            else
+                $query0 .= ", ";
+            $num = $statusgroups;
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable, $val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+        else
+            $query0 .=" ORDER BY MCRunData.fMCRunNumber ASC";
+
+        if (empty($_GET["fNumStart"]))
+            $start=0;
+        else
+            $start=$_GET["fNumStart"];
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $start . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet()
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        InitCTAMCRunInfo($first);
+    }
+
+    function PrintForm($host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"ctamcinfo.php\" METHOD=\"GET\">\n");
+
+        printf("<input id='sh' type='hidden' name='fShowHide' value='");
+        if (!empty($_GET["fShowHide"]))
+            printf("%s", $_GET["fShowHide"]);
+        else
+            printf("1000000010");
+        printf("'>\n");
+        printf("<img id='allbutton' src='minus.png' alt='-' onclick=\"showhide('all')\"> <b>Menu</b>&nbsp;&nbsp;&nbsp;&nbsp;\n");
+        printf("&nbsp;&nbsp;<img id='infobutton'   src='plus.png' alt='+' onClick=\"showhide('info');showhide('info2')\"> MCRunInfo  \n");
+        printf("&nbsp;&nbsp;<img id='statbutton'   src='plus.png' alt='+' onClick=\"showhide('stat');showhide('fail')\">  StatusInfo \n");
+        printf("&nbsp;&nbsp;<img id='rangesbutton' src='plus.png' alt='+' onClick=\"showhide('ranges')\">                 Ranges     \n");
+
+        printf(" <div id='all' style='display:block'>");
+        PrintCTAMCRunInfoMenu($host,$user,$pw,$db);
+//        PrintRunInfo2Menu($host,$user,$pw,$db);
+        PrintCTAMCRunStatMenu();
+        PrintFailMenu();
+        printf(" <div id='ranges' style='display:none'>");
+//        PrintSequMenu($host,$user,$pw,$db);
+//        PrintNightRangeMenu($host,$user,$pw,$db, "RunData");
+        printf("<p>");
+//        PrintZdRangeMenu($host,$user,$pw,$db);
+        PrintCTAMCRunRangeMenu($host,$user,$pw,$db);
+//        printf(" <P>\n");
+//        PrintSourceMenu($host,$user,$pw,$db);
+        printf("<p>");
+        printf("</div>");
+        printf("</div>");
+        printf(" <P>\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        PrintNumResPullDown();
+        PrintButtons("ctamcinfo.php");
+
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+        mysql_query("SET BIG_TABLES=1"); // necessary for mySQL <= 4
+
+        $query0 = CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1, "");
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("menu.php");
+    include ("ctadefs.php");
+
+    ini_set("display_errors",   "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet();
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors",   "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/culminating.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/culminating.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/culminating.php	(revision 17960)
@@ -0,0 +1,276 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $fromtable="Sequences";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0)
+        {
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+            //--------------------------------------------------
+            $query0 .= "SUM(fRunTime)/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
+            //--------------------------------------------------
+            $query0 .= " SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "', ";
+            $query0 .= " COUNT(*) as '# Sequ' ";
+        }
+        else
+        {
+            if (!empty($_GET["fSendTxt"]))
+                $query0 .= " SELECT fSequenceFirst ";
+            else
+                $query0 .= " CONCAT('<A&ws;HREF=\"index.php?',  'fRunStart=On', '&fZenithDistance=On', '&fRunMin=', fSequenceFirst, '&fMeanTriggerRate=On', '&fRunTypeName=On', '&fRunMax=', fSequenceLast, '&fNumEvents=On', '&fSourceName=On&', 'fExcludedFDAKEY=1', '&fSequenceFirst=On', '&fNumResults=500\">', fSequenceFirst, '</A>') ";
+            $query0 .= " as 'Sequence#' ";
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On")
+                    if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                        $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM " . $fromtable;
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty($joins[$key]))
+                $query0 .= GetJoin($fromtable, $key);
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= "fSequenceFirst BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+
+        if (!empty($_GET["fSourceN"]))
+            $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+        $query0 .= " AND ((fAzimuthMin<0 and fAzimuthMax>0) OR (fAzimuthMin<180 and fAzimuthMax>180)) ";
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable, $key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $query0 .= " ORDER BY " . substr($_GET["fSortBy"], 0, -1) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+
+        if (empty($_GET["fLastUpdate"]))
+            $_GET["fLastUpdate"]="Off";
+
+        if (empty($_GET["fSourceName"]))
+            $_GET["fSourceName"]=$first?"On":"";
+
+        if (empty($_GET["fRunStart"]))
+            $_GET["fRunStart"]=$first?"On":"";
+
+        if (empty($_GET["fAzimuthMin"]))
+            $_GET["fAzimuthMin"]="Off";
+
+        if (empty($_GET["fAzimuthMax"]))
+            $_GET["fAzimuthMax"]="Off";
+
+        if (empty($_GET["fZenithDistanceMin"]))
+            $_GET["fZenithDistanceMin"]=$first?"On":"";
+
+        if (empty($_GET["fZenithDistanceMax"]))
+            $_GET["fZenithDistanceMax"]="Off";
+
+        if (empty($_GET["fRunTime/60"]))
+            $_GET["fRunTime/60"]="Off";
+
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"culminating.php\" METHOD=\"GET\">\n");
+        printf(" <table>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fAzimuthMin",        "Azimuth min");
+        CheckBox("fAzimuthMax",        "Azimuth max");
+        CheckBox("fZenithDistanceMin", "Zenith distance min");
+        CheckBox("fZenithDistanceMax", "Zenith distance max");
+
+        printf("  </tr><tr>\n");
+
+        CheckBox("fRunTime/60",        "Duration");
+
+        printf(" </table>\n");
+        printf(" <p>\n");
+
+        printf(" <table>\n");
+        printf("  <tr><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "Source",      "fSourceName",      "fSourceKEY", "Source Name");
+        printf("  </td></tr>\n");
+        printf(" </table>\n");
+        printf(" <p>\n");
+
+        if (empty($_GET["fRunMin"]))
+            $min = GetMin("fSequenceFirst", "Sequences", $host, $user, $pw, $db);
+        else
+            $min = $_GET["fRunMin"];
+
+        if (empty($_GET["fRunMax"]))
+            $max = GetMax("fSequenceFirst", "Sequences", $host, $user, $pw, $db);
+        else
+            $max = $_GET["fRunMax"];
+
+
+        printf("Source&nbsp;(<A HREF=\"regexp.html\">regexp</A>)&nbsp;<input name=\"fSourceN\" type=\"text\" size=\"15\" maxlength=\"15\" value=\"");
+        if (!empty($_GET["fSourceN"]))
+            printf("%s", $_GET["fSourceN"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n");
+
+        printf("Sequences&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">\n", $min);
+        printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+
+        printf(" <P>\n");
+
+        printf(" Results:\n");
+        printf(" <select name=\"fNumResults\">\n");
+
+        $numres = array("10", "20", "50", "100", "200", "500");
+        foreach ($numres as $element)
+        {
+            if ($element==$_GET["fNumResults"])
+                printf("<option value=\"%s\" selected>%3s</option>\n", $element, $element);
+            else
+                printf("<option value=\"%s\">%3s</option>\n", $element, $element);
+        }
+        printf(" </select>\n");
+        printf(" &nbsp;&nbsp;&nbsp;\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"culminating.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+    include ("include.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+            PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/datacheck.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/datacheck.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/datacheck.php	(revision 17960)
@@ -0,0 +1,476 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $checkenumgroup, $needs)
+    {
+        $fromtable="RunData";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $enumgroups = 0;
+        foreach ($checkenumgroup as $element)
+            if ($element==-1)
+                $enumgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0)
+        {
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+            $query0 .= " COUNT(*) as 'Runs' ";
+        }
+        else
+        {
+            if ($statusgroups>0)
+            {
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .= " (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval 12 hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+//                        $query0 .= " (if(IsNull(" . $key . "), 'not done' ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+
+                $query0 .= " count(*) as 'Runs'";
+
+            }
+            else
+            {
+                if ($enumgroups>0)
+                {
+                    foreach ($checkenumgroup as $key => $element)
+                        if ($element==-1)
+                            $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+                    $query0 .= " COUNT(*) as 'Runs' ";
+                }
+                else
+                {
+                    $query0 .= " RunData.fRunNumber as 'RunNumber'";
+                    if (!empty($_GET["fLinks"]))
+                    {
+                        $query0 .= ", CONCAT('<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sinope/' , DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%Y') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%m') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%d') , '/sinope-dat' ,  LPAD(CONCAT(RunData.fRunNumber , '.html'), 13,'0') , '\">dl</A>' ";
+                        $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sinope/' , DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%Y') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%m') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%d') , '/sinope-cal' ,  LPAD(CONCAT(RunData.fRunNumber , '.html'), 13,'0') , '\">cl</A>' ";
+                        $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sinope/' , DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%Y') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%m') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%d') , '/sinope-dat' ,  LPAD(CONCAT(RunData.fRunNumber , '.txt'), 12,'0') , '\">dt</A>' ";
+                        $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sinope/' , DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%Y') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%m') , '/', DATE_FORMAT(ADDDATE(RunData.fRunStart, INTERVAL 13 HOUR), '%d') , '/sinope-cal' ,  LPAD(CONCAT(RunData.fRunNumber , '.txt'), 12,'0') , '\">ct</A>' ";
+                        $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/' , LEFT(LPAD(CONCAT(fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(fSequenceFirst, '/'), 9,'0'), 'callisto', LPAD(CONCAT(fSequenceFirst , '.html'), 13,'0') , '\">c</A>'";
+                        $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/star/' , LEFT(LPAD(CONCAT(fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(fSequenceFirst, '/'), 9,'0'), 'star', LPAD(CONCAT(fSequenceFirst , '.html'), 13,'0') , '\">s</A>'";
+                        $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sequences/' , LEFT(LPAD(CONCAT(fSequenceFirst, '.'), 9,'0'),4), '/sequence', LPAD(CONCAT(fSequenceFirst , '.txt'), 12,'0') , '\">', 'f </A>') ";
+                        $query0 .= " as 'Links'";
+                    }
+
+                    foreach ($_GET as $key => $element)
+                        if ($_GET[$key]=="On")
+                            if ($key!="fLinks")
+                                if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                                    $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+                }
+            }
+        }
+
+        $query0 .= " FROM RunData ";
+
+        $query0 .= " LEFT JOIN RunProcessStatus USING(fRunNumber,fTelescopeNumber,fFileNumber) ";
+        $query0 .= " LEFT JOIN DataCheck USING(fRunNumber) ";
+        $query0 .= " LEFT JOIN RunType USING(fRunTypeKEY) ";
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= StatusQuery("fRawFileAvail", $needs, $timelimits);
+        $query0 .= StatusQuery("fDataCheckDone", $needs, $timelimits);
+
+        $query0 .= EnumQuery("fHasSignal");
+        $query0 .= EnumQuery("fHasPedestal");
+        $query0 .= EnumQuery("fHasSignalInterlaced");
+        $query0 .= EnumQuery("fHasPedestalInterlaced");
+
+        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
+            $query0 .= "RunData.fRunNumber BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+
+        if (!empty($_GET["fSourceN"]))
+            $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable,$key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if ($statusgroups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $statusgroups;
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if ($enumgroups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $enumgroups;
+            foreach ($checkenumgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable, $val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fSortBy"]) && $groups==0 && $statusgroups==0)
+            $query0 .= " ORDER BY RunData.fRunNumber ASC ";
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+
+        if (empty($_GET["fLinks"]))
+            $_GET["fLinks"]=$first?"On":"";
+
+        if (empty($_GET["fSequenceFirst"]))
+            $_GET["fSequenceFirst"]=$first?"On":"";
+
+        if (empty($_GET["fEvents"]))
+            $_GET["fEvents"]=$first?"On":"";
+
+        if (empty($_GET["fPositionSignal"]))
+            $_GET["fPositionSignal"]="Off";
+
+        if (empty($_GET["fPositionFWHM"]))
+            $_GET["fPositionFWHM"]="Off";
+
+        if (empty($_GET["fHeightSignal"]))
+            $_GET["fHeightSignal"]="Off";
+
+        if (empty($_GET["fHeightFWHM"]))
+            $_GET["fHeightFWHM"]="Off";
+
+        if (empty($_GET["fHasSignal"]))
+            $_GET["fHasSignal"]=$first?"On":"";
+
+        if (empty($_GET["fHasSignalEnum"]))
+            $_GET["fHasSignalEnum"]="0";
+
+        if (empty($_GET["fHasPedestal"]))
+            $_GET["fHasPedestal"]=$first?"On":"";
+
+        if (empty($_GET["fHasPedestalEnum"]))
+            $_GET["fHasPedestalEnum"]="0";
+
+        if (empty($_GET["fPositionAsym"]))
+            $_GET["fPositionAsym"]="Off";
+
+        if (empty($_GET["fHeightAsym"]))
+            $_GET["fHeightAsym"]="Off";
+
+        if (empty($_GET["fEventsInterlaced"]))
+            $_GET["fEventsInterlaced"]=$first?"On":"";
+
+        if (empty($_GET["fPositionSignalInterlaced"]))
+            $_GET["fPositionSignalInterlaced"]="Off";
+
+        if (empty($_GET["fPositionFWHMInterlaced"]))
+            $_GET["fPositionFWHMInterlaced"]="OFf";
+
+        if (empty($_GET["fHeightSignalInterlaced"]))
+            $_GET["fHeightSignalInterlaced"]="Off";
+
+        if (empty($_GET["fHeightFWHMInterlaced"]))
+            $_GET["fHeightFWHMInterlaced"]="Off";
+
+        if (empty($_GET["fHasSignalInterlaced"]))
+            $_GET["fHasSignalInterlaced"]=$first?"On":"";
+
+        if (empty($_GET["fHasSignalInterlacedEnum"]))
+            $_GET["fHasSignalInterlacedEnum"]="0";
+
+        if (empty($_GET["fHasPedestalInterlaced"]))
+            $_GET["fHasPedestalInterlaced"]=$first?"On":"";
+
+        if (empty($_GET["fHasPedestalInterlacedEnum"]))
+            $_GET["fHasPedestalInterlacedEnum"]="0";
+
+        if (empty($_GET["fPositionAsymInterlaced"]))
+            $_GET["fPositionAsymInterlaced"]="Off";
+
+        if (empty($_GET["fHeightAsymInterlaced"]))
+            $_GET["fHeightAsymInterlaced"]="Off";
+
+        if (empty($_GET["fRunTypeName"]))
+            $_GET["fRunTypeName"]=$first?"On":"";
+
+        if (empty($_GET["fDataCheckDone"]))
+            $_GET["fDataCheckDone"]="Off";
+
+        if (empty($_GET["fDataCheckDoneStatus"]))
+            $_GET["fDataCheckDoneStatus"]=$first?"1":"";
+
+        if (empty($_GET["fRawFileAvail"]))
+            $_GET["fRawFileAvail"]="Off";
+
+        if (empty($_GET["fRawFileAvailStatus"]))
+            $_GET["fRawFileAvailStatus"]=$first?"1":"";
+
+        if (empty($_GET["fStartTime"]))
+            $_GET["fStartTime"]="Off";
+
+        if (empty($_GET["fFailedTime"]))
+            $_GET["fFailedTime"]="Off";
+
+        if (empty($_GET["fReturnCode"]))
+            $_GET["fReturnCode"]="Off";
+
+        if (empty($_GET["fProgramId"]))
+            $_GET["fProgramId"]="Off";
+
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"datacheck.php\" METHOD=\"GET\">\n");
+        printf(" <table>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fLinks",             "Links");
+        CheckBox("fEvents",            "DataEvents");
+        CheckBox("fEventsInterlaced",  "CalEvents");
+        CheckBox("fSequenceFirst",     "Sequence#");
+
+        printf("  </tr><tr>\n");
+
+        CheckBox("fPositionSignal",            "ArrTime");
+        CheckBox("fPositionFWHM",              "ArrTimeFWHM");
+        CheckBox("fPositionSignalInterlaced",  "ArrTimeCal");
+        CheckBox("fPositionFWHMInterlaced",    "ArrTimeFWHMCal");
+
+        printf("  </tr><tr>\n");
+
+        CheckBox("fHeightSignal",            "Signal");
+        CheckBox("fPositionFWHM",            "SignalFWHM");
+        CheckBox("fHeightSignalInterlaced",  "SignalCal");
+        CheckBox("fPositionFWHMInterlaced",  "SignalFWHMCal");
+
+        printf("  </tr><tr>\n");
+
+        CheckBox("fPositionAsym",            "ArrTimeAsym");
+        CheckBox("fHeightAsym",              "SignalAsym");
+        CheckBox("fPositionAsymInterlaced",  "ArrTimeAsymCal");
+        CheckBox("fHeightAsymInterlaced",    "SignalAsymCal");
+
+        printf("  </tr><tr><td>\n");
+
+        PrintEnumMenu("fHasSignal",               "HasSignal");
+        printf("  </td><td>\n");
+        PrintEnumMenu("fHasPedestal",             "HasPedestal");
+        printf("  </td><td>\n");
+        PrintEnumMenu("fHasSignalInterlaced",     "HasSignalCal");
+        printf("  </td><td>\n");
+        PrintEnumMenu("fHasPedestalInterlaced",   "HasPedestalCal");
+
+        printf("  </td></tr><tr><td>\n");
+
+        PrintStatusMenu("fDataCheckDone", "DataCheck");
+        printf("  </td><td>\n");
+        PrintStatusMenu("fRawFileAvail", "RawFile");
+        printf("</td><td>\n");
+
+        PrintPullDown($host, $user, $pw, $db, "RunType",      "fRunTypeName",      "fRunTypeKEY", "Run Type");
+
+        printf("  </td></tr>\n");
+        printf(" </table>\n");
+
+        printf(" <table>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fStartTime",     "StartTime");
+        CheckBox("fFailedTime",    "FailedTime");
+        CheckBox("fReturnCode",    "RetCode");
+        CheckBox("fProgramId",     "ProgramId");
+
+        printf("  </tr>\n");
+        printf(" </table>\n");
+        printf(" <p>\n");
+
+        if (empty($_GET["fRunMin"]))
+            $min = GetMin("fRunNumber", "RunData", $host, $user, $pw, $db);
+        else
+            $min = $_GET["fRunMin"];
+
+        if (empty($_GET["fRunMax"]))
+            $max = GetMax("fRunNumber", "RunData", $host, $user, $pw, $db);
+        else
+            $max = $_GET["fRunMax"];
+
+/*
+        printf("Date&nbsp;(yyyy-mm-dd)&nbsp;<input name=\"fDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"");
+        if (!empty($_GET["fDate"]))
+            printf("%s", $_GET["fDate"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n");
+*/
+
+        printf("DataCheck&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">\n", $min);
+        printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+
+        printf(" <P>\n");
+
+        printf(" Results:\n");
+        printf(" <select name=\"fNumResults\">\n");
+
+        $numres = array("10", "20", "50", "100", "200", "500");
+        foreach ($numres as $element)
+        {
+            if ($element==$_GET["fNumResults"])
+                printf("<option value=\"%s\" selected>%3s</option>\n", $element, $element);
+            else
+                printf("<option value=\"%s\">%3s</option>\n", $element, $element);
+        }
+        printf(" </select>\n");
+        printf(" &nbsp;&nbsp;&nbsp;\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"datacheck.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Print' onClick='self.location.href=\"%s&fPrintTable=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $checkenumgroup, $needs)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $checkenumgroup, $needs);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $checkenumgroup, $needs);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $checkenumgroup, $needs);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $checkenumgroup, $needs);
+        }
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/datasetinfo-aio.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/datasetinfo-aio.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/datasetinfo-aio.php	(revision 17960)
@@ -0,0 +1,295 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs)
+    {
+        $fromtable="DataSets";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0 || $statusgroups>0)
+        {
+            if ($groups>0)
+            {
+                foreach ($checkgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+                $query0 .= " COUNT(*) as '# Datasets', ";
+            }
+
+            //--------------------------------------------------
+            $query0 .= "SUM(fRunTime)/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
+            //--------------------------------------------------
+            $query0 .= " Min(fZenithDistanceMin) as '" . $alias["Min(fZenithDistanceMin)"] . "', ";
+            $query0 .= " Max(fZenithDistanceMax) as '" . $alias["Max(fZenithDistanceMax)"] . "', ";
+            $query0 .= " COUNT(*) as '# Sequ' ";
+
+            if ($statusgroups>0)
+            {
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .= ", (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval 12 hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "' ";
+//                        $query0 .= " (if(IsNull(" . $key . "), 'not done' ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+
+                $query0 .= ", COUNT(*) as '# Datasets'";
+
+            }
+        }
+        else
+        {
+            $query0 .= " " . $fromtable . ".fDataSetNumber as '" . $alias["fDataSetNumber"] . "' ";
+            if (!empty($_GET["fLinks"]))
+            {
+                //$query0 .= ", CONCAT('<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/datasets/' , LEFT(LPAD(CONCAT(DataSets.fDataSetNumber, '.'), 9,'0'),5), '/dataset', LPAD(CONCAT(DataSets.fDataSetNumber , '.txt'), 12,'0') , '\">f</A>' ";
+                //$query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/ganymed/' , LEFT(LPAD(CONCAT(DataSets.fDataSetNumber, '.'), 9,'0'),5), '/', LEFT(LPAD(CONCAT(DataSets.fDataSetNumber, '.'), 9,'0'), 8), '\">g</A>'";
+                //$query0 .= ", '&nbsp;<A&ws;HREF=\"ganymed.php?fDataSetNo=', DataSets.fDataSetNumber, '\">i</A>') ";
+                $query0 .= ", CONCAT('<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/datasets/' , LEFT(LPAD(CONCAT(DataSets.fDataSetNumber, '.'), 9,'0'),5), '/dataset', LPAD(CONCAT(DataSets.fDataSetNumber , '.txt'), 12,'0') , '\">f</A>' ";
+                $query0 .= ", '&nbsp;<A&ws;HREF=\"tabs.php?t=ganymed&n=' , fDataSetNumber, '\">g</A>'";
+                $query0 .= ", '&nbsp;<A&ws;HREF=\"tabs.php?t=gplotdb&n=' , fDataSetNumber, '\">pdb</A>'";
+                //$query0 .= ", '&nbsp;<A&ws;HREF=\"ganymed.php?fDataSetNo=', DataSets.fDataSetNumber, '\">i</A>' ";
+                $query0 .= ") as 'Links'";
+            }
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On")
+                    if ($key!="fLinks")
+                        if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                            $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM " . $fromtable;
+
+        $query0 .= " LEFT JOIN DataSetProcessStatus USING(fDataSetNumber) ";
+        $query0 .= " LEFT JOIN Ganymed USING(fDataSetNumber) ";
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty($joins[$key]))
+                $query0 .= GetJoin($fromtable,$key);
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= StatusQuery("fDataSetInserted", $needs, $timelimits);
+        $query0 .= StatusQuery("fStarFilesAvail", $needs, $timelimits);
+        $query0 .= StatusQuery("fGanymed", $needs, $timelimits);
+        $query0 .= StatusQuery("fFillGanymed", $needs, $timelimits);
+
+        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
+            $query0 .= "DataSets.fDataSetNumber BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+
+/*
+        if (!empty($_GET["fDate"]))
+            $query0 .= " AND fRunStart REGEXP \"^" . $_GET["fDate"] . "\" ";
+*/
+
+        if (!empty($_GET["fSourceN"]))
+            $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable,$key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if ($statusgroups>0)
+        {
+            if (strpos($query0, " GROUP BY ")==FALSE)
+                $query0 .= " GROUP BY  ";
+            else
+                $query0 .= ",  ";
+            $num = $statusgroups;
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable, $val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fSortBy"]) && $groups==0 && $statusgroups==0)
+            $query0 .= "ORDER BY DataSets.fDataSetNumber ASC ";
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="50";
+
+        InitDataSetInfo($_GET, $first);
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"datasetinfo-aio.php\" METHOD=\"GET\">\n");
+
+        printf("<input id='sh' type='hidden' name='fShowHide' value='");
+        if (!empty($_GET["fShowHide"]))
+            printf("%s", $_GET["fShowHide"]);
+        else
+            printf("1000000000");
+        printf("'>\n");
+        printf("<img id='allbutton' src='minus.png' alt='-' onclick=showhide('all')> <b>Menu</b>&nbsp;&nbsp;&nbsp;&nbsp;\n");
+        printf("&nbsp;&nbsp;<img id='infobutton'   src='plus.png' alt='+' onClick=showhide('info');showhide('info2')> DataSetInfo\n");
+        printf("&nbsp;&nbsp;<img id='statbutton'   src='plus.png' alt='+' onClick=showhide('stat');showhide('fail')>  StatusInfo \n");
+        printf("&nbsp;&nbsp;<img id='rangesbutton' src='plus.png' alt='+' onClick=showhide('ranges')>                 Ranges     \n");
+
+        printf(" <div id='all' style='display:block'>");
+        PrintDataSetInfoMenu($host, $user, $pw, $db);
+        PrintDataSetInfoMenu2($host, $user, $pw, $db);
+        printf(" <p>\n");
+        PrintFailMenu($host, $user, $pw, $db);
+        PrintDataSetStatMenu($host, $user, $pw, $db);
+
+        printf(" <p>\n");
+        printf(" <div id='ranges' style='display:none'>");
+        PrintSourceMenu($host,$user,$pw,$db);
+        PrintDataSetRangeMenu($host,$user,$pw,$db);
+        printf("</div>");
+        printf("</div>");
+        printf(" <P>\n");
+
+        PrintNumResPullDown();
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        PrintButtons("datasetinfo-aio.php");
+
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("menu.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/fact_runinfo.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/fact_runinfo.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/fact_runinfo.php	(revision 17960)
@@ -0,0 +1,443 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $fromtable="RunInfo";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0)
+        {
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+            //don't put a '#' at the beginning of the alias, else SortBy won't work anymore
+            $query0 .= " COUNT(*) as 'NumRuns', ";
+            //$query0 .= " Round(Sum(TimeDiff(fRunStop,fRunStart))/60./60.,2) as 'Time [h]' ";
+            $query0 .= " Sec_to_time(Sum(Time_to_sec(TimeDiff(fRunStop,fRunStart)))) as 'Time<br>[hh:mm:ss]' ";
+        }
+        else
+        {
+            $query0 .= " Concat(fNight,'_', LPAD(fRunID, 3, 0)) as 'Run' ";
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On")
+                    if ($key!="fComments")
+                        if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                            $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+
+            if (!empty($_GET["fComments"]))
+            {
+                //$query0 .= ", if (Count(fComment)>0, Concat('<a&ws;id=\'commentcell', fNight, fRunID, '\'&ws;href=\'run_comment.php?fNight=',fNight,'&fRunID=', fRunID, '\'&ws;onmouseover=\'get_comments(', fNight, ',', fRunID, ')\'>', Count(fComment), '</a>'), ' ') ";
+                $query0 .= ", CONCAT(if (Count(fComment)>0, Concat('<a&ws;id=\'commentcell', fNight, fRunID, '\'&ws;href=\'run_comment.php?fNight=',fNight,'&fRunID=', fRunID, '\'&ws;onmouseover=\'get_comments(', fNight, ',', fRunID, ')\'>', Count(fComment), '</a>')";
+                $query0 .= ", ' '), ' ', ";
+                $query0 .= "CONCAT('<a&ws;id=\'commentcell', fNight, fRunID, '\'&ws;href=\'../../logbook/calendar.php?calendar=1&year=', left(fNight,4), '&month=', left(right(fNight,4),2), '&day=', right(fNight,2), '&action=dayview\'>lbk</a>', '')) ";
+                //$query0 .= ", if (Count(fComment)>0, Concat('<a&ws;href=\'run_comment.php?fNight=',fNight,'&fRunID=', fRunID, '\'&ws;onmouseover=\'bla\'>', Count(fComment), '</a>'), ' ') ";
+                $query0 .= " as 'Comments'";
+            }
+
+        }
+
+        $query0 .= " FROM " . $fromtable;
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty($joins[$key]))
+                $query0 .= GetJoin($fromtable, $key);
+        $query0 .= " LEFT JOIN RunComments USING (fNight, fRunID) ";
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)// this if clause doesn't work
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        if (!empty($_GET["fStartDate"]))
+        {
+            $startdate=substr($_GET["fStartDate"], 0, 10);
+//            if ($startdate=="0000-00-00")
+                $query0 .=" fNight >= " . $startdate . " ";
+//            else
+//                $query0 .= " fNight >= " . $startdate . " - 1 ";
+        }
+
+        if (!empty($_GET["fStopDate"]))
+        {
+//            if (strpos(strrev($query0), " DNA ")!=0)
+//                $query0 .= " AND ";
+
+            $stopdate=substr($_GET["fStopDate"], 0, 10);
+            $query0 .= " AND fNight <= " . $stopdate . "  ";
+        }
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable, $key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+        else
+            $query0 .= " GROUP BY fNight, fRunID ";
+
+
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $query0 .= " ORDER BY " . substr($_GET["fSortBy"], 0, -1) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+        else
+            if ($groups==0)
+                $query0 .= " ORDER BY Run DESC";
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fStartDate"]) && empty($_GET["fStopDate"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="200";
+            
+        if (empty($_GET["fNumEvents"]))
+            $_GET["fNumEvents"]=$first?"Off":"";
+
+        if (empty($_GET["fComments"]))
+            $_GET["fComments"]=$first?"On":"";
+
+        if (empty($_GET["fNumPhysicsTrigger"]))
+            $_GET["fNumPhysicsTrigger"]=$first?"On":"";
+
+        if (empty($_GET["Round(fNumPhysicsTrigger/Time_to_sec(TimeDiff(fRunStop,fRunStart)),1)"]))
+            $_GET["Round(fNumPhysicsTrigger/Time_to_sec(TimeDiff(fRunStop,fRunStart)),1)"]=$first?"On":"";
+
+        if (empty($_GET["fNumPedestalTrigger"]))
+            $_GET["fNumPedestalTrigger"]=$first?"On":"";
+
+        if (empty($_GET["fNumELPTrigger"]))
+            $_GET["fNumELPTrigger"]=$first?"On":"";
+
+        if (empty($_GET["fNumTimeTrigger"]))
+            $_GET["fNumTimeTrigger"]=$first?"Off":"";
+
+        if (empty($_GET["fNumExt1Trigger"]))
+            $_GET["fNumExt1Trigger"]=$first?"Off":"";
+
+        if (empty($_GET["fNumExt2Trigger"]))
+            $_GET["fNumExt2Trigger"]=$first?"Off":"";
+
+        if (empty($_GET["fNumILPTrigger"]))
+            $_GET["fNumILPTrigger"]=$first?"Off":"";
+
+        if (empty($_GET["fNumOtherTrigger"]))
+            $_GET["fNumOtherTrigger"]=$first?"Off":"";
+
+        if (empty($_GET["TimeDiff(fRunStop,fRunStart)"]))
+            $_GET["TimeDiff(fRunStop,fRunStart)"]=$first?"On":"";
+
+        if (empty($_GET["fRunStart"]))
+            $_GET["fRunStart"]=$first?"On":"";
+
+        if (empty($_GET["fRunStop"]))
+            $_GET["fRunStop"]=$first?"Off":"";
+
+        if (empty($_GET["fROI"]))
+            $_GET["fROI"]=$first?"On":"";
+
+        if (empty($_GET["fROITimeMarker"]))
+            $_GET["fROITimeMarker"]=$first?"Off":"";
+
+        if (empty($_GET["fFitsFileErrors"]))
+            $_GET["fFitsFileErrors"]=$first?"Off":"";
+
+        if (empty($_GET["fCompileTime"]))
+            $_GET["fCompileTime"]=$first?"Off":"";
+
+        if (empty($_GET["fRevisionNumber"]))
+            $_GET["fRevisionNumber"]=$first?"Off":"";
+
+        if (empty($_GET["if(fHasDrsFile=0,\"N\",fDrsStep)"]))
+            $_GET["if(fHasDrsFile=0,\"N\",fDrsStep)"]=$first?"Off":"";
+
+        if (empty($_GET["if(isnull(fCheckSum)+isnull(fDataSum),Concat(fMd5sumRaw,\"/\",fMd5sumRawZip),Concat(fCheckSum,\"/\",fDataSum))"]))
+            $_GET["if(isnull(fCheckSum)+isnull(fDataSum),Concat(fMd5sumRaw,\"/\",fMd5sumRawZip),Concat(fCheckSum,\"/\",fDataSum))"]=$first?"Off":"";
+
+        if (empty($_GET["fRunTypeName"]))
+            $_GET["fRunTypeName"]=$first?"On":"";
+
+        if (empty($_GET["fTriggerRateMedian"]))
+            $_GET["fTriggerRateMedian"]=$first?"Off":"";
+
+        if (empty($_GET["fThresholdMedian"]))
+            $_GET["fThresholdMedian"]=$first?"On":"";
+
+        if (empty($_GET["fBiasVoltageMedian"]))
+            $_GET["fBiasVoltageMedian"]=$first?"Off":"";
+
+        if (empty($_GET["fRightAscension"]))
+            $_GET["fRightAscension"]=$first?"Off":"";
+
+        if (empty($_GET["fDeclination"]))
+            $_GET["fDeclination"]=$first?"Off":"";
+
+        if (empty($_GET["fZenithDistanceMean"]))
+            $_GET["fZenithDistanceMean"]=$first?"On":"";
+
+        if (empty($_GET["fAzimuthMean"]))
+            $_GET["fAzimuthMean"]=$first?"On":"";
+
+        if (empty($_GET["fMoonZenithDistance"]))
+            $_GET["fMoonZenithDistance"]=$first?"Off":"";
+
+        if (empty($_GET["fMoonDisk"]))
+            $_GET["fMoonDisk"]=$first?"Off":"";
+
+        if (empty($_GET["fAngleToMoon"]))
+            $_GET["fAngleToMoon"]=$first?"Off":"";
+
+        if (empty($_GET["fSunZenithDistance"]))
+            $_GET["fSunZenithDistance"]=$first?"Off":"";
+
+        if (empty($_GET["fCameraTempMean"]))
+            $_GET["fCameraTempMean"]=$first?"Off":"";
+
+        if (empty($_GET["fCameraTempRms"]))
+            $_GET["fCameraTempRms"]=$first?"Off":"";
+
+        if (empty($_GET["fOutsideTempMean"]))
+            $_GET["fOutsideTempMean"]=$first?"Off":"";
+
+        if (empty($_GET["fOutsideTempRms"]))
+            $_GET["fOutsideTempRms"]=$first?"Off":"";
+
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"fact_runinfo.php\" METHOD=\"GET\">\n");
+
+        // pull down boxes
+
+        printf(" <table>\n");
+        printf("  <tr><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "RunType",  "fRunTypeName",  "fRunTypeKEY", "RunType");
+        printf(" </td></tr></table>\n");
+        printf(" <p>\n");
+
+        printf(" <table>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fComments",                     "comments");
+        CheckBox("fRunStart",                     "start time");
+        CheckBox("fRunStop",                      "stop time");
+        CheckBox("TimeDiff(fRunStop,fRunStart)",  "duration");
+        CheckBox("fNumEvents",                    "#Evts");
+        CheckBox("fROI",                          "roi");
+
+        printf("  </tr>\n");
+        printf("  <tr>\n");
+
+        CheckBox("Round(fNumPhysicsTrigger/Time_to_sec(TimeDiff(fRunStop,fRunStart)),1)",    "phys rate");
+        CheckBox("fNumPhysicsTrigger",    "#Phys");
+        CheckBox("fNumPedestalTrigger",   "#Ped");
+        CheckBox("fNumELPTrigger",        "#ELP");
+        CheckBox("fNumTimeTrigger",       "#Time");
+
+        printf("  </tr>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fNumExt1Trigger",       "#Ext1");
+        CheckBox("fNumExt2Trigger",       "#Ext2");
+        CheckBox("fNumILPTrigger",        "#ILP");
+        CheckBox("fNumOtherTrigger",      "#Other");
+
+        printf("  </tr>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fTriggerRateMedian",    "rate");
+        CheckBox("fThresholdMedian",      "threshold");
+        CheckBox("fBiasVoltageMedian",    "voltage");
+        CheckBox("if(fHasDrsFile=0,\"N\",fDrsStep)", "drs");
+        CheckBox("fROITimeMarker",                   "roi-tm");
+
+        printf("  </tr>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fZenithDistanceMean",   "ZdMean");
+        CheckBox("fAzimuthMean",          "AzMean");
+        CheckBox("fRightAscension",       "RA");
+        CheckBox("fDeclination",          "Dec");
+
+        printf("  </tr>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fMoonZenithDistance",   "ZdMoon");
+        CheckBox("fSunZenithDistance",    "ZdSun");
+        CheckBox("fMoonDisk",             "MoonDisk");
+        CheckBox("fAngleToMoon",          "Angle2Moon");
+
+        printf("  </tr>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fOutsideTempMean",      "temp mean");
+        CheckBox("fOutsideTempRms",       "temp rms");
+        CheckBox("fCameraTempMean",       "cam temp mean");
+        CheckBox("fCameraTempRms",        "cam temp rms");
+
+        printf("  </tr>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fFitsFileErrors",                  "file err");
+        CheckBox("fCompileTime",                     "compiled");
+        CheckBox("fRevisionNumber",                  "rev#");
+        CheckBox("if(isnull(fCheckSum)+isnull(fDataSum),Concat(fMd5sumRaw,\"/\",fMd5sumRawZip),Concat(fCheckSum,\"/\",fDataSum))",  "checksum");
+
+        printf("  </tr>\n");
+        printf(" </table>\n");
+        printf(" <p>\n");
+
+        if (empty($_GET["fStartDate"]))
+            $timemin = GetMin("fNight", "RunInfo", $host, $user, $pw, $db);
+        else
+            $timemin = $_GET["fStartDate"];
+
+        if (empty($_GET["fStopDate"]))
+            $timemax = GetMax("fNight", "RunInfo", $host, $user, $pw, $db);
+        else
+            $timemax = $_GET["fStopDate"];
+
+        printf("Run&nbsp;(yyyymmdd)&nbsp;from&nbsp;<input name=\"fStartDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">\n", $timemin);
+        printf("to&nbsp;<input name=\"fStopDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">&nbsp;&nbsp;&nbsp;&nbsp;\n", $timemax);
+
+        printf(" Results:\n");
+        printf(" <select name=\"fNumResults\">\n");
+
+        $numres = array("10", "20", "50", "100", "200", "500", "1000", "2000");
+        foreach ($numres as $element)
+        {
+            if ($element==$_GET["fNumResults"])
+                printf("<option value=\"%s\" selected>%3s</option>\n", $element, $element);
+            else
+                printf("<option value=\"%s\">%3s</option>\n", $element, $element);
+        }
+        printf(" </select>\n");
+        printf(" &nbsp;&nbsp;&nbsp;\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"fact_runinfo.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+        mysql_query("SET BIG_TABLES=1"); // necessary for mySQL <= 4
+
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("factdefs.php");
+
+    ini_set("display_errors",   "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+            PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors",   "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/factdefs.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/factdefs.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/factdefs.php	(revision 17960)
@@ -0,0 +1,120 @@
+<?php
+
+$checkwhere = array
+    (
+     "fRunTypeName"                      => CheckWhere("fRunTypeKEY"),
+    );
+
+$checkgroup = array
+    (
+     "fRunTypeName"                      => CheckGroup("fRunTypeKEY"),
+    );
+
+
+            //don't put a '#' at the beginning of the alias, else SortBy won't work anymore
+$alias = array
+    (
+     "NumRuns"                          => "#Runs",
+     "Run"                              => "Run",
+     "fRunTypeName"                     => "RunType",
+     "if(isnull(fCheckSum)+isnull(fDataSum),Concat(fMd5sumRaw,\"/\",fMd5sumRawZip),Concat(fCheckSum,\"/\",fDataSum))" => "checksum",
+     "fROI"                             => "roi",
+     "fROITimeMarker"                   => "roi-tm",
+     "fLastUpdate"                      => "LastUpd",
+     //"SUM(fRunTime)/3600"               => "Time [h]",
+     "SUM(fNumEvents)"                  => "Evts",
+     "Min(fZenithDistanceMin)"          => "ZDMin",
+     "Max(fZenithDistanceMax)"          => "ZDMax",
+     "Min(fZenithDistance)"             => "ZdMin",
+     "Max(fZenithDistance)"             => "ZdMax",
+     "fNumEvents"                       => "#Evts",
+     "fRunStart"                        => "start",
+     "fRunStop"                         => "stop",
+     "fFitsFileErrors"                  => "file err",
+     "fCompileTime"                     => "compiled",
+     "fRevisionNumber"                  => "rev#",
+     "if(fHasDrsFile=0,\"N\",fDrsStep)" => "drs",
+     "TimeDiff(fRunStop,fRunStart)"     => "duration",
+     "Round(fNumPhysicsTrigger/Time_to_sec(TimeDiff(fRunStop,fRunStart)),1)"  => "phys<br>rate<br>[Hz]",
+     "fNumPhysicsTrigger"               => "#Phys",
+     "fNumExt1Trigger"                  => "#Ext1",
+     "fNumExt2Trigger"                  => "#Ext2",
+     "fNumELPTrigger"                   => "#ELP",
+     "fNumILPTrigger"                   => "#ILP",
+     "fNumPedestalTrigger"              => "#Ped",
+     "fNumTimeTrigger"                  => "#Time",
+     "fNumOtherTrigger"                 => "#Other",
+     //"Round(Sum(TimeDiff(fRunStop,fRunStart))/60./60.,1)"  => "Time [h]",
+     "fTriggerRateMedian"               => "median rate",
+     "fBiasVoltageMedian"               => "median bias",
+     "fThresholdMedian"                 => "median<br>threshold",
+     "fRightAscension"                  => "RA",
+     "fDeclination"                     => "Decl",
+     "fZenithDistanceMean"              => "Zd",
+     "fMoonZenithDistance"              => "ZdMoon",
+     "fMoonDisk"                        => "MoonDisk",
+     "fAngleToMoon"                     => "Angle2Moon",
+     "fSunZenithDistance"               => "ZdSun",
+     "fAzimuthMean"                     => "Az",
+     "fCameraTempMean"                  => "CamTemp",
+     "fCameraTempRms"                   => "CamTempRms",
+     "fOutsideTempMean"                 => "Temp",
+     "fOutsideTempRms"                  => "TempRms",
+     //"Sec_to_time(Sum(Time_to_sec(TimeDiff(fRunStop,fRunStart))))" => "Time<br>[hh:mm:ss]",
+     //"Time [hh:mm:ss]" => "Time<br>[hh:mm:ss]",
+    );
+
+
+$rightalign = array
+    (
+     //$alias["fRunTypeName"]              => "1",
+     $alias["fNumEvents"]                => "1",
+     $alias["Round(fNumPhysicsTrigger/Time_to_sec(TimeDiff(fRunStop,fRunStart)),1)"] => "1",
+     $alias["fNumPhysicsTrigger"]        => "1",
+     $alias["fNumExt1Trigger"]           => "1",
+     $alias["fNumExt2Trigger"]           => "1",
+     $alias["fNumELPTrigger"]            => "1",
+     $alias["fNumILPTrigger"]            => "1",
+     $alias["fNumPedestalTrigger"]       => "1",
+     $alias["fNumTimeTrigger"]           => "1",
+     $alias["fNumOtherTrigger"]          => "1",
+     $alias["fFitsFileErrors"]           => "1",
+     $alias["fRevisionNumber"]           => "1",
+     $alias["fROI"]                      => "1",
+     $alias["fROITimeMarker"]            => "1",
+     //"Time [h]"                          => "1",
+     "Time<br>[hh:mm:ss]"                          => "1",
+     "NumRuns"                           => "1",
+     "Evts"                              => "1",
+);
+
+function GetCheck($fromtable, $val)
+{
+    $checks = array
+        (
+         "fRunTypeName"                      => $fromtable . ".fRunTypeKEY",
+        );
+
+    $check="";
+    if (!empty($checks[$val]))
+        $check=$checks[$val];
+    return $check;
+}
+
+
+function GetJoin($fromtable, $val)
+{
+    $joins = array
+        (
+         "fRunTypeName"                     => " LEFT JOIN RunType                     USING(fRunTypeKEY) ",
+        );
+
+
+    $join="";
+    if (!empty($joins[$val]))
+        $join=$joins[$val];
+    return $join;
+}
+
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/ganymed.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/ganymed.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/ganymed.php	(revision 17960)
@@ -0,0 +1,355 @@
+<?php
+{
+    function CreateQuery($_GET)
+    {
+        $query0  = "SELECT ";
+        //datasets (0-3)
+        $query0 .= " DataSets.fDataSetNumber, fDataSetName, fComment, ";//0,1,2
+        $query0 .= " fSourceName, fObservationModeName, ";//3, 4
+        //steps (5-8)
+        $query0 .= " fDataSetInserted, fStarFilesAvail, ";//5,6
+        $query0 .= " fGanymed, fFillGanymed, ";//7,8
+        //ganymed (9-14)
+        $query0 .= " fExcessEvents, fBackgroundEvents, fSignalEvents, ";//9,10,11
+        $query0 .= " fSignificance, fScaleFactor, fEffOnTime/3600 ";//12,13, 14
+
+        $query0 .= " FROM DataSets ";
+
+        $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
+        $query0 .= " LEFT JOIN ObservationMode USING(fObservationModeKEY) ";
+        $query0 .= " LEFT JOIN DataSetProcessStatus USING(fDataSetNumber) ";
+        $query0 .= " LEFT JOIN Ganymed USING(fDataSetNumber) ";
+
+        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
+            $query0 .= " WHERE DataSets.fDataSetNumber between " . $_GET["fRunMin"] . " and " . $_GET["fRunMax"] ;
+        if (!empty($_GET["fDataSetNo"]))
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+            $query0 .= " DataSets.fDataSetNumber='" . $_GET["fDataSetNo"] . "'";
+        }
+        if (!empty($_GET["fSourceN"]))
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+            $query0 .= " fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+        }
+        $query0 .= " ORDER BY DataSets.fDataSetNumber ";
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+
+        if (empty($_GET["fAll"]))
+            $_GET["fAll"]="Off";
+
+        if (empty($_GET["fSequ"]))
+            $_GET["fSequ"]="Off";
+
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"ganymed.php\" METHOD=\"GET\">\n");
+
+        printf("DataSet#&nbsp;<input name=\"fDataSetNo\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"");
+        if (!empty($_GET["fDataSetNo"]))
+            printf("%s", $_GET["fDataSetNo"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n");
+
+        if (empty($_GET["fRunMin"]))
+//            $min = "100";
+            $min = GetMin("fDataSetNumber", "DataSets", $host, $user, $pw, $db);
+        else
+            $min = $_GET["fRunMin"];
+
+        if (empty($_GET["fRunMax"]))
+            $max = GetMax("fDataSetNumber", "DataSets", $host, $user, $pw, $db);
+        else
+            $max = $_GET["fRunMax"];
+
+        printf("DataSets&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">\n", $min);
+        printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+
+        if ($_GET["fAll"]=="On")
+            $checked = "checked";
+        else
+            $checked = "";
+        printf("<input type=\"checkbox\" name=\"fAll\" value=\"On\" %s>plots\n", $checked);
+
+        if ($_GET["fSequ"]=="On")
+            $checked = "checked";
+        else
+            $checked = "";
+        printf("<input type=\"checkbox\" name=\"fSequ\" value=\"On\" %s>sequences\n", $checked);
+
+        printf(" <P>\n");
+
+        printf("Source&nbsp;(<A HREF=\"regexp.html\">regexp</A>)&nbsp;<input name=\"fSourceN\" type=\"text\" size=\"15\" maxlength=\"15\" value=\"");
+        if (!empty($_GET["fSourceN"]))
+            printf("%s", $_GET["fSourceN"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n");
+
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"ganymed.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Print' onClick='self.location.href=\"%s&fPrintTable=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function GetStatus($step)
+    {
+        if (is_null($step))
+            return "<font color='#FF0000'>not done</font>";
+        else
+        {
+            if (strpos($step, "1970-01-01 00:00:00")==FALSE)
+                return "done";
+            else
+                return "not to be done";
+        }
+        return "there is an error -> tell Dani";
+    }
+
+    function GetRanges($db_id, $sequences)
+    {
+        $query="SELECT Min(fZenithDistanceMin), Max(fZenithDistanceMax), Min(fRunStart), Max(fRunStart) FROM Sequences WHERE fSequenceFirst IN (";
+        $sequlist=str_replace(" ", ",", trim($sequences));
+//        printf("sequ-after: %s", $sequlist);
+        $query .= $sequlist . ")";
+        $result = mysql_query($query, $db_id);
+//        printf("query: %s", $query);
+        $zdmin=mysql_result($result, $i, 0);
+        $zdmax=mysql_result($result, $i, 1);
+        $starttime=str_replace("-", "/",substr(mysql_result($result, $i, 2),0,10));
+        $stoptime=str_replace("-", "/",substr(mysql_result($result, $i, 3),0,10));
+        printf("<br> Zd: %s - %s degree <br> Observationperiod: %s - %s ", $zdmin, $zdmax, $starttime, $stoptime);
+    }
+
+    function PrintDataSetInfo($db_id, $result0, $ganymedtabsw, $ganymedtabs)
+    {
+        $numres = mysql_num_rows($result0);
+
+        printf("<center>");
+        printf("<table BORDER=\"0\">\n");
+        printf("<tr><td>");
+        printf("# of DataSets: %d ", $numres);
+        printf("</td></tr>");
+
+        for ($i=0 ; $i<$numres ; $i++)
+        {
+            $datasetno=mysql_result($result0, $i, 0);
+            $datasetname=mysql_result($result0, $i, 1);
+            $comment=mysql_result($result0, $i, 2);
+            $source=mysql_result($result0, $i, 3);
+            $wobble=mysql_result($result0, $i, 4);
+            $inserted=mysql_result($result0, $i, 5);
+            $filesavail=mysql_result($result0, $i, 6);
+            $ganymed=mysql_result($result0, $i, 7);
+            $fillganymed=mysql_result($result0, $i, 8);
+            $excess=mysql_result($result0, $i, 9);
+            $bg=mysql_result($result0, $i, 10);
+            $signal=mysql_result($result0, $i, 11);
+            $signif=mysql_result($result0, $i, 12);
+            $scale=mysql_result($result0, $i, 13);
+            $effontime=mysql_result($result0, $i, 14);
+            $num=sprintf("%08d",$datasetno);
+            $num2=substr($num,0,5);
+            $datasetfile="http://www.astro.uni-wuerzburg.de/datacenter/datasets/" . $num2 . "/dataset" . $num . ".txt";
+
+            printf("<tr><td>");
+
+            printf(" <table BORDER=\"1\">");
+            printf(" <tr BGCOLOR='#C0C0C0'>\n");
+            printf(" <th colspan=\"6\"><big>Source: <big>%s </big></big>(DataSet#:", $source, $datasetno);
+            printf(" <a href=\"%s\">%s</a>) </th>", $datasetfile, $datasetno);
+            printf(" </tr><tr BGCOLOR='#E0E0E0' ALIGN='left'>\n");
+            printf(" <th colspan=\"6\"> <b>%s Mode</b>, %s ", $wobble, $comment);
+            printf(" </th></tr><tr>\n");
+
+            printf(" <td colspan=\"6\"> DatasetName: %s", $datasetname);
+            if (!is_null($ganymed))
+                printf(", <font color='green'> ganymed done</font> ");
+
+            printf(" <tr>");
+
+            if (!is_null($fillganymed))
+            {
+                printf("<td colspan=\"6\"></td></tr>\n");
+                printf(" <tr BGCOLOR='#C0C0C0'><th colspan=\"6\">results ");
+                printf(" (<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/ganymed/%s/%s/\">plots</a>)",
+                       $num2, $num);
+                printf(" </th></tr><tr BGCOLOR='#E0E0E0'>\n");
+                printf(" <td>excess events</td>\n");
+                printf(" <td>background events</td>\n");
+                printf(" <td>signal events</td>\n");
+                printf(" <td>significance</td>\n");
+                printf(" <td>scale factor</td>\n");
+                printf(" <td>effective ontime</td>\n");
+                printf(" </tr><tr BGCOLOR='#D0D0D0' align='right'>");
+                printf(" <td>%s</td>\n", $excess);
+                printf(" <td>%s</td>\n", $bg);
+                printf(" <td>%s</td>\n", $signal);
+                printf(" <td>%s</td>\n", $signif);
+                printf(" <td>%s</td>\n", $scale);
+                printf(" <td>%s h</td>\n", $effontime);
+            }
+
+            if ($_GET["fSequ"]=="On")
+            {
+                $dataset=file_get_contents($datasetfile);
+                $onpos=strpos($dataset, "SequencesOn:");
+                $offpos=strpos($dataset, "SequencesOff:");
+                $possource=strpos($dataset, "SourceName:");
+                $sequoff="";
+                if (!empty($offpos))
+                    $sequoff=substr($dataset, $offpos+13, $possource-($offpos+13));
+                if (empty($offpos))
+                    $offpos=$possource;
+                $sequon=substr($dataset, $onpos+12, $offpos-($onpos+12));
+
+                if (!empty($sequon))
+                {
+                    printf("<tr><td colspan=\"6\">\n SequencesOn: ");
+                    $sequences=split(" ", trim($sequon));
+                    foreach($sequences as $key => $sequ)
+                        printf("<a href=\"sequence.php?fSequenceNo=%s&fAll=On\">%s</a> ", $sequ, $sequ);
+                    GetRanges($db_id, $sequon);
+                    printf("</td></tr>");
+
+                    if (!empty($sequoff))
+                    {
+                        printf("<tr><td colspan=\"6\">\n SequencesOff: ");
+                        $sequences=split(" ", trim($sequoff));
+                        foreach($sequences as $key => $sequ)
+                            printf("<a href=\"sequence.php?fSequenceNo=%s&fAll=On\">%s</a> ", $sequ, $sequ);
+                        GetRanges($db_id, $sequoff);
+                        printf("</td></tr>");
+                    }
+                }
+            }
+            printf("<tr><td colspan=\"6\">\n Plots: ");
+
+            if ($wobble=='Wobble')
+                $tabs=$ganymedtabsw;
+            else
+                $tabs=$ganymedtabs;
+            foreach($tabs as $key => $element)
+                if (!$key==0)
+                    printf("<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/ganymed/%s/%s/ganymed%s-tab%s.png\">%s</a> ", $num2, $num, $num, $key, $element);
+
+            printf("</td></tr>");
+
+            if ($_GET["fAll"]=="On" && !is_null($ganymed))
+            {
+                //plotting Hist and FS
+                printf("<tr><td colspan=\"6\" align='center'>\n");
+                printf(" <img src=\"http://www.astro.uni-wuerzburg.de/datacenter/ganymed/%s/%s/ganymed%s-tab14.png\">",
+                       $num2, $num, $num);
+                printf(" <img src=\"http://www.astro.uni-wuerzburg.de/datacenter/ganymed/%s/%s/ganymed%s-tab13.png\">",
+                       $num2, $num, $num);
+                printf(" </td></tr>");
+            }
+
+            printf(" </table>");
+            printf("</td></tr><tr><td><br></td></tr>");
+        }
+        printf("</table>\n");
+
+        printf("</center>\n");
+        printf("</tr><tr class='Block'><td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $ganymedtabsw, $ganymedtabs)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET);
+
+        $result0 = mysql_query($query0, $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintDataSetInfo($db_id, $result0, $ganymedtabsw, $ganymedtabs);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("tabs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $ganymedtabsw, $ganymedtabs);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $ganymedtabsw, $ganymedtabs);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $ganymedtabsw, $ganymedtabs);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/include.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/include.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/include.php	(revision 17960)
@@ -0,0 +1,725 @@
+<?php
+
+function EnumQuery($name)
+{
+    $var  = $name . "Enum";
+    $txt  = "";
+    switch ($_GET[$var])
+    {
+    case 0: $txt .= ""; break;
+    case 1: $txt .= $name . "='yes' AND "; break;
+    case 2: $txt .= $name . "='no' AND "; break;
+    case 3: $txt .= ""; break;
+    }
+    return $txt;
+}
+
+function PrintEnumMenu($name, $text)
+{
+    $var = $name . "Enum";
+
+    if ($_GET[$name]=="On")
+        $checked = "checked";
+    else
+        $checked = "";
+
+    printf("    <input type='checkbox' name='%s' value='On' %s>%s\n", $name, $checked, $text);
+    printf("<BR>");
+
+    printf(" <select name='%s'>\n", $var);
+
+    $status = array
+        ( 0 => "all",
+          1 => "yes",
+          2 => "no",
+          3 => "group by"
+        );
+
+    $stat=$_GET[$var];
+    for ($i=0; $i<4; $i++)
+    {
+        if ($stat==$i)
+            printf("<option value='%d' selected>%s</option>\n", $i, $status[$i]);
+        else
+            printf("<option value='%d'>%s</option>\n", $i, $status[$i]);
+    }
+
+    printf(" </select>\n");
+    printf(" &nbsp;&nbsp;&nbsp;\n");
+
+}
+
+function StatusQuery($name, $timelimits)
+{
+    if (empty($timelimits[$name]))
+        $timelimit="12";
+    else
+        $timelimit=$timelimits[$name];
+    $var  = $name . "Status";
+    $txt  = "";
+    switch ($_GET[$var])
+    {
+    case 0://all
+        $txt .= " ";
+        break;
+    case 1://done and avail
+        $txt .= " NOT ISNULL(" . $name . "Status.fStartTime) AND "
+            ." NOT ISNULL(" . $name . "Status.fStopTime) AND "
+            ." NOT ISNULL(" . $name . "Status.fAvailable) AND "
+            ." ISNULL(" . $name . "Status.fReturnCode) AND ";
+        break;
+    case 2://done
+        $txt .= " NOT ISNULL(" . $name . "Status.fStartTime) AND "
+            ." NOT ISNULL(" . $name . "Status.fStopTime) AND "
+            ." ISNULL(" . $name . "Status.fAvailable) AND "
+            ." ISNULL(" . $name . "Status.fReturnCode) AND ";
+        break;
+    case 3://not done
+        $txt .= " ISNULL(" . $name . "Status.fStartTime) AND "
+            ." ISNULL(" . $name . "Status.fStopTime) AND "
+            ." ISNULL(" . $name . "Status.fReturnCode) AND ";
+        break;
+    case 4://not to be done
+        $txt .= $name ."Status.fStartTime='1970-01-01 00:00:00' AND "
+            . $name ."Status.fStopTime='1970-01-01 00:00:00' AND ";
+        break;
+    case 5://running
+        $txt .= " NOT ISNULL(" . $name . "Status.fStartTime) AND "
+            ." DATE_SUB(Now(),INTERVAL " . $timelimit . " HOUR) < " . $name . "Status.fStartTime AND "
+            ." ISNULL(" . $name . "Status.fStopTime) AND "
+            ." ISNULL(" . $name . "Status.fReturnCode) AND ";
+        break;
+    case 6://failed
+        $txt .= " NOT ISNULL(" . $name . "Status.fStartTime) AND "
+            ." NOT ISNULL(" . $name . "Status.fStopTime) AND "
+            ." NOT ISNULL(" . $name . "Status.fReturnCode) AND ";
+        break;
+    case 7://crashed
+        $txt .= " NOT ISNULL(" . $name . "Status.fStartTime) AND "
+            ." DATE_SUB(Now(),INTERVAL " . $timelimit . " HOUR) > " . $name . "Status.fStartTime AND "
+            ." ISNULL(" . $name . "Status.fStopTime) AND "
+            ." ISNULL(" . $name . "Status.fReturnCode) AND ";
+        break;
+    case 8://group by
+        $txt .= "";
+        break;
+    }
+    return $txt;
+}
+
+function PrintStatusMenu($name, $text)
+{
+    $var = $name . "Status";
+
+    if ($_GET[$name]=="On")
+        $checked = "checked";
+    else
+        $checked = "";
+
+    printf("    <input type='checkbox' name='%s' value='On' %s>%s\n", $name, $checked, $text);
+    printf("<BR>");
+
+    printf(" <select name='%s'>\n", $var);
+
+    $status = array
+        ( 0 => "ALL",
+          1 => "done and avail",
+          2 => "done",
+          3 => "not done",
+          4 => "not to be done",
+          5 => "running",
+          6 => "failed",
+          7 => "crashed",
+          8 => "GROUP BY",
+        );
+
+    $stat=$_GET[$var];
+    for ($i=0; $i<9; $i++)
+    {
+        if ($stat==$i)
+            printf("<option value='%d' selected>%s</option>\n", $i, $status[$i]);
+        else
+            printf("<option value='%d'>%s</option>\n", $i, $status[$i]);
+    }
+
+    printf(" </select>\n");
+    printf(" &nbsp;&nbsp;&nbsp;\n");
+
+}
+
+function PrintPullDown($host, $user, $pw, $db, $table, $name, $index, $descr)
+{
+    $db_id = mysql_connect($host, $user, $pw);
+    if ($db_id==FALSE)
+    {
+            printf("mysql_connect returned the following error:<br>");
+            printf("%s<br>", mysql_error());
+            die("");
+    }
+
+    $query   = "SELECT " . $index . ", " . $name . " FROM " . $db . "." . $table . " ORDER BY " . $name;
+    $result  = mysql_query($query);
+
+    if (!$result)
+    {
+        printf("-N/A-");
+        return;
+    }
+
+    $numrows = mysql_num_rows($result);
+
+    if ($_GET[$name]=="On")
+        $checked = "checked";
+    else
+        $checked = "";
+
+    printf("    <input type='checkbox' name='%s' value='On' %s><A HREF='printtable.php?fTable=%s'>%s</A>\n", $name, $checked, $table, $descr);
+
+    printf("   <BR>\n");
+
+    printf("   <select name='%s' size='1' class='Width'>\n", $index);
+
+    if (empty($_GET[$index]) || $_GET[$index]==0)
+        printf("    <option value='0' selected>--- ALL ---</option>\n");
+    else
+        printf("    <option value='0'>--- ALL ---</option>\n");
+
+    if (!empty($_GET[$index]) && $_GET[$index]==-1)
+        printf("    <option value='-1' selected>--- GROUP BY ---</option>\n");
+    else
+        printf("    <option value='-1'>--- GROUP BY ---</option>\n");
+
+    while ($row = mysql_fetch_row($result))
+    {
+        if (!empty($_GET[$index]) && $_GET[$index]==$row[0])
+            printf("    <option value='%s' selected>%s</option>\n", $row[0], $row[1]);
+        else
+            printf("    <option value='%s'>%s</option>\n", $row[0], $row[1]);
+    }
+    printf("   </select>\n");
+    printf("   &nbsp;\n", $index);
+    
+    mysql_free_result($result);
+
+    mysql_close($db_id);
+}
+
+function GetMin($field, $table, $host, $user, $pw, $db)
+{
+    $db_id = mysql_connect($host, $user, $pw);
+    if ($db_id==FALSE)
+    {
+            printf("mysql_connect returned the following error:<br>");
+            printf("%s<br>", mysql_error());
+            die("");
+    }
+
+    $query  = "SELECT MIN(" . $field . ") FROM " . $db . "." . $table;
+    $result = mysql_query($query);
+    if (!$result)
+        return "0";
+
+    $row = mysql_fetch_row($result);
+
+    $min = $row[0];
+
+    mysql_free_result($result);
+    mysql_close($db_id);
+
+    return $min;
+}
+
+function GetMax($field, $table, $host, $user, $pw, $db)
+{
+    $db_id = mysql_connect($host, $user, $pw);
+    if ($db_id==FALSE)
+    {
+            printf("mysql_connect returned the following error:<br>");
+            printf("%s<br>", mysql_error());
+            die("");
+    }
+
+    $query  = "SELECT MAX(" . $field . ") FROM " . $db . "." . $table;
+    $result = mysql_query($query);
+    if (!$result)
+        return "0";
+
+    $row = mysql_fetch_row($result);
+
+    $max = $row[0];
+
+    mysql_free_result($result);
+    mysql_close($db_id);
+
+    return $max;
+}
+
+function GetMaxDate($field, $table, $host, $user, $pw, $db)
+{
+    $db_id = mysql_connect($host, $user, $pw);
+    if ($db_id==FALSE)
+    {
+            printf("mysql_connect returned the following error:<br>");
+            printf("%s<br>", mysql_error());
+            die("");
+    }
+
+    $query  = "SELECT DATE_FORMAT(if(MAX(" . $field . ")<'13:00:00', MAX(" . $field . "), ADDDATE(MAX(" . $field . "), INTERVAL +1 DAY)), '%Y-%m-%d') FROM " . $db . "." . $table;
+    $result = mysql_query($query);
+    if (!$result)
+        return "0";
+
+    $row = mysql_fetch_row($result);
+
+    $maxdate = $row[0];
+
+    mysql_free_result($result);
+    mysql_close($db_id);
+
+    return $maxdate;
+}
+
+//for download of output
+function PrintText($result0)
+{
+    while ($row0 = mysql_fetch_assoc($result0))
+    {
+        foreach ($row0 as $key => $element)
+            printf("%s\t", $element);
+        printf("\n");
+    }
+}
+
+function PrintSubmittedQuery($query0, $db, $old)
+{
+    //diplay query on old websites
+    if (empty($old))
+        printf("<tr class='Block' id='showquery' style='display:none'><td>\n");
+    else
+        printf("<tr class='Block' id='showquery' style='display:block'><td>\n");
+    printf("<b>DB:</b> %s <br>\n", $db);
+    printf("<U><B>submitted query:</B></U><BR>%s<BR>\n", htmlspecialchars($query0));
+    printf("</td></tr>\n");
+}
+
+function Checkbox($value, $text)
+{
+    if ($_GET[$value]=="On")
+        $checked = "checked";
+    else
+        $checked = "";
+
+    printf("<td><input type='checkbox' name='%s' value='On' %s>%s</td>\n", $value, $checked, $text);
+}
+
+function RadioButton($name, $value, $text)
+{
+    if ($_SESSION[$name]==$value)
+        $checked = "checked";
+    else
+        $checked = "";
+
+    printf("<td><input type='radio' name='%s' value='%s' %s>%s</td>\n", $name, $value, $checked, $text);
+}
+
+function CheckWhere($column)
+{
+    foreach ($_GET as $key => $element)
+    {
+        if ($key==$column)
+        {
+//            if ($element>0)
+//                printf ("FIXED: %s<BR>", $column);
+            return $element;
+        }
+    }
+    return 0;
+}
+
+function CheckGroup($column)
+{
+    foreach ($_GET as $key => $element)
+    {
+        if ($key==$column)
+        {
+            //if ($element==-1)
+            //    printf ("GROUP: %s<BR>", $column);
+            return $element;
+        }
+    }
+    return 0;
+}
+
+function CheckStatusGroup($column)
+{
+    foreach ($_GET as $key => $element)
+        if ($key==$column."Status")
+            if ($element==8)
+                return -1;
+    return 0;
+}
+
+function CheckEnumGroup($column)
+{
+    foreach ($_GET as $key => $element)
+        if ($key==$column)
+            if ($element==3)
+                return -1;
+    return 0;
+}
+
+function RemoveSortBy()
+{
+    $menu = "";
+
+    $uri = $_SERVER["REQUEST_URI"];
+    $pos = strpos($uri, "fSortBy");
+    $amp3=FALSE;
+    if ($pos!=FALSE)
+    {
+        $amp1 = substr($uri, 0, $pos-1);
+        $amp2 = substr($uri, $pos);
+        $amp3 = strchr($amp2, "&");
+
+        $uri = $amp1;
+    }
+
+    return $uri;
+}
+
+function FindAlias($alias, $search)
+{
+    foreach ($alias as $key => $element)
+        if ($element==$search)
+            return $key;
+
+    if ($search=="# Runs")
+        return "NumRuns";
+    if ($search=="# Sequ")
+        return "NumSequ";
+    if ($search=="# Datasets")
+        return "NumDS";
+    if ($search=="# days")
+        return "NumDays";
+    return $search;
+    return "";
+}
+
+//function for button in builddatasets.php
+function GetClearedURL($all)
+{
+    $url=$_SERVER["REQUEST_URI"];
+    if ($all=="yes")
+    {
+        $url=str_replace("&DisplaySelected=yes",     "", $url);
+        $url=str_replace("&DisplaySelected=no",      "", $url);
+        $url=str_replace("&DisplaySelected=inverse", "", $url);
+        //reset fNumStart
+        $url=preg_replace("/&fNumStart[=][0-9]*/", "", $url);
+    }
+    $url=str_replace("&insert=yes", "", $url);
+    $url=str_replace("&fSendTxt=2", "", $url);
+    $url=str_replace("&fSendTxt=1", "", $url);
+    $url=htmlspecialchars($url);
+    return $url;
+}
+
+function PrintUpdateDataSetButton()
+{
+    if (empty($_SESSION["insert"]))
+        printf("<input type='submit' value='Update Selection'>&nbsp;&nbsp;&nbsp;\n");
+    else
+        printf("<input type='button' value='Continue' onClick='self.location.href=\"%s\"'>&nbsp;&nbsp;&nbsp;\n", GetClearedURL());
+
+}
+
+//function for button in builddatasets.php
+function PrintDisplaySequencesButtons()
+{
+    if (!empty($_SESSION["DataSetSelection"]) && empty($_SESSION["DataSetAcknowledged"]))
+        return;
+
+    if ((empty($_SESSION["DisplaySelected"]) || $_SESSION["DisplaySelected"]=="no")
+        && !(empty($_SESSION["sequon"]) && empty($_SESSION["sequoff"])))
+    {
+        PrintUpdateDataSetButton();
+        printf("<input type='button' value='Display Selected Sequences' onClick='self.location.href=\"%s&DisplaySelected=yes\"'>\n", GetClearedURL("yes"));
+        printf("&nbsp;&nbsp;&nbsp;<input type='button' value='Display Not-Selected Sequences' onClick='self.location.href=\"%s&DisplaySelected=inverse\"'>\n", GetClearedURL("yes"));
+        printf("<br><br>\n");
+    }
+
+    if ($_SESSION["DisplaySelected"]=="yes"
+       && !(empty($_SESSION["sequon"]) && empty($_SESSION["sequoff"])))
+    {
+        PrintUpdateDataSetButton();
+        printf("<input type='button' value='Display Not-Selected Sequences' onClick='self.location.href=\"%s&DisplaySelected=inverse\"'>\n", GetClearedURL("yes"));
+        printf("&nbsp;&nbsp;&nbsp;<input type='button' value='Display All Sequences' onClick='self.location.href=\"%s&DisplaySelected=no\"'>\n", GetClearedURL("yes"));
+        printf("&nbsp;&nbsp;&nbsp;<i>Currently only selected sequences are displayed.</i><br><br>\n");
+    }
+
+    if ($_SESSION["DisplaySelected"]=="inverse"
+       && !(empty($_SESSION["sequon"]) && empty($_SESSION["sequoff"])))
+    {
+        PrintUpdateDataSetButton();
+        printf("<input type='button' value='Display Selected Sequences' onClick='self.location.href=\"%s&DisplaySelected=yes\"'>\n", GetClearedURL("yes"));
+        printf("&nbsp;&nbsp;&nbsp;<input type='button' value='Display All Sequences' onClick='self.location.href=\"%s&DisplaySelected=no\"'>\n", GetClearedURL("yes"));
+        printf("&nbsp;&nbsp;&nbsp;<i>Currently only NOT selected sequences are displayed.</i><br><br>\n");
+    }
+}
+
+
+function ReplaceInUri($name, $rows, $direction, $totalnumrows=0)
+{
+    //direction:
+    // 0: Prev Link
+    // 1: Next Link
+    // 2: First Link
+    // 3: Last Link
+
+    $uri = htmlspecialchars($_SERVER["REQUEST_URI"]);
+    //append string in case it is not in url
+    if (!preg_match("/&fNumStart[=][0-9]*/", $uri))
+        $uri.="&amp;fNumStart=";
+
+    switch($direction)
+    {
+    case 0:
+        $pos = $_GET["fNumStart"]-$rows;
+        if ($pos<0)
+            $pos=0;
+        $link .= " <A HREF='" . preg_replace("/&amp;fNumStart[=][0-9]*/", "&amp;fNumStart=".$pos, $uri) . "'>< Prev</A> \n";
+        break;
+    case 1:
+        //display link only if more results available
+        if ($_GET["fNumStart"]+$rows==$totalnumrows)
+            break;
+        $pos = $_GET["fNumStart"]+$rows;
+        $link .= " <A HREF='" . preg_replace("/&amp;fNumStart[=][0-9]*/", "&amp;fNumStart=".$pos, $uri) . "'>Next ></A> \n";
+        break;
+    case 2:
+        $pos = 0;
+        $link .= " <A HREF='" . preg_replace("/&amp;fNumStart[=][0-9]*/", "&amp;fNumStart=".$pos, $uri) . "'><< First</A> \n";
+        break;
+    case 3:
+        //display link only if more results available
+        if ($_GET["fNumStart"]+$rows==$totalnumrows)
+            break;
+        $pos = $totalnumrows-$rows+1;
+        $link .= " <A HREF='" . preg_replace("/&amp;fNumStart[=][0-9]*/", "&amp;fNumStart=".$pos, $uri) . "'>Last >></A> \n";
+        break;
+    }
+
+    return $link;
+}
+
+function CreateMenu($rows, $totalnumrows)
+{
+    $menu = "";
+
+    if (empty($_GET["fNumResults"]))
+        return;
+
+    if ($_GET["fNumStart"]!=0)
+    {
+        $menu .= ReplaceInUri("fNumStart", $rows, 2, $totalnumrows);
+        $menu .= ReplaceInUri("fNumStart", $rows, 0, $totalnumrows);
+    }
+
+    $menu .= "&nbsp;&nbsp;&nbsp;---&nbsp;<B>";
+    if (empty($_GET["fNumStart"]))
+        $menu .= "0";
+    else
+        $menu .= $_GET["fNumStart"];
+    $menu .= "</B>&nbsp;---&nbsp;&nbsp;&nbsp;\n";
+
+    if ($rows==$_GET["fNumResults"])
+    {
+        $menu .= ReplaceInUri("fNumStart", $rows, 1, $totalnumrows);
+        $menu .= ReplaceInUri("fNumStart", $rows, 3, $totalnumrows);
+    }
+    return $menu;
+}
+
+function PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $result1, $form="")
+{
+    $row1 = mysql_fetch_assoc($result1);
+    $totalnumrows=$row1["FOUND_ROWS()"];
+
+    $col   = FALSE;
+    $first = TRUE;
+
+    $sigma = array
+        (
+         1    => "#33CC00",
+         2    => "#FFFF66",
+         3    => "#FF9900",
+         5    => "#FF0000",
+        );
+    $okcolour="#006600";
+
+
+    $menu = CreateMenu(mysql_num_rows($result0), $totalnumrows);
+
+    if ($form)
+    {
+        printf("<form method='POST'>");
+        PrintDisplaySequencesButtons();
+    }
+    printf("\n<center>\n");
+    if (empty($_GET["fPrintTable"]))
+        printf("%s\n", $menu);
+
+    printf("<table BORDER='0' style='margin-top:1ex'>\n");
+    $counter=0;
+    while ($row0 = mysql_fetch_assoc($result0))
+    {
+        if ($first)
+        {
+            printf(" <tr BGCOLOR='#C0C0C0'>\n<td BGCOLOR='#F0F0F0'><img src='plus.png' alt='+' onClick='showalllines(%d)'></td>\n", mysql_num_rows($result0));
+            $first = FALSE;
+            if ($form)
+            {
+                printf("<td>ON<br><input type='radio' name='SelectAllSequForDS' value='ON' onclick='selectallsequences(\"ON\");' %s></td>\n",
+                       $_SESSION["SelectAllSequForDS"]=="ON"?"checked":"");
+                printf("<td>Off<br><input type='radio' name='SelectAllSequForDS' value='Off' onclick='selectallsequences(\"Off\");' %s></td>\n",
+                       $_SESSION["SelectAllSequForDS"]=="Off"?"checked":"");
+                printf("<td>Not<br><input type='radio' name='SelectAllSequForDS' value='Not' onclick='selectallsequences(\"Not\");' %s></td>\n",
+                       $_SESSION["SelectAllSequForDS"]=="Not"?"checked":"");
+            }
+            foreach ($row0 as $key => $element)
+            {
+                $col = FindAlias($alias, $key);
+
+                $ord="-";
+                $issort = "";
+                if (!empty($_GET["fSortBy"]) && substr($_GET["fSortBy"], 0, -1)==$col)
+                {
+                    if (substr($_GET["fSortBy"], -1)=="-")
+                    {
+                        $ord="+";
+                        $issort="&nbsp;<IMG SRC='down.gif'>";
+                    }
+                    else
+                        $issort="&nbsp;<IMG SRC='up.gif'>";
+                }
+                printf("  <th>&nbsp;<A HREF='%s&amp;fSortBy=%s%s'>%s</A>%s&nbsp;</th>\n",
+                       htmlspecialchars(RemoveSortBy()), $col, $ord, $key, $issort);
+            }
+            printf(" </tr>\n\n");
+        }
+
+        $counter++;
+        if (!$col)
+            printf(" <tr id='line%s' BGCOLOR='#E0E0E0'>\n<td BGCOLOR='#F0F0F0'>\n<img id='line%sbutton' src='minus.png' alt='-' onClick='showhide(\"line%s\")'>\n</td>\n", $counter, $counter, $counter);
+        else
+            printf(" <tr id='line%s' BGCOLOR='#D0D0D0'>\n<td BGCOLOR='#F0F0F0'>\n<img id='line%sbutton' src='minus.png' alt='-' onClick='showhide(\"line%s\")'>\n</td>\n", $counter, $counter, $counter);
+        $col = !$col;
+
+        if ($form)
+        {
+            RadioButton("DSSeq".$row0["Sequ"],  "ON", "");
+            RadioButton("DSSeq".$row0["Sequ"], "Off", "");
+            RadioButton("DSSeq".$row0["Sequ"], "Not", "");
+        }
+        foreach ($row0 as $key => $element)
+        {
+            if (empty($rightalign[$key]))
+                printf("  <td align='left' valign='top'>");
+            else
+                printf("  <td align='right' valign='top'>");
+
+            $colour='#000000';
+            //determine color of text in cell
+            if (!empty($limitsmean))
+            {
+                foreach($limitsmean as $key2 => $element2)
+                {
+                    $mean=$key2 . "Mean";
+                    $rms2=$key2 . "Rms";
+                    if ($key==$alias[$element2] && !empty($_GET[$mean]) && !empty($_GET[$rms2]))
+                    {
+                        $colour=$okcolour;
+                        foreach ($sigma as $margin => $newcolour)
+                        {
+                            $min=$_GET[$mean] - ($margin * $_GET[$rms2]);
+                            $max=$_GET[$mean] + ($margin * $_GET[$rms2]);
+                            if (!($min < $element && $element < $max))
+                                $colour=$newcolour;
+                        }
+                    }
+                }
+            }
+            if (!empty($limitsmin))
+            {
+                foreach($limitsmin as $key2 => $element2)
+                {
+                    $limit1=$key2 . "1";
+                    $limit2=$key2 . "2";
+                    if ($key==$alias[$element2] && !empty($_GET[$limit1]))
+                    {
+                        if ($colour=='#000000')
+                            $colour=$okcolour;
+
+                        if (!empty($_GET[$limit2]) && $_GET[$limit2] > $element)
+                                $colour=$sigma[5];
+
+                        if ($_GET[$limit1] > $element && $_GET[$limit2] <= $element)
+                            $colour=$sigma[3];
+                    }
+                }
+            }
+
+            if (!empty($limitsmax))
+            {
+                foreach($limitsmax as $key2 => $element2)
+                {
+                    $limit1=$key2 . "1";
+                    $limit2=$key2 . "2";
+                    if ($key==$alias[$element2] && !empty($_GET[$limit1]))
+                    {
+                        if ($colour=='#000000')
+                            $colour=$okcolour;
+
+                        if (!empty($_GET[$limit2]) && $_GET[$limit2] < $element)
+                                $colour=$sigma[5];
+
+                        if ($_GET[$limit1] < $element && $_GET[$limit2] >= $element)
+                            $colour=$sigma[3];
+                    }
+                }
+            }
+            if ($colour!='#000000' && (!empty($limitsmean) || !empty($limitsmin) || !empty($limitsmax)))
+                printf("<font color='%s' style='font-weight:bold'>", $colour);
+
+            //fill text in cell
+            printf("&nbsp;%s&nbsp;</td>\n", str_replace("&ws;", " ", str_replace(" ", "&nbsp;", $element)));
+
+            if ($colour!='#000000' && (!empty($limitsmean) || !empty($limitsmin) || !empty($limitsmax)))
+                printf("</font>");
+        }
+        printf(" </tr>\n");
+    }
+    printf("</table>\n");
+
+    /*
+     $info = mysql_info();
+     if (!empty($info))
+     printf("%s<BR>\n", $info);
+     */
+
+    printf("<P><B>Number of displayed results: %d of %s in total</B><P><P>\n", mysql_num_rows($result0), $totalnumrows);
+    if (empty($_GET["fPrintTable"]))
+        printf("%s\n", $menu);
+    printf("<P>\n");
+    printf("</center>\n");
+
+    if (!$form)
+    {
+        printf("</td>\n");
+        printf("</tr>\n");
+    }
+    else
+        PrintDisplaySequencesButtons();
+}
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/index-footer.html
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/index-footer.html	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/index-footer.html	(revision 17960)
@@ -0,0 +1,21 @@
+
+</table>
+
+<hr NOSHADE WIDTH="80%">
+<i><font color="#000099" size=-1>
+This Web Site is <!--hosted by Apache for OS/2 and--> done by 
+<a href="mailto:tbretz@astro.uni-wuerzburg.de">Thomas&nbsp;Bretz</a>
+and
+<a href="mailto:daniela.dorner@unige.ch">Daniela&nbsp;Dorner</a>.
+</font></i>
+<BR>&nbsp;<BR>
+<a href="http://validator.w3.org/check/referer">
+<img border="0"src="valid-html40.png" alt="Valid HTML 4.0!" height="20" width="66"></a>
+<BR>&nbsp;
+</center>
+</td>
+</tr>
+</table></center>
+
+</body>
+</html>
Index: branches/Mars_McMismatchStudy/datacenter/db/index-header.html
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/index-header.html	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/index-header.html	(revision 17960)
@@ -0,0 +1,58 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+   <meta name="Author" content="Thomas Bretz">
+   <title>Magic Database</title>
+   <link rel="stylesheet" type="text/css" href="mars.css">
+   <style type="text/css">
+    <!--
+       select.Width
+         { width: 150px; }
+       input.Width 
+         { width: 102px; }
+     -->
+   </style>
+<script type="text/javascript" src="menu.js"></script>
+</head>
+
+<body onload="getdisplay();" background="background.gif" text="#000000" bgcolor="#000099" link="#1122FF" vlink="#8888FF" alink="#FF0000">
+&nbsp;
+
+<center><table class="Main" CELLPADDING="0">
+
+<tr>
+<td class="Edge"><img SRC="ecke.gif" ALT=""></td>
+<td class="Header">
+<font size='+1'><B>Magic Database</B></font><BR>
+<hr SIZE=1 NOSHADE WIDTH="80%">
+<A HREF="http://www.astro.uni-wuerzburg.de/wiki/Database_Websites">Home</A>&nbsp;
+<A HREF="http://www.astro.uni-wuerzburg.de/wiki/Database_Tutorial">Help</A>&nbsp;
+<A HREF="printtable.php?fTable=MarsVersion">Mars</A>&nbsp;
+<A HREF="plotdb.php">Plots</A>
+Info:&nbsp;
+<A HREF="runinfo-aio.php">Run</A>&nbsp;
+<A HREF="sequinfo-aio.php">Sequ</A>&nbsp;
+<A HREF="datasetinfo-aio.php">DataSets</A>&nbsp;
+<A HREF="queryrbk.php">Runbook</A>&nbsp;
+<BR>
+more:&nbsp;
+<!--
+<A HREF="ganymed.php">Results</A>&nbsp;
+<A HREF="sequence.php">Sequ</A>&nbsp;
+-->
+<A HREF="sources.php">Sources</A>&nbsp;
+<A HREF="statussbs.php">SequBuildStatus</A>&nbsp;
+<A HREF="builddatasets.php">BuildDataSets</A>
+<hr SIZE=1 NOSHADE WIDTH="80%">
+</td>
+</tr>
+
+<tr>
+<td COLSPAN="2" BGCOLOR="#FFFFFF">
+
+
+<center><table class="Inner" CELLPADDING=15>
+<tr  class="Block">
+<td>
Index: branches/Mars_McMismatchStudy/datacenter/db/magicdefs.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/magicdefs.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/magicdefs.php	(revision 17960)
@@ -0,0 +1,776 @@
+<?php
+
+$needs = array
+    (
+     "fCCFilled"             => "SequenceBuildStatus.fDate",
+     "fExclusionsDone"       => "fCCFilled",
+     "fSequenceEntriesBuilt" => "fExclusionsDone",
+     "fCCFileAvail"          => "RunProcessStatus.fRunNumber",
+     "fCaCoFileAvail"        => "RunProcessStatus.fRunNumber",
+     "fCaCoFileFound"        => "RunProcessStatus.fRunNumber",
+     "fRawFileAvail"         => "RunProcessStatus.fRunNumber",
+     "fDataCheckDone"        => "fRawFileAvail",
+     "fTimingCorrection"     => "fRawFileAvail",
+     "fSequenceFileWritten"  => "SequenceProcessStatus.fSequenceFirst",
+     "fAllFilesAvail"        => "fSequenceFileWritten",
+     "fCallisto"             => "fAllFilesAvail",
+     "fStar"                 => "fCallisto",
+     "fFillCallisto"         => "fCallisto",
+     "fFillStar"             => "fStar",
+     "fDataSetInserted"      => "DataSetProcessStatus.fDataSetNumber",
+     "fDataSetFileWritten"   => "fDataSetInserted",
+     "fStarFilesAvail"       => "fDataSetFileWritten",
+     "fGanymed"              => "fStarFilesAvail",
+     "fFillGanymed"          => "fGanymed",
+     );
+
+
+$timelimits = array();
+
+
+$limitsmean = array
+    (
+     "fPedRmsInLimit"    => "fMeanPedRmsInner",
+//     "fArrTRmsLimit"     => "fArrTimeRmsInner",
+     "fMuonRateLimit"    => "fMuonRate",
+     "fMuonCalLimit"     => "fRatio",
+     "fPSFLimit"         => "fPSF",
+     "fInhomLimit"       => "fInhomogeneity",
+     "fNumIslLimit"      => "fMeanNumberIslands",
+     "fImgRateLimit"     => "fDataRate",
+     "fSkyBrightLimit"   => "fBrightnessMed",
+    );
+
+$limitsmin = array
+    (
+     "fZdMinLimit"       => "fZenithDistanceMin",
+     "fNumStarsLimit"    => "fNumStarsMed",
+     "fNumStarsCorLimit" => "fNumStarsCorMed",
+     "fMuonNumLimit"     => "fMuonNumber",
+//     "fArrTimeLimit"     => "fArrTimeInner",
+     "fPulsePosLimit"    => "fMeanPulsePosInner",
+     "fRunTimeLimit"     => "fRunTime/60",
+     "fRelTimeMinLimit"  => "fEffOnTime/fRunTime",
+    );
+
+$limitsmax = array
+    (
+     "fZdMaxLimit"       => "fZenithDistanceMax",
+     "fUnsInLimit"       => "fUnsuitableInner",
+     "fIsoInLimit"       => "fIsolatedInner",
+     "fIMCLimit"         => "fIsolatedMaxCluster",
+     "fMaxHumLimit"      => "fMaxHumidity",
+     "fRelTimeMaxLimit"  => "fEffOnTime/fRunTime",
+     "fCloudinessLimit"  => "fAvgCloudiness",
+    );
+
+$checkwhere = array
+    (
+     "fRunTypeName"                      => CheckWhere("fRunTypeKEY"),
+     "fProjectName"                      => CheckWhere("fProjectKEY"),
+     "fSourceName"                       => CheckWhere("fSourceKEY"),
+     "fMagicNumberName"                  => CheckWhere("fMagicNumberKEY"),
+     "fL1TriggerTableName"               => CheckWhere("fL1TriggerTableKEY"),
+     "fL2TriggerTableName"               => CheckWhere("fL2TriggerTableKEY"),
+     "fL3TriggerTableName"               => CheckWhere("fL3TriggerTableKEY"),
+     "fHvSettingsName"                   => CheckWhere("fHvSettingsKEY"),
+     "fCalibrationScriptName"            => CheckWhere("fCalibrationScriptKEY"),
+     "fExcludedFDAName"                  => CheckWhere("fExcludedFDAKEY"),
+     "fManuallyChangedName"              => CheckWhere("fManuallyChangedKEY"),
+     "fObservationModeName"              => CheckWhere("fObservationModeKEY"),
+     "fSumTriggerFlagName"               => CheckWhere("fSumTriggerFlagKEY"),
+     "fDiscriminatorThresholdTableName"  => CheckWhere("fDiscriminatorThresholdTableKEY"),
+     "fTriggerDelayTableName"            => CheckWhere("fTriggerDelayTableKEY"),
+     "fTestFlagName"                     => CheckWhere("fTestFlagKEY"),
+     "fLightConditionsName"              => CheckWhere("fLightConditionsKEY"),
+     "fParticleTypeName"                 => CheckWhere("fParticleTypeKEY"),
+     "fFitsFileName"                     => CheckWhere("fFitsFileKEY"),
+     "fObjectName"                       => CheckWhere("fObjectKEY"),
+     "fStatusName"                       => CheckWhere("fStatusKEY"),
+     "fTelescopeName"                    => CheckWhere("fTelescopeKEY"),
+     "fBandName"                         => CheckWhere("fBandKEY"),
+     "fUserName"                         => CheckWhere("fUserKEY"),
+     "fCycleName"                        => CheckWhere("fCycleKEY"),
+     "fPIName"                           => CheckWhere("fPIKEY"),
+     "fWorkingGroupName"                 => CheckWhere("fWorkingGroupKEY"),
+     "fProposalName"                     => CheckWhere("fProposalKEY"),
+    );
+
+$checkgroup = array
+    (
+     "fRunTypeName"                      => CheckGroup("fRunTypeKEY"),
+     "fProjectName"                      => CheckGroup("fProjectKEY"),
+     "fSourceName"                       => CheckGroup("fSourceKEY"),
+     "fMagicNumberName"                  => CheckGroup("fMagicNumberKEY"),
+     "fL1TriggerTableName"               => CheckGroup("fL1TriggerTableKEY"),
+     "fL2TriggerTableName"               => CheckGroup("fL2TriggerTableKEY"),
+     "fL3TriggerTableName"               => CheckGroup("fL3TriggerTableKEY"),
+     "fHvSettingsName"                   => CheckGroup("fHvSettingsKEY"),
+     "fCalibrationScriptName"            => CheckGroup("fCalibrationScriptKEY"),
+     "fExcludedFDAName"                  => CheckGroup("fExcludedFDAKEY"),
+     "fManuallyChangedName"              => CheckGroup("fManuallyChangedKEY"),
+     "fObservationModeName"              => CheckGroup("fObservationModeKEY"),
+     "fSumTriggerFlagName"               => CheckGroup("fSumTriggerFlagKEY"),
+     "fDiscriminatorThresholdTableName"  => CheckGroup("fDiscriminatorThresholdTableKEY"),
+     "fTriggerDelayTableName"            => CheckGroup("fTriggerDelayTableKEY"),
+     "fTestFlagName"                     => CheckGroup("fTestFlagKEY"),
+     "fLightConditionsName"              => CheckGroup("fLightConditionsKEY"),
+     "fParticleTypeName"                 => CheckGroup("fParticleTypeKEY"),
+     "fFitsFileName"                     => CheckGroup("fFitsFileKEY"),
+     "fObjectName"                       => CheckGroup("fObjectKEY"),
+     "fStatusName"                       => CheckGroup("fStatusKEY"),
+     "fBandName"                         => CheckGroup("fBandKEY"),
+     "fUserName"                         => CheckGroup("fUserKEY"),
+     "fTelescopeName"                    => CheckGroup("fTelescopeKEY"),
+     "fCycleName"                        => CheckWhere("fCycleKEY"),
+     "fPIName"                           => CheckWhere("fPIKEY"),
+     "fWorkingGroupName"                 => CheckWhere("fWorkingGroupKEY"),
+     "fProposalName"                     => CheckWhere("fProposalKEY"),
+    );
+
+
+$checkstatusgroup = array
+    (
+     "fCCFilled"                         => CheckStatusGroup("fCCFilledStatus"),
+     "fExclusionsDone"                   => CheckStatusGroup("fExclusionsDoneStatus"),
+     "fSequenceEntriesBuilt"             => CheckStatusGroup("fSequenceEntriesBuiltStatus"),
+     "fCCFileAvail"                      => CheckStatusGroup("fCCFileAvailStatus"),
+     "fCaCoFileAvail"                    => CheckStatusGroup("fCaCoFileAvailStatus"),
+     "fCaCoFileFound"                    => CheckStatusGroup("fCaCoFileFoundStatus"),
+     "fRawFileAvail"                     => CheckStatusGroup("fRawFileAvailStatus"),
+     "fTimingCorrection"                 => CheckStatusGroup("fTimingCorrectionStatus"),
+     "fDataCheckDone"                    => CheckStatusGroup("fDataCheckDoneStatus"),
+//     "fFillDotRaw"                       => CheckStatusGroup("fFillDotRawStatus"),
+     "fSequenceFileWritten"              => CheckStatusGroup("fSequenceFileWrittenStatus"),
+     "fAllFilesAvail"                    => CheckStatusGroup("fAllFilesAvailStatus"),
+     "fCallisto"                         => CheckStatusGroup("fCallistoStatus"),
+     "fFillCallisto"                     => CheckStatusGroup("fFillCallistoStatus"),
+     "fStar"                             => CheckStatusGroup("fStarStatus"),
+     "fFillStar"                         => CheckStatusGroup("fFillStarStatus"),
+     "fDataSetInserted"                  => CheckStatusGroup("fDataSetInsertedStatus"),
+     "fDataSetFileWritten"               => CheckStatusGroup("fDataSetFileWrittenStatus"),
+     "fStarFilesAvail"                   => CheckStatusGroup("fStarFilesAvailStatus"),
+     "fGanymed"                          => CheckStatusGroup("fGanymedStatus"),
+     "fFillGanymed"                      => CheckStatusGroup("fFillGanymedStatus"),
+    );
+
+
+$checkenumgroup = array
+    (
+     "fHasSignal"              => CheckEnumGroup("fHasSignalEnum"),
+     "fHasPedestal"            => CheckEnumGroup("fHasPedestalEnum"),
+     "fHasSignalInterlaced"    => CheckEnumGroup("fHasSignalInterlacedEnum"),
+     "fHasPedestalInterlaced"  => CheckEnumGroup("fHasPedestalInterlacedEnum"),
+    );
+
+
+
+$alias = array
+    (
+     "fRawFileKEY"                      => "Idx",
+     "fMagicNumberName"                 => "Magic#",
+     "fFormatVersion"                   => "F-Ver",
+     "fLastUpdate"                      => "LastUpd",
+//     "fRunNumber"                       => "Run#",
+     "Run#"                       => "Run#",
+     "Tel:Run:File"                       => "Tel:Run:File",
+     "fRunTypeName"                     => "RunType",
+     "fMeanTriggerRate"                 => "Rate<br>[Hz]",
+     "fDaqTriggerRate"                  => "Daq<br>TRate<br>[Hz]",
+     "fDaqStoreRate"                    => "Daq<br>SRate<br>[Hz]",
+     "fL2RatePresc"                     => "L2<br>pRate<br>[Hz]",
+     "fL3TriggerRate"                   => "L3<br>TRate<br>[Hz]",
+     "fL2RateUnpresc"                   => "L2<br>upRate<br>[Hz]",
+     "fManuallyChangedName"             => "Manually<br>Changed",
+     "fObservationModeName"             => "Obs.<br>Mode",
+     "fSumTriggerFlagName"              => "SumTrigger<br>Flag",
+     "fLastUpdate"                      => "LastUpd",
+     "fSequenceFirst"                   => "Sequ",
+     "fProjectName"                     => "Project",
+     "fSourceName"                      => "Source",
+     "fNumEvents"                       => "#Evts",
+     "fRunTime/60"                      => "Up<br>Time<br>[min]",
+     "fRunStart"                        => "Start",
+     "fRunStop"                         => "Stop",
+//     "fRunStart"                        => "StartTime",
+     "fSequenceLast"                    => "Last<br>Run",
+     "fL1TriggerTableName"              => "L1Trig<br>Table",
+     "fL2TriggerTableName"              => "L2Trig<br>Table",
+     "fL3TriggerTableName"              => "L3Trig<br>Table",
+     "fHvSettingsName"                  => "HV Settings",
+     "fCalibrationScriptName"           => "Cal Script",
+     "fTestFlagName"                    => "Testflag",
+     "fLightConditionsName"             => "Lightcond",
+     "fTriggerDelayTableName"           => "TrigDelay",
+     "fDiscriminatorThresholdTableName" => "DT",
+     "fExcludedFDAName"                 => "Exclusion",
+     "fCycleName"                       => "Cycle",
+     "fPIName"                          => "PI name",
+     "fWorkingGroupName"                => "Working<br>Group",
+     "fProposalName"                    => "Proposal",
+     "fWheelPos1"                       => "Wheel<br>Pos 1",
+     "fWheelPos2"                       => "Wheel<br>Pos 2",
+     "fZenithDistance"                  => "Zd",
+     "fAzimuth"                         => "Az",
+     "fZenithDistanceMin"               => "Zd<br>Min",
+     "fZenithDistanceMax"               => "Zd<br>Max",
+     "fAzimuthMin"                      => "Az<br>Min",
+     "fAzimuthMax"                      => "Az<br>Max",
+     "fTest"                            => "Test",
+     "fSourceKEY"                       => "KEY",
+     "fDate"                            => "Date",
+     "fCCFilled"                        => "CCFilled",
+     "fExclusionsDone"                  => "Exclusions",
+     "fSequenceEntriesBuilt"            => "Sequences",
+     "fCCFileAvail"                     => "CCFile",
+     "fCaCoFileAvail"                   => "CaCoFile",
+     "fCaCoFileFound"                   => "CaCoRun",
+     "fRawFileAvail"                    => "RawFile",
+     "fTimingCorrection"                => "TimingCorr",
+     "fDataCheckDone"                   => "Datacheck",
+//     "fFillDotRaw"                      => "Filldotraw",
+     "fSequenceFileWritten"             => "SequFile",
+     "fAllFilesAvail"                   => "FilesAvail",
+     "fCallisto"                        => "Callisto",
+     "fStar"                            => "Star",
+     "fFillCallisto"                    => "FillCal",
+     "fFillStar"                        => "FillStar",
+     "fDataSetInserted"                 => "DataSet",
+     "fDataSetFileWritten"              => "DataSetFile",
+     "fStarFilesAvail"                  => "FilesAvail",
+     "fGanymed"                         => "Ganymed",
+     "fFillGanymed"                     => "FillGanymed",
+     "fUnsuitableOuter"                 => "Un<br>suit.<br>Out",
+     "fUnreliableOuter"                 => "Un<br>rel.<br>Out",
+     "fUnreliableInner"                 => "Un<br>rel.<br>In",
+     "fUnsuitableInner"                 => "Un<br>suit.<br>In",
+     "fUnsuitable50"                    => "Un<br>suit.<br>50",
+     "fUnsuitable01"                    => "Un<br>suit.<br>01",
+     "fUnsuitableMax"                   => "Un<br>suit.<br>Max",
+     "fDeadMax"                         => "Dead<br>Max",
+     "fRateTrigEvts"                    => "Rate Trig.<br>Evts [Hz]",
+     "fRateSumEvts"                     => "Rate Sum<br>Evts [Hz]",
+     "fRatePedEvts"                     => "Rate Ped<br>Evts [Hz]",
+     "fRatePedTrigEvts"                 => "Rate Ped.Trig.<br>Evts [Hz]",
+     "fRateCalEvts"                     => "Rate Cal.<br>Evts [Hz]",
+     "fRateNullEvts"                    => "Rate Null<br>Evts [Hz]",
+     "fRateUnknownEvts"                 => "Rate Unknown<br>Evts [Hz]",
+     "fRatioCalEvents"                  => "Ratio Cal.<br>Events",
+     "fPulsePosCalib"                   => "Pulse Pos.<br>Calib",
+     "fIsolatedOuter"                   => "Isol.<br>Out",
+     "fIsolatedInner"                   => "Isol.<br>In",
+     "fMeanPedRmsOuter"                 => "Ped<br>Rms<br>Out",
+     "fMeanPedRmsInner"                 => "Ped<br>Rms<br>In",
+     "fArrTimeMeanInner"                => "Arr<br>Time<br>In",
+     "fArrTimeMeanOuter"                => "Arr<br>Time<br>Out",
+     "fArrTimeRmsInner"                 => "Rms<br>ArrT<br>In",
+     "fArrTimeRmsOuter"                 => "Rms<br>ArrT<br>Out",
+     "fMeanSignalInner"                 => "Sign<br>In",
+     "fMeanSignalOuter"                 => "Sign<br>Out",
+     "fMeanPulsePosInner"               => "Pulse<br>PosIn",
+     "fPulsePosMean"                    => "Puls<br>Pos",
+     "fConvFactorInner"                 => "Conv<br>In",
+     "fConvFactorOuter"                 => "Conv<br>Out",
+     //             "fConvFactorInner"                 => "Conv Inner<BR>[ph/FADC]",
+     //             "fConvFactorOuter"                 => "Conv Outer<BR>[ph/FADC]",
+     "fIsolatedMaxCluster"              => "Isol.<br>Max<br>Cl",
+     "fMeanNumberIslands"               => "Mean<br>Num<br>Isl",
+     "fPSF"                             => "PSF<br>[mm]",
+     "fRatio"                           => "Ratio<br>[%]",
+     "fMuonNumber"                      => "#<br>Muons",
+     "fEffOnTime"                       => "EffOn<br>Time<br>[s]",
+     "fEffOnTime/fRunTime"              => "RelOn<br>Time",
+     "fEffOnTime/3600"                  => "EffOn<br>Time<br>[h]",
+     "fMuonRate"                        => "Muon<br>Rate<br>[Hz]",
+     "fInhomogeneity"                   => "Inhom",
+     "fDataRate"                        => "Img.<br>Rate<br>[Hz]",
+     "fSparkRate"                       => "Spark<br>Rate<br>[Hz]",
+     "fMaxHumidity"                     => "Max<br>Hum<br>[%]",
+     "fBrightnessMed"                   => "Sky<br>Brightn.<br>Med",
+     "fBrightnessRMS"                   => "Sky<br>Brightn.<br>RMS",
+     "fNumStarsMed"                     => "#<br>id.<br>stars",
+     "fNumStarsRMS"                     => "RMS<br>id.<br>stars",
+     "fNumStarsCorMed"                  => "#<br>cor.<br>stars",
+     "fNumStarsCorRMS"                  => "RMS<br>cor.<br>stars",
+     "fAvgWindSpeed"                    => "Avg. wind<br>speed [m/s]",
+     "fAvgTemperature"                  => "Avg. temp.<br>[deg]",
+     "fAvgHumidity"                     => "Avg. hum.<br>[%]",
+     "fAvgTempSky"                      => "Avg. sky<br>temp [deg]",
+     "fAvgCloudiness"                   => "Avg. cloud.<br>[%]",
+     "fRmsCloudiness"                   => "RMS cloud.<br>[%]",
+     "fEvents"                          => "DataEvents",
+     "fPositionSignal"                  => "ArrTime",
+     "fPositionFWHM"                    => "ArrTimeFWHM",
+     "fHeightSignal"                    => "Signal",
+     "fHeightFWHM"                      => "SignalFWHM",
+     "fHasSignal"                       => "HasSignal",
+     "fHasPedestal"                     => "HasPedestal",
+     "fPositionAsym"                    => "ArrTimeAsym",
+     "fHeightAsym"                      => "SignalAsym",
+     "fEventsInterlaced"                => "CalEvents",
+     "fPositionSignalInterlaced"        => "ArrTimeCal",
+     "fPositionFWHMInterlaced"          => "ArrTimeFWHMCal",
+     "fHeightSignalInterlaced"          => "SignalCal",
+     "fHeightFWHMInterlaced"            => "SignalFWHMCal",
+     "fHasSignalInterlaced"             => "HasSignalCal",
+     "fHasPedestalInterlaced"           => "HasPedestalCal",
+     "fPositionAsymInterlaced"          => "ArrTimeAsymCal",
+     "fHeightAsymInterlaced"            => "SignalAsymCal",
+     "fExcessEvents"                    => "Exc<br>Evts",
+     "fBackgroundEvents"                => "Bg<br>Evts",
+     "fSignalEvents"                    => "Sign<br>Evts",
+     "fSignificance"                    => "Sign",
+     "fScaleFactor"                     => "Scale",
+     "fDataSetNumber"                   => "Data<br>Set#",
+     "fComment"                         => "Comment",
+     "fUserName"                        => "User",
+     "fRunTime"                         => "Up<br>Time<br>[min]",
+     "fDataSetName"                     => "Name",
+     "fExcessEvents*60/fEffOnTime"      => "Exc<br>Rate",
+     "fBackgroundEvents*60/fEffOnTime"  => "Bg<br>Rate",
+     "fSignalEvents*60/fEffOnTime"      => "Sign<br>Rate",
+     "Round(fSignificance/Sqrt(fEffOnTime/3600),2)" => "Signf<br>Rate",
+     "SUM(fRunTime)/3600"               => "Time [h]",
+     "SUM(fNumEvents)"                  => "Evts",
+     "Min(fZenithDistanceMin)"          => "ZDMin",
+     "Max(fZenithDistanceMax)"          => "ZDMax",
+     "Min(fZenithDistance)"             => "ZdMin",
+     "Max(fZenithDistance)"             => "ZdMax",
+//     "fArrTimeLimit"                    => "ArrTRms",
+//     "fArrTimeLimit"                    => "ArrTime",
+     "fPulsePosLimit"                   => "PulsePos",
+     "fRunTimeLimit"                    => "UpTime",
+     "fPedRmsInLimit"                   => "PedRms",
+     "fMuonRateLimit"                   => "MuonRate",
+     "fMuonNumLimit"                    => "# Muons",
+     "fMuonCalLimit"                    => "MuonCal",
+     "fPSFLimit"                        => "PSF",
+     "fInhomLimit"                      => "Inhom.",
+     "fNumIslLimit"                     => "# Islands",
+     "fImgRateLimit"                    => "ImgRate",
+     "fSkyBrightLimit"                  => "SkyBrightness",
+     "fNumStarsLimit"                   => "# id. Stars",
+     "fNumStarsCorLimit"                => "# cor. Stars",
+     "fUnsInLimit"                      => "Unsuit.In",
+     "fIsoInLimit"                      => "Isol.In",
+     "fIMCLimit"                        => "IMC",
+     "fMaxHumLimit"                     => "Humidity",
+     "fCloudinessLimit"                 => "Cloudiness",
+     "fZdMinLimit"                      => "ZdMin",
+     "fZdMaxLimit"                      => "ZdMax",
+     "fRelTimeMaxLimit"                 => "Rel.Ontime",
+     "fRelTimeMinLimit"                 => "Rel.Ontime",
+     "fEMin"                            => "Emin",
+     "fEMax"                            => "Emax",
+     "fParticleTypeName"                => "Particle",
+     "fStartTime"                       => "Process",
+     "fFailedTime"                      => "Failed",
+     "fReturnCode"                      => "Ret<br>Code",
+     "fProgramId"                       => "Prgr<br>Id",
+     "fTimestamp"                       => "Time",
+     "fExposure"                        => "Exposure",
+     "fFitsFileName"                    => "FitsFile",
+     "fObjectName"                      => "Object",
+     "fSkyLevel"                        => "SkyLevel",
+     "fFWHM"                            => "FWHM",
+     "fApertureRadius"                  => "Ap.Rad.",
+     "fInstrumentalMag"                 => "Instr.Mag.",
+     "fInstrumentalMagErr"              => "Instr.Mag.Err.",
+     "fStatusName"                      => "StatusCode",
+     "fTelescopeName"                   => "Telescope",
+     "fBandName"                        => "Band",
+//     "COUNT(*)"                         => "# Runs",
+//     "COUNT(*)"                         => "Sequence",
+    );
+
+
+$rightalign = array
+    (
+     $alias["fRawFileKEY"]               => "1",
+     $alias["fFormatVersion"]            => "1",
+//     $alias["fRunNumber"]                => "1",
+     $alias["fZenithDistance"]           => "1",
+     $alias["fAzimuth"]                  => "1",
+     $alias["fMeanTriggerRate"]          => "1",
+     $alias["fDaqTriggerRate"]           => "1",
+     $alias["fDaqStoreRate"]             => "1",
+     $alias["fL2RatePresc"]              => "1",
+     $alias["fL3TriggerRate"]            => "1",
+     $alias["fL2RateUnpresc"]            => "1",
+     $alias["fSequenceFirst"]            => "1",
+     $alias["fNumEvents"]                => "1",
+     $alias["fRunTime/60"]               => "1",
+     $alias["fSequenceLast"]             => "1",
+     $alias["fZenithDistanceMin"]        => "1",
+     $alias["fZenithDistanceMax"]        => "1",
+     $alias["fWheelPos1"]                => "1",
+     $alias["fWheelPos2"]                => "1",
+     $alias["fAzimuthMin"]               => "1",
+     $alias["fAzimuthMax"]               => "1",
+     $alias["fUnsuitableOuter"]          => "1",
+     $alias["fUnreliableOuter"]          => "1",
+     $alias["fUnsuitableInner"]          => "1",
+     $alias["fUnreliableInner"]          => "1",
+     $alias["fUnsuitable50"]             => "1",
+     $alias["fUnsuitable01"]             => "1",
+     $alias["fUnsuitableMax"]            => "1",
+     $alias["fDeadMax"]                  => "1",
+     $alias["fRateTrigEvts"]             => "1",
+     $alias["fRateSumEvts"]              => "1",
+     $alias["fRatePedEvts"]              => "1",
+     $alias["fRatePedTrigEvts"]          => "1",
+     $alias["fRateCalEvts"]              => "1",
+     $alias["fRateNullEvts"]             => "1",
+     $alias["fRateUnknownEvts"]          => "1",
+     $alias["fRatioCalEvents"]           => "1",
+     $alias["fPulsePosCalib"]            => "1",
+     $alias["fIsolatedOuter"]            => "1",
+     $alias["fIsolatedInner"]            => "1",
+     $alias["fMeanPedRmsOuter"]          => "1",
+     $alias["fMeanPedRmsInner"]          => "1",
+     $alias["fArrTimeMeanInner"]         => "1",
+     $alias["fArrTimeMeanOuter"]         => "1",
+     $alias["fArrTimeRmsInner"]          => "1",
+     $alias["fArrTimeRmsOuter"]          => "1",
+     $alias["fMeanSignalInner"]          => "1",
+     $alias["fMeanSignalOuter"]          => "1",
+     $alias["fPulsePosMean"]             => "1",
+     $alias["fConvFactorInner"]          => "1",
+     $alias["fConvFactorOuter"]          => "1",
+     $alias["fIsolatedMaxCluster"]       => "1",
+     $alias["fMeanNumberIslands"]        => "1",
+     $alias["fPSF"]                      => "1",
+     $alias["fRatio"]                    => "1",
+     $alias["fMuonNumber"]               => "1",
+     $alias["fEffOnTime"]                => "1",
+     $alias["fEffOnTime/fRunTime"]       => "1",
+     $alias["fEffOnTime/3600"]           => "1",
+     $alias["fMuonRate"]                 => "1",
+     $alias["fInhomogeneity"]            => "1",
+     $alias["fDataRate"]                 => "1",
+     $alias["fSparkRate"]                => "1",
+     $alias["fMaxHumidity"]              => "1",
+     $alias["fBrightnessMed"]            => "1",
+     $alias["fBrightnessRMS"]            => "1",
+     $alias["fNumStarsMed"]              => "1",
+     $alias["fNumStarsRMS"]              => "1",
+     $alias["fNumStarsCorMed"]           => "1",
+     $alias["fNumStarsCorRMS"]           => "1",
+     $alias["fAvgWindSpeed"]             => "1",
+     $alias["fAvgTemperature"]           => "1",
+     $alias["fAvgHumidity"]              => "1",
+     $alias["fAvgTempSky"]               => "1",
+     $alias["fAvgCloudiness"]            => "1",
+     $alias["fRmsCloudiness"]            => "1",
+     $alias["fDate"]                     => "1",
+     $alias["fCaCoFileFound"]            => "1",
+     $alias["fTest"]                     => "1",
+     $alias["fSourceKEY"]                => "1",
+     $alias["fEvents"]                   => "1",
+     $alias["fPositionSignal"]           => "1",
+     $alias["fPositionFWHM"]             => "1",
+     $alias["fHeightSignal"]             => "1",
+     $alias["fHeightFWHM"]               => "1",
+     $alias["fHasSignal"]                => "1",
+     $alias["fHasPedestal"]              => "1",
+     $alias["fPositionAsym"]             => "1",
+     $alias["fHeightAsym"]               => "1",
+     $alias["fEventsInterlaced"]         => "1",
+     $alias["fPositionSignalInterlaced"] => "1",
+     $alias["fPositionFWHMInterlaced"]   => "1",
+     $alias["fHeightSignalInterlaced"]   => "1",
+     $alias["fHeightFWHMInterlaced"]     => "1",
+     $alias["fHasSignalInterlaced"]      => "1",
+     $alias["fHasPedestalInterlaced"]    => "1",
+     $alias["fPositionAsymInterlaced"]   => "1",
+     $alias["fHeightAsymInterlaced"]     => "1",
+     $alias["fReturnCode"]               => "1",
+     $alias["fProgramId"]                => "1",
+     "Time"                              => "1",
+//     "Time [h]"                 => "1",
+     "ZDMin"                             => "1",
+     "ZDMax"                             => "1",
+//     "Evts#"                    => "1",
+//     "Runs#"                    => "1"
+     "Runs"                              => "1",
+     "Evts"                              => "1",
+);
+
+function GetCheck($fromtable, $val)
+{
+    $checks = array
+        (
+         "fRunTypeName"                      => $fromtable . ".fRunTypeKEY",
+         "fProjectName"                      => $fromtable . ".fProjectKEY",
+         "fSourceName"                       => $fromtable . ".fSourceKEY",
+         "fMagicNumberName"                  => $fromtable . ".fMagicNumberKEY",
+         "fL1TriggerTableName"               => $fromtable . ".fL1TriggerTableKEY",
+         "fL2TriggerTableName"               => $fromtable . ".fL2TriggerTableKEY",
+         "fL3TriggerTableName"               => $fromtable . ".fL3TriggerTableKEY",
+         "fHvSettingsName"                   => $fromtable . ".fHvSettingsKEY",
+         "fCalibrationScriptName"            => $fromtable . ".fCalibrationScriptKEY",
+         "fExcludedFDAName"                  => $fromtable . ".fExcludedFDAKEY",
+         "fManuallyChangedName"              => $fromtable . ".fManuallyChangedKEY",
+         "fObservationModeName"              => $fromtable . ".fObservationModeKEY",
+         "fSumTriggerFlagName"               => $fromtable . ".fSumTriggerFlagKEY",
+         "fDiscriminatorThresholdTableName"  => $fromtable . ".fDiscriminatorThresholdTableKEY",
+         "fTriggerDelayTableName"            => $fromtable . ".fTriggerDelayTableKEY",
+         "fTestFlagName"                     => $fromtable . ".fTestFlagKEY",
+         "fLightConditionsName"              => $fromtable . ".fLightConditionsKEY",
+         "fParticleTypeName"                 => $fromtable . ".fParticleTypeKEY",
+         "fFitsFileName"                     => $fromtable . ".fFitsFileKEY",
+         "fObjectName"                       => $fromtable . ".fObjectKEY",
+         "fStatusName"                       => $fromtable . ".fStatusKEY",
+         "fBandName"                         => $fromtable . ".fBandKEY",
+         "fUserName"                         => $fromtable . ".fUserKEY",
+         "fTelescopeName"                    => $fromtable . ".fTelescopeKEY",
+         "fCycleName"                        => $fromtable . ".fCycleKEY",
+         "fPIName"                           => $fromtable . ".fPIKEY",
+         "fWorkingGroupName"                 => $fromtable . ".fWorkingGroupKEY",
+         "fProposalName"                     => $fromtable . ".fProposalKEY",
+        );
+
+    $check="";
+    if (!empty($checks[$val]))
+        $check=$checks[$val];
+    return $check;
+}
+
+
+function GetTable($fromtable, $val)
+{
+    $tables = array
+        (
+         "fSequenceFirst"                    => $fromtable . ".fSequenceFirst",
+         "fSequenceLast"                     => $fromtable . ".fSequenceLast",
+         "fNumEvents"                        => $fromtable . ".fNumEvents",
+         "fRunStart"                         => $fromtable . ".fRunStart",
+         "fLastUpdate"                       => $fromtable . ".fLastUpdate",
+         "fRunTime"                          => $fromtable . ".fRunTime",
+         "fRunTime/60"                       => $fromtable . ".fRunTime/60",
+         "fAzimuthMin"                       => $fromtable . ".fAzimuthMin",
+         "fAzimuthMax"                       => $fromtable . ".fAzimuthMax",
+         "fZenithDistanceMin"                => $fromtable . ".fZenithDistanceMin",
+         "fZenithDistanceMax"                => $fromtable . ".fZenithDistanceMax",
+         "fRunNumber"                        => "RunData.fRunNumber",
+         "fRunStop"                          => "RunData.fRunStop",
+         "fAzimuth"                          => "RunData.fAzimuth",
+         "fZenithDistance"                   => "RunData.fZenithDistance",
+         "fFormatVersion"                    => "RunData.fFormatVersion",
+         "fRunTypeName"                      => "RunType.fRunTypeName",
+         "fDaqStoreRate"                     => "RunData.fDaqStoreRate",
+         "fDaqTriggerRate"                   => "RunData.fDaqTriggerRate",
+         "fMeanTriggerRate"                  => "RunData.fMeanTriggerRate",
+         "fL2RatePresc"                      => "RunData.fL2RatePresc",
+         "fL3TriggerRate"                    => "RunData.fL3TriggerRate",
+         "fL2RateUnpresc"                    => "RunData.fL2RateUnpresc",
+         "fMagicNumberName"                  => "MagicNumber.fMagicNumberName",
+         "fExcludedFDAName"                  => "ExcludedFDA.fExcludedFDAName",
+         "fProjectName"                      => "Project.fProjectName",
+         "fSourceName"                       => "Source.fSourceName",
+         "fL1TriggerTableName"               => "L1TriggerTable.fL1TriggerTableName",
+         "fL2TriggerTableName"               => "L2TriggerTable.fL2TriggerTableName",
+         "fL3TriggerTableName"               => "L3TriggerTable.fL3TriggerTableName",
+         "fHvSettingsName"                   => "HvSettings.fHvSettingsName",
+         "fManuallyChangedName"              => "ManuallyChanged.fManuallyChangedName",
+         "fObservationModeName"              => "ObservationMode.fObservationModeName",
+         "fSumTriggerFlagName"               => "SumTriggerFlag.fSumTriggerFlagName",
+         "fTriggerDelayTableName"            => "TriggerDelayTable.fTriggerDelayTableName",
+         "fDiscriminatorThresholdTableName"  => "DiscriminatorThresholdTable.fDiscriminatorThesholdTableName",
+         "fCalibrationScriptName"            => "CalibrationScript.fCalibrationScriptName",
+         "fTestFlagName"                     => "TestFlag.fTestFlagName",
+         "fLightConditionsName"              => "LightConditions.fLightConditionsName",
+         "fRawFileAvail"                     => "RunProcessStatus.fRawFileAvail",
+         "fCCFileAvail"                      => "RunProcessStatus.fCCFileAvail",
+         "fCaCoFileAvail"                    => "RunProcessStatus.fCaCoFileAvail",
+         "fCaCoFileFound"                    => "RunProcessStatus.fCaCoFileFound",
+         "fTimingCorrection"                 => "RunProcessStatus.fTimingCorrection",
+//         "fFillDotRaw"                       => "RunProcessStatus.fFillDotRaw",
+         "fSequenceFileWritten"              => "SequenceProcessStatus.fSequenceFileWritten",
+         "fAllFilesAvail"                    => "SequenceProcessStatus.fAllFilesAvail",
+         "fCallisto"                         => "SequenceProcessStatus.fCallisto",
+         "fFillCallisto"                     => "SequenceProcessStatus.fFillCallisto",
+         "fStar"                             => "SequenceProcessStatus.fStar",
+         "fFillStar"                         => "SequenceProcessStatus.fFillStar",
+         "fUnsuitableInner"                  => "Calibration.fUnsuitableInner",
+         "fUnsuitableOuter"                  => "Calibration.fUnsuitableOuter",
+         "fUnsuitable50"                     => "Calibration.fUnsuitable50",
+         "fUnsuitable01"                     => "Calibration.fUnsuitable01",
+         "fUnsuitableMax"                    => "Calibration.fUnsuitableMax",
+         "fDeadMax"                          => "Calibration.fDeadMax",
+         "fRateTrigEvts"                     => "Calibration.fRateTrigEvts",
+         "fRateSumEvts"                      => "Calibration.fRateSumEvts",
+         "fRatePedEvts"                      => "Calibration.fRatePedEvts",
+         "fRatePedTrigEvts"                  => "Calibration.fRatePedTrigEvts",
+         "fRateCalEvts"                      => "Calibration.fRateCalEvts",
+         "fRateNullEvts"                     => "Calibration.fRateNullEvts",
+         "fRateUnknownEvts"                  => "Calibration.fRateUnknownEvts",
+         "fRatioCalEvents"                   => "Calibration.fRatioCalEvents",
+         "fPulsePosCalib"                    => "Calibration.fPulsePosCalib",
+         "fUnreliableInner"                  => "Calibration.fUnreliableInner",
+         "fUnreliableOuter"                  => "Calibration.fUnreliableOuter",
+         "fIsolatedInner"                    => "Calibration.fIsolatedInner",
+         "fIsolatedOuter"                    => "Calibration.fIsolatedOuter",
+         "fIsolatedMaxCluster"               => "Calibration.fIsolatedMaxCluster",
+         "fLastUpdate"                       => "Calibration.fLastUpdate",
+         "fMeanPedRmsInner"                  => "Calibration.fMeanPedRmsInner",
+         "fMeanPedRmsOuter"                  => "Calibration.fMeanPedRmsOuter",
+         "fArrTimeMeanInner"                 => "Calibration.fArrTimeMeanInner",
+         "fArrTimeMeanOuter"                 => "Calibration.fArrTimeMeanOuter",
+         "fArrTimeRmsInner"                  => "Calibration.fArrTimeRmsInner",
+         "fArrTimeRmsOuter"                  => "Calibration.fArrTimeRmsOuter",
+         "fMeanSignalInner"                  => "Calibration.fMeanSignalInner",
+         "fMeanSignalOuter"                  => "Calibration.fMeanSignalOuter",
+         "fPulsePosMean"                     => "Calibration.fPulsePosMean",
+         "fConvFactorInner"                  => "Calibration.fConvFactorInner",
+         "fConvFactorOuter"                  => "Calibration.fConvFactorOuter",
+         "fMeanNumberIslands"                => "Star.fMeanNumberIslands",
+         "fPSF"                              => "Star.fPSF",
+         "fRatio"                            => "Star.fRatio",
+         "fMuonNumber"                       => "Star.fMuonNumber",
+         "fEffOnTime"                        => "fEffOnTime",
+         "fEffOnTime/fRunTime"               => "Sequences.fRunTime/Star.fEffOnTime",
+         "fEffOnTime/3600"                   => "fEffOnTime/3600",
+//         "fEffOnTime"                        => $fromtable . ".fEffOnTime",
+         "fMuonRate"                         => "Star.fMuonRate",
+         "fInhomogeneity"                    => "Star.fInhomogeneity",
+         "fDataRate"                         => "Star.fDataRate",
+         "fSparkRate"                        => "Star.fSparkRate",
+         "fMaxHumidity"                      => "Star.fMaxHumidity",
+         "fBrightnessMed"                    => "Star.fBrightnessMed",
+         "fBrightnessRMS"                    => "Star.fBrightnessRMS",
+         "fNumStarsMed"                      => "Star.fNumStarsMed",
+         "fNumStarsRMS"                      => "Star.fNumStarsRMS",
+         "fNumStarsCorMed"                   => "Star.fNumStarsCorMed",
+         "fNumStarsCorRMS"                   => "Star.fNumStarsCorRMS",
+         "fAvgWindSpeed"                     => "Star.fAvgWindSpeed",
+         "fAvgTemperature"                   => "Star.fAvgTemperature",
+         "fAvgHumidity"                      => "Star.fAvgHumidity",
+         "fAvgTempSky"                       => "Star.fAvgTempSky",
+         "fAvgCloudiness"                    => "Star.fAvgCloudiness",
+         "fRmsCloudiness"                    => "Star.fRmsCloudiness",
+         "fDataSetNumber"                    => $fromtable . ".fDataSetNumber",
+         "fDataSetInserted"                  => "DataSetProcessStatus.fDataSetInserted",
+         "fDataSetFileWritten"               => "DataSetProcessStatus.fDataSetFileWritten",
+         "fStarFilesAvail"                   => "DataSetProcessStatus.fStarFilesAvail",
+         "fGanymed"                          => "DataSetProcessStatus.fGanymed",
+         "fFillGanymed"                      => "DataSetProcessStatus.fFillGanymed",
+         "fComment"                          => "DataSets.fComment",
+         "fDataSetName"                      => "DataSets.fDataSetName",
+         "fEvents"                           => "DataCheck.fEvents",
+         "fPositionSignal"                   => "DataCheck.fPositionSignal",
+         "fPositionFWHM"                     => "DataCheck.fPositionFWHM",
+         "fHeightSignal"                     => "DataCheck.fHeightSignal",
+         "fHeightFWHM"                       => "DataCheck.fHeightFWHM",
+         "fHasSignal"                        => "DataCheck.fHasSignal",
+         "fHasPedestal"                      => "DataCheck.fHasPedestal",
+         "fPositionAsym"                     => "DataCheck.fPositionAsym",
+         "fHeightAsym"                       => "DataCheck.fHeightAsym",
+         "fEventsInterlaced"                 => "DataCheck.fEventsInterlaced",
+         "fPositionSignalInterlaced"         => "DataCheck.fPositionSignalInterlaced",
+         "fPositionFWHMInterlaced"           => "DataCheck.fPositionFWHMInterlaced",
+         "fHeightSignalInterlaced"           => "DataCheck.fHeightSignalInterlaced",
+         "fHeightFWHMInterlaced"             => "DataCheck.fHeightFWHMInterlaced",
+         "fHasSignalInterlaced"              => "DataCheck.fHasSignalInterlaced",
+         "fHasPedestalInterlaced"            => "DataCheck.fHasPedestalInterlaced",
+         "fPositionAsymInterlaced"           => "DataCheck.fPositionAsymInterlaced",
+         "fHeightAsymInterlaced"             => "DataCheck.fHeightAsymInterlaced",
+         "fExcessEvents"                     => "Ganymed.fExcessEvents",
+         "fBackgroundEvents"                 => "Ganymed.fBackgroundEvents",
+         "fSignalEvents"                     => "Ganymed.fSignalEvents",
+         "fSignificance"                     => "Ganymed.fSignificance",
+         "fScaleFactor"                      => "Ganymed.fScaleFactor",
+         "fExcessEvents*60/fEffOnTime"       => "fExcessEvents*60/fEffOnTime",
+         "fBackgroundEvents*60/fEffOnTime"   => "fBackgroundEvents*60/fEffOnTime",
+         "fSignalEvents*60/fEffOnTime"       => "fSignalEvents*60/fEffOnTime",
+         "Round(fSignificance/Sqrt(fEffOnTime/3600),2)" => "Round(fSignificance/Sqrt(fEffOnTime/3600),2)",
+         "SUM(fRunTime)/3600"                => "'Time [h]'",
+         "SUM(fNumEvents)"                   => "'Evts'",
+         "Min(fZenithDistanceMin)"           => "'ZDMin'",
+         "Max(fZenithDistanceMax)"           => "'ZDMax'",
+         "Min(fZenithDistance)"              => "'ZdMin'",
+         "Max(fZenithDistance)"              => "'ZdMax'",
+//         "COUNT(*)"                          => "'Sequence'",
+         "fStartTime"                        => "fStartTime",
+         "fFailedTime"                       => "fFailedTime",
+         "fReturnCode"                       => "fReturnCode",
+         "fProgramId"                        => "fProgramId",
+         "fParticleTypeName"                 => "ParticleType.fParticleTypeName",
+         "fFitsFileName"                     => "FitsFile.fFitsFileName",
+         "fObjectName"                       => "Object.fObjectName",
+         "fStatusName"                       => "Status.fStatusName",
+         "fBandName"                         => "Band.fBandName",
+         "fTelescopeName"                    => "Telescope.fTelescopeName",
+         "fUserName"                         => "User.fUserName",
+         "fCycleName"                        => "Cycle.fCycleName",
+         "fPIName"                           => "PI.fPIName",
+         "fWorkingGroupName"                 => "WorkingGroup.fWorkingGroupName",
+         "fProposalName"                     => "Proposal.fProposalName",
+         "fWheelPos1"                        => "RunData.fWheelPos1",
+         "fWheelPos2"                        => "RunData.fWheelPos2",
+        );
+
+    $table="";
+    if (!empty($tables[$val]))
+        $table=$tables[$val];
+    if ($val=="Tel:Run/File")
+        $table="'Tel:Run/File'";
+    if ($val=="Tel:Sequ")
+        $table="CONCAT('M', Sequences.fTelescopeNumber, ':', LPAD(Sequences.fSequenceFirst, 8, '0'))";
+    if ($val=="NumRuns")
+        $table="'# Runs'";
+    if ($val=="NumSequ")
+        $table="'# Sequ'";
+    if ($val=="NumDS")
+        $table="'# Datasets'";
+    if ($val=="NumDays")
+        $table="'# days'";
+    if (empty($table))
+        $table=$val;
+    return $table;
+}
+
+
+function GetJoin($fromtable, $val)
+{
+    $joins = array
+        (
+         "fRunTypeName"                     => " LEFT JOIN RunType                     USING(fRunTypeKEY) ",
+         "fProjectName"                     => " LEFT JOIN Project                     USING(fProjectKEY) ",
+         "fSourceName"                      => " LEFT JOIN Source                      USING(fSourceKEY) ",
+         "fMagicNumberName"                 => " LEFT JOIN MagicNumber                 USING(fMagicNumberKEY) ",
+         "fL1TriggerTableName"              => " LEFT JOIN L1TriggerTable              USING(fL1TriggerTableKEY) ",
+         "fL2TriggerTableName"              => " LEFT JOIN L2TriggerTable              USING(fL2TriggerTableKEY) ",
+         "fL3TriggerTableName"              => " LEFT JOIN L3TriggerTable              USING(fL3TriggerTableKEY) ",
+         "fHvSettingsName"                  => " LEFT JOIN HvSettings                  USING(fHvSettingsKEY) ",
+         "fCalibrationScriptName"           => " LEFT JOIN CalibrationScript           USING(fCalibrationScriptKEY) ",
+         "fExcludedFDAName"                 => " LEFT JOIN ExcludedFDA                 USING(fExcludedFDAKEY) ",
+         "fManuallyChangedName"             => " LEFT JOIN ManuallyChanged             USING(fManuallyChangedKEY) ",
+         "fObservationModeName"             => " LEFT JOIN ObservationMode             USING(fObservationModeKEY) ",
+         "fSumTriggerFlagName"              => " LEFT JOIN SumTriggerFlag              USING(fSumTriggerFlagKEY) ",
+         "fDiscriminatorThresholdTableName" => " LEFT JOIN DiscriminatorThresholdTable USING(fDiscriminatorThresholdTableKEY) ",
+         "fTriggerDelayTableName"           => " LEFT JOIN TriggerDelayTable           USING(fTriggerDelayTableKEY) ",
+         "fTestFlagName"                    => " LEFT JOIN TestFlag                    USING(fTestFlagKEY) ",
+         "fLightConditionsName"             => " LEFT JOIN LightConditions             USING(fLightConditionsKEY) ",
+         "fParticleTypeName"                => " LEFT JOIN ParticleType                USING(fParticleTypeKEY) ",
+         "fFitsFileName"                    => " LEFT JOIN FitsFile                    USING(fFitsFileKEY) ",
+         "fObjectName"                      => " LEFT JOIN Object                      USING(fObjectKEY) ",
+         "fStatusName"                      => " LEFT JOIN Status                      USING(fStatusKEY) ",
+         "fBandName"                        => " LEFT JOIN Band                        USING(fBandKEY) ",
+         "fUserName"                        => " LEFT JOIN User                        USING(fUserKEY) ",
+         "fTelescopeName"                   => " LEFT JOIN Telescope                   USING(fTelescopeKEY) ",
+         "fCycleName"                       => " LEFT JOIN Cycle                       USING(fCycleKEY) ",
+         "fPIName"                          => " LEFT JOIN PI                          USING(fPIKEY) ",
+         "fWorkingGroupName"                => " LEFT JOIN WorkingGroup                USING(fWorkingGroupKEY) ",
+         "fProposalName"                    => " LEFT JOIN Proposal                    USING(fProposalKEY) ",
+        );
+
+
+    $join="";
+    if (!empty($joins[$val]))
+        $join=$joins[$val];
+    return $join;
+}
+
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/mcdefs.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/mcdefs.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/mcdefs.php	(revision 17960)
@@ -0,0 +1,197 @@
+<?php
+
+$timelimits = array
+    (
+     "Corsika" => "60",
+     "Ceres" => "2",
+     "SequenceFile" => "1",
+     "Callisto" => "1",
+     "Star" => "1",
+     );
+
+
+$checkwhere = array
+    (
+     "fParticleTypeName"                 => CheckWhere("fParticleTypeKEY"),
+     "fRunTypeName"                      => CheckWhere("fRunTypeKEY"),
+     "fAtmosphericModelName"             => CheckWhere("fAtmosphericModelKEY"),
+     "fCeresSetupName"                   => CheckWhere("fCeresSetupKEY"),
+    );
+
+$checkgroup = array
+    (
+     "fParticleTypeName"                 => CheckGroup("fParticleTypeKEY"),
+     "fRunTypeName"                      => CheckGroup("fRunTypeKEY"),
+     "fAtmosphericModelName"             => CheckGroup("fAtmosphericModelKEY"),
+     "fCeresSetupName"                   => CheckGroup("fCeresSetupKEY"),
+    );
+
+
+$checkstatusgroup = array
+    (
+     "Corsika"      => CheckStatusGroup("Corsika"),
+     "Ceres"        => CheckStatusGroup("Ceres"),
+     "SequenceFile" => CheckStatusGroup("SequenceFile"),
+     "Callisto"     => CheckStatusGroup("Callisto"),
+     "Star"         => CheckStatusGroup("Star"),
+    );
+
+
+
+$alias = array
+    (
+     "Run.File"                         => "Run.File",
+     "fSequenceNumber"                  => "Sequ",
+     "fNumEvents"                       => "#Showers",
+     "fNumEvents*fNumReUseShowers"      => "#Evts",
+     "fNumReUseShowers"                 => "reused",
+     "SUM(fNumEvents)"                  => "Showers",
+     "SUM(fNumEvents*fNumReUseShowers)" => "Evts",
+     "fParticleTypeName"                => "Particle",
+     "fRunTypeName"                     => "RunType",
+     "fAtmosphericModelName"            => "Atm.Model",
+     "fCeresSetupName"                  => "CeresSetup",
+     "fCorsikaInputCreated"             => "Input",
+     "Corsika"                          => "Corsika",
+     "Ceres"                            => "Ceres",
+     "SequenceFile"                     => "SequenceFile",
+     "Callisto"                         => "Callisto",
+     "Star"                             => "Star",
+     "fZenithDistanceMin"               => "Zd<br>Min",
+     "fZenithDistanceMax"               => "Zd<br>Max",
+     "fAzimuthMin"                      => "Az<br>Min",
+     "fAzimuthMax"                      => "Az<br>Max",
+     "Min(fZenithDistanceMin)"          => "ZDMin",
+     "Max(fZenithDistanceMax)"          => "ZDMax",
+     "fEnergyMin"                       => "EMin<br>[GeV]",
+     "fEnergyMax"                       => "EMax<br>[GeV]",
+     "fImpactMax"                       => "Impact<br>[cm]",
+     "fViewConeMax"                     => "View<br>cone<br>[deg]",
+     "fEnergySlope"                     => "Slope",
+     "fStartingAltitude"                => "Altitude<br>[g/sqcm]",
+     "fMirrorDiameter"                  => "Mirror<br>diam.<br>[cm]",
+    );
+
+
+$rightalign = array
+    (
+     $alias["fSequenceNumber"]              => "1",
+     $alias["fNumEvents"]                   => "1",
+     $alias["fNumEvents*fNumReUseShowers"]  => "1",
+     $alias["fZenithDistanceMin"]           => "1",
+     $alias["fZenithDistanceMax"]           => "1",
+     $alias["fAzimuthMin"]                  => "1",
+     $alias["fAzimuthMax"]                  => "1",
+     $alias["fEnergyMin"]                   => "1",
+     $alias["fEnergyMax"]                   => "1",
+     $alias["fImpactMax"]                   => "1",
+     $alias["fViewConeMax"]                 => "1",
+     $alias["fEnergySlope"]                 => "1",
+     $alias["fStartingAltitude"]            => "1",
+     $alias["fMirrorDiameter"]              => "1",
+     "Time"                                 => "1",
+     "Runs"                                 => "1",
+     "Evts"                                 => "1",
+);
+
+function GetCheck($fromtable, $val)
+{
+    $checks = array
+        (
+         "fParticleTypeName"         => "ParticleType.fParticleTypeKEY",
+         "fRunTypeName"              => "RunType.fRunTypeKEY",
+         "fAtmosphericModelName"     => "AtmosphericModel.fAtmosphericModelKEY",
+         "fCeresSetupName"           => "CeresSetup.fCeresSetupKEY",
+        );
+
+    $check="";
+    if (!empty($checks[$val]))
+        $check=$checks[$val];
+    return $check;
+}
+
+
+function GetTable($fromtable, $val)
+{
+    $tables = array
+        (
+         "fNumEvents"                        => "CorsikaInfo.fNumEvents",
+         "fMCRunNumber"                      => "MCCorsikaRunData.fMCRunNumber",
+         "fRawFileAvail"                     => "RunProcessStatus.fRawFileAvail",
+         "SUM(fRunTime)/3600"                => "'Time [h]'",
+         "SUM(fNumEvents)"                   => "'Evts'",
+         "fParticleTypeName"                 => "ParticleType.fParticleTypeName",
+         "fRunTypeName"                      => "RunType.fRunTypeName",
+         "fAtmosphericModelName"             => "AtmosphericModel.fAtmosphericModelName",
+         "fCeresSetupName"                   => "CeresSetup.fCeresSetupName",
+         "fAzimuthMin"                       => "CorsikaInfo.fAzimuthMin",
+         "fAzimuthMax"                       => "CorsikaInfo.fAzimuthMax",
+         "fZenithDistanceMin"                => "CorsikaInfo.fZenithDistanceMin",
+         "fZenithDistanceMax"                => "CorsikaInfo.fZenithDistanceMax",
+         "fEnergyMin"                        => "CorsikaInfo.fEnergyMin",
+         "fEnergyMax"                        => "CorsikaInfo.fEnergyMax",
+         "fImpactMax"                        => "CorsikaInfo.fImpactMax",
+         "fViewConeMax"                      => "CorsikaInfo.fViewConeMax",
+         "fEnergySlope"                      => "CorsikaInfo.fEnergySlope",
+         "fStartingAltitude"                 => "CorsikaInfo.fStartingAltitude",
+         "fMirrorDiameter"                   => "CorsikaInfo.fMirrorDiameter",
+         "Min(fZenithDistanceMin)"           => "'ZDMin'",
+         "Max(fZenithDistanceMax)"           => "'ZDMax'",
+        );
+
+    $table="";
+    if (!empty($tables[$val]))
+        $table=$tables[$val];
+    if ($val=="Run.File")
+        $table="'Run.File'";
+    if ($val=="Tel:Sequ")
+        $table="CONCAT('M', Sequences.fTelescopeNumber, ':', LPAD(Sequences.fSequenceFirst, 8, '0'))";
+    if ($val=="NumRuns")
+        $table="'# Runs'";
+    if ($val=="NumSequ")
+        $table="'# Sequ'";
+    if ($val=="NumDS")
+        $table="'# Datasets'";
+    if ($val=="# Files")
+        $table="'# Files'";
+    if ($val=="NumDays")
+        $table="'# days'";
+    if (empty($table))
+        $table=$val;
+    return $table;
+}
+
+
+function GetJoin($fromtable, $val)
+{
+    $joins = array
+        (
+         "fParticleTypeKEY"           => " LEFT JOIN ParticleType         USING(fParticleTypeKEY) ",
+         "fRunTypeKEY"                => " LEFT JOIN RunType              USING(fRunTypeKEY) ",
+         "fAtmosphericModelKEY"       => " LEFT JOIN AtmosphericModel     USING(fAtmosphericModelKEY) ",
+         "fCeresSetupKEY"             => " LEFT JOIN CeresSetup           USING(fCeresSetupKEY) ",
+         "fParticleTypeName"          => " LEFT JOIN ParticleType         USING(fParticleTypeKEY) ",
+         "fRunTypeName"               => " LEFT JOIN RunType              USING(fRunTypeKEY) ",
+         "fAtmosphericModelName"      => " LEFT JOIN AtmosphericModel     USING(fAtmosphericModelKEY) ",
+         "fCeresSetupName"            => " LEFT JOIN CeresSetup           USING(fCeresSetupKEY) ",
+         "CorsikaStatus"              => " LEFT JOIN CorsikaStatus        USING(fRunNumber, fFileNumber) ",
+         "CeresStatus"                => " LEFT JOIN CeresStatus          USING(fRunNumber, fCeresSetupKEY) ",
+         "SequenceFileStatus"         => " LEFT JOIN SequenceFileStatus   USING(fSequenceNumber) ",
+         "CallistoStatus"             => " LEFT JOIN CallistoStatus       USING(fSequenceNumber, fCeresSetupKEY) ",
+         "StarStatus"                 => " LEFT JOIN StarStatus           USING(fSequenceNumber, fCeresSetupKEY) ",
+         "Corsika"                    => " LEFT JOIN CorsikaStatus        USING(fRunNumber, fFileNumber) ",
+         "Ceres"                      => " LEFT JOIN CeresStatus          USING(fRunNumber, fCeresSetupKEY) ",
+         "SequenceFile"               => " LEFT JOIN SequenceFileStatus   USING(fSequenceNumber) ",
+         "Callisto"                   => " LEFT JOIN CallistoStatus       USING(fSequenceNumber, fCeresSetupKEY) ",
+         "Star"                       => " LEFT JOIN StarStatus           USING(fSequenceNumber, fCeresSetupKEY) ",
+        );
+
+
+    $join="";
+    if (!empty($joins[$val]))
+        $join=$joins[$val];
+    return $join;
+}
+
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/mcinfo.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/mcinfo.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/mcinfo.php	(revision 17960)
@@ -0,0 +1,320 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $timelimits)
+    {
+        $fromtable="CeresInfo";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0 || $statusgroups>0)
+        {
+            if ($groups>0)
+            {
+                foreach ($checkgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+            }
+
+            if ($statusgroups>0)
+            {
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .= " IF( ISNULL(" . $key . "Status.fStartTime) "
+                            ." AND ISNULL(" . $key . "Status.fStopTime) "
+                            ." AND ISNULL(" . $key . "Status.fReturnCode), 'not done', "
+                            //crashed
+                            ." IF (NOT ISNULL(" . $key . "Status.fStartTime) "
+                            ." AND DATE_SUB(Now(),INTERVAL " . $timelimits[$key] . " HOUR) > " . $key . "Status.fStartTime "
+                            ." AND ISNULL(" . $key . "Status.fStopTime) "
+                            ." AND ISNULL(" . $key . "Status.fReturnCode), 'crashed', "
+                            //running
+                            ." IF (NOT ISNULL(" . $key . "Status.fStartTime) "
+                            ." AND DATE_SUB(Now(),INTERVAL " . $timelimits[$key] . " HOUR) < " . $key . "Status.fStartTime "
+                            ." AND ISNULL(" . $key . "Status.fStopTime) "
+                            ." AND ISNULL(" . $key . "Status.fReturnCode), 'running', "
+                            //failed
+                            ." IF (NOT ISNULL(" . $key . "Status.fStartTime) "
+                            ." AND NOT ISNULL(" . $key . "Status.fStopTime) "
+                            ." AND NOT ISNULL(" . $key . "Status.fReturnCode), 'failed', "
+                            //done or done and avail
+                            ." IF (NOT ISNULL(" . $key . "Status.fStartTime) "
+                            ." AND NOT ISNULL(" . $key . "Status.fStopTime) "
+                            ." AND ISNULL(" . $key . "Status.fReturnCode)"
+                            ." AND ISNULL(" . $key . "Status.fAvailable), 'done', 'done and avail' "
+                            ." ))))) AS '". $key . "', ";
+            }
+            $query0 .= " COUNT(*) as '# Files' ";
+            $query0 .= ", SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "' ";
+            $query0 .= ", SUM(fNumEvents*fNumReUseShowers) as '" . $alias["SUM(fNumEvents*fNumReUseShowers)"] . "' ";
+        }
+        else
+        {
+            $query0 .= " CONCAT(LPAD(" . $fromtable . ".fRunNumber,8, ' '),'.', ";
+            $query0 .= " RIGHT(LPAD(" . $fromtable . ".fFileNumber, 6, 0), 3)) as 'Run.File' ";
+
+            if (empty($_GET["fSendTxt"]) && !empty($_GET["fLinks"]))
+            {
+                $query0 .= ", CONCAT('<A&ws;HREF=\"queryrbk.php?fNight=', date_format(adddate(fRunStart, interval +13 HOUR), '%Y-%m-%d') , '&amp;fDate=2\">rbk</A>') ";
+                $query0 .= " as 'Links'";
+            }
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On" && $key!="fTest" && $key!="fLinks")
+                    if (!ereg("^f", $key))
+                    {
+
+                        $query0 .= ", IF (ISNULL(" . $key . "Status.fStartTime) AND ";
+                        $query0 .= " ISNULL(" . $key . "Status.fStopTime) AND ";
+                        $query0 .= " ISNULL(" . $key . "Status.fReturnCode), 'not done', ";
+
+                        $query0 .= " IF (NOT ISNULL(" . $key . "Status.fStartTime) ";
+                        $query0 .= " AND ISNULL(" . $key . "Status.fStopTime) ";
+                        $query0 .= " AND ISNULL(" . $key . "Status.fReturnCode) ";
+                        $query0 .= " AND DATE_SUB(Now(),INTERVAL " . $timelimits[$key] . " HOUR) > " . $key . "Status.fStartTime, ";
+                        $query0 .= " CONCAT('maybe crashed (started at ', " . $key . "Status.fStartTime, ')'), ";
+
+                        $query0 .= " IF (NOT ISNULL(" . $key . "Status.fStartTime) ";
+                        $query0 .= " AND ISNULL(" . $key . "Status.fStopTime) ";
+                        $query0 .= " AND ISNULL(" . $key . "Status.fReturnCode) ";
+                        $query0 .= " AND DATE_SUB(Now(),INTERVAL " . $timelimits[$key] . " HOUR) < " . $key . "Status.fStartTime, ";
+                        $query0 .= " CONCAT('running (started at ', " . $key . "Status.fStartTime, ')'), ";
+
+                        $query0 .= " IF (NOT ISNULL(" . $key . "Status.fReturnCode), ";
+                        $query0 .= " CONCAT('failed (', " . $key . "Status.fReturnCode, ', ', " . $key . "Status.fStopTime, ')'), ";
+                        $query0 .= " CONCAT('done (', " . $key . "Status.fStopTime, ";
+                        $query0 .= " ', ', TIMEDIFF(" . $key . "Status.fStopTime, " . $key . "Status.fStartTime), ')'))))) ";
+
+                        $query0 .= " AS '" . $alias[$key] . "' ";
+                    }
+                    else
+                        if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                            $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM " . $fromtable;
+
+        $query0 .= " LEFT JOIN CorsikaInfo USING(fRunNumber,fFileNumber) ";
+
+        foreach ($_GET as $key => $element)
+            if ($_GET[$key]=="On" || $_GET[$key]!=0)
+                if (strpos($query0, GetJoin($fromtable,$key))==FALSE)
+                    $query0 .= GetJoin($fromtable,$key);
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)// this if clause doesn't work
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= StatusQuery("Corsika",      $timelimits);
+        $query0 .= StatusQuery("Ceres",        $timelimits);
+        $query0 .= StatusQuery("SequenceFile", $timelimits);
+        $query0 .= StatusQuery("Callisto",     $timelimits);
+        $query0 .= StatusQuery("Star",         $timelimits);
+
+        if ((!empty($_GET["fRunMin"]) || $_GET["fRunMin"]=="0") && !empty($_GET["fRunMax"]))
+            $query0 .= " " . $fromtable . ".fRunNumber BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+
+
+        //remove WHERE or AND in the end of the query
+        $query0=preg_replace("/ WHERE\s+$/", " ", $query0);
+        $query0=preg_replace("/ AND\s+$/", " ", $query0);
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable,$key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if ($statusgroups>0)
+        {
+            if (strpos($query0, " GROUP BY ")==FALSE)
+                $query0 .= " GROUP BY ";
+            else
+                $query0 .= ", ";
+            $num = $statusgroups;
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable, $val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+        else
+            $query0 .=" ORDER BY " . $fromtable . ".fRunNumber ASC";
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        InitMCRunInfo($_GET, $first);
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"mcinfo.php\" METHOD=\"GET\">\n");
+
+        printf("<input id='sh' type='hidden' name='fShowHide' value='");
+        if (!empty($_GET["fShowHide"]))
+            printf("%s", $_GET["fShowHide"]);
+        else
+            printf("1000000010");
+        printf("'>\n");
+        printf("<img id='allbutton' src='minus.png' alt='-' onclick=\"showhide('all')\"> <b>Menu</b>&nbsp;&nbsp;&nbsp;&nbsp;\n");
+        printf("&nbsp;&nbsp;<img id='infobutton'   src='plus.png' alt='+' onClick=\"showhide('info');showhide('info2')\"> MCRunInfo  \n");
+        printf("&nbsp;&nbsp;<img id='statbutton'   src='plus.png' alt='+' onClick=\"showhide('stat')\">  StatusInfo \n");
+        printf("&nbsp;&nbsp;<img id='rangesbutton' src='plus.png' alt='+' onClick=\"showhide('ranges')\">                 Ranges     \n");
+
+        printf(" <div id='all' style='display:block'>");
+        PrintMCRunInfoMenu($host,$user,$pw,$db);
+        PrintMCRunStatMenu();
+        printf(" <div id='ranges' style='display:none'>");
+        printf("<p>");
+        PrintMCRunRangeMenu($host,$user,$pw,$db);
+        printf("<p>");
+        printf("</div>");
+        printf("</div>");
+        printf(" <P>\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        PrintNumResPullDown();
+        PrintButtons("mcinfo.php");
+
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $timelimits)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+        mysql_query("SET BIG_TABLES=1"); // necessary for mySQL <= 4
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $timelimits);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "");
+    }
+
+    include ("include.php");
+    include ("db2.php");
+    include ("menu.php");
+    include ("mcdefs.php");
+
+    ini_set("display_errors",   "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $timelimits);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header-fact.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $timelimits);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $timelimits);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors",   "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/menu.js
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/menu.js	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/menu.js	(revision 17960)
@@ -0,0 +1,262 @@
+
+//functions and arrays needed for showing and hiding the menu on the db websites
+ids = new Array( "all", "info", "info2", "stat", "fail", "cal", "star", "limits", "ranges", "showquery");
+statarr = new Array( 1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+
+//function to get the input for fShowHide from the page
+//called each time, when an element is changed with showhide()
+//and when the page is reloaded
+function setdisplays ()
+{
+    //reset variable for fShowHide
+    var sh="";
+    for (var i = 0 ; i < ids.length ; i++)
+    {
+        //get element for each possible menu element
+        var d = document.getElementById(ids[i]);
+        //if element exists, check if it is currently displayed
+        //set the value in the status array accordingly
+        //0: element is not shown
+        //1: element is shown
+        if (d)
+            d.style.display == 'none' ? statarr[i]=0 : statarr[i]=1;
+        //set the value of 'all' to 0
+        //to make sure, that the whole menu is hidden in case of a query
+        if (i==0)
+            statarr[i]=0;
+        //add value to the variable for fShowHide
+        sh=sh+statarr[i];
+    }
+    //return variable for fShowHide
+    return sh;
+}
+
+//function to hide one element of the menu and adapt the button accordingly
+function hide(el,img)
+{
+    el.style.display="none";
+    if (img)
+    {
+        img.src='plus.png';
+        img.alt='+';
+    }
+}
+
+//function to show one element of the menu and adapt the button accordingly
+function show(el,img)
+{
+    el.style.display="block";
+    if (img)
+    {
+        img.src='minus.png';
+        img.alt='-';
+    }
+}
+
+//function to show or hide one element of the menu
+function showhide (id)
+{
+    //get menu element and button for the element that has to be changed
+    var el = document.getElementById(id);
+    var img = document.getElementById(id+"button");
+    //query current status and change it accordingly
+    if (el.style.display != 'none')
+        hide(el,img);
+    else
+    {
+        show(el,img);
+        //expand the whole menu, when one element is shown
+        if (id!="showquery")
+        {
+            var el2 = document.getElementById("all");
+            var img2 = document.getElementById("allbutton");
+            show(el2,img2);
+        }
+    }
+    //update the value of fShowHide (id sh)
+    var fShowHide = document.getElementById("sh");
+    fShowHide.value = setdisplays();
+}
+
+//function getting the info, how the menu is from fShowHide
+//is called when the page is loaded (s. index-header.html)
+function getdisplay()
+{
+    //get value of fShowHide
+    var stat = document.getElementById("sh");
+    statvalue=stat.value;
+    //set menu variables for each element accordingly
+    for (var i = 0 ; i < ids.length ; i++)
+    {
+        //get value of this element from fShowHide
+        var status = statvalue.slice(i,i+1);
+        //get elements of menu and button
+        var el = document.getElementById(ids[i]);
+        var img = document.getElementById(ids[i]+"button");
+        //not all element exist on each page
+        if (!el)
+            continue;
+        //show or hide element according to the status value
+        status==0 ? hide(el,img) : show(el,img);
+    }
+    //set the value of fShowHide (id sh)
+    // needed here to make sure, that the whole menu is hidden
+    //  even if nothing has been expanded (needed since 'ranges'
+    //  is expanded by default)
+    var fShowHide = document.getElementById("sh");
+    fShowHide.value = setdisplays();
+}
+
+//show all lines on db website
+function showalllines(num)
+{
+    for (var i = 1 ; i < num+1 ; i++)
+    {
+        var el = document.getElementById("line"+i);
+        var img = document.getElementById("line"+i+"button");
+        if (el.style.display == 'none')
+        {
+            el.style.display='';
+            if (img)
+            {
+                img.src='minus.png';
+                img.alt='-';
+            }
+        }
+    }
+}
+
+
+//functions and arrays needed for the menu of plotdb.php
+primaries = new Array( "fSequenceFirst", "fRunNumber", "fDataSetNumber");
+
+//for each primary (run#, seq#, dataset#) two pulldowns exist
+//the first is needed when plotting versus primary ('prim' is chosen)
+//the second is only needed when plotting versus a second value ('val' is chosen)
+
+//shows the first pulldown for a given primary
+// and hides the ones of the other primaries
+// and hides the second one for the primary if needed
+//is called when a primary is chosen from the pulldown
+function showpulldown (id2)
+{
+    //loop over primaries
+    for (var i = 0 ; i < primaries.length ; i++)
+    {
+        //if primary is given id
+        if (primaries[i]==id2)
+        {
+            //show first pulldown
+            var el2 = document.getElementById(primaries[i]);
+            el2.style.display="inline";
+            //show pulldowns for limits
+            var el4 = document.getElementById(primaries[i]+"3");
+            el4.style.display="inline";
+            var el6 = document.getElementById(primaries[i]+"4");
+            el6.style.display="inline";
+        }
+        else
+        {
+            //hide first pulldown
+            var el2 = document.getElementById(primaries[i]);
+            el2.style.display="none";
+            //get element for second pulldown
+            var el3 = document.getElementById(primaries[i]+"2");
+            //if second pulldown is shown,
+            // hide second pulldown
+            // and show second pulldown for chosen primary (id2)
+            if (el3.style.display=='inline')
+            {
+                var el6 = document.getElementById(id2+"2");
+                el6.style.display="inline";
+                el3.style.display="none";
+            }
+            //hide pulldowns for limits
+            var el4 = document.getElementById(primaries[i]+"3");
+            el4.style.display="none";
+            var el5 = document.getElementById(primaries[i]+"4");
+            el5.style.display="none";
+        }
+    }
+}
+
+//shows the second pulldown and inputs for the ranges
+function showpulldown2 ()
+{
+    count=0;
+    for (var i = 0 ; i < primaries.length ; i++)
+    {
+        //get element
+        var el = document.getElementById(primaries[i]);
+        //if the first pulldown is shown, show also the second one
+        if (el.style.display=='inline')
+        {
+            var el2 = document.getElementById(primaries[i]+"2");
+            el2.style.display="inline";
+        }
+        else
+            count++;
+    }
+    //if no first pulldown is shown, i.e. the primary has not yet been chosen,
+    //all second pulldowns are shown
+    if (count==3)
+        for (var i = 0 ; i < primaries.length ; i++)
+        {
+            var el2 = document.getElementById(primaries[i]+"2");
+            el2.style.display="inline";
+        }
+
+    //show the inputs for the ranges for the second pulldown
+    //there is only one element for this (not one for each primary)
+    var el3 = document.getElementById("Range2");
+    el3.style.display="inline";
+}
+
+//hides the second pulldown and inputs for the ranges
+function hidepulldown2 ()
+{
+    for (var i = 0 ; i < primaries.length ; i++)
+    {
+        var el2 = document.getElementById(primaries[i]+"2");
+        el2.style.display="none";
+    }
+    var el3 = document.getElementById("Range2");
+    el3.style.display="none";
+}
+
+//show the element for inserting the second set
+function showset2()
+{
+    var el = document.getElementById("set2");
+    el.style.display="inline";
+}
+
+//hide the element for inserting the second set
+function hideset2()
+{
+    var el = document.getElementById("set2");
+    el.style.display="none";
+}
+
+
+
+//
+//functions for builddatasets.php
+//
+
+function selectallsequences(val)
+{
+    var sequs = document.getElementsByTagName("input");
+    for (var i=0; i<sequs.length; i++)
+    {
+        var sequname = sequs[i].name;
+        if (!sequname.match("^DSSeq[0-9]*$"))
+            continue;
+        var sequval = sequs[i].value;
+        if (sequval != val)
+            sequs[i].checked = false;
+        else
+            sequs[i].checked = true;
+    }
+}
+
Index: branches/Mars_McMismatchStudy/datacenter/db/menu.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/menu.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/menu.php	(revision 17960)
@@ -0,0 +1,1729 @@
+<?php
+
+//MC stuff
+function PrintMCRunInfoMenu($host,$user,$pw,$db)
+{
+    printf(" <div id='info' style='display:none'>");
+    printf(" <table>\n");
+    printf("  <tr valign='top'>\n");
+
+    CheckBox("fNumEvents",                  "Num of showers");
+    CheckBox("fNumEvents*fNumReUseShowers", "Num of events");
+    CheckBox("fNumReUseShowers",            "reused");
+    CheckBox("fSequenceNumber",             "Sequ#");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fImpactMax",                  "Impact");
+    CheckBox("fViewConeMax",                "Viewcone");
+    CheckBox("fStartingAltitude",           "Starting alt.");
+    CheckBox("fMirrorDiameter",             "Mirror diam.");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fZenithDistanceMin",           "Zenith dist. min");
+    CheckBox("fZenithDistanceMax",           "Zenith dist. max");
+    CheckBox("fAzimuthMin",                  "Azimuth min");
+    CheckBox("fAzimuthMax",                  "Azimuth max");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fEnergyMin",                   "Emin");
+    CheckBox("fEnergyMax",                   "Emax");
+    CheckBox("fEnergySlope",                 "Slope");
+
+    printf("  </tr><tr>\n");
+    printf("  <td>\n");
+    PrintPullDown($host, $user, $pw, $db, "ParticleType",     "fParticleTypeName",     "fParticleTypeKEY", "Particle type");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "RunType",     "fRunTypeName",     "fRunTypeKEY", "Run type");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "AtmosphericModel",     "fAtmosphericModelName",     "fAtmosphericModelKEY", "Atm. model");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "CeresSetup",     "fCeresSetupName",     "fCeresSetupKEY", "Ceres setup");
+    printf("  </td>\n");
+
+    printf("  </tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintMCRunStatMenu()
+{
+    printf(" <div id=\"stat\" style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr><td>\n");
+
+    PrintStatusMenu("Corsika",    "Corsika");
+    printf("  </td><td>\n");
+    PrintStatusMenu("Ceres",    "Ceres");
+    printf("  </td><td>\n");
+    PrintStatusMenu("SequenceFile",    "SequenceFile");
+
+    printf("  </td></tr><tr><td>\n");
+
+    PrintStatusMenu("Callisto",    "Callisto");
+    printf("  </td><td>\n");
+    PrintStatusMenu("Star",    "Star");
+
+    printf(" </td></tr></table>\n");
+    printf(" <p>\n");
+    printf(" </div><p>\n");
+}
+
+//cta mc stuff
+function PrintCTAMCRunInfoMenu($host,$user,$pw,$db)
+{
+    printf(" <div id='info' style='display:none'>");
+    printf(" <table>\n");
+    printf("  <tr valign='top'>\n");
+
+    CheckBox("fNumEvents",        "Num of events");
+    CheckBox("fObsLevel",         "Observation level");
+    CheckBox("fLinks",            "Links");
+
+    printf("  </tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "ParticleType",     "fParticleTypeName",     "fParticleTypeKEY", "Particle type");
+    printf("  </td><td>\n");
+
+    printf("  </tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintCTAMCRunStatMenu()
+{
+    printf(" <div id=\"stat\" style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr><td>\n");
+
+    PrintStatusMenu("fCorsikaSimTelarray",    "Corsika and Simtel");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fChimp",   "Chimp");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fCTAStar", "Star");
+
+    printf("  </td></tr><tr><td>\n");
+
+    PrintStatusMenu("fStereoB", "StereoB");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fStereoC", "StereoC");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fStereoG", "StereoG");
+
+    printf(" </td></tr></table>\n");
+    printf(" <p>\n");
+    printf(" </div><p>\n");
+}
+
+//magic data stuff
+function PrintRunInfoMenu()
+{
+    printf(" <div id='info' style='display:none'>");
+    printf(" <table>\n");
+    printf("  <tr>\n");
+
+    CheckBox("fRunStart",         "Run start time");
+    CheckBox("fL2RatePresc",      "L2 presc Rate");
+    CheckBox("fDaqStoreRate",     "DAQ Storage Rate");
+    CheckBox("fAzimuth",          "Azimuth");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fRunStop",          "Run stop time");
+    CheckBox("fL2RateUnpresc",    "L2 unpresc Rate");
+    CheckBox("fDaqTriggerRate",   "DAQ Trigger Rate");
+    CheckBox("fZenithDistance",   "Zenith distance");
+
+    printf("  </tr><tr>\n");
+
+    //        CheckBox("fFormatVersion",    "File format");
+    CheckBox("fNumEvents",        "Num of events");
+    CheckBox("fMeanTriggerRate",  "Mean Trigger Rate");
+    CheckBox("fL3TriggerRate",    "L3 Trigger Rate");
+    CheckBox("fSequenceFirst",    "Sequence Number");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fTest",             "incl. TestSources");
+    CheckBox("fLinks",            "Links");
+    CheckBox("fWheelPos1",        "Wheel Position 1");
+    CheckBox("fWheelPos2",        "Wheel Position 2");
+
+    printf("  </tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintRunStatMenu()
+{
+    printf(" <div id=\"stat\" style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr><td>\n");
+
+    PrintStatusMenu("fCCFileAvail",    "CC File available");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fCaCoFileAvail",  "Caco File available");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fRawFileAvail",   "Rawfile available");
+
+    printf("  </td></tr><tr><td>\n");
+
+    PrintStatusMenu("fTimingCorrection",  "Timing Correction");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fCaCoFileFound",     "Caco File");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fDataCheckDone",        "DataCheck");
+
+    printf(" </td></tr></table>\n");
+    printf(" <p>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintRunInfo2Menu($host,$user,$pw,$db)
+{
+    printf(" <div id='info2' style='display:none'>");
+    printf(" <table>\n");
+    printf("  <tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "RunType",     "fRunTypeName",     "fRunTypeKEY", "Run type");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Source",      "fSourceName",      "fSourceKEY", "Source Name");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "HvSettings",  "fHvSettingsName",  "fHvSettingsKEY", "HV Settings");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "L1TriggerTable", "fL1TriggerTableName", "fL1TriggerTableKEY", "L1 Trigger Table");
+    printf("  </td></tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "TestFlag",  "fTestFlagName",  "fTestFlagKEY", "Test Flag");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Project",     "fProjectName",     "fProjectKEY", "Project Name");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "DiscriminatorThresholdTable",  "fDiscriminatorThresholdTableName",  "fDiscriminatorThresholdTableKEY", "DT Table");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "L2TriggerTable", "fL2TriggerTableName", "fL2TriggerTableKEY", "L2 Trigger Table");
+    printf("  </td></tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "ExcludedFDA", "fExcludedFDAName", "fExcludedFDAKEY", "Exclusions");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "LightConditions",  "fLightConditionsName",  "fLightConditionsKEY", "Light Conditions");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "CalibrationScript",  "fCalibrationScriptName",  "fCalibrationScriptKEY", "Cal Script");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "L3TriggerTable", "fL3TriggerTableName", "fL3TriggerTableKEY", "L3 Trigger Table");
+    printf("  </td></tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "MagicNumber", "fMagicNumberName", "fMagicNumberKEY", "Magic Number");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "ObservationMode",   "fObservationModeName", "fObservationModeKEY", "Obs. Mode");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "SumTriggerFlag",   "fSumTriggerFlagName", "fSumTriggerFlagKEY", "SumTrigger Flag");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "TriggerDelayTable",  "fTriggerDelayTableName",  "fTriggerDelayTableKEY", "Trigger Delay Table");
+    printf("  </td></tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Cycle",   "fCycleName", "fCycleKEY", "Cycle");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "PI",   "fPIName", "fPIKEY", "PI");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "WorkingGroup",   "fWorkingGroupName", "fWorkingGroupKEY", "Working Group");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Proposal",   "fProposalName", "fProposalKEY", "Proposal");
+    printf(" </td></tr></table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintSequInfoMenu()
+{
+    printf(" <div id='info' style='display:none'>");
+    printf(" <table>\n");
+
+    printf("<tr><td align='center'>\n");
+    printf("  <tr>\n");
+
+    CheckBox("fRunStart",          "Start time");
+    CheckBox("fRunStop",           "Stop time");
+    CheckBox("fNumEvents",         "Num of events");
+    CheckBox("fRunTime/60",        "Duration");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fZenithDistanceMin", "Zenith distance min");
+    CheckBox("fZenithDistanceMax", "Zenith distance max");
+    CheckBox("fAzimuthMin",        "Azimuth min");
+    CheckBox("fAzimuthMax",        "Azimuth max");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fSequenceLast",      "Last run");
+    CheckBox("fLinks",             "Links");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fOnlySum",           "only sumtrigger");
+    CheckBox("fTest",              "incl. TestSources");
+    CheckBox("fOff",               "incl. offsources");
+    CheckBox("fOnlyOff",           "only offsources");
+
+    printf("  </tr></table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintSequInfo2Menu($host,$user,$pw,$db)
+{
+    printf(" <div id='info2' style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Source",                      "fSourceName",                      "fSourceKEY",                      "Source Name");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Project",                     "fProjectName",                     "fProjectKEY",                     "Project Name");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "L1TriggerTable",              "fL1TriggerTableName",              "fL1TriggerTableKEY",              "L1Trigger Table");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Cycle",   "fCycleName", "fCycleKEY", "Cycle");
+    printf("  </td></tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "LightConditions",             "fLightConditionsName",             "fLightConditionsKEY",             "Light Conditions");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "HvSettings",                  "fHvSettingsName",                  "fHvSettingsKEY",                  "HV Settings");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "L2TriggerTable",              "fL2TriggerTableName",              "fL2TriggerTableKEY",              "L2Trigger Table");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "PI",   "fPIName", "fPIKEY", "PI");
+    printf("  </td></tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "ObservationMode",             "fObservationModeName",             "fObservationModeKEY",             "Obs. Mode");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "DiscriminatorThresholdTable", "fDiscriminatorThresholdTableName", "fDiscriminatorThresholdTableKEY", "DT Table");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "L3TriggerTable",              "fL3TriggerTableName",              "fL3TriggerTableKEY",              "L3Trigger Table");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "WorkingGroup",   "fWorkingGroupName", "fWorkingGroupKEY", "Working Group");
+    printf("  </td></tr><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "SumTriggerFlag",              "fSumTriggerFlagName",              "fSumTriggerFlagKEY",              "SumTrigger Flag");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "TriggerDelayTable",           "fTriggerDelayTableName",           "fTriggerDelayTableKEY",           "Trigger Delay Table");
+    printf("  </td><td>\n");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Proposal",   "fProposalName", "fProposalKEY", "Proposal");
+//    printf("  </td><td>\n");
+//    PrintPullDown($host, $user, $pw, $db, "ManuallyChanged",             "fManuallyChangedName",             "fManuallyChangedKEY",             "Manually changed");
+//    printf("  </td><td>\n");
+//    PrintPullDown($host, $user, $pw, $db, "TestFlag",                    "fTestFlagName",                    "fTestFlagKEY",                    "Test Flag");
+    printf("  </td></tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintLimitsMenu($limitsmean, $limitsmin, $limitsmax, $alias, $old)
+{
+    printf("<div id='limits' style='display:none'>\n");
+    printf("  <table>\n");
+    printf("  <tr><th colspan='3'>Limits</th></tr>\n");
+    printf("  <tr><td valign='top'>\n");
+
+    printf("   <table>\n");
+    printf("  <tr><th>Name </th><th> Mean </th><th> Rms </th></tr>\n");
+
+    foreach($limitsmean as $key => $element)
+    {
+        printf("<tr><td>%s</td>\n", $alias[$key]);
+        $mean=$key . "Mean";
+        $limitmean=$_GET[$mean];
+        printf("<td><input name=\"%sMean\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limitmean);
+        $rms2=$key . "Rms";
+        $limitrms=$_GET[$rms2];
+        printf("<td><input name=\"%sRms\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limitrms);
+        printf("</tr>\n");
+    }
+
+    if (empty($old))
+    {
+        printf("  </table>\n");
+        printf("  </td>\n");
+        printf("  <td valign='top'>\n");
+        printf("   <table>\n");
+    }
+
+    printf("  <tr><th>Name </th><th> Min </th><th> Min2 </th></tr>\n");
+    foreach($limitsmin as $key => $element)
+    {
+        printf("<tr><td>%s</td>\n", $alias[$key]);
+        $level1=$key . "1";
+        $limit1=$_GET[$level1];
+        printf("<td><input name=\"%s1\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limit1);
+        $level2=$key . "2";
+        $limit2=$_GET[$level2];
+        printf("<td><input name=\"%s2\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limit2);
+        printf("</tr>\n");
+    }
+
+    if (empty($old))
+    {
+        printf("  </table>\n");
+        printf("  </td>\n");
+        printf("  <td valign='top'>\n");
+        printf("   <table>\n");
+    }
+
+    printf("  <tr><th>Name </th><th> Max </th><th> Max2 </th></tr>\n");
+    foreach($limitsmax as $key => $element)
+    {
+        printf("<tr><td>%s</td>\n", $alias[$key]);
+        $level1=$key . "1";
+        $limit1=$_GET[$level1];
+        printf("<td><input name=\"%s1\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limit1);
+        $level2=$key . "2";
+        $limit2=$_GET[$level2];
+        printf("<td><input name=\"%s2\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limit2);
+        printf("</tr>\n");
+    }
+    printf("  </table>\n");
+
+    printf("  </td></tr></table>\n");
+    printf("<p>\n");
+    printf("</div>\n");
+}
+
+function PrintSequStatMenu()
+{
+    printf(" <div id='stat' style='display:none'>\n");
+    printf(" <table><tr><td>\n");
+
+    PrintStatusMenu("fAllFilesAvail",       "Files avail");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fCallisto",            "Callisto");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fStar",                "Star");
+    printf("  </td></tr><tr><td>\n");
+    PrintStatusMenu("fSequenceFileWritten", "Sequfile");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fFillCallisto",        "Fillcallisto");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fFillStar",            "Fillstar");
+
+    printf("</td></tr> </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintFailMenu()
+{
+    printf(" <div id='fail' style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr>\n");
+
+    CheckBox("fStartTime",     "ProcessTime");
+    CheckBox("fFailedTime",    "FailTime");
+    CheckBox("fReturnCode",    "RetCode");
+    CheckBox("fProgramId",     "ProgramId");
+
+    printf("  </tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintCalMenu()
+{
+    printf(" <div id='cal' style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr>\n");
+
+    CheckBox("fUnsuitableInner",     "Unsuitable inner");
+    CheckBox("fUnsuitableOuter",     "Unsuitable outer");
+    CheckBox("fUnreliableInner",     "Unreliable inner");
+    CheckBox("fUnreliableOuter",     "Unreliable outer");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fUnsuitable50",        "Unsuitable (50%)");
+    CheckBox("fUnsuitable01",        "Unsuitable (1%)");
+    CheckBox("fUnsuitableMax",       "UnsuitableMax");
+    CheckBox("fDeadMax",             "DeadMax");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fIsolatedInner",       "Isolated inner");
+    CheckBox("fIsolatedOuter",       "Isolated outer");
+    CheckBox("fIsolatedMaxCluster",  "IsolatedMaxCluster");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fArrTimeMeanInner",    "ArrTimeMean inner ");
+    CheckBox("fArrTimeMeanOuter",    "ArrTimeMean outer ");
+    CheckBox("fArrTimeRmsInner",     "ArrTimeRms inner ");
+    CheckBox("fArrTimeRmsOuter",     "ArrTimeRms outer ");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fMeanPedRmsInner",     "MeanPedRms inner");
+    CheckBox("fMeanPedRmsOuter",     "MeanPedRms outer");
+    CheckBox("fMeanSignalInner",     "MeanSignal inner");
+    CheckBox("fMeanSignalOuter",     "MeanSignal outer");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fConvFactorInner",     "Conv inner ");
+    CheckBox("fConvFactorOuter",     "Conv outer ");
+    CheckBox("fPulsePosMean",        "Mean PulsePos");
+    CheckBox("fPulsePosCalib",       "Cal PulsePos");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fRateTrigEvts",        "Rate Trig evts");
+    CheckBox("fRateSumEvts",         "Rate Sum Trig evts");
+    CheckBox("fRatePedEvts",         "Rate Ped evts");
+    CheckBox("fRatePedTrigEvts",     "Rate Ped Trig evts");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fRateCalEvts",         "Rate Cal evts");
+    CheckBox("fRateNullEvts",        "Rate Null evts");
+    CheckBox("fRateUnknownEvts",     "Rate Unknown evts");
+    CheckBox("fRatioCalEvents",      "Ratio Cal evts");
+
+    printf(" </tr></table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintStarMenu()
+{
+    printf(" <div id='star' style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr>\n");
+
+    CheckBox("fDataRate",           "CleanedEvtRate");
+    CheckBox("fMeanNumberIslands",  "MeanNumIslands");
+    CheckBox("fMaxHumidity",        "MaxHumidity");
+    CheckBox("fInhomogeneity",      "Inhomogeneity");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fMuonRate",           "MuonRate");
+    CheckBox("fMuonNumber",         "MuonNumber");
+    CheckBox("fRatio",              "Ratio");
+    CheckBox("fPSF",                "PSF");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fSparkRate",      "SparkRate");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fEffOnTime",          "EffOnTime");
+    CheckBox("fEffOnTime/fRunTime", "RelOnTime");
+    CheckBox("fBrightnessMed",      "SkyBrightnessMed");
+    CheckBox("fBrightnessRMS",      "SkyBrightnessRMS");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fNumStarsMed",        "# id. Stars");
+    CheckBox("fNumStarsRMS",        "RMS id. Stars");
+    CheckBox("fNumStarsCorMed",     "# cor. Stars");
+    CheckBox("fNumStarsCorRMS",     "RMS cor. Stars");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fAvgWindSpeed",       "Avg wind speed");
+    CheckBox("fAvgTemperature",     "Avg temperature");
+    CheckBox("fAvgHumidity",        "Avg humidity");
+    CheckBox("fAvgTempSky",         "Avg sky temperature");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fAvgCloudiness",      "Avg cloudiness");
+    CheckBox("fRmsCloudiness",      "RMS cloudiness");
+
+    printf("  </tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintDataSetInfoMenu($host,$user,$pw,$db)
+{
+    printf(" <div id=\"info\" style='display:none'>");
+    printf(" <table>\n");
+    printf("  <tr>\n");
+
+    CheckBox("fDataSetName",       "Name");
+    CheckBox("fComment",           "Comment");
+    CheckBox("fRunTime",           "Uptime");
+    CheckBox("fRunStart",          "Start");
+    CheckBox("fRunStop",           "Stop");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fZenithDistanceMin", "ZdMin");
+    CheckBox("fZenithDistanceMax", "ZdMax");
+    CheckBox("fLinks",             "Links");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fEffOnTime/3600",    "EffOnTime");
+    CheckBox("fExcessEvents",      "ExcEvts");
+    CheckBox("fBackgroundEvents",  "BgEvts");
+    CheckBox("fSignalEvents",      "SignEvts");
+    CheckBox("fSignificance",      "Sign");
+
+    printf("  </tr><tr>\n");
+
+    CheckBox("fScaleFactor",                                  "Scale");
+    CheckBox("fExcessEvents*60/fEffOnTime",                   "ExcRate");
+    CheckBox("fBackgroundEvents*60/fEffOnTime",               "BgRate");
+    CheckBox("fSignalEvents*60/fEffOnTime",                   "SignRate");
+    CheckBox("Round(fSignificance/Sqrt(fEffOnTime/3600),2)",  "SignfRate");
+
+    printf("  </tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintDataSetInfoMenu2($host,$user,$pw,$db)
+{
+    printf(" <div id='info2' style='display:none'>");
+    printf("  <table><tr><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "Source",          "fSourceName",          "fSourceKEY",          "Source Name");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "ObservationMode", "fObservationModeName", "fObservationModeKEY", "Observation Mode");
+    printf("  </td><td>\n");
+    PrintPullDown($host, $user, $pw, $db, "User",            "fUserName",            "fUserKEY",            "User");
+    printf("  </td></tr>\n");
+    printf(" </table>\n");
+    printf("</div>");
+}
+
+function PrintDataSetStatMenu($host,$user,$pw,$db)
+{
+    printf(" <div id=\"stat\" style='display:none'>\n");
+    printf(" <table>\n");
+    printf("  <tr>\n");
+
+    printf("  <td>\n");
+    PrintStatusMenu("fDataSetInserted", "DataSet Inserted");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fDataSetFileWritten", "DataSetFile");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fStarFilesAvail",  "FilesAvail");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fGanymed",         "Ganymed");
+    printf("  </td><td>\n");
+    PrintStatusMenu("fFillGanymed",     "FillGanymed");
+    printf("  </tr>\n");
+    printf(" </table>\n");
+    printf(" </div><p>\n");
+}
+
+function PrintRunRangeMenu($host,$user,$pw,$db)
+{
+    if (empty($_GET["fRunMin"]))
+        $min = GetMin("fRunNumber", "RunData", $host, $user, $pw, $db);
+    else
+        $min = $_GET["fRunMin"];
+
+    if (empty($_GET["fRunMax"]))
+        $max = GetMax("fRunNumber", "RunData", $host, $user, $pw, $db);
+    else
+        $max = $_GET["fRunMax"];
+
+    printf("Runs&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">\n", $min);
+    printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+}
+
+function PrintCTAMCRunRangeMenu($host,$user,$pw,$db)
+{
+    if (empty($_GET["fRunMin"]))
+        $min = GetMin("fMCRunNumber", "MCRunData", $host, $user, $pw, $db);
+    else
+        $min = $_GET["fRunMin"];
+
+    if (empty($_GET["fRunMax"]))
+        $max = GetMax("fMCRunNumber", "MCRunData", $host, $user, $pw, $db);
+    else
+        $max = $_GET["fRunMax"];
+
+    printf("Runs&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">\n", $min);
+    printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+}
+
+function PrintMCRunRangeMenu($host,$user,$pw,$db)
+{
+    if (empty($_GET["fRunMin"]))
+        $min = GetMin("fRunNumber", "CeresInfo", $host, $user, $pw, $db);
+    else
+        $min = $_GET["fRunMin"];
+
+    if (empty($_GET["fRunMax"]))
+        $max = GetMax("fRunNumber", "CeresInfo", $host, $user, $pw, $db);
+    else
+        $max = $_GET["fRunMax"];
+
+    printf("Runs&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">\n", $min);
+    printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+}
+
+function PrintSequRangeMenu($host,$user,$pw,$db)
+{
+    if (empty($_GET["fRunMin"]))
+        $min = GetMin("fSequenceFirst", "Sequences", $host, $user, $pw, $db);
+    else
+        $min = $_GET["fRunMin"];
+
+    if (empty($_GET["fRunMax"]))
+        $max = GetMax("fSequenceFirst", "Sequences", $host, $user, $pw, $db);
+    else
+        $max = $_GET["fRunMax"];
+
+    printf("Sequences&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">\n", $min);
+    printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+}
+
+function PrintDataSetRangeMenu($host,$user,$pw,$db)
+{
+    if (empty($_GET["fRunMin"]))
+        $min = GetMin("fDataSetNumber", "DataSets", $host, $user, $pw, $db);
+    else
+        $min = $_GET["fRunMin"];
+
+    if (empty($_GET["fRunMax"]))
+        $max = GetMax("fDataSetNumber", "DataSets", $host, $user, $pw, $db);
+    else
+        $max = $_GET["fRunMax"];
+
+    printf("DataSets&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">\n", $min);
+    printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+}
+
+function PrintZdRangeMenu($host,$user,$pw,$db)
+{
+    if (empty($_GET["fZDMin"]))
+        $zdmin = GetMin("fZenithDistanceMin", "Sequences", $host, $user, $pw, $db);
+    else
+        $zdmin = $_GET["fZDMin"];
+
+    if (empty($_GET["fZDMax"]))
+        $zdmax = GetMax("fZenithDistanceMax", "Sequences", $host, $user, $pw, $db);
+    else
+        $zdmax = $_GET["fZDMax"];
+
+    printf("ZenithDistance&nbsp;from&nbsp;<input name=\"fZDMin\" type=\"text\" size=\"2\" maxlength=\"2\" value=\"%s\">\n", $zdmin);
+    printf("to&nbsp;<input name=\"fZDMax\" type=\"text\" size=\"2\" maxlength=\"2\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $zdmax);
+}
+
+function PrintNightRangeMenu($host,$user,$pw,$db, $table)
+{
+    if (empty($_GET["fStartDate"]))
+        $timemin = GetMin("Date_Format(fRunStart, '%Y-%m-%d')", $table, $host, $user, $pw, $db);
+    else
+        $timemin = $_GET["fStartDate"];
+
+    if (empty($_GET["fStopDate"]))
+        $timemax = GetMaxDate("Date_Format(fRunStart, '%Y-%m-%d')", $table, $host, $user, $pw, $db);
+    else
+        $timemax = $_GET["fStopDate"];
+
+    printf("Night&nbsp;(yyyy-mm-dd)&nbsp;from&nbsp;<input name=\"fStartDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">\n", $timemin);
+    printf("to&nbsp;<input name=\"fStopDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">&nbsp;&nbsp;&nbsp;&nbsp;\n", $timemax);
+}
+
+function PrintStarRangeMenu($host,$user,$pw,$db)
+{
+    if (empty($_GET["fStarStart"]))
+        $starmin = GetMin("fStar", "SequenceProcessStatus", $host, $user, $pw, $db);
+    else
+        $starmin = $_GET["fStarStart"];
+
+    if (empty($_GET["fStarStop"]))
+        $starmax = GetMax("fStar", "SequenceProcessStatus", $host, $user, $pw, $db);
+    else
+        $starmax = $_GET["fStarStop"];
+
+    printf("<p>StarDone&nbsp;(yyyy-mm-dd hh:mm:ss)&nbsp;from&nbsp;<input name=\"fStarStart\" type=\"text\" size=\"19\" maxlength=\"19\" value=\"%s\">\n", $starmin);
+    printf("to&nbsp;<input name=\"fStarStop\" type=\"text\" size=\"19\" maxlength=\"19\" value=\"%s\">&nbsp;&nbsp;&nbsp;&nbsp;\n", $starmax);
+}
+
+function PrintGroupByDateMenu()
+{
+    printf("Group by Date ");
+    printf("<select name='fGroupByDate' size='1' class='Width'>\n");
+    if (empty($_GET["fGroupByDate"]) || $_GET["fGroupByDate"]==0)
+        printf("    <option value='0' selected>--- NO GROUP BY ---</option>\n");
+    else
+        printf("    <option value='0'>--- NO GROUP BY ---</option>\n");
+    $dates=array("Year", "Month","Night");
+    foreach ($dates as $date)
+    {
+        if ($_GET["fGroupByDate"]==$date)
+            printf("    <option value='%s' selected> %s </option>\n", $date, $date);
+        else
+            printf("    <option value='%s'> %s </option>\n", $date, $date);
+    }
+    printf("   </select>\n");
+}
+
+function PrintSourceMenu($host,$user,$pw,$db)
+{
+    printf("Source&nbsp;(<A HREF=\"regexp.html\">regexp</A>)&nbsp;<input name=\"fSourceN\" type=\"text\" size=\"15\" maxlength=\"15\" value=\"");
+    if (!empty($_GET["fSourceN"]))
+        printf("%s", $_GET["fSourceN"]);
+    printf("\">&nbsp;&nbsp;&nbsp;\n");
+}
+function PrintSequMenu($host,$user,$pw,$db)
+{
+    printf("Sequ#&nbsp;<input name=\"fSequenceNo\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"");
+    if (!empty($_GET["fSequenceNo"]))
+        printf("%s", $_GET["fSequenceNo"]);
+    printf("\">&nbsp;&nbsp;&nbsp;\n");
+}
+
+function PrintNumResPullDown()
+{
+    printf(" Results:\n");
+    printf(" <select name=\"fNumResults\">\n");
+
+    $numres = array("10", "20", "50", "100", "200", "500", "1000", "2000");
+    foreach ($numres as $element)
+    {
+        if ($element==$_GET["fNumResults"])
+            printf("<option value=\"%s\" selected>%3s</option>\n", $element, $element);
+        else
+            printf("<option value=\"%s\">%3s</option>\n", $element, $element);
+    }
+    printf(" </select>\n");
+    printf(" &nbsp;&nbsp;&nbsp;\n");
+}
+
+function PrintButtons($page)
+{
+    printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+    printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"%s\"'>&nbsp;&nbsp;&nbsp;\n", $page);
+//    printf("<p>");
+    if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+    {
+        printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&amp;fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", htmlspecialchars($_SERVER["REQUEST_URI"]));
+        printf("<input class='Width' type='button' value='Print' onClick='self.location.href=\"%s&amp;fPrintTable=1\"'>&nbsp;&nbsp;&nbsp;\n", htmlspecialchars($_SERVER["REQUEST_URI"]));
+        printf("MySqlQuery: <img id='showquerybutton' src='../plus.png' alt='+' onClick='showhide(\"showquery\")'>\n");
+    }
+}
+
+function InitInfo($first)
+{
+    if (empty($_GET["fNumResults"]))
+        $_GET["fNumResults"]="20";
+
+    if (empty($_GET["fRunStart"]))
+        $_GET["fRunStart"]="Off";
+
+    if (empty($_GET["fRunStop"]))
+        $_GET["fRunStop"]="Off";
+
+    if (empty($_GET["fTest"]))
+        $_GET["fTest"]="Off";
+
+    if (empty($_GET["fSourceName"]))
+        $_GET["fSourceName"]="Off";
+
+    if (empty($_GET["fProjectName"]))
+        $_GET["fProjectName"]="Off";
+
+    if (empty($_GET["fL1TriggerTableName"]))
+        $_GET["fL1TriggerTableName"]="Off";
+
+    if (empty($_GET["fL2TriggerTableName"]))
+        $_GET["fL2TriggerTableName"]="Off";
+
+    if (empty($_GET["fL3TriggerTableName"]))
+        $_GET["fL3TriggerTableName"]="Off";
+
+    if (empty($_GET["fHvSettingsName"]))
+        $_GET["fHvSettingsName"]="Off";
+
+    if (empty($_GET["fDiscriminatorThresholdTableName"]))
+        $_GET["fDiscriminatorThresholdTableName"]="Off";
+
+    if (empty($_GET["fTriggerDelayTableName"]))
+        $_GET["fTriggerDelayTableName"]="Off";
+
+    if (empty($_GET["fLightConditionsName"]))
+        $_GET["fLightConditionsName"]="Off";
+
+    if (empty($_GET["fTestFlagName"]))
+        $_GET["fTestFlagName"]="Off";
+
+    if (empty($_GET["fCycleName"]))
+        $_GET["fCycleName"]="Off";
+
+    if (empty($_GET["fPIName"]))
+        $_GET["fPIName"]="Off";
+
+    if (empty($_GET["fWorkingGroupName"]))
+        $_GET["fWorkingGroupName"]="Off";
+
+    if (empty($_GET["fProposalName"]))
+        $_GET["fProposalName"]="Off";
+}
+
+function InitRunStatus($first)
+{
+   if (empty($_GET["fDataCheckDone"]))
+        $_GET["fDataCheckDone"]="Off";
+
+    if (empty($_GET["fDataCheckDoneStatus"]))
+        $_GET["fDataCheckDoneStatus"]="0";
+
+    if (empty($_GET["fCCFileAvail"]))
+        $_GET["fCCFileAvail"]="Off";
+
+    if (empty($_GET["fCCFileAvailStatus"]))
+        $_GET["fCCFileAvailStatus"]="0";
+
+    if (empty($_GET["fCaCoFileAvail"]))
+        $_GET["fCaCoFileAvail"]=$first?"On":"";
+
+    if (empty($_GET["fCaCoFileAvailStatus"]))
+        $_GET["fCaCoFileAvailStatus"]="0";
+
+    if (empty($_GET["fCaCoFileFound"]))
+        $_GET["fCaCoFileFound"]="Off";
+
+    if (empty($_GET["fCaCoFileFoundStatus"]))
+        $_GET["fCaCoFileFoundStatus"]="0";
+
+    if (empty($_GET["fRawFileAvail"]))
+        $_GET["fRawFileAvail"]="Off";
+
+    if (empty($_GET["fRawFileAvailStatus"]))
+        $_GET["fRawFileAvailStatus"]="0";
+
+    if (empty($_GET["fTimingCorrection"]))
+        $_GET["fTimingCorrection"]="Off";
+
+    if (empty($_GET["fTimingCorrectionStatus"]))
+        $_GET["fTimingCorrectionStatus"]="0";
+}
+
+function InitRunInfo($first)
+{
+    InitRunStatus($first);
+    InitInfo($first);
+
+    if (empty($_GET["fNumEvents"]))
+        $_GET["fNumEvents"]=$first?"Off":"";
+
+    if (empty($_GET["fLinks"]))
+        $_GET["fLinks"]=$first?"On":"";
+
+    if (empty($_GET["fFormatVersion"]))
+        $_GET["fFormatVersion"]="Off";
+
+    if (empty($_GET["fAzimuth"]))
+        $_GET["fAzimuth"]="Off";
+
+    if (empty($_GET["fZenithDistance"]))
+        $_GET["fZenithDistance"]="Off";
+
+    if (empty($_GET["fRunTypeName"]))
+        $_GET["fRunTypeName"]="Off";
+
+    if (empty($_GET["fExcludedFDAName"]))
+        $_GET["fExcludedFDAName"]="Off";
+
+    if (empty($_GET["fMagicNumberName"]))
+        $_GET["fMagicNumberName"]="Off";
+
+    if (empty($_GET["fObservationModeName"]))
+        $_GET["fObservationModeName"]="Off";
+
+    if (empty($_GET["fSumTriggerFlagName"]))
+        $_GET["fSumTriggerFlagName"]="Off";
+
+    if (empty($_GET["fMeanTriggerRate"]))
+        $_GET["fMeanTriggerRate"]="Off";
+
+    if (empty($_GET["fCalibrationScriptName"]))
+        $_GET["fCalibrationScriptName"]="Off";
+
+    if (empty($_GET["fTestFlagName"]))
+        $_GET["fTestFlagName"]="Off";
+
+    if (empty($_GET["fDaqStoreRate"]))
+        $_GET["fDaqStoreRate"]="Off";
+
+    if (empty($_GET["fDaqTriggerRate"]))
+        $_GET["fDaqTriggerRate"]="Off";
+
+    if (empty($_GET["fL2RatePresc"]))
+        $_GET["fL2RatePresc"]="Off";
+
+    if (empty($_GET["fL3TriggerRate"]))
+        $_GET["fL3TriggerRate"]="Off";
+
+    if (empty($_GET["fWheelPos1"]))
+        $_GET["fWheelPos1"]="Off";
+
+    if (empty($_GET["fWheelPos2"]))
+        $_GET["fWheelPos2"]="Off";
+
+    if (empty($_GET["fL2RateUnpresc"]))
+        $_GET["fL2RateUnpresc"]="Off";
+
+    if (empty($_GET["fSequenceFirst"]))
+        $_GET["fSequenceFirst"]="Off";
+
+    if (empty($_GET["fSequenceNo"]))
+        $_GET["fSequenceNo"]="";
+}
+
+function InitSequStatus($first)
+{
+    if (empty($_GET["fSequenceFileWritten"]))
+        $_GET["fSequenceFileWritten"]="Off";
+
+    if (empty($_GET["fSequenceFileWrittenStatus"]))
+        $_GET["fSequenceFileWrittenStatus"]="0";
+
+    if (empty($_GET["fAllFilesAvail"]))
+        $_GET["fAllFilesAvail"]="Off";
+
+    if (empty($_GET["fAllFilesAvailStatus"]))
+        $_GET["fAllFilesAvailStatus"]="0";
+
+    if (empty($_GET["fCallisto"]))
+        $_GET["fCallisto"]="Off";
+
+    if (empty($_GET["fCallistoStatus"]))
+        $_GET["fCallistoStatus"]="0";
+
+    if (empty($_GET["fFillCallisto"]))
+        $_GET["fFillCallisto"]="Off";
+
+    if (empty($_GET["fFillCallistoStatus"]))
+        $_GET["fFillCallistoStatus"]="0";
+
+    if (empty($_GET["fStar"]))
+        $_GET["fStar"]="Off";
+
+    if (empty($_GET["fStarStatus"]))
+        $_GET["fStarStatus"]="0";
+
+    if (empty($_GET["fFillStar"]))
+        $_GET["fFillStar"]="Off";
+
+    if (empty($_GET["fFillStarStatus"]))
+        $_GET["fFillStarStatus"]="0";
+}
+
+function InitStarInfo($first)
+{
+    if (empty($_GET["fMeanNumberIslands"]))
+        $_GET["fMeanNumberIslands"]="Off";
+
+    if (empty($_GET["fPSF"]))
+        $_GET["fPSF"]="Off";
+
+    if (empty($_GET["fRatio"]))
+        $_GET["fRatio"]="Off";
+
+    if (empty($_GET["fMuonNumber"]))
+        $_GET["fMuonNumber"]="Off";
+
+    if (empty($_GET["fEffOnTime"]))
+        $_GET["fEffOnTime"]="Off";
+
+    if (empty($_GET["fEffOnTime/fRunTime"]))
+        $_GET["fEffOnTime/fRunTime"]="Off";
+
+    if (empty($_GET["fMuonRate"]))
+        $_GET["fMuonRate"]="Off";
+
+    if (empty($_GET["fInhomogeneity"]))
+        $_GET["fInhomogeneity"]="Off";
+
+    if (empty($_GET["fDataRate"]))
+        $_GET["fDataRate"]="Off";
+
+    if (empty($_GET["fSparkRate"]))
+        $_GET["fSparkRate"]="Off";
+
+    if (empty($_GET["fMaxHumidity"]))
+        $_GET["fMaxHumidity"]="Off";
+
+    if (empty($_GET["fBrightnessMed"]))
+        $_GET["fBrightnessMed"]="Off";
+
+    if (empty($_GET["fBrightnessRMS"]))
+        $_GET["fBrightnessRMS"]="Off";
+
+    if (empty($_GET["fNumStarsMed"]))
+        $_GET["fNumStarsMed"]="Off";
+
+    if (empty($_GET["fNumStarsRMS"]))
+        $_GET["fNumStarsRMS"]="Off";
+
+    if (empty($_GET["fNumStarsCorMed"]))
+        $_GET["fNumStarsCorMed"]="Off";
+
+    if (empty($_GET["fNumStarsCorRMS"]))
+        $_GET["fNumStarsCorRMS"]="Off";
+
+    if (empty($_GET["fAvgWindSpeed"]))
+        $_GET["fAvgWindSpeed"]="Off";
+
+    if (empty($_GET["fAvgTemperature"]))
+        $_GET["fAvgTemperature"]="Off";
+
+    if (empty($_GET["fAvgHumidity"]))
+        $_GET["fAvgHumidity"]="Off";
+
+    if (empty($_GET["fAvgTempSky"]))
+        $_GET["fAvgTempSky"]="Off";
+
+    if (empty($_GET["fAvgCloudiness"]))
+        $_GET["fAvgCloudiness"]="Off";
+
+    if (empty($_GET["fRmsCloudiness"]))
+        $_GET["fRmsCloudiness"]="Off";
+}
+
+function InitCalInfo($first)
+{
+    if (empty($_GET["fUnreliableInner"]))
+        $_GET["fUnreliableInner"]="Off";
+
+    if (empty($_GET["fUnsuitableOuter"]))
+        $_GET["fUnsuitableOuter"]="Off";
+
+    if (empty($_GET["fUnreliableOuter"]))
+        $_GET["fUnreliableOuter"]="Off";
+
+    if (empty($_GET["fUnsuitableInner"]))
+        $_GET["fUnsuitableInner"]="Off";
+
+    if (empty($_GET["fUnsuitable50"]))
+        $_GET["fUnsuitable50"]="Off";
+
+    if (empty($_GET["fUnsuitable01"]))
+        $_GET["fUnsuitable01"]="Off";
+
+    if (empty($_GET["fUnsuitableMax"]))
+        $_GET["fUnsuitableMax"]="Off";
+
+    if (empty($_GET["fDeadMax"]))
+        $_GET["fDeadMax"]="Off";
+
+    if (empty($_GET["fRateTrigEvts"]))
+        $_GET["fRateTrigEvts"]="Off";
+
+    if (empty($_GET["fRateSumEvts"]))
+        $_GET["fRateSumEvts"]="Off";
+
+    if (empty($_GET["fRatePedEvts"]))
+        $_GET["fRatePedEvts"]="Off";
+
+    if (empty($_GET["fRatePedTrigEvts"]))
+        $_GET["fRatePedTrigEvts"]="Off";
+
+    if (empty($_GET["fRateCalEvts"]))
+        $_GET["fRateCalEvts"]="Off";
+
+    if (empty($_GET["fRateNullEvts"]))
+        $_GET["fRateNullEvts"]="Off";
+
+    if (empty($_GET["fRateUnknownEvts"]))
+        $_GET["fRateUnknownEvts"]="Off";
+
+    if (empty($_GET["fRatioCalEvents"]))
+        $_GET["fRatioCalEvents"]="Off";
+
+    if (empty($_GET["fPulsePosCalib"]))
+        $_GET["fPulsePosCalib"]="Off";
+
+    if (empty($_GET["fIsolatedInner"]))
+        $_GET["fIsolatedInner"]="Off";
+
+    if (empty($_GET["fIsolatedOuter"]))
+        $_GET["fIsolatedOuter"]="Off";
+
+    if (empty($_GET["fMeanPedRmsInner"]))
+        $_GET["fMeanPedRmsInner"]="Off";
+
+    if (empty($_GET["fMeanPedRmsOuter"]))
+        $_GET["fMeanPedRmsOuter"]="Off";
+
+    if (empty($_GET["fIsolatedMaxCluster"]))
+        $_GET["fIsolatedMaxCluster"]="Off";
+
+    if (empty($_GET["fArrTimeMeanInner"]))
+        $_GET["fArrTimeMeanInner"]="Off";
+
+    if (empty($_GET["fArrTimeMeanOuter"]))
+        $_GET["fArrTimeMeanOuter"]="Off";
+
+    if (empty($_GET["fArrTimeRmsInner"]))
+        $_GET["fArrTimeRmsInner"]="Off";
+
+    if (empty($_GET["fArrTimeRmsOuter"]))
+        $_GET["fArrTimeRmsOuter"]="Off";
+
+    if (empty($_GET["fMeanSignalInner"]))
+        $_GET["fMeanSignalInner"]=$first?"Off":"";
+
+    if (empty($_GET["fMeanSignalOuter"]))
+        $_GET["fMeanSignalOuter"]=$first?"Off":"";
+
+    if (empty($_GET["fPulsePosMean"]))
+        $_GET["fPulsePosMean"]=$first?"Off":"";
+
+    if (empty($_GET["fConvFactorInner"]))
+        $_GET["fConvFactorInner"]="Off";
+
+    if (empty($_GET["fConvFactorOuter"]))
+        $_GET["fConvFactorOuter"]="Off";
+}
+
+function InitSequInfo($first)
+{
+    InitInfo($first);
+    InitSequStatus($first);
+    InitCalInfo($first);
+    InitStarInfo($first);
+
+    if (empty($_GET["fNumEvents"]))
+        $_GET["fNumEvents"]=$first?"Off":"";
+
+    if (empty($_GET["fRunTime/60"]))
+        $_GET["fRunTime/60"]="Off";
+
+    if (empty($_GET["fSequenceLast"]))
+        $_GET["fSequenceLast"]="Off";
+
+    if (empty($_GET["fAzimuthMin"]))
+        $_GET["fAzimuthMin"]="Off";
+
+    if (empty($_GET["fAzimuthMax"]))
+        $_GET["fAzimuthMax"]="Off";
+
+    if (empty($_GET["fZenithDistanceMin"]))
+        $_GET["fZenithDistanceMin"]="Off";
+
+    if (empty($_GET["fZenithDistanceMax"]))
+        $_GET["fZenithDistanceMax"]="Off";
+
+    if (empty($_GET["fObservationModeName"]))
+        $_GET["fObservationModeName"]="Off";
+
+    if (empty($_GET["fSumTriggerFlagName"]))
+        $_GET["fSumTriggerFlagName"]="Off";
+
+    if (empty($_GET["fOnlySum"]))
+        $_GET["fOnlySum"]="Off";
+
+//    if (empty($_GET["fManuallyChangedName"]))
+//        $_GET["fManuallyChangedName"]="Off";
+}
+
+function InitDataSetStatus($first)
+{
+    if (empty($_GET["fDataSetInserted"]))
+        $_GET["fDataSetInserted"]="Off";
+
+    if (empty($_GET["fDataSetInsertedStatus"]))
+        $_GET["fDataSetInsertedStatus"]="0";
+
+    if (empty($_GET["fDataSetFileWritten"]))
+        $_GET["fDataSetFileWritten"]=$first?"On":"";
+
+    if (empty($_GET["fDataSetFileWrittenStatus"]))
+        $_GET["fDataSetFileWrittenStatus"]="0";
+
+    if (empty($_GET["fStarFilesAvail"]))
+        $_GET["fStarFilesAvail"]="Off";
+
+    if (empty($_GET["fStarFilesAvailStatus"]))
+        $_GET["fStarFilesAvailStatus"]="0";
+
+    if (empty($_GET["fGanymed"]))
+        $_GET["fGanymed"]=$first?"On":"";
+
+    if (empty($_GET["fGanymedStatus"]))
+        $_GET["fGanymedStatus"]="0";
+
+    if (empty($_GET["fFillGanymed"]))
+        $_GET["fFillGanymed"]="Off";
+
+    if (empty($_GET["fFillGanymedStatus"]))
+        $_GET["fFillGanymedStatus"]="0";
+}
+
+function InitDataSetInfo($first)
+{
+    InitDataSetStatus($first);
+
+    if (empty($_GET["fNumResults"]))
+        $_GET["fNumResults"]="50";
+
+    if (empty($_GET["fLinks"]))
+        $_GET["fLinks"]=$first?"On":"";
+
+    if (empty($_GET["fExcessEvents"]))
+        $_GET["fExcessEvents"]=$first?"On":"";
+
+    if (empty($_GET["fBackgroundEvents*60/fEffOnTime"]))
+        $_GET["fBackgroundEvents*60/fEffOnTime"]=$first?"On":"";
+
+    if (empty($_GET["fBackgroundEvents"]))
+        $_GET["fBackgroundEvents"]=$first?"On":"";
+
+    if (empty($_GET["fSignalEvents"]))
+        $_GET["fSignalEvents"]=$first?"On":"";
+
+    if (empty($_GET["fSignificance"]))
+        $_GET["fSignificance"]=$first?"On":"";
+
+    if (empty($_GET["fScaleFactor"]))
+        $_GET["fScaleFactor"]=$first?"On":"";
+
+    if (empty($_GET["fEffOnTime/3600"]))
+        $_GET["fEffOnTime/3600"]=$first?"On":"";
+
+    if (empty($_GET["fSourceName"]))
+        $_GET["fSourceName"]=$first?"On":"";
+
+    if (empty($_GET["fObservationModeName"]))
+        $_GET["fObservationModeName"]=$first?"On":"";
+
+    if (empty($_GET["fComment"]))
+        $_GET["fComment"]="Off";
+
+    if (empty($_GET["fUserName"]))
+        $_GET["fUserName"]="Off";
+
+    if (empty($_GET["fRunStart"]))
+        $_GET["fRunStart"]="Off";
+
+    if (empty($_GET["fRunStop"]))
+        $_GET["fRunStop"]="Off";
+
+    if (empty($_GET["fZenithDistanceMin"]))
+        $_GET["fZenithDistanceMin"]=$first?"On":"";
+
+    if (empty($_GET["fZenithDistanceMax"]))
+        $_GET["fZenithDistanceMax"]=$first?"On":"";
+
+    if (empty($_GET["fRunTime"]))
+        $_GET["fRunTime"]="Off";
+
+    if (empty($_GET["fDataSetName"]))
+        $_GET["fDataSetName"]=$first?"On":"";
+
+    if (empty($_GET["fExcessEvents*60/fEffOnTime"]))
+        $_GET["fExcessEvents*60/fEffOnTime"]="Off";
+
+    if (empty($_GET["fSignalEvents*60/fEffOnTime"]))
+        $_GET["fSignalEvents*60/fEffOnTime"]="Off";
+
+    if (empty($_GET["Round(fSignificance/Sqrt(fEffOnTime/3600),2)"]))
+        $_GET["Round(fSignificance/Sqrt(fEffOnTime/3600),2)"]="Off";
+
+}
+
+function InitFindOffData($first)
+{
+    InitSequInfo($first);
+
+    //init for limits
+
+    if (empty($_GET["fArrTimeLimitMean"]))
+        $_GET["fArrTimeLimitMean"]="";
+
+    if (empty($_GET["fArrTimeLimitRms"]))
+        $_GET["fArrTimeLimitRms"]="";
+
+    if (empty($_GET["fSkyBrightLimitMean"]))
+        $_GET["fSkyBrightLimitMean"]="";
+
+    if (empty($_GET["fSkyBrightLimitRms"]))
+        $_GET["fSkyBrightLimitRms"]="";
+
+    if (empty($_GET["fMaxHumLimit1"]))
+        $_GET["fMaxHumLimit1"]="";
+
+    if (empty($_GET["fMaxHumLimit2"]))
+        $_GET["fMaxHumLimit2"]="";
+
+    if (empty($_GET["fCloudinessLimit1"]))
+        $_GET["fCloudinessLimit1"]="40";
+
+    if (empty($_GET["fCloudinessLimit2"]))
+        $_GET["fCloudinessLimit2"]="50";
+
+    //values that differ for different data
+    if (empty($_GET["fPSFLimitMean"]))
+        $_GET["fPSFLimitMean"]="";
+
+    if (empty($_GET["fPedRmsInLimitMean"]))
+        $_GET["fPedRmsInLimitMean"]="";
+
+    if (empty($_GET["fZdMinLimit1"]))
+        $_GET["fZdMinLimit1"]="";
+
+    if (empty($_GET["fZdMinLimit2"]))
+        $_GET["fZdMinLimit2"]="";
+
+    if (empty($_GET["fZdMaxLimit1"]))
+        $_GET["fZdMaxLimit1"]="";
+
+    if (empty($_GET["fZdMaxLimit2"]))
+        $_GET["fZdMaxLimit2"]="";
+
+    // values taken from distribution or from experience
+    if (empty($_GET["fUnsInLimit1"]))
+        $_GET["fUnsInLimit1"]=$first?"12":"";
+
+    if (empty($_GET["fUnsInLimit2"]))
+        $_GET["fUnsInLimit2"]=$first?"20":"";
+
+    if (empty($_GET["fRunTimeLimit1"]))
+        $_GET["fRunTimeLimit1"]=$first?"5":"";
+
+    if (empty($_GET["fRunTimeLimit2"]))
+        $_GET["fRunTimeLimit2"]=$first?"2":"";
+
+    if (empty($_GET["fPSFLimitRms"]))
+        $_GET["fPSFLimitRms"]=$first?"1.0":"";
+
+    if (empty($_GET["fPedRmsInLimitRms"]))
+        $_GET["fPedRmsInLimitRms"]=$first?"0.08":"";
+
+    if (empty($_GET["fNumIslLimitMean"]))
+        $_GET["fNumIslLimitMean"]=$first?"1.230":"";
+
+    if (empty($_GET["fNumIslLimitRms"]))
+        $_GET["fNumIslLimitRms"]=$first?"0.013":"";
+
+    if (empty($_GET["fMuonCalLimitMean"]))
+        $_GET["fMuonCalLimitMean"]=$first?"100.0":"";
+
+    if (empty($_GET["fMuonCalLimitRms"]))
+        $_GET["fMuonCalLimitRms"]=$first?"1.6":"";
+
+    if (empty($_GET["fRelTimeMaxLimit1"]))
+        $_GET["fRelTimeMaxLimit1"]=$first?"1.0":"";
+
+    if (empty($_GET["fRelTimeMaxLimit2"]))
+        $_GET["fRelTimeMaxLimit2"]=$first?"1.02":"";
+
+    if (empty($_GET["fRelTimeMinLimit1"]))
+        $_GET["fRelTimeMinLimit1"]=$first?"0.97":"";
+
+    if (empty($_GET["fRelTimeMinLimit2"]))
+        $_GET["fRelTimeMinLimit2"]=$first?"0.93":"";
+
+    if (empty($_GET["fIMCLimit1"]))
+        $_GET["fIMCLimit1"]=$first?"00":"";
+
+    if (empty($_GET["fIMCLimit2"]))
+        $_GET["fIMCLimit2"]=$first?"00":"";
+
+    if (empty($_GET["fIsoInLimit1"]))
+        $_GET["fIsoInLimit1"]=$first?"00":"";
+
+    if (empty($_GET["fIsoInLimit2"]))
+        $_GET["fIsoInLimit2"]=$first?"00":"";
+
+    if (empty($_GET["fInhomLimitMean"]))
+        $_GET["fInhomLimitMean"]=$first?"10":"";
+
+    if (empty($_GET["fInhomLimitRms"]))
+        $_GET["fInhomLimitRms"]=$first?"3":"";
+
+    if (empty($_GET["fImgRateLimitMean"]))
+        $_GET["fImgRateLimitMean"]=$first?"180":"";
+
+    if (empty($_GET["fImgRateLimitRms"]))
+        $_GET["fImgRateLimitRms"]=$first?"30":"";
+
+    if (empty($_GET["fMuonRateLimitMean"]))
+        $_GET["fMuonRateLimitMean"]=$first?"1":"";
+
+    if (empty($_GET["fMuonRateLimitRms"]))
+        $_GET["fMuonRateLimitRms"]=$first?"0.1":"";
+
+    if (empty($_GET["fMuonNumLimit1"]))
+        $_GET["fMuonNumLimit1"]=$first?"180":"";
+
+    if (empty($_GET["fMuonNumLimit2"]))
+        $_GET["fMuonNumLimit2"]=$first?"120":"";
+
+    if (empty($_GET["fPulsePosLimit1"]))
+        $_GET["fPulsePosLimit1"]=$first?"3.5":"";
+
+    if (empty($_GET["fPulsePosLimit2"]))
+        $_GET["fPulsePosLimit2"]=$first?"2.5":"";
+
+    if (empty($_GET["fNumStarsLimit1"]))
+        $_GET["fNumStarsLimit1"]=$first?"30":"";
+
+    if (empty($_GET["fNumStarsLimit2"]))
+        $_GET["fNumStarsLimit2"]=$first?"20":"";
+
+    if (empty($_GET["fNumStarsCorLimit1"]))
+        $_GET["fNumStarsCorLimit1"]=$first?"10":"";
+
+    if (empty($_GET["fNumStarsCorLimit2"]))
+        $_GET["fNumStarsCorLimit2"]=$first?"5":"";
+
+}
+
+function InitBuildDataSets($first)
+{
+        if (empty($_GET["fNumResults"]))
+//            $_GET["fNumResults"]="50";
+            $_GET["fNumResults"]="10";
+
+        if (empty($_GET["fRunStart"]))
+            $_GET["fRunStart"]=$first?"On":"";
+
+        if (empty($_GET["fRunTime/60"]))
+            $_GET["fRunTime/60"]=$first?"On":"";
+
+        if (empty($_GET["fZenithDistanceMin"]))
+            $_GET["fZenithDistanceMin"]=$first?"On":"";
+
+        if (empty($_GET["fZenithDistanceMax"]))
+            $_GET["fZenithDistanceMax"]=$first?"On":"";
+
+        if (empty($_GET["fSourceName"]))
+            $_GET["fSourceName"]=$first?"On":"";
+
+        if (empty($_GET["fObservationModeName"]))
+            $_GET["fObservationModeName"]=$first?"On":"";
+
+        if (empty($_GET["fUnsuitableInner"]))
+            $_GET["fUnsuitableInner"]=$first?"On":"";
+
+        if (empty($_GET["fUnreliableInner"]))
+            $_GET["fUnreliableInner"]=$first?"On":"";
+
+        if (empty($_GET["fIsolatedInner"]))
+            $_GET["fIsolatedInner"]=$first?"On":"";
+
+        if (empty($_GET["fIsolatedMaxCluster"]))
+            $_GET["fIsolatedMaxCluster"]=$first?"On":"";
+
+        if (empty($_GET["fArrTimeRmsInner"]))
+            $_GET["fArrTimeRmsInner"]=$first?"On":"";
+
+        if (empty($_GET["fMeanPedRmsInner"]))
+            $_GET["fMeanPedRmsInner"]=$first?"On":"";
+
+        if (empty($_GET["fPulsePosMean"]))
+            $_GET["fPulsePosMean"]=$first?"On":"";
+
+        if (empty($_GET["fConvFactorInner"]))
+            $_GET["fConvFactorInner"]=$first?"On":"";
+
+        if (empty($_GET["fInhomogeneity"]))
+            $_GET["fInhomogeneity"]=$first?"On":"";
+
+        if (empty($_GET["fPSF"]))
+            $_GET["fPSF"]=$first?"On":"";
+
+        if (empty($_GET["fMuonNumber"]))
+            $_GET["fMuonNumber"]=$first?"On":"";
+
+        if (empty($_GET["fEffOnTime/fRunTime"]))
+            $_GET["fEffOnTime/fRunTime"]=$first?"On":"";
+
+        if (empty($_GET["fMuonRate"]))
+            $_GET["fMuonRate"]=$first?"On":"";
+
+        if (empty($_GET["fDataRate"]))
+            $_GET["fDataRate"]=$first?"On":"";
+
+        if (empty($_GET["fAvgCloudiness"]))
+            $_GET["fAvgCloudiness"]=$first?"On":"";
+
+        if (empty($_GET["fNumStarsMed"]))
+            $_GET["fNumStarsMed"]=$first?"On":"";
+
+        if (empty($_GET["fNumStarsCorMed"]))
+            $_GET["fNumStarsCorMed"]=$first?"On":"";
+
+        if (empty($_GET["fOff"]))
+            $_GET["fOff"]=$first?"On":"";
+
+        if (empty($_GET["fLinks"]))
+            $_GET["fLinks"]=$first?"On":"";
+
+        if (empty($_GET["fOnlyOff"]))
+            $_GET["fOnlyOff"]=$first?"Off":"";
+
+        InitFindOffData($first);
+}
+
+// cta mc stuff
+function InitCTAMCRunStatus($first)
+{
+    if (empty($_GET["fCorsikaSimTelarray"]))
+        $_GET["fCorsikaSimTelarray"]="On";
+
+    if (empty($_GET["fCorsikaSimTelarrayStatus"]))
+        $_GET["fCorsikaSimTelarrayStatus"]="0";
+
+    if (empty($_GET["fChimp"]))
+        $_GET["fChimp"]="Off";
+
+    if (empty($_GET["fChimpStatus"]))
+        $_GET["fChimpStatus"]="0";
+
+    if (empty($_GET["fCTAStar"]))
+        $_GET["fCTAStar"]="Off";
+
+    if (empty($_GET["fCTAStarStatus"]))
+        $_GET["fCTAStarStatus"]="0";
+
+    if (empty($_GET["fStereoB"]))
+        $_GET["fStereoB"]="Off";
+
+    if (empty($_GET["fStereoBStatus"]))
+        $_GET["fStereoBStatus"]="0";
+
+    if (empty($_GET["fStereoC"]))
+        $_GET["fStereoC"]="Off";
+
+    if (empty($_GET["fStereoCStatus"]))
+        $_GET["fStereoCStatus"]="0";
+
+    if (empty($_GET["fStereoG"]))
+        $_GET["fStereoG"]="Off";
+
+    if (empty($_GET["fStereoGStatus"]))
+        $_GET["fStereoGStatus"]="0";
+
+}
+
+function InitCTAMCRunInfo($first)
+{
+    if (empty($_GET["fNumResults"]))
+        $_GET["fNumResults"]="50";
+
+    if (empty($_GET["fNumEvents"]))
+        $_GET["fNumEvents"]="On";
+
+    InitCTAMCRunStatus($first);
+    InitInfo($first);
+
+    if (empty($_GET["fNumEvents"]))
+        $_GET["fNumEvents"]=$first?"Off":"";
+
+    if (empty($_GET["fObsLevel"]))
+        $_GET["fObsLevel"]="On";
+
+    if (empty($_GET["fParticleTypeName"]))
+        $_GET["fParticleTypeName"]="On";
+
+    if (empty($_GET["fNumEvents"]))
+        $_GET["fNumEvents"]=$first?"On":"";
+
+    if (empty($_GET["fLinks"]))
+        $_GET["fLinks"]=$first?"On":"";
+
+}
+
+//other MC stuff
+function InitMCRunStatus($_GET, $first)
+{
+
+    if (empty($_GET["Corsika"]))
+        $_GET["Corsika"]=$first?"On":"";
+
+    if (empty($_GET["CorsikaStatus"]))
+        $_GET["CorsikaStatus"]="0";
+
+    if (empty($_GET["Ceres"]))
+        $_GET["Ceres"]=$first?"On":"";
+
+    if (empty($_GET["CeresStatus"]))
+        $_GET["CeresStatus"]="0";
+
+    if (empty($_GET["SequenceFile"]))
+        $_GET["SequenceFile"]=$first?"Off":"";
+
+    if (empty($_GET["SequenceFileStatus"]))
+        $_GET["SequenceFileStatus"]="0";
+
+    if (empty($_GET["Callisto"]))
+        $_GET["Callisto"]=$first?"Off":"";
+
+    if (empty($_GET["CallistoStatus"]))
+        $_GET["CallistoStatus"]="0";
+
+    if (empty($_GET["Star"]))
+        $_GET["Star"]=$first?"On":"";
+
+    if (empty($_GET["StarStatus"]))
+        $_GET["StarStatus"]="0";
+
+}
+
+function InitMCRunInfo($_GET, $first)
+{
+    if (empty($_GET["fNumResults"]))
+        $_GET["fNumResults"]="50";
+
+    InitMCRunStatus($_GET, $first);
+    InitInfo($_GET, $first);
+
+    if (empty($_GET["fParticleTypeName"]))
+        $_GET["fParticleTypeName"]=$first?"On":"";
+
+    if (empty($_GET["fRunTypeName"]))
+        $_GET["fRunTypeName"]=$first?"On":"";
+
+    if (empty($_GET["fAtmosphericModelName"]))
+        $_GET["fAtmosphericModelName"]="Off";
+
+    if (empty($_GET["fCeresSetupName"]))
+        $_GET["fCeresSetupName"]=$first?"On":"";
+
+    if (empty($_GET["fNumEvents"]))
+        $_GET["fNumEvents"]=$first?"Off":"";
+
+    if (empty($_GET["fNumEvents*fNumReUseShowers"]))
+        $_GET["fNumEvents*fNumReUseShowers"]=$first?"On":"";
+
+    if (empty($_GET["fSequenceNumber"]))
+        $_GET["fSequenceNumber"]=$first?"On":"";
+
+    if (empty($_GET["fZenithDistanceMin"]))
+        $_GET["fZenithDistanceMin"]=$first?"Off":"";
+
+    if (empty($_GET["fZenithDistanceMax"]))
+        $_GET["fZenithDistanceMax"]=$first?"Off":"";
+
+    if (empty($_GET["fAzimuthMin"]))
+        $_GET["fAzimuthMin"]=$first?"Off":"";
+
+    if (empty($_GET["fAzimuthMax"]))
+        $_GET["fAzimuthMax"]=$first?"Off":"";
+
+    if (empty($_GET["fEnergyMin"]))
+        $_GET["fEnergyMin"]=$first?"On":"";
+
+    if (empty($_GET["fEnergyMax"]))
+        $_GET["fEnergyMax"]=$first?"On":"";
+
+    if (empty($_GET["fImpactMax"]))
+        $_GET["fImpactMax"]=$first?"On":"";
+
+    if (empty($_GET["fViewConeMax"]))
+        $_GET["fViewConeMax"]=$first?"On":"";
+
+    if (empty($_GET["fEnergySlope"]))
+        $_GET["fEnergySlope"]=$first?"On":"";
+
+    if (empty($_GET["fStartingAltitude"]))
+        $_GET["fStartingAltitude"]=$first?"On":"";
+
+    if (empty($_GET["fMirrorDiameter"]))
+        $_GET["fMirrorDiameter"]=$first?"On":"";
+
+    if (empty($_GET["fNumReUseShowers"]))
+        $_GET["fNumReUseShowers"]=$first?"Off":"";
+
+}
+
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/opticaldata.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/opticaldata.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/opticaldata.php	(revision 17960)
@@ -0,0 +1,323 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $fromtable="OpticalData";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0)
+        {
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+            $query0 .= " COUNT(*) as '# Runs' ";
+        }
+        else
+        {
+            $query0 .= " fTimeStamp as 'Time' ";
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On")
+                    if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                        $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM " . $fromtable;
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty($joins[$key]))
+                $query0 .= GetJoin($fromtable, $key);
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)// this if clause doesn't work
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        if (!empty($_GET["fStartDate"]))
+        {
+            $startdate=substr($_GET["fStartDate"], 0, 10);
+            if ($startdate=="0000-00-00")
+                $query0 .=" fTimestamp >= '" . $startdate . " 00:00:00' ";
+            else
+                $query0 .= " fTimestamp >= ADDDATE('" . $startdate . " 13:00:00', INTERVAL -1 DAY) ";
+        }
+
+        if (!empty($_GET["fStopDate"]))
+        {
+//            if (strpos(strrev($query0), " DNA ")!=0)
+//                $query0 .= " AND ";
+
+            $stopdate=substr($_GET["fStopDate"], 0, 10);
+            $query0 .= " AND fTimestamp < '" . $stopdate . " 13:00:00' ";
+        }
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable, $key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $query0 .= " ORDER BY " . substr($_GET["fSortBy"], 0, -1) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+            
+        if (empty($_GET["fTimestamp"]))
+            $_GET["fTimestamp"]=$first?"On":"";
+
+        if (empty($_GET["fExposure"]))
+            $_GET["fExposure"]=$first?"On":"";
+
+        if (empty($_GET["fSkyLevel"]))
+            $_GET["fSkyLevel"]=$first?"On":"";
+
+        if (empty($_GET["fFWHM"]))
+            $_GET["fFWHM"]=$first?"On":"";
+
+        if (empty($_GET["fApertureRadius"]))
+            $_GET["fApertureRadius"]=$first?"On":"";
+
+        if (empty($_GET["fInstrumentalMag"]))
+            $_GET["fInstrumentalMag"]=$first?"On":"";
+
+        if (empty($_GET["fInstrumentalMagErr"]))
+            $_GET["fInstrumentalMagErr"]=$first?"On":"";
+
+        if (empty($_GET["fFitsFileName"]))
+            $_GET["fFitsFileName"]="Off";
+
+        if (empty($_GET["fObjectName"]))
+            $_GET["fObjectName"]=$first?"On":"";
+
+        if (empty($_GET["fStatusName"]))
+            $_GET["fStatusName"]="Off";
+
+        if (empty($_GET["fBandName"]))
+            $_GET["fBandName"]=$first?"On":"";
+
+        if (empty($_GET["fTelescopeName"]))
+            $_GET["fTelescopeName"]=$first?"On":"";
+
+//        if (empty($_GET["fRunStop"]))
+//            $_GET["fRunStop"]="Off";
+
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"opticaldata.php\" METHOD=\"GET\">\n");
+        printf(" <table>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fTimestamp",         "Time");
+        CheckBox("fExposure",      "Exposure");
+        CheckBox("fSkyLevel",     "Skylevel");
+        CheckBox("fFWHM",          "FWHM");
+
+        printf("  </tr><tr>\n");
+
+        CheckBox("fApertureRadius",     "Aperture radius");
+        CheckBox("fInstrumentalMag",    "instrumental magnitude");
+        CheckBox("fInstrumentalMagErr", "instrum. mag. error");
+
+        printf("  </tr>\n");
+        printf(" </table>\n");
+        printf(" <p>\n");
+
+        // pull down boxes
+
+        printf(" <table>\n");
+        printf("  <tr><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "Telescope",  "fTelescopeName",  "fTelescopeKEY", "Telescope");
+        printf("  </td><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "Object",      "fObjectName",      "fObjectKEY", "Object Name");
+        printf("  </td><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "Band",     "fBandName",     "fBandKEY", "Band");
+        printf("  </td></tr><tr><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "FitsFile",     "fFitsFileName",     "fFitsFileKEY", "Fits File");
+        printf("  </td><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "Status",  "fStatusName",  "fStatusKEY", "Status Code");
+        printf(" </td></tr></table>\n");
+        printf(" <p>\n");
+
+        if (empty($_GET["fStartDate"]))
+            $timemin = GetMin("fTimestamp", "OpticalData", $host, $user, $pw, $db);
+        else
+            $timemin = $_GET["fStartDate"];
+
+        if (empty($_GET["fStopDate"]))
+            $timemax = GetMax("fTimestamp", "OpticalData", $host, $user, $pw, $db);
+        else
+            $timemax = $_GET["fStopDate"];
+
+        printf("Night&nbsp;(yyyy-mm-dd)&nbsp;from&nbsp;<input name=\"fStartDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">\n", $timemin);
+        printf("to&nbsp;<input name=\"fStopDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">&nbsp;&nbsp;&nbsp;&nbsp;\n", $timemax);
+
+        printf(" Results:\n");
+        printf(" <select name=\"fNumResults\">\n");
+
+        $numres = array("10", "20", "50", "100", "200", "500", "1000", "2000");
+        foreach ($numres as $element)
+        {
+            if ($element==$_GET["fNumResults"])
+                printf("<option value=\"%s\" selected>%3s</option>\n", $element, $element);
+            else
+                printf("<option value=\"%s\">%3s</option>\n", $element, $element);
+        }
+        printf(" </select>\n");
+        printf(" &nbsp;&nbsp;&nbsp;\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"opticaldata.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+        mysql_query("SET BIG_TABLES=1"); // necessary for mySQL <= 4
+
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors",   "On");
+    ini_set("mysql.trace_mode", "On");
+
+    $sitepw="\$1\$jfBkkHx1\$WmxNVaOWPCBC8asfKDfBZ/";
+    $siteuser="optical";
+
+    if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER']!=$siteuser)
+    {
+        header('WWW-Authenticate: Basic realm="Optical Data - Tuorla Observatory"');
+        header('HTTP/1.0 401 Unauthorized');
+        echo 'Action cancelled.';
+        return;
+    }
+    else
+    {
+//    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
+//    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
+//    printf("pw: %s", crypt($_SERVER['PHP_AUTH_PW']));
+        if (crypt($_SERVER['PHP_AUTH_PW'], $sitepw)!=$sitepw || $_SERVER['PHP_AUTH_USER']!=$siteuser)
+        {
+            printf("<br>pw or user incorrect<br>");
+            return;
+        }
+    }
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+            PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors",   "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/plot.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/plot.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/plot.php	(revision 17960)
@@ -0,0 +1,113 @@
+<?php
+    require_once("./phpchartdir.php");
+
+include("plotinclude.php");
+
+function GetData($db_id, $tables, $joins, $set, &$prim, &$val1, &$val2)
+{
+    $query=GetQuery($tables, $joins, $set);
+//    printf("query:%s<br>", $query);
+    $result=mysql_query($query, $db_id);
+
+    while ($row = mysql_fetch_row($result))
+    {
+        $prim[] = $row[0];
+        $val1[] = $row[1];
+        if ($_GET["plot"]=="val")
+            $val2[] = $row[2];
+    }
+    mysql_free_result($result);
+}
+
+$primary=$_GET["prim"];
+$column=$_GET[$primary."Col"];
+
+//get data from db
+$db_id = mysql_pconnect($host, $user, $pw);
+if ($db_id==FALSE)
+{
+    printf("mysql_connect returned the following error: %s\n", mysql_error());
+    die("");
+}
+mysql_select_db($db);
+
+GetData($db_id, $tables, $joins, "", $prim, $val1, $val2);
+if (!empty($_GET["Set"]))
+    GetData($db_id, $tables, $joins, "Set", $Setprim, $Setval1, $Setval2);
+if (!empty($_GET["Set2"]))
+    GetData($db_id, $tables, $joins, "Set2", $Set2prim, $Set2val1, $Set2val2);
+
+mysql_close($db_id);
+
+//set up plot
+if (empty($_GET["x"]))
+    $x=640;
+else
+    $x=$_GET["x"];
+if (empty($_GET["y"]))
+    $y=400;
+else
+    $y=$_GET["y"];
+
+$c= new XYChart($x,$y);//, 0xeeeeee, 0x000000, 1);
+$c->setPlotArea(70, 45, $x-100, $y-100, 0xffffff, -1, 0xcccccc, 0xccccccc);
+//$c= new XYChart(440,250);//, 0xeeeeee, 0x000000, 1);
+//$c->setPlotArea(70, 45, 340, 150, 0xffffff, -1, 0xcccccc, 0xccccccc);
+//$c->setRoundedFrame();
+
+//size of the symbols
+$small=2;//normal data
+$large=8;//set1, set2
+//fonts
+$titlesize=13;
+$font="arialbd.ttf";
+$axisfont="";
+$axissize=10;
+$labelfont="arialdb.ttf";
+$labelsize=10;
+//colours
+$colour=0x000000;
+$setcolour=0x0080ff;
+$set2colour=0xff0000;
+
+if ($_GET["plot"]=="val")
+{
+    $column2=$_GET[$primary."Col2"];
+    $c->addScatterLayer($val2, $val1, $column, CircleSymbol, $small, $colour, $colour);
+    if (!empty($_GET["Set"]))
+        $c->addScatterLayer($Setval2, $Setval1, $column, CircleSymbol, $large, $setcolour, $setcolour);
+    if (!empty($_GET["Set2"]))
+        $c->addScatterLayer($Set2val2, $Set2val1, $column, CircleSymbol, $large, $set2colour, $set2colour);
+    $c->yAxis->setTitle($column, $axisfont, $axissize);
+    $c->xAxis->setTitle($column2, $axisfont, $axissize);
+    $textBoxObj = $c->addTitle(ltrim($column, "f")."  vs  ".ltrim($column2, "f"), $font, $titlesize);
+}
+else
+{
+    $c->addScatterLayer($prim, $val1, $column, CircleSymbol, $small, $colour, $colour);
+    if (!empty($_GET["Set"]))
+        $c->addScatterLayer($Setprim, $Setval1, $column, CircleSymbol, $large, $setcolour, $setcolour);
+    if (!empty($_GET["Set2"]))
+        $c->addScatterLayer($Set2prim, $Set2val1, $column, CircleSymbol, $large, $set2colour, $set2colour);
+    $c->yAxis->setTitle($column, $axisfont, $axissize);
+    $c->xAxis->setTitle($primary, $axisfont, $axissize);
+    $textBoxObj = $c->addTitle(ltrim($column,"f")."  vs  ".ltrim($primary,"f"), $font, $titlesize);
+}
+//get scaling of the yAxis
+if (!empty($_GET[$column."Start"]) && !empty($_GET[$column."Stop"]))
+{
+    $start=$_GET[$column."Start"];
+    $stop=$_GET[$column."Stop"];
+    $numticks=($stop-$start)/4;
+    $numticks2=($stop-$start)/8;
+    $c->yAxis->setLinearScale($start, $stop, $numticks, $numticks2);
+}
+//background of title
+$textBoxObj->setBackground(0xccccff,-1, softLighting());
+$c->xAxis->setLabelStyle($labelfont, $labelsize);
+$c->yAxis->setLabelStyle($labelfont, $labelsize);
+
+header("Content-type: image/png");
+print($c->makeChart2(PNG));
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/plotdb.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/plotdb.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/plotdb.php	(revision 17960)
@@ -0,0 +1,278 @@
+<?php
+{
+    function GetSequencesFromDataSet($onoff)
+    {
+        include("db.php");
+        $db_id = mysql_pconnect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+        $query="SELECT fSequenceFirst FROM DataSetSequenceMapping WHERE fDataSetNumber IN (";
+        $query .= str_replace(" ", ",", trim($_GET["Set"])) . ") AND fOnOff=" . $onoff;
+//        printf("Q: %s<br>", $query);
+        $result=mysql_query($query, $db_id);
+
+        $sequences="";
+        while ($row = mysql_fetch_row($result))
+            $sequences.= $row[0] . " ";
+
+        mysql_free_result($result);
+        mysql_close($db_id);
+
+        $text="";
+        if (!empty($sequences))
+            $text.= str_replace(" ", "+", trim($sequences));
+        return $text;
+    }
+  
+    function PrintDiv($host, $user, $pw, $db, $column, $tables, $num)
+    {
+        $list=GetList($host, $user, $pw, $db, $column, $tables);
+
+        if (($_GET["prim"]==$column && empty($num))
+            || ($_GET["prim"]==$column && $num==3)
+            || ($_GET["prim"]==$column && $num==4)
+            || ($_GET["prim"]==$column && $_GET["plot"]=="val" && $num==2)
+            || (empty($_GET["prim"]) && $column=="fSequenceFirst"))
+            printf("<div id='%s%s' style='display:inline'>\n", $column, $num);
+        else
+            printf("<div id='%s%s' style='display:none'>\n", $column, $num);
+
+        if ($num==2)
+            $vs="vs";
+
+        printf("<select name='%sCol%s' size='1' class='Width'>\n", $column, $num);
+        foreach($list as $column2)
+            if ($_GET[$column."Col".$num]==$column2)
+                printf("<option value='%s' selected>%s %s</option>\n", $column2, $vs, $column2);
+            else
+                printf("<option value='%s'>%s %s</option>\n", $column2, $vs, $column2);
+
+        printf("</select>\n<br>\n");
+        printf("</div>\n");
+    }
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    echo (file_get_contents("index-header.html"));
+
+    include("plotinclude.php");
+
+    //init
+    if (empty($_GET["plot"]))
+        $_GET["plot"]="";
+    if (empty($_GET["primstart"]))
+        $_GET["primstart"]="";
+    if (empty($_GET["primstop"]))
+        $_GET["primstop"]="";
+    if (empty($_GET["prim"]))
+        $_GET["prim"]="";
+    if (empty($_GET["fSequenceFirstCol"]))
+        $_GET["fSequenceFirstCol"]="";
+    if (empty($_GET["fSequenceFirstCol2"]))
+        $_GET["fSequenceFirstCol2"]="";
+    if (empty($_GET["fSequenceFirstCol3"]))
+        $_GET["fSequenceFirstCol3"]="";
+    if (empty($_GET["fRunNumberCol"]))
+        $_GET["fRunNumberCol"]="";
+    if (empty($_GET["fRunNumberCol2"]))
+        $_GET["fRunNumberCol2"]="";
+    if (empty($_GET["fRunNumberCol3"]))
+        $_GET["fRunNumberCol3"]="";
+    if (empty($_GET["fDataSetNumberCol"]))
+        $_GET["fDataSetNumberCol"]="";
+    if (empty($_GET["fDataSetNumberCol2"]))
+        $_GET["fDataSetNumberCol2"]="";
+    if (empty($_GET["fDataSetNumberCol3"]))
+        $_GET["fDataSetNumberCol3"]="";
+    if (empty($_GET["Start"]))
+        $_GET["Start"]="";
+    if (empty($_GET["Stop"]))
+        $_GET["Stop"]="";
+    if (empty($_GET["Start2"]))
+        $_GET["Start2"]="";
+    if (empty($_GET["Stop2"]))
+        $_GET["Stop2"]="";
+    if (empty($_GET["Start3"]))
+        $_GET["Start3"]="";
+    if (empty($_GET["Stop3"]))
+        $_GET["Stop3"]="";
+    if (empty($_GET["Start4"]))
+        $_GET["Start4"]="";
+    if (empty($_GET["Stop4"]))
+        $_GET["Stop4"]="";
+    if (empty($_GET["Set"]))
+        $_GET["Set"]="";
+    if (empty($_GET["Set2"]))
+        $_GET["Set2"]="";
+    if (empty($_GET["set"]))
+        $_GET["set"]="";
+
+    if (empty($_GET["x"]))
+        $totalx=640+410+60;
+    else
+        $totalx=$_GET["x"]+410+60;
+    
+    printf("<center>\n<table cellpadding='0' width='%s' border='0'>\n", $totalx);
+    printf("<tr><td align='left'>\n");
+    printf("<form style='margin-bottom:0;' action='plotdb.php' METHOD='GET'>\n");
+
+    printf("&nbsp;<input type='radio' name='plot' value='prim' onclick='hidepulldown2()' %s> vs primary &nbsp;", $_GET["plot"]=="prim" ? "checked" : "");
+    printf("&nbsp;<input type='radio' name='plot' value='val' onclick='showpulldown2()' %s> vs value <br><br>", ($_GET["plot"]=="val" || empty($_GET["plot"])) ? "checked" : "");
+
+    printf("<table>\n");
+    printf("<tr><td>\n");
+    printf("<select name='prim' size='1' class='Width'>\n");
+    foreach($prims as $primary => $column)
+        if ($_GET["prim"]==$column)
+            printf("<option onclick=\"showpulldown('%s')\" value='%s' selected>%s</option>\n", $column, $column, $primary);
+        else
+            printf("<option onclick=\"showpulldown('%s')\" value='%s'>%s</option>\n", $column, $column, $primary);
+    printf("</select>\n");
+    printf(" </td><td valign='top'>\n ");
+    printf(" from&nbsp;<input name='primstart' type='text' size='8' maxlength='8' value='%s'>", $_GET["primstart"]);
+    printf(" to&nbsp;<input name='primstop' type='text' size='8' maxlength='8' value='%s'>", $_GET["primstop"]);
+    printf("</td>\n</tr>\n");
+
+    printf("<tr><td>\n");
+    foreach($prims as $primary => $column)
+        PrintDiv($host, $user, $pw, $db, $column, $tables, "");
+    printf(" </td><td valign='top'>\n <div id='Range' style='display:inline'>\n ");
+    printf(" from&nbsp;<input name='Start' type='text' size='8' maxlength='8' value='%s'>", $_GET["Start"]);
+    printf(" to&nbsp;<input name='Stop' type='text' size='8' maxlength='8' value='%s'>\n", $_GET["Stop"]);
+    printf("</div></td>\n</tr>\n");
+
+    printf("<tr><td>\n");
+    foreach($prims as $primary => $column)
+        PrintDiv($host, $user, $pw, $db, $column, $tables, "2");
+//    if ($_GET["plot"]=="val")
+    if ($_GET["plot"]=="val" || empty($_GET["plot"]))
+        printf(" </td><td valign='top'>\n <div id='Range2' style='display:inline'>\n ");
+    else
+        printf(" </td><td valign='top'>\n <div id='Range2' style='display:none'>\n ");
+    printf(" from&nbsp;<input name='Start2' type='text' size='8' maxlength='8' value='%s'>", $_GET["Start2"]);
+    printf(" to&nbsp;<input name='Stop2' type='text' size='8' maxlength='8' value='%s'>\n", $_GET["Stop2"]);
+    printf("</div></td>\n</tr>\n");
+
+    printf("<tr>\n<td colspan='2'>\nLimits</td>\n</tr>\n<tr>\n<td>\n");
+    foreach($prims as $primary => $column)
+        PrintDiv($host, $user, $pw, $db, $column, $tables, "3");
+    printf(" </td><td valign='top'>\n <div id='Range3' style='display:inline'>\n ");
+    printf(" from&nbsp;<input name='Start3' type='text' size='8' maxlength='8' value='%s'>", $_GET["Start3"]);
+    printf(" to&nbsp;<input name='Stop3' type='text' size='8' maxlength='8' value='%s'>\n", $_GET["Stop3"]);
+    printf("</div></td>\n</tr>\n");
+
+    printf("<tr>\n<td>\n");
+    foreach($prims as $primary => $column)
+        PrintDiv($host, $user, $pw, $db, $column, $tables, "4");
+    printf(" </td><td valign='top'>\n <div id='Range4' style='display:inline'>\n ");
+    printf(" from&nbsp;<input name='Start4' type='text' size='8' maxlength='8' value='%s'>", $_GET["Start4"]);
+    printf(" to&nbsp;<input name='Stop4' type='text' size='8' maxlength='8' value='%s'>\n", $_GET["Stop4"]);
+    printf("</div></td>\n</tr>\n");
+
+    printf("</table>\n");
+    printf("<br>\n");
+
+    printf("&nbsp;<input type='radio' name='set' value='sequences' onclick='showset2()' %s> sequences &nbsp;\n", $_GET["set"]=="sequences" ? "checked" : "");
+    printf("&nbsp;<input type='radio' name='set' value='datasets' onclick='hideset2()' %s> datasets <br>\n", $_GET["set"]=="datasets" ? "checked" : "");
+
+    printf("<div id='set1' style='display:inline'>Set1: <input name='Set' type='text' size='20' maxlength='150' value='%s'>\n</div>\n<br>\n", $_GET["Set"]);
+    if (empty($_GET["set"]) || $_GET["set"]=="sequences")
+        printf("<div id='set2' style='display:inline'>Set2: <input name='Set2' type='text' size='20' maxlength='100' value='%s'>\n</div>\n<br>\n", $_GET["Set2"]);
+    else
+        printf("<div id='set2' style='display:none'>Set2: <input name='Set2' type='text' size='20' maxlength='150' value='%s'>\n</div>\n<br>\n", $_GET["Set2"]);
+
+    printf("<br>\nSource&nbsp;(<A HREF=\"regexp.html\">regexp</A>)&nbsp;<input name=\"fSourceN\" type=\"text\" size=\"15\" maxlength=\"15\" value=\"");
+    if (!empty($_GET["fSourceN"]))
+        printf("%s", $_GET["fSourceN"]);
+    printf("\">\n<br>\n");
+
+    printf("<br>\nPlot format: &nbsp; x = <select name='x' size='1'>\n");
+    $x = array( 740, 640, 540, 440);
+    foreach($x as $key => $el)
+        if ($_GET["x"]==$el || (empty($_GET["x"]) && $el==640))
+            printf("<option value='%s' selected>%s</option>\n", $el, $el);
+        else
+            printf("<option value='%s'>%s</option>\n", $el, $el);
+    printf("</select>\n ");
+
+    printf("&nbsp; y = <select name='y' size='1'>\n");
+    $y= array( 600, 500, 400, 300);
+    foreach($y as $key => $el)
+        if ($_GET["y"]==$el || (empty($_GET["y"]) && $el==400))
+            printf("<option value='%s' selected>%s</option>\n", $el, $el);
+        else
+            printf("<option value='%s'>%s</option>\n", $el, $el);
+    printf("</select>\n");
+
+    printf("<br><br><input class='Width' type='submit' value='Query Plot'> &nbsp;\n");
+    printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"plotdb.php\"'><br>\n");
+
+    printf("</form>");
+    printf("</td>\n");
+
+//    printf("<td align='right' width='640px' height='400px'>\n");
+    printf("<td align='right'>\n");
+    if (!empty($_GET))
+    {
+        $img="plot.php?par=hallo";
+        foreach($_GET as $var => $val)
+        {
+            if ($var=="Set2" && $_GET["set"]=="datasets")
+                continue;
+            if ($var=="Set" && $_GET["set"]=="datasets" && !empty($val))
+            {
+                $img.= "&amp;Set=" . GetSequencesFromDataSet("1");
+                $img.= "&amp;Set2=" . GetSequencesFromDataSet("2");
+                continue;
+            }
+            $img.="&amp;".$var ."=".$val;
+        }
+//        printf("link: %s<br>", $img);
+        printf("<img src='%s' alt='plot'>", $img);
+    }
+    printf("</td></tr>\n");
+    printf("<tr><td colspan='2'>\n");
+    printf("<br>some remarks:\n<ul>");
+    printf("<li>For Runs plotting the whole range (i.e. without giving a range or when giving a too large range) \n");
+    printf("doesn't work with ChartDirector.</li>\n");
+    printf("<li>In Set1 and Set2 Sets can be given: <br>\n ");
+    printf("If 'sequences' is selected e.g. on sequences in Set1 (displayed in blue) and off sequences in Set2 \n");
+    printf("(diplayed in red). <br>\n ");
+    printf("If 'datasets' is selected you can enter a dataset number as Set1. The on data is displayed in blue, \n");
+    printf("the off data in red. <br>\n");
+    printf("&nbsp;&nbsp;&nbsp;Please give the numbers with space as separator (e.g. 40004 40022).<br>\n</<li>\n");
+    printf("<li>0 is not accepted in the ranges fields, please write .0 or 00</li>\n");
+    printf("<li>Be aware, that plotting timestamps, e.g. fRunStart, and strings, e.g. fComment doesn't work. </li>\n");
+    printf("</ul>\n</td>\n</tr>\n");
+
+    /*
+    printf("<tr><td colspan='2'>\n");
+    $query=GetQuery($tables, $joins, "");
+    printf("Q: %s<br>", $query);
+    if (!empty($_GET["Set"]))
+    {
+        $query=GetQuery($tables, $joins, "Set");
+        printf("Q: %s<br>", $query);
+    }
+    if (!empty($_GET["Set2"]))
+    {
+        $query=GetQuery($tables, $joins, "Set2");
+        printf("Q: %s<br>", $query);
+    }
+    printf("</td></tr>");
+    */
+
+    printf("</table>\n");
+    printf("</center>\n");
+
+    echo (file_get_contents("index-footer.html"));
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/plotinclude.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/plotinclude.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/plotinclude.php	(revision 17960)
@@ -0,0 +1,263 @@
+<?php
+
+//arrays and functions for plot.php and plotdb.php
+include("include.php");
+include("magicdefs.php");
+include("db.php");
+
+$tables=array("fSequenceFirst" => "Sequences",
+              "fRunNumber"     => "RunData",
+              "fDataSetNumber" => "DataSets");
+
+$prims=array("SequenceNumber" => "fSequenceFirst",
+             "RunNumber"      => "fRunNumber",
+             "DataSetNumber"  => "fDataSetNumber");
+
+$joins=array("fSequenceFirst" => " LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) "
+             ."LEFT JOIN Calibration USING(fSequenceFirst,fTelescopeNumber) ",
+             "fRunNumber" => " LEFT JOIN DataCheck USING(fRunNumber) ",
+             "fDataSetNumber" =>" LEFT JOIN Ganymed USING(fDataSetNumber) ");
+
+function GetList($host, $user, $pw, $db, $column, $tables)
+{
+    $tab_fSequenceFirst=array("Sequences", "Calibration", "Star");
+    $tab_fRunNumber=array("RunData");
+    $tab_fDataSetNumber=array("DataSets", "Ganymed");
+
+    $table=$tables[$column];
+    foreach(${"tab_".$column} as $tab)
+    {
+        $query="EXPLAIN " . $tab;
+
+        mysql_connect($host, $user, $pw);
+        mysql_select_db($db);
+
+        $result=mysql_query($query);
+
+        while ($row = mysql_fetch_row($result))
+            $list[] = $row[0];
+    }
+    return $list;
+}
+
+function CheckQuery($query)
+{
+    if (strpos($query, " WHERE ")==FALSE)
+        return " WHERE ";
+    else
+        return " AND ";
+}
+
+function GetQuery($tables, $joins, $set)
+{
+    if (empty($_GET["prim"]))
+        $_GET["prim"]="";
+    $primary=$_GET["prim"];
+    if (empty($primary))
+        return "";
+    if (empty($_GET[$primary."Col"]))
+        $_GET[$primary."Col"]="";
+    $column=$_GET[$primary."Col"];
+    $table=$tables[$primary];
+    if (empty($_GET["primstart"]))
+        $_GET["primstart"]="";
+    $primstart=$_GET["primstart"];
+    if (empty($_GET["primstop"]))
+        $_GET["primstop"]="";
+    $primstop=$_GET["primstop"];
+    if (empty($_GET["Start"]))
+        $_GET["Start"]="";
+    $start1=$_GET["Start"];
+    if (empty($_GET["Stop"]))
+        $_GET["Stop"]="";
+    $stop1=$_GET["Stop"];
+
+    if (empty($_GET["fSourceN"]))
+        $_GET["fSourceN"]="";
+    $source=$_GET["fSourceN"];
+
+    $query="SELECT " . $table . "." . $primary . ", ";
+    if ($column==$primary)
+        $query.=$table . "." . $column;
+    else
+        $query.=$column;
+
+    if ($_GET["plot"]=="val")
+    {
+        if (empty($_GET[$primary."Col2"]))
+            $_GET[$primary."Col2"]="";
+        $column2=$_GET[$primary."Col2"];
+        if (empty($_GET["Start2"]))
+            $_GET["Start2"]="";
+        $start2=$_GET["Start2"];
+        if (empty($_GET["Stop2"]))
+            $_GET["Stop2"]="";
+        $stop2=$_GET["Stop2"];
+
+        if ($column2==$primary)
+            $query.=", " . $table . "." . $column2;
+        else
+            $query.=", " . $column2;
+    }
+    $query.=" FROM " . $table;
+    $query.=$joins[$primary];
+
+    if (!empty($source))
+        $query.= " LEFT JOIN Source USING(fSourceKEY) ";
+
+    if (!empty($primstart))
+        $query.= " WHERE " . $table . "." . $primary . " > " . $primstart;
+
+    if (!empty($primstop))
+        $query.= CheckQuery($query) . $table . "." . $primary . " < " . $primstop;
+
+    if (!empty($start1))
+        $query.= CheckQuery($query) . GetTable($table, $column) . " > " . $start1;
+
+    if (!empty($stop1))
+        $query.= CheckQuery($query) . GetTable($table, $column) . " < " . $stop1;
+
+    if ($_GET["plot"]=="val")
+    {
+        if (!empty($start2))
+            $query.= CheckQuery($query) . GetTable($table, $column2) . " > " . $start2;
+
+        if (!empty($stop2))
+            $query.= CheckQuery($query) . GetTable($table, $column2) . " < " . $stop2;
+    }
+
+    if (!empty($set) && !empty($_GET[$set]))
+        $query.= CheckQuery($query) . $table . "." . $primary . " IN (" . str_replace(" ", ",", $_GET[$set]) . ") ";
+
+    if (empty($_GET[$primary."Col3"]))
+        $_GET[$primary."Col3"]="";
+    $column3=$_GET[$primary."Col3"];
+    if (empty($_GET["Start3"]))
+        $_GET["Start3"]="";
+    $start3=$_GET["Start3"];
+    if (empty($_GET["Stop3"]))
+        $_GET["Stop3"]="";
+    $stop3=$_GET["Stop3"];
+
+    if (!empty($start3))
+        $query.= CheckQuery($query) . GetTable($table, $column3) . " > " . $start3;
+
+    if (!empty($stop3))
+        $query.= CheckQuery($query) . GetTable($table, $column3) . " < " . $stop3;
+
+    if (empty($_GET[$primary."Col4"]))
+        $_GET[$primary."Col4"]="";
+    $column4=$_GET[$primary."Col4"];
+    if (empty($_GET["Start4"]))
+        $_GET["Start4"]="";
+    $start4=$_GET["Start4"];
+    if (empty($_GET["Stop4"]))
+        $_GET["Stop4"]="";
+    $stop4=$_GET["Stop4"];
+
+    if (!empty($start4))
+        $query.= CheckQuery($query) . GetTable($table, $column4) . " > " . $start4;
+
+    if (!empty($stop4))
+        $query.= CheckQuery($query) . GetTable($table, $column4) . " < " . $stop4;
+
+    if (!empty($source))
+        $query.= CheckQuery($query) . " fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+    return $query;
+}
+
+//functions for showplots*.php
+function gettypename($type2)
+{
+    switch ($type2)
+    {
+    case "calib":
+        $type="callisto";
+        break;
+    case "signal":
+        $type="callisto";
+        break;
+    case "star":
+        $type="star";
+        break;
+    }
+    return $type;
+}
+
+function getplotname($seq, $tabnum, $type, $type2)
+{
+    $seqlong=str_pad($seq, 8, "0", STR_PAD_LEFT);
+    $seqshort=substr($seqlong, 0, 4);
+    $plot  = "http://datacenter.astro.uni-wuerzburg.de/";
+    $plot .= $type . "/" . str_pad( $seqshort, 4, "0", STR_PAD_LEFT);
+//    $plot .= "/" . $seqlong . "/" . $type2 . $seqlong . "-tab" . $tabnum . ".png";
+    $plot .= "/" . $seqlong . "/" . $type2 . $tabnum . ".png";
+    return $plot;
+}
+
+function getinfofromdb($seq)
+{
+    include("db.php");
+
+    $db_id = mysql_pconnect($host, $user, $pw);
+    if ($db_id==FALSE)
+    {
+        printf("mysql_connect returned the following error: %s\n", mysql_error());
+        die("");
+    }
+    mysql_select_db($db);
+
+    $query0  = "SELECT fSequenceFirst ";
+    $query0 .= ", DATE_FORMAT(ADDDATE(fRunStart,Interval 12 hour), '%Y-%m-%d') as 'ObsNight'";
+    $query0 .= ", fSourceName ";
+    $query0 .= ", fZenithDistanceMin ";
+    $query0 .= ", fZenithDistanceMax ";
+    $query0 .= ", fMeanPedRmsInner ";
+    $query0 .= ", fRunTime/60 as 'UpTime' ";
+    $query0 .= ", if(isnull(fStar), 'N/A', if(isnull(fRateSumEvts), 'no', CONCAT('yes (',fRateSumEvts, ')'))) as 'Sum' ";
+    $query0 .= "FROM Sequences ";
+    $query0 .= "LEFT JOIN Source USING(fSourceKEY) ";
+    $query0 .= "LEFT JOIN Calibration USING(fSequenceFirst) ";
+    $query0 .= "LEFT JOIN Star USING(fSequenceFirst) ";
+    $query0 .= "LEFT JOIN SequenceProcessStatus USING(fSequenceFirst) ";
+    $query0 .= "WHERE fSequenceFirst=".$seq;
+
+//    echo $query0;
+
+    $result0 = mysql_query($query0, $db_id);
+    while ($row0 = mysql_fetch_assoc($result0))
+        $info="<b>".$row0["fSourceName"]."</b> ".$row0["ObsNight"]
+            ." (".$row0["UpTime"]."min)"
+            ." Zd: ".$row0["fZenithDistanceMin"]."-".$row0["fZenithDistanceMax"]
+            ." PedRmsIn: ".$row0["fMeanPedRmsInner"]
+            ." SumTrigger: ".$row0["Sum"];
+
+    mysql_free_result($result0);
+    mysql_close($db_id);
+
+    return $info;
+}
+
+function PrintType2Pulldown($type2)
+{
+    $types=array("calib", "signal", "star");
+    printf("<select name='type2'>\n");
+    foreach($types as $t => $typename)
+        if ($type2==$typename)
+            printf("<option value='%s' selected>%s </option>\n", $type2, $type2);
+        else
+            printf("<option value='%s'>%s </option>\n", $typename, $typename);
+    print("</select>\n");
+}
+
+function PrintHomeHelp()
+{
+    printf("<td valign='top'>\n");
+    printf("<a href='http://www.astro.uni-wuerzburg.de/wiki/Database_Websites'>home</a>\n");
+    printf("<a href='http://www.astro.uni-wuerzburg.de/wiki/Database_Tutorial#showplots:_calib.2C_signal.2C_star'>help</a>\n");
+    printf("</td>\n");
+}
+
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/printtable.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/printtable.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/printtable.php	(revision 17960)
@@ -0,0 +1,100 @@
+<?php
+{
+    function PrintForm($_GET)
+    {
+        if (empty($_GET["fTable"]))
+        {
+            printf("ERROR - No table selected.\n");
+            return;
+        }
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $limits, $rms)
+    {
+        if (empty($_GET["fTable"]))
+        {
+            printf("ERROR - No table selected.\n");
+            return;
+
+        }
+
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $fromtable=$_GET["fTable"];
+        $query0  = "SELECT SQL_CALC_FOUND_ROWS * FROM " . $fromtable;
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable,$val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1")
+            {
+                $alias = array
+                (
+                );
+                $rightalign = array
+                (
+                );
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            }
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, "", "");
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        PrintForm($_GET);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+            PrintPage("1", $host, $user, $pw, $db, "", "");
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/querymc.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/querymc.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/querymc.php	(revision 17960)
@@ -0,0 +1,293 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $fromtable="MCRunData";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0)
+        {
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+            //--------------------------------------------------
+            //$query0 .= " TIMEDIFF(fRunStop, fRunStart), ";
+            // Only available in MySQL>4.1.1
+//            $query0 .= "SUM(if(TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)<0, " .
+//                "TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)+24*60*60, " .
+//                "TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)))/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
+            //--------------------------------------------------
+            $query0 .= " SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "', ";
+//            $query0 .= " Min(fZenithDistance) as '" . $alias["Min(fZenithDistance)"] . "', ";
+//            $query0 .= " Max(fZenithDistance) as '" . $alias["Max(fZenithDistance)"] . "', ";
+            $query0 .= " COUNT(*) as '# Runs' ";
+        }
+        else
+        {
+            $query0 .= " fRunNumber as 'Run#' ";
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On")
+                    if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                        $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM MCRunData ";
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty($joins[$key]))
+                $query0 .= GetJoin($fromtable, $key);
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)// this if clause doesn't work
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
+            $query0 .= "fRunNumber BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+
+/*
+        if (!empty($_GET["fSequenceNo"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0)
+                $query0 .= " AND ";
+
+            $query0 .= " fSequenceFirst = '" . $_GET["fSequenceNo"] . "' ";
+        }
+*/
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable, $key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $query0 .= " ORDER BY " . substr($_GET["fSortBy"], 0, -1) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        /*
+         if (empty($_GET["fRawFileKEY"]))
+         $_GET["fRawFileKEY"]="Off";
+         */
+
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+            
+        if (empty($_GET["fNumEvents"]))
+            $_GET["fNumEvents"]=$first?"On":"";
+
+        if (empty($_GET["fEMin"]))
+            $_GET["fEMin"]=$first?"On":"";
+
+        if (empty($_GET["fEMax"]))
+            $_GET["fEMax"]=$first?"On":"";
+
+        if (empty($_GET["fParticleTypeName"]))
+            $_GET["fParticleTypeName"]="Off";
+
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"querymc.php\" METHOD=\"GET\">\n");
+        printf(" <table>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fNumEvents",        "Num of events");
+        CheckBox("fEMin",             "EMin");
+        CheckBox("fEMax",             "EMax");
+
+        printf("  </tr>\n");
+        printf(" </table>\n");
+         printf(" <p>\n");
+
+        // pull down boxes
+
+        printf(" <table>\n");
+        printf("  <tr><td>\n");
+        PrintPullDown($host, $user, $pw, $db, "ParticleType",     "fParticleTypeName",     "fParticleTypeKEY", "particle type");
+        printf(" </td></tr></table>\n");
+        printf(" <p>\n");
+
+/*
+        if (empty($_GET["fStartDate"]))
+            $timemin = GetMin("fRunStart", "RunData", $host, $user, $pw, $db);
+        else
+            $timemin = $_GET["fStartDate"];
+
+        if (empty($_GET["fStopDate"]))
+            $timemax = GetMax("fRunStart", "RunData", $host, $user, $pw, $db);
+        else
+            $timemax = $_GET["fStopDate"];
+
+        printf("Night&nbsp;(yyyy-mm-dd)&nbsp;from&nbsp;<input name=\"fStartDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">\n", $timemin);
+        printf("to&nbsp;<input name=\"fStopDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">&nbsp;&nbsp;&nbsp;&nbsp;\n", $timemax);
+*/
+
+        if (empty($_GET["fRunMin"]))
+            $min = GetMin("fRunNumber", "MCRunData", $host, $user, $pw, $db);
+        else
+            $min = $_GET["fRunMin"];
+
+        if (empty($_GET["fRunMax"]))
+            $max = GetMax("fRunNumber", "MCRunData", $host, $user, $pw, $db);
+        else
+            $max = $_GET["fRunMax"];
+
+        printf("Runs&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">\n", $min);
+        printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+
+        printf(" <P>\n");
+
+/*
+        printf("Sequ#&nbsp;<input name=\"fSequenceNo\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"");
+        if (!empty($_GET["fSequenceNo"]))
+            printf("%s", $_GET["fSequenceNo"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n");
+*/
+
+        printf(" Results:\n");
+        printf(" <select name=\"fNumResults\">\n");
+
+        $numres = array("10", "20", "50", "100", "200", "500", "1000", "2000");
+        foreach ($numres as $element)
+        {
+            if ($element==$_GET["fNumResults"])
+                printf("<option value=\"%s\" selected>%3s</option>\n", $element, $element);
+            else
+                printf("<option value=\"%s\">%3s</option>\n", $element, $element);
+        }
+        printf(" </select>\n");
+        printf(" &nbsp;&nbsp;&nbsp;\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"querymc.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+        mysql_query("SET BIG_TABLES=1"); // necessary for mySQL <= 4
+
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            printf("<U><B>submitted query:</B></U><BR>%s<BR>", htmlspecialchars($query0));
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors",   "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+            PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup);
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors",   "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/queryrbk.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/queryrbk.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/queryrbk.php	(revision 17960)
@@ -0,0 +1,133 @@
+<?php
+{
+    function PrintForm($_GET)
+    {
+        if (empty($_GET["fDate"]))
+            $_GET["fDate"]=date("Y-m-d");
+
+        printf("<center>\n");
+        printf("<form action=\"queryrbk.php\" METHOD=\"GET\">\n");
+
+        printf("Date&nbsp;(yyyy-mm-dd)&nbsp;<input name=\"fDate\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"");
+        printf("%s\">&nbsp;&nbsp;&nbsp;\n", $_GET["fDate"]);
+
+        printf("Search&nbsp;<A HREF=\"regexp.html\">regexp:</A>&nbsp;<input name=\"fRegexp\" type=\"text\" size=\"32\" maxlength=\"128\" value=\"");
+        if (!empty($_GET["fRegexp"]))
+            printf("%s", $_GET["fRegexp"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n<P>\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("Night&nbsp;(yyyy-mm-dd)&nbsp;<input name=\"fNight\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"");
+        printf("%s\">&nbsp;&nbsp;&nbsp;\n", $_GET["fNight"]);
+
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"queryrbk.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+        {
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+            printf("<input class='Width' type='button' value='Print' onClick='self.location.href=\"%s&amp;fPrintTable=1\"'>&nbsp;&nbsp;&nbsp;\n", htmlspecialchars($_SERVER["REQUEST_URI"]));
+        }
+
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0  = "SELECT SQL_CALC_FOUND_ROWS fRunBookDate AS Date, fRunBookText AS Entry ";
+        $query0 .= "FROM " . $db . ".RunBook ";
+        $query0 .= "WHERE fRunBookDate REGEXP '^" . $_GET["fDate"] . "' ";
+
+        if (!empty($_GET["fRegexp"]))
+            $query0 .= "AND fRunBookText REGEXP '" . $_GET["fRegexp"] . "' ";
+
+        if (!empty($_GET["fNight"]))
+            $query0 .= "AND fRunBookDate < '" . $_GET["fNight"] . " 13:00:00' AND fRunBookDate > ADDDATE( '" . $_GET["fNight"] . " 13:00:00', INTERVAL -1 DAY) ";
+
+        $query0 .= "ORDER BY fRunBookDate";
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+            {
+                $alias = array
+                (
+                 "fRunBookDate"  => "Date",
+                 "fRunBookText"  => "Entry"
+                );
+                $rightalign = array
+                (
+                );
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            }
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db);
+            else
+                PrintPage("2", $host, $user, $pw, $db);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/reference.html
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/reference.html	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/reference.html	(revision 17960)
@@ -0,0 +1,115 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+   
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+   
+<meta name="Author" content="Thomas Bretz">
+   
+<title>Magic Database</title>
+   
+<link rel="stylesheet" type="text/css" href="mars.css">
+</head>
+
+<body background="background.gif" text="#000000" bgcolor="#000099" link="#1122FF" vlink="#8888FF" alink="#FF0000">
+&nbsp;
+
+<center>
+<table class="Main" CELLPADDING=0>
+
+<tr>
+<td class="Edge">
+<img SRC="ecke.gif" ALT="">
+</td>
+<td class="Header">
+<font size=+1><B>Magic Database</B></font><BR>
+</td>
+</tr>
+
+<tr>
+<td COLSPAN=2 BGCOLOR="#FFFFFF">
+<hr SIZE=1 NOSHADE WIDTH="80%">
+<center>
+<table class="Inner" CELLPADDING=15>
+
+<tr class="Block">
+<td>
+<table BORDER=\"1\">
+<tr BGCOLOR='#D0D0D0'>
+<th BGCOLOR='#C0C0C0'>calibration</th>
+<td>inner</td>
+<td>outer</td>
+</tr><tr BGCOLOR='#E0E0E0'>
+<td>unsuitable pixel</td>
+<td> </td>
+<td> </td>
+</tr><tr BGCOLOR='#D0D0D0'>
+<td>unreliable pixel</td>
+<td> 198 </td>
+<td> 90 </td>
+</tr><tr BGCOLOR='#E0E0E0'>
+<td>isolated pixel</td>
+<td>  </td>
+<td>  </td>
+</tr><tr BGCOLOR='#D0D0D0'>
+<td>arrival time</td>
+<td> 1.5 &lt; time &lt; 8.5 &plusmn; 3.5 </td>
+<td> 1.5 &lt; time &lt; 8.5 &plusmn; 3.5 </td>
+</tr><tr BGCOLOR='#E0E0E0'>
+<td>conversion factor (df)</td>
+<td> 0.8 &plusmn; 0.1 </td>
+<td> 3.8 &plusmn; 0.5 </td>
+</tr><tr BGCOLOR='#E0E0E0'>
+<td>conversion factor (spline)</td>
+<td> 1.7 &plusmn; 0.2 </td>
+<td> 6.5 &plusmn; 0.8 </td>
+</tr><tr BGCOLOR='#D0D0D0'>
+<td>mean ped rms</td>
+<td>  </td>
+<td>  </td>
+</tr>
+</table>
+
+</td>
+</tr>
+
+</table>
+</center>
+
+<center>
+<hr NOSHADE WIDTH="80%"><i><font color="#000099"><font size=-1>This Web Site is 
+hosted by Apache for OS/2 and done by <a href="mailto:tbretz@astro.uni-wuerzburg.de">Thomas&nbsp;Bretz</a> and <a href="mailto:dorner@astro.uni-wuerzburg.de">Daniela&nbsp;Dorner</a> .</font></font></i><BR>
+&nbsp;<BR>
+<a href="http://validator.w3.org/check/referer"><img border="0"
+   src="../../valid-html40.png" alt="Valid HTML 4.0!" height="20" width="66"></a>
+</center>&nbsp;
+</tr>
+</table>
+
+<BR>
+
+<table class="Main">
+<tr>
+<!-- This is the old stylish counter....
+  <td ALIGN=RIGHT VALIGN=TOP>NedStat - website access statistics:&nbsp;<a href="http://de.nedstat.net/viewstat.asp?name=magicmars" onMouseover="status='Statistics on Web Access by NedStat.de';return true;" onMouseout="status='';return true;"><img SRC="http://de.nedstat.net/scripts/nedstat.dll?name=magicmars" ALT="STAT" BORDER=0 height=18 width=18 align=TEXTTOP></a></td>
+-->
+<td ALIGN=RIGHT VALIGN=MIDDLE><FONT COLOR="#FFFFFF">NedStat - website access statistics:&nbsp;</FONT>
+<script language='JavaScript' src="http://m1.nedstatbasic.net/basic.js" type="text/javascript"></script>
+<script language="JavaScript" type="text/javascript">          
+<!--
+  nedstatbasic("AAGh1A6qQKZFLpl2rXaOC3LPo1OA", 0);
+// -->
+</script>
+<!--<noscript>-->
+<a target="_self" href="http://v1.nedstatbasic.net/stats?AAGh1A6qQKZFLpl2rXaOC3LPo1OA" onMouseover="status='Statistics on Web Access by NedStat.de';return true;" onMouseout="status='';return true;"></a>
+<!--</noscript>-->
+</td>
+
+</tr>
+</table>
+</center>
+
+</body>
+</html>
+
Index: branches/Mars_McMismatchStudy/datacenter/db/regexp.html
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/regexp.html	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/regexp.html	(revision 17960)
@@ -0,0 +1,389 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+   <meta name="Author" content="Thomas Bretz">
+   <title>MARS: Magic Analysis and Reconstruction Software</title>
+   <link rel="stylesheet" type="text/css" href="mars.css">
+</head>
+
+<body background="background.gif" text="#000000" bgcolor="#000099" link="#1122FF" vlink="#8888FF" alink="#FF0000">
+&nbsp;
+
+<center>
+<table class="Main" CELLPADDING=0>
+
+<tr>
+<td class="Edge"><img SRC="ecke.gif" ALT=""></td>
+<td class="Header">
+<B>M A R S</B><BR><B>M</B>agic <B>A</B>nalysis and <B>R</B>econstruction <B>S</B>oftware
+</td>
+</tr>
+
+<tr>
+<td COLSPAN=2 BGCOLOR="#FFFFFF">
+<hr SIZE=1 NOSHADE WIDTH="80%">
+<center><table class="Inner" CELLPADDING=15>
+
+<tr class="Block">
+<td><b><u><A NAME="OVERVIEW">MySQL Regular Expressions</A>:</u></b>
+<P>
+A <B>regular expression (regex)</B> is a powerful way of specifying a complex search. <P>
+
+  MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 
+  1003.2. MySQL uses the extended version. <P>
+
+  This is a simplistic reference that skips the details. To get more exact information, see 
+  Henry Spencer's <A HREF="#REGEX">regex(7)</A><P>
+
+  A regular expression describes a set of strings. The simplest regexp is one that has no special characters in it. For 
+  example, the regexp <b>hello</B> matches <B>hello</B> and nothing else. <P>
+
+  Non-trivial regular expressions use certain special constructs so that they can match more than one string. For 
+  example, the regexp hello|word matches either the string hello or the string word. <P>
+
+  As a more complex example, the regexp B[an]*s matches any of the strings Bananas, Baaaaas, Bs, and any 
+  other string starting with a B, ending with an s, and containing any number of a or n characters in between. <P>
+
+  A regular expression may use any of the following special characters/constructs:   <P>
+<pre>
+  ^         Match the beginning of a string. 
+            mysql> SELECT "fo\nfo" REGEXP "^fo$";           -> 0 
+            mysql> SELECT "fofo"   REGEXP "^fo";            -> 1 
+
+  $         Match the end of a string. 
+            mysql> SELECT "fo\no" REGEXP "^fo\no$";         -> 1 
+            mysql> SELECT "fo\no" REGEXP "^fo$";            -> 0 
+
+  .         Match any character (including newline). 
+            mysql> SELECT "fofo"  REGEXP "^f.*";            -> 1 
+            mysql> SELECT "fo\nfo" REGEXP "^f.*";           -> 1 
+
+  a*        Match any sequence of zero or more a characters. 
+            mysql> SELECT "Ban"   REGEXP "^Ba*n";           -> 1 
+            mysql> SELECT "Baaan" REGEXP "^Ba*n";           -> 1 
+            mysql> SELECT "Bn"    REGEXP "^Ba*n";           -> 1 
+
+  a+        Match any sequence of one or more a characters. 
+            mysql> SELECT "Ban" REGEXP "^Ba+n";             -> 1 
+            mysql> SELECT "Bn"  REGEXP "^Ba+n";             -> 0 
+
+  a?        Match either zero or one a character. 
+            mysql> SELECT "Bn"   REGEXP "^Ba?n";            -> 1 
+            mysql> SELECT "Ban"  REGEXP "^Ba?n";            -> 1 
+            mysql> SELECT "Baan" REGEXP "^Ba?n";            -> 0 
+
+  de|abc    Match either of the sequences de or abc. 
+            mysql> SELECT "pi"  REGEXP "pi|apa";            -> 1 
+            mysql> SELECT "axe" REGEXP "pi|apa";            -> 0 
+            mysql> SELECT "apa" REGEXP "pi|apa";            -> 1 
+            mysql> SELECT "apa" REGEXP "^(pi|apa)$";        -> 1 
+            mysql> SELECT "pi"  REGEXP "^(pi|apa)$";        -> 1 
+            mysql> SELECT "pix" REGEXP "^(pi|apa)$";        -> 0 
+
+  (abc)*    Match zero or more instances of the sequence abc. 
+            mysql> SELECT "pi"   REGEXP "^(pi)*$";          -> 1 
+            mysql> SELECT "pip"  REGEXP "^(pi)*$";          -> 0 
+            mysql> SELECT "pipi" REGEXP "^(pi)*$";          -> 1 
+
+  {1}       The is a more general way of writing regexps that match many
+  {2,3}     occurrences of the previous atom.   
+              a*          Can be written as a{0,}. 
+              a+          Can be written as a{1,}. 
+              a?          Can be written as a{0,1}.   
+
+              To be more precise, an atom followed by a bound containing one 
+              integer i and no comma matches a sequence of exactly i matches 
+              of the atom. An atom followed by a bound containing one integer i 
+              and a comma matches a sequence of i or more matches of the atom. 
+              An atom followed by a bound containing two integers i and j matches 
+              a sequence of i through j (inclusive) matches of the atom. 
+
+              Both arguments must be in the range from 0 to RE_DUP_MAX (default 255), 
+              inclusive.  If there are two arguments, the second must be greater
+              than or equal to the first. 
+
+  [a-dX]    Matches any character which is (or is not, if ^ is used) either a, b, c, 
+  [^a-dX]   d or X. To include a literal ] character, it must immediately follow 
+            the opening bracket [.  To include a literal - character, it must be 
+            written first or last. So [0-9] matches any decimal digit. Any character 
+            that does not have a defined meaning inside a [] pair has no special 
+            meaning and matches only itself. 
+               mysql> SELECT "aXbc"   REGEXP "[a-dXYZ]";               -> 1 
+               mysql> SELECT "aXbc"   REGEXP "^[a-dXYZ]$";             -> 0 
+               mysql> SELECT "aXbc"   REGEXP "^[a-dXYZ]+$";            -> 1 
+               mysql> SELECT "aXbc"   REGEXP "^[^a-dXYZ]+$";           -> 0 
+               mysql> SELECT "gheis"  REGEXP "^[^a-dXYZ]+$";           -> 1 
+               mysql> SELECT "gheisa" REGEXP "^[^a-dXYZ]+$";           -> 0 
+
+  [[.characters.]] 
+            The sequence of characters of that collating element. characters is 
+            either a single character or a character name like newline. You can 
+            find the full list of character names in 'regexp/cname.h'. 
+
+  [ =character_class=] 
+            An equivalence class, standing for the sequences of characters of all 
+            collating elements equivalent to that one, including itself. 
+
+            For example, if o and (+) are the members of an equivalence class, 
+            then [[=o=]], [[=(+)=]], and [o(+)] are all synonymous. An equivalence 
+            class may not be an endpoint of a range. 
+
+  [:character_class:] 
+            Within a bracket expression, the name of a character class enclosed 
+            in [: and :] stands for the list of all characters belonging to that 
+            class. Standard character class names are: 
+
+            These stand for the character classes defined in the ctype(3) manual 
+            page. A locale may provide others. A character class may not be used 
+            as an endpoint of a range. 
+               mysql> SELECT "justalnums" REGEXP "[[:alnum:]]+";       -> 1 
+               mysql> SELECT "!!" REGEXP "[[:alnum:]]+";               -> 0 
+                        
+  [[:<:]]   These match the null string at the beginning and end of a word 
+  [[:>:]]   respectively.  A word is defined as a sequence of word characters 
+            which is neither preceded nor followed by word characters. A word 
+            character is an alnum character (as defined by ctype(3)) or an 
+            underscore (_). 
+               mysql> SELECT "a word a" REGEXP "[[:<:]]word[[:>:]]";   -> 1 
+               mysql> SELECT "a xword a" REGEXP "[[:<:]]word[[:>:]]";  -> 0 
+                          
+            mysql> SELECT "weeknights" REGEXP "^(wee|week)(knights|nights)$"; -> 1 
+</pre>
+</td></tr>
+<tr class="Block">
+<td>
+<center><h3>--- <A NAME="REGEX"><U>REGEX</U></A>(7) ---</h3></center>
+<B>NAME</B><BR>
+       regex - POSIX 1003.2 regular expressions<P>
+
+<B>DESCRIPTION</B><BR>
+       Regular expressions (``RE''s), as defined in POSIX 1003.2,
+       come in two forms: modern REs  (roughly  those  of  egrep;
+       1003.2  calls  these  ``extended''  REs)  and obsolete REs
+       (roughly those of ed; 1003.2 ``basic'' REs).  Obsolete REs
+       mostly  exist  for backward compatibility in some old pro-
+       grams; they will be discussed at the end.   1003.2  leaves
+       some  aspects  of  RE  syntax and semantics open; `' marks
+       decisions on these aspects that may not be fully  portable
+       to other 1003.2 implementations.<P>
+
+       A (modern) RE is one or more non-empty branches, separated
+       by `|'.  It matches  anything  that  matches  one  of  the
+       branches.<P>
+
+       A  branch is one or more pieces, concatenated.  It matches
+       a match for the first, followed by a match for the second,
+       etc.<P>
+
+       A piece is an atom possibly followed by a single `*', `+',
+       `?', or bound.  An atom followed by `*' matches a sequence
+       of 0 or more matches of the atom.  An atom followed by `+'
+       matches a sequence of 1 or more matches of the  atom.   An
+       atom  followed by `?' matches a sequence of 0 or 1 matches
+       of the atom.<P>
+
+       A bound is `{' followed by an  unsigned  decimal  integer,
+       possibly  followed  by  `,'  possibly  followed by another
+       unsigned decimal integer, always  followed  by  `}'.   The
+       integers  must  lie  between 0 and RE_DUP_MAX (255) inclu-
+       sive, and if there are two of  them,  the  first  may  not
+       exceed the second.  An atom followed by a bound containing
+       one integer i and no comma matches a sequence of exactly i
+       matches of the atom.  An atom followed by a bound contain-
+       ing one integer i and a comma matches a sequence of  i  or
+       more  matches  of  the  atom.  An atom followed by a bound
+       containing two integers i and j matches a  sequence  of  i
+       through j (inclusive) matches of the atom.<P>
+
+       An atom is a regular expression enclosed in `()' (matching
+       a match for the regular expression), an empty set of  `()'
+       (matching  the  null  string),  a  bracket expression (see
+       below), `.'  (matching any single character), `^'  (match-
+       ing  the  null  string  at  the  beginning of a line), `$'
+       (matching the null string at the end of  a  line),  a  `\'
+       followed by one of the characters `^.[$()|*+?{\' (matching
+       that character taken as an ordinary character), a `\' fol-
+       lowed  by  any  other  character  (matching that character
+       taken as an ordinary character, as if the `\' had not been
+       present), or a single character with no other significance
+       (matching that character).  A `{' followed by a  character
+       other  than  a  digit  is  an  ordinary character, not the
+       beginning of a bound.  It is illegal to  end  an  RE  with
+       `\'.<P>
+
+       A  bracket  expression is a list of characters enclosed in
+       `[]'.  It normally matches any single character  from  the
+       list  (but  see  below).   If the list begins with `^', it
+       matches any single character (but see below) not from  the
+       rest of the list.  If two characters in the list are sepa-
+       rated by `-', this is shorthand  for  the  full  range  of
+       characters  between those two (inclusive) in the collating
+       sequence, e.g. `[0-9]' in ASCII matches any decimal digit.
+       It  is  illegal  for two ranges to share an endpoint, e.g.
+       `a-c-e'.  Ranges  are  very  collating-sequence-dependent,
+       and portable programs should avoid relying on them.<P>
+
+       To  include  a  literal `]' in the list, make it the first
+       character (following a possible `^').  To include  a  lit-
+       eral `-', make it the first or last character, or the sec-
+       ond endpoint of a range.  To use  a  literal  `-'  as  the
+       first  endpoint of a range, enclose it in `[.' and `.]' to
+       make it a collating element (see below).  With the  excep-
+       tion  of  these  and some combinations using `[' (see next
+       paragraphs), all other special characters, including  `\',
+       lose  their  special significance within a bracket expres-
+       sion.<P>
+
+       Within a bracket expression, a collating element (a  char-
+       acter,  a  multi-character sequence that collates as if it
+       were a single character, or a collating-sequence name  for
+       either)  enclosed in `[.' and `.]' stands for the sequence
+       of characters of that collating element.  The sequence  is
+       a  single  element  of  the  bracket expression's list.  A
+       bracket expression containing a multi-character  collating
+       element  can  thus  match more than one character, e.g. if
+       the collating sequence includes a `ch' collating  element,
+       then the RE `[[.ch.]]*c' matches the first five characters
+       of `chchcc'.<P>
+
+       Within a bracket expression, a collating element  enclosed
+       in `[=' and `=]' is an equivalence class, standing for the
+       sequences of characters of all collating elements  equiva-
+       lent  to  that  one,  including  itself.  (If there are no
+       other equivalent collating elements, the treatment  is  as
+       if  the  enclosing  delimiters  were  `[.' and `.]'.)  For
+       example, if o and ^ are  the  members  of  an  equivalence
+       class,  then `[[=o=]]', `[[=^=]]', and `[o^]' are all syn-
+       onymous.  An equivalence class may not be an endpoint of a
+       range.<P>
+
+       Within a bracket expression, the name of a character class
+       enclosed in `[:' and `:]' stands for the list of all char-
+       acters  belonging to that class.  Standard character class
+       names are:<P>
+<table>
+<tr><td>alnum</TD><td>digit</td><td>punct</td></tr>
+<tr><td>alpha</TD><td>graph</TD><td>space</td></tr>
+<tr><td>blank</TD><td>lower</TD><td>upper</td></tr>
+<tr><td>cntrl</TD><td>print</TD><td>xdigit</td></tr>
+</table>
+<P>
+       These stand for the character classes defined in ctype(3).
+       A locale may provide others.  A character class may not be
+       used as an endpoint of a range.<P>
+
+       There are two special cases of  bracket  expressions:  the
+       bracket expressions `[[:&lt;:]]' and `[[:&gt;:]]' match the null
+       string at the beginning and end of a word respectively.  A
+       word  is defined as a sequence of word characters which is
+       neither preceded nor followed by word characters.  A  word
+       character  is  an alnum character (as defined by ctype(3))
+       or an underscore.  This is an extension,  compatible  with
+       but not specified by POSIX 1003.2, and should be used with
+       caution in software intended to be portable to other  sys-
+       tems.<P>
+
+       In  the  event  that  an RE could match more than one sub-
+       string of a given string, the RE matches the one  starting
+       earliest  in  the string.  If the RE could match more than
+       one substring starting  at  that  point,  it  matches  the
+       longest.   Subexpressions  also match the longest possible
+       substrings, subject to the constraint that the whole match
+       be  as long as possible, with subexpressions starting ear-
+       lier in the RE taking priority over ones  starting  later.
+       Note  that  higher-level subexpressions thus take priority
+       over their lower-level component subexpressions.<P>
+
+       Match lengths are measured in  characters,  not  collating
+       elements.   A  null  string  is  considered longer than no
+       match at all.  For example, `bb*' matches the three middle
+       characters    of   `abbbc',   `(wee|week)(knights|nights)'
+       matches all ten characters of `weeknights', when  `(.*).*'
+       is  matched  against `abc' the parenthesized subexpression
+       matches all three characters, and when `(a*)*' is  matched
+       against  `bc'  both  the  whole  RE  and the parenthesized
+       subexpression match the null string.<P>
+
+       If case-independent matching is specified, the  effect  is
+       much  as  if  all  case distinctions had vanished from the
+       alphabet.  When an  alphabetic  that  exists  in  multiple
+       cases  appears  as an ordinary character outside a bracket
+       expression, it is effectively transformed into  a  bracket
+       expression containing both cases, e.g. `x' becomes `[xX]'.
+       When it appears inside  a  bracket  expression,  all  case
+       counterparts of it are added to the bracket expression, so
+       that  (e.g.)  `[x]'  becomes  `[xX]'  and  `[^x]'  becomes
+       `[^xX]'.<P>
+
+       No particular limit is imposed on the length of REs.  Pro-
+       grams intended to be portable should not employ REs longer
+       than  256 bytes, as an implementation can refuse to accept
+       such REs and remain POSIX-compliant.<P>
+
+       Obsolete (``basic'') regular expressions differ in several
+       respects.   `|',  `+', and `?' are ordinary characters and
+       there is  no  equivalent  for  their  functionality.   The
+       delimiters  for bounds are `\{' and `\}', with `{' and `}'
+       by themselves ordinary characters.   The  parentheses  for
+       nested  subexpressions are `\(' and `\)', with `(' and `)'
+       by themselves ordinary characters.   `^'  is  an  ordinary
+       character  except at the beginning of the RE or the begin-
+       ning of a parenthesized subexpression, `$' is an  ordinary
+       character  except  at  the  end  of the RE or the end of a
+       parenthesized subexpression, and `*' is an ordinary  char-
+       acter  if  it  appears  at  the beginning of the RE or the
+       beginning of a parenthesized subexpression (after a possi-
+       ble leading `^').  Finally, there is one new type of atom,
+       a back reference: `\' followed by a non-zero decimal digit
+       d  matches  the same sequence of characters matched by the
+       dth parenthesized subexpression (numbering  subexpressions
+       by  the  positions  of  their opening parentheses, left to
+       right), so that (e.g.) `\([bc]\)\1' matches `bb'  or  `cc'
+       but not `bc'.<P>
+
+<B>SEE ALSO</B><BR>
+       POSIX 1003.2, section 2.8 (Regular Expression Notation).<P>
+
+<B>BUGS</B><BR>
+       Having two kinds of REs is a botch.<P>
+
+       The current 1003.2 spec says that `)' is an ordinary char-
+       acter in the absence of an  unmatched  `(';  this  was  an
+       unintentional  result  of  a  wording error, and change is
+       likely.  Avoid relying on it.<P>
+
+       Back references are a dreadful botch, posing  major  prob-
+       lems  for  efficient implementations.  They are also some-
+       what  vaguely  defined   (does   `a\(\(b\)*\2\)*d'   match
+       `abbbd'?).  Avoid using them.<P>
+
+       1003.2's  specification  of  case-independent  matching is
+       vague.  The ``one  case  implies  all  cases''  definition
+       given  above is current consensus among implementors as to
+       the right interpretation.<P>
+
+       The syntax for word boundaries is incredibly ugly.<P>
+
+<B>AUTHOR</B><BR>
+       This page was taken from Henry Spencer's regex package.
+</td>
+</tr>
+
+</table></center>
+
+<center>
+<hr NOSHADE WIDTH="80%"><i><font color="#000099"><font size=-1>This Web Site is 
+hosted by Apache for OS/2 and done by <a href="mailto:tbretz@astro.uni-wuerzburg.de">Thomas&nbsp;Bretz</a>.</font></font></i><BR>
+&nbsp;<BR>
+<a href="http://validator.w3.org/check/referer"><img border="0"
+   src="../../valid-html40.png" alt="Valid HTML 4.0!" height="20" width="66"></a>
+</center>&nbsp;
+</tr>
+</table>
+
+</center>
+
+</body>
+</html>
Index: branches/Mars_McMismatchStudy/datacenter/db/resetseq.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/resetseq.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/resetseq.php	(revision 17960)
@@ -0,0 +1,281 @@
+<?php
+{
+    function PrintPage($host, $user, $pw, $db)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query1="SELECT fMarsVersionName, fStartDate FROM MarsVersion ORDER BY fMarsVersion DESC LIMIT 0,1";
+        $marsresult=mysql_query($query1);
+        $row = mysql_fetch_row($marsresult);
+        $mars=$row[0];
+        $date=$row[1];
+        if (mysql_errno()>0)
+            printf("&nbsp; Error-Number: %s <br>", mysql_errno());
+        if (mysql_error()!="")
+            printf("&nbsp; Error-Message: %s <br>", mysql_error());
+        if (mysql_info()!="")
+            printf("&nbsp; Mysql-Info: %s <br>", mysql_info());
+        mysql_free_result($marsresult);
+        if (empty($mars))
+        {
+            printf("Could not get information for latest Mars version from the database.");
+            return;
+        }
+
+        if (empty($_GET["insert"]))
+        {
+            $query0  = "SELECT SequenceProcessStatus.fSequenceFirst, ";
+//            $query0 .= "if (fCallisto " . " < '" . $date . "', 'to be resetted', ";
+            $query0 .= "if (fCallisto " . " < '" . $date . "', CONCAT('outdated (', (SELECT fMarsVersionName FROM MarsVersion WHERE fCallisto > fStartDate ORDER BY fMarsVersion DESC LIMIT 0,1), ')'), ";
+            $query0 .= "if (not isnull(fCallisto), 'up to date (" . $mars . ")', ";
+            $query0 .= "if (fStartTime > ADDDATE(Now(), INTERVAL -1 DAY) AND isnull(fFailedTime), 'running (" . $mars . ")',";
+            $query0 .= "if (isnull(fFailedTime), 'already resetted', ";
+            $query0 .= " 'crashed or failed')))) as 'calstat', ";
+//            $query0 .= "if (fStar " . " < '" . $date . "', 'to be resetted', ";
+            $query0 .= "if (fStar " . " < '" . $date . "', CONCAT('outdated (', (SELECT fMarsVersionName FROM MarsVersion WHERE fStar > fStartDate ORDER BY fMarsVersion DESC LIMIT 0,1), ')'), ";
+            $query0 .= "if (not isnull(fStar), 'up to date (" . $mars . ")', ";
+            $query0 .= "if (fStartTime > ADDDATE(Now(), INTERVAL -1 DAY) AND isnull(fFailedTime) AND not isnull(fCallisto), 'running (" . $mars . ")',";
+            $query0 .= "if (isnull(fFailedTime), 'already resetted', ";
+            $query0 .= " 'crashed or failed')))) as 'starstat', fProjectName, fRunStart ";
+            $query0 .= "FROM SequenceProcessStatus ";
+            $query0 .= "LEFT JOIN Sequences USING(fSequenceFirst,fTelescopeNumber) ";
+            $query0 .= "LEFT JOIN Project USING(fProjectKEY) ";
+        }
+        else
+        {
+            $query0 = "UPDATE SequenceProcessStatus SET ";
+            if ($_GET["step"]=="callisto")
+                $query0 .="fCallisto=NULL, fFillCallisto=NULL, fStar=NULL, fFillStar=NULL, ";
+            else
+                if ($_GET["step"]=="star")
+                    $query0 .="fStar=NULL, fFillStar=NULL, ";
+            $query0 .="fStartTime=NULL, fFailedTime=NULL, fProgramId=NULL, fReturnCode=NULL ";
+
+            if ($_GET["step"]=="callisto")
+                $query0 .= " WHERE fCallisto " . " < '" . $date . "'";
+            else
+                if ($_GET["step"]=="star")
+                    $query0 .= " WHERE fStar " . " < '" . $date . "'";
+                else
+                    $query0 .= " WHERE (NOT ISNULL(fFailedTime) OR fStartTime < ADDDATE(Now(), INTERVAL -1 DAY))";
+        }
+        if (ereg("^([ ]*[0-9]{5,8}[ ]*[,])*[ ]*[0-9]{5,8}[ ]*$",$_GET["Seqs"]))
+        {
+            if (strpos($query0, " WHERE ")==FALSE || (strpos($query0, " CONCAT(")==TRUE && strpos($query0, " WHERE ")==TRUE))
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+            $query0 .=" SequenceProcessStatus.fSequenceFirst IN (" . $_GET["Seqs"] . ")";
+        }
+        else
+        {
+            echo "You have to give the sequences, which you want to reset, in the correct format, i.e. sequence numbers separated by ','.<br>";
+            return;
+        }
+        if (empty($_GET["step"]))
+        {
+            echo "Please choose what you want to reset: <br>";
+            echo "crashed processes (i.e. running longer than 1 day or failed), callisto or star.<br>";
+            return;
+        }
+
+        $result0=mysql_query($query0);
+        if (mysql_errno()>0)
+            printf("&nbsp; Errorno: %s <br>", mysql_errno());
+        if (mysql_error()!="")
+            printf("&nbsp; Errormsg: %s <br>", mysql_error());
+        if (!empty($_GET["insert"]) && !empty($_GET["step"]))
+        {
+            printf("%s Sequences have been resetted. <br><br>\n", mysql_affected_rows());
+            if (mysql_info()!="")
+                printf("Mysql-Info: %s <br><br>\n", mysql_info());
+        }
+        else
+        {
+            if (mysql_affected_rows()==0)
+            {
+                echo "No sequence to reset.<br>";
+                echo "The sequences you listed are already resetted.<br>";
+                mysql_free_result($result0);
+                return;
+            }
+//            echo "The status of the sequences you entered: <br>\n";
+            $star="";
+            $callisto="";
+            $crashed="";
+            $calcolor='black';
+            $starcolor='black';
+            $style='normal';
+            $col   = FALSE;
+            $bgcolor='#C0C0C0';
+            $checked=0;
+            printf("<table border='0' align='center'>\n");
+            printf("<tr bgcolor='%s'>\n<th style='padding-left:1ex;padding-right:1ex'>\n<u>Sequence</u>\n</th>\n", $bgcolor);
+            printf("\n<th>\n<u>ProjectName</u>\n</th>\n");
+            printf("<th>\n<u>Status Callisto</u>\n</th>");
+            printf("\n<th>\n<u>Status Star</u>\n</th>\n");
+            printf("\n<th>\n<u>Starttime</u>\n</th>\n");
+            printf("</tr>\n");
+            while ($row = mysql_fetch_row($result0))
+            {
+                if (ereg('outdated', $row[2]) && $_GET["step"]=='star')
+                {
+                    $star[]=$row[0];
+                    $starcolor='green';
+                    $style='bold';
+                    $row[2]=str_replace('outdated', 'marked for reset', $row[2]);
+                }
+                if (ereg('outdated', $row[1]) && $_GET["step"]=='callisto')
+                {
+                    $callisto[]=$row[0];
+                    $calcolor='green';
+                    $starcolor='green';
+                    $style='bold';
+                }
+                if (($row[1]=='crashed or failed' || $row[2]=='crashed or failed') && $_GET["step"]=='crashed')
+                {
+                    $crashed[]=$row[0];
+                    if ($row[1]=='crashed or failed')
+                    {
+                        $calcolor='green';
+                        $style='bold';
+                    }
+                    else
+                    {
+                        $starcolor='green';
+                        $style='bold';
+                    }
+                }
+                if (!$col)
+                    $bgcolor='#E0E0E0';
+                else
+                    $bgcolor='#D0D0D0';
+                $col = !$col;
+                printf("<tr bgcolor='%s'>\n<td align='center' style='font-weight:%s'>\n%s \n</td>\n", $bgcolor, $style, $row[0]);
+                printf("<td style='padding-left:1ex;padding-right:1ex'>\n %s \n</td>\n", $row[3]);
+                printf("<td style='padding-left:1ex;padding-right:1ex'>\n <font color='%s'>%s </font>\n</td>\n", $calcolor, $row[1]);
+                printf("<td style='padding-left:1ex;padding-right:1ex'>\n <font color='%s'>%s </font>\n</td>\n", $starcolor, $row[2]);
+                printf("<td style='padding-left:1ex;padding-right:1ex'>\n %s \n</td>\n", $row[4]);
+                printf("</tr>\n");
+                $calcolor='black';
+                $starcolor='black';
+                $style='normal';
+                $checked+=1;
+            }
+            printf("</table>\n");
+
+            if ($_GET["step"]=="crashed")
+                printf("<br>\n You chose to reset only the sequences which are crashed or failed.<br>\n");
+            else
+                printf("<br>\n Only the sequences which are not 'up to date', 'running' or 'resetted', can be resetted.<br>\n");
+            if (empty($star) && empty($callisto) && empty($crashed))
+                echo "With your choice no sequences would be resetted.";
+            else
+                echo "With your choice the following sequences would be resetted:\n ";
+            $marked=0;
+            if (!empty($star))
+            {
+                foreach($star as $num => $seq)
+                    echo $seq . " ";
+                $marked+=count($star);
+            }
+            if (!empty($callisto))
+            {
+                foreach($callisto as $num => $seq)
+                    echo $seq . " ";
+                $marked+=count($callisto);
+            }
+            if (!empty($crashed))
+            {
+                foreach($crashed as $num => $seq)
+                    echo $seq . " ";
+                $marked+=count($crashed);
+            }
+            printf("<br>\n Listed: %d <br> Marked: %d", $checked, $marked);
+            printf("<br>\n<br>\nTo <b>reset</b> the <font color='green'>green marked entries</font>, please press the button 'Reset Sequences'.<br><br>\n");
+
+            mysql_free_result($result0);
+            printf("<input type='button' value='Reset Sequences' onClick='self.location.href=\"%s&amp;insert=On\"'>&nbsp;&nbsp;&nbsp;\n", htmlspecialchars($_SERVER["REQUEST_URI"]));
+
+        }
+        mysql_close($db_id);
+
+//        PrintSubmittedQuery($query0, "1", $db, "old");
+
+    }
+
+    include ("include.php");
+    include ("menu.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    echo (file_get_contents("index-header.html"));
+
+    $ips=array("132.187.47.10", //Thomas
+               "129.194.169.21" //Dani ISDC
+              );
+    if (!in_array($_SERVER['REMOTE_ADDR'], $ips))
+    {
+        echo "You are not allowed to reset sequences.<br>";
+        echo "If you want to reset your sequences in the automatic analysis, please contact Daniela Dorner.<br>";
+        echo (file_get_contents("index-footer.html"));
+        return;
+    }
+
+    $environment = sizeof($_GET);
+
+    //init
+    if (empty($_GET["Seqs"]))
+        $_GET["Seqs"]="";
+    if (empty($_GET["step"]))
+        $_GET["step"]="";
+
+    //print form
+    printf("<center>\n");
+    printf("<form action=\"resetseq.php\" METHOD=\"GET\">\n");
+
+    printf("<input type='radio' name='step' value='crashed' %s> crashed processes &nbsp;", $_GET["step"]=="crashed" ? "checked" : "");
+    printf("<input type='radio' name='step' value='callisto' %s> callisto &nbsp;", $_GET["step"]=="callisto" ? "checked" : "");
+    printf("<input type='radio' name='step' value='star' %s> star<br>", $_GET["step"]=="star" ? "checked" : "");
+
+    printf("<table>\n<tr>\n<td align='left'>\nSequences: \n</td>\n</tr>\n<tr>\n<td>\n");
+    printf("<input name='Seqs' type='text' size='80' maxlength='300' value='%s'>\n</td>\n</tr>\n</table>\n<br>\n", $_GET["Seqs"]);
+
+    ini_set("mysql.trace_mode", "Off");
+//    ini_set("display_errors", "Off");
+
+    printf("<input type='submit' value='Check Sequence Status'>&nbsp;&nbsp;&nbsp;\n");
+    printf("<input class='Width' type='button' value='Clear Form' onClick='self.location.href=\"resetseq.php\"'>&nbsp;&nbsp;&nbsp;\n");
+//    if (!empty($_GET["step"]) && ereg("^([ ]*[0-9]{5,8}[ ]*[,])*[ ]*[0-9]{5,8}[ ]*$",$_GET["Seqs"]))
+//        printf("<input type='checkbox' name='insert' value='On'>insert\n");
+    printf("<br>\n");
+    printf("</form>\n");
+    printf("</center>\n");
+    printf("</td>\n</tr>\n");
+    printf("<tr class='Block'>\n<td>\n");
+
+    if ($environment==0)
+    {
+        printf("No query submitted yet.<br>\n");
+        printf("To reset sequences, please insert them in the following format: <i>12345,87654321</i><br>\n");
+        printf("and choose whether you want to reset just crashed processes, callisto (this includes star) or just star.<br>\n");
+        printf("You can enter up to 300 characters in the sequences field.<br>\n");
+    }
+    else
+        PrintPage($host, $user, $pw, $db);
+
+    echo (file_get_contents("index-footer.html"));
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/run_comment.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/run_comment.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/run_comment.php	(revision 17960)
@@ -0,0 +1,293 @@
+<?php
+{
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (empty($_GET["fMode"]))
+    {
+        $_GET["fMode"]="view";
+        $sign=strpos($_SERVER['REQUEST_URI'], "?")==false ? "?" : "&";
+        $_SERVER['REQUEST_URI']=$_SERVER['REQUEST_URI'] . $sign . "fMode=view";
+    }
+
+    if (empty($_GET["fRunID"]))
+        $_GET["fRunID"]="all";
+
+    if (empty($_GET["fSequenceID"]))
+        $_GET["fSequenceID"]="all";
+
+    if (empty($_GET["fTable"]))
+    {
+        $_GET["fTable"]="RunComments";
+//        $_GET["fTable"]="SequenceComments";
+        $sign=strpos($_SERVER['REQUEST_URI'], "?")==false ? "?" : "&";
+        $_SERVER['REQUEST_URI']=$_SERVER['REQUEST_URI'] . $sign . "fTable=RunComments";
+    }
+
+    if (empty($_GET["fNight"]))
+        $_GET["fNight"]=date("Ymd", time()-(12*60*60));
+
+    if (strcmp($_GET["fMode"], "tooltip")!=0)
+        echo (file_get_contents("index-header.html"));
+
+
+    //
+    // insert/update part
+    //
+    include ("ldap_include.php");
+    if (strcmp($_GET["fMode"], "insert")==0 || strcmp($_GET["fMode"], "update")==0)
+    {
+        if (!isset($_SERVER['PHP_AUTH_USER']))
+        {
+            header('WWW-Authenticate: Basic realm="Edit Run Comments"');
+            header('HTTP/1.0 401 Unauthorized');
+            return;
+        }
+        else
+        {
+            //echo "The password is not yet evaluated, but the username is inserted into the DB.<br>";
+            if (!CheckUsernameAndPassword($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], GetLDAPOptions()))
+                return;
+        }
+        if (!empty($_GET["fComment"]))
+        {
+            include("db2.php");
+            $db_id = mysql_pconnect($host, $user, $pw);
+            if ($db_id==FALSE)
+            {
+                printf("mysql_connect returned the following error: %s\n", mysql_error());
+                die("");
+            }
+            mysql_select_db($db);
+            //for insert
+            if (strcmp($_GET["fMode"], "insert")==0)
+                $query0 = "INSERT " . $_GET["fTable"] . " SET ";
+            //for update
+            if (strcmp($_GET["fMode"], "update")==0)
+                $query0 = "UPDATE " . $_GET["fTable"] . " SET ";
+            //for both
+            $query0.= " fComment='".str_replace("'", "\'", $_GET["fComment"])."'";
+            $query0.= ", fUser='".$_SERVER['PHP_AUTH_USER']."'";
+            //for insert
+            if (strcmp($_GET["fMode"], "insert")==0)
+            {
+                $query0.=", fNight=".$_GET["fNight"];
+                if (strcmp($_GET["fTable"], "RunComments")==0)
+                    $query0.= ", fRunID=".$_GET["fRunID"];
+                if (strcmp($_GET["fTable"], "SequenceComments")==0)
+                    $query0.= ", fSequenceID=".$_GET["fSequenceID"];
+            }
+            //for update
+            if (strcmp($_GET["fMode"], "update")==0)
+            {
+                $query2="SELECT fCommentKEY FROM " . $_GET["fTable"];
+                $query2.=" WHERE fNight=".$_GET["fNight"];
+                if (strcmp($_GET["fTable"], "RunComments")==0)
+                    $query2.=" AND fRunID=".$_GET["fRunID"];
+                if (strcmp($_GET["fTable"], "SequenceComments")==0)
+                    $query2.=" AND fSequenceID=".$_GET["fSequenceID"];
+                $query2.=" AND fComment='".str_replace("'", "\'", $_GET["fOldComment"])."'";
+                $result2=mysql_query($query2, $db_id);
+                $row2 = mysql_fetch_row($result2);
+                $commentkey=$row2[0];
+                mysql_free_result($result2);
+                $query0.=" WHERE fCommentKEY=".$commentkey;
+            }
+            //echo "insert query: " . $query0 . "<br>";
+            $result0=mysql_query($query0, $db_id);
+            mysql_close($db_id);
+        }
+    }
+
+
+
+    //
+    // display part
+    //
+    include("db.php");
+    if (strcmp($_GET["fMode"], "tooltip")!=0)
+    {
+        //mode
+        printf("With this page, you can \n");
+        //view mode
+        if (strcmp($_GET["fMode"], "view")==0)
+            printf("<b>view</b>,\n");
+        else
+            printf("<a href='%s'>view</a>,\n", str_replace($_GET["fMode"], 'view', $_SERVER['REQUEST_URI']));
+        //update mode
+        if (strcmp($_GET["fMode"], "update")==0)
+            printf("<b>update</b> and\n");
+        else
+            printf("<a href='%s'>update</a> and \n", str_replace($_GET["fMode"], 'update', $_SERVER['REQUEST_URI']));
+        //insert mode
+        if (strcmp($_GET["fMode"], "insert")==0)
+            printf("<b>insert</b>\n");
+        else
+            printf("<a href='%s'>insert</a> \n", str_replace($_GET["fMode"], 'insert', $_SERVER['REQUEST_URI']));
+
+        //table
+        printf("entries in the tables <b>%s</b> \n", $_GET["fTable"]);
+        if (strcmp($_GET["fTable"], "RunComments")==0)
+            printf(" and <a href='%s'>SequenceComments</a> \n", str_replace($_GET["fTable"], 'SequenceComments', $_SERVER['REQUEST_URI']));
+        else
+            printf(" and <a href='%s'>RunComments</a> \n", str_replace($_GET["fTable"], 'RunComments', $_SERVER['REQUEST_URI']));
+        //database
+        printf("from the DB %s.<br><br>\n", $db);
+
+        //insert field for run/sequence number
+        printf("<form action=\"run_comment.php\" METHOD=\"GET\">\n");
+        if (strcmp($_GET["fTable"], "RunComments")==0)
+        {
+            printf("Run#&nbsp;(YYYYMMDD_FFF)&nbsp;<input title='Enter here Night in the format YYYYMMDD or \"all\" to query all comments.' name=\"fNight\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">\n", $_GET["fNight"]);
+            printf("_ <input title='Enter here RunID in the format FFF or \"all\" (only viewing mode) to query all comments of one night.' name=\"fRunID\" type=\"text\" size=\"3\" maxlength=\"3\" value=\"%s\">\n", $_GET["fRunID"]);
+        }
+        if (strcmp($_GET["fTable"], "SequenceComments")==0)
+        {
+            printf("Sequence#&nbsp;(YYYYMMDD_FFF)&nbsp;<input title='Enter here Night in the format YYYYMMDD or \"all\" to query all comments.' name=\"fNight\" type=\"text\" size=\"8\" maxlength=\"8\" value=\"%s\">\n", $_GET["fNight"]);
+            printf("_ <input title='Enter here SequenceID in the format FFF or \"all\" (only viewing mode) to query all comments of one night.' name=\"fSequenceID\" type=\"text\" size=\"3\" maxlength=\"3\" value=\"%s\">\n", $_GET["fSequenceID"]);
+        }
+        printf("<input type='hidden' name='fMode' value='%s'>", $_GET["fMode"]);
+        printf("<input type='hidden' name='fTable' value='%s'>", $_GET["fTable"]);
+        printf("<input type='submit' value='Get Comments'><br><br>\n");
+        printf("</form>\n");
+    }
+
+    if (!(preg_match("/20[0-9][0-9][01][0-9][0-3][0-9]/",$_GET["fNight"])
+          || (preg_match("/all/",$_GET["fNight"]) && strcmp($_GET["fMode"], "view")==0)))
+    {
+        printf("-%s-<br>", $_GET["fMode"]);
+        printf("Please enter a valid number for the Night (format: YYYYMMDD).");
+        return;
+    }
+
+    if (strcmp($_GET["fTable"], "RunComments")==0 &&
+        (!(preg_match("/[0-9][0-9]?[0-9]?/",$_GET["fRunID"])
+           || (preg_match("/all/",$_GET["fRunID"]) && strcmp($_GET["fMode"], "view")==0))))
+    {
+        printf("Please enter a valid number for the RunID (format: FFF, e.g. 001).");
+        return;
+    }
+
+    if (strcmp($_GET["fTable"], "SequenceComments")==0 &&
+        (!(preg_match("/[0-9][0-9]?[0-9]?/",$_GET["fSequenceID"])
+          || (preg_match("/all/",$_GET["fSequenceID"]) && strcmp($_GET["fMode"], "view")==0))))
+    {
+        printf("Please enter a valid number for the SequenceID (format: FFF, e.g. 001).");
+        return;
+    }
+
+    $db_id = mysql_pconnect($host, $user, $pw);
+    if ($db_id==FALSE)
+    {
+        printf("mysql_connect returned the following error: %s\n", mysql_error());
+        die("");
+    }
+    mysql_select_db($db);
+
+    if (strcmp($_GET["fTable"], "RunComments")==0)
+        $query1 = "SELECT CONCAT(fNight,'_', LPAD(fRunID, 3, 0))";
+    if (strcmp($_GET["fTable"], "SequenceComments")==0)
+        $query1 = "SELECT CONCAT(fNight,'_', LPAD(fSequenceID, 3, 0))";
+    $query1 .= ", fComment FROM " . $_GET["fTable"] . "  ";
+
+    if (strcmp($_GET["fNight"], "all")!=0)
+    {
+        $query1 .= "WHERE fNight=".$_GET["fNight"];
+        if (strcmp($_GET["fTable"], "RunComments")==0)
+            if (strcmp($_GET["fRunID"], "all")!=0)
+                $query1 .=" AND fRunID=".$_GET["fRunID"];
+        if (strcmp($_GET["fTable"], "SequenceComments")==0)
+            if (strcmp($_GET["fSequenceID"], "all")!=0)
+                $query1 .=" AND fSequenceID=".$_GET["fSequenceID"];
+    }
+    if (strcmp($_GET["fTable"], "RunComments")==0)
+        $query1 .= " ORDER BY fNight, fRunID, fCommentKEY ";
+    if (strcmp($_GET["fTable"], "SequenceComments")==0)
+        $query1 .= " ORDER BY fNight, fSequenceID, fCommentKEY ";
+
+    //printf("Query: %s <br>\n\n", $query1);
+    $result1=mysql_query($query1, $db_id);
+    printf("Found %d comment(s).\n\n", mysql_num_rows($result1));
+    if (strcmp($_GET["fMode"], "tooltip")!=0)
+    {
+        printf("<br>\n");
+        printf("<table BORDER='0' style='margin-top:1ex'>");
+        $col   = FALSE;
+        printf("<tr BGCOLOR='#C0C0C0'><td>Run#</td><td>Comment</td></tr>");
+    }
+    while ($row1 = mysql_fetch_row($result1))
+    {
+        if (strcmp($_GET["fMode"], "tooltip")!=0)
+        {
+            if (!$col)
+                printf("<tr BGCOLOR='#E0E0E0'>\n");
+            else
+                printf("<tr BGCOLOR='#D0D0D0'>\n");
+            $col = !$col;
+
+            if (strcmp($_GET["fMode"], "update")==0)
+                printf("<form style='display:inline' action=\"run_comment.php\" METHOD=\"GET\">\n");
+            printf("<td>\n%s\n</td>\n", $row1[0]);
+            if (strcmp($_GET["fMode"], "update")==0)
+            {
+                printf("<td>\n");
+                printf("<input type='text' size='50' maxlength='255' name='fComment' value='%s'>\n", htmlspecialchars($row1[1],ENT_QUOTES));
+                printf("<input type='hidden' name='fOldComment' value='%s'>\n", htmlspecialchars($row1[1],ENT_QUOTES));
+                printf("<input type='hidden' name='fMode' value='%s'>\n", $_GET["fMode"]);
+                printf("<input type='hidden' name='fNight' value='%s'>\n", $_GET["fNight"]);
+                printf("<input type='hidden' name='fRunID' value='%s'>\n", $_GET["fRunID"]);
+                printf("<input type='hidden' name='fSequenceID' value='%s'>\n", $_GET["fSequenceID"]);
+                printf("<input type='hidden' name='fTable' value='%s'>\n", $_GET["fTable"]);
+                printf("<input type='submit' value='Update Comment'>\n");
+                printf("</td>\n");
+                printf("</form>\n");
+            }
+            else
+                printf("<td>\n%s\n</td>\n", $row1[1]);
+            printf("</tr>\n");
+        }
+        else
+        {
+            if (strcmp($_GET["fTable"], "RunComments")==0)
+                printf("%s_%03d: %s\n", $_GET["fNight"], $_GET["fRunID"], $row1[1]);
+            if (strcmp($_GET["fTable"], "SequenceComments")==0)
+                printf("%s_%03d: %s\n", $_GET["fNight"], $_GET["fSequenceID"], $row1[1]);
+        }
+    }
+    //insert mode
+    if (strcmp($_GET["fMode"], "insert")==0)
+    {
+        printf("<tr BGCOLOR='#C0C0C0'>");
+        if (strcmp($_GET["fTable"], "RunComments")==0)
+            printf("<td>%s_%s</td>\n", $_GET["fNight"], $_GET["fRunID"]);
+        if (strcmp($_GET["fTable"], "SequenceComments")==0)
+            printf("<td>%s_%s</td>\n", $_GET["fNight"], $_GET["fSequenceID"]);
+        printf("<td>\n");
+        printf("<form style='display:inline' action=\"run_comment.php\" METHOD=\"GET\">\n");
+        printf("<input type='text' size='50' maxlength='255' name='fComment'>\n");
+        printf("<input type='hidden' name='fMode' value='%s'>\n", $_GET["fMode"]);
+        printf("<input type='hidden' name='fNight' value='%s'>\n", $_GET["fNight"]);
+        printf("<input type='hidden' name='fRunID' value='%s'>\n", $_GET["fRunID"]);
+        printf("<input type='hidden' name='fSequenceID' value='%s'>\n", $_GET["fSequenceID"]);
+        printf("<input type='hidden' name='fTable' value='%s'>\n", $_GET["fTable"]);
+        printf("<input type='submit' value='Insert Comment'>\n");
+        printf("</form>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+    }
+    if (strcmp($_GET["fMode"], "tooltip")!=0)
+        printf("</table>");
+
+    if (strcmp($_GET["fMode"], "update")==0)
+        printf("Remark: You can update only one comment at once.");
+
+    mysql_free_result($result1);
+    mysql_close($db_id);
+
+    if (strcmp($_GET["fMode"], "tooltip")!=0)
+        echo (file_get_contents("index-footer.html"));
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/runinfo-aio.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/runinfo-aio.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/runinfo-aio.php	(revision 17960)
@@ -0,0 +1,387 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs)
+    {
+        $fromtable="RunData";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0 || ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0) || $statusgroups>0)
+        {
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+
+            if ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0)
+            {
+                $query0 .= " DATE_FORMAT(ADDDATE(fRunStart,Interval 12 hour), '";
+                switch($_GET["fGroupByDate"])
+                {
+                case "Year":
+                    $query0 .= "%Y ";
+                    break;
+                case "Month":
+                    $query0 .= "%Y-%m ";
+                    break;
+                case "Night":
+                    $query0 .= "%Y-%m-%d ";
+                    break;
+                }
+                $query0 .= "')  AS GroupByDate, ";
+            }
+
+            //--------------------------------------------------
+            //$query0 .= " TIMEDIFF(fRunStop, fRunStart), ";
+            // Only available in MySQL>4.1.1
+            $query0 .= "SUM(if(TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)<0, " .
+                "TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)+24*60*60, " .
+                "TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)))/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
+            //--------------------------------------------------
+            $query0 .= " SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "', ";
+            $query0 .= " Min(fZenithDistance) as '" . $alias["Min(fZenithDistance)"] . "', ";
+            $query0 .= " Max(fZenithDistance) as '" . $alias["Max(fZenithDistance)"] . "', ";
+            $query0 .= " COUNT(*) as '# Runs' ";
+
+            if ($statusgroups>0)
+            {
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .= ", (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval 12 hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "' ";
+//                        $query0 .= " (if(IsNull(" . $key . "), 'not done' ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+
+                $query0 .= ", COUNT(*) AS '# Runs'";
+
+            }
+        }
+        else
+        {
+            //$query0 .= " RunData.fRunNumber as 'Run#' ";
+            //$query0 .= " Concat(RunData.fTelescopeNumber,':', RunData.fRunNumber,':', RunData.fFileNumber) as 'Run' ";
+            $query0 .= " Concat('M', RunData.fTelescopeNumber,':', LPAD(RunData.fRunNumber,8, ' '),'/', LPAD(RunData.fFileNumber, 3, ' ')) as 'Tel:Run/File' ";
+
+            if (empty($_GET["fSendTxt"]) && !empty($_GET["fLinks"]))
+            {
+                $query0 .= ", CONCAT('<A&ws;HREF=\"queryrbk.php?fNight=', date_format(adddate(fRunStart, interval +13 HOUR), '%Y-%m-%d') , '&amp;fDate=2\">rbk</A>') ";
+                $query0 .= " as 'Links'";
+            }
+
+            foreach ($_GET as $key => $element)
+                if ($key!="fLinks" && $_GET[$key]=="On" && $key!="fTest")
+                    if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                        $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM RunData ";
+
+        $query0 .= " LEFT JOIN RunProcessStatus USING(fRunNumber,fTelescopeNumber,fFileNumber) ";
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty($joins[$key]))
+                $query0 .= GetJoin($fromtable,$key);
+
+        if ($_GET["fTest"]!="On")
+        {
+            if ($_GET["fSourceName"]!="On")
+                $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
+            $query0 .= " WHERE fTest='no'";
+        }
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)// this if clause doesn't work
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= StatusQuery("fCCFileAvail", $needs, $timelimits);
+        $query0 .= StatusQuery("fCaCoFileAvail", $needs, $timelimits);
+        $query0 .= StatusQuery("fCaCoFileFound", $needs, $timelimits);
+        $query0 .= StatusQuery("fRawFileAvail", $needs, $timelimits);
+        $query0 .= StatusQuery("fDataCheckDone", $needs, $timelimits);
+        $query0 .= StatusQuery("fTimingCorrection", $needs, $timelimits);
+
+        if ((!empty($_GET["fRunMin"]) || $_GET["fRunMin"]=="0") && !empty($_GET["fRunMax"]))
+            $query0 .= "RunData.fRunNumber BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+
+        if ((!empty($_GET["fZDMin"]) || $_GET["fZDMin"]==0) && !empty($_GET["fZDMax"]))
+            $query0 .= "AND fZenithDistance BETWEEN " . $_GET["fZDMin"] . " AND  " . $_GET["fZDMax"] . " ";
+
+/*
+        if (!empty($_GET["fDate"]))
+            $query0 .= " AND fRunStart REGEXP \"^" . $_GET["fDate"] . "\" ";
+*/
+
+        if (!empty($_GET["fSourceN"]))
+            $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+        if (!empty($_GET["fStartDate"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0)
+                $query0 .= " AND ";
+
+            $startdate=substr($_GET["fStartDate"], 0, 10);
+            if ($startdate=="0000-00-00")
+                $query0 .=" fRunStart >= '" . $startdate . " 00:00:00' ";
+            else
+                $query0 .= " fRunStart >= ADDDATE('" . $startdate . " 13:00:00', INTERVAL -1 DAY) ";
+        }
+
+        if (!empty($_GET["fStopDate"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0)
+                $query0 .= " AND ";
+
+            $stopdate=substr($_GET["fStopDate"], 0, 10);
+            $query0 .= " fRunStart < '" . $stopdate . " 13:00:00' ";
+        }
+
+        if (!empty($_GET["fSequenceNo"]) || $_GET["fSequenceNo"]=="0")
+        {
+            if (strpos(strrev($query0), " DNA ")!=0)
+                $query0 .= " AND ";
+
+            $query0 .= " fSequenceFirst = '" . $_GET["fSequenceNo"] . "' ";
+        }
+
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable,$key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0)
+            if (strpos($query0, " GROUP BY ")==FALSE)
+                $query0 .= " GROUP BY GroupByDate ";
+            else
+                $query0 .= ", GroupByDate ";
+
+        if ($statusgroups>0)
+        {
+            if (strpos($query0, " GROUP BY ")==FALSE)
+                $query0 .= " GROUP BY  ";
+            else
+                $query0 .= ",  ";
+            $num = $statusgroups;
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable, $val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+        else
+            $query0 .=" ORDER BY RunData.fRunNumber ASC";
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+
+        if (empty($_GET["fTest"]))
+            $_GET["fTest"]=$first?"On":"";
+
+        if (empty($_GET["fNumEvents"]))
+            $_GET["fNumEvents"]=$first?"On":"";
+
+        if (empty($_GET["fRunStart"]))
+            $_GET["fRunStart"]=$first?"On":"";
+
+        if (empty($_GET["fZenithDistance"]))
+            $_GET["fZenithDistance"]=$first?"On":"";
+
+        if (empty($_GET["fRunTypeName"]))
+            $_GET["fRunTypeName"]=$first?"On":"";
+
+        if (empty($_GET["fSourceName"]))
+            $_GET["fSourceName"]=$first?"On":"";
+
+        if (empty($_GET["fMeanTriggerRate"]))
+            $_GET["fMeanTriggerRate"]=$first?"On":"";
+
+        if (empty($_GET["fExcludedFDAName"]))
+            $_GET["fExcludedFDAName"]=$first?"On":"";
+
+        if (empty($_GET["fSequenceNo"]))
+            $_GET["fSequenceNo"]="";
+
+        InitRunInfo($_GET, $first);
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"runinfo-aio.php\" METHOD=\"GET\">\n");
+
+        printf("<input id='sh' type='hidden' name='fShowHide' value='");
+        if (!empty($_GET["fShowHide"]))
+            printf("%s", $_GET["fShowHide"]);
+        else
+            printf("1000000010");
+        printf("'>\n");
+        printf("<img id='allbutton' src='minus.png' alt='-' onclick=\"showhide('all')\"> <b>Menu</b>&nbsp;&nbsp;&nbsp;&nbsp;\n");
+        printf("&nbsp;&nbsp;<img id='infobutton'   src='plus.png' alt='+' onClick=\"showhide('info');showhide('info2')\"> RunInfo    \n");
+        printf("&nbsp;&nbsp;<img id='statbutton'   src='plus.png' alt='+' onClick=\"showhide('stat');showhide('fail')\">  StatusInfo \n");
+        printf("&nbsp;&nbsp;<img id='rangesbutton' src='plus.png' alt='+' onClick=\"showhide('ranges')\">                 Ranges     \n");
+
+        printf(" <div id='all' style='display:block'>");
+        PrintRunInfoMenu();
+        PrintRunInfo2Menu($host,$user,$pw,$db);
+        PrintRunStatMenu();
+        PrintFailMenu();
+        printf(" <div id='ranges' style='display:none'>");
+        PrintSequMenu($host,$user,$pw,$db);
+        PrintNightRangeMenu($host,$user,$pw,$db, "RunData");
+        printf("<p>");
+        PrintZdRangeMenu($host,$user,$pw,$db);
+        PrintRunRangeMenu($host,$user,$pw,$db);
+        printf(" <P>\n");
+        PrintSourceMenu($host,$user,$pw,$db);
+        PrintGroupByDateMenu();
+        printf("<p>");
+        printf("</div>");
+        printf("</div>");
+        printf(" <P>\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        PrintNumResPullDown();
+        PrintButtons("runinfo-aio.php");
+
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+        mysql_query("SET BIG_TABLES=1"); // necessary for mySQL <= 4
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("menu.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors",   "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors",   "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/sequence.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/sequence.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/sequence.php	(revision 17960)
@@ -0,0 +1,628 @@
+<?php
+{
+    function CreateQuery($_GET)
+    {
+        $query0  = "SELECT ";
+        //main (0-18)
+        $query0 .= " Sequences.fSequenceFirst, fSequenceLast, ";//0,1
+        $query0 .= " fSourceName, fProjectName, ";//2,3
+        $query0 .= " fRunStart, fRunTime, fNumEvents, ";//4,5,6
+        $query0 .= " fZenithDistanceMin, fZenithDistanceMax, ";//7,8
+        $query0 .= " fAzimuthMin, fAzimuthMax, ";//9,10
+        $query0 .= " fHvSettingsName, fDiscriminatorThresholdTableName, ";//11,12
+        $query0 .= " fL1TriggerTableName, fL2TriggerTableName, ";//13,14
+        $query0 .= " fTriggerDelayTableName, fTestFlagName, ";//15,16
+        $query0 .= " fLightConditionsName, fManuallyChangedName, ";//17,18
+        //steps (19-24)
+        $query0 .= " fSequenceFileWritten, fAllFilesAvail, ";//19,20
+        $query0 .= " fCallisto, fFillCallisto, ";//21,22
+        $query0 .= " fStar, fFillStar, ";//23,24
+        //calibration (25-42)
+        $query0 .= " fUnsuitableInner, fUnsuitableOuter, ";//25,26
+        $query0 .= " fUnreliableInner, fUnreliableOuter, ";//27,28
+        $query0 .= " fIsolatedInner, fIsolatedOuter, fIsolatedMaxCluster, ";//29,30,31
+        $query0 .= " fArrTimeMeanInner, fArrTimeMeanOuter, ";//32,33
+        $query0 .= " fArrTimeRmsInner, fArrTimeRmsOuter, ";//34,35
+        $query0 .= " fConvFactorInner, fConvFactorOuter, ";//36,37
+        $query0 .= " fMeanPedRmsInner, fMeanPedRmsOuter, ";//38,39
+        $query0 .= " fMeanSignalInner, fMeanSignalOuter, ";//40,41
+        $query0 .= " fPulsePosMean, ";//42
+        //myon,star (43-51)
+        $query0 .= " fPSF, fRatio, fMuonRate, ";//43,44,45
+        $query0 .= " fMuonNumber, fEffOnTime, fDataRate, ";//46,47,48
+        $query0 .= " fMaxHumidity, fMeanNumberIslands, fInhomogeneity, fEffOnTime/fRunTime, ";//49,50,51,52
+        $query0 .= " CONCAT('<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), 'callisto', LPAD(CONCAT(Sequences.fSequenceFirst , '.html'), 13,'0') , '\">cal-log</A>') as 'CalLink', ";//53
+        $query0 .= " CONCAT('<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/star/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), 'star', LPAD(CONCAT(Sequences.fSequenceFirst , '.html'), 13,'0') , '\">star-log</A>') as 'StarLink', ";//54
+        $query0 .= " CONCAT('<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/sequences/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/sequence', LPAD(CONCAT(Sequences.fSequenceFirst , '.txt'), 12,'0') , '\">', 'sequ-file</a>') as 'SequLink' ";//55
+
+        $query0 .= " FROM Sequences ";
+
+        $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
+        $query0 .= " LEFT JOIN Project USING(fProjectKEY) ";
+        $query0 .= " LEFT JOIN HvSettings USING(fHvSettingsKEY) ";
+        $query0 .= " LEFT JOIN DiscriminatorThresholdTable USING(fDiscriminatorThresholdTableKEY) ";
+        $query0 .= " LEFT JOIN L1TriggerTable USING(fL1TriggerTableKEY) ";
+        $query0 .= " LEFT JOIN L2TriggerTable USING(fL2TriggerTableKEY) ";
+        $query0 .= " LEFT JOIN TriggerDelayTable USING(fTriggerDelayTableKEY) ";
+        $query0 .= " LEFT JOIN TestFlag USING(fTestFlagKEY) ";
+        $query0 .= " LEFT JOIN LightConditions USING(fLightConditionsKEY) ";
+        $query0 .= " LEFT JOIN ManuallyChanged USING(fManuallyChangedKEY) ";
+        $query0 .= " LEFT JOIN SequenceProcessStatus USING(fSequenceFirst,fTelescopeNumber) ";
+        $query0 .= " LEFT JOIN Calibration USING(fSequenceFirst,fTelescopeNumber) ";
+        $query0 .= " LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) ";
+
+
+        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
+            $query0 .= " WHERE Sequences.fSequenceFirst between " . $_GET["fRunMin"] . " and " . $_GET["fRunMax"] ;
+        if (!empty($_GET["fSequenceNo"]))
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+            $query0 .= " Sequences.fSequenceFirst='" . $_GET["fSequenceNo"] . "'";
+        }
+        if (!empty($_GET["fSourceN"]))
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+            $query0 .= " fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+        }
+        $query0 .= " ORDER BY Sequences.fSequenceFirst ";
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+
+        if (empty($_GET["fAll"]))
+            $_GET["fAll"]=$first?"On":"";
+
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"sequence.php\" METHOD=\"GET\">\n");
+
+        printf("Sequ#&nbsp;<input name=\"fSequenceNo\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"");
+        if (!empty($_GET["fSequenceNo"]))
+            printf("%s", $_GET["fSequenceNo"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n");
+//        printf("Sequence&nbsp;&nbsp;<input name=\"fSequence\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"\">&nbsp;&nbsp;\n");
+
+        if (empty($_GET["fRunMin"]))
+            $min = GetMin("fSequenceFirst", "Sequences", $host, $user, $pw, $db);
+        else
+            $min = $_GET["fRunMin"];
+
+        if (empty($_GET["fRunMax"]))
+            $max = GetMax("fSequenceFirst", "Sequences", $host, $user, $pw, $db);
+        else
+            $max = $_GET["fRunMax"];
+
+        printf("Sequences&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">\n", $min);
+        printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+
+        if ($_GET["fAll"]=="On")
+            $checked = "checked";
+        else
+            $checked = "";
+        printf("<input type=\"checkbox\" name=\"fAll\" value=\"On\" %s>all information\n", $checked);
+
+        printf(" <P>\n");
+
+        printf("Source&nbsp;(<A HREF=\"regexp.html\">regexp</A>)&nbsp;<input name=\"fSourceN\" type=\"text\" size=\"15\" maxlength=\"15\" value=\"");
+        if (!empty($_GET["fSourceN"]))
+            printf("%s", $_GET["fSourceN"]);
+        printf("\">&nbsp;&nbsp;&nbsp;\n");
+
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"sequence.php\"'>&nbsp;&nbsp;&nbsp;\n");
+//        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+//            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Print' onClick='self.location.href=\"%s&fPrintTable=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function GetStatus($step)
+    {
+        if (is_null($step))
+            return "<font color='#FF0000'>not done</font>";
+        else
+        {
+            if (strpos($step, "1970-01-01 00:00:00")==FALSE)
+                return "done";
+            else
+                return "not to be done";
+        }
+        return "there is an error -> tell Dani";
+    }
+
+    function GetCulm($azmin, $azmax)
+    {
+        $cul1=0;
+        $cul2=180;
+        if (($azmin < $cul1 && $azmax > $cul1) || ($azmin < $cul2 && $azmax > $cul2))
+            return "<font color='#FF0000'>yes</font>";
+        else
+            return "no";
+    }
+
+    function QueryRuns($type, $sequ, $db_id, $db)
+    {
+        $query1  = "SELECT fRunNumber, fCalibrationScriptName FROM RunData ";
+        $query1 .= " LEFT JOIN RunType USING(fRunTypeKEY) ";
+        $query1 .= " LEFT JOIN CalibrationScript USING(fCalibrationScriptKEY) ";
+        $query1 .= " WHERE fSequenceFirst=" . $sequ . " AND fRunTypeName='" . $type . "'";
+
+        mysql_select_db($db);
+        $runs = mysql_query($query1, $db_id);
+        $numruns = mysql_num_rows($runs);
+        $calscript=mysql_result($runs, 0, 1);
+        printf(" <td align='left'>");
+        for ($i=0 ; $i<$numruns ; $i++)
+        {
+            $run=mysql_result($runs, $i, 0);
+            if ($i!=0)
+                printf(", ");
+            printf(" %s ", $run);
+        }
+        printf(" </td>\n");
+        printf(" <td> %s ", $calscript);
+        printf(" </td>\n");
+     }
+
+    function QueryMissingFiles($column, $sequ, $db_id, $db)
+    {
+        $query2  = "SELECT RunData.fRunNumber FROM RunData ";
+        $query2 .= " LEFT JOIN RunProcessStatus USING(fRunNumber,fTelescopeNumber,fFileNumber) ";
+        $query2 .= " WHERE fSequenceFirst=" . $sequ . " AND IsNull(" . $column . ")";
+
+        mysql_select_db($db);
+        $files = mysql_query($query2, $db_id);
+        $numfiles = mysql_num_rows($files);
+        printf(" <td align='left'>");
+        for ($i=0 ; $i<$numfiles ; $i++)
+        {
+            $file=mysql_result($files, $i, 0);
+            if ($i!=0)
+                printf(", ");
+            printf(" %s ", $file);
+        }
+        printf(" </td>\n");
+     }
+
+
+    function PrintSequenceInfo($result0, $db_id, $db, $calibtabs, $signaltabs, $startabs)
+    {
+        $numres = mysql_num_rows($result0);
+
+        printf("<center>");
+        printf("<table BORDER=\"0\">\n");
+        printf("<tr><td>");
+        printf("# of Sequences: %d ", $numres);
+        printf("</td></tr>");
+
+        for ($i=0 ; $i<$numres ; $i++)
+        {
+            $firstrun=mysql_result($result0, $i, 0);
+            $num=sprintf("%08d",$firstrun);
+            $num2=substr($num,0,4);
+            $lastrun=mysql_result($result0, $i, 1);
+            $source=mysql_result($result0, $i, 2);
+            $project=mysql_result($result0, $i, 3);
+            $starttime=mysql_result($result0, $i, 4);
+            $duration=mysql_result($result0, $i, 5);
+            $numevents=mysql_result($result0, $i, 6);
+            $zdmin=mysql_result($result0, $i, 7);
+            $zdmax=mysql_result($result0, $i, 8);
+            $azmin=mysql_result($result0, $i, 9);
+            $azmax=mysql_result($result0, $i, 10);
+            $hv=mysql_result($result0, $i, 11);
+            $dt=mysql_result($result0, $i, 12);
+            $l1tt=mysql_result($result0, $i, 13);
+            $l2tt=mysql_result($result0, $i, 14);
+            $td=mysql_result($result0, $i, 15);
+            $testflag=mysql_result($result0, $i, 16);
+            $lightcond=mysql_result($result0, $i, 17);
+            $manuallychanged=mysql_result($result0, $i, 18);
+            $sequfile=mysql_result($result0, $i, 19);
+            $filesavail=mysql_result($result0, $i, 20);
+            $callisto=mysql_result($result0, $i, 21);
+            $star=mysql_result($result0, $i, 22);
+            $fillcallisto=mysql_result($result0, $i, 23);
+            $fillstar=mysql_result($result0, $i, 24);
+            $unsi=mysql_result($result0, $i, 25);
+            $unso=mysql_result($result0, $i, 26);
+            $unri=mysql_result($result0, $i, 27);
+            $unro=mysql_result($result0, $i, 28);
+            $isoi=mysql_result($result0, $i, 29);
+            $isoo=mysql_result($result0, $i, 30);
+            $imc=mysql_result($result0, $i, 31);
+            $arrtimei=mysql_result($result0, $i, 32);
+            $arrtimeo=mysql_result($result0, $i, 33);
+            $arrtimermsi=mysql_result($result0, $i, 34);
+            $arrtimermso=mysql_result($result0, $i, 35);
+            $convi=mysql_result($result0, $i, 36);
+            $convo=mysql_result($result0, $i, 37);
+            $meanpedrmsi=mysql_result($result0, $i, 38);
+            $meanpedrmso=mysql_result($result0, $i, 39);
+            $meansignali=mysql_result($result0, $i, 40);
+            $meansignalo=mysql_result($result0, $i, 41);
+            $pulsposmean=mysql_result($result0, $i, 42);
+            $psf=mysql_result($result0, $i, 43);
+            $ratio=mysql_result($result0, $i, 44);
+            $muonrate=mysql_result($result0, $i, 45);
+            $muonnum=mysql_result($result0, $i, 46);
+            $effontime=mysql_result($result0, $i, 47);
+            $datarate=mysql_result($result0, $i, 48);
+            $maxhum=mysql_result($result0, $i, 49);
+            $meannumislands=mysql_result($result0, $i, 50);
+            $inhom=mysql_result($result0, $i, 51);
+            $relontime=mysql_result($result0, $i, 52);
+            $callink=mysql_result($result0, $i, 53);
+            $starlink=mysql_result($result0, $i, 54);
+            $sequlink=mysql_result($result0, $i, 55);
+
+            printf("<tr><td>");
+
+            printf(" <table BORDER=\"1\">");
+            printf(" <tr BGCOLOR='#C0C0C0'>\n");
+            printf(" <th>Sequence#: <a href=\"http://www.astro.uni-wuerzburg.de/datacenter/sequences/%s/sequence%s.txt\">%s</a> </th>", $num2, $num, $firstrun);
+            printf(" </tr><tr BGCOLOR='#D0D0D0' ALIGN='left'>\n");
+            printf(" <th> %s, %s, zd: %s&deg;-%s&deg;, %.2fmin ",
+                   $source, $starttime, $zdmin, $zdmax, $duration/60);
+            if (!is_null($star))
+                printf(", <font color='green'>image files available</font> ");
+            printf(" </td>\n");
+            printf(" </tr><tr>\n");
+            printf(" <td>\n");
+
+            printf("</td></tr><tr><td>\n");
+
+            printf(" <table BORDER=\"1\">");
+            printf(" <tr BGCOLOR='#C0C0C0'>\n");
+            printf(" <th colspan=\"4\">conditions</th>");
+            printf(" <th colspan=\"3\">muon parameter</th>\n");
+            printf(" </tr><tr BGCOLOR='#E0E0E0'>\n");
+            printf(" <td>light</td>\n");
+            printf(" <td>max hum</td>\n");
+            printf(" <td>zd</td>\n");
+            printf(" <td>culmination</td>");
+            if (!is_null($fillstar))
+            {
+                printf(" <td>muon rate</td>\n");
+                printf(" <td>ratio</td>\n");
+                printf(" <td>psf</td>\n");
+            }
+            printf(" </tr><tr BGCOLOR='#E0E0E0' align='right'>");
+            printf(" <td>%s</td>\n", $lightcond);
+            printf(" <td>%s %%</td>\n", $maxhum);
+            printf(" <td>%s&deg;-%s&deg;</td>\n", $zdmin, $zdmax);
+            printf(" <td>%s</td>\n", GetCulm($azmin, $azmax));
+            if (!is_null($fillstar))
+            {
+                printf(" <td> %sHz </td>\n", $muonrate);
+                printf(" <td> %s </td>\n", $ratio);
+                printf(" <td> %smm </td>\n", $psf);
+            }
+            printf(" </tr></table>");
+
+
+            if ($_GET["fAll"]=="On")
+            {
+                printf("</td></tr><tr><td>\n");
+                printf("</td></tr><tr><td>\n");
+
+                printf(" <table BORDER=\"1\">");
+                printf(" <tr BGCOLOR='#C0C0C0'>\n");
+                printf(" <th colspan=\"6\">general information</th>");
+                printf(" </tr>\n");
+                printf(" <tr BGCOLOR='#E0E0E0'>\n");
+                printf(" <td>source name</td>\n");
+                printf(" <td># events</td>\n");
+                printf(" <td>project name</td>\n");
+                printf(" <td>light conditions</td>\n");
+                printf(" <td>manually changed</td>\n");
+                printf(" <td>test flag</td>");
+                printf(" </tr><tr BGCOLOR='#E0E0E0'>");
+                printf(" <td> %s </td>\n", $source);
+                printf(" <td> %s </td>\n", $numevents);
+                printf(" <td> %s </td>\n", $project);
+                printf(" <td> %s </td>\n", $lightcond);
+                printf(" <td> %s </td>\n", $manuallychanged);
+                printf(" <td> %s </td>\n", $testflag);
+                printf(" </tr></table>");
+
+                printf("</td></tr><tr><td>\n");
+
+                printf(" <table BORDER=\"1\">");
+                printf(" <tr BGCOLOR='#C0C0C0'>\n");
+                printf(" <th colspan=\"5\">trigger & camera</th>");
+                printf(" </tr>\n");
+                printf(" <tr BGCOLOR='#E0E0E0'>\n");
+                printf(" <td>l1 trigger</td>\n");
+                printf(" <td>l2 trigger</td>\n");
+                printf(" <td>trigger delay</td>\n");
+                printf(" <td>HvSettings</td>\n");
+                printf(" <td>DT</td>");
+                printf(" </tr><tr BGCOLOR='#E0E0E0'>");
+                printf(" <td> %s </td>\n", $l1tt);
+                printf(" <td> %s </td>\n", $l2tt);
+                printf(" <td> %s </td>\n", $td);
+                printf(" <td> %s </td>\n", $hv);
+                printf(" <td> %s </td>\n", $dt);
+                printf(" </tr></table>");
+
+                printf("</td></tr><tr><td>\n");
+
+                printf(" <table BORDER=\"1\">");
+                printf(" <tr BGCOLOR='#C0C0C0'>\n");
+                printf(" <th colspan=\"6\">steps</th>");
+                printf(" </tr>\n");
+                printf(" <tr BGCOLOR='#E0E0E0' align='center'>\n");
+                printf(" <td>sequencefile</td>\n");
+                printf(" <td>files avail</td>\n");
+                printf(" <td>callisto</td>\n");
+                printf(" <td>fillcal</td>\n");
+                printf(" <td>star</td>");
+                printf(" <td>fillstar</td>");
+                printf(" </tr><tr BGCOLOR='#E0E0E0' align='right'>");
+                printf(" <td> %s </td>\n", GetStatus($sequfile));
+                printf(" <td> %s </td>\n", GetStatus($filesavail));
+                printf(" <td> %s </td>\n", GetStatus($callisto));
+                printf(" <td> %s </td>\n", GetStatus($fillcallisto));
+                printf(" <td> %s </td>\n", GetStatus($star));
+                printf(" <td> %s </td>\n", GetStatus($fillstar));
+                printf(" </tr>\n");
+                printf(" <tr BGCOLOR='#E0E0E0' align='center'>\n");
+                printf(" <td>%s</td>\n", $sequlink);
+                printf(" <td><br></td>\n");
+                printf(" <td>%s</td>\n", $callink);
+                printf(" <td><br></td>\n");
+                printf(" <td>%s</td>", $starlink);
+                printf(" <td><br></td>");
+                printf(" </tr></table>");
+
+                printf("</td></tr><tr><td>\n");
+
+                if (!is_null($fillcallisto))
+                {
+                    printf(" <table BORDER=\"1\">");
+                    printf(" <tr BGCOLOR='#D0D0D0'>");
+                    printf(" <th BGCOLOR='#C0C0C0'>calibration (<a href=\"reference.html\">ref</a>)</th>\n");
+                    printf(" <td>inner</td>\n");
+                    printf(" <td>outer</td>");
+                    printf(" </tr><tr BGCOLOR='#E0E0E0'>");
+                    printf(" <td>unsuitable pixel</td>\n");
+                    printf(" <td align='right'> %s </td>\n", $unsi);
+                    printf(" <td align='right'> %s </td>\n", $unso);
+                    printf(" </tr><tr BGCOLOR='#D0D0D0'>");
+                    printf(" <td>unreliable pixel</td>\n");
+                    printf(" <td align='right'> %s </td>\n", $unri);
+                    printf(" <td align='right'> %s </td>\n", $unro);
+                    printf(" </tr><tr BGCOLOR='#E0E0E0'>");
+                    printf(" <td>isolated pixel</td>\n");
+                    printf(" <td align='right'> %s </td>\n", $isoi);
+                    printf(" <td align='right'> %s </td>\n", $isoo);
+                    printf(" </tr><tr BGCOLOR='#D0D0D0'>");
+                    printf(" <td>isolated max cluster</td>\n");
+                    printf(" <td colspan=\"2\" align='right'> %s </td>\n", $imc);
+                    printf(" </tr><tr BGCOLOR='#E0E0E0'>");
+                    printf(" <td>arrival time</td>\n");
+                    printf(" <td align='right'> %s &plusmn; %s </td>\n", $arrtimei, $arrtimermsi);
+                    printf(" <td align='right'> %s &plusmn; %s </td>\n", $arrtimeo, $arrtimermso);
+                    printf(" </tr><tr BGCOLOR='#D0D0D0'>");
+                    printf(" <td>conversion factor</td>\n");
+                    printf(" <td align='right'> %s </td>\n", $convi);
+                    printf(" <td align='right'> %s </td>\n", $convo);
+                    printf(" </tr><tr BGCOLOR='#E0E0E0'>");
+                    printf(" <td>mean ped rms</td>\n");
+                    printf(" <td align='right'> %s </td>\n", $meanpedrmsi);
+                    printf(" <td align='right'> %s </td>\n", $meanpedrmso);
+                    printf(" </tr><tr BGCOLOR='#D0D0D0'>");
+                    printf(" <td>mean signal</td>\n");
+                    printf(" <td align='right'> %s </td>\n", $meansignali);
+                    printf(" <td align='right'> %s </td>\n", $meansignalo);
+                    printf(" </tr><tr BGCOLOR='#E0E0E0'>");
+                    printf(" <td>mean pulse pos</td>\n");
+                    printf(" <td colspan=\"2\" align='right'> %s </td>\n", $pulsposmean);
+                    printf(" </tr>");
+                    printf(" </table>");
+
+                    printf("</td></tr><tr><td>\n");
+                }
+
+                if (!is_null($fillstar))
+                {
+                    printf(" <table BORDER=\"1\">");
+                    printf(" <tr BGCOLOR='#C0C0C0'>");
+                    printf(" <th colspan=\"9\">star</th>\n");
+                    printf(" </tr><tr BGCOLOR='#D0D0D0' ALIGN='center'>");
+                    printf(" <td># islands</td>\n");
+                    printf(" <td># muons</td>\n");
+                    printf(" <td>effontime</td>\n");
+                    printf(" <td>datarate</td>\n");
+                    printf(" <td>muon rate</td>\n");
+                    printf(" <td>ratio</td>\n");
+                    printf(" <td>psf</td>\n");
+                    printf(" <td>inhom</td>\n");
+                    printf(" <td>rel. ontime</td>\n");
+                    printf(" <tr BGCOLOR='#E0E0E0' ALIGN='right'>");
+                    printf(" <td> %s </td>\n", $meannumislands);
+                    printf(" <td> %s </td>\n", $muonnum);
+                    printf(" <td> %ss </td>\n", $effontime);
+                    printf(" <td> %sHz </td>\n", $datarate);
+                    printf(" <td> %sHz </td>\n", $muonrate);
+                    printf(" <td> %s </td>\n", $ratio);
+                    printf(" <td> %smm </td>\n", $psf);
+                    printf(" <td> %s </td>\n", $inhom);
+                    printf(" <td> %s </td>\n", $relontime);
+                    printf(" </tr>");
+                    printf(" </table>");
+
+                    printf("</td></tr><tr><td>");
+                }
+
+
+                printf(" <table BORDER=\"1\">");
+                printf(" <tr BGCOLOR='#C0C0C0'>");
+                printf(" <th>plots</th>\n");
+                printf(" <tr><td>calib: ");
+                foreach($calibtabs as $key => $element)
+                    if (!$key==0)
+                        printf("<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/%s/%s/calib%s-tab%s.png\">%s</a> ", $num2, $num, $num, $key, $element);
+                printf("</td></tr>");
+                printf(" <tr><td>signal: ");
+                foreach($signaltabs as $key => $element)
+                    if (!$key==0)
+                        printf("<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/%s/%s/signal%s-tab%s.png\">%s</a> ", $num2, $num, $num, $key, $element);
+                printf("</td></tr>");
+                printf(" <tr><td>star: ");
+                foreach($startabs as $key => $element)
+                    if (!$key==0)
+                        printf("<a href=\"http://www.astro.uni-wuerzburg.de/datacenter/star/%s/%s/star%s-tab%s.png\">%s</a> ", $num2, $num, $num, $key, $element);
+                printf("</td></tr>");
+
+                printf(" </tr>");
+                printf(" </table>");
+
+                printf(" <table BORDER=\"1\">");
+                printf(" <tr BGCOLOR='#C0C0C0'>");
+                printf(" <th><A HREF=\"runinfo.php?fRunStart=On&fZenithDistance=On&fRunMin=%s&fMeanTriggerRate=On&fRunTypeName=On&fRunMax=%s&fNumEvents=On&fSourceName=On&fExcludedFDAKEY=1&fSequenceFirst=On&fRawFileAvail=On&fCCFileAvail=On&fCaCoFileAvail=On&fNumResults=500\">runs</A></th>", $firstrun, $lastrun);
+                printf(" <td>runs</td>\n");
+                printf(" <td>calscript</td>\n");
+                printf(" </tr><tr BGCOLOR='#D0D0D0' ALIGN='center'>");
+                printf(" <td>dataruns</td>\n");
+                QueryRuns("Data", $firstrun, $db_id, $db);
+                printf(" </tr><tr BGCOLOR='#E0E0E0' ALIGN='center'>");
+                printf(" <td>pedruns</td>\n");
+                QueryRuns("Pedestal", $firstrun, $db_id, $db);
+                printf(" </tr><tr BGCOLOR='#D0D0D0' ALIGN='center'>");
+                printf(" <td>calruns</td>\n");
+                QueryRuns("Calibration", $firstrun, $db_id, $db);
+                printf(" </tr>");
+                printf(" </table>");
+
+                if (is_null($filesavail))
+                {
+                    printf(" <table BORDER=\"1\">");
+                    printf(" <tr BGCOLOR='#C0C0C0'>");
+                    printf(" <th>missing files</th>");
+                    printf(" <td>run# of missing files</td>\n");
+                    printf(" </tr><tr BGCOLOR='#D0D0D0' ALIGN='center'>");
+                    printf(" <td>rawfiles</td>\n");
+                    QueryMissingFiles("fRawFileAvail", $firstrun, $db_id, $db);
+                    printf(" </tr><tr BGCOLOR='#E0E0E0' ALIGN='center'>");
+                    printf(" <td>ccfiles</td>\n");
+                    QueryMissingFiles("fCCFileAvail", $firstrun, $db_id, $db);
+                    printf(" </tr><tr BGCOLOR='#D0D0D0' ALIGN='center'>");
+                    printf(" <td>cacofiles</td>\n");
+                    QueryMissingFiles("fCaCoFileAvail", $firstrun, $db_id, $db);
+                    printf(" </tr>");
+                    printf(" </table>");
+                }
+
+
+            }
+            printf(" </table>");
+            printf("</td></tr><tr><td><br></td></tr>");
+
+        }
+        printf("</table>\n");
+
+        printf("</center>\n");
+        printf("</tr><tr class='Block'><td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $calibtabs, $signaltabs, $startabs)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET);
+
+        $result0 = mysql_query($query0, $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintSequenceInfo($result0, $db_id, $db, $calibtabs, $signaltabs, $startabs);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("tabs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $calibtabs, $signaltabs, $startabs);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $calibtabs, $signaltabs, $startabs);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $calibtabs, $signaltabs, $startabs);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/sequinfo-aio.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/sequinfo-aio.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/sequinfo-aio.php	(revision 17960)
@@ -0,0 +1,460 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs)
+    {
+        $fromtable="Sequences";
+
+        $groups = 0;
+        foreach ($checkgroup as $element)
+            if ($element==-1)
+                $groups++;
+
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($groups>0 || ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0) || $statusgroups>0)
+        {
+            if ($groups>0)
+                foreach ($checkgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
+
+            if ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0)
+            {
+                $query0 .= " DATE_FORMAT(ADDDATE(fRunStart,Interval 12 hour), '";
+                switch($_GET["fGroupByDate"])
+                {
+                case "Year":
+                    $query0 .= "%Y ";
+                    break;
+                case "Month":
+                    $query0 .= "%Y-%m ";
+                    break;
+                case "Night":
+                    $query0 .= "%Y-%m-%d ";
+                    break;
+                }
+                $query0 .= "')  AS GroupByDate, ";
+            }
+
+            //--------------------------------------------------
+            $query0 .= "SUM(fRunTime)/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
+            //--------------------------------------------------
+            $query0 .= " SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "', ";
+            $query0 .= " Min(fZenithDistanceMin) as '" . $alias["Min(fZenithDistanceMin)"] . "', ";
+            $query0 .= " Max(fZenithDistanceMax) as '" . $alias["Max(fZenithDistanceMax)"] . "', ";
+            $query0 .= " COUNT(*) as '# Sequ' ";
+
+            if ($statusgroups>0)
+            {
+                foreach ($checkstatusgroup as $key => $element)
+                    if ($element==-1)
+                        $query0 .= ", (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval 12 hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "' ";
+//                        $query0 .= " (if(IsNull(" . $key . "), 'not done' ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+
+                $query0 .= ", COUNT(*) as '# Sequ'";
+
+            }
+        }
+        else
+        {
+            if (!empty($_GET["fSendTxt"]))
+                $query0 .= " " . $fromtable . ".fSequenceFirst as '" . $alias["fSequenceFirst"] . "' ";
+            else
+            {
+                //old version using fRunMin, fRunMax
+                //$query0 .= " CONCAT('<A&ws;HREF=\"runinfo-aio.php?',  'fRunStart=On', '&amp;fZenithDistance=On', '&amp;fRunMin=', Sequences.fSequenceFirst, '&amp;fMeanTriggerRate=On', '&amp;fTest=On', '&amp;fRunTypeName=On', '&amp;fRunMax=', fSequenceLast, '&amp;fNumEvents=On', '&amp;fSourceName=On&amp;', 'fExcludedFDAKEY=1', '&amp;fSequenceFirst=On', '&amp;fRawFileAvail=On', '&amp;fCCFileAvail=On', '&amp;fCaCoFileAvail=On', '&amp;fNumResults=500\">', Sequences.fSequenceFirst, '</A>') ";
+                //new version using fSequenceNo
+                $query0 .= " CONCAT('<A&ws;HREF=\"runinfo-aio.php?',  'fRunStart=On', '&amp;fZenithDistance=On', '&amp;fSequenceNo=', Sequences.fSequenceFirst, '&amp;fMeanTriggerRate=On', '&amp;fTest=On', '&amp;fRunTypeName=On', '&amp;fNumEvents=On', '&amp;fSourceName=On&amp;', 'fExcludedFDAKEY=1', '&amp;fSequenceFirst=On', '&amp;fRawFileAvail=On', '&amp;fCCFileAvail=On', '&amp;fCaCoFileAvail=On', '&amp;fNumResults=500\">', 'M', Sequences.fTelescopeNumber, ':', LPAD(Sequences.fSequenceFirst, 8, ' '), '</A>') ";
+                //$query0 .= " as " . $alias["fSequenceFirst"];
+                $query0 .= " as 'Tel:Sequ'";
+                if (!empty($_GET["fLinks"]))
+                {
+                    $query0 .= ", CONCAT('<A&ws;HREF=\"tabs.php?t=calib&n=', fSequenceFirst, '\">cal</A>'";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"tabs.php?t=signal&n=', fSequenceFirst, '\">sig</A>'";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"tabs.php?t=star&n=', fSequenceFirst, '\">star</A>'";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sequences/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/sequence', LPAD(CONCAT(Sequences.fSequenceFirst , '.txt'), 12,'0') , '\">', 'f </A>' ";
+                    //$query0 .= ", '&nbsp;<A&ws;HREF=\"sequence.php?fSequenceNo=', Sequences.fSequenceFirst , '&amp;fAll=On\">i</A>'";
+                    $query0 .= ", '&nbsp;<A&ws;HREF=\"queryrbk.php?fNight=', date_format(adddate(fRunStart, interval +13 HOUR), '%Y-%m-%d') , '&amp;fDate=2\">rbk</A>') ";
+                    //$query0 .= ", CONCAT('<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), 'callisto', LPAD(CONCAT(Sequences.fSequenceFirst , '.html'), 13,'0') , '\">cl</A>'";
+                    //$query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), '\">c</A>'";
+                    //$query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/star/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), 'star', LPAD(CONCAT(Sequences.fSequenceFirst , '.html'), 13,'0') , '\">sl</A>'";
+                    //$query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/star/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), '\">s</A>'";
+                    //$query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/sequences/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/sequence', LPAD(CONCAT(Sequences.fSequenceFirst , '.txt'), 12,'0') , '\">', 'f </A>' ";
+                    //$query0 .= ", '&nbsp;<A&ws;HREF=\"sequence.php?fSequenceNo=', Sequences.fSequenceFirst , '&amp;fAll=On\">i</A>'";
+                    //$query0 .= ", '&nbsp;<A&ws;HREF=\"queryrbk.php?fNight=', date_format(adddate(fRunStart, interval +13 HOUR), '%Y-%m-%d') , '&amp;fDate=2\">rbk</A>') ";
+                    $query0 .= " as 'Links'";
+                }
+            }
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On")
+                    if ($key!="fLinks" && $key!="fOff" && $key!="fOnlyOff" && $key!="fOnlySum")
+                        if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                            $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM " . $fromtable;
+
+        $query0 .= " LEFT JOIN SequenceProcessStatus USING(fSequenceFirst,fTelescopeNumber) ";
+        $query0 .= " LEFT JOIN Calibration USING(fSequenceFirst,fTelescopeNumber) ";
+        $query0 .= " LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) ";
+
+        foreach ($_GET as $key => $element)
+            if (($_GET[$key]=="On" || $groups>0))// && !empty(GetJoin($fromtable,$key)))
+                $query0 .= GetJoin($fromtable,$key);
+
+        if ($_GET["fTest"]!="On")
+        {
+            if ($_GET["fSourceName"]!="On")
+                $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
+            $query0 .= " WHERE fTest='no'";
+        }
+
+        if ($_GET["fOff"]=="Off")
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+
+            $query0 .= " NOT (fSourceName like '%Off%')";
+        }
+
+        if ($_GET["fOnlyOff"]=="On")
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+
+            $query0 .= " fSourceName like '%Off%'";
+        }
+
+        if ($_GET["fOnlySum"]=="On")
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+
+            $query0 .= " NOT ISNULL(fRateSumEvts) ";
+        }
+
+        foreach ($checkwhere as $key => $element)
+        {
+            if (empty($element) || $element<=0)
+                continue;
+
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                if ($element!=-1)
+                    if (strrpos($query0, " AND ")!=strlen($query0)-5)
+                        $query0 .= " AND ";
+
+            if ($element!=-1)
+                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
+        }
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= StatusQuery("fSequenceFileWritten", $needs, $timelimits);
+        $query0 .= StatusQuery("fAllFilesAvail", $needs, $timelimits);
+        $query0 .= StatusQuery("fCallisto", $needs, $timelimits);
+        $query0 .= StatusQuery("fFillCallisto", $needs, $timelimits);
+        $query0 .= StatusQuery("fStar", $needs, $timelimits);
+        $query0 .= StatusQuery("fFillStar", $needs, $timelimits);
+
+        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
+            $query0 .= "Sequences.fSequenceFirst BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+        else
+            $query0 = substr($query0, 0, -4);
+
+        if ((!empty($_GET["fZDMin"]) || $_GET["fZDMin"]==0) && !empty($_GET["fZDMax"]))
+            $query0 .= "AND (fZenithDistanceMin >= " . $_GET["fZDMin"] . " AND fZenithDistanceMax <= " . $_GET["fZDMax"] . ") ";
+
+        if (!empty($_GET["fSourceN"]))
+            $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+
+        if (!empty($_GET["fStartDate"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                $query0 .= " AND ";
+
+            $startdate=substr($_GET["fStartDate"], 0, 10);
+            if ($startdate=="0000-00-00")
+                $query0 .=" fRunStart >= '" . $startdate . " 00:00:00' ";
+            else
+                $query0 .= " fRunStart >= ADDDATE('" . $startdate . " 13:00:00', INTERVAL -1 DAY) ";
+        }
+
+        if (!empty($_GET["fStopDate"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                $query0 .= " AND ";
+
+            $stopdate=substr($_GET["fStopDate"], 0, 10);
+            $query0 .= " fRunStart < '" . $stopdate . " 13:00:00' ";
+        }
+
+        if (!empty($_GET["fStarStart"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                $query0 .= " AND ";
+
+            $starstart=substr($_GET["fStarStart"], 0, 10);
+            $query0 .=" fStar >= '" . $starstart . " 00:00:00' ";
+        }
+
+        if (!empty($_GET["fStarStop"]))
+        {
+            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                $query0 .= " AND ";
+
+            $starstop=substr($_GET["fStarStop"], 0, 10);
+            $query0 .= " fStar < '" . $starstop . " 23:59:59' ";
+        }
+
+        if ($groups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $groups;
+            foreach ($checkgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= GetCheck($fromtable,$key);
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0)
+            if (strpos($query0, " GROUP BY ")==FALSE)
+                $query0 .= " GROUP BY GroupByDate ";
+            else
+                $query0 .= ", GroupByDate ";
+
+        if ($statusgroups>0)
+        {
+//            $query0 .= " GROUP BY ";
+            if (strpos($query0, " GROUP BY ")==FALSE)
+                $query0 .= " GROUP BY ";
+            else
+                $query0 .= ", ";
+            $num = $statusgroups;
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $val=substr($_GET["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable,$val) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fSortBy"]) && $groups==0 && $statusgroups==0)
+            $query0 .= "ORDER BY Sequences.fSequenceFirst ASC ";
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet()
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="50";
+
+        if (empty($_GET["fRunStart"]))
+            $_GET["fRunStart"]=$first?"On":"";
+
+        if (empty($_GET["fRunTime/60"]))
+            $_GET["fRunTime/60"]=$first?"On":"";
+
+        if (empty($_GET["fZenithDistanceMin"]))
+            $_GET["fZenithDistanceMin"]=$first?"On":"";
+
+        if (empty($_GET["fSourceName"]))
+            $_GET["fSourceName"]=$first?"On":"";
+
+        if (empty($_GET["fStar"]))
+            $_GET["fStar"]=$first?"On":"";
+
+        if (empty($_GET["fInhomogeneity"]))
+            $_GET["fInhomogeneity"]=$first?"On":"";
+
+        if (empty($_GET["fPSF"]))
+            $_GET["fPSF"]=$first?"On":"";
+
+        if (empty($_GET["fMeanPedRmsInner"]))
+            $_GET["fMeanPedRmsInner"]=$first?"On":"";
+
+        if (empty($_GET["fOff"]))
+            $_GET["fOff"]=$first?"On":"";
+
+        if (empty($_GET["fLinks"]))
+            $_GET["fLinks"]=$first?"On":"";
+
+        if (empty($_GET["fOnlyOff"]))
+            $_GET["fOnlyOff"]=$first?"Off":"";
+
+        if (empty($_GET["fOnlySum"]))
+            $_GET["fOnlySum"]=$first?"Off":"";
+
+        InitFindOffData($first);
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias)
+    {
+        printf("<center>\n");
+        printf("<form action='sequinfo-aio.php' METHOD='GET'>\n");
+        printf("<input id='sh' type='hidden' name='fShowHide' value='");
+        if (!empty($_GET["fShowHide"]))
+            printf("%s", $_GET["fShowHide"]);
+        else
+            printf("1000000010");
+        printf("'>\n");
+        printf("<img id='allbutton' src='minus.png' alt='-' onclick='showhide(\"all\")'> <b>Menu</b>&nbsp;&nbsp;&nbsp;&nbsp; \n");
+        printf("&nbsp;&nbsp;<img id='infobutton'   src='plus.png'  alt='+' onClick='showhide(\"info\");showhide(\"info2\")'> SequInfo   \n");
+        printf("&nbsp;&nbsp;<img id='statbutton'   src='plus.png'  alt='+' onClick='showhide(\"stat\");showhide(\"fail\")'>  StatusInfo \n");
+        printf("&nbsp;&nbsp;<img id='calbutton'    src='plus.png'  alt='+' onClick='showhide(\"cal\")'>                      CalInfo    \n");
+        printf("&nbsp;&nbsp;<img id='starbutton'   src='plus.png'  alt='+' onClick='showhide(\"star\")'>                     StarInfo   \n");
+        printf("&nbsp;&nbsp;<img id='limitsbutton' src='plus.png'  alt='+' onClick='showhide(\"limits\")'>                   Limits     \n");
+        printf("&nbsp;&nbsp;<img id='rangesbutton' src='minus.png' alt='-' onClick='showhide(\"ranges\")'>                   Ranges     \n");
+
+        printf(" <div id='all' style='display:block'>");
+
+        PrintSequInfoMenu();
+        PrintSequInfo2Menu($host,$user,$pw,$db);
+        PrintSequStatMenu();
+        PrintFailMenu();
+        PrintCalMenu();
+        PrintStarMenu();
+        PrintLimitsMenu($limitsmean, $limitsmin, $limitsmax, $alias, "");
+
+        printf(" <div id='ranges' style='display:block'>");
+        PrintZdRangeMenu($host,$user,$pw,$db);
+        PrintSequRangeMenu($host,$user,$pw,$db);
+        printf("<p>");
+        PrintSourceMenu($host,$user,$pw,$db);
+        PrintGroupByDateMenu();
+        printf("<p>");
+        PrintNightRangeMenu($host,$user,$pw,$db, "Sequences");
+        printf("<p>");
+        printf("</div>");
+
+        printf("</div>");
+        printf(" <P>\n");
+
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        PrintNumResPullDown();
+        PrintButtons("sequinfo-aio.php");
+
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs)
+    {
+        $db_id = mysql_pconnect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1" || $html=="2")
+                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $result1, "");
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "");
+    }
+
+    include ("include.php");
+    include ("menu.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+    }
+    else
+    {
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet();
+        if (empty($_GET["fPrintTable"]))
+            PrintForm($_GET, $host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+        {
+            if (empty($_GET["fPrintTable"]))
+                PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+            else
+                PrintPage("2", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+        }
+
+        if (empty($_GET["fPrintTable"]))
+            echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/showplots-ds.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/showplots-ds.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/showplots-ds.php	(revision 17960)
@@ -0,0 +1,153 @@
+<?php
+
+ini_set("display_errors", "On");
+
+include("plotinclude.php");
+//print header
+printf("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
+printf("<html>\n<head>\n");
+printf("<meta http-equiv='content-type' content='text/html; charset=ISO-8859-1'>\n");
+printf("<title>show plots</title>\n");
+printf("<link rel='stylesheet' type='text/css' href='lamouette.css'>\n");
+printf("</head>\n");
+printf("<body>\n");
+
+//init
+$ds=0;
+if (!empty($_GET["ds"]))
+    $ds=$_GET["ds"];
+$tabnum=1;
+if (!empty($_GET["tabnum"]))
+    $tabnum=$_GET["tabnum"];
+$type2="calib";
+if (!empty($_GET["type2"]))
+    $type2=$_GET["type2"];
+$plot="";
+$nextseq=0;
+$prevseq=0;
+$seq=0;
+if (!empty($_GET["prevseq"]) && !empty($_GET["prev"]))
+    $seq=$_GET["prevseq"];
+if (!empty($_GET["nextseq"]) && !empty($_GET["next"]))
+    $seq=$_GET["nextseq"];
+$next=0;
+$prev=0;
+$numseq=0;
+
+//check if dataset file is existing
+if (!empty($ds))
+{
+    $num=sprintf("%08d",$ds);
+    $num2=substr($num,0,5);
+    $datasetfile="./datasets/" . $num2 . "/dataset" . $num . ".txt";
+    if (!file_exists($datasetfile))
+    {
+        printf("Sorry, there's no file for dataset %s available.", $ds);
+        //set dataset and sequence numbers to 0 for next checks
+        $ds=0;
+        $seq=0;
+    }
+}
+
+//in case of a valid dataset
+if (!empty($ds))
+{
+    //get sequences from dataset file
+    // alternative: query it from db
+    $dataset=file_get_contents($datasetfile);
+    $onpos=strpos($dataset, "SequencesOn:");
+    $offpos=strpos($dataset, "SequencesOff:");
+    $possource=strpos($dataset, "SourceName:");
+    $sequoff="";
+    if (!empty($offpos))
+        $sequoff=split(" ", trim(substr($dataset, $offpos+13, $possource-($offpos+13))));
+    if (empty($offpos))
+        $offpos=$possource;
+    $sequon=split(" ", trim(substr($dataset, $onpos+12, $offpos-($onpos+12))));
+    $sequences=$sequon;
+    if (!empty($sequoff))
+        $sequences=array_merge($sequences,$sequoff);
+    if ($seq!=0 && !in_array($seq, $sequences))
+        $seq=0;
+
+    //get next, current and previous sequence
+    foreach($sequences as $key => $sequ)
+    {
+        if ($seq==0)
+            $seq=$sequ;
+        if ($next==1)
+        {
+            $nextseq=$sequ;
+            if ($prevseq!=0)
+                break;
+            $next=0;
+        }
+        if ($sequ==$seq)
+        {
+            $next=1;
+            continue;
+        }
+        $prevseq=$sequ;
+    }
+    $numseq=count($sequences);
+
+    //in case a dataset consists of less than 3 sequences
+    if ($numseq==2)
+        $nextseq=$prevseq;
+}
+
+//get link for plot
+$type=gettypename($type2);
+$plot=getplotname($seq, $tabnum, $type, $type2);
+
+//print form for choosing dataset and plots
+printf("<form action='showplots-ds.php' method='GET'>\n");
+printf("<table width='100%%' border='0'>\n");
+printf("<tr><td valign='top'>\n<tr>\n");
+PrintHomeHelp();
+printf("<td align='center'>\n");
+if (!empty($prevseq))
+    printf("%d &nbsp;", $prevseq);
+if ($numseq>1)
+    printf("<input type='submit' value='<< Prev Plot' name='prev'>\n");
+printf("<input type='text' name='ds' size='5' maxlength='5' value='%s'>\n", $ds);
+PrintType2PullDown($type2);
+printf("<input type='text' name='tabnum' size='2' maxlenght='2' value='%s'>\n", $tabnum);
+printf("<input type='hidden' name='prevseq' size='2' maxlenght='2' value='%s'>\n", $prevseq);
+printf("<input type='hidden' name='nextseq' size='2' maxlenght='2' value='%s'>\n", $nextseq);
+if ($numseq>1)
+    printf("<input type='submit' value='Next Plot >>' name='next'>\n");
+else
+    printf("<input type='submit' value='Plot' name='next'>\n");
+if (!empty($nextseq))
+    printf("&nbsp;%d ", $nextseq);
+if ($numseq>0)
+{
+    printf("&nbsp; [ %d sequence", $numseq);
+    if ($numseq>1)
+        printf("s");
+    print(" ] \n");
+}
+printf("</td><td align='right'>\n");
+printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"showplots-ds.php\"'>\n");
+printf("</td>\n</tr>\n<tr>\n<td align='center' colspan='3'>\n");
+if (!empty($seq))
+{
+    if (in_array($seq, $sequon))
+        $color="green";
+    else
+        $color="red";
+
+    printf("<div style='color:%s' onmouseover=\"this.innerHTML='%s';style.color='black'\" onmouseout=\"this.innerHTML='%s';style.color='%s'\"> %s </div>\n", $color, getinfofromdb($seq), $plot, $color, $plot);
+    printf("<img src='%s'>\n", $plot);
+}
+else
+    printf("You have to insert a dataset number into the first field.");
+printf("</td>\n</tr>\n</table>\n");
+printf("</form>\n");
+printf("</body>\n");
+printf("</html>\n");
+
+ini_set("display_errors", "Off");
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/showplots-seq.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/showplots-seq.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/showplots-seq.php	(revision 17960)
@@ -0,0 +1,188 @@
+<?php
+
+ini_set("display_errors", "On");
+
+include("plotinclude.php");
+include("db.php");
+
+printf("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
+printf("<html>\n<head>\n");
+printf("<meta http-equiv='content-type' content='text/html; charset=ISO-8859-1'>\n");
+printf("<title>show plots</title>\n");
+printf("<link rel='stylesheet' type='text/css' href='lamouette.css'>\n");
+printf("</head>\n");
+printf("<body>\n");
+
+//init
+$source="";
+if (!empty($_GET["source"]))
+    $source=$_GET["source"];
+$from="";
+if (!empty($_GET["from"]))
+    $from=$_GET["from"];
+$to="";
+if (!empty($_GET["to"]))
+    $to=$_GET["to"];
+$tabnum=1;
+if (!empty($_GET["tabnum"]))
+    $tabnum=$_GET["tabnum"];
+$type2="calib";
+if (!empty($_GET["type2"]))
+    $type2=$_GET["type2"];
+$plot="";
+$nextseq=0;
+$prevseq=0;
+$seq=0;
+if (!empty($_GET["prevseq"]) && !empty($_GET["prev"]))
+    $seq=$_GET["prevseq"];
+if (!empty($_GET["nextseq"]) && !empty($_GET["next"]))
+    $seq=$_GET["nextseq"];
+$next=0;
+$prev=0;
+$numseq=0;
+//$sequences=array(0,10,20);
+//$sequences=array();
+
+
+if (!empty($from) || !empty($to))
+{
+    //get sequences from db
+    $query="SELECT fSequenceFirst FROM Sequences ";
+    if (!empty($from) && !empty($to))
+        $query.="WHERE fSequenceFirst BETWEEN " . $from . " AND " . $to;
+    else
+    {
+        if (!empty($from))
+            $query.="WHERE fSequenceFirst > " . $from;
+        if (!empty($to))
+            $query.="WHERE fSequenceFirst < " . $to;
+    }
+    // WHERE has to be there as $from is given by default
+    if (!empty($source))
+        $query.=" AND fSourceKEY=" . $source;
+
+    //connection to database
+    $db_id = mysql_pconnect($host, $user, $pw);
+    if ($db_id==FALSE)
+    {
+        printf("mysql_connect returned the following error: %s\n", mysql_error());
+        die("");
+    }
+    mysql_select_db($db);
+
+    $result=mysql_query($query, $db_id);
+    while ($row = mysql_fetch_row($result))
+        $sequences[] = $row[0];
+    mysql_free_result($result);
+
+    mysql_close($db_id);
+
+    if (isset($sequences))
+    {
+        //get next, current and previous sequence
+        foreach($sequences as $key => $sequ)
+        {
+            if ($seq==0)
+                $seq=$sequ;
+            if ($next==1)
+            {
+                $nextseq=$sequ;
+                if ($prevseq!=0)
+                    break;
+                $next=0;
+            }
+            if ($sequ==$seq)
+            {
+                $next=1;
+                continue;
+            }
+            $prevseq=$sequ;
+        }
+        $numseq=count($sequences);
+        //in case a dataset consists of less than 3 sequences
+        if ($numseq==2)
+            $nextseq=$prevseq;
+    }
+}
+
+
+$type=gettypename($type2);
+$plot=getplotname($seq, $tabnum, $type, $type2);
+
+printf("<form action='showplots-seq.php' method='GET'>\n");
+printf("<table width='100%%' border='0'>\n<tr>\n");
+PrintHomeHelp();
+printf("<td align='center'>\n");
+if (!empty($prevseq))
+    printf("%d &nbsp;", $prevseq);
+if ($numseq>1)
+    printf("<input type='submit' value='<< Prev Plot' name='prev'>\n");
+if (empty($from))
+    $from=34099;//21.8.2004
+
+$db_id = mysql_connect($host, $user, $pw);
+if ($db_id==FALSE)
+{
+    printf("mysql_connect returned the following error:<br>");
+    printf("%s<br>", mysql_error());
+    die("");
+}
+    mysql_select_db($db);
+
+$query="SELECT fSourceKEY, fSourceName FROM Source ORDER BY fSourceName";
+$result=mysql_query($query);
+if (!$result)
+    printf("-N/A-");
+printf("&nbsp;<select name='source' size='1' class='Width'>\n");
+if (empty($source) || $source==0)
+    printf("<option value='0' selected>--- ALL ---</option>\n");
+else
+    printf("<option value='0'>--- ALL ---</option>\n");
+while ($row = mysql_fetch_row($result))
+{
+    if (!empty($source) && $source==$row[0])
+        printf("<option value='%s' selected>%s</option>\n", $row[0], $row[1]);
+    else
+        printf("<option value='%s'>%s</option>\n", $row[0], $row[1]);
+}
+printf("</select>\n");
+mysql_free_result($result);
+mysql_close($db_id);
+
+printf("from <input type='text' name='from' size='6' maxlength='8' value='%s'>\n", $from);
+printf(" to <input type='text' name='to' size='6' maxlength='8' value='%s'>\n", $to);
+PrintType2PullDown($type2);
+printf("<input type='text' name='tabnum' size='2' maxlenght='2' value='%s'>\n", $tabnum);
+printf("<input type='hidden' name='prevseq' size='2' maxlenght='2' value='%s'>\n", $prevseq);
+printf("<input type='hidden' name='nextseq' size='2' maxlenght='2' value='%s'>\n", $nextseq);
+if ($numseq>1)
+    printf("<input type='submit' value='Next Plot >>' name='next'>\n");
+else
+    printf("<input type='submit' value='Plot' name='next'>\n");
+if (!empty($nextseq))
+    printf("&nbsp;%d ", $nextseq);
+if ($numseq>0)
+{
+    printf("&nbsp; [ %d sequence", $numseq);
+    if ($numseq>1)
+        printf("s");
+    print(" ] \n");
+}
+printf("</td><td align='right'>\n");
+printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"showplots-seq.php\"'>\n");
+printf("</td>\n</tr>\n<tr>\n<td align='center' colspan='3'>\n");
+if (!empty($seq))
+{
+    printf("<div onmouseover=\"this.innerHTML='%s'\" onmouseout=\"this.innerHTML='%s'\"> %s </div>", getinfofromdb($seq), $plot, $plot);
+    printf("<img src='%s'>", $plot);
+}
+else
+    printf("Choose a source and/or a range of sequences or just click 'Plot' for going through all sequences.");
+printf("</td>\n</tr>\n</table>\n");
+printf("</form>\n");
+printf("</body>\n");
+printf("</html>\n");
+
+ini_set("display_errors", "Off");
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/showplots.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/showplots.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/showplots.php	(revision 17960)
@@ -0,0 +1,116 @@
+<?php
+
+include("plotinclude.php");
+
+printf("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
+printf("<html>\n<head>\n");
+printf("<meta http-equiv='content-type' content='text/html; charset=ISO-8859-1'>\n");
+printf("<title>show plots</title>\n");
+printf("<link rel='stylesheet' type='text/css' href='lamouette.css'>\n");
+printf("</head>\n");
+printf("<body>\n");
+
+//init
+$seq=0;
+if (!empty($_GET["seq"]))
+    $seq=str_replace(" ", "", $_GET["seq"]);
+$tabnum=1;
+if (!empty($_GET["tabnum"]))
+    $tabnum=$_GET["tabnum"];
+$type2="calib";
+if (!empty($_GET["type2"]))
+    $type2=$_GET["type2"];
+$next=0;
+$prev=0;
+
+if (!empty($seq))
+{
+    //decision whether next or previous plot has been chosen
+    if (!empty($_GET["next"]))
+        $tabnum=$tabnum+1;
+    if (!empty($_GET["prev"]))
+        $tabnum=$tabnum-1;
+
+    //be careful: this has to be adapted in case tabs are removed or new tabs are added
+    //number of tabs for calib*.root, signal*.root and star*.root
+    if ($seq > 200000)
+        $signaltabs=12;
+    else
+        $signaltabs=14;
+    $calibtabs=11;
+    $startabs=20;
+
+    //in case the tab does not exist, because it's one the far
+    //go to next type
+    if (($type2=="calib" && $tabnum==($calibtabs+1))
+        || ($type2=="signal" && $tabnum==($signaltabs+1))
+        || ($type2=="star" && $tabnum==($startabs+1)))
+    {
+        $tabnum=1;
+        switch ($type2)
+        {
+        case "calib":
+            $type2="signal";
+            break;
+        case "signal":
+            $type2="star";
+            break;
+        case "star":
+            $type2="calib";
+            break;
+        }
+    }
+    //in case the tab does not exist, because it's 0
+    //go to previous type
+    if ($tabnum==0)
+    {
+        switch($type2)
+        {
+        case "calib":
+            $type2="star";
+            $tabnum=$startabs;
+            break;
+        case "signal":
+            $type2="calib";
+            $tabnum=$calibtabs;
+            break;
+        case "star":
+            $type2="signal";
+            $tabnum=$signaltabs;
+            break;
+        }
+    }
+    //get link for plot
+    $type=gettypename($type2);
+    $plot=getplotname($seq, $tabnum, $type, $type2);
+
+    $next=$tabnum+1;
+    $prev=$tabnum-1;
+}
+printf("<form action='showplots.php' method='GET'>\n");
+printf("<table width='100%%' border='0'>\n<tr>\n");
+PrintHomeHelp();
+printf("<td align='center'>\n");
+if (!empty($seq))
+    printf("<input type='submit' value='<< %d Prev Plot' name='prev'>\n", $prev);
+printf("<input type='text' name='seq' size='10' maxlength='10' value='%s'>\n", $seq);
+PrintType2PullDown($type2);
+printf("<input type='text' name='tabnum' size='2' maxlenght='2' value='%s'>\n", $tabnum);
+printf("<input type='submit' value='Show Plot'>\n");
+if (!empty($seq))
+    printf("<input type='submit' value='Next Plot %d >>' name='next'>\n", $next);
+
+printf("</td>\n</tr>\n<tr>\n<td align='center' colspan='2'>\n");
+if (!empty($seq))
+{
+    printf("<div onmouseover=\"this.innerHTML='%s'\" onmouseout=\"this.innerHTML='%s'\"> %s </div>", getinfofromdb($seq), $plot, $plot);
+    printf("<img src='%s'>", $plot);
+}
+else
+    printf("You have to insert a sequence number into the first field.");
+printf("</td>\n</tr>\n</table>\n");
+printf("</form>\n");
+printf("</body>\n");
+printf("</html>\n");
+
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/sources.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/sources.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/sources.php	(revision 17960)
@@ -0,0 +1,167 @@
+<?php
+{
+    function CreateQuery($_GET, $alias)
+    {
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+        if ($_GET["fLinks"]=="Off" || !empty($_GET["fSendTxt"]))
+            $query0 .= " fSourceName as 'Source' ";
+        else
+        {
+            $query0 .= " CONCAT('<A&ws;HREF=\"sequinfo-aio.php?', ";
+            $query0 .= " 'fRunStart=On', '&fZenithDistanceMin=On', '&fNumEvents=On', '&fRunTime%2F60=On', '&fSequenceLast=On', ";
+            $query0 .= " '&fSequenceFileWrittenStatus=0', '&fAllFilesAvailStatus=0', '&fCallistoStatus=0', '&fStar=On', '&fStarStatus=0', '&fFillCallistoStatus=0', '&fFillStarStatus=0', ";
+            $query0 .= " '&fSourceName=On', '&fSourceKEY=', fSourceKEY, "; //'&fRunMin=0', '&fRunMax=1000000', ";
+            $query0 .= " '&fNumResults=500\">', fSourcename, '</A>') ";
+            $query0 .= " as 'Source' ";
+        }
+        $query0 .= " , fSourceKEY as 'KEY', fTest as 'Test' ";
+        $query0 .= " FROM Source ";
+
+        if ($_GET["fTest"]=="Off")
+            $query0 .= " WHERE fTest='no'";
+
+        if ($_GET["fOff"]=="Off")
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+
+            $query0 .= " NOT (fSourceName like '%Off%')";
+        }
+
+        if (!empty($_GET["fSourceN"]))
+        {
+            if (strpos($query0, " WHERE ")==FALSE)
+                $query0 .= " WHERE ";
+            else
+                $query0 .= " AND ";
+
+            $query0 .= " fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
+        }
+
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $query0 .= " ORDER BY " . substr($_GET["fSortBy"], 0, -1) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+        else
+            $query0 .= " ORDER BY fSourceKEY ";
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+
+        if (empty($_GET["fOff"]))
+            $_GET["fOff"]="Off";
+
+        if (empty($_GET["fTest"]))
+            $_GET["fTest"]="Off";
+
+        if (empty($_GET["fLinks"]))
+            $_GET["fLinks"]="On";
+
+    }
+
+    function PrintForm($_GET,$host,$user,$pw,$db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"sources.php\" METHOD=\"GET\">\n");
+        printf(" <p><table>\n");
+        printf("  <tr>\n");
+
+        CheckBox("fOff",   "incl. offsources");
+        CheckBox("fTest",  "incl. test-sources");
+        CheckBox("fLinks", "links");
+
+        printf(" </table></p>\n");
+        printf("<p>");
+        PrintSourceMenu($host,$user,$pw,$db);
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"sources.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET, $alias);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("menu.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        PrintForm($_GET,$host,$user,$pw,$db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+            PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign);
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/statussbs.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/statussbs.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/statussbs.php	(revision 17960)
@@ -0,0 +1,233 @@
+<?php
+{
+    function CreateQuery($_GET, $alias, $checkstatusgroup, $checkwhere, $needs)
+    {
+        $statusgroups = 0;
+        foreach ($checkstatusgroup as $element)
+            if ($element==-1)
+                $statusgroups++;
+
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
+
+        if ($statusgroups>0)
+        {
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                    $query0 .= " (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval 12 hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+//                    $query0 .= " (if(IsNull(" . $key . "), 'not done' ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
+
+            $query0 .= " count(*) as '# days'";
+
+        }
+        else
+        {
+            if (!empty($_GET["fSendTxt"]))
+                $query0 .= " fDate ";
+            else
+            {
+                $query0 .= " CONCAT( fDate , ':  <A&ws;HREF=\"index.php?', 'fRunStart=On', '&fZenithDistance=On', '&fMeanTriggerRate=On', '&fRunTypeName=On', '&fNumEvents=On', '&fSourceName=On&', 'fExcludedFDAKEY=1', '&fSequenceFirst=On', '&fStartDate=', fDate, '&fStopDate=', fDate, '&fNumResults=500\">Runs</A> ' , ";
+                $query0 .= " ' <A&ws;HREF=\"queryseq.php?', 'fRunStart=On', '&fZenithDistanceMin=On', '&fNumEvents=On', '&fSourceName=On&', '&fStartDate=', fDate, '&fStopDate=', fDate, '&fNumResults=500\">Sequ</A> ') ";
+            }
+            $query0 .= " as 'Date' ";
+
+            foreach ($_GET as $key => $element)
+                if ($_GET[$key]=="On")
+                    if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                        $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+        }
+
+        $query0 .= " FROM SequenceBuildStatus ";
+
+        if (strpos($query0, " WHERE ")==FALSE)
+            $query0 .= " WHERE ";
+        else
+            $query0 .= " AND ";
+
+        $query0 .= StatusQuery("fCCFilled", $needs, $timelimits);
+        $query0 .= StatusQuery("fExclusionsDone", $needs, $timelimits);
+        $query0 .= StatusQuery("fSequenceEntriesBuilt", $needs, $timelimits);
+
+        $query0 .= "fDate BETWEEN '" . $_GET["fRunMin"] . "' AND '" . $_GET["fRunMax"] . "' ";
+
+        if ($statusgroups>0)
+        {
+            $query0 .= " GROUP BY ";
+            $num = $statusgroups;
+            foreach ($checkstatusgroup as $key => $element)
+                if ($element==-1)
+                {
+                    $query0 .= $alias[$key];
+                    if ($num-->1)
+                        $query0 .= ", ";
+                }
+        }
+
+        if (!empty($_GET["fSortBy"]))
+        {
+            $query0 .= " ORDER BY " . substr($_GET["fSortBy"], 0, -1) . " ";
+            if (substr($_GET["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_GET["fSortBy"]) && $statusgroups==0)
+            $query0 .= "ORDER BY SequenceBuildStatus.fDate ASC ";
+
+        if (empty($_GET["fNumStart"]))
+            $_GET["fNumStart"]=0;
+
+        if (empty($_GET["fSendTxt"]))
+            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+
+        return $query0;
+    }
+
+    function InitGet($_GET)
+    {
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+
+        if (empty($_GET["fNumResults"]))
+            $_GET["fNumResults"]="20";
+
+        if (empty($_GET["fCCFilled"]))
+            $_GET["fCCFilled"]=$first?"On":"";
+
+        if (empty($_GET["fExclusionsDone"]))
+            $_GET["fExclusionsDone"]=$first?"On":"";
+
+        if (empty($_GET["fSequenceEntriesBuilt"]))
+            $_GET["fSequenceEntriesBuilt"]=$first?"On":"";
+    }
+
+    function PrintForm($_GET, $host, $user, $pw, $db)
+    {
+        printf("<center>\n");
+        printf("<form action=\"statussbs.php\" METHOD=\"GET\">\n");
+        printf(" <table>\n");
+        printf("  <tr><td>\n");
+
+        PrintStatusMenu("fCCFilled", "CC Filled");
+
+        printf("  </td><td>\n");
+
+        PrintStatusMenu("fExclusionsDone", "Exclusions");
+
+        printf("  </td><td>\n");
+
+        PrintStatusMenu("fSequenceEntriesBuilt", "Sequences");
+
+        printf(" </td></tr></table>\n");
+        printf(" <p>\n");
+
+
+        if (empty($_GET["fRunMin"]))
+            $min = GetMin("fDate", "SequenceBuildStatus", $host, $user, $pw, $db);
+        else
+            $min = $_GET["fRunMin"];
+
+        if (empty($_GET["fRunMax"]))
+            $max = GetMax("fDate", "SequenceBuildStatus", $host, $user, $pw, $db);
+        else
+            $max = $_GET["fRunMax"];
+
+
+        printf("Date&nbsp;from&nbsp;<input name=\"fRunMin\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">\n", $min);
+        printf("to&nbsp;<input name=\"fRunMax\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">&nbsp;&nbsp;&nbsp;\n", $max);
+
+        printf(" <P>\n");
+
+        printf(" Results:\n");
+        printf(" <select name=\"fNumResults\">\n");
+
+        $numres = array("10", "20", "50", "100", "200", "500");
+        foreach ($numres as $element)
+        {
+            if ($element==$_GET["fNumResults"])
+                printf("<option value=\"%s\" selected>%3s</option>\n", $element, $element);
+            else
+                printf("<option value=\"%s\">%3s</option>\n", $element, $element);
+        }
+        printf(" </select>\n");
+        printf(" &nbsp;&nbsp;&nbsp;\n");
+
+        ini_set("mysql.trace_mode", "Off");
+        ini_set("display_errors", "Off");
+
+        printf("<input class='Width' type='submit' value='Query Table'>&nbsp;&nbsp;&nbsp;\n");
+        printf("<input class='Width' type='button' value='Reset' onClick='self.location.href=\"statussbs.php\"'>&nbsp;&nbsp;&nbsp;\n");
+        if (strchr($_SERVER["REQUEST_URI"], '?')!=FALSE)
+            printf("<input class='Width' type='button' value='Get .txt' onClick='self.location.href=\"%s&fSendTxt=1\"'>&nbsp;&nbsp;&nbsp;\n", $_SERVER["REQUEST_URI"]);
+        printf("</form>\n");
+        printf("</center>\n");
+        printf("</td>\n");
+        printf("</tr>\n");
+        printf("<tr class='Block'>\n");
+        printf("<td>\n");
+    }
+
+    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkstatusgroup, $checkwhere, $needs)
+    {
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error: %s\n", mysql_error());
+            die("");
+        }
+        mysql_select_db($db);
+
+        $query0 = CreateQuery($_GET, $alias, $checkstatusgroup, $checkwhere, $needs);
+
+        $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
+
+        if ($result0)
+        {
+            if ($html=="1")
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
+            else
+                PrintText($result0);
+
+            mysql_free_result($result0);
+            mysql_free_result($result1);
+        }
+        mysql_close($db_id);
+
+        if ($html=="1")
+            PrintSubmittedQuery($query0, $db, "old");
+    }
+
+    include ("include.php");
+    include ("db.php");
+    include ("magicdefs.php");
+
+    ini_set("display_errors", "On");
+    ini_set("mysql.trace_mode", "On");
+
+    if (!empty($_GET["fSendTxt"]))
+    {
+        header("Content-type: application/octet");
+        header("Content-Disposition: attachment; filename=query-result.txt");
+
+        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkstatusgroup, $checkwhere, $needs);
+    }
+    else
+    {
+        echo (file_get_contents("index-header.html"));
+
+        $environment = sizeof($_GET);
+
+        InitGet($_GET);
+        PrintForm($_GET, $host, $user, $pw, $db);
+
+        if ($environment==0)
+            printf("No query submitted yet.<BR>");
+        else
+            PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkstatusgroup, $checkwhere, $needs);
+
+        echo (file_get_contents("index-footer.html"));
+    }
+
+    ini_set("display_errors", "Off");
+    ini_set("mysql.trace_mode", "Off");
+}
+?>
Index: branches/Mars_McMismatchStudy/datacenter/db/tabs.css
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/tabs.css	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/tabs.css	(revision 17960)
@@ -0,0 +1,244 @@
+/* ************************************************** 
+ * Tab support based on http://www.alistapart.com/articles/slidingdoors/
+ * ************************************************** */
+
+body {
+  /* font: x-small sans-serif; */
+  background: #f9f9f9 url(/ewiki/skins/monobook/headbg.jpg) 0 0 no-repeat;
+  color: black;
+/*  margin: 0;
+  padding 0;*/
+}
+
+
+.tabs,.tabs-blue {
+  float:left;
+/*  width:5000;*/  /* STUPID HACK */
+/*  background:#DAE0D2 url("Tab-bg.gif") repeat-x bottom;*/
+  font-size:93%;
+  line-height:normal;
+  margin: 0;
+  padding: 0;
+}
+.tabs-blue {
+/*  background:#CCCCFF url("SDbg.gif") repeat-x bottom;*/
+}
+
+.tabs ul,.tabs-blue ul {
+  margin:0;
+  padding:10px 10px 0px;
+  list-style:none;
+  overflow:hidden;
+/*  display:none;*/
+/*  border-collapse:collapse;*/
+/*  height:2.6ex;*/
+}
+
+.tabs li,.tabs-blue li {
+  background:url("Tab-left.gif") no-repeat left top;
+  margin:0;
+  padding:0 0 0 9px;
+  float:left;
+/*  float:right;
+  direction:rtl;*/
+}
+
+/* MediaWiki automatically removes links for the current page and surrounds it with <strong> tags instead */
+.tabs a,.tabs-blue a,.tabs strong,.tabs-blue strong {
+  float:none;
+  display:block;
+  background:url("Tab-right.gif") no-repeat right top;
+  padding: 3px 8px 2px 0px;
+  text-decoration:none;
+  font-weight:bold;
+  font-family:Arial,Helvetica,Sans-serif;
+  font-size: x-small;
+  color:#765;
+}
+
+.tabs-blue li {
+  background:url("SDleft.gif") no-repeat left top;
+/*  border-bottom: 1px solid #aa9988;*/
+}
+
+.tabs-blue a,.tabs-blue strong {
+  background:url("SDright.gif") no-repeat right top;
+}
+
+.tabs-blue #current {
+  background-image:url("SDleft_on.gif");
+}
+
+.tabs-blue #magnify {
+  background-image:url("Tab-left.gif");
+  margin: 0 7px 0 0;
+}
+.tabs-blue #magnify a,.tabs-blue #current strong {
+  background-image:url("Tab-right.gif");
+}
+
+.tabs-blue #prevnext {
+   background-image:url("Tab-left.gif");
+   float:right;
+}
+.tabs-blue #prevnext a,.tabs-blue #current strong {
+  background-image:url("Tab-right.gif");
+}
+
+.tabs-blue #current a,.tabs-blue #current strong {
+  background-image:url("SDright_on.gif");
+}
+
+.tabs #current {
+  background-image:url("Tab-left_on.gif");
+}
+
+.tabs-blue #current {
+   border-bottom:none;
+}
+
+.tabs #current a,.tabs #current strong,.tabs-blue #current a, .tabs-blue #current strong {
+  background-image:url("Tab-right_on.gif");
+  color:#825;
+  padding-bottom:3px;
+/*  border-bottom:none;*/
+}
+
+.tabcontent {
+  font:             x-small sans-serif;
+/*  border:           1px dashed #aa9988;
+  padding:          5px 7px 5px 5px;
+  border-top:       none;*/
+  border:           1px solid #aa9988;
+  padding: 0;
+
+/*  background-color: #f6f6f0;*/
+background-color: #ffffff;
+  color:            #000;
+  clear:   	    both;
+  /*opacity:          0.8;*/
+  border-collapse:collapse;
+  /*cursor:url("zoomin.cur");*/
+}
+
+.tabcontent #prevtab {
+  float: left;
+  margin-top: -1.5em; 
+  background-color: #DAE0D2; 
+  color: #000; 
+  padding: .2em .6em; 
+  font-size: 130%; 
+  border: 1px solid #765;
+}
+
+.tabcontent #nexttab {
+  float: right; 
+  margin-top: -1.5em; 
+  background-color: #DAE0D2; 
+  color: #000; 
+  padding: .2em .6em; 
+  font-size: 130%; 
+  border: 1px solid #765;
+}
+
+/* Commented Backslash Hack
+   hides rule from IE5-Mac \*/
+.tabs a, .tabs-blue a {float:none;}
+/* End IE5-Mac hack */
+.tabs a:hover, .tabs-blue a:hover {
+  color:#001;
+}
+
+.marstable {
+  font: small sans-serif;
+}
+
+.marstable tr {
+  background-color: #eeeeee;
+}
+
+.marstable #title {
+   text-align:       center;
+   font-weight:      bold;
+   font-size:        150%;
+   background-color: #cccccc;
+   border: 1px solid #bbaa99;
+   background-image:url("box_mtl_ctr.gif");
+}
+
+.marstable #left {
+  text-align: right;
+  padding:0px 5px;
+}
+
+.marstable #middle {
+  text-align: center;
+  padding:1px 5px;
+}
+
+.marstable #right {
+  text-align: left;
+  padding:0px 5px;
+}
+
+.marstable a {
+  font-weight:bold;
+  text-decoration:none;
+  color:#63F;
+}
+
+/* Commented Backslash Hack
+   hides rule from IE5-Mac \*/
+.marstable a {float:none;}
+/* End IE5-Mac hack */
+.marstable a:hover {
+  color:#333;
+}
+
+a.tooltip {
+   text-decoration:none;  
+}                  
+
+.tooltip span.info {
+   display: none;
+}
+
+.tooltip:hover span.info {
+   margin:     20px 5px 5px 5px;
+   padding:    3px 15px 5px 15px;
+   border:     1px solid #808080;
+   background: #F6F6F6;
+   display:    block;
+   position:   absolute;
+   width:      200px;
+   font-size:  small;
+   opacity:    0.94;
+}
+
+.tooltip span.preview {
+   display:none;
+}
+
+.tooltip:hover span.preview {
+   padding:    30px 40px 30px 40px;
+   border:     1px solid #808080;
+   background: #F0F0F8;
+   display:    block;
+   position:   fixed;
+   top:        100;
+   right:      40;
+   opacity:    0.95;
+   text-align: center;
+   font-size:  14;
+}
+
+.tooltip:hover img {
+   border:     1px solid #808080;
+}
+
+.tooltip span.preview div {
+   padding:          4px 0px 4px;
+   background-color: #C0C0C8;
+   border:           1px solid #808080;
+   border-bottom:    none;
+}
Index: branches/Mars_McMismatchStudy/datacenter/db/tabs.js
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/tabs.js	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/tabs.js	(revision 17960)
@@ -0,0 +1,384 @@
+var gFit    = true;
+var gWidth  = 800;
+var gHeight = 600;
+
+function getStyle(element, strCssRule)
+{
+    if (document.defaultView && document.defaultView.getComputedStyle)
+        return document.defaultView.getComputedStyle(element, "").getPropertyValue(strCssRule);
+
+    if (!element.currentStyle)
+        return "";
+
+    strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1) { return p1.toUpperCase(); });
+    return element.currentStyle[strCssRule];
+}
+
+function getIntStyle(element, strCssRule)
+{
+    if (getStyle(element, strCssRule)=="auto")
+        return 0;
+
+    return parseInt(getStyle(element, strCssRule).replace("px", ""));
+}
+
+function HasClass(element, classname)
+{
+    if (!element)
+        return "";
+
+    var elemClasses = element.className.split(' '); // get list of classes
+    for (var i=0; i<elemClasses.length; i++)
+    {
+        var elemClass = elemClasses[i];
+        if (elemClass.substring(0, classname.length)==classname)
+            return elemClass.substring(classname.length, elemClass.length);
+    }
+    return "";
+}
+
+function GetCurrentTab()
+{
+    var element = document.getElementById('current');
+
+    var sub = HasClass(element, "tabno");
+    return sub ? parseInt(sub) : -1;
+}
+
+function GetFirstVisibleTab()
+{
+    var currentTab = GetCurrentTab();
+    if (currentTab<0)
+        return -1;
+
+    var elems = document.getElementsByTagName("li");
+    for (var i=0; i<elems.length; i++)
+    {
+        var n = HasClass(elems[i], "tabno");
+        if (!n || n=='0')
+            continue;
+
+        if (elems[i].style.display=='none')
+            continue;
+
+        return i;
+    }
+
+    return -1;
+}
+
+function Hide()
+{
+    var tab = GetFirstVisibleTab();
+    if (tab<0)
+        return;
+
+    var elems = document.getElementsByTagName("li");
+    if (tab<elems.length-1)
+        elems[tab].style.display = 'none';
+}
+
+function Show()
+{
+    var tab = GetFirstVisibleTab();
+    if (tab<0)
+        return;
+
+    var elems = document.getElementsByTagName("li");
+    if (tab>0)
+        elems[tab-1].style.display='block';
+}
+
+function Switch(tabnum)
+{
+    var cnt = 0;
+
+    var elems = document.getElementsByTagName("li");
+    for (var i=0; i<elems.length; i++)
+    {
+        if (HasClass(elems[i], "tabno"))
+        {
+            elems[i].id = "";
+            cnt++;
+        }
+    }
+
+    tabnum = (tabnum+cnt)%cnt;
+
+    for (var i=0; i<elems.length; i++)
+    {
+        if (!HasClass(elems[i], "tabno"))
+            continue;
+
+        if (tabnum-->0)
+            continue;
+
+        elems[i].id = 'current';
+        break;
+    }
+
+    var cur = document.getElementById('current');
+    if (!cur)
+        return;
+
+    var elem = cur.getElementsByTagName('a')[0];
+    var type = HasClass(elem, "load_");
+
+    if (type=="png")
+        LoadImg(elem.name);
+    if (type=="html")
+        LoadLog(elem.name);
+    if (type=="rc")
+        LoadRc(elem.name);
+    if (type=="def")
+        Mars();
+}
+
+function Add(i)
+{
+    var currentTab = GetCurrentTab();
+    if (currentTab<0)
+        return;
+
+    Switch(currentTab+i);
+}
+
+function GetWidth()
+{
+    var dw = 0;
+
+    var element1 = document.getElementById('tabcontent');
+    dw += getIntStyle(element1, "padding-right");
+    dw += getIntStyle(element1, "padding-left");
+
+    dw += 2*14;   // width of box_mtl_topl.gif and box_mtl_topr.gif
+
+    return gFit ? document.width-dw : gWidth;
+}
+
+function GetHeight()
+{
+    var element = document.getElementById('tabcontent');
+
+    var dh = 0;
+    dh += getIntStyle(element, "padding-top");
+    dh += getIntStyle(element, "padding-bottom");
+
+    return gFit ? (document.width-dh)*gHeight/gWidth : gHeight;
+}
+
+function ChangeCursor()
+{
+//    document.body.style.cursor='url(magnify-glass.cur)';
+}
+
+function LoadImg(fname)
+{
+    var img = new Image();
+    img.src = fname;
+
+    gWidth  = img.width;
+    gHeight = img.height;
+
+    document.getElementById('tabcontent').innerHTML =
+        "<IMG id='mainpic' "+
+        "onclick='ToggleSize();' style='background-color:#ffffff;' alt='"+fname+"' "+
+        (GetWidth()>0 ?("width='"+GetWidth()+"'"):"")+
+        (GetHeight()>0?("height='"+GetHeight()+"'"):"")+
+        " src='"+fname+"'"+"></IMG>";
+}
+
+function LoadImgTT(fname)
+{
+    var img = new Image();
+    img.src = fname;
+
+    var w = 480;
+    var h = 480*img.height/img.width;
+
+    var elements = document.getElementsByTagName('span');
+    for (var i=0; i<elements.length; i++)
+    {
+        var elemClasses = elements[i].className.split(' '); // get list of classes
+        for (var j=0; j<elemClasses.length; j++)
+        {
+            if (elemClasses[j]=="preview")
+            {
+                elements[i].getElementsByTagName('span')[0].innerHTML =
+                    "<IMG style='background-color:#ffffff;' alt='"+fname+"' width='"+w+"' height='"+h+"' src='"+fname+"'"+"></IMG>";
+                break;
+            }
+        }
+
+    }
+}
+
+function Mars()
+{
+    document.getElementById('tabcontent').innerHTML = "<div style='padding:1 5 5 15;'>"
+        + document.getElementById('default').innerHTML + "</div>";
+    // width:"+GetWidth()+";height:"+GetHeight()+"
+}
+
+function Size(fit)
+{
+    gFit = fit;
+
+    Resize();
+
+    var element = document.getElementById('mainpic');
+    if (!element)
+        return;
+
+    element.width  = GetWidth();
+    element.width  = GetWidth(); /* INTENTIONAL */
+    element.height = GetHeight();
+}
+
+function ToggleSize()
+{
+    Size(!gFit);
+    document.getElementById('magtxt').innerHTML = gFit ? "O" : "Z";
+    Resize();
+}
+
+function Resize()
+{
+    var e = document.getElementById('tabsul');
+    var h = getIntStyle(document.getElementById('magnify'), "height");
+    var p = getIntStyle(e, "padding-right");
+
+    // Order is important!
+    e.style.height = h;  // +1 to show the bottom border
+    e.style.width  = document.width-p*2;
+
+/*
+    var w = 0;
+
+    w += getIntStyle(element, "padding-right");
+    w += getIntStyle(element, "padding-left");
+
+    document.getElementById('myContent').innerHTML = w+" ";
+
+    var elements = document.getElementsByTagName('li');
+    for (var i=0; i<elements.length; i++)
+    {
+        w += getIntStyle(elements[i], "padding-left");
+        w += getIntStyle(elements[i], "padding-right");
+        w += getIntStyle(elements[i], "width");
+    }
+
+    document.getElementById('tabs').style.width = w;*/
+}
+
+var xmlHttpObject = false;
+if (typeof XMLHttpRequest != 'undefined')
+    xmlHttpObject = new XMLHttpRequest();
+
+if (!xmlHttpObject)
+{
+    try { xmlHttpObject = new ActiveXObject("Msxml2.XMLHTTP"); }
+    catch(e) 
+    {
+        try { xmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP"); }
+        catch(e) { xmlHttpObject = null; }
+    }
+}
+
+function LoadLog(file)
+{
+
+    document.getElementById('tabcontent').innerHTML = 
+        '<iframe style="border-width:1px;border-style:solid;" frameborder="0" height="90%" width="100%" src="'+file+'">'+
+        '<P>Please click <a href="'+file+'">here</a>.</P>'+
+        '</iframe>';
+
+    /*
+    xmlHttpObject.open('get', file);
+    xmlHttpObject.onreadystatechange = handleContentLog;
+    xmlHttpObject.send(null);
+    return false;*/
+}
+
+function handleContentLog()
+{
+    /*
+       0: nicht initialisiert
+       1: objekt bereit aber noch keine daten gesendet
+       3: daten werden empfangen
+       4: alle daten wurden empfangen
+       */
+    if (xmlHttpObject.readyState == 4)
+    {
+        document.getElementById('tabcontent').innerHTML = xmlHttpObject.responseText;
+    }
+}
+
+function LoadRc($file)
+{
+    document.getElementById('tabcontent').innerHTML = 
+        '<iframe style="border-width:1px;border-style:solid;" frameborder="0" height="90%" width="100%" src="'+file+'">'+
+        '<P>Please click <a href="'+file+'">here</a>.</P>'+
+        '</iframe>';
+/*
+    xmlHttpObject.open('get', $file);
+    xmlHttpObject.onreadystatechange = handleContentRc;
+    xmlHttpObject.send(null);
+    return false;*/
+}
+
+function handleContentRc()
+{
+    /*
+     0: nicht initialisiert
+     1: objekt bereit aber noch keine daten gesendet
+     3: daten werden empfangen
+     4: alle daten wurden empfangen
+     */
+    if (xmlHttpObject.readyState == 4)
+    {
+        document.getElementById('tabcontent').innerHTML = "<pre>"+xmlHttpObject.responseText+"<pre>";
+    }
+}
+
+function LoadLogTT(file)
+{
+    return false;
+
+    xmlHttpObject.open('get', file);
+    xmlHttpObject.onreadystatechange = handleContentTT;
+    xmlHttpObject.send(null);
+    return false;
+}
+
+function handleContentTT()
+{
+    /*
+     0: nicht initialisiert
+     1: objekt bereit aber noch keine daten gesendet
+     3: daten werden empfangen
+     4: alle daten wurden empfangen
+     */
+    if (xmlHttpObject.readyState == 4)
+    {
+        var elements = document.getElementsByTagName('span');
+        for (var i=0; i<elements.length; i++)
+        {
+            var elemClasses = elements[i].className.split(' '); // get list of classes
+            for (var j=0; j<elemClasses.length; j++)
+            {
+                if (elemClasses[j]=="preview")
+                {
+                    elements[i].innerHTML = xmlHttpObject.responseText;
+                    break;
+                }
+            }
+
+        }
+    }
+}
+
+function Execute()
+{
+   Size(gFit);
+}
Index: branches/Mars_McMismatchStudy/datacenter/db/tabs.php
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/db/tabs.php	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/db/tabs.php	(revision 17960)
@@ -0,0 +1,243 @@
+<?  // To be shifted to magicdefs.pho
+$htpath = "/var/www/uni-wuerzburg.de/astro/db/htdocs/datacenter";
+$htlink = "http://datacenter.astro.uni-wuerzburg.de";
+
+$htlinks = dirname($_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);
+
+$paths = array
+    (
+     "star"    => "/star/",
+     "calib"   => "/callisto/",
+     "signal"  => "/callisto/",
+     "ganymed" => "/ganymed/",
+     "gplotdb" => "/ganymed/",
+     "db"      => "/plotdb/",
+     "status"  => "/status/",
+     "condor"  => "/condor/",
+     "optical" => "/optical/",
+     );
+
+$csvname = array
+    (
+     "star"    => "star",
+     "calib"   => "calib",
+     "signal"  => "signal",
+     "ganymed" => "ganymed",
+     "gplotdb" => "plotdb",
+     "db"      => "plotdb",
+     "status"  => "plotstat",
+     "condor"  => "plotusage",
+     "optical" => "plotoptical",
+     );
+
+$prefix = array
+    (
+     "star"    => "star",
+     "calib"   => "calib",
+     "signal"  => "signal",
+     "ganymed" => "ganymed",
+     "gplotdb" => "gplotdb",
+     "db"      => "plotdb",
+     "status"  => "status",
+     "condor"  => "condor",
+     "optical" => "optical",
+     );
+
+?>
+<?   // Prepare
+
+   $number = empty($_GET["n"]) ? -1   : $_GET["n"];
+   $type   = empty($_GET["t"]) ? "db" : $_GET["t"];
+
+   $path = $htpath.$paths[$type];
+   if ($number>0)
+       if ($type=="ganymed" || $type=="gplotdb")
+           $path = sprintf($path."%05d/%08d/", $number/1000, $number);
+       else
+           $path = sprintf($path."%04d/%08d/", $number/10000, $number);
+?>
+<?
+
+   $csvfile=$path.$csvname[$type].".csv";
+   if (file_exists($csvfile))
+   {
+       // read the file into an array
+       $lines = file($csvfile);
+
+       // some replacement for the printf
+       $search  = array ("%",  "\n", "\\"   );
+       $replace = array ("%%", "",   "\\\\" );
+
+       for ($i=0; $i<sizeof($lines); $i++)
+       {
+           //$arr = get_csv($lines[$i], "\t\n");
+           $tok = strtok($lines[$i], "\t\n");
+           $j=0;
+           while ($tok!==false)
+           {
+               $arr[$i][$j++] = str_replace($search, $replace, $tok);
+               $tok = strtok("\t");
+           }
+       }
+   }
+
+//    fclose($file);
+?>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+   <meta name="Author" content="Thomas Bretz">
+   <link rel="stylesheet" type="text/css" href="tabs.css">
+   <script type="text/javascript" src="tabs.js">You need JavaScript switched on for this page to work!</script>
+   <title>Tabs: <? printf($arr[0][2]); ?></title>
+</head>
+
+<body onload="Resize();Switch(0);" onresize="Execute();">
+<div class="tabs-blue" id="tabs">
+<ul id="tabsul">
+ <li id='prevnext'><A HREF="#" accesskey='alt-shift-P' style="width:6;" class='tooltip' onclick="Add(+1);">+<span class='info'>Switch to previous tab.</span></A></li>
+ <li id='prevnext' style='margin-left:5px'><A HREF="#" accesskey='alt-shift-N' style="width:6;" class='tooltip' onclick="Add(-1);">-<span class='info'>Switch to next tab.</span></A></li>
+ <li id='prevnext'><A HREF="#" accesskey='alt-shift-P' style="width:6;" class='tooltip' onclick="Hide();">&gt;<span class='info'>Step in shown tabs to right.</span></A></li>
+ <li id='prevnext' style='margin-left:5px'><A HREF="#" accesskey='alt-shift-N' style="width:6;" class='tooltip' onclick="Show();">&lt;<span class='info'>Step in shown tabs to leaft.</span></A></li>
+ <li id='magnify'><A HREF="#" style="width:8;" class='tooltip' id="magtxt" onclick="ToggleSize();">O<span class='info'>Toggle between original image size and resized to the document's width.</span></A></li>
+<?
+   $n=0;
+
+   printf(" <li style='margin-right:3px' id='current' class='tabno%d'><A HREF=\"#\" class='tooltip load_def' onclick=\"Switch(%d);\">MARS<span class='info' style='text-align:center;'><P><font style='text-decoration:underline;'>Tab Overview</font><P>%s</span></A></li>\n",
+          $n, $n, $arr[0][2]);
+
+   $n++;
+
+   for ($i=1; $i<sizeof($lines); $i++, $n++)
+   {
+       // Use blur() to remove the focus after the click
+
+       foreach (glob($path.$prefix[$type].$i.".png") as $file)
+       {
+           $link = ereg_replace("^".$htpath, $htlink, $file);
+           $name = basename($file);
+
+           printf(" <li class='tabno".$n."'>");
+           printf("<A class='tooltip load_png' name='".$link."' ");
+           printf("onclick=\"Switch(".$n.");\" ");
+           printf("onmouseover=\"LoadImgTT('".$link."');\" HREF='#'>");
+           printf($arr[$i][1]."<span class='info'>".$arr[$i][2]."</span>");
+           printf("<span class='preview' id='preview'><div>".$arr[$i][2]."</div>");
+           printf("<span id='image'></span></span></A></li>\n");
+       }
+   }
+
+   foreach (glob($path."/*") as $file)
+   {
+        $info = pathinfo($file); // dirname, extension, basename, filename
+
+        $link   = ereg_replace("^".$htpath, $htlink, $file);
+        $name   = $info['basename'];
+        $exten  = $info['extension'];
+        
+
+        // Define list of valid extension
+        if ($exten!="html" && $exten!="rc")
+           continue;
+
+        printf(" <li class='tabno".$n."'>");
+        printf("<A class='tooltip load_".$exten."' name='".$link."' ");
+        printf("onclick=\"Switch(".$n.");\" HREF='#'>");
+
+        if ($exten=="html")
+            printf(ereg_replace("[0-9]{8}\.html", "", $name).".log");
+        if ($exten=="rc")
+            printf($name);
+
+        printf("<span class='info'>".$name."</span></A></li>\n");
+
+        $n++;
+   }
+?>
+</ul>
+</div>
+<table style="clear:both;" background="box_mtl_ctr.gif" border="0" cellpadding="0" cellspacing="0" width="100%">
+<tbody>
+  <tr height="12">
+     <td width="12"><img src="box_mtl_topl.gif"></td>
+     <td background="box_mtl_top.gif"><img src="spacer.gif"></td>
+     <td width="12"><img src="box_mtl_topr.gif"></td>
+  </tr>
+  <tr>
+     <td background="box_mtl_l.gif" width="12"><img src="spacer.gif"></td>
+     <td align="center" background="bg_spacer.gif" valign="top">
+       <div class="tabcontent" id="tabcontent"></div>
+     </td>
+     <td background="box_mtl_r.gif" width="12"><img src="spacer.gif"></td>
+  </tr>
+  <tr height="14">
+     <td width="12"><img src="box_mtl_botl.gif"></td>
+     <td background="box_mtl_bot.gif"><img src="spacer.gif"></td>
+     <td width="12"><img src="box_mtl_botr.gif"></td>
+  </tr>
+</tbody>
+</table>
+<!--
+<div class="tabcontent" id="tabcontent"></div>
+-->
+<div style="display:none" id="default">
+<?
+     printf("<p>\n");
+     printf("<center>\n");
+     printf(" <table class='marstable'>\n");
+     printf("  <tr><td id='title' colspan='3'>%s</td></tr>\n", $arr[0][2]);
+
+     for ($i=1; $i<sizeof($lines); $i++)
+     {
+         foreach (glob($path.$prefix[$type].$i.".png") as $file)
+         {
+             $link = ereg_replace("^".$htpath, $htlink, $file);
+             $name = basename($file);
+
+             printf("  <tr>");
+             printf("<td id='left'>%d</td>", $i);
+             printf("<td id='middle'><A HREF=\"#\" ");
+             printf("onclick=\"Switch(".$i.");\">");
+             printf(htmlspecialchars($arr[$i][1])."</A></td>");
+             printf("<td id='right'>".htmlspecialchars($arr[$i][2])."</td>");
+            printf("</tr>\n");
+         }
+     }
+
+     foreach (glob($path."*") as $file)
+        if (ereg("\.(root|log|html|pdf|ps|rc)$", $file))
+        {
+            $link = ereg_replace("^".$htpath, $htlink, $file);
+            $name = basename($file);
+
+            printf("  <tr>");
+            printf("<td id='left'></td>");
+            printf("<td id='middle'>Download</td>");
+            printf("<td id='middle' colspan='1'><A HREF=\"".$link."\">".$name."</A></td>");
+            printf("</tr>\n");
+        }
+        
+     printf(" </table>\n");
+     printf("</center>\n");
+     printf("</p>\n");
+?>
+</div>
+<p id="myContent">
+<?/*printf(
+"SERVER: ".$_SERVER["SERVER_NAME"]."<br>".
+"HTTP_HOST: ".$_SERVER["HTTP_HOST"]."<br>".
+"REQ_URI: ".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]."<br>".
+"DIR: ".dirname($_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"])."<br>".
+"REQ_URI: ".basename($_SERVER["REQUEST_URI"])."<br>".
+"PATH_TRANS: ".$_SERVER["PATH_TRANSLATED"]."<br>".
+"PATH_INFO: ".$_SERVER["PATH_INFO"]."<br>".
+"SCRIPT_NAME: ".$_SERVER["SCRIP_NAME"]."<br>".
+"_FILE_: ".__FILE__."<br>".
+"_DIR_: ".__DIR__."<br>".
+$paths[$type]."\n".$path."\n".$_GET["number"]."\n".$_GET["type"]."\n".$number."\n".$type);
+*/?>
+</p>
+</body>
+</html>
Index: branches/Mars_McMismatchStudy/datacenter/macros/buildsequenceentries.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/buildsequenceentries.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/buildsequenceentries.C	(revision 17960)
@@ -0,0 +1,1283 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// buildsequenceentries.C
+// ======================
+//
+// to group the runs of one night into sequences, this marco:
+//  - reads the runinformation of one night from the database
+//  - group the runs into sets of following runs with the same conditions
+//  - groups the runs in this sets to sequences such that each run belongs
+//    to the nearest (in time) calibration run
+//  - check if the runs with the same runtype have the same calibration script
+//    and the same trigger tables
+//  if sequence is okay:
+//  - check if in the range of the runnumbers of this sequence other sequences
+//    exist in the database
+//  if there are no sequences, insert the new sequence, else:
+//  - delete overlaping sequences
+//  if there's only one sequence in the same runnumber range:
+//  - check if the new and the old sequence are identical
+//    if they are identical, do nothing, if not, delete the old sequence and
+//    insert the new one
+//
+// remark: deleting sequences includes the following steps:
+// - delete entries from the tables Sequences, SequenceProcessStatus,
+//   Calibration and Star
+// - updating the sequence number (fSequenceFirst) in the table RunData
+// - remove the Sequence File, the calibrated data and the image files from
+//   the disk
+//
+// the macro can be executed either for all nights or for one single night
+// .x buildsequenceentries.C+( "datapath", "sequpath", Bool_t dummy=kTRUE)
+// .x buildsequenceentries.C+( "night", "datapath", "sequpath")
+//
+// the Bool_t dummy:
+//  kTRUE:  dummy-mode, i.e. nothing is inserted into the database, but the
+//          commands, that would be executed are returned
+//  kFALSE: the information is inserted into the database and the files of
+//          removed sequences is deleted
+// be careful with this option - for tests use always kTRUE
+//
+// TString datapath, TString sequpath:
+//  datapath: path, where the processed data is stored in the datacenter
+//  sequpath: path, where the sequence files are stored in the datacenter
+// the datapath (standard: /magic/data/) and the sequencepath (standard:
+// /magic/sequences) have to be given, that the sequence file, the
+// calibrated data and the star files can be removed, when an old sequence
+// has to be removed from the database
+//
+// If nothing failes 1 is returned. In the case of an error 2 and if
+// there's no connection to the database 0 is returned.
+// This is needed for the scripts that execute the macro.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+#include <errno.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include <TEnv.h>
+#include <TMap.h>
+#include <TMath.h>
+#include <TExMap.h>
+#include <TArrayI.h>
+#include <TArrayL.h>
+#include <TArrayD.h>
+#include <TPRegexp.h>
+#include <TSystem.h>
+#include <TObjString.h>
+#include <TObjArray.h>
+
+#include "MTime.h"
+#include "MDirIter.h"
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+    /*static*/ ULong_t GetId(const TString str)
+    {
+        const Ssiz_t dot = str.First('.');
+
+        const UInt_t run = str.Atoi();
+        const UInt_t sub = dot<0 ? 0 : atoi(str.Data()+dot+1);
+
+        return ULong_t(run)*1000+sub;
+    }
+
+
+class Rule : public TObject
+{
+private:
+    TPRegexp fRegexp;
+
+    ULong_t fMin;
+    ULong_t fMax;
+
+public:
+    Rule(TObjArray &arr) :
+        fRegexp(arr.GetEntries()>0?Form("^%s", arr[0]->GetName()):""),
+            fMin(0), fMax((ULong_t)-1)
+    {
+        if (arr.GetEntries()>1)
+            fMin = GetId(arr[1]->GetName());
+        if (arr.GetEntries()>2)
+            fMax = GetId(arr[2]->GetName());
+    }
+
+    Ssiz_t Match(const TString &str, Int_t idx, Long_t run=-1)
+    {
+        if (!IsValid(run))
+            return 0;
+
+        TString mods;
+        TArrayI pos;
+        fRegexp.Match(str.Data()+idx, mods, 0, str.Length()*10, &pos);
+
+        return pos.GetSize()<2 ? 0 : pos[1]-pos[0];
+    }
+
+    Bool_t IsValid(ULong_t run) const { return run>=fMin && run<=fMax; }
+    ClassDef(Rule, 0)
+};
+ClassImp(Rule);
+
+class CheckMatch : public TObject
+{
+private:
+    TPRegexp fRunType1;
+    TPRegexp fRunType2;
+
+    TPRegexp fRegexp1;
+    TPRegexp fRegexp2;
+
+    ULong_t fMin;
+    ULong_t fMax;
+
+    void Init(const TObjArray &arr, Int_t idx=0)
+    {
+        const Int_t n = arr.GetEntries();
+
+        const Bool_t isminus = n>idx && TString(arr[idx]->GetName())=="-";
+
+        for (int i=0; i<n-idx; i++)
+        {
+            //cout << arr[i+idx]->GetName() << " ";
+
+            TString str(arr[i+idx]->GetName());
+            if (str=="*")
+                str = ".*";
+
+            switch (isminus && i>1 ? i+1 : i)
+            {
+            case 0: fRunType1 = TPRegexp(Form(isminus?"-":"^%s$", str.Data())); break;
+            case 1: fRunType2 = TPRegexp(Form("^%s$", str.Data())); break;
+            case 2: fRegexp1  = TPRegexp(Form("^%s$", str.Data())); break;
+            case 3: fRegexp2  = TPRegexp(Form("^%s$", str.Data())); break;
+            case 4: fMin      = GetId(str);               break;
+            case 5: fMax      = GetId(str);               break;
+            }
+        }
+    }
+
+public:
+    CheckMatch() : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2("") {}
+
+    CheckMatch(const TString &txt) : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2(""), fMin(0), fMax((ULong_t)-1)
+    {
+        TObjArray *arr = txt.Tokenize(" ");
+        Init(*arr);
+        delete arr;
+    }
+
+    CheckMatch(TObjArray &arr, Int_t idx=0) : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2(""), fMin(0), fMax((ULong_t)-1)
+    {
+        Init(arr, idx);
+    }
+
+    CheckMatch(const char *from, const char *to, Long_t min=0, Long_t max=-1)
+        : fRunType1(".*"), fRunType2(".*"), fRegexp1(Form("^%s$", from)), fRegexp2(Form("^%s$", to)), fMin(min), fMax(max)
+    {
+    }
+
+    Int_t Matches(const TString &rt1, const TString &rt2, const TString &lc1, const TString &lc2, ULong_t run=0)
+    {
+        if (run>0)
+        {
+            if (run<fMin || run>fMax)
+                return kFALSE;
+        }
+
+        const TString test("X-"); // FIXME:STUPID!
+
+        //if (test.Index(fRunType2)==1)
+         //   return -(!rt1(fRunType1).IsNull() && !lc1(fRegexp1).IsNull());
+
+        if (test.Index(fRunType1,0)==1)
+            return -(!rt2(fRunType2).IsNull() && !lc2(fRegexp2).IsNull());
+
+        return !rt1(fRunType1).IsNull() && !rt2(fRunType2).IsNull() && !lc1(fRegexp1).IsNull() && !lc2(fRegexp2).IsNull();
+    }
+    ClassDef(CheckMatch,0)
+};
+ClassImp(CheckMatch);
+
+class CheckList : public TList
+{
+public:
+    CheckList() { SetOwner(); }
+    Int_t Matches(const TString &rt1, const TString &rt2, const TString &lc1, const TString &lc2, Long_t run=-1) const
+    {
+        TIter Next(this);
+
+        CheckMatch *check = 0;
+
+        while ((check=(CheckMatch*)Next()))
+        {
+            const Int_t rc = check->Matches(rt1, rt2, lc1, lc2, run);
+            if (rc)
+                return rc;
+        }
+
+        return kFALSE;
+    }
+    ClassDef(CheckList,0)
+};
+ClassImp(CheckList);
+
+class SequenceBuild : public MSQLMagic
+{
+private:
+    TString fPathRawData;
+    TString fPathSequences;
+
+    Int_t fTelescopeNumber;
+
+    TMap  fMap;
+    TList fListRegexp;
+
+    Int_t CheckTransition(TSQLResult &res, const TString *keys, TSQLRow &row, Int_t i)
+    {
+        // Get the name of the column from result table
+        const TString key = res.GetFieldName(i);
+
+        // Get the list with the allowed attributed from the map
+        CheckList *list = dynamic_cast<CheckList*>(fMap.GetValue(key));
+        if (!list)
+            return kFALSE;
+
+        // Check whether the current run (row[0]) with the current attribute
+        // (row[i]) and the current run-type (row[1]) matches the attribute
+        // of the last run (keys[i] with run-type row[i])
+        return list->Matches(keys[1], row[1], keys[i], row[i], atol(row[0]));
+    }
+
+    Bool_t InsertSequence(Long_t from, Long_t to)
+    {
+        cout << "     - Inserting Sequence into database." << endl;
+
+        // ========== Request number of events ==========
+
+        // Can be replaced by
+
+        const TString runtime =
+            "SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))), ";
+
+        const TString where = Form("(fRunNumber*1000+fFileNumber BETWEEN %ld AND %ld) "
+                                   "AND fTelescopeNumber=%d AND fExcludedFDAKEY=1",
+                                   from, to, fTelescopeNumber);
+
+        TString query;
+        query  = "SELECT SUM(fNumEvents), ";
+        query += runtime;
+        query += " MIN(fZenithDistance), MAX(fZenithDistance), ";
+        query += " MIN(fAzimuth), MAX(fAzimuth), ";
+        query += " MIN(if(fRunStart=0,NULL,fRunStart)), ";
+        query += " MAX(if(fRunStop=0,NULL,fRunStop)), ";
+        query += " ELT(MAX(FIELD(fLightConditionsKEY, 1, 2, 7, 5, 8)), 1, 2, 7, 5, 8) ";
+        query += " FROM RunData WHERE ";
+        query += where;
+        query += " AND fRunTypeKEY=2";
+
+        TSQLResult *res = Query(query);
+        if (!res)
+            return kFALSE;
+
+        TSQLRow *row = res->Next();
+        if (!row || res->GetFieldCount()!=9)
+        {
+            cout << "ERROR - Wrong result from query: " << query << endl;
+            return kFALSE;
+        }
+
+        const TString nevts = (*row)[0];
+        const TString secs  = (*row)[1];
+        const TString zdmin = (*row)[2];
+        const TString zdmax = (*row)[3];
+        const TString azmin = (*row)[4];
+        const TString azmax = (*row)[5];
+        const TString start = (*row)[6];
+        const TString stop  = (*row)[7];
+        const TString light = (*row)[8];
+
+        delete res;
+
+        const TString elts = GetELTSource(where);
+        if (elts.IsNull())
+            return kFALSE;
+
+        const TString eltp = GetELTProject(where);
+        if (eltp.IsNull())
+            return kFALSE;
+
+        // ========== Request data of sequence ==========
+        query  = "SELECT ";
+        query += elts;
+        query += ", ";
+        query += eltp;
+        query += ", fL1TriggerTableKEY, fL2TriggerTableKEY,"
+            " fHvSettingsKEY, fDiscriminatorThresholdTableKEY,"
+            " fTriggerDelayTableKEY, fObservationModeKEY, fSumTriggerFlagKEY "
+            " FROM RunData WHERE fRunTypeKEY=2 AND ";
+        query += where;
+        query += " LIMIT 1";
+
+        res = Query(query);
+        if (!res)
+            return kFALSE;
+
+        row = res->Next();
+        if (!row || res->GetFieldCount()!=9)
+        {
+            cout << "ERROR - No result from query: " << query << endl;
+            return kFALSE;
+        }
+
+        const TString set = Form("fSequenceFirst=%ld, fTelescopeNumber=%d ", from/1000, fTelescopeNumber);
+
+        TString query1;
+        query1 += set;
+        query1 += Form(",fSequenceLast=%ld,",                   to/1000);
+        query1 += Form(" fSourceKEY=%s,",                      (*row)[0]);
+        query1 += Form(" fProjectKEY=%s,",                     (*row)[1]);
+        query1 += Form(" fNumEvents=%s,",                      nevts.Data());
+        query1 += Form(" fRunTime=%s,",                        secs.Data());
+        query1 += Form(" fRunStart=\"%s\",",                   start.Data());
+        query1 += Form(" fRunStop=\"%s\",",                    stop.Data());
+        query1 += Form(" fZenithDistanceMin=%s,",              zdmin.Data());
+        query1 += Form(" fZenithDistanceMax=%s,",              zdmax.Data());
+        query1 += Form(" fAzimuthMin=%s,",                     azmin.Data());
+        query1 += Form(" fAzimuthMax=%s,",                     azmax.Data());
+        query1 += Form(" fL1TriggerTableKEY=%s,",              (*row)[2]);
+        query1 += Form(" fL2TriggerTableKEY=%s,",              (*row)[3]);
+        query1 += Form(" fHvSettingsKEY=%s,",                  (*row)[4]);
+        query1 += Form(" fDiscriminatorThresholdTableKEY=%s,", (*row)[5]);
+        query1 += Form(" fTriggerDelayTableKEY=%s,",           (*row)[6]);
+        query1 += Form(" fLightConditionsKEY=%s,",             light.Data());
+        query1 += Form(" fObservationModeKEY=%s, ",            (*row)[7]);
+        query1 += Form(" fSumTriggerFlagKEY=%s, ",             (*row)[8]);
+        query1 += "fManuallyChangedKEY=1";
+
+        delete res;
+
+        const TString where2 = Form("(fRunTypeKEY BETWEEN 2 AND 4) AND %s",
+                                    where.Data());
+
+        if (!Insert("Sequences", query1))
+        {
+            cout << "ERROR - Could not insert Sequence into Sequences." << endl;
+            return kFALSE;
+        }
+
+        if (!Update("RunData", set, where))
+        {
+            cout << "ERROR - Could not update RunData." << endl;
+            return kFALSE;
+        }
+
+        TString prio = set;
+        prio += Form(", fPriority=%ld ", from/1000);
+        if (!Insert("SequenceProcessStatus", prio))
+        {
+            cout << "ERROR - Could not insert Sequence into SequenceProcessStatus." << endl;
+            return kFALSE;
+        }
+
+        return kTRUE;
+    }
+
+    Bool_t DeleteSequence(Int_t sequ)
+    {
+        if (fPathRawData.IsNull() || fPathSequences.IsNull())
+        {
+            cout << "       + Deletion " << sequ << " skipped due to missing path." << endl;
+            return kTRUE;
+        }
+
+        //queries to delete information from the database
+        const TString query(Form("fSequenceFirst=%d", sequ));
+
+        //commands to delete files from the disk
+        const TString fname(Form("%s/%04d/sequence%08d.txt", fPathSequences.Data(),sequ/10000, sequ));
+        const TString cmd1(Form("rm -rf %s/callisto/%04d/%08d/", fPathRawData.Data(), sequ/10000, sequ));
+        const TString cmd2(Form("rm -rf %s/star/%04d/%08d/", fPathRawData.Data(), sequ/10000, sequ));
+
+        if (!Delete("Calibration", query))
+            return 2;
+
+        if (!Delete("Star", query))
+            return 2;
+
+        if (!Delete("SequenceProcessStatus", query))
+            return 2;
+
+        if (!Delete("Sequences", query))
+            return 2;
+
+        if (!Update("RunData", "fSequenceFirst=0", query))
+            return 2;
+
+        if (IsDummy())
+        {
+            cout << "       + would unlink " << fname << endl;
+            cout << "       + would remove " << cmd1 << endl;
+            cout << "       + would remove " << cmd2 << endl;
+            return kTRUE;
+        }
+
+        cout << "       + will unlink " << fname << endl;
+        cout << "       + will remove " << cmd1 << endl;
+        cout << "       + will remove " << cmd2 << endl;
+
+        gSystem->Unlink(fname);
+
+        gSystem->Exec(cmd1);
+        gSystem->Exec(cmd2);
+
+        return kTRUE;
+    }
+
+    Int_t CheckSequence(Long_t runstart, Long_t runstop)
+    {
+        const char *fmt1 = "SELECT fRunNumber*1000+fFileNumber AS Id FROM RunData WHERE";
+        const char *fmt2 = "AND fExcludedFDAKEY=1 AND (fRunTypeKEY BETWEEN 2 AND 4) ORDER BY Id";
+
+        const TString query1 = Form("%s fTelescopeNumber=%d AND fSequenceFirst=%ld %s",                              fmt1, fTelescopeNumber, runstart/1000,     fmt2);
+        const TString query2 = Form("%s fTelescopeNumber=%d AND fRunNumber*1000+fFileNumber BETWEEN %ld AND %ld %s", fmt1, fTelescopeNumber, runstart, runstop, fmt2);
+
+        TSQLResult *res1 = Query(query1);
+        if (!res1)
+            return 2;
+
+        TSQLResult *res2 = Query(query2);
+        if (!res2)
+        {
+            delete res1;
+            return 2;
+        }
+
+        while (1)
+        {
+            TSQLRow *row1 = res1->Next();
+            TSQLRow *row2 = res2->Next();
+
+            if (!row1 && !row2)
+                return kTRUE;
+
+            if (!row1 || !row2)
+                return kFALSE;
+
+            if (atol((*row1)[0])!=atol((*row2)[0]))
+                return kFALSE;
+        }
+
+        return kFALSE;
+    }
+
+    Int_t CreateSequence(Long_t runstart, Long_t runstop)
+    {
+        cout << "   * Creating Sequence " << runstart << "-" << runstop << ":" << endl;
+
+        TString query=
+            Form("SELECT fSequenceFirst FROM RunData "
+                 " WHERE fRunNumber*1000+fFileNumber BETWEEN %ld AND %ld AND "
+                 " fTelescopeNumber=%d AND fSequenceFirst>0 AND "
+                 " fExcludedFDAKEY=1 AND (fRunTypeKEY BETWEEN 2 AND 4)"
+                 " GROUP BY fSequenceFirst", runstart, runstop,
+                 fTelescopeNumber);
+
+        TSQLResult *res = Query(query);
+        if (!res)
+            return 2;
+
+        const Int_t cnt = res->GetRowCount();
+
+        Int_t rc = kTRUE;
+        if (cnt==1)
+        {
+            TSQLRow *row=res->Next();
+            const Int_t check = CheckSequence(runstart, runstop);
+            if (check==kTRUE)
+            {
+                cout << "     - Identical sequence already existing." << endl;
+                delete res;
+                return kTRUE;
+            }
+            if (check==2)
+                rc=2;
+            else
+            {
+                cout << "     - Deleting quasi-identical sequence " << atoi((*row)[0]) << endl;
+                if (DeleteSequence(atoi((*row)[0]))==2)
+                    rc = 2;
+            }
+        }
+        else
+        {
+            TSQLRow *row=0;
+            while ((row=res->Next()))
+            {
+                cout << "     - Deleting overlapping sequence " << atoi((*row)[0]) << endl;
+                if (DeleteSequence(atoi((*row)[0]))==2)
+                    rc = 2;
+            }
+        }
+
+        delete res;
+
+        if (rc==2)
+            return 2;
+
+        if (!InsertSequence(runstart, runstop))
+            return 2;
+
+        return kTRUE;
+    }
+
+    Bool_t ReadResources(const char *fname)
+    {
+        // Check for the section header
+        TPRegexp regexp("^\\[(Transition|Regexp):?[0-9 ]*\\]$");
+        // Check if section header contains a number
+        TPRegexp regnum("[0-9]");
+        // Check if section header contains the telescope number
+        TPRegexp regtel(Form("[^0-9]0*%d[^0-9]", fTelescopeNumber));
+
+        ifstream fin(fname);
+        if (!fin)
+        {
+            cout << "Cannot open file " << fname << ": ";
+            cout << strerror(errno) << endl;
+            return kFALSE;
+        }
+
+        Int_t section = 0;
+
+        TString key;
+        while (1)
+        {
+            TString txt;
+            txt.ReadLine(fin);
+            if (!fin)
+                break;
+
+            txt = txt.Strip(TString::kBoth);
+
+            if (txt[0]=='#' || txt.IsNull())
+                continue;
+
+            if (txt[0]=='[')
+            {
+                TString sec = txt(regexp);
+                if (!sec.IsNull())
+                {
+                    // Skip sections with the wrong telescope number
+                    // (If section contains numbers but not the tel num)
+                    if (!sec(regnum).IsNull() && sec(regtel).IsNull())
+                        continue;
+
+                    // Check which section we are in
+                    if (sec.BeginsWith("[Transition"))
+                        section = 1;
+                    if (sec.BeginsWith("[Regexp"))
+                        section = 2;
+
+                    continue;
+                }
+
+                if (section!=2)
+                {
+                    cout << "WARNING - Line starts with [ but we are not in the Regexp section." << endl;
+                    cout << txt << endl;
+                    continue;
+                }
+            }
+
+
+            TObjArray *arr = txt.Tokenize(" ");
+
+            if (arr->GetEntries()>0)
+                switch (section)
+                {
+                case 1:
+                    {
+                        TString key = arr->At(0)->GetName();
+                        key.Prepend("f");
+                        key.Append("KEY");
+
+                        CheckList *list = dynamic_cast<CheckList*>(fMap.GetValue(key));
+                        if (!list)
+                        {
+                            //cout << key << endl;
+                            list = new CheckList;
+                            fMap.Add(new TObjString(key), list);
+                        }
+
+                        if (arr->GetEntries()>1)
+                        {
+                            //cout << key << " ";
+                            list->Add(new CheckMatch(*arr, 1));
+                        }
+                    }
+                    break;
+                case 2:
+                    fListRegexp.Add(new Rule(*arr));
+                    break;
+                }
+
+            delete arr;
+        }
+
+        return kTRUE;
+    }
+
+    TString GetELT(const char *col, TSQLResult *res, TList &regexp)
+    {
+        TObjArray names; // array with old names (including regexp)
+
+        // Add to array and expand the array if necessary
+        TSQLRow *row=0;
+        while ((row=res->Next()))
+            names.AddAtAndExpand(new TObjString((*row)[1]), atoi((*row)[0]));
+
+        // Now a LUT is build which converts the keys for
+        // the names including the regexp into keys for
+        // the names excluding the regexp
+        TString elt(Form("ELT(RunData.f%sKEY+1", col));
+
+        // loop over all entries in the list
+        const Int_t n = names.GetSize();
+        for (int i=0; i<n; i++)
+        {
+            // For all entries which are not in the list
+            // write an undefined value into the LUT
+            TObject *o = names.UncheckedAt(i);
+            if (!o)
+            {
+                elt += ",0";
+                continue;
+            }
+
+            // Remove the regexp from the string which includes it
+            TString name = o->GetName();
+
+            TIter NextR(&regexp);
+            TObject *obj=0;
+            while ((obj=NextR()))
+            {
+                TPRegexp reg(obj->GetName());
+                const Ssiz_t pos = name.Index(reg, 0);
+                if (pos>0)
+                {
+                    name.Remove(pos);
+                    name += "-W";
+                    break;
+                }
+            }
+
+            // Check if such a Key exists, if not insert it
+            const Int_t key = QueryKeyOfName(col, name);
+
+            // RESOLVE return code!!!
+            //if (key<0)
+            //     return "";
+
+            // add index to the LUT
+            elt += Form(",%d", key);
+        }
+
+        // close LUT expression
+        //    elt += ") AS Elt";
+        //    elt += col;
+
+        elt += ") AS f";
+        elt += col;
+        elt += "KEY";
+
+        // return result
+        return elt;
+    }
+
+    TString GetELT(const char *col, TSQLResult *res, TString regexp)
+    {
+        TList list;
+        list.SetOwner();
+        list.Add(new TObjString(regexp));
+        return GetELT(col, res, list);
+    }
+
+    TString GetELTQuery(const char *col, const char *cond) const
+    {
+        return Form("SELECT RunData.f%sKEY, f%sName FROM RunData "
+                    "LEFT JOIN %s USING (f%sKEY) WHERE %s GROUP BY f%sName",
+                    col, col, col, col, cond, col);
+    }
+
+    TString GetELTSource(const char *cond)
+    {
+        //query all sources observed in this night
+        TSQLResult *resx = Query(GetELTQuery("Source", cond));
+        if (!resx)
+            return "";
+
+        // In the case there is only a single source
+        // do not replace the source key by the ELT
+        if (resx->GetRowCount()==1)
+            return "fSourceKEY";
+
+        TString elts = GetELT("Source", resx, "\\-?W[1-9][ abc]?$");
+        delete resx;
+
+        return elts;
+    }
+
+    TString GetELTProject(const char *cond)
+    {
+        //query all project names observed in this night
+        TSQLResult *resx = Query(GetELTQuery("Project", cond));
+        if (!resx)
+            return "";
+
+        // In the case there is only a single project
+        // do not replace the project key by the ELT
+        if (resx->GetRowCount()==1)
+            return "fProjectKEY";
+
+        TList regexp;
+        regexp.Add(new TObjString("\\-?W[1-9][abc]?$"));
+        regexp.Add(new TObjString("\\-W[0-9]\\.[0-9][0-9]\\+[0-9][0-9][0-9]$"));
+
+        TString eltp2 = GetELT("Project", resx, regexp);
+        delete resx;
+        regexp.Delete();
+
+        return eltp2;
+    }
+
+    Bool_t HasAtLeastOne(TString src, TString chk) const
+    {
+        src.ToLower();
+        chk.ToLower();
+
+        for (int i=0; i<chk.Length(); i++)
+            if (src.First(chk[i])<0)
+                return kFALSE;
+
+        return kTRUE;
+    }
+
+    TString PrepareString(TSQLResult &res, TArrayL &runs)
+    {
+        // Number of result rows
+        const Int_t rows = res.GetRowCount();
+
+        runs.Set(rows);       // initialize size of array for run numbers
+
+        TArrayD start(rows);  // instantiate array for start times
+        TArrayD stop(rows);   // instantiate array for stop times
+
+        TString str;          // result string
+
+        Int_t idx=0;
+        TSQLRow *row=0;
+        while ((row=res.Next()))
+        {
+            runs[idx] = atol((*row)[0]);          // run number
+
+            const TString tstart = ((*row)[2]);   // start time
+            const TString tstop  = ((*row)[3]);   // stop time
+
+            start[idx] = MTime(tstart).GetMjd();  // convert to double
+            stop[idx]  = MTime(tstop).GetMjd();   // convert to double
+
+            // This is a workaround for broken start-times
+            if (tstart=="0000-00-00 00:00:00")
+                start[idx] = stop[idx];
+
+            // Add a run-type character for this run to the string
+            str += RunType((*row)[1]);
+
+            // Increase index
+            idx++;
+        }
+
+        // Now the P- and D- runs are classified by the time-distance
+        // to the next or previous C-Run
+        Double_t lastc = -1;
+        Double_t nextc = -1;
+        for (int i=0; i<str.Length(); i++)
+        {
+            if (str[i]=='C')
+            {
+                // Remember stop time of C-Run as time of last C-run
+                lastc = stop[i];
+
+                // Calculate start time of next C-Run
+                const TString residual = str(i+1, str.Length());
+                const Int_t pos = residual.First('C');
+
+                // No C-Run found anymore. Finished...
+                if (pos<0)
+                    break;
+
+                // Remember start  time of C-Run as time of next C-run
+                nextc = start[i+1+pos];
+                continue;
+            }
+
+            // Check whether the identifying character should
+            // be converted to lower case
+            if (start[i]-lastc>nextc-stop[i])
+                str[i] = tolower(str[i]);
+        }
+        //cout << str << endl;
+        return str;
+    }
+
+    void PrintResidual(Long_t runstart, Long_t runstop, TString residual, const char *descr)
+    {
+        residual.ToLower();
+
+        // Count number of unsequences "characters"
+        const Int_t nump = residual.CountChar('p');
+        const Int_t numd = residual.CountChar('d');
+        const Int_t numc = residual.CountChar('c');
+
+        // Print some information to the output steram
+        if (nump+numc+numd==0)
+            return;
+
+        cout << "   ! " << runstart << "-" << runstop << " [" << setw(3) << 100*residual.Length()/(runstop-runstart+1) << "%]: " << descr << " not sequenced:  P=" << nump << "  C=" << numc << "  D=" << numd;
+        if (numd>0)
+            cout << "  (DATA!)";
+
+        if (nump==0 || numc==0 || numd==0)
+            cout << "  Missing";
+        if (numd==0)
+            cout << " D";
+        if (nump==0)
+            cout << " P";
+        if (numc==0)
+            cout << " C";
+
+        cout << endl;
+    }
+
+    Int_t SplitBlock(Long_t runstart, Long_t runstop, const TString &cond)
+    {
+        // Request data necessary to split block into sequences
+        /*const*/ TString query=
+            Form("SELECT fRunNumber*1000+fFileNumber AS Id, fRunTypeKEY, fRunStart, fRunStop"
+                 " FROM RunData "
+                 " WHERE fRunNumber*1000+fFileNumber BETWEEN %ld AND %ld AND "
+                 /*" fExcludedFDAKEY=1 AND (fRunTypeKEY BETWEEN 2 AND 4)"
+                  " ORDER BY Id"*/, runstart, runstop);
+
+        query += cond;
+        query += " ORDER BY Id";
+
+
+        // Send query
+        TSQLResult *res = Query(query);
+        if (!res)
+            return 2;
+
+        // Get String containing the sequence of P-,C- and D-Runs
+        // and an array with the corresponding run-numbers
+        TArrayL runs;
+        const TString str = PrepareString(*res, runs);
+
+        delete res;
+
+        // Check if the prepared string at least contains one run of each type
+        if (!HasAtLeastOne(str, "PCD"))
+        {
+            PrintResidual(runstart, runstop, str, "Block");
+            return kTRUE;
+        }
+
+        // Start the sequence building
+        // ---------------------------
+
+        Int_t   pos = 0;   // Position in the string
+        TExMap  map;       // Map for resulting sequences
+        TString residual;  // Unsequences "characters"
+
+        // Step through the string one character by one
+        cout << "   ";
+        while (pos<str.Length())
+        {
+            Bool_t found = kFALSE;
+
+            // Loop over the predefined regular expressions
+            TIter Next(&fListRegexp);
+            Rule *obj = 0;
+            while ((obj=(Rule*)Next()))
+            {
+                // Check if regular expressions matchs
+                const Ssiz_t len = obj->Match(str, pos, runs[pos]);
+                if (len>0)
+                {
+                    // In case of match get the substring which
+                    // defines the sequence and print it
+                    TString sub = str(pos, len);
+                    sub.ToUpper();
+                    cout << runs[pos]<<":"<< sub << "|";
+
+                    // Add the first and last run of the sequence to the map
+                    map.Add(runs[pos], runs[pos+len-1]);
+
+                    // A sequence was found...
+                    found = kTRUE;
+
+                    // step forward in the string by the length of the sequence
+                    pos += len;
+                    break;
+                }
+            }
+
+            // If a sequence was found go on...
+            if (found)
+                continue;
+
+            // print unsequenced characters
+            cout << (char)tolower(str[pos]);
+
+            // Count the number of "characters" not sequenced
+            residual += str[pos];
+
+            // step one character forward
+            pos++;
+        }
+        cout << endl;
+
+        PrintResidual(runstart, runstop, residual, "Runs ");
+
+        // Create all sequences which were previously found
+        Long_t first, last;
+        TExMapIter iter(&map);
+        while (iter.Next(first, last))
+            if (CreateSequence(first, last)==2)
+                return 2;
+
+        return kTRUE;
+    }
+
+    Char_t RunType(Int_t n) const
+    {
+        switch (n)
+        {
+        case 2: return 'D';
+        case 3: return 'P';
+        case 4: return 'C';
+        }
+        return '-';
+    }
+    Char_t RunType(const char *str) const
+    {
+        return RunType(atoi(str));
+    }
+
+    Int_t BuildBlocks(TSQLResult *res, TExMap &blocks, const TString &cond)
+    {
+        // col key content
+        // -----------------------------
+        //  0   -  runnumber
+        //  1   0  RunTypeKEY
+        //  2   1  source
+        //  3   2  project
+        //  .   .
+        //  .   .
+        //  .   .  from transition.txt
+        //
+
+        //build blocks of runs, which have the same values
+        //for each block the first and the last run are stored in a TExMap
+        //the values are checked with the help of an array of TStrings
+        Long_t runstart = -1;
+        Long_t runstop  = -1;
+
+        const UInt_t ncols = res->GetFieldCount();
+
+        TString keys[ncols]; // Index 0 is not used (Index 1: RunType)
+
+        // Loop over runs
+        TSQLRow *row=0;
+        while ((row=res->Next()))
+        {
+            // This is the runnumber of the first run in the new block
+            if (runstart<0)
+                runstart=atol((*row)[0]);
+
+            // Check which transitions might be allowed for this run and
+            // which are not. Check also which attributes should be ignored
+            // for this run. The information about it is stored in the map.
+            Int_t rc[ncols];
+            for (UInt_t i=2; i<ncols; i++)
+                rc[i] = CheckTransition(*res, keys, *row, i);
+
+            for (UInt_t i=2; i<ncols; i++)
+            {
+                switch (rc[i])
+                {
+                case kTRUE:    // Transition allowed, switch to new attribute
+                    keys[i] = (*row)[i];
+                    continue;
+
+                case -1:       // Ignore attribute, continue with next one
+                    //if (keys[i] == (*row)[i])
+                    //    break; // Only ignore it if it is really different
+                    continue;
+
+                case kFALSE:   // No decision (nothing matching found in map)
+                    break;     //  go on checking
+
+                }
+
+                // If past-attribute is not yet initialized, do it now.
+                if (keys[i].IsNull())
+                    keys[i] = (*row)[i];
+
+                // Check whether key has changed for this run
+                // (this condition is never true for the first run)
+                // This condition in only reached if keys[i] was initialized
+                if (keys[i] == (*row)[i])
+                    continue;
+
+                // Found one block with unique keys, fill values into TExMap
+                // (except if this is the first run processed)
+                cout << endl;
+                cout << " - Identical conditions from " << runstart << " to " << runstop << endl;
+                blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
+                if (SplitBlock(runstart, runstop, cond)==2)
+                    return 2;
+                cout << " - Transition from " << RunType(keys[1]) << ":";
+                cout << QueryNameOfKey(res->GetFieldName(i), keys[i]) << " <" << keys[i] << "> to " << RunType((*row)[1]) << ":";
+                cout << QueryNameOfKey(res->GetFieldName(i), (*row)[i]) << " <" << (*row)[i] << ">";
+                cout << " in " << res->GetFieldName(i) << " of " << (*row)[0] << endl;
+
+                // This is already the first run of the new block
+                runstart=atol((*row)[0]);
+
+                // These are the keys corresponding to the first run
+                // in the new block. All following runs should have
+                // identical keys. Do not set the attribute if for
+                // this attribute the transition check evaluated
+                // to "ignore".
+                for (UInt_t j=2; j<ncols; j++)
+                    keys[j] = rc[j]==-1 ? "" : (*row)[j];
+
+                break;
+            }
+
+            keys[1] = (*row)[1]; // Remember run type for next run
+
+            // This is the new runnumber of the last run in this block
+            runstop=atol((*row)[0]);
+        }
+
+        // If runstart==-1 a possible block would contain a single run...
+        if (runstart>0 && runstart!=runstop)
+        {
+            cout << " - Identical conditions from " << runstart << " to " << runstop << " (last run)" << endl;
+            //fill values into TExMap (last value)
+            blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
+            if (SplitBlock(runstart, runstop, cond)==2)
+                return 2;
+        }
+        cout << "Done." << endl << endl;
+
+        return kTRUE;
+    }
+
+public:
+    SequenceBuild(Int_t tel=1, const char *rc="sql.rc") : MSQLMagic(rc), fTelescopeNumber(tel)
+    {
+        fListRegexp.SetOwner();
+
+        // FIXME: THIS IS NOT YET HANDLED
+        if (ReadResources("resources/sequences.rc"))
+            return;
+    }
+
+    SequenceBuild(TEnv &env, Int_t tel=1) : MSQLMagic(env), fTelescopeNumber(tel)
+    {
+        fListRegexp.SetOwner();
+
+        // FIXME: THIS IS NOT YET HANDLED
+        if (ReadResources("resources/sequences.rc"))
+            return;
+    }
+    ~SequenceBuild()
+    {
+        fMap.DeleteAll();
+    }
+
+    void SetPathRawData(const char *path) { fPathRawData=path; }
+    void SetPathSequences(const char *path) { fPathSequences=path; }
+
+    int Build(TString day)
+    {
+        cout << endl;
+        cout << "Night of sunrise at " << day << ":" << endl;
+
+        day += " 13:00:00";
+        const TString cond =
+            Form("(fRunStart>ADDDATE(\"%s\", INTERVAL -1 DAY) AND fRunStart<\"%s\") "
+                 "AND fExcludedFDAKEY=1 AND fRunTypeKEY BETWEEN 2 AND 4 "
+                 "AND fTelescopeNumber=%d ",
+                 day.Data(), day.Data(), fTelescopeNumber);
+
+        //query all sources observed in this night
+        const TString elts = GetELTSource(cond);
+        if (elts.IsNull())
+            return 2;
+
+        //query all project names observed in this night
+        const TString eltp2 = GetELTProject(cond);
+        if (elts.IsNull())
+            return 2;
+
+        // Setup query to get all values from the database,
+        // that are relevant for building sequences
+        TString query("SELECT fRunNumber*1000+fFileNumber AS Id, fRunTypeKEY, ");
+        query += elts;
+        query += ", ";
+        query += eltp2;
+
+        // Now add all entries from the transition table to the query
+        TIter NextPair(&fMap);
+        TObject *mapkey = 0;
+        while ((mapkey=(TPair*)NextPair()))
+            if (!query.Contains(mapkey->GetName()))
+            {
+                query += ", ";
+                query += mapkey->GetName();
+            }
+        query += " FROM RunData WHERE ";
+        query += cond;
+        query += " ORDER BY Id";
+
+        TSQLResult *res = Query(query);
+        if (!res)
+            return 2;
+
+        TExMap blocks;
+        const Int_t rc = BuildBlocks(res, blocks, cond);
+        delete res;
+
+        return rc;
+    }
+
+    Int_t Build()
+    {
+        //get all dates from the database
+        TSQLResult *res = Query("SELECT fDate FROM SequenceBuildStatus ORDER BY fDate DESC");
+        if (!res)
+            return 2;
+
+        //execute buildsequenceentries for all dates
+        TSQLRow *row=0;
+        while ((row=res->Next()))
+            Build((*row)[0]);
+
+        delete res;
+
+        return 1;
+    }
+    ClassDef(SequenceBuild, 0)
+};
+
+ClassImp(SequenceBuild);
+
+int buildsequenceentries(TString day, TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    SequenceBuild serv(tel, "sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "buildsequenceentries" << endl;
+    cout << "--------------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    if (!datapath.IsNull())
+        cout << "DataPath:  " << datapath << endl;
+    if (!sequpath.IsNull())
+        cout << "SeqPath:   " << sequpath << endl;
+    cout << "Day:       " << day      << endl;
+    cout << "Telescope: " << tel      << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+    serv.SetPathRawData(datapath);
+    serv.SetPathSequences(sequpath);
+    return serv.Build(day);
+}
+
+//
+// Build Sequences for all Nights
+//
+int buildsequenceentries(TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    SequenceBuild serv(tel, "sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "buildsequenceentries" << endl;
+    cout << "--------------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "DataPath:  " << datapath << endl;
+    cout << "SeqPath:   " << sequpath << endl;
+    cout << "Telescope: " << tel      << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+    serv.SetPathRawData(datapath);
+    serv.SetPathSequences(sequpath);
+    return serv.Build();
+}
+
+int buildsequenceentries(Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    return buildsequenceentries("", "", tel, dummy);
+}
+
+int buildsequenceentries(TString day, Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    return buildsequenceentries(day, "", "", tel, dummy);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/checkfileavail.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/checkfileavail.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/checkfileavail.C	(revision 17960)
@@ -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): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// checkfileavail.C
+// ================
+//
+// check the availability of the files of one sequence:
+// the script filesondisk has inserted the information (which files are on
+// disk into the database) and with this macro this information is checked
+// for the runs of one sequence
+//
+// executing the macro:
+//  .x checkfileavail.C+(100002)
+// the sequencefile (including path) has to be given, as the macro retrieves
+// from there the runnumbers
+//
+// the macro returns 0, if there's no connection to the database, 2 if a
+// file is missing, and 1 if all files are there, 3 in case of error.
+// the return value is checked by the script, that executes the macro
+//
+// this macro is very similar to the macro checkstardone.C
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MSQLServer.h"
+
+using namespace std;
+
+int checkfileavail(Int_t num, Int_t tel)
+{
+    MSQLServer serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "checkfileavail" << endl;
+    cout << "--------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+    cout << "Sequence: " << num << endl;
+    cout << "Telecope: " << tel << endl;
+    cout << endl;
+
+    // -------------------------------------------
+
+    TString query = "SELECT MIN( NOT ("
+        "ISNULL(fRawFileAvail) OR "
+        "ISNULL(fCCFileAvail) OR "
+       // "ISNULL(fCaCoFileAvail) OR "
+       // "ISNULL(fCaCoFileFound) OR "
+        "ISNULL(fTimingCorrection) OR "
+        "ISNULL(fCompmux) "
+        ")) "
+        "FROM RunProcessStatus "
+        "LEFT JOIN RunData USING (fTelescopeNumber,fRunNumber,fFileNumber) ";
+    query += Form("WHERE fSequenceFirst=%d AND fTelescopeNumber=%d", num, tel);
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return 3;
+
+    if (res->GetRowCount()!=1)
+    {
+        cout << "ERROR - Unexpected number of returned rows (" << res->GetRowCount() << ")" << endl;
+        cout << query << endl;
+        delete res;
+        return 3;
+    }
+
+    TSQLRow *row = res->Next();
+
+    if (!row || !(*row)[0])
+    {
+        cout << "ERROR - Unexpected result." << endl;
+        cout << query << endl;
+        delete res;
+        return 3;
+    }
+
+    const Int_t rc = atoi((*row)[0]);
+
+    delete res;
+
+    return rc==1 ? 1 : 2;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/checkstardone.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/checkstardone.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/checkstardone.C	(revision 17960)
@@ -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): Daniela Dorner, 05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// checkstardone.C
+// ===============
+//
+// check the availability of all star files for one dataset:
+// if star has been executed successfully, this information has been inserted
+// into the database (SequenceProcessStatus) with this macro this information
+// is checked 
+//
+// executing the macro:
+//  .x checkstardone.C+(1)
+//
+// The macro returns 0, if there's no connection to the database, 2 if
+// star is not done, and 1 if star done, 3 in case of error.
+// the return value is checked by the script, that executes the macro
+//
+// This macro is very similar to the macro checkfileavail.C
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MSQLServer.h"
+
+using namespace std;
+
+int checkstardone(Int_t num)
+{
+    MSQLServer serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "checkstardone" << endl;
+    cout << "-------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+    cout << "Dataset: " << num << endl;
+    cout << endl;
+
+    // -------------------------------------------
+
+    TString query = "SELECT MIN(NOT ISNULL(fStar)) FROM SequenceProcessStatus "
+        "LEFT JOIN DataSetSequenceMapping USING (fTelescopeNumber,fSequenceFirst) ";
+    query += Form("WHERE fDataSetNumber=%d", num);
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return 3;
+
+    if (res->GetRowCount()!=1)
+    {
+        cout << "ERROR - Unexpected number of returned rows (" << res->GetRowCount() << ")" << endl;
+        delete res;
+        return 3;
+    }
+
+    TSQLRow *row = res->Next();
+
+    if (!row || !(*row)[0])
+    {
+        cout << "ERROR - Unexpected result." << endl;
+        delete res;
+        return 3;
+    }
+
+    const Int_t rc = atoi((*row)[0]);
+
+    delete res;
+
+    return rc==1 ? 1 : 2;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/createdataset.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/createdataset.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/createdataset.C	(revision 17960)
@@ -0,0 +1,237 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Daniela Dorner, 06/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// createdataset.C
+// ===============
+//
+// this script is not run automatically
+// the purpose of this script is to make it easier for people to write
+// datasetfiles
+//
+// be careful with the path in this macro, if you use it for test-reasons!
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TEnv.h>
+
+#include <MSQLServer.h>
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+#include <TSystem.h>
+
+using namespace std;
+
+
+
+int createdataset(Int_t dataset, TString source, TString wobble,
+                  Bool_t cal=kFALSE,
+                  TString startdate="0000-00-00 00:00:00",
+                  TString stopdate="3000-00-00 00:00:00",
+                  TString off="none",
+                  TString offstartdate="0000-00-00 00:00:00",
+                  TString offstopdate="3000-00-00 00:00:00")
+{
+    TEnv env("sql.rc");
+
+    MSQLServer serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+    cout << "createdataset" << endl;
+    cout << "-------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    TString fname(Form("/magic/datasets/%05d/dataset%08d.txt", dataset/1000, dataset));
+    TString fhtml="/home/operator/html";
+    Bool_t exist=gSystem->AccessPathName(fname,kFileExists);
+    if (exist==0)
+    {
+        cout << fname << " already exists, please choose different dataset#" << endl;
+        return 0;
+    }
+
+    ofstream fouthtml(fhtml, ios::app);
+    fouthtml << "<tr><td>" << endl;
+    fouthtml << dataset << endl;
+    fouthtml << "</td><td>" << endl;
+    fouthtml << source << endl;
+    fouthtml << "</td><td>" << endl;
+    if (wobble!="N")
+        fouthtml << "wobble," << endl;
+    if (startdate=="0000-00-00 00:00:00")
+        fouthtml << "all" << endl;
+    else
+        fouthtml << "from " << startdate << " to " << stopdate << endl;
+    if (cal)
+        fouthtml << ", only data processed to the imgpar is taken into account" << endl;
+    fouthtml << "</td></tr>" << endl;
+
+    ofstream fout(fname, ios::app);
+    cout << "writing to file " << fname << endl;
+    fout << "AnalysisNumber: " << dataset << endl << endl;
+
+    TString query="Select Sequences.fSequenceFirst from Sequences left join Source on ";
+    query +="Sequences.fSourceKEY=Source.fSourceKEY ";
+    if (cal)
+        query +=" left join SequenceProcessStatus on Sequences.fSequenceFirst=SequenceProcessStatus.fSequenceFirst ";
+    if (wobble=="N")
+        query +=Form(" where fSourceName like '%s%%' and fRunStart between '%s' and '%s'",
+                     source.Data(), startdate.Data(), stopdate.Data());
+    else
+        query +=Form(" where fSourceName like '%s%%' and fRunStart between '%s' and '%s'",
+                     wobble.Data(), startdate.Data(), stopdate.Data());
+    if (cal)
+        query +=" and not IsNull(fStar) ";
+    query +=" order by Sequences.fSequenceFirst ";
+
+    cout << "Q: " << query << endl;
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "Error - no sequence found" << endl;
+        return 0;
+    }
+
+    fout << "SequencesOn: " << flush;
+    TSQLRow *row=0;
+    while ((row = res->Next()))
+        fout << " " << (*row)[0] <<  " " << flush;
+    fout << endl << endl;
+
+    delete res;
+
+    if (wobble=="N")
+    {
+        if (off=="none")
+        {
+            off  ="Off";
+            off +=source;
+            off.Remove(10,15);
+        }
+
+        cout << "off: " << off << endl;
+        query  ="Select Sequences.fSequenceFirst from Sequences left join Source on ";
+        query +="Sequences.fSourceKEY=Source.fSourceKEY ";
+        if (cal)
+            query +=" left join SequenceProcessStatus on Sequences.fSequenceFirst=SequenceProcessStatus.fSequenceFirst ";
+        query +=Form("where fSourceName like '%s%%' and fRunStart between '%s' and '%s'",
+                     off.Data(), offstartdate.Data(), offstopdate.Data());
+        if (cal)
+            query +=" and not IsNull(fStar) ";
+        query +=" order by Sequences.fSequenceFirst ";
+
+        cout << "Q: " << query << endl;
+
+        res = serv.Query(query);
+        if (!res)
+        {
+            cout << "Error - no sequence found" << endl;
+            return 0;
+        }
+
+        fout << "SequencesOff: " << flush;
+        row=0;
+        while ((row = res->Next()))
+            fout << " " << (*row)[0] <<  " " << flush;
+        fout << endl << endl;
+
+        delete res;
+    }
+
+    if (wobble=="N")
+        fout << "#" << flush;
+    fout << "SourceName: " << source << endl;
+    fout << "Catalog: /magic/datacenter/setup/magic_favorites.edb" << endl;
+    if (wobble=="N")
+        fout << "#" << flush;
+    fout << "WobbleMode: On" << endl << endl;
+
+
+    return 1;
+}
+
+int createdataset(TString filename)
+{
+    ifstream fin(filename);
+    if (!fin)
+    {
+        cout << "Could not open file " << filename << endl;
+        return 0;
+    }
+    cout << "reading file " << filename << endl;
+
+    while (1)
+    {
+        TString strng;
+        strng.ReadToDelim(fin, ',');
+        if (!fin)
+            break;
+
+        if (strng.BeginsWith("#"))
+        {
+            cout << "comment line: " << strng << endl;
+            strng.ReadToDelim(fin, '\n');
+            continue;
+        }
+
+        Int_t dataset=atoi(strng.Data());
+        if (dataset==0)
+            continue;
+        cout << "creating dataset # " << dataset << endl;
+
+        TString source;
+        source.ReadToDelim(fin, ',');
+        TString wobble;
+        wobble.ReadToDelim(fin, ',');
+        strng.ReadToDelim(fin, ',');
+        Bool_t cal=kFALSE;
+        if (strng=="kTRUE")
+            cal=kTRUE;
+        TString startdate;
+        startdate.ReadToDelim(fin, ',');
+        TString stopdate;
+        stopdate.ReadToDelim(fin, ',');
+        TString off;
+        off.ReadToDelim(fin, ',');
+        TString offstartdate;
+        offstartdate.ReadToDelim(fin, ',');
+        TString offstopdate;
+        offstopdate.ReadToDelim(fin, '\n');
+
+        cout << createdataset(dataset, source, wobble, cal, startdate, stopdate, off, offstartdate, offstopdate) << endl;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/doexclusions.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/doexclusions.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/doexclusions.C	(revision 17960)
@@ -0,0 +1,207 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// doexclusions.C
+// ==============
+//
+// this macro sets the ExcludedFDA flag for runs, that can be excluded
+// automatically
+// the information which runs have to be excluded is retrieved from the
+// resource file automatic-exclusions.rc
+//
+// the macro can be executed either for a night or for a range of runnumbers
+// or for all nights
+// .x doexclusions.C+("night", telnum)
+// .x doexclusions.C+(startrun,stoprun, telnum)
+// .x doexclusions.C+
+//
+// resource file: automatic-exclustions.rc
+// for each exclusion-reason there is one block of 6 lines in this file:
+// example for one exclusion-reason:
+//  #NumEventsSmaller10:                   (name of exclusion)
+//  key15.Column: fNumEvents               (name of the affected column)
+//  #key15.Join1:                          (name of column that has to 
+//  #key15.Join2:                                             be joined)
+//  key15.Cond: fNumEvents between 2 and 9 (condition that fulfils exclusion)
+//  #key15.SpecialRunCond:                 (special condition, if exclusion
+//                                          is needed only for certain runs)
+// if a value is not needed for an exclusion (like the joins and the special
+// condition in this example), the line is commented out
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TEnv.h>
+#include <TSystem.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+//get minimum or maximum runnumber of the runs of a night
+int GetRunNumber(MSQLServer &serv, Int_t tel, TString date, TString cmd)
+{
+    TString query;
+    query  = Form("SELECT %s(fRunNumber) FROM RunData ", cmd.Data());
+    query += Form("WHERE fTelescopeNumber=%d", tel);
+
+    if (date!="NULL")
+    {
+        TString day=date+" 13:00:00";
+        query += Form(" AND (fRunStart>ADDDATE(\"%s\", INTERVAL -1 DAY) AND fRunStart<\"%s\")",
+                      day.Data(), day.Data());
+    }
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Could not get " << cmd << " fRunNumber." << endl;
+        return -1;
+    }
+
+    TSQLRow *row =res->Next();
+    if (TString((*row)[0]).IsNull())
+    {
+        cout << "No run available for " << date << endl;
+        delete res;
+        return 0;
+    }
+    delete res;
+
+    return atoi((*row)[0]);
+}
+
+int doexclusions(Int_t startrun, Int_t stoprun, Int_t tel=1, TString date="NULL", Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    // Open rc files with exclusions
+    TEnv rc("resources/exclusions.rc");
+
+    // Some information for the user
+    cout << "doexclusions" << endl;
+    cout << "------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Date:      " << date << endl;
+    cout << "Telescope: " << tel << endl;
+
+    serv.SetIsDummy(dummy);
+
+    // if neither start- nor stoprun is given, the minimum and maximum
+    // runnumber is queried from the database to do the exclusions for
+    // all runs if a night is given for all runs of this night
+    if (startrun==0 && stoprun==0)
+    {
+        startrun = GetRunNumber(serv, tel, date, "MIN");
+        stoprun  = GetRunNumber(serv, tel, date, "MAX");
+    }
+
+    cout << "Start Run: " << startrun << endl;
+    cout << "Stop  Run: " << stoprun  << endl;
+
+    //check format of start- and stoprun
+    if (startrun<0 || stoprun<0)
+    {
+        cout << "ERROR - Startrun<0 or stoprun<0." << endl;
+        return 2;
+    }
+
+    //if no run for date is available, GetRunNumber() returns 0
+    if (startrun==0 || stoprun==0)
+        return 1;
+
+    // Get exclusions-reasons (stored in the table ExcludedFDA) from the DB
+    TSQLResult *res = serv.Query("SELECT fExcludedFDAKEY, fExcludedFDAName "
+                                 "FROM ExcludedFDA "
+                                 "ORDER BY fExcludedFDAImportance ASC");
+    if (!res)
+        return 2;
+
+    //update the exclusion-reasons for all runs
+    TSQLRow *row=0;
+    while ((row = res->Next()))
+    {
+        // check the key (NULL means "No exclusion")
+        const TString key = (*row)[0];
+        if (key.IsNull())
+            continue;
+
+        // Get the corresponding condition from the file
+        const TString cond = rc.GetValue("key"+key, "");
+        if (cond.IsNull())
+            continue;
+
+        // Get all files to be excluded
+        TString query2 = "SELECT fRunNumber, fFileNumber FROM RunData ";
+        query2 += serv.GetJoins("RunData", query2+cond);
+
+        query2 += Form("WHERE (%s) ", cond.Data());
+        query2 += Form("AND fRunNumber BETWEEN %d AND %d ", startrun, stoprun);
+        query2 += Form("AND fTelescopeNumber=%d", tel);
+
+        TSQLResult *res2 = serv.Query(query2);
+        if (!res2)
+            return 2;
+
+        // Update exlcusion for file
+        TSQLRow *row2=0;
+        while ((row2 = res2->Next()))
+        {
+            TString vars(Form("fExcludedFDAKEY=%s", key.Data()));
+            TString where(Form("fRunNumber=%s AND fFileNumber=%s AND fTelescopeNumber=%d", (*row2)[0], (*row2)[1], tel));
+
+            if (serv.Update("RunData", vars, where)==kFALSE)
+                return 2;
+
+            cout << "File M" << tel << ":" << (*row2)[0] << "/" << setw(3) << setfill('0') << (*row2)[1] << " excluded due to: " << (*row)[1] << "." << endl;
+        }
+
+        delete res2;
+    }
+    delete res;
+
+    return 1;
+}
+
+//run doexclusions for one night
+int doexclusions(TString date="NULL", Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    return doexclusions(0, 0, tel, date, dummy);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillcalib.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillcalib.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillcalib.C	(revision 17960)
@@ -0,0 +1,332 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillcalib.C
+// ===========
+//
+// This macro is used to read the calibartion-/callisto-output files.
+// These files are automatically called calib00000.root.
+//
+// From this file the MBadPixelsCam and the MGeomCam is extracted. If
+// the geometry isn't found MGeomCamMagic is used as a default.
+// The bad pixel information and other information, extracted from the status
+// display, is inserted into the database in the table Calibration, which
+// stores the results from the calibration.
+// The corresponding sequence number is extracted from the filename...
+// FIXME: MSeqeuence should be stored in the calib-file?
+//
+// Usage:
+//  .x fillcalib.C("/magic/data/callisto/0004/00047421/calib00047421.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillcalib.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillcalib.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+
+#include <TH1.h>
+
+#include <TFile.h>
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+
+#include "MSQLMagic.h"
+
+#include "MStatusArray.h"
+#include "MHCamera.h"
+#include "MSequence.h"
+#include "MGeomCamMagic.h"
+#include "MBadPixelsCam.h"
+
+using namespace std;
+
+int Process(MSQLMagic &serv, TString fname)
+{
+    //getting number of unsuitable, unreliable and isolated pixel
+    MBadPixelsCam badpix;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+    if (badpix.Read("MBadPixelsCam")<=0)
+    {
+        cout << "ERROR - Reading of MBadPixelsCam failed." << endl;
+        return 2;
+    }
+
+    MGeomCamMagic def;
+
+    MGeomCam *geom = (MGeomCam*)file.Get("MGeomCam");
+    if (!geom)
+    {
+        cout << "WARNING - Reading of MGeomCam failed... using default <MGeomCamMagic>" << endl;
+        geom = &def;
+    }
+
+    cout << "Camera Geometry: " << geom->ClassName() << endl;
+
+    const Short_t unsin  = badpix.GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, geom, 0);
+    const Short_t unsout = badpix.GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, geom, 1);
+
+    const Short_t unrin  = badpix.GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, geom, 0);
+    const Short_t unrout = badpix.GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, geom, 1);
+
+    const Short_t isoin  = badpix.GetNumIsolated(*geom, 0);
+    const Short_t isoout = badpix.GetNumIsolated(*geom, 1);
+
+    const Short_t clumax = badpix.GetNumMaxCluster(*geom);
+
+    if (unsin<0 || unsout<0 || unrin<0 || unrout<0 || isoin<0 || isoout<0 || clumax<0)
+    {
+        cout << "ERROR - one of the pixel values < 0." << endl;
+        return 2;
+    }
+
+    //     MHCamera hist(geom);
+    //     hist.SetCamContent(badpix, 1);
+    //     hist.DrawCopy();
+    //     hist.SetCamContent(badpix, 3);
+    //     hist.DrawCopy();
+
+    //Getting values from the status display
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        cout << "ERROR - could not read MStatusArray." << endl;
+        return 2;
+    }
+
+    TH1 *h;
+
+    //getting the mean and rms from the arrival time (inner cam)
+    h = (TH1*)arr.FindObjectInCanvas("HRelTimeHiGainArea0", "TH1F", "Time");
+    if (!h)
+    {
+        cout << "ERROR - Could not find histogram HRelTimeHiGainArea0 in Time." << endl;
+        return 2;
+    }
+
+    TString meaninner = Form("%5.1f", h->GetMean());
+    TString rmsinner  = Form("%6.2f", h->GetRMS());
+
+    //getting the mean and rms from the arrival time (outer cam)
+    h = (TH1*)arr.FindObjectInCanvas("HRelTimeHiGainArea1", "TH1F", "Time");
+    if (!h)
+    {
+        cout << "ERROR - Could not find histogram HRelTimeHiGainArea1 in Time." << endl;
+        return 2;
+    }
+
+    TString meanouter = Form("%5.1f", h->GetMean());
+    TString rmsouter  = Form("%6.2f", h->GetRMS());
+
+    //Getting conversion factors
+    MHCamera *c = (MHCamera*)arr.FindObjectInCanvas("TotalConvPhe", "MHCamera", "Conversion");
+    if (!c)
+    {
+        cout << "ERROR - Could not find MHCamera TotalConv in Conversion." << endl;
+        return 2;
+    }
+
+    TArrayI inner(1), outer(1);
+    inner[0] = 0;
+    outer[0] = 1;
+
+    Int_t s0[] = { 1, 2, 3, 4, 5, 6 };
+
+    Stat_t meanconvi = c->GetMeanSectors(TArrayI(6, s0), inner);
+    Stat_t meanconvo = c->GetMeanSectors(TArrayI(6, s0), outer);
+    TString meanconvinner=Form("%6.3f", meanconvi);
+    TString meanconvouter=Form("%6.3f", meanconvo);
+
+    //Getting relative charge rms
+    c = (MHCamera*)arr.FindObjectInCanvas("RMSperMean", "MHCamera", "FitCharge");
+    if (!c)
+    {
+        cout << "ERROR - Could not find MHCamera RMSperMean in FitCharge." << endl;
+        return 2;
+    }
+
+    Stat_t relrmsi = c->GetMedianSectors(TArrayI(6, s0), inner);
+    Stat_t relrmso = c->GetMedianSectors(TArrayI(6, s0), outer);
+    TString relrmsinner=Form("%6.3f", relrmsi);
+    TString relrmsouter=Form("%6.3f", relrmso);
+
+    //Getting relative charge rms
+    c = (MHCamera*)arr.FindObjectInCanvas("NumPhes", "MHCamera", "FitCharge");
+    if (!c)
+    {
+        cout << "ERROR - Could not find MHCamera NumPhes in FitCharge." << endl;
+        return 2;
+    }
+
+    Stat_t numphei = c->GetMedianSectors(TArrayI(6, s0), inner);
+    Stat_t numpheo = c->GetMedianSectors(TArrayI(6, s0), outer);
+    TString numpheinner=Form("%5.1f", numphei);
+    TString numpheouter=Form("%5.1f", numpheo);
+
+    MSequence seq;
+    if (seq.Read("sequence[0-9]{8}[.]txt|MSequence")<=0)
+    {
+        cout << "ERROR - Could not find sequence in file: " << fname << endl;
+        return 2;
+    }
+    if (!seq.IsValid())
+    {
+        cout << "ERROR - Sequence read from file inavlid: " << fname << endl;
+        return 2;
+    }
+
+    //getting the ratio of calibration events used
+    h = (TH1*)arr.FindObjectInCanvas("ArrTm;avg", "MHCamera", "ArrTm");
+    if (!h)
+    {
+        cout << "ERROR - Could not find histogram ArrTime;avg." << endl;
+        return 2;
+    }
+
+    UInt_t nevts = TMath::Nint(h->GetEntries());
+
+    TString query;
+    query = Form("SELECT SUM(fNumEvents) FROM RunData "
+                 "LEFT JOIN RunType USING (fRunTypeKEY) "
+                 "WHERE fSequenceFirst=%d AND fTelescopeNumber=%d AND "
+                 "RunType.fRunTypeName='Calibration'",
+                 seq.GetSequence(), seq.GetTelescope());
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+
+    TSQLRow *row = res->Next();
+    if (!row)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+
+    Float_t ratiocalib = 100.*nevts/atof((*row)[0]);
+
+    TString ratiocal = Form("%.1f", ratiocalib);
+
+    delete res;
+
+    cout << "Sequence M" << seq.GetTelescope() << ":" << seq.GetSequence() << endl;
+    cout << "  Unsuitable: (i/o)  " << Form("%3d %3d", (int)unsin, (int)unsout) << endl; // Unbrauchbar
+    cout << "  Unreliable: (i/o)  " << Form("%3d %3d", (int)unrin, (int)unrout) << endl; // Unzuverlaessig
+    cout << "  Isolated:   (i/o)  " << Form("%3d %3d", (int)isoin, (int)isoout) << endl; // Isolated (unbrauchbar)
+    cout << "  Max.Cluster:       " << Form("%3d", (int)clumax)                 << endl; // Max Cluster
+    cout << "  Arr Time inner:     " << meaninner << " +- " << rmsinner  << endl;
+    cout << "  Arr Time outer:     " << meanouter << " +- " << rmsouter  << endl;
+    cout << "  Mean Conv inner:     " << meanconvinner << endl;
+    cout << "  Mean Conv outer:     " << meanconvouter << endl;
+    cout << "  Rel.charge rms in:   " << relrmsinner << endl;
+    cout << "  Rel.charge rms out:  " << relrmsouter << endl;
+    cout << "  Med. num phe inner: " << numpheinner << endl;
+    cout << "  Med. num phe outer: " << numpheouter << endl;
+    cout << "  Ratio Calib Evts:   " << ratiocal << endl;
+
+    // FIXME: Fill calibration charge
+
+    //inserting or updating the information in the database
+    TString vars =
+        Form(" fSequenceFirst=%d, "
+             " fTelescopeNumber=%d, "
+             " fUnsuitableInner=%d, "
+             " fUnsuitableOuter=%d, "
+             " fUnreliableInner=%d, "
+             " fUnreliableOuter=%d, "
+             " fIsolatedInner=%d, "
+             " fIsolatedOuter=%d, "
+             " fIsolatedMaxCluster=%d, "
+             " fArrTimeMeanInner=%s, "
+             " fArrTimeRmsInner=%s, "
+             " fArrTimeMeanOuter=%s, "
+             " fArrTimeRmsOuter=%s, "
+             " fConvFactorInner=%s, "
+             " fConvFactorOuter=%s, "
+             " fRatioCalEvents=%s, "
+             " fRelChargeRmsInner=%s, "
+             " fRelChargeRmsOuter=%s, "
+             " fMedNumPheInner=%s, "
+             " fMedNumPheOuter=%s ",
+             seq.GetSequence(), seq.GetTelescope(),
+             (int)unsin, (int)unsout, (int)unrin,
+             (int)unrout, (int)isoin, (int)isoout, (int)clumax,
+             meaninner.Data(), rmsinner.Data(),
+             meanouter.Data(), rmsouter.Data(),
+             meanconvinner.Data(), meanconvouter.Data(),
+             ratiocal.Data(),
+             relrmsinner.Data(), relrmsouter.Data(),
+             numpheinner.Data(), numpheouter.Data()
+            );
+
+    TString where = Form("fSequenceFirst=%d AND fTelescopeNumber=%d",
+                         seq.GetSequence(), seq.GetTelescope());
+
+    return serv.InsertUpdate("Calibration", vars, where) ? 1 : 2;
+}
+
+int fillcalib(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillcalib" << endl;
+    cout << "---------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    return Process(serv, fname);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillcamera.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillcamera.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillcamera.C	(revision 17960)
@@ -0,0 +1,954 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 11/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!   Author(s): Daniel Hoehne, 06/2008 <mailto:hoehne@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillcamera.C
+// ============
+//
+// This macro is used to read the camera-output files and fill the values
+// into the MC database.
+// You have to specify the path where to search for the camera files.
+// As default the dummy mode is kTRUE, so nothing will be filled but only
+// the mysql orders are printed. To really fill the db, set dummy to kFALSE.
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+// In order not to confuse the MC processing with the data processing,
+// both branches will be processed in two different Mars directories,
+// e.g. Mars-2.0 for data and Mars.MC for MCs.
+//
+// Returns 2 in case of failure and 1 in case of success.
+// Returns 0 in case of no connection to the db.
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+#include <TObjectTable.h>
+
+#include <TFile.h>
+#include <TTree.h>
+#include <TBranch.h>
+
+//#include <TH1.h>
+
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+#include <TSystem.h>
+
+#include "MSQLServer.h"
+#include "MSQLMagic.h"
+
+#include "MMcRunHeader.hxx"
+#include "MMcConfigRunHeader.h"
+#include "MMcCorsikaRunHeader.h"
+#include "MMcFadcHeader.hxx"
+#include "MMcEvtBasic.h"
+#include "MRawRunHeader.h"
+//#include "MRawEvtData.h"
+#include <MDirIter.h>
+
+#include <math.h>
+
+using namespace std;
+
+int Process(MSQLMagic &serv, TString fname, Bool_t dummy)
+{
+    //
+    // Read file
+    //
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+    //
+    // Get tree RunHeaders from file
+    //
+    TTree *tree = dynamic_cast<TTree*>(file.Get("RunHeaders"));
+    if (!tree)
+    {
+        cout << "ERROR - Tree RunHeaders not found in file " << fname << endl;
+        return 2;
+    }
+
+    //
+    // Get branch MMcCorsikaRunHeader from tree RunHeaders
+    //
+/*    TBranch *b1 = tree->GetBranch("MMcCorsikaRunHeader.");
+    if (!b1)
+    {
+        cout << "ERROR - Branch MMcCorsikaRunHeader. not found in file " << fname << endl;
+        return 2;
+    }
+    MMcCorsikaRunHeader *runheader1 = 0;
+    b1->SetAddress(&runheader1);
+*/
+    MMcCorsikaRunHeader *runheader1 = 0;
+    tree->SetBranchAddress("MMcCorsikaRunHeader.", &runheader1);
+
+    //
+    // Get branch MMcConfigRunHeader from tree RunHeaders
+    //
+    MMcConfigRunHeader *runheader2 = 0;
+    tree->SetBranchAddress("MMcConfigRunHeader.", &runheader2);
+
+    //
+    // Get branch MMcRunHeader from tree RunHeaders
+    //
+    MMcRunHeader *runheader3 = 0;
+    tree->SetBranchAddress("MMcRunHeader.", &runheader3);
+
+    //
+    // Get branch MMcFadcRunHeader from tree RunHeaders
+    //
+    MMcFadcHeader *fadcheader = 0;
+    tree->SetBranchAddress("MMcFadcHeader.", &fadcheader);
+
+    //
+    // Get branch MRawRunHearder from tree RunHeaders
+    //
+    MRawRunHeader *rawheader = 0;
+    tree->SetBranchAddress("MRawRunHeader.", &rawheader);
+
+    if (tree->GetEntry(0)<0)
+    {
+        cout << "ERROR - No entry found in tree RunHeaders of file: " << fname << endl;
+        return 2;
+    }
+
+    //
+    // Get tree Events from file
+    //
+    TTree *tree2 = dynamic_cast<TTree*>(file.Get("Events"));
+    if (!tree2)
+    {
+        cout << "ERROR - Tree Events not found in file " << fname << endl;
+        return 2;
+    }
+
+    //
+    // Get branch MMcEvtBasic from tree Events
+    //
+    MMcEvtBasic *evtbasic = 0;
+    tree2->SetBranchAddress("MMcEvtBasic.", &evtbasic);
+
+    if (tree2->GetEntry(0)<0)
+    {
+        cout << "ERROR - No entry found in tree Events of file: " << fname << endl;
+        return 2;
+    }
+
+
+    // Definition of values
+    Double_t misptx       = runheader2->GetMissPointingX();
+    Double_t mispty       = runheader2->GetMissPointingY();
+    Double_t point        = runheader2->GetPointSpread();
+    Double_t pointspreadx = runheader2->GetPointSpreadX();
+    Double_t addspotsize;
+    if (pointspreadx < 0.25)
+    {
+        addspotsize = 0;
+    }
+    else
+    {
+        addspotsize = TMath::Sqrt(pointspreadx*pointspreadx - 0.25);
+    }
+    Double_t realpsf      = TMath::Sqrt(pointspreadx*pointspreadx + 0.25);
+    Double_t pointspready = runheader2->GetPointSpreadY();
+    Double_t coneai       = runheader1->GetViewconeAngleInner();
+    Double_t coneao       = runheader1->GetViewconeAngleOuter();
+    Double_t spectrum     = runheader1->GetSlopeSpec();
+    Double_t tmin         = runheader3->GetShowerThetaMin();
+    Double_t tmax         = runheader3->GetShowerThetaMax();
+    UInt_t   corsvers     = runheader3->GetCorsikaVersion();
+    UInt_t   reflvers     = runheader3->GetReflVersion();
+    UInt_t   camvers      = runheader3->GetCamVersion();
+    UInt_t   numsimshow   = runheader3->GetNumSimulatedShowers();
+    UInt_t   numevents    = tree2->GetEntries();
+
+    // some calculations: round the given values
+    pointspreadx = TMath::Floor(pointspreadx*100+0.5)/100;
+    addspotsize  = TMath::Floor(addspotsize*100+0.5)/100;
+    realpsf      = TMath::Floor(realpsf*100+0.5)/100;
+    pointspready = TMath::Floor(pointspready*100+0.5)/100;
+    point        = TMath::Floor(point*10+0.5)/10;
+    coneai       = TMath::Floor(coneai*10+0.5)/10;
+    coneao       = TMath::Floor(coneao*10+0.5)/10;
+    spectrum     = TMath::Floor(spectrum*10+0.5)/10;
+
+    // Definition of strings
+    TString numslices = Form("%5.0i", rawheader->GetNumSamplesHiGain());
+    TString elow      = Form("%5.1f", runheader1->GetELowLim());
+    TString eupp      = Form("%5.1f", runheader1->GetEUppLim());
+    TString slope     = Form("%5.1f", spectrum);
+    TString wobble    = Form("%5.0f", runheader1->GetWobbleMode());
+    TString corsika1  = Form("%5.0f", runheader1->GetCorsikaVersion());
+    TString coneanglei = Form("%5.1f", coneai);
+    TString coneangleo = Form("%5.1f", coneao);
+    TString atmomodel = Form("%5.1f", runheader1->GetAtmosphericModel());
+    TString psf       = Form("%5.1f", point);
+    TString psfx      = Form("%5.2f", pointspreadx);
+    TString addspot   = Form("%5.2f", addspotsize);
+    TString rpsf      = Form("%5.2f", realpsf);
+    TString psfy      = Form("%5.2f", pointspready);
+    TString psfadd    = Form("%5.2f", TMath::Hypot(runheader2->GetPointSpreadX(), runheader2->GetPointSpread()));
+    Int_t mirr = runheader2->GetMirrorFraction();
+    TString mirrfrac  = Form("%5.2f", runheader2->GetMirrorFraction());
+    if (mirr < 0 )
+        mirrfrac = "NULL";
+    TString misx      = Form("%5.2f", misptx);
+    TString misy      = Form("%5.2f", mispty);
+    TString reflector = Form("%5.0i", reflvers);
+    TString camera    = Form("%5.0i", camvers);
+    Int_t impact = runheader3->GetImpactMax();
+    TString imax      = Form("%5.1f", runheader3->GetImpactMax());
+    if (impact < 0)
+        imax = "NULL";
+    TString numphe    = Form("%7.3f", runheader3->GetNumPheFromDNSB());
+    TString pmin      = Form("%5.2f", runheader3->GetShowerPhiMin());
+    TString pmax      = Form("%5.2f", runheader3->GetShowerPhiMax());
+    TString numss     = Form("%7.0i", numsimshow);
+    TString thetamin  = Form("%5.2f", tmin);
+    TString thetamax  = Form("%5.2f", tmax);
+    TString ped       = Form("%5.1f", fadcheader->GetPedestal(1));
+    TString low2high  = Form("%5.1f", fadcheader->GetLow2HighGain());
+    TString amplfadc  = Form("%5.2f", fadcheader->GetAmplitud());
+    TString amplfadco = Form("%5.2f", fadcheader->GetAmplitudOuter());
+    TString enoise    = Form("%5.1f", fadcheader->GetElecNoise(1));
+    TString dnoise    = Form("%5.1f", fadcheader->GetDigitalNoise(1));
+    TString numevt    = Form("%7.0i", numevents);
+    TString partid    = Form("%5.0f", evtbasic->GetPartId());
+    TString partname  = evtbasic->GetParticleName();
+
+    // get the number of triggers
+    UInt_t ntrig = (UInt_t)tree2->Draw("Length$(MRawEvtData.fHiGainPixId.fN)", "MRawEvtData.fHiGainPixId.fN!=0", "goff");
+    if (ntrig<0)
+    {
+        cout << "ERROR - Evaluating triggered events in file: " << fname << endl;
+        return 2;
+    }
+    TString numtrig   = Form("%7.0i", ntrig);
+//    TH1I h("myhist", "", 1, -0.5, 0.5);
+//    tree2->Draw("MRawEvtData.GetNumPixels()>>myhist", "", "goff");
+//    h.SetDirectory(0);
+//    TString numtrig   = Form("%7.0i", TMath::Nint(h.GetBinContent(2)));
+
+    UInt_t nsumtrig = (UInt_t)tree2->Draw("Length$(MRawEvtHeader.fTrigPattern[0])","(MRawEvtHeader.fTrigPattern[0]==0xffffdfdf) || (MRawEvtHeader.fTrigPattern[0]==0xffffdede)","goff");
+    if (nsumtrig<0)
+    {
+        cout << "ERROR - Evaluating sumtrigger events in file: " << fname << endl;
+        return 2;
+    }
+    TString numsumtrig   = Form("%7.0i", nsumtrig);
+    if (nsumtrig==0)
+        numsumtrig = "0";
+
+    // Determine observation mode, fake wobble means On mode with mispointing
+    TString wobblemod="Wobble";
+    if (atoi(wobble)==0)
+        wobblemod = misptx == 0 && mispty == 0 ? "On" : "Fake Wobble";
+    if (atoi(coneangleo)>0)
+        wobblemod = "Diffuse";
+
+    //get the psf value for the path for linking
+    Float_t pointsfuncx = pointspreadx*10;
+    pointsfuncx         = TMath::Floor(pointsfuncx*10+0.5)/10;
+    Int_t pointsfx      = TMath::Nint(pointsfuncx);
+
+    Float_t aspotsize   = addspotsize*10;
+    aspotsize           = TMath::Floor(aspotsize*10+0.5)/10;
+    Int_t ass           = TMath::Nint(aspotsize);
+
+    Float_t realpointsf = realpsf*10;
+    realpointsf         = TMath::Floor(realpointsf*10+0.5)/10;
+    Int_t rpointsf = TMath::Nint(realpointsf);
+
+
+    // Get zbin
+    Float_t zBin=TMath::Nint((1-((TMath::Cos(tmin*TMath::Pi()/180)+TMath::Cos(tmax*TMath::Pi()/180))/2))*100);
+    Float_t zBinmin=TMath::Nint((1-(TMath::Cos(tmin*TMath::Pi()/180)))*100);
+    Float_t zBinmax=TMath::Nint((1-(TMath::Cos(tmax*TMath::Pi()/180)))*100);
+    Int_t zBin2=TMath::Nint(zBin);
+    Int_t zBin2Min=TMath::Nint(zBinmin);
+    Int_t zBin2Max=TMath::Nint(zBinmax);
+
+    // Definition of keys
+    Int_t corsikakey;
+    Int_t reflectorkey;
+    Int_t camerakey;
+    Int_t observationkey;
+    Int_t particlekey;
+    Int_t atmomodelkey;
+    Int_t amplfadckey;
+    Int_t psfkey;
+    Int_t spotsizekey;
+    Int_t viewconeangleokey;
+    Int_t spectrumkey;
+    Int_t triggerkey;
+
+    // Definition of variables to be filled in the db
+    TString vars;
+
+    // Separation of ped/cal and data runs by checking the value pointspread
+    // ped/cal runs
+    if(point==-1)
+    {
+        cout << endl;
+        cout << "psf value: " << point << " -> MC P or C run." << endl;
+        cout << endl;
+        cout << "--- From File ---" << endl;
+        cout << endl;
+        cout << "Energy Range    " << elow << " < E < " << eupp      << endl;
+        cout << "SpectralIndex   " << slope     << endl;
+        cout << "CorsikaVer      " << corsika1  << endl;
+        cout << "ParticleId      " << partid    << endl;
+        cout << "ParticleName    "  << partname  << endl;
+        cout << "PointSpread     " << psf       << endl;
+        cout << "NumSimShowers   " << numsimshow << endl;
+        cout << "ImpactMax       " << imax      << endl;
+        cout << "NumEvents       " << numevt    << endl;
+        cout << "NumTriggers     " << numtrig   << endl;
+        cout << "NumSumTriggers  " << numsumtrig   << endl;
+        cout << "NumPheFromDNSB  " << numphe    << endl;
+        cout << "ViewconeAngleInner  " << coneanglei << endl;
+        cout << "ViewconeAngleOuter  " << coneangleo << endl;
+        cout << "AtmosphericModel " << atmomodel << endl;
+        cout << "Pedestal        " << ped       << endl;
+        cout << "Low2HighGain    " << low2high  << endl;
+        cout << "AmplitudeFADC   " << amplfadc  << endl;
+        cout << "AmplFADCOuter   " << amplfadco << endl;
+        cout << "ElecNoise       " << enoise    << endl;
+        cout << "DigiNoise       " << dnoise    << endl;
+        cout << "Num HiGainSlices " << numslices << endl;
+        cout << "PhiMin          " << pmin      << endl;
+        cout << "PhiMax          " << pmax      << endl;
+        cout << "ThetaMin        " << thetamin  << endl;
+        cout << "ThetaMax        " << thetamax  << endl;
+        cout << "Zenith range    " << tmin << " to " << tmax << endl;
+        cout << "MirrorFraction  " << mirrfrac << endl;
+        cout << endl;
+        cout << endl;
+        cout << "P/C run: there will be fixed values inserted into the db for the following parameters:" << endl;
+        cout << "ObservationMode " << wobblemod   << " -> " << "n/a" <<endl;
+        cout << "ReflVer         " << reflvers    << " -> " << "n/a" <<endl;
+        cout << "CamVer          " << camvers     << " -> " << "n/a" <<endl;
+        cout << "PointSpreadX    " << psfx        << " -> " << "0" <<endl;
+        cout << "Add. SpotSize   " << addspot     << " -> " << "0" <<endl;
+        cout << "Real PSF        " << rpsf        << " -> " << "0" <<endl;
+        cout << "PointSpreadY    " << psfy        << " -> " << "0" <<endl;
+        cout << "MispointingX    " << misx        << " -> " << "0" <<endl;
+        cout << "MispointingY    " << misy        << " -> " << "0" <<endl;
+        cout << endl;
+        cout << "--- key's from mcdb tables ---" << endl;
+        cout << endl;
+
+        corsikakey     = 1;
+        reflectorkey   = 1;
+        camerakey      = 1;
+        observationkey = 1;
+        particlekey    = 1;
+        atmomodelkey   = serv.QueryKeyOfName("AtmosphericModel", atmomodel.Data());
+        amplfadckey    = serv.QueryKeyOfName("AmplFadc", amplfadc.Data());
+        viewconeangleokey = serv.QueryKeyOfName("ViewconeAngleO", coneangleo.Data());
+        spectrumkey    = 1;
+        triggerkey = nsumtrig == 0 ? 2 : 3;
+        psfkey         = 1;
+        spotsizekey    = 1;
+
+        if (corsvers==0)
+        {
+            cout << "CorsikaVersion not available" << endl;
+        }
+        else
+        {
+            corsikakey = serv.QueryKeyOfName("CorsikaVersion", corsika1.Data());
+        }
+        if (reflvers==0)
+        {
+            cout << "ReflectorVersion not available" << endl;
+        }
+        else
+        {
+            reflectorkey = serv.QueryKeyOfName("ReflectorVersion", reflector.Data());
+        }
+        if (camvers==0)
+        {
+            cout << "CameraVersion not available" << endl;
+        }
+        else
+        {
+            camerakey = serv.QueryKeyOfName("CameraVersion", camera.Data());
+        }
+
+        cout << "corsikakey:     " << corsikakey << endl;
+        cout << "reflectorkey:   " << reflectorkey << endl;
+        cout << "camerakey:      " << camerakey << endl;
+        cout << "observationkey: " << observationkey << endl;
+        cout << "particlekey:    " << particlekey << endl;
+        cout << "atmomodelkey:   " << atmomodelkey << endl;
+        cout << "amplfadckey:    " << amplfadckey << endl;
+        cout << "psfkey:         " << psfkey << endl;
+        cout << "spotsizekey:    " << spotsizekey << endl;
+        cout << "coneangleokey:  " << viewconeangleokey << endl;
+        cout << "spectrumkey:    " << spectrumkey << endl;
+        cout << "triggerkey:     " << triggerkey << endl;
+        cout << endl;
+
+        // For ped/cal: fixed values for psf and mispointing
+        vars = Form("fPointSpreadX=0, fAdditionalSpotSize=0, fRealPointSpread=0, fPointSpreadY=0, fMissPointingX=0, fMissPointingY=0, ");
+
+    }
+    // Data runs
+    else
+    {
+
+        cout << endl;
+        cout << "psf value: " << point << " -> MC data run." << endl;
+        cout << endl;
+        cout << "--- From File ---" << endl;
+        cout << endl;
+        cout << "Energy Range    " << elow << " < E < " << eupp      << endl;
+        cout << "SpectralIndex   " << slope     << endl;
+        cout << "ObservationMode " << wobblemod << endl;
+        cout << "CorsikaVer      " << corsika1  << endl;
+        cout << "ReflVer         " << reflector << endl;
+        cout << "CamVer          " << camera    << endl;
+        cout << "ParticleId      " << partid    << endl;
+        cout << "ParticleName    " << partname  << endl;
+        cout << "PointSpread     " << psf       << endl;
+        cout << "PointSpreadX    " << pointspreadx << endl;
+        cout << "Add. SpotSize   " << addspot   << endl;
+        cout << "Real PSF        " << rpsf      << endl;
+        cout << "PointSpreadXY   " << psfx      << " /" << psfy << endl;
+//        cout << "AdditionPSF     " << psfadd << endl;
+        cout << "MispointingXY   " << misx << " /" << misy <<endl;
+        cout << "NumSimShowers   " << numss     << endl;
+        cout << "ImpactMax       " << imax      << endl;
+        cout << "NumEvents       " << numevt    << endl;
+        cout << "NumTriggers     " << numtrig   << endl;
+        cout << "NumSumTriggers  " << numsumtrig   << endl;
+        cout << "NumPheFromDNSB  " << numphe    << endl;
+        cout << "ViewconeAngleInner  " << coneanglei << endl;
+        cout << "ViewconeAngleOuter  " << coneangleo << endl;
+        cout << "AtmosphericModel " << atmomodel << endl;
+        cout << "Pedestal        " << ped       << endl;
+        cout << "Low2HighGain    " << low2high  << endl;
+        cout << "AmplitudeFADC   " << amplfadc  << endl;
+        cout << "AmplFADCOuter   " << amplfadco << endl;
+        cout << "ElecNoise       " << enoise    << endl;
+        cout << "DigiNoise       " << dnoise    << endl;
+        cout << "Num HiGainSlices " << numslices << endl;
+        cout << "PhiMin          " << pmin      << endl;
+        cout << "PhiMax          " << pmax      << endl;
+        cout << "ThetaMin        " << thetamin  << endl;
+        cout << "ThetaMax        " << thetamax  << endl;
+        cout << "Zenith range    " << tmin << " to " << tmax << endl;
+        cout << "MirrorFraction  " << mirrfrac << endl;
+        cout << endl;
+        cout << endl;
+        cout << "--- key's from mcdb tables ---" << endl;
+        cout << endl;
+
+        corsikakey     = 1;
+        reflectorkey   = 1;
+        camerakey      = 1;
+        observationkey = serv.QueryKeyOfName("ObservationMode", wobblemod.Data());
+        particlekey    = serv.QueryKeyOfName("MCParticle", partname.Data());
+        atmomodelkey   = serv.QueryKeyOfName("AtmosphericModel", atmomodel.Data());
+        amplfadckey    = serv.QueryKeyOfName("AmplFadc", amplfadc.Data());
+        viewconeangleokey = serv.QueryKeyOfName("ViewconeAngleO", coneangleo.Data());
+        psfkey         = serv.QueryKeyOfName("PSF", rpsf);
+        spotsizekey    = serv.QueryKeyOfName("AddSpotSize", addspot);
+        spectrumkey    = serv.QueryKeyOfName("Spectrum", slope);
+        triggerkey = nsumtrig == 0 ? 2 : 3;
+
+
+        if (corsvers==0)
+        {
+            cout << "CorsikaVersion not available" << endl;
+        }
+        else
+        {
+            corsikakey = serv.QueryKeyOfName("CorsikaVersion", corsika1.Data());
+        }
+        if (reflvers==0)
+        {
+            cout << "ReflectorVersion not available" << endl;
+        }
+        else
+        {
+            reflectorkey = serv.QueryKeyOfName("ReflectorVersion", reflector.Data());
+        }
+        if (camvers==0)
+        {
+            cout << "CameraVersion not available" << endl;
+        }
+        else
+        {
+            camerakey = serv.QueryKeyOfName("CameraVersion", camera.Data());
+        }
+
+        cout << "corsikakey:     " << corsikakey << endl;
+        cout << "reflectorkey:   " << reflectorkey << endl;
+        cout << "camerakey:      " << camerakey << endl;
+        cout << "observationkey: " << observationkey << endl;
+        cout << "particlekey:    " << particlekey << endl;
+        cout << "atmomodelkey:   " << atmomodelkey << endl;
+        cout << "amplfadckey:    " << amplfadckey << endl;
+        cout << "psfkey:         " << psfkey << endl;
+        cout << "spotsizekey:    " << spotsizekey << endl;
+        cout << "coneangleokey:  " << viewconeangleokey << endl;
+        cout << "spectrumkey:    " << spectrumkey << endl;
+        cout << "triggerkey:     " << triggerkey << endl;
+        cout << endl;
+
+        // For data runs the values are taken from the file
+        vars = Form("fPointSpreadX=%5.2f, fAdditionalSpotSize=%5.2f, fRealPointSpread=%5.2f, fPointSpreadY=%5.2f, fMissPointingX=%s, fMissPointingY=%s, ",
+                    pointspreadx, addspotsize, realpsf, pointspready, misx.Data(), misy.Data());
+
+    }
+
+    // Query maximum run number and add 1 to it, if no runnumber is found, start with 1
+    TString query(Form("SELECT IF (isnull(MAX(MCRunData.fRunNumber)+1),1,MAX(MCRunData.fRunNumber)+1) FROM MCRunData;"));
+    //        TString query(Form("SELECT MCRunData.fRunNumber, IF (isnull(MAX(MCRunData.fRunNumber)+1),1,MAX(MCRunData.fRunNumber)+1), "
+    //                           "fFileName FROM MCRunData LEFT JOIN "
+    //                           "MCRunProcessStatus ON MCRunData.fRunNumber=MCRunProcessStatus.fRunNumber "
+    //                           "where fFileName=\"%s\" group by MCRunData.fRunNumber;", fname.Data()));
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+
+    TSQLRow *row = 0;
+    row = res->Next();
+    if (!row)
+        return 2;
+    TString num=(*row)[0];
+    Int_t RunNum=atoi(num.Data());
+
+    delete res;
+//    delete row;
+    // Query run number and filename from MCRunProcessStatus
+    TString query2(Form("SELECT fRunNumber, fFileName from MCRunProcessStatus where fFileName=\"%s\"", fname.Data()));
+    res = serv.Query(query2);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query2 << endl;
+        return 2;
+    }
+
+    row = res->Next();
+    // If query gives no entry for the filename the file will be inserted into the db
+    if (!row)
+    {
+        cout << "No entry in query result: " << query2 << endl;
+        cout << "--------" << endl;
+        cout << "RunNum: " << RunNum << endl;
+        cout << "File: " << fname << endl;
+        cout << endl;
+
+        vars +=
+            Form("fELowLim=%s, fEUppLim=%s, fSlopeSpec=%5.2f, "
+                 "fImpactMax=%s, fNumSimulatedShowers=%d, fNumEvents=%d, "
+                 "fNumPheFromDNSB=%s, fZBin=%d, fZBinMin=%d, fZBinMax=%d, fThetaMin=%s, "
+                 "fThetaMax=%s, fPhiMin=%s, fPhiMax=%s, fPointSpread=%s, "
+                 "fPedesMean=%s, fLow2HighGain=%s, "
+                 "fAmplFadcInner=%s, fAmplFadcOuter=%s, ",
+                 elow.Data(), eupp.Data(), spectrum,
+                 imax.Data(), numsimshow, numevents,
+                 numphe.Data(), zBin2, zBin2Min, zBin2Max, thetamin.Data(),
+                 thetamax.Data(), pmin.Data(), pmax.Data(), psf.Data(),
+                 ped.Data(), low2high.Data(),
+                 amplfadc.Data(), amplfadco.Data());
+        vars +=
+            Form("fElectricNoise=%s, "
+                 "fDigitalNoise=%s, fRunNumber=%d, "
+                 "fNumSlices=%s, fCorsikaVersionKEY=%d, "
+                 "fReflectorVersionKEY=%d, fCameraVersionKEY=%d, "
+                 "fObservationModeKEY=%d, fMCParticleKEY=%d, "
+                 "fNumTriggers=%d, fNumSumTriggers=%d, fViewconeAngleInner=%5.2f, fViewconeAngleOuter=%5.2f, "
+                 "fAtmosphericModelKEY=%d, fAmplFadcKEY=%d, fAddSpotSizeKEY=%d, "
+                 "fPSFKEY=%d, fViewconeAngleOKEY=%d, fSpectrumKEY=%d, fTriggerFlagKEY=%d ",
+                 enoise.Data(),
+                 dnoise.Data(), RunNum,
+                 numslices.Data(), corsikakey,
+                 reflectorkey, camerakey,
+                 observationkey, particlekey,
+                 ntrig, nsumtrig, coneai, coneao,
+                 atmomodelkey, amplfadckey, spotsizekey,
+                 psfkey, viewconeangleokey, spectrumkey, triggerkey);
+
+        TString vars2 =
+            Form("fRunFilled=Now(), fFileName=\"%s\", fRunNumber=%d, fPriority=%d ",
+                 fname.Data(), RunNum, RunNum);
+
+
+        if (!serv.ExistStr("fRunNumber", "MCRunData", Form("%d", RunNum)))
+        {
+            if (!serv.Insert("MCRunData", vars))
+                return 2;
+        }
+        else
+            if (!serv.Update("MCRunData", vars, Form("fRunNumber=%d", RunNum)))
+                return 2;
+
+//MarsVersion miteintragen bei Prozessierung
+
+        if (!serv.ExistStr("fRunNumber", "MCRunProcessStatus", Form("%d", RunNum)))
+        {
+            if (!serv.Insert("MCRunProcessStatus", vars2))
+                return 2;
+        }
+        else
+            if (!serv.Update("MCRunProcessStatus", vars2, Form("fRunNumber=%d", RunNum)))
+                return 2;
+    }
+    // If the file is already filled into the db, the values will be updated
+    else
+    {
+        TString run=(*row)[0];
+        TString check=(*row)[1];
+        if (check==fname)
+        {
+            RunNum=atoi(run.Data());
+            cout << "File already inserted into db, do update " << endl;
+            cout << "--------" << endl;
+            cout << "RunNum: " << RunNum << endl;
+            cout << "File: " << fname << endl;
+            cout << endl;
+
+            vars +=
+                Form("fELowLim=%s, fEUppLim=%s, fSlopeSpec=%5.2f, "
+                     "fImpactMax=%s, fNumSimulatedShowers=%d, fNumEvents=%d, "
+                     "fNumPheFromDNSB=%s, fZBin=%d, fZBinMin=%d, fZBinMax=%d, fThetaMin=%s, "
+                     "fThetaMax=%s, fPhiMin=%s, fPhiMax=%s, fPointSpread=%s, "
+                     "fPedesMean=%s, fLow2HighGain=%s, "
+                     "fAmplFadcInner=%s, fAmplFadcOuter=%s, ",
+                     elow.Data(), eupp.Data(), spectrum,
+                     imax.Data(), numsimshow, numevents,
+                     numphe.Data(), zBin2, zBin2Min, zBin2Max, thetamin.Data(),
+                     thetamax.Data(), pmin.Data(), pmax.Data(), psf.Data(),
+                     ped.Data(), low2high.Data(),
+                     amplfadc.Data(), amplfadco.Data());
+            vars +=
+                Form("fElectricNoise=%s, "
+                     "fDigitalNoise=%s, fRunNumber=%d, "
+                     "fNumSlices=%s, fCorsikaVersionKEY =%d, "
+                     "fReflectorVersionKEY=%d, fCameraVersionKEY=%d, "
+                     "fObservationModeKEY=%d, fMCParticleKEY=%d, "
+                     "fNumTriggers=%d, fNumSumTriggers=%d, fViewconeAngleInner=%5.2f, fViewconeAngleOuter=%5.2f, "
+                     "fAtmosphericModelKEY=%d, fAmplFadcKEY=%d, fAddSpotSizeKEY=%d, "
+                     "fPSFKEY=%d, fViewconeAngleOKEY=%d, fSpectrumKEY=%d, fTriggerFlagKEY=%d ",
+                     enoise.Data(),
+                     dnoise.Data(), RunNum,
+                     numslices.Data(), corsikakey,
+                     reflectorkey, camerakey,
+                     observationkey, particlekey,
+                     ntrig, nsumtrig, coneai, coneao,
+                     atmomodelkey, amplfadckey, spotsizekey,
+                     psfkey, viewconeangleokey, spectrumkey, triggerkey);
+
+            TString vars2 =
+                Form("fRunFilled=Now(), fFileName=\"%s\", fRunNumber=%d, fPriority=%d ",
+                     fname.Data(), RunNum, RunNum);
+
+
+            if (!serv.ExistStr("fRunNumber", "MCRunData", Form("%d", RunNum)))
+            {
+                if (!serv.Insert("MCRunData", vars))
+                    return 2;
+            }
+            else
+                if (!serv.Update("MCRunData", vars, Form("fRunNumber=%d", RunNum)))
+                    return 2;
+
+            if (!serv.ExistStr("fRunNumber", "MCRunProcessStatus", Form("%d", RunNum)))
+            {
+                if (!serv.Insert("MCRunProcessStatus", vars2))
+                    return 2;
+            }
+            else
+                if (!serv.Update("MCRunProcessStatus", vars2, Form("fRunNumber=%d", RunNum)))
+                    return 2;
+        }
+        //If none of the above options is true, something must be wrong
+        else
+        {
+            cout << "ERROR - Filename in query (" << check << ") and processed filename (" << fname << ") should be the same!" << endl;
+            return 2;
+        }
+    }
+    delete res;
+//    delete row;
+
+    //link file geht nur fuer data files, cal und ped haben keine psf... muessen aber in alle verzeichnisse verlinkt werden
+    //wieder mit if point 0.5/-1.0 else
+
+//    TString query3(Form("SELECT fMCParticleName, fSpectrum, fFileName, fObservationModeKEY from MCRunData "
+//                        "left join MCParticle on MCRunData.fMCParticleKEY=MCParticle.fMCParticleKEY "
+//                        "left join Spectrum on Spectrum.fSpectrumKEY=MCRunData.fSpectrumKEY "
+//                        "left join MCRunProcessStatus on MCRunProcessStatus.fRunNumber=MCRunData.fRunNumber "
+//                        "where MCRunData.fRunNumber=%d;", RunNum));
+    TString query3(Form("SELECT fMCParticleName, fSpectrum FROM MCRunData "
+                        "LEFT JOIN MCParticle USING (fMCParticleKEY) "
+//                        "LEFT JOIN ON MCRunData.fMCParticleKEY=MCParticle.fMCParticleKEY "
+                        "LEFT JOIN Spectrum USING (fSpectrumKEY) "
+//                        "LEFT JOIN Spectrum ON Spectrum.fSpectrumKEY=MCRunData.fSpectrumKEY "
+                        "WHERE MCRunData.fRunNumber=%d;", RunNum));
+    res = serv.Query(query3);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query3 << endl;
+        return 2;
+    }
+
+    row = res->Next();
+    if (!row)
+        return 2;
+
+
+    // Definition of variables for linking the file
+    TString rawpath;
+    TString type = "D";  //P, C, D
+    TString particle = (*row)[0];    //ParticleName abfragen
+    TString spec     = (*row)[1];    //Spectrum.fSpectrum abfragen
+    TString obsmode;             //wird ueber obskey praezisiert
+    TString trigmode;            //wird ueber triggerkey praezisiert
+    TString mkdir;
+    TString link;
+    TString linkname;
+    TString RunNumber=Form("%08d",RunNum);
+
+    delete res;
+    rawpath = Form("/magic/montecarlo/rawfiles/19%02d/%02d/%02d", zBin2, amplfadckey, ass);
+//    rawpath = Form("/home/hoehne/Analyse/TestMonteCarlo/montecarlo/rawfiles/19%02d/%02d/%02d", zBin2, amplfadckey, ass);
+    mkdir = Form("mkdir -p -v %s", rawpath.Data());
+
+    switch (observationkey)
+    {
+    case 1:
+//        obsmode = ""; //evtl für ped u cal verwenden
+        cout << "" << endl;
+        cout << "Ped or Cal run -> no linking by fillcamera.C" << endl;
+//        spec = "";
+//        particle="MonteCarlo";
+//        TRegexp pedcal("_._");
+//        TString peca = fname(pedcal);
+//        if (peca="_P_")
+//            type="P";
+//        if (peca="_C_")
+//            type="C";
+        break;
+        //Problem: zbin und psf
+        //19990101_00002_C_MonteCarlo_E.root
+
+    case 2:
+        obsmode = "W";
+        break;
+
+    case 3:
+        obsmode = "";
+        break;
+
+    case 4:
+        obsmode = "FW";
+        break;
+
+    case 5:
+        obsmode = "Diff";
+        break;
+
+    default:
+        cout << "ERROR - ObservationModeKEY wrong value" << endl;
+        return 2;
+    }
+
+    TRegexp reg("_w.");
+    TString add = fname(reg);
+//    add = add.Data()+2;
+    if (add=="_w+" || add=="_w-")
+    {
+        if (add=="_w+")
+            obsmode += "1";
+        else
+            obsmode += "2";
+    }
+
+    switch(triggerkey)
+    {
+    case 2:
+        obsmode += "";
+        break;
+    case 3:
+        obsmode += "SUM";
+        break;
+    default:
+        cout << "ERROR - TriggerFlagKEY wrong value" << endl;
+        return 2;
+    }
+
+    if (observationkey!=1)
+    {
+        link = Form("ln -sv %s %s/19%02d%02d%02d_%s_%s_%s%s%s_E.root", fname.Data(), rawpath.Data(), zBin2, amplfadckey, ass, RunNumber.Data(), type.Data(), particle.Data(), spec.Data(), obsmode.Data());
+        linkname = Form("%s/19%02d%02d%02d_%s_%s_%s%s%s_E.root", rawpath.Data(), zBin2, amplfadckey, ass, RunNumber.Data(), type.Data(), particle.Data(), spec.Data(), obsmode.Data());
+
+        if (dummy==kFALSE)
+        {
+            gSystem->Exec(mkdir);
+            gSystem->Exec(link);
+
+            TString vars3 =
+                Form("fRunLinked=Now(), fLinkName=\"%s\", fRunNumber=%d ",
+                     linkname.Data(), RunNum);
+
+            if (!serv.ExistStr("fRunNumber", "MCRunProcessStatus", Form("%d", RunNum)))
+            {
+                if (!serv.Insert("MCRunProcessStatus", vars3))
+                    return 2;
+            }
+            else
+                if (!serv.Update("MCRunProcessStatus", vars3, Form("fRunNumber=%d", RunNum)))
+                    return 2;
+
+        }
+        else
+        {
+            cout << "" << endl;
+            cout << "Dummy mode. The following commands would be executed:" << endl;
+            cout << mkdir << endl;
+            cout << link << endl;
+            cout << "" << endl;
+        }
+    }
+    else
+    {
+        cout << "" << endl;
+        cout << "P/C Linking will be done by fillcamera script" << endl;
+        cout << "" << endl;
+    }
+
+//    delete runheader1;
+//    delete runheader2;
+//    delete runheader3;
+//    delete fadcheader;
+//    delete rawheader;
+//    delete evtbasic;
+
+
+
+    return 1;
+
+}
+/*
+int fillcamera(TString fname, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << endl;
+    cout << "fillcamera" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    return Process(serv, fname, dummy);
+}
+*/
+int fillcamera(TString path="/magic/montecarlo/camera", Bool_t dummy=kTRUE)
+{
+//    TEnv env("mcsql.rc");
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+//    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << endl;
+    cout << "fillcamera" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Search path: " << path << endl;
+    cout << endl;
+
+
+    TString fname;
+    TString name;
+
+
+    MDirIter Next(path,"*.root",-1);
+
+    while(1)
+    {
+        TString name = Next();
+        if (name.IsNull())
+            break;
+        fname=name;
+        cout << endl;
+        cout << endl;
+        cout << "filename: " << fname << endl;
+
+//        TObject::SetObjectStat(kTRUE);
+
+        if (!Process(serv, name, dummy))
+            return 2;
+/*
+        if (TObject::GetObjectStat())
+        {
+            TObject::SetObjectStat(kFALSE);
+            gObjectTable->Print();
+        }
+*/
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillcmt.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillcmt.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillcmt.C	(revision 17960)
@@ -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, 01/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillcmt.C
+// =========
+//
+// This macro is used to read an extinction file from the CMT and fill
+// its contents into the db.
+//
+// Usage:
+//   .x fillcmt.C("camext.06", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Filling the database is done with 'UPADTE' for _all_ columns
+// matching the date!
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillcmt.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillcmt.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <iostream>
+#include <errno.h>
+
+#include <TEnv.h>
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MSQLMagic.h"
+
+using namespace std;
+
+int fillcmt(TString fname, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    gSystem->ExpandPathName(fname);
+
+    cout << "fillcmt" << endl;
+    cout << "-------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        gLog << err << "Cannot open file " << fname << ": ";
+        gLog << strerror(errno) << endl;
+        return 2;
+    }
+
+    TString line;
+    for (int i=0; i<23; i++)
+        line.ReadLine(fin);
+
+    if (!fin)
+    {
+        gLog << err << "File " << fname << ": Not enough lines." << endl;
+        return 2;
+    }
+
+    while (1)
+    {
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        const_cast<char&>(line.Data()[ 6]) = 0;
+        const_cast<char&>(line.Data()[10]) = 0;
+        const_cast<char&>(line.Data()[19]) = 0;
+        const_cast<char&>(line.Data()[35]) = 0;
+        const_cast<char&>(line.Data()[39]) = 0;
+        const_cast<char&>(line.Data()[45]) = 0;
+        const_cast<char&>(line.Data()[51]) = 0;
+
+        const Int_t checked = atoi(line.Data()+7);
+        if (checked==0)
+            continue;
+
+        const TString date    = line.Data();
+        const Float_t extr    = atof(line.Data()+11);     //5.3
+        const Int_t   phot    = line.Data()[18] == ':';
+        const Float_t extrerr = atof(line.Data()+20);     //5.3
+        const Float_t tmphot  = atof(line.Data()+40);     //5.2
+        const Float_t tmnphot = atof(line.Data()+46);     //5.2
+
+        MTime t;
+        t.SetStringFmt(date, "%y%m%d");
+
+        const TString vars = Form("fExtinctionR=%.3f, "
+                                  "fExtinctionRerr=%.3f, "
+                                  "fIsPhotometric=%d, "
+                                  "fTimePhotometric=%.2f, "
+                                  "fTimeNonPhotometric=%.2f",
+                                  extr, extrerr, phot, tmphot, tmnphot);
+
+
+        const TString where = Form("fData='%s'", t.GetSqlDateTime().Data());
+
+        if (!serv.InsertUpdate("ExtinctionCMT", vars, where))
+            return 2;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillcondor.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillcondor.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillcondor.C	(revision 17960)
@@ -0,0 +1,187 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 06/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillcondor.C
+// ============
+//
+// This macro is used to read self written condor log-files.
+// These files are written to /magic/data/autologs/condor/
+//
+// Usage:
+//   .x fillcondor.C("/magic/datacenter/autologs/condor", "2008-06-28", kTRUE)
+//   .x fillcondor.C("/magic/datacenter/autologs/condor/2008/06/28", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillcondor.C+\(\"2008-06-28\"\,kFALSE\) 2>&1 | tee fillcondor.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <fstream>
+#include <iomanip>
+#include <iostream>
+
+#include <TSystem.h>
+
+#include "MTime.h"
+#include "MDirIter.h"
+#include "MSQLMagic.h"
+
+Bool_t Process(MSQLMagic &serv, const TString &path)
+{
+    Int_t rc[3] = {0, 0, 0};
+
+    MDirIter Next(path, "status.*", -1);
+    while (1)
+    {
+        TString fname=Next();
+        if (fname.IsNull())
+            break;
+
+        ifstream fin(fname);
+        if (!fin)
+            continue;
+
+        // Remove path and "status."
+        TString date = gSystem->BaseName(fname)-11;
+        date.ReplaceAll("/status.", " ");
+        date.ReplaceAll("/", "-");
+        date.Insert(13, ":");
+        date += ":00";
+
+        Int_t    num   = 0;
+        Double_t load  = 0;
+        Double_t cload = 0;
+        Int_t    claim = 0;
+
+        MTime tm(date);
+        while (1)
+        {
+            TString str;
+            str.ReadLine(fin);
+            if (!fin)
+                break;
+
+            if (str.IsNull())
+                continue;
+
+            if (str.Contains("coma"))
+                continue;
+
+            if (!str.BeginsWith("slot") && !str.BeginsWith("wast"))
+                continue;
+
+            TObjArray *obj = str.Tokenize(' ');
+
+            const TString ld = ((*obj)[3])->GetName();
+            const TString cm = ((*obj)[5])->GetName();
+
+            load += ld.Atof();
+            num++;
+
+            if (cm=="Claimed")
+            {
+                cload += ld.Atof();
+                claim++;
+            }
+
+            delete obj;
+        }
+
+        if (num==0)
+            continue;
+
+        const TString vars = Form("fNumTotal=%d, fNumClaimed=%d, fLoadTotal=%.2f, fLoadClaimed=%.2f",
+                                  num, claim, load, cload);
+
+        const Int_t res = serv.InsertUpdate("CondorStatus", "fTime", tm.GetSqlDateTime(), vars);
+        rc[res+1]++;
+        if (res==kFALSE)
+            break;
+    }
+
+    if (rc[0]==0 && rc[1]==0 && rc[2]==0)
+        return kTRUE;
+
+    cout << "Dummies:  " << rc[0] << endl;
+    cout << "Failed:   " << rc[1] << endl;
+    cout << "Success:  " << rc[2] << endl;
+    cout << endl;
+
+    // Non failed -> success
+    if (rc[1]==0)
+        return kTRUE;
+
+    // At least one failed -> error
+    if (rc[1]>0)
+        return 2;
+
+    // Must have been dummy mode
+    return -1;
+}
+
+int fillcondor(TString path="/magic/datacenter/autologs/condor", Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillcondor" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Path: " << path << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    return Process(serv, path);
+}
+
+int fillcondor(TString path, TString date, Bool_t dummy=kTRUE)
+{
+    if (!path.EndsWith("/"))
+        path += '/';
+
+    date.ReplaceAll("-", "/");
+    path += date;
+
+    return fillcondor(path, dummy);
+}
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/filldotraw.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/filldotraw.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/filldotraw.C	(revision 17960)
@@ -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, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// filldotraw.C
+// ============
+//
+// This macro is used to read a merpped raw data file or a raw data file
+// directly. The descision is taken by the file-name extension (".root" or
+// ".raw")
+//
+// Usage:
+//   .x filldotraw.C("/data/MAGIC/Period014/filename.raw", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Filling the database is done with 'UPADTE' for _all_ columns
+// matching the Run-Number!
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b filldotraw.C+\(\"filename\"\,kFALSE\) 2>&1 | tee filldotraw.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <iostream>
+
+#include <TEnv.h>
+#include <TFile.h>
+#include <TTree.h>
+#include <TRegexp.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MZlib.h"
+#include "MSQLMagic.h"
+#include "MRawRunHeader.h"
+#include "MDirIter.h"
+
+using namespace std;
+
+Int_t QueryFromName(MSQLMagic &serv, const char *col, const char *val)
+{
+    const TString query1 = Form("SELECT f%sKEY FROM %s WHERE f%s='%s'",
+                                col, col, col, val);
+
+    TSQLResult *res1 = serv.Query(query1);
+    if (!res1)
+    {
+        cout << "ERROR - Query has failed: " << query1 << endl;
+        return -1;
+    }
+
+    TSQLRow *row=res1->Next();
+
+    const Int_t rc1 = row && (*row)[0] ? atoi((*row)[0]) : -1;
+    delete res1;
+    return rc1;
+}
+
+//get key for a magic number
+Int_t MagicNumber(MSQLMagic &serv, const MRawRunHeader &h)
+{
+    return QueryFromName(serv, "MagicNumber", Form("%d", h.GetMagicNumber()));
+}
+
+Bool_t ReadRaw(TString fname, MRawRunHeader &h)
+{
+    MZlib fin(fname);
+    if (!fin)
+    {
+        cout << "ERROR - Couldn't open file " << fname << endl;
+        return kFALSE;
+    }
+
+    if (!h.ReadEvt(fin))
+    {
+        cout << "ERROR - Reading header from file " << fname << endl;
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+Bool_t ReadRoot(TString fname, MRawRunHeader *h)
+{
+    TFile file(fname, "READ");
+    if (file.IsZombie())
+    {
+        cout << "ERROR - Cannot open file " << fname << endl;
+        return kFALSE;
+    }
+
+    TTree *t = (TTree*)file.Get("RunHeaders");
+    if (!t)
+    {
+        cout << "ERROR - Tree RunHeaders not found." << endl;
+        return kFALSE;
+    }
+
+    t->SetBranchAddress("MRawRunHeader.", &h);
+    t->GetEntry(0);
+
+    return kTRUE;
+}
+
+Bool_t CheckRunNumber(MSQLMagic &serv, Int_t num)
+{
+    TString query(Form("SELECT fRunNumber from RunData where fRunNumber=%d", num));
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return kFALSE;
+    }
+
+    TSQLRow *row = res->Next();
+
+    Bool_t rc = row && (*row)[0] ? atoi((*row)[0])==num : kFALSE;
+    delete res;
+    return rc;
+
+}
+
+Bool_t InsertEntry(MSQLMagic &serv, MRawRunHeader &h)
+{
+    const Int_t magickey  = MagicNumber(serv, h);
+    const Int_t runkey    = QueryFromName(serv, "RunType",         h.GetRunTypeStr());
+    const Int_t projkey   = serv.QueryKeyOfName("Project",         h.GetProjectName());
+    const Int_t sourcekey = serv.QueryKeyOfName("Source",          h.GetSourceName());
+    const Int_t modekey   = serv.QueryKeyOfName("ObservationMode", h.GetObservationMode());
+
+    if (magickey<0 || runkey<0 || projkey<0 || sourcekey<0 || modekey<0)
+        return -1;
+
+    TString query;
+
+    query += Form("fRunNumber=%d, ",          h.GetRunNumber());
+    query += Form("fMagicNumberKEY=%d, ",     magickey);
+    query += Form("fFormatVersion=%d, ",      h.GetFormatVersion());
+    query += Form("fRunTypeKEY=%d, ",         runkey);
+    query += Form("fProjectKEY=%d, ",         projkey);
+    query += Form("fSourceKEY=%d, ",          sourcekey);
+    query += Form("fNumEvents=%d, ",          h.GetNumEvents());
+    query += Form("fRunStart='%s', ",         h.GetRunStart().GetSqlDateTime().Data());
+    query += Form("fRunStop='%s', ",          h.GetRunEnd().GetSqlDateTime().Data());
+    query += Form("fObservationModeKEY=%d, ", modekey);
+
+    query += "fExcludedFDAKEY=1, fTestFlagKEY=1, fLightConditionsKEY=1, ";
+    query += "fCalibrationScriptKEY=1, fDiscriminatorThresholdTableKEY=1, ";
+    query += "fTriggerDelayTableKEY=1, fL1TriggerTableKEY=1, fL2TriggerTableKEY=1, ";
+    query += "fHvSettingsKEY=1, fZenithDistance=0, fAzimuth=0, ";
+    query += "fDaqStoreRate=0, fDaqTriggerRate=0, fMeanTRiggerRate=0, ";
+    query += "fL2RatePresc=0, fL2RateUnpresc=0 ";
+
+    return serv.Insert("RunData", query);
+}
+
+Int_t UpdateEntry(MSQLMagic &serv, MRawRunHeader &h)
+{
+    //get key for the magic number
+    const Int_t key = MagicNumber(serv, h);
+    if (key<0)
+        return -1;
+
+    TString vars(Form("fMagicNumberKEY=%d, fFormatVersion=%d",
+                       key, h.GetFormatVersion()));
+    TString where(Form("fRunNumber=%d", h.GetRunNumber()));
+
+    return serv.Update("RunData", vars, where);
+}
+
+
+int Process(MSQLMagic &serv, TString fname, Bool_t dummy)
+{
+    MRawRunHeader h;
+
+    //read header either from root or from raw file
+    if (fname.EndsWith(".root"))
+        ReadRoot(fname, &h);
+    if (fname.EndsWith(".raw"))
+        ReadRaw(fname, h);
+    if (fname.EndsWith(".raw.gz"))
+        ReadRaw(fname, h);
+
+    if (dummy)
+        h.Print("header");
+
+    Int_t rc = CheckRunNumber(serv, h.GetRunNumber()) ?
+        UpdateEntry(serv, h) : InsertEntry(serv, h);
+
+    return rc==0 ? 2 : 1;
+}
+
+int filldotraw(TString fname, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << "filldotraw" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    return Process(serv, fname, dummy);
+}
+
+int filldotraw(Int_t runno, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << "filldotraw" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Run: " << runno << endl;
+    cout << endl;
+
+    //get date for the run to build path of the file
+    TString query(Form("SELECT DATE_FORMAT(ADDDATE(fRunStart, Interval 13 HOUR), '%%Y/%%m/%%d') FROM RunData WHERE fRunNumber=%d",
+                       runno));
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+
+    TSQLRow *row = 0;
+    row = res->Next();
+    TString date=(*row)[0];
+    cout << "date: " << date << endl;
+    TString path(Form("/magic/data/rawfiles/%s", date.Data()));
+    TString file(Form("*%d_*_*_E.raw.?g?z?", runno));
+
+    delete res;
+
+    cout << "path: " << path << " - file : " << file << endl;
+    TString fname;
+    TString name;
+
+    Int_t count=0;
+    MDirIter Next(path, file, -1);
+    while (1)
+    {
+        name = Next();
+        if (name.IsNull())
+            break;
+        fname=name;
+        cout << "filename: " << fname << endl;
+        count++;
+    }
+
+    //check if there's only one file with this runno
+    if (count!=1)
+    {
+        cout << "ERROR - there's are " << count << " files. " << endl;
+        return 2;
+    }
+
+    return Process(serv, fname, dummy);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/filldotrbk.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/filldotrbk.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/filldotrbk.C	(revision 17960)
@@ -0,0 +1,239 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// filldotrbk.C
+// ============
+//
+// This macro is used to read the central control runbook files from
+// the data center and store their contents in the runbook-database.
+//
+// Usage:
+//   .x filldotrbk.C("/magic/subsystemdata/cc/", kTRUE)
+//
+// The first argument is the directory in which all subdirectories are
+// searched for CC_*.rbk files. All these files are analysed and the runbook
+// entries will be put into the DB, eg:
+//  "/magic/subsystemdata/cc"                  would do it for all data
+//  "/magic/subsystemdata/cc/2005"                  for one year
+//  "/magic/subsystemdata/cc/2005/11"               for one month
+//  "/magic/subsystemdata/cc/2005/11/11"            for a single day
+//  "/magic/subsystemdata/cc/2005/11/11/file.rbk"   for a single file
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Before an entry is added, its existance is checked... if it is already
+// in the database, it is ignored.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b filldotrbk.C+\(\"path\"\,kFALSE\) 2>&1 | tee filldotrbk.log
+//
+// Make sure, that database and password are corretly set in the macro.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+///////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TRegexp.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MDirIter.h"
+#include "MSQLServer.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an entry for this date is already existing
+//
+Bool_t ExistStr(MSQLServer &serv, const char *column, const char *table, const char *test)
+{
+    TString query(Form("SELECT %s FROM %s WHERE %s='%s'", column, table, column, test));
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    TSQLRow *row;
+
+    Bool_t rc = kFALSE;
+    while ((row=res->Next()))
+    {
+        if ((*row)[0])
+        {
+            rc = kTRUE;
+            break;
+        }
+    }
+    delete res;
+    return rc;
+}
+
+int insert(MSQLServer &serv, Bool_t dummy, TString entry, TString date)
+{
+
+    //check if entry is already in database
+    if (ExistStr(serv, "fRunBookDate", "RunBook", date))
+        return 0;
+
+    entry.ReplaceAll("'", "\\'");
+    entry.ReplaceAll("\"", "\\\"");
+
+    // This is a sanity check for \0-bytes in .rbk-files
+    for (int i=0; i<entry.Length(); i++)
+        if ((int)entry[i]==0)
+            entry.Remove(i--);
+
+    //insert entry into the database
+    TString query("INSERT RunBook (fRunBookDate, fRunBookText) VALUES (\"");
+    query += date;
+    query += "\", \"";
+    query += entry;
+    query += "\");";
+
+    if (dummy)
+        return 1;
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return 0;
+
+    delete res;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// insert the entries from this runbook file into the database
+//
+int process(MSQLServer &serv, Bool_t dummy, TString fname)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        cout << "Could not open file " << fname << endl;
+        return 0;
+    }
+
+    TRegexp regexp("^.20[0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].$", kFALSE);
+
+    Int_t num=0;
+
+    TString entry="";
+    TString date="";
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+        {
+            num += insert(serv, dummy, entry, date);
+            break;
+        }
+
+        TString l0 = line(regexp);
+
+        if (l0.IsNull() || entry.IsNull())
+        {
+            entry += line;
+            entry += "\n";
+            continue;
+        }
+/*
+        if (entry.Contains("Operator names: "))
+        {
+            cout << "OPERATORS: " << entry << flush;
+            entry="";
+        }
+*/
+
+        //skip run statistics from old runbooks
+        if (entry.Contains("MAGIC ELECTRONIC RUNBOOK")   ||
+            entry.Contains("DATA RUN STATISTICS")        ||
+            entry.Contains("CALIBRATION RUN STATISTICS") ||
+            entry.Contains("PEDESTAL RUN STATISTICS"))
+            entry ="";
+
+        if (!entry.IsNull() && !date.IsNull())
+            num += insert(serv, dummy, entry, date);
+
+        date=l0(1, l0.Length()-2);
+        entry="";
+    }
+
+    cout << fname(TRegexp("CC_.*.rbk", kFALSE)) << " <" << num << ">";
+    cout << (dummy?" DUMMY":"") << endl;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// loop over all files in this path
+//
+int filldotrbk(TString path="/data/MAGIC/Period017/ccdata", Bool_t dummy=kTRUE)
+{
+    MSQLServer serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << endl;
+    cout << "filldotrbk" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Search Path: " << path << endl;
+    cout << endl;
+
+    //get all runbook files in path
+    if (path.EndsWith(".rbk"))
+        return process(serv, dummy, path);
+
+    //fill entries for each runbook file
+    MDirIter Next(path, "CC_*.rbk", -1);
+    while (1)
+    {
+        TString name = Next();
+        if (name.IsNull())
+            break;
+
+        if (!process(serv, dummy, name))
+            return 0;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/filldotrun.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/filldotrun.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/filldotrun.C	(revision 17960)
@@ -0,0 +1,844 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// filldotrun.C
+// ============
+//
+// This macro is used in the datacenter to automatically fill the run-database
+// with the information stored in the .run-files written by the central
+// control.
+//
+// To following Arehucas versions are Currently supported:
+//   040505-0, 040514-0,
+//   040518-0, 040727-0,
+//   041113-0, 041209-0, 041221-0
+//   050224-0, 050317-0, 050322-0, 050401-0, 050413-0, 050415-0, 050714-0,
+//   050719-0, 050829-0, 051025-0,
+//   060330-0, 060401-0, 060808-0
+//   070416-0,
+//   080220-0, 080519-0, 080912-0, 081204-0, 081214-0,
+//   090203-0, 090221-0, 090522-0, 090525-0, 090616-0, 090625-0, 090702-0,
+//   090706-0, 090731-0
+//
+// Usage:
+//    .x filldotrun.C+("/data/MAGIC/Period019/ccdata", kTRUE)
+//
+// While the first argument is the directory in which all subdirectories where
+// searches for CC_*.run files. All these files were analysed and the run
+// info will be put into the DB, eg:
+//  "/magic/subsystemdata/cc"                  would do it for all data
+//  "/magic/subsystemdata/cc/2005"                  for one year
+//  "/magic/subsystemdata/cc/2005/11"               for one month
+//  "/magic/subsystemdata/cc/2005/11/11"            for a single day
+//  "/magic/subsystemdata/cc/2005/11/11/file.run"   for a single file
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. Instead
+// informations about the subtables are displayed. This is usefull for tests
+// when adding a new arehucas version support. If it is kFALSE the information
+// are written into the subtables and the runs info is written into the
+// rundatabase.
+//
+// In the automatic case it makes sense to check the logfiles to make sure
+// that everything is fine...
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b filldotrun.C+\(\"path\"\,kFALSE\) 2>&1 | tee filldotrun.log
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TMath.h>
+#include <TRegexp.h>
+
+#include "MTime.h"
+#include "MDirIter.h"
+#include "MSQLMagic.h"
+
+using namespace std;
+
+Int_t insert(MSQLMagic &serv, Bool_t dummy, TString filename)
+{
+    ifstream fin(filename);
+    if (!fin)
+    {
+        cout << "Could not open file " << filename << endl;
+        return -1;
+    }
+
+    TString strng;
+    TObjArray *array = new TObjArray();
+    Int_t check=0;
+
+    strng.ReadLine(fin);
+    if (strng!=TString("[CC Plain Run Summary File]"))
+    {
+        cout << filename << ": No Plain Run Summary File" << endl;
+        cout << "First Line: " << strng << endl;
+        cout << endl;
+        return -1;
+    }
+
+    strng.ReadLine(fin);
+    TRegexp reg("[0-9][0-9][0-9][0-9][0-9][0-9]-[0-9]");
+    TString arehucas = strng(reg);
+    arehucas.Prepend("20");
+    arehucas.ReplaceAll("-", "");
+
+    Int_t version = atoi(arehucas.Data());
+    if (version!=200405050 && version!=200405140 && version!=200405180 &&
+        version!=200407270 && version!=200411130 && version!=200412090 &&
+        version!=200412210 &&
+        version!=200502240 && version!=200503170 && version!=200503220 &&
+        version!=200504010 && version!=200504130 && version!=200504150 &&
+        version!=200507140 && version!=200507190 && version!=200508290 &&
+        version!=200510250 &&
+        version!=200603300 && version!=200604010 && version!=200608080 &&
+        version!=200704160 &&
+        version!=200802200 && version!=200805190 && version!=200809120 &&
+        version!=200812040 && version!=200812140 &&
+        version!=200902030 && version!=200902210 && version!=200905220 &&
+	version!=200905250 && version!=200906160 && version!=200906250 &&
+	version!=200907020 && version!=200907060 && version!=200907310)
+    {
+        cout << filename << ": File Version unknown - please update the macro!" << endl;
+        cout << "Second Line: " << strng << endl;
+        cout << endl;
+        return -1;
+    }
+
+    Int_t telcheck=1;
+    TString tcheck;
+    if (version >= 200805190)
+    {
+	strng.ReadLine(fin);
+        if (!strng.BeginsWith("Telescope M"))
+        {
+            cout << "WARNING - Line 3 doesn't start with 'Telescope M'." << endl;
+            cout << strng << endl;
+        }
+	telcheck = atoi(strng.Data()+11);
+
+        if (telcheck != 1 && telcheck != 2)
+        {
+            cout << filename << ": Telescope declaration wrong!" << endl;
+            cout << "Third Line: " << strng << endl;
+            cout << endl;
+            return -1;
+        }
+    }
+
+    if (version >= 200411130)
+    {
+        strng.ReadLine(fin);
+        if (strng[0]!='#')
+        {
+            cout << "WARNING - '#' expected." << endl;
+            cout << strng << endl;
+        }
+    }
+
+    cout << " * V" << version << " " << endl;
+
+    Int_t cnt=0;
+    while (1)
+    {
+        // ===== Check for number of columns in file =====
+        // different arehucas versions provide a different number of columns:
+        // 200405050 - 200405140: 18 columns
+        // 200405180 - 200407270: 35 columns
+        // 200411130 - 200510250: 43 columns
+        // 200603300 - 200802200: 52 columns
+        // 200805190 - 200809120: 54 columns
+        // 200812040 - 200906160: 55 columns
+        // >= 200906250:          61 columns
+        //
+	strng.ReadLine(fin);
+	//fill an array with the values separated by ' '. Advantage: In contrast to ReadToDelim(' ') objects 'between'
+	//two whitespaces are not written to the array. In case of a missing column the error is detected by comparison
+	//with the number of default columns. In case of an 'accidental' double(triple)-whitespace the columns are treated
+	//in the right way, only a warning is released to edit the file, if necessary.
+	array = strng.Tokenize(" ");
+	check = array->GetEntries();
+
+        if (strng.Contains("  ") || strng. Contains("   "))
+	{
+	    cout << "WARNING - Multiple whitespaces found, please check the file:" << endl;
+	    cout << filename << endl;
+	}
+
+        /*
+	for (int n=0; n< array->GetEntries(); n++)
+	{
+	    cout << (*array)[n]->GetName() << endl;
+	}
+        */
+        //check the number of columns for the different versions, if there is an empty line (check=0), do nothing
+        if (check != 0)
+        {
+            if ((version <= 200405140 && check != 18) ||
+                (version >  200405140 && version <= 200407270 && check != 35) ||
+                (version >  200407270 && version <= 200510250 && check != 43) ||
+                (version >  200510250 && version <= 200802200 && check != 52) ||
+                (version >  200802200 && version <= 200809120 && check != 54) ||
+                (version >  200809120 && version <= 200906160 && check != 55) ||
+                (version >  200906160 && ((telcheck == 1 && check != 61) || (telcheck == 2 && check != 63))))
+            {
+		cout << "ERROR - Number of columns (" << check << ") doesn't match number of required columns, please check the file:" << endl;
+                cout << filename << endl;
+		delete array;
+                continue;
+            }
+	}
+
+	//when reaching the end of the file...
+	if (!fin)
+            break;
+
+        // count variable for the columns
+	Int_t i = 0;
+
+        // ========== Col 1: Telescope Number =========
+        Int_t telnumber = 1; // FIXME: "NULL"?
+        if (version >=200805190)
+        {
+            strng = (*array)[i++]->GetName();
+
+	    if (strng[0]!='M')
+            {
+                cout << "WARNING - First character is not an M." << endl;
+                cout << strng << endl;
+                delete array;
+                continue;
+            }
+	    telnumber = atoi(strng.Data()+1);
+
+        }
+
+        // ========== Col 2: Run Number =========
+        //Reading the line
+        //and converting some strings to ints/floats
+	strng = (*array)[i++]->GetName();
+
+        Int_t runnumber = atoi(strng.Data());
+
+        //runnumber=0 means no valid dataset
+        //-> continue
+        if (runnumber == 0)
+        {
+	    delete array;
+            cout << "WARNING - Runnumber == 0" << endl;
+            continue;
+	}
+
+	//cout << runnumber << " ";
+
+        // ========== Col 3: Subrun Number ========= starting with version 200805190
+        Int_t filenumber = 0; // FIXME: "NULL"?
+        if (version >=200805190)
+        {
+	    strng = (*array)[i++]->GetName();
+            filenumber = atoi(strng.Data());
+        }
+
+        TString where = Form("fTelescopeNumber=%d AND fFileNumber=%d",
+                             telnumber, filenumber);
+        if (serv.ExistStr("fRunNumber", "RunData", Form("%d", runnumber), where))
+        {
+            // FIXME: Maybe we can implement a switch to update mode?
+            cout << "WARNING - Entry M" << telnumber << ":" << runnumber << "/" << filenumber << " already existing... skipped." << endl;
+            delete array;
+            continue;
+	}
+
+
+        // ========== Col 4: Run Type =========
+	strng = (*array)[i++]->GetName();
+        if (strng.Contains("???"))
+            strng="n/a";
+
+        Int_t runtype = serv.QueryKeyOfName("RunType", strng, kFALSE);
+        if (runtype<0)
+        {
+            cout << "ERROR - RunType " << strng << " not available." << endl;
+            delete array;
+            continue;
+	}
+
+
+        // ========== Col 5,6: Start Time =========
+        TString startdate, starttime;
+	startdate = (*array)[i++]->GetName();
+	starttime = (*array)[i++]->GetName();
+        //cout << startdate << " " << starttime << " ";
+
+        // ========== Col 7,8: Stop Time =========
+	TString stopdate, stoptime;
+	stopdate = (*array)[i++]->GetName();
+	stoptime = (*array)[i++]->GetName();
+        //cout << stopdate << " " << stoptime << " ";
+
+        if (startdate.Contains("???"))
+            startdate="0000-00-00";
+        if (starttime.Contains("???"))
+            starttime="00:00:00";
+        if (stopdate.Contains("???"))
+            stopdate="0000-00-00";
+        if (stoptime.Contains("???"))
+            stoptime="00:00:00";
+
+        // ========== Col 9: Source Name =========
+	strng = (*array)[i++]->GetName();
+        if (strng.Contains("???"))
+            strng="Unavailable";
+
+        Int_t sourcekey = serv.QueryKeyOfName("Source", strng.Data());
+        if (sourcekey<0)
+        {
+            delete array;
+            continue;
+        }
+
+	//cout << sourcekey << " ";
+
+        // ========== Col 10,11: Local source position =========
+	strng = (*array)[i++]->GetName();
+        Float_t zd = atof(strng.Data());
+
+	strng = (*array)[i++]->GetName();
+	Float_t az = atof(strng.Data());
+
+        //cout << zd << " " << az << " ";
+
+        // ========== Col 12: Number of Events =========
+	strng = (*array)[i++]->GetName();
+	Int_t evtno = atoi(strng.Data());
+
+        //cout << evtno << " ";
+
+        // ========== Col 13: Project Name =========
+	strng = (*array)[i++]->GetName();
+        if (strng.Contains("???"))
+            strng="Unavailable";
+
+        Int_t projkey = serv.QueryKeyOfName("Project", strng);
+        if (projkey<0)
+        {
+            delete array;
+            continue;
+        }
+	//cout << projkey << " ";
+
+        // ========== Col 14: Trigger Table Name =========
+        // starting from version 200411130: Col 14,15: Trigger Table Name =========
+	strng = (*array)[i++]->GetName();
+        if (strng.Contains("???"))
+            strng="n/a";
+
+        Int_t l1triggerkey=1;
+        Int_t l2triggerkey=1;
+        if (version >=200411130)
+        {
+            l1triggerkey = serv.QueryKeyOfName("L1TriggerTable", strng);
+            if (l1triggerkey<0)
+            {
+                delete array;
+                continue;
+            }
+
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            l2triggerkey = serv.QueryKeyOfName("L2TriggerTable", strng);
+            if (l2triggerkey<0)
+            {
+                delete array;
+                continue;
+	    }
+        }
+        else
+        {
+            Int_t c=0;
+
+            if (strng.Contains(":"))
+                c=1;
+
+            if (strng.Contains("L1_") && !(strng.Contains(":")))
+                c=2;
+
+            if (strng.Contains("n/a"))
+                c=3;
+
+            switch (c)
+            {
+            case 0:
+                {
+                    l2triggerkey = serv.QueryKeyOfName("L2TriggerTable", strng);
+                    if (l2triggerkey<0)
+                    {
+                        delete array;
+                        continue;
+                    }
+
+                    strng="n/a";
+                    l1triggerkey = 1;
+
+                    break;
+                }
+            case 1:
+                {
+                    TString L1TT, L2TT;
+                    L2TT=strng(7,12);
+                    L1TT=strng(0,6);
+
+                    l1triggerkey = serv.QueryKeyOfName("L1TriggerTable", L1TT);
+                    if (l1triggerkey<0)
+                    {
+                        delete array;
+                        continue;
+                    }
+
+                    l2triggerkey = serv.QueryKeyOfName("L2TriggerTable", L2TT);
+                    if (l2triggerkey<0)
+                    {
+                        delete array;
+                        continue;
+                    }
+
+                    break;
+                }
+            case 2:
+                {
+                    l1triggerkey = serv.QueryKeyOfName("L1TriggerTable", strng);
+                    if (l1triggerkey<0)
+                    {
+                        delete array;
+                        continue;
+                    }
+
+                    strng="n/a";
+                    l2triggerkey = 1;
+
+                    break;
+                }
+            case 3:
+                {
+                    l1triggerkey = 1;
+                    l2triggerkey = 1;
+                    break;
+                }
+            default:
+                {
+                    cout << "WARNING: neither L1 nor L2 Trigger table - please check what is happening." << strng << endl;
+                    break;
+                }
+            }
+        }
+
+        // ========== Col 16-18: TrigRate, L2 UnPresc Rate, L2 Presc Rate ==========
+	strng = (*array)[i++]->GetName();
+        Float_t trigrate = atof(strng.Data());
+
+	strng = (*array)[i++]->GetName();
+        Float_t l2uprate = atof(strng.Data());
+
+	strng = (*array)[i++]->GetName();
+        Float_t l2prrate = atof(strng.Data());
+
+        // ========== Col 19,20: DaqRate, Storage Rate ==========
+	strng = (*array)[i++]->GetName();
+        Float_t daqrate = atof(strng.Data());
+
+	strng = (*array)[i++]->GetName();
+        Float_t storerate = atof(strng.Data());
+
+        // ========== Col 21: HV table =========
+	strng = (*array)[i++]->GetName();
+	if (version==200405050 || version==200405140)
+	{
+	    delete array;
+	    continue;
+	}
+        if (strng.Contains("???"))
+            strng="n/a";
+
+        Int_t hvkey = serv.QueryKeyOfName("HvSettings", strng);
+        if (hvkey<0)
+        {
+            delete array;
+            continue;
+        }
+
+        if (version==200405180 || version==200407270)
+	{
+	    delete array;
+	    continue;
+	}
+
+        Int_t testflagkey=1;
+        Int_t lightcondkey=1;
+        Int_t dttablekey=1;
+        Int_t triggerdelaytablekey=1;
+        Int_t calibrationscriptkey=1;
+        if (version>=200411130)
+        {
+            // ========== Col 22-38: DC and HV-values, mjd =========
+            for (int n=0 ; n<17 ; n++)
+            {
+                i++;
+            }
+
+            // ========== Col 39: test-flag =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            testflagkey = serv.QueryKeyOfName("TestFlag", strng);
+            if (testflagkey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========== Col 40: light conditions =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            lightcondkey = serv.QueryKeyOfName("LightConditions", strng);
+            if (lightcondkey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========== Col 41: discriminator threshold table =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            dttablekey = serv.QueryKeyOfName("DiscriminatorThresholdTable", strng);
+            if (dttablekey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========== Col 42: trigger delay table =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            triggerdelaytablekey = serv.QueryKeyOfName("TriggerDelayTable", strng);
+            if (triggerdelaytablekey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========== Col 43,44: Telescope RA and Dec sent to drive =========
+            i++;
+            i++;
+
+            // ========== Col 45: Calibration Script =========
+	    strng = (*array)[i++]->GetName();
+            if (version>=200411130 && version<=200510250)
+	    {
+		delete array;
+		continue;
+	    }
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            calibrationscriptkey = serv.QueryKeyOfName("CalibrationScript", strng);
+            if (calibrationscriptkey<0)
+            {
+                delete array;
+                continue;
+            }
+
+        }
+
+        Int_t observationmodekey=1;
+        if (version>=200603300)
+        {
+            // ========== Col 46: Observation Mode =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            observationmodekey = serv.QueryKeyOfName("ObservationMode", strng);
+            if (observationmodekey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========== Col 47-54: Source RA and Dec, DT's and IPR =========
+            for (int n=0 ; n<7 ; n++)
+            {
+                i++;
+            }
+	    strng = (*array)[i++]->GetName();
+	    if (version<=200809120)
+	    {
+		delete array;
+		continue;
+	    }
+        }
+
+        Int_t sumtriggerflagkey=1;
+        if (version>=200812040)
+        {
+            // ========= Col 55: SumTrigger flag =========
+	    strng = (*array)[i++]->GetName();
+            if (version<=200906160)
+	    {
+		delete array;
+		continue;
+	    }
+	    if (strng.Contains("???"))
+                strng="n/a";
+
+            sumtriggerflagkey = serv.QueryKeyOfName("SumTriggerFlag", strng);
+            if (sumtriggerflagkey<0)
+            {
+                delete array;
+                continue;
+            }
+        }
+
+        Int_t l3triggerkey=1;
+        Int_t cyclekey=1;
+        Int_t pikey=1;
+        Int_t workinggroupkey=1;
+	Int_t proposalkey=1;
+        Float_t l3trigrate=0;
+        TString wheelpos1 = "NULL";
+        TString wheelpos2 = "NULL";
+        if (version>=200906250)
+        {
+            // for MAGIC 2: additional columns wheel_pos1 and ~2
+
+            if (telnumber == 2)
+            {
+		strng = (*array)[i++]->GetName();
+                wheelpos1 = strng.Data();
+		strng = (*array)[i++]->GetName();
+                wheelpos2 = strng.Data();
+            }
+
+	    // ========= Col 56: L3 trigger table =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???") || strng.Contains("na") || strng.Contains("Unknown"))
+                strng="n/a";
+
+            l3triggerkey = serv.QueryKeyOfName("L3TriggerTable", strng);
+            if (l3triggerkey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========= Col 57: L3 trigger rate =========
+	    strng = (*array)[i++]->GetName();
+            l3trigrate = atof(strng.Data());
+
+            // ========= Col 58: Cycle =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???") || strng.Contains("na"))
+                strng="n/a";
+
+            cyclekey = serv.QueryKeyOfName("Cycle", strng);
+            if (cyclekey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========= Col 59: PI =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???") || strng.Contains("na"))
+                strng="n/a";
+
+            pikey = serv.QueryKeyOfName("PI", strng);
+            if (pikey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========= Col 60: Working group =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???") || strng.Contains("na"))
+                strng="n/a";
+
+            workinggroupkey = serv.QueryKeyOfName("WorkingGroup", strng);
+            if (workinggroupkey<0)
+            {
+                delete array;
+                continue;
+            }
+
+            // ========= Col 61: Proposal =========
+	    strng = (*array)[i++]->GetName();
+            if (strng.Contains("???") || strng.Contains("na"))
+                strng="n/a";
+
+            proposalkey = serv.QueryKeyOfName("Proposal", strng);
+            if (proposalkey<0)
+            {
+                delete array;
+                continue;
+            }
+        }
+	delete array;
+
+
+        // ================================================================
+        // ========== Data read from file now access the database =========
+        // ================================================================
+
+        //assemble the query that is needed to insert the values of this run
+        TString query;
+        query += Form("fTelescopeNumber=%d, ", telnumber);
+        query += Form("fRunNumber=%d, ",       runnumber);
+        query += Form("fFileNumber=%d, ",      filenumber);
+        query += Form("fRunTypeKEY=%d, ",      runtype);
+        query += Form("fProjectKEY=%d, ",      projkey);
+        query += Form("fSourceKEY=%d, ",       sourcekey);
+        query += Form("fNumEvents=%d, ",       evtno);
+        query += Form("fRunStart=\"%s %s\", ", startdate.Data(), starttime.Data());
+        query += Form("fRunStop=\"%s %s\", ",  stopdate.Data(),  stoptime.Data());
+        query += Form("fL1TriggerTableKEY=%d, ",    l1triggerkey);
+        query += Form("fL2TriggerTableKEY=%d, ",    l2triggerkey);
+        query += Form("fTestFlagKEY=%d, ",          testflagkey);
+        query += Form("fCalibrationScriptKEY=%d, ", calibrationscriptkey);
+        query += Form("fTriggerDelayTableKEY=%d, ", triggerdelaytablekey);
+        query += Form("fDiscriminatorThresholdTableKEY=%d, ", dttablekey);
+        query += Form("fLightConditionsKEY=%d, ",   lightcondkey);
+        query += Form("fHvSettingsKEY=%d, ",        hvkey);
+        query += Form("fObservationModeKEY=%d, ",   observationmodekey);
+        query += Form("fSumTriggerFlagKEY=%d, ",    sumtriggerflagkey);
+        query += Form("fL3TriggerTableKEY=%d, ",    l3triggerkey);
+        query += Form("fCycleKEY=%d, ",             cyclekey);
+        query += Form("fPIKEY=%d, ",                pikey);
+        query += Form("fWorkingGroupKEY=%d, ",      workinggroupkey);
+        query += Form("fProposalKEY=%d, ",          proposalkey);
+        if (!TMath::IsNaN(zd) && TMath::Finite(zd))
+            query += Form("fZenithDistance=%d, ", TMath::Nint(zd));
+        if (!TMath::IsNaN(az) && TMath::Finite(az))
+            query += Form("fAzimuth=%d, ", TMath::Nint(az));
+        if (!TMath::IsNaN(storerate) && TMath::Finite(storerate))
+            query += Form("fDaqStoreRate=%d, ", TMath::Nint(storerate));
+        if (!TMath::IsNaN(daqrate) && TMath::Finite(daqrate))
+            query += Form("fDaqTriggerRate=%d, ", TMath::Nint(daqrate));
+        if (!TMath::IsNaN(trigrate) && TMath::Finite(trigrate))
+            query += Form("fMeanTriggerRate=%d, ", TMath::Nint(trigrate));
+        if (!TMath::IsNaN(l2prrate) && TMath::Finite(l2prrate))
+            query += Form("fL2RatePresc=%d, ", TMath::Nint(l2prrate));
+        if (!TMath::IsNaN(l2uprate) && TMath::Finite(l2uprate))
+            query += Form("fL2RateUnpresc=%d, ", TMath::Nint(l2uprate));
+        if (!TMath::IsNaN(l3trigrate) && TMath::Finite(l3trigrate))
+            query += Form("fL3TriggerRate=%d, ", TMath::Nint(l3trigrate));
+	query += Form("fWheelPos1=%s, ", wheelpos1.Data());
+	query += Form("fWheelPos2=%s, ", wheelpos2.Data());
+        query += "fMagicNumberKEY=1, fExcludedFDAKEY=1";
+
+        cnt++;
+
+        //send query, add dataset to DB
+        if (serv.Insert("RunData", query)==kFALSE)
+            return -1;
+
+        TString query2=Form("fTelescopeNumber=%d, fRunNumber=%d, fFileNumber=%d, "
+                            "fPriority=%d, fTimingCorrection='1970-01-01 00:00:00', fCompmux='1970-01-01 00:00:00'",
+                            telnumber, runnumber, filenumber, runnumber);
+        if (testflagkey==3)
+            query2+=" , fDataCheckDone='1970-01-01 00:00:00'";
+
+        //create entry in table RunProcessStatus for this runnumber
+        if (serv.Insert("RunProcessStatus", query2)==kFALSE)
+            return -1;
+    }
+
+    return cnt;
+}
+
+// This tool will work from Period017 (2004_05_17) on...
+int filldotrun(const TString path="/home/lapalma/transfer/ccdata", Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "filldotrun" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Search Path: " << path << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    if (path.EndsWith(".run"))
+    {
+        cout << path(TRegexp("CC_.*.run", kFALSE)) << flush;
+        Int_t n = insert(serv, dummy, path);
+        cout << " <" << n << "> " << (dummy?"DUMMY":"") << endl;
+
+        return n<0 ? 2 : 1;
+    }
+
+    MDirIter Next(path, "CC_*.run", -1);
+    while (1)
+    {
+        TString name = Next();
+        if (name.IsNull())
+            break;
+
+        cout << " * " << name(TRegexp("CC_.*.run", kFALSE)) << endl;
+        Int_t n = insert(serv, dummy, name);
+        cout << "   <" << n << "> " << (dummy?"DUMMY":"") << endl;
+
+        if (n<0)
+            return 2;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillganymed.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillganymed.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillganymed.C	(revision 17960)
@@ -0,0 +1,177 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillganymed.C
+// =============
+//
+// This macro is used to read the ganymed-output files.
+// These files are automatically called ganymed00000.root.
+// From MAlphaFitter and the Status Display the results from ganymed are
+// extracted an inserted into the database, where they are stored in the table
+// Ganymed.
+// The dataset number is extracted from the filename.
+//
+// Usage:
+//  .x fillganymed.C("/magic/data/ganymed/0000/0001/ganmymed0001.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillganymed.C+\(\"filename\"\,kFALSE\) 2>&1 | tee file.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TRegexp.h>
+
+#include <TH1.h>
+#include <TGraph.h>
+#include <TProfile.h>
+#include <TFile.h>
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+
+#include "MSQLMagic.h"
+
+#include "MStatusArray.h"
+#include "MGeomCamMagic.h"
+#include "MAlphaFitter.h"
+
+using namespace std;
+
+int Process(MSQLMagic &serv, TString fname, Bool_t dummy)
+{
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+    //get excess, signal, background events and the scale factor from MAlphaFitter
+    MAlphaFitter *fit;
+    file.GetObject("MAlphaFitter", fit);
+
+    if (!fit)
+    {
+        cout << "WARNING - Reading of MAlphaFitter failed." << endl;
+        return 2;
+    }
+
+    Int_t exc = (Int_t)fit->GetEventsExcess();
+    Int_t sig = (Int_t)fit->GetEventsSignal();
+    Int_t bgd = (Int_t)fit->GetEventsBackground();
+    Float_t S = fit->GetSignificance();
+    TString signif = Form("%5.1f", S);
+    Float_t f = fit->GetScaleFactor();
+    TString scale = Form("%5.2f", f);
+
+    //get effective ontime from the status display
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
+        return 2;
+    }
+
+    TH1D *vstime = (TH1D*)arr.FindObjectInCanvas("Theta",  "TH1D", "OnTime");
+    if (!vstime)
+    {
+        cout << "WARNING - Reading of Theta failed." << endl;
+        return 2;
+    }
+
+
+    Int_t tm = (Int_t)vstime->Integral();
+
+    //get dataset number from filename
+    TString dataset = fname(TRegexp("ganymed[0-9]+[.]root$"));
+    if (dataset.IsNull())
+    {
+        cout << "WARNING - Could get dataset# from filename: " << fname << endl;
+        return 2;
+    }
+
+    Int_t ds = atoi(dataset.Data()+8);
+
+    cout << "Dataset #" << ds << endl;
+    cout << "  Excess     Events:  " << exc    << endl;
+    cout << "  Background Events:  " << bgd    << endl;
+    cout << "  Signal     Events:  " << sig    << endl;
+    cout << "  Significance:       " << signif << endl;
+    cout << "  Scale Factor:       " << scale  << endl;
+    cout << "  Total eff. on-time: " << tm     << "s = " << tm/3600. << "h" << endl;
+
+//    cout << "  Excess       Rate:  " << exc*60/tm << " evts/min"  << endl;
+//    cout << "  Background   Rate:  " << bgd*60/tm << " evts/min"  << endl;
+//    cout << "  Significance Rate:  " << S/TMath::Sqrt(tm/3600.) << " sigma/sqrt(h)" << endl;
+
+    TString vars =  Form(" fDataSetNumber=%d, "
+                         " fExcessEvents=%d, "
+                         " fBackgroundEvents=%d, "
+                         " fSignalEvents=%d, "
+                         " fSignificance=%s, "
+                         " fScaleFactor=%s, "
+                         " fEffOnTime=%d ",
+                         ds, exc, bgd, sig,
+                         signif.Data(),
+                         scale.Data(), tm);
+
+
+    TString where = Form("fDataSetNumber=%d", ds);
+
+    return serv.InsertUpdate("Ganymed", vars, where) ? 1 : 2;
+}
+
+int fillganymed(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillganymed" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    return Process(serv, fname, dummy);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillmccalib.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillmccalib.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillmccalib.C	(revision 17960)
@@ -0,0 +1,305 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!   Author(s): Daniel Hoehne-Moench, 01/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillmccalib.C
+// ===========
+//
+// This macro is used to read the calibration-/callisto-output files.
+// These files are automatically called calib00000.root.
+//
+// From this file the MBadPixelsCam and the MGeomCam is extracted. If
+// the geometry isn't found MGeomCamMagic is used as a default.
+// The bad pixel information and other information, extracted from the status
+// display, is inserted into the database in the table MCCalibration, which
+// stores the results from the calibration.
+// The corresponding sequence number is extracted from the filename...
+//
+// Usage:
+//  .x fillmccalib.C("/magic/montecarlo/callisto/0002/00048270/calib00028270.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillmccalib.C+\(\"filename\"\,kFALSE\)
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+
+#include <TRegexp.h>
+
+#include <TH1.h>
+
+#include <TFile.h>
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+
+#include "MSQLServer.h"
+#include "MSQLMagic.h"
+
+#include "MStatusArray.h"
+#include "MHCamera.h"
+#include "MSequence.h"
+#include "MGeomCamMagic.h"
+#include "MBadPixelsCam.h"
+
+using namespace std;
+
+int Process(MSQLMagic &serv, TString fname)
+{
+    //getting number of unsuitable, unreliable and isolated pixel
+    MBadPixelsCam badpix;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+    if (badpix.Read("MBadPixelsCam")<=0)
+    {
+        cout << "ERROR - Reading of MBadPixelsCam failed." << endl;
+        return 2;
+    }
+
+    MGeomCamMagic def;
+
+    MGeomCam *geom = (MGeomCam*)file.Get("MGeomCam");
+    if (!geom)
+    {
+        cout << "WARNING - Reading of MGeomCam failed... using default <MGeomCamMagic>" << endl;
+        geom = &def;
+    }
+
+    cout << "Camera Geometry: " << geom->ClassName() << endl;
+
+    const Short_t unsin  = badpix.GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, geom, 0);
+    const Short_t unsout = badpix.GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, geom, 1);
+
+    const Short_t unrin  = badpix.GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, geom, 0);
+    const Short_t unrout = badpix.GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, geom, 1);
+
+    const Short_t isoin  = badpix.GetNumIsolated(*geom, 0);
+    const Short_t isoout = badpix.GetNumIsolated(*geom, 1);
+
+    const Short_t clumax = badpix.GetNumMaxCluster(*geom);
+
+    if (unsin<0 || unsout<0 || unrin<0 || unrout<0 || isoin<0 || isoout<0 || clumax<0)
+    {
+        cout << "ERROR - one of the pixel values < 0." << endl;
+        return 2;
+    }
+
+    //Getting values from the status display
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        cout << "ERROR - could not read MStatusArray." << endl;
+        return 2;
+    }
+
+    TH1 *h;
+
+    //getting the mean and rms from the arrival time (inner cam)
+    h = (TH1*)arr.FindObjectInCanvas("HRelTimeHiGainArea0", "TH1F", "Time");
+    if (!h)
+    {
+        cout << "ERROR - Could not find histogram HRelTimeHiGainArea0." << endl;
+        return 2;
+    }
+
+    TString meaninner = Form("%5.1f", h->GetMean());
+    TString rmsinner  = Form("%6.2f", h->GetRMS());
+
+    //getting the mean and rms from the arrival time (outer cam)
+    h = (TH1*)arr.FindObjectInCanvas("HRelTimeHiGainArea1", "TH1F", "Time");
+    if (!h)
+    {
+        cout << "ERROR - Could not find histogram HRelTimeHiGainArea1." << endl;
+        return 2;
+    }
+
+    TString meanouter = Form("%5.1f", h->GetMean());
+    TString rmsouter  = Form("%6.2f", h->GetRMS());
+
+    //Getting conversion factors
+    MHCamera *c = (MHCamera*)arr.FindObjectInCanvas("TotalConvPhe", "MHCamera", "Conversion");
+    if (!c)
+    {
+        cout << "ERROR - Could not find MHCamera TotalConv." << endl;
+        return 2;
+    }
+
+    TArrayI inner(1), outer(1);
+    inner[0] = 0;
+    outer[0] = 1;
+
+    Int_t s0[] = { 1, 2, 3, 4, 5, 6 };
+
+    Stat_t meanconvi = c->GetMeanSectors(TArrayI(6, s0), inner);
+    Stat_t meanconvo = c->GetMeanSectors(TArrayI(6, s0), outer);
+    TString meanconvinner=Form("%6.3f", meanconvi);
+    TString meanconvouter=Form("%6.3f", meanconvo);
+
+    //Getting relative charge rms
+    c = (MHCamera*)arr.FindObjectInCanvas("RMSperMean", "MHCamera", "FitCharge");
+    if (!c)
+    {
+        cout << "ERROR - Could not find MHCamera RMSperMean in FitCharge." << endl;
+        return 2;
+    }
+
+    Stat_t relrmsi = c->GetMedianSectors(TArrayI(6, s0), inner);
+    Stat_t relrmso = c->GetMedianSectors(TArrayI(6, s0), outer);
+    TString relrmsinner=Form("%6.3f", relrmsi);
+    TString relrmsouter=Form("%6.3f", relrmso);
+
+    //Getting relative charge rms
+    c = (MHCamera*)arr.FindObjectInCanvas("NumPhes", "MHCamera", "FitCharge");
+    if (!c)
+    {
+        cout << "ERROR - Could not find MHCamera NumPhes in FitCharge." << endl;
+        return 2;
+    }
+
+    Stat_t numphei = c->GetMedianSectors(TArrayI(6, s0), inner);
+    Stat_t numpheo = c->GetMedianSectors(TArrayI(6, s0), outer);
+    TString numpheinner=Form("%5.1f", numphei);
+    TString numpheouter=Form("%5.1f", numpheo);
+
+    MSequence seq;
+    if (seq.Read("sequence[0-9]{8}[.]txt|MSequence")<=0)
+    {
+        cout << "ERROR - Could not find sequence in file: " << fname << endl;
+        return 2;
+    }
+    if (!seq.IsValid())
+    {
+        cout << "ERROR - Sequence read from file inavlid: " << fname << endl;
+        return 2;
+    }
+
+    //getting the ratio of calibration events used
+    h = (TH1*)arr.FindObjectInCanvas("ArrTm;avg", "MHCamera", "ArrTm");
+    if (!h)
+    {
+        cout << "ERROR - Could not find histogram ArrTime;avg." << endl;
+        return 2;
+    }
+
+    UInt_t nevts = TMath::Nint(h->GetEntries());
+
+    //Num of calibration events is 5000 for all MC C runs
+    UInt_t calevts = 5000;
+
+    Float_t ratiocalib = 100.*nevts/calevts;
+
+    TString ratiocal = Form("%.1f", ratiocalib);
+
+    cout << "Sequence " << seq.GetSequence() << endl;
+    cout << "  Unsuitable: (i/o)  " << Form("%3d %3d", (int)unsin, (int)unsout) << endl; // Unbrauchbar
+    cout << "  Unreliable: (i/o)  " << Form("%3d %3d", (int)unrin, (int)unrout) << endl; // Unzuverlaessig
+    cout << "  Isolated:   (i/o)  " << Form("%3d %3d", (int)isoin, (int)isoout) << endl; // Isolated (unbrauchbar)
+    cout << "  Max.Cluster:       " << Form("%3d", (int)clumax)                 << endl; // Max Cluster
+    cout << "  Arr Time inner:     " << meaninner << " +- " << rmsinner  << endl;
+    cout << "  Arr Time outer:     " << meanouter << " +- " << rmsouter  << endl;
+    cout << "  Mean Conv inner:     " << meanconvinner << endl;
+    cout << "  Mean Conv outer:     " << meanconvouter << endl;
+    cout << "  Rel.charge rms in:   " << relrmsinner << endl;
+    cout << "  Rel.charge rms out:  " << relrmsouter << endl;
+    cout << "  Med. num phe inner: " << numpheinner << endl;
+    cout << "  Med. num phe outer: " << numpheouter << endl;
+    cout << "  Ratio Calib Evts:   " << ratiocal << endl;
+
+    //inserting or updating the information in the database
+    TString vars =
+        Form(" fSequenceFirst=%d, "
+             " fUnsuitableInner=%d, "
+             " fUnsuitableOuter=%d, "
+             " fUnreliableInner=%d, "
+             " fUnreliableOuter=%d, "
+             " fIsolatedInner=%d, "
+             " fIsolatedOuter=%d, "
+             " fIsolatedMaxCluster=%d, "
+             " fArrTimeMeanInner=%s, "
+             " fArrTimeRmsInner=%s, "
+             " fArrTimeMeanOuter=%s, "
+             " fArrTimeRmsOuter=%s, "
+             " fConvFactorInner=%s, "
+             " fConvFactorOuter=%s, "
+             " fRatioCalEvts=%s, "
+             " fRelChargeRmsInner=%s, "
+             " fRelChargeRmsOuter=%s, "
+             " fMedNumPheInner=%s, "
+             " fMedNumPheOuter=%s ",
+             seq.GetSequence(),
+             (int)unsin, (int)unsout, (int)unrin,
+             (int)unrout, (int)isoin, (int)isoout, (int)clumax,
+             meaninner.Data(), rmsinner.Data(),
+             meanouter.Data(), rmsouter.Data(),
+             meanconvinner.Data(), meanconvouter.Data(),
+             ratiocal.Data(),
+             relrmsinner.Data(), relrmsouter.Data(),
+             numpheinner.Data(), numpheouter.Data()
+            );
+
+    TString where = Form("fSequenceFirst=%d", seq.GetSequence());
+
+    return serv.InsertUpdate("MCCalibration", vars, where) ? 1 : 2;
+}
+
+int fillmccalib(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillmccalib" << endl;
+    cout << "---------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    return Process(serv, fname);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillmcsignal.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillmcsignal.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillmcsignal.C	(revision 17960)
@@ -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, 04/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 04/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!   Author(s): Daniel Hoehne-Moench, 01/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillmcsignal.C
+// ============
+//
+// This macro is used to read the calibration-/callisto-output files
+// signal00000.root.
+//
+// From this file the mean pedrms, the mean signal and the pulse position
+// for the inner and outer camera is extracted and inserted into the database
+// in the table MCCalibration, where the results of callisto are stored.
+// The sequence number is extracted from the filename.
+//
+// Usage:
+//   .x fillmcsignal.C("/magic/montecarlo/callisto/0002/00028270/signal00028270.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillmcsignal.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillsignal.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TRegexp.h>
+
+#include <TFile.h>
+#include <TGraph.h>
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+
+#include "MSQLServer.h"
+#include "MSQLMagic.h"
+
+#include "MStatusArray.h"
+#include "MSequence.h"
+#include "MHCamera.h"
+#include "MHVsTime.h"
+
+#include "MCalibrationPulseTimeCam.h"
+#include "MCalibrationPix.h"
+
+using namespace std;
+
+int Process(MSQLMagic &serv, TString fname)
+{
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+    TString meanextpulpos("NULL");
+    TString rmsextpulpos("NULL");
+
+    MCalibrationPulseTimeCam *pt;
+    file.GetObject("MCalibrationPulseTimeCam", pt);
+    if (pt)
+    {
+        Double_t meanextpul = pt->GetAverageArea(0).GetHiGainMean();
+        Double_t rmsextpul  = pt->GetAverageArea(0).GetHiGainRms();
+
+        if (meanextpul>=0 || rmsextpulpos>=0)
+        {
+            meanextpulpos.Form("%6.2f", meanextpul);
+            rmsextpulpos.Form("%6.2f", rmsextpul);
+        }
+    }
+
+
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
+        return 2;
+    }
+
+    MHCamera *cam = (MHCamera*)arr.FindObjectInCanvas("PedRMS;avg", "MHCamera", "PedRMS");
+    if (!cam)
+    {
+        cout << "ERROR - Reading of PedRMS;avg failed." << endl;
+        return 2;
+    }
+
+    MHCamera *cal = (MHCamera*)arr.FindObjectInCanvas("CalPos;avg", "MHCamera", "CalPos");
+    MHCamera *pul = (MHCamera*)arr.FindObjectInCanvas("PulsePos;avg", "MHCamera", "PulsePos");
+    if (!pul)
+    {
+        cout << "ERROR - Reading of PulsePos;avg failed." << endl;
+        return 2;
+    }
+
+    MSequence seq;
+    if (seq.Read("sequence[0-9]{8}[.]txt|MSequence")<=0)
+    {
+        cout << "ERROR - Could not find sequence in file: " << fname << endl;
+        return 2;
+    }
+    if (!seq.IsValid())
+    {
+        cout << "ERROR - Sequence read from file inavlid: " << fname << endl;
+        return 2;
+    }
+
+    TString medpuloff("NULL");
+    TString devpuloff("NULL");
+    TString medhilocal("NULL");
+    TString devhilocal("NULL");
+
+    TString query(Form("SELECT MCSequences.fAmplFadcKEY FROM MCSequences LEFT JOIN "
+                       "AmplFadc on MCSequences.fAmplFadcKEY=AmplFadc.fAmplFadcKEY "
+                       "where fSequenceFirst=%d;",seq.GetSequence()));
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+
+    TSQLRow *row = res->Next();
+    if (!row)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+    TString epochkey  = (*row)[0];
+    Int_t epoch = atoi(epochkey.Data());
+
+    delete res;
+
+    if (epoch!=1)
+    {
+        MHCamera *hilooff = (MHCamera*)arr.FindObjectInCanvas("HiLoOff;avg", "MHCamera", "HiLoOff");
+        if (!hilooff)
+        {
+            cout << "ERROR - Reading of HiLoOff failed." << endl;
+            return 2;
+        }
+
+        MHCamera *hilocal = (MHCamera*)arr.FindObjectInCanvas("HiLoCal;avg", "MHCamera", "HiLoCal");
+        if (!hilocal)
+        {
+            cout << "ERROR - Reading of HiLoCal failed." << endl;
+            return 2;
+        }
+
+        medpuloff.Form("%7.4f",  hilooff->GetMedian());
+        devpuloff.Form("%7.4f",  hilooff->GetDev());
+        medhilocal.Form("%6.2f", hilocal->GetMedian());
+        devhilocal.Form("%6.2f", hilocal->GetDev());
+    }
+
+    TArrayI inner(1);
+    inner[0] = 0;
+
+    TArrayI outer(1);
+    outer[0] = 1;
+
+    Int_t s0[] = { 1, 2, 3, 4, 5, 6 };
+
+    Stat_t meanrmsi = cam->GetMeanSectors(TArrayI(6, s0), inner);
+    Stat_t meanrmso = cam->GetMeanSectors(TArrayI(6, s0), outer);
+
+    if (meanrmsi<0 || meanrmso<0)
+    {
+        cout << "ERROR - MeanPedRMS inner or outer < 0 " << endl;
+        cout << "MeanPedRMS inner " << meanrmsi << endl;
+        cout << "MeanPedRMS outer " << meanrmso << endl;
+        return 2;
+    }
+
+    TString meanrmsinner=Form("%6.2f", meanrmsi);
+    TString meanrmsouter=Form("%6.2f", meanrmso);
+
+    cam = (MHCamera*)arr.FindObjectInCanvas("Interp'd;avg", "MHCamera", "Interp'd");
+    if (!cam)
+    {
+        cout << "ERROR - Reading of Interp'd;avg failed." << endl;
+        return 2;
+    }
+
+    Stat_t meansigi = cam->GetMeanSectors(TArrayI(6, s0), inner);
+    Stat_t meansigo = cam->GetMeanSectors(TArrayI(6, s0), outer);
+
+    if (meansigi<0 || meansigo<0)
+    {
+        cout << "ERROR - MeanInterp'd inner or outer < 0 " << endl;
+        cout << "MeanInterp'd inner " << meansigi << endl;
+        cout << "MeanInterp'd outer " << meansigo << endl;
+        return 2;
+    }
+
+    TString meansiginner =Form("%6.2f", meansigi);
+    TString meansigouter =Form("%6.2f", meansigo);
+
+    TString calpos = cal ? Form("%5.1f", cal->GetMean()) : "NULL";
+
+    if (pul->GetMean()<0 || pul->GetRMS()<0)
+    {
+        cout << "ERROR - PulsePos'd mean or rms < 0 " << endl;
+        cout << "PulsePos'd mean " << pul->GetMean() << endl;
+        cout << "PulsePos'd rms  " << pul->GetRMS() << endl;
+        return 2;
+    }
+
+    TString meanpulpos = Form("%6.2f", pul->GetMean());
+    TString rmspulpos  = Form("%6.2f", pul->GetRMS());
+
+    cam = (MHCamera*)arr.FindObjectInCanvas("Unsuitable;avg", "MHCamera", "Unsuitable");
+    if (!cam)
+    {
+        cout << "ERROR - Reading of Unsuitable;avg failed." << endl;
+        return 2;
+    }
+
+    Int_t unsuitable50 = cam->GetNumBinsAboveThreshold(0.50);
+    Int_t unsuitable01 = cam->GetNumBinsAboveThreshold(0.01);
+
+    // *****************************************************
+
+    cout << "Sequence #" << seq.GetSequence() << endl;
+    cout << "  Mean Ped RMS inner [phe] " << meanrmsinner  << endl;
+    cout << "  Mean Ped RMS outer [phe] " << meanrmsouter  << endl;
+    cout << "  Mean Signal  inner [phe] " << meansiginner  << endl;
+    cout << "  Mean Signal  outer [phe] " << meansigouter  << endl;
+    cout << "  Mean extracted  PulsePos " << meanextpulpos << " +- " << rmsextpulpos << endl;
+    cout << "  Mean calibrated PulsePos " << meanpulpos    << " +- " << rmspulpos    << endl;
+    cout << "  Mean calib pulse pos     " << calpos << endl;
+    cout << "  Lo-Hi gain offset:       " << medpuloff    << " +- " << devpuloff    << endl;
+    cout << "  Hi/Lo gain ratio:        " << medhilocal   << " +- " << devhilocal   << endl;
+    cout << "  Unsuitable > 50%:       " << setw(6) << unsuitable50 << endl;
+    cout << "  Unsuitable >  1%:       " << setw(6) << unsuitable01 << endl;
+    cout << endl;
+
+    //build query and insert information into the database
+    // here only a update query is built, as this macro is exexuted after
+    // the macro fillmccalib.C in the script fillmccallisto
+    // and so the table MCCalibration is always updated
+    TString vars = Form(" fMeanPedRmsInner=%s,    fMeanPedRmsOuter=%s,  "
+                         " fMeanSignalInner=%s,   fMeanSignalOuter=%s,  "
+                         " fPulsePosMean=%s,      fPulsePosRms=%s,      "
+                         " fPulsePosCheckMean=%s, fPulsePosCheckRms=%s, "
+                         " fPulsePosOffMed=%s,    fPulsePosOffDev=%s,   "
+                         " fHiLoGainRatioMed=%s,  fHiLoGainRatioDev=%s, "
+                         " fUnsuitable50=%d,      fUnsuitable01=%d,     "
+                         " fPulsePosCalib=%s ",
+                         meanrmsinner.Data(),  meanrmsouter.Data(),
+                         meansiginner.Data(),  meansigouter.Data(),
+                         meanpulpos.Data(),    rmspulpos.Data(),
+                         meanextpulpos.Data(), rmsextpulpos.Data(),
+                         medpuloff.Data(),     devpuloff.Data(),
+                         medhilocal.Data(),    devhilocal.Data(),
+                         unsuitable50,         unsuitable01,
+                         calpos.Data());
+
+    TString where = Form("fSequenceFirst=%d", seq.GetSequence());
+    return serv.Update("MCCalibration", vars, where) ? 1 : 2;
+
+}
+
+int fillmcsignal(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillmcsignal" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    //process file
+    return Process(serv, fname);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillmcstar.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillmcstar.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillmcstar.C	(revision 17960)
@@ -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, 05/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!   Author(s): Daniel Hoehne-Moench, 01/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillmcstar.C
+// ==========
+//
+// This macro is used to read the star-output files.
+// These files are automatically called star00000000.root.
+// From these files the number of islands and a parameter describing the
+// inhomogeneity are extracted from the status display.
+// The sequence number is extracted from the filename.
+//
+// Usage:
+//   .x fillmcstar.C("/magic/montecarlo/star/0002/00028270/star00028270.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillmcstar.C+\(\"filename\"\,kFALSE\)
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TFile.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TGraph.h>
+
+#include "MSQLMagic.h"
+
+#include "MHCamera.h"
+#include "MHMuonPar.h"
+#include "MSequence.h"
+#include "MStatusArray.h"
+#include "MBadPixelsCam.h"
+#include "MHEffectiveOnTime.h"
+
+using namespace std;
+
+bool CheckGraph(const TGraph *g)
+{
+    return g && g->GetN()>0 && !(g->GetN()==1 && g->GetX()[0]==0);
+}
+
+int Process(MSQLMagic &serv, TString fname)
+{
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
+        return 2;
+    }
+
+    MHCamera *hevts = (MHCamera*)arr.FindObjectInCanvas("Sparkless;avg", "MHCamera", "Sparkless");
+    if (!hevts)
+    {
+        cout << "ERROR - Reading of Sparkless failed." << endl;
+        return 2;
+    }
+
+    MHCamera *hsparks = (MHCamera*)arr.FindObjectInCanvas("Sparks;avg", "MHCamera", "Sparks");
+    if (!hsparks)
+    {
+        cout << "ERROR - Reading of Sparks failed." << endl;
+        return 2;
+    }
+
+    TH2F *hcog = (TH2F*)arr.FindObjectInCanvas("Center", "TH2F", "MHHillas");
+    if (!hcog)
+    {
+        cout << "ERROR - Reading of MHHillas failed." << endl;
+        return 2;
+    }
+
+    MHMuonPar *hmuon = (MHMuonPar*)arr.FindObjectInCanvas("MHMuonPar", "MHMuonPar", "MHMuonPar");
+    if (!hmuon)
+    {
+        cout << "ERROR - Reading of MHMuon failed." << endl;
+        return 2;
+    }
+
+    Double_t val[6];
+    for (int x=1; x<hcog->GetNbinsX(); x++)
+        for (int y=1; y<hcog->GetNbinsY(); y++)
+        {
+            Stat_t px = hcog->GetXaxis()->GetBinCenter(x);
+            Stat_t py = hcog->GetYaxis()->GetBinCenter(y);
+            Int_t  i  = (TMath::Nint(3*TMath::ATan2(px,py)/TMath::Pi())+6)%6;
+            val[i] += hcog->GetBinContent(x, y);
+        }
+
+    Float_t inhom = TMath::RMS(6, val)*6/hcog->GetEntries()*100;
+    TString inhomogen = Form("%5.1f", inhom);
+
+    Int_t   num = (int)hmuon->GetEntries();
+
+    Float_t ratiodatamc = (hmuon->GetMeanSize()/7216)*100;
+    TString ratio = Form("%5.1f", ratiodatamc);
+
+    TH1 *h = (TH1*)arr.FindObjectInCanvas("Islands", "TH1F", "MHImagePar");
+    if (!h)
+    {
+        cout << "ERROR - Reading of Islands failed." << endl;
+        return 2;
+    }
+
+    TString islands = Form("%6.2f", h->GetMean());
+
+    Int_t numsparks = (int)hsparks->GetEntries();
+    Int_t numevents = (int)hevts->GetEntries();
+
+    MSequence seq;
+    if (seq.Read("sequence[0-9]{8}[.]txt|MSequence")<=0)
+    {
+        cout << "ERROR - Could not find sequence in file: " << fname << endl;
+        return 2;
+    }
+    if (!seq.IsValid())
+    {
+        cout << "ERROR - Sequence read from file inavlid: " << fname << endl;
+        return 2;
+    }
+
+    cout << "Sequence " << seq.GetSequence() << endl;
+    cout << "  Inhomogeneity            " << inhomogen << endl;
+    cout << "  Island Quality           " << islands   << endl;
+    cout << "  Muon Number              " << num       << endl;
+    cout << "  # of Events (w/o sparks) " << numevents << endl;
+    cout << "  # of Sparks              " << numsparks << endl;
+
+    TString vars = Form(" fSequenceFirst=%d, "
+                        " fMeanNumberIslands=%s,"
+                        " fMuonNumber=%d,"
+                        " fNumEvts=%d, "
+                        " fNumSparks=%d, "
+                        " fInhomogeneity=%s ",
+                        seq.GetSequence(),
+                        islands.Data(),
+                        num,
+                        numevents, numsparks,
+                        inhomogen.Data());
+
+    TString where = Form("fSequenceFirst=%d", seq.GetSequence());
+
+    return serv.InsertUpdate("MCStar", vars, where) ? 1 : 2;
+}
+
+int fillmcstar(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillmcstar" << endl;
+    cout << "--------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    return Process(serv, fname);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/filloptical.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/filloptical.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/filloptical.C	(revision 17960)
@@ -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): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// filloptical.C
+// =============
+//
+// This macro is used to read the files from KVA containing the results from
+// the optical observations.
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b filloptical.C+\(\"filename\"\,kFALSE\) 
+//
+// Make sure, that database and password are corretly set.
+//
+// Returns 1 in case of success.
+// Returns 2 in case of invalid file or line in file.
+// Returns 3 in case of a missing object name in the database.
+// Returns 4 in case of a telescope line with more or less than 2 arguments
+// Returns 5 in case of a timestamp line with more or less than 4 arguments
+// Returns 6 in case of a object line with more or less than 10 arguments
+//
+///////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TVector3.h>
+
+#include <TRegexp.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MDirIter.h"
+#include "MSQLServer.h"
+#include "MSQLMagic.h"
+
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MAstroSky2Local.h"
+
+using namespace std;
+
+//
+// insert the entries from this optical data file into the db
+//
+int process(MSQLMagic &serv, TString fname)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        cout << "Could not open file " << fname << endl;
+        return 0;
+    }
+
+    TRegexp regexp("^20[0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].*$", kFALSE);
+
+    Int_t numexp=0;
+    Int_t numstars=0;
+
+    TString timestamp;
+    TString exposure;
+    TString fitsfile;
+    TString object;
+    TString skylevel;
+    TString fwhm;
+    TString ellipticity;
+    TString posangle;
+    TString aperturer;
+    TString mag;
+    TString magerr;
+    TString status;
+    TString query;
+    TString select;
+    TString telescope;
+    TString telname;
+    TString ccd;
+    TString filterband;
+    TString filter;
+    TString band;
+    Double_t ra=0;
+    Double_t dec=0;
+    Double_t zd=0;
+    MTime t;
+    MObservatory obs(MObservatory::kMagic1);
+    TVector3 v;
+
+    if (fname(TRegexp("20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_[RV][_]?[12]?[.]instr", kFALSE)).IsNull())
+    {
+        cout << "Found not valid file: " << fname << endl;
+        return 2;
+    }
+
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+        {
+            cout << numstars << " objects inserted for this exposure. " << endl;
+            break;
+        }
+
+        if (line.IsNull())
+            continue;
+
+        TObjArray *arr = line.Tokenize("  ");
+
+        if (line=="KVA_Celestron_ST8  KVA_Celestron_R" ||
+            line=="KVA_Celestron_ST8  KVA_Celestron_V" ||
+            line=="Tuorla_ST1001E  Tuorla_R")
+        {
+            if (arr->GetEntries()!=2)
+            {
+                cout << "WARNING: Telescopeline with less or more than 2 arguments found in file " <<
+                    fname(TRegexp("20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_[RV][_]?[12]?[.]instr", kFALSE)) << endl;
+                cout << "Line: " << line << endl;
+                return 4;
+            }
+            telescope=(*arr)[0]->GetName();
+            telname=telescope(0,telescope.First('_'));
+            ccd=telescope(telescope.Last('_')+1, telescope.Length());
+            filterband=(*arr)[1]->GetName();
+            filter=filterband(0,filterband.Last('_'));
+            band=filterband(filterband.Last('_')+1, filterband.Length());
+            continue;
+        }
+
+        if (!line(regexp).IsNull())
+        {
+            if (arr->GetEntries()!=4)
+            {
+                cout << "WARNING: Timestampline with less or more than 4 arguments found in file " <<
+                    fname(TRegexp("20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_[RV][_]?[12]?[.]instr", kFALSE)) << endl;
+                cout << "Line: " << line << endl;
+                return 5;
+            }
+            numexp+=1;
+            if (numstars)
+                cout << numstars << " objects inserted for this exposure. " << endl;
+            numstars=0;
+            timestamp =Form("%s %s", (*arr)[0]->GetName(),(*arr)[1]->GetName());
+
+            exposure   = (*arr)[2]->GetName();
+            fitsfile = (*arr)[3]->GetName();
+            t.SetSqlDateTime(timestamp.Data());
+            continue;
+        }
+        else
+        {
+            if (arr->GetEntries()!=10)
+            {
+                cout << "WARNING: Objectline with less or more than 10 arguments found in file " <<
+                    fname(TRegexp("20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_[RV][_]?[12]?[.]instr", kFALSE)) << endl;
+                cout << "Line: " << line << endl;
+                return 6;
+            }
+
+            //calculation of zd if ra and dec are available
+            if (numstars==0)
+            {
+                select="SELECT fRightAscension, fDeclination FROM Object WHERE ";
+                select+=Form("fObjectName='%s/BL'", (*arr)[0]->GetName());
+
+                TSQLResult *res = serv.Query(select);
+                if (!res)
+                    return 2;
+
+                TSQLRow *row=res->Next();
+                if (!row)
+                {
+                    cout << "Couldn't get ZD - Query failed: " << select << endl;
+                    cout << "Position of the object is missing in the DB." << endl;
+                    return 3;
+                }
+                else
+                {
+                    ra =atof((*row)[0]);
+                    dec=atof((*row)[1]);
+                    v.SetMagThetaPhi(1, TMath::Pi()/2-(dec*TMath::DegToRad()), ra*TMath::DegToRad()*15);
+                    v *= MAstroSky2Local(t, obs);
+                    zd = v.Theta()*TMath::RadToDeg();
+                }
+                delete res;
+            }
+
+            object      = Form("%s/%s", (*arr)[0]->GetName(),(*arr)[1]->GetName());
+            skylevel    = (*arr)[2]->GetName();
+            fwhm        = (*arr)[3]->GetName();
+            ellipticity = (*arr)[4]->GetName();
+            posangle    = (*arr)[5]->GetName();
+            aperturer   = (*arr)[6]->GetName();
+            mag         = (*arr)[7]->GetName();
+            magerr      = (*arr)[8]->GetName();
+            status      = (*arr)[9]->GetName();
+            //make sure that no nonsense values enter the db
+            if (skylevel.Contains("-"))
+                skylevel = "NULL";
+            if (ellipticity.Contains("-"))
+                ellipticity = "NULL";
+            if (fwhm.Contains("-") || !fwhm.IsFloat())
+                fwhm     = "NULL";
+            if (posangle.EndsWith("-"))
+                posangle     = "NULL";
+            if (!mag.IsFloat())
+                mag      = "NULL";
+            if (!magerr.IsFloat())
+                magerr   = "NULL";
+            numstars+=1;
+        }
+        delete arr;
+
+        if (numstars!=0)
+        {
+            /*
+            cout << numexp << "th exposure: star # " << numstars << endl;
+            cout << " timestamp  : " << timestamp   << endl;
+            cout << " exposure   : " << exposure    << endl;
+            cout << " fitsfile   : " << fitsfile    << endl;
+            cout << " object     : " << object      << endl;
+            cout << " skylevel   : " << skylevel    << endl;
+            cout << " fwhm       : " << fwhm        << endl;
+            cout << " ellipticity: " << ellipticity << endl;
+            cout << " posangle   : " << posangle    << endl;
+            cout << " aperturer  : " << aperturer   << endl;
+            cout << " mag        : " << mag << " +/- " << magerr << endl;
+            cout << " status     : " << status      << endl << endl;
+            */
+
+            Int_t statuskey   = serv.QueryKeyOfName("Status", status.Data());
+            Int_t objectkey   = serv.QueryKeyOfName("Object", object.Data());
+            Int_t fitsfilekey = serv.QueryKeyOfName("FitsFile", fitsfile.Data());
+            Int_t telkey      = serv.QueryKeyOfName("Telescope", telname.Data());
+            Int_t ccdkey      = serv.QueryKeyOfName("CCD", ccd.Data());
+            Int_t bandkey     = serv.QueryKeyOfName("Band", band.Data());
+            Int_t filterkey   = serv.QueryKeyOfName("Filter", filter.Data());
+
+            query=Form("fTimeStamp='%s', fExposure=%s, fFitsFileKEY=%d, "
+                       "fObjectKEY=%d, fSkyLevel=%s, fFWHM=%s, "
+                       "fEllipticity=%s, fPosAngle=%s, fApertureRadius=%s, "
+                       "fInstrumentalMag=%s, fInstrumentalMagErr=%s, "
+                       "fStatusKEY=%d, fCCDKEY=%d, fFilterKEY=%d, "
+                       "fTelescopeKEY=%d, fBandKEY=%d, fZenithDistance=%.1f ",
+                       timestamp.Data(), exposure.Data(), fitsfilekey,
+                       objectkey, skylevel.Data(), fwhm.Data(),
+                       ellipticity.Data(), posangle.Data(), aperturer.Data(),
+                       mag.Data(), magerr.Data(), statuskey, ccdkey,
+                       filterkey, telkey, bandkey, zd);
+
+            /*
+            if (ra==0 || dec==0 || zd==0)
+                query+="NULL";
+            else
+                query+=Form("%.1f", zd);
+            */
+            if (serv.Insert("OpticalData", query)==kFALSE)
+                return 2;
+        }
+    }
+
+    cout << fname(TRegexp("20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_[RV][_]?[12]?[.]instr", kFALSE))
+        << ": " << setw(2) << numexp << " exposures." << endl << endl;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// loop over all files in this path
+//
+int filloptical(TString path, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << endl;
+    cout << "filloptical" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Search Path: " << path << endl;
+    cout << endl;
+
+    //get all runbook files in path
+    if (path.EndsWith(".instr"))
+        return process(serv, path);
+
+    //fill entries for each optical data file
+    MDirIter Next(path, "20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_*_R[_]?[12]?[.]instr", -1);
+    while (1)
+    {
+        TString name = Next();
+        if (name.IsNull())
+            break;
+
+        if (!process(serv, name))
+            return 0;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillsignal.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillsignal.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillsignal.C	(revision 17960)
@@ -0,0 +1,403 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 04/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 04/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillsignal.C
+// ============
+//
+// This macro is used to read the calibration-/callisto-output files
+// signal00000.root.
+//
+// From this file the mean pedrms, the mean signal and the pulse position
+// for the inner and outer camera is extracted and inserted into the database
+// in the table Calibration, where the results of callisto are stored.
+// The sequence number is extracted from the filename.
+//
+// Usage:
+//   .x fillsignal.C("/magic/data/callisto/0004/00047421/signal00047421.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillsignal.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillsignal.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TRegexp.h>
+
+#include <TH2.h>
+#include <TFile.h>
+#include <TGraph.h>
+#include <TSQLResult.h>
+
+#include "MSQLMagic.h"
+
+#include "MStatusArray.h"
+#include "MSequence.h"
+#include "MHCamera.h"
+#include "MHVsTime.h"
+
+#include "MCalibrationPulseTimeCam.h"
+#include "MCalibrationPix.h"
+
+using namespace std;
+
+int Process(MSQLMagic &serv, TString fname)
+{
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+    TString meanextpulpos("NULL");
+    TString rmsextpulpos("NULL");
+
+    MCalibrationPulseTimeCam *pt;
+    file.GetObject("MCalibrationPulseTimeCam", pt);
+    if (pt)
+    {
+        Double_t meanextpul = pt->GetAverageArea(0).GetHiGainMean();
+        Double_t rmsextpul  = pt->GetAverageArea(0).GetHiGainRms();
+
+        if (meanextpul>=0 || rmsextpulpos>=0)
+        {
+            meanextpulpos.Form("%6.2f", meanextpul);
+            rmsextpulpos.Form("%6.2f", rmsextpul);
+        }
+    }
+
+
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
+        return 2;
+    }
+
+    MHCamera *cam = (MHCamera*)arr.FindObjectInCanvas("PedRMS;avg", "MHCamera", "PedRMS");
+    if (!cam)
+    {
+        cout << "ERROR - Reading of PedRMS;avg failed." << endl;
+        return 2;
+    }
+
+    MHCamera *cal = (MHCamera*)arr.FindObjectInCanvas("CalPos;avg", "MHCamera", "CalPos");
+    MHCamera *pul = (MHCamera*)arr.FindObjectInCanvas("PulsePos;avg", "MHCamera", "PulsePos");
+    if (!pul)
+    {
+        cout << "ERROR - Reading of PulsePos;avg failed." << endl;
+        return 2;
+    }
+/*
+    MHCamera *difflo = (MHCamera*)arr.FindObjectInCanvas("DiffLo;avg", "MHCamera", "DiffLo");
+    if (!difflo)
+    {
+        cout << "ERROR - Reading of DiffLo;avg failed." << endl;
+        return 2;
+    }
+    MHCamera *diffhi = (MHCamera*)arr.FindObjectInCanvas("DiffHi;avg", "MHCamera", "DiffHi");
+    if (!diffhi)
+    {
+        cout << "ERROR - Reading of DiffHi;avg failed." << endl;
+        return 2;
+    }
+*/
+
+    MSequence seq;
+    if (seq.Read("sequence[0-9]{8}[.]txt|MSequence")<=0)
+    {
+        cout << "ERROR - Could not find sequence in file: " << fname << endl;
+        return 2;
+    }
+    if (!seq.IsValid())
+    {
+        cout << "ERROR - Sequence read from file inavlid: " << fname << endl;
+        return 2;
+    }
+
+    TString medpuloff("NULL");
+    TString devpuloff("NULL");
+    TString medhilocal("NULL");
+    TString devhilocal("NULL");
+
+    if (seq.GetSequence()<200000 && seq.GetTelescope()==1)
+    {
+        MHCamera *hilooff = (MHCamera*)arr.FindObjectInCanvas("HiLoOff;avg", "MHCamera", "HiLoOff");
+        if (!hilooff)
+        {
+            cout << "ERROR - Reading of HiLoOff failed." << endl;
+            return 2;
+        }
+
+        MHCamera *hilocal = (MHCamera*)arr.FindObjectInCanvas("HiLoCal;avg", "MHCamera", "HiLoCal");
+        if (!hilocal)
+        {
+            cout << "ERROR - Reading of HiLoCal failed." << endl;
+            return 2;
+        }
+
+        medpuloff.Form("%7.4f",  hilooff->GetMedian());
+        devpuloff.Form("%7.4f",  hilooff->GetDev());
+        medhilocal.Form("%6.2f", hilocal->GetMedian());
+        devhilocal.Form("%6.2f", hilocal->GetDev());
+    }
+
+    TArrayI inner(1);
+    inner[0] = 0;
+
+    TArrayI outer(1);
+    outer[0] = 1;
+
+    Int_t s0[] = { 1, 2, 3, 4, 5, 6 };
+
+    Stat_t meanrmsi = cam->GetMeanSectors(TArrayI(6, s0), inner);
+    Stat_t meanrmso = cam->GetMeanSectors(TArrayI(6, s0), outer);
+
+    if (meanrmsi<0 || meanrmso<0)
+    {
+        cout << "ERROR - MeanPedRMS inner or outer < 0 " << endl;
+        cout << "MeanPedRMS inner " << meanrmsi << endl;
+        cout << "MeanPedRMS outer " << meanrmso << endl;
+        return 2;
+    }
+
+    TString meanrmsinner=Form("%6.2f", meanrmsi);
+    TString meanrmsouter=Form("%6.2f", meanrmso);
+
+    cam = (MHCamera*)arr.FindObjectInCanvas("Interp'd;avg", "MHCamera", "Interp'd");
+    if (!cam)
+    {
+        cout << "ERROR - Reading of Interp'd;avg failed." << endl;
+        return 2;
+    }
+
+    Stat_t meansigi = cam->GetMeanSectors(TArrayI(6, s0), inner);
+    Stat_t meansigo = cam->GetMeanSectors(TArrayI(6, s0), outer);
+
+    if (meansigi<0 || meansigo<0)
+    {
+        cout << "ERRROR - MeanInterp'd inner or outer < 0 " << endl;
+        cout << "MeanInterp'd inner " << meansigi << endl;
+        cout << "MeanInterp'd outer " << meansigo << endl;
+        return 2;
+    }
+
+    TString meansiginner =Form("%6.2f", meansigi);
+    TString meansigouter =Form("%6.2f", meansigo);
+
+    TString calpos = cal ? Form("%5.1f", cal->GetMean()) : "NULL";
+
+    if (pul->GetMean()<0 || pul->GetRMS()<0)
+    {
+        cout << "ERROR - PulsePos'd mean or rms < 0 " << endl;
+        cout << "PulsePos'd mean " << pul->GetMean() << endl;
+        cout << "PulsePos'd rms  " << pul->GetRMS() << endl;
+        return 2;
+    }
+
+    TString meanpulpos = Form("%6.2f", pul->GetMean());
+    TString rmspulpos  = Form("%6.2f", pul->GetRMS());
+
+/*
+    Double_t meanhi  = TMath::Nint(pulhi->GetMean()*100.)/100.;
+    Double_t rmshi   = TMath::Nint(pulhi->GetRMS() *100.)/100.;
+
+    Double_t meanlo  = TMath::Nint(pullo->GetMean()*100.)/100.;
+    Double_t rmslo   = TMath::Nint(pullo->GetRMS() *100.)/100.;
+    pullo->Add(pullo, pulhi, 1, -1);
+    pullo->ResetBit(MHCamera::kProfile);
+
+    Double_t meanoff = TMath::Nint(pullo->GetMean()*100.)/100.;
+    Double_t rmsoff  = TMath::Nint(pullo->GetRMS() *100.)/100.;
+
+    // USE MEDIAN INSTEAD? GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum=0);
+
+    TString meanpulhi    =Form("%6.2f", meanhi);
+    TString rmspulhi     =Form("%6.2f", rmshi);
+
+    TString meanpullo    =Form("%6.2f", meanlo);
+    TString rmspullo     =Form("%6.2f", rmslo);
+    */
+
+    cam = (MHCamera*)arr.FindObjectInCanvas("Unsuitable;avg", "MHCamera", "Unsuitable");
+    if (!cam)
+    {
+        cout << "ERROR - Reading of Unsuitable;avg failed." << endl;
+        return 2;
+    }
+
+    Int_t unsuitable50 = cam->GetNumBinsAboveThreshold(0.50);
+    Int_t unsuitable01 = cam->GetNumBinsAboveThreshold(0.01);
+
+    TString unsuitablemax = "NULL";
+    TString deadmax       = "NULL";
+
+    TGraph *gr = (TGraph*)arr.FindObjectInCanvas("BadPixTm", "TGraph", "BadPixTm");
+    if (gr)
+    {
+        const Int_t p = TMath::FloorNint(gr->GetN()*0.999);
+        unsuitablemax = Form("%d", TMath::Nint(TMath::KOrdStat(gr->GetN(), gr->GetY(), p)));
+    }
+
+    gr = (TGraph*)arr.FindObjectInCanvas("DeadPixTm", "TGraph", "DeadPixTm");
+    if (gr)
+        deadmax = Form("%d", TMath::Nint(TMath::MaxElement(gr->GetN(), gr->GetY())));
+
+    TString rateped  = "NULL";
+    TString rateped2 = "NULL";
+    TString ratecal  = "NULL";
+    TString ratetrig = "NULL";
+    TString ratesum  = "NULL";
+    TString ratena   = "NULL";
+    TString ratenull = "NULL";
+
+    TH2D *htp = (TH2D*)arr.FindObjectInCanvas("TrigPat", "TH2D", "TrigPat");
+    if (htp)
+    {
+        htp->ResetBit(TH1::kCanRebin);
+
+        Int_t iped  = htp->GetYaxis()->FindBin("Ped");
+        Int_t iped2 = htp->GetYaxis()->FindBin("Ped+Trig");
+        Int_t ical  = htp->GetYaxis()->FindBin("Cal");
+        Int_t itrig = htp->GetYaxis()->FindBin("Trig");
+        Int_t isum  = htp->GetYaxis()->FindBin("Sum");
+        Int_t inull = htp->GetYaxis()->FindBin("0");
+        Int_t ina   = htp->GetYaxis()->FindBin("UNKNOWN");
+
+        Int_t nx = htp->GetNbinsX();
+
+        rateped  = iped <0 ? "NULL" : Form("%8.1f", htp->Integral(1, nx, iped,  iped)  / nx);
+        rateped2 = iped2<0 ? "NULL" : Form("%7.2f", htp->Integral(1, nx, iped2, iped2) / nx);
+        ratecal  = ical <0 ? "NULL" : Form("%8.1f", htp->Integral(1, nx, ical,  ical)  / nx);
+        ratetrig = itrig<0 ? "NULL" : Form("%8.1f", htp->Integral(1, nx, itrig, itrig) / nx);
+        ratesum  = isum <0 ? "NULL" : Form("%8.1f", htp->Integral(1, nx, isum,  isum)  / nx);
+        ratenull = inull<0 ? "NULL" : Form("%8.1f", htp->Integral(1, nx, inull, inull) / nx);
+        ratena   = ina  <0 ? "NULL" : Form("%7.2f", htp->Integral(1, nx, ina,   ina)   / nx);
+    }
+
+    // *****************************************************
+
+    cout << "Sequence M" << seq.GetTelescope() << "/" << seq.GetSequence() << endl;
+    cout << "  Mean Ped RMS inner [phe] " << meanrmsinner  << endl;
+    cout << "  Mean Ped RMS outer [phe] " << meanrmsouter  << endl;
+    cout << "  Mean Signal  inner [phe] " << meansiginner  << endl;
+    cout << "  Mean Signal  outer [phe] " << meansigouter  << endl;
+    cout << "  Mean extracted  PulsePos " << meanextpulpos << " +- " << rmsextpulpos << endl;
+    cout << "  Mean calibrated PulsePos " << meanpulpos    << " +- " << rmspulpos    << endl;
+    cout << "  Mean calib pulse pos     " << calpos << endl;
+//    cout << "  Mean ext.HiGain PulsePos " << meanpulhi     << " +- " << rmspulhi     << endl;
+//    cout << "  Mean ext.LoGain PulsePos " << meanpullo     << " +- " << rmspullo     << endl;
+    cout << "  Lo-Hi gain offset:      " << medpuloff    << " +-  " << devpuloff    << endl;
+    cout << "  Hi/Lo gain ratio:        " << medhilocal   << " +- " << devhilocal   << endl;
+    cout << "  Unsuitable > 50%:       " << setw(6) << unsuitable50 << endl;
+    cout << "  Unsuitable >  1%:       " << setw(6) << unsuitable01 << endl;
+    cout << "  UnsuitableMax (99.9%)   " << setw(6) << unsuitablemax << endl;
+    cout << "  DeadMax                 " << setw(6) << deadmax << endl;
+    cout << "  Rate Trigger       [Hz] "  << ratetrig << endl;
+    cout << "  Rate SUM           [Hz] "  << ratesum  << endl;
+    cout << "  Rate Ped+Trigger   [Hz]  " << rateped2 << endl;
+    cout << "  Rate Pedestal      [Hz] "  << rateped  << endl;
+    cout << "  Rate Calibration   [Hz] "  << ratecal  << endl;
+    cout << "  Rate 0             [Hz] "  << ratenull << endl;
+    cout << "  Rate UNKNOWN       [Hz]  " << ratena   << endl;
+    cout << endl;
+
+    //build query and insert information into the database
+    // here only a update query is built, as this macro is exexuted after
+    // the macro fillcalib.C in the script fillcallisto
+    // and so the table Calibration is always updated
+    TString vars = Form(" fMeanPedRmsInner=%s,   fMeanPedRmsOuter=%s,  "
+                        " fMeanSignalInner=%s,   fMeanSignalOuter=%s,  "
+                        " fPulsePosMean=%s,      fPulsePosRms=%s,      "
+                        " fPulsePosCheckMean=%s, fPulsePosCheckRms=%s, "
+                        " fPulsePosCalib=%s, "
+                        //" fPulsePosHiMean=%s,    fPulsePosHiRms=%s,    "
+                        //" fPulsePosLoMean=%s,    fPulsePosLoRms=%s,    "
+                        " fPulsePosOffMed=%s,    fPulsePosOffDev=%s,   "
+                        " fHiLoGainRatioMed=%s,  fHiLoGainRatioDev=%s, "
+                        " fUnsuitable50=%d,      fUnsuitable01=%d, "
+                        " fUnsuitableMax=%s,     fDeadMax=%s, "
+                        " fRateTrigEvts=%s,      fRateSumEvts=%s, "
+                        " fRatePedTrigEvts=%s,   fRatePedEvts=%s, "
+                        " fRateCalEvts=%s,       fRateNullEvts=%s, "
+                        " fRateUnknownEvts=%s ",
+                         meanrmsinner.Data(),  meanrmsouter.Data(),
+                         meansiginner.Data(),  meansigouter.Data(),
+                         meanpulpos.Data(),    rmspulpos.Data(),
+                         meanextpulpos.Data(), rmsextpulpos.Data(),
+                         calpos.Data(),
+                         //meanpulhi.Data(),     rmspulhi.Data(),
+                         //meanpullo.Data(),     rmspullo.Data(),
+                         medpuloff.Data(),     devpuloff.Data(),
+                         medhilocal.Data(),    devhilocal.Data(),
+                         unsuitable50,         unsuitable01,
+                         unsuitablemax.Data(), deadmax.Data(),
+                         ratetrig.Data(),      ratesum.Data(),
+                         rateped2.Data(),      rateped.Data(),
+                         ratecal.Data(),       ratenull.Data(),
+                         ratena.Data()
+                       );
+
+    TString where = Form("fSequenceFirst=%d AND fTelescopeNumber=%d",
+                         seq.GetSequence(), seq.GetTelescope());
+    return serv.Update("Calibration", vars, where) ? 1 : 2;
+}
+
+int fillsignal(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillsignal" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    //process file
+    return Process(serv, fname);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillsinope.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillsinope.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillsinope.C	(revision 17960)
@@ -0,0 +1,208 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 04/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillsinope.C
+// ============
+//
+// This macro is used to read the sinope output files sinope*.txt
+// For each run sinope is run twice: once for the data events and once for the
+// calibration events. The pulse position and height is checked. The output is
+// stored in a sinope*.root and a sinope*.txt file. The files for data events
+// are marked with -dat and the ones for calibration events with -cal.
+// From the txt files the result is extracted and inserted into the database
+// in the table DataCheck, which stores the datacheck results.
+// As the column names in the database differ only by the addition 'Interlaced'
+// which is given to columns corresponding to the calibration events, the
+// files can be processed with the same function.
+//
+// Usage:
+//   .x fillsinope.C(runnumber, "datapath", kTRUE)
+//
+// The first argument is the runnumber (given as int), the second argument is
+// the datapath, where the rawfiles can be found. The last argument is the
+// 'dummy-mode'. If it is kTRUE dummy-mode is switched on and nothing will be
+// written into the database. This is usefull for tests.
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillsinope.C+\(runno\,kFALSE\) 2>&1 | tee fillsinope.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+
+#include <TFile.h>
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+
+#include "MSQLServer.h"
+
+#include "MStatusArray.h"
+#include "MHCamera.h"
+
+using namespace std;
+
+Bool_t ExistStr(MSQLServer &serv, const char *column, const char *table, const char *test)
+{
+    TString query(Form("SELECT %s FROM %s WHERE %s='%s'", column, table, column, test));
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return kFALSE;
+    }
+
+    Bool_t rc = kFALSE;
+
+    TSQLRow *row=res->Next();
+    if (row && (*row)[0])
+        rc=kTRUE;
+
+    delete res;
+    return rc;
+}
+
+int Process(MSQLServer &serv, TString fname, Int_t runno, Bool_t cal, Bool_t dummy)
+{
+    TEnv env(fname);
+
+    //build query
+    TString query="UPDATE DataCheck SET ";
+
+    //array with part of column names
+    TString values[9] = { "Events" , "HasSignal" , "HasPedestal" , "PositionSignal" , "PositionFWHM" , "PositionAsym" , "HeightSignal" , "HeightFWHM" , "HeightAsym" };
+
+    //get values from the file add them to query
+    TString str;
+    for (Int_t i=0 ; i<9 ; i++)
+    {
+        str = env.GetValue(values[i], "");
+        if (str.IsNull())
+            continue;
+
+        if (cal)
+            values[i]+="InterLaced";
+        values[i]+="='";
+        values[i]+=str;
+
+        if (i!=0)
+            query+=", ";
+        query+=" f";
+        query+=values[i];
+        query+="' ";
+
+        cout << "value: " << values[i] << endl;
+
+    }
+
+    query+=Form(" WHERE fRunNumber=%d", runno);
+
+    cout << "Q: " << query << endl;
+    //insert information into db
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+    delete res;
+    return 1;
+}
+
+int fillsinope(Int_t runno, TString datapath, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLServer serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillsignal" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Run: " << runno << endl;
+    cout << endl;
+
+    //get date of run from database
+    TString query(Form("SELECT DATE_FORMAT(ADDDATE(fRunStart, Interval 13 HOUR), '%%Y/%%m/%%d') FROM RunData WHERE fRunNumber=%d",
+                       runno));
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return 2;
+    }
+
+    TSQLRow *row = 0;
+    row = res->Next();
+    TString date=(*row)[0];
+    cout << "date: " << date << endl;
+    delete res;
+
+    //insert entry for the run into the database in the table DataCheck, if it is not yet existing
+    if (!ExistStr(serv, "fRunNumber", "DataCheck", Form("%d", runno)))
+    {
+        query=Form("INSERT DataCheck SET fRunNumber=%d", runno);
+
+        res = serv.Query(query);
+        if (!res)
+        {
+            cout << "ERROR - Query failed: " << query << endl;
+            return 2;
+        }
+    }
+
+    //get filenames of sinope output files
+    TString fname(Form("%s/sinope/%s/sinope-dat%08d.txt",
+                       datapath.Data(), date.Data(), runno));
+    cout << "file: " << fname << endl;
+    TString fnamecal(Form("%s/sinope/%s/sinope-cal%08d.txt",
+                        datapath.Data(), date.Data(), runno));
+    cout << "file-cal: " << fnamecal << endl;
+
+    Int_t rc=0;
+    //process dat-file
+    rc=Process(serv, fname, runno, kFALSE, dummy);
+    if (rc==2)
+        return rc;
+
+    //process cal-file
+    rc=Process(serv, fnamecal, runno, kTRUE, dummy);
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillsources.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillsources.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillsources.C	(revision 17960)
@@ -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): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillsources.C
+// ============
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+
+#include <fstream>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+int fillsources(TString catalog, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+    cout << "insertsources" << endl;
+    cout << "-------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Catalog file: " << catalog << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        cout << "Could not open file " << catalog << endl;
+        return 1;
+    }
+
+    while (1)
+    {
+        TString src, ra, de, dum, epoch;
+
+        src.ReadToDelim(fin, ',');
+        dum.ReadToDelim(fin, ',');
+        ra.ReadToDelim(fin, ',');
+        de.ReadToDelim(fin, ',');
+        dum.ReadToDelim(fin, ',');
+        epoch.ReadToDelim(fin, '\n');
+
+        if (!fin)
+            break;
+/*
+        Double_t r,d;
+        if (!MAstro::Coordinate2Angle(ra, r))
+        {
+            cout << "ERROR - Interpreting right ascension: " << ra << endl;
+            return 2;
+        }
+        if (!MAstro::Coordinate2Angle(de, d))
+        {
+            cout << "ERROR - Interpreting declination: " << de << endl;
+            return 2;
+        }
+ */
+        TString vars(Form("fRightAscension='%s', fDeclination='%s', fEpoch='%s'",
+                           ra.Data(), de.Data(), epoch.Data()));
+
+        TString where(Form("fSourceName='%s'", src.Data()));
+
+        if (!serv.InsertUpdate("Source", vars, where))
+            return 2;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/fillstar.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/fillstar.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/fillstar.C	(revision 17960)
@@ -0,0 +1,380 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 05/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillstar.C
+// ==========
+//
+// This macro is used to read the star-output files.
+// These files are automatically called star00000000.root.
+// From these files the muon parameters (psf, muon number, ratio, muon rate),
+// the  rate, the number of islands, the effective ontime, the maximum
+// humidity and a parameter describing the inhomogeneity are extracted from
+// the status display.
+// The sequence number is extracted from the filename.
+//
+// Usage:
+//   .x fillstar.C("/magic/data/star/0004/00047421/star00047421.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillstar.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillstar.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TFile.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TGraph.h>
+
+#include "MSQLMagic.h"
+
+#include "MHCamera.h"
+#include "MHMuonPar.h"
+#include "MSequence.h"
+#include "MStatusArray.h"
+#include "MBadPixelsCam.h"
+#include "MHEffectiveOnTime.h"
+
+using namespace std;
+
+bool CheckGraph(const TGraph *g)
+{
+    return g && g->GetN()>0 && !(g->GetN()==1 && g->GetX()[0]==0);
+}
+
+int Process(MSQLMagic &serv, TString fname)
+{
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        cout << "ERROR - Could not find file " << fname << endl;
+        return 2;
+    }
+
+
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
+        return 2;
+    }
+
+    MHCamera *hsparks = (MHCamera*)arr.FindObjectInCanvas("Sparks;avg", "MHCamera", "Sparks");
+    if (!hsparks)
+    {
+        cout << "ERROR - Reading of Sparks failed." << endl;
+        return 2;
+    }
+
+    TH2F *hcog = (TH2F*)arr.FindObjectInCanvas("Center", "TH2F", "MHHillas");
+    if (!hcog)
+    {
+        cout << "ERROR - Reading of MHHillas failed." << endl;
+        return 2;
+    }
+
+    MHMuonPar *hmuon = (MHMuonPar*)arr.FindObjectInCanvas("MHMuonPar", "MHMuonPar", "MHMuonPar");
+    if (!hmuon)
+    {
+        cout << "ERROR - Reading of MHMuon failed." << endl;
+        return 2;
+    }
+
+    Double_t val[6];
+    for (int x=1; x<hcog->GetNbinsX(); x++)
+        for (int y=1; y<hcog->GetNbinsY(); y++)
+        {
+            Stat_t px = hcog->GetXaxis()->GetBinCenter(x);
+            Stat_t py = hcog->GetYaxis()->GetBinCenter(y);
+            Int_t  i  = (TMath::Nint(3*TMath::ATan2(px,py)/TMath::Pi())+6)%6;
+            val[i] += hcog->GetBinContent(x, y);
+        }
+
+    Float_t inhom = TMath::RMS(6, val)*6/hcog->GetEntries()*100;
+    TString inhomogen = Form("%5.1f", inhom);
+
+    Float_t mw  = hmuon->GetMeanWidth();
+    Float_t psf = 70.205*mw - 28.055;
+    TString PSF = Form("%5.1f", (psf<0?0:psf));
+    Int_t   num = (int)hmuon->GetEntries();
+
+    Float_t ratiodatamc = (hmuon->GetMeanSize()/7216)*100;
+    TString ratio = Form("%5.1f", ratiodatamc);
+
+    TH1 *h = (TH1*)arr.FindObjectInCanvas("Islands", "TH1F", "MHImagePar");
+    if (!h)
+    {
+        cout << "ERROR - Reading of Islands failed." << endl;
+        return 2;
+    }
+
+    TString islands = Form("%6.2f", h->GetMean());
+
+    h = (TH1*)arr.FindObjectInCanvas("EffOnTheta", "TH1D", "EffOnTime");
+
+    Float_t effon = h ? h->Integral() : -1;
+
+    h = (TH1*)arr.FindObjectInCanvas("Cleaned;avg", "TH1D", "Cleaned");
+    if (!h)
+    {
+        cout << "ERROR - Reading of Cleaned;avg failed." << endl;
+        return 2;
+    }
+
+    if (effon<0)
+        effon = h->GetEntries()/100;
+
+    Float_t mrate = num/effon;
+
+    TString muonrate  = mrate<0 || effon==0 ? "NULL" : Form("%6.2f", mrate);
+    TString effontime = Form("%.1f", effon);
+
+    Int_t numsparks = (int)hsparks->GetEntries();
+    Int_t numevents = (int)h->GetEntries() - numsparks;
+
+    TString datarate  = effon==0 ? "NULL" : Form("%.0f", numevents/effon);
+    TString sparkrate = Form("%5.2f", numsparks/effon);
+    if (sparkrate.Contains("inf") || sparkrate.Contains("nan"))
+        sparkrate="NULL";
+
+    MHEffectiveOnTime *ontm = (MHEffectiveOnTime*)arr.FindObjectInCanvas("MHEffectiveOnTime", "MHEffectiveOnTime", "EffOnTime");
+    TString totontime = ontm ? Form("%d", TMath::Nint(ontm->GetTotalTime())) : "NULL";
+    TString relontime = ontm ? Form("%.2f", effon/ontm->GetTotalTime()*100) : "NULL";
+
+    TGraph *g = (TGraph*)arr.FindObjectInCanvas("MCamEvent", "TGraph", "Currents");
+
+    TString maxdc = CheckGraph(g) ? Form("%5.2f", TMath::MaxElement(g->GetN(), g->GetY())) : "NULL";
+    TString mindc = CheckGraph(g) ? Form("%5.2f", TMath::MinElement(g->GetN(), g->GetY())) : "NULL";
+    TString meddc = CheckGraph(g) ? Form("%5.2f", TMath::Median(g->GetN(), g->GetY())) : "NULL";
+
+    g = (TGraph*)arr.FindObjectInCanvas("Humidity", "TGraph", "MHWeather");
+
+    TString maxhum = CheckGraph(g) ? Form("%5.1f", TMath::MaxElement(g->GetN(), g->GetY())) : "NULL";
+    TString avghum = CheckGraph(g) ? Form("%5.1f", g->GetMean(2)) : "NULL";
+
+    g = (TGraph*)arr.FindObjectInCanvas("Temperature", "TGraph", "MHWeather");
+
+    TString avgtemp = CheckGraph(g) ? Form("%5.1f", g->GetMean(2)) : "NULL";
+
+    g = (TGraph*)arr.FindObjectInCanvas("WindSpeed", "TGraph", "MHWeather");
+
+    TString avgwind = CheckGraph(g) ? Form("%5.1f", g->GetMean(2)) : "NULL";
+
+    g = (TGraph*)arr.FindObjectInCanvas("Cloudiness", "TGraph", "MHWeather");
+    //if (!g)
+    //    cout << "WARNING - Reading of Cloudiness failed." << endl;
+    TString avgclouds = CheckGraph(g) ? Form("%5.1f", g->GetMean(2)) : "NULL";
+    TString rmsclouds = CheckGraph(g) ? Form("%5.1f", g->GetRMS(2))  : "NULL";
+
+    g = (TGraph*)arr.FindObjectInCanvas("TempSky", "TGraph", "MHWeather");
+    //if (!g)
+    //    cout << "WARNING - Reading of TempSky failed." << endl;
+    TString avgsky = CheckGraph(g) ? Form("%5.1f", g->GetMean(2)+200) : "NULL";
+
+
+    g = (TGraph*)arr.FindObjectInCanvas("NumStars", "TGraph", "MHPointing");
+    //if (!g)
+    //    cout << "WARNING - Reading of NumStars failed." << endl;
+    TString numstarsmed = CheckGraph(g) ? Form("%5.1f", TMath::Median(g->GetN(), g->GetY())) : "NULL";
+    TString numstarsrms = CheckGraph(g) ? Form("%5.1f", g->GetRMS(2)) : "NULL";
+
+    g = (TGraph*)arr.FindObjectInCanvas("NumStarsCor", "TGraph", "MHPointing");
+    //if (!g)
+    //    cout << "WARNING - Reading of NumStarsCor failed." << endl;
+    TString numcorsmed = CheckGraph(g) ? Form("%5.1f", TMath::Median(g->GetN(), g->GetY())) : "NULL";
+    TString numcorsrms = CheckGraph(g) ? Form("%5.1f", g->GetRMS(2)) : "NULL";
+
+    g = (TGraph*)arr.FindObjectInCanvas("Brightness", "TGraph", "MHPointing");
+    //if (!g)
+    //    cout << "WARNING - Reading of SkyBrightness failed." << endl;
+    TString skybrightnessmed = CheckGraph(g) ? Form("%5.1f", TMath::Median(g->GetN(), g->GetY())) : "NULL";
+    TString skybrightnessrms = CheckGraph(g) ? Form("%5.1f", g->GetRMS(2)) : "NULL";
+
+    MSequence seq;
+    if (seq.Read("sequence[0-9]{8}[.]txt|MSequence")<=0)
+    {
+        cout << "ERROR - Could not find sequence in file: " << fname << endl;
+        return 2;
+    }
+    if (!seq.IsValid())
+    {
+        cout << "ERROR - Sequence read from file inavlid: " << fname << endl;
+        return 2;
+    }
+
+    cout << "Sequence M" << seq.GetTelescope() << ":" << seq.GetSequence() << endl;
+    cout << "  Inhomogeneity            " << inhomogen << endl;
+    cout << "  PSF [mm]                 " << PSF       << endl;
+    cout << "  Island Quality           " << islands   << endl;
+    cout << "  Ratio [%]                " << ratio     << endl;
+    cout << "  Muon Number              " << num       << endl;
+    cout << "  Eff. OnTime [s]          " << effontime << endl;
+    cout << "  Tot. OnTime [s]          " << totontime << endl;
+    cout << "  Rel. OnTime [%]          " << relontime << endl;
+    cout << "  Muon Rate [Hz]           " << muonrate  << endl;
+    cout << "  # of Events (w/o sparks) " << numevents << endl;
+    cout << "  # of Sparks              " << numsparks << endl;
+    cout << "  Rate after ImgCl [Hz]    " << datarate  << endl;
+    cout << "  Rate of sparks [Hz]      " << sparkrate << endl;
+    cout << "  Minimum DC current [nA]  " << mindc     << endl;
+    cout << "  Median  DC current [nA]  " << meddc     << endl;
+    cout << "  Maximum DC current [nA]  " << maxdc     << endl;
+    cout << "  Maximum Humidity [%]     " << maxhum    << endl;
+    cout << "  Average Humidity [%]     " << avghum    << endl;
+    cout << "  Average WindSpeed [km/h] " << avgwind   << endl;
+    cout << "  Average Temp [" << UTF8::kDeg << "C]        " << avgtemp   << endl;
+    cout << "  Average Sky Temp [K]     " << avgsky    << endl;
+    cout << "  Cloundiness [%]          " << avgclouds        << " +/- " << rmsclouds        << endl;
+    cout << "  Number of Stars          " << numstarsmed      << " +/- " << numstarsrms      << endl;
+    cout << "  Number of cor. Stars     " << numcorsmed       << " +/- " << numcorsrms       << endl;
+    cout << "  Skybrightness            " << skybrightnessmed << " +/- " << skybrightnessrms << endl;
+
+    TString vars = Form(" fSequenceFirst=%d, "
+                        " fTelescopeNumber=%d, "
+                        " fMeanNumberIslands=%s,"
+                        " fRatio=%s,"
+                        " fMuonNumber=%d,"
+                        " fEffOnTime=%s,"
+                        " fTotOnTime=%s,"
+                        " fMuonRate=%s,"
+                        " fPSF=%s,"
+                        " fDataRate=%s,"
+                        " fSparkRate=%s,"
+                        " fMinCurrents=%s, "
+                        " fMedCurrents=%s, "
+                        " fMaxCurrents=%s, "
+                        " fMaxHumidity=%s,"
+                        " fAvgHumidity=%s, "
+                        " fAvgTemperature=%s,"
+                        " fAvgWindSpeed=%s,"
+                        " fAvgTempSky=%s,"
+                        " fAvgCloudiness=%s, "
+                        " fRmsCloudiness=%s, "
+                        " fNumStarsMed=%s,"
+                        " fNumStarsRMS=%s,"
+                        " fNumStarsCorMed=%s,"
+                        " fNumStarsCorRMS=%s,"
+                        " fBrightnessMed=%s,"
+                        " fBrightnessRMS=%s,"
+                        " fInhomogeneity=%s ",
+                        seq.GetSequence(), seq.GetTelescope(),
+                        islands.Data(), ratio.Data(),
+                        num, effontime.Data(), totontime.Data(),
+                        muonrate.Data(), PSF.Data(),
+                        datarate.Data(), sparkrate.Data(),
+                        mindc.Data(), meddc.Data(), maxdc.Data(),
+                        maxhum.Data(), avghum.Data(),
+                        avgtemp.Data(), avgwind.Data(),
+                        avgsky.Data(), avgclouds.Data(), rmsclouds.Data(),
+                        numstarsmed.Data(), numstarsrms.Data(),
+                        numcorsmed.Data(), numcorsrms.Data(),
+                        skybrightnessmed.Data(), skybrightnessrms.Data(),
+                        inhomogen.Data());
+
+    TString where = Form("fSequenceFirst=%d AND fTelescopeNumber=%d",
+                         seq.GetSequence(), seq.GetTelescope());
+
+    if (!serv.InsertUpdate("Star", vars, where))
+        return 2;
+
+    cout << endl;
+
+    h = (TH1*)arr.FindObjectInCanvas("Rate", "TH2D", "Rate");
+    if (!h)
+        return 1;
+
+    h->ResetBit(TH1::kCanRebin);
+
+    Int_t itrig = h->GetYaxis()->FindBin("Trig");
+    Int_t isum  = h->GetYaxis()->FindBin("Sum");
+    Int_t inull = h->GetYaxis()->FindBin("0");
+
+    for (int i=0; i<h->GetNbinsX(); i++)
+    {
+        Int_t id = atoi(h->GetXaxis()->GetBinLabel(i+1));
+
+        Int_t run  = seq.GetSequence()<1000000 ? id : id/1000 + 1000000;
+        Int_t file = seq.GetSequence()<1000000 ? 0  : id%1000;
+
+        const char *rtrig = itrig<0 ? "NULL" : Form("%8.1f", h->GetBinContent(i+1, itrig));
+        const char *rsum  = isum <0 ? "NULL" : Form("%8.1f", h->GetBinContent(i+1, isum));
+        const char *rnull = inull<0 ? "NULL" : Form("%8.1f", h->GetBinContent(i+1, inull));
+
+        cout << "  M" << seq.GetTelescope() << ":" << run << "/" << file << " " <<rtrig << " " << rsum << " " << rnull << endl;
+
+        TString vars = Form(" fTelescopeNumber=%d, "
+                            " fRunNumber=%d, "
+                            " fFileNumber=%d, "
+                            " fRateCleanedTrig=%s,"
+                            " fRateCleanedSum=%s,"
+                            " fRateCleanedNull=%s",
+                            seq.GetTelescope(), run, file,
+                            rtrig, rsum, rnull);
+
+        TString where = Form("fTelescopeNumber=%d AND fRunNumber=%d AND fFileNumber=%d",
+                             seq.GetTelescope(), run, file);
+
+        if (!serv.InsertUpdate("RunDataCheck", vars, where))
+            return 2;
+    }
+
+    return 1;
+}
+
+int fillstar(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillstar" << endl;
+    cout << "--------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    return Process(serv, fname);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/findcacofiles.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/findcacofiles.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/findcacofiles.C	(revision 17960)
@@ -0,0 +1,154 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// findcacofiles.C
+// ===============
+//
+// Macro to find caco files for runs which don't have a dedicated caco file.
+// Called by the script filesondisk
+//
+// Sometimes the DAQ aborts a run and starts itself a new one. In this cases
+// the camera controll doesn't start a new file, as the command to
+// start a new run was not sent by the central control. So the caco
+// information is stored in the previous caco file, which has a different
+// runnumber. To be able to merpp the information into the calibrated data
+// file, the runnumber of the file containing the information has to be found.
+// 
+// findcacofiles.C searches in the database for runs which don't have a
+// dedicated caco file, and searches for each of these runs, if one of the 10
+// previous runs has a dedicated caco file. In case one is found, it is
+// inserted into the database.
+//
+// Usage:
+//   .x findcacofiles.C+
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TSystem.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+
+int findcacofiles()
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+    cout << "findcacofiles" << endl;
+    cout << "-------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    //get runnumbers and dates from database
+    TString query="SELECT RunProcessStatus.fRunNumber, ";
+    query+=" DATE_FORMAT(ADDDATE(if(fRunStart='0000-00-00 00:00:00', fRunStop, fRunStart), INTERVAL +13 HOUR), '%Y/%m/%d') ";
+    query+=" FROM RunProcessStatus ";
+    query+=" LEFT JOIN RunData USING (fRunNumber) ";
+    query+=" LEFT JOIN Source USING (fSourceKEY) ";
+    query+=" WHERE IsNull(fCaCoFileFound) AND fExcludedFDAKEY=1 ";
+    query+=" AND RunProcessStatus.fRunNumber > 10000 AND NOT IsNull(fCCFileAvail)";
+    query+=" AND fTest='no'";
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "Error." << endl;
+        return 0;
+    }
+
+    Int_t counter=0;
+    Int_t counter2=0;
+    TSQLRow *row=0;
+    while ((row = res->Next()))
+    {
+        //search nearest previous available CaCoFile
+        Int_t run=atoi((*row)[0]);
+        if (TString((*row)[1]).IsNull())
+        {
+            cout << "For run " << (*row)[0] << " fRunStart and fRunStop are 0000-00-00 00:00:00. No CaCoFile can be determined. " << endl;
+            continue;
+        }
+        cout << "CaCoFile missing for run " << (*row)[0] << " with date " << (*row)[1] << endl;
+
+        query ="SELECT MAX(fCaCoFileFound) FROM RunProcessStatus ";
+        query+=" LEFT JOIN RunData USING (fRunNumber) ";
+        query+=Form("WHERE DATE_FORMAT(ADDDATE(fRunStart, INTERVAL +13 HOUR), '%%Y/%%m/%%d')='%s' ",
+                    (*row)[1]);
+        query+=Form("AND RunData.fRunNumber IN (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
+                    run, run-1, run-2, run-3, run-4, run-5,
+                    run-6, run-7, run-8, run-9, run-10);
+
+        TSQLResult *res2 = serv.Query(query);
+        if (!res2)
+        {
+            cout << "Error." << endl;
+            return 0;
+        }
+        TSQLRow *row2=0;
+        row2 = res2->Next();
+        if ((*row2)[0])
+        {
+            cout << "Found CaCoFile at run " << (*row2)[0] << endl;
+            TString vals=Form("fCaCoFileAvail=Now(), fCaCoFileFound=%s", (*row2)[0]);
+            TString where=Form("fRunNumber=%d", run);
+
+            //insert found runnumber
+            if (!serv.Update("RunProcessStatus", vals,where))
+                return 0;
+            counter2+=1;
+        }
+        else
+            cout << " No caco file found for run " << run << endl;
+
+        delete res2;
+        counter+=1;
+    }
+    cout << endl << counter << " missing caco files. " << endl;
+    cout << counter2 << " caco files found and inserted. " << endl;
+
+    delete res;
+    return 1;
+}
+
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/insertcacofile.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/insertcacofile.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/insertcacofile.C	(revision 17960)
@@ -0,0 +1,102 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// insertcacofiles.C
+// =================
+//
+// Macro to insert runnumber of the caco files, which contain the information
+// for a run, for which no caco file is available.
+//
+// Sometimes the DAQ aborts a run and starts itself a new one. In this cases
+// the camera controll doesn't start a new file, as the command to
+// start a new run was not sent by the central control. So the caco
+// information is stored in the previous caco file, which has a different
+// runnumber. To be able to merpp the information into the calibrated data
+// file, the runnumber of the file containing the information has to be found.
+// This is done by a script.
+// insertcacofiles.C inserts the runnumber of the file, that has been found,
+// into the column CaCoFileFound. 
+//
+// Usage:
+//   .x insertcacofile.C+("runnumber", "newrunnumber")
+// The first is the runnumber of which the cacofile is missing, the second is
+// the runnumber of the file in which the information probably can be found.
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TSystem.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MSQLServer.h"
+
+using namespace std;
+
+int insertcacofile(TString runnumber, TString newrunnumber)
+{
+    cout << "ERROR - TelescopeNumber and FileNumber not implemeted." << endl;
+    return 2;
+/*
+    MSQLServer serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+    cout << "insertcacofile" << endl;
+    cout << "--------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    //get new runnumber
+    Int_t newrunno=atoi(newrunnumber.Data());
+    //build query and insert information
+    TString query(Form("UPDATE RunProcessStatus SET fCaCoFileAvail=Now(), fCaCoFileFound=%d WHERE fRunNumber=%s ",
+                       newrunno, runnumber.Data()));
+    cout << "qu: " << query << endl;
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "Error - update didn't work." << endl;
+        return 0;
+    }
+
+    delete res;
+    return 1;
+    */
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/insertdataset.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/insertdataset.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/insertdataset.C	(revision 17960)
@@ -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): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// insertdataset.C
+// ===============
+//
+// This macro inserts datasets into the database.
+// If a new dataset file has been stored in the dataset directory, the
+// information file is read by a script and the information is inserted with
+// this macro into the database in the tables DataSets and
+// DataSetProcessStatus, where in the information about datasets is stored.
+//
+// Usage:
+//   .x insertdataset.C+("number","source,"wobble","comment",kTRUE)
+// The first argument is the dataset number, the second is giving the source
+// name, the third the observation mode (wobble/on-off), the fourth a comment
+// about the dataset. This arguments are extracted by a script from the
+// dataset file.
+// The last argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+int insertdataset(TString number, TString source, TString wobble, TString comment, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << "insertdataset" << endl;
+    cout << "-------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    //get source key
+    Int_t sourcekey = serv.QueryKeyOfName("Source", source.Data(), kFALSE);
+    if (sourcekey<0)
+    {
+        cout << "Error - could not get sourcename from DB -> " << flush;
+        cout << "maybe you have the wrong sourcename in your datasetfile" << endl;
+        return 2;
+    }
+
+    cout << "no:" << number << endl;
+
+    //if dataset is not yet in database, insert the information
+    if (serv.ExistStr("fDataSetNumber", "DataSets", number.Data())) // Form("%d", number)
+    {
+        cout << number << " already exists... " << endl;
+        return 3;
+    }
+
+    TString vals = Form("fDataSetNumber='%s', fSourceKEY=%d, "
+                        "fWobble='%s', fComment='%s' ", number.Data(),
+                        sourcekey, wobble.Data(), comment.Data());
+
+    Int_t rc = serv.Insert("DataSets", vals);
+
+    if (rc<=0) // dummy mode or failed
+        return 0;
+
+    vals = Form("fDataSetNumber='%s', fPriority='%s', fDataSetInserted=Now()",
+                number.Data(), number.Data());
+    rc = serv.Insert("DataSetProcessStatus", vals);
+
+    if (rc<=0) // dummy mode or failed
+        return 0;
+
+    return 1;
+}
+
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/insertdate.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/insertdate.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/insertdate.C	(revision 17960)
@@ -0,0 +1,100 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// insertdate.C
+// ============
+//
+// This macro is inserting a date into the table SequenceBuildStatus.
+// It is executed by the script copyscript, which copies the slow control
+// data to the appropriate directory and inserts the information into the
+// database.
+//
+// Usage:
+//  .x insertdate.C+("date")
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+
+#include <TEnv.h>
+
+#include <MSQLMagic.h>
+
+using namespace std;
+
+int insertdate(TString date)
+{
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+    cout << "insertdate" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    //insert entry for date into the table SequenceBuildStatus,
+    // if entry is not yet existing
+    if (!serv.ExistStr("fDate", "SequenceBuildStatus", date))
+    {
+        TString vals(Form("fDate='%s', fCCFilled=Now()", date.Data()));
+
+        const Int_t rc = serv.Insert("SequenceBuildStatus", vals);
+        if (rc==kFALSE) // Query failed
+            return -1;
+        //if (rc<0)       // Dummy mode
+        //    return 0;
+    }
+    else
+    {
+        cout << date << " already exists... do update. " << endl;
+
+        const Int_t rc = serv.Update("SequenceBuildStatus",
+                                     "fCCFilled=Now(), fExclusionsDone=NULL, fSequenceEntriesBuilt=NULL",
+                                     Form("fDate='%s'", date.Data()));
+
+        if (rc==kFALSE) // Query failed
+            return -1;
+        //if (rc<0)       // Dummy mode
+        //    return 0;
+
+    }
+
+    return 1;
+}
+
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/insertsequence.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/insertsequence.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/insertsequence.C	(revision 17960)
@@ -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): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// insertsequence.C
+// ================
+//
+// This macro inserts a sequence into the database. It extracts the
+// information from a sequence file.
+// This macro is not used by the automatic analysis. It is needed to insert
+// manually built sequences into the database.
+//
+// Usage:
+//  .x insertsequence.C+("filename", kTRUE)
+// The first argument is the filename of the manual written sequencefile.
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+
+#include <TEnv.h>
+
+#include <MSQLMagic.h>
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+using namespace std;
+
+int insertsequence(TString filename, Bool_t dummy=kTRUE)
+{
+    cout << "ERROR - TelescopeNumber and FileNumber not implemeted." << endl;
+    return 2;
+/*
+    TEnv env("sql.rc");
+    TEnv sequ(filename);
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << "insertsequence" << endl;
+    cout << "--------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    //get sequence number from file
+    TString sequnum;
+    sequnum=sequ.GetValue("Sequence", "");
+    Int_t seq=atoi(sequnum.Data());
+
+    //get runs from sequence file
+    TString runs;
+    runs = sequ.GetValue("Runs", "");
+    runs.ReplaceAll(" ", ",");
+    if (runs.IsNull())
+    {
+        cout << "ERROR - No runs in file " << filename << " found." << endl;
+        return 0;
+    }
+
+    //get source key
+    TString sourcename = sequ.GetValue("Source", "");
+    Int_t sourcekey = serv.QueryKeyOfName("Source", sourcename.Data(), kFALSE);
+    if (sourcekey<0)
+    {
+        cout << "Error - could not get sourcename from DB -> " << flush;
+        cout << "maybe you have the wrong sourcename in your datasetfile" << endl;
+        return 2;
+    }
+
+    //get values for the sequence
+    TString query="SELECT max(fRunNumber), min(fRunStart), ";
+    query +="sum(time_to_sec(fRunStop)-time_to_sec(fRunStart)), ";
+    query +="min(fZenithDistance), max(fZenithDistance), ";
+    query +="min(fAzimuth), max(fAzimuth), sum(fNumEvents) from RunData ";
+    query +=Form("WHERE fRunNumber IN (%s)",runs.Data());
+
+    cout << "runs: " << runs << endl;
+    cout << "q1: " << query << endl;
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return 0;
+
+    TSQLRow *row=res->Next();
+    TString lastrun=(*row)[0];
+    TString starttime=(*row)[1];
+    TString uptime=(*row)[2];
+    TString zdmin=(*row)[3];
+    TString zdmax=(*row)[4];
+    TString azmin=(*row)[5];
+    TString azmax=(*row)[6];
+    TString numevts=(*row)[7];
+
+    delete res;
+
+    query  ="SELECT fProjectKEY, fSourceKEY, fHvSettingsKEY, ";
+    query +="fTriggerDelayTableKEY, fDiscriminatorThresholdTableKEY, ";
+    query +="fTestFlagKEY, fLightConditionsKEY, fL1TriggerTableKEY, ";
+    query +=Form("fL2TriggerTableKEY FROM RunData WHERE fRunNumber=%d", seq);
+
+    cout << "q2: " << query << endl;
+
+    res = serv.Query(query);
+    if (!res)
+        return 0;
+
+    row=res->Next();
+    TString project=(*row)[0];
+    TString source=(*row)[1];
+    TString hv=(*row)[2];
+    TString delay=(*row)[3];
+    TString dt=(*row)[4];
+    TString testflag=(*row)[5];
+    TString lightcond=(*row)[6];
+    TString l1tt=(*row)[7];
+    TString l2tt=(*row)[8];
+
+    delete res;
+
+    cout << "seq: "       << seq        << endl;
+    cout << "  lastrun   " << lastrun   << endl;
+    cout << "  startime  " << starttime << endl;
+    cout << "  uptime    " << uptime    << endl;
+    cout << "  zdmin     " << zdmin     << endl;
+    cout << "  zdmax     " << zdmax     << endl;
+    cout << "  azmin     " << azmin     << endl;
+    cout << "  azmax     " << azmax     << endl;
+    cout << "  numevts   " << numevts   << endl;
+    cout << " keys:"                    <<  endl;
+    cout << "  project   " << project   << endl;
+    cout << "  source1   " << source    << " (from db -> run "  << seq << ") " << endl;
+    cout << "  source2   " << sourcekey << " (from sequ file) " << endl;
+    if (!(atoi(source.Data())==sourcekey))
+    {
+        cout << "new source name: " << sourcename << " -> inserting..." << endl;
+        sourcekey = serv.QueryKeyOfName("Source", sourcename.Data(), kFALSE);
+        if (sourcekey<0)
+        {
+            cout << "Error - could not get sourcename from DB -> " << flush;
+            cout << "maybe you have the wrong sourcename in your datasetfile" << endl;
+            return 2;
+        }
+        source=Form("%d",sourcekey);
+    }
+    cout << "  source    " << source    << endl;
+    cout << "  hv        " << hv        << endl;
+    cout << "  delay     " << delay     << endl;
+    cout << "  dt        " << dt        << endl;
+    cout << "  testflag  " << testflag  << endl;
+    cout << "  lightcond " << lightcond << endl;
+    cout << "  l1tt      " << l1tt      << endl;
+    cout << "  l2tt      " << l2tt      << endl;
+
+    //build queries
+    TString vals=
+        Form("fManuallyChangedKEY=2, "
+             "fSequenceFirst=%d, fSequenceLast=%s, "
+             "fProjectKEY=%s, fSourceKEY=%s, fNumEvents=%s, "
+             "fRunStart='%s', fHvSettingsKEY=%s, fRunTime=%s, "
+             "fTriggerDelayTableKEY=%s, fDiscriminatorThresholdTableKEY=%s, "
+             "fTestFlagKEY=%s, fLightConditionsKEY=%s, fAzimuthMin=%s, "
+             "fAzimuthMax=%s, fZenithDistanceMin=%s, fZenithDistanceMax=%s, "
+             "fL1TriggerTableKEY=%s, fL2TriggerTableKEY=%s ",
+             seq, lastrun.Data(), project.Data(), source.Data(),
+             numevts.Data(), starttime.Data(), hv.Data(), uptime.Data(),
+             delay.Data(), dt.Data(), testflag.Data(), lightcond.Data(),
+             azmin.Data(), azmax.Data(), zdmin.Data(), zdmax.Data(),
+             l1tt.Data(), l2tt.Data());
+
+    const Int_t rc1 = serv.Insert("Sequences", vals);
+    if (rc1<0)       // dummy
+        return 1;
+    if (rc1==kFALSE) // insert failed
+        return 0;
+
+    //the time of the column fSequenceFileWritten is set to 'not to be done'
+    vals=Form("fSequenceFirst=%d, fSequenceFileWritten='1970-01-01 00:00:00'", seq);
+
+    const Int_t rc2 = serv.Insert("SequencesProcessStatus", vals);
+
+    if (rc2<0)       // dummy
+        return 1;
+    if (rc2==kFALSE) // insert failed
+        return 0;
+
+    return 1;
+    */
+}
+
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/plotdb.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/plotdb.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/plotdb.C	(revision 17960)
@@ -0,0 +1,831 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: plotdb.C,v 1.56 2009-03-16 15:13:43 tbretz Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// plotdb.C
+// ========
+//
+// This macro is used to read quality parameters from the DB and plot them.
+// 
+// The parameters are from the following files:
+// calib*.root:mean conversion factor, mean arrival time, rms arrival time
+// (each parameter for inner and outer camera)
+// signal*.root: mean pedestal rms (for inner and outer camera)
+// star*.root: PSF, # of Muons, Effective OnTime, Muon rate,
+// Ratio MC/Data(MuonSize) and mean number of islands
+// 
+// In the DB these values are stored in the tables Calibration and Star.
+// 
+// Usage:
+//   .x plotdb.C   --> all values in the DB are plotted
+// You can chose are certain period:
+//   .x plotdb.C(25)   --> all values from period 25 are plotted
+// or a time period from a certain date to a certain date
+//   .x plotdb.C("2004-11-14 00:00:00", "2005-02-28 00:00:00")
+//  --> all values from 14.11.2004 0h to 28.2.2005 0h are plotted
+// or all data, but with dataset data highlighted
+//   .x plotdb.C("dataset.txt", "outpath")
+//  --> the sequences defined in dataset.txt are highlighted (blue:on, red:off)
+//  --> You can also add a dataset-name as last argument to one of the
+//      calls above
+//  --> You must give an outpath (but can be "") where to store plotdb.root
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TLine.h>
+#include <TText.h>
+#include <TFrame.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TPRegexp.h>
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+#include <TGraphErrors.h>
+
+#include "MTime.h"
+#include "MAstro.h"
+#include "MDataSet.h"
+#include "MSQLMagic.h"
+#include "MStatusDisplay.h"
+
+class MPlot : public MParContainer
+{
+public:
+    // Possible constants to group-by (average) over a certain period
+    enum GroupBy_t
+    {
+        kNone,
+        kGroupByPrimary,
+        kGroupByHour,
+        kGroupByDay,
+        kGroupByNight,
+        kGroupByWeek,
+        kGroupByMonth,
+        kGroupBySeason,
+        kGroupByYear
+    };
+
+private:
+    MSQLMagic &fServer;         // Reference to the sql-server class
+
+    MDataSet *fDataSet;         // A possible dtaset to highlite single points
+
+    TString   fPrimaryDate;     // The name of the data we plot
+    TString   fPrimaryNumber;   // The corresponding name for the key number
+    TString   fSecondary;       // The value versus which the second plot is made
+
+    TString   fRequestFrom;     // Start of a requested date range
+    TString   fRequestTo;       // End of a requested date range
+    Int_t     fRequestPeriod;   // A possible requested period
+
+    Float_t   fPlotMin;
+    Float_t   fPlotMax;
+
+    Float_t   fHistMin;
+    Float_t   fHistMax;
+
+    TString   fDescription;     // The description (title) of the plot
+    TString   fNameTab;         // The name of the tab in the display
+
+    TString   fCondition;       // An additional condition added to the query
+    GroupBy_t fGroupBy;         // A possible Group-By flag
+
+    // --------------------------------------------------------------------------
+    //
+    // Function to plot the result of the query
+    //
+    void PlotTable(TSQLResult &res, TString name, Float_t fmin, Float_t fmax, Float_t resolution)
+    {
+        // Enable all otions in the statistics box
+        gStyle->SetOptStat(111111);
+
+        // Create TGraph objects
+        TGraph &gt = res.GetFieldCount()>4 ? *new TGraphErrors : *new TGraph;
+        gt.SetNameTitle(Form("%s_time", res.GetFieldName(2)), Form("%s vs %s", res.GetFieldName(2), res.GetFieldName(0)));
+        gt.SetMarkerStyle(kFullDotMedium);
+
+        TGraph gz;
+        gz.SetNameTitle(res.GetFieldName(2), Form("%s vs %s", res.GetFieldName(2), res.GetFieldName(1)));
+        gz.SetMarkerStyle(kFullDotMedium);
+
+        TGraph gt0, gt1;
+        gt0.SetMarkerColor(kRed);
+        gt1.SetMarkerColor(kBlue);
+        gt0.SetMarkerStyle(kFullDotLarge);
+        gt1.SetMarkerStyle(kFullDotLarge);
+
+        TGraph gz0, gz1;
+        gz0.SetMarkerColor(kRed);
+        gz1.SetMarkerColor(kBlue);
+        gz0.SetMarkerStyle(kFullDotLarge);
+        gz1.SetMarkerStyle(kFullDotLarge);
+
+        Int_t first = -1;
+        Int_t last  = -1;
+
+        // Loop over the data
+        TSQLRow *row = 0;
+        while ((row=res.Next()))
+        {
+            Int_t pos=0;
+            // Get all fields of this row
+            const char *date  = (*row)[pos++];
+            const char *zd    = (*row)[pos++];
+            const char *val   = (*row)[pos++];
+            const char *zderr = fGroupBy!=kNone ? (*row)[pos++] : 0;
+            const char *verr  = fGroupBy!=kNone ? (*row)[pos++] : 0;
+            const char *snum  = fDataSet        ? (*row)[pos++] : 0;
+
+            delete row;
+
+            if (!date || !val || !zd)
+                continue;
+
+            // check if date is valid
+            MTime t(date);
+            if (!t.SetSqlDateTime(date))
+                continue;
+
+            // check if it belongs to the requested MAGIC period
+            if (fRequestPeriod>0 && MAstro::GetMagicPeriod(t.GetMjd())!=fRequestPeriod)
+                continue;
+
+            // Get axis range
+            if (first<0)
+                first = TMath::Nint(TMath::Floor(t.GetMjd()));
+            last = TMath::Nint(TMath::Ceil(t.GetMjd()));
+
+            // Convert a possible key number into a integer
+            UInt_t seq = snum ? atoi(snum) : 0;
+
+            // convert primary and secondary value into floats
+            Float_t value = atof(val);
+            Float_t zenith = atof(zd);
+
+            // If a datset is given add the point to the special TGraphs
+            // used for highliting these dates
+            if (fDataSet)
+            {
+                if (fDataSet->HasOnSequence(seq))
+                {
+                    gt1.SetPoint(gt1.GetN(), t.GetAxisTime(), value);
+                    gz1.SetPoint(gz1.GetN(), zenith, value);
+                }
+
+                if (fDataSet->HasOffSequence(seq))
+                {
+                    gt0.SetPoint(gt0.GetN(), t.GetAxisTime(), value);
+                    gz0.SetPoint(gz0.GetN(), zenith, value);
+                }
+            }
+
+            // Add Data to TGraph
+            gt.SetPoint(gt.GetN(), t.GetAxisTime(), value);
+            gz.SetPoint(gz.GetN(), zenith, value);
+
+            // Set error-bar, if one
+            if (verr)
+                static_cast<TGraphErrors&>(gt).SetPointError(gt.GetN()-1, 0, atof(verr));
+        }
+
+        // If this is done earlier the plots remain empty since root 5.12/00
+        if (fmax>fmin)
+        {
+            gt.SetMinimum(fmin);
+            gt.SetMaximum(fmax);
+            gz.SetMinimum(fmin);
+            gz.SetMaximum(fmax);
+        }
+
+        gROOT->SetSelectedPad(0);
+
+        TString cname  = fNameTab.IsNull() ? name(name.First('.')+2, name.Length()) : fNameTab;
+        TString ctitle = fDescription.IsNull() ? name.Data() : fDescription.Data();
+        if (ctitle.First(';')>0)
+            ctitle.Remove(ctitle.First(';'), ctitle.Length());
+
+        // Create a TCanvas or open a new tab
+        TCanvas &c = fDisplay ? fDisplay->AddTab(cname, ctitle) : *new TCanvas(cname, ctitle);
+        // Set fillcolor, remove border and divide pad
+        c.SetFillColor(kWhite);
+        c.SetFrameBorderMode(0);
+        c.SetBorderMode(0);
+        c.Divide(1,2);
+
+        // Output mean and rms to console
+        cerr << setprecision(4) << setw(10) << cname << ":   ";
+        if (gt.GetN()==0)
+        {
+            cerr << "     <empty>" << endl;
+            return;
+        }
+        cerr << setw(8) << gt.GetMean(2) << "+-" << setw(8) << gt.GetRMS(2) << "   ";
+        if (gt0.GetN()>0 || gt1.GetN()>0)
+        {
+            cerr << setw(8) << gt1.GetMean(2) << "+-" << setw(8) << gt1.GetRMS(2) << "   ";
+            cerr << setw(8) << gt0.GetMean(2) << "+-" << setw(8) << gt0.GetRMS(2);
+        }
+        cerr << endl;
+
+        // format axis
+        TH1 *h = gt.GetHistogram();
+
+        const Double_t min = fHistMin>fHistMax ? h->GetMinimum()-resolution/2 : fHistMin;
+        const Double_t max = fHistMin>fHistMax ? h->GetMaximum()+resolution/2 : fHistMax;
+
+        // Create histogram
+        const Int_t n = resolution>0 ? TMath::Nint((max-min)/resolution) : 50;
+
+        TH1F hist("Hist", Form("Distribution of %s", fDescription.IsNull() ? name.Data() : fDescription.Data()), n, min, max);
+        hist.SetDirectory(0);
+
+        // Fill data into histogra,
+        for (int i=0; i<gt.GetN(); i++)
+            hist.Fill(gt.GetY()[i]);
+
+        // Format histogram
+        if (fDescription.IsNull())
+            hist.SetXTitle(name);
+        hist.SetYTitle("Counts");
+
+        TVirtualPad *pad = gPad;
+
+        // draw contants of pad 2 (counting starts at 0)
+        pad->cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridy();
+
+        gPad->SetLeftMargin(0.06);
+        gPad->SetRightMargin(0.06);
+        gPad->SetBottomMargin(0.08);
+
+        h->SetXTitle("Time");
+        h->SetYTitle(hist.GetXaxis()->GetTitle());
+        h->GetXaxis()->SetTimeDisplay(1);
+        h->GetYaxis()->SetTitleOffset(0.8);
+        h->GetXaxis()->SetTitleOffset(1.0);
+        h->GetXaxis()->SetLabelOffset(0.01);
+
+        // draw TGraph
+        gROOT->SetSelectedPad(0);
+        gt.DrawClone("AP");
+        if (gt0.GetN()>0)
+            gt0.DrawClone("P");
+        if (gt1.GetN()>0)
+            gt1.DrawClone("P");
+
+        // Add lines and text showing the MAGIC periods
+        TLine l;
+        TText t;
+        Int_t num=0;
+        l.SetLineStyle(kDotted);
+        l.SetLineColor(kBlue);
+        t.SetTextColor(kBlue);
+        l.SetLineWidth(1);
+        t.SetTextSize(h->GetXaxis()->GetLabelSize());
+        t.SetTextAlign(21);
+        Int_t p0 = MAstro::GetMagicPeriod(first);
+        for (Int_t p = first; p<last; p++)
+        {
+            Int_t p1 = MAstro::GetMagicPeriod(p);
+            if (p1!=p0)
+            {
+                l.DrawLine(MTime(p).GetAxisTime(), h->GetMinimum(), MTime(p).GetAxisTime(), h->GetMaximum());
+                t.DrawText(MTime(p+15).GetAxisTime(), h->GetMaximum(), Form("%d", p1));
+                num++;
+            }
+            p0 = p1;
+        }
+        if (num<4)
+            gPad->SetGridx();
+
+        // Go back to first (upper) pad, format it and divide it again
+        pad->cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->Divide(2,1);
+
+        TVirtualPad *pad2 = gPad;
+
+        // format left pad
+        pad2->cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+
+        // plot histogram
+        hist.DrawCopy("");
+
+        // format right pad
+        pad2->cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridy();
+
+        // draw graph
+        gROOT->SetSelectedPad(0);
+        gz.GetXaxis()->SetTitle(res.GetFieldName(1));
+        gz.GetYaxis()->SetTitle(hist.GetXaxis()->GetTitle());
+        gz.DrawClone("AP");
+
+        if (gz0.GetN()>0)
+            gz0.DrawClone("P");
+        if (gz1.GetN()>0)
+            gz1.DrawClone("P");
+    }
+
+public:
+    MPlot(MSQLMagic &server) : fServer(server), fDataSet(NULL),
+        fRequestPeriod(-1), fPlotMin(0), fPlotMax(-1), fHistMin(0), fHistMax(-1), fGroupBy(kNone)
+    {
+    }
+    ~MPlot()
+    {
+        if (fDataSet)
+            delete fDataSet;
+    }
+    void SetDataSet(const TString filename, UInt_t num=(UInt_t)-1)
+    {
+        if (fDataSet)
+        {
+            delete fDataSet;
+            fDataSet = NULL;
+        }
+
+        fPrimaryNumber="";
+
+        if (filename.IsNull())
+            return;
+
+        fDataSet = new MDataSet(filename, num);
+        fPrimaryNumber="Sequences.fSequenceFirst";
+    }
+    void SetPlotRange(Float_t min, Float_t max/*, Int_t n=5*/) { fPlotMin = min; fPlotMax = max; }
+    void SetHistRange(Float_t min, Float_t max) { fHistMin = min; fHistMax = max; }
+    void SetRequestRange(const char *from="", const char *to="") { fRequestFrom = from; fRequestTo = to; }
+    void SetRequestPeriod(Int_t n=-1) { fRequestPeriod = n; }
+    void SetCondition(const char *cond="") { fCondition = cond; }
+    void SetDescription(const char *d, const char *t=0) { fDescription = d; fNameTab = t; }
+    void SetTabName(const char *t) { fNameTab = t; }
+    void SetGroupBy(GroupBy_t b=kGroupByWeek) { fGroupBy=b; }
+    void SetPrimaryDate(const char *ts) { fPrimaryDate=ts; }
+    void SetPrimaryNumber(const char *ts) { }
+    void SetSecondary(const char *ts) { fSecondary=ts; }
+
+    MStatusDisplay *GetDisplay() { return fDisplay; }
+    MSQLMagic &GetServer() { return fServer; }
+
+    Bool_t Plot(const char *value, Float_t min=0, Float_t max=-1, Float_t resolution=0)
+    {
+        TString named  = fPrimaryDate;
+        TString named2 = fSecondary;
+        TString namev  = value;
+
+        TString tablev = namev(0, namev.First('.'));
+        TString valuev = namev(namev.First('.')+1, namev.Length());
+
+        TString tabled = named(0, named.First('.'));
+        TString valued = named(named.First('.')+1, named.Length());
+
+        TString query="SELECT ";
+        switch (fGroupBy)
+        {
+        case kNone:
+        case kGroupByPrimary:
+            query += Form("%s AS %s", named.Data(), valued.Data()+1);
+            break;
+        case kGroupByHour:
+            query += Form("DATE_FORMAT(%s, '%%Y-%%m-%%d %%H:30:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
+            break;
+        case kGroupByNight:
+            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-%%m-%%d 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
+            break;
+        case kGroupByDay:
+            query += Form("DATE_FORMAT(%s, '%%Y-%%m-%%d 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
+            break;
+        case kGroupByWeek:
+            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%x%%v') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
+            break;
+        case kGroupByMonth:
+            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-%%m-15 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
+            break;
+        case kGroupBySeason:
+            //query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-%%m-15 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
+            break;
+        case kGroupByYear:
+            query += Form("DATE_FORMAT(ADDDATE(%s,Interval 12 hour), '%%Y-08-15 00:00:00') AS %s ", fPrimaryDate.Data(), valued.Data()+1);
+            break;
+        }
+
+        if (fGroupBy==kNone)
+        {
+            query += ", ";
+            query += fSecondary;
+            query += ", ";
+            query += value;
+        }
+        else
+        {
+            TString  v(value);
+            TPRegexp regexp(" +[aA][sS] +[a-zA-Z0-9]+ *$");
+
+            TString as = v(regexp);
+            Ssiz_t  p  = v.Index(as);
+
+            v.Prepend("(");
+            v.Insert(p<=0?v.Length():p+1, ")");
+
+            query += ", AVG(";
+            query += fSecondary;
+            query += "), AVG(";
+            query += v;
+            query += "), STD(";
+            query += fSecondary;
+            query += "), STD(";
+            query += v;
+            query += ")";
+        }
+
+        if (fDataSet)
+        {
+            query += ", ";
+            query += fPrimaryNumber;
+        }
+
+        query += Form(" FROM %s ", tabled.Data());
+
+        const Bool_t interval = !fRequestFrom.IsNull() && !fRequestTo.IsNull();
+
+        TString where(fCondition);
+        if (interval)
+        {
+            if (!where.IsNull())
+                where += " AND ";
+            where += Form("%s BETWEEN '%s' AND '%s' ",
+                          fPrimaryDate.Data(), fRequestFrom.Data(), fRequestTo.Data());
+        }
+
+        // ------------------------------
+
+        query += fServer.GetJoins(tabled, query+" "+where);
+
+        if (!where.IsNull())
+        {
+            query += "WHERE ";
+            query += where;
+            query += " ";
+        }
+
+        if (fGroupBy!=kNone)
+        {
+            query += Form("GROUP BY %s ", valued.Data()+1);
+            //query += Form(" HAVING COUNT(%s)=(COUNT(*)+1)/2 ", valuev.Data());
+        }
+        query += Form("ORDER BY %s ", valued.Data()+1);
+
+        // ------------------------------
+        TSQLResult *res = fServer.Query(query);
+        if (!res)
+        {
+            cout << "ERROR - Query failed: " << query << endl;
+            return kFALSE;
+        }
+
+        if (max>min)
+            PlotTable(*res, namev, min, max, resolution);
+        else
+            PlotTable(*res, namev, fPlotMin, fPlotMax, resolution);
+
+
+        delete res;
+        return kTRUE;
+    }
+//    ClassDef(MPlot, 0)
+};
+
+//ClassImp(MPlot);
+
+void plotalldb(MPlot &plot)
+{
+    //plot.SetGroupBy(MPlot::kGroupByMonth);
+    //plot.SetDataSet("dataset.txt");
+
+    plot.SetPrimaryDate("Sequences.fRunStart");
+    plot.SetSecondary("(Sequences.fZenithDistanceMin+Sequences.fZenithDistanceMax)/2 as '<Zd>'");
+
+    //inner camera
+    //from calib*.root
+    plot.SetDescription("Median number of calibration phe in inner pixels;C [phe]", "CalPheI");
+    plot.Plot("Calibration.fMedNumPheInner", 0, 200, 1);
+    plot.SetDescription("Relative rms of calibration charge inner pixels;\\sigma_C [%]", "CalRmsI");
+    plot.Plot("Calibration.fRelChargeRmsInner", 0, 0.5, 0.01);
+    plot.SetDescription("Conversion Factor inner Camera;C_{I} [phe/fadc cnts]", "ConvI");
+    plot.Plot("Calibration.fConvFactorInner",  0, 0.7, 0.002);
+    plot.SetDescription("Mean Arrival Time inner Camera;T_{I} [sl]", "ArrTmI");
+    plot.Plot("Calibration.fArrTimeMeanInner", 0, 40.0, 0.1);
+    plot.SetDescription("RMS Arrival Time inner Camera;\\sigma_{T,I} [sl]", "RmsArrTmI");
+    plot.Plot("Calibration.fArrTimeRmsInner",  0, 6.5, 0.01);
+    plot.SetDescription("Number of unsuitable pixels inner Camera;N_{I}", "UnsuitI");
+    plot.Plot("Calibration.fUnsuitableInner",  0, 75, 1);
+    plot.SetDescription("Number of unsuitable pixels >50%;N", "Unsuit50");
+    plot.Plot("Calibration.fUnsuitable50",  0, 75, 1);
+    plot.SetDescription("Number of unsuitable pixels >1%;N", "Unsuit01");
+    plot.Plot("Calibration.fUnsuitable01",  0, 200, 5);
+
+    //from signal*.root
+    plot.SetDescription("Mean Pedestal RMS inner Camera;\\sigma_{P,I} [phe]", "PedRmsI");
+    plot.Plot("Calibration.fMeanPedRmsInner",  0, 3.5, 0.05);
+    plot.SetDescription("Mean Signal inner Camera;S_{I} [phe]", "SignalI");
+    plot.Plot("Calibration.fMeanSignalInner",  0, 7.0, 0.05);
+
+    plot.SetDescription("Mean PulsePosCheck (maximum slice) inner camera;T [sl]", "ChkPos");
+    plot.Plot("Calibration.fPulsePosCheckMean", 1, 50.0, 0.1);
+    plot.SetDescription("Rms PulsePosCheck (maximum slice) inner camera;T [sl]", "ChkRms");
+    plot.Plot("Calibration.fPulsePosCheckRms", 0, 12.0, 0.1);
+    plot.SetDescription("Mean calibrated PulsePos (as extracted);T [ns]", "PulPos");
+    plot.Plot("Calibration.fPulsePosMean", 1, 40.0, 0.1);
+    plot.SetDescription("Rms calibrated PulsePos (as extracted);T [ns]", "PulRms");
+    plot.Plot("Calibration.fPulsePosRms", 0, 3.0, 0.02);
+
+    plot.SetDescription("Ratio of accepted calibration events in cal-run;f [%]", "RatioCal");
+    plot.Plot("Calibration.fRatioCalEvents", 0, 105, 5);
+
+    plot.SetDescription("Average rate of events with lvl1 trigger;R [Hz]", "RateTrig");
+    plot.Plot("Calibration.fRateTrigEvts", 0, 500, 5);
+    plot.SetDescription("Average rate of events with only Sum trigger;R [Hz]", "RateSum");
+    plot.Plot("Calibration.fRateSumEvts", 0, 1500, 5);
+    //plot.SetDescription("Ratio of only Sum to Lvl1 triggers;R [Hz]", "RateRatio");
+    //plot.Plot("100*Calibration.fRateSumEvts/Calibration.fRateTrigEvts", 0, 500, 1);
+    plot.SetDescription("Average rate of events with calibration trigger;R [Hz]", "RateCal");
+    plot.Plot("Calibration.fRateCalEvts", 0, 75, 1);
+    plot.SetDescription("Average rate of events with pedestal trigger;R [Hz]", "RatePed");
+    plot.Plot("Calibration.fRatePedEvts", 0, 50, 1);
+    plot.SetDescription("Average rate of events with ped+cosmics trigger;R [Hz]", "RatePT");
+    plot.Plot("Calibration.fRatePedTrigEvts", 0, 4.0, 0.1);
+    plot.SetDescription("Average rate of events without trigger pattern;R [Hz]", "Rate0");
+    plot.Plot("Calibration.fRateNullEvts", 0, 3.5, 0.1);
+    plot.SetDescription("Average rate of unknown trigger pattern;R [Hz]", "RateUnknown");
+    plot.Plot("Calibration.fRateUnknownEvts", 0, 3.5, 0.1);
+
+    plot.SetDescription("Hi-/Lo-Gain offset;", "PulOff");
+    plot.Plot("Calibration.fPulsePosOffMed", -0.33, 0.5, 0.01);
+    plot.SetDescription("Hi-/Lo-Gain ratio;", "HiLoRatio");
+    plot.Plot("Calibration.fHiLoGainRatioMed", 10, 15, 0.05);
+
+    //plot.SetDescription("Pulse Variance;", "PulVar");
+    //plot.Plot("Calibration.fPulsePosVar", 0, 0.03, 0.001);
+
+    //from star*.root
+    //muon
+    plot.SetCondition("Star.fMuonNumber>300");
+    plot.SetDescription("Point Spred Function;PSF [mm]");
+    plot.Plot("Star.fPSF",                     0,  30, 0.5);
+    plot.SetDescription("Muon Calibration Ratio Data/MC;r [1]", "MuonCal");
+    plot.Plot("Star.fRatio",                   50, 150, 0.5);
+    plot.SetDescription("Muon Rate after Muon Cuts;R [Hz]");
+    plot.Plot("Star.fMuonRate",                0, 2.0, 0.05);
+    plot.SetCondition();
+
+    //quality
+    plot.SetDescription("Datarate [Hz]", "Rate");
+    plot.Plot("Star.fDataRate",                0, 600, 10);
+    plot.SetDescription("Camera Inhomogeneity;\\sigma [%]", "Inhom");
+    plot.Plot("Star.fInhomogeneity",           0, 100, 1);
+    plot.SetDescription("Camera Spark Rate;R [Hz]", "Sparks");
+    plot.Plot("Star.fSparkRate",               0.075, 7.425, 0.05);
+    plot.SetDescription("Relative effective on time;T_{eff}/T_{obs} [ratio]", "RelTime");
+    plot.Plot("Star.fEffOnTime/Sequences.fRunTime",    0.006, 1.506, 0.01);
+    //imgpar
+    plot.SetDescription("Mean Number of Islands after cleaning;N [#]", "NumIsl");
+    plot.Plot("Star.fMeanNumberIslands",       0.5, 4.5, 0.01);
+    //weather
+    plot.SetCondition("");
+    plot.SetDescription("Average Temperature [\\circ C];T [\\circ C]", "Temp");
+    plot.Plot("Star.fAvgTemperature",        -5, 25, 1);
+    plot.SetDescription("Average Cloudiness [%]", "AvgClouds");
+    plot.Plot("Star.fAvgCloudiness",           0, 100, 1);
+    plot.SetDescription("RMS Cloudiness [%]", "RmsClouds");
+    plot.Plot("Star.fRmsCloudiness",           0,  30, 1);
+    plot.SetDescription("Sky Temperature [K]", "SkyTemp");
+    plot.Plot("Star.fAvgTempSky",         180, 280, 1);
+    plot.SetDescription("Maximum Humidity [%]", "MaxHum");
+    plot.Plot("Star.fMaxHumidity",             0, 100, 1);
+    plot.SetDescription("Average Humidity [%]", "AvgHum");
+    plot.Plot("Star.fAvgHumidity",             0, 100, 1);
+    plot.SetDescription("Average Wind Speed [km/h];v [km/h]", "Wind");
+    plot.Plot("Star.fAvgWindSpeed",        0, 50, 1);
+
+    //currents
+    plot.SetSecondary("Calibration.fMeanPedRmsInner as '<PedRMS_{I}>'");
+    plot.SetDescription("Minimum average DC current [nA];<I_{min}> [nA]", "MinDC");
+    plot.Plot("Star.fMinCurrents",        0, 25, 0.1);
+    plot.SetDescription("Median average DC current [nA];<I_{med}> [nA]", "MedDC");
+    plot.Plot("Star.fMedCurrents",        0, 25, 0.1);
+    plot.SetDescription("Maximum average DC current [nA];<I_{max}> [nA]", "MaxDC");
+    plot.Plot("Star.fMaxCurrents",        0, 25, 0.1);
+    plot.SetSecondary("(Sequences.fZenithDistanceMin+Sequences.fZenithDistanceMax)/2 as '<Zd>'");
+
+    //muon
+    //plot.SetDescription("Number of Muons after Muon Cuts;N [#]");
+    //plot.Plot("Star.fMuonNumber",              0, 10000, 100);
+
+    // starguider
+    plot.SetDescription("Median No. Stars recognized by the starguider;N_{0}", "StarsMed");
+    plot.Plot("Star.fNumStarsMed",                          0,  100,  1);
+    plot.SetDescription("RMS No. Stars recognized by the starguider;\\sigma_{N_{0}}", "StarsRMS");
+    plot.Plot("Star.fNumStarsRMS",                          0,   25,  1);
+    plot.SetDescription("Median No. Stars correlated by the starguider;N", "CorMed");
+    plot.Plot("Star.fNumStarsCorMed",                       0,  100,  1);
+    plot.SetDescription("RMS No. Stars correlated by the starguider;\\sigma_{N}", "CorRMS");
+    plot.Plot("Star.fNumStarsCorRMS",                       0,   25,  1);
+    plot.SetDescription("Relative number of correlated stars;N/N_{0} [%]", "StarsRel");
+    plot.Plot("Star.fNumStarsCorMed/Star.fNumStarsMed*100", 0, 100, 10);
+    plot.SetDescription("Median skbrightess measured by the starguider;B [au]", "BrightMed");
+    plot.Plot("Star.fBrightnessMed",                        0, 111,  1);
+    plot.SetDescription("RMS skybrightess measured by the starguider;\\sigma_{B} [au]", "BrightRMS");
+    plot.Plot("Star.fBrightnessRMS",                        0,  64,  1);
+
+    //outer camera
+    //from calib*.root
+    plot.SetDescription("Median number of calibration phe in outer pixels;C [phe]", "CalPheO");
+    plot.Plot("Calibration.fMedNumPheOuter", 0, 200, 1);
+    plot.SetDescription("Relative rms of calibration charge outer pixels;\\sigma_C [%]", "CalRmsO");
+    plot.Plot("Calibration.fRelChargeRmsOuter", 0, 0.5, 0.01);
+    plot.SetDescription("Conversion Factor outer Camera;C_{O} [phe/fadc cnts]", "ConvO");
+    plot.Plot("Calibration.fConvFactorOuter",  0, 3.0, 0.01);
+    plot.SetDescription("Mean Arrival Time outer Camera;T_{O} [sl]", "ArrTmO");
+    plot.Plot("Calibration.fArrTimeMeanOuter", 0, 45, 0.1);
+    plot.SetDescription("RMS Arrival Time outer Camera;\\sigma_{T,O} [sl]", "RmsArrTmO");
+    plot.Plot("Calibration.fArrTimeRmsOuter",  0, 4.5, 0.01);
+    plot.SetDescription("Number of unsuitable pixels outer Camera;N_{O}", "UnsuitO");
+    plot.Plot("Calibration.fUnsuitableOuter",  0, 25, 1);
+    //from signal*.root
+    plot.SetDescription("Mean Pedestal RMS outer Camera;\\sigma_{P,O} [phe]", "PedRmsO");
+    plot.Plot("Calibration.fMeanPedRmsOuter",  0, 4.0, 0.05);
+    plot.SetDescription("Mean Signal outer Camera;S_{O} [phe]", "SignalO");
+    plot.Plot("Calibration.fMeanSignalOuter",  0, 4.0, 0.05);
+}
+
+int plotdb(TString from, TString to, const char *dataset=0, UInt_t num=(UInt_t)-1)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotdb" << endl;
+    cout << "------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    plot.SetDataSet(dataset, num);
+    plot.SetDisplay(d);
+    plot.SetRequestRange(from, to);
+    plotalldb(plot);
+    d->SaveAsRoot("plotdb.root");
+    //d->SaveAsPS("plotdb.ps");
+
+    return 1;
+}
+
+int plotdb(const char *ds, UInt_t num, TString path="/magic/sequences")
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotdb" << endl;
+    cout << "------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    plot.SetDataSet(ds, num);
+    plot.SetDisplay(d);
+    plot.SetRequestRange("", "");
+    plotalldb(plot);
+    d->SaveAsRoot(path+"plotdb.root");
+//    d->SaveAsPS("plotdb.ps");
+
+    return 1;
+}
+
+int plotdb(const char *ds, TString path="/magic/sequences")
+{
+    return plotdb(ds, (UInt_t)-1, path);
+}
+
+int plotdb(TString path)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotdb" << endl;
+    cout << "------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+//    plot.SetDataSet(ds);
+    plot.SetDisplay(d);
+    plot.SetRequestRange("", "");
+    plotalldb(plot);
+    d->SaveAsRoot(path+"plotdb.root");
+//    d->SaveAsPS("plotdb.ps");
+
+    return 1;
+}
+
+int plotdb(Int_t period, const char *dataset="")
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotdb" << endl;
+    cout << "------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    plot.SetDataSet(dataset);
+    plot.SetDisplay(d);
+    plot.SetRequestPeriod(period);
+    plotalldb(plot);
+    d->SaveAsRoot("plotdb.root");
+    //d->SaveAsPS("plotdb.ps");
+
+    return 1;
+}
+
+int plotdb()
+{
+    return plotdb("", "", "");
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/plotoptical.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/plotoptical.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/plotoptical.C	(revision 17960)
@@ -0,0 +1,297 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: plotoptical.C,v 1.11 2009-01-27 13:56:15 tbretz Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// plotoptical.C
+// =============
+//
+// This macro is used to read optical data from the DB and plot them.
+// 
+// In the DB these values are stored in the tables Calibration and Star.
+//
+//
+// To plot the whole database simple use:
+//   .x plotdb.C+
+//
+// Plot only data for one source. For the available sources see the database
+//   .x plotdb.C+("source")
+//
+// You can chose are certain MAGIC-period:
+//   .x plotdb.C+(25)   --> all values from period 25 are plotted
+//
+// MAGIC periods correspond to one moon-phase and are defined as
+// moon period-284. For details see MAstro::MoonPeriod and
+// MAstro::MagicPeriod.
+//
+// or a time period from a certain date to a certain date
+//   .x plotdb.C+("2004-11-14 00:00:00", "2005-02-28 00:00:00")
+//  --> all values from 14.11.2004 0h to 28.2.2005 0h are plotted
+//   .x plotdb.C+("2004-11-14 00:00:00", "2005-02-28 00:00:00", "source")
+//  --> all values from 14.11.2004 0h to 28.2.2005 0h of "source" are plotted
+//
+//
+// For details of the plots produced see the function plotall() below.
+//
+//
+// The plot title and axis-titles are created by:
+//    plot.SetDescription("Title;x", "TabName");
+//
+// Drawing the plot is initiated by
+//    plot.Plot("OpticalData.fExposure", min, max, width);
+//
+// While OpticalData.fExposure can be any kind of variable to plot.
+// min and max are the minimum and maximum of the histogram which is
+// filled and width is the bin-width of this histogram.
+//
+// To group data (average) of a certain period use:
+//    plot.GroupBy(MPlot::kGroupByNight);
+// before initiating the plot.
+//
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "plotdb.C"
+
+void plotalloptical(MPlot &plot, TString source)
+{
+    // Setup here the values for timestamp and secondary (upper/right) plot
+    plot.SetPrimaryDate("OpticalData.fTimestamp");
+    plot.SetPrimaryNumber("OpticalData.fTimestamp");
+    plot.SetSecondary("OpticalData.fZenithDistance");
+
+    // This is the condition to take only the "ok" flagged data
+    // and to restrict the query to a given source (if any)
+    TString cond = "fStatusKEY=1 AND fTelescopeKEY=1 AND fCCDKEY=1 AND fFilterKEY=1";
+    if (!source.IsNull())
+    {
+        const Int_t key = plot.GetServer().QueryKeyOfName("Object", source, kFALSE);
+        if (key<0)
+            return;
+        cond += Form(" AND Object.fObjectKEY=%d", key);
+    }
+
+    plot.SetCondition(cond);
+
+    // Plot exposure
+    plot.SetDescription("Exposure;T_{E} [s]", "Expo");
+    plot.Plot("OpticalData.fExposure",  0, 900, 60);
+
+    // plot sky level
+    plot.SetDescription("Sky Level;B [s^{-1}]", "SkyLvl");
+    plot.Plot("OpticalData.fSkyLevel/OpticalData.fExposure", 0, 5.0, 0.01);
+
+    // plot FWHM
+    plot.SetDescription("Full Width Half Maximum;FWHM [s^{-1}]", "Fwhm");
+    plot.Plot("OpticalData.fFWHM/OpticalData.fExposure",  0, 0.05, 0.001);
+
+    // plot Aperture Radius
+    plot.SetDescription("Aperture Radius;R_{A}", "ApRad");
+    plot.Plot("OpticalData.fApertureRadius", 0, 10, 1);
+
+    /*
+     // Plot instrumental magnitude
+     plot.SetDescription("Instrumental Magnitude;M_{I}", "InstMag");
+     plot.Plot("OpticalData.fInstrumentalMag",  0, 30, 0.5);
+
+     // Plot error of instrumental magnitude
+     plot.SetDescription("Instrumental Magnitude Error;\\sigma_{M}", "MagErr");
+     plot.Plot("OpticalData.fInstrumentalMagErr",  0, 1, 0.01);
+     */
+
+    // Plot magnitude corrected for the exposure
+    plot.SetDescription("m_{1};m_{1}", "M1");
+    plot.Plot("OpticalData.fInstrumentalMag+2.5*log10(OpticalData.fExposure)", 10, 35, 0.2);
+
+    // Now take out all points named */BL from further queries
+    // And skip all sources the magnitude is not known
+    cond += " AND Object.fObjectName NOT LIKE '%/BL' AND NOT ISNULL(Object.fMagnitude) ";
+    plot.SetCondition(cond);
+
+    // Formula to calculate the extinction
+    TString ext("3080/25.0*pow(10, (OpticalData.fInstrumentalMag+2.5*log10(OpticalData.fExposure)-Object.fMagnitude)/-2.5)");
+    // Add this to correct for the ZA dependancy
+    //    ext += "+0.0028*fZenithDistance-0.08";
+
+    // Group all data of one image together and plot extinction
+    plot.SetGroupBy(MPlot::kGroupByPrimary);
+    plot.SetDescription("m_{1}-m_{true} (Extinction per Image);m_{1}-m_{true}", "ExtImg");
+    plot.Plot(ext, 0.05, 1.2, 0.01);
+
+    // Group data hourly together and plot extinction
+    plot.SetGroupBy(MPlot::kGroupByHour);
+    plot.SetDescription("m_{1}-m_{true} (Extinction per Hour);m_{1}-m_{true}", "ExtHour");
+    plot.Plot(ext, 0.5, 1.2, 0.01);
+
+    // Group data hourly together and plot extinction
+    plot.SetGroupBy(MPlot::kGroupByNight);
+    plot.SetDescription("m_{1}-m_{true} (Extinction per Night);m_{1}-m_{true}", "ExtNight");
+    plot.Plot(ext, 0.5, 1.2, 0.01);
+
+    // Group data monthly together and plot extinction
+    plot.SetGroupBy(MPlot::kGroupByMonth);
+    plot.SetDescription("m_{1}-m_{true} (Extinction per Month);m_{1}-m_{true}", "ExtMonth");
+    plot.Plot(ext, 0.5, 1.2, 0.01);
+
+    // Group data yearly together and plot extinction
+    plot.SetGroupBy(MPlot::kGroupByYear);
+    plot.SetDescription("m_{1}-m_{true} (Extinction per Year);m_{1}-m_{true}", "ExtYear");
+    plot.Plot(ext, 0.5, 1.2, 0.01);
+}
+
+int plotoptical(TString from, TString to, const char *source=0)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotoptical" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    // plot.SetDataSet(dataset);
+    plot.SetDisplay(d);
+    plot.SetRequestRange(from, to);
+    plotalloptical(plot, source);
+    // Use this to create output plots automatically
+    d->SaveAsRoot("plotoptical.root");
+    //  d->SaveAsPS("plotoptical.ps");
+
+    return 1;
+}
+
+int plotoptical(const char *source, TString path)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotoptical" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    // plot.SetDataSet(ds);
+    plot.SetDisplay(d);
+    plot.SetRequestRange("", "");
+    plotalloptical(plot, source);
+    // Use this to create output plots automatically
+    d->SaveAsRoot("plotoptical.root");
+    //  d->SaveAsPS("plotoptical.ps");
+
+    return 1;
+}
+
+int plotoptical(Int_t period, const char *source="")
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotoptical" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    // plot.SetDataSet(dataset);
+    plot.SetDisplay(d);
+    plot.SetRequestPeriod(period);
+    plotalloptical(plot, source);
+
+    // Use this to create output plots automatically
+    d->SaveAsRoot("plotoptical.root");
+    //  d->SaveAsPS("plotoptical.ps");
+
+    return 1;
+}
+
+int plotoptical(TString path)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotoptical" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    // plot.SetDataSet(dataset);
+    plot.SetDisplay(d);
+    //plot.SetRequestPeriod(period);
+    plotalloptical(plot, 0);
+
+    // Use this to create output plots automatically
+    d->SaveAsRoot(path+"plotoptical.root");
+    //  d->SaveAsPS("plotoptical.ps");
+
+    return 1;
+}
+
+int plotoptical()
+{
+    return plotoptical("", "");
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/plotrundb.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/plotrundb.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/plotrundb.C	(revision 17960)
@@ -0,0 +1,220 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: plotrundb.C,v 1.9 2009-03-16 15:13:43 tbretz Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// plotundb.C
+// ==========
+//
+// This macro is used to read quality parameters from the DB and plot them.
+// 
+// The parameters are from the following files:
+// calib*.root:mean conversion factor, mean arrival time, rms arrival time
+// (each parameter for inner and outer camera)
+// signal*.root: mean pedestal rms (for inner and outer camera)
+// star*.root: PSF, # of Muons, Effective OnTime, Muon rate,
+// Ratio MC/Data(MuonSize) and mean number of islands
+// 
+// In the DB these values are stored in the tables Calibration and Star.
+// 
+// Usage:
+//   .x plotundb.C   --> all values in the DB are plotted
+// You can chose are certain period:
+//   .x plotrundb.C(25)   --> all values from period 25 are plotted
+// or a time period from a certain date to a certain date
+//   .x plotrundb.C("2004-11-14 00:00:00", "2005-02-28 00:00:00")
+//  --> all values from 14.11.2004 0h to 28.2.2005 0h are plotted
+// or all data, but with dataset data highlighted
+//   .x plotrundb.C("dataset.txt")
+//  --> the sequences defined in dataset.txt are highlighted (blue:on, red:off)
+//  --> You can also add a dataset-name as last argument to one of the
+//      calls above
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "plotdb.C"
+
+void plotall(MPlot &plot, Int_t tel=0)
+{
+    //    plot.SetGroupBy(MPlot::kGroupByNight);
+
+    plot.SetPrimaryDate("RunData.fRunStart");
+    plot.SetPrimaryNumber("RunData.fRunNumber");
+    plot.SetSecondary("RunData.fZenithDistance");
+
+    MTime t(-1);
+    TString cond = "RunData.fExcludedFDAKEY=1 AND RunData.fRunStart BETWEEN '2004-01-01' AND '";
+    cond += t.GetSqlDateTime();
+    cond += "'";
+    if (tel>0)
+    {
+        cond += " AND fTelescopeNumber=";
+        cond += tel;
+    }
+
+    //cond +=" AND (RunData.fSourceKEY=403 OR RunData.fSourceKEY=871) ";
+
+    plot.SetCondition(cond);
+
+    //inner camera
+    //from calib*.root
+    plot.SetDescription("DAQ Storage Rate;R_{DAQ,S} [Hz]", "StoreRate");
+    plot.Plot("RunData.fDaqStoreRate",  -0.5, 999.5, 5);
+    plot.SetDescription("DAQ Trigger Rate;R_{DAQ,T} [Hz]", "TrigRate");
+    plot.Plot("RunData.fDaqTriggerRate", -0.5, 999.5, 5);
+    plot.SetDescription("Mean Trigger Rate;<R> [Hz]", "MeanTrig");
+    plot.Plot("RunData.fMeanTriggerRate", -0.5, 999.5, 5);
+    plot.SetDescription("L2 Trigger rate after prescaler;R_{L2,P}", "Presc");
+    plot.Plot("RunData.fL2RatePresc", -0.5, 999.5, 5);
+    plot.SetDescription("L2 Trigger rate before prescaler;R_{L2,U}", "Unpresc");
+    plot.Plot("RunData.fL2RateUnpresc", -0.5, 999.5, 5);
+
+    plot.SetDescription("L1 trigger rate after cleaning;R_{L1}", "CleanL1");
+    plot.Plot("RunDataCheck.fRateCleanedTrig", -0.5, 399.5, 1);
+    plot.SetDescription("Sum trigger rate after cleaning;R_{sum}", "CleanSum");
+    plot.Plot("RunDataCheck.fRateCleanedSum", -0.5, 399.5, 1);
+    plot.SetDescription("Unknown events trigger rate after cleaning;R_{0}", "Clean0");
+    plot.Plot("RunDataCheck.fRateCleanedNull", -0.5, 399.5, 1);
+
+/*
+    //from signal*.root
+    plot.SetDescription("Signal Position;<T_{S}> [sl]", "PosMean");
+    plot.Plot("DataCheck.fPositionSignal",  -0.5, 29.5, 1);
+    plot.SetDescription("Signal Position FWHM;\\sigma_{S} [sl]", "PosFWHM");
+    plot.Plot("DataCheck.fPositionFWHM",  -0.5, 29.5, 1);
+    plot.SetDescription("Signal Height;<H_{s}> [counts]", "SigMean");
+    plot.Plot("DataCheck.fHeightSignal",  -0.5, 256.5, 1);
+    plot.SetDescription("Signal Height FWHM;\\sigma_{H} [counts]", "SigFWHM");
+    plot.Plot("DataCheck.fHeightFWHM",  -0.5, 155.5, 1);
+
+    plot.SetDescription("Interleaved Signal Position;<T_{S}> [sl]", "IPosMean");
+    plot.Plot("DataCheck.fPositionSignalInterlaced", -0.5, 29.5, 1);
+    plot.SetDescription("Interleaved Signal Position FWHM;\\sigma_{S} [sl]", "IPosFWHM");
+    plot.Plot("DataCheck.fPositionFWHMInterlaced", -0.5, 29.5, 1);
+    plot.SetDescription("Interleaved Signal Height;<H_{s}> [counts]", "ISigMean");
+    plot.Plot("DataCheck.fHeightSignalInterlaced", -0.5, 256.5, 1);
+    plot.SetDescription("Interleaved Signal Height FWHM;\\sigma_{H} [counts]", "ISigFWHM");
+    plot.Plot("DataCheck.fHeightFWHMInterlaced",  -0.5, 155.5, 1);
+*/
+}
+
+int plotrundb(TString from, TString to, const char *dataset=0, UInt_t num=(UInt_t)-1)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotrundb" << endl;
+    cout << "---------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    plot.SetDataSet(dataset, num);
+    plot.SetDisplay(d);
+    plot.SetRequestRange(from, to);
+    plotall(plot);
+    d->SaveAsRoot("plotrundb.root");
+    d->SaveAsPS("plotrundb.ps");
+
+    return 1;
+}
+
+int plotrundb(const char *ds, UInt_t num=(UInt_t)-1)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotrundb" << endl;
+    cout << "---------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    plot.SetDataSet(ds, num);
+    plot.SetDisplay(d);
+    plot.SetRequestRange("", "");
+    plotall(plot);
+    d->SaveAsRoot("plotrundb.root");
+    d->SaveAsPS("plotrundb.ps");
+
+    return 1;
+}
+
+int plotrundb(Int_t period, const char *dataset="")
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotrundb" << endl;
+    cout << "---------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    plot.SetDataSet(dataset);
+    plot.SetDisplay(d);
+    plot.SetRequestPeriod(period);
+    plotall(plot);
+    d->SaveAsRoot("plotrundb.root");
+    d->SaveAsPS("plotrundb.ps");
+
+    return 1;
+}
+
+int plotrundb()
+{
+    return plotrundb("", "");
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/plotstat.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/plotstat.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/plotstat.C	(revision 17960)
@@ -0,0 +1,746 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: plotstat.C,v 1.11 2009-01-30 14:58:40 tbretz Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 02/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// plotstat.C
+// ==========
+//
+// This macro is used to plot processing statistics from the db.
+//
+// Normally all period are processed. If you want to restric processing to
+// less periods, use:
+//   > root plotstat.C+(20, -1)
+// means that all periods since 20 are taken into account. The two numbers
+// denote the first and last period taken into account, -1 means
+// open start or open end.
+// 
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+
+#include <TH2.h>
+#include <TPad.h>
+#include <TLine.h>
+#include <TText.h>
+#include <TCanvas.h>
+#include <TLegend.h>
+#include <TPaveText.h>
+#include <TEllipse.h>
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MH.h"
+#include "MTime.h"
+#include "MBinning.h"
+#include "MSQLServer.h"
+#include "MStatusDisplay.h"
+
+using namespace std;
+
+TString GetFullQuery(TString query, TString from="", TString to="")
+{
+    if (from.IsNull())
+        return query;
+
+    if (!query.Contains("where", TString::kIgnoreCase))
+        query += " where ";
+    else
+        query += " and ";
+
+    query += " fRunStart>'";
+    query += from;
+    query += "' and fRunStart<'";
+    query += to;
+    query += "'";
+
+    return query;
+}
+
+Double_t GetTime(MSQLServer &serv, TString query, TString from="", TString to="")
+{
+    query = GetFullQuery(query, from, to);
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return -1;
+    }
+
+    TSQLRow *row=res->Next();
+    if (!row)
+    {
+        cout << "ERROR - Query " << query << " empty." << endl;
+        delete res;
+        return -1;
+    }
+
+    const char *time = (*row)[0];
+
+    const Double_t rc = time ? atof(time) : 0;
+
+    delete res;
+    return rc<0 || rc>200 ? 0 : rc;
+}
+
+TArrayD GetObsDist(MSQLServer &serv, TString from="", TString to="")
+{
+    // 8: Sequenced RunTime per source and night
+    //query[8]  = "select SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart)))/3600, ";
+    //query[8] += "DATE_FORMAT(ADDDATE(fRunStart,Interval 12 hour), '%Y-%m-%d') as Start,";
+    //query[8] += "from RunData where fRunTypeKEY=2 and fExcludedFDAKEY=1 group by Start, fSourceKEY";
+
+    TString query;
+
+    query  = "SELECT SUM(fRunTime)/3600, ";
+    query += "DATE_FORMAT(ADDDATE(fRunStart, INTERVAL 12 hour), '%Y-%m-%d') AS Start ";
+    query += "FROM Sequences ";
+
+    query  = GetFullQuery(query, from, to);
+    query += " GROUP BY Start, fSourceKEY";
+
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return -1;
+    }
+
+    TSQLRow *row = 0;
+
+    TArrayD arr;
+
+    while ((row=res->Next()))
+    {
+        const char *time = (*row)[0];
+
+        const Double_t rc = time ? atof(time) : 0;
+
+        if (rc>0 && rc<200)
+        {
+            arr.Set(arr.GetSize()+1);
+            arr[arr.GetSize()-1] = rc;
+        }
+    }
+
+    delete res;
+
+    return arr;
+}
+
+void DrawYears()
+{
+    UInt_t year   = 2004;
+    Int_t  period = 0;
+
+    MTime past, from, now(-1);
+    past.Set(2004, 1, 1, 13, 1);
+
+    TLine l;
+    l.SetLineStyle(kDotted);
+    l.SetLineColor(kWhite);
+    while (past<now)
+    {
+        if (period!=past.GetMagicPeriod())
+        {
+            period = past.GetMagicPeriod();
+            from = past;
+        }
+
+        if (past.Year()!=year)
+        {
+            Double_t dx = (past.GetMjd()-from.GetMjd())/28;
+            l.DrawLine(past.GetMagicPeriod()+dx, 0,
+                       past.GetMagicPeriod()+dx, gPad->GetUymax());
+            year = past.Year();
+        }
+        past.SetMjd(past.GetMjd()+1);
+    }
+}
+
+void DrawCake(TH1F *h, Int_t p0=-1, Int_t p1=9999)
+{
+    gPad->Range(-1, -0.84, 1, 1.16);
+
+    gPad->SetFillColor(kWhite);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+
+    const Double_t r1 = 0.8;
+    const Double_t r2 = 0.59;
+
+    const Double_t tot0 = h[0].Integral(p0, p1);
+    const Double_t tot1 = h[1].Integral(p0, p1);
+    const Double_t tot2 = h[2].Integral(p0, p1);
+    const Double_t tot3 = h[3].Integral(p0, p1);
+    const Double_t tot4 = h[4].Integral(p0, p1);
+    const Double_t tot5 = h[5].Integral(p0, p1);
+    const Double_t tot6 = h[6].Integral(p0, p1);
+    const Double_t tot7 = h[7].Integral(p0, p1);
+
+
+    TPaveText *pave = new TPaveText(-0.99, 0.87, 0.99, 1.15);
+    pave->SetBorderSize(1);
+
+    TString title = Form("Total = %.1fh (excl=%.1fh)", tot1, tot1-tot2);
+    if (p0>0 && p1<9000 && p0==p1)
+        title.Prepend(Form("P%d: ", TMath::Nint(h[0].GetBinCenter(p0))));
+
+    pave->AddText(title)->SetTextAlign(22);
+
+    if (p0>0 && p1<9000)
+    {
+        MTime t0, t1;
+        t0.SetMagicPeriodStart(p0);
+        t1.SetMagicPeriodStart(p1+1);
+
+        pave->AddText(Form("%s 12h  -  %s 12h", t0.GetStringFmt("%Y/%m/%d").Data(), t1.GetStringFmt("%Y/%m/%d").Data()));
+    }
+    pave->SetBit(kCanDelete);
+    pave->Draw();
+
+    if (tot1<0.1)
+        return;
+
+    TEllipse e;
+    e.SetFillColor(15);
+    //e.SetLineColor(15);
+    e.DrawEllipse(0, 0, r1*1.1, r2*1.1, 90, tot0/tot1*360+90, 0);
+
+    //    0    : hollow
+    //    1001 : Solid
+    //    2001 : hatch style
+    //    3000+pattern_number (see below)
+    //    4000 :the window is transparent.
+    //    4000 to 4100 the window is 100% transparent to 100% opaque
+
+    e.SetLineColor(10);//17);
+    e.SetFillColor(10);//17);
+    e.DrawEllipse(0, 0, r1, r2, 0, 360, 0);
+    e.SetLineColor(kBlack);
+
+    e.SetFillColor(kBlack);
+    e.DrawEllipse(0, 0, r1, r2, 90, tot2/tot1*360+90, 0);
+    //e.SetLineColor(kBlue);
+    e.SetFillColor(kBlue);
+    e.DrawEllipse(0, 0, r1, r2, 90, tot3/tot1*360+90, 0);
+    //e.SetLineColor(kRed);
+    e.SetFillColor(kRed);
+    e.DrawEllipse(0, 0, r1, r2, 90, tot4/tot1*360+90, 0);
+    //e.SetLineColor(kGreen);
+    e.SetFillColor(kGreen);
+    e.DrawEllipse(0, 0, r1, r2, 90, tot5/tot1*360+90, 0);
+    //e.SetLineColor(kRed+100);
+    e.SetFillColor(kRed+100);
+    e.DrawEllipse(0, 0, r1, r2, 90, tot6/tot1*360+90, 0);
+    //e.SetLineColor(kGreen+100);
+    e.SetFillColor(kGreen+100);
+    e.DrawEllipse(0, 0, r1, r2, 90, tot7/tot1*360+90, 0);
+
+    TText txt;
+    txt.SetTextSize(0.08);
+
+    txt.SetTextAlign(32);
+
+    txt.SetTextColor(kBlack);
+    txt.DrawText(0.99, 0.65,    Form("%.1f%%", (tot2-tot3)/tot1*100));
+    txt.SetTextColor(kBlue);
+    txt.DrawText(0.99, -0.58,   Form("%.1f%%", (tot3-tot4)/tot1*100));
+    txt.SetTextColor(kRed+100);
+    txt.DrawText(-0.35, -0.70,  Form("%.1f%%", (tot6-tot7)/tot1*100));
+
+    txt.SetTextAlign(12);
+
+    txt.SetTextColor(kBlack);
+    txt.DrawText(0, 0.77,       Form("%.1f%%", (tot1-tot2)/tot1*100));
+    txt.SetTextColor(15);
+    txt.DrawText(-0.99, 0.65,   Form("%.1f%%", tot0/tot1*100));
+    txt.SetTextColor(kGreen+100);
+    txt.DrawText(-0.99, -0.58,  Form("%.1f%%", tot7/tot1*100));
+    txt.SetTextColor(kRed);
+    txt.DrawText(0.35, -0.70,   Form("%.1f%%", (tot4-tot5)/tot1*100));
+
+    txt.SetTextAlign(22);
+
+    txt.SetTextColor(kGreen);
+    txt.DrawText(0, -0.79,      Form("%.1f%%", (tot5-tot6)/tot1*100));
+}
+
+TObject *DrawLegend(TH1F *h)
+{
+    TLegend leg(0.01, 0.12, 0.99, 0.98, "Data Statistics");
+    leg.SetBorderSize(1);
+    leg.SetTextSize(0.1);
+
+    TH1 *hc[8];
+
+    for (int i=0; i<8; i++)
+    {
+        hc[i] = (TH1*)h[i].Clone();
+        hc[i]->SetBit(kCanDelete);
+        hc[i]->SetDirectory(0);
+    }
+
+    leg.AddEntry(hc[0], "Files available",     "L");
+    leg.AddEntry(hc[1], "Excluded data",       "F");
+    leg.AddEntry(hc[2], "Not sequenced",       "F");
+    leg.AddEntry(hc[3], "Callisto not done",   "F");
+    leg.AddEntry(hc[4], "Callisto failed",     "F");
+    leg.AddEntry(hc[5], "Star not done",       "F");
+    leg.AddEntry(hc[6], "Star failed",         "F");
+    leg.AddEntry(hc[7], "Star OK",             "F");
+
+    gROOT->SetSelectedPad(0);
+    TObject *obj = leg.DrawClone();
+    obj->SetBit(kCanDelete);;
+    return obj;
+}
+
+Bool_t plot(MStatusDisplay &d, MSQLServer &serv, Int_t first, Int_t last)
+{
+    TString query[8];
+
+    // 0: All data for which are files available
+    query[0]  = "SELECT SUM(TIME_TO_SEC(TIMEDIFF(fRunStop, fRunStart)))/3600 ";
+    query[0] += "FROM RunData ";
+    query[0] += "LEFT JOIN RunProcessStatus USING (fTelescopeNumber, fRunNumber, fFileNumber) ";
+    query[0] += "WHERE fRunTypeKey=2 AND NOT ISNULL(fRawFileAvail)";
+    /*
+    if (tel>0)
+    {
+        query[0] += " AND fTelescopeNumber=";
+        query[0] += tel;
+    }
+    */
+
+    // 1: All data
+    query[1]  = "SELECT SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart)))/3600 ";
+    query[1] += "FROM RunData WHERE fRunTypeKEY=2";
+
+    // 2: All data which is not excluded
+    query[2]  = "SELECT SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart)))/3600 ";
+    query[2] += "FROM RunData WHERE fRunTypeKEY=2 AND fExcludedFDAKEY=1";
+
+    // 3: All sequences
+    query[3]  = "SELECT SUM(fRunTime)/3600 FROM Sequences";
+
+    // 4: All sequences with callisto failed
+    query[4]  = "SELECT SUM(fRunTime)/3600 FROM Sequences ";
+    query[4] += "LEFT JOIN SequenceProcessStatus USING (fSequenceFirst) ";
+    query[4] += "WHERE ISNULL(fCallisto) AND NOT ISNULL(fFailedTime) AND NOT ISNULL(fAllFilesAvail)";
+
+    // 5: All sequences with callisto=OK
+    query[5]  = "SELECT SUM(fRunTime)/3600 FROM Sequences ";
+    query[5] += "LEFT JOIN SequenceProcessStatus USING (fSequenceFirst) ";
+    query[5] += "WHERE NOT ISNULL(fCallisto)";
+
+    // 6: All sequences with star failed
+    query[6]  = "SELECT SUM(fRunTime)/3600 FROM Sequences ";
+    query[6] += "LEFT JOIN SequenceProcessStatus USING (fSequenceFirst) ";
+    query[6] += "WHERE ISNULL(fStar) AND NOT ISNULL(fFailedTime) AND NOT ISNULL(fCallisto)";
+
+    // 7: All sequences with star=OK
+    query[7]  = "SELECT SUM(fRunTime)/3600 FROM Sequences ";
+    query[7] += "LEFT JOIN SequenceProcessStatus USING (fSequenceFirst) ";
+    query[7] += "WHERE NOT ISNULL(fStar)";
+
+    // 0: All data
+    // 1: All data which is not excluded
+    // 2: All data for which are files available
+    // 3: All sequences
+    // 4: All sequences with callisto=not done
+    // 5: All sequences with callisto not done and failed
+    // 6: All sequences with star=not done
+    // 7: All sequences with star not done and failed
+
+    MTime now(-1);
+    MTime past;
+    past.Set(2004, 1, 1, 13, 1);
+
+    if (first<0)
+        first=14;
+    if (last<0)
+        last=now.GetMagicPeriod();
+
+    TH1F h[8];
+    TH2F h8;
+
+    MBinning binsp(last-first+1, first-0.5, last+0.5);
+    MBinning binst(4*7, 0, 7);
+    for (int i=0; i<8; i++)
+    {
+        binsp.Apply(h[i]);
+        h[i].SetName(Form("H%d", i));
+        h[i].SetDirectory(0);
+    }
+
+    MH::SetBinning(&h8, &binsp, &binst);
+    h8.SetNameTitle("ObsTime", "Distribution of observation time per exposure");
+    h8.SetXTitle("Observation Period");
+    h8.SetYTitle("Obs. time per exposure [h]");
+    h8.SetZTitle("Counts");
+    h8.SetDirectory(0);
+
+    Int_t period = 0;
+    MTime from;
+
+    while (1)
+    {
+        if (past.GetMagicPeriod()!=period)
+        {
+            period = past.GetMagicPeriod();
+
+            if (period>first && period-1<=last)
+            {
+                TString a = from.GetSqlDateTime();
+                TString b = past.GetSqlDateTime();
+
+                for (int i=0; i<8; i++)
+                    h[i].Fill(period-1, GetTime(serv, query[i], a, b));
+
+                TArrayD arr(GetObsDist(serv, a, b));
+
+                for (int i=0; i<arr.GetSize(); i++)
+                    h8.Fill(period-1, arr[i]);
+            }
+
+            if (past>now)
+                break;
+
+            from = past;
+
+        }
+        past.SetMjd(past.GetMjd()+1);
+    }
+
+    for (int i=0; i<h[0].GetNbinsX(); i++)
+        h[0].SetBinError(i+1, 0.001);
+
+
+    h[4].Add(&h[5]);
+    h[6].Add(&h[7]);
+
+    // --------------------------------------------
+
+    TCanvas &c0 = d.AddTab("ObsDist", h8.GetTitle());
+    c0.SetFillColor(kWhite);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetFillColor(kWhite);
+    gPad->SetRightMargin(0.01);
+    //gPad->SetTopMargin(0.02);
+    //gPad->SetLeftMargin(0.09);
+    //gPad->SetBottomMargin(0.12);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    gPad->SetLogy();
+
+    TH1 * p = h8.ProjectionY();
+
+    p->SetYTitle("Counts");
+    p->SetDirectory(0);
+    p->SetBit(kCanDelete);
+    p->Draw();
+
+    // --------------------------------------------
+
+    TCanvas &c1 = d.AddTab("Hist", "Bar chart of the processing status of all data");
+    c1.SetFillColor(kWhite);
+    c1.Divide(2,2);
+
+    c1.cd(1);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetFillColor(kWhite);
+    gPad->SetRightMargin(0.01);
+    gPad->SetTopMargin(0.02);
+    gPad->SetLeftMargin(0.09);
+    gPad->SetBottomMargin(0.12);
+    gPad->SetGridy();
+    gPad->SetPad(0, 0.5, 0.75, 1.0);
+
+    h[1].SetBit(TH1::kNoStats);
+    // h[0].GetXaxis()->SetRangeUser(13.5, period+0.5);
+    h[1].GetXaxis()->CenterTitle();
+    h[1].GetXaxis()->SetTitleSize(0.06);
+    h[1].GetYaxis()->SetTitleSize(0.06);
+    h[1].GetYaxis()->SetTitleOffset(0.7);
+    h[1].GetXaxis()->SetLabelSize(0.06);
+    h[1].GetYaxis()->SetLabelSize(0.06);
+    h[1].GetXaxis()->SetNdivisions(550);
+    h[1].SetYTitle("Time [h]");
+    h[1].SetFillColor(kWhite);
+    h[1].SetLineColor(kBlack);
+    h[1].DrawCopy("");
+
+    h[2].SetLineColor(kBlack);
+    h[2].SetFillColor(kBlack);
+    h[2].DrawCopy("Bsame");
+
+    h[3].SetLineColor(kBlue);
+    h[3].SetFillColor(kBlue);
+    h[3].DrawCopy("Bsame");
+
+    h[4].SetLineColor(kRed);
+    h[4].SetFillColor(kRed);
+    h[4].DrawCopy("Bsame");
+
+    h[5].SetLineColor(kGreen);
+    h[5].SetFillColor(kGreen);
+    h[5].DrawCopy("Bsame");
+
+    h[6].SetLineColor(kRed+100);
+    h[6].SetFillColor(kRed+100);
+    h[6].DrawCopy("Bsame");
+
+    h[7].SetLineColor(kGreen+100);
+    h[7].SetFillColor(kGreen+100);
+    h[7].DrawCopy("Bsame");
+
+    h[0].SetMarkerSize(0);
+    h[0].SetMarkerColor(15);
+    h[0].SetLineWidth(3);
+    h[0].SetLineColor(15);
+    h[0].DrawCopy("EPsame");
+
+    gPad->Update();
+    DrawYears();
+
+    c1.cd(4);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetPad(0.75, 0, 1.0, 0.5);
+
+    DrawCake(h);
+
+    // --------------------------------------------
+
+    TCanvas &cx = d.AddTab("All", "Pie charts for all periods");
+    cx.SetBorderMode(0);
+    cx.SetFrameBorderMode(0);
+    cx.SetFillColor(kWhite);
+    cx.Divide(12,7);
+    cx.cd(1);
+    TObject *leg=DrawLegend(h);
+
+    for (int i=h[0].GetNbinsX()-1; i>=0; i--)
+    {
+        const Int_t num = TMath::Nint(h[0].GetBinCenter(i+1));
+
+        TCanvas &c = d.AddTab(Form("P%d", num), Form("Pie char for period %d", num));
+        c.SetBorderMode(0);
+        c.SetFrameBorderMode(0);
+        c.SetFillColor(kWhite);
+
+        c.cd();
+
+        TPad *pad0 = new TPad(Form("Pad%dl", num), "", 0.59, 0.5, 1, 1);
+        pad0->SetBorderMode(0);
+        pad0->SetFrameBorderMode(0);
+        pad0->SetFillColor(kWhite);
+        pad0->SetBit(kCanDelete);
+        pad0->Draw();
+        pad0->cd();
+
+        leg->Draw();
+
+        c.cd();
+
+        TPad *pad1 = new TPad(Form("Pad%da", num), "", 0.03, 0, 0.50, 1);
+        pad1->SetBorderMode(0);
+        pad1->SetFrameBorderMode(0);
+        pad1->SetFillColor(kWhite);
+        pad1->SetBit(kCanDelete);
+        pad1->Draw();
+        pad1->cd();
+
+        DrawCake(h, i+1, i+1);
+
+        cx.cd(i+2);
+        DrawCake(h, i+1, i+1);
+
+        c.cd();
+
+        TPad *pad2 = new TPad(Form("Pad%db", num), "", 0.55, 0.02, 1, 0.48);
+        pad2->SetBorderMode(0);
+        pad2->SetFrameBorderMode(0);
+        pad2->SetFillColor(kWhite);
+        pad2->SetBit(kCanDelete);
+        pad2->SetGridx();
+        pad2->SetGridy();
+        pad2->SetRightMargin(0.01);
+        pad2->Draw();
+        pad2->cd();
+
+        TH1 * p = h8.ProjectionY(Form("Obs%d", num), i+1, i+1);
+
+        p->Rebin(2);
+        p->SetBit(TH1::kNoStats);
+        p->SetTitle("");
+        p->SetYTitle("Counts");
+        p->SetDirectory(0);
+        p->SetBit(kCanDelete);
+        p->Draw();
+
+        /*
+        c.cd();
+
+        TPaveText *pave = new TPaveText(0.6, 0.52, 0.98, 0.98);
+        pave->SetBorderSize(1);
+        pave->AddText(Form("Period: %d", num))->SetTextAlign(22);
+        pave->AddSeperator();
+        pave->AddText(Form("Start: %s", num));
+        pave->AddText(Form("End:   %s", num));
+        pave->SetBit(kCanDelete);
+        pave->Draw();
+        */
+    }
+
+    c1.cd(2);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetRightMargin(0.01);
+    gPad->SetTopMargin(0.02);
+    gPad->SetLeftMargin(0.09);
+    gPad->SetBottomMargin(0.12);
+    gPad->SetPad(0, 0, 0.75, 0.5);
+    gPad->SetGridy();
+
+    h[1].Scale(0.01);
+    h[0].Divide(&h[1]);
+    h[2].Divide(&h[1]);
+    h[3].Divide(&h[1]);
+    h[4].Divide(&h[1]);
+    h[5].Divide(&h[1]);
+    h[6].Divide(&h[1]);
+    h[7].Divide(&h[1]);
+    h[1].Divide(&h[1]);
+    h[1].Scale(100);
+
+    for (int i=0; i<h[0].GetNbinsX(); i++)
+        h[0].SetBinError(i+1, 0.001);
+
+    h[1].GetXaxis()->SetNdivisions(550);
+    h[1].SetYTitle("%");
+    h[1].SetXTitle("Period");
+    h[1].GetYaxis()->SetRangeUser(0, 100);
+
+    h[1].DrawCopy();
+    h[2].DrawCopy("same");
+    h[3].DrawCopy("same");
+    h[4].DrawCopy("same");
+    h[5].DrawCopy("same");
+    h[6].DrawCopy("same");
+    h[7].DrawCopy("same");
+    h[0].DrawCopy("same");
+/*
+    TLine l;
+    l.SetLineColor(kWhite);
+    l.SetLineWidth(1);
+    l.SetLineStyle(kDotted);
+    for (int i=10; i<95; i+=10)
+        l.DrawLine(13.5, i, period+0.5, i);
+    l.SetLineStyle(kSolid);
+    l.DrawLine(13.5, 50, period+0.5, 50);
+ */
+    gPad->Update();
+    DrawYears();
+
+    c1.cd(3);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetPad(0.75, 0.5, 1.0, 1.0);
+
+    DrawLegend(h);
+
+    return kTRUE;
+}
+
+int plotstat(Int_t first=-1, Int_t last=-1)
+{
+    MSQLServer serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotstat" << endl;
+    cout << "--------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    plot(*d, serv, first, last);
+
+    //d->SaveAsRoot("plotstat.root");
+    //d->SaveAsPS("plotstat.ps");
+
+    return 1;
+}
+
+int plotstat(TString path)
+{
+    MSQLServer serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotstat" << endl;
+    cout << "--------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    plot(*d, serv, -1, -1);
+
+    d->SaveAsRoot(path+"plotstat.root");
+    //d->SaveAsPS(path+"plotstat.ps");
+
+    return 1;
+}
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/plotusage.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/plotusage.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/plotusage.C	(revision 17960)
@@ -0,0 +1,109 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: plotusage.C,v 1.2 2008-08-15 12:14:52 dorner Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Droner, 08/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// plotusage.C
+// ===========
+//
+// This macro is used to read parameters (condor usage of the cluster) from
+// the DB and plot them.
+// 
+// Usage:
+//   .x plotusage.C   --> all values in the DB are plotted
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "plotdb.C"
+
+void plotallusage(MPlot &plot)
+{
+    // plot.SetGroupBy(MPlot::kGroupByDay);
+
+    plot.SetPrimaryDate("CondorStatus.fTime");
+
+    // plot.SetPrimaryNumber("Sequences.fSequenceFirst");
+    // plot.SetCondition("((Sequences.fSequenceFirst>95000 AND Sequences.fSequenceFirst<261988) OR Sequences.fSequenceFirst>267750)"
+    //                   "AND Star.fAvgTemperature<25 AND Star.fMuonNumber>500");
+
+    plot.SetSecondary("CondorStatus.fLoadTotal");
+    plot.SetDescription("Total number of available CPUs;Available CPUs", "TotCPU");
+    plot.Plot("CondorStatus.fNumTotal as CPUs",  0,  50, 1);
+
+    plot.SetSecondary("CondorStatus.fLoadClaimed");
+    plot.SetDescription("Total number of claimed CPUs;Claimed CPUs", "ClaimedCPU");
+    plot.Plot("CondorStatus.fNumClaimed as CPUs",  0,  50, 1);
+
+    plot.SetSecondary("CondorStatus.fNumClaimed");
+    plot.SetDescription("Total load of available CPUs;Total load", "AbsTotLoad");
+    plot.Plot("CondorStatus.fLoadTotal",  0,  50, 1);
+
+    plot.SetSecondary("CondorStatus.fNumClaimed");
+    plot.SetDescription("Total load of claimed CPUs;Claimed load", "AbsClaimedLoad");
+    plot.Plot("CondorStatus.fLoadClaimed",  0,  50, 1);
+
+    plot.SetSecondary("CondorStatus.fNumClaimed");
+    plot.SetDescription("Relative load per available CPUs;Relative load", "RelTotLoad");
+    plot.Plot("CondorStatus.fLoadTotal/CondorStatus.fNumTotal",  0,  1.2, 0.02);
+
+    plot.SetSecondary("CondorStatus.fNumClaimed");
+    plot.SetDescription("Relative load per claimed CPUs;Relative load", "RelClaimedLoad");
+    plot.Plot("CondorStatus.fLoadClaimed/CondorStatus.fNumClaimed",  0,  1.2, 0.02);
+}
+
+int plotusage(TString path="")
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotusage" << endl;
+    cout << "---------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetWindowName(serv.GetName());
+    d->SetTitle(serv.GetName());
+
+    MPlot plot(serv);
+    plot.SetDisplay(d);
+
+    plotallusage(plot);
+
+    d->SaveAsRoot(path+"plotusage.root");
+//    d->SaveAsPS("plotusage.ps");
+
+    return 1;
+}
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/resetallruns.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/resetallruns.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/resetallruns.C	(revision 17960)
@@ -0,0 +1,136 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// resetallruns.C
+// ==============
+//
+// This macro resets the values of a column in the table RunProcessStatus. It
+// is used by the script filesondisk to reset the values for the columns,
+// which indicate the availability of the files.
+//
+// Usage:
+//   .x resetallrun.C+("filename", "column")
+// The first argument is giving a file, in which a list of runs can be found
+// for which the column will be set to Now() by this macro. The second
+// argument is giving the column, which has to be reset.
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TPRegexp.h>
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+int resetallruns(TString filename, TString column, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "resetallruns" << endl;
+    cout << "------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+    cout << "File:   " << filename << endl;
+    cout << "Column: " << column << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    //reset column to NULL, if the column is fCaCoFileAvail,
+    //reset also the column fCaCoFileFound
+    TString vars(column);
+    vars += "=NULL";
+    if (column.Contains("CaCo"))
+        vars += ", fCaCoFileFound=NULL";
+
+    if (serv.Update("RunProcessStatus", vars)==kFALSE)
+        return 2;
+
+    //read in file
+    ifstream fin(filename);
+    if (!fin)
+    {
+        cout << "ERROR - File " << filename << " missing!" << endl;
+        return 2;
+    }
+
+    TPRegexp regtel("^_M[0-9]_");
+    TPRegexp regrun("_[0-9]{5,8}");
+    TPRegexp regfile("[.][0-9]{3,5}_$");
+    while (1)
+    {
+        //get runnumber
+        TString str;
+        str.ReadLine(fin);
+        if (!fin)
+            break;
+
+        const TString tel  = str(regtel);
+        const TString run  = str(regrun);
+        const TString file = str(regfile);
+
+        const UInt_t ntel  = tel.IsNull()  ? 1 : atoi(tel.Data()+2);
+        const UInt_t nfile = file.IsNull() ? 0 : atoi(file.Data()+1);
+        const UInt_t nrun  = atoi(run.Data()+1);
+
+        if (nrun>999999 && (tel.IsNull() || file.IsNull()))
+        {
+            cout << "ERROR - Run number " << nrun << ">999999 and telescope and/or run-number missing!" << endl;
+            cout << str << endl;
+            continue;
+        }
+
+        const UInt_t id = nrun*1000+nfile;
+
+        //build query and set status for this run to Now()
+        TString vars2(column);
+        vars2 += "=Now()";
+        if (column.Contains("CaCo"))
+            vars2 += Form(", fCaCoFileFound=%d", id);
+
+        TString where = Form("fTelescopeNumber=%d AND fRunNumber=%d AND fFileNumber=%d ",
+                             ntel, nrun, nfile);
+
+        if (serv.Update("RunProcessStatus", vars2, where)==kFALSE)
+            return 2;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/resetcolumn.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/resetcolumn.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/resetcolumn.C	(revision 17960)
@@ -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): Daniela Dorner, 05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// resetcolumn.C
+// =============
+//
+// This macro is used to reset values in the DB.
+//
+// If a step in the automatic analysis chain has to be repeated, the value
+// for this step in the DB has to be reset. This can be done with this macro.
+//
+// As arguments you have to give the column, the table and from which
+// to which Date/Sequence/Run/Dataset you want to reset the value.
+//
+// The last argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests (i.e. if you want to see if the query is correct).
+//
+// Usage:
+//   .x resetcolumn.C("fStar","SequenceProcessStatus","45114","49329",kTRUE)
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TEnv.h>
+#include <TObjString.h>
+#include <TList.h>
+
+#include <MSQLServer.h>
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+using namespace std;
+
+
+int resetcolumn(TString column, TString table, TString from, TString to, Bool_t dummy=kTRUE)
+{
+    cout << "This macro has not yet been adapted to the new data structure (Magic II)." << endl;
+    return 0;
+
+    TEnv env("sql.rc");
+
+    MSQLServer serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+    cout << "resetcolumn" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    TEnv rc("steps.rc");
+    //get steps which are influenced by the step, which is resetted
+    TString influences  = rc.GetValue(table+"."+column+".Influences", "");
+
+    cout << "resetting column " << column << flush;
+    cout << " and the columns it influences(" << influences << ") from " << flush;
+    cout << from << " to " << to << "..." << endl;
+
+    TList l;
+    while (!influences.IsNull())
+    {
+        influences = influences.Strip(TString::kBoth);
+
+        Int_t idx = influences.First(' ');
+        if (idx<0)
+            idx = influences.Length();
+
+        TString influence = influences(0, idx);
+        influences.Remove(0, idx);
+        l.Add(new TObjString(influence));
+    }
+
+    //build query and reset columns
+    TString query(Form("Update %s SET %s=NULL ", table.Data(), column.Data()));
+    query+=", fStartTime=NULL, fFailedTime=NULL, fReturnCode=NULL, fProgramId=NULL ";
+
+    TIter Next(&l);
+    TObject *o=0;
+    while ((o=Next()))
+        query+=Form(", %s=NULL ", o->GetName());
+
+    query+=Form(" WHERE %s between '%s' and '%s'", rc.GetValue(table+".Primary", ""), from.Data(), to.Data());
+
+    if (dummy)
+    {
+        cout << "query: " << query << endl;
+        return 1;
+    }
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return 2;
+
+    delete res;
+
+    return 1;
+}
+
+
Index: branches/Mars_McMismatchStudy/datacenter/macros/stage.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/stage.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/stage.C	(revision 17960)
@@ -0,0 +1,51 @@
+#include <iostream>
+
+#include <TSystem.h>
+
+#include "MSQLMagic.h"
+#include "MSequenceSQL.h"
+
+using namespace std;
+
+void stage(MSequence &s, TString path)
+{
+    MDirIter iter1, iter2;
+
+    s.GetRuns(iter1, MSequence::kRawPed, path);
+    s.GetRuns(iter1, MSequence::kRawCal, path);
+    s.GetRuns(iter1, MSequence::kRawDat, path);
+
+    TString req = "ssh -nx phoenix /opt/SUNWsamfs/bin/stage -V";
+    while (1)
+    {
+        TString name = iter1.Next();
+        if (name.IsNull())
+            break;
+
+        req += " "+name;
+    }
+
+    gSystem->Exec(req);
+}
+
+int stage(Int_t sequno, Int_t tel, TString path="")
+{
+    const MSequenceSQL s("sql.rc", sequno, tel);
+    if (!s.IsValid())
+        return 2;
+
+    stage(s, path);
+
+    return 0;
+}
+
+int stage(const char *seq, TString path="")
+{
+    const MSequence s(seq);
+    if (!s.IsValid())
+        return 2;
+
+    stage(s, path);
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/writedatasetfile.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/writedatasetfile.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/writedatasetfile.C	(revision 17960)
@@ -0,0 +1,181 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: writedatasetfile.C,v 1.3 2008-07-05 19:01:43 tbretz Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// writedatasetfile.C
+// ==================
+//
+// reads the dataset information from the database and writes it into a
+// txt file
+//
+// Usage:
+//  .x writedatasetfile.C+(dsno, "dspath")
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include <errno.h>
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+Int_t GetDataOnOff(MSQLMagic &serv, Int_t dsno, Int_t type, TString &data)
+{
+    //get sequence information from database
+    TString query1(Form("SELECT fSequenceFirst FROM DataSetSequenceMapping "
+                       " WHERE fDataSetNumber=%d AND fOnOff=%d", dsno, type));
+
+    TSQLResult *res = serv.Query(query1);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query1 << endl;
+        return 2;
+    }
+    if (res->GetRowCount()==0 && type==1)
+    {
+        cout << "ERROR - Dataset #" << dsno << " has no on-sequences." << endl;
+        return 2;
+    }
+
+    TSQLRow *row = 0;
+    while ((row=res->Next()))
+    {
+        data += " ";
+        data += (*row)[0];
+    }
+
+    delete res;
+
+    return kTRUE;
+}
+
+Int_t Process(MSQLMagic &serv, Int_t dsno, TString seqpath)
+{
+    //get sequence information from database
+    TString query0(Form("SELECT fSourceName, fComment, fDataSetName, fRunTime, fObservationModeKEY"
+                       " FROM DataSets LEFT JOIN Source USING (fSourceKEY)"
+                       " WHERE fDataSetNumber=%d", dsno));
+
+    TSQLResult *res = serv.Query(query0);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query0 << endl;
+        return 2;
+    }
+    if (res->GetRowCount()==0)
+    {
+        cout << "ERROR - No dataset #" << dsno << " found." << endl;
+        return 2;
+    }
+    if (res->GetRowCount()!=1)
+    {
+        cout << "ERROR - Wrong number of datasets #" << dsno << " found." << endl;
+        return 2;
+    }
+
+    TSQLRow *row = res->Next();
+
+    TString source  = (*row)[0];
+    TString comment = (*row)[1];
+    TString name    = (*row)[2];
+    TString runtime = (*row)[3];
+    TString mode    = (*row)[4];
+    TString on      = "SequencesOn:";
+    TString off     = "SequencesOff:";
+
+    const Bool_t wobble = mode.Atoi()==2;
+
+    delete res;
+
+
+    Int_t rc1 = GetDataOnOff(serv, dsno, 1, on);
+    if (rc1!=kTRUE)
+        return rc1;
+
+    Int_t rc2 = GetDataOnOff(serv, dsno, 2, off);
+    if (rc2!=kTRUE)
+        return rc1;
+
+
+    if (!seqpath.IsNull() && !seqpath.EndsWith("/"))
+        seqpath += "/";
+    seqpath += Form("dataset%08d.txt", dsno);
+
+    ofstream fout(seqpath);
+    if (!fout)
+    {
+        cout << "ERROR - Cannot open file " << seqpath << ": " << strerror(errno) << endl;
+        return 2;
+    }
+
+    fout << "AnalysisNumber: " << dsno << endl << endl;
+    fout << on << endl;
+    if (off.Length()>13)
+        fout << off << endl;
+    fout << endl;
+    fout << "SourceName: " << source << endl;
+    fout << "Catalog: /magic/datacenter/setup/magic_favorites_dc.edb" << endl;
+    if (wobble)
+        fout << "WobbleMode: On" << endl;
+    fout << endl;
+    fout << "RunTime: " << runtime << endl;
+    fout << "Name: " << name << endl;
+    fout << "Comment: " << comment << endl;
+    fout << endl;
+
+    return 1;
+}
+
+int writedatasetfile(Int_t dsno, TString seqpath)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "writedatasetfile" << endl;
+    cout << "----------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    return Process(serv, dsno, seqpath);
+}
Index: branches/Mars_McMismatchStudy/datacenter/macros/writesequencefile.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/macros/writesequencefile.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/macros/writesequencefile.C	(revision 17960)
@@ -0,0 +1,88 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// writesequencefile.C
+// ===================
+//
+// reads the sequence information from the database and writes it into a
+// txt file
+//
+// Usage:
+//  .x writesequencefile.C+(sequno,"sequpath")
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 2 in case of failure, 1 in case of success and 0 if the connection
+// to the database is not working.
+//
+//
+// This tool will work from Period017 (2004_05_17) on...
+//
+// For more details see MSequence and MSequenceSQL
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+
+#include "MSQLMagic.h"
+#include "MSequenceSQL.h"
+
+using namespace std;
+
+int writesequencefile(Int_t sequno, Int_t tel, TString sequpath="")
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "writesequencefile" << endl;
+    cout << "-----------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Sequence:  " << sequno << endl;
+    cout << "Telescope: " << tel << endl;
+    cout << endl;
+
+    const MSequenceSQL s(serv, sequno, tel);
+    if (!s.IsValid())
+        return 2;
+
+    if (sequpath.IsNull())
+    {
+        s.Print();
+        return 1;
+    }
+
+    const TString fname(Form("%s/%04d/sequence%08d.txt", sequpath.Data(), sequno/10000, sequno));
+
+    cout << "File:     " << fname << endl;
+
+    return s.WriteFile(fname) ? 1 : 2;
+}
Index: branches/Mars_McMismatchStudy/datacenter/scripts/budb
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/budb	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/budb	(revision 17960)
@@ -0,0 +1,143 @@
+#!/bin/bash
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  10/2006 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2011
+#
+#
+# ========================================================================
+#
+# This script backups the databases give in setup.XXX in the array dbnames
+# 
+# In addition, it writes out the commands how to create the database 
+# MyMagic, in case all databases are backuped. 
+#
+
+today=`date +%F`
+olday=`date +%F --date="-30day"`
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+
+set -C
+
+path=/home/`whoami`/DB_Backup
+logpath=$path/log
+filepath=$path/files
+mkdir -pv $logpath
+mkdir -pv $filepath
+logfile=$logpath/budb$today.log
+oldlog=$logpath/budb$olday.log
+
+date > $logfile
+getdbsetup
+
+echo "today: $today" >> $logfile 2>&1
+echo "date to remove: $olday" >> $logfile 2>&1
+
+if ls $oldlog >/dev/null 2>&1
+then 
+   echo "removing old logfile..." >> $logfile 2>&1
+   rm -v $oldlog >> $logfile 2>&1
+fi
+
+if [ "${dbnames[0]}" == "all" ]
+then
+   dbname=MyMagic
+   command=$filepath/Create$dbname$today.txt
+   oldcommand=$filepath/Create$dbname$olday.txt
+   file=$filepath/alldatabases
+   end=.sql.bz2
+   zipfile=$file$today$end
+   oldzip=$file$olday$end
+
+   echo "removing old files..." >> $logfile 2>&1
+   if ls $oldzip >/dev/null 2>&1
+   then 
+      rm -v $oldzip >> $logfile 2>&1
+   fi
+   if ls $oldcommand >/dev/null 2>&1
+   then 
+      rm -v $oldcommand >> $logfile 2>&1
+   fi
+  
+   echo "writing create commands to $command..." >> $logfile 2>&1
+   # commands to create MyMagic
+   if ! mysqldump --host=$ho --database $dbname -u dump --no-data >| $command 2>> $logfile
+   then
+      printprocesslog "ERROR mysqldump failed "
+      echo "ERROR mysqldump failed " >> $logfile 2>&1
+   fi
+
+   echo "writing all databases to $zipfile..." >> $logfile 2>&1
+   # complete databases 
+   if ! mysqldump --host=$ho --all-databases -u dump | bzip2 -9 -c >| $zipfile 2>> $logfile
+   then
+     printprocesslog "ERROR mysqldump failed "
+     echo "ERROR mysqldump failed " >> $logfile 2>&1
+   fi
+else 
+   echo "doing backup for the following databases: "${dbnames[@]}  >> $logfile 2>&1
+   for dbname in ${dbnames[@]}
+   do 
+      filepath2=$filepath/$dbname
+      command=$filepath2"/Create_"$dbname"_"$today".txt"
+      oldcommand=$filepath2"/Create_"$dbname"_"$olday".txt"
+      mkdir -pv $filepath2
+
+      file=$filepath2/$dbname
+      end=.sql.bz2
+      zipfile=$file"_"$today$end
+      oldzip=$file"_"$olday$end
+
+      echo "removing old files..." >> $logfile 2>&1
+      if ls $oldzip >/dev/null 2>&1
+      then
+         rm -v $oldzip >> $logfile 2>&1
+      fi
+      if ls $oldlog >/dev/null 2>&1
+      then
+         rm -v $oldlog >> $logfile 2>&1
+      fi
+      if ls $oldcommand >/dev/null 2>&1
+      then
+         rm -v $oldcommand >> $logfile 2>&1
+      fi
+
+      echo "writing create commands to $command..." >> $logfile 2>&1
+      # commands to create db
+      if ! mysqldump --host=$ho --database $dbname -u dump --no-data >| $command 2>> $logfile
+      then
+         printprocesslog "ERROR mysqldump failed "
+         echo "ERROR mysqldump failed " >> $logfile 2>&1
+      fi
+
+      echo "writing database $dbname to $zipfile..." >> $logfile 2>&1
+      
+      if ! mysqldump --host=$ho --database $dbname -u dump | bzip2 -9 -c >| $zipfile 2>> $logfile
+      then
+        printprocesslog "ERROR mysqldump failed "
+        echo "ERROR mysqldump failed " >> $logfile 2>&1
+      fi
+   done
+fi
+
+finish >> $logfile 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/buildsequenceentries
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/buildsequenceentries	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/buildsequenceentries	(revision 17960)
@@ -0,0 +1,93 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the building of sequences for all days for which 
+# this step is needed. 
+#
+# After checking if the script is already running the todolist is written.
+# Then the sequences are built for each date in the todolist using the 
+# macro buildsequenceentries.C
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=buildsequenceentries
+column=fSequenceEntriesBuilt
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+for (( s=0 ; s < $num ; s++ ))
+do
+   date=${primaries[$s+$s]}
+   telnum=${primaries[$s+$s+1]}
+   printprocesslog "INFO build sequence entries for $date"
+   year2=`echo $date | cut -c 1-4`
+   buildsequentriespath=$logpath/$program/$year2
+   makedir  $buildsequentriespath 
+   buildsequentrieslog=$buildsequentriespath/buildsequenceentries-$date.log
+
+   setstatus "start" 
+
+   check1=`root -q -b $macrospath/buildsequenceentries.C+\("\"$date\""\,"\"$datapath\""\,"\"$sequpath\""\,$telnum\,kFALSE\) | tee $buildsequentrieslog | intgrep`
+
+   case $check1 in
+      1)   printprocesslog "INFO sequence entries successfully built for $date (check1=$check1)"
+           IFS=$'\n'
+           missing=( `grep "Missing" $buildsequentrieslog` )
+           if [ ${#missing[@]} -gt 0 ]
+           then
+              for miss in ${missing[@]}
+              do
+                 printprocesslog "WARN $buildsequentrieslog: $miss"
+              done
+           fi
+           unset IFS
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check1=$check1)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR $program.C failed for $date (check1=$check1)"
+           com=$Fbuildsequ
+           check=$check1
+           ;;
+   esac
+
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/checkfilesforsequenceavail
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/checkfilesforsequenceavail	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/checkfilesforsequenceavail	(revision 17960)
@@ -0,0 +1,87 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the checking of the availability of the files for 
+# the sequences. 
+#
+# After checking if the script is already running the todolist is written.
+# Then for each sequence the availability of the files (raw, cc, caco) is 
+# checked by using the macro checkfilesavail.C 
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=checkfilesavail
+column=fAllFilesAvail
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s+$s]}
+   telnum=${primaries[$s+$s+1]}
+   printprocesslog "INFO checking files for sequence $sequence"
+   no=`printf %08d $sequence | cut -c 0-4`
+   no2=`printf %08d $sequence`
+   checkfileavailpath=$logpath/$program/$no
+   makedir $checkfileavailpath 
+   checkfileavaillog=$checkfileavailpath/$program-$no2.log
+
+   setstatus "start" 
+
+   check1=`root -q -b $macrospath/checkfileavail.C+\($sequence,$telnum\) | tee $checkfileavaillog | intgrep`
+
+   case $check1 in
+      1)   printprocesslog "INFO files available for sequence $sequence (check1=$check1)"
+           ;;
+      2)   printprocesslog "INFO files not yet available for sequence $sequence (check1=$check1)"
+           check="no"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check1=$check1)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR $program.C failed for sequence $sequence (check1=$check1)"
+           com=$Ffilesavail
+           check=$check1
+           ;;
+   esac
+
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/checklogs
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/checklogs	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/checklogs	(revision 17960)
@@ -0,0 +1,47 @@
+#!/bin/bash
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script checks, if there are WARNs or ERRORs in the processlog of 
+# the last night and sends them to the emailadresse(s) in $erradr
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+
+oldprocesslog=$processlogpath/process`date +%F --date="-1day"`.log
+
+if grep WARN $oldprocesslog >/dev/null
+then 
+   grep WARN $oldprocesslog | mail -s 'found warnings in '$oldprocesslog $erradrs
+fi
+
+if grep ERROR $oldprocesslog >/dev/null
+then 
+   grep ERROR $oldprocesslog | mail -s 'found errors in '$oldprocesslog $erradrs
+fi
+
+printprocesslog "INFO finished $0"
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/checkmd5sum
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/checkmd5sum	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/checkmd5sum	(revision 17960)
@@ -0,0 +1,130 @@
+#!/bin/bash
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Stefan Ruegamer 05/2007 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script is checking the md5 sums of files read from tape. It
+# computes the checksums for the extracted files and compares them with
+# the checksums from La Palma, read out from the md5 sum file which is
+# transferred together with the logfile.
+#
+
+no=$@
+if [ "$no" == "" ]
+then
+   echo "no tape specified -> aborting"
+   exit
+fi
+
+checkpath=/home/lapalma/tapecont/cont/muxdata/checksums
+file=/home/lapalma/tapecont/cont/muxdata/tape_${no}L*.md5
+L=`echo $file | cut -c49`
+id=${no}L${L}
+logfile=${checkpath}/tape_${id}.log
+
+if [ ! -f $file ]
+then
+   echo "tape $file not found -> aborting" >> $logfile 2>&1
+   exit
+fi
+
+if [ -f ${checkpath}/tape_${id}.md5.lapalma ] || [ -f ${checkpath}/tape_${id}.md5.wue ]
+then
+   echo "Output files already existing -> aborting" >> $logfile 2>&1
+   exit
+#   echo "Output files already existing. Are you sure you wish to continue (yes/no)?"
+#   read cont
+#   if [ ! $cont == "yes" ]
+#   then
+#      echo "Aborting."
+#      exit
+#   fi
+fi
+
+if [ "`cat $file`" == "" ]
+then
+   echo "$file is empty, the checksums are missing -> aborting" >> $logfile 2>&1
+   exit
+fi
+
+date | tee ${checkpath}/tape_${id}.md5.lapalma | tee ${checkpath}/tape_${id}.md5.wue > /dev/null
+muxslog=`grep muxdata/20[01][0-9].*/20[01][0-9].*.raw $file | wc -l`
+
+# read the tapecont file line by line
+while read line
+do
+   muxchk=`echo $line | cut -d/ -f1`
+   type=`echo $line | sed -e 's/.*20[01][0-9]\{5\}_.*\(.raw\)/\1/' | cut -c 0-4`
+   # only check muxdata rawfiles, not cc-, caco- or drivelog-files
+   if [ "$muxchk" = "muxdata" ] && [ "$type" = ".raw" ]
+   then
+      sum=($line)
+      
+      # check if the file has been extracted from tape; if not, don't write anything to the logfiles (so they can still be compared)
+      if [ ! -f /magic/datacenter/fromtape/${sum[0]} ] && [ ! -f /data/fromtape/${sum[0]} ]
+      then
+      	echo "File ${sum[0]} does not exist." >> $logfile 2>&1
+        continue
+      fi
+      
+      # reformat the files and checksums correctly and compare them
+      echo "${sum[1]}  ${sum[0]}" >> ${checkpath}/tape_${id}.md5.lapalma
+      
+      if [ ! -f /magic/datacenter/fromtape/${sum[0]} ]
+      then
+         nice -n 19 /opt/csw/bin/gmd5sum /data/fromtape/${sum[0]} | sed -e 's/\/data\/fromtape\///' >> ${checkpath}/tape_${id}.md5.wue
+      else
+         nice -n 19 /opt/csw/bin/gmd5sum /magic/datacenter/fromtape/${sum[0]} | sed -e 's/\/magic\/datacenter\/fromtape\///' >> ${checkpath}/tape_${id}.md5.wue
+      fi
+   fi
+done < $file
+
+date | tee -a ${checkpath}/tape_${id}.md5.lapalma | tee -a ${checkpath}/tape_${id}.md5.wue > /dev/null
+
+if [ ! -f ${checkpath}/tape_${id}.md5.lapalma ] || [ ! -f ${checkpath}/tape_${id}.md5.wue ]
+then
+   echo "No output files written! Something went wrong... -> aborting" >> $logfile 2>&1
+   exit
+fi
+
+echo "Wrote checksums to ${checkpath}/tape_${id}.md5.lapalma and ${checkpath}/tape_${id}.md5.wue. Comparing now." >> $logfile 2>&1
+
+# check for differences in the checksums
+output=`diff ${checkpath}/tape_${id}.md5.lapalma ${checkpath}/tape_${id}.md5.wue`
+
+if [ "$output" = "" ]
+then
+   echo "All checksums are identical." >> $logfile 2>&1
+   muxschk=`grep muxdata/20[01][0-9].*/20[01][0-9].*.raw ${checkpath}/tape_${id}.md5.wue | wc -l`
+   if [ $muxslog == $muxschk ]
+   then
+      echo "Number of checked files matches. Files are ready." >> $logfile 2>&1
+   else
+      echo "Number of checked files doesn't match number of extracted files. Something went wrong..." >> $logfile 2>&1
+   fi
+else
+   echo -e "The files are not identical! diff found the following differences:\n$output" >> $logfile 2>&1
+fi
+
+echo "Program terminated." >> $logfile 2>&1
Index: branches/Mars_McMismatchStudy/datacenter/scripts/checkscriptrunning
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/checkscriptrunning	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/checkscriptrunning	(revision 17960)
@@ -0,0 +1,49 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2007 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script checks, if another script - given by command line option - 
+# is running. 
+#
+
+source `dirname $0`/sourcefile
+#printprocesslog "INFO starting $0"
+
+if ! [ "$2" = "" ]
+then
+   printprocesslog "WARN two many command line options given in $@ -> exit"
+   finish >/dev/null
+fi
+
+path=`dirname $0`
+script="/bin/sh "$path/$1
+if ! ps -o "%a" -C '$1' | grep -x "$script" >/dev/null
+then 
+   printprocesslog "INFO starting $script"
+   $script &
+fi 
+
+#printprocesslog "INFO finished $0"
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/checkstardone
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/checkstardone	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/checkstardone	(revision 17960)
@@ -0,0 +1,81 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script launches the checking of the availability of the files for 
+# the datasets. 
+#
+# After checking if the script is already running the todolist is written.
+# Then for each dataset the sequences are extracted from the datasetfile 
+# and for each sequence the availability of the star files checked by using 
+# the macro checkstardone.C 
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=checkstardone
+column=fStarFilesAvail
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+for (( s=0 ; s < $num ; s++ ))
+do
+   dataset=${primaries[$s]}
+   printprocesslog "INFO checking star done for sequences of dataset $dataset"
+
+   outpath=$logpath/$program/`printf %08d $dataset | cut -c 0-5`
+   makedir $outpath 
+
+   setstatus "start" 
+
+   check1=`root -q -b $macrospath/checkstardone.C+\($dataset\) | tee $outpath/checkstardone-$dataset.log | intgrep`
+
+   case $check1 in
+      1)   printprocesslog "INFO check1=$check1 -> everything ok -> continue with next dataset..." 
+           ;;
+      2)   printprocesslog "INFO files not yet available for dataset $dataset (check1=$check1)"
+           check="no"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check1=$check1)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR checkstardone.C failed for dataset $dataset (check1=$check1)"
+           com=$Fstardone
+           check=$check1
+           ;;
+   esac
+
+   setstatus "stop" 
+done
+
+finish 
Index: branches/Mars_McMismatchStudy/datacenter/scripts/checktransfer
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/checktransfer	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/checktransfer	(revision 17960)
@@ -0,0 +1,58 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  09/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script checks the transfer: 
+# 1) the transfer of subsystem files from LP
+# 2) the transfer of rawfiles from PIC
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+
+#checking the transfer of the subsystemdata files
+transferdir=/home/lapalma/transfer
+dirs=`find $transferdir -type d`
+for dir in $dirs
+do 
+   if [ "$dir" = "$transferdir" ]
+   then 
+      continue
+   fi
+   files=`find $dir -maxdepth 1 -type f | wc -l`
+   if [ $files -eq 0 ]
+   then
+      continue
+   fi
+   printprocesslog "WARN $dir contains still $files files"
+done
+
+#checking if there are temporary zipfiles
+files=`find $datapath/rawfiles/20[0-1][0-9]/ -name ".*\.raw\.??????"`
+
+for file in ${files[@]}
+do 
+   printprocesslog "WARN found temporary zipfile $file"
+done
Index: branches/Mars_McMismatchStudy/datacenter/scripts/condorstatistics
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/condorstatistics	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/condorstatistics	(revision 17960)
@@ -0,0 +1,89 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  07/2008 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script reads the output of the cronjob
+#  /usr/local/bin/condor_status -state 
+# which is stored in /magic/datacenter/autologs/condor/YYYY/MM/DD
+# and fills it to the database (table CondorStatus). 
+# The output of the cronjob
+#  /usr/local/bin/condor_userprio -all -usage -activefrom 1 1 2000 
+# is not jet filled.
+# After filling the directories are tared. 
+#
+# From the database plots are produced (root, pdf and png files) and 
+# moved to the webdirectory.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=condorstatistics
+
+set -C
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+condorpath=$logpath/condor
+dates=`find $condorpath -mindepth 3 -maxdepth 3 -type d -regex "^$condorpath/20[01][0-9]/[01][0-9]/[0-3][0-9]$"`
+
+for date in ${dates[@]}
+do
+   cd $mars
+   
+   echo "filling condor statistics for $date... " >> $scriptlog 2>&1
+   printprocesslog "INFO filling condor statistics for $date"
+   check0=`root -q -b $macrospath/fillcondor.C+\("\"$date\""\,kFALSE\) | tee -a $scriptlog | intgrep`
+   
+   case $check0 in 
+      1)   echo " check0=$check0 -> everything ok -> move files" >> $scriptlog 2>&1
+           printprocesslog "INFO condor statistic filled succesfully"
+           day=`basename $date`
+           cd `dirname $date`
+           if ! tar -czf $day.tar.gz $day/*  >> $scriptlog 2>&1
+           then 
+              printprocesslog "WARN tarring $date failed"
+              echo "tarring $date failed" >> $scriptlog 2>&1
+           else
+              if ! rm -r $day >> $scriptlog 2>&1
+              then 
+                 printprocesslog "WARN removing of $date failed"
+              fi
+           fi
+           cd $mars
+           ;;
+      *)   echo " check0=$check0 -> ERROR -> couldn't fill condor statistic to DB -> exit" >> $scriptlog 2>&1
+           printprocesslog "ERROR filling condor statistic to DB failed"
+           finish >> $scriptlog 2>&1
+           ;;
+   esac
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/copyoutput
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/copyoutput	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/copyoutput	(revision 17960)
@@ -0,0 +1,112 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  10/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# script copy processing output from one site to the other
+# 
+# FIXME: solve problem how to know which files have to be copied for which 
+# step (alias/function for file-definitions?)
+
+if [ "$SOURCEFILEPATH" = "" ]
+then 
+   source `dirname $0`/sourcefile
+else
+   source $SOURCEFILEPATH/sourcefile
+fi
+printprocesslog "INFO starting $0"
+program="corsika"
+
+function copyandcheckfile()
+{ 
+   # do rsync of file
+   command="rsync -aR -u "$extension"/"$1" "$remotemachine":"$todir
+   printprocesslog "DEBUG executing: "$command
+   if ! $command
+   then
+      printprocesslog "ERROR could not rsync file "$1
+      continue
+   fi
+   # get local checksum
+   if ! checksum1=`md5sum $fromdir/$1`
+   then
+      printprocesslog "ERROR could not get md5sum file "$1
+      continue
+   else
+      checksum1=`echo $checksum1 | awk ' { print \$1 } '`
+   fi
+   # get remote checksum
+   if ! checksum2=`ssh $remotemachine " md5sum $todir/$extension/$1 " `
+   then
+      printprocesslog "ERROR could not get remote md5sum file "$1" from "$remotemachine
+      continue
+   else
+      checksum2=`echo $checksum2 | awk ' { print \$1 } '`
+   fi
+   # compare checksums
+   if ! [ "$checksum1" = "$checksum2" ]
+   then
+      printprocesslog "ERROR local and remote md5sum for file "$1" do not match"
+      continue
+   fi
+}
+
+for step in ${tocopy[@]}
+do
+   printprocesslog "INFO copying output of step "$step 
+   getstepinfo
+   
+   # get primaries for which output has to be copied
+   query="SELECT "${prims[@]}" FROM "$step"Status WHERE NOT ISNULL(fStartTime) AND NOT ISNULL(fStopTime) AND ISNULL(fAvailable) AND ISNULL(fReturnCode) AND fProcessingSiteKEY="$sitekey
+   primstocopy=( `sendquery` )
+   num=`expr ${#primstocopy[@]} / ${#prims[@]} `
+   if [ ${#primstocopy[@]} -eq 0 ]
+   then 
+      printprocesslog "INFO no files to copy for step "$step
+      continue
+   fi
+   # BE CAREFUL: 
+   # this only works for corsika so far
+   for (( s=0 ; s < $num ; s++ ))
+   do
+      runnum=${primstocopy[$s+$s]}
+      filenum=${primstocopy[$s+$s+1]}
+      printprocesslog "INFO copying corsika files for run "$runnum" file "$filenum
+      extension=`printf %08d $runnum | cut -c 1-4`/`printf %08d $runnum | cut -c 5-8`
+      cd $mcpath/$program
+      fromdir=$mcpath/$program/$extension
+      todir=$remotedir"/simulated/"$program
+      # copy files and check md5sums
+      corsikafile=cer000`printf %06d $filenum | cut -c 4-6`
+      copyandcheckfile $corsikafile
+      corsikalogfile=cer000`printf %06d $filenum | cut -c 4-6`".log"
+      copyandcheckfile $corsikalogfile
+      
+      # in case all copying succeeded and the checksums are ok
+      # continue and update the DB
+      query="UPDATE "$step"Status SET fAvailable=Now() WHERE fFileNumber="$filenum" AND fRunNumber="$runnum
+      sendquery >/dev/null
+   done   
+done
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/copyscript
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/copyscript	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/copyscript	(revision 17960)
@@ -0,0 +1,361 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+#
+# This script handles the subsystem logfiles, which are copied every
+# day automatically from /local/ on pc15 in La Palma to 
+# /home/lapalma/transfer/ on coma in the datacenter in Wuerzburg
+# The structure in this directory is: subsystem/date/logfile.*
+# The logfiles are from CC (*.rep, CC*.dbg, CC*.rbk, CC*.rep, CC*.run,
+# CC*.run.html), Cosy (cosy*.log, cosy*.rep, tpoint*.txt/starg*.txt) 
+# AMC (AMC*.log, AMC*.info, AMC*.lut) and CaCo (dc*.txt) 
+#
+# the script performs the following steps:
+# ----------------------------------------
+# - filling the information from the *.rbk and *.run files into the DB
+# using the macros filldotrbk.C and filldotrun.C
+# - moving all logfiles to the correct directory:
+# /subsystemdata/subsystem/YYYY/MM/DD/file.*
+# - building the sequences for the standard analysis in the database
+#   (for each day of which a file was copied) 
+# - if a new catalogfile has been copied, it is installed as standard in the
+#   setup directory /magic/datacenter/setup and the new lines are sent to 
+#   the adresses specified in the script
+# 
+# -- to make sure that no file is copied twice there's a textfile
+# (.processed), to which every file, that was processed, is added 
+# .processed is copied to La Palma, so that it is possible to copy
+# only new files
+# -- to make sure that a file was copied completely before it is
+# processed, a file with the checksum of all files is also copied from
+# La Palma and the checksum is checked with this script for each file
+# before processing it. 
+# 
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=copyscript
+
+set -C
+
+umask 0002
+
+transdir=/home/lapalma/transfer
+char=24
+datetime=`date +%F-%H-%M-%S`
+lockfile=$lockpath/lock-$program.txt
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if the script is already running
+checklock  >> $scriptlog 2>&1
+
+cd $transdir
+
+#check the checksums, write output into file
+md5sum -c .checksums | tee $transdir/.check  >> $scriptlog 2>&1 
+
+if ! test -e $transdir/.check
+then
+   echo "couldn't create checkfile -> exit script" >> $scriptlog 2>&1
+   finish >> $scriptlog 2>&1
+else
+   echo "checkfile created" >> $scriptlog 2>&1
+fi
+
+
+ssh lapalma@dc09 chmod -R g+w $transdir/* >> $scriptlog 2>&1
+
+
+cd $mars 
+
+echo "remove empty directories: "  >> $scriptlog 2>&1 
+rmdir -pv $transdir/*/*  >> $scriptlog 2>&1 
+
+#find all dates in transfer-directory
+dates=`find $transdir/*/ -type d | grep -o --regexp=20[0-9][0-9]_[0-1][0-9]_[0-3][0-9] | sort | uniq` >> $scriptlog 2>&1
+if ! [ "$dates" = "" ]
+then 
+   echo "dates found: "$dates  >> $scriptlog 2>&1 
+   #loop over dates 
+   for date in ${dates[@]}
+   do 
+      printprocesslog "INFO processing files for $date"
+      #find all files for this date
+      files=`find $transdir/*/$date/ -name "*.*"`  >> $scriptlog 2>&1
+      if [ "$files" = "" ]
+      then
+         echo "no files found for $date"  >> $scriptlog 2>&1
+         continue
+      else
+         echo "files found for $date"  >> $scriptlog 2>&1
+      fi
+
+      date2=`echo $date | sed -e 's/_/\//g'`
+      copylogpath=$logpath/$program/$date2
+      echo "copylogpath: "$copylogpath >> $scriptlog 2>&1
+      makedir $copylogpath >> $scriptlog 2>&1
+
+      #loop over all files in the directories for this date
+      for file in $files
+      do
+         echo "file: "$file  >> $scriptlog 2>&1
+         filename=`basename $file`
+
+         #check for each file whether it has to be processed
+         if grep -i "$filename: OK" $transdir/.check  >> $scriptlog 2>&1
+         then
+            newfile=`echo $file | sed -e 's/home\/lapalma\/transfer/magic\/subsystemdata/' -e 's/ccdata/cc/' -e 's/cacodata/caco/' -e 's/drivelogs/drive/' -e 's/_/\//1' -e 's/_/\//1' `
+            echo "file (new path): "$newfile >> $scriptlog 2>&1
+            newpath=`dirname $newfile`
+            #make sure, that the needed directories are available
+            makedir $newpath >> $scriptlog 2>&1
+
+            #run macros if the file is a *.rbk or a *.run file to
+            #fill the information into the db
+            if echo $filename | grep \\\.rbk$  >> $scriptlog 2>&1
+            then
+               echo "found rbk-file $filename"  >> $scriptlog 2>&1
+
+               checkfillrbk=`root -q -b $macrospath/filldotrbk.C+\("\"$file\""\,kFALSE\) | tee $copylogpath/filldotrbk-$filename-log.txt | intgrep`
+
+               case $checkfillrbk in
+                  1) echo " checkfillrbk=$checkfillrbk -> everything ok " >> $scriptlog 2>&1
+                     echo "  -> go on with moving file" >> $scriptlog 2>&1
+                     ;;
+                  *) echo " checkfillrbk=$checkfillrbk - Error -> go on with next file" >> $scriptlog 2>&1
+                     printprocesslog "ERROR filldotrbk.C failed for $file"
+                     continue
+                     ;;
+               esac
+            fi
+
+            if echo $file | grep 'CC_.*.run' >> $scriptlog 2>&1  && ! echo $file | grep .run.html >> $scriptlog 2>&1
+            then
+               echo "found run-file $filename" >> $scriptlog 2>&1
+
+               fillrunlog=$copylogpath"/filldotrun-$filename-log.txt"
+               checkfillrun=`root -q -b $macrospath/filldotrun.C+\("\"$file\""\,kFALSE\) | tee $fillrunlog | intgrep`
+               if grep WARN $fillrunlog >/dev/null
+               then 
+                  printprocesslog "WARN found in logfile "$fillrunlog
+               fi
+               
+               if grep ERROR $fillrunlog >/dev/null
+               then 
+                  printprocesslog "ERROR found in logfile "$fillrunlog
+               fi
+
+               case $checkfillrun in
+                  1) echo " checkfillrun=$checkfillrun -> everything ok " >> $scriptlog 2>&1
+                     echo "  -> insert date in SequenceBuildStatus for $date" >> $scriptlog 2>&1
+
+                     checkinsertdate=`root -q -b $macrospath/insertdate.C+\("\"$date\""\) | tee $copylogpath/insertdate-$date-log.txt | intgrep`
+
+                     case $checkinsertdate in
+                        1) echo "date inserted" >> $scriptlog 2>&1 ;;
+                        *) echo " checkinsertdate=$checkinsertdate -> ERROR - insert date didn't work" >> $scriptlog 2>&1
+                           printprocesslog "ERROR insertdate.C failed for $date"
+                           continue
+                           ;;
+                     esac
+                     echo " -> go on with moving file" >> $scriptlog 2>&1
+                     ;;
+                  *) echo " checkfillrun=$checkfillrun Error -> go on with next file" >> $scriptlog 2>&1
+                     printprocesslog "ERROR filldotrun.C failed for $file"
+                     continue
+                     ;;
+               esac
+            fi
+
+            if mv -v $file $newpath >> $scriptlog 2>&1
+            then
+               #add file to donelist
+               filename3=`echo $file | cut -c $char-999`
+               echo "$filename3 processed" >> $transdir/.processed
+               echo $filename" moved and added to .processed" >> $scriptlog 2>&1
+            else
+               echo $file" couldn't be moved!!!!!" >> $scriptlog 2>&1
+               printprocesslog "WARN moving of file $file didn't work"
+            fi
+
+         else
+            #if the checksum for the file is not ok or the file was
+            #already processed (entry in donelist) -> go on with next file
+            echo $file": checksum not ok " >> $scriptlog 2>&1
+            printprocesslog "WARN checksum for file $file is not ok"
+         fi
+      done
+   done
+fi
+
+
+echo "remove empty directories: "  >> $scriptlog 2>&1 
+rmdir -pv $transdir/*/*  >> $scriptlog 2>&1 
+
+rm -v $transdir/.check >> $scriptlog 2>&1 
+
+
+# second part of the script
+#searching optical data files, inserting the information into the db and
+#moving the files
+file=""
+printprocesslog "INFO processing optical files"
+echo "processing optical files..." >> $scriptlog 2>&1
+opticalfiles=`find $transdir/optical -regextype posix-egrep -regex "^$transdir/optical/20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_[RV][_]?[12]?[.]instr$"`
+for opticalfile in $opticalfiles
+do
+   printprocesslog "INFO process "$opticalfile
+   file=`basename $opticalfile`
+   year=`echo $file | cut -c 0-4`
+   opticallogpath=$logpath/filloptical/$year
+   makedir $opticallogpath >> $scriptlog 2>&1
+   opticallogfile=$opticallogpath/filloptical-$file.log
+  
+   checkfilloptical=`root -q -b $macrospath/filloptical.C+\("\"$opticalfile\""\,kFALSE\) | tee $opticallogfile | intgrep`
+            
+   case $checkfilloptical in
+      1) echo " checkfilloptical=$checkfilloptical -> everything ok -> go on with moving file" >> $scriptlog 2>&1 
+         newdir=$subsystempath/optical/$year
+         newfile=$newdir/$file
+         makedir $newdir >> $scriptlog 2>&1
+         
+         if mv -v $opticalfile $newfile >> $scriptlog 2>&1 
+         then
+            echo "moved "$opticalfile" successfully" >> $scriptlog 2>&1 
+            printprocesslog "INFO moved "$opticalfile" successfully"
+         else
+            echo $opticalfile" couldn't be moved!!!!!" >> $scriptlog 2>&1 
+            printprocesslog "WARN moving of file $opticalfile didn't work"
+         fi
+         ;;
+      3) echo " checkfilloptical=$checkfilloptical - ERROR filloptical.C failed for $opticalfile: position of one object is missing in the database" >> $scriptlog 2>&1 
+         printprocesslog "ERROR filloptical.C failed for $opticalfile: position of one object is missing in the database"
+         continue ;;
+      4) echo " checkfilloptical=$checkfilloptical - ERROR filloptical.C failed for $opticalfile: telescope line with more or less than 2 arguments" >> $scriptlog 2>&1 
+         printprocesslog "ERROR filloptical.C failed for $opticalfile: telescope line with more or less than 2 arguments"
+         continue ;;
+      5) echo " checkfilloptical=$checkfilloptical - ERROR filloptical.C failed for $opticalfile: timestamp line with more or less than 4 arguments" >> $scriptlog 2>&1 
+         printprocesslog "ERROR filloptical.C failed for $opticalfile: timestamp line with more or less than 4 arguments"
+         continue ;;
+      6) echo " checkfilloptical=$checkfilloptical - ERROR filloptical.C failed for $opticalfile: object line with more or less than 8 arguments" >> $scriptlog 2>&1 
+         printprocesslog "ERROR filloptical.C failed for $opticalfile: object line with more or less than 8 arguments"
+         continue ;;
+      *) echo " checkfilloptical=$checkfilloptical - ERROR filloptical.C failed for $opticalfile -> go on with next file" >> $scriptlog 2>&1 
+         printprocesslog "ERROR filloptical.C failed for $opticalfile (returned $checkfilloptical)"
+         continue ;;
+   esac
+done
+
+
+# third part of the script:
+#update the catalog file magic_favorites.edb
+printprocesslog "INFO processing new catalog files"
+echo "Processing new catalog files" >> $scriptlog 2>&1
+magfav=magic_favorites.edb #catalog filename
+catalog=$setuppath/$magfav #current catalogfile
+diff=/tmp/magic_favorites_diff #file to store difference
+
+#getting new catalogfiles 
+for (( i=0 ; i < 31 ; i++ ))
+do
+   date=`date --date "-${i}day" +%Y/%m/%d`
+   path=$subsystempath/cc/$date
+   catfiles=$catfiles" "`find $path -name $magfav -newer $catalog`
+done
+
+for catfile in ${catfiles[@]}
+do
+   printprocesslog "INFO processing catalog file $catfile"
+   #write information into .diff
+   echo "diff $catfile $catalog" >| $diff
+   diff $catfile $catalog >> $diff
+   #getting differences
+   ins=`cat $diff | grep '>'`  #what has been inserted
+   outs=`cat $diff | grep '<'` #what has been removed
+   
+   #check if lines have been inserted
+   if ! [ "$ins" == "" ]
+   then 
+      echo "--> catalogfile: "$catfile >> $scriptlog 2>&1 
+      echo "the following lines were added:" >> $scriptlog 2>&1 
+      cat $diff | grep '>'  >> $scriptlog 2>&1 
+   
+      #check if lines have been removed
+      if ! [ "$outs" == "" ]
+      then 
+         echo "the following lines have been removed" >> $scriptlog 2>&1 
+         cat $diff | grep '<'  >> $scriptlog 2>&1 
+         echo " -> please check the file $catfile" >> $scriptlog 2>&1 
+         #inform $adrs about removed lines
+         nail -s 'catalogfile - removed lines' $adrs < $diff
+         printprocesslog "NEWS catalog file: lines have been removed ($catfile)"
+         finish >> $scriptlog 2>&1
+      fi
+      
+      #getting date of new catalogfile from path
+      date=`echo $catfile | cut -d/ -f5-7 | sed -e 's/\///g'`
+
+      oldcatalogpath=$setuppath/oldcatalogs
+      makedir $oldcatalogpath >> $scriptlog 2>&1
+      #rsync current catalogfile to directory with old catalogfiles including the date of the new catalogfile into the filename
+      if ! rsync -av $catalog $oldcatalogpath/$magfav.$date >> $scriptlog 2>&1 
+      then 
+         echo "could not do 'rsync -av $catalog $setuppath/oldcatalogs/$magfav.$date' -> exit" >> $scriptlog 2>&1 
+         printprocesslog "ERROR rsync of catalog file ($catalog -> $oldcatalogpath/$magfav.$date) didn't work"
+         finish >> $scriptlog 2>&1
+      fi
+      #rsync new catalogfile to current catalogfile
+      if ! rsync -av $catfile $catalog >> $scriptlog 2>&1 
+      then 
+         echo "could not do 'rsync -av $catfile $catalog' -> exit" >> $scriptlog 2>&1 
+         printprocesslog "ERROR rsync of catalog file ($catfile -> $catalog) didn't work"
+         finish >> $scriptlog 2>&1
+      fi
+      #inform $adrs about changes
+      echo "file has been rsynced sucessfully -> sending email" >> $scriptlog 2>&1 
+      nail -s 'new catalogfile installed - new lines'  $adrs < $diff
+      printprocesslog "NEWS there are new lines in the catalogfile (see $catalog)"
+      continue
+   fi
+   #check if lines have been removed
+   if ! [ "$outs" == "" ]
+   then 
+      echo "the following lines have been removed" >> $scriptlog 2>&1 
+      cat $diff | grep '<'  >> $scriptlog 2>&1 
+      echo " -> please check the file $catfile" >> $scriptlog 2>&1 
+      #inform $adrs about removed lines
+      nail -s 'catalogfile - removed lines' $adrs < $diff
+      printprocesslog "NEWS catalog file: lines have been removed ($catfile)"
+      finish >> $scriptlog 2>&1
+   fi
+#   echo "nothing has changed ($catfile)"  >> $scriptlog 2>&1 
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/correcttime
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/correcttime	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/correcttime	(revision 17960)
@@ -0,0 +1,109 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script runs the timing correction for all run, that need the timing
+# correction
+#
+# After checking if the script is already running the todolist is written.
+# Then for each run the timing correction is done 
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+# This script was needed for the data between 06/2004 and 02/2005 (including
+# this months). 
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+echo "This script has not been adapted to the new file structure (MAGIC II) and new logging. "
+echo "Please adapt it before using it."
+exit
+
+program=correct_raw_time
+column=fTimingCorrection
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+if [ -e $todofile ]
+then 
+   echo "$program is already running -> exit" >> $scriptlog 2>&1
+   exit
+fi
+
+# get todo list
+getdolist  >> $scriptlog 2>&1
+
+# retrieving runs from todo file
+runs=(`cat $listpath/ToDo-$table-$column.txt`)
+if [ "$runs" = "" ]
+then 
+   echo "nothing to do -> exit" >> $scriptlog 2>&1
+   finish >> $scriptlog 2>&1
+fi
+echo "runs: "${runs[@]} >> $scriptlog 2>&1
+
+cd $mars
+
+for run in ${runs[@]}
+do 
+   printprocesslog "INFO run correct_raw_time for run $run"
+   no=`printf %08d $run | cut -c 1-5`
+   echo "getting path for run $run ... " >> $scriptlog 2>&1
+   infile=`find $datapath/rawfiles-wrong-timing/ -name *${run}_[DCPS]_*`
+   echo "infile:"$infile >> $scriptlog 2>&1
+   outfile=`echo $infile | sed -e 's/-wrong-timing//g'`
+   echo "outfile:"$outfile >> $scriptlog 2>&1
+   outpath=`dirname $outfile`
+   echo "outpath:"$outpath >> $scriptlog 2>&1
+   makedir $outpath >> $scriptlog 2>&1
+
+   timecorrpath=$outpath"/timecorrlogs"
+   echo "timecorrpath: "$timecorrpath >> $scriptlog 2>&1
+   makedir $timecorrpath >> $scriptlog 2>&1
+
+   check1=0
+   echo "run $program..." >> $scriptlog 2>&1
+   primvar=$run
+   setstatus "start" >> $scriptlog 2>&1
+
+   /home/tape/MagicReadout/correct_raw_time $infile $outfile > $timecorrpath/$program-$run.log
+   check1=$?
+
+   case $check1 in
+      1)   echo " check1=$check1 -> everything ok -> setting status..." >> $scriptlog 2>&1 ;;
+      *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+           printprocesslog "ERROR $program failed"
+           com=$Ftimecorr
+           check=$check1
+           ;;
+   esac
+   
+   setstatus "stop" >> $scriptlog 2>&1
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/cutslices
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/cutslices	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/cutslices	(revision 17960)
@@ -0,0 +1,105 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Stefan Ruegamer 12/2007 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script is removing the switching noise out of raw files.
+# Corresponding information will be inserted into the database. The noise
+# removal is being done by the script 'compmux'.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=compmux
+column=fCompmux
+
+set -C
+
+scriptlog=$runlogpath/run$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# query db 20 times for jobs
+for ((j=0 ; j < 10000 ; j++))
+do
+   gettodo "1" >> $scriptlog 2>&1
+   runno=${primaries[0]}
+   tempfile=/data/tmp/temp${runno}.gz
+   
+   lockfile=$lockpath/lock-$table-$column-$runno.txt
+   checklock continue >> $scriptlog 2>&1
+   
+   setstatus "start" >> $scriptlog 2>&1
+   
+   # try to find the file; if impossible, continue with an error
+   echo "getting path for run $runno..." >> $scriptlog 2>&1
+   printprocesslog "INFO starting $program for run $runno"
+   fullname=`find $datapath/rawfiles/2007/0[2-9] -name 20070*${runno}_[DCPS]_*.raw.gz`
+   arraycheck=`echo $fullname | wc -w`
+   if [ "$fullname" == "" ] || ! [ $arraycheck == 1 ]
+   then
+      echo "ERROR file for run $runno not found or more than one file found... continue" >> $scriptlog 2>&1
+      printprocesslog "ERROR $program failed, file for run $runno not found or more than one file found"
+      rm -v $lockpath/lock-$table-$column-$runno.txt >> $scriptlog 2>&1
+      check=20
+      com=$FCompmux
+      setstatus "stop" >> $scriptlog 2>&1
+      echo "" >> $scriptlog 2>&1
+      continue
+   fi
+   
+   # cut the slices
+   check1=`ssh -nx phoenix 'cd /home/operator/compmux ; nice -n 19 gzip -cd' $fullname '| nice -n 19 ./compmux | nice -n 19 gzip -1c > /data/tmp/temp'${runno}.gz ' ; echo ${PIPESTATUS[1]}'`
+   
+   # check success and insert information into the database
+   case $check1 in
+      0)   echo " check1=$check1 -> everything ok -> compmux succeeded, overwriting old file for run $runno" >> $scriptlog 2>&1
+      	   ssh -nx phoenix nice -n 19 touch -r $fullname $tempfile
+           ssh -nx phoenix nice -n 19 mv -f $tempfile $fullname >> $scriptlog 2>&1
+           check2=$?
+           case $check2 in
+              0)   echo " check2=$check2 -> everything ok -> mv done, setting db status for run $runno" >> $scriptlog 2>&1
+      	           ssh -nx phoenix nice -n 19 chmod a=r $fullname
+                   ;;
+              *)   echo " check2=$check2 -> ERROR - moving of run $runno failed" >> $scriptlog 2>&1
+                   printprocesslog "ERROR $program failed, moving of run $runno failed"
+        	   check=$check2
+              	   com=$FCompmux
+                   ;;
+           esac
+           printprocesslog "INFO $program finished successfully for run $runno"
+           ;;
+      *)   echo " check1=$check1 -> ERROR - $program failed for run $runno" >> $scriptlog 2>&1
+           printprocesslog "ERROR $program failed for run $runno"
+           rm -v $tempfile >> $scriptlog 2>&1
+           check=$check1
+      	   com=$FCompmux
+           ;;
+   esac
+   
+   rm -v $lockpath/lock-$table-$column-$runno.txt >> $scriptlog 2>&1
+   setstatus "stop" >> $scriptlog 2>&1
+   echo "" >> $scriptlog 2>&1
+done
+
+finish >> $scriptlog 2>&1
Index: branches/Mars_McMismatchStudy/datacenter/scripts/dbchk
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/dbchk	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/dbchk	(revision 17960)
@@ -0,0 +1,199 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Thomas Bretz  03/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+#   Author(s): Daniela Dorner  02/2008 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Stefan Ruegamer  02/2008 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script searches for crashed runs, sequences or datasets in the db
+# as well as obsolete or missing sequence files and corresponding callisto
+# and star folders. In the third and fourth check the consistency between
+# the Run and Sequence DB is checked.
+#
+#
+# TODO
+#
+# Spped up with SQL: FIELD(25123, 1, 2, 3, 4, 5, ..., 1000200);
+# Cross check sequences in Sequence and other databases
+# added switch which allows to correct for the problems immediatly
+# unify the checks (especially 1b and 1c)
+# for the sequences better use 0* instead of 0+ ?
+
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=dbchk
+
+getdbsetup
+alias mymysql='mysql -s -u $us --password=$pw --host=$ho $db'
+
+# check for crashed nights, runs, sequences and datasets
+printprocesslog "INFO Checking if something is crashed on nightly basis" 
+nights=`echo "SELECT fDate FROM SequenceBuildStatus WHERE isnull(fFailedTime) and not isnull(fStartTime) and adddate(fStartTime, Interval 12 HOUR) < Now()" | mymysql`
+if [ ! "$nights" = "" ]
+then
+   printprocesslog "WARN For the following nights something seems to be crashed. Please check manually: $nights"
+else
+   printprocesslog "INFO Nothing found." 
+fi
+
+printprocesslog "INFO Checking if something is crashed on run basis" 
+cruns=`echo "SELECT fRunNumber FROM RunProcessStatus WHERE isnull(fFailedTime) and not isnull(fStartTime) and adddate(fStartTime, Interval 12 HOUR) < Now()" | mymysql`
+if [ ! "$cruns" = "" ]
+then
+   printprocesslog "WARN The following runs seem to be crashed. Please check manually: $cruns"
+else
+   printprocesslog "INFO Nothing found." 
+fi
+
+printprocesslog "INFO Checking if something is crashed on sequence basis" 
+csequences=`echo "SELECT fSequenceFirst FROM SequenceProcessStatus WHERE isnull(fFailedTime) and not isnull(fStartTime) and adddate(fStartTime, Interval 12 HOUR) < Now()" | mymysql`
+if [ ! "$csequences" = "" ]
+then
+   printprocesslog "WARN The following sequences seem to be crashed. Please check manually: $csequences"
+else
+   printprocesslog "INFO Nothing found." 
+fi
+
+printprocesslog "INFO Checking if something is crashed on dataset basis" 
+cdatasets=`echo "SELECT fDataSetNumber FROM DataSetProcessStatus WHERE isnull(fFailedTime) and not isnull(fStartTime) and adddate(fStartTime, Interval 12 HOUR) < Now()"  | mymysql`
+if [ ! "$cdatasets" = "" ]
+then
+   printprocesslog "WARN The following datasets seem to be crashed. Please check manually: $cdatasets"
+else
+   printprocesslog "INFO Nothing found." 
+fi
+
+# CHECK 1
+printprocesslog "INFO Checking if all sequence files have a corresponding entry in Sequences" 
+files=`find $sequpath -type f`
+for file in $files
+do
+   sequence=`echo $file | sed -e "s/^.*\/sequence0\+\([0-9]\+\)\.txt$/\1/"`
+   if [ "$sequence" = "" ] || [ "$sequence" = "$file" ]
+   then
+      printprocesslog "ERROR No sequence file: $file" 
+      continue
+   fi
+ 
+   var=`echo SELECT fSequenceFirst FROM Sequences WHERE fSequenceFirst=$sequence | mymysql`
+   if ! [ "$sequence" = "$var" ]
+   then
+      printprocesslog "ERROR Sequence-File $sequence exists, but it is not in Sequences (DB)." 
+      continue
+   fi
+done
+
+# CHECK 1b (callisto)
+printprocesslog "INFO Checking if all sequences in ${datapath}/callisto have a corresponding sequence in Sequence" 
+dirs=`find ${datapath}/callisto -mindepth 2 -maxdepth 2 -type d`
+for dir in $dirs
+do
+   sequence=`echo $dir | sed -e "s/^.*\/0\+\([0-9]\+\)$/\1/"`
+   if [ "$sequence" = "" ] || [ "$sequence" = "$dir" ]
+   then
+      printprocesslog "ERROR Invalid directory: $dir" 
+      continue
+   fi
+   
+   var=`echo SELECT fSequenceFirst FROM Sequences WHERE fSequenceFirst=$sequence | mymysql`
+   if ! [ "$sequence" = "$var" ]
+   then
+      printprocesslog "ERROR $dir exists, but no corresponding sequence in Sequences (DB)." 
+      continue
+   fi
+done
+
+# CHECK 1c (star)
+printprocesslog "INFO Checking if all sequences in ${datapath}/star have a corresponding sequence in Sequence" 
+dirs=`find ${datapath}/star -mindepth 2 -type d`
+for dir in $dirs
+do
+   sequence=`echo $dir | sed -e "s/^.*\/0\+\([0-9]\+\)$/\1/"`
+   if [ "$sequence" = "" ] || [ "$sequence" = "$dir" ]
+   then
+      printprocesslog "ERROR Invalid directory: $dir" 
+      continue
+   fi
+   
+   var=`echo SELECT fSequenceFirst FROM Sequences WHERE fSequenceFirst=$sequence | mymysql`
+   if ! [ "$sequence" = "$var" ]
+   then
+      printprocesslog "ERROR $dir exists, but no corresponding sequence in Sequences (DB)." 
+      continue
+   fi
+done
+
+# CHECK 2
+printprocesslog "INFO Checking if all sequences in Sequences have a corresponding sequence files" 
+sequences=`echo SELECT fSequenceFirst FROM Sequences left join SequenceProcessStatus using (fSequenceFirst,fTelescopeNumber) where not isnull(fSequenceFileWritten) | mymysql`
+for sequence in $sequences
+do
+   var=`find $sequpath -type f -regex .*/sequence0+${sequence}\.txt$`
+   if [ "$var" = "" ]
+   then
+      printprocesslog "ERROR Sequence-File for $sequence not found but in DB." 
+   fi
+done
+
+# CHECK 3
+printprocesslog "INFO Checking if all sequences from Sequences exist RunData" 
+sequences=`echo SELECT fSequenceFirst FROM Sequences GROUP BY fSequenceFirst | mymysql`
+for sequence in $sequences
+do
+   res=`echo SELECT fSequenceFirst FROM RunData WHERE fSequenceFirst=$sequence GROUP BY fSequenceFirst | mymysql`
+   if ! [ "$sequence" = "$res" ]
+   then
+      printprocesslog "ERROR Sequence $sequence exists in Sequences but not in RunData (DB)."
+      continue
+   fi
+done
+
+# CHECK 4
+printprocesslog "INFO Checking if all sequences from RunData exist in Sequences" 
+sequences=`echo SELECT fSequenceFirst FROM RunData WHERE not fSequenceFirst=0 GROUP BY fSequenceFirst | mymysql`
+for sequence in $sequences
+do
+   var=`echo SELECT fSequenceFirst FROM Sequences WHERE fSequenceFirst=$sequence | mymysql`
+   if ! [ "$sequence" = "$var" ]
+   then
+      printprocesslog "ERROR Sequence $sequence exists in RunData but not in Sequences (DB)." 
+      continue
+   fi
+done
+
+# CHECK 5
+printprocesslog "INFO Checking if all sequences from RunData exist in SequenceProcessStatus" 
+sequences=`echo SELECT fSequenceFirst FROM RunData WHERE not fSequenceFirst=0 GROUP BY fSequenceFirst | mymysql`
+for sequence in $sequences
+do
+   var=`echo SELECT fSequenceFirst FROM SequenceProcessStatus WHERE fSequenceFirst=$sequence | mymysql`
+   if ! [ "$sequence" = "$var" ]
+   then
+      printprocesslog "ERROR Sequence $sequence exists in RunData but not in SequenceProcessStatus (DB)." 
+      continue
+   fi
+done
+
+finish 
Index: branches/Mars_McMismatchStudy/datacenter/scripts/dodatacheck
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/dodatacheck	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/dodatacheck	(revision 17960)
@@ -0,0 +1,194 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the datacheck for all runs, which are not yet 
+# checked
+#
+# Get todo file
+# Then for each run the following steps are done: 
+#  - filldotraw.C
+#  - sinope (once for data and once for calibration events)
+#  - fillsinope
+#  - reset ExclusionsDone, so that the result from the datacheck can be 
+#    taken into account when doexclusions is running the next time
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+echo "This script has not been adapted to the new file structure (MAGIC II) and new logging. "
+echo "Only the usage of getodo has been adapted, but not tested."
+echo "Please adapt it before using it."
+exit
+
+program=datacheck
+column=fDataCheckDone
+
+set -C
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# get run # 
+gettodo "1" >> $scriptlog 2>&1
+run=${primaries[0]}
+telnum=${primaries[1]}
+filenum=${primaries[2]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$run.txt
+checklock >> $scriptlog 2>&1
+
+cd $mars
+
+echo "do $program for run "$run >> $scriptlog 2>&1
+printprocesslog "INFO do $program for run $run"
+no=`printf %08d $run | cut -c 0-2`
+no2=`printf %08d $run`
+query="SELECT DATE_FORMAT(ADDDATE(fRunStart, INTERVAL +13 HOUR), '%Y/%m/%d') FROM RunData where fRunNumber="$run
+date=`sendquery`
+rawfile=`find /magic/data/rawfiles/$date -name *${run}_[D,P,C,S,N]_*.raw -o -name *${run}_[DPCSN]_*.raw.gz`
+echo "rawfile: "$rawfile >> $scriptlog 2>&1
+# for sinope the date is needed in the format YYYY-MM-DD
+date2=`echo $date | sed -e 's/\//-/g'`
+
+#primvar=$no2
+setstatus "start" >> $scriptlog 2>&1
+
+# running filldotraw
+echo "doing filldotraw..." >> $scriptlog 2>&1
+filldotrawpath=$logpath/filldotraw/$date
+makedir $filldotrawpath >> $scriptlog 2>&1
+filldotrawlogfile=$filldotrawpath/filldotraw-$no2.log
+
+check1=`root -q -b $macrospath/filldotraw.C+\("\"$rawfile\""\,kFALSE\) | tee $filldotrawlogfile | intgrep`
+
+case $check1 in 
+   1)   echo " check1=$check1 -> everything ok -> go on with $program..." >> $scriptlog 2>&1
+        printprocesslog "INFO finished filldotraw.C sucessfully for $rawfile"
+        ;;
+   0)   echo " check1=$check1 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+        printprocesslog "WARN connection to DB failed"
+        check="no"
+        setstatus "stop" >> $scriptlog 2>&1
+        continue ;;
+   *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+        printprocesslog "ERROR filldotraw.C failed for $rawfile"
+        com=$Ffillraw
+        check=$check1
+        setstatus "stop" >> $scriptlog 2>&1
+        continue ;;
+esac
+
+# running sinope 
+printprocesslog "INFO running sinope for $run"
+sinopepath=$datapath/sinope/$date
+makedir $sinopepath >> $scriptlog 2>&1
+
+sins=( "-dat"  "-cal")
+for sin in ${sins[@]}
+do 
+   sinopefile=sinope$sin$no2
+   
+   echo "running sinope $sin..." >> $scriptlog 2>&1
+   ./sinope -b -q -v4 -f $sin --outf=$sinopefile --out=$sinopepath --log=$sinopepath/$sinopefile.log --html=$sinopepath/$sinopefile.html --run=$run --date=$date2  2>> $scriptlog > /dev/null
+   check2=$?
+   
+   case $check2 in 
+      0)   echo " check2=$check2 -> everything ok -> go on with $program..." >> $scriptlog 2>&1
+           ;;
+      *)   echo " check2=$check2 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+           printprocesslog "ERROR sinope $sin failed for $rawfile"
+           com=$Fsinope
+#           comadd=
+           check=$check2
+           setstatus "stop" >> $scriptlog 2>&1
+           continue 2;;
+   esac
+   check2=1
+done
+
+# running fillsinope
+fillsinopepath=$logpath/fillsinope/$date
+makedir $fillsinopepath >> $scriptlog 2>&1
+fillsinopelogfile=$fillsinopepath/fillsinope-$no2.log
+
+echo "doing fillsinope..." >> $scriptlog 2>&1
+check3=`root -q -b $macrospath/fillsinope.C+\($run\,"\"$datapath\""\,kFALSE\) | tee $fillsinopelogfile | intgrep`
+
+case $check3 in 
+   1)   echo " check3=$check3 -> everything ok -> set status..." >> $scriptlog 2>&1
+        printprocesslog "INFO finished fillsinope.C sucessfully for run $run"
+        ;;
+   0)   echo " check3=$check3 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+        printprocesslog "WARN connection to DB failed"
+        check="no"
+        setstatus "stop" >> $scriptlog 2>&1
+        continue ;;
+   *)   echo " check3=$check3 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+        printprocesslog "ERROR fillsinope.C failed for run $run"
+        com=$Ffillsinope
+        check=$check3
+        setstatus "stop" >> $scriptlog 2>&1
+        continue ;;
+esac
+
+# resetting the status for exclusions
+echo "resetting the status for fExclusionsDone for date $date2" >> $scriptlog 2>&1
+printprocesslog "INFO resetting fExclusions done for $date2"
+resetlogpath=$logpath/resetexclusions/$date
+makedir $resetlogpath >> $scriptlog 2>&1
+resetlog=$resetlogpath/reset-exclusions-$no2-$date2.log
+
+check5=`root -q -b $macrospath/resetcolumn.C+\("\"fExclusionsDone\""\,"\"SequenceBuildStatus\""\,"\"$date2\""\,"\"$date2\""\,kFALSE\) | tee $resetlog | intgrep`
+case $check5 in
+   1)   echo " check5=$check5 -> everything ok, fExclusions have been reset " >> $scriptlog 2>&1
+        printprocesslog "INFO resetted fExclusions done for $date2 successfully"
+        ;;
+   0)   echo " check5=$check5 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+        printprocesslog "WARN connection to DB failed"
+        check="no"
+        setstatus "stop" >> $scriptlog 2>&1
+        continue ;;
+   *)   echo " check5=$check5 -> ERROR -> step could not be resetted -> repeat step " >> $scriptlog 2>&1
+        printprocesslog "ERROR resetcolumn.C failed for date $date2"
+        com=$Fresetexcl
+        comadd=`echo $date2 | sed -e 's/-//g'`
+        check=$check5
+        setstatus "stop" >> $scriptlog 2>&1
+        continue ;;
+esac
+
+# set status
+statustime="Now()"
+failed="NULL"
+starttime="NULL"
+failedtime="NULL"
+setstatus "stop" >> $scriptlog 2>&1
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/doexclusions
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/doexclusions	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/doexclusions	(revision 17960)
@@ -0,0 +1,84 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the excluding of runs for all days for which 
+# this step is needed. 
+#
+# After checking if the script is already running the todolist is written.
+# Then the run are excluded for each date in the todolist using the 
+# macro doexclusions.C
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=doexclusions
+column=fExclusionsDone
+
+set -C
+
+# check if the script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+# do exclusions for each date in the todo file
+for (( s=0 ; s < $num ; s++ ))
+do
+   date=${primaries[$s+$s]}
+   telnum=${primaries[$s+$s+1]}
+   printprocesslog "INFO do exclusions for $date $date"
+   year2=`echo $date | cut -c 1-4`
+   doexclusionspath=$logpath/$program/$year2
+   makedir $doexclusionspath 
+   doexclusionslog=$doexclusionspath/doexclusions-$date.log
+
+   setstatus "start" 
+
+   check1=`root -q -b $macrospath/doexclusions.C+\("\"$date\""\,$telnum\,kFALSE\) | tee $doexclusionslog | intgrep`
+
+   case $check1 in
+      1)   printprocesslog "INFO exclusions successfully done for $date (check1=$check1)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check1=$check1)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR $program.C failed (check1=$check1)"
+           com=$Fdoexcl
+           check=$check1
+           ;;
+   esac
+   
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/dowebplots
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/dowebplots	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/dowebplots	(revision 17960)
@@ -0,0 +1,338 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2008 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script produces the plots from all root-files in the web directory
+# 
+# After checking, if the script is already running, the plots are produced:
+# With the programm showplot a ps-file is written, from which the png 
+# files are produced. 
+#
+# The files from which plots are created can be devided into two categories:
+# general: plots needed only once per telescope
+# individual: plots done for each sequence / dataset
+#
+# For 'general' first the rootfiles are created with a macro from the 
+# database, then from this the ps via showplot, from this the pdf and the 
+# png files. 
+# For 'individual' running the macro is only needed for the plotdb for 
+# ganymed. The other steps are done accordingly. 
+#
+# Via command line options the plots can be selected. For more information
+# execute the script with the -h option. 
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=dowebplots
+
+set -C
+
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+echo $@  >> $scriptlog 2>&1
+
+# definition of the plots to be created
+generals=( plotdb optical condor status )
+individuals=( calib signal star ganymed gplotdb )
+# definition of the variables needed and varying for the plots
+names=(     plotdb     optical    condor   status     calib     signal     star     ganymed           gplotdb )
+pathnames=( plotdb     optical    condor   status  callisto   callisto     star     ganymed           ganymed )
+macros=(    plotdb plotoptical plotusage plotstat        no         no       no          no                no )
+filenames=( plotdb plotoptical plotusage plotstat     calib     signal     star     ganymed            plotdb )
+columns=(       no          no        no       no fWebCalib fWebSignal fWebStar fWebGanymed fWebPlotDBGanymed )
+digits=( 0 0 0 0 4 4 4 5 5 )
+
+# function to print the usage of the script
+function usage()
+{
+   echo "Usage: $0 [options]"
+   echo "options:"
+   echo -n "  --general    name  "
+   echo " where 'name' can be 'all' or one of the following: ${generals[@]} "
+   echo -n "  --individual name  "
+   echo " where 'name' can be 'all' or one of the following: ${individuals[@]} "
+   echo -n "  -h                 "
+   echo " print this usage "
+   echo "" 
+   echo "Remark: if no commandline option is given the plots are produced for everything." 
+   echo "" 
+   exit
+}
+
+# reading in the command line options
+general=( )
+individual=( )
+while [ "$1" ]
+do 
+   case $1 in 
+        --general) shift
+                   if [ "$1" = "all" ]
+                   then
+                      general=( ${generals[@]} )
+                   else 
+                      general=( ${general[@]} $1 )
+                   fi
+                   ;;
+     --individual) shift
+                   if [ "$1" = "all" ]
+                   then
+                      individual=( ${individuals[@]} )
+                   else 
+                      individual=( ${individual[@]} $1 )
+                   fi
+                   ;;
+              -h)  usage 
+                   exit
+                   ;;
+               *)  echo "unknown option $1 " >> $scriptlog 2>&1
+                   usage  >> $scriptlog 2>&1
+                   exit
+                   ;;
+   esac
+   shift
+done
+
+if [ ${#general[@]} -eq 0 ] && [ ${#individual[@]} -eq 0 ]
+then
+   all=( ${names[@]} )
+else
+   all=( ${general[@]} ${individual[@]} ) 
+fi
+
+echo "For the following plots will be produced: "${all[@]} >> $scriptlog 2>&1
+
+# using hour for lock => after 24 no new script is 
+#  started in case the previous is still running
+hour=`date +%H`
+lockfile=$lockpath/${program}-${hour}h.txt
+checklock  >> $scriptlog 2>&1
+
+# make sure that ./showplot is executed from the right directory
+cd $mars 
+
+count=0
+# loop over all scripts in $names
+while [ 1 -gt 0 ]
+do
+   check="ok"
+   # get needed variables from the arrays
+   name=${names[$count]}
+   macro=${macros[$count]}
+   pathname=${pathnames[$count]}
+   filename=${filenames[$count]}
+   column=${columns[$count]}
+   digit=${digits[$count]}
+   
+   count=`expr $count + 1`
+   if [ $count -gt ${#names[@]} ]
+   then
+      count=0
+      continue
+   fi
+   # find out if these plots have to be created
+   #  by looping over the complete array $all and comparing the entries to those of the array $names
+   for (( a=0 ; a <= ${#all[@]} ; a++ ))
+   do 
+      # exit the loop if the entries agree
+      #  i.e. produce plots for this entry
+      if [ "${all[$a]}" = "$name" ]
+      then
+         break
+      fi
+      # continue if the end of array is not yet reached
+      if [ $a -lt ${#all[@]} ]
+      then
+         continue
+      fi
+      # exit both loops if no entry in the array is left
+      #  i.e. there is nothing to do anymore
+      if [ ${#all[@]} -eq 0 ]
+      then
+         break 2
+      fi
+      # continue with the next entry in the array $names
+      #  in case the end of the array $all is reached without agreement
+      continue 2
+   done
+
+   # do things specific to 'general' and 'individual'
+   if [ "$macro" = "no" ]
+   then 
+      # 'individual'
+      # remove name from list in case there is nothing left to do
+      getstatus >> $scriptlog 2>&1
+      if [ "$numproc" = "0" ]
+      then 
+         unset all[$a]
+         all=( ${all[@]} )
+         continue
+      fi
+      # get one sequence or dataset from the database for which plots have to be produced
+      gettodo "1" >> $scriptlog 2>&1
+      num=${primaries[0]}
+      echo "executing $name for number "$num  >> $scriptlog 2>&1
+      # lock the process
+      lockfile=$lockpath/$program-$name-$num.txt
+      checklock continue  >> $scriptlog 2>&1
+      setstatus "start" >> $scriptlog 2>&1
+      # set needed file and path names
+      pathpart=$pathname/`printf %08d $num | cut -c 0-${digit}`/`printf %08d $num`
+      inpath=$datapath/$pathpart
+      outpath=$webpath/$pathpart
+      tmppath=/tmp/pstoimg$pathpart
+      rootfile=$inpath/$filename`printf %08d $num`.root
+      psfile=$inpath/$filename`printf %08d $num`.ps
+      csvfile=$outpath/$filename.csv
+      pdffile=$outpath/$filename`printf %08d $num`.pdf
+      # rsync
+      makedir $outpath >> $scriptlog 2>&1
+      rsync -aLv --exclude=20[01][0-9]*_[YI]_*[.]root $inpath/ $outpath >> $scriptlog 2>&1
+
+      # for ganymed not only the ganymed*.root is processed but also a plotdb.root for the 
+      #  dataset. therefore the macro plotdb.C has to be run in this case
+      if [ "$name" = "gplotdb" ]
+      then
+         # overwrite needed file and path names
+         rootfile=$inpath/$filename.root
+         psfile=$inpath/$filename.ps
+         csvfile=$outpath/$filename.csv
+         pdffile=$outpath/$filename.pdf
+         datasetfile=$datasetpath/`printf %08d $num | cut -c 0-${digit}`/dataset`printf %08d $num`.txt
+         
+         echo "check1=root -q -b $macrospath/plotdb.C+\(\"$datasetfile\"\,\"$inpath/\"\) 2>|/dev/null | tee -a $scriptlog | intgrep" >> $scriptlog 2>&1
+         check1=`root -q -b $macrospath/plotdb.C+\("\"$datasetfile\""\,"\"$inpath/\""\) 2>|/dev/null | tee -a $scriptlog | intgrep`
+         case $check1 in 
+            1)   echo " check1=$check1 -> everything ok" >> $scriptlog 2>&1
+                 printprocesslog "INFO rootfile $rootfile successfully produced"
+                 ;;
+            *)   echo " check1=$check1 -> ERROR -> couldn't create plots -> exit" >> $scriptlog 2>&1
+                 printprocesslog "ERROR producing rootfile $rootfile failed"
+                 com=$Fdowebplots
+                 check=$check1
+                 ;;
+         esac
+      fi
+   else
+      # 'general'
+      echo "executing $name "  >> $scriptlog 2>&1
+      # remove 'general' from list as they need to be executed only once
+      unset all[$a]
+      all=( ${all[@]} )
+      # lock process
+      lockfile=$lockpath/$program-$name.txt
+      checklock continue >> $scriptlog 2>&1
+      # set needed file and path names
+      outpath=$webpath/$pathname
+      tmppath=/tmp/$pathname
+      rootfile=$outpath/$filename.root
+      psfile=$outpath/$filename.ps
+      csvfile=$outpath/$filename.csv
+      pdffile=$outpath/$filename.pdf
+      txtfile=$outpath/$filename.txt
+      
+      echo "check2=root -q -b $macrospath/$macro.C+\(\"$outpath/\"\) 2>| $txtfile | tee -a $scriptlog | intgrep" >> $scriptlog 2>&1
+      check2=`root -q -b $macrospath/$macro.C+\("\"$outpath/\""\) 2>| $txtfile | tee -a $scriptlog | intgrep`
+      case $check2 in 
+         1)   echo " check2=$check2 -> everything ok" >> $scriptlog 2>&1
+              printprocesslog "INFO rootfile $rootfile successfully produced"
+              ;;
+         *)   echo " check2=$check2 -> ERROR -> couldn't produce root file $rootfile  -> exit" >> $scriptlog 2>&1
+              printprocesslog "ERROR producing rootfile $rootfile failed"
+              com=$Fdowebplots
+              check=$check2
+              ;;
+      esac
+   fi
+   
+   # in case no error occured, the plots are produced from the rootfile
+   if [ "$check" = "ok" ]
+   then
+      printprocesslog "INFO producing plots (psfile and png) for $rootfile"
+      if ! ls $rootfile >/dev/null 2>&1
+      then
+         echo "rootfile $rootfile does not exist" >> $scriptlog 2>&1
+         printprocesslog "ERROR rootfile $rootfile does not exist"
+         com=$Fdowebplots
+         check=3
+      else
+         echo "producing psfile and csvfile..." >> $scriptlog 2>&1
+         if ! ./showplot -b --save-as-ps=$psfile --save-as-csv=$csvfile $rootfile >> $scriptlog 2>&1
+         then
+            com=$Fdowebplots
+            check=4
+         else
+            echo "creating temporary directory for pstoimg..." >> $scriptlog 2>&1
+            makedir $tmppath >> $scriptlog 2>&1
+            
+            echo "converting plots to png..." >> $scriptlog 2>&1
+            if ! pstoimg -antialias -aaliastext -interlaced -flip r270 -density 100 -tmp $tmppath -out=$outpath/$name -type png -multipage $psfile >> $scriptlog 2>&1
+            then 
+               printprocesslog "WARN could not create png files for $psfile "
+               com=$Fdowebplots
+               check=5
+            fi
+            
+            echo "removing temporary directory..." >> $scriptlog 2>&1
+            rmdir -pv $tmppath >> $scriptlog 2>&1
+            
+            echo "converting $psfile to pdf..." >> $scriptlog 2>&1
+         fi
+         
+         if ps2pdf $psfile $pdffile >> $scriptlog 2>&1
+         then 
+            rm -v $psfile  >> $scriptlog 2>&1
+         else
+            printprocesslog "WARN could not convert $psfile to $pdffile"
+            com=$Fdowebplots
+            check=6
+         fi
+      fi
+   fi
+   
+   setstatus "stop" >> $scriptlog 2>&1
+   
+   rm -v $lockfile >> $scriptlog 2>&1
+
+   sleep 2
+done
+
+# rsync subsystemdata, sequence and dataset files
+echo "do rsync for subsystem files" >> $scriptlog 2>&1
+rsync -av --delete $subsystempath/ $webpath/subsystemdata >> $scriptlog 2>&1
+
+echo "do rsync for sequence files" >> $scriptlog 2>&1
+rsync -av --delete $sequpath/ $webpath/sequences >> $scriptlog 2>&1
+
+echo "do rsync for dataset files" >> $scriptlog 2>&1
+rsync -av --delete $datasetpath/ $webpath/datasets >> $scriptlog 2>&1
+
+
+lockfile=$lockpath/${program}-${hour}h.txt
+finish >> $scriptlog 2>&1
+
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/dunotseqruns
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/dunotseqruns	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/dunotseqruns	(revision 17960)
@@ -0,0 +1,23 @@
+#!/bin/sh
+#
+
+query="select concat('/magic/data/rawfiles', Date_Format(adddate(fRunStart, interval 12 HOUR), '/%Y/%m/%d/'),'*', fRunNumber, '*.raw.gz')  from RunData where fSequenceFirst='0' and fRunStart > '2004-08-20'"
+
+files=`mysql -u MAGIC --host=vela --password=d99swMT! MyMagic -s -e " $query"`
+
+sum=0
+
+for file in $files
+do 
+   name=`basename $file`
+   dir=`dirname $file`
+   num=`find $dir -name $name -printf '%k '`
+   if [ "$num" = "" ]
+   then
+      echo "num is empty for $file"
+      continue
+   fi
+   sum=`expr $sum + $num`
+done
+echo $sum
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/filesondisk
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/filesondisk	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/filesondisk	(revision 17960)
@@ -0,0 +1,159 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script checks which files are on disk and updates the database 
+# accordingly. It is not yet running automatically. 
+# 
+# It is checking the:
+# - ccfiles
+# - cacofiles 
+#   this includes also the search for missing cacofiles:
+#   Sometimes the DAQ aborts a run and starts itself a new one. In this 
+#   cases the camera control doesn't start a new file, as the command to 
+#   start a new run was not sent by the central control. So the caco 
+#   information is stored in the previous caco file, which has a 
+#   different runnumber. To be able to merpp the information into the 
+#   calibrated data file, the runnumber of the file containing the 
+#   information has to be found.
+#   In this script the search and inserting into the database is done 
+#   using the macro findcacofiles.C 
+# - rawfiles
+# The update in the database is done using the macro resetallruns.C
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=filesondisk
+
+
+set -C
+
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+filesondisklogpath=$logpath/$program/`date +%Y/%m`
+makedir $filesondisklogpath >> $scriptlog 2>&1
+
+cd $mars
+
+
+# ---------------- check disk for cc-files --------------------
+
+echo "checking disk for ccfiles..."  >> $scriptlog 2>&1
+printprocesslog "INFO checking ccfiles"
+filename=$filesondisklogpath/ccfilesondisk-$datetime.txt
+find $subsystempath/cc/ -regextype posix-egrep -regex "^$subsystempath/cc/20[01][0-9]/[01][0-9]/[0-3][0-9]/20[01][0-9][01][0-9][0-3][0-9]_(M[0-9]_)?[0-9]{5,8}(\.[0-9]{3,5})?_[PCDSN]_.*.rep$" | grep -E -o "(_M[0-9])?_[0-9]{5,8}(\.[0-9]{3,5})?_" > $filename
+
+echo "resetting runs..." >> $scriptlog 2>&1
+check3=`root -q -b $macrospath/resetallruns.C+\("\"$filename\""\,"\"fCCFileAvail\"",kFALSE\) | tee -a $scriptlog | intgrep`
+
+case $check3 in 
+   1)   echo " check3=$check3 -> everything ok -> reset is done" >> $scriptlog 2>&1 
+        printprocesslog "INFO ccfiles resetted successfully"
+        ;;
+   0)   echo " check1=$check1 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+        printprocesslog "WARN connection to DB failed"
+        ;;
+   *)   echo " check3=$check3 -> ERROR -> something went wrong while resetting" >> $scriptlog 2>&1 
+        printprocesslog "ERROR resettallruns.C failed for ccfiles"
+        ;;
+esac
+
+
+# ---------------- check disk for caco-files --------------------
+
+echo "checking disk for cacofiles..."  >> $scriptlog 2>&1 
+printprocesslog "INFO checking cacofiles"
+filename=$filesondisklogpath/cacofilesondisk-$datetime.txt
+
+find $subsystempath/caco/ -regextype posix-egrep -regex "^$subsystempath/caco/20[01][0-9]/[01][0-9]/[0-3][0-9]/dc_20[01][0-9]_[01][0-9]_[0-3][0-9]_[012][0-9]_[0-5][0-9]_[0-5][0-9]_[0-9]{5,8}_.*\.txt$" | grep -E -o "(_M[0-9])?_[0-9]{5,8}(\.[0-9]{3,5})?_" > $filename
+
+echo "resetting runs..." >> $scriptlog 2>&1 
+check0=`root -q -b $macrospath/resetallruns.C+\("\"$filename\""\,"\"fCaCoFileAvail\"",kFALSE\) | tee -a $scriptlog | intgrep`
+
+case $check0 in 
+   1)   echo " check0=$check0 -> everything ok -> reset is done" >> $scriptlog 2>&1 
+        printprocesslog "INFO cacofiles resetted successfully"
+        ;;
+   0)   echo " check1=$check1 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+        printprocesslog "WARN connection to DB failed"
+        ;;
+   *)   echo " check0=$check0 -> ERROR -> something went wrong while resetting" >> $scriptlog 2>&1 
+        printprocesslog "ERROR resettallruns.C failed for cacofiles"
+        ;;
+esac
+
+
+# ---------------- find missing caco-files --------------------
+
+#echo "finding missing cacofiles..." >> $scriptlog 2>&1 
+#printprocesslog "INFO checking missing cacofiles"
+#check1=`root -q -b $macrospath/findcacofiles.C+ | tee -a $scriptlog | intgrep`
+#
+#case $check1 in 
+#   1)   echo " check1=$check1 -> everything ok -> missing cacofiles are found" >> $scriptlog 2>&1 
+#        printprocesslog "INFO missing cacofiles found"
+#        ;;
+#   0)   echo " check1=$check1 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+#        printprocesslog "WARN connection to DB failed"
+#        ;;
+#   *)   echo " check1=$check1 -> ERROR -> something went wrong while resetting" >> $scriptlog 2>&1
+#        printprocesslog "ERROR findcacofiles.C failed"
+#        ;;
+#esac
+
+
+# ---------------- check disk for rawfiles --------------------
+
+echo "checking disk for rawfiles..."  >> $scriptlog 2>&1 
+printprocesslog "INFO checking rawfiles"
+filename=$filesondisklogpath/rawfilesondisk-$datetime.txt
+
+find $datapath/rawfiles/20[01][0-9] -regextype posix-egrep -regex "^$datapath/rawfiles/20[01][0-9]/[01][0-9]/[0-3][0-9]/20[01][0-9][01][0-9][0-3][0-9]_(M[0-9]_)?[0-9]{5,8}(\.[0-9]{3,5})?_[PCDSN]_.*\.raw(\.gz)?$" | grep -E -o "(_M[0-9])?_[0-9]{5,8}(\.[0-9]{3,5})?_" > $filename
+
+echo "resetting runs..." >> $scriptlog 2>&1 
+check4=`root -q -b $macrospath/resetallruns.C+\("\"$filename\""\,"\"fRawFileAvail\"",kFALSE\) | tee -a $scriptlog | intgrep`
+
+case $check4 in 
+   1)   echo " check4=$check4 -> everything ok -> reset is done" >> $scriptlog 2>&1 
+        printprocesslog "INFO rawfiles resetted successfully"
+        ;;
+   0)   echo " check1=$check1 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+        printprocesslog "WARN connection to DB failed"
+        ;;
+   *)   echo " check4=$check4 -> ERROR -> something went wrong while resetting" >> $scriptlog 2>&1 
+        printprocesslog "ERROR resettallruns.C failed for rawfiles"
+        ;;
+esac
+
+
+
+finish >> $scriptlog 2>&1
Index: branches/Mars_McMismatchStudy/datacenter/scripts/fillcallisto
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/fillcallisto	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/fillcallisto	(revision 17960)
@@ -0,0 +1,108 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the filling of the results from the calibration for 
+# all sequences of which the results are not yet in the database.
+#
+# After checking if the script is already running the todolist is written.
+# Then for each sequence in the todo list the calibration results are 
+# filled into the table Calibration in the database using the macros 
+# fillcalib.C and fillsignal.C 
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=fillcallisto
+column=fFillCallisto
+
+set -C
+
+# check if the script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo file
+gettodo 
+
+cd $mars
+
+# fill information into the database for all sequences in the todo file
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s+$s]}
+   telnum=${primaries[$s+$s+1]}
+   printprocesslog "INFO starting $program for sequence $sequence"
+   no=`printf %08d $sequence | cut -c 0-4`
+   no2=`printf %08d $sequence`
+   path="$datapath/callisto/$no/$no2"
+   signalfile=$path/signal$no2.root
+   calibfile=$path/calib$no2.root
+   fillcallistologpath=$logpath/$program/$no
+   makedir $fillcallistologpath 
+   fillcaliblog=$fillcallistologpath/fillcalib-$sequence.log
+   fillsignallog=$fillcallistologpath/fillsignal-$sequence.log
+
+   printprocesslog "INFO run $program for sequence $sequence" 
+   setstatus "start" 
+   printprocesslog "INFO starting fillcalib for sequence $sequence"
+
+   check1=`root -q -b $macrospath/fillcalib.C+\("\"$calibfile\""\,kFALSE\) | tee $fillcaliblog | intgrep`
+
+   case $check1 in
+      1)   printprocesslog "INFO done fillcalib successfully for sequence $sequence (check1=$check1)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check1=$check1)"
+           check="no"
+           setstatus "stop" 
+           continue ;;
+      *)   printprocesslog "ERROR fillcalib failed for sequence $sequence (check1=$check1)"
+           com=$Ffillcalib
+           check=$check1
+           setstatus "stop" 
+           continue ;;
+   esac
+
+   printprocesslog "INFO starting fillsignal for sequence $sequence"
+   check2=`root -q -b $macrospath/fillsignal.C+\("\"$signalfile\""\,kFALSE\) | tee $fillsignallog | intgrep`
+   case $check2 in
+      1)   printprocesslog "INFO done fillsignal successfully for sequence $sequence (check2=$check2)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check2=$check2)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR fillsignal failed for sequence $sequence (check2=$check2)"
+           com=$Ffillsignal
+           check=$check2
+           ;;
+   esac
+   
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/fillcamera
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/fillcamera	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/fillcamera	(revision 17960)
@@ -0,0 +1,203 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniel Hoehne-Moench  03/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This script launches the inserting of mc parameters into the db by 
+# starting fillcamera.C
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=fillcamera
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+getdbsetup
+
+#mccampath=$mcpath/camera
+mccampath=/magic/montecarlo/camera
+#workaround
+cameradirs=`find /magic/montecarlo/camera -maxdepth 4 -mindepth 2 -type d ! -name Gamma ! -name Muon ! -name Proton ! -name Spot_?.?`
+printprocesslog "INFO camera dirs: "${cameradirs[@]} 
+
+cd $mars
+
+# process directories
+for cameradir in ${cameradirs[@]}
+do
+   printprocesslog "INFO inserting information for all root camera files in $cameradir"
+   cam=`basename $cameradir`
+   spot=`echo $cameradir | cut -d/ -f7` #spotsize
+   par=`echo $cameradir | cut -d/ -f6` #particle name
+   if [ $cam = "Cal_and_Ped" ]
+   then
+      par=""
+      spot=""
+   fi
+   epo=`echo $cameradir | cut -d/ -f5` #epoch
+   printprocesslog "INFO dir: "$cameradir 
+   fillcamerapath=$logpath/$program
+   makedir $fillcamerapath 
+   fillcameralog=$fillcamerapath/$program-$epo-$par-$spot-$cam.log
+   
+   check0=`root -q -b $macrospath/fillcamera.C+\("\"$cameradir\""\,kFALSE\) | tee $fillcameralog | intgrep`
+#   check0=`root -q -b $macrospath/fillcamera.C+\("\"$cameradir\""\,kTRUE\) | tee $fillcameralog | intgrep`
+   case $check0 in 
+      1)   printprocesslog "INFO fillcamera run successfully for dir $cameradir (check0=$check0)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check0=$check0)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR $program.C failed for dir $cameradir (check0=$check0)"
+           ;;
+   esac
+   
+   printprocesslog "INFO linking cal and ped files"
+   
+   if [ $cam = "Cal_and_Ped" ];
+   then
+      printprocesslog "INFO Cal_and_Ped folder, no cal and ped files will be linked" 
+   else
+
+      epo=`echo $cameradir | cut -d/ -f5` #filename
+      #epo=`basename $cameradir` #filename
+      pedfile=`find $mccampath/$epo/Cal_and_Ped -name *_P_*.root`
+      calfile=`find $mccampath/$epo/Cal_and_Ped -name *_C_*.root`
+   
+      printprocesslog "INFO calfile for epoch $epo : " $calfile 
+      printprocesslog "INFO pedfile for epoch $epo : " $pedfile 
+   
+      #check number of files
+      numfiles=`echo $pedfile $calfile | wc -w`
+   
+      if [ "$numfiles" != "2" ]
+      then
+      	printprocesslog "ERROR too many or too less ped and cal files found in $epo/Cal_and_Ped"
+      	finish 
+      fi
+      
+      
+      cquery=" select fRunNumber from MCRunProcessStatus where fFileName=\"$calfile\" "
+      pquery=" select fRunNumber from MCRunProcessStatus where fFileName=\"$pedfile\" "
+      
+      crun=`mysql -ss -u $us --password=$pw --host=$ho $db -e " $cquery "`
+      prun=`mysql -ss -u $us --password=$pw --host=$ho $db -e " $pquery "`
+      cnum=`printf %08d $crun`
+      pnum=`printf %08d $prun`
+      printprocesslog "INFO calrun number: " $cnum 
+      printprocesslog "INFO pedrun number: " $pnum 
+      #get all directories in the linked structure for the epoch
+      #dirs=`find $mcrawpath/ -mindepth 3 -maxdepth 3 -type d`
+      files=`find $mcrawpath/ -lname *$epo*.root`
+   
+      for file in ${files[@]}
+      do 
+         dir=`dirname $file`
+         #datacenter
+         date=`echo $file | cut -c 28-31,33,34,36,37`
+         #for tests
+         #date=`echo $file | cut -c 57-60,62,63,65,66`
+         
+         newpedfile="${dir}/${date}_${pnum}_P_MonteCarlo_E.root"
+         newcalfile="${dir}/${date}_${cnum}_C_MonteCarlo_E.root"
+         pupdate=" update MCRunProcessStatus set fRunLinked=Now(), fLinkName=\"$newpedfile\" where fRunNumber=\"$prun\" "
+         cupdate=" update MCRunProcessStatus set fRunLinked=Now(), fLinkName=\"$newcalfile\" where fRunNumber=\"$crun\" "
+         if ls $dir | grep MonteCarlo | grep $pnum
+         then 
+            printprocesslog "INFO P run already there, do mysql update" 
+   #         continue
+            mysql -ss -u $us --password=$pw --host=$ho $db -e " $pupdate "
+         else 
+            printprocesslog "INFO linking P run for epoch $epo" 
+            ln -sv $pedfile $newpedfile 
+            mysql -ss -u $us --password=$pw --host=$ho $db -e " $pupdate "
+         fi
+         
+         if ls $dir | grep MonteCarlo | grep $cnum
+         then 
+            printprocesslog "INFO C run already there, do mysql update" 
+   #         continue
+            mysql -ss -u $us --password=$pw --host=$ho $db -e " $cupdate "
+         else 
+            printprocesslog "INFO linking C run for epoch $epo" 
+            ln -sv $calfile $newcalfile 
+            mysql -ss -u $us --password=$pw --host=$ho $db -e " $cupdate "
+         fi
+   
+      done
+   
+   fi
+
+done
+
+readme=$mcrawpath/README.txt #file in which the information about the properties of the files is redirected to have always an updated explanation
+
+# observation epochs 
+epochs=("" "After January 07 (MUX FADCs)," "From April 06 to January 07 (Siegen FADCs with splitters)," "Before April 06 (Siegen FADCs)")
+
+# print information and explanation of structure into README.txt 
+date >| $readme 2>&1
+echo "" >> $readme 2>&1
+echo "Explanation for the structure in which the mc files are linked" >> $readme 2>&1
+echo "--------------------------------------------------------------" >> $readme 2>&1
+echo "" >> $readme 2>&1
+echo "the files are linked in a YYYY/MM/DD structure like the data files" >> $readme 2>&1
+echo "YYYY represents 19zbin" >> $readme 2>&1
+echo "MM represents the epoch" >> $readme 2>&1
+echo "DD represents the additional spot size in mm" >> $readme 2>&1
+echo "" >> $readme 2>&1
+echo "explanation of the epochs" >> $readme 2>&1
+echo "epochs: "${epochs[@]} >> $readme 2>&1
+echo "" >> $readme 2>&1
+for (( i=1 ; i <= 3 ; i++ )) 
+do 
+   if [ "${epochs[i]}" != "" ]
+   then 
+      numofepoch=`printf %02d $i`
+      echo "epoch (MM) = $numofepoch means ${epochs[$i]}" >> $readme 2>&1
+   fi
+done
+echo "" >> $readme 2>&1
+echo "the epoch is indicating " >> $readme 2>&1
+echo " - the time for which the MCs are produced" >> $readme 2>&1
+echo "   the epoch is determined from the AmplFADCs value filled into the MC-DB" >> $readme 2>&1
+echo "" >> $readme 2>&1
+echo "----------------" >> $readme 2>&1
+echo "" >> $readme 2>&1
+echo "The names of the files characterize their properties. Structure:" >> $readme 2>&1
+echo "/magic/montecarlo/rawfiles/YYYY/MM/DD/YYYYMMDD_<RunNumber>_<P/C/D>_<Particle><Spectrum><ObservationMode>_E.root" >> $readme 2>&1
+echo "<P/C/D> indicates the run type" >> $readme 2>&1
+echo "<Particle>: Gamma, Proton, Muon, MonteCarlo (for P,C runs)" >> $readme 2>&1
+echo "<Spectrum>: 'empty' or HE, depending on the simulated MC spectrum" >> $readme 2>&1
+echo "<ObservationMode>: 'empty' (On), W1/W2 (Wobble), FW (Fake Wobble), Diff (Diffuse)" >> $readme 2>&1
+echo "" >> $readme 2>&1
+
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/fillganymed
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/fillganymed	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/fillganymed	(revision 17960)
@@ -0,0 +1,86 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the filling of the results of ganymed into the db 
+# for all datasets of which the results are not yet in the database.
+#
+# After checking if the script is already running the todolist is written. 
+# Then for each dataset in the todo list the ganymed results are filled 
+# into the table Ganymed in the database using the macro fillganymed.C
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=fillganymed
+column=fFillGanymed
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+# run fillganymed for datasets
+for (( s=0 ; s < $num ; s++ ))
+do
+   dataset=${primaries[$s]}
+   printprocesslog "INFO starting $program for dataset $dataset"
+   no=`printf %08d $dataset | cut -c 0-5`
+   no2=`printf %08d $dataset`
+   path="$datapath/ganymed/$no/$no2"
+   ganymedfile=$path/ganymed$no2.root
+   fillganymedlogpath=$logpath/$program/$no
+   makedir $fillganymedlogpath 
+   fillganymedlog=$fillganymedlogpath/$program-$dataset.log
+
+   printprocesslog "INFO run $program for dataset $dataset" 
+   setstatus "start" 
+
+   check2=`root -q -b $macrospath/fillganymed.C+\("\"$ganymedfile\""\,kFALSE\) | tee $fillganymedlog | intgrep`
+   case $check2 in
+      1)   printprocesslog "INFO done fillganymed successfully for dataset $dataset (check2=$check2)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check2=$check2)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR fillganymed failed for dataset $datset (check2=$check2)"
+           com=$Ffillganymed
+           check=$check2
+           ;;
+   esac
+
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/fillmccallisto
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/fillmccallisto	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/fillmccallisto	(revision 17960)
@@ -0,0 +1,118 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Daniel Hoehne-Moench  08/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This script launches the filling of the results from the calibration for 
+# all mc sequences of which the results are not yet in the database.
+#
+# After checking if the script is already running the todolist is written.
+# Then for each sequence in the todo list the calibration results are 
+# filled into the table MCCalibration in the database using the macros 
+# fillmccalib.C and fillmcsignal.C 
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=fillmccallisto
+column=fFillCallisto
+
+set -C
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if the script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+# get todo file
+gettodo  >> $scriptlog 2>&1
+
+cd $mars
+
+# fill information into the database for all sequences in the todo file
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s]}
+   printprocesslog "INFO starting $program for mc sequence $sequence"
+   no=`printf %08d $sequence | cut -c 0-4`
+   no2=`printf %08d $sequence`
+   path="$mcpath/callisto/$no/$no2"
+   signalfile=$path/signal$no2.root
+   calibfile=$path/calib$no2.root
+   fillcallistologpath=$logpath/$program/$no
+   makedir $fillcallistologpath >> $scriptlog 2>&1
+   fillcaliblog=$fillcallistologpath/fillcalib-$sequence.log
+   fillsignallog=$fillcallistologpath/fillsignal-$sequence.log
+
+   echo "run $program for mc sequence $sequence" >> $scriptlog 2>&1
+   setstatus "start" >> $scriptlog 2>&1
+   echo "run fillmccalib..." >> $scriptlog 2>&1
+   printprocesslog "INFO starting fillmccalib for mc sequence $sequence"
+
+   check1=`root -q -b $macrospath/fillmccalib.C+\("\"$calibfile\""\,kFALSE\) | tee $fillcaliblog | intgrep`
+
+   case $check1 in
+      1)   echo " check1=$check1 -> everything ok -> run fillmcsignal " >> $scriptlog 2>&1 
+           printprocesslog "INFO done fillmccalib successfully for mc sequence $sequence"
+           ;;
+      0)   echo " check1=$check1 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+           printprocesslog "WARN connection to DB failed"
+           check="no"
+           setstatus "stop" >> $scriptlog 2>&1
+           continue ;;
+      *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+           printprocesslog "ERROR fillmccalib failed for mc sequence $sequence"
+           com=$Ffillmccalib
+           check=$check1
+           setstatus "stop" >> $scriptlog 2>&1
+           continue ;;
+   esac
+
+   printprocesslog "INFO starting fillmcsignal for sequence $sequence"
+   check2=`root -q -b $macrospath/fillmcsignal.C+\("\"$signalfile\""\,kFALSE\) | tee $fillsignallog | intgrep`
+   case $check2 in
+      1)   echo " check2=$check2 -> everything ok " >> $scriptlog 2>&1 
+           printprocesslog "INFO done fillmcsignal successfully for mc sequence $sequence"
+           ;;
+      0)   echo " check2=$check2 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+           printprocesslog "WARN connection to DB failed"
+           check="no"
+           ;;
+      *)   echo " check2=$check2 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+           printprocesslog "ERROR fillmcsignal failed for mc sequence $sequence"
+           com=$Ffillmcsignal
+           check=$check2
+           ;;
+   esac
+   
+   setstatus "stop" >> $scriptlog 2>&1
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/fillmcdb
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/fillmcdb	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/fillmcdb	(revision 17960)
@@ -0,0 +1,91 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  04/2009 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# script to insert new runs into mc database
+#
+
+
+#
+# to be given by user
+#
+
+# number of runs to be inserted
+#numruns=300
+numruns=2700
+# number of events per run
+numevts=200000
+# particle type: 
+#   1 = gamma
+#  14 = proton
+#   6 = muon
+#particlekey=1
+particlekey=14
+
+obslevel=3700
+
+#
+# infos concerning DB:
+# table names: MCRunData, MCRunProcessStatus
+#     primary: fMCRunNumber
+#
+# currently working for CTA_MC
+#
+
+
+
+# begin of script
+
+source `dirname $0 `/sourcefile
+
+query="SELECT Max(fMCRunNumber)+1, Max(fMCRunNumber)+"$numruns" FROM MCRunData"
+echo $query
+# get next runnumber from db
+runs=( `sendquery "$query"` )
+if [ "${runs[0]}" == "NULL" ]
+then
+   runs[0]=1
+   runs[1]=$numruns
+fi
+
+
+echo "Inserting "$numruns" runs with "$numevts" events each and particle number "$particlekey" and observation level "$obslevel" m."
+echo "Next runs in DB from run number "${runs[0]}" to run number "${runs[1]}"."
+if [ "$1" == "-n" ]
+then 
+   echo "Dummy-Mode => exit"
+   exit
+fi
+
+for i in `seq ${runs[0]} ${runs[1]}` 
+do 
+   query="INSERT MCRunData SET fNumEvents=$numevts, fParticleTypeKEY=$particlekey, fObsLevel=$obslevel, fMCRunNumber=$i"
+   echo $query
+   sendquery "$query"
+   query="INSERT MCRunProcessStatus SET fMCRunNumber=$i, fPriority=$i"
+   echo $query
+   sendquery "$query"
+done
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/fillmcstar
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/fillmcstar	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/fillmcstar	(revision 17960)
@@ -0,0 +1,93 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Daniel Hoehne-Moench  01/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This script launches the filling of the results of star into the db 
+# for all mc sequences of which the results are not yet in the database.
+#
+# After checking if the script is already running the todolist is written. 
+# Then for each sequence in the todo list the star results are filled 
+# into the table Star in the database using the macro fillmcstar.C
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=fillmcstar
+column=fFillStar
+
+set -C
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if the script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+# get todo list
+gettodo  >> $scriptlog 2>&1
+
+cd $mars
+
+# run fillstar for sequences
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s]}
+   printprocesslog "INFO starting $program for mc sequence $sequence"
+   no=`printf %08d $sequence | cut -c 0-4`
+   no2=`printf %08d $sequence`
+   path="$mcpath/star/$no/$no2"
+   starfile=$path/star$no2.root
+   fillstarlogpath=$logpath/$program/$no
+   makedir $fillstarlogpath >> $scriptlog 2>&1
+   fillstarlog=$fillstarlogpath/$program-$sequence.log
+
+   echo "run $program for mc sequence $sequence" >> $scriptlog 2>&1
+   setstatus "start" >> $scriptlog 2>&1
+
+   check2=`root -q -b $macrospath/fillmcstar.C+\("\"$starfile\""\,kFALSE\) | tee $fillstarlog | intgrep`
+   case $check2 in
+      1)   echo " check2=$check2 -> everything ok " >> $scriptlog 2>&1 
+           printprocesslog "INFO done fillmcstar successfully for mc sequence $sequence"
+           ;;
+      0)   echo " check2=$check2 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+           printprocesslog "WARN connection to DB failed"
+           check="no"
+           ;;
+      *)   echo " check2=$check2 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+           printprocesslog "ERROR fillmcstar failed for mc sequence $sequence"
+           com=$Ffillmcstar
+           check=$check2
+           ;;
+   esac
+   
+   setstatus "stop" >> $scriptlog 2>&1
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/fillstar
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/fillstar	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/fillstar	(revision 17960)
@@ -0,0 +1,86 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the filling of the results of star into the db 
+# for all sequences of which the results are not yet in the database.
+#
+# After checking if the script is already running the todolist is written. 
+# Then for each sequence in the todo list the star results are filled 
+# into the table Star in the database using the macro fillstar.C
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=fillstar
+column=fFillStar
+
+set -C
+
+# check if the script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+# run fillstar for sequences
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s+$s]}
+   telnum=${primaries[$s+$s+1]}
+   printprocesslog "INFO starting $program for sequence $sequence"
+   no=`printf %08d $sequence | cut -c 0-4`
+   no2=`printf %08d $sequence`
+   path="$datapath/star/$no/$no2"
+   starfile=$path/star$no2.root
+   fillstarlogpath=$logpath/$program/$no
+   makedir $fillstarlogpath 
+   fillstarlog=$fillstarlogpath/$program-$sequence.log
+
+   setstatus "start" 
+
+   check2=`root -q -b $macrospath/fillstar.C+\("\"$starfile\""\,kFALSE\) | tee $fillstarlog | intgrep`
+   case $check2 in
+      1)   printprocesslog "INFO done fillstar successfully for sequence $sequence (check2=$check2)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check2=$check2)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR fillstar failed for sequence $sequence (check2=$check2)"
+           com=$Ffillstar
+           check=$check2
+           ;;
+   esac
+   
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/findnewstars
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/findnewstars	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/findnewstars	(revision 17960)
@@ -0,0 +1,122 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  10/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script checks from the DB which new starfiles have been produced 
+# and sends it to the person in charge for building datasets
+#
+
+#source `dirname $0`/sourcefile
+#printprocesslog "INFO starting $0"
+function usage()
+{
+   echo "Usage: $0 [options]"
+   echo "options:"
+   echo -n "  --sequ sequence#       "
+   echo -n " giving number of the sequence starting from which "
+   echo " sequences with star done are returned "
+   echo -n "  --date                 "
+   echo -n " giving date starting from which sequences with star "
+   echo "done are returned"
+   echo ""
+   exit
+}
+
+
+while [ "$1" ]
+do 
+   case $1 in 
+      --sequ)  shift
+               seq=$1
+               echo "Only sequences starting from sequence # $seq are considered"
+               ;;
+      --date)  shift
+               date=$1
+               echo "Only star starting from date $date is considered"
+               ;;
+          -h)  usage
+               ;;
+           *)  echo "unknown option $1 "
+               usage
+               exit
+               ;;
+   esac
+   shift
+done
+
+alias mymysql='mysql -u MAGIC --password=d99swMT! --host=vela MyMagic -s -e'
+
+query="SELECT fSequenceFirst FROM SequenceProcessStatus WHERE NOT ISNULL(fStar) "
+cond=""
+if ! [ "$seq" = "" ]
+then 
+   cond=$cond" AND SequenceProcessStatus.fSequenceFirst > $seq " 
+fi
+if ! [ "$date" = "" ]
+then
+   cond=$cond" AND fStar > '$date'"
+fi 
+query=$query$cond
+
+sequences=`mymysql " $query "`
+if [ "$sequences" = "" ]
+then 
+   echo "no sequences with new star files found "
+   exit
+fi 
+sequences2=`echo $sequences | sed -e 's/ /,/g'`
+query="SELECT fSourceKEY FROM Sequences WHERE fSequenceFirst IN ($sequences2) GROUP BY fSourceKEY"
+sources=`mymysql " $query "`
+sources2=`echo $sources | sed -e 's/ /,/g'`
+query="SELECT fSourceName FROM Source WHERE fSourceKEY IN ($sources2)"
+sourcenames=`mymysql " $query "`
+#echo "for the following sources new starfiles have been produced: $sourcenames"
+#echo ""
+for sourcename in $sourcenames
+do 
+   query="SELECT Sequences.fSequenceFirst FROM Sequences "
+   query=$query" LEFT JOIN Source ON Source.fSourceKEY=Sequences.fSourceKEY "
+   query=$query" LEFT JOIN SequenceProcessStatus ON SequenceProcessStatus.fSequenceFirst=Sequences.fSequenceFirst "
+   query=$query"WHERE fSourceName='$sourcename'"
+   query=$query$cond
+   seqspersource=`mymysql " $query "`
+   seqs=`echo $seqspersource | sed -e 's/ /,/g'`
+   printf "star done for %12s the following new sequences: %s \n" $sourcename $seqs
+done
+
+for sourcename in $sourcenames
+do 
+   echo "searching datasets for $sourcename"
+   if ! grep $sourcename /magic/test/bu.2006.10.10/datasets/*/*.txt 2>/dev/null
+   then
+      echo "sorry, no dataset found for $sourcename, please create a new dataset"
+   fi
+done
+
+
+#nail -s 'found warnings in '$oldprocesslog $erradrs
+
+#printprocesslog "INFO finished $0"
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/findnotseqruns
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/findnotseqruns	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/findnotseqruns	(revision 17960)
@@ -0,0 +1,219 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  10/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script checks from the DB which new starfiles have been produced 
+# and sends it to the person in charge for building datasets
+#
+
+#source `dirname $0`/sourcefile
+#printprocesslog "INFO starting $0"
+function usage()
+{
+   echo "Usage: $0 [options]"
+   echo "options:"
+   echo -n "  -a               "
+   echo " all runs are considered  "
+   echo -n "  -c               "
+   echo " only calibration runs are considered  "
+   echo -n "  -d               "
+   echo " only data runs are considered  "
+   echo -n "  -p               "
+   echo " only pedestal runs are considered  "
+   echo -n "  --notexcl        "
+   echo " only not excluded runs are considered  "
+   echo -n "  --printruns      "
+   echo " print all runs "
+   echo -n "  --run run#       "
+   echo " runs > run# are considered  "
+   echo -n "  --runmin run#    "
+   echo " runs > run# are considered (use together with --runmax)"
+   echo -n "  --runmax run#    "
+   echo " runs < run# are considered (use together with --runmin)"
+   echo -n "  --source source  "
+   echo " only runs of which the sourcename contains 'source' are considered"
+   echo ""
+   exit
+}
+
+
+while [ "$1" ]
+do 
+   case $1 in 
+         --run)  shift
+                 run=$1
+                 echo "Only runs starting from run # $run are considered"
+                 ;;
+      --runmin)  shift
+                 runmin=$1
+                 echo "Only runs with run # > $runmin are considered"
+                 ;;
+      --runmax)  shift
+                 runmax=$1
+                 echo "Only runs with run # < $runmax are considered"
+                 ;;
+      --source)  shift
+                 source=$1
+                 echo "Only runs of which the sourcename contains $source are considered"
+                 ;;
+     --notexcl)  notexcl="yes"
+                 echo "Only not excluded runs are considered"
+                 ;;
+   --printruns)  printruns="yes"
+                 ;;
+            -a)  all="yes"
+                 echo "All runs are considered"
+                 ;;
+            -c)  cal="yes"
+                 echo "Only calibration runs are considered"
+                 ;;
+            -d)  dat="yes"
+                 echo "Only data runs are considered"
+                 ;;
+            -p)  ped="yes"
+                 echo "Only ped runs are considered"
+                 ;;
+            -h)  usage
+                 ;;
+             *)  echo "unknown option $1 "
+                 usage
+                 exit
+                 ;;
+   esac
+   shift
+done
+
+alias mymysql='mysql -u MAGIC --password=d99swMT! --host=vela MyMagic -s -e'
+
+if [ "$dat" = "" ] && [ "$cal" = "" ] && [ "$ped" = "" ] && ! [ "$all" = "yes" ]
+then
+   echo "You have to select at least one of the options -a -c -d -p "
+   usage
+fi
+
+if [ "$all" = "yes" ]
+then
+   cal=
+   dat=
+   ped=
+fi
+
+query="SELECT fRunNumber FROM RunData "
+if ! [ "$source" = "" ]
+then
+   query=$query" LEFT JOIN Source ON Source.fSourceKEY=RunData.fSourceKEY "
+fi
+query=$query" WHERE fSequenceFirst='0' "
+
+cond=""
+if ! [ "$source" = "" ]
+then
+   subquery="SELECT fSourceKEY FROM Source WHERE fSourceName LIKE '%$source%'"
+   sourcekeys=`mymysql "$subquery"`
+   if [ "$sourcekeys" = "" ]
+   then
+      echo "No source found containing $source"
+      exit
+   fi
+   sourcekeys2=`echo $sourcekeys | sed -e 's/ /,/g'`
+   cond=$cond" AND Source.fSourceKEY IN ($sourcekeys2)"
+fi
+if ! [ "$run" = "" ]
+then 
+   cond=$cond" AND RunData.fRunNumber > $run " 
+fi
+if ! [ "$runmin" = "" ] && ! [ "$runmax" = "" ]
+then 
+   cond=$cond" AND RunData.fRunNumber BETWEEN $runmin AND $runmax " 
+fi
+if [ "$cal" = "yes" ] &&  [ "$dat" = "yes" ]
+then 
+   cond=$cond" AND (fRunTypeKEY=4 OR fRunTypeKEY=2) "
+fi
+if [ "$cal" = "yes" ] &&  [ "$ped" = "yes" ]
+then 
+   cond=$cond" AND (fRunTypeKEY=4 OR fRunTypeKEY=3) "
+fi
+if [ "$dat" = "yes" ] && [ "$ped" = "yes" ]
+then 
+   cond=$cond" AND (fRunTypeKEY=2 OR fRunTypeKEY=3)"
+fi
+if [ "$cal" = "yes" ]
+then 
+   cond=$cond" AND fRunTypeKEY=4 "
+fi
+if [ "$dat" = "yes" ]
+then 
+   cond=$cond" AND fRunTypeKEY=2 "
+fi
+if [ "$ped" = "yes" ]
+then 
+   cond=$cond" AND fRunTypeKEY=3 "
+fi
+if [ "$notexcl" = "yes" ]
+then 
+   cond=$cond" AND fExcludedFDAKEY=1 "
+fi
+query=$query$cond
+
+runs=(`mymysql " $query "`)
+echo "found ${#runs[@]} not sequenced runs "
+if [ ${#runs[@]} -eq 0 ]
+then 
+   exit
+fi 
+if [ ${#runs[@]} -gt 1000 ]
+then 
+   echo "> 1000 runs found, please restrict the range with the options --runmin and --runmax " 
+   exit
+fi 
+runs2=`echo ${runs[@]} | sed -e 's/ /,/g'`
+query="SELECT fSourceKEY FROM RunData WHERE fRunNumber IN ($runs2) GROUP BY fSourceKEY"
+sources=`mymysql " $query "`
+sources2=`echo $sources | sed -e 's/ /,/g'`
+query="SELECT fSourceName FROM Source WHERE fSourceKEY IN ($sources2)"
+sourcenames=`mymysql " $query "`
+
+for sourcename in $sourcenames
+do 
+   query="SELECT fRunNumber FROM RunData "
+   query=$query" LEFT JOIN Source ON Source.fSourceKEY=RunData.fSourceKEY "
+   query=$query"WHERE fSourceName='$sourcename' AND fSequenceFirst='0' "
+   query=$query$cond
+   runspersource=(`mymysql " $query "`)
+   if [ "$printruns" = "yes" ]
+   then 
+      runsps=`echo ${runspersource[@]} | sed -e 's/ /,/g'`
+      printf "for %12s the following runs are not sequenced: %s \n" $sourcename $runsps
+   else
+      printf "for %12s the %04d runs are not sequenced \n" $sourcename ${#runspersource[@]}
+   fi
+      
+done
+
+#nail -s 'found warnings in '$oldprocesslog $erradrs
+
+#printprocesslog "INFO finished $0"
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/insertdatasets
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/insertdatasets	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/insertdatasets	(revision 17960)
@@ -0,0 +1,102 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the inserting of the datasets into the db.
+#
+# Extract information (dataset number, source name, comment, observation 
+# mode) from dataset file and insert it into the database in the table 
+# DataSets using the macro insertdataset.C
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=insertdatasets
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get all datasetfiles
+datasetfiles=(`ls $datasetpath/*/*.txt`)
+printprocesslog "INFO datasetfiles: "${datasetfiles[@]} 
+
+cd $mars
+
+# extract information from dataset file and insert it into db with the macro insertdataset.C
+printprocesslog "INFO inserting dataset information into db"
+for datasetfile in ${datasetfiles[@]}
+do 
+   # get datasetnumber from filename
+   no=`echo $datasetfile | cut -d/ -f5 | cut -c8-99 | cut -d. -f1`
+   # get datasetnumber from file and get it with 8 digits
+   no2=`grep 'AnalysisNumber:' $datasetfile | sed -e 's/AnalysisNumber://g' | sed -e 's/ //g'`
+   no3=`printf %08d $no2`
+   no4=`printf %08d $no2 | cut -c 1-5`
+   # compare the two datasetnumber 
+   # continue only if number is the same
+   if [ "$no" = "$no3" ]
+   then 
+      printprocesslog "INFO number in filename and in file are the same -> continue" 
+   else
+      printprocesslog "ERROR number in filename ($no) and file ($no3) are not the same for dataset $no2"
+      continue
+   fi
+   # get source name, comment and observation mode from dataset file
+   source=`grep 'SourceName:' $datasetfile | sed -e 's/SourceName://g' | sed -e 's/ //g' | sed -e 's/#//g'` 
+   comment=`grep 'Comment:' $datasetfile | sed -e 's/Comment://g'` 
+   mode=`grep 'WobbleMode:' $datasetfile` 
+   mode2=`echo $mode | grep ^\#` 
+   if [ "$mode2" = "" ]
+   then 
+      wobble="Y" 
+   else
+      wobble="N" 
+   fi
+   
+   insertdatasetpath=$logpath/insertdataset/$no4
+   makedir $insertdatasetpath 
+   insertdatasetlog=$insertdatasetpath/insertdataset-$no3.log
+
+   printprocesslog "INFO inserting dataset $no2"
+   # insert information into db
+   check0=`root -q -b $macrospath/insertdataset.C+\("\"$no2\""\,"\"$source\""\,"\"$wobble\""\,"\"$comment\""\,kFALSE\) | tee $insertdatasetlog | intgrep`
+   case $check0 in 
+      1)   printprocesslog "INFO dataset $no2 successfully inserted (check0=$check0)"
+           ;;
+      3)   printprocesslog "INFO dataset $no2 exists already (check0=$check0)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check0=$check0)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR $program.C failed for dataset $no2 (check0=$check0)"
+           ;;
+   esac
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/insertmc
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/insertmc	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/insertmc	(revision 17960)
@@ -0,0 +1,319 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# script used to insert MC to the DB TestFACTSetup
+#   also inserts sequence information
+# 
+
+
+#
+# setup
+# to be filled by the user:
+#
+
+# to really insert information set insert="yes"
+insert="yes"
+insert=
+
+
+# give array of ceres keys
+# remark: in case you insert new ceres keys: 
+#  make sure that the information on the setup (i.e. table CeresSetup) 
+#  has been inserted before
+cereskeys=( 7 ) 
+cereskeys=( 1 2 3 4 5 6 7 8 9 10 11 12 ) 
+cereskeys=( 8 9 10 11 12 ) 
+
+
+# give run number range which you want to process with the new setup
+#   if one of these values is empty a new run is inserted with the setup given below
+# 423-960 corresponds to the range of runs used for the sensitivity curve
+#  gammas:  files 1300-1999 i.e. runs 423-630
+#  muons:   files 2400-2999 i.e. runs 753-930
+#  protons: files 2000-2399 i.e. runs 633-750
+#  protons: files 3000-3099 i.e. runs 933-960
+#  protons: new runs 1040-1070
+runmin=423
+runmax=960
+runmin=1040
+runmax=1070
+runmin=
+runmax=
+
+
+#
+# setup for a new run
+#
+
+# number of events per file
+numevents=35000  # Protons CSCAT=20
+#numevents=2000 # Gamma CSCAT=20
+
+# number of files per run
+#numfile=1 #
+numfile=50 # Protons CSCAT=20
+#numfile=10 # Gamma CSCAT=20
+
+numreuse=1
+numreuse=20
+
+# particle type
+#particle=1 # gamma
+particle=14 # proton
+#particle=6 # muon
+#particle=3 # electron
+#particle=402 # helium
+#particle=5626 # iron
+
+
+# zenith range
+zdmin=30
+zdmax=30
+# azimuth range
+azmin=180
+azmax=180
+
+# energy (in GeV)
+emin=20  # 20
+emax=200000  # 200000
+#emin=100 # Gamma
+#emax=50000 # Gamma
+#slope=-2.7 # for gammas, depends on source spectrum, or for test
+slope=-2.78 # for protons and muons and irons
+
+# impact
+impactmax=80000 # for protons (and irons ?)
+#impactmax=42500 # for gammas
+#impactmax=20000 # for muons
+
+# view cone
+viewconemax=5.0 # for protons and irons
+#viewconemax=4.5 # for muons 
+#viewconemax=0 # for gammas
+
+# starting altitude
+startalt=0 # for gammas and protons and irons
+#startalt=280 # for muons
+
+# mirror diameter
+mirrordia=1800
+mirrordia=900
+
+# wavelength range
+wavelengthmin=290
+wavelengthmax=900
+
+# observatory key
+obskey=1 # LP
+
+#
+# script - do not edit below
+#
+source `dirname $0`/sourcefile
+
+
+function sendquery2()
+{
+   if [ "$insert" = "yes" ]
+   then 
+      sendquery >/dev/null
+   else 
+      echo "Q: "$query
+   fi
+}
+
+# atmospheric model (at the moment only 11 to be used)
+#   will be moved to user settings later
+atm=11
+
+# switches for insert
+newrun=
+newceres=
+
+# get ceres setup name
+query="SELECT fCeresSetupName FROM CeresSetup WHERE fCeresSetupKEY in ("`echo ${cereskeys[@]} | sed -e 's/\ /,/g'`")"
+echo $query
+ceresnames=( `sendquery` )
+if [ ${#ceresnames[@]} -lt ${#cereskeys[@]} ]
+then
+   echo "Please insert first the information on all new ceres setups (keys: "${cereskeys[@]}") into the database."
+   echo "EXIT."
+   exit
+fi
+
+if [ "$runmin" == "" ] || [ "$runmax" == "" ]
+then 
+   newrun="yes"
+   # get next run number
+   query="SELECT Max(fRunNumber)+1 FROM CorsikaStatus"
+   prun=`sendquery`
+   crun=`echo " $prun + 1 " | bc -l`
+   drun=`echo " $prun + 2 " | bc -l`
+   runs=( $drun )
+   
+   # get particle type name
+   query="SELECT fParticleTypeName FROM ParticleType WHERE fParticleTypeKEY="$particle
+   pname=`sendquery`
+   
+   # get observatory name
+   query="SELECT fObservatoryName FROM Observatory WHERE fObservatoryKEY="$obskey
+   obsname=`sendquery`
+   
+   echo "Do you really want to insert the following run(s)?"
+   echo "  D-Run:             "$drun" ("$numfile" file(s))"
+   echo "  P-Run:             "$prun
+   echo "  C-Run:             "$crun
+   echo "  Particle:          "$particle" ("$pname")"
+   echo "  Number of events:  "$numevents
+   echo "  Energy:            "$emin" GeV - "$emax" GeV "
+   echo "  Slope:             "$slope
+   echo "  Maximum Impact:    "$impactmax" cm "
+   echo "  Maximum View Cone: "$viewconemax" deg "
+   echo "  Starting Altitude: "$startalt
+   echo "  Mirror Diameter:   "$mirrordia" cm "
+   echo "  Zenith Distance:   "$zdmin" deg - "$zdmax" deg "
+   echo "  Azimuth:           "$azmin" deg - "$azmax" deg "
+   echo "  Wavelength:        "$wavelengthmin" nm - "$wavelengthmax" nm "
+   echo "  Observatory:       "$obskey" ("$obsname")"
+else
+   newceres="yes"
+   echo "Do you really want to insert the following cereskey(s)?"
+   echo "  run number range:  "$runmin" - "$runmax
+   query="SELECT fRunNumber FROM CorsikaInfo WHERE fRunNumber BETWEEN "$runmin" AND "$runmax" GROUP BY fRunNumber"
+   runs=( `sendquery` )
+   echo "    i.e. the following runs: "${runs[@]}
+fi
+echo "  Ceres Setups:      "${cereskeys[@]}" ("${ceresnames[@]}") "
+echo ""
+if [ "$insert" = "yes" ]
+then
+   echo "You are NOT executing the script in dummy mode => the runs will be inserted. "
+else
+   echo "You are executing the script in dummy mode => nothing will be inserted. "
+fi
+
+echo "Please insert y, if you want to continue"
+echo "              n, if you want to exit the script"
+
+answer=`head -n 1`
+#answer=y
+echo "Your answer: "$answer
+
+case $answer in
+   y) ;;
+   n) echo "EXIT"
+      exit
+      ;;
+   *) echo "Your answer is not clear -> EXIT"
+      exit
+      ;;
+esac
+
+
+
+if [ "$newrun" = "yes" ]
+then 
+   echo "inserting new run "$drun" and according C-run, P-run and sequence information..."
+   #
+   # corsika information
+   #
+   for (( i=1 ; i<=$numfile ; i++ ))
+   do
+      seed1=`echo " $drun * 1000 + $i " | bc -l`
+      seed2=`echo " $drun * 1000 + $i + 1 " | bc -l`
+      seed3=`echo " $drun * 1000 + $i + 2 " | bc -l`
+
+      query="INSERT CorsikaStatus SET fRunNumber="$drun", fFileNumber="$i", fPriority="$drun
+      sendquery2 
+      query="INSERT CorsikaInfo SET fRunNumber="$drun", fFileNumber="$i
+      query=$query", fAtmosphericModelKEY="$atm", fParticleTypeKEY="$particle
+      query=$query", fCorsikaSeed1="$seed1", fCorsikaSeed2="$seed2", fCorsikaSeed3="$seed3
+      query=$query", fZenithDistanceMin="$zdmin", fZenithDistanceMax="$zdmax
+      query=$query", fAzimuthMin="$azmin", fAzimuthMax="$azmax", fNumEvents="$numevents
+      query=$query", fEnergyMin="$emin", fEnergyMax="$emax", fEnergySlope="$slope
+      query=$query", fImpactMax="$impactmax", fViewConeMax="$viewconemax
+      query=$query", fStartingAltitude="$startalt", fMirrorDiameter="$mirrordia
+      query=$query", fObservatoryKEY="$obskey", fNumReUseShowers="$numreuse
+      query=$query", fWavelengthMin="$wavelengthmin", fWavelengthMax="$wavelengthmax
+      sendquery2 
+   done
+
+   query="INSERT CorsikaStatus SET fRunNumber="$prun", fFileNumber=1, fStartTime='1970-01-01 00:00:00', fStopTime='1970-01-01 00:00:00', fAvailable='1970-01-01 00:00:00', fPriority="$prun
+   sendquery2 
+   query="INSERT CorsikaStatus SET fRunNumber="$crun", fFileNumber=1, fStartTime='1970-01-01 00:00:00', fStopTime='1970-01-01 00:00:00', fAvailable='1970-01-01 00:00:00', fPriority="$crun
+   sendquery2 
+
+   # sequence file
+   #   does not need ceres key as well
+   query="INSERT SequenceFileStatus SET fSequenceNumber="$drun", fPriority="$drun
+   sendquery2 
+fi
+
+#
+# further tables: CeresInfo, CeresStatus, Callisto, Calibration, Star, StarStatus, SequenceInfo
+#
+for run in ${runs[@]}
+do 
+   drun=$run
+   crun=`echo " $drun - 1 " | bc -l`
+   prun=`echo " $drun - 2 " | bc -l`
+   
+   for cereskey in ${cereskeys[@]}
+   do
+      query="SELECT fFileNumber FROM CorsikaInfo WHERE fRunNumber="$drun
+      files=`sendquery`
+      for file in ${files[@]}
+      do
+         query="INSERT CeresInfo SET fSequenceNumber="$drun", fRunNumber="$drun", fFileNumber="$file", fCeresSetupKEY="$cereskey", fRunTypeKEY=2"
+         sendquery2 
+      done
+
+      query="INSERT CeresInfo SET fSequenceNumber="$drun", fRunNumber="$prun", fFileNumber=1, fCeresSetupKEY="$cereskey", fRunTypeKEY=3"
+      sendquery2 
+      query="INSERT CeresInfo SET fSequenceNumber="$drun", fRunNumber="$crun", fFileNumber=1, fCeresSetupKEY="$cereskey", fRunTypeKEY=4"
+      sendquery2 
+      query="INSERT CeresStatus SET fRunNumber="$drun", fCeresSetupKEY="$cereskey", fPriority="$drun
+      sendquery2 
+      query="INSERT CeresStatus SET fRunNumber="$prun", fCeresSetupKEY="$cereskey", fPriority="$prun
+      sendquery2 
+      query="INSERT CeresStatus SET fRunNumber="$crun", fCeresSetupKEY="$cereskey", fPriority="$crun
+      sendquery2 
+      query="INSERT Star SET fSequenceNumber="$drun", fCeresSetupKEY="$cereskey
+      sendquery2 
+      query="INSERT StarStatus SET fSequenceNumber="$drun", fCeresSetupKEY="$cereskey", fPriority="$drun
+      sendquery2 
+      query="INSERT CallistoStatus SET fSequenceNumber="$drun", fCeresSetupKEY="$cereskey", fPriority="$drun
+      sendquery2 
+      query="INSERT Calibration SET fSequenceNumber="$drun", fCeresSetupKEY="$cereskey
+      sendquery2 
+      query="INSERT SequenceInfo SET fSequenceNumber="$drun", fCeresSetupKEY="$cereskey
+      sendquery2 
+   done
+done
+
+echo "To make sure that the inserted runs are processed also on callisto/star level, please run the following script: "`dirname $0`"/writemcsequencefile"
+
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/insertsequences
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/insertsequences	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/insertsequences	(revision 17960)
@@ -0,0 +1,84 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the inserting of sequences into the db.
+# It is not used in the automatic processing of data, but only for 
+# inserting of manual written sequences. 
+#
+# Find manual written sequence files and insert information into the 
+# database using the macro insertsequence.C 
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=insertsequences
+
+set -C
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+# finding manual written sequence files (marked by the comment '#manually changed')
+# for test reasons there has to be cut from 1-47 (not as for operator from 1-42) because of
+# sequpath=/magic/test/sequences (not /magic/sequences)
+sequencefiles=(`grep -R '#manually changed' $sequpath/ | cut -c 1-42`)
+echo "sequencefiles: "${sequencefiles[@]}  >> $scriptlog 2>&1 
+echo "" >> $scriptlog 2>&1 
+
+cd $mars
+
+# process sequencefiles: insert information into the database
+for sequencefile in ${sequencefiles[@]}
+do 
+   printprocesslog "INFO inserting sequence from file $sequencefile"
+   echo "file: "$sequencefile >> $scriptlog 2>&1 
+   no=`echo $sequencefile | cut -c 31-38`
+   no2=`echo $no | cut -c 1-4`
+   insertsequencepath=$logpath/$program/$no2
+   makedir $insertsequencepath >> $scriptlog 2>&1
+   insertsequencelog=$insertsequencepath/$program-$no.log
+
+   check0=`root -q -b $macrospath/insertsequence.C+\("\"$sequencefile\""\,kFALSE\) | tee $insertsequencelog | intgrep`
+   case $check0 in 
+      1)   echo "check0=$check0 -> everything ok " >> $scriptlog 2>&1 
+           printprocesslog "INFO sequence $no2 successfully inserted"
+           ;;
+      0)   echo " check1=$check1 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+           printprocesslog "WARN connection to DB failed"
+           check="no"
+           ;;
+      *)   echo "check0=$check0 -> ERROR " >> $scriptlog 2>&1 
+           printprocesslog "ERROR $program.C failed for sequence $no2"
+           ;;
+   esac
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/jobmanager
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/jobmanager	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/jobmanager	(revision 17960)
@@ -0,0 +1,332 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This a script, which launches other scripts (all scripts, that are run 
+# on primary basis)
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+
+set -C
+
+# function to continue in loop and go to next script
+function sleepawhile()
+{
+   usedsleeptime=$sleeptime
+   case $1 in 
+      "error") if ! [ "$errorsleeptime" = "" ]
+               then 
+                  if [ $errorsleeptime -lt $sleeptimelimit ]
+                  then 
+                     errorsleeptime=`echo " $errorsleeptime + $errorsleeptimedefault " | bc`
+                  fi
+                  usedsleeptime=$errorsleeptime
+               fi
+               ;;
+         "ok") errorsleeptime=$errorsleeptimedefault
+               ;;
+   esac
+   echo `date +%F\ %T`" sleeping "$usedsleeptime" seconds... (status: "$1")" >> $jmscriptlog 2>&1
+   echo "" >> $jmscriptlog 2>&1
+   sleep $usedsleeptime
+   continue
+}
+
+echo "" >> $jmscriptlog 2>&1
+echo "" >> $jmscriptlog 2>&1
+echo -n `date +%F\ %T`" starting jobmanager for setup "$AUTOMATIONSETUP >> $jmscriptlog 2>&1
+
+user=`whoami`
+
+# choose commands according to queueing system (defined in setup)
+case $queuesys in
+      sge)  echo " on queuing system 'sun grid engine'" >> $jmscriptlog 2>&1
+            # (-hard) -l hostname=compute-*
+            #   for qstat this returns the jobs running on that node + all jobs in the queue
+            alias 'queuesubmit'='/opt/gridengine/bin/lx26-amd64/qsub -b y -t 1-`echo $tosubmit` -v AUTOMATIONSETUP=$AUTOMATIONSETUP -e `echo $runlogpath`/error-`echo $date`.log -o `echo $runlogpath`/log-`echo $date`.log `echo $noderequirementsub` `echo $scriptspath`/`echo ${scripts[$i]}` '
+#            alias 'queuesubmit'='/opt/gridengine/bin/lx26-amd64/qsub -b y -v AUTOMATIONSETUP=$AUTOMATIONSETUP -e `echo $runlogpath`/error-`echo $date`.log -o `echo $runlogpath`/log-`echo $date`.log `echo $scriptspath`/`echo ${scripts[$i]}` '
+#            alias 'queuesubmit'='/opt/gridengine/bin/lx26-amd64/qsub -sc runlogpath=`echo $runlogpath` -sc date=`echo $date` -sc scriptspath=`echo $scriptspath` -sc script=`echo ${scripts[$i]}` `echo $scriptspath`/job.sge '
+            # FIXME: get complete scriptname (including command line option), needed for runstereo
+            alias 'checkqueue'="/opt/gridengine/bin/lx26-amd64/qstat \`echo \$noderequirementstat\`  | awk ' { print \"Owner\"\$4\" \" \$3\"Jobstatus\"\$5 } '"
+            break
+            ;;
+      pbs)  echo " on queuing system 'pbs'" >> $jmscriptlog 2>&1
+            alias 'queuesubmit'='$pbspath/qsub -t 1-`echo $tosubmit` -l walltime=`echo $walltime` -l pmem=`echo $pmem` -v AUTOMATIONSETUP=$AUTOMATIONSETUP,SOURCEFILEPATH=$SOURCEFILEPATH,SCRIPTNAME=`echo ${scripts[$i]}` -e `echo $runlogpath`/error-`echo $date`.log -o `echo $runlogpath`/log-`echo $date`.log `echo $noderequirementsub` `echo $scriptspath`/`echo ${scripts[$i]}` '
+            # check queue (restricted to current user only)
+            alias 'checkqueue'="$pbspath/qstat -a -u $user | awk ' { print \"Owner\"\$2\" \" \$4\"Jobstatus\"\$10 } '"
+            break
+            ;;
+   condor)  echo " on queuing system 'condor'" >> $jmscriptlog 2>&1
+            alias 'queuesubmit'='$condorpath/condor_submit -a path=`echo $scriptspath` -a prog=`echo ${scripts[$i]}` -a date=`echo $date` -a dir=`echo $runlogpath` -a num=`echo $tosubmit` -a automationsetup=$AUTOMATIONSETUP `echo $scriptspath`/run.condor'
+            alias 'checkqueue'='$condorpath/condor_q -global -format "Owner%s " Owner -format "%s" CMD -format "Jobstatus%s\n" Jobstatus '
+            break 
+            ;;
+        *)  echo "" >> $jmscriptlog 2>&1
+            finish >> $jmscriptlog 2>&1
+            ;;
+esac
+
+echo "" >> $jmscriptlog 2>&1
+
+# for processing with local storage on different nodes
+currentnode=$minnode
+numevaluated=0
+
+# endless loop
+notcount=0
+errorsleeptime=$errorsleeptimedefault
+while (( $notcount < 100 ))
+do
+   # get and set some information for the processing
+   source `dirname $0`/sourcefile
+   # reset some values
+   tosubmit=0
+   idleratio=0
+   addtoscript=
+   
+   # get processes in queue
+   q=(`checkqueue 2>&1 `)
+   if echo $q | egrep \(Error\|failed\)
+   then 
+      echo `date +%F\ %T`" WARN checking query ($queuesys) failed" >> $jmscriptlog 2>&1
+      printprocesslog "WARN checking query ($queuesys) failed"
+      echo `date +%F\ %T`" WARN checking query ($queuesys) failed" >> $jmerrorlog
+      sleepawhile "error"
+   fi
+
+   # general check whether one should submit something depending on chosen algorithm
+   # algorithm 1: 
+   #   submit new jobs in case there are less than $limitidle idle jobs in the queue
+   # algorithm 2: 
+   #   submit new jobs in case the total number of jobs in the queue has fallen below $totalpno
+   case $algorithm in
+      1) # algorithm 1
+         # get number of idle jobs in the queue
+         q5=( `echo ${q[@]} | egrep -o \(Jobstatus1\|Jobstatusq\|JobstatusQ\)` )
+         idle=${#q5[@]}
+         if [ $idle -gt $limitidle ]
+         then 
+            echo `date +%F\ %T`" more than "$limitidle" jobs waiting ("$idle")" >> $jmscriptlog 2>&1
+            sleepawhile "ok"
+         fi
+         ;;
+      2) # algorithm 2
+         # get processes of user in queue
+         q1=( `echo ${q[@]} | egrep -o "Owner$user"`)
+         queued=${#q1[@]}
+         hour=`date +%k`
+         # choose array of total number of jobs to be done 
+         #   according to the day of the week
+         dayofweek=`date +%u`
+         case $dayofweek in
+            0 | 6)  totalpno=${pnototal[$hour]} ;;
+                *)  totalpno=${pnototalwe[$hour]} ;;
+         esac
+         # get total number of jobs to be submitted
+         if [ $queued -gt $totalpno ]
+         then 
+            echo `date +%F\ %T`" more than "$totalpno" jobs waiting ("$queued")" >> $jmscriptlog 2>&1
+            sleepawhile "ok"
+         else
+            tosubmittotal=`echo "$totalpno - $queued" | bc -l`
+         fi
+         ;;
+      *) echo "Please give an algorithm to calculate the number of allowed jobs."
+         exit
+         ;;
+   esac
+   echo `date +%F\ %T`" Total number of jobs to be submitted: "$tosubmittotal >> $jmscriptlog 2>&1
+
+
+   # first loop to determine 
+   # a) how many jobs of this script have to be done
+   # b) how many jobs of this script are running or queued
+   for (( i=0 ; i < ${#scripts[@]} ; i++ ))
+   do 
+      # set the step to be evaluated
+      step=${scriptscolname[$i]}
+      getstepinfo
+
+      # check if the script is restricted to one node 
+      #   (i.e. where output of previous step(s) is stored)
+      #   this information is taken from the steps.rc file
+      #   currently this is implemented for sge only
+      # then get number of jobs to be done 
+      if [ "$noderestricted" = "yes" ]
+      then
+         # get number of next node 
+         if [ $numevaluated -ge $numrestrictedscripts ]
+         then 
+            currentnode=`echo " $currentnode + 1 " | bc -l`
+            numevaluated=1
+         else
+            numevaluated=`echo " $numevaluated + 1 " | bc -l`
+         fi
+         if [ $currentnode -gt $maxnode ]
+         then 
+            currentnode=$minnode
+         fi
+         # check if node is excluded
+         for excludednode in ${excludednodes[@]}
+         do
+            if [ $currentnode -eq $excludednode ]
+            then
+               echo `date +%F\ %T`" Node compute-0-$currentnode is currently excluded." >> $jmscriptlog 2>&1
+               continue 2
+            fi
+         done
+         # define requirement for submission 
+         # FIXME: currently only for sge at isdc
+         echo `date +%F\ %T`" Checking for node $currentnode. " >> $jmscriptlog 2>&1
+         noderequirementsub=" -hard -l hostname=compute-0-${currentnode}"
+         noderequirementstat=" -l hostname=compute-0-${currentnode}"
+         # get number of jobs to be done from the DB
+         getstatus $currentnode >> $jmscriptlog 2>&1
+      else
+         noderequirementsub=""
+         noderequirementstat=""
+         # get number of jobs to be done from the DB
+         getstatus >> $jmscriptlog 2>&1
+      fi
+      # store the number of processes to be done for this script
+      todo[$i]=$numproc
+      tododb[$i]=$numproc
+      
+      # FIXME: sge cuts scriptname to 8 digits in qstat
+      # number of idle jobs, i.e. jobs waiting in the queue to run
+      #   condor: 1
+      #   sge: q
+      #   pbs: Q
+      q4=( `echo ${q[@]} | egrep -o \("${scripts[$i]}"Jobstatus1\|"${scripts[$i]}"Jobstatusq\|"${scripts[$i]}"JobstatusQ\)` )
+      idlescript[$i]=${#q4[@]}
+
+      q2=( `echo ${q[@]} | egrep -o "${scripts[$i]}"`)
+      queuedscript[$i]=${#q2[@]}
+
+      stillfree[$i]=`echo "${maxjobs[$i]} - ${queuedscript[$i]} " | bc -l`
+
+      if [ $numproc -eq 0 ] || [ ${todo[$i]} -le ${idlescript[$i]} ] || [ ${maxjobs[$i]} -le ${queuedscript[$i]} ]
+      then 
+         # store the fraction of cpus to add it to another process
+         idleratio=`echo " ${ratio[$i]} + $idleratio " | bc -l`
+         ratio[$i]=0
+         todo[$i]=0
+         idlenum=$i
+         continue
+      fi
+   done
+   echo `date +%F\ %T`" Evaluated scripts: "${scripts[@]} >> $jmscriptlog 2>&1
+   echo `date +%F\ %T`" Running scripts: "${queuedscript[@]}" (max: "${maxjobs[@]}")" >> $jmscriptlog 2>&1
+   echo `date +%F\ %T`" Number of jobs to be done (from DB): "${tododb[@]} >> $jmscriptlog 2>&1
+   echo `date +%F\ %T`" Number of jobs to be done (updated): "${todo[@]} >> $jmscriptlog 2>&1
+   echo `date +%F\ %T`" Ratio: "${ratio[@]}" (idle: "$idleratio")" >> $jmscriptlog 2>&1
+   
+   # loop to update the ratio taking into account the ratio of
+   #   a) steps where nothing has to done
+   #   b) steps where already enough jobs are in the queue
+   # sum up this idle ratio
+   # determine for which step still most jobs have to be done
+   if ! [ "$idleratio" = "0" ]
+   then 
+      addtoscript=
+      for (( i=0 ; i < ${#scripts[@]} ; i++ ))
+      do 
+         if [ ${todo[$i]} -gt ${todo[$idlenum]} ] && [ ${todo[$i]} -gt 0 ] 
+         then
+            if ! [ "$addtoscript" = "" ] 
+            then 
+               if [ ${todo[$i]} -lt ${todo[$addtoscript]} ]
+               then
+                  continue
+               fi
+            fi
+            addtoscript=$i
+         fi
+      done
+      
+      # continue in case nothing has to be done for all steps
+      # else: update the ratio for the step where most jobs have to be done
+      #   by adding the idle ratio
+      if [ "$addtoscript" = "" ] 
+      then
+         echo `date +%F\ %T`" No jobs to be done for any step." >> $jmscriptlog 2>&1
+         sleepawhile "ok"
+      else
+         ratio[$addtoscript]=`echo " ${ratio[$addtoscript]} + $idleratio " | bc -l`
+      fi
+   fi
+   echo `date +%F\ %T`" Updated ratio: "${ratio[@]} >> $jmscriptlog 2>&1
+   
+   
+   # loop to submit jobs to queueing system
+   for (( i=0 ; i < ${#scripts[@]} ; i++ ))
+   do 
+      # calculate number of jobs to be submitted
+      tosubmit=`echo "scale=0; $tosubmittotal * ${ratio[$i]} / 1 " | bc -l`
+      if [ ${todo[$i]} -lt $tosubmit ]
+      then
+         echo `date +%F\ %T`" Updating tosubmit for "${scripts[$i]}" from "$tosubmit" to "${todo[$i]} >> $jmscriptlog 2>&1
+         tosubmit=${todo[$i]}
+      fi
+      if [ $tosubmit -eq 0 ]
+      then
+         echo `date +%F\ %T`" No jobs to be submitted for script '"${scripts[$i]}"'" >> $jmscriptlog 2>&1
+         continue
+      fi
+      if [ $tosubmit -gt ${stillfree[$i]} ]
+      then
+         echo `date +%F\ %T`" Updating tosubmit for "${scripts[$i]}" from "$tosubmit" to "${stillfree[$i]} >> $jmscriptlog 2>&1
+         tosubmit=${stillfree[$i]}
+      fi
+      
+      # set the step to be evaluated
+      step=${scriptscolname[$i]}
+      # check if walltime has to be set
+      if [ "$setwalltime" = "yes" ]
+      then
+         walltime=${walltimes[$i]}
+      fi
+      # check if memory has to be set
+      if [ "$setpmem" = "yes" ]
+      then
+         pmem=${pmems[$i]}
+      fi
+
+      # submit $tosubmit scripts to queuing system
+      echo `date +%F\ %T`" Submitting "$tosubmit" jobs for script '"${scripts[$i]}"' to "$queuesys >> $jmscriptlog 2>&1
+      date=`date +%Y-%m-%d`
+      if ! queuesubmit 2>> $jmerrorlog
+      then 
+         echo `date`" WARN submitting job ($queuesys) failed" >> $jmerrorlog
+         echo `date +%F\ %T`" WARN $queuesys is not working -> sleeping $errorsleeptime [\$errorsleeptime]" >> $jmscriptlog 2>&1
+         printprocesslog "WARN submitting ${scripts[$i]} ($queuesys) failed"
+         sleepawhile "error"
+      fi
+   done
+   sleepawhile "ok"
+done
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/linkmc
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/linkmc	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/linkmc	(revision 17960)
@@ -0,0 +1,267 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  12/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Daniel Hoehne   06/2007 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script is linking the montecarlo files from the original structure
+# to a structure from which the files can be processed more easily with the
+# automatic analysis. 
+# Furthermore the content of the files is filled in the database running
+# fillcamera.C.
+# This script is not yet running automatically. 
+#
+# original structure:
+# /magic/montecarlo/camera/
+#
+# new structure: 
+# /magic/montecarlo/rawfiles/YYYY/MM/DD/file.root
+# more explanation concerning the file structure can be found in the file
+# /magic/montecarlo/rawfiles/README.txt
+#
+# First a file is linked and then fillcamera.C is executed. In case of an 
+# error in fillcamera.C the link is removed.
+# In each new directory also the pedestal and calibration file is linked. 
+#
+# ========================================================================
+
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=linkmc
+
+set -C
+
+scriptlog=$runlogpath/$program-`date +%F`.log
+date >> $scriptlog 2>&1
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+mccampath=$mcpath/camera
+next=$mcrawpath/.next #in .next the next runno is stored
+processed=$mcrawpath/.processed #in .processed the linked files are stored
+readme=$mcrawpath/README.txt #file in which the information about the modes is redirected to have always an updated explanation
+
+# check if file with next runnumber is available
+if ! ls $next >> $scriptlog 2>&1
+then
+   echo "file $next not found -> no start-runno -> exit" >> $scriptlog 2>&1
+   printprocesslog "ERROR file $next (last runno) not found"
+   finish >> $scriptlog 2>&1
+fi
+
+
+# observation modes 
+modes=("" "Gammawobble+" "Gammanowobble0" "GammawobbleHE+" "GammanowobbleHE0" "Gammawobble0" "GammawobbleHE0" "Gammadiffuse0" "Protonnowobble0" "ProtonnowobbleHE0")
+# be careful: 
+# w- not yet foreseen in this script
+
+# print information and explanation of structure into README.txt 
+date >| $readme 2>&1
+echo "" >> $readme 2>&1
+echo "Explanation for the structure in which the mc files are linked" >> $readme 2>&1
+echo "--------------------------------------------------------------" >> $readme 2>&1
+echo "" >> $readme 2>&1
+echo "the files are linked in a YYYY/MM/DD structure like the data files" >> $readme 2>&1
+echo "YYYY represents 19zbin" >> $readme 2>&1
+echo "MM represents the mode" >> $readme 2>&1
+echo "DD represents the psf in mm" >> $readme 2>&1
+echo "" >> $readme 2>&1
+echo "explanation of the modes" >> $readme 2>&1
+echo "modes: "${modes[@]} >> $readme 2>&1
+echo "" >> $readme 2>&1
+for (( i=1 ; i <= 12 ; i++ )) 
+do 
+   if [ "${modes[i]}" != "" ]
+   then 
+      numofmode=`printf %02d $i`
+      echo "mode (MM) = $numofmode means ${modes[$i]}" >> $readme 2>&1
+   fi
+done
+echo "" >> $readme 2>&1
+echo "the mode is indicating " >> $readme 2>&1
+echo " - the particle type" >> $readme 2>&1
+echo " - wobble/nowobble" >> $readme 2>&1
+echo " - HE" >> $readme 2>&1
+echo " - w+/w0 (as +/0)" >> $readme 2>&1
+echo " a combination of w0 and wobble means 'fake wobble'" >> $readme 2>&1
+echo "  (normal mc shifted by 0.4 deg -> abberation not taken into account)" >> $readme 2>&1
+echo "" >> $readme 2>&1
+
+
+
+runno=`cat $next`
+
+#get files, which have to be linked
+camfiles=`find $mccampath -type f | grep -v Cal_and_Ped | sort`
+
+printprocesslog "INFO linking new camerafiles starting with runno $runno"
+for camfile in ${camfiles[@]}
+do 
+
+
+   #continue, if file is already linked 
+   if find $mcpath/* -lname '$mccampath*.root' -printf %l'\n' | grep $camfile >> $scriptlog 2>&1
+#   if grep $camfile $processed >> $scriptlog 2>&1
+   then 
+      continue
+   fi
+
+
+   printprocesslog "INFO linking $file"
+   file=`basename $camfile` #filename
+   no=`printf %08d $runno | cut -c 0-5` #first 5 digits of a 8digit runno -> for path
+   no2=`printf %08d $runno` #runno with 8 digits
+   zbin=`echo $file | cut -d_ -f2 | cut -c 5-6` #zbin from filename 
+   zbin=`printf %02d $zbin` #2digit
+   wobble=`echo $file | cut -d_ -f6 | cut -c 2` #mode from filename
+   particle=`echo $file | cut -d_ -f1` #particle type from filename
+   psf=`echo $camfile | cut -d/ -f6 | cut -c 6,8` #psf from path
+   
+   particledir=`echo $camfile | cut -d/ -f5` #particletype from path
+   wobbledir=`echo $camfile | cut -d/ -f7` #mode from path
+   
+   #build mode name
+   testmode=$particle$wobbledir$wobble 
+
+   #get mode extension for filename
+   case $wobble in 
+       0)   wobblemode="";;
+       +)   wobblemode="W1";;
+       -)   wobblemode="W2";;
+       *)   echo "couldn't find any indication for mode (wobble)" >> $scriptlog 2>&1
+            ;;
+   esac
+   
+   #get no of mode from array $modes
+   for (( i=1 ; i <= 12 ; i++ )) 
+   do 
+      if [ "${modes[$i]}" == "$testmode" ]
+      then 
+         totalmode=$i
+         break
+      fi
+   done
+
+   totalmode=`printf %02d $totalmode` #2 digits
+
+   project=${particle}${zbin}${wobblemode} #build project name
+   #create new filename
+   newfile="$mcrawpath/19$zbin/$totalmode/$psf/19${zbin}${totalmode}${psf}_${no2}_D_${project}_E.root"
+   newdir=`dirname $newfile`
+   makedir $newdir >> $scriptlog 2>&1
+
+   runno=`expr $runno + 1` #next runnumber
+   echo $runno >| $next 
+
+   linkmclogpath=$logpath/$program/$no2
+   makedir $linkmclogpath >> $scriptlog 2>&1
+   linkmclog=$linkmclogpath/$program-$no2.log
+
+   #link file
+   echo "linking file $camfile"
+   ln -sv $camfile $newfile >> $scriptlog 2>&1 
+
+   # run fillcamera.C. In case of success the camfile is written to .processed. In case of an error the link is removed
+   echo "run fillcamera for mc run $no2" >> $scriptlog 2>&1
+   check2=`root -q -b $macrospath/fillcamera.C+\("\"$newfile\""\,kTRUE\) | tee $linkmclog | intgrep`
+   case $check2 in
+      1)   echo " check2=$check2 -> everything ok " >> $scriptlog 2>&1 
+           printprocesslog "INFO done fillcamera successfully for mc run $no2"
+           # add filename to .processed
+           echo $camfile >> $processed
+           ;;
+      0)   echo " check2=$check2 -> no connection to db -> continue..." >> $scriptlog 2>&1 
+           printprocesslog "WARN connection to DB failed, removing link"
+           check="no"
+           # remove link
+           rm $newfile >> $scriptlog 2>&1
+           ;;
+      *)   echo " check2=$check2 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+           printprocesslog "ERROR fillcamera failed for mc run $no2, removing link"
+           check=$check2
+           # remove link
+           rm $newfile >> $scriptlog 2>&1
+           ;;
+   esac
+
+done
+
+printprocesslog "INFO linking cal and ped files"
+echo "linking cal and ped file" >> $scriptlog 2>&1
+#get files
+pedfile=`find $mccampath/Cal_and_Ped -name *_P_*.root`
+
+
+calfile=`find $mccampath/Cal_and_Ped -name *_C_*.root`
+
+
+echo "calfile"$calfile >> $scriptlog 2>&1
+echo "pedfile"$pedfile >> $scriptlog 2>&1
+#check number of files
+numfiles=`echo $pedfile $calfile | wc -w`
+if [ "$numfiles" != "2" ]
+then 
+   "too many files in the directory $mccampath/Cal_and_Ped -> exit" >> $scriptlog 2>&1
+
+
+   rm -v $lockfile >> $scriptlog 2>&1
+   exit
+   printprocesslog "ERROR too many ped and cal files found in $mccampath/Cal_and_Ped"
+   finish >> $scriptlog 2>&1
+fi
+
+#get all directories in the linked structure
+dirs=`find $mcrawpath -type d`
+
+for dir in ${dirs[@]}
+do 
+   #continue, if directory has already linked C and P run
+   cont=`ls $dir/*_0000000[12]_[CP]_MonteCarlo_E.root 2>/dev/null | wc -w`
+   if [ "$cont" == "2" ] >> $scriptlog 2>&1
+   then 
+      continue
+   fi
+
+   #continue, if directory is not at the lowest level of the structure
+   cont=`echo $dir | cut -d/ -f6`
+   if [ "$cont" == "" ]
+   then
+      continue
+   fi
+
+   #get date for filename from directory name
+   date=`echo $dir | cut -c 22-25,27,28,30,31`
+   
+   #create new filenames and link files
+   newcalfile="${dir}/${date}_00000002_C_MonteCarlo_E.root"
+   ln -sv $calfile $newcalfile >> $scriptlog 2>&1
+   newpedfile="${dir}/${date}_00000001_P_MonteCarlo_E.root"
+   ln -sv $pedfile $newpedfile >> $scriptlog 2>&1
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/makecallistolinks
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/makecallistolinks	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/makecallistolinks	(revision 17960)
@@ -0,0 +1,95 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script links a special callisto.rc for data, for which the 
+# calibration with the standard callisto.rc failes. 
+# 
+# The sequences with failing calibration are searched by searching for the 
+# reason of failure in the callisto.log Then the special callisto.rc is 
+# linked to the directory of the sequence. 
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=makecallistolinks
+column=fCallisto
+table=SequenceProcessStatus
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+callistorcseq=callisto.rc
+callistorcnew=callisto_Dec04Jan05.rc
+
+# query failed callistos (returncode 13) from DB
+query="SELECT fSequenceFirst, fTelescopeNumber from SequenceProcessStatus where fReturnCode=13 and fProgramId=14 and fSequenceFirst<200000"
+primaries=( `sendquery` )
+if [ ${#primaries[@]} -eq 0 ]
+then 
+   printprocesslog "INFO nothing to do -> exit" 
+   finish 
+fi
+num=`expr ${#primaries[@]} / 2 `
+
+cd $mars
+
+printprocesslog "INFO linking callisto.rc files"
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s+$s]}
+   telnum=${primaries[$s+$s+1]}
+   callistorc=$datapath/callisto/`printf %08d $sequence | cut -c 0-4`/`printf %08d $sequence`/$callistorcseq
+   if ! ls -l $callistorc 2>/dev/null | grep $callistorcnew >/dev/null
+   then 
+      printprocesslog "INFO linking $callistorcnew to $callistorc for sequ $sequence"
+      # resetting the calibration
+      printprocesslog "INFO resetting the callisto for sequence $sequence" 
+
+      query="UPDATE SequenceProcessStatus set fStartTime=NULL, fFailedTime=NULL, fProgramId=NULL, fReturnCode=NULL where fSequenceFirst=$sequence and fTelescopeNumber=$telnum"
+      if ! sendquery 
+      then 
+         printprocesslog "ERROR resetting calibration failed for sequence $sequence"
+         continue
+      else 
+         printprocesslog "INFO resetted calibration successfully for sequence $sequence"
+      fi
+      
+      #linking callisto.rc
+      if ln -fs $setuppath/callisto/$callistorcnew $callistorc
+      then 
+         printprocesslog "INFO link callisto.rc successfully for sequence $sequence"
+      else 
+         printprocesslog "ERROR linking callisto.rc failed for sequence $sequence"
+      fi
+      
+   fi
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/mcsequences
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/mcsequences	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/mcsequences	(revision 17960)
@@ -0,0 +1,148 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  12/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Daniel Hoehne-Moench  08/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# The script is building one sequence per mc run. The relevant parameters 
+# are taken from the MC database.
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=mcsequences
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+                                              
+# find montecarlo directories, build one sequence per run
+printprocesslog "INFO building one sequence per run"
+
+getdbsetup
+
+dirs=`find $mcrawpath -type d`
+for dir in ${dirs[@]}
+do 
+   cont=`echo $dir | cut -d/ -f7`
+   #cont=`echo $dir | cut -d/ -f10`
+   if [ "$cont" == "" ]
+   then
+      continue
+   fi
+   printprocesslog "INFO dir: "$dir 
+   
+   epochs=`ls -l $mcpath/camera | cut -d' ' -f8`
+   for epoch in ${epochs[@]}
+   do
+      printprocesslog "INFO epoch: "$epoch 
+
+      calfile=`find $dir -lname *${epoch}/*.root | grep "_C_"`
+      pedfile=`find $dir -lname *${epoch}/*.root | grep "_P_"`
+      calrun=`echo $calfile | cut -d_ -f2`
+      pedrun=`echo $pedfile | cut -d_ -f2`
+      
+      modes=("Gamma" "GammaW1" "GammaW2" "GammaFW" "GammaDiff" "GammaHE" "GammaHEW1" "GammaHEW2" "GammaHEFW" "GammaHEDiff" "ProtonDiff" "ProtonHEDiff" "MuonDiff" "MuonHEDiff" "GammaSUM" "GammaW1SUM" "GammaW2SUM" "GammaFWSUM" "GammaDiffSUM" "GammaHESUM" "GammaHEW1SUM" "GammaHEW2SUM" "GammaHEFWSUM" "GammaHEDiffSUM" "ProtonDiffSUM" "ProtonHEDiffSUM" "MuonDiffSUM" "MuonHEDiffSUM")
+      for mode in ${modes[@]}
+      do
+         datruns=`find $dir -lname *${epoch}/*.root | grep ${mode}_ | grep "_D_" | cut -d_ -f2 | tr "\n" " "`
+         if [ "$datruns" != "" ]
+         then
+            date=`echo $dir | cut -c 28-37 | sed -e 's/\//-/g'`
+            #date=`echo $dir | cut -c 57-66 | sed -e 's/\//-/g'`
+            zbin=`echo $date | cut -c 3,4`
+         
+            for datrun in ${datruns[@]}
+            do
+               query1=" select fSpectrumKEY, fPSFKEY, fAmplFadcKEY, fAtmosphericModelKEY, fObservationModeKEY, fMCParticleKEY, fReflectorVersionKEY, fCorsikaVersionKEY, fCameraVersionKEY, fViewConeAngleOKEY, fAddSpotSizeKEY, fTriggerFlagKEY, fPhiMax, fPhiMin from MCRunData where fRunNumber=\"$datrun\" "
+               query2=" select sum(fNumEvents), sum(fNumTriggers), sum(fNumSumTriggers) from MCRunData where fRunNumber=\"$datrun\" "
+               values=`mysql -ss -u $us --password=$pw --host=$ho $db -e " $query1 "`
+               values2=`mysql -ss -u $us --password=$pw --host=$ho $db -e " $query2 "`
+               spec=`echo $values | cut -d" " -f1`
+               psf=`echo $values | cut -d" " -f2`
+               amplfadc=`echo $values | cut -d" " -f3`
+               atmo=`echo $values | cut -d" " -f4`
+               obs=`echo $values | cut -d" " -f5`
+               part=`echo $values | cut -d" " -f6`
+               refl=`echo $values | cut -d" " -f7`
+               cors=`echo $values | cut -d" " -f8`
+               cam=`echo $values | cut -d" " -f9`
+               view=`echo $values | cut -d" " -f10`
+               ass=`echo $values | cut -d" " -f11`
+               trig=`echo $values | cut -d" " -f12`
+               azmax=`echo $values | cut -d" " -f13`
+               azmin=`echo $values | cut -d" " -f14`
+               events=`echo $values2 | cut -d" " -f1`
+               triggers=`echo $values2 | cut -d" " -f2`
+               sumtriggers=`echo $values2 | cut -d" " -f3`
+               query3=" select fSequenceFirst from MCSequenceProcessStatus where fSequenceFirst=\"$datrun\" "
+               query4=" select fSequenceFirst from MCSequences where fSequenceFirst=\"$datrun\" "
+               insert1=" insert MCSequenceProcessStatus set fSequenceFirst=\"$datrun\", fPriority=\"$datrun\", fSequenceFileWritten=Now() "
+               insert2=" insert MCSequences set fSequenceFirst=\"$datrun\", fRunStart=\"$date\", fNumEvents=\"$trainevents\", fNumTriggers=\"$triggers\", fNumSumTriggers=\"$sumtriggers\", fZBin=\"$zbin\", fSpectrumKEY=\"$spec\", fPSFKEY=\"$psf\", fAddSpotSizeKEY=\"$ass\", fAmplFadcKEY=\"$amplfadc\", fAtmosphericModelKEY=\"$atmo\", fObservationModeKEY=\"$obs\", fMCParticleKEY=\"$part\", fReflectorVersionKEY=\"$refl\", fCorsikaVersionKEY=\"$cors\", fCameraVersionKEY=\"$cam\", fViewConeAngleOKEY=\"$view\", fTriggerFlagKEY=\"$trig\", fPhiMax=\"$azmax\", fPhiMin=\"$azmin\", fTestTrainKEY=2 "
+               update1=" update MCRunData set fSequenceFirst=\"$datrun\" where fRunNumber=\"$datrun\" "
+               update2=" update MCSequences set fRunStart=\"$date\", fNumEvents=\"$events\", fNumTriggers=\"$triggers\", fNumSumTriggers=\"$sumtriggers\", fZBin=\"$zbin\", fSpectrumKEY=\"$spec\", fPSFKEY=\"$psf\", fAddSpotSizeKEY=\"$ass\", fAmplFadcKEY=\"$amplfadc\", fAtmosphericModelKEY=\"$atmo\", fObservationModeKEY=\"$obs\", fMCParticleKEY=\"$part\", fReflectorVersionKEY=\"$refl\", fCorsikaVersionKEY=\"$cors\", fCameraVersionKEY=\"$cam\", fViewConeAngleOKEY=\"$view\", fTriggerFlagKEY=\"$trig\", fPhiMax=\"$azmax\", fPhiMin=\"$azmin\", fTestTrainKEY=2 where fSequenceFirst=\"$datrun\" "
+
+               mysql -ss -u $us --password=$pw --host=$ho $db -e " $update1 "
+               check3=`mysql -ss -u $us --password=$pw --host=$ho $db -e " $query3 "`
+               check4=`mysql -ss -u $us --password=$pw --host=$ho $db -e " $query4 "`
+               if [ "$check3" == "" ]
+               then
+                  mysql -ss -u $us --password=$pw --host=$ho $db -e " $insert1 "
+               fi
+               if [ "$check4" == "" ]
+               then
+                  mysql -ss -u $us --password=$pw --host=$ho $db -e " $insert2 "
+               else
+                  mysql -ss -u $us --password=$pw --host=$ho $db -e " $update2 "
+               fi
+               
+               no=`echo $datrun | cut -c 1-4`
+               sequpath=$mcsequpath/$no
+               makedir $sequpath 
+               sequfile=$sequpath/sequence$datrun.txt
+               printprocesslog "INFO writing sequencefile $sequfile"
+               
+               echo "Sequence:        $datrun" >| $sequfile
+               echo "Night:           $date" >> $sequfile
+               echo "Epoch:           $epoch" >> $sequfile
+               echo "Mode:            $mode" >> $sequfile
+               echo "Azimuth:         $azmin - $azmax" >> $sequfile
+               echo "" >> $sequfile
+               echo "CalRuns:         $calrun" >> $sequfile
+               echo "PedRuns:         $pedrun" >> $sequfile
+               echo "DatRuns:         $datrun" >> $sequfile
+               echo "" >> $sequfile
+               echo "MonteCarlo: Yes" >> $sequfile
+               echo "" >> $sequfile
+               
+            done
+         fi
+      done
+   done
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/movingrawfiles
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/movingrawfiles	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/movingrawfiles	(revision 17960)
@@ -0,0 +1,89 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Stefan Ruegamer 02/2007 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script is moving the rawfiles from the directory
+# /magic/datacenter/fromtape/rawdata to the structure
+# /magic/data/rawfiles/YYYY/MM/DD
+# 
+# As the data transfer is at the moment not working via .finished files,
+# you have to use the script movingrawfiles_OK for moving these data
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=movingrawfiles
+
+set -C
+umask 0002
+
+# check whether script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# change permission for files
+ssh tape@dc07 chmod -R g+w /magic/datacenter/fromtape/rawdata/* 
+
+# find rawfiles belonging to tape (don't move files not yet md5-sum checked)
+rawfiles=`find /magic/{datacenter,data/rawfiles}/fromtape/???data/ -regextype posix-egrep -regex '.*/20[01][0-9]{5}_(M[12]_)?[0-9]{8}(\.[0-9]{3})?_.*.raw(.gz)?$' -type f -user tape`
+
+if [ "$rawfiles" == "" ]
+then
+   printprocesslog "INFO no files to move -> exit" 
+   finish 
+fi
+
+# move rawfiles
+printprocesslog "INFO moving rawfiles to $datapath/rawfiles"
+for rawfile in $rawfiles
+do
+# workaround for rawfiles with wrong timing
+#   newrawfile=`echo $rawfile | sed -e 's/center\/fromtape\/rawdata/\/rawfiles-wrong-timing/g' -e 's/_/\//1' -e 's/_/\//1'`
+   path=`dirname $rawfile | cut -d/ -f3`
+   if [ "$path" == "datacenter" ]
+   then
+      subpath=`dirname $rawfile | cut -d/ -f5`
+      newrawfile=`echo $rawfile | sed -e 's/center\/fromtape\/'${subpath}'/\/rawfiles/g' -e 's/_/\//1' -e 's/_/\//1'`
+   elif [ "$path" == "data" ]
+   then
+      newrawfile=`echo $rawfile | sed -e 's/\/fromtape\/muxdata//g' -e 's/_/\//1' -e 's/_/\//1'`
+   else
+      printprocesslog "ERROR moving rawfile $rawfile failed"
+      continue
+   fi
+   
+   newdir=`dirname $newrawfile`
+   makedir $newdir 
+   
+   mv -v $rawfile $newrawfile 
+done
+
+rmdir -v /magic/{datacenter,data/rawfiles}/fromtape/???data/* 
+
+printprocesslog "INFO launching filesondisk"
+$scriptspath/filesondisk &
+
+finish 
Index: branches/Mars_McMismatchStudy/datacenter/scripts/movingrawfiles_OK
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/movingrawfiles_OK	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/movingrawfiles_OK	(revision 17960)
@@ -0,0 +1,107 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Stefan Ruegamer 02/2007 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script is moving the rawfiles from the directory
+# /magic/datacenter/fromtape/rawdata to the structure
+# /magic/data/rawfiles/YYYY/MM/DD
+# 
+# Before running this script via cronjob, a check has to be included
+# which logs in to La Palma and checks if the corresponding link in the
+# Wuerbzurg transfer folder has already been deleted (else the file will
+# be transferred again after moving)
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=movingrawfiles_OK
+
+set -C
+umask 0002
+
+# check whether script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# change permission for files
+ssh tape@dc07 chmod -R g+w /magic/datacenter/fromtape/rawdata/* 
+ssh lapalma@dc09 chmod -R g+w /magic/datacenter/fromlapalma/RAW*/ 
+# output for chmod with -v or -c (only changes)
+
+printprocesslog "INFO moving directories from fromlapalma to fromtape"
+#find directories which have to be copied
+dirs=`ls /magic/datacenter/fromlapalma/RAW/*/*.OK | sed -e 's/.OK//g'`
+if [ ! "$dirs" == "" ]
+then
+   # change permission for this directories
+   ssh lapalma@dc09 chmod -R g+w $dirs 
+   # move directories to the tapedirectory
+   dates=`find /magic/datacenter/fromlapalma/RAW/*200* -type d | cut -d/ -f6`
+   for date in ${dates[@]}
+   do
+	ssh lapalma@dc09 mkdir /magic/datacenter/fromlapalma/RAWchk/$date 
+      	makedir /magic/datacenter/fromtape/rawdata/$date 
+        
+   	OKs=`ls /magic/datacenter/fromlapalma/RAW/$date/*.OK`
+      	for OK in ${OKs[@]}
+        do
+		ssh lapalma@dc09 mv -v $OK /magic/datacenter/fromlapalma/RAWchk/$date/ 
+                files=`echo $OK | sed -e 's/.OK//g'`
+		mv -v $files /magic/datacenter/fromtape/rawdata/$date/ 
+	done
+   done
+fi
+
+rmdir -v /magic/datacenter/fromlapalma/RAW/*200* 
+
+# find rawfiles
+rawfiles=`find /magic/datacenter/fromtape/rawdata/ -name '*.*'`
+
+if [ "$rawfiles" == "" ]
+then
+   printprocesslog "INFO no files to move -> exit" 
+   finish 
+fi
+
+printprocesslog "INFO moving rawfiles to $datapath/rawfiles"
+for rawfile in $rawfiles
+do
+# workaround for rawfiles with wrong timing
+#   newrawfile=`echo $rawfile | sed -e 's/center\/fromtape\/rawdata/\/rawfiles-wrong-timing/g' -e 's/_/\//1' -e 's/_/\//1'`
+   newrawfile=`echo $rawfile | sed -e 's/center\/fromtape\/rawdata/\/rawfiles/g' -e 's/_/\//1' -e 's/_/\//1'`
+   newdir=`dirname $newrawfile`
+   makedir $newdir 
+   
+   mv -v $rawfile $newrawfile 
+done
+
+rmdir -v /magic/datacenter/fromtape/rawdata/* 
+
+printprocesslog "INFO launching filesondisk"
+$scriptspath/filesondisk&
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/movingsubsystemfiles
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/movingsubsystemfiles	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/movingsubsystemfiles	(revision 17960)
@@ -0,0 +1,57 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script is moving the subsystemfiles from the directory 
+# /magic/datacenter/fromtape to the structure 
+# /magic/subsystemdata/subsystem/YYYY/MM/DD
+# 
+
+umask 0002
+
+# change permission for files 
+# perhaps needed as the tapes are read by the user tape 
+ssh tape@dc07 chmod -R g+w /magic/datacenter/fromtape/{ccdata,cacodata,amc,daqlog}/* 
+
+# find subsystem files
+subsysfiles=`find /magic/datacenter/fromtape/ccdata/ -name '*.*'`
+subsysfiles=("${subsysfiles[@]}" `find /magic/datacenter/fromtape/daqlog/ -name '*.*'`)
+subsysfiles=("${subsysfiles[@]}" `find /magic/datacenter/fromtape/cacodata/ -name '*.*'`)
+subsysfiles=("${subsysfiles[@]}" `find /magic/datacenter/fromtape/amc/ -name '*.*'`)
+
+# moving subsystem files
+for subsysfile in ${subsysfiles[@]}
+do 
+   newsubsysfile=`echo $subsysfile | sed -e 's/datacenter\/fromtape/subsystemdata/g' -e 's/daqlog/daq__/g' -e 's/ccdata/cc/g' -e 's/cacodata/caco/g' -e 's/_/\//1' -e 's/_/\//1' -e 's/\/\///g'`
+   newdir=`dirname $newsubsysfile`
+   if [ ! -d $newdir ]
+   then
+      echo "make dir "$newdir
+      mkdir -p $newdir
+   fi
+
+   mv -v $subsysfile $newsubsysfile
+done
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/processmcsequences
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/processmcsequences	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/processmcsequences	(revision 17960)
@@ -0,0 +1,149 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  12/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script is an intermediate solution to process the montecarlo files.
+# As soon as the montecarlo database is running, this script shall be 
+# exchanged. 
+# 
+# The script is processing the montecarlo sequences: callisto and star
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=processmcsequences
+
+set -C
+
+scriptlog=$runlogpath/$program`date +%F-%H-%M-%S`.log
+date >> $scriptlog 2>&1
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+mccalpath=$mcpath/callisto
+mcimgpath=$mcpath/star
+callistorc=$setuppath/callisto/callisto.rc
+
+cd $mars
+
+# find montecarlo sequence files
+printprocesslog "INFO processing mc sequences"
+sequfiles=`find $mcsequpath -type f`
+for sequfile in ${sequfiles[@]}
+do 
+   sequno=`echo $sequfile | cut -c 42-49`
+   no=`echo $sequno | cut -c 0-4`
+   date=`grep Night $sequfile | cut -c 18-29 | sed -e 's/-/\//g'`
+   muxcheck=`grep Epoch $sequfile | cut -c 18-32`
+   case $muxcheck in
+      "MC_up_to_April06")
+      callistorc=$setuppath/callisto/callisto.rc
+      ;;
+      "MC_old")
+      callistorc=$setuppath/callisto/callisto.rc
+      ;;
+      "MC_April_May06")
+      callistorc=$setuppath/callisto/callisto.rc
+      ;;
+      "MC_post_June06")
+      callistorc=$setuppath/callisto/callisto.rc
+      ;;
+      "MC_MuxFADCs")
+      callistorc=$setuppath/callisto/callisto_mux.rc
+      ;;
+      "MC_MuxFADCs_NEW")
+      callistorc=$setuppath/callisto/callisto_mux.rc
+      ;;
+      *)
+      echo "No epoch found"
+      printprocesslog "ERROR no epoch found in $sequfile for setting the right callisto.rc, using standard callisto.rc, epoch: $epoch"
+      finish >> $scriptlog 2>&1
+      ;;
+   esac
+      
+   caloutpath=$mccalpath/$no/$sequno
+   makedir $caloutpath >> $scriptlog 2>&1
+   
+   # continue with next sequence if sequence is already processed
+   # or processing of sequence is just running
+   if ls $caloutpath/.done >> $scriptlog 2>&1
+   then 
+      continue
+   fi
+   if ls $caloutpath/.doing >> $scriptlog 2>&1
+   then 
+      continue
+   fi
+   
+   # lock file
+   touch $caloutpath/.doing
+   echo "processing sequ $sequfile" >> $scriptlog 2>&1
+   # find callisto.rc file
+   if [ -e $caloutpath/callisto.rc ]
+   then
+      echo "found callisto.rc in $caloutpath -> using this" >> $scriptlog 2>&1
+      callistorcseq=$caloutpath/callisto.rc
+   else
+      echo "no callisto.rc found in $caloutpath -> making link " >> $scriptlog 2>&1
+      ln -vs $callistorc $caloutpath/callisto.rc >> $scriptlog 2>&1
+      callistorcseq=$caloutpath/callisto.rc
+   fi
+   # calibrate data
+   echo "./callisto -mc -f -b -q --ind=$mcrawpath/$date --log=$caloutpath/callisto$sequno.log --html=$caloutpath/callisto$sequno.html --out=$caloutpath --config=$callistorcseq $sequfile 2>> $scriptlog > /dev/null" >> $scriptlog 2>&1
+   ./callisto -mc -f -b -q --ind=$mcrawpath/$date --log=$caloutpath/callisto$sequno.log --html=$caloutpath/callisto$sequno.html --out=$caloutpath --config=$callistorcseq $sequfile 2>> $scriptlog > /dev/null
+   check1=$?
+   # if calibration worked -> run star for sequence
+   case $check1 in
+      0)   echo " check1=$check1 -> everything ok..." >> $scriptlog 2>&1
+           printprocesslog "INFO calibrated mc sequence $sequno successfully"
+           touch $caloutpath/.done
+           rm $caloutpath/.doing
+           imgoutpath=$mcimgpath/$no/$sequno
+           makedir $imgoutpath >> $scriptlog 2>&1
+           
+           echo "./star -b -q -v4 -f -mc --log=$imgoutpath/star$sequno.log --html=$imgoutpath/star$sequno.html --ind=$caloutpath --out=$imgoutpath $sequfile  2>> $scriptlog> /dev/null" >> $scriptlog 2>&1
+           ./star -b -q -v4 -f -mc --log=$imgoutpath/star$sequno.log --html=$imgoutpath/star$sequno.html --ind=$caloutpath --out=$imgoutpath $sequfile  2>> $scriptlog> /dev/null
+           check2=$?
+           
+           case $check2 in
+              0)   echo " check2=$check2 -> everything ok..." >> $scriptlog 2>&1
+                   printprocesslog "INFO run star successfully for mc sequence $sequno"
+                   touch $imgoutpath/.done
+                   ;;
+              *)   echo " check2=$check2 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+                   printprocesslog "ERROR star failed for mc sequence $sequno"
+                   ;;
+           esac
+    	   ;;
+      *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+           printprocesslog "ERROR callisto failed for mc sequence $sequno"
+           ;;
+   esac
+done
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/read_lapalma-tapes
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/read_lapalma-tapes	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/read_lapalma-tapes	(revision 17960)
@@ -0,0 +1,206 @@
+#!/bin/bash
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Stefan Ruegamer 08/2008 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script will read raw file tapes from La Palma. After specifying the
+# tape number the tape will be loaded into a free or idle drive and the
+# files will be extracted to the /data/fromtape directory. Then
+# checkmd5sum will be started and, if successful, also movingrawfiles.
+# After file extraction the tape drive will be switched to normal state
+# again, and after successful md5 test the tape will be exported.
+# The logfile can be found at /home/lapalma/tapecont/cont/muxdata/readlogs
+#
+# ToDo: check the available space on /data and /magic, so the user does no
+#       longer have to do it. What's with the SATAs?
+#       movingrawfiles, find source file if this script is in /tools!
+
+#mars=`dirname $0 | sed -e 's/\/datacenter\/tools//'`
+mars=`dirname $0 | sed -e 's/\/datacenter\/scripts//'`
+
+echo -e "IMPORTANT: make sure that enough space is left on the FC and SATA arrays before executing this script! \n"
+
+tape=$@
+if [ "$tape" == "" ]
+then
+   echo "Please specify the tape number (e.g. 3MG005). The following foreign tapes have been found in the L700:"
+   samcmd v 100 | grep "NOT SAM MEDIA" | grep -v "\-il---b-----" | cut -c 55-60 | sort
+   read tape
+   
+   if [ "$tape" == "" ]
+   then
+      echo "No tape specified. Exiting."
+      exit
+   fi
+fi
+
+#mindataspace=
+#minmagicspace=
+magictapepath=/magic/datacenter/fromtape/
+datatapepath=/data/fromtape/
+logfile=/home/lapalma/tapecont/cont/muxdata/readlogs/tape_$tape.log
+number=`echo $tape | cut -c 4-6`
+
+if [ -f $logfile ]
+then
+   echo "logfile already existing -> aborting"
+   exit
+fi
+
+# check if the tape is existing and which drives are free (---------p == present)
+tapeslot=`samcmd v 100 | grep "$tape " | cut -c-4 | sed -e 's/ //g'`
+drive=`samcmd s | grep /dev/rmt/10.cbn | grep "\---------p" | cut -d/ -f4 | cut -c1-3`
+
+# if no drive is free, check for idle drives
+if [ "$drive" == "" ]
+then
+   drive=`samcmd s | grep /dev/rmt/10.cbn | grep "\--l------r" | cut -d/ -f4 | cut -c1-3`
+fi
+
+if [ "$tapeslot" == "" ]
+then
+   echo "Tape $tape not found in the L700. Exiting."
+   exit
+fi
+
+# in case that no drives are ready -> exit; in case more than one drive is ready, take the first one
+if [ "$drive" == "" ]
+then
+   echo "No drive available for reading. Exiting."
+   exit
+else
+   drive=`echo $drive | cut -c1-3`
+fi
+
+echo "Thank you. Your query is being processed. This will take some hours. Check the logfile $logfile for further information."
+
+# check the available space on /magic and on /data; use preferably /data
+#if [ $dataspace -gt $magicspace && $dataspace -gt $mindataspace ]
+#then
+#   echo "$dataspace available on /data. Changing directory to $datatapepath." >> $logfile 2>&1
+#   cd $datatapepath >> $logfile 2>&1
+#   tapepath=$datatapepath
+#else
+#   if [ $magicspace -gt $minmagicspace ]
+#   then
+#      echo "$magicspace available on /magic. Changing directory to $magictapepath." >> $logfile 2>&1
+#      cd $magictapepath >> $logfile 2>&1
+#      tapepath=$magictapepath
+#   else
+#      echo "Not enough space available for reading tapes (/data: $dataspace, /magic: $magicspace). Exiting."
+#      exit
+#   fi
+#fi
+
+date >> $logfile 2>&1
+echo "Loading tape $tape from slot $tapeslot into drive ${drive}cbn..." >> $logfile 2>&1
+
+# set the drive to unavail status; -w checks if the drive is really free
+set_state -w unavail $drive ; load 100:$tapeslot $drive
+
+# check if the drive is ready for reading
+while [ "`samcmd s | grep /dev/rmt/${drive}cbn | grep "\---------r"`" == "" ]
+do
+   sleep 5
+done
+
+cd $datatapepath >> $logfile 2>&1
+
+# if drive is ready begin reading; for tapes > 3MG432 the block size has changed
+if [ "`samcmd s | grep /dev/rmt/${drive}cbn | grep "\---------r"`" == "" ]
+then
+   echo "Drive $drive is not ready. Something went wrong... aborting." >> $logfile 2>&1
+   set_state on $drive
+   exit
+else
+   if [ "$number" -gt "432" ]
+   then
+      (time star -b 1024 --exclude=ccdata/* --exclude=cacodata/* --exclude=drivelogs/* --exclude=*.root --exclude=*.pdf --exclude=*.gif --exclude=*.ps --exclude=*.txt -xvf /dev/rmt/${drive}cbn) >> $logfile 2>&1 ; set_state on $drive
+   else
+      (time star --exclude=ccdata/* --exclude=cacodata/* --exclude=drivelogs/* --exclude=*.root --exclude=*.pdf --exclude=*.gif --exclude=*.ps --exclude=*.txt -xvf /dev/rmt/${drive}cbn) >> $logfile 2>&1 ; set_state on $drive
+   fi
+   echo "Unloading tape $tape..." >> $logfile 2>&1
+fi
+
+echo -e "\nPerforming md5sum check. This will also take some hours." >> $logfile 2>&1
+date >> $logfile 2>&1
+${mars}/datacenter/scripts/checkmd5sum $tape
+date >> $logfile 2>&1
+md5=`cat /home/lapalma/tapecont/cont/muxdata/checksums/tape_${tape}L?.log | grep "Number of checked files matches. Files are ready."`
+
+if [ "$md5" = "" ]
+then
+   echo "md5sum check failed! Please check what happened (see /home/lapalma/tapecont/cont/muxdata/checksums/tape_${tape}L*.md5.*). Exiting now." | tee -a $logfile 2>&1
+   exit
+else
+   echo "files could be extracted without errors" >> $logfile 2>&1
+
+   # if movingrawfiles is not running change the file attributes, but only for the current tape
+   if ! [ -f /magic/datacenter/locks/lock-movingrawfiles*.txt ]
+   then
+      days=`grep "muxdata/...._.._.." /home/lapalma/tapecont/cont/muxdata/tape_${tape}L?.log | cut -d/ -f2 | sort -u`
+      for day in ${days[@]}
+      do
+         chmod -R g+w  ${datatapepath}/muxdata/$day >> $logfile 2>&1
+      	 chgrp -R auto ${datatapepath}/muxdata/$day >> $logfile 2>&1
+   	 chown -R tape ${datatapepath}/muxdata/$day >> $logfile 2>&1
+      done
+   fi
+fi
+
+# move the raw files if neither movingrawfiles nor filesondisk is running
+wait=1
+if ! [ -f /magic/datacenter/locks/lock-movingrawfiles*.txt ] && ! [ -f /magic/datacenter/locks/lock-filesondisk.txt ]
+then
+   #echo "Moving raw files from $tapepath to /data. This may take some hours if moving from ${magictapepath}. Please stand by." >> $logfile 2>&1
+   echo -e "\nMoving raw files from $datatapepath to /data. This may take some hours if moving from ${magictapepath}. Please stand by." >> $logfile 2>&1
+   date >> $logfile 2>&1
+   ssh -nx operator@dc07 'cd' $mars ' ; export AUTOMATIONSETUP=wue.magic.data ; '${mars}'/datacenter/scripts/movingrawfiles' >> $logfile 2>&1
+   date >> $logfile 2>&1
+   echo "Moving tape $tape to the export slots." >> $logfile 2>&1
+   #determine slot again, the tape might have been moved manually to another slot
+   tapeslot=`samcmd v 100 | grep "$tape " | cut -c-4 | sed -e 's/ //g'`
+   samcmd export 100:$tapeslot
+else
+   while [ $wait -lt 10 ]
+   do
+      echo "movingrawfiles or filesondisk is running -> sleeping 60 s" >> $logfile 2>&1
+      let wait++
+      sleep 60
+      if [ $wait == 10 ]
+      then
+         echo "Tried 10 times to launch movingrawfiles without avail. Finishing now." >> $logfile 2>&1
+         echo "Moving tape $tape to the export slots." >> $logfile 2>&1
+	 #determine slot again, the tape might have been moved manually to another slot
+	 tapeslot=`samcmd v 100 | grep "$tape " | cut -c-4 | sed -e 's/ //g'`
+   	 samcmd export 100:$tapeslot
+         echo -e "\nTape $tape read but the files have NOT been moved. You will have to do it manually. The tape has been exported. Have a nice day." | tee -a $logfile 2>&1
+         date >> $logfile 2>&1
+         exit
+      fi
+   done
+fi
+
+echo -e "\nTape $tape read and files successfully moved. The tape has been exported. Have a nice day." | tee -a $logfile 2>&1
+date >> $logfile 2>&1
Index: branches/Mars_McMismatchStudy/datacenter/scripts/rmlocks
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/rmlocks	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/rmlocks	(revision 17960)
@@ -0,0 +1,62 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script is removing lock files which are older than 12 hours. 
+# 
+# Each process in the automatic analysis is writing a lock file. As these 
+# processes are launched with condor, they are stopped after 12 hours, if 
+# they are still running. In this case the lock files are not removed. 
+# 
+# By comparing the date of the lock file and the current date, the 
+# running time of a process is determined and if it is bigger than 12 
+# hours (which means that the process has been already kill by condor) the 
+# lock file is removed
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+
+files=`ls $lockpath/* 2>/dev/null`
+
+for file in ${files[@]}
+do 
+   filedate=`date +%Y%j%H%M -r $file`
+   #date to compare: now - 12hours
+   compdate=`date +%Y%j%H%M --date="-12hour"`
+
+   if [ $compdate -gt $filedate ]
+   then 
+      printprocesslog "WARN lockfile $file is older than 12 hours"
+#      printprocesslog "INFO removing file $file"
+#      rm -v $file
+#      echo "date:  "$filedate
+#      echo "comp:  "$compdate
+#      date
+   fi
+done
+
+printprocesslog "INFO finished $0"
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/run.condor
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/run.condor	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/run.condor	(revision 17960)
@@ -0,0 +1,14 @@
+copy_to_spool = false
+Universe      = vanilla
+Executable    = $(path)/$(prog)
+Arguments     = $(args)
+Log           = condor-$(date).log
+output        = log-$(date).log
+error         = error-$(date).log
+notification  = Error
+environment   = AUTOMATIONSETUP=$(automationsetup)
+
+Initialdir = $(dir)
+
+Queue $(num)
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runcallisto
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runcallisto	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runcallisto	(revision 17960)
@@ -0,0 +1,165 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script is launching the calibration of sequences. 
+# 
+# As callisto takes some time, only one sequence is processed at once. 
+# First the script gets a sequence number from the database, for which 
+# the calibration has to be done (function gettodo). After setting the 
+# status in the database (set fStartTime to know, that the sequence is 
+# already being processed), the sequence is calibrated and the merpp 
+# update is done. Afterwards the status in the database is updated 
+# according to the return value of the program. In case one of the merpp 
+# update failes, also the corresponding runnumber is inserted into the 
+# database. 
+# The important INFOs, WARNings and ERRORs are written not only to the 
+# scriptlog but also to the processlog. 
+# 
+# The callisto.rc files are stored in the setup directory
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=callisto
+column=fCallisto
+
+set -C
+
+scriptlog=$runlogpath/run$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# get sequence # 
+gettodo "1" >> $scriptlog 2>&1
+sequence=${primaries[0]}
+telnum=${primaries[1]}
+
+# lock sequ for cal
+lockfile=$lockpath/lock-$table-$column-$sequence.txt
+checklock >> $scriptlog 2>&1
+
+cd $mars
+
+# run calibration for sequence
+echo "run $program for sequence $sequence..." >> $scriptlog 2>&1
+printprocesslog "INFO starting $program for sequence $sequence"
+no=`printf %08d $sequence | cut -c 0-4`
+no2=`printf %08d $sequence`
+sequfile="$sequpath/$no/sequence$no2.txt"
+
+outpath="$datapath/$program/$no/$no2"
+makedir $outpath >> $scriptlog 2>&1
+
+# define callisto.rc files
+callistorcnew=$setuppath/$program/callisto.rc
+callistorcmux=$setuppath/$program/callisto_mux.rc
+
+# find callisto.rc file
+if [ -e $outpath/callisto.rc ]
+then
+   echo "found $program.rc in $outpath -> using this " >> $scriptlog 2>&1
+   callistorcseq=$outpath/callisto.rc
+else
+   echo "no $program.rc found in $outpath -> making link " >> $scriptlog 2>&1
+   if [ $sequence -gt 200000 ]
+   then
+      ln -vs $callistorcmux $outpath/callisto.rc >> $scriptlog 2>&1
+   else
+      ln -vs $callistorcnew $outpath/callisto.rc >> $scriptlog 2>&1
+   fi
+   callistorcseq=$outpath/callisto.rc
+fi
+
+# lock sequ for zipping
+lockfile=$lockpath/calzip${sequence}-${telnum}.txt
+# if lockfile is already existing, 1 is returned
+if ! checklock return 1 >> $scriptlog 2>&1
+then
+   # reset lockfile name
+   lockfile=$lockpath/lock-$table-$column-$sequence.txt
+   finish >> $scriptlog 2>&1
+fi
+
+setstatus "start" >> $scriptlog 2>&1
+
+# stage the needed files; to be removed as soon as the correct stub file size has been determined
+echo "staging files:" >> $scriptlog 2>&1
+
+echo 'root -q -b $macrospath/stage.C\("\"$sequfile\""\) | tee -a $scriptlog | intgrep' >> $scriptlog 2>&1 
+check0=`root -q -b $macrospath/stage.C\("\"$sequfile\""\) | tee -a $scriptlog | intgrep`
+
+case $check0 in
+   0)   echo " check0=$check0 -> everything ok -> files staging..." >> $scriptlog 2>&1 
+        printprocesslog "INFO staging files started for $sequence"
+        ;;
+   *)   echo " check0=$check0 -> an error occured..." >> $scriptlog 2>&1 
+        printprocesslog "ERROR getting sequence $sequence"
+        check="no"
+        ;;
+esac
+
+
+echo "./callisto -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --out=$outpath --config=$callistorcseq $sequfile  2>> $scriptlog > /dev/null" >> $scriptlog 2>&1
+./callisto -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --out=$outpath --config=$callistorcseq $sequfile  2>> $scriptlog > /dev/null
+check1=$?
+
+# remove lockfile for zip and reset lockfile name
+rm -v $lockfile >> $scriptlog 2>&1
+lockfile=$lockpath/lock-$table-$column-$sequence.txt
+
+case $check1 in
+   0)   echo " check1=$check1 -> everything ok -> doing update..." >> $scriptlog 2>&1
+        printprocesslog "INFO $program finished successfully for sequence $sequence"
+
+        printprocesslog "INFO starting merpp/ccupdate for sequence $sequence"
+
+        # updated calibrated data files with the information from the cc and caco files
+        echo "./merpp -v3 --log=$outpath/merpp$no2.log --html=$outpath/merpp$no2.html --auto-time-stop $sequfile $outpath 2>> $scriptlog> /dev/null" >> $scriptlog 2>&1
+        ./merpp -v3 --log=$outpath/merpp$no2.log --html=$outpath/merpp$no2.html --auto-time-stop $sequfile $outpath 2>> $scriptlog > /dev/null
+        check2=$?
+
+        case $check2 in
+           0)   echo " check2=$check2 -> everything ok, merpp/ccupdate worked -> continue" >> $scriptlog 2>&1
+                printprocesslog "INFO merpp/ccupdate of sequence $sequence sucessfull"
+                ;;
+           *)   echo " check2=$check2 -> ERROR -> merpp/ccupdate $sequence failed" >> $scriptlog 2>&1
+                printprocesslog "ERROR merpp/ccupdate of sequence $sequence failed"
+                com=$Fmerppcc
+                check=$check2
+#                comadd=$runno
+                ;;
+        esac
+        ;;
+   *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+        printprocesslog "ERROR $program failed for sequence $sequence (return code $check1)"
+        com=$Fcallisto
+        check=$check1
+        ;;
+esac
+
+setstatus "stop"  >> $scriptlog 2>&1
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runcallisto_mc
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runcallisto_mc	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runcallisto_mc	(revision 17960)
@@ -0,0 +1,90 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  07/2010 <mailto:daniela.dorner@unige.ch>
+#              Christian Farnier 07/2010 <mailto:christian.farnier@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This script is launching the calibration of mc sequences. 
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=callisto
+step=Callisto
+
+set -C
+
+# get sequence # 
+numchanged=0
+while (( 0 < 21 ))
+do 
+   if ! [ $numchanged -eq 1 ]
+   then 
+      if ! [ "$sequence" = "" ] && ! [ "$cereskey" = "" ]
+      then
+         printprocesslog "INFO $program for sequence $sequence cereskey $cereskey is already running => request new number "
+      fi
+      gettodo "1" 
+      sequence=${primaries[0]}
+      cereskey=${primaries[1]}
+      if [ "$sequence" = "" ] || [ "$cereskey" = "" ]
+      then
+         printprocesslog "INFO nothing to do for $program "
+      fi
+   else
+      printprocesslog "INFO starting $program for sequence $sequence cereskey $cereskey"
+      break
+   fi
+   setstatus "start"
+done
+
+cd $mars
+
+# run calibration for sequence
+
+# define files and paths
+sequfile="$mcsequpath/`printf %08d $sequence | cut -c 1-4`/sequence`printf %08d $sequence`.txt"
+outpath=$mcpath/$program/`printf %03d $cereskey`/`printf %08d $sequence | cut -c 1-4`/`printf %08d $sequence | cut -c 5-8`
+makedir $outpath
+log=$outpath/$program`printf %08d $sequence`
+callistorc=$setuppath/$program/`printf %03d $cereskey`/callisto.rc
+inpath=$mcpath/ceres/`printf %03d $cereskey`/`printf %08d $sequence | cut -c 1-4`/`printf %08d $sequence | cut -c 5-8`
+
+command="./callisto -b -q -v4 -f --out=$outpath --ind=$inpath --log=$log.log --html=$log.html --config=$callistorc $sequfile"
+printprocesslog "INFO executing "$command
+$command
+check1=$?
+
+case $check1 in
+   0)  printprocesslog "INFO $program finished successfully for sequence $sequence cereskey $cereskey (return code $check1)"
+       ;;
+   *)  printprocesslog "ERROR $program failed for sequence $sequence cereskey $cereskey (return code $check1)"
+       check=$check1
+       ;;
+esac
+
+setstatus "stop"
+
+finish
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runcamera
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runcamera	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runcamera	(revision 17960)
@@ -0,0 +1,122 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2007 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script runs the reflector.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=camera
+column=fCameraFileAvail
+
+set -C
+
+# printing input card to stdout
+function printinputcard()
+{
+   echo $cameraversion
+   echo "ct_num 1"
+   echo "ct_geom 1"
+   echo "qe_file 0 $detectordir/Data/qe-emi-coat.RFL.dat"
+   echo "input_file 0 "$mcpath"/reflector/"$date"/"$infile
+   echo "data_file $outpath/"`echo $infile | sed -e 's/rfl/dat/'`
+   echo "root_file $outpath/"`echo $infile | sed -e 's/rfl/root/'`
+   echo "trigger_prop 3.0 0.25 1.0 2.0"
+   echo "trigger_single 0 4 4 2"
+   echo "nsb_on"
+   echo "nsb_mean 0.178 50"
+   echo "fadc_noise 1.3 2.4 1."
+   echo "sigma_xy_cm_spot "$spotsize
+   echo "mirror_fraction 0 0.73"
+   echo "seeds "$seeds
+   echo "nsb_directory $detectordir/StarLight/inner/"
+   echo "nsb_dir_outer $detectordir/StarLight/outer/"
+   echo "fadc_prop 1 7.8 5.0"
+   echo "fadc_outer 1 3.2 5.0"
+   echo "write_McTrig"
+   echo "write_McFadc"
+   echo "end_file"
+}
+
+
+# get sequence # 
+gettodo 
+run=$process
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$sequence.txt
+checklock 
+
+printprocesslog "INFO starting $program for run $run"
+
+setstatus "start" 
+
+printprocesslog "INFO create input card... "
+
+# get values for inputcard
+query="SELECT fMCRunNumber FROM MCRunData where fMCRunNumber="$run
+reflectorrunno=`sendquery`
+query="SELECT DATE_FORMAT(fRunStart, '%Y/%m/%d') FROM MCReflectorRunData where fReflectorRunNumber="$reflectorrunno
+date=`sendquery`
+query="SELECT fParticleTypeName FROM MCCorsikaRunData "
+query=$query" LEFT JOIN ParticleType ON MCCorsikaRunData.fParticleTypeKEY=ParticleType.fParticleTypeKEY "
+query=$query" LEFT JOIN MCRunData ON MCCorsikaRunData.fCorsikaRunNumber=MCRunData.fCorsikaRunNumber "
+query=$query" WHERE fMCRunNumber="$run
+particle=`sendquery`
+outpath=$mcpath"/"$program"/"$date
+date2=`echo $date | sed -e 's/\///g'`
+infile=$date2"_"`printf %06d $reflectorrunno`"_"$particle".rfl"
+query="SELECT fAdditionalSpotSize FROM MCRunData where fMCRunNumber="$run
+spotsize=`sendquery`
+query="SELECT fCameraSeed, fCameraSeed+1 FROM MCRunData where fMCRunNumber="$run
+seeds=`sendquery`
+
+logfile=$outpath/$program"-"`printf %06d $run`".log"
+makedir $outpath 
+
+cd $detectordir/Camera
+
+echo "INPUTCARD:" >| $logfile 2>&1
+printinputcard >> $logfile 2>&1
+echo "" >> $logfile 2>&1
+echo "" >> $logfile 2>&1
+printinputcard | ./camera >> $logfile 2>&1
+
+check1=$?
+
+case $check1 in
+   0)   printprocesslog "INFO $program finished successfully for sequence $sequence (check1=$check1)"
+        ;;
+   *)   printprocesslog "ERROR $program failed for sequence $sequence (check1=$check1)"
+        com=$Fcamera
+        check=$check1
+        ;;
+esac
+
+setstatus "stop" 
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runceres
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runceres	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runceres	(revision 17960)
@@ -0,0 +1,124 @@
+#!/bin/bash
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  06/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This script is launching ceres for corsika runs. 
+# 
+# The ceres.rc and other setup files are stored in the setup directory.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=ceres
+step=Ceres
+
+set -C
+
+# get run # 
+numchanged=0
+while (( 0 < 21 ))
+do 
+   if ! [ $numchanged -eq 1 ]
+   then 
+      if ! [ "$run" = "" ] && ! [ "$cereskey" = "" ]
+      then
+         printprocesslog "INFO $program for run $run cereskey $cereskey is already running => request new number "
+      fi
+      gettodo "1" 
+      run=${primaries[0]}
+      cereskey=${primaries[1]}
+      if [ "$run" = "" ] || [ "$cereskey" = "" ]
+      then
+         printprocesslog "INFO nothing to do for $program "
+      fi
+   else
+      printprocesslog "INFO starting $program for run $run cereskey $cereskey"
+      break
+   fi
+   setstatus "start"
+done
+
+cd $mars
+
+# run ceres for run
+
+setupfile=$setuppath/$program/`printf %03d $cereskey`/ceres.rc
+
+query="SELECT fRunTypeKEY FROM CeresInfo WHERE fRunNumber="$run" AND fCeresSetupKEY="$cereskey" GROUP BY fRunNumber"
+runkey=`sendquery`
+
+case $runkey in 
+   2) printprocesslog "INFO run $run is a data run (key="$runkey")"
+      printprocesslog "INFO getting file numbers for run "$run
+      query="SELECT CONCAT('"$mcpath"/corsika/', LEFT(LPAD(CeresInfo.fRunNumber, 8, '0'), 4),"
+      query=$query" '/', RIGHT(LPAD(CeresInfo.fRunNumber, 8, '0'), 4), '/cer000', "
+      query=$query" RIGHT(LPAD(CeresInfo.fFileNumber, 6, '0'), 3)) from CeresInfo "
+      query=$query" WHERE fRunNumber="$run" AND fCeresSetupKEY="$cereskey
+      inputfiles=`sendquery`
+      outpath=$mcpath/ceres/`printf %03d $cereskey`/`printf %08d $run | cut -c 1-4`/`printf %08d $run | cut -c 5-8`
+      makedir $outpath
+      log=$outpath/ceres`printf %08d $run `
+      command="./ceres -b -q -f --config=$setupfile --out=$outpath --log=$log.log --html=$log.html --run-number=$run $inputfiles"
+      printprocesslog "INFO executing "$command
+      $command
+      check1=$?
+      ;;
+   3) printprocesslog "INFO run $run is a pedestal run (key="$runkey")"
+      drun=`echo "$run + 2 " | bc -l`
+      outpath=$mcpath/ceres/`printf %03d $cereskey`/`printf %08d $drun | cut -c 1-4`/`printf %08d $drun | cut -c 5-8`
+      makedir $outpath
+      log=$outpath/ceres`printf %08d $run `
+      command="./ceres -b -q -f --config=$setupfile --out=$outpath --log=$log.log --html=$log.html --run-number=$run pedestal"
+      printprocesslog "INFO executing "$command
+      $command
+      check1=$?
+      ;;
+   4) printprocesslog "INFO run $run is a calibration run (key="$runkey")"
+      drun=`echo "$run + 1 " | bc -l`
+      outpath=$mcpath/ceres/`printf %03d $cereskey`/`printf %08d $drun | cut -c 1-4`/`printf %08d $drun | cut -c 5-8`
+      makedir $outpath
+      log=$outpath/ceres`printf %08d $run `
+      command="./ceres -b -q -f --config=$setupfile --out=$outpath --log=$log.log --html=$log.html --run-number=$run calibration"
+      printprocesslog "INFO executing "$command
+      $command
+      check1=$?
+      ;;
+   *) printprocesslog "WARN not valid fRunTypeKEY ("$runkey") was queried from the DB."
+      check="no"
+      ;;
+esac
+
+case $check1 in
+   0)   printprocesslog "INFO $program finished successfully for run $run, cereskey $cereskey, runtype $runkey (check1=$check1)"
+        ;;
+   *)   printprocesslog "ERROR $program failed for run $run, cereskey $cereskey, runtype $runkey (check1=$check1)"
+        check=$check1
+        ;;
+esac
+
+setstatus "stop"
+
+finish
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runchimp
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runchimp	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runchimp	(revision 17960)
@@ -0,0 +1,97 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  04/2009 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+
+rootsys=/opt/root5.20.x86_64
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=chimp
+column=fChimp
+chimpdir=/home/dorner/Chimp
+export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$chimpdir/hessioxxx/lib:.
+
+set -C
+
+node=`echo $HOSTNAME | sed -e 's/compute-0-//' -e 's/[.]local//'`
+#printprocesslog "INFO $program is running on node $node"
+# get run # 
+gettodo "1" $node
+run=${primaries[0]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$run.txt
+checklock 
+
+printprocesslog "INFO starting $program for run $run"
+
+#get particle for file name
+particles[1]="gamma"
+particles[14]="proton"
+particles[6]="muon"
+particles[3]="electron"
+query="select fParticleTypeKEY from MCRunData where fMCRunNumber=$run"
+key=( `mysql -P 3306 -u operator --password=Ics+eMM! --host=mysql.isdc.unige.ch CTA_MC -s -e "$query"` )
+particle=${particles[$key]}
+infile=$mcpath/simtel/cta-ultra3/0.0deg/Data/${particle}_20deg_90deg_run`printf '%06d' ${run}`___cta-ultra3_desert.simtel.gz
+outfile=$mcpath/chimp/cta-ultra3/0.0deg/Data/${particle}_20deg_90deg_run`printf '%06d' ${run}`___cta-ultra3_desert.root
+outpath=$mcpath/chimp/cta-ultra3/0.0deg/Data
+logfile=$outpath/chimp_run`printf '%06d' ${run}`.log
+makedir $outpath
+chimppath=/home/dorner/data/chimp
+clusterchimppath=/state/cta/chimp
+makedir $chimppath
+
+
+setstatus "start" 
+
+cd $chimpdir
+
+printprocesslog "INFO ./chimp $infile >| $logfile 2>&1 "
+./chimp $infile >| $logfile 2>&1 
+check1=$?
+
+case $check1 in
+   0)   printprocesslog "INFO $program finished successfully for run $run (check1=$check1)"
+#        if ! cp $outfile $chimppath
+        if ! scp $outfile $clusterchimppath
+        then
+           printprocesslog "ERROR copying $outfile to $chimppath failed"
+           com=$Fchimpcp
+           check=2
+        else
+           printprocesslog "INFO copied $outfile successfully to $chimppath"
+        fi
+        ;;
+   *)   printprocesslog "ERROR $program failed for run $run (check1=$check1)"
+        com=$Fchimp
+        check=$check1
+        ;;
+esac
+
+setstatus "stop"
+
+finish
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runcorsika
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runcorsika	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runcorsika	(revision 17960)
@@ -0,0 +1,254 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2007 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This script runs corsika.
+# 
+
+if [ "$SOURCEFILEPATH" = "" ]
+then 
+   source `dirname $0`/sourcefile
+else
+   source $SOURCEFILEPATH/sourcefile
+fi
+printprocesslog "INFO starting $0"
+program=corsika
+step=Corsika
+
+set -C
+
+export FLUPRO=$corsikapath'/fluka2008_3'
+
+# printing input card to stdout
+function printinputcard()
+{
+   # Run number
+   echo "RUNNR "$file
+   # Starting event number
+   echo "EVTNR 1"
+   # Number of simulated events
+   echo "NSHOW "$numevts
+   # Seed values for simulation
+   echo "SEED "$seed1" 0 0 "
+   echo "SEED "$seed2" 0 0 "
+   echo "SEED "$seed3" 0 0 "
+   # Primary particle
+   echo "PRMPAR "$primparticle
+   echo "ERANGE "$erange
+   echo "ESLOPE "$slope
+   # Simulation range (theta, phi, view cone, starting altitude)
+   echo "THETAP "$zdrange
+   echo "PHIP "$azrange
+   echo "VIEWCONE 0. "$viewconemax
+   echo "FIXCHI "$startalt
+   # Observation level, magnetic field, atmosphere
+   echo "OBSLEV "$obslev".E2"
+   # From www.noaa.gov/geomagmodels roughly for January 2009. (was 29.5 and 23.0)
+   # MAGNET BX BZ (BX is the horizontal component (muT) to the x-direction of
+   # the detector, BZ is the vertical component (muT) downwards)
+   echo "MAGNET "$magnet
+   # Rotation angle between array x-direction and magnetic north direction
+   # positive if array x-direction points to the west
+   echo "ARRANG "$magnetrot
+   # Atmosphere (model, true/false for atmospheric refraction of cer-photons)
+   # Atmosphere read from atmprof11.dat
+   # My current understanding is that only refraction (bending of light
+   # but no absorption of photons is taken into account) setting T.
+   echo "ATMOSPHERE "$atm" T"
+
+   # Current boundaries in reflector program
+   # echo "ATMLAY 400000 1000000 4000000 10000000"
+
+   # Boundaries as determined by CORSIKA
+   # Until we can read the result from the corsika fit we fix the
+   # values which come out of the fit. This is not ideal but forces
+   # things to be consistent. Be careful is using a different model -
+   # the fit might not be ideal.
+   echo "ATMLAY 775000 1650000 5000000 10500000"
+
+   # Other parameters
+   echo "RADNKG 200.E2"
+   echo "ECUTS 0.3 0.3 0.02 0.02"
+   echo "ECTMAP 1.E4"
+   # Don't add muon particle data to output
+   echo "MUADDI F"
+   # Enable muon multiple scattering
+   echo "MUMULT T"
+   # Wavelength range (was originally 600)
+   echo "CWAVLG "$wavelengths
+   # MMCS
+   echo "CSCAT "$numreuse" 0. "$impactmax
+   # CORSIKA
+   # echo "CSCAT "$numreuse" "$impactmax" 0."
+   echo "CERSIZ 1."
+   # Write Cherenkov photons to cer-file
+   echo "CERFIL T"
+   # Number of telescopes
+   echo "CERTEL 1"
+   # MMCS
+   echo " 0. 0. 0. 0. 0. "$diameter" "$diameter
+   # CORSIKA (x, y, z, r)
+   # echo "TELESCOPE 0. 0. 0. "$diameter
+   # This keyword has no relevance but allows to store the 
+   # maximum simulated impact parameter. The "magic" is that
+   # ceres interpretes the third and fourth argument as
+   # maximum simulated impact if they are identical and
+   # the other four arguments are 1
+   # echo "CERARY 1 1 "$diameter" "$diameter" 1 1"
+   # How the longitudinal shower development is sampled
+   # echo "LONGI T 10. T F"
+   echo "LONGI F 20 0 F F"
+   # Maximum number of detailed particles to print
+   echo "MAXPRT 0"
+   # Suppress file with partciles reaching ground (DATnnnnnn)
+   # FIXME: Should we make this switchable by the database?
+   echo "PAROUT F F"
+   # Don't write a database file
+   echo "DATBAS F"
+   # Switch off all debugging output
+   echo "DEBUG F 6 F 1000000"
+   # Output path
+   echo "DIRECT "$outpath
+   # DIRECT /dev/null
+   # TELFIL filename
+   # TELFIL | gzip
+   # TELESCOPE X Y Z R
+   # User and host (for convenience)
+   echo "USER "`whoami`
+   echo "HOST "`hostname`
+   # End of input card
+   echo "EXIT"
+}
+
+
+# get run # and file #
+numchanged=0
+while (( 0 < 21 ))
+do 
+   if ! [ $numchanged -eq 1 ]
+   then 
+      if ! [ "$run" = "" ] && ! [ "$file" = "" ]
+      then
+         printprocesslog "INFO $program for run $run and file $file is already running => request new number "
+      fi
+      gettodo "1" 
+      run=${primaries[0]}
+      file=${primaries[1]}
+      if [ "$run" = "" ] || [ "$file" = "" ]
+      then
+         printprocesslog "INFO nothing to do for $program "
+      fi
+   else
+      printprocesslog "INFO starting $program for run $run and file $file"
+      break
+   fi
+   setstatus "start"
+done
+
+# running corsika
+printprocesslog "INFO run $program for run $run  and file $file" 
+printprocesslog "INFO create input card for run $run  and file $file" 
+
+# get values for inputcard
+query="SELECT fParticleTypeKEY FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+primparticle=`sendquery`
+query="SELECT fEnergyMin, fEnergyMax FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+erange=`sendquery`
+query="SELECT fNumEvents FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+numevts=`sendquery`
+query="SELECT fEnergySlope FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+slope=`sendquery`
+query="SELECT fZenithDistanceMin, fZenithDistanceMax FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+zdrange=`sendquery`
+# Change from the MARS definition (Az=90 -> East) to Corsika (Az=90 -> West)
+query="SELECT 180-fAzimuthMin, 180-fAzimuthMax FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+azrange=`sendquery`
+query="SELECT fCorsikaSeed1 FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+seed1=`sendquery`
+query="SELECT fCorsikaSeed2 FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+seed2=`sendquery`
+query="SELECT fCorsikaSeed3 FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+seed3=`sendquery`
+query="SELECT fImpactMax FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+impactmax=`sendquery`
+query="SELECT fViewConeMax FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+viewconemax=`sendquery`
+query="SELECT fStartingAltitude FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+startalt=`sendquery`
+query="SELECT fMirrorDiameter FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+diameter=`sendquery`
+query="SELECT fAtmosphericModelKEY FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+atm=`sendquery`
+query="SELECT fObsLevel FROM CorsikaInfo LEFT JOIN Observatory USING(fObservatoryKEY) WHERE fRunNumber=$run AND fFileNumber=$file"
+obslev=`sendquery`
+query="SELECT fMagnetBX, fMagnetBZ FROM CorsikaInfo LEFT JOIN Observatory USING(fObservatoryKEY) WHERE fRunNumber=$run AND fFileNumber=$file"
+magnet=`sendquery`
+query="SELECT fMagnetRotation FROM CorsikaInfo LEFT JOIN Observatory USING(fObservatoryKEY) WHERE fRunNumber=$run AND fFileNumber=$file"
+magnetrot=`sendquery`
+query="SELECT fWavelengthMin, fWavelengthMax FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+wavelengths=`sendquery`
+query="SELECT fNumReUseShowers FROM CorsikaInfo WHERE fRunNumber=$run AND fFileNumber=$file"
+numreuse=`sendquery`
+
+outpath=$mcpath"/"$program"/"`printf %08d $run | cut -c 1-4`/`printf %08d $run | cut -c 5-8`
+makedir $outpath 
+logfile=$outpath/cer000`printf %06d $file | cut -c 4-6`".log"
+
+cd $corsikapath
+
+printprocesslog "INFO executing 'printinputcard | ./cc6501p-linux >| $logfile 2>&1' in directory $corsikapath "
+printinputcard | ./cc6501p-linux >| $logfile 2>&1
+
+check1=$?
+case $check1 in
+   0)   printprocesslog "INFO $program finished successfully for run $run file $file (return code $check1)"
+        if [ $file -gt 999 ]
+        then 
+           corsikafilenew=$mcpath/$program/`printf %08d $run | cut -c 1-4`/`printf %08d $run | cut -c 5-8`/cer000`printf %06d $file | cut -c 4-6`
+           corsikafileold=$mcpath/$program/`printf %08d $run | cut -c 1-4`/`printf %08d $run | cut -c 5-8`/cer`printf %06d $file`
+           if ! mv $corsikafileold $corsikafilenew
+           then
+              printprocesslog "ERROR could not mv $corsikafileold to $corsikafilenew"
+              check=2
+           fi
+        fi
+        if ! grep 'END OF RUN' $logfile
+        then
+           printprocesslog "ERROR could not find 'END OF RUN' in $logfile => unknown error for run $run file $file "
+           check=2
+        fi
+        ;;
+   *)   printprocesslog "ERROR $program failed for run $run file $file (return code $check1)"
+        check=$check1
+        ;;
+esac
+
+# removing empty datnnnnnn file
+rm -f $outpath/dat`printf %06d $file`
+
+setstatus "stop" 
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runctastar
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runctastar	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runctastar	(revision 17960)
@@ -0,0 +1,92 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  04/2009 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+
+rootsys=/opt/root5.12.i386
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=ctastar
+column=fCTAStar
+bcnmars=/home/dorner/Mars.BCN.2009.03.27.cvs
+
+set -C
+
+node=`echo $HOSTNAME | sed -e 's/compute-0-//' -e 's/[.]local//'`
+printprocesslog "INFO $program is running on node $node"
+# get run # 
+gettodo "1" $node
+run=${primaries[0]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$run.txt
+checklock 
+
+printprocesslog "INFO starting $program for run $run"
+
+#get particle for file name
+particles[1]="gamma"
+particles[14]="proton"
+particles[6]="muon"
+particles[3]="electron"
+query="select fParticleTypeKEY from MCRunData where fMCRunNumber=$run"
+key=( `mysql -P 3306 -u operator --password=Ics+eMM! --host=mysql.isdc.unige.ch CTA_MC -s -e "$query"` )
+particle=${particles[$key]}
+infile=$mcpath/chimp/cta-ultra3/0.0deg/Data/${particle}_20deg_90deg_run`printf '%06d' ${run}`___cta-ultra3_desert.root
+outpath=$mcpath/star
+outfile=$outpath/${particle}_20deg_90deg_run`printf '%06d' ${run}`___cta-ultra3_desert_I.root
+starpath=/home/dorner/data/star
+makedir $starpath
+logfile=$outpath/CTAstar_run`printf '%06d' ${run}`.log
+makedir $outpath
+
+setstatus "start" 
+
+cd $bcnmars
+
+printprocesslog "INFO starting: root -q -b macros/CTAstar.C\("\"$infile\""\,"\"$outpath\""\) | tee $logfile | intgrep" 
+check1=`root -q -b macros/CTAstar.C\(\""$infile\""\,\""$outpath\""\) | tee $logfile | intgrep`
+
+case $check1 in
+   1)   printprocesslog "INFO $program finished successfully for run $run (check1=$check1)"
+        if ! cp $outfile $starpath
+        then
+           printprocesslog "ERROR copying $outfile to $starpath failed"
+           com=$Fctastarcp
+           check=2
+        else
+           printprocesslog "INFO copied $outfile successfully to $starpath"
+        fi
+        ;;
+   *)   printprocesslog "ERROR $program failed for run $run (check1=$check1)"
+        com=$Fctastar
+        check=$check1
+        ;;
+esac
+
+setstatus "stop"
+
+finish
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runganymed
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runganymed	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runganymed	(revision 17960)
@@ -0,0 +1,98 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script is launching ganymed for datasets.
+# 
+# As ganymed takes some time, only one dataset is processed at once. 
+# First the script gets a dataset number from the database, for which 
+# ganymed has to be done (function gettodo). After setting the status in 
+# the database (set fStartTime to know, that the dataset is already being 
+# processed), the background suppression is done for the dataset. 
+# Afterwards the status in the database is updated according to the return 
+# value of ganymed. 
+# The important INFOs, WARNings and ERRORs are written not only to the 
+# scriptlog but also to the processlog. 
+#
+# The ganymed.rc files are stored in the setup directory.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=ganymed
+column=fGanymed
+
+set -C
+
+scriptlog=$runlogpath/run$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# get dataset # 
+gettodo "1" >> $scriptlog 2>&1
+dataset=${primaries[0]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$dataset.txt
+checklock >> $scriptlog 2>&1
+
+cd $mars
+
+echo "run $program for dataset $dataset..." >> $scriptlog 2>&1
+printprocesslog "INFO starting $program for dataset $dataset"
+no=`printf %08d $dataset | cut -c 0-5`
+no2=`printf %08d $dataset`
+outpath="$datapath/$program/$no/$no2"
+makedir $outpath >> $scriptlog 2>&1
+
+datasetfile="$datasetpath/$no/dataset$no2.txt"
+# choose ganymed.rc file
+if grep 'WobbleMode:' $datasetfile >/dev/null
+then 
+   ganymedrc=$setuppath/ganymed/ganymed_wobble.rc
+else
+   ganymedrc=$setuppath/ganymed/ganymed_onoff.rc
+fi
+
+setstatus "start" >> $scriptlog 2>&1
+
+echo "./ganymed -b -q -v4 -f --ind=$datapath/star --ins=$sequpath --config=$ganymedrc --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --out=$outpath $datasetfile "  >> $scriptlog 2>&1
+./ganymed -b -q -v4 -f --ind=$datapath/star --ins=$sequpath --config=$ganymedrc --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --out=$outpath $datasetfile  2>> $scriptlog> /dev/null
+check1=$?
+
+case $check1 in
+   0)   echo " check1=$check1 -> everything ok " >> $scriptlog 2>&1 
+        printprocesslog "INFO $program finished successfully for dataset $dataset"
+        ;;
+   *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+        printprocesslog "ERROR $program failed for dataset $dataset (return code $check1)"
+        com=$Fganymed
+        check=$check1
+        ;;
+esac
+
+setstatus "stop" >> $scriptlog 2>&1
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runmccallisto
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runmccallisto	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runmccallisto	(revision 17960)
@@ -0,0 +1,117 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Daniel Hoehne-Moench  01/2009 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This script is launching the calibration of mc sequences. 
+# 
+# As callisto takes some time, only one sequence is processed at once. 
+# First the script gets a sequence number from the mc database, for which 
+# the calibration has to be done (function gettodo). After setting the 
+# status in the database (set fStartTime to know, that the sequence is 
+# already being processed), the sequence is calibrated. Afterwards 
+# the status in the mc database is updated according to the return value 
+# of the program.
+# The important INFOs, WARNings and ERRORs are written not only to the 
+# scriptlog but also to the processlog. 
+#
+# Atm the processing has to be done in a separate Mars directory because 
+# different sql.rc and steps.rc files are needed.
+# 
+# The callisto.rc files are stored in the setup directory
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=callisto
+column=fCallisto
+
+set -C
+
+scriptlog=$runlogpath/runmc$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# get sequence # 
+gettodo "1" >> $scriptlog 2>&1
+sequence=${primaries[0]}
+
+# lock sequ for cal
+lockfile=$lockpath/lock-$table-$column-$sequence.txt
+checklock >> $scriptlog 2>&1
+
+cd $mars
+
+# run calibration for sequence
+echo "run $program for mc sequence $sequence..." >> $scriptlog 2>&1
+printprocesslog "INFO starting $program for mc sequence $sequence"
+no=`printf %08d $sequence | cut -c 0-4`
+no2=`printf %08d $sequence`
+outpath="$mcpath/$program/$no/$no2"
+makedir $outpath >> $scriptlog 2>&1
+sequfile="$mcsequpath/$no/sequence$no2.txt"
+
+# define callisto.rc files
+callistorcnew=$setuppath/$program/callisto.rc
+callistorcmux=$setuppath/$program/callisto_mux.rc
+
+epoch=`grep Epoch $sequfile | cut -d: -f2 | grep Mux`
+# find callisto.rc file
+if [ -e $outpath/callisto.rc ]
+then
+   echo "found $program.rc in $outpath -> using this " >> $scriptlog 2>&1
+   callistorcseq=$outpath/callisto.rc
+else
+   echo "no $program.rc found in $outpath -> making link " >> $scriptlog 2>&1
+   if [ "$epoch" = "" ]
+   then
+      ln -vs $callistorcnew $outpath/callisto.rc >> $scriptlog 2>&1
+   else
+      ln -vs $callistorcmux $outpath/callisto.rc >> $scriptlog 2>&1
+   fi
+   callistorcseq=$outpath/callisto.rc
+fi
+
+primvar=$no2
+setstatus "start" >> $scriptlog 2>&1
+
+echo "./callisto -mc -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --out=$outpath --config=$callistorcseq $sequfile  2>> $scriptlog > /dev/null" >> $scriptlog 2>&1
+./callisto -mc -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --out=$outpath --config=$callistorcseq $sequfile  2>> $scriptlog > /dev/null
+check1=$?
+
+case $check1 in
+   0)   echo " check1=$check1 -> everything ok" >> $scriptlog 2>&1
+        printprocesslog "INFO $program finished successfully for mc sequence $sequence"
+        ;;
+   *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+        printprocesslog "ERROR $program failed for mc sequence $sequence (return code $check1)"
+        com=$Fmccallisto
+        check=$check1
+        ;;
+esac
+
+setstatus "stop"  >> $scriptlog 2>&1
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runmcstar
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runmcstar	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runmcstar	(revision 17960)
@@ -0,0 +1,117 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Stefan Ruegamer 08/2007 <mailto:snruegam@astro.uni-wuerzburg.de>
+#   Author(s): Daniel Hoehne   06/2008 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script is launching star for mc sequences.
+# 
+# As star takes some time, only one mc sequence is processed at once. 
+# First the script gets a sequence number from the database for which 
+# star has to be done (function gettodo). After setting the status in the 
+# database (set fStartTime; to know that the sequence is already being 
+# processed), the image parameters are calculated for the sequence. 
+# Afterwards the status in the database is updated according to the return 
+# value of star. 
+# The important INFOs, WARNings and ERRORs are written not only to the 
+# scriptlog but also to the processlog.
+#
+# Atm the processing has to be done in a separate Mars directory because 
+# different sql.rc and steps.rc files are needed.
+#
+# The star.rc files are taken from the datacenter/setup/star directory
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=star
+column=fStar
+
+set -C
+
+scriptlog=$runlogpath/runmc$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# get sequence # 
+gettodo "1" >> $scriptlog 2>&1
+sequence=${primaries[0]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$sequence.txt
+checklock >> $scriptlog 2>&1
+
+cd $mars
+
+echo "run $program for mc sequence $sequence..." >> $scriptlog 2>&1
+printprocesslog "INFO starting $program for mc sequence $sequence"
+no=`printf %08d $sequence | cut -c 0-4`
+no2=`printf %08d $sequence`
+outpath="$mcpath/$program/$no/$no2"
+inpath=`echo $outpath | sed -e 's/star/callisto/'`
+makedir $outpath >> $scriptlog 2>&1
+
+sequfile="$mcsequpath/$no/sequence$no2.txt"
+
+primvar=$no2
+setstatus "start" >> $scriptlog 2>&1
+
+#echo "staging files..." >> $scriptlog 2>&1
+#ssh -nx phoenix /opt/SUNWsamfs/bin/stage -V $inpath/19*_0*${run}_Y_*_E.root >> $scriptlog 2>&1
+
+
+# define star.rc files
+starrcnew=$setuppath/$program/star.rc
+starrcmux=$setuppath/$program/star_mux.rc
+
+epoch=`grep Epoch $sequfile | cut -d: -f2 | grep Mux`
+# link star.rc file
+echo "linking the star.rc file to $outpath" >> $scriptlog 2>&1
+if [ "$epoch" = "" ]
+then
+   ln -vsf $starrcnew $outpath/star.rc >> $scriptlog 2>&1
+else
+   ln -vsf $starrcmux $outpath/star.rc >> $scriptlog 2>&1
+fi
+starrcseq=$outpath/star.rc
+
+echo "./star -mc -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --ind=$inpath --out=$outpath $sequfile --config=$starrcseq 2>> $scriptlog> /dev/null" >> $scriptlog 2>&1
+./star -mc -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --ind=$inpath --out=$outpath $sequfile --config=$starrcseq 2>> $scriptlog> /dev/null
+check1=$?
+
+case $check1 in
+   0)   echo " check1=$check1 -> everything ok " >> $scriptlog 2>&1
+        printprocesslog "INFO $program finished successfully for mc sequence $sequence"
+        ;;
+   *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+        printprocesslog "ERROR $program failed for mc sequence $sequence"
+        com=$Fmcstar
+        check=$check1
+        ;;
+esac
+
+setstatus "stop" >> $scriptlog 2>&1
+
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runreflector
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runreflector	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runreflector	(revision 17960)
@@ -0,0 +1,127 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2007 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script runs the reflector.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=reflector
+column=fReflectorFileAvail
+
+set -C
+
+# printing input card to stdout
+function printinputcard()
+{
+   echo $reflectorversion
+   echo "verbose_level 4"
+   echo "seeds "$seeds
+   echo "fixed_target 0. 0. "
+   echo "telescopes_layout 1 1"
+   echo "telescope_position 0.0 0.0"
+   if [ $wobble -eq 2 ]
+   then 
+      echo "wobble_mode 1"
+   else
+      echo "wobble_mode 0"
+   fi
+   echo "ct_file $detectordir/Data/magic.def"
+   echo "reflectivity_file $detectordir/Data/reflectivity.dat"
+   echo "axisdev_file $detectordir/Data/axisdev.dat"
+   echo "output_file "$outfile
+   echo "atm_model ATM_MagicWinter"
+   echo "cer_files "
+   echo $infile
+}
+
+# get sequence # 
+gettodo "1" 
+run=${primaries[0]}
+# get reflector runnumber
+query="SELECT fReflectorRunNumber FROM MCRunData where fMCRunNumber="$run
+reflectorrunno=`sendquery`
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$reflectorrunno.txt
+checklock 
+
+printprocesslog "INFO starting $program for run $run"
+
+setstatus "start" 
+
+printprocesslog "INFO create input card... "
+
+# get values for inputcard
+query="SELECT fReflectorSeed, fReflectorSeed+1 FROM MCReflectorRunData where fReflectorRunNumber="$reflectorrunno
+seeds=`sendquery`
+query="SELECT fObservationModeKEY FROM MCReflectorRunData where fReflectorRunNumber="$reflectorrunno
+wobble=`sendquery`
+query="SELECT DATE_FORMAT(fRunStart, '%Y/%m/%d') FROM MCReflectorRunData where fReflectorRunNumber="$reflectorrunno
+date=`sendquery`
+query="SELECT fParticleTypeName FROM MCCorsikaRunData "
+query=$query" LEFT JOIN ParticleType ON MCCorsikaRunData.fParticleTypeKEY=ParticleType.fParticleTypeKEY "
+query=$query" LEFT JOIN MCReflectorRunData ON MCCorsikaRunData.fCorsikaRunNumber=MCReflectorRunData.fCorsikaRunNumber "
+query=$query" WHERE fReflectorRunNumber="$reflectorrunno
+particle=`sendquery`
+outpath=$mcpath"/"$program"/"$date
+date2=`echo $date | sed -e 's/\///g'`
+outfile=$outpath"/"$date2"_"`printf %06d $reflectorrunno`"_"$particle".rfl"
+query="SELECT fCorsikaRunNumber FROM MCReflectorRunData where fReflectorRunNumber="$reflectorrunno
+infile=$mcpath"/corsika/"$date"/cer"`printf %06d \`sendquery\``
+
+makedir $outpath 
+if ls $outfile >/dev/null 2>&1
+then
+   rm -v $outfile
+fi
+logfile=$outpath/$program"-"`printf %06d $reflectorrunno`".log"
+
+cd $detectordir/ReflectorII
+
+echo "INPUTCARD:" >| $logfile 2>&1
+printinputcard >> $logfile 2>&1
+echo "" >> $logfile 2>&1
+echo "" >> $logfile 2>&1
+printinputcard | ./reflector >> $logfile 2>&1
+
+check1=$?
+
+echo "the reflector returned: "$check1
+
+case $check1 in
+   0)   printprocesslog "INFO $program finished successfully for run $reflectorrunno (check1=$check1)"
+        ;;
+   *)   printprocesslog "ERROR $program failed for run $reflectorrunno (check1=$check1)"
+        com=$Freflector
+        check=$check1
+        ;;
+esac
+
+setstatus "stop" 
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runsimtel
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runsimtel	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runsimtel	(revision 17960)
@@ -0,0 +1,191 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of CheObs, the Modular Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appears in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  01/2009 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: CheObs Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This script runs corsika and simtelarray.
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=corsikasimtel
+column=fCorsikaSimTelarray
+
+# todo:
+# evtl trennung v corsika u simtel
+
+set -C
+# set write permission for group
+umask 002
+
+simdir=$mcpath/software/simtel
+
+export CORSIKA_PATH=$simdir/corsika-6970/run/
+export SIM_TELARRAY_PATH=$simdir/sim_telarray
+#export SIM_TELARRAY_PATH=$simdir
+export SIM_TELARRAY_RUN_PATH=$simdir/sim_telarray
+export MCDATA_PATH=$mcpath
+export CORSIKA_DATA="${MCDATA_PATH}/corsika"
+export SIM_TELARRAY_DATA="${MCDATA_PATH}/simtel"
+export LD_LIBRARY_PATH=$simdir/hessioxxx/lib/
+
+# printing input card to stdout
+function printinputcard()
+{
+   # Run number
+   echo "RUNNR "$run
+   # Number of simulated events
+   echo "NSHOW "$numevts
+   # Seed values for simulation
+   echo "SEED "$run" 0 0 "
+   echo "SEED "$run" 0 0 "
+   echo "SEED "$run" 0 0 "
+   echo "SEED "$run" 0 0 "
+   # Observation level
+   echo "OBSLEV "$obslev".E2"
+   # output directory
+   echo "DIRECT "$outpath"/ "
+   cat $inputcardpart
+}
+
+
+# get hostname
+prodhost=`echo $HOSTNAME | sed -e 's/compute-0-//' -e 's/[.]local//'`
+
+diskusage=( `df $mcpath | grep $mcpath ` )
+# continue only if more than 90 GB are left on /state/cta
+if [ ${diskusage[2]} -lt 90000000 ]
+then
+   printprocesslog "WARN less than 90 GB left on $mcpath on node $prodhost "
+   finish
+else
+   printprocesslog "INFO still ${diskusage[3]} left on $mcpath on node $prodhost "
+fi
+
+
+# get sequence # 
+gettodo "1" 
+run=${primaries[0]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$run.txt
+checklock 
+
+printprocesslog "INFO starting $program for run $run"
+
+# get values for inputcard
+query="SELECT fParticleTypeName FROM MCRunData LEFT JOIN ParticleType using (fParticleTypeKEY) where fMCRunNumber="$run
+primparticle=`sendquery`
+query="SELECT fNumEvents FROM MCRunData where fMCRunNumber="$run
+numevts=`sendquery`
+
+# get observation level for the script to be begun for sim_telarray
+query="SELECT fObsLevel FROM MCRunData WHERE fMCRunNumber="$run
+obslev=`sendquery`
+# export $OBSLEVEL for the script sim_telarray/cta-ultra2_run.sh or sim_telarray/cta-ultra2-moon_run.sh
+export OBSLEVEL=$obslev
+
+# get moon condition for the script to be begun for sim_telarray
+query="SELECT fMoonConditionKEY FROM MCRunData where fMCRunNumber="$run
+mooncase=`sendquery`
+# export $moon for the script sim_telarray/multi/multi_cta-ultra3.cfg
+case $mooncase in
+   0)   export moon=''
+        ;;
+   1)   export moon="-moon"
+        ;;
+   *)   printprocesslog "ERROR $program failed to retrieve the moon condition"
+        finish
+        ;;
+esac
+
+# for MC for 5at5
+if [ "$obslev" == "5000" ]
+then
+   export moon="-5at5"
+   inputcardpart=$setuppath/INPUTS_CTA_ULTRA3_${primparticle}_part_5at5
+else
+   inputcardpart=$setuppath/INPUTS_CTA_ULTRA3_${primparticle}_part
+fi
+
+
+# path and logs
+outpath=$mcpath"/corsika/"`printf %06d $run`
+logfile=$outpath/$program"-"`printf %06d $run`".log"
+inputcard=$outpath/$program"-"`printf %06d $run`".card"
+makedir $outpath 
+
+# insert host into db
+query="UPDATE MCRunProcessStatus set fProductionHostKEY=$prodhost where fMCRunNumber="$run
+if ! sendquery $query
+then
+   printprocesslog "inserting host failed"
+   finish
+fi
+
+setstatus "start" 
+
+cd $CORSIKA_PATH
+
+printprocesslog "INFO create inputcard for run $run"
+
+#
+# starting corsika with pipe to simtelarray
+#  in the inputcard the path to the script is defined:
+#     ${SIM_TELARRAY_PATH}/run_sim_cta-ultra3 (i.e. run_sim_hessarray_generic)
+#  in this script a setup file is chosen:
+#     multicfg="multi/multi_${cfg}.cfg"
+#  in multi/multi_cta-ultra3.cfg one can choose whether to store 
+#     the corsika files:
+#     gzip > ${CORSIKA_DATA}/run${CORSIKA_RUN}.corsika.gz
+#  and multi/multi_cta-ultra3.cfg starts the script
+#     ${SIM_TELARRAY_PATH}/cta-ultra2_run.sh (i.e. generic_run.sh)
+#     in which e.g. path and file name are set
+#
+printinputcard >| $inputcard
+#./corsika < $inputcard >| $logfile 2>&1
+./corsika6970Linux_QGSII_urqmd < $inputcard >| $logfile 2>&1
+check1=$?
+
+case $check1 in
+   0)   printprocesslog "INFO finished corsika and simtelarray without error (check1=$check1) "
+        if ! grep 'END OF RUN' $logfile
+        then
+           printprocesslog "ERROR could not find 'END OF RUN' in $logfile => unknown error for run $run"
+           com=$Fcorsikasimtel
+           check=2
+        else
+           printprocesslog "INFO $program finished successfully for mc run number $run"
+        fi
+        ;;
+   *)   printprocesslog "ERROR $program failed for mc run number $run (check1=$check1)"
+        com=$Fcorsikasimtel
+        check=$check1
+        ;;
+esac
+
+setstatus "stop"
+
+finish
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runstar
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runstar	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runstar	(revision 17960)
@@ -0,0 +1,96 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Stefan Ruegamer 08/2007 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script is launching star for sequences.
+# 
+# As star takes some time, only one sequence is processed at once. 
+# First the script gets a sequence number from the database for which 
+# star has to be done (function gettodo). After setting the status in the 
+# database (set fStartTime; to know that the sequence is already being 
+# processed), the image parameters are calculated for the sequence. 
+# Afterwards the status in the database is updated according to the return 
+# value of star. 
+# The important INFOs, WARNings and ERRORs are written not only to the 
+# scriptlog but also to the processlog. 
+#
+# The star.rc files are taken from the datacenter/setup/star directory
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=star
+column=fStar
+
+set -C
+
+scriptlog=$runlogpath/run$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# get sequence # 
+gettodo "1" >> $scriptlog 2>&1
+sequence=${primaries[0]}
+telnum=${primaries[1]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$sequence.txt
+checklock >> $scriptlog 2>&1
+
+cd $mars
+
+echo "run $program for sequence $sequence..." >> $scriptlog 2>&1
+printprocesslog "INFO starting $program for sequence $sequence"
+no=`printf %08d $sequence | cut -c 0-4`
+no2=`printf %08d $sequence`
+outpath="$datapath/$program/$no/$no2"
+inpath=`echo $outpath | sed -e 's/star/callisto/'`
+makedir $outpath >> $scriptlog 2>&1
+
+sequfile="$sequpath/$no/sequence$no2.txt"
+
+setstatus "start" >> $scriptlog 2>&1
+
+echo "staging files..." >> $scriptlog 2>&1
+ssh -nx phoenix /opt/SUNWsamfs/bin/stage -V $inpath/20[01][0-9]*_0*${run}_Y_*.root >> $scriptlog 2>&1
+
+echo "./star -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --ind=$inpath --out=$outpath $sequfile 2>> $scriptlog> /dev/null" >> $scriptlog 2>&1
+./star -b -q -v4 -f --log=$outpath/$program$no2.log --html=$outpath/$program$no2.html --ind=$inpath --out=$outpath $sequfile 2>> $scriptlog> /dev/null
+check1=$?
+
+case $check1 in
+   0)   echo " check1=$check1 -> everything ok " >> $scriptlog 2>&1
+        printprocesslog "INFO $program finished successfully for sequence $sequence"
+        ;;
+   *)   echo " check1=$check1 -> ERROR -> step has to be repeated" >> $scriptlog 2>&1
+        printprocesslog "ERROR $program failed for sequence $sequence"
+        com=$Fstar
+        check=$check1
+        ;;
+esac
+
+setstatus "stop" >> $scriptlog 2>&1
+
+finish >> $scriptlog 2>&1
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runstar_mc
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runstar_mc	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runstar_mc	(revision 17960)
@@ -0,0 +1,88 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  07/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This script is launching star for mc sequences. 
+# 
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=star
+step=Star
+
+set -C
+
+# get sequence # 
+numchanged=0
+while (( 0 < 21 ))
+do 
+   if ! [ $numchanged -eq 1 ]
+   then 
+      if ! [ "$sequence" = "" ] && ! [ "$cereskey" = "" ]
+      then
+         printprocesslog "INFO $program for sequence $sequence cereskey $cereskey is already running => request new number "
+      fi
+      gettodo "1" 
+      sequence=${primaries[0]}
+      cereskey=${primaries[1]}
+      if [ "$sequence" = "" ] || [ "$cereskey" = "" ]
+      then
+         printprocesslog "INFO nothing to do for $program "
+      fi
+   else
+      printprocesslog "INFO starting $program for sequence $sequence cereskey $cereskey"
+      break
+   fi
+   setstatus "start"
+done
+
+cd $mars
+
+# run calibration for sequence
+
+# define files and paths
+sequfile="$mcsequpath/`printf %08d $sequence | cut -c 1-4`/sequence`printf %08d $sequence`.txt"
+outpath=$mcpath/$program/`printf %03d $cereskey`/`printf %08d $sequence | cut -c 1-4`/`printf %08d $sequence | cut -c 5-8`
+makedir $outpath
+log=$outpath/$program`printf %08d $sequence`
+inpath=$mcpath/callisto/`printf %03d $cereskey`/`printf %08d $sequence | cut -c 1-4`/`printf %08d $sequence | cut -c 5-8`
+
+command="./star -b -q -v4 -f --ind=$inpath --out=$outpath --log=$log.log --html=$log.html $sequfile"
+printprocesslog "INFO executing "$command
+$command
+check1=$?
+
+case $check1 in
+   0)  printprocesslog "INFO $program finished successfully for sequence $sequence cereskey $cereskey (return code $check1)"
+       ;;
+   *)  printprocesslog "ERROR $program failed for sequence $sequence cereskey $cereskey (return code $check1)"
+       check=$check1
+       ;;
+esac
+
+setstatus "stop"
+
+finish
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/runstereo
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/runstereo	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/runstereo	(revision 17960)
@@ -0,0 +1,111 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  04/2009 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+
+rootsys=/opt/root5.12.i386
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=ctastereo
+case $1 in 
+   2) column=fStereoB
+      Fctastereo=$FctastereoB
+      outpath=$mcpath/stereoB
+      stereopath=/home/dorner/data/stereoB
+      ;;
+   3) column=fStereoC
+      Fctastereo=$FctastereoC
+      outpath=$mcpath/stereoC
+      stereopath=/home/dorner/data/stereoC
+      ;;
+   7) column=fStereoG
+      Fctastereo=$FctastereoG
+      outpath=$mcpath/stereoG
+      stereopath=/home/dorner/data/stereoG
+      ;;
+   *) printprocesslog "ERROR Unknown commandline option $1"
+      finish
+      ;;
+esac
+bcnmars=/home/dorner/Mars.BCN.2009.03.27.cvs
+
+set -C
+
+node=`echo $HOSTNAME | sed -e 's/compute-0-//' -e 's/[.]local//'`
+printprocesslog "INFO $program (for column $column) is running on node $node"
+# get run # 
+gettodo "1" $node
+run=${primaries[0]}
+
+# lock sequ
+lockfile=$lockpath/lock-$table-$column-$run.txt
+checklock 
+
+printprocesslog "INFO starting $program for run $run"
+
+#get particle for file name
+particles[1]="gamma"
+particles[14]="proton"
+particles[6]="muon"
+particles[3]="electron"
+query="select fParticleTypeKEY from MCRunData where fMCRunNumber=$run"
+key=( `mysql -P 3306 -u operator --password=Ics+eMM! --host=mysql.isdc.unige.ch CTA_MC -s -e "$query"` )
+particle=${particles[$key]}
+infile=$mcpath/chimp/cta-ultra3/0.0deg/Data/${particle}_20deg_90deg_run${run}___cta-ultra3_desert_I.root
+inpath=$mcpath/star
+infile=$inpath/${particle}_20deg_90deg_run${run}___cta-ultra3_desert_I.root
+outfile=$outpath/${particle}_20deg_90deg_run${run}___cta-ultra3_desert_S.root
+makedir $stereopath
+logfile=$outpath/CTAstereo_run${run}.log
+makedir $outpath
+
+setstatus "start" 
+
+cd $bcnmars
+
+printprocesslog "INFO starting: root -q -b macros/CTAstereoSub.C\("\"$infile\""\,"\"$outpath"\"\,"$1"\) | tee $logfile | intgrep" 
+check1=`root -q -b macros/CTAstereoSub.C\(\""$infile\""\,\""$outpath\""\,$1\) 2>&1 | tee $logfile | intgrep`
+
+case $check1 in
+   1)   printprocesslog "INFO $program finished successfully for run $run (check1=$check1)"
+        if ! cp $outfile $stereopath
+        then
+           printprocesslog "ERROR copying $outfile to $starpath failed"
+           com=$Fctastereocp
+           check=2
+        else
+           printprocesslog "INFO copied $outfile successfully to $starpath"
+        fi
+        ;;
+   *)   printprocesslog "ERROR $program failed for run $run (check1=$check1)"
+        com=$Fctastereo
+        check=$check1
+        ;;
+esac
+
+setstatus "stop"
+
+finish
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/scriptlauncher
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/scriptlauncher	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/scriptlauncher	(revision 17960)
@@ -0,0 +1,99 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This a script, which launches other scripts
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0 $@"
+
+errorlog=$runlogpath/scriptlauncher-error`date +%F`.log
+scriptlog=$runlogpath/scriptlauncher`date +%F`.log
+
+echo `date`": starting $0 $@" >> $scriptlog 2>&1
+
+path=`dirname $0`
+date=`date +%Y-%m-%d`
+
+num=$#
+echo "$num scripts have to be launched" >> $scriptlog 2>&1
+i=1
+
+if echo $@ | grep "allatthesametime" >/dev/null 2>$errorlog
+then
+   all="yes"
+else
+   all="no"
+fi
+
+while [ $i -le $num ]
+do 
+   com=( )
+   prog=
+   if [ "$1" = "allatthesametime" ]
+   then
+      shift
+      i=`expr $i + 1`
+      continue
+   fi
+   com=( $1 )
+   prog=${com[0]}
+   if ! ls $path/${com[0]} >/dev/null 2>&1
+   then
+      echo "script $path/$1 does not exist." >> $scriptlog 2>&1
+      shift
+      i=`expr $i + 1`
+      continue
+   fi
+   if [ `echo $1 | wc -w` -gt 1 ]
+   then
+      unset com[0]
+      arguments="${com[@]}"
+   fi
+   echo " launching $1..." >> $scriptlog 2>&1
+   echo "$condorpath/condor_submit -a path=$path -a prog=$prog -a args=\"$arguments\" -a date=$date -a dir=$runlogpath -a automationsetup=$AUTOMATIONSETUP $path/run.condor 2>> $errorlog | grep 'submitted to cluster' | cut -dr -f2" >> $scriptlog 2>&1
+   pid=`$condorpath/condor_submit -a path=$path -a prog=$prog -a args="$arguments" -a date=$date -a dir=$runlogpath -a automationsetup=$AUTOMATIONSETUP $path/run.condor 2>> $errorlog | grep 'submitted to cluster' | cut -dr -f2`
+   if [ "$pid" = "" ]
+   then 
+      echo `date`" WARN condor is not working " >> $errorlog 2>&1
+      printprocesslog "WARN submitting $1 to condor failed"
+      shift
+      i=`expr $i + 1`
+      continue
+   fi
+   if [ "$all" = "no" ]
+   then
+      echo "  waiting for $1 to be done..." >> $scriptlog 2>&1
+      $condorpath/condor_wait $runlogpath/condor-$date.log $pid >/dev/null 2>$errorlog
+   fi
+   shift
+   i=`expr $i + 1`
+done
+echo `date`": all done/submitted." >> $scriptlog 2>&1
+echo "" >> $scriptlog 2>&1
+
+printprocesslog "INFO finished $0 $@"
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/setup.isdc.cta
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/setup.isdc.cta	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/setup.isdc.cta	(revision 17960)
@@ -0,0 +1,141 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2009 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+#
+
+if [ "$rootsys" = "" ]
+then 
+   rootsys=/opt/root5.20.x86_64
+fi
+if ! export | grep ROOTSYS | grep $rootsys  >|/dev/null
+then
+   export ROOTSYS=$rootsys
+   export PATH=$PATH:$ROOTSYS/bin
+   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib/root
+fi
+
+# queuing system
+queuesys=sge #isdc
+
+# logging and setup
+logpath=/share/cta/automation/autologs
+lockpath=/share/cta/automation/locks
+setuppath=/share/cta/automation/setup
+
+## paths of data
+#datapath=/magic/data
+#subsystempath=/magic/subsystemdata
+#sequpath=/magic/sequences
+#datasetpath=/magic/datasets
+
+# paths and setup for mc
+mcpath=/share/cta
+#mcrawpath=$mcpath/rawfiles
+#mcsequpath=$mcpath/sequences
+#corsikapath=/home/operator/Corsika/Mmcs6500/
+#detectordir=/home/msmeyer/MC/MagicSoft/Simulation/Detector
+#reflectorversion="reflector 0.7"
+#cameraversion="camera 0.8"
+#export FLUPRO=$corsikapath'/fluka2008_3'
+
+
+#webpath=/www/htdocs/datacenter
+
+
+# get paths for mars, macros and scripts
+mars=`dirname $0 | sed -e 's/\/datacenter\/scripts//'`
+macrospath=$mars/datacenter/macros
+scriptspath=$mars/datacenter/scripts
+# rcfiles
+# dependencies of steps
+steps=$mars/resources/steps_cta_new.rc
+# file with db information
+sqlrc=$mars/sql.rc
+
+
+#addresses to which the errors are sent
+erradrs="daniela.dorner@unige.ch" 
+#addresses to which the changes are sent
+adrs="daniela.dorner@unige.ch" 
+
+
+#setup for jobmanager
+sleeptime=30 #30
+sleeptimelimit=360 #360
+errorsleeptimedefault=60 #60
+max=50 #maximum number of processes for one script in case there are more than one and the others do not have anything to do
+totalmax=1600 #maximum number of processes (total) overwrites pnototal(we) in case it is smaller
+
+
+#
+# FIXME: 
+# max anz an prozessen setzen
+# besser Verhaeltnis zwischen den Prozessen und das am besten noch 
+# automatisch anpassen 
+# evtl noch maximale anz an callistos setzen
+# 
+
+#hour:            0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
+pnototal=(       1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 )
+pnototalwe=(     1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 )
+
+pnosimtel=(       50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 )
+pnosimtelwe=(     50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 )
+
+# restricted to nodes => numbers per node 
+pnochimp=(         2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnochimpwe=(       2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnoctastar=(       2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnoctastarwe=(     2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnostereob=(       2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnostereobwe=(     2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnostereoc=(       2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnostereocwe=(     2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnostereog=(       2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+pnostereogwe=(     2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ) 
+
+# set variables for jobmanager 
+#scripts=( "runsimtel" "runchimp" "runctastar" "runstereo 2" "runstereo 3" "runstereo 7" )
+#scriptscolname=( "fCorsikaSimTelarray" "fChimp" "fCTAStar" "fStereoB" "fStereoC" "fStereoG" )
+#pnosweek=( ${pnosimtel[@]}   ${pnochimp[@]}   ${pnoctastar[@]}   ${pnostereob[@]}   ${pnostereoc[@]}   ${pnostereog[@]} )
+#pnoswe=( ${pnosimtelwe[@]} ${pnochimpwe[@]} ${pnoctastarwe[@]} ${pnostereobwe[@]} ${pnostereocwe[@]} ${pnostereogwe[@]} )
+scripts=( "runsimtel" "runchimp" "runctastar" )
+scriptscolname=( "fCorsikaSimTelarray" "fChimp" "fCTAStar" )
+pnosweek=( ${pnosimtel[@]}   ${pnochimp[@]}   ${pnoctastar[@]} )
+pnoswe=( ${pnosimtelwe[@]} ${pnochimpwe[@]} ${pnoctastarwe[@]} )
+
+# number of script that are limited to a certain node
+#numrestrictedscripts=5
+numrestrictedscripts=2
+
+# set up for nodes 
+#  for processes that can run only on certain node
+#  db: fProductionHostKEY
+minnode=0
+maxnode=26
+excludednodes=( 7 14 23 )
Index: branches/Mars_McMismatchStudy/datacenter/scripts/setup.lp.fact
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/setup.lp.fact	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/setup.lp.fact	(revision 17960)
@@ -0,0 +1,114 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  06/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+#
+
+rootsys=/opt/root_v5.12.00f
+if ! export | grep $rootsys  >|/dev/null
+then
+   export ROOTSYS=$rootsys
+   export PATH=$PATH:$ROOTSYS/bin
+   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib
+fi
+
+# site
+processingsite=lp
+sitekey= # to be filled
+storagesite=wue
+
+# for db backup
+dbnames=( "mysql" "programoptions" "scheduling" "systemstatus" "postfix" "horde" "logbook" "factdata" )
+
+# queuing system
+# queuesys=condor # wuerzburg data center
+# condorpath=/usr/local/bin
+
+# logging and setup
+logpath=/home/fact/logs.automatic.processing/autologs
+lockpath=/home/fact/logs.automatic.processing/locks
+#setuppath=/magic/simulated/setup
+
+## paths of data
+#datapath=/magic/data
+#subsystempath=/magic/subsystemdata
+#sequpath=/magic/sequences
+#datasetpath=/magic/datasets
+
+## paths and setup for mc
+#mcpath=/magic/simulated
+#mcrawpath=$mcpath/rawfiles
+#mcsequpath=$mcpath/sequences
+#corsikapath=/home/montecarlo/MagicSoft/Simulation/Corsika/Mmcs6500
+#export FLUPRO=$corsikapath'/fluka2008_3'
+
+
+#webpath=/www/htdocs/datacenter
+
+# get paths for mars, macros and scripts
+#   in case the variable is not yet set
+if [ "$mars" == "" ]
+then 
+  mars=`dirname $0 | sed -e 's/\/datacenter\/scripts//'`
+fi
+macrospath=$mars/datacenter/macros
+scriptspath=$mars/datacenter/scripts
+# rcfiles
+# dependencies of steps
+steps=$mars/resources/steps_fact.rc
+# file with db information
+sqlrc=$mars/sql.rc
+
+
+#addresses to which the errors are sent
+erradrs="daniela.dorner@unige.ch" 
+#addresses to which the changes are sent
+adrs="daniela.dorner@unige.ch" 
+
+
+#
+#setup for jobmanager
+#
+sleeptime=600 #30
+sleeptimelimit=360 #360
+errorsleeptimedefault=60 #60
+
+algorithm=2
+#hour:            0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
+pnototal=(       32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 )
+pnototalwe=(     32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 )
+
+
+# set variables for jobmanager 
+#scripts=( "runcorsika" "runceres" "runcallisto_mc" "runstar_mc" ) 
+#scriptscolname=( "Corsika" "Ceres" "Callisto" "Star" ) 
+#ratio=( 0.2 0.6 0.1 0.1 )
+#maxjobs=( 20 20 25 25 )
+
+
+# further wishlist: adapt ratio automatically
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/setup.phido.fact.mc
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/setup.phido.fact.mc	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/setup.phido.fact.mc	(revision 17960)
@@ -0,0 +1,126 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  09/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+#
+
+rootsys=/fhgfs/groups/app/magic/software/root_v5.12.00g
+if ! export | grep $rootsys  >|/dev/null
+then
+   export ROOTSYS=$rootsys
+   export PATH=$PATH:$ROOTSYS/bin
+   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib
+fi
+
+# site
+processingsite=phido
+sitekey=2
+storagesite=wue
+
+# queuing system
+queuesys=pbs # wuerzburg data center
+pbspath=/cm/shared/apps/torque/2.3.7/bin
+setwalltime="yes"
+setpmem="yes"
+
+
+mainpath=/fhgfs/groups/app
+
+# logging and setup
+logpath=$mainpath/fact/datacenter/autologs
+lockpath=$mainpath/fact/datacenter/locks
+setuppath=$mainpath/fact/simulated/setup
+
+## paths of data
+#datapath=/magic/data
+#subsystempath=/magic/subsystemdata
+#sequpath=/magic/sequences
+#datasetpath=/magic/datasets
+
+## paths and setup for mc
+mcpath=$mainpath/fact/simulated
+mcsequpath=$mcpath/sequences
+corsikapath=$mainpath/magic/software/MagicSoft/Simulation/Corsika/Mmcs6500
+corsikapath=$mainpath/fact/Mmcs6500
+export FLUPRO=$corsikapath'/fluka2008_3c'
+
+
+#webpath=/www/htdocs/datacenter
+
+# get paths for mars, macros and scripts
+if [ "$SOURCEFILEPATH" = "" ]
+then 
+   mars=`dirname $0 | sed -e 's/\/datacenter\/scripts//'`
+else
+   mars=`echo $SOURCEFILEPATH | sed -e 's/\/datacenter\/scripts//'`
+fi
+macrospath=$mars/datacenter/macros
+scriptspath=$mars/datacenter/scripts
+# rcfiles
+# dependencies of steps
+steps=$mars/resources/steps_fact.rc
+# file with db information
+sqlrc=$mars/sql.rc
+
+
+#addresses to which the errors are sent
+erradrs="dorner@astro.uni-wuerzburg.de" 
+#addresses to which the changes are sent
+adrs="dorner@astro.uni-wuerzburg.de" 
+
+
+#
+#setup for jobmanager
+#
+sleeptime=900 #900
+
+algorithm=1
+tosubmittotal=150 #150
+limitidle=10
+
+# set variables for jobmanager 
+scripts=( "runcorsika"  ) 
+scriptscolname=( "Corsika" ) 
+ratio=( 1 )
+maxjobs=( 800 )
+
+# settings for pbs
+walltimes=( "72:00:00" )
+pmems=( "1gb" ) 
+
+
+#
+#information for copying: 
+#
+
+# steps to be copied
+tocopy=( "Corsika" )
+
+# machine
+remotemachine="dc10"
+remotedir="/magic"
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.fact.mc
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.fact.mc	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.fact.mc	(revision 17960)
@@ -0,0 +1,114 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  06/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+#
+
+rootsys=/opt/root_v5.12.00f
+if ! export | grep $rootsys  >|/dev/null
+then
+   export ROOTSYS=$rootsys
+   export PATH=$PATH:$ROOTSYS/bin
+   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib
+fi
+
+# site
+processingsite=wue
+sitekey=1
+storagesite=wue
+
+# for db backup
+dbnames=( "TestFACTSetup" )
+
+# queuing system
+queuesys=condor # wuerzburg data center
+condorpath=/usr/local/bin
+
+# logging and setup
+logpath=/magic/datacenter/fact/autologs
+lockpath=/magic/datacenter/fact/locks
+setuppath=/magic/simulated/setup
+
+## paths of data
+#datapath=/magic/data
+#subsystempath=/magic/subsystemdata
+#sequpath=/magic/sequences
+#datasetpath=/magic/datasets
+
+## paths and setup for mc
+mcpath=/magic/simulated
+#mcrawpath=$mcpath/rawfiles
+mcsequpath=$mcpath/sequences
+corsikapath=/home/montecarlo/MagicSoft/Simulation/Corsika/Mmcs6500
+export FLUPRO=$corsikapath'/fluka2008_3'
+
+
+#webpath=/www/htdocs/datacenter
+
+# get paths for mars, macros and scripts
+mars=`dirname $0 | sed -e 's/\/datacenter\/scripts//'`
+macrospath=$mars/datacenter/macros
+scriptspath=$mars/datacenter/scripts
+# rcfiles
+# dependencies of steps
+steps=$mars/resources/steps_fact.rc
+# file with db information
+sqlrc=$mars/sql.rc
+
+
+#addresses to which the errors are sent
+erradrs="dorner@astro.uni-wuerzburg.de" 
+#addresses to which the changes are sent
+adrs="dorner@astro.uni-wuerzburg.de" 
+
+
+#
+#setup for jobmanager
+#
+sleeptime=600 #30
+sleeptimelimit=360 #360
+errorsleeptimedefault=60 #60
+
+algorithm=2
+#hour:            0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
+pnototal=(       32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 )
+pnototalwe=(     32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 )
+
+
+# set variables for jobmanager 
+#scripts=( "runcorsika" "runceres" "runcallisto_mc" "runstar_mc" ) 
+#scriptscolname=( "Corsika" "Ceres" "Callisto" "Star" ) 
+#ratio=( 0.2 0.6 0.1 0.1 )
+#maxjobs=( 20 20 25 25 )
+
+scripts=( "runceres" "runcallisto_mc" "runstar_mc" ) 
+scriptscolname=( "Ceres" "Callisto" "Star" ) 
+ratio=( 0.6 0.2 0.2 )
+maxjobs=( 30 25 25 )
+
+# further wishlist: adapt ratio automatically
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.magic.data
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.magic.data	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.magic.data	(revision 17960)
@@ -0,0 +1,123 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2009 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+#
+
+rootsys=/opt/root_v5.12.00f
+if ! export | grep $rootsys  >|/dev/null
+then
+   export ROOTSYS=$rootsys
+   export PATH=$PATH:$ROOTSYS/bin
+   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib
+fi
+
+# queuing system
+queuesys=condor # wuerzburg data center
+condorpath=/usr/local/bin
+
+# for db backup
+dbnames=( "all" )
+
+# logging and setup
+logpath=/magic/datacenter/autologs
+lockpath=/magic/datacenter/locks
+setuppath=/magic/datacenter/setup
+
+# paths of data
+datapath=/magic/data
+subsystempath=/magic/subsystemdata
+sequpath=/magic/sequences
+datasetpath=/magic/datasets
+
+## paths and setup for mc
+#mcpath=/magic/montecarlo
+#mcrawpath=$mcpath/rawfiles
+#mcsequpath=$mcpath/sequences
+#corsikapath=/home/operator/Corsika/Mmcs6500/
+#detectordir=/home/msmeyer/MC/MagicSoft/Simulation/Detector
+#reflectorversion="reflector 0.7"
+#cameraversion="camera 0.8"
+#export FLUPRO=$corsikapath'/fluka2008_3'
+
+
+webpath=/www/htdocs/datacenter
+
+# get paths for mars, macros and scripts
+mars=`dirname $0 | sed -e 's/\/datacenter\/scripts//'`
+macrospath=$mars/datacenter/macros
+scriptspath=$mars/datacenter/scripts
+# rcfiles
+# dependencies of steps
+steps=$mars/resources/steps.rc
+# file with db information
+sqlrc=$mars/sql.rc
+
+
+#addresses to which the errors are sent
+erradrs="datacenter@astro.uni-wuerzburg.de" 
+#addresses to which the changes are sent
+adrs="datacenter@astro.uni-wuerzburg.de, tbretz@astro.uni-wuerzburg.de" 
+
+
+#setup for jobmanager
+sleeptime=30 #30
+sleeptimelimit=360 #360
+errorsleeptimedefault=60 #60
+max=42 #maximum number of processes for one script in case there are more than one and the others do not have anything to do
+totalmax=40 #maximum number of processes (total) overwrites pnototal(we) in case it is smaller
+
+#
+# FIXME: 
+# max anz an prozessen setzen
+# besser Verhaeltnis zwischen den Prozessen und das am besten noch 
+# automatisch anpassen 
+# evtl noch maximale anz an callistos setzen
+# 
+
+#hour:            0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
+pnototal=(       42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 )
+pnototalwe=(     42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 )
+
+pnocallisto=(    32 32 32 32 32 20 20 18 18 12 12 12 12 12 12 12 12 12 12 18 18 20 20 32 )
+pnostar=(        10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 )
+pnoganymed=(      7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7 )
+#pnocutslices=(    8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8 )
+#pnodatacheck=(   20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 )
+
+pnocallistowe=(  32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 )
+pnostarwe=(      10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 )
+pnoganymedwe=(    7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7 )
+#pnocutsliceswe=(  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8 )
+#pnodatacheckwe=( 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 )
+
+# set variables for jobmanager 
+scripts=( "runganymed" "runstar" "runcallisto" ) # not used: "dodatacheck" "cutslices"
+scriptscolname=( "fGanymed" "fStar" "fCallisto" ) # not used: "fDataCheckDone" "fCompmux" 
+pnosweek=( ${pnoganymed[@]} ${pnostar[@]} ${pnocallisto[@]} ) # not used: ${pnodatacheck[@]} ${pnocutslices[@]}
+pnoswe=( ${pnoganymedwe[@]} ${pnostarwe[@]} ${pnocallistowe[@]} ) # not used: ${pnodatacheckwe[@]} ${pnocutsliceswe[@]}
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.magic.mc
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.magic.mc	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/setup.wue.magic.mc	(revision 17960)
@@ -0,0 +1,117 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2009 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2009
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+#
+
+rootsys=/opt/root_v5.12.00f
+if ! export | grep $rootsys  >|/dev/null
+then
+   export ROOTSYS=$rootsys
+   export PATH=$PATH:$ROOTSYS/bin
+   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib
+fi
+
+# queuing system
+queuesys=condor # wuerzburg data center
+condorpath=/usr/local/bin
+
+# logging and setup
+logpath=/magic/datacenter/autologs
+lockpath=/magic/datacenter/locks
+setuppath=/magic/datacenter/setup
+
+## paths of data
+#datapath=/magic/data
+#subsystempath=/magic/subsystemdata
+#sequpath=/magic/sequences
+#datasetpath=/magic/datasets
+
+# paths and setup for mc
+mcpath=/magic/montecarlo
+mcrawpath=$mcpath/rawfiles
+mcsequpath=$mcpath/sequences
+corsikapath=/home/operator/Corsika/Mmcs6500/
+detectordir=/home/msmeyer/MC/MagicSoft/Simulation/Detector
+reflectorversion="reflector 0.7"
+cameraversion="camera 0.8"
+export FLUPRO=$corsikapath'/fluka2008_3'
+
+
+#webpath=/www/htdocs/datacenter
+
+
+# get paths for mars, macros and scripts
+mars=`dirname $0 | sed -e 's/\/datacenter\/scripts//'`
+macrospath=$mars/datacenter/macros
+scriptspath=$mars/datacenter/scripts
+# rcfiles
+# dependencies of steps
+steps=$mars/resources/steps.rc
+# file with db information
+sqlrc=$mars/sql.rc
+
+
+#addresses to which the errors are sent
+erradrs="datacenter@astro.uni-wuerzburg.de" 
+#addresses to which the changes are sent
+adrs="datacenter@astro.uni-wuerzburg.de, tbretz@astro.uni-wuerzburg.de" 
+
+
+#setup for jobmanager
+sleeptime=30 #30
+sleeptimelimit=360 #360
+errorsleeptimedefault=60 #60
+max=42 #maximum number of processes for one script in case there are more than one and the others do not have anything to do
+totalmax=40 #maximum number of processes (total) overwrites pnototal(we) in case it is smaller
+
+#
+# FIXME: 
+# max anz an prozessen setzen
+# besser Verhaeltnis zwischen den Prozessen und das am besten noch 
+# automatisch anpassen 
+# evtl noch maximale anz an callistos setzen
+# 
+
+#hour:            0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
+pnototal=(       42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 )
+pnototalwe=(     42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 )
+
+pnocorsika=(     12 12 12 12 12 12 12 10  9  8  7  7  7  7  7  7  7  7  7  8  9 10 12 12 )
+pnoreflector=(    8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8 )
+pnocamera=(       4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4 )
+
+pnocorsikawe=(   12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 )
+pnoreflectorwe=(  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8  8 )
+pnocamerawe=(     4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4 )
+
+# set variables for jobmanager 
+scripts=( "runcorsika" "runreflector" "runcamera" )
+scriptscolname=( "fCorsikaFileAvail" "fReflectorFileAvail" "fCameraFileAvail" )
+pnosweek=( ${pnocorsika[@]} ${pnoreflector[@]} ${pnocamera[@]} )
+pnoswe=( ${pnocorsikawe[@]} ${pnoreflectorwe[@]} ${pnocamerawe[@]} )
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/sourcefile
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/sourcefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/sourcefile	(revision 17960)
@@ -0,0 +1,467 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+# Only constant variables are stored here, changing variables are stored 
+# in datacenter/scripts/setup
+#
+
+# check if script has been started with absolute path
+if ! dirname $0 | grep -E '^/' >/dev/null 2>&1
+then 
+   echo "Please start your script with an absolute path."
+   exit
+fi
+
+if [ "$AUTOMATIONSETUP" = "" ]
+then 
+   echo "Please set the environment variable \$AUTOMATIONSETUP."
+   exit
+fi
+
+if [ "$SOURCEFILEPATH" = "" ]
+then 
+   export SOURCEFILEPATH=`dirname $0`
+fi
+if [ "$SCRIPTNAME" = "" ]
+then 
+   SCRIPTNAME=`basename $0`
+fi
+
+source $SOURCEFILEPATH/setup.$AUTOMATIONSETUP
+
+datetime=`date +%F-%H-%M-%S`
+
+
+# function to make sure that a directory is made
+function makedir()
+{
+   if [ ! -d $@ ]
+   then
+      mkdir -pv $@ 
+      if [ ! -d $@ ]
+      then 
+         if ! [ "$processlog" = "" ]
+         then
+            echo `date +%F\ %T`" "`whoami`"@"$HOSTNAME" "$SCRIPTNAME"["$$"] ERROR could not make dir "$@ >> $processlog
+         else
+            echo "could not make dir "$@
+         fi
+         if ls $lockfile >/dev/null 2>&1
+         then 
+            rm -v $lockfile
+         fi
+         exit
+      fi
+   fi
+}
+
+# logging paths for runlogs and processlog
+runlogpath=$logpath/run/`date +%Y/%m/%d`
+processlogpath=$logpath/processlog
+makedir $runlogpath
+makedir $processlogpath
+processlog=$processlogpath/process`date +%F`.log
+
+makedir $lockpath
+
+
+# function to provide proper logging in a single logfile ($processlog)
+function printprocesslog
+{
+   makedir $processlogpath
+   echo `date +%F\ %T`" "`whoami`"@"$HOSTNAME" "$SCRIPTNAME"["$$"] "$@ >> $processlog
+}
+
+# function to exit a script properly
+function finish()
+{
+   if ! [ "$lockfile" = "" ] && ls $lockfile >/dev/null 2>&1
+   then 
+      printprocesslog "DEBUG " `rm -v $lockfile`
+   fi
+   printprocesslog "DEBUG finished "$SOURCEFILEPATH"/"$SCRIPTNAME
+   exit
+}
+
+
+# set checkvalue to ok at the beginning of the scripts
+check="ok"
+
+# setup for jobmanager:
+#   log files (can't be defined in script itself, as script can run longer 
+#   than one day
+jmerrorlog=$runlogpath/jobmanager-`whoami`-$HOSTNAME-$AUTOMATIONSETUP-`date +%F`-error.log
+jmscriptlog=$runlogpath/jobmanager-`whoami`-$HOSTNAME-$AUTOMATIONSETUP-`date +%F`.log
+
+# check if rc-files are available
+if ! ls $steps >/dev/null
+then
+   echo "Can't find steps.rc ($steps)"
+   finish
+fi
+if ! ls $sqlrc >/dev/null
+then
+   echo "Can't find sql.rc ($sqlrc)"
+   finish
+fi
+
+# resetting values for jobmanager
+pno=0
+totalpno=0
+running=0
+queued=0
+runningscript=0
+queuedscript=0
+stillinqueue=0
+
+
+# alias (we cannot check the beginning of the line due to
+# color codes in filldotraw.C)
+alias 'intgrep'='grep -E -o \\\(int\\\)[0-9]+$ | grep -E -o [0-9]+'
+
+
+# in the following the functions, which are needed by several scripts, are 
+# defined
+
+# function to check if a process is already locked
+#  command line option can be used to execute something, e.g. 'continue'
+function checklock()
+{
+   if ! echo `date +%F\ %T`" "`whoami`"@"$HOSTNAME" "$SCRIPTNAME"["$$"] "`uname -a` > $lockfile 2>/dev/null
+   then 
+      printprocesslog "WARN lockfile $lockfile exists"
+      $@
+      exit
+   else
+      printprocesslog "DEBUG created lockfile $lockfile"
+   fi
+}
+
+# print the current status values
+function printstatusvalues()
+{
+   echo "the current values are:"
+   echo " starttime=$starttime"
+   echo " stoptime=$stoptime"
+   echo " availtime=$availtime"
+   echo " returncode=$returncode"
+   echo "-- check: -$check-"
+   echo ""
+}
+
+# get the db-setup from the sql.rc
+function getdbsetup()
+{
+   db=`grep Database $sqlrc | grep -v '#' | sed -e 's/Database: //' -e 's/ //g'`
+   pw=`grep Password $sqlrc | grep -v '#' | sed -e 's/Password: //' -e 's/ //g'`
+   us=`grep User $sqlrc | grep -v '#' | sed -e 's/User: //' -e 's/ //g'`
+   ho=`grep URL $sqlrc | grep -v '#' | sed -e 's/ //g' -e 's/URL:mysql:\/\///'`
+#   echo "setup: "
+#   echo " db: "$db
+#   echo " pw: "$pw
+#   echo " us: "$us
+#   echo " ho: "$ho
+}
+
+# function to get information from the setupfile $steps
+function getfromsetup()
+{
+   grep $1"[.]"$2":" $steps | grep -v '#' | sed -e "s/$1[.]$2://"
+}
+
+# function to get the needed information from the dependencies-file steps.rc
+function getstepinfo()
+{
+   getdbsetup
+   needs=( `getfromsetup $step "Needs"` )
+   noderestricted=`getfromsetup $step "NodeRestricted"`
+   prims=( `getfromsetup $step "Primaries"` )
+   maintable=`getfromsetup $step "MainTable" | sed -e "s/\ //g"`
+#   echo " maintable: "$maintable
+#   echo " needs: "${needs[@]}
+#   echo " noderestricted: "$noderestricted
+#   echo " prims: "${prims[@]}
+}
+
+# function to get the joins needed for the get/set status queries
+function getalljoins()
+{
+   # add table
+   query=$query" "$maintable"Status"
+   # add special join
+   query=$query" "`getfromsetup $maintable "SpecialJoin"`
+   # add join for step unless step is the same as maintable
+   if ! [ "$step" = "$maintable" ]
+   then 
+      query=$query" LEFT JOIN "$step"Status USING("${prims[@]}") "
+   fi
+   # add joins for influences or needs
+   for otherstep in ${othersteps[@]}
+   do
+      if ! [ "$otherstep" = "$maintable" ]
+      then 
+         query=$query" LEFT JOIN "$otherstep"Status USING("`getfromsetup $otherstep "Primaries"`") "
+      fi
+   done
+}
+
+# function to create the middle part of a query
+#  which is identical for the functions getstatus() and gettodo()
+function getstatusquery()
+{
+   # add from which table the information is queried
+   query=$query" FROM "
+   othersteps=${needs[@]}
+   getalljoins
+   # add condition
+   query=$query" WHERE "
+   # add condition for step, i.e. step is not yet done
+   query=$query" ISNULL("$step"Status.fStartTime) "
+   query=$query" AND ISNULL("$step"Status.fStopTime) "
+   query=$query" AND ISNULL("$step"Status.fAvailable) "
+   query=$query" AND ISNULL("$step"Status.fReturnCode) "
+   # add requirement for production host in case it is needed
+   if [ "$1 " != " " ]
+   then 
+      query=$query" AND fProductionHostKEY=$2 "
+   fi
+   if ! echo $query | grep UPDATE >/dev/null 2>&1
+   then 
+      query=$query" GROUP BY "${prims[@]}
+   fi
+   # add condition for needs, i.e. that step is done
+   for (( k=0 ; k < ${#needs[@]} ; k++ ))
+   do
+      if [ $k -eq 0 ]
+      then 
+         query=$query" HAVING "
+      else
+         query=$query" AND "
+      fi
+      query=$query" COUNT(*)=COUNT(IF("
+      query=$query" NOT ISNULL("${needs[$k]}"Status.fStartTime) "
+      query=$query" AND NOT ISNULL("${needs[$k]}"Status.fStopTime) "
+      query=$query" AND NOT ISNULL("${needs[$k]}"Status.fAvailable) "
+      query=$query" AND ISNULL("${needs[$k]}"Status.fReturnCode) "
+      query=$query" , 1, NULL)) "
+   done
+}
+
+# function to get todolist
+#   returns the next or the list of next steps
+function gettodo()
+{
+   # reset the variable for the number of the next step 
+   process=
+   printprocesslog "DEBUG getting todo for step $step..."
+   getstepinfo
+   # get query
+   query=" SELECT "${prims[@]}
+   getstatusquery $2
+   # order by priority to the the number of the next step to be done
+   query=$query" ORDER BY "$step"Status.fPriority desc "
+   # add limitation in case only one or a limited number of 
+   #  processes should be executed
+   if [ "$1 " != " " ]
+   then 
+      query=$query" limit 0, $1 "
+   fi
+   # print query 
+   printprocesslog "DEBUG gettodo for step $step QUERY: "$query
+   # execute query 
+   if ! process=`mysql -s -u $us --password=$pw --host=$ho $db -e " $query "`
+   then
+      printprocesslog "ERROR could not query processes from db (program: $program, function gettodo)"
+      finish
+   fi
+   # get numbers of next step from mysql result
+   if [ "$process" = "" ]
+   then
+      printprocesslog "DEBUG => nothing to do"
+      finish
+   else
+      primaries=( $process )
+      num=`expr ${#primaries[@]} / ${#prims[@]} `
+   fi
+}
+
+# function to get the number of processes which still have to be done
+function getstatus()
+{
+   # reset the variable for the number of steps to be done
+   numproc=0
+   getstepinfo
+   # get query
+   query=" SELECT "${prims[@]}
+   getstatusquery $1
+   # print query
+   printprocesslog "DEBUG getstatus for step $step QUERY: "$query
+   # execute query
+   if ! numproc=`mysql -s -u $us --password=$pw --host=$ho $db -e " $query " | wc -l`
+   then
+      printprocesslog "ERROR could not query number of processes from db (program: $program, function getstatus)"
+      echo `date +%F\ %T`" ERROR could not query number of processes from db (program: $program, function getstatus)"
+      continue
+   fi
+}
+
+# function to set status of a process in the db
+function setstatus()
+{
+   # remark:
+   # this function does not include the 'Default' flag 
+   # for resetting steps
+
+   # for dowebplots (there are steps which have no entry in the DB)
+   if [ "$step" = "no" ]
+   then
+      return
+   fi
+   
+   # reset status values
+   starttime=NULL
+   stoptime=NULL
+   availtime=NULL
+   returncode=NULL
+   # evaluate the status values
+   case $@ in
+      start)   printprocesslog "DEBUG setstatus start"
+               starttime="Now()"
+               ;;
+       stop)   case $check in
+                  ok)  printprocesslog "DEBUB setstatus stop - ok"
+                       starttime=noreset
+                       stoptime="Now()"
+                       if [ "$processingsite" = "$storagesite" ]
+                       then
+                          availtime="Now()"
+                       fi
+                       ;;
+                  no)  printprocesslog "DEBUG setstatus stop - nothing new"
+                       check="ok"
+                       ;;
+                   *)  printprocesslog "DEBUG setstatus stop - failed"
+                       starttime=noreset
+                       stoptime="Now()"
+                       if [ "$processingsite" = "$storagesite" ]
+                       then
+                          availtime="Now()"
+                       fi
+                       if [ "$check" == "" ]
+                       then
+                          returncode=1
+                       else
+                          returncode=$check
+                       fi
+                       check="ok"
+                       ;;
+               esac
+               ;;
+          *)   printprocesslog "ERROR function setstatus got wrong variable"
+               finish
+               ;;
+   esac
+   
+   # get 
+   getstepinfo
+   
+   # get the influences from the steps.rc by evaluating the needs of all steps
+   othersteps=`grep $step $steps | grep "Needs" | grep -v "$step[.]Needs" | cut -d'.' -f1`
+   
+   # get query
+   query=" UPDATE "
+   getalljoins
+   # set the status values according to the new status of the step
+   query=$query" SET "
+   if ! [ "$starttime" = "noreset" ]
+   then
+      query=$query" "$step"Status.fStartTime=$starttime, "
+   fi
+   query=$query" "$step"Status.fStopTime=$stoptime, "$step"Status.fAvailable=$availtime"
+   query=$query", "$step"Status.fReturnCode=$returncode , "$step"Status.fProcessingSiteKEY=$sitekey "
+   # set also the status values of the influenced steps
+   for otherstep in $othersteps
+   do
+      query=$query", "$otherstep"Status.fStartTime=NULL "
+      query=$query", "$otherstep"Status.fStopTime=NULL "
+      query=$query", "$otherstep"Status.fAvailable=NULL "
+      query=$query", "$otherstep"Status.fReturnCode=NULL "
+      query=$query", "$otherstep"Status.fProcessingSiteKEY=NULL "
+   done
+   # give the condition for which step the status values have to be set
+   query=$query" WHERE "
+   if [ "$s" = "" ]
+   then
+      s=0
+   fi
+   query=$query" "$step"Status."`echo ${prims[0]} | sed -e 's/,//g'`"='${primaries[$s*${#prims[@]}]}'"
+   for (( j=1 ; j < ${#prims[@]} ; j++ ))
+   do
+      query=$query" AND "$step"Status."`echo ${prims[$j]} | sed -e 's/,//g'`"='${primaries[$s*${#prims[@]}+$j]}' "
+   done 
+   # add additional query to allow for locking in db
+   if [ "$1" = "start" ]
+   then 
+      query=$query" AND ISNULL("$step"Status.fStartTime) "
+   fi
+   # add row count to know how many rows have been changed
+   query=$query"; SELECT ROW_COUNT();"
+   # print query
+   printprocesslog "DEBUG setstatus for step $step QUERY: "$query
+   # execute query
+   if ! numchanged=`mysql -s -u $us --password=$pw --host=$ho $db -e " $query "`
+   then
+      printprocesslog "ERROR could not set status in db (program: $program, function setstatus)"
+      finish
+   fi
+   if [ $numchanged -gt 0 ]
+   then
+      printprocesslog "INFO successful setting of status in db (program: $program, function setstatus)"
+   else
+      printprocesslog "INFO status in db was already set by other process (program: $program, function setstatus)"
+   fi
+}
+
+# function to send a mysql query
+function sendquery()
+{
+   getdbsetup
+   printprocesslog "DEBUG sendquery QUERY: "$query
+   if ! val=`mysql -s -u $us --password=$pw --host=$ho $db -e " $query "`
+   then
+      printprocesslog "ERROR could not query db (program: $program, function sendquery)"
+      return 1
+   fi
+   if [ "$val" = "NULL" ]
+   then
+      val=
+   fi
+   echo $val
+   return 0
+}
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/writedatasetfiles
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/writedatasetfiles	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/writedatasetfiles	(revision 17960)
@@ -0,0 +1,84 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the checking of the availability of the files for 
+# the datasets. 
+#
+# After checking if the script is already running the todolist is written.
+# Then for each dataset the sequences are extracted from the datasetfile 
+# and for each sequence the availability of the star files checked by using 
+# the macro checkstardone.C 
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=writedatasetfiles
+column=fDataSetFileWritten
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+for (( s=0 ; s < $num ; s++ ))
+do
+   dataset=${primaries[$s]}
+   printprocesslog "INFO writing datasetfile for dataset $dataset"
+   no=`printf %08d $dataset | cut -c 0-5`
+   no2=`printf %08d $dataset`
+   datasetpathcpl=$datasetpath/$no
+   makedir $datasetpathcpl 
+   writedatasetfilelogpath=$logpath/$program/$no
+   makedir $writedatasetfilelogpath 
+   logfile=$writedatasetfilelogpath/$program-$no2.log
+
+   setstatus "start" 
+   
+   check1=`root -q -b $macrospath/writedatasetfile.C+\($dataset\,\""$datasetpathcpl\""\) | tee $logfile | intgrep`
+
+   case $check1 in
+      1)   printprocesslog "INFO wrote datasetfile for dataset $dataset successfully (check1=$check1)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check1=$check1)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR writedatasetfile.C failed (check1=$check1)"
+           com=$Fwritedatasetfile
+           check=$check1
+           ;;
+   esac
+   
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/writemcsequencefile
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/writemcsequencefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/writemcsequencefile	(revision 17960)
@@ -0,0 +1,106 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  06/2010 <mailto:daniela.dorner@unige.ch>
+#
+#   Copyright: MAGIC Software Development, 2000-2010
+#
+#
+# ========================================================================
+#
+# This script launches the writing of the sequence files for all mc sequences
+# for which this step is needed. 
+#
+# After checking if the script is already running the todolist is written.
+# Then the sequence file is written for each sequence in the todolist using
+# the macro writesequencefile.C
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=writemcsequencefile
+step=SequenceFile
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+printprocesslog "INFO writing sequence files for $num mc sequences"
+# write sequence file for all sequences which don't have one yet
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s]}
+   printprocesslog "INFO write sequence files for sequence $sequence"
+   setstatus "start" 
+   
+   no=`printf %08d $sequence | cut -c 0-4`
+   no2=`printf %08d $sequence`
+   sequencepath=$mcsequpath/$no
+   makedir $sequencepath 
+   sequencefile=$sequencepath/sequence$no2.txt
+   
+   # data runs
+   query="SELECT CONCAT(fRunNumber, '.', RIGHT(fFileNumber, 3)) FROM CeresInfo WHERE fRunTypeKEY=2 AND fSequenceNumber="$sequence" GROUP BY fRunNumber, fFileNumber "
+   datruns=`sendquery`
+   if [ "$datruns" = "" ]
+   then 
+      printprocesslog "ERROR data runs for sequence "$sequence" are missing in the database "
+      check=2
+   fi
+   # pedestal runs
+   query="SELECT CONCAT(fRunNumber, '.', RIGHT(fFileNumber, 3)) FROM CeresInfo WHERE fRunTypeKEY=3 AND fSequenceNumber="$sequence" GROUP BY fRunNumber, fFileNumber "
+   pedruns=`sendquery`
+   if [ "$pedruns" = "" ]
+   then 
+      printprocesslog "ERROR pedestal runs for sequence "$sequence" are missing in the database "
+      check=2
+   fi
+   # calibration runs
+   query="SELECT CONCAT(fRunNumber, '.', RIGHT(fFileNumber, 3)) FROM CeresInfo WHERE fRunTypeKEY=4 AND fSequenceNumber="$sequence" GROUP BY fRunNumber, fFileNumber "
+   calruns=`sendquery`
+   if [ "$calruns" = "" ] 
+   then 
+      printprocesslog "ERROR calibration runs for sequence "$sequence" are missing in the database "
+      check=2
+   fi
+   
+   printprocesslog "INFO writing sequencefile $sequencefile"
+   echo "Sequence: "$sequence >| $sequencefile
+   echo ""                    >> $sequencefile
+   echo "CalRuns: "$calruns   >> $sequencefile
+   echo "PedRuns: "$pedruns   >> $sequencefile
+   echo "DatRuns: "$datruns   >> $sequencefile
+   echo ""                    >> $sequencefile
+   echo "MonteCarlo: Yes"     >> $sequencefile
+   echo ""                    >> $sequencefile
+   
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/writesequencefiles
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/writesequencefiles	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/writesequencefiles	(revision 17960)
@@ -0,0 +1,87 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script launches the writing of the sequence files for all sequences
+# for which this step is needed. 
+#
+# After checking if the script is already running the todolist is written.
+# Then the sequence file is written for each sequence in the todolist using
+# the macro writesequencefile.C
+# If this was successful, the status is inserted into the database using 
+# the function setstatus.
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+program=writesequencefile
+column=fSequenceFileWritten
+
+set -C
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock 
+
+# get todo list
+gettodo 
+
+cd $mars
+
+# write sequence file for all sequences which don't have one yet
+for (( s=0 ; s < $num ; s++ ))
+do
+   sequence=${primaries[$s+$s]}
+   telnum=${primaries[$s+$s+1]}
+   printprocesslog "INFO write sequence files for sequence $sequence"
+   no=`printf %08d $sequence | cut -c 0-4`
+   no2=`printf %08d $sequence`
+   sequencepath=$sequpath/$no
+   makedir $sequencepath 
+
+   writesequencefilelogpath=$logpath/$program/$no
+   makedir $writesequencefilelogpath 
+   writesequencefilelog=$writesequencefilelogpath/writesequencefile-$no2.log
+
+   setstatus "start" 
+
+   check1=`root -q -b $macrospath/writesequencefile.C\($sequence\,$telnum\,"\"$sequpath\""\) | tee $writesequencefilelog | intgrep`
+   case $check1 in
+      1)   printprocesslog "INFO sequence file successfully written for sequence $sequence (check1=$check1)"
+           ;;
+      0)   printprocesslog "WARN connection to DB failed (check1=$check1)"
+           check="no"
+           ;;
+      *)   printprocesslog "ERROR $program.C failed for sequence $sequence (check1=$check1)"
+           com=$Fwritesequfile
+           check=$check1
+           ;;
+   esac
+   
+   setstatus "stop" 
+done
+
+finish 
+
Index: branches/Mars_McMismatchStudy/datacenter/scripts/zipscript
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/scripts/zipscript	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/scripts/zipscript	(revision 17960)
@@ -0,0 +1,135 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  09/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Stefan Ruegamer 08/2008 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+# This script zips the incoming rawfiles. 
+#
+
+source `dirname $0`/sourcefile
+printprocesslog "INFO starting $0"
+# to give the possibility to run several zipscripts at the same time, 
+# $1 is added
+program=zipscript$1
+
+set -C
+
+rawdatapath=$datapath/rawfiles/
+files=`find ${rawdatapath}20* -type f -name '*.raw'`
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock  >> $scriptlog 2>&1
+
+
+if [ "$files" == "" ]
+then
+   echo "no files to zip" >> $scriptlog 2>&1
+   finish >> $scriptlog 2>&1
+fi
+
+for file in ${files[@]}
+do
+   if ! [ -f $file ]
+   then
+      continue
+   fi
+   
+   echo -e "\nprocessing file $file..." >> $scriptlog 2>&1 
+   runno=`basename $file | sed -e 's/.*20[01][0-9]\{5\}_\(M[12]_\)\?.*\([0-9]\{8\}\).\([0-9]\{3\}\)\?.*/\2/'`
+   fileno=`basename $file | sed -e 's/.*20[01][0-9]\{5\}_\(M[12]_\)\?.*\([0-9]\{8\}\).\([0-9]\{3\}\)\?.*/\3/'`
+   telno=`basename $file | sed -e 's/.*20[01][0-9]\{5\}_\(M[12]_\)\?.*\([0-9]\{8\}\).\([0-9]\{3\}\)\?.*/\1/' | cut -c2`
+   # old runs have a fileno of 0
+   if [ "$fileno" == "" ]
+   then
+      fileno=0
+   fi
+   # old runs have a telno of 1
+   if [ "$telno" == "" ]
+   then
+      telno=1
+   fi
+   
+   # get the sequence corresponding to the run
+   query="SELECT fSequenceFirst FROM RunData WHERE fRunNumber="$runno" AND fFileNumber="$fileno" AND fTelescopeNumber="$telno
+   echo " sending query: $query" >> $scriptlog 2>&1
+   if ! seq=`sendquery`
+   then
+      echo "querying seq for run M${telno}_${runno}.${fileno} from the db did not work -> continue" >> $scriptlog 2>&1
+      printprocesslog "WARN query $seq for run M${telno}_${runno}.${fileno} from the db did not work"
+      continue
+   fi
+   if [ "$seq" == "" ] || [ "$seq" == "0" ]
+   then
+      echo "no seq found for run M${telno}_${runno}.${fileno} -> locking only run..." >> $scriptlog 2>&1
+      seq=${runno}.${fileno}
+   fi
+   
+   # lock the sequence against zipscript
+   echo "locking sequence ${seq}-${telno}..."  >> $scriptlog 2>&1
+   lockfile=$lockpath/calzip${seq}-${telno}.txt
+   checklock continue >> $scriptlog 2>&1
+   
+   # lock the run in the db
+   query="UPDATE SequenceProcessStatus set fNotZipping=NULL WHERE fSequenceFirst=$seq AND fTelescopeNumber=$telno"
+   echo " sending query: $query" >> $scriptlog 2>&1
+   if ! sendquery 
+   then
+      echo "locking ${seq}-${telno} for callisto in db did not work ..." >> $scriptlog 2>&1
+      printprocesslog "WARN locking ${seq}-${telno} for callisto in db did not work"
+      rm -v $lockfile >> $scriptlog 2>&1
+      continue
+   fi
+   
+   # zip the run
+   echo "zipping $file ..." >> $scriptlog 2>&1
+   if ssh -xn phoenix nice -n 19 gzip -1f $file >> $scriptlog 2>&1
+   then 
+      gzfile=$file".gz"
+      chmod a-w $gzfile >> $scriptlog 2>&1
+   else
+      printprocesslog "WARN zipping $file did not work"
+   fi
+   
+   # unlock the sequence in the db
+   echo "unlocking sequence ${seq}-${telno}..."  >> $scriptlog 2>&1
+   query="UPDATE SequenceProcessStatus set fNotZipping=Now() WHERE fSequenceFirst=$seq AND fTelescopeNumber=$telno"
+   echo " sending query: $query" >> $scriptlog 2>&1
+   if ! sendquery 
+   then
+      echo "unlocking ${seq}-${telno} for callisto in db did not work ..." >> $scriptlog 2>&1
+      printprocesslog "ERROR unlocking ${seq}-${telno} for callisto in db did not work"
+      rm -v $lockfile >> $scriptlog 2>&1
+      continue
+   fi
+   rm -v $lockfile >> $scriptlog 2>&1
+done
+
+lockfile=$lockpath/lock-$program.txt
+finish >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/tools/comparesequences
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/comparesequences	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/comparesequences	(revision 17960)
@@ -0,0 +1,57 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2006
+#
+#
+# ========================================================================
+#
+
+date=`date +.%Y.%m.%d.%H.%M.%S`
+olddb=MyMagic
+newdb=TestSequ2
+pw=d99swMT!
+host=vela
+
+query="select fRunNumber from RunData where fRunNumber > 32000";
+runs=`mysql -s -u MAGIC --password=$pw --host=$host MyMagic -e " $query "`
+
+for run in $runs
+do 
+   query="select fSequenceFirst from RunData where fRunNumber=$run"
+   s1=`mysql -s -u MAGIC --password=$pw --host=$host $olddb -e " $query "`
+   s2=`mysql -s -u test  --password=Ics+eaTD --host=$host $newdb -e " $query "`
+   if [ $s1 -eq 0 ] && [ $s2 -eq 0 ]
+   then 
+      continue
+   fi
+   if [ $s1 -eq $s2 ]
+   then 
+      continue
+   fi
+   echo "run: $run sequ#: $s1 -> $s2"
+   echo "run: $run sequ#: $s1 -> $s2" >> sequ.changes$date
+   if [ $s2 -eq 0 ]
+   then 
+      echo "run: $run sequ#: $s1 -> $s2" >> not-sequenced.anymore$date
+   fi
+done
+
Index: branches/Mars_McMismatchStudy/datacenter/tools/fillobjects.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/fillobjects.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/fillobjects.C	(revision 17960)
@@ -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, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillobjects.C
+// ==============
+//
+// read file with magnitudes and colour for the objects
+// File: resources/good_compstars_R.txt
+//
+// In resources also the file compstars_R.txt can be found, which contains
+// more stars. As the value for the magnitude for these stars is not good
+// enough, they are not inserted into the database, as the values there are
+// used for the calculation of the extinction.
+// E.g. resources/good_compstars_R.txt does not contain the blazars itself.
+//
+///////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MAstro.h"
+#include "MDirIter.h"
+#include "MSQLServer.h"
+#include "MSQLMagic.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// loop over all files in this path
+//
+int fillobjects(TString fname, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << endl;
+    cout << "fillobjects" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        cout << "Could not open file " << fname << endl;
+        return 0;
+    }
+
+    Int_t num=0;
+    TString object;
+    TString query;
+    TString where;
+    TString comment;
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        if (line.IsNull())
+            continue;
+
+        line.ReplaceAll("\t", " ");
+        TObjArray *arr = line.Tokenize(" ");
+        if (arr->GetEntries()!=5)
+        {
+            cout << "WARNING: line with less or more than 5 arguments found " << endl;
+            cout << line << endl;
+            return 2;
+        }
+        query=Form("fMagnitude=%s, fVRColour=%s, fObject=",
+                   (*arr)[2]->GetName(), (*arr)[3]->GetName());
+        comment=(*arr)[4]->GetName();
+        if (comment=="-")
+            query+="NULL";
+        else
+            query+=Form("'%s'", comment.Data());
+
+        query+=Form(", fObjectName='%s/%s'", (*arr)[0]->GetName(), (*arr)[1]->GetName());
+        where=Form(" fObjectName='%s/%s'", (*arr)[0]->GetName(), (*arr)[1]->GetName());
+        delete arr;
+
+        if (serv.InsertUpdate("Object", query, where)==kFALSE)
+            return 2;
+        num +=1;
+
+    }
+
+    cout << fname << " <" << num << "> " << endl;
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/tools/fillobjects2.C
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/fillobjects2.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/fillobjects2.C	(revision 17960)
@@ -0,0 +1,131 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillobjects2.C
+// ==============
+//
+// read file with coordinates for the objects (only the blazars)
+// File resources/TeVsources.txt
+//
+///////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MAstro.h"
+#include "MDirIter.h"
+#include "MSQLServer.h"
+#include "MSQLMagic.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// loop over all files in this path
+//
+int fillobjects2(TString fname, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLMagic serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    serv.SetIsDummy(dummy);
+
+    cout << endl;
+    cout << "fillobjects" << endl;
+    cout << "-----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        cout << "Could not open file " << fname << endl;
+        return 0;
+    }
+
+    Int_t num=0;
+    TString object;
+    TString query;
+    TString where;
+    TString RA;
+    TString DEC;
+    Double_t ra;
+    Double_t dec;
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        if (line.IsNull())
+            continue;
+
+        TObjArray *arr = line.Tokenize(" ");
+        if (arr->GetEntries()!=10)
+        {
+            cout << "WARNING: line with less or more than 11 arguments found " << endl;
+            cout << line << endl;
+            continue;
+        }
+        object=Form("%s/BL",(*arr)[0]->GetName());
+        RA=Form("%s:%s:%s", (*arr)[2]->GetName(), (*arr)[3]->GetName(), (*arr)[4]->GetName());
+        DEC=Form("%s:%s:%s", (*arr)[5]->GetName(), (*arr)[6]->GetName(), (*arr)[7]->GetName());
+        delete arr;
+//        cout << "RA: " << RA << " -  DEC " << DEC << endl;
+        MAstro::Coordinate2Angle(RA, ra);
+        MAstro::Coordinate2Angle(DEC, dec);
+//        cout << "ra: " << ra << " -  dec " << dec << endl;
+
+        query=Form("fRightAscension=%.7f, fDeclination=%.7f, fEpoche=2000",
+                   ra, dec);
+
+        query+=Form(", fObjectName='%s'", object.Data());
+        where=Form(" fObjectName='%s'", object.Data());
+
+        if (serv.InsertUpdate("Object", query, where)==kFALSE)
+            return 2;
+        num +=1;
+
+    }
+
+    cout << fname << " <" << num << "> " << endl;
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/datacenter/tools/findnotanymoresequencedruns
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/findnotanymoresequencedruns	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/findnotanymoresequencedruns	(revision 17960)
@@ -0,0 +1,47 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2005 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2006
+#
+#
+# ========================================================================
+#
+# This a resource file for the scripts, in which the standard paths and 
+# functions, which are needed more often are stored. 
+#
+
+olds=0
+cnt=0
+sequences=`cat /home/bla/not-sequenced.anymore.2006.10.06.19.20.34 | cut -c 19-23`
+for sequence in $sequences
+do 
+#   echo "v: $sequence $cnt"
+   if ! [ $sequence -eq $olds ]
+   then 
+       if [ $cnt -gt 10 ]
+       then 
+          echo "seq: $olds $cnt"
+       fi
+       olds=$sequence
+       cnt=0
+   fi
+   cnt=`echo $cnt + 1 | bc`
+done
Index: branches/Mars_McMismatchStudy/datacenter/tools/rename_rawfiles
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/rename_rawfiles	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/rename_rawfiles	(revision 17960)
@@ -0,0 +1,65 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Stefan Ruegamer  07/2008 <mailto:snruegam@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script searches for raw files with a 5 digit subrun number and
+# changes this number to a 3 digit one.
+
+
+source `dirname $0`/sourcefile
+program=rename_rawfiles
+
+scriptlog=$runlogpath/$program-$datetime.log
+date >> $scriptlog 2>&1
+
+# check if script is already running
+lockfile=$lockpath/lock-$program.txt
+checklock >> $scriptlog 2>&1
+
+rawdatapath=/data/fromtape/muxdata
+
+# find raw files named after the new convention but having a 5 digit subrun number
+files=`find ${rawdatapath}/ -regextype posix-egrep -regex '.*/20[01][0-9]{5}_M[12]_[0-9]{8}\.[0-9]{5}_.*.raw' -type f`
+
+# convert to 3 digit subrun number
+for file in ${files[@]}
+do
+   zero=`basename $file | cut -d_ -f3 | cut -c 10-11`
+   if ! [ $zero == "00" ]
+   then
+      echo "${file}: subrunnumber greater than 999 -> continue" >> $scriptlog 2>&1
+      continue
+   else
+      # s/ ()() / \1\2 /
+      newfile=`echo $file | sed -e 's/\(.*\/20[01][0-9]\{5\}_M[12]_[0-9]\{8\}\.\)00\([0-9]\{3\}.*\)/\1\2/'`
+      # raw files without .-separation between run and subrun number and without M[12]
+      #newfile=`echo $file | sed -e 's/\(.*20[01][0-9]\{5\}_\)\([0-9]\{8\}\)00\([0-9]\{3\}.*\)/\1M1_\2.\3/'`
+      echo "moving $file to $newfile..." >> $scriptlog 2>&1
+      mv $file $newfile
+   fi
+done
+
+rm -v $lockfile >> $scriptlog 2>&1
+
Index: branches/Mars_McMismatchStudy/datacenter/tools/resetdataset
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/resetdataset	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/resetdataset	(revision 17960)
@@ -0,0 +1,164 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  10/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2006
+#
+#
+# ========================================================================
+#
+# This script checks from the DB which new starfiles have been produced 
+# and sends it to the person in charge for building datasets
+#
+
+datasetpath=/magic/datasets
+#datasetpath=/test/bu.2006.10.05/datasets
+
+function usage()
+{
+   echo "Usage: $0 [options]"
+   echo "options:"
+   echo -n "  --ds  dataset#       "
+   echo " number of the dataset you want to reset "
+   echo -n "  --db                 "
+   echo " name of the db in which you want to reset "
+   echo -n "  --user               "
+   echo " db user "
+   echo -n "  --pw                 "
+   echo " pw of the db user "
+   echo ""
+   exit
+}
+
+
+while [ "$1" ]
+do 
+   case $1 in 
+        --ds) shift
+              dataset=$1
+              ;;
+        --db) shift
+              db=$1
+              ;;
+        --pw) shift
+              pw=$1
+              ;;
+      --user) shift
+              user=$1
+              ;;
+          -h) usage
+              ;;
+           *) echo "unknown option $1 "
+              usage
+              exit
+              ;;
+   esac
+   shift
+done
+
+if [ "$dataset" = "" ]
+then 
+   echo "Please give the number for the dataset you want to reset."
+   usage
+fi
+
+if [ "$pw" = "" ] || [ "$user" = "" ]
+then 
+   echo "Please give user and password for the DB $db."
+   usage
+fi
+
+if [ "$db" = "" ]
+then 
+   echo "Please give the DB in which you want to reset."
+   usage
+fi
+
+
+alias mymysql='mysql -u $user --password=$pw --host=vela $db -s -e'
+
+whereclause1=" WHERE fDataSetNumber=$dataset"
+statusreset=", fStartTime=NULL, fFailedTime=NULL, fFailedCode=NULL, fFailedCodeAdd=NULL, fReturnCode=NULL"
+query1="UPDATE DataSetProcessStatus SET fStarFilesAvail=NULL, fGanymed=NULL, fFillGanymed=NULL"
+query1=$query1$statusreset$whereclause1
+
+query2="DELETE FROM Ganymed "$whereclause1
+
+no=`printf %08d $dataset`
+no2=`echo $no | cut -c 0-5`
+datasetfile=$datasetpath/$no2/dataset$no.txt
+if ! ls $datasetfile 2>&1 >/dev/null
+then
+   echo "There's no datasetfile $datasetfile"
+   exit
+fi
+echo " getting sequence numbers from $datasetfile"
+
+seqon=`grep "SequencesOn" $datasetfile | grep -v '#' | sed -e 's/SequencesOn://' -e 's/^ //g' -e 's/ $//g' -e 's/ /,/g'`
+seqoff=`grep "SequencesOff" $datasetfile | grep -v '#' | sed -e 's/SequencesOff://' -e 's/^ //g' -e 's/ $//g' -e 's/ /,/g'`
+
+echo " Found the following  on sequences: $seqon"
+echo " Found the following off sequences: $seqoff"
+
+if [ "$seqoff" = "" ]
+then
+   whereclause2=" WHERE fSequenceFirst IN ($seqon)"
+else
+   whereclause2=" WHERE fSequenceFirst IN ($seqon,$seqoff)"
+fi
+query3="UPDATE SequenceProcessStatus SET fAllFilesAvail=NULL, fCallisto=NULL, fStar=NULL "
+query3=$query3$statusreset$whereclause2
+
+query4="DELETE FROM Calibration"$whereclause2
+query5="DELETE FROM Star"$whereclause2
+
+
+echo ""
+echo "The following queries would be executed:"
+echo "Q1: "$query1
+echo "Q2: "$query2
+echo "Q3: "$query3
+echo "Q4: "$query4
+echo "Q5: "$query5
+echo ""
+echo "  DB: "$db
+echo "user: " $user
+echo ""
+echo "Are you sure you want to continue?" 
+echo "please insert y, if you want continue"
+echo "              n, if you want quit"
+
+answer=`head -n 1`
+case $answer in
+   y) echo "continue resetting DB"
+      ;;
+   n) exit
+      ;;
+   *) echo "your answer is not clear -> exit"
+      exit
+      ;;
+esac
+
+mymysql "$query1"
+mymysql "$query2"
+mymysql "$query3"
+mymysql "$query4"
+mymysql "$query5"
+
Index: branches/Mars_McMismatchStudy/datacenter/tools/resetpriorities
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/resetpriorities	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/resetpriorities	(revision 17960)
@@ -0,0 +1,145 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  08/2008 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2008
+#
+#
+# ========================================================================
+#
+# This script resets the priorities for the tables RunProcessStatus
+# SequenceProcessStatus and DataSetProcessStatus
+#
+
+alias mymysql='mysql -u $user --password=$pw --host=vela $db -e'
+
+
+function usage()
+{
+   echo "Usage: $0 [options]"
+   echo "options:"
+   echo -n "  --db          "
+   echo " name of the db for which you want to reset the priorities"
+   echo "                   if no db is given, MyMagic is resetted"
+   echo -n "  --user        "
+   echo " db user "
+   echo -n "  --pw          "
+   echo " pw of the db user "
+   echo ""
+   echo -n "  -d            "
+   echo " reset only priorities of datasets"
+   echo -n "  -r            "
+   echo " reset only priorities of runs"
+   echo -n "  -s            "
+   echo " reset only priorities of sequences"
+   echo ""
+   echo "  If none of the last three option is chosen, all of them are resetted."
+   echo ""
+   exit
+}
+
+
+all="yes"
+while [ "$1" ]
+do 
+   case $1 in 
+        --db) shift
+              db=$1
+              ;;
+        --pw) shift
+              pw=$1
+              ;;
+      --user) shift
+              user=$1
+              ;;
+          -h) usage
+              ;;
+          -d) ds="yes"
+              all="no"
+              ;;
+          -r) rn="yes"
+              all="no"
+              ;;
+          -s) sq="yes"
+              all="no"
+              ;;
+           *) echo "unknown option $1 "
+              usage
+              exit
+              ;;
+   esac
+   shift
+done
+
+
+if [ "$pw" = "" ] || [ "$user" = "" ]
+then 
+   echo "Please give user and password for the DB $db."
+   usage
+fi
+
+if [ "$db" = "" ]
+then 
+   echo "You didn't give a database. The priorities for MyMagic will be resetted in 5 seconds..."
+   db="MyMagic"
+   sleep 5
+fi
+
+if [ "$all" = "yes" ]
+then 
+   ds="yes"
+   rn="yes"
+   sq="yes"
+fi
+
+
+if [ "$rn" = "yes" ]
+then
+   query1="update RunProcessStatus set fPriority=fRunNumber"
+   if ! mymysql "$query1"
+   then
+      echo "ERROR: could not reset priorities for RunProcessStatus"
+   else
+      echo "The priorities for RunProcessStatus have been resetted successfully."
+   fi
+fi
+
+if [ "$sq" = "yes" ]
+then
+   query2="update SequenceProcessStatus set fPriority=fSequenceFirst"
+   if ! mymysql "$query2"
+   then
+      echo "ERROR: could not reset priorities for SequenceProcessStatus"
+   else
+      echo "The priorities for SequenceProcessStatus have been resetted successfully."
+   fi
+fi
+
+if [ "$ds" = "yes" ]
+then
+   query3="update DataSetProcessStatus set fPriority=fDataSetNumber"
+   if ! mymysql "$query3"
+   then
+      echo "ERROR: could not reset priorities for DataSetProcessStatus"
+   else
+      echo "The priorities for DataSetProcessStatus have been resetted successfully."
+   fi
+fi
+
Index: branches/Mars_McMismatchStudy/datacenter/tools/sps-bu
===================================================================
--- branches/Mars_McMismatchStudy/datacenter/tools/sps-bu	(revision 17960)
+++ branches/Mars_McMismatchStudy/datacenter/tools/sps-bu	(revision 17960)
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+file=SPS.2006.10.17.cp.sql
+while read LINE
+do 
+   if [ "$LINE" = "" ]
+   then
+      continue
+   fi
+   cal=`echo $LINE | cut -d, -f4`
+   if [ "$cal" = "NULL" ]
+   then
+      continue
+   fi
+   query="UPDATE SequenceProcessStatus set fCallisto=$cal"
+   star=`echo $LINE | cut -d, -f5`
+   if ! [ "$star" = "NULL" ]
+   then
+      query=$query", fStar=$star"
+   fi
+#   echo $LINE
+   seq=`echo $LINE | cut -d\( -f2 | cut -d, -f1`
+#   query=$query", fFillCallisto=NULL, fFillStar=NULL"
+#   query=$query", fStartTime=NULL, fFailedCode=NULL, fReturnCode=NULL"
+#   query=$query", fFailedTime=NULL, fFailedCodeAdd=NULL"
+   query=$query", fAllFilesAvail=Now() where fSequenceFirst=$seq;"
+#   echo "LINE: "$LINE
+   echo $query
+#   sleep 1
+done < $file
+
+
Index: branches/Mars_McMismatchStudy/fact/analysis/callisto.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/callisto.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/callisto.C	(revision 17960)
@@ -0,0 +1,957 @@
+#include "MLogManip.h"
+
+int callisto(const char *seqfile="seq/2012/01/23/20120123_023.seq", const char *outpath = "output")
+{
+    // ======================================================
+
+    // true:  Display correctly mapped pixels in the camera displays
+    //        but the value-vs-index plot is in software/spiral indices
+    // false: Display pixels in hardware/linear indices,
+    //        but the order is the camera display is distorted
+    bool usemap = true;
+
+    // map file to use (get that from La Palma!)
+    const char *map = usemap ? "/home/fact/FACT++/FACTmap111030.txt" : NULL;
+/*
+    Bool_t maximum = kTRUE;
+
+    const char *lp_template    = maximum ?
+        "template-lp-extractor-maximum.root" :
+        "template-lp-extractor-leading-edge.root";
+
+    const char *pulse_template = "template-pulse.root";
+*/
+    // ------------------------------------------------------
+
+    //bool use_delays=false;
+
+    int spike_removal=3;
+
+    // The gain as extracted from our dark count spectra
+    double gain = 258;
+
+    // ------------------------------------------------------
+
+    // Extraction range in slices. It will always(!) contain the full range
+    // of integration
+    const int first_slice =  25; //  10ns
+    const int last_slice  = 225; // 125ns
+
+    // Note that rise and fall time mean different things whether you use IntegralFixed or IntegraRel:
+    //
+    //  IntegralFixed:
+    //    * fRiseTime: Number of slices left  from arrival time
+    //    * fFallTime: Number of slices right from arrival time
+    //  IntegralRel:
+    //    * fRiseTime: Number of slices left  from maximum time
+    //    * fFallTime: Number of slices right from maximum time
+    //
+/*
+    const int rise_time_cal = maximum ?  40 :  10; // was 13;   5ns
+    const int fall_time_cal = maximum ? 120 : 160; // was 23;  80ns
+
+    const int rise_time_dat = maximum ?  10 :   2; // was 13; was 10;   1ns
+    const int fall_time_dat = maximum ?  40 :  48; // was 23; was 40;  24ns
+
+    // Extraction type: Extract integral and half leading edge
+
+    const int type = maximum ? (MExtralgoSpline::kAmplitudeRel) : (MExtralgoSpline::kIntegralFixed);
+    //const int type = MExtralgoSpline::kIntegralFixed;
+
+
+    const double heighttm   = 0.5; // IntegralAbs { 1.5pe * 9.6mV/pe } / IntegralRel { 0.5 }
+*/
+    Long_t max  =    0;  // All
+    Long_t max0 =  max;  // Time marker
+    //Long_t max1 =  max;  // Light pulser
+    //Long_t max2 = 3000;  // Calibration ratio
+    //Long_t max3 =  max;  // Pedestal Rndm
+    //Long_t max4 =  max;  // Pedestal Ext
+    Long_t max5 =  max;  // Data
+
+    // ======================================================
+
+    if (map && gSystem->AccessPathName(map, kFileExists))
+    {
+        gLog << err << "ERROR - Cannot access mapping file '" << map << "'" << endl;
+        return 1;
+    }
+
+    // The sequence file which defines the files for the analysis
+    MSequence seq(seqfile);
+    if (!seq.IsValid())
+    {
+        gLog << err << "ERROR - Sequence '" << seqfile << "' invalid!" << endl;
+        return 2;
+    }
+
+    // --------------------------------------------------------------------------------
+
+    gLog.Separator("Callisto");
+    gLog << all << "Calibrate data of sequence '" << seq.GetFileName() << "'" << endl;
+    gLog << endl;
+
+    // ------------------------------------------------------
+
+    ostringstream drsname;
+    drsname << gSystem->DirName(seqfile) << "/";
+    drsname << seq.GetNight().GetNightAsInt() << "_";
+    drsname << Form("%03d", seq.GetDrsSequence()) << ".drs.seq";
+
+    MSequence drs(drsname.str().c_str());
+    if (!drs.IsValid())
+    {
+        gLog << err << "ERROR - DRS sequence invalid!" << endl;
+        return 3;
+    }
+
+    gLog << all << "DRS sequence file: " << drsname.str() << '\n' << endl;
+
+    TString drsfile = seq.GetFileName(0, MSequence::kRawDrs);
+    if (drsfile.IsNull())
+    {
+        gLog << err << "No DRS file available in sequence." << endl;
+        return 4;
+    }
+
+    TString timfile = drs.GetFileName(0, MSequence::kFitsDat);
+    TString drs1024 = drs.GetFileName(0, MSequence::kFitsDrs);
+    TString calfile = seq.GetFileName(0, MSequence::kFitsCal);
+    //TString pedfile = seq.GetFileName(0, MSequence::kFitsPed);
+
+    gLog << all;
+    gLog << "DRS calib     300: " << drsfile << '\n';
+    gLog << "DRS calib    1024: " << drs1024 << "\n\n";
+
+    MDrsCalibration drscalib300;
+    if (!drscalib300.ReadFits(drsfile.Data()))
+        return 5;
+
+    MDrsCalibration drscalib1024;
+    if (!drscalib1024.ReadFits(drs1024.Data()))
+        return 6;
+
+    gLog << all;
+    gLog << "Time calibration : " << timfile << '\n';
+    gLog << "Light Pulser file: " << calfile << '\n' << endl;
+    //gLog << "Pedestal     file: " << pedfile << '\n';
+
+    // ------------------------------------------------------
+
+    MDirIter iter;
+    if (seq.GetRuns(iter, MSequence::kFitsDat)<=0)
+    {
+        gLog << err << "ERROR - Sequence valid but without files." << endl;
+        return 7;
+    }
+    iter.Print();
+
+    // ======================================================
+
+    MStatusArray arrt, arrp;
+
+    TFile ft(lp_template);
+    if (arrt.Read()<=0)
+    {
+        gLog << err << "ERROR - Reading LP template from " << lp_template << endl;
+        return 100;
+    }
+
+    MHCamera *lpref = (MHCamera*)arrt.FindObjectInCanvas("ExtCalSig;avg", "MHCamera", "Cam");
+    if (!lpref)
+    {
+        gLog << err << "ERROR - LP Template not found in " << lp_template << endl;
+        return 101;
+    }
+    lpref->SetDirectory(0);
+
+    MHCamera *gain = (MHCamera*)arrt.FindObjectInCanvas("gain", "MHCamera", "Gain");
+    if (!gain)
+    {
+        gLog << err << "ERROR - Gain not found in " << lp_template << endl;
+        return 101;
+    }
+    gain->SetDirectory(0);
+
+    TFile fp(pulse_template);
+    if (arrp.Read()<=0)
+    {
+        gLog << err << "ERROR - Reading Pulse template from " << pulse_template << endl;
+        return 102;
+    }
+
+    TH1F *hpulse = (TH1F*)arrp.FindObjectInCanvas("hPixelEdgeMean0_0", "TH1F", "cgpPixelPulses0");
+    if (!hpulse)
+    {
+        gLog << err << "ERROR - Pulse Template not found in " << pulse_template << endl;
+        return 103;
+    }
+    hpulse->SetDirectory(0);
+
+    // ======================================================
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MBadPixelsCam badpixels;
+    badpixels.InitSize(1440);
+    badpixels[ 424].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 583].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 830].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 923].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[1208].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[1399].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+
+    //  Twin pixel
+    //     113
+    //     115
+    //     354
+    //     423
+    //    1195
+    //    1393
+
+    MDrsCalibrationTime timecam;
+
+    // Plot the trigger pattern rates vs. run-number
+    MH3 hrate("MRawRunHeader.GetFileID", "MRawEvtHeader.GetTriggerID&0xff00");
+    hrate.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hrate.SetName("Rate");
+    hrate.SetTitle("Event rate [Hz];File Id;Trigger Type;");
+    hrate.InitLabels(MH3::kLabelsXY);
+    hrate.DefineLabelY(    0, "Data"); // What if TriggerID==0 already???
+    hrate.DefineLabelY(0x100, "Cal");
+    hrate.DefineLabelY(0x400, "Ped");
+    // hrate.DefaultLabelY("ERROR");
+
+    Bool_t isinteg =
+        (type&MExtralgoSpline::kIntegral)    ||
+        (type&MExtralgoSpline::kFixedWidth)  ||
+        (type&MExtralgoSpline::kDynWidth)
+        ? kTRUE : kFALSE;
+
+    gStyle->SetOptFit(kTRUE);
+
+    // ======================================================
+
+    gLog << endl;
+    gLog.Separator("Processing DRS timing calibration run");
+
+    MTaskList tlist0;
+
+    MParList plist0;
+    plist0.AddToList(&tlist0);
+    plist0.AddToList(&drscalib1024);
+    plist0.AddToList(&badpixels);
+    plist0.AddToList(&timecam);
+
+    MEvtLoop loop0("DetermineTimeCal");
+    loop0.SetDisplay(d);
+    loop0.SetParList(&plist0);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read0(timfile);
+
+    MContinue cont0("MRawEvtHeader.GetTriggerID!=33792", "SelectTim");
+
+    MGeomApply apply0;
+
+    MDrsCalibApply drsapply0;
+    drsapply0.SetRemoveSpikes(spike_removal);
+
+    MFillH fill0("MHDrsCalibrationTime");
+    fill0.SetNameTab("DeltaT");
+
+    tlist0.AddToList(&read0);
+    tlist0.AddToList(&apply0);
+    tlist0.AddToList(&drsapply0);
+    tlist0.AddToList(&cont0);
+    tlist0.AddToList(&fill0);
+
+    if (!loop0.Eventloop(max0))
+        return 8;
+
+    if (!loop0.GetDisplay())
+        return 9;
+
+    /*
+     MHDrsCalibrationT *t = (MHDrsCalibrationT*)plist4.FindObject("MHDrsCalibrationT");
+     t->SetDisplay(d);
+     t->PlotAll();
+     */
+
+    // ======================================================
+/*
+    gLog << endl;
+    gLog.Separator("Processing external light pulser run");
+
+    MTaskList tlist1;
+
+    MParList plist1;
+    plist1.AddToList(&tlist1);
+    plist1.AddToList(&drscalib300);
+    plist1.AddToList(&badpixels);
+    plist1.AddToList(&timecam);
+
+    MEvtLoop loop1("DetermineCalConst");
+    loop1.SetDisplay(d);
+    loop1.SetParList(&plist1);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read1;
+    read1.LoadMap(map);
+    read1.AddFile(calfile);
+
+    MContinue cont1("(MRawEvtHeader.GetTriggerID&0xff00)!=0x100", "SelectCal");
+
+    MGeomApply apply1;
+
+    MDrsCalibApply drsapply1;
+    drsapply1.SetRemoveSpikes(spike_removal);
+
+    // ---
+
+    MExtractTimeAndChargeSpline extractor1b("ExtractPulse");
+    extractor1b.SetRange(first_slice, last_slice);
+    extractor1b.SetRiseTimeHiGain(rise_time_cal);
+    extractor1b.SetFallTimeHiGain(fall_time_cal);
+    extractor1b.SetHeightTm(heighttm);
+    extractor1b.SetChargeType(type);
+    extractor1b.SetSaturationLimit(600000);
+    extractor1b.SetNoiseCalculation(kFALSE);
+
+    MExtractTimeAndChargeSpline extractor1c("ExtractAmplitude");
+    extractor1c.SetRange(first_slice, last_slice);
+    extractor1c.SetChargeType(MExtralgoSpline::kAmplitude);
+    extractor1c.SetSaturationLimit(600000);
+    extractor1c.SetNoiseCalculation(kFALSE);
+    extractor1c.SetNameSignalCam("Amplitude");
+    extractor1c.SetNameTimeCam("AmplitudePos");
+
+    // ---
+
+    MHCamEvent evt1a(5, "CalRatio", "Ratio per slice between integrated signal and amplitude;; r [1/n]");
+    evt1a.SetNameSub("Amplitude", kTRUE);
+    MFillH fill1a(&evt1a, "MExtractedSignalCam", "FillRatio");
+    fill1a.SetDrawOption("gaus");
+
+    MParameterD ratio1a;
+    ratio1a.SetVal(1./(fall_time_cal+rise_time_cal));
+    fill1a.SetWeight(&ratio1a);
+
+    // ---
+
+    MHCamEvent evt1f(0, "ExtCalSig", "Extracted calibration signal;;S [mV·sl]");
+    MHCamEvent evt1g(4, "ExtCalTm",  "Extracted arrival times;;T [sl]");
+    MHCamEvent evt1h(6, "CalCalTm",  "Calibrated arrival times;;T [sl]");
+
+    MHSectorVsTime hist1rmsb("ExtSigVsTm");
+    MHSectorVsTime hist1tmb("CalTmVsTm");
+    hist1rmsb.SetTitle("Extracted calibration vs event number;;S [mV·sl]");
+    hist1rmsb.SetType(0);
+    hist1tmb.SetTitle("Extracted arrival time vs event number;;T [sl]");
+    //hist1tmb.SetType(4);
+    hist1tmb.SetType(6);
+
+    MFillH fill1f(&evt1f, "MExtractedSignalCam", "FillExtSig");
+    MFillH fill1g(&evt1g, "MArrivalTimeCam",     "FillExtTm");
+    MFillH fill1h(&evt1h, "MSignalCam",          "FillCalTm");
+    MFillH fill1r(&hist1rmsb, "MExtractedSignalCam", "FillExtSigVsTm");
+    //MFillH fill1j(&hist1tmb,  "MArrivalTimeCam",     "FillExtTmVsTm");
+    MFillH fill1j(&hist1tmb,  "MSignalCam",     "FillCalTmVsTm");
+
+    fill1f.SetDrawOption("gaus");
+    fill1h.SetDrawOption("gaus");
+
+    // ---
+
+    MCalibrateDrsTimes calctm1a("CalibrateCalEvents");
+    calctm1a.SetNameUncalibrated("UncalibratedTimes");
+
+    MBadPixelsTreat treat1;
+    treat1.SetProcessPedestalRun(kFALSE);
+    treat1.SetProcessPedestalEvt(kFALSE);
+
+    // ---
+
+    MHCamEvent evt1c(6, "ExtCalTmShift", "Relative extracted arrival time of calibration pulse (w.r.t. event-median);;\\Delta T [ns]");
+    MHCamEvent evt1d(6, "CalCalTmShift", "Relative calibrated arrival time of calibration pulse (w.r.t. event-median);;\\Delta T [ns]");
+
+    evt1c.SetMedianShift();
+    evt1d.SetMedianShift();
+
+    MFillH fill1c(&evt1c, "UncalibratedTimes", "FillExtCalTm");
+    MFillH fill1d(&evt1d, "MSignalCam",        "FillCalCalTm");
+    fill1d.SetDrawOption("gaus");
+
+    // ------------------ Setup eventloop and run analysis ---------------
+
+    tlist1.AddToList(&read1);
+    tlist1.AddToList(&apply1);
+    tlist1.AddToList(&drsapply1);
+    tlist1.AddToList(&cont1);
+    tlist1.AddToList(&extractor1b);
+    if (isinteg)
+    {
+        tlist1.AddToList(&extractor1c);
+        tlist1.AddToList(&fill1a);
+    }
+    tlist1.AddToList(&calctm1a);
+    tlist1.AddToList(&treat1);
+    tlist1.AddToList(&fill1f);
+    tlist1.AddToList(&fill1g);
+    tlist1.AddToList(&fill1h);
+    tlist1.AddToList(&fill1r);
+    tlist1.AddToList(&fill1j);
+    tlist1.AddToList(&fill1c);
+    tlist1.AddToList(&fill1d);
+
+    if (!loop1.Eventloop(max1))
+        return 10;
+
+    if (!loop1.GetDisplay())
+        return 11;
+
+    if (use_delays)
+        timecam.SetDelays(*evt1h.GetHist());
+
+    // ========================= Result ==================================
+
+    Double_t avgS = evt1f.GetHist()->GetMean();
+    Double_t medS = evt1f.GetHist()->GetMedian();
+    Double_t rmsS = evt1f.GetHist()->GetRMS();
+    Double_t maxS = evt1f.GetHist()->GetMaximum();
+
+    MArrayF der1(hpulse->GetNbinsX());
+    MArrayF der2(hpulse->GetNbinsX());
+
+    MExtralgoSpline spline(hpulse->GetArray()+1, hpulse->GetNbinsX(),
+                           der1.GetArray(), der2.GetArray());
+    spline.SetRiseFallTime(rise_time_dat, fall_time_dat);
+    spline.SetExtractionType(type);
+    spline.SetHeightTm(heighttm);
+
+    spline.Extract(hpulse->GetMaximumBin()-1);
+
+    // The pulser signal is most probably around 400mV/9.5mV
+    // IntegraFixed 2/48 corresponds to roughly 215mV*50slices
+    Double_t scale = 1./spline.GetSignal();
+
+    MArrayD calib(1440);
+    for (int i=0; i<1440; i++)
+    {
+        Double_t g = gain->GetBinContent(i+1)>0.5 ? gain->GetBinContent(i+1) : 1;
+        if (evt1f.GetHist()->GetBinContent(i+1)>0 && !badpixels[i].IsUnsuitable())
+            calib[i] = lpref->GetBinContent(i+1) / evt1f.GetHist()->GetBinContent(i+1) / g;
+    }
+
+    gROOT->SetSelectedPad(0);
+    d->AddTab("PulseTemp");
+    gPad->SetGrid();
+    hpulse->SetNameTitle("Pulse", "Single p.e. pulse template");
+    hpulse->SetDirectory(0);
+    hpulse->SetLineColor(kBlack);
+    hpulse->DrawCopy();
+
+    TAxis *ax = hpulse->GetXaxis();
+
+    Double_t w = hpulse->GetBinWidth(1);
+    Double_t T = w*(spline.GetTime()+0.5)       +ax->GetXmin();
+    Double_t H = w*(hpulse->GetMaximumBin()+0.5)+ax->GetXmin();
+
+    TLine line;
+    line.SetLineColor(kRed);
+    line.DrawLine(T-rise_time_dat*w, spline.GetHeight(),
+                  T+fall_time_dat*w, spline.GetHeight());
+    line.DrawLine(T, spline.GetHeight()/4, T, 3*spline.GetHeight()/4);
+    line.DrawLine(T-rise_time_dat*w, 0,
+                  T-rise_time_dat*w, spline.GetHeight());
+    line.DrawLine(T+fall_time_dat*w, 0,
+                  T+fall_time_dat*w, spline.GetHeight());
+
+    TGraph gg;
+    for (int ix=1; ix<=hpulse->GetNbinsX(); ix++)
+        for (int i=0; i<10; i++)
+        {
+            Double_t x = hpulse->GetBinLowEdge(ix)+i*hpulse->GetBinWidth(ix)/10.;
+            gg.SetPoint(gg.GetN(), x+w/2, spline.EvalAt(ix-1+i/10.));
+        }
+
+    gg.SetLineColor(kBlue);
+    gg.SetMarkerColor(kBlue);
+    gg.SetMarkerStyle(kFullDotMedium);
+    gg.DrawClone("L");
+
+    gROOT->SetSelectedPad(0);
+    d->AddTab("CalConst");
+    MGeomCamFACT fact;
+    MHCamera hcalco(fact);
+    hcalco.SetName("CalConst");
+    hcalco.SetTitle(Form("Relative calibration constant [%.0f/pe]", 1./scale));
+    hcalco.SetCamContent(calib);
+    hcalco.SetAllUsed();
+    //hcalco.Scale(scale);
+    hcalco.DrawCopy();
+*/
+
+    TF1 f("f", "[0]*(1-1/(1+exp(x/[1])))*exp(-x/[2])", -15, 150);
+    f.SetParameter(0, gain*0.05143);
+    f.SetParameter(1, 1.075);
+    f.SetParameter(2, 19.3);
+    f.SetNpx(2*165); //2GHz
+
+    // Convert to graph
+    TGraph g(&f);
+
+    // Convert to float
+    MArrayF x(g.GetN());
+    MArrayF y(g.GetN());
+    for (int i=0; i<g.GetN(); i++)
+    {
+        x[i] = g.GetX()[i];
+        y[i] = g.GetY()[i];
+    }
+
+    MFilterData filter;
+    filter.Filter(1, g.GetN(), y.GetArray(), y.GetArray());
+
+    // Define spline
+    MArrayF der1(g.GetN());
+    MArrayF der2(g.GetN());
+
+    MExtralgoSpline spline(y.GetArray(), y.GetSize(),
+                           der1.GetArray(), der2.GetArray());
+
+    spline.SetExtractionType(MExtralgoSpline::kAmplitudeRel);
+    spline.SetHeightTm(0.5);
+
+    // Estimate where the maximum is and extract signal
+    Long64_t maxi = TMath::LocMax(y.GetSize(), y.GetArray());
+    spline.Extract(maxi);
+
+    // Scale factor for signal extraction
+    double scale = 1./spline.GetSignal();
+
+    // ======================================================
+/*
+    gLog << endl;
+    gLog.Separator("Extracting random pedestal");
+
+    MTaskList tlist3;
+
+    MParList plist3;
+    plist3.AddToList(&tlist3);
+    plist3.AddToList(&drscalib300);
+    plist3.AddToList(&badpixels);
+    plist3.AddToList(&timecam);
+
+    MEvtLoop loop3("DetermineRndmPed");
+    loop3.SetDisplay(d);
+    loop3.SetParList(&plist3);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read3;
+    read3.LoadMap(map);
+    read3.AddFile(pedfile);
+
+    MFillH fill3a(&hrate);
+
+    MContinue cont3("(MRawEvtHeader.GetTriggerID&0xff00)!=0x400", "SelectPed");
+
+    MGeomApply apply3;
+
+    MDrsCalibApply drsapply3;
+    drsapply3.SetRemoveSpikes(spike_removal);
+
+    //---
+
+    MExtractTimeAndChargeSpline extractor3;
+    extractor3.SetRange(first_slice, last_slice);
+    extractor3.SetRiseTimeHiGain(rise_time_dat);
+    extractor3.SetFallTimeHiGain(fall_time_dat);
+    extractor3.SetHeightTm(heighttm);
+    extractor3.SetChargeType(type);
+    extractor3.SetSaturationLimit(600000);
+    extractor3.SetNoiseCalculation(kTRUE);
+
+    MCalibrateFact conv3;
+    conv3.SetScale(scale);
+    conv3.SetCalibConst(calib);
+
+    MBadPixelsTreat treat3;
+    treat3.SetProcessPedestalRun(kFALSE);
+    treat3.SetProcessPedestalEvt(kFALSE);
+    treat3.SetProcessTimes(kFALSE);
+
+    MHCamEvent evt3b(0, "PedRdm","Interpolated random pedestal;;Signal [~phe]");
+    //evt2b.SetErrorSpread(kFALSE);
+
+    MFillH fill3b(&evt3b, "MSignalCam", "FillPedRdm");
+    fill3b.SetDrawOption("gaus");
+
+    // ------------------ Setup eventloop and run analysis ---------------
+
+    tlist3.AddToList(&read3);
+    tlist3.AddToList(&apply3);
+    tlist3.AddToList(&drsapply3);
+    tlist3.AddToList(&cont3);
+    tlist3.AddToList(&extractor3);
+//    tlist3.AddToList(&fill3a);
+    tlist3.AddToList(&conv3);
+    tlist3.AddToList(&treat3);
+    tlist3.AddToList(&fill3b);
+
+    if (!loop3.Eventloop(max3))
+        return 14;
+
+    if (!loop3.GetDisplay())
+        return 15;
+
+    // ======================================================
+
+    gLog << endl;
+    gLog.Separator("Extracting pedestal");
+
+    MTaskList tlist4;
+
+    MParList plist4;
+    plist4.AddToList(&tlist4);
+    plist4.AddToList(&drscalib300);
+    plist4.AddToList(&badpixels);
+    plist4.AddToList(&timecam);
+
+    MEvtLoop loop4("DetermineExtractedPed");
+    loop4.SetDisplay(d);
+    loop4.SetParList(&plist4);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read4;
+    read4.LoadMap(map);
+    read4.AddFile(pedfile);
+
+    MContinue cont4("(MRawEvtHeader.GetTriggerID&0xff00)!=0x400", "SelectPed");
+
+    MGeomApply apply4;
+
+    MDrsCalibApply drsapply4;
+    drsapply4.SetRemoveSpikes(spike_removal);
+
+    MExtractTimeAndChargeSpline extractor4;
+    extractor4.SetRange(first_slice, last_slice);
+    extractor4.SetRiseTimeHiGain(rise_time_dat);
+    extractor4.SetFallTimeHiGain(fall_time_dat);
+    extractor4.SetHeightTm(heighttm);
+    extractor4.SetChargeType(type);
+    extractor4.SetSaturationLimit(600000);
+    extractor4.SetNoiseCalculation(kFALSE);
+
+    MCalibrateFact conv4;
+    conv4.SetScale(scale);
+    conv4.SetCalibConst(calib);
+
+    MBadPixelsTreat treat4;
+    treat4.SetProcessPedestalRun(kFALSE);
+    treat4.SetProcessPedestalEvt(kFALSE);
+
+    MHCamEvent evt4b(0, "PedExt","Interpolated extracted pedestal;;Signal [~phe]");
+    //evt4b.SetErrorSpread(kFALSE);
+
+    MFillH fill4b(&evt4b, "MSignalCam", "FillPedExt");
+    fill4b.SetDrawOption("gaus");
+
+    // ------------------ Setup eventloop and run analysis ---------------
+
+    tlist4.AddToList(&read4);
+    tlist4.AddToList(&apply4);
+    tlist4.AddToList(&drsapply4);
+    tlist4.AddToList(&cont4);
+    tlist4.AddToList(&extractor4);
+//    tlist4.AddToList(&fill4a);
+    tlist4.AddToList(&conv4);
+    tlist4.AddToList(&treat4);
+    tlist4.AddToList(&fill4b);
+
+    if (!loop4.Eventloop(max4))
+        return 15;
+
+    if (!loop4.GetDisplay())
+        return 16;
+*/
+    // ===================================================================
+
+    gLog << endl;
+    gLog.Separator("Extracting and calibration data");
+
+    MTaskList tlist5;
+
+    MParList plist5;
+    plist5.AddToList(&tlist5);
+    plist5.AddToList(&drscalib300);
+    plist5.AddToList(&badpixels);
+    plist5.AddToList(&timecam);
+
+    MEvtLoop loop5("CalibratingData");
+    loop5.SetDisplay(d);
+    loop5.SetParList(&plist5);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read5;
+    read5.LoadMap(map);
+    read5.AddFiles(iter);
+
+    MFillH fill5a(&hrate);
+
+    MGeomApply apply5;
+
+    MDrsCalibApply drsapply5;
+    drsapply5.SetRemoveSpikes(spike_removal);
+
+    MFDataPhrase filterdat("(MRawEvtHeader.GetTriggerID&0xff00)==0",     "SelectDat");
+    MFDataPhrase filtercal("(MRawEvtHeader.GetTriggerID&0xff00)==0x100", "SelectCal");
+    MFDataPhrase filterped("(MRawEvtHeader.GetTriggerID&0xff00)==0x400", "SelectPed");
+    MFDataPhrase filterncl("(MRawEvtHeader.GetTriggerID&0xff00)!=0x100", "SelectNonCal");
+
+    //MContinue cont4("MRawEvtHeader.GetTriggerID!=4", "SelectData");
+
+    // ---
+
+    MTreatSaturation treatsat5;
+    MFilterData filterdata5;
+
+    MExtractFACT extractor5dat;
+    extractor5dat.SetRange(first_slice, last_slice);
+/*
+    MExtractTimeAndChargeSpline extractor5cal;
+    extractor5cal.SetRange(first_slice, last_slice);
+    extractor5cal.SetRiseTimeHiGain(rise_time_cal);
+    extractor5cal.SetFallTimeHiGain(fall_time_cal);
+    extractor5cal.SetHeightTm(heighttm);
+    extractor5cal.SetChargeType(type);
+    extractor5cal.SetSaturationLimit(600000);
+    extractor5cal.SetNoiseCalculation(kFALSE);
+
+    MExtractTimeAndChargeSpline extractor5tm("ExtractTM");
+    extractor5tm.SetRange(last_slice, 294);
+    extractor5tm.SetRiseTimeHiGain(1);
+    extractor5tm.SetFallTimeHiGain(1);
+    extractor5tm.SetHeightTm(0.5);
+    extractor5tm.SetChargeType(MExtralgoSpline::kAmplitudeRel);
+    extractor5tm.SetSaturationLimit(600000);
+    extractor5tm.SetNoiseCalculation(kFALSE);
+    extractor5tm.SetNameSignalCam("TimeMarkerAmplitude");
+    extractor5tm.SetNameTimeCam("TimeMarkerTime");
+*/
+    extractor5dat.SetFilter(&filterncl);
+    //extractor5cal.SetFilter(&filtercal);
+    //extractor4tm.SetFilter(&filtercal);
+
+    // ---
+    MCalibrateFact conv5;
+    conv5.SetScale(scale);
+    conv5.SetCalibConst(calib);
+
+    MCalibrateDrsTimes calctm5;
+    calctm5.SetNameUncalibrated("UncalibratedTimes");
+/*
+    MCalibrateDrsTimes calctm5tm("CalibrateTimeMarker");
+    calctm5tm.SetNameArrivalTime("TimeMarkerTime");
+    calctm5tm.SetNameUncalibrated("UncalTimeMarker");
+    calctm5tm.SetNameCalibrated("TimeMarker");
+    calctm5tm.SetTimeMarker();
+    //calctm4tm.SetFilter(&filtercal);
+
+    MHCamEvent evt5m(6, "ExtTm",      "Extracted arrival times of calibration pulse;;\\Delta T [ns]");
+    MHCamEvent evt5n(6, "CalTm",      "Calibrated arrival times of calibration pulse;;\\Delta T [ns]");
+    MHCamEvent evt5q(6, "ExtTmShift", "Relative extracted arrival times of calibration pulse (w.r.t. event-median);;\\Delta T [ns]");
+    MHCamEvent evt5r(6, "CalTmShift", "Relative calibrated arrival times of calibration pulse (w.r.t. event-median);;\\Delta T [ns]");
+    MHCamEvent evt5s(6, "ExtTM",      "Extracted absolute time marker position;;T [sl]");
+    MHCamEvent evt5t(6, "CalTM",      "Calibrated absolute time marker position;;T [ns]");
+    MHCamEvent evt5u(6, "ExtTMshift", "Relative extracted time marker position (w.r.t. event-median);;\\Delta T [ns]");
+    MHCamEvent evt5v(6, "CalTMshift", "Relative calibrated time marker position (w.r.t. event-median);;\\Delta T [ns]");
+    MHCamEvent evt5w(6, "ExtDiff",    "Difference between extracted arrival time of time marker and calibration pulse;;\\Delta T [ns]");
+    MHCamEvent evt5x(6, "CalDiff",    "Difference between calibrated arrival time of time marker and calibration pulse;;\\Delta T [ns]");
+
+    evt5w.SetNameSub("UncalibratedTimes");
+    evt5x.SetNameSub("MSignalCam");
+
+    evt5q.SetMedianShift();
+    evt5r.SetMedianShift();
+    evt5u.SetMedianShift();
+    evt5v.SetMedianShift();
+    //evt4w.SetMedianShift();
+    //evt4x.SetMedianShift();
+
+    MFillH fill5m(&evt5m, "UncalibratedTimes", "FillExtTm");
+    MFillH fill5n(&evt5n, "MSignalCam",        "FillCalTm");
+    MFillH fill5q(&evt5q, "UncalibratedTimes", "FillExtTmShift");
+    MFillH fill5r(&evt5r, "MSignalCam"       , "FillCalTmShift");
+    MFillH fill5s(&evt5s, "UncalTimeMarker",   "FillExtTM");
+    MFillH fill5t(&evt5t, "TimeMarker",        "FillCalTM");
+    MFillH fill5u(&evt5u, "UncalTimeMarker",   "FillExtTMshift");
+    MFillH fill5v(&evt5v, "TimeMarker",        "FillCalTMshift");
+    MFillH fill5w(&evt5w, "UncalTimeMarker",   "FillExtDiff");
+    MFillH fill5x(&evt5x, "TimeMarker",        "FillCalDiff");
+
+    fill5m.SetDrawOption("gaus");
+    fill5n.SetDrawOption("gaus");
+    fill5q.SetDrawOption("gaus");
+    fill5r.SetDrawOption("gaus");
+    //fill5s.SetDrawOption("gaus");
+    //fill5t.SetDrawOption("gaus");
+    //fill5u.SetDrawOption("gaus");
+    //fill5v.SetDrawOption("gaus");
+    //fill5w.SetDrawOption("gaus");
+    //fill5x.SetDrawOption("gaus");
+*/
+
+    MBadPixelsTreat treat5;
+    treat5.SetProcessPedestalRun(kFALSE);
+    treat5.SetProcessPedestalEvt(kFALSE);
+/*
+    MHSectorVsTime hist5cal("CalVsTm");
+    MHSectorVsTime hist5ped("PedVsTm");
+    hist5cal.SetTitle("Median calibrated calibration signal vs event number;;Signal [~phe]");
+    hist5ped.SetTitle("Median calibrated pedestal signal vs event number;;Signal [~phe]");
+    hist5cal.SetType(0);
+    hist5ped.SetType(0);
+    hist5cal.SetMinimum(0);
+    hist5ped.SetMinimum(0);
+    hist5cal.SetUseMedian();
+    hist5ped.SetUseMedian();
+    hist5cal.SetNameTime("MTime");
+    hist5ped.SetNameTime("MTime");
+
+    MFillH fill5cal(&hist5cal, "MSignalCam", "FillCalVsTm");
+    MFillH fill5ped(&hist5ped, "MSignalCam", "FillPedVsTm");
+    fill5cal.SetFilter(&filtercal);
+    fill5ped.SetFilter(&filterped);
+*/
+    MHCamEvent evt5b(0, "ExtSig",   "Extracted signal;;S [mV·sl]");
+    MHCamEvent evt5c(0, "CalSig",   "Calibrated and interpolated signal;;S [~phe]");
+    MHCamEvent evt5d(4, "ExtSigTm", "Extracted time;;T [sl]");
+    MHCamEvent evt5e(6, "CalSigTm", "Calibrated and interpolated time;;T [ns]");
+
+    MFillH fill5b(&evt5b, "MExtractedSignalCam", "FillExtSig");
+    MFillH fill5c(&evt5c, "MSignalCam",          "FillCalSig");
+    MFillH fill5d(&evt5d, "MArrivalTimeCam",     "FillExtTm");
+    MFillH fill5e(&evt5e, "MSignalCam",          "FillCalTm");
+
+    fill5c.SetDrawOption("gaus");
+    fill5d.SetDrawOption("gaus");
+    fill5e.SetDrawOption("gaus");
+
+    /*
+    fill4b.SetFilter(&filterdat);
+    fill4c.SetFilter(&filterdat);
+    fill4d.SetFilter(&filterdat);
+    fill4e.SetFilter(&filterdat);
+    */
+
+    //MFSoftwareTrigger swtrig;
+    //MContinue contsw(&swtrig, "FilterSwTrigger", "Software trigger");
+    //contsw.SetInverted();
+
+    const TString fname(Form("s/([0-9]+_[0-9]+)[.]fits([.][fg]z)?$/%s\\/$1_C.root/",
+                             MJob::Esc(outpath).Data()));
+
+    // The second rule is for the case reading raw-files!
+    MWriteRootFile write5(2, fname, "RECREATE", "Calibrated Data");
+    write5.AddContainer("MRawRunHeader",       "RunHeaders");
+    write5.AddContainer("MGeomCam",            "RunHeaders");
+    write5.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE);
+    write5.AddContainer("MCorsikaRunHeader",   "RunHeaders", kFALSE);
+    write5.AddContainer("MMcRunHeader",        "RunHeaders", kFALSE);
+
+    // Common events
+    write5.AddContainer("MCorsikaEvtHeader",   "Events", kFALSE);
+    write5.AddContainer("MMcEvt",              "Events", kFALSE);
+    write5.AddContainer("IncidentAngle",       "Events", kFALSE);
+    write5.AddContainer("MPointingPos",        "Events", kFALSE);
+    write5.AddContainer("MSignalCam",          "Events");
+    write5.AddContainer("MTime",               "Events", kFALSE);
+    write5.AddContainer("MRawEvtHeader",       "Events");
+
+    // ------------------ Setup histograms and fill tasks ----------------
+
+    MContinue test;
+    test.SetFilter(&filterncl);
+/*
+    MTaskList tlist5tm;
+    tlist5tm.AddToList(&extractor5tm);
+    tlist5tm.AddToList(&calctm5tm);
+    tlist5tm.AddToList(&fill5m);
+    tlist5tm.AddToList(&fill5n);
+    tlist5tm.AddToList(&fill5q);
+    tlist5tm.AddToList(&fill5r);
+    //tlist5tm.AddToList(&fill5s);
+    //tlist5tm.AddToList(&fill5t);
+    tlist5tm.AddToList(&fill5u);
+    tlist5tm.AddToList(&fill5v);
+    tlist5tm.AddToList(&fill5w);
+    tlist5tm.AddToList(&fill5x);
+    tlist5tm.SetFilter(&filtercal);
+*/
+    MTaskList tlist5dat;
+    tlist5dat.AddToList(&fill5b);
+    tlist5dat.AddToList(&fill5c);
+    tlist5dat.AddToList(&fill5d);
+    tlist5dat.AddToList(&fill5e);
+    tlist5dat.SetFilter(&filterdat);
+
+    tlist5.AddToList(&read5);
+    tlist5.AddToList(&apply5);
+    tlist5.AddToList(&drsapply5);
+    tlist5.AddToList(&filterncl);
+    //tlist5.AddToList(&test);
+    tlist5.AddToList(&filterdat);
+    tlist5.AddToList(&filtercal);
+    tlist5.AddToList(&filterped);
+    tlist5.AddToList(&fill5a);
+    tlist5.AddToList(&treatsat5);
+    tlist5.AddToList(&filterdata5);
+    tlist5.AddToList(&extractor5dat);
+    //tlist5.AddToList(&extractor5cal);
+    tlist5.AddToList(&calctm5);
+    //tlist5.AddToList(&tlist5tm);
+    tlist5.AddToList(&conv5);
+    tlist5.AddToList(&treat5);
+    //tlist5.AddToList(&fill5ped);
+    //tlist5.AddToList(&fill5cal);
+    tlist5.AddToList(&tlist5dat);
+    tlist5.AddToList(&write5);
+
+    if (!loop5.Eventloop(max4))
+        return 18;
+
+    if (!loop5.GetDisplay())
+        return 19;
+
+    TString title = "--  Calibrated signal #";
+    title += seq.GetSequence();
+    title += " (";
+    title += drsfile;
+    title += ")  --";
+    d->SetTitle(title, kFALSE);
+
+    TString path;
+    path += Form("%s/20%6d_%03d-calibration.root", outpath,
+                 seq.GetSequence()/1000, seq.GetSequence()%1000);
+
+    d->SaveAs(path);
+
+    return 0;
+}
+
+int callisto(const ULong64_t seqnum, const char *outpath = "output")
+{
+    UInt_t night = seqnum/1000;
+    UInt_t num   = seqnum%1000;
+
+    TString file = Form("/scratch/fact/sequences/%04d/%02d/%02d/%06d_%03d.seq",
+                        night/10000, (night/100)%100, night%100, num);
+
+    return callisto(file.Data(), outpath);
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/extract_aux.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/extract_aux.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/extract_aux.C	(revision 17960)
@@ -0,0 +1,375 @@
+#include <iostream>
+
+#include <TString.h>
+#include <TFile.h>
+#include <TGraph.h>
+
+#include "zfits.h"
+#include "PixelMap.h"
+#include "Interpolator2D.h"
+
+#include "MMath.h"
+#include "MHCamera.h"
+#include "MGeomCamFACT.h"
+
+PixelMap pmap;
+
+bool extract_current(UInt_t day, double tstart, double tstop, MHCamera &havg, MHCamera &hrms, TGraph &g)
+{
+    TString naux = Form("/fact/aux/%4d/%02d/%02d/%8d.FEEDBACK_CALIBRATED_CURRENTS.fits",
+                        day/10000, (day/100)%100, day%100, day);
+
+    // =====================================================================
+
+    // Now we read the temperatures of the sensors during the
+    // single pe run and average them
+    fits faux(naux.Data());
+    if (!faux)
+    {
+        cout << "Could not open " << naux << endl;
+        return false;
+    }
+
+    Double_t time;
+    Float_t  I[416];
+
+    if (!faux.SetPtrAddress("Time",  &time))
+        return false;
+    if (!faux.SetPtrAddress("I", I))
+        return false;
+
+    TArrayD avg(320);
+    TArrayD rms(320);
+    TArrayI cnt(320);
+
+    while (faux.GetNextRow())
+    {
+        if (time<tstart || time>tstop)
+            continue;
+
+        TArrayD med(320);
+
+        int j=0;
+        for (int i=0; i<320; i++)
+        {
+            if (i!=66 && i!=191 && i!=193 && i!=17 && i!=206)
+                med[j++]  = I[i];
+
+            avg[i] += I[i];
+            rms[i] += I[i]*I[i];
+            cnt[i]++;
+        }
+
+        Double_t median;
+        MMath::MedianDev(315, med.GetArray(), median);
+        g.SetPoint(g.GetN(), time, median);
+    }
+
+    if (cnt[0]==0)
+        return 2;
+
+    for (int i=0; i<320; i++)
+    {
+        avg[i] /= cnt[i];
+        rms[i] /= cnt[i];
+        rms[i] -= avg[i]*avg[i];
+        rms[i] = rms[i]<0 ? 0 : sqrt(rms[i]);
+    }
+
+    double mn = 0;
+    for (int i=0; i<1440; i++)
+    {
+        mn += avg[pmap.index(i).hv()];
+        havg.SetBinContent(i+1, avg[pmap.index(i).hv()]);
+        hrms.SetBinContent(i+1, rms[pmap.index(i).hv()]);
+    }
+
+    return true;
+}
+
+bool extract_dac(UInt_t day, double tstart, double tstop, MHCamera &havg, MHCamera &hrms, TGraph &g)
+{
+    TString naux = Form("/fact/aux/%4d/%02d/%02d/%8d.BIAS_CONTROL_DAC.fits",
+                        day/10000, (day/100)%100, day%100, day);
+
+    // =====================================================================
+
+    // Now we read the temperatures of the sensors during the
+    // single pe run and average them
+    fits faux(naux.Data());
+    if (!faux)
+    {
+        cout << "Could not open " << naux << endl;
+        return false;
+    }
+
+    Double_t time;
+    UShort_t dac[416];
+
+    if (!faux.SetPtrAddress("Time",  &time))
+        return false;
+    if (!faux.SetPtrAddress("U", dac))
+        return false;
+
+    TArrayD avg(320);
+    TArrayD rms(320);
+    TArrayI cnt(320);
+
+    while (faux.GetNextRow())
+    {
+        if (time<tstart || time>tstop)
+            continue;
+
+        TArrayD med(320);
+
+        for (int i=0; i<320; i++)
+        {
+            med[i]  = dac[i];
+            avg[i] += dac[i];
+            rms[i] += dac[i]*dac[i];
+            cnt[i]++;
+        }
+
+        Double_t median;
+        MMath::MedianDev(320, med.GetArray(), median);
+        g.SetPoint(g.GetN(), time, median);
+    }
+
+    if (cnt[0]==0)
+        return 2;
+
+    for (int i=0; i<320; i++)
+    {
+        avg[i] /= cnt[i];
+        rms[i] /= cnt[i];
+        rms[i] -= avg[i]*avg[i];
+        rms[i] = rms[i]<0 ? 0 : sqrt(rms[i]);
+    }
+
+    for (int i=0; i<1440; i++)
+    {
+        havg.SetBinContent(i+1, avg[pmap.index(i).hv()]);
+        hrms.SetBinContent(i+1, rms[pmap.index(i).hv()]);
+    }
+
+    return true;
+}
+
+bool extract_temp(UInt_t day, double tstart, double tstop, MHCamera &havg, MHCamera &hrms, TGraph &g)
+{
+    TString naux = Form("/fact/aux/%4d/%02d/%02d/%8d.FSC_CONTROL_TEMPERATURE.fits",
+                        day/10000, (day/100)%100, day%100, day);
+
+    Interpolator2D interpol;
+
+    const auto sens = Interpolator2D::ReadGrid("operation/sensor-pos.txt");
+    if (sens.size()!=31)
+    {
+        cout << "Reading sensor-pos.txt failed: " << interpol.getInputGrid().size() << endl;
+        return false;
+    }
+
+    // =====================================================================
+
+    // Now we read the temperatures of the sensors during the
+    // single pe run and average them
+    fits faux(naux.Data());
+    if (!faux)
+    {
+        cout << "Could not open " << naux << endl;
+        return false;
+    }
+
+    Double_t time;
+    Float_t  temp[31];
+
+    if (!faux.SetPtrAddress("Time",  &time))
+        return false;
+    if (!faux.SetPtrAddress("T_sens", temp))
+        return false;
+
+    TArrayD avg(31);
+    TArrayD rms(31);
+    TArrayI cnt(31);
+
+    while (faux.GetNextRow())
+    {
+        if (time<tstart || time>tstop)
+            continue;
+
+        double mean  = 0;
+        int    count = 0;
+
+        for (int i=0; i<31; i++)
+        {
+            if (temp[i]==0)
+                continue;
+
+            double T = temp[i];
+
+            mean += T;
+            count++;
+
+            avg[i] += T;
+            rms[i] += T*T;
+            cnt[i]++;
+        }
+
+        g.SetPoint(g.GetN(), time, mean/count);
+
+    }
+
+    vector<double> zavg;
+    vector<double> zrms;
+
+    vector<Interpolator2D::vec> pos;
+    for (int i=0; i<31; i++)
+    {
+        if (cnt[i]>0)
+        {
+            avg[i] /= cnt[i];
+            rms[i] /= cnt[i];
+            rms[i] -= avg[i]*avg[i];
+            rms[i] = rms[i]<0 ? 0 : sqrt(rms[i]);
+
+            pos.push_back(sens[i]);
+            zavg.push_back(avg[i]);
+            zrms.push_back(rms[i]);
+        }
+    }
+
+    // ================================================================
+
+    interpol.SetInputGrid(pos);
+
+    if (!interpol.ReadOutputGrid("operation/bias-positions.txt"))
+    {
+        cout << "Error setting output grid." << endl;
+        return false;
+    }
+    if (interpol.getOutputGrid().size()!=320)
+    {
+        cout << "Reading bias-positions.txt failed: " << interpol.getOutputGrid().size() << endl;
+        return false;
+    }
+
+    // ================================================================
+
+    const auto &input = interpol.getInputGrid();
+
+    TGraph sensors(input.size());
+
+    for (unsigned int i=0; i<input.size(); i++)
+        sensors.SetPoint(i, input[i].x, input[i].y);
+
+    const vector<double> rc_avg = interpol.Interpolate(zavg);
+    const vector<double> rc_rms = interpol.Interpolate(zrms);
+
+    // ================================================================
+
+    for (int i=0; i<1440; i++)
+    {
+        havg.SetBinContent(i+1, rc_avg[pmap.index(i).hv()]);
+        hrms.SetBinContent(i+1, rc_rms[pmap.index(i).hv()]);
+    }
+
+    return true;
+
+}
+
+void extract_aux(UInt_t day=20131114, UInt_t run=136, const char *output=0)
+{
+    if (!pmap.Read("operation/FACTmap111030.txt"))
+    {
+        cout << "FACTmap111030.txt not found." << endl;
+        return;
+    }
+
+    // =====================================================================
+
+    TString nraw = Form("/fact/raw/%4d/%02d/%02d/%8d_%03d.fits.fz",
+                        day/10000, (day/100)%100, day%100, day, run);
+
+
+    zfits fraw(nraw.Data());
+    if (!fraw)
+    {
+        cout << "Open raw file failed: " << nraw << endl;
+        return;
+    }
+
+    double tstart = fraw.GetUInt("TSTARTI") + fraw.GetFloat("TSTARTF");
+    double tstop  = fraw.GetUInt("TSTOPI")  + fraw.GetFloat("TSTOPF");
+
+    // =====================================================================
+
+    MGeomCamFACT geom;
+
+    TGraph gcur;
+    MHCamera hcur_m(geom);
+    MHCamera hcur_r(geom);
+    if (!extract_current(day, tstart, tstop, hcur_m, hcur_r, gcur))
+        return;
+
+    TGraph gtmp;
+    MHCamera htmp_m(geom);
+    MHCamera htmp_r(geom);
+    if (!extract_temp(day, tstart, tstop, htmp_m, htmp_r, gtmp))
+        return;
+
+    TGraph gdac;
+    MHCamera hdac_m(geom);
+    MHCamera hdac_r(geom);
+    if (!extract_dac(day, tstart, tstop, hdac_m, hdac_r, gdac))
+        return;
+
+    // ================================================================
+
+    TCanvas *c = new TCanvas;
+    c->Divide(3, 3);
+
+    c->cd(1);
+    hcur_m.SetName("CurrentAvg");
+    hcur_m.SetAllUsed();
+    hcur_m.DrawCopy();
+    c->cd(4);
+    hcur_r.SetName("CurrentRms");
+    hcur_r.SetAllUsed();
+    hcur_r.DrawCopy();
+    c->cd(7);
+    gcur.SetName("CurrentTime");
+    gcur.SetMarkerStyle(kFullDotMedium);
+    gcur.SetMinimum(0);
+    gcur.DrawClone("AP");
+
+    c->cd(2);
+    htmp_m.SetName("TempAvg");
+    htmp_m.SetAllUsed();
+    htmp_m.DrawCopy();
+    c->cd(5);
+    htmp_r.SetName("TempRms");
+    htmp_r.SetAllUsed();
+    htmp_r.DrawCopy();
+    c->cd(8);
+    gtmp.SetName("TempTime");
+    gtmp.SetMarkerStyle(kFullDotMedium);
+    gtmp.SetMinimum(0);
+    gtmp.DrawClone("AP");
+
+    c->cd(3);
+    hdac_m.SetName("DacAvg");
+    hdac_m.SetAllUsed();
+    hdac_m.DrawCopy();
+    c->cd(6);
+    hdac_r.SetName("DacRms");
+    hdac_r.SetAllUsed();
+    hdac_r.DrawCopy();
+    c->cd(9);
+    gdac.SetName("DacTime");
+    gdac.SetMarkerStyle(kFullDotMedium);
+    gdac.SetMinimum(0);
+    gdac.DrawClone("AP");
+
+    if (output)
+        c->SaveAs(output);
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/extract_aux.sh
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/extract_aux.sh	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/extract_aux.sh	(revision 17960)
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+macro=$PWD/extract_aux.C
+outpath=$PWD/aux
+
+mkdir -p $outpath
+cp ${macro} ${outpath}
+
+where="(((fNumPedestalTrigger=3000 OR fNumPedestalTrigger=5000) AND fRunTypeKey=2) OR (fNumPedestalTrigger=10000 AND fRunTypeKey=3) OR fRunTypeKey=17)"
+wheredrs="(drs.fROI=single.fROI AND fDrsStep=2)"
+
+query="SELECT Concat(fNight, '_', fRunID, '_', (SELECT fRunID FROM RunInfo \`drs\` WHERE drs.fNight=single.fNight AND "$wheredrs" AND single.fRunID<30+drs.fRunID ORDER BY ABS(CAST(single.fRunID AS SIGNED) - CAST(drs.fRunID AS SIGNED)) ASC LIMIT 0,1)) AS num "
+query=$query" FROM RunInfo \`single\` WHERE "$where" AND fNight>20130306 ORDER BY fNight DESC"
+
+runpairs=( `mysql -u factread --password=r3adfac! --host=lp-fact factdata -s -e "$query"` )
+
+for runpair in ${runpairs[@]}
+do
+   if [ $runpair = 'NULL' ]
+   then
+      continue
+   fi
+
+   night=`echo $runpair | cut -d_ -f1`
+   run=`echo $runpair | cut -d_ -f2`
+   runnum=`printf %03d $run`
+
+   log=$outpath"/"$night"_"$runnum
+
+   outfile=$outpath/${night}_${runnum}.root
+
+   if [ -e $outfile ]
+   then
+      continue
+   fi
+
+   cd ~/Mars
+
+   cmd="ROOT_HIST=0 ${ROOTSYS}/bin/root -q -b -l ${macro}+\($night,$run,\\\"${outfile}\\\"\)"
+
+   echo "date; echo '${cmd}'; ${cmd}" | qsub -N t${night}${runnum} -q test -cwd -e ${log}".err" -o ${log}".log"
+
+   cd - > /dev/null
+done
+
+
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/extract_singles.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/extract_singles.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/extract_singles.C	(revision 17960)
@@ -0,0 +1,902 @@
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+#include <TF1.h>
+#include <TProfile.h>
+#include <TProfile2D.h>
+#include <TMath.h>
+#include <TGraph.h>
+#include <TFitResultPtr.h>
+#include <TFitResult.h>
+#include <TFile.h>
+
+#include <cstdio>
+#include <stdio.h>
+#include <stdint.h>
+
+#include "MH.h"
+#include "MArrayI.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MDirIter.h"
+#include "MFillH.h"
+#include "MEvtLoop.h"
+#include "MCamEvent.h"
+#include "MHCamEvent.h"
+#include "MGeomApply.h"
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MContinue.h"
+#include "MBinning.h"
+#include "MDrsCalibApply.h"
+#include "MDrsCalibration.h"
+#include "MRawFitsRead.h"
+#include "MBadPixelsCam.h"
+#include "MStatusDisplay.h"
+#include "MTaskInteractive.h"
+#include "MPedestalSubtractedEvt.h"
+#include "MHCamera.h"
+#include "MGeomCamFACT.h"
+#include "MRawRunHeader.h"
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+#include "MParameters.h"
+
+using namespace std;
+using namespace TMath;
+
+// Structure to store the extracted value and the extracted time
+struct Single
+{
+    float    fSignal;
+    float    fTime;
+};
+
+//Storage class to kKeep a list of the extracted single
+class MSingles : public MParContainer, public MCamEvent
+{
+    Int_t fIntegrationWindow;
+
+    vector<vector<Single>> fData;
+
+public:
+    MSingles(const char *name=NULL, const char *title=NULL) : fIntegrationWindow(30)
+    {
+        fName = name ? name : "MSingles";
+        fName = title ? title : "Storeage for vector of singles";
+    }
+
+    void InitSize(const UInt_t i)
+    {
+        fData.resize(i);
+    }
+
+    vector<Single> &operator[](UInt_t i) { return fData[i]; }
+    vector<Single> &GetVector(UInt_t i)  { return fData[i]; }
+
+    UInt_t GetNumPixels() const { return fData.size(); }
+
+    void SetIntegrationWindow(Int_t w) { fIntegrationWindow = w; }
+    Int_t GetIntegrationWindow() const { return fIntegrationWindow; }
+
+    Bool_t GetPixelContent(Double_t &, Int_t , const MGeomCam &, Int_t) const
+    {
+        return kTRUE;
+    }
+    void   DrawPixelContent(Int_t) const { }
+
+    ClassDef(MSingles, 1)
+};
+
+// Histogram class to extract the baseline
+class MHBaseline : public MH
+{
+    TH2F fBaseline;
+
+    MPedestalCam *fPedestal;
+
+    // The baseline is only extracted where also the signal is extracted
+    // FIXME: Make sure this is consistent with MExtractSingles
+    UShort_t fSkipStart;
+    UShort_t fSkipEnd;
+
+public:
+    MHBaseline() : fPedestal(0), fSkipStart(20), fSkipEnd(10)
+    {
+        fName = "MHBaseline";
+
+        // Setup the histogram
+        fBaseline.SetName("Baseline");
+        fBaseline.SetTitle("Median spectrum");
+        fBaseline.SetXTitle("Pixel [idx]");
+        fBaseline.SetYTitle("Median baseline [mV]");
+        fBaseline.SetDirectory(NULL);
+    }
+
+    Bool_t ReInit(MParList *plist)
+    {
+        fPedestal = (MPedestalCam*)plist->FindCreateObj("MPedestalCam");
+        if (!fPedestal)
+            return kFALSE;
+
+        const MRawRunHeader *header = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+        if (!header)
+        {
+            *fLog << err << "MRawRunHeader not found... abort." << endl;
+            return kFALSE;
+        }
+
+        // Bin width should be around 1 dac count which is about 0.5mV
+        MBinning binsx, binsy;
+        binsx.SetEdges(header->GetNumNormalPixels(), -0.5, header->GetNumNormalPixels()-0.5);
+        binsy.SetEdges(100, -20.5, 29.5);
+
+        // Setup binnning
+        MH::SetBinning(fBaseline, binsx, binsy);
+
+        return kTRUE;
+    }
+
+    // Fill the samples into the histogram
+    Int_t Fill(const MParContainer *par, const Stat_t)
+    {
+        const MPedestalSubtractedEvt *evt = dynamic_cast<const MPedestalSubtractedEvt*>(par);
+
+        const Int_t n = evt->GetNumSamples()-fSkipStart-fSkipEnd;
+
+        // Loop over all pixels
+        for (int pix=0; pix<evt->GetNumPixels(); pix++)
+        {
+            // Get samples for each pixel
+            const Float_t *ptr = evt->GetSamples(pix);
+
+            // Average two consecutive samples
+            for (int i=0; i<n; i+=2)
+            {
+                const Double_t val = 0.5*ptr[i+fSkipStart]+0.5*ptr[i+1+fSkipStart];
+                fBaseline.Fill(pix, val);
+            }
+        }
+
+        return kTRUE;
+    }
+
+    // Extract the baseline value from the distrbutions
+    Bool_t Finalize()
+    {
+        if (!fPedestal)
+            return kTRUE;
+
+        fPedestal->InitSize(fBaseline.GetNbinsX());
+        fPedestal->SetNumEvents(GetNumExecutions());
+
+        Int_t    cnt = 0;
+        Double_t avg = 0;
+        Double_t rms = 0;
+
+        // Loop over all 'pixels'
+        for (int x=0; x<fBaseline.GetNbinsX(); x++)
+        {
+            // Get the corresponding slice from the histogram
+            TH1D *hist = fBaseline.ProjectionY("proj", x+1, x+1);
+
+            // Get the maximum bin
+            const Int_t bin  = hist->GetMaximumBin();
+
+            // Calculate a parabola through this and the surrounding points
+            // on logarithmic values (that's a gaussian)
+
+            //
+            // Quadratic interpolation
+            //
+            // calculate the parameters of a parabula such that
+            //    y(i)  = a + b*x(i) +   c*x(i)^2
+            //    y'(i) =     b      + 2*c*x(i)
+            //
+            //
+
+            // -------------------------------------------------------------------------
+            // a = y2;
+            // b = (y3-y1)/2;
+            // c = (y3+y1)/2 - y2;
+
+            const Double_t v1 = hist->GetBinContent(bin-1);
+            const Double_t v2 = hist->GetBinContent(bin);
+            const Double_t v3 = hist->GetBinContent(bin+1);
+            if (v1<=0 || v2<=0 || v3<=0)
+                continue;
+
+            const Double_t y1 = TMath::Log(v1);
+            const Double_t y2 = TMath::Log(v2);
+            const Double_t y3 = TMath::Log(v3);
+
+            //Double_t a = y2;
+            const Double_t b = (y3-y1)/2;
+            const Double_t c = (y1+y3)/2 - y2;
+            if (c>=0)
+                continue;
+
+            const Double_t w  = -1./(2*c);
+            const Double_t dx =  b*w;
+
+            if (dx<-1 || dx>1)
+                continue;
+
+            // y = exp( - (x-k)^2 / s^2 / 2 )
+            //
+            // -2*s^2 * log(y) = x^2 - 2*k*x + k^2
+            //
+            // a = (k/s0)^2/2
+            // b = k/s^2
+            // c = -1/(2s^2)      -->    s = sqrt(-1/2c)
+
+            const Double_t binx = hist->GetBinCenter(bin);
+            const Double_t binw = hist->GetBinWidth(bin);
+
+            //const Double_t p = hist->GetBinCenter(hist->GetMaximumBin());
+            const Double_t p = binx + dx*binw;
+
+            avg += p;
+            rms += p*p;
+
+            cnt++;
+
+            // Store baseline and sigma
+            MPedestalPix &pix = (*fPedestal)[x];
+
+            pix.SetPedestal(p);
+            pix.SetPedestalRms(TMath::Sqrt(w)*binw);
+
+            delete hist;
+        }
+
+        avg /= cnt;
+        rms /= cnt;
+
+        cout << "Baseline(" << cnt << "): " << avg << " +- " << sqrt(rms-avg*avg) << endl;
+
+        return kTRUE;
+    }
+
+    // Draw histogram
+    void Draw(Option_t *)
+    {
+        TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+        AppendPad("");
+
+        pad->SetBorderMode(0);
+        pad->SetFrameBorderMode(0);
+        fBaseline.Draw("colz");
+    }
+
+
+    ClassDef(MHBaseline, 1);
+};
+
+// Histogram class for the signal and time distribution as
+// well as the pulse shape
+class MHSingles : public MH
+{
+    TH2F       fSignal;
+    TH2F       fTime;
+    TProfile2D fPulse;
+
+    UInt_t fNumEntries;
+
+    MSingles               *fSingles;   //!
+    MPedestalSubtractedEvt *fEvent;     //!
+    MBadPixelsCam          *fBadPix;    //!
+
+public:
+    MHSingles() : fNumEntries(0), fSingles(0), fEvent(0)
+    {
+        fName = "MHSingles";
+
+        // Setup histograms
+        fSignal.SetName("Signal");
+        fSignal.SetTitle("pulse integral spectrum");
+        fSignal.SetXTitle("pixel [SoftID]");
+        fSignal.SetYTitle("time [a.u.]");
+        fSignal.SetDirectory(NULL);
+
+        fTime.SetName("Time");
+        fTime.SetTitle("arival time spectrum");
+        fTime.SetXTitle("pixel [SoftID]");
+        fTime.SetYTitle("time [a.u.]");
+        fTime.SetDirectory(NULL);
+
+        fPulse.SetName("Pulse");
+        fPulse.SetTitle("average pulse shape spectrum");
+        fPulse.SetXTitle("pixel [SoftID]");
+        fPulse.SetYTitle("time [a.u.]");
+        fPulse.SetDirectory(NULL);
+    }
+
+    Bool_t SetupFill(const MParList *plist)
+    {
+        fSingles = (MSingles*)plist->FindObject("MSingles");
+        if (!fSingles)
+        {
+            *fLog << err << "MSingles not found... abort." << endl;
+            return kFALSE;
+        }
+
+        fEvent = (MPedestalSubtractedEvt*)plist->FindObject("MPedestalSubtractedEvt");
+        if (!fEvent)
+        {
+            *fLog << err << "MPedestalSubtractedEvt not found... abort." << endl;
+            return kFALSE;
+        }
+
+        fBadPix = (MBadPixelsCam*)plist->FindObject("MBadPixelsCam");
+        if (!fBadPix)
+        {
+            *fLog << err << "MBadPixelsCam not found... abort." << endl;
+            return kFALSE;
+        }
+
+        fNumEntries = 0;
+
+        return kTRUE;
+    }
+
+    Bool_t ReInit(MParList *plist)
+    {
+        const MRawRunHeader *header = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+        if (!header)
+        {
+            *fLog << err << "MRawRunHeader not found... abort." << endl;
+            return kFALSE;
+        }
+
+        // Setup binning
+        const Int_t w = fSingles->GetIntegrationWindow();
+
+        MBinning binsx, binsy;
+        binsx.SetEdges(fSingles->GetNumPixels(), -0.5, fSingles->GetNumPixels()-0.5);
+        binsy.SetEdges(22*w, -10*w, 100*w);
+
+        MH::SetBinning(fSignal, binsx, binsy);
+
+        const UShort_t roi = header->GetNumSamples();
+
+        // Correct for DRS timing!!
+        MBinning binst(roi, -0.5, roi-0.5);
+        MH::SetBinning(fTime, binsx, binst);
+
+        MBinning binspy(2*roi, -roi-0.5, roi-0.5);
+        MH::SetBinning(fPulse, binsx, binspy);
+
+        return kTRUE;
+    }
+
+    // Fill singles into histograms
+    Int_t Fill(const MParContainer *, const Stat_t)
+    {
+        // Get pointer to samples to fill samples
+        const Float_t *ptr = fEvent->GetSamples(0);
+        const Short_t  roi = fEvent->GetNumSamples();
+
+        // Loop over all pixels
+        for (unsigned int i=0; i<fSingles->GetNumPixels(); i++)
+        {
+            if ((*fBadPix)[i].IsUnsuitable())
+                continue;
+
+            // loop over all singles
+            const vector<Single> &result = fSingles->GetVector(i);
+
+            for (unsigned int j=0; j<result.size(); j++)
+            {
+                // Fill signal and time
+                fSignal.Fill(i, result[j].fSignal);
+                fTime.Fill  (i, result[j].fTime);
+
+                if (!ptr)
+                    continue;
+
+                // Fill pulse shape
+                const Short_t tm = floor(result[j].fTime);
+
+                for (int s=0; s<roi; s++)
+                    fPulse.Fill(i, s-tm, ptr[s]);
+            }
+
+            ptr += roi;
+        }
+
+        fNumEntries++;
+
+        return kTRUE;
+    }
+
+    // Getter for histograms
+    const TH2 *GetSignal() const { return &fSignal; }
+    const TH2 *GetTime() const   { return &fTime; }
+    const TH2 *GetPulse() const  { return &fPulse; }
+
+    UInt_t GetNumEntries() const { return fNumEntries; }
+
+    void Draw(Option_t *)
+    {
+        TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+        AppendPad("");
+
+        pad->Divide(2,2);
+
+        pad->cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        fSignal.Draw("colz");
+
+        pad->cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        fTime.Draw("colz");
+
+        pad->cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        fPulse.Draw("colz");
+    }
+
+    void DrawCopy(Option_t *)
+    {
+        TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+        AppendPad("");
+
+        pad->Divide(2,2);
+
+        pad->cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        fSignal.DrawCopy("colz");
+
+        pad->cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        fTime.DrawCopy("colz");
+
+        pad->cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        fPulse.DrawCopy("colz");
+    }
+
+    ClassDef(MHSingles, 1)
+};
+
+// Task to extract the singles
+class MExtractSingles : public MTask
+{
+    MSingles *fSingles;
+    MPedestalCam *fPedestal;
+    MPedestalSubtractedEvt *fEvent;
+
+    // On time for each pixel in samples
+    MArrayI fExtractionRange;
+
+    // Number of samples for sliding average
+    size_t fNumAverage;
+
+    // The range in which the singles have to fit in
+    // FIXME: Make sure this is consistent with MHBaseline
+    UInt_t fStartSkip;
+    UInt_t fEndSkip;
+
+    UInt_t fIntegrationSize;
+    UInt_t fMaxSearchWindow;
+
+    Int_t    fMaxDist;
+    Double_t fThreshold;
+
+public:
+    MExtractSingles() : fSingles(0), fPedestal(0), fEvent(0),
+        fExtractionRange(1440),
+        fNumAverage(10), fStartSkip(20), fEndSkip(10),
+        fIntegrationSize(3*10), fMaxSearchWindow(30)
+    {
+    }
+
+    void SetMaxDist(Int_t m) { fMaxDist = m; }
+    void SetThreshold(Int_t th) { fThreshold = th; }
+
+    UInt_t GetIntegrationSize() const { return fIntegrationSize; }
+
+    const MArrayI &GetExtractionRange() const { return fExtractionRange; }
+
+
+    Int_t PreProcess(MParList *plist)
+    {
+        fSingles = (MSingles*)plist->FindCreateObj("MSingles");
+        if (!fSingles)
+            return kFALSE;
+
+        fEvent = (MPedestalSubtractedEvt*)plist->FindObject("MPedestalSubtractedEvt");
+        if (!fEvent)
+        {
+            *fLog << err << "MPedestalSubtractedEvt not found... abort." << endl;
+            return kFALSE;
+        }
+
+        fPedestal = (MPedestalCam*)plist->FindObject("MPedestalCam");
+        if (!fPedestal)
+        {
+            *fLog << err << "MPedestalCam not found... abort." << endl;
+            return kFALSE;
+        }
+
+        return kTRUE;
+    }
+
+    Int_t Process()
+    {
+        const UInt_t roi = fEvent->GetNumSamples();
+
+        const size_t navg              = fNumAverage;
+        const float  threshold         = fThreshold; 
+        const UInt_t start_skip        = fStartSkip;
+        const UInt_t end_skip          = fEndSkip;
+        const UInt_t integration_size  = fIntegrationSize;
+        const UInt_t max_search_window = fMaxSearchWindow;
+        const UInt_t max_dist          = fMaxDist;
+
+        vector<float> val(roi-navg);//result of first sliding average
+        for (int pix=0; pix<fEvent->GetNumPixels(); pix++)
+        {
+            // Total number of samples as 'on time'
+            fExtractionRange[pix] += roi-start_skip-navg-end_skip-integration_size;
+
+            // Clear singles for this pixel
+            vector<Single> &result = fSingles->GetVector(pix);
+            result.clear();
+
+            // Get pointer to samples
+            const Float_t *ptr = fEvent->GetSamples(pix);
+
+            // Get Baseline
+            const Double_t ped = (*fPedestal)[pix].GetPedestal();
+
+            // Subtract baseline and do a sliding average over
+            // the samples to remove noise (mainly the 200MHz noise)
+            for (size_t i=0; i<roi-navg; i++)
+            {
+                val[i] = 0;
+                for (size_t j=i; j<i+navg; j++)
+                    val[i] += ptr[j];
+                val[i] /= navg;
+                val[i] -= ped;
+            }
+
+            // peak finding via threshold
+            UInt_t imax = roi-navg-end_skip-integration_size;
+            for (UInt_t i=start_skip; i<imax; i++)
+            {
+                //search for threshold crossings
+                if (val[i+0]>threshold ||
+                    val[i+4]>threshold ||
+
+                    val[i+5]<threshold ||
+                    val[i+9]<threshold)
+                    continue;
+
+                //search for maximum after threshold crossing
+                UInt_t k_max = i+5;
+                for (UInt_t k=i+6; k<i+max_search_window; k++)
+                {
+                    if (val[k] > val[k_max])
+                        k_max = k;
+                }
+
+                // Check if the findings make sense
+                if (k_max == i+5 || k_max == i + max_search_window-1)
+                    continue;
+
+                //search for half maximum before maximum
+                UInt_t k_half_max = 0;
+                for (UInt_t k=k_max; k>k_max-25; k--)
+                {
+                    if (val[k-1] < val[k_max]/2 &&
+                        val[k] >= val[k_max]/2 )
+                    {
+                        k_half_max = k;
+                        break;
+                    }
+                }
+                // Check if the finding makes sense
+                if (k_half_max+integration_size > roi-navg-end_skip)
+                    continue;
+                if (k_half_max == 0)
+                    continue;
+                if (k_max - k_half_max > max_dist)
+                    continue;
+
+                // FIXME: Evaluate arrival time more precisely!!!
+                // FIXME: Get a better integration window
+
+                // Compile "single"
+                Single single;
+                single.fSignal = 0;
+                single.fTime   = k_half_max;
+
+                // Crossing of the threshold is at 5
+                for (UInt_t j=k_half_max; j<k_half_max+integration_size; j++)
+                    single.fSignal += ptr[j];
+
+                single.fSignal -= integration_size*ped;
+
+                // Add single to list
+                result.push_back(single);
+
+                // skip falling edge
+                i += 5+integration_size;
+
+                // Remove skipped samples from 'on time'
+                fExtractionRange[pix] -= i>imax ? 5+integration_size-(i-imax) : 5+integration_size;
+            }
+        }
+        return kTRUE;
+    }
+};
+
+int extract_singles(
+                    Int_t        max_dist   = 14,
+                    Double_t     threshold  =  5,
+                    const char  *runfile    = "/fact/raw/2012/07/23/20120723_",
+                    int          firstRunID =  6,
+                    int          lastRunID  =  6,
+                    const char  *drsfile    = "/fact/raw/2012/07/23/20120723_004.drs.fits.gz",
+                    const char  *outpath    = "."
+                   )
+{
+    // ======================================================
+
+    MDirIter iter;
+
+    // built outpu filename and path
+    TString outfile = Form("%s/", outpath);
+    outfile += gSystem->BaseName(runfile);
+    outfile += Form("%03d_%03d.root", firstRunID, lastRunID);
+
+
+    if (!gSystem->AccessPathName(outfile))
+        return 0;
+
+    // add input files to directory iterator
+    for (Int_t fileNr = firstRunID; fileNr <= lastRunID; fileNr++)
+    {
+        TString filename = runfile;
+        filename += Form("%03d.fits", fileNr);
+        iter.AddDirectory(gSystem->DirName(runfile), gSystem->BaseName(filename+".fz"));
+        iter.AddDirectory(gSystem->DirName(runfile), gSystem->BaseName(filename+".gz"));
+        iter.AddDirectory(gSystem->DirName(runfile), gSystem->BaseName(filename));
+    }
+
+    // ======================================================
+
+    // true:  Display correctly mapped pixels in the camera displays
+    //        but the value-vs-index plot is in software/spiral indices
+    // false: Display pixels in hardware/linear indices,
+    //        but the order is the camera display is distorted
+    bool usemap = true;
+
+    // map file to use (get that from La Palma!)
+    const char *map = usemap ? "/scratch/fact/FACTmap111030.txt" : NULL;
+
+    // ------------------------------------------------------
+
+    Long_t max0 = 0;
+    Long_t max1 = 0;
+
+    // ======================================================
+
+    if (map && gSystem->AccessPathName(map, kFileExists))
+    {
+        gLog << "ERROR - Cannot access mapping file '" << map << "'" << endl;
+        return 1;
+    }
+    if (gSystem->AccessPathName(drsfile, kFileExists))
+    {
+        gLog << "ERROR - Cannot access drsfile file '" << drsfile << "'" << endl;
+        return 2;
+    }
+
+    // --------------------------------------------------------------------------------
+
+    gLog.Separator("Singles");
+    gLog << "Extract singles with '" << drsfile << "'" << endl;
+    gLog << endl;
+
+    // ------------------------------------------------------
+
+    MDrsCalibration drscalib300;
+    if (!drscalib300.ReadFits(drsfile))
+        return 3;
+
+    // ------------------------------------------------------
+
+    iter.Sort();
+    iter.Print();
+
+    TString title;
+    title =  iter.Next();
+    title += "; ";
+    title += max1;
+    iter.Reset();
+
+    // ======================================================
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MBadPixelsCam badpixels;
+    badpixels.InitSize(1440);
+    badpixels[ 424].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 583].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 830].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 923].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[1208].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[1399].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+
+    //  Twin pixel
+    //     113
+    //     115
+    //     354
+    //     423
+    //    1195
+    //    1393
+
+    MH::SetPalette();
+
+    MContinue cont("(MRawEvtHeader.GetTriggerID&0xff00)!=0x100", "SelectCal");
+
+    MGeomApply apply;
+
+    MDrsCalibApply drsapply;
+
+    MRawFitsRead read;
+    read.LoadMap(map);
+    read.AddFiles(iter);
+
+    // ======================================================
+
+    gLog << endl;
+    gLog.Separator("Calculating baseline");
+
+    MTaskList tlist0;
+
+    MRawRunHeader header;
+    MPedestalCam  pedcam;
+
+    MParList plist;
+    plist.AddToList(&tlist0);
+    plist.AddToList(&drscalib300);
+    plist.AddToList(&header);
+    plist.AddToList(&pedcam);
+
+    // ------------------ Setup the tasks ---------------
+
+    MFillH fill0("MHBaseline", "MPedestalSubtractedEvt");
+
+    drsapply.SetRemoveSpikes(4);
+
+    // ------------------ Setup eventloop and run analysis ---------------
+
+    tlist0.AddToList(&read);
+    tlist0.AddToList(&apply);
+    tlist0.AddToList(&drsapply);
+    tlist0.AddToList(&fill0);
+
+    // ------------------ Setup and run eventloop ---------------
+
+    MEvtLoop loop0(title);
+    loop0.SetDisplay(d);
+    loop0.SetParList(&plist);
+
+    if (!loop0.Eventloop(max0))
+        return 4;
+
+    if (!loop0.GetDisplay())
+        return 5;
+
+    // ----------------------------------------------------------------
+
+    MGeomCamFACT fact;
+    MHCamera hped(fact);
+    hped.SetCamContent(pedcam);
+    hped.SetCamError(pedcam, 4);
+    hped.SetAllUsed();
+    MHCamEvent display;
+    display.SetHist(hped);
+
+    d->AddTab("Baseline");
+    display.Clone()->Draw();
+
+    // ======================================================
+
+    gLog << endl;
+    gLog.Separator("Extracting singles");
+
+    MTaskList tlist1;
+
+    MSingles singles;
+
+    plist.Replace(&tlist1);
+    plist.AddToList(&badpixels);
+    plist.AddToList(&singles);
+
+    // ------------------ Setup the tasks ---------------
+
+    MExtractSingles extract;
+    extract.SetMaxDist(max_dist);
+    extract.SetThreshold(threshold);
+
+    MFillH fill("MHSingles");
+
+    // ------------------ Setup eventloop and run analysis ---------------
+
+    tlist1.AddToList(&read);
+    tlist1.AddToList(&apply);
+    tlist1.AddToList(&drsapply);
+    tlist1.AddToList(&extract);
+    tlist1.AddToList(&fill);
+
+    // ------------------ Setup and run eventloop ---------------
+
+    MEvtLoop loop1(title);
+    loop1.SetDisplay(d);
+    loop1.SetParList(&plist);
+
+    if (!loop1.Eventloop(max1))
+        return 6;
+
+    if (!loop1.GetDisplay())
+        return 7;
+
+    if (fill.GetNumExecutions()==0)
+        return 8;
+
+    // =============================================================
+
+    gStyle->SetOptFit(kTRUE);
+
+    MHSingles* h = (MHSingles*) plist.FindObject("MHSingles");
+    if (!h)
+        return 9;
+
+    const TH2 *htime   = h->GetTime();
+    const TH2 *hpulse  = h->GetPulse();
+
+    d->AddTab("Time");
+    TH1 *ht = htime->ProjectionY();
+    ht->SetYTitle("Counts [a.u.]");
+    ht->Scale(1./1440);
+    ht->Draw();
+
+    d->AddTab("Pulse");
+    TH1 *hp = hpulse->ProjectionY();
+    hp->SetYTitle("Counts [a.u.]");
+    hp->Scale(1./1440);
+    hp->Draw();
+
+    d->SaveAs(outfile);
+
+    TFile f(outfile, "UPDATE");
+
+    MParameterI par("NumEvents");
+    par.SetVal(fill.GetNumExecutions());
+    par.Write();
+
+    MParameterI win("IntegrationWindow");
+    win.SetVal(extract.GetIntegrationSize());
+    win.Write();
+
+    extract.GetExtractionRange().Write("ExtractionRange");
+
+    if (firstRunID==lastRunID)
+        header.Write();
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/extract_temp.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/extract_temp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/extract_temp.C	(revision 17960)
@@ -0,0 +1,156 @@
+#include <iostream>
+
+#include <TString.h>
+#include <TFile.h>
+#include <TGraph.h>
+
+#include "zfits.h"
+#include "PixelMap.h"
+#include "Interpolator2D.h"
+
+#include "MHCamera.h"
+#include "MGeomCamFACT.h"
+
+int extract_temp(UInt_t day=20130902, UInt_t run=146, const char *output=0)
+{
+    TString nraw = Form("/fact/raw/%4d/%02d/%02d/%8d_%03d.fits.fz",
+                        day/10000, (day/100)%100, day%100, day, run);
+
+    TString naux = Form("/fact/aux/%4d/%02d/%02d/%8d.FSC_CONTROL_TEMPERATURE.fits",
+                        day/10000, (day/100)%100, day%100, day);
+
+    PixelMap pmap;
+    if (!pmap.Read("FACTmap111030.txt"))
+    {
+        cout << "FACTmap111030.txt not found." << endl;
+        return 1;
+    }
+
+    Interpolator2D interpol;
+
+    const auto sens = Interpolator2D::ReadGrid("operation/sensor-pos.txt");
+    if (sens.size()!=31)
+    {
+        cout << "Reading sensor-pos.txt failed: " << interpol.getInputGrid().size() << endl;
+        return 2;
+    }
+
+    // =====================================================================
+
+    zfits fraw(nraw.Data());
+    if (!fraw)
+    {
+        cout << "Open raw file failed: " << nraw << endl;
+        return 1;
+    }
+
+    double tstart = fraw.GetUInt("TSTARTI") + fraw.GetFloat("TSTARTF");
+    double tstop  = fraw.GetUInt("TSTOPI")  + fraw.GetFloat("TSTOPF");
+
+    // =====================================================================
+
+    // Now we read the temperatures of the sensors during the
+    // single pe run and average them
+    fits faux(naux.Data());
+    if (!faux)
+    {
+        cout << "Could not open " << naux << endl;
+        return 1;
+    }
+
+    Double_t time;
+    Float_t  temp[31];
+
+    if (!faux.SetPtrAddress("Time",  &time))
+        return -1;
+    if (!faux.SetPtrAddress("T_sens", temp))
+        return -1;
+
+    TArrayD avg(31);
+    TArrayD rms(31);
+    TArrayI cnt(31);
+
+    while (faux.GetNextRow())
+    {
+        if (time<tstart || time>tstop)
+            continue;
+
+        for (int i=0; i<31; i++)
+        {
+            if (temp[i]==0)
+                continue;
+
+            double T = temp[i];
+
+            avg[i] += T;
+            rms[i] += T*T;
+            cnt[i]++;
+        }
+    }
+
+    vector<double> z;
+
+    vector<Interpolator2D::vec> pos;
+    for (int i=0; i<31; i++)
+    {
+        if (cnt[i]>0)
+        {
+            avg[i] /= cnt[i];
+            rms[i] /= cnt[i];
+            rms[i] = sqrt(rms[i]-avg[i]*avg[i]);
+
+            pos.push_back(sens[i]);
+            z.push_back(avg[i]);
+        }
+    }
+
+    // ================================================================
+
+    interpol.SetInputGrid(pos);
+
+    if (!interpol.ReadOutputGrid("operation/bias-positions.txt"))
+    {
+        cout << "Error setting output grid." << endl;
+        return 3;
+    }
+    if (interpol.getOutputGrid().size()!=320)
+    {
+        cout << "Reading bias-positions.txt failed: " << interpol.getOutputGrid().size() << endl;
+        return 3;
+    }
+
+    // ================================================================
+
+    const auto &input = interpol.getInputGrid();
+
+    TGraph sensors(input.size());
+
+    for (unsigned int i=0; i<input.size(); i++)
+        sensors.SetPoint(i, input[i].x, input[i].y);
+
+    const vector<double> rc = interpol.Interpolate(z);
+
+    // ================================================================
+
+    TCanvas *c = new TCanvas;
+    c->SetName("Temp");
+
+    MGeomCamFACT geom;
+
+    MHCamera h1(geom);
+    h1.SetName("Temp");
+    for (int i=0; i<1440; i++)
+        h1.SetBinContent(i+1, rc[pmap.index(i).hv()]);
+
+    h1.SetAllUsed();
+    h1.DrawCopy();
+
+    sensors.SetName("Sensors");
+    sensors.SetMarkerColor(kWhite);
+    sensors.DrawClone("*");
+
+    if (output)
+        c->SaveAs(output);
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/fit.sh
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/fit.sh	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/fit.sh	(revision 17960)
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+inpath=$PWD/$1
+outpath=${inpath}/fit
+macro=${PWD}/fit_spectra.C
+
+mkdir -p $outpath
+cp ${macro} ${outpath}
+
+files_out=`ls -1r ${inpath}  | grep \.root`
+files_fit=`ls -1r ${outpath} | grep \.root`
+
+for file in $files_out
+do
+    infile=$inpath"/"${file}
+    outfile=${outpath}"/"${file}
+
+    if [ -e $outfile ]
+    then 
+       continue
+    fi
+
+    cmd="ROOT_HIST=0 ${ROOTSYS}/bin/root -b -q -l ${macro}+\(\\\"${infile}\\\",\\\"${outfile}\\\"\)"
+
+    cd ~/Mars
+
+    echo "echo '${cmd}'; date; ${cmd}" | qsub -N f${file} -q test -cwd -e ${outfile}".err" -o ${outfile}".log"
+
+    cd - > /dev/null
+done
+
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/fit_spectra.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/fit_spectra.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/fit_spectra.C	(revision 17960)
@@ -0,0 +1,931 @@
+#include <iomanip>
+#include <iostream>
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TProfile2D.h>
+#include <TFile.h>
+#include <TFitResult.h>
+#include <TStyle.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MStatusArray.h"
+#include "MStatusDisplay.h"
+#include "MHCamera.h"
+#include "MGeomCamFACT.h"
+#include "MParameters.h"
+#include "MArrayI.h"
+#include "MRawRunHeader.h"
+#include "PixelMap.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+
+// Fit function for a single pe spectrum
+Double_t fcn_g(Double_t *xx, Double_t *par)
+{
+    const Double_t ampl  = par[0];
+    const Double_t gain  = par[1];
+    const Double_t sigma = par[2]*gain;
+    const Double_t cross = par[3];
+    const Double_t shift = par[4];
+    const Double_t noise = par[5]<0 ? sigma : par[5];
+    const Double_t expo  = par[6];
+
+    Double_t y = 0;
+    for (int N=1; N<14; N++)
+    {
+        const Double_t muN  = N*gain + shift;
+        const Double_t sigN = TMath::Sqrt(N*sigma*sigma + noise*noise);
+
+        const Double_t p = TMath::Power(cross, N-1) * TMath::Power(N, -expo);
+
+        y += TMath::Gaus(xx[0], muN, sigN) * p / sigN;
+    }
+
+    const Double_t sig1 = TMath::Sqrt(sigma*sigma + noise*noise);
+    return ampl*sig1*y;
+}
+
+// Calculate the crosstalk from the function parameters
+Double_t xtalk(TF1 &f)
+{
+    Double_t cross = f.GetParameter(3);
+    Double_t expo  = f.GetParameter(6);
+
+    Double_t y = 0;
+    for (int N=2; N<14; N++)
+        y +=  TMath::Power(cross,  N-1) * TMath::Power(N, -expo);
+
+    return y / (y + 1);
+}
+
+// calculate the integral in units per millisecond
+double integral(TF1 &func, TH1 &hist)
+{
+    const Double_t sigma = func.GetParameter(2)*func.GetParameter(1);
+    const Double_t cross = func.GetParameter(3);
+    const Double_t noise = func.GetParameter(5)<0 ? sigma : func.GetParameter(5);
+    const Double_t expo  = func.GetParameter(6);
+
+    Double_t sum = 0;
+    for (int N=1; N<14; N++)
+        sum += TMath::Power(cross, N-1) * TMath::Power(N, -expo);
+
+    const Double_t scale = hist.GetBinWidth(1);
+    const Double_t sig1  = TMath::Sqrt(sigma*sigma + noise*noise);
+    const Double_t integ = func.GetParameter(0)*sum*sig1*sqrt(TMath::TwoPi())/scale;
+
+    return integ/1e-9/1e6;
+}
+
+
+// --------------------------------------------------------------------------
+
+// Print function parameters
+void PrintFunc(TF1 &f, float integration_window=30)
+{
+    //cout << "--------------------" << endl;
+    cout << "Ampl:       " << setw(8) << f.GetParameter(0) << " +/- " << f.GetParError(0) << endl;
+    cout << "Gain:       " << setw(8) << f.GetParameter(1) << " +/- " << f.GetParError(1) << endl;
+    cout << "Rel.sigma:  " << setw(8) << f.GetParameter(2) << " +/- " << f.GetParError(2) << endl;
+    cout << "Baseline:   " << setw(8) << f.GetParameter(4)/integration_window << " +/- " << f.GetParError(4)/integration_window << endl;
+    cout << "Crosstalk:  " << setw(8) << f.GetParameter(3) << " +/- " << f.GetParError(3) << endl;
+    cout << "Pcrosstalk: " << setw(8) << xtalk(f) << endl;
+    if (f.GetParameter(5)>=0)
+        cout << "Noise:      " << setw(8) << f.GetParameter(5)/sqrt(integration_window) << " +/- " << f.GetParError(5)/sqrt(integration_window) << endl;
+    cout << "Expo:       " << setw(8) << f.GetParameter(6) << " +/- " << f.GetParError(6) << endl;
+    //cout << "--------------------" << endl;
+
+}
+
+// --------------------------------------------------------------------------
+
+// The parameters for the function are the filenam from the gain extraction
+// and the output filename
+int fit_spectra(const char *filename = "20130222_018_018.root",
+                const char *outfile  = "20130222_018_018-fit.root",
+                bool fixednoise=true)
+{
+    // Read the mapping between bias channels and hardware channels
+    PixelMap pmap;
+    if (!pmap.Read("FACTmap111030.txt"))
+    {
+        cout << "FACTmap111030.txt not found." << endl;
+        return 1;
+    }
+
+    // It is more correct to fit the integral, but this is super
+    // slow, especially for 1440 pixel. To get that, one would have
+    // to analytically integrate and fit this function.
+    // (Currently the integral is switched off for the 1440 individual
+    // spectra in all cases)
+    bool fast = false; // Switch off using integral
+
+    // Values which should be read from the file but not available atm
+    Int_t integration_window = 30;
+
+    // Map for which pixel shall be plotted and which not
+    TArrayC usePixel(1440);
+    memset(usePixel.GetArray(), 1, 1440);
+
+    // List of Pixel that should be ignored in camera view
+    usePixel[424]  = 0;
+    usePixel[923]  = 0;
+    usePixel[1208] = 0;
+    usePixel[583]  = 0;
+    usePixel[830]  = 0;
+    usePixel[1399] = 0;
+    usePixel[113]  = 0;
+    usePixel[115]  = 0;
+    usePixel[354]  = 0;
+    usePixel[423]  = 0;
+    usePixel[1195] = 0;
+    usePixel[1393] = 0;
+
+    cout << setprecision(3);
+
+    // ======================================================
+    // Read data and histograms from file
+
+    TFile file(filename);
+    if (file.IsZombie())
+    {
+        gLog << err << "Opening file '" << filename << "' failed." << endl;
+        return 1;
+    }
+
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        gLog << err << "Reading of MStatusArray from '" << filename << "' failed." << endl;
+        return 2;
+    }
+
+    TH2 *hsignal = (TH2*)arr.FindObjectInCanvas("Signal", "TH2F", "MHSingles");
+    if (!hsignal)
+    {
+        gLog << err << "Histogram Signal not found in '" << filename << "'." << endl;
+        return 3;
+    }
+    TH2 *htime = (TH2*)arr.FindObjectInCanvas("Time", "TH2F", "MHSingles");
+    if (!htime)
+    {
+        gLog << err << "Histogram Time not found in '" << filename << "'." << endl;
+        return 4;
+    }
+    TProfile2D *hpulse = (TProfile2D*)arr.FindObjectInCanvas("Pulse", "TProfile2D", "MHSingles");
+    if (!hpulse)
+    {
+        gLog << err << "Histogram Pulse not found in '" << filename << "'." << endl;
+        return 5;
+    }
+    TH2F *hbase = (TH2F*)arr.FindObjectInCanvas("Baseline", "TH2F", "MHBaseline");
+    if (!hbase)
+    {
+        gLog << err << "Histogram Baseline not found in '" << filename << "'." << endl;
+        return 6;
+    }
+
+    MRawRunHeader header;
+    if (header.Read()<=0)
+    {
+        gLog << err << "MRawRunheader not found in '" << filename << "'." << endl;
+        return 7;
+    }
+
+    MParameterI par("NumEvents");
+    if (par.Read()<=0)
+    {
+        gLog << err << "NumEvents not found in '" << filename << "'." << endl;
+        return 8;
+    }
+
+    MArrayI ext;
+    if (ext.Read("ExtractionRange")<=0)
+    {
+        gLog << err << "ExtractionRange not found in '" << filename << "'." << endl;
+        return 9;
+
+    }
+
+    // ======================================================
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Camera geometry for displays
+    MGeomCamFACT fact;
+
+    // ------------------ Spectrum Fit ---------------
+    // Instantiate the display histograms
+    MHCamera cRate(fact);
+    MHCamera cGain(fact);
+    MHCamera cRelSigma(fact);
+    MHCamera cCrosstalk(fact);
+    MHCamera cBaseline(fact);
+    MHCamera cNoise(fact);
+    MHCamera cChi2(fact);
+    MHCamera cNormGain(fact);
+    MHCamera cFitProb(fact);
+    MHCamera cCrosstalkP(fact);
+    MHCamera cCoeffR(fact);
+
+    // Set name and title for the histograms
+    cRate.SetNameTitle      ("Rate",      "Dark count rate");
+    cGain.SetNameTitle      ("Gain",      "Gain distribution");
+    cRelSigma.SetNameTitle  ("RelSigma",  "Rel. Sigma");
+    cCrosstalk.SetNameTitle ("Crosstalk", "Crosstalk probability");
+    cBaseline.SetNameTitle  ("Baseline",  "Baseline per sample");
+    cNoise.SetNameTitle     ("Noise",     "Noise per sample");
+    cChi2.SetNameTitle      ("Chi2",      "\\Chi^2");
+    cNormGain.SetNameTitle  ("NormGain",  "Normalized gain");
+    cFitProb.SetNameTitle   ("FitProb",   "Root's fit probability");
+    cCrosstalkP.SetNameTitle("Pxtalk",    "Crosstalk coeff. P");
+    cCoeffR.SetNameTitle    ("CoeffR",    "Coefficient R");
+
+    // Instantiate 1D histograms for the distributions
+    // including TM channels
+    TH1F hRate1      ("Rate1",      "Dark count rate",       150,  0,    15);
+    TH1F hGain1      ("Gain1",      "Gain distribution",     100,  0,   400);
+    TH1F hRelSigma1  ("RelSigma1",  "Rel. Sigma",            160,  0,  0.40);
+    TH1F hCrosstalk1 ("Crosstalk1", "Crosstalk probability",  90,  0,  0.30);
+    TH1F hBaseline1  ("Baseline1",  "Baseline per sample",    75, -7.5, 7.5);
+    TH1F hNoise1     ("Noise1",     "Noise per sample",       60,  0,    30);
+    TH1F hChiSq1     ("ChiSq1",     "\\Chi^2",               200,  0,     4);
+    TH1F hNormGain1  ("NormGain1",  "Normalized gain",        51,  0.5, 1.5);
+    TH1F hFitProb1   ("FitProb1",   "FitProb distribution",  100,  0,     1);
+    TH1F hCrosstalkP1("Pxtalk1",    "Crosstalk coeff.",       90,  0,   0.3);
+    TH1F hCoeffR1    ("CoeffR1",    "Coefficient R",          90, -1,     2);
+
+    // excluding TM channels
+    TH1F hRate2      ("Rate2",      "Dark count rate",       150,  0,    15);
+    TH1F hGain2      ("Gain2",      "Gain distribution",     100,  0,   400);
+    TH1F hRelSigma2  ("RelSigma2",  "Rel. Sigma",            160,  0,  0.40);
+    TH1F hCrosstalk2 ("Crosstalk2", "Crosstalk probability",  90,  0,  0.30);
+    TH1F hBaseline2  ("Baseline2",  "Baseline per sample",    75, -7.5, 7.5);
+    TH1F hNoise2     ("Noise2",     "Noise per sample",       60,  0,    30);
+    TH1F hChiSq2     ("ChiSq2",     "\\Chi^2",               200,  0,     4);
+    TH1F hNormGain2  ("NormGain2",  "Normalized gain",        51,  0.5, 1.5);
+    TH1F hFitProb2   ("FitProb2",   "FitProb distribution",  100,  0,     1);
+    TH1F hCrosstalkP2("Pxtalk2",    "Crosstalk coeff.",       90,  0,   0.3);
+    TH1F hCoeffR2    ("CoeffR2",    "Coefficient R",          90, -1,     2);
+
+    // Histigram for the sum of all spectrums
+    TH1F hSum("Sum1", "Signal spectrum of all pixels",
+              hsignal->GetNbinsY(), hsignal->GetYaxis()->GetXmin(),  hsignal->GetYaxis()->GetXmax());
+    hSum.SetXTitle("pulse integral [mV sample]");
+    hSum.SetYTitle("Counts");
+    hSum.SetStats(false);
+    hSum.Sumw2();
+
+    // Histogram for the sum of all pixels excluding the ones with faulty fits
+    TH1F hSumClear1("SumC1", "Signal spectrum of all pixels (incl TM)",
+                    hsignal->GetNbinsY(), hsignal->GetYaxis()->GetXmin(),  hsignal->GetYaxis()->GetXmax());
+    hSumClear1.SetXTitle("pulse integral [mV sample]");
+    hSumClear1.SetYTitle("Counts");
+    hSumClear1.SetStats(false);
+    hSumClear1.SetLineColor(kBlue);
+    hSumClear1.Sumw2();
+
+    TH1F hSumClear2("SumC2", "Signal spectrum of all pixels (excp TM)",
+                    hsignal->GetNbinsY(), hsignal->GetYaxis()->GetXmin(),  hsignal->GetYaxis()->GetXmax());
+    hSumClear2.SetXTitle("pulse integral [mV sample]");
+    hSumClear2.SetYTitle("Counts");
+    hSumClear2.SetStats(false);
+    hSumClear2.SetLineColor(kBlue);
+    hSumClear2.Sumw2();
+
+    // Arrival time spectrum of the extracted pulses
+    TH1F hTime("Time", "Arrival time spectrum", htime->GetNbinsY(), htime->GetYaxis()->GetXmin(), htime->GetYaxis()->GetXmax());
+    hTime.SetXTitle("pulse arrival time [sample]");
+    hTime.SetYTitle("Counts");
+    hTime.SetStats(false);
+
+    // average pulse shape of the extracted pulses
+    TH1F hPulse("Puls", "Average pulse", hpulse->GetNbinsY(), hpulse->GetYaxis()->GetXmin(), hpulse->GetYaxis()->GetXmax());
+    hPulse.SetXTitle("pulse arrival time [sample]");
+    hPulse.SetYTitle("Counts");
+    hPulse.SetStats(false);
+
+    // Spektrum for the normalized individual spectra
+    TH1F hSumScale1("SumScale1", "Signal spectrum of all pixels (incl TM)",  120, 0.05, 12.05);
+    hSumScale1.SetXTitle("pulse integral [pe]");
+    hSumScale1.SetYTitle("Rate");
+    hSumScale1.SetStats(false);
+    hSumScale1.Sumw2();
+
+    TH1F hSumScale2("SumScale2", "Signal spectrum of all pixels (excl TM)",  120, 0.05, 12.05);
+    hSumScale2.SetXTitle("pulse integral [pe]");
+    hSumScale2.SetYTitle("Rate");
+    hSumScale2.SetStats(false);
+    hSumScale2.Sumw2();
+
+    // define fit function for Amplitudespectrum
+    TF1 func("spektrum", fcn_g, 0, hSum.GetXaxis()->GetXmax(), 7);
+    func.SetNpx(2000);
+    func.SetParNames("Maximum", "Gain", "Sigma", "XtalkProb", "Offset", "Noise", "Expo");
+    func.SetLineColor(kRed);
+
+    //--------------------- fill sum spectrum --------------------------------
+
+    d->SetStatusLine("Calculating sum spectrum", 0);
+
+    // Begin of Loop over Pixels
+    for (Int_t pixel = 0; pixel < hsignal->GetNbinsX(); pixel++)
+    {
+        //jump to next pixel if the current is marked as faulty
+        if (usePixel[pixel]==0)
+            continue;
+
+        TH1D *hist = hsignal->ProjectionY("proj", pixel+1, pixel+1);
+        hSum.Add(hist);
+        delete hist;
+    }
+
+    //----------------- get starting values -------------------------------
+
+    hSum.GetXaxis()->SetRangeUser(150, hSum.GetXaxis()->GetXmax());
+
+    const Int_t    maxbin   = hSum.GetMaximumBin();
+    const Double_t maxpos   = hSum.GetBinCenter(maxbin);
+    const Double_t binwidth = hSum.GetBinWidth(maxbin);
+    const Double_t ampl     = hSum.GetBinContent(maxbin);
+
+    double fwhmSum = 0;
+
+    //Calculate full width half Maximum
+    for (int i=1; i<maxbin; i++)
+        if (hSum.GetBinContent(maxbin-i)+hSum.GetBinContent(maxbin+i)<ampl)
+        {
+            fwhmSum = 2*(i-0.5)*binwidth;
+            break;
+        }
+
+    if (fwhmSum==0)
+    {
+        gLog << warn << "Could not determine start value for sigma." << endl;
+    }
+
+    Double_t sigma_est = fwhmSum/2.3548; // FWHM = 2*sqrt(2*ln(2))*sigma
+
+    Double_t fitmin = maxpos-3*sigma_est; // was 3
+    Double_t fitmax = hSum.GetXaxis()->GetXmax();
+
+    // ------------------- fit --------------------------------
+
+    //Fit and draw spectrum
+    func.SetParLimits(0, 0, 2*ampl);       // Amplitude
+    func.SetParLimits(1, 0, 2*maxpos);     // Gain
+    func.SetParLimits(2, 0, 1);            // Sigma
+    func.SetParLimits(3, 0, 1);            // Crosstalk
+    if (!fixednoise)
+        func.SetParLimits(5, 0, 150);          // Noise
+
+    func.SetParameter(0, ampl);                         // Amplitude
+    func.SetParameter(1, maxpos);                       // Gain
+    func.SetParameter(2, 0.1);                          // Sigma
+    func.SetParameter(3, 0.16);                         // Crosstalk
+    func.SetParameter(4, 0*integration_window);         // Baseline
+    if (fixednoise)
+        func.FixParameter(5, -1);                       // Noise
+    else
+        func.SetParameter(5, 0.1*maxpos);               // Noise
+
+    func.SetParameter(6, 0.4);                          // Expo
+
+    func.SetRange(fitmin, fitmax);
+    hSum.Fit(&func, fast?"N0QSR":"IN0QSR");
+
+    Double_t res_par[7];
+    func.GetParameters(res_par);
+
+    //func.FixParameter(6, func.GetParameter(6));                          // Expo
+
+    // ------------------ display result -------------------------------
+
+    cout << "--------------------" << endl;
+    cout << "AmplEst:    " << ampl      << endl;
+    cout << "GainEst:    " << maxpos    << endl;
+    cout << "SigmaEst:   " << sigma_est << endl;
+    PrintFunc(func, integration_window);
+    cout << "--------------------" << endl;
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c11 = d->AddTab("SumHist");
+    c11.cd();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    hSum.GetXaxis()->SetRange();
+    hSum.DrawCopy("hist");
+    func.DrawCopy("same");
+
+    // ===================================================================
+    //  Gain Calculation for each Pixel
+    // ===================================================================
+
+    // counter for number of processed pixel
+    int count_ok = 0;
+
+    // Begin of Loop over Pixels
+    for (Int_t pixel=0; pixel<hsignal->GetNbinsX(); pixel++)
+    {
+        // User information
+        d->SetStatusLine(Form("Fitting pixel #%d", pixel), 0);
+        d->SetProgressBarPosition((pixel+1.)/hsignal->GetNbinsX(), 1);
+
+        // Skip pixels known to be faulty
+        if (usePixel[pixel]==0)
+            continue;
+
+        //Projectipon of a certain Pixel out of Ampl.Spectrum
+        TH1D *hist = hsignal->ProjectionY("proj", pixel+1, pixel+1);
+        hist->SetDirectory(0);
+
+        if (hist->GetEntries()<100)
+        {
+            gLog << warn << pixel << " ...histogram empty." << endl;
+            usePixel[pixel] = 0;
+            delete hist;
+            continue;
+        }
+
+        //Rebin Projection
+        hist->Rebin(2);
+
+        // Fit range
+        hist->GetXaxis()->SetRangeUser(150, hist->GetXaxis()->GetXmax());
+
+        // Determine start values
+        const Int_t    maxBin = hist->GetMaximumBin();
+        const Double_t maxPos = hist->GetBinCenter(maxBin);
+
+        const Double_t gain    = res_par[1];
+        const Double_t GainRMS = res_par[2];
+
+        const double fit_min = maxPos-GainRMS*gain*2.5;
+        const double fit_max = fitmax;//maxPos+gain*(maxOrder-0.5);
+
+        TArrayD cpy_par(7, res_par);
+
+        cpy_par[0] = hist->GetBinContent(maxBin);
+        cpy_par[1] = maxPos-res_par[4];  // correct position for avg baseline
+
+        func.SetParameters(cpy_par.GetArray());
+        func.SetParLimits(0, 0, 2*cpy_par[0]);
+        func.SetParLimits(1, 0, 2*cpy_par[1]);
+
+        // For individual spectra, the average fit yields 1 anyway
+        //func.SetParameter(6, 0); // Expo
+
+        // ----------- Fit Pixels spectrum ---------------
+
+        const TFitResultPtr rc = hist->Fit(&func, /*fast?*/"LLN0QS"/*:"LLIN0QS"*/, "", fit_min, fit_max);
+
+        // ----------- Calculate quality parameter ---------------
+
+        Int_t b1 = hist->GetXaxis()->FindFixBin(fit_min);
+        Int_t b2 = hist->GetXaxis()->FindFixBin(fit_max);
+
+        Double_t chi2 = 0;
+        Int_t    cnt  = 0;
+        for (int i=b1; i<=b2; i++)
+        {
+            if (hist->GetBinContent(i)<1.5 || func.Eval(hist->GetBinCenter(i))<1.5)
+                continue;
+
+            const Double_t y = func.Integral(hist->GetBinLowEdge(i), hist->GetBinLowEdge(i+1));
+            const Double_t v = hist->GetBinContent(i)*hist->GetBinWidth(i);
+
+            const Double_t chi = (v-y)/v;
+
+            chi2 += chi*chi;
+            cnt ++;
+        }
+
+        chi2 = cnt==0 ? 0 : sqrt(chi2/cnt);
+
+        // ----------------- Fit result --------------------
+
+        const double fit_prob   = rc->Prob();
+
+        const float fRate      = integral(func, *hist)/(ext[pixel]*0.5);
+        const float fGain      = func.GetParameter(1);
+        const float fGainRMS   = func.GetParameter(2);
+        const float fCrosstalkP= func.GetParameter(3);
+        const float fCrosstlk  = xtalk(func);
+        const float fOffset    = func.GetParameter(4);
+        const float fNoise     = func.GetParameter(5)<0 ? fGainRMS*fGain/sqrt(integration_window) : func.GetParameter(5)/sqrt(integration_window);
+        const float fCoeffR    = func.GetParameter(6);
+
+        // Fill histograms with result values
+        cRate.SetBinContent(      pixel+1, fRate);
+        cGain.SetBinContent(      pixel+1, fGain);
+        cRelSigma.SetBinContent(  pixel+1, fGainRMS);
+        cCrosstalk.SetBinContent( pixel+1, fCrosstlk);
+        cBaseline.SetBinContent(  pixel+1, fOffset/integration_window);
+        cNoise.SetBinContent(     pixel+1, fNoise);
+        cChi2.SetBinContent(      pixel+1, chi2);
+        cNormGain.SetBinContent(  pixel+1, fGain/gain);
+        cFitProb.SetBinContent(   pixel+1, fit_prob);
+        cCrosstalkP.SetBinContent(pixel+1, fCrosstalkP);
+        cCoeffR.SetBinContent(    pixel+1, fCoeffR);
+
+        // ======================================================
+
+        // Try to determine faulty fits
+
+        bool ok = int(rc)==0;
+
+        // mark pixels suspicious with failed fit
+        if (!ok)
+            gLog << warn <<  pixel << " ...fit failed!" << endl;
+
+        // mark pixels suspicious with negative GainRMS
+        if (fabs(fGain/gain-1)>0.3)
+        {
+            gLog << warn <<  pixel << " ...gain deviates more than 30% from sum-gain." << endl;
+            ok = 0;
+        }
+
+        if (fabs(fOffset/integration_window)>3)
+        {
+            gLog << warn <<  pixel << " ...baseline deviates." << endl;
+            ok = 0;
+        }
+
+        // cancel out pixel where the fit was not succsessfull
+        usePixel[pixel] = ok;
+
+        // Plot pixel 0 and 5 (TM) and all faulty fits
+        if (pixel==0 || pixel==5 || !ok)
+        {
+            TCanvas &c = d->AddTab(Form("Pix%d", pixel));
+            c.cd();
+            gPad->SetLogy();
+            gPad->SetGridx();
+            gPad->SetGridy();
+
+            hist->SetStats(false);
+            hist->SetXTitle("Extracted signal");
+            hist->SetYTitle("Counts");
+            hist->SetName(Form("Pix%d", pixel));
+            hist->GetXaxis()->SetRange();
+            hist->DrawCopy("hist")->SetDirectory(0);
+            func.DrawCopy("SAME")->SetRange(fit_min, fit_max);
+
+            cout << "--------------------" << endl;
+            cout << "Pixel:      "   << pixel  << endl;
+            cout << "fit prob:   "   << fit_prob  << endl;
+            cout << "AmplEst:    "   << cpy_par[0] << endl;
+            cout << "GainEst:    "   << cpy_par[1] << endl;
+            PrintFunc(func, integration_window);
+            cout << "--------------------" << endl;
+        }
+
+        if (!ok)
+        {
+            delete hist;
+            continue;
+        }
+
+        // Fill Parameters into histograms
+        hRate1.Fill(      fRate);
+        hGain1.Fill(      fGain);
+        hRelSigma1.Fill(  fGainRMS);
+        hCrosstalk1.Fill( fCrosstlk);
+        hBaseline1.Fill(  fOffset/integration_window);
+        hNoise1.Fill(     fNoise);
+        hChiSq1.Fill(     chi2);
+        hNormGain1.Fill(  fGain/gain);
+        hFitProb1.Fill(   fit_prob);
+        hCrosstalkP1.Fill(fCrosstalkP);
+        hCoeffR1.Fill(    fCoeffR);
+
+        if (!pmap.index(pixel).isTM())
+        {
+            hRate2.Fill(      fRate);
+            hGain2.Fill(      fGain);
+            hRelSigma2.Fill(  fGainRMS);
+            hCrosstalk2.Fill( fCrosstlk);
+            hBaseline2.Fill(  fOffset/integration_window);
+            hNoise2.Fill(     fNoise);
+            hChiSq2.Fill(     chi2);
+            hNormGain2.Fill(  fGain/gain);
+            hFitProb2.Fill(   fit_prob);
+            hCrosstalkP2.Fill(fCrosstalkP);
+            hCoeffR2.Fill(    fCoeffR);
+        }
+
+        // Fill sum spectrum
+        for (int b=1; b<=hist->GetNbinsX(); b++)
+            hSumScale1.Fill((hist->GetBinCenter(b)-fOffset)/fGain, hist->GetBinContent(b));
+
+        if (!pmap.index(pixel).isTM())
+            for (int b=1; b<=hist->GetNbinsX(); b++)
+                hSumScale2.Fill((hist->GetBinCenter(b)-fOffset)/fGain, hist->GetBinContent(b));
+
+        delete hist;
+
+        // Because of the rebinning...
+        hist = hsignal->ProjectionY("proj", pixel+1, pixel+1);
+        hSumClear1.Add(hist);
+        if (!pmap.index(pixel).isTM())
+            hSumClear2.Add(hist);
+        delete hist;
+
+        hist = htime->ProjectionY("proj", pixel+1, pixel+1);
+        hTime.Add(hist);
+        delete hist;
+
+        hist = hpulse->ProjectionY("proj", pixel+1, pixel+1);
+        hPulse.Add(hist);
+        delete hist;
+
+        count_ok++;
+    }
+
+    //------------------fill histograms-----------------------
+    // Display only pixels used and with valid fits
+
+    cRate.SetUsed(usePixel);
+    cGain.SetUsed(usePixel);
+    cRelSigma.SetUsed(usePixel);
+    cCrosstalk.SetUsed(usePixel);
+    cBaseline.SetUsed(usePixel);
+    cNoise.SetUsed(usePixel);
+    cChi2.SetUsed(usePixel);
+    cNormGain.SetUsed(usePixel);
+    cFitProb.SetUsed(usePixel);
+    cCrosstalkP.SetUsed(usePixel);
+    cCoeffR.SetUsed(usePixel);
+
+    // --------------------------------------------------------
+    // Display data
+
+    TCanvas *canv = &d->AddTab("Cams1");
+    canv->Divide(3,2);
+
+    canv->cd(1);
+    cRate.DrawCopy();
+
+    canv->cd(2);
+    cGain.DrawCopy();
+
+    canv->cd(3);
+    cBaseline.DrawCopy();
+
+    canv->cd(4);
+    cRelSigma.DrawCopy();
+
+    canv->cd(5);
+    cCrosstalk.DrawCopy();
+
+    canv->cd(6);
+    cNoise.DrawCopy();
+
+
+    canv = &d->AddTab("Cams2");
+    canv->Divide(3,2);
+
+    canv->cd(1);
+    cFitProb.DrawCopy();
+
+    canv->cd(2);
+    cChi2.DrawCopy();
+
+    canv->cd(4);
+    cCoeffR.DrawCopy();
+
+    canv->cd(5);
+    cCrosstalkP.DrawCopy();
+
+    // --------------------------------------------------------
+
+    gStyle->SetOptFit(1);
+
+    canv = &d->AddTab("Hists1");
+    canv->Divide(3,2);
+
+    TH1 *hh = 0;
+
+    canv->cd(1);
+    hh = hRate1.DrawCopy();
+    hh = hRate2.DrawCopy("same");
+
+    canv->cd(2);
+    hh = hGain1.DrawCopy();
+    hh = hGain2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    canv->cd(3);
+    hh = hBaseline1.DrawCopy();
+    hh = hBaseline2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    canv->cd(4);
+    hh = hRelSigma1.DrawCopy();
+    hh = hRelSigma2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    canv->cd(5);
+    hh = hCrosstalk1.DrawCopy();
+    hh = hCrosstalk2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    canv->cd(6);
+    hh = hNoise1.DrawCopy();
+    hh = hNoise2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    // --------------------------------------------------------
+
+    canv = &d->AddTab("Hists2");
+    canv->Divide(3,2);
+
+    canv->cd(1);
+    gPad->SetLogy();
+    hh = hFitProb1.DrawCopy();
+    hh = hFitProb2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    canv->cd(2);
+    hChiSq1.DrawCopy();
+    hChiSq2.DrawCopy("same");
+
+    canv->cd(4);
+    hh = hCoeffR1.DrawCopy();
+    hh = hCoeffR2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    canv->cd(5);
+    hh = hCrosstalkP1.DrawCopy();
+    hh = hCrosstalkP2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    // --------------------------------------------------------
+
+    canv = &d->AddTab("NormGain");
+    canv->Divide(2,1);
+
+    canv->cd(1);
+    cNormGain.SetMinimum(0.8);
+    cNormGain.SetMaximum(1.2);
+    cNormGain.DrawCopy();
+
+    canv->cd(2);
+    gPad->SetLogy();
+    hh = hNormGain1.DrawCopy();
+    hh = hNormGain2.DrawCopy("same");
+    hh->Fit("gaus");
+
+    //------------------ Draw gain corrected sum specetrum -------------------
+    gROOT->SetSelectedPad(0);
+    c11.cd();
+    hSumClear1.DrawCopy("hist same");
+
+    //-------------------- fit gain corrected sum spectrum -------------------
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c11b = d->AddTab("CleanHist1");
+    c11b.cd();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    const Int_t    maxbin1 = hSumClear1.GetMaximumBin();
+    const Double_t ampl1   = hSumClear1.GetBinContent(maxbin1);
+
+    func.SetParameters(res_par);
+    func.SetParLimits(0, 0, 2*ampl1);
+    func.SetParameter(0, ampl1);
+    func.ReleaseParameter(6);
+
+    hSumClear1.Fit(&func, fast?"LN0QSR":"LIN0QSR");
+
+    hSumClear1.DrawCopy();
+    func.DrawCopy("same");
+
+    cout << "--------------------" << endl;
+    PrintFunc(func, integration_window);
+    cout << "--------------------" << endl;
+
+    //-------------------- fit gain corrected sum spectrum -------------------
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c11c = d->AddTab("CleanHist2");
+    c11c.cd();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    const Int_t    maxbin1b = hSumClear2.GetMaximumBin();
+    const Double_t ampl1b   = hSumClear2.GetBinContent(maxbin1b);
+
+    func.SetParameters(res_par);
+    func.SetParLimits(0, 0, 2*ampl1b);
+    func.SetParameter(0, ampl1b);
+    func.ReleaseParameter(6);
+
+    hSumClear2.Fit(&func, fast?"LN0QSR":"LIN0QSR");
+
+    hSumClear2.DrawCopy();
+    func.DrawCopy("same");
+
+    cout << "--------------------" << endl;
+    PrintFunc(func, integration_window);
+    cout << "--------------------" << endl;
+
+    //-------------------- fit gain corrected sum spectrum -------------------
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c12 = d->AddTab("GainHist1");
+    c12.cd();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    const Int_t    maxbin2 = hSumScale1.GetMaximumBin();
+    const Double_t ampl2   = hSumScale1.GetBinContent(maxbin2);
+
+    //Set fit parameters
+    Double_t par2[7] =
+    {
+        ampl2, 1, 0.1, res_par[3], 0, res_par[5]<0 ? -1 : res_par[5]/res_par[1], res_par[6]
+    };
+
+    func.SetParameters(par2);
+    func.SetParLimits(0, 0, 2*ampl2);
+    func.FixParameter(1, 1);
+    func.FixParameter(4, 0);
+
+    func.SetRange(0.62, 9);
+    hSumScale1.Fit(&func, fast?"LN0QSR":"LIN0QSR");
+
+    hSumScale1.DrawCopy();
+    func.DrawCopy("same");
+
+    cout << "--------------------" << endl;
+    PrintFunc(func, integration_window);
+    cout << "--------------------" << endl;
+
+    //-------------------- fit gain corrected sum spectrum -------------------
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c12b = d->AddTab("GainHist2");
+    c12b.cd();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    const Int_t    maxbin2b = hSumScale2.GetMaximumBin();
+    const Double_t ampl2b   = hSumScale2.GetBinContent(maxbin2b);
+
+    //Set fit parameters
+    Double_t par2b[7] =
+    {
+        ampl2b, 1, 0.1, res_par[3], 0, res_par[5]<0 ? -1 : res_par[5]/res_par[1], res_par[6]
+    };
+
+    func.SetParameters(par2b);
+    func.SetParLimits(0, 0, 2*ampl2b);
+    func.FixParameter(1, 1);
+    func.FixParameter(4, 0);
+
+    func.SetRange(0.62, 9);
+    hSumScale2.Fit(&func, fast?"LN0QSR":"LIN0QSR");
+
+    hSumScale2.DrawCopy();
+    func.DrawCopy("same");
+
+    cout << "--------------------" << endl;
+    PrintFunc(func, integration_window);
+    cout << "--------------------" << endl;
+
+    //--------fit gausses to peaks of gain corrected sum specetrum -----------
+
+    d->AddTab("ArrTime");
+    gPad->SetGrid();
+    hTime.DrawCopy();
+
+    // -----------------------------------------------------------------
+
+    d->AddTab("Pulse");
+    gPad->SetGrid();
+    hPulse.DrawCopy();
+
+    // ================================================================
+
+    cout << "Saving results to '" << outfile << "'" << endl;
+    d->SaveAs(outfile);
+    cout << "..success!" << endl;
+
+    TFile f(outfile, "UPDATE");
+    par.Write();
+    ext.Write("ExtractionRange");
+    header.Write();
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/runanalysis.sh
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/runanalysis.sh	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/runanalysis.sh	(revision 17960)
@@ -0,0 +1,65 @@
+#!/bin/bash
+
+threshold=5
+maxdist=14
+macro=$PWD/extract_singles.C
+outpath=$PWD/files
+
+mkdir -p $outpath
+cp ${macro} ${outpath}
+
+where="(((fNumPedestalTrigger=3000 OR fNumPedestalTrigger=5000) AND fRunTypeKey=2) OR (fNumPedestalTrigger=10000 AND fRunTypeKey=3) OR fRunTypeKey=17)"
+wheredrs="(drs.fROI=single.fROI AND fDrsStep=2)"
+
+query="SELECT Concat(fNight, '_', fRunID, '_', (SELECT fRunID FROM RunInfo \`drs\` WHERE drs.fNight=single.fNight AND "$wheredrs" AND single.fRunID<30+drs.fRunID ORDER BY ABS(CAST(single.fRunID AS SIGNED) - CAST(drs.fRunID AS SIGNED)) ASC LIMIT 0,1)) AS num "
+query=$query" FROM RunInfo \`single\` WHERE "$where
+
+runpairs=( `mysql -u factread --password=r3adfac! --host=lp-fact factdata -s -e "$query"` )
+
+for runpair in ${runpairs[@]}
+do
+   if [ $runpair = 'NULL' ]
+   then
+      continue
+   fi
+
+   year=`echo $runpair | cut -c1-4`
+   month=`echo $runpair | cut -c5-6`
+   day=`echo $runpair | cut -c7-8`
+   night=`echo $runpair | cut -d_ -f1`
+   run=`echo $runpair | cut -d_ -f2`
+   drs=`echo $runpair | cut -d_ -f3`
+   name=`echo $night | cut -c3-`
+
+   runnum=`printf %03d $run`
+   drsnum=`printf %03d $drs`
+
+   #runpath="/archive/fact/fails/raw/"$year"/"$month"/"$day
+   #drspath="/fact/raw/"$year"/"$month"/"$day
+
+   runpath="/fact/raw/"$year"/"$month"/"$day
+   drspath="/fact/raw/"$year"/"$month"/"$day
+
+   runfile=$runpath"/"$night"_"
+   drsfile=$drspath"/"$night"_"$drsnum.drs.fits.gz
+   log=$outpath"/"$night"_"$runnum
+
+   outfile=$outpath/`basename $runfile`${runnum}_${runnum}.root
+
+   if [ -e $outfile ]
+   then
+      continue
+   fi
+
+#  echo "Submitting "${night}"_"${runnum}"["${drsnum}"]"
+
+   cd ~/Mars
+
+   cmd="ROOT_HIST=0 ${ROOTSYS}/bin/root -q -b -l ${macro}+\($maxdist,$threshold,\\\"$runfile\\\",$run,$run,\\\"$drsfile\\\",\\\"${outpath}\\\"\)"
+
+   echo "echo '${cmd}'; date; ${cmd}" | qsub -N e${name}${runnum} -q test -cwd -e ${log}".err" -o ${log}".log"
+
+   cd - > /dev/null
+done
+
+
Index: branches/Mars_McMismatchStudy/fact/analysis/gain/temp.sh
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/gain/temp.sh	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/gain/temp.sh	(revision 17960)
@@ -0,0 +1,45 @@
+#!/bin/bash
+
+macro=$PWD/extract_temp.C
+outpath=$PWD/temp
+
+mkdir -p $outpath
+cp ${macro} ${outpath}
+
+where="(((fNumPedestalTrigger=3000 OR fNumPedestalTrigger=5000) AND fRunTypeKey=2) OR (fNumPedestalTrigger=10000 AND fRunTypeKey=3) OR fRunTypeKey=17)"
+wheredrs="(drs.fROI=single.fROI AND fDrsStep=2)"
+
+query="SELECT Concat(fNight, '_', fRunID, '_', (SELECT fRunID FROM RunInfo \`drs\` WHERE drs.fNight=single.fNight AND "$wheredrs" AND single.fRunID<30+drs.fRunID ORDER BY ABS(CAST(single.fRunID AS SIGNED) - CAST(drs.fRunID AS SIGNED)) ASC LIMIT 0,1)) AS num "
+query=$query" FROM RunInfo \`single\` WHERE "$where
+
+runpairs=( `mysql -u factread --password=r3adfac! --host=lp-fact factdata -s -e "$query"` )
+
+for runpair in ${runpairs[@]}
+do
+   if [ $runpair = 'NULL' ]
+   then
+      continue
+   fi
+
+   night=`echo $runpair | cut -d_ -f1`
+   runnum=`printf %03d $run`
+
+   log=$outpath"/"$night"_"$runnum
+
+   outfile=$outpath/${runnum}_${runnum}.root
+
+   if [ -e $outfile ]
+   then
+      continue
+   fi
+
+   cd ~/Mars
+
+   cmd="ROOT_HIST=0 ${ROOTSYS}/bin/root -q -b -l ${macro}+\($night,$runnum,\\\"${outfile}\\\"\)"
+
+   echo "date; echo '${cmd}'; ${cmd}" | qsub -N t${night}${runnum} -q test -cwd -e ${log}".err" -o ${log}".log"
+
+   cd - > /dev/null
+done
+
+
Index: branches/Mars_McMismatchStudy/fact/analysis/ganymed.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/ganymed.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/ganymed.C	(revision 17960)
@@ -0,0 +1,466 @@
+void SetupWriter(MWriteRootFile *write, const char *name) const
+{
+    if (!write)
+        return;
+
+    write->SetName(name);
+    write->AddContainer("MHillas",        "Events");
+    write->AddContainer("MHillasSrc",     "Events");
+    write->AddContainer("MHillasExt",     "Events");
+    write->AddContainer("MPointingPos",   "Events");
+    write->AddContainer("MHillasSrcAnti", "Events", kFALSE);
+    write->AddContainer("MImagePar",      "Events", kFALSE);
+    write->AddContainer("MNewImagePar",   "Events", kFALSE);
+    write->AddContainer("MNewImagePar2",  "Events", kFALSE);
+    write->AddContainer("Hadronness",     "Events", kFALSE);
+    write->AddContainer("MSrcPosCam",     "Events", kFALSE);
+    write->AddContainer("MSrcPosAnti",    "Events", kFALSE);
+    write->AddContainer("ThetaSquared",   "Events", kFALSE);
+    write->AddContainer("OpticalAxis",    "Events", kFALSE);
+    write->AddContainer("Disp",           "Events", kFALSE);
+    write->AddContainer("Ghostbuster",    "Events", kFALSE);
+    write->AddContainer("MEnergyEst",     "Events", kFALSE);
+    write->AddContainer("MTime",          "Events", kFALSE);
+    write->AddContainer("MMcEvt",         "Events", kFALSE);
+    write->AddContainer("DataType",       "Events");
+    write->AddContainer("FileId",         "Events");
+    write->AddContainer("EvtNumber",      "Events");
+    //    write->AddContainer("MMuonSearchPar", "Events", kFALSE);
+    //    write->AddContainer("MMuonCalibPar",  "Events", kFALSE);
+}
+
+int ganymed(const char *dataset, const char *outfile, Float_t ra, Float_t dec)
+{
+    MDirIter files;
+    if (files.ReadList(dataset)<=0)
+        return 2;
+    files.Sort();
+
+    // =============================================================
+
+    // Crab (05h34'32" 22d00'52")
+    MPointingPos source("MSourcePos");
+    //source.SetSkyPosition(5.5755, 22.0144); // ra[h], dec[deg]
+    //source.SetSkyPosition(12.356089, 30.176897); // ra[h], dec[deg]//1218
+    //source.SetSkyPosition(16.897867,39.760201);// mrk501
+    //source.SetSkyPosition(11.0742, 38.2089); // ra[h], dec[deg]//mrk421
+    source.SetSkyPosition(ra, dec); // ra[h], dec[deg]//mrk421
+
+    UInt_t fNumOffSourcePos = 5;
+
+    // =============================================================
+
+    // FIXME: If fPathIn read cuts and energy estimator from file!
+    MContinue contq("MImagePar.fNumIslands>3.5"
+                    "|| MNewImagePar.fNumUsedPixels<5.5"
+                    "|| MNewImagePar.fLeakage1>0.1",
+                    "CutQ");
+
+    MContinue cont0("MHillas.fSize<0"
+                    "|| MHillasExt.fSlopeSpreadWeighted>0.68"
+                    "|| MHillasExt.fSlopeSpreadWeighted<0.18"
+                    "|| log10(MHillas.GetArea*MGeomCam.fConvMm2Deg^2)>(log10(MHillas.fSize)-2)*1.1-1.55"
+                    "|| MNewImagePar.fConcCore < 0.13"
+                    "|| MNewImagePar.fConcCOG  < 0.15"
+                    , "Cut0");
+
+    // Cuts before plots
+    MContinue cont2("0"
+                    "|| MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)*MGeomCam.fConvMm2Deg<-0.07"
+                    "|| log10(MNewImagePar.fConc1)<-log10(MHillas.fSize)*0.57+0.13"
+                    //"|| log10(MNewImagePar.fConc1)>-log10(MHillas.fSize)*0.57+0.5"
+                    //"|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg>log10(MHillas.fSize)*0.42+0.29"
+                    "|| MHillas.GetArea*MGeomCam.fConvMm2Deg^2<0.01"
+                    "|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg>log10(MHillas.fSize)*0.5+0.095"
+                    "|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg<0.4"
+                    "|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg>1.2",
+                    "Cut2");
+
+    TArrayD param(12);
+    // Parametrization of Disp
+    param[0]  =  1.15136;     // constant
+    param[8]  =  0.0681437;   // slope
+    param[9]  =  2.62932;     // leak
+    param[10] =  1.51279;     // size-offset
+    param[11] =  0.0507821;   // size-slope
+    // Parametrization for sign of disp (m3long, slope)
+    param[5]  = -0.07;
+    param[6]  =  7.2;
+    param[7]  =  0.5;
+    // ThetaSq-Cut
+    param[1]  =  0.11;  // 0.215
+    // Area-Cut
+    param[2]  =  0.215468;
+    param[3]  =  5.63973;
+    param[4]  =  0.0836169;
+
+    // --------------------------------------------------------------------------------
+
+    // Setup fitter and histograms
+    MAlphaFitter fit;
+    fit.SetBackgroundFitMin(0.09);
+    fit.SetBackgroundFitMax(0.25);
+    fit.SetPolynomOrder(1);
+    fit.SetSignalFunction(MAlphaFitter::kThetaSq);
+    fit.SetScaleUser(1./fNumOffSourcePos); // includes fit.SetScaleMode(MAlphaFitter::kUserScale);
+
+    // --------------------------------------------------------------------------------
+
+    MBinning bins3( 67, -0.005, 0.665, "BinningTheta",  "asin");
+    MBinning binsD( 25,   0,      2.5, "BinningDist");
+    MBinning binsC( 25,   0,      2.5, "BinningDistC");
+    MBinning binsR( 60,   0,      300, "BinningRate");
+
+    // --------------------------------------------------------------------------------
+
+    MParList plist;
+    plist.AddToList(&source);
+    plist.AddToList(&fit);
+
+    // Initialize default binnings
+    plist.AddToList(&bins3);
+    plist.AddToList(&binsD);
+    plist.AddToList(&binsC);
+    plist.AddToList(&binsR);
+
+    MParameterI par("DataType");
+    plist.AddToList(&par);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // La Palma Magic1
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    // --------------------------------------------------------------------------------
+
+    MParameterD scale;
+    scale.SetVal(1./fNumOffSourcePos);
+
+    MHThetaSq *halphaoff = plist.FindCreateObj("MHThetaSq", "HistOff");
+    halphaoff->ForceUsingSize();
+
+    MFillH falpha(halphaoff, "", "FillHist");
+
+    MFMagicCuts cuts;
+    cuts.SetHadronnessCut(MFMagicCuts::kNoCut);
+    cuts.SetVariables(param);
+
+    // Cuts before thetasq
+    MContinue cont1(&cuts, "Cut1");
+
+    // Cuts before writing
+    MContinue cont3("",    "Cut3");
+    contq.SetAllowEmpty();
+    cont0.SetAllowEmpty();
+    cont1.SetAllowEmpty();
+    cont2.SetAllowEmpty();
+    cont3.SetAllowEmpty();
+
+    cont1.SetInverted();
+
+    // Filter for VsSize
+    MFDataPhrase ftheta("ThetaSquared.fVal < ThetaSquaredCut.fVal", "CutT");
+
+    // ------------- Loop Off Data --------------------
+    MReadReports readoffdata;
+    // readoffdata.DisableAutoScheme();
+    readoffdata.AddTree("Events", "MTime.", MReadReports::kMaster);
+    readoffdata.AddTree("Drive",            MReadReports::kRequired);
+
+    readoffdata.AddFiles(files);
+
+    TString fname0 = Form("%s-summary.root",  outfile);
+    TString fname1 = Form("%s-analysis.root", outfile);
+
+    MWriteRootFile dummy0(fname0.Data(), "RECREATE");
+    MWriteRootFile dummy1(fname1.Data(), "RECREATE");
+
+    MWriteRootFile *write0 = &dummy0;
+    MWriteRootFile *write1 = &dummy1;
+    SetupWriter(write0, "WriteAfterCut0");
+    SetupWriter(write1, "WriteAfterCut3");
+
+    MParameterCalc setevtnum("MRawEvtHeader.fDAQEvtNumber", "SetEvtNumber");
+    setevtnum.SetNameParameter("EvtNumber");
+
+    MParameterCalc setrunnum("MRawRunHeader.GetFileID", "SetFileId");
+    setrunnum.SetNameParameter("FileId");
+
+    MFillH fill1a("MHHillasOffPre  [MHHillas]",      "MHillas",      "FillHillasPre");
+    MFillH fill2a("MHHillasOffPost [MHHillas]",      "MHillas",      "FillHillasPost");
+    MFillH fill3a("MHVsSizeOffPost [MHVsSize]",      "MHillasSrc",   "FillVsSizePost");
+    MFillH fill3c("MHVsSizeOffTheta [MHVsSize]",     "MHillasSrc",   "FillVsSizeTheta");
+    MFillH fill4a("MHHilExtOffPost [MHHillasExt]",   "MHillasSrc",   "FillHilExtPost");
+    MFillH fill5a("MHHilSrcOffPost [MHHillasSrc]",   "MHillasSrc",   "FillHilSrcPost");
+    MFillH fill6a("MHImgParOffPost [MHImagePar]",    "MImagePar",    "FillImgParPost");
+    MFillH fill7a("MHNewParOffPost [MHNewImagePar]", "MNewImagePar", "FillNewParPost");
+    //MFillH fill9a("MHEffOffTime    [MHEffectiveOnTime]", "MTime",        "FillEffOnTime");
+    fill1a.SetNameTab("PreCut");
+    fill2a.SetNameTab("PostCut");
+    fill3a.SetNameTab("VsSize");
+    fill3c.SetNameTab("CutT");
+    fill4a.SetNameTab("HilExt");
+    fill5a.SetNameTab("HilSrc");
+    fill6a.SetNameTab("ImgPar");
+    fill7a.SetNameTab("NewPar");
+    //fill9a.SetNameTab("EffOffT");
+
+    fill3c.SetFilter(&ftheta);
+
+    //MFDataMember fbin("Bin.fVal", '>', 0);
+    //fill9a.SetFilter(&fbin);
+
+    MTaskList tlist2;
+    tlist2.SetNumPasses(fNumOffSourcePos);
+    fill2a.SetWeight(&scale);
+    fill3a.SetWeight(&scale);
+    fill3c.SetWeight(&scale);
+    fill4a.SetWeight(&scale);
+    fill5a.SetWeight(&scale);
+    fill6a.SetWeight(&scale);
+    fill7a.SetWeight(&scale);
+
+    // How to get source position from off- and on-data?
+    MSrcPosCalc scalc;
+    scalc.SetMode(MSrcPosCalc::kWobble);
+    scalc.SetCallback(&tlist2);
+
+    MSrcPosCorrect scor;
+
+    MHillasCalc hcalc;
+    MHillasCalc hcalc2("MHillasCalcAnti");
+    hcalc.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetNameHillasSrc("MHillasSrcAnti");
+    hcalc2.SetNameSrcPosCam("MSrcPosAnti");
+
+    MSrcPosRndm srcrndm;
+
+    tlist2.AddToList(&scalc);
+    //tlist2.AddToList(&scor);
+    tlist2.AddToList(&srcrndm);
+    tlist2.AddToList(&hcalc);
+    tlist2.AddToList(&hcalc2);
+    tlist2.AddToList(&setrunnum);
+    tlist2.AddToList(&setevtnum);
+    tlist2.AddToList(&cuts);
+    tlist2.AddToList(write0);
+    tlist2.AddToList(&cont0);  // Post/Pre shown cuts
+    tlist2.AddToList(&cont1);  // Calculate ThetaSq
+    tlist2.AddToList(&fill2a);
+    tlist2.AddToList(&ftheta); // Calculate theta Cut
+    tlist2.AddToList(&falpha);
+    tlist2.AddToList(&fill3c); // With theta cut
+    tlist2.AddToList(&cont2);  
+    tlist2.AddToList(&fill3a);
+    tlist2.AddToList(&fill4a);
+    tlist2.AddToList(&fill5a);
+    tlist2.AddToList(&fill6a);
+    tlist2.AddToList(&fill7a);
+    tlist2.AddToList(&cont3);
+    tlist2.AddToList(write1);
+
+    MPointingPosCalc pcalc;
+    MPointingDevCalc devcalc;
+
+    tlist.AddToList(&readoffdata);
+    tlist.AddToList(&pcalc,  "Drive");
+    tlist.AddToList(&contq,  "Events");
+    tlist.AddToList(&fill1a, "Events");
+    tlist.AddToList(&tlist2, "Events");
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    par.SetVal(0);
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop("Off");
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+        return 2;
+
+    if (!evtloop.GetDisplay())
+        return 2;
+
+    // ------------- Loop On Data --------------------
+    MReadReports readondata;
+    // readoffdata.DisableAutoScheme();
+    readondata.AddTree("Events", "MTime.", MReadReports::kMaster);
+    readondata.AddTree("Drive",            MReadReports::kRequired);
+    readondata.AddTree("Rates",            MReadReports::kRequired);
+    readondata.AddTree("Humidity",         MReadReports::kRequired);
+    readondata.AddTree("Temperatures",     MReadReports::kRequired);
+
+    readondata.AddFiles(files);
+
+    scalc.SetMode(MSrcPosCalc::kDefault);
+    scalc.SetNumRandomOffPositions(fNumOffSourcePos);
+
+    MFillH fill1b("MHHillasOnPre  [MHHillas]",      "MHillas",      "FillHillasPre");
+    MFillH fill2b("MHHillasOnPost [MHHillas]",      "MHillas",      "FillHillasPost");
+    MFillH fill3b("MHVsSizeOnPost [MHVsSize]",      "MHillasSrc",   "FillVsSizePost");
+    MFillH fill3d("MHVsSizeOnTheta [MHVsSize]",     "MHillasSrc",   "FillVsSizeTheta");
+    MFillH fill4b("MHHilExtOnPost [MHHillasExt]",   "MHillasSrc",   "FillHilExtPost");
+    MFillH fill5b("MHHilSrcOnPost [MHHillasSrc]",   "MHillasSrc",   "FillHilSrcPost");
+    MFillH fill6b("MHImgParOnPost [MHImagePar]",    "MImagePar",    "FillImgParPost");
+    MFillH fill7b("MHNewParOnPost [MHNewImagePar]", "MNewImagePar", "FillNewParPost");
+    //MFillH fill9b("MHEffOnTime    [MHEffectiveOnTime]", "MTime",        "FillEffOnTime");
+    fill1b.SetNameTab("PreCut");
+    fill2b.SetNameTab("PostCut");
+    fill3b.SetNameTab("VsSize");
+    fill3d.SetNameTab("CutT");
+    fill4b.SetNameTab("HilExt");
+    fill5b.SetNameTab("HilSrc");
+    fill6b.SetNameTab("ImgPar");
+    fill7b.SetNameTab("NewPar");
+    //fill9b.SetNameTab("EffOnT");
+    fill1b.SetDrawOption("same");
+    fill2b.SetDrawOption("same");
+    fill3b.SetDrawOption("same");
+    fill3d.SetDrawOption("same");
+    fill4b.SetDrawOption("same");
+    fill5b.SetDrawOption("same");
+    fill6b.SetDrawOption("same");
+    fill7b.SetDrawOption("same");
+    //fill9b.SetFilter(&fbin);
+
+    fill3d.SetFilter(&ftheta);
+
+    MHThetaSq *halphaon = plist.FindCreateObj("MHThetaSq", "Hist");
+    halphaon->ForceUsingSize();
+
+    MFillH falpha2(halphaon, "", "FillHist");
+
+    tlist2.SetNumPasses();
+
+    tlist.Replace(&readondata);
+
+    MHSrcPosCam hsrcpos(kTRUE);
+
+    MFillH fillsrc(&hsrcpos, "MSrcPosCam", "FillSrcPosCam");
+    fillsrc.SetNameTab("SrcPos");
+
+    tlist2.AddToListBefore(&fillsrc, &hcalc);
+
+    MH3 hvs1("MPointingPos.fZd");
+    MH3 hvs2("MPointingPos.fZd");
+    MHVsTime hvstM("MTimeDrive.GetMjd");
+    MHVsTime hvst0("MPointingPos.fZd");
+    MHVsTime hvst1("MReportRates.fTriggerRate");
+    MH3      hvst2("MPointingPos.fZd", "MReportRates.fTriggerRate");
+    MHVsTime hvst("MReportTemperatures.GetTempMean");
+    MHVsTime hvsh("MReportHumidity.GetMean");
+    hvs1.SetName("ObsTime;Theta");
+    hvs2.SetName("OnTime;Theta");
+    hvstM.SetName("MJD");
+    hvst0.SetName("ZdTime");
+    hvst1.SetName("Rate");
+    hvst2.SetName("RateZd;Theta;Rate");
+    hvst.SetName("CamTemp");
+    hvsh.SetName("CamHum");
+    hvs1.SetTitle("Observation time vs. Zenith Angle;\\Theta [\\circ];T_{on} [s]");
+    hvs2.SetTitle("On-Time vs. Zenith Angle;\\Theta [\\circ];T_{on} [s]");
+    hvstM.SetTitle("MJD vs time;Time;MJD");
+    hvst0.SetTitle("Zenith distance vs time;Time;Zd [\\circ]");
+    hvst1.SetTitle("Camera trigger rate vs time;Time;Rate [Hz]");
+    hvst2.SetTitle("Camera trigger rate vs Zd; Zd [\\circ];Rate [Hz]");
+    hvst.SetTitle("Average sensor compartment temperature;Time;T [\\circ C]");
+    hvsh.SetTitle("Average camera humidity;Time;Hum [%]");
+
+    MFillH fillvs1(&hvs1, "", "FillObsTime");
+    MFillH fillvs2(&hvs2, "", "FillOnTime");
+    MFillH fillvstM(&hvstM, "MTime", "FillMjdVsTime");
+    MFillH fillvst0(&hvst0, "MTimeDrive", "FillZdVsTime");
+    MFillH fillvst1(&hvst1, "MTimeRates", "FillRate");
+    MFillH fillvst2(&hvst2, "", "FillRateVsZd");
+    MFillH fillvst(&hvst, "MTimeTemperatures", "FillCamTemp");
+    MFillH fillvsh(&hvsh, "MTimeHumidity",     "FillCamHum");
+    fillvs1.SetNameTab("ObsTime");
+    fillvs2.SetNameTab("OnTime");
+    fillvst1.SetNameTab("Rate");
+    fillvst2.SetNameTab("RateZd");
+    fillvst.SetNameTab("CamTemp");
+    fillvsh.SetNameTab("CamHum");
+
+    hvs1.SetWeight("MReportRates.fElapsedTime");
+    hvs2.SetWeight("MReportRates.fElapsedOnTime");
+
+    hvst1.SetMinimum(0);
+    hvst2.SetDrawOption("colz");
+
+    MH3 hrate("MRawRunHeader.GetFileID"/*, "MRawEvtHeader.GetTriggerID"*/);
+    hrate.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hrate.SetName("RateVsRun");
+    hrate.SetTitle("Event rate after quality cuts;File Id;Event Rate [Hz];");
+    hrate.InitLabels(MH3::kLabelsX);
+    hrate.GetHist().SetMinimum(0);
+
+    MFillH fillr(&hrate, "", "FillRateVsRun");
+    tlist.AddToListAfter(&fillr, &contq, "Events");
+
+    tlist.Replace(&fill1b);
+
+    tlist2.Replace(&fill2b);
+    tlist2.Replace(&fill3b);
+    tlist2.Replace(&fill3d);
+    tlist2.Replace(&fill4b);
+    tlist2.Replace(&fill5b);
+    tlist2.Replace(&fill6b);
+    tlist2.Replace(&fill7b);
+    tlist2.Replace(&falpha2);
+    tlist.AddToList(&fillvs1,  "Rates");
+    tlist.AddToList(&fillvs2,  "Rates");
+    tlist.AddToList(&fillvst1, "Rates");
+    tlist.AddToList(&fillvst2, "Rates");
+    tlist.AddToList(&fillvst,  "Temperatures");
+    tlist.AddToList(&fillvsh,  "Humidity");
+    tlist.AddToList(&fillvst0, "Drive");
+    tlist.AddToList(&fillvstM, "Drive");
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    par.SetVal(1);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+        return 2;
+
+    if (!evtloop.GetDisplay())
+        return 2;
+
+    TObjArray cont;
+    //cont.Add(const_cast<TEnv*>(GetEnv()));
+    //cont.Add(const_cast<MSequence*>(&fSequence));
+
+    //TNamed cmdline("CommandLine", fCommandLine.Data());
+    //cont.Add(&cmdline);
+
+    if (d)
+    {
+        TString title = "--  Analysis #";
+        title += dataset;
+        title += "  --";
+        d->SetTitle(title, kFALSE);
+
+        cont.Add(d);
+        TString path;
+        path += fname1;
+
+        d->SaveAs(path);
+    }
+
+//    if (!WriteContainer(cont, fname1, "RECREATE"))
+//        return;
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/lightcurve.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/lightcurve.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/lightcurve.C	(revision 17960)
@@ -0,0 +1,701 @@
+#include <iostream>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TF1.h>
+#include <TGraph.h>
+#include <TGraphErrors.h>
+#include <TText.h>
+#include <TFile.h>
+#include <TSystem.h>
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+#include <TPRegexp.h>
+
+#include "MSQLMagic.h"
+#include "MAlphaFitter.h"
+#include "MHThetaSq.h"
+
+#include "MObservatory.h"
+#include "MAstro.h"
+#include "MAstroSky2Local.h"
+#include "MAstroCatalog.h"
+#include "MVector3.h"
+#include "MMath.h"
+#include "MDirIter.h"
+#include "MStatusArray.h"
+#include "MStatusDisplay.h"
+#include "MHCamera.h"
+#include "MSequence.h"
+
+using namespace std;
+
+
+int lightcurve(Int_t sourcekey=1, Int_t nightmin=0, Int_t nightmax=0, Int_t minutes=20, TString table="AnalysisResultsRunLP", TString outfile="lc", Bool_t dch=kTRUE)
+{
+
+    cout << minutes << " min bins..." << endl;
+    minutes*=60;
+    cout << minutes << " sec bins..." << endl;
+
+    MSQLServer serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    TString query;
+    query=Form("SELECT Min(fNight), Max(fNight) FROM %s ", table.Data());
+    query+=" LEFT JOIN RunInfo USING(fNight, fRunID) ";
+    query+=Form(" WHERE fSourceKey=%d", sourcekey);
+    if (nightmin)
+        query+=Form(" AND fNight >=%d",nightmin);
+    if (nightmax)
+        query+=Form(" AND fNight <=%d",nightmax);
+
+    // datacheck
+    TString datacheck=" ";
+    //remove data with wrong settings
+    datacheck+=" AND fNight>20120420 AND NOT fNight IN (20120406,20120410,20120503) AND";//data with different bias voltage
+    datacheck+=" NOT fNight BETWEEN 20121206 AND 20130110"; // broken bias channel
+    //datacheck+=" AND NOT (fNight=20120608 AND fRunID=65) "; // something went wrong with tracking?
+    // 24.6. new coefficients
+    TString zdparam=" pow(0.753833 * cos(Radians(fZenithDistanceMean)), 7.647435) * exp(-5.753686*pow(Radians(fZenithDistanceMean),2.089609))";
+    TString thparam=" pow((if(isnull(fThresholdMinSet),fThresholdMedian,fThresholdMinSet)-329.4203),2) * (-0.0000002044803) ";
+    TString param=" (fNumEvtsAfterBgCuts/5-fNumSigEvts)/fOnTimeAfterCuts - "+zdparam+" - "+thparam+" ";
+    datacheck+=" AND -0.085 < ("+param+") ";
+    datacheck+=" AND 0.25 > ("+param+") ";
+
+
+    if (dch)
+        query+=datacheck;
+
+    //cout << "Q: " << query << endl;
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return 1;
+
+    TSQLRow *row=res->Next();
+    TString nightstart=(*row)[0];
+    TString nightstop=(*row)[1];
+    delete res;
+
+    query =" SELECT fNight FROM "+table;
+    query+=" LEFT JOIN RunInfo USING(fNight, fRunID) ";
+    query+=Form(" WHERE fSourceKey=%d", sourcekey);
+    query+=Form(" AND fNight BETWEEN %s AND %s ", nightstart.Data(), nightstop.Data());
+    query+=" GROUP BY fNight ";
+    query+=" ORDER BY fNight ";
+
+    cout << "Q: " << query << endl;
+
+
+    TSQLResult *res3 = serv.Query(query);
+    if (!res3)
+        return 1;
+
+    //counter
+    Int_t counter=0;//counter for graphs
+    Int_t counter2=0;//counter for loop
+
+    //graphs and histograms
+    TGraphErrors excessrate;
+    TGraphErrors backgroundrate;
+    TGraphErrors signif;
+    TGraphErrors significancerate;
+    TGraphErrors excratevsbgrate;
+    TGraphErrors excvsbg;
+    TGraphErrors excvszd;
+    TGraphErrors bgvszd;
+    TGraphErrors excvscur;
+    TGraphErrors bgvscur;
+    TGraphErrors excvsth;
+    TGraphErrors bgvsth;
+    TGraphErrors zdvstime;
+    TGraphErrors curvstime;
+    TGraphErrors thvstime;
+    TH1F exc("exc","rates", 43, -12.5, 202.5);
+    TH1F bg("bg","rates", 43, -12.5, 202.5);
+
+    //variables for calculations and graphs
+    Float_t significance;
+    TString excevts;
+    TString bgevts;
+    TString sigevts;
+    TString ontime;
+    TString zd2;
+    TString zd3;
+    TString cur;
+    TString th;
+    Float_t excevtssum=0;
+    Float_t bgevtssum=0;
+    Float_t sigevtssum=0;
+    Float_t ontimesum=0;
+    Float_t excrate=0;
+    Float_t bgrate=0;
+    Float_t signifrate=0;
+    Float_t excerr=0;
+    Float_t bgerr=0;
+    Float_t zdmean=0;
+    Float_t curmean=0;
+    Float_t thmean=0;
+    Float_t zddiff=0;
+    Float_t curdiff=0;
+    Float_t thdiff=0;
+    Float_t zdmin=0;
+    Float_t zdmax=0;
+    Float_t curmin=0;
+    Float_t curmax=0;
+    Float_t thmin=0;
+    Float_t thmax=0;
+    MTime start;
+    MTime stop;
+    Double_t mjdstart=0;
+    Double_t mjdstop=0;
+    Double_t mjd=0;
+    Double_t mjddiff=0;
+
+    TSQLRow *row3=0;
+    while ((row3=res3->Next()))
+    {
+        cout << "NIGHT " << (*row3)[0] << endl;
+        //query =" SELECT IF(ISNULL(fOnTimeAfterCuts), IF(ISNULL(fOnTime), Time_to_sec(Timediff(fRunStop,fRunStart)), fOnTime), fOnTimeAfterCuts), ";
+        query =" SELECT fOnTimeAfterCuts, fNumBgEvts, fNumSigEvts, fNumExcEvts, ";
+        query+=" fRunStart, fRunStop, ";
+        query+=" fZenithDistanceMax, fZenithDistanceMin, ";
+        query+=" fCurrentsMedMeanBeg, fThresholdMinSet FROM "+table;
+        query+=" LEFT JOIN RunInfo USING(fNight, fRunID) ";
+        query+=Form(" WHERE fSourceKey=%d", sourcekey);
+        query+=Form(" AND fNight= %s ", (*row3)[0]);
+        query+=" AND fOnTimeAfterCuts < 1000 "; //exclude runs with wrong/too high ontime
+        query+=" AND NOT ISNULL(fNumExcEvts) ";// only where excess was extracted
+
+        if (dch)
+            query+=datacheck;
+
+        query+=" ORDER BY fRunID ";
+
+        cout << "Q: " << query << endl;
+
+        TSQLResult *res2 = serv.Query(query);
+        if (!res2)
+            return 1;
+
+        counter2=0;
+        excevtssum=0;
+        bgevtssum=0;
+        sigevtssum=0;
+        ontimesum=0;
+        TSQLRow *row2=0;
+        while ((row2=res2->Next()))
+        {
+            counter2++;
+            ontime=(*row2)[0];
+            bgevts=(*row2)[1];
+            sigevts=(*row2)[2];
+            excevts=(*row2)[3];
+            zd2=(*row2)[6];//zdmin
+            zd3=(*row2)[7];//zdmax
+            cur=(*row2)[8];//currents
+            th=(*row2)[9];//threshold
+            if (counter2==1)
+            {
+                start.SetSqlDateTime((*row2)[4]);
+                zdmin=zd3.Atof();
+                zdmax=zd2.Atof();
+                curmin=cur.Atof();
+                curmax=cur.Atof();
+                thmin=th.Atof();
+                thmax=th.Atof();
+            }
+
+            if (ontimesum+ontime.Atof()>minutes && minutes>0)
+            {
+                //calculate values
+                significance = MMath::SignificanceLiMaSigned(sigevtssum, bgevtssum*5, 0.2);
+                signifrate = significance/sqrt(ontimesum/3600);
+                bgrate = bgevtssum/ontimesum*3600;
+                excrate = excevtssum/ontimesum*3600;
+                excerr = MMath::ErrorExc(sigevtssum, bgevtssum*5, 0.2)/ontimesum*3600.;
+                bgerr = sqrt(bgevtssum)/ontimesum*3600;
+                zdmean = zdmin+(zdmax-zdmin)/2;
+                zddiff = (zdmax-zdmin)/2;
+                curmean = curmin+(curmax-curmin)/2;
+                curdiff = (curmax-curmin)/2;
+                thmean = thmin+(thmax-thmin)/2;
+                thdiff = (thmax-thmin)/2;
+                mjdstart = start.GetMjd();
+                mjdstop = stop.GetMjd();
+                mjd = mjdstart+(mjdstop-mjdstart)/2.;
+                mjddiff = ontimesum/3600./24/2;
+
+                //fill histograms and graphs
+                exc.Fill(excrate);
+                bg.Fill(bgrate);
+                excessrate.SetPoint(counter, mjd, excrate);
+                excessrate.SetPointError(counter, mjddiff, excerr);
+                backgroundrate.SetPoint(counter, mjd, bgrate);
+                backgroundrate.SetPointError(counter, mjddiff, bgerr);
+                excvsbg.SetPoint(counter, bgrate, excrate);
+                excvsbg.SetPointError(counter, bgerr, excerr);
+                excvszd.SetPoint(counter, zdmean, excrate);
+                excvszd.SetPointError(counter, zddiff, excerr);
+                bgvszd.SetPoint(counter, zdmean, bgrate);
+                bgvszd.SetPointError(counter, zddiff, bgerr);
+                excvscur.SetPoint(counter, curmean, excrate);
+                excvscur.SetPointError(counter, curdiff, excerr);
+                bgvscur.SetPoint(counter, curmean, bgrate);
+                bgvscur.SetPointError(counter, curdiff, bgerr);
+                excvsth.SetPoint(counter, thmean, excrate);
+                excvsth.SetPointError(counter, thdiff, excerr);
+                bgvsth.SetPoint(counter, thmean, bgrate);
+                bgvsth.SetPointError(counter, thdiff, bgerr);
+                signif.SetPoint(counter, mjd, significance);
+                signif.SetPointError(counter, mjddiff, 0);
+                significancerate.SetPoint(counter, mjd, signifrate);
+                significancerate.SetPointError(counter, mjddiff, 0);
+                zdvstime.SetPoint(counter, mjd, zdmean);
+                zdvstime.SetPointError(counter, mjddiff, zddiff);
+                curvstime.SetPoint(counter, mjd, curmean);
+                curvstime.SetPointError(counter, mjddiff, curdiff);
+                thvstime.SetPoint(counter, mjd, thmean);
+                thvstime.SetPointError(counter, mjddiff, thdiff);
+
+                //set couter for graphs
+                counter++;
+                //reset counter for calculation
+                counter2=0;
+                //reset variables
+                start.SetSqlDateTime((*row2)[4]);
+                excevtssum=0;
+                bgevtssum=0;
+                sigevtssum=0;
+                ontimesum=0;
+            }
+            //set stop time
+            stop.SetSqlDateTime((*row2)[5]);
+            //add up variables
+            ontimesum+=ontime.Atof();
+            excevtssum+=excevts.Atof();
+            bgevtssum+=bgevts.Atof();
+            sigevtssum+=sigevts.Atof();
+
+            //update zdmin
+            if (zdmin>zd3.Atof())
+                zdmin=zd3.Atof();
+            //update zdmax
+            if (zdmax<zd2.Atof())
+                zdmax=zd2.Atof();
+
+            //update curmin
+            if (curmin>cur.Atof())
+                curmin=cur.Atof();
+            //update curmax
+            if (curmax<cur.Atof())
+                curmax=cur.Atof();
+
+            //update thmin
+            if (thmin>th.Atof())
+                thmin=th.Atof();
+            //update thmax
+            if (thmax<th.Atof())
+                thmax=th.Atof();
+
+        }
+        //cout << "reached last run" << endl;
+        // if ontime is larger than 90% of the timebin width, the last point is filled
+        if (ontimesum>(minutes-0.1*minutes) || minutes<0)
+        {
+            if (minutes<0 && ontimesum>20*60 && bgevtssum!=0)
+            {
+                //calculate values
+                significance = MMath::SignificanceLiMaSigned(sigevtssum, bgevtssum*5, 0.2);
+                signifrate = significance/sqrt(ontimesum/3600);
+                bgrate = bgevtssum/ontimesum*3600;
+                excrate = excevtssum/ontimesum*3600;
+                excerr = MMath::ErrorExc(sigevtssum, bgevtssum*5, 0.2)/ontimesum*3600.;
+                bgerr = sqrt(bgevtssum)/ontimesum*3600;
+                zdmean = zdmin+(zdmax-zdmin)/2;
+                zddiff = (zdmax-zdmin)/2;
+                curmean = curmin+(curmax-curmin)/2;
+                curdiff = (curmax-curmin)/2;
+                thmean = thmin+(thmax-thmin)/2;
+                thdiff = (thmax-thmin)/2;
+                mjdstart = start.GetMjd();
+                mjdstop = stop.GetMjd();
+                mjd = mjdstart+(mjdstop-mjdstart)/2.;
+                mjddiff = ontimesum/3600./24/2;
+
+                //fill histograms and graphs
+                exc.Fill(excrate);
+                bg.Fill(bgrate);
+                excessrate.SetPoint(counter, mjd, excrate);
+                excessrate.SetPointError(counter, mjddiff, excerr);
+                backgroundrate.SetPoint(counter, mjd, bgrate);
+                backgroundrate.SetPointError(counter, mjddiff, bgerr);
+                excvsbg.SetPoint(counter, bgrate, excrate);
+                excvsbg.SetPointError(counter, bgerr, excerr);
+                excvszd.SetPoint(counter, zdmean, excrate);
+                excvszd.SetPointError(counter, zddiff, excerr);
+                bgvszd.SetPoint(counter, zdmean, bgrate);
+                bgvszd.SetPointError(counter, zddiff, bgerr);
+                excvscur.SetPoint(counter, curmean, excrate);
+                excvscur.SetPointError(counter, curdiff, excerr);
+                bgvscur.SetPoint(counter, curmean, bgrate);
+                bgvscur.SetPointError(counter, curdiff, bgerr);
+                excvsth.SetPoint(counter, thmean, excrate);
+                excvsth.SetPointError(counter, thdiff, excerr);
+                bgvsth.SetPoint(counter, thmean, bgrate);
+                bgvsth.SetPointError(counter, thdiff, bgerr);
+                signif.SetPoint(counter, mjd, significance);
+                signif.SetPointError(counter, mjddiff, 0);
+                significancerate.SetPoint(counter, mjd, signifrate);
+                significancerate.SetPointError(counter, mjddiff, 0);
+                zdvstime.SetPoint(counter, mjd, zdmean);
+                zdvstime.SetPointError(counter, mjddiff, zddiff);
+                curvstime.SetPoint(counter, mjd, curmean);
+                curvstime.SetPointError(counter, mjddiff, curdiff);
+                thvstime.SetPoint(counter, mjd, thmean);
+                thvstime.SetPointError(counter, mjddiff, thdiff);
+
+                //set counter for graphs
+                counter++;
+
+                //reset variables
+                excevtssum=0;
+                bgevtssum=0;
+                sigevtssum=0;
+                ontimesum=0;
+            }
+
+            //reset for calculations
+            counter2=0;
+        }
+        delete res2;
+    }
+    delete res3;
+
+    if (excessrate.GetN()<1)
+        return 1;
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+//    if (dch)
+//        backgroundrate.SetTitle(Form("Rates vs MJD (dch: %s)", limit.Data()));
+//    else
+
+
+    Double_t x;
+    Double_t y;
+    Double_t min;
+    Double_t max;
+
+    TText txt;
+    txt.SetTextColor(kGray+2);
+    txt.SetTextSize(0.07);
+    TString text="FACT Preliminary";
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c1 = d->AddTab("Rates vs MJD", "Rates vs MJD");
+    gPad->SetGridy();
+
+    excessrate.GetPoint(1,x,y);
+    max = excessrate.GetHistogram()->GetMaximum();
+    min = excessrate.GetHistogram()->GetMinimum();
+
+    backgroundrate.SetTitle("Rates vs MJD");
+    backgroundrate.SetMarkerStyle(8);
+    backgroundrate.SetMarkerSize(0.8);
+    backgroundrate.SetLineWidth(2);
+    backgroundrate.SetMarkerColor(kBlue);
+    backgroundrate.SetLineColor(kBlue);
+    backgroundrate.GetYaxis()->SetTitle("evts/h");
+    backgroundrate.GetXaxis()->SetTitle("MJD");
+    backgroundrate.GetXaxis()->CenterTitle();
+    backgroundrate.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    backgroundrate.DrawClone("AP");
+
+    excessrate.SetMarkerStyle(8);
+    excessrate.SetMarkerSize(0.8);
+    excessrate.SetLineWidth(2);
+    excessrate.DrawClone("Psame");
+
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c2 = d->AddTab("Excess vs MJD", "Excess vs MJD");
+    gPad->SetGridy();
+    excessrate.SetTitle("Excess Rate vs MJD");
+    excessrate.SetMarkerStyle(7);
+    excessrate.SetMarkerSize(2);
+    excessrate.GetYaxis()->SetTitle("excess evts/h");
+    excessrate.GetXaxis()->SetTitle("MJD");
+    excessrate.GetXaxis()->CenterTitle();
+    excessrate.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    excessrate.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c4 = d->AddTab("Exc vs Bg", "Exc vs Bg");
+
+    backgroundrate.GetPoint(1,x,y);
+    max = excvsbg.GetHistogram()->GetMaximum();
+    min = excvsbg.GetHistogram()->GetMinimum();
+
+    excvsbg.SetTitle("Excess Rate vs Background Rate");
+    excvsbg.SetMarkerStyle(7);
+    excvsbg.SetMarkerSize(2);
+    excvsbg.GetYaxis()->SetTitle("excess evts/h");
+    excvsbg.GetXaxis()->SetTitle("background evts/h");
+    excvsbg.GetXaxis()->CenterTitle();
+    excvsbg.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    excvsbg.DrawClone("AP");
+    txt.DrawText(excvsbg.GetMean(1), max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c3 = d->AddTab("Exc vs Zd", "Exc vs Zd");
+
+    excvszd.GetPoint(1,x,y);
+    max = excvszd.GetHistogram()->GetMaximum();
+    min = excvszd.GetHistogram()->GetMinimum();
+
+    excvszd.SetTitle("Excess Rate vs Zd");
+    excvszd.SetMarkerStyle(7);
+    excvszd.SetMarkerSize(2);
+    excvszd.GetYaxis()->SetTitle("excess evts/h");
+    excvszd.GetXaxis()->SetTitle("deg");
+    excvszd.GetXaxis()->CenterTitle();
+    excvszd.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    excvszd.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c5 = d->AddTab("Bg vs Zd", "Bg vs Zd");
+
+    zdvstime.GetPoint(1,x,y);
+    max = bgvszd.GetHistogram()->GetMaximum();
+    min = bgvszd.GetHistogram()->GetMinimum();
+
+    bgvszd.SetTitle("Background Rate vs Zd");
+    bgvszd.SetMarkerStyle(7);
+    bgvszd.SetMarkerSize(2);
+    bgvszd.GetYaxis()->SetTitle("background evts/h");
+    bgvszd.GetXaxis()->SetTitle("deg");
+    bgvszd.GetXaxis()->CenterTitle();
+    bgvszd.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    bgvszd.DrawClone("AP");
+    txt.DrawText(y, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c6 = d->AddTab("Signifrate vs MJD", "Signifrate vs MJD");
+    gPad->SetGridy();
+
+    significancerate.GetPoint(1,x,y);
+    max = significancerate.GetHistogram()->GetMaximum();
+    min = significancerate.GetHistogram()->GetMinimum();
+
+    significancerate.SetTitle("Significance Rate vs MJD");
+    significancerate.SetMarkerStyle(7);
+    significancerate.SetMarkerSize(2);
+    significancerate.GetYaxis()->SetTitle("sigma/sqrt(h)");
+    significancerate.GetXaxis()->SetTitle("MJD");
+    significancerate.GetXaxis()->CenterTitle();
+    significancerate.GetYaxis()->SetRangeUser(0,max*1.1);
+    significancerate.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c7 = d->AddTab("Signif vs MJD", "Signif vs MJD");
+
+    signif.GetPoint(1,x,y);
+    max = signif.GetHistogram()->GetMaximum();
+    min = signif.GetHistogram()->GetMinimum();
+
+    signif.SetTitle("Significance vs MJD");
+    signif.SetMarkerStyle(7);
+    signif.SetMarkerSize(2);
+    signif.GetYaxis()->SetTitle("sigma");
+    signif.GetXaxis()->SetTitle("MJD");
+    signif.GetXaxis()->CenterTitle();
+    signif.GetYaxis()->SetRangeUser(0,max*1.1);
+    signif.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c8 = d->AddTab("Rate Hist", "Rate Hist");
+
+    max = bg.GetMaximum()*1.1;
+    min = bg.GetMinimum();
+
+    bg.SetLineColor(kBlue);
+    bg.GetYaxis()->SetRangeUser(0,max*1.1);
+    bg.GetXaxis()->SetTitle("evts/h");
+    bg.DrawCopy("hist");
+    exc.DrawCopy("histsame");
+    txt.DrawText(min, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c9 = d->AddTab("Zd vs Time", "Zd vs Time");
+    gPad->SetGridy();
+
+    zdvstime.GetPoint(1,x,y);
+    max = zdvstime.GetHistogram()->GetMaximum();
+    min = zdvstime.GetHistogram()->GetMinimum();
+
+    zdvstime.SetTitle("Zd vs MJD");
+    zdvstime.SetMarkerStyle(7);
+    zdvstime.SetMarkerSize(2);
+    zdvstime.GetYaxis()->SetTitle("deg");
+    zdvstime.GetXaxis()->SetTitle("MJD");
+    zdvstime.GetXaxis()->CenterTitle();
+    zdvstime.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    zdvstime.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c10 = d->AddTab("Cur vs Time", "Cur vs Time");
+    gPad->SetGridy();
+
+    curvstime.GetPoint(1,x,y);
+    max = curvstime.GetHistogram()->GetMaximum();
+    min = curvstime.GetHistogram()->GetMinimum();
+
+    curvstime.SetTitle("Currents vs MJD");
+    curvstime.SetMarkerStyle(7);
+    curvstime.SetMarkerSize(2);
+    curvstime.GetYaxis()->SetTitle("#muA");
+    curvstime.GetXaxis()->SetTitle("MJD");
+    curvstime.GetXaxis()->CenterTitle();
+    curvstime.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    curvstime.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c11 = d->AddTab("Th vs Time", "Th vs Time");
+    gPad->SetGridy();
+
+    thvstime.GetPoint(1,x,y);
+    max = thvstime.GetHistogram()->GetMaximum();
+    min = thvstime.GetHistogram()->GetMinimum();
+
+    thvstime.SetTitle("Threshold vs MJD");
+    thvstime.SetMarkerStyle(7);
+    thvstime.SetMarkerSize(2);
+    thvstime.GetYaxis()->SetTitle("DAC counts");
+    thvstime.GetXaxis()->SetTitle("MJD");
+    thvstime.GetXaxis()->CenterTitle();
+    thvstime.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    thvstime.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c12 = d->AddTab("Exc vs Cur", "Exc vs Cur");
+
+    excvscur.GetPoint(1,x,y);
+    max = excvscur.GetHistogram()->GetMaximum();
+    min = excvscur.GetHistogram()->GetMinimum();
+
+    excvscur.SetTitle("Excess Rate vs Currents");
+    excvscur.SetMarkerStyle(7);
+    excvscur.SetMarkerSize(2);
+    excvscur.GetYaxis()->SetTitle("excess evts/h");
+    excvscur.GetXaxis()->SetTitle("#muA");
+    excvscur.GetXaxis()->CenterTitle();
+    excvscur.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    excvscur.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c13 = d->AddTab("Bg vs Cur", "Bg vs Cur");
+
+    curvstime.GetPoint(1,x,y);
+    max = bgvscur.GetHistogram()->GetMaximum();
+    min = bgvscur.GetHistogram()->GetMinimum();
+
+    bgvscur.SetTitle("Background Rate vs Current");
+    bgvscur.SetMarkerStyle(7);
+    bgvscur.SetMarkerSize(2);
+    bgvscur.GetYaxis()->SetTitle("background evts/h");
+    bgvscur.GetXaxis()->SetTitle("#muA");
+    bgvscur.GetXaxis()->CenterTitle();
+    bgvscur.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    bgvscur.DrawClone("AP");
+    txt.DrawText(y, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c14 = d->AddTab("Exc vs Th", "Exc vs Th");
+
+    excvsth.GetPoint(1,x,y);
+    max = excvsth.GetHistogram()->GetMaximum();
+    min = excvsth.GetHistogram()->GetMinimum();
+
+    excvsth.SetTitle("Excess Rate vs Threshold");
+    excvsth.SetMarkerStyle(7);
+    excvsth.SetMarkerSize(2);
+    excvsth.GetYaxis()->SetTitle("excess evts/h");
+    excvsth.GetXaxis()->SetTitle("DAC counts");
+    excvsth.GetXaxis()->CenterTitle();
+    excvsth.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    excvsth.DrawClone("AP");
+    txt.DrawText(x, max, text);
+
+
+
+    gROOT->SetSelectedPad(0);
+    TCanvas &c15 = d->AddTab("Bg vs Th", "Bg vs Th");
+
+    thvstime.GetPoint(1,x,y);
+    max = bgvsth.GetHistogram()->GetMaximum();
+    min = bgvsth.GetHistogram()->GetMinimum();
+
+    bgvsth.SetTitle("Background Rate vs Threshold");
+    bgvsth.SetMarkerStyle(7);
+    bgvsth.SetMarkerSize(2);
+    bgvsth.GetYaxis()->SetTitle("background evts/h");
+    bgvsth.GetXaxis()->SetTitle("DAC counts");
+    bgvsth.GetXaxis()->CenterTitle();
+    bgvsth.GetYaxis()->SetRangeUser(min-min*0.1,max*1.1);
+    bgvsth.DrawClone("AP");
+    txt.DrawText(y, max, text);
+
+
+
+
+    d->SaveAs(outfile);
+
+    return 0;
+
+}
+
+
+
Index: branches/Mars_McMismatchStudy/fact/analysis/mc/callisto.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/mc/callisto.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/mc/callisto.C	(revision 17960)
@@ -0,0 +1,710 @@
+#include <sstream>
+#include <iostream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#if !defined(__CINT__) || defined(__MAKECINT__)
+
+#include "TH1F.h"
+#include "TFile.h"
+#include "TStyle.h"
+#include "TGraph.h"
+#include "TLine.h"
+
+#include "../mcore/DrsCalib.h"
+#include "MDrsCalibration.h"
+#include "MExtralgoSpline.h"
+#include "MSequence.h"
+#include "MStatusArray.h"
+#include "MHCamera.h"
+#include "MJob.h"
+#include "MWriteRootFile.h"
+#include "MHCamera.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+#include "MDirIter.h"
+#include "MTaskList.h"
+#include "MFDataPhrase.h"
+#include "MArrayF.h"
+#include "MBadPixelsTreat.h"
+#include "MCalibrateDrsTimes.h"
+#include "MHSectorVsTime.h"
+#include "MHCamEvent.h"
+#include "MExtractTimeAndChargeSpline.h"
+#include "MFillH.h"
+#include "MDrsCalibApply.h"
+#include "MGeomApply.h"
+#include "MContinue.h"
+#include "MRawFitsRead.h"
+#include "MReadMarsFile.h"
+#include "MEvtLoop.h"
+#include "MParList.h"
+#include "MStatusDisplay.h"
+#include "MDrsCalibrationTime.h"
+#include "MH3.h"
+#include "MGeomCamFACT.h"
+#include "MCalibrateFact.h"
+#include "MParameters.h"
+#include "MWriteAsciiFile.h"
+
+#endif
+
+using namespace std;
+
+/* Maybe you wanna use this macro like this:
+ * 
+ * 0.) ---- call root ----
+ *  root -b
+ * 
+ * 1.) ---- compile the stuff ----
+ *  .L fact/analysis/callisto_buildable_no_sequence_file.C++
+ *  <read a lot of warnings>
+ * 
+ * 2.) ---- you can call it then ---- 
+ *      Therefore you need to specify all the paths ... see below.
+ *   
+ * When you wanna call the stuff directly from the bash make sure to 
+ * escape the bracets and quotes correctly.
+ * 
+ * your can do:
+ *  root -b -q callisto_buildable_no_sequence_file.C++'("path1","path2",...)'
+ * or:
+ *  root -b -q callisto_buildable_no_sequence_file.C++(\"path1\",\"$HOME\",...)
+ * using bash enviroment variables like $HOME is not possible in the upper variant.
+ */
+
+int callisto(const TString drsfile="test300samples.drs.fits",
+             const TString pedfile="00000001.001_P_MonteCarlo000_Events.fits",
+             const TString datfile="00000003.387_D_MonteCarlo010_Events.fits",
+             TString outfile = "",
+             TString displayfile = "", TString displaytitle = "")
+{
+
+    // ======================================================
+
+    if (displaytitle.IsNull())
+        displaytitle = gSystem->BaseName(datfile);
+
+    FileStat_t fstat;
+    int rc = gSystem->GetPathInfo(outfile, fstat);
+    bool isdir = !rc || R_ISDIR(fstat.fMode);
+
+    const char *buf = gSystem->ConcatFileName(outfile, "callisto.root");
+    outfile = buf;
+    delete [] buf;
+
+    if (displayfile.IsNull())
+    {
+        displayfile = outfile;
+        displayfile.Insert(displayfile.Last('.'), "-display");
+    }
+    else
+    {
+        if (isdir && gSystem->DirName(displayfile)==TString("."))
+        {
+            buf = gSystem->ConcatFileName(outfile, displayfile);
+            displayfile = buf;
+            delete [] buf;
+        }
+    }
+
+    // ======================================================
+
+    // true:  Display correctly mapped pixels in the camera displays
+    //        but the value-vs-index plot is in software/spiral indices
+    // false: Display pixels in hardware/linear indices,
+    //        but the order is the camera display is distorted
+    bool usemap = true;
+
+    // map file to use (get that from La Palma!)
+    const char *pmap = usemap ? "TestForThomas/FACT/FACTmap111030.txt" : NULL;
+
+    Bool_t maximum = kTRUE;
+
+    //const char *lp_template    = maximum ?
+    //    "/cm/shared/apps/fact/Mars_svn_LP/template-lp-extractor-maximum.root" :
+    //    "/cm/shared/apps/fact/Mars_svn_LP/template-lp-extractor-leading-edge.root";
+
+    const char *pulse_template = "TestForThomas/FACT/template-pulse.root";
+
+    // ------------------------------------------------------
+
+    // Calib: 51 / 90 / 197 (20% TH)
+    // Data:  52 / 64 / 104 (20% TH)
+
+    // Extraction range in slices. It will always(!) contain the full range
+    // of integration
+    const int first_slice =  20; //  10ns
+    const int last_slice  = 250; // 125ns
+
+    // Note that rise and fall time mean different things whether you use IntegralFixed or IntegraRel:
+    //
+    //  IntegralFixed:
+    //    * fRiseTime: Number of slices left  from arrival time
+    //    * fFallTime: Number of slices right from arrival time
+    //  IntegralRel:
+    //    * fRiseTime: Number of slices left  from maximum time
+    //    * fFallTime: Number of slices right from maximum time
+    //
+    const int rise_time_cal = maximum ?  40 :  10; // was 13;   5ns
+    const int fall_time_cal = maximum ? 120 : 160; // was 23;  80ns
+
+    const int rise_time_dat = maximum ?  10 :   2; // was 13; was 10;   1ns
+    const int fall_time_dat = maximum ?  40 :  48; // was 23; was 40;  24ns
+
+    // Extraction type: Extract integral and half leading edge
+
+    const MExtralgoSpline::ExtractionType_t type = maximum ? (MExtralgoSpline::kIntegralRel) : (MExtralgoSpline::kIntegralFixed);
+    //const int type = MExtralgoSpline::kIntegralFixed;
+
+
+    const double heighttm   = 0.5; // IntegralAbs { 1.5pe * 9.6mV/pe } / IntegralRel { 0.5 }
+
+    Long_t max  =    0;  // All
+    Long_t max3 =  max;  // Pedestal Rndm
+    Long_t max4 =  max;  // Pedestal Ext
+
+    // ======================================================
+
+    if (pmap && gSystem->AccessPathName(pmap, kFileExists))
+    {
+        gLog << err << "ERROR - Cannot access mapping file '" << pmap << "'" << endl;
+        return 1;
+    }
+
+    gLog.Separator("Callisto");
+    gLog << all;
+    gLog << "Data File:     " << datfile << '\n';
+    gLog << "DRS calib 300: " << drsfile << endl;;
+
+    MDrsCalibration drscalib300;
+    if (!drscalib300.ReadFits(drsfile.Data())) {
+        gLog << err << "ERROR - Cannot access drscallib300 file '" << drsfile << "'" << endl;
+        return 5;
+    }
+    gLog << all;
+    gLog << "Pedestal file: " << pedfile << '\n';
+    gLog << "Output file:   " << outfile << '\n';
+    gLog << "Display file:  " << displayfile << '\n';
+    gLog << "Display title: " << displaytitle << endl;
+
+    // ------------------------------------------------------
+    MStatusArray arrt, arrp;
+
+    // TFile ft(lp_template);
+    // if (arrt.Read()<=0)
+    // {
+    //     gLog << err << "ERROR - Reading LP template from " << lp_template << endl;
+    //     return 100;
+    // }
+
+    // MHCamera *lpref = (MHCamera*)arrt.FindObjectInCanvas("ExtCalSig;avg", "MHCamera", "Cam");
+    // if (!lpref)
+    // {
+    //     gLog << err << "ERROR - LP Template not found in " << lp_template << endl;
+    //     return 101;
+    // }
+    // lpref->SetDirectory(0);
+
+    // MHCamera *gain = (MHCamera*)arrt.FindObjectInCanvas("gain", "MHCamera", "Gain");
+    // if (!gain)
+    // {
+    //     gLog << err << "ERROR - Gain not found in " << lp_template << endl;
+    //     return 101;
+    // }
+    // gain->SetDirectory(0);
+
+    TFile fp(pulse_template);
+    if (arrp.Read()<=0)
+    {
+        gLog << err << "ERROR - Reading Pulse template from " << pulse_template << endl;
+        return 102;
+    }
+
+    TH1F *hpulse = (TH1F*)arrp.FindObjectInCanvas("hPixelEdgeMean0_0", "TH1F", "cgpPixelPulses0");
+    if (!hpulse)
+    {
+        gLog << err << "ERROR - Pulse Template not found in " << pulse_template << endl;
+        return 103;
+    }
+    hpulse->SetDirectory(0);
+    // ======================================================
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MBadPixelsCam badpixels;
+    badpixels.InitSize(1440);
+    /*
+    badpixels[ 424].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 583].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 830].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[ 923].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[1208].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    badpixels[1399].SetUnsuitable(MBadPixelsPix::kUnsuitable);
+    */
+    //  Twin pixel
+    //     113
+    //     115
+    //     354
+    //     423
+    //    1195
+    //    1393
+
+    MDrsCalibrationTime timecam;
+
+    // Plot the trigger pattern rates vs. run-number
+    MH3 hrate("MRawRunHeader.GetFileID", "MRawEvtHeader.GetTriggerID&0xff00");
+    hrate.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hrate.SetName("Rate");
+    hrate.SetTitle("Event rate [Hz];File Id;Trigger Type;");
+    hrate.InitLabels(MH3::kLabelsXY);
+    hrate.DefineLabelY(    0, "Data"); // What if TriggerID==0 already???
+    hrate.DefineLabelY(0x100, "Cal");
+    hrate.DefineLabelY(0x400, "Ped");
+    // hrate.DefaultLabelY("ERROR");
+    gStyle->SetOptFit(kTRUE);
+
+
+    // ========================= Result ==================================
+
+    //~ Double_t avgS = evt1f.GetHist()->GetMean();
+    //~ Double_t medS = evt1f.GetHist()->GetMedian();
+    //~ Double_t rmsS = evt1f.GetHist()->GetRMS();
+    //~ Double_t maxS = evt1f.GetHist()->GetMaximum();
+
+    MArrayF der1(hpulse->GetNbinsX());
+    MArrayF der2(hpulse->GetNbinsX());
+
+    MExtralgoSpline spline(hpulse->GetArray()+1, hpulse->GetNbinsX(),
+                           der1.GetArray(), der2.GetArray());
+    spline.SetRiseFallTime(rise_time_dat, fall_time_dat);
+    spline.SetExtractionType(type);
+    spline.SetHeightTm(heighttm);
+
+    spline.Extract(hpulse->GetMaximumBin()-1);
+
+    // The pulser signal is most probably around 400mV/9.5mV
+    // IntegraFixed 2/48 corresponds to roughly 215mV*50slices
+    Double_t scale = 1./spline.GetSignal();
+
+    MArrayD calib(1440);
+    for (int i=0; i<1440; i++)
+        calib[i] =1.;
+
+    gROOT->SetSelectedPad(0);
+    d->AddTab("PulseTemp");
+    gPad->SetGrid();
+    hpulse->SetNameTitle("Pulse", "Single p.e. pulse template");
+    hpulse->SetDirectory(0);
+    hpulse->SetLineColor(kBlack);
+    hpulse->DrawCopy();
+
+    TAxis *ax = hpulse->GetXaxis();
+
+    Double_t w = hpulse->GetBinWidth(1);
+    Double_t T = w*(spline.GetTime()+0.5)       +ax->GetXmin();
+    //~ Double_t H = w*(hpulse->GetMaximumBin()+0.5)+ax->GetXmin();
+
+    TLine line;
+    line.SetLineColor(kRed);
+    line.DrawLine(T-rise_time_dat*w, spline.GetHeight(),
+                  T+fall_time_dat*w, spline.GetHeight());
+    line.DrawLine(T, spline.GetHeight()/4, T, 3*spline.GetHeight()/4);
+    line.DrawLine(T-rise_time_dat*w, 0,
+                  T-rise_time_dat*w, spline.GetHeight());
+    line.DrawLine(T+fall_time_dat*w, 0,
+                  T+fall_time_dat*w, spline.GetHeight());
+
+    TGraph gg;
+    for (int ix=1; ix<=hpulse->GetNbinsX(); ix++)
+        for (int i=0; i<10; i++)
+        {
+            Double_t x = hpulse->GetBinLowEdge(ix)+i*hpulse->GetBinWidth(ix)/10.;
+            gg.SetPoint(gg.GetN(), x+w/2, spline.EvalAt(ix-1+i/10.));
+        }
+
+    gg.SetLineColor(kBlue);
+    gg.SetMarkerColor(kBlue);
+    gg.SetMarkerStyle(kFullDotMedium);
+    gg.DrawClone("L");
+
+    gROOT->SetSelectedPad(0);
+    d->AddTab("CalConst");
+    MGeomCamFACT fact;
+    MHCamera hcalco(fact);
+    hcalco.SetName("CalConst");
+    hcalco.SetTitle(Form("Relative calibration constant [%.0f/pe]", 1./scale));
+    hcalco.SetCamContent(calib);
+    hcalco.SetAllUsed();
+    //hcalco.Scale(scale);
+    hcalco.DrawCopy();
+
+    // ======================================================
+
+    gLog << endl;
+    gLog.Separator("Extracting random pedestal");
+
+    MTaskList tlist3;
+
+    MParList plist3;
+    plist3.AddToList(&tlist3);
+    plist3.AddToList(&drscalib300);
+    plist3.AddToList(&badpixels);
+    plist3.AddToList(&timecam);
+
+    MEvtLoop loop3("DetermineRndmPed");
+    loop3.SetDisplay(d);
+    loop3.SetParList(&plist3);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read3;
+    read3.LoadMap(pmap);
+    read3.AddFile(pedfile);
+
+    MFillH fill3a(&hrate);
+
+    MContinue cont3("(MRawEvtHeader.GetTriggerID&0xff00)!=0x400", "SelectPed");
+
+    MGeomApply apply3;
+
+    MDrsCalibApply drsapply3;
+
+    //---
+
+    MExtractTimeAndChargeSpline extractor3;
+    extractor3.SetRange(first_slice, last_slice);
+    extractor3.SetRiseTimeHiGain(rise_time_dat);
+    extractor3.SetFallTimeHiGain(fall_time_dat);
+    extractor3.SetHeightTm(heighttm);
+    extractor3.SetChargeType(type);
+    extractor3.SetSaturationLimit(600000);
+    extractor3.SetNoiseCalculation(kTRUE);
+
+//    MHCamEvent evt2a(0, "PedRdm", "Extracted Pedestal Signal;;S");
+
+//    MFillH fill2a(&evt2a, "MExtractedSignalCam", "FillPedRndm");
+
+    // Use this for data, but not for calibration events
+//    evt2a.SetErrorSpread(kFALSE);
+
+    /*
+     MCalibrateData conv3;
+     conv3.SetCalibrationMode(MCalibrateData::kNone);
+     conv3.SetPedestalFlag(MCalibrateData::kNo);
+     conv3.SetCalibConvMinLimit(0);
+     conv3.SetCalibConvMaxLimit(10000);
+     conv3.SetScaleFactor(scale);
+     */
+
+    MCalibrateFact conv3;
+    conv3.SetScale(scale);
+    conv3.SetCalibConst(calib);
+
+    MBadPixelsTreat treat3;
+    treat3.SetProcessPedestalRun(kFALSE);
+    treat3.SetProcessPedestalEvt(kFALSE);
+    treat3.SetProcessTimes(kFALSE);
+
+    MHCamEvent evt3b(0, "PedRdm","Interpolated random pedestal;;Signal [~phe]");
+    //evt2b.SetErrorSpread(kFALSE);
+
+    MFillH fill3b(&evt3b, "MSignalCam", "FillPedRdm");
+    fill3b.SetDrawOption("gaus");
+
+    // ------------------ Setup eventloop and run analysis ---------------
+
+    tlist3.AddToList(&read3);
+    tlist3.AddToList(&apply3);
+    tlist3.AddToList(&drsapply3);
+    tlist3.AddToList(&cont3);
+    tlist3.AddToList(&extractor3);
+//    tlist3.AddToList(&fill3a);
+    tlist3.AddToList(&conv3);
+    tlist3.AddToList(&treat3);
+    tlist3.AddToList(&fill3b);
+
+    if (!loop3.Eventloop(max3))
+        return 14;
+
+    if (!loop3.GetDisplay())
+        return 15;
+
+    // ======================================================
+
+    gLog << endl;
+    gLog.Separator("Extracting pedestal");
+
+    MTaskList tlist4;
+
+    MParList plist4;
+    plist4.AddToList(&tlist4);
+    plist4.AddToList(&drscalib300);
+    plist4.AddToList(&badpixels);
+    plist4.AddToList(&timecam);
+
+    MEvtLoop loop4("DetermineExtractedPed");
+    loop4.SetDisplay(d);
+    loop4.SetParList(&plist4);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read4;
+    read4.LoadMap(pmap);
+    read4.AddFile(pedfile);
+
+    MContinue cont4("(MRawEvtHeader.GetTriggerID&0xff00)!=0x400", "SelectPed");
+
+    MGeomApply apply4;
+
+    MDrsCalibApply drsapply4;
+
+    MExtractTimeAndChargeSpline extractor4;
+    extractor4.SetRange(first_slice, last_slice);
+    extractor4.SetRiseTimeHiGain(rise_time_dat);
+    extractor4.SetFallTimeHiGain(fall_time_dat);
+    extractor4.SetHeightTm(heighttm);
+    extractor4.SetChargeType(type);
+    extractor4.SetSaturationLimit(600000);
+    extractor4.SetNoiseCalculation(kFALSE);
+
+    //    MHCamEvent evt3a(0, "PedExt", "Extracted Pedestal Signal;;S");
+
+    //    MFillH fill3a(&evt3a, "MExtractedSignalCam", "FillPedExt");
+
+    // Use this for data, but not for calibration events
+//    evt3a.SetErrorSpread(kFALSE);
+/*
+    MCalibrateData conv4;
+    conv4.SetCalibrationMode(MCalibrateData::kNone);
+    conv4.SetPedestalFlag(MCalibrateData::kNo);
+    conv4.SetCalibConvMinLimit(0);
+    conv4.SetCalibConvMaxLimit(10000);
+    conv4.SetScaleFactor(scale);
+*/
+    MCalibrateFact conv4;
+    conv4.SetScale(scale);
+    conv4.SetCalibConst(calib);
+
+    MBadPixelsTreat treat4;
+    treat4.SetProcessPedestalRun(kFALSE);
+    treat4.SetProcessPedestalEvt(kFALSE);
+
+    MHCamEvent evt4b(0, "PedExt","Interpolated extracted pedestal;;Signal [~phe]");
+    //evt4b.SetErrorSpread(kFALSE);
+
+    MFillH fill4b(&evt4b, "MSignalCam", "FillPedExt");
+    fill4b.SetDrawOption("gaus");
+
+    // ------------------ Setup eventloop and run analysis ---------------
+
+    tlist4.AddToList(&read4);
+    tlist4.AddToList(&apply4);
+    tlist4.AddToList(&drsapply4);
+    tlist4.AddToList(&cont4);
+    tlist4.AddToList(&extractor4);
+//    tlist4.AddToList(&fill4a);
+    tlist4.AddToList(&conv4);
+    tlist4.AddToList(&treat4);
+    tlist4.AddToList(&fill4b);
+
+    if (!loop4.Eventloop(max4))
+        return 15;
+
+    if (!loop4.GetDisplay())
+        return 16;
+
+    // ===================================================================
+
+    gLog << endl;
+    gLog.Separator("Extracting and calibration data");
+
+    MTaskList tlist5;
+
+    MParList plist5;
+    plist5.AddToList(&tlist5);
+    plist5.AddToList(&drscalib300);
+    plist5.AddToList(&badpixels);
+    plist5.AddToList(&timecam);
+
+    MEvtLoop loop5("CalibratingData");
+    loop5.SetDisplay(d);
+    loop5.SetParList(&plist5);
+
+    // ------------------ Setup the tasks ---------------
+
+    MRawFitsRead read5a;
+    MReadMarsFile read5b("Events");
+    read5a.LoadMap(pmap);
+    read5a.AddFile(datfile);
+    read5b.DisableAutoScheme();
+    read5b.AddFile(datfile);
+
+    MRead &read5 = datfile.EndsWith(".root") ? static_cast<MRead&>(read5b) : static_cast<MRead&>(read5a);
+
+    MFillH fill5a(&hrate);
+
+    MGeomApply apply5;
+
+    MDrsCalibApply drsapply5;
+
+    MFDataPhrase filterdat("(MRawEvtHeader.GetTriggerID&0xff00)==0",     "SelectDat");
+    MFDataPhrase filtercal("(MRawEvtHeader.GetTriggerID&0xff00)==0x100", "SelectCal");
+    MFDataPhrase filterped("(MRawEvtHeader.GetTriggerID&0xff00)==0x400", "SelectPed");
+    MFDataPhrase filterncl("(MRawEvtHeader.GetTriggerID&0xff00)!=0x100", "SelectNonCal");
+
+    //MContinue cont4("MRawEvtHeader.GetTriggerID!=4", "SelectData");
+
+    // ---
+
+    MExtractTimeAndChargeSpline extractor5dat;
+    extractor5dat.SetRange(first_slice, last_slice);
+    extractor5dat.SetRiseTimeHiGain(rise_time_dat);
+    extractor5dat.SetFallTimeHiGain(fall_time_dat);
+    extractor5dat.SetHeightTm(heighttm);
+    extractor5dat.SetChargeType(type);
+    extractor5dat.SetSaturationLimit(600000);
+    extractor5dat.SetNoiseCalculation(kFALSE);
+
+    MExtractTimeAndChargeSpline extractor5cal;
+    extractor5cal.SetRange(first_slice, last_slice);
+    extractor5cal.SetRiseTimeHiGain(rise_time_cal);
+    extractor5cal.SetFallTimeHiGain(fall_time_cal);
+    extractor5cal.SetHeightTm(heighttm);
+    extractor5cal.SetChargeType(type);
+    extractor5cal.SetSaturationLimit(600000);
+    extractor5cal.SetNoiseCalculation(kFALSE);
+
+    MExtractTimeAndChargeSpline extractor5tm("ExtractTM");
+    extractor5tm.SetRange(last_slice, 294);
+    extractor5tm.SetRiseTimeHiGain(1);
+    extractor5tm.SetFallTimeHiGain(1);
+    extractor5tm.SetHeightTm(0.5);
+    extractor5tm.SetChargeType(MExtralgoSpline::kAmplitudeRel);
+    extractor5tm.SetSaturationLimit(600000);
+    extractor5tm.SetNoiseCalculation(kFALSE);
+    extractor5tm.SetNameSignalCam("TimeMarkerAmplitude");
+    extractor5tm.SetNameTimeCam("TimeMarkerTime");
+
+    extractor5dat.SetFilter(&filterncl);
+    extractor5cal.SetFilter(&filtercal);
+    //extractor4tm.SetFilter(&filtercal);
+
+    // ---
+/*
+    MCalibrateData conv5;
+    conv5.SetCalibrationMode(MCalibrateData::kNone);
+    conv5.SetPedestalFlag(MCalibrateData::kNo);
+    conv5.SetCalibConvMinLimit(0);
+    conv5.SetCalibConvMaxLimit(10000);
+    conv5.SetScaleFactor(scale);
+*/
+    MCalibrateFact conv5;
+    conv5.SetScale(scale);
+    conv5.SetCalibConst(calib);
+
+    MCalibrateDrsTimes calctm5;
+    calctm5.SetNameUncalibrated("UncalibratedTimes");
+
+    MCalibrateDrsTimes calctm5tm("CalibrateTimeMarker");
+    calctm5tm.SetNameArrivalTime("TimeMarkerTime");
+    calctm5tm.SetNameUncalibrated("UncalTimeMarker");
+    calctm5tm.SetNameCalibrated("TimeMarker");
+    calctm5tm.SetTimeMarker();
+    //calctm4tm.SetFilter(&filtercal);
+
+    MBadPixelsTreat treat5;
+    treat5.SetProcessPedestalRun(kFALSE);
+    treat5.SetProcessPedestalEvt(kFALSE);
+
+    MHCamEvent evt5b(0, "ExtSig",   "Extracted signal;;S [mV·sl]");
+    MHCamEvent evt5c(0, "CalSig",   "Calibrated and interpolated signal;;S [~phe]");
+    MHCamEvent evt5d(4, "ExtSigTm", "Extracted time;;T [sl]");
+    MHCamEvent evt5e(6, "CalSigTm", "Calibrated and interpolated time;;T [ns]");
+
+    MFillH fill5b(&evt5b, "MExtractedSignalCam", "FillExtSig");
+    MFillH fill5c(&evt5c, "MSignalCam",          "FillCalSig");
+    MFillH fill5d(&evt5d, "MArrivalTimeCam",     "FillExtTm");
+    MFillH fill5e(&evt5e, "MSignalCam",          "FillCalTm");
+
+    fill5c.SetDrawOption("gaus");
+    fill5d.SetDrawOption("gaus");
+    fill5e.SetDrawOption("gaus");
+
+    /*
+    fill4b.SetFilter(&filterdat);
+    fill4c.SetFilter(&filterdat);
+    fill4d.SetFilter(&filterdat);
+    fill4e.SetFilter(&filterdat);
+    */
+
+    //MFSoftwareTrigger swtrig;
+    //MContinue contsw(&swtrig, "FilterSwTrigger", "Software trigger");
+    //contsw.SetInverted();
+
+    // The second rule is for the case reading raw-files!
+    
+    MWriteRootFile write5(outfile, "RECREATE", "Calibrated Data", 2);
+    write5.AddContainer("MRawRunHeader",       "RunHeaders");
+    write5.AddContainer("MGeomCam",            "RunHeaders");
+    write5.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE);
+    write5.AddContainer("MCorsikaRunHeader",   "RunHeaders", kFALSE);
+    write5.AddContainer("MMcRunHeader",        "RunHeaders", kFALSE);
+
+    // Common events
+    write5.AddContainer("MCorsikaEvtHeader",   "Events", kFALSE);
+    write5.AddContainer("MMcEvt",              "Events", kFALSE);
+    write5.AddContainer("IncidentAngle",       "Events", kFALSE);
+    write5.AddContainer("MPointingPos",        "Events", kFALSE);
+    write5.AddContainer("MSignalCam",          "Events");
+    write5.AddContainer("MTime",               "Events", kFALSE);
+    write5.AddContainer("MRawEvtHeader",       "Events");
+    //write.AddContainer("MTriggerPattern", "Events");
+    
+    // ------------------ Setup histograms and fill tasks ----------------
+
+    MContinue test;
+    test.SetFilter(&filterncl);
+
+    MTaskList tlist5tm;
+    tlist5tm.AddToList(&extractor5tm);
+    tlist5tm.AddToList(&calctm5tm);
+    tlist5tm.SetFilter(&filtercal);
+
+    MTaskList tlist5dat;
+    tlist5dat.AddToList(&fill5b);
+    tlist5dat.AddToList(&fill5c);
+    tlist5dat.AddToList(&fill5d);
+    tlist5dat.AddToList(&fill5e);
+    tlist5dat.SetFilter(&filterdat);
+
+    tlist5.AddToList(&read5);
+    tlist5.AddToList(&apply5);
+    tlist5.AddToList(&drsapply5);
+    tlist5.AddToList(&filterncl);
+    //tlist5.AddToList(&test);
+    tlist5.AddToList(&filterdat);
+    tlist5.AddToList(&filtercal);
+    tlist5.AddToList(&filterped);
+    tlist5.AddToList(&fill5a);
+    tlist5.AddToList(&extractor5dat);
+    tlist5.AddToList(&extractor5cal);
+    tlist5.AddToList(&calctm5);
+    tlist5.AddToList(&tlist5tm);
+    tlist5.AddToList(&conv5);
+    tlist5.AddToList(&treat5);
+    tlist5.AddToList(&tlist5dat);
+    tlist5.AddToList(&write5);
+
+    if (!loop5.Eventloop(max4))
+        return 18;
+
+    if (!loop5.GetDisplay())
+        return 19;
+
+    d->SetTitle(displaytitle, kFALSE);
+    d->SaveAs(displayfile);
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/mc/ganymed.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/mc/ganymed.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/mc/ganymed.C	(revision 17960)
@@ -0,0 +1,525 @@
+void SetupWriter(MWriteRootFile *write, const char *name, Bool_t ismc) const
+{
+    if (!write)
+        return;
+
+    write->SetName(name);
+    write->AddContainer("MHillas",        "Events");
+    write->AddContainer("MHillasSrc",     "Events");
+    write->AddContainer("MHillasExt",     "Events");
+    write->AddContainer("MPointingPos",   "Events");
+    write->AddContainer("MHillasSrcAnti", "Events", kFALSE);
+    write->AddContainer("MImagePar",      "Events", kFALSE);
+    write->AddContainer("MNewImagePar",   "Events", kFALSE);
+    write->AddContainer("MNewImagePar2",  "Events", kFALSE);
+    write->AddContainer("Hadronness",     "Events", kFALSE);
+    write->AddContainer("MSrcPosCam",     "Events", kFALSE);
+    write->AddContainer("MSrcPosAnti",    "Events", kFALSE);
+    write->AddContainer("ThetaSquared",   "Events", kFALSE);
+    write->AddContainer("OpticalAxis",    "Events", kFALSE);
+    write->AddContainer("Disp",           "Events", kFALSE);
+    write->AddContainer("Ghostbuster",    "Events", kFALSE);
+    write->AddContainer("MEnergyEst",     "Events", kFALSE);
+    write->AddContainer("MTime",          "Events", kFALSE);
+    write->AddContainer("MMcEvt",         "Events", kFALSE);
+    write->AddContainer("MEnergyEst",     "Events", kFALSE);
+    write->AddContainer("DataType",       "Events");
+    write->AddContainer("Weight",         "Events");
+    write->AddContainer("FileId",         "Events");
+    write->AddContainer("EvtNumber",      "Events");
+
+    write->AddContainer("MMcRunHeader",         "RunHeaders", kFALSE);
+    write->AddContainer("MMcCorsikaRunHeader",  "RunHeaders", kFALSE);
+    write->AddContainer("MCorsikaRunHeader",    "RunHeaders", kFALSE);
+
+    //if (ismc)
+    //    write->AddCopySource("OriginalMC");
+}
+
+int ganymed(const char *dataset, const char *outfile, Float_t ra, Float_t dec, Bool_t ismc=false)
+{
+    MDirIter files;
+    if (files.ReadList(dataset)<=0)
+        return 2;
+    files.Sort();
+
+    // =============================================================
+
+    // Crab (05h34'32" 22d00'52")
+    MPointingPos source("MSourcePos");
+    //source.SetSkyPosition(5.5755, 22.0144); // ra[h], dec[deg]
+    //source.SetSkyPosition(12.356089, 30.176897); // ra[h], dec[deg]//1218
+    //source.SetSkyPosition(16.897867,39.760201);// mrk501
+    //source.SetSkyPosition(11.0742, 38.2089); // ra[h], dec[deg]//mrk421
+
+    if (ismc)
+        source.SetLocalPosition(ra, dec); // RA is ZD, DEC, is AZ!!!!
+    else
+        source.SetSkyPosition(ra, dec); // ra[h], dec[deg]//mrk421
+
+    UInt_t fNumOffSourcePos = 5;
+
+    // =============================================================
+
+    // FIXME: If fPathIn read cuts and energy estimator from file!
+    MContinue contq("MImagePar.fNumIslands>3.5"
+                    "|| MNewImagePar.fNumUsedPixels<5.5"
+                    "|| MNewImagePar.fLeakage1>0.1",
+                    "CutQ");
+
+    MContinue cont0("MHillas.fSize<0"
+                    "|| MHillasExt.fSlopeSpreadWeighted>0.68"
+                    "|| MHillasExt.fSlopeSpreadWeighted<0.18"
+                    "|| log10(MHillas.GetArea*MGeomCam.fConvMm2Deg^2)>(log10(MHillas.fSize)-2)*1.1-1.55"
+                    "|| MNewImagePar.fConcCore < 0.13"
+                    "|| MNewImagePar.fConcCOG  < 0.15"
+                    , "Cut0");
+
+    // Cuts before plots
+    MContinue cont2("0"
+                    "|| MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)*MGeomCam.fConvMm2Deg<-0.07"
+                    "|| log10(MNewImagePar.fConc1)<-log10(MHillas.fSize)*0.57+0.13"
+                    //"|| log10(MNewImagePar.fConc1)>-log10(MHillas.fSize)*0.57+0.5"
+                    //"|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg>log10(MHillas.fSize)*0.42+0.29"
+                    "|| MHillas.GetArea*MGeomCam.fConvMm2Deg^2<0.01"
+                    "|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg>log10(MHillas.fSize)*0.5+0.095"
+                    "|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg<0.4"
+                    "|| MHillasSrc.fDist*MGeomCam.fConvMm2Deg>1.2",
+                    "Cut2");
+
+    TArrayD param(12);
+    // Parametrization of Disp
+    param[0]  =  1.15136;     // constant
+    param[8]  =  0.0681437;   // slope
+    param[9]  =  2.62932;     // leak
+    param[10] =  1.51279;     // size-offset
+    param[11] =  0.0507821;   // size-slope
+    // Parametrization for sign of disp (m3long, slope)
+    param[5]  = -0.07;
+    param[6]  =  7.2;
+    param[7]  =  0.5;
+    // ThetaSq-Cut
+    param[1]  =  0.11;  // 0.215
+    // Area-Cut
+    param[2]  =  0.215468;
+    param[3]  =  5.63973;
+    param[4]  =  0.0836169;
+
+    // --------------------------------------------------------------------------------
+
+    // Setup fitter and histograms
+    MAlphaFitter fit;
+    fit.SetBackgroundFitMin(0.09);
+    fit.SetBackgroundFitMax(0.25);
+    fit.SetPolynomOrder(1);
+    fit.SetSignalFunction(MAlphaFitter::kThetaSq);
+    fit.SetScaleUser(1./fNumOffSourcePos); // includes fit.SetScaleMode(MAlphaFitter::kUserScale);
+
+    // --------------------------------------------------------------------------------
+
+    MBinning bins3( 67, -0.005, 0.665, "BinningTheta",  "asin");
+    MBinning binsD( 25,   0,      2.5, "BinningDist");
+    MBinning binsC( 25,   0,      2.5, "BinningDistC");
+    MBinning binsR( 60,   0,      300, "BinningRate");
+
+    // --------------------------------------------------------------------------------
+
+    MParList plist;
+    plist.AddToList(&source);
+    plist.AddToList(&fit);
+
+    // Initialize default binnings
+    plist.AddToList(&bins3);
+    plist.AddToList(&binsD);
+    plist.AddToList(&binsC);
+    plist.AddToList(&binsR);
+
+    MParameterI par("DataType");
+    MParameterD weight("Weight");
+    plist.AddToList(&par);
+    plist.AddToList(&weight);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // La Palma Magic1
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    // --------------------------------------------------------------------------------
+
+    MParameterD scale;
+    scale.SetVal(1./fNumOffSourcePos);
+
+    MHThetaSq *halphaoff = plist.FindCreateObj("MHThetaSq", "HistOff");
+    halphaoff->ForceUsingSize();
+
+    MFillH falpha(halphaoff, "", "FillHist");
+    MFillH fenergy1("HistEOff [MHThetaSq]", "", "FillHistE");
+
+    MFMagicCuts cuts;
+    cuts.SetHadronnessCut(MFMagicCuts::kNoCut);
+    cuts.SetVariables(param);
+
+    // Cuts before thetasq
+    MContinue cont1(&cuts, "Cut1");
+
+    // Energy estimation
+    MEnergyEstimate energyest;
+    energyest.SetRule("MHillas.fSize^0.815*pow(10, 0.0199*(MHillasSrc.fDist*1.17e-2 - (-6.95))^2*(MHillasSrc.fDist*1.17e-2>(-6.95)) + 0.5997 *(MHillasSrc.fDist*1.17e-2 - 0.7568)^2 * (MHillasSrc.fDist*1.17e-2>0.7568) )");
+
+    // Cuts before writing
+    MContinue cont3("",    "Cut3");
+    contq.SetAllowEmpty();
+    cont0.SetAllowEmpty();
+    cont1.SetAllowEmpty();
+    cont2.SetAllowEmpty();
+    cont3.SetAllowEmpty();
+
+    cont1.SetInverted();
+
+    // Filter for VsSize
+    MFDataPhrase ftheta("ThetaSquared.fVal < ThetaSquaredCut.fVal", "CutT");
+
+    // ------------- Loop Off Data --------------------
+    MRead *readoffdata = NULL;
+    if (ismc)
+    {
+        MReadMarsFile *read = new MReadMarsFile("Events");
+        read->DisableAutoScheme();
+        readoffdata = read;
+    }
+    else
+    {
+        MReadReports *read = new MReadReports;
+        read->AddTree("Events", "MTime.", MReadReports::kMaster);
+        read->AddTree("Drive",MReadReports::kRequired);
+        read->AddTree("Rates",MReadReports::kRequired);
+        readoffdata = read;
+    }
+
+    readoffdata->AddFiles(files);
+
+    TString fname0 = Form("%s-summary.root",  outfile);
+    TString fname1 = Form("%s-analysis.root", outfile);
+
+    MWriteRootFile dummy0(fname0.Data(), "RECREATE");
+    MWriteRootFile dummy1(fname1.Data(), "RECREATE");
+
+    MWriteRootFile *write0 = &dummy0;
+    MWriteRootFile *write1 = &dummy1;
+    SetupWriter(write0, "WriteAfterCut0", ismc);
+    SetupWriter(write1, "WriteAfterCut3", ismc);
+
+    MWriteRootFile write2(fname1.Data(), "RECRATE");
+    write2.AddContainer("MReportRates", "Rates");
+    write2.AddContainer("MTimeRates",   "Rates");
+
+    MParameterCalc setevtnum("MRawEvtHeader.fDAQEvtNumber", "SetEvtNumber");
+    setevtnum.SetNameParameter("EvtNumber");
+
+    MParameterCalc setrunnum("MRawRunHeader.GetFileID", "SetFileId");
+    setrunnum.SetNameParameter("FileId");
+
+    MFillH fill1a("MHHillasOffPre  [MHHillas]",      "MHillas",      "FillHillasPre");
+    MFillH fill2a("MHHillasOffPost [MHHillas]",      "MHillas",      "FillHillasPost");
+    MFillH fill3a("MHVsSizeOffPost [MHVsSize]",      "MHillasSrc",   "FillVsSizePost");
+    MFillH fill3c("MHVsSizeOffTheta [MHVsSize]",     "MHillasSrc",   "FillVsSizeTheta");
+    MFillH fill4a("MHHilExtOffPost [MHHillasExt]",   "MHillasSrc",   "FillHilExtPost");
+    MFillH fill5a("MHHilSrcOffPost [MHHillasSrc]",   "MHillasSrc",   "FillHilSrcPost");
+    MFillH fill6a("MHImgParOffPost [MHImagePar]",    "MImagePar",    "FillImgParPost");
+    MFillH fill7a("MHNewParOffPost [MHNewImagePar]", "MNewImagePar", "FillNewParPost");
+    //MFillH fill9a("MHEffOffTime    [MHEffectiveOnTime]", "MTime",        "FillEffOnTime");
+    fill1a.SetNameTab("PreCut");
+    fill2a.SetNameTab("PostCut");
+    fill3a.SetNameTab("VsSize");
+    fill3c.SetNameTab("CutT");
+    fill4a.SetNameTab("HilExt");
+    fill5a.SetNameTab("HilSrc");
+    fill6a.SetNameTab("ImgPar");
+    fill7a.SetNameTab("NewPar");
+    //fill9a.SetNameTab("EffOffT");
+
+    fill3c.SetFilter(&ftheta);
+
+    //MFDataMember fbin("Bin.fVal", '>', 0);
+    //fill9a.SetFilter(&fbin);
+
+    MTaskList tlist2;
+    tlist2.SetNumPasses(fNumOffSourcePos);
+    fill2a.SetWeight(&scale);
+    fill3a.SetWeight(&scale);
+    fill3c.SetWeight(&scale);
+    fill4a.SetWeight(&scale);
+    fill5a.SetWeight(&scale);
+    fill6a.SetWeight(&scale);
+    fill7a.SetWeight(&scale);
+
+    // How to get source position from off- and on-data?
+    MSrcPosCalc scalc;
+    scalc.SetMode(MSrcPosCalc::kWobble);
+    scalc.SetCallback(&tlist2);
+
+    MSrcPosCorrect scor;
+
+    MHillasCalc hcalc;
+    MHillasCalc hcalc2("MHillasCalcAnti");
+    hcalc.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetNameHillasSrc("MHillasSrcAnti");
+    hcalc2.SetNameSrcPosCam("MSrcPosAnti");
+
+    MSrcPosRndm srcrndm;
+
+    tlist2.AddToList(&scalc);
+    //tlist2.AddToList(&scor);
+    tlist2.AddToList(&srcrndm);
+    tlist2.AddToList(&hcalc);
+    tlist2.AddToList(&hcalc2);
+    tlist2.AddToList(&setrunnum);
+    tlist2.AddToList(&setevtnum);
+    tlist2.AddToList(&cuts);
+    tlist2.AddToList(&energyest);
+    tlist2.AddToList(write0);
+    tlist2.AddToList(&cont0);  // Post/Pre shown cuts
+    tlist2.AddToList(&cont1);  // Calculate ThetaSq
+    tlist2.AddToList(&fill2a);
+    tlist2.AddToList(&ftheta); // Calculate theta Cut
+    if (!ismc)
+    {
+        tlist2.AddToList(&falpha);
+        tlist2.AddToList(&fenergy1);
+    }
+    tlist2.AddToList(&fill3c); // With theta cut
+    tlist2.AddToList(&cont2);  
+    tlist2.AddToList(&fill3a);
+    tlist2.AddToList(&fill4a);
+    tlist2.AddToList(&fill5a);
+    tlist2.AddToList(&fill6a);
+    tlist2.AddToList(&fill7a);
+    tlist2.AddToList(&cont3);
+    tlist2.AddToList(write1);
+
+    MPointingPosCalc pcalc;
+    MPointingDevCalc devcalc;
+
+    tlist.AddToList(readoffdata);
+    if (!ismc)
+        tlist.AddToList(&pcalc, "Drive");
+    tlist.AddToList(&contq,  "Events");
+    tlist.AddToList(&fill1a, "Events");
+    tlist.AddToList(&tlist2, "Events");
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    par.SetVal(0);
+    weight.SetVal(-1./fNumOffSourcePos);
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop("Off");
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+        return 2;
+
+    if (!evtloop.GetDisplay())
+        return 2;
+
+    // ------------- Loop On Data --------------------
+    MRead *readondata = NULL;
+    if (ismc)
+    {
+        MReadMarsFile *read = new MReadMarsFile("Events");
+        read->DisableAutoScheme();
+        readondata = read;
+    }
+    else
+    {
+        MReadReports *read = new MReadReports;
+        read->AddTree("Events", "MTime.", MReadReports::kMaster);
+        read->AddTree("Drive",        MReadReports::kRequired);
+        read->AddTree("Rates",        MReadReports::kRequired);
+        read->AddTree("Humidity",     MReadReports::kRequired);
+        read->AddTree("Temperatures", MReadReports::kRequired);
+        readondata = read;
+    }
+    readondata->AddFiles(files);
+
+    scalc.SetMode(MSrcPosCalc::kDefault);
+    scalc.SetNumRandomOffPositions(fNumOffSourcePos);
+
+    MFillH fill1b("MHHillasOnPre  [MHHillas]",      "MHillas",      "FillHillasPre");
+    MFillH fill2b("MHHillasOnPost [MHHillas]",      "MHillas",      "FillHillasPost");
+    MFillH fill3b("MHVsSizeOnPost [MHVsSize]",      "MHillasSrc",   "FillVsSizePost");
+    MFillH fill3d("MHVsSizeOnTheta [MHVsSize]",     "MHillasSrc",   "FillVsSizeTheta");
+    MFillH fill4b("MHHilExtOnPost [MHHillasExt]",   "MHillasSrc",   "FillHilExtPost");
+    MFillH fill5b("MHHilSrcOnPost [MHHillasSrc]",   "MHillasSrc",   "FillHilSrcPost");
+    MFillH fill6b("MHImgParOnPost [MHImagePar]",    "MImagePar",    "FillImgParPost");
+    MFillH fill7b("MHNewParOnPost [MHNewImagePar]", "MNewImagePar", "FillNewParPost");
+    //MFillH fill9b("MHEffOnTime    [MHEffectiveOnTime]", "MTime",        "FillEffOnTime");
+    fill1b.SetNameTab("PreCut");
+    fill2b.SetNameTab("PostCut");
+    fill3b.SetNameTab("VsSize");
+    fill3d.SetNameTab("CutT");
+    fill4b.SetNameTab("HilExt");
+    fill5b.SetNameTab("HilSrc");
+    fill6b.SetNameTab("ImgPar");
+    fill7b.SetNameTab("NewPar");
+    //fill9b.SetNameTab("EffOnT");
+    fill1b.SetDrawOption("same");
+    fill2b.SetDrawOption("same");
+    fill3b.SetDrawOption("same");
+    fill3d.SetDrawOption("same");
+    fill4b.SetDrawOption("same");
+    fill5b.SetDrawOption("same");
+    fill6b.SetDrawOption("same");
+    fill7b.SetDrawOption("same");
+    //fill9b.SetFilter(&fbin);
+
+    fill3d.SetFilter(&ftheta);
+
+    MHThetaSq *halphaon = plist.FindCreateObj("MHThetaSq", "Hist");
+    halphaon->ForceUsingSize();
+
+    MFillH falpha2(halphaon, "", "FillHist");
+    MFillH fenergy2("HistE [MHThetaSq]", "", "FillHistE");
+
+    tlist2.SetNumPasses();
+
+    tlist.Replace(readondata);
+
+    MHSrcPosCam hsrcpos(kTRUE);
+
+    MFillH fillsrc(&hsrcpos, "MSrcPosCam", "FillSrcPosCam");
+    fillsrc.SetNameTab("SrcPos");
+
+    tlist2.AddToListBefore(&fillsrc, &hcalc);
+
+    MH3 hvs1("MPointingPos.fZd");
+    MH3 hvs2("MPointingPos.fZd");
+    MHVsTime hvstM("MTimeDrive.GetMjd");
+    MHVsTime hvst0("MPointingPos.fZd");
+    MHVsTime hvst1("MReportRates.fTriggerRate");
+    MH3      hvst2("MPointingPos.fZd", "MReportRates.fTriggerRate");
+    MHVsTime hvst("MReportTemperatures.GetTempMean");
+    MHVsTime hvsh("MReportHumidity.GetMean");
+    hvs1.SetName("ObsTime;Theta");
+    hvs2.SetName("OnTime;Theta");
+    hvstM.SetName("MJD");
+    hvst0.SetName("ZdTime");
+    hvst1.SetName("Rate");
+    hvst2.SetName("RateZd;Theta;Rate");
+    hvst.SetName("CamTemp");
+    hvsh.SetName("CamHum");
+    hvs1.SetTitle("Observation time vs. Zenith Angle;\\Theta [\\circ];T_{on} [s]");
+    hvs2.SetTitle("On-Time vs. Zenith Angle;\\Theta [\\circ];T_{on} [s]");
+    hvstM.SetTitle("MJD vs time;Time;MJD");
+    hvst0.SetTitle("Zenith distance vs time;Time;Zd [\\circ]");
+    hvst1.SetTitle("Camera trigger rate vs time;Time;Rate [Hz]");
+    hvst2.SetTitle("Camera trigger rate vs Zd; Zd [\\circ];Rate [Hz]");
+    hvst.SetTitle("Average sensor compartment temperature;Time;T [\\circ C]");
+    hvsh.SetTitle("Average camera humidity;Time;Hum [%]");
+
+    MFillH fillvs1(&hvs1, "", "FillObsTime");
+    MFillH fillvs2(&hvs2, "", "FillOnTime");
+    MFillH fillvstM(&hvstM, "MTime", "FillMjdVsTime");
+    MFillH fillvst0(&hvst0, "MTimeDrive", "FillZdVsTime");
+    MFillH fillvst1(&hvst1, "MTimeRates", "FillRate");
+    MFillH fillvst2(&hvst2, "", "FillRateVsZd");
+    MFillH fillvst(&hvst, "MTimeTemperatures", "FillCamTemp");
+    MFillH fillvsh(&hvsh, "MTimeHumidity",     "FillCamHum");
+    fillvs1.SetNameTab("ObsTime");
+    fillvs2.SetNameTab("OnTime");
+    fillvst1.SetNameTab("Rate");
+    fillvst2.SetNameTab("RateZd");
+    fillvst.SetNameTab("CamTemp");
+    fillvsh.SetNameTab("CamHum");
+
+    hvs1.SetWeight("MReportRates.fElapsedTime");
+    hvs2.SetWeight("MReportRates.fElapsedOnTime");
+
+    hvst1.SetMinimum(0);
+    hvst2.SetDrawOption("colz");
+
+    MH3 hrate("MRawRunHeader.GetFileID"/*, "MRawEvtHeader.GetTriggerID"*/);
+    hrate.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hrate.SetName("RateVsRun");
+    hrate.SetTitle("Event rate after quality cuts;File Id;Event Rate [Hz];");
+    hrate.InitLabels(MH3::kLabelsX);
+    hrate.GetHist().SetMinimum(0);
+
+    MFillH fillr(&hrate, "", "FillRateVsRun");
+    tlist.AddToListAfter(&fillr, &contq, "Events");
+
+    tlist.Replace(&fill1b);
+
+    tlist2.Replace(&fill2b);
+    tlist2.Replace(&fill3b);
+    tlist2.Replace(&fill3d);
+    tlist2.Replace(&fill4b);
+    tlist2.Replace(&fill5b);
+    tlist2.Replace(&fill6b);
+    tlist2.Replace(&fill7b);
+    tlist2.Replace(&falpha2);
+    tlist2.Replace(&fenergy2);
+    if (!ismc)
+    {
+        tlist.AddToList(&fillvs1,  "Rates");
+        tlist.AddToList(&fillvs2,  "Rates");
+        tlist.AddToList(&fillvst1, "Rates");
+        tlist.AddToList(&fillvst2, "Rates");
+        tlist.AddToList(&write2,   "Rates");
+        tlist.AddToList(&fillvst,  "Temperatures");
+        tlist.AddToList(&fillvsh,  "Humidity");
+        tlist.AddToList(&fillvst0, "Drive");
+        tlist.AddToList(&fillvstM, "Drive");
+    }
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    par.SetVal(1);
+    weight.SetVal(1);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+        return 2;
+
+    if (!evtloop.GetDisplay())
+        return 2;
+
+    delete readondata;
+    delete readoffdata;
+
+    TObjArray cont;
+    //cont.Add(const_cast<TEnv*>(GetEnv()));
+    //cont.Add(const_cast<MSequence*>(&fSequence));
+
+    //TNamed cmdline("CommandLine", fCommandLine.Data());
+    //cont.Add(&cmdline);
+
+    if (d)
+    {
+        TString title = "--  Analysis #";
+        title += dataset;
+        title += "  --";
+        d->SetTitle(title, kFALSE);
+
+        cont.Add(d);
+        TString path;
+        path += fname1;
+
+        d->Write();
+    }
+
+//    if (!WriteContainer(cont, fname1, "RECREATE"))
+//        return;
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/mc/star.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/mc/star.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/mc/star.C	(revision 17960)
@@ -0,0 +1,420 @@
+#include <sstream>
+#include <iostream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#if !defined(__CINT__) || defined(__MAKECINT__)
+
+#include "TH1F.h"
+#include "TFile.h"
+#include "TStyle.h"
+#include "TGraph.h"
+#include "TLine.h"
+
+#include "../mcore/DrsCalib.h"
+#include "MDrsCalibration.h"
+//#include "MLogManip.h"
+#include "MExtralgoSpline.h"
+#include "MSequence.h"
+#include "MStatusArray.h"
+#include "MHCamera.h"
+#include "MJob.h"
+#include "MWriteRootFile.h"
+#include "MHCamera.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+#include "MDirIter.h"
+#include "MTaskList.h"
+#include "MFDataPhrase.h"
+#include "MArrayF.h"
+#include "MBadPixelsTreat.h"
+#include "MCalibrateDrsTimes.h"
+#include "MHSectorVsTime.h"
+#include "MHCamEvent.h"
+#include "MExtractTimeAndChargeSpline.h"
+#include "MFillH.h"
+#include "MDrsCalibApply.h"
+#include "MGeomApply.h"
+#include "MContinue.h"
+#include "MRawFitsRead.h"
+#include "MEvtLoop.h"
+#include "MParList.h"
+#include "MStatusDisplay.h"
+#include "MDrsCalibrationTime.h"
+#include "MH3.h"
+#include "MGeomCamFACT.h"
+#include "MCalibrateFact.h"
+#include "MParameters.h"
+#include "MWriteAsciiFile.h"
+#include "MFMagicCuts.h"
+
+#include "MMuonSetup.h"
+#include "MReadMarsFile.h"
+#include "MHillasCalc.h"
+#include "MHn.h"
+#include "MMuonSearchParCalc.h"
+#include "MMuonCalibParCalc.h"
+#include "MBinning.h"
+#include "MImgCleanStd.h"
+
+#endif
+
+using namespace std;
+
+int star(const TString callistofile, TString outfile,
+         TString displayfile, TString displaytitle,
+         const TString txtfile,
+         Double_t lvl1=4.0, Double_t lvl2=2.5, Double_t deltat = 17.5);
+
+
+int star(const TString infile = "callisto.root", TString outfile = "",
+         Double_t lvl1=4.0,  Double_t lvl2=2.5, Double_t deltat = 17.5)
+{
+    return star(infile, outfile, "", "", "", lvl1, lvl2, deltat);
+}
+
+int star(const TString callistofile, TString outfile,
+         TString displayfile,  TString displaytitle,
+         const TString txtfile,
+         Double_t lvl1, Double_t lvl2, Double_t deltat)
+{
+
+    //Double_t lvl1=7.8, 
+    //Double_t lvl2=3.9,
+    //    lvl1 = 2.5;
+    //    lvl2 = 0.5;
+    // ------------------------------------------------------
+
+    if (displaytitle.IsNull())
+        displaytitle = gSystem->BaseName(callistofile);
+
+    FileStat_t fstat;
+    int rc = gSystem->GetPathInfo(outfile, fstat);
+    bool isdir = !rc || R_ISDIR(fstat.fMode);
+
+    char *buf = gSystem->ConcatFileName(outfile, "star.root");
+    outfile = buf;
+    delete [] buf;
+
+    if (displayfile.IsNull())
+    {
+        displayfile = outfile;
+        displayfile.Insert(displayfile.Last('.'), "-display");
+    }
+    else
+    {
+        if (isdir && gSystem->DirName(displayfile)==TString("."))
+        {
+            buf = gSystem->ConcatFileName(outfile, displayfile);
+            displayfile = buf;
+            delete [] buf;
+        }
+    }
+
+    // ------------------------------------------------------
+
+    gLog.Separator("Star");
+    gLog << all << "Calculate image parameters of sequence ";
+    gLog << endl;
+    gLog << "Callisto file: " << callistofile << endl;
+    gLog << "Output file:   " << outfile << endl;
+    gLog << "Display file:  " << displayfile << endl;
+    gLog << "Display title: " << displaytitle << endl;
+    gLog << endl;
+    gLog << "lvl1: "   << lvl1 <<endl;
+    gLog << "lvl2: "   << lvl2 <<endl;
+    gLog << "deltat: " << deltat <<endl;
+    
+    
+    gLog << endl;
+
+    // ------------------------------------------------------
+
+    gLog.Separator();
+
+    // --------------------------------------------------------
+
+    MBinning bins1(  36,    -90,    90, "BinningAlpha");
+    MBinning bins3(  67, -0.005, 0.665, "BinningTheta", "asin");
+    MBinning bins4(  25,      0,   2.5, "BinningDist");
+    MBinning binsM1(100,      0,     5, "BinningMuonRadius");
+    MBinning binsM2( 60,      0,   0.3, "BinningMuonDeviation");
+    MBinning binsM3(150,      0,    60, "BinningMuonTime");
+    MBinning binsM4(300,      0,    30, "BinningMuonTimeRms");
+    MBinning binsM5( 20,      0,   360, "BinningMuonArcPhi");
+    MBinning binsM6( 50,      0,   0.5, "BinningMuonArcWidth");
+    MBinning binsM7( 30,      5,  5000, "BinningMuonSize", "log");
+    MBinning binsM8(100,      0,     5, "BinningMuonRelTimeSigma");
+    MBinning binsM9(100,      0,     5, "BinningRadius");
+
+    // ---------------------------------------------------------
+
+    // Filter to start muon analysis
+    //MFDataPhrase fmuon1("MHillas.fSize>150 && MNewImagePar.fConcCOG<0.1", "MuonPreCut");
+    // Filter to calculate further muon parameters
+//    MFDataPhrase fmuon2("(MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg>0.6) && (MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg<1.35) &&"
+//                        "(MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg<0.152)", "MuonSearchCut");
+    MFDataPhrase fmuon2("MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg>0.015 &&"
+                        "MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg>(MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg-0.1)*0.15/0.4",
+                        "MuonSearchCut");
+
+    // Filter to fill the MHMuonPar
+    MFDataPhrase fmuon3("MMuonCalibPar.fArcPhi>190 && MMuonCalibPar.fRelTimeSigma<3.2",
+                        "MuonFinalCut");
+    // Filter to write Muons to Muon tree
+    //MFDataMember fmuon4("MMuonCalibPar.fArcPhi", '>', -0.5, "MuonWriteCut");
+
+    // ---------------------------------------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MTaskList tlist;
+
+    MParList plist2;
+    plist2.AddToList(&tlist);
+    plist2.AddToList(&bins1);
+    plist2.AddToList(&bins3);
+    plist2.AddToList(&bins4);
+    plist2.AddToList(&binsM1);
+    plist2.AddToList(&binsM2);
+    plist2.AddToList(&binsM3);
+    plist2.AddToList(&binsM4);
+    plist2.AddToList(&binsM5);
+    plist2.AddToList(&binsM6);
+    plist2.AddToList(&binsM7);
+    plist2.AddToList(&binsM8);
+    plist2.AddToList(&binsM9);
+
+    MMuonSetup muonsetup;
+    plist2.AddToList(&muonsetup);
+
+    MEvtLoop loop;
+    loop.SetDisplay(d);
+    loop.SetParList(&plist2);
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile(callistofile);
+
+    MContinue cont("MRawEvtHeader.GetTriggerID!=4", "SelectData");
+
+    MGeomApply apply;
+
+    MImgCleanStd clean(lvl1, lvl2);
+    clean.SetMethod(MImgCleanStd::kAbsolute);
+    clean.SetTimeLvl1(deltat);//17.5/*1.3*/);
+    clean.SetTimeLvl2(deltat);//17.5/*1.3*/);
+    clean.SetPostCleanType(3);
+
+    MHillasCalc hcalc;
+    hcalc.Disable(MHillasCalc::kCalcConc);
+
+    MH3 hrate("MRawRunHeader.GetFileID"/*, "MRawEvtHeader.GetTriggerID"*/);
+    hrate.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hrate.SetName("Rate");
+    hrate.SetTitle("Event rate after cleaning;File Id;Event Rate [Hz];");
+    hrate.InitLabels(MH3::kLabelsX);
+    hrate.GetHist().SetMinimum(0);
+
+    MFillH fillR(&hrate, "", "FillRate");
+
+    // ------------------ Setup histograms and fill tasks ----------------
+    MHCamEvent evtC1(0, "Cleaned",  "Average signal after Cleaning;;S [phe]");
+    MHCamEvent evtC2(0, "UsedPix",  "Fraction of Events in which Pixels are used;;Fraction");
+    MHCamEvent evtC3(8, "PulsePos", "Pulse Position of signal after cleaning;;T [ns]");
+    evtC1.SetErrorSpread(kFALSE);
+    evtC2.SetErrorSpread(kFALSE);
+    evtC2.SetThreshold(0);
+
+    MFillH fillC1(&evtC1, "MSignalCam", "FillSignalCam");
+    MFillH fillC2(&evtC2, "MSignalCam", "FillCntUsedPixels");
+    MFillH fillC3(&evtC3, "MSignalCam", "FillPulsePos");
+
+    MFillH fillD1("MHHillas",      "MHillas",      "FillHillas");
+    MFillH fillD2("MHHillasExt",   "",             "FillHillasExt");
+    MFillH fillD3("MHHillasSrc",   "MHillasSrc",   "FillHillasSrc");
+    MFillH fillD4("MHImagePar",    "MImagePar",    "FillImagePar");
+    MFillH fillD5("MHNewImagePar", "MNewImagePar", "FillNewImagePar");
+    MFillH fillD6("MHVsSize",      "MHillasSrc",   "FillVsSize");
+
+    MH3 halpha("MHillasSrc.fDist*MGeomCam.fConvMm2Deg", "fabs(MHillasSrc.fAlpha)");
+    halpha.SetName("AvsD;Dist;Alpha");
+
+    MFillH filla(&halpha);
+    filla.SetNameTab("AvsD");
+    filla.SetDrawOption("colz");
+
+    // ----------------------- Muon Analysis ----------------------
+    //writem.SetFilter(&fmuon4);
+
+    MHn mhn1;
+    mhn1.AddHist("MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg");
+    mhn1.InitName("MuonRadius");
+    mhn1.InitTitle("MuonRadius");
+
+    mhn1.AddHist("MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg");
+    mhn1.InitName("MuonDeviation");
+    mhn1.InitTitle("MuonDeviation");
+
+    mhn1.AddHist("MMuonSearchPar.fTime");
+    mhn1.InitName("MuonTime");
+    mhn1.InitTitle("MuonTime");
+
+    mhn1.AddHist("MMuonSearchPar.fTimeRms");
+    mhn1.InitName("MuonTimeRms");
+    mhn1.InitTitle("MuonTimeRms");
+
+    MHn mhn3;
+    mhn3.AddHist("MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg","MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg");
+    mhn3.InitName("MuonRadius;MuonRadius;MuonDeviation");
+    mhn3.InitTitle("MuonRadius");
+    mhn3.SetDrawOption("colz");
+
+    MHn mhn2;
+    mhn2.AddHist("MMuonCalibPar.fArcPhi");
+    mhn2.InitName("MuonArcPhi");
+    mhn2.InitTitle("MuonArcPhi");
+
+    mhn2.AddHist("MMuonCalibPar.fArcWidth");
+    mhn2.InitName("MuonArcWidth");
+    mhn2.InitTitle("MuonArcWidth");
+
+    mhn2.AddHist("MMuonCalibPar.fMuonSize");
+    mhn2.InitName("MuonSize");
+    mhn2.InitTitle("MuonSize");
+
+    mhn2.AddHist("MMuonCalibPar.fRelTimeSigma");
+    mhn2.InitName("MuonRelTimeSigma");
+    mhn2.InitTitle("MuonRelTimeSigma");
+
+    MHn mhn4;
+    mhn4.AddHist("MMuonCalibPar.fArcPhi","MMuonCalibPar.fArcWidth");
+    mhn4.InitName("MuonArcPhi;MuonArcPhi;MuonArcWidth");
+    mhn4.InitTitle("MuonArcPhi");
+    mhn4.SetDrawOption("colz");
+
+    MFillH fillmhn1(&mhn1, "", "FillMuonSearchPar");
+    MFillH fillmhn2(&mhn2, "", "FillMuonCalibPar");
+    MFillH fillmhn3(&mhn3, "", "FillMuonDevVsRadius");
+    MFillH fillmhn4(&mhn4, "", "FillMuonWidthVsPhi");
+    fillmhn1.SetNameTab("MuonS");
+    fillmhn3.SetNameTab("DevVsRad");
+    fillmhn2.SetNameTab("MuonC");
+    fillmhn4.SetNameTab("WidthVsPhi");
+    fillmhn2.SetFilter(&fmuon2);
+    fillmhn4.SetFilter(&fmuon2);
+
+    MMuonSearchParCalc muscalc;
+    //muscalc.SetFilter(&fmuon1);
+
+    MMuonCalibParCalc mcalc;
+    mcalc.SetFilter(&fmuon2);
+
+    MFillH fillmuon("MHSingleMuon", "", "FillMuon");
+    MFillH fillmpar("MHMuonPar",    "", "FillMuonPar");
+    fillmuon.SetFilter(&fmuon2);
+    fillmpar.SetFilter(&fmuon3);
+    fillmuon.SetBit(MFillH::kDoNotDisplay);
+
+    // ---------------------------------------------------------------
+
+    MWriteAsciiFile writeascii(txtfile, "MHillas");
+    writeascii.AddColumns("MHillasExt");
+    writeascii.AddColumns("MHillasSrc");
+
+
+    MWriteRootFile write(outfile, "RECREATE", "Image parameters", 2);
+    write.AddContainer("MTime",               "Events", kFALSE);
+    write.AddContainer("MHillas",             "Events");
+    write.AddContainer("MHillasExt",          "Events");
+    write.AddContainer("MHillasSrc",          "Events");
+    write.AddContainer("MImagePar",           "Events");
+    write.AddContainer("MNewImagePar",        "Events");
+    write.AddContainer("MRawEvtHeader",       "Events");
+    write.AddContainer("ThetaSquared",        "Events");
+    write.AddContainer("Disp",                "Events");
+    write.AddContainer("MCorsikaEvtHeader",   "Events", kFALSE);
+    write.AddContainer("MMcEvt",              "Events", kFALSE);
+    write.AddContainer("IncidentAngle",       "Events", kFALSE);
+    write.AddContainer("MPointingPos",        "Events", kFALSE);
+
+    write.AddContainer("MRawRunHeader",       "RunHeaders");
+    write.AddContainer("MGeomCam",            "RunHeaders");
+    write.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE);
+    write.AddContainer("MCorsikaRunHeader",   "RunHeaders", kFALSE);
+    write.AddContainer("MMcRunHeader",        "RunHeaders", kFALSE);
+
+    MFDataPhrase fmuonhn("MMuonCalibPar.fRelTimeSigma>=0",
+                         "MuonHistCut");
+    fillmhn2.SetFilter(&fmuonhn);
+
+    TArrayD param(12);
+    // Parametrization of Disp
+    param[0]  =  1.15136;     // constant
+    param[8]  =  0.0681437;   // slope
+    param[9]  =  2.62932;     // leak
+    param[10] =  1.51279;     // size-offset
+    param[11] =  0.0507821;   // size-slope
+    // Parametrization for sign of disp (m3long, slope)
+    param[5]  = -0.07;
+    param[6]  =  7.2;
+    param[7]  =  0.5;
+    // ThetaSq-Cut
+    param[1]  =  0.11;  // 0.215
+    // Area-Cut
+    param[2]  =  0.215468;
+    param[3]  =  5.63973;
+    param[4]  =  0.0836169;
+    MFMagicCuts cuts;
+    cuts.SetHadronnessCut(MFMagicCuts::kNoCut);
+    cuts.SetVariables(param);
+
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&cuts);
+    tlist.AddToList(&fillC1);
+    tlist.AddToList(&fillC2);
+    tlist.AddToList(&fillC3);
+    tlist.AddToList(&fillR);
+    tlist.AddToList(&fillD1);
+    tlist.AddToList(&fillD2);
+    tlist.AddToList(&fillD3);
+    tlist.AddToList(&fillD4);
+    tlist.AddToList(&fillD5);
+    tlist.AddToList(&fillD6);
+    tlist.AddToList(&filla);
+    //tlist.AddToList(&fmuon1);
+    tlist.AddToList(&muscalc);
+    tlist.AddToList(&fillmhn1);
+    tlist.AddToList(&fillmhn3);
+    tlist.AddToList(&fmuon2);
+    tlist.AddToList(&fillmuon);
+    tlist.AddToList(&mcalc);
+    tlist.AddToList(&fmuonhn);
+    tlist.AddToList(&fillmhn2);
+    tlist.AddToList(&fillmhn4);
+    tlist.AddToList(&fmuon3);
+    tlist.AddToList(&fillmpar);
+    //tlist.AddToList(&fmuon4);
+    //tlist.AddToList(&writem);
+    tlist.AddToList(&write);
+    if (!txtfile.IsNull())
+        tlist.AddToList(&writeascii);
+
+    if (!loop.Eventloop())
+        return 3;
+
+    if (!loop.GetDisplay())
+        return 4;
+
+    d->SetTitle(displaytitle, kFALSE);
+    d->SaveAs(displayfile);
+
+    return 0;
+}
+
Index: branches/Mars_McMismatchStudy/fact/analysis/merpp.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/merpp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/merpp.C	(revision 17960)
@@ -0,0 +1,130 @@
+#include "MLogManip.h"
+
+void merpp(TString &froot, const char *id, const char *faux)
+{
+    gLog.Separator(froot+" - "+TString(id));
+
+    TFile file(froot);
+    if (file.IsZombie())
+    {
+        gLog << err << "merpp: Invalid file '" << froot << "'" << endl;
+        return;
+    }
+
+    MRawRunHeader *h = NULL;
+    TTree *tree = file.Get("RunHeaders");
+    if (!tree)
+    {
+        gLog << err << "merpp: Tree 'RunHeaders' not found... skipped." << endl;
+        return;
+    }
+
+    if (tree->GetEntries()!=1)
+    {
+        gLog << err << "merpp: Number of RunHeaders do not match 1... skipped." << endl;
+        return;
+    }
+
+    tree->SetBranchAddress("MRawRunHeader.", &h);
+    tree->GetEntry(0);
+
+    if (file.Get(id))
+    {
+        gLog << warn << "WARNING - Tree '" << id << "' already existing... skipped." << endl;
+        return;
+    }
+
+    file.Close();
+
+    UInt_t night = h->GetRunNumber();
+
+    TString ffits = Form("/fact/aux/%4d/%02d/%02d/%6d.%s.fits",
+                         night/10000, (night/100)%100, night%100, night, faux);
+
+    TString report = Form("MReport%s", id);
+    TString time   = Form("MTime%s",   id);
+
+    gLog << all;
+    gLog << " --- Fits file: " << ffits << endl;
+    gLog << " --- Root file: " << froot << endl;
+    gLog << " --- Tree:      " << id << " (" << faux << ")" << endl;
+
+    MReportFitsRead read(ffits);
+    read.SetReportName(report);
+    read.SetTimeStart(h->GetRunStart());
+    read.SetTimeStop(h->GetRunEnd());
+
+    // FIXME: Write also last event BEFORE start of run
+
+    MWriteRootFile write(froot, "UPDATE");
+    write.AddContainer(report, id);
+    write.AddContainer(time,   id);
+
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&write);
+
+    MEvtLoop loop;
+    loop.SetParList(&plist);
+
+    if (!loop.Eventloop())
+        return;
+}
+
+int merpp(const char *seqfile="sequences/20111205_013.seq", const char *path = "output")
+{
+    // The sequence file which defines the files for the analysis
+    MSequence seq(seqfile);
+    if (!seq.IsValid())
+    {
+        gLog << err << "ERROR - Sequence invalid!" << endl;
+        return 1;
+    }
+
+    // ------------------------------------------------------
+
+    gLog.Separator("Merpp");
+    gLog << all;
+    gLog << "Merge slow control data of sequence ";
+    gLog << seq.GetFileName() << endl;
+    gLog << endl;
+    gLog << "Path:  " << path << endl;
+
+    MDirIter iter;
+    if (seq.GetRuns(iter, MSequence::kFactImg, path)<=0)
+    {
+        gLog << err << "ERROR - Sequence valid but without files." << endl;
+        return 2;
+    }
+
+    iter.Print();
+
+    while (1)
+    {
+        TString fname = iter.Next();
+        if (fname.IsNull())
+            break;
+
+        merpp(fname, "Weather",      "MAGIC_WEATHER_DATA");
+        merpp(fname, "Drive",        "DRIVE_CONTROL_TRACKING_POSITION");
+        merpp(fname, "Rates",        "FTM_CONTROL_TRIGGER_RATES");
+        merpp(fname, "Temperatures", "FSC_CONTROL_TEMPERATURE");
+        merpp(fname, "Humidity",     "FSC_CONTROL_HUMIDITY");
+    }
+
+    return 0;
+}
+
+int merpp(const ULong64_t seqnum, const char *path="output")
+{
+    UInt_t night = seqnum/1000;
+    UInt_t num   = seqnum%1000;
+
+    TString file = Form("/scratch/fact/sequences/%04d/%02d/%02d/%06d_%03d.seq",
+                        night/10000, (night/100)%100, night%100, num);
+
+    return merpp(file.Data(), path);
+}
Index: branches/Mars_McMismatchStudy/fact/analysis/star.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/analysis/star.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/analysis/star.C	(revision 17960)
@@ -0,0 +1,308 @@
+#include "MLogManip.h"
+
+int star(const char *seqfile="sequences/20111205_013.seq", Double_t lvl1=4.0, Double_t lvl2=2.5, const char *inpath = "output", const char *outpath = "output")
+{
+    double deltat = 17.5;
+    //    lvl1 = 2.5;
+    //    lvl2 = 0.5;
+
+    // The sequence file which defines the files for the analysis
+    MSequence seq(seqfile);
+    if (!seq.IsValid())
+    {
+        gLog << err << "ERROR - Sequence invalid!" << endl;
+        return 1;
+    }
+
+    // ------------------------------------------------------
+
+    gLog.Separator("Star");
+    gLog << all << "Calculate image parameters of sequence ";
+    gLog << seq.GetFileName() << endl;
+    gLog << endl;
+
+    // ------------------------------------------------------
+
+    gLog << "Inpath:   " << inpath << endl;
+    gLog << "Outpath:  " << outpath << endl;
+
+    const TString rule(Form("s/([0-9]+_[0-9]+)_C[.]root?$/%s\\/$1_I.root/",
+                            MJob::Esc(outpath).Data()));
+    gLog << "Rule:     " << rule << endl;
+
+    MDirIter iter;
+    if (seq.GetRuns(iter, MSequence::kFactCal, inpath)<=0)
+    {
+        gLog << err << "ERROR - Sequence valid but without files." << endl;
+        return 2;
+    }
+
+    iter.Print();
+
+    gLog.Separator();
+
+    // --------------------------------------------------------
+
+    MBinning bins1(  36,    -90,    90, "BinningAlpha");
+    MBinning bins3(  67, -0.005, 0.665, "BinningTheta", "asin");
+    MBinning bins4(  25,      0,   2.5, "BinningDist");
+
+    MBinning binsM1(100,      0,     5, "BinningMuonRadius");
+    MBinning binsM2( 60,      0,   0.3, "BinningMuonDeviation");
+    MBinning binsM3(150,      0,    60, "BinningMuonTime");
+    MBinning binsM4(300,      0,    30, "BinningMuonTimeRms");
+    MBinning binsM5( 20,      0,   360, "BinningMuonArcPhi");
+    MBinning binsM6( 50,      0,   0.5, "BinningMuonArcWidth");
+    MBinning binsM7( 30,      5,  5000, "BinningMuonSize", "log");
+    MBinning binsM8(100,      0,     5, "BinningMuonRelTimeSigma");
+
+    MBinning binsM9(100,      0,     5, "BinningRadius");
+
+    // ---------------------------------------------------------
+
+    // Filter to start muon analysis
+    //MFDataPhrase fmuon1("MHillas.fSize>150 && MNewImagePar.fConcCOG<0.1", "MuonPreCut");
+    // Filter to calculate further muon parameters
+//    MFDataPhrase fmuon2("(MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg>0.6) && (MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg<1.35) &&"
+//                        "(MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg<0.152)", "MuonSearchCut");
+    MFDataPhrase fmuon2("MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg>0.015 &&"
+                        "MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg>(MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg-0.1)*0.15/0.4",
+                        "MuonSearchCut");
+
+    // Filter to fill the MHMuonPar
+    MFDataPhrase fmuon3("MMuonCalibPar.fArcPhi>190 && MMuonCalibPar.fRelTimeSigma<3.2",
+                        "MuonFinalCut");
+    // Filter to write Muons to Muon tree
+    //MFDataMember fmuon4("MMuonCalibPar.fArcPhi", '>', -0.5, "MuonWriteCut");
+
+    // ---------------------------------------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MTaskList tlist;
+
+    MParList plist2;
+    plist2.AddToList(&tlist);
+    plist2.AddToList(&bins1);
+    plist2.AddToList(&bins3);
+    plist2.AddToList(&bins4);
+    plist2.AddToList(&binsM1);
+    plist2.AddToList(&binsM2);
+    plist2.AddToList(&binsM3);
+    plist2.AddToList(&binsM4);
+    plist2.AddToList(&binsM5);
+    plist2.AddToList(&binsM6);
+    plist2.AddToList(&binsM7);
+    plist2.AddToList(&binsM8);
+    plist2.AddToList(&binsM9);
+
+    MMuonSetup muonsetup;
+    plist2.AddToList(&muonsetup);
+
+    MEvtLoop loop;
+    loop.SetDisplay(d);
+    loop.SetParList(&plist2);
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFiles(iter);
+
+    MContinue cont("MRawEvtHeader.GetTriggerID!=4", "SelectData");
+
+    MGeomApply apply;
+
+    MImgCleanStd clean(lvl1, lvl2);
+    clean.SetMethod(MImgCleanStd::kAbsolute);
+    clean.SetTimeLvl1(deltat);//17.5/*1.3*/);
+    clean.SetTimeLvl2(deltat);//17.5/*1.3*/);
+    clean.SetPostCleanType(3);
+
+    MHillasCalc hcalc;
+    hcalc.Disable(MHillasCalc::kCalcConc);
+
+    MH3 hrate("MRawRunHeader.GetFileID"/*, "MRawEvtHeader.GetTriggerID"*/);
+    hrate.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hrate.SetName("Rate");
+    hrate.SetTitle("Event rate after cleaning;File Id;Event Rate [Hz];");
+    hrate.InitLabels(MH3::kLabelsX);
+    hrate.GetHist().SetMinimum(0);
+
+    MFillH fillR(&hrate, "", "FillRate");
+
+    // ------------------ Setup histograms and fill tasks ----------------
+    MHCamEvent evtC1(0, "Cleaned",  "Average signal after Cleaning;;S [phe]");
+    MHCamEvent evtC2(0, "UsedPix",  "Fraction of Events in which Pixels are used;;Fraction");
+    MHCamEvent evtC3(8, "PulsePos", "Pulse Position of signal after cleaning;;T [ns]");
+    evtC1.SetErrorSpread(kFALSE);
+    evtC2.SetErrorSpread(kFALSE);
+    evtC2.SetThreshold(0);
+
+    MFillH fillC1(&evtC1, "MSignalCam", "FillSignalCam");
+    MFillH fillC2(&evtC2, "MSignalCam", "FillCntUsedPixels");
+    MFillH fillC3(&evtC3, "MSignalCam", "FillPulsePos");
+
+    MFillH fillD1("MHHillas",      "MHillas",      "FillHillas");
+    MFillH fillD2("MHHillasExt",   "",             "FillHillasExt");
+    MFillH fillD3("MHHillasSrc",   "MHillasSrc",   "FillHillasSrc");
+    MFillH fillD4("MHImagePar",    "MImagePar",    "FillImagePar");
+    MFillH fillD5("MHNewImagePar", "MNewImagePar", "FillNewImagePar");
+    MFillH fillD6("MHVsSize",      "MHillasSrc",   "FillVsSize");
+
+    MH3 halpha("MHillasSrc.fDist*MGeomCam.fConvMm2Deg", "fabs(MHillasSrc.fAlpha)");
+    halpha.SetName("AvsD;Dist;Alpha");
+
+    MFillH filla(&halpha);
+    filla.SetNameTab("AvsD");
+    filla.SetDrawOption("colz");
+
+    // ----------------------- Muon Analysis ----------------------
+    //writem.SetFilter(&fmuon4);
+
+    MHn mhn1;
+    mhn1.AddHist("MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg");
+    mhn1.InitName("MuonRadius");
+    mhn1.InitTitle("MuonRadius");
+
+    mhn1.AddHist("MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg");
+    mhn1.InitName("MuonDeviation");
+    mhn1.InitTitle("MuonDeviation");
+
+    mhn1.AddHist("MMuonSearchPar.fTime");
+    mhn1.InitName("MuonTime");
+    mhn1.InitTitle("MuonTime");
+
+    mhn1.AddHist("MMuonSearchPar.fTimeRms");
+    mhn1.InitName("MuonTimeRms");
+    mhn1.InitTitle("MuonTimeRms");
+
+    MHn mhn3;
+    mhn3.AddHist("MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg","MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg");
+    mhn3.InitName("MuonRadius;MuonRadius;MuonDeviation");
+    mhn3.InitTitle("MuonRadius");
+    mhn3.SetDrawOption("colz");
+
+    MHn mhn2;
+    mhn2.AddHist("MMuonCalibPar.fArcPhi");
+    mhn2.InitName("MuonArcPhi");
+    mhn2.InitTitle("MuonArcPhi");
+
+    mhn2.AddHist("MMuonCalibPar.fArcWidth");
+    mhn2.InitName("MuonArcWidth");
+    mhn2.InitTitle("MuonArcWidth");
+
+    mhn2.AddHist("MMuonCalibPar.fMuonSize");
+    mhn2.InitName("MuonSize");
+    mhn2.InitTitle("MuonSize");
+
+    mhn2.AddHist("MMuonCalibPar.fRelTimeSigma");
+    mhn2.InitName("MuonRelTimeSigma");
+    mhn2.InitTitle("MuonRelTimeSigma");
+
+    MHn mhn4;
+    mhn4.AddHist("MMuonCalibPar.fArcPhi","MMuonCalibPar.fArcWidth");
+    mhn4.InitName("MuonArcPhi;MuonArcPhi;MuonArcWidth");
+    mhn4.InitTitle("MuonArcPhi");
+    mhn4.SetDrawOption("colz");
+
+    MFillH fillmhn1(&mhn1, "", "FillMuonSearchPar");
+    MFillH fillmhn2(&mhn2, "", "FillMuonCalibPar");
+    MFillH fillmhn3(&mhn3, "", "FillMuonDevVsRadius");
+    MFillH fillmhn4(&mhn4, "", "FillMuonWidthVsPhi");
+    fillmhn1.SetNameTab("MuonS");
+    fillmhn3.SetNameTab("DevVsRad");
+    fillmhn2.SetNameTab("MuonC");
+    fillmhn4.SetNameTab("WidthVsPhi");
+    fillmhn2.SetFilter(&fmuon2);
+    fillmhn4.SetFilter(&fmuon2);
+
+    MMuonSearchParCalc muscalc;
+    //muscalc.SetFilter(&fmuon1);
+
+    MMuonCalibParCalc mcalc;
+    mcalc.SetFilter(&fmuon2);
+
+    MFillH fillmuon("MHSingleMuon", "", "FillMuon");
+    MFillH fillmpar("MHMuonPar",    "", "FillMuonPar");
+    fillmuon.SetFilter(&fmuon2);
+    fillmpar.SetFilter(&fmuon3);
+    fillmuon.SetBit(MFillH::kDoNotDisplay);
+
+    // ---------------------------------------------------------------
+
+    MWriteRootFile write(2, rule, "RECREATE", "Image parameters"); // EffectiveOnTime
+    write.AddContainer("MTime",           "Events");
+    write.AddContainer("MHillas",         "Events");
+    write.AddContainer("MHillasExt",      "Events");
+    write.AddContainer("MHillasSrc",      "Events");
+    write.AddContainer("MImagePar",       "Events");
+    write.AddContainer("MNewImagePar",    "Events");
+    write.AddContainer("MRawEvtHeader",   "Events");
+    write.AddContainer("MRawRunHeader",   "RunHeaders");
+    write.AddContainer("MGeomCam",        "RunHeaders");
+
+    MFDataPhrase fmuonhn("MMuonCalibPar.fRelTimeSigma>=0",
+                         "MuonHistCut");
+    fillmhn2.SetFilter(&fmuonhn);
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&fillC1);
+    tlist.AddToList(&fillC2);
+    tlist.AddToList(&fillC3);
+    tlist.AddToList(&fillR);
+    tlist.AddToList(&fillD1);
+    tlist.AddToList(&fillD2);
+    tlist.AddToList(&fillD3);
+    tlist.AddToList(&fillD4);
+    tlist.AddToList(&fillD5);
+    tlist.AddToList(&fillD6);
+    tlist.AddToList(&filla);
+    //tlist.AddToList(&fmuon1);
+    tlist.AddToList(&muscalc);
+    tlist.AddToList(&fillmhn1);
+    tlist.AddToList(&fillmhn3);
+    tlist.AddToList(&fmuon2);
+    tlist.AddToList(&fillmuon);
+    tlist.AddToList(&mcalc);
+    tlist.AddToList(&fmuonhn);
+    tlist.AddToList(&fillmhn2);
+    tlist.AddToList(&fillmhn4);
+    tlist.AddToList(&fmuon3);
+    tlist.AddToList(&fillmpar);
+    //tlist.AddToList(&fmuon4);
+    //tlist.AddToList(&writem);
+    tlist.AddToList(&write);
+
+    if (!loop.Eventloop())
+        return 3;
+
+    if (!loop.GetDisplay())
+        return 4;
+
+    TString title = "--  Image parameters #";
+    title += seq.GetSequence();
+    title += "  --";
+    d->SetTitle(title, kFALSE);
+
+    TString path;
+    path += Form("%s/20%06d_%03d-images.root", outpath,
+                 seq.GetSequence()/1000, seq.GetSequence()%1000);
+
+    d->SaveAs(path);
+
+    return 0;
+}
+
+int star(const ULong64_t seqnum, Double_t lvl1=4.0, Double_t lvl2=2.5, const char *inpath = "output", const char *outpath = "output")
+{
+    UInt_t night = seqnum/1000;
+    UInt_t num   = seqnum%1000;
+
+    TString file = Form("/scratch/fact/sequences/%04d/%02d/%02d/%06d_%03d.seq",
+                        night/10000, (night/100)%100, night%100, num);
+
+    return star(file.Data(), lvl1, lvl2, inpath, outpath);
+}
Index: branches/Mars_McMismatchStudy/fact/plots/DataEfficiency.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/plots/DataEfficiency.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/plots/DataEfficiency.C	(revision 17960)
@@ -0,0 +1,236 @@
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TCanvas.h>
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+#include <TEnv.h>
+#include <TH2F.h>
+#include <TPad.h>
+
+#include "MSQLMagic.h"
+#include "MStatusDisplay.h"
+#include "MTime.h"
+
+using namespace std;
+
+int DataEfficiency()
+{
+    MSQLServer serv("/home/fact/fast_setup_for_automatic_analysis/Mars.von.Thomas.2012.06.22/sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    // get first night from DB
+    TString query="SELECT Min(fNight) from ObservationTimes";
+    TSQLResult *res0 = serv.Query(query);
+    if (!res0)
+        return kFALSE;
+    TSQLRow *row0=res0->Next();
+    Int_t nightmin=atoi((*row0)[0]);
+    delete res0;
+
+    query="SELECT Min(fRunStart), Max(fRunStop) from RunInfo";
+    res0 = serv.Query(query);
+    if (!res0)
+        return kFALSE;
+    row0=res0->Next();
+    float start=MTime((*row0)[0]).GetAxisTime();
+    float stop=MTime((*row0)[1]).GetAxisTime();
+    delete res0;
+
+    cout << start << " " << stop << endl;
+
+    query="SELECT fNight, ";
+    //time from start to end of astronomical twilight
+    query+=" Time_to_sec(Timediff(fStopObservation, fStartObservation)) as astrotime, ";
+    //time from start of first to end of last run
+    query+=" Time_to_sec(Timediff(Max(fRunStop),Min(fRunStart))) as obstime, ";
+    // sum of durations of all runs with duration shorter than 30 min
+    query+=" Sum(if (Timediff(fRunStop,fRunStart)<'00:30:00', Time_to_sec(Timediff(fRunStop,fRunStart)), 0)) as runtime, ";
+    // sum of durations of all data runs with duration shorter than 30 min
+    query+=" Sum(if (Timediff(fRunStop,fRunStart)<'00:30:00' and fRunTypeKey=1, Time_to_sec(Timediff(fRunStop,fRunStart)), 0)) as runtime2, ";
+    //ratio all runs / runtime
+    query+=" Sum(Time_to_sec(if (Timediff(fRunStop,fRunStart)<'00:30:00', Time_to_sec(Timediff(fRunStop,fRunStart)), 0)))/Time_to_sec(Timediff(Max(fRunStop),Min(fRunStart))) as ratio, ";
+    //ratio all runs / astronomical twilight time
+    query+=" Sum(Time_to_sec(if (Timediff(fRunStop,fRunStart)<'00:30:00', Time_to_sec(Timediff(fRunStop,fRunStart)), 0)))/Time_to_sec(Timediff(fStopObservation, fStartObservation)) as ratio2, ";
+    //ratio data runs / runtime
+    query+=" Sum(Time_to_sec(if (Timediff(fRunStop,fRunStart)<'00:30:00' and fRunTypeKey=1, Time_to_sec(Timediff(fRunStop,fRunStart)), 0)))/Time_to_sec(Timediff(Max(fRunStop),Min(fRunStart))) as ratio3, ";
+    //ratio data runs / astronomical twilight time
+    query+=" Sum(Time_to_sec(if (Timediff(fRunStop,fRunStart)<'00:30:00' and fRunTypeKey=1, Time_to_sec(Timediff(fRunStop,fRunStart)), 0)))/Time_to_sec(Timediff(fStopObservation, fStartObservation)) as ratio4, ";
+    // time first to last run / range astronomical twilight
+    query+=" Time_to_sec(Timediff(Max(fRunStop),Min(fRunStart)))/Time_to_sec(Timediff(fStopObservation, fStartObservation)) as ratio5 ";
+    query+=" FROM ObservationTimes LEFT JOIN RunInfo USING(fNight) ";
+    //query+=" WHERE not isnull(fRunStart) and not isnull(fRunStop) group by fNight having not isnull(obstime) order by fNight; ";
+    query+=" group by fNight order by fNight; ";
+
+    cout << "Q: " << query << endl;
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    Int_t numrows=res->GetRowCount();
+
+    TH1F ratio("ratio","sum of time of data runs / time from start to stop of astronomical twilight", 21, 0.025, 1.025);
+    TH1F ratio2("ratio2","sum of time of data runs  / time from beginning of first to end of last run", 21, 0.025, 1.025);
+    TH1F ratio3("ratio3","time from beginning of first to end of last run / time from start to stop of astronomical twilight", 21, 0.025, 1.025);
+
+    Float_t axis = MTime(nightmin/10000, (nightmin/100)%100, nightmin%100).GetAxisTime();
+    Float_t days = numrows*24*3600;
+
+    TH1F time1("time1","hours astronomical twilight", numrows, axis, axis+days);
+    TH1F time2("time2","hours from first to last run", numrows, axis, axis+days);
+    TH1F time3("time3","hours all runs", numrows, axis, axis+days);
+    TH1F time4("time4","hours all data runs", numrows, axis, axis+days);
+
+    TH1F eff2("eff2","hours from first to last run", numrows, axis, axis+days);
+    TH1F eff3("eff3","hours all runs", numrows, axis, axis+days);
+    TH1F eff4("eff4","hours all data runs", numrows, axis, axis+days);
+
+    //time1.SetRangeUser(start, stop);
+    //eff2.SetRangeUser(start, stop);
+
+
+    Int_t counter=0;
+    Int_t counter2=0;
+    TSQLRow *row=0;
+    while ((row=res->Next()))
+    {
+        counter++;
+        //0: night
+        //1: astronomical twilight range
+        //2: time when data was taken
+        //3: runtime all runs
+        //4: runtime data runs
+        //5: ratio runtime all runs / runtime
+        //6: ratio runtime all runs / astronomical twilight range
+        //7: ratio runtime data runs / runtime
+        //8: ratio runtime data runs / astronomical twilight range
+        if ((*row)[7])
+            ratio2.Fill(atof((*row)[7]));
+        if ((*row)[8])
+            ratio.Fill(atof((*row)[8]));
+        if ((*row)[9])
+            ratio3.Fill(atof((*row)[9]));
+        //if (atof((*row)[2])/60./60.>12)
+        //{
+        //    cout << (*row)[0] << " " << atof((*row)[2])/60./60. << endl;
+        //    counter2++;
+        //}
+        //cout << "c: " << counter << " night: " << (*row)[0] << " " << atof((*row)[1])/60./60.<< " " << atof((*row)[2])/60./60.<< " " << atof((*row)[3])/60./60.<< " " << atof((*row)[4])/60./60. << endl;
+        if (!(*row)[1])
+            continue;
+
+        float twilight = atof((*row)[1]);
+
+        time1.SetBinContent(counter, twilight/60./60.);
+        if ((*row)[2])
+        {
+            time2.SetBinContent(counter, atof((*row)[2])/60./60.);
+            eff2.SetBinContent(counter, atof((*row)[2])/twilight);
+        }
+        if ((*row)[3])
+        {
+            time3.SetBinContent(counter, atof((*row)[3])/60./60.);
+            eff3.SetBinContent(counter, atof((*row)[3])/twilight);
+        }
+        if ((*row)[4])
+        {
+            time4.SetBinContent(counter, atof((*row)[4])/60./60.);
+            eff4.SetBinContent(counter, atof((*row)[4])/twilight);
+        }
+    }
+    cout << "For " << counter2 << " nights the time from beginning of first to the end of the last run was > 12 hours." << endl;
+
+    delete res;
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    TCanvas &c1 = d->AddTab("Ratio Hist", "Ratio Hist");
+    c1.Divide(1,3);
+    c1.cd(1);
+    ratio.DrawCopy("hist");
+    c1.cd(2);
+    ratio2.DrawCopy("hist");
+    c1.cd(3);
+    ratio3.DrawCopy("hist");
+
+    TCanvas &c2 = d->AddTab("Times");
+    time1.GetXaxis()->SetTimeDisplay(true);
+    time1.GetXaxis()->SetTimeFormat("%m/%y %F1995-01-01 00:00:00 GMT");
+    time1.GetXaxis()->SetLabelSize(0.045);
+    time1.GetYaxis()->SetLabelSize(0.045);
+    time1.GetXaxis()->CenterTitle();
+    time1.GetYaxis()->CenterTitle();
+    time1.SetXTitle("Date");
+    time1.SetYTitle("Observation time / hours");
+    time1.SetFillColor(kBlue);
+    time1.SetTitle("Observation Times");
+    time1.SetMinimum(0);
+    time1.SetStats(kFALSE);
+    time1.DrawCopy("hist");
+    time2.SetFillColor(kGreen);
+    time2.DrawCopy("histsame");
+    time3.SetFillColor(kYellow);
+    time3.DrawCopy("histsame");
+    time4.SetFillColor(kRed+2);
+    time4.DrawCopy("histsame");
+
+    TCanvas &c3 = d->AddTab("Times2");
+    time1.SetFillColor(kBlue);
+    time1.SetTitle("Observation Times");
+    time1.SetStats(kFALSE);
+    time1.DrawCopy("hist");
+    time3.SetFillColor(kYellow);
+    time3.DrawCopy("histsame");
+    time4.SetFillColor(kRed+2);
+    time4.DrawCopy("histsame");
+
+    TCanvas &c4 = d->AddTab("Eff");
+    c4.SetGridy();
+    eff2.GetXaxis()->SetTimeDisplay(true);
+    eff2.GetXaxis()->SetTimeFormat("%m/%y %F1995-01-01 00:00:00 GMT");
+    eff2.GetXaxis()->SetLabelSize(0.045);
+    eff2.GetYaxis()->SetLabelSize(0.045);
+    eff2.GetXaxis()->CenterTitle();
+    eff2.GetYaxis()->CenterTitle();
+    eff2.SetXTitle("Date");
+    eff2.SetYTitle("Efficiency");
+    eff2.SetTitle("Observation efficiency");
+    eff2.SetMinimum(0);
+    eff2.SetMaximum(1);
+    eff2.SetStats(kFALSE);
+    eff2.SetLineColor(kGreen);
+    eff2.SetFillColor(kGreen);
+    eff2.DrawCopy("hist");
+    eff3.SetFillColor(kYellow);
+    eff3.SetLineColor(kYellow);
+    eff3.DrawCopy("histsame");
+    eff4.SetFillColor(kRed+2);
+    eff4.SetLineColor(kRed+2);
+    eff4.DrawCopy("histsame");
+
+    TCanvas &c5 = d->AddTab("Eff2", "Eff2");
+    c5.SetGridy();
+    eff3.GetXaxis()->SetTimeDisplay(true);
+    eff3.GetXaxis()->SetTimeFormat("%m/%y %F1995-01-01 00:00:00 GMT");
+    eff3.GetXaxis()->SetLabelSize(0.045);
+    eff3.GetYaxis()->SetLabelSize(0.045);
+    eff3.GetXaxis()->CenterTitle();
+    eff3.GetYaxis()->CenterTitle();
+    eff3.SetXTitle("Date");
+    eff3.SetYTitle("Efficiency");
+    eff3.SetTitle("Observation efficiency");
+    eff3.SetMinimum(0);
+    eff3.SetMaximum(1);
+    eff3.SetStats(kFALSE);
+    eff3.DrawCopy("hist");
+    eff4.DrawCopy("histsame");
+
+    d->SaveAs("DataEfficiency.root");
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/plots/plotratescan.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/plots/plotratescan.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/plots/plotratescan.C	(revision 17960)
@@ -0,0 +1,378 @@
+/*void Fit(TGraph &g, double rate_start=3e5, double rate_kink=80, double rate_end=1)
+{
+    double begin = -1;
+    double end   = -1;
+
+    double kinkx = -1;
+    double kinky =  0;
+
+    TGraph gl;
+    for (int j=0; j<g.GetN(); j++)
+    {
+        gl.SetPoint(gl.GetN(), g.GetX()[j], log10(g.GetY()[j]));
+        if (g.GetY()[j]<rate_start && begin<0)
+            begin = g.GetX()[j];
+        if (g.GetY()[j]<rate_end && end<0)
+        {
+            end = g.GetX()[j];
+            //if (end<550)
+            //    end = 750;
+        }
+        if (g.GetY()[j]<rate_kink && kinkx<0)
+        {
+            kinkx = g.GetX()[j];
+            kinky = g.GetY()[j];
+        }
+    }
+
+    if (end==-1)
+        end = 600;//g.GetX()[g.GetN()-1];
+
+    TF1 func2("f2", "log10("
+              "  [1]*exp([2]*(x-[0]))"
+              "+ [1]*exp([3]*(x-[0]))"
+              //"+ [4]*exp([5]*(x-700))"
+              ")", begin, end);
+
+    Double_t v00 = g.Eval(kinkx-150, 0, "S");
+    Double_t v01 = g.Eval(kinkx- 50, 0, "S");
+
+    Double_t v10 = g.Eval(kinkx+100, 0, "S");
+    Double_t v11 = g.Eval(kinkx+200, 0, "S");
+
+    //Double_t v20 = g.Eval(700-50, 0, "S");
+    //Double_t v21 = g.Eval(700,    0, "S");
+    //Double_t v22 = g.Eval(700+50, 0, "S");
+
+    func2.SetParameter(0,  kinkx);
+    func2.SetParameter(1,  kinky);
+    func2.SetParameter(2,  log(v01/v00)/100);
+    func2.SetParameter(3,  log(v11/v10)/100);
+
+    func2.FixParameter(4,  0);
+    func2.FixParameter(5,  0);
+    func2.SetLineWidth(1);
+    func2.SetLineColor(kBlue);
+
+    gl.Fit(&func2, "N0", "", begin, end);
+
+    TF1 func("f1",
+             "[0]*exp([1]*(x-[6])) + "
+             "[2]*exp([3]*(x-[6])) + "
+             "[4]*exp([5]*(x-700))", begin, end);
+    func.FixParameter(0,  func2.GetParameter(1));
+    func.FixParameter(1,  func2.GetParameter(2));
+    func.FixParameter(2,  func2.GetParameter(1));
+    func.FixParameter(3,  func2.GetParameter(3));
+    func.FixParameter(4,  func2.GetParameter(4));
+    func.FixParameter(5,  func2.GetParameter(5));
+    func.FixParameter(6,  func2.GetParameter(0));
+    func.SetLineWidth(2);
+    func.SetLineColor(kBlue);
+    func.DrawClone("same");
+    func.SetLineWidth(1);
+
+    cout << begin << " -- " << end << " : " << kinkx << endl;
+
+    func.SetLineStyle(kDashed);
+    func.SetRange(0, 1000);
+
+    func.FixParameter(0,  0);
+    func.FixParameter(2,  0);
+    func.FixParameter(4,  func2.GetParameter(4));
+    func.DrawClone("same");
+
+    func.FixParameter(0,  func2.GetParameter(1));
+    func.FixParameter(2,  0);
+    func.FixParameter(4,  0);
+    func.DrawClone("same");
+
+    func.FixParameter(0,  0);
+    func.FixParameter(2,  func2.GetParameter(1));
+    func.FixParameter(4,  0);
+    func.DrawClone("same");
+
+
+    TLatex txt;
+    txt.SetTextColor(kBlue);
+    txt.SetTextAlign(33);
+    txt.DrawLatex(func2.GetParameter(0), func2.GetParameter(1),
+                  Form("%.1fHz @ %.0f", func2.GetParameter(1), func2.GetParameter(0)));
+
+    // [1]*exp([2]*(x-[0])) / exp(1)           = [1]*exp([3]*(x-[0]))
+    //     exp([2]*(x-[0])) / exp(1)           =    exp([3]*(x-[0]))
+    //     exp([2]*(x-[0])) / exp([3]*(x-[0])) =    exp(1)
+    //     exp([2]*(x-[0])  -     [3]*(x-[0])) =    exp(1)
+    //         [2]*(x-[0])  -     [3]*(x-[0])  =    1
+    //
+    // x = 1/([2]-[3]) + [0]
+
+
+    Double_t th       = 1. / (func2.GetParameter(3)-func2.GetParameter(2)) + func2.GetParameter(0);
+    Double_t rate     = pow(10, func2.Eval(th));
+    Double_t rate_end = pow(10, func2.Eval(end)-0.5);
+
+    txt.SetTextAlign(11);
+    txt.DrawLatex(th+10, rate, Form("%.1fHz @ %.0f", rate, th));
+
+    txt.SetTextAlign(12);
+    txt.DrawLatex(180, 3e6,      Form("%.1f", 1./func2.GetParameter(2)));
+    txt.DrawLatex(end, rate_end, Form("%.0f", 1./func2.GetParameter(3)));
+
+    TLine line;
+    line.SetLineStyle(kDashed);
+    line.SetLineColor(kBlue);
+    line.DrawLine(th, 1e-2, th, 1e8);
+}*/
+
+Bool_t plot(MSQLMagic &serv, Long64_t search_id, TGraph &g, TGraph *gb)
+{
+    TString query;
+    query += "SELECT fTimeBegin, fTimeEnd, fVoltageIsOn, fOvervoltage, fCurrentMedMean, fNight ";
+    query += "FROM Ratescan WHERE fRatescanID=";
+    query += search_id;
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    if (res->GetRowCount()!=1)
+    {
+        cout << "ERROR - Row count is not 1." << endl;
+        delete res;
+        return kTRUE;
+    }
+
+    TSQLRow *row = res->Next();
+
+    const char *time_beg = (*row)[0];
+    const char *time_end = (*row)[1];
+    const char *night    = (*row)[5];
+
+    int   voltage_on  = (*row)[2] ? atoi((*row)[2]) :   -1;
+    float overvoltage = (*row)[3] ? atof((*row)[3]) : -100;
+    float current     = (*row)[4] ? atof((*row)[4]) :   -1;
+
+    delete row;
+
+    gROOT->SetSelectedPad(0);
+    TCanvas *c = new TCanvas(time_beg+11, time_beg);
+
+    c->SetGrid();
+    c->SetLogy();
+    c->SetTopMargin(0.01);
+    c->SetRightMargin(0.005);
+
+    TPaveText leg(600, 1e5, 1050, 8e8, "br");
+    leg.SetBorderSize(1);
+    leg.SetFillColor(kWhite);
+    leg.AddText("Ratescan");
+    leg.AddText("");
+    leg.AddText(Form("Begin    %s", time_beg));
+    leg.AddText(Form("End       %s", time_end));
+    leg.AddText("");
+    if (voltage_on==0)
+        leg.AddText("Voltage off");
+    else
+    {
+        if (current>=0)
+            leg.AddText(Form("Current     <I_{med}>  =  %.1f #muA", current));
+        if (overvoltage>-70)
+            leg.AddText(Form("Voltage         #DeltaU  =  %+.2f V", overvoltage));
+    }
+
+    TH1D h0("frame", "", 1050, 0, 1050);
+    h0.SetDirectory(0);
+    h0.SetStats(kFALSE);
+    h0.SetXTitle("Threshold [dac counts]");
+    h0.SetYTitle("Trigger rate [Hz]");
+    h0.GetXaxis()->SetLabelSize(0.05);
+    h0.GetXaxis()->SetTitleSize(0.05);
+    h0.GetYaxis()->SetLabelSize(0.05);
+    h0.GetYaxis()->SetTitleSize(0.05);
+    h0.SetMaximum(8e8);
+    h0.SetMinimum(0.61);
+    h0.DrawCopy();
+
+    leg.DrawClone();
+
+    for (int i=0; i<40; i++)
+    {
+        gb[i].SetNameTitle(Form("Board%02d", i), "Board trigger rate (time 40)");
+        gb[i].DrawClone("P");
+    }
+
+    g.SetMarkerStyle(kFullDotMedium);
+    g.SetMarkerColor(kBlue);
+    g.SetLineColor(kBlue);
+    g.SetNameTitle("Camera", "Camera trigger rate");
+    g.DrawClone("PL");
+
+    c->Write();
+
+    TString name;
+    name += night;
+    name += "-ratescan ";
+    name += time_beg;
+
+    c->SaveAs(name+".pdf");
+    c->SaveAs(name+".eps");
+    c->SaveAs(name+".png");
+
+    delete c;
+}
+
+Int_t plotid(MSQLMagic &serv, fits &file, const char *_search_id, Int_t row)
+{
+    Long64_t search_id = atol(_search_id);
+
+    cout << "   " << search_id << endl;
+
+    UInt_t offset = file.GetUInt("MJDREF");
+
+    bool old = file.HasColumn("Data0");
+
+    Double_t  *ptime   = file.SetPtrAddress("Time");
+    UInt_t    *pid     = file.SetPtrAddress(old ? "Data0" : "Id");
+    Float_t   *rates   = file.SetPtrAddress(old ? "Data5" : "BoardRate");
+    UInt_t    *pth     = file.SetPtrAddress(old ? "Data1" : "Threshold");
+    Float_t   *ptrig   = file.SetPtrAddress(old ? "Data4" : "TriggerRate");
+    Float_t   *pontime = file.SetPtrAddress(old ? "Data3" : "RelOnTime");
+
+    if (!ptime || !pid || !rates || !pth || !ptrig || !pontime)
+        return -1;
+
+    TGraph g;
+    TGraph gb[40];
+
+    while (file.GetRow(row++))
+    {
+        if (pid[0]<search_id)
+            continue;
+
+        if (pid[0]!=search_id)
+            break;
+
+        g.SetPoint(g.GetN(), pth[0], ptrig[0]/pontime[0]);
+        for (int i=0; i<40; i++)
+            gb[i].SetPoint(gb[i].GetN(), pth[0], rates[i]*40);
+    }
+
+    if (g.GetN()>0)
+        plot(serv, search_id, g, gb);
+
+    return row;
+
+
+}
+
+Bool_t plotratescan(MSQLMagic &serv, const char *_night)
+{
+    Long64_t night = atol(_night);
+
+    TString fname = Form("/fact/aux/%04d/%02d/%02d/%06d.RATE_SCAN_DATA.fits",
+                         night/10000, (night/100)%100, night%100, night);
+
+    cout << "   " << fname << endl;
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cout << "ERROR - Cannot access " << fname << ": " << gSystem->GetError() << endl;
+        return kFALSE;
+    }
+
+    TString query;
+    query += "SELECT fRatescanID FROM Ratescan WHERE fNight=";
+    query += night;
+    query += " ORDER BY fRatescanID";
+    /*
+    query += "SELECT fRatescanID, fTimeBeg, fTimeEnd, fVoltageIsOn, ";
+    query += "       fOvervoltage, fCurrentMedMean, fRateBegin, fRateEnd, ";
+    query += "       fThresholdBegin, fThresholdEnd, fNumPoints ";
+    query += "WHERE fNight=";
+    query += night;
+     */
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    if (res->GetRowCount()==0)
+    {
+        delete res;
+        return kTRUE;
+    }
+
+    TString oname = Form("%06d-ratescan.root", night);
+
+    cout << "   " << oname << '\n' << endl;
+
+    TFile rootfile(oname.Data(), "recreate");
+
+    TSQLRow *row = 0;
+
+    Int_t cnt = 0;
+    while ((row=res->Next()) && cnt>=0)
+    {
+        const char *id = (*row)[0];
+        cnt = plotid(serv, file, id, cnt);
+        delete row;
+    }
+
+    delete res;
+
+    cout << endl;
+
+    return cnt>=0;
+}
+
+Bool_t plotratescan(const char *night)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotratescan" << endl;
+    cout << "------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Night: " << night << endl;
+    cout << endl;
+
+    return plotratescan(serv, night);
+}
+
+Bool_t plotratescan()
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "plotratescan" << endl;
+    cout << "------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    TSQLResult *res = serv.Query("SELECT fNight FROM Ratescan GROUP BY fNight ORDER BY fNight");
+    if (!res)
+        return kFALSE;
+
+    TSQLRow *row = 0;
+    while ((row=res->Next()))
+    {
+        const char *night = (*row)[0];
+        plotratescan(serv, night);
+        delete row;
+    }
+
+    delete res;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/fact/plots/quality.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/plots/quality.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/plots/quality.C	(revision 17960)
@@ -0,0 +1,752 @@
+#include <algorithm>
+#include <functional>
+
+Bool_t Contains(TArrayD **vec, Double_t t0, Double_t range=0)
+{
+    TArrayD *arr0 = vec[0];
+    TArrayD *arr1 = vec[1];
+    TArrayD *arr2 = vec[2];
+
+    for (int i=0; i<arr0->GetSize(); i++)
+    {
+        Double_t start = (*arr1)[i];
+        Double_t stop  = (*arr2)[i];
+
+        if (stop>start+305./24/3600)
+            stop = start+305./24/3600;
+
+        if (t0>start-range && t0<stop+range)
+        //{
+        //    if (fmod(t0, 1)>4./24 && fmod(t0,1)<4.1/24)
+        //        cout << t0-start << " " <<t0 << " " << stop-t0 << " " << start-15779 << " " << stop-15779 << " " << (*arr0)[i] << endl;
+            return kTRUE;
+        //}
+    }
+
+    return arr0->GetSize()==0;
+}
+
+Int_t PlotThresholds(TArrayD **vec, TString fname)
+{
+    fname += ".RATE_CONTROL_THRESHOLD.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    UShort_t th;
+
+    if (!file.SetPtrAddress("Time", &time))
+        return -1;
+
+    if (!file.SetPtrAddress("threshold", &th))
+        return -1;
+
+    TGraph g;
+    g.SetName("Threshold");
+
+    while (file.GetNextRow())
+    {
+        if (Contains(vec, time, 10./(24*3600)))
+            g.SetPoint(g.GetN(), time*24*3600, th);
+    }
+
+    g.SetMinimum(281);
+    g.SetMarkerStyle(kFullDotMedium);
+    g.GetXaxis()->SetTimeDisplay(true);
+    g.GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    g.GetXaxis()->SetLabelSize(0.12);
+    g.GetYaxis()->SetLabelSize(0.1);
+    g.GetYaxis()->SetTitle("THRESHOLD");
+    g.GetYaxis()->SetTitleOffset(0.2);
+    g.GetYaxis()->SetTitleSize(0.1);
+    g.DrawClone("AP");
+
+    return 0;
+}
+
+#include <vector>
+#include <pair>
+
+vector<pair<double, Nova::EquPosn>> vecp;
+
+Nova::EquPosn FindPointing(Double_t time)
+{
+    for (int i=0; i<vecp.size(); i++)
+        if (time<vecp[i].first)
+        {
+            if (i==0)
+                return Nova::EquPosn();
+            else
+                return vecp[i-1].second;
+        }
+
+    return vecp[vecp.size()-1].second;
+}
+
+Float_t Prediction(Double_t time)
+{
+    Double_t jd = time + 40587 + 2400000.5;
+
+    // Sun properties
+    Nova::EquPosn  sun  = Nova::GetSolarEquCoords(jd);
+    Nova::ZdAzPosn hrzs = Nova::GetHrzFromEqu(sun, jd);
+
+    // Get source position
+    Nova::EquPosn pos = FindPointing(time);
+
+    // Moon properties
+    Nova::EquPosn moon = Nova::GetLunarEquCoords(jd, 0.01);
+    Nova::HrzPosn hrzm = Nova::GetHrzFromEqu(moon, jd);
+    double        disk = Nova::GetLunarDisk(jd);
+
+    // Derived moon properties
+    double angle = Nova::GetAngularSeparation(moon, pos);
+    double edist = Nova::GetLunarEarthDist(jd)/384400;
+
+    // Current prediction
+    double sin_malt  = hrzm.alt<0 ? 0 : sin(hrzm.alt*TMath::DegToRad());
+    double cos_mdist = cos(angle*TMath::DegToRad());
+    double sin_szd   = sin(hrzs.zd*TMath::DegToRad());
+
+    double c0 = pow(disk,      2.63);
+    double c1 = pow(sin_malt,  0.60);
+    double c2 = pow(edist,    -2.00);
+    double c3 = exp(0.67*cos_mdist*cos_mdist*cos_mdist*cos_mdist);
+    double c4 = exp(-97.8+105.8*sin_szd*sin_szd);
+
+    double cur = 6.2 + 95.7*c0*c1*c2*c3 + c4;
+
+    return cur;
+}
+
+Int_t ReadSources(TString fname)
+{
+    fname += ".DRIVE_CONTROL_SOURCE_POSITION.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    Double_t time, ra, dec;
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+    if (!file.SetPtrAddress("Ra_cmd", &ra))
+        return -1;
+    if (!file.SetPtrAddress("Dec_cmd", &dec))
+        return -1;
+
+    while (file.GetNextRow())
+    {
+        Nova::EquPosn p;
+        p.ra  = ra*15;
+        p.dec = dec;
+
+        vecp.push_back(make_pair(time, p));
+    }
+
+    return 0;
+}
+
+Int_t PlotCurrent(TArrayD **vec, TString fname)
+{
+    Int_t rc = ReadSources(fname);
+    if (rc<0)
+        return rc;
+
+    fname += ".FEEDBACK_CALIBRATED_CURRENTS.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  Imed;
+    Float_t  Idev;
+    Float_t  I[416];
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+
+    if (!file.SetPtrAddress("I_med", &Imed))
+        return -1;
+
+    if (!file.SetPtrAddress("I_dev", &Idev))
+        return -1;
+
+    if (!file.SetPtrAddress("I", I))
+        return -1;
+
+    TGraph g1;
+    TGraph g2;
+    TGraph g3;
+    TGraph g4;
+    TGraph g5;
+    g1.SetName("CurrentsMed");
+    g2.SetName("Prediction");
+    g3.SetName("CurrentsDev");
+    g4.SetName("CurrentsMax-4");
+    g5.SetName("CurrentsMax");
+
+    while (file.GetNextRow())
+        if (Contains(vec, time))
+        {
+            // crazy pixels
+            I[66]  = 0;
+            I[191] = 0;
+            I[193] = 0;
+
+            sort(I, I+320);
+
+            g1.SetPoint(g1.GetN(), time*24*3600, Imed);
+            g2.SetPoint(g2.GetN(), time*24*3600, Prediction(time));
+            g3.SetPoint(g3.GetN(), time*24*3600, Imed+Idev);
+            g4.SetPoint(g4.GetN(), time*24*3600, I[315]);
+            g5.SetPoint(g5.GetN(), time*24*3600, I[319]);
+        }
+
+    g1.SetMinimum(0);
+    g1.SetMaximum(149);
+
+    g1.SetMarkerStyle(kFullDotMedium);
+    g1.GetXaxis()->SetTimeDisplay(true);
+    g1.GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    g1.GetXaxis()->SetLabelSize(0.12);
+    g1.GetYaxis()->SetLabelSize(0.1);
+    g1.GetYaxis()->SetTitle("CURRENT");
+    g1.GetYaxis()->SetTitleOffset(0.2);
+    g1.GetYaxis()->SetTitleSize(0.1);
+    g1.DrawClone("AP");
+
+    g5.SetMarkerColor(kGray);
+    g5.DrawClone("P");
+
+    g4.SetMarkerColor(kGray+1);
+    g4.DrawClone("P");
+
+    g3.SetMarkerColor(kGray+2);
+    g3.DrawClone("P");
+
+    g2.SetMarkerColor(kBlue);
+    g2.SetMarkerStyle(kFullDotMedium);
+    g2.DrawClone("P");
+
+    g1.DrawClone("P");
+
+    return 0;
+}
+
+Int_t PlotRate(TArrayD **vec, TString fname)
+{
+    fname += ".FTM_CONTROL_TRIGGER_RATES.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  rate;
+    Float_t  ontime, elapsed;
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+
+    if (!file.SetPtrAddress("TriggerRate", &rate))
+        return -1;
+    if (!file.SetPtrAddress("OnTime", &ontime))
+        return -1;
+    if (!file.SetPtrAddress("ElapsedTime", &elapsed))
+        return -1;
+
+    TGraph g1, g2;
+    g1.SetName("TriggerRate");
+    g2.SetName("RelOnTime");
+
+    while (file.GetNextRow())
+        if (Contains(vec, time))
+        {
+            if (rate>=0)
+            {
+                g1.SetPoint(g1.GetN(), time*24*3600, rate);
+                g2.SetPoint(g2.GetN(), time*24*3600, ontime/elapsed);
+            }
+        }
+
+    g1.SetMinimum(0);
+    g1.SetMaximum(269);
+    g1.SetMarkerStyle(kFullDotMedium);
+    g1.GetXaxis()->SetTimeDisplay(true);
+    g1.GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    g1.GetXaxis()->SetLabelSize(0.12);
+    g1.GetYaxis()->SetLabelSize(0.1);
+    g1.GetYaxis()->SetTitle("TRIGGER RATE");
+    g1.GetYaxis()->SetTitleOffset(0.2);
+    g1.GetYaxis()->SetTitleSize(0.1);
+    g1.DrawClone("AP");
+
+    gROOT->SetSelectedPad(0);
+    gPad->GetCanvas()->cd(4);
+
+    gPad->SetGrid();
+    gPad->SetTopMargin(0);
+    gPad->SetBottomMargin(0);
+    gPad->SetRightMargin(0.001);
+    gPad->SetLeftMargin(0.04);
+
+    g2.SetMinimum(0);
+    g2.SetMaximum(1);
+    g2.SetMarkerStyle(kFullDotMedium);
+    g2.GetXaxis()->SetTimeDisplay(true);
+    g2.GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    g2.GetXaxis()->SetLabelSize(0.12);
+    g2.GetYaxis()->SetLabelSize(0.1);
+    g2.GetYaxis()->SetTitle("RELATIVE ON TIME");
+    g2.GetYaxis()->SetTitleOffset(0.2);
+    g2.GetYaxis()->SetTitleSize(0.1);
+    g2.DrawClone("AP");
+
+    return 0;
+}
+
+void PlotRateQC(UInt_t night, MSQLServer &serv)
+{
+    TString query = 
+        "LEFT JOIN AnalysisResultsRunLP USING(fNight, fRunID) "
+        "WHERE fRunTypeKey=1 AND NOT ISNULL (AnalysisResultsRunLP.fNumEvtsAfterCleaning) AND fNight=";
+    query += night;
+
+    TTree *t = serv.GetTree("RunInfo", query);
+    if (!t)
+        return;
+
+    int save = gErrorIgnoreLevel;
+    gErrorIgnoreLevel = kFatal;
+
+    gROOT->SetSelectedPad(0);
+    gPad->GetCanvas()->cd(3);
+
+    t->Draw("AnalysisResultsRunLP.fNumEvtsAfterCleaning/AnalysisResultsRunLP.fOnTimeAfterCuts:(RunInfo.fRunStart+RunInfo.fRunStop)/2+9131*24*3600", "", "same");
+    TGraph *g = (TGraph*)gPad->GetPrimitive("Graph");
+    if (g)
+    {
+        g->SetName("CleaningRate");
+        g->SetMarkerColor(kRed);
+        g->SetMarkerStyle(29);//kFullDotMedium);
+    }
+
+    t->Draw("AnalysisResultsRunLP.fNumEvtsAfterQualCuts/AnalysisResultsRunLP.fOnTimeAfterCuts:(RunInfo.fRunStart+RunInfo.fRunStop)/2+9131*24*3600", "", "same");
+    g = (TGraph*)gPad->GetPrimitive("Graph");
+    if (g)
+    {
+        g->SetName("RateAfterQC");
+        g->SetMarkerColor(kBlue);
+        g->SetMarkerStyle(29);//kFullDotMedium);
+    }
+
+    gErrorIgnoreLevel = save;
+}
+
+
+Int_t PlotPointing(TArrayD **vec, TString fname)
+{
+    fname += ".DRIVE_CONTROL_POINTING_POSITION.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Double_t zd;
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+    if (!file.SetPtrAddress("Zd", &zd))
+        return -1;
+
+    TGraph g;
+    g.SetName("Zd");
+
+    while (file.GetNextRow())
+        if (Contains(vec, time))
+            g.SetPoint(g.GetN(), time*24*3600, 90-zd);
+
+    g.SetMinimum(1);
+    g.SetMaximum(90);
+    g.SetMarkerStyle(kFullDotMedium);
+    g.GetXaxis()->SetTimeDisplay(true);
+    g.GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    g.GetXaxis()->SetLabelSize(0.12);
+    g.GetYaxis()->SetLabelSize(0.1);
+    g.GetYaxis()->SetTitle("ELEVATION");
+    g.GetYaxis()->SetTitleOffset(0.2);
+    g.GetYaxis()->SetTitleSize(0.1);
+    g.DrawClone("AP");
+
+    return 0;
+}
+
+Int_t PlotTemperature1(TArrayD **vec, TString fname)
+{
+    fname += ".TEMPERATURE_DATA.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  temp;
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+    if (!file.SetPtrAddress("T", &temp))
+        return -1;
+
+    TGraph g;
+    g.SetName("ContainerTemp");
+
+    while (file.GetNextRow())
+        if (Contains(vec, time))
+            g.SetPoint(g.GetN(), time*24*3600, temp);
+
+    g.SetMinimum(-5);
+    g.SetMaximum(49);
+    g.SetMarkerStyle(kFullDotMedium);
+    g.SetMarkerColor(kRed);
+    g.GetXaxis()->SetTimeDisplay(true);
+    g.GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    g.GetXaxis()->SetLabelSize(0.1);
+    g.GetYaxis()->SetLabelSize(0.1);
+    g.GetYaxis()->SetTitle("TEMP");
+    g.GetYaxis()->SetTitleOffset(0.2);
+    g.GetYaxis()->SetTitleSize(0.1);
+    g.DrawClone("AP");
+
+    return 0;
+}
+
+Int_t PlotTemperature2(TArrayD **vec, TString fname)
+{
+    fname += ".MAGIC_WEATHER_DATA.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  temp;
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+    if (!file.SetPtrAddress("T", &temp))
+        return -1;
+
+    TGraph g;
+    g.SetName("OutsideTemp");
+
+    while (file.GetNextRow())
+        if (Contains(vec, time))
+            g.SetPoint(g.GetN(), time*24*3600, temp);
+
+    g.SetMarkerStyle(kFullDotMedium);
+    g.SetMarkerColor(kBlue);
+    g.DrawClone("P");
+
+    return 0;
+}
+
+Int_t PlotTemperature3(TArrayD **vec, TString fname)
+{
+    fname += ".FSC_CONTROL_TEMPERATURE.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  temp[31];
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+    if (!file.SetPtrAddress("T_sens", temp))
+        return -1;
+
+    TGraph g, g1, g2;
+    g.SetName("SensorTempAvg");
+    g1.SetName("SensorTempMin");
+    g2.SetName("SensorTempMax");
+
+    while (file.GetNextRow())
+        if (Contains(vec, time))
+        {
+            float min =  100;
+            float max = -100;
+            double avg = 0;
+            int num = 0;
+            for (int i=0; i<31; i++)
+                if (temp[i]!=0)
+                {
+                    avg += temp[i];
+                    num++;
+
+                    min = TMath::Min(min, temp[i]);
+                    max = TMath::Max(max, temp[i]);
+                }
+
+            g.SetPoint(g.GetN(), time*24*3600, avg/num);
+            g1.SetPoint(g1.GetN(), time*24*3600, min);
+            g2.SetPoint(g2.GetN(), time*24*3600, max);
+        }
+
+    g.SetMarkerStyle(kFullDotMedium);
+    g.DrawClone("P");
+
+    /*
+     g1.SetLineWidth(1);
+     g1.DrawClone("L");
+
+     g2.SetLineWidth(1);
+     g2.DrawClone("L");
+    */
+    return 0;
+}
+
+Int_t PlotTemperature4(TArrayD **vec, TString fname)
+{
+    fname += ".FAD_CONTROL_TEMPERATURE.fits";
+
+    fits file(fname.Data());
+    if (!file)
+    {
+        cerr << fname << ": " << gSystem->GetError() << endl;
+        return -2;
+    }
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  temp[160];
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+    if (!file.SetPtrAddress("Data1", temp) &&
+        !file.SetPtrAddress("temp", temp))
+        return -1;
+
+    Int_t num = file.GetN("temp")==0 ? file.GetN("Data1") : file.GetN("temp");
+    Int_t beg = num==82 ? 2 : 0;
+
+    TGraphErrors g1;
+    TGraph g2,g3;
+
+    g1.SetName("FadTempAvg");
+    g2.SetName("FadTempMin");
+    g3.SetName("FadTempMax");
+
+    while (file.GetNextRow())
+        if (Contains(vec, time))
+        {
+            double avg = 0;
+            double rms = 0;
+            float min =  100;
+            float max = -100;
+            for (int i=beg; i<num; i++)
+            {
+                avg += temp[i];
+                rms += temp[i]*temp[i];
+
+                min = TMath::Min(min, temp[i]);
+                max = TMath::Max(max, temp[i]);
+            }
+
+            avg /= num-beg;
+            rms /= num-beg;
+
+            g1.SetPoint(g1.GetN(), time*24*3600, avg);
+            g1.SetPointError(g1.GetN()-1, 0, sqrt(rms-avg*avg));
+
+            g2.SetPoint(g2.GetN(), time*24*3600, min);
+            g3.SetPoint(g3.GetN(), time*24*3600, max);
+        }
+
+    g1.SetLineColor(kGreen);
+    g1.DrawClone("[]");
+
+    g2.SetLineColor(kGreen);
+    g2.SetLineWidth(1);
+    g2.DrawClone("L");
+
+    g3.SetLineColor(kGreen);
+    g3.SetLineWidth(1);
+    g3.DrawClone("L");
+
+    return 0;
+}
+
+int quality(UInt_t y=0, UInt_t m=0, UInt_t d=0, const char *outpath="quality")
+{
+    // To get correct dates in the histogram you have to add
+    // the MJDREF offset (should be 40587) and 9131.
+
+    if (y==0)
+    {
+        UInt_t nt = MTime(MTime(-1).GetMjd()-1.5).GetNightAsInt();
+        y =  nt/10000;
+        m = (nt/100)%100;
+        d =  nt%100;
+
+        cout << y << "/" << m << "/" << d << endl;
+    }
+
+    TString fname=Form("/fact/aux/%04d/%02d/%02d/%04d%02d%02d", y, m, d, y, m, d);
+
+    UInt_t night = MTime(y, m, d, 0).GetNightAsInt();
+
+    MSQLMagic serv("sql.rc");
+    Bool_t con = serv.IsConnected();
+
+    cout << "quality" << endl;
+    cout << "-------" << endl;
+    cout << endl;
+    if (con)
+    {
+        cout << "Connected to " << serv.GetName() << endl;
+        cout << endl;
+    }
+    cout << "Night: " << Form("%04d-%02d-%02d", y, m, d) << endl;
+    cout << endl;
+
+    TArrayD run, beg, end;
+
+    TArrayD *runs[3] = { &run, &beg, &end };
+
+    if (con)
+    {
+        TString query;
+        query += "SELECT fRunID, fRunStart, fRunStop FROM RunInfo";
+        query += " WHERE fNight=";
+        query += night;
+        query += " AND fRunTypeKey=1 ORDER BY fRunStart";
+
+        TSQLResult *res = serv.Query(query);
+        if (!res)
+            return 1;
+
+        run.Set(res->GetRowCount());
+        beg.Set(res->GetRowCount());
+        end.Set(res->GetRowCount());
+
+        Int_t n = 0;
+
+        TSQLRow *row = 0;
+        while ((row=res->Next()))
+        {
+            run[n] = atoi((*row)[0]);
+            beg[n] = MTime((*row)[1]).GetMjd()-40587;
+            end[n] = MTime((*row)[2]).GetMjd()-40587;
+            n++;
+            delete row;
+        }
+
+        delete res;
+
+        if (n==0)
+            cout << "WARNING - No data runs in db, displaying all data." << endl;
+        else
+            cout << "Num: " << n << "\n" << endl;
+    }
+
+    TCanvas *c = new TCanvas("quality", Form("Quality %04d/%02d/%02d", y, m, d), 1280, 960);
+    c->Divide(1, 6, 1e-5, 1e-5);
+
+    gROOT->SetSelectedPad(0);
+
+    c->cd(1);
+    gPad->SetGrid();
+    gPad->SetTopMargin(0);
+    gPad->SetRightMargin(0.001);
+    gPad->SetLeftMargin(0.04);
+    gPad->SetBottomMargin(0);
+    cout << PlotThresholds(runs, fname) << endl;
+
+    gROOT->SetSelectedPad(0);
+    c->cd(2);
+    gPad->SetGrid();
+    gPad->SetTopMargin(0);
+    gPad->SetRightMargin(0.001);
+    gPad->SetLeftMargin(0.04);
+    gPad->SetBottomMargin(0);
+    cout << PlotCurrent(runs, fname) << endl;
+
+    gROOT->SetSelectedPad(0);
+    c->cd(3);
+    gPad->SetGrid();
+    gPad->SetTopMargin(0);
+    gPad->SetBottomMargin(0);
+    gPad->SetRightMargin(0.001);
+    gPad->SetLeftMargin(0.04);
+    cout << PlotRate(runs, fname) << endl;
+    cout << PlotRateQC(night, serv) << endl;
+
+    gROOT->SetSelectedPad(0);
+    c->cd(5);
+    gPad->SetGrid();
+    gPad->SetTopMargin(0);
+    gPad->SetBottomMargin(0);
+    gPad->SetRightMargin(0.001);
+    gPad->SetLeftMargin(0.04);
+    cout << PlotPointing(runs, fname) << endl;
+
+    gROOT->SetSelectedPad(0);
+    c->cd(6);
+    gPad->SetGrid();
+    gPad->SetTopMargin(0);
+    gPad->SetRightMargin(0.001);
+    gPad->SetLeftMargin(0.04);
+    cout << PlotTemperature1(runs, fname) << endl;
+    cout << PlotTemperature2(runs, fname) << endl;
+    cout << PlotTemperature3(runs, fname) << endl;
+    cout << PlotTemperature4(runs, fname) << endl;
+
+    c->SaveAs(Form("%s/%04d%02d%02d.png", outpath, y, m, d));
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/buildseqentries.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/buildseqentries.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/buildseqentries.C	(revision 17960)
@@ -0,0 +1,1423 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// buildsequenceentries.C
+// ======================
+//
+// to group the runs of one night into sequences, this marco:
+//  - reads the runinformation of one night from the database
+//  - group the runs into sets of following runs with the same conditions
+//  - groups the runs in this sets to sequences such that each run belongs
+//    to the nearest (in time) calibration run
+//  - check if the runs with the same runtype have the same calibration script
+//    and the same trigger tables
+//  if sequence is okay:
+//  - check if in the range of the runnumbers of this sequence other sequences
+//    exist in the database
+//  if there are no sequences, insert the new sequence, else:
+//  - delete overlaping sequences
+//  if there's only one sequence in the same runnumber range:
+//  - check if the new and the old sequence are identical
+//    if they are identical, do nothing, if not, delete the old sequence and
+//    insert the new one
+//
+// remark: deleting sequences includes the following steps:
+// - delete entries from the tables Sequences, SequenceProcessStatus,
+//   Calibration and Star
+// - updating the sequence number (fSequenceFirst) in the table RunData
+// - remove the Sequence File, the calibrated data and the image files from
+//   the disk
+//
+// the macro can be executed either for all nights or for one single night
+// .x buildsequenceentries.C+( "datapath", "sequpath", Bool_t dummy=kTRUE)
+// .x buildsequenceentries.C+( "night", "datapath", "sequpath")
+//
+// the Bool_t dummy:
+//  kTRUE:  dummy-mode, i.e. nothing is inserted into the database, but the
+//          commands, that would be executed are returned
+//  kFALSE: the information is inserted into the database and the files of
+//          removed sequences is deleted
+// be careful with this option - for tests use always kTRUE
+//
+// TString datapath, TString sequpath:
+//  datapath: path, where the processed data is stored in the datacenter
+//  sequpath: path, where the sequence files are stored in the datacenter
+// the datapath (standard: /magic/data/) and the sequencepath (standard:
+// /magic/sequences) have to be given, that the sequence file, the
+// calibrated data and the star files can be removed, when an old sequence
+// has to be removed from the database
+//
+// If nothing failes 1 is returned. In the case of an error 2 and if
+// there's no connection to the database 0 is returned.
+// This is needed for the scripts that execute the macro.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <map>
+#include <utility>
+
+#include <errno.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include <TEnv.h>
+#include <TMap.h>
+#include <TMath.h>
+#include <TExMap.h>
+#include <TArrayI.h>
+#include <TArrayL.h>
+#include <TArrayD.h>
+#include <TPRegexp.h>
+#include <TSystem.h>
+#include <TObjString.h>
+#include <TObjArray.h>
+
+#include "MTime.h"
+#include "MSequence.h"
+
+#include "MSQLMagic.h"
+
+using namespace std;
+
+    /*static*/ ULong_t GetId(const TString str)
+    {
+        const Ssiz_t dot = str.First('.');
+
+        const UInt_t run = str.Atoi();
+        const UInt_t sub = dot<0 ? 0 : atoi(str.Data()+dot+1);
+
+        return ULong_t(run)*1000+sub;
+    }
+
+
+class Rule : public TObject
+{
+private:
+    TPRegexp fRegexp;
+
+    ULong_t fMin;
+    ULong_t fMax;
+
+public:
+    Rule(TObjArray &arr) :
+        fRegexp(arr.GetEntries()>0?Form("^%s", arr[0]->GetName()):""),
+            fMin(0), fMax((ULong_t)-1)
+    {
+        if (arr.GetEntries()>1)
+            fMin = GetId(arr[1]->GetName());
+        if (arr.GetEntries()>2)
+            fMax = GetId(arr[2]->GetName());
+    }
+
+    Ssiz_t Match(const TString &str, Int_t idx, Long_t run=-1)
+    {
+        if (!IsValid(run))
+            return 0;
+
+        TString mods;
+        TArrayI pos;
+        fRegexp.Match(str.Data()+idx, mods, 0, str.Length()*10, &pos);
+
+        return pos.GetSize()<2 ? 0 : pos[1]-pos[0];
+    }
+
+    Bool_t IsValid(ULong_t run) const { return run>=fMin && run<=fMax; }
+    ClassDef(Rule, 0)
+};
+ClassImp(Rule);
+
+class CheckMatch : public TObject
+{
+private:
+    TPRegexp fRunType1;
+    TPRegexp fRunType2;
+
+    TPRegexp fRegexp1;
+    TPRegexp fRegexp2;
+
+    ULong_t fMin;
+    ULong_t fMax;
+
+    void Init(const TObjArray &arr, Int_t idx=0)
+    {
+        const Int_t n = arr.GetEntries();
+
+        const Bool_t isminus = n>idx && TString(arr[idx]->GetName())=="-";
+
+        for (int i=0; i<n-idx; i++)
+        {
+            //cout << arr[i+idx]->GetName() << " ";
+
+            TString str(arr[i+idx]->GetName());
+            if (str=="*")
+                str = ".*";
+
+            switch (isminus && i>1 ? i+1 : i)
+            {
+            case 0: fRunType1 = TPRegexp(Form(isminus?"-":"^%s$", str.Data())); break;
+            case 1: fRunType2 = TPRegexp(Form("^%s$", str.Data())); break;
+            case 2: fRegexp1  = TPRegexp(Form("^%s$", str.Data())); break;
+            case 3: fRegexp2  = TPRegexp(Form("^%s$", str.Data())); break;
+            case 4: fMin      = GetId(str);               break;
+            case 5: fMax      = GetId(str);               break;
+            }
+        }
+    }
+
+public:
+    CheckMatch() : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2("") {}
+
+    CheckMatch(const TString &txt) : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2(""), fMin(0), fMax((ULong_t)-1)
+    {
+        TObjArray *arr = txt.Tokenize(" ");
+        Init(*arr);
+        delete arr;
+    }
+
+    CheckMatch(TObjArray &arr, Int_t idx=0) : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2(""), fMin(0), fMax((ULong_t)-1)
+    {
+        Init(arr, idx);
+    }
+
+    CheckMatch(const char *from, const char *to, Long_t min=0, Long_t max=-1)
+        : fRunType1(".*"), fRunType2(".*"), fRegexp1(Form("^%s$", from)), fRegexp2(Form("^%s$", to)), fMin(min), fMax(max)
+    {
+    }
+
+    Int_t Matches(const TString &rt1, const TString &rt2, const TString &lc1, const TString &lc2, ULong_t run=0)
+    {
+        if (run>0)
+        {
+            if (run<fMin || run>fMax)
+                return kFALSE;
+        }
+
+        const TString test("X-"); // FIXME:STUPID!
+
+        //if (test.Index(fRunType2)==1)
+         //   return -(!rt1(fRunType1).IsNull() && !lc1(fRegexp1).IsNull());
+
+        if (test.Index(fRunType1,0)==1)
+            return -(!rt2(fRunType2).IsNull() && !lc2(fRegexp2).IsNull());
+
+        return !rt1(fRunType1).IsNull() && !rt2(fRunType2).IsNull() && !lc1(fRegexp1).IsNull() && !lc2(fRegexp2).IsNull();
+    }
+    ClassDef(CheckMatch,0)
+};
+ClassImp(CheckMatch);
+
+class CheckList : public TList
+{
+public:
+    CheckList() { SetOwner(); }
+    Int_t Matches(const TString &rt1, const TString &rt2, const TString &lc1, const TString &lc2, Long_t run=-1) const
+    {
+        TIter Next(this);
+
+        CheckMatch *check = 0;
+
+        while ((check=(CheckMatch*)Next()))
+        {
+            const Int_t rc = check->Matches(rt1, rt2, lc1, lc2, run);
+            if (rc)
+                return rc;
+        }
+
+        return kFALSE;
+    }
+    ClassDef(CheckList,0)
+};
+ClassImp(CheckList);
+
+class SequenceBuild : public MSQLMagic
+{
+private:
+    TString fPathRawData;
+    TString fPathSequences;
+
+    Int_t fTelescopeNumber;
+
+    TMap  fMap;
+    TList fListRegexp;
+
+    Int_t CheckTransition(TSQLResult &res, const TString *keys, TSQLRow &row, Int_t i)
+    {
+        // Get the name of the column from result table
+        const TString key = res.GetFieldName(i);
+
+        // Get the list with the allowed attributed from the map
+        CheckList *list = dynamic_cast<CheckList*>(fMap.GetValue(key));
+        if (!list)
+            return kFALSE;
+
+        // Check whether the current run (row[0]) with the current attribute
+        // (row[i]) and the current run-type (row[1]) matches the attribute
+        // of the last run (keys[i] with run-type row[i])
+        return list->Matches(keys[1], row[1], keys[i], row[i], atol(row[0]));
+    }
+
+    Bool_t InsertSequence(std::pair<Long_t,Long_t> drs, Long_t from, Long_t to, const TString &cond)
+    {
+        //cout << "     - Inserting Sequence into database." << endl;
+
+        TString query;
+        query  = "SELECT fNight, STR_TO_DATE(fNight,'%Y%m%d') ";
+        query += " FROM RunInfo WHERE ";
+        query += cond;
+        query += Form(" AND fRunID=%ld", from);
+
+        TSQLResult *res = Query(query);
+        if (!res)
+            return kFALSE;
+
+        if (res->GetFieldCount()!=2 || res->GetRowCount()!=1)
+        {
+            cout << "ERROR - Wrong result from query: " << query << endl;
+            return kFALSE;
+        }
+
+        TSQLRow *row = res->Next();
+
+        UInt_t  run = atoi((*row)[0]);
+        TString day = (*row)[1];
+
+        delete res;
+
+        query  = "SELECT fRunID, fRunTypeKEY, fHasDrsFile, fDrsStep ";
+        query += " FROM RunInfo WHERE ";
+        query += cond;
+        query += Form(" AND fRunID BETWEEN %ld AND %ld ORDER BY fRunID", from, to);
+
+        if (!(res = Query(query)))
+            return kFALSE;
+
+        if (res->GetFieldCount()!=4)
+        {
+            cout << "ERROR - Wrong result from query: " << query << endl;
+            return kFALSE;
+        }
+
+        MSequence seq("sequence.def", "", (run%1000000)*1000+from);
+        seq.SetNight(day);
+
+        if (drs.first!=from)
+        {
+            seq.SetDrsSequence(drs.first);
+            if (drs.second!=-1)
+                seq.AddFile(drs.second, -1, MSequence::kDrsFile);
+        }
+
+        while ((row=res->Next()))
+        {
+            UInt_t num = atol((*row)[0]);
+            UInt_t key = atol((*row)[1]);
+
+            switch (key)
+            {
+            case 1: seq.AddFile(num, -1, MSequence::kDat);    break;
+            case 2: seq.AddFile(num, -1, MSequence::kPed);    break;
+            case 3: seq.AddFile(num, -1, MSequence::kDrsRun); break;
+            case 4: seq.AddFile(num, -1, MSequence::kCal);    break;
+            case 5: seq.AddFile(num, -1, MSequence::kDat);    break;
+            case 6: seq.AddFile(num, -1, MSequence::kCal);    break;
+            }
+
+            if (atoi((*row)[2])==1)
+                if (!(*row)[3] || atoi((*row)[3])==2)
+                    seq.AddFile(num, -1, MSequence::kDrsFile);
+        }
+
+        const TString path =
+            Form("%s/%04d/%02d/%02d", fPathSequences.Data(),
+                 run/10000, (run/100)%100, run%100);
+
+        const TString fname =
+            Form("%s/%d_%03ld.%s", path.Data(), run, from,
+                 drs.first==from?"drs.seq":"seq");
+
+        if (IsDummy())
+        {
+            cout << "----- " << fname << " -----" << endl;
+            seq.Print();
+            cout << "^^^^^ " << fname << " ^^^^^" << endl;
+        }
+        else
+        {
+            if (gSystem->AccessPathName(path, kFileExists))
+                if (gSystem->mkdir(path, kTRUE)<0)
+                    cout << "ERROR - Could not create " << path << endl;
+
+            if (!gSystem->AccessPathName(path, kFileExists))
+                seq.WriteFile(fname);
+        }
+
+        delete res;
+
+        if (drs.first==from)
+            return kTRUE;
+
+        // ========== Request number of events ==========
+
+        // Can be replaced by
+
+        const TString runtime =
+            "SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))), ";
+
+        const TString where = Form("(fRunID BETWEEN %ld AND %ld) AND fExcludedFDAKEY=1 AND %s",
+                                   from, to, cond.Data());
+
+        query  = "SELECT SUM(fNumEvents), ";
+        query += runtime;
+        query += " MIN(fZenithDistanceMin), MAX(fZenithDistanceMax), ";
+        query += " MIN(fAzimuthMin), MAX(fAzimuthMax), ";
+        query += " MIN(fRunStart), MAX(fRunStop) ";
+        query += " FROM RunInfo WHERE ";
+        query += where;
+        query += " AND fRunTypeKEY=1";// GROUP BY fNight";
+
+        res = Query(query);
+        if (!res)
+            return kFALSE;
+
+        row = res->Next();
+        if (!row || res->GetFieldCount()!=8)
+        {
+            cout << "ERROR - Wrong result from query: " << query << endl;
+            return kFALSE;
+        }
+
+        const TString nevts = (*row)[0];
+        const TString secs  = (*row)[1];
+        const TString zdmin = (*row)[2];
+        const TString zdmax = (*row)[3];
+        const TString azmin = (*row)[4];
+        const TString azmax = (*row)[5];
+        const TString start = (*row)[6];
+        const TString stop  = (*row)[7];
+
+        delete res;
+/*
+        const TString elts = GetELTSource(where);
+        if (elts.IsNull())
+            return kFALSE;
+
+        const TString eltp = GetELTProject(where);
+        if (eltp.IsNull())
+            return kFALSE;
+
+        // ========== Request data of sequence ==========
+        query  = "SELECT ";
+
+        query += elts;
+        query += ", ";
+        query += eltp;
+
+        query += ", fL1TriggerTableKEY, fL2TriggerTableKEY,"
+            " fHvSettingsKEY, fDiscriminatorThresholdTableKEY,"
+            " fTriggerDelayTableKEY, fObservationModeKEY, fSumTriggerFlagKEY "
+            " FROM RunData WHERE fRunTypeKEY=2 AND ";
+        query += where;
+        query += " LIMIT 1";
+
+        res = Query(query);
+        if (!res)
+            return kFALSE;
+
+        row = res->Next();
+        if (!row || res->GetFieldCount()!=9)
+        {
+            cout << "ERROR - No result from query: " << query << endl;
+            return kFALSE;
+        }
+        */
+
+        const TString set1 = Form("fSequenceID=%ld", from);
+        const TString set2 = set1 + Form(", fNight=%d", run);
+        const TString set3 = set2 + Form(", fStartTime=Now(), fStopTime=Now(), fProcessingSiteKEY=4, fAvailable=Now() ");
+
+        TString query1;
+        query1 += set2+",";
+        query1 += Form(" fNumEvents=%s,",         nevts.Data());
+        query1 += Form(" fSequenceDuration=%s,",  secs.Data());
+        query1 += Form(" fSequenceStart=\"%s\",", start.Data());
+        query1 += Form(" fSequenceStop=\"%s\",",  stop.Data());
+        query1 += Form(" fZenithDistanceMin=%s,", zdmin.IsNull() ? "NULL" : zdmin.Data());
+        query1 += Form(" fZenithDistanceMax=%s,", zdmax.IsNull() ? "NULL" : zdmax.Data());
+        query1 += Form(" fAzimuthMin=%s,",        azmin.IsNull() ? "NULL" : azmin.Data());
+        query1 += Form(" fAzimuthMax=%s",         azmax.IsNull() ? "NULL" : azmax.Data());
+
+        if (!Insert("SequenceInfo", query1))
+        {
+            cout << "ERROR - Could not insert Sequence into Sequences." << endl;
+            return kFALSE;
+        }
+
+        if (!Insert("SequenceFileAvailISDCStatus", set3))
+        {
+            cout << "ERROR - Could not insert Sequence into SequenceFileAvailISDCStatus." << endl;
+            return kFALSE;
+        }
+
+        if (!Update("RunInfo", set1, where))
+        {
+            cout << "ERROR - Could not update RunData." << endl;
+            return kFALSE;
+        }
+
+        return kTRUE;
+    }
+
+    Bool_t DeleteSequence(Int_t sequ, UInt_t night)
+    {
+        if (fPathRawData.IsNull() || fPathSequences.IsNull())
+        {
+            cout << "       + Deletion " << sequ << " skipped due to missing path." << endl;
+            return kTRUE;
+        }
+
+        //queries to delete information from the database
+        const TString cond(Form("fSequenceID=%d AND fNight=%d", sequ, night));
+
+        const TString path(Form("%04d/%02d/%02d", night/10000, (night/100)%100, night%100));
+
+        //commands to delete files from the disk
+        const TString cmd0(Form("rm -f %s/%s/%08d_%03d*seq", fPathSequences.Data(), path.Data(), night, sequ));
+
+//        const TString cmd1(Form("rm -rf %s/callisto/%04d/%08d/", fPathRawData.Data(),   sequ/10000, sequ));
+//        const TString cmd2(Form("rm -rf %s/star/%04d/%08d/",     fPathRawData.Data(),   sequ/10000, sequ));
+
+        if (!Delete("SequenceInfo", cond))
+            return 2;
+
+        if (!Update("RunInfo", "fSequenceID=NULL", cond))
+            return 2;
+
+        if (IsDummy())
+        {
+            cout << "       + would execute: " << cmd0 << endl;
+//            cout << "       + would execute: " << cmd1 << endl;
+//            cout << "       + would execute: " << cmd2 << endl;
+            return kTRUE;
+        }
+
+        cout << "       + will execute: " << cmd0 << endl;
+//        cout << "       + will execute: " << cmd1 << endl;
+//        cout << "       + will execute: " << cmd2 << endl;
+
+        gSystem->Exec(cmd0);
+//        gSystem->Exec(cmd1);
+//        gSystem->Exec(cmd2);
+
+        return kTRUE;
+    }
+
+    Int_t CheckSequence(Long_t runstart, Long_t runstop, const TString &cond)
+    {
+        const char *fmt1 = "SELECT fRunID FROM RunInfo WHERE";
+        const char *fmt2 = "AND fExcludedFDAKEY=1 ORDER BY fRunID";
+
+        const TString query1 = Form("%s fSequenceID=%ld AND %s %s",            fmt1, runstart, cond.Data(), fmt2);
+        const TString query2 = Form("%s fRunID BETWEEN %ld AND %ld AND %s %s", fmt1, runstart, runstop, cond.Data(), fmt2);
+
+        TSQLResult *res1 = Query(query1);
+        if (!res1)
+            return 2;
+
+        TSQLResult *res2 = Query(query2);
+        if (!res2)
+        {
+            delete res1;
+            return 2;
+        }
+
+        while (1)
+        {
+            TSQLRow *row1 = res1->Next();
+            TSQLRow *row2 = res2->Next();
+
+            if (!row1 && !row2)
+                return kTRUE;
+
+            if (!row1 || !row2)
+                return kFALSE;
+
+            if (atol((*row1)[0])!=atol((*row2)[0]))
+                return kFALSE;
+        }
+
+        return kFALSE;
+    }
+
+    Int_t CreateSequence(std::pair<Long_t,Long_t> &drs, Long_t runstart, Long_t runstop, const TString &cond)
+    {
+        cout << "   * Creating Sequence " << runstart << "-" << runstop << " (drs=" << drs.first << "/" << drs.second << "):" << endl;
+
+        //----------------------------------------------------------------------------
+
+        TString query;
+        query  = "SELECT fRunID FROM runinfo WHERE fExcludedFDAKEY=1 AND ";
+        query += cond;
+        query += " AND fRunTypeKEY=4 AND fRunID BETWEEN ";
+        query += Form("%ld AND %ld", runstart, runstop);
+
+        TSQLResult *res = Query(query);
+        if (!res)
+            return kFALSE;
+
+        // Check if this is a DRS calibration (contains a G run)
+        if (res->GetRowCount()>0 && res->GetFieldCount()==1)
+        {
+            delete res;
+
+            // Get DRS file with pedestal (roi<1024)
+            query  = "SELECT MAX(fRunID) FROM runinfo WHERE ";
+            query += cond;
+            query += " AND fHasDrsFile=1 AND (fDrsStep IS NULL OR fDrsStep=2) AND fRunTypeKEY=2";
+            query += " AND fRunID BETWEEN ";
+            query += Form("%ld AND %ld", runstart, runstop);
+
+            res = Query(query);
+            if (!res)
+                return kFALSE;
+
+            if (res->GetRowCount()==0 || res->GetFieldCount()!=1)
+                return kFALSE;
+
+            TSQLRow *row = res->Next();
+
+            drs.first  = runstart;
+            drs.second = (*row)[0] ? atol((*row)[0]) : -1;
+        }
+
+        delete res;
+
+        //----------------------------------------------------------------------------
+
+        query  = "SELECT fSequenceID, fNight FROM RunInfo WHERE ";
+        query += cond;
+        query += " AND fRunID BETWEEN ";
+        query += Form("%ld AND %ld", runstart, runstop);
+        query += " AND fSequenceID>0";
+        query += " GROUP BY fSequenceID";
+
+        res = Query(query);
+        if (!res)
+            return -2;
+
+        const Int_t cnt = res->GetRowCount();
+
+        Int_t rc = kTRUE;
+        if (cnt==1)
+        {
+            TSQLRow *row=res->Next();
+            const Int_t check = CheckSequence(runstart, runstop, cond);
+            if (check==kTRUE)
+            {
+                cout << "     - Identical sequence already existing." << endl;
+                delete res;
+                return -1; // kTRUE
+            }
+            if (check==2)
+                rc=2;
+            else
+            {
+                cout << "     - Deleting quasi-identical sequence " << atoi((*row)[0]) << endl;
+                if (DeleteSequence(atoi((*row)[0]), atoi((*row)[1]))==2)
+                    rc = 2;
+            }
+        }
+        else
+        {
+            TSQLRow *row=0;
+            while ((row=res->Next()))
+            {
+                cout << "     - Deleting overlapping sequence " << atoi((*row)[0]) << endl;
+                if (DeleteSequence(atoi((*row)[0]), atoi((*row)[1]))==2)
+                    rc = 2;
+            }
+        }
+
+        delete res;
+
+        if (rc==2)
+            return -2;
+
+        if (!InsertSequence(drs, runstart, runstop, cond))
+            return -2;
+
+        return kTRUE;
+    }
+
+    Bool_t ReadResources(const char *fname)
+    {
+        // Check for the section header
+        TPRegexp regexp("^\\[(RunTypes|Transition|Regexp):?[0-9 ]*\\]$");
+        // Check if section header contains a number
+        TPRegexp regnum("[0-9]");
+        // Check if section header contains the telescope number
+        TPRegexp regtel(Form("[^0-9]0*%d[^0-9]", fTelescopeNumber));
+
+        ifstream fin(fname);
+        if (!fin)
+        {
+            cout << "Cannot open file " << fname << ": ";
+            cout << strerror(errno) << endl;
+            return kFALSE;
+        }
+
+        Int_t section = 0;
+
+        TString key;
+        while (1)
+        {
+            TString txt;
+            txt.ReadLine(fin);
+            if (!fin)
+                break;
+
+            txt = txt.Strip(TString::kBoth);
+
+            if (txt[0]=='#' || txt.IsNull())
+                continue;
+
+            if (txt[0]=='[')
+            {
+                TString sec = txt(regexp);
+                if (!sec.IsNull())
+                {
+                    // Skip sections with the wrong telescope number
+                    // (If section contains numbers but not the tel num)
+                    if (!sec(regnum).IsNull() && sec(regtel).IsNull())
+                        continue;
+
+                    // Check which section we are in
+                    if (sec.BeginsWith("[RunTypes"))
+                        section = 1;
+                    if (sec.BeginsWith("[Transition"))
+                        section = 2;
+                    if (sec.BeginsWith("[Regexp"))
+                        section = 3;
+
+                    continue;
+                }
+
+                if (section!=3)
+                {
+                    cout << "WARNING - Line starts with [ but we are not in the Regexp section." << endl;
+                    cout << txt << endl;
+                    continue;
+                }
+            }
+
+
+            TObjArray *arr = txt.Tokenize(" ");
+
+            if (arr->GetEntries()>0)
+                switch (section)
+                {
+                case 1:
+                    // Create a llist of run-types
+                    // drs-time T
+                    break;
+                case 2:
+                    {
+                        TString key = arr->At(0)->GetName();
+                        key.Prepend("f");
+                        key.Append("KEY");
+
+                        CheckList *list = dynamic_cast<CheckList*>(fMap.GetValue(key));
+                        if (!list)
+                        {
+                            //cout << key << endl;
+                            list = new CheckList;
+                            fMap.Add(new TObjString(key), list);
+                        }
+
+                        if (arr->GetEntries()>1)
+                        {
+                            //cout << key << " ";
+                            list->Add(new CheckMatch(*arr, 1));
+                        }
+                    }
+                    break;
+                case 3:
+                    fListRegexp.Add(new Rule(*arr));
+                    break;
+                }
+
+            delete arr;
+        }
+
+        return kTRUE;
+    }
+/*
+    TString GetELT(const char *col, TSQLResult *res, TList &regexp)
+    {
+        TObjArray names; // array with old names (including regexp)
+
+        // Add to array and expand the array if necessary
+        TSQLRow *row=0;
+        while ((row=res->Next()))
+            names.AddAtAndExpand(new TObjString((*row)[1]), atoi((*row)[0]));
+
+        // Now a LUT is build which converts the keys for
+        // the names including the regexp into keys for
+        // the names excluding the regexp
+        TString elt(Form("ELT(RunData.f%sKEY+1", col));
+
+        // loop over all entries in the list
+        const Int_t n = names.GetSize();
+        for (int i=0; i<n; i++)
+        {
+            // For all entries which are not in the list
+            // write an undefined value into the LUT
+            TObject *o = names.UncheckedAt(i);
+            if (!o)
+            {
+                elt += ",0";
+                continue;
+            }
+
+            // Remove the regexp from the string which includes it
+            TString name = o->GetName();
+
+            TIter NextR(&regexp);
+            TObject *obj=0;
+            while ((obj=NextR()))
+            {
+                TPRegexp reg(obj->GetName());
+                const Ssiz_t pos = name.Index(reg, 0);
+                if (pos>0)
+                {
+                    name.Remove(pos);
+                    name += "-W";
+                    break;
+                }
+            }
+
+            // Check if such a Key exists, if not insert it
+            const Int_t key = QueryKeyOfName(col, name);
+
+            // RESOLVE return code!!!
+            //if (key<0)
+            //     return "";
+
+            // add index to the LUT
+            elt += Form(",%d", key);
+        }
+
+        // close LUT expression
+        //    elt += ") AS Elt";
+        //    elt += col;
+
+        elt += ") AS f";
+        elt += col;
+        elt += "KEY";
+
+        // return result
+        return elt;
+    }
+
+    TString GetELT(const char *col, TSQLResult *res, TString regexp)
+    {
+        TList list;
+        list.SetOwner();
+        list.Add(new TObjString(regexp));
+        return GetELT(col, res, list);
+    }
+
+    TString GetELTQuery(const char *col, const char *cond) const
+    {
+        return Form("SELECT RunData.f%sKEY, f%sName FROM RunData "
+                    "LEFT JOIN %s USING (f%sKEY) WHERE %s GROUP BY f%sName",
+                    col, col, col, col, cond, col);
+    }
+
+    TString GetELTSource(const char *cond)
+    {
+        //query all sources observed in this night
+        TSQLResult *resx = Query(GetELTQuery("Source", cond));
+        if (!resx)
+            return "";
+
+        // In the case there is only a single source
+        // do not replace the source key by the ELT
+        if (resx->GetRowCount()==1)
+            return "fSourceKEY";
+
+        TString elts = GetELT("Source", resx, "\\-?W[1-9][ abc]?$");
+        delete resx;
+
+        return elts;
+    }
+
+    TString GetELTProject(const char *cond)
+    {
+        //query all project names observed in this night
+        TSQLResult *resx = Query(GetELTQuery("Project", cond));
+        if (!resx)
+            return "";
+
+        // In the case there is only a single project
+        // do not replace the project key by the ELT
+        if (resx->GetRowCount()==1)
+            return "fProjectKEY";
+
+        TList regexp;
+        regexp.Add(new TObjString("\\-?W[1-9][abc]?$"));
+        regexp.Add(new TObjString("\\-W[0-9]\\.[0-9][0-9]\\+[0-9][0-9][0-9]$"));
+
+        TString eltp2 = GetELT("Project", resx, regexp);
+        delete resx;
+        regexp.Delete();
+
+        return eltp2;
+    }
+*/
+    Bool_t HasAtLeastOne(TString src, TString chk) const
+    {
+        src.ToLower();
+        chk.ToLower();
+
+        for (int i=0; i<chk.Length(); i++)
+            if (src.First(chk[i])<0)
+                return kFALSE;
+
+        return kTRUE;
+    }
+
+    TString PrepareString(TSQLResult &res, TArrayL &runs)
+    {
+        // Number of result rows
+        const Int_t rows = res.GetRowCount();
+
+        runs.Set(rows);       // initialize size of array for run numbers
+
+        TArrayD start(rows);  // instantiate array for start times
+        TArrayD stop(rows);   // instantiate array for stop times
+
+        TString str;          // result string
+
+        Int_t idx=0;
+        TSQLRow *row=0;
+        while ((row=res.Next()))
+        {
+            runs[idx] = atol((*row)[0]);          // run number
+
+            const TString tstart = ((*row)[2]);   // start time
+            const TString tstop  = ((*row)[3]);   // stop time
+
+            start[idx] = MTime(tstart).GetMjd();  // convert to double
+            stop[idx]  = MTime(tstop).GetMjd();   // convert to double
+
+            // This is a workaround for broken start-times
+            if (tstart=="0000-00-00 00:00:00")
+                start[idx] = stop[idx];
+
+            // Add a run-type character for this run to the string
+            str += RunType((*row)[1]);
+
+            // Increase index
+            idx++;
+        }
+/*
+        // Now the P- and D- runs are classified by the time-distance
+        // to the next or previous C-Run
+        Double_t lastc = -1;
+        Double_t nextc = -1;
+        for (int i=0; i<str.Length(); i++)
+        {
+            if (str[i]=='C')
+            {
+                // Remember stop time of C-Run as time of last C-run
+                lastc = stop[i];
+
+                // Calculate start time of next C-Run
+                const TString residual = str(i+1, str.Length());
+                const Int_t pos = residual.First('C');
+
+                // No C-Run found anymore. Finished...
+                if (pos<0)
+                    break;
+
+                // Remember start  time of C-Run as time of next C-run
+                nextc = start[i+1+pos];
+                continue;
+            }
+
+            // Check whether the identifying character should
+            // be converted to lower case
+            if (start[i]-lastc>nextc-stop[i])
+                str[i] = tolower(str[i]);
+        }
+*/
+        //cout << str << endl;
+        return str;
+    }
+
+    void PrintResidual(Long_t runstart, Long_t runstop, TString residual, const char *descr)
+    {
+        residual.ToLower();
+
+        // Count number of unsequences "characters"
+        const Int_t numd = residual.CountChar('d');
+        const Int_t nump = residual.CountChar('p');
+        const Int_t numb = residual.CountChar('b');
+        const Int_t numg = residual.CountChar('g');
+        const Int_t numt = residual.CountChar('t');
+        const Int_t numc = residual.CountChar('c');
+
+        // Print some information to the output steram
+        if (numd+nump+numb+numg+numt+numc==0)
+            return;
+
+        cout << "   ! " << runstart << "-" << runstop << " [" << setw(3) << 100*residual.Length()/(runstop-runstart+1) << "%]: " << descr << " not sequenced:  P=" << nump << "  C=" << numc << "  D=" << numd;
+        if (numd>0)
+            cout << "  (DATA!)";
+/*
+        if (nump==0 || numc==0 || numd==0)
+            cout << "  Missing";
+        if (numd==0)
+            cout << " D";
+        if (nump==0)
+            cout << " P";
+        if (numc==0)
+            cout << " C";
+*/
+        cout << endl;
+    }
+
+    Int_t SplitBlock(Long_t runstart, Long_t runstop, const TString &cond)
+    {
+        // Request data necessary to split block into sequences
+        /*const*/
+        TString query =
+            "SELECT fRunID, fRunTypeKEY, fRunStart, fRunStop"
+            " FROM RunInfo WHERE fExcludedFDAKEY=1 AND ";
+        query += Form("fRunID BETWEEN %ld AND %ld AND "
+                      /*" (fRunTypeKEY BETWEEN 2 AND 4)"*/, runstart, runstop);
+
+        query += cond;
+        query += " ORDER BY fRunID";
+
+
+        // Send query
+        TSQLResult *res = Query(query);
+        if (!res)
+            return 2;
+
+        // Get String containing the sequence of P-,C- and D-Runs
+        // and an array with the corresponding run-numbers
+        TArrayL runs;
+        const TString str = PrepareString(*res, runs);
+
+        delete res;
+
+        // Check if the prepared string at least contains one run of each type
+        // ??????????????????????????????????
+        /*
+        if (!HasAtLeastOne(str, "PCD"))
+        {
+            PrintResidual(runstart, runstop, str, "Block");
+            return kTRUE;
+        }*/
+        // ??????????????????????????????????
+
+        // Start the sequence building
+        // ---------------------------
+
+        Int_t   pos = 0;   // Position in the string
+        std::map<Long_t, Long_t>  map;       // Map for resulting sequences
+        TString residual;  // Unsequences "characters"
+
+        // Step through the string one character by one
+        cout << "   ";
+        while (pos<str.Length())
+        {
+            Bool_t found = kFALSE;
+
+            // Loop over the predefined regular expressions
+            TIter Next(&fListRegexp);
+            Rule *obj = 0;
+            while ((obj=(Rule*)Next()))
+            {
+                // Check if regular expressions matchs
+                const Ssiz_t len = obj->Match(str, pos, runs[pos]);
+                if (len>0)
+                {
+                    // In case of match get the substring which
+                    // defines the sequence and print it
+                    TString sub = str(pos, len);
+                    sub.ToUpper();
+                    cout << runs[pos]<<":"<< sub << "|";
+
+                    // Add the first and last run of the sequence to the map
+                    //map.Add(runs[pos], runs[pos+len-1]);
+                    map[runs[pos]] = runs[pos+len-1];
+
+                    // A sequence was found...
+                    found = kTRUE;
+
+                    // step forward in the string by the length of the sequence
+                    pos += len;
+                    break;
+                }
+            }
+
+            // If a sequence was found go on...
+            if (found)
+                continue;
+
+            // print unsequenced characters
+            cout << (char)tolower(str[pos]);
+
+            // Count the number of "characters" not sequenced
+            residual += str[pos];
+
+            // step one character forward
+            pos++;
+        }
+        cout << endl;
+
+        PrintResidual(runstart, runstop, residual, "Runs ");
+
+        // Create all sequences which were previously found
+        std::pair<Long_t,Long_t> drs(-1, -1);
+        for (std::map<Long_t,Long_t>::const_iterator it=map.begin();
+             it!=map.end(); it++)
+            if (CreateSequence(drs, it->first, it->second, cond)==2)
+                return 2;
+        /*
+        Long64_t first, last;
+        TExMapIter iter(&map);
+        while (iter.Next(first, last))
+            if (CreateSequence(first, last, cond)==2)
+                return 2;
+         */
+        return kTRUE;
+    }
+
+    Char_t RunType(Int_t n) const
+    {
+        switch (n)
+        {
+        case  1: return 'D';
+        case  2: return 'P'; // Ped1024
+        case  3: return 'B'; // Ped 300
+        case  4: return 'G'; // drs-gain
+        case  5: return 'T'; // drs-time
+        case  6: return 'C'; // light-pulser-ext
+        case 11: return 'M'; // ped-and-lp-ext
+        case 12: return 'U'; // drs-time-upshifted
+        }
+        return '-';
+    }
+    Char_t RunType(const char *str) const
+    {
+        return RunType(atoi(str));
+    }
+
+    Int_t BuildBlocks(TSQLResult *res, TExMap &blocks, const TString &cond)
+    {
+        // col key content
+        // -----------------------------
+        //  0   -  runnumber
+        //  1   0  RunTypeKEY
+        //  2   1  source
+        //  3   2  project
+        //  .   .
+        //  .   .
+        //  .   .  from transition.txt
+        //
+
+        //build blocks of runs, which have the same values
+        //for each block the first and the last run are stored in a TExMap
+        //the values are checked with the help of an array of TStrings
+        Long_t runstart = -1;
+        Long_t runstop  = -1;
+
+        const UInt_t ncols = res->GetFieldCount();
+
+        TString keys[ncols]; // Index 0 is not used (Index 1: RunType)
+
+        // Loop over runs
+        TSQLRow *row=0;
+        while ((row=res->Next()))
+        {
+            // This is the runnumber of the first run in the new block
+            if (runstart<0)
+                runstart=atol((*row)[0]);
+
+            // Check which transitions might be allowed for this run and
+            // which are not. Check also which attributes should be ignored
+            // for this run. The information about it is stored in the map.
+            Int_t rc[ncols];
+            for (UInt_t i=2; i<ncols; i++)
+                rc[i] = CheckTransition(*res, keys, *row, i);
+
+            for (UInt_t i=2; i<ncols; i++)
+            {
+                switch (rc[i])
+                {
+                case kTRUE:    // Transition allowed, switch to new attribute
+                    keys[i] = (*row)[i];
+                    continue;
+
+                case -1:       // Ignore attribute, continue with next one
+                    //if (keys[i] == (*row)[i])
+                    //    break; // Only ignore it if it is really different
+                    continue;
+
+                case kFALSE:   // No decision (nothing matching found in map)
+                    break;     //  go on checking
+
+                }
+
+                // If past-attribute is not yet initialized, do it now.
+                if (keys[i].IsNull())
+                    keys[i] = (*row)[i];
+
+                // Check whether key has changed for this run
+                // (this condition is never true for the first run)
+                // This condition in only reached if keys[i] was initialized
+                if (keys[i] == (*row)[i])
+                    continue;
+
+                // Found one block with unique keys, fill values into TExMap
+                // (except if this is the first run processed)
+                cout << endl;
+                cout << " - Identical conditions from " << runstart << " to " << runstop << endl;
+                blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
+                if (SplitBlock(runstart, runstop, cond)==2)
+                    return 2;
+                cout << " - Transition from " << RunType(keys[1]) << ":";
+                cout << QueryNameOfKey(res->GetFieldName(i), keys[i]) << " <" << keys[i] << "> to " << RunType((*row)[1]) << ":";
+                cout << QueryNameOfKey(res->GetFieldName(i), (*row)[i]) << " <" << (*row)[i] << ">";
+                cout << " in " << res->GetFieldName(i) << " of " << (*row)[0] << endl;
+
+                // This is already the first run of the new block
+                runstart=atol((*row)[0]);
+
+                // These are the keys corresponding to the first run
+                // in the new block. All following runs should have
+                // identical keys. Do not set the attribute if for
+                // this attribute the transition check evaluated
+                // to "ignore".
+                for (UInt_t j=2; j<ncols; j++)
+                    keys[j] = rc[j]==-1 ? "" : (*row)[j];
+
+                break;
+            }
+
+            keys[1] = (*row)[1]; // Remember run type for next run
+
+            // This is the new runnumber of the last run in this block
+            runstop=atol((*row)[0]);
+        }
+
+        // If runstart==-1 a possible block would contain a single run...
+        if (runstart>0 && runstart!=runstop)
+        {
+            cout << " - Identical conditions from " << runstart << " to " << runstop << " (last run)" << endl;
+            //fill values into TExMap (last value)
+            blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
+            if (SplitBlock(runstart, runstop, cond)==2)
+                return 2;
+        }
+        cout << "Done." << endl << endl;
+
+        return kTRUE;
+    }
+
+public:
+    SequenceBuild(Int_t tel=1, const char *rc="sql.rc") : MSQLMagic(rc), fTelescopeNumber(tel)
+    {
+        fListRegexp.SetOwner();
+
+        // FIXME: THIS IS NOT YET HANDLED
+        if (ReadResources("fact/resources/sequences.rc"))
+            return;
+    }
+
+    SequenceBuild(TEnv &env, Int_t tel=1) : MSQLMagic(env), fTelescopeNumber(tel)
+    {
+        fListRegexp.SetOwner();
+
+        // FIXME: THIS IS NOT YET HANDLED
+        if (ReadResources("fact/resources/sequences.rc"))
+            return;
+    }
+    ~SequenceBuild()
+    {
+        fMap.DeleteAll();
+    }
+
+    void SetPathRawData(const char *path) { fPathRawData=path; }
+    void SetPathSequences(const char *path) { fPathSequences=path; }
+
+    int Build(TString day)
+    {
+        cout << endl;
+        cout << "Night of sunset at " << day << ":" << endl;
+
+        const TString cond = Form("fNight=%s ", day.Data());
+
+        //    Form("fRunNumber=%s "
+        //         "AND fExcludedFDAKEY=1 AND fRunTypeKEY BETWEEN 2 AND 4 "
+        //         "AND fTelescopeNumber=%d ",
+        //         day.Data(), fTelescopeNumber);
+/*
+        //query all sources observed in this night
+        const TString elts = GetELTSource(cond);
+        if (elts.IsNull())
+            return 2;
+
+        //query all project names observed in this night
+        const TString eltp2 = GetELTProject(cond);
+        if (elts.IsNull())
+            return 2;
+*/
+        // Setup query to get all values from the database,
+        // that are relevant for building sequences
+        TString query("SELECT fRunID, fRunTypeKEY ");
+/*
+        query += elts;
+        query += ", ";
+        query += eltp2;
+*/
+        // Now add all entries from the transition table to the query
+        TIter NextPair(&fMap);
+        TObject *mapkey = 0;
+        while ((mapkey=(TPair*)NextPair()))
+            if (!query.Contains(mapkey->GetName()))
+            {
+                query += ", ";
+                query += mapkey->GetName();
+            }
+        query += " FROM RunInfo WHERE fExcludedFDAKEY=1 AND ";
+        query += cond;
+        query += " ORDER BY fRunID";
+
+        TSQLResult *res = Query(query);
+        if (!res)
+            return 2;
+
+        TExMap blocks;
+        const Int_t rc = BuildBlocks(res, blocks, cond);
+        delete res;
+
+        return rc;
+    }
+
+    Int_t Build()
+    {
+        //get all dates from the database
+        TSQLResult *res = Query("SELECT fNight FROM RunInfo GROUP BY fNight ORDER BY fNight DESC");
+        if (!res)
+            return 2;
+
+        //execute buildsequenceentries for all dates
+        TSQLRow *row=0;
+        while ((row=res->Next()))
+            Build((*row)[0]);
+
+        delete res;
+
+        return 1;
+    }
+    ClassDef(SequenceBuild, 0)
+};
+
+ClassImp(SequenceBuild);
+
+int buildseqentries(TString day, TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    SequenceBuild serv(tel, "sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "buildseqentries" << endl;
+    cout << "---------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    if (!datapath.IsNull())
+        cout << "DataPath:  " << datapath << endl;
+    if (!sequpath.IsNull())
+        cout << "SeqPath:   " << sequpath << endl;
+    cout << "Day:       " << day      << endl;
+    cout << "Telescope: " << tel      << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+    serv.SetPathRawData(datapath);
+    serv.SetPathSequences(sequpath);
+    return serv.Build(day);
+}
+
+//
+// Build Sequences for all Nights
+//
+int buildseqentries(TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    SequenceBuild serv(tel, "sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "buildseqentries" << endl;
+    cout << "---------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "DataPath:  " << datapath << endl;
+    cout << "SeqPath:   " << sequpath << endl;
+    cout << "Telescope: " << tel      << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+    serv.SetPathRawData(datapath);
+    serv.SetPathSequences(sequpath);
+    return serv.Build();
+}
+
+int buildseqentries(Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    return buildseqentries("", "", tel, dummy);
+}
+
+int buildseqentries(TString day, Int_t tel=1, Bool_t dummy=kTRUE)
+{
+    return buildseqentries(day, "", "", tel, dummy);
+}
Index: branches/Mars_McMismatchStudy/fact/processing/calibrate.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/calibrate.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/calibrate.C	(revision 17960)
@@ -0,0 +1,288 @@
+/*
+#ifndef HAVE_ZLIB
+#define HAVE_ZLIB
+#endif
+
+#include <TMath.h>
+
+#include "fits.h"
+#include "ofits.h"
+
+#include "MArrayF.h"
+#include "MMath.h"
+*/
+
+using namespace std;
+
+bool Read(const char *fname, int *npix)
+{
+    std::ifstream fin(fname);
+
+    int l = 0;
+
+    while (1)
+    {
+        if (l>1439)
+            break;
+
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        line = line.Strip(TString::kBoth);
+        if (line[0]=='#')
+            continue;
+
+        TObjArray *arr = line.Tokenize(' ');
+        int cbpx  = atoi(((*arr)[1])->GetName());
+        int board = atoi(((*arr)[6])->GetName());
+        int ch    = atoi(((*arr)[7])->GetName());
+        delete arr;
+
+        int hv = board*32+ch;
+        if (hv>=416)
+            return false;
+
+        int n = cbpx%10>3 ? 5 : 4;
+        if (npix[hv]>0 && npix[hv]!=n)
+            return false;
+
+        npix[hv] = n;
+        l++;
+    }
+
+    return l==1440;
+}
+
+int calibrate(UInt_t night, TString path="/fact/aux")
+{
+    int npix[416];
+    memset(npix, 0, sizeof(int)*416);
+    if (!Read("/gpfs/scratch/fact/FACTmap111030.txt", npix))
+        return 42;
+
+    UInt_t d =  night%100;
+    UInt_t m = (night/100)%100;
+    UInt_t y =  night/10000;
+
+    path += Form("/%04d/%02d/%02d/%d", y, m, d, night);
+    TString path2 = Form("/gpfs/scratch/fact/calibrated_currents/%d", night);
+
+    TString filec = path + ".FEEDBACK_CALIBRATION.fits";
+    TString fileu = path + ".BIAS_CONTROL_VOLTAGE.fits";
+    TString filei = path + ".BIAS_CONTROL_CURRENT.fits";
+    TString fileo = path2 + ".CALIBRATED_CURRENTS.fits";
+
+    cout << filec << endl;
+    cout << fileu << endl;
+    cout << filei << endl;
+    cout << fileo << endl;
+
+    fits fitsc1(filec.Data());
+    fits fitsc2(filec.Data());
+    if (!fitsc2)
+    {
+        cout << "ERROR - Open " << filec << " failed." << endl;
+        return 1;
+    }
+
+    fits fitsu1(fileu.Data());
+    fits fitsu2(fileu.Data());
+    if (!fitsu2)
+    {
+        cout << "ERROR - Open " << fileu << " failed." << endl;
+        return 2;
+    }
+
+    fits fitsi1(filei.Data());
+    fits fitsi2(filei.Data());
+    if (!fitsi2)
+    {
+        cout << "ERROR - Open " << filei << " failed." << endl;
+        return 3;
+    }
+
+    ofits fout(fileo.Data());
+    if (!fout)
+    {
+        cout << "ERROR - Open " << fileo << " failed." << endl;
+        return 4;
+    }
+
+    //const MTime now;
+    fout.SetStr(  "TELESCOP", "FACT",               "Telescope that acquired this data");
+    fout.SetStr(  "PACKAGE",  "MARS",               "Package name");
+    fout.SetStr(  "VERSION",  "1.0",                "Package description");
+    fout.SetFloat("EXTREL",   1.0,                  "Release Number");
+    //fout.SetStr(  "COMPILED", __DATE__" "__TIME__,  "Compile time");
+    fout.SetStr(  "ORIGIN",   "FACT",               "Institution that wrote the file");
+    //fout.SetStr(  "DATE",     now.GetStringFmt("%Y-%m-%dT%H:%M:%S").Data(), "File creation date");
+    //fout.SetInt(  "NIGHT",    now.GetNightAsInt(),  "Night as int");
+    fout.SetStr(  "TIMESYS",  "UTC",                "Time system");
+    fout.SetStr(  "TIMEUNIT", "d",                  "Time given in days w.r.t. to MJDREF");
+    fout.SetInt(  "MJDREF",   40587,                "MJD to UNIX time (seconds since 1970/1/1)");
+
+    fout.AddColumnDouble("Time",  "MJD", "Event time: MJD - MJDREF (= Unix Time)");
+    fout.AddColumnDouble("T_cal", "MJD", "Calibration time: MJD - MJDREF (= Unix Time)");
+    fout.AddColumnInt(   "N",     "",    "Number of valid values");
+    fout.AddColumnFloat( "I_avg", "uA",  "Average calibrated current (320 channels)");
+    fout.AddColumnFloat( "I_rms", "uA",  "RMS of calibrated current (320 channels)");
+    fout.AddColumnFloat( "I_med", "uA",  "Median of calibrated currents (320 channels)");
+    fout.AddColumnFloat( "I_dev", "uA",  "Deviation of calibrated currents (320 channels)");
+    fout.AddColumnFloat(416, "I", "uA", "My comment");
+
+    fout.WriteTableHeader("CALIBRATED");
+
+    Double_t timec, timeu, timei;
+    Double_t nextc, nextu, nexti;
+
+    if (!fitsc1.SetPtrAddress("Time", &timec))
+    {
+        cout << "ERROR couldn't get pointer to 1st Time for R" << endl;
+        return 2;
+    }
+    if (!fitsu1.SetPtrAddress("Time", &timeu))
+    {
+        cout << "ERROR couldn't get pointer to 1st Time for U" << endl;
+        return 2;
+    }
+    if (!fitsi1.SetPtrAddress("Time", &timei))
+    {
+        cout << "ERROR couldn't get pointer to 1st Time for I" << endl;
+        return 2;
+    }
+
+    if (!fitsc2.SetPtrAddress("Time", &nextc))
+    {
+        cout << "ERROR couldn't get pointer to 2nd Time for R" << endl;
+        return 2;
+    }
+    if (!fitsu2.SetPtrAddress("Time", &nextu))
+    {
+        cout << "ERROR couldn't get pointer to 2nd Time for U" << endl;
+        return 2;
+    }
+    if (!fitsi2.SetPtrAddress("Time", &nexti))
+    {
+        cout << "ERROR couldn't get pointer to 2nd Time for I" << endl;
+        return 2;
+    }
+
+    Float_t  R[416];
+    Float_t  U[416];
+    UShort_t I[416];
+
+    if (!fitsc1.SetPtrAddress("R",    R))
+    {
+        cout << "ERROR couldn't get pointer to R" << endl;
+        return 2;
+    }
+    if (!fitsu1.SetPtrAddress("Uout", U))
+    {
+        cout << "ERROR couldn't get pointer to U" << endl;
+        return 2;
+    }
+    if (!fitsi1.SetPtrAddress("I",    I))
+    {
+        cout << "ERROR couldn't get pointer to I" << endl;
+        return 2;
+    }
+
+    fitsc2.GetNextRow();
+    fitsu2.GetNextRow();
+    fitsi2.GetNextRow();
+
+    if (!fitsc1.GetNextRow())
+        return 0;
+    if (!fitsc2.GetNextRow())
+        nextc = 1e50;
+
+    while (1)
+    {
+        // First the next two rows (voltage, current)
+        // with identical time stamp
+        if (nextu<nextc && nextu<nexti)
+        {
+            if (!fitsu1.GetNextRow())
+                break;
+            fitsu2.GetNextRow();
+            continue;
+        }
+
+        if (nexti<nextc && nexti<nextu)
+        {
+            if (!fitsi1.GetNextRow())
+                break;
+            fitsi2.GetNextRow();
+            continue;
+        }
+
+        // At this point we have found currents and voltages
+        // with the same time-stamp
+        if (nexti!=nextu)
+            break;
+
+        // Now read the next row, voltages and currenst, which
+        // should be evaluated
+        if (!fitsu1.GetNextRow() || !fitsi1.GetNextRow())
+            break;
+
+        // Read also one event in advance to get the next time-stamps
+        fitsu2.GetNextRow();
+        fitsi2.GetNextRow();
+
+        // Read new calibration events as long as the difference
+        // in time to the next calibration evenet is smaller
+        // than to the current one. In this way always the
+        // closest one is used.
+        while (fabs(nextc-nextu)<fabs(timec-timeu))
+        {
+            // If there is no next one, make sure that
+            // the the condition is never met again.
+            if (!fitsc1.GetNextRow())
+            {
+                nextc=1e50;
+                break;
+            }
+            fitsc2.GetNextRow();
+        }
+
+        // Calibrate the data (subtract offset)
+        MArrayF rc(9+416);
+        MArrayF stat(416);
+
+        Float_t *cur = rc.GetArray()+9;
+
+        UInt_t cnt = 0;
+        for (int i=0; i<416; i++)
+        {
+            if (R[i]<=0)
+                continue;
+
+            // Convert dac counts to uA
+            // Measued current minus leakage current (bias crate calibration)
+            cur[i] = I[i] * 5000./4096 - U[i]/R[i]*1e6;
+
+            if (npix[i]>0)
+            {
+                cur[i] /= npix[i];
+                stat[cnt++] = cur[i];
+            }
+        }
+
+        memcpy(rc.GetArray(),   &timeu, sizeof(Double_t));
+        memcpy(rc.GetArray()+2, &timec, sizeof(Double_t));
+        memcpy(rc.GetArray()+4, &cnt,   sizeof(UInt_t));
+
+        Double_t med;
+        rc[5] = TMath::Mean(cnt, stat.GetArray());
+        rc[6] = TMath::RMS(cnt, stat.GetArray());
+        rc[8] = MMath::MedianDev(cnt, stat.GetArray(), med);
+        rc[7] = med;
+
+        fout.WriteRow(rc.GetArray(), rc.GetSize()*sizeof(Float_t));
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/camtemp.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/camtemp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/camtemp.C	(revision 17960)
@@ -0,0 +1,82 @@
+void camtemp(const char *fname, double beg=0, double end=100000)
+{
+    fits file(fname);
+
+    //file.PrintColumns();
+    //file.PrintKeys();
+
+    Double_t time;
+    Float_t temp[31];
+    file.SetPtrAddress("Time", &time);
+    file.SetPtrAddress("T_sens", temp);
+
+    UInt_t offset = file.GetUInt("MJDREF");
+    if (beg < 30000)
+        beg+=offset;
+    if (end < 30000)
+        end+=offset;
+
+    double avg    = 0;
+    double avgrms = 0;
+    double rms    = 0;
+    int    cnt    = 0;
+
+    double last  = -1;
+    double lastr = -1;
+    double diff  = -1;
+
+    while (file.GetNextRow())
+    {
+        time += offset;
+
+        if (time>end)
+            break;
+
+        double m = 0;
+        double r = 0;
+        int    n = 0;
+        for (int i=0; i<31; i++)
+        {
+            if (temp[i]!=0)
+            {
+                m += temp[i];
+                r += temp[i]*temp[i];
+                n++;
+            }
+        }
+        m /= n;
+        r /= n;
+
+        if (time<beg)
+        {
+            last  = m;
+            lastr = sqrt(r-m*m);
+            diff  = beg-time;
+            continue;
+        }
+
+        avgrms += sqrt(r-m*m);
+
+        avg += m;
+        rms += m*m;
+        cnt ++;
+    }
+
+    if (cnt==0)
+    {
+        if (diff<5./24/3600)
+            return;
+
+        cout << "result " << last << " 0 " << lastr << endl;
+        return;
+    }
+
+    avg /= cnt;
+    rms /= cnt;
+
+    avgrms /= cnt;
+
+    rms = sqrt(rms-avg*avg);
+
+    cout << "result " << avg << " " << rms << " " << avgrms << endl;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/ctrldev.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/ctrldev.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/ctrldev.C	(revision 17960)
@@ -0,0 +1,65 @@
+void ctrldev(const char *fname, double beg=0, double end=100000)
+{
+    fits file(fname);
+
+    //file.PrintColumns();
+    //file.PrintKeys();
+
+    Double_t time;
+    Double_t zd, dzd, daz;
+    file.SetPtrAddress("Time", &time);
+    file.SetPtrAddress("Zd",   &zd);
+    file.SetPtrAddress("dZd",  &dzd);
+    file.SetPtrAddress("dAz",  &daz);
+
+    UInt_t offset = file.GetUInt("MJDREF");
+    if (beg < 30000)
+        beg+=offset;
+    if (end < 30000)
+        end+=offset;
+
+    double avg  = 0;
+    double rms  = 0;
+    int    cnt  = 0;
+
+    double last = -1;
+    double diff = -1;
+
+    while (file.GetNextRow())
+    {
+        time += offset;
+
+        if  (time>end)
+            break;
+
+        // Calculate absolute misspointing from error in zd and error in az
+        Double_t dev = MAstro::GetDevAbs(zd, dzd, daz)*60;
+
+        if (time<beg)
+        {
+            last = dev;
+            diff = beg-time;
+            continue;
+        }
+
+        avg += dev;
+        rms += dev*dev;
+        cnt ++;
+    }
+
+    if (cnt==0)
+    {
+        if (diff<5./24/3600)
+            return;
+
+        cout << "result " << last << " 0 " << endl;
+        return;
+    }
+
+    avg /= cnt;
+    rms /= cnt;
+
+    rms = sqrt(rms-avg*avg);
+
+    cout << "result " << avg << " " << rms << endl;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/currents.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/currents.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/currents.C	(revision 17960)
@@ -0,0 +1,143 @@
+
+
+void currents(const char *fname, double beg=0, double end=100000)
+{
+    fits file(fname);
+
+    //file.PrintColumns();
+    //file.PrintKeys();
+
+    Double_t time;
+    Double_t jd;
+
+    Float_t med, dev;
+    file.SetPtrAddress("Time",  &time);
+    file.SetPtrAddress("I_med", &med);
+    file.SetPtrAddress("I_dev", &dev);
+
+    UInt_t offset = file.GetUInt("MJDREF");
+    if (beg < 30000)
+        beg+=offset;
+    if (end < 30000)
+        end+=offset;
+
+    double med_beg  = 0;
+    double med_end  = 0;
+    double med_avg  = 0;
+    double med_rms  = 0;
+    double dev_avg  = 0;
+    double dev_rms  = 0;
+    int    cnt_beg  = 0;
+    int    cnt_end  = 0;
+
+    double med_last = -1;
+    double dev_last = -1;
+    double diff = -1;
+
+    double calc_dev_avg  = 0;
+    double calc_dev_rel  = 0;
+
+    TGraph g;
+
+    while (file.GetNextRow())
+    {
+        time += offset;
+        jd    = time + 2400000.5;
+
+        if (time>end)
+            break;
+
+        if (time<beg)
+        {
+            med_last = med;
+            dev_last = dev;
+            diff = beg-time;
+            continue;
+        }
+
+        med_avg += med;
+        med_rms += med*med;
+        dev_avg += dev;
+        dev_rms += dev*dev;
+
+        if (time<beg+15./24/3600)
+        {
+            med_beg += med;
+            cnt_beg++;
+        }
+        if (time>end-15./24/3600)
+        {
+            med_end += med;
+            cnt_end++;
+        }
+
+        //calculate the moon
+        Nova::EquPosn moon = Nova::GetLunarEquCoords(jd, 0.01);
+        // get local position of moon
+        Nova::HrzPosn hrzm = Nova::GetHrzFromEqu(moon, jd);
+
+        //calculate the light condition
+        double disk = Nova::GetLunarDisk(jd);
+
+        // Current prediction
+        //double cang = sin(angle);
+        const double calt = sin(hrzm.alt*TMath::DegToRad());
+
+        //                                                                           semi-major axis
+        const double lc = /*cang==0 ? 0 :*/ calt*pow(disk, 2.2)*pow(Nova::GetLunarEarthDist(jd)/384400, -2);///sqrt(cang);
+        //const double lc = cang==0 ? -1 : calt*pow(disk, 2.2)*pos(dist, -2);
+        const double Ical = lc>0 ? 4+103*lc : 4;
+
+        g.SetPoint(g.GetN(), time, med);
+
+        calc_dev_avg += med - Ical;
+        calc_dev_rel += med/Ical;
+
+    }
+
+    if (g.GetN()==0)
+    {
+        if (diff<5./24/3600)
+            return;
+
+        // return the last report before the run
+        //   (if not older than 5 minutes)
+        cout << "result " << med_last << " 0 " << dev_last << " 0 0 0 0" << endl;
+        return;
+    }
+
+    Double_t a0, a1;
+    Int_t ifail;
+    g.LeastSquareLinearFit(0, a0, a1, ifail);
+
+    double fluct_abs = 0;
+    double fluct_rel = 0;
+    if (ifail==0)
+    {
+        for (int i=0; i<g.GetN(); i++)
+            g.GetY()[i] -= a0+a1*g.GetX()[i];
+        fluct_abs = g.GetRMS(2);
+
+        for (int i=0; i<g.GetN(); i++)
+            g.GetY()[i] /= a0+a1*g.GetX()[i];
+        fluct_rel = g.GetRMS(2);
+    }
+
+    med_beg = cnt_beg>0 ? med_beg/cnt_beg : -1;
+    med_end = cnt_end>0 ? med_end/cnt_end : -1;
+
+    med_avg /= g.GetN();
+    med_rms /= g.GetN();
+    med_rms = sqrt(med_rms-med_avg*med_avg);
+
+    dev_avg /= g.GetN();
+    dev_rms /= g.GetN();
+    dev_rms = sqrt(dev_rms-dev_avg*dev_avg);
+    calc_dev_avg /= g.GetN();
+
+    calc_dev_rel -= g.GetN();
+    calc_dev_rel /= g.GetN();
+
+
+    cout << "result " << med_avg << " " << med_rms << " " << dev_avg << " " << dev_rms << " " << med_beg << " " << med_end << " " << calc_dev_avg << " " << calc_dev_rel << " " << fluct_abs << " " << fluct_rel << endl;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/drstemp.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/drstemp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/drstemp.C	(revision 17960)
@@ -0,0 +1,173 @@
+void drstemp82(fits &file, double beg, double end)
+{
+    UInt_t offset = file.GetUInt("MJDREF");
+    if (beg < 30000)
+        beg+=offset;
+    if (end < 30000)
+        end+=offset;
+
+    double time;
+    file.SetPtrAddress("Time", &time);
+
+    float *temp = file.SetPtrAddress("temp");
+
+    double avgmin = 0;
+    double avgmax = 0;
+    double rmsmin = 0;
+    double rmsmax = 0;
+
+    int cnt = 0;
+
+    double lastavgmin = -1;
+    double lastavgmax = -1;
+    double lastrmsmin = -1;
+    double lastrmsmax = -1;
+
+    double diff  = -1;
+
+    while (file.GetNextRow())
+    {
+        time += offset;
+
+        if (time>end)
+            break;
+
+        double mn = 0;
+        double mx = 0;
+        double rn = 0;
+        double rx = 0;
+        for (int i=1; i<=40; i++)
+        {
+            mn += temp[i];
+            rn += temp[i]*temp[i];
+
+            mx += temp[i+41];
+            rx += temp[i+41]*temp[i+41];
+        }
+        mn /= 40;
+        mx /= 40;
+        rn /= 40;
+        rx /= 40;
+
+        if (time<beg)
+        {
+            lastavgmin  = mn;
+            lastavgmax  = mx;
+            lastrmsmin  = sqrt(rn-mn*mn);
+            lastrmsmax  = sqrt(rx-mx*mx);
+            diff  = beg-time;
+            continue;
+        }
+
+        avgmin += mn;
+        avgmax += mx;
+
+        rmsmin += sqrt(rn-mn*mn);
+        rmsmax += sqrt(rx-mx*mx);
+
+        cnt ++;
+    }
+
+    if (cnt==0)
+    {
+        if (diff<5./24/3600)
+            return;
+
+        cout << "result " << lastavgmin << " " << lastavgmax << " " << lastrmsmin << " " << lastrmsmax << endl;
+        return;
+    }
+
+    avgmin /= cnt;
+    avgmax /= cnt;
+    rmsmin /= cnt;
+    rmsmax /= cnt;
+
+    cout << "result " << avgmin << " " << avgmax << " " << rmsmin << " " << rmsmax << endl;
+}
+
+void drstemp160(fits &file, double beg, double end)
+{
+    UInt_t offset = file.GetUInt("MJDREF");
+    if (beg < 30000)
+        beg+=offset;
+    if (end < 30000)
+        end+=offset;
+
+    double time;
+    file.SetPtrAddress("Time", &time);
+
+    float *temp = file.SetPtrAddress("temp");
+
+    double avg = 0;
+    double rms = 0;
+
+    int cnt = 0;
+
+    double lastavg = -1;
+    double lastrms = -1;
+
+    double diff  = -1;
+
+    while (file.GetNextRow())
+    {
+        time += offset;
+
+        if (time>end)
+            break;
+
+        double mn = 0;
+        double rn = 0;
+        for (int i=0; i<=160; i++)
+        {
+            mn += temp[i];
+            rn += temp[i]*temp[i];
+        }
+        mn /= 160;
+        rn /= 160;
+
+        if (time<beg)
+        {
+            lastavg = mn;
+            lastrms = sqrt(rn-mn*mn);
+            diff    = beg-time;
+            continue;
+        }
+
+        avg += mn;
+        rms += sqrt(rn-mn*mn);
+
+        cnt ++;
+    }
+
+    if (cnt==0)
+    {
+        if (diff<5./24/3600)
+            return;
+
+        cout << "result " << lastavg << " " << lastavg << " " << lastrms << " " << lastrms << endl;
+        return;
+    }
+
+    avg /= cnt;
+    rms /= cnt;
+
+    cout << "result " << avg << " " << avg << " " << rms << " " << rms << endl;
+}
+
+void drstemp(const char *fname, double beg=0, double end=100000)
+{
+    fits file(fname);
+
+    //file.PrintColumns();
+    //file.PrintKeys();
+
+    float temp[160];
+    if (file.SetPtrAddress("temp", temp, 82))
+    {
+        drstemp82(file, beg, end);
+        return;
+    }
+
+    file.SetPtrAddress("temp", temp, 160);
+    drstemp160(file, beg, end);
+}
Index: branches/Mars_McMismatchStudy/fact/processing/fillratescan.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/fillratescan.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/fillratescan.C	(revision 17960)
@@ -0,0 +1,436 @@
+Int_t CheckVoltage(TString fname, Double_t beg, Double_t end)
+{
+    fname.ReplaceAll("RATE_SCAN_DATA", "BIAS_CONTROL_VOLTAGE");
+
+    fits file(fname.Data());
+    if (!file)
+        return -2;
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  Uout[416];
+    UShort_t Uref[416];
+    memset(Uout, 0, 416*4);
+    memset(Uref, 0, 416*2);
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -1;
+
+    if (!file.SetPtrAddress("Uout", Uout) && !file.SetPtrAddress("Uref", Uref))
+        return -1;
+
+    //cout << "Search for: " << beg-15773 << " " << end-15773 << endl;
+
+    Int_t rows = 0;
+    while (file.GetNextRow())
+    {
+        if (time<beg)
+            continue;
+
+        if (time>end)
+            break;
+
+        Int_t cnt = 0;
+        for (int i=0; i<320; i++)
+            if (Uout[i]>50 || Uref[i]>2900)
+                cnt++;
+
+        if (cnt<318)
+            return kFALSE;
+
+        rows++;
+    }
+
+    return rows>0;
+}
+
+Float_t GetOffset(TString fname, Double_t beg, Double_t end)
+{
+    fname.ReplaceAll("RATE_SCAN_DATA", "FEEDBACK_DEVIATION");
+
+    fits file(fname.Data());
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t  delta      = -100;
+    Float_t  delta_prev = -100;
+
+    if (!file.SetPtrAddress("Time",  &time))
+        return -100;
+
+    if (!file.SetPtrAddress("DeltaUser", &delta))
+        return -100;
+
+    //cout << "Search for: " << beg-15773 << " " << end-15773 << endl;
+
+    Int_t rows = 0;
+    while (file.GetNextRow())
+    {
+        if (time>beg)
+            return delta_prev;
+
+        delta_prev = delta;
+    }
+
+    return -100;
+}
+
+Float_t GetCurrent(TString fname, Double_t beg, Double_t end)
+{
+    fname.ReplaceAll("RATE_SCAN_DATA", "CALIBRATED_CURRENTS");
+    fname = gSystem->BaseName(fname.Data());
+
+    fname.Prepend("/scratch_nfs/calibrated_currents/");
+
+    fits file(fname.Data());
+    if (!file)
+        return -2;
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Float_t med, dev;
+    if (!file.SetPtrAddress("Time",  &time) ||
+        !file.SetPtrAddress("I_med", &med))
+        return -2;
+
+    double med_avg  = 0;
+    int    cnt  = 0;
+
+    //cout << "Search for: " << beg-15773 << " " << end-15773 << endl;
+
+    while (file.GetNextRow())
+    {
+//        if (int(time)==15773)
+//            cout << time-15773 << endl;
+
+        if (time<beg)
+            continue;
+
+        if (time>end)
+            break;
+
+        med_avg += med;
+        cnt ++;
+    }
+
+    return cnt==0 ? -1 : med_avg/cnt;
+}
+
+TArrayD GetPointing(TString fname, Double_t beg, Double_t end)
+{
+    fname.ReplaceAll("RATE_SCAN_DATA", "DRIVE_CONTROL_TRACKING_POSITION");
+
+    fits file(fname.Data());
+    if (!file)
+        return TArrayD();
+
+    //cout << fname << endl;
+
+    Double_t time;
+    Double_t zd, az, ra, dec;
+    if (!file.SetPtrAddress("Time", &time) ||
+        !file.SetPtrAddress("Az",   &az)   ||
+        !file.SetPtrAddress("Zd",   &zd)   ||
+        !file.SetPtrAddress("Ra",   &ra)   ||
+        !file.SetPtrAddress("Dec",  &dec))
+        return TArrayD();
+
+    Int_t n = 0;
+
+    TArrayD rc;
+    while (file.GetNextRow())
+    {
+        if (time<beg)
+            continue;
+
+        if (time>end)
+            break;
+
+        if (rc.GetSize()==0)
+        {
+            rc.Set(6);
+
+            rc[0] = zd;
+            rc[1] = az;
+            rc[2] = zd;
+            rc[3] = az;
+
+            rc[4] = ra;
+            rc[5] = dec;
+            continue;
+        }
+
+        if (zd<rc[0]) rc[0] = zd;
+        if (zd>rc[2]) rc[2] = zd;
+
+        if (az<rc[1]) rc[1] = az;
+        if (az>rc[3]) rc[3] = az;
+
+        rc[4] += ra;
+        rc[5] += dec;
+
+        n++;
+    }
+
+    if (rc.GetSize()>0)
+    {
+        rc[4] /= n;
+        rc[5] /= n;
+    }
+
+    return rc;
+}
+
+struct data {
+    TString name;
+    int offset;
+    double time[2];
+    UShort_t th[2];
+    double rate[2];
+    int cnt;
+    Long64_t id;
+
+    data(TString fname)
+    {
+        name = fname;
+        offset = -100;
+        time[0] = time[1] = -1;
+        th[0] = th[1] = 0;
+        rate[0] = rate[1] = -1;
+        cnt = 0;
+        id = -1;
+    }
+};
+
+int Delete(MSQLMagic &serv, TString fname)
+{
+    TRegexp rex("20[0-1][0-9]/[01][0-9]/[0-3][0-9]");
+
+    TString date = fname(rex);
+
+    date.ReplaceAll("/", "-");
+
+    MTime beg;
+    beg.SetSqlDateTime(date);
+
+    TString query;
+    query += "fTimeBegin>'";
+    query += beg.GetSqlDateTime();
+    query += "' AND ";
+    query += "fTimeEnd<'";
+    query += MTime(beg.GetMjd()+1).GetSqlDateTime();
+    query += "'";
+
+    return serv.Delete("Ratescan", query) ? 1 : 2;
+}
+
+int Fill(MSQLMagic &serv, data &d)
+{
+    if (d.time[1]<0 || d.cnt==0 || d.th[0]==d.th[1])
+        return 1;
+
+    Int_t   volt    = CheckVoltage(d.name, d.time[0], d.time[1]);
+    Float_t current = GetCurrent(d.name, d.time[0], d.time[1]);
+    Float_t ov      = GetOffset(d.name, d.time[0], d.time[1]);
+    TArrayD point   = GetPointing(d.name, d.time[0], d.time[1]);
+
+    MTime tbeg(d.time[0]+d.offset);
+    MTime tend(d.time[1]+d.offset);
+
+    TString beg = tbeg.GetSqlDateTime();
+    TString end = tend.GetSqlDateTime();
+
+    cout << "=== BEG === " << beg  << '\n';
+
+    cout << " ID          " << d.id << endl;
+
+    if (current>=0)
+        cout << " CUR         " << current << '\n';
+
+    if (volt>=0)
+        cout << " VOLT        " << volt << '\n';
+
+    if (ov>-70)
+        cout << " OV          " << ov                      << '\n';
+
+    cout << " TH_beg      " << d.th[0]                  << '\n';
+    cout << " TH_end      " << d.th[1]                 << '\n';
+    cout << " RATE_beg    " << d.rate[0]                << '\n';
+    cout << " RATE_end    " << d.rate[1]               << '\n';
+    cout << " COUNT       " << d.cnt                     << '\n';
+    if (point.GetSize()>0)
+    {
+        cout << " ZD/AZ[deg]  " << point[0] << "/" << point[1] << " -- " << point[2] << "/" << point[3] <<'\n';
+        cout << " RA/DEC      " << point[4] << "h/" << point[5] << "deg\n";
+    }
+    cout << "=== END === " << MTime(d.time[1]+d.offset).GetSqlDateTime() << '\n' << endl;
+
+    TString vars;
+    if (volt>=0)
+        vars += Form("fVoltageIsOn=%d, ", volt);
+    if (current>=0)
+        vars += Form("fCurrentMedMean=%f, ", current);
+    if (ov>=-70)
+        vars += Form("fOvervoltage=%f, ", ov);
+    if (point.GetSize()>0)
+    {
+        vars += Form("fZdMin=%f, ", point[0]);
+        vars += Form("fZdMax=%f, ", point[2]);
+        vars += Form("fAzMin=%f, ", point[1]);
+        vars += Form("fAzMax=%f, ", point[3]);
+        vars += Form("fRaMean=%f, ", point[4]);
+        vars += Form("fDecMean=%f, ", point[5]);
+    }
+    vars += Form("fNight=%d, ",           MTime(tbeg.GetMjd()-1).GetNightAsInt());
+    vars += Form("fRatescanID=%d, ",      d.id);
+    vars += Form("fTimeBegin='%s', ",     beg.Data());
+    vars += Form("fTimeEnd='%s', ",       end.Data());
+    vars += Form("fRateBegin=%f, ",       d.rate[0]);
+    vars += Form("fRateEnd=%f, ",         d.rate[1]);
+    vars += Form("fThresholdBegin=%d, ",  d.th[0]);
+    vars += Form("fThresholdEnd=%d, ",    d.th[1]);
+    vars += Form("fNumPoints=%d ",       d.cnt);
+
+
+    return serv.Insert("Ratescan", vars);
+}
+
+int Process(MSQLMagic &serv, TString fname)
+{
+    data d(fname);
+
+    Int_t cnt = 0;
+
+    fits file(fname.Data());
+    if (!file)
+        return 2;
+
+    d.offset = file.GetUInt("MJDREF");
+
+    bool old = file.HasColumn("Data0");
+
+    /*  ================== That does not work, I don't know why ===================
+    Double_t  time;
+    ULong64_t id;
+    UInt_t    th;
+    Float_t   trig;
+    Float_t   ontime;
+
+    if (!file.SetPtrAddress(string("Time"), &time) ||
+        !file.SetPtrAddress(string(old ? "Data0" : "Id"), &id) ||
+        !file.SetPtrAddress(string(old ? "Data1" : "Threshold"), &th) ||
+        !file.SetPtrAddress(string(old ? "Data4" : "TriggerRate"), &trig) ||
+        !file.SetPtrAddress(string(old ? "Data3" : "RelOnTime"), &ontime))
+        return -1;
+    */
+    Double_t  *ptime   = file.SetPtrAddress("Time");
+    ULong64_t *pid     = file.SetPtrAddress(old ? "Data0" : "Id");
+    UInt_t    *pth     = file.SetPtrAddress(old ? "Data1" : "Threshold");
+    Float_t   *ptrig   = file.SetPtrAddress(old ? "Data4" : "TriggerRate");
+    Float_t   *pontime = file.SetPtrAddress(old ? "Data3" : "RelOnTime");
+
+    if (!ptime || !pid || !pth || !ptrig || !pontime)
+        return;
+
+    Double_t  &time   = *ptime;
+    ULong64_t &id     = *pid;
+    UInt_t    &th     = *pth;
+    Float_t   &trig   = *ptrig;
+    Float_t   &ontime = *pontime;
+
+    while (file.GetNextRow())
+    {
+        if (th>3000)
+            continue;
+
+        if (id!=d.id)
+        {
+            if (!Fill(serv, d))
+                return 0;
+
+            d.rate[0] = ontime>0 ? trig/ontime : -1;
+            d.time[0] = time;
+            d.th[0]   = th;
+            d.id      = id;
+
+            d.cnt = 0;
+        }
+
+        d.rate[1] = ontime>0 ? trig/ontime : -1;
+        d.time[1] = time;
+        d.th[1]   = th;
+
+        d.cnt++;
+    }
+
+    return Fill(serv, d);
+}
+
+int fillratescan(TString fname, Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillratescan" << endl;
+    cout << "------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    if (!Delete(serv, fname))
+        return 2;
+
+    //return Process(serv, fname);
+    if (!Process(serv, fname))
+        return 2;
+
+    return 1;
+}
+
+int fillratescan(Bool_t dummy=kTRUE)
+{
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << "fillratescan" << endl;
+    cout << "------------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << endl;
+
+    serv.SetIsDummy(dummy);
+
+    MDirIter Next("/fact/aux", "*RATE_SCAN_DATA.fits", 3);
+
+    while (1)
+    {
+        TString name = Next();
+        if (name.IsNull())
+            break;
+
+        if (name==".")
+            continue;
+
+        cout << "File: " << name << endl;
+        if (!Delete(serv, name))
+            return 2;
+        if (!Process(serv, name))
+            return 2;
+    }
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/magictemp.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/magictemp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/magictemp.C	(revision 17960)
@@ -0,0 +1,62 @@
+void magictemp(const char *fname, double beg=0, double end=100000)
+{
+    fits file(fname);
+
+    //file.PrintColumns();
+    //file.PrintKeys();
+
+    Double_t time;
+    Float_t temp;
+    file.SetPtrAddress("Time", &time);
+    file.SetPtrAddress("T", &temp);
+
+    UInt_t offset = file.GetUInt("MJDREF");
+    //cout << "offset: " << offset << endl;
+    if (beg < 30000)
+        beg+=offset;
+    if (end < 30000)
+        end+=offset;
+
+    double avg  = 0;
+    double rms  = 0;
+    int    cnt  = 0;
+
+    double last = -1;
+    double diff = -1;
+
+    while (file.GetNextRow())
+    {
+        time += offset;
+        //cout << time << " " << temp << endl;
+
+        if  (time>end)
+            break;
+
+        if (time<beg)
+        {
+            last = temp;
+            diff = beg-time;
+            continue;
+        }
+
+        avg += temp;
+        rms += temp*temp;
+        cnt ++;
+    }
+
+    if (cnt==0)
+    {
+        if (diff<5./24/3600)
+            return;
+
+        cout << "result " << last << " 0 " << endl;
+        return;
+    }
+
+    avg /= cnt;
+    rms /= cnt;
+
+    rms = sqrt(rms-avg*avg);
+
+    cout << "result " << avg << " " << rms << endl;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/numevents.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/numevents.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/numevents.C	(revision 17960)
@@ -0,0 +1,281 @@
+#include <iostream>
+
+#include <TCanvas.h>
+#include <TString.h>
+#include <TTree.h>
+#include <TFile.h>
+#include <TSystem.h>
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+
+#include "MSQLMagic.h"
+#include "MAlphaFitter.h"
+#include "MHThetaSq.h"
+#include "MStatusArray.h"
+
+
+using namespace std;
+
+//missing:
+// remove sourcekey in paths
+// create tables in DB
+
+int numevents(TString night="20130418", TString inpath="/daq/analysis/1/", TString table= "AnalysisResultsRunLP", Bool_t dummy=kTRUE, Bool_t pernight=kFALSE, Int_t source=0)
+{
+
+    //connect to mysql server
+    //MSQLServer serv("sql.rc");
+    MSQLMagic serv("sql.rc");
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+    serv.SetIsDummy(dummy);
+
+    //select runs, where star finished, format the list nicely
+    TString query;
+    query = " SELECT CONCAT(fNight, '_', LPAD(fRunID, 3, 0)), SUBSTRING(fNight, 1,4), SUBSTRING(fNight, 5,2), SUBSTRING(fNight, 7,2), ";
+    query += " fNight, fRunID FROM RunInfo";
+
+    //and only data runs
+    query+=" WHERE fRunTypeKEY=1 ";
+    query+=" AND fNight="+night;
+    //query+=" AND fRunID=128 ";
+    if (pernight)
+        query+=" GROUP BY fNight";
+
+    cout << "Q: " << query << endl;
+
+    //post the query
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - no result from query " << query << endl;
+        return 2;
+    }
+
+    //allocate variables to use in the loop
+    TString night2;
+    TString runid;
+    TString run;
+    TString year;
+    TString month;
+    TString day;
+    TString ganymed_fname;
+    TString star_fname;
+    TString where;
+    TString vars;
+
+    //the variables to save into the db
+    Int_t fNumEvtsAfterCleaning = 0;
+    Int_t fNumEvtsAfterQualCuts = 0;
+    Int_t fNumEvtsAfterBgCuts   = 0;
+    Float_t fNumBgEvts          = 0;
+    Float_t fNumSigEvts         = 0;
+    Float_t fNumExcEvts         = 0;
+    Float_t fNumIslandsMean     = 0;
+    Float_t fOnTimeAfterCuts    = 0;
+
+    //loop over the data files
+    TSQLRow *row=0;
+
+    /*
+    //cout the data names
+    cout<<"#evts_after_cleaning" << "    "
+        <<"evts_after_qual-cuts" << "    "
+        <<"evts_after_bg-cuts" << "    "
+        <<"mean_evts_from_off_regions"<< "    "
+        <<"evts_from_on_region"  << "    "
+        <<"calculated_excess_evts_in_file" << "    " << endl;
+    */
+
+    while ((row=res->Next()))
+    {
+        //use the results from the query
+        night2=(*row)[4];
+        runid=(*row)[5];
+        run=(*row)[0];
+        year=(*row)[1];
+        month=(*row)[2];
+        day=(*row)[3];
+
+        // to be fixed: path for nightly ganymeds
+        if (!pernight)
+            ganymed_fname=inpath+"/ganymed_run/"+year+"/"+month+"/"+day+"/"+run+"-analysis.root";
+        else
+            if (!source)
+                cout << "ERROR - source " << source << " not valid. " << endl;
+            else
+                ganymed_fname=Form("%s/ganymed_night/%d/%s-analysis.root", inpath.Data(), source, night2.Data());
+        cout << "gf => " << ganymed_fname << endl;
+
+        if (!pernight)
+        {
+            star_fname=inpath+"/star/"+year+"/"+month+"/"+day+"/"+run+"_I.root";
+            cout << "sf => " << star_fname << endl;
+
+            //check star file status
+            if (gSystem->AccessPathName(star_fname))
+            {
+                cout << "ERROR - file " << star_fname << " does not exist." << endl;
+                continue;
+            }
+
+            //try to open the star file
+            TFile star_file(star_fname, "READ");
+            if (!star_file.IsOpen())
+            {
+                cout << "ERROR - Could not open file " << star_fname << endl;
+                continue;
+            }
+
+            //Get the events tree
+            TTree *star_tree = (TTree *)star_file.Get("Events");
+            if (!star_tree)
+            {
+                cout << "ERROR - Could not read tree " << star_fname << endl;
+                continue;
+            }
+
+            //the number of events after cleaning
+            fNumEvtsAfterCleaning = star_tree->GetEntries();
+
+            //get the mean number of islands in the _I.root file on runbasis
+            star_tree->Draw("MImagePar.fNumIslands>>IslandHisto","","");
+            TH1F *HistJo = (TH1F*)gDirectory->Get("IslandHisto");
+            if (!HistJo)
+            {
+                cout << "ERROR - Reading of IslandHisto failed " << HistJo << endl;
+                continue;
+            }
+            fNumIslandsMean = HistJo->GetMean();
+        }
+
+        //check ganymed file status
+        if (gSystem->AccessPathName(ganymed_fname))
+        {
+            cout << "ERROR - file " << ganymed_fname << " does not exist." << endl;
+            continue;
+        }
+
+        //try to open the ganymed file
+        TFile ganymed_file(ganymed_fname, "READ");
+        if (!ganymed_file.IsOpen())
+        {
+            cout << "ERROR - Could not open file " << ganymed_fname << endl;
+            continue;
+        }
+
+        //Get the status display contents
+        MStatusArray arr;
+        if (arr.Read()<=0)
+        {
+            cout << "ERROR - could not read MStatusArray, file " << ganymed_fname << endl;
+            continue;
+        }
+
+        TH1D *vstime = (TH1D*)arr.FindObjectInCanvas("OnTime",  "TH1D", "OnTime");
+        if (!vstime)
+        {
+            cout << "WARNING - Reading of Theta failed." << endl;
+            continue;
+        }
+        fOnTimeAfterCuts = vstime->Integral();
+
+        //Get number of events after quality cuts
+        //from the number of entries in a histogram
+        TH1F *precut =
+                (TH1F*)arr.FindCanvas("PreCut")->FindObject("SizeSame");
+        if (!precut)
+        {
+            cout << "WARNING - Reading of PreCut canvas failed." << endl;
+            continue;
+        }
+        fNumEvtsAfterQualCuts = precut->GetEntries();
+
+        //Get number of events after background rejection cuts
+        //from the number of entries in a histogram
+        TH1F *postcut =
+                (TH1F*)arr.FindCanvas("PostCut")->FindObject("SizeSame");
+        if (!postcut)
+        {
+            cout << "WARNING - Reading of PostCut canvas failed." << endl;
+            continue;
+        }
+        fNumEvtsAfterBgCuts = postcut->GetEntries();
+
+        //Get signal, bg and excess events
+        MHThetaSq *halphaon = (MHThetaSq*)arr.FindObjectInCanvas("MHThetaSq", "Hist");
+        if (!halphaon)
+        {
+            cout << "WARNING - Reading of MHThetaSq failed, file " << ganymed_fname << endl;
+            continue;
+        }
+        const MAlphaFitter &fit = halphaon->GetAlphaFitter();
+        if (!&fit)
+        {
+            cout << "WARNING - Reading of MAlphaFitter failed, file " << ganymed_fname << endl;
+            continue;
+        }
+
+        //check if the excess events number is small and close to 0
+        //due to the computer precision error when subtracting sig and bg events
+        fNumBgEvts  = fit.GetEventsBackground();
+        fNumSigEvts = fit.GetEventsSignal();
+        fNumExcEvts = fit.GetEventsExcess();
+        fNumExcEvts = fabs(fNumExcEvts)<1e-5 ? 0 : fNumExcEvts;
+
+        /*
+        cout<< fNumEvtsAfterCleaning<< "    "
+            << fNumEvtsAfterQualCuts<< "    "
+            << fNumEvtsAfterBgCuts  << "    "
+            << fNumBgEvts           << "    "
+            << fNumSigEvts          << "    "
+            << fNumExcEvts          << endl; 
+        */
+
+        //inserting or updating the information in the database
+        if (!pernight)
+            vars = Form("fRunID=%s, fNight=%s,", runid.Data(), night2.Data());
+        else
+            vars = Form("fNight=%s, fSourceKey=%d, ", night2.Data(), source);
+        vars += Form(" fNumEvtsAfterQualCuts=%d, "
+                    " fNumEvtsAfterBgCuts=%d, "
+                    " fNumBgEvts=%6.1f, "
+                    " fNumSigEvts=%6.1f, "
+                    " fNumExcEvts=%6.1f, "
+                    " fOnTimeAfterCuts=%7.2f ",
+                    fNumEvtsAfterQualCuts,
+                    fNumEvtsAfterBgCuts,
+                    fNumBgEvts,
+                    fNumSigEvts,
+                    fNumExcEvts,
+                    fOnTimeAfterCuts
+                   );
+        if (!pernight)
+            vars += Form(", fNumIslandsMean=%6.2f, fNumEvtsAfterCleaning=%d ",
+                         fNumIslandsMean,
+                         fNumEvtsAfterCleaning
+                        );
+                    
+
+        if (pernight)
+            where = Form("fNight=%s AND fSourceKey=%d", night2.Data(), source);
+        else
+            where = Form("fRunID=%s AND fNight=%s", runid.Data(), night2.Data());
+
+        cout << "vars: " << vars << endl;
+        cout << "where: " << where << endl;
+
+        if (!serv.InsertUpdate(table, vars, where))
+        {
+            cout << "ERROR - insert/update to DB failed  (vars:" << vars << " where: " << where << ")." << endl;
+            return 2;
+	}
+
+    }
+
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/fact/processing/ontime.C
===================================================================
--- branches/Mars_McMismatchStudy/fact/processing/ontime.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/processing/ontime.C	(revision 17960)
@@ -0,0 +1,129 @@
+void ontime(const char *fname, double beg=0, double end=100000)
+{
+    //open the file
+    fits file(fname);
+
+    //file.PrintColumns();
+    //file.PrintKeys();
+
+    //allocate variables to read data into
+    Double_t time;
+    Float_t OnTime, ElTime, TriggerRate;
+    file.SetPtrAddress("Time",  &time);
+    file.SetPtrAddress("OnTime", &OnTime);
+    file.SetPtrAddress("ElapsedTime", &ElTime);
+    file.SetPtrAddress("TriggerRate", &TriggerRate);
+
+    //some file MJDREF offset fun. Before a given day, the MJDREF was not subtracted correctly.
+    //Also, see the logbook for more details (there are also some broken files)
+    UInt_t offset = file.GetUInt("MJDREF");
+    if (beg < 30000)
+        beg+=offset;
+    if (end < 30000)
+        end+=offset;
+
+    //variables to calculate stuff with
+    double  SumOnTime           = 0.;   //Sum up the OnTime_i for later effective on calculation
+    double  SumElTime           = 0.;   //sum up ElTime_i for later effective on calculation
+
+    double  SumOnEl             = 0.;   //Sum of the OnTime_i / ElapsedTime_i
+    double  SumOnEl2            = 0.;   //Sum of the (OnTime_i / ElapsedTime_i)^2,
+                                        //both values needed for variance of the effective on timeseries
+
+    double  EffectiveOn         = 0.;   //this will be the one effective on value
+    double  EffectiveOnRMS      = 0.;   //this will be variance(effective on)
+    int     counter             = 0;    //cnt the number of non zero ElTime datapoints
+
+    double  TriggerTimeOver100  = 0.;   //this will be the time  in sec the Trigger
+    double  TriggerTimeOver125  = 0.;   //is above 100Hz,125Hz,...
+    double  TriggerTimeOver150  = 0.;
+    double  TriggerTimeOver175  = 0.;
+
+    double  SumRate             = 0.;   //for calculating the sqrt(var) of the trigger rate
+    double  SumRate2            = 0.;   //same
+    double  TriggerRateRms      = 0.;
+    int     ratecounter         = 0;
+
+    //loop over all rows in slow-file
+    while (file.GetNextRow())
+    {
+        //add the offset, as the data is saved with the offset subtracted
+        time += offset;
+
+        //if the end of the run is reached, break
+        if (time>end)
+            break;
+
+        //if the data is before the beginning of the run, continue
+        if (time<beg)
+        {
+            continue;
+        }
+
+        //sum the data for the mean effective on
+        SumOnTime   += OnTime;
+        SumElTime   += ElTime;
+
+        //sum the data for the variance of the effective on timeseries, check for zero elapsed time
+        if (ElTime>0){
+            SumOnEl     += OnTime/ElTime;
+            SumOnEl2    += OnTime/ElTime*OnTime/ElTime;
+            counter++;
+            //cout << "OnTime:" << OnTime << " # ElTime:" << ElTime << " # OnTime/ElTime:" << OnTime/ElTime << " # (OnTime/ElTime)^2:" << OnTime/ElTime*OnTime/ElTime << " # Counter:" << counter << endl;
+        }
+
+        //to calculate the sqrt(var) of the rate
+        SumRate     +=TriggerRate;
+        SumRate2    +=TriggerRate*TriggerRate;
+        ratecounter +=1;
+
+        //sum the time the triggerate is over 100Hz, 125Hz,...
+        if (TriggerRate>100.){
+            TriggerTimeOver100 += ElTime;
+
+            if (TriggerRate>125.){
+                TriggerTimeOver125 += ElTime;
+
+                if (TriggerRate>1500.){
+                    TriggerTimeOver150 += ElTime;
+
+                    if (TriggerRate>175.){
+                        TriggerTimeOver175 += ElTime;
+
+                    }
+                }
+            }
+        }
+
+    }
+
+    //cout << "SumOnEl2:" << SumOnEl2 << " # SumOnEl:" << SumOnEl << " # (SumOnEl2/counter-(SumOnEl/counter*SumOnEl/counter)): " << (SumOnEl2/counter-(SumOnEl/counter*SumOnEl/counter)) << endl;
+
+    //calculate the return values, watch out for traps when doing math operations!
+    EffectiveOn         = SumElTime>0 ? SumOnTime/SumElTime : 0.;
+    EffectiveOnRMS      = counter>0 ? (SumOnEl2/counter-
+                                       (SumOnEl/counter*SumOnEl/counter)) : 0.;
+    EffectiveOnRMS      = EffectiveOnRMS>0 ? sqrt(EffectiveOnRMS) : 0;
+    TriggerRateRms      = ratecounter>0? (SumRate2/ratecounter-
+                                          (SumRate/ratecounter*SumRate/ratecounter)) : 0.;
+    TriggerRateRms      = TriggerRateRms>0 ? sqrt(TriggerRateRms) : 0;
+
+    //check for crap data, which happenes sometimes...
+    if (EffectiveOn>1.) EffectiveOn = 1.;
+    if (EffectiveOnRMS>0.5) EffectiveOnRMS = 0.5;
+    if (TriggerRateRms>1000) TriggerRateRms = 0.;
+
+    //return fun. The style from daniela (grep the output) requires an non scientific notation,
+    //i.e. withour exponential+ therefore set the precision to ~double with fixed width after decimal point
+    cout << setiosflags(ios::fixed) << setprecision(12)
+         << "result "
+         << EffectiveOn         << " "
+         << EffectiveOnRMS      << " "
+         << SumOnTime           << " "
+         << TriggerTimeOver100  << " "
+         << TriggerTimeOver125  << " "
+         << TriggerTimeOver150  << " "
+         << TriggerTimeOver175  << " "
+         << TriggerRateRms  << " "
+         << endl;
+}
Index: branches/Mars_McMismatchStudy/fact/resources/sequences.rc
===================================================================
--- branches/Mars_McMismatchStudy/fact/resources/sequences.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/fact/resources/sequences.rc	(revision 17960)
@@ -0,0 +1,230 @@
+#/////////////////////////////////////////////////////////////////////////
+#
+# This file is compiled from two sections. One defines which transitions
+# are allowed to build a sequence (for example changing L1 Trigger
+# Tables between Calibration and Pedestal runs). The other section 
+# defines a regular expression to define the allowed ordering
+# of the P-, C- and D-runs.
+#
+# The sections a introduced by [Transition] and [Regexp]. For further
+# details see below.
+#
+# If a section should be valid only for one telescope use:
+#   [Transition]         # Valid for all telescope numbers
+#   [Transition 5]       # Valid for telescope 5
+#   [Transition: 5]      # Valid for telescope 5
+#   [Transition: 5 6]    # Valid for telescopes 5 and 6
+#
+#
+# File-Id:
+#   A file is uniquely identified by run-number and file-number.
+#   If you give just a number it is identical to run-number with
+#   file-number 0. To give a dedicated file-number you can use:
+#     run.file
+#
+#/////////////////////////////////////////////////////////////////////////
+
+##########################################################################
+#
+# Explanation [Transition]
+#
+# Rules to build blocks which will later be broken into sequences
+#
+# Syntax:
+#
+# [Transition]
+# rule1
+# rule2
+# rule3
+#
+#
+# Colums of rule:
+# 0 [1 2 3 4 [5 [6]]]
+# 
+# 0: Table/Column to which the transition is applied
+# 1: Run type of previous run
+# 2: Run type of run to be accepted
+# 3: Key for previous run
+# 4: key for run to be accepted
+# 5: first file-id to apply this rule <default=0>
+# 6: last  file-id to apply this rule <default=max>
+#
+# Run Types:
+#  D  2
+#  P  3
+#  C  4
+#
+# The columns 1-4 can be expressed as regular expressions (ala TRegexp)
+# a ^ is prepended and a $ is appended automatically.
+#
+# A single "*" is an abbreviation for the regexp ".*" .
+#
+# As soon as any transition (column 0) is specified this transisiton 
+# is checked not to change within a sequence.
+#
+# A "-" is an abbreviation for transitions "to be ignored". For example:
+#     [Transition]
+#     Test - 4 * 1200 1300
+# would mean:
+#     ignore all keys (*) of column test for all current files
+#     with run-type 4 if its file-id is between 1200.0 and 1300.0
+#     The (former) third column in this case is obsolete.
+#
+# Each Transition which appears at least once is checked.
+#
+
+[Transition: 1]
+
+# Ignore project name for calibration files between 20100 and 45100
+#Project           - 4 *    20100 45100
+#HvSettings        - 2 *    86094 86094
+#TriggerDelayTable
+#ObservationMode
+
+# Transition setup for L1/2-TriggerTable of very old data
+#L1TriggerTable  3 2  1 [235]  26206 35478
+#L1TriggerTable  2 3  [235] 1  26206 35478
+
+#L1TriggerTable  - [^2] * 0 26830
+#L2TriggerTable  - [^2] * 0 26830
+
+#L1TriggerTable  2 4  3 1  26816 39429
+
+#L2TriggerTable  3 2  7 2  36049 38012
+#L2TriggerTable  2 3  2 7  36053 38011
+
+#L2TriggerTable  4 3  9 7  20170 37382
+#L2TriggerTable  3 4  7 9  22712 37935
+
+#L2TriggerTable  3 2  7 5  26207 35455
+#L2TriggerTable  2 3  5 7  26207 35477
+
+#L2TriggerTable  4 2  9 2  36157 37938
+#L2TriggerTable  4 3  5 7  26207 35477
+#L2TriggerTable  3 2  7 5  35460 36478
+#L2TriggerTable  2 4  5 9  27170 31869
+
+
+# The Discriminator Thresholds do not influence the pedestal- and
+# calibration-trigger and need therefore not to be checked for these runs.
+# This allows all kind of transitions from P/C to P/C and from C to D.
+#DiscriminatorThresholdTable  [34]  [34]   *   *
+#DiscriminatorThresholdTable    4     2    *   *
+
+# This defines which changes in the calibration script are allowed
+# P 177: CPedestals_500Hz
+# P 199: Pedestals_500Hz
+# C 180: 23Led_Blue
+# C 181: 10_Led_UV
+# C 182: 1Led_Green
+# C 183: 10Led_Blue
+# C 195: 1Led_Blue
+# C 207: 10Led_UV_PinDiode
+# C 256: 10Led_UV_PEDANDCAL_1kHz
+# D 179: 10Led_UV_50Hz
+# D 209: 10Led_UV_50Hz_PinDiode
+# D 238: 10Led_UV_50Hz_PinDiode.  <---  has an additional dot
+# D 188: 10Led_UV_train50Hz
+# D 200: 10Led_UV_train50Hz_PinDiode
+# D 210: 10Led_Blue_50Hz
+# D 245: 10Led_UV_50Hz_Ped
+
+# Current DEFAULT setup. This what is used to build the
+# sequences from the newest data
+#CalibrationScript  2 3  209 199                      79266 200000
+#CalibrationScript  3 4  199 207                      50640
+#CalibrationScript  4 2  207 209                      91301
+#CalibrationScript  4 3  207 199                      53875 200000
+#CalibrationScript  4 2  207 245                     200000
+#CalibrationScript  3 4  199 256                    1007866
+#CalibrationScript  4 2  256 245                    1007866
+#CalibrationScript  3 4  199 181                    1007844
+#CalibrationScript  4 2  181 245                    1007844
+
+# Previous defaults. This are cases which are widely used
+# through our data and can thus be considered old defaults
+#CalibrationScript  4 2  181 179                      46305 50600
+#CalibrationScript  4 2  207 209                      50641 84570
+#CalibrationScript  4 2  207 179                      50879 91252
+#CalibrationScript  2 3  179 199                      46313 91423
+#CalibrationScript  2 3  209 199                      50784 79256
+#CalibrationScript  3 2  199 179                      46313 90220
+
+#CalibrationScript  3 2  199 209                      50785 57781
+#CalibrationScript  3 4  199 181                      45730 50805
+
+# This was used only in some rare cases (still to be checked!)
+# This are cases used through a big part of our data
+# but take place only in some single cases.
+#CalibrationScript  4 3  181 199                      46405 50137
+#CalibrationScript  3 4  199 181                      67116 68714
+#CalibrationScript  2 4  179 207                      87824 87842
+
+# Single calibration runs inbetween data. Should be
+# excluded differently, because these blocks will not
+# give valid sequences anyhow
+#CalibrationScript  2 4  179 207                      68731 68731
+#CalibrationScript  2 4  179 207                      61374 61459
+#CalibrationScript  2 4  179 207                      53901 53901
+#CalibrationScript  2 4  179 207                      51153 51170
+#CalibrationScript  2 4  188 181                      50084 50084
+#CalibrationScript  2 4  209 207                      96951 96951
+
+# For some reasons here are two consecutive calibration
+# runs with two different colors (still to be checked!)
+#CalibrationScript  4 4  181 183                      51173 51173
+
+# Special setup for more than one C-Run. Old data had several
+# calibration runs with different taken sequentually
+#CalibrationScript  4 4  (181|195) (182|183|193|195)  44834 45579
+
+# This was a typo 238 is basically the same as 209
+#CalibrationScript  4 2  207 238                      78696 78696
+
+# This is for runs with special calibration scripts (177,188,200,210)
+#CalibrationScript  2 3  (179|188|200) (177|199)      44831 46223
+#CalibrationScript  3 2  (177|199) (179|188|200)      44831 46223
+#CalibrationScript  4 2  (181|182|195) (188|200)      44831 46223
+#CalibrationScript  3 4  177 (181|195)                44831 45718
+#CalibrationScript  4 3  181 177                      44831 45717
+#CalibrationScript  4 2  181 188                      50083 50273
+#CalibrationScript  3 2  199 188                      50083 50273
+#CalibrationScript  2 3  188 199                      50083 50273
+#CalibrationScript  4 2  207 210                      50687 50746
+#CalibrationScript  2 3  210 199                      50687 50746
+#CalibrationScript  3 2  199 210                      50687 50746
+
+# Special rules for calibration script 183
+#CalibrationScript  2 4  209 183                      50642 50642
+#CalibrationScript  4 3  183 199                      51193 51193
+#CalibrationScript  2 4  179 183                      51192 51192
+#CalibrationScript  4 2  183 179                      51174 51174
+
+#########################################################################
+#
+# Explanation [Regexp]
+#
+# To build sequences a string with the run-types is evaluated.
+# A capital case D or P means: The nearest C-Run is the last C-Run
+# A lower case   d or p means: The nearest C-Run is the next C-Run
+#
+# The first expression is evaluated first. The last one last.
+# If one regexp matches the others are not evaluated anymore and
+# the sequence is build from the match.
+#
+# For details on regular expressions check 
+#     http://perldoc.perl.org/perlre.html
+#
+# The syntax is
+#   [Regexp]
+#   regexp [firstrun [lastrun]]
+#
+[Regexp: 1]
+
+#BGBB?T(BG)?PP? 0
+BGBB?TU?PP? 0
+PCD+        0
+
+#[bB][gG][bB][bB][tT][pP][pP] 0 20120116
+#[bB][gG][bB][bB][tT][pP][pP] 0 20120116
+#[pP][cC][dD]+                0
Index: branches/Mars_McMismatchStudy/ganymed.cc
===================================================================
--- branches/Mars_McMismatchStudy/ganymed.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/ganymed.cc	(revision 17960)
@@ -0,0 +1,350 @@
+#include <TTree.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MDataSet.h"
+#include "MJCut.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "========================================================" << endl;
+    gLog << "                  Ganymed - MARS V" << MARSVER            << endl;
+    gLog << "   MARS -- Gammas Are Now Your Most Exciting Discovery"   << endl;
+    gLog << "     Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " ganymed [options] dataset.txt|number" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   dataset.txt:              File defining a collection of datasets/sequences"   << endl;
+    gLog << "                             (for more details see MSequence/MDataSet)"          << endl;
+    gLog << "   number:                   The dataset number (using file in the datacenter)"  << endl;
+    gLog << "                             For more details see MDataSet."                     << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)"         << endl;
+    gLog << endl;
+    gLog << " Operation Mode:" << endl;
+    gLog << "   -mc                       Monte Carlo dataset (no times)"                     << endl;
+    gLog << "   --wobble                  Force wobble mode (overwrites dataset)"             << endl;
+    gLog << "   --no-wobble               Force normal mode (overwrites dataset)"             << endl;
+    gLog << endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>"      << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after execution"        << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup"  << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file and"     << endl;
+    gLog << "                             command line" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << "   --rc=Name:option          Set or overwrite a resource of the resource file."  << endl;
+    gLog << "                             (Note, this option can be used multiple times)"     << endl;
+    gLog << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   --n=number                Analysis number (required if not in dataset file)"  << endl;
+    gLog << "   --dataset=number          Choose a dataset from a collection of datasets"     << endl;
+    gLog << "                             in your file (for more details see MDataSet)"       << endl;
+    gLog << "   --out=path                Path to write all output to [def=local path]"       << endl;
+    gLog << "   --ind=path                Path to data/star files [default=datacenter path]"  << endl;
+    gLog << "   --ins=path                Path to sequence files [default=datacenter path]"   << endl;
+    gLog << "   --outf=filename           Filename for output file (eg. status display)"      << endl;
+    gLog << "   --sum[=filename]          Enable writing of summary file (events after cut0)" << endl;
+//    gLog << "   --res[=filename]          Enable writing of result file (surviving events)" << endl;
+    gLog << "   --skip-res                Disable writing of result events"                   << endl;
+    gLog << "   --write-only              Only write output files. No histograms filled."     << endl;
+    gLog << "   --print-ds                Print dataset as interpreted from the dataset file" << endl;
+    gLog << "   --print-files             Print files from sequences, '+' found, '-' missing" << endl;
+//    gLog << "   --full-display            Show as many plots as possible" << endl;
+    gLog << "   --config=ganymed.rc       Resource file [default=ganymed.rc]"                 << endl;
+    gLog << endl;
+    gLog << "   --max-file-size=number    Sets the maximum size before root opens a new file" << endl;
+    gLog << "                             automatically. The number is given in kB (1000b)."  << endl;
+    gLog << "                             Use this option with caution it can result in"      << endl;
+    gLog << "                             extremely large files (especially summary files),"  << endl;
+    gLog << "                             use (e.g. lower size) cuts instead to decrease"     << endl;
+    gLog << "                             the file size. Root's default is 1.9GB."            << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number"           << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Ganymed is the largest moon of Jupiter, a large, icy, outer moon that" << endl;
+    gLog << " is scarred  with impact craters  and  many parallel faults.  It has a" << endl;
+    gLog << " diameter of about  5268km  and orbits  Jupiter  at a mean distance of" << endl;
+    gLog << " 1,070,000km.  It has a magnetic field  and probably has a molten iron" << endl;
+    gLog << " core.  It takes  Ganymed  7.15 days to  orbit  Jupiter.  Its mass  is" << endl;
+    gLog << " 1.5e23kg. It was independently discovered by  Galileo and S.Marius in" << endl;
+    gLog << " 1610.  Ganymed is  the largest moon  in the solar system;  it is also" << endl;
+    gLog << " larger than the planets Mercury and Pluto." << endl << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    // FIXME: Record command line to file!!!
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    const TString kConfig       = arg.GetStringAndRemove("--config=", "ganymed.rc");
+
+    const Bool_t  kPrintSeq     = arg.HasOnlyAndRemove("--print-ds");
+    const Bool_t  kPrintFiles   = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kDebugMem     = arg.HasOnlyAndRemove("--debug-mem");
+    const Bool_t  kWriteOnly    = arg.HasOnlyAndRemove("--write-only");
+//    const Bool_t  kFullDisplay  = arg.HasOnlyAndRemove("--full-display");
+    Int_t  kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit          = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch         = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite     = arg.HasOnlyAndRemove("-f");
+    //const Bool_t  kForceExec   = arg.HasOnlyAndRemove("-ff");
+
+    const Bool_t  kIsMc          = arg.HasOnlyAndRemove("-mc");
+    const Bool_t  kWobbleModeOn  = arg.HasOnlyAndRemove("--wobble");
+    const Bool_t  kWobbleModeOff = arg.HasOnlyAndRemove("--no-wobble");
+
+    const Int_t   kNumAnalysis   = arg.GetIntAndRemove("--n=", -1);
+    const Int_t   kNumDataset    = arg.GetIntAndRemove("--dataset=", -1);
+    const TString kOutpath       = arg.GetStringAndRemove("--out=",  ".");
+    const TString kOutfile       = arg.GetStringAndRemove("--outf=",  "");
+    const TString kPathDataFiles = arg.GetStringAndRemove("--ind=",  "");
+    const TString kPathSequences = arg.GetStringAndRemove("--ins=",  "");
+    const Bool_t  kWriteSummary  = arg.HasOnlyAndRemove("--sum");
+    const TString kNameSummary   = arg.GetStringAndRemove("--sum=");
+    const Bool_t  kSkipResult    = arg.HasOnlyAndRemove("--skip-res");
+
+//    const Bool_t  kWriteResult   = arg.HasOnlyAndRemove("--res");
+//    const TString kNameResult    = arg.GetStringAndRemove("--res=");
+
+    TTree::SetMaxTreeSize((Long64_t)arg.GetIntAndRemove("--max-file-size=", TTree::GetMaxTreeSize()/1000)*1000);
+
+    if (kWobbleModeOn && kWobbleModeOff)
+    {
+        gLog << err << "ERROR - Wobble mode options are exclusive." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // check for the right usage of the program (number of arguments)
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        gLog << warn << "WARNING - Wrong number of arguments..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // Now we access/read the resource file. This will remove all
+    // --rc= from the list of arguments.
+    //
+    MEnv env(kConfig, "ganymed.rc");
+    if (!env.IsValid())
+    {
+        gLog << err << "ERROR - Reading resource file " << kConfig << "." << endl;
+        return 0xfe;
+    }
+
+    // And move the resource options from the command line to the MEnv
+    if (!env.TakeEnv(arg, kDebugEnv>2))
+        return 0xfd;
+
+    //
+    // check for the right usage of the program (number of options)
+    //
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown command-line options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 2;
+    }
+
+    //
+    // Setup sequence file and check for its existence
+    //
+    TString kSequences = arg.GetArgumentStr(0);
+
+    //
+    // Something special for datacenter access
+    //
+    if (kSequences.IsDigit())
+    {
+        const Int_t numseq = kSequences.Atoi();
+        kSequences = Form("/magic/datasets/%05d/dataset%08d.txt", numseq/1000, numseq);
+        gLog << inf << "inflated dataset file: " << kSequences << endl;
+    }
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Setup sequence and check its validity
+    //
+    MDataSet seq(kSequences, (UInt_t)kNumDataset, kPathSequences, kPathDataFiles);
+    if (!seq.IsValid())
+    {
+        gLog << err << "ERROR - Reading dataset file " << kSequences << "." << endl;
+        return 0xfc;
+    }
+    if (!seq.IsMonteCarlo())
+        seq.SetMonteCarlo(kIsMc);
+    if (kWobbleModeOn || kWobbleModeOff)
+        seq.SetWobbleMode(kWobbleModeOn);
+    if (kNumAnalysis>=0)
+        seq.SetNumAnalysis(kNumAnalysis);
+    if (kPrintSeq || kPrintFiles)
+    {
+        gLog << all;
+        gLog.Separator(kSequences);
+        seq.Print(kPrintFiles?"files":"");
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Dataset read but not valid (maybe analysis number not set)!" << endl << endl;
+        return 2;
+    }
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("ganymed", &argc, argv);
+    if ((!gROOT->IsBatch() && !gClient) || (gROOT->IsBatch() && !kBatch))
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(Form("-- Ganymed: %s --", kSequences.Data()));
+
+    //
+    // Run cut program. (block for debug-mem)
+    //
+    {
+        MJCut job(Form("MJCut #%d", seq.GetNumAnalysis()));
+        job.SetEnv(&env);
+        job.SetEnvDebug(kDebugEnv);
+        job.SetDisplay(d);;
+        job.SetOverwrite(kOverwrite);
+        job.SetPathOut(kOutpath);
+        job.SetNameOutFile(kOutfile);
+        job.SetNameSummaryFile(kNameSummary);
+        job.SetCommandLine(MArgs::GetCommandLine(argc, argv));
+        //job.SetNameResultFile(kNameResult);
+        job.EnableWriteOnly(kWriteOnly);
+        //if (kFullDisplay)
+        //    job.EnableFullDisplay(kFullDisplay);
+        job.EnableStorageOfResult(!kSkipResult);
+        if (kWriteSummary) // Don't change flag set in SetNameSummaryFile
+            job.EnableStorageOfSummary();
+        //if (kWriteResult)  // Don't change flag set in SetNameSummaryFile
+        //    job.EnableStorageOfResult();
+
+        const Int_t rc = job.Process(seq);
+        if (rc<=0)
+        {
+            gLog << err << "Calculation of cuts failed." << endl << endl;
+
+            //error coding for the automatic analysis (to be filled into the database)
+            switch (rc)
+            {
+            case  0:        // MJCut failed
+                return 3;
+            case -1:        // Source not found
+                return 4;
+            case -2:        // FillRndSrcCam failed
+                return 5;
+            case -3:        // Processing off-data failed
+                return 6;
+            case -4:        // Processing on-data failed
+                return 7;
+            }
+            return 2;
+        }
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/ganymed.rc
===================================================================
--- branches/Mars_McMismatchStudy/ganymed.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/ganymed.rc	(revision 17960)
@@ -0,0 +1,221 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                               Cuts
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write output to somewhere here you can give
+# the output path
+# -------------------------------------------------------------------------
+#MJCuts.PathOut: .
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+BinningAlpha.Raw:        36    0    90
+BinningFalseSource.Raw:  91   -1.5  1.5
+BinningWidth.Raw:        50    0    1
+BinningLength.Raw:       25    0    1
+BinningDist.Raw:         25    0    2
+BinningAsym.Raw:         51   -0.7  0.7
+BinningM3Long.Raw:       51   -0.7  0.7
+BinningM3Trans.Raw:      51   -0.7  0.7
+BinningSlope.Raw:        51   -7.5  7.5
+
+# -------------------------------------------------------------------------
+# Using the starguider for pointing correction. 
+# To switch it off use "MPointingDevCalc.MaxAbsDev: -1"
+# For details see the class reference of MPointingDevCalc
+# -------------------------------------------------------------------------
+#MPointingDevCalc.MaxAbsDev:   15
+#MPointingDevCalc.NumMinStars: 8
+#MPointingDevCalc.NsbLevel:    3.0
+#MPointingDevCalc.NsbMin:      30
+#MPointingDevCalc.NsbMax:      60
+#MPointingDevCalc.Dx          -0.001
+#MPointingDevCalc.Dy          -0.004
+#MPointingDevCalc.MaxAge       1.0
+
+MPointingDevCalc.PointingModels: 1 81855 83722 89180 267253 291104 328198 1000534
+
+# -------------------------------------------------------------------------
+# Setup misfocussing correction (see class reference for MSrcPosCorrect)
+# -------------------------------------------------------------------------
+#MSrcPosCorrect.Dx: 0
+#MSrcPosCorrect.Dy: 0
+
+# -------------------------------------------------------------------------
+# Setup fit mode and ranges
+# -------------------------------------------------------------------------
+#MAlphaFitter.SignalIntegralMax:    15
+#MAlphaFitter.SignalFitMax:         25
+#MAlphaFitter.BackgroundFitMin:     35
+#MAlphaFitter.BackgroundFitMax:     75
+#MAlphaFitter.ScaleMin:             35
+#MAlphaFitter.ScaleMax:             80
+#MAlphaFitter.PolynomOrder:         2
+#MAlphaFitter.ScaleMode:            None
+
+# -------------------------------------------------------------------------
+# Define here which histogram class to use to determin the signal.
+# Currently availyble: MHAlpha, MHTheta <default>
+# -------------------------------------------------------------------------
+#MJCut.NameHist: MHAlpha
+
+# Be carefull: The spectrum might be done with a different binning
+# This might change the scale factor
+#MHThetaSq.NumBinsSignal:   3
+#MHThetaSq.NumBinsTotal:   75
+
+# -------------------------------------------------------------------------
+# To get a meaningfull false source plot in wobble mode use magic cuts
+# and the following two lines.
+# -------------------------------------------------------------------------
+MJCut.NameHistFS: MHDisp
+
+MHDisp.Smearing: 0.06
+#MHDisp.Wobble:   Yes
+#MHDisp.ScaleMin: 0.325
+#MHDisp.ScaleMax: 0.475
+
+# -------------------------------------------------------------------------
+# To get/use a random source position in the off data with the distribution
+# in the camera of the on-data
+# -------------------------------------------------------------------------
+#MJCut.RandomSourcePosition: Yes
+
+# -------------------------------------------------------------------------
+# There are three cuts:
+#   CutQ: Cut after reading file
+#   Cut0: After calculation of src dependent parameters, energy estimation
+#         and disp calculation, before writing summary file
+#   Cut1: After writing summary file before filling false source plots
+#   Cut2: After filling false source plots before filling alpha plots
+#   Cut3: After filling alpha plots (eg. Alpha cuts) for image parameter
+#         display, eg. write only events after alpha cut to ganymed file
+# -------------------------------------------------------------------------
+CutQ.Inverted: Yes
+Cut0.Inverted: Yes
+Cut1.Inverted: Yes
+Cut2.Inverted: Yes
+Cut3.Inverted: Yes
+
+# Quality-cuts (remove unphysical and obvious non-gamma events)
+CutQ.Condition: {0} && {1} && {2} && {3} && {4} && {5}
+CutQ.0: MImagePar.fNumIslands<3
+CutQ.1: MNewImagePar.fNumUsedPixels>5
+CutQ.2: MNewImagePar.fLeakage1 < 0.3
+CutQ.3: log10(MNewImagePar.fConcCOG)<-0.45+0.08*(log10(MHillas.fSize)<3.9)*(log10(MHillas.fSize)-3.9)^2
+CutQ.4: log10(MNewImagePar.fConc1)  <-0.75+0.10*(log10(MHillas.fSize)<3.8)*(log10(MHillas.fSize)-3.8)^2
+CutQ.5: MHillas.fLength>-3.6*(log10(MHillas.fSize)-6.0)^2+70
+
+# -------------------------------------------------------------------------
+# Such a cut could be used to exclude strange pointing positions. like
+# the camera center in wobble mode. Note, that a cut in the poiting
+# position directly influences the effective observation time and should
+# only be applied if the events are lost anyhow. In both cases you must
+# correct for the loss of observation time calculating your flux!
+# -------------------------------------------------------------------------
+#Cut0.Condition: MSrcPosCam.GetDist*MGeomCam.fConvMm2Deg>0.3
+
+# ---------- SETUP FOR ONOFF-MODE -----------
+MAlphaFitter.ScaleMin: 0.137
+MAlphaFitter.ScaleMax: 0.640
+MAlphaFitter.BackgroundFitMin: 0.137
+MAlphaFitter.BackgroundFitMax: 1.000
+MAlphaFitter.PolynomOrder: 1
+MAlphaFitter.ScaleMode: OffRegion
+MAlphaFitter.SignalFunction: ThetaSq
+
+# For more details on the magic cuts see its class reference
+Cut1.Condition: MFMagicCuts
+Cut1.ThetaCut: None
+# Parametrization of Disp
+Cut1.Param0:   1.15136
+Cut1.Param8:   0.0681437
+Cut1.Param9:   2.62932
+Cut1.Param10:  1.51279
+Cut1.Param11:  0.0507821
+# Parametrization for sign of disp (m3long, slope)
+Cut1.Param5:  -0.07
+Cut1.Param6:   7.2
+Cut1.Param7:   0.5
+# ThetaSq-Cut
+Cut1.Param1:   0.215
+# Area-Cut
+Cut1.Param2:   0.215468
+Cut1.Param3:   5.63973
+Cut1.Param4:   0.0836169
+
+# ---------- SETUP FOR WOBBLE-MODE -----------
+#MAlphaFitter.ScaleMode: none
+#MAlphaFitter.BackgroundFitMin: 0.09
+#MAlphaFitter.BackgroundFitMax: 0.25
+#MAlphaFitter.PolynomOrder: 1
+#MAlphaFitter.SignalFunction: ThetaSq
+
+# ---------- SETUP TO USE RANDOM FOREST -----------
+
+# To switch on random forest uncomment the following lines
+#Cut1.HadronnessCut: Hadronness
+#Cut1.Param13: 0.5
+#Cut1.Param14: 100
+
+# To use both, hadronness and area cut do
+#Cut1.HadronnessCut: All
+
+# -------------------------------------------------------------------------
+# This cut is applied exclusively to the plots in the tab CutT. It is
+# resonable to show the events within your signal region here to
+# see if your signal region is clean from strange events (e.g. sparks)
+# -------------------------------------------------------------------------
+CutT.Condition: ThetaSquared.fVal < ThetaSquaredCut.fVal
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to calc hadronness) before Cut1
+# -------------------------------------------------------------------------
+# CalcHadronness: MRanForestCalc
+# CalcHadronness.FileName: rf-separation.root
+# CalcHadronness.NameOutput: Hadronness
+# CalcHadronness.Debug: No
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to calc disp) before Cut1
+# -------------------------------------------------------------------------
+# CalcDisp: MRanForestCalc
+# CalcDisp.FileName: rf-disp.root
+# CalcDisp.NameOutput: Disp
+# CalcDisp.Debug: No
+# Cut1.CalcDisp: No
+
+# CalcDisp: MParameterCalc
+# CalcDisp.Rule: 1.15*(1-MHillas.fWidth/MHillas.fLength)
+# CalcDisp.NameOutput: Disp
+# Cut1.CalcDisp: No
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to estimate energy) after all Cuts
+# -------------------------------------------------------------------------
+# EstimateEnergy: MRanForestCalc
+# EstimateEnergy.NameOutput: MEnergyEst
+# EstimateEnergy.FileName: ranforest.root
+# EstimateEnergy.Debug: No
Index: branches/Mars_McMismatchStudy/ganymed_onoff.rc
===================================================================
--- branches/Mars_McMismatchStudy/ganymed_onoff.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/ganymed_onoff.rc	(revision 17960)
@@ -0,0 +1,211 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                               Cuts
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write output to somewhere here you can give
+# the output path
+# -------------------------------------------------------------------------
+#MJCuts.PathOut: .
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+BinningAlpha.Raw:        36    0    90
+BinningFalseSource.Raw:  91   -1.5  1.5
+BinningWidth.Raw:        50    0    1
+BinningLength.Raw:       25    0    1
+BinningDist.Raw:         25    0    2
+BinningAsym.Raw:         51   -0.7  0.7
+BinningM3Long.Raw:       51   -0.7  0.7
+BinningM3Trans.Raw:      51   -0.7  0.7
+BinningSlope.Raw:        51   -7.5  7.5
+
+# -------------------------------------------------------------------------
+# Using the starguider for pointing correction. 
+# To switch it off use "MPointingDevCalc.MaxAbsDev: -1"
+# For details see the class reference of MPointingDevCalc
+# -------------------------------------------------------------------------
+#MPointingDevCalc.MaxAbsDev:   15
+#MPointingDevCalc.NumMinStars: 8
+#MPointingDevCalc.NsbLevel:    3.0
+#MPointingDevCalc.NsbMin:      30
+#MPointingDevCalc.NsbMax:      60
+#MPointingDevCalc.Dx          -0.001
+#MPointingDevCalc.Dy          -0.004
+#MPointingDevCalc.MaxAge       1.0
+
+MPointingDevCalc.PointingModels: 1 81855 83722 89180 267253 291104 328198 1000534
+
+# -------------------------------------------------------------------------
+# Setup misfocussing correction (see class reference for MSrcPosCorrect)
+# -------------------------------------------------------------------------
+#MSrcPosCorrect.Dx: 0
+#MSrcPosCorrect.Dy: 0
+
+# -------------------------------------------------------------------------
+# Setup fit mode and ranges
+# -------------------------------------------------------------------------
+#MAlphaFitter.SignalIntegralMax:    15
+#MAlphaFitter.SignalFitMax:         25
+#MAlphaFitter.BackgroundFitMin:     35
+#MAlphaFitter.BackgroundFitMax:     75
+#MAlphaFitter.ScaleMin:             35
+#MAlphaFitter.ScaleMax:             80
+#MAlphaFitter.PolynomOrder:         2
+#MAlphaFitter.ScaleMode:            None
+
+# -------------------------------------------------------------------------
+# Define here which histogram class to use to determin the signal.
+# Currently availyble: MHAlpha, MHTheta <default>
+# -------------------------------------------------------------------------
+#MJCut.NameHist: MHAlpha
+
+# Be carefull: The spectrum might be done with a different binning
+# This might change the scale factor
+#MHThetaSq.NumBinsSignal:   3
+#MHThetaSq.NumBinsTotal:   75
+
+# -------------------------------------------------------------------------
+# To get a meaningfull false source plot in wobble mode use magic cuts
+# and the following two lines.
+# -------------------------------------------------------------------------
+MJCut.NameHistFS: MHDisp
+
+MHDisp.Smearing: 0.06
+#MHDisp.ScaleMin: 0.325
+#MHDisp.ScaleMax: 0.475
+
+# -------------------------------------------------------------------------
+# To get use a random source position in the off data with the distribution
+# in the camera of the on-data
+# -------------------------------------------------------------------------
+MJCut.RandomSourcePosition: Yes
+
+# -------------------------------------------------------------------------
+# There are three cuts:
+#   CutQ: Cut after reading file
+#   Cut0: After calculation of src dependent parameters, energy estimation
+#         and disp calculation, before writing summary file
+#   Cut1: After writing summary file before filling false source plots
+#   Cut2: After filling false source plots before filling alpha plots
+#   Cut3: After filling alpha plots (eg. Alpha cuts) for image parameter
+#         display, eg. write only events after alpha cut to ganymed file
+# -------------------------------------------------------------------------
+CutQ.Inverted: Yes
+Cut0.Inverted: Yes
+Cut1.Inverted: Yes
+Cut2.Inverted: Yes
+Cut3.Inverted: Yes
+
+# Quality-cuts (remove unphysical and obvious non-gamma events)
+CutQ.Condition: {0} && {1} && {2} && {3} && {4} && {5}
+CutQ.0: MImagePar.fNumIslands<3
+CutQ.1: MNewImagePar.fNumUsedPixels>5
+CutQ.2: MNewImagePar.fLeakage1 < 0.3
+CutQ.3: log10(MNewImagePar.fConcCOG)<-0.45+0.08*(log10(MHillas.fSize)<3.9)*(log10(MHillas.fSize)-3.9)^2
+CutQ.4: log10(MNewImagePar.fConc1)  <-0.75+0.10*(log10(MHillas.fSize)<3.8)*(log10(MHillas.fSize)-3.8)^2
+CutQ.5: MHillas.fLength>-3.6*(log10(MHillas.fSize)-6.0)^2+70
+
+# -------------------------------------------------------------------------
+# Such a cut could be used to exclude strange pointing positions. like
+# the camera center in wobble mode. Note, that a cut in the poiting
+# position directly influences the effective observation time and should
+# only be applied if the events are lost anyhow. In both cases you must
+# correct for the loss of observation time calculating your flux!
+# -------------------------------------------------------------------------
+#Cut0.Condition: MSrcPosCam.GetDist*MGeomCam.fConvMm2Deg>0.3
+
+# ---------- SETUP FOR ONOFF-MODE -----------
+MAlphaFitter.ScaleMin: 0.137
+MAlphaFitter.ScaleMax: 0.640
+MAlphaFitter.BackgroundFitMin: 0.137
+MAlphaFitter.BackgroundFitMax: 1.000
+MAlphaFitter.PolynomOrder: 1
+MAlphaFitter.ScaleMode: OffRegion
+MAlphaFitter.SignalFunction: ThetaSq
+
+# For more details on the magic cuts see its class reference
+Cut1.Condition: MFMagicCuts
+Cut1.ThetaCut: None
+# Parametrization of Disp
+Cut1.Param0:   1.15136
+Cut1.Param8:   0.0681437
+Cut1.Param9:   2.62932
+Cut1.Param10:  1.51279
+Cut1.Param11:  0.0507821
+# Parametrization for sign of disp (m3long, slope)
+Cut1.Param5:  -0.07
+Cut1.Param6:   7.2
+Cut1.Param7:   0.5
+# ThetaSq-Cut
+Cut1.Param1:   0.215
+# Area-Cut
+Cut1.Param2:   0.215468
+Cut1.Param3:   5.63973
+Cut1.Param4:   0.0836169
+
+# To switch on random forest uncomment the following lines
+#Cut1.HadronnessCut: Hadronness
+#Cut1.Param13: 0.5
+#Cut1.Param14: 100
+
+# To use both, hadronness and area cut do
+#Cut1.HadronnessCut: All
+
+# -------------------------------------------------------------------------
+# This cut is applied exclusively to the plots in the tab CutT. It is
+# resonable to show the events within your signal region here to
+# see if your signal region is clean from strange events (e.g. sparks)
+# -------------------------------------------------------------------------
+CutT.Condition: ThetaSquared.fVal < ThetaSquaredCut.fVal
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to calc hadronness) before Cut1
+# -------------------------------------------------------------------------
+# CalcHadronness: MRanForestCalc
+# CalcHadronness.FileName: rf-separation.root
+# CalcHadronness.NameOutput: Hadronness
+# CalcHadronness.Debug: No
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to calc disp) before Cut1
+# -------------------------------------------------------------------------
+# CalcDisp: MRanForestCalc
+# CalcDisp.FileName: rf-disp.root
+# CalcDisp.NameOutput: Disp
+# CalcDisp.Debug: No
+# Cut1.CalcDisp: No
+
+# CalcDisp: MParameterCalc
+# CalcDisp.Rule: 1.15*(1-MHillas.fWidth/MHillas.fLength)
+# CalcDisp.NameOutput: Disp
+# Cut1.CalcDisp: No
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to estimate energy) after all Cuts
+# -------------------------------------------------------------------------
+# EstimateEnergy: MRanForestCalc
+# EstimateEnergy.NameOutput: MEnergyEst
+# EstimateEnergy.FileName: ranforest.root
+# EstimateEnergy.Debug: No
Index: branches/Mars_McMismatchStudy/ganymed_wobble.rc
===================================================================
--- branches/Mars_McMismatchStudy/ganymed_wobble.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/ganymed_wobble.rc	(revision 17960)
@@ -0,0 +1,211 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                               Cuts
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write output to somewhere here you can give
+# the output path
+# -------------------------------------------------------------------------
+#MJCuts.PathOut: .
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+BinningAlpha.Raw:        36    0    90
+BinningFalseSource.Raw:  91   -1.5  1.5
+BinningWidth.Raw:        50    0    1
+BinningLength.Raw:       25    0    1
+BinningDist.Raw:         25    0    2
+BinningAsym.Raw:         51   -0.7  0.7
+BinningM3Long.Raw:       51   -0.7  0.7
+BinningM3Trans.Raw:      51   -0.7  0.7
+BinningSlope.Raw:        51   -7.5  7.5
+
+# -------------------------------------------------------------------------
+# Using the starguider for pointing correction. 
+# To switch it off use "MPointingDevCalc.MaxAbsDev: -1"
+# For details see the class reference of MPointingDevCalc
+# -------------------------------------------------------------------------
+#MPointingDevCalc.MaxAbsDev:   15
+#MPointingDevCalc.NumMinStars: 8
+#MPointingDevCalc.NsbLevel:    3.0
+#MPointingDevCalc.NsbMin:      30
+#MPointingDevCalc.NsbMax:      60
+#MPointingDevCalc.Dx          -0.001
+#MPointingDevCalc.Dy          -0.004
+#MPointingDevCalc.MaxAge       1.0
+
+MPointingDevCalc.PointingModels: 1 81855 83722 89180 267253 291104 328198 1000534
+
+# -------------------------------------------------------------------------
+# Setup misfocussing correction (see class reference for MSrcPosCorrect)
+# -------------------------------------------------------------------------
+#MSrcPosCorrect.Dx: 0
+#MSrcPosCorrect.Dy: 0
+
+# -------------------------------------------------------------------------
+# Setup fit mode and ranges
+# -------------------------------------------------------------------------
+#MAlphaFitter.SignalIntegralMax:    15
+#MAlphaFitter.SignalFitMax:         25
+#MAlphaFitter.BackgroundFitMin:     35
+#MAlphaFitter.BackgroundFitMax:     75
+#MAlphaFitter.ScaleMin:             35
+#MAlphaFitter.ScaleMax:             80
+#MAlphaFitter.PolynomOrder:         2
+#MAlphaFitter.ScaleMode:            None
+
+# -------------------------------------------------------------------------
+# Define here which histogram class to use to determin the signal.
+# Currently availyble: MHAlpha, MHTheta <default>
+# -------------------------------------------------------------------------
+#MJCut.NameHist: MHAlpha
+
+# -------------------------------------------------------------------------
+# Define here the number of off-source regions used in wobble mode
+# -------------------------------------------------------------------------
+#MJCut.NumOffSourcePositions: 3
+
+# -------------------------------------------------------------------------
+# To get a meaningfull false source plot in wobble mode use magic cuts
+# and the following two lines.
+# -------------------------------------------------------------------------
+MJCut.NameHistFS: MHDisp
+
+MHDisp.Wobble:   Yes
+MHDisp.Smearing: 0.06
+#MHDisp.ScaleMin: 0.325
+#MHDisp.ScaleMax: 0.475
+
+# -------------------------------------------------------------------------
+# Use this to set the number of bins corresponding to the signal region
+# and if you use a Anti-Theta cut the second one has to be enabled
+# -------------------------------------------------------------------------
+#MHPhi.NumBinsSignal: 2
+#MHPhi.UseAntiPhiCut: No
+
+# -------------------------------------------------------------------------
+# There are three cuts:
+#   CutQ: Cut after reading file
+#   Cut0: After calculation of src dependent parameters, energy estimation
+#         and disp calculation, before writing summary file
+#   Cut1: After writing summary file before filling false source plots
+#   Cut2: After filling false source plots before filling alpha plots
+#   Cut3: After filling alpha plots (eg. Alpha cuts) for image parameter
+#         display, eg. write only events after alpha cut to ganymed file
+# -------------------------------------------------------------------------
+CutQ.Inverted: Yes
+Cut0.Inverted: Yes
+Cut1.Inverted: Yes
+Cut2.Inverted: Yes
+Cut3.Inverted: Yes
+
+# Quality-cuts (remove unphysical and obvious non-gamma events)
+CutQ.Condition: {0} && {1} && {2} && {3} && {4} && {5}
+CutQ.0: MImagePar.fNumIslands<3
+CutQ.1: MNewImagePar.fNumUsedPixels>5
+CutQ.2: MNewImagePar.fLeakage1 < 0.3
+CutQ.3: log10(MNewImagePar.fConcCOG)<-0.45+0.08*(log10(MHillas.fSize)<3.9)*(log10(MHillas.fSize)-3.9)^2
+CutQ.4: log10(MNewImagePar.fConc1)  <-0.75+0.10*(log10(MHillas.fSize)<3.8)*(log10(MHillas.fSize)-3.8)^2
+CutQ.5: MHillas.fLength>-3.6*(log10(MHillas.fSize)-6.0)^2+70
+
+# -------------------------------------------------------------------------
+# Such a cut could be used to exclude strange pointing positions. like
+# the camera center in wobble mode. Note, that a cut in the poiting
+# position directly influences the effective observation time and should
+# only be applied if the events are lost anyhow. In both cases you must
+# correct for the loss of observation time calculating your flux!
+# -------------------------------------------------------------------------
+#Cut0.Condition: MSrcPosCam.GetDist*MGeomCam.fConvMm2Deg>0.3
+
+# ---------- SETUP FOR WOBBLE-MODE -----------
+#MAlphaFitter.ScaleMode: none
+MAlphaFitter.BackgroundFitMin: 0.09
+MAlphaFitter.BackgroundFitMax: 0.25
+MAlphaFitter.PolynomOrder: 1
+MAlphaFitter.SignalFunction: ThetaSq
+
+# For more details on the magic cuts see its class reference
+Cut1.Condition: MFMagicCuts
+Cut1.ThetaCut: None
+# Parametrization of Disp
+Cut1.Param0:   1.15136
+Cut1.Param8:   0.0681437
+Cut1.Param9:   2.62932
+Cut1.Param10:  1.51279
+Cut1.Param11:  0.0507821
+# Parametrization for sign of disp (m3long, slope)
+Cut1.Param5:  -0.07
+Cut1.Param6:   7.2
+Cut1.Param7:   0.5
+# ThetaSq-Cut
+Cut1.Param1:   0.215
+# Area-Cut
+Cut1.Param2:   0.215468
+Cut1.Param3:   5.63973
+Cut1.Param4:   0.0836169
+
+# To switch on random forest uncomment the following lines
+#Cut1.HadronnessCut: Hadronness
+#Cut1.Param13: 0.5
+#Cut1.Param14: 100
+
+# To use both, hadronness and area cut do
+#Cut1.HadronnessCut: All
+
+# -------------------------------------------------------------------------
+# This cut is applied exclusively to the plots in the tab CutT. It is
+# resonable to show the events within your signal region here to
+# see if your signal region is clean from strange events (e.g. sparks)
+# -------------------------------------------------------------------------
+CutT.Condition: ThetaSquared.fVal < ThetaSquaredCut.fVal
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to calc hadronness) before Cut1
+# -------------------------------------------------------------------------
+# CalcHadronness: MRanForestCalc
+# CalcHadronness.FileName: rf-separation.root
+# CalcHadronness.NameOutput: Hadronness
+# CalcHadronness.Debug: No
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to calc disp) before Cut1
+# -------------------------------------------------------------------------
+# CalcDisp: MRanForestCalc
+# CalcDisp.FileName: rf-disp.root
+# CalcDisp.NameOutput: Disp
+# CalcDisp.Debug: No
+# Cut1.CalcDisp: No
+
+# CalcDisp: MParameterCalc
+# CalcDisp.Rule: 1.15*(1-MHillas.fWidth/MHillas.fLength)
+# CalcDisp.NameOutput: Disp
+# Cut1.CalcDisp: No
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to estimate energy) after all Cuts
+# -------------------------------------------------------------------------
+# EstimateEnergy: MRanForestCalc
+# EstimateEnergy.NameOutput: MEnergyEst
+# EstimateEnergy.FileName: ranforest.root
+# EstimateEnergy.Debug: No
Index: branches/Mars_McMismatchStudy/lib/lib.txt
===================================================================
--- branches/Mars_McMismatchStudy/lib/lib.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/lib/lib.txt	(revision 17960)
@@ -0,0 +1,1 @@
+Directory for libraries while compiling
Index: branches/Mars_McMismatchStudy/macros/CCDataCheck.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/CCDataCheck.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/CCDataCheck.C	(revision 17960)
@@ -0,0 +1,1456 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Raquel de los Reyes, 02/2004 <mailto:reyes@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== *//////////////////////////////////////////////////////////////////////////////
+//
+// This macro made the check of the central control files (.rep files).
+// It displays 9 tabs:
+//   - Drive system
+//   - Camera status
+//   - HV of power supplies and HV settings
+//   - DC of power supplies 
+//   - LV power supplies
+//   - Cooling system
+//   - Trigger system
+//   - Trigger macrocells
+//   - Weather station
+//
+////////////////////////////////////////////////////////////////////////////
+
+void CCDataCheck(const TString filename="CC_2004_04_28.root", const TString directory="/home/raquel/")
+{
+
+  //
+  // If you want to run the macro in batch mode, set batchmode to kTRUE
+  //
+  Bool_t batchmode = kFALSE;
+
+  if(!batchmode)
+    {
+      MStatusDisplay *d = new MStatusDisplay;
+      d->SetTitle(filename);
+      d->SetLogStream(&gLog, kTRUE);            // Disables output to stdout
+    }
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Set all the MHVsTime classes:
+  // Drive system
+  MHVsTime hZd("MReportDrive.fNominalZd");
+  hZd.SetName("Zd");
+  MHVsTime hAz("MReportDrive.fNominalAz");
+  hAz.SetName("Az");
+  MHVsTime hDState("MReportDrive.fState");
+  hDState.SetName("State");
+  // HV power supplies
+  MHVsTime hHVA("MCameraHV.fVoltageA");
+  hHVA.SetName("HVA");
+  MHVsTime hHVB("MCameraHV.fVoltageB");
+  hHVB.SetName("HVB");
+  MHVsTime hCA("MCameraHV.fCurrentA");
+  hCA.SetName("CA");
+  MHVsTime hCB("MCameraHV.fCurrentB");
+  hCB.SetName("CB");
+  // LV power supplies
+  MHVsTime hLVTemp("MCameraLV.fTemp");
+  hLVTemp.SetName("LVTemp");
+  MHVsTime hLVHum("MCameraLV.fHumidity");
+  hLVHum.SetName("LVHum");
+  MHVsTime hLVStatus("MCameraHV.fStatus");
+  hLVStatus.SetName("LVStatus");
+  MHVsTime hLVRPS("MCameraLV.fRequestPowerSupply");
+  hLVRPS.SetName("LVRPS");
+  // Cooling system
+  MHVsTime hTCenter("MCameraCooling.fTempCenter");
+  hTCenter.SetName("TCenter");
+  MHVsTime hTWall("MCameraCooling.fTempWall");
+  hTWall.SetName("TWall");
+  MHVsTime hTWater("MCameraCooling.fTempWater");
+  hTWater.SetName("TWater");
+  MHVsTime hTOptLink("MCameraCooling.fTempOptLink");
+  hTOptLink.SetName("TOptLink");
+  MHVsTime hHWall("MCameraCooling.fHumWall");
+  hHWall.SetName("HWall");
+  MHVsTime hHCenter("MCameraCooling.fHumCenter");
+  hHCenter.SetName("HCenter");
+  // Weather station
+  MHVsTime hCCHum("MReportCC.fHumidity");
+  hCCHum.SetName("CCHum");
+  MHVsTime hCCTemp("MReportCC.fTemperature");
+  hCCTemp.SetName("CCTemp");
+  MHVsTime hCCWS("MReportCC.fWindSpeed");
+  hCCWS.SetName("CCWS");
+  MHVsTime hCCSR("MReportCC.fSolarRadiation");
+  hCCSR.SetName("CCSR");
+  // Trigger system
+  MHVsTime hTrigBL2("MReportTrigger.fL2BeforePrescaler");
+  hTrigBL2.SetName("TrigBL2");
+  MHVsTime hTrigAL2("MReportTrigger.fL2AfterPrescaler");
+  hTrigAL2.SetName("TrigAL2");
+  MHVsTime hTrigStatus("MReportTrigger.fState");
+  hTrigStatus.SetName("TrigStatus");
+  // Camera status
+  MHVsTime hCamStatus("MReportCamera.fState");
+  hCamStatus.SetName("CamStatus");
+  MHVsTime hCamSentStatus("MReportCamera.fStatus");
+  hCamSentStatus.SetName("CamSentStatus");
+  MHVsTime hCamStatusDC("MReportCamera.fStatusDC");
+  hCamStatusDC.SetName("CamDCStatus");
+  MHVsTime hHVStatus("MCameraHV.fStatus");
+  hHVStatus.SetName("HVStatus");
+  MHVsTime hLidsStatus("MCameraLids.fStatus");
+  hLidsStatus.SetName("LidsStatus");
+  MHVsTime hCoolStatus("MCameraCooling.fStatus");
+  hCoolStatus.SetName("CoolingStatus");
+  MHVsTime hCamMean("MCameraHV.fMean");
+  hCamMean.SetName("CameraMean");
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Drive");
+  read.AddTree("Camera");
+  read.AddTree("CC");
+  read.AddTree("Trigger");
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportDrive.*");
+  read.AddToBranchList("MCameraHV.*");
+  read.AddToBranchList("MCameraLV.*");
+  read.AddToBranchList("MCameraCooling.*");
+  read.AddToBranchList("MReportCC.*");
+  read.AddToBranchList("MReportTrigger.*");
+  read.AddToBranchList("MReportCamera.*");
+  read.AddToBranchList("MCameraLids.*");
+
+  MGeomApply geomapl;
+  tlist.AddToList(&geomapl);
+
+  // Set of MHCamEvents classes
+  MHCamEvent HVdisplay("CamHV","Camera mean HV settings");
+  HVdisplay.SetBit(MHCamera::kVariance);
+  plist.AddToList(&HVdisplay);
+
+  // Set of MHPixVsTime classes (Trigger macroscells)
+  MHPixVsTime htrigmc1(0,"TrigMacrocell1");
+  htrigmc1.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc1);
+  MHPixVsTime htrigmc2(1,"TrigMacrocell2");
+  htrigmc2.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc2);
+  MHPixVsTime htrigmc3(2,"TrigMacrocell3");
+  htrigmc3.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc3);
+  MHPixVsTime htrigmc4(3,"TrigMacrocell4");
+  htrigmc4.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc4);
+  MHPixVsTime htrigmc5(4,"TrigMacrocell5");
+  htrigmc5.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc5);
+  MHPixVsTime htrigmc6(5,"TrigMacrocell6");
+  htrigmc6.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc6);
+  MHPixVsTime htrigmc7(6,"TrigMacrocell7");
+  htrigmc7.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc7);
+  MHPixVsTime htrigmc8(7,"TrigMacrocell8");
+  htrigmc8.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc8);
+  MHPixVsTime htrigmc9(8,"TrigMacrocell9");
+  htrigmc9.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc9);
+  MHPixVsTime htrigmc10(9,"TrigMacrocell10");
+  htrigmc10.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc10);
+  MHPixVsTime htrigmc11(10,"TrigMacrocell11");
+  htrigmc11.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc11);
+  MHPixVsTime htrigmc12(11,"TrigMacrocell12");
+  htrigmc12.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc12);
+  MHPixVsTime htrigmc13(12,"TrigMacrocell13");
+  htrigmc13.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc13);
+  MHPixVsTime htrigmc14(13,"TrigMacrocell14");
+  htrigmc14.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc14);
+  MHPixVsTime htrigmc15(14,"TrigMacrocell15");
+  htrigmc15.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc15);
+  MHPixVsTime htrigmc16(15,"TrigMacrocell16");
+  htrigmc16.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc16);
+  MHPixVsTime htrigmc17(16,"TrigMacrocell17");
+  htrigmc17.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc17);
+  MHPixVsTime htrigmc18(17,"TrigMacrocell18");
+  htrigmc18.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc18);
+  MHPixVsTime htrigmc19(18,"TrigMacrocell19");
+  htrigmc19.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc19);
+
+  // Set of MH3 classes
+  MH3 hError("MReportDrive.GetAbsError*60");
+  hError.SetName("DeltaH");
+  MBinning bins("BinningDeltaH");
+  bins.SetEdges(18, 0, 3.6);
+  plist.AddToList(&bins);
+  MH3 hError2("MReportDrive.fNominalZd","MReportDrive.GetAbsError*60");
+  hError2.SetName("DeltaHvsZd");
+  MBinning bins2("BinningDeltaHvsZdX");
+  MBinning bins3("BinningDeltaHvsZdY");
+  bins2.SetEdges(90, 0, 90);
+  bins3.SetEdges(18, 0, 3.6);
+  plist.AddToList(&bins2);
+  plist.AddToList(&bins3);
+  MH3 hTempOptLink("MCameraCooling.fTempOptLink");
+  hTempOptLink.SetName("TOptLink");
+  MBinning bins4("BinningTOptLinkX");
+  bins4.SetEdges(50, 0, 50);
+  plist.AddToList(&bins4);
+  MH3 hTrigZd("MReportDrive.fNominalZd","MReportTrigger.fL2AfterPrescaler");
+  hTrigZd.SetName("TrigZd");
+  MBinning bins5("BinningTrigZdX");
+  bins5.SetEdges(90, 0, 90);
+  plist.AddToList(&bins5);
+  MBinning bins6("BinningTrigZdY");
+  bins6.SetEdges(10000, 0, 15000);
+  plist.AddToList(&bins6);
+
+
+  // Fill all the MH classes defined before
+  MFillH fillZd(&hZd,             "MTimeDrive");
+  MFillH fillAz(&hAz,             "MTimeDrive");
+  MFillH fillError(&hError);
+  MFillH fillDState(&hDState,     "MTimeDrive");
+  MFillH fillError2(&hError2);
+  MFillH fillHVA(&hHVA,           "MTimeCamera");
+  MFillH fillHVB(&hHVB,           "MTimeCamera");
+  MFillH fillCA(&hCA,             "MTimeCamera");
+  MFillH fillCB(&hCB,             "MTimeCamera");
+  MFillH fillLVTemp(&hLVTemp,     "MTimeCamera");
+  MFillH fillLVHum(&hLVHum,       "MTimeCamera");
+  MFillH fillLVStatus(&hLVStatus, "MTimeCamera");
+  MFillH fillLVRPS(&hLVRPS,       "MTimeCamera");
+  MFillH fillTCenter(&hTCenter,   "MTimeCamera");
+  MFillH fillTWall(&hTWall,       "MTimeCamera");
+  MFillH fillTWater(&hTWater,     "MTimeCamera");
+  MFillH fillTOptLink(&hTOptLink, "MTimeCamera");
+  MFillH fillTempOptLink(&hTempOptLink);
+  MFillH fillHWall(&hHWall,       "MTimeCamera");
+  MFillH fillHCenter(&hHCenter,   "MTimeCamera");
+  MFillH fillCCHum(&hCCHum,       "MTimeCC");
+  MFillH fillCCTemp(&hCCTemp,     "MTimeCC");
+  MFillH fillCCWS(&hCCWS,         "MTimeCC");
+  MFillH fillCCSR(&hCCSR,         "MTimeCC");
+  MFillH fillTrigBL2(&hTrigBL2,   "MTimeTrigger");
+  MFillH fillTrigAL2(&hTrigAL2,   "MTimeTrigger");
+  MFillH fillTrigStatus(&hTrigStatus,   "MTimeTrigger");
+  MFillH fillTrigZd(&hTrigZd);
+  MFillH fillCamStatus(&hCamStatus,"MTimeCamera");
+  MFillH fillCamSentStatus(&hCamSentStatus,"MTimeCamera");
+  MFillH fillCamStatusDC(&hCamStatusDC, "MTimeCamera");
+  MFillH fillHVStatus(&hHVStatus, "MTimeCamera");
+  MFillH fillLidsStatus(&hLidsStatus, "MTimeCamera");
+  MFillH fillCoolStatus(&hCoolStatus, "MTimeCamera");
+  MFillH filltrigmc1("TrigMacrocell1","MReportTrigger");
+  MFillH filltrigmc2("TrigMacrocell2","MReportTrigger");
+  MFillH filltrigmc3("TrigMacrocell3","MReportTrigger");
+  MFillH filltrigmc4("TrigMacrocell4","MReportTrigger");
+  MFillH filltrigmc5("TrigMacrocell5","MReportTrigger");
+  MFillH filltrigmc6("TrigMacrocell6","MReportTrigger");
+  MFillH filltrigmc7("TrigMacrocell7","MReportTrigger");
+  MFillH filltrigmc8("TrigMacrocell8","MReportTrigger");
+  MFillH filltrigmc9("TrigMacrocell9","MReportTrigger");
+  MFillH filltrigmc10("TrigMacrocell10","MReportTrigger");
+  MFillH filltrigmc11("TrigMacrocell11","MReportTrigger");
+  MFillH filltrigmc12("TrigMacrocell12","MReportTrigger");
+  MFillH filltrigmc13("TrigMacrocell13","MReportTrigger");
+  MFillH filltrigmc14("TrigMacrocell14","MReportTrigger");
+  MFillH filltrigmc15("TrigMacrocell15","MReportTrigger");
+  MFillH filltrigmc16("TrigMacrocell16","MReportTrigger");
+  MFillH filltrigmc17("TrigMacrocell17","MReportTrigger");
+  MFillH filltrigmc18("TrigMacrocell18","MReportTrigger");
+  MFillH filltrigmc19("TrigMacrocell19","MReportTrigger");
+  MFillH fillcammean(&hCamMean,"MTimeCamera");
+  MFillH fillHVD(&HVdisplay,"MCameraHV");
+
+  // Do not display the result given by the default draw function
+  fillZd.SetBit(MFillH::kDoNotDisplay);
+  fillAz.SetBit(MFillH::kDoNotDisplay);
+  fillError.SetBit(MFillH::kDoNotDisplay);
+  fillDState.SetBit(MFillH::kDoNotDisplay);
+  fillError2.SetBit(MFillH::kDoNotDisplay);
+  fillHVA.SetBit(MFillH::kDoNotDisplay);
+  fillHVB.SetBit(MFillH::kDoNotDisplay);
+  fillCA.SetBit(MFillH::kDoNotDisplay);
+  fillCB.SetBit(MFillH::kDoNotDisplay);
+  fillLVTemp.SetBit(MFillH::kDoNotDisplay);
+  fillLVHum.SetBit(MFillH::kDoNotDisplay);
+  fillLVStatus.SetBit(MFillH::kDoNotDisplay);
+  fillLVRPS.SetBit(MFillH::kDoNotDisplay);
+  fillTCenter.SetBit(MFillH::kDoNotDisplay);
+  fillTWall.SetBit(MFillH::kDoNotDisplay);
+  fillTWater.SetBit(MFillH::kDoNotDisplay);
+  fillTOptLink.SetBit(MFillH::kDoNotDisplay);
+  fillTempOptLink.SetBit(MFillH::kDoNotDisplay);
+  fillHWall.SetBit(MFillH::kDoNotDisplay);
+  fillHCenter.SetBit(MFillH::kDoNotDisplay);
+  fillCCHum.SetBit(MFillH::kDoNotDisplay);
+  fillCCTemp.SetBit(MFillH::kDoNotDisplay);
+  fillCCWS.SetBit(MFillH::kDoNotDisplay);
+  fillCCSR.SetBit(MFillH::kDoNotDisplay);
+  fillTrigBL2.SetBit(MFillH::kDoNotDisplay);
+  fillTrigAL2.SetBit(MFillH::kDoNotDisplay);
+  fillTrigStatus.SetBit(MFillH::kDoNotDisplay);
+  fillTrigZd.SetBit(MFillH::kDoNotDisplay);
+  fillCamStatus.SetBit(MFillH::kDoNotDisplay);
+  fillCamSentStatus.SetBit(MFillH::kDoNotDisplay);
+  fillCamStatusDC.SetBit(MFillH::kDoNotDisplay);
+  fillHVStatus.SetBit(MFillH::kDoNotDisplay);
+  fillLidsStatus.SetBit(MFillH::kDoNotDisplay);
+  fillCoolStatus.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc1.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc2.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc3.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc4.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc5.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc6.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc7.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc8.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc9.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc10.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc11.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc12.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc13.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc14.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc15.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc16.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc17.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc18.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc19.SetBit(MFillH::kDoNotDisplay);
+  fillcammean.SetBit(MFillH::kDoNotDisplay);
+  fillHVD.SetBit(MFillH::kDoNotDisplay);
+
+  // Skip the fill function is there is no tree entries
+  fillZd.SetBit(MFillH::kCanSkip);
+  fillAz.SetBit(MFillH::kCanSkip);
+  fillError.SetBit(MFillH::kCanSkip);
+  fillDState.SetBit(MFillH::kCanSkip);
+  fillError2.SetBit(MFillH::kCanSkip);
+  fillHVA.SetBit(MFillH::kCanSkip);
+  fillHVB.SetBit(MFillH::kCanSkip);
+  fillCA.SetBit(MFillH::kCanSkip);
+  fillCB.SetBit(MFillH::kCanSkip);
+  fillLVTemp.SetBit(MFillH::kCanSkip);
+  fillLVHum.SetBit(MFillH::kCanSkip);
+  fillLVStatus.SetBit(MFillH::kCanSkip);
+  fillLVRPS.SetBit(MFillH::kCanSkip);
+  fillTCenter.SetBit(MFillH::kCanSkip);
+  fillTWall.SetBit(MFillH::kCanSkip);
+  fillTWater.SetBit(MFillH::kCanSkip);
+  fillTOptLink.SetBit(MFillH::kCanSkip);
+  fillTempOptLink.SetBit(MFillH::kCanSkip);
+  fillHWall.SetBit(MFillH::kCanSkip);
+  fillHCenter.SetBit(MFillH::kCanSkip);
+  fillCCHum.SetBit(MFillH::kCanSkip);
+  fillCCTemp.SetBit(MFillH::kCanSkip);
+  fillCCWS.SetBit(MFillH::kCanSkip);
+  fillCCSR.SetBit(MFillH::kCanSkip);
+  fillTrigBL2.SetBit(MFillH::kCanSkip);
+  fillTrigAL2.SetBit(MFillH::kCanSkip);
+  fillTrigStatus.SetBit(MFillH::kCanSkip);
+  fillTrigZd.SetBit(MFillH::kCanSkip);
+  fillCamStatus.SetBit(MFillH::kCanSkip);
+  fillCamSentStatus.SetBit(MFillH::kCanSkip);
+  fillCamStatusDC.SetBit(MFillH::kCanSkip);
+  fillHVStatus.SetBit(MFillH::kCanSkip);
+  fillLidsStatus.SetBit(MFillH::kCanSkip);
+  fillCoolStatus.SetBit(MFillH::kCanSkip);
+  filltrigmc1.SetBit(MFillH::kCanSkip);
+  filltrigmc2.SetBit(MFillH::kCanSkip);
+  filltrigmc3.SetBit(MFillH::kCanSkip);
+  filltrigmc4.SetBit(MFillH::kCanSkip);
+  filltrigmc5.SetBit(MFillH::kCanSkip);
+  filltrigmc6.SetBit(MFillH::kCanSkip);
+  filltrigmc7.SetBit(MFillH::kCanSkip);
+  filltrigmc8.SetBit(MFillH::kCanSkip);
+  filltrigmc9.SetBit(MFillH::kCanSkip);
+  filltrigmc10.SetBit(MFillH::kCanSkip);
+  filltrigmc11.SetBit(MFillH::kCanSkip);
+  filltrigmc12.SetBit(MFillH::kCanSkip);
+  filltrigmc13.SetBit(MFillH::kCanSkip);
+  filltrigmc14.SetBit(MFillH::kCanSkip);
+  filltrigmc15.SetBit(MFillH::kCanSkip);
+  filltrigmc16.SetBit(MFillH::kCanSkip);
+  filltrigmc17.SetBit(MFillH::kCanSkip);
+  filltrigmc18.SetBit(MFillH::kCanSkip);
+  filltrigmc19.SetBit(MFillH::kCanSkip);
+  fillcammean.SetBit(MFillH::kCanSkip);
+  fillHVD.SetBit(MFillH::kCanSkip);
+
+  // Add all the task to the task list
+  tlist.AddToList(&read);
+  tlist.AddToList(&fillZd,       "Drive");
+  tlist.AddToList(&fillAz,       "Drive");
+  tlist.AddToList(&fillError,    "Drive");
+  tlist.AddToList(&fillDState,   "Drive");
+  tlist.AddToList(&fillError2,   "Drive");
+  tlist.AddToList(&fillHVA,      "Camera");
+  tlist.AddToList(&fillHVB,      "Camera");
+  tlist.AddToList(&fillCA,       "Camera");
+  tlist.AddToList(&fillCB,       "Camera");
+  tlist.AddToList(&fillLVTemp,   "Camera");
+  tlist.AddToList(&fillLVHum,    "Camera");
+  tlist.AddToList(&fillLVStatus, "Camera");
+  tlist.AddToList(&fillLVRPS,    "Camera");
+  tlist.AddToList(&fillTCenter,  "Camera");
+  tlist.AddToList(&fillTWall,    "Camera");
+  tlist.AddToList(&fillTWater,   "Camera");
+  tlist.AddToList(&fillTOptLink, "Camera");
+  tlist.AddToList(&fillTempOptLink, "Camera");
+  tlist.AddToList(&fillHWall,    "Camera");
+  tlist.AddToList(&fillHCenter,  "Camera");
+  tlist.AddToList(&fillCCHum,    "CC");
+  tlist.AddToList(&fillCCTemp,   "CC");
+  tlist.AddToList(&fillCCWS,     "CC");
+  tlist.AddToList(&fillCCSR,     "CC");
+  tlist.AddToList(&fillTrigBL2,  "Trigger");
+  tlist.AddToList(&fillTrigAL2,  "Trigger");
+  tlist.AddToList(&fillTrigStatus,  "Trigger");
+  tlist.AddToList(&fillTrigZd);
+  tlist.AddToList(&fillCamStatus,  "Camera");
+  tlist.AddToList(&fillCamSentStatus,  "Camera");
+  tlist.AddToList(&fillCamStatusDC,"Camera");
+  tlist.AddToList(&fillHVStatus,"Camera");
+  tlist.AddToList(&fillLidsStatus,"Camera");
+  tlist.AddToList(&fillCoolStatus,"Camera");
+  tlist.AddToList(&filltrigmc1, "Trigger");
+  tlist.AddToList(&filltrigmc2, "Trigger");
+  tlist.AddToList(&filltrigmc3, "Trigger");
+  tlist.AddToList(&filltrigmc4, "Trigger");
+  tlist.AddToList(&filltrigmc5, "Trigger");
+  tlist.AddToList(&filltrigmc6, "Trigger");
+  tlist.AddToList(&filltrigmc7, "Trigger");
+  tlist.AddToList(&filltrigmc8, "Trigger");
+  tlist.AddToList(&filltrigmc9, "Trigger");
+  tlist.AddToList(&filltrigmc10, "Trigger");
+  tlist.AddToList(&filltrigmc11, "Trigger");
+  tlist.AddToList(&filltrigmc12, "Trigger");
+  tlist.AddToList(&filltrigmc13, "Trigger");
+  tlist.AddToList(&filltrigmc14, "Trigger");
+  tlist.AddToList(&filltrigmc15, "Trigger");
+  tlist.AddToList(&filltrigmc16, "Trigger");
+  tlist.AddToList(&filltrigmc17, "Trigger");
+  tlist.AddToList(&filltrigmc18, "Trigger");
+  tlist.AddToList(&filltrigmc19, "Trigger");
+  tlist.AddToList(&fillcammean, "Camera");
+  tlist.AddToList(&fillHVD);
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  if(!batchmode)
+    evtloop.SetDisplay(d);
+    
+  //
+  // Execute your analysis
+  //
+  if (!evtloop.Eventloop())
+    return;
+ 
+  tlist.PrintStatistics();
+
+  gStyle->SetPadGridX(kTRUE);
+  gStyle->SetPadGridY(kTRUE);
+  gStyle->SetCanvasColor(kWhite);
+  MHVsTime *clone1;
+  TGraph *g;
+  TH1 *hist;
+  TH1 *hist2;
+  TAxis *axey;
+  TAxis *axex;
+  MH3 *mh3;
+  MHPixVsTime *pixclone1;
+  MHCamera *Sum;
+  //
+  // Drive report (pointing.C from T. Bretz)
+  //
+  TCanvas *c1;
+  if ((d = evtloop.GetDisplay()))
+      c1 = &d->AddTab("DRIVE SYSTEM");
+  else
+      c1 = new TCanvas();
+
+  // ************* Plot the telescope tracking positions on the sky ***********
+  TGraph *g1 = hZd.GetGraph();
+  TGraph *g2 = hAz.GetGraph();
+  TPad *p = new TPad("", "",0,0.05,0.6,0.95);
+  p->Draw();
+  p->cd();
+  gPad->SetTheta(-90);
+  gPad->SetPhi(90);
+  gPad->SetBorderMode(0);
+  gStyle->SetOptStat(0);
+  TH2F h("pol", "Telescope Tracking Positions on the Sky", 16, 0, 1, 9, 0, 1);
+  h.DrawClone("surf1pol");
+  gPad->Modified();
+  gPad->Update();
+  TView *view = gPad->GetView();
+  if (!view)
+    {
+      cout << "No View!" << endl;
+      return;
+    }
+  Double_t *zd=g1->GetY();
+  Double_t *az=g2->GetY();
+  Double_t old[2] = {0,0};
+  for (int i=0; i<g1->GetN(); i++)
+    {
+      az[i] += 180;
+      az[i] *= TMath::Pi()/180;
+      Double_t x[3] = { zd[i]*cos(az[i])/90, zd[i]*sin(az[i])/90, 0};
+      Double_t y[3];
+      view->WCtoNDC(x, y);
+      if (old[0]!=0 && old[1]!=1)
+        {
+	  TLine *l = new TLine(y[0], y[1], old[0], old[1]);
+	  l->SetLineColor(kBlue);
+	  l->Draw();
+        }
+      TMarker *m = new TMarker(y[0], y[1], kFullDotMedium);
+      m->SetMarkerColor(i==g1->GetN()-1 ? kGreen : kRed);
+      m->Draw();
+      old[0] = y[0];
+      old[1] = y[1];
+    }
+  // ---------------------- Control deviation of the motors -------------------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0, 1, 0.29);
+  p->Draw();
+  p->cd();
+  gStyle->SetOptStat(1110);
+  gStyle->SetStatFormat(".2g");
+  mh3 = (MH3*)hError.DrawClone("nonew");
+  mh3->GetHist().SetXTitle("\\Delta [arcmin]");
+  mh3->GetHist().SetYTitle("");
+  mh3->GetHist().SetTitle("Control deviation of the motors");
+  mh3->GetHist().SetStats(1);
+  mh3->GetHist().SetLabelSize(0.06,"X");
+  mh3->GetHist().SetLabelSize(0.06,"Y");
+  mh3->GetHist().SetTitleSize(0.06,"X");
+  TLine ln;
+  ln.SetLineColor(kGreen);
+  ln.DrawLine(0.5*360*60/16384., 0, 0.5*360*60/16384., hError.GetHist().GetMaximum());
+  ln.SetLineColor(kYellow);
+  ln.DrawLine(1.0*360*60/16384., 0, 1.0*360*60/16384., hError.GetHist().GetMaximum());
+  ln.SetLineColor(kRed);
+  ln.DrawLine(2.0*360*60/16384., 0, 2.0*360*60/16384., hError.GetHist().GetMaximum());
+  // ---------------------- Plot the drive status vs time ---------------------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0.29, 1, 0.42);
+  p->Draw();
+  p->cd();
+  MHVsTime *hvt = (MHVsTime*)hDState.DrawClone("nonew");
+  hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+  if (hvt->GetGraph()->GetN())
+    {
+      hist = hvt->GetGraph()->GetHistogram();
+      TAxis *axey = hist->GetYaxis();
+      TAxis *axex = hist->GetXaxis();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+      hist->SetTitle("");
+      hist->SetLabelSize(0.1,"X");
+      hist->SetTitleSize(0.06,"X");
+      hist->SetStats(0);
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(4.5);
+      axey->Set(5, -0.5, 4.5);
+      axey->SetBinLabel(axey->FindFixBin(0), "Error");
+      axey->SetBinLabel(axey->FindFixBin(1), "Stopped");
+      axey->SetBinLabel(axey->FindFixBin(3), "Moving");
+      axey->SetBinLabel(axey->FindFixBin(4), "Tracking");
+      axey->SetLabelSize(0.15);
+      axex->SetLabelSize(0.08);
+      axex->SetTitleSize(0.09);
+      axex->SetTitleOffset(0.45);
+    }  
+  // --------------- Control deviation of the motors vs zenith angle ----------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0.71, 1, 1);
+  p->Draw();
+  p->cd();
+  gStyle->SetOptStat(1110);
+  gStyle->SetStatFormat(".2g");
+  mh3 = (MH3*)hError2.DrawClone("nonew");
+  mh3->GetHist().SetXTitle("Zd [\\circ]");
+  mh3->GetHist().SetYTitle("\\Delta [arcmin]");
+  mh3->GetHist().SetTitle("Control deviation of the motors");
+  mh3->GetHist().SetLabelSize(0.06,"X");
+  mh3->GetHist().SetLabelSize(0.06,"Y");
+  mh3->GetHist().SetTitleSize(0.06,"X");
+  mh3->GetHist().SetTitleSize(0.06,"Y");
+  mh3->GetHist().SetStats(1);
+  mh3->GetHist().Draw("box");
+  // -------------------------- Zenith angle vs time --------------------------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0.42, 1, 0.71);
+  p->Draw();
+  p->cd();
+  gPad->SetBorderMode(0);
+  hvt = (MHVsTime*)hZd.DrawClone("nonew");
+  hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+  if (hvt->GetGraph()->GetN())
+    {
+      hvt->GetGraph()->GetHistogram()->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hvt->GetGraph()->GetHistogram()->SetXTitle("Time");
+      hvt->GetGraph()->GetHistogram()->SetYTitle("Zd [\\circ]");
+      hvt->GetGraph()->GetHistogram()->SetTitle("Zd vs. Time");
+      hvt->GetGraph()->GetHistogram()->SetLabelSize(0.06,"X");
+      hvt->GetGraph()->GetHistogram()->SetTitleSize(0.06,"X");
+      hvt->GetGraph()->GetHistogram()->SetLabelSize(0.06,"Y");
+      hvt->GetGraph()->GetHistogram()->SetTitleSize(0.06,"Y");
+      hvt->GetGraph()->GetHistogram()->SetStats(0);
+    }
+  
+  
+  //
+  // Camera report 
+  // 
+  // **************************** CAMERA STATUS ********************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c2 = d.AddTab("CAMERA STATUS");
+  else
+    TCanvas *c2 = new TCanvas();
+  c2->Divide(1,2);
+  c2->cd(1);
+  g = hCamStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera status");
+  clone1 = (MHVsTime*)hCamStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"EROR");
+      axey->SetBinLabel(axey->FindFixBin(1),"ALARM");
+      axey->SetBinLabel(axey->FindFixBin(2),"BLOCKED!");
+      axey->SetBinLabel(axey->FindFixBin(3),"WARM!");
+      axey->SetBinLabel(axey->FindFixBin(4),"HOT");
+      axey->SetBinLabel(axey->FindFixBin(5),"HVRAMPING");
+      axey->SetBinLabel(axey->FindFixBin(6),"OK");
+      axey->SetBinLabel(axey->FindFixBin(7),"INIT");
+      axey->SetBinLabel(axey->FindFixBin(8),"SHUTD");
+      axey->SetBinLabel(axey->FindFixBin(9),"N/A");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  c2->cd(2);
+  g = hLidsStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera Lids status");
+  clone1 = (MHVsTime*)hLidsStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"SafetyLimit");
+      axey->SetBinLabel(axey->FindFixBin(4),"Closed");
+      axey->SetBinLabel(axey->FindFixBin(5),"Opened");
+      axey->SetBinLabel(axey->FindFixBin(6),"Moving");
+      axey->SetBinLabel(axey->FindFixBin(7),"Stopped");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.06,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  // ************************* HV of power supplies ***************************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c3 = d.AddTab("CAMERA HV");
+  else
+    TCanvas *c3 = new TCanvas();
+  c3->Divide(2,2);
+  c3->cd(1);
+  // --------------- Power supplies  and HV settings --------------------------
+  TLegend *legHV = new TLegend(0.75,0.85,0.99,0.99);
+  g = hHVA.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Voltages of power supplies and camera settings");
+  legHV->AddEntry(g,"PS A (hvps1)","l");
+  clone1 = (MHVsTime*)hHVA.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("High voltage [V]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMinimum(0);
+    }
+  g = hHVB.GetGraph();
+  g->SetMarkerColor(3);
+  g->SetLineColor(3);
+  legHV->AddEntry(g,"PS B (hvps2)","l");
+  clone1 = (MHVsTime*)hHVB.DrawClone("nonewsame");
+  g = hCamMean.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  legHV->AddEntry(g,"Camera mean HV","l");
+  clone1 = (MHVsTime*)hCamMean.DrawClone("nonewsame");
+  legHV->DrawClone();
+ // ---------------------------- HV status -----------------------------------
+  c3->cd(2);
+  g = hHVStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera HV status");
+  clone1 = (MHVsTime*)hHVStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Mismatch");
+      axey->SetBinLabel(axey->FindFixBin(2),"Trip");
+      axey->SetBinLabel(axey->FindFixBin(3),"Ramping");
+      axey->SetBinLabel(axey->FindFixBin(4),"Off");
+      axey->SetBinLabel(axey->FindFixBin(5),"Nominal");
+      axey->SetBinLabel(axey->FindFixBin(6),"LimCurrentWarning");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  // ---------------------------- HV settings ---------------------------------
+  c3->cd(3);
+  Sum = (MHCamera*)HVdisplay.GetHistByName("sum");
+  TVirtualPad *c = gPad;
+  c->cd(1);
+  gPad->SetBorderMode(0);
+  Sum->SetYTitle("Mean");
+  Sum->DrawClone("pixelindex"); 
+  c3->cd(4);
+  gPad->SetBorderMode(0);
+  Sum->SetYTitle("Mean HV settings");
+  Sum->DrawClone("EPhist");
+
+  // ******************** Currents of power supplies *******************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c4 = d.AddTab("CAMERA DC");
+  else
+    TCanvas *c4 = new TCanvas();
+ // ----------------------------- Power supplies ------------------------------
+  c4->Divide(1,2);
+  c4->cd(1);
+  TLegend *legC = new TLegend(0.85,0.75,0.99,0.99);
+  g = hCA.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Currents of power supplies");
+  legC->AddEntry(g,"PS A (curr1)","l");
+  clone1 = (MHVsTime*)hCA.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Current [mA]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMinimum(0);
+    }
+  g = hCB.GetGraph();
+  g->SetMarkerColor(3);
+  g->SetLineColor(3);
+  legC->AddEntry(g,"PS B (curr2)","l");
+  clone1 = (MHVsTime*)hCB.DrawClone("nonewsame");
+  legC->DrawClone();
+  c4->cd(2);
+  g = hCamStatusDC.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera DC status");
+  clone1 = (MHVsTime*)hCamStatusDC.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Alarm");
+      axey->SetBinLabel(axey->FindFixBin(3),"Hot");
+      axey->SetBinLabel(axey->FindFixBin(5),"Ok");
+      axey->SetBinLabel(axey->FindFixBin(6),"Warm");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.09,"Y");
+      hist->SetLabelSize(0.04,"X");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+
+
+  // ***************************** LV power supplies **************************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c5 = d.AddTab("CAMERA LV");
+  else
+    TCanvas *c5 = new TCanvas();
+  c5->Divide(2,2);
+  c5->cd(1);
+  g = hLVTemp.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("LV temperature");
+  clone1 = (MHVsTime*)hLVTemp.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Temperature [\\circ]");
+      hist->SetLabelSize(0.04,"X");
+    }
+  c5->cd(2);
+  g = hLVHum.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  g->SetTitle("LV humidity");
+  clone1 = (MHVsTime*)hLVHum.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Humidity [%]");
+      hist->SetLabelSize(0.04,"X");
+    }
+  c5->cd(3);
+  g = hLVStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("LV status");
+  clone1 = (MHVsTime*)hLVStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Alarm");
+      axey->SetBinLabel(axey->FindFixBin(2),"Trip");
+      axey->SetBinLabel(axey->FindFixBin(4),"Off");
+      axey->SetBinLabel(axey->FindFixBin(5),"On");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  c5->cd(4);
+  g = hLVRPS.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("LV request power supply");
+  clone1 = (MHVsTime*)hLVRPS.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+      hist->SetLabelSize(0.04,"X");
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(1.5);
+      axey->Set(2, -0.5, 1.5);
+      axey->SetBinLabel(axey->FindFixBin(0), "OFF");
+      axey->SetBinLabel(axey->FindFixBin(1), "ON");
+    }
+  // ****************************** Cooling ***********************************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c6 = d.AddTab("COOLING SYSTEM");
+  else
+    TCanvas *c6 = new TCanvas();
+  gStyle->SetPadGridX(kTRUE);
+  gStyle->SetPadGridY(kTRUE);
+  c6->Divide(2,2);
+  c6->cd(1);
+  // -------------------------- Camera temperatures ---------------------------
+  TLegend *legtemp = new TLegend(0.75,0.80,0.99,0.99);
+  g = hTCenter.GetGraph();
+  g->SetMarkerColor(8);
+  g->SetLineColor(8);
+  g->SetTitle("Camera temperature");
+  legtemp->AddEntry(g,"camera center","l");
+  clone1 = (MHVsTime*)hTCenter.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Temperature [\\circ C]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMinimum(0);
+    }
+  g = hTWall.GetGraph();
+  g->SetMarkerColor(12);
+  g->SetLineColor(12);
+  legtemp->AddEntry(g,"camera wall","l");
+  clone1 = (MHVsTime*)hTWall.DrawClone("nonewsame");
+  g = hTWater.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  legtemp->AddEntry(g,"water deposit","l");
+  clone1 = (MHVsTime*)hTWater.DrawClone("nonewsame");
+  g = hTOptLink.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  legtemp->AddEntry(g,"optical links","l");
+  clone1 = (MHVsTime*)hTOptLink.DrawClone("nonewsame");
+  legtemp->DrawClone();
+  c6->cd(2);
+  g = hCoolStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera cooling status");
+  clone1 = (MHVsTime*)hCoolStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Alarm");
+      axey->SetBinLabel(axey->FindFixBin(4),"Off");
+      axey->SetBinLabel(axey->FindFixBin(5),"Ok");
+      axey->SetBinLabel(axey->FindFixBin(6),"Temp.Warning");
+      axey->SetBinLabel(axey->FindFixBin(7),"Cond.Warning");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  // ------------------------- Camera relative humidity -----------------------
+  c6->cd(3);
+  TLegend *leghum = new TLegend(0.75,0.85,0.99,0.99);
+  g = hHCenter.GetGraph();
+  g->SetMarkerColor(8);
+  g->SetLineColor(8);
+  g->SetTitle("Camera relative humidity");
+  leghum->AddEntry(g,"camera center","l");
+  clone1 = (MHVsTime*)hHCenter.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Relative humidity [%]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMaximum(50);
+      hist->SetMinimum(0);
+    }
+  g = hHWall.GetGraph();
+  g->SetMarkerColor(12);
+  g->SetLineColor(12);
+  leghum->AddEntry(g,"camera wall","l");
+  clone1 = (MHVsTime*)hHWall.DrawClone("nonewsame");
+  leghum->DrawClone();
+  // ---------------------- Temperature distribution --------------------------
+  c6->cd(4);
+  hist = hTempOptLink.GetHistByName("TOptLink");
+  hist->SetXTitle("Temperature [\\circ C]");
+  hist->SetYTitle("");
+  hist->SetLineColor(2);
+  hist->SetTitle("Distribution of opt. links temperature");
+  hist->SetLabelSize(0.04,"X");
+  hist->SetStats(0);
+  mh3 = (MH3*)hTempOptLink.DrawClone("nonew");
+  //
+  // **************************** Trigger report ******************************
+  //
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c7 = d.AddTab("TRIGGER SYSTEM");
+  else
+    TCanvas *c7 = new TCanvas();
+  c7->Divide(1,3);
+  c7->cd(1);
+  gStyle->SetPadGridX(kTRUE);
+  gStyle->SetPadGridY(kTRUE);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.85,0.85,0.99,0.99);
+  g = hTrigBL2.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("L2 trigger rate");
+  legtrig->AddEntry(g,"Before prescaler","l");
+  clone1 = (MHVsTime*)hTrigBL2.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetLabelSize(0.06,"X");
+      hist->SetLabelSize(0.06,"Y");
+      hist->SetTitleSize(0.06,"X");
+      hist->SetTitleSize(0.06,"Y");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("L2 trigger rate [Hz]"); 
+    }
+  g = hTrigAL2.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  legtrig->AddEntry(g,"After prescaler","l");
+  clone1 = (MHVsTime*)hTrigAL2.DrawClone("nonewsame");
+  legtrig->DrawClone();
+   c7->cd(2);
+   gPad->SetLogy();
+   hist = hTrigZd.GetHistByName("TrigZd");
+   hist->SetLabelSize(0.06,"X");
+   hist->SetLabelSize(0.06,"Y");
+   hist->SetTitleSize(0.06,"X");
+   hist->SetTitleSize(0.06,"Y");
+   hist->SetXTitle("Zenith angle[\\circ]");
+   hist->SetYTitle("Trigger rate [Hz]");
+   hist->SetMarkerColor(4);
+   hist->SetTitle("L2 trigger rate after prescaler");
+   hist->SetStats(0);
+   mh3 = (MH3*)hTrigZd.DrawClone("nonew");
+   hist->SetMinimum(1);
+   c7->cd(3);
+   g = hTrigStatus.GetGraph();
+   g->SetMarkerStyle(kFullDotSmall);
+   g->SetTitle("Trigger status");
+   clone1 = (MHVsTime*)hTrigStatus.DrawClone("nonew");
+   if(clone1->GetGraph()->GetN())
+     {
+       hist = clone1->GetGraph()->GetHistogram();
+       axey = hist->GetYaxis();
+       hist->SetMinimum(-0.5);
+       hist->SetMaximum(5.5);
+       axey->Set(6,-0.5,5.5);
+       axey->SetBinLabel(axey->FindFixBin(0),"Error");
+       axey->SetBinLabel(axey->FindFixBin(1),"Idle");
+       axey->SetBinLabel(axey->FindFixBin(2),"Loading");
+       axey->SetBinLabel(axey->FindFixBin(3),"Ready");
+       axey->SetBinLabel(axey->FindFixBin(4),"Active");
+       axey->SetBinLabel(axey->FindFixBin(5),"Stopped");
+       hist->SetLabelSize(0.07,"Y");
+       hist->SetLabelSize(0.06,"X");
+       hist->SetTitleSize(0.06,"X");
+       hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+       hist->SetXTitle("Time");
+       hist->SetYTitle("");
+     }
+  // ***************************** Trigger of macrocells **********************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c8 = d.AddTab("TRIG. MACROCELLs");
+  else
+    TCanvas *c8 = new TCanvas();
+  c8->Divide(2,2);
+  c8->cd(1);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.80,0.99,0.99);
+  g = htrigmc1.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Trigger rate of macrocell 1 : (maximum)");
+  pixclone1 = (MHPixVsTime*)htrigmc1.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = htrigmc1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  legtrig->AddEntry(hist,Form("Mc 1: %3.0e",hist->GetMaximum()),"p");
+  legtrig->DrawClone();
+  c8->cd(2);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.70,0.99,0.99);
+  g = htrigmc2.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetTitle("Trigger rate of macrocells 2-7 : (maximum)");
+  pixclone1 = (MHPixVsTime*)htrigmc2.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = pixclone1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  legtrig->AddEntry(hist,Form("Mc 2: %3.0e",hist->GetMaximum()),"p");
+  g=htrigmc3.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  if(htrigmc3.GetGraph()->GetN())
+  {
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      legtrig->AddEntry(g,Form("Mc 3: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc3.DrawClone("nonewsame");
+  g=htrigmc4.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  if(htrigmc4.GetGraph()->GetN())
+  {
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      legtrig->AddEntry(g,Form("Mc 4: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc4.DrawClone("nonewsame");
+  g=htrigmc5.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(5);
+  if(htrigmc5.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 5: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc5.DrawClone("nonewsame");
+  g=htrigmc6.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(6);
+  if(htrigmc6.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 6: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc6.DrawClone("nonewsame");
+  g=htrigmc7.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(7);
+  if(htrigmc7.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 7: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc7.DrawClone("nonewsame");
+  legtrig->DrawClone();
+  c8->cd(3);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.70,0.99,0.99);
+  g = htrigmc8.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetTitle("Trigger rate of macrocells 8-13 : (maximum)");
+  if(htrigmc8.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 8: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc8.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+	hist = pixclone1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  g=htrigmc9.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  if(htrigmc9.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 9: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc9.DrawClone("nonewsame");
+  g=htrigmc10.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  if(htrigmc10.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 10: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc10.DrawClone("nonewsame");
+  g=htrigmc11.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(5);
+  if(htrigmc11.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 11: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc11.DrawClone("nonewsame");
+  g=htrigmc12.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(6);
+  if(htrigmc12.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 12: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc12.DrawClone("nonewsame");
+  g=htrigmc13.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(7);
+  if(htrigmc13.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 13: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc13.DrawClone("nonewsame");
+  legtrig->DrawClone();
+  c8->cd(4);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.70,0.99,0.99);
+  TGraph *g = htrigmc14.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  if(htrigmc14.GetGraph()->GetN())
+      legtrig->AddEntry(g,Form("Mc 14: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+  g->SetTitle("Trigger rate of macrocells 14-19 : (maximum)");
+  pixclone1 = (MHPixVsTime*)htrigmc14.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = pixclone1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  g=htrigmc15.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  if(htrigmc15.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 15: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc15.DrawClone("nonewsame");
+  g=htrigmc16.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  if(htrigmc16.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 16: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc16.DrawClone("nonewsame");
+  g=htrigmc17.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(5);
+  if(htrigmc17.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 17: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc17.DrawClone("nonewsame");
+  g=htrigmc18.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(6);
+  if(htrigmc18.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 18: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc18.DrawClone("nonewsame");
+  g=htrigmc19.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(7);
+  if(htrigmc19.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 19: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc19.DrawClone("nonewsame");
+  legtrig->DrawClone();
+
+  //
+  // *************************** Weather station ******************************
+  //
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c9 = d.AddTab("WEATHER STATION");
+  else
+    TCanvas *c9 = new TCanvas();
+  c9->Divide(2,2);
+  // ----------------------- Relative humidity --------------------------------
+  c9->cd(1);
+  g = hCCHum.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  g->SetTitle("Relative humidity outside");
+  clone1 = (MHVsTime*)hCCHum.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Humidity [%]"); 
+    }
+  // -------------------------- Temperature -----------------------------------
+  c9->cd(2);
+  g = hCCTemp.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Temperature outside");
+  clone1 = (MHVsTime*)hCCTemp.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Temperature [\\circ C]"); 
+    }
+  // --------------------------- Wind speed -----------------------------------
+  c9->cd(3);
+  g = hCCWS.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  g->SetLineColor(3);
+  g->SetTitle("Wind speed outside");
+  clone1 = (MHVsTime*)hCCWS.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Wind speed [km/h]"); 
+    }
+  // -------------------------- Solar radiation -------------------------------
+  c9->cd(4);
+  g = hCCSR.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(9);
+  g->SetLineColor(9);
+  g->SetTitle("Solar radiation outside");
+  clone1 = (MHVsTime*)hCCSR.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Solar radiation [W/m^2]"); 
+    }
+
+  // Save data in a postscriptfile (filename.ps)
+  TString file;
+  if (filename.Last('.')>0)
+    file = filename(0, filename.Last('.')); 
+
+  // Make sure the display hasn't been deleted by the user while the
+  // eventloop was running.
+  if ((d = evtloop.GetDisplay()))
+      d->SaveAsPS(directory+file+".ps");
+  else
+    {
+      c1->Print(directory+file+".ps(");
+      c2->Print(directory+file+".ps");
+      c3->Print(directory+file+".ps");
+      c4->Print(directory+file+".ps");
+      c5->Print(directory+file+".ps");
+      c6->Print(directory+file+".ps");
+      c7->Print(directory+file+".ps");
+      c8->Print(directory+file+".ps");
+      c9->Print(directory+file+".ps)");
+    }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/macros/DAQDataCheck.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/DAQDataCheck.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/DAQDataCheck.C	(revision 17960)
@@ -0,0 +1,313 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Raquel de los Reyes, 05/2004 <mailto:reyes@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+// This macro makes the check of the DAQ files (.raw files).
+//
+// The only argument to the macro is the directory with the night raw files
+// (ended with "/"). The macro sorts the entries in alphabetical order;
+// it then joins all the consecutive pedestal, calibration and data runs 
+// and analyses all of them together. Data runs are taken consecutively
+// until it finds a run of other type (pedestal or calibration) or a data run 
+// from another source. When a given source has no previous pedestal and/or
+// calibration runs, the macro takes the most recent ones. 
+//
+// The analysis is done through the jobs classes MJPedestal and MJCalibration.
+//
+///////////////////////////////////////////////////////////////////////////
+void DataAnalysis(const Int_t prun1,const Int_t prun2,
+		  const Int_t crun1,const Int_t crun2,
+		  const Int_t drun1,const Int_t drun2,
+		  const TString inpath,
+		  const TString outdir)
+{
+
+  // Check if no pedestal runs has been detected
+  if(prun1==0)
+  {
+      cout << "No pedestal run(s)!!!"<< endl;
+      break;
+  }
+
+  gStyle->SetOptStat(1);
+  gStyle->SetOptFit();
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+  //
+  // Set the filter of MRunIter to .raw files
+  pruns.SetRawFile(kTRUE);
+  cruns.SetRawFile(kTRUE);
+  druns.SetRawFile(kTRUE);
+
+  //
+  // Check if you are analyzing more than one file
+  if(prun1==prun2)
+    pruns.AddRun(prun1,inpath);
+  else
+    pruns.AddRuns(prun1,prun2,inpath);
+  if(crun1==crun2)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+  if(drun1==drun2)
+    druns.AddRun(drun1,inpath);
+  else
+    druns.AddRuns(drun1,drun2,inpath);
+
+  // 
+  // Set up the source run-range
+  //
+  TRegexp type("_[A-Z]_");
+  TString source = "";
+  if(pruns.GetNumRuns()!=0)
+    source = pruns.Next();
+  source = source(source.Index(type)+3,source.Length());
+  source.Remove(source.Last('_'),source.Length());
+
+  TString title = outdir+source+"_"+prun2+"-"+crun2+"-"+drun2+".ps";
+
+  MStatusDisplay *d = new MStatusDisplay;
+  d->SetTitle(title);
+  d->SetLogStream(&gLog, kTRUE);
+
+  TObject::SetObjectStat(kTRUE);
+ 
+  //
+  // Choose the signal Extractor:
+  //
+  //  MExtractFixedWindowPeakSearch extractor;
+  //  MExtractSlidingWindow  extractor;
+   MExtractFixedWindow    extractor;
+ 
+  //
+  // Set Ranges or Windows
+  //
+   extractor.SetRange(3,14,3,14);
+  //  extractor.SetWindows(8,8);
+ 
+  //
+  // Choose the arrival time Extractor:
+  //
+  //  MExtractTimeHighestIntegral timeext;
+  MExtractTimeFastSpline timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+  // ************************ GENERAL CONTAINERS  *************************
+  MBadPixelsCam     badcam;
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  MCalibrationQECam qecam;  
+
+  // **********************************************************************
+  // ***************************** PEDESTALS ******************************
+  // **********************************************************************
+  if(pruns.GetNumRuns()==0)
+    {
+      cout << "Warning, no entries found in pedestal run(s)!!!"<< endl;
+      break;
+    }
+
+  MJPedestal pedloop;
+  pedloop.SetExtractor(&extractor);           
+  pedloop.SetInput(&pruns);
+  pedloop.SetDisplay(d);
+  pedloop.SetBadPixels(badcam);
+  //
+  // If you want to run the data-check on RAW DATA!!!, choose:
+  pedloop.SetDataCheck(kTRUE);
+
+  //
+  // Execute first analysis
+  //
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+  if (!pedloop.Process())
+    return;
+
+  //
+  // Save display into a postcript file
+  //
+  d->SaveAsPS(outdir+source+"_"+prun2+"-"+crun2+"-"+drun2+".ps");
+
+  // **********************************************************************
+  // ***************************** CALIBRATION ****************************
+  // **********************************************************************
+  if(cruns.GetNumRuns()==0)
+    {
+      cout << "Warning, no entries found in calibration run(s)!!!"<< endl;
+      break;
+    }
+
+  //
+  // Tell if you want to calibrate times:
+  //
+  static const  Bool_t useTimes = kTRUE;
+
+  MJCalibration calloop;
+  //
+  // If you want to run the data-check on RAW DATA!!!, choose:
+  calloop.SetDataCheck();
+  //
+  // If you want to see the data-check plots only, choose:
+  calloop.SetDataCheckDisplay();
+
+  calloop.SetRelTimeCalibration(useTimes);
+  calloop.SetExtractor(&extractor);
+  calloop.SetTimeExtractor(&timeext);
+  calloop.SetInput(&cruns);
+  calloop.SetDisplay(d);
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());            
+
+  //
+  // Execute first analysis
+  //
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  if (!calloop.Process(pedloop.GetPedestalCam()))
+    return;
+
+  //
+  // Save display into a postcript file
+  //
+  d->SaveAsPS(outdir+source+"_"+prun2+"-"+crun2+"-"+drun2+".ps");
+
+
+}
+
+void DAQDataCheck(const TString directory="/remote/bigdown/data/Magic-DATA/Period014/rawdata/2004_02_17/",const TString outdir="./")
+{
+
+  MDirIter iter;
+  iter.AddDirectory(directory,"*.raw");
+
+  TString str=iter.Next();
+
+  TList list;
+  while(!str.IsNull())
+    {
+      list.Add(new TNamed(str,""));
+      str=iter.Next();
+    }
+  list.Sort();
+
+  TIter Next(&list);
+
+  TString fName="file.raw";
+
+  TRegexp run("_[0-9][0-9][0-9][0-9][0-9]_");
+  TRegexp type("_[A-Z]_");
+
+  Int_t pedrun1=0, pedrun2=0;
+  Int_t calrun1=0, calrun2=0;
+  Int_t datarun1=0, datarun2=0;
+
+  TString source="";
+
+  TObject o*;
+  o=Next();
+  fName = o->GetName();  // absolut path
+
+  while(!fName.IsNull())
+    {
+
+      source = fName(fName.Index(type)+3,fName.Length());
+      source.Remove(source.Last('_'),source.Length());
+
+      // Pedestal runs
+      if(fName.Contains("_P_"))
+	pedrun1=atoi(fName(fName.Index(run)+1,5).Data());
+      pedrun2=pedrun1;
+
+      while(fName.Contains("_P_")&&fName.Contains(source))
+	{
+	  pedrun2=atoi(fName(fName.Index(run)+1,5).Data());
+	  o=Next();
+	  if(!o)
+	    {
+	      fName="";
+	      break;
+	    }
+	  fName = o->GetName(); 
+	}
+
+      // Calibration runs
+      if(fName.Contains("_C_"))//||(!fName.Contains(source)))
+	calrun1=atoi(fName(fName.Index(run)+1,5).Data());
+//      else
+//	  calrun1=0; 
+      calrun2=calrun1;
+
+      while(fName.Contains("_C_")&&fName.Contains(source))
+	{
+	  calrun2=atoi(fName(fName.Index(run)+1,5).Data());
+	  o=Next();
+	  if(!o)
+	    {
+	      fName = "";
+	      break;
+	    }
+	  fName = o->GetName(); 
+	}
+
+      // Data runs
+      if(fName.Contains("_D_"))//||(!fName.Contains(source)))
+	datarun1=atoi(fName(fName.Index(run)+1,5).Data());
+      else
+	  datarun1=0; 
+      datarun2=datarun1;
+
+      while(fName.Contains("_D_")&&fName.Contains(source))
+	{
+	  datarun2=atoi(fName(fName.Index(run)+1,5).Data());
+	  o=Next();
+	  if(!o)
+	    {
+	      fName = "";
+	      break;
+	    }
+	  fName = o->GetName(); 
+	}
+
+//        cout << pedrun1 << "\t"<<pedrun2 << endl;
+//        cout << calrun1 << "\t"<<calrun2 << endl;
+//        cout << datarun1 << "\t"<<datarun2 << endl;
+
+      DataAnalysis(pedrun1,pedrun2,calrun1,calrun2,datarun1,datarun2,directory,outdir);
+
+      cout << "----------------------------------------------" << endl;
+
+    }
+
+}
+
+
+
Index: branches/Mars_McMismatchStudy/macros/MagicHillas.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/MagicHillas.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/MagicHillas.C	(revision 17960)
@@ -0,0 +1,190 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// MagicHillas.C
+// =============
+//
+// This is a demonstration program which calculates image (Hillas +)
+// parameters using as input a Merpp output file (raw data).
+// All parameters are written to an output file called hillas.root. Also
+// filles histograms are displayed.
+// For the calculation an arbitrary signal extractor (MCerPhotAnal2/Calc)
+// is used.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void MagicHillas(const char *filename="~/data/Gamma_20_N*.root")
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Use this if you want to change the binning of one of
+    // the histograms. You can use:
+    // BinningConc, BinningConc1, BinningAsym, BinningM3Long,
+    // BinningM3Trans, BinningWidth, BinningLength, BinningDist,
+    // BinningHeadTail, BinningAlpha, BinningSize, BinningDelta,
+    // BinningPixels and BinningCamera
+    //
+    // For more information see MBinning and the corresponding
+    // histograms
+    //
+    // MBinning binsalpha("BinningAlpha");
+    // binsalpha.SetEdges(90, 0, 90);       // 90 bins from 0 to 90 deg
+    // plist.AddToList(&binsalpha);
+
+    // MBinning binssize("BinningSize");
+    // binssize.SetEdgesLog(50, 1, 1e7);
+    // plist.AddToList(&binssize);
+
+    //
+    // Craete the object which hlods the source positions in the camera
+    // plain in respect to which the image parameters will be calculated.
+    // For real data the containers will be filled by a task.
+    //
+    MSrcPosCam source;
+    source.SetReadyToSave();
+    plist.AddToList(&source);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    // The first argument is the tree you want to read.
+    //   Events:     Cosmic ray events
+    //   PedEvents:  Pedestal Events
+    //   CalEvents:  Calibration Events
+    //
+    MReadMarsFile read("Events", filename);
+    read.DisableAutoScheme();
+
+    // Setup a task which makes sure that all used arrays have
+    // the correct size
+    MGeomApply geomapl;
+
+    // tasks used if MC files are detected to calculate pedestals
+    MMcPedestalCopy pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    // calculate the signal in a very simple way
+    // for real adat files use MCerPhotAnal2 instead which also
+    // calculates the pedestal.
+    MCerPhotCalc ncalc;
+    //
+    //  Alternative photon calculation:
+    //  Example: use only 2nd to 6th FADC slices for photon calculation:
+    //
+    //    const Float_t x[15]={0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+    //    const TArrayF w(15,(Float_t*)x);
+    //    ncalc.SetWeights(w);
+    //
+
+    // setup image cleaning and blind pixel treatment
+    MImgCleanStd    clean;
+    MBlindPixelCalc blind;
+
+    //
+    // Instead of unmapping the pixels you can also (The use of this
+    // class is deprecated, it will be replaced by MBadPixels*)
+    //
+    // blind.SetUseInterpolation();
+    // blind.SetUseCetralPixel();
+    //
+
+    // setup tasks to calculate image parameters
+    MHillasCalc    hcalc;
+    MHillasSrcCalc csrc1;
+
+    // setup tasks to fill histograms
+    MFillH hfill1("MHHillas", "MHillas");
+    MFillH hfill2("MHHillasExt");
+    MFillH hfill3("MHStarMap", "MHillas");
+    MFillH hfill4("HistExtSource [MHHillasExt]", "MHillasSrc");
+    MFillH hfill5("HistSource [MHHillasSrc]", "MHillasSrc");
+    MFillH hfill6("MHNewImagePar");
+
+    // setup task to write containers to a file
+    MWriteRootFile write("hillas.root");
+    write.AddContainer("MHStarMap");
+    write.AddContainer("MHHillas");
+    write.AddContainer("MHHillasExt");
+    write.AddContainer("HistSource");
+    write.AddContainer("HistExtSource");
+    write.AddContainer("MHNewImagePar");
+
+    // Setup the contents of zour tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&blind);
+
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&csrc1);
+
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+    tlist.AddToList(&hfill6);
+    tlist.AddToList(&write);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // After the analysis is finished we can display the histograms
+    //
+    plist.FindObject("MHHillas")->DrawClone();
+    plist.FindObject("MHHillasExt")->DrawClone();
+    plist.FindObject("MHStarMap")->DrawClone();
+    plist.FindObject("HistSource")->DrawClone();
+    plist.FindObject("HistExtSource")->DrawClone();
+    plist.FindObject("MHNewImagePar")->DrawClone();
+}
+
Index: branches/Mars_McMismatchStudy/macros/RFEnergyEst.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/RFEnergyEst.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/RFEnergyEst.C	(revision 17960)
@@ -0,0 +1,265 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck, 02/2005 <mailto:hengsteb@physik.hu-berlin.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// This macro shows you how to use the new class MRFEnergyEst, which is
+// an implementation of energy estimation with RF. It contains following
+// functions:
+//
+//   - CreateMatrices()  : Create matrix for training (and matrix for test)
+//   - RFEnergyEstTrain(): Training of RFs
+//   - ReadForests()     : Read and print out energy bins which have been used
+//                         in training (depence on statistics)
+//
+//   - RFEnergyEstTest() : Fast testing using a matrix with test data
+//   - RFEnergyEstLoop() : Application of RF energy est in eventloop
+//
+////////////////////////////////////////////////////////////////////////////
+
+
+//****************************************************************************
+// main user settings
+//****************************************************************************
+
+//----------------------------------------------------------------------------
+// settings for RF training
+const Int_t ntrees    = 50; // 50-100 is usually sufficient
+const Int_t numtrials = 3;  // should be <= sqrt(no. of used var)
+const Int_t nodesize  = 1;  // best results with 1
+
+// settings for energy grid
+const Int_t ebins   = 30;
+const Float_t e_low = log10(10);    // lower limit of log10(energy[GeV])
+const Float_t e_up  = log10(30000); // upper limit
+
+//----------------------------------------------------------------------------
+// data settings
+TString path="/emc/commich/Mars/mcdata/oldout/";
+
+//TString nameTrain = "19990101_10001_I_MCGamTrainLZA_E_10_5";
+//TString nameTest  = "19990101_10002_I_MCGamTestLZA_E_10_5";
+TString nameTrain = "19990101_10003_I_MCGamTrainHZA_E_10_5";
+TString nameTest  = "19990101_10004_I_MCGamTestHZA_E_10_5" ;
+
+TString info=""; // put here additional info e.g. about cuts used in
+                 // CreateMatrices function
+
+//----------------------------------------------------------------------------
+// generate filenames
+TString fileNameTrain = path + nameTrain + ".root";
+TString fileNameTest  = path + nameTest  + ".root";
+
+TString fileMatrixTrain = nameTrain + "_Matrix" + info + ".root";
+TString fileMatrixTest  = nameTest  + "_Matrix" + info + ".root";
+
+TString fileForest = "EForests" + nameTrain + info + ".root";
+
+
+//****************************************************************************
+//   Create matrices for training (and test)
+//****************************************************************************
+void CreateMatrices()
+{
+    MGeomCamMagic gcam;
+    const Double_t mm2deg=gcam.GetConvMm2Deg();//180./17000./3.14159265358979312;
+
+    TString filename[2]   = {fileNameTrain,fileNameTest};
+    TString filematrix[2] = {fileMatrixTrain,fileMatrixTest};
+
+    for(int i=0;i<2;i++)
+    {
+        if(filename[i].IsNull() || filematrix[i].IsNull())
+            continue;
+
+        MParList  plist;
+        MTaskList tlist;
+        plist.AddToList(&tlist);
+
+        MReadTree  read("Events", filename[i]);
+        read.DisableAutoScheme();
+
+        MHMatrix matrix("MatrixGammas");
+        // setting rules (MC energy must be last column!!!)
+        matrix.AddColumn("log10(MHillas.fSize)");
+        matrix.AddColumn("MHillasSrc.fDist");
+        matrix.AddColumn("MHillas.fWidth");
+        matrix.AddColumn("MHillas.fLength");
+        matrix.AddColumn("log10(MHillas.fSize/(MHillas.fLength*MHillas.fWidth))");
+        matrix.AddColumn("MNewImagePar.fConc");
+        matrix.AddColumn("MNewImagePar.fLeakage1");
+        matrix.AddColumn("MPointingPos.fZd");
+        matrix.AddColumn("MMcEvt.fEnergy");
+
+        plist.AddToList(&matrix);
+        MFillH fillmat("MatrixGammas");
+
+        // pre-cuts on data,
+        // take care that this is inverted logic (MContinue task!!)
+        MContinue sizecut("MHillas.fSize<60.");
+        MContinue leakcut("MNewImagePar.fLeakage1>0.1");
+        MContinue distcutlo(Form("MHillasSrc.fDist*%f<0.3",mm2deg));
+        MContinue distcutup(Form("MHillasSrc.fDist*%f>1.1",mm2deg));
+        MContinue hcut("MHadronness.fHadronness>0.3");
+
+        tlist.AddToList(&read);
+
+        // put cuts into tlist
+        tlist.AddToList(&sizecut);
+        tlist.AddToList(&leakcut);
+        tlist.AddToList(&distcutlo);
+        tlist.AddToList(&distcutup);
+        //tlist.AddToList(&hcut);
+
+        tlist.AddToList(&fillmat);
+
+        MEvtLoop evtloop;
+        evtloop.SetParList(&plist);
+
+        if (!evtloop.Eventloop()) return;
+        tlist.PrintStatistics();
+
+        TFile file(filematrix[i],"recreate","");
+        matrix.Write();
+        file.Close();
+    }
+
+    return;
+}
+
+//****************************************************************************
+//   Training of RFs
+//****************************************************************************
+void RFEnergyEstTrain()
+{
+    // initializations
+    TArrayD egrid(ebins+1);
+
+    for(Int_t i=0;i<=ebins;i++)
+        egrid[i]=e_low+i*(e_up-e_low)/float(ebins);
+
+    MHMatrix matrix;
+    TFile *file=new TFile(fileMatrixTrain);
+    matrix.Read("MatrixGammas");
+
+    // output info about used rules
+    cout<<endl<<"Rules for energy estimation:"<<endl;
+    for(Int_t i=0;i<matrix.GetM().GetNcols();i++)
+    {
+        MDataArray *rules = matrix.GetColumns();
+        MData &data=(*rules)[i];
+
+        cout<<" "<<i+1<<") "<<data.GetRule()<<endl;
+    }
+
+    // setup RF for energy estimation
+    MRFEnergyEst rf;
+    rf.SetMatrixTrain(&matrix);
+    rf.SetFile(fileForest);
+    rf.SetLogEnergyGrid(egrid);
+
+    rf.SetNumTrees(ntrees);  // number of trees
+    rf.SetNumTry(numtrials); // number of trials in random split selection
+    rf.SetNdSize(nodesize);  // limit for nodesize
+
+    rf.Train();
+
+    return;
+}
+
+//****************************************************************************
+//   Check which energy bins have been used
+//****************************************************************************
+void ReadForests()
+{
+    TFile fileRF(fileForest,"read");
+    TList *list=(TList*)fileRF.GetListOfKeys();
+    const Int_t n=list->GetSize()-1;// subtract 1 since 1 key belongs to MDataArray
+
+    MRanForest forest;
+    for(Int_t i=0;i<n;i++)
+    {
+        forest.Read(Form("%d",i));
+        MRanForest *curforest=(MRanForest*)forest.Clone();
+        const char *energy=list->FindObject(Form("%d",i))->GetTitle();
+        const char *bin   =list->FindObject(Form("%d",i))->GetName();
+
+        if(i<10) cout<<"Bin  "<<bin<<":   log10(Energy[GeV]) = "<<energy<<endl;
+        else     cout<<"Bin "<< bin<<":   log10(Energy[GeV]) = "<<energy<<endl;
+    }
+    fileRF.Close();
+
+    return;
+}
+
+//****************************************************************************
+//   Fast Testing with matrix
+//****************************************************************************
+void RFEnergyEstTest()
+{
+    MHMatrix matrix;
+    TFile *file=new TFile(fileMatrixTest);
+    matrix.Read("MatrixGammas");
+
+    MRFEnergyEst rf;
+    rf.SetMatrixTest(&matrix);
+    rf.SetFile(fileForest);
+
+    rf.SetBit(MParContainer::kEnableGraphicalOutput,1);
+    rf.Test();
+
+    return;
+}
+
+//****************************************************************************
+//   Apply RF energy estimation in eventloop
+//****************************************************************************
+void RFEnergyEstLoop()
+{
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    MReadTree  read("Events",fileNameTest);
+    read.DisableAutoScheme();
+
+    MRFEnergyEst rf;
+    rf.SetFile(fileForest);
+
+    MWriteRootFile write("EnergyEstTest.root");
+    write.AddContainer("MMcEvt",     "Events");
+    write.AddContainer("MEnergyEst", "Events");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&rf);
+    tlist.AddToList(&write);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop()) return;
+    tlist.PrintStatistics();
+
+    return;
+}
Index: branches/Mars_McMismatchStudy/macros/RanForest.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/RanForest.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/RanForest.C	(revision 17960)
@@ -0,0 +1,179 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>!
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void RanForest()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadMarsFile  read("Events", "~/MagicData/data1/CT1Data/ONTrain/*.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    MFParticleId fgamma("MMcEvt", '=', MMcEvt::kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    MHMatrix matrixg("MatrixGammas");
+    matrixg.AddColumn("cos(MMcEvt.fTelescopeTheta)");
+    matrixg.AddColumn("MSigmabar.fSigmabar");
+    matrixg.AddColumn("log10(Hillas.fSize)");
+    matrixg.AddColumn("HillasSrc.fDist");
+    matrixg.AddColumn("Hillas.fWidth");
+    matrixg.AddColumn("Hillas.fLength");
+    matrixg.AddColumn("log10(Hillas.fSize)/Hillas.fWidth*Hillas.fLength");
+    matrixg.AddColumn("abs(Hillas.fM3Long)");
+    matrixg.AddColumn("Hillas.fConc");
+    matrixg.AddColumn("Hillas.fConc1");
+
+    //matrixg.AddColumn("abs(Hillas.fAsym)");
+    //matrixg.AddColumn("abs(Hillas.fM3Trans)");
+    //matrixg.AddColumn("abs(HillasSrc.fHeadTail)");
+    //matrixg.AddColumn("abs(HillasSrc.fAlpha)");
+
+    plist.AddToList(&read);
+
+    plist.AddToList(&matrixg);
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.AddColumns(matrixg.GetColumns());
+    plist.AddToList(&matrixh);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&fgamma);
+    tlist.AddToList(&fillmatg);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&fhadrons);
+    tlist.AddToList(&fillmath);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // second event loop: the trees of the random forest are grown,
+    // the event loop is now actually a tree loop (loop of training
+    // process)
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(10);
+    rfgrow2.SetNumTry(3);
+    rfgrow2.SetNdSize(10);
+
+    MWriteRootFile rfwrite2("RF.root");
+    rfwrite2.AddContainer("MRanTree","Tree");       //save all trees
+    MFillH fillh2("MHRanForestGini");
+
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    // gRandom is accessed from MRanForest (-> bootstrap aggregating)
+    // and MRanTree (-> random split selection) and should be initialized
+    // here if you want to set a certain random number generator
+    if(gRandom)
+        delete gRandom;
+    gRandom = new TRandom3(0);
+
+    //
+    // Execute tree growing (now the eventloop is actually a treeloop)
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist2.PrintStatistics();
+
+    plist.FindObject("MHRanForestGini")->DrawClone();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // third event loop: the control sample (star2.root) is processed
+    // through the previously grown random forest,
+    //
+    // the histograms MHHadronness (quality of g/h-separation) and
+    // MHRanForest are created and displayed.
+    // MHRanForest shows the convergence of the classification error
+    // as function of the number of grown (and combined) trees
+    // and tells the user how many trees are actually needed in later
+    // classification tasks.
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist3;
+
+    plist.Replace(&tlist3);
+
+    MReadMarsFile  read3("Events", "~/MagicData/data1/CT1Data/ONTest/*.root");
+    read3.DisableAutoScheme();
+    tlist3.AddToList(&read3);
+
+    MRanForestCalc calc;
+    tlist3.AddToList(&calc);
+
+    MFillH fillh3a("MHHadronness");
+    MFillH fillh3b("MHRanForest");
+
+    tlist3.AddToList(&fillh3a);
+    tlist3.AddToList(&fillh3b);
+
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist3.PrintStatistics();
+
+    plist.FindObject("MHRanForest")->DrawClone();
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();//*/
+}
Index: branches/Mars_McMismatchStudy/macros/RanForest2.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/RanForest2.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/RanForest2.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/checkaclic.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/checkaclic.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/checkaclic.C	(revision 17960)
@@ -0,0 +1,61 @@
+Bool_t check(const char *path)
+{
+    cout << "Compiling " << path << "...";
+
+    if (!gSystem->CompileMacro(Form("datacenter/macros/%s", path), "cf"))
+        return kFALSE;
+
+    cout << "done." << endl;
+
+    return kTRUE;
+}
+
+int checkaclic()
+{
+    gLog.SetDebugLevel(2);
+
+    if (!check("buildsequenceentries.C"))
+        return 1;
+    if (!check("checkfileavail.C"))
+        return 1;
+    if (!check("checkstardone.C"))
+        return 1;
+    if (!check("doexclusions.C"))
+        return 1;
+    if (!check("resetcolumn.C"))
+        return 1;
+    if (!check("plotstat.C"))
+        return 1;
+    if (!check("plotdb.C"))
+        return 1;
+    if (!check("fillstar.C"))
+        return 1;
+    if (!check("fillsinope.C"))
+        return 1;
+    if (!check("fillsignal.C"))
+        return 1;
+    if (!check("fillganymed.C"))
+        return 1;
+    if (!check("filldotrun.C"))
+        return 1;
+    if (!check("filldotrbk.C"))
+        return 1;
+    if (!check("filldotraw.C"))
+        return 1;
+    if (!check("fillcalib.C"))
+        return 1;
+    if (!check("findcacofiles.C"))
+        return 1;
+    if (!check("insertcacofile.C"))
+        return 1;
+    if (!check("insertdataset.C"))
+        return 1;
+    if (!check("insertdate.C"))
+        return 1;
+    if (!check("resetallruns.C"))
+        return 1;
+    if (!check("writesequencefile.C"))
+        return 1;
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/macros/collarea.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/collarea.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/collarea.C	(revision 17960)
@@ -0,0 +1,191 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Abelardo Moralejo, 2/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+// 
+// Example macro on how to calculate effective areas. The input is a file 
+// containing Hillas parameters of the MC events surviving a certain kind 
+// of analysis. It must also contain a tree called "OriginalMC" with a branch
+// "MMcEvtBasic" and one entry per original simulated shower used to produce
+// the events in that input file. The current (2/2005) camera simulation in 
+// the cvs already writes out all events with the MMcEvtBasic container to
+// the Events tree. In Mars/macros/mccalibrate.C and starmc2.C you can see
+// how this branch is put to a separate tree "OriginalMC" and written out
+// to the "star" file. This will not work with star files not containing this
+// extra tree. Please contact moralejo@pd.infn.it in case of questions
+// about this new approach to the calculation of effective areas.
+//
+
+void collarea(TString filename="star_gamma_test.root", TString outname="area.root")
+{
+  MStatusDisplay *d = new MStatusDisplay;
+    // redirect logging output to GUI, kFALSE to disable stream to stdout
+  d->SetLogStream(&gLog, kTRUE);
+
+  //
+  // First loop: fill the MHMcCollectionArea::fHistAll histogram containing
+  // all the events produced at the Corsika level:
+  //
+  MParList  parlist;
+  MTaskList tasklist;
+
+  parlist.AddToList(&tasklist);
+
+  //
+  // Setup out tasks:
+  //  - First we have to read the events
+  //
+  MReadMarsFile reader("OriginalMC", filename);
+  reader.DisableAutoScheme();
+
+  //
+  // Create collection area object and add it to the task list
+  //
+  MHMcCollectionArea collarea;
+  parlist.AddToList(&collarea);
+
+  //
+  // Set the COARSE binnings in which you will divide your data, to get
+  // the collection area in these same binnings. You can set also this
+  // binnings on an existing and filled MHMcCollectionAreaObject, and
+  // call Calc again to get the effective area in other coarse bins.
+  //
+  MBinning binsTheta("binsTheta");
+  MBinning binsEnergy("binsEnergy"); // name must be standardized!
+  Int_t nbins = 8;
+  TArrayD edges(nbins+1);
+  edges[0] = 0;
+  edges[1] = 10.;
+  edges[2] = 20.;
+  edges[3] = 30.;
+  edges[4] = 40.;
+  edges[5] = 50.;
+  edges[6] = 60.;
+  edges[7] = 70.;
+  edges[8] = 80.;
+  binsTheta.SetEdges(edges);              // Theta [deg]
+  binsEnergy.SetEdgesLog(20, 2., 20000);  // Energy [GeV]
+  parlist.AddToList(&binsTheta);
+  parlist.AddToList(&binsEnergy);
+
+  // Task which fills the necessary histograms in MHMcCollectionArea
+  MMcCollectionAreaCalc effi;
+
+  // Tentative energy spectrum. This may slightly modify the calculation
+  // of effective areas. If not added to the parameter list, a flat spectrum
+  // in dN/dE will be assumed. "x" stands for the energy. The name of the 
+  // function must be standardized!
+
+  TF1 Spectrum("Spectrum", "pow(x,-5.)");
+  effi.SetSpectrum(&Spectrum);
+
+  tasklist.AddToList(&reader);
+  tasklist.AddToList(&effi);
+
+  //
+  // set up the loop for the processing
+  //
+  MEvtLoop magic;
+  magic.SetParList(&parlist);
+
+  //
+  // Start to loop over all events
+  //
+  magic.SetDisplay(d);
+
+  if (!magic.Eventloop())
+    return;
+
+  tasklist.PrintStatistics();
+
+
+  //
+  // Second loop: now fill the histogram MHMcCollectionArea::fHistSel
+  //
+
+  MParList parlist2;
+  MTaskList tasklist2;
+  parlist2.AddToList(&tasklist2);
+  parlist2.AddToList((MHMcCollectionArea*)parlist->FindObject("MHMcCollectionArea"));
+
+  MReadMarsFile reader2("Events", filename);
+  reader2.DisableAutoScheme();
+
+  tasklist2.AddToList(&reader2);
+
+  // The same task as before, now will fill MHMcCollectionArea::fHistSel
+  // and call MHMcCollectionArea::Calc in the PostProcess
+  tasklist2.AddToList(&effi);
+
+  //
+  // set up the loop for the processing
+  //
+  MEvtLoop magic2;
+  magic2.SetParList(&parlist2);
+
+  //
+  // Start to loop over all events
+  //
+  magic2.SetDisplay(d);
+
+  if (!magic2.Eventloop())
+    return;
+
+  tasklist2.PrintStatistics();
+
+  //
+  // Now the histogram we wanted to get out of the data is
+  // filled and can be displayed
+  //
+  if ((d = magic2.GetDisplay()))
+    d->AddTab("Collection Area");
+  else
+    new TCanvas("CollArea", "Result of the collection area calculation");
+
+  gStyle->SetPalette(1,0);
+  gPad->SetLogx();
+  TH2D* areaplot = ((MHMcCollectionArea*)parlist2.FindObject
+		    ("MHMcCollectionArea"))->GetHistCoarse();
+
+  areaplot->SetStats(0);
+  areaplot->SetTitle("Effective area (m^{2})");
+  areaplot->GetXaxis()->SetTitle("Energy (GeV)");
+  areaplot->GetYaxis()->SetTitle("\\theta (deg)");
+  areaplot->DrawCopy("zcol");
+
+  //
+  // Write histogram to a file in case an output
+  // filename has been supplied
+  //
+
+  if (outname.IsNull())
+    return;
+
+  TFile f(outname, "recreate");
+  if (!f)
+    return;
+
+  // Write to the output file:
+  parlist2.FindObject("MHMcCollectionArea")->Write();
+}
Index: branches/Mars_McMismatchStudy/macros/comprob.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/comprob.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/comprob.C	(revision 17960)
@@ -0,0 +1,130 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   macro comprob.C
+!
+!   Author(s): Abelardo Moralejo
+!   Author(s): Thomas Bretz, 2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//  This macro demonstrates one way of gamma hadron separation using the
+//  composite probability method. To use it you need a star-file (which is
+//  a file ouput by the star.C macro containing image parameters)
+//
+///////////////////////////////////////////////////////////////////////////
+void comprob()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    // Create task list and add it to the parameter list:
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // First task in list: read the star file (reference data)
+    MReadMarsFile read("Events", "star.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    //
+    // Task to do the composite analysis of Hillas parameters:
+    // Add(rule, number of bins, lower limit, upper limit)
+    // For the meaning of the rule see MDataChain
+    //
+    MHCompProb compprob(500);
+    compprob.Add("MHillas.fWidth",              500,    0, 160);
+    compprob.Add("MHillas.fLength",             500,    0, 300);
+    compprob.Add("abs(MHillas.fAsym)",          500,    0, 400);
+    compprob.Add("MHillasSrc.fDist",            500,    0, 400);
+    compprob.Add("abs(MHillasSrc.fHeadTail)",   500,    0, 400);
+    compprob.Add("abs(MHillas.fM3Long)",        500,    0, 300);
+    compprob.Add("abs(MHillas.fM3Trans)",       500,    0, 150);
+    compprob.Add("MHillas.fConc1",              500,    0, 0.6);
+    compprob.Add("MHillas.fConc",               500,    0, 0.9);
+    compprob.Add("log10(MHillas.fSize)",        500,    0,   5);
+
+    plist.AddToList(&compprob);
+
+    MFillH fill(&compprob, "MMcEvt");
+
+    // Use this if you want to do it for a fixed energy range:
+    /*
+     MF filter("MMcEvt.fEnergy < 100");
+     fill->SetFilter(&filter);
+     tlist.AddToList(&filter);
+     */
+
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    // Loop over all data to fill the "normal" histograms:
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    gLog.SetDebugLevel(2);
+
+    // Loop to fill the variable bin histograms:
+    read.SetEventNum(0);
+    if (!evtloop.Eventloop())
+        return;
+
+    // ------------------------------------------------------------------
+
+    // Create task list and replace the old task list with the new one
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    // First task in list: read star file (test data)
+    MReadMarsFile read2("Events", "star2.root");
+    read2.DisableAutoScheme();
+    tlist2.AddToList(&read2);
+
+    // create task to calculate composite probabilities
+    MCompProbCalc calc;
+    tlist2.AddToList(&calc);
+
+    // fill probabilities (hadroness) into histogram
+    MFillH fill2("MHHadronness");
+    tlist2.AddToList(&fill2);
+
+    // Loop to fill the hadronness histograms:
+    if (!evtloop.Eventloop())
+        return;
+
+    //
+    // Display the hadroness histograms and print some informations on
+    // the console window
+    //
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();
+}
+
Index: branches/Mars_McMismatchStudy/macros/datatrigcheck.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/datatrigcheck.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/datatrigcheck.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/dohtml.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/dohtml.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/dohtml.C	(revision 17960)
@@ -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  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// dohtml.C
+// ========
+//
+// This is a service macro used to create the html-documentation from
+// source code (THtml)
+//
+// Add here all directories in which files are stored from which the
+// documentation should be created an add all macros which should be
+// converted to HTML.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void dohtml()
+{
+    //
+    //  don't forget that the shared object must have been loaded
+    //
+
+    //
+    // Do not print 'Info' messages from the root system such like
+    // TCanvas::Print
+    //
+    gErrorIgnoreLevel=kWarning;
+
+    //
+    //   create the html document class
+    //
+    THtml html;
+
+    TString sourcedir;
+    sourcedir += "manalysis:";
+    sourcedir += "mastro:";
+    sourcedir += "mbadpixels:";
+    sourcedir += "mbase:";
+    sourcedir += "mcamera:";
+    sourcedir += "mcalib:";
+    sourcedir += "mcorsika:";
+    sourcedir += "mdata:";
+    sourcedir += "melectronics:";
+    sourcedir += "mextralgo:";
+    sourcedir += "mfbase:";
+    sourcedir += "mfileio:";
+    sourcedir += "mfilter:";
+    sourcedir += "mfit:";
+    sourcedir += "mgeom:";
+    sourcedir += "mgui:";
+    sourcedir += "mhbase:";
+    sourcedir += "mhflux:";
+    sourcedir += "mhft:";
+    sourcedir += "mhist:";
+    sourcedir += "mhistmc:";
+    sourcedir += "mhcalib:";
+    sourcedir += "mhvstime:";
+    sourcedir += "mimage:";
+    sourcedir += "mjobs:";
+    sourcedir += "mjoptim:";
+    sourcedir += "mjtrain:";
+    sourcedir += "mmain:";
+    sourcedir += "mmc:";
+    sourcedir += "mmontecarlo:";
+    sourcedir += "mmovie:";
+    sourcedir += "mmuon:";
+    sourcedir += "mpedestal:";
+    sourcedir += "mpointing:";
+    sourcedir += "mranforest:";
+    sourcedir += "mraw:";
+    sourcedir += "mreflector:";
+    sourcedir += "mreport:";
+    sourcedir += "msignal:";
+    sourcedir += "msim:";
+    sourcedir += "msimcamera:";
+    sourcedir += "msimreflector:";
+    sourcedir += "msql:";
+    sourcedir += "mstarcam:";
+    sourcedir += "mtools:";
+    sourcedir += "mtrigger:";
+    sourcedir += ".:";
+
+    html.SetSourceDir(sourcedir);
+    html.SetOutputDir("htmldoc");
+
+    html.MakeAll(kTRUE);
+
+    html.SetSourceDir("macros");
+    html.Convert("merpp.C",                     "MARS - Merging and Preprocessing");
+    html.Convert("tutorials/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("starfield.C",                 "MARS - Display a starfield in the camera");
+    html.Convert("starvisday.C",                "MARS - Display visibility of stars at a single day");
+    html.Convert("starvisyear.C",               "MARS - Display visibility of a source around the year");
+    html.Convert("tutorials/starplot.C",        "MARS - Plot parameters from file created with star.C");
+    html.Convert("tutorials/readrfl.C",         "MARS - Example of reading reflector output with Mars");
+    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("tutorials/plot.C",            "MARS - Plots 1D mars histogram");
+    html.Convert("tutorials/plot2.C",           "MARS - Plots a 2D mars histogram");
+    html.Convert("tutorials/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("tutorials/pedvsevent.C",      "MARS - Example to use MPedCalcPedRun");
+    //html.Convert("pedphotcalc.C",   "MARS - Example to use MPedPhotCalc");
+    html.Convert("tutorials/derotatedc.C",      "MARS - Example of plotting derotated dc currents");
+    html.Convert("tutorials/evtrate.C",         "MARS - Example how to plot the event rate");
+//    html.Convert("tutorials/pixvsevent.C",  "MARS - Example how to plot pixel value versus event number/time");
+    html.Convert("tutorials/sectorvstime.C",    "MARS - Example how to plot mean value of a camera sector versus time");
+    html.Convert("tutorials/pedestalvstime.C",  "MARS - Example how to plot pedestal/rms versus time");
+    html.Convert("tutorials/pixfirerate.C",     "MARS - Example how to plot the firerate of a pixel (times above threshold)");
+    html.Convert("tutorials/pixsatrate.C",      "MARS - Example how to plot the saturation rate of a pixel");
+    html.Convert("tutorials/threshold.C",       "MARS - Example how to calculate the threshold");
+    //html.Convert("calibration.C",   "MARS - Example how to use the calibrationa camera ");
+    //html.Convert("bootcampstandardanalysis.C", "MARS - Example of the status of the standard analysis at the bootcamp");
+    html.Convert("readIPR.C",                   "MARS - Example to read and display the IPRs from a (merpped) report file");
+    html.Convert("tutorials/extendcam.C",       "MARS - Example of using MGeomCamExtend and MHexagonalFTCalc");
+    html.Convert("tutorials/hft.C",             "MARS - Example of using MHexagonalFTCalc");
+    html.Convert("tutorials/calendar.C",        "MARS - Example of producing a calendar sheet");
+    html.Convert("tutorials/weights.C",         "MARS - Example of using weights with MFillH");
+}
Index: branches/Mars_McMismatchStudy/macros/fact/drscal.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/fact/drscal.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/fact/drscal.C	(revision 17960)
@@ -0,0 +1,164 @@
+int drscal(const char *drsname="~dorner/mysequences/2012/02/28/20120228_200.drs.seq", const char *outpath = "output")
+{
+    // ======================================================
+
+    const char *map = "/scratch_nfs/FACTmap111030.txt";
+
+    // ======================================================
+
+    if (map && gSystem->AccessPathName(map, kFileExists))
+    {
+        gLog << "ERROR - Cannot access mapping file '" << map << "'" << endl;
+        return 1;
+    }
+
+    // The sequence file which defines the files for the analysis
+    MSequence drs(drsname);
+    if (!drs.IsValid())
+    {
+        gLog << "ERROR - Sequence '" << drsname << "' invalid!" << endl;
+        return 2;
+    }
+
+    // DrsRuns 1
+    // CalRuns 1
+    // DrsFiles 1 [1024], PedRuns 1 [300]
+
+    // --------------------------------------------------------------------------------
+
+    gLog.Separator("DRS Calibration");
+    gLog << "Calculate drs calibration constants of drs sequence:\n" << drs.GetFileName() << endl;
+    gLog << endl;
+
+    // ------------------------------------------------------
+
+    TString drsped  = drs.GetFileName(0, MSequence::kFitsDrsRuns);
+    TString drsgain = drs.GetFileName(0, MSequence::kFitsCal);
+    TString drs1024 = drs.GetFileName(1, MSequence::kFitsDrsRuns);
+    TString drs300  = drs.GetFileName(0, MSequence::kFitsPed);
+
+    gLog << "DRS ped  1024: " << drsped   << '\n';
+    gLog << "DRS gain 1024: " << drsgain  << '\n';
+    gLog << "DRS ped  1024: " << drs1024  << "\n";
+    gLog << "DRS ped   300: " << drs300   << endl;
+
+    // ======================================================
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MParList plist;
+
+    MHDrsCalibration hist;
+    plist.AddToList(&hist);
+
+    hist.SetOutputPath(outpath);
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MEvtLoop loop;
+    loop.SetParList(&plist);
+    loop.SetDisplay(d);
+
+    // --------------------------------------------------------
+
+    gLog.Separator("Calculating cell offset");
+
+    MRawFitsRead read1(drsped);
+    read1.LoadMap(map);
+
+    MGeomApply apply;
+
+    tlist.AddToList(&read1);
+    tlist.AddToList(&apply);
+
+    MFillH fill("MHDrsCalibration");
+    fill.SetNameTab("Ped1");
+
+    tlist.AddToList(&fill);
+
+    if (!loop.Eventloop())
+        return 3;
+
+    if (!loop.GetDisplay())
+        return 4;
+
+    // --------------------------------------------------------
+
+    gLog.Separator("Calculating cell gain");
+
+    MRawFitsRead read2(drsgain);
+    read2.LoadMap(map);
+    tlist.Replace(&read2);
+    fill.SetNameTab("Gain");
+
+    if (!loop.Eventloop())
+        return 5;
+
+    if (!loop.GetDisplay())
+        return 6;
+
+    // --------------------------------------------------------
+
+    gLog.Separator("Calculating drs constants for roi=1024");
+
+    fill.SetNameTab("Ped2-1024");
+
+    // I think one HAS to use the same file than for step one
+    // this is the only way to get rid of a systematic shift.
+    MRawFitsRead read3(drs1024);
+    read3.LoadMap(map);
+    tlist.Replace(&read3);
+
+    if (!loop.Eventloop())
+        return 7;
+
+    if (!loop.GetDisplay())
+        return 8;
+
+    // --------------------------------------------------------
+
+    gLog.Separator("Calculating drs constants for roi=300");
+
+    fill.SetNameTab("Ped2-300");
+
+    if (!hist.ResetSecondaryBaseline())
+    {
+        cout << "ERROR - Reset failed." << endl;
+        return 100;
+    }
+
+    // This would just result in a wrong consistency check for the roi
+    plist.Remove((MParContainer*)plist.FindObject("MRawRunHeader"));
+    plist.Remove((MParContainer*)plist.FindObject("MRawEvtData"));
+
+    // I think one HAS to use the same file than for step one
+    // this is the only way to get rid of a systematic shift.
+    MRawFitsRead read4(drs300);
+    read4.LoadMap(map);
+    tlist.Replace(&read4);
+
+    if (!loop.Eventloop())
+        return 9;
+
+    if (!loop.GetDisplay())
+        return 10;
+
+    // --------------------------------------------------------
+
+    TString title = "--  DRS Calibration #";
+    title += drs.GetSequence();
+    title += " (";
+    title += drsname;
+    title += ")  --";
+    d->SetTitle(title, kFALSE);
+
+    TString path;
+    path += Form("%s/20%6d_%03d-drs.root", outpath,
+                 drs.GetSequence()/1000, drs.GetSequence()%1000);
+
+    d->SaveAs(path);
+
+    return 0;
+
+}
Index: branches/Mars_McMismatchStudy/macros/fact/fact_trigger.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/fact/fact_trigger.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/fact/fact_trigger.C	(revision 17960)
@@ -0,0 +1,74 @@
+void fact_trigger()
+{
+    MLut lut;
+
+    // read all trigger patches
+    lut.ReadFile("resmc/fact-trigger-all.txt");
+    // read only the regular trigger patches
+    //lut.ReadFile("resmc/fact-trigger-sum.txt");
+
+    // For crosscheck print the table to the console
+    lut.Print();
+
+    // Create FACT camera geometry
+    MGeomCamFACT fact;
+
+    // create to camera histograms, one for the colors and one for the patch number
+    MHCamera h(fact);
+    MHCamera p(fact);
+    h.SetTitle("FACT trigger layout in MARS");
+
+    // remove all obsolete stuff around
+    h.SetStats(kFALSE);
+    h.SetBit(MHCamera::kNoLegend);
+
+    // Number of maximum colors
+    Int_t n = 99;
+
+    for (int i=0; i<lut.GetNumRows(); i++)
+    {
+        // Get the i-th patch
+        MArrayI &row = lut.GetRow(i);
+
+        // Check for all colors already used in the neighborhood
+        MArrayI col(n+1);
+        for (int j=0; j<9; j++)
+        {
+            if (row[j]==1438 || row[j]==1439)
+                continue;
+
+            for (int k=0; k<fact[row[j]].GetNumNeighbors(); k++)
+                col[TMath::Nint(h.GetBinContent(fact[row[j]].GetNeighbor(k)+1))]=1;
+        }
+
+        // Find the first unused color
+        int k = 1;
+        for (; k<n+1; k++)
+            if (col[k]<0.5)
+                break;
+
+        // This is just to "adjust" the colors a bit more to the palette
+        // For simplicity (rounding below) the adjustment must not exceed +- 0.5
+        // If the number of needed colors is different this needs adjustment!
+        Double_t c[99] = { 1.0, 2.4, 3.4, 4.1, 5.0 };
+
+        // Loop over all nine pixles in the patch
+        for (int j=0; j<9; j++)
+        {
+            if (row[j]==1438 || row[j]==1439)
+                continue;
+
+            h.SetBinContent(row[j]+1, c[k-1]);  // Color (For a funny symmetry replace it by row[0]%6)
+            p.SetBinContent(row[j]+1, i);       // Patch number
+            h.SetUsed(row[j]);                  // Switch on that the color is shown
+        }
+    }
+
+    // Plot the colors and the numbers on top
+    h.DrawCopy("");
+    p.DrawCopy("same integer");
+
+    // Adjust the canvas attributes
+    gPad->SetBorderMode(0);
+    gPad->SetFillColor(kWhite);
+}
Index: branches/Mars_McMismatchStudy/macros/fact/fake_drs_calibration.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/fact/fake_drs_calibration.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/fact/fake_drs_calibration.C	(revision 17960)
@@ -0,0 +1,62 @@
+#include "DrsCalib.h"
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+
+int fake_drs_calibration()
+{
+    DrsCalibration drscalib;
+    uint16_t fRoi = 300;
+    const string filename = "/fhgfs/groups/app/fact/mc_test/testingdrsfile/12bitADC/offsetMinus1850/test300samples.drs.fits";
+    uint16_t fNumTm = 0;
+    float baselineMean = -1850.0 * 2000.0/4096.0;
+    float baselineRms = 0;
+    float gainMean = 1907.35;
+    float gainRms = 0;
+    float triggerOffsetMean = 0;
+    float triggerOffsetRms = 0;
+    float triggerOffsetTmMean = 0;
+    float triggerOffsetTmRms = 0;
+
+    const size_t n = 1440*1024*4 + 1440*fRoi*2 + fNumTm*fRoi*2 + 3;
+    vector<float> vec;
+    vec.resize(n);
+
+    reinterpret_cast<uint32_t*>(vec.data())[0] = fRoi;
+    reinterpret_cast<uint32_t*>(vec.data())[1] = 1;
+    reinterpret_cast<uint32_t*>(vec.data())[2] = 2;
+    reinterpret_cast<uint32_t*>(vec.data())[3] = 3;
+
+    for (int i = 0 ; i < 1024*1440 ; i++)
+    {
+        vec.data()[i+4]             = baselineMean;
+        vec.data()[i+4+1*1024*1440] = baselineRms;
+        vec.data()[i+4+2*1024*1440] = gainMean;
+        vec.data()[i+4+3*1024*1440] = gainRms;
+    }
+    for (int i = 0 ; i < fRoi*1440 ; i++)
+    {
+        vec.data()[i+4+4*1024*1440]             = triggerOffsetMean;
+        vec.data()[i+4+4*1024*1440+1*fRoi*1440] = triggerOffsetRms;
+    }
+    for (int i = 0 ; i < fRoi*fNumTm ; i++)
+    {
+        vec.data()[i+4+2*1024*1440+2*fRoi*1440]             = triggerOffsetTmMean;
+        vec.data()[i+4+3*1024*1440+2*fRoi*1440+fRoi*fNumTm] = triggerOffsetTmRms;
+    }
+
+    drscalib.fRoi   = fRoi;
+    drscalib.fNumTm = fNumTm;
+    drscalib.fStep  = 2;
+
+    drscalib.fNumOffset = 1000;
+    drscalib.fNumGain   = 1000*1953125;
+    drscalib.fNumTrgOff = 1000;
+
+    drscalib.WriteFitsImp(filename,vec);
+
+    return 0;
+}
+
Index: branches/Mars_McMismatchStudy/macros/fact/plotBiasOffset.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/fact/plotBiasOffset.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/fact/plotBiasOffset.C	(revision 17960)
@@ -0,0 +1,58 @@
+void plotBiasOffset()
+{
+    PixelMap map;
+    if (!map.Read("/home/fact/operation/FACTmap111030.txt"))
+        return;
+
+    BiasMap bias;
+    if (!bias.Read("/home/fact/operation/GAPDmap_with_spare_module.txt"))
+        return;
+
+    MGeomCamFACT fact;
+
+    MHCamera h1(fact);
+    MHCamera h2(fact);
+    MHCamera h3(fact);
+    MHCamera h4(fact);
+
+    h1.SetName("Vnom [V]");
+    h2.SetName("Voff [V]");
+    h3.SetName("Vnom+Voff [DAC]");
+    h4.SetName("Voff [-0.12V/0.19V]");
+
+    h1.SetAllUsed();
+    h2.SetAllUsed();
+    h3.SetAllUsed();
+    h4.SetAllUsed();
+
+    for (int i=0; i<1440; i++)
+    {
+        // Get entry corresponding to pixel index
+        PixelMapEntry &pix = map.index(i);
+
+        // Get entry corresponding to pixel
+        BiasMapEntry &ch = bias.hv(pix);
+
+        h1.SetBinContent(i+1,  ch.Vnom); // Volt
+        h2.SetBinContent(i+1,  ch.Voff); // Volt
+        h3.SetBinContent(i+1, (ch.Vnom+ch.Voff)*4096/90.); // DAC counts
+        h4.SetBinContent(i+1,  ch.Voff); // Volt
+    }
+
+
+    TCanvas *c = new TCanvas;
+    c->Divide(2,2);
+
+    c->cd(1);
+    h1.DrawCopy();
+
+    c->cd(2);
+    h2.DrawCopy();
+
+    c->cd(3);
+    h3.DrawCopy();
+
+    c->cd(4);
+    h4.SetMinMax(-0.12, 0.19);
+    h4.DrawCopy();
+}
Index: branches/Mars_McMismatchStudy/macros/fact/plotlpsimple.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/fact/plotlpsimple.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/fact/plotlpsimple.C	(revision 17960)
@@ -0,0 +1,59 @@
+void plotlpsimple()
+{
+    MParList plist;
+
+    MDrsCalibration calib;
+    if (!calib.ReadFits("/loc_data/raw/2011/10/30/20111030_023.drs.fits"))
+        return;
+    plist.AddToList(&calib);
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MRawFitsRead read1;
+    read1.AddFile("/loc_data/raw/2011/10/30/20111030_028.fits");
+    read1.LoadMap("../FACT++/FACTmap111030.txt");
+    tlist.AddToList(&read1);
+
+    MGeomApply apply;
+    tlist.AddToList(&apply);
+
+    MDrsCalibApply drscal;
+    tlist.AddToList(&drscal);
+
+    MExtractTimeAndChargeSpline extractor;
+    extractor.SetRange(180, 240);   // 0, 1023
+    extractor.SetRiseTimeHiGain(13);
+    extractor.SetFallTimeHiGain(23);
+    extractor.SetChargeType(MExtralgoSpline::kIntegralRel); // 1.4V-1.8V   T=290
+    extractor.SetSaturationLimit(600000);
+    extractor.SetNoiseCalculation(kFALSE);
+    tlist.AddToList(&extractor);
+
+    MHCamEvent evt2(0, "Extra'd", "Extracted Calibration Signal;;S [cnts/sl]");
+    MHCamEvent evt9(4, "ArrTm",   "Extracted ArrivalTime;;T");
+
+    MHSectorVsTime histrms;
+    MHSectorVsTime histtm;
+    histrms.SetTitle("Pulser Amplitude (maximum extracted with spline);;Amplitude [mV]");
+    histrms.SetType(0);
+    histtm.SetTitle("Pulser arrival bin (leading edge extracted with spline);;Arrival time [slice]");
+    histtm.SetType(0);
+
+    MFillH fill2(&evt2,      "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill9(&evt9,      "MArrivalTimeCam",     "FillArrivalTime");
+    MFillH fillrms(&histrms, "MExtractedSignalCam", "FillAmplVsTime");
+    MFillH filltm(&histtm,   "MArrivalTimeCam",     "FillATVsTime");
+
+    tlist.AddToList(&fill2);
+    tlist.AddToList(&fill9);
+    tlist.AddToList(&fillrms);
+    tlist.AddToList(&filltm);
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MEvtLoop loop;
+    loop.SetParList(&plist);
+    loop.SetDisplay(d);
+    loop.Eventloop();
+}
Index: branches/Mars_McMismatchStudy/macros/fact/ratescan.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/fact/ratescan.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/fact/ratescan.C	(revision 17960)
@@ -0,0 +1,293 @@
+MStatusDisplay *d = new MStatusDisplay;
+TList list[201];
+
+void Fit(TGraph &g, double rate_start=3e6, double rate_kink=100, double rate_end=10)
+{
+
+    double begin = -1;
+    double end   = -1;
+
+    double kinkx = -1;
+    double kinky =  0;
+
+    TGraph gl;
+    for (int j=0; j<g.GetN(); j++)
+    {
+        gl.SetPoint(gl.GetN(), g.GetX()[j], log10(g.GetY()[j]));
+        if (g.GetY()[j]<rate_start && begin<0)
+            begin = g.GetX()[j];
+        if (g.GetY()[j]<rate_end && end<0)
+            end = g.GetX()[j];
+        if (g.GetY()[j]<rate_kink && kinkx<0)
+        {
+            kinkx = g.GetX()[j];
+            kinky = g.GetY()[j];
+        }
+    }
+
+    TF1 func2("f2", "log10("
+              "  [1]*exp([2]*(x-[0]))"
+              "+ [1]*exp([3]*(x-[0]))"
+              //"+ [4]*exp([5]*(x-700))"
+              ")", begin, end);
+
+    Double_t v00 = g.Eval(kinkx-150, 0, "S");
+    Double_t v01 = g.Eval(kinkx- 50, 0, "S");
+
+    Double_t v10 = g.Eval(kinkx+100, 0, "S");
+    Double_t v11 = g.Eval(kinkx+200, 0, "S");
+
+    //Double_t v20 = g.Eval(700-50, 0, "S");
+    //Double_t v21 = g.Eval(700,    0, "S");
+    //Double_t v22 = g.Eval(700+50, 0, "S");
+
+    func2.SetParameter(0,  kinkx);
+    func2.SetParameter(1,  kinky);
+    func2.SetParameter(2,  log(v01/v00)/100);
+    func2.SetParameter(3,  log(v11/v10)/100);
+
+    func2.FixParameter(4,  0);
+    func2.FixParameter(5,  0);
+    func2.SetLineWidth(1);
+    func2.SetLineColor(kBlue);
+
+    gl.Fit(&func2, "N0", "", begin, end);
+
+    TF1 func("f1",
+             "[0]*exp([1]*(x-[6])) + "
+             "[2]*exp([3]*(x-[6])) + "
+             "[4]*exp([5]*(x-700))", begin, end);
+    func.FixParameter(0,  func2.GetParameter(1));
+    func.FixParameter(1,  func2.GetParameter(2));
+    func.FixParameter(2,  func2.GetParameter(1));
+    func.FixParameter(3,  func2.GetParameter(3));
+    func.FixParameter(4,  func2.GetParameter(4));
+    func.FixParameter(5,  func2.GetParameter(5));
+    func.FixParameter(6,  func2.GetParameter(0));
+    func.SetLineWidth(2);
+    func.SetLineColor(kBlue);
+    func.DrawClone("same");
+    func.SetLineWidth(1);
+
+    func.SetLineStyle(kDashed);
+    func.SetRange(0, 1000);
+
+    func.FixParameter(0,  0);
+    func.FixParameter(2,  0);
+    func.FixParameter(4,  func2.GetParameter(4));
+    func.DrawClone("same");
+
+    func.FixParameter(0,  func2.GetParameter(1));
+    func.FixParameter(2,  0);
+    func.FixParameter(4,  0);
+    func.DrawClone("same");
+
+    func.FixParameter(0,  0);
+    func.FixParameter(2,  func2.GetParameter(1));
+    func.FixParameter(4,  0);
+    func.DrawClone("same");
+
+
+    TLatex txt;
+    txt.SetTextColor(kBlue);
+    txt.SetTextAlign(33);
+    txt.DrawLatex(func2.GetParameter(0), func2.GetParameter(1),
+                  Form("%.1fHz @ %.0f", func2.GetParameter(1), func2.GetParameter(0)));
+
+    // [1]*exp([2]*(x-[0])) / exp(1)           = [1]*exp([3]*(x-[0]))
+    //     exp([2]*(x-[0])) / exp(1)           =    exp([3]*(x-[0]))
+    //     exp([2]*(x-[0])) / exp([3]*(x-[0])) =    exp(1)
+    //     exp([2]*(x-[0])  -     [3]*(x-[0])) =    exp(1)
+    //         [2]*(x-[0])  -     [3]*(x-[0])  =    1
+    //
+    // x = 1/([2]-[3]) + [0]
+
+
+    Double_t th   = 1. / (func2.GetParameter(3)-func2.GetParameter(2)) + func2.GetParameter(0);
+    Double_t rate = pow(10, func2.Eval(th));
+
+    txt.SetTextAlign(11);
+    txt.DrawLatex(th+10, rate, Form("%.1fHz @ %.0f", rate, th));
+
+    txt.SetTextAlign(12);
+    txt.DrawLatex(180, 3e6, Form("%.1f", 1./func2.GetParameter(2)));
+    txt.DrawLatex(350,   3, Form("%.0f", 1./func2.GetParameter(3)));
+
+    TLine line;
+    line.SetLineStyle(kDashed);
+    line.SetLineColor(kBlue);
+    line.DrawLine(th, 1e-2, th, 1e8);
+
+}
+
+void plot(const char *tab, const char *title="")
+{
+    gROOT->SetSelectedPad(0);
+    d->AddTab(tab);
+
+    gPad->SetGrid();
+    gPad->SetLogy();
+
+    TH1D h0("frame", title, 1000, 0, 1000);
+    h0.SetStats(kFALSE);
+    h0.SetXTitle("Threshold [dac]");
+    h0.SetYTitle("Trigger rate [Hz]");
+    h0.SetDirectory(0);
+    h0.SetMaximum(1e8);
+    h0.SetMinimum(0.01);
+    h0.DrawCopy();
+}
+
+
+void same(const char *id, const char *fmt, bool fit=true, bool boards=false, bool patches=false)
+{
+    for (int i=0; i<160; i++)
+    {
+        TGraph *g = (TGraph*)list[i+41].FindObject(id);
+        if (!g)
+        {
+            cout << "==W==> " << id << " not found in i=" << i+41 << endl;
+            return;
+        }
+
+        g->SetMarkerStyle(kFullDotSmall);
+        g->SetMarkerColor(kGray+1);
+        g->SetLineColor(kGray+1);
+        if (patches)
+            g->DrawClone(fmt);
+
+        if (g->Eval(400)>10)
+            cout << "Patch " << setw(3) << i << ": C" << i/40 << " B" << (i%40)/4 << " P" << (i%40)%4 << ": " << g->Eval(400) << "Hz @ th=400" << endl;
+    }
+
+    for (int i=0; i<40; i++)
+    {
+        TGraph *g = (TGraph*)list[i+1].FindObject(id);
+        if (!g)
+        {
+            cout << "==W==> " << id << " not found in i=" << i+1 << endl;
+            return;
+        }
+
+        g->SetMarkerStyle(kFullDotSmall);
+        g->SetMarkerColor(kGray+2);
+        g->SetLineColor(kGray+2);
+        if (boards)
+            g->DrawClone(fmt);
+
+        if (g->Eval(400)>10)
+            cout << "Board " << setw(3) << i << ": C" << i/10 << " B" << i%10 << ":    " << g->Eval(400) << "Hz @ th=400" << endl;
+    }
+
+
+    TGraph *g001 = (TGraph*)list[0].FindObject(id);
+    if (!g001)
+    {
+        cout << "==W==> " << id << " not found in i=0" << endl;
+        return;
+    }
+
+    g001->SetMarkerStyle(boards||patches?kFullDotMedium:kFullDotSmall);
+    g001->DrawClone(fmt);
+
+    if (fit)
+        Fit(*g001);
+}
+
+void read(const char *filename)
+{
+    fits fin(filename);
+    if (!fin)
+        return;
+
+    cout << '\n' << filename << '\n';
+    cout << setfill('-') <<setw(strlen(filename)) << '-' << setfill(' ') << endl;
+
+    //fin.PrintColumns();
+
+    ULong64_t start;
+    UInt_t    threshold;
+    Float_t   time;
+    Float_t   ontime;
+    Float_t   Rc;
+    Float_t   Rb[40];
+    Float_t   Rp[160];
+
+    fin.SetPtrAddress("Data0", &start);
+    fin.SetPtrAddress("Data1", &threshold);
+    fin.SetPtrAddress("Data2", &time);
+    fin.SetPtrAddress("Data3", &ontime);
+    fin.SetPtrAddress("Data4", &Rc);
+    fin.SetPtrAddress("Data5", Rb);
+    fin.SetPtrAddress("Data6", Rp);
+
+    ULong_t first = 0;
+
+    TGraph *g[201];
+
+    while (fin.GetNextRow())
+    {
+        if (first==0 || first!=start)
+        {
+            first = start;
+
+            MTime t;
+            t.SetUnixTime(start);
+
+            TString name = t.GetString();
+            name = name(0, 19);
+
+            cout << name << endl;
+
+            for (int i=0; i<201; i++)
+            {
+                g[i] = new TGraph;
+                g[i]->SetMarkerStyle(kFullDotMedium);
+                g[i]->SetName(name);
+                g[i]->SetTitle(t.GetStringFmt("%H:%M:%S"));
+
+                list[i].Add(g[i]);
+            }
+        }
+
+        g[0]->SetPoint(g[0]->GetN(), threshold, Rc/ontime);
+        for (int i=0; i<40; i++)
+            g[i+1]->SetPoint(g[i+1]->GetN(), threshold, Rb[i]);
+        for (int i=0; i<160; i++)
+            g[i+41]->SetPoint(g[i+41]->GetN(), threshold, Rp[i]);
+    }
+}
+
+void ratescan()
+{
+    cout << setprecision(4);
+
+    // Read three files
+    read("/loc_data/aux/2012/02/18/20120218.RATE_SCAN_DATA.fits");
+    read("/loc_data/aux/2012/02/19/20120219.RATE_SCAN_DATA.fits");
+    read("/loc_data/aux/2012/02/21/20120221.RATE_SCAN_DATA.fits");
+
+    // add a new tab
+    plot("0.0V", "Temp control 19.02./22.02. (+0V)");
+
+    // Plot a curve, do not fit
+    same("19.02.2012 20:21:26", "LP", false);
+
+    // plot a curve, fit and plot boards
+    same("22.02.2012 04:19:15", "LP", true, true);
+
+    // raed another file
+    read("/loc_data/aux/2012/03/25/20120325.RATE_SCAN_DATA.fits");
+
+    // add another tab
+    plot("25/03", "Current control 25.03. (+0V)");
+
+    // plot curve, fit and plot boards and patches
+    same("26.03.2012 03:01:14", "LP", true, true, true);
+
+    // plot curve, do not fit, do not draw boards and patches
+    same("26.03.2012 03:21:47", "LP", false);
+
+    // write result to output file
+    d->SaveAs("/home/tbretz/ratescan.root");
+}
Index: branches/Mars_McMismatchStudy/macros/fact/underflow.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/fact/underflow.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/fact/underflow.C	(revision 17960)
@@ -0,0 +1,60 @@
+int underflow(const char *filename="/raid10/raw/2013/06/21/20130621_062.fits", const char *outname="underflow-check.root")
+{
+    // The input file must be a drs-gain file
+    // The return value is
+    //  0) Success
+    //  1) Underflow detected
+    //  3) Event loop stopped
+    //  4) Display closed
+    // ======================================================
+
+    gLog.Separator("Underflow check");
+
+    // ------------------------------------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MEvtLoop loop;
+    loop.SetParList(&plist);
+    loop.SetDisplay(d);
+
+    // --------------------------------------------------------
+
+    MRawFitsRead read1(filename);
+
+    MGeomApply apply;
+
+    tlist.AddToList(&read1);
+    tlist.AddToList(&apply);
+
+    MHDrsCalibration hcalib;
+
+    MFillH fill(&hcalib);
+    fill.SetNameTab("Check");
+
+    tlist.AddToList(&fill);
+
+    if (!loop.Eventloop())
+        return 3;
+
+    if (!loop.GetDisplay())
+        return 4;
+
+    // --------------------------------------------------------
+
+    TString title = "--  Underflow check ";
+    title += " (";
+    title += filename;
+    title += ")  --";
+    d->SetTitle(title, kFALSE);
+    d->SaveAs(outname);
+
+    // --------------------------------------------------------
+
+    return hcalib.GetNumUnderflows(1.3)>0 ? 1 : 0;
+}
Index: branches/Mars_McMismatchStudy/macros/libnova/sun.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/libnova/sun.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/libnova/sun.C	(revision 17960)
@@ -0,0 +1,42 @@
+void sun()
+{
+    TGraph gr, gs;
+
+    MTime t(MTime(-1).Year(), 01, 01, 00);
+
+    const double jd = t.GetJD();
+    const double at = t.GetAxisTime();
+
+    for (int d=0; d<365; d++)
+    {
+        Nova::RstTime sun_day = Nova::GetSolarRst(jd+d);
+
+        gr.SetPoint(gr.GetN(), at+d*24*3600, (fmod(sun_day.rise, 1)-0.5)*24*3600+at);
+        gs.SetPoint(gs.GetN(), at+d*24*3600, (fmod(sun_day.set,  1)+0.5)*24*3600+at);
+    }
+
+    TH1S h("", "", 12*60, at+2*24*3600, at+365*24*3600);
+    h.SetStats(kFALSE);
+    h.SetMinimum(at);
+    h.SetMaximum(at+24*3600);
+
+    h.GetXaxis()->CenterLabels();
+    h.GetXaxis()->CenterTitle();
+    h.GetXaxis()->SetNdivisions(412, kFALSE);  // 4 weeks per month, 12 months per year
+    h.GetXaxis()->SetTitle("Month");
+    h.GetXaxis()->SetTimeDisplay(true);
+    h.GetXaxis()->SetTimeFormat("%m %F1995-01-01 00:00:00 GMT");
+
+    h.GetYaxis()->SetTitle("UTC");
+    h.GetYaxis()->SetNdivisions(412, kFALSE);  // 12 'hours' ticks every 15min.
+    h.GetYaxis()->SetTitleOffset(1.4);
+    h.GetYaxis()->SetTimeDisplay(true);
+    h.GetYaxis()->SetTimeFormat("%Hh %F1995-01-01 00:00:00 GMT");
+
+    h.DrawCopy();
+
+    gPad->SetGrid();
+
+    gr.DrawClone("P");
+    gs.DrawClone("P");
+}
Index: branches/Mars_McMismatchStudy/macros/mccalibrate.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/mccalibrate.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/mccalibrate.C	(revision 17960)
@@ -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): Abelardo Moralejo 1/2004 <mailto:moralejo@pd.infn.it>
+   !              Thomas Bretz  5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2004
+   !
+   !
+   \* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMCALIBRATE - Calibration of MC data
+//
+//  This macro converts raw MC data into calibrated data (photons per pixel) 
+//  It optionally divides the output into a train and a test sample
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MImgCleanStd.h"
+
+void mccalibrate()
+{
+  //
+  // This macro reads in MC camera files and produces and output with 
+  // calibrated events (signal in photons for all pixels, in MCerPhotEvt 
+  // containers).
+  //
+
+  // ------------- user change -----------------
+  TString* CalibrationFilename;
+
+  CalibrationFilename = new TString("/users/emc/moralejo/mcdata/Period021_0.73_mirror/gammas_nonoise/Gamma_*root");  // File to be used for the calibration (must be a camera file without added noise)
+
+  Char_t* AnalysisFilename = "Gamma_zbin*w0.root";  // File to be analyzed
+
+
+  TString* OutFilename1;
+  TString* OutFilename2;
+
+  // Output file names
+  OutFilename1 = new TString("calibrated_gamma_train.root");
+  OutFilename2 = new TString("calibrated_gamma_test.root"); 
+
+  // To get only one output file, just comment out the second 
+  // one of the above lines
+
+
+  //
+  //  USER CHANGE: Set signal extractor
+  //
+  //    MExtractFixedWindowPeakSearch sigextract;
+  //    sigextract.SetWindows(6, 6, 4);
+  //
+
+  //    MExtractTimeAndChargeDigitalFilter sigextract;
+  //    sigextract.SetNameWeightsFile("/users/emc/moralejo/Mars/msignal/MC_weights.dat");
+  //    sigextract.SetRange(1, 14, 3, 14);
+
+  MExtractTimeAndChargeSpline sigextract;
+  sigextract.SetRiseTimeHiGain(0.5);
+  sigextract.SetFallTimeHiGain(0.5);
+
+
+  // USER CHANGE: high to low gain ratio. DEPENDS on EXTRACTOR!!
+  // One should calculate somewhere else what this factor is for each extractor!
+  Float_t hi2low = 12.; // tentative value for spline with risetime 0.5, fall time 0.5
+
+  MMcCalibrationUpdate  mccalibupdate;
+  mccalibupdate.SetUserLow2HiGainFactor(hi2low);
+  ///// User change: calibrate in photons or phe- :
+  mccalibupdate.SetSignalType(MCalibrateData::kPhe);
+  //  mccalibupdate.SetSignalType(MCalibrateData::kPhot);
+
+  // ---------------------------------------------------------------------
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  MBadPixelsCam badpix;
+  plist.AddToList(&badpix);  // Not used for now.
+ 
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+
+  if (CalibrationFilename)
+    read.AddFile(CalibrationFilename->Data());
+
+  read.DisableAutoScheme();
+
+  MGeomApply geom; 
+  // Reads in geometry from MC file and sets the right sizes for
+  // several parameter containers.
+
+  MMcPedestalCopy   pcopy; 
+  // Copies pedestal data from the MC file run fadc header to the 
+  // MPedestalCam container.
+
+  MPointingPosCalc pointcalc;
+  // Creates MPointingPos object and fills it with the telescope 
+  // orientation information taken from MMcEvt.
+
+  MCalibrateData calib; 
+  //
+  // MCalibrateData transforms signals from ADC counts into photons or phe-
+  // (this can be selected anove). In the first loop it applies a "dummy" 
+  // calibration supplied by MMcCalibrationUpdate, just to equalize inner 
+  // and outer pixels, and calculates SIZE in "equivalent number of inner 
+  // ADC counts". At the end of the first loop, in the PostProcess of 
+  // MMcCalibrationCalc (see below) the true calibration constants
+  // are calculated.
+  //
+  calib.SetCalibrationMode(MCalibrateData::kFfactor);
+  // Do not change the CalibrationMode above for MC...!
+
+  // Now set also whether to calibrate in photons or phe-:
+  calib.SetSignalType(mccalibupdate.GetSignalType());
+
+  MImgCleanStd clean;
+  //
+  // Applies tail cuts to image. Since the calibration is performed on 
+  // noiseless camera files, the precise values of the cleaning levels 
+  // are unimportant (in any case, only pixels without any C-photon will
+  // be rejected).
+  //
+
+  MHillasCalc hcalc; 
+  hcalc.Disable(MHillasCalc::kCalcHillasSrc);
+  // Calculates Hillas parameters not dependent on source position.
+
+  MMcCalibrationCalc mccalibcalc; 
+  // Calculates calibration constants to convert from ADC counts to photons.
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+
+  MF notrigger("MMcTrig.fNumFirstLevel<1");
+  MContinue skipnotrig(&notrigger);
+  tlist.AddToList(&skipnotrig);
+
+  tlist.AddToList(&pcopy);
+  tlist.AddToList(&pointcalc);
+  tlist.AddToList(&sigextract);
+  tlist.AddToList(&mccalibupdate);
+  tlist.AddToList(&calib);
+  tlist.AddToList(&clean);
+  tlist.AddToList(&hcalc);
+
+  tlist.AddToList(&mccalibcalc);
+
+  //
+  // Open output files:
+  //
+  MWriteRootFile write1(OutFilename1->Data()); // Writes output
+
+  MWriteRootFile write1_b(OutFilename1->Data());
+  write1_b.AddContainer("MMcEvtBasic", "OriginalMC", kFALSE);
+  // Add the MMcEvtBasic container only in case it exists in 
+  // the input camera files
+
+  write1.AddContainer("MGeomCam",            "RunHeaders");
+  write1.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write1.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write1.AddContainer("MMcFadcHeader",       "RunHeaders");
+  write1.AddContainer("MMcRunHeader",        "RunHeaders");
+  write1.AddContainer("MMcTrigHeader",       "RunHeaders");
+  write1.AddContainer("MRawRunHeader",       "RunHeaders");
+
+  write1.AddContainer("MMcEvt",        "Events");
+  write1.AddContainer("MMcTrig",       "Events");
+  write1.AddContainer("MPointingPos",  "Events");
+  write1.AddContainer("MRawEvtHeader", "Events");
+  write1.AddContainer("MCerPhotEvt",   "Events");
+  write1.AddContainer("MPedPhotCam",   "Events");
+
+  if (OutFilename2)
+    {
+      MWriteRootFile write2(OutFilename2->Data()); // Writes output    
+
+      MWriteRootFile write2_b(OutFilename2->Data());
+      write2_b.AddContainer("MMcEvtBasic", "OriginalMC", kFALSE);
+      // Add the MMcEvtBasic container only in case it exists in 
+      // the input camera files
+
+      write2.AddContainer("MGeomCam",            "RunHeaders");
+      write2.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+      write2.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+      write2.AddContainer("MMcFadcHeader",       "RunHeaders");
+      write2.AddContainer("MMcRunHeader",        "RunHeaders");
+      write2.AddContainer("MMcTrigHeader",       "RunHeaders");
+      write2.AddContainer("MRawRunHeader",       "RunHeaders");
+
+      write2.AddContainer("MMcEvt",        "Events");
+      write2.AddContainer("MMcTrig",       "Events");
+      write2.AddContainer("MPointingPos",  "Events");
+      write2.AddContainer("MRawEvtHeader", "Events");
+      write2.AddContainer("MCerPhotEvt",   "Events");
+      write2.AddContainer("MPedPhotCam",   "Events");
+
+      //
+      // Divide output in train and test samples, using the event number
+      // (odd/even) to achieve otherwise unbiased event samples:
+      //
+      MF filter1("{MMcEvt.fEvtNumber%2}>0.5");
+      MF filter2("{MMcEvt.fEvtNumber%2}<0.5");
+
+      write1.SetFilter(&filter1);
+      write2.SetFilter(&filter2);
+
+      write1_b.SetFilter(&filter1);
+      write2_b.SetFilter(&filter2);
+    }
+
+  //
+  // First loop: Calibration loop
+  //
+
+  MProgressBar bar;
+  bar.SetWindowName("Calibrating...");
+
+  MEvtLoop evtloop;
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (CalibrationFilename)
+    {
+      if (!evtloop.Eventloop())
+	return;
+      mccalibcalc->GetHistADC2PhotEl()->Write();
+      mccalibcalc->GetHistPhot2PhotEl()->Write();
+      // Writes out the histograms used for calibration. In case of
+      // aslit output in train and test file, this is written only
+      // in the test file for now.
+    }
+
+  //
+  // Second loop: apply calibration factors to MC events in the 
+  // file to be anlyzed:
+  //
+
+  //
+  // Change the read task by another one which reads the file we want to analyze:
+  //
+
+  MReadMarsFile read2("Events");
+  read2.AddFile(AnalysisFilename);
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read, "All");
+  tlist.RemoveFromList(&read);
+
+  // Now add tasks to write MMcEvtBasic to the OriginalMC tree:
+  tlist.AddToListBefore(&write1_b, &skipnotrig, "All");
+  if (OutFilename2)
+    tlist.AddToListBefore(&write2_b, &skipnotrig, "All");
+
+
+  if (OutFilename2) // Add filters to split output in train and test
+    {
+      tlist.AddToListBefore(&filter1, &write1_b, "All");
+      tlist.AddToListBefore(&filter2, &write1_b, "All");
+    }
+
+  bar.SetWindowName("Writing...");
+
+  tlist.RemoveFromList(&clean);
+  tlist.RemoveFromList(&hcalc);
+  tlist.RemoveFromList(&mccalibcalc);
+
+  tlist.AddToList(&write1);
+
+  if (OutFilename2)
+    tlist.AddToList(&write2); 
+  // Add tasks to write the Events and RunHeaders trees to output.
+
+  if (!evtloop.Eventloop())
+    return;
+
+
+  tlist.PrintStatistics();
+}
Index: branches/Mars_McMismatchStudy/macros/mergecamera.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/mergecamera.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/mergecamera.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/merpp.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/merpp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/merpp.C	(revision 17960)
@@ -0,0 +1,103 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// merpp.C
+// =======
+//
+// This is an easy implementation of the Merging process (as root Macro)
+//
+// at the moment it reads a binary file ("rawtest.raw") which was written
+// in the DAQ raw format.
+//
+// The data are stored in root container objects (classes derived from
+// TObject like MRawRunHeader)
+//
+// This containers are written to a root file ("rawtest.root")
+//
+// It also demonstrates how you can loop over files in a single or more
+// than one directory and process them. For details see MRunIter.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void ProcessFile(TString fname)
+{
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MTaskList tasks;
+    MParList plist;
+
+    plist.AddToList(&tasks);
+
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    // REMARK: Don't change the order of the two instantiations.
+    //         I don't have an idea why, but here it crashes the
+    //         Interpreter.
+    //         (Using root 2.25/03, with Cint 5.14.50 on OSF1)
+    //
+    MRawFileRead  reader(fname);
+    MRawFileWrite writer(fname(0, fname.Last('.')+1) + "root", "RECREATE", fname, 1);
+    tasks.AddToList(&reader);
+    tasks.AddToList(&writer);
+
+    //
+    // create the looping object and thell it about the parameters to use
+    // and the tasks to execute
+    //
+    MEvtLoop magic;
+
+    magic.SetParList(&plist);
+
+    //
+    // Start the eventloop which reads the raw file (MRawFileRead) and
+    // write all the information into a root file (MRawFileWrite)
+    //
+    // between reading and writing we can do, transformations, checks, etc.
+    // (I'm think of a task like MRawDataCheck)
+    //
+    magic.Eventloop();
+}
+
+void merpp(const char *dirname="/home/MAGIC/online_data/rawdata/")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "*.raw", -1);
+
+    while (1)
+    {
+        TString fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+    }
+}
+
Index: branches/Mars_McMismatchStudy/macros/multidimdist.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/multidimdist.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/multidimdist.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/multidimdist2.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/multidimdist2.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/multidimdist2.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/optPad.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/optPad.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/optPad.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/optim/optimcrab.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/optim/optimcrab.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/optim/optimcrab.C	(revision 17960)
@@ -0,0 +1,71 @@
+void optimcrab()
+{
+    MJOptimize opt;
+    opt.SetDebug(2);
+    opt.SetOptimizer(MJOptimize::kSimplex);
+
+    // ---------------------------------------------------
+
+    opt.FixParameter(0,  -0.10011,   -5, 5);
+    opt.FixParameter(1,   0.0669669,  -5, 5);
+
+    opt.FixParameter(2,   0.923,  -5,5);
+    opt.FixParameter(3,  -0.8900478,  -5, 5);
+
+    opt.FixParameter(4,   0.215533, -5, 5);
+
+    // ---------------------------------------------------
+    opt.FixParameter(5,   0.106519,  -1, 1);
+    opt.FixParameter(6,   0.5);
+    // --------------------ALPHA--------------------------
+
+    opt.FixParameter(7,   2.13579,   0, 20);
+    opt.FixParameter(8,   4.78171,   0, 20);
+    opt.FixParameter(9,   1.17461,   0, 20);
+    // ---------------------AREA--------------------------
+
+    opt.FixParameter(10,  0.263628,  0, 20);
+    opt.FixParameter(11,  5.25951,   0, 20);
+    opt.FixParameter(12,  0.111246,  0, 20);
+    // --------------------D1/D2--------------------------
+
+    opt.FixParameter(13,  0.188982,   0, 20);
+    opt.FixParameter(14,  1.10405,    0, 20);
+
+    opt.FixParameter(15,  0.0960984,  0, 10);
+    opt.FixParameter(16,  0.0991635,  0, 10);
+
+    opt.FixParameter(17,  0, -10, 10);
+    opt.FixParameter(18,  0, -10, 10);
+    // --------------------MD1/MD2--------------------------
+
+    opt.SetParameter(20,  0.4, -10, 10);
+    opt.FixParameter(21,  0,   -10, 10);
+    opt.SetParameter(22,  1.0, -10, 10);
+    opt.FixParameter(23,  0,   -10, 10);
+
+    opt.SetParameter(24, -1,   -10, 10);
+    opt.FixParameter(25,  0,   -10, 10);
+    opt.FixParameter(26,  0,   -10, 10);
+
+    // S=14.7, E=485, B=285
+    // ---------------------------------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    MAlphaFitter fit;
+    fit.SetScaleMode(MAlphaFitter::kNone);
+    fit.SetSignalIntegralMax(99);
+    //fit.SetMinimizationStrategy(MAlphaFitter::kExcess);
+    fit.SetMinimizationStrategy(MAlphaFitter::kSignificanceLogExcess);
+    //fit.SetMinimizationStrategy(MAlphaFitter::kSignificance);
+
+    // A88A
+    // DIST vs. atan(width/w, length/l)
+    // Image cleaning with AT to get better size! (IMPORTANCE: E-est!)
+
+    MFMagicCuts cuts;
+    cuts.SetAlphaCut(MFMagicCuts::kWobble);
+    opt.RunOnOff("wobblelza-abs.root", &cuts, &fit);
+}
Index: branches/Mars_McMismatchStudy/macros/optim/optimdisp.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/optim/optimdisp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/optim/optimdisp.C	(revision 17960)
@@ -0,0 +1,84 @@
+/* More explanations at the end of the file */
+void optimdisp()
+{
+    MJOptimizeDisp opt;                     // Initialize optimization class
+    opt.SetDebug(2);                        // Choose the level of output
+    opt.SetOptimizer(MJOptimize::kMigrad);  // Choose the fit algorithm (see MJOptimize)
+    opt.EnableTestTrain();                  // Split sample into test and train
+
+    // -------------------- Setup ----------------------------
+
+    opt.AddParameter("1-MHillas.fWidth/MHillas.fLength");   // M[0]
+    opt.AddParameter("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg"); // M[1]
+    opt.AddParameter("MNewImagePar.fLeakage1");             // M[2]
+    opt.AddParameter("log10(MHillas.fSize)");               // M[3]
+
+    // -------------- Parametrization --------------------
+
+    char *r = "M[0]*([0] + [1]*M[1] + [2]*M[2] + (M[3]>[3])*[4]*(M[3]-[3])^2)";
+
+    opt.FixParameter(0, 1.15136);
+    opt.FixParameter(1, 0.0681437);
+    opt.FixParameter(2, 2.62932);
+    opt.FixParameter(3, 1.51279);
+    opt.FixParameter(4, 0.0507821);
+
+    opt.AddPreCut("MNewImagePar.fLeakage1>0");
+    //opt.AddPreCut("log10(MHillas.fSize)<2.5"); //3.2
+
+    opt.AddPreCut("MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)*MGeomCam.fConvMm2Deg>-0.07");
+    opt.AddPreCut("DataType.fVal>0.5");
+
+    //opt.AddPreCut("abs(MHillasSrc.fDCA*MGeomCam.fConvMm2Deg)<0.2");
+    //opt.AddPreCut("(MHillasSrc.fDist*MGeomCam.fConvMm2Deg-0.5)*7.2>MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg");
+
+    // -------------------- Run ----------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    /*
+     -------------------- Magic-Cuts ----------------------
+     MFMagicCuts cuts;
+     cuts.SetHadronnessCut(MFMagicCuts::kArea);
+     cuts.SetThetaCut(MFMagicCuts::kNone);
+
+     TArrayD arr(10);
+     arr[0]=  1.3245;
+     arr[1]=  0.208700;
+     arr[2]=  0.0836169;
+     arr[3]=  5.63973;
+     arr[4]=  0.0844195;
+     arr[5]= -0.07;
+     arr[6]=  13.2;
+     arr[7]=  1.0;
+     arr[8]=  7.2;
+     arr[9]=  0.5;
+
+     cuts.SetVariables(arr);
+
+     opt.AddPreCut(&cuts);
+
+     -------------------- Energy Slope --------------------
+     MFEnergySlope slope(-2.8);
+     opt.AddPreCut(&slope);
+
+     -------------------- Other cuts ----------------------
+     */
+
+    // opt.SetPathOut("optimdisp.root");
+    opt.RunDisp("ganymed00000001-summary.root", r);
+}
+
+/* ------------------ Good strategy -------------------
+
+   Par  |   0    1     2      3     4     |  Cut
+ -------+---------------------------------+-----------------------
+  Fit 1 |  1.3  0.1  fix=0  fix=0  fix=0  | Leak1==0 lgSize<2.5
+  Fit 2 |  fix  fix  fix=0   2.5    0.2   | Leak1==0
+  Fit 2 |  fix  fix   1.8    fix    fix   | Leak1>0
+  Fit 3 |  free free  fix    fix    fix   | -/-
+  Fit 4 |  fix  fix   fix    free   free  | -/-
+  Fit 5 |  fix  fix   free   fix    fix   | -/-
+ -------+---------------------------------+-----------------------
+*/
Index: branches/Mars_McMismatchStudy/macros/optim/optimenergy.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/optim/optimenergy.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/optim/optimenergy.C	(revision 17960)
@@ -0,0 +1,50 @@
+void optimenergy()
+{
+    MJOptimizeEnergy opt;
+    opt.SetDebug(2);
+    opt.SetOptimizer(MJOptimize::kMigrad);
+    opt.EnableTestTrain();
+
+    // -------------------- Setup ----------------------------
+    opt.AddParameter("MHillas.fSize");
+
+    opt.FixParameter(0, 0.9, 0, 2);  //0.562676
+
+    char *r = "[0]*M[0]";
+
+    // -------------------- Run ----------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    /*
+     -------------------- Magic-Cuts ----------------------
+     MFMagicCuts cuts;
+     cuts.SetHadronnessCut(MFMagicCuts::kArea);
+     cuts.SetThetaCut(MFMagicCuts::kOn);
+
+     TArrayD arr(10);
+     arr[0]=  1.3245;
+     arr[1]=  0.208700;
+     arr[2]=  0.229200;
+     arr[3]=  5.305200;
+     arr[4]=  0.098930;
+     arr[5]= -0.082950;
+     arr[6]=  8.2957;
+     arr[7]=  0.8677;
+
+     cuts.SetVariables(arr);
+
+     opt.AddPreCut(&cuts);
+
+     -------------------- Energy Slope --------------------
+     MFEnergySlope slope(-2.8);
+     opt.AddPreCut(&slope);
+
+     -------------------- Other cuts ----------------------
+     opt.AddPreCut("MPointingPos.fZd<7");
+    */
+
+    // opt.SetPathOut("optimenergy.root");
+    opt.RunEnergy("ganymedmcpart.root", r);
+}
Index: branches/Mars_McMismatchStudy/macros/optim/optimonoff.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/optim/optimonoff.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/optim/optimonoff.C	(revision 17960)
@@ -0,0 +1,51 @@
+void optimonoff()
+{
+    MJOptimizeCuts opt("MHThetaSq");
+    opt.SetDebug(2);
+    opt.SetOptimizer(MJOptimize::kSimplex);
+
+    // ------------------- Xi -----------------------
+    opt.FixParameter( 0, 1.15136);
+    opt.FixParameter( 8, 0.0681437);
+    opt.FixParameter( 9, 2.62932);
+    opt.FixParameter(10, 1.51279);
+    opt.FixParameter(11, 0.0507821);
+                  
+    // --------------- Theta Sq ---------------------
+    opt.FixParameter( 1, 0.215);
+
+    // ----------------- Area -----------------------
+    opt.SetParameter( 2, 0.21);
+    opt.SetParameter( 3, 5.6);
+    opt.SetParameter( 4, 0.083);
+
+    // ----------------- M3L ------------------------
+    opt.FixParameter( 5, -0.07);
+
+    // ---------------- Slope -----------------------
+    opt.FixParameter( 6, 7.2);
+    opt.FixParameter( 7, 0.5);
+
+    // ----------------- Fit ------------------------
+
+    MAlphaFitter fit;
+    fit.SetScaleMode(MAlphaFitter::kBackground);
+    fit.SetBackgroundFitMin(0.137);
+    fit.SetBackgroundFitMax(0.640);
+    fit.SetPolynomOrder(1);
+    fit.SetSignalFunction(MAlphaFitter::kThetaSq);
+    fit.SetMinimizationStrategy(MAlphaFitter::kSignificanceLogExcess);
+
+    // ----------------- Cuts -----------------------
+
+    MFMagicCuts cuts;
+    cuts.SetThetaCut(MFMagicCuts::kNone);
+
+    // ----------------------------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    // opt.SetPathOut("optimonoff.root");
+    opt.RunOnOff("ganymed00000001-summary.root", &cuts, &fit);
+}
Index: branches/Mars_McMismatchStudy/macros/optim/optimwobble.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/optim/optimwobble.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/optim/optimwobble.C	(revision 17960)
@@ -0,0 +1,60 @@
+void optimwobble()
+{
+    MJOptimizeCuts opt("MHThetaSq");
+    opt.SetDebug(2);
+    opt.SetOptimizer(MJOptimize::kSimplex);
+
+    // ------------------- Xi -----------------------
+    opt.FixParameter( 0, 1.15136);
+    opt.FixParameter( 8, 0.0681437);
+    opt.FixParameter( 9, 2.62932);
+    opt.FixParameter(10, 1.51279);
+    opt.FixParameter(11, 0.0507821);
+                  
+    // --------------- Theta Sq ---------------------
+    opt.FixParameter( 1, 0.215);
+
+    // ----------------- Area -----------------------
+    opt.SetParameter( 2, 0.21);
+    opt.SetParameter( 3, 5.6);
+    opt.SetParameter( 4, 0.083);
+
+    // ----------------- M3L ------------------------
+    opt.FixParameter( 5, -0.07);
+
+    // ---------------- Slope -----------------------
+    opt.FixParameter( 6, 7.2);
+    opt.FixParameter( 7, 0.5);
+
+    // ----------------- Fit ------------------------
+
+    MAlphaFitter fit;
+    fit.SetScaleMode(MAlphaFitter::kNone);
+    fit.SetSignalFunction(MAlphaFitter::kThetaSq);
+    fit.SetMinimizationStrategy(MAlphaFitter::kSignificanceLogExcess);
+
+    // For wobble mode with three off-regions
+    //  (sets also ScaleMode to kUser)
+    fit.SetScaleUser(1./3);
+
+    // ----------------- Cuts -----------------------
+
+    MFMagicCuts cuts;
+    cuts.SetThetaCut(MFMagicCuts::kOn);
+
+    /* You can also try (switch on scaling):
+
+     fit.SetScaleMode(MAlphaFitter::kBackground);
+     fit.SetBackgroundFitMin(0.12);
+     fit.SetBackgroundFitMax(0.5);
+
+     cuts.SetThetaCut(MFMagicCuts::kOff);
+     */
+
+    // -----------------------------------------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    opt.RunOnOff("ganymed00000001-summary.root", &cuts, &fit);
+}
Index: branches/Mars_McMismatchStudy/macros/optim/rfenergyest.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/optim/rfenergyest.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/optim/rfenergyest.C	(revision 17960)
@@ -0,0 +1,132 @@
+void rfenergyest()
+{
+    MSequence seqtst("~/Software/mc/sequencemc-test.txt");
+    MSequence seqtrn("~/Software/mc/sequencemc-train.txt");
+
+    if (!seqtst.IsValid())
+    {
+        cout << "Test sequence not valid" << endl;
+        return;
+    }
+    if (!seqtrn.IsValid())
+    {
+        cout << "Train sequence not valid" << endl;
+        return;
+    }
+
+    // --------------------- Setup files --------------------
+    MReadMarsFile read("Events");
+    MReadMarsFile read2("Events");
+    read.DisableAutoScheme();
+    read2.DisableAutoScheme();
+
+    MDirIter iter, iter2;
+    seqtrn.SetupDatRuns(iter,  MSequence::kImages, "~/Software/mc/img-abs");
+    seqtst.SetupDatRuns(iter2, MSequence::kImages, "~/Software/mc/img-abs");
+
+    read.AddFiles(iter);
+    read2.AddFiles(iter2);
+
+    // ----------------------- Setup RF ----------------------
+    MHMatrix train("Train");
+    train.AddColumn("MHillas.fSize");
+    train.AddColumn("MHillasSrc.fDist");
+    train.AddColumn("MPointingPos.fZd");
+    /*
+     train.AddColumn("MImagePar.fSizeSinglePixels");
+     train.AddColumn("MHillas.GetArea");
+     train.AddColumn("MNewImagePar.fLeakage1");
+     train.AddColumn("MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)");
+     */
+
+    // ------------------------------------------------------------
+
+    // Last column must contain energy
+    train.AddColumn("MMcEvt.fImpact/100");
+    train.AddColumn("MMcEvt.fTelescopeTheta*kRad2Deg");
+    train.AddColumn("MMcEvt.fEnergy");
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // ----------------------- Fill Matrix RF ----------------------
+
+    if(gRandom)
+        delete gRandom;
+    gRandom = new TRandom3();
+
+    MTFillMatrix fill;
+    fill.SetDisplay(d);
+    fill.SetDestMatrix1(&train, 10000);//99999999);
+    fill.SetReader(&read);
+
+    /* ---------- It doesn't seem to improve anything ----------
+     MFMagicCuts cuts;
+
+     cuts.SetHadronnessCut(MFMagicCuts::kArea);
+     cuts.SetThetaCut(MFMagicCuts::kOn);
+
+     TArrayD arr(10);
+     arr[0]=  1.3245;
+     arr[1]=  0.208700;
+     arr[2]=  0.229200;
+     arr[3]=  5.305200;
+     arr[4]=  0.098930;
+     arr[5]= -0.082950;
+     arr[6]=  8.2957;
+     arr[7]=  0.8677;
+
+     cuts.SetVariables(arr);
+
+     fill.AddPreCut(&cuts);
+
+     --------------- Use the cuts also in test-loop ----------------
+     */
+
+    if (!fill.Process())
+        return;
+
+    // ------------------------ Train RF --------------------------
+
+    MRFEnergyEst rf;
+    rf.SetDisplay(d);
+    rf.SetFileName("rfenergys.root");
+
+    MBinning b(32, 10, 100000, "BinningEnergyEst", "log");
+    /*
+    if (!rf.TrainMultiRF(train, b.GetEdgesD()))    // classification with one tree per bin
+        return;
+
+    if (!rf.TrainSingleRF(train, b.GetEdgesD()))   // classification into different bins
+        return;
+    */
+    if (!rf.TrainSingleRF(train))                  // regression (best choice)
+        return;
+
+
+    gLog.Separator("Test");
+
+    // --------------------- Display result ----------------------
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    plist.AddToList(&b);
+
+    MHEnergyEst hist;
+    //MContinue cont(&cuts);
+    //cont.SetInverted();
+    MFillH fillh(&hist);
+
+    tlist.AddToList(&read2);
+    //tlist.AddToList(&cont);
+    tlist.AddToList(&rf);
+    tlist.AddToList(&fillh);
+
+    MEvtLoop loop;
+    loop.SetDisplay(d);
+    loop.SetParList(&plist);
+
+    if (!loop.Eventloop())
+        return;
+
+    //d->SaveAsPS("rfenergys.ps");
+}
Index: branches/Mars_McMismatchStudy/macros/pedestalstudies.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/pedestalstudies.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/pedestalstudies.C	(revision 17960)
@@ -0,0 +1,504 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+// pedestalstudies.C
+//
+// macro to study the pedestal and pedestalRMS with the number of FADC 
+// slices summed up. 
+//
+/////////////////////////////////////////////////////////////////////////////////
+const TString pedfile = "./20040303_20123_P_NewCalBoxTestLidOpen_E.root";
+
+void pedestalstudies(const TString pedname=pedfile)
+{
+
+  Int_t loops = 13;
+  Int_t stepsize = 2;
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+  
+  TArrayF *hmeandiffinn = new TArrayF(loops);
+  TArrayF *hrmsdiffinn  = new TArrayF(loops);
+  TArrayF *hmeandiffout = new TArrayF(loops);
+  TArrayF *hrmsdiffout  = new TArrayF(loops);
+  TArrayF *hmeaninn  = new TArrayF(loops);
+  TArrayF *hmeanout  = new TArrayF(loops);
+  TArrayF *hrmsinn   = new TArrayF(loops);
+  TArrayF *hrmsout   = new TArrayF(loops);
+  TArrayF *hmuinn    = new TArrayF(loops);
+  TArrayF *hmuout    = new TArrayF(loops);
+  TArrayF *hsigmainn = new TArrayF(loops);
+  TArrayF *hsigmaout = new TArrayF(loops);
+
+  TArrayF *hmeandiffinnerr = new TArrayF(loops);
+  TArrayF *hrmsdiffinnerr  = new TArrayF(loops);
+  TArrayF *hmeandiffouterr = new TArrayF(loops);
+  TArrayF *hrmsdiffouterr  = new TArrayF(loops);
+  TArrayF *hmeaninnerr  = new TArrayF(loops);
+  TArrayF *hmeanouterr  = new TArrayF(loops);
+  TArrayF *hrmsinnerr   = new TArrayF(loops);
+  TArrayF *hrmsouterr   = new TArrayF(loops);
+  TArrayF *hmuinnerr    = new TArrayF(loops);
+  TArrayF *hmuouterr    = new TArrayF(loops);
+  TArrayF *hsigmainnerr = new TArrayF(loops);
+  TArrayF *hsigmaouterr = new TArrayF(loops);
+
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(500);
+  display->Resize(850,700);
+      
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  for (Int_t samples=2;samples<stepsize*loops+1;samples=samples+stepsize)
+    {
+
+      plist.Reset();
+      tlist.Reset();
+      
+      //
+      // Now setup the tasks and tasklist for the pedestals:
+      // ---------------------------------------------------
+      //
+      
+      MReadMarsFile read("Events", pedname);
+      read.DisableAutoScheme();
+      
+      MGeomApply      geomapl;
+      //
+      // Set the extraction range higher:
+      //		
+      MExtractFixedWindow sigcalc;
+      sigcalc.SetRange(0,samples-1,0,1);
+  
+      MPedCalcPedRun pedcalc;
+      pedcalc.SetRange(0,samples-1,0,0);
+      pedcalc.SetWindowSize((Int_t)sigcalc.GetNumHiGainSamples());
+
+      //
+      // Additionally to calculating the pedestals, 
+      // you can fill histograms and look at them
+      //
+      MFillH fill("MHPedestalCam", "MExtractedSignalCam");
+      fill.SetNameTab(Form("%s%2d","PedCam",samples));
+
+      tlist.AddToList(&read);
+      tlist.AddToList(&geomapl);
+      tlist.AddToList(&sigcalc);
+      tlist.AddToList(&pedcalc);
+      tlist.AddToList(&fill);
+      
+      MGeomCamMagic      geomcam;
+      MPedestalCam       pedcam;
+      MBadPixelsCam      badcam;
+      badcam.AsciiRead("badpixels.dat");  
+      
+      MHPedestalCam      hpedcam;
+      MCalibrationPedCam cpedcam;
+      
+      plist.AddToList(&geomcam);
+      plist.AddToList(&pedcam);
+      plist.AddToList(&hpedcam);
+      plist.AddToList(&cpedcam);
+      plist.AddToList(&badcam);
+      
+      //
+      // Create and setup the eventloop
+      //
+      MEvtLoop evtloop;
+      
+      evtloop.SetParList(&plist);
+      evtloop.SetDisplay(display);
+
+      //
+      // Execute first analysis
+      //
+      if (!evtloop.Eventloop())
+        return;
+      
+      // 
+      // Look at one specific pixel, after all the histogram manipulations:
+      //
+      /*
+      MHGausEvents &hpix = hpedcam.GetAverageHiGainArea(0);
+      hpix.DrawClone("fourierevents");
+      
+      MHGausEvents &lpix = hpedcam.GetAverageHiGainArea(1);
+      lpix.DrawClone("fourierevents");
+
+      hpedcam[170].DrawClone("fourierevents");
+  
+      */
+
+      MHCamera dispped0  (geomcam, "Ped;Pedestal",       "Mean per Slice");
+      MHCamera dispped2  (geomcam, "Ped;PedestalRms",    "RMS per Slice");
+      MHCamera dispped4  (geomcam, "Ped;Mean",           "Fitted Mean per Slice");
+      MHCamera dispped6  (geomcam, "Ped;Sigma",          "Fitted Sigma per Slice");
+      MHCamera dispped9  (geomcam, "Ped;DeltaPedMean",   "Rel. Diff. Mean per Slice (Fit-Calc.)");
+      MHCamera dispped11 (geomcam, "Ped;DeltaRmsSigma",  "Rel. Diff. RMS per Slice (Fit-Calc.)");
+  
+      dispped0.SetCamContent(  pedcam, 0);
+      dispped0.SetCamError(    pedcam, 1);
+      dispped2.SetCamContent(  pedcam, 2);
+      dispped2.SetCamError(    pedcam, 3);
+      
+      dispped4.SetCamContent( hpedcam, 0);
+      dispped4.SetCamError(   hpedcam, 1);
+      dispped6.SetCamContent( hpedcam, 2);
+      dispped6.SetCamError(   hpedcam, 3);
+      dispped9.SetCamContent( hpedcam, 5);
+      dispped9.SetCamError(   hpedcam, 6);
+      dispped11.SetCamContent(hpedcam, 8);
+      dispped11.SetCamError(  hpedcam, 9);
+  
+      dispped0.SetYTitle("Calc. Pedestal per slice [FADC counts]");
+      dispped2.SetYTitle("Calc. Pedestal RMS per slice [FADC counts]");
+      dispped4.SetYTitle("Fitted Mean per slice [FADC counts]");
+      dispped6.SetYTitle("Fitted Sigma per slice [FADC counts]");
+      dispped9.SetYTitle("Rel. Diff. Pedestal per slice Fit-Calc [1]");
+      dispped11.SetYTitle("Rel. Diff. Pedestal RMS per slice Fit-Calc [1]");
+
+
+      // Histogram values
+      TCanvas &b1 = display->AddTab(Form("%s%d","MeanRMS",samples));
+      b1.Divide(4,3);
+
+      CamDraw(b1,dispped0,1,4,*hmeaninn,*hmeanout,*hmeaninnerr,*hmeanouterr,samples,stepsize);
+      CamDraw(b1,dispped2,2,4,*hrmsinn,*hrmsout,*hrmsinnerr,*hrmsouterr,samples,stepsize);  
+      CamDraw(b1,dispped4,3,4,*hmuinn,*hmuout,*hmuinnerr,*hmuouterr,samples,stepsize);
+      CamDraw(b1,dispped6,4,4,*hsigmainn,*hsigmaout,*hsigmainnerr,*hsigmaouterr,samples,stepsize); 
+      
+      display->SaveAsGIF(3*((samples-1)/stepsize)+2,Form("%s%d","MeanRmsSamples",samples));
+
+      // Differences
+      TCanvas &c4 = display->AddTab(Form("%s%d","RelDiff",samples));
+      c4.Divide(2,3);
+      
+      CamDraw(c4,dispped9,1,2,*hmeandiffinn,*hmeandiffout,*hmeandiffinnerr,*hmeandiffouterr,samples,stepsize);
+      CamDraw(c4,dispped11,2,2,*hrmsdiffinn,*hrmsdiffout,*hrmsdiffinnerr,*hrmsdiffouterr,samples,stepsize); 
+
+      display->SaveAsGIF(3*((samples-1)/stepsize)+3,Form("%s%d","RelDiffSamples",samples));
+
+    }
+
+  /*
+  TF1 *logg = new TF1("logg","[1]+TMath::Log(x-[0])",1.,30.,2);
+  logg->SetParameters(1.,3.5);
+  logg->SetParLimits(0,-1.,3.);
+  logg->SetParLimits(1,-1.,7.);
+  logg->SetLineColor(kRed);
+  */
+
+  TCanvas *canvas = new TCanvas("PedstudInner","Pedestal Studies Inner Pixels",600,900);
+  canvas->Divide(2,3);
+  canvas->cd(1);
+
+  TGraphErrors *gmeaninn = new TGraphErrors(hmeaninn->GetSize(),
+                                            CreateXaxis(hmeaninn->GetSize(),stepsize),hmeaninn->GetArray(),
+                                            CreateXaxisErr(hmeaninnerr->GetSize(),stepsize),hmeaninnerr->GetArray());
+  gmeaninn->Draw("A*");
+  gmeaninn->SetTitle("Calculated Mean per Slice Inner Pixels");
+  gmeaninn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeaninn->GetYaxis()->SetTitle("Calculated Mean per slice");
+  //  gmeaninn->Fit("pol0");
+  //  gmeaninn->GetFunction("pol0")->SetLineColor(kGreen);
+  //  //  gmeaninn->Fit(logg);
+
+  canvas->cd(2);
+
+  TGraphErrors *gmuinn = new TGraphErrors(hmuinn->GetSize(),
+                                          CreateXaxis(hmuinn->GetSize(),stepsize),hmuinn->GetArray(),
+                                          CreateXaxisErr(hmuinnerr->GetSize(),stepsize),hmuinnerr->GetArray());
+  gmuinn->Draw("A*");
+  gmuinn->SetTitle("Fitted Mean per Slice Inner Pixels");
+  gmuinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmuinn->GetYaxis()->SetTitle("Fitted Mean per Slice");
+  //  gmuinn->Fit("pol0");
+  //  gmuinn->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmuinn->Fit(logg);
+
+
+  canvas->cd(3);
+
+  TGraphErrors *grmsinn = new TGraphErrors(hrmsinn->GetSize(),
+                                           CreateXaxis(hrmsinn->GetSize(),stepsize),hrmsinn->GetArray(),
+                                           CreateXaxisErr(hrmsinnerr->GetSize(),stepsize),hrmsinnerr->GetArray());
+  grmsinn->Draw("A*");
+  grmsinn->SetTitle("Calculated Rms per Slice Inner Pixels");
+  grmsinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsinn->GetYaxis()->SetTitle("Calculated Rms per Slice");
+  //  //grmsinn->Fit("pol2");
+  //  //grmsinn->GetFunction("pol2")->SetLineColor(kRed);
+  //  grmsinn->Fit(logg);
+
+  canvas->cd(4);
+
+  TGraphErrors *gsigmainn = new TGraphErrors(hsigmainn->GetSize(),
+                                             CreateXaxis(hsigmainn->GetSize(),stepsize),hsigmainn->GetArray(),
+                                             CreateXaxisErr(hsigmainnerr->GetSize(),stepsize),hsigmainnerr->GetArray());
+  gsigmainn->Draw("A*");
+  gsigmainn->SetTitle("Fitted Sigma per Slice Inner Pixels");
+  gsigmainn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gsigmainn->GetYaxis()->SetTitle("Fitted Sigma per Slice");
+  //  //  gsigmainn->Fit("pol2");
+  //  //  gsigmainn->GetFunction("pol2")->SetLineColor(kRed);
+  //  gsigmainn->Fit(logg);
+
+  canvas->cd(5);
+
+  TGraphErrors *gmeandiffinn = new TGraphErrors(hmeandiffinn->GetSize(),
+                                                CreateXaxis(hmeandiffinn->GetSize(),stepsize),hmeandiffinn->GetArray(),
+                                                CreateXaxisErr(hmeandiffinnerr->GetSize(),stepsize),hmeandiffinnerr->GetArray());
+  gmeandiffinn->Draw("A*"); 
+  gmeandiffinn->SetTitle("Rel. Difference  Mean per Slice Inner Pixels");
+  gmeandiffinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeandiffinn->GetYaxis()->SetTitle("Rel. Difference Mean per Slice");
+  //  //gmeandiffinn->Fit("pol2");
+  //  //gmeandiffinn->GetFunction("pol2")->SetLineColor(kBlue);
+  //  gmeandiffinn->Fit(logg);
+
+
+  canvas->cd(6);
+
+  TGraphErrors *grmsdiffinn = new TGraphErrors(hrmsdiffinn->GetSize(),
+                                               CreateXaxis(hrmsdiffinn->GetSize(),stepsize),hrmsdiffinn->GetArray(),
+                                               CreateXaxisErr(hrmsdiffinnerr->GetSize(),stepsize),hrmsdiffinnerr->GetArray());
+  grmsdiffinn->Draw("A*");
+  grmsdiffinn->SetTitle("Rel. Difference Sigma per Slice-RMS Inner Pixels");
+  grmsdiffinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsdiffinn->GetYaxis()->SetTitle("Rel. Difference Sigma per Slice-RMS");
+  //  //grmsdiffinn->Fit("pol2");
+  //  //grmsdiffinn->GetFunction("pol2")->SetLineColor(kBlue);
+  //  grmsdiffinn->Fit(logg);
+
+  canvas->SaveAs("PedestalStudyInner.root");
+  canvas->SaveAs("PedestalStudyInner.ps");
+
+  TCanvas *canvas2 = new TCanvas("PedstudOut","Pedestal Studies Outer Pixels",600,900);
+  canvas2->Divide(2,3);
+  canvas2->cd(1);
+
+  TGraphErrors *gmeanout = new TGraphErrors(hmeanout->GetSize(),
+                                            CreateXaxis(hmeanout->GetSize(),stepsize),hmeanout->GetArray(),
+                                            CreateXaxisErr(hmeanouterr->GetSize(),stepsize),hmeanouterr->GetArray());
+  gmeanout->Draw("A*");
+  gmeanout->SetTitle("Calculated Mean per Slice Outer Pixels");
+  gmeanout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeanout->GetYaxis()->SetTitle("Calculated Mean per Slice");
+  //  gmeanout->Fit("pol0");
+  //  gmeanout->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmeanout->Fit(logg);
+
+  canvas2->cd(2);
+
+  TGraphErrors *gmuout = new TGraphErrors(hmuout->GetSize(),
+                                          CreateXaxis(hmuout->GetSize(),stepsize),hmuout->GetArray(),
+                                          CreateXaxisErr(hmuouterr->GetSize(),stepsize),hmuouterr->GetArray());
+  gmuout->Draw("A*");
+  gmuout->SetTitle("Fitted Mean per Slice Outer Pixels");
+  gmuout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmuout->GetYaxis()->SetTitle("Fitted Mean per Slice");
+  //  gmuout->Fit("pol0");
+  //  gmuout->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmuout->Fit(logg);
+
+  canvas2->cd(3);
+
+  TGraphErrors *grmsout = new TGraphErrors(hrmsout->GetSize(),
+                                           CreateXaxis(hrmsout->GetSize(),stepsize),hrmsout->GetArray(),
+                                           CreateXaxisErr(hrmsouterr->GetSize(),stepsize),hrmsouterr->GetArray());
+  grmsout->Draw("A*");
+  grmsout->SetTitle("Calculated Rms per Slice Outer Pixels");
+  grmsout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsout->GetYaxis()->SetTitle("Calculated Rms per Slice");
+  //  //grmsout->Fit("pol2");
+  //  //grmsout->GetFunction("pol2")->SetLineColor(kRed);
+  //  grmsout->Fit(logg);
+
+  canvas2->cd(4);
+
+  TGraphErrors *gsigmaout = new TGraphErrors(hsigmaout->GetSize(),
+                                             CreateXaxis(hsigmaout->GetSize(),stepsize),hsigmaout->GetArray(),
+                                             CreateXaxisErr(hsigmaouterr->GetSize(),stepsize),hsigmaouterr->GetArray());
+  gsigmaout->Draw("A*");
+  gsigmaout->SetTitle("Fitted Sigma per Slice Outer Pixels");
+  gsigmaout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gsigmaout->GetYaxis()->SetTitle("Fitted Sigma per Slice");
+  //  //gsigmaout->Fit("pol2");
+  //  //gsigmaout->GetFunction("pol2")->SetLineColor(kRed);
+  //  gsigmaout->Fit(logg);
+
+
+  canvas2->cd(5);
+
+  TGraphErrors *gmeandiffout = new TGraphErrors(hmeandiffout->GetSize(),
+                                                CreateXaxis(hmeandiffout->GetSize(),stepsize),hmeandiffout->GetArray(),
+                                                CreateXaxisErr(hmeandiffouterr->GetSize(),stepsize),hmeandiffouterr->GetArray());
+  gmeandiffout->Draw("A*");
+  gmeandiffout->SetTitle("Rel. Difference  Mean per Slice Outer Pixels");
+  gmeandiffout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeandiffout->GetYaxis()->SetTitle("Rel. Difference Mean per Slice");
+  //  //gmeandiffout->Fit("pol2");
+  //w  //gmeandiffout->GetFunction("pol2")->SetLineColor(kBlue);
+  //  gmeandiffout->Fit(logg);
+
+  canvas2->cd(6);
+
+  TGraphErrors *grmsdiffout = new TGraphErrors(hrmsdiffout->GetSize(),
+                                               CreateXaxis(hrmsdiffout->GetSize(),stepsize),hrmsdiffout->GetArray(),
+                                               CreateXaxisErr(hrmsdiffouterr->GetSize(),stepsize),hrmsdiffouterr->GetArray());
+  grmsdiffout->Draw("A*");
+  grmsdiffout->SetTitle("Rel. Difference Sigma per Slice-RMS Outer Pixels");
+  grmsdiffout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsdiffout->GetYaxis()->SetTitle("Rel. Difference Sigma per Slice-RMS");
+  //  //grmsdiffout->Fit("pol2");
+  //  //grmsdiffout->GetFunction("pol2")->SetLineColor(kBlue);
+  //  grmsdiffout->Fit(logg);
+
+
+  canvas2->SaveAs("PedestalStudyOuter.root");
+  canvas2->SaveAs("PedestalStudyOuter.ps");
+
+
+}
+
+
+void CamDraw(TCanvas &c, MHCamera &cam, Int_t i, Int_t j, TArrayF &a1, TArrayF &a2, 
+             TArrayF &a1err, TArrayF &a2err, Int_t samp, Int_t stepsize)
+{
+
+  c.cd(i);
+  MHCamera *obj1=(MHCamera*)cam.DrawCopy("hist");
+  obj1->SetDirectory(NULL);
+  
+  c.cd(i+j);
+  obj1->Draw();
+  ((MHCamera*)obj1)->SetPrettyPalette();
+
+  c.cd(i+2*j);
+  TH1D *obj2 = (TH1D*)obj1->Projection();
+  obj2->SetDirectory(NULL);
+  
+  //      obj2->Sumw2();
+  obj2->Draw();
+  obj2->SetBit(kCanDelete);
+  
+  const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+  const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+  const Double_t integ = obj2->Integral("width")/2.5066283;
+  const Double_t mean  = obj2->GetMean();
+  const Double_t rms   = obj2->GetRMS();
+  const Double_t width = max-min;
+  
+  if (rms == 0. || width == 0. )
+    return;
+  
+  TArrayI s0(6);
+  s0[0] = 6;
+  s0[1] = 1;
+  s0[2] = 2;
+  s0[3] = 3;
+  s0[4] = 4;
+  s0[5] = 5;
+  
+  TArrayI inner(1);
+  inner[0] = 0;
+  
+  TArrayI outer(1);
+  outer[0] = 1;
+      
+  // Just to get the right (maximum) binning
+  TH1D *half[2];
+  half[0] = obj1->ProjectionS(s0, inner, "Inner");
+  half[1] = obj1->ProjectionS(s0, outer, "Outer");
+
+  half[0]->SetDirectory(NULL);
+  half[1]->SetDirectory(NULL);
+  
+  for (int i=0; i<2; i++)
+    {
+      half[i]->SetLineColor(kRed+i);
+      half[i]->SetDirectory(0);
+      half[i]->SetBit(kCanDelete);
+      half[i]->Draw("same");
+      half[i]->Fit("gaus","Q+");
+
+      if (i==0)
+        {
+          a1[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParameter(1);
+          a1err[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParError(1);
+          if (a1err[(samp-1)/stepsize] > 3.)
+            a1err[(samp-1)/stepsize] = 1.;
+        }
+     if (i==1)
+       {
+         a2[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParameter(1);
+         a2err[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParError(1);
+          if (a2err[(samp-1)/stepsize] > 3.)
+            a2err[(samp-1)/stepsize] = 1.;
+       }
+    }
+  
+  
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *CreateXaxis(Int_t n, Int_t step)
+{
+
+  Float_t *xaxis = new Float_t[n];
+
+  for (Int_t i=0;i<n;i++)
+    xaxis[i] = 2. + step*i;
+
+  return xaxis;
+                 
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *CreateXaxisErr(Int_t n, Int_t step)
+{
+
+  Float_t *xaxis = new Float_t[n];
+
+  for (Int_t i=0;i<n;i++)
+    xaxis[i] = step/2.;
+
+  return xaxis;
+                 
+}
Index: branches/Mars_McMismatchStudy/macros/pedphotcalc.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/pedphotcalc.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/pedphotcalc.C	(revision 17960)
@@ -0,0 +1,541 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Josep  Flix,  01/2004 <mailto:jflix@ifae.es>
+!              Javier Rico,  01/2004 <mailto:jrico@ifae.es>
+!              Markus Gaug,  03/2004 <mailto:markus@ifae.es>
+!
+!   (based on bootcampstandardanalysis.C by Javier López)
+!
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  pedphotcalc.C
+//
+//  This macro is an example of the use of MPedPhotCalc. It computes
+//  the pedestal mean and rms from pedestal files undergoing the
+//  signal extraction + calibration chain, in units of photons. It
+//  produces plots of the relevant computed quantities.
+//
+//  Needs as arguments the run number of a pedestal file ("*_P_*.root"), 
+//  one of a calibration file ("*_C_*.root").
+//  performs the pedestal calculation, the calibration 
+/// constants calculation and the calibration of the pedestals. 
+//
+//  The TString inpath has to be set correctly.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1" 
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or 
+//  "ct1" in the filenames. If no colour or multiple colours are found, the 
+//  execution is aborted.  
+//
+////////////////////////////////////////////////////////////////////////////////////
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MJPedestal.h"
+#include "MJCalibration.h"
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MGeomCamMagic.h"
+#include "MEvtLoop.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+#include "MExtractedSignalCam.h"
+#include "MExtractSlidingWindow.h" 
+#include "MExtractFixedWindow.h" 
+#include "MCerPhotEvt.h"
+#include "MCalibrateData.h"
+#include "MPedPhotCalc.h"
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+#include "MHCamera.h"
+#include "MRunIter.h"
+#include "MDirIter.h"
+#include "MStatusDisplay.h"
+#include "MHCamera.h"
+
+#include "TTimer.h"
+#include "TString.h"
+#include "TCanvas.h"
+#include "TStyle.h"
+#include "TF1.h"
+#include "TLegend.h"
+
+#include <iostream.h>
+#include "Getline.h"
+
+const TString inpath = "/mnt/Data/rootdata/CrabNebula/2004_02_10/";
+const Int_t dpedrun  = 14607;
+const Int_t dcalrun1 = 14608;
+const Int_t dcalrun2 = 0;
+const Bool_t usedisplay = kTRUE;
+
+
+
+void DrawProjection(MHCamera *obj1, Int_t fit) 
+{
+    TH1D *obj2 = (TH1D*)obj1->Projection(obj1->GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+    gPad->SetLogy();
+
+    if (obj1->GetGeomCam().InheritsFrom("MGeomCamMagic"))
+    {
+        TArrayI s0(3);
+        s0[0] = 6;
+        s0[1] = 1;
+        s0[2] = 2;
+
+        TArrayI s1(3);
+        s1[0] = 3;
+        s1[1] = 4;
+        s1[2] = 5;
+
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TH1D *half[4];
+        half[0] = obj1->ProjectionS(s0, inner, "Sector 6-1-2 Inner");
+        half[1] = obj1->ProjectionS(s1, inner, "Sector 3-4-5 Inner");
+        half[2] = obj1->ProjectionS(s0, outer, "Sector 6-1-2 Outer");
+        half[3] = obj1->ProjectionS(s1, outer, "Sector 3-4-5 Outer");
+
+        for (int i=0; i<4; i++)
+        {
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->Draw("same");
+        }
+    }
+
+    const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+    const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+    const Double_t integ = obj2->Integral("width")/2.5066283;
+    const Double_t mean  = obj2->GetMean();
+    const Double_t rms   = obj2->GetRMS();
+    const Double_t width = max-min;
+
+    if (rms==0 || width==0)
+        return;
+
+    const TString dgausformula("([0]-[3])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])"
+                               "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])");
+
+    TF1 *f=0;
+    switch (fit)
+    {
+        // FIXME: MAYBE add function to TH1?
+    case 0:
+        f = new TF1("sgaus", "gaus(0)", min, max);
+        f->SetLineColor(kYellow);
+        f->SetBit(kCanDelete);
+        f->SetParNames("Area", "#mu", "#sigma");
+        f->SetParameters(integ/rms, mean, rms);
+        f->SetParLimits(0, 0,   integ);
+        f->SetParLimits(1, min, max);
+        f->SetParLimits(2, 0,   width/1.5);
+        obj2->Fit(f, "QLRM");
+        break;
+
+    case 1:
+        f = new TF1("dgaus", dgausformula, min, max);
+        f->SetLineColor(kYellow);
+        f->SetBit(kCanDelete);
+        f->SetParNames("A_{tot}", "#mu_{1}", "#sigma_{1}", "A_{2}", "#mu_{2}", "#sigma_{2}");
+        f->SetParameters(integ,         (min+mean)/2, width/4,
+                         integ/width/2, (max+mean)/2, width/4);
+        // The left-sided Gauss
+        f->SetParLimits(0, integ-1.5,      integ+1.5);
+        f->SetParLimits(1, min+(width/10), mean);
+        f->SetParLimits(2, 0,              width/2);
+        // The right-sided Gauss
+        f->SetParLimits(3, 0,    integ);
+        f->SetParLimits(4, mean, max-(width/10));
+        f->SetParLimits(5, 0,    width/2);
+        obj2->Fit(f, "QLRM");
+        break;
+
+    default:
+        obj2->Fit("gaus", "Q");
+        obj2->GetFunction("gaus")->SetLineColor(kYellow);
+        break;
+    }
+}
+
+void CamDraw(TCanvas &c, Int_t x, Int_t y, MHCamera &cam1, Int_t fit)
+{
+    c.cd(x);
+    gPad->SetBorderMode(0);
+    MHCamera *obj1=(MHCamera*)cam1.DrawCopy("hist");
+
+    c.cd(x+y);
+    gPad->SetBorderMode(0);
+    obj1->Draw();
+
+    c.cd(x+2*y);
+    gPad->SetBorderMode(0);
+    DrawProjection(obj1, fit);
+}
+
+void pedphotcalc(const Int_t prun=dpedrun, // pedestal file
+                 const Int_t crun1=dcalrun1, const Int_t crun2=dcalrun2 // calibration file(s)
+                 )
+{
+
+  MExtractFixedWindow extractor;
+  
+  MRunIter pruns;
+  MRunIter cruns;
+
+  pruns.AddRun(prun,inpath);
+
+  if (crun2==0)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+
+  //
+  // Now setup the tasks and tasklist for the pedestals:
+  // ---------------------------------------------------
+  //
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  MStatusDisplay   *display = NULL;
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MJPedestal pedloop;
+  pedloop.SetInput(&pruns);
+  if (usedisplay)
+    {
+      display = new MStatusDisplay;
+      display->SetUpdateTime(3000);
+      display->Resize(850,700);
+      display->SetBit(kCanDelete);
+      pedloop.SetDisplay(display);
+    }
+  
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Process())
+    return;
+
+  MPedestalCam pedcam = pedloop.GetPedestalCam();
+
+  /****************************/
+  /* SECOND LOOP: CALIBRATION */
+  /****************************/
+  
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+  //
+  // Use as signal extractor MExtractSignal:
+  //
+  calloop.SetExtractor(&extractor);
+  //
+  // The next two commands are for the display:
+  //
+  if (usedisplay)
+    {
+      calloop.SetDisplay(display);
+      calloop.SetDataCheck();
+    }
+  
+  cout << "***********************************" << endl;
+  cout << "** COMPUTING CALIBRATION FACTORS **" << endl;
+  cout << "***********************************" << endl;
+
+  if (!calloop.Process(pedcam))
+    return;
+  
+  MCalibrationChargeCam &calcam = calloop.GetCalibrationCam();
+  MCalibrationQECam     &qecam  = calloop.GetQECam();
+
+  /************************************************************************/
+  /* THIRD LOOP: PEDESTAL COMPUTATION USING EXTRACTED SIGNAL (IN PHOTONS) */
+  /************************************************************************/
+  
+  // Create an empty Parameter List and an empty Task List
+  MParList  plist3;  
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+
+  // containers
+  MCerPhotEvt    photcam;
+  MPedPhotCam    pedphotcam;
+  MExtractedSignalCam extedsig;
+  
+  plist3.AddToList(&geomcam);
+  plist3.AddToList(&pedcam );
+  plist3.AddToList(&calcam );
+  plist3.AddToList(&qecam  );
+  plist3.AddToList(&photcam);
+  plist3.AddToList(&extedsig);
+  plist3.AddToList(&pedphotcam);
+  
+  //tasks
+  MReadMarsFile read3("Events");
+  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(pruns);  
+
+  MCalibrateData  photcalc;
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);
+  MPedPhotCalc    pedphotcalc;  
+
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&extractor);
+  tlist3.AddToList(&photcalc);
+  tlist3.AddToList(&pedphotcalc);
+  
+  // Create and execute eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+    
+  cout << "*************************************************************" << endl;
+  cout << "** COMPUTING PEDESTALS USING EXTRACTED SIGNAL (IN PHOTONS) **" << endl;
+  cout << "*************************************************************" << endl;
+  
+  if (!evtloop3.Eventloop())  
+    return;  
+  tlist3.PrintStatistics();
+
+  /**********************/
+  /* PRODUCE NICE PLOTS */
+  /**********************/
+
+  if (usedisplay)
+    {
+      
+      MHCamera disp0(geomcam, "MPedPhotCam;ped", "Pedestals");
+      MHCamera disp1(geomcam, "MPedPhotCam;rms", "Sigma Pedestal");
+      
+      disp0.SetCamContent(pedphotcam, 0);
+      disp0.SetCamError  (pedphotcam, 1);
+      
+      disp1.SetCamContent(pedphotcam, 1);
+      
+      disp0.SetYTitle("Pedestal signal [photons]");
+      disp1.SetYTitle("Pedestal signal RMS [photons]");
+      
+      //
+      // Display data
+      //
+      TCanvas &c1 = display->AddTab("PedPhotCam");
+      c1.Divide(2,3);
+      
+      CamDraw(c1, 1, 2, disp0, 0);
+      CamDraw(c1, 2, 2, disp1, 1);
+      
+    }
+  
+
+#if 0
+  const UShort_t npix = 577;
+
+  // declare histograms
+  // pedestals
+  TH1F* pedhist    = new TH1F("pedhist","Pedestal",npix,0,npix);
+  TH1F* pedrmshist = new TH1F("pedrmshist","Pedestal RMS",npix,0,npix);
+  TH1F* peddist    = new TH1F("peddist","Pedestal",100,0,20);
+  TH1F* pedrmsdist = new TH1F("pedrmsdist","Pedestal RMS",100,0,15);
+  
+  // calibration factors
+  TH1F* calhist    = new TH1F("calhist","Calibration factors",npix,0,npix);
+  TH1F* caldist    = new TH1F("caldist","Calibration factors",100,0,1);
+  TH1F* qehist     = new TH1F("qehist", "Quantrum efficiencies",npix,0,npix);
+  TH1F* qedist     = new TH1F("qedist", "Quantrum efficiencies",100,0,1);
+
+  // pedestal signals
+  TH1F* pedphothist    = new TH1F("pedphothist","Pedestal Signal",npix,0,npix);
+  TH1F* pedphotrmshist = new TH1F("pedphotrmshist","Pedestal Signal RMS",npix,0,npix);
+  TH1F* pedphotdist    = new TH1F("pedphotdist","Pedestal Signal",100,-0.4,0.4);
+  TH1F* pedphotrmsdist = new TH1F("pedphotrmsdist","Pedestal Signal RMS",100,0,25);
+
+  // fill histograms
+  for(int i=0;i<npix;i++)
+    {
+      MCalibrationChargePix &calpix = (MCalibrationChargePix&)calcam[i];
+      MCalibrationQEPix     &qepix  = (MCalibrationQEPix&)    qecam[i];
+
+      const Float_t ped        = pedcam[i].GetPedestal();
+      const Float_t pedrms     = pedcam[i].GetPedestalRms();
+      const Float_t cal        = calpix.GetMeanConvFADC2Phe();
+      const Float_t qe         = qepix .GetQECascadesFFactor();
+      const Float_t pedphot    = pedphotcam[i].GetMean();
+      const Float_t pedphotrms = pedphotcam[i].GetRms();
+
+      pedhist->Fill(i,ped);
+      peddist->Fill(ped);
+      pedrmshist->Fill(i,pedrms);
+      pedrmsdist->Fill(pedrms);
+
+      calhist->Fill(i,cal);
+      caldist->Fill(cal);
+      qehist->Fill(i,qe);
+      qedist->Fill(qe);
+
+      pedphothist->Fill(i,pedphot);
+      pedphotdist->Fill(pedphot);
+      pedphotrmshist->Fill(i,pedphotrms);
+      pedphotrmsdist->Fill(pedphotrms);
+    }
+
+  // Draw
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  TCanvas* canvas = new TCanvas("canvas","pedphotcalc.C", 0, 100, 650, 800);
+  canvas->SetBorderMode(0);    // Delete the Canvas' border line     
+  canvas->cd();
+
+  canvas->Divide(2,5);
+
+  // draw pedestal histo
+  canvas->cd(1);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+
+  pedhist->SetStats(kFALSE);
+  pedhist->GetXaxis()->SetTitle("Pixel SW Id");
+  pedhist->GetYaxis()->SetTitle("Pedestal (ADC counts)");
+  pedrmshist->SetStats(kFALSE);
+  pedrmshist->SetLineColor(2);
+  pedhist->Draw();
+  pedrmshist->Draw("same");
+
+  TLegend* leg1 = new TLegend(.14,.68,.39,.88);
+  leg1->SetHeader("");
+  leg1->AddEntry(pedhist,"Pedestal","L");
+  leg1->AddEntry(pedrmshist,"Pedestal RMS","L");
+  leg1->SetFillColor(0);
+  leg1->SetLineColor(0);
+  leg1->SetBorderSize(0);
+  leg1->Draw();
+     
+  // draw pedestal distribution
+  canvas->cd(2);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  peddist->GetXaxis()->SetTitle("Pedestal (ADC counts)");
+  pedrmsdist->SetLineColor(2);
+  peddist->Draw();
+  pedrmsdist->Draw("same");
+
+  TLegend* leg2 = new TLegend(.14,.68,.39,.88);
+  leg2->SetHeader("");
+  leg2->AddEntry(pedhist,"Pedestal","L");
+  leg2->AddEntry(pedrmshist,"Pedestal RMS","L");
+  leg2->SetFillColor(0);
+  leg2->SetLineColor(0);
+  leg2->SetBorderSize(0);
+  leg2->Draw();
+
+  // draw calibration histo
+  canvas->cd(3);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  calhist->GetXaxis()->SetTitle("Pixel SW Id");
+  calhist->SetMaximum(1);
+  calhist->SetMinimum(0);
+  calhist->GetYaxis()->SetTitle("Calibration factor (phe/ADC count)");
+  calhist->SetStats(kFALSE);
+  calhist->Draw();
+
+  // draw calibration distribution
+  canvas->cd(4);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  caldist->GetXaxis()->SetTitle("Calibration factor (phe/ADC count)");
+  caldist->Draw();
+
+  // draw qe histo
+  canvas->cd(5);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  qehist->GetXaxis()->SetTitle("Pixel SW Id");
+  qehist->SetMaximum(1);
+  qehist->SetMinimum(0);
+  qehist->GetYaxis()->SetTitle("Quantum efficiency for cascades");
+  qehist->SetStats(kFALSE);
+  qehist->Draw();
+
+  // draw qe distribution
+  canvas->cd(6);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  qedist->GetXaxis()->SetTitle("Quantum efficiency for cascades");
+  qedist->Draw();
+
+  // draw pedestal signal histo
+  canvas->cd(7);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphothist->GetXaxis()->SetTitle("Pixel SW Id");
+  pedphothist->GetYaxis()->SetTitle("Pedestal signal (photons)");
+  pedphothist->SetStats(kFALSE);
+  pedphothist->Draw();
+
+  // draw pedestal signal distribution
+  canvas->cd(8);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphotdist->GetXaxis()->SetTitle("Pedestal signal (photons)");
+  pedphotdist->Draw();
+
+  // draw pedestal signal rms histo
+  canvas->cd(9);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphotrmshist->GetXaxis()->SetTitle("Pixel SW Id");
+  pedphotrmshist->GetYaxis()->SetTitle("Pedestal signal rms (photons)");
+  pedphotrmshist->SetStats(kFALSE);
+  pedphotrmshist->Draw();
+
+  // draw pedestal signal rms distribution
+  canvas->cd(10);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphotrmsdist->GetXaxis()->SetTitle("Pedestal signal rms (photons)");
+  pedphotrmsdist->Draw();
+
+  canvas->SaveAs("pedphotcalc.root");
+
+#endif
+}
Index: branches/Mars_McMismatchStudy/macros/plot/mucal.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/plot/mucal.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/plot/mucal.C	(revision 17960)
@@ -0,0 +1,101 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// mucal.C
+// =======
+//
+// Use this macro to plot the calibration correction factors versus period.
+//
+/////////////////////////////////////////////////////////////////////////////
+void mucal()
+{
+    TEnv env("resources/calibration.rc");
+
+    TGraph g;
+    for (int i=0; i<100; i++)
+    {
+        TString s;
+        s += i;
+
+        Double_t f = env.GetValue(s, -1.0);
+        if (f>0)
+            g.SetPoint(g.GetN(), i, f);
+    }
+
+    TH1   *h    = g.GetHistogram();
+    TAxis *axex = h->GetXaxis();
+    TAxis *axey = h->GetYaxis();
+
+    h->SetXTitle("Observation Period");
+    h->SetYTitle("Calibration correction factor (S_{D}/S_{MC})");
+    axey->CenterTitle();
+    axex->CenterTitle();
+
+    axey->SetLabelSize(0.06);
+    axey->SetTitleSize(0.05);
+    axex->SetLabelSize(0.06);
+    axex->SetTitleSize(0.06);
+    axey->SetTitleOffset(0.65);
+
+    g.SetMarkerStyle(kFullDotLarge);
+
+    TCanvas *c1 = new TCanvas;
+    c1->Divide(1,2);
+    c1->cd(1);
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    gPad->SetTopMargin(0.01);
+    gPad->SetRightMargin(0.01);
+    gPad->SetLeftMargin(0.07);
+    gPad->SetBottomMargin(0.13);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetFillColor(kWhite);
+
+    Double_t min = 0.71;
+    Double_t max = 1.29;
+
+    g.SetMinimum(min);
+    g.SetMaximum(max);
+    g.DrawClone("AP");
+
+    TLine l;
+    l.SetLineStyle(kDashed);
+    l.SetLineWidth(1);
+    l.DrawLine(axex->GetXmin(), 1, axex->GetXmax(), 1);
+
+    l.SetLineColor(kBlue);
+    l.SetLineStyle(kDashed);
+    for (int i=2000; i<2020; i++)
+    {
+        Double_t period = MAstro::GetMagicNewYear(i);
+        if (period>axex->GetXmin() && period<axex->GetXmax())
+            l.DrawLine(period, min, period, max);
+    }
+}
Index: branches/Mars_McMismatchStudy/macros/pointing.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/pointing.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/pointing.C	(revision 17960)
@@ -0,0 +1,462 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// pointing.C
+// ==========
+//
+// This macro is a demonstartion how check plots for a subsystem
+// (here the drive) can be made using Mars.
+//
+// In this case a merpped (root-) cc-report file is read in. The data
+// of the Drive branch is extracted using MReadReports and the
+// Stream-Id feature of MTaskList (second argument in AddToList).
+//
+// The output are plots showing (hopefully) the peformance of the system.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+/*
+ class MGraph : public TGraph
+{
+public:
+    MGraph() : TGraph() {}
+    MGraph(Int_t n) : TGraph(n) {}
+    MGraph(Int_t n, const Int_t *x, const Int_t *y) : TGraph(n, x, y) {}
+    MGraph(Int_t n, const Float_t *x, const Float_t *y) : TGraph(n, x, y) {}
+    MGraph(Int_t n, const Double_t *x, const Double_t *y) : TGraph(n, x, y) {}
+    MGraph(const TVector  &vx, const TVector  &vy) : TGraph(vx, vy) {}
+    MGraph(const TVectorD &vx, const TVectorD &vy) : TGraph(vx, vy) {}
+    MGraph(const TH1 *h) : TGraph(h) {}
+    MGraph(const TF1 *f, Option_t *option="") : TGraph(f, option) {}
+    MGraph(const char *filename, const char *format="%lg %lg", Option_t *option="") : TGraph(filename, format, option) {}
+
+    void Paint(Option_t *o="")
+    {
+        if (!strstr(option,"POL") && !strstr(option,"pol"))
+        {
+            TGraph::Paint(o);
+            return;
+        }
+
+        //gPad->Range(-1.15, -1, 1.15, 1);
+
+        //gPad->Modified();
+        //gPad->Update();
+
+        TView *view = gPad->GetView();
+        if (!view)
+        {
+            cout << "No View!" << endl;
+            return;
+        }
+
+        TGraph gr;
+
+        Double_t *zd=g1->GetY();
+        Double_t *az=g2->GetY();
+
+        TMarker m;
+        m.SetMarkerStyle(kFullDotMedium);
+        m.SetMarkerColor(kRed);
+
+        for (int i=0; i<fN; i++)
+        {
+            const Double_t x = fX[i]/90;
+            const Double_t y = (fY[i]/180+1)*TMath::Pi();
+
+            Double_t r0[3] = { y*cos(x), y*sin(x), 0};
+            Double_t r1[3];
+
+            //gr.SetPoint(gr.GetN(), r0[0], r0[1]);
+
+            view->WCtoNDC(x, y);
+
+            m->PaintMarker(r1[0], r1[1]);
+        }
+    }
+};*/
+
+void pointing()
+{
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetLogStream(&gLog, kTRUE);
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+    MReadReports read;
+    read.AddTree("Drive");
+    read.AddFile("data/2004_01_26_report.root");
+    read.AddToBranchList("MReportDrive.*");
+
+    MContinue tracking("MReportDrive.fState<3.5");
+
+    // Create a task which fills one histogram with the data
+    //MHVsTime h0("MReportDrive.fMjd");
+    MHVsTime h1("MReportDrive.fNominalZd");
+    MHVsTime h2("MReportDrive.fNominalAz");
+    MHVsTime h3("MReportDrive.fState");
+    MHVsTime h7("MReportDrive.GetAbsError*60");
+    //h0.SetName("Mjd");
+    h1.SetName("Zd");
+    h2.SetName("Az");
+    h3.SetName("State");
+    h7.SetName("ControlDeviation");
+
+    MH3 h4("MReportDrive.GetAbsError*60");
+    h4.SetName("DeltaH");
+
+    MH3 h5("MReportDrive.fNominalZd","MReportDrive.GetAbsError*60");
+    h5.SetName("DeltaHvsZd");
+
+    MBinning bins("BinningDeltaH");
+    bins.SetEdges(18, 0, 3.6);
+
+    MBinning bins2("BinningDeltaHvsZdX");
+    MBinning bins3("BinningDeltaHvsZdY");
+    bins2.SetEdges(90, 0, 90);
+    bins3.SetEdges(18, 0, 3.6);
+
+    plist.AddToList(&bins);
+    plist.AddToList(&bins2);
+    plist.AddToList(&bins3);
+
+    //MFillH fill0(&h0, "MTimeDrive");
+    MFillH fill1(&h1, "MTimeDrive");
+    MFillH fill2(&h2, "MTimeDrive");
+    MFillH fill3(&h3, "MTimeDrive");
+    MFillH fill7(&h7, "MTimeDrive");
+    MFillH fill4(&h4);
+    MFillH fill5(&h5);
+
+    //fill0.SetBit(MFillH::kDoNotDisplay);
+    fill1.SetBit(MFillH::kDoNotDisplay);
+    fill2.SetBit(MFillH::kDoNotDisplay);
+    fill3.SetBit(MFillH::kDoNotDisplay);
+    fill4.SetBit(MFillH::kDoNotDisplay);
+    fill5.SetBit(MFillH::kDoNotDisplay);
+    fill7.SetBit(MFillH::kDoNotDisplay);
+
+    // -----------------------------------------------
+
+    //
+    // Setup Task list
+    //
+    tlist.AddToList(&read);
+    tlist.AddToList(&fill3);
+    tlist.AddToList(&tracking);
+    //tlist.AddToList(&fill0);
+    tlist.AddToList(&fill1);
+    tlist.AddToList(&fill2);
+    tlist.AddToList(&fill4);
+    tlist.AddToList(&fill5);
+    tlist.AddToList(&fill7);
+
+    gStyle->SetOptStat(0);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    evtloop.SetDisplay(d);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+
+    TGraph *g1 = h1.GetGraph();
+    TGraph *g2 = h2.GetGraph();
+
+    TCanvas &c = d->AddTab("Sky");
+    c.cd();
+
+    //Skyplot
+    TPad *p = new TPad("", "",0,0.32,0.5,1);
+    p->Draw();
+    p->cd();
+
+    gPad->SetTheta(-90);
+    gPad->SetPhi(90);
+    gPad->SetBorderMode(0);
+    gStyle->SetOptStat(0);
+
+    TH2F h("pol", "Telescope Tracking Positions on the Sky", 16, 0, 1, 9, 0, 1);
+    h.DrawClone("surf1pol");
+
+    gPad->Modified();
+    gPad->Update();
+
+    TView *view = gPad->GetView();
+    if (!view)
+    {
+        cout << "No View!" << endl;
+        return;
+    }
+
+    Double_t *zd=g1->GetY();
+    Double_t *az=g2->GetY();
+
+    Double_t old[2] = {0,0};
+
+    for (int i=0; i<g1->GetN(); i++)
+    {
+        az[i] += 180;
+        az[i] *= TMath::Pi()/180;
+
+        Double_t x[3] = { zd[i]*cos(az[i])/90, zd[i]*sin(az[i])/90, 0};
+        Double_t y[3];
+
+        view->WCtoNDC(x, y);
+
+        if (old[0]!=0 && old[1]!=1)
+        {
+            TLine *l = new TLine(y[0], y[1], old[0], old[1]);
+            l->SetLineColor(kBlue);
+            l->Draw();
+        }
+
+        TMarker *m = new TMarker(y[0], y[1], kFullDotMedium);
+        m->SetMarkerColor(i==g1->GetN()-1 ? kGreen : kRed);
+        m->Draw();
+
+        old[0] = y[0];
+        old[1] = y[1];
+    }
+
+    c.cd();
+
+
+/*
+    //MJD
+    p = new TPad("", "", 0.6, 0.66, 1, 1);
+    p->Draw();
+    p->cd();
+
+    MHVsTime *hvt=h0.DrawClone("nonew");
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+    hvt->GetGraph()->GetHistogram()->SetXTitle("Time");
+    hvt->GetGraph()->GetHistogram()->SetYTitle("");
+    hvt->GetGraph()->GetHistogram()->SetTitle("MJD vs. Time");
+    hvt->GetGraph()->GetHistogram()->SetStats(0);
+
+    c.cd();
+*/
+
+
+    //Histogram of Control Deviation
+    p = new TPad("", "", 0, 0, 0.5, 0.32);
+    p->Draw();
+    p->cd();
+
+    gPad->SetBorderMode(0);
+    //number of entries, mean, rms and number of overflows in the statusbox
+    gStyle->SetOptStat("emro"); 
+    //gStyle->SetStatFormat(".2g");
+
+    MH3 *mh3 = (MH3*)h4.DrawClone("nonew");
+
+    TAxis *axey = mh3->GetHist()->GetYaxis();
+    TAxis *axex = mh3->GetHist()->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.05);
+    axex->SetTitleOffset(0.85);
+
+    mh3->GetHist()->SetXTitle("\\Delta [arcmin]");
+    mh3->GetHist()->SetYTitle("");
+    mh3->GetHist()->SetTitle("Control deviation of the motors");
+    mh3->GetHist()->SetStats(1);
+
+    //insert lines for 0.5, 1 and 2 SE
+    TLine ln;
+    ln.SetLineColor(kGreen);
+    ln.DrawLine(0.5*360*60/16384., 0, 0.5*360*60/16384., h4.GetHist()->GetMaximum());
+    ln.SetLineColor(kYellow);
+    ln.DrawLine(1.0*360*60/16384., 0, 1.0*360*60/16384., h4.GetHist()->GetMaximum());
+    ln.SetLineColor(kRed);
+    ln.DrawLine(2.0*360*60/16384., 0, 2.0*360*60/16384., h4.GetHist()->GetMaximum());
+
+    c.cd();
+
+
+    //Status of the Drive System vs Time
+    p = new TPad("", "", 0.5, 0.86, 1, 1);
+    p->Draw();
+    p->cd();
+    gPad->SetBorderMode(0);
+    p->SetGridx();
+
+    hvt = (MHVsTime*)h3.DrawClone("nonew");
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+
+    TH1 *hist = hvt->GetGraph()->GetHistogram();
+    TAxis *axey = hist->GetYaxis();
+    TAxis *axex = hist->GetXaxis();
+
+    hist->SetXTitle("Time");
+    hist->SetYTitle("");
+    hist->SetTitle("");//Drive Status vs. Time");
+    hist->SetStats(0);
+    hist->SetMinimum(-0.5);
+    hist->SetMaximum(4.5);
+    axey->Set(5, -0.5, 4.5);
+    axey->SetBinLabel(axey->FindFixBin(0), "Error");
+    axey->SetBinLabel(axey->FindFixBin(1), "Stopped");
+    axey->SetBinLabel(axey->FindFixBin(3), "Moving");
+    axey->SetBinLabel(axey->FindFixBin(4), "Tracking");
+    axey->SetLabelSize(0.15);
+    axex->SetLabelSize(0.08);
+    axex->SetTitleSize(0.09);
+    axex->SetTitleOffset(0.45);
+
+    c.cd();
+
+
+    //Zd vs Time
+    p = new TPad("", "", 0.5, 0.59, 1, 0.86);
+    p->Draw();
+    p->cd();
+    gPad->SetBorderMode(0);
+    p->SetGridx();
+
+    hvt = (MHVsTime*)h1.DrawClone("nonew");
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+
+    TH1 *hist = hvt->GetGraph()->GetHistogram();
+    if (hvt->GetGraph()->GetN())
+    {
+        hist->SetXTitle("Time");
+        hist->SetYTitle("Zd [\\circ]");
+        hist->SetTitle("Zd vs. Time");
+        hist->SetStats(0);
+    }
+
+    TAxis *axey = hist->GetYaxis();
+    TAxis *axex = hist->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axey->SetTitleSize(0.06);
+    axey->SetTitleOffset(0.6);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.06);
+    axex->SetTitleOffset(0.85);
+
+    c.cd();
+
+
+    //Controll Deviation vs Time
+    p = new TPad("", "", 0.5, 0.32, 1, 0.59);
+    p->Draw();
+    p->cd();
+    gPad->SetBorderMode(0);
+    p->SetGridx();
+
+    hvt = (MHVsTime*)h7.DrawClone("nonew L");
+    TH1 *hist = hvt->GetGraph()->GetHistogram();
+    hist->SetAxisRange(-0.5, 10.5, "Y");
+    hist->SetXTitle("Time");
+    hist->SetYTitle("\\Delta [arcmin]");
+    hist->SetTitle("Control Deviation vs. Time");
+
+    TAxis *axey = hist->GetYaxis();
+    TAxis *axex = hist->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axey->SetTitleSize(0.06);
+    axey->SetTitleOffset(0.5);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.06);
+    axex->SetTitleOffset(0.8);
+
+    //insert lines for 0.5, 1 and 2 SE
+    TLine ln;
+    ln.SetLineColor(kGreen);
+    ln.DrawLine(hist->GetXaxis()->GetXmin(), 0.5*360*60/16384., hist->GetXaxis()->GetXmax(), 0.5*360*60/16384.);
+    ln.SetLineColor(kYellow);
+    ln.DrawLine(hist->GetXaxis()->GetXmin(), 1.0*360*60/16384., hist->GetXaxis()->GetXmax(), 1.0*360*60/16384.);
+    ln.SetLineColor(kRed);
+    ln.DrawLine(hist->GetXaxis()->GetXmin(), 2.0*360*60/16384., hist->GetXaxis()->GetXmax(), 2.0*360*60/16384.);
+
+    c.cd();
+
+
+    //Controll Deviation vs Zd
+    p = new TPad("", "", 0.5, 0, 1, 0.32);
+    p->Draw();
+    p->cd();
+
+    gPad->SetBorderMode(0);
+    gStyle->SetOptStat(1110);
+    gStyle->SetStatFormat(".2g");
+
+    mh3 = (MH3*)h5.DrawClone("nonew");
+
+    TAxis *axey = mh3->GetHist()->GetYaxis();
+    TAxis *axex = mh3->GetHist()->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axey->SetTitleSize(0.05);
+    axey->SetTitleOffset(0.7);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.05);
+    axex->SetTitleOffset(0.85);
+
+    mh3->GetHist()->SetYTitle("Zd [\\circ]");
+    mh3->GetHist()->SetXTitle("\\Delta [arcmin]");
+    mh3->GetHist()->SetTitle("Control deviation of the motors");
+    mh3->GetHist()->SetStats(1);
+    mh3->GetHist()->Draw("box");
+
+    //insert lines for 0.5, 1 and 2 SE
+    TLine ln;
+    ln.SetLineColor(kGreen);
+    ln.DrawLine(0, 0.5*360*60/16384., 90, 0.5*360*60/16384.);
+    ln.SetLineColor(kYellow);
+    ln.DrawLine(0, 1.0*360*60/16384., 90, 1.0*360*60/16384.);
+    ln.SetLineColor(kRed);
+    ln.DrawLine(0, 2.0*360*60/16384., 90, 2.0*360*60/16384.);
+
+
+    //d.SaveAsPS(2, "rep_files/CC_2003_11_27_22_31_59-new.ps");
+    //d.SaveAsRoot(2, "~/dev/Mars/rep_files/CC_2003_11_27_22_31_59-new.root");
+
+}
Index: branches/Mars_McMismatchStudy/macros/pointspreadfunction.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/pointspreadfunction.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/pointspreadfunction.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/readCalibration.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/readCalibration.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/readCalibration.C	(revision 17960)
@@ -0,0 +1,130 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 05/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  readCalibration.C
+//
+//  Needs as arguments the run number of a calibration file ("*_C_*.root") and 
+//  the run number of the corresponding pedestal file ("*_P_*.root"). 
+//
+//  The TString inpath has to be set correctly.
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+static const TString inpath = ".";
+//
+// the default start calibration run 
+//
+static const Int_t   calrun = 26209;
+//
+// Tell if you want to use the display:
+//
+static Bool_t useDisplay = kFALSE;
+//
+void readCalibration(const Int_t crun=calrun)
+{
+
+  const TString calname  = Form("%s/calib%08d.root", (const char*)inpath,crun);
+
+  if (gSystem->AccessPathName(calname, kFileExists))
+    {
+      cout << "Input file " << calname << " doesn't exist." << endl;
+      return;
+    }
+
+  MStatusDisplay = NULL;
+  
+  if (useDisplay)
+    display = new MStatusDisplay;
+
+  MPedestalCam                 pedcam;
+  MCalibrationChargeCam        chargecam;  
+  MCalibrationQECam            qecam;
+  MCalibrationRelTimeCam       relcam;
+  MBadPixelsCam                badcam;
+
+  cout << "Reading from file: " << calname << endl;
+
+  TFile calfile(calname, "READ");
+  if (chargecam.Read()<=0)
+    {
+      cout << "Unable to read MCalibrationChargeCam from " << calname << endl;
+      return;
+    }
+  if (qecam.Read()<=0)
+    {
+      cout << "Unable to read MCalibrationQECam from " << calname << endl;
+      return;
+    }
+
+  if (calfile.FindKey("MBadPixelsCam"))
+      {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+          {
+            cout << "Unable to read MBadPixelsCam from " << calname << endl;
+            return;
+          }
+        badcam.Merge(bad);
+      }
+  if (relcam.Read()<=0)
+    {
+      cout << "Unable to read MCalibrationRelTimeCam from " << calname << endl;
+      return;
+    }
+
+  cout << "Size of QECam: "      << qecam.GetSize() << endl;
+  cout << "Size of Chargecam: "  << chargecam.GetSize() << endl;
+  cout << "Size of RelTimeCam: "  << relcam.GetSize() << endl;
+
+   MGeomCamMagic geom;
+
+  if (useDisplay)
+    display->Read();
+  
+  for (Int_t i=0; i<relcam.GetSize(); i++)
+  {
+      MCalibrationRelTimePix &rpix = (MCalibrationRelTimePix&)relcam[i];
+      MBadPixelsPix &badpix = badcam[i];
+      if (!badpix.IsUnsuitable())
+        cout << "Number of outliers in time pixel: " << i << ": " << rpix.GetNumPickup()+rpix.GetNumBlackout() << endl;
+  } 
+
+  for (Int_t i=0; i<2; i++)
+  {  
+      TArrayF conv = chargecam.GetAveragedConvFADC2PhotPerArea(geom,qecam,i,&badcam);
+      cout << "Average Conv Factor Area idx: " << i << ":  " << conv[0] << "+-" << conv[1] << endl;
+  }
+
+  for (Int_t i=0; i<qecam.GetSize(); i++)
+    {
+      MCalibrationChargePix &cpix = (MCalibrationChargePix&)chargecam[i];
+      MCalibrationQEPix     &qpix = (MCalibrationQEPix&)    qecam[i];
+      MBadPixelsPix         &bpix  = badcam[i];
+      if (!bpix.IsUnsuitable())
+        cout << "Conversion Factor: " << cpix.GetMeanConvFADC2Phe() / qpix.GetQECascadesFFactor() << endl;
+    }
+
+}
+
Index: branches/Mars_McMismatchStudy/macros/readIPR.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/readIPR.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/readIPR.C	(revision 17960)
@@ -0,0 +1,74 @@
+///////////////////////////////////////////////////////////////////////////
+// 
+//    readIPR.C
+//
+//   This macro shows how to read the Individual Pixel Rates from 
+//   a CC report file.
+//
+//   Input: 
+//     - root file obtained merpping a .rep CC file
+//       container: MTriggerIPR
+//
+//   Output:
+//     - a camera display showing the IPRs
+//     - Some histos for checking purposes
+//   
+//   Note: 
+//     a similar macro can be used to read the following trigger containers:
+//     - MTriggerIPR        (Individual Pixel Rates)
+//     - MTriggerCell       (Rate of trigger cells)
+//     - MTriggerBit        (Output Bits from prescaler (before/after presc.)
+//     - MTriggerPrescFact  (Prescaling factors for each bit)
+//     - MTriggerLiveTime   (Values of counters for dead/livetime)
+//
+//    Author(s): Antonio Stamerra. 09/04 <antonio.stamerra@pi.infn.it>
+//
+////////////////////////////////////////////////////////////////////////////
+void readIPR(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // Create the magic geometry
+    MGeomCamMagic geom;
+    plist.AddToList(&geom);
+
+    // First Task: Read ROOT file with Trigger-REPORT data
+    MReadTree read("Trigger", fname);
+    read.DisableAutoScheme();
+
+    tlist.AddToList(&read);
+
+    MHCamEvent evt0(0, "IPR", "Individual Pixel Rate;;IPR [Hz]");
+    //    evt0b.SetThreshold(0);
+
+    MFillH fill0(&evt0, "MTriggerIPR", "FillIPR");
+
+    tlist.AddToList(&fill0);
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    if (!evtloop.Eventloop())
+      return;
+
+    tlist.PrintStatistics();
+}
+
Index: branches/Mars_McMismatchStudy/macros/readMagic.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/readMagic.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/readMagic.C	(revision 17960)
@@ -0,0 +1,229 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// readMagic.C
+// ===========
+//
+// This is a demonstration program showing how to do particular processing
+// on a single event basis. Here we simply display uncleand und cleand
+// images.
+// Therefor MInteractiveTask is used, which gives you the possibility
+// to develop new tasks without the need of compilation.
+// The input is a merpp raw-data file.
+//
+///////////////////////////////////////////////////////////////////////////
+
+Bool_t HandleInput()
+{
+    // This must be there to get accesss to the GUI while the macro
+    // is still running!
+
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+//
+// Setup the data-members of your 'virtual' class
+//
+MHCamera display[4];
+
+TCanvas   *c;
+MParList  *fParList;
+MTaskList *fTaskList;
+
+//
+// Called like all PreProcess functions of tasks. Get the access to
+// the containers necessary for you.
+//
+Int_t PreProcess(MParList *plist)
+{
+    // Get parameter and tasklist, see Process
+    fParList = plist;
+    fTaskList = (MTaskList*)plist->FindObject("MTaskList");
+
+    // Get camera geoemtry
+    MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+
+    // setup canvas and camera-histograms
+    c = new TCanvas("Events", "Real Events", 600, 600);
+    c->SetBorderMode(0);
+    c->Divide(2,2);
+    for (int i=0; i<4; i++)
+    {
+        display[i].SetGeometry(*geomcam);
+        c->cd(i+1);
+        display[i].Draw();
+        gPad->cd(1);
+        plist->FindObject("MHillas")->Draw();
+    }
+    return kTRUE;
+}
+
+//
+// Called like all Process functions of tasks. Process a single
+// event - here display it.
+//
+Int_t Process()
+{
+    // For simplicity we search in the Process function for the
+    // objects. This is deprectaed! Store the pointers to the objects
+    // as data member and get the pointers in PreProcess.
+    MReadMarsFile *read = (MReadMarsFile*)fTaskList->FindObject("MRead");
+    MClone *clone = (MClone*)fTaskList->FindObject("MClone");
+    MImgCleanStd *clean = (MImgCleanStd*)fTaskList->FindObject("MImgCleanStd");
+    MGeomCam *geom = (MGeomCam*)fParList->FindObject("MGeomCam");
+
+    // Ouput event number
+    cout << "Event #" << read->GetNumEntry() << ":" << endl;
+
+    // Fill the data into your camera-histograms
+    display[0].SetCamContent(*(MCerPhotEvt*)clone->GetClone());
+    display[1].SetCamContent(*(MCerPhotEvt*)fParList->FindObject("MCerPhotEvt"));
+    display[2].SetCamContent(*(MCameraData*)fParList->FindObject("MCameraData"));
+    display[3].SetCamContent(*(MCameraData*)fParList->FindObject("MCameraData"));
+
+    // Setup the cleaning level histogram
+    TArrayF lvl(2);
+    lvl[0] = clean->GetCleanLvl2();
+    lvl[1] = clean->GetCleanLvl1();
+    display[3].SetLevels(lvl);
+
+    // Update the display
+    for (int i=1; i<=4; i++)
+    {
+        c->GetPad(i)->GetPad(1)->Modified();
+        c->GetPad(i)->GetPad(1)->Update();
+    }
+
+    // print the data on the console
+    ((MHillas*)fParList->FindObject("MHillas"))->Print(*geom);
+    ((MHillasExt*)fParList->FindObject("MHillasExt"))->Print(*geom);
+    ((MNewImagePar*)fParList->FindObject("MNewImagePar"))->Print(*geom);
+
+    // wait for 'return'
+    return HandleInput();
+}
+
+//
+// Called like all PostProcess functions of tasks. Delete
+// instanciated objects.
+//
+Int_t PostProcess()
+{
+    delete c;
+}
+
+void readMagic(const char *fname="../Proton*.root")
+{
+    // Setup parameter- and tasklist
+    MParList  plist;
+    MTaskList tlist;
+
+    plist.AddToList(&tlist);
+
+    // setup reading task
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    // setup a task making sure that all arrays are resized correctly
+    MGeomApply geomapl;
+
+    // Setup a print task calling TObject::Print
+    MPrint print1("MMcEvt");
+    MPrint print2("MRawEvtHeader");
+    // Skip them if conatainers are not found
+    print1.EnableSkip();
+    print2.EnableSkip();
+
+    // Copy MC pedestals to apropriate conatiners (if MC file)
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    // Calculate signal and pedestal from data (use MCerPhotCalc
+    // in case of MC files)
+    MCerPhotAnal2     ncalc;
+
+    // Blind Pixel Treatment (deprecated, will be replaced by
+    // MBadPixel*)
+    MBlindPixelCalc   blind;
+    blind.SetUseInterpolation();
+
+    // Clone MCerPhotEvt befor eimage cleaning
+    MClone            clone("MCerPhotEvt");
+
+    // Setup image cleaning
+    MImgCleanStd      clean;
+
+    // Setup calculation of Image parameters
+    MHillasCalc       hcalc;
+
+    // Setup intercative task calling the functions defined above
+    MTaskInteractive  mytask;
+
+    mytask.SetPreProcess(PreProcess);
+    mytask.SetProcess(Process);
+
+    // Setup your tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&print1);
+    tlist.AddToList(&print2);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&blind);
+    tlist.AddToList(&clone);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&mytask);
+
+    // Run your analysis
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print statistics information about your loop
+    tlist.PrintStatistics();
+}
+
Index: branches/Mars_McMismatchStudy/macros/rootlogon.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/rootlogon.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/rootlogon.C	(revision 17960)
@@ -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-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// rootlogon.C
+// ===========
+//
+// This file is the startup script ("autoexec.bat") executed when root is
+// started. The definition which file to start is done in ".rootrc".
+// There are three files which are automatically processed by root at
+// startup: A systemwide .rootrc, one in your home directory and one
+// in the current directory.
+// So rootlogon.C is correctly executed if your start root from your
+// Mars directory.
+//
+// The script setupts some small environmental things and makes
+// sure that the Mars shared object (libmars.so) is loaded. This shared
+// object gives you access to all Mars features from within the root
+// interpreter.
+//
+// If libmars.so is not found in the current directory we search in the
+// directory given in "MARSSYS" environment variable.
+//
+///////////////////////////////////////////////////////////////////////////
+#include <iomanip>
+
+
+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()
+{
+    // This is a workaround to make axis behave as they
+    // are UTC and not local time
+    //    gSystem->Setenv("TZ", "UTC");
+
+    cout << endl;
+
+    const Bool_t fileexist = !gSystem->AccessPathName("libmars.so", kFileExists);
+
+    TString dir = fileexist ? "" : gSystem->Getenv("MARSSYS");
+    if (!dir.IsNull())
+    {
+        cout << "\033[34m\033[1m" << "Searching Mars in " << dir << " (MARSSYS)" << "\033[0m" << endl << endl;
+
+        if (!dir.EndsWith("/"))
+            dir += "/";
+    }
+
+    if (!load(dir))
+        return;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    // This initialized the thread factory. This is needed to supress
+    // an error which is displayed if the thread factory is initialized
+    // from another than the main thread (e.g. in the constructor
+    // of MStatusDisplay)
+    TThread::Self();
+
+    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+"mcore");
+    gInterpreter->AddIncludePath(dir+"mdrs");
+    gInterpreter->AddIncludePath(dir+"mhcalib");
+    gInterpreter->AddIncludePath(dir+"mdata");
+    gInterpreter->AddIncludePath(dir+"mfbase");
+    gInterpreter->AddIncludePath(dir+"mfileio");
+    gInterpreter->AddIncludePath(dir+"mfilter");
+    gInterpreter->AddIncludePath(dir+"mgeom");
+    gInterpreter->AddIncludePath(dir+"mgui");
+    gInterpreter->AddIncludePath(dir+"mhbase");
+    gInterpreter->AddIncludePath(dir+"mhflux");
+    gInterpreter->AddIncludePath(dir+"mhft");
+    gInterpreter->AddIncludePath(dir+"mhist");
+    gInterpreter->AddIncludePath(dir+"mhistmc");
+    gInterpreter->AddIncludePath(dir+"mhvstime");
+    gInterpreter->AddIncludePath(dir+"mimage");
+    gInterpreter->AddIncludePath(dir+"mjobs");
+    gInterpreter->AddIncludePath(dir+"mjoptim");
+    gInterpreter->AddIncludePath(dir+"mjtrain");
+    gInterpreter->AddIncludePath(dir+"mmain");
+    gInterpreter->AddIncludePath(dir+"mmc");
+    gInterpreter->AddIncludePath(dir+"mmontecarlo");
+    gInterpreter->AddIncludePath(dir+"mmuon");
+    gInterpreter->AddIncludePath(dir+"mpedestal");
+    gInterpreter->AddIncludePath(dir+"mpointing");
+    gInterpreter->AddIncludePath(dir+"mranforest");
+    gInterpreter->AddIncludePath(dir+"mraw");
+    gInterpreter->AddIncludePath(dir+"mreflector");
+    gInterpreter->AddIncludePath(dir+"mreport");
+    gInterpreter->AddIncludePath(dir+"msignal");
+    gInterpreter->AddIncludePath(dir+"msql");
+    gInterpreter->AddIncludePath(dir+"mstarcam");
+    gInterpreter->AddIncludePath(dir+"mtools");
+    gInterpreter->AddIncludePath(dir+"mtrigger");
+    gInterpreter->AddIncludePath(dir+"melectronics");
+    gInterpreter->AddIncludePath(dir+"msim");
+    gInterpreter->AddIncludePath(dir+"msimreflector");
+    gInterpreter->AddIncludePath(dir+"msimcamera");
+    gInterpreter->AddIncludePath(dir+"mcorsika");
+    gInterpreter->AddIncludePath(dir+"mextralgo");
+
+    TString opt(gSystem->GetFlagsOpt());
+    TString dbg(gSystem->GetFlagsDebug());
+    TString lib(gSystem->GetLinkedLibs());
+
+    TString add = " -O5 -std=c++0x -Wall -Winit-self -fPIC -Wpointer-arith -Wcast-align -Woverloaded-virtual";
+    add += " -D__MARS__";
+    add += " -DHAVE_ZLIB";
+    add += " -DPACKAGE_NAME='\""+MARS::GetPackageName()+"\"'";
+    add += " -DPACKAGE_VERSION='\""+MARS::GetPackageName()+"\"'";
+    add += " -DREVISION='\""+MARS::GetRevision()+"\"'";
+
+    opt += add;
+    dbg += add;
+
+    lib += " -lnova -lz";
+
+    gSystem->SetLinkedLibs(lib);
+    gSystem->SetFlagsOpt(opt);
+    gSystem->SetFlagsDebug(dbg);
+
+
+    cout << "\033[32m" << "Welcome to the Mars Root environment." << "\033[0m" << endl;
+    cout << endl;
+}
Index: branches/Mars_McMismatchStudy/macros/star.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/star.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/star.C	(revision 17960)
@@ -0,0 +1,131 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STAR - STandard Analysis and Reconstruction
+//
+// This macro is the standard converter to convert raw data into image
+// parameters. It is a demonstration how the star-executable implementation
+// looks like.
+//
+// As an input you need a Merpp output file (raw data).
+// All parameters are written to an output file called starfile.root.
+// For the calculation an arbitrary signal extractor (MCerPhotAnal2/Calc)
+// is used.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void star()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+
+    // ------------- user change -----------------
+    read.AddFile("~/MC/test_sample/Gamma_zbin0_0_*.root");
+
+    MGeomApply        apply;
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    MCerPhotCalc      ncalc;
+    MCerPhotAnal2     nanal;
+
+    MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);
+    MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);
+
+    ncalc.SetFilter(&f1);
+    nanal.SetFilter(&f2);
+
+    MBlindPixelCalc   blind;
+    blind.SetUseInterpolation();
+
+    MSigmabarCalc     sgcal;
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+
+    // ------------- user change -----------------
+    MWriteRootFile write("starfile.root");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&f1);
+    tlist.AddToList(&f2);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&nanal);
+    tlist.AddToList(&blind);
+    tlist.AddToList(&sgcal);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&scalc);
+    tlist.AddToList(&write);
+
+    // ------------- user change -----------------
+    // You may use the "UPDATE" option in the constructor
+    // of MWriteRootFile to update an existing file.
+    //
+    // tlist.SetSerialNumber(1); // Serial number of telescope
+    write.AddContainer(write.AddSerialNumber("MMcEvt"),       "Events", kFALSE);
+    write.AddContainer(write.AddSerialNumber("MSigmabar"),    "Events");
+    write.AddContainer(write.AddSerialNumber("MHillas"),      "Events");
+    write.AddContainer(write.AddSerialNumber("MHillasExt"),   "Events");
+    write.AddContainer(write.AddSerialNumber("MHillasSrc"),   "Events");
+    write.AddContainer(write.AddSerialNumber("MNewImagePar"), "Events");
+    write.AddContainer(write.AddSerialNumber("MSrcPosCam"),   "RunHeaders");
+    write.AddContainer("MRawRunHeader", "RunHeaders");
+    write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+
+    //
+    // Create and set up the eventloop
+    //
+    MProgressBar bar;
+
+    MEvtLoop evtloop;
+    evtloop.SetProgressBar(&bar);
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+}
Index: branches/Mars_McMismatchStudy/macros/starfield.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/starfield.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/starfield.C	(revision 17960)
@@ -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/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// starfield.C
+// ===========
+//
+// This is a macro demonstrating how to use Mars to display a starfield.
+// It also is a tutorial for MAstroCatalog and MAstroCamera.
+//
+// For more details on this classes see the class-reference.
+//
+// If you want to display stars in a camera you need the camera geometry
+// and the mirror definition. You can get this either from a Monte Carlo
+// file containing both or create your MGeomCam object manually and
+// read a magic.def file which you will find in the camera simulation
+// program.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void ReadSetup(MAstroCamera &cam)
+{
+    /*
+     // Name of a MC file having MGeomCam and MMcConfigRunHeader
+     TString fname = "../Mars/Gamma_zbin7_90_7_53395to53399_w0.root";
+
+     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);
+     */
+
+    MGeomCamMagic geom;
+    cam.SetGeom(geom);
+    cam.SetMirrors("resources/mirrors.def");
+}
+
+void starfield()
+{
+    // 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(stars);   // Use this top display a catalog on top of a camera
+    stars.SetLimMag(6);
+    stars.SetRadiusFOV(3);
+    stars.SetRaDec(ra, dec);
+
+    // Read the stars from a star catalog. The catalogs can be downloaded
+    // from the Mars web page. For more information see class reference.
+    stars.ReadBSC("bsc5.dat");
+
+    stars.SetObservatory(magic1);
+    stars.SetTime(time);
+    stars.SetGuiActive();
+
+    // See the cooresponding Draw-function for more options
+    TObject *o = stars.Clone();
+    o->SetBit(kCanDelete);
+    o->Draw();
+
+}
Index: branches/Mars_McMismatchStudy/macros/starmc.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/starmc.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/starmc.C	(revision 17960)
@@ -0,0 +1,317 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): 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("nonoise/Gamma_zbin0_0_7_1000to1009_w0.root");
+  // File to be used in the calibration (must be a camera file without added noise)
+
+  Char_t* AnalysisFilename = "Gamma_zbin0_0_*.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.;
+
+  // USER CHANGE: tail cuts for image analysis
+
+  Float_t CleanLev[2] = {10., 5.}; // Tail cuts for the analysis loop
+  MImgCleanStd clean2(CleanLev[0], CleanLev[1]); // Applies tail cuts to image.
+  clean2.SetMethod(MImgCleanStd::kAbsolute); 
+
+  //  USER CHANGE: signal extraction
+
+  //  MExtractTimeAndChargeDigitalFilter sigextract;
+  //  sigextract.SetNameWeightsFile("/users/emc/moralejo/Mars/msignal/MC_weights.dat");
+  //  sigextract.SetRange(1, 14, 3, 14);
+
+  MExtractTimeAndChargeSpline sigextract;
+  sigextract.SetChargeType(MExtractTimeAndChargeSpline::kIntegral);
+  sigextract.SetRiseTimeHiGain(0.5);
+  sigextract.SetFallTimeHiGain(0.5);
+
+  // USER CHANGE: high to low gain ratio. DEPENDS on EXTRACTOR!!
+  // One should calculate somewhere else what this factor is for each extractor!
+
+  //  Float_t hi2low = 10.83; 
+  // value for digital filter, HG window 4, LG window 6
+
+  Float_t hi2low = 11.28; 
+  // value for spline with risetime 0.5, fall time 0.5, low gain stretch 1.5
+
+
+  ////////// Calibration //////////
+  MMcCalibrationUpdate  mccalibupdate;
+  mccalibupdate.SetUserLow2HiGainFactor(hi2low);
+
+  ///// USER CHANGE: calibrate in photons or phe- :
+  mccalibupdate.SetSignalType(MCalibrateData::kPhe);
+  //  mccalibupdate.SetSignalType(MCalibrateData::kPhot);
+
+
+  MImgCleanStd  clean(0.,0.); 
+  // All pixels containing any photon will be accepted. This is what we want
+  // for the calibration loop (since no noise is added)
+  clean.SetMethod(MImgCleanStd::kAbsolute); 
+  // In absolute units (phot or phe- as chosen below)
+
+  MSrcPosCam src;
+  //
+  // ONLY FOR WOBBLE MODE!! : set the rigt source position on camera!
+  //   src.SetX(120.);   // units: mm. Value for MC w+ files
+  //   src.SetX(-120.);  // units: mm. Value for MC w- files
+
+  src.SetReadyToSave();
+
+  // -------------------------------------------
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  src.SetReadyToSave();
+  plist.AddToList(&src);
+
+  MBadPixelsCam badpix;
+  plist.AddToList(&badpix);
+
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+
+  if (CalibrationFilename)
+    read.AddFile(CalibrationFilename->Data());
+
+  read.DisableAutoScheme();
+
+  MGeomApply geom; // Reads in geometry from MC file and sets the right sizes for
+  // several parameter containers.
+
+  MMcPedestalCopy   pcopy; 
+  // Copies pedestal data from the MC file run fadc header to the MPedestalCam container.
+
+  MPointingPosCalc pointcalc;
+  // Creates MPointingPos object and fill it with the telescope orientation
+  // information taken from MMcEvt.
+
+  MCalibrateData calib; // Applies calibration to the data
+  calib.SetCalibrationMode(MCalibrateData::kFfactor);
+  // Do not change the CalibrationMode above for MC...!
+  calib.SetSignalType(mccalibupdate.GetSignalType());
+
+  //    MBlindPixelCalc   blind;
+  //    blind.SetUseInterpolation();
+
+  MHillasCalc       hcalc; // Calculates Hillas parameters not dependent on source position.
+  hcalc.Disable(MHillasCalc::kCalcHillasSrc);
+
+  MMcCalibrationCalc mccalibcalc;
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+  tlist.AddToList(&pcopy);
+  tlist.AddToList(&pointcalc);
+
+  tlist.AddToList(&sigextract);
+  tlist.AddToList(&mccalibupdate);
+  tlist.AddToList(&calib);
+  tlist.AddToList(&clean);
+  //    tlist.AddToList(&blind);
+  tlist.AddToList(&hcalc);
+
+  tlist.AddToList(&mccalibcalc);
+
+  //
+  // Open output files:
+  //
+
+  MWriteRootFile write1(OutFilename1->Data()); // Writes output1
+  write1.AddContainer("MRawRunHeader", "RunHeaders");
+  write1.AddContainer("MMcRunHeader",  "RunHeaders");
+  write1.AddContainer("MSrcPosCam",    "RunHeaders");
+  write1.AddContainer("MGeomCam",      "RunHeaders");
+  write1.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write1.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write1.AddContainer("MMcFadcHeader",  "RunHeaders");
+  write1.AddContainer("MMcTrigHeader",  "RunHeaders");
+
+
+  write1.AddContainer("MMcEvt",        "Events");
+  write1.AddContainer("MHillas",       "Events");
+  write1.AddContainer("MHillasExt",    "Events");
+  write1.AddContainer("MHillasSrc",    "Events");
+  write1.AddContainer("MImagePar",     "Events");
+  write1.AddContainer("MNewImagePar",  "Events");
+  write1.AddContainer("MConcentration","Events");
+  write1.AddContainer("MPointingPos",  "Events");
+
+  if (OutFilename2)
+    {
+      MWriteRootFile write2(OutFilename2->Data()); // Writes output2
+      write2.AddContainer("MRawRunHeader", "RunHeaders");
+      write2.AddContainer("MMcRunHeader",  "RunHeaders");
+      write2.AddContainer("MSrcPosCam",    "RunHeaders");
+      write2.AddContainer("MGeomCam",      "RunHeaders");
+      write2.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+      write2.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+      write2.AddContainer("MMcFadcHeader",  "RunHeaders");
+      write2.AddContainer("MMcTrigHeader",  "RunHeaders");
+
+
+      write2.AddContainer("MMcEvt",        "Events");
+      write2.AddContainer("MHillas",       "Events");
+      write2.AddContainer("MHillasExt",    "Events");
+      write2.AddContainer("MHillasSrc",    "Events");
+      write2.AddContainer("MImagePar",     "Events");
+      write2.AddContainer("MNewImagePar",  "Events");
+      write2.AddContainer("MConcentration","Events");
+      write2.AddContainer("MPointingPos",  "Events");
+
+      //
+      // Divide output in train and test samples, using the event number
+      // (odd/even) to achieve otherwise unbiased event samples:
+      //
+      
+      MF filter1("{MMcEvt.fEvtNumber%2}>0.5");
+      MF filter2("{MMcEvt.fEvtNumber%2}<0.5");
+
+      write1.SetFilter(&filter1);
+      write2.SetFilter(&filter2);
+    }
+
+  //
+  // First loop: Calibration loop
+  //
+
+
+  MProgressBar bar;
+  bar.SetWindowName("Calibrating...");
+
+  MEvtLoop evtloop;
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (CalibrationFilename)
+    {
+      if (!evtloop.Eventloop())
+	return;
+      mccalibcalc->GetHistADC2PhotEl()->Write();
+      mccalibcalc->GetHistPhot2PhotEl()->Write();
+    }
+
+  //
+  // Second loop: analysis loop
+  //
+
+  //
+  // Change the read task by another one which reads the file we want to analyze:
+  //
+
+  MReadMarsFile read2("Events");
+  read2.AddFile(AnalysisFilename);
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read);
+  tlist.RemoveFromList(&read);
+
+  tlist.AddToListBefore(&clean2, &clean);
+  tlist.RemoveFromList(&clean);
+
+  //
+  // Analyzed only the desired fraction of events, skip the rest:
+  //
+  MFEventSelector eventselector;
+  Float_t rejected_fraction = 1. - accepted_fraction; 
+  eventselector.SetSelectionRatio(rejected_fraction);
+  MContinue skip(&eventselector);
+  tlist.AddToListBefore(&skip, &sigextract);
+
+  bar.SetWindowName("Analyzing...");
+
+  tlist.RemoveFromList(&mccalibcalc); // Removes calibration task from list.
+
+  hcalc.Enable(MHillasCalc::kCalcHillasSrc);
+
+  // Add tasks to write output:
+
+  if (OutFilename2)
+    {
+      tlist.AddToList(&filter1);
+      tlist.AddToList(&filter2);
+      tlist.AddToList(&write2); 
+    }
+
+  tlist.AddToList(&write1); 
+
+  if (!evtloop.Eventloop())
+    return;
+
+
+  tlist.PrintStatistics();
+}
Index: branches/Mars_McMismatchStudy/macros/starmc2.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/starmc2.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/starmc2.C	(revision 17960)
@@ -0,0 +1,148 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Abelardo Moralejo 1/2004 <mailto:moralejo@pd.infn.it>
+   !              Thomas Bretz  5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2004
+   !
+   !
+   \* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STARMC2 - STandard Analysis and Reconstruction (MC example)
+//
+//  This macro converts into image  parameters an input file of MC data 
+//  previously calibrated (see mccalibrate.C).
+//  
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MImgCleanStd.h"
+
+void starmc2()
+{
+  //  Char_t* AnalysisFilename = "calibrated_gamma_train.root"; // File to be analyzed
+  Char_t* AnalysisFilename = "calibrated_gamma_test.root"; // File to be analyzed
+
+  TString* OutFilename;
+
+  // Output file name
+  //  OutFilename = new TString("star_gamma_train.root");   // Output file name
+  OutFilename = new TString("star_gamma_test.root");   // Output file name
+
+  MImgCleanStd      clean(10., 5.); // Applies tail cuts to image.
+  clean.SetMethod(MImgCleanStd::kAbsolute);
+
+  // WARNING: the tightness of the tail cuts depends on the signal extraction method
+  // used in mccalibrate.C!! (some methods result in positively biased signals)
+
+  // ------------------------------------------------------------------
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  MSrcPosCam src;
+  //
+  // FOR WOBBLE MODE!! Set source position on camera here.
+  //  src.SetX(120.);  
+  // units: mm. This 120 mm correspond to MC wobble mode w+ for zbin>0
+  //
+
+  src.SetReadyToSave();
+
+  plist.AddToList(&src);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+
+  read.AddFile(AnalysisFilename);
+  read.DisableAutoScheme();
+
+
+  MHillasCalc       hcalc; // Calculates Hillas parameters not dependent on source position.
+  hcalc.Enable(MHillasCalc::kCalcHillasSrc);
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&clean);
+  tlist.AddToList(&hcalc);
+
+  //
+  // Open output file(s):
+  //
+  MWriteRootFile write(OutFilename->Data()); // Writes output   
+  //
+  // Add MC containers only if they exist. 
+  // In this way you can also run on real calibrated data.
+  //
+  write.AddContainer("MRawRunHeader", "RunHeaders");
+  write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MGeomCam",      "RunHeaders", kFALSE);
+  write.AddContainer("MMcConfigRunHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE);
+  write.AddContainer("MMcFadcHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MMcTrigHeader",  "RunHeaders", kFALSE);
+       
+  write.AddContainer("MMcEvt",        "Events", kFALSE);
+  write.AddContainer("MPointingPos",  "Events", kFALSE);
+  write.AddContainer("MMcTrig",       "Events", kFALSE);
+  write.AddContainer("MSrcPosCam",    "Events", kFALSE);
+  write.AddContainer("MRawEvtHeader", "Events");
+  write.AddContainer("MHillas",       "Events");
+  write.AddContainer("MHillasExt",    "Events");
+  write.AddContainer("MHillasSrc",    "Events");
+  write.AddContainer("MImagePar",     "Events");
+  write.AddContainer("MNewImagePar",  "Events");
+  write.AddContainer("MConcentration","Events");
+
+  //
+  // Next line makes that the tree "OriginalMC" containing the MMcEvtBasic
+  // container for all produced Corsika events from which the events in the
+  // normal "Events" tree derive:
+  //
+  write.AddCopySource("OriginalMC");
+
+  tlist.AddToList(&write);
+
+  //
+  // analysis loop
+  //
+
+  MEvtLoop evtloop;
+  MProgressBar bar;
+  bar.SetWindowName("Analyzing...");
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (!evtloop.Eventloop())
+    return;
+
+  tlist.PrintStatistics();
+
+  return;
+}
Index: branches/Mars_McMismatchStudy/macros/starmcstereo.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/starmcstereo.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/starmcstereo.C	(revision 17960)
@@ -0,0 +1,367 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!
+!   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
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void starmcstereo(Int_t ct1 = 1, Int_t ct2 = 2)
+{
+  // ------------- user change -----------------
+
+  TString* CalibrationFilename = 0;
+
+  // Calibration file: a file with no added noise. Comment out next line if you
+  // do not want to calibrate the data (means SIZE will be in ADC counts)
+
+  CalibrationFilename = new TString("nonoise/Gamma_20_0_7_200000to200009_XX_w0.root");
+
+  Char_t* AnalysisFilename = "Gamma_20_0_7_*_XX_w0.root";  // File to be analyzed
+  Char_t* OutFileTag      = "gammas";           // Output file tag
+
+  // First open input files to check that the required telescopes 
+  // are in the file, and get telescope coordinates.
+
+  TChain *rh = new TChain("RunHeaders");
+  rh->Add(AnalysisFilename);
+  MMcCorsikaRunHeader *corsrh = new MMcCorsikaRunHeader();
+  rh->SetBranchAddress("MMcCorsikaRunHeader.", &corsrh);
+  rh->GetEvent(0); 
+  // We assume that all the read files will have the same telescopes inside, 
+  // so we look only into the first runheader.
+  Int_t allcts = corsrh->GetNumCT();
+  if (ct1 >  allcts || ct2 >  allcts)
+    {
+      cout << endl << "Wrong CT id number, not contained in input file!" << endl;
+      return;
+    }
+  // Set telescope coordinates as read from first runheader:
+  Float_t ctx[2];
+  Float_t cty[2];
+  ctx[0] = ((*corsrh)[ct1-1])->GetCTx();
+  cty[0] = ((*corsrh)[ct1-1])->GetCTy();
+  ctx[1] = ((*corsrh)[ct2-1])->GetCTx();
+  cty[1] = ((*corsrh)[ct2-1])->GetCTy();
+
+  // Now find out number of pixels in each camera:
+  MMcConfigRunHeader* confrh1 = new MMcConfigRunHeader();
+  MMcConfigRunHeader* confrh2 = new MMcConfigRunHeader();
+  rh->SetBranchAddress("MMcConfigRunHeader;1.", &confrh1);
+  rh->SetBranchAddress("MMcConfigRunHeader;2.", &confrh2);
+  rh->GetEvent(0);
+  Int_t npix[2];
+  npix[0] = confrh1->GetNumPMTs();
+  npix[1] = confrh2->GetNumPMTs();
+
+  rh->Delete();
+
+
+  Int_t CT[2] = {ct1, ct2};  // Only 2-telescope analysis for the moment
+  Int_t NCTs = 2;
+
+
+  // ------------- user change -----------------
+
+  Float_t BinsHigh[2] = {0, 79};
+  Float_t BinsLow[2]  = {0, 79};  // FADC slices (2GHz sampling)
+  Float_t CleanLev[2] = {7., 5.}; // Units: phes (absolute cleaning will be used later!) 
+  // Tail cuts for the analysis loop. In the first (calibration) loop they will not 
+  // be used; we run over a noiseless file and we want to accept all pixels with any 
+  // number of phes.
+
+
+  MImgCleanStd**     clean = new MImgCleanStd*[NCTs];  
+
+  MImgCleanStd* clean[0] = new MImgCleanStd(1.,1.);
+  MImgCleanStd* clean[1] = new MImgCleanStd(1.,1.); 
+  // Just dummy levels. Since the calibration file will be a noiseless file, RMS of 
+  // pedestal will be 0, and all events will be accepted, regardless of the cleaning level.
+  // For some reason the above lines do not work if made on a loop! (???)
+  clean[0]->SetSerialNumber(CT[0]);
+  clean[1]->SetSerialNumber(CT[1]);
+
+  MExtractTimeAndChargeSpline* sigextract = new MExtractTimeAndChargeSpline[NCTs];
+  MMcCalibrationUpdate*  mccalibupdate = new MMcCalibrationUpdate[NCTs];
+  MCalibrateData* calib = new MCalibrateData[NCTs];
+  MMcCalibrationCalc* mccalibcalc = new MMcCalibrationCalc[NCTs];
+
+  // -------------------------------------------
+  // 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];
+
+  Float_t hi2lowratio = 10.0;
+
+  for (Int_t i = 0; i < NCTs; i++)
+    {
+      TString s = "MSrcPosCam;";
+      s += CT[i];
+      src[i].SetName(s);
+      src[i].SetReadyToSave();
+      plist.AddToList(&(src[i]));
+
+      TString b = "MBadPixelsCam;";
+      b += CT[i];
+      badpix[i].SetName(b);
+      badpix[i].InitSize(npix[i]);
+      badpix[i].SetReadyToSave();
+      plist.AddToList(&(badpix[i]));
+
+      sigextract[i].SetSerialNumber(CT[i]);
+      sigextract[i].SetRange(BinsHigh[0], BinsHigh[1], BinsLow[0], BinsLow[1]);
+      sigextract[i].SetRiseTimeHiGain(0.5);
+      sigextract[i].SetFallTimeHiGain(0.5);
+      sigextract[i].SetLoGainStretch(1.);
+
+      mccalibupdate[i].SetSerialNumber(CT[i]);
+      mccalibupdate[i].SetUserLow2HiGainFactor(hi2lowratio);
+      mccalibupdate[i].SetSignalType(MCalibrateData::kPhe);
+
+      calib[i].SetSerialNumber(CT[i]);
+      calib[i].SetCalibConvMinLimit(0.);
+      calib[i].SetCalibConvMaxLimit(100.); // Override limits for real data  
+      calib[i].SetCalibrationMode(MCalibrateData::kFfactor);
+      // Do not change CalibrationMode (just indicates where the cal. constants will be stored)
+      calib[i].SetSignalType(mccalibupdate[i].GetSignalType());
+
+      mccalibcalc[i].SetSerialNumber(CT[i]);
+      mccalibcalc[i].SetMinSize(200); 
+      // Minimum SIZE for an event to be used in the calculation of calibration constants.
+      // Units are ADC counts, and value depends on signal extractor!
+    }
+
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+
+  if (CalibrationFilename)
+    read.AddFile(CalibrationFilename->Data());
+
+
+  MGeomApply*        apply = new MGeomApply[NCTs];
+  MMcPedestalCopy*   pcopy = new MMcPedestalCopy[NCTs];
+  MHillasCalc*       hcalc = new MHillasCalc[NCTs];
+
+  TString outfile = "star_";
+  outfile += CT[0];
+  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];
+  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]);
+
+      hcalc[i]->SetSerialNumber(CT[i]);
+      hcalc[i].Disable(MHillasCalc::kCalcHillasSrc); 
+      // Source-dependent parameters not needed in the first loop (calibration)
+
+      write1.SetSerialNumber(CT[i]);
+      write2.SetSerialNumber(CT[i]);
+
+      write1.AddContainer("MMcEvt",       "Events");
+      write1.AddContainer("MHillas",      "Events");
+      write1.AddContainer("MHillasExt",   "Events");
+      write1.AddContainer("MHillasSrc",   "Events");
+      write1.AddContainer("MNewImagePar", "Events");
+      write1.AddContainer("MSrcPosCam",   "Events");
+      write2.AddContainer("MMcEvt",       "Events");
+      write2.AddContainer("MHillas",      "Events");
+      write2.AddContainer("MHillasExt",   "Events");
+      write2.AddContainer("MHillasSrc",   "Events");
+      write2.AddContainer("MNewImagePar", "Events");
+      write2.AddContainer("MSrcPosCam",   "Events");
+    }
+
+  MStereoPar* mstereo = new MStereoPar;
+  plist.AddToList(mstereo);
+
+  write1.AddContainer(mstereo, "Events");
+  write2.AddContainer(mstereo, "Events");
+  // We use MWriteRootFile::AddContainer(MParContainer* ,...) instead
+  // of using the container name as above, because in the former case the 
+  // serial number tag (indicating the telescope id) is added to the 
+  // container name, which is fine for containers of which there is one
+  // per telescope. However, the container MStereoPar is unique, since it
+  // is filled with information coming from both telescopes.
+
+  write1.AddContainer("MRawRunHeader", "RunHeaders");
+  write1.AddContainer("MMcRunHeader",  "RunHeaders");
+
+  write2.AddContainer("MRawRunHeader", "RunHeaders");
+  write2.AddContainer("MMcRunHeader",  "RunHeaders");
+
+  tlist.AddToList(&read);
+
+  // Skip untriggered events (now camera simulation output contains by default all simulated events)
+  MContinue* trigger = new MContinue("(MMcTrig;1.fNumFirstLevel<1) && (MMcTrig;2.fNumFirstLevel<1)","Events");
+  tlist.AddToList(trigger);
+
+  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(&(mccalibcalc[i]));
+    }
+
+
+  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);
+
+  //
+  // Create and set up the eventloop
+  //
+  MProgressBar bar;
+  bar.SetWindowName("Calibrating");
+
+  MEvtLoop evtloop;
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  //
+  // First loop: calibration loop. Go over MC events simulated with 
+  // no noise, to correlate SIZE with the number of phes and get the
+  // conversion factor (this is done by MMcCalibrationCalc).
+  //
+  if (CalibrationFilename)
+    {
+      if (!evtloop.Eventloop())
+	return;
+    }
+
+  tlist.PrintStatistics();
+
+  ///////////////////////////////////////////////////////////////////////
+
+
+  // Now prepare the second loop: go over the events you want to analyze.
+  // This time the MMcCalibrationUpdate tasks will apply the previously
+  // calculated calibration factors.
+
+  // First substitute the reading task:
+  MReadMarsFile read2("Events");
+  read2.AddFile(AnalysisFilename);  
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read);
+  tlist.RemoveFromList(&read);
+
+  // Delete cleaning tasks and create new ones with absolute cleaning method:
+    for (Int_t i= 0; i < NCTs; i++ )
+    {
+      tlist.RemoveFromList(clean[i]);
+      delete clean[i];
+    }
+
+  // New cleaning tasks:
+  clean[0] = new MImgCleanStd(CleanLev[0], CleanLev[1]);
+  clean[1] = new MImgCleanStd(CleanLev[0], CleanLev[1]);
+  clean[0]->SetMethod(MImgCleanStd::kAbsolute); 
+  clean[1]->SetMethod(MImgCleanStd::kAbsolute); 
+  clean[0]->SetSerialNumber(CT[0]);
+  clean[1]->SetSerialNumber(CT[1]);
+  tlist.AddToListBefore(clean[0],&(hcalc[0]));
+  tlist.AddToListBefore(clean[1],&(hcalc[1]));
+
+  tlist.RemoveFromList(&(mccalibcalc[0]));
+  tlist.RemoveFromList(&(mccalibcalc[1])); // Remove calibration tasks from list.
+
+  // Now calculate also source-dependent Hillas parameters:
+  for (i = 0; i < NCTs; i++)
+    hcalc[i].Enable(MHillasCalc::kCalcHillasSrc);
+
+  // Add task to calculate stereo parameters:
+  MStereoCalc stereocalc;
+  stereocalc.SetCTids(CT[0],CT[1]);
+  stereocalc.SetCT1coor(ctx[0],cty[0]);
+  stereocalc.SetCT2coor(ctx[1],cty[1]);
+  tlist.AddToList(&stereocalc);
+
+  // Add writing tasks:
+  tlist.AddToList(&filter1);
+  tlist.AddToList(&write1);
+  tlist.AddToList(&filter2);
+  tlist.AddToList(&write2);
+
+  bar.SetWindowName("Analyzing");
+
+  if (!evtloop.Eventloop())
+    return;
+
+  tlist.PrintStatistics();
+
+  for (Int_t i= 0; i < NCTs; i++ )
+    delete clean[i];
+
+  plist.FindObject("MCalibrationChargeCam;1")->Write();
+  plist.FindObject("MCalibrationChargeCam;2")->Write();
+
+  plist.FindObject("MCalibrationQECam;1")->Write();
+  plist.FindObject("MCalibrationQECam;2")->Write();
+
+  return;
+}
Index: branches/Mars_McMismatchStudy/macros/starvisday.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/starvisday.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/starvisday.C	(revision 17960)
@@ -0,0 +1,195 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2006
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// starvisday.C
+//
+// displays the star visibility of several stars for one day
+//
+// See the code for ducumentation and setup
+//
+///////////////////////////////////////////////////////////////////////////
+
+void zoom()
+{
+    TH1 *h = (TH1*)gPad->FindObject("frame");
+    if (!h)
+        return;
+
+    Int_t mjd = TMath::FloorNint(h->GetXaxis()->GetXmin());
+
+    h->GetXaxis()->SetRangeUser(mjd+0.33*3600*24, mjd+0.85*3600*24);
+    h->GetYaxis()->SetRangeUser(35, 90);
+
+    gPad->Modified();
+    gPad->Update();
+}
+
+
+void starvisday()
+{
+    // Date (UTC) for which to get the visibility plot
+    MTime time(-1); // -1 means NOW
+
+    // Setup a different time as you like
+    // time.Set(2006, 12, 20);
+
+    // Current observatory (see class reference of MObservatory)
+    const MObservatory obs(MObservatory::kMagic1);
+
+    // The class contaning the catalog
+    MAstroCatalog stars;
+    stars.SetObservatory(obs);
+    stars.SetTime(time);
+
+    // Read the stars from a star catalog. The catalogs can be downloaded
+    // from the Mars web page. For more information see class reference.
+    stars.ReadXephem("magic_favorites.edb");
+
+    // Mark the stars you would like to display (see the names in the catalog)
+    stars.MarkObject("CrabNebula");
+    stars.MarkObject("1ES1218+304");
+    stars.MarkObject("1ES1426+428");
+    stars.MarkObject("Mrk421");
+    // stars.MarkObject("Mrk501");
+    // stars.MarkObject("1ES1959+650");
+    // stars.MarkObject("1ES2344+514");
+    stars.MarkObject("M87");
+
+    // --------------------------------------------------------------------------
+    //
+    //  Start producing the nice plot
+    //
+
+    // open and setup a new canvas
+    TCanvas *c = new TCanvas;
+    c->SetBorderMode(0);
+    c->SetFillColor(kWhite);
+    c->SetFrameBorderMode(0);
+    c->SetFrameFillStyle(0);
+
+    c->SetGridx();
+    c->SetGridy();
+
+    // Setup the TGraph which is drawn
+    TGraph g;
+    g.SetTitle(Form("Visibility at %s, %s (MOON=%.1f%%)",
+                    obs.GetObservatoryName().Data(),
+                    time.GetStringFmt("%A %e.%B %Y").Data(),
+                    MAstro::GetMoonPhase(time.GetMjd())*100)
+              );
+    g.SetLineWidth(2);
+
+    // ===================
+    // Set graph name to object name
+    g.SetName("Moon");
+
+    // produce visibility curve
+    stars.GetVisibilityCurve(g, "Moon");
+
+    // Draw Frame
+    TH1F *hist = g.GetHistogram();
+    hist->SetName("frame");
+    hist->DrawCopy();
+
+    // Get x-range
+    TAxis *axex = g.GetXaxis();
+    Float_t mn = axex->GetBinLowEdge(axex->GetFirst());
+    Float_t mx = axex->GetBinUpEdge(axex->GetLast());
+
+    // Draw the twilight and dark time
+    TBox box;
+
+    for (int i=3; i>=0; i--)
+    {
+        double set = obs.GetSunRiseSet(time.GetMjd()-1, -6*i)[1];
+        double ris = obs.GetSunRiseSet(time.GetMjd(),   -6*i)[0];
+
+        box.SetFillStyle(3001);
+        box.SetFillColor(kGray+3-i);
+        box.DrawBox(mn, 5, MTime(set).GetAxisTime(), 90);
+        box.DrawBox(MTime(ris).GetAxisTime(), 5, mx, 90);
+        box.DrawBox(MTime(set).GetAxisTime(), 15+(i+1)*10,
+                    MTime(ris).GetAxisTime(),  5)+i*10;
+    }
+
+    // Draw TGraph for Moon
+    g.SetFillStyle(3003);
+    g.SetFillColor(kRed+1);
+    g.SetLineColor(kRed+1);
+    g.SetLineWidth(1);
+    g.SetLineStyle(kDotted);
+    g.DrawClone("bc")->SetBit(kCanDelete);
+    g.SetLineWidth(2);
+
+    // ===================
+
+    // Some helper to iterate these three colors
+    Int_t col[] = { kBlack, kBlue, kRed+1, kMagenta+1, kGreen+2 };
+
+    // Loop over all stars in the catalog
+    int k=0;
+    TIter Next(stars.GetList());
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        // Check if the star was previously marked
+        if (!o->TestBit(1<<14))
+            continue;
+
+        // Set graph name to object name
+        g.SetName(o->GetName());
+
+        // produce visibility curve
+        stars.GetVisibilityCurve(g);
+
+        // Setup color and style of TGraph
+        g.SetLineColor(col[k%5]);
+        g.SetLineStyle(1+k/3);
+
+        // Draw TGraph
+        g.DrawClone("c")->SetBit(kCanDelete);
+
+        // Search for culmination
+        Long64_t max = TMath::LocMax(g.GetN(), g.GetY());
+
+        // Setup description
+        TText txt;
+        txt.SetTextFont(102);
+        txt.SetTextSize(0.03);
+        txt.SetTextColor(g.GetLineColor());
+
+        // draw name at culmination
+        txt.DrawText(g.GetX()[max]-1.0*3600, g.GetY()[max]+1, o->GetName());
+
+        k++;
+    }
+
+    c->Modified();
+    c->Update();
+
+    TButton *but = new TButton("zoom", "zoom()", 0.88, 0.95, 0.99, 0.99);
+    but->Draw();
+}
Index: branches/Mars_McMismatchStudy/macros/starvisyear.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/starvisyear.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/starvisyear.C	(revision 17960)
@@ -0,0 +1,215 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2006
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// starvisyear.C
+//
+// displays the star visibility along one year
+//
+// See the code for ducumentation and setup
+//
+///////////////////////////////////////////////////////////////////////////
+
+#include <TString.h>
+#include <TCanvas.h>
+#include <TH2D.h>
+#include <TGraph.h>
+
+#include "MObservatory.h"
+#include "MTime.h"
+#include "MAstro.h"
+#include "MAstroSky2Local.h"
+#include "MVector3.h"
+#include "MH.h"
+
+
+void starvisyear()
+{
+    // Setup the observatory location (see MObservatory for details)
+    MObservatory obs(MObservatory::kMagic1);;
+
+    // Setup the start time of the year (365 days) to be displayed
+    MTime time(-1);  // -1 mean NOW
+
+    // Setup a different time if you like
+    time.Set(2006, 1, 1, 0);
+
+    // Setup right ascension and declination of the source to display
+    //Crab
+    const Double_t ra  = MAstro::Hms2Rad(5, 34, 31.9);
+    const Double_t dec = MAstro::Dms2Rad(22, 0, 52.0);
+
+    cout << obs.Print() << endl;
+
+    return;
+
+    // Setup the name of the source
+    TString source("CrabNebula");
+
+    // Setup palette you would like to see (99 is fixed)
+    // for more details see MH::SetPalette
+    MH::SetPalette("glow2", 99);
+
+    // --------------------------------------------------------------------------
+    //
+    //  Start producing the data for the plot
+    //
+
+    // Setup the source in the appropriate format
+    MVector3 v;
+    v.SetRaDec(ra, dec);
+
+    // For simplicity get mjd of time
+    Double_t mjd = time.GetMjd();
+
+    // Setup axis ranges
+    Double_t first = time.GetAxisTime();
+    Double_t last  = MTime(mjd+365).GetAxisTime();
+
+    Int_t h0 = 13-obs.GetLongitudeDeg()/15;
+
+    // Define histograms
+    TH2D hist( "1", "", 365, first, last, 24*12, first+h0*60*60, first+(h0+24)*60*60);//h0/24.+1, (h0+24)/24.+1);
+    TH2D hmoon("2", "", 365, first, last, 24*12, first+h0*60*60, first+(h0+24)*60*60);//h0/24.+1, (h0+24)/24.+1);
+
+    // Fill histograms
+    TGraph sunset[4], sunrise[4];
+    for (int x=0; x<365; x++)
+    {
+        // Get moon phase and axis time for mjd+x
+        Double_t moon = MAstro::GetMoonPhase(mjd+x);
+        Double_t tmx  = MTime(mjd+x).GetAxisTime();
+
+        // get sunrise and sunset for the current day
+        Double_t sunst[4], sunri[4];
+        for (int i=0; i<4; i++)
+        {
+            // get sunset and sunrise of next day
+            sunri[i] = obs.GetSunRiseSet(mjd+x+1,-18+6*i)[0];
+            sunst[i] = obs.GetSunRiseSet(mjd+x,  -18+6*i)[1];
+
+            // fill both into the TGraphs
+            sunset[i].SetPoint( sunset[i].GetN(),  tmx, MTime(sunst[i]).GetAxisTime()-x*24*60*60);
+            sunrise[i].SetPoint(sunrise[i].GetN(), tmx, MTime(sunri[i]).GetAxisTime()-x*24*60*60);
+        }
+
+        // If nautical twilight doesn't take place skip the rest
+        if (sunri[1]<0 || sunst[1]<0)
+            continue;
+
+        // Now calculate in steps of five minutes
+        for (int hor=0; hor<24*12; hor++)
+        {
+            Double_t hr = hor/12. + h0;
+            Double_t offset = x + hr/24.;
+
+            // mjd of the current time
+            MTime tm(mjd+offset);
+
+            // Check if current time is within darkness
+            if (tm.GetMjd()>sunri[1] || tm.GetMjd()<sunst[1])
+                continue;
+
+            // Initialize conversion from sky coordinates to local coordinates
+            MAstroSky2Local conv(tm.GetGmst(), obs);
+
+            // get moon position on the sky
+            Double_t moonra, moondec;
+            MAstro::GetMoonRaDec(tm.GetMjd(), moonra, moondec);
+
+            // calculate moon position as seen by the telescope
+            v.SetRaDec(moonra, moondec);
+            v *= conv;
+
+            // check if moon is above or below horizont
+            if (v.Theta()*TMath::RadToDeg()<90)
+                moon = 0;
+
+            // fill moon visibility into histpogram
+            hmoon.SetBinContent(x+1, hor+1, moon);
+
+            // calculate source position as seen by the telescope
+            v.SetRaDec(ra, dec);
+            v *= conv;
+
+            // fill altitude of source into histogram
+            hist.SetBinContent(x+1, hor+1, v.Theta()*TMath::RadToDeg());
+        }
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    //  Start producing the nice plot
+    //
+
+    // Setup canvas
+    TCanvas *c = new TCanvas;
+    c->SetBorderMode(0);
+    c->SetGridx();
+    c->SetGridy();
+
+    // Setup histogram
+    TString name = obs.GetObservatoryName();
+    hist.SetTitle(Form("Zenith distance of %s at %s", source.Data(), name.Data()));
+
+    hist.SetXTitle("Day");
+    hist.SetYTitle("UTC");
+
+    hist.GetXaxis()->CenterTitle();
+    hist.GetYaxis()->CenterTitle();
+
+    hist.GetXaxis()->SetTimeFormat("%d/%m/%y %F1995-01-01 00:00:00 GMT");
+    hist.GetXaxis()->SetTimeDisplay(1);
+    hist.GetXaxis()->SetLabelSize(0.033);
+
+    hist.GetYaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    hist.GetYaxis()->SetTimeDisplay(1);
+    hist.GetYaxis()->SetLabelSize(0.033);
+    hist.GetYaxis()->SetTitleOffset(1.3);
+
+    hist.SetContour(99);
+    hist.SetMinimum(0);
+    hist.SetMaximum(90);
+
+    hist.SetStats(kFALSE);
+
+    // draw histograms
+    hist.DrawCopy("colz");
+    hmoon.DrawCopy("scat=7 same");
+
+    // Draw rise and set time of sun
+    Int_t style[] = { kSolid, 5, 4, kDotted };
+    for (int i=0; i<4; i++)
+    {
+        sunset[i].SetLineColor(kBlue);
+        sunrise[i].SetLineColor(kBlue);
+        sunset[i].SetLineWidth(2);
+        sunrise[i].SetLineWidth(2);
+        sunset[i].SetLineStyle(style[i]);
+        sunrise[i].SetLineStyle(style[i]);
+        sunset[i].DrawClone("L");
+        sunrise[i].DrawClone("L");
+    }
+}
Index: branches/Mars_McMismatchStudy/macros/status.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/status.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/status.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tar.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tar.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tar.C	(revision 17960)
@@ -0,0 +1,65 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// tar.C
+// =====
+//
+// Service script. used to create the tar archive for an release. It makes
+// sure that the correct files are included and the name of the archive is
+// the name of the current directory (+.tar.gz)
+//
+///////////////////////////////////////////////////////////////////////////
+void tar()
+{
+    TString dir = gSystem->pwd();
+
+    Int_t slash = dir.Last('/');
+
+    TString name = &dir[slash+1];
+
+    if (!gSystem->AccessPathName("../"+name+".tar"))
+    {
+        cout << "File '../" << name << ".tar' existing." << endl;
+        return;
+    }
+
+    if (!gSystem->AccessPathName("../"+name+".tar.gz"))
+    {
+        cout << "File '../" << name << ".tar.gz' existing." << endl;
+        return;
+    }
+
+    gSystem->cd("..");
+
+    TString cmd = "tar cvf "+name+".tar --exclude=Makefile.depend --exclude=Root --exclude=Tag --exclude=mtemp "+name+"/.rootrc "+name+"/*";
+
+    cout << "Executing: " << cmd << endl;
+
+    gSystem->Exec(cmd);
+    gSystem->Exec("gzip -9 "+name+".tar");
+
+    gSystem->cd(name);
+}
Index: branches/Mars_McMismatchStudy/macros/test/extralgospline.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/test/extralgospline.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/test/extralgospline.C	(revision 17960)
@@ -0,0 +1,69 @@
+void extralgospline()
+{
+    Int_t n = 40;
+
+    TArrayF x(n);
+    TArrayF y(n);
+    for (int i=0; i<n; i++)
+    {
+        x[i] = i;
+        y[i] = gRandom->Uniform(10)-5;
+
+        y[n/2-2] = 50;
+        y[n/2-1] = 100;
+        y[n/2]   = 110;
+        y[n/2+1] = 70;
+        y[n/2+2] = 30;
+
+    }
+
+    TArrayF d1(n);
+    TArrayF d2(n);
+
+    // Do some handling if maxpos is last slice!
+    MExtralgoSpline s(y.GetArray(), n, d1.GetArray(), d2.GetArray());
+
+    s.SetHeightTm(0.5);
+    s.SetRiseFallTime(0.5, 0.5);
+
+    Int_t maxpos = TMath::LocMax(n, y.GetArray());
+
+    Float_t time, dtime, sum, dsum, mtime, max;
+    s.SetExtractionType(MExtralgoSpline::kIntegralRel);
+    s.Extract(0, maxpos);
+    s.GetTime(time, dtime);
+    s.GetSignal(sum, dsum);
+
+    s.SetExtractionType(MExtralgoSpline::kAmplitude);
+    s.Extract(0, maxpos);
+    s.GetTime(mtime, dtime);
+    s.GetSignal(max, dsum);
+
+    TGraph gr1(n, x.GetArray(), y.GetArray());
+
+    TGraph gr2;
+    for (int i=0; i<n*10; i++)
+        gr2.SetPoint(gr2.GetN(), 0.1*i, s.EvalAt(0.1*i));
+
+    gr2.SetMarkerColor(kBlue);
+    gr2.SetMarkerStyle(kFullDotMedium);
+    gr1.SetMarkerStyle(kFullDotMedium);
+
+    gr1.DrawClone("AP*");
+    gr2.DrawClone("PL");
+
+    TMarker m;
+    m.SetMarkerStyle(kFullDotMedium);
+    m.SetMarkerColor(kRed);
+    m.DrawMarker(x[maxpos], y[maxpos]);
+
+    TLine line;
+    line.SetLineColor(kRed);
+    line.DrawLine(mtime, max-5, mtime, max+5);
+    line.DrawLine(mtime-0.5, max, mtime+0.5, max);
+    line.SetLineStyle(kDashed);
+    line.DrawLine(time, 0, time, 110);
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+}
Index: branches/Mars_McMismatchStudy/macros/threshold.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/threshold.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/threshold.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/train/traincuts.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/train/traincuts.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/train/traincuts.C	(revision 17960)
@@ -0,0 +1,109 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2010 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// traincuts.C
+// ===========
+//
+// For more details see the class description of MJTrainCuts
+//
+/////////////////////////////////////////////////////////////////////////////
+void traincuts()
+{
+    // Instantiate class
+    MJTrainCuts opt;
+    //opt.SetDebug();
+
+    // These are control parameters how to train the random forest (use with care!)
+    //opt.SetNumTrees(100);
+    //opt.SetNdSize(5);
+    //opt.SetNumTry(0);
+
+    // Setup datasets
+    MDataSet seton ("dataset_on.txt");
+    MDataSet setoff("dataset_off.txt");
+
+    opt.SetDataSetOn(seton);
+    opt.SetDataSetOff(setmix);
+
+    // Define the parameters you want the random forest to use
+    Int_t p00 = opt.AddParameter("MHillas.fSize");
+    Int_t p01 = opt.AddParameter("MHillas.GetArea*MGeomCam.fConvMm2Deg^2");
+    Int_t p02 = opt.AddParameter("MHillasSrc.fDist*MGeomCam.fConvMm2Deg");
+    Int_t p03 = opt.AddParameter("MHillasExt.fTimeSpreadWeighted");
+    Int_t p04 = opt.AddParameter("MHillasExt.fSlopeSpreadWeighted");
+
+    Int_t p05 = opt.AddParameter("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg");
+    Int_t p06 = opt.AddParameter("MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)*MGeomCam.fConvMm2Deg");
+
+    // A selection of more parameters
+    //    Int_t p07 = opt.AddParameter("MNewImagePar.fLeakage1");
+    //    Int_t p08 = opt.AddParameter("MNewImagePar.fLeakage2");
+    //    Int_t p09 = opt.AddParameter("MNewImagePar.fConcCOG");
+    //    Int_t p10 = opt.AddParameter("MNewImagePar.fConcCore");
+    //    Int_t p11 = opt.AddParameter("MNewImagePar.fConc1");
+    //    Int_t p12 = opt.AddParameter("MNewImagePar.fUsedArea*MGeomCam.fConvMm2Deg^2");
+    //    Int_t p13 = opt.AddParameter("MNewImagePar.fCoreArea*MGeomCam.fConvMm2Deg^2");
+
+    // Define the binning for all the parameters
+    //    opt.AddBinning(p00, MBinning(40,   10, 10000, "", "log"));  // Size
+    //    opt.AddBinning(p01, MBinning(40,    0, 0.3));               // Area
+    //    opt.AddBinning(p02, MBinning(50,    0, 2.5));               // Dist
+    //    opt.AddBinning(p03, MBinning(50,    0, 2.5));               // TimeSpreadW
+    //    opt.AddBinning(p04, MBinning(50,    0, 1.0));               // SlopeSpreadW
+    //    opt.AddBinning(p05, MBinning(51,  -12,  12));               // SlopeLong
+    //    opt.AddBinning(p06, MBinning(51, -0.5, 0.5));               // M3Long
+    //    opt.AddBinning(p07, MBinning(50,    0, 0.5));               // Leakage1
+    //    opt.AddBinning(p08, MBinning(50,    0, 0.5));               // Leakage2
+    //    opt.AddBinning(p09, MBinning(50,    0,   1));               // ConcCOG
+    //    opt.AddBinning(p10, MBinning(50,    0,   1));               // ConcCore
+    //    opt.AddBinning(p11, MBinning(50,    0,   1));               // Conc1
+    //    opt.AddBinning(p12, MBinning(50,    0, 0.3));               // UsedArea
+    //    opt.AddBinning(p13, MBinning(50,    0, 0.3));               // CoreArea
+
+    // Define the histograms you want to see by AddHist(x[,y[,z]]);
+    opt.AddHist(p00, p01);    // Area vs Size
+    opt.AddHist(p02, p03);    // TimeSpreadW vs Dist
+    opt.AddHist(p02, p04);    // SlopeSpreadW vs Dist
+    // opt.AddHist(p09);;          // ConcCOG
+
+    // Define additional cuts which are applied after reading the data
+    //opt.AddPreCut("MNewImagePar.fConcCOG>0.1");
+    //opt.AddPreCut("MHillasSrc.fDist*MGeomCam.fConvMm2Deg<2.0");
+
+    // -------------------- Run ----------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    // ------------------------------------------------------
+
+    // Use random forest regression method
+    // opt.EnableRegression();
+
+    // Allows overwrite of existing files
+    // opt.SetOverwrite();
+    opt.Process("rf-cuts.root");
+}
Index: branches/Mars_McMismatchStudy/macros/train/traindisp.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/train/traindisp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/train/traindisp.C	(revision 17960)
@@ -0,0 +1,190 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== *//////////////////////////////////////////////////////////////////////////////
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// traindisp.C
+// ===========
+//
+// Trains a random forest for disp estimation.
+//
+// The additional code below shows how the MagicCuts can be used in
+// training and testing. There is also code which allows to change the
+// slope of the input spectrum. If a min- or max-break energy is given
+// the new slope is only applied in this region. Further possibilities
+// for additional cuts are shown.
+//
+// SequencesOn:   Monte Carlo Sequences used for training
+// SequencesOff:  Monte Carlo Sequences used for testing
+//
+// Use:
+//  opt.AddPreCut    to use cut for test and training
+//  opt.AddTestCut   to use cut for test only
+//  opt.AddTrainCut  to use cut for train only
+//  opt.AddPreTask   a task executed before filling the matrix/evaluating the RF
+//  opt.AddPostTask  a task executed before training, after evaluating the RF
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void traindisp()
+{
+    MDataSet set("mcsponde/mcdataset-for-training.txt");
+    set.SetNumAnalysis(1);            // Necessary
+
+    // alternatively use:
+    //MDataSet set("mcctesttrain.txt", "/magic/montacrlo/sequences", "/magic/montecarlo/star");
+
+    MJTrainDisp opt;
+    //opt.SetDebug();
+
+    // These are control parameters how to train the random forest (use with care!)
+    //opt.SetNumTrees(100);
+    //opt.SetNdSize(5);
+    //opt.SetNumTry(0);
+
+    // --- Change the theta-cut for the displayed cut-effieincy ---
+    //opt.SetThetaCut(0.16);
+
+    // ------- Parameters to train Random Forest --------
+    opt.AddParameter("MHillas.fLength");
+    opt.AddParameter("MHillas.fWidth");
+    opt.AddParameter("MHillas.fSize");
+    opt.AddParameter("MNewImagePar.fLeakage1");
+    opt.AddParameter("MPointingPos.fZd");
+    opt.AddParameter("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)");
+    //opt.AddParameter("MNewImagePar.fLeakage2");
+    //opt.AddParameter("MNewImagePar.fConc");
+    //opt.AddParameter("MNewImagePar.fConc1");
+    //opt.AddParameter("MNewImagePar.fUsedArea");
+    //opt.AddParameter("MNewImagePar.fCoreArea");
+    //opt.AddParameter("MNewImagePar.fNumUsedPixels");
+    //opt.AddParameter("MNewImagePar.fNumCorePixels");
+    //opt.AddParameter("MImagePar.fSizeSinglePixels");
+    //opt.AddParameter("MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)");
+    //opt.AddParameter("MHillasExt.fAsym*sign(MHillasSrc.fCosDeltaAlpha)");
+
+    // -------------------- Run ----------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    /*
+     // -------------------- Magic-Cuts ----------------------
+     MFMagicCuts cuts;
+     cuts.SetHadronnessCut(MFMagicCuts::kArea);
+     cuts.SetThetaCut(MFMagicCuts::kNone);
+
+     TArrayD arr(13);
+     arr[0]  =  1.15136;
+     arr[1]  =  0.215;
+     arr[2]  =  0.215468;
+     arr[3]  =  5.63973;
+     arr[4]  =  0.0836169;
+     arr[5]  = -0.07;
+     arr[6]  =  7.2;
+     arr[7]  =  0.5;
+     arr[8]  =  0.0681437;
+     arr[9]  =  2.62932;
+     arr[10] =  1.51279;
+     arr[11] =  0.0507821;
+
+     cuts.SetVariables(arr);
+
+     opt.AddTestCut(&cuts);
+
+     // -------------------- Other cuts ----------------------
+     opt.AddPreCut("MNewImagePar.fLeakage1<0.0001");
+     opt.AddPreCut("MHillas.fSize>200");
+     opt.AddPreCut("MHillasSrc.fDCA*MGeomCam.fConvMm2Deg<0.3");
+     opt.AddPreCut("MPointingPos.fZd<25");
+     opt.AddTestCut("MHillasExt.fM3Long   *sign(MHillasSrc.fCosDeltaAlpha)*MGeomCam.fConvMm2Deg>-0.07");
+     opt.AddTestCut("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg<(MHillasSrc.fDist*MGeomCam.fConvMm2Deg-0.5)*7.2");
+
+     // ---------------------- Histogram  --------------------
+     MHn hist("MyHist", "Dist Residual (Disp-Dist)");
+
+     MBinning bins(50, -0.5, 0.5);
+
+     hist.AddHist("MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)*3.37e-3", "Disp.fVal-MHillasSrc.fDist*3.37e-3");
+     hist.InitName("ResM3l;M3Long;ResidualDist");
+     hist.InitTitle(";M3l [\\circ];Disp-Dist [\\circ];");
+     hist.SetDrawOption("colz profx");
+     hist.SetBinnings(&bins);
+
+     hist.AddHist("MHillasExt.fAsym*sign(MHillasSrc.fCosDeltaAlpha)*3.37e-3", "Disp.fVal-MHillasSrc.fDist*3.37e-3");
+     hist.InitName("ResAsym;M3Long;ResidualDist");
+     hist.InitTitle(";Asym [\\circ];Disp-Dist [\\circ];");
+     hist.SetDrawOption("colz profx");
+     hist.SetBinnings(&bins);
+
+     MFillH fill(&hist, "", "FillMyHist");
+     //fill.SetWeight(); // Enable weights to be used to fill this histogram
+     opt.AddTestTask(&fill);
+
+     // -------------------- Energy Slope --------------------
+     // Note, that weight normally doesn't improve anything here.
+     // This is a way to throw away events to a different slope
+     MFEnergySlope slope(-4.0); // New slope for mc spectrum
+     opt.AddPreCut(&slope);     // throw away events to change slope
+
+     // This is a way to weight the events to a different spectrum
+     MMcSpectrumWeight weight;
+     weight.SetFormula("pow(X/300, -2.31-0.26*log10(X/300))");
+     opt.SetWeights(&weight);
+
+     // ------------------ Zd distribution -------------------
+     TFile file("ganymed00001111.root");
+
+     MStatusArray arr;
+     if (arr.Read()<=0)
+        return;
+     TH1D *vstime = (TH1D*)arr.FindObjectInCanvas("Theta",  "TH1D", "OnTime");
+     if (!vstime)
+         return -1;
+
+     MMcSpectrumWeight weight;
+     weight.SetWeightsZd(vstime);
+     opt.AddPreTask(&weight);
+
+     // ------- A trick for testing the parametrization -------
+     // This will overwrite the random forest calculated disp.
+     // Therefore you can test our disp-parametrization.
+     MParameterCalc calc("(1.15136 +"
+                         "0.0681437*MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/3.37e-3 +"
+                         "0.0507821*(log10(MHillas.fSize)-1.51279)^2*(log10(MHillas.fSize)>1.51279) +"
+                         "2.62932*MNewImagePar.fLeakage1)*"
+                         "(1-MHillas.fWidth/MHillas.fLength)");
+     calc.SetNameParameter("Disp");
+     opt.AddPostTask(&calc);
+
+     // ------------------------------------------------------
+    */
+
+     // To allow overwrite of existing files
+     // opt.SetOverwrite();
+
+     // The number is the number of events read from the file
+     // randomly and is the number of events before cuts
+     opt.Train("rf-disp.root", set, 30000);
+}
Index: branches/Mars_McMismatchStudy/macros/train/trainenergy.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/train/trainenergy.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/train/trainenergy.C	(revision 17960)
@@ -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, 11/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== *//////////////////////////////////////////////////////////////////////////////
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// trainenergy.C
+// =============
+//
+// Trains a random forest for energy estimation.
+//
+// The additional code below shows how the MagicCuts can be used in
+// training and testing. There is also code which allows to change the
+// slope of the input spectrum. If a min- or max-break energy is given
+// the new slope is only applied in this region. Further possibilities
+// for additional cuts are shown.
+//
+// SequencesOn:   Monte Carlo Sequences used for training
+// SequencesOff:  Monte Carlo Sequences used for testing
+//
+// Use:
+//  opt.AddPreCut    to use cut for test and training
+//  opt.AddTestCut   to use cut for test only
+//  opt.AddTrainCut  to use cut for train only
+//  opt.AddPreTask   a task executed before filling the matrix/evaluating the RF
+//  opt.AddPostTask  a task executed before training, after evaluating the RF
+//
+/////////////////////////////////////////////////////////////////////////////
+void trainenergy()
+{
+    MDataSet set("mcsponde/mcdataset-for-training.txt");
+    set.SetNumAnalysis(1);            // Necessary
+
+    // alternatively use:
+    //MDataSet set("mcctesttrain.txt", "/magic/montacrlo/sequences", "/magic/montecarlo/star");
+
+    MJTrainEnergy opt;
+    //opt.SetDebug();
+
+    // These are control parameters how to train the random forest (use with care!)
+    //opt.SetNumTrees(100);
+    //opt.SetNdSize(5);
+    //opt.SetNumTry(0);
+
+    // ------- Parameters to train Random Forest --------
+    // The following parameters are the best parameters
+    opt.AddParameter("MHillas.fSize");
+    opt.AddParameter("MHillasSrc.fDist");
+    opt.AddParameter("MPointingPos.fZd");
+    opt.AddParameter("MNewImagePar.fLeakage1");
+    opt.AddParameter("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)");
+    // The influence of these parameters is unclear
+    //opt.AddParameter("MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)");
+    //opt.AddParameter("MNewImagePar.fConcCOG");
+    //opt.AddParameter("MHillas.GetArea");
+    //opt.AddParameter("MNewImagePar.fConc1");
+    //opt.AddParameter("MNewImagePar.fConc");
+    //opt.AddParameter("MNewImagePar.fUsedArea");
+    //opt.AddParameter("MNewImagePar.fCoreArea");
+    //opt.AddParameter("MNewImagePar.fLeakage2");
+
+    // Setup how to train the RF. This one gives best results so far
+    opt.SetTrainFunc("log(MMcEvt.fEnergy)/log(MHillas.fSize)", "MHillas.fSize^x");
+    // opt.SetTrainLog(); // Train in log-energy
+    // opt.SetTrainLin(); // Train just in energy
+
+    // -------------------- Run ----------------------------
+
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    // -------------------- Magic-Cuts ----------------------
+    // It is recommended to test with your cuts, but train with all events
+
+    MFMagicCuts cuts;
+    cuts.SetHadronnessCut(MFMagicCuts::kArea);
+    cuts.SetThetaCut(MFMagicCuts::kOn);
+
+    TArrayD arr(13);
+    arr[0]  =  1.15136;
+    arr[1]  =  0.215;
+    arr[2]  =  0.215468;
+    arr[3]  =  5.63973;
+    arr[4]  =  0.0836169;
+    arr[5]  = -0.07;
+    arr[6]  =  7.2;
+    arr[7]  =  0.5;
+    arr[8]  =  0.0681437;
+    arr[9]  =  2.62932;
+    arr[10] =  1.51279;
+    arr[11] =  0.0507821;
+
+    cuts.SetVariables(arr);
+
+    // opt.AddPreCut(&cuts);    // add cut for training and testing
+    // opt.AddTrainCut(&cuts);  // add cut for training only
+    opt.AddTestCut(&cuts);   // add cut for testing only
+
+    /*
+     // ---------------------- Histogram  --------------------
+     MHn hist("MyHist", "Energy Residual (lg E_{est} - lg E_{mc})");
+
+     hist.AddHist("MNewImagePar.fConcCOG", "log10(MEnergyEst.fVal)-log10(MMcEvt.fEnergy)");
+     hist.InitName("ResConc;Conc;EnergyResidual");
+     hist.InitTitle(";C;\\Delta lg E;");
+     hist.SetDrawOption("colz profx");
+
+     MBinning bins(50, 0, 1);
+     hist.SetBinnings(&bins);
+
+     MFillH fill(&hist, "", "FillMyHist");
+     //fill.SetWeight(); // Enable weights to be used to fill this histogram
+     opt.AddTestTask(&fill);
+
+     // -------------------- Other cuts ----------------------
+     opt.AddPreCut("MHillasSrc.fDist*MGeomCam.fConvMm2Deg<1.0");
+     opt.AddPreCut("MHillas.fSize>200");
+
+     // -------------------- Energy Slope --------------------
+     // Note, that weight normally doesn't improve anything here.
+     // This is a way to throw away events to a different slope
+     MFEnergySlope slope(-4.0); // New slope for mc spectrum
+     opt.AddPreCut(&slope);     // throw away events to change slope
+
+     // This is a way to weight the events to a different spectrum
+     MMcSpectrumWeight weight;
+     weight.SetFormula("pow(X/300, -2.31-0.26*log10(X/300))");
+     opt.SetWeights(&weight);
+
+     // ------------------ Zd distribution -------------------
+     TFile file("ganymed00001111.root");
+
+     MStatusArray arr;
+     if (arr.Read()<=0)
+        return;
+     TH1D *vstime = (TH1D*)arr.FindObjectInCanvas("Theta",  "TH1D", "OnTime");
+     if (!vstime)
+         return -1;
+
+     MMcSpectrumWeight weight;
+     weight.SetWeightsZd(vstime);
+     opt.AddPreTask(&weight);
+
+     // ------------------------------------------------------
+    */
+
+     // To allow overwrite of existing files
+     // opt.SetOverwrite();
+
+     opt.Train("rf-energy.root", set, 30000);
+}
Index: branches/Mars_McMismatchStudy/macros/train/trainseparation.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/train/trainseparation.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/train/trainseparation.C	(revision 17960)
@@ -0,0 +1,51 @@
+void trainseparation()
+{
+    MDataSet settrn("mctrain.txt");
+    MDataSet settst("mctest.txt");
+    settrn.SetNumAnalysis(1);
+    settst.SetNumAnalysis(2);
+
+    // alternatively use:
+    //MDataSet settrn("mctrain.txt", "/magic/montacrlo/sequences", "/magic/montecarlo/star");
+    //MDataSet settst("mctest.txt" , "/magic/montacrlo/sequences", "/magic/montecarlo/star");
+
+    MJTrainSeparation opt;
+    //opt.SetDebug();
+
+    // ------- Parameters to train Random Forest --------
+    opt.AddParameter("MHillas.fSize");
+    opt.AddParameter("MHillas.fWidth");
+    opt.AddParameter("MHillas.fLength");
+    opt.AddParameter("TMath::Abs(MHillasExt.fM3Long)");
+    opt.AddParameter("MNewImagePar.fConc");
+    opt.AddParameter("MNewImagePar.fConc1");
+
+    // -------------------- Run ----------------------------
+    MStatusDisplay *d = new MStatusDisplay;
+    opt.SetDisplay(d);
+
+    /*
+     -------------------- Energy Slope --------------------
+     MFEnergySlope slope(-2.8);
+     opt.AddPreCut(&slope);
+
+     -------------------- Other cuts ----------------------
+     opt.AddPreCut("MHillas.fSize>200");
+     opt.AddPreCut("MHillasSrc.fDCA*MGeomCam.fConvMm2Deg<0.3");
+    */
+
+    opt.SetDataSetTrain(settrn, 10000, 10000);
+    //opt.SetDataSetTest(settst);
+
+    opt.Train("rf-separation.root");
+}
+
+/*
+ // SequencesOn:   Monte Carlo sequences (gammas)
+ // SequencesOff:  Data sequences (background)
+
+ // Use:
+ // opt.AddPreCut    to use cut for test and training
+ // opt.AddTestCut   to use cut for test only
+ // opt.AddTrainCut  to use cut for train only
+ */
Index: branches/Mars_McMismatchStudy/macros/triglvl2.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/triglvl2.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/triglvl2.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/trigrate.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/trigrate.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/trigrate.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/calendar.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/calendar.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/calendar.C	(revision 17960)
@@ -0,0 +1,185 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 8/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2006
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// calendar.C
+//
+// example of how to use MCalendar to draw your calendar
+//
+// For more details of the usage and the resources resources please
+// refer to the class reference of MCalendar and the descriptions
+// of its member functions.
+//
+// To write an output file check the end of the loop.
+//
+// For more information on the setup see also
+//   macros/tutorials/calendar.rc
+//   macros/tutorials/holidays.rc
+//
+///////////////////////////////////////////////////////////////////////////
+
+void calendar()
+{
+    // 2, 10, 13
+    gStyle->SetTextFont(6*10+2);
+
+    // Define the path where your resource files are located
+    TString rcpath  = "macros/tutorials/";
+
+    // Define the path where your images are
+    TString imgpath = "./";
+
+    // Create the object containing your setup
+    MEnv env(rcpath+"calendar.rc");
+
+    // Create the display to show your calendar
+    MStatusDisplay *d = new MStatusDisplay(1426, 1050);
+
+    // Define the first and last month which you want to make a
+    // piece of
+    Int_t first=1;
+    Int_t last=12;
+
+    // Loop over all months
+    for (Int_t month=first; month<=last; month++)
+    {
+        // Create an object do draw your calendar
+        MCalendar *cal=new MCalendar;
+        cal->SetBit(kCanDelete);
+
+        // Set the month and year you want to draw it for
+        cal->SetDate(month, 2006);
+
+        // Read resource file defining the layout.
+        // You could also skip this line. In this case a nice
+        // default layout is used instead
+        cal->ReadResourceFile(rcpath+"calendar.rc");
+
+        // Read file containing the holidays.
+        // You could also skip this file. In this case
+        // only New Year, Easter and Christmas are shown.
+        cal->ReadHolidayFile(rcpath+"holidays.rc");
+
+        // Get the image corresponding to the month
+        TASImage *img = cal->GetImage(&env, imgpath);
+        if (!img)
+        {
+            delete cal;
+            continue;
+        }
+
+        // Check whether the layout should be horizontal or vertical
+        Bool_t hor = img->GetWidth()>img->GetHeight();
+        Int_t background = kWhite;
+
+        // Define layout of day-table for this month
+        if (hor)
+            cal->SetLayout(2, 0.05, 0.1, 0.015, 0.03);
+        else
+            cal->SetLayout(1, 0.05, 0.05, 0.005, 0);
+
+        // Get the name of the month
+        TString strmonth = cal->GetStringFmt("%b");
+        // convert Umlauts to "StatusDisplay-charset"
+        MCalendar::ConvertUTF8(strmonth, kFALSE);
+
+        // Add a new tab for this month
+        TCanvas &c = d->AddTab(strmonth);
+        // Set background color for the tab
+        c.SetFillColor(background);
+
+        // conver month name to latex format
+        MCalendar::Convert2Latex(strmonth);
+
+        // Create the main pad
+        TPad *pad2;
+        if (hor)
+            pad2=new TPad("Dat", "Data", 0, 0.01, 1, 0.3);
+        else
+            pad2=new TPad("Dat", "Data", 0.5, 0.19, 1, 0.81);
+        pad2->SetBorderMode(0);
+        pad2->SetFillColor(background);
+        pad2->SetBit(kCanDelete);
+
+        // Draw the image to your month-tab
+        c.cd();
+
+        if (hor)
+            cal->DrawImage(*img, 0, 0.305, 0.628, 1, kTRUE);
+        else
+            cal->DrawImage(*img, 0, 0, 0.5, 0.99, kTRUE);
+
+        gPad->SetFixedAspectRatio();
+        delete img;
+
+        // Draw the date to your month-tab
+        Double_t x1, y1, x2, y2;
+        gPad->GetPadPar(x1, y1, x2, y2);
+
+        c.cd();
+
+        // "comic" is the ttf-font name. You find other ones typically
+        // in $ROOTSYS/fonts or /usr/X11R6/lib/X11/fonts/truetype
+        if (hor)
+            cal->DrawTTFDate(0.64, 0.83, 1, 1, "%B %Y", 0.072, "comic");
+        else
+            cal->DrawTTFDate(0.5, 0.83, 1, 1, "%B %Y", 0.085, "comic");
+
+
+        c.cd();
+
+        // Get description and draw description
+        TString txt = env.GetValue(Form("%02d.Text", month), "");
+        if (!txt.IsNull())
+        {
+            MCalendar::Convert2Latex(txt);
+
+            TAttText att1(11, 0, kBlack, 42, 0.023);
+            if (hor)
+                cal->DrawDate(0.63, 0.31, txt, att1);
+            else
+                cal->DrawDate(0.5, 0.01, txt, att1);
+
+        }
+
+        // Now make sure that everything is displayed as expected...
+        pad2->Draw();
+
+        gROOT->SetSelectedPad(0);
+        pad2->cd();
+        cal->Draw();
+
+        pad2->Modified();
+        pad2->Update();
+
+        c.Update();
+
+        // Uncomment this lines to write a postscript (or pdf) file
+        //TString psfile = "calendar.ps";
+        //if (month==first) psfile+="(";
+        //if (month==last)  psfile+=")";
+        //c.Print(psfile, "portrait");
+    }
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/calendar.rc
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/calendar.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/calendar.rc	(revision 17960)
@@ -0,0 +1,159 @@
+# -------------------------------------------------------------
+#  THIS RESOURCE FILES IS AN EXAMPLE AND BELONGS TO calendar.C
+# -------------------------------------------------------------
+
+# Define the images for the 12 months
+01: magic_t.xpm
+02: marslogo.xpm
+03: marslogo.xpm
+04: magic_t.xpm
+05: marslogo.xpm
+06: marslogo.xpm
+07: magic_t.xpm
+08: marslogo.xpm
+09: marslogo.xpm
+10: magic_t.xpm
+11: marslogo.xpm
+12: marslogo.xpm
+
+# define descriptions for your images
+01.Text: All File types supported by TASImage are supported.
+02.Text: Please try to use the context menu on the small boxes.
+03.Text: Choose SetDefaultLayout from the context menu.
+04.Text: Play around with th eoptions in the context menu.
+05.Text: Parts of the context menu are sensitive to the mouse position.
+06.Text: To create a postscript file of your calendar change the macro.
+07.Text: 
+08.Text: 
+09.Text: 
+10.Text: 
+11.Text: 
+12.Text: 
+
+# ------------------------------------------------------------
+# General information
+#
+# This are the most important settings. For more details of
+# more resources please have a look at the class reference 
+# of MCalendar and the descriptions of its member functions.
+
+# For something in the box for each day (defined in "Contents")
+# you have several options which are always known (as an example
+# "Day" is used here):
+#
+#  - Day.TextAlign: Center
+#    Defines the position of the output in the box. For more 
+#    details about what is allowed see MEnv::GetAlign
+#
+#  - Day.Format: %e
+#    available if a number (month, week, day, etc) should be
+#    formatted (or converted into text) For more details on
+#    the allowed formats see MTime::GetFormatStr or strftime
+#
+#  - Day.TextColor: Blue
+#    Defined the output color. For more details see
+#    MEnv::GetColor
+#
+#  - Day.TextFont: 62
+#    Define the font for the output text. For more details
+#    see TAttText
+#
+#  - To change the settings depending on the day of the week
+#    (0=sonday, 1=monday, etc) put the number of the day
+#    behind the Name of your resource, eg. To diaply the day-number
+#    of sundays in red (while all others are black) use
+#       Day.TextColor: Black
+#       Day.Active.0.TextColor: Red
+#    The term Active before the 0 defines that only the active
+#    days are printed in red. Active days are the days which belong 
+#    to the current month (sometimes before the beginning or end
+#    of a month the days of the previous or next month are shown,
+#    the are called Inactive) To change the color of the inactive
+#    sundays to red do
+#       Day.Inactive.0.TextColor: Red
+#    You can also change the text font to green for all active
+#    days (except the sunday which is already set to red):
+#       Day.Active.TextColor: red
+#
+# ------------------------------------------------------------
+
+# Which contents should the calendar have? Here you define what
+# should be displayed in your box. You could also name them
+# A and B instead of Day and Date. The result would be identical 
+# (I mean the name is totally artificial and defined here)
+# This also means that you can define as many of them as you want.
+# In this example files (calendar.rc and holidays.rc) the
+# following possible options are defined (see below):
+#   Day Date Holiday Birthday DayName Week
+Contents: Day Date Holiday Birthday DayName
+
+# What is the language for the month and day names?
+Language: de_DE
+
+# Where in the boxes should the moon grafic and text be aligned?
+# (The numbers are according to TAttText, 0 means off)
+Moon.Graf.Align:              11
+Moon.Text.Align:              0
+#Moon.Text.Type:              0
+#Moon.Text.Continous:         No
+
+# This is the definition of the moon grafic color
+Moon.Inactive.FillColor:      18
+Moon.Inactive.0.FillColor:    17
+
+# This lines can be used to draw the week number somewhere
+# Restriction is string containing the number of all days
+# at which the week should be printed (eg. "0" for sundays,
+# "1" for mondays or "01" for sunday and monday
+#Week.TextAlign:              top right
+#Week.Format:                 KW%V
+#Week.Restriction:            1
+#Week.TextSize:               0.1
+#Week.Active.TextColor:       Grey8
+#Week.Inactive.TextFont:      42
+#Week.Inactive.TextColor:     17
+
+# Define the layout of the day-name.
+Day.TextAlign:                top left
+Day.Format:                   %e
+#Day.TextFont: 62
+#Day.Active.TextFont:         22
+Day.Inactive.TextFont:        42
+Day.Inactive.TextColor:       17
+Day.Inactive.0.TextColor:     17
+
+# Define the layout of the date (number)
+Date.TextAlign:               bottom right
+Date.Format:                  %a
+Date.Active.0.TextColor:      2
+#Date.Active.TextFont:        22
+Date.Inactive.TextFont:       42
+Date.Inactive.FillColor:      19
+Date.Inactive.TextColor:      17
+Date.Active.0.FillColor:      17
+Date.Inactive.0.FillColor:    18
+Date.Inactive.0.TextColor:    17
+
+# Define the layout of holidays, including the easter holidays
+# (see holiday.rc)
+Holiday.TextAlign:            center
+Holiday.TextSize:             0.13
+Holiday.TextColor:            4
+Holiday.Inactive.TextColor:   17
+Holiday.TextFont:             62
+
+# Define the layout of birthdays (see holiday.rc)
+Birthday.TextAlign:           center
+Birthday.TextSize:            0.13
+Birthday.TextColor:           Dark Green
+Birthday.Inactive.TextColor:  17
+Birthday.TextFont:            62
+
+# Define the layout for days with a name (eg. "Good Friday") which
+# might not be holidays
+DayName.TextColor:            13
+DayName.TextAlign:            Center
+DayName.TextFont:             62
+DayName.TextSize:             0.13
+DayName.Inactive.TextColor:   17
+DayName.Inactive.0.TextColor: 17
Index: branches/Mars_McMismatchStudy/macros/tutorials/derotatedc.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/derotatedc.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/derotatedc.C	(revision 17960)
@@ -0,0 +1,104 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// derotatedc.C
+// ============
+//
+// Derotate a MCamEvent and fill a histogram with derotated data
+// (sky-plot).
+//
+// As an input you need a merpped root file conataining DC information
+// from a camera report file. To be able to derotate you also need
+// aproproitate time-stamps and the corresponding pointing information.
+//
+// All events are filled into a 2D histograms - derotated.
+//
+// The example shows the usage of MHCamEventRot. The output is the derotated
+// sky-plot.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void derotatedc()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // Define Observatory location (for derotation)
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    // Set the camera geometry (for histogram size)
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+
+    // setup pointing position
+    MPointingPos ppos;
+    ppos.SetSkyPosition(MAstro::Hms2Hor(5, 34, 31.9), MAstro::Dms2Deg(22, 0, 52.0));
+    plist.AddToList(&ppos);
+
+    // Define which file to read
+    MReadTree read("Currents", "../dc.root");
+    read.DisableAutoScheme();
+
+    // Derotated histogram to fill
+    MHCamEventRot hist;
+
+    // Set name of time container corresponding to your data
+    hist.SetNameTime("MTimeCurrents");
+
+    // Setup fill task
+    MFillH fill(&hist, "MCameraDC");
+
+    // Set a draw option for your 2D histogram
+    //fill.SetDrawOption("colz");
+
+    // Setup tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    MStatusDisplay *d = new MStatusDisplay;
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/disprfl.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/disprfl.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/disprfl.C	(revision 17960)
@@ -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, 2/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+void disprfl()
+{
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MGeomCamMagic geomcam;
+    plist.AddToList(&geomcam);
+
+    MDirIter files("/magic/montecarlo/reflector/reflex/gammas/HE/zbin0", "Gamma*.rfl");
+
+    MReadRflFile read;
+    read.AddFiles(files);
+    tlist.AddToList(&read);
+
+    MHReflector refl;
+    MFillH fill(&refl);
+
+    tlist.AddToList(&fill);
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    if (!evtloop.Eventloop())
+        return;
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/evtrate.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/evtrate.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/evtrate.C	(revision 17960)
@@ -0,0 +1,78 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// evtrate.C
+// =========
+//
+// Example macro how to calulate the eventrate (per event) and display
+// the result versus time.
+//
+// As an input you need a merpped raw-data file containing correct times.
+// The output is the plot: Eventrate vs. time.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void evtrate()
+{
+    // Setup parameter- and tasklist
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // Setup reading task
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile("test-time.root");
+
+    // Setup event rate calculator
+    MEventRateCalc calc;
+    // Setup number of events to be averaged
+    calc.SetNumEvents(200);
+
+    // Setup histogram to be filles with rate
+    MHVsTime rate("MEventRate.fRate");
+
+    // Setup task to fill the histogram
+    MFillH fill(&rate, "MTime");
+
+    // Setup tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&calc);
+    tlist.AddToList(&fill);
+
+    // Execute your eventloop
+    MEvtLoop loop;
+    loop.SetParList(&plist);
+
+    if (!loop.Eventloop())
+        return;
+
+    // print some execution statistics
+    tlist.PrintStatistics();
+
+    // Draw result
+    rate.DrawClone();
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/extendcam.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/extendcam.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/extendcam.C	(revision 17960)
@@ -0,0 +1,237 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz,  12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// extendcam.C
+//
+// This macro demonstrates how to extend the magic camera and performes
+// a fourier transformation on it
+//
+/////////////////////////////////////////////////////////////////////////////////
+
+Bool_t HandleInput()
+{
+    // This must be there to get accesss to the GUI while the macro
+    // is still running!
+
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+TCanvas   *c;
+MHCamera *d1=new MHCamera(MGeomCamMagic());
+MHCamera *d2=new MHCamera;
+MHCamera *d3=new MHCamera;
+MHCamera *d4=new MHCamera;
+MHCamera *d5=new MHCamera;
+MHCamera *d6=new MHCamera(MGeomCamMagicXT());
+
+MSignalCam *evt=0;
+MMcEvt *mc;
+
+MHexagonFreqSpace *fFreq1;
+MHexagonFreqSpace *fFreq2;
+
+Int_t PreProcess(MParList *plist)
+{
+    fFreq1 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace1");
+    if (!fFreq1)
+        return kFALSE;
+    fFreq2 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace2");
+    if (!fFreq2)
+        return kFALSE;
+
+    //Für Real-Raum
+    evt = (MSignalCam*)plist->FindObject("MSignalCam");
+    if (!evt)
+    {
+        cout << "Fehler: MSignalCam" << endl;
+        return kFALSE;
+    }
+
+    mc = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!mc)
+    {
+        cout << "Fehler: MMcEvt" << endl;
+        return kFALSE;
+    }
+
+    c = new TCanvas("Events", "Real Events", 900, 600);
+    c->SetBorderMode(0);
+    c->Divide(3,2);
+
+    MGeomCam *geomfreq=fFreq1->NewGeomCam();
+    geomfreq->SetName("FreqSpace");
+
+    c->cd(1);
+    d1->SetPrettyPalette();
+    d1->Draw();
+    c->cd(2);
+    d2->SetGeometry(MGeomCamMagicXT());
+    d2->SetPrettyPalette();
+    d2->Draw();
+    c->cd(4);
+    d3->SetGeometry(*geomfreq);
+    d3->SetPrettyPalette();
+    d3->Draw();
+    c->cd(5);
+    d4->SetGeometry(MGeomCamMagicXT());
+    d4->SetPrettyPalette();
+    d4->Draw();
+    c->cd(3);
+    d5->SetGeometry(MGeomCamMagicXT());
+    d5->SetPrettyPalette();
+    d5->Draw();
+    c->cd(6);
+    //d6->SetGeometry(MGeomCamMagicXT());
+    d6->SetPrettyPalette();
+    d6->Draw();
+    return kTRUE;
+}
+
+MClone *cl1;
+MClone *cl2;
+MClone *cl3;
+MClone *cl4;
+
+Int_t Process()
+{
+    d1->SetCamContent(*(MSignalCam*)cl1->GetClone());
+    d2->SetCamContent(*(MSignalCam*)cl2->GetClone());
+    d3->SetCamContent(*fFreq2);
+    d4->SetCamContent(*(MSignalCam*)cl4->GetClone());
+    d5->SetCamContent(*(MSignalCam*)cl3->GetClone());
+    d6->SetCamContent(*evt);
+
+    d2->SetMaximum(-1111);
+    d4->SetMaximum(-1111);
+    d2->SetMinimum(0);
+    d4->SetMinimum(0);
+    d2->SetMaximum(TMath::Max(d2->GetMaximum(), d4->GetMaximum()));
+    d4->SetMaximum(d2->GetMaximum());
+
+    for (int i=1; i<7; i++)
+    {
+        c->GetPad(i)->GetPad(1)->Modified();
+        c->GetPad(i)->GetPad(1)->Update();
+    }
+
+    c->Modified();
+    c->Update();
+
+
+    return HandleInput();
+}
+
+void extendcam()
+{
+    MParList  plist;
+    MTaskList tlist;
+
+    MGeomCamMagicXT geom("MGeomCamMagicXT");
+    plist.AddToList(&geom);
+
+    plist.AddToList(&tlist);
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile("/home/tbretz/Software/mcwobble/lza/cal/19*.root");
+    //read.AddFile("/home/hoehne/data/mcdata/gammas/calib/calib_gamma_zbin0.root");
+    //read.AddFile("/home/hoehne/data/mcdata/hadrons/calib/calib_proton_zbin0.root");
+
+
+    // Setup intercative task calling the functions defined above
+    MGeomApply           apply; //necessary for evt
+    MGeomCamMagicEnhance enhance;
+    // enhance.SetNameCerPhotEvtOut("MCerPhotEvt2");
+
+    MClone clone1("MSignalCam", "Clone1");
+    MClone clone2("MSignalCam", "Clone2");
+    MClone clone3("MSignalCam", "Clone3");
+    MClone clone4("MSignalCam", "Clone4");
+
+    cl1 = &clone1;
+    cl2 = &clone2;
+    cl3 = &clone3;
+    cl4 = &clone4;
+
+    MHexagonalFTCalc     ftcalc;
+    ftcalc.SetNameGeomCam("MGeomCamMagicXT");
+    // ftcalc.SetNameCerPhotEvt("MCerPhotEvt2");
+
+    MTaskInteractive mytask;
+    mytask.SetPreProcess(PreProcess);
+    mytask.SetProcess(Process);
+
+    MImgCleanStd clean1(8, 4.5);
+    clean1.SetMethod(MImgCleanStd::kAbsolute);
+    clean1.SetNameGeomCam("MGeomCamMagicXT");
+    clean1.SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+
+    MImgCleanStd clean2(8, 4.5);
+    clean2.SetMethod(MImgCleanStd::kAbsolute);
+    clean2.SetNameGeomCam("MGeomCamMagicXT");
+    clean2.SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+
+    // Setup your tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&clone1);
+    tlist.AddToList(&enhance);
+    tlist.AddToList(&clone2);
+    tlist.AddToList(&clean1);
+    tlist.AddToList(&clone3);
+    tlist.AddToList(&ftcalc);
+    tlist.AddToList(&clone4);
+    tlist.AddToList(&clean2);
+    tlist.AddToList(&mytask);
+
+    // Run your analysis
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print statistics information about your loop
+    tlist.PrintStatistics();
+}
+
Index: branches/Mars_McMismatchStudy/macros/tutorials/hft.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/hft.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/hft.C	(revision 17960)
@@ -0,0 +1,237 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// hft.C
+//
+// example of using MHexagonal*
+//
+///////////////////////////////////////////////////////////////////////////
+
+Bool_t HandleInput()
+{
+    // This must be there to get accesss to the GUI while the macro
+    // is still running!
+
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+//
+// Setup the data-members of your 'virtual' class
+//
+MHCamera display[5];
+
+TCanvas   *c;
+MParList  *fParList;
+MTaskList *fTaskList;
+
+MHexagonalFTCalc  hft;
+MHexagonFreqSpace *fFreq1;
+MHexagonFreqSpace *fFreq2;
+
+MGeomCam *geomfreq;
+
+TH1F histo("", "", 35, -0.5, 35);
+
+//
+// Called like all PreProcess functions of tasks. Get the access to
+// the containers necessary for you.
+//
+Int_t PreProcess(MParList *plist)
+{
+    fFreq1 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace1");
+    if (!fFreq1)
+        return kFALSE;
+    fFreq2 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace2");
+    if (!fFreq2)
+        return kFALSE;
+
+    geomfreq=fFreq1->NewGeomCam();
+    geomfreq->SetName("FreqSpace");
+    plist->AddToList(geomfreq);
+
+    //    return kTRUE;
+
+    // Get parameter and tasklist, see Process
+    fParList = plist;
+    fTaskList = (MTaskList*)plist->FindObject("MTaskList");
+
+    // Get camera geoemtry
+    MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+
+    // setup canvas and camera-histograms
+    c = new TCanvas("Events", "Real Events", 900, 600);
+    c->SetBorderMode(0);
+    c->Divide(3,2);
+    for (int i=0; i<3; i++)
+    {
+        display[i].SetGeometry(*geomfreq);
+        display[i].SetPrettyPalette();
+        c->cd(i+1);
+        display[i].Draw();
+    }
+
+    display[1].SetName("In");
+    display[2].SetName("Out");
+    display[0].SetName("Freq");
+
+    return kTRUE;
+}
+
+//
+// Called like all Process functions of tasks. Process a single
+// event - here display it.
+//
+Int_t Process()
+{
+    // For simplicity we search in the Process function for the
+    // objects. This is deprectaed! Store the pointers to the objects
+    // as data member and get the pointers in PreProcess.
+    MClone *clone1 = (MClone*)fTaskList->FindObject("Clone1");
+    MClone *clone2 = (MClone*)fTaskList->FindObject("Clone2");
+    MGeomCam *geom = (MGeomCam*)fParList->FindObject("MGeomCam");
+
+    // Fill the data into your camera-histograms
+    display[1].SetCamContent(*fFreq1, 1);
+    display[2].SetCamContent(*fFreq1, 2);
+    display[0].SetCamContent(*fFreq2, 0);
+
+    display[1].SetMaximum(-1111);
+    display[2].SetMaximum(-1111);
+    display[1].SetMinimum(0);
+    display[2].SetMinimum(0);
+    display[1].SetMaximum(TMath::Max(display[1].GetMaximum(),
+                                     display[2].GetMaximum()));
+    display[2].SetMaximum(display[1].GetMaximum());
+
+    MHexagonalFT *ft = &hft.GetHFT();
+
+    histo.Reset();
+    for (int i=0; i<ft->GetNumKnots(); i++)
+    {
+        Double_t val=0;
+        fFreq2->GetPixelContent(val, i, *display[1].GetGeometry());
+        histo.Fill(ft->GetRow(i), val/(i+1));
+    }
+
+    c->cd(4);
+    histo.Draw();
+
+    c->cd(5);
+
+    TH1D *obj1 = (TH1D*)display[1].Projection("Proj1");
+    obj1->SetLineColor(kBlue);
+    obj1->Draw();
+    obj1 = (TH1D*)display[2].Projection("Proj2");
+    obj1->Draw("same");
+
+    c->cd(6);
+    display[0].DrawProjection();
+
+    // Update the display
+    for (int i=1; i<=3; i++)
+    {
+        c->GetPad(i)->GetPad(1)->Modified();
+        c->GetPad(i)->GetPad(1)->Update();
+    }
+
+    return HandleInput();
+}
+
+//
+// Called like all PostProcess functions of tasks. Delete
+// instanciated objects.
+//
+Int_t PostProcess()
+{
+    delete c;
+    delete geomfreq;
+}
+
+void hft(const char *fname="/home/tbretz/Software/mcwobble/lza/cal/19*.root")
+{
+    // Setup parameter- and tasklist
+    MParList  plist;
+    MTaskList tlist;
+
+    plist.AddToList(&tlist);
+
+    // setup reading task
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    // Clone MCerPhotEvt befor eimage cleaning
+    MClone clone1("MSignalCam", "Clone1");
+
+    // Setup image cleaning
+    MImgCleanStd clean(8.5, 4);
+    clean.SetMethod(MImgCleanStd::kAbsolute);
+    clean.SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+
+    // Clone MCerPhotEvt befor eimage cleaning
+    MClone clone2("MSignalCam", "Clone2");
+
+    // Setup intercative task calling the functions defined above
+    MTaskInteractive  mytask;
+
+    mytask.SetPreProcess(PreProcess);
+    mytask.SetProcess(Process);
+
+    // Setup your tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&clone1);
+    tlist.AddToList(&hft);
+    tlist.AddToList(&clone2);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&mytask);
+
+    // Run your analysis
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print statistics information about your loop
+    tlist.PrintStatistics();
+}
+
Index: branches/Mars_McMismatchStudy/macros/tutorials/holidays.rc
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/holidays.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/holidays.rc	(revision 17960)
@@ -0,0 +1,94 @@
+# -------------------------------------------------------------
+#  THIS RESOURCE FILES IS AN EXAMPLE AND BELONGS TO calendar.C
+# -------------------------------------------------------------
+
+# --------------------------------------------------
+# Use this file to change the holidays to your local
+# holidays with the corresponding names
+# --------------------------------------------------
+#
+# There are sevral kind of holidays:
+#
+#   - Holiday.mm/dd: Name
+#     A holiday at the date defined by mm/dd
+#      eg. Holiday.01/01: New Year
+#
+#   - Holiday.n: Name
+#     A holiday n days after easter (sunday)
+#      eg. Holiday.1: Easter Monday
+#
+#   - Holiday.-n: Name
+#     A holiday n days before easter (sunday)
+#      eg. Holiday.-2: Good Friday
+#
+# If it is not a holiday (as "Good Friday" might be) replace
+# Holiday by DayName which is used for days which have a name
+# but which are no holidays, eg.
+#
+#      DayName.-2: Good Friday
+#
+# For Birthdays use:
+#  
+#    - Birthday.mm/dd: Name
+#      eg. Birthday.09/09: Thomas
+#
+# ----------------- Fixed holidays -----------------
+Holiday.01/01: Neujahr
+Holiday.01/06: Hl. drei Könige
+#Holiday.05/01: #splitline{Tag der}{ Arbeit}
+Holiday.05/01: Maifeiertag
+Holiday.08/15: #splitline{      Mariä}{Himmelfahrt}
+Holiday.10/03: #splitline{  Tag der}{dt. Einheit}
+Holiday.11/01: Allerheiligen
+Holiday.12/25: 1.Weihnachtstag
+Holiday.12/26: 2.Weihnachtstag
+Holiday.12/31: Silvester
+
+# --------- Days with a name w.r.t. Easter ---------
+DayName.-48: Rosenmontag
+DayName.-47: #splitline{Faschings-}{  dienstag}
+DayName.-46: #splitline{ Ascher-}{mittwoch}
+DayName.-7: Palmsonntag
+DayName.-3: Gründonnerstag
+DayName.-2: Karfreitag
+DayName.7: Weißer Sonntag
+DayName.02/14: Valentinstag
+DayName.05/05: Europatag
+DayName.06/27: Siebenschläfer
+DayName.10/31: Reformationstag
+DayName.11/02: Allerseelen
+DayName.11/11: Martin
+DayName.12/06: Nikolaus
+DayName.12/24: Heiligabend
+
+DayName.03/20: Frühlingsanfang
+DayName.06/21: Sommeranfang
+DayName.09/22: Herbstanfang
+DayName.12/21: Winteranfang
+
+# ------------------- Birthdays -------------------
+Birthday.09/09: Thomas
+Birthday.07/16: Daniela
+
+# -------------- Holidays wrt. easter -------------
+Holiday.0: Ostersonntag
+Holiday.1: Ostermontag
+Holiday.39: #splitline{    Christi}{Himmelfahrt}
+Holiday.49: Pfingstsonntag
+Holiday.50: Pfingstmontag
+Holiday.60: Fronleichnam
+
+# ------------ Last Sunday before -----------------
+DayName.05/14-0: Muttertag
+DayName.11/19-0: Volkstrauertag
+DayName.11/26-4: Buß- und Bettag
+DayName.11/11-0: Totensonntag
+DayName.12/03-0: 1.Advent
+DayName.12/10-0: 2.Advent
+DayName.12/17-0: 3.Advent
+DayName.12/24-0: 4.Advent
+
+# "T+" and "T-" are used to display the symbols
+# to show the change between summer and winter time
+DayName.03/31-0: T+
+DayName.10/31-0: T-
Index: branches/Mars_McMismatchStudy/macros/tutorials/mirrordelay.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/mirrordelay.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/mirrordelay.C	(revision 17960)
@@ -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): Thomas Bretz, 2/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+void mirrordelay()
+{
+    TF1 fpar("Parab",  "x*x/(4*[0])");
+    TF1 fsph("Sphere", "-sqrt(4*[0]*[0] - x*x) + 2*[0]");
+
+    Double_t F = 4.92; // Fokallaenge = 1/4a
+    Double_t D = 4.5;  // Mirror Diameter
+    Double_t x = 1.85; // incident point for photon
+                                     
+    fsph.SetRange(-D*0.55, D*0.55);
+    fpar.SetRange(-D*0.55, D*0.55);
+
+    fpar.SetParameter(0, F);
+    fsph.SetParameter(0, F);
+
+    fpar.SetMaximum(F*1.05);
+
+    TCanvas *c = new TCanvas;
+    c->SetBorderMode(0);
+    c->SetFrameBorderMode(0);
+    c->SetFillColor(kWhite);
+
+    TF1 *f = (TF1*)fpar.DrawClone();
+    fsph.DrawClone("same");
+
+    f->GetXaxis()->SetTitle("x [m]");
+    f->GetYaxis()->SetTitle("y [m]");
+    f->GetXaxis()->CenterTitle();
+
+    TArrow l;
+    l.SetLineColor(kBlue);
+    l.DrawArrow(-x, F*1.05, -x, fsph.Eval(-x), 0.02);
+    l.DrawArrow( x, F*1.05,  x, fsph.Eval( x), 0.02);
+    l.SetLineColor(kRed);
+    l.DrawArrow(-x, fsph.Eval(-x), -x, fpar.Eval(-x), 0.02);
+    l.DrawArrow( x, fsph.Eval(-x),  x, fpar.Eval( x), 0.02);
+    l.DrawArrow(-x, fpar.Eval(-x), 0, F, 0.02);
+    l.DrawArrow(-x, fsph.Eval(-x), 0, F, 0.02);
+    l.DrawArrow( x, fpar.Eval( x), 0, F, 0.02);
+    l.DrawArrow( x, fsph.Eval( x), 0, F, 0.02);
+
+    TMarker m;
+    m.SetMarkerStyle(kStar);
+    m.DrawMarker(0, F);
+
+    // Plot run-time different versus distance
+
+    c = new TCanvas;
+    c->SetBorderMode(0);
+    c->SetFrameBorderMode(0);
+    c->SetFillColor(kWhite);
+    c->SetGridx();
+    c->SetGridy();
+    c->SetRightMargin(0.01);
+
+    TLegend leg(0.40, 0.6, 0.60, 0.85, "Focal length");//, "NDC");
+
+    for (int i=-2; i<3; i++)
+    {
+        // Make sure to set the parameters BEFORE reusing the function!
+        fsph.SetParameter(0, F+i*0.10*F);
+        fpar.SetParameter(0, F+i*0.10*F);
+
+        TF1 fdel1("Diff1", "Sphere-Parab");
+        TF1 fdel2("Diff2", "TMath::Hypot(x-0, Parab-[0])-TMath::Hypot(x-0, Sphere-[0])");
+        fdel2.SetParameter(0, F+i*0.10*F);
+
+        TF1 fdel("Diff", "(Diff1+Diff2)/3e8*1e9");
+        fdel.SetRange(-D*0.55, D*0.55);
+        fdel.SetLineWidth(2);
+        fdel.SetParameter(0, F+i*0.10*F);
+
+        fdel.SetLineColor(kBlack+(abs(i)==2?3:abs(i)));
+        if (i<0)
+            fdel.SetLineStyle(2);
+        if (i==0)
+            fdel.SetLineStyle(kSolid);
+        if (i>0)
+            fdel.SetLineStyle(7);
+
+        f = (TF1*)fdel.DrawClone(i==-2?"":"same");
+
+        f->GetHistogram()->SetTitle("Arrival time delay for a spherical mirror");
+
+        f->GetXaxis()->SetTitle("r [m]");
+        f->GetYaxis()->SetTitle("Delay  \\Delta t [ns]");
+        f->GetXaxis()->CenterTitle();
+        f->GetYaxis()->CenterTitle();
+        f->GetYaxis()->SetTitleOffset(1.3);
+
+        leg.AddEntry(f, Form("F=%.1fm", F+i*0.10*F));
+    }
+
+    leg.DrawClone();
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/pedestalvstime.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/pedestalvstime.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/pedestalvstime.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/pedvsevent.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/pedvsevent.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/pedvsevent.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/pixfirerate.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/pixfirerate.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/pixfirerate.C	(revision 17960)
@@ -0,0 +1,133 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// pixfirerate.C
+// =============
+//
+// This macro can help to  find "hot" pixels firing too often
+// or pixels firing too rarely. It plots camera displays showing how many 
+// times the FADC integral of each pixel has been found to be above pedestal
+// by 10, 20, 50, 100 or 200 ADC counts. As "pedestal"  we now use simply 
+// the signal in the first ADC slice, which seemed reasonable from a first
+// look at the available test data.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void pixfirerate(TString filename="rawfile.root")
+{
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Set update time to 5s
+    // d->SetUpdateTime(5000);
+
+    // Disable online update
+    // d->SetUpdateTime(-1);
+
+    d->SetLogStream(&gLog, kTRUE); // Disables output to stdout
+    gLog.SetOutputFile("status.log", kTRUE); // Enable output to file
+    //gLog.EnableOutputDevice(MLog::eStdout); // Enable output to stdout again
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MTaskList tlist;
+    MParList  plist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile(filename);
+    tlist.AddToList(&read);
+
+    MGeomApply geomapl;
+    tlist.AddToList(&geomapl);
+
+    // A list of threshold which should be displayed. The last entry
+    // MUST be -1.
+    Double_t threshold[] = { 10, 20, 100, 200, -1 };
+
+    Int_t cnt = 0;
+    while (threshold[cnt]>0) cnt++;
+
+    // Create the corresponding fill tasks and containers
+    for (int i=0; i<cnt; i++)
+    {
+        TString name = "Above ";
+        TString num;
+        num += threshold[i];
+        name += num.Strip(TString::kBoth);
+        TString title = "Firerate [%] of pixels with signal > ";
+        title += num.Strip(TString::kBoth);
+
+        MHTriggerLvl0 *trigmap = new MHTriggerLvl0(threshold[i], name, title);
+        MFillH *fillh = new MFillH(trigmap, "MRawEvtData");
+        trigmap->SetBit(kCanDelete);
+        fillh->SetBit(kCanDelete);
+        plist.AddToList(trigmap);
+        tlist.AddToList(fillh);
+    }
+
+    // create the eventloop
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // Make sure the display hasn't been deleted by the user while the
+    // eventloop was running.
+    //
+    if ((d = evtloop.GetDisplay()))
+    {
+        // Save data in a postscriptfile (status.ps)
+        d->SaveAsPS();
+        /*
+         * ----------- Write status to a root file ------------
+         *
+         TFile file("status.root", "RECREATE");
+         d->Write();
+         file.Close();
+         delete d;
+         */
+    }
+
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/pixsatrate.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/pixsatrate.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/pixsatrate.C	(revision 17960)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// pixfirerate.C
+// =============
+//
+// This macro can help to  find "hot" pixels firing too often
+// or pixels firing too rarely. It plots camera displays showing how many 
+// times the FADC integral of each pixel has been found to be above pedestal
+// by 10, 20, 50, 100 or 200 ADC counts. As "pedestal"  we now use simply 
+// the signal in the first ADC slice, which seemed reasonable from a first
+// look at the available test data.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void pixsatrate(TString filename="rawfile.root")
+{
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Set update time to 5s
+    // d->SetUpdateTime(5000);
+
+    // Disable online update
+    // d->SetUpdateTime(-1);
+
+    d->SetLogStream(&gLog, kTRUE); // Disables output to stdout
+    gLog.SetOutputFile("status.log", kTRUE); // Enable output to file
+    //gLog.EnableOutputDevice(MLog::eStdout); // Enable output to stdout again
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MTaskList tlist;
+    MParList  plist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile(filename);
+    tlist.AddToList(&read);
+
+    MGeomApply geomapl;
+    tlist.AddToList(&geomapl);
+
+    // Create histograms with saturation limits at 254
+    MHTriggerLvl0 trighi(254, "SaturationHi", "Saturation Rate of Hi Gains");
+    MHTriggerLvl0 triglo(254, "SaturationLo", "Saturation Rate of Lo Gains");
+    trighi.SetType(1);
+    triglo.SetType(2);
+
+    // craete fill tasks to fill the histogarms
+    MFillH fillhi(&trighi, "MRawEvtData");
+    MFillH filllo(&triglo, "MRawEvtData");
+    tlist.AddToList(&fillhi);
+    tlist.AddToList(&filllo);
+
+    // create eventloop
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // Make sure the display hasn't been deleted by the user while the
+    // eventloop was running.
+    //
+    if ((d = evtloop.GetDisplay()))
+    {
+        // Save data in a postscriptfile (status.ps)
+        d->SaveAsPS();
+        /*
+         * ----------- Write status to a root file ------------
+         *
+         TFile file("status.root", "RECREATE");
+         d->Write();
+         file.Close();
+         delete d;
+         */
+    }
+
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/plot.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/plot.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/plot.C	(revision 17960)
@@ -0,0 +1,146 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudy Bock, 5/2002 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//  plot.C
+//  ======
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+//  The advantage of using Mars histograms instead of root-trees is that
+//  you can fill values in your histogram which is calculated in the
+//  eventloop.
+//
+//  In this particular sample we fill a histogram with the size parameter
+//  of gammas and one with hadron's size. At the end we display both in a
+//  single plot.
+//
+//  The input is a star-macro already conatining image parameters.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void plot()
+{
+    // Create a status display for graphical output
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetLogStream(&gLog);
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+    MReadMarsFile  read("Events", "MC_OFF1.root");
+    read.AddFile("MC_ON1.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    // Create a filter for Gammas
+    MFParticleId fgamma("MMcEvt", '=', MMcEvt::kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    // Create a filter for Non-Gammas
+    MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    // -------------------------------------------------------
+    //
+    // set the name of the variable to plot and the binning
+    //
+    TString var("Hillas.fSize");
+
+    MBinning bins("BinningMH3X");
+    bins.SetEdgesLog(50, 100, 20000);
+    plist.AddToList(&bins);
+    //
+    // -------------------------------------------------------
+
+    // Create a histogram for the data from gammas and from non-gammas
+    MH3 h3g(var);
+    MH3 h3h(var);
+
+    // Add the histograms to the parameter container list
+    plist.AddToList(&h3g);
+    plist.AddToList(&h3h);
+
+    // Create a task which fills one histogram with the gamma-data
+    MFillH fillg(&h3g);
+    fillg.SetFilter(&fgamma);
+    tlist.AddToList(&fillg);
+
+    // Create a task which fills the other histogram with the non-gamma-data
+    MFillH fillh(&h3h);
+    fillh.SetFilter(&fhadrons);
+    tlist.AddToList(&fillh);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    evtloop.SetDisplay(d);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // Create a pad, check if MStatusDisplay was not closed meanwhile
+    if (evtloop.GetDisplay())
+        d->AddTab("Size");
+    else
+        MH::MakeDefCanvas("Plot");
+
+    // x-axis to logarithmic scale
+    gPad->SetLogx();
+
+    // Setup some style options of the two histograms
+    // and draw a copy of both
+    h3h.GetHist().SetLineColor(kRed);
+    MH::DrawCopy(h3h.GetHist(), h3g.GetHist(), "Size");
+
+    // Now create a new histogram, fill it with the division of the
+    // two histograms and draw also a copy of it
+    TH1D h;
+    MH::SetBinning(&h, &bins);
+    h.Divide(&h3g.GetHist(), &h3h.GetHist());
+    h.SetLineColor(kGreen);
+    h.DrawCopy("same");
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/plot2.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/plot2.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/plot2.C	(revision 17960)
@@ -0,0 +1,154 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudy Bock, 5/2002 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//  plot2.C
+//  =======
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+//  The advantage of using Mars histograms instead of root-trees is that
+//  you can fill values in your histogram which is calculated in the
+//  eventloop.
+//
+//  In this particular sample we fill a histogram with width vs length
+//  of gammas and hadrons. At the end we display both in a single plot.
+//
+//  The input is a star-macro already conatining image parameters.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void plot2()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: read in a file created with star.C
+    MReadMarsFile  read("Events", "star.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    // Create a filter for the gamma events
+    MFParticleId fgamma("MMcEvt", '=', MMcEvt::kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    // Create a filter for the non-gamma events
+    MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    // -------------------------------------------------------
+    //
+    // set the name of the variable to plot and the binning
+    //
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+
+    // Set the variables (converted to deg)
+    TString vary("MHillas.fWidth*MGeomCam.fConvMm2Deg");
+    TString varx("MHillas.fLength*MGeomCam.fConvMm2Deg");
+
+    // Set the binning
+    MBinning binsy("BinningMH3Y");
+    MBinning binsx("BinningMH3X");
+    binsy.SetEdges(11, 0, 0.3);
+    binsx.SetEdges(11, 0, 0.6);
+    plist.AddToList(&binsx);
+    plist.AddToList(&binsy);
+    //
+    // -------------------------------------------------
+
+    // Create two 2D histograms and add them to the list
+    MH3 h3g(varx, vary);
+    MH3 h3h(varx, vary);
+
+    plist.AddToList(&h3g);
+    plist.AddToList(&h3h);
+
+    // Create a task to fill one histogram with the gamma data
+    MFillH fillg(&h3g);
+    fillg.SetFilter(&fgamma);
+    tlist.AddToList(&fillg);
+
+    // Create a task to fill the other one with the non gamma data
+    MFillH fillh(&h3h);
+    fillh.SetFilter(&fhadrons);
+    tlist.AddToList(&fillh);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // Create a default canvas
+    MH::MakeDefCanvas("Plot");
+
+    // setup some style options
+    h3h.GetHist().SetMarkerColor(kRed);
+    h3h.GetHist().SetLineColor(kRed);
+    h3h.GetHist().SetFillStyle(4000);
+
+    // show a contour plot of both histograms
+    h3h.GetHist().DrawCopy("cont3");
+    h3g.GetHist().DrawCopy("cont3same");
+
+    return;
+
+    //
+    // Use this (or something similar) if you want to plot the profile
+    // histograms
+    //
+    TProfile *p = ((TH2&)h3g.GetHist()).ProfileX();
+    p->Draw("same");
+    p->SetBit(kCanDelete);
+
+    TProfile *p = ((TH2&)h3h.GetHist()).ProfileX();
+    p->SetLineColor(kRed);
+    p->SetFillStyle(4000);
+    p->Draw("same");
+    p->SetBit(kCanDelete);
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/readIPR.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readIPR.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readIPR.C	(revision 17960)
@@ -0,0 +1,139 @@
+///////////////////////////////////////////////////////////////////////////
+// 
+//    readIPR.C
+//
+//   This macro shows how to read the Individual Pixel Rates from 
+//   a CC report file.
+//
+//   Input: 
+//     - root file obtained merpping a .rep CC file
+//       container: MTriggerIPR
+//
+//   Output:
+//     - a camera display showing the IPRs
+//     - Some histos for checking purposes
+//   
+//   Note: 
+//     a similar macro can be used to read the following trigger containers:
+//     - MTriggerIPR        (Individual Pixel Rates)
+//     - MTriggerCell       (Rate of trigger cells)
+//     - MTriggerBit        (Output Bits from prescaler (before/after presc.)
+//     - MTriggerPrescFact  (Prescaling factors for each bit)
+//     - MTriggerLiveTime   (Values of counters for dead/livetime)
+//
+//    Author(s): Antonio Stamerra. 09/04 <antonio.stamerra@pi.infn.it>
+//
+////////////////////////////////////////////////////////////////////////////
+void readIPR(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // Create the magic geometry
+    MGeomCamMagic geom;
+    plist.AddToList(&geom);
+
+    // First Task: Read ROOT file with Trigger-REPORT data
+    MReadTree read("Trigger", fname);
+    read.DisableAutoScheme();
+
+    tlist.AddToList(&read);
+
+    // Create the container for the IPRs
+    MTriggerIPR ipr;
+    plist.AddToList(&ipr);
+
+    // Create the histo to display the IPRs
+    MHCamEvent IPRhist("IPRhist","IPRs");
+    plist.AddToList(&IPRhist);
+        
+    // create a task to fill a histogram from the container
+    MFillH fillIPR(&IPRhist, "MTriggerIPR");
+    tlist.AddToList(&fillIPR);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    //-----------------------------------
+    // Now display the result of the loop
+    //
+
+    // create a MHCamera histo where the sum off all events is filled
+    MHCamera &h = *(MHCamera*)IPRhist.GetHistByName("sum");
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(2, 2);
+
+    MHCamera *disp1=h.Clone();
+    MHCamera *disp2=h.Clone();
+    //MHCamera *disp3=h.Clone();
+    disp2->SetCamContent(h, 1);
+    //disp3->SetCamContent(h, 2);
+
+    disp1->SetYTitle("Rate [Hz]");
+    disp2->SetYTitle("\\sigma_{Rate} [Hz]");
+    //disp3->SetYTitle("\\sigma_{Rate} [%]");
+    disp1->SetName("IPRs;avg");
+    disp2->SetName("IPRs;err");
+    //disp3->SetName("IPRs;rel");
+    disp1->SetTitle("IPRs Average");
+    disp2->SetTitle("IPRs error");
+    //disp3->SetTitle("IPRs relative error");
+
+    c->cd(1);
+    TText text(0.1, 0.95, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.03);
+    text.DrawClone();
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp1->Draw();
+    disp1->SetBit(kCanDelete);
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp2->Draw();
+    disp2->SetBit(kCanDelete);
+    //c->cd(3);
+    //gPad->SetBorderMode(0);
+    //gPad->Divide(1,1);
+    //gPad->cd(1);
+    //gPad->SetLogy();
+    //disp3->Draw();
+    //disp3->SetBit(kCanDelete);
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    disp1->Draw("EPhist");
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp2->Draw("Phist");
+    //c->cd(6);
+    //gPad->SetBorderMode(0);
+    //gPad->SetLogy();
+    //disp3->Draw("Phist");
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
Index: branches/Mars_McMismatchStudy/macros/tutorials/readcurrents.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readcurrents.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readcurrents.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/readin.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readin.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readin.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/readpix.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readpix.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readpix.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/readraw.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readraw.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readraw.C	(revision 17960)
@@ -0,0 +1,95 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+void readraw(const char *fname="/data/MAGIC/Period016/mcdata/spot_1cm/standard/gamma/Gamma_zbin9_90_7_1740to1749_w0.root")
+{
+    //
+    // open the file
+    //
+    TFile input(fname, "READ");
+
+    //
+    // open the Run Header tree
+    //
+    TTree *runtree = (TTree*) input.Get("RunHeaders") ;
+
+    if (!runtree)
+        return;
+
+    cout << " Entries in Tree RunHeaders: " << runtree->GetEntries() << endl ;
+
+    //
+    // create an instance of MRawRunHeader, enable the branch and
+    // read the header, print it
+    //
+    MRawRunHeader *runheader = new MRawRunHeader();
+    runtree->GetBranch("MRawRunHeader.")->SetAddress(&runheader);
+    runtree->GetEvent(0);
+    runheader->Print();
+
+    //
+    // open the Data Tree
+    //
+    TTree *evttree = (TTree*) input.Get("Events");
+
+    //
+    // create the instances of the data to read in
+    //
+    MRawEvtHeader  *evtheader = 0;
+    MTime          *evttime   = 0;
+    MRawEvtData    *evtdata   = 0;
+    MRawCrateArray *evtcrate  = 0;
+
+    //
+    // enable the corresponding branches
+    //
+    evttree->GetBranch("MRawEvtHeader.")->SetAddress(&evtheader);
+    evttree->GetBranch("MRawEvtData.")->SetAddress(&evtdata);
+
+    // Use this for real data only
+    //evttree->GetBranch("MTime.")->SetAddress(&evttime);
+    //evttree->GetBranch("MRawCrateArray.")->SetAddress(&evtcrate);
+
+    //
+    // loop over all events and print the information
+    //
+    Int_t iEnt = evttree->GetEntries();
+    cout << " Entries in Tree Data: " << iEnt << endl;
+
+    for (Int_t i = 0; i<iEnt; i++)
+    {
+      // readin event with the selected branches
+      evttree->GetEvent(i);
+
+      evtheader->Print();
+      evtdata->Print();
+
+      // Use this for real data only
+      //evttime->Print();
+      //evtcrate->Print();
+    } 
+}
+
+
Index: branches/Mars_McMismatchStudy/macros/tutorials/readrep.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readrep.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readrep.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/readrfl.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readrfl.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readrfl.C	(revision 17960)
@@ -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 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="~msmeyer/MC/MagicSoft/Simulation/Detector/ReflectorII/resultsQi/000302.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;
+
+    runhead.Print();
+
+    while (JumpTo(tlist, read, runno, evtno))
+    {
+        runno = -1;
+
+        cout << "Run #" << runhead.GetRunNumber() << "   ";
+        cout << "Event #" << evthead.GetEvtNumber() << endl;
+
+        evthead.Print();
+
+	display.SetCamContent(event);
+
+        if (display.GetMean()<1e-5)
+            continue;
+
+	gPad->Modified();
+	gPad->Update();
+	
+        if (!HandleInput())
+            break;
+    } 
+
+    evtloop.PostProcess();
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/readstarguider.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/readstarguider.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/readstarguider.C	(revision 17960)
@@ -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): Thomas Bretz, 5/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// This macro demonstrates how to fill MHPoinitingPos directly from a
+// CC file. This may be helpfull when debugging reading starguider
+// information from a CC file.
+//
+//////////////////////////////////////////////////////////////////////////////
+
+void readstarguider(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);
+
+    MReportFileReadCC read(fname);
+    tlist.AddToList(&read);
+
+    read.AddToList("MReportStarguider");
+
+    MFillH fillh("MHPointing", "MTimeStarguider");
+    tlist.AddToList(&fillh);
+
+    MStatusDisplay *d = new MStatusDisplay;
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    if (!evtloop.Eventloop())
+        return;
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/runbook.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/runbook.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/runbook.C	(revision 17960)
@@ -0,0 +1,150 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// runbook.C
+// =========
+//
+// This is an example macro how to extract the runbook information of
+// a given date from the runbook files.
+//
+// The argument is a date in regexp format, eg.
+//   .x runbook.C("2004-05-1[0-9]")
+//
+// With an MDirIter you can tell the macro which directories and files
+// should be searched.
+//
+// The output are the runbook entries matching your query.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void Wrap(TString &str)
+{
+    // Wrap lines to 80 chars
+    while (str.Length()>80)
+    {
+        TString ss = str(0, 80);
+        Int_t l = ss.Last(' ');
+        if (l<0)
+            break;
+        cout << str(0, l) << endl;
+        str.Remove(0, l);
+    }
+    cout << str << endl;
+}
+
+void ProcessFile(TString fname, TString date)
+{
+    // File processed
+    cout << fname << endl;
+
+    // Open file
+    ifstream fin(fname);
+
+    TString line;
+
+    int i=81;
+
+    TRegexp r0("20[0-2][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]");
+    TRegexp r1(date+" [0-2][0-9]:[0-5][0-9]:[0-5][0-9]");
+
+    int lcnt=0;
+
+    int print = 0;
+
+    while (!fin.eof())
+    {
+        // Read file line by line
+        char *txt=new char[i];
+        fin.getline(txt, i-1);
+
+        if (lcnt++<4)
+            continue;
+
+        if (!fin)
+            txt[i-1]=0;
+
+        line += txt;
+        delete txt;
+
+        if (line.Length()==0)
+        {
+            if (print)
+                cout << endl;
+            continue;
+        }
+
+        if (!fin)
+        {
+            i *= 2;
+            fin.clear();
+            continue;
+        }
+
+        // Check whether line matches regexp
+        if (!line(r0).IsNull())
+            print = !line(r1).IsNull();
+
+        // Wrap lines to 80 chars
+        if (print)
+            Wrap(line);
+        line = "";
+        i=81;
+    }
+    cout << "DONE." << endl;
+}
+
+void runbook(const char *d="20[0-2][0-9]-[0-1][0-9]-[0-3][0-9]")
+{
+    // Regexp to check for valid date
+    TString regexp = "20[0-2][0-9]-[0-1][0-9]-[0-3][0-9]";
+
+    if (regexp!=d)
+    {
+        TRegexp r(regexp);
+
+        TString date=d;
+        if (date(r).IsNull())
+        {
+            cout << "ERROR - Date has wrong format (2003-05-06)" << endl;
+            return;
+        }
+    }
+
+    // Tell which dierctories and files to search
+    MDirIter Next;
+    Next.AddDirectory("/home/MAGIC/online_data/runbook", "CC_*.rbk");
+
+    // Loop over files
+    TString name;
+    while (1)
+    {
+        name=Next();
+        if (name.IsNull())
+            break;
+
+        ProcessFile(name, d);
+    }
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/sectorvstime.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/sectorvstime.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/sectorvstime.C	(revision 17960)
@@ -0,0 +1,100 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// sectorvstime.C
+// ==============
+//
+// In this example we plot the mean content of the right and left half of
+// camera. As an input we use a class derived from MCamEvent. Here this
+// are dc currents read directly from a camera control report file.
+//
+// The output are two histograms one for each half.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void sectorvstime()
+{
+    // Initialize Mars environment
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // Create Magic camera geometry
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+
+    // Which DC file to read?
+    MReportFileRead read("/data/MAGIC/Period013/cacodata/2004_01_26/dc_2004_01_26_05_35_10_12117_OffMrk421-1.txt");
+    read.SetHasNoHeader();
+    read.AddToList("MReportCurrents");
+
+    // Initialize histogram
+    MHSectorVsTime hist1;
+    hist1.SetNameTime("MTimeCurrents");
+
+    // Define sectors you want to display the mean from
+    TArrayI s0(3);
+    s0[0] = 6;
+    s0[1] = 1;
+    s0[2] = 2;
+
+    // Define area index [0=inner, 1=outer]
+    TArrayI inner(1);
+    inner[0] = 0;
+
+    // Don't call this if you want to have all sectors
+    hist1.SetSectors(s0);
+
+    // Don't call this if you want to have all area indices
+    hist1.SetAreaIndex(inner);
+
+    // Task to fill the histogram
+    MFillH fill1(&hist1, "MCameraDC");
+
+    // Also fill a histogram with the mean of all pixels
+    MHCamEvent hist2;
+    MFillH fill2(&hist2, "MCameraDC");
+
+    // Setup Tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&fill1);
+    tlist.AddToList(&fill2);
+
+    // Setup Eventloop
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    // Run Eventloop
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print some statistics
+    tlist.PrintStatistics();
+
+    // Draw clones of the histograms
+    hist1.DrawClone();
+    hist2.DrawClone();
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/spline.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/spline.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/spline.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/starplot.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/starplot.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/starplot.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/sumcurrents.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/sumcurrents.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/sumcurrents.C	(revision 17960)
@@ -0,0 +1,162 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// sumcurrents.C
+// =============
+//
+// This is a demonstration macro to display mean DC currents for all pixels.
+// The input is cc report file. The output are histograms and plots.
+// Using the MDirIter functionality you can process more than one file
+// in one or more directories. For more information see MDirIter.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void ProcessFile(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // Create the magic geometry
+    MGeomCamMagic geom;
+    plist.AddToList(&geom);
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+    MReportFileRead read(fname);
+    read.SetHasNoHeader();
+    read.AddToList("MReportCurrents");
+    tlist.AddToList(&read);
+
+    // create a task to fill a histogram
+    MFillH fill("MHCamEvent", "MCameraDC");
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // Now display the result of the loop
+    //
+    MHCamEvent &h2 = *(MHCamEvent*)plist->FindObject("MHCamEvent");
+    MHCamera &h = *(MHCamera*)h2.GetHistByName("sum");
+;
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamera *disp1=h.Clone();
+    MHCamera *disp2=h.Clone();
+    MHCamera *disp3=h.Clone();
+    disp2->SetCamContent(h, 1);
+    disp3->SetCamContent(h, 2);
+
+    disp1->SetYTitle("I [nA]");
+    disp2->SetYTitle("\\sigma_{I} [\\mu A]");
+    disp3->SetYTitle("\\sigma_{I} [%]");
+    disp1->SetName("Currents;avg");
+    disp2->SetName("Currents;err");
+    disp3->SetName("Currents;rel");
+    disp1->SetTitle("Currents Average");
+    disp2->SetTitle("Currents error");
+    disp3->SetTitle("Currents relative error");
+
+    c->cd(1);
+    TText text(0.1, 0.95, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.03);
+    text.DrawClone();
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp1->Draw();
+    disp1->SetBit(kCanDelete);
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp2->Draw();
+    disp2->SetBit(kCanDelete);
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp3->Draw();
+    disp3->SetBit(kCanDelete);
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    disp1->Draw("EPhist");
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp2->Draw("Phist");
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp3->Draw("Phist");
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+void sumcurrents(const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "dc_*.txt", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+    }
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/sumevents.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/sumevents.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/sumevents.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/sumeventserr.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/sumeventserr.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/sumeventserr.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/sumeventsrms.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/sumeventsrms.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/sumeventsrms.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/sumpedestalrms.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/sumpedestalrms.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/sumpedestalrms.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/sumpedestals.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/sumpedestals.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/sumpedestals.C	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/macros/tutorials/testenv.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/testenv.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/testenv.C	(revision 17960)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// testenv.C
+// =========
+//
+// This example reads an config-file (steering card, input card, ...)
+// The contents of the file a forwarded to the apropriate eventloop
+// setup in your file.
+//
+// All tasks and containers in an eventloop should implement the
+// ReadEnv/WriteEnv function (for an example see the tasks used below).
+//
+// The functions gets the corresponding setup data from the file as an
+// argument and can change their behaviour and setup on this information.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void testenv()
+{
+    // Setup for all MHMatrix objects is done by:
+    // MHMatrix.Column0: ...
+    //
+    // This can be overwritten for a MHMatrix called MatrixGammas by:
+    // MatrixGammas.Column0;
+    //
+    // This can be overwritten for all MHMatrix in one Job by:
+    // Job1.MHMatrix.Column0;
+    //
+    // This can be overwritten for a MHMatrix called MatrixGammas in one Job by:
+    // Job1.MatrixGammas.Column0;
+    //
+    TEnv env(".marsrc");
+
+    //
+    // For developers: Set this to kTRUE to see how the TEnv file
+    // entries are checked.
+    //
+    Bool_t print = kFALSE;
+
+    // ------------ Job 1 -------------------
+    if (env.GetValue("Job1", kFALSE))
+    {
+        cout << "++++++++++++++++++ Job 1 +++++++++++++++++++" << endl;
+        MParList plist1;
+        MTaskList tlist1;
+
+        plist1.AddToList(&tlist1);
+
+        MReadMarsFile read1("Events");
+
+        MHMatrix matrix1("MatrixGammas");
+
+        MFillH fillm1(&matrix1);
+        plist1.AddToList(&matrix1);
+
+        tlist1.AddToList(&read1);
+        tlist1.AddToList(&fillm1);
+
+        MEvtLoop evtloop1("Job1");
+        evtloop1.SetParList(&plist1);
+        cout << "--------------------------------------------" << endl;
+        evtloop1.ReadEnv(env, "", print);
+        cout << "--------------------------------------------" << endl;
+        evtloop1.Eventloop();
+        cout << endl;
+    }
+
+    // ------------ Job 2 -------------------
+
+    if (env.GetValue("Job2", kTRUE))
+    {
+        cout << "++++++++++++++++++ Job 2 +++++++++++++++++++" << endl;
+        MParList plist2;
+        MTaskList tlist2;
+
+        plist2.AddToList(&tlist2);
+
+        MReadMarsFile read2("Events");
+
+        MHMatrix matrix2("MatrixGammas");
+
+        MFillH fillm2(&matrix2);
+        plist2.AddToList(&matrix2);
+
+        tlist2.AddToList(&read2);
+        tlist2.AddToList(&fillm2);
+
+        MEvtLoop evtloop2("Job2");
+        evtloop2.SetParList(&plist2);
+        cout << "--------------------------------------------" << endl;
+        evtloop2.ReadEnv(env, "", print);
+        cout << "--------------------------------------------" << endl;
+        evtloop2.Eventloop();
+        cout << endl;
+    }
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/threshold.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/threshold.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/threshold.C	(revision 17960)
@@ -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-2005
+!
+!
+\* ======================================================================== */
+
+
+void threshold()
+{
+    //
+    // This macro fill the container MHMcEnergies using the task
+    // MMcThresholdCalc and shows the results.
+    //
+    MParList parlist;
+
+    MTaskList tasklist;
+    parlist.AddToList(&tasklist);
+
+    // Setup reading task
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+
+    // Setup files to read or monte carlo dataset to be read
+    MDataSet set("~/Software/montecarlo-onoff-lza.txt");
+    set.AddFilesOn(read);
+
+    // If you want to get the threshold after cuts setup your cuts
+    TArrayD cuts(8);
+    cuts[0]=  1.3245;
+    cuts[1]=  0.22;
+    cuts[2]=  0.215;
+    cuts[3]=  5.486;
+    cuts[4]=  0.0897;
+    cuts[5]= -0.07;
+    cuts[6]=  8.2957;
+    cuts[7]=  0.8677;
+
+    MFMagicCuts mcuts;
+    mcuts.SetThetaCut(MFMagicCuts::kOn);
+    mcuts.SetHadronnessCut(MFMagicCuts::kArea);
+    mcuts.SetVariables(cuts);
+
+    MContinue cont(&mcuts);
+    cont.SetInverted();
+
+    // Setup the threshold histogram to be filled
+    MFillH fill("MHThreshold", "", "FillThreshold");
+    fill.SetNameTab("Threshold");
+
+    // If you like to change your input spectrum use this...
+    MMcSpectrumWeight weight;
+    weight.SetNewSlope(-3.5);
+    fill.SetWeight();
+
+    // Setup your tasklist
+    tasklist.AddToList(&read);     // read data
+    tasklist.AddToList(&cont);     // skip background events
+    tasklist.AddToList(&weight);   // caluclate spectral weight
+    tasklist.AddToList(&fill);     // fill histogram
+
+    // Setup the display
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Setup your eventloop
+    MEvtLoop loop("Threshold");
+    loop.SetParList(&parlist);
+    loop.SetDisplay(d);
+
+    // Start your analysis
+    if (!loop.Eventloop())
+        return;
+}
Index: branches/Mars_McMismatchStudy/macros/tutorials/weights.C
===================================================================
--- branches/Mars_McMismatchStudy/macros/tutorials/weights.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/macros/tutorials/weights.C	(revision 17960)
@@ -0,0 +1,138 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez, 10/2003 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// weights.C
+// =========
+//
+// This macro shows how to use the class MMcWeightEnergySpecCalc
+// to convert the energy spectrum of the MC showers generated with Corsika,
+// to a different one.
+//
+//////////////////////////////////////////////////////////////////////////////
+
+Double_t myfunction(Double_t *x, Double_t *par)
+{
+  Double_t xx = x[0];
+
+  return pow(xx,-2)*exp(-xx/20);  
+}
+
+void weights(TString filename="/up1/data/Magic-MC/CameraAll/Gammas/zbin0/Gamma_zbin0_0_7_1000to1009_w0-4:4:2.root")
+{
+
+    //
+    // PartList
+    //
+    MParList  parlist;
+    MTaskList tasklist;
+    
+    MHMcEnergyImpact h1("h1");
+    MHMcEnergyImpact h2("h2");
+    parlist.AddToList(&h1);
+    parlist.AddToList(&h2);
+
+    MBinning binsenergy("BinningEnergy");
+    binsenergy.SetEdgesLog(100, 1, 1e5);
+    parlist.AddToList(&binsenergy);
+
+    MBinning binsimpact("BinningImpact");
+    binsimpact.SetEdges(100, 0, 450);
+    parlist.AddToList(&binsimpact);
+
+    parlist.AddToList(&tasklist);
+
+
+    //
+    // TaskList
+    //
+    MReadMarsFile reader("Events", filename);
+    reader.EnableBranch("fEnergy");
+    reader.EnableBranch("fImpact");
+
+
+    // -------------------------------------------------------------
+    //
+    // Option 1. Just change the slope of the MC power law spectrum
+    //
+    //MMcWeightEnergySpecCalc wcalc(-2.0);                //<-- Uncomment me
+
+    //
+    // Option 2. A completely differente specturm pass as a TF1 function
+    //           e.g. spectrum with exponential cutoff
+    //
+    //TF1 spec("spectrum","pow(x,[0])*exp(-x/[1])");      //<-- Uncomment me
+    //spec->SetParameter(0,-2.0);                         //<-- Uncomment me
+    //spec->SetParameter(1,50);                           //<-- Uncomment me
+    //MMcWeightEnergySpecCalc wcalc(spec);                //<-- Uncomment me
+ 
+    //
+    // Option 3. A completely differente specturm pass as a cahr*
+    //           
+    //char* func = "pow(x,-2)";                           //<-- Uncomment me
+    //MMcWeightEnergySpecCalc wcalc(func);                //<-- Uncomment me
+
+    //
+    // Option 4. A completely differente specturm pass as a c++ function
+    //     
+    MMcWeightEnergySpecCalc wcalc((void*)myfunction);   //<-- Uncomment me
+    //
+    //-------------------------------------------------------------
+
+    MFillH hfill(&h1,"MMcEvt");
+    MFillH hfill2(&h2,"MMcEvt");
+    hfill2.SetWeight("MWeight");
+
+    tasklist.AddToList(&reader);
+    tasklist.AddToList(&wcalc);
+    tasklist.AddToList(&hfill);
+    tasklist.AddToList(&hfill2);
+
+    //
+    // EventLoop
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    if (!magic.Eventloop())
+        return;
+
+    tasklist.PrintStatistics();
+    parlist.Print();
+
+    //
+    // Draw the Results
+    //
+    TCanvas *c = new TCanvas();
+    c->SetLogy();
+    c->SetLogx();
+
+    TH1D* hist1 = (h1->GetHist())->ProjectionX();
+    TH1D* hist2 = (h2->GetHist())->ProjectionX();
+    hist2->SetLineColor(2);
+
+    hist1->DrawClone();
+    hist2->DrawClone("same");    
+}
Index: branches/Mars_McMismatchStudy/magic_t.xpm
===================================================================
--- branches/Mars_McMismatchStudy/magic_t.xpm	(revision 17960)
+++ branches/Mars_McMismatchStudy/magic_t.xpm	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/magiclogo.xpm
===================================================================
--- branches/Mars_McMismatchStudy/magiclogo.xpm	(revision 17960)
+++ branches/Mars_McMismatchStudy/magiclogo.xpm	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/AnalysisIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/AnalysisIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/AnalysisIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/manalysis/AnalysisLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/AnalysisLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/AnalysisLinkDef.h	(revision 17960)
@@ -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 MCameraData+;
+
+#pragma link C++ class MGeomApply+;
+
+//#pragma link C++ class MCompProbCalc+;
+#pragma link C++ class MMultiDimDistCalc+;
+
+#pragma link C++ class MEnergyEstimate+;
+#pragma link C++ class MParameterCalc+;
+
+#pragma link C++ class MMatrixLoop+;
+
+#pragma link C++ class MEventRate+;
+#pragma link C++ class MEventRateCalc+;
+
+//#pragma link C++ class MMcTriggerLvl2+;
+//#pragma link C++ class MMcTriggerLvl2Calc+;
+
+#pragma link C++ class MMcCalibrationUpdate+;
+
+#endif
Index: branches/Mars_McMismatchStudy/manalysis/MCameraData.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MCameraData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MCameraData.cc	(revision 17960)
@@ -0,0 +1,493 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 08/2004 <mailto:hbartko@mppmu.mpg.de>
+!   Author(s): Stefan Ruegamer, 03/2006 <mailto:snruegam@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraData
+//
+// This is a generalized class storing camera data. For example the cleaning
+// level for the image cleaning is one possibility.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraData.h"
+
+#include <TArrayI.h>
+
+#include "MMath.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+ClassImp(MCameraData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MSignalPix object for each pixel in the event
+//
+MCameraData::MCameraData(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCameraData";
+    fTitle = title ? title : "Generalized storage container for camera contents";
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// This is not yet implemented like it should.
+//
+
+void MCameraData::Draw(Option_t* option) 
+{
+    //
+    //   FIXME!!! Here the Draw function of the CamDisplay
+    //   should be called to add the CamDisplay to the Pad.
+    //   The drawing should be done in MCamDisplay::Paint
+    //
+
+    //    MGeomCam *geom = fType ? new MGeomCamMagic : new MGeomCamCT1;
+    //    MCamDisplay *disp = new MCamDisplay(geom);
+    //    delete geom;
+    //    disp->DrawPhotNum(this);
+}
+*/
+
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event
+// as the ratio between the measured photons and the pedestal rms.
+// In order to do the image cleaning on average in the same photon flux
+// (reconstructed photons per pixel area) for the inner and outer pixels,
+// a correction factor is applied to the outer pixels (see TDAS 02-14).
+// The correction factor assumes the ideal case that the pedestal rms 
+// scales with the inverse square root of the pixel area.
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningLevel(const MSignalCam &evt, const MPedPhotCam &cam,
+                                    const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // Reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    const Int_t entries = evt.GetNumPixels();
+
+    // calculate cleaning levels
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        const Float_t noise = cam[idx].GetRms();
+
+        if (noise<=0) // fData[idx]=0, fValidity[idx]=0
+            continue;
+
+        //
+	// We calculate a correction factor which accounts for the 
+	// fact that pixels have different size (see TDAS 02-14).
+	//
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatioSqrt(idx) / noise;
+        fValidity[idx] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event
+// as the ratio between the measured photons and the pedestal rms.
+// In order to do the image cleaning on average in the same photon flux
+// (reconstructed photons per pixel area) for the inner and outer pixels,
+// a correction factor is applied to the outer pixels (see TDAS 02-14).
+// The correction factor takes the actual average pedestal RMS of the
+// inner and outer pixels into account.
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningLevel2(const MSignalCam &evt, const MPedPhotCam &cam,
+                                     const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of rms with area index 0
+    const Float_t anoise0 = cam.GetArea(0).GetRms();
+    if (anoise0<=0)
+        return;
+
+    // calculate cleaning levels
+    const Int_t entries = evt.GetNumPixels();
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        const Float_t noise = cam[idx].GetRms();
+
+        if (noise<=0) // fData[idx]=0, fValidity[idx]=0
+            continue;
+
+        //
+	// We calculate a correction factor which accounts for the 
+	// fact that pixels have different size (see TDAS 02-14).
+	// We also take into account that the RMS does not scale 
+	// with the square root of the pixel area.
+	// 
+        const UInt_t  aidx  = geom[idx].GetAidx();
+        const Float_t ratio = cam.GetArea(aidx).GetRms()/anoise0;
+
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatio(idx) * ratio / noise;
+        fValidity[idx] = 1;
+    }
+}
+
+void MCameraData::CalcCleaningLevel(const MSignalCam &evt, Double_t noise,
+                                    const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of noise
+    if (noise<=0)
+        return;
+
+    // calculate cleaning levels
+    const Int_t entries = evt.GetNumPixels();
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        //
+	// We calculate a correction factor which accounts for the 
+	// fact that pixels have different size (see TDAS 02-14).
+	//
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatio(idx) / noise;
+        fValidity[idx] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event
+// as the ratio between the reconstructed number of photons per area of an
+// inner pixel and the average pedestal RMS of the inner pixels (democratic
+// image cleaning, see TDAS 02-14).
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningLevelDemocratic(const MSignalCam &evt, const MPedPhotCam &cam,
+                                              const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of rms with area index 0
+    const Float_t noise0 = cam.GetArea(0).GetRms();
+    if (noise0<=0)
+        return;
+
+    // calculate cleaning levels
+    const Int_t entries = evt.GetNumPixels();
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        const Float_t noise = cam[idx].GetRms();
+
+        if (noise<=0)
+            continue;
+
+        //
+        // We calculate a correction factor which accounts for the
+        // fact that pixels have different size (see TDAS 02-14).
+        //
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatio(idx) / noise0;
+        fValidity[idx] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event.
+// The level is the probability that the signal is a real signal (taking
+// the signal height and the fluctuation of the background into account)
+// times one minus the probability that the signal is a background
+// fluctuation (calculated from the time spread of arrival times
+// around the pixel with the highest signal)
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningProbability(const MSignalCam &evt, const MPedPhotCam &pcam,
+                                          const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // Reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of noise
+    const Float_t anoise0 = pcam.GetArea(0).GetRms();
+    if (anoise0<=0)
+        return;
+
+    const Int_t entries = evt.GetNumPixels();
+
+    // Find pixel with max signal
+    Int_t maxidx = 0;
+
+    // Find pixel entry with maximum signal
+    for (Int_t i=0; i<entries; i++)
+    {
+        const Double_t s0 = evt[i].GetNumPhotons()      * geom.GetPixRatio(i);
+        const Double_t s1 = evt[maxidx].GetNumPhotons() * geom.GetPixRatio(maxidx);
+        if (s0>s1)
+            maxidx = i;
+    }
+
+    const Double_t timemean = evt[maxidx].GetArrivalTime();
+    const Double_t timerms  = 0.75; //[slices] rms time spread around highest pixel
+
+    // calculate cleaning levels
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &spix = evt[idx];
+
+        const Float_t rms = pcam[idx].GetRms();
+        if (rms<=0) // fData[idx]=0, fValidity[idx]=0
+            continue;
+
+        fValidity[idx]=1;
+
+        // get signal and arrival time
+        const UInt_t  aidx     = geom[idx].GetAidx();
+        const Float_t ratio    = pcam.GetArea(aidx).GetRms()/anoise0;
+
+        const Double_t signal  = spix.GetNumPhotons() * geom.GetPixRatio(idx) * ratio / rms;
+        const Double_t time    = evt[idx].GetArrivalTime();
+
+        // if signal<0 the probability is equal 0
+        if (signal<0)
+            continue;
+
+        // Just for convinience for easy readybility
+        const Double_t means   = 0;
+        const Double_t meant   = timemean;
+
+        const Double_t sigmas  = rms;
+        const Double_t sigmat  = timerms;
+
+        // Get probabilities
+        const Double_t psignal = MMath::GaussProb(signal, sigmas, means);
+        const Double_t pbckgnd = MMath::GaussProb(time,   sigmat, meant);
+
+        // Set probability
+        fData[idx]     = psignal*(1-pbckgnd);
+        fValidity[idx] = 1;
+
+        // Make sure, that we don't run into trouble because of
+        // a little numerical uncertanty
+        if (fData[idx]>1)
+            fData[idx]=1;
+        if (fData[idx]<0)
+            fData[idx]=0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event.
+// The level is the absolute number of photons times the area-ratio.
+//
+void MCameraData::CalcCleaningAbsolute(const MSignalCam &evt, const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // Reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    const Int_t entries = evt.GetNumPixels();
+
+    // calculate cleaning levels
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &spix = evt[idx];
+
+        // Set probability
+        fData[idx]     = spix.GetNumPhotons() * geom.GetPixRatio(idx);
+        fValidity[idx] = 1;
+    }
+}
+
+void MCameraData::CalcCleaningArrivalTime(const MSignalCam &evt, const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // Reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of noise
+    const Int_t entries = evt.GetNumPixels();
+    TArrayD u(6), w(6);
+    TArrayI ii(6);
+
+    for (int i=0; i<entries; i++)
+    {
+        if (evt[i].IsPixelUnmapped())
+            continue;
+
+        const Double_t t0 = evt[i].GetArrivalTime();
+        const Double_t s0 = evt[i].GetNumPhotons();
+        const Double_t r0 = geom.GetPixRatio(i);
+        const Double_t x0 = geom[i].GetX();
+        const Double_t y0 = geom[i].GetY();
+
+        const Double_t e0 = s0<0.01 ? 100 : 1./s0;
+
+        const Int_t n2 = geom[i].GetNumNeighbors();
+
+        Int_t cnt2=0;
+        for (int j=0; j<n2; j++)
+        {
+            Int_t idx = geom[i].GetNeighbor(j);
+
+            if (evt[idx].IsPixelUnmapped())
+                continue;
+
+            const Double_t tj = evt[idx].GetArrivalTime()-t0;
+            const Double_t sj = evt[idx].GetNumPhotons();
+            const Double_t rj = geom.GetPixRatio(idx)+r0;
+            const Double_t xj = geom[idx].GetX()-x0;
+            const Double_t yj = geom[idx].GetY()-y0;
+
+            const Double_t d2 = xj*xj+yj*yj;
+
+            const Double_t ej = sj<0.01 ? 100 : 1./sj;
+
+            u[cnt2] =  tj*tj/rj;
+            w[cnt2] =  1./(e0+ej)/d2;         // TYPE I+II
+            cnt2++;
+        }
+
+        TMath::Sort(cnt2, u.GetArray(), ii.GetArray(), kFALSE);
+
+        Double_t sumt = 0;
+        Double_t sumw = 0;
+        for (int j=0; j<TMath::Min(cnt2, 3); j++)
+        {
+            sumt += u[ii[j]]*w[ii[j]];
+            sumw += w[ii[j]];
+        }
+
+        const Double_t wuz = TMath::Sqrt(sumt/sumw);
+
+        if (TMath::IsNaN(wuz))
+            *fLog << warn << "WARNING - MCameraData " << sumt << " " << sumw << endl;
+
+        Double_t val = s0<0 || TMath::IsNaN(wuz) || wuz<1e-200 ? 0 : s0*r0/wuz;
+
+        if ((s0>0 && wuz<1e-200) || val>100)
+            val=100;
+
+        fData[i] = TMath::Log10(val+1)*5;
+
+        if (TMath::IsNaN(fData[i]))
+            //     0                1e-6          0              NaN
+            *fLog << warn << "WARNING - MCameraData " << sumt << " " << sumw << " " << wuz << " " << val << endl;
+
+        fValidity[i] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the contents of the pixel.
+//
+Bool_t MCameraData::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx<0 || idx>=fData.GetSize())
+        return kFALSE;
+
+    val = fData[idx];
+    return fValidity[idx];
+}
+
+void MCameraData::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MCameraData::DrawPixelContent - not available." << endl;
+}
+
+void MCameraData::Print(Option_t *o) const
+{
+    MParContainer::Print(o);
+    *fLog << "Size = " << fData.GetSize() << endl;
+    for (int i=0; i<fData.GetSize(); i++)
+        cout << i << ": " << fData[i] << endl;
+}
Index: branches/Mars_McMismatchStudy/manalysis/MCameraData.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MCameraData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MCameraData.h	(revision 17960)
@@ -0,0 +1,59 @@
+#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 MSignalCam;
+class MPedPhotCam;
+
+class MCameraData : public MParContainer, public MCamEvent
+{
+private:
+    TArrayD fData;  //
+    TArrayC fValidity;
+
+public:
+    MCameraData(const char *name=NULL, const char *title=NULL);
+    ~MCameraData() { }
+
+    UInt_t GetNumPixels() const { return fData.GetSize(); }
+
+    void CalcCleaningLevel(const MSignalCam &evt, const MPedPhotCam &fCam,
+                           const MGeomCam &geom);
+    void CalcCleaningLevel(const MSignalCam &evt, Double_t noise,
+                           const MGeomCam &geom);
+    void CalcCleaningLevel2(const MSignalCam &evt, const MPedPhotCam &fCam,
+                            const MGeomCam &geom);
+    void CalcCleaningLevelDemocratic(const MSignalCam &evt, const MPedPhotCam &cam,
+                                     const MGeomCam &geom);
+    void CalcCleaningProbability(const MSignalCam &evt, const MPedPhotCam &pcam,
+                                 const MGeomCam &geom);
+    void CalcCleaningAbsolute(const MSignalCam &evt, const MGeomCam &geom);
+    void CalcCleaningArrivalTime(const MSignalCam &evt, const MGeomCam &geom);
+
+    const TArrayD &GetData() const { return fData; }
+    const TArrayC &GetValidity() const  { return fValidity; }
+
+    Double_t operator[](int i) { return fData[i]; }
+
+    void Print(Option_t *o="") const;
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MCameraData, 1) // Generalized storage class for camera data
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/manalysis/MCompProbCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MCompProbCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MCompProbCalc.cc	(revision 17960)
@@ -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): 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 "MDataPhrase.h"
+
+#include "MHCompProb.h"
+#include "MParameters.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
+//
+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()))
+    {
+        MDataPhrase *chain = new MDataPhrase(data->GetName());
+        if (!chain->PreProcess(plist))
+        {
+            delete chain;
+            return kFALSE;
+        }
+        fData->Add(chain);
+    }
+
+    fHadronness = (MParameterD*)plist->FindCreateObj("MParameterD", "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 Hadronness 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->SetVal(pow(p, 1./n));
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/manalysis/MCompProbCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MCompProbCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MCompProbCalc.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MCompProbCalc
+#define MARS_MCompProbCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MParList;
+class MParameterD;
+
+class MCompProbCalc : public MTask
+{
+private:
+    MParameterD *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: branches/Mars_McMismatchStudy/manalysis/MEnergyEstParam.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEnergyEstParam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEnergyEstParam.cc	(revision 17960)
@@ -0,0 +1,377 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): 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;
+
+        // !Finitite includes IsNaN
+        if (!TMath::Finite(ir))
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+        if (!TMath::Finite(er))
+        {
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+            er = 0;
+        }
+
+	est->SetEnergy(er);
+        est->SetImpact(ir);
+        est->SetReadyToSave();
+    }
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/manalysis/MEnergyEstParam.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEnergyEstParam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEnergyEstParam.h	(revision 17960)
@@ -0,0 +1,69 @@
+#ifndef MARS_MEnergyEstParam
+#define MARS_MEnergyEstParam
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MHillasSrc;
+class MEnergyEst;
+class MHillas;
+class MMcEvt;
+class MHMatrix;
+
+class MEnergyEstParam : public MTask
+{
+private:
+    Int_t     fMap[100]; // FIXME!
+
+    MHMatrix *fMatrix;
+
+    TList    *fPairs;
+
+    TList    *fHillasSrc;
+    TList    *fEnergy;
+
+    MHillas  *fHillas;
+    TString   fHillasName;
+
+    TArrayD   fA;
+    TArrayD   fB;
+
+    MMcEvt   *fMc;
+
+    void InitCoefficients();
+
+    Double_t GetVal(Int_t i) const;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MEnergyEstParam(const char *hil="MHillas", const char *name=NULL, const char *title=NULL);
+    ~MEnergyEstParam();
+
+    void Add(const TString hillas, const TString energy="MEnergyEst");
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping();
+
+    Int_t GetNumCoeff() const { return fA.GetSize()+fB.GetSize(); }
+
+    void SetCoeff(const TArrayD &arr);
+    void SetCoeffA(const TArrayD &arr);
+    void SetCoeffB(const TArrayD &arr);
+
+    void SetVariables(const TArrayD &arr) { SetCoeff(arr); }
+
+    Double_t GetCoeff(Int_t i) { return i<fA.GetSize()? fA[i] : fB[i-fA.GetSize()]; }
+
+    void Print(Option_t *o=NULL) const;
+
+    ClassDef(MEnergyEstParam, 0) // Task to estimate the energy
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/manalysis/MEnergyEstParamDanielMkn421.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEnergyEstParamDanielMkn421.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEnergyEstParamDanielMkn421.cc	(revision 17960)
@@ -0,0 +1,402 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  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;
+
+        // !Finitite includes IsNaN
+        if (!TMath::Finite(ir))
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+        if (!TMath::Finite(er))
+        {
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+            er = 0;
+        }
+
+	est->SetEnergy(er);
+        est->SetImpact(ir);
+        est->SetReadyToSave();
+
+    }
+
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MEnergyEstParamDanielMkn421.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEnergyEstParamDanielMkn421.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEnergyEstParamDanielMkn421.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/MEnergyEstimate.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEnergyEstimate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEnergyEstimate.cc	(revision 17960)
@@ -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/2002 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MEnergyEstimate
+//
+// Task to estimate the energy by a rule, eg:
+//
+// MEnergyEstimate est;
+// est.SetRule("0.5 + (1.1*MHillas.fLength) + (2.2*MHillasSrc.fDist) + (3.3*MHillas.fSize) +"
+//             "(4.4*MHillas.fSize*MHillas.fLength) + (5.5*MHillasSrc.fDist*MHillas.fLength)");
+//
+// For description of rules, see MDataPhrase.
+//
+// The default rule is "MMcEvt.fEnergy"
+//
+// Output:
+//   MEnergyEst [MParameterD]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MEnergyEstimate.h"
+
+ClassImp(MEnergyEstimate);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Initialize fData with default rule "MMcEvt.fEnergy"
+//
+MEnergyEstimate::MEnergyEstimate(const char *name, const char *title)
+    : MParameterCalc("MMcEvt.fEnergy")
+{
+    fName  = name  ? name  : "MEnergyEstimate";
+    fTitle = title ? title : "Task to estimate the energy by a rule";
+
+    SetNameParameter("MEnergyEst");
+}
Index: branches/Mars_McMismatchStudy/manalysis/MEnergyEstimate.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEnergyEstimate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEnergyEstimate.h	(revision 17960)
@@ -0,0 +1,17 @@
+#ifndef MARS_MEnergyEstimate
+#define MARS_MEnergyEstimate
+
+#ifndef MARS_MParameterCalc
+#include "MParameterCalc.h"
+#endif
+
+class MEnergyEstimate : public MParameterCalc
+{
+public:
+    MEnergyEstimate(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MEnergyEstimate, 1) // Task to estimate the energy by a rule
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/manalysis/MEventRate.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEventRate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEventRate.cc	(revision 17960)
@@ -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): 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 <TMath.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]";
+}
+
+Double_t MEventRate::GetError() const
+{
+    return TMath::Sqrt(1./fNumEvents);
+}
Index: branches/Mars_McMismatchStudy/manalysis/MEventRate.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEventRate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEventRate.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/MEventRateCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEventRateCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEventRateCalc.cc	(revision 17960)
@@ -0,0 +1,248 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MEventRateCalc
+//
+//  This task calculates the event rates from the event times and numbers.
+//
+//  The algorithm is explained in Process()
+//
+//
+//    rate = Number of events / time in which the events were recorded
+//       r = N / t
+//       s = t / N  = 1 / r    mean time interval between consecutive events
+//
+//    for an exponential distribution of the time differences d between
+//    consecutive events:
+//
+//       s = <d>
+//       sigma(d)     = <d> = s
+//       delta(s)     = sigma(d) /sqrt(N) = s / sqrt(N)
+//       delta(s) / s = 1 / sqrt(N)
+//
+//       delta(r) / r = delta(s) / s = 1 / sqrt(N)
+//
+//
+//  In addition the difference between the event time of the current event
+//  and the last event is written into a MParameterD calles MTimeDiff.
+//
+//
+//  Input Containers:
+//    MTime
+//
+//  Output Containers:
+//    MEventRate
+//    MTimeDiff [MParameterD]
+//    MTimeRate [MTime] (missing)
+//
+//  FIXME: For convinience we could implement a mode which always takes
+//         n events to calculate the event rate and sets the corresponding
+//         time. This mode could be used to UPADTE files with the event
+//         rate.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MEventRateCalc.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MTime.h"
+#include "MEventRate.h"
+#include "MParameters.h"
+
+ClassImp(MEventRateCalc);
+
+using namespace std;
+
+const TString MEventRateCalc::gsDefName  = "MEventRateCalc";
+const TString MEventRateCalc::gsDefTitle = "Calculate event rate";
+
+const TString MEventRateCalc::gsNameTime      = "MTime";
+const TString MEventRateCalc::gsNameEventRate = "MEventRate";
+const TString MEventRateCalc::gsNameTimeDiff  = "MTimeDiff";
+const TString MEventRateCalc::gsNameTimeRate  = "MTimeRate";
+
+const Int_t MEventRateCalc::gsNumEvents = 1000;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MEventRateCalc::MEventRateCalc(const char *name, const char *title)
+    : fNameEventRate(gsNameEventRate), fNameTime(gsNameTime),
+    fNameTimeRate(gsNameTimeRate), fNameTimeDiff(gsNameTimeDiff),
+    fTimes(gsNumEvents)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//   MTime
+//
+// The PreProcess searches for the following input containers:
+//   MEventRate
+//
+// Reset all times in the buffer
+//
+Int_t MEventRateCalc::PreProcess(MParList *pList)
+{
+    fTime = (MTime*)pList->FindObject(AddSerialNumber(fNameTime), "MTime");
+    if (!fTime)
+    {
+        *fLog << err << AddSerialNumber(fNameTime) << " [MTime] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRate = (MEventRate*)pList->FindCreateObj("MEventRate", AddSerialNumber(fNameEventRate));
+    if (!fRate)
+        return kFALSE;
+
+    fTimeRate = (MTime*)pList->FindCreateObj("MTime", AddSerialNumber(fNameTimeRate));
+    if (!fTimeRate)
+        return kFALSE;
+
+    fTimeDiff = (MParameterD*)pList->FindCreateObj("MParameterD", AddSerialNumber(fNameTimeDiff));
+    if (!fTimeDiff)
+        return kFALSE;
+
+    fTimes.Reset();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This resets the calculation whenever a new file is opened.
+//
+Bool_t MEventRateCalc::ReInit(MParList *pList)
+{
+    fNumFirstEvent = GetNumExecutions();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the events rate as (t1-t0)/n while t1 is the n-th event after
+// t0. If there are not yet enough events in the buffer n is the number
+// of available events. Otherwise the number setup in SetNumEvents.
+//
+Int_t MEventRateCalc::Process()
+{
+    const ULong_t exec = GetNumExecutions()-fNumFirstEvent-1;
+
+    //*fLog << all << fNumFirstEvent << " " << exec << endl;
+
+    // Calculate the rate
+    const UInt_t n = fTimes.GetSize();
+
+    // Get the positon in the ring-buffer
+    const UInt_t n1 = exec;
+    const UInt_t n2 = exec>=n ? exec+1 : 0;
+
+    // Store the current event time
+    fTimes[n1%n] = *fTime;
+
+    // Get the number of events
+    const UInt_t cnt = n1<n2 ? n : n1-n2;
+
+    // Store the time difference between two consecutive events
+    fTimeDiff->SetVal(exec==0 ? -1 : fTimes[n1%n] - fTimes[(n1+n-1)%n]);
+    fTimeDiff->SetReadyToSave();
+
+    // Make sure, that the beginning of data-takeing (open
+    // a new file) doesn't effect the rate too much
+    if (cnt<n/10)
+        return kTRUE;
+
+    // Calculate the rate
+    const Double_t rate = (Double_t)cnt/(fTimes[n1%n]-fTimes[n2%n]);
+
+    // Store the rate
+    fRate->SetRate(exec>1?rate:0, cnt);
+    fRate->SetReadyToSave();
+
+    // Calculate and store the corresponding time
+    const Double_t diff = fTimes[n1%n] - fTimes[n2%n];
+    const Double_t time = fTimes[n2%n] + (cnt-n/10.)/(n-n/10.)*diff/2;
+
+    fTimeRate->SetMean(time, time);
+    fTimeRate->SetReadyToSave();
+
+   /*
+    // Store the corresponding time
+    if (exec==fNumFirstEvent+n)
+        fTimeRate->SetMean(fTimes[n2%n], fTimes[n2%n]);
+    else
+        fTimeRate->SetMean(fTimes[n1%n], fTimes[n2%n]);
+        */
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MEventRateCalc::StreamPrimitive(ostream &out) const
+{
+    out << "   MEventRateCalc " << GetUniqueName() << "(";
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "\"" <<fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (fTimes.GetSize()!=gsNumEvents)
+        out << "   " << GetUniqueName() << ".SetNumEvents(" << fTimes.GetSize() << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MEventRateCalc.NumEvents: 1000
+//
+Int_t MEventRateCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumEvents", print))
+    {
+        rc = kTRUE;
+        SetNumEvents(GetEnvValue(env, prefix, "NumEvents", fTimes.GetSize()));
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/manalysis/MEventRateCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MEventRateCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MEventRateCalc.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MEventRateCalc
+#define MARS_MEventRateCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MTime;
+class MEventRate;
+class MParameterD;
+
+class MEventRateCalc : public MTask
+{
+private:
+    static const TString gsDefName;       //! Default name of container
+    static const TString gsDefTitle;      //! Default title of container
+
+    static const TString gsNameEventRate; //! default name of rate container
+    static const TString gsNameTime;      //! Default name of time container
+    static const TString gsNameTimeDiff;  //! default name of time-diff container
+    static const TString gsNameTimeRate;  //! default name of time-rate container
+
+    static const Int_t gsNumEvents;       //! Default number of events
+
+
+    MTime       *fTime;       //! pointer to event time
+    MTime       *fTimeRate;   //! pointer to time of event rate
+    MEventRate  *fRate;       //! pointer to rate storage container
+    MParameterD *fTimeDiff;   //! Difference of time between two consecutive events
+
+    TString fNameEventRate;  // name of event rate container
+    TString fNameTime;       // name of time container
+    TString fNameTimeRate;   // name of event rate time container
+    TString fNameTimeDiff;   // name of time-diff container
+
+    TArrayD  fTimes;         //! internal array to store the last n event times
+
+    Int_t fNumFirstEvent;    //! Number of first event in file
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+    void  StreamPrimitive(std::ostream &out) const;
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MEventRateCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetNumEvents(ULong_t num) { fTimes.Set(num); }
+
+    void SetNameEventRate(const char *name) { fNameEventRate = name; }
+    void SetNameTime(const char *name)      { fNameTime = name; }
+    void SetNameTimeDiff(const char *name)  { fNameTimeDiff = name; }
+    void SetNameTimeRate(const char *name)  { fNameTimeRate = name; }
+
+    ClassDef(MEventRateCalc, 1)// Task to calculate event rates
+};
+ 
+
+#endif
Index: branches/Mars_McMismatchStudy/manalysis/MFiltercutsCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MFiltercutsCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MFiltercutsCalc.cc	(revision 17960)
@@ -0,0 +1,180 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): 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 "MFDataPhrase.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 MFDataPhrase(lo<name && name<up) to the filter list (&&),
+// for more details see MFDataPhrase::MFDataPhrase(), too.
+//
+void MFiltercutsCalc::AddCut(const char *name, Double_t lo, Double_t up)
+{
+    AddToList(new MFDataPhrase(Form("%s>%.15f", name, lo));
+    AddToList(new MFDataPhrase(name, '<', up));
+}
+
+// --------------------------------------------------------------------------
+//
+// There is MUCH space for speed improvement!
+// Add MFDataPhrase(fabs(name)<val) to the filter list (&&),
+// for more details see MFDataPhrase::MFDataPhrase(), 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 MFDataPhrase::MFDataPhrase(), too.
+//
+void MFiltercutsCalc::AddCut(const char *cut)
+{
+    AddToList(new MFDataPhrase(cut));
+}
+
+// --------------------------------------------------------------------------
+//
+// There is MUCH space for speed improvement!
+// Add cut to filter list (&&), for more details see MFDataPhrase::MFDataPhrase(), 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: branches/Mars_McMismatchStudy/manalysis/MFiltercutsCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MFiltercutsCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MFiltercutsCalc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/MGeomApply.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MGeomApply.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MGeomApply.cc	(revision 17960)
@@ -0,0 +1,283 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 09/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Markus Gaug,  03/2004 <mailto:markus@ifae.es>
+!              Hendrik Bartko, 07/2003 <mailto:hbartko@mppmu.mpg.de>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MGeomApply
+//
+//  Applies the geometry to geometry dependant containers.
+//
+//  It changes the size of the arrays in the containers to a size
+//  matching the number of pixels, eg:
+//
+//   MPedestalCam
+//   MCalibrationChargeCam
+//   MCalibrationRelTimeCam
+//   MCalibrationQECam
+//   MCalibrationPedCam
+//   MPedPhotCam
+//   MExtractedSignalCam
+//   MArrivalTime
+//
+//  It uses the geometry (MGeomCam) found in the parameter list.
+//  If it is not found the task tries to create the geometry
+//  specified in the constructor. The default geometry is
+//  MGeomCamMagic.
+//
+// In a standard setup all containers in the parameter list which derive
+// from MCamEvent are processed automatically in ReInit. To allow having
+// two parallel geometries in the parameter list or for MCamEvent in the
+// parameter list you can switch off the automatic procedure by adding
+// the containers to be processed using AddCamEvent().
+//
+// 
+//  Input Containers:
+//   [MGeomCam]
+//   [all MCamEvent]
+//
+//  Output Containers:
+//   [all MCamEvent]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MGeomApply.h"
+
+#include <stdlib.h> // atoi (Ubuntu 8.10)
+
+#include <fstream>
+
+#include <TObjString.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MCamEvent.h"
+#include "MRawRunHeader.h"
+
+ClassImp(MGeomApply);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. MGeomCamMagic is the default geometry.
+//
+MGeomApply::MGeomApply(const char *name, const char *title)
+    : fGeomName("MGeomCamMagic"), fNamesList(0), fList(0)
+{
+    fName  = name  ? name  : "MGeomApply";
+    fTitle = title ? title : "Task to apply geometry settings";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete fList if available.
+//
+MGeomApply::~MGeomApply()
+{
+    if (fList)
+        delete fList;
+    if (fNamesList)
+        delete fNamesList;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Try to find 'MGeomCam' in the Parameter List. If it is not found,
+//  try to create a fGeomName object.
+//
+Int_t MGeomApply::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (cam)
+        return kTRUE;
+
+    MRawRunHeader *h = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (h->GetCameraVersion()==0xfac7 && fGeomName=="MGeomCamMagic")
+        fGeomName = "MGeomCamFACT";
+
+    cam = (MGeomCam*)pList->FindCreateObj(AddSerialNumber(fGeomName), "MGeomCam");
+
+    return cam ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check the whole parameter list for MCamEvent. For all MCamEvent
+//  MCamEvent::Init(MGeomCam&) is called.
+//
+void MGeomApply::ProcessAutomatic(MParList &list, const MGeomCam &geom) const
+{
+    TIter Next(list);
+    TObject *o = 0;
+
+    while ((o=Next()))
+    {
+        MCamEvent *cam = dynamic_cast<MCamEvent*>(o);
+        if (!cam)
+            continue;
+
+        // If the MGeomApply task has a serial number >0 (indicating most likely
+        // a specific telescope in a multi-telescope file), then apply the
+        // geometry only to objects with the same serial number. This is important
+        // for stereo setups in which the telescopes have cameras with different
+        // numbers of pixels. If the MGeomApply task has serial number 0 (default),
+        // it will apply the geometry to all found objects as it used to do.
+        const TString name(o->GetName());
+
+        // Extract serial number from name:
+        const Int_t serial = atoi(name.Data()+name.Last(';')+1);
+
+        // Compare with the serial number of this task:
+        if (serial>0 && serial!=GetSerialNumber())
+            continue;
+
+        // Initialize object according to camera geometry:
+        cam->Init(geom);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check all containers in fNamesList and fList. For all MCamEvent
+//  MCamEvent::Init(MGeomCam&) is called.
+//
+Bool_t MGeomApply::ProcessManual(MParList &list, const MGeomCam &geom) const
+{
+    TIter NextN(fNamesList);
+    TObject *o = 0;
+
+    while ((o=NextN()))
+    {
+        TObject *cont = list.FindObject(o->GetName(), "MCamEvent");
+        if (!cont)
+        {
+            *fLog << err << o->GetName() << " [MCamEvent] not found... abort." << endl;
+            return kFALSE;
+        }
+
+        MCamEvent *cam = dynamic_cast<MCamEvent*>(o);
+        cam->Init(geom);
+    }
+
+    TIter NextL(fList);
+    while ((o=NextL()))
+    {
+        MCamEvent *cam = dynamic_cast<MCamEvent*>(o);
+        cam->Init(geom);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Try to find 'MGeomCam' in the Parameter List. If it is not found,
+//  processing is stopped.
+//
+Bool_t MGeomApply::ReInit(MParList *pList)
+{
+    MGeomCam *geom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!geom)
+    {
+       *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // FIXME (workaround): this call to CalcPixRatio is here just to allow
+    // the use of some MC camera files from the 0.7 beta version in which the 
+    // array containing pixel ratios is not initialized.
+    geom->StreamerWorkaround();
+    geom->CalcPixRatio();
+
+    if (fList)
+        return ProcessManual(*pList, *geom);
+
+    ProcessAutomatic(*pList, *geom);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MGeomApply::StreamPrimitive(ostream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (fGeomName.IsNull())
+        return;
+
+    out << "   " << GetUniqueName() << ".SetGeometry(\"";
+    out << fGeomName << "\");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a MCamEvent to be processed. This switches off the automatic
+// processing of all MCamEvent in the parameter list completely!
+//
+void MGeomApply::AddCamEvent(TObject *obj)
+{
+    if (!obj->InheritsFrom(MCamEvent::Class()))
+    {
+        *fLog << warn << "MGeomApply::AddCamEvent - WARNING: Object doesn't inherit from MCamEvent... ignored." << endl;
+        return;
+    }
+
+    if (!fList)
+    {
+        fList = new TList;
+        fNamesList = new TList;
+
+        fNamesList->SetOwner();
+    }
+
+    fList->Add(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a MCamEvent to be processed. This switches off the automatic
+// processing of all MCamEvent in the parameter list completely!
+//
+void MGeomApply::AddCamEvent(const char *name)
+{
+    if (!fList)
+    {
+        fList = new TList;
+        fNamesList = new TList;
+
+        fNamesList->SetOwner();
+    }
+
+    fNamesList->Add(new TObjString(name));
+}
Index: branches/Mars_McMismatchStudy/manalysis/MGeomApply.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MGeomApply.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MGeomApply.h	(revision 17960)
@@ -0,0 +1,39 @@
+#ifndef MARS_MGeomApply
+#define MARS_MGeomApply
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MGeomCam;
+
+class MGeomApply : public MTask
+{
+private:
+    TString fGeomName; // Name of geometry class
+
+    TList *fNamesList;
+    TList *fList;
+
+    void ProcessAutomatic(MParList &plist, const MGeomCam &geom) const;
+    Bool_t ProcessManual(MParList &plist, const MGeomCam &geom) const;
+
+    Int_t  PreProcess(MParList *plist);
+    Bool_t ReInit(MParList *pList);
+    void   StreamPrimitive(std::ostream &out) const;
+
+public:
+    MGeomApply(const char *name=NULL, const char *title=NULL);
+    ~MGeomApply();
+
+    void SetGeometry(TString geom) { fGeomName = geom; }
+
+    void AddCamEvent(TObject *obj);
+    void AddCamEvent(const char *name);
+
+    ClassDef(MGeomApply, 0) // Task to apply geometry settings
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/manalysis/MMakePadHistograms.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMakePadHistograms.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMakePadHistograms.cc	(revision 17960)
@@ -0,0 +1,350 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 09/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMakePadHistograms
+//
+//     reads calibrated data of a particular type (ON, OFF or MC)
+//     and produces the histograms for the padding
+//
+//     these histograms are further treated in MPad
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMakePadHistograms.h"
+
+#include <math.h>
+#include <stdio.h>
+
+#include <TH2.h>
+#include <TH3.h>
+#include <TCanvas.h>
+#include <TFile.h>
+
+#include "MBadPixelsCalc.h"
+#include "MBadPixelsTreat.h"
+#include "MContinue.h"
+#include "MEvtLoop.h"
+#include "MFillH.h"
+#include "MFSelBasic.h"
+#include "MGeomApply.h"
+#include "MHBadPixels.h"
+#include "MHSigmaTheta.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadReports.h"
+#include "MTaskList.h"
+//#include "MExtrapolatePointingPos.h"
+#include "MPointingPosCalc.h"
+
+ClassImp(MMakePadHistograms);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MMakePadHistograms::MMakePadHistograms(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MMakePadHistograms";
+  fTitle = title ? title : "Class to make Pad histograms";
+
+  fHSigmaTheta      = NULL;
+  fHSigmaThetaOuter = NULL;
+  fHDiffPixTheta    = NULL;
+  fHSigmaPixTheta   = NULL;
+
+  fHBadIdTheta      = NULL;
+  fHBadNTheta       = NULL;
+
+  // default values
+  fType             = "";
+  fMaxEvents        = -1;
+  fNamePedPhotCam   = "MPedPhotCamFromData";
+  fNameInputFile    = "";
+  fNameOutputFile   = "";
+  fPedestalLevel    = 3.0;
+  fUseInterpolation = kTRUE;
+  fProcessPedestal  = kTRUE;
+  fProcessTime      = kFALSE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// SetDataType. 
+//
+//    the type may be  ON, OFF or MC
+//
+void MMakePadHistograms::SetDataType(const char *type) 
+{
+  fType = type;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetMaxEvents. 
+//
+//    set the maximum number of events to be read
+//
+void MMakePadHistograms::SetMaxEvents(Int_t maxev) 
+{
+  fMaxEvents = maxev;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNameInputFile. 
+//
+//    the input file contains the calibrated data
+//
+void MMakePadHistograms::SetNameInputFile(const char *input) 
+{
+  fNameInputFile = input;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNameOutputFile. 
+//
+//    the output file contains the histgrams for the padding
+//
+void MMakePadHistograms::SetNameOutputFile(const char *output) 
+{
+  fNameOutputFile = output;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNamePedPhotCam. 
+//
+//    set the name of the MPedPhotCam container;
+//    it is used in : MBadPixelsCalc, MBadPixelsTreat, MHSigmaTheta
+//
+void MMakePadHistograms::SetNamePedPhotCam(const char *name) 
+{
+  fNamePedPhotCam = name;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetPedestalLevel. 
+//
+//    set the pedestal level;
+//    it is used in : MBadPixelsCalc
+//
+void MMakePadHistograms::SetPedestalLevel(Float_t pedlevel) 
+{
+  fPedestalLevel = pedlevel;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetUseInterpolation. 
+//
+//    set the option "UseInterpolation";
+//    it is used in : MBadPixelsTreat
+//
+void MMakePadHistograms::SetUseInterpolation(Bool_t useinter) 
+{
+  fUseInterpolation = useinter;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetProcessPedestal. 
+//
+//    set the option "ProcessPedestal";
+//    it is used in : MBadPixelsTreat
+//
+void MMakePadHistograms::SetProcessPedestal(Bool_t procped) 
+{
+  fProcessPedestal = procped;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetProcessTime. 
+//
+//    set the option "ProcessTime";
+//    it is used in : MBadPixelsTreat
+//
+void MMakePadHistograms::SetProcessTime(Bool_t proctim) 
+{
+  fProcessTime = proctim;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MMakePadHistograms::MakeHistograms()
+{
+      if (fType == "")
+      {
+        *fLog << err << "MMakePadHistograms::MakeHistograms;   type of input data is not defined"
+              << endl;
+        return kFALSE;
+      }
+
+      if (fNameInputFile == "")
+      {
+        *fLog << err << "MMakePadHistograms::MakeHistograms;   name of input file is not defined"
+              << endl;
+        return kFALSE;
+      }
+
+      if (fNameOutputFile == "")
+      {
+        *fLog << err << "MMakePadHistograms::MakeHistograms;   name of output file is not defined"
+              << endl;
+        return kFALSE;
+      }
+
+      *fLog << "------------" << endl;
+      *fLog << fType << " events :" << endl;
+      *fLog << "------------" << endl;
+      *fLog << "MMakePadHistograms : calibrated " << fType
+            << "  data are read from file " << fNameInputFile << endl;
+
+
+      MTaskList tlist;
+      MParList  plist;
+
+      MReadReports read;
+      read.AddTree("Drive");
+      read.AddTree("Events","MTime.",kTRUE);
+      static_cast<MRead&>(read).AddFile(fNameInputFile);
+
+      read.AddToBranchList("MReportDrive.*");
+      read.AddToBranchList("MRawEvtHeader.*");
+
+//      MReadMarsFile  read("Events", fNameInputFile);
+//      read.DisableAutoScheme();
+
+
+      MGeomApply apply;
+
+//      MExtrapolatePointingPos extraPointing(fNameInputFile);
+      MPointingPosCalc pointposcalc;
+
+      MBadPixelsCalc badcalc;
+      badcalc.SetNamePedPhotCam(fNamePedPhotCam);
+      badcalc.SetPedestalLevel(fPedestalLevel);
+
+      MBadPixelsTreat badtreat;
+      badtreat.SetNamePedPhotCam(fNamePedPhotCam);
+      badtreat.SetUseInterpolation(fUseInterpolation);
+      badtreat.SetProcessPedestal(fProcessPedestal);
+      badtreat.SetProcessTimes(fProcessTime);
+
+      MFSelBasic selbasic;
+      MContinue contbasic(&selbasic);
+      contbasic.SetName("SelBasic");
+
+      MHBadPixels bad("BadPixels");
+      bad.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillbad("BadPixels[MHBadPixels]", "MBadPixelsCam");
+      fillbad.SetName("FillBad");
+
+      MHSigmaTheta sigth("SigmaTheta");
+      sigth.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "");
+      fillsigtheta.SetName("FillSigTheta");    
+ 
+      //*****************************
+      // entries in MParList
+    
+      plist.AddToList(&tlist);
+      plist.AddToList(&bad);
+      plist.AddToList(&sigth);
+
+      //*****************************
+      // entries in MTaskList
+    
+      tlist.AddToList(&read);
+      tlist.AddToList(&apply);
+      tlist.AddToList(&pointposcalc, "Events");
+
+//      tlist.AddToList(&badcalc);  done in callisto
+//      tlist.AddToList(&badtreat); done in callisto
+
+      tlist.AddToList(&contbasic, "Events");
+      tlist.AddToList(&fillbad, "Events");
+      tlist.AddToList(&fillsigtheta, "Events");
+      //*****************************
+
+      MProgressBar bar;
+      MEvtLoop evtloop;
+      evtloop.SetParList(&plist);
+      evtloop.SetProgressBar(&bar);
+
+      //      if ( !evtloop.Eventloop(fMaxEvents) )
+      //    return kFALSE;
+      evtloop.Eventloop(fMaxEvents);
+
+      tlist.PrintStatistics(0, kTRUE);
+
+      bad.DrawClone();
+      sigth.DrawClone();
+
+      // save the histograms for the padding
+      fHSigmaTheta     = (TH2D*)sigth.GetSigmaTheta();
+      fHSigmaThetaOuter= (TH2D*)sigth.GetSigmaThetaOuter();
+      fHSigmaPixTheta  = (TH3D*)sigth.GetSigmaPixTheta();
+      fHDiffPixTheta   = (TH3D*)sigth.GetDiffPixTheta();
+
+      fHBadIdTheta = (TH2D*)bad.GetBadId();
+      fHBadNTheta  = (TH2D*)bad.GetBadN();
+
+      TFile filewrite(fNameOutputFile, "RECREATE", "");
+      fHSigmaTheta->Write();
+      fHSigmaThetaOuter->Write();
+      //fHSigmaPixTheta->Write();
+      fHDiffPixTheta->Write();
+      //fHBadIdTheta->Write();
+      //fHBadNTheta->Write();
+      filewrite.Close();
+
+      *fLog << "" << endl;
+      *fLog << "MMakePadHistograms : padding plots for " << fType
+            << "  data written onto file " << fNameOutputFile << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MMakePadHistograms.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMakePadHistograms.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMakePadHistograms.h	(revision 17960)
@@ -0,0 +1,73 @@
+#ifndef MARS_MMakePadHistograms
+#define MARS_MMakePadHistograms
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH2D;
+class TH3D;
+
+class MMakePadHistograms : public MH
+{
+private:
+
+    TString  fType;              // type of data to be padded (ON, OFF, MC)
+    Int_t    fMaxEvents;         // maximum no.of events to be read
+    TString  fNamePedPhotCam;    // name of the 'MPedPhotCam' container
+    TString  fNameInputFile;     // name of input file (calibrated data)
+    TString  fNameOutputFile;    // name of output file (Pad histograms)
+    Float_t  fPedestalLevel;     // pedestal level for MBadPixelsCalc
+    Bool_t   fUseInterpolation;  // option for MBadPixelsTreat
+    Bool_t   fProcessPedestal;   // option for MBadPixelsTreat
+    Bool_t   fProcessTime;       // option for MBadPixelsTreat
+
+
+    //----------------------------------
+    // plots needed for the padding
+
+    TH2D  *fHSigmaTheta;      // 2D-histogram (Theta, sigmabar(inner))
+    TH2D  *fHSigmaThetaOuter; // 2D-histogram (Theta, sigmabar(outer))
+    TH3D  *fHDiffPixTheta;  // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/Area)
+    TH3D  *fHSigmaPixTheta; // 3D-histogram (Theta, pixel, sigma)
+
+    TH2D  *fHBadIdTheta;    // 2D-histogram (Theta, Id of bad pixel)
+    TH2D  *fHBadNTheta;     // 2D-histogram (Theta, no.of bad pixels)
+
+
+public:
+    MMakePadHistograms(const char *name=NULL, const char *title=NULL);
+ 
+    void SetDataType(const char *);       // type of data (ON, OFF, MC) 
+    void SetMaxEvents(Int_t);             // mx. no.of events to be read 
+    void SetNameInputFile(const char *);  // Calibrated data   
+    void SetNameOutputFile(const char *); // Pad histograms 
+    void SetNamePedPhotCam(const char *); // "MPedPhotCamFromData"
+
+    // parameters for MBadPixelsCalc
+    void SetPedestalLevel(Float_t);
+
+    // parameters for MBadPixelsTreat
+    void SetUseInterpolation(Bool_t);
+    void SetProcessPedestal(Bool_t);
+    void SetProcessTime(Bool_t);
+
+    Bool_t MakeHistograms();
+
+    ClassDef(MMakePadHistograms, 0)    // class for making the padding histograms 
+}; 
+
+#endif
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MMarquardt.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMarquardt.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMarquardt.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/MMarquardt.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMarquardt.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMarquardt.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/MMatrixLoop.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMatrixLoop.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMatrixLoop.cc	(revision 17960)
@@ -0,0 +1,95 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  9/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMatrixLoop
+//
+// Use this task instead of reading from a file. It loops through the rows
+// of a given MHMatrix. PreProcessing the task again starts from scratch.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMatrixLoop.h"
+
+#include "MHMatrix.h"
+#include "MLog.h"
+
+ClassImp(MMatrixLoop);
+
+const TString MMatrixLoop::gsDefName  = "MRead";
+const TString MMatrixLoop::gsDefTitle = "Loop through a MHMatrix (instead of reading from a file)";
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor. Specify the MHMatrix object you want to loop
+//  through.
+//
+MMatrixLoop::MMatrixLoop(MHMatrix *mat, const char *name, const char *title) : fMatrix(mat), fOperationMode(kDefault)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of events (rows) in the matrix
+//
+UInt_t MMatrixLoop::GetEntries()
+{
+    if (!fMatrix)
+        return 0;
+
+    return fOperationMode==kDefault ? fMatrix->GetNumRows() : (fMatrix->GetNumRows()+1)/2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return name of MHMatrix, <n/a> if not available
+// The name of the matrix must nor contain a '/'
+//
+TString MMatrixLoop::GetFullFileName() const
+{
+    return fMatrix ? fMatrix->GetName() : "<n/a>";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MMatrixLoop::PreProcess(MParList *plist)
+{
+    fNumRow = fOperationMode==kOdd ? 1 : 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()
+{
+    const Int_t rc = fMatrix->SetNumRow(fNumRow);
+    fNumRow += fOperationMode==kDefault ? 1 : 2;
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/manalysis/MMatrixLoop.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMatrixLoop.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMatrixLoop.h	(revision 17960)
@@ -0,0 +1,48 @@
+#ifndef MARS_MMatrixLoop
+#define MARS_MMatrixLoop
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MHMatrix;
+
+class MMatrixLoop : public MRead
+{
+public:
+    enum OperationMode_t {
+        kDefault,
+        kEven,
+        kOdd
+    };
+private:
+    // MMatrixLoop
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    MHMatrix *fMatrix;
+    Int_t     fNumRow;    //! Number of dimensions of histogram
+
+    Byte_t fOperationMode;
+
+    // MRead
+    UInt_t  GetEntries();
+    TString GetFullFileName() const;
+    Bool_t  Rewind() { fNumRow=0; return kTRUE; }
+
+    virtual Int_t AddFile(const char *fname, Int_t entries=-1) { return 0; }
+    Int_t AddFiles(MDirIter &dir) { return 0; }
+
+    // MTask
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MMatrixLoop(MHMatrix *mat, const char *name=NULL, const char *title=NULL);
+
+    void SetOperationMode(OperationMode_t mode) { fOperationMode = mode; }
+
+    ClassDef(MMatrixLoop, 0) // Task 'reading' events from a MHMatrix
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/manalysis/MMcCalibrationUpdate.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMcCalibrationUpdate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMcCalibrationUpdate.cc	(revision 17960)
@@ -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): Abelardo Moralejo, 12/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMcCalibrationUpdate
+//
+//  This task looks for the information about FADC pedestals in
+//  MMcFadcHeader and translates it to the pedestal mean and rms (in adc counts).
+//  If not already existing in the parameter list, an MCalibrationCam object
+//  is created, with the conversion factor between ADC counts and photons or 
+//  photoelectrons (depending on fSignalType) is set to 1 to allow the analysis 
+//  to proceed.
+//
+//  Then it creates and fills also the MPedPhotCam object containing the pedestal
+//  mean and rms in units of photons or photoelectrons.
+//
+//  Input Containers:
+//   MMcFadcHeader
+//   MRawRunHeader
+//  [MCalibrationChargeCam] (if it existed previously)
+//  [MCalibrationQECam] (if it existed previously)
+//
+//  Output Containers:
+//   MPedPhotCam
+//  [MCalibrationChargeCam] (if it did not exist previously)
+//  [MCalibrationQECam] (if it did not exist previously)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcCalibrationUpdate.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargeCam.h"
+
+#include "MCalibrationQEPix.h"
+#include "MCalibrationQECam.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+#include "MGeomCam.h"
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MRawRunHeader.h"
+#include "MMcRunHeader.hxx"
+#include "MMcFadcHeader.hxx"
+#include "MMcConfigRunHeader.h"
+#include "MCalibrateData.h"
+
+ClassImp(MMcCalibrationUpdate);
+
+using namespace std;
+
+MMcCalibrationUpdate::MMcCalibrationUpdate(const char *name, const char *title)
+  :  fFillCalibrationCam(kTRUE), fOuterPixelsGainScaling(kTRUE), fAmplitude(-1.), 
+     fAmplitudeOuter(-1.), fConversionHiLo(-1.), fUserLow2HiGainFactor(-1.), 
+     fSignalType(MCalibrateData::kPhe)
+{
+    fName  = name  ? name  : "MMcCalibrationUpdate";
+    fTitle = title ? title : "Write MC pedestals and conversion factors into MCalibration Container";
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    const MRawRunHeader *run = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!run)
+    {
+        *fLog << warn << dbginf << "WARNING - cannot check file type, MRawRunHeader not found." << endl;
+        return kTRUE;
+    }
+
+    //
+    // If it is no MC file skip this function...
+    //
+    fGeom = 0;
+    if (!run->IsMonteCarloRun())
+    {
+        *fLog << inf << "This is no MC file... skipping." << endl;
+        return kTRUE;
+    }
+
+    const MMcRunHeader* mcrunh = (MMcRunHeader*) pList->FindObject(AddSerialNumber("MMcRunHeader"));
+    if (!mcrunh)
+    {
+        *fLog << err << AddSerialNumber("MMcRunHeader") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (mcrunh->IsCeres())
+    {
+        *fLog << inf;
+        *fLog << "This is a ceres file... skipping." << endl;
+        *fLog << "   MCalibrationChargeCam (calibration constants), MCalibrationQECam (avg quantum efficiency)" << endl;
+        *fLog << "   and MPedPhotCam (randomly extracted pedestal) not updated." << 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;
+    }
+
+    //
+    // Initialize Fadc simulation parameters:
+    //
+    if (fAmplitude < 0)
+    {
+	fAmplitude = fHeaderFadc->GetAmplitud();
+	if (mcrunh->GetCamVersion() > 60)
+	  {
+	    fAmplitudeOuter = fHeaderFadc->GetAmplitudOuter();
+
+	    fHeaderLow2HiGainFactor = fHeaderFadc->GetLow2HighGain();
+
+	    // The high to low gain ratio is stored in MMcFadcHeader.Low2HighGain. 
+	    // However, this is just the ratio of total pulse integrals. Since the 
+	    // shape of the low gain pulse is different from that of the high gain,
+	    // the factor to be applied to signals extracted from low gain depends
+	    // on the type of signal extractor (for instance if we extract the pulse 
+	    // height, the factor is larger than Low2HighGain, because the low gain
+	    // pulse shape is wider and hence lower than the high gain pulse. So the 
+	    // user can set manually the value of the factor to be applied. If such 
+	    // value has not been set by the user, then we takes as default Low2HighGain.
+
+	    if (fUserLow2HiGainFactor < 0.)
+	      fConversionHiLo = fHeaderLow2HiGainFactor;
+	    else
+	      fConversionHiLo = fUserLow2HiGainFactor;
+
+	  }
+	else // old MC files, camera  < v0.7
+	  {
+	    fAmplitudeOuter = fAmplitude;
+	    fConversionHiLo = 10;  // dummy value
+	  }
+
+    }
+    else   // Check that the following files have all the same FADC parameters as the first
+    {
+      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) // files from camera 0.7 or newer
+	{
+	  if( fabs(fHeaderFadc->GetAmplitudOuter()-fAmplitudeOuter) > 1.e-6  ||
+	      fabs(fHeaderLow2HiGainFactor-fHeaderFadc->GetLow2HighGain()) > 1.e-6 )
+	    {
+	      *fLog << err << "Parameters of MMcFadcHeader are not the same for all files... aborting." << endl;
+	      return kFALSE;
+	    }
+	}
+    }
+
+    //
+    // If MCalibrationChargeCam and MCalibrationQECam already existed 
+    // in the parameter list before MMcCalibrationUpdate::PreProcess was 
+    // executed (from a previous calibration loop) we must not fill them, 
+    // hence nothing else has to be done in ReInit:
+    //
+    if (!fFillCalibrationCam)
+        return kTRUE;
+
+    // Now check the light collection for inner and outer pixels to
+    // calculate the ratio between the two. FIXME! Light collection
+    // depends on the incidence angle of the light w.r.t. the camera
+    // plane. For the moment we take the ratio for light impinging
+    // perpendicular to the camera plane.
+    //
+    // As it happens with most containers, we look for AddSerialNumber("MMcConfigRunHeader")
+    // because in the stereo option the camera simulation writes one such header 
+    // per telescope.
+    //
+    MMcConfigRunHeader* mcconfig = (MMcConfigRunHeader*) pList->FindObject(AddSerialNumber("MMcConfigRunHeader"));
+    if (!mcconfig)
+    {
+        *fLog << err << AddSerialNumber("MMcConfigRunHeader") << 
+	  " not found... aborting." << endl;
+        return kFALSE;
+    }
+    TArrayF innerlightcoll = mcconfig->GetLightCollectionFactor();
+    TArrayF outerlightcoll = mcconfig->GetLightCollectionFactorOuter();
+
+    // In principle outer pixels seem to have a different average light 
+    // collection efficiency than outer ones. We set here the factor between
+    // the two.
+
+    fOuterPixelsLightCollection = outerlightcoll[90] / innerlightcoll[90]; 
+    // (at angle = 90 deg)
+
+    // Set now the default conversion from ADC counts to photoelectrons 
+    // (in case no previous calibration existed in the parameter list).
+    //
+    // As default we want to have SIZE in ADC counts, or rather, in "inner pixel
+    // equivalent ADC counts".
+    //
+    // To achieve this:
+    // - In the case fSignalType==kPhot: we set the ADC to photoelectron conversion 
+    // equal to the QE, which will later make the ADC to photon conversion factor 
+    // (= ADC2PhotEl/QE) to be = 1, 
+    //
+    // - In the case fSignalType==kPhe: we set the ADC to photoelectron conversion 
+    // equal to 1, since this will be applied directly to the signals...
+
+    if (fSignalType == MCalibrateData::kPhot)
+      fADC2PhElInner = MCalibrationQEPix::gkDefaultAverageQE;
+    else
+      fADC2PhElInner = 1.;
+
+    //
+    // Set the default ADC to "photoelectrons" conversion factor for outer 
+    // pixels. One can choose not to apply the known (in MC) gain factor 
+    // between inner and outer pixels, (in case fOuterPixelsGainScaling = kFALSE),
+    // which may be useful for display purposes.
+    // If on the contrary we apply the factor, we must take into account the 
+    // different gains photoelectrons->ADC counts, given in MC by fAmplitude
+    // and fAmplitudeOuter. This "default" calibration is such that a shower
+    // completely contained in the inner part would have Size in ADC counts, 
+    // whereas one partially in the outer part would have Size in "equivalent 
+    // inner ADC counts" : the "same" shower (light density distribution) would
+    // have the same Size no matter where in the camera it lies. For this we have 
+    // also to set later (see below) the right QE for outer pixels, which may 
+    // be different from that of inner pixels.
+    //
+
+    if (fOuterPixelsGainScaling)
+      fADC2PhElOuter = fADC2PhElInner
+	* (fAmplitude / fAmplitudeOuter);
+    else
+      fADC2PhElOuter = fADC2PhElInner;
+
+
+    Int_t num = fCalCam->GetSize();
+
+    fCalCam->SetFFactorMethodValid   ( kTRUE );
+    fQECam->SetFFactorMethodValid    ( kTRUE );
+    fQECam->SetBlindPixelMethodValid ( kTRUE );
+    fQECam->SetCombinedMethodValid   ( kTRUE );
+    fQECam->SetPINDiodeMethodValid   ( kTRUE );  
+    
+    for (Int_t i=0; i<num; i++)
+    {
+        MCalibrationChargePix &calpix = (MCalibrationChargePix&)(*fCalCam)[i];
+
+	calpix.SetFFactorMethodValid();
+
+	calpix.SetConversionHiLo(fConversionHiLo);
+	calpix.SetConversionHiLoErr(0.);         // FIXME ?
+
+	//
+	// Write conversion factor ADC to photo-electrons (different for inner
+	// and outer pixels).
+	//
+	Float_t adc2photel = (fGeom->GetPixRatio(i) < fGeom->GetPixRatio(0))?
+	  fADC2PhElOuter : fADC2PhElInner;
+
+
+	calpix.SetMeanConvFADC2Phe(adc2photel);
+        calpix.SetMeanConvFADC2PheVar(0.);
+        calpix.SetMeanFFactorFADC2Phot(0.); // Not used for now.
+
+    }
+
+    //
+    // Now set the average QE for each type of pixels. Correct outer pixels
+    // for different light collection efficiency.
+    //
+    num = fQECam->GetSize();
+    for (Int_t i=0; i<num; i++)
+    {
+        MCalibrationQEPix &qepix = (MCalibrationQEPix&)(*fQECam)[i];
+
+	Float_t avqe = MCalibrationQEPix::gkDefaultAverageQE;
+
+	if (fOuterPixelsGainScaling)
+	  if (fGeom->GetPixRatio(i) < fGeom->GetPixRatio(0))
+	    avqe = MCalibrationQEPix::gkDefaultAverageQE*fOuterPixelsLightCollection;
+
+	qepix.SetAvNormFFactor(1.);
+	// This factor should convert the default average QE to average QE 
+	// for a spectrum like that of Cherenkov light. See the documentation 
+	// of MCalibrationQEPix. Here it is 1 because we calibrate using 
+	// Cherenkov light.
+
+	qepix.SetAverageQE(avqe);
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the MCerPhotPed object
+//
+// This has to be done on an event by event basis because the (calibrated)
+// pedestal fluctuations depend on whether, for each pixel, we are using
+// the high gain or the low gain branch.
+//
+Int_t MMcCalibrationUpdate::Process()
+{
+    // This is the case it is no MC file...
+    if (!fGeom)
+        return kTRUE;
+
+    const Int_t num = fCalCam->GetSize();
+
+    for (Int_t i=0; i<num; i++)
+    {
+	MExtractedSignalPix &sigpix = (*fSignalCam)[i];
+
+        const Bool_t uselo = sigpix.IsHiGainSaturated();
+
+	//
+	// 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 = uselo ?
+	  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 = uselo ?
+            fSignalCam->GetNumUsedLoGainFADCSlices() :
+            fSignalCam->GetNumUsedHiGainFADCSlices();
+
+        const Float_t rms0 = uselo ?
+            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:
+	//
+        const MCalibrationChargePix &calpix = (MCalibrationChargePix&)(*fCalCam)[i];
+        const MCalibrationQEPix     &qepix  = (MCalibrationQEPix&)(*fQECam)[i];
+
+        const Float_t conv = fSignalType == MCalibrateData::kPhot ?
+            calpix.GetMeanConvFADC2Phe() / qepix.GetAverageQE() :
+            calpix.GetMeanConvFADC2Phe();
+
+        const Float_t hi2lo = uselo ? calpix.GetConversionHiLo() : 1;
+
+        (*fPedPhotCam)[i].Set(conv*hi2lo*pedestmean, conv*hi2lo*pedestrms);
+
+    }
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/manalysis/MMcCalibrationUpdate.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMcCalibrationUpdate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMcCalibrationUpdate.h	(revision 17960)
@@ -0,0 +1,69 @@
+#ifndef MARS_MMcCalibrationUpdate
+#define MARS_MMcCalibrationUpdate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MCalibrateData
+#include "MCalibrateData.h"
+#endif
+
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MPedPhotCam;
+class MGeomCam;
+class MMcFadcHeader;
+class MExtractedSignalCam;
+
+class MMcCalibrationUpdate : public MTask
+{
+private:
+    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 to be used for low gain signal calibration.
+
+    Float_t fHeaderLow2HiGainFactor; // Ratio of high to low gain, as read from the MMcFadcHeader
+    Float_t fUserLow2HiGainFactor;   // Ratio of high to low gain, as set manually by the user
+
+
+    Float_t fOuterPixelsLightCollection; 
+    // Photon collection efficiency of outer pixels w.r.t. inner ones.
+
+    MCalibrateData::SignalType_t fSignalType;  
+    // Type defined in MCalibrateData.h. Indicates whether calibration is 
+    // made in photons or in photoelectrons! Default: MCalibrateData::kPhe
+
+    
+public:
+    MMcCalibrationUpdate(const char *name=NULL, const char *title=NULL);
+
+    void SetOuterPixelsGainScaling(Bool_t tf) 
+      { fOuterPixelsGainScaling = tf; }
+
+    void SetUserLow2HiGainFactor(Float_t x) { fUserLow2HiGainFactor = x; }
+
+    void SetSignalType (MCalibrateData::SignalType_t x) { fSignalType = x; }
+    MCalibrateData::SignalType_t GetSignalType () const { return fSignalType; }
+
+    ClassDef(MMcCalibrationUpdate, 0)   // Task which obtains, for MC files, the pedestal mean and rms, and the calibration factor from ADC counts to photons. 
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2.cc	(revision 17960)
@@ -0,0 +1,1040 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Antonio Stamerra  1/2003 <mailto:antono.stamerra@pi.infn.it>
+!   Author(s): Marcos Lopez 1/2003 <mailto:marcos@gae.ucm.es>
+!   Author(s): Nicola Galante 7/2003 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MMcTriggerLvl2                                                          //
+//   Storage container for the 2nd level trigger selection parameters      //
+//    as part of the 2nd level trigger simulation                          //
+//                                                                         //
+// input parameter:                                                        //
+//    fCompactNN number of next neighboors that define a compact pixel     //
+//                                                                         //
+//                                                                         //
+// Basic L2T Selection Parameters:                                         //
+//                                                                         //
+//    fLutPseudoSize number of compact pixels in one LUT                   //
+//    fPseudoSize Multiplicity of the bigger cluster                       //
+//    fSizeBiggerCell higher number of fired pixel in cell                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MMcTriggerLvl2.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MGeomCamMagic.h"
+
+#include "MMcTrig.hxx"
+
+#include "MMcEvt.hxx"
+
+#include "MLog.h"
+
+#include <TCanvas.h>
+
+ClassImp(MMcTriggerLvl2);
+
+using namespace std;
+
+// ---------------------------
+// Initialization of static const data members pixel_in_cell and pixel_in_lut
+
+//
+// Correspondence TABLE between pixel numbering in the trigger cells and
+// the standard spiral counting 
+// (*Note*: Pixels start to count ** from 1 ** instead of 0)
+//
+// This correspondence is valid only for MAGIC-like geometries!
+//
+//  FIXME!  These definitions should be included in a GeomTrig class
+//
+const  Int_t  MMcTriggerLvl2::gsPixelsInCell[gsNPixInCell][gsNCells] = {
+    {26,  91,  66,  71,  76,  81,  86,  269,  224,  233,  242,  251,  260,  391,  336,  347,  358,	369,  380},
+    {25,  61,  41,  45,  49,  53,  57,  215,  175,  183,  191,  199,  207,  325,  275,  285,  295,  305,  315},
+    {24,  37,  22,  25,  28,  31,  34,  167,  132,  139,  146,  153,  160,  265,  220,  229,  238,  247,  256},
+    {23,  19,   9,  11,  13,  15,  17,  125,   95,  101,  107,  113,  119,  211,  171,  179,  187,  195,  203},
+    {27,  62,  67,  72,  77,  82,  87,  270,  225,  234,  243,  252,  261,  392,  337,  348,  359,  370,  381},
+    {12,  38,  42,  46,  50,  54,  58,  216,  176,  184,  192,  200,  208,  326,  276,  286,  296,  306,  316},
+    {11,  20,  23,  26,  29,  32,  35,  168,  133,  140,  147,  154,  161,  266,  221,  230,  239,  248,  257},
+    {10,   8,  10,  12,  14,  16,  18,  126,   96,  102,  108,  114,  120,  212,  172,  180,  188,  196,  204},
+    {22,   2,   3,   4,   5,   6,   7,   90,   65,   70,   75,   80,   85,  164,  129,  136,  143,  150,  157},
+    {28,  93,  99, 105, 111, 117, 123,  271,  226,  235,  244,  253,  262,  393,  338,  349,  360,  371,  382},
+    {13,  63,  68,  73,  78,  83,  88,  217,  177,  185,  193,  201,  209,  327,  277,  287,  297,  307,  317},
+    { 4,  39,  43,  47,  51,  55,  59,  169,  134,  141,  148,  155,  162,  267,  222,  231,  240,  249,  258},
+    { 3,  21,  24,  27,  30,  33,  36,  127,   97,  103,  109,  115,  121,  213,  173,  181,  189,  197,  205},
+    { 9,   9,  11,  13,  15,  17,  19,   91,   66,   71,   76,   81,   86,  165,  130,  137,  144,  151,  158},
+    {21,   3,   4,   5,   6,   7,   2,   61,   41,   45,   49,   53,   57,  123,   93,   99,  105,  111,  117},
+    {29, 130, 137, 144, 151, 158, 165,  218,  227,  236,  245,  254,  263,  394,  339,  350,  361,  372,  383},
+    {14,  94, 100, 106, 112, 118, 124,  170,  178,  186,  194,  202,  210,  328,  278,  288,  298,  308,  318},
+    { 5,  64,  69,  74,  79,  84,  89,  128,  135,  142,  149,  156,  163,  268,  223,  232,  241,  250,  259},
+    { 1,  40,  44,  48,  52,  56,  60,   92,   98,  104,  110,  116,  122,  214,  174,  182,  190,  198,  206},
+    { 2,  22,  25,  28,  31,  34,  37,   62,   67,   72,   77,   82,   87,  166,  131,  138,  145,  152,  159},
+    { 8,  10,  12,  14,  16,  18,   8,   38,   42,   46,   50,   54,   58,  124,   94,  100,  106,  112,  118},
+    {20,  11,  13,  15,  17,  19,   9,   20,   23,   26,   29,   32,   35,   88,   63,   68,   73,   78,   83},
+    {30, 131, 138, 145, 152, 159, 166,  219,  228,  237,  246,  255,  264,  329,  279,  289,  299,  309,  319},
+    {15,  95, 101, 107, 113, 119, 125,  171,  179,  187,  195,  203,  211,  269,  224,  233,  242,  251,  260},
+    { 6,  65,  70,  75,  80,  85,  90,  129,  136,  143,  150,  157,  164,  215,  175,  183,  191,  199,  207},
+    { 7,  41,  45,  49,  53,  57,  61,   93,   99,  105,  111,  117,  123,  167,  132,  139,  146,  153,  160},
+    {19,  23,  26,  29,  32,  35,  20,   63,   68,   73,   78,   83,   88,  125,   95,  101,  107,  113,  119},
+    {37,  24,  27,  30,  33,  36,  21,   39,   43,   47,   51,   55,   59,   89,   64,   69,   74,   79,   84},
+    {31, 132, 139, 146, 153, 160, 167,  220,  229,  238,  247,  256,  265,  270,  225,  234,  243,  252,  261},
+    {16,  96, 102, 108, 114, 120, 126,  172,  180,  188,  196,  204,  212,  216,  176,  184,  192,  200,  208},
+    {17,  66,  71,  76,  81,  86,  91,  130,  137,  144,  151,  158,  165,  168,  133,  140,  147,  154,  161},
+    {18,  42,  46,  50,  54,  58,  38,   94,  100,  106,  112,  118,  124,  126,   96,  102,  108,  114,  120},
+    {36,  43,  47,  51,  55,  59,  39,   64,   69,   74,   79,   84,   89,   90,   65,   70,   75,   80,   85},
+    {32, 133, 140, 147, 154, 161, 168,  221,  230,  239,  248,  257,  266,  217,  177,  185,  193,  201,  209},
+    {33,  97, 103, 109, 115, 121, 127,  173,  181,  189,  197,  205,  213,  169,  134,  141,  148,  155,  162},
+    {35,  68,  73,  78,  83,  88,  63,   95,  101,  107,  113,  119,  125,   91,   66,   71,   76,   81,   86}
+  };
+
+//
+// corrispondence between pixels in cell and lut (pix numbering starts from 1)
+//
+const Int_t MMcTriggerLvl2::gsPixelsInLut[gsNLutInCell][gsNPixInLut] = {
+    { 1,  2,  3,  4,  6,  7,  8,  9, 12, 13, 14, 15},
+    {34, 29, 23, 16, 30, 24, 17, 10, 25, 18, 11,  5},
+    {35, 31, 26, 20, 19, 32, 27, 21, 36, 33, 28, 22},
+  };
+
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor
+//
+MMcTriggerLvl2::MMcTriggerLvl2(const char *name, const char *title):fCompactNN(2),fTriggerPattern(0)
+{
+  fName = name ? name : ClassName();
+  fTitle = title;
+
+  *fLog << "created MMcTriggerLvl2" << endl;
+
+  //
+  // Initialization of the fPixels array to zero
+  //
+  memset (fPixels,0,gsNPixInCell*gsNCells*sizeof(Int_t));
+  memset (fFiredPixel,0,gsNTrigPixels*sizeof(Int_t));
+
+  // create a new camera
+  SetNewCamera(new MGeomCamMagic);
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor
+//
+MMcTriggerLvl2::~MMcTriggerLvl2()
+{
+  delete fGeomCam;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Print functions for debugging and testing
+//
+//  Options available:
+//
+// "cell":
+//     Print out the pixel number of a given trigger cell
+//
+// "status":
+//     Print a table with the status (pixel is fired or not after Lvl1) for 
+//     all the pixels in all the trigger cells
+//
+// "check"
+//     Print a warning message when no starting pixel is found in the 
+//     CalcPseudoSize method.
+//
+//  no option:
+//     Print the value of the selection parameters
+//
+//
+void MMcTriggerLvl2::Print(Option_t *opt) const
+{
+  TString str(opt);
+
+  if (str.Contains("status", TString::kIgnoreCase)) 
+    {
+      *fLog << "    Status of cells 1-9" <<endl;
+      for(int i=0; i<gsNPixInCell; i++)
+	{
+	  for(int j=0; j<9; j++)
+	    {
+	      //      *fLog.width(3);
+	      *fLog <<gsPixelsInCell[i][j]-1 << ":" << fPixels[i][j]  << "\t ";
+	    } 
+	  *fLog << endl;
+	}      
+    }
+  else if (str.Contains("cell", TString::kIgnoreCase)) 
+    {
+      *fLog << "   Pixel numbering in cells 1-9" <<endl;
+      for (int i=0;i<gsNPixInCell;i++)
+	{
+	  for(int j=0; j<9; j++)
+	    {
+	      *fLog << gsPixelsInCell[i][j]-1 << "\t";
+	    }
+	  *fLog << endl;
+	}
+    }
+  else if (str.Contains("check", TString::kIgnoreCase)) 
+    {
+      // check when no starting pixels was found (<<--to be fixed)
+      if (fPseudoSize < 0)
+	*fLog << "  Warning: starting pixel not found. Pseudosize set to -1." << endl;
+    }
+  else 
+    {
+      *fLog << "  L2T selection parameters: " << endl;
+      *fLog << "   - LutPseudoSize  = " << fLutPseudoSize <<  endl;
+      *fLog << "   - CellPseudoSize  = " << fCellPseudoSize <<  endl;
+      *fLog << "   - PseudoSize  = " << fPseudoSize <<  endl;
+      *fLog << "   - BiggerCellSize = " << fSizeBiggerCell << endl;
+      *fLog << "   - TriggerPattern = " << fTriggerPattern << endl;
+    }
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Take the information supplied by the Lvl1 (it reads from the object MMcTrig
+// the status of all pixels after Lvl1) and pass it to the Lvl2 (fill the 
+// array fPixels)
+//
+//
+void MMcTriggerLvl2::SetLv1(MMcTrig *trig)
+{
+  if (!trig)
+    return;
+
+  fMcTrig = trig;
+
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      for(int j=0; j<gsNCells; j++)
+	{
+	  int pixel = gsPixelsInCell[i][j]-1;
+	  fPixels[i][j] = (fMcTrig->IsPixelFired(pixel,0)) ? 1 : 0;
+	  fFiredPixel[pixel]=(fMcTrig->IsPixelFired(pixel,0)) ? 1 : 0;
+	  //if (fFiredPixel[pixel]==1)
+	  //*fLog << pixel<<",";
+	}
+    }
+  //*fLog<<endl<<"Fine evento"<<endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the trigger status ( pixel fired(=1) or not(=0) ) manually for a given
+// pixel of a given cell
+//
+//
+void MMcTriggerLvl2::SetPixelFired(Int_t pixel, Int_t fired)
+{
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      for(int j=0; j<gsNCells; j++)
+	{
+	  if(gsPixelsInCell[i][j]-1==pixel) fPixels[i][j]=fired;
+	}
+    }
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Level 2 Trigger (L2T) parameters. They can be used 
+//  to select the events that have passed the L2T selection rule.
+//
+//
+void MMcTriggerLvl2::Calc()
+{
+
+  // Find the Lut and cell with the higher LutPseudoSize. 
+  int lutcell = CalcBiggerLutPseudoSize(); 
+  fMaxCell = lutcell/10;
+  int maxlut = lutcell-fMaxCell*10;
+  fLutPseudoSize = GetLutCompactPixel(fMaxCell,maxlut);
+
+  fMaxCell = CalcBiggerCellPseudoSize();  // fCellPseudoSize
+  // fMaxCell is used by the PseudoSize to find the starting pixel
+  CalcPseudoSize();
+
+  fSizeBiggerCell = GetCellNumberFired(CalcBiggerFiredCell());
+
+  //*fLog << "fLPS="<<fLutPseudoSize<<endl;
+}
+
+
+
+// --------------------------------------------------------------------------
+//  
+// For a given cell, just count how many pixels have been fired after Lvl1
+//
+Int_t MMcTriggerLvl2::GetCellNumberFired(int cell)
+{
+  int size=0;
+ 
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      size += fPixels[i][cell];
+    }
+
+  return size;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//  
+//  Find the cell which the bigger number of fired pixels
+// 
+//
+Int_t MMcTriggerLvl2::CalcBiggerFiredCell()
+{
+  int size=-1;
+  int cell=-1;
+
+  for(int j=0; j<gsNCells; j++)
+    {
+      if (GetCellNumberFired(j) > size) 
+	{
+	  size = GetCellNumberFired(j);
+	  cell = j;
+	}
+    }
+  
+  //  *fLog << "size " <<size <<" in cell " << cell << endl;
+
+  return cell;
+  
+}
+
+// --------------------------------------------------------------------------
+//  
+// Calculate the higher LutPseudoSize of one event defined as the higher number
+//   of compact pixel in the LUTs of the trigger cells.
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology (it can be 2-NN or 3-NN)
+//
+//   It returns the cell and the LUT with the bigger LutPseudoSize, coded
+//      accordingly to:   cell*10 + LUT 
+//
+Int_t MMcTriggerLvl2::CalcBiggerLutPseudoSize()
+{
+  int size=0;
+  int cell=-1;
+  int lut=-1;
+ 
+  for(int j=0; j<gsNCells; j++)
+    {
+      for(int i=0; i<gsNLutInCell; i++)
+	{
+	  if (GetLutCompactPixel(j,i) >= size) 
+	    {
+	      size = GetLutCompactPixel(j,i);
+	      cell = j;
+	      lut = i;
+	    }      
+	}
+    }
+  
+  //*fLog <<"Max cell: " << cell+1 << "  Max Lut: " << lut+1 << "  PseudoSize: " << size <<endl;
+    
+  return cell*10+lut;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+// Identify compact pixels in one LUT and calculate the LutPseudoSize 
+//   (=number of compact pixels in one LUT)
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology.  
+//   Up to now only  2NN or 3NN are considered 
+//    <!if changed: change check made by Preprocess in MMcTriggerLvl2Calc>    
+//
+//   Returns: 
+//     -1    wrong neighpix
+//     -2    wrong cell (<1 or >19)
+//     -3    wrong lut  (<1 or >3)
+//    else:
+//      the number of compact pixels in one LUT.
+//     
+Int_t MMcTriggerLvl2::GetLutCompactPixel(int cell, int lut)
+{
+  int size=0;
+  int lutpix, a[gsNPixInLut]; 
+  int neighpix= (*this).fCompactNN;
+
+  // check on input variables
+
+  if (neighpix >3 || neighpix < 2) 
+    return(-1);
+
+  if (cell<0 || cell> gsNCells-1)
+    return(-2);
+
+  if (lut<0 || lut> gsNLutInCell-1)
+    return(-3);
+
+
+  //
+  // Warning!!! Following configurations are valid only for the standard MAGIC 
+  // trigger geometry; FIXME! these should be coded somewhere else....
+  //
+
+  // LUT 1 and 2 are similar; LUT 3 differs
+  
+  for(int j=0; j< gsNPixInLut; j++)
+    {
+      lutpix = gsPixelsInLut[lut][j]-1;
+      //    *fLog << "j=" <<j<<"  lutpix="<<lutpix<<"  Cell="<<cell<<endl;
+      a[j] = fPixels[lutpix][cell]; 
+    }
+  
+  //
+  // Look for compact pixels 2NN
+  //
+  if (neighpix==2)
+    {    
+      //  case Lut 1 and 2
+      if (lut == 0 || lut == 1)
+	{
+	  if (a[0] && a[1] && a[4])
+	    size ++;
+	  if (a[1] && ((a[0] && a[4]) || 
+		       (a[4] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[6]) || 
+		       (a[6] && a[7]) )) 
+	    size ++;
+	  if (a[4] && ((a[0] && a[1]) || 
+		       (a[1] && a[5]) || 
+		       (a[5] && a[8]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2]) || 
+		       (a[2] && a[6]) || 
+		       (a[6] && a[9]) || 
+		       (a[9] && a[8]) || 
+		       (a[8] && a[4]) || 
+		       (a[4] && a[1]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3]) || 
+		       (a[3] && a[7]) || 
+		       (a[7] && a[10]) || 
+		       (a[10] && a[9]) || 
+		       (a[9] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6]) || 
+		       (a[6] && a[10]) || 
+		       (a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && ((a[4] && a[5]) || 
+		       (a[5] && a[9]) )) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6]) || 
+			(a[6] && a[7]) || 
+			(a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10]) 
+	    size ++;
+	}
+      
+      //  case Lut 3
+      if (lut==2) 
+	{
+	  if (a[0] && a[1] && a[5])
+	    size ++;
+	  if (a[1] && ((a[0] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[3] && a[4]) || 
+		       (a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[6]) || 
+		       (a[6] && a[7]) || 
+		       (a[2] && a[4]) )) 
+	    size ++;
+	  if (a[4] && ((a[2] && a[3]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2]) || 
+		       (a[2] && a[6]) || 
+		       (a[6] && a[9]) || 
+		       (a[9] && a[8]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3]) || 
+		       (a[3] && a[7]) || 
+		       (a[7] && a[10]) || 
+		       (a[10] && a[9]) || 
+		       (a[9] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6]) || 
+		       (a[6] && a[10]) || 
+		       (a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && a[5] && a[9]) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6]) || 
+			(a[6] && a[7]) || 
+			(a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10]) 
+	    size ++;    
+	}
+    }
+  
+  //
+  // Look for compact pixels 3NN 
+  //
+  if (neighpix==3)
+    {
+      //  case Lut 1 and 2
+      if (lut == 0 || lut == 1)
+	{
+	  if (a[0] && a[1] && a[4] && a[5]) // pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[1] && ((a[0] && a[4] && a[5]) || 
+		       (a[2] && a[4] && a[5]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && (a[2] && a[6] && a[7] ))  
+	    size ++;
+	  if (a[4] && ((a[0] && a[1] && a[5]) || 
+		       (a[1] && a[5] && a[8]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2] && a[6]) || 
+		       (a[2] && a[6] && a[9]) || 
+		       (a[6] && a[9] && a[8]) || 
+		       (a[9] && a[8] && a[4]) || 
+		       (a[8] && a[4] && a[1]) || 
+		       (a[4] && a[1] && a[2]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3] && a[7]) || 
+		       (a[3] && a[7] && a[10]) || 
+		       (a[7] && a[10] && a[9]) || 
+		       (a[10] && a[9] && a[5]) || 
+		       (a[9] && a[5] && a[2]) || 
+		       (a[5] && a[2] && a[3]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6] && a[10]) || 
+		       (a[6] && a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && (a[4] && a[5] && a[9] )) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6] && a[7]) || 
+			(a[6] && a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10] && a[6]) //pix 0 is compact if there is a 4NN
+	    size ++;
+	}
+      
+      //  case Lut 3
+      if (lut==2) 
+	{
+	  if (a[0] && a[1] && a[5] && a[8]) // pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[1] && (a[0] && a[5] && a[2])) //pix 0 is compact if there is a 4NN 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5] && a[6]) || 
+		       (a[3] && a[5] && a[6]) || 
+		       (a[6] && a[3] && a[4]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[4] && a[6]) || 
+		       (a[2] && a[6] && a[7]) )) 
+	    size ++;
+	  if (a[4] && (a[2] && a[3] && a[6] )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2] && a[6]) || 
+		       (a[2] && a[6] && a[9]) || 
+		       (a[6] && a[9] && a[8]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3] && a[7]) || 
+		       (a[3] && a[7] && a[10]) || 
+		       (a[7] && a[10] && a[9]) || 
+		       (a[10] && a[9] && a[5]) || 
+		       (a[9] && a[5] && a[2]) || 
+		       (a[5] && a[2] && a[3]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6] && a[10]) || 
+		       (a[6] && a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && a[5] && a[9] && a[6])  //pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[9] && ((a[8] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6] && a[7]) || 
+			(a[6] && a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10] && a[6]) //pix 0 is compact if there is a 4NN
+	    size ++;
+	}
+    }
+  
+
+  if(size<0 ||size>gsNPixInLut)
+    *fLog << "*" << size <<"-";
+  
+  return size;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+// Look for clusters and calculate the PseudoSize of one event, 
+//   defined as the multiplicity of the bigger cluster. 
+//
+//
+//
+void MMcTriggerLvl2::CalcPseudoSize()
+{
+  // Fill the fCompactPixel array with the compact pixels
+  CalcCompactPixels(fGeomCam);
+
+  // seek the LUT with higher number of compact pixels
+  //
+  //int fMaxCell = CalcBiggerCellPseudoSize();
+  int sizetemp=0;
+  int maxlut=0;
+
+  for (int i=0;i<gsNLutInCell;i++)
+    if (GetLutCompactPixel(fMaxCell,i) > sizetemp)
+      {
+        maxlut=i;
+        sizetemp = GetLutCompactPixel(fMaxCell,i);
+      }
+
+  int startpix;
+  // 
+  // seek a starting pixel for the iteration inside the lut
+  //
+  int check=1;
+  for (int pixlut=0;pixlut<gsNPixInLut;pixlut++)
+    {
+      int pixcell =gsPixelsInLut[maxlut][pixlut]-1;
+      startpix = gsPixelsInCell[pixcell][fMaxCell]-1;
+      //*fLog << "pix, compact:" << startpix << "@"<<fCompactPixel[startpix];
+      if (fCompactPixel[startpix]) // a starting pixel was found
+		break;
+      check++;
+    }
+
+  //*fLog << "check = " << check << endl;
+  // A LUT contains 12 pixels
+  if (check > gsNPixInLut)
+	  {   
+		   *fLog <<"Warning: a starting pixel was not found! - PseudoSize = "<< fPseudoSize << endl;
+	    fPseudoSize=-1;
+	    return;
+	  }
+
+  //
+  // Bulding cluster
+  //
+  Int_t cluster[gsNTrigPixels];
+  int pnt=0;
+  int pnt2=0; //pointer in the array fCluster_pix, needed for filling
+
+  memset (cluster,0,gsNTrigPixels*sizeof(Int_t));
+  memset (fCluster_pix,-1,gsNTrigPixels*sizeof(Int_t));
+
+  cluster[startpix]=1;  
+  fCluster_pix[0]=startpix; //the starting pix is the first in cluster
+  
+  // Look at neighbour pixs if they are compact (iterative search)
+  //  until the array (fCluster_pix) has no more compact pixels.
+  // pnt points to the pixel in the array fCluster_pix whose neighbors are
+  // under study; pnt2 points to the last element of this array.
+  //
+  while (fCluster_pix[pnt] != -1)
+    { 
+      const MGeomPix &pix=(*fGeomCam)[fCluster_pix[pnt]];
+
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+	    {
+	       int pix_neigh = pix.GetNeighbor(i);
+	       // check if pixel is fired and doesn't belong to cluster
+	       if (fCompactPixel[pix_neigh] && !cluster[pix_neigh])
+	         {
+	            cluster[pix_neigh] = 1;
+	            fCluster_pix[++pnt2] = pix_neigh;
+	         }
+	    }
+      pnt++;
+    }
+
+  fPseudoSize = pnt;
+
+  //if (fPseudoSize < 4)
+    //    *fLog << "fPseudoSize = " << fPseudoSize << endl;
+
+  //  *fLog << "ClusterID:" <<(*clust).GetClusterId() << " Mult:" << (*clust).GetMultiplicity()<<endl;  
+  /*
+  *fLog <<"PSize: "<< fPseudoSize << " in cell:" << fMaxCell << " lut:" <<maxlut << endl << "   Pixels: ";
+  for (int i =0;i<fPseudoSize; i++)
+    *fLog << fCluster_pix[i]+1 <<"; ";
+  *fLog << endl;
+  */
+  return;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Fill the fCompactPixels array with the pixels which are compact
+//
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology (it can be 2-NN or 3-NN)
+//
+//   Note: it is a *global* method; it looks in the all camera as a whole
+//         
+//
+void MMcTriggerLvl2::CalcCompactPixels(MGeomCam *geom)
+{
+  memset (fCompactPixel,0,gsNTrigPixels*sizeof(Int_t));
+  //  *fLog << endl << "NEW Event!";
+  for(Int_t pixid=0; pixid<gsNTrigPixels; pixid++)
+    {
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+	     continue;
+      
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Reshuffle pixneighbour order, to arrange them (anti)clockwise
+      //   around the current pixel (Bubble sorting)
+      // The NeighPixOrdered array has a doubledd size so that
+      // the content in the first index is repeated in the last one
+      // to have a closed loop
+
+      Int_t NeighPixOrdered[2*pix.GetNumNeighbors()];
+
+      for (Int_t j=0; j<pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = pix.GetNeighbor(j);
+      
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++)
+        {
+          for (Int_t jk=pix.GetNumNeighbors()-1;jk>j;--jk)
+            {
+               UInt_t tmp = NeighPixOrdered[j+1];
+               const MGeomPix &pixneigh = (*geom)[NeighPixOrdered[j]];
+               for (int k=0; k<pix.GetNumNeighbors(); k++)
+                 if (NeighPixOrdered[jk] == pixneigh.GetNeighbor(k))
+     		       {
+                      NeighPixOrdered[j+1] = NeighPixOrdered[jk];
+                      NeighPixOrdered[jk] = tmp;
+              	   }
+	        }
+        }
+      
+      // Duplicate second half to take into account configurations
+ 	  //  containing tha last and first pixel
+      for (Int_t j=pix.GetNumNeighbors(); j<2*pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = NeighPixOrdered[j-pix.GetNumNeighbors()];
+
+      // Look for compact pixels. 
+      // A compact pixel must have at least fCompactNN adjacent fired neighbors
+      // It checks the 6 different configurations of neighbors pixels; if
+	  // one has fCompacNN adjacent fired pixels than the pixel pixid is
+	  // promoted to compact pixel and saved into the fCompactPixel array.
+	  //
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+	    { 
+	      int j=0; // j counts the adjacent fired pixels
+	      //*fLog << pixid <<"->"<< pix.GetNeighbor(i+j) << endl;
+	      while ((i+j < 2*pix.GetNumNeighbors()) && (fFiredPixel[NeighPixOrdered[i+j]]==1) && (j < fCompactNN))
+	        j++;  
+	      if (j>=fCompactNN)	 // configuration satisfies the compact condition  
+		{
+	      	  fCompactPixel[pixid]=1; // pixel is compact
+	      	  //	  *fLog << ","<<pixid;
+		  break;
+		}
+	    }      
+    }
+
+}
+
+// --------------------------------------------------------------------------
+//  
+//  The Energy has to be given by this class to the Energy-PSSize correlation 
+//   histogram (MHMcTriggerLvl2)  
+//
+void MMcTriggerLvl2::GetEnergy(MMcEvt *fMcEvt)
+{
+   const MMcEvt &h = *(MMcEvt *)fMcEvt; 
+   fEnergy = h.GetEnergy();
+   return;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+//   Looks for a x-NN compact pattern in the whole camera
+//   We have x-NN compact pattern when a triggered pix has
+//   x-1 triggered neighbor pixels.  
+//   The variable fTriggerPattern = x is computed
+//   (x= 2,3,4,5,6,7)  
+//
+//   x=2   * *
+//
+//   x=3   * *
+//          *        *
+//            x=4   * *
+//                   *       
+//                       * *
+//                 x=5  * * *
+//          * 
+//   x=6   * * *
+//          * *
+//               * *
+//          x=7 * * *
+//               * *
+//
+void MMcTriggerLvl2::CalcTriggerPattern(MGeomCam *geom)
+{
+  fTriggerPattern=0; //initialize
+
+  for(Int_t pixid=0;pixid<gsNTrigPixels;pixid++)
+    {
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+		continue;
+      
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Look for x-NN compact pattern
+      // If a x-NN pattern exists then a pixel must have 
+      // at least x-1 adjacent neighbors (look at patterns)
+      // For each triggered pixel the number of adjacent triggered pixels 
+      // is counted.
+      //
+      int j=1;
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+		if (fFiredPixel[pix.GetNeighbor(i)]==1) j++;
+	     
+      if (j > fTriggerPattern) 
+		fTriggerPattern=j;	 
+
+      if (fTriggerPattern==7) 
+	  	break;	 // the 7-NN (max) pattern was found: exit  
+
+    } // next pixel
+}
+
+
+// --------------------------------------------------------------------------
+//  Look for the cell with higher number of Compact pixels
+//  Return the cell number (starting from 0)
+//
+Int_t MMcTriggerLvl2::CalcBiggerCellPseudoSize()
+{
+  Int_t maxcell=-1;
+
+  fCellPseudoSize=0;
+
+  for (Int_t i=0;i<gsNCells;i++)
+    {
+      int size = GetCellCompactPixel(i,fGeomCam);
+      if (size > fCellPseudoSize)
+        {
+          fCellPseudoSize = size;
+          maxcell = i;
+        }
+    }
+  
+  //*fLog << "fCellPseudoSize = " << fCellPseudoSize << " in cell N. " << fMaxCell+1 << endl;
+
+  return maxcell;
+}
+
+// --------------------------------------------------------------------------
+//  Compute the number of compact pixels in one cell
+//
+Int_t MMcTriggerLvl2::GetCellCompactPixel(int cell, MGeomCam *geom)
+{
+  int size=0;
+
+  // check on input variables
+
+  if (cell<0 || cell>gsNCells-1)
+    return(-2);
+
+  //*fLog << " CNN:" << fCompactNN;
+  //*fLog << "Cell: " << cell+1 << " Compat Pixels:"; 
+
+  for(Int_t id=0; id<gsNPixInCell; id++)
+    {
+      UInt_t pixid = gsPixelsInCell[id][cell]-1;
+ 
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+        continue;
+
+      //*fLog << "Fired pix:"<<pixid+1 << " ";
+
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Reshuffle pixneighbour order, to arrange them (anti)clockwise 
+      //   around the current pixel (Bubble sorting)
+      // The NeighPixOrdered has one index more so that 
+      // the content in the first index is repeated in the last one
+      // to have a closed loop
+      Int_t NeighPixOrdered[2*pix.GetNumNeighbors()];
+      for (Int_t j=0; j<pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = pix.GetNeighbor(j);
+      
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++)
+        {
+          for (Int_t jk=pix.GetNumNeighbors()-1;jk>j;--jk)
+            {
+              UInt_t tmp = NeighPixOrdered[j+1];                  
+              const MGeomPix &pixneigh = (*geom)[NeighPixOrdered[j]];
+              for (int k=0; k<pix.GetNumNeighbors(); k++)
+                if (NeighPixOrdered[jk] == pixneigh.GetNeighbor(k))
+                  {
+                    NeighPixOrdered[j+1] = NeighPixOrdered[jk];
+                    NeighPixOrdered[jk] = tmp;
+                  }
+            }
+        }
+
+      // Duplicate second half of the array to take into account configurations
+      // containing tha last and first pixel
+      for (Int_t j=pix.GetNumNeighbors(); j<2*pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = NeighPixOrdered[j-pix.GetNumNeighbors()];
+
+      // Look for compact pixels. 
+
+      // A compact pixel must have at least fCompactNN adjacent neighbors
+      // It checks the 6 different configurations of neighbors pixels.
+      // The neighbour pixels must belong to the cell
+
+      //      *fLog << "cell:"<< cell << "   ordered pixels:";
+      /*
+      for (int i=0;i<2*pix.GetNumNeighbors();i++)
+	{
+	  if (fFiredPixel[NeighPixOrdered[i]])
+	    *fLog << NeighPixOrdered[i]+1 << "*;";
+	  else
+	    *fLog << NeighPixOrdered[i]+1 << ";";
+	}
+      */
+      //*fLog <<endl;
+      //*fLog << pixid <<"->"<< pix.GetNumNeighbors() << " CNN="<< fCompactNN <<endl;
+
+
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+        { 
+          int j=0;
+          while ((i+j < 2*pix.GetNumNeighbors()) && (fFiredPixel[NeighPixOrdered[i+j]]==1) && (j < fCompactNN) && IsPixelInCell(NeighPixOrdered[i+j],cell) )
+            j++;  
+
+          if (j>=fCompactNN) //configuration satisfies the compact condition  
+	    {          
+	      size++; // pixel is compact
+	      //*fLog << "->" << pixid+1;
+	      break; // (new pixel)
+	    }
+	}
+    }
+  
+  //*fLog <<" - size:" << size << endl<<endl;
+  
+  return size;
+  
+}
+
+//---------------------------------------------------------------------
+//  Check if a given pixel belongs to a given cell
+//
+Bool_t MMcTriggerLvl2::IsPixelInCell(Int_t pixel, Int_t cell)
+{
+  for (int i=0; i<gsNPixInCell; i++)
+    if ((gsPixelsInCell[i][cell]-1) == pixel)
+      return kTRUE;
+  
+  return kFALSE;
+}
+
+//---------------------------------------------------------------------
+//  Check if a given pixel is in the trigger region
+//
+Bool_t MMcTriggerLvl2::IsPixelInTrigger(Int_t pixel) const
+{
+  for (int cell=0; cell<gsNCells; cell++)
+    for (int i=0; i<gsNPixInCell; i++)
+      if ((gsPixelsInCell[i][cell]-1) == pixel)
+	return kTRUE;
+  
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns, depending on the type flag:
+//
+//  0: 1,0 if the pixel is triggered (1) or not (0)
+// 
+//
+Bool_t MMcTriggerLvl2::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  // Pixel in no-trigger region are set to 0
+  val = this->IsPixelInTrigger(idx) ?  fFiredPixel[idx]+fCompactPixel[idx] : 0;
+
+  return kTRUE;
+}
+
+void MMcTriggerLvl2::DrawPixelContent(Int_t num) const
+{
+    *fLog << "MMcTriggerLvl2::DrawPixelContent - not available." << endl;
+}
Index: branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2.h	(revision 17960)
@@ -0,0 +1,106 @@
+#ifndef MARS_MMcTriggerLvl2
+#define MARS_MMcTriggerLvl2
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MMcTrig;
+class MMcEvt;
+class MGeomCamMagic;
+class MGeomCam;
+class MGeomPix;
+
+class MMcTriggerLvl2 : public MParContainer, public MCamEvent
+{
+ private:
+  
+  // Global trigger variables related to the geometry and trigger structures are here defined.  
+  // FIXME!  this is a temporary solution: these variables should be defined in a GeomTrg class    
+
+  static const Int_t fNumPixCell = 36; // Number of pixels in one cell
+
+  static const Int_t gsNCells = 19;   
+  static const Int_t gsNTrigPixels = 397;   
+  static const Int_t gsNPixInCell = 36;  
+  static const Int_t gsNLutInCell = 3;  
+  static const Int_t gsNPixInLut = 12; 
+  Int_t fPixels[gsNPixInCell][gsNCells];  
+  
+  // Array with flag for triggered pixels. 1st idx:pixels in trigger cell; 2nd idx:trigger cell number      
+
+  Int_t fFiredPixel[gsNTrigPixels]; // Array with flag for triggered pixel. idx: pixel id    
+  static const Int_t gsPixelsInCell[gsNPixInCell][gsNCells];   
+  static const Int_t gsPixelsInLut[gsNLutInCell][gsNPixInLut];     
+
+  Int_t fMaxCell;  // Cell with maximum number of fired pixels
+
+  Int_t fLutPseudoSize;   // number of compact pixels in one lut   
+  Int_t fPseudoSize;   // Multiplicity of the cluster identified by the L2T    
+  Int_t fSizeBiggerCell; // Number of fired pixel in bigger cell    
+  Int_t fCompactNN;    //Number of NN pixels that define a compact pixel    
+  Int_t fCompactPixel[gsNTrigPixels]; //Array with flag for compact pixels    
+  Int_t fCluster_pix[gsNTrigPixels]; //Array with pixel in cluster   
+  Double_t fEnergy;  // Energy of the shower    
+  Int_t fTriggerPattern; // x-NN compact trigger pattern;    
+  Int_t fCellPseudoSize; // number of compact pixels in one cell    
+  //  Int_t fCellCompactPixels[fNumPixCell]; // Array with compact pixels in cell
+
+  MMcTrig *fMcTrig;   
+  MGeomCam *fGeomCam;      
+
+     
+  Int_t CalcBiggerFiredCell();   
+  Int_t CalcBiggerLutPseudoSize();   
+  void CalcPseudoSize();   
+  Int_t CalcCellPseudoSize();   
+  Int_t CalcBiggerCellPseudoSize();    
+  Int_t GetCellCompactPixel(int cell, MGeomCam *fCam);
+
+  void SetNewCamera(MGeomCam *geom) {fGeomCam = geom;}   
+
+ public:     
+
+  MMcTriggerLvl2(const char* name = NULL, const char* title = NULL);   
+  ~MMcTriggerLvl2();      
+
+  virtual void Calc();    
+  virtual void Print(Option_t *opt="") const;    
+
+  void SetLv1(MMcTrig *trig = NULL);    
+  void SetPixelFired(Int_t pixel, Int_t fired=1);     
+  void SetCompactNN(Int_t neighpix)     {fCompactNN=neighpix;}    
+
+  Int_t GetPseudoSize() const     {return fPseudoSize;}   
+  Int_t GetLutPseudoSize() const  {return fLutPseudoSize;}   
+  Int_t GetSizeBiggerCell() const {return fSizeBiggerCell;}   
+  Int_t GetCompactNN() const      {return fCompactNN;}   
+  Int_t GetCellPseudoSize() const {return fCellPseudoSize;}
+  Int_t GetMaxCell() const        {return (fMaxCell+1);} // Returns
+                     // cell with maximum number of compact pixels
+  Int_t GetCellNumberFired(int cell);   
+  Int_t GetLutCompactPixel(int cell, int lut); 
+  void CalcCompactPixels(MGeomCam *fCam);
+  void CalcTriggerPattern(MGeomCam *fCam);
+    
+  Int_t GetTriggerPattern() const {return fTriggerPattern;}    
+
+  void GetEnergy(MMcEvt *fMcEvt = NULL);     
+  Double_t GetEnergy() const    {return fEnergy;}      
+
+  Bool_t IsPixelInCell(Int_t pixel, Int_t cell);    
+  Bool_t IsPixelInTrigger(Int_t pixel) const;    
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t num) const;
+
+
+  ClassDef(MMcTriggerLvl2,0) // Container for 2nd Level Trigger selection parameters 
+    };  
+    
+#endif      
+    
Index: branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2Calc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2Calc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2Calc.cc	(revision 17960)
@@ -0,0 +1,209 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Antonio Stamerra  1/2003 <mailto:antono.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTriggerLvl2Calc                                                        //
+//   This is a task to calculate the 2nd level trigger selection           //
+//   parameters                                                            //
+//                                                                         //
+//  Input containers:                                                      //
+//    MMcTriggerLvl2                                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MMcTriggerLvl2Calc.h"
+#include "MMcTriggerLvl2.h"
+#include "MHMcTriggerLvl2.h"
+
+#include "MParList.h"
+#include "MLog.h"
+#include "MLogManip.h"
+
+//#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+#include "MRawRunHeader.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MMcTriggerLvl2Calc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//                                                                         
+//  Default constructor
+// 
+//
+MMcTriggerLvl2Calc::MMcTriggerLvl2Calc(const char *name, const char *title)
+{
+  fName  = name  ? name  : "MMcTriggerLvl2Calc";
+  fTitle = title ? title : "Task to Fill the MMcTriggerLvl2 object";  
+} 
+
+ // --------------------------------------------------------------------------
+//
+// Check for the run type. Return kTRUE if it is a MC run or if there
+// is no MC run header (old camera files) kFALSE in case of a different
+// run type
+//
+Bool_t MMcTriggerLvl2Calc::IsMCRun(MParList *pList) const
+{
+  const MRawRunHeader *run = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!run)
+    {
+      *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+      return kTRUE;
+    }
+  
+  return run->IsMonteCarloRun();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the runtype.
+// Search for .
+//
+Bool_t MMcTriggerLvl2Calc::ReInit(MParList *pList)
+{
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//                                                                         
+//  PreProcess
+//  Check the exxistence of the MMcTriggerLvl2 containers and the correct 
+//    setting of the fCompactNN that defines a compact pixel
+//
+Int_t MMcTriggerLvl2Calc::PreProcess (MParList *pList)
+{
+
+    //    fMMcTriggerLvl2 = (MMcTriggerLvl2*)pList->FindObject("MMcTriggerLvl2");
+    fMMcTriggerLvl2 = (MMcTriggerLvl2*)pList->FindCreateObj("MMcTriggerLvl2");
+    if (!fMMcTriggerLvl2)
+    {
+        *fLog << err << dbginf << "MMcTriggerLvl2 not found... exit." << endl;
+        return kFALSE;
+    }
+
+    fMHMcTriggerLvl2 = (MHMcTriggerLvl2*)pList->FindCreateObj("MHMcTriggerLvl2");
+    if (!fMHMcTriggerLvl2)
+    {
+        *fLog << err << dbginf << "MHMcTriggerLvl2 not found... exit." << endl;
+        return kFALSE;
+    }
+
+    // Check if the variable fCompactNN has been correctly set;
+    //  accepted values for fCompactNN are (up to now) 2 and 3.
+    if (fMMcTriggerLvl2->GetCompactNN()<2 || fMMcTriggerLvl2->GetCompactNN()>3)
+      {
+	*fLog << err << dbginf << "fCompactNN is not correctly set ("<<fMMcTriggerLvl2->GetCompactNN() <<") ... exit" <<endl;
+        return kFALSE;	
+      }
+    else
+      *fLog << "Compact pixel is set with at least "<<fMMcTriggerLvl2->GetCompactNN() << " NN" <<endl;
+
+    //------------------------------------------------------------
+    //
+    // If it is no MC file skip this function...
+    //
+    if (!IsMCRun(pList))
+    {
+        *fLog << inf << "Reading a data file...skipping the rest of PreProcess()" << endl;
+        return kTRUE;
+    }
+        
+    //
+    // Check all necessary containers in case of a MC run
+    //
+    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 << err << "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 << warn << "MGeomCam has a wrong geometry; only MAGIC geometry (577 pixels) is accepted by now... the Task is skipped." <<endl;
+	return kSKIP;
+      }
+
+    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: branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2Calc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2Calc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMcTriggerLvl2Calc.h	(revision 17960)
@@ -0,0 +1,48 @@
+#ifndef MARS_MMcTriggerLvl2Calc
+#define MARS_MMcTriggerLvl2Calc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MMcEvt;
+class MMcTrig;
+
+class MMcTriggerLvl2;
+class MHMcTriggerLvl2;
+
+class MGeomCam;
+
+class MMcTriggerLvl2Calc : public MTask
+{
+ private:
+
+  MMcEvt  *fMcEvt;
+  MMcTrig *fMcTrig;
+
+  MGeomCam *fCam;
+
+  MMcTriggerLvl2 *fMMcTriggerLvl2;
+  MHMcTriggerLvl2 *fMHMcTriggerLvl2;
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess();
+
+  Bool_t ReInit(MParList *pList);
+  Bool_t IsMCRun(MParList *pList) const;
+
+ public:
+    MMcTriggerLvl2Calc(const char *name=NULL, const char *title=NULL);   
+
+    ClassDef(MMcTriggerLvl2Calc, 0) // Task to calculate the MMcTriggerLvl2 Parameters
+};
+
+#endif 
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MMultiDimDistCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMultiDimDistCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMultiDimDistCalc.cc	(revision 17960)
@@ -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, 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 <math.h>
+
+#include <TVector.h>
+
+#include "MHMatrix.h" // must be before MLogManip.h
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+//#include "MDataPhrase.h"
+#include "MDataArray.h"
+
+#include "MParameters.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();
+     */
+}
+
+// --------------------------------------------------------------------------
+//
+// 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()))
+    {
+        MDataPhrase *chain = new MDataPhrase(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 = (MParameterD*)plist->FindCreateObj("MParameterD", 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->SetVal(dg==0 ? 0 : exp(-dh/dg));
+    fHadronness->SetReadyToSave();
+
+    return kTRUE;
+}
+
+void MMultiDimDistCalc::StreamPrimitive(ostream &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: branches/Mars_McMismatchStudy/manalysis/MMultiDimDistCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MMultiDimDistCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MMultiDimDistCalc.h	(revision 17960)
@@ -0,0 +1,48 @@
+#ifndef MARS_MMultiDimDistCalc
+#define MARS_MMultiDimDistCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MHMatrix;
+class MParList;
+class MDataArray;
+class MParameterD;
+
+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
+
+    MParameterD *fHadronness; //! Output container for calculated hadroness
+
+    MDataArray  *fData;       //! Used to store the MDataChains to get the event values
+
+    void  StreamPrimitive(std::ostream &out) const;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MMultiDimDistCalc(const char *name=NULL, const char *title=NULL);
+
+    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: branches/Mars_McMismatchStudy/manalysis/MPad.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MPad.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MPad.cc	(revision 17960)
@@ -0,0 +1,2690 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 10/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPad
+//
+//  The aim of the padding is to make the noise level (NSB + electronic noise)
+//  equal for the MC, ON and OFF data samples
+//  
+//  The target noise level is determined by 'merging' the (sigmabar vs. Theta)
+//  distributions of MC, ON and OFF data.
+//
+//  The prescription on which fraction of events has to padded from
+//  bin k of sigmabar to bin j is stored in the matrices 
+//  fHgMC, fHgON and fHgOFF.
+//
+//  By the padding the number of photons, its error and the pedestal sigmas 
+//  are altered. On average, the number of photons added is zero.
+//
+//  The formulas used can be found in Thomas Schweizer's Thesis,
+//                                    Section 2.2.1
+//
+//  The padding is done as follows :
+//
+//     Increase the sigmabar according to the matrices fHg.... Then generate 
+//     a pedestal sigma for each pixel using the 3D-histogram Theta, pixel no.,
+//     Sigma^2-Sigmabar^2 (fHDiffPixTheta).
+//
+//  The padding has to be done before the image cleaning because the
+//  image cleaning depends on the pedestal sigmas.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPad.h"
+
+#include <math.h>
+#include <stdio.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TFile.h>
+#include <TVirtualPad.h>
+
+#include "MBinning.h"
+#include "MPointingPos.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MH.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRead.h"
+#include "MFilterList.h"
+#include "MTaskList.h"
+#include "MHBadPixels.h"
+#include "MFillH.h"
+#include "MHSigmaTheta.h"
+#include "MEvtLoop.h"
+
+ClassImp(MPad);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor. 
+//
+MPad::MPad(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MPad";
+  fTitle = title ? title : "Task for the padding";
+
+  fType = "";
+
+  fHSigmaTheta       = NULL;
+  fHSigmaThetaOuter  = NULL;
+
+  fHSigmaThetaMC         = NULL;
+  fHSigmaThetaOuterMC    = NULL;
+  fHDiffPixThetaMC       = NULL;
+  fHDiffPixThetaTargetMC = NULL;
+
+  fHSigmaThetaON          = NULL;
+  fHSigmaThetaOuterON     = NULL;
+  fHDiffPixThetaON        = NULL;
+  fHDiffPixThetaTargetON  = NULL;
+
+  fHSigmaThetaOFF         = NULL;
+  fHSigmaThetaOuterOFF    = NULL;
+  fHDiffPixThetaOFF       = NULL;
+  fHDiffPixThetaTargetOFF = NULL;
+
+  fHgMC  = NULL;
+  fHgON  = NULL;
+  fHgOFF = NULL;
+
+  fHgOuterMC  = NULL;
+  fHgOuterON  = NULL;
+  fHgOuterOFF = NULL;
+
+  fHSigmaPedestal = NULL;
+  fHPhotons       = NULL;
+  fHNSB           = NULL;
+
+  fNamePedPhotCam = "MPedPhotCamFromData";
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MPad::~MPad()
+{
+  delete fHSigmaTheta;
+  delete fHSigmaThetaOuter;
+
+  if (fHSigmaThetaMC)
+  {
+    delete fHSigmaThetaMC;
+    delete fHSigmaThetaOuterMC;
+    delete fHDiffPixThetaMC;
+    delete fHDiffPixThetaTargetMC;
+    delete fHgMC;
+    delete fHgOuterMC;
+  }
+
+  if (fHSigmaThetaON)
+  {
+    delete fHSigmaThetaON;
+    delete fHSigmaThetaOuterON;
+    delete fHDiffPixThetaON;
+    delete fHDiffPixThetaTargetON;
+    delete fHgON;
+    delete fHgOuterON;
+  }
+
+  if (fHSigmaThetaOFF)
+  {
+    delete fHSigmaThetaOFF;
+    delete fHSigmaThetaOuterOFF;
+    delete fHDiffPixThetaOFF;
+    delete fHDiffPixThetaTargetOFF;
+    delete fHgOFF;
+    delete fHgOuterOFF;
+  }
+
+  delete fHSigmaPedestal;
+  delete fHPhotons;
+  delete fHNSB;
+
+  delete fInfile;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNamePedPhotCam 
+//
+//    set the name of the MPedPhotCam container
+
+void MPad::SetNamePedPhotCam(const char *name) 
+{
+  fNamePedPhotCam = name;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set type of data to be padded
+//
+//     this is not necessary if the type of the data can be recognized
+//     directly from the input
+//
+//
+void MPad::SetDataType(const char* type)
+{
+  fType = type;
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read pad histograms from a file
+//      these are the histograms generated by MMakePadHistograms
+//
+Bool_t MPad::ReadPadHistograms(TString type, TString namepad)
+{
+
+  //------------------------------------
+  Int_t OK = 0;
+
+  if (type == "ON")
+  {
+      *fLog << inf << "MPad : Read pad histograms for " << type 
+            << " data from file " << namepad << endl;
+
+      TH2D *sigth    = new TH2D;
+      TH2D *sigthout = new TH2D;
+      TH3D *diff     = new TH3D;
+
+      TFile *fInfile = new TFile(namepad);
+      fInfile->ls();
+
+      OK = sigth->Read("2D-ThetaSigmabar(Inner)"); 
+      fHSigmaThetaON = new TH2D( (const TH2D&)(*sigth) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Inner)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaON->SetNameTitle("2D-ThetaSigmabarON", 
+                                   "2D-ThetaSigmabarON (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Inner)' was read in" 
+            << endl;
+
+
+      OK = sigthout->Read("2D-ThetaSigmabar(Outer)");
+      fHSigmaThetaOuterON = new TH2D( (const TH2D&)(*sigthout) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Outer)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOuterON->SetNameTitle("2D-ThetaSigmabarOuterON", 
+                                   "2D-ThetaSigmabarOuterON (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Outer)' was read in" 
+            << endl;
+
+
+      OK = diff->Read("3D-ThetaPixDiff");
+      fHDiffPixThetaON = new TH3D( (const TH3D&)(*diff) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '3D-ThetaPixDiff' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHDiffPixThetaON->SetNameTitle("3D-ThetaPixDiffON", 
+                                     "3D-ThetaPixDiffON (orig.)");
+      *fLog << all 
+            << "        MPad : Object '3D-ThetaPixDiff' was read in" << endl;
+
+
+      return kTRUE;
+  }
+
+  //------------------------------------
+  if (type == "OFF")
+  {
+      *fLog << inf << "MPad : Read pad histograms for " << type 
+            << " data from file " << namepad << endl;
+
+
+      TH2D *sigth    = new TH2D;
+      TH2D *sigthout = new TH2D;
+      TH3D *diff     = new TH3D;
+
+      TFile *fInfile = new TFile(namepad);
+      fInfile->ls();
+
+      OK = sigth->Read("2D-ThetaSigmabar(Inner)");
+      fHSigmaThetaOFF = new TH2D( (const TH2D&)(*sigth) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Inner)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOFF->SetNameTitle("2D-ThetaSigmabarOFF", 
+                                    "2D-ThetaSigmabarOFF (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Inner)' was read in" 
+            << endl;
+
+
+      OK = sigthout->Read("2D-ThetaSigmabar(Outer)");
+      fHSigmaThetaOuterOFF = new TH2D( (const TH2D&)(*sigthout) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Outer)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOuterOFF->SetNameTitle("2D-ThetaSigmabarOuterOFF", 
+                                    "2D-ThetaSigmabarOuterOFF (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Outer)' was read in" 
+            << endl;
+
+
+      OK = diff->Read("3D-ThetaPixDiff");
+      fHDiffPixThetaOFF = new TH3D( (const TH3D&)(*diff) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '3D-ThetaPixDiff' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHDiffPixThetaOFF->SetNameTitle("3D-ThetaPixDiffOFF", 
+                                      "3D-ThetaPixDiffOFF (orig.)");
+      *fLog << all 
+            << "        MPad : Object '3D-ThetaPixDiff' was read in" << endl;
+
+
+
+      return kTRUE;
+  }
+
+    //------------------------------------
+  if (type == "MC")
+  {
+
+      TH2D *sigth    = new TH2D;
+      TH2D *sigthout = new TH2D;
+      TH3D *diff     = new TH3D;
+
+      *fLog << inf << "MPad : Read pad histograms for " << type 
+            << " data from file " << namepad << endl;
+
+      TFile *fInfile = new TFile(namepad);
+      fInfile->ls();
+
+      OK = sigth->Read("2D-ThetaSigmabar(Inner)");
+      fHSigmaThetaMC = new TH2D( (const TH2D&)(*sigth) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Inner)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaMC->SetNameTitle("2D-ThetaSigmabarMC", 
+                                   "2D-ThetaSigmabarMC (orig.)");
+      *fLog << all 
+            << "       MPad : Object '2D-ThetaSigmabar(Inner)' was read in" 
+            << endl;
+
+      OK = sigthout->Read("2D-ThetaSigmabar(Outer)");
+      fHSigmaThetaOuterMC = new TH2D( (const TH2D&)(*sigthout) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Outer)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOuterMC->SetNameTitle("2D-ThetaSigmabarOuterMC", 
+                                   "2D-ThetaSigmabarOuterMC (orig.)");
+      *fLog << all 
+            << "       MPad : Object '2D-ThetaSigmabar(Outer)' was read in" 
+            << endl;
+
+
+      
+      OK = diff->Read("3D-ThetaPixDiff");
+      fHDiffPixThetaMC = new TH3D( (const TH3D&)(*diff) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '3D-ThetaPixDiff' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHDiffPixThetaMC->SetNameTitle("3D-ThetaPixDiffMC", 
+                                     "3D-ThetaPixDiffMC (orig.)");
+
+      *fLog << all 
+            << "       MPad : Object '3D-ThetaPixDiff' was read in" << endl;
+      
+      return kTRUE;
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Merge the distributions 
+//   fHSigmaTheta      2D-histogram  (Theta, sigmabar)
+//
+// ===>   of ON, OFF and MC data   <==============
+//
+// and define the matrices fHgMC, fHgON and fHgOFF 
+//
+// These matrices tell which fraction of events should be padded 
+// from bin k of sigmabar to bin j
+//
+
+Bool_t MPad::MergeONOFFMC(TString nameon, TString nameoff,
+                          TString namemc, TString fileout)
+{
+  // read the histograms produced by MMakePadHistograms
+  TH2D *hist2patternin  = NULL;
+  TH2D *hist2patternout = NULL;
+  TH3D *hist3pattern = NULL;
+
+  Bool_t OK = 0;
+
+  if (namemc != "")
+  {
+    OK = ReadPadHistograms("MC",  namemc);  
+    if (!OK) 
+    {
+      *fLog << err << "MPad::MergeONOFFMC : Pad histograms for MC not available"
+            << endl;
+      return kFALSE;
+    }
+
+    hist2patternin  = fHSigmaThetaMC;
+    hist2patternout = fHSigmaThetaOuterMC;
+    hist3pattern = fHDiffPixThetaMC;
+    *fLog << inf << "" << endl;
+    *fLog << inf << "MPad::MergeONOFFMC : Pad histograms for MC data read from file "
+             << namemc << endl;
+  }
+
+  if (nameoff != "")
+  {
+    OK = ReadPadHistograms("OFF", nameoff);
+    if (!OK) 
+    {
+      *fLog << err << "MPad::MergeONOFFMC : Pad histograms for OFF not available"
+            << endl;
+      return kFALSE;
+    }
+
+    hist2patternin  = fHSigmaThetaOFF;
+    hist2patternout = fHSigmaThetaOuterOFF;
+    hist3pattern = fHDiffPixThetaOFF;  
+    *fLog << inf << "" << endl;
+    *fLog << inf << "MPad::MergeONOFFMC : Pad histograms for OFF data read from file "
+             << nameoff << endl;
+  }
+
+  if (nameon != "")
+  {
+    OK = ReadPadHistograms("ON",  nameon);
+    if (!OK) 
+    {
+      *fLog << err << "MPad::MergeONOFFMC : Pad histograms for ON not available"
+            << endl;
+      return kFALSE;
+    }
+
+    hist2patternin  = fHSigmaThetaON;
+    hist2patternout = fHSigmaThetaOuterON;
+    hist3pattern = fHDiffPixThetaON;
+    *fLog << inf << "" << endl;
+    *fLog << inf << "MPad::MergeONOFFMC : Pad histograms for ON data read from file "
+             << nameon << endl;
+  }  
+
+  //*fLog << "hist2patternin = "  << hist2patternin << endl;
+  //*fLog << "hist2patternout = " << hist2patternout << endl;
+  //*fLog << "hist3pattern = " << hist3pattern << endl;
+
+
+  TAxis *axs = hist2patternin->GetXaxis();
+  Int_t nbinsthetas = axs->GetNbins();
+  //*fLog << "vor fHSigmaTheta : nbinsthetas = " << nbinsthetas << endl;
+
+  TArrayD edgess;
+  edgess.Set(nbinsthetas+1);
+  for (Int_t i=0; i<=nbinsthetas; i++)
+  {
+    edgess[i] = axs->GetBinLowEdge(i+1);
+    //*fLog << all << "i, theta low edge = " << i << ",  " << edgess[i] 
+    //      << endl; 
+  }
+
+
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+  // for testing
+  /*
+  TAxis *xa = sigthon.GetXaxis();
+  Int_t nbitheta = xa->GetNbins();
+
+  TAxis *ya = sigthon.GetYaxis();
+  Int_t nbisig = ya->GetNbins();
+  for (Int_t i=1; i<=nbitheta; i++)
+  {
+    for (Int_t j=1; j<=nbisig; j++)
+    {
+      if (i>0)
+      {
+        sigthmc.SetBinContent( i, j, (Float_t) (625000.0+(nbisig*nbisig*nbisig-j*j*j)) );
+        sigthon.SetBinContent( i, j, (Float_t)(1.0) );
+        sigthoff.SetBinContent(  i, j, (Float_t)( (0.5*nbisig-j)*(0.5*nbisig-j)            ) );
+      }
+      else
+      {
+        sigthmc.SetBinContent( i, j, 0.0);
+        sigthon.SetBinContent( i, j, 0.0);
+        sigthoff.SetBinContent(i, j, 0.0);
+      }
+    }
+  }
+  */
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+  *fLog << all << "----------------------------------------------------------------------------------" << endl;
+  *fLog << all << "MPad::MergeONOFFMC(); Merge the ON, OFF and MC histograms to obtain the target distributions for the padding"
+        << endl;
+
+
+  //-------------------------
+  fHSigmaTheta = new TH2D;
+  hist2patternin->Copy(*fHSigmaTheta);
+  fHSigmaTheta->SetNameTitle("2D-ThetaSigmabar", "2D-ThetaSigmabar (target)");
+
+  //-------------------------
+  fHSigmaThetaOuter = new TH2D;
+  hist2patternout->Copy(*fHSigmaThetaOuter);
+  fHSigmaThetaOuter->SetNameTitle("2D-ThetaSigmabarOuter", "2D-ThetaSigmabarOuter (target)");
+
+  //--------------------------
+  fHDiffPixThetaTargetMC = new TH3D;
+  hist3pattern->Copy(*fHDiffPixThetaTargetMC);
+  fHDiffPixThetaTargetMC->SetNameTitle("3D-ThetaPixDiffTargetMC", "3D-ThetaPixDiffMC (target)");
+
+  //-------------------------  
+  fHDiffPixThetaTargetON = new TH3D;
+  hist3pattern->Copy(*fHDiffPixThetaTargetON);
+  fHDiffPixThetaTargetON->SetNameTitle("3D-ThetaPixDiffTargetON", "3D-ThetaPixDiffON (target)");
+
+  //-------------------------
+  fHDiffPixThetaTargetOFF = new TH3D;
+  hist3pattern->Copy(*fHDiffPixThetaTargetOFF);
+  fHDiffPixThetaTargetOFF->SetNameTitle("3D-ThetaPixDiffTargetOFF", "3D-ThetaPixDiffOFF (target)");
+
+  *fLog << all << "MPad::MergeONOFFMC(); Histograms for the merged padding plots were booked" 
+        << endl;
+
+
+  //--------------------------
+
+  // get binning for fHgON, fHgOFF and fHgMC  from fHSigmaTheta
+  // binning in Theta
+  TAxis *ax = hist2patternin->GetXaxis();
+  Int_t nbinstheta = ax->GetNbins();
+
+  //*fLog << "nbinstheta = " << nbinstheta << endl;
+
+  TArrayD edgesx;
+  edgesx.Set(nbinstheta+1);
+  for (Int_t i=0; i<=nbinstheta; i++)
+  {
+    edgesx[i] = ax->GetBinLowEdge(i+1);
+    //*fLog << all << "i, theta low edge = " << i << ",  " << edgesx[i] 
+    //      << endl; 
+  }
+  MBinning binth;
+  binth.SetEdges(edgesx);
+
+  // binning in sigmabar
+  TAxis *ay = hist2patternin->GetYaxis();
+  Int_t nbinssig = ay->GetNbins();
+
+  //*fLog << "nbinssig = " << nbinssig << endl;
+
+  TArrayD edgesy;
+  edgesy.Set(nbinssig+1);
+  for (Int_t i=0; i<=nbinssig; i++)
+  {
+    edgesy[i] = ay->GetBinLowEdge(i+1); 
+    //*fLog << all << "i, sigmabar low edge = " << i << ",  " << edgesy[i] 
+    //      << endl; 
+  }
+  MBinning binsg;
+  binsg.SetEdges(edgesy);
+
+
+  fHgMC = new TH3D;
+  MH::SetBinning(fHgMC, &binth, &binsg, &binsg);
+  fHgMC->SetNameTitle("3D-PaddingMatrixMC", "3D-PadMatrixThetaMC");
+
+  fHgON = new TH3D;
+  MH::SetBinning(fHgON, &binth, &binsg, &binsg);
+  fHgON->SetNameTitle("3D-PaddingMatrixON", "3D-PadMatrixThetaON");
+
+  fHgOFF = new TH3D;
+  MH::SetBinning(fHgOFF, &binth, &binsg, &binsg);
+  fHgOFF->SetNameTitle("3D-PaddingMatrixOFF", "3D-PadMatrixThetaOFF");
+
+  *fLog << all << "fHg histograms were booked" << endl;
+
+  //-----------------------
+  // get binning for fHgOuterON, fHgOuterOFF and fHgOuterMC  
+  // from fHSigmaThetaOuter
+  // binning in sigmabar
+  TAxis *ayout = hist2patternout->GetYaxis();
+  Int_t nbinssigout = ayout->GetNbins();
+  TArrayD edgesyout;
+  edgesyout.Set(nbinssigout+1);
+  for (Int_t i=0; i<=nbinssigout; i++)
+  {
+    edgesyout[i] = ayout->GetBinLowEdge(i+1); 
+    //*fLog << all << "i, sigmabar low edge = " << i << ",  " << edgesyout[i] 
+    //      << endl; 
+  }
+  MBinning binsgout;
+  binsgout.SetEdges(edgesyout);
+
+
+  fHgOuterMC = new TH3D;
+  MH::SetBinning(fHgOuterMC, &binth, &binsgout, &binsgout);
+  fHgOuterMC->SetNameTitle("3D-PaddingMatrixOuterMC", "3D-PadMatrixThetaOuterMC");
+
+  fHgOuterON = new TH3D;
+  MH::SetBinning(fHgOuterON, &binth, &binsgout, &binsgout);
+  fHgOuterON->SetNameTitle("3D-PaddingMatrixOuterON", "3D-PadMatrixThetaOuterON");
+
+  fHgOuterOFF = new TH3D;
+  MH::SetBinning(fHgOuterOFF, &binth, &binsgout, &binsgout);
+  fHgOuterOFF->SetNameTitle("3D-PaddingMatrixOuterOFF", "3D-PadMatrixThetaOuterOFF");
+
+  *fLog << all << "fHgOuter histograms were booked" << endl;
+
+
+  //--------------------------------------------------------------------
+  // define the first (A), second (B) and third (C) data set
+  // (A, B, C) may be (ON, OFF, MC)
+  //               or (ON, OFF, "")
+  //               or (ON, MC,  "")
+  //               or (OFF,MC,  "")
+  // or the same sets in any other order
+
+  TString tagA = "";
+  TString tagB = "";
+  TString tagC = "";
+
+  TH2D *histA = NULL;
+  TH2D *histB = NULL;
+  TH2D *histC = NULL;
+
+  TH2D *histOuterA = NULL;
+  TH2D *histOuterB = NULL;
+  TH2D *histOuterC = NULL;
+
+  TH3D *histDiffA = NULL;
+  TH3D *histDiffB = NULL;
+  TH3D *histDiffC = NULL;
+
+  TH3D *fHgA = NULL;
+  TH3D *fHgB = NULL;
+  TH3D *fHgC = NULL;
+
+  TH3D *fHgOuterA = NULL;
+  TH3D *fHgOuterB = NULL;
+  TH3D *fHgOuterC = NULL;
+
+  if (fHSigmaThetaON)
+  {
+    tagA = "ON";
+    histA      = fHSigmaThetaON;
+    histOuterA = fHSigmaThetaOuterON;
+    histDiffA  = fHDiffPixThetaON;
+    fHgA       = fHgON;
+    fHgOuterA  = fHgOuterON;
+
+    if (fHSigmaThetaOFF)
+    {
+      tagB = "OFF";
+      histB      = fHSigmaThetaOFF;
+      histOuterB = fHSigmaThetaOuterOFF;
+      histDiffB  = fHDiffPixThetaOFF;
+      fHgB       = fHgOFF;
+      fHgOuterB  = fHgOuterOFF;
+
+      if (fHSigmaThetaMC)
+      {
+        tagC = "MC";
+        histC      = fHSigmaThetaMC;
+        histOuterC = fHSigmaThetaOuterMC;
+        histDiffC  = fHDiffPixThetaMC;
+        fHgC       = fHgMC;
+        fHgOuterC  = fHgOuterMC;
+      }
+    }
+
+    else if (fHSigmaThetaMC)
+    {
+      tagB = "MC";
+      histB      = fHSigmaThetaMC;
+      histOuterB = fHSigmaThetaOuterMC;
+      histDiffB  = fHDiffPixThetaMC;
+      fHgB       = fHgMC;
+      fHgOuterB  = fHgOuterMC;
+    }
+  }
+  
+  else if (fHSigmaThetaOFF)
+  {
+    tagA = "OFF";
+    histA      = fHSigmaThetaOFF;
+    histOuterA = fHSigmaThetaOuterOFF;
+    histDiffA  = fHDiffPixThetaOFF;
+    fHgA       = fHgOFF;
+    fHgOuterA  = fHgOuterOFF;
+
+    if (fHSigmaThetaMC)
+    {
+      tagB = "MC";
+      histB      = fHSigmaThetaMC;
+      histOuterB = fHSigmaThetaOuterMC;
+      histDiffB  = fHDiffPixThetaMC;
+      fHgB       = fHgMC;
+      fHgOuterB  = fHgOuterMC;
+    }
+
+    else
+    {
+      *fLog << err << "MPad::MergeONOFFMC; there are no data sets to be merged : tagA, tagB, tagC = "
+            << tagA << ",  " << tagB << ",  " << tagC << endl;
+      return kFALSE;
+    }
+  }
+ 
+  else
+  {
+    *fLog << err << "MPad::MergeONOFFMC; there are no data sets to be merged"
+          << endl;
+    return kFALSE;
+  }
+
+  *fLog << inf << "MPad::MergeONOFFMC; the following data sets will be merged : "
+        << tagA << "   " << tagB << "   " << tagC << endl;
+
+
+  //-------------------------------------------
+  // merge the 2D histograms (theta, Sigmabar)
+  //       from the data sets A, B and C
+  // for the inner pixels and for the outer pixels
+
+  TString canv("Inner");
+  MergeABC(tagA, tagB, tagC,  histA, histB, histC, 
+           fHSigmaTheta,      fHgA, fHgB, fHgC,    canv);
+
+  TString canvout("Outer");
+  MergeABC(tagA, tagB, tagC,  histOuterA, histOuterB, histOuterC, 
+           fHSigmaThetaOuter, fHgOuterA,  fHgOuterB,  fHgOuterC,  canvout);
+
+
+  //-------------------------------------------  
+  // Define the target distributions    fHDiffPixThetaTargetON, ..OFF,  ..MC
+  // (fHDiffPixThetaTarget.. will be used in the padding)
+
+
+  //............   start of new loop over Theta bins   ....................
+  for (Int_t j=1; j<=nbinstheta; j++)
+  {
+    // fraction of A/B/C events to be padded : fracA, fracB, fracC
+    Double_t fracA = 0.0;
+    Double_t fracB = 0.0;
+    Double_t fracC = 0.0;
+
+    fracA = fHgA->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+    fracB = fHgB->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+    if (tagC != "") fracC = fHgC->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+
+    *fLog << all << "Theta bin j : tagA, fracA, tagB, fracB, tagC, fracC = " 
+          << j << ".    " << tagA << ": " << fracA << ";  " << tagB << ": " 
+	  << fracB << ";  " << tagC << ": " << fracC << endl; 
+
+
+    //------------------------------------------------------------------
+    // for the current theta bin :
+    // define target distribution  'sigma^2-sigmabar^2 vs. pixel number'
+    // take the distribution from that sample which has the lowest 'frac.'
+    // At present, for all samples (ON, OFF, MC) the same target distribution 
+    // is used
+
+    Double_t fracmin = fracA;
+    TString tag = tagA;
+
+    if (tagB != "")
+    {
+      if (fracB < fracmin)
+      {
+        fracmin = fracB;
+        tag = tagB;
+      }
+      if (tagC != "")
+      {
+        if (fracC < fracmin)
+        {
+          fracmin = fracC;
+          tag = tagC;
+        }
+      }
+    }
+
+    *fLog << all << "MPad::MergeONOFFMC; thetabin " << j 
+          << " : sample with smallest frac = " << tag << endl; 
+
+    TH3D *hist3 = NULL;
+    if (tag == "ON")
+      hist3 = fHDiffPixThetaON;
+    else if (tag == "OFF")
+      hist3 = fHDiffPixThetaOFF;
+    else if (tag == "MC")
+      hist3 = fHDiffPixThetaMC;
+
+    ay = hist3->GetYaxis();
+    Int_t nbinspixel = ay->GetNbins();
+
+    TAxis *az = hist3->GetZaxis();
+    Int_t nbinsdiff = az->GetNbins();
+
+    for (Int_t k=1; k<=nbinspixel; k++)
+    {
+      for (Int_t l=1; l<=nbinsdiff; l++)
+      {
+        Double_t cont = hist3->GetBinContent(j, k,l);
+        fHDiffPixThetaTargetON-> SetBinContent(j, k, l, cont);  
+        fHDiffPixThetaTargetOFF->SetBinContent(j, k, l, cont);  
+        fHDiffPixThetaTargetMC-> SetBinContent(j, k, l, cont);  
+      }
+    }
+  }
+  //............   end of new loop over Theta bins   ....................
+
+  *fLog << all 
+        << "MPad::MergeONOFFMC(); The target distributions for the padding have been created" 
+        << endl;
+  *fLog << all << "----------------------------------------------------------" 
+        << endl;
+  //--------------------------------------------
+
+  fHSigmaTheta->SetDirectory(NULL);
+  fHSigmaThetaOuter->SetDirectory(NULL);
+
+  if (tagA == "MC"  ||  tagB == "MC"  ||  tagC == "MC")
+  { 
+    fHSigmaThetaMC->SetDirectory(NULL);
+    fHSigmaThetaOuterMC->SetDirectory(NULL);
+    fHDiffPixThetaMC->SetDirectory(NULL);
+    fHgMC->SetDirectory(NULL);
+    fHgOuterMC->SetDirectory(NULL);
+  }
+
+  if (tagA == "ON"  ||  tagB == "ON"  ||  tagC == "ON")
+  { 
+    fHSigmaThetaON->SetDirectory(NULL);
+    fHSigmaThetaOuterON->SetDirectory(NULL);
+    fHDiffPixThetaON->SetDirectory(NULL);
+    fHgON->SetDirectory(NULL);
+    fHgOuterON->SetDirectory(NULL);
+  }
+
+  if (tagA == "OFF"  ||  tagB == "OFF"  ||  tagC == "OFF")
+  { 
+    fHSigmaThetaOFF->SetDirectory(NULL);
+    fHSigmaThetaOuterOFF->SetDirectory(NULL);
+    fHDiffPixThetaOFF->SetDirectory(NULL);
+    fHgOFF->SetDirectory(NULL);
+    fHgOuterOFF->SetDirectory(NULL);
+  }
+
+  // write the target padding histograms onto a file  ---------
+  WritePaddingDist(fileout);     
+
+  //-------------------------------------------------------
+  TCanvas *pad = MH::MakeDefCanvas("target", "target", 600, 300); 
+  gROOT->SetSelectedPad(NULL);
+
+  pad->Divide(2, 1);
+
+  pad->cd(1);
+  gPad->SetBorderMode(0);
+  fHSigmaTheta->SetDirectory(NULL);
+  fHSigmaTheta->UseCurrentStyle();
+  fHSigmaTheta->DrawClone();
+  fHSigmaTheta->SetBit(kCanDelete);    
+
+  pad->cd(2);
+  gPad->SetBorderMode(0);
+  fHSigmaThetaOuter->SetDirectory(NULL);
+  fHSigmaThetaOuter->UseCurrentStyle();
+  fHSigmaThetaOuter->DrawClone();
+  fHSigmaThetaOuter->SetBit(kCanDelete);    
+
+  pad->Draw();
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Merge the 2D-histograms  (Theta, sigmabar) 
+//       hA, hB and hC
+//
+// - put the merged distribution into hM
+// - and define the matrices hgA, hgB and hgC 
+//
+// These matrices tell which fraction of events should be padded 
+// from bin k of sigmabar to bin j
+//
+
+Bool_t MPad::MergeABC(TString tA, TString tB, TString tC,
+                      TH2D *hA,   TH2D *hB,   TH2D *hC,   TH2D *hM,
+                      TH3D *hgA,  TH3D *hgB,  TH3D *hgC, TString canv)
+{
+  *fLog << all << "MPad::MergeABC();  Entry" << endl;
+
+  TAxis *ax = hM->GetXaxis();
+  Int_t nbinstheta = ax->GetNbins();
+
+  TAxis *ay = hM->GetYaxis();
+  Int_t nbinssig = ay->GetNbins();
+
+  TArrayD edgesy;
+  edgesy.Set(nbinssig+1);
+  for (Int_t i=0; i<=nbinssig; i++)
+  {
+    edgesy[i] = ay->GetBinLowEdge(i+1); 
+    //*fLog << all << "i, sigmabar low edge = " << i << ",  " << edgesy[i] 
+    //      << endl; 
+  }
+  MBinning binsg;
+  binsg.SetEdges(edgesy);
+
+
+  //............   loop over Theta bins   ...........................
+
+  //*fLog << all << "MPad::MergeABC(); bins of Theta, Sigmabarold, Sigmabarnew, fraction of events to be padded" << endl;
+  for (Int_t l=1; l<=nbinstheta; l++)
+  {
+    //-------------------------------------------
+    // merge A (ON) and B (OFF) distributions
+    // input : hista is the normalized 1D distr. of sigmabar for A (ON)  data
+    //         histb is the normalized 1D distr. of sigmabar for B (OFF) data
+    // output : histap    will be the merged distribution (AB)
+    //          fHga(k,j) will tell which fraction of A (ON) events should be 
+    //                    padded from bin k to bin j
+    //          fHgb(k,j) will tell which fraction of B (OFF) events should be 
+    //                    padded from bin k to bin j
+
+    TH2D * fHga = new TH2D;
+    MH::SetBinning(fHga, &binsg, &binsg);
+    TH2D * fHgb = new TH2D;
+    MH::SetBinning(fHgb, &binsg, &binsg);
+
+    TH1D *hista  = hA->ProjectionY("sigon_y", l, l, "");
+    TString tita(canv);
+    tita += "-A (orig)-";
+    tita += l;
+    hista->SetNameTitle(tita, tita); 
+    Stat_t suma = hista->Integral();
+    if (suma != 0.0) hista->Scale(1./suma);
+
+    TH1D *histap  = new TH1D( (const TH1D&)*hista );
+    TString titab(canv);
+    titab += "-AB (merged)-";
+    titab += l;
+    histap->SetNameTitle(titab, titab); 
+
+    TH1D *histb  = hB->ProjectionY("sigoff_y", l, l, "");
+    TString titb(canv);
+    titb += "-B (orig)-";
+    titb += l;
+    histb->SetNameTitle(titb, titb); 
+    Stat_t sumb = histb->Integral();
+    if (sumb != 0.0) histb->Scale(1./sumb);
+
+    if (suma == 0.0  ||  sumb == 0.0)
+    {
+      delete hista;
+      delete histb;
+      delete fHga;
+      delete fHgb;
+      delete histap;
+
+      *fLog << err 
+            << "cannot call Merge2Distributions(A=" << tA << ", B="
+            << tB << ")  for theta bin l = " 
+            << l << ";  NevA, NevB = " << suma << ",  " << sumb << endl;
+
+      // clear the corresponding area of fHSigmaTheta
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = 0.0;
+        hM->SetBinContent(l, j, a);
+
+        //*fLog << "MPad::MergeABC; l, j, a = " << l << ",  " << j << ",  "
+        //      << a << endl;
+      }
+
+      // go to next theta bin (l)
+      continue;
+    }
+
+    //*fLog << "call Merge2Distributions(A=" << tA << ", B="
+    //      << tB << ")  for theta bin l = "
+    //      << l << endl;
+
+    TString canvab(canv);
+    canvab += "AB-";
+    canvab += l;
+    Merge2Distributions(hista, histb, histap, fHga, fHgb, nbinssig, canvab);
+
+    // fill fHgA and fHgB
+    for (Int_t k=1; k<=nbinssig; k++)
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = fHga->GetBinContent(k,j);
+        hgA->SetBinContent(l, k, j, a);
+
+        Double_t b = fHgb->GetBinContent(k,j);
+        hgB->SetBinContent(l, k, j, b);
+      }
+
+
+    //-------------------------------------------------
+    // if there is no further distribution to be merged
+    // fill target distribution fHSigmaTheta 
+    // 
+    if (!hC)
+    {
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = histap->GetBinContent(j);
+        hM->SetBinContent(l, j, a);
+
+        //*fLog << "MPad::MergeABC; l, j, a = " << l << ",  " << j << ",  "
+        //      << a << endl;
+      }
+
+      delete fHga;
+      delete fHgb;
+      delete histap;
+    }
+
+    //--------------   next merge (start) ----------------------------------
+    if (hC)
+    {
+
+    // now merge AB (ON-OFF) and C (MC) distributions
+    // input : histe is the result of the merging of A (ON) and B (OFF)
+    //                  distributions  
+    //         histf is the normalized 1D distr. of sigmabar for C (MC) data
+    // output : histep    will be the merged distribution (target distribution)
+    //          fHge(k,j) will tell which fraction of A (ON), B (OFF) events 
+    //                    should be padded from bin k to bin j
+    //          fHgf(k,j) will tell which fraction of C (MC) events should be 
+    //                    padded from bin k to bin j
+
+    TH2D * fHge = new TH2D;
+    MH::SetBinning(fHge, &binsg, &binsg);
+    TH2D * fHgf = new TH2D;
+    MH::SetBinning(fHgf, &binsg, &binsg);
+
+    TH1D *histe  = new TH1D( (const TH1D&)*histap);
+    TString titabm(canv);
+    titabm += "-AB (merged)-";
+    titabm += l;
+    histe->SetNameTitle(titabm, titabm); 
+
+    TH1D *histep  = new TH1D( (const TH1D&)*histe);
+    TString titabcm(canv);
+    titabcm +="-ABC (merged)-";
+    titabcm += l;
+    histep->SetNameTitle(titabcm, titabcm); 
+
+    TH1D *histf  = hC->ProjectionY("sigmc_y", l, l, "");
+    TString titc(canv);
+    titc += "-C (orig)-";
+    titc += l;
+    histf->SetNameTitle(titc, titc); 
+    Double_t sumf = histf->Integral();
+    if (sumf != 0.0) histf->Scale(1./sumf);
+
+    if (sumf == 0.0)
+    {
+      delete hista;
+      delete histb;
+      delete fHga;
+      delete fHgb;
+      delete histap;
+
+      delete histe;
+      delete histf;
+      delete fHge;
+      delete fHgf;
+      delete histep;
+
+      *fLog << err 
+            << "cannot call Merge2Distributions(AB=" << tA << "-" << tB 
+            << ", C=" << tC << ")  for theta bin l = " 
+            << l << ";  NevC = " << sumf << endl;
+
+      // go to next theta bin (l)
+      continue;
+    }
+
+    //*fLog << "call Merge2Distributions(AB=" << tA << "-" << tB 
+    //      << ", C=" << tC << ")  for theta bin l = "
+    //      << l << endl;
+
+    TString canvabc(canv);
+    canvabc += "ABC-";
+    canvabc += l;
+    Merge2Distributions(histe, histf, histep, fHge, fHgf, nbinssig, canvabc);
+
+    // update fHgA and fHgB
+    UpdateHg(fHga, histap, fHge, hgA,  nbinssig, l);
+    UpdateHg(fHgb, histap, fHge, hgB, nbinssig, l);
+
+    // fill fHgC
+    for (Int_t k=1; k<=nbinssig; k++)
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t f = fHgf->GetBinContent(k,j);
+        hgC->SetBinContent(l, k, j, f);
+      }
+
+    // fill target distribution fHSigmaTheta 
+    // 
+    for (Int_t j=1; j<=nbinssig; j++)
+    {
+      Double_t ep = histep->GetBinContent(j);
+      hM->SetBinContent(l, j, ep);
+
+      //*fLog << "MPad::MergeABC; l, j, ep = " << l << ",  " << j << ",  "
+      //      << ep << endl;
+    }
+
+
+    //-------------------------------------------
+
+    delete hista;
+    delete histb;
+    delete fHga;
+    delete fHgb;
+    delete histap;
+
+    delete histe;
+    delete histf;
+    delete fHge;
+    delete fHgf;
+    delete histep;
+
+    }
+    //--------------   next merge (end) ----------------------------------
+
+  }
+  //............   end of loop over Theta bins   ....................
+
+  *fLog << all << "MPad::MergeABC();  Return" << endl;
+
+  return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// Merge the sigmabar distributions of 2 samples (samples A and B)
+//
+// input : the original distributions for samples A and B (hista, histb)
+//
+// output : the prescription which fraction of events should be padded
+//          from the sigmabar bin k to bin j (fHgMC, fHgON, fHgOFF)
+//
+
+Bool_t MPad::Merge2Distributions(TH1D *hista, TH1D *histb, TH1D *histap,
+                                 TH2D *fHga,  TH2D *fHgb, Int_t nbinssig,
+                                 TString canv )
+{
+  *fLog << all << "MPad::Merge2Distributions();  Entry" << endl;
+
+
+  // hista is the normalized 1D histogram of sigmabar for sample A
+  // histb is the normalized 1D histogram of sigmabar for sample B
+  // histc is the difference A-B
+
+  // at the beginning, histap is a copy of hista
+  // at the end, it will be the 1D histogram for sample A after padding
+
+  // at the beginning, histbp is a copy of histb
+  // at the end, it will be the 1D histogram for sample B after padding
+
+  // at the beginning, histcp is a copy of histc
+  // at the end, it should be the difference histap-histbp,
+  //             which should be zero
+
+  // fHga[k][j]  tells which fraction of events from sample A should be padded
+  //             from sigma_k to sigma_j
+
+
+  // fHgb[k][j]  tells which fraction of events from sample B should be padded
+  //             from sigma_k to sigma_j
+
+  //*fLog << all << "MPad::Merge2Distributions(); Entry" << endl;
+
+  Double_t eps = 1.e-10;
+
+    TH1D *histbp  = new TH1D( (const TH1D&)*histb );
+
+    TH1D *histc   = new TH1D( (const TH1D&)*hista );
+    histc->Add(histb, -1.0);
+
+    TH1D *histcp  = new TH1D( (const TH1D&)*histc );    
+
+
+  //--------   start j loop   ------------------------------------------------
+  // loop over bins in histc, 
+  // starting from the end (i.e. at the largest sigmabar)
+  Double_t v, s, w, t, x, u, a, b, arg;
+
+  //*fLog << "Content of histcp : " << endl;
+
+  for (Int_t j=nbinssig; j >= 1; j--)
+  {
+    //*fLog << "j, hista, histb , histap : " << j << ",  " 
+    //                              <<  hista->GetBinContent(j) << ",  "
+    //                              <<  histb->GetBinContent(j) << ",  "
+    //                              <<  histap->GetBinContent(j) << endl;
+
+    v = histcp->GetBinContent(j);
+    //*fLog << "cp : j, v = " << j << ",  " << v << endl;
+
+    if ( fabs(v) < eps ) continue;
+    if (v >= 0.0) 
+      s = 1.0;
+    else
+      s = -1.0;
+
+    //................   start k loop   ......................................
+    // look for a bin k which may compensate the content of bin j
+    for (Int_t k=j-1; k >= 1; k--)
+    {
+      w = histcp->GetBinContent(k);
+      if ( fabs(w) < eps ) continue;
+      if (w >= 0.0) 
+        t = 1.0;
+      else
+        t = -1.0;
+
+      // if s==t bin k cannot compensate, go to next k bin
+      if (s == t) continue;
+
+      x = v + w;
+      if (x >= 0.0) 
+        u = 1.0;
+      else
+        u = -1.0;
+
+      // if u==s bin k will partly compensate : pad the whole fraction
+      // w from bin k to bin j
+      if (u == s)
+        arg = -w;
+
+      // if u!=s bin k would overcompensate : pad only the fraction
+      // v from bin k to bin j
+      else
+        arg = v;
+
+      if (arg <=0.0)
+      {
+        fHga->SetBinContent(k, j, -arg);
+        fHgb->SetBinContent(k, j,  0.0);
+      }
+      else
+      {
+        fHga->SetBinContent(k, j,  0.0);
+        fHgb->SetBinContent(k, j,  arg);
+      }
+
+      //*fLog << all << "k, j, arg = " << k << ",  " << j 
+      //      << ",  " << arg << endl;
+
+      //......................................
+      // this is for checking the procedure
+      if (arg < 0.0)
+      {
+        a = histap->GetBinContent(k);
+        histap->SetBinContent(k, a+arg);
+        a = histap->GetBinContent(j);
+        histap->SetBinContent(j, a-arg);
+      }
+      else
+      {
+        b = histbp->GetBinContent(k);
+        histbp->SetBinContent(k, b-arg);
+        b = histbp->GetBinContent(j);
+        histbp->SetBinContent(j, b+arg);
+      }
+      //......................................
+
+      if (u == s)
+      {
+        histcp->SetBinContent(k, 0.0);
+        histcp->SetBinContent(j,   x);
+
+        v = histcp->GetBinContent(j);
+        if ( fabs(v) < eps ) break;
+
+        // bin j was only partly compensated : go to next k bin
+        continue;
+      }
+      else
+      {
+        histcp->SetBinContent(k,   x);
+        histcp->SetBinContent(j, 0.0);
+
+        // bin j was completely compensated : go to next j bin
+        break;
+      }
+
+    }
+    //................   end k loop   ......................................
+  } 
+  //--------   end j loop   ------------------------------------------------
+
+  // check results 
+
+  //*fLog << "Content of histap, histbp, histcp : " << endl;
+
+  for (Int_t j=1; j<=nbinssig; j++)
+  {
+    Double_t a = histap->GetBinContent(j);
+    Double_t b = histbp->GetBinContent(j);
+    Double_t c = histcp->GetBinContent(j);
+
+    //*fLog << "j, a, b, c = " << j << ":  " << a << ",  " << b << ",  "
+    //      << c << endl;
+
+    if( fabs(a-b)>3.0*eps  ||  fabs(c)>3.0*eps )
+      *fLog << err << "MPad::Merge2Distributions(); inconsistency in results; j, a, b, c = "
+            << j << ",  " << a << ",  " << b << ",  " << c << endl;
+  }
+
+  //---------------------------------------------------------------
+  TCanvas *pad = MH::MakeDefCanvas(canv, canv, 600, 600); 
+  gROOT->SetSelectedPad(NULL);
+
+  pad->Divide(2, 2);
+
+  pad->cd(1);
+  gPad->SetBorderMode(0);
+  hista->SetDirectory(NULL);
+  hista->UseCurrentStyle();
+  hista->DrawClone();
+  hista->SetBit(kCanDelete);    
+
+  pad->cd(2);
+  gPad->SetBorderMode(0);
+  histb->SetDirectory(NULL);
+  histb->UseCurrentStyle();
+  histb->DrawClone();
+  histb->SetBit(kCanDelete);    
+
+  pad->cd(3);
+  gPad->SetBorderMode(0);
+  histap->SetDirectory(NULL);
+  histap->UseCurrentStyle();
+  histap->DrawClone();
+  histap->SetBit(kCanDelete);    
+
+  pad->Draw();
+
+  //--------------------------------------------------------------------
+
+  delete histc;
+  delete histbp;
+  delete histcp;
+
+  *fLog << all << "MPad::Merge2Distributions();  Return" << endl;
+
+  return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Update the matrix fHgA
+// which contains the final padding prescriptions
+//
+
+Bool_t MPad::UpdateHg(TH2D *fHga, TH1D *histap, TH2D *fHge, TH3D *fHgA,
+                      Int_t nbinssig, Int_t l)
+{
+  // histap  target distribution after ON-OFF merging
+  // fHga    padding prescription for ON (or OFF) data to get to histap
+  // fHge    padding prescription to get from histap to the target
+  //         distribution after the ON-OFF-MC merging
+  // fHgA    updated padding prescription for ON (or OFF) data to get
+  //         from the original ON (or OFF) histogram to the target
+  //         distribution after the ON-OFF-MC merging
+  // l       Theta bin
+
+  Double_t eps = 1.e-10;
+
+  for (Int_t k=1; k<=nbinssig; k++)
+  {
+    Double_t na  = fHga->Integral(1, nbinssig, k, k, " ");
+    Double_t ne  = fHge->Integral(k, k, 1, nbinssig, " ");
+    Double_t nap = histap->GetBinContent(k);
+
+    if (ne <= eps) 
+    {
+      // go to next k
+      continue;
+    }
+
+    Double_t r = nap - na;
+
+    if (r >= ne-eps)
+    {
+      for (Int_t j=k+1; j<=nbinssig; j++)
+      {
+        Double_t e = fHge->GetBinContent(k,j);
+        Double_t A = fHgA->GetBinContent(l,k,j);
+        fHgA->SetBinContent(l, k, j, A + e);
+      }
+      // go to next k
+      continue;
+    }
+
+    for (Int_t j=k+1; j<=nbinssig; j++)
+    {
+      Double_t e = fHge->GetBinContent(k,j);
+      Double_t A = fHgA->GetBinContent(l,k,j);
+      fHgA->SetBinContent(l, k, j, A + r*e/ne);
+    }
+
+    if (na <= eps) 
+    {
+      // go to next k
+      continue;
+    }
+
+    for (Int_t i=1; i<k; i++)
+    {
+      Double_t a = fHga->GetBinContent(i,k);
+      Double_t A = fHgA->GetBinContent(l,i,k);
+      fHgA->SetBinContent(l, i, k, A - (ne-r)*a/na);
+    }
+
+    for (Int_t i=1; i<=nbinssig; i++)
+    {
+      if (i == k) continue;
+      for (Int_t j=i+1; j<=nbinssig; j++)
+      {
+        if (j == k) continue;
+        Double_t a = fHga->GetBinContent(i,k);
+        Double_t e = fHge->GetBinContent(k,j);
+        Double_t A = fHgA->GetBinContent(l,i,j);
+        fHgA->SetBinContent(l, i, j, A + (ne-r)*a*e/(na*ne)  );
+      }
+    }
+  }
+  
+  return kTRUE; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Write padding distributions onto a file
+//       these are the histograms produced in the member function
+//       MergeONOFFMC
+//       plus the distributions produced by MMakePadHistograms
+//
+Bool_t MPad::WritePaddingDist(TString namefileout)
+{
+  *fLog << all << "MPad::WritePaddingDist();  Padding distributions for  "; 
+
+  TFile outfile(namefileout, "RECREATE");
+
+  fHSigmaTheta->Write();
+  fHSigmaThetaOuter->Write();
+
+  if (fHSigmaThetaMC)
+  {
+    *fLog << all << " MC ";
+    fHSigmaThetaMC->Write();
+    fHSigmaThetaOuterMC->Write();
+    fHDiffPixThetaMC->Write();
+    fHDiffPixThetaTargetMC->Write();
+    fHgMC->Write();
+    fHgOuterMC->Write();
+  }
+
+  if (fHSigmaThetaON)
+  {
+    *fLog << all << " ON ";
+    fHSigmaThetaON->Write();
+    fHSigmaThetaOuterON->Write();
+    fHDiffPixThetaON->Write();
+    fHDiffPixThetaTargetON->Write();
+    fHgON->Write();
+    fHgOuterON->Write();
+  }
+
+  if (fHSigmaThetaOFF)
+  {
+    *fLog << all << " OFF ";
+    fHSigmaThetaOFF->Write();
+    fHSigmaThetaOuterOFF->Write();
+    fHDiffPixThetaOFF->Write();
+    fHDiffPixThetaTargetOFF->Write();
+    fHgOFF->Write();
+    fHgOuterOFF->Write();
+  }
+
+  *fLog << all << "  data were written onto file " 
+        << namefileout << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read padding distributions from a file
+//      thes are the distributions which were written out by
+//      the member function WritePaddingDist
+//
+Bool_t MPad::ReadPaddingDist(TString namefilein)
+{
+  *fLog << all << "MPad : Read padding histograms from file " 
+        << namefilein << endl;
+
+  Int_t OK = 0;
+
+  fInfile = new TFile(namefilein);
+  fInfile->ls();
+
+    //------------------------------------
+  
+      fHSigmaTheta = new TH2D; 
+      OK = fHSigmaTheta->Read("2D-ThetaSigmabar");
+      if (OK) 
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabar' was read in" << endl;
+      }
+
+      fHSigmaThetaOuter = new TH2D; 
+      OK =fHSigmaThetaOuter->Read("2D-ThetaSigmabarOuter");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuter' was read in" << endl;
+      }
+
+
+    //------------------------------------
+
+      fHSigmaThetaMC = new TH2D; 
+      OK = fHSigmaThetaMC->Read("2D-ThetaSigmabarMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarMC' was read in" << endl;
+      }
+
+      fHSigmaThetaOuterMC = new TH2D; 
+      OK = fHSigmaThetaOuterMC->Read("2D-ThetaSigmabarOuterMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuterMC' was read in" << endl;
+      }
+
+      fHDiffPixThetaMC = new TH3D;
+      OK = fHDiffPixThetaMC->Read("3D-ThetaPixDiffMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffMC' was read in" << endl;
+      }
+
+      fHDiffPixThetaTargetMC = new TH3D;
+      OK = fHDiffPixThetaTargetMC->Read("3D-ThetaPixDiffTargetMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffTargetMC' was read in" << endl;
+      }
+
+      fHgMC = new TH3D;
+      OK = fHgMC->Read("3D-PaddingMatrixMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixMC' was read in" << endl;
+      }
+
+      fHgOuterMC = new TH3D;
+      OK = fHgOuterMC->Read("3D-PaddingMatrixOuterMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOuterMC' was read in" << endl;
+      }
+
+    //------------------------------------
+
+      fHSigmaThetaON = new TH2D;
+      OK =fHSigmaThetaON->Read("2D-ThetaSigmabarON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarON' was read in" << endl;
+      }
+
+      fHSigmaThetaOuterON = new TH2D;
+      OK = fHSigmaThetaOuterON->Read("2D-ThetaSigmabarOuterON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuterON' was read in" << endl;
+      }
+
+      fHDiffPixThetaON = new TH3D;
+      OK = fHDiffPixThetaON->Read("3D-ThetaPixDiffON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffON' was read in" << endl;
+      }
+
+      fHDiffPixThetaTargetON = new TH3D;
+      OK = fHDiffPixThetaTargetON->Read("3D-ThetaPixDiffTargetON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffTargetON' was read in" << endl;
+      }
+
+      fHgON = new TH3D;
+      OK = fHgON->Read("3D-PaddingMatrixON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixON' was read in" << endl;
+      }
+
+      fHgOuterON = new TH3D;
+      OK = fHgOuterON->Read("3D-PaddingMatrixOuterON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOuterON' was read in" << endl;
+      }
+
+    //------------------------------------
+
+      fHSigmaThetaOFF = new TH2D;
+      OK = fHSigmaThetaOFF->Read("2D-ThetaSigmabarOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOFF' was read in" << endl;
+      }
+
+      fHSigmaThetaOuterOFF = new TH2D;
+      OK = fHSigmaThetaOuterOFF->Read("2D-ThetaSigmabarOuterOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuterOFF' was read in" << endl;
+      }
+
+      fHDiffPixThetaOFF = new TH3D;
+      OK = fHDiffPixThetaOFF->Read("3D-ThetaPixDiffOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffOFF' was read in" << endl;
+      }
+
+      fHDiffPixThetaTargetOFF = new TH3D;
+      OK = fHDiffPixThetaTargetOFF->Read("3D-ThetaPixDiffTargetOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffTargetOFF' was read in" << endl;
+      }
+
+      fHgOFF = new TH3D;
+      OK = fHgOFF->Read("3D-PaddingMatrixOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOFF' was read in" << endl;
+      }
+
+      fHgOuterOFF = new TH3D;
+      OK = fHgOuterOFF->Read("3D-PaddingMatrixOuterOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOuterOFF' was read in" << endl;
+      }
+
+    //------------------------------------
+
+  return kTRUE;
+}
+
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Set the pointers and prepare the histograms
+//
+Int_t MPad::PreProcess(MParList *pList)
+{
+  if ( !fHSigmaThetaMC     && !fHSigmaThetaON     && !fHSigmaThetaOFF      ||  
+       !fHDiffPixThetaMC   && !fHDiffPixThetaON   && !fHDiffPixThetaOFF    ||
+       !fHgMC              && !fHgON              && !fHgOFF                 )
+  { 
+       *fLog << err 
+             << "MPad : There are no input histograms for the padding ... aborting." 
+             << endl;
+       return kFALSE;
+  }
+
+  fPointPos = (MPointingPos*)pList->FindObject("MPointingPos");
+  if (!fPointPos)
+    {
+       *fLog << err << dbginf << "MPad : MPointingPos not found... aborting." 
+             << endl;
+       return kFALSE;
+    }
+  
+    fPed = (MPedPhotCam*)pList->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+    if (!fPed)
+    {
+        *fLog << err << AddSerialNumber(fNamePedPhotCam) 
+              << "[MPedPhotCam] not found... aborting." << endl;
+        return kFALSE;
+    }    
+    *fLog << all << "MPad::PreProcess();  name of MPedPhotCam container = "
+	  << fNamePedPhotCam << endl;  
+   
+
+   fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+   if (!fCam)
+     {
+       *fLog << err 
+             << "MPad : MGeomCam not found (no geometry information available)... aborting." 
+             << endl;
+       return kFALSE;
+     }
+  
+   fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+   if (!fEvt)
+     {
+       *fLog << err << "MPad : MCerPhotEvt not found... aborting." 
+             << endl;
+       return kFALSE;
+     }
+
+
+   fBad = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+   if (!fBad)
+     {
+       *fLog << inf 
+             << "MPad : MBadPixelsCam container not present... continue." 
+             << endl;
+     }
+
+   
+   if (fType !="ON"  &&  fType !="OFF"  &&  fType !="MC")
+     {
+       *fLog << err 
+             << "MPad : Type of data to be padded not defined... aborting." 
+             << endl;
+       return kFALSE;
+     }
+
+
+   //--------------------------------------------------------------------
+   // histograms for checking the padding
+   //
+   // plot pedestal sigmas
+   fHSigmaPedestal = new TH2D("SigPed","Sigma: after vs. before padding", 
+                     100, 0.0, 75.0, 100, 0.0, 75.0);
+   fHSigmaPedestal->SetXTitle("Pedestal sigma before padding");
+   fHSigmaPedestal->SetYTitle("Pedestal sigma after padding");
+   fHSigmaPedestal->SetDirectory(NULL);
+   fHSigmaPedestal->UseCurrentStyle();
+   fHSigmaPedestal->GetYaxis()->SetTitleOffset(1.25);
+
+   // plot no.of photons (before vs. after padding) 
+   fHPhotons = new TH2D("Photons/area",
+                        "Photons/area: after vs.before padding", 
+                        100, -100.0, 300.0, 100, -100, 300);
+   fHPhotons->SetXTitle("no.of photons/area before padding");
+   fHPhotons->SetYTitle("no.of photons/area after padding");
+   fHPhotons->SetDirectory(NULL);
+   fHPhotons->UseCurrentStyle();
+   fHPhotons->GetYaxis()->SetTitleOffset(1.25);
+
+   // plot of added NSB
+   fHNSB = new TH1D("NSB/area","Distribution of added NSB/area", 
+                    100, -100.0, 200.0);
+   fHNSB->SetXTitle("no.of added NSB photons/area");
+   fHNSB->SetYTitle("no.of pixels");
+   fHNSB->SetDirectory(NULL);
+   fHNSB->UseCurrentStyle();
+   fHNSB->GetYaxis()->SetTitleOffset(1.25);
+
+   //--------------------------------------------------------------------
+
+  *fLog << inf << "Type of data to be padded : " << fType << endl; 
+  *fLog << inf << "Name of MPedPhotCam container : " << fNamePedPhotCam 
+        << endl; 
+
+   fIter = 10;
+
+   memset(fInf,      0, sizeof(fInf));
+   memset(fErrors,   0, sizeof(fErrors));
+   memset(fWarnings, 0, sizeof(fWarnings));
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the Padding (noise adjustment)
+//
+// input for the padding : 
+//  - the matrices fHgON, fHgOFF, fHgMC
+//  - the original distributions fHSigmaTheta, fHDiffPixTheta
+//
+
+Int_t MPad::Process()
+{
+  //*fLog << all << "Entry MPad::Process();" << endl;
+
+  // this is the conversion factor from the number of photons
+  //                                 to the number of photo electrons
+  // later to be taken from MCalibration
+  // fPEperPhoton = PW * LG * QE * 1D
+  Double_t fPEperPhoton = 0.92 * 0.94 * 0.23 * 0.9;   //  (= 0.179)
+
+  //------------------------------------------------
+  // Add pixels to MCerPhotEvt which are not yet in;
+  // set their number of photons equal to zero. 
+  // Purpose : by the padding the number of photons is changed
+  // so that cleaning and cuts may be affected.
+  // However, no big effect is expectec unless the padding is strong
+  // (strong increase of the noise level)
+  // At present comment out this code
+
+  /*
+  UInt_t imaxnumpix = fCam->GetNumPixels();
+
+  for (UInt_t i=0; i<imaxnumpix; i++)
+  {
+    Bool_t alreadythere = kFALSE;
+    UInt_t npix = fEvt->GetNumPixels();
+    for (UInt_t j=0; j<npix; j++)
+    {
+      MCerPhotPix &pix = (*fEvt)[j];
+      UInt_t id = pix.GetPixId();
+      if (i==id)
+      {
+        alreadythere = kTRUE;
+        break;
+      }
+    }
+    if (alreadythere)
+      continue;
+
+    fEvt->AddPixel(i, 0.0, (*fPed)[i].GetRms());
+  }
+  */
+
+
+  //-----------------------------------------
+  Int_t rc=0;
+  Int_t rw=0;
+
+  const UInt_t npix = fEvt->GetNumPixels();
+
+  //*fLog << all << "MPad::Process(); before padding : " << endl;
+
+  //-------------------------------------------
+  // Calculate average sigma of the event
+  //
+  fPed->ReCalc(*fCam, fBad);
+  //*fLog << "pedestalRMS, inner and outer = " << (fPed->GetArea(0)).GetRms()
+  //      << ",  " << (fPed->GetArea(1)).GetRms() << endl;
+
+
+  // inner sigmabar/sqrt(area)
+  Double_t ratioinn = fCam->GetPixRatio(0);
+  Double_t sigbarInnerold_phot = (fPed->GetArea(0)).GetRms();
+  Double_t sigbarInnerold  = sigbarInnerold_phot * fPEperPhoton * sqrt(ratioinn);
+  Double_t sigbarInnerold2 = sigbarInnerold*sigbarInnerold;
+
+  // outer sigmabar/sqrt(area)
+  Double_t ratioout = fCam->GetPixRatio(500);
+  Double_t sigbarOuterold_phot = (fPed->GetArea(1)).GetRms();
+  Double_t sigbarOuterold  = sigbarOuterold_phot * fPEperPhoton * sqrt(ratioout);
+  Double_t sigbarOuterold2 = sigbarOuterold*sigbarOuterold;
+
+  const Double_t theta = fPointPos->GetZd();
+
+  //*fLog << all << "theta = " << theta << endl;
+
+  Int_t binTheta = fHSigmaTheta->GetXaxis()->FindBin(theta);
+  if ( binTheta < 1  ||  binTheta > fHSigmaTheta->GetNbinsX() )
+  {
+    *fLog << warn 
+          << "MPad::Process(); binNumber out of range : theta, binTheta = "
+          << theta << ",  " << binTheta << endl;
+
+    rc = 2;
+    fErrors[rc]++;
+    return kCONTINUE;
+  }
+
+  //*fLog << all << "binTheta = " << binTheta << endl;
+  
+
+  //-------------------------------------------
+  // get number of events in this theta bin               (nTheta)
+  // and number of events in this sigbarInnerold_phot bin (nSigma)
+
+  Double_t nTheta;
+  Double_t nSigma;
+
+  TH2D *st = NULL;
+  if      (fType == "MC")  st = fHSigmaThetaMC;
+  else if (fType == "ON")  st = fHSigmaThetaON;
+  else if (fType == "OFF") st = fHSigmaThetaOFF;
+  else
+  {
+    *fLog << err << "MPad : illegal data type '" << fType 
+          <<  "'" << endl;
+    return kERROR;  
+  }
+
+  TH1D *hn;
+  hn = st->ProjectionY("", binTheta, binTheta, "");
+
+  //*fLog << "Title of histogram : " << st->GetTitle() << endl;
+  //for (Int_t i=1; i<=hn->GetNbinsX(); i++)
+  //{
+  //  *fLog << "bin " << i << " : no.of entries = " << hn->GetBinContent(i)
+  //        << endl;
+  //}
+
+  nTheta = hn->Integral();
+  Int_t binSigma = hn->FindBin(sigbarInnerold_phot);
+  nSigma = hn->GetBinContent(binSigma);
+
+  //*fLog << all           
+  //       << "Theta, sigbarold_phot, binTheta, binSigma, nTheta, nSigma = "
+  //       << theta << ",  " << sigbarInnerold_phot << ",  " << binTheta 
+  //       << ",  "
+  //       << binSigma << ",  " << nTheta << ",  " << nSigma   << endl;      
+
+  delete hn;
+ 
+  //-------------------------------------------
+
+  //******************************************************************
+  // has the event to be padded ?
+  // if yes : to which sigmabar should it be padded ?
+  //
+
+  TH3D *Hg = NULL;
+  if      (fType == "MC")  Hg = fHgMC;
+  else if (fType == "ON")  Hg = fHgON;
+  else if (fType == "OFF") Hg = fHgOFF;
+  else
+  {
+    *fLog << err << "MPad : illegal type of data '" << fType << "'"
+          << endl;
+    return kERROR;
+  }
+
+  Int_t binSig = Hg->GetYaxis()->FindBin(sigbarInnerold_phot);
+  //*fLog << all << "binSig, sigbarInnerold_phot = " << binSig << ",  " 
+  //        << sigbarInnerold_phot << endl;
+
+  Double_t prob;
+  TH1D *hpad = NULL;
+
+
+  hpad = Hg->ProjectionZ("zON", binTheta, binTheta, binSig, binSig, "");
+
+  //Int_t nb = hpad->GetNbinsX();
+  //for (Int_t i=1; i<=nb; i++)
+  //{
+  //  if (hpad->GetBinContent(i) != 0.0)
+  //    *fLog << all << "i, Hg = " << i << ",  " 
+  //          << hpad->GetBinContent(i) << endl;
+  //}
+
+  if (nSigma != 0.0)
+    prob = hpad->Integral() * nTheta/nSigma;
+  else
+    prob = 0.0;
+
+  //*fLog << all << "nTheta, nSigma, prob = " << nTheta << ",  " << nSigma 
+  //       << ",  " << prob << endl;
+
+  if ( prob <= 0.0  ||  gRandom->Uniform() > prob )
+  {
+    delete hpad;
+    // event should not be padded
+    //*fLog << all << "event is not padded" << endl;
+
+    rc = 0;
+    fInf[rc]++;
+    return kTRUE;
+  }
+  // event should be padded
+  //*fLog << all << "event will be padded" << endl;  
+
+
+  //-------------------------------------------
+  // for the current theta, generate a sigmabar_inner :
+  //     for MC/ON/OFF data according to the matrix fHgMC/ON/OFF
+  //
+  Double_t sigmabarInner_phot = 0;
+  Double_t sigmabarInner      = 0;
+
+  
+  //Int_t nbinsx = hpad->GetNbinsX();
+  //for (Int_t i=1; i<=nbinsx; i++)
+  //{
+  //  if (hpad->GetBinContent(i) != 0.0)
+  //    *fLog << all << "i, fHg = " << i << ",  " << hpad->GetBinContent(i) 
+  //          << endl;
+  //}
+
+  sigmabarInner_phot = hpad->GetRandom();
+  sigmabarInner = sigmabarInner_phot * fPEperPhoton * sqrt(ratioinn); 
+
+  //*fLog << all << "sigmabarInner_phot = " << sigmabarInner_phot << endl;
+
+  delete hpad;
+  
+  // new inner sigmabar2/area
+  const Double_t sigmabarInner2 = sigmabarInner*sigmabarInner;
+
+  //*fLog << all << "MPad::Process(); sigbarInnerold, sigmabarInner = " 
+  //      << sigbarInnerold << ",  "<< sigmabarInner << endl;
+
+  // Stop if target sigmabar is <= sigbarold
+  if (sigmabarInner <= sigbarInnerold)
+  {
+    *fLog << all << "MPad::Process(); target sigmabarInner is less than sigbarInnerold : "
+          << sigmabarInner << ",  " << sigbarInnerold << ",   aborting" 
+          << endl;
+
+    rc = 4;
+    fErrors[rc]++;
+    return kCONTINUE;     
+  }
+
+  //-------------------------------------------
+  // estimate a sigmabar_outer from sigmabar_inner :
+  // using the target distributions fHSigmaTheta and fHSigmaThetaOuter
+  // for sigmabar(inner) and sigmabar(outer)
+
+  Double_t innerMeantarget = 0.0;
+  Double_t outerMeantarget = 0.0;
+  Double_t innerRMStarget  = 0.0;
+  Double_t outerRMStarget  = 0.0;
+
+  // projection doesn't work
+  //TH1D *hi = fHSigmaTheta->ProjectionY("proinner", binTheta, binTheta, "e");
+  //TH1D *ho = fHSigmaThetaOuter->ProjectionY("proouter", binTheta, binTheta, "e");
+  //sigmabarOuter2 =   sigmabarInner2   + fPEperPhoton*fPEperPhoton * 
+  //                 (   ho->GetMean()*ho->GetMean()*ratioout 
+  //                   - hi->GetMean()*hi->GetMean()*ratioinn);
+
+  //innerMeantarget = hi->GetMean()*sqrt(ratioinn)*fPEperPhoton;
+  //outerMeantarget = ho->GetMean()*sqrt(ratioout)*fPEperPhoton;
+  //innerRMStarget  = hi->GetRMS(1)*sqrt(ratioinn)*fPEperPhoton;
+  //outerRMStarget  = ho->GetRMS(1)*sqrt(ratioout)*fPEperPhoton;
+
+  Double_t y      = 0.0;
+  Double_t ybar   = 0.0;
+  Double_t y2bar  = 0.0;
+  Double_t w      = 0.0;
+
+  Double_t isum   = 0.0;
+  Double_t isumy  = 0.0;
+  Double_t isumy2 = 0.0;
+  for (Int_t i=1; i<=fHSigmaTheta->GetNbinsY(); i++)
+  {
+    w = fHSigmaTheta->GetBinContent(binTheta, i);
+    y = fHSigmaTheta->GetYaxis()->GetBinCenter(i);
+    isum   += w;
+    isumy  += w * y;
+    isumy2 += w * y*y;
+  }
+  if (isum == 0.0)
+  {
+    innerMeantarget = 0.0;
+    innerRMStarget  = 0.0;
+  }    
+  else
+  {
+    ybar  = isumy /isum;
+    y2bar = isumy2/isum;
+    innerMeantarget = ybar                      * sqrt(ratioinn)*fPEperPhoton;
+    innerRMStarget  = sqrt( y2bar - ybar*ybar ) * sqrt(ratioinn)*fPEperPhoton;
+  }
+
+  Double_t osum   = 0.0;
+  Double_t osumy  = 0.0;
+  Double_t osumy2 = 0.0;
+  for (Int_t i=1; i<=fHSigmaThetaOuter->GetNbinsY(); i++)
+  {
+    w = fHSigmaThetaOuter->GetBinContent(binTheta, i);
+    y = fHSigmaThetaOuter->GetYaxis()->GetBinCenter(i);
+    osum   += w;
+    osumy  += w * y;
+    osumy2 += w * y*y;
+  }
+  if (osum == 0.0)
+  {
+    outerMeantarget = 0.0;
+    outerRMStarget  = 0.0;
+  }    
+  else
+  {
+    ybar  = osumy /osum;
+    y2bar = osumy2/osum;
+    outerMeantarget = ybar                      * sqrt(ratioout)*fPEperPhoton;
+    outerRMStarget  = sqrt( y2bar - ybar*ybar ) * sqrt(ratioout)*fPEperPhoton;
+  }
+
+
+  // new outer sigmabar2/area
+  Double_t sigmabarOuter2;
+
+  Double_t scal = ( innerMeantarget*innerRMStarget == 0.0   ||
+                    outerMeantarget*outerRMStarget == 0.0 )    ?  1.0 :
+          (outerMeantarget*outerRMStarget)/(innerMeantarget*innerRMStarget);
+  sigmabarOuter2 = outerMeantarget*outerMeantarget +
+                   scal * (sigmabarInner2 - innerMeantarget*innerMeantarget);
+
+  //*fLog << "innerMeantarget, innerRMStarget = " << innerMeantarget 
+  //      << ",  " << innerRMStarget << endl;
+
+  //*fLog << "outerMeantarget, outerRMStarget = " << outerMeantarget 
+  //      << ",  " << outerRMStarget << endl;
+
+  //*fLog << "sigmabarInner2, sigmabarOuter2, scal = " << sigmabarInner2 
+  //      << ",  " << sigmabarOuter2 << ",  " << scal << endl;
+
+  //delete hi;
+  //delete ho;
+
+  //-------------------------------------------
+  //
+  // Calculate average number of NSB photo electrons to be added (lambdabar)
+  // from the value of sigmabar, 
+  //  - using a fixed value (F2excess)  for the excess noise factor
+  
+  Double_t elNoise2;         // [photo electrons]  
+  Double_t F2excess  = 1.3;
+  Double_t lambdabar;        // [photo electrons]
+
+  //----------------
+  TH3D *sp = NULL;
+  if      (fType == "MC")  sp = fHDiffPixThetaTargetMC;
+  else if (fType == "ON")  sp = fHDiffPixThetaTargetON;
+  else if (fType == "OFF") sp = fHDiffPixThetaTargetOFF;
+
+  //----------------
+
+  Int_t bincheck = sp->GetXaxis()->FindBin(theta);
+  if (binTheta != bincheck)
+  {
+    *fLog << err 
+          << "MPad::Process(); The binnings of the 2 histograms are not identical; aborting"
+          << endl;
+    return kERROR;
+  }
+
+  // In this Theta bin, get RMS of (Sigma^2-sigmabar^2)/area for inner pixels.
+  // The average electronic noise (to be added) has to be in the order of
+  // this RMS, otherwise the electronic noise of an individual pixel 
+  // (elNoise2Pix) may become negative
+
+  //----------------
+
+
+  // Attention : maximum ID of inner pixels hard coded !!!
+  Int_t idmaxpixinner = 396;
+  Int_t binmaxpixinner = 
+        sp->GetYaxis()->FindBin( (Double_t)idmaxpixinner );
+
+  TH1D *hnoise = NULL;
+    hnoise = sp->ProjectionZ("", binTheta, binTheta, 0, binmaxpixinner, "");
+
+  Double_t RMS_phot = hnoise->GetRMS(1);  
+  Double_t RMS = RMS_phot * fPEperPhoton * fPEperPhoton;
+  delete hnoise;
+
+  elNoise2 = TMath::Min(2.0*RMS,  sigmabarInner2 - sigbarInnerold2);
+  //*fLog << all << "RMS_phot, elNoise2 = " << RMS_phot << ",  "
+  //      << elNoise2 << endl; 
+
+  lambdabar = (sigmabarInner2 - sigbarInnerold2 - elNoise2) / F2excess;  
+
+  if (lambdabar <= 0.0)
+  {
+    rc = 3;
+    fErrors[rc]++;
+  }
+
+  //*fLog << "lambdabar = " << lambdabar << endl;
+
+  // This value of lambdabar is the same for all pixels;
+  // note that lambdabar is the NSB p.e. density
+
+  //----------   start loop over pixels   ---------------------------------
+  // do the padding for each pixel
+  //
+  // pad only pixels   - which are used 
+  //
+
+  Double_t sigma2      = 0;
+
+  Double_t diff_phot   = 0;
+  Double_t diff        = 0;
+
+  Double_t addSig2_phot= 0;
+  Double_t addSig2     = 0;
+
+  Double_t elNoise2Pix = 0;
+
+
+  // throw the Sigma for the pixels from the distribution fHDiffPixTheta
+  // MC  : from fHDiffPixThetaTargetMC
+  // ON  : from fHDiffPixThetaTaregtON
+  // OFF : from fHDiffPixThetaTargetOFF
+
+
+  Double_t sigbarold2;
+  Double_t sigmabar2;
+
+  for (UInt_t i=0; i<npix; i++) 
+  {   
+
+    MCerPhotPix &pix = (*fEvt)[i];
+    if ( !pix.IsPixelUsed() )
+      continue;
+
+    //if ( pix.GetNumPhotons() == 0.0)
+    //{
+    //  *fLog << warn 
+    //        << "MPad::Process(); no.of photons is 0 for used pixel" 
+    //        << endl;
+    //  continue;
+    //}
+
+    Int_t j = pix.GetPixId();
+
+    // GetPixRatio returns (area of pixel 0 / area of current pixel)
+    Double_t ratio = fCam->GetPixRatio(j);
+
+    if (ratio > 0.5)
+    {
+      sigbarold2 = sigbarInnerold2;
+      sigmabar2  = sigmabarInner2;
+    }
+    else
+    {
+      sigbarold2 = sigbarOuterold2;
+      sigmabar2  = sigmabarOuter2;
+    }
+
+    MPedPhotPix &ppix = (*fPed)[j];
+
+    // count number of pixels treated
+    fWarnings[0]++;
+
+
+    Double_t oldsigma_phot = ppix.GetRms();
+    Double_t oldsigma = oldsigma_phot * fPEperPhoton * sqrt(ratio);
+    Double_t oldsigma2 = oldsigma*oldsigma;
+
+    //---------------------------------
+    // throw the Sigma for this pixel 
+    //
+    Int_t binPixel = sp->GetYaxis()->FindBin( (Double_t)j );
+
+    Int_t count;
+    Bool_t ok;
+
+    TH1D *hdiff = NULL;
+
+     hdiff = sp->ProjectionZ("", binTheta, binTheta,
+                                 binPixel, binPixel, "");
+     Double_t integral =  hdiff->Integral();
+     // if there are no entries in hdiff, diff cannot be thrown
+     // in this case diff will be set to the old difference
+     if ( integral == 0 )
+     {
+       //*fLog << warn << "MPad::Process(); fType = " << fType 
+       //      << ", projection of '"
+       //      << sp->GetName() << "' for Theta bin " 
+       //      << binTheta << "  and pixel " << j  
+       //      << " has no entries; set diff equal to the old difference  " 
+       //      << endl;
+
+       diff = TMath::Max(oldsigma2 - sigbarold2,
+                         lambdabar*F2excess + oldsigma2 - sigmabar2);
+
+       rc = 2;
+       fWarnings[rc]++;
+     }
+
+     // start of else -------------------
+     else
+     {
+       count = 0;
+       ok = kFALSE;
+       for (Int_t m=0; m<fIter; m++)
+       {
+         count += 1;
+         diff_phot = hdiff->GetRandom();
+
+         //*fLog << "after GetRandom : j, m, diff_phot = " << j << " : "
+         //      << m << ",  " << diff_phot << endl;
+
+         diff = diff_phot * fPEperPhoton * fPEperPhoton;
+ 
+         // the following condition ensures that elNoise2Pix > 0.0 
+         if ( (diff + sigmabar2 - oldsigma2
+                                - lambdabar*F2excess) > 0.0 )
+         {
+           ok = kTRUE;
+           break;
+         }
+       }
+
+       if (!ok)
+       {
+         //*fLog << all << "theta, j, count, sigmabar2, diff, oldsigma2, ratio, lambdabar = " 
+         //      << theta << ",  " 
+         //      << j << ",  " << count << ",  " << sigmabar2 << ",  " 
+         //      << diff << ",  " << oldsigma2 << ",  " << ratio << ",  "
+         //      << lambdabar << endl;
+         diff = lambdabar*F2excess + oldsigma2 - sigmabar2; 
+
+         rw = 1;
+         fWarnings[rw]++;
+       }
+     }
+     // end of else --------------------
+
+    delete hdiff;
+    sigma2 = diff + sigmabar2;
+
+
+    //---------------------------------
+    // get the additional sigma^2 for this pixel (due to the padding)
+
+    addSig2 = (sigma2 - oldsigma2) / ratio;
+    addSig2_phot = addSig2 / (fPEperPhoton * fPEperPhoton);
+
+    //---------------------------------
+    // get the additional electronic noise for this pixel
+
+    elNoise2Pix = addSig2 - lambdabar*F2excess/ratio;
+
+
+    //---------------------------------
+    // throw actual number of additional NSB photo electrons (NSB)
+    //       and its RMS (sigmaNSB) 
+
+    Double_t NSB0 = gRandom->Poisson(lambdabar/ratio);
+    Double_t arg  = NSB0*(F2excess-1.0) + elNoise2Pix;
+    Double_t sigmaNSB0;
+
+    if (arg >= 0.0)
+    {
+      sigmaNSB0 = sqrt( arg );
+    }
+    else
+    {
+      sigmaNSB0 = 0.0000001;      
+      if (arg < -1.e-10)
+      {
+        *fLog << warn << "MPad::Process(); argument of sqrt < 0 : "
+              << arg << endl;
+      }
+    }
+
+
+    //---------------------------------
+    // smear NSB0 according to sigmaNSB0
+    // and subtract lambdabar because of AC coupling
+
+    Double_t NSB = gRandom->Gaus(NSB0, sigmaNSB0) - lambdabar/ratio;
+    Double_t NSB_phot = NSB / fPEperPhoton;
+
+    //---------------------------------
+ 
+    // add additional NSB to the number of photons
+    Double_t oldphotons_phot = pix.GetNumPhotons();
+    Double_t oldphotons = oldphotons_phot * fPEperPhoton;
+    Double_t newphotons = oldphotons + NSB;
+    Double_t newphotons_phot = newphotons / fPEperPhoton;    
+    pix.SetNumPhotons(	newphotons_phot );
+
+
+    fHNSB->Fill( NSB_phot*ratio );
+    fHPhotons->Fill( oldphotons_phot*ratio, 
+                     newphotons_phot*ratio );
+
+
+    // error: add sigma of padded noise quadratically
+    Double_t olderror_phot = pix.GetErrorPhot();
+    Double_t newerror_phot = 
+                           sqrt( olderror_phot*olderror_phot + addSig2_phot );
+    pix.SetErrorPhot( newerror_phot );
+
+
+    Double_t newsigma = sqrt( sigma2 / ratio ); 
+    Double_t newsigma_phot = newsigma / fPEperPhoton; 
+    ppix.SetRms( newsigma_phot );
+
+    fHSigmaPedestal->Fill( oldsigma_phot, newsigma_phot );
+  } 
+  //----------   end of loop over pixels   ---------------------------------
+
+
+  //*fLog << all << "MPad::Process(); after padding : " << endl;
+
+  // Calculate sigmabar again and crosscheck
+  fPed->ReCalc(*fCam, fBad);
+  //*fLog << "pedestalRMS, inner and outer = " << (fPed->GetArea(0)).GetRms()
+  //      << ",  " << (fPed->GetArea(1)).GetRms() << endl;
+
+  //*fLog << all << "Exit MPad::Process();" << endl;
+
+  rc = 0;
+  fErrors[rc]++;
+
+  return kTRUE;
+  //******************************************************************
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MPad::PostProcess()
+{
+    if (GetNumExecutions() != 0)
+    {
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    if (fWarnings[0] == 0 ) fWarnings[0] = 1;
+
+    *fLog << " " << setw(7) << fWarnings[1] << " (" << setw(3) 
+          << (int)(fWarnings[1]*100/fWarnings[0])
+          << "%) Pixel: iteration to find acceptable sigma failed" 
+          << ", fIter = " << fIter << endl;
+
+    *fLog << " " << setw(7) << fWarnings[2] << " (" << setw(3) 
+          << (int)(fWarnings[2]*100/fWarnings[0]) 
+          << "%) Pixel: No data for generating Sigma^2-Sigmabar^2" << endl;
+
+
+    *fLog << " " << setw(7) << fErrors[2] << " (" << setw(3) 
+          << (int)(fErrors[2]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Zenith angle out of range" << endl;
+
+    *fLog << " " << setw(7) << fErrors[4] << " (" << setw(3) 
+          << (int)(fErrors[4]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: new sigma <= old sigma" << endl;
+
+    *fLog << " " << setw(7) << fErrors[3] << " (" << setw(3) 
+          << (int)(fErrors[3]*100/GetNumExecutions()) 
+          << "%) lambdabar = 0" << endl;
+
+    *fLog << " " << setw(7) << fInf[0] << " (" << setw(3) 
+          << (int)(fInf[0]*100/GetNumExecutions()) 
+          << "%) Evts didn't have to be padded" << endl;
+
+    *fLog << " " << fErrors[0] << " (" 
+          << (int)(fErrors[0]*100/GetNumExecutions()) 
+          << "%) Evts were successfully padded!" << endl;
+    *fLog << endl;
+
+    }
+
+    //---------------------------------------------------------------
+    TCanvas &c = *(MH::MakeDefCanvas("Pad", "", 900, 1200)); 
+    c.Divide(3, 4);
+    gROOT->SetSelectedPad(NULL);
+
+    c.cd(1);
+    fHNSB->DrawCopy();
+    fHNSB->SetBit(kCanDelete);    
+
+    c.cd(2);
+    fHSigmaPedestal->DrawCopy();
+    fHSigmaPedestal->SetBit(kCanDelete);    
+
+    c.cd(3);
+    fHPhotons->DrawCopy();
+    fHPhotons->SetBit(kCanDelete);    
+
+    //--------------------------------------------------------------------
+
+    if (fHgON)
+    {
+      c.cd(4);
+      TH2D *m1;
+      m1 = (TH2D*) ((TH3*)fHgON)->Project3D("zy");
+      m1->SetDirectory(NULL);
+      m1->UseCurrentStyle();
+      m1->SetTitle("(fHgON) Sigmabar-new vs. Sigmabar-old (ON, all  \\Theta)");
+      m1->SetXTitle("Sigmabar-old");
+      m1->SetYTitle("Sigmabar-new");
+
+      m1->DrawCopy("box");
+      m1->SetBit(kCanDelete);;
+    }
+
+    if (fHgOFF)
+    {
+      c.cd(5);
+      TH2D *m2;
+      m2 = (TH2D*) ((TH3*)fHgOFF)->Project3D("zy");
+      m2->SetDirectory(NULL);
+      m2->UseCurrentStyle();
+      m2->SetTitle("(fHgOFF) Sigmabar-new vs. Sigmabar-old (OFF, all  \\Theta)");
+      m2->SetXTitle("Sigmabar-old");
+      m2->SetYTitle("Sigmabar-new");
+
+      m2->DrawCopy("box");
+      m2->SetBit(kCanDelete);;
+    }
+
+    if (fHgMC)
+    {
+      c.cd(6);
+      TH2D *m3;
+      m3 = (TH2D*) ((TH3*)fHgMC)->Project3D("zy");
+      m3->SetDirectory(NULL);
+      m3->UseCurrentStyle();
+      m3->SetTitle("(fHgMC) Sigmabar-new vs. Sigmabar-old (MC, all  \\Theta)");
+      m3->SetXTitle("Sigmabar-old");
+      m3->SetYTitle("Sigmabar-new");
+
+      m3->DrawCopy("box");
+      m3->SetBit(kCanDelete);;
+    }
+
+    //--------------------------------------------------------------------
+
+    if (fHgOuterON)
+    {
+      c.cd(7);
+      TH2D *m1;
+      m1 = (TH2D*) ((TH3*)fHgOuterON)->Project3D("zy");
+      m1->SetDirectory(NULL);
+      m1->UseCurrentStyle();
+      m1->SetTitle("(fHgOuterON) Sigmabar-new vs. Sigmabar-old (ON, all  \\Theta)");
+      m1->SetXTitle("Sigmabar-old");
+      m1->SetYTitle("Sigmabar-new");
+
+      m1->DrawCopy("box");
+      m1->SetBit(kCanDelete);;
+    }
+
+    if (fHgOuterOFF)
+    {
+      c.cd(8);
+      TH2D *m2;
+      m2 = (TH2D*) ((TH3*)fHgOuterOFF)->Project3D("zy");
+      m2->SetDirectory(NULL);
+      m2->UseCurrentStyle();
+      m2->SetTitle("(fHgOuterOFF) Sigmabar-new vs. Sigmabar-old (OFF, all  \\Theta)");
+      m2->SetXTitle("Sigmabar-old");
+      m2->SetYTitle("Sigmabar-new");
+
+      m2->DrawCopy("box");
+      m2->SetBit(kCanDelete);;
+    }
+
+    if (fHgOuterMC)
+    {
+      c.cd(9);
+      TH2D *m3;
+      m3 = (TH2D*) ((TH3*)fHgOuterMC)->Project3D("zy");
+      m3->SetDirectory(NULL);
+      m3->UseCurrentStyle();
+      m3->SetTitle("(fHgOuterMC) Sigmabar-new vs. Sigmabar-old (MC, all  \\Theta)");
+      m3->SetXTitle("Sigmabar-old");
+      m3->SetYTitle("Sigmabar-new");
+
+      m3->DrawCopy("box");
+      m3->SetBit(kCanDelete);;
+    }
+
+    //--------------------------------------------------------------------
+
+    c.cd(10);
+    fHSigmaTheta->SetDirectory(NULL);
+    fHSigmaTheta->UseCurrentStyle();
+    fHSigmaTheta->DrawCopy();
+    fHSigmaTheta->SetBit(kCanDelete);    
+
+    c.cd(11);
+    fHSigmaThetaOuter->SetDirectory(NULL);
+    fHSigmaThetaOuter->UseCurrentStyle();
+    fHSigmaThetaOuter->DrawCopy();
+    fHSigmaThetaOuter->SetBit(kCanDelete);    
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MPad.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MPad.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MPad.h	(revision 17960)
@@ -0,0 +1,131 @@
+#ifndef MARS_MPad
+#define MARS_MPad
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+class MGeomCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MPointingPos;
+class MParList;
+class MBadPixelsCam;
+class MRead;
+class MFilterList;
+
+
+class MPad : public MTask
+{
+private:
+    MGeomCam       *fCam;
+    MCerPhotEvt    *fEvt; 
+    MPointingPos   *fPointPos;
+    MPedPhotCam    *fPed;
+    MBadPixelsCam  *fBad;
+
+    TString  fNamePedPhotCam; // name of the 'MPedPhotCam' container
+    TString  fType;           // type of data to be padded
+    TFile    *fInfile;        // input file containing padding histograms
+
+    Int_t          fIter;
+
+    Int_t          fInf[9];
+    Int_t          fErrors[9];
+    Int_t          fWarnings[3];
+
+    //----------------------------------
+    // plots used for the padding
+    // for all plots it is assumed that the pedestal RMS is given in units of "number of photons"
+
+    // original distributions
+    TH2D  *fHSigmaThetaMC;     // 2D-histogram (sigmabar_inner vs. Theta)
+    TH2D  *fHSigmaThetaON;     // 2D-histogram (sigmabar_inner vs. Theta)
+    TH2D  *fHSigmaThetaOFF;    // 2D-histogram (sigmabar_inner vs. Theta)
+
+    TH2D  *fHSigmaThetaOuterMC;   // 2D-histogram (sigmabar_outer vs. Theta)
+    TH2D  *fHSigmaThetaOuterON;   // 2D-histogram (sigmabar_outer vs. Theta)
+    TH2D  *fHSigmaThetaOuterOFF;  // 2D-histogram (sigmabar_outer vs. Theta)
+
+    TH3D  *fHDiffPixThetaMC;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaON;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaOFF;  // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+
+    //---------------------
+    // target distributions
+    TH2D  *fHSigmaTheta;       // 2D-histogram (sigmabar_inner vs. Theta)
+    TH2D  *fHSigmaThetaOuter;  // 2D-histogram (sigmabar_outer vs. Theta)
+
+    TH3D  *fHDiffPixThetaTargetMC;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaTargetON;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaTargetOFF;  // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+
+    //---------------------
+    // matrices according to which the padding is performed
+    TH3D  *fHgMC;        // matrix (Theta, sigbarold, sigbarnew) for MC data
+    TH3D  *fHgON;        // matrix (Theta, sigbarold, sigbarnew) for ON data
+    TH3D  *fHgOFF;       // matrix (Theta, sigbarold, sigbarnew) for OFF data
+
+    TH3D  *fHgOuterMC;   // matrix (Theta, sigbarold, sigbarnew) for MC data
+    TH3D  *fHgOuterON;   // matrix (Theta, sigbarold, sigbarnew) for ON data
+    TH3D  *fHgOuterOFF;  // matrix (Theta, sigbarold, sigbarnew) for OFF data
+
+    //-------------------------------
+    // plots for checking the padding
+    TH2D  *fHSigmaPedestal; // 2D-histogram : pedestal sigma after
+                            //                versus before padding
+    TH2D  *fHPhotons;       // 2D-histogram : no.of photons/area after
+                            //                versus before padding
+    TH1D  *fHNSB;           // 1D-histogram : additional NSB/area
+
+    //-------------------------------
+    Bool_t MergeABC(TString tA, TString tB, TString tC,
+                    TH2D *hA,   TH2D *hB,   TH2D *hC,   TH2D *hM,
+                    TH3D *hgA,  TH3D *hgB,  TH3D *hgC,  TString canv);
+
+    Bool_t Merge2Distributions(TH1D *hista, TH1D *histb, TH1D *histap,
+                               TH2D *fHga,  TH2D *fHgb,  Int_t nbinssig,
+                               TString canv);
+
+    Bool_t UpdateHg(TH2D *fHga, TH1D *histap, TH2D *fHge, TH3D *fHgA,
+                    Int_t nbinssig, Int_t l); 
+
+public:
+    MPad(const char *name=NULL, const char *title=NULL);
+    ~MPad();
+
+    void SetDataType(const char *type);       // type of data to be padded
+    void SetNamePedPhotCam(const char *name); // name of MPedPhotCam container
+
+    Bool_t ReadPadHistograms(TString type, TString filein);
+
+    Bool_t MergeONOFFMC(TString nameon="", TString nameoff="",
+                        TString namemc="", TString fileout="");
+
+    Bool_t WritePaddingDist(TString fileout);
+    Bool_t ReadPaddingDist(TString  filein);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    ClassDef(MPad, 0)    // task for the padding 
+}; 
+
+#endif
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MPadding.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MPadding.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MPadding.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/MPadding.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MPadding.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MPadding.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/MParameterCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MParameterCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MParameterCalc.cc	(revision 17960)
@@ -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  6/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MParameterCalc
+//
+// Task to calculate a parameter stored ina MParametrD by a rule, eg:
+//
+// MParameterCalc est;
+// est.SetRule("0.5 + (1.1*MHillas.fLength) + (2.2*MHillasSrc.fDist) + (3.3*MHillas.fSize) +"
+//             "(4.4*MHillas.fSize*MHillas.fLength) + (5.5*MHillasSrc.fDist*MHillas.fLength)");
+//
+// For description of rules, see MDataPhrase.
+//
+// Output:
+//   fNameParameter [MParameterD] <default=MParameterD>
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MParameterCalc.h"
+
+#include <TMath.h>
+
+#include "MParList.h"
+
+#include "MDataPhrase.h"
+#include "MParameters.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MParameterCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Initialize fData with default rule "MMcEvt.fEnergy"
+//
+MParameterCalc::MParameterCalc(const char *def, const char *name, const char *title)
+    : fData(0), fParameter(0), fNameParameter("MParameterD")
+{
+    fName  = name  ? name  : "MParameterCalc";
+    fTitle = title ? title : "Task to calculate a MParameterD";
+
+    fData = new MDataPhrase(def);
+}
+
+// --------------------------------------------------------------------------
+//
+// delete fData
+//
+MParameterCalc::~MParameterCalc()
+{
+    delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fData. Initialize a new MDataPhrase with rule.
+// Returns if fData->IsValid()
+//
+Bool_t MParameterCalc::SetRule(const char *rule)
+{
+    delete fData;
+    fData = new MDataPhrase(rule);
+
+    return fData->IsValid();
+}
+
+// --------------------------------------------------------------------------
+//
+// Forwards SetVariables to fData to allow optimizations.
+//
+void MParameterCalc::SetVariables(const TArrayD &arr)
+{
+    fData->SetVariables(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate "MEnergyEst"
+// PreProcess fData.
+//
+Int_t MParameterCalc::PreProcess(MParList *plist)
+{
+    memset(fCounter, 0, sizeof(ULong_t)*2);
+
+    fParameter = (MParameterD*)plist->FindCreateObj("MParameterD", fNameParameter);
+    if (!fParameter)
+        return kFALSE;
+
+    *fLog << inf << "Rule for " << fNameParameter << ": " << fData->GetRule() << endl;
+
+    if (!fData->PreProcess(plist))
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get value from fData and set it to fEnergy. SetReadyToSave for fEnergy.
+// Return kCONTINUE if value is NaN (Not a Number)
+//
+Int_t MParameterCalc::Process()
+{
+    const Double_t val = fData->GetValue();
+    if (TMath::IsNaN(val))
+    {
+        fCounter[0]++;
+        return kCONTINUE;
+    }
+    if (!TMath::Finite(val))
+    {
+        fCounter[1]++;
+        return kCONTINUE;
+    }
+
+    fParameter->SetVal(val);
+    fParameter->SetReadyToSave();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print some execution statistics
+//
+Int_t MParameterCalc::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    PrintSkipped(fCounter[0], "Skipped due to NaN-result (Not a Number)");
+    PrintSkipped(fCounter[1], "Skipped due to inf-result (infinite)");
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the rule used for energy estimation
+//
+void MParameterCalc::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":";
+    if (!fData)
+        *fLog << " <n/a>" << endl;
+    else
+        *fLog << endl << fData->GetRule() << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+// Avoid trailing 0's!
+//
+// Example:
+//   test.C:
+//     MParameterCalc est("MyEstimator");
+//
+//   test.rc:
+//     MyEstimator.Rule: {0} + {1}
+//     MyEstimator.NameOutput: MParameterD
+//     MyEstimator.0: log10(MHillas.fSize)
+//     MyEstimator.1: 5.5
+//
+// For more details see MDataPhrase::ReadEnv
+//
+Int_t MParameterCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    MDataPhrase *f = new MDataPhrase;
+    f->SetName(fName);
+
+    const Bool_t rc = f->ReadEnv(env, prefix, print);
+    if (rc!=kTRUE)
+    {
+        delete f;
+        return rc;
+    }
+
+    delete fData;
+    fData = f;
+
+    if (!f->HasValidRule())
+    {
+        *fLog << err << "MParameterCalc::ReadEnv - ERROR: Inavlid rule from resource file." << endl;
+        return kERROR;
+    }
+
+    if (IsEnvDefined(env, prefix, "NameOutput", print))
+        fNameParameter = GetEnvValue(env, prefix, "NameOutput", fNameParameter);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/manalysis/MParameterCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MParameterCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MParameterCalc.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MParameterCalc
+#define MARS_MParameterCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MData;
+class MParameterD;
+
+class MParameterCalc : public MTask
+{
+private:
+    MData       *fData;          //-> Input MDataPhrase with rule
+    MParameterD *fParameter;     //!  Output parameter
+
+    TString      fNameParameter; //!  Name for output parameter
+
+    ULong_t      fCounter[2];    //!  Counterf for continues
+
+    // MTask
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t PostProcess();
+
+
+public:
+    MParameterCalc(const char *def=0, const char *name=NULL, const char *title=NULL);
+    ~MParameterCalc();
+
+    // Setter
+    Bool_t SetRule(const char *rule);
+    void   SetVariables(const TArrayD &);
+    void   SetNameParameter(const char *name) { fNameParameter=name; }
+
+    // TObject
+    void Print(Option_t *o="") const; //*MENU*
+
+    ClassDef(MParameterCalc, 1) // Task to estimate the energy by a rule
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/manalysis/MSourcePosfromStarPos.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MSourcePosfromStarPos.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MSourcePosfromStarPos.cc	(revision 17960)
@@ -0,0 +1,888 @@
+
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Wolfgang Wittek 02/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSourcePosfromStarPos
+//
+//  This is a task which
+//  - calculates the position of the source in the camera
+//    from the position of a known star in the camera
+//  - and puts the source position into the container MSrcPosCam
+//
+//  Input :
+//   ASCII file containing for each run 
+//   - the run number
+//   - the direction (theta, phi) the telescope is pointing to in [deg]
+//   - the position  (xStar, yStar)   of a known star in the camera in [mm]
+//   - the error     (dxStar, dyStar) of this position in [mm]
+//
+//  Output Containers :
+//   MSrcPosCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <TList.h>
+#include <TSystem.h>
+#include <TMatrixD.h>
+
+#include <fstream>
+
+#include "MSourcePosfromStarPos.h"
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MPointingPos.h"
+#include "MMcEvt.hxx"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MObservatory.h"
+
+ClassImp(MSourcePosfromStarPos);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MSourcePosfromStarPos::MSourcePosfromStarPos(
+                                         const char *name, const char *title)
+  : fIn(NULL)
+{
+    fName  = name  ? name  : "MSourcePosfromStarPos";
+    fTitle = title ? title : "Calculate source position from star position";
+
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    fRuns  = 0;
+    fSize  = 100;
+
+    fRunNr.Set(fSize);
+
+    fThetaTel.Set(fSize);
+    fPhiTel.Set(fSize);
+    fdThetaTel.Set(fSize);
+    fdPhiTel.Set(fSize);
+
+    Int_t fRows = 1;
+    fDecStar.Set(fRows);
+    fRaStar.Set(fRows);
+    fxStar.ResizeTo(fRows,fSize);
+    fyStar.ResizeTo(fRows,fSize);
+    fdxStar.ResizeTo(fRows,fSize);
+    fdyStar.ResizeTo(fRows,fSize);
+
+    fStars     = 0;
+    fStarsRead = 0;
+    fDecSource = 0.0;
+    fRaSource  = 0.0;
+
+    // these are the default values when starting the excution;
+    // later these locations contain the values of the last event
+    fxSourceold  =  25.0;
+    fySourceold  = -40.0;
+    fThetaradold =  25.0/kRad2Deg;
+    fPhiradold   = 180.0/kRad2Deg;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MSourcePosfromStarPos::~MSourcePosfromStarPos()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the sky coordinates of the source and of the star
+//
+// Input :
+// declination in units of     (Deg,  Min, Sec)
+// right ascension in units of (Hour, Min, Sec)
+//
+
+void MSourcePosfromStarPos::SetSourceAndStarPosition(
+	 TString  nameSource,
+	 Double_t decSourceDeg, Double_t decSourceMin, Double_t decSourceSec, 
+         Double_t raSourceHour, Double_t raSourceMin,  Double_t raSourceSec,
+	 TString nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  )
+{
+  *fLog << "MSourcePosfromStarPos::SetSourceAndStarPosition :" << endl;
+  *fLog << "       Source (dec) : "  << nameSource << "   " << decSourceDeg << ":" 
+        << decSourceMin << ":" << decSourceSec << endl;
+  *fLog << "       Source (ra)  : "  << nameSource  << "   " << raSourceHour << ":" 
+        << raSourceMin  << ":" << raSourceSec << endl;
+
+  *fLog << "       Star  (dec) : "  << nameStar   << "   " << decStarDeg << ":" 
+        << decStarMin << ":"   << decStarSec << endl;
+  *fLog << "       Star  (ra)  : "  << nameStar   << "   " << raStarHour << ":" 
+        << raStarMin << ":"    << raStarSec  << endl;
+
+  // convert into radians
+  fDecSource = (decSourceDeg + decSourceMin/60.0 + decSourceSec/3600.0)
+               / kRad2Deg;
+  fRaSource  = (raSourceHour + raSourceMin/60.0  + raSourceSec/3600.0)
+               * 360.0 / (24.0 * kRad2Deg);
+
+  fStars += 1;
+  fDecStar.Set(fStars);
+  fRaStar.Set(fStars);
+  fxStar.ResizeTo(fStars,fSize);
+  fyStar.ResizeTo(fStars,fSize);
+  fdxStar.ResizeTo(fStars,fSize);
+  fdyStar.ResizeTo(fStars,fSize);
+
+  fDecStar[fStars-1] = (decStarDeg + decStarMin/60.0 + decStarSec/3600.0)
+                       / kRad2Deg;
+  fRaStar[fStars-1]  = (raStarHour + raStarMin/60.0  + raStarSec/3600.0)
+                       * 360.0 / (24.0 * kRad2Deg);
+
+  *fLog << all << "MSourcePosfromStarPos::SetSourceAndStarPosition; fStars = "
+        << fStars << endl;
+  *fLog << all << "       fDecSource, fRaSource, fDecStar, fRaStar were set to : [radians]  "
+        << fDecSource << ",  " << fRaSource << ",  "
+        << fDecStar[fStars-1] << ",  " << fRaStar[fStars-1] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the sky coordinates of another star
+//
+// Input :
+// declination in units of     (Deg,  Min, Sec)
+// right ascension in units of (Hour, Min, Sec)
+//
+
+void MSourcePosfromStarPos::AddStar(
+	 TString nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  )
+{
+  *fLog << "MSourcePosfromStarPos::AddStar :" << endl;
+  *fLog << "       Star (dec)  : "  << nameStar   << "   " << decStarDeg << ":" 
+        << decStarMin << ":"   << decStarSec << endl;
+  *fLog << "       Star (ra)   : "  << nameStar   << "   " << raStarHour << ":" 
+        << raStarMin << ":"    << raStarSec  << endl;
+
+  // convert into radians
+  fStars += 1;
+  fDecStar.Set(fStars);
+  fRaStar.Set(fStars);
+  fxStar.ResizeTo(fStars,fSize);
+  fyStar.ResizeTo(fStars,fSize);
+  fdxStar.ResizeTo(fStars,fSize);
+  fdyStar.ResizeTo(fStars,fSize);
+
+  fDecStar[fStars-1] = (decStarDeg + decStarMin/60.0 + decStarSec/3600.0)
+                       / kRad2Deg;
+  fRaStar[fStars-1]  = (raStarHour + raStarMin/60.0  + raStarSec/3600.0)
+                       * 360.0 / (24.0 * kRad2Deg);
+
+  *fLog << all << "MSourcePosfromStarPos::AddStar; fStars = " << fStars 
+        << endl;
+  *fLog << all << "       fDecStar, fRaStar were set to : [radians]  "
+        << fDecStar[fStars-1] << ",  " << fRaStar[fStars-1] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MSourcePosfromStarPos::PreProcess(MParList *pList)
+{
+    MGeomCam *geom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!geom)
+    {
+        *fLog << err << "MSourcePosfromStarPos : MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+    fMm2Deg = geom->GetConvMm2Deg();
+    // fDistCameraReflector is the distance of the camera from the reflector center in [mm]
+    fDistCameraReflector = kRad2Deg / fMm2Deg;   
+        *fLog << all << "MSourcePosfromStarPos::PreProcess; fMm2Deg, fDistCameraReflector = " 
+              << fMm2Deg << ",  " << fDistCameraReflector << endl;
+
+    fObservatory = (MObservatory*)pList->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+    {
+        *fLog << err << "MObservatory not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+    fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MSourcePosfromStarPos::PreProcess; MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+
+   fPointPos = (MPointingPos*)pList->FindCreateObj("MPointingPos");
+   if (!fPointPos)
+   {
+       *fLog << err << "MSourcePosfromStarPos::PreProcess; MPointingPos not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+   if (!fMcEvt)
+   {
+       *fLog << all << "MSourcePosfromStarPos::PreProcess; MMcEvt not found... continue." << endl;
+   }
+   else
+   {
+       *fLog << all << "MSourcePosfromStarPos::PreProcess; MMcEvt was found... continue." << endl;
+   }
+
+
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << "MSourcePosfromStarPos::PreProcess; MSrcPosCam not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+    //---------------------------------------------------------------------
+    // read all files and call ReadData() to read and store the information
+    //
+
+    *fLog << all << "---------------------------------" << endl;
+    while(1)
+    {
+      if (!OpenNextFile()) 
+      {
+        *fLog << "there is no more file to open" << endl;
+        break;
+      }
+
+      *fLog << "read data" << endl;
+
+      // read "fStarsRead" = no.of (x,y) pairs to be read
+      *fIn >> fStarsRead;
+
+      while (1)
+      {
+        if (fIn->eof())
+        {
+          *fLog << "eof encountered; open next file" << endl;
+
+          if (!OpenNextFile()) break;
+        }
+
+        // FIXME! Set InputStreamID
+      
+        ReadData();
+      }
+    }
+
+    *fLog << "all data were read" << endl;
+    FixSize();
+
+    if (fDecSource == 0.0  ||  fRaSource == 0.0  ||  fStars == 0) 
+    {
+      *fLog << warn << "MSourcePosfromStarPos::PreProcess; there are no sky coordinates defined for the source or from stars; fStars, fStarsRead = " 
+            << fStars << ",  " << fStarsRead 
+            << endl;
+    }
+    *fLog << all << "---------------------------------" << endl;
+
+    //-------------------------------------------------------------
+
+    return kTRUE;
+}
+
+//=========================================================================
+//
+// SourcefromStar
+//
+// this routine calculates the position of a source (for example Crab) in the camera
+// from the position of a star (for example ZetaTauri) in the camera. The latter 
+// position may have been determined by analysing the DC currents in the different
+// pixels.
+//
+// Input  : thetaTel, phiTel          the direction the telescope is pointing to,
+//                                    in local coordinates
+//          f                         the distance between camera and reflector
+//          decStar, raStar           the position of the star in sky coordinates
+//          decSource, raSource       the position of the source in sky coordinates
+//          xStar, yStar              the position of the star in the camera
+//          dxStar, dyStar            error of the position of the star in the camera
+//
+// Output : xSource, ySource       the calculated position of the source in the camera
+//          dxSource, dySource     error of the calculated position of the source in 
+//                                 the camera
+//
+// Useful formulas can be found in TDAS 00-11 and TDAS 01-05
+//
+
+void MSourcePosfromStarPos::SourcefromStar(Double_t &f,
+		    TArrayD  &decStar,     TArrayD  &raStar,
+		    Double_t &decSource,   Double_t &raSource,
+                    Double_t &thetaTel,    Double_t &phiTel,    
+		    TArrayD  &xStar,       TArrayD  &yStar,
+		    TArrayD  &dxStar,      TArrayD  &dyStar,
+		    Double_t &xSource,     Double_t &ySource,
+		    Double_t &dxSource,    Double_t &dySource)
+{
+  /*
+  *fLog << "MSourcePosfromStarPos::SourcefromStar :  printout in degrees" << endl;
+  *fLog << "       decStar, raStar = " << decStar[0]*kRad2Deg << ",  " 
+        << raStar[0]*kRad2Deg << endl;
+  *fLog << "       decSource, raSource = " << decSource*kRad2Deg << ",  " 
+        << raSource*kRad2Deg << endl;
+  *fLog << "       thetaTel, phiTel = " << thetaTel*kRad2Deg << ",  " 
+        << phiTel*kRad2Deg << endl;
+  *fLog << "       xStar, yStar = " << xStar[0]*fMm2Deg << ",  " 
+        << yStar[0]*fMm2Deg << endl;
+
+  *fLog << "MSourcePosfromStarPos::SourcefromStar :  printout in radians and mm" << endl;
+  *fLog << "       decStar, raStar = " << decStar[0] << ",  " 
+        << raStar[0] << endl;
+  *fLog << "       decSource, raSource = " << decSource << ",  " 
+        << raSource << endl;
+  *fLog << "       thetaTel, phiTel = " << thetaTel << ",  " 
+        << phiTel << endl;
+  *fLog << "       xStar, yStar = " << xStar[0] << ",  " 
+        << yStar[0] << endl;
+  */
+
+  // the units are assumed to be radians for theta, phi, dec and ra
+  //            and                   mm for f, x and y
+
+
+  // calculate rotation angle alpha of sky image in camera 
+  // (see TDAS 00-11, eqs. (18) and (20))
+  // a1 = cos(Lat), a3 = -sin(Lat), where Lat is the geographical latitude of La Palma
+  Double_t a1 =  0.876627;
+  Double_t a3 = -0.481171;
+
+  Double_t denom =  1./ sqrt( sin(thetaTel)*sin(phiTel) * sin(thetaTel)*sin(phiTel) +
+			      ( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) ) * 
+                              ( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) )   );
+  Double_t cosal = - (a3 * sin(thetaTel) + a1 * cos(thetaTel) * cos(phiTel)) * denom;
+  Double_t sinal =    a1 * sin(phiTel) * denom;
+
+  *fLog << "old thetaTel, phiTel, cosal, sinal = " << thetaTel << ",  "
+        << phiTel << ",  " << cosal << ",  " << sinal << endl;
+
+
+  fObservatory->RotationAngle(thetaTel, phiTel, sinal, cosal);
+
+  *fLog << "new thetaTel, phiTel, cosal, sinal = " << thetaTel << ",  "
+        << phiTel << ",  " << cosal << ",  " << sinal << endl;
+
+
+  // calculate coordinates of source in system B (see TDAS 00-11, eqs. (2))
+  // note that right ascension and hour angle go into opposite directions
+  Double_t xB0 =  cos(decSource) * cos(-raSource);
+  Double_t yB0 =  cos(decSource) * sin(-raSource);
+  Double_t zB0 = -sin(decSource);
+
+  //*fLog << "xB0, yB0, zB0 = " << xB0 << ",  " << yB0 << ",  "
+  //      << zB0 << endl;
+
+  //-----------------------------------------------------
+  // loop over stars
+  Double_t sumx  = 0.0;
+  Double_t sumy  = 0.0;
+  Double_t sumwx = 0.0;
+  Double_t sumwy = 0.0;
+
+  for (Int_t i=0; i<decStar.GetSize(); i++)
+  {
+    // calculate weights
+    Double_t weightx = 1.0 / (dxStar[i]*dxStar[i]);
+    Double_t weighty = 1.0 / (dyStar[i]*dyStar[i]);
+    sumwx += weightx;
+    sumwy += weighty;
+
+    //*fLog << "weightx, weighty = " << weightx << ",  " << weighty << endl;
+
+    // calculate coordinates of star in system B (see TDAS 00-11, eqs. (2))
+    // note that right ascension and hour angle go into opposite directions
+    Double_t xB  =  cos(decStar[i]) * cos(-raStar[i]);
+    Double_t yB  =  cos(decStar[i]) * sin(-raStar[i]);
+    Double_t zB  = -sin(decStar[i]);
+
+
+    //*fLog << "xB, yB, zB = " << xB << ",  " << yB << ",  "
+    //    << zB << endl;
+
+ 
+    // calculate coordinates of star in a system with the basis vectors e1, e2, e3
+    // where  e1 is in the direction (r0 x a)
+    //        e2 is in the direction (e1 x r0)
+    //   and  e3 is in the direction -r0;
+    // r0 is the direction to the source
+    // and a is the earth rotation axis (pointing to the celestial north pole)
+    // 
+    Double_t x = (-xB*yB0 + xB0*yB) / sqrt( xB0*xB0 + yB0*yB0 );
+    Double_t y = ( xB*xB0*zB0 + yB*yB0*zB0 - zB*(xB0*xB0 + yB0*yB0) ) 
+                                    / sqrt( xB0*xB0 + yB0*yB0 );
+    Double_t z = -(xB*xB0 + yB*yB0 + zB*zB0);
+
+    //*fLog << "x, y, z = " << x << ",  " << y << ",  "
+    //    << z << endl;
+
+
+    // calculate coordinates of star in camera
+    Double_t xtilde = -f/z * (cosal*x - sinal*y);
+    Double_t ytilde = -f/z * (sinal*x + cosal*y);
+
+    //*fLog << "i, xtilde, ytile = " << i << " : " << xtilde << ",  " 
+    //      << ytilde << endl;
+
+
+    // calculate coordinates of source in camera
+    // note : in real camera signs are inverted (therefore s = -1.0)
+    Double_t s = -1.0;
+
+    Double_t xs = xStar[i] - s * xtilde;
+    Double_t ys = yStar[i] - s * ytilde;
+
+    *fLog << "i, xs, ys = " << i << " : " << xs << ",  " 
+          << ys << endl;
+
+    sumx += xs * weightx;
+    sumy += ys * weighty;
+  }
+  //-----------------------------------------------------
+
+  xSource  = sumx / sumwx;
+  ySource  = sumy / sumwy;
+  dxSource = 1.0 / sqrt(sumwx);
+  dySource = 1.0 / sqrt(sumwy);
+    
+  /*
+  Int_t run = fRun->GetRunNumber();
+  *fLog << all << "MSourcePosfromStarPos::SourcefromStar; run, xSource, ySource = "
+        << run << " : "
+        << xSource << " +- " << dxSource << ",   " 
+        << ySource << " +- " << dySource << endl; 
+   */
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the source position and put it into MSrcPosCam
+//
+//
+Bool_t MSourcePosfromStarPos::ReInit(MParList *pList)
+{
+  Int_t run = fRun->GetRunNumber();
+  *fLog << all << "MSourcePosfromStarPos::ReInit; run = " << run << endl;
+
+  // temporary solution for MC
+  // copy (theta, phi) from MMcEvt into MPointingPos
+  if (fRun->GetRunType() > 255.5)
+  {
+    *fLog << all << "                     these are MC data" << endl;
+    Double_t thetarad = fMcEvt->GetTelescopeTheta();
+    Double_t phirad   = fMcEvt->GetTelescopePhi();
+    fPointPos->SetLocalPosition(thetarad*kRad2Deg, phirad*kRad2Deg);
+    fPointPos->SetReadyToSave();
+    return kTRUE;    
+  }
+
+  //-------------------------------------------------------------------
+  // search this run in the list 
+  for (Int_t i=0; i<fSize; i++)
+  {
+    if (run == fRunNr[i])
+    {
+      //-----------------------------------------
+      // put the zenith angle into MPointingPos
+
+      Double_t thetarad = fThetaTel[i];
+      Double_t phirad   = fPhiTel[i];
+
+      if (fabs(thetarad*kRad2Deg+1.0) < 0.001)
+        thetarad = fThetaradold;
+      else
+        fThetaradold = thetarad;
+      if (fabs(phirad*kRad2Deg+1.0) < 0.001)
+        phirad = fPhiradold;
+      else
+        fPhiradold = phirad;
+
+      fPointPos->SetLocalPosition(thetarad*kRad2Deg, phirad*kRad2Deg);
+      fPointPos->SetReadyToSave();
+
+      *fLog << all << "theta, phi = " << thetarad*kRad2Deg << ",  "
+            << phirad*kRad2Deg << " deg" << endl;
+       
+      //-----------------------------------------
+      // Get source position and put it into MSrcPosCam
+
+      
+      if (fStars > 0  && fStars == fStarsRead)
+      {
+        TArrayD xStar(fxStar.GetNrows());
+        TArrayD dxStar(fdxStar.GetNrows());
+        TArrayD yStar(fyStar.GetNrows());
+        TArrayD dyStar(fdyStar.GetNrows());
+        for (Int_t j=0; j<fxStar.GetNrows(); j++)
+        {
+          xStar[j]  = fxStar(j, i);
+          dxStar[j] = fdxStar(j, i);
+          yStar[j]  = fyStar(j, i);
+          dyStar[j] = fdyStar(j, i);
+        }
+
+        SourcefromStar( fDistCameraReflector,
+                        fDecStar, fRaStar, fDecSource, fRaSource,
+                        thetarad, phirad,   
+         	        xStar,          yStar,
+		        dxStar,         dyStar,
+		        fxSource,       fySource,
+		        fdxSource,      fdySource);
+      
+        fSrcPos->SetXY(fxSource, fySource);
+
+        fxSourceold = fxSource;
+        fySourceold = fySource;
+
+        *fLog << all << "MSourcePosfromStarPos::ReInit; fRunNr, fxSource, fySource = "
+              << fRunNr[i] << ",  " << fxSource << " +- " << fdxSource 
+              << ",  " << fySource  << " +- "  << fdySource << endl;
+       
+        fSrcPos->SetReadyToSave();       
+      }
+      else
+      {
+        // set default values
+        fxSource = fxSourceold;
+        fySource = fySourceold;
+        fSrcPos->SetXY(fxSource, fySource);
+        fSrcPos->SetReadyToSave();       
+
+
+        *fLog << warn << "MSourcePosfromStarPos::ReInit;  no information on source position for run number = "
+              << run << endl;
+        *fLog << warn << "       set xSource, ySource = " << fxSource << ",  "
+              << fySource << " mm" << endl;
+      }
+      
+
+      return kTRUE;
+    }
+  }
+  //-------------------------------------------------------------------  
+
+    // set default values
+    fxSource = fxSourceold;
+    fySource = fySourceold;
+    fSrcPos->SetXY(fxSource, fySource);
+    fSrcPos->SetReadyToSave();       
+
+    Double_t thetarad = fThetaradold;
+    Double_t phirad = fPhiradold;
+    fPointPos->SetLocalPosition(thetarad*kRad2Deg, phirad*kRad2Deg);
+    fPointPos->SetReadyToSave();
+
+
+    *fLog << warn << "MSourcePosfromStarPos::ReInit;  no information on theta, phi and source position for run number = "
+          << run << endl;
+    *fLog << warn << "       set xSource, ySource = " << fxSource << ",  "
+          << fySource << " mm" << endl;
+    *fLog << warn << "       set theta, phi = " << thetarad*kRad2Deg << ",  "
+          << phirad*kRad2Deg << " deg" << endl;
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MSourcePosfromStarPos::Process()
+{
+  //Int_t run = fRun->GetRunNumber();
+  //*fLog << "MSourcePosfromStarPos::Process; run = " << run << endl;
+    
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MSourcePosfromStarPos::PostProcess()
+{
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// read the data from the ASCII file and store them
+//
+void MSourcePosfromStarPos::FixSize()
+{
+    fSize = fRuns;
+    if (fRuns <= 0)
+      fSize = 1;
+
+    fRunNr.Set(fSize);
+
+    fThetaTel.Set(fSize);
+    fPhiTel.Set(fSize);
+    fdThetaTel.Set(fSize);
+    fdPhiTel.Set(fSize);
+
+    Int_t fRows = fxStar.GetNrows();
+    fxStar.ResizeTo(fRows, fSize);
+    fyStar.ResizeTo(fRows, fSize);
+    fdxStar.ResizeTo(fRows, fSize);
+    fdyStar.ResizeTo(fRows, fSize);
+
+  *fLog << "MSourcePosfromStarPos::FixSize; fix size of arrays : fStars = "
+        << fStars << ",  fRuns = " << fRuns << ",  fRows = " << fRows
+        << ",  fSize = " << fSize << endl;
+  if (fRuns > 0)
+  {
+    *fLog << "       first run : " << fRunNr[0] << ",  last run : "
+          << fRunNr[fRuns-1] << endl;
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// read the data from the ASCII file and store them
+//
+void MSourcePosfromStarPos::ReadData()
+{
+  Float_t val;
+  Int_t   ival;
+
+  // extend size of arrays if necessary
+  if ( fRuns >= fSize )
+  {
+    fSize += 100;
+
+    fRunNr.Set(fSize);
+
+    fThetaTel.Set(fSize);
+    fPhiTel.Set(fSize);
+    fdThetaTel.Set(fSize);
+    fdPhiTel.Set(fSize);
+    
+    Int_t fRows = fxStar.GetNrows();
+    fxStar.ResizeTo(fRows, fSize);
+    fyStar.ResizeTo(fRows, fSize);
+    fdxStar.ResizeTo(fRows, fSize);
+    fdyStar.ResizeTo(fRows, fSize);
+
+    *fLog << "MSourcePosfromStarPos::ReadData(); size of arrays has been increased to (fRows, fSize) = ("
+          << fRows << ",  " << fSize << ")" << endl;
+  }
+
+  //-------------------
+  // read header line
+  //*fIn >> val;
+
+  //*fLog << "val =" << val << endl;
+
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //-------------------
+
+
+
+  while(1)
+  {
+    *fIn >> ival;
+
+    if (fIn->eof())
+      return;
+
+    // run number must be greater than 10000
+    if (TMath::Abs(ival) < 10000)
+    {
+      *fLog << err << "===========> Error when reading file with theta and phi <========="
+	    << "             ival = " << ival << endl;
+    }          
+    else
+      break;
+  }  
+
+  fRuns += 1;
+  //*fLog << fRuns <<"th run : " << ival << endl;  
+
+  fRunNr.AddAt(ival, fRuns-1);
+
+  //*fLog << "check : fRuns, fRunNr[fRuns-1], fRunNr[fRuns] = " << fRuns << ",  "
+  //      << fRunNr[fRuns-1] << ",  " << fRunNr[fRuns] << endl;
+
+ 
+  // read mjdS, hmsS, mjdE, hmsE
+  // these data are present only for ON data (fStars > 0)
+  /*
+  if (fStars > 0)
+  {
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+  }
+  */
+
+  *fIn >> val;
+  fThetaTel.AddAt(val/kRad2Deg, fRuns-1);
+  //*fLog << "val, fThetaTel[fRuns-1] = " << val << ",  "
+  //      << fThetaTel[fRuns-1] << endl;
+
+
+  *fIn >> val;
+  fPhiTel.AddAt(val/kRad2Deg, fRuns-1);
+  //*fLog << "val, fPhiTel[fRuns-1] = " << val << ",  "
+  //      << fPhiTel[fRuns-1] << endl;
+
+
+  //*fIn >> val;
+  //fdThetaTel.AddAt(val/kRad2Deg, fRuns-1);
+  //*fIn >> val;
+  //fdPhiTel.AddAt(val/kRad2Deg, fRuns-1);
+
+  // input is in [deg], convert to [mm]
+
+  //*fLog << "ReadData : fStarsRead = " << fStarsRead << endl;
+
+    for (Int_t i=0; i<fStarsRead; i++)
+    {
+      *fIn >> val;
+      if (i<fStars) fxStar(i, fRuns-1) = val;
+
+      *fIn >> val;
+      if (i<fStars) fyStar(i, fRuns-1) = val;
+
+      //*fIn >> val;
+      // if (i < fStars) fdxStar(i, fRuns-1) = val;
+      if (i < fStars) fdxStar(i, fRuns-1) = 1.0;
+
+      //*fIn >> val;
+      // if (i < fStars) fdyStar(i, fRuns-1) = val;
+      if (i < fStars) fdyStar(i, fRuns-1) = 1.0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain
+//
+Int_t MSourcePosfromStarPos::AddFile(const char *txt, Int_t)
+{
+    TNamed *name = new TNamed(txt, "");
+    fFileNames->AddLast(name);
+
+    *fLog << "MSourcePosfromStarPos::AddFile; add file '" << txt << "'"
+          << endl;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MSourcePosfromStarPos::OpenNextFile()
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existence of a next file to read
+    //
+    TNamed *file = (TNamed*)fFileNames->First();
+    if (!file)
+        return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const char *name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    fIn = new ifstream(expname);
+    delete [] expname;
+
+    const Bool_t noexist = !(*fIn);
+
+
+    if (noexist)
+        *fLog << dbginf << "Cannot open file '" << name << "'" << endl;
+    else
+        *fLog << "Open file: '" << name << "'" << endl;
+
+    //
+    // Remove this file from the list of pending files
+    //
+    fFileNames->Remove(file);
+
+    return !noexist;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MSourcePosfromStarPos.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MSourcePosfromStarPos.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MSourcePosfromStarPos.h	(revision 17960)
@@ -0,0 +1,129 @@
+#ifndef MARS_MSourcePosfromStarPos
+#define MARS_MSourcePosfromStarPos
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MSourcePosfromStarPos                                                   //
+//                                                                         //
+// Task to calculate the position of the source in the camera from
+//      the position of a known star in the camera
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TMatrixD
+#include <TMatrixD.h>
+#endif
+
+class TList;
+class MRawRunHeader;
+class MPointingPos;
+class MMcEvt;
+class MGeomCam;
+class MSrcPosCam;
+class MObservatory;
+
+
+class MSourcePosfromStarPos : public MTask
+{
+ private:
+    const MRawRunHeader *fRun;      //!
+    const MGeomCam      *fGeomCam;  //! Camera Geometry used to calculate Hillas
+    MMcEvt              *fMcEvt;       //!
+    MPointingPos        *fPointPos;       //!
+    MSrcPosCam          *fSrcPos;         //!
+    MObservatory        *fObservatory;    //!
+
+    ifstream    *fIn;             // input file
+    TList       *fFileNames;      // array which contains the \0-terminated file names
+
+    Double_t fMm2Deg;
+    Double_t fDistCameraReflector;
+
+    Int_t   fRuns;                // current number of runs
+    Int_t   fSize;                // final   number of runs
+    Int_t   fStars;               // number of stars
+    Int_t   fStarsRead;           // number of (x,y) pairs to be read
+
+
+    Double_t fDecSource;  // sky coordinates of source
+    Double_t fRaSource;
+    Double_t fxSource;    // estimated position of source in camera
+    Double_t fySource;
+    Double_t fdxSource;
+    Double_t fdySource;
+
+    TArrayI fRunNr;       // list of run numbers
+    TArrayD fThetaTel;    // for each run : theta, phi, ...
+    TArrayD fPhiTel;
+    TArrayD fdThetaTel;
+    TArrayD fdPhiTel;
+
+    TArrayD  fDecStar;   // sky coordinates of stars
+    TArrayD  fRaStar;
+    TMatrixD fxStar;     // for each run : positions of stars in camera (from DC currents)
+    TMatrixD fyStar;
+    TMatrixD fdxStar;
+    TMatrixD fdyStar;
+
+    Double_t fxSourceold;  
+    Double_t fySourceold;
+    Double_t fThetaradold;
+    Double_t fPhiradold;
+
+    Bool_t OpenNextFile();
+    void   ReadData();
+    void   FixSize();
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MSourcePosfromStarPos(const char *name=NULL, const char *title=NULL);
+    ~MSourcePosfromStarPos();
+
+    void SetSourceAndStarPosition(
+	 TString  nameSource,
+	 Double_t decSourceDeg, Double_t decSourceMin, Double_t decSourceSec, 
+         Double_t raSourceHour, Double_t raSourceMin,  Double_t raSourceSec,
+	 TString  nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  );
+
+    Int_t  AddFile(const char *fname, Int_t dummy=-1);
+
+    void AddStar(
+	 TString  nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  );
+
+    void SourcefromStar(Double_t &, 
+      TArrayD  &, TArrayD  &, Double_t &, Double_t &, Double_t &, Double_t &, 
+      TArrayD  &, TArrayD  &, TArrayD  &, TArrayD  &, Double_t &, Double_t &, 
+      Double_t &, Double_t & );
+
+    ClassDef(MSourcePosfromStarPos, 0) // Task to calculate the source position from a star position
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MSupercutsCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MSupercutsCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MSupercutsCalc.cc	(revision 17960)
@@ -0,0 +1,346 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MSupercutsCalc
+//
+//   this class calculates the hadronness for the supercuts
+//   the parameters of the supercuts are taken
+//                  from the container MSupercuts
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSupercutsCalc.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "TFile.h"
+#include "TArrayD.h"
+
+#include "MParList.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MMcEvt.hxx"
+#include "MGeomCam.h"
+#include "MHadronness.h"
+#include "MHMatrix.h"
+#include "MSupercuts.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSupercutsCalc);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+
+MSupercutsCalc::MSupercutsCalc(const char *hilname, 
+                                     const char *hilsrcname, 
+                                     const char *name, const char *title)
+  : fHadronnessName("MHadronness"), fHilName(hilname), fHilSrcName(hilsrcname),
+    fHilExtName("MHillasExt"), fNewParName("MNewImagePar"), 
+    fSuperName("MSupercuts") 
+{
+    fName  = name  ? name  : "MSupercutsCalc";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fMatrix = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MSupercutsCalc::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    fHadronness = (MHadronness*)pList->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadronness)
+    {
+        *fLog << err << fHadronnessName << " [MHadronness] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSuper = (MSupercuts*)pList->FindObject(fSuperName, "MSupercuts");
+    if (!fSuper)
+    {
+        *fLog << err << fSuperName << " [MSupercuts] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fMatrix)
+        return kTRUE;
+
+    //-----------------------------------------------------------
+    fHil = (MHillas*)pList->FindObject(fHilName, "MHillas");
+    if (!fHil)
+    {
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject(fHilExtName, "MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << fHilExtName << " [MHillasExt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << fHilSrcName << " [MHillasSrc] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject(fNewParName, "MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << fNewParName << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculation of upper and lower limits
+//
+Double_t MSupercutsCalc::CtsMCut(const Double_t* a,  Double_t ls, Double_t ct,
+                                    Double_t ls2, Double_t dd2) const
+{
+    // define cut-function
+    //
+    //    dNOMLOGSIZE = 5.0 (=log(150.0)
+    //    dNOMCOSZA   = 1.0
+    //
+    //      a: array of cut parameters
+    //     ls: log(SIZE) - dNOMLOGSIZE
+    //    ls2: ls^2
+    //     ct: Cos(ZA.) - dNOMCOSZA
+    //    dd2: DIST^2
+    const Double_t limit =
+        a[0] + a[1] * dd2 + a[2] * ct  +
+        ls  * (a[3] + a[4] * dd2 + a[5] * ct) +
+        ls2 * (a[6] + a[7] * dd2);
+
+    //*fLog << "MSupercutsCalc::CtsMCut; *a = "
+    //      << *a     << ",  " << *(a+1) << ",  " << *(a+2) << ",  "
+    //      << *(a+3) << ",  " << *(a+4) << ",  " << *(a+5) << ",  "
+    //      << *(a+6) << ",  " << *(a+7) << endl;
+
+    //*fLog << "MSupercutsCalc::CtsMCut; ls, ls2, ct, dd2, limit = " << ls
+    //      << ",  " << ls2 << ",  " << ct << ",  " << dd2 << ",  "
+    //      << limit << endl;
+
+    return limit;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MSupercutsCalc::GetVal(Int_t i) const
+{
+
+    Double_t val = (*fMatrix)[fMap[i]];
+
+
+    //*fLog << "MSupercutsCalc::GetVal; i, fMatrix, fMap, val = "
+    //    << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+void MSupercutsCalc::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta");
+    fMap[1] = fMatrix->AddColumn("MHillas.fWidth");
+    fMap[2] = fMatrix->AddColumn("MHillas.fLength");
+    fMap[3] = fMatrix->AddColumn("MHillas.fSize");
+    fMap[4] = fMatrix->AddColumn("MHillas.fMeanX");
+    fMap[5] = fMatrix->AddColumn("MHillas.fMeanY");
+    fMap[6] = fMatrix->AddColumn("MHillasSrc.fDist");
+    fMap[7] = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+    fMap[8] = fMatrix->AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    fMap[9] = fMatrix->AddColumn("MNewImagePar.fConc");
+    fMap[10]= fMatrix->AddColumn("MNewImagePar.fLeakage1");
+}
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical supercuts 
+// 
+//          set hadronness to 0.25 if cuts are fullfilled
+//                            0.75 otherwise
+//
+Int_t MSupercutsCalc::Process()
+{
+    const Double_t kNomLogSize = 4.1;
+    const Double_t kNomCosZA   = 1.0;
+
+    const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();
+    const Double_t width0  = fMatrix ? GetVal(1) : fHil->GetWidth();
+    const Double_t length0 = fMatrix ? GetVal(2) : fHil->GetLength();
+    const Double_t size    = fMatrix ? GetVal(3) : fHil->GetSize();
+    const Double_t meanx   = fMatrix ? GetVal(4) : fHil->GetMeanX();
+    const Double_t meany   = fMatrix ? GetVal(5) : fHil->GetMeanY();
+    const Double_t dist0   = fMatrix ? GetVal(6) : fHilSrc->GetDist();
+
+    Double_t help;
+    if (!fMatrix)
+      help = TMath::Sign(fHilExt->GetM3Long(), 
+	      		 fHilSrc->GetCosDeltaAlpha());
+    const Double_t asym0   = fMatrix ? GetVal(8) : help;
+    const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+    const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+
+    const Double_t newdist = dist0 * fMm2Deg;
+
+    const Double_t dist2   = meanx*meanx + meany*meany;
+    const Double_t dist    = sqrt(dist2) * fMm2Deg;
+    const Double_t dd2     = dist*dist;
+
+
+    const Double_t dmls    = log(size) - kNomLogSize;
+    const Double_t dmls2   = dmls * dmls;
+
+    const Double_t dmcza   = cos(theta) - kNomCosZA;
+
+    const Double_t length  = length0 * fMm2Deg;
+    const Double_t width   = width0  * fMm2Deg;
+    const Double_t asym    = asym0   * fMm2Deg;
+
+    /*
+    *fLog << "newdist, length, width, asym, dist, conc, leakage = " 
+          << newdist << ",  " << length << ",  " << width << ",  "
+          << asym    << ",  " << dist   << ",  " << conc  << ",  " << leakage
+          << endl;
+  
+    *fLog << "upper cuts in newdist, length, width, asym, dist, conc, leakage = " 
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLengthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLengthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetWidthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetWidthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLeakage1Up(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLeakage1Lo(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << endl;
+    */
+
+
+    if (
+        //dist    < 1.05                                                     &&
+        //newdist < 1.05                                                     &&
+
+        newdist < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        newdist > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        length  < CtsMCut (fSuper->GetLengthUp(), dmls, dmcza, dmls2, dd2) &&
+        length  > CtsMCut (fSuper->GetLengthLo(), dmls, dmcza, dmls2, dd2) &&
+
+        width   < CtsMCut (fSuper->GetWidthUp(),  dmls, dmcza, dmls2, dd2) &&
+        width   > CtsMCut (fSuper->GetWidthLo(),  dmls, dmcza, dmls2, dd2) &&
+
+        asym    < CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) &&
+        asym    > CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        dist    < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        dist    > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        conc    < CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) &&
+        conc    > CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        leakage < CtsMCut (fSuper->GetLeakage1Up(),dmls, dmcza, dmls2, dd2) &&
+        leakage > CtsMCut (fSuper->GetLeakage1Lo(),dmls, dmcza, dmls2, dd2)  ) 
+
+      fHadronness->SetHadronness(0.25);
+    else
+      fHadronness->SetHadronness(0.75);
+
+    //*fLog << "SChadroness = " << fHadronness->GetHadronness() << endl;
+
+    fHadronness->SetReadyToSave();
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysis/MSupercutsCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/MSupercutsCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/MSupercutsCalc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysis/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/manalysis/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysis/Makefile	(revision 17960)
@@ -0,0 +1,51 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Analysis
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mmc -I../mraw -I../mgeom -I../mfilter \
+	   -I../mdata -I../mhbase -I../mhist -I../mgui -I../mimage   \
+           -I../mhistmc -I../mfileio -I../mmain -I../mcalib \
+           -I../msignal -I../mpointing -I../mtools -I../mfbase       \
+           -I../mbadpixels -I../mastro -I../mpedestal
+# mcalib: MGeomApply (MCalibrationCam)
+
+SRCFILES = MGeomApply.cc \
+           MCameraData.cc \
+           MParameterCalc.cc \
+           MEnergyEstimate.cc \
+           MMatrixLoop.cc \
+           MMultiDimDistCalc.cc \
+           MEventRate.cc \
+           MEventRateCalc.cc \
+           MMcCalibrationUpdate.cc
+
+#           MMcTriggerLvl2.cc \
+#           MMcTriggerLvl2Calc.cc \
+#           MCompProbCalc.cc \
+
+############################################################
+
+all:  $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
Index: branches/Mars_McMismatchStudy/manalysisct1/AnalysisCT1Incl.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/AnalysisCT1Incl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/AnalysisCT1Incl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/manalysisct1/AnalysisCT1LinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/AnalysisCT1LinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/AnalysisCT1LinkDef.h	(revision 17960)
@@ -0,0 +1,18 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+// Doesn't compile: Please replace MBlindPixels by MBadPixel*
+//#pragma link C++ class MCT1PadSchweizer+;
+//#pragma link C++ class MCT1PadONOFF+;
+
+#pragma link C++ class MCT1PointingCorrCalc+;
+#pragma link C++ class MCT1Supercuts+;
+#pragma link C++ class MCT1SupercutsCalc+;
+#pragma link C++ class MCT1FindSupercuts+;
+#pragma link C++ class MCT1ReadPreProc+;
+#pragma link C++ class MCT1ReadAscii+;
+
+#endif
Index: branches/Mars_McMismatchStudy/manalysisct1/MCT1FindSupercuts.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1FindSupercuts.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1FindSupercuts.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1FindSupercuts.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1FindSupercuts.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1FindSupercuts.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1PadONOFF.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1PadONOFF.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1PadONOFF.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1PadONOFF.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1PadONOFF.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1PadONOFF.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1PadSchweizer.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1PadSchweizer.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1PadSchweizer.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1PadSchweizer.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1PadSchweizer.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1PadSchweizer.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1PointingCorrCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1PointingCorrCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1PointingCorrCalc.cc	(revision 17960)
@@ -0,0 +1,218 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  03/2003 <mailto:wittek@mppmu.mpg.de>
+!              Nadia Tonello    05/2003 <mailto:tonello@mppmu.mpg.de>
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MCT1PointingCorrCalc                                                   //
+//                                                                         //
+//  This is a task to do the CT1 pointing correction.                      // 
+//                                                                         //
+//  NT: You can correct the Mkn421 data (default setting), or the 1ES1959  //
+//      data.                                                              // 
+//      To change to the correction needed for 1ES1959,  you have to call  //
+//      the member funcion: SetPointedSource                               //
+//                                                                         //
+//  Example:                                                               //
+//      MCT1PointingCorrCalc correct;                                      //
+//      correct.SetPointedSource(MCT1PointingCorrectionCalc::K1959)        //
+//                                                                         // 
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MCT1PointingCorrCalc.h"
+
+#include "MParList.h"
+
+#include "MSrcPosCam.h"
+#include "MGeomCam.h"
+#include "MParameters.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCT1PointingCorrCalc);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCT1PointingCorrCalc::MCT1PointingCorrCalc(const char *srcname,
+                                           const char *name, const char *title)
+  : fSrcName(srcname), fPoiSource(k421)
+{
+    fName  = name  ? name  : "MCT1PointingCorrCalc";
+    fTitle = title ? title : "Task to do the CT1 pointing correction";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MCT1PointingCorrCalc::PreProcess(MParList *pList)
+{
+    MGeomCam *geom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << GetDescriptor() << ": No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+    }
+
+   fHourAngle = (MParameterD*)pList->FindObject("HourAngle", "MParameterD");
+    if (!fHourAngle)
+    {
+        *fLog << err << "HourAngle [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject(fSrcName, "MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << fSrcName << " [MSrcPosCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//Implemented Daniel Kranich's pointing correction for Mkn421 (2001 data)
+//
+
+void MCT1PointingCorrCalc::PointCorr421()
+{
+   //*fLog << "MCT1PointingCorrCalc::Process; fhourangle = " 
+   //      << fhourangle << endl;
+
+   Float_t fhourangle = fHourAngle->GetVal();
+
+   Float_t cx = -0.05132 - 0.001064 * fhourangle 
+                         - 3.530e-6 * fhourangle * fhourangle;
+   cx /= fMm2Deg;
+
+   Float_t cy = -0.04883 - 0.0003175* fhourangle
+                         - 2.165e-5 * fhourangle * fhourangle;
+   cy /= fMm2Deg;
+
+   fSrcPos->SetXY(cx, cy);
+
+   //*fLog << "MCT1PointingCorrCal::Process; fhourangle, cx, cy, fMm2Deg = "
+   //      << fhourangle << ",  " << cx << ",  " << cy << ",  " 
+   //      << fMm2Deg << endl;
+
+   fSrcPos->SetReadyToSave();
+   return;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// NT :Implemente Daniel Kranich's pointing correction for 1ES1959 (2002 data)
+
+void MCT1PointingCorrCalc::PointCorr1959()
+{
+   //*fLog << "MCT1PointingCorrCalc::Process; fhourangle = " 
+   //      << fhourangle << endl;
+
+   Float_t fhourangle = fHourAngle->GetVal();
+
+   Float_t cx = -0.086 - 0.00091 * fhourangle ;
+   cx /= fMm2Deg;
+
+   Float_t cy = -0.083 - 0.001 * fhourangle ;
+   cy /= fMm2Deg;
+
+   fSrcPos->SetXY(cx, cy);
+
+   //*fLog << "MCT1PointingCorrCal::Process; fhourangle, cx, cy, fMm2Deg = "
+   //      << fhourangle << ",  " << cx << ",  " << cy << ",  " 
+   //      << fMm2Deg << endl;
+
+   fSrcPos->SetReadyToSave();
+   return;
+
+}
+// --------------------------------------------------------------------------
+//
+// Do the pointing correction
+//
+Int_t MCT1PointingCorrCalc::Process()
+{
+   // fhourangle is the hour angle [degrees]
+   // (cx, cy) is the source position in the camera [mm]
+   //
+   switch (fPoiSource)
+    {
+    case k421:
+        PointCorr421();
+    case k1959:
+        PointCorr1959();
+    }  
+   return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysisct1/MCT1PointingCorrCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1PointingCorrCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1PointingCorrCalc.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MCT1PointingCorrCalc
+#define MARS_MCT1PointingCorrCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCT1PointingCorrCalc                                                    //
+//                                                                         //
+// Task to do the pointing correction                                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MSrcPosCam;
+class MParameterD;
+
+
+class MCT1PointingCorrCalc : public MTask
+{
+public:
+    typedef enum {
+        k421,
+        k1959
+    } PointedSource_t;
+
+private:
+
+    MSrcPosCam   *fSrcPos;
+    TString       fSrcName;
+    MParameterD  *fHourAngle;
+
+    PointedSource_t fPoiSource;
+    Float_t       fMm2Deg;
+
+    void PointCorr421();
+    void PointCorr1959();
+
+public:
+
+    MCT1PointingCorrCalc(const char *srcname="MSrcPosCam",
+                         const char *name=NULL, const char *title=NULL);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    void SetPointedSource(PointedSource_t s) { fPoiSource = s; }
+ 
+    ClassDef(MCT1PointingCorrCalc, 0)   // Task to do the CT1 pointing correction for Mkn421 2001 data or 1ES1959 2002 data
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadAscii.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadAscii.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadAscii.cc	(revision 17960)
@@ -0,0 +1,304 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCT1ReadAscii
+//
+// Reads a ascii file with CT1 data. The file description and some example
+// files can be found on the Magic homepage.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1ReadAscii.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TList.h>
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+ClassImp(MCT1ReadAscii);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates an array which stores the file names of
+// the files which should be read. If a filename is given it is added
+// to the list.
+//
+MCT1ReadAscii::MCT1ReadAscii(const char *fname,
+			     const char *name, 
+                             const char *title)
+    : fIn(NULL)
+{
+    fName  = name  ? name  : "MCT1ReadAscii";
+    fTitle = title ? title : "Task to loop over events in CT1 ascii file";
+
+    //
+    // remember file name for opening the file in the preprocessor
+    //
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MCT1ReadAscii::~MCT1ReadAscii()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain
+//
+Int_t MCT1ReadAscii::AddFile(const char *txt, Int_t)
+{
+    TNamed *name = new TNamed(txt, "");
+    fFileNames->AddLast(name);
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MCT1ReadAscii::OpenNextFile()
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existance of a next file to read
+    //
+    TNamed *file = (TNamed*)fFileNames->First();
+    if (!file)
+        return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const char *name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    fIn = new ifstream(expname);
+
+    const Bool_t noexist = !(*fIn);
+    if (noexist)
+    {
+        *fLog << err << "Cannot open file " << expname << ": ";
+        *fLog << strerror(errno) << endl;
+    }
+    else
+        *fLog << inf << "Open file: '" << name << "'" << endl;
+
+    delete [] expname;
+
+    //
+    // Remove this file from the list of pending files
+    //
+    fFileNames->Remove(file);
+
+    return !noexist;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the first file in the list. Check for the output containers or create
+// them if they don't exist.
+//
+// Initialize the size of the MPedPhotCam container to 127 pixels (CT1 camera)
+//
+Int_t MCT1ReadAscii::PreProcess(MParList *pList)
+{
+    //
+    // Preprocessing
+    //
+
+    //
+    // Try to open at least one (the first) file
+    //
+    if (!OpenNextFile())
+        return kFALSE;
+
+    //
+    //  look for the MCerPhotEvt class in the plist
+    //
+    fNphot = (MCerPhotEvt*)pList->FindCreateObj("MCerPhotEvt");
+    if (!fNphot)
+        return kFALSE;
+
+    //
+    //  look for the pedestal class in the plist
+    //
+    fPedest = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+    if (!fPedest)
+        return kFALSE;
+
+    MGeomCam *geom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fPedest->Init(*geom);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read apedestal entry (line) from the file
+//
+void MCT1ReadAscii::ReadPedestals()
+{
+    //
+    // skip the next 4 values
+    //
+    Float_t val;
+
+    *fIn >> val;
+    *fIn >> val;
+    *fIn >> val;
+    *fIn >> val;
+
+    //
+    //    read in the next 127 numbers as the pedestals
+    //
+    for (Int_t i = 0; i<127; i++)
+    {
+        *fIn >> val;
+
+        if (val>0)
+            (*fPedest)[i].Set(0, val);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a data entry (line) from the file
+//
+void MCT1ReadAscii::ReadData()
+{
+    //
+    // five unsused numbers
+    //
+    Int_t val;
+
+    *fIn >> val;   // ener
+    *fIn >> val;   // zenang
+    *fIn >> val;   // sec1
+    *fIn >> val;   // sec2
+
+    //
+    // read in the number of cerenkov photons and add the 'new' pixel
+    // too the list with it's id, number of photons and error
+    //
+    for (Int_t i = 0; i<127; i++ )
+    {
+        Float_t nphot;
+
+        *fIn >> nphot;
+
+        if (nphot > 0.0)
+            fNphot->AddPixel(i, nphot, (*fPedest)[i].GetRms());
+    }
+    fNphot->FixSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the event number and depending on this number decide if
+// pedestals or event data has to be read.
+//
+// If the end of the file is reached try to open the next in the list. If
+// there is now next file stop the eventloop.
+//
+Int_t MCT1ReadAscii::Process()
+{
+    //
+    // FIXME. This function should switch between reading pedestals and
+    // reading event data by the 'switch entry'.
+    // After reading it should set the InputStreamID correctly.
+    // (should use MPedPhotCam )
+    //
+ 
+    //
+    // read in the event nr
+    //
+    Int_t evtnr;
+    *fIn >> evtnr;
+
+    //
+    // check if we are done. Try to open the next file in chain.
+    // If it was possible start reading. If not break the event loop
+    //
+    if (fIn->eof())
+        return OpenNextFile() ? kCONTINUE : kFALSE;
+
+    //
+    // if the first number is negativ this is a pedestal line:
+    // read in pedestals
+    //
+    // FIXME! Set InputStreamID
+
+    if (evtnr < 0)
+    {
+        ReadPedestals();
+        return kCONTINUE;
+    }
+
+    ReadData();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadAscii.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadAscii.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadAscii.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadPreProc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadPreProc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadPreProc.cc	(revision 17960)
@@ -0,0 +1,1171 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCT1ReadPreProc
+//
+// Reads a output file of the CT1 preproc.
+//
+// Implements usage of a selector (see MRead) Use such a filter to skip
+// events before reading! But never use a filter which needs read data
+// as input...
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//    MCerPhotEvt     the data container for all data.
+//    MPedPhotCam     CT1 pedestals
+//    MMcEvt          monte carlo data container for MC files
+//    MMcTrig         mc data container for trigger information
+//    MSrcPosCam      source position in the camera
+//    MBadPixelsCam   Array holding blind pixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1ReadPreProc.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TList.h>
+#include <TSystem.h>
+#include <TRandom3.h>
+
+#define LINUX
+#define HISTO void
+#define HBOOK_FILE int
+#include "defines.h"
+#include "structures.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MFilter.h"
+
+#include "MParList.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRawRunHeader.h"
+#include "MTaskList.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+#include "MBinning.h"
+
+#include "MParameters.h"
+
+ClassImp(MCT1ReadPreProc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates an array which stores the file names of
+// the files which should be read. If a filename is given it is added
+// to the list.
+//
+MCT1ReadPreProc::MCT1ReadPreProc(const char *fname, const char *name,
+                                 const char *title) : fIn(NULL), fEntries(0)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Reads a CT1 preproc data file";
+
+    //
+    // remember file name for opening the file in the preprocessor
+    //
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MCT1ReadPreProc::~MCT1ReadPreProc()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain
+//
+Int_t MCT1ReadPreProc::AddFile(const char *txt, int)
+{
+    const char *name = gSystem->ExpandPathName(txt);
+
+    TString fname(name);
+    delete [] name;
+
+    if (!CheckHeader(fname))
+    {
+        *fLog << warn << "WARNING - Problem reading header... ignored." << endl;
+        return 0;
+    }
+
+    const Int_t n = GetNumEvents(fname);
+    if (n==0)
+    {
+        *fLog << warn << "WARNING - File contains no data... ignored." << endl;
+        return 0;
+    }
+
+    fEntries += n;
+
+    *fLog << inf << "File " << txt << " contains " << n << " events (Total=" << fEntries << ")" << endl;
+
+    fFileNames->AddLast(new TNamed(txt, ""));
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print data from the header to the screen and analyse the header data,
+// means store and copy the needed data into Mars structures and
+// data members
+//
+void MCT1ReadPreProc::ProcessRunHeader(const struct outputpars &outpars)
+{
+    if (outpars.inumpixels != iMAXNUMPIX)
+        *fLog << warn << "WARNING! File doesn't contain " << iMAXNUMPIX << " Pixels... maybe corrupt." << endl;
+
+    fNumEventsInRun = 0;
+
+    //
+    // ------------------- Output some stuff -----------------------
+    //
+
+    // int     itelescope;       // number of the CT which took the data
+    *fLog << inf << "Telescope: CT" << outpars.itelescope;
+
+    // float   flongitude_deg;   // longitude (counted positive towards West) of CT position */
+    // float   flatitude_deg;    // latitude (counted positive towards North) of CT position */
+    *fLog << " located @ Longitude=" << outpars.flongitude_deg;
+    *fLog << "deg  Latitude=" << outpars.flatitude_deg << "deg" << endl;
+
+    // int     irunnum;          // run number (from parameters file)
+    fRawRunHeader->SetRunNumber(outpars.irunnum);
+    fRawRunHeader->SetReadyToSave();
+
+    // enum    onoroff {NEITHER_ON_NOR_OFF, OFF_SOURCE, ON_SOURCE} eruntype; // runtype
+    *fLog << "Run:       #" << outpars.irunnum << "  (";
+    switch (outpars.eruntype)
+    {
+    case NEITHER_ON_NOR_OFF: *fLog << "unknown";    break;
+    case OFF_SOURCE:         *fLog << "off-source"; break;
+    case ON_SOURCE:          *fLog << "on-source";  break;
+    default:                 *fLog << (int)outpars.eruntype; break;
+    }
+    *fLog << ", ";
+    switch (outpars.etrackmode)
+    {
+    case NORMAL:  *fLog << "normal tracking";  break;
+    case REVERSE: *fLog << "reverse tracking"; break;
+    case DUNNO:   *fLog << "unknown tracking"; break;
+    default:      *fLog << (int)outpars.etrackmode; break;
+    }
+    *fLog << ")" << endl;
+
+    //double  dsourcera_hours;  // right ascension of observed source in hours
+    //double  dsourcedec_deg;   // declination of observed source in degrees
+    *fLog << "Source:    RA=" << outpars.dsourcera_hours << "h  DEC=";
+    *fLog << outpars.dsourcedec_deg << "deg" << endl;
+
+    //int     inummuonpixels;   // number of pixels in the muon shield
+    //int     inumcointdcs;     // number of coincidence tdcs recorded in the runfile
+    //float   fpixdiameter_deg; // smallest pixel diameter (degrees) (from parameters file) */
+
+    // enum    axes {RA, DEC, ALT, AZ} ese1_is; // name of the axis to which shaft encoder 1 is attached (implies the type of mount)
+    *fLog << "Shaftencoder 1 @ ";
+    switch (outpars.ese1_is)
+    {
+    case RA:  *fLog << "RA";  break;
+    case DEC: *fLog << "DEC"; break;
+    case ALT: *fLog << "ALT"; break;
+    case AZ:  *fLog << "AZ";  break;
+    default:  *fLog << (int)outpars.ese1_is; break;
+    }
+    *fLog << endl;
+
+    // int     isezeropos[2];       // zero position of shaftencoders 1 and 2 (from parameters file)
+    *fLog << "SE Zero:   SE(1)=" << outpars.isezeropos[0] << "  ";
+    *fLog << "SE(2)=" << outpars.isezeropos[1] << endl;
+
+    // int     iaz_rev_track_corr;  // correction for the azimuth shaft encoder (ALT/AZ mount only) in reverse tracking mode
+    // int     ialt_rev_track_corr; // correction for the altitude shaft encoder (ALT/AZ mount only) in reverse tracking mode
+    *fLog << "Reverse tracking corrections: SE(az)=" << outpars.iaz_rev_track_corr;
+    *fLog << "  SE(alt)=" << outpars.ialt_rev_track_corr << endl;
+
+    // float   fbendingcorr;        // bending correction factor (ALT/AZ mount only)
+    // float   fextinction;         // atmospheric extinction (typically taken from the Carlsberg Meridian Circle data)
+    *fLog << "Bending: Correction factor=" << outpars.fbendingcorr << "  ";
+    *fLog << "Extinction=" << outpars.fextinction << endl;
+
+    // Boolean bdontusepix[iMAXNUMPIX]; // bdontusepix is set true if the pixel should not be used in image analysis, otherwise it is true;
+
+    fBlinds->Clear();
+    *fLog << "Don't use pixels: ";
+    for (int i=0; i<iMAXNUMPIX; i++)
+        if (outpars.bdontusepix[i])
+        {
+            *fLog << i << " ";
+            (*fBlinds)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+        }
+    *fLog << endl;
+
+    *fLog << "Exclude pixels: ";
+    // Boolean bexcludepix[iMAXNUMPIX];
+    for (int i=0; i<iMAXNUMPIX; i++)
+        if (outpars.bexcludepix[i])
+        {
+            *fLog << i << " ";
+            (*fBlinds)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+        }
+    *fLog << endl;
+
+    // save blind pixels for all events of this run
+    fBlnd.Set(iMAXNUMPIX);
+    for (int i=0; i<iMAXNUMPIX; i++)
+        fBlnd[i] = (*fBlinds)[i].IsBad() ? 1 : 0;
+
+    fBlinds->SetReadyToSave();
+
+    /* bexcludepix[] is set TRUE (== exclude from pedestal, Laser
+     * calibration and the further analysis) when the Mean value
+     * of a pixel inside a pedestal Run is larger than 50 or ( || )
+     * if the pedestal RMS value of this pixel is larger than 5.0
+     * This is reflected in the (new for versions >= 0.4)
+     * variable "pixonoff" in the ntuple written by preproc:
+     * preproc.nt.hbook
+     *
+     * When the pixel is excluded by the user it will get a -2 otherwise
+     * pixonoff = 0.
+     * Additive to this a -1 is added when preproc excludes the pixel
+     * for a given Run. So the actual value tells you whether you caught
+     * it already by hand or not.
+     *
+     * A plot of pixonoff may also be handy to tell you the status of your
+     * ADC equipment. */
+
+    // float   fphotoel_per_adccnt[iMAXNUMPIX]; // conversion factors for the pixel signals */
+    /*
+    float padc = outpars.fphotoel_per_adccnt[0];
+    *fLog << "Phe/ADC (pixel 0): " << padc << endl;
+    for (int i=0; i<iMAXNUMPIX; i++)
+        *fLog << outpars.fphotoel_per_adccnt[i] << " ";
+    *fLog << endl;
+    */
+    /*
+     --- USEFULL? NEEDED? ---
+     int     irubminusutc_usecs;              // difference between rubidium clock and UTC in microseconds
+     int     isum_thresh_phot;                // threshold for the total sum of photoelectrons filter
+     int     i2out_thresh_phot;               // threshold for the two-pixels-out-of-all software
+     int     imuoncut_thresh_adccnt[iMAXNUMMUONPIX]; // thresholds for the muon cut
+     Boolean bmuon_suppression;               // "Dolby" noise reduction flag
+     float   ftolerated_pointerror_deg;       // maximum tolerated pointing error in the position
+     */
+
+    // float fxpointcorr_deg; // pointing correction (to be added along the camera x axis) e.g. from point run */
+    // float fypointcorr_deg; // pointing correction (to be added along the camera y axis) e.g. from point run */
+    *fLog << "Pointing correction: dx=" << outpars.fxpointcorr_deg << "deg  ";
+    *fLog << "dy=" << outpars.fypointcorr_deg << "deg" << endl;
+
+    // FIXME? Is x-y echanged between Mars CT1 geometry and CT1 definition?
+    fSrcPos->SetXY(-outpars.fypointcorr_deg/fGeom->GetConvMm2Deg(),
+                   -outpars.fxpointcorr_deg/fGeom->GetConvMm2Deg());
+    fSrcPos->SetReadyToSave();
+
+    /*
+     --- USEFULL? NEEDED? ---
+     float   fcamera_align_angle_deg;         // the angle between the camera y-axis and the meridian when a culminating object is observed (defined counter-clockwise looking at the sky)
+     int     iratecalc_numevents_odd;         // number of events used in the rate calculation (must be odd)
+     int     inumpedfile;                     // number of the pedestal file used
+     int     inumpedrun;                      // number of the pedestal run used in the file (starting at 0)
+     int     inumcalfile;                     // number of the calibration file used
+     int     inumlaserrun;                    // number of the laserrun used in the file (starting at 0)
+     int     inumtellogfile;                  // number of the TelLog file to be used
+     int     inumtellogrun;                   // number of the tellog entry (Runnumber) used from the log file
+     int     imcparticle;                     // CORSIKA-coded Monte Carlo particle type.
+    */
+
+    // ----- preprocessing results -----
+
+    // int     istart_mjdate_day;                 // MJD of run start (first event) */
+    // int     iend_mjdate_day;                   // MJD of run end (last event) */
+    // int     irunduration_secs;                 // difference between start and end time (secs) */
+    *fLog << "Run Time: From " << outpars.istart_mjdate_day << " to ";
+    *fLog << outpars.iend_mjdate_day << " (MJD),  Duration=";
+    *fLog << outpars.irunduration_secs/3600 << "h";
+    *fLog << (outpars.irunduration_secs/60)%60 << "m";
+    *fLog << outpars.irunduration_secs%60 << "s" << endl;
+    fRawRunHeader->SetRunTime(outpars.istart_mjdate_day, outpars.iend_mjdate_day);
+    fRawRunHeader->SetReadyToSave();
+
+    /*
+     --- USEFULL? NEEDED? ---
+     int     iproc_mjdate;                      // MJD of data processing (i.e. creation of this file)
+     */
+
+    // int     iproc_evts;                        // number of events processed */
+    *fLog << "Number of processed events: " << outpars.iproc_evts << endl;
+
+    // --- USEFULL? NEEDED? ---
+    // double  dactual_sourcera_hours;            // for off runs: the false source (that should have been) observed */
+
+    // float   frms_pedsig_phot[iMAXNUMPIX];      // standard deviation of the calibrated signals from the pedestal run */
+    fPedest->Init(*fGeom);
+
+    fPedRMS.Set(iMAXNUMPIX);
+
+    *fLog << "PedestalRMS : ";
+    for (Int_t i=0; i<iMAXNUMPIX; i++)
+    {
+        (*fPedest)[i].Set(0, outpars.frms_pedsig_phot[i]);
+        *fLog << outpars.frms_pedsig_phot[i] << " "; 
+        fPedRMS[i] = outpars.frms_pedsig_phot[i];
+    }
+    *fLog << endl;
+
+    fPedest->SetReadyToSave();
+
+    // Used to communicate the mean over all pixels
+    // pedestal RMS into the Runs NTuple, as it might
+    // be used for e.g. quality cuts.
+    // float   fpedrms_mean;
+    *fLog << "Pedestal RMS: " << outpars.fpedrms_mean << endl;
+
+    // The average current over the active pixels
+    // for this run. This is done separately for
+    // ON and OF runs.
+    //float   fcurrent_mean;
+
+    // enum eERRORTOLERANCE {CAUTIOUS=0, GOODPHYSICS, TANK} eerrortolerance;
+    /* 0 == "cautious", exits on any reason (but tells in
+     * the .err file,
+     * 1 == "goodphysics", exits when physics could be affected
+     * by the error,
+     * 2 == "tank", never exits except on coredumps and when
+     * all files have been processed. Do not use such files for
+     * physics analysis!
+     *
+     * NOTE: the capital letter words are the enums, the small letter
+     * words must be used inside the parameter file. */
+
+    // enum eMCTRIGGERFLAG {ALL=0, FLAG, NOFLAG} emctriggerflag;
+    /* all: all events which survive the filter are written to the
+     *      events NTuple.
+     * flag: When Dorota's triggerflag is set to 1 for a particular
+     *       event, it shall be written to the output. All others shall
+     *       just be disregarded. (Default)
+     * noflag: Opposite of 'flag': only events with triggerflag = 0 shall
+     *         be treated further. */
+
+    *fLog << "Particle Id #" << outpars.imcparticle << endl;
+    *fLog << "Right Ascension: " << outpars.dsourcera_hours << "h" << endl;
+    *fLog << "Declination: " << outpars.dsourcedec_deg << "deg" << endl;
+
+    // Next statement commented out because bmontecarlo was set wrongly
+    //fIsMcFile = outpars.bmontecarlo==TRUE;
+    fIsMcFile = (outpars.dsourcera_hours==0 && outpars.dsourcedec_deg==0 &&
+                 outpars.imcparticle != 0);
+
+    if (fIsMcFile != (outpars.bmontecarlo==TRUE))
+    {
+        *fLog << "File tells you that it is a ";
+        *fLog << (outpars.bmontecarlo ? "Monte Carlo" : "Real Data");
+        *fLog << " file." << endl;
+    }
+
+    *fLog << "File detected as a ";
+    *fLog << (fIsMcFile ? "Monte Carlo" : "Real Data");
+    *fLog << " file." << endl;
+    *fLog << " " << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read CT1 PreProc File Header:
+//
+Int_t MCT1ReadPreProc::ReadRunHeader()
+{
+    char cheadertitle[iHEADERTITLELENGTH];
+    fIn->read(cheadertitle, iHEADERTITLELENGTH);
+
+    TString s = cheadertitle;
+    TString m = cTITLE_TEMPLATE;
+
+    if (!s.BeginsWith(m(0, m.First('%'))))
+        return kFALSE;
+
+    *fLog << cheadertitle << flush;
+
+    // cTITLE_TEMPLATE "PREPROC V%f/S%f CT %d RUN %d %d PROCMJD %d\n"
+    struct outputpars outpars;
+
+    int dummy;
+
+    Float_t fpreprocversion, structversion;
+    sscanf(cheadertitle, cTITLE_TEMPLATE,
+           &fpreprocversion,    &structversion,
+           &outpars.itelescope, &outpars.irunnum,
+           &dummy/*&outpars.eruntype*/, &outpars.iproc_mjdate);
+
+    if (fpreprocversion<0.6)
+    {
+        *fLog << err << "Sorry, only files from PreProc V0.6 and newer are supported." << endl;
+        return kFALSE;
+    }
+
+    //
+    // This is a stupid way of getting rid of numerical uncertanties when
+    // comparing floating point numbers (Argh...)
+    //
+    TString s1 = Form("%.2f", structversion);
+    TString s2 = Form("%.2f", STRUCT_VERSION);
+
+    if (s1 != s2)
+    {
+        *fLog << warn << "WARNING: Version of C-structures of file (V";
+        *fLog << s1 << ") not identical with current structures (V";
+        *fLog << s2 << ")" << endl;
+    }
+
+    fIn->read((char*)&outpars, sizeof(struct outputpars));
+
+    ProcessRunHeader(outpars);
+
+    //rwagner: ReInit whenever new run commences
+    // rc==-1 means: ReInit didn't work out
+
+    MTaskList *tlist = (MTaskList*)fParList->FindCreateObj("MTaskList");
+    if (!tlist)
+        return -1;
+
+    if (!tlist->ReInit(fParList))
+        return -1;
+
+    return kTRUE;
+}
+
+Int_t MCT1ReadPreProc::ReadRunFooter()
+{
+    char cheadertitle[iHEADERTITLELENGTH];
+    fIn->read(cheadertitle, iHEADERTITLELENGTH);
+    /*
+     sscanf(cheadertitle, cEND_EVENTS_TEMPLATE,
+     &filterres.ifilter_passed_evts);
+     */
+
+    TString s = cheadertitle;
+    TString m = cEND_EVENTS_TEMPLATE;
+    Int_t p = m.First('%');
+
+
+    if (!s.BeginsWith(m(0,p)))
+    {
+        fIn->seekg(-iHEADERTITLELENGTH, ios::cur);
+        return 0;
+    }
+
+    *fLog << inf << cheadertitle << flush;
+
+    struct filterresults filterres;
+    fIn->read((char*)&filterres, sizeof(struct filterresults));
+    /*
+     int   imax_alt_arcs;            // maximum altitude reached during the run
+     int   iaz_at_max_alt_arcs;      // azimuth at the time the max. alt. was reached
+     int   itimeaverage_alt_arcs;    // altitude averaged over the runtime
+     int   icoord_inconsist_evts;    // number of events with time-coordinate inconsistency in this run
+     int   ifilter_passed_evts;      // number of events which passed the filter
+     int   imuon_fail_evts;          // number of events rejected as muons (other filters passed)
+     int   i2out_fail_evts;          // number of events which failed in the two out of all pixels software trigger
+     int   imuon_and_2out_fail_evts; // number of events failing in both muon and 2out filter
+     int   isum_fail_evts;           // number of events which failed the sum-of-all-calibrated ADC counts filter
+     int   isum_and_muon_fail_evts;  // number of events which failed in both the sum and the muon filter
+     int   isum_and_2out_fail_evts;  // number of events which failed in both the sum and the 2out filter
+     int   iall_filters_fail_evts;   // number of events which failed in all filters
+     float favg_event_rate_hz;       // average rate before filtering
+     float fstddev_event_rate_hz;    // standard deviation of the rate before filtering
+     */
+
+    if (fNumEventsInRun!=(UInt_t)filterres.ifilter_passed_evts)
+    {
+        *fLog << err << "ERROR! Number of events in run (" << (UInt_t)filterres.ifilter_passed_evts;
+        *fLog << ") doesn't match number of read events (";
+        *fLog << fNumEventsInRun << ")" << endl;
+        *fLog << "       File corrupted." << endl;
+        return -1;
+    }
+
+    fNumFilterEvts += fNumEventsInRun;
+    fNumRuns++;
+
+    *fLog << inf << "Read " << fNumEventsInRun << " events from run (Total=";
+    *fLog << fNumFilterEvts << "/" << fEntries << " [";
+    *fLog << 100*fNumFilterEvts/fEntries << "%], Runs=" << fNumRuns << ")";
+    *fLog << endl;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MCT1ReadPreProc::OpenNextFile()
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existence of a next file to read
+    //
+    if (fNumFile >= (UInt_t)fFileNames->GetSize())
+        return kFALSE;
+
+    TNamed *file = (TNamed*)fFileNames->At(fNumFile);
+
+    //TNamed *file = (TNamed*)fFileNames->GetFirst();
+    //if (!file)
+    //    return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const TString name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    const TString fname(expname);
+    delete [] expname;
+
+    //
+    // Remove this file from the list of pending files
+    //
+    //fFileNames->Remove(file);
+
+    *fLog << inf << "Open file: '" << name << "'" << endl;
+
+    if (!CheckHeader(fname))
+        return kFALSE;
+
+    fNumFile++;
+
+    fIn = new ifstream(fname);
+    if (!*fIn)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "-----------------------------------------------------------------------" << endl;
+
+    switch (ReadRunHeader())
+    {
+    case kFALSE:
+        *fLog << warn << "Unable to read first run header... skipping file." << endl;
+        return kFALSE;
+    case -1:
+        *fLog << warn << "ReInit of Tasklist didn't succeed." << endl;
+        return kFALSE;
+    default:
+        *fLog << "After opening next file: Number of Events #" << fNumEventsInRun << endl;
+        return kTRUE;
+    }
+}
+
+Bool_t MCT1ReadPreProc::CheckHeader(const TString fname) const
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << dbginf << err << "ERROR - Cannot open file '" << fname << "'" << endl;
+        return kFALSE;
+    }
+
+    char cheadertitle[iHEADERTITLELENGTH];
+    fin.read(cheadertitle, iHEADERTITLELENGTH);
+
+    Float_t fpreprocversion, structversion;
+    Int_t dummyi;
+
+    sscanf(cheadertitle, cTITLE_TEMPLATE,
+           &fpreprocversion, &structversion,
+           &dummyi, &dummyi, &dummyi, &dummyi);
+
+    if (fpreprocversion < 0.6)
+    {
+        *fLog << dbginf << err << "ERROR - You must use PreProc V0.6 or higher." << endl;
+        return kFALSE;
+    }
+
+    if (STRUCT_VERSION > structversion)
+    {
+        *fLog << warn << "WARNING: Version of C-structures of file (V";
+        *fLog << structversion << ") newer than current structures (V";
+        *fLog << STRUCT_VERSION << ")" << endl;
+    }
+
+    *fLog << "Current structures: " << STRUCT_VERSION << "  ";
+    *fLog << "Structures in file: " << structversion << "  ";
+    *fLog << "Used preproc version: " << fpreprocversion << endl;
+
+    return kTRUE;
+}
+
+
+Int_t MCT1ReadPreProc::GetNumEvents(const TString fname) const
+{
+    *fLog << inf << "Scanning file " << fname << " for size" << flush;
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << dbginf << err << "ERROR - Opening file." << endl;
+        return 0;
+    }
+
+    const TString m(cEND_EVENTS_TEMPLATE);
+    const Int_t p = m.First('%');
+    const TString test = m(0, p);
+
+    Int_t nevts = 0;
+    Int_t nruns = 0;
+
+    while (!fin.eof() && fin.peek()!=EOF)
+    {
+        fin.seekg(iHEADERTITLELENGTH, ios::cur);
+        fin.seekg(sizeof(struct outputpars), ios::cur);
+
+        while (1)
+        {
+            if (fin.peek()==cEND_EVENTS_TEMPLATE[0])
+            {
+                char cheadertitle[iHEADERTITLELENGTH];
+                fin.read(cheadertitle, iHEADERTITLELENGTH);
+
+                const TString s = cheadertitle;
+                if (s.BeginsWith(test))
+                {
+                    fin.seekg(sizeof(struct filterresults), ios::cur);
+                    nruns++;
+                    break;
+                }
+
+                fin.seekg(-iHEADERTITLELENGTH, ios::cur);
+            }
+
+            fin.seekg(sizeof(struct eventrecord), ios::cur);
+            if (fin.eof())
+                break;
+
+            nevts++;
+        }
+        *fLog << "." << flush;
+    }
+
+    *fLog << "done." << endl;
+    *fLog << "Found " << nevts << " events in " << nruns << " runs." << endl;
+
+    return nevts;
+}
+
+Bool_t MCT1ReadPreProc::Rewind()
+{
+    fNumFilterEvts = 0;
+    fNumEvents     = 0;
+    fNumRuns       = 0;
+    fNumFile       = 0;
+    if (fIn)
+        delete fIn;
+
+    fIn=NULL;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the first file in the list. Check for the output containers or create
+// them if they don't exist.
+//
+// Initialize the size of the MPedPhotCam container to 127 pixels (CT1 camera)
+//
+Int_t MCT1ReadPreProc::PreProcess(MParList *pList)
+{
+    fParList = pList;
+
+    //
+    //  look for the HourAngle container in the plist
+    //
+    fHourAngle = (MParameterD*)pList->FindCreateObj("MParameterD", "HourAngle");
+    if (!fHourAngle)
+        return kFALSE;
+    fHourAngle->SetTitle("Store the CT1 hour angle [deg]");
+
+    //
+    //  look for the ThetaOrig container in the plist
+    //
+    fThetaOrig = (MParameterD*)pList->FindCreateObj("MParameterD", "ThetaOrig");
+    if (!fThetaOrig)
+        return kFALSE;
+    fThetaOrig->SetTitle("Store the original CT1 zenith angle [rad]");
+
+    //
+    //  look for the MCerPhotEvt class in the plist
+    //
+    fNphot = (MCerPhotEvt*)pList->FindCreateObj("MCerPhotEvt");
+    if (!fNphot)
+        return kFALSE;
+
+    //
+    //  look for the pedestal class in the plist
+    //
+    fPedest = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+    if (!fPedest)
+        return kFALSE;
+
+    //
+    //  look for the time class in the plist
+    //
+    fTime = (MTime*)pList->FindCreateObj("MTime");
+    if (!fTime)
+        return kFALSE;
+
+    //
+    //  look for the pedestal class in the plist
+    //
+    fBlinds = (MBadPixelsCam*)pList->FindCreateObj("MBadPixelsCam");
+    if (!fBlinds)
+        return kFALSE;
+
+    //
+    //  look for the source position in the camera
+    //
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPos)
+        return kFALSE;
+
+    //
+    //  look for the camera geometry
+    //
+    fGeom = (MGeomCam*)pList->FindCreateObj("MGeomCamCT1", "MGeomCam");
+    if (!fGeom)
+        return kFALSE;
+
+    //
+    //  look for the mc event class
+    //
+    fMcEvt = (MMcEvt*)pList->FindCreateObj("MMcEvt");
+    if (!fMcEvt)
+        return kFALSE;
+
+    //
+    //  look for the mc trigger class
+    //
+    fMcTrig = (MMcTrig*)pList->FindCreateObj("MMcTrig");
+    if (!fMcTrig)
+        return kFALSE;
+
+    //
+    //  look for the raw run header class
+    //
+    fRawRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+    if (!fRawRunHeader)
+        return kFALSE;
+
+    fBinningT = (MBinning*)pList->FindObject("BinningTheta");
+
+    Rewind();
+
+    fPedest->Init(*fGeom);
+
+    return GetSelector() ? GetSelector()->CallPreProcess(pList) : kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Smear Theta uniformly in a bin of Theta
+//   theta [rad]
+//   SmearTheta [rad]
+//
+Double_t MCT1ReadPreProc::SmearTheta(Double_t theta)
+{
+    if (!fBinningT)
+        return theta;
+
+    const Int_t bin = fBinningT->FindLoEdge(theta * 180/TMath::Pi());
+    if (bin<0)
+        return theta;
+
+    // smear Theta within the Theta bin
+    const Double_t low = fBinningT->GetEdges()[bin];
+    const Double_t up  = fBinningT->GetEdges()[bin+1];
+
+    // "up-": Do not allow the upper edge
+    return (up - gRandom->Uniform() * (up-low)) * TMath::Pi()/180;
+}
+
+// --------------------------------------------------------------------------
+//
+// Discretize Theta according to the binning in Theta
+//   theta [rad]
+//   DiscreteTheta [rad]  (= bin center)
+//
+Double_t MCT1ReadPreProc::DiscreteTheta(Double_t theta)
+{
+    if (!fBinningT)
+        return theta;
+
+    const Int_t bin = fBinningT->FindLoEdge(theta * 180/TMath::Pi());
+    if (bin<0)
+        return theta;
+
+    const Double_t low = fBinningT->GetEdges()[bin];
+    const Double_t up  = fBinningT->GetEdges()[bin+1];
+
+    return 0.5*(up+low) * TMath::Pi()/180;
+}
+
+// --------------------------------------------------------------------------
+//
+// Analyse the event data, means store and copy the needed data into
+// Mars structures and data members
+//
+Bool_t MCT1ReadPreProc::ProcessEvent(const struct eventrecord &event)
+{
+    /*
+    if (fRawRunHeader->GetRunNumber() == 1)
+    {
+        *fLog << "eventrecord" << endl;
+        *fLog << "isecs_since_midday = " << event.isecs_since_midday << endl;
+        *fLog << "isecfrac_200ns     = " << event.isecfrac_200ns << endl;
+        *fLog << "snot_ok_flags      = " << event.snot_ok_flags << endl;
+        *fLog << "ialt_arcs          = " << event.ialt_arcs << endl;
+        *fLog << "iaz_arcs           = " << event.iaz_arcs << endl;
+        *fLog << "ipreproc_alt_arcs  = " << event.ipreproc_alt_arcs << endl;
+        *fLog << "ipreproc_az_arcs   = " << event.ipreproc_az_arcs << endl;
+        *fLog << "ifieldrot_arcs     = " << event.ifieldrot_arcs << endl;
+
+        *fLog << "srate_millihz      = " << event.srate_millihz << endl;
+        *fLog << "fhourangle         = " << event.fhourangle << endl;
+        *fLog << "fmcenergy_tev      = " << event.fmcenergy_tev << endl;
+        *fLog << "fmcsize_phel       = " << event.fmcsize_phel << endl;
+        *fLog << "imcimpact_m        = " << event.imcimpact_m << endl;
+        *fLog << "imcparticle        = " << event.imcparticle << endl;
+        *fLog << "imctriggerflag     = " << event.imctriggerflag << endl;
+    }
+    */
+
+    // reset blind pixels for this event
+    fBlinds->Clear();
+    for (int i=0; i<iMAXNUMPIX; i++)
+        if (fBlnd[i]==1)
+            (*fBlinds)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+
+    // reset pedestal RMS for this event
+    for (Int_t i=0; i<iMAXNUMPIX; i++)
+        (*fPedest)[i].Set(0, fPedRMS[i]);
+
+    //  int   isecs_since_midday; // seconds passed since midday before sunset (JD of run start)
+    //  int   isecfrac_200ns;     // fractional part of isecs_since_midday
+    fTime->SetCT1Time((UInt_t)fRawRunHeader->GetRunStart().GetMjd(), event.isecfrac_200ns, event.isecs_since_midday);
+    fTime->SetReadyToSave();
+
+    /*
+     --- USEFULL? NEEDED? ---
+     short snot_ok_flags;      // the bits in these two bytes are flags for additional information on the event: Everything OK =: all Bits = 0
+
+     // for ALT-AZ mount telescopes: rotation angle of the field of
+     // view; this angle is defined mathematically positive looking
+     // towards the sky as the angle between the hour circle through
+     // the object being tracked and the line through pixel 1 and 2
+     int   ifieldrot_arcs;
+
+     // event rate in milli Hertz before filtering calculated by
+     // iratecalc_numevents_odd/(time[i+iratecalc_numevents_odd/2] -
+     // time[i-iratecalc_numevents_odd/2])
+     // For the first and the last iratecalc_numevents_odd/2
+     // events the rate is assumed to be constant
+     unsigned short srate_millihz;
+
+     // This is the angle between the observation of this event and the
+     // culmination point. It is going to be written into the events NTuple.
+     float fhourangle;
+     */
+
+    //
+    // read in the number of cerenkov photons and add the 'new' pixel
+    // too the list with it's id, number of photons and error
+    // number of photoelectrons measured in each pixel only the
+    // actual number of pixels (outputpars.inumpixels) is written out
+    // short spixsig_10thphot[iMAXNUMPIX];
+    //
+    for (Int_t i=0; i<iMAXNUMPIX; i++)
+    {
+      //*fLog << event.spixsig_10thphot[i] << " ";
+
+      if (event.spixsig_10thphot[i]==0)
+            continue;
+
+        fNphot->AddPixel(i, 0.1*event.spixsig_10thphot[i], (*fPedest)[i].GetRms());
+    }
+    fNphot->FixSize();
+    fNphot->SetReadyToSave();
+
+    // int ipreproc_alt_arcs; // "should be" alt according to preproc (arcseconds)
+    // int ipreproc_az_arcs;  // "should be" az according to preproc (arcseconds)
+
+    // smear Theta in its Theta bin
+    const Double_t theta = TMath::Pi()*(0.5-1./180*event.ialt_arcs/3600);
+    fThetaOrig->SetVal(theta);
+
+    // store hour angle
+    fHourAngle->SetVal(event.fhourangle);
+
+    fMcEvt->Fill(event.isecs_since_midday,     //0, /*fEvtNum*/
+                 fIsMcFile ? event.imcparticle : 0, /*corsika particle type*/
+                 fIsMcFile ? event.fmcenergy_tev*1000 : 0,
+		 0, /* fThi0 */
+		 0, /* fFirTar */
+                 0, /* fzFirInt */
+		 // 0, /* fThet*/
+		 // rwagner: The following should be theta, right? Check with
+		 // altitude fill some lines down...
+		 0, // altitude (arcseconds)
+                 0, /* fPhii */
+                 0, /* fCorD */
+                 0, /* fCorX */
+                 0, /* fCorY */
+                 fIsMcFile ? event.imcimpact_m*100 : 0,
+                 TMath::Pi()/180*event.iaz_arcs/3600, // azimuth (arcseconds)
+		 // fIsMcFile ? SmearTheta(theta) : theta,
+                 DiscreteTheta(theta),
+                 0, /* fTFirst */
+		 0, /* fTLast */
+		 0, /* fL_Nmax */
+		 0, /* fL_t0 */
+		 0, /* fL_tmax */
+		 0, /* fL_a */
+		 0, /* fL_b */
+		 0, /* fL_c */
+		 0, /* fL_chi2 */
+		 0, /* uiPin */
+		 0, /* uiPat */
+		 0, /* uiPre */
+		 0, /* uiPco */
+		 0, /* uiPelS */
+                 (int)(fIsMcFile ? event.fmcsize_phel : 0), /* uiPelC, Simulated SIZE */
+		 0, /* elec */
+		 0, /* muon */
+		 0  /* other */
+                 );
+
+    fMcTrig->SetFirstLevel(event.imctriggerflag);    // MC data from Dorota get a triggerflag: 1 means triggered, 0 not. */
+
+    fMcTrig->SetReadyToSave();
+    fMcEvt->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Because of the file format of the preproc output we have to check at any
+// event where in the file stream we are...
+//
+Bool_t MCT1ReadPreProc::CheckFilePosition()
+{
+    //
+    // Means: If no file is open (first call) try to open the first file
+    //
+    if (!fIn)
+        return kFALSE;
+
+    //
+    // Because we can have 0-event runs in the file we loop as often
+    // as we don't find a new footer-header combination.
+    //
+    while (1)
+    {
+        //
+        // If the first character isn't the first of the footer it must be
+        // an event
+        //
+        if (fIn->peek()!=cEND_EVENTS_TEMPLATE[0])
+            return kTRUE;
+
+        //
+        // Try reading the footer. If this isn't successful...
+        // must be an event
+        //
+        switch (ReadRunFooter())
+        {
+        case -1:
+            return kFALSE;
+        case 0:
+            return kTRUE;
+        }
+
+        *fLog << inf << "Footer found." << endl;
+
+        const char c = fIn->peek();
+
+        //
+        // No after reading the footer check if we reached the end of the file
+        //
+        if (fIn->eof() || c==EOF)
+        {
+            *fLog << "End of file." << endl;
+            return kFALSE;
+        }
+
+        //
+        // If the eof isn't reached a new header must follow. Check for it.
+        //
+        if (c!=cTITLE_TEMPLATE[0])
+        {
+            *fLog << inf << "Error finding new run header in file (possible EOF)... skipping rest of file." << endl;
+            return kFALSE;
+        }
+
+        *fLog << "-----------------------------------------------------------------------" << endl;
+
+
+        if (ReadRunHeader() < 0)
+        {
+            *fLog << warn << "ReInit of Tasklist didn't succeed." << endl;
+            return kFALSE;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the event number and depending on this number decide if
+// pedestals or event data has to be read.
+//
+// If the end of the file is reached try to open the next in the list. If
+// there is now next file stop the eventloop.
+//
+Int_t MCT1ReadPreProc::Process()
+{
+    //
+    // Check where in the file we are. If neither a new event, nor a
+    // footer/header combination is detected go to the next file.
+    //
+    if (!CheckFilePosition())
+        if (!OpenNextFile())
+            return kFALSE;
+
+    //
+    // Check for a selector. If one is given and returns kFALSE
+    // skip this event.
+    //
+    if (GetSelector())
+    {
+        //
+        // Make sure selector is processed
+        //
+        if (!GetSelector()->CallProcess())
+        {
+            *fLog << err << dbginf << "Processing Selector failed." << endl;
+            return kFALSE;
+        }
+
+        //
+        // Skip Event
+        //
+        if (!GetSelector()->IsConditionTrue())
+        {
+            fIn->seekg(sizeof(struct eventrecord), ios::cur);
+
+            fNumEvents++;
+            fNumEventsInRun++;
+
+            return kCONTINUE;
+        }
+    }
+
+    // event data to be read from the file
+    struct eventrecord event;
+
+
+
+    // read the eventrecord from the file
+    fIn->read((char*)&event, sizeof(struct eventrecord));
+
+    switch (ProcessEvent(event))
+    {
+    case kFALSE:
+        return kFALSE;
+    case kCONTINUE:
+        return kCONTINUE;
+    }
+
+    fNumEvents++;
+    fNumEventsInRun++;
+
+    return kTRUE;
+}
+
+Int_t MCT1ReadPreProc::PostProcess()
+{
+    *fLog << all;
+    *fLog << "Number events passed the filter: " << fNumFilterEvts << endl;
+    *fLog << "Number of Events read from file: " << fNumEvents << endl;
+    *fLog << "Number of Runs read from file:   " << fNumRuns << endl;
+    *fLog << "Number of events detected first: " << fEntries << endl;
+
+    if (fNumEvents!=fNumFilterEvts)
+    {
+        *fLog << warn << "WARNING! Number of events in file doesn't match number of read events..." << endl;
+        *fLog << "         File might be corrupt." << endl;
+    }
+
+    delete fIn;
+    fIn = NULL;
+
+    return GetSelector() ? GetSelector()->CallPostProcess() : kTRUE;
+}
Index: branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadPreProc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadPreProc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1ReadPreProc.h	(revision 17960)
@@ -0,0 +1,104 @@
+#ifndef MARS_MCT1ReadPreProc
+#define MARS_MCT1ReadPreProc
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class TList;
+class MTime;
+class MMcEvt;
+class MMcTrig;
+class MGeomCam;
+class MSrcPosCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MBadPixelsCam;
+class MRawRunHeader;
+class MTaskList;
+class MParList;
+class MParameterD;
+class MBinning;
+
+struct outputpars;
+struct eventrecord;
+
+class MCT1ReadPreProc : public MRead
+{
+private:
+    ifstream *fIn;          // the inputfile
+    TList    *fFileNames;   // Array which stores the \0-terminated filenames
+
+    MGeomCam      *fGeom;    // camera geometry
+    MCerPhotEvt   *fNphot;   // the data container for all data.
+    MPedPhotCam   *fPedest;  // ct1 pedestals
+    MTime         *fTime;    // event time
+    MMcEvt        *fMcEvt;   // monte carlo data container for MC files
+    MMcTrig       *fMcTrig;  // mc data container for trigger information
+    MSrcPosCam    *fSrcPos;  // source position in the camera
+    MBadPixelsCam *fBlinds;  // Array holding blind pixels
+    MRawRunHeader *fRawRunHeader; // raw run header
+    MParList      *fParList;      // parameter list
+    MParameterD   *fHourAngle;    // hour angle [deg]
+    MParameterD   *fThetaOrig;    // original zenith angle [rad]
+    MBinning      *fBinningT;     // Theta binning for the smearing
+
+    Bool_t fIsMcFile;       // Flag whether current run is a MC run
+
+    UInt_t fNumFile;
+    UInt_t fNumEvents;      // number of events counted in all runs in all files
+    UInt_t fNumEventsInRun; // number of events in the counted in th ecurrent run
+    UInt_t fNumRuns;        // number of processed runs of all files
+    UInt_t fEntries;        // entries of all files succesfully added
+    UInt_t fNumFilterEvts;  // number of events mentioned in the runs footers
+
+    TArrayF fPedRMS;
+    TArrayI fBlnd;
+
+    Bool_t OpenNextFile();
+
+    Int_t  GetNumEvents(const TString name) const;
+    Bool_t CheckHeader(const TString fname) const;
+
+    void   ReadPedestals();
+    Int_t  ReadRunHeader();
+    Int_t  ReadRunFooter();
+    Bool_t CheckFilePosition();
+    void   ProcessRunHeader(const struct outputpars &outpars);
+    Bool_t ProcessEvent(const struct eventrecord &event);
+
+    Double_t SmearTheta(Double_t theta);
+    Double_t DiscreteTheta(Double_t theta);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t Rewind();
+
+public:
+    MCT1ReadPreProc(const char *filename=NULL,
+                    const char *name=NULL,
+                    const char *title=NULL);
+
+    ~MCT1ReadPreProc();
+
+    Int_t AddFile(const char *fname, int i=0);
+
+    UInt_t GetEntries() { return fEntries; }
+
+    ClassDef(MCT1ReadPreProc, 0) // Reads the CT1 preproc data file
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/manalysisct1/MCT1Supercuts.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1Supercuts.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1Supercuts.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1Supercuts.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1Supercuts.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1Supercuts.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1SupercutsCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1SupercutsCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1SupercutsCalc.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MCT1SupercutsCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MCT1SupercutsCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MCT1SupercutsCalc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelBasic.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelBasic.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelBasic.cc	(revision 17960)
@@ -0,0 +1,261 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: MFCT1SelBasic.cc,v 1.13 2006-10-17 14:07:17 tbretz Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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: branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelFinal.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelFinal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelFinal.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelFinal.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelFinal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelFinal.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelStandard.cc
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelStandard.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelStandard.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelStandard.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelStandard.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/MFCT1SelStandard.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/manalysisct1/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/Makefile	(revision 17960)
@@ -0,0 +1,45 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = AnalysisCT1
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mdata -I../mfbase -I../mgeom     \
+           -I../mfileio -I../mfilter -I../manalysis -I../mpedestal -I../mmc \
+           -I../mhist -I../mpointing -I../mimage -I../mgui -I../mbadpixels  \
+           -I../mraw
+
+SRCFILES = MCT1FindSupercuts.cc \
+           MCT1PointingCorrCalc.cc \
+           MCT1Supercuts.cc \
+           MCT1SupercutsCalc.cc \
+           MCT1ReadPreProc.cc \
+           MCT1ReadAscii.cc
+
+# Doesn't compile: Please replace MBlindPixels by MBadPixel*
+#           MCT1PadONOFF.cc \
+#           MCT1PadSchweizer.cc \
+
+############################################################
+
+all:  $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/manalysisct1/structures.h
===================================================================
--- branches/Mars_McMismatchStudy/manalysisct1/structures.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/manalysisct1/structures.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mars-config.cc
===================================================================
--- branches/Mars_McMismatchStudy/mars-config.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mars-config.cc	(revision 17960)
@@ -0,0 +1,38 @@
+#include <iostream>
+
+#include <string.h> // strcmp (Ubuntu 8.10)
+
+#include <RVersion.h>
+
+using namespace std;
+
+static void Usage()
+{
+    cout << endl;
+    cout << "Sorry the usage is:" << endl;
+    cout << "   mars-config [--root-ver|--mars-ver]" << endl;
+    cout << endl;
+    cout << "Options:" << endl;
+    cout << "  --root-ver  Show root version which were used for compilation." << endl;
+    cout << "              To be compared with the output of \"root-config --version\"" << endl;
+    cout << "  --version   Show mars version." << endl;
+    cout << endl;
+    cout << "Only one command line option is allowed." << endl;
+    cout << endl;
+}
+
+int main(int argc, char *const argv[])
+{
+    if (argc!=2)
+    {
+        Usage();
+        return 2;
+    }
+
+    if (!strcmp(argv[1], "--root-ver"))
+        cout << ROOT_RELEASE << endl;
+    if (!strcmp(argv[1], "--version"))
+        cout << MARSVER << endl;
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/mars.cc
===================================================================
--- branches/Mars_McMismatchStudy/mars.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mars.cc	(revision 17960)
@@ -0,0 +1,189 @@
+#include <TClass.h>
+#include <TApplication.h>
+
+#include "MAGIC.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+#include "MArray.h"
+#include "MParContainer.h"
+
+#ifdef HAVE_XPM
+#include "MLogo.h"
+#endif
+
+#include "MCameraDisplay.h"
+#include "MEventDisplay.h"
+
+using namespace std;
+
+// **********************************************************************
+//
+//    MARS main program  
+//
+//    The only job of the main program is the initialization of ROOT and 
+//    the start of the GUI interface 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 << "   Modular Analysis and Reconstruction Software"    << endl;
+    gLog << "   Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " mars [options] filename|number" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   filename: Name of a merpped raw file, a calibrated (Y) file," << endl;
+    gLog << "             sequence file or sequence number." << endl;
+    gLog << " Options:" << endl;
+    gLog << "   --ind=path                Path to files, valid if sequence file or number given." << endl;
+    gLog << "   --config=mars.rc:         Change configuration file" << endl;
+    gLog << "                             <not yet implemented!>" << endl;
+    gLog.Usage();
+    gLog << "   -?/-h:                    This help" << endl << endl;
+}
+
+/*
+Bool_t InflateRun(TString &run, Bool_t ismc)
+{
+    if (run.IsDigit())
+    {
+        const Int_t numrun = run.Atoi();
+        seq = "/magic/";
+        if (ismc)
+            seq += ismc ? "montecarlo/" : "rawfiles/";
+        seq += Form("sequences/%04d/sequence%08d.txt", numseq/10000, numseq);
+        gLog << inf << "Inflated sequence file: " << seq << endl;
+    }
+
+    if (!gSystem->AccessPathName(seq, kFileExists))
+        return kTRUE;
+
+    gLog << err << "Sorry, sequence file '" << seq << "' doesn't exist." << endl;
+    return kFALSE;
+}
+*/
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    //const Bool_t  kIsSequence = arg.HasOnlyAndRemove("--seq");
+    const TString kConfig  = arg.GetStringAndRemove("--config=", "mars.rc");
+    const TString kInpathD = arg.GetStringAndRemove("--ind=", "");
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 2;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()>1)
+    {
+        gLog << warn << "WARNING - Too many arguments..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // This is to make argv[i] more readable inside the code
+    //
+    const TString kFilename = arg.GetArgumentStr(0);
+
+    //if (!kIsSequence && !InflateRun(kFilename))
+    //    return 3;
+
+#ifdef HAVE_XPM
+    MLogo logo;
+    logo.Popup();
+#endif
+
+    //
+    // initialize ROOT
+    //
+    TApplication app("mars", &argc, argv);
+    if (gROOT->IsBatch() || !gClient)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Switch of TObject Streamer in our base classes derived from TObject
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+#ifdef HAVE_XPM
+    logo.Popdown();
+#endif
+
+    /*
+    MEnv env(kConfig);
+    if (!env.IsValid())
+    {
+        gLog << err << "Configuration file " << kConfig << " not found." << endl;
+        return 0xfe;
+    }
+    */
+
+    //
+    // start the main window
+    //
+    if (kFilename.IsNull())
+        new MCameraDisplay;
+    else
+    {
+        MEventDisplay *d = new MEventDisplay(kFilename, kInpathD);
+        d->SetBit(MStatusDisplay::kExitLoopOnExit);
+        d->SetTitle(kFilename);
+    }
+
+    //
+    // run the application
+    //
+    app.Run();
+
+    gLog << all << endl;
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/mars.rc
===================================================================
--- branches/Mars_McMismatchStudy/mars.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mars.rc	(revision 17960)
@@ -0,0 +1,106 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#
+#  This is a resource file for the Mars executable. You can here setup
+#   setup the tasks of the eventloops executed in the Mars executable -
+#   if supported by these tasks.
+#
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# -------------------------------------------------------------------------
+# Define here which signal extractor you are going to use for the
+# whole calibration chain
+# -------------------------------------------------------------------------
+#ExtractSignal: MExtractTimeAndChargeDigitalFilter
+#ExtractSignal.WeightsFile: msignal/MC_weights46.dat
+# -------------------------------------------------------------------------
+# Define here parameters valid for all extractors above
+# -------------------------------------------------------------------------
+#ExtractSignal.LoGainSwitch:      120
+#ExtractSignal.LoGainStartShift: -2.5
+# -------------------------------------------------------------------------
+# Define here parameters valid for the spline:
+# -------------------------------------------------------------------------
+#ExtractSignal.HiGainFirst:         0
+#ExtractSignal.HiGainLast:         14
+#ExtractSignal.LoGainFirst:         1
+#ExtractSignal.LoGainLast:         14
+#ExtractSignal.Resolution:       0.05
+#ExtractSignal.RiseTimeHiGain:   0.64
+#ExtractSignal.FallTimeHiGain:   0.76
+#ExtractSignal.LoGainStretch:     1.5
+#ExtractSignal.OffsetLoGain:      1.3
+#ExtractSignal.ExtractionType: Integral <default>
+#ExtractSignal.ExtractionType: Amplitude
+# -------------------------------------------------------------------------
+# Define here parameters valid for the Digital Filter:
+# -------------------------------------------------------------------------
+#ExtractSignal.HiGainFirst:         0
+#ExtractSignal.HiGainLast:         16
+#ExtractSignal.LoGainFirst:         1
+#ExtractSignal.LoGainLast:         14
+#ExtractSignal.OffsetLoGain:     0.95
+
+# =========================================================================
+# To look into MUX data use the following setup
+# =========================================================================
+#ExtractSignal: MExtractTimeAndChargeSpline
+#ExtractSignal.RiseTimeHiGain:   4.3
+#ExtractSignal.FallTimeHiGain:   5.1
+#ExtractSignal.HiGainFirst:      0
+#ExtractSignal.HiGainLast:       49
+
+# -------------------------------------------------------------------------
+# In the case of the Digital filter you have to overwrite the default
+# weights file depending on what you are extracting
+# -------------------------------------------------------------------------
+#ExtractSignal.WeightsFile: msignal/cosmics_weights.dat
+
+# -------------------------------------------------------------------------
+# Setup level for determining of bad pixels
+# -------------------------------------------------------------------------
+#MBadPixelsCalc.PedestalLevel:         3.0
+#MBadPixelsCalc.PedestalLevelVariance: 3.0
+#MBadPixelsTreat.NumMinNeighbors:      3
+#MBadPixelsTreat.UseInterpolation:     yes
+#MBadPixelsTreat.ProcessPedestalEvt:   yes
+#MBadPixelsTreat.ProcessPedestalRun:   no
+#MBadPixelsTreat.ProcessTimes:         yes
+#MBadPixelsTreat.UseCentralPixel:      no
+#MBadPixelsTreat.HardTreatment:        no
+
+# -------------------------------------------------------------------------
+# This is how you can setup the Image cleaning used in the Camera Display
+#  e.g. Standard, Absolute, Scaled, Time
+# -------------------------------------------------------------------------
+MImgCleanStd.CleanMethod:   absolute
+#MImgCleanStd.CleanLevel0:   6.0
+MImgCleanStd.CleanLevel1:   6.0
+MImgCleanStd.CleanLevel2:   3.0
+MImgCleanStd.TimeLevel1:    17.5
+MImgCleanStd.TimeLevel2:    17.5
+MImgCleanStd.PostCleanType: 3
+
+#MImgCleanStd.CleanRings: 1
+#MImgCleanStd.KeepSinglePixels: No
+
+# -------------------------------------------------------------------------
+# Setup a cut to choose the events which should be displayed
+#    (Use this cuts to display only good Muon candidates)
+# -------------------------------------------------------------------------
+#Cut.Inverted: Yes
+#Cut.Condition: {0} && {1} && {2}
+#Cut.0: MHillas.fSize>150
+#Cut.1: (MMuonSearchPar.fRadius>180) && (MMuonSearchPar.fRadius<400) && (MMuonSearchPar.fDeviation<45)
+#Cut.2: (MMuonCalibPar.fArcPhi>190)  && (MMuonSearchPar.fDeviation<35) && (MMuonCalibPar.fArcWidth<0.20) && (MMuonCalibPar.fArcWidth>0.04)
Index: branches/Mars_McMismatchStudy/marslogo.xpm
===================================================================
--- branches/Mars_McMismatchStudy/marslogo.xpm	(revision 17960)
+++ branches/Mars_McMismatchStudy/marslogo.xpm	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mastro/AstroIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/AstroIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/AstroIncl.h	(revision 17960)
@@ -0,0 +1,8 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include <TArrayD.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mastro/AstroLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/AstroLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/AstroLinkDef.h	(revision 17960)
@@ -0,0 +1,18 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MAttLine+;
+
+#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: branches/Mars_McMismatchStudy/mastro/MAstro.cc
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstro.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstro.cc	(revision 17960)
@@ -0,0 +1,1091 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MAstro
+// ------
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MAstro.h"
+
+#include <math.h>     // fmod on darwin
+
+#include <iostream>
+
+#include <TArrayD.h>  // TArrayD
+#include <TVector3.h> // TVector3
+
+#include "MTime.h"    // MTime::GetGmst
+#include "MString.h"
+
+#include "MAstroCatalog.h" // FIXME: replace by MVector3!
+
+using namespace std;
+
+ClassImp(MAstro);
+
+const Double_t MAstro::kSynMonth = 29.53058868; // synodic month (new Moon to new Moon)
+const Double_t MAstro::kEpoch0   = 44240.37917; // First full moon after 1980/1/1
+
+Double_t MAstro::RadToHor()
+{
+    return 24/TMath::TwoPi();
+}
+
+Double_t MAstro::HorToRad()
+{
+    return TMath::TwoPi()/24;
+}
+
+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)
+{
+    Day2Hms(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);
+}
+
+TString MAstro::GetStringDeg(Double_t deg, const char *fmt)
+{
+    Char_t sgn;
+    UShort_t d, m, s;
+    Deg2Dms(deg, sgn, d, m, s);
+
+    return MString::Format(fmt, sgn, d, m ,s);
+}
+
+TString MAstro::GetStringHor(Double_t deg, const char *fmt)
+{
+    Char_t sgn;
+    UShort_t h, m, s;
+    Hor2Hms(deg, sgn, h, m, s);
+
+    return MString::Format(fmt, sgn, h, m ,s);
+}
+
+// --------------------------------------------------------------------------
+//
+// Interpretes a string ' - 12 30 00.0' or '+ 12 30 00.0'
+// as floating point value -12.5 or 12.5. If interpretation is
+// successfull kTRUE is returned, otherwise kFALSE. ret is not
+// touched if interpretation was not successfull. The successfull
+// interpreted part is removed from the TString.
+//
+Bool_t MAstro::String2Angle(TString &str, Double_t &ret)
+{
+    Char_t  sgn;
+    Int_t   d, len;
+    UInt_t  m;
+    Float_t s;
+
+    // Skip whitespaces before %c and after %f
+    int n=sscanf(str.Data(), " %c %d %d %f %n", &sgn, &d, &m, &s, &len);
+
+    if (n!=4 || (sgn!='+' && sgn!='-'))
+        return kFALSE;
+
+    str.Remove(0, len);
+
+    ret = Dms2Deg(d, m, s, sgn);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interpretes a string '-12:30:00.0', '12:30:00.0' or '+12:30:00.0'
+// as floating point value -12.5, 12.5 or 12.5. If interpretation is
+// successfull kTRUE is returned, otherwise kFALSE. ret is not
+// touched if interpretation was not successfull.
+//
+Bool_t MAstro::Coordinate2Angle(const TString &str, Double_t &ret)
+{
+    Char_t  sgn = str[0]=='-' ? '-' : '+';
+    Int_t   d;
+    UInt_t  m;
+    Float_t s;
+
+    const int n=sscanf(str[0]=='+'||str[0]=='-' ? str.Data()+1 : str.Data(), "%d:%d:%f", &d, &m, &s);
+
+    if (n!=3)
+        return kFALSE;
+
+    ret = Dms2Deg(d, m, s, sgn);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns val=-12.5 as string '-12:30:00'
+//
+TString MAstro::Angle2Coordinate(Double_t val)
+{
+    Char_t  sgn;
+    UShort_t d,m,s;
+
+    Deg2Dms(val, sgn, d, m, s);
+
+    return MString::Format("%c%02d:%02d:%02d", sgn, d, m, s);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return year y, month m and day d corresponding to Mjd.
+//
+void MAstro::Mjd2Ymd(UInt_t mjd, UShort_t &y, Byte_t &m, Byte_t &d)
+{
+    // Express day in Gregorian calendar
+    const ULong_t jd   = mjd + 2400001;
+    const ULong_t n4   = 4*(jd+((6*((4*jd-17918)/146097))/4+1)/2-37);
+    const ULong_t nd10 = 10*(((n4-237)%1461)/4)+5;
+
+    y = n4/1461L-4712;
+    m = ((nd10/306+2)%12)+1;
+    d = (nd10%306)/10+1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return Mjd corresponding to year y, month m and day d.
+//
+Int_t MAstro::Ymd2Mjd(UShort_t y, Byte_t m, Byte_t d)
+{
+    // Month lengths in days
+    static int months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+
+    // Validate month
+    if (m<1 || m>12)
+        return -1;
+
+    // Allow for leap year
+    months[1] = (y%4==0 && (y%100!=0 || y%400==0)) ? 29 : 28;
+
+    // Validate day
+    if (d<1 || d>months[m-1])
+        return -1;
+
+    // Precalculate some values
+    const Byte_t  lm = 12-m;
+    const ULong_t lm10 = 4712 + y - lm/10;
+
+    // Perform the conversion
+    return 1461L*lm10/4 + (306*((m+9)%12)+5)/10 - (3*((lm10+188)/100))/4 + d - 2399904;
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert a mjd to a number yymmdd. The century is just cut away, e.g.
+//   54393 -->  71020   (2007/10/20)
+//   50741 --> 971020   (1997/10/20)
+//   17868 -->  71020   (1907/10/20)
+//
+UInt_t MAstro::Mjd2Yymmdd(UInt_t mjd)
+{
+    UShort_t y;
+    Byte_t m, d;
+    Mjd2Ymd(mjd, y, m, d);
+
+    return d + m*100 + (y%100)*10000;
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert a yymmdd number to mjd. The century is defined as 2000 for
+// yy<70, 1900 otherwise.
+//    71020 --> 54393 (2007/10/20)
+//   971020 --> 50741 (1997/10/20)
+//
+UInt_t MAstro::Yymmdd2Mjd(UInt_t yymmdd)
+{
+    const Byte_t   dd =  yymmdd%100;
+    const Byte_t   mm = (yymmdd/100)%100;
+    const UShort_t yy = (yymmdd/10000)%100;
+
+    return Ymd2Mjd(yy + (yy<70 ? 2000 : 1900), mm, dd);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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)
+{
+    // v1 = theta0/phi0 --> theta0 / 0
+    // v2 = theta1/phi1 --> theta1 / phi1-phi0
+    // acos(alpha) = v1*v2/|v1||v2|    |v1|*|v2|=1
+    const Double_t sin2 = TMath::Sin(theta0)*TMath::Sin(theta1);
+    const Double_t cos2 = TMath::Cos(theta0)*TMath::Cos(theta1);
+
+    return TMath::ACos(sin2*TMath::Cos(phi1-phi0) + cos2);
+    /*
+     TVector3 v0;
+     v0.SetMagThetaPhi(1, theta0, phi0);
+
+     TVector3 v1;
+     v1.SetMagThetaPhi(1, theta0, phi0);
+
+     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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Estimates the time at which a source culminates.
+//
+// ra: right ascension [rad]
+// elong: observers longitude [rad]
+// mjd: modified julian date (utc)
+//
+// return time in [-12;12]
+//
+Double_t MAstro::EstimateCulminationTime(Double_t mjd, Double_t elong, Double_t ra)
+{
+    // startime at 1.1.2000 for greenwich 0h
+    const Double_t gmt0 = 6.664520;
+
+    // difference of startime for greenwich for two calendar days [h]
+    const Double_t d0 = 0.06570982224;
+
+    // mjd of greenwich 1.1.2000 0h
+    const Double_t mjd0 = 51544;
+
+    // mjd today
+    const Double_t mjd1 = TMath::Floor(mjd);
+
+    // scale between star-time and sun-time
+    const Double_t scale = 1;//1.00273790926;
+
+    const Double_t UT = (ra-elong)*RadToHor() - (gmt0 + d0 * (mjd1-mjd0))/scale;
+
+    return fmod(2412 + UT, 24) - 12;
+}
+
+// --------------------------------------------------------------------------
+//
+// Kepler - solve the equation of Kepler
+//
+Double_t MAstro::Kepler(Double_t m, Double_t ecc)
+{
+    m *= TMath::DegToRad();
+
+    Double_t delta = 0;
+    Double_t e = m;
+    do {
+        delta = e - ecc * sin(e) - m;
+        e -= delta / (1 - ecc * cos(e));
+    } while (fabs(delta) > 1e-6);
+
+    return e;
+}
+
+// --------------------------------------------------------------------------
+//
+// GetMoonPhase - calculate phase of moon as a fraction:
+//  Returns -1 if calculation failed
+//
+Double_t MAstro::GetMoonPhase(Double_t mjd)
+{
+    /****** Calculation of the Sun's position. ******/
+
+    // date within epoch
+    const Double_t epoch = 44238;       // 1980 January 0.0
+    const Double_t day = mjd - epoch;
+    if (day<0)
+    {
+        cout << "MAstro::GetMoonPhase - Day before Jan 1980" << endl;
+        return -1;
+    }
+
+    // mean anomaly of the Sun
+    const Double_t n = fmod(day*360/365.2422, 360);
+
+    const Double_t elonge = 278.833540; // ecliptic longitude of the Sun at epoch 1980.0
+    const Double_t elongp = 282.596403; // ecliptic longitude of the Sun at perigee
+
+    // convert from perigee co-ordinates to epoch 1980.0
+    const Double_t m = fmod(n + elonge - elongp + 360, 360);
+
+    // solve equation of Kepler
+    const Double_t eccent = 0.016718; // eccentricity of Earth's orbit
+    const Double_t k   = Kepler(m, eccent);
+    const Double_t ec0 = sqrt((1 + eccent) / (1 - eccent)) * tan(k / 2);
+    // true anomaly
+    const Double_t ec  = 2 * atan(ec0) * TMath::RadToDeg();
+
+    // Sun's geocentric ecliptic longitude
+    const Double_t lambdasun = fmod(ec + elongp + 720, 360);
+
+
+    /****** Calculation of the Moon's position. ******/
+
+    // Moon's mean longitude.
+    const Double_t mmlong  = 64.975464;  // moon's mean lonigitude at the epoch
+    const Double_t ml      = fmod(13.1763966*day + mmlong + 360, 360);
+    // Moon's mean anomaly.
+    const Double_t mmlongp = 349.383063; // mean longitude of the perigee at the epoch
+    const Double_t mm      = fmod(ml - 0.1114041*day - mmlongp + 720, 360);
+    // Evection.
+    const Double_t ev   = 1.2739 * sin((2 * (ml - lambdasun) - mm)*TMath::DegToRad());
+    // Annual equation.
+    const Double_t sinm = TMath::Sin(m*TMath::DegToRad());
+    const Double_t ae   = 0.1858 * sinm;
+    // Correction term.
+    const Double_t a3   = 0.37 * sinm;
+    // Corrected anomaly.
+    const Double_t mmp  = (mm + ev - ae - a3)*TMath::DegToRad();
+    // Correction for the equation of the centre.
+    const Double_t mec  = 6.2886 * sin(mmp);
+    // Another correction term.
+    const Double_t a4   = 0.214 * sin(2 * mmp);
+    // Corrected longitude.
+    const Double_t lp   = ml + ev + mec - ae + a4;
+    // Variation.
+    const Double_t v    = 0.6583 * sin(2 * (lp - lambdasun)*TMath::DegToRad());
+    // True longitude.
+    const Double_t lpp  = lp + v;
+    // Age of the Moon in degrees.
+    const Double_t age  = (lpp - lambdasun)*TMath::DegToRad();
+
+    // Calculation of the phase of the Moon.
+    return (1 - TMath::Cos(age)) / 2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the Period to which the time belongs to. The Period is defined
+// as the number of synodic months ellapsed since the first full moon
+// after Jan 1st 1980 (which was @ MJD=44240.37917)
+//
+Double_t MAstro::GetMoonPeriod(Double_t mjd)
+{
+    const Double_t et = mjd-kEpoch0; // Elapsed time
+    return et/kSynMonth;
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert a moon period back to a mjd
+//
+// See also
+//   MAstro::GetMoonPeriod
+//
+Double_t MAstro::GetMoonPeriodMjd(Double_t p)
+{
+    return p*kSynMonth+kEpoch0;
+}
+
+// --------------------------------------------------------------------------
+//
+// To get the moon period as defined for MAGIC observation we take the
+// nearest integer mjd, eg:
+//   53257.8 --> 53258
+//   53258.3 --> 53258
+// Which is the time between 12h and 11:59h of the following day. To
+// this day-period we assign the moon-period at midnight. To get
+// the MAGIC definition we now substract 284.
+//
+// For MAGIC observation period do eg:
+//   GetMagicPeriod(53257.91042)
+// or
+//   MTime t;
+//   t.SetMjd(53257.91042);
+//   GetMagicPeriod(t.GetMjd());
+// or
+//   MTime t;
+//   t.Set(2004, 1, 1, 12, 32, 11);
+//   GetMagicPeriod(t.GetMjd());
+//
+// To get a floating point magic period use
+//   GetMoonPeriod(mjd)-284
+//
+Int_t MAstro::GetMagicPeriod(Double_t mjd)
+{
+    const Double_t mmjd   = (Double_t)TMath::Nint(mjd);
+    const Double_t period = GetMoonPeriod(mmjd);
+
+    return (Int_t)TMath::Floor(period)-284;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the start time (12h noon) of the MAGIC period p.
+//
+// See also
+//   MAstro::GetMagicPeriod
+//
+Double_t MAstro::GetMagicPeriodStart(Int_t p)
+{
+    return TMath::Floor(GetMoonPeriodMjd(p+284))+0.5;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns right ascension and declination [rad] of the sun at the
+// given mjd (ra, dec).
+//
+// returns the mean longitude [rad].
+//
+// from http://xoomer.alice.it/vtomezzo/sunriset/formulas/index.html
+//
+Double_t MAstro::GetSunRaDec(Double_t mjd, Double_t &ra, Double_t &dec)
+{
+    const Double_t T = (mjd-51544.5)/36525;// +  (h-12)/24.0;
+
+    const Double_t T2 = T<0 ? -T*T : T*T;
+    const Double_t T3 = T*T*T;
+
+    // Find the ecliptic longitude of the Sun
+
+    // Geometric mean longitude of the Sun
+    const Double_t L = 280.46646 + 36000.76983*T + 0.0003032*T2;
+
+    // mean anomaly of the Sun
+    Double_t g = 357.52911 + 35999.05029*T - 0.0001537*T2;
+    g *= TMath::DegToRad();
+
+    // Longitude of the moon's ascending node
+    Double_t omega = 125.04452 - 1934.136261*T + 0.0020708*T2 + T3/450000;
+    omega *= TMath::DegToRad();
+
+    const Double_t coso = cos(omega);
+    const Double_t sino = sin(omega);
+
+    // Equation of the center
+    const Double_t C = (1.914602 - 0.004817*T - 0.000014*T2)*sin(g) +
+        (0.019993 - 0.000101*T)*sin(2*g) + 0.000289*sin(3*g);
+
+    // True longitude of the sun
+    const Double_t tlong = L + C;
+
+    // Apperent longitude of the Sun (ecliptic)
+    Double_t lambda = tlong - 0.00569 - 0.00478*sino;
+    lambda *= TMath::DegToRad();
+
+    // Obliquity of the ecliptic
+    Double_t obliq = 23.4392911 - 0.01300416667*T - 0.00000016389*T2 + 0.00000050361*T3 + 0.00255625*coso;
+    obliq *= TMath::DegToRad();
+
+    // Find the RA and DEC of the Sun
+    const Double_t sinl =  sin(lambda);
+
+    ra  = atan2(cos(obliq) * sinl, cos(lambda));
+    dec = asin(sin(obliq) * sinl);
+
+    return L*TMath::DegToRad();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns right ascension and declination [rad] of the moon at the
+// given mjd (ra, dec).
+//
+void MAstro::GetMoonRaDec(Double_t mjd, Double_t &ra, Double_t &dec)
+{
+    // Mean Moon orbit elements as of 1990.0
+    const Double_t l0 = 318.351648 * TMath::DegToRad();
+    const Double_t P0 =  36.340410 * TMath::DegToRad();
+    const Double_t N0 = 318.510107 * TMath::DegToRad();
+    const Double_t i  =   5.145396 * TMath::DegToRad();
+
+    Double_t sunra, sundec, g;
+    {
+        const Double_t T = (mjd-51544.5)/36525;// +  (h-12)/24.0;
+        const Double_t T2 = T<0 ? -T*T : T*T;
+
+        GetSunRaDec(mjd, sunra, sundec);
+
+        // mean anomaly of the Sun
+        g = 357.52911 + 35999.05029*T - 0.0001537*T2;
+        g *= TMath::DegToRad();
+    }
+
+    const Double_t sing   = sin(g)*TMath::DegToRad();
+
+    const Double_t D      = (mjd-47891) * TMath::DegToRad();
+    const Double_t l      =    13.1763966*D + l0;
+    const Double_t MMoon  = l  -0.1114041*D - P0; // Moon's mean anomaly M
+    const Double_t N      = N0 -0.0529539*D;      // Moon's mean ascending node longitude
+
+    const Double_t C      = l-sunra;
+    const Double_t Ev     = 1.2739 * sin(2*C-MMoon) * TMath::DegToRad();
+    const Double_t Ae     = 0.1858 * sing;
+    const Double_t A3     = 0.37   * sing;
+    const Double_t MMoon2 = MMoon+Ev-Ae-A3;  // corrected Moon anomaly
+
+    const Double_t Ec     = 6.2886 * sin(MMoon2)  * TMath::DegToRad();  // equation of centre
+    const Double_t A4     = 0.214  * sin(2*MMoon2)* TMath::DegToRad();
+    const Double_t l2     = l+Ev+Ec-Ae+A4; // corrected Moon's longitude
+
+    const Double_t V      = 0.6583 * sin(2*(l2-sunra)) * TMath::DegToRad();
+    const Double_t l3     = l2+V; // true orbital longitude;
+
+    const Double_t N2     = N -0.16*sing;
+
+    ra  = fmod( N2 + atan2( sin(l3-N2)*cos(i), cos(l3-N2) ), TMath::TwoPi() );
+    dec = asin(sin(l3-N2)*sin(i) );
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Euqation of time in hours for given mjd
+//
+Double_t MAstro::GetEquationOfTime(Double_t mjd)
+{
+    Double_t ra, dec;
+    const Double_t L = fmod(GetSunRaDec(mjd, ra, dec), TMath::TwoPi());
+
+    if (L-ra>TMath::Pi())
+        ra += TMath::TwoPi();
+
+    return 24*(L - ra)/TMath::TwoPi();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns noon time (the time of the highest altitude of the sun)
+// at the given mjd and at the given observers longitude [deg]
+//
+// The maximum altitude reached at noon time is
+//   altmax = 90.0 + dec - latit;
+//   if (dec > latit)
+//      altmax = 90.0 + latit - dec;
+// dec=Declination of the sun
+//
+Double_t MAstro::GetNoonTime(Double_t mjd, Double_t longit)
+{
+    const Double_t equation = GetEquationOfTime(TMath::Floor(mjd));
+    return 12. + equation - longit/15;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the time (in hours) between noon (the sun culmination)
+// and the sun being at height alt[deg] (90=zenith, 0=horizont)
+//
+//       civil twilight:      0deg to  -6deg
+//       nautical twilight:  -6deg to -12deg
+//       astronom twilight: -12deg to -18deg
+//
+// latit is the observers latitude in rad
+//
+// returns -1 in case the sun doesn't reach this altitude.
+// (eg. alt=0: Polarnight or -day)
+//
+// To get the sun rise/set:
+//    double timediff = MAstro::GetTimeFromNoonToAlt(mjd, latit*TMath::DegToRad(), par[0]);
+//    double noon     = MAstro::GetNoonTime(mjd, longit);
+//    double N        = TMath::Floor(mjd)+noon/24.;
+//    double risetime = N-timediff/24.;
+//    double settime  = N+timediff/24.;
+//
+Double_t MAstro::GetTimeFromNoonToAlt(Double_t mjd, Double_t latit, Double_t alt)
+{
+    Double_t ra, dec;
+    GetSunRaDec(mjd, ra, dec);
+
+    const Double_t h = alt*TMath::DegToRad();
+
+    const Double_t arg = (sin(h) - sin(latit)*sin(dec))/(cos(latit)*cos(dec));
+
+    return TMath::Abs(arg)>1 ? -1 : 12*acos(arg)/TMath::Pi();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the time of the sunrise/set calculated before and after
+// the noon of floor(mjd) (TO BE IMPROVED)
+//
+// Being longit and latit the longitude and latitude of the observer
+// in deg and alt the hight above or below the horizont in deg.
+//
+//       civil twilight:      0deg to  -6deg
+//       nautical twilight:  -6deg to -12deg
+//       astronom twilight: -12deg to -18deg
+//
+// A TArrayD(2) is returned with the the mjd of the sunrise in
+// TArray[0] and the mjd of the sunset in TArrayD[1].
+//
+TArrayD MAstro::GetSunRiseSet(Double_t mjd, Double_t longit, Double_t latit, Double_t alt)
+{
+    const Double_t timediff = MAstro::GetTimeFromNoonToAlt(mjd, latit*TMath::DegToRad(), alt);
+    const Double_t noon     = MAstro::GetNoonTime(mjd, longit);
+
+    const Double_t N = TMath::Floor(mjd)+noon/24.;
+
+    const Double_t rise = timediff<0 ? N-0.5 : N-timediff/24.;
+    const Double_t set  = timediff<0 ? N+0.5 : N+timediff/24.;
+
+    TArrayD rc(2);
+    rc[0] = rise;
+    rc[1] = set;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the distance in x,y between two polar-vectors (eg. Alt/Az, Ra/Dec)
+// projected on aplain in a distance dist. For Magic this this the distance
+// of the camera plain (1700mm) dist also determins the unit in which
+// the TVector2 is returned.
+//
+// v0 is the reference vector (eg. the vector to the center of the camera)
+// v1 is the vector to which we determin the distance on the plain
+//
+//  (see also MStarCamTrans::Loc0LocToCam())
+//
+TVector2 MAstro::GetDistOnPlain(const TVector3 &v0, TVector3 v1, Double_t dist)
+{
+    v1.RotateZ(-v0.Phi());
+    v1.RotateY(-v0.Theta());
+    v1.RotateZ(-TMath::Pi()/2); // exchange x and y
+    v1 *= dist/v1.Z();
+
+    return v1.XYvector(); //TVector2(v1.Y(), -v1.X());//v1.XYvector();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the absolute misspointing from the nominal zenith angle nomzd
+// and the deviations in zd (devzd) and az (devaz).
+// All values given in deg, the return value, too.
+//
+Double_t MAstro::GetDevAbs(Double_t nomzd, Double_t meszd, Double_t devaz)
+{
+    nomzd *= TMath::DegToRad();
+    meszd *= TMath::DegToRad();
+    devaz *= TMath::DegToRad();
+
+    const double x = sin(meszd) * sin(nomzd) * cos(devaz);
+    const double y = cos(meszd) * cos(nomzd);
+
+    return acos(x + y) * TMath::RadToDeg();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returned is the offset (number of days) which must be added to
+// March 1st of the given year, eg:
+//
+//    Int_t offset = GetDayOfEaster(2004);
+//
+//    MTime t;
+//    t.Set(year, 3, 1);
+//    t.SetMjd(t.GetMjd()+offset);
+//
+//    cout << t << endl;
+//
+//  If the date coudn't be calculated -1 is returned.
+//
+//  The minimum value returned is 21 corresponding to March 22.
+//  The maximum value returned is 55 corresponding to April 25.
+//
+// --------------------------------------------------------------------------
+//
+// Gauss'sche Formel zur Berechnung des Osterdatums
+// Wann wird Ostern gefeiert? Wie erfährt man das Osterdatum für ein
+// bestimmtes Jahr, ohne in einen Kalender zu schauen?
+//
+// Ostern ist ein "bewegliches" Fest. Es wird am ersten Sonntag nach dem
+// ersten Frühlingsvollmond gefeiert. Damit ist der 22. März der früheste
+// Termin, der 25. April der letzte, auf den Ostern fallen kann. Von
+// diesem Termin hängen auch die Feste Christi Himmelfahrt, das 40 Tage
+// nach Ostern, und Pfingsten, das 50 Tage nach Ostern gefeiert wird, ab.
+//
+// Von Carl Friedrich Gauß (Mathematiker, Astronom und Physiker;
+// 1777-1855) stammt ein Algorithmus, der es erlaubt ohne Kenntnis des
+// Mondkalenders die Daten der Osterfeste für die Jahre 1700 bis 2199 zu
+// bestimmen.
+//
+// Gib eine Jahreszahl zwischen 1700 und 2199 ein:
+//
+// Und so funktioniert der Algorithmus:
+//
+// Es sei:
+//
+// J	die Jahreszahl
+// a	der Divisionsrest von	J/19
+// b	der Divisionsrest von	J/4
+// c	der Divisionsrest von	J/7
+// d	der Divisionsrest von	(19*a + M)/30
+// e	der Divisionsrest von	(2*b + 4*c + 6*d + N)/7
+//
+// wobei M und N folgende Werte annehmen:
+//
+// für die Jahre	M	N
+//  1583-1599          22       2
+//  1600-1699          22       2
+//  1700-1799          23       3
+//  1800-1899          23       4
+//  1900-1999          24       5
+//  2000-2099          24       5
+//  2100-2199          24       6
+//  2200-2299          25       0
+//  2300-2399          26       1
+//  2400-2499          25       1
+//
+// Dann fällt Ostern auf den
+// (22 + d + e)ten März
+//
+// oder den
+// (d + e - 9)ten April
+//
+// Beachte:
+// Anstelle des 26. Aprils ist immer der 19. April zu setzen,
+// anstelle des 25. Aprils immer dann der 18. April, wenn d=28 und a>10.
+//
+// Literatur:
+// Schüler-Rechenduden
+// Bibliographisches Institut
+// Mannheim, 1966
+//
+// --------------------------------------------------------------------------
+//
+// Der Ostersonntag ist ein sog. unregelmäßiger Feiertag. Alle anderen
+// unregelmäßigen Feiertage eines Jahres leiten sich von diesem Tag ab:
+//
+//    * Aschermittwoch ist 46 Tage vor Ostern.
+//    * Pfingsten ist 49 Tage nach Ostern.
+//    * Christi Himmelfahrt ist 10 Tage vor Pfingsten.
+//    * Fronleichnam ist 11 Tage nach Pfingsten.
+//
+// Man muß also nur den Ostersonntag ermitteln, um alle anderen
+// unregelmäßigen Feiertage zu berechnen. Doch wie geht das?
+//
+// Dazu etwas Geschichte:
+//
+// Das 1. Kirchenkonzil im Jahre 325 hat festgelegt:
+//
+//    * Ostern ist stets am ersten Sonntag nach dem ersten Vollmond des
+//      Frühlings.
+//    * Stichtag ist der 21. März, die "Frühlings-Tagundnachtgleiche".
+//
+// Am 15.10.1582 wurde von Papst Gregor XIII. der bis dahin gültige
+// Julianische Kalender reformiert. Der noch heute gültige Gregorianische
+// Kalender legt dabei folgendes fest:
+//
+// Ein Jahr hat 365 Tage und ein Schaltjahr wird eingefügt, wenn das Jahr
+// durch 4 oder durch 400, aber nicht durch 100 teilbar ist. Hieraus
+// ergeben sich die zwei notwendigen Konstanten, um den Ostersonntag zu
+// berechnen:
+//
+//   1. Die Jahreslänge von und bis zum Zeitpunkt der
+//      Frühlings-Tagundnachtgleiche: 365,2422 mittlere Sonnentage
+//   2. Ein Mondmonat: 29,5306 mittlere Sonnentage
+//
+// Mit der "Osterformel", von Carl Friedrich Gauß (1777-1855) im Jahre 1800
+// entwickelt, läßt sich der Ostersonntag für jedes Jahr von 1583 bis 8202
+// berechnen.
+//
+// Der früheste mögliche Ostertermin ist der 22. März. (Wenn der Vollmond
+// auf den 21. März fällt und der 22. März ein Sonntag ist.)
+//
+// Der späteste mögliche Ostertermin ist der 25. April. (Wenn der Vollmond
+// auf den 21. März fällt und der 21. März ein Sonntag ist.)
+//
+Int_t MAstro::GetEasterOffset(UShort_t year)
+{
+    if (year<1583 || year>2499)
+    {
+        cout << "MAstro::GetDayOfEaster - Year " << year << " not between 1700 and 2199" << endl;
+        return -1;
+    }
+
+    Int_t M=0;
+    Int_t N=0;
+    switch (year/100)
+    {
+    case 15: 
+    case 16: M=22; N=2; break;
+    case 17: M=23; N=3; break;
+    case 18: M=23; N=4; break;
+    case 19: 
+    case 20: M=24; N=5; break;
+    case 21: M=24; N=6; break;
+    case 22: M=25; N=0; break;
+    case 23: M=26; N=1; break;
+    case 24: M=25; N=1; break;
+    }
+
+    const Int_t a = year%19;
+    const Int_t b = year%4;
+    const Int_t c = year%7;
+    const Int_t d = (19*a + M)%30;
+    const Int_t e = (2*b + 4*c + 6*d + N)%7;
+
+    if (e==6 && d==28 && a>10)
+        return 48;
+
+    if (d+e==35)
+        return 49;
+
+    return d + e + 21;
+}
Index: branches/Mars_McMismatchStudy/mastro/MAstro.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstro.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstro.h	(revision 17960)
@@ -0,0 +1,116 @@
+#ifndef MARS_MAstro
+#define MARS_MAstro
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+class TArrayD;
+class TVector3;
+class MTime;
+
+class MAstro
+{
+private:
+    static const Double_t kSynMonth; // synodic month (new Moon to new Moon)
+    static const Double_t kEpoch0;   // First full moon after 1980/1/1
+
+    static Double_t Round(Double_t val);
+    static Double_t Trunc(Double_t val);
+
+    static Double_t Kepler(Double_t m, Double_t ecc);
+
+public:
+    virtual ~MAstro() { }
+
+    // Unit conversion
+    static Double_t Parsec2Meter()    { return 3.0856776e+16; }
+    static Double_t Parsec2Lighyear() { return 3.2615644; }
+
+    static Double_t DegToHor()        { return 15; }
+    static Double_t HorToDeg()        { return 1./15; }
+
+    static Double_t RadToHor(); // { return 24/TMath::TwoPi(); }
+    static Double_t HorToRad(); // { return TMath::TwoPi()/24; }
+
+    // Angle/Time conversion functions
+    static Double_t Hms2Sec(Int_t deg, UInt_t min, Double_t sec, char sgn='+');
+    static Double_t Dms2Rad(Int_t deg, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Hms2Rad(Int_t hor, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Dms2Deg(Int_t deg, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Hms2Deg(Int_t hor, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Dms2Hor(Int_t deg, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Hms2Hor(Int_t hor, UInt_t min, Double_t sec, Char_t sgn='+');
+
+    static void Day2Hms(Double_t day, Char_t &sgn, UShort_t &h, UShort_t &m, UShort_t &s);
+    static void Rad2Dms(Double_t rad, Char_t &sgn, UShort_t &d, UShort_t &m, UShort_t &s);
+    static void Rad2Hms(Double_t rad, Char_t &sgn, UShort_t &h, UShort_t &m, UShort_t &s);
+    static void Deg2Dms(Double_t deg, Char_t &sgn, UShort_t &d, UShort_t &m, UShort_t &s);
+    static void Deg2Hms(Double_t deg, Char_t &sgn, UShort_t &h, UShort_t &m, UShort_t &s);
+    static void Hor2Dms(Double_t hor, Char_t &sgn, UShort_t &d, UShort_t &m, UShort_t &s);
+    static void Hor2Hms(Double_t hor, Char_t &sgn, UShort_t &h, UShort_t &m, UShort_t &s);
+
+    static void Day2Hm(Double_t day, Char_t &sgn, UShort_t &h, Double_t &m);
+    static void Rad2Dm(Double_t rad, Char_t &sgn, UShort_t &d, Double_t &m);
+    static void Rad2Hm(Double_t rad, Char_t &sgn, UShort_t &h, Double_t &m);
+    static void Deg2Dm(Double_t deg, Char_t &sgn, UShort_t &d, Double_t &m);
+    static void Deg2Hm(Double_t deg, Char_t &sgn, UShort_t &h, Double_t &m);
+    static void Hor2Dm(Double_t rad, Char_t &sgn, UShort_t &d, Double_t &m);
+    static void Hor2Hm(Double_t rad, Char_t &sgn, UShort_t &h, Double_t &m);
+
+    // Print funtions
+    static TString GetStringDeg(Double_t deg, const char *fmt="%c%d:%02d:%02d");
+    static TString GetStringHor(Double_t deg, const char *fmt="%c%d:%02d:%02d");
+
+    // Angle treatment functions
+    static Bool_t  String2Angle(TString &str, Double_t &ret);
+    static Bool_t  Coordinate2Angle(const TString &str, Double_t &ret);
+    static TString Angle2Coordinate(Double_t val);
+
+    static Double_t AngularDistance(Double_t theta0, Double_t phi0, Double_t theta1, Double_t phi1);
+
+    // Time treatment functions
+    static void  Mjd2Ymd(UInt_t mjd, UShort_t &y, Byte_t &m, Byte_t &d);
+    static Int_t Ymd2Mjd(UShort_t y, Byte_t m, Byte_t d);
+
+    static UInt_t Mjd2Yymmdd(UInt_t mjd);
+    static UInt_t Yymmdd2Mjd(UInt_t yymmdd);
+
+    static Double_t UT2GMST(Double_t ut1);
+
+    // Rotation angle between local and sky coordinate system
+    static void     RotationAngle(Double_t sinl, Double_t cosl, Double_t theta, Double_t phi, Double_t &sin, Double_t &cos);
+    static Double_t RotationAngle(Double_t sinl, Double_t cosl, Double_t theta, Double_t phi);
+
+    static void     GetMoonRaDec(Double_t mjd, Double_t &ra, Double_t &dec);
+
+    static Double_t GetMoonPhase(Double_t mjd);
+    static Double_t GetMoonPeriod(Double_t mjd);
+    static Double_t GetMoonPeriodMjd(Double_t p);
+    static Int_t    GetMagicPeriod(Double_t mjd);
+    static Double_t GetMagicPeriodStart(Int_t p);
+
+    static Double_t EstimateCulminationTime(Double_t mjd, Double_t longit, Double_t ra);
+
+    // Estimate some parameters around the sun
+    static Double_t GetSunRaDec(Double_t mjd, Double_t &ra, Double_t &dec);
+    static Double_t GetEquationOfTime(Double_t mjd);
+    static Double_t GetNoonTime(Double_t mjd, Double_t longit);
+    static Double_t GetTimeFromNoonToAlt(Double_t mjd, Double_t latit, Double_t alt);
+    static TArrayD  GetSunRiseSet(Double_t mjd, Double_t longit, Double_t latit, Double_t alt=0);
+
+    // Get distance between v1 and v0 in a plain perpendicular to v0 in distance dist
+    static TVector2 GetDistOnPlain(const TVector3 &v0, TVector3 v1, Double_t dist=1);
+
+    // Calculate absolute misspointing from error in zd and error in az
+    static Double_t GetDevAbs(Double_t nomzd, Double_t devzd, Double_t devaz);
+
+    static Int_t GetEasterOffset(UShort_t year);
+
+    ClassDef(MAstro, 0)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mastro/MAstroCamera.cc
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstroCamera.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstroCamera.cc	(revision 17960)
@@ -0,0 +1,571 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Robert Wagner, 7/2004 <mailto:rwagner@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MAstroCamera
+// ============
+//
+// A tools displaying stars from a catalog in the camera display.
+// PRELIMINARY!!
+//
+//
+// Usage:
+// ------
+// For a usage example see macros/starfield.C
+//
+// To be able to reflect the star-light you need the geometry of the
+// mirror and the distance of the plain screen.
+//
+// You can get the mirror geometry from a MC file and the distance of
+// the screen from MGeomCam.
+//
+//
+// Algorithm:
+// ----------
+// The calculation of the position of the reflection in the camera is
+// done by:
+//   - Rotation of the star-field such that the camera is looking into
+//     the pointing direction
+//   - Calculation of the reflected star-light vector by calling
+//     MGeomMirror::GetReflection (which returns the point at which
+//     the vector hits the camera plain)
+//   - Depending on the draw-option you get each reflected point, the
+//     reflection on a virtual ideal mirror or the reflection on each
+//     individual mirror
+//
+//
+// GUI:
+// ----
+//  * You can use the the cursor keys to change the pointing position
+//    and plus/minus to change the time by a quarter of an hour.
+//
+// ToDo:
+// -----
+//  * possibility to overwrite distance from mirror to screen
+//  * read the mirror geometry directly from the MC input file
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MAstroCamera.h"
+
+#include <errno.h>        // strerror
+#include <fstream>        // ifstream
+
+#include <KeySymbols.h>   // kKey_*
+
+#include <TH2.h>          // TH2D
+#include <TMarker.h>      // TMarker
+#include <TVirtualPad.h>  // gPad
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomMirror.h"
+
+#include "MString.h"
+
+#include "MTime.h"
+#include "MAstroSky2Local.h"
+#include "MObservatory.h"
+
+#include "MHCamera.h" // FIXME: This dependancy is very bad!
+                      // HOW TO GET RID OF IT? Move MHCamera to mgeom?
+
+//#include "MStarPos.h"
+
+ClassImp(MAstroCamera);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Create a virtual MGeomMirror which is in the center of the coordinate
+// system and has a normal vector in z-direction.
+//
+MAstroCamera::MAstroCamera() : fGeom(0), fMirrors(0)
+{
+    fMirror0 = new MGeomMirror;
+    fMirror0->SetMirrorContent(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fGeom, fMirrors and the virtual 0-Mirror fMirror0
+//
+MAstroCamera::~MAstroCamera()
+{
+    if (fGeom)
+        delete fGeom;
+    if (fMirrors)
+        delete fMirrors;
+
+    delete fMirror0;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a list of mirrors. The Mirrors must be of type MGeomMirror and
+// stored in a TClonesArray
+//
+void MAstroCamera::SetMirrors(TClonesArray &arr)
+{
+    if (arr.GetClass()!=MGeomMirror::Class())
+    {
+      cout << "ERROR - TClonesArray doesn't contain objects of type MGeomMirror... ignored." << endl;
+      return;
+    }
+
+    const Int_t n = arr.GetSize();
+
+    if (!fMirrors)
+        fMirrors = new TClonesArray(MGeomMirror::Class(), n);
+
+    fMirrors->ExpandCreate(n);
+
+    for (int i=0; i<n; i++)
+        memcpy((*fMirrors)[i], arr[i], sizeof(MGeomMirror));
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Read the mirror geometry from a MC .def file. The following
+// structure is expected:
+//
+// #*  TYPE=1  (MAGIC)
+// #*      i  f   sx   sy   x   y   z   thetan  phin 
+// #* 
+// #*       i : number of the mirror
+// #*       f : focal distance of that mirror
+// #*      sx : curvilinear coordinate of mirror's center in X[cm]
+// #*      sy : curvilinear coordinate of mirror's center in X[cm]
+// #*       x : x coordinate of the center of the mirror [cm]
+// #*       y : y coordinate of the center of the mirror [cm]
+// #*       z : z coordinate of the center of the mirror [cm]
+// #*  thetan : polar theta angle of the direction where the mirror points to
+// #*    phin : polar phi angle of the direction where the mirror points to
+// #*      xn : xn coordinate of the normal vector in the center (normalized)
+// #*      yn : yn coordinate of the normal vector in the center (normalized)
+// #*      zn : zn coordinate of the normal vector in the center (normalized)
+// #
+// define_mirrors
+//   1 1700.9200   25.0002   75.0061   25.0000   75.0000    0.9207 0.02328894 1.24904577 -0.00736394 -0.02209183 0.99972882
+//   2 ...
+//
+void MAstroCamera::SetMirrors(const char *fname)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        gLog << err << "Cannot open file " << fname << ": ";
+        gLog << strerror(errno) << endl;
+        return;
+    }
+
+    TString line;
+    while (1)
+    {
+        line.ReadLine(fin);
+        if (!fin)
+            return;
+
+        line = line.Strip(TString::kBoth);
+
+        if (line.BeginsWith("n_mirrors"))
+        {
+            Int_t n;
+            sscanf(line.Data(), "%*s %d", &n);
+
+            if (!fMirrors)
+                fMirrors = new TClonesArray(MGeomMirror::Class(), n);
+
+            fMirrors->ExpandCreate(n);
+            continue;
+        }
+
+
+        Int_t id;
+        Float_t f, sx, sy, x, y, z, thetan, phin, xn, yn, zn;
+
+        const Int_t n = sscanf(line.Data(), "%d %f %f %f %f %f %f %f %f %f %f %f",
+                               &id, &f, &sx, &sy, &x, &y, &z, &thetan,
+                               &phin, &xn, &yn, &zn);
+        if (n!=12)
+            continue;
+
+        new ((*fMirrors)[id-1]) MGeomMirror;
+        ((MGeomMirror*)(*fMirrors)[id-1])->SetMirrorContent(id, f, sx, sy, x, y, z, thetan, phin, xn, yn, zn);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the camera geometry. The MGeomCam object is cloned.
+//
+void MAstroCamera::SetGeom(const MGeomCam &cam)
+{
+    if (fGeom)
+        delete fGeom;
+
+    fGeom = (MGeomCam*)cam.Clone();
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert To Pad coordinates (see MAstroCatalog)
+//
+Int_t MAstroCamera::ConvertToPad(const TVector3 &w, TVector2 &v) const
+{
+    /*
+     --- Use this to plot the 'mean grid' instead of the grid of a
+         theoretical central mirror ---
+
+        TVector3 spot;
+        const Int_t num = fConfig->GetNumMirror();
+        for (int i=0; i<num; i++)
+        spot += fConfig->GetMirror(i).GetReflection(w, fGeom->GetCameraDist())*1000;
+        spot *= 1./num;
+        */
+
+    const TVector3 spot = fMirror0->GetReflection(w, fGeom->GetCameraDist())*1000;
+    v.Set(spot(0), spot(1));
+
+    const Float_t max = fGeom->GetMaxRadius()*0.70;
+    return v.X()>-max && v.Y()>-max && v.X()<max && v.Y()<max;
+}
+
+// --------------------------------------------------------------------------
+//
+// Find an object with a given name in the list of primitives of this pad.
+//
+TObject *FindObjectInPad(const char *name, TVirtualPad *pad)
+{
+    if (!pad)
+        pad = gPad;
+
+    if (!pad)
+        return NULL;
+
+    TObject *o;
+
+    TIter Next(pad->GetListOfPrimitives());
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(gROOT->GetClass(name)))
+            return o;
+
+        if (o->InheritsFrom("TPad"))
+            if ((o = FindObjectInPad(name, (TVirtualPad*)o)))
+                return o;
+    }
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Options:
+//
+//  '*' Draw the mean of the reflections on all mirrors
+//  '.' Draw a dot for the reflection on each individual mirror
+//  'h' To create a TH2D of the star-light which is displayed
+//  'c' Use the underlaying MHCamera as histogram
+//  '0' Draw the reflection on a virtual perfect mirror
+//  '=' Draw '0' or '*' propotional to the star magnitude
+//
+// If the Pad contains an object MHCamera of type MHCamera it is used.
+// Otherwise a new object is created.
+//
+// FIXME: Add Project functionand change treating MHCamera and
+//        TH2D accordingly
+//
+void MAstroCamera::AddPrimitives(TString o)
+{
+    if (!fTime || !fObservatory || !fMirrors)
+    {
+      cout << "Missing data..." << endl;
+        return;
+    }
+
+    if (o.IsNull())
+        o = "*.";
+
+    const Bool_t hasnull = o.Contains("0", TString::kIgnoreCase);
+    const Bool_t hashist = o.Contains("h", TString::kIgnoreCase);
+    const Bool_t hasmean = o.Contains("*", TString::kIgnoreCase);
+    const Bool_t hasdot  = o.Contains(".", TString::kIgnoreCase);
+    const Bool_t usecam  = o.Contains("c", TString::kIgnoreCase);
+    const Bool_t resize  = o.Contains("=", TString::kIgnoreCase);
+
+    // Get camera
+    MHCamera *camera=(MHCamera*)FindObjectInPad("MHCamera", gPad);
+    if (camera)
+    {
+        if (!camera->GetGeometry() || camera->GetGeometry()->IsA()!=fGeom->IsA())
+            camera->SetGeometry(*fGeom);
+    }
+    else
+    {
+        camera = new MHCamera(*fGeom);
+        camera->SetName("MHCamera");
+        camera->SetStats(0);
+        camera->SetInvDeepBlueSeaPalette();
+        camera->SetBit(kCanDelete);
+        camera->Draw();
+    }
+
+    camera->SetTitle(GetPadTitle());
+
+    gPad->cd(1);
+
+    if (!usecam)
+    {
+        if (camera->GetEntries()==0)
+            camera->SetBit(MHCamera::kNoLegend);
+    }
+    else
+    {
+        camera->Reset();
+        camera->SetYTitle("arb.cur");
+    }
+
+    TH2 *h=0;
+    if (hashist)
+    {
+        TH2F hist("","", 90, -650, 650, 90, -650, 650);
+        hist.SetMinimum(0);
+        h = (TH2*)hist.DrawCopy("samecont1");
+    }
+
+    const TRotation rot(GetGrid(kTRUE));
+
+    MVector3 *radec;
+    TIter Next(&fList);
+
+    while ((radec=(MVector3*)Next()))
+    {
+        const Double_t mag = radec->Magnitude();
+        if (mag>GetLimMag())
+            continue;
+
+        TVector3 star(*radec);
+
+        // Rotate Star into telescope system
+        star *= rot;
+
+        TVector3 mean;
+
+        Int_t num = 0;
+
+        MGeomMirror *mirror = 0;
+        TIter NextM(fMirrors);
+        while ((mirror=(MGeomMirror*)NextM()))
+        {
+  	    const TVector3 spot = mirror->GetReflection(star, fGeom->GetCameraDist())*1000;
+            
+            // calculate mean of all 'stars' hitting the camera plane
+            // by taking the sum of the intersection points between
+            // the light vector and the camera plane
+            mean += spot;
+
+            if (hasdot)
+            {
+                TMarker *m=new TMarker(spot(0), spot(1), 1);
+                m->SetMarkerColor((Int_t)(6*mirror->GetMirrorCenter().Mag())+51);
+                m->SetMarkerStyle(kDot);
+                fMapG.Add(m);
+            }
+            if (h)
+                h->Fill(spot(0), spot(1), pow(10, -mag/2.5));
+
+            if (usecam)
+                camera->Fill(spot(0), spot(1), pow(10, -mag/2.5));
+
+            num++;
+        }
+
+        // transform meters into millimeters (camera display works with mm)
+        mean *= 1./num;
+        DrawStar(mean(0), mean(1), *radec, hasmean?kBlack:-1, MString::Format("x=%.1fmm y=%.1fmm", mean(0), mean(1)), resize);
+        if (hasnull)
+        {
+            TVector3 vstar(*radec);
+            vstar *= rot;
+            const TVector3 spot = fMirror0->GetReflection(vstar, fGeom->GetCameraDist())*1000;
+            DrawStar(spot(0), spot(1), *radec, hasmean?kBlack:-1, MString::Format("x=%.1fmm y=%.1fmm", mean(0), mean(1)), resize);
+            // This can be used to get the abberation...
+            //cout << TMath::Hypot(spot(0), spot(1)) << " " << TMath::Hypot(mean(0)-spot(0), mean(1)-spot(1)) << endl;
+        }
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fills a TList with all stars found under current presets
+// (Coordinates, Time, FOV). The list is emptied before the filling is done.
+// Currently, the mean spot when averaging over all mirrors is used.
+//
+/*
+void MAstroCamera::FillStarList(TList* list)
+{
+    if (!fTime || !fObservatory || !fMirrors) {
+      cout << "Missing data..." << endl;
+      return;
+    }
+
+    if (!list) {
+      cout << "Missing storage list for stars found..." << endl;
+      return;
+    }
+
+    list->Delete(); // dump old list... (otherwise the same stars would pile up)
+   
+    const TRotation rot(GetGrid(kTRUE));
+    MVector3 *radec;
+    TIter Next(&fList);
+
+    while ((radec=(MVector3*)Next())) {
+      const Double_t mag = radec->Magnitude();
+      if (mag>GetLimMag())
+	continue;
+      TVector3 star(*radec);
+      // Rotate Star into telescope system
+      star *= rot;
+      TVector3 mean;
+      Int_t num = 0;
+      MGeomMirror *mirror = 0;
+      TIter NextM(fMirrors);
+      while ((mirror=(MGeomMirror*)NextM())) {
+	const TVector3 spot = mirror->GetReflection(star, fGeom->GetCameraDist())*1000;
+	mean += spot;
+	num++;
+      }
+      mean *= 1./num;
+
+      MStarPos *starpos = new MStarPos;
+      starpos->SetExpValues(mag,mean(0),mean(1));
+
+      // Do _not_ remove this, name needs to be 
+      // transferred to the starpos.
+      const TString name = radec->GetName();
+      starpos->SetName(name.IsNull() ? "n/a" : name.Data());
+
+      const TVector3 spot = fMirror0->GetReflection(star, fGeom->GetCameraDist())*1000;
+      starpos->SetIdealValues(mag,spot(0),spot(1));
+      list->Add(starpos);
+    }
+}
+*/
+
+// ------------------------------------------------------------------------
+//
+// Uses fRaDec as a reference point.
+//
+// Return dZd and dAz corresponding to the distance from x,y to fRaDec
+//
+// Before calling this function you should correct for abberation. In
+// case of MAGIC you can do this by:
+//    x /= 1.0713;
+//    y /= 1.0713;
+//
+// x [mm]: x coordinate in the camera plane (assuming a perfect mirror)
+// y [mm]: y coordinate in the camera plane (assuming a perfect mirror)
+//
+// We assume (0, 0) to be the center of the FOV
+//
+// dzd [deg]: Delta Zd
+// daz [deg]: Delta Az
+//
+void MAstroCamera::GetDiffZdAz(Double_t x, Double_t y, Double_t &dzd, Double_t &daz)
+{
+    // Reflect the corrected pixel on a perfect mirror
+    TVector3 v(x, y, fGeom->GetCameraDist()*1000);
+    TVector3 spot = fMirror0->GetReflection(v);
+    
+    // Derotate into the local coordinate system
+    const MAstroSky2Local rot(*fTime, *fObservatory);
+    const TRotation align(AlignCoordinates(rot*fRaDec).Inverse());
+    spot *= align;
+
+    cout << "Zd="<<spot.Theta()*TMath::RadToDeg() << " ";
+    cout << "Az="<<spot.Phi()  *TMath::RadToDeg()+360 << endl;
+
+    // Derotatet the center of the camera
+    TVector3 c(0, 0, 1);
+    c *= align;
+
+    dzd = (spot.Theta()-c.Theta())*TMath::RadToDeg();
+    daz = (spot.Phi()  -c.Phi())  *TMath::RadToDeg();
+
+    if (daz> 180) daz -= 360;
+    if (daz<-180) daz += 360;
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a gui event on the camera
+//
+void MAstroCamera::ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2)
+{
+    // if (mp1>0 && mp2>0)
+    // {
+    //     // Calculate World coordinates from pixel
+    //     Double_t x = gPad->AbsPixeltoX(mp1);
+    //     Double_t y = gPad->AbsPixeltoY(mp2);
+    //
+    //     // Correct for abberation
+    //     x /= 1.0713;
+    //     y /= 1.0713;
+    //
+    //     Double_t dzd, daz;
+    //     GetDiffZdAz(x, y, dzd, daz);
+    //
+    //     cout << "dZd="<< dzd << " " << "dAz="<< daz << endl;
+    // }
+    //
+    // For MAGIC the distance of the mean of the light distribution
+    // to the Mirror0 reflection of the star (Abberation) can be
+    // expressed as:  dr = 0.0713*r = r/14.03
+    //                   +-0.0002
+
+    if (event==kKeyPress && fTime)
+        switch (mp2)
+        {
+        case kKey_Plus:
+            fTime->SetMjd(fTime->GetMjd()+0.25/24);
+            Update(kTRUE);
+            return;
+
+        case kKey_Minus:
+            fTime->SetMjd(fTime->GetMjd()-0.25/24);
+            Update(kTRUE);
+            return;
+        }
+
+    MAstroCatalog::ExecuteEvent(event, mp1, mp2);
+}
Index: branches/Mars_McMismatchStudy/mastro/MAstroCamera.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstroCamera.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstroCamera.h	(revision 17960)
@@ -0,0 +1,44 @@
+#ifndef MARS_MAstroCamera
+#define MARS_MAstroCamera
+
+#ifndef MARS_MAstroCatalog
+#include "MAstroCatalog.h"
+#endif
+
+class TClonesArray;
+class TList;
+
+class MTime;
+class MGeomCam;
+class MGeomMirror;
+class MObservatory;
+
+class MAstroCamera : public MAstroCatalog
+{
+private:
+    MGeomCam     *fGeom;
+    TClonesArray *fMirrors;
+
+    MGeomMirror  *fMirror0;     //!
+
+    Int_t  ConvertToPad(const TVector3 &w, TVector2 &v) const;
+    void   AddPrimitives(TString o);
+    void   SetRangePad(Option_t *o) { }
+    void   ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2);
+
+public:
+    MAstroCamera();
+    ~MAstroCamera();
+
+    void SetMirrors(TClonesArray &arr);
+    void SetMirrors(const char *fname);
+    void SetGeom(const MGeomCam &cam);
+
+    //void FillStarList(TList *list);
+
+    void GetDiffZdAz(Double_t x, Double_t y, Double_t &dzd, Double_t &daz);
+
+    ClassDef(MAstroCamera, 1) // Display class to display stars on the camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mastro/MAstroCatalog.cc
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstroCatalog.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstroCatalog.cc	(revision 17960)
@@ -0,0 +1,1575 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MAstroCatalog
+//  =============
+//
+//  THIS IMPLEMENTATION IS PRELIMINARY AND WILL BE MERGED WITH
+//  SOME PARTS OF THE DRIVE SOFTWARE SOON!
+//
+//
+//  Catalogs:
+//  ---------
+//
+//  To be able to use this class you need a catalog file suppored by
+//  MAstroCatalog.
+//  Catalog files can be found at
+//  http://magic.astro.uni-wuerzburg.de/mars/catalogs.html
+//  You must copy the file into the directory from which you start your macro
+//  or give an abolute path loading the catalog.
+//
+//
+//  Usage:
+//  ------
+//
+//  To display a starfield you must have a supported catalog, then do:
+//
+//    MTime time;
+//    // Time for which to get the picture
+//    time.Set(2004, 2, 28, 20, 14, 7);
+//    // Current observatory
+//    MObservatory magic1;
+//    // Right Ascension [h] and declination [deg] of source
+//    // Currently 'perfect' pointing is assumed
+//    const Double_t ra  = MAstro::Hms2Rad(5, 34, 31.9);
+//    const Double_t dec = MAstro::Dms2Rad(22, 0, 52.0);
+//    MAstroCatalog stars;
+//    // Magnitude up to which the stars are loaded from the catalog
+//    stars.SetLimMag(6);
+//    // Radius of FOV around the source position to load the stars
+//    stars.SetRadiusFOV(3);
+//    // Source position
+//    stars.SetRaDec(ra, dec);
+//    // Catalog to load (here: Bright Star Catalog V5)
+//    stars.ReadBSC("bsc5.dat");
+//    // Obersavatory and time to also get local coordinate information
+//    stars.SetObservatory(magic1);
+//    stars.SetTime(time);
+//    // Enable interactive GUI
+//    stars.SetGuiActive();
+//    //Clone the catalog due to the validity range of the instance
+//    TObject *o = stars.Clone();
+//    o->SetBit(kCanDelete);
+//    o->Draw();
+//
+//  If no time and/or Obervatory location is given no local coordinate
+//  information is displayed.
+//
+//
+//  Coordinate Transformation:
+//  -------------------------
+//  The conversion from sky coordinates to local coordinates is done using
+//  MAstroSky2Local which does a simple rotation of the coordinate system.
+//  This is inaccurate in the order of 30arcsec due to ignorance of all
+//  astrometrical corrections (nutation, precission, abberation, ...)
+//
+//
+//  GUI:
+//  ----
+//    * If the gui is interactive you can use the cursor keys to change
+//      the position you are looking at and with plus/minus you
+//      can (un)zoom the FOV (Field Of View)
+//    * The displayed values mean the following:
+//        + alpha: Right Ascension
+//        + delta: Declination
+//        + theta: zenith distance / zenith angle
+//        + phi:   azimuth angle
+//        + rho:   angle of rotation sky-coordinate system vs local-
+//                 coordinate system
+//        + time of display
+//    * Move the mouse on top of the grid points or the stars to get
+//      more setailed information.
+//    * Enable the event-info in a canvas to see the current
+//      ObjectInfo=tooltip-text
+//    * call SetNoToolTips to supress the tooltips
+//    * the blue lines are the local coordinat system
+//    * the red lines are sky coordinate system
+//
+//
+//  ToDo:
+//  -----
+//   - replace MVetcor3 by a more convinient class. Maybe use TExMap, too.
+//   - change tooltips to multi-line tools tips as soon as root
+//     supports them
+//   - a derived class is missing which supports all astrometrical
+//     correction (base on slalib and useable in Cosy)
+//   - Implement a general loader for heasarc catlogs, see
+//     http://heasarc.gsfc.nasa.gov/W3Browse/star-catalog/
+//
+//  Class Version 2:
+//    + MAttLine fAttLineSky;    // Line Style and color for sky coordinates
+//    + MAttLine fAttLineLocal;  // Line Style and color for local coordinates
+//    + added new base class TAttMarker
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAstroCatalog.h"
+
+#include <errno.h>      // strerror
+#include <stdlib.h>     // ati, atof
+#include <limits.h>     // INT_MAX (Suse 7.3/gcc 2.95)
+
+#include <fstream>
+
+#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 <TH1.h>        // TH1F
+#include <TGraph.h>     // TGraph
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "izstream.h"   // izstream <ifstream>
+
+#include "MTime.h"
+#include "MString.h"
+#include "MAstro.h"
+#include "MAstroSky2Local.h"
+#include "MObservatory.h"
+
+#undef DEBUG
+//#define DEBUG
+
+#ifdef DEBUG
+#include <TStopwatch.h>
+#endif
+
+ClassImp(MAttLine);
+ClassImp(MAstroCatalog);
+
+using namespace std;
+
+// Datacenter default path for catalogs
+const TString MAstroCatalog::kDefaultPath="/magic/datacenter/setup/";
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor. Set Default values:
+//   fLimMag    = 99
+//   fRadiusFOV = 90
+//
+MAstroCatalog::MAstroCatalog() : fLimMag(99), fRadiusFOV(90), fToolTip(0), fObservatory(0), fTime(0)
+{
+    fList.SetOwner();
+    fMapG.SetOwner();
+
+    fToolTip = gROOT->IsBatch() || !gClient ? 0 : new TGToolTip(0, "", 0);
+
+    fAttLineSky.SetLineStyle(kDashDotted);
+    fAttLineLocal.SetLineStyle(kDashDotted);
+
+    fAttLineSky.SetLineColor(kRed);
+    fAttLineLocal.SetLineColor(kBlue);
+
+    SetMarkerColor(kBlack);
+    SetMarkerStyle(kCircle);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete fTime, fObservatory. Disconnect signal. delete tooltip.
+// Delete Map with gui primitives
+//
+MAstroCatalog::~MAstroCatalog()
+{
+    // First disconnect the EventInfo...
+    // FIXME: There must be an easier way!
+    TIter Next(gROOT->GetListOfCanvases());
+    TCanvas *c;
+    while ((c=(TCanvas*)Next()))
+        c->Disconnect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)", this,
+                      "EventInfo(Int_t,Int_t,Int_t,TObject*)");
+
+    // Now delete the data members
+    if (fTime)
+        delete fTime;
+    if (fObservatory)
+        delete fObservatory;
+
+    if (fToolTip)
+    {
+        fToolTip->Hide();
+        delete fToolTip;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Radius of FOV using the pixsize [arcsec/pix], width
+// and height [pixel] of image
+//
+void MAstroCatalog::SetRadiusFOV(Double_t pixsize, Double_t w, Double_t h)
+{
+    // pixsize [arcsec/pixel]
+    // w       [pixel]
+    // h       [pixel]
+    const Double_t scale = TMath::Hypot(w, h)/2;
+    SetRadiusFOV(scale*pixsize/3600);
+} 
+
+// --------------------------------------------------------------------------
+//
+// Snippet to for reading catalog files.
+//
+TString MAstroCatalog::FindToken(TString &line, Char_t tok)
+{
+    Ssiz_t token = line.First(tok);
+    if (token<0)
+    {
+        const TString copy(line);
+        line = "";
+        return copy;
+    }
+
+    const TString res = line(0, token);
+    line.Remove(0, token+1);
+    return res;
+}
+
+// --------------------------------------------------------------------------
+//
+// return int correspoding to TString
+//
+Int_t MAstroCatalog::atoi(const TString &s)
+{
+    return const_cast<TString&>(s).Atoi();
+}
+
+// --------------------------------------------------------------------------
+//
+// return float correspoding to TString
+//
+Float_t MAstroCatalog::atof(const TString &s)
+{
+    return const_cast<TString&>(s).Atof();
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a xephem catalog, set bit kHasChahanged.
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadXephem(TString catalog)
+{
+    gLog << inf << "Reading Xephem catalog: " << catalog << endl;
+
+    gSystem->ExpandPathName(catalog);
+    if (gSystem->AccessPathName(catalog, kReadPermission))
+    {
+        gLog << inf2 << "Searching Xephem catalog " << catalog << " in " << kDefaultPath << endl;
+        catalog.Prepend(kDefaultPath);
+    }
+
+    izstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t pos=0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        pos++;
+
+        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 #" << pos << ": " << row << endl;
+            continue;
+        }
+
+        cnt++;
+
+        const Double_t mag = atof(m);
+
+        maxmag = TMath::Max(maxmag, mag);
+
+        if (mag>fLimMag)
+            continue;
+
+        if (epoch.Atoi()!=2000)
+        {
+            gLog << warn << "Epoch != 2000... skipped." << endl;
+            continue;
+        }
+
+        Double_t ra0, dec0;
+        MAstro::Coordinate2Angle(r, ra0);
+        MAstro::Coordinate2Angle(d, dec0);
+
+        ra0  *= TMath::Pi()/12;
+        dec0 *= TMath::Pi()/180;
+
+        if (AddObject(ra0, dec0, mag, name))
+            add++;
+    }
+    gLog << inf << "Read " << add << " out of " << cnt << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a NGC2000 catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadNGC2000(TString catalog)
+{
+    gLog << inf << "Reading NGC2000 catalog: " << catalog << endl;
+
+    gSystem->ExpandPathName(catalog);
+    if (gSystem->AccessPathName(catalog, kReadPermission))
+    {
+        gLog << inf2 << "Searching NGC2000 catalog " << catalog << " in " << kDefaultPath << endl;
+        catalog.Prepend(kDefaultPath);
+    }
+
+    izstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        cnt++;
+
+        const Int_t   rah  = atoi(row(13, 2));
+        const Float_t ram  = atof(row(16, 4));
+        const Char_t  decs = row(22);
+        const Int_t   decd = atoi(row(23, 2));
+        const Int_t   decm = atoi(row(26, 2));
+        const TString m    = row(43, 4);
+
+        if (m.Strip().IsNull())
+            continue;
+
+        n++;
+
+        const Double_t mag = atof(m);
+
+        maxmag = TMath::Max(maxmag, mag);
+
+        if (mag>fLimMag)
+            continue;
+
+        const Double_t ra  = MAstro::Hms2Rad(rah,  (int)ram, fmod(ram, 1)*60);
+        const Double_t dec = MAstro::Dms2Rad(decd, decm, 0, decs);
+
+        if (AddObject(ra, dec, mag, row(0,8)))
+            add++;
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a Bright Star Catalog catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadBSC(TString catalog)
+{
+    gLog << inf << "Reading Bright Star Catalog (BSC5) catalog: " << catalog << endl;
+
+    gSystem->ExpandPathName(catalog);
+    if (gSystem->AccessPathName(catalog, kReadPermission))
+    {
+        gLog << inf2 << "Searching Bright Star catalog " << catalog << " in " << kDefaultPath << endl;
+        catalog.Prepend(kDefaultPath);
+    }
+
+    izstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        cnt++;
+
+        const Int_t   rah    = atoi(row(75, 2));
+        const Int_t   ram    = atoi(row(77, 2));
+        const Float_t ras    = atof(row(79, 4));
+        const Char_t  decsgn = row(83);
+        const Int_t   decd   = atoi(row(84, 2));
+        const Int_t   decm   = atoi(row(86, 2));
+        const Int_t   decs   = atoi(row(88, 2));
+        const TString m      = row(102, 5);
+
+        if (m.Strip().IsNull())
+            continue;
+
+        n++;
+
+        const Double_t mag = atof(m.Data());
+
+        maxmag = TMath::Max(maxmag, mag);
+
+        if (mag>fLimMag)
+            continue;
+
+        const Double_t ra  = MAstro::Hms2Rad(rah, ram, ras);
+        const Double_t dec = MAstro::Dms2Rad(decd, decm, decs, decsgn);
+
+        if (AddObject(ra, dec, mag, row(4,9)))
+            add++;
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a ascii heasarc ppm catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+// If the second argument is given all survived stars are written
+// to a file outname. This files will contain an apropriate compressed
+// file format. You can read such files again using ReadCompressed.
+//
+// FIXME: A General loader for heasarc catlogs is missing, see
+//        http://heasarc.gsfc.nasa.gov/W3Browse/star-catalog/
+//
+Int_t MAstroCatalog::ReadHeasarcPPM(TString catalog, TString outname)
+{
+    gLog << inf << "Reading Heasarc PPM catalog: " << catalog << endl;
+
+    gSystem->ExpandPathName(catalog);
+    if (gSystem->AccessPathName(catalog, kReadPermission))
+    {
+        gLog << inf2 << "Searching Heasarc PPM catalog " << catalog << " in " << kDefaultPath << endl;
+        catalog.Prepend(kDefaultPath);
+    }
+
+    izstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    ofstream *fout = outname.IsNull() ? 0 : new ofstream(outname);
+    if (fout && !*fout)
+    {
+        gLog << warn << "Cannot open output file " << outname << ": ";
+        gLog << strerror(errno) << endl;
+        delete fout;
+        fout = 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        cnt++;
+
+        if (!row.BeginsWith("PPM "))
+            continue;
+
+        const TString name = row(0, row.First('|'));
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        const TString vmag = row(0, row.First('|'));
+
+        n++;
+        const Double_t mag = atof(vmag.Data());
+        maxmag = TMath::Max(maxmag, mag);
+        if (mag>fLimMag)
+            continue;
+
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        const TString ra = row(0, row.First('|'));
+        row = row(row.First('|')+1, row.Length());
+        const TString de = row(0, row.First('|'));
+        row = row(row.First('|')+1, row.Length());
+
+        Char_t sgn;
+        Int_t d, m;
+        Float_t s;
+        if (sscanf(ra.Data(), "%d %d %f", &d, &m, &s)!=3)
+        {
+            // gLog << "Error loading entry in line " << i << endl;
+            continue;
+        }
+        const Double_t ra0 = MAstro::Hms2Rad(d, m, s);
+
+        if (sscanf(de.Data(), "%c%d %d %f", &sgn, &d, &m, &s)!=4)
+        {
+            // gLog << "Error loading entry in line " << i << endl;
+            continue;
+        }
+        const Double_t de0 = MAstro::Dms2Rad(d, m, s, sgn);
+
+        if (!AddObject(ra0, de0, mag, name))
+            continue;
+
+        add++;
+
+        if (fout)
+            ((MVector3*)fList.Last())->WriteBinary(*fout);
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a MAstroCatalog compressed catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadCompressed(TString catalog)
+{
+    SetBit(kHasChanged);
+
+    gLog << inf << "Reading MAstroCatalog compressed catalog: " << catalog << endl;
+
+    gSystem->ExpandPathName(catalog);
+    if (gSystem->AccessPathName(catalog, kReadPermission))
+    {
+        gLog << inf2 << "Searching MAstroCatalog comressed catalog " << catalog << " in " << kDefaultPath << endl;
+        catalog.Prepend(kDefaultPath);
+    }
+
+    izstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    MVector3 entry;
+
+    while (1)
+    {
+        cnt++;
+
+        entry.ReadBinary(fin);
+        if (!fin)
+            break;
+
+        n++;
+
+        const Double_t mag = entry.Magnitude();
+        maxmag = TMath::Max(maxmag, mag);
+        if (mag>fLimMag)
+            continue;
+
+        if (entry.Angle(fRaDec)*TMath::RadToDeg()>fRadiusFOV)
+            continue;
+
+        fList.Add(entry.Clone());
+        add++;
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add an object to the star catalog manually. Return true if the object
+// was added and false otherwise (criteria is the FOV)
+//
+Bool_t MAstroCatalog::AddObject(Float_t ra, Float_t dec, Float_t mag, TString name)
+{
+    MVector3 *star = new MVector3;
+    star->SetRaDec(ra, dec, mag);
+    star->SetName(name);
+
+    if (star->Angle(fRaDec)*TMath::RadToDeg()>fRadiusFOV)
+    {
+        delete star;
+        return 0;
+    }
+
+    SetBit(kHasChanged);
+    fList.AddLast(star);
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the visibility curve (altitude vs time) for the current time
+// and observatory for the catalog entry with name name.
+// If name==0 the name of the TGraph is taken instead.
+// The day is divided into as many points as the graph has
+// points. If the graph has no points the default is 96.
+//
+void MAstroCatalog::GetVisibilityCurve(TGraph &g, const char *name) const
+{
+    if (!fTime || !fObservatory)
+    {
+        g.Set(0);
+        return;
+    }
+
+    const Bool_t ismoon = TString(name).CompareTo("moon", TString::kIgnoreCase)==0;
+
+    MVector3 *star = ismoon ? 0 : static_cast<MVector3*>(FindObject(name ? name : g.GetName()));
+    if (!star && !ismoon)
+        return;
+
+    const Double_t mjd = TMath::Floor(fTime->GetMjd());
+    const Double_t lng = fObservatory->GetLongitudeDeg()/360;
+
+    if (g.GetN()==0)
+        g.Set(96);
+
+    for (int i=0; i<g.GetN(); i++)
+    {
+        const Double_t offset = (Double_t)i/g.GetN() - 0.5;
+
+        const MTime tm(mjd-lng+offset);
+
+        MVector3 v = star ? *star : MVector3();
+        if (!star)
+        {
+            Double_t ra, dec;
+            MAstro::GetMoonRaDec(tm.GetMjd(), ra, dec);
+            v = MVector3(ra, dec);
+        }
+
+        v *= MAstroSky2Local(tm.GetGmst(), *fObservatory);
+
+        g.SetPoint(i, tm.GetAxisTime(), 90-v.Theta()*TMath::RadToDeg());
+    }
+
+    TH1   &h = *g.GetHistogram();
+    TAxis &x = *h.GetXaxis();
+    TAxis &y = *h.GetYaxis();
+
+    y.SetTitle("Altitude [\\circ]");
+    y.CenterTitle();
+
+    x.SetTitle("UTC");
+    x.CenterTitle();
+    x.SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+    x.SetTimeDisplay(1);
+    x.SetLabelSize(0.033);
+
+    const Double_t atm = MTime(mjd).GetAxisTime();
+
+    x.SetRangeUser(atm-(0.5+lng)*24*60*60+15*60, atm+(0.5-lng)*24*60*60-15*60);
+
+    g.SetMinimum(5);
+    g.SetMaximum(90);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Range of pad. If something has changed create and draw new primitives.
+// Paint all gui primitives.
+//
+void MAstroCatalog::Paint(Option_t *o)
+{
+    if (!fRaDec.IsValid())
+        return;
+
+    SetRangePad(o);
+
+    // In the case MAstroCatalog has been loaded from a file
+    // kHasChanged is not set, but fMapG.GetSize() is ==0
+    if (TestBit(kHasChanged) || fMapG.GetSize()==0)
+        DrawPrimitives(o);
+
+    fMapG.Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Range of pad if pad available. If something has changed create
+// and draw new primitives. Paint all gui primitives to the Drawable with
+// Id id. This can be used to be able to
+//
+/*
+void MAstroCatalog::PaintImg(Int_t id, Option_t *o)
+{
+    if (gPad)
+        SetRangePad(o);
+
+    if (TestBit(kHasChanged))
+    {
+        if (id>0)
+            gPad=0;
+        DrawPrimitives(o);
+    }
+
+    fMapG.Paint(id, fRadiusFOV);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Set Range of pad. If something has changed create and draw new primitives.
+// Paint all gui primitives.
+//
+// Because in some kind of multi-threaded environments gPad doesn't stay
+// the same in a single thread (because it might be changed in the same
+// thread inside a gui updating timer for example) we have to secure the
+// usage of gPad with a bit. This is also not multi-thread safe against
+// calling this function, but the function should work well in multi-
+// threaded environments. Never call this function from different threads
+// simultaneously.
+//
+void MAstroCatalog::PaintImg(unsigned char *buf, int w, int h, Option_t *o)
+{
+    if (!o)
+        o = "local mirrorx yellow * =";
+
+    if (TestBit(kHasChanged))
+    {
+        SetBit(kDrawingImage);
+        DrawPrimitives(o);
+        ResetBit(kDrawingImage);
+    }
+
+    fMapG.Paint(buf, w, h, fRadiusFOV);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a black marker at the position of the star. Create a corresponding
+// tooltip with the coordinates.
+// x, y: Pad Coordinates to draw star
+// v: Sky position (Ra/Dec) of the star
+// col: Color of marker (<0 mean transparent)
+// txt: additional tooltip text
+// resize: means resize the marker according to the magnitude
+//
+void MAstroCatalog::DrawStar(Double_t x, Double_t y, const TVector3 &v, Int_t col, const char *txt, Bool_t resize)
+{
+    const Double_t ra  = v.Phi()*TMath::RadToDeg()/15;
+    const Double_t dec = (TMath::Pi()/2-v.Theta())*TMath::RadToDeg();
+
+    const Double_t mag = -2.5*log10(v.Mag());
+
+    TString str(v.GetName());
+    if (!str.IsNull())
+        str += ":  ";
+    str += MString::Format("Ra=%.2fh  Dec=%.1fd  Mag=%.1f", ra, dec, mag);
+    if (txt)
+    {
+        str += "  (";
+        str += txt;
+        str += ")";
+    }
+
+    // draw star on the camera display
+    TMarker *tip=new TMarker(x, y, kDot);
+    tip->SetMarkerColor(col);
+
+    TAttMarker::Copy(*tip);
+
+    fMapG.Add(tip, new TString(str));
+
+    if (resize)
+        tip->SetMarkerSize((10 - (mag>1 ? mag : 1))/15);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set pad as modified.
+//
+void MAstroCatalog::Update(Bool_t upd)
+{
+    SetBit(kHasChanged);
+    if (gPad && TestBit(kMustCleanup))
+    {
+        gPad->Modified();
+        if (upd)
+            gPad->Update();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the observation time. Necessary to use local coordinate
+// system. The MTime object is cloned.
+//
+void MAstroCatalog::SetTime(const MTime &time)
+{
+    if (fTime)
+        delete fTime;
+    fTime=(MTime*)time.Clone();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the observatory location. Necessary to use local coordinate
+// system. The MObservatory object is cloned.
+//
+void MAstroCatalog::SetObservatory(const MObservatory &obs)
+{
+    if (fObservatory)
+        delete fObservatory;
+    fObservatory=new MObservatory;
+    obs.Copy(*fObservatory);
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert the vector to pad coordinates. After conversion
+// the x- coordinate of the vector must be the x coordinate
+// of the pad - the same for y. If the coordinate is inside
+// the current draw area return kTRUE, otherwise kFALSE.
+// If it is an invalid coordinate return kERROR
+//
+Int_t MAstroCatalog::ConvertToPad(const TVector3 &w0, TVector2 &v) const
+{
+    TVector3 w(w0);
+
+    // Stretch such, that the Z-component is alwas the same. Now
+    // X and Y contains the intersection point between the star-light
+    // and the plain of a virtual plain screen (ccd...)
+    if (TestBit(kPlainScreen))
+        w *= 1./w(2);
+
+    w *= TMath::RadToDeg(); // FIXME: *conversion factor?
+    v.Set(TestBit(kMirrorX) ? -w(0) : w(0),
+          TestBit(kMirrorY) ? -w(1) : w(1));
+
+    v=v.Rotate(fAngle*TMath::DegToRad());
+
+    if (w(2)<0)
+        return kERROR;
+
+    if (TestBit(kDrawingImage) || !gPad)
+        return v.Mod2()<fRadiusFOV*fRadiusFOV;
+
+    return v.X()>gPad->GetX1() && v.Y()>gPad->GetY1() &&
+           v.X()<gPad->GetX2() && v.Y()<gPad->GetY2();
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert theta/phi coordinates of v by TRotation into new coordinate
+// system and convert the coordinated to pad by ConvertToPad.
+// The result is retunred in v.
+//
+Int_t MAstroCatalog::Convert(const TRotation &rot, TVector2 &v) const
+{
+    MVector3 w;
+    w.SetMagThetaPhi(1, v.Y(), v.X());
+    w *= rot;
+
+    return ConvertToPad(w, v);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a line from v to v+(dx,dy) using Convert/ConvertToPad to get the
+// corresponding pad coordinates.
+//
+Bool_t MAstroCatalog::DrawLine(const TVector2 &v, Int_t dx, Int_t dy, const TRotation &rot, Int_t type)
+{
+    const TVector2 add(dx*TMath::DegToRad(), dy*TMath::DegToRad());
+
+    // Define all lines in the same direction
+    const TVector2 va(dy==1?v:v+add);
+    const TVector2 vb(dy==1?v+add:v);
+
+    TVector2 v0(va);
+    TVector2 v1(vb);
+
+    const Int_t rc0 = Convert(rot, v0);
+    const Int_t rc1 = Convert(rot, v1);
+
+    // Both are kFALSE or both are kERROR
+    if ((rc0|rc1)==kFALSE || (rc0&rc1)==kERROR)
+        return kFALSE;
+
+    TLine *line = new TLine(v0.X(), v0.Y(), v1.X(), v1.Y());
+    if (type==1)
+        dynamic_cast<TAttLine&>(fAttLineSky).Copy(dynamic_cast<TAttLine&>(*line));
+    else
+        dynamic_cast<TAttLine&>(fAttLineLocal).Copy(dynamic_cast<TAttLine&>(*line));
+    fMapG.Add(line);
+
+    if (dx!=0)
+        return kTRUE;
+
+    const TVector2 deg = va*TMath::RadToDeg();
+
+    const TString txt = type==1 ?
+        MString::Format("Ra=%.2fh  Dec=%.1fd", fmod(deg.X()/15+48, 24),  fmod(90-deg.Y()+270,180)-90) :
+        MString::Format("Zd=%.1fd  Az=%.1fd",  fmod(deg.Y()+270,180)-90, fmod(deg.X()+720, 360));
+
+    TMarker *tip=new TMarker(v0.X(), v0.Y(), kDot);
+    tip->SetMarkerColor(kWhite+type*2);
+    fMapG.Add(tip, new TString(txt));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use "local" draw option to align the display to the local
+// coordinate system instead of the sky coordinate system.
+// dx, dy are arrays storing recuresively all touched points
+// stepx, stepy are the step-size of the current grid.
+//
+void MAstroCatalog::Draw(const TVector2 &v0, const TRotation &rot, TArrayI &dx, TArrayI &dy, Int_t stepx, Int_t stepy, Int_t type)
+{
+    // Calculate the end point
+    const TVector2 v1 = v0 + TVector2(dx[0]*TMath::DegToRad(), dy[0]*TMath::DegToRad());
+
+    // Check whether the point has already been touched.
+    Int_t idx[] = {1, 1, 1, 1};
+
+    Int_t dirs[4][2] = { {0, stepy}, {stepx, 0}, {0, -stepy}, {-stepx, 0} };
+
+    // Check for ambiguities.
+    for (int i=0; i<dx.GetSize(); i++)
+    {
+        for (int j=0; j<4; j++)
+        {
+            const Bool_t rcx0 = (dx[i]+720)%360==(dx[0]+dirs[j][0]+720)%360;
+            const Bool_t rcy0 = (dy[i]+360)%180==(dy[0]+dirs[j][1]+360)%180;
+            if (rcx0&&rcy0)
+                idx[j] = 0;
+        }
+    }
+
+    // Enhance size of array by 1, copy current
+    // position as last entry
+    dx.Set(dx.GetSize()+1);
+    dy.Set(dy.GetSize()+1);
+
+    dx[dx.GetSize()-1] = dx[0];
+    dy[dy.GetSize()-1] = dy[0];
+
+    // Store current positon
+    const Int_t d[2] = { dx[0], dy[0] };
+
+    for (int i=0; i<4; i++)
+        if (idx[i])
+        {
+            // Calculate new position
+            dx[0] = d[0]+dirs[i][0];
+            dy[0] = d[1]+dirs[i][1];
+
+            // Draw corresponding line and iterate through grid
+            if (DrawLine(v1, dirs[i][0], dirs[i][1], rot, type))
+                Draw(v0, rot, dx, dy, stepx, stepy, type);
+
+            dx[0]=d[0];
+            dy[0]=d[1];
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a grid recursively around the point v0 (either Ra/Dec or Zd/Az)
+// The points in the grid are converted by a TRotation and CovertToPad
+// to pad coordinates. The type arguemnts is neccessary to create the
+// correct tooltip (Ra/Dec, Zd/Az) at the grid-points.
+// From the pointing position the step-size of teh gris is caluclated.
+//
+void MAstroCatalog::DrawGrid(const TVector3 &v0, const TRotation &rot, Int_t type)
+{
+    TArrayI dx(1);
+    TArrayI dy(1);
+
+    // align to 1deg boundary
+    TVector2 v(v0.Phi()*TMath::RadToDeg(), v0.Theta()*TMath::RadToDeg());
+    v.Set((Float_t)TMath::Nint(v.X()), (Float_t)TMath::Nint(v.Y()));
+
+    // calculate stepsizes based on visible FOV
+    Int_t stepx = 1;
+
+    if (v.Y()<fRadiusFOV || v.Y()>180-fRadiusFOV)
+        stepx=36;
+    else
+    {
+        // This is a rough estimate how many degrees are visible
+        const Float_t m = log(fRadiusFOV/180.)/log(90./(fRadiusFOV+1)+1);
+        const Float_t t = log(180.)-m*log(fRadiusFOV);
+        const Float_t f = m*log(90-fabs(90-v.Y()))+t;
+        const Int_t nx = (Int_t)(exp(f)+0.5);
+        stepx = nx<4 ? 1 : nx/4;
+        if (stepx>36)
+            stepx=36;
+    }
+
+    const Int_t ny = (Int_t)(fRadiusFOV+1);
+    Int_t stepy = ny<4 ? 1 : ny/4;
+
+    // align stepsizes to be devisor or 180 and 90
+    while (180%stepx)
+        stepx++;
+    while (90%stepy)
+        stepy++;
+
+    // align to step-size boundary (search for the nearest one)
+    Int_t dv = 1;
+    while ((int)(v.X())%stepx)
+    {
+        v.Set(v.X()+dv, v.Y());
+        dv = -TMath::Sign(TMath::Abs(dv)+1, dv);
+    }
+
+    dv = 1;
+    while ((int)(v.Y())%stepy)
+    {
+        v.Set(v.X(), v.Y()+dv);
+        dv = -TMath::Sign(TMath::Abs(dv)+1, dv);
+    }
+
+    // draw...
+    v *= TMath::DegToRad();
+
+    Draw(v, rot, dx, dy, stepx, stepy, type);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get a rotation matrix which aligns the pointing position
+// to the center of the x,y plain
+//
+TRotation MAstroCatalog::AlignCoordinates(const TVector3 &v) const
+{
+    TRotation trans;
+    trans.RotateZ(-v.Phi());
+    trans.RotateY(-v.Theta());
+    trans.RotateZ(-TMath::Pi()/2);
+    return trans;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the rotation matrix which converts either sky or
+// local coordinates to coordinates which pole is the current
+// pointing direction.
+//
+TRotation MAstroCatalog::GetGrid(Bool_t local)
+{
+    const Bool_t enable = fTime && fObservatory;
+
+    // If sky coordinate view is requested get rotation matrix and
+    // draw corresponding sky-grid and if possible local grid
+    if (!local)
+    {
+        const TRotation trans(AlignCoordinates(fRaDec));
+
+        DrawGrid(fRaDec, trans, 1);
+
+        if (enable)
+        {
+            const MAstroSky2Local rot(*fTime, *fObservatory);
+            DrawGrid(rot*fRaDec, trans*rot.Inverse(), 2);
+        }
+
+        // Return the correct rotation matrix
+        return trans;
+    }
+
+    // If local coordinate view is requested get rotation matrix and
+    // draw corresponding sky-grid and if possible local grid
+    if (local && enable)
+    {
+        const MAstroSky2Local rot(*fTime, *fObservatory);
+
+        const TRotation trans(AlignCoordinates(rot*fRaDec));
+
+        DrawGrid(fRaDec,     trans*rot, 1);
+        DrawGrid(rot*fRaDec, trans,     2);
+
+        // Return the correct rotation matrix
+        return trans*rot;
+    }
+
+    return TRotation();
+}
+
+// --------------------------------------------------------------------------
+//
+// Create the title for the pad.
+//
+TString MAstroCatalog::GetPadTitle() const
+{
+    const Double_t ra  = fRaDec.Phi()*TMath::RadToDeg();
+    const Double_t dec = (TMath::Pi()/2-fRaDec.Theta())*TMath::RadToDeg();
+
+    TString txt;
+    txt += MString::Format("\\alpha=%.2fh ",      fmod(ra/15+48, 24));
+    txt += MString::Format("\\delta=%.1f\\circ ", fmod(dec+270,180)-90);
+    txt += MString::Format("/ 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 += MString::Format("  \\theta=%.1f\\circ ", fmod(zd+270,180)-90);
+    txt += MString::Format("\\phi=%.1f\\circ ",     fmod(az+720, 360));
+    txt += MString::Format(" / \\rho=%.1f\\circ",   rho*TMath::RadToDeg());
+    txt += "}{<";
+    txt += fTime->GetSqlDateTime();
+    txt += ">}";
+    return txt;
+}
+
+// --------------------------------------------------------------------------
+//
+// To overlay the catalog make sure, that in any case you are using
+// the 'same' option.
+//
+// If you want to overlay this on top of any picture which is created
+// by derotation of the camera plain you have to use the 'mirror' option
+// the compensate the mirroring of the image in the camera plain.
+//
+// If you have already compensated this by x=-x and y=-y when creating
+// the histogram you can simply overlay the catalog.
+//
+// To overlay the catalog on a 2D histogram the histogram must have
+// units of degrees (which are plain, like you directly convert the
+// camera units by multiplication to degrees)
+//
+// To be 100% exact you must use the option 'plain' which assumes a plain
+// screen. This is not necessary for the MAGIC-camera because the
+// difference between both is less than 1e-3.
+//
+// You should always be aware of the fact, that the shown stars and the
+// displayed grid is the ideal case, like a reflection on a virtual
+// perfectly aligned central mirror. In reality the star-positions are
+// smeared to the edge of the camera the more the distance to the center
+// is, such that the center of gravity of the light distribution might
+// be more far away from the center than the display shows.
+//
+// If you want the stars to be displayed as circles with a size
+// showing their magnitude use "*" as an option.
+//
+// Use 'white'  to display white instead of black stars
+// Use 'yellow' to display white instead of black stars
+//
+//
+void MAstroCatalog::AddPrimitives(TString o)
+{
+    const Bool_t same   = o.Contains("same",    TString::kIgnoreCase);
+    const Bool_t local  = o.Contains("local",   TString::kIgnoreCase);
+    const Bool_t mirx   = o.Contains("mirrorx", TString::kIgnoreCase);
+    const Bool_t miry   = o.Contains("mirrory", TString::kIgnoreCase);
+    const Bool_t mirror = o.Contains("mirror",  TString::kIgnoreCase) && !mirx && !miry;
+    const Bool_t size   = o.Contains("*",       TString::kIgnoreCase);
+    const Bool_t white  = o.Contains("white",   TString::kIgnoreCase);
+    const Bool_t yellow = o.Contains("yellow",  TString::kIgnoreCase) && !white;
+    const Bool_t rot180 = o.Contains("180",     TString::kIgnoreCase);
+    const Bool_t rot270 = o.Contains("270",     TString::kIgnoreCase);
+    const Bool_t rot90  = o.Contains("90",      TString::kIgnoreCase);
+
+    if (white)
+        SetMarkerColor(kWhite);
+
+    fAngle = 0;
+    if (rot90)
+        fAngle=90;
+    if (rot180)
+        fAngle=180;
+    if (rot270)
+        fAngle=270;
+
+    // X is vice versa, because ra is defined anti-clockwise
+    mirx || mirror ? ResetBit(kMirrorX) : SetBit(kMirrorX);
+    miry || mirror ? SetBit(kMirrorY) : ResetBit(kMirrorY);
+
+    const TRotation rot(GetGrid(local));
+
+    TIter Next(&fList);
+    MVector3 *v=0;
+    while ((v=(MVector3*)Next()))
+    {
+        if (v->Magnitude()>fLimMag)
+            continue;
+
+        TVector2 s(v->Phi(), v->Theta());
+        if (Convert(rot, s)==kTRUE)
+            DrawStar(s.X(), s.Y(), *v, yellow?kYellow:(white?kWhite:kBlack), 0, size);
+    }
+
+    if (!same && !TestBit(kDrawingImage) && gPad)
+    {
+        TPaveText *pv = new TPaveText(0.01, 0.90, 0.63, 0.99, "brNDC");
+        pv->AddText(GetPadTitle());
+        fMapG.Add(pv);
+    }
+
+    TMarker *mk=new TMarker(0, 0, kMultiply);
+    mk->SetMarkerColor(white||yellow?kWhite:kBlack);
+    mk->SetMarkerSize(1.5);
+    fMapG.Add(mk);
+}
+
+// --------------------------------------------------------------------------
+//
+// Do nothing if 'same' option given.
+// Otherwise set pad-range such that x- and y- coordinates have the same
+// step-size
+//
+void MAstroCatalog::SetRangePad(Option_t *o)
+{
+    if (TString(o).Contains("same", TString::kIgnoreCase))
+        return;
+
+    const Double_t edge = fRadiusFOV/TMath::Sqrt(2.);
+    //gPad->Range(-edge, -edge, edge, edge);
+
+    const Float_t w = gPad->GetWw();
+    const Float_t h = gPad->GetWh();
+
+    if (w<h)
+        gPad->Range(-edge, -edge*h/w, edge, edge*h/w);
+    else
+        gPad->Range(-edge*w/h, -edge, edge*w/h, edge);
+}
+
+// --------------------------------------------------------------------------
+//
+// Bends some pointers into the right direction...
+// Calls TAttLine::SetLineAttributes and connects some signals
+// to the gui to recreate the gui elements if something has changed.
+//
+void MAstroCatalog::SetLineAttributes(MAttLine &att)
+{
+    if (!gPad)
+        return;
+
+    gPad->SetSelected(&att);
+    gROOT->SetSelectedPrimitive(&att);
+
+    att.SetLineAttributes();
+
+    TQObject::Connect("TGColorSelect", "ColorSelected(Pixel_t)", "MAstroCatalog", this, "ForceUpdate()");
+    TQObject::Connect("TGListBox",     "Selected(Int_t)",        "MAstroCatalog", this, "ForceUpdate()");
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls TAttMarker::SetMarkerAttributes and connects some signals
+// to the gui to recreate the gui elements if something has changed.
+//
+void MAstroCatalog::SetMarkerAttributes()
+{
+    if (!gPad)
+        return;
+
+    TAttMarker::SetMarkerAttributes();
+
+    // Make sure that if something is changed the gui elements
+    // are recreated
+    TQObject::Connect("TGedMarkerSelect", "MarkerSelected(Style_t)", "MAstroCatalog", this, "ForceUpdate()");
+    TQObject::Connect("TGColorSelect",    "ColorSelected(Pixel_t)",  "MAstroCatalog", this, "ForceUpdate()");
+    TQObject::Connect("TGListBox",        "Selected(Int_t)",         "MAstroCatalog", this, "ForceUpdate()");
+}
+
+void MAstroCatalog::DrawPrimitives(Option_t *o)
+{
+    fMapG.Delete();
+
+    if (!TestBit(kDrawingImage) && gPad)
+        SetRangePad(o);
+
+#ifdef DEBUG
+    TStopwatch clk;
+    clk.Start();
+#endif
+    AddPrimitives(o);
+#ifdef DEBUG
+    clk.Stop();
+    clk.Print();
+#endif
+
+    // Append to a possible second pad
+    if (!TestBit(kDrawingImage) && gPad && !gPad->GetListOfPrimitives()->FindObject(this))
+        AppendPad(o);
+
+    ResetBit(kHasChanged);
+}
+
+// --------------------------------------------------------------------------
+//
+// Append "this" to current pad
+// set bit kHasChanged to recreate all gui elements
+// Connect signal
+//
+void MAstroCatalog::Draw(Option_t *o)
+{
+    // Append to first pad
+    AppendPad(o);
+
+    // If contents have not previously changed make sure that
+    // all primitives are recreated.
+    SetBit(kHasChanged);
+
+    // Connect all TCanvas::ProcessedEvent to this->EventInfo
+    // This means, that after TCanvas has processed an event
+    // EventInfo of this class is called, see TCanvas::HandleInput
+    gPad->GetCanvas()->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",
+                               "MAstroCatalog", this,
+                               "EventInfo(Int_t,Int_t,Int_t,TObject*)");
+}
+
+// --------------------------------------------------------------------------
+//
+// This function was connected to all created canvases. It is used
+// to redirect GetObjectInfo into our own status bar.
+//
+// The 'connection' is done in Draw. It seems that 'connected'
+// functions must be public.
+//
+void MAstroCatalog::EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected)
+{
+    TCanvas *c = (TCanvas*)gTQSender;
+
+    gPad = c ? c->GetSelectedPad() : NULL;
+    if (!gPad)
+        return;
+
+
+    // Try to find a corresponding object with kCannotPick set and
+    // an available TString (for a tool tip)
+    TString str;
+    if (!selected || selected==this)
+        selected =  fMapG.PickObject(px, py, str);
+
+    if (!selected)
+        return;
+
+    // Handle some gui events
+    switch (event)
+    {
+    case kMouseMotion:
+        if (fToolTip && !fToolTip->IsMapped() && !str.IsNull())
+            ShowToolTip(px, py, str);
+        break;
+
+    case kMouseLeave:
+        if (fToolTip && fToolTip->IsMapped())
+            fToolTip->Hide();
+        break;
+
+    case kKeyPress:
+        ExecuteEvent(kKeyPress, px, py);
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Handle keyboard events.
+//
+void MAstroCatalog::ExecuteEventKbd(Int_t /*keycode*/, Int_t keysym)
+{
+    Double_t dra =0;
+    Double_t ddec=0;
+
+    switch (keysym)
+    {
+    case kKey_Left:
+        dra = -TMath::DegToRad();
+        break;
+    case kKey_Right:
+        dra = +TMath::DegToRad();
+        break;
+    case kKey_Up:
+        ddec = +TMath::DegToRad();
+        break;
+    case kKey_Down:
+        ddec = -TMath::DegToRad();
+        break;
+    case kKey_Plus:
+        SetRadiusFOV(fRadiusFOV+1);
+        break;
+    case kKey_Minus:
+        SetRadiusFOV(fRadiusFOV-1);
+        break;
+
+    default:
+        return;
+    }
+
+    const Double_t r = fRaDec.Phi();
+    const Double_t d = TMath::Pi()/2-fRaDec.Theta();
+
+    SetRaDec(r+dra, d+ddec);
+
+    gPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a gui event on the camera
+//
+void MAstroCatalog::ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2)
+{
+    if (!TestBit(kGuiActive))
+        return;
+
+    if (event==kKeyPress)
+        ExecuteEventKbd(mp1, mp2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Displays a tooltip
+//
+void MAstroCatalog::ShowToolTip(Int_t px, Int_t py, const char *txt)
+{
+    if (TestBit(kNoToolTips))
+        return;
+
+    Int_t x=0;
+    Int_t y=0;
+
+    const Window_t id1 = gVirtualX->GetWindowID(gPad->GetCanvasID());
+    const Window_t id2 = fToolTip->GetParent()->GetId();
+
+    Window_t id3;
+    gVirtualX->TranslateCoordinates(id1, id2, px, py, x, y, id3);
+
+    // Show tool tip
+    fToolTip->SetText(txt);
+    fToolTip->Show(x+4, y+4);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate distance to primitive by checking all gui elements
+//
+Int_t MAstroCatalog::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    return fMapG.DistancetoPrimitive(px, py);
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns string containing info about the object at position (px,py).
+// Returned string will be re-used (lock in MT environment).
+//
+char *MAstroCatalog::GetObjectInfo(Int_t px, Int_t py) const
+{
+    return fMapG.GetObjectInfo(px, py);
+}
Index: branches/Mars_McMismatchStudy/mastro/MAstroCatalog.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstroCatalog.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstroCatalog.h	(revision 17960)
@@ -0,0 +1,184 @@
+#ifndef MARS_MAstroCatalog
+#define MARS_MAstroCatalog
+
+#ifndef MARS_MVector3
+#include "MVector3.h"
+#endif
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+#ifndef ROOT_TAttLine
+#include <TAttLine.h>
+#endif
+#ifndef ROOT_TAttMarker
+#include <TAttMarker.h>
+#endif
+#ifndef MARS_MGMap
+#include <MGMap.h>
+#endif
+
+class MTime;
+class MObservatory;
+class TArrayI;
+class TGToolTip;
+class TGraph;
+
+class MAttLine : public TObject, public TAttLine
+{
+public:
+    MAttLine() { }
+    ClassDef(MAttLine, 1) // Helper class to have a TAttLine derving from TObject (for standalone GED editor)
+};
+
+class MAstroCatalog : public TObject, public TAttMarker
+{
+private:
+    static const TString kDefaultPath; //! Datacenter default path for catalogs
+
+    Double_t   fLimMag;     // [1]   Limiting Magnitude
+    Double_t   fRadiusFOV;  // [deg] Radius of Field of View
+
+    TGToolTip *fToolTip;    //! The tooltip currently displayed
+    Double_t   fAngle;      //! Rotation angle of map
+
+    MAttLine fAttLineSky;   // Line Style and color for sky coordinates
+    MAttLine fAttLineLocal; // Line Style and color for local coordinates
+
+    void ShowToolTip(Int_t px, Int_t py, const char *txt);
+    void SetLineAttributes(MAttLine &att);
+
+    TString FindToken(TString &line, Char_t tok=',');
+
+    Int_t   atoi(const TString &s);
+    Float_t atof(const TString &s);
+
+//#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,03)
+//    Bool_t fPlainScreen;  //! Just a dummy!!!! ([Set,Is]Freezed)
+//    Bool_t fNoToolTips;   //! Just a dummy!!!! ([Set,Is]Freezed)
+//#endif
+
+    virtual Int_t ConvertToPad(const TVector3 &w, TVector2 &v) const;
+    virtual void  AddPrimitives(TString o);
+    virtual void  SetRangePad(Option_t *o);
+
+    Int_t  Convert(const TRotation &rot, TVector2 &v) const;
+    void   Draw(const TVector2 &v0, const TRotation &rot, TArrayI &dx, TArrayI &dy, Int_t stepx, Int_t stepy, Int_t type);
+    void   DrawPrimitives(Option_t *o);
+    Bool_t DrawLine(const TVector2 &v0, Int_t dx, Int_t dy, const TRotation &rot, Int_t type);
+    void   DrawGrid(const TVector3 &v0, const TRotation &rot, Int_t type);
+    void   Paint(Option_t *o="");
+    Int_t  DistancetoPrimitive(Int_t px, Int_t py);
+
+protected:
+    enum {
+        kMark         = BIT(14), // A mark for the sources in the list
+        kHasChanged   = BIT(15), // Display has changed
+        kGuiActive    = BIT(16), // GUI is interactive
+        kPlainScreen  = BIT(17), // View is a plain screen view
+        kMirrorX      = BIT(18), // Mirror display in X
+        kMirrorY      = BIT(19), // Mirror display in Y
+        kNoToolTips   = BIT(20), // suppress tooltips
+        kDrawingImage = BIT(21)  // just drawing into a bitmap
+    };
+
+    MGMap    fMapG;              //! A map with all gui primitives and tooltips
+
+    TList    fList;              // List of stars loaded
+    MVector3 fRaDec;             // pointing position
+
+    MObservatory *fObservatory;  // Possible obervatory location
+    MTime        *fTime;         // Possible observation time
+
+    TRotation AlignCoordinates(const TVector3 &v) const;
+    virtual TString GetPadTitle() const;
+    TRotation GetGrid(Bool_t local);
+    void      DrawStar(Double_t x, Double_t y, const TVector3 &v, Int_t col, const char *txt=0, Bool_t resize=kFALSE);
+    void      Update(Bool_t upd=kFALSE);
+
+    void      ExecuteEventKbd(Int_t keycode, Int_t keysym);
+    void      ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2);
+    char     *GetObjectInfo(Int_t px, Int_t py) const;
+
+public:
+    MAstroCatalog();
+    ~MAstroCatalog();
+
+    void ForceUpdate() { Update(kTRUE); } // Slot for marker handling
+
+    // Setter to control the sky position and behaviour
+    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 pixsize, Double_t w, Double_t h);
+    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
+
+    // Interface to set stars
+    Int_t  ReadXephem(TString catalog = "/usr/X11R6/lib/xephem/catalogs/YBS.edb");
+    Int_t  ReadNGC2000(TString catalog = "ngc2000.dat");
+    Int_t  ReadBSC(TString catalog = "bsc5.dat");
+    Int_t  ReadHeasarcPPM(TString catalog = "heasarc_ppm.tdat", TString fout="");
+    Int_t  ReadCompressed(TString catalog);
+    Bool_t AddObject(Float_t ra, Float_t dec, Float_t mag, TString name="");
+
+    // Interface to get stars
+    TList *GetList() { return &fList; } // Return list of stars
+    UInt_t GetNumStars() const { return fList.GetEntries(); }
+    TObject *FindObject(const char *name) const { return fList.FindObject(name); }
+    TObject *FindObject(const TObject *obj) const { return fList.FindObject(obj); }
+    void MarkObject(const char *name) const { TObject *o=FindObject(name); if (o) o->SetBit(kMark); }
+
+    void GetVisibilityCurve(TGraph &g, const char *name=0) const;
+
+    // TObject
+    void Delete(Option_t * = "") { fList.Delete(); fMapG.Delete(); } // Delete list of stars
+    void Print(Option_t * = "") const { fList.Print(); } // Print all stars
+    void Draw(Option_t * = "");
+    void SetDrawOption(Option_t *option="")
+    {
+        TObject::SetDrawOption(option);
+        Update(kTRUE);
+    } //*MENU*
+
+    // Interface to Cosy
+    void PaintImg(unsigned char *buf, int w=768, int h=576, Option_t *o=0);
+
+    // Interface to line styles
+    void SetLineAttributesLocal() { SetLineAttributes(fAttLineLocal); } //*MENU*
+    void SetLineAttributesSky()   { SetLineAttributes(fAttLineSky);   } //*MENU*
+    void SetMarkerAttributes();   //*MENU*
+
+    TAttLine &GetAttLineSky() { return fAttLineSky; }
+    TAttLine &GetAttLineLocal() { return fAttLineLocal; }
+
+    virtual void EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected=0);
+
+    ClassDef(MAstroCatalog, 2) // Display class for star catalogs
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mastro/MAstroSky2Local.cc
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstroSky2Local.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstroSky2Local.cc	(revision 17960)
@@ -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-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 rotation 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.
+//
+// dzd and daz is a pointing offset, which is subtracted from the
+// calculated local coordinates correspoding to time, observatory
+// and ra/dec.
+//
+// For more information see MAstro::RotationAngle
+//
+Double_t MAstroSky2Local::RotationAngle(Double_t ra, Double_t dec, Double_t dzd, Double_t daz) const
+{
+    TVector3 v;
+    v.SetMagThetaPhi(1, TMath::Pi()/2-dec, ra);
+    v *= *this;
+
+    return MAstro::RotationAngle(ZZ(), XZ(), v.Theta()-dzd, v.Phi()-daz);
+}
Index: branches/Mars_McMismatchStudy/mastro/MAstroSky2Local.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MAstroSky2Local.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MAstroSky2Local.h	(revision 17960)
@@ -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, Double_t dzd=0, Double_t daz=0) const;
+
+    ClassDef(MAstroSky2Local, 1) // Rotation Matrix to convert sky coordinates to ideal local coordinates
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mastro/MObservatory.cc
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MObservatory.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MObservatory.cc	(revision 17960)
@@ -0,0 +1,237 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 <TArrayD.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";   
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor sets name and title of instace.
+// Default location is kMagic1
+//
+MObservatory::MObservatory(const char *name, const char *title)
+{
+    Init(name, title);
+
+    SetLocation(kMagic1);
+}
+
+// --------------------------------------------------------------------------
+//
+// For example "MObservator(MObservatory::kMagic1)"
+//
+MObservatory::MObservatory(LocationName_t key, const char *name, const char *title)
+{
+    Init(name, title);
+
+    SetLocation(key);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls SetLocation
+//
+MObservatory::MObservatory(Double_t lon, Double_t lat, const char *name)
+{
+    Init();
+
+    SetLocation(lon, lat, 0, name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls SetLocation
+//
+MObservatory::MObservatory(Double_t lon, Double_t lat, Double_t h, const char *name)
+{
+    Init();
+
+    SetLocation(lon, lat, h, name);
+}
+
+// --------------------------------------------------------------------------
+//
+// BE EXTREMLY CARFEFULL CHANGING THIS CLASS! THE TRACKING SYSTEM IS BASED
+// ON IT!
+//
+void MObservatory::SetLocation(LocationName_t name)
+{
+    switch (name)
+    {
+        // BE EXTREMLY CARFEFULL CHANGING THIS CLASS!
+        // THE TRACKING SYSTEM IS BASED ON IT!
+    case kMagic1:
+        // Values taken from the GPS Receiver (avg 24h)
+        // on 29/04/2004 at 17h30 in the counting house
+        fLatitude  = MAstro::Dms2Rad(28, 45, 42.462, '+');
+        fLongitude = MAstro::Dms2Rad(17, 53, 26.525, '-');
+        fHeight    = 2199.4; // m
+        fObservatoryName = "Observatorio del Roque de los Muchachos (Magic1)";
+        break;
+
+    case kWuerzburgCity:
+        fLatitude  = MAstro::Dms2Rad(51, 38, 48.0);
+        fLongitude = MAstro::Dms2Rad( 9, 56, 36.0);
+        fHeight    = 300;
+        fObservatoryName = "Wuerzburg City";
+        break;
+
+    case kTuorla:
+        fLatitude  = MAstro::Dms2Rad(60, 24, 57.0);
+        fLongitude = MAstro::Dms2Rad(22, 26, 42.0);
+        fHeight    = 53;
+        fObservatoryName = "Tuorla";
+        break;
+    }
+
+    fObservatoryKey = name;
+
+    fSinLatitude = TMath::Sin(fLatitude);
+    fCosLatitude = TMath::Cos(fLatitude);
+}
+
+// --------------------------------------------------------------------------
+//
+// Longitude/Latitude [rad]
+// Height             [m]
+//
+void MObservatory::SetLocation(Double_t lon, Double_t lat, Double_t h, const char *name)
+{
+    fLongitude = lon;
+    fLatitude  = lat;
+    fHeight    = h;
+
+    fSinLatitude = TMath::Sin(fLatitude);
+    fCosLatitude = TMath::Cos(fLatitude);
+
+    if (name)
+        fObservatoryName = name;
+}
+
+void MObservatory::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << underline << fObservatoryName << ":" << endl;
+    *fLog << "Latitude:  " << TMath::Abs(fLatitude*kRad2Deg)  << " deg " << (fLatitude  > 0 ? "N" : "S") << endl;
+    *fLog << "Longitude: " << TMath::Abs(fLongitude*kRad2Deg) << " deg " << (fLongitude < 0 ? "E" : "W") << 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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the time (as mjd) of sunrise/sunset at the day floor(mjd)
+// above/below alt[deg]
+//
+// For more information see MAstro::GetSunRiseSet
+//
+// A TArrayD(2) is returned with the sunrise in TArray[0] and the
+// sunset in TArrayD[1].
+//
+TArrayD MObservatory::GetSunRiseSet(Double_t mjd, Double_t alt) const
+{
+    return MAstro::GetSunRiseSet(mjd, GetLongitudeDeg(), GetLatitudeDeg(), alt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the observatory location from resource file:
+//    MObservatory.Name: Magic1, WuerzburgCity
+//
+Int_t MObservatory::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (IsEnvDefined(env, prefix, "Name", print))
+    {
+        TString name = GetEnvValue(env, prefix, "Name", "Magic1");
+        name = name.Strip(TString::kBoth);
+
+        if (name==(TString)"Magic1")
+        {
+            SetLocation(kMagic1);
+            return kTRUE;
+        }
+
+        if (name==(TString)"WuerzburgCity")
+        {
+            SetLocation(kWuerzburgCity);
+            return kTRUE;
+        }
+
+        *fLog << err << "MObservatory::ReadEnv - ERROR: Observatory " << name << " unknown." << endl;
+        return kERROR;
+    }
+
+    return kFALSE;
+
+}
Index: branches/Mars_McMismatchStudy/mastro/MObservatory.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MObservatory.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MObservatory.h	(revision 17960)
@@ -0,0 +1,86 @@
+#ifndef MARS_MObservatory
+#define MARS_MObservatory
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MTime;
+class TArrayD;
+
+class MObservatory : public MParContainer
+{
+public:
+    enum LocationName_t
+    {
+        kMagic1,
+        kWuerzburgCity,
+        kTuorla
+    };
+
+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=NULL, const char *title=NULL);
+
+public:
+    MObservatory(const char *name=NULL, const char *title=NULL);
+    MObservatory(LocationName_t key, const char *name=NULL, const char *title=NULL);
+    MObservatory(Double_t lon, Double_t lat, const char *name="<n/a>");
+    MObservatory(Double_t lon, Double_t lat, Double_t h, const char *name="<n/a>");
+
+    void Copy(TObject &obj) const
+    {
+        MObservatory &obs = (MObservatory&)obj;
+        obs.fObservatoryName = fObservatoryName;
+        obs.fLongitude = fLongitude;
+        obs.fLatitude = fLatitude;
+        obs.fSinLatitude = fSinLatitude;
+        obs.fCosLatitude = fCosLatitude;
+        obs.fHeight = fHeight;
+    }
+
+    void SetLocation(LocationName_t name);
+    void SetLocation(Double_t lon, Double_t lat, Double_t h=0, const char *name=NULL);
+
+    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; }
+
+    TArrayD GetSunRiseSet(Double_t mjd, Double_t alt=0) const;
+
+    void RotationAngle(Double_t theta, Double_t phi, Double_t &sin, Double_t &cos) const;
+    Double_t RotationAngle(Double_t theta, Double_t phi) const;
+
+    LocationName_t GetObservatoryKey() const { return fObservatoryKey; }
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MObservatory, 0) // class storing observatory locations
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mastro/MVector3.cc
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MVector3.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MVector3.cc	(revision 17960)
@@ -0,0 +1,88 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MVector3
+//  ========
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MVector3.h"
+
+#include <iostream>
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MVector3);
+
+using namespace std;
+
+void MVector3::SetThetaPhiMag(Double_t theta, Double_t phi, Double_t mag)
+{
+    SetMagThetaPhi(TMath::Power(10, -mag/2.5), theta, phi);
+}
+
+Double_t MVector3::Magnitude() const
+{
+    return -2.5*TMath::Log10(Mag());
+}
+
+void MVector3::SetRaDec(Double_t ra, Double_t dec, Double_t mag)
+{
+    fType = kIsRaDec;
+    SetThetaPhiMag(TMath::Pi()/2-dec, ra, mag);
+}
+
+void MVector3::SetAltAz(Double_t alt, Double_t az, Double_t mag)
+{
+    fType = kIsAltAz;
+    SetThetaPhiMag(TMath::Pi()/2-alt, az, mag);
+}
+
+void MVector3::WriteBinary(ostream &out) const
+{
+    const Double_t t = Theta();
+    const Double_t p = Phi();
+    const Float_t  m = Mag();
+    out.write((char*)&t, 8);
+    out.write((char*)&p, 8);
+    out.write((char*)&m, 4);
+    out << fName << endl;
+}
+
+void MVector3::ReadBinary(istream &in)
+{
+    Double_t t, p;
+    Float_t  m;
+
+    in.read((char*)&t, 8);
+    in.read((char*)&p, 8);
+    in.read((char*)&m, 4);
+    fName.ReadLine(in);
+
+    SetMagThetaPhi(m, t, p);
+}
Index: branches/Mars_McMismatchStudy/mastro/MVector3.h
===================================================================
--- branches/Mars_McMismatchStudy/mastro/MVector3.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/MVector3.h	(revision 17960)
@@ -0,0 +1,55 @@
+#ifndef MARS_MVector3
+#define MARS_MVector3
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+class MVector3 : public TVector3
+{
+private:
+    enum VectorType_t
+    {
+        kIsInvalid,
+        kIsRaDec,
+        kIsZdAz,
+        kIsAltAz,
+        kIsArbitrary
+    };
+
+    VectorType_t fType;
+
+    TString fName;
+
+    void SetThetaPhiMag(Double_t theta, Double_t phi, Double_t mag); // SetMagThetaPhi(TMath::Power(10, -mag/2.5), theta, phi);
+
+public:
+    MVector3() { fType=kIsInvalid; }
+    MVector3(Double_t theta, Double_t phi, Double_t mag=0)
+    {
+        SetThetaPhiMag(theta, phi, mag);
+        fType=kIsArbitrary;
+    }
+    MVector3(const TVector3 &v3) : TVector3(v3) { fType=kIsArbitrary; }
+    Double_t Magnitude() const;// { return -2.5*TMath::Log10(Mag()); }
+
+    Bool_t IsValid() const { return fType!=kIsInvalid; }
+
+    void SetRaDec(Double_t ra, Double_t dec, Double_t mag=0); // SetThetaPhiMag(TMath::Pi()/2-dec, ra, mag);
+    void SetAltAz(Double_t alt, Double_t az, Double_t mag=0); // SetThetaPhiMag(TMath::Pi()/2-alt, az, mag);
+    void SetZdAz(Double_t zd, Double_t az, Double_t mag=0)
+    {
+        fType = kIsZdAz;
+        SetThetaPhiMag(zd, az, mag);
+    }
+
+    void SetName(const TString &str) { fName = str.Strip(TString::kBoth); }
+    const char *GetName() const { return fName; }
+
+    void WriteBinary(std::ostream &out) const;
+    void ReadBinary(std::istream &in);
+
+    ClassDef(MVector3, 1) // A specialized TVector3 storing a star-name
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mastro/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mastro/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mastro/Makefile	(revision 17960)
@@ -0,0 +1,50 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Astro
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES =  -I. -I../mbase -I../mgeom -I../mtemp -I../mstarcam -I../mhist -I../mcore
+# mgeom (MAstroCamera): MGeomCam, MGeomMirror
+
+SRCFILES = MVector3.cc \
+	   MAstro.cc \
+	   MAstroSky2Local.cc \
+	   MAstroCatalog.cc \
+           MAstroCamera.cc \
+           MObservatory.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mbadpixels/BadPixelsIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/BadPixelsIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/BadPixelsIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mbadpixels/BadPixelsLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/BadPixelsLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/BadPixelsLinkDef.h	(revision 17960)
@@ -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 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+;
+#pragma link C++ class MHBadPixels+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCalc.cc	(revision 17960)
@@ -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, 02/2004 <mailto:tbretz@astro.uni.wuerzburg.de>
+!   Author(s): Stefan Ruegamer, 08/2005 <mailto:snruegam@astro.uni.wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBadPixelsCalc
+//
+//
+// The job of the task is to determin bad pixels event-wise. This must be
+// redone for each event. This particular task is for what is explained
+// below.
+// New algorithms may enter new tasks.
+//
+//
+// Check the pedestal RMS of every pixel with respect to the mean
+// pedestal RMS of the camera.
+//
+// The pixels can be set as blind if the pedestalRMS is too big or 0.
+//
+// If you don't want to use this option set the PedestalLevel<=0;
+//
+//     MBadPixelsCalc calc;
+//     calc.SetPedestalLevel(-1);
+//
+//
+//  Input Containers:
+//   [MPedPhotCam]
+//   [MGeomCam]
+//
+//  Output Containers:
+//   MBadPixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsCalc.h"
+
+#include <TEnv.h>
+
+#include "MArrayI.h"
+#include "MArrayD.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeom.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), fPedestalLevelVarianceLo(5),
+    fPedestalLevelVarianceHi(5), fNamePedPhotCam("MPedPhotCam"),
+    fCheckInProcess(kTRUE), fCheckInPostProcess(kFALSE)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MBadPixelsCalc::PreProcess (MParList *pList)
+{
+    fBadPixels = (MBadPixelsCam*)pList->FindCreateObj(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+        return kFALSE;
+
+    if (fPedestalLevel>0)
+    {
+        fPedPhotCam = (MPedPhotCam*)pList->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+        if (!fPedPhotCam)
+        {
+	  *fLog << err << fNamePedPhotCam << "[MPedPhotCam] not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+        if (!fGeomCam)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    *fLog << inf << "Name of MPedPhotCam to get pedestal rms from: " << fNamePedPhotCam << endl;
+    if (fPedestalLevel>0)
+        *fLog << "Checking mean 'pedestal rms' against absolute value with level " << fPedestalLevel << endl;
+    if (fPedestalLevelVarianceLo>0)
+        *fLog << "Checking mean 'pedestal rms' against its lower variance with level " << fPedestalLevelVarianceLo << endl;
+    if (fPedestalLevelVarianceHi>0)
+        *fLog << "Checking mean 'pedestal rms' against its upper variance with level " << fPedestalLevelVarianceHi << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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(MBadPixelsPix::UnsuitableType_t type) const
+{
+    const Bool_t checklo = fPedestalLevelVarianceLo>0;
+    const Bool_t checkhi = fPedestalLevelVarianceHi>0;
+
+    if (fPedestalLevel<=0 && !checklo && !checkhi)
+        return kTRUE;
+
+    if (!fGeomCam || !fPedPhotCam || !fBadPixels)
+    {
+        *fLog << err << "MBadPixelsCalc::CheckPedestalRms: ERROR - One of the necessary container are not initialized..." << endl;
+        return kFALSE;
+    }
+
+    const Int_t entries = fPedPhotCam->GetSize();
+
+    const Int_t na = fGeomCam->GetNumAreas();
+
+    MArrayD meanrms(na);
+    MArrayI npix(na);
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        if ((*fBadPixels)[i].IsUnsuitable())
+            continue;
+
+        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
+    Int_t counter=0;
+    for (int i=0; i<na; i++)
+    {
+        if (npix[i]==0 || meanrms[i]==0) //no valid Pedestals Rms
+        {
+            counter++;
+            continue;
+        }
+
+        meanrms[i] /= npix[i];
+        npix[i]=0;
+    }
+
+    if (counter==na)
+    {
+        *fLog << err << "MBadPixelsCalc::CheckPedestalRms: ERROR - No pixel seems to contain a valid pedestal RMS..." << endl;
+        return kFALSE;
+    }
+
+    MArrayD meanrms2(na);
+    MArrayD varrms2(na);
+    for (Int_t i=0; i<entries; i++)
+    {
+        if ((*fBadPixels)[i].IsUnsuitable())
+            continue;
+
+        const Double_t rms = (*fPedPhotCam)[i].GetRms();
+        const Byte_t  aidx = (*fGeomCam)[i].GetAidx();
+
+        //Calculate the corrected means:
+        if (rms<=meanrms[aidx]/1.5 || rms>=meanrms[aidx]*1.5)
+            continue;
+
+        meanrms2[aidx] += rms;
+        varrms2 [aidx] += rms*rms;
+        npix[aidx]++;
+    }
+
+    //if no pixel has a minimum signal, return
+    MArrayD lolim1(na), lolim2(na); // Precalcualtion of limits
+    MArrayD uplim1(na), uplim2(na); // for speeed reasons
+    counter = 0;
+    for (int i=0; i<na; i++)
+    {
+        if (npix[i]==0 || meanrms2[i]==0)
+        {
+            counter++;
+            continue;
+        }
+
+        meanrms2[i] /= npix[i];
+
+        if (fPedestalLevel>0)
+        {
+            lolim1[i]  = meanrms2[i]/fPedestalLevel;
+            uplim1[i]  = meanrms2[i]*fPedestalLevel;
+        }
+
+        if (checklo || checkhi)
+        {
+            varrms2[i] /= npix[i];
+            varrms2[i]  = TMath::Sqrt(varrms2[i]-meanrms2[i]*meanrms2[i]);
+
+            lolim2[i]   = meanrms2[i]-fPedestalLevelVarianceLo*varrms2[i];
+            uplim2[i]   = meanrms2[i]+fPedestalLevelVarianceHi*varrms2[i];
+        }
+    }
+
+    if (counter==na)
+    {
+        *fLog << err << "MBadPixelsCalc::CheckPedestalRms: ERROR - No pixel seems to contain a valid pedestal RMS anymore..." << endl;
+        return kFALSE;
+    }
+
+    Int_t bads = 0;
+
+    //Blind the Bad Pixels
+    for (Int_t i=0; i<entries; i++)
+    {
+        if ((*fBadPixels)[i].IsUnsuitable())
+            continue;
+
+        const Double_t rms = (*fPedPhotCam)[i].GetRms();
+        const Byte_t  aidx = (*fGeomCam)[i].GetAidx();
+
+        if ((fPedestalLevel<=0 || (rms> lolim1[aidx] && rms<=uplim1[aidx])) &&
+            (!checklo          ||  rms> lolim2[aidx])                       &&
+            (!checkhi          ||  rms<=uplim2[aidx])
+           )
+            continue;
+
+        (*fBadPixels)[i].SetUnsuitable(type);
+        if (type==MBadPixelsPix::kUnsuitableRun)
+            (*fBadPixels)[i].SetUncalibrated(MBadPixelsPix::kDeadPedestalRms);
+
+        bads++;
+    }
+
+    // Check if the number of pixels to blind is > 60% of total number of pixels
+    //
+    if (bads>0.5*entries)
+    {
+        *fLog << err << "ERROR - More than 50% unsuitable pixels (" << bads << "/" << entries << ")... something must be wrong!" << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Bool_t MBadPixelsCalc::CheckPedestalRms(MBadPixelsCam &cam, const MPedPhotCam &ped, MBadPixelsPix::UnsuitableType_t t)
+{
+    MBadPixelsCam *store1 = fBadPixels;
+    const MPedPhotCam *store2 = fPedPhotCam;
+
+    fBadPixels  = &cam;
+    fPedPhotCam = &ped;
+
+    const Bool_t rc = CheckPedestalRms(t);
+
+    fBadPixels  = store1;
+    fPedPhotCam = store2;
+
+    return rc;
+}
+
+Bool_t MBadPixelsCalc::CheckPedestalRms(MBadPixelsCam &cam, const MPedestalCam &ped, MBadPixelsPix::UnsuitableType_t t)
+{
+    return CheckPedestalRms(cam, MPedPhotCam(ped), t);
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MBadPixelsCalc::Process()
+{
+    if (!fCheckInProcess)
+        return kTRUE;
+
+    return CheckPedestalRms(MBadPixelsPix::kUnsuitableEvt) ? kTRUE : kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MBadPixelsCalc::PostProcess()
+{
+    return fCheckInPostProcess ? CheckPedestalRms(MBadPixelsPix::kUnsuitableRun) : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MBadPixelsCalc.PedestalLevel:         3.0
+//
+//   MBadPixelsCalc.PedestalLevelVariance:   5.0
+//     overwrites
+//   MBadPixelsCalc.PedestalLevelVarianceLo: 5.0
+//     and
+//   MBadPixelsCalc.PedestalLevelVarianceHi: 5.0
+//
+Int_t MBadPixelsCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "PedestalLevel", print))
+    {
+        rc = kTRUE;
+        SetPedestalLevel(GetEnvValue(env, prefix, "PedestalLevel", fPedestalLevel));
+    }
+    if (IsEnvDefined(env, prefix, "PedestalLevelVarianceLo", print))
+    {
+        rc = kTRUE;
+        SetPedestalLevelVarianceLo(GetEnvValue(env, prefix, "PedestalLevelVarianceLo", fPedestalLevelVarianceLo));
+    }
+    if (IsEnvDefined(env, prefix, "PedestalLevelVarianceHi", print))
+    {
+        rc = kTRUE;
+        SetPedestalLevelVarianceHi(GetEnvValue(env, prefix, "PedestalLevelVarianceHi", fPedestalLevelVarianceHi));
+    }
+
+    if (IsEnvDefined(env, prefix, "PedestalLevelVariance", print))
+    {
+        rc = kTRUE;
+        SetPedestalLevelVariance(GetEnvValue(env, prefix, "PedestalLevelVariance", -1));
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCalc.h	(revision 17960)
@@ -0,0 +1,67 @@
+#ifndef MARS_MBadPixelsCalc
+#define MARS_MBadPixelsCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+class MBadPixelsCam;
+class MGeomCam;
+class MPedPhotCam;
+class MPedestalCam;
+
+class MBadPixelsCalc : public MTask
+{
+private:
+    const MGeomCam      *fGeomCam;    //! Input container storing the pixel sizes
+    const MPedPhotCam   *fPedPhotCam; //! Input container storing the pedestal and pedestal rms of all pixels
+          MBadPixelsCam *fBadPixels;  //! Output container holding the bad pixels
+
+    Float_t fPedestalLevel;
+    Float_t fPedestalLevelVarianceLo;
+    Float_t fPedestalLevelVarianceHi;
+
+    TString fNamePedPhotCam; // name of the 'MPedPhotCam' container
+
+    Bool_t fCheckInProcess;
+    Bool_t fCheckInPostProcess;
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MBadPixelsCalc(const char *name=NULL, const char *title=NULL);
+
+    // Setter
+    void SetPedestalLevel(Float_t f=-1)           { fPedestalLevel=f; }
+    void SetPedestalLevelVariance(Float_t f=-1)   { fPedestalLevelVarianceLo=fPedestalLevelVarianceHi=f; }
+    void SetPedestalLevelVarianceLo(Float_t f=-1) { fPedestalLevelVarianceLo=f; }
+    void SetPedestalLevelVarianceHi(Float_t f=-1) { fPedestalLevelVarianceHi=f; }
+
+    void SetNamePedPhotCam(const char *name)      { fNamePedPhotCam = name; }
+    void SetGeomCam(const MGeomCam *geom)         { fGeomCam = geom; }
+
+    void EnableCheckInProcess(Bool_t b=kTRUE)     { fCheckInProcess = b; }
+    void EnableCheckInPostProcess(Bool_t b=kTRUE) { fCheckInPostProcess = b; }
+
+    // MBadPixelsCalc
+    Bool_t CheckPedestalRms(MBadPixelsPix::UnsuitableType_t t) const;
+    Bool_t CheckPedestalRms(MBadPixelsCam &cam, const MPedPhotCam  &ped, MBadPixelsPix::UnsuitableType_t t=MBadPixelsPix::kUnsuitableRun);
+    Bool_t CheckPedestalRms(MBadPixelsCam &cam, const MPedestalCam &ped, MBadPixelsPix::UnsuitableType_t t=MBadPixelsPix::kUnsuitableRun);
+
+    ClassDef(MBadPixelsCalc, 1) // Task to find bad pixels (star, broken pixels, etc)
+}; 
+
+#endif
+
+
+
+
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCam.cc	(revision 17960)
@@ -0,0 +1,737 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Markus Gaug  3/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MBadPixelsCam                           
+//
+//
+// Storage container to store bad pixel of the camera...
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsCam.h"
+
+#include <iostream>
+
+#include <TArrayC.h>
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MBadPixelsPix.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+ClassImp(MBadPixelsCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MBadPixelsCam::MBadPixelsCam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MBadPixelsCam";
+    fTitle = title ? title : "Storage container to store bad pixel information";
+
+    fArray = new TClonesArray("MBadPixelsPix", 1);
+}
+
+MBadPixelsCam::MBadPixelsCam(const MBadPixelsCam &cam)
+{
+    fName  = "MBadPixelsCam";
+    fTitle = "Storage container to store bad pixel information";
+
+    fArray = new TClonesArray("MBadPixelsPix", 1);
+    cam.Copy(*this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the array conatining the bad pixel information
+//
+MBadPixelsCam::~MBadPixelsCam()
+{
+    delete fArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MBadPixelsCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MBadPixelsCam
+//
+Int_t MBadPixelsCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MBadPixelsCam::Copy(TObject &object) const
+{
+    MBadPixelsCam &cam = (MBadPixelsCam&)object;
+
+    const Int_t n = GetSize();
+
+    if (n==0)
+        return;
+
+    cam.InitSize(n);
+    for (int i=0; i<n; i++)
+        (*this)[i].Copy(cam[i]);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MBadPixelsPix &MBadPixelsCam::operator[](Int_t i)
+{
+    return *static_cast<MBadPixelsPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MBadPixelsPix &MBadPixelsCam::operator[](Int_t i) const
+{
+    return *static_cast<MBadPixelsPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Merge MBadPixelsCam cam into this, see also MBadPixelsPix::Merge
+//
+void MBadPixelsCam::Merge(const MBadPixelsCam &cam)
+{
+    const Int_t n = cam.GetSize();
+    if (n==0)
+    {
+        *fLog << inf << "MBadPixelsCam::Merge: Container empty." << endl;
+        return;
+    }
+
+    if (GetSize()==0)
+        InitSize(n);
+
+    if (GetSize()<n)
+    {
+        *fLog << warn << "MBadPixelsCam::Merge: Size mismatch (" << n << "," << GetSize() << ")... 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->R__FOR_EACH(TObject, Clear)(o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset event depending bits
+//
+void MBadPixelsCam::Reset()
+{
+    fArray->R__FOR_EACH(MParContainer, Reset)();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the number of pixels without the given type-flags.
+//
+// The second argument aidx is the area index (see MGeomCam, MGeom)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumSuitable(MBadPixelsPix::UnsuitableType_t type, const MGeomCam *geom, Int_t aidx) const
+{
+    const UInt_t n = GetSize();
+
+    if (aidx>=0 && (!geom || geom->GetNumPixels()!=n))
+    {
+        *fLog << err << GetDescriptor() << "ERROR - Geometry (" << geom->ClassName() << ") size mismatch!" << endl;
+        return -1;
+    }
+
+    Short_t rc = 0;
+    for (UInt_t i=0; i<n; i++)
+    {
+        if (aidx>=0 && geom && (*geom)[i].GetAidx()!=aidx)
+            continue;
+
+        if (!(*this)[i].IsUnsuitable(type))
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the number of pixels with the given type-flags.
+//
+// The second argument aidx is the area index (see MGeomCam, MGeom)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type, const MGeomCam *geom, Int_t aidx) const
+{
+    const UInt_t n = GetSize();
+
+    if (aidx>=0 && geom && geom->GetNumPixels()!=n)
+    {
+        *fLog << err << GetDescriptor() << "ERROR - Geometry (" << geom->ClassName() << ") size mismatch!" << endl;
+        return -1;
+    }
+
+    Short_t rc = 0;
+    for (UInt_t i=0; i<n; i++)
+    {
+        if (aidx>=0 && geom && (*geom)[i].GetAidx()!=aidx)
+            continue;
+
+        if ((*this)[i].IsUnsuitable(type))
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Count the number of unsuitable pixels.
+//
+Short_t MBadPixelsCam::GetNumUnsuitable() const
+{
+    const UInt_t n = GetSize();
+
+    Short_t rc = 0;
+    for (UInt_t i=0; i<n; i++)
+        if ((*this)[i].IsUnsuitable())
+            rc++;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Counts the number of neighbors matching NOT UnsuitableType type
+//
+Short_t MBadPixelsCam::GetNumSuitableNeighbors(MBadPixelsPix::UnsuitableType_t type, const MGeom &pix) const
+{
+    const Int_t n2 = pix.GetNumNeighbors();
+
+    Int_t cnt=0;
+    for (int j=0; j<n2; j++)
+    {
+        const Int_t id2 = pix.GetNeighbor(j);
+        if (!(*this)[id2].IsUnsuitable(type))
+            cnt++;
+    }
+
+    return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the number of pixels which are - under no circumstances -
+// interpolatable, called isolated. This means that a pixel (its own status
+// doesn't matter) has less than two reliable neighbor pixels.
+//
+// The second argument aidx is the area index (see MGeomCam, MGeom)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumIsolated(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx) const
+{
+    const Int_t n = geom.GetNumPixels();
+
+    if (n!=GetSize())
+    {
+        *fLog << err << GetDescriptor() << "ERROR - Geometry (" << geom.ClassName() << ") size mismatch!" << endl;
+        return -1;
+    }
+
+    Short_t rc = 0;
+    for (int i=0; i<n; i++)
+    {
+        const MGeom &pix = geom[i];
+        if (aidx>=0 && pix.GetAidx()!=aidx)
+            continue;
+
+        if (GetNumSuitableNeighbors(type, pix)<2)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a helper function which calculates the size of a single cluster
+// by iterative calling.
+//
+// If a pixel matches the criterias the counter is increased by 1 and
+// the function is called for all its neighbors. If
+//
+// The second argument aidx is the area index (see MGeomCam, MGeom)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, TObjArray &list, Int_t idx, Int_t aidx) const
+{
+    const MGeom *pix = (MGeom*)list[idx];
+    if (!pix)
+        return 0;
+
+    // Check whether more than one neighbor contains useful information,
+    // which mean it can later be interpolated
+    if (GetNumSuitableNeighbors(type, *pix)>1)
+        return 0;
+
+    // If the requested area-index is valid check whether it is the requested one
+    if (aidx>=0 && pix->GetAidx()!=aidx)
+        return 1;
+
+    // Remove the pixel from the list of pixels to be checked
+    list.RemoveAt(idx);
+
+    // Do the same for the neighbor pixels recursively and count the 1-results
+    Short_t cnt = 1;
+    const Int_t n = pix->GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        cnt += GetNumMaxCluster(type, list, pix->GetNeighbor(i), aidx);
+
+    // return the number of neighbor pixels/clusters which have unsuitable-type type
+    return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the size of the biggest cluster with the given UnsuitableType
+// type and the given area index.
+//
+// The second argument aidx is the area index (see MGeomCam, MGeom)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx) const
+{
+    const Int_t n = geom.GetNumPixels();
+
+    if (n!=GetSize())
+    {
+        *fLog << err << GetDescriptor() << "ERROR - Geometry (" << geom.ClassName() << ") size mismatch!" << endl;
+        return -1;
+    }
+
+    TObjArray list(n);
+    for (int i=0; i<n; i++)
+        list.AddAt(&geom[i], i);
+
+    Short_t max = 0;
+    for (int i=0; i<n; i++)
+        max = TMath::Max(GetNumMaxCluster(type, list, i, aidx), max);
+
+    return max;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of all bad pixels
+//
+void MBadPixelsCam::Print(Option_t *o) const
+{
+  *fLog << all << GetDescriptor() << ":" << endl;
+  *fLog << "Pixels without problems:" << endl;
+    
+  Int_t count = 0;
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if (!(*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          *fLog << i << " ";
+          count ++;
+        }
+    }
+  *fLog << count << " normal pixels" << endl;
+  *fLog << endl;
+
+  *fLog << "Pixels unsuited for the whole run:" << endl;
+
+  count = 0;
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          *fLog << i << " ";
+          count ++;
+        }
+    }
+
+  *fLog << count << " unsuited pixels per run :-(" << endl;
+  *fLog << endl;
+
+  *fLog << "Pixels unsuited for this event:" << endl;
+
+  count = 0;
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableEvt))
+        {
+          *fLog << i << " ";
+          count ++;
+        }
+    }
+
+  *fLog << count << " unsuited pixels per event :-(" << endl;
+  *fLog << endl;
+
+  count = 0;
+
+  *fLog << all << "Pixels unreliable for the whole run:" << endl;
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+        {
+          *fLog << i << " ";
+          count ++;
+        }
+    }
+
+  *fLog << count << " unreliable pixels :-(" << endl;
+  *fLog << endl;
+  *fLog << endl;
+  *fLog << all << "Unsuited pixels statistics:" << endl;
+  *fLog << endl;
+
+  PrintBadPixels(MBadPixelsPix::kPreviouslyExcluded,"Previously excluded");
+  PrintBadPixels(MBadPixelsPix::kChargeIsPedestal,"Signal smaller 3 Pedestal RMS");
+  PrintBadPixels(MBadPixelsPix::kChargeRelErrNotValid,"Signal Rel. error too large");
+  PrintBadPixels(MBadPixelsPix::kLoGainSaturation,"Low Gain Saturation");
+  PrintBadPixels(MBadPixelsPix::kMeanTimeInFirstBin,"Mean Arr. Time In First Extraction Bin");
+  PrintBadPixels(MBadPixelsPix::kMeanTimeInLast2Bins,"Mean Arr. Time In Last 2 Extraction Bins");
+  PrintBadPixels(MBadPixelsPix::kDeviatingNumPhes,"Deviating Number of Photo-electrons");
+  PrintBadPixels(MBadPixelsPix::kDeviatingNumPhots,"Deviating Number of Photons");
+  PrintBadPixels(MBadPixelsPix::kHiGainOverFlow,"High-Gain Histogram Overflow");
+  PrintBadPixels(MBadPixelsPix::kLoGainOverFlow,"Low-Gain Histogram Overflow");
+  PrintBadPixels(MBadPixelsPix::kDeadPedestalRms,"Presumably dead from Ped. Rms");
+  PrintBadPixels(MBadPixelsPix::kDeviatingAbsTimeResolution,"Deviating abs. time resolution");
+  PrintBadPixels(MBadPixelsPix::kDeviatingRelTimeResolution,"Deviating rel. time resolution");
+  //  PrintBadPixels(MBadPixelsPix::kFluctuatingArrivalTimes,"Fluctuating Pulse Arrival Times");
+
+  *fLog << endl;
+  *fLog << all << "Unreliable pixels statistics:" << endl;
+  *fLog << endl;
+
+  PrintBadPixels(MBadPixelsPix::kChargeSigmaNotValid,"Signal Sigma smaller Pedestal RMS");
+  PrintBadPixels(MBadPixelsPix::kHiGainNotFitted    ,"High Gain Signals could not be fitted");
+  PrintBadPixels(MBadPixelsPix::kLoGainNotFitted    ,"Low  Gain Signals could not be fitted");
+  PrintBadPixels(MBadPixelsPix::kRelTimeNotFitted   ,"Relative Arr. Times could not be fitted");
+  PrintBadPixels(MBadPixelsPix::kHiGainOscillating  ,"High Gain Signals Oscillation");
+  PrintBadPixels(MBadPixelsPix::kLoGainOscillating  ,"Low  Gain Signals Oscillation");
+  PrintBadPixels(MBadPixelsPix::kRelTimeOscillating ,"Relative Arr. Times Oscillation");
+  PrintBadPixels(MBadPixelsPix::kDeviatingFFactor   ,"Deviating global F-Factor");
+}
+
+TArrayC MBadPixelsCam::GetUnsuitable(MBadPixelsPix::UnsuitableType_t typ) const
+{
+    TArrayC rc(GetSize());
+
+    for (Int_t i=0; i<rc.GetSize(); i++)
+        rc[i] = (*this)[i].IsUnsuitable(typ) ? 0 : 1;
+
+    return rc;
+}
+
+TArrayC MBadPixelsCam::GetUncalibrated(MBadPixelsPix::UncalibratedType_t typ) const
+{
+    TArrayC rc(GetSize());
+
+    for (Int_t i=0; i<rc.GetSize(); i++)
+        rc[i] = (*this)[i].IsUncalibrated(typ) ? 0 : 1;
+
+    return rc;
+}
+
+void MBadPixelsCam::PrintBadPixels( MBadPixelsPix::UncalibratedType_t typ, const char *text) const 
+{
+  *fLog << "Pixels with " << text << ": " << endl;
+  UInt_t count = 0;
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUncalibrated(typ))
+        {
+          *fLog << i << " ";
+          count++;
+        }
+    }
+  
+  *fLog << Form("%3i",count) << " pixels in total " << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from an ascii file of the format:
+//    pixel1
+//    pixel2
+//    pixel3
+//    pixel4
+// while pixel1,2,3,4 are the pixel indices used in the software.
+//
+void MBadPixelsCam::AsciiRead(istream &fin)
+{
+    TString str;
+
+    while (1)
+    {
+        str.ReadLine(fin);
+        if (!fin)
+            break;
+
+        if (str[0]=='#')
+            continue;
+
+        const Int_t idx = str.Atoi();
+
+        if (idx>=GetSize())
+            InitSize(idx+1);
+
+        (*this)[idx].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+        (*this)[idx].SetUncalibrated(MBadPixelsPix::kPreviouslyExcluded);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the information into an ascii file.
+//
+Bool_t MBadPixelsCam::AsciiWrite(ostream &fout) const
+{
+    for (int i=0; i<GetSize(); i++)
+        if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            fout << i << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The types are the following:
+// 0: MBadPixelsPix::GetInfo()[0]
+// 1: MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun)
+// 2: MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableEvt)
+// 3: MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnreliableRun)
+// 4: MBadPixelsPix::IsHiGainBad()
+// 5: MBadPixelsPix::IsLoGainBad()
+// 6: MBadPixelsPix::GetUnsuitableCalLevel()
+// 7: MBadPixelsPix::GetUnreliableCalLevel()
+// 8: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainNotFitted)
+// 9: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainNotFitted)
+// 10: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainOscillating)
+// 11: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainOscillating)
+// 12: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainSaturation )
+// 13: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeIsPedestal )
+// 14: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeErrNotValid)
+// 15: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeRelErrNotValid)
+// 16: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid )
+// 17: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin  )
+// 18: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kMeanTimeInLast2Bins )
+// 19: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes    )
+// 20: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kRelTimeNotFitted    )
+// 21: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kRelTimeOscillating  )
+// 22: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kDeviatingNumPhots   )
+// 23: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainOverFlow      )
+// 24: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainOverFlow      )
+// 102: MBadPixelsPix::IsUnsuitable()
+//
+Bool_t MBadPixelsCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx >= GetSize())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      return (*this)[idx].GetInfo()[0];
+    case 1:
+      if  (!(*this)[idx].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        return kFALSE;
+      val = 1;
+      break;
+    case 2:
+      if  (!(*this)[idx].IsUnsuitable(MBadPixelsPix::kUnsuitableEvt))
+        return kFALSE;
+      val = 1;
+      break;
+    case 3:
+      if  (!(*this)[idx].IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+          return kFALSE;
+      val = 1;
+      break;
+    case 4:
+      if  (!(*this)[idx].IsHiGainBad())
+        return kFALSE;
+      val = 1;
+      break;
+    case 5:
+      if  (!(*this)[idx].IsLoGainBad())
+        return kFALSE;
+      val = 1;
+      break;
+    case 6:
+      val = (*this)[idx].GetUnsuitableCalLevel();
+      return val>0;
+    case 7:
+      val = (*this)[idx].GetUnreliableCalLevel();
+      return val>0;
+    case 8:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainNotFitted))
+        return kFALSE;
+      val = 1;
+      break;
+    case 9:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainNotFitted))
+        return kFALSE;
+      val = 1;
+      break;
+    case 10:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainOscillating))
+        return kFALSE;
+      val = 1;
+      break;
+    case 11:
+      if (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainOscillating))
+        return kFALSE;
+      val = 1;
+      break;
+    case 12:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainSaturation ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 13:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeIsPedestal ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 14:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeErrNotValid))
+        return kFALSE;
+      val = 1;
+      break;
+    case 15:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeRelErrNotValid))
+        return kFALSE;
+      val = 1;
+      break;
+    case 16:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 17:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin  ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 18:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kMeanTimeInLast2Bins ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 19:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 20:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kRelTimeNotFitted ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 21:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kRelTimeOscillating))
+        return kFALSE;
+      val = 1;
+      break;
+    case 22:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhots))
+        return kFALSE;
+      val = 1;
+      break;
+    case 23:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainOverFlow    ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 24:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainOverFlow   ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 102:
+      if  (!(*this)[idx].IsUnsuitable())
+          return kFALSE;
+      val = 1;
+      break;
+    default:
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+void MBadPixelsCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MBadPixelsCam::DrawPixelContent - not available." << endl;
+}
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsCam.h	(revision 17960)
@@ -0,0 +1,70 @@
+/* ======================================================================== *\
+!  $Name: not supported by cvs2svn $:$Id: MBadPixelsCam.h,v 1.13 2009-03-01 21:48:13 tbretz Exp $
+\* ======================================================================== */
+#ifndef MARS_MBadPixelsCam
+#define MARS_MBadPixelsCam
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TArrayC;
+class TClonesArray;
+
+class MGeom;
+
+class MBadPixelsCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray; //-> 
+
+    Short_t GetNumSuitableNeighbors(MBadPixelsPix::UnsuitableType_t type, const MGeom &pix) const;
+    Short_t GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, TObjArray &list, Int_t idx, Int_t aidx) const;
+
+    void PrintBadPixels( MBadPixelsPix::UncalibratedType_t typ, const char *text) const;
+    
+public:
+    MBadPixelsCam(const char *name=NULL, const char *title=NULL);
+    MBadPixelsCam(const MBadPixelsCam &cam);
+    ~MBadPixelsCam();
+
+    void Reset();
+    void Clear(Option_t *o="");
+    void Print(Option_t *o="") const; //*MENU*
+    void Copy(TObject &object) const;
+
+    void InitSize(const UInt_t i);
+    Int_t GetSize() const;
+
+    MBadPixelsPix &operator[](Int_t i);
+    const MBadPixelsPix &operator[](Int_t i) const;
+
+    void Merge(const MBadPixelsCam &cam);
+
+    Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type, const MGeomCam *geom, Int_t aidx=-1) const;
+    Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type) const { return GetNumUnsuitable(type, 0); }
+    Short_t GetNumUnsuitable() const;
+    Short_t GetNumSuitable(MBadPixelsPix::UnsuitableType_t type, const MGeomCam *geom, Int_t aidx=-1) const;
+    Short_t GetNumSuitable(MBadPixelsPix::UnsuitableType_t type) const { return GetNumSuitable(type, 0); }
+    Short_t GetNumIsolated(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx=-1) const;
+    Short_t GetNumIsolated(const MGeomCam &geom, Int_t aidx=-1) const { return GetNumIsolated(MBadPixelsPix::kUnsuitableRun, geom, aidx); }
+    Short_t GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx=-1) const;
+    Short_t GetNumMaxCluster(const MGeomCam &geom, Int_t aidx=-1) { return GetNumMaxCluster(MBadPixelsPix::kUnsuitableRun, geom, aidx); }
+
+    TArrayC GetUnsuitable(MBadPixelsPix::UnsuitableType_t typ=MBadPixelsPix::kUnsuitable) const;
+    TArrayC GetUncalibrated(MBadPixelsPix::UncalibratedType_t typ) const;
+
+    void   AsciiRead(std::istream &fin);
+    Bool_t AsciiWrite(std::ostream &out) 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(MBadPixelsCam, 1)	//Storage container to store bad pixel of the camera...
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsIntensityCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsIntensityCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsIntensityCam.cc	(revision 17960)
@@ -0,0 +1,553 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+// MBadPixelsIntensityCam
+//
+// Base class for intensity calibration results
+//
+// Contains TClonesArrays for the following objects:
+// - fCams:  Array of classes derived from MBadPixelsCam, one entry
+//           per calibration camera result. Has to be created
+//
+// See also: MCalibrationIntensityChargeCam, MCalibrationCam, MCalibrationPix,
+//           MHCalibrationChargePix, MHCalibrationChargeCam
+//           MCalibrationChargeBlindPix, MCalibrationChargePINDiode
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsIntensityCam.h"
+
+#include <TOrdCollection.h>
+#include <TGraph.h>
+
+#include "MGeomPix.h"
+#include "MHCamera.h"
+#include "MLogManip.h"
+
+ClassImp(MBadPixelsIntensityCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes and sets owner of:
+// - fCams
+// - Initializes fCams to entry 
+//
+MBadPixelsIntensityCam::MBadPixelsIntensityCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MBadPixelsIntensityCam";
+  fTitle = title ? title : "Base container for the Intensity Calibration";
+  
+  fCams = new TOrdCollection;
+  fCams->SetOwner();
+
+  InitSize(1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the cameras if they exist
+//
+MBadPixelsIntensityCam::~MBadPixelsIntensityCam()
+{
+  if (fCams)
+    delete fCams;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new MBadPixelsCam to fCams, give it the name "name" and initialize
+// it with geom.
+//
+void MBadPixelsIntensityCam::AddToList( const char* name, const MGeomCam &geom) 
+{
+  InitSize(GetSize()+1);
+  GetCam()->SetName(name);
+  GetCam()->Init(geom);
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MBadPixelsIntensityCam::Copy(TObject& object) const
+{
+  
+  MBadPixelsIntensityCam &calib = (MBadPixelsIntensityCam&)object;
+  
+  MParContainer::Copy(calib);
+  
+  const UInt_t n = GetSize();
+  if (n != 0)
+    {
+      calib.InitSize(n);
+      for (UInt_t i=0; i<n; i++)
+        GetCam(i)->Copy(*(calib.GetCam(i)));
+    }
+  
+}
+
+// -----------------------------------------------------
+//
+// Calls Clear() for all entries fCams
+//
+void MBadPixelsIntensityCam::Clear(Option_t *o)
+{
+
+  fCams->R__FOR_EACH(MBadPixelsCam, Clear)();
+
+  return;
+}
+
+// -----------------------------------------------------
+//
+// Calls Print(o) for all entries fCams
+//
+void MBadPixelsIntensityCam::Print(Option_t *o) const
+{
+  fCams->R__FOR_EACH(MBadPixelsCam, Print)(o);
+}
+
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollection using the 
+// function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MBadPixelsIntensityCam::InitSize(const UInt_t i)
+{
+
+  const UInt_t save = GetSize();
+
+  if (i==save)
+    return;
+  
+  if (i>save)
+    Add(save,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MBadPixelsCams in the ranges from - to. In order to initialize
+// from MBadPixelsCam derived containers, overwrite this function
+//
+void MBadPixelsIntensityCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MBadPixelsCam,i);
+}
+
+
+// -------------------------------------------------------------------
+//
+// If size is still 0, Intialize a first Cam.
+// Calls Init(geom) for all fCams
+//
+void MBadPixelsIntensityCam::Init(const MGeomCam &geom)
+{
+  if (GetSize() == 0)
+    InitSize(1);
+
+  fCams->R__FOR_EACH(MBadPixelsCam,Init)(geom);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fCams 
+// independently if the MBadPixelsCam is filled with values or not.
+//
+Int_t MBadPixelsIntensityCam::GetSize() const 
+{
+  return fCams->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+MBadPixelsPix &MBadPixelsIntensityCam::operator[](Int_t i)
+{
+  return (*GetCam())[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+const MBadPixelsPix &MBadPixelsIntensityCam::operator[](Int_t i) const 
+{
+  return (*GetCam())[i];
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+MBadPixelsCam *MBadPixelsIntensityCam::GetCam(Int_t i)
+{
+  return static_cast<MBadPixelsCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+const MBadPixelsCam *MBadPixelsIntensityCam::GetCam(Int_t i) const 
+{
+  return static_cast<MBadPixelsCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+/*
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+MBadPixelsCam *MBadPixelsIntensityCam::GetCam(const char *name )
+{
+  return static_cast<MBadPixelsCam*>(fCams->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+const MBadPixelsCam *MBadPixelsIntensityCam::GetCam(const char *name ) const 
+{
+  return static_cast<MBadPixelsCam*>(fCams->FindObject(name));
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Calls GetPixelContent for the current entry in fCams
+//
+Bool_t MBadPixelsIntensityCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  return GetCam()->GetPixelContent(val,idx,cam,type);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls DrawPixelContent for the current entry in fCams
+//
+void MBadPixelsIntensityCam::DrawPixelContent( Int_t num ) const
+{
+  return GetCam()->DrawPixelContent(num);
+}
+
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraph with the number of uncalibrated type pixels per area index
+// vs. the calibration camera.
+//
+TGraph *MBadPixelsIntensityCam::GetUncalibratedPerAreaVsTime(const MBadPixelsPix::UncalibratedType_t typ,
+                                                             const Int_t aidx, const MGeomCam &geom)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF uncal(size);
+  TArrayF time(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MBadPixelsCam *cam = GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+
+          if (geom[j].GetAidx() != aidx && aidx > -1)
+            continue;
+
+          const MBadPixelsPix &pix = (*cam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (pix.IsUncalibrated(typ))
+            uncal[i]++;
+        }
+      time[i] = i;
+    }
+  
+  TGraph *gr = new TGraph(size,time.GetArray(),uncal.GetArray());
+  
+  gr->SetTitle(Form("Uncalibrated Pixels Area %d",aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_{uncal}> [1]");      
+  return gr;
+}
+
+TGraph *MBadPixelsIntensityCam::GetUnsuitablePerAreaVsTime(const MBadPixelsPix::UnsuitableType_t typ, const Int_t aidx, const MGeomCam &geom)
+{
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF unsuit(size);
+  TArrayF time(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MBadPixelsCam *cam = GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          if (geom[j].GetAidx() != aidx && aidx > -1)
+            continue;
+
+          const MBadPixelsPix &pix = (*cam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (pix.IsUnsuitable(typ))
+            unsuit[i]++;
+        }
+      time[i] = i;
+    }
+  
+  TGraph *gr = new TGraph(size,time.GetArray(),unsuit.GetArray());
+  
+  gr->SetTitle(Form("Unsuitable Pixels Area %d",aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_{unsuit}> [1]");      
+  return gr;
+}
+
+MHCamera *MBadPixelsIntensityCam::GetUnsuitableSpectrum(const MBadPixelsPix::UnsuitableType_t typ, const MGeomCam &geom)
+{
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TString title;
+  TString axist;
+  
+  switch (typ)
+    {
+    case MBadPixelsPix::kUnsuitableRun:
+      title = "Unsuitable Pixels";
+      break;
+    case MBadPixelsPix::kUnreliableRun:
+      title = "Unreliable Pixels";
+      break;
+    default:
+      *fLog << warn << "Could not determine unsuitable type ... abort " << endl;
+      return NULL;
+    }
+  
+  MHCamera *camunsuit = new MHCamera(geom,"Unsuitables",title.Data());
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MBadPixelsCam *cam = GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MBadPixelsPix &pix = (*cam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (pix.IsUnsuitable(typ))
+            {
+              camunsuit->Fill(j,1);
+              camunsuit->SetUsed(j);
+            }
+        }
+    }
+  
+  return camunsuit;
+}
+
+MHCamera *MBadPixelsIntensityCam::GetUncalibratedSpectrum(const MBadPixelsPix::UncalibratedType_t typ, const MGeomCam &geom)
+{
+
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TString title;
+  TString axist;
+  
+  switch (typ)
+    {
+      case MBadPixelsPix::kPreviouslyExcluded:
+        title = "PreviouslyExcluded";
+        break;
+      case MBadPixelsPix::kHiGainNotFitted:
+        title = "HiGainNotFitted";
+        break;
+      case MBadPixelsPix::kLoGainNotFitted:
+        title = "LoGainNotFitted";
+        break;
+      case MBadPixelsPix::kRelTimeNotFitted:
+        title = "RelTimeNotFitted";
+        break;
+      case MBadPixelsPix::kHiGainOscillating:
+        title = "HiGainOscillating";
+        break;
+      case MBadPixelsPix::kLoGainOscillating:
+        title = "LoGainOscillating";
+        break;
+      case MBadPixelsPix::kRelTimeOscillating:
+        title = "RelTimeOscillating";
+        break;
+      case MBadPixelsPix::kLoGainSaturation:
+        title = "LoGainSaturation";
+        break;
+      case MBadPixelsPix::kChargeIsPedestal:
+        title = "ChargeIsPedestal";
+        break;
+      case MBadPixelsPix::kChargeErrNotValid:
+        title = "ChargeErrNotValid";
+        break;
+      case MBadPixelsPix::kChargeRelErrNotValid:
+        title = "ChargeRelErrNotValid";
+        break;
+      case MBadPixelsPix::kChargeSigmaNotValid:
+        title = "ChargeSigmaNotValid";
+        break;
+      case MBadPixelsPix::kMeanTimeInFirstBin:
+        title = "MeanTimeInFirstBin";
+        break;
+      case MBadPixelsPix::kMeanTimeInLast2Bins:
+        title = "MeanTimeInLast2Bins";
+        break;
+      case MBadPixelsPix::kDeviatingNumPhes:
+        title = "DeviatingNumPhes";
+        break;
+      case MBadPixelsPix::kDeviatingNumPhots:
+        title = "DeviatingNumPhots";
+        break;
+      case MBadPixelsPix::kDeviatingFFactor:
+        title = "DeviatingFFactor";
+        break;
+      case MBadPixelsPix::kDeviatingTimeResolution:
+        title = "DeviatingTimeResolution";
+        break;
+      case MBadPixelsPix::kConversionHiLoNotValid:
+        title = "ConversionHiLoNotValid";
+        break;
+      case MBadPixelsPix::kHiGainOverFlow:
+        title = "HiGainOverFlow";
+        break;
+      case MBadPixelsPix::kLoGainOverFlow:
+        title = "LoGainOverFlow";
+        break;
+      case MBadPixelsPix::kHiLoNotFitted:
+        title = "HiLoNotFitted";
+        break;
+      case MBadPixelsPix::kHiLoOscillating:
+        title = "HiLoOscillating";
+        break;
+      case MBadPixelsPix::kDeadPedestalRms:
+        title = "DeadPedestalRms";
+        break;
+      case MBadPixelsPix::kFluctuatingArrivalTimes:
+        title = "FluctuatingArrivalTimes";
+        break;
+    default:
+      *fLog << warn << "Could not determine uncalibrated type ... abort " << endl;
+      return NULL;
+    }
+  
+  MHCamera *camuncal = new MHCamera(geom,"Uncalibrated",title.Data());
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MBadPixelsCam *cam = GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MBadPixelsPix &pix = (*cam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (pix.IsUncalibrated(typ))
+            {
+              camuncal->Fill(j,1);
+              camuncal->SetUsed(j);
+            }
+        }
+    }
+  
+  return camuncal;
+}
+
+
+
+void MBadPixelsIntensityCam::DrawUnsuitablePerAreaVsTime(const MBadPixelsPix::UnsuitableType_t typ, const Int_t aidx, const MGeomCam &geom)
+{
+  TGraph *gr = GetUnsuitablePerAreaVsTime(typ,aidx,geom);
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+
+void MBadPixelsIntensityCam::DrawUncalibratedPerAreaVsTime(const MBadPixelsPix::UncalibratedType_t typ, const Int_t aidx, const MGeomCam &geom)
+{
+  TGraph *gr = GetUncalibratedPerAreaVsTime(typ,aidx,geom);
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsIntensityCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsIntensityCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsIntensityCam.h	(revision 17960)
@@ -0,0 +1,102 @@
+#ifndef MARS_MBadPixelsIntensityCam
+#define MARS_MBadPixelsIntensityCam
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+#ifndef MARS_MGeomCamMagic
+#include "MGeomCamMagic.h"
+#endif
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+class TGraph;
+class MHCamera;
+
+class MBadPixelsIntensityCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TOrdCollection *fCams;        //-> Array of MBadPixelsCams, one per pulse colour and intensity
+
+  void Add(const UInt_t from, const UInt_t to);
+  
+public:
+
+  MBadPixelsIntensityCam(const char *name=NULL, const char *title=NULL);
+  ~MBadPixelsIntensityCam();
+  
+  void  Clear ( Option_t *o="" );
+  void  Print ( Option_t *o="" ) const;
+  void  Copy  ( TObject& object) const;  
+  
+  void AddToList( const char* name, const MGeomCam &geom );
+
+  // Getters
+  Int_t GetSize() const;
+
+        MBadPixelsCam *GetCam     ( Int_t i=-1);
+  const MBadPixelsCam *GetCam     ( Int_t i=-1) const;
+  /*
+        MBadPixelsCam *GetCam     ( const char *name );
+  const MBadPixelsCam *GetCam     ( const char *name ) const;
+  */
+
+  // The "DeleteOldCam" function must not delete the first entry in
+  // the array because it is a special cam from the MParList. (see above)
+  void DeleteOldCam(MBadPixelsCam *cam) {/* if (fCams->IndexOf(cam)>0) delete fCams->Remove(cam);*/ }
+
+        MBadPixelsPix &operator[] ( Int_t i );
+  const MBadPixelsPix &operator[] ( Int_t i )  const;
+ 
+  Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type,const MGeomCam *geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumUnsuitable(type,geom,aidx); }
+  Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type) 
+	const { return GetCam()->GetNumUnsuitable(type); }
+  Short_t GetNumIsolated(MBadPixelsPix::UnsuitableType_t type,const MGeomCam &geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumIsolated(type,geom,aidx); }
+  Short_t GetNumIsolated(const MGeomCam &geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumIsolated(geom, aidx); }
+  Short_t GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type,const MGeomCam &geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumMaxCluster(type,geom,aidx); }
+  Short_t GetNumMaxCluster(const MGeomCam &geom,Int_t aidx=-1)
+        { return GetCam()->GetNumMaxCluster(geom, aidx); }
+  
+  void   AsciiRead(istream &fin) { GetCam()->AsciiRead(fin); }
+  Bool_t AsciiWrite(ostream &out) const { return GetCam()->AsciiWrite(out); }
+  
+  // Inits
+  void Init   ( const MGeomCam &geom );
+  void InitSize( const UInt_t i );
+
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam,Int_t type=0) const;
+  void   DrawPixelContent( Int_t num) const;
+
+  TGraph *GetUncalibratedPerAreaVsTime( const MBadPixelsPix::UncalibratedType_t typ,
+                                        const Int_t aidx=-1, const MGeomCam &geom=MGeomCamMagic());
+  TGraph *GetUnsuitablePerAreaVsTime( const MBadPixelsPix::UnsuitableType_t typ,
+                                      const Int_t aidx=-1, const MGeomCam &geom=MGeomCamMagic());
+
+  MHCamera *GetUnsuitableSpectrum( const MBadPixelsPix::UnsuitableType_t typ, const MGeomCam &geom=MGeomCamMagic());
+
+  MHCamera *GetUncalibratedSpectrum( const MBadPixelsPix::UncalibratedType_t typ, const MGeomCam &geom=MGeomCamMagic());
+
+  void DrawUncalibratedPerAreaVsTime( const MBadPixelsPix::UncalibratedType_t typ,
+                                        const Int_t aidx=-1, const MGeomCam &geom=MGeomCamMagic()); // *MENU*
+  void DrawUnsuitablePerAreaVsTime( const MBadPixelsPix::UnsuitableType_t typ,
+                                      const Int_t aidx=-1, const MGeomCam &geom=MGeomCamMagic()); // *MENU*
+  
+
+
+  ClassDef(MBadPixelsIntensityCam, 1) // Base Container Intensity BadPixels Results
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsMerge.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsMerge.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsMerge.cc	(revision 17960)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 02/2004 <mailto:tbretz@astro.uni.wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBadPixelsMerge
+//  ===============
+//
+//  Merges in ReInit two bad pixel containers together:
+//   1) The contents of the container given in the constructor is in ReInit
+//      merged into MBadPixelsCam from the parameter list (aka run-headers)
+//   2) MBadPixelsCam from the parameter list (aka run-headers) is merged
+//      into the container given in the constructor. While the contents
+//      to which 1) refers are still untouched.
+//
+//
+// An explanation taken from Mantis:
+// --------------------------------
+// In my eyes everything works a supposed to do. We have different sources
+// for bad-pixels, eg from Pedestal calculation, from the calibration
+// constant calculation, manual setting and so on. If processing data we
+// have to take care of all this different sources. Therefor we have to
+// store the bad pixels from this sources (eg. from calibration). In
+// addition MBadPixelsCam is read from the file containing the data (once
+// per file). Now always after a new (data-)file has been opened the bad
+// pixels from (for example) the calibration file have to be merged into
+// the container loaded from the (data-)file which is stored in the
+// parameter list. Copying the pointer would totally overwrite the pixels
+// loaded (automatically by MReadMarsFile) from the data-file. All this is
+// done using a copy of the original MBadPixelsCam (fSource). In addition
+// fDest is initialized to the pointer given as argument to the
+// constructor. To keep track of all bad pixels the instance this pointer
+// is pointing to is used to collect all bad pixels used so far.
+//
+//
+// ToDo:
+//   - Take a setup file (ReadEnv-implementation) as input
+//
+//
+//  Input Containers:
+//   MBadPixelsCam
+//
+//  Output Containers:
+//   MBadPixelsCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsMerge.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MBadPixelsMerge);
+
+using namespace std;
+
+const TString MBadPixelsMerge::fgDefName  = "MBadPixelsMerge";
+const TString MBadPixelsMerge::fgDefTitle = "Merge extra- and intra-loop pixels";
+
+// --------------------------------------------------------------------------
+//
+// Constructor. A copy of the given MBadPixelsCam is created. This copy
+// is - in ReInit - merged into the MBadPixelsCam which is found in the
+// parameter list. In addition the pointer is stored and all MBadPixelsCam
+// which are processed in ReInit are merged into this container.
+//
+MBadPixelsMerge::MBadPixelsMerge(MBadPixelsCam *bad, const char *name, const char *title)
+    : fDest(bad)
+{
+    fName  = name  ? name  : fgDefName.Data();
+    fTitle = title ? title : fgDefTitle.Data();
+
+    fSource = new MBadPixelsCam(*bad);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the copy of the primer MBadPixelsCam
+//
+MBadPixelsMerge::~MBadPixelsMerge()
+{
+    delete fSource;
+}
+
+// --------------------------------------------------------------------------
+//
+// 1) Get MBadPixelCam from the parameter list, if it doesn't yet exist,
+//    it will be created.
+// 2) Merge MBasPixelsCam into the primer container given in the constructor
+// 3) Merge the primer container given in the constructor into MBadPixelsCam
+//
+Bool_t MBadPixelsMerge::ReInit(MParList *pList)
+{
+    MBadPixelsCam *cam = (MBadPixelsCam*)pList->FindCreateObj("MBadPixelsCam");
+    if (!cam)
+        return kFALSE;
+
+    fDest->Merge(*cam);
+    cam->Merge(*fSource);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsMerge.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsMerge.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsMerge.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsPix.cc	(revision 17960)
@@ -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:
+//
+//
+// * Set bits leading to an unsuitable flag:
+//
+// BIT(7 ): kLoGainSaturation     :  The Low Gain signals were saturated during calibration
+// BIT(8 ): kChargeIsPedestal     :  The calibration signal contained only pedestals - presumably dead pixel
+// BIT(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 phes deviates by more than +6-5.5 sigma of the phes mean of the same area idx.
+// BIT(19): kHiGainOverFlow       :  The Hi-Gain calibration histogram showed overflow in more than 0.5% of the events
+// BIT(20): kLoGainOverFlow       :  The Lo-Gain calibration histogram showed overflow in more than 0.5% of the events
+// BIT(23): kDeadPedestalRms      :  The pedestal RMS was 4.5 sigma below or 25 sigma above the average per area idx.
+// BIT(24): kFluctuatingArivalTimes: The RMS of the position of the pulse maximum is larger than 3.5 FADC slices.
+// BIT(24): kLoGainBlackout       :  A high gain saturated pixel had too many blackout events in the low gain
+//
+//
+// * Set bits leading to an unreliable flag:
+// 
+// BIT(1 ): kHiGainNotFitted     :  Any High Gain signal is calibrated without a Gauss Fit to the signal distribution
+// BIT(2 ): kLoGainNotFitted     :  Any Low  Gain signal is calibrated without a Gauss Fit to the signal distribution
+// BIT(3 ): kRelTimeNotFitted    :  Any High Gain signal's arrival times are calibrated without a Gauss Fit
+// BIT(4 ): kHiGainOscillating   :  The High Gain signals fourier transform showed abnormal behavior  
+// BIT(5 ): kLoGainOscillating   :  The Low  Gain signals fourier transform showed abnormal behavior  
+// BIT(6 ): kRelTimeOscillating  :  The High Gain arrival times fourier transform showed abnormal behavior  
+// BIT(11): kChargeSigmaNotValid :  The sigma of the signal distribution is smaller than the pedestal RMS - presumably a pixel with a star in its FOV only during the pedestal taking
+// BIT(16): kDeviatingFFactor    :  The calculated overall F-Factor deviates too much from the mean - inconsistency
+// BIT(15): kDeviatingNumPhots   :  The calculated number of calibrated photons deviates too much from the mean - inconsistency
+//
+//
+// * Set bits leading to not useable low-gain signal:
+//
+// BIT(17): kConversionHiLoNotValid: The inter-calibration constant between Hi-Gain and Low Gain does not exist.
+//
+// These bits can be called with the enum MBadPixelsPix::UncalibratedType_t in combination 
+// with the function IsUncalibrated(MBadPixelsPix::UncalibratedTupe_t), e.g. 
+// MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainNotCalibrated) asks if the Hi Gain signal
+// could be calibrated.
+//
+// The third index (fInfo[2]) holds information about possible hardware mulfunctionning. The bits 
+// are coded in the following form:
+// BIT(1 ): kHVNotNominal :  The HV deviates more than 3% from the nominal value.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MBadPixelsPix);
+
+using namespace std;
+
+const Int_t MBadPixelsPix::fgRunMask =
+    MBadPixelsPix::kUnsuitableRun |
+    MBadPixelsPix::kUnreliableRun;
+
+// ------------------------------------------------------------------------
+//
+// Initialize Pixel to be Ok.
+//
+MBadPixelsPix::MBadPixelsPix(const char* name, const char* title)
+{
+    fName  = name  ? name  : "MBadPixelsPix";
+    fTitle = title ? title : "Container storing bad pixel information for a single pixel";
+
+    fInfo.Set(3);
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate all bits which are not run-wise. This will be called for
+// all entries in the parameter list, just before each time the task-list
+// is executed.
+//
+void MBadPixelsPix::Reset()
+{
+    fInfo[0] &= fgRunMask;
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values (set=0 which mean Pixel OK)
+//
+void MBadPixelsPix::Clear(Option_t *o)
+{
+    if (TString(o).IsNull())
+    {
+        fInfo[1] &= BIT(0);
+        fInfo[0]  = fInfo[1] ? kUnsuitableRun : 0;
+        fInfo[2]  = 0;
+    }
+    else
+        fInfo.Reset(0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Merge (bitwise or) the information in pix into this pixel.
+//
+void MBadPixelsPix::Merge(const MBadPixelsPix &pix)
+{
+  const Int_t n = pix.fInfo.GetSize();
+  if (n>fInfo.GetSize())
+    fInfo.Set(n);
+  
+  for (int i=0; i<n; i++)
+    fInfo[i] |= pix.fInfo[i];
+}
+
+
+/****************************************************************************
+           This is a collection of possible defects for later use
+ ****************************************************************************/
+
+/*
+ 1  PMT defective.
+ 2  Preamplifier defective.
+ 3  Optical link defective.
+ 4  HV cannot be set.
+ 7  HV unstable.
+ 5  HV readout defective.
+ 8  DC unstable.
+ 6  DC readout defective.
+ 9  Discriminator threshold cannot be set.
+ 10  Trigger delay cannot be set.
+ 11  Discriminator gives no output.
+ <-? 12  Pixel out of L1T.
+ 13  FADC defective.
+ 14  FADC board digital information defective.
+ */
+
+/*
+ 1  Pixel shows no signal
+ */
+
+/*
+
+Hardware defects which cannot be detected automatically by software. This might be stored at least in the data-base. I think we should wait until we implement these things...
+Preamplifier defective.
+Optical link defective.
+HV cannot be set.
+HV readout defective.
+DC readout defective.
+Discriminator threshold cannot be set.
+Trigger delay cannot be set.
+Discriminator gives no output.
+FADC defective.
+FADC board digital information defective.
+Pixel out of L1T. (this is an important information, but not necessarily a defect, is it?)
+
+*/
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsPix.h	(revision 17960)
@@ -0,0 +1,176 @@
+#ifndef MARS_MBadPixelsPix
+#define MARS_MBadPixelsPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MBadPixelsPix : public MParContainer
+{
+private:
+    TArrayI fInfo;
+
+public:
+    MBadPixelsPix(const char* name=NULL, const char* title=NULL);
+
+    enum UnsuitableType_t {
+        kUnsuitableRun = BIT(1),
+        kUnsuitableEvt = BIT(2),
+        kUnsuitable    = kUnsuitableRun|kUnsuitableEvt,
+        kUnreliableRun = BIT(3),
+        kUnreliableEvt = BIT(4),
+        kUnreliable    = kUnreliableRun|kUnreliableEvt
+    };
+
+    static const Int_t fgRunMask; // All types which are not event wise determined
+
+    // All types are initialized to normal behaviour
+    enum UncalibratedType_t {
+      kPreviouslyExcluded       = BIT(0),
+      kHiGainNotFitted          = BIT(1),
+      kLoGainNotFitted          = BIT(2), 
+      kRelTimeNotFitted         = BIT(3),
+      kHiGainOscillating        = BIT(4),
+      kLoGainOscillating        = BIT(5),
+      kRelTimeOscillating       = BIT(6),
+      kLoGainSaturation         = BIT(7),
+      kChargeIsPedestal         = BIT(8),
+      kChargeErrNotValid        = BIT(9),
+      kChargeRelErrNotValid     = BIT(10),
+      kChargeSigmaNotValid      = BIT(11),
+      kMeanTimeInFirstBin       = BIT(12),
+      kMeanTimeInLast2Bins      = BIT(13), 
+      kDeviatingNumPhes         = BIT(14),
+      kDeviatingNumPhots        = BIT(15),
+      kDeviatingFFactor         = BIT(16),
+      kDeviatingRelTimeResolution  = BIT(17),
+      kConversionHiLoNotValid   = BIT(18),
+      kHiGainOverFlow           = BIT(19),
+      kLoGainOverFlow           = BIT(20),
+      kHiLoNotFitted            = BIT(21),
+      kHiLoOscillating          = BIT(22),
+      kDeadPedestalRms          = BIT(23),
+      kDeviatingAbsTimeResolution  = BIT(24),
+      kLoGainBlackout           = BIT(25),
+    };
+    
+    // This is just a start..
+    enum HardwareType_t {
+      kHVNotNominal             = BIT(1)
+    };
+    
+      
+    void Reset();
+    void Clear(Option_t *o="");
+    void Copy(TObject &object) const
+    {
+        static_cast<MBadPixelsPix&>(object).fInfo = fInfo;
+    }
+
+    // Setter
+    void SetUnsuitable  (UnsuitableType_t   typ) { fInfo[0] |= typ; }
+    void SetUncalibrated(UncalibratedType_t typ) { fInfo[1] |= typ; }
+    void SetHardware    (HardwareType_t     typ) { fInfo[2] |= typ; }
+
+    // Getter
+    Bool_t IsUnsuitable  (UnsuitableType_t   typ) const { return fInfo[0]&typ; }
+    Bool_t IsUncalibrated(UncalibratedType_t typ) const { return fInfo[1]&typ; }
+    Bool_t IsHardwareBad (HardwareType_t     typ) const { return fInfo[2]&typ; }
+
+    Bool_t IsUnsuitable() const   { return fInfo[0]&kUnsuitable; }
+    Bool_t IsUnreliable() const   { return fInfo[0]&kUnreliable; }
+    Bool_t IsUncalibrated() const { return fInfo[1]!=0; }
+
+    Bool_t IsOK()  const { return fInfo[0]==0; }
+    Bool_t IsBad() const { return fInfo[0]!=0; }
+
+    Bool_t IsLoGainBad() const { return IsUnsuitable  (kUnsuitableRun      )
+				     || IsUncalibrated(kLoGainSaturation   ) 
+				     || IsUncalibrated(kConversionHiLoNotValid) 
+				     || IsUncalibrated(kLoGainOscillating  )
+				     || IsUncalibrated(kLoGainBlackout  ); }
+    Bool_t IsHiGainBad() const { return IsUnsuitable  (kUnsuitableRun      )
+  				     || IsUncalibrated(kHiGainOscillating  ) ; }
+
+    Int_t  GetUnsuitableCalLevel() const   {
+      if (!IsUnsuitable())                           return 0;
+      if (IsUncalibrated( kChargeIsPedestal    ))    return 1;
+      if (IsUncalibrated( kLoGainSaturation    ))    return 2;
+//      if (IsUncalibrated( kMeanTimeInFirstBin  ))    return 3;
+//      if (IsUncalibrated( kMeanTimeInLast2Bins ))    return 4;
+      if (IsUncalibrated( kHiGainOverFlow      ))    return 3;
+      if (IsUncalibrated( kLoGainOverFlow      ))    return 4;
+      if (IsUncalibrated( kDeadPedestalRms     ))    return 5;
+      if (IsUncalibrated( kDeviatingNumPhes    ))    return 6;
+      //if (IsUncalibrated( kFluctuatingArrivalTimes)) return 7;
+      if (IsUncalibrated( kDeviatingAbsTimeResolution)) return 7;
+      if (IsUncalibrated( kDeviatingRelTimeResolution)) return 8;
+      if (IsUncalibrated( kLoGainBlackout      ))    return 9;
+      if (IsUncalibrated( kPreviouslyExcluded  ))    return 10;
+      return 11;
+    }
+
+    static TString GetUnsuitableName(Int_t lvl)
+    {
+        switch (lvl)
+        {
+        case  1: return "Signal smaller 4.5 Pedestal RMS";
+        case  2: return "Low Gain Saturation";
+        case  3: return "High-Gain Histogram Overflow";
+        case  4: return "Low-Gain Histogram Overflow";
+        case  5: return "Presumably dead from Ped. Rms";
+        case  6: return "Deviating Number of Photo-electrons";
+        case  7: return "Deviation from median abs.arr-time rms";
+        case  8: return "Deviation from median rel.arr-time rms";
+        case  9: return "Too many Low-Gain Blackout Events";
+        case 10: return "Previously Excluded";
+        default: return "";
+        }
+    }
+
+    static Int_t GetNumUnsuitable() { return 10; }
+
+    Int_t  GetUnreliableCalLevel() const   {
+      if (!IsUnreliable() || IsUnsuitable())      return 0;
+      if (IsUncalibrated( kChargeSigmaNotValid )) return 1;
+      if (IsUncalibrated( kHiGainNotFitted     )) return 2;
+      if (IsUncalibrated( kLoGainNotFitted     )) return 3;
+      if (IsUncalibrated( kRelTimeNotFitted    )) return 4;
+      if (IsUncalibrated( kHiGainOscillating   )) return 5;
+      if (IsUncalibrated( kLoGainOscillating   )) return 6;
+      if (IsUncalibrated( kRelTimeOscillating  )) return 7;
+      if (IsUncalibrated( kDeviatingFFactor    )) return 8;
+      return 9;
+    }
+
+    static TString GetUnreliableName(Int_t lvl)
+    {
+        switch (lvl)
+        {
+        case 1: return "Signal Sigma smaller Pedestal RMS";
+        case 2: return "High Gain Signals could not be fitted";
+        case 3: return "Low  Gain Signals could not be fitted";
+        case 4: return "Relative Arr. Times could not be fitted";
+        case 5: return "High Gain Signals Oscillation";
+        case 6: return "Low  Gain Signals Oscillation";
+        case 7: return "Relative Arr. Times Oscillation";
+        case 8: return "Deviating global F-Factor";
+        default: return "";
+        }
+    }
+
+    static Int_t GetNumUnreliable() { return 8; }
+
+    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: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsTreat.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsTreat.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsTreat.cc	(revision 17960)
@@ -0,0 +1,658 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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): Stefan Ruegamer <mailto:snruegam@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBadPixelsTreat
+//
+//  You can use MBadPixelsTreat::SetUseInterpolation to replaced the
+//  bad pixels by the average of its neighbors instead of unmapping
+//  them. If you want to include the central pixel use
+//  MBadPixelsTreat::SetUseCentralPixel. The bad pixels are taken from
+//  an existing MBadPixelsCam.
+//
+//  It check if there are enough neighbors to calculate the mean
+//  If not, unmap the pixel. The minimum number of good neighbors
+//  should be set using SetNumMinNeighbors
+//
+//  If you want to interpolate unreliable pixels and  unsuitable
+//  (broken) pixels use SetHardTreatment().
+//
+//
+// Options:
+// --------
+//   SetHardTreatment:      Also interpolate unreliable pixels not only unsuitable
+//   SetUseInterpolation:   Interpolate pixels instead of unmapping them
+//   SetUseCentralPixel:    also use the pixel itself for interpolation
+//   SetProcessPedestalRun: process the pedestals once per run/file
+//   SetProcessPedestalEvt: process the pedestal once per event
+//   SetProcessTimes:       do interpolation of the arrival time
+//
+// If the arrival time treatment is switched on and "MPedPhotFromExtractor"
+// and "MPedPhotFromExtractorRndm" are found the pixel is filled with
+// a random gaus calculated from these two MPedPhotCams in the case
+// the pixels is detected as background.
+//
+//
+//  Input Containers:
+//   MSignalCam
+//   MPedPhotCam
+//   MBadPixelsCam
+//   [MGeomCam]
+//
+//  Output Containers:
+//   MSignalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsTreat.h"
+
+#include <fstream>
+
+#include <TEnv.h>
+#include <TRandom.h>
+#include <TObjString.h>
+
+//#include "MArrayD.h" // Used instead of TArrayD because operator[] has no range check
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeom.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.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)
+    : fGeomCam(0), fEvt(0), fBadPixels(0), fPedPhot1(0), fPedPhot2(0),
+    fNameSignalCam("MSignalCam"),
+    fFlags(0), fNumMinNeighbors(3), fMaxArrivalTimeDiff(3.)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetUseInterpolation();
+    SetProcessPedestal();
+    SetProcessTimes();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the status of a pixel. If kHardTreatment is set a pixel must
+// be unsuitable or uriliable to be treated. If not it is treated only if 
+// it is unsuitable
+// (IsBad() checks for any flag)
+//
+Bool_t MBadPixelsTreat::IsPixelBad(Int_t idx) const
+{
+    return TESTBIT(fFlags, kHardTreatment) ? (*fBadPixels)[idx].IsBad():(*fBadPixels)[idx].IsUnsuitable();
+}
+
+void MBadPixelsTreat::AddNamePedPhotCam(const char *name)
+{
+    fNamePedPhotCams.Add(new TObjString(name));
+}
+
+// --------------------------------------------------------------------------
+//
+//  - Try to find or create MBlindPixels in parameter list.
+//  - get the MSignalCam from the parlist (abort if missing)
+//  - if no pixels are given by the user try to determin the starfield
+//    from the monte carlo run header.
+//
+Int_t MBadPixelsTreat::PreProcess (MParList *pList)
+{
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+    {
+        *fLog << err << AddSerialNumber("MBadPixelsCam") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MSignalCam*)pList->FindObject(AddSerialNumber(fNameSignalCam), "MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << AddSerialNumber(fNameSignalCam) << " [MSignalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = 0;
+    if (!IsUseInterpolation())
+        return kTRUE;
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << AddSerialNumber("MGeomCam") << " not found - can't use interpolation... abort." << endl;
+        *fLog << " Use MBadPixelsTreat::SetUseInterpolation(kFALSE) to switch interpolation" << endl;
+        *fLog << " off and use unmapping instead." << endl;
+        return kFALSE;
+    }
+
+    const Bool_t proc = IsProcessPedestalEvt() || IsProcessPedestalRun();
+
+    if (fNamePedPhotCams.GetSize()>0 && !proc)
+    {
+        *fLog << err << "Pedestal list contains entries, but pedestal treatment is switched off... abort." << endl;
+        return kFALSE;
+    }
+
+    if (proc)
+    {
+        if (fNamePedPhotCams.GetSize()==0)
+        {
+            *fLog << inf << "No container names specified... using default: MPedPhotCam." << endl;
+            AddNamePedPhotCam();
+        }
+
+        fPedPhotCams.Clear();
+
+        TIter Next(&fNamePedPhotCams);
+        TObject *o=0;
+        while ((o=Next()))
+        {
+            TObject *p = pList->FindObject(AddSerialNumber(o->GetName()), "MPedPhotCam");
+            if (!p)
+            {
+                *fLog << err << AddSerialNumber(o->GetName()) << " [MPedPhotCam] not found... aborting." << endl;
+                return kFALSE;
+            }
+
+            fPedPhotCams.Add(p);
+        }
+    }
+
+    if (IsProcessTimes())
+    {
+        fPedPhot1 = (MPedPhotCam*)pList->FindObject("MPedPhotFromExtractor",     "MPedPhotCam");
+        fPedPhot2 = (MPedPhotCam*)pList->FindObject("MPedPhotFromExtractorRndm", "MPedPhotCam");
+
+        *fLog << inf << "Additional no-signal-interpolation switched ";
+        *fLog << (fPedPhot1 && fPedPhot2 ? "on" : "off");
+        *fLog << "." << endl;
+
+        if (fPedPhot1 && fPedPhot2)
+            *fLog << "Maximum arrival time difference: " << fMaxArrivalTimeDiff << "ns" << endl;
+
+    }
+
+    *fLog << inf << "Minimum number of neighbor pixels: " << (int)fNumMinNeighbors << endl;
+
+    if (IsProcessPedestalEvt())
+        *fLog << "Processing Pedestals once per event..." << endl;
+    if (IsProcessPedestalRun())
+        *fLog << "Processing Pedestals once per run..." << endl;
+    if (IsProcessTimes())
+        *fLog << "Processing Arrival Times once per event..." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Replaces each pixel (signal, signal error, pedestal, pedestal rms)
+//  by the average of its surrounding pixels.
+//  If TESTBIT(fFlags, kUseCentralPixel) is set the central pixel is also
+//  included.
+//
+void MBadPixelsTreat::InterpolateSignal() const
+{
+    const UShort_t entries = fGeomCam->GetNumPixels();
+
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (!IsPixelBad(i))
+            continue;
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        MSignalPix  &pix  = (*fEvt)[i];
+        const MGeom &gpix = (*fGeomCam)[i];
+
+        // Do Not-Use-Central-Pixel
+        const Bool_t nucp = !TESTBIT(fFlags, kUseCentralPixel);
+
+        Int_t num = nucp ? 0 : 1;
+
+        Double_t nphot  = nucp ? 0 : pix.GetNumPhotons();
+        Double_t perr   = 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 *= ratio;
+        perr  *= ratio;
+
+        //
+        // Loop over all its neighbors
+        //
+        const Int_t n = gpix.GetNumNeighbors();
+        for (int j=0; j<n; j++)
+        {
+            const UShort_t nidx = gpix.GetNeighbor(j);
+
+            //
+            // Do not use blind neighbors
+            //
+            if (IsPixelBad(nidx))
+                continue;
+
+            //
+            // Get the geometry for the neighbor
+            //
+            const Double_t nratio = fGeomCam->GetPixRatio(nidx);
+
+            //
+	    //The error is calculated as the quadratic sum of the errors
+	    //
+            const MSignalPix &evtpix = (*fEvt)[nidx];
+
+            nphot += nratio*evtpix.GetNumPhotons();
+            perr  += nratio*Pow2(evtpix.GetErrorPhot());
+
+            num++;
+        }
+
+	// Check if there are enough neighbors to calculate the mean
+        // If not, unmap the pixel. The maximum number of blind neighbors
+        // should be 2
+        if (num<fNumMinNeighbors)
+        {
+            pix.SetPixelUnmapped();
+            continue;
+        }
+
+        //
+        // Now the mean is calculated and the values rescaled back
+        // to the pixel area
+        //
+	nphot /= num*ratio;
+        perr   = TMath::Sqrt(perr/(num*ratio));
+ 
+        pix.Set(nphot, perr);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+void MBadPixelsTreat::InterpolatePedestals(MPedPhotCam &pedphot) const
+{
+    const Int_t entries = pedphot.GetSize();
+
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (!IsPixelBad(i))
+            continue;
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        const MGeom       &gpix = (*fGeomCam)[i];
+        const MPedPhotPix &ppix = pedphot[i];
+
+        // Do Not-Use-Central-Pixel
+        const Bool_t nucp = !TESTBIT(fFlags, kUseCentralPixel);
+
+        Int_t num = nucp ? 0 : 1;
+
+        Double_t ped = nucp ? 0 : ppix.GetMean();
+        Double_t rms = 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 *= ratio;
+        rms *= ratio;
+
+        //
+        // Loop over all its neighbors
+        //
+        const Int_t n = gpix.GetNumNeighbors();
+        for (int j=0; j<n; j++)
+        {
+            const UShort_t nidx = gpix.GetNeighbor(j);
+
+            //
+            // Do not use blind neighbors
+            //
+            if (IsPixelBad(nidx))
+                continue;
+
+            //
+            // Get the geometry for the neighbor
+            //
+            const Double_t    nratio = fGeomCam->GetPixRatio(nidx);
+            const MPedPhotPix &nppix = pedphot[nidx];
+
+            //
+            //The error is calculated as the quadratic sum of the errors
+            //
+            ped += nratio*nppix.GetMean();
+            rms += 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)
+        {
+            (*fEvt)[i].SetPixelUnmapped();
+            continue;
+        }
+
+        //
+        // Now the mean is calculated and the values rescaled back
+        // to the pixel area
+        //
+        ped /= num*ratio;
+        rms  = TMath::Sqrt(rms/(num*ratio));
+
+        pedphot[i].Set(ped, rms);
+    }
+    pedphot.SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+// loop over all MPedPhotCam and interpolate them
+//
+void MBadPixelsTreat::InterpolatePedestals() const
+{
+    TIter Next(&fPedPhotCams);
+    MPedPhotCam *cam=0;
+    while ((cam=(MPedPhotCam*)Next()))
+    {
+        InterpolatePedestals(*cam);
+        cam->ReCalc(*fGeomCam, fBadPixels);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+void MBadPixelsTreat::InterpolateTimes() const
+{
+    const Int_t n = fEvt->GetNumPixels();
+    for (int i=0; i<n; i++)
+    {
+        // Check whether pixel with idx i is bad
+        if (!IsPixelBad(i))
+            continue;
+
+        // Geometry of bad pixel
+        const MGeom &gpix = (*fGeomCam)[i];
+
+        // Number of neighbor pixels
+        const Int_t n2 = gpix.GetNumNeighbors();
+
+        // Copy the arrival time of all neighboring bad pixels
+        // to a new array for simplicity
+        Double_t time[6];
+        Int_t cnt = 0;
+        for (Int_t j=0; j<n2; j++)
+        {
+            const Int_t idx = gpix.GetNeighbor(j);
+            if (!IsPixelBad(idx))
+                time[cnt++] = (*fEvt)[idx].GetArrivalTime();
+        }
+
+        // if there are too few neighbours, don't interpolate the pixel
+        //if ((cnt < 3 && n2 > 3) || (cnt < 2 && n2 == 3))
+        if (cnt<fNumMinNeighbors)
+        {
+            (*fEvt)[i].SetPixelUnmapped();
+            continue;
+        }
+
+        Double_t min =  FLT_MAX; // Find minimum arrival time
+        Double_t max = -FLT_MAX; // Find maximum arrival time
+
+        Double_t sum2 = 0; // Sum of arrival times of the pixels
+        Int_t    cnt2 = 0; // Number of pixels summed in sum2
+
+        for (Int_t j=0; j<cnt; j++)
+        {
+            const Double_t tm1 = time[j];         // time of one neighbor pixel
+            const Double_t tm2 = time[(j+1)%cnt]; // time of its neighbor pixel
+
+            // Calculate mean arrival time of pixel probably inside the shower
+            if (TMath::Abs(tm1 - tm2)<fMaxArrivalTimeDiff)
+            {
+                sum2 += tm1+tm2;
+                cnt2++;
+            }
+
+            // Find minimum arrival time
+            if (tm1<min)
+                min = tm1;
+
+            // Find maximum arrival time
+            if (tm1>max)
+                max = tm1;
+        }
+
+        // If less than two nbeighbors belong to a shower the pixel doesn't
+        // belong to the shower, too. Set the arrival time to a uniform
+        // random value, otherwise use the mean value of the pixels belonging
+        // to the shower.
+        if (cnt2<=2)
+        {
+            sum2 = gRandom->Uniform(max-min)+min; // FIXME? Set Seed value?
+
+            // Proceed with a treatment of the signal of empty pixels
+            // better than the interpolation. (FIXME: Maybe a function
+            // different from a gaussian could be a better choice...)
+            if (fPedPhot1 && fPedPhot2)
+            {
+                const Int_t    aidx = gpix.GetAidx();
+                // This is to which bias level the signal fluctuates
+                const Double_t mean = fPedPhot1->GetArea(aidx).GetMean();
+                // This is how the signal fluctuates
+                const Double_t rms  = fPedPhot2->GetArea(aidx).GetRms();
+                const Double_t phe  = gRandom->Gaus(mean, rms);
+
+                (*fEvt)[i].SetNumPhotons(phe);
+            }
+        }
+        else
+            sum2 /= cnt2*2;
+
+        (*fEvt)[i].SetArrivalTime(sum2);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Removes all blind pixels from the analysis by setting their state
+//  to unused.
+//
+void MBadPixelsTreat::Unmap() const
+{
+    const UShort_t entries = fEvt->GetNumPixels();
+
+    //
+    // remove the pixels in fPixelsIdx if they are set to be used,
+    // (set them to 'unused' state)
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        if (IsPixelBad(i))
+            (*fEvt)[i].SetPixelUnmapped();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Interpolate Pedestals if kProcessPedestal not set
+//
+Bool_t MBadPixelsTreat::ReInit(MParList *pList)
+{
+    if (IsUseInterpolation() && IsProcessPedestalRun())
+        InterpolatePedestals();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Treat the blind pixels
+//
+Int_t MBadPixelsTreat::Process()
+{
+    if (IsUseInterpolation())
+    {
+        InterpolateSignal();
+        if (IsProcessPedestalEvt())
+            InterpolatePedestals();
+        if (IsProcessTimes())
+            InterpolateTimes();
+    }
+    else
+        Unmap();
+
+    return kTRUE;
+}
+
+void MBadPixelsTreat::StreamPrimitive(ostream &out) const
+{
+    out << "   MBadPixelsTreat " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl;
+
+    if (IsUseInterpolation())
+        out << "   " << GetUniqueName() << ".SetUseInterpolation();" << endl;
+    if (IsUseCentralPixel())
+        out << "   " << GetUniqueName() << ".SetUseCentralPixel();" << endl;
+    if (IsProcessPedestalRun())
+        out << "   " << GetUniqueName() << ".SetProcessPedestalRun();" << endl;
+    if (IsProcessPedestalEvt())
+        out << "   " << GetUniqueName() << ".SetProcessPedestalEvt();" << endl;
+    if (IsProcessTimes())
+        out << "   " << GetUniqueName() << ".SetProcessTimes();" << endl;
+    if (IsHardTreatment())
+        out << "   " << GetUniqueName() << ".SetHardTreatment();" << endl;
+    if (fNumMinNeighbors!=3)
+        out << "   " << GetUniqueName() << ".SetNumMinNeighbors(" << (int)fNumMinNeighbors << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MBadPixelsTreat.UseInterpolation:    no
+//   MBadPixelsTreat.UseCentralPixel:     no
+//   MBadPixelsTreat.HardTreatment:       no
+//   MBadPixelsTreat.ProcessPedestalRun:  no
+//   MBadPixelsTreat.ProcessPedestalEvt:  no
+//   MBadPixelsTreat.NumMinNeighbors:     3
+//   MBadPixelsTreat.MaxArrivalTimeDiff:  0.9
+//
+Int_t MBadPixelsTreat::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "UseInterpolation", print))
+    {
+        rc = kTRUE;
+        SetUseInterpolation(GetEnvValue(env, prefix, "UseInterpolation", IsUseInterpolation()));
+    }
+    if (IsEnvDefined(env, prefix, "UseCentralPixel", print))
+    {
+        rc = kTRUE;
+        SetUseCentralPixel(GetEnvValue(env, prefix, "UseCentralPixel", IsUseCentralPixel()));
+    }
+    if (IsEnvDefined(env, prefix, "HardTreatment", print))
+    {
+        rc = kTRUE;
+        SetHardTreatment(GetEnvValue(env, prefix, "HardTreatment", IsHardTreatment()));
+    }
+    if (IsEnvDefined(env, prefix, "ProcessPedestalRun", print))
+    {
+        rc = kTRUE;
+        SetProcessPedestalRun(GetEnvValue(env, prefix, "ProcessPedestalRun", IsProcessPedestalRun()));
+    }
+    if (IsEnvDefined(env, prefix, "ProcessPedestalEvt", print))
+    {
+        rc = kTRUE;
+        SetProcessPedestalEvt(GetEnvValue(env, prefix, "ProcessPedestalEvt", IsProcessPedestalEvt()));
+    }
+    if (IsEnvDefined(env, prefix, "ProcessTimes", print))
+    {
+        rc = kTRUE;
+        SetProcessTimes(GetEnvValue(env, prefix, "ProcessTimes", IsProcessTimes()));
+    }
+    if (IsEnvDefined(env, prefix, "NumMinNeighbors", print))
+    {
+        rc = kTRUE;
+        SetNumMinNeighbors(GetEnvValue(env, prefix, "NumMinNeighbors", fNumMinNeighbors));
+    }
+    if (IsEnvDefined(env, prefix, "MaxArrivalTimeDiff", print))
+    {
+        rc = kTRUE;
+        SetMaxArrivalTimeDiff(GetEnvValue(env, prefix, "MaxArrivalTimeDiff", fMaxArrivalTimeDiff));
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsTreat.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsTreat.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MBadPixelsTreat.h	(revision 17960)
@@ -0,0 +1,113 @@
+#ifndef MARS_MBadPixelsTreat
+#define MARS_MBadPixelsTreat
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MSignalCam;
+class MPedPhotCam;
+class MBadPixelsCam;
+
+class MBadPixelsTreat : public MTask
+{
+private:
+    MGeomCam      *fGeomCam;       //! Camera geometry to get the area scaling factors
+    MSignalCam    *fEvt;           //! Signal Event to be interpolated
+    MBadPixelsCam *fBadPixels;     //! Bad Pixels to be interpolated
+
+    MPedPhotCam   *fPedPhot1;      //! Pedestal from extractor used for "no-signal" in InterpolateTimes
+    MPedPhotCam   *fPedPhot2;      //! Pedestal from extractor used for "no-signal" in InterpolateTimes
+
+    TString fNameSignalCam;
+
+    TList fPedPhotCams;            // List of PedPhotCams to be treated
+
+    Byte_t  fFlags;                // flag for the method which is used
+    Byte_t  fNumMinNeighbors;      // Number of neighbors required
+    Float_t fMaxArrivalTimeDiff;   // Maximum allowed arrival time difference of neighboring pixels
+
+    TList fNamePedPhotCams;
+
+    enum
+    {
+        kUseInterpolation   = 1,
+        kUseCentralPixel    = 2,
+        kProcessPedestalRun = 3,
+        kProcessPedestalEvt = 4,
+        kProcessTimes       = 5,
+        kHardTreatment      = 6
+    };
+
+    static Double_t Pow2(Double_t x) { return x*x; }
+
+    void InterpolateTimes() const;
+    void InterpolateSignal() const;
+    void InterpolatePedestals(MPedPhotCam &pedphot) const;
+    void InterpolatePedestals() const;
+
+    void   Unmap() const;
+    Bool_t IsPixelBad(Int_t idx) const;
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    void   StreamPrimitive(std::ostream &out) const;
+
+public:
+    MBadPixelsTreat(const char *name=NULL, const char *title=NULL);
+
+    void SetUseInterpolation(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kUseInterpolation) : CLRBIT(fFlags, kUseInterpolation);
+    }
+    void SetUseCentralPixel(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kUseCentralPixel) : CLRBIT(fFlags, kUseCentralPixel);
+    }
+    void SetProcessPedestalRun(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kProcessPedestalRun) : CLRBIT(fFlags, kProcessPedestalRun);
+    }
+    void SetProcessPedestalEvt(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kProcessPedestalEvt) : CLRBIT(fFlags, kProcessPedestalEvt);
+    }
+    void SetProcessPedestal(Bool_t b=kTRUE)
+    {
+        SetProcessPedestalRun(!b);
+        SetProcessPedestalEvt(b);
+    }
+    void SetProcessTimes(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kProcessTimes) : CLRBIT(fFlags, kProcessTimes);
+    }
+    void SetHardTreatment(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kHardTreatment) : CLRBIT(fFlags, kHardTreatment);
+    }
+
+    Bool_t IsHardTreatment() const      { return TESTBIT(fFlags, kHardTreatment); }
+    Bool_t IsProcessPedestalRun() const { return TESTBIT(fFlags, kProcessPedestalRun); }
+    Bool_t IsProcessPedestalEvt() const { return TESTBIT(fFlags, kProcessPedestalEvt); }
+    Bool_t IsProcessTimes() const       { return TESTBIT(fFlags, kProcessTimes); }
+    Bool_t IsUseCentralPixel() const    { return TESTBIT(fFlags, kUseCentralPixel); }
+    Bool_t IsUseInterpolation() const   { return TESTBIT(fFlags, kUseInterpolation); }
+
+    void SetNumMinNeighbors(Byte_t num)   { fNumMinNeighbors=num; }
+    void SetMaxArrivalTimeDiff(Float_t d) { fMaxArrivalTimeDiff=d; }
+    void SetNameSignalCam(const char *name="MSignalCam") { fNameSignalCam=name; }
+    void AddNamePedPhotCam(const char *name="MPedPhotCam");
+    void SetNamePedPhotCam(const char *name)
+    {
+        AddNamePedPhotCam(name);
+    } // Deprecated! Use AddNamePedPhotCam instead (directly)
+
+    ClassDef(MBadPixelsTreat, 1) // Task to treat bad pixels (interpolation, unmapping)
+}; 
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mbadpixels/MHBadPixels.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MHBadPixels.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MHBadPixels.cc	(revision 17960)
@@ -0,0 +1,257 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHBadPixels
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHBadPixels.h" 
+
+#include <TCanvas.h>
+
+#include "MPointingPos.h"
+#include "MBadPixelsCam.h"
+#include "MGeomCam.h"
+#include "MPedPhotCam.h"
+#include "MParList.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHBadPixels);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MHBadPixels::MHBadPixels(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHBadPixels";
+    fTitle = title ? title : "Histogram for Bad Pixels vs. Theta";
+
+    fBadId = new TH2D;
+    fBadId->SetName("2D-IdBadPixels");
+    fBadId->SetTitle("2D-IdBadPixels");
+    fBadId->SetDirectory(NULL);
+    fBadId->UseCurrentStyle();
+    fBadId->SetXTitle("\\Theta [\\circ]");
+    fBadId->SetYTitle("pixel Id");
+    fBadId->SetTitleOffset(1.2, "Y");
+
+    fBadN = new TH2D;
+    fBadN->SetName("2D-NBadPixels");
+    fBadN->SetTitle("2D-NBadPixels");
+    fBadN->SetDirectory(NULL);
+    fBadN->UseCurrentStyle();
+    fBadN->SetXTitle("\\Theta [\\circ]");
+    fBadN->SetYTitle("number of bad pixels");
+    fBadN->SetTitleOffset(1.2, "Y");
+
+    // define default binnings
+    fBinsTheta = new MBinning;
+    fBinsTheta->SetEdgesCos(10,  0.0,  90.0);    // theta
+
+    fBinsPix = new MBinning;
+    fBinsPix->SetEdges(578, -0.5, 577.5);    // pixel id
+
+    SetBinning(*fBadId, *fBinsTheta, *fBinsPix);
+    SetBinning(*fBadN,  *fBinsTheta, *fBinsPix);
+
+    //-----------------------------------------
+    fNamePedPhotCam = "MPedPhotCamFromData";
+}
+
+
+// -------------------------------------------------------------------------
+//
+//  Destructor.
+//
+MHBadPixels::~MHBadPixels()
+{
+  delete fBadId;
+  delete fBadN;
+
+  delete fBinsTheta;
+  delete fBinsPix;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHBadPixels::SetupFill(const MParList *plist)
+{
+    fCam = (MGeomCam*)plist->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)    
+    {
+        *fLog << err << "MHBadPixels::SetupFill; MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+    *fLog << "MHBadPixels::SetupFill; fCam = " << fCam << endl;
+
+    fPointPos = (MPointingPos*)plist->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fPedPhot = (MPedPhotCam*)plist->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+    if (!fPedPhot)
+    {
+        *fLog << err << AddSerialNumber(fNamePedPhotCam) 
+              << "[MPedPhotCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+    fPedPhot->InitSize(fCam->GetNumPixels());
+
+
+    //----------------------------------------------------
+    *fLog << inf << "Name of MPedPhotCam container : " << fNamePedPhotCam
+          << endl;
+
+
+    //----------------------------------------------------
+    // redefine the binnings
+    
+    // Get Theta Binning
+    const MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta", "MBinning");
+    if (!binstheta)
+    {
+        *fLog << err << "Object 'BinningTheta' [MBinning] not found... use default binning." << endl;
+        binstheta = fBinsTheta;
+    }
+
+    // Define binning for pixel number
+    const UInt_t npix1 = fPedPhot->GetSize()+1;
+    //*fLog << "MHBadPixels::SetupFill(); npix1 = " << npix1 << endl;
+    const MBinning binspix(npix1, -0.5, npix1-0.5);
+
+    // Set binnings in histograms
+    SetBinning(*fBadId, *binstheta, binspix);
+    SetBinning(*fBadN,  *binstheta, binspix);
+
+    *fLog << "MHBadPixels::SetupFill(); binnings were set" << endl;
+    
+
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+// 
+// Fill the histograms
+//
+
+Int_t MHBadPixels::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "ERROR - par==NULL." << endl;
+        return kERROR;
+    }
+
+    const Double_t theta = fPointPos->GetZd();
+
+    const MBadPixelsCam *fBadPixels = (MBadPixelsCam*)par;
+
+    const UInt_t entries = fPedPhot->GetSize(); 
+    UInt_t nb = 0;
+    for (UInt_t i=0; i<entries; i++)
+    {
+      //*fLog << "MHBadPixels::Fill; i = " << i << endl;
+
+      if ( (*fBadPixels)[i].IsUnsuitable() )
+      {
+	//*fLog << "MHBadPixels::Fill; (UnSuitable) " << endl;
+
+          fBadId->Fill(theta, i, w);
+          nb++;
+      }   
+    }
+    fBadN->Fill(theta, nb, w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------
+//
+// Draw the histograms
+//
+void MHBadPixels::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(2,2);
+
+    TH1D *h;
+
+    pad->cd(1);
+    fBadId->Draw(option);
+
+    pad->cd(2);
+    fBadN->Draw(option);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = ((TH2*)fBadId)->ProjectionY("ProjY-pixId", -1, 9999, "");
+    h->SetDirectory(NULL);
+    h->SetTitle("Distribution of bad pixel Id");
+    h->SetXTitle("Id of bad pixel");
+    h->SetYTitle("No. of events");
+    h->SetTitleOffset(1.2, "Y");
+    h->Draw(option);
+    h->SetBit(kCanDelete);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    h = ((TH2*)fBadN)->ProjectionY("ProjY-pixN", -1, 9999, "");
+    h->SetDirectory(NULL);
+    h->SetTitle("Distribution of no.of bad pixels");
+    h->SetXTitle("No. of bad pixels");
+    h->SetYTitle("No. of events");
+    h->SetTitleOffset(1.2, "Y");
+    h->Draw(option);
+    h->SetBit(kCanDelete);
+
+    pad->Modified();
+    pad->Update();
+}
+//==========================================================================
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mbadpixels/MHBadPixels.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MHBadPixels.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MHBadPixels.h	(revision 17960)
@@ -0,0 +1,55 @@
+#ifndef MARS_MHBadPixels
+#define MARS_MHBadPixels
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MPedPhotCam;
+class MPointingPos;
+class MParList;
+class MGeomCam;
+
+class MHBadPixels : public MH
+{
+private:
+    MGeomCam      *fCam;      //!
+    MPedPhotCam   *fPedPhot;  //!
+    MPointingPos  *fPointPos; //!
+
+    TString  fNamePedPhotCam; //! name of the 'MPedPhotCam' container
+    MBinning *fBinsTheta;     //!
+    MBinning *fBinsPix;       //!
+
+    TH2D          *fBadId; // 2D-histogram : pixel Id vs. Theta
+    TH2D          *fBadN;  // 2D-histogram : no.of bad pixels vs. Theta
+
+public:
+    MHBadPixels(const char *name=NULL, const char *title=NULL);
+    ~MHBadPixels();
+
+    void SetNamePedPhotCam(const char *name)  { fNamePedPhotCam = name; }
+
+    const TH2D *GetBadId()       { return fBadId; }
+    const TH2D *GetBadId() const { return fBadId; }
+
+    const TH2D *GetBadN()       { return fBadN; }
+    const TH2D *GetBadN() const { return fBadN; }
+
+    TH2 *GetBadIdByName(const TString name) { return fBadId; }
+    TH2 *GetBadNByName(const TString name)  { return fBadN; }
+
+    void Draw(Option_t* option = "");
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    ClassDef(MHBadPixels, 1)  // Histogram of bad pixel Id vs. Theta
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mbadpixels/MMcBadPixelsSet.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MMcBadPixelsSet.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MMcBadPixelsSet.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbadpixels/MMcBadPixelsSet.h
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/MMcBadPixelsSet.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/MMcBadPixelsSet.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbadpixels/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mbadpixels/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbadpixels/Makefile	(revision 17960)
@@ -0,0 +1,49 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = BadPixels
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../manalysis -I../mgeom -I../mgui \
+           -I../mmc -I../mpedestal -I../msignal -I../mpointing \
+           -I../mhbase -I../mhist -I../mraw
+# MBadPixelsCalc  (manalysis): MPedPhotCam, MSigmabar
+# MBadPixelsCalc  (mgeom):     MGeomCam
+# MBadPixelsCam   (mgui):      MCamEvent
+# MMcBadPixelsSet (mmc):       MMcRunHeader
+# MBadPixelsTreat (mpedestal): MPedPhot*
+# MBadPixelsTreat (msignal):   MArrivalTime
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MBadPixelsPix.cc \
+           MBadPixelsCam.cc \
+           MBadPixelsMerge.cc \
+           MBadPixelsCalc.cc \
+           MBadPixelsTreat.cc \
+           MMcBadPixelsSet.cc \
+           MHBadPixels.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mbase/BaseIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/BaseIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/BaseIncl.h	(revision 17960)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TArrayD.h>
+#include <TVector3.h>
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mbase/BaseLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/BaseLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/BaseLinkDef.h	(revision 17960)
@@ -0,0 +1,101 @@
+#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+;
+
+// I/O
+//#pragma link C++ class MBzlib2+;
+
+// Basic Network Tools
+#pragma link C++ class MReadSocket+;
+
+// Basic Tools
+#pragma link C++ namespace MARS;
+#pragma link C++ namespace MMath;
+#pragma link C++ namespace UTF8;
+
+#pragma link C++ class MSpline3+;
+#pragma link C++ class MQuaternion+;
+#pragma link C++ class MReflection+;
+
+#pragma link C++ class MString+;
+#pragma link C++ class MEnv+;
+#pragma link C++ class MIter+;
+#pragma link C++ class MDirIter+;
+//#pragma link C++ class MRunIter+;
+#pragma link C++ class MThread+;
+
+// Mars core
+#pragma link C++ class MInputStreamID+;
+
+#pragma link C++ class MParContainer+;
+#pragma link C++ class MParList+;
+
+#pragma link C++ class MTask+;
+#pragma link C++ class MTaskEnv+;
+#pragma link C++ class MTaskInteractive+;
+#pragma link C++ class MTaskList+;
+
+#pragma link C++ class MFilter+;
+
+#pragma link C++ class MEvtLoop+;
+
+// Mars core (GUI part)
+#pragma link C++ class MStatusArray+;
+#pragma link C++ class MStatusDisplay+;
+#pragma link C++ class MProgressBar+;
+#pragma link C++ class MSearch+;
+
+#pragma link C++ class MGTask+;
+#pragma link C++ class MGList+;
+#pragma link C++ class MGMap+;
+#pragma link C++ class MGGroupFrame+;
+
+// Root enhancements
+//#pragma link C++ class MGraph+;
+
+// Basic containers
+#pragma link C++ class MArray;
+#pragma link C++ class MArrayB;
+#pragma link C++ class MArrayS;
+#pragma link C++ class MArrayD;
+#pragma link C++ class MArrayF;
+#pragma link C++ class MArrayI;
+
+#pragma link C++ class MLut+;
+#pragma link C++ class MObjLookup+;
+
+#pragma link C++ class MTime+;
+#pragma link C++ function operator<<(ostream&, const MTime&);
+#pragma link C++ function operator>>(istream&, MTime&);
+
+#pragma link C++ class MArgs+;
+#pragma link C++ class MArgsEntry+;
+
+#pragma link C++ class MParameterI+;
+#pragma link C++ class MParameterD+;
+#pragma link C++ class MParameterDerr+;
+
+#pragma link C++ class MParEnv+;
+#pragma link C++ class MParEmulated+;
+
+#pragma link C++ class MParSpline+;
+
+// Tool tasks
+#pragma link C++ class MClone+;
+#pragma link C++ class MPrint+;
+#pragma link C++ class MContinue+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MAGIC.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MAGIC.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MAGIC.cc	(revision 17960)
@@ -0,0 +1,74 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MARS
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MAGIC.h"
+
+#include <stdlib.h> // getenv (Ubuntu 8.10)
+
+#include <iostream>
+
+//NamespaceImp(MARS);
+
+using namespace std;
+
+bool MARS::CheckRootVer()
+{
+    if (strcmp(gROOT->GetVersion(), "5.22/00")>0 && strcmp(gROOT->GetVersion(), "5.26/00")<0)
+    {
+        cout << "WARNING - Especially root 5.24/00 has a severe bug in projection 2D histograms" << endl;
+        cout << "          which might cause unexpected crashes and could also affect the results." << endl;
+        cout << "          Please, avoid using these root versions." << endl;
+    }
+
+    if (!strcmp(gROOT->GetVersion(), ROOT_RELEASE))
+        return true;
+
+    cout << "FATAL ERROR - ROOT version mismatch." << endl;
+    cout << "  Your mars has been compiled using root v" << ROOT_RELEASE << endl;
+    cout << "  The libraries you are using are from root v" << gROOT->GetVersion() << endl;
+    cout << "  Your environment contains:" << endl;
+    cout << "    ROOTSYS         = " << getenv("ROOTSYS") << endl;
+    cout << "    PATH            = " << getenv("PATH") << endl;
+    cout << "    LD_LIBRARY_PATH = " << getenv("LD_LIBRARY_PATH") << endl << endl;
+    cout << "  If this is the right root-version please do" << endl;
+    cout << "    make mrproper && make" << endl;
+    cout << "  for a complete recompilation." << endl << endl;
+    cout << "  If this is the wrong root-version make sure that the file ~/.bashrc contains:" << endl;
+    cout << "    export ROOTSYS=/PathTo/Your/RootVersion" << endl;
+    cout << "    export PATH=$ROOTSYS/bin:$PATH" << endl;
+    cout << "    export LD_LIBRARY_PATH=$ROOTSYS/lib:$LD_LIBRARY_PATH" << endl;
+    cout << "  and start a new shell. Check it by typing \"export\"" << endl;
+    cout << endl;
+
+    return false;
+}
+
+TString MARS::GetPackageName() { return PACKAGE_NAME; }
+TString MARS::GetPackageVersion() { return PACKAGE_VERSION; }
+TString MARS::GetRevision() { return REVISION; }
Index: branches/Mars_McMismatchStudy/mbase/MAGIC.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MAGIC.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MAGIC.h	(revision 17960)
@@ -0,0 +1,101 @@
+#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
+
+#ifndef R__FOR_EACH
+#define R__FOR_EACH ForEach
+#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;
+
+namespace MARS
+{
+    bool CheckRootVer();
+    TString GetPackageName();
+    TString GetPackageVersion();
+    TString GetRevision();
+}
+
+// Check for example: http://www.utf8-zeichentabelle.de
+namespace UTF8
+{
+    const char *const kCent        = "\xc2\xa2";
+    const char *const kPound       = "\xc2\xa3";
+    const char *const kYen         = "\xc2\xa5";
+    const char *const kParagraph   = "\xc2\xa7";
+    const char *const kCopyright   = "\xc2\xa9";
+    const char *const kRegistered  = "\xc2\xae";
+    const char *const kDeg         = "\xc2\xb0";
+    const char *const kPlusMinus   = "\xc2\xb1";
+    const char *const kSquare      = "\xc2\xb2";
+    const char *const kThird       = "\xc2\xb3";
+    const char *const kMu          = "\xc2\xb5";
+    const char *const kDot         = "\xc2\xb7";
+    const char *const kQuarter     = "\xc2\xbc";
+    const char *const kHalf        = "\xc2\xbd";
+    const char *const kSmaller     = "\xc2\xab";
+    const char *const kLarger      = "\xc2\xbb";
+    const char *const kThreeFourth = "\xc2\xbe";
+    const char *const kTimes       = "\xc3\x97";
+    const char *const kCapGamma    = "\xce\x93";
+    const char *const kCapDelta    = "\xce\x94";
+    const char *const kCapSigma    = "\xce\xa3";
+    const char *const kCapTheta    = "\xce\x98";
+    const char *const kCapLambda   = "\xce\x9b";
+    const char *const kCapXi       = "\xce\x9e";
+    const char *const kCapPi       = "\xce\xa0";
+    const char *const kCapPhi      = "\xce\xa6";
+    const char *const kCapPsi      = "\xce\xa8";
+    const char *const kCapOmega    = "\xce\xa9";
+    const char *const kAlpha       = "\xce\xb1";
+    const char *const kBata        = "\xce\xb2";
+    const char *const kGamma       = "\xce\xb3";
+    const char *const kDelta       = "\xce\xb4";
+    const char *const kEpsilon     = "\xce\xb5";
+    const char *const kZeta        = "\xce\xb6";
+    const char *const kEta         = "\xce\xb7";
+    const char *const kTheta       = "\xce\xb8";
+    const char *const kIota        = "\xce\xb9";
+    const char *const kKappa       = "\xce\xba";
+    const char *const kLambda      = "\xce\xbb";
+    const char *const kNu          = "\xce\xbd";
+    const char *const kXi          = "\xce\xbe";
+    const char *const kOmicron     = "\xce\xbf";
+    const char *const kPi          = "\xce\xc0";
+    const char *const kRho         = "\xce\xc1";
+    const char *const kSigma       = "\xce\xc3";
+    const char *const kTau         = "\xce\xc4";
+    const char *const kPhi         = "\xce\xc6";
+    const char *const kChi         = "\xce\xc7";
+    const char *const kPsi         = "\xce\xc8";
+    const char *const kOmega       = "\xce\xc9";
+    const char *const kEuro        = "\xe2\x82\xac";
+}
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MArgs.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArgs.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArgs.cc	(revision 17960)
@@ -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, 7/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2003-2008
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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'
+//
+// All arguments appearing after '--' on the commandline are
+//  also cosidered as '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 *) 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)
+{
+    TString cmdline;
+    // FIXME: argv has no const-qualifier to be idetical with
+    //        TApplication.
+    fName  = argv[0];
+    fTitle = argv[0];
+
+    fArgv.SetOwner();
+
+    for (int i=1; i<argc; i++)
+    {
+        fTitle += " ";
+        fTitle += argv[i];
+        fArgv.Add(new MArgsEntry(argv[i]));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Remove all root commandline options from the list,
+//  namely: -b, -n, -q, -l, -?, -h, --help, -config
+//
+//  Returns the number of found root options (max 8)
+//
+Int_t MArgs::RemoveRootArgs()
+{
+    Int_t n = 0;
+
+    n += HasOnlyAndRemove("-b");
+    n += HasOnlyAndRemove("-n");
+    n += HasOnlyAndRemove("-q");
+    n += HasOnlyAndRemove("-l");
+    n += HasOnlyAndRemove("-?");
+    n += HasOnlyAndRemove("-h");
+    n += HasOnlyAndRemove("--help");
+    n += HasOnlyAndRemove("-config");
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print everything parsed.
+// Using 'options' as option only 'options' are printed.
+// Using 'arguments' as option only 'arguments' are printed.
+// Using 'cmdline' as option the command line is printed instead of
+//       just the program name
+//
+void MArgs::Print(const Option_t *o) const
+{
+    TString str(o);
+
+    gLog << all << underline;
+    if (str.Contains("cmdline"))
+        gLog << fTitle << endl;
+    else
+        gLog << fName << ":" << endl;
+
+    str.ReplaceAll("cmdline", "");
+    str.ReplaceAll(" ", "");
+
+    if (!str.CompareTo("options", TString::kIgnoreCase))
+    {
+        TIter Next(&fArgv);
+        TString *s = NULL;
+        while ((s=dynamic_cast<TString*>(Next())))
+            if (*s!="--" && 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!="--" && !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 "";
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Integer corresponding to the i-th argument. This is ment
+// for enumerations like
+//  executable 1 7 2
+//  GetArgumentInt(1) will return 7
+//
+Int_t MArgs::GetArgumentInt(Int_t i) const
+{
+    return atoi(GetArgumentStr(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the floating point value corresponding to the i-th argument.
+// This is ment for enumerations like
+//  executable 1.7 7.5 2.3
+//  GetArgumentFloat(1) will return 7.5
+//
+Float_t MArgs::GetArgumentFloat(Int_t i) const
+{
+    return atof(GetArgumentStr(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetIntAndRemove. If HasOption returns kFALSE def is returned.
+//
+Int_t MArgs::GetIntAndRemove(const TString name, Int_t def)
+{
+    if (!HasOption(name))
+        return def;
+    return GetIntAndRemove(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetFloatAndRemove. If HasOption returns kFALSE def is returned.
+//
+Double_t MArgs::GetFloatAndRemove(const TString name, Double_t def)
+{
+    if (!HasOption(name))
+        return def;
+    return GetFloatAndRemove(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetStringAndRemove. If HasOption returns kFALSE def is returned.
+//
+TString MArgs::GetStringAndRemove(const TString name, const TString def)
+{
+    if (!HasOption(name))
+        return def;
+    return GetStringAndRemove(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the MArgsEntry of 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
+//
+MArgsEntry *MArgs::GetArgument(Int_t i) const
+{
+    Int_t num = 0;
+
+    Bool_t allarg = kFALSE;
+
+    TIter Next(&fArgv);
+    MArgsEntry *e = NULL;
+    while ((e=static_cast<MArgsEntry*>(Next())))
+    {
+        const TString &s=*dynamic_cast<TString*>(e);
+
+        if (s=="--")
+        {
+            allarg = kTRUE;
+            continue;
+        }
+
+        if (s.BeginsWith("-") && !allarg)
+            continue;
+
+        if (i==num++)
+            return e;
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+{
+    const MArgsEntry *e = GetArgument(i);
+    return e==0 ? "" : dynamic_cast<const TString&>(*e);
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of arguments without a trainling '-'
+//
+Int_t MArgs::GetNumArguments() const
+{
+    Int_t num = 0;
+
+    Bool_t allarg = kFALSE;
+
+    TIter Next(&fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+    {
+        if (*s=="--")
+        {
+            allarg = kTRUE;
+            continue;
+        }
+
+        if (s->BeginsWith("-") && !allarg)
+            continue;
+
+        num++;
+    }
+
+    return num;
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove the i-th argument from the list. Return kTRUE in case of sucess
+// kFALSE otherwise
+//
+Bool_t MArgs::RemoveArgument(Int_t i)
+{
+    MArgsEntry *e = GetArgument(i);
+    if (!e)
+        return kFALSE;
+
+    delete fArgv.Remove(e);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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=="--")
+            return num;
+
+        if (s->BeginsWith("-"))
+            num++;
+    }
+
+    return num;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the total number of entries
+//
+Int_t MArgs::GetNumEntries() const
+{
+    return fArgv.FindObject("--") ? fArgv.GetSize()-1 : fArgv.GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is existing, eg:
+//  executable -value5
+//  executable -value
+//  HasOption("-value") will return true in both cases
+//
+Bool_t MArgs::Has(const TString n) const
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    TIter Next(&fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (s->BeginsWith(name))
+            return kTRUE;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is existing, eg:
+//  executable -value5
+//   HasOption("-value") will return false
+//  executable -value
+//   HasOption("-value") will return true
+//
+Bool_t MArgs::HasOnly(const TString n) const
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    TIter Next(&fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (*s==name)
+            return kTRUE;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is exists and a
+// corresponding option is available, eg.
+//  executable -value5
+//  HasOption("-value") will return true
+// but:
+//  executable -value
+//  HasOption("-value") will return false
+//
+Bool_t MArgs::HasOption(const TString n) const
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    TIter Next(&fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (s->BeginsWith(name) && s->Length()>name.Length())
+            return kTRUE;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is exists and a
+// corresponding option is available, eg.
+//  executable -value5
+//  HasOption("-value") will return false
+// but:
+//  executable -value
+//  HasOption("-value") will return true
+//
+// The argument is removed from the internal list.
+//
+Bool_t MArgs::HasOnlyAndRemove(const TString n)
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    Bool_t rc = kFALSE;
+
+    TIter Next(&fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (*s==name)
+        {
+            delete fArgv.Remove(dynamic_cast<TObject*>(s));
+            rc = kTRUE;
+        }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return all arguments and options in the order as they are stored
+// in memory.
+//
+TString MArgs::GetCommandLine() const
+{
+    TString rc;
+
+    TIter Next(&fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+    {
+        rc += *s;
+        rc += " ";
+    }
+
+    return rc.Strip(TString::kBoth);
+}
Index: branches/Mars_McMismatchStudy/mbase/MArgs.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArgs.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArgs.h	(revision 17960)
@@ -0,0 +1,80 @@
+#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()
+    {
+        ReplaceAll("\015", "");
+        dynamic_cast<TString&>(*this) = Strip(TString::kBoth);
+    }
+
+    void Print(const Option_t *o) const;
+
+    ClassDef(MArgsEntry, 0)
+};
+
+class MArgs : public TNamed
+{
+private:
+    Int_t fArgc; //!
+    TList fArgv; //!
+
+    MArgsEntry *GetArgument(Int_t i) const;
+    MArgsEntry *GeOption(Int_t i) const;
+
+public:
+    MArgs(int argc, char **argv);
+
+    // TObject
+    void Print(const Option_t *o="") const;
+
+    // FIXME: Add max, min option
+    // FIXME: Add default option
+
+    // MArgs
+    Int_t    RemoveRootArgs();
+
+    Int_t    GetInt(const TString name) const;
+    Double_t GetFloat(const TString name) const;
+    TString  GetString(const TString name) const;
+
+    Int_t    GetIntAndRemove(const TString name);
+    Double_t GetFloatAndRemove(const TString name);
+    TString  GetStringAndRemove(const TString name);
+
+    Int_t    GetIntAndRemove(const TString name, Int_t def);
+    Double_t GetFloatAndRemove(const TString name, Double_t def);
+    TString  GetStringAndRemove(const TString name, const TString def);
+
+    Bool_t   Has(const TString name) const;
+    Bool_t   HasOnly(const TString name) const;
+    Bool_t   HasOption(const TString name) const;
+    Bool_t   HasOnlyAndRemove(const TString name);
+
+    TString  GetArgumentStr(Int_t i) const;
+    Int_t    GetArgumentInt(Int_t i) const;
+    Float_t  GetArgumentFloat(Int_t i) const;
+    Int_t    GetNumArguments() const;
+    Int_t    GetNumOptions() const;
+    Int_t    GetNumEntries() const;
+
+    Bool_t   RemoveArgument(Int_t i);
+
+    TString  GetCommandLine() const;
+
+    static TString GetCommandLine(int argc, char **argv) { return MArgs(argc, argv).GetCommandLine(); }
+
+    ClassDef(MArgs, 0)  //Class to parse command line arguments
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MArray.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArray.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArray.cc	(revision 17960)
@@ -0,0 +1,41 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// MArray                                                                   //
+//                                                                          //
+// This is an abstract base class for TObject derived Arrays. In principal  //
+// it is almost the same than TArray. The difference is that this array     //
+// base classed is derived from TObject which makes storage of variable     //
+// sized arrays possible with splitlevel=1.                                 //
+//                                                                          //
+// This should not be needed anymore for root >3.00                         //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MArray.h"
+
+ClassImp(MArray);
+
Index: branches/Mars_McMismatchStudy/mbase/MArray.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArray.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArray.h	(revision 17960)
@@ -0,0 +1,35 @@
+#ifndef MARS_MArray
+#define MARS_MArray
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MArray                                                                  //
+//                                                                         //
+// Abstract array base class for TObject derived Arrays                    //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class MArray : public TObject
+{
+protected:
+    UInt_t fN; // Number of array elements
+
+public:
+   MArray()                              { fN = 0; }
+   MArray(UInt_t n)                      { fN = n; }
+   MArray(const MArray &a) : TObject()   { fN = a.fN; }
+   virtual ~MArray()                     { fN = 0; }
+
+   MArray &operator=(const MArray &rhs)  { fN = rhs.fN; return *this; }
+
+   UInt_t       GetSize() const          { return fN; }
+   virtual void Set(UInt_t n) = 0;
+   
+   ClassDef(MArray, 1)  //Abstract array base class for TObject derived Arrays
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MArrayB.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayB.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayB.cc	(revision 17960)
@@ -0,0 +1,38 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayB
+//
+// Array of Byte_t. It is almost the same than TArrayC, but it containes
+// Byte_t instead of Char_t and it can be stored with splitlevel=1 to a
+// a root-file because of it's derivement from MArray (TObject)                                                                                    //
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayB.h"
+
+ClassImp(MArrayB);
+
Index: branches/Mars_McMismatchStudy/mbase/MArrayB.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayB.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayB.h	(revision 17960)
@@ -0,0 +1,180 @@
+#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) : MArray()
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    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 Reset(Byte_t v)
+    {
+        for (Byte_t *b=fArray; b<fArray+fN; b++)
+            *b = v;
+    }
+
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Byte_t *temp = fArray;
+        if (n == 0)
+            fArray = 0;
+        else
+        {
+            fArray = new Byte_t[n];
+            if (n < fN)
+                memcpy(fArray,temp, n*sizeof(Byte_t));
+            else
+            {
+                memcpy(fArray,temp,fN*sizeof(Byte_t));
+                memset(&fArray[fN],0,(n-fN)*sizeof(Byte_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Byte_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Byte_t[fN];
+
+        memcpy(fArray,array, n*sizeof(Byte_t));
+    }
+
+    Byte_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Byte_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    ClassDef(MArrayB, 1)  //Array of Byte_t
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MArrayD.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayD.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayD.cc	(revision 17960)
@@ -0,0 +1,73 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayD
+//
+// Array of Double_t. It is almost the same than TArrayD but derives from
+// TObject
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayD.h"
+#include "TArrayD.h"
+
+ClassImp(MArrayD);
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayD::StripZeros(TArrayD &arr)
+{
+
+  const Int_t n = arr.GetSize();
+  
+  for (Int_t i=n-1; i>=0; i--)
+    if (arr[i] != 0)
+        {
+          arr.Set(i+1);
+          break;
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayD::StripZeros()
+{
+    const Int_t n = GetSize();
+
+    for (Int_t i=n-1; i>=0; i--)
+      if ((*this)[i] != 0)
+        {
+          Set(i+1);
+          break;
+        }
+}
+
Index: branches/Mars_McMismatchStudy/mbase/MArrayD.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayD.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayD.h	(revision 17960)
@@ -0,0 +1,176 @@
+#ifndef MARS_MArrayD
+#define MARS_MArrayD
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class TArrayD;
+class MArrayD : public MArray
+{
+private:
+    Double_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayD()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayD(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+        Set(n);
+    }
+
+    MArrayD(UInt_t n, Double_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+        Set(n, array);
+    }
+
+    MArrayD(const MArrayD &array) : MArray()
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    MArrayD &operator=(const MArrayD &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayD()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, Double_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(Double_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    Double_t     At(UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    Double_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(Double_t));
+    }
+
+    void Reset(Double_t v)
+    {
+        for (Double_t *d=fArray; d<fArray+fN; d++)
+            *d = v;
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Double_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new Double_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(Double_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(Double_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(Double_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Double_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Double_t[fN];
+
+        memcpy(fArray, array, n*sizeof(Double_t));
+    }
+
+    Double_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Double_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    Double_t GetSum() const
+    {
+        const Double_t *end = fArray+fN;
+
+        Double_t sum = 0;
+        for (Double_t *ptr = fArray; ptr<end; ptr++)
+            sum += *ptr;
+        return sum;
+    }
+
+    static void  StripZeros(TArrayD &arr);
+    void  StripZeros();
+
+    ClassDef(MArrayD, 1)  //Array of Double_t
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MArrayF.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayF.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayF.cc	(revision 17960)
@@ -0,0 +1,73 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayF
+//
+// Array of Float_t. It is almost the same than TArrayF but derives from
+// TObject
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayF.h"
+#include "TArrayF.h"
+
+ClassImp(MArrayF);
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayF::StripZeros(TArrayF &arr)
+{
+
+  const Int_t n = arr.GetSize();
+  
+  for (Int_t i=n-1; i>=0; i--)
+    if (arr[i] != 0)
+        {
+          arr.Set(i+1);
+          break;
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayF::StripZeros()
+{
+    const Int_t n = GetSize();
+
+    for (Int_t i=n-1; i>=0; i--)
+      if ((*this)[i] != 0)
+        {
+          Set(i+1);
+          break;
+        }
+}
+
Index: branches/Mars_McMismatchStudy/mbase/MArrayF.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayF.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayF.h	(revision 17960)
@@ -0,0 +1,213 @@
+#ifndef MARS_MArrayF
+#define MARS_MArrayF
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class TArrayF;
+class MArrayF : public MArray
+{
+private:
+    Float_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayF()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayF(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+        Set(n);
+    }
+
+    MArrayF(UInt_t n, Float_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+        Set(n, array);
+    }
+
+    MArrayF(const MArrayF &array) : MArray()
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    MArrayF &operator=(const MArrayF &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayF()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, Float_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(Float_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    Float_t     At(UInt_t i) const 
+    {
+        return fArray[i];
+    }
+
+    Float_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(Float_t));
+    }
+
+    void Reset(Float_t v)
+    {
+        for (Float_t *f=fArray; f<fArray+fN; f++)
+            *f = v;
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Float_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new Float_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(Float_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(Float_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(Float_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Float_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Float_t[fN];
+
+        memcpy(fArray, array, n*sizeof(Float_t));
+    }
+
+    Float_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Float_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    Double_t GetSum() const
+    {
+        const Float_t *end = fArray+fN;
+
+        Double_t sum = 0;
+        for (Float_t *ptr=fArray; ptr<end; ptr++)
+            sum += *ptr;
+
+        return sum;
+    }
+
+    template<class T>
+        void Add(const T *src, UInt_t n, UInt_t beg=0, Float_t scale=1)
+    {
+        if (!src || beg >= fN)
+            return;
+
+        Float_t *ptr = fArray+beg;
+        const Float_t *end  = beg+n>fN ? fArray+fN : ptr+n;
+
+        // we treat the case m==1. special, in order to speed up the code a bit
+        // since when m==1. the multiplication can be omitted and this should be a bit faster then.
+        if (scale==1)
+        {
+            while (ptr<end)
+                *ptr++ += *src++;
+        }
+        else
+        {
+            while (ptr<end)
+                *ptr++ += (*src++) * scale;
+        }
+    }
+
+    template<class T>
+        void AddClipped(Double_t th, const T *src, UInt_t n, UInt_t beg=0)
+    {
+        if (!src || beg>=fN)
+            return;
+
+        Float_t *ptr = fArray + beg;
+        const Float_t *end  = beg+n>fN ? fArray+fN : ptr+n;
+
+        while (ptr<end)
+            *ptr++ += TMath::Min(*src++, th);
+    }
+
+    static void  StripZeros(TArrayF &arr);
+    void  StripZeros();
+
+    ClassDef(MArrayF, 1)  //Array of Float_t
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MArrayI.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayI.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayI.cc	(revision 17960)
@@ -0,0 +1,45 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayI
+//
+// Array of Int_t. It is almost the same than TArrayI but derives from
+// TObject
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayI.h"
+
+#include "MMath.h"
+
+ClassImp(MArrayI);
+
+void MArrayI::ReSort(Bool_t down)
+{
+    MMath::ReSort(fN, fArray, down);
+}
Index: branches/Mars_McMismatchStudy/mbase/MArrayI.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayI.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayI.h	(revision 17960)
@@ -0,0 +1,185 @@
+#ifndef MARS_MArrayI
+#define MARS_MArrayI
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class MArrayI : public MArray
+{
+private:
+    Int_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayI()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayI(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+        Set(n);
+    }
+
+    MArrayI(UInt_t n, Int_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+        Set(n, array);
+    }
+
+    MArrayI(const MArrayI &array) : MArray()
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    MArrayI &operator=(const MArrayI &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayI()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, Int_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(Int_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    void Add(Int_t c)
+    {
+        Set(fN+1);
+        fArray[fN-1] = c;
+    }
+
+    Int_t Find(Int_t c) const
+    {
+        for (Int_t *ptr=fArray; ptr<fArray+fN; ptr++)
+            if (*ptr==c)
+                return ptr-fArray;
+
+        return -1;
+    }
+
+    void AddUniq(Int_t c)
+    {
+        if (Find(c)<0)
+            Add(c);
+    }
+
+    Int_t     At(UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    Int_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(Int_t));
+    }
+
+    void Reset(Int_t v)
+    {
+        for (Int_t *i=fArray; i<fArray+fN; i++)
+            *i = v;
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Int_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new Int_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(Int_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(Int_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(Int_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Int_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Int_t[fN];
+
+        memcpy(fArray, array, n*sizeof(Int_t));
+    }
+
+    Int_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Int_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    void ReSort(Bool_t down=kFALSE);
+
+    ClassDef(MArrayI, 1)  //Array of Int_t
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MArrayS.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayS.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayS.cc	(revision 17960)
@@ -0,0 +1,40 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayS
+//
+// Array of UShort_t. It is almost the same than TArrayS, but it containes
+// UShort_t instead of Short_t and it can be stored with splitlevel=1 to a
+// a root-file because of it's derivement from MArray (TObject)                                                                                    //
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayS.h"
+
+ClassImp(MArrayS);
+
Index: branches/Mars_McMismatchStudy/mbase/MArrayS.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MArrayS.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MArrayS.h	(revision 17960)
@@ -0,0 +1,170 @@
+#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) : MArray()
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    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 Reset(UShort_t v)
+    {
+        for (UShort_t *s=fArray; s<fArray+fN; s++)
+            *s = v;
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        UShort_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new UShort_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(UShort_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(UShort_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(UShort_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, UShort_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new UShort_t[fN];
+
+        memcpy(fArray, array, n*sizeof(UShort_t));
+    }
+
+    UShort_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const UShort_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    ClassDef(MArrayS, 1)  //Array of UShort_t
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MBzlib2.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MBzlib2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MBzlib2.cc	(revision 17960)
@@ -0,0 +1,166 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MBzlib2
+//
+// This is a C++ wrapper for zlib (taken from root)
+//
+// WARNING: - There might not be support for all features.
+//          - seek calls might be rather slow
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MBzlib2.h"
+
+#include <string.h>
+
+ClassImp(MBzlib2);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Open a file by name. Test if it is open like for an ifstream
+// It doesn't matter whether the file is gzip compressed or not.
+//
+void MBzlib2::open(const char* name)
+{
+    if (is_open())
+    {
+        clear(rdstate()|ios::badbit);
+        return;
+    }
+
+    fFile = BZ2_bzopen(name, "rb0");
+    if (fFile == 0)
+    {
+        clear(rdstate()|ios::badbit);
+        return;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Close an open file.
+//
+void MBzlib2::close()
+{
+    if (!is_open())
+        return;
+
+    sync();
+
+    BZ2_bzclose(fFile);
+//    if (BZ2_bzclose(fFile) != Z_OK)
+//        clear(rdstate()|ios::badbit);
+
+    fFile = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+int MBzlib2::underflow()
+{
+    if (gptr() && gptr()<egptr())
+        return * reinterpret_cast<unsigned char *>(gptr());
+
+    if (!is_open())
+        return EOF;
+
+    // implementation of inbuf
+    const int putback = gptr()-eback()>4 ? 4 : gptr()-eback();
+
+    memcpy(fBuffer+(4-putback), gptr()-putback, putback);
+
+    const int num = BZ2_bzread(fFile, fBuffer+4, fgBufferSize-4);
+    if (num <= 0) // ERROR or EOF
+        return EOF;
+
+    // reset buffer pointers
+    setg(fBuffer+(4-putback), fBuffer+4, fBuffer+4+num);
+
+    // return next character
+    return *reinterpret_cast<unsigned char *>(gptr());
+}
+
+// --------------------------------------------------------------------------
+//
+int MBzlib2::flush_buffer()
+{
+    // Separate the writing of the buffer from overflow() and sync() operation.
+    const int w = pptr() - pbase();
+
+    if (BZ2_bzwrite(fFile, pbase(), w) != w)
+        return EOF;
+
+    pbump(-w);
+
+    return w;
+}
+
+/*
+int MBzlib2::overflow( int c)
+{
+    if ( ! ( mode & ios::out) || ! opened)
+        return EOF;
+
+    if (c != EOF)
+    {
+        *pptr() = c;
+        pbump(1);
+
+    }
+    if ( flush_buffer() == EOF)
+        return EOF;
+
+    return c;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+int MBzlib2::sync()
+{
+    // Use flush_buffer() instead of overflow(EOF) to
+    // cause proper behavior with std::endl and flush()
+    if (pptr() && pptr()>pbase())
+    {
+        if (flush_buffer() == EOF)
+            return -1;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+streambuf::pos_type MBzlib2::seekoff(streambuf::off_type offset, ios_base::seekdir dir, ios_base::openmode)
+{
+    char *c = new char[offset];
+    int rc = BZ2_bzread(fFile, c, offset);
+    delete c;
+    return rc;
+//    return gzseek(fFile, offset, dir);
+}
Index: branches/Mars_McMismatchStudy/mbase/MBzlib2.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MBzlib2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MBzlib2.h	(revision 17960)
@@ -0,0 +1,56 @@
+#ifndef MARS_MBzlib2
+#define MARS_MBzlib2
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+
+#ifdef __CINT__
+typedef void *BZFILE;
+#else
+#include <bzlib.h>
+#endif
+
+#include <iostream>  // base classes for MLog
+
+class MBzlib2 : public std::streambuf, virtual public std::istream, public TObject
+{
+private:
+    static const int fgBufferSize = 47+256; // size of data buff totals 512 bytes under g++ for igzstream at the end.
+
+    BZFILE *fFile;                 // file handle for compressed file
+    char    fBuffer[fgBufferSize]; // data buffer
+
+    int flush_buffer();
+    int underflow();
+    int sync();
+
+public:
+    MBzlib2() : istream(this), fFile(0)
+    {
+        setp(fBuffer,   fBuffer+fgBufferSize-1);
+        setg(fBuffer+4, fBuffer+4, fBuffer+4);
+    }
+    MBzlib2(const char *name) : istream(this), fFile(0)
+    {
+        setp(fBuffer,   fBuffer+fgBufferSize-1);
+        setg(fBuffer+4, fBuffer+4, fBuffer+4);
+
+        open(name);
+    }
+    ~MBzlib2() { MBzlib2::close(); }
+
+    int is_open() { return fFile!=0; }
+
+    void open(const char* name);
+    void close();
+
+    std::streambuf::pos_type seekoff(std::streambuf::off_type, std::ios_base::seekdir,
+                                     std::ios_base::openmode = std::ios_base::in | std::ios_base::out);
+    //std::streambuf::pos_type seekpos(std::streambuf::pos_type,
+    //                                 std::ios_base::openmode = std::ios_base::in | std::ios_base::out);
+
+    ClassDef(MBzlib2, 0) // A C++ wrapper to istream zlib files
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MClone.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MClone.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MClone.cc	(revision 17960)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  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";
+
+    fForceClone = kFALSE;
+
+    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()
+{
+    if (fClone && !fForceClone)
+    {
+        fObject->Copy(*fClone);
+        return kTRUE;
+    }
+
+    Clear();
+
+    fClone = fObject->Clone();
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mbase/MClone.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MClone.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MClone.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MClone
+#define MARS_MClone
+
+#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
+
+    Bool_t fForceClone;
+
+    // MClone
+    void Init(const char *name, const char *title);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+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();
+
+    // TObject
+    void Clear(Option_t *opt=NULL);
+
+    // MClone
+    TObject *GetClone() const  { return fClone; }
+    const TObject *GetObject() const { return fObject; }
+
+    void SetForceClone(Bool_t b=kTRUE) { fForceClone = b; }
+
+    ClassDef(MClone, 0) // Task to clone (duplicate) an object in memory
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/mbase/MContinue.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MContinue.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MContinue.cc	(revision 17960)
@@ -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 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:
+//   -/-
+//
+//
+// Class Version 2:
+// ----------------
+//  + Int_t fRc;
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MContinue.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MF.h"
+#include "MString.h"
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MContinue);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Use this constructor if a rule (see MF for more details) shell be used.
+// MContinue will create a MF object and use it as a filter for the
+// instance. The MF-Task is added to the tasklist in front of the MContinue
+// instance and also automatically deleted, eg.
+//   MContinue cont("MHillas.fSize<20");
+//   tasklist.AddToList(&cont);
+// would skip all events which fullfill "MHillas.fSize<20" from this point
+// in the tasklist.
+// It is not necessary to put the filter in the tasklist. The PreProcess
+// will search for the filter and if it isn't found in the tasklist it
+// is added to the tasklist in front of MContinue.
+//
+// Use the default constructor (or an empty rule) if you want to read the
+// rule from a resource file.
+//
+MContinue::MContinue(const TString rule, const char *name, const char *title)
+    : fTaskList(0), fRc(kCONTINUE)
+{
+    fName  = name  ? name  : "MContinue";
+    fTitle = title ? title : "Task returning kCONTINUE";
+
+    if (rule.IsNull())
+        return;
+
+    SetBit(kIsOwner);
+
+    MTask::SetFilter(new MF(rule, TString("MF(")+fName+")"));
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this if you have a filter. Would be the same as if you would call:
+//   MContinue cont;
+//   cont.SetFilter(f);
+// It is not necessary to put the filter in the tasklist. The PreProcess
+// will search for the filter and if it isn't found in the tasklist it
+// is added to the tasklist in front of MContinue.
+//
+MContinue::MContinue(MFilter *f, const char *name, const char *title)
+    : fTaskList(0), fRc(kCONTINUE)
+{
+    fName  = name  ? name  : "MContinue";
+    fTitle = title ? title : "Task returning kCONTINUE (or any other return code)";
+
+    SetFilter(f);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete the filter if it was created automatically
+//
+MContinue::~MContinue()
+{
+    if (TestBit(kIsOwner))
+        delete GetFilter();
+}
+
+// --------------------------------------------------------------------------
+//
+//  PreProcess tries to find the tasklist MTaskList, adds the filter
+//  before this instance to the tasklist and preprocesses the filter.
+//
+Int_t MContinue::PreProcess(MParList *list)
+{
+    ResetBit(kFilterIsPrivate);
+
+    if (!GetFilter())
+    {
+        if (IsAllowEmpty())
+        {
+            *fLog << warn << GetDescriptor() << " - WARNING: Filter empty... task removed." << endl;
+            return kSKIP;
+        }
+
+        *fLog << inf << "My filter has vanished... skipping." << endl;
+        return kSKIP;
+    }
+
+    fTaskList = (MTaskList*)list->FindTaskListWithTask(this);
+    if (!fTaskList)
+    {
+        *fLog << err << dbginf << "ERROR - MTaskList with this not found... abort." << endl;
+        return kFALSE;
+    }
+
+    if (fTaskList->FindObject(GetFilter()))
+    {
+        *fLog << inf << dbginf << "The filter is already in the tasklist..." << endl;
+        return kTRUE;
+    }
+
+    if ((TString)GetFilter()->GetName()==fName)
+        GetFilter()->SetName(MString::Format("MF:%s", fName.Data()));
+
+    if (!fTaskList->AddToListBefore(GetFilter(), this))
+    {
+        *fLog << err << dbginf << "ERROR - Adding filter before MContinue failed... abort." << endl;
+        return kFALSE;
+    }
+
+    // Make sure, that everything is correctly propageted to the childs
+    GetFilter()->SetDisplay(fDisplay);
+    GetFilter()->SetLogStream(fLog);
+    GetFilter()->SetAccelerator(GetAccelerator());
+
+    // Remeber that the filter is not already in tasklist
+    SetBit(kFilterIsPrivate);
+
+    return GetFilter()->CallPreProcess(list);
+}
+
+// --------------------------------------------------------------------------
+//
+// Propagate display to filter (if set)
+//
+void MContinue::SetDisplay(MStatusDisplay *d)
+{
+    if (GetFilter())
+        GetFilter()->SetDisplay(d);
+
+    MTask::SetDisplay(d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Propagate log stream to filter (if set)
+//
+void MContinue::SetLogStream(MLog *lg)
+{
+    if (GetFilter())
+        GetFilter()->SetLogStream(lg);
+
+    MTask::SetLogStream(lg);
+}
+
+// --------------------------------------------------------------------------
+//
+// If the filter was added to the tasklist automatically it is removed
+// from the tasklist.
+//
+Int_t MContinue::PostProcess()
+{
+    if (!TestBit(kFilterIsPrivate))
+        return kTRUE;
+
+    if (fTaskList->RemoveFromList(GetFilter()))
+        return kTRUE;
+
+    *fLog << err << "ERROR: MContinue::PostProcess - Cannot remove Filter from tasklist" << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If a filter is setup, call its 'IsInverted' to invert its meaning
+// (boolean "not")
+//
+void MContinue::SetInverted(Bool_t i)
+{
+    if (GetFilter())
+        GetFilter()->SetInverted(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// If a filter is setup, its IsInverted status is returned. If now filter
+// has been setup yet, kFALSE is returned.
+//
+Bool_t MContinue::IsInverted() const
+{
+    return GetFilter() ? GetFilter()->IsInverted() : kFALSE;
+}
+
+void MContinue::Print(Option_t *) const
+{
+    *fLog << all << GetDescriptor() << ":";
+    if (GetFilter())
+        *fLog << " <" << GetFilter()->GetDescriptor() << ">";
+    *fLog << endl;
+    if (GetFilter())
+        GetFilter()->Print();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+// Avoid trailing 0's!
+//
+// Example:
+//   test.C:
+//     MContinue cont("", "MyContinue");
+//
+//   test.rc:
+//     MyContinue.Condition: {0} && {1}
+//     MyContinue.Inverted: yes
+//     MyContinue.0: MHillas.fSize>1000
+//     MyContinue.1: MHillas.fSize<10000
+//   or (the syntax might change in the future!)
+//     MyContinue.Condition: <MMyClass>
+//     MMyClass.Variable1: ...
+//     MMyClass.Variable2: ...
+//
+// For more details see MF::ReadEnv
+//
+Int_t MContinue::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    MFilter *f = GetFilter();
+    if (IsEnvDefined(env, prefix, "Condition", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "Condition", "");
+        txt = txt.Strip(TString::kBoth);
+        if (txt.BeginsWith("<") && txt.EndsWith(">"))
+        {
+            const TString name = txt(1, txt.Length()-2);
+            f = (MFilter*)GetNewObject(name, MFilter::Class());
+            if (!f)
+                return kERROR;
+        }
+    }
+
+    if (!f)
+        f = new MF;
+
+    f->SetName(fName);
+
+    const Bool_t rc = f->ReadEnv(env, prefix, print);
+
+    if (rc!=kTRUE)
+    {
+        if (f!=GetFilter())
+            delete f;
+        return rc;
+    }
+
+    if (f != GetFilter())
+    {
+        if (TestBit(kIsOwner))
+            delete GetFilter();
+        SetBit(kIsOwner);
+    }
+
+    MTask::SetFilter(f);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mbase/MContinue.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MContinue.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MContinue.h	(revision 17960)
@@ -0,0 +1,62 @@
+#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 fRc;             // Return code returned in Process()
+
+    // MTask
+    Int_t  PreProcess(MParList *list);
+    Int_t  Process() { return fRc; }
+    Int_t  PostProcess();
+
+    // MContinue
+    enum { kIsOwner = BIT(14), kFilterIsPrivate = BIT(15), kAllowEmpty = BIT(16) };
+
+public:
+    MContinue(const TString rule="", const char *name=NULL, const char *title=NULL);
+    MContinue(MFilter *f, const char *name=NULL, const char *title=NULL);
+    ~MContinue();
+
+    // MContinue
+    void SetAllowEmpty(Bool_t b=kTRUE) { b ? SetBit(kAllowEmpty) : ResetBit(kAllowEmpty); }
+    Bool_t IsAllowEmpty() const { return TestBit(kAllowEmpty); }
+
+    void SetInverted(Bool_t i=kTRUE);
+    Bool_t IsInverted() const;
+
+    void SetRc(Int_t rc) { fRc = rc; }
+
+    // MParContainer
+    void SetDisplay(MStatusDisplay *d);
+    void SetLogStream(MLog *lg);
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // TObject
+    void Print(Option_t *o="") const; //*MENU*
+
+    ClassDef(MContinue, 2) //Task returning kCONTINUE (or any other return code)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MDirIter.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MDirIter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MDirIter.cc	(revision 17960)
@@ -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): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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 <fstream>
+#include <iostream>
+
+#include <TList.h>
+#include <TNamed.h>
+#include <TRegexp.h>
+#include <TPRegexp.h>
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.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 NextD(dir);
+
+    TString c;
+    while (!(c=NextD(kTRUE)).IsNull())
+    {
+        // Do not process . and .. entries
+        if (c.EndsWith("/.") || c.EndsWith("/.."))
+            continue;
+
+        // If entry is a directory add it with a lower recursivity
+        if (IsDir(c)==0)
+            rc += AddDirectory(c, filter, recursive-1);
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a single file to the iterator
+//
+Int_t MDirIter::AddFile(const char *name)
+{
+    return AddDirectory(gSystem->DirName(name), gSystem->BaseName(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds all entries from iter to this object
+//
+void MDirIter::Add(const MDirIter &iter)
+{
+    TIter NextD(&iter.fList);
+    TObject *o=0;
+    while ((o=NextD()))
+        fList.Add(o->Clone());
+}
+
+Int_t MDirIter::ReadList(const char *name, const TString &path)
+{
+    const char *con = gSystem->ConcatFileName(path.Data(), name);
+    TString fname(path.IsNull() ? name : con);
+    delete [] con;
+
+    gSystem->ExpandPathName(fname);
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        gLog << err << "Cannot open file " << fname << ": ";
+        gLog << strerror(errno) << " [errno=" << errno << "]" <<endl;
+        return -1;
+    }
+
+    Int_t rc = 0;
+
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        line = line.Strip(TString::kBoth);
+        if (line[0]=='#' || line.IsNull())
+            continue;
+
+        TObjArray &arr = *line.Tokenize(' ');
+
+        for (int i=1; i<arr.GetEntries(); i++)
+            rc += AddDirectory(arr[0]->GetName(), arr[i]->GetName(), -1);
+
+        delete &arr;
+    }
+
+    return true;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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.
+//
+// If the filter is encapsulated in ^ and $ it is assumed to be
+// a valid regular expression and TPRegexp is used for filtering.
+//
+// In other cases TRegex is used:
+//
+// As the filter string may contain a + character, we have to replace
+// this filter by a new filter contaning a \+ at all locations where a +
+// was in the original filter.
+//
+// We replace:
+//   .  by  \\.
+//   +  by  \\+
+//   *  by  [^\\/:]*
+//
+// And surround the filter by ^ and $.
+//
+// For more details you can have a look at the template:
+//  TRegexp::MakeWildcard
+//
+Bool_t MDirIter::MatchFilter(const TString &n, TString f) const
+{
+    if (f.IsNull())
+        return kTRUE;
+
+    if (f[0]=='^' && f[f.Length()-1]=='$')
+    {
+        TPRegexp regex(f);
+        return !n(regex).IsNull();
+    }
+
+    f.Prepend("^");
+    f.ReplaceAll(".", "\\.");
+    f.ReplaceAll("+", "\\+");
+    f.ReplaceAll("*", "[^\\/:]*");
+    //f.ReplaceAll("?", "[^\\/:]?");
+    f.Append("$");
+
+    return !n(TRegexp(f)).IsNull();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether fqp is a directory.
+// Returns -1 if fqp couldn't be accesed, 0 if it is a directory,
+// 1 otherwise
+//
+Int_t MDirIter::IsDir(const char *fqp) const
+{
+    Long_t t[4];
+    if (gSystem->GetPathInfo(fqp, t, t+1, t+2, t+3))
+        return -1;
+
+    if (t[2]==3)
+        return 0;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the current entry in the directory n is valid or not.
+// Entries must:
+//  - not be . or ..
+//  - match the associated filter
+//  - match the global filter
+//  - not be a directory
+//  - have read permission
+//
+Bool_t MDirIter::CheckEntry(const TString n) const
+{
+    // Check . and ..
+    if (n=="." || n=="..")
+        return kFALSE;
+
+    // Check associated filter
+    if (!MatchFilter(n, fCurrentPath->GetTitle()))
+        return kFALSE;
+
+    // Check global filter
+    if (!MatchFilter(n, fFilter))
+         return kFALSE;
+
+    // Check for file or directory
+    const TString fqp = ConcatFileName(fCurrentPath->GetName(), n);
+    if (IsDir(fqp)<=0)
+        return kFALSE;
+
+    // Check for rread perissions
+    return !gSystem->AccessPathName(fqp, kReadPermission);
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset the iteration and strat from scratch. To do this correctly we have
+// to reset the list of directories to iterate _and_ to close the current
+// directory. When you call Next() the next time the first directory will
+// be reopened again and you'll get the first entry.
+//
+// Do not try to only close the current directory or to reset the directory
+// list only. This might not give the expected result!
+//
+void  MDirIter::Reset()
+{
+    Close();
+    fNext.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Next file in the directory which is valid (see Check())
+// nocheck==1 returns the next entry unchecked
+//
+TString MDirIter::Next(Bool_t nocheck)
+{
+    while (1)
+    {
+        fDirPtr = Open();
+        if (!fDirPtr)
+            break;
+
+        // Get next entry in dir, if existing check validity
+        const char *n = gSystem->GetDirEntry(fDirPtr);
+        if (!n)
+        {
+            // Otherwise close directory and try to get next entry
+            Close();
+            continue;
+        }
+
+        if (nocheck || CheckEntry(n))
+            return ConcatFileName(fCurrentPath->GetName(), n);
+    }
+
+    return "";
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 *opt) const
+{
+    TString s(opt);
+    if (s.Contains("dbg", TString::kIgnoreCase))
+        fList.Print();
+
+    if (!s.Contains("all", TString::kIgnoreCase))
+    {
+        TIter NextD(&fList);
+        TObject *o=NULL;
+        while ((o=NextD()))
+            PrintEntry(*o);
+        return;
+    }
+
+    MDirIter NextD(*this);
+    TString name;
+    TString d;
+    while (!(name=NextD()).IsNull())
+    {
+        const TString p = NextD.fCurrentPath->GetName();
+        if (p!=d)
+        {
+            d=p;
+            PrintEntry(*NextD.fCurrentPath);
+        }
+        cout << " " << name << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over all contents (files). Sort the files alphabetically.
+// Delete the contents of this DirIter and add all sorted files
+// to this DirIter.
+//
+void MDirIter::Sort()
+{
+    MDirIter NextD(*this);
+
+    TList l;
+    l.SetOwner();
+
+    TString name;
+    while (!(name=NextD()).IsNull())
+        l.Add(new TNamed(name.Data(), ""));
+
+    l.Sort();
+
+    fList.Delete();
+    Close();
+    fFilter = "";
+
+    TIter NextN(&l);
+    TObject *o=0;
+    while ((o=NextN()))
+    {
+        TString dir   = o->GetName();
+        TString fname = o->GetName();
+
+        const Int_t last = dir.Last('/');
+        if (last<0)
+            continue;
+
+        dir.Remove(last);
+        fname.Remove(0, last+1);
+
+        AddDirectory(dir, fname);
+    }
+}
Index: branches/Mars_McMismatchStudy/mbase/MDirIter.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MDirIter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MDirIter.h	(revision 17960)
@@ -0,0 +1,75 @@
+#ifndef MARS_MDirIter
+#define MARS_MDirIter
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MDirIter : public TObject
+{
+private:
+    TObjArray fList;
+    TString   fFilter;
+
+    TIter     fNext;        //!
+    void     *fDirPtr;      //!
+    TObject  *fCurrentPath; //!
+
+    void   *Open();
+    void    Close();
+    Bool_t  CheckEntry(const TString n) const;
+    Int_t   IsDir(const char *dir) const;
+    Bool_t  MatchFilter(const TString &name, 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) : TObject(), fNext(&fList), fDirPtr(NULL)
+    {
+        fList.SetOwner();
+
+        TObject *o=NULL;
+        TIter NextD(&dir.fList);
+        while ((o=NextD()))
+            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 ReadList(const char *fname, const TString &path="");
+    void Sort();
+
+    Int_t AddDirectory(const char *dir, const char *filter="", Int_t recursive=0);
+    Int_t AddFile(const char *name);
+    void  Add(const MDirIter &iter);
+    void  Reset();
+
+    TString Next(Bool_t nocheck=kFALSE);
+    TString operator()(Bool_t nocheck=kFALSE) { return Next(nocheck); }
+
+    void SetFilter(const char *f="") { fFilter = f; }
+    UInt_t GetNumEntries() const
+    {
+        UInt_t n = 0;
+        MDirIter NextD(*this);
+        while (!NextD().IsNull()) n++;
+        return n;
+    }
+
+    void Print(const Option_t *o="") const;
+
+    ClassDef(MDirIter, 1) // Iterator for files in several directories (with filters)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MEnv.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MEnv.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MEnv.cc	(revision 17960)
@@ -0,0 +1,1139 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MEnv
+//
+// It is a slightly changed version of TEnv. It logs all resources which are
+// touched, so that you can print all untouched resources by
+// PrintUntouched()
+//
+// A new special resource is available. With the resource "Include"
+// you can include resources from other files, for example
+//
+//   Include: file1.rc file2.rc
+//
+// Including can be done recursively. Resources from the included files
+// have lower priority. This allows to write a resource file with your
+// default resources which then can be included in other files overwriting
+// some of the resources.
+//
+// If given paths are not absolute there base is always th elocation of
+// the including file.
+//
+// Class Version 1:
+// ----------------
+//  + TString fName
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MEnv.h"
+
+#include <Gtypes.h>
+#include <TObjString.h>
+#include <TObjArray.h>
+
+#include <TPave.h>
+#include <TAttText.h>
+#include <TAttMarker.h>
+#include <THashList.h>   // needed since root v5.10/00 (TEnv::GetTable)
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+#include "MString.h"
+
+ClassImp(MEnv);
+
+using namespace std;
+
+//---------------------------------------------------------------------------
+//
+// (Default) constructor. If the given file cannot be accessed SetRcName("")
+// is called which can then be checked by IsValid()
+//
+// The second argument is the default name. Usually as name of the MEnv
+// the base name of the file is returned. By giving a default name
+// you can overwrite this behavious. This is useful for I/O
+// because it allows to use Read and Write without argument.
+//
+MEnv::MEnv(const char *name, const char *defname) : TEnv(name), fName(defname)
+{
+    fChecked.SetOwner();
+
+    // If TEnv::TEnv has not set fRcName
+    if (!IsValid())
+        return;
+
+    // ExpandPathName (not done by TEnv::TEnv) and read again
+    TString fname(name);
+    gSystem->ExpandPathName(fname);
+
+    // Is file accessible
+    if (gSystem->AccessPathName(fname, kFileExists))
+        fname = "";
+
+    SetRcName(fname);
+
+    // No file found
+    if (fname.IsNull())
+        return;
+
+    // File has been already processed, but ReadInclude is part of a
+    // derived function, i.e. not yet executed.
+    if (GetEntries()>0 || fname==name)
+    {
+        if (ReadInclude()<0)
+            SetRcName("");
+        return;
+    }
+
+    // File not yet processed. Reread file.
+    if (ReadFile(fname, kEnvLocal)<0)
+        SetRcName("");
+}
+
+//---------------------------------------------------------------------------
+//
+// Process an Include directive and read the corresponding contents
+//
+Int_t MEnv::ReadInclude()
+{
+    // Check for "Include" resource
+    const TString incl = GetValue("Include", "");
+    if (incl.IsNull())
+        return 0;
+
+    const char *dir = gSystem->DirName(GetRcName());
+
+    // Tokenize the array into single files divided by a whitespace
+    TObjArray *arr = incl.Tokenize(" ");
+
+    // We have to rebuild the Include array from scratch to get the
+    // correct sorting for a possible rereading.
+    SetValue("Include", "");
+
+    // FIXME: Make sure that recursions don't crash the system!
+
+    for (int i=0; i<arr->GetEntries(); i++)
+    {
+        // Get file name to include
+        TString fenv = (*arr)[i]->GetName();
+
+        // If the is not anabsolute path we prepend the dir-name
+        // of the including file. This allows that includes
+        // do not necessarily need absolute paths and paths are always
+        // relative to the location of th eincluding file.
+        if (!gSystem->IsAbsoluteFileName(fenv))
+        {
+            fenv.Prepend("/");
+            fenv.Prepend(dir);
+        }
+
+        // Read included file and check if its valid
+        const MEnv env(fenv);
+        if (!env.IsValid())
+        {
+            delete arr;
+            return -1;
+        }
+
+        // Add file name before its childs
+        SetValue("+Include", fenv);
+
+        // If it is valid add entries from include without overwriting,
+        // i.e. the included resources have lower priority
+        AddEnv(env, kFALSE);
+
+        // Get a possible child include from env
+        const TString incl2 = const_cast<MEnv&>(env).GetValue("Include", "");
+        if (!incl2.IsNull())
+            SetValue("+Include", incl2);
+    }
+
+    delete arr;
+
+    // Get final compiled resource
+    TString inc = GetValue("Include", "");
+
+    // Remove obsolete whitespaces for convinience
+    inc.ReplaceAll("  ", " ");
+    inc = inc.Strip(TString::kBoth);
+
+    // Set final resource, now as kEnvLocal (previously set as kEnvChanged)
+    SetValue("Include", inc, kEnvLocal);
+
+    // FIXME: Remove douplets in the correct order
+
+    return 0;
+}
+
+//---------------------------------------------------------------------------
+//
+// Read and parse the resource file for a certain level.
+// Returns -1 on case of error, 0 in case of success.
+//
+// Check for an include directive
+//
+Int_t MEnv::ReadFile(const char *fname, EEnvLevel level)
+{
+    // First read the file via TEnv
+    if (TEnv::ReadFile(fname, level)<0)
+        return -1;
+
+    return ReadInclude();
+}
+
+// --------------------------------------------------------------------------
+//
+// Read an object from the current directory. If no name is given
+// the name of this object is used. 
+//
+Int_t MEnv::Read(const char *name)
+{
+    const Int_t rc = TEnv::Read(name?name:(const char*)fName);
+    //if (name)
+    //    SetName(name);
+    return rc;
+}
+
+//---------------------------------------------------------------------------
+//
+// Make sure that the name used for writing doesn't contain a full path
+//
+const char *MEnv::GetName() const
+{
+    if (!fName.IsNull())
+        return fName;
+
+    const char *pos = strrchr(GetRcName(), '/');
+    return pos>0 ? pos+1 : GetRcName();
+}
+
+//---------------------------------------------------------------------------
+//
+// Return the total number of entries in the table
+//
+Int_t MEnv::GetEntries() const
+{
+    if (!GetTable())
+        return -1;
+
+    return GetTable()->GetEntries();
+}
+
+//---------------------------------------------------------------------------
+//
+// Compile str+post and make sure that in between there is a unique dot.
+//
+TString MEnv::Compile(TString str, const char *post) const
+{
+    if (!str.IsNull() && !str.EndsWith("."))
+        str += ".";
+
+    str += post;
+
+    return str;
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the value from the table and remember the value as checked 
+//
+Int_t MEnv::GetValue(const char *name, Int_t dflt)
+{
+    if (!fChecked.FindObject(name))
+        fChecked.Add(new TObjString(name));
+    return TEnv::GetValue(name, dflt);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the value from the table and remember the value as checked 
+//
+Double_t MEnv::GetValue(const char *name, Double_t dflt)
+{
+    if (!fChecked.FindObject(name))
+        fChecked.Add(new TObjString(name));
+    return TEnv::GetValue(name, dflt);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the value from the table and remember the value as checked 
+//
+const char *MEnv::GetValue(const char *name, const char *dflt)
+{
+    if (!fChecked.FindObject(name))
+        fChecked.Add(new TObjString(name));
+    return TEnv::GetValue(name, dflt);
+}
+
+//---------------------------------------------------------------------------
+//
+// TEnv doen't have a streamer --> cannot be cloned
+//   --> we have to clone it ourself
+//
+TObject *MEnv::Clone(const char *) const
+{
+    MEnv *env = new MEnv("/dev/null");
+    env->SetRcName(GetRcName());
+    env->AddEnv(*this);
+    return env;
+}
+
+//---------------------------------------------------------------------------
+//
+// Interprete fill style: Hollow, Solid, Hatch, 0%-100%
+// If no text style is detected the value is converted to an integer.
+//
+Int_t MEnv::GetFillStyle(const char *name, Int_t dftl)
+{
+    TString str = GetValue(name, "");
+    str = str.Strip(TString::kBoth);
+    if (str.IsNull())
+        return dftl;
+
+    str.ToLower();
+
+    switch (str.Hash())
+    {
+    case 2374867578U: return 0;    // hollow
+    case  764279305U: return 1001; // solid
+    case 1854683492U: return 2001; // hatch
+    }
+
+    return str.EndsWith("%") ? 4000+str.Atoi() : str.Atoi();
+}
+
+//---------------------------------------------------------------------------
+//
+// Interprete line style: Solid, Dashed, Dotted, DashDotted
+// If no line style is detected the value is converted to an integer.
+//
+Int_t MEnv::GetLineStyle(const char *name, Int_t dftl)
+{
+    TString str = GetValue(name, "");
+    str = str.Strip(TString::kBoth);
+    if (str.IsNull())
+        return dftl;
+
+    str.ToLower();
+
+    switch (str.Hash())
+    {
+    case  764279305U: return kSolid;
+    case  241979881U: return kDashed;
+    case 2391642602U: return kDotted;
+    case 1124931659U: return kDashDotted;
+    }
+
+    return str.Atoi();
+}
+
+//---------------------------------------------------------------------------
+//
+// Interprete alignment: Top, Right, Left, Bottom, Center, tr, cc, bl, ...
+// If no text align is detected the value is converted to an integer.
+//
+//  eg.
+//    Top Right
+//    Bottom Center
+//    Center
+//    tr
+//    br
+//    cr
+//
+Int_t MEnv::GetAlign(const char *name, Int_t dftl)
+{
+    TString str = GetValue(name, "");
+    str = str.Strip(TString::kBoth);
+    if (str.IsNull())
+        return dftl;
+
+    str.ToLower();
+
+    switch (str.Hash())
+    {
+    case 29746: return 33; // tr
+    case 25379: return 22; // cc
+    case 25132: return 11; // bl
+
+    case 25388: return 12; // cl
+    case 25394: return 32; // cr
+
+    case 29731: return 23; // tc
+    case 25123: return 32; // bc
+
+    case 29740: return 13; // tl
+    case 25138: return 13; // br
+    }
+
+    Int_t align = 0;
+    if (str.Contains("right", TString::kIgnoreCase))
+        align += 3;
+    if (str.Contains("left", TString::kIgnoreCase))
+        align += 1;
+    if (str.Contains("bottom", TString::kIgnoreCase))
+        align += 10;
+    if (str.Contains("top", TString::kIgnoreCase))
+        align += 30;
+
+    if (str.Contains("center", TString::kIgnoreCase))
+    {
+        if (align==0)
+            return 22;
+        if (align/10==0)
+            return align+20;
+        if (align%10==0)
+            return align+2;
+    }
+
+    return align>0 ? align : str.Atoi();
+}
+
+//---------------------------------------------------------------------------
+//
+// Interprete color: Black, White, Red, Green, Blue, Yellow, Magenta,
+// Cyan, Gray1-5, Grey1-5.
+// If no text color is detected the value is converted to an integer.
+//
+//  eg.
+//    Red
+//    Light Red
+//    Dark Red
+//
+Int_t MEnv::GetColor(const char *name, Int_t dftl)
+{
+    TString str = GetValue(name, "");
+
+    str = str.Strip(TString::kBoth);
+    if (str.IsNull())
+        return dftl;
+
+    str.ToLower();
+
+    Int_t offset=0;
+    if (str.Contains("dark"))
+    {
+        str.ReplaceAll("dark", "");
+        str = str.Strip(TString::kBoth);
+        offset = 100;
+    }
+    if (str.Contains("light"))
+    {
+        str.ReplaceAll("light", "");
+        str = str.Strip(TString::kBoth);
+        offset = 150;
+    }
+
+    switch (str.Hash())
+    {
+    case 2368543371U: return kWhite+offset;
+    case 1814927399U: return kBlack+offset;
+    case    7496964U: return kRed+offset;
+    case 2897107074U: return kGreen+offset;
+    case 1702194402U: return kBlue+offset;
+    case 2374817882U: return kYellow+offset;
+    case 2894218701U: return kMagenta+offset;
+    case 1851881955U: return kCyan+offset;
+    case  749623518U: return 19; // grey1
+    case  749623517U: return 18; // grey2
+    case  749623516U: return 17; // grey3
+    case  749623515U: return 16; // grey4
+    case  749623514U: return 15; // grey5
+    case  749623513U: return 14; // grey6
+    case  749623512U: return 13; // grey7
+    case  749623511U: return 12; // grey8
+    case  741234910U: return 19; // gray1
+    case  741234909U: return 18; // gray2
+    case  741234908U: return 17; // gray3
+    case  741234907U: return 16; // gray4
+    case  741234906U: return 15; // gray5
+    case  741234905U: return 14; // gray6
+    case  741234904U: return 13; // gray7
+    case  741234903U: return 12; // gray8
+    }
+    return str.Atoi();
+}
+
+//---------------------------------------------------------------------------
+//
+// As possible convert the color col into a text string which can be
+// interpreted by GetColor before setting the resource value
+//
+void MEnv::SetColor(const char *name, Int_t col)
+{
+    TString val;
+
+    if (col>99 && col<101+kCyan)
+    {
+        val = "Dark ";
+        col -= 100;
+    }
+    if (col>150 && col<151+kCyan)
+    {
+        val = "Light ";
+        col -= 150;
+    }
+
+    switch (col)
+    {
+    case kWhite:   val += "White";   break;
+    case kBlack:   val += "Black";   break;
+    case kRed:     val += "Red";     break;
+    case kGreen:   val += "Green";   break;
+    case kBlue:    val += "Blue";    break;
+    case kYellow:  val += "Yellow";  break;
+    case kMagenta: val += "Magenta"; break;
+    case kCyan:    val += "Cyan";    break;
+    case 19:       val += "Grey1";   break;
+    case 18:       val += "Grey2";   break;
+    case 17:       val += "Grey3";   break;
+    case 16:       val += "Grey4";   break;
+    case 15:       val += "Grey5";   break;
+    case 14:       val += "Grey6";   break;
+    case 13:       val += "Grey7";   break;
+    case 12:       val += "Grey8";   break;
+    }
+
+    if (val.IsNull())
+        val += col;
+
+    SetValue(name, val);
+}
+
+//---------------------------------------------------------------------------
+//
+// As possible convert the alignment align into a text string which can be
+// interpreted by GetAlign before setting the resource value
+//
+void MEnv::SetAlign(const char *name, Int_t align)
+{
+    TString val;
+    if (align==22)
+    {
+        SetValue(name, "Center");
+        return;
+    }
+
+    switch (align%10)
+    {
+    case 1: val += "Left";   break;
+    case 2: val += "Center"; break;
+    case 3: val += "Right";  break;
+    }
+
+    switch (align/10)
+    {
+    case 1: val += "Bottom"; break;
+    case 2: val += "Center"; break;
+    case 3: val += "Top";    break;
+    }
+
+    SetValue(name, val);
+}
+
+//---------------------------------------------------------------------------
+//
+// As possible convert the fill style style into a text string which can be
+// interpreted by GetFillStyle before setting the resource value
+//
+void MEnv::SetFillStyle(const char *name, Int_t style)
+{
+    TString val;
+
+    if (style>3999 && style<4101)
+        val = MString::Format("%d%%", style-4000);
+
+    switch (style)
+    {
+    case 0:    val = "Hollow"; break;
+    case 1001: val = "Solid";  break;
+    case 2001: val = "Hatch";  break;
+    }
+
+    if (val.IsNull())
+        val += style;
+
+    SetValue(name, val);
+}
+
+//---------------------------------------------------------------------------
+//
+// As possible convert the line style style into a text string which can be
+// interpreted by GetLineStyle before setting the resource value
+//
+void MEnv::SetLineStyle(const char *name, Int_t style)
+{
+    TString val;
+    switch (style)
+    {
+    case kSolid:      val = "Solid";       break;
+    case kDashed:     val = "Dashed";      break;
+    case kDotted:     val = "Dotted";      break;
+    case kDashDotted: val = "DashDotted";  break;
+    }
+
+    if (val.IsNull())
+        val += style;
+
+    SetValue(name, val);
+}
+
+//---------------------------------------------------------------------------
+//
+// As possible convert the marker style style into a text string which can be
+// interpreted by GetLineStyle before setting the resource value
+//
+void MEnv::SetMarkerStyle(const char *name, Int_t style)
+{
+    TString val;
+    switch (style)
+    {
+    case kDot:              val = "dot";
+    case kPlus:             val = "plus";
+    case kCircle:           val = "circle";
+    case kMultiply:         val = "multiply";
+    case kFullDotSmall:     val = "fulldotsmall";
+    case kFullDotMedium:    val = "fulldotmedium";
+    case kFullDotLarge:     val = "fulldotlarge";
+//    case kOpenTriangleDown: val = "opentriangledown";
+//    case kFullCross:        val = "fullcross";
+    case kFullCircle:       val = "fullcircle";
+    case kFullSquare:       val = "fullsquare";
+    case kFullTriangleDown: val = "fulltriangledown";
+    case kOpenCircle:       val = "opencircle";
+    case kOpenSquare:       val = "opensquare";
+    case kOpenTriangleUp:   val = "opentriangleup";
+    case kOpenDiamond:      val = "opendiamond";
+    case kOpenCross:        val = "opencross";
+    case kFullStar:         val = "fullstar";
+    case kOpenStar:         val = "openstar";
+    }
+
+    if (val.IsNull())
+        val += style;
+
+    SetValue(name, val);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the attributed from a TAttLine (if dftl is given use it as default)
+//   name.LineColor  <see also GetColor>
+//   name.LineStyle
+//   name.LineWidth
+// For more details on the meaning see TAttLine
+//
+void MEnv::GetAttLine(const char *name, TAttLine &line, TAttLine *dftl)
+{
+    const TString color = Compile(name, "LineColor");
+    const TString style = Compile(name, "LineStyle");
+    const TString width = Compile(name, "LineWidth");
+
+    if (!dftl)
+        dftl = &line;
+
+    const Color_t col = GetColor(color, dftl->GetLineColor());
+    const Style_t sty = GetLineStyle(style, dftl->GetLineStyle());
+    const Style_t wid = GetValue(width, dftl->GetLineWidth());
+
+    line.SetLineColor(col);
+    line.SetLineStyle(sty);
+    line.SetLineWidth(wid);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the attributed from a TAttText (if dftl is given use it as default)
+//   name.TextColor  <see also GetColor>
+//   name.TextAlign  <see also GetAlign>
+//   name.TextAngle
+//   name.TextFont
+//   name.TextSize
+// For more details on the meaning see TAttText
+//
+void MEnv::GetAttText(const char *name, TAttText &text, TAttText *dftl)
+{
+   const TString color = Compile(name, "TextColor");
+   const TString align = Compile(name, "TextAlign");
+   const TString angle = Compile(name, "TextAngle");
+   const TString font  = Compile(name, "TextFont");
+   const TString size  = Compile(name, "TextSize");
+
+    if (!dftl)
+        dftl = &text;
+
+    const Color_t col = GetColor(color, dftl->GetTextColor());
+    const Short_t ali = GetAlign(align, dftl->GetTextAlign());
+    const Float_t ang = GetValue(angle, dftl->GetTextAngle());
+    const Font_t  fon = GetValue(font,  dftl->GetTextFont());
+    const Float_t siz = GetValue(size,  dftl->GetTextSize());
+
+    text.SetTextColor(col);
+    text.SetTextAlign(ali);
+    text.SetTextAngle(ang);
+    text.SetTextFont(fon);
+    text.SetTextSize(siz);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the attributed from a TAttFill (if dftl is given use it as default)
+//   name.FillColor  <see also GetColor>
+//   name.FillStyle  <see also GetFillStyle>
+// For more details on the meaning see TAttFill
+//
+void MEnv::GetAttFill(const char *name, TAttFill &fill, TAttFill *dftl)
+{
+    const TString color = Compile(name, "FillColor");
+    const TString style = Compile(name, "FillStyle");
+
+    if (!dftl)
+        dftl = &fill;
+
+    const Color_t col = GetColor(color, dftl->GetFillColor());
+    const Style_t sty = GetFillStyle(style, dftl->GetFillStyle());
+ 
+    fill.SetFillColor(col);
+    fill.SetFillStyle(sty);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the attributed from a TAttMarker (if dftl is given use it as default)
+//   name.MarkerColor  <see also GetColor>
+//   name.MarkerStyle
+//   name.MarkerSize
+// For more details on the meaning see TAttMarker
+//
+void MEnv::GetAttMarker(const char *name, TAttMarker &marker, TAttMarker *dftl)
+{
+    const TString color = Compile(name, "MarkerColor");
+    const TString style = Compile(name, "MarkerStyle");
+    const TString size  = Compile(name, "MarkerSize");
+
+    if (!dftl)
+        dftl = &marker;
+
+    const Color_t col = GetColor(color, dftl->GetMarkerColor());
+    const Style_t sty = GetValue(style, dftl->GetMarkerStyle());
+    const Size_t  siz = GetValue(size,  dftl->GetMarkerSize());
+
+    marker.SetMarkerColor(col);
+    marker.SetMarkerStyle(sty);
+    marker.SetMarkerSize(siz);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the attributed from a TPave (if dftl is given use it as default)
+//   name.CornerRadius
+//   name.BorderSize
+//   name.Option
+// Also all resources from TAttLine and TAttFill are supported.
+//
+// For your conveinience: If the CornerRadius is greater than 0 "arc" is
+// added to the options. If it is equal or less than 0 "arc" is removed
+// from the options.
+//
+// For more details on the meaning see TPave
+//
+void MEnv::GetAttPave(const char *str, TPave &pave, TPave *dftl)
+{
+    const TString post(str);
+
+    TString name(pave.GetName());
+    if (!name.IsNull() && name!=pave.ClassName())
+        name = Compile(name, post);
+
+    GetAttLine(name, pave, dftl);
+    GetAttFill(name, pave, dftl);
+
+    const TString corner = Compile(name, "CornerRadius");
+    const TString border = Compile(name, "BorderSize");
+    const TString option = Compile(name, "Option");
+
+    if (!dftl)
+        dftl = &pave;
+
+    const Double_t cor = GetValue(corner, dftl->GetCornerRadius());
+    const Int_t    bor = GetValue(border, dftl->GetBorderSize());
+
+    pave.SetCornerRadius(cor);
+    pave.SetBorderSize(bor);
+
+    TString  opt = GetValue(option, dftl->GetOption());
+    opt.ToLower();
+
+    const Bool_t has = pave.GetCornerRadius()>0;
+
+    if (has && !opt.Contains("arc"))
+        opt += "arc";
+
+    if (!has && opt.Contains("arc"))
+        opt.ReplaceAll("arc", "");
+
+    pave.SetOption(opt);
+
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the attributed for the TObject obj. Use dftl for default attributes
+// if given.
+//
+// There is support for:
+//    TPave      <see GetAttPave>
+//    TAttLine   <see GetAttLine>
+//    TAttText   <see GetAttText>
+//    TAttFill   <see GetAttFill>
+//    TAttMarker <see GetAttMarker>
+//
+void MEnv::GetAttributes(const char *name, TObject *obj, TObject *dftl)
+{
+    //TAttAxis         *line = dynamic_cast<TAttAxis*>(obj);
+    //TAtt3D           *line = dynamic_cast<TAtt3D*>(obj);
+    //TAttCanvas       *line = dynamic_cast<TAttCanvas*>(obj);
+    //TAttFillCanvas   *line = dynamic_cast<TAttFillEitor*>(obj);
+    //TAttLineCanvas   *line = dynamic_cast<TAttLineCanvas*>(obj);
+    //TAttLineEditor   *line = dynamic_cast<TAttLineEditor*>(obj);
+    //TAttMarkerCanvas *line = dynamic_cast<TAttMarkerCanvas*>(obj);
+    //TAttMarkerEditor *line = dynamic_cast<TAttMarkerEditor*>(obj);
+    //TAttPad          *line = dynamic_cast<TAttPad*>(obj);
+    //TAttParticle     *line = dynamic_cast<TAttParticle*>(obj);
+    //TAttTextCanvas   *line = dynamic_cast<TAttTextCanvas*>(obj);
+    //TAttTextEditor   *line = dynamic_cast<TAttTextEditor*>(obj);
+
+    TPave      *pave = dynamic_cast<TPave*>(obj);
+    TAttLine   *line = dynamic_cast<TAttLine*>(obj);
+    TAttText   *text = dynamic_cast<TAttText*>(obj);
+    TAttFill   *fill = dynamic_cast<TAttFill*>(obj);
+    TAttMarker *mark = dynamic_cast<TAttMarker*>(obj);
+
+    if (pave)
+    {
+        GetAttPave(name, *pave, dynamic_cast<TPave*>(dftl));
+        return;
+    }
+
+    if (line)
+        GetAttLine(name, *line, dynamic_cast<TAttLine*>(dftl));
+    if (text)
+        GetAttText(name, *text, dynamic_cast<TAttText*>(dftl));
+    if (fill)
+        GetAttFill(name, *fill, dynamic_cast<TAttFill*>(dftl));
+    if (mark)
+        GetAttMarker(name, *mark, dynamic_cast<TAttMarker*>(dftl));
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the resources from a TAttLine:
+//   name.LineColor  <see also SetColor>
+//   name.LineStyle
+//   name.LineWidth
+//
+void MEnv::SetAttLine(const char *name, const TAttLine &line)
+{
+    const TString color = Compile(name, "LineColor");
+    const TString style = Compile(name, "LineStyle");
+    const TString width = Compile(name, "LineWidth");
+
+    SetColor(color, line.GetLineColor());
+    SetLineStyle(style, line.GetLineStyle());
+    SetValue(width, line.GetLineWidth());
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the resources from a TAttText:
+//   name.TextColor  <see also SetColor>
+//   name.TextAlign  <see also SetAlign>
+//   name.TextAngle
+//   name.TextFont
+//   name.TextSize
+//
+void MEnv::SetAttText(const char *name, const TAttText &text)
+{
+    const TString color = Compile(name, "TextColor");
+    const TString align = Compile(name, "TextAlign");
+    const TString angle = Compile(name, "TextAngle");
+    const TString font  = Compile(name, "TextFont");
+    const TString size  = Compile(name, "TextSize");
+
+    SetColor(color, text.GetTextColor());
+    SetAlign(align, text.GetTextAlign());
+    SetValue(angle, text.GetTextAngle());
+    SetValue(font,  text.GetTextFont());
+    SetValue(size,  text.GetTextSize());
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the resources from a TAttFill:
+//   name.FillColor  <see also SetColor>
+//   name.FillStyle  <see also SetFillStyle>
+//
+void MEnv::SetAttFill(const char *name, const TAttFill &fill)
+{
+    const TString color = Compile(name, "FillColor");
+    const TString style = Compile(name, "FillStyle");
+
+    SetColor(color, fill.GetFillColor());
+    SetFillStyle(style, fill.GetFillStyle());
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the resources from a TAttMarker:
+//   name.MarkerColor  <see also SetColor>
+//   name.MarkerStyle
+//   name.MarkerSize
+//
+void MEnv::SetAttMarker(const char *name, const TAttMarker &marker)
+{
+    const TString color = Compile(name, "MarkerColor");
+    const TString style = Compile(name, "MarkerStyle");
+    const TString size  = Compile(name, "MarkerSize");
+
+    SetColor(color, marker.GetMarkerColor());
+    SetMarkerStyle(style, marker.GetMarkerStyle());
+    SetValue(size,  marker.GetMarkerSize());
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the resources from a TPave:
+//   name.CornerRadius
+//   name.BorderSize
+//   name.Option
+// Also all resources from TAttLine and TAttFill are supported.
+//
+void MEnv::SetAttPave(const char *str, const TPave &pave)
+{
+    const TString name(str);
+
+    SetAttLine(name, pave);
+    SetAttFill(name, pave);
+
+    const TString corner = Compile(name, "CornerRadius");
+    const TString border = Compile(name, "BorderSize");
+    const TString option = Compile(name, "Option");
+
+    SetValue(corner, const_cast<TPave&>(pave).GetCornerRadius());
+    SetValue(border, const_cast<TPave&>(pave).GetBorderSize());
+    SetValue(option, pave.GetOption());
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the attributed for the TObject obj.
+//
+// There is support for:
+//    TPave      <see SetAttPave>
+//    TAttLine   <see SetAttLine>
+//    TAttText   <see SetAttText>
+//    TAttFill   <see SetAttFill>
+//    TAttMarker <see SetAttMarker>
+//
+void MEnv::SetAttributes(const char *name, const TObject *obj)
+{
+    const TPave      *pave = dynamic_cast<const TPave*>(obj);
+    const TAttLine   *line = dynamic_cast<const TAttLine*>(obj);
+    const TAttText   *text = dynamic_cast<const TAttText*>(obj);
+    const TAttFill   *fill = dynamic_cast<const TAttFill*>(obj);
+    const TAttMarker *mark = dynamic_cast<const TAttMarker*>(obj);
+
+    if (pave)
+    {
+        SetAttPave(name, *pave);
+        return;
+    }
+
+    if (line)
+        SetAttLine(name, *line);
+    if (text)
+        SetAttText(name, *text);
+    if (fill)
+        SetAttFill(name, *fill);
+    if (mark)
+        SetAttMarker(name, *mark);
+}
+
+//---------------------------------------------------------------------------
+//
+// Add all values from TEnv env the this MEnv. To not overwrite existing
+// values set overwrite to kFALSE
+//
+void MEnv::AddEnv(const TEnv &env, Bool_t overwrite)
+{
+    if (!GetTable() || !env.GetTable())
+        return;
+
+    TIter Next(env.GetTable());
+
+    TEnvRec *er;
+    while ((er = (TEnvRec*)Next()))
+    {
+        if (overwrite || !Defined(er->GetName()))
+            SetValue(er->GetName(), er->GetValue(), er->GetLevel(), er->GetType());
+    }
+}
+
+//---------------------------------------------------------------------------
+//
+// Check MArgs for all options "--rc=" and remove them. Options should be
+// given like
+//
+//    program --rc=Option1:Test1 --rc=Option2.SubOption:Test2
+//
+// If all resources could be interpeted corrctly kTRUE is returned. If
+// there were problems kFALSE is returned.
+//
+Bool_t MEnv::TakeEnv(MArgs &arg, Bool_t print, Bool_t overwrite)
+{
+    if (!GetTable())
+    {
+        gLog << err << "ERROR - MEnv not yet initialized." << endl;
+        return kFALSE;
+    }
+
+    Bool_t ret = kTRUE;
+    while (1)
+    {
+        const TString rc = arg.GetStringAndRemove("--rc=");
+        if (rc.IsNull())
+            break;
+
+        const Ssiz_t pos = rc.First(':');
+        if (pos<0)
+        {
+            gLog << warn << "WARNING - Resource '" << rc << "' doesn't contain a colon... ignored." << endl;
+            ret=kFALSE;
+            continue;
+        }
+        if (pos==0)
+        {
+            gLog << warn << "WARNING - Resource '" << rc << "' doesn't contain a name... ignored." << endl;
+            ret=kFALSE;
+            continue;
+        }
+        if (pos==rc.Length()-1)
+        {
+            gLog << warn << "WARNING - Resource '" << rc << "' empty... ignored." << endl;
+            ret=kFALSE;
+            continue;
+        }
+
+        const TString name = rc(0,     pos);
+        const TString val  = rc(pos+1, rc.Length());
+
+        if (print)
+            gLog << all << "Command line resource '" << name << "' with value '" << val << "'...";
+
+        const Bool_t exists = Defined(name);
+        if (!exists)
+        {
+            SetValue(name, val, kEnvLocal);
+            if (print)
+                gLog << "set." << endl;
+            continue;
+        }
+
+        if (overwrite)
+        {
+            SetValue(name, "");
+            SetValue(name, val, kEnvLocal);
+            if (print)
+                gLog << "changed." << endl;
+            continue;
+        }
+
+        if (print)
+            gLog << "skipped/existing." << endl;
+    }
+    return ret;
+}
+
+//---------------------------------------------------------------------------
+//
+// Add name and full path to output
+//
+void MEnv::PrintEnv(EEnvLevel level) const
+{
+    if (!TString(GetRcName()).IsNull())
+    {
+        cout << "# Path: " << GetRcName() << endl;
+        cout << "# File: " << gSystem->BaseName(GetRcName()) << endl;
+    }
+    if (!fName.IsNull())
+        cout << "# Name: " << fName << endl;
+
+    TEnv::PrintEnv(level);
+}
+
+//---------------------------------------------------------------------------
+//
+// Print resources which have never been touched (for debugging)
+//
+void MEnv::PrintUntouched() const
+{
+    int i=0;
+    gLog << inf << flush;
+
+    TString sep = "Untouched Resources in ";
+    sep += GetRcName();
+    gLog.Separator(sep);
+    TIter Next(GetTable());
+    TObject *o=0;
+
+    while ((o=Next()))
+        if (!fChecked.FindObject(o->GetName()))
+        {
+            gLog << warn << " - Resource " << o->GetName() << " untouched" << endl;
+            i++;
+        }
+    if (i==0)
+        gLog << inf << "None." << endl;
+    else
+        gLog << inf << i << " resources have not been touched." << endl;
+}
+
+//---------------------------------------------------------------------------
+//
+// Return number of resources which have not been touched.
+//
+Int_t MEnv::GetNumUntouched() const
+{
+    int i=0;
+    TIter Next(GetTable());
+    TObject *o=0;
+    while ((o=Next()))
+        if (!fChecked.FindObject(o->GetName()))
+            i++;
+    return i;
+}
Index: branches/Mars_McMismatchStudy/mbase/MEnv.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MEnv.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MEnv.h	(revision 17960)
@@ -0,0 +1,95 @@
+#ifndef MARS_MEnv
+#define MARS_MEnv
+
+#ifndef ROOT_TEnv
+#include <TEnv.h>
+#endif
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+class TAttLine;
+class TAttMarker;
+class TAttText;
+class TAttFill;
+class TPave;
+
+class MArgs;
+
+class MEnv : public TEnv
+{
+private:
+    TOrdCollection fChecked; //!
+
+    TString fName;
+
+    TString Compile(TString str, const char *post) const;
+    Int_t   ReadInclude();
+
+public:
+    MEnv(const char *name="", const char *defname=0);
+
+    Bool_t      IsValid() const { return !TString(GetRcName()).IsNull(); }
+
+    TObject    *Clone(const char *newname="") const;
+
+    Bool_t      Touch(const char *name) { return !TString(GetValue(name, "")).IsNull(); }
+
+    Int_t       GetEntries() const;
+
+    Int_t       GetValue(const char *name, Int_t dflt);
+    Double_t    GetValue(const char *name, Double_t dflt);
+    const char *GetValue(const char *name, const char *dflt="");
+
+    // GetValue: regexp
+
+    const char *GetName() const;
+    void        SetName(const char *name=0) { fName = name; }
+
+    Int_t       GetColor(const char *name, Int_t dftl);
+    Int_t       GetAlign(const char *name, Int_t dftl);
+    Int_t       GetFillStyle(const char *name, Int_t dftl);
+    Int_t       GetLineStyle(const char *name, Int_t dftl);
+
+    void        GetAttributes(const char *name, TObject *obj, TObject *dftl=0);
+    void        GetAttLine(const char *name, TAttLine &line, TAttLine *dftl=0);
+    void        GetAttText(const char *name, TAttText &text, TAttText *dftl=0);
+    void        GetAttFill(const char *name, TAttFill &fill, TAttFill *dftl=0);
+    void        GetAttMarker(const char *name, TAttMarker &marker, TAttMarker *dftl=0);
+    void        GetAttPave(const char *name, TPave &pave, TPave *dftl=0);
+
+    void        SetColor(const char *name, Int_t col);
+    void        SetAlign(const char *name, Int_t align);
+    void        SetFillStyle(const char *name, Int_t style);
+    void        SetLineStyle(const char *name, Int_t style);
+    void        SetMarkerStyle(const char *name, Int_t style);
+
+    void        SetAttributes(const char *name, const TObject *obj);
+    void        SetAttLine(const char *name, const TAttLine &line);
+    void        SetAttText(const char *name, const TAttText &text);
+    void        SetAttFill(const char *name, const TAttFill &fill);
+    void        SetAttMarker(const char *name, const TAttMarker &marker);
+    void        SetAttPave(const char *name, const TPave &pave);
+
+    void        AddEnv(const TEnv &env, Bool_t overwrite=kTRUE);
+    Bool_t      TakeEnv(MArgs &args, Bool_t print=kFALSE, Bool_t overwrite=kTRUE);
+
+    Int_t       Read(const char *name=0);
+    Int_t       ReadFile(const char *fname, EEnvLevel level);
+
+    Int_t       WriteFile(const char *filename, EEnvLevel level) { return TEnv::WriteFile(filename, level); }
+    Int_t       WriteFile(const char *filename) { return WriteFile(filename, kEnvLocal); } //*MENU*
+
+    void        PrintEnv(EEnvLevel level = kEnvAll) const;
+    void        Print(Option_t *option) const { TEnv::Print(option); }
+    void        Print() const { PrintEnv(kEnvLocal); } //*MENU*
+
+    void PrintUntouched() const;
+    Int_t GetNumUntouched() const;
+
+    ClassDef(MEnv, 1) // A slightly more advanced version of TEnv
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/mbase/MEvtLoop.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MEvtLoop.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MEvtLoop.cc	(revision 17960)
@@ -0,0 +1,1151 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MEvtLoop
+//
+// This class is the core of each event processing.
+// First you must set the parameter list to use. The parameter list
+// must contain the task list (MTaskList) to use. The name of the task
+// list can be specified if you call Eventloop. The standard name is
+// "MTaskList". The name you specify must match the name of the MTaskList
+// object.
+//
+// If you call Eventloop() first all PreProcess functions - with the
+// parameter list as an argument - of the tasks in the task list are
+// executed. If one of them returns kFALSE then the execution is stopped.
+// If the preprocessing was ok, The Process function of the tasks are
+// executed as long as one function returns kSTOP. Only the tasks which
+// are marked as "All" or with a string which matches the MInputStreamID
+// of MTaskList are executed. If one tasks returns kCONTINUE the pending
+// tasks in the list are skipped and the execution in continued with
+// the first one in the list.
+// Afterwards the PostProcess functions are executed.
+//
+// If you want to display the progress in a gui you can use SetProgressBar
+// and a TGProgressBar or a MProgressBar. If you set a MStatusDisplay
+// using SetDisplay, the Progress bar from this display is used.
+//
+// You can create a macro from a completely setup eventloop by:
+//   evtloop.MakeMacro("mymacro.C");
+//
+// You will always need to check the macro, it will not run, but it
+// should have al important information.
+//
+//
+// You can also write all this information to a root file:
+//   TFile file("myfile.root");
+//   evtloop.Write("MyEvtloopKey");
+//
+// You can afterwards read the information from an open file by:
+//   evtloop.Read("MyEvtloopKey");
+//
+// To lookup the information write it to a file using MakeMacro
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MEvtLoop.h"
+
+#include <time.h>           // time_t
+#include <fstream>          // ofstream, SavePrimitive
+
+#include <TEnv.h>           // TEnv
+#include <TRint.h>          // gApplication, TRint::Class()
+#include <TTime.h>          // TTime
+#include <TFile.h>          // gFile
+#include <TThread.h>        // TThread::Self()
+#include <TDatime.h>        // TDatime
+#include <TSystem.h>        // gSystem
+#include <TStopwatch.h>
+#include <TGProgressBar.h>  
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.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), fTaskList(NULL), fProgress(NULL)
+{
+    fName = name;
+
+    gROOT->GetListOfCleanups()->Add(this); // To remove fDisplay
+    SetBit(kMustCleanup);
+
+    *fLog << inf << endl << underline << "Instantiated MEvtLoop (" << name << "), using ROOT v" << ROOT_RELEASE << 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()
+{
+    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("MTaskList");
+    if (!fTaskList)
+    {
+        *fLog << err << dbginf << "Cannot find MTaskList 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(fName);
+        fDisplay->SetIconName(fName);
+        // Start automatic update
+        fDisplay->StartUpdate();
+        // Cascade display through childs
+        if (!TestBit(kPrivateDisplay))
+            fParList->SetDisplay(fDisplay);
+    }
+#endif
+
+    if (fProgress)
+        fProgress->SetPosition(0);
+
+    //
+    //  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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the memory currently used by this process (VmSize)
+// which contains shared memory, data memory and private memory.
+//
+UInt_t MEvtLoop::GetMemoryUsage()
+{
+    const TString path = MString::Format("/proc/%d/status", gSystem->GetPid());
+    if (gSystem->AccessPathName(path, kFileExists))
+        return 0;
+
+    return TEnv(path).GetValue("VmSize", 0);
+}
+
+Bool_t MEvtLoop::ProcessGuiEvents(Int_t num, Int_t looprc)
+{
+    if (gROOT->IsBatch())
+        return kTRUE;
+
+    //
+    // Check status of display
+    //
+    Bool_t rc = kTRUE;
+
+    if (fDisplay)
+        switch (fDisplay->CheckStatus())
+        {
+        case MStatusDisplay::kLoopPause:
+            fDisplay->SetStatusLine1(MString::Format("Paused after %d", num-1));
+            while (fDisplay && fDisplay->CheckStatus()==MStatusDisplay::kLoopPause)
+            {
+                gSystem->ProcessEvents();
+                gSystem->Sleep(1);
+            }
+            // FALLTHROUGH
+        case MStatusDisplay::kLoopStep:
+            if (fDisplay && fDisplay->CheckStatus()==MStatusDisplay::kLoopStep && looprc!=kCONTINUE)
+            {
+                //fDisplay->ClearStatus();
+                fDisplay->SetPause();
+            }
+            // FALLTHROUGH
+        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 && (Int_t)fNumEvents-num>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 (fNumEvents>0 && fProgress)
+    {
+        const Double_t pos = (Double_t)num/fNumEvents;
+        fProgress->SetPosition(pos);
+//        if (gROOT->IsBatch())
+//            *fLog << all << MString::Format("%.1f", pos) << "%..." << flush;
+    }
+
+    // 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;
+
+    const UInt_t mem0 = GetMemoryUsage();
+
+    //
+    //   loop over all events and process all tasks for
+    //   each event
+    //
+    *fLog << all <<"Eventloop running (";
+
+    if (maxcnt==0)
+        *fLog << "all";
+    else
+        *fLog << dec << maxcnt;
+
+    *fLog << " events)..." << flush;
+
+    UInt_t entries = kMaxUInt;
+    fNumEvents = 0;
+
+    if (fProgress && !gROOT->IsBatch())
+    {
+        fProgress->Reset();
+        fProgress->SetRange(0, 1);
+
+#ifdef __MARS__
+        MRead *read = (MRead*)fTaskList->FindObject("MRead");
+        if (read && read->GetEntries()>0)
+            entries = read->GetEntries();
+#endif
+
+        if (maxcnt>0)
+            fNumEvents = TMath::Min(maxcnt, entries);
+        else
+            if (entries!=kMaxUInt)
+                fNumEvents = entries;
+    }
+
+    if (fDisplay)
+    {
+        fDisplay->SetStatusLine1("Processing...");
+        fDisplay->SetStatusLine2("");
+    }
+
+    //
+    // start a stopwatch
+    //
+    TStopwatch clock;
+    clock.Start();
+
+    //
+    // This is the MAIN EVENTLOOP which processes the data
+    // if maxcnt==0 the number of processed events is counted
+    // else only maxcnt events are processed
+    //
+    UInt_t numcnts = 0;
+    UInt_t dummy   = maxcnt;
+
+    Int_t rc=kTRUE;
+    if (maxcnt==0)
+        // process first and increment if sucessfull
+        while (1)
+        {
+            rc=fTaskList->CallProcess();
+            if (rc!=kTRUE && rc!=kCONTINUE)
+                break;
+
+            numcnts++;
+            if (!ProcessGuiEvents(++dummy, rc))
+                break;
+        }
+    else
+        // check for number and break if unsuccessfull
+        while (dummy--)
+        {
+            rc=fTaskList->CallProcess();
+            if (rc!=kTRUE && rc!=kCONTINUE)
+                break;
+
+            numcnts++;
+            if (!ProcessGuiEvents(maxcnt - dummy, rc))
+                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";
+
+
+    const UInt_t mem1 = GetMemoryUsage();
+    if (mem1>mem0)
+        *fLog << endl << "Mem  - Loss: " << mem1-mem0 << "kB" << endl;
+
+    *fLog << endl << endl;
+
+    return rc!=kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The postprocessing part of the eventloop. Be careful, this is
+// for developers or use in special jobs only!
+//
+Bool_t MEvtLoop::PostProcess() const
+{
+    //
+    //  execute the post process of all tasks
+    //
+    return fTaskList ? fTaskList->PostProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// See class description above. Returns kTRUE if PreProcessing,
+// Processing and PostProcessing was successfull.
+// kFALSE is retuned if something was not successfull, eg:
+//   PreProcess or PostProcess returned kFALSE
+//   process returned kERRR
+//
+// maxcnt==0 means: all events
+// tlist is the name of the task-list to be used. Be carefull, this
+// feature is not finally implemented - it will only work if no
+// task will access the tasklist.
+//
+Bool_t MEvtLoop::Eventloop(UInt_t maxcnt, Statistics_t printstat)
+{
+    *fLog << inf << endl << underline << "Eventloop: " << fName << " started at " << TDatime().AsString() << endl;
+
+    Bool_t rc = PreProcess();
+
+    //
+    // 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 Process has ever been called print statistics
+    //
+    if (fTaskList && fTaskList->GetNumExecutions()>0)
+        switch (printstat)
+        {
+        case kNoStatistics:
+            break;
+        case kStdStatistics:
+            fTaskList->PrintStatistics();
+            break;
+        case kFullStatistics:
+            fTaskList->PrintStatistics(0, kTRUE);
+            break;
+        }
+
+    if (!fDisplay)
+        return rc;
+
+    // Set status lines
+    fDisplay->SetStatusLine1(fName);
+    fDisplay->SetStatusLine2(rc ? "Done." : "Error!");
+    // Stop automatic update
+    fDisplay->StopUpdate();
+    // Reallow context menus
+    fDisplay->SetNoContextMenu(kFALSE);
+    // Reallow user to exit window by File menu
+    fDisplay->UnLock();
+
+    //
+    // If postprocessing of all preprocessed tasks was sucefully return rc.
+    // This gives an error in case the preprocessing has failed already.
+    // Otherwise the eventloop is considered: successfully.
+    //
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  After you setup (or read) an Evtloop you can use MakeMacro() to write
+//  the eventloop setup as a macro. The default name is "evtloop.C". The
+//  default extension is .C If the extension is not given, .C is added.
+//  If the last character in the argument is a '+' the file is not closed.
+//  This is usefull if you have an eventloop which runs three times and
+//  you want to write one macro. If the first character is a '+' no
+//  opening is written, eg:
+//
+//     MEvtLoop evtloop;
+//     // some setup
+//     evtloop.MakeMacro("mymacro+");
+//     // replace the tasklist the first time
+//     evtloop.MakeMacro("+mymacro+");
+//     // replace the tasklist the second time
+//     evtloop.MakeMacro("+mymacro");
+//
+void MEvtLoop::MakeMacro(const char *filename)
+{
+    TString name(filename);
+
+    name = name.Strip(TString::kBoth);
+
+    Bool_t open  = kTRUE;
+    Bool_t close = kTRUE;
+    if (name[0]=='+')
+    {
+        open = kFALSE;
+        name.Remove(0, 1);
+        name = name.Strip(TString::kBoth);
+    }
+
+    if (name[name.Length()-1]=='+')
+    {
+        close = kFALSE;
+        name.Remove(name.Length()-1, 1);
+        name = name.Strip(TString::kBoth);
+    }
+
+    if (!name.EndsWith(".C"))
+        name += ".C";
+
+    ofstream fout;
+
+    if (!open)
+    {
+        fout.open(name, ios::app);
+        fout << endl;
+        fout << "   // ----------------------------------------------------------------------" << endl;
+        fout << endl;
+    }
+    else
+    {
+        fout.open(name);
+
+        time_t t = time(NULL);
+        fout <<
+            "/* ======================================================================== *\\" << endl <<
+            "!" << endl <<
+            "! *" << endl <<
+            "! * This file is part of MARS, the MAGIC Analysis and Reconstruction" << endl <<
+            "! * Software. It is distributed to you in the hope that it can be a useful" << endl <<
+            "! * and timesaving tool in analysing Data of imaging Cerenkov telescopes." << endl <<
+            "! * It is distributed WITHOUT ANY WARRANTY." << endl <<
+            "! *" << endl <<
+            "! * Permission to use, copy, modify and distribute this software and its" << endl <<
+            "! * documentation for any purpose is hereby granted without fee," << endl <<
+            "! * provided that the above copyright notice appear in all copies and" << endl <<
+            "! * that both that copyright notice and this permission notice appear" << endl <<
+            "! * in supporting documentation. It is provided \"as is\" without express" << endl <<
+            "! * or implied warranty." << endl <<
+            "! *" << endl <<
+            "!" << endl <<
+            "!" << endl <<
+            "!   Author(s): Thomas Bretz et al. <mailto:tbretz@astro.uni-wuerzburg.de>" << endl <<
+            "!" << endl <<
+            "!   Copyright: MAGIC Software Development, 2000-2005" << endl <<
+            "!" << endl <<
+            "!" << endl <<
+            "\\* ======================================================================== */" << endl << endl <<
+            "// ------------------------------------------------------------------------" << endl <<
+            "//" << endl <<
+            "//     This macro was automatically created on" << endl<<
+            "//             " << ctime(&t) <<
+            "//        with the MEvtLoop::MakeMacro tool." << endl <<
+            "//" << endl <<
+            "// ------------------------------------------------------------------------" << endl << endl <<
+            "void " << name(0, name.Length()-2) << "()" << endl <<
+            "{" << endl;
+    }
+
+    SavePrimitive(fout, (TString)"" + (open?"open":"") + (close?"close":""));
+
+    if (!close)
+        return;
+
+    fout << "}" << endl;
+
+    *fLog << inf << "Macro '" << name << "' written." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MEvtLoop::StreamPrimitive(ostream &out) const
+{
+    out << "   MEvtLoop " << GetUniqueName();
+    if (fName!="Evtloop")
+        out << "(\"" << fName << "\")";
+    out << ";" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+void MEvtLoop::SavePrimitive(ostream &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->R__FOR_EACH(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->R__FOR_EACH(TObject, ResetBit)(BIT(15));
+    delete gListOfPrimitives;
+    gListOfPrimitives = 0;
+}
+
+void MEvtLoop::SavePrimitive(ofstream &out, Option_t *o)
+{
+    SavePrimitive(static_cast<ostream&>(out), o);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 *) const
+{
+    if (fParList)
+        fParList->Print();
+    else
+        *fLog << all << "MEvtloop: No Parameter List available." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Writes a eventloop to a file. The default name is "Evtloop".
+// Therefor an open file must exist (See TFile for more information)
+//
+//  eg:
+//        TFile file("myfile.root", "RECREATE");
+//        MEvtLoop evtloop;
+//        evtloop.Write();
+//        file.Close();
+//
+Int_t MEvtLoop::Write(const char *name, Int_t option, Int_t bufsize) const
+{
+    if (!gFile)
+    {
+        *fLog << err << "MEvtloop::Write: No file found. Please create a TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsOpen())
+    {
+        *fLog << err << "MEvtloop::Write: File not open. Please open the TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsWritable())
+    {
+        *fLog << err << "MEvtloop::Write: File not writable." << endl;
+        return 0;
+    }
+
+    Int_t n = 0;
+
+    TObjArray list;
+    list.SetOwner();
+
+    fParList->GetNames(list);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,02,00)
+    n += const_cast<MEvtLoop*>(this)->TObject::Write(name, option, bufsize);
+#else
+    n += TObject::Write(name, option, bufsize);
+#endif
+
+    if (n==0)
+    {
+        *fLog << err << "MEvtloop::Read: No objects written." << endl;
+        return 0;
+    }
+
+    n += list.Write((TString)name+"_names", kSingleKey);
+
+    HasDuplicateNames(list, "MEvtLoop::Write");
+
+    *fLog << inf << "Eventloop written to file as " << name << "." << endl;
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+//
+// With the argument prefix you can overwrite the name of the MEvtLoop object
+// as prefix - use with extreme care! The prifix argument must not end with
+// a dot!
+//
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Int_t MEvtLoop::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+//    if (!prefix.IsNull())
+//        *fLog << warn << "WARNING - Second argument in MEvtLoop::ReadEnv has no meaning... ignored." << endl;
+
+    if (prefix.IsNull())
+        prefix = fName;
+    prefix += ".";
+
+    *fLog << inf << "Looking for resources with prefix " << prefix /*TEnv::fRcName << " from " << env.GetRcName()*/ << endl;
+
+    fLog->ReadEnv(env, prefix, print);
+
+    if (!fParList)
+    {
+        *fLog << warn << "WARNING - No parameter list to propagate resources to." << endl;
+        return kTRUE;
+    }
+
+    if (fParList->ReadEnv(env, prefix, print)==kERROR)
+    {
+        *fLog << err << "ERROR - Reading resource file." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls 'ReadEnv' with a TEnv initialized with the given file name.
+// If 'config=0' kTRUE is returned.
+//
+Bool_t MEvtLoop::ReadEnv(const char *config, Bool_t print)
+{
+    if (!config)
+        return kTRUE;
+
+    const Bool_t fileexist = !gSystem->AccessPathName(config, kFileExists);
+    if (!fileexist)
+    {
+        *fLog << warn << "WARNING - resource file '" << config << "' not found... no resources applied." << endl;
+        return kFALSE;
+    }
+
+    const TEnv env(config);
+    return ReadEnv(env, "", print);
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MEvtLoop::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    if (!prefix.IsNull())
+        *fLog << warn << "WARNING - Second argument in MEvtLoop::WriteEnv has no meaning... ignored." << endl;
+
+    prefix = fName;
+    prefix += ".";
+
+    *fLog << inf << "Writing resources with prefix " << prefix /*TEnv::fRcName << " to " << env.GetRcName()*/ << endl;
+
+    fLog->WriteEnv(env, prefix, print);
+
+    if (!fParList)
+    {
+        *fLog << warn << "WARNING - No parameter list to get resources from." << endl;
+        return kTRUE;
+    }
+
+
+    if (fParList->WriteEnv(env, prefix, print)!=kTRUE)
+    {
+        *fLog << err << "ERROR - Writing resource file." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void MEvtLoop::RecursiveRemove(TObject *obj)
+{
+    // If the tasklist was deleted... remove it
+    if (obj==fTaskList)
+        fTaskList = NULL;
+
+    // If the parlist was deleted...invalidate par- and tasklist
+    if (obj==fParList)
+    {
+        fParList=NULL;
+        fTaskList=NULL;
+    }
+
+    // if the progress bar was deleted...remove it
+    if (obj==fProgress)
+        fProgress = NULL;
+
+    // If it was something else check par- and tasklist
+    if (fParList)
+        fParList->RecursiveRemove(obj);
+    else
+        if (fTaskList) // Note that the tasklist is included in the parlist
+            fTaskList->RecursiveRemove(obj);
+
+    // Now check for fDisplay and fLog
+    MParContainer::RecursiveRemove(obj);
+}
Index: branches/Mars_McMismatchStudy/mbase/MEvtLoop.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MEvtLoop.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MEvtLoop.h	(revision 17960)
@@ -0,0 +1,103 @@
+#ifndef MARS_MEvtLoop
+#define MARS_MEvtLoop
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MEvtLoop                                                                //
+//                                                                         //
+// Class to execute the tasks in a tasklist                                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MTask;
+class MParList;
+class MTaskList;
+class TGProgressBar;
+#ifdef __MARS__
+class MProgressBar;
+#endif
+
+class MEvtLoop : public MParContainer
+{
+private:
+    MParList  *fParList;
+    MTaskList *fTaskList;      //!
+
+    TGProgressBar *fProgress;  //!
+
+    ULong_t fNumEvents;        //!
+
+    enum { kIsOwner = BIT(14), kPrivateDisplay = BIT(15) };
+
+    Bool_t HasDuplicateNames(const TString txt) const;
+    Bool_t HasDuplicateNames(TObjArray &arr, const TString txt) const;
+
+    void StreamPrimitive(std::ostream &out) const;
+
+    Bool_t ProcessGuiEvents(Int_t num, Int_t rc);
+
+public:
+    enum Statistics_t {
+        kNoStatistics   = 0,
+        kStdStatistics  = 1,
+        kFullStatistics = 2
+    };
+
+    MEvtLoop(const char *name="Evtloop");
+    virtual ~MEvtLoop();
+
+    void       SetParList(MParList *p);
+    MParList  *GetParList() const  { return fParList; }
+    MTaskList *GetTaskList() const { return fTaskList; }
+
+    MTask *FindTask(const char *name) const;
+    MTask *FindTask(const MTask *obj) const;
+
+    MStatusDisplay *GetDisplay() { return fDisplay; }
+    void SetDisplay(MStatusDisplay *d);
+    void SetPrivateDisplay(Bool_t b=kTRUE) { b ? SetBit(kPrivateDisplay) : ResetBit(kPrivateDisplay); } // Prevent status display from being cascaded in PreProcess
+
+    void SetOwner(Bool_t enable=kTRUE);
+
+    void SetProgressBar(TGProgressBar *bar);
+#ifdef __MARS__
+    void SetProgressBar(MProgressBar *bar);
+#endif
+
+    Bool_t PreProcess();
+    Int_t  Process(UInt_t maxcnt);
+    Bool_t PostProcess() const;
+
+    Bool_t Eventloop(UInt_t maxcnt=0, Statistics_t printstat=kStdStatistics);
+
+    void MakeMacro(const char *filename="evtloop.C");
+
+    void SavePrimitive(std::ostream &out, Option_t *o="");
+    void SavePrimitive(std::ofstream &out, Option_t *o="");
+
+    Int_t Read(const char *name="Evtloop");
+    Int_t Write(const char *name="Evtloop", Int_t option=0, Int_t bufsize=0) const;
+    Int_t Write(const char *name="Evtloop", Int_t option=0, Int_t bufsize=0)
+    {
+        return const_cast<MEvtLoop*>(this)->Write(name, option, bufsize);
+    }
+
+    void Print(Option_t *opt="") const;
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix="", Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix="", Bool_t print=kFALSE) const;
+
+    Bool_t ReadEnv(const char *config, Bool_t print=kFALSE);
+
+    void RecursiveRemove(TObject *obj);
+
+    static UInt_t GetMemoryUsage();
+
+    ClassDef(MEvtLoop, 1) // Class to execute the tasks in a tasklist
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MFilter.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MFilter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MFilter.cc	(revision 17960)
@@ -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, 07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFilter
+//
+//   This is a base class which defines an interface to create your own
+//   filters. To do it derive a class from MFilter.
+//
+//   You can invert the meaning of a filter (logical NOT '!') by calling
+//   SetInverted().
+//
+//   You can create two types of Filters:
+//    - static Filters and
+//    - dynamic Filters
+//
+//   Static Filters:
+//    A static filter is a filter which value doesn't change dynamically,
+//    which mean only once while running through your tasklist. To create
+//    a static filter override the Process-function of MFilter (this is
+//    the function in which the filer-value should be updated). If
+//    necessary you can also overwrite Pre-/PostProcess. The process
+//    function should calculate the return value of IsExpressionTrue.
+//    IsExpressionTrue should simply return this value. This kind of
+//    filter must be added to the tasklist at a point which is forseen to
+//    update the value of the filter (eg. after the reading task).
+//
+//   Dynamic Filters:
+//    A dynamic filter is a filter which returns a value which must be
+//    calculated at the time the filter is called. To create such a
+//    filter you have to overwrite IsExpressionTrue only. If there is
+//    no need for a 'one-point' update this filter must not be added to
+//    the tasklist.
+//
+//   Usage:
+//    A Filter is connected to a task by calling MTask::SetFilter. The
+//    task is now executed when IsExpressionTrue returns a value
+//    (different from kFALSE) only.
+//
+//   Remarks:
+//    - Make sure, that all tasks which depends on this filter are either
+//      collected in a MTaskList-object or are conected to the same
+//      filter.
+//    - If you want to use different filters (combined logically) for one
+//      task please look for the MFilterList class.
+//    - Be careful, the return value of IsExpressionTrue is NOT a real
+//      boolean. You can return other values, too.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFilter.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+ClassImp(MFilter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor for a filter. Initializes fInverted with kFALSE
+//
+MFilter::MFilter(const char *name, const char *title) : fInverted(kFALSE)
+{
+    fName  = name  ? name  : "MFilter";
+    fTitle = title ? title : "Base Class for a filter";
+}
+
+// --------------------------------------------------------------------------
+//
+//  return the Rule corresponding to this filter (see MF and MDataChain)
+//
+TString MFilter::GetRule() const
+{
+    return MString::Format("(%s)", ClassName()); //"<GetRule n/a for " + fName + ">";
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is used to print the output in the PostProcess/Finalize.
+//  Or everywhere else in a nice fashioned and unified way.
+//
+void MFilter::PrintSkipped(UInt_t n, const char *str)
+{
+    *fLog << " " << setw(7) << n << " (";
+    *fLog << setw(3) << TMath::Nint(100.*n/GetNumExecutions());
+    *fLog << "%) Evts fullfilled: " << str << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+//
+// Assuming your filter is called (Set/GetName): MyFilter
+//
+// First you can setup whether the filter is inverted or not:
+//     MyFilter.Inverted: yes, no  <default=no>
+//
+Int_t MFilter::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (IsEnvDefined(env, prefix, "Inverted", print))
+    {
+        SetInverted(GetEnvValue(env, prefix, "Inverted", IsInverted()));
+        return kTRUE;
+    }
+    return kFALSE;
+}
Index: branches/Mars_McMismatchStudy/mbase/MFilter.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MFilter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MFilter.h	(revision 17960)
@@ -0,0 +1,35 @@
+#ifndef MARS_MFilter
+#define MARS_MFilter
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MFilter : public MTask
+{
+private:
+    Bool_t fInverted;
+
+    virtual Bool_t IsExpressionTrue() const = 0;
+
+public:
+    MFilter(const char *name=NULL, const char *title=NULL);
+
+    virtual TString GetRule() const;
+    virtual TString GetDataMember() const { return ""; }
+
+    Bool_t IsConditionTrue() const { return fInverted ? !IsExpressionTrue() : IsExpressionTrue(); }
+
+    void SetInverted(Bool_t i=kTRUE) { fInverted=i; }
+    Bool_t IsInverted() const  { return fInverted; }
+
+    void PrintSkipped(UInt_t n, const char *str);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MFilter, 1)		// Abstract base class for the filters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MFits.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MFits.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MFits.cc	(revision 17960)
@@ -0,0 +1,1 @@
+#include "MFits.h"
Index: branches/Mars_McMismatchStudy/mbase/MGGroupFrame.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGGroupFrame.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGGroupFrame.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MGGroupFrame.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGGroupFrame.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGGroupFrame.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MGList.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGList.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGList.cc	(revision 17960)
@@ -0,0 +1,313 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  11/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MGList                                                                 //
+//                                                                         //
+//  This is a TList object which has some enhancements for GUI elements.   //
+//  Use GetWidget to search for a GUI element with a given widget id.      //
+//  Add checkes for the existances of a GUI element with the same widget   //
+//  id (for IDs>=0).                                                       //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MGList.h"
+
+#include <iostream>
+
+#include <TROOT.h>
+#include <TClass.h>
+#include <TGClient.h>
+#include <TGWidget.h>
+#include <TGPicture.h>
+
+ClassImp(MGList);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Add the list to the global list of cleanups
+//  objects in the list.
+//
+MGList::MGList() : TList()
+{
+    // Make sure that all object deleted are also deleted from this list
+    gROOT->GetListOfCleanups()->Add(this);
+    // Make sure that this doesn't remain in ListOfCleanups after deletion
+    SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Before destroying the list with all its contents free all TGPicture
+//  objects in the list.
+//
+MGList::~MGList()
+{
+    DeletePictures();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Free/Delete all TGPicture store in list.
+//
+void MGList::DeletePictures()
+{
+    TObject *obj;
+    TIter Next(this);
+    while ((obj=Next()))
+    {
+        if (!obj->InheritsFrom(TGPicture::Class()))
+            continue;
+
+        //
+        // Remove the object first. Otherwise we would remove
+        // a non existing object...
+        //
+        Remove(obj);
+        if (gClient)
+            gClient->FreePicture((TGPicture*)obj);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete all pictures. Call TList::Delete.
+//
+void MGList::Delete(Option_t *option)
+{
+    DeletePictures();
+    TList::Delete(option);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Does a dynamic cast from a TObject to a TGWidget. This is necesary
+//  if a class derived from TObject inherits also from TGWidget and
+//  you have only a pointer to the TObject available.
+//
+TGWidget *MGList::GetWidget(TObject *obj) const
+{
+    //
+    // - IsA gives a pointer to the parent class entry in the dictionary
+    // - DynamicCast tries to cast obj of class type obj->IsA to one
+    //   of its base classes TGWidget
+    // - This method is ment for dynamic casts (multi inheritance)
+    //
+    //  If this functions makes trouble check for the correct inheritance
+    //  first via obj->InheritsFrom(TGWidget::Class())
+    //
+    //  The root implementation is used, because for space reasons
+    //  the C++ dynamic_cast<TGWidget*> is turned off by the option
+    //  -fno-rtti, which could be used in 'plain' C++
+    //
+
+    //
+    // FIXME: This should not be necessary but it is, why??
+    //
+    // TRY: TGPicture *pic = gClient->GetPicture("pic");
+    //      cout << pic->IsA()->DynamicCast(TGWidget::Class(), pic) << endl;
+    //
+    //      Is this another bug in root?
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,07)
+    if (!obj->InheritsFrom(TGWidget::Class()))
+        return NULL;
+#endif
+
+    return (TGWidget*)obj->IsA()->DynamicCast(TGWidget::Class(), obj);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Returns kTRUE if the object is derived from TGWidget and a widget
+//  with the TGWidget id of this object is already in the list.
+//  If the object is not derived from TGWidget or no TGWidget object
+//  with the same widget id is existing in the list kFALSE is returned.
+//  If the TGWidget has an object id < 0 kFALSE is always retuned.
+//
+Bool_t MGList::IsExisting(TObject *obj) const
+{
+    const TGWidget *wid = GetWidget(obj);
+
+    //
+    // check whether it is a TGWidget
+    //
+    if (!wid)
+        return kFALSE;
+
+    const Int_t id = wid->WidgetId();
+
+    //
+    // check whether is has a valid id
+    // (not id=-1, which is the standard id)
+    //
+    if (id < 0)
+        return kFALSE;
+
+    //
+    // check whether Widget id is already existing in the list
+    //
+    return FindWidget(id) ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the given object obj is derived from TGWidget and a TGWidget with
+//  the same widget id is already existing in the list the object is
+//  ignored, otherwise it is added to the list via TList::Add(TObject *)
+//
+void MGList::Add(TObject *obj)
+{
+    if (IsExisting(obj))
+    {
+        // FIXME: Replace by gLog
+        const Int_t id = GetWidget(obj)->WidgetId();
+        cout << "Widget with id #" << id << " (";
+        cout << FindWidget(id)->ClassName() << ") already in list... ";
+        cout << obj->GetName() << " ignored." << endl;
+        return;
+    }
+
+    TList::Add(obj);
+    obj->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the given object obj is derived from TGWidget and a TGWidget with
+//  the same widget id is already existing in the list the object is
+//  ignored, otherwise it is added to the list via
+//  TList::Add(TObject *, Option_t *)
+//
+void MGList::Add(TObject *obj, Option_t *opt)
+{
+    if (IsExisting(obj))
+    {
+        Int_t id = GetWidget(obj)->WidgetId();
+        cout << "Widget with id #" << id << " (";
+        cout << FindWidget(id)->ClassName() << ") already in list... ";
+        cout << obj->GetName() << " ignored." << endl;
+        return;
+    }
+
+    TList::Add(obj, opt);
+    obj->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Adds the picture physically to the list. The list takes care of that
+//   - The picture is freed as often as it was retrieved from gClient
+//
+void MGList::AddPicture(TGPicture *pic, const char *name)
+{
+    //
+    // Check whether the picture exists
+    //
+    if (!pic)
+    {
+        cout << "Warning: Requested picture '" << name << "' not found... ignored." << endl;
+        cout << "    Please copy " << name << " to $HOME or $HOME/icons or add" << endl;
+        cout << "      Unix.*.Gui.IconPath: ~/Path/To/The/Picture" << endl;
+        cout << "    to [$HOME/].rootrc."  << endl;
+        return;
+    }
+
+    //
+    // Add the picture to the list
+    //
+    TList::Add(pic);
+    pic->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This gets a picture from the picture pool of the TGClient-object.
+//  The pictures are freed automatically in the dstructor of the list.
+//  The picture counts itself how often it got used, so that only
+//  the first call to GetPicture will craete it and the last call to
+//  FreePicture will destroy it. If you access the picture only via
+//  MGList::GetPicture you don't have to care about.
+//
+//  Don't try to call FreePicture by yourself for a picture gotten by
+//  GetPicture. This is independant of the kIsOwner bit.
+//
+const TGPicture *MGList::GetPicture(const char *name)
+{
+    if (!gClient)
+        return NULL;
+
+    TGPicture *pic = const_cast<TGPicture*>(gClient->GetPicture(name));
+    AddPicture(pic, name);
+    return pic;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This gets a picture from the picture pool of the TGClient-object.
+//  The pictures are freed automatically in the dstructor of the list.
+//  The picture counts itself how often it got used, so that only
+//  the first call to GetPicture will craete it and the last call to
+//  FreePicture will destroy it. If you access the picture only via
+//  MGList::GetPicture you don't have to care about.
+//
+//  Don't try to call FreePicture by yourself for a picture gotten by
+//  GetPicture. This is independant of the kIsOwner bit.
+//
+const TGPicture *MGList::GetPicture(const char *name, Int_t width, Int_t height)
+{
+    if (!gClient)
+        return NULL;
+
+    TGPicture *pic = const_cast<TGPicture*>(gClient->GetPicture(name, width, height));
+    AddPicture(pic, name);
+    return pic;
+}
+// --------------------------------------------------------------------------
+//
+//  Search the list for a object derived from TGidget which has the given
+//  widget id. Returns a pointer to this object otherwise NULL.
+//  For IDs < 0 the function returns always NULL.
+//
+TObject *MGList::FindWidget(Int_t id) const
+{
+    if (id<0)
+        return NULL;
+
+    TObject *obj;
+    TIter Next(this);
+    while ((obj=Next()))
+    {
+        const TGWidget *wid = GetWidget(obj);
+
+        if (!wid)
+            continue;
+
+        if (id == wid->WidgetId())
+            return obj;
+    }
+    return NULL;
+}
Index: branches/Mars_McMismatchStudy/mbase/MGList.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGList.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGList.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MGList
+#define MARS_MGList
+
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+
+class TGWidget;
+class TGPicture;
+
+class MGList : public TList
+{
+private:
+    TGWidget *GetWidget(TObject *obj) const;
+    Bool_t    IsExisting(TObject *obj) const;
+
+    void      AddPicture(TGPicture *pic, const char *name);
+    void      DeletePictures();
+
+public:
+    MGList();
+    ~MGList();
+
+    void Add(TObject *obj);
+    void Add(TObject *obj, Option_t *opt);
+
+    void Delete(Option_t *option="");
+
+    const TGPicture *GetPicture(const char *name);
+    const TGPicture *GetPicture(const char *name, Int_t width, Int_t height);
+
+    TObject *FindWidget(Int_t id) const;
+
+    ClassDef(MGList, 0)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MGMap.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGMap.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGMap.cc	(revision 17960)
@@ -0,0 +1,635 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 05/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MGMap
+//  =====
+//
+// This Map of TObjects connects TObjects with a TString. It can be used
+// to create maps which displays tooltips it the mouse is above the objects.
+//
+// It is also a tool to convert TObjects which are drawn into
+// a bitmap or to draw them into a TGFrame. Because in both cases the
+// support for drawing such object must be programmed explicitly only
+// simple objects (TLine, TMarker, etc) are supported.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MGMap.h"
+
+#include <climits>  // INT_MAX (Ubuntu 8.10)
+
+#include <TMath.h>
+
+#include <TPad.h>    // gPad, TPad::GetMaxDistance()
+
+#include <TLine.h>
+#include <TMarker.h>
+
+#include <TGToolTip.h>
+
+ClassImp(MGMap);
+
+using namespace std;
+
+//
+// THIS IS A WORKAROUND TO GET A MORE DIRECT ACCESS TO TGX11
+//
+/*
+#include <TGX11.h>
+class MGX11 : public TGX11
+{
+public:
+    ULong_t GetGc(Int_t which) const
+    {
+        return (ULong_t)*TGX11::GetGC(which);
+    }
+    void DrawLine(Drawable_t id, TObject *o, Int_t dx, Int_t dy, Float_t r)
+    {
+        TLine *l = dynamic_cast<TLine*>(o);
+        if (!l)
+            return;
+
+        SetLineColor(l->GetLineColor());
+        SetLineWidth(l->GetLineWidth());
+        SetLineStyle(l->GetLineStyle());
+
+        if (l->GetLineColor()==kRed)
+            SetLineColor(50);
+        if (l->GetLineColor()==kBlue)
+            SetLineColor(9);
+
+        gVirtualX->DrawLine(id, GetGc(0),
+                            dx+(l->GetX1()/r), dy-(l->GetY1()/r),
+                            dx+(l->GetX2()/r), dy-(l->GetY2()/r));
+    }
+    void DrawMarker(Drawable_t id, TObject *o, Int_t dx, Int_t dy, Float_t r)
+    {
+        TMarker *m = dynamic_cast<TMarker*>(o);
+        if (!m)
+            return;
+
+        SetLineColor(m->GetMarkerColor());
+        SetLineStyle(kSolid);
+        SetLineWidth(1);
+
+        const Double_t x = dx+(m->GetX()/r);
+        const Double_t y = dy-(m->GetY()/r);
+        const Int_t l = (Int_t)(m->GetMarkerSize()*5)+1;
+
+        switch (m->GetMarkerStyle())
+        {
+        case kPlus:
+            gVirtualX->DrawLine(id, GetGc(0), x-l, y, x+l, y);
+            gVirtualX->DrawLine(id, GetGc(0), x, y-l, x, y+l);
+            break;
+        case kCircle:
+            for (int i=0; i<8; i++)
+                gVirtualX->DrawLine(id, GetGc(0),
+                                    x+l*cos(i*TMath::TwoPi()/8),
+                                    y+l*sin(i*TMath::TwoPi()/8),
+                                    x+l*cos(((i+1)%8)*TMath::TwoPi()/8),
+                                    y+l*sin(((i+1)%8)*TMath::TwoPi()/8));
+            break;
+        case kCross:
+            gVirtualX->DrawLine(id, GetGc(0), x-l, y-l, x+l, y+l);
+            gVirtualX->DrawLine(id, GetGc(0), x-l, y+l, x+l, y-l);
+            break;
+        }
+    }
+};
+*/
+// --------------------------------------------------------------------------
+//
+// Constructor. For more details see TExMap
+//
+MGMap::MGMap(Int_t mapSize) : TExMap(mapSize)//, fToolTip(0)
+{
+//    fToolTip = new TGToolTip(0, "", 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes all objects of the map if kIsOwner is set via
+// SetOwner.
+//
+MGMap::~MGMap()
+{
+    if (TestBit(kIsOwner))
+        Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add an TObject to be drawn and if necessary a corresponding TString
+// to the Map. You must take care of deleting both objects if SetOwner()
+// was not called. Otherwise MGMap takes the ownership of the objects.
+//
+void MGMap::Add(TObject *k, TString *v)
+{
+    TExMap::Add((ULong_t)GetSize(), (Long_t)k, (Long_t)v);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete all objects stored in the TExMap
+//
+void MGMap::Delete(Option_t *)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+    Long_t key, val;
+#else
+    Long64_t key, val;
+#endif
+
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        delete (TObject*)(key);
+        if (val)
+            delete (TString*)(val);
+        /*
+         Long_t key2, val2;
+         TExMapIter map2(&fMapG);
+         while (map2.Next(key2, val2))
+         if (val==val2)
+         {
+         delete (TObject*)key;
+         fMapG.Remove(key);
+         }
+         */
+    }
+    TExMap::Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint all TObjects (which are supported) to a drawable with Id id.
+// Scale is the distance of the center of your drawable to one edge in
+// user coordinates.
+//
+// FIXME: Currently the width and height is hardcoded to 768x576 -
+//        find a way to get it from the drawable.
+//
+/*
+void MGMap::Paint(Drawable_t id, Float_t scale)
+{
+    if (id==0 && gPad)
+        id = gVirtualX->GetWindowID(gPad->GetPixmapID());
+
+    const Int_t w = 768;
+    const Int_t h = 576;
+
+    scale /= TMath::Hypot((float)w, (float)h)/2;
+
+    Long_t key, val;
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        TObject *o = (TObject*)key;
+        ((MGX11*)gVirtualX)->DrawLine(id,   o, w/2, h/2, scale);
+        ((MGX11*)gVirtualX)->DrawMarker(id, o, w/2, h/2, scale);
+    }
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Convert root colors to arbitrary bitmap coordinates
+//
+UChar_t MGMap::Color(int col)
+{
+    switch (col)
+    {
+    case kBlack:  return 0;
+    case kWhite:  return 0xff;
+    case kYellow: return 0x0f;
+    case kRed:    return 2;
+    case kGreen:  return 2<<2;
+    case kBlue:   return 2<<4;
+    default:
+        return 0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a line into the buffer (size w*h) from (x1, y1) to (x2, y2) with
+// the color col and the line style style (default: solid)
+//
+void MGMap::DrawLine(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style)
+{
+    const Int_t    step = style==kSolid?1:3;
+    const Double_t len  = TMath::Hypot(x2-x1, y2-y1);
+    const Double_t dx   = (x2-x1)/len*step;
+    const Double_t dy   = (y2-y1)/len*step;
+
+    Double_t x = x1;
+    Double_t y = y1;
+
+    for (int i=0; i<len; i+=step)
+    {
+        x+= dx;
+        y+= dy;
+
+        const Int_t iy = TMath::Nint(y);
+        if (iy<0 || iy>=h)
+            continue;
+
+        const Int_t ix = TMath::Nint(x);
+        if (ix<0 || ix>=w)
+            continue;
+
+        buf[ix+iy*w] = col;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a box into the buffer (size w*h) from (x1, y1) to (x2, y2) with
+// the color col and the line style style (default: solid)
+//
+void MGMap::DrawBox(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style)
+{
+    DrawLine(buf, w, h, x1, y1, x2, y1, col, style);
+    DrawLine(buf, w, h, x1, y2, x2, y1, col, style);
+    DrawLine(buf, w, h, x1, y1, x1, y2, col, style);
+    DrawLine(buf, w, h, x2, y1, x2, y2, col, style);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a hexagon into the buffer (size w*h) around (x, y) with radius r and
+// the color col.
+//
+void MGMap::DrawHexagon(UChar_t *buf, int w, int h, Float_t px, Float_t py, Float_t d, UChar_t col, Int_t style)
+{
+    const Int_t np = 6;
+
+    const Double_t dy[np+1] = { .5   , 0.    , -.5   , -.5   , 0.    ,  .5   , .5    };
+    const Double_t dx[np+1] = { .2886,  .5772,  .2886, -.2886, -.5772, -.2886, .2886 };
+
+    //
+    //  calculate the positions of the pixel corners
+    //
+    Double_t x[np+1], y[np+1];
+    for (Int_t i=0; i<np+1; i++)
+    {
+        x[i] = px + dx[i]*d;
+        y[i] = py + dy[i]*d;
+    }
+
+    for (int i=0; i<6; i++)
+        DrawLine(buf, w, h, x[i], y[i], x[i+1], y[i+1], col, style);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a circle into the buffer (size w*h) around (x, y) with radius r and
+// the color col.
+//
+void MGMap::DrawCircle(UChar_t *buf, int w, int h, Float_t x, Float_t y, Float_t r, UChar_t col)
+{
+    const Int_t n = TMath::Nint(sqrt(2.)*r*TMath::Pi()/2);
+    for (int i=0; i<n-1; i++)
+    {
+        const Double_t angle = TMath::TwoPi()*i/n;
+
+        const Double_t dx = r*cos(angle);
+        const Double_t dy = r*sin(angle);
+
+        const Int_t x1 = TMath::Nint(x+dx);
+        const Int_t x2 = TMath::Nint(x-dx);
+
+        const Int_t y1 = TMath::Nint(y+dy);
+        if (y1>=0 && y1<h)
+        {
+            if (x1>=0 && x1<w)
+                buf[x1+y1*w] = col;
+
+            if (x2>=0 && x2<w)
+                buf[x2+y1*w] = col;
+        }
+
+        const Int_t y2 = TMath::Nint(y-dy);
+        if (y2>=0 && y2<h)
+        {
+            if (x1>=0 && x1<w)
+                buf[x1+y2*w] = col;
+
+            if (x2>=0 && x2<w)
+                buf[x2+y2*w] = col;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a dot into the buffer (size w*h) at (x, y) with color col.
+//
+void MGMap::DrawDot(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, UChar_t col)
+{
+    const Int_t x1 = TMath::Nint(cx);
+    const Int_t y1 = TMath::Nint(cy);
+
+    if (x1>=0 && y1>=0 && x1<w && y1<h)
+        buf[x1+y1*w] = col;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a line into the buffer. The TObject must be a TLine.
+// Currently only solid and non sloid line are supported.
+//
+void MGMap::DrawLine(TObject *o, UChar_t *buf, int w, int h, Double_t scale)
+{
+    TLine *l = dynamic_cast<TLine*>(o);
+    if (!l)
+        return;
+
+    const Double_t x1 = 0.5*w-(l->GetX1()/scale);
+    const Double_t x2 = 0.5*w-(l->GetX2()/scale);
+    const Double_t y1 = 0.5*h-(l->GetY1()/scale);
+    const Double_t y2 = 0.5*h-(l->GetY2()/scale);
+
+    const Int_t col = Color(l->GetLineColor());
+    DrawLine(buf, w, h, x1, y1, x2, y2, col, l->GetLineStyle());
+}
+
+void MGMap::DrawMultiply(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col)
+{
+    DrawLine(buf, w, h, cx-size, cy-size, cx+size, cy+size, col);
+    DrawLine(buf, w, h, cx+size, cy-size, cx-size, cy+size, col);
+}
+
+void MGMap::DrawCross(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col)
+{
+    DrawLine(buf, w, h, cx-size, cy, cx+size, cy, col);
+    DrawLine(buf, w, h, cx, cy-size, cx, cy+size, col);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw marker into the buffer. The TObject must be a TMarker.
+// Currently kCircle, kMultiply and KDot are supported.
+//
+void MGMap::DrawMarker(TObject *o, UChar_t *buf, int w, int h, Double_t scale)
+{
+    TMarker *m = dynamic_cast<TMarker*>(o);
+    if (!m)
+        return;
+
+    Double_t x = 0.5*w-(m->GetX()/scale);
+    Double_t y = 0.5*h-(m->GetY()/scale);
+
+    Int_t col = Color(m->GetMarkerColor());
+
+    switch (m->GetMarkerStyle())
+    {
+    case kCircle:
+        DrawCircle(buf, w, h, x, y, m->GetMarkerSize()*2+1, col);
+        break;
+    case kDot:
+        DrawDot(buf, w, h, x, y, col);
+        break;
+    case kMultiply:
+        DrawMultiply(buf, w, h, x, y, m->GetMarkerSize()*2+1, col);
+        break;
+    case kCross:
+        DrawCross(buf, w, h, x, y, m->GetMarkerSize()*2+1, col);
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint all elements to the pad by calling their Paint() function
+//
+void MGMap::Paint(Option_t *)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+    Long_t key, val;
+#else
+    Long64_t key, val;
+#endif
+
+    TExMapIter map(this);
+    while (map.Next(key, val))
+        ((TObject*)key)->Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint all objects into a buffer of w*h UChar_ts. The scale
+// gives you the conversio factor to convert pad coordinates into
+// buffer pixels - it is the distance from the center of the buffer
+// to one of its edges.
+//
+void MGMap::Paint(UChar_t *buf, int w, int h, Float_t scale)
+{
+    scale /= TMath::Hypot((float)w, (float)h)/2;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+    Long_t key, val;
+#else
+    Long64_t key, val;
+#endif
+
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        TObject *o = (TObject*)key;
+        DrawLine(o, buf, w, h, scale);
+        DrawMarker(o, buf, w, h, scale);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for an object at px, py. Return the pointer to it
+// if found. Set str accordingly if a corresponding TString is found.
+//
+TObject *MGMap::PickObject(Int_t px, Int_t py, TString &str) const
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+    Long_t key, val;
+#else
+    Long64_t key, val;
+#endif
+
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        if (!val)
+            continue;
+
+        TObject *o=(TObject*)key;
+        if (o->DistancetoPrimitive(px, py)>TPad::GetMaxPickDistance())
+            continue;
+
+        str = *(TString*)val;
+        return o;
+    }
+    return NULL;
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns string containing info about the object at position (px,py).
+// Returned string will be re-used (lock in MT environment).
+// The text will be truncated to 128 charcters
+//
+char *MGMap::GetObjectInfo(Int_t px, Int_t py) const
+{
+    TString str;
+    PickObject(px, py, str);
+
+    static char txt[129];
+    txt[128]=0;
+
+    return strncpy(txt, str.Data(), 128);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate distance to primitive by checking all gui elements
+//
+Int_t MGMap::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    Int_t min = INT_MAX;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+    Long_t key, val;
+#else
+    Long64_t key, val;
+#endif
+
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        TObject *o=(TObject*)key;
+
+        const Int_t d = o->DistancetoPrimitive(px, py);
+
+        if (d<TPad::GetMaxPickDistance())
+            return 0;
+
+        if (d<min)
+            min=d;
+    }
+
+    return min;
+}
+
+// --------------------------------------------------------------------------
+//
+// Displays a tooltip
+//
+/*
+void MGMap::ShowToolTip(Int_t px, Int_t py, const char *txt)
+{
+    if (TestBit(kNoToolTips))
+        return;
+
+    Int_t x=0;
+    Int_t y=0;
+
+    const Window_t id1 = gVirtualX->GetWindowID(gPad->GetCanvasID());
+    const Window_t id2 = fToolTip->GetParent()->GetId();
+
+    Window_t id3;
+    gVirtualX->TranslateCoordinates(id1, id2, px, py, x, y, id3);
+
+    // Show tool tip
+    fToolTip->SetText(txt);
+    fToolTip->Show(x+4, y+4);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// This function was connected to all created canvases. It is used
+// to redirect GetObjectInfo into our own status bar.
+//
+// The 'connection' is done in Draw. It seems that 'connected'
+// functions must be public.
+//
+/*
+void MGMap::EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected)
+{
+    TVirtualPad *c = (TVirtualPad*)gTQSender; // gTQSender==TCanvas
+
+    gPad = c ? c->GetSelectedPad() : NULL;
+    if (!gPad)
+        return;
+
+    // Try to find a corresponding object with kCannotPick set and
+    // an available TString (for a tool tip)
+    TString str;
+    if (!selected || selected==this)
+        selected =  PickObject(px, py, str);
+
+    if (!selected)
+        return;
+
+    // Handle some gui events
+    switch (event)
+    {
+    case kMouseMotion:
+        if (!fToolTip->IsMapped() && !str.IsNull())
+            ShowToolTip(px, py, str);
+        break;
+
+    case kMouseLeave:
+        if (fToolTip->IsMapped())
+            fToolTip->Hide();
+        break;
+
+    default:
+        ExecuteEvent(event, px, py);
+        break;
+    }
+}
+*/
+
+/*
+void MAstroCatalog::RecursiveRemove(TObject *obj)
+{
+    ULong_t hash;
+    Long_t key, val;
+
+    TExMapIter map(&fMapG);
+    while (map.Next(hash, key, val))
+    {
+        if (key != (Long_t)obj)
+            continue;
+
+        fMapG.Remove(hash, key);
+        delete (TObject*)(key);
+        if (val)
+            delete (TString*)(val);
+        break;
+    }
+}
+*/
Index: branches/Mars_McMismatchStudy/mbase/MGMap.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGMap.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGMap.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MGMap
+#define MARS_MGMap
+
+#ifndef ROOT_GuiTypes
+#include <GuiTypes.h> // Drawable_t
+#endif
+#ifndef ROOT_TExMap
+#include <TExMap.h>
+#endif
+
+class TString;
+class TGToolTip;
+
+#include <iostream>
+
+class MGMap : public TExMap
+{
+private:
+    //    TGToolTip *fToolTip;   //! The tooltip currently displayed
+
+    enum {
+        kIsOwner    = BIT(14),
+        // kNoToolTips = BIT(15), // suppress tooltips
+    };
+
+    //    void ShowToolTip(Int_t px, Int_t py, const char *txt);
+
+public:
+    MGMap(Int_t mapSize = 100);
+    ~MGMap();
+
+    void     SetOwner(Bool_t o=kTRUE) { o ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+    void     Add(TObject *k, TString *v=0);
+    void     Delete(Option_t *opt="");
+    void     Clear(Option_t *o="") { TExMap::Delete(o); }
+
+    //    void   SetNoToolTips(Bool_t b=kTRUE) { b ? SetBit(kNoToolTips) : ResetBit(kNoToolTips); } // *TOGGLE* *GETTER=HasNoToolTips
+    //    Bool_t HasNoToolTips() const         { return TestBit(kNoToolTips); }
+
+    void     Paint(Option_t *o="");
+    void     Paint(UChar_t *buf, int w, int h, Float_t scale);
+    //void     Paint(Drawable_t id, Float_t scale);
+
+    void     DrawLine(TObject *o, UChar_t *buf, int w, int h, Double_t scale);
+    void     DrawMarker(TObject *o, UChar_t *buf, int w, int h, Double_t scale);
+
+    //void     EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected);
+    TObject *PickObject(Int_t px, Int_t py, TString &str) const;
+    char    *GetObjectInfo(Int_t px, Int_t py) const;
+    Int_t    DistancetoPrimitive(Int_t px, Int_t py);
+
+    static UChar_t Color(int col);
+    static void    DrawCircle(UChar_t *buf, int w, int h, Float_t x, Float_t y, Float_t r, UChar_t col);
+    static void    DrawHexagon(UChar_t *buf, int w, int h, Float_t x, Float_t y, Float_t r, UChar_t col, Int_t style=1);
+    static void    DrawLine(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style=1);
+    static void    DrawBox(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style=1);
+    static void    DrawDot(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, UChar_t col);
+    static void    DrawMultiply(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col);
+    static void    DrawCross(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col);
+
+    ClassDef(MGMap, 1) // Special TExMap supporting enhanced drawing and bitmap drawing
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MGMenu.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGMenu.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGMenu.cc	(revision 17960)
@@ -0,0 +1,235 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2003 <mailto:tbretz@astro-uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGMenu, MGPopupMenu
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MGMenu.h"
+
+
+MGMenuEntry::MGMenuEntry(TGMenuEntry *ent)
+{
+    memcpy(this, ent, sizeof(*ent));
+}
+
+// -------------------------------------------------------------
+//
+// Return the keycode corresponding to the hot string of
+// a TGmenuEntry
+//
+UInt_t MGPopupMenu::GetKeyCode(TGMenuEntry *el)
+{
+    TGHotString *str = MGMenuEntry(el).GetLabel();
+    return gVirtualX->KeysymToKeycode(str->GetHotChar());
+}
+
+// -------------------------------------------------------------
+//
+// Bind all hot keys used in this popup menu subsequentlt
+// to the TGMainFrame and send a HandleKey message to the
+// TGWindow
+//
+void MGPopupMenu::BindKeys(const TGWindow *w, TGMainFrame *frame)
+{
+    TIter Next(fEntryList);
+    TGMenuEntry *el;
+
+    //
+    // Loop Through all entries
+    //
+    while ((el=(TGMenuEntry*)Next()))
+    {
+        switch (el->GetType())
+        {
+            //
+            // For seperators and labels nothing to do
+            //
+        case kMenuSeparator:
+        case kMenuLabel:
+            continue;
+
+            //
+            // For an entry and a popup menu bind the hot key
+            // In case of a popup menu call BindKeys subsequently
+            //
+        case kMenuEntry:
+        case kMenuPopup:
+            frame->BindKey(w, GetKeyCode(el), kKeyMod1Mask);
+            if (el->GetType()==kMenuPopup)
+                MGMenuEntry(el).GetPopup()->BindKeys(w, frame);
+            continue;
+        }
+    }
+}
+
+/*
+ kMenuActiveMask  = BIT(0),
+ kMenuEnableMask  = BIT(1),
+ kMenuDefaultMask = BIT(2),
+ kMenuCheckedMask = BIT(3),
+ kMenuRadioMask   = BIT(4),
+ kMenuHideMask    = BIT(5)
+ */
+
+// -------------------------------------------------------------
+//
+//  Handle a keyboard event. Return kFALSE in case of a
+//  successfully send message, which means: close all open
+//  popups.
+//
+Bool_t MGPopupMenu::HandleKey(Event_t *evt)
+{
+    //
+    // Loop through all entries in this popup menu. If the entry is
+    // an open popup menu send the key event to the open popup.
+    //
+    TIter Next(fEntryList);
+    TGMenuEntry *el;
+    while ((el=(TGMenuEntry*)Next()))
+    {
+        if (el->GetType()==kMenuPopup && el->GetStatus()&kMenuActiveMask)
+            return MGMenuEntry(el).GetPopup()->HandleKey(evt);
+    }
+
+    Next.Reset();
+
+    //
+    // If no open popup is found search the pressed key in this
+    // popup menu.
+    //
+    while ((el=(TGMenuEntry*)Next()))
+    {
+        switch (el->GetType())
+        {
+            //
+            // Do nothing
+            //
+        case kMenuSeparator:
+        case kMenuLabel:
+            continue;
+
+            //
+            // If the keycode corresponds to the hot key
+            // of this entry and the entry is enabled activate the entry
+            // and send the corresponding message/
+            //
+        case kMenuEntry:
+            if (GetKeyCode(el)==evt->fCode && el->GetStatus()&kMenuEnableMask)
+            {
+                Activate(el);
+                SendMessage(fMsgWindow, MK_MSG(kC_COMMAND, kCM_MENU),
+                            el->GetEntryId(), (Long_t)MGMenuEntry(el).GetUserData());
+                return kFALSE;
+            }
+            continue;
+
+            //
+            // If the keycode corresponds to the hot key
+            // of this popup menu activate the popup menu.
+            //
+        case kMenuPopup:
+            if (GetKeyCode(el)!=evt->fCode)
+                continue;
+
+            Activate(el);
+            HandleTimer(NULL);
+            return kTRUE;
+        }
+    }
+    return kTRUE;
+}
+
+// -------------------------------------------------------------
+//
+// Bind the keys of all popups subsequently to the given main
+// frame. The menu bar hot keys are already bound by TGMenuBar.
+// Bind the Escape key to close the popups, too.
+//
+void MGMenuBar::BindKeys(TGMainFrame *frame)
+{
+    TGFrameElement *el=NULL;
+    TIter Next(fList);
+    while ((el = (TGFrameElement *)Next()))
+        ((MGPopupMenu*)((TGMenuTitle *) el->fFrame)->GetMenu())->BindKeys(this, frame);
+
+    frame->BindKey(this, 9/*ESC*/, 0);
+}
+
+// -------------------------------------------------------------
+//
+// Handle the keyboard event send to this menu bar.
+//
+Bool_t MGMenuBar::HandleKey(Event_t *event)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,02,00)
+    //
+    // If this isn't a pressed key do nothing
+    //
+    if (event->fType != kGKeyPress)
+        return kTRUE;
+
+    //
+    // Check whether one popup is alreadu open
+    //
+    TGFrameElement *el=NULL;
+    TIter Next(fList);
+    while ((el = (TGFrameElement *)Next()))
+    {
+        if (!((TGMenuTitle*)el->fFrame)->GetState())
+            continue;
+
+        TGMenuTitle &f = *(TGMenuTitle*)el->fFrame;
+
+        //
+        // If a open popup is found redirect the key event to this
+        // popup menu
+        //
+        Bool_t rc = ((MGPopupMenu*)f.GetMenu())->HandleKey(event);
+
+        //
+        // If a message could be successfully send or the escape key
+        // was pressed close the popup.
+        //
+        if (rc && event->fCode!=9/*ESC*/)
+            return kTRUE;
+
+        f.SetState(kFALSE);
+        gVirtualX->GrabPointer(0, 0, 0, 0, kFALSE);  // ungrab pointer
+        gVirtualX->SetKeyAutoRepeat(kTRUE); // set in TGMainFrame::HandleKey
+        fCurrent = 0;
+        return kTRUE;
+    }
+#endif
+
+    return TGMenuBar::HandleKey(event);
+}
+
+void MGMenuBar::BindKeys(Bool_t b)
+{
+#if ROOT_VERSION_CODE >= ROOT_VERSION(4,02,00)
+    TGMenuBar::BindKeys(b);
+#endif
+}  // root>=4.02.00
Index: branches/Mars_McMismatchStudy/mbase/MGMenu.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGMenu.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGMenu.h	(revision 17960)
@@ -0,0 +1,54 @@
+#ifndef MARS_MGMenu
+#define MARS_MGMenu
+
+#ifndef ROOT_TGMenu
+#include <TGMenu.h>
+#endif
+
+class MGPopupMenu;
+
+class MGMenuEntry : public TGMenuEntry
+{
+    /*
+     Workaround for the protected data mambers of TGMenuEntry
+     */
+public:
+    MGMenuEntry(TGMenuEntry *ent);
+    ~MGMenuEntry()
+    {
+        fLabel=0;
+    }
+
+    MGPopupMenu *GetPopup() { return (MGPopupMenu*)fPopup; }
+    TGHotString *GetLabel() { return fLabel; }
+    void *GetUserData()     { return fUserData; }
+};
+
+class MGPopupMenu : public TGPopupMenu
+{
+public:
+    MGPopupMenu(const TGWindow* p = 0, UInt_t w = 10, UInt_t h = 10, UInt_t options = 0) :
+        TGPopupMenu(p, w, h, options)
+    {
+    }
+
+    UInt_t GetKeyCode(TGMenuEntry *el);
+
+    void BindKeys(const TGWindow *w, TGMainFrame *frame);
+
+    Bool_t HandleKey(Event_t *evt);
+};
+
+class MGMenuBar : public TGMenuBar
+{
+public:
+    MGMenuBar(const TGWindow* p, UInt_t w, UInt_t h, UInt_t options = kHorizontalFrame|kRaisedFrame) :
+        TGMenuBar(p, w, h, options) {}
+
+    void BindKeys(TGMainFrame *frame);                   // root<=3.10.02
+    void BindKeys(Bool_t b);
+
+    Bool_t HandleKey(Event_t *event);
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MGTask.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGTask.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGTask.cc	(revision 17960)
@@ -0,0 +1,184 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  11/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MGTask                                                                //
+//                                                                         //
+//   A MTask with several enhancments for a graphical interface.           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MGTask.h"
+
+#include <TClass.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: branches/Mars_McMismatchStudy/mbase/MGTask.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MGTask.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MGTask.h	(revision 17960)
@@ -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 *) {}
+
+    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: branches/Mars_McMismatchStudy/mbase/MInputStreamID.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MInputStreamID.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MInputStreamID.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MInputStreamID.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MInputStreamID.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MInputStreamID.h	(revision 17960)
@@ -0,0 +1,46 @@
+#ifndef MARS_MInputStreamID
+#define MARS_MInputStreamID
+
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MInpuStreamID                                                     //
+//                                                                   //
+// Assigns an ID to tasks or a task list                             //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+// -----------------------------------------------------------------------
+
+class MInputStreamID : public MParContainer
+{
+private:
+    TString fStreamId;	//! which type of task should be processed?
+
+public:
+    MInputStreamID(const char *name=NULL, const char *title=NULL);
+
+    Bool_t HasStreamId() const { return fStreamId.CompareTo("all", TString::kIgnoreCase)!=0; }
+
+    const TString &GetStreamId() const { return fStreamId; }
+    void SetStreamId(const char *t)    { fStreamId = t; }
+
+    Bool_t operator==(MInputStreamID &id) const
+    {
+        return fStreamId == id.fStreamId;
+    }
+
+    Bool_t operator!=(MInputStreamID &id) const
+    {
+        return fStreamId != id.fStreamId;
+    }
+
+    ClassDef(MInputStreamID, 0)	//Assigns an Id to tasks or a task list
+};
+
+// ---------------------------------------------------------------------
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MIter.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MIter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MIter.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MIter.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MIter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MIter.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MLog.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLog.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLog.cc	(revision 17960)
@@ -0,0 +1,932 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2006
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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()
+#include <TSystem.h>
+
+#ifdef _REENTRANT
+#include <TMutex.h>
+#endif
+#include <TGTextView.h>
+
+#include <TEnv.h>       // gEnv (ErrorHandler)
+#include <TError.h>     // TError (SetErrorHandler)
+
+#include "MArgs.h"
+#include "MTime.h"
+#include "MString.h"
+#include "MParContainer.h"
+
+#include "MLogHtml.h"
+#include "MLogManip.h"  // inf,warn,err (MLog::ErrorHandler)
+
+ClassImp(MLog);
+
+using namespace std;
+
+#undef DEBUG
+//#define DEBUG
+
+
+// root 3.02:
+// check for TObjectWarning, TObject::Info, gErrorIgnoreLevel
+
+const char MLog::kESC = '\033'; // (char)27
+const char *const MLog::kEsc       = "\033[";
+const char *const MLog::kReset     = "\033[0m";
+const char *const MLog::kRed       = "\033[31m";
+const char *const MLog::kGreen     = "\033[32m";
+#ifdef HAVE_DARKBACKGROUND
+const char *const MLog::kYellow    = "\033[33m\033[1m";
+#else
+const char *const MLog::kYellow    = "\033[33m";
+#endif
+const char *const MLog::kBlue      = "\033[34m";
+const char *const MLog::kUnderline = "\033[4m";
+const char *const MLog::kBlink     = "\033[5m";
+const char *const MLog::kBright    = "\033[1m";
+const char *const MLog::kDark      = "\033[2m";
+
+//
+// This is the definition of the global log facility
+//
+MLog gLog;
+
+// --------------------------------------------------------------------------
+//
+// this strange usage of an unbufferd buffer is a workaround
+// to make it work on Alpha and Linux!
+//
+void MLog::Init()
+{
+    //
+    // Creat drawing semaphore
+    //
+#ifdef _REENTRANT
+    fMuxGui    = new TMutex;
+    fMuxStream = new TMutex;
+#endif
+
+    fPlugins = new TList;
+    gROOT->GetListOfCleanups()->Add(fPlugins);
+    fPlugins->SetBit(kMustCleanup);
+
+    setp(&fBuffer, &fBuffer+1);
+    *this << '\0';
+}
+
+// --------------------------------------------------------------------------
+//
+// default constructor which initializes the streamer and sets the device
+// which is used for the output (i)
+//
+MLog::MLog(int i) : ostream(this), fPPtr(fBase), fEPtr(fBase+fgBufferSize), 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 &sout) : ostream(this), fPPtr(fBase), fEPtr(fBase+fgBufferSize), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eFile), fIsNull(kFALSE), fOut(&sout), 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 &sout) : ostream(this), fPPtr(fBase), fEPtr(fBase+fgBufferSize), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eGui), fOut(NULL), fOutAllocated(kFALSE), fGui(&sout), 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+fgBufferSize), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eFile), fIsNull(kFALSE), fGui(NULL), fNumLines(0)
+{
+    Init();
+
+    AllocateFile(fname);
+    CheckFlag(eFile, flag);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor, destroying the gui mutex.
+//
+MLog::~MLog()
+{
+    DeallocateFile();
+
+#ifdef DEBUG
+    TIter Next(fPlugins);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        cout << "Delete: " << o->GetName() << std::flush;
+        cout << " [" << o->ClassName() << "]" << endl;
+        delete o;
+    }
+
+    cout << "Delete: fPlugins " << fPlugins << "..." << std::flush;
+#endif
+
+    delete fPlugins;
+#ifdef DEBUG
+    cout << "done." << endl;
+#endif
+
+#ifdef _REENTRANT
+    delete fMuxStream;
+    delete fMuxGui;
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// copyt constructor
+//
+/*
+MLog::MLog(MLog const& log)
+{
+//    fOutputLevel = log.fOutputLevel;
+//    fDebugLevel  = log.fDebugLevel;
+//    fDevice      = log.fDevice;
+}
+*/
+
+void MLog::Underline()
+{
+    if (fIsNull)
+        return;
+
+    SetBit(kIsUnderlined);
+
+    fPlugins->R__FOR_EACH(MLogPlugin, Underline)();
+
+    if (TestBit(eNoColors))
+        return;
+
+    if (fDevice&eStdout)
+        cout << kUnderline;
+
+    if (fDevice&eStderr)
+        cerr << kUnderline;
+}
+
+void MLog::Output(ostream &sout, 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:  sout << MLog::kRed;     break;  // err
+        case 2:  sout << MLog::kYellow;  break;  // warn
+        case 3:                                  // inf
+        case 4:                                  // inf2
+        case 5:  sout << MLog::kGreen;   break;  // inf3
+        default: sout << 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')
+        sout << TString(fBase, len-endline);
+        // reset colors if working with colors
+        if (!TestBit(eNoColors))
+            sout << kReset;
+        // output EOL of check found EOL
+        if (endline)
+        {
+            sout << '\n';
+            // Check whether text was underlined
+            if (TestBit(kIsUnderlined) && TestBit(eNoColors))
+            {
+                sout << setw(len-1) << setfill('-') << "" << "\n";
+                ResetBit(kIsUnderlined);
+            }
+        }
+    }
+    sout.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->R__FOR_EACH(MLogPlugin, SetColor)(fOutputLevel);
+    fPlugins->R__FOR_EACH(MLogPlugin, WriteBuffer)(fBase, len);
+
+    if (fDevice&eGui && fGui)
+    {
+        // check whether the current text was flushed or endl'ed
+        const Int_t endline = fBase[len-1]=='\n' ? 1 : 0;
+
+        // for the gui remove trailing characters ('\n' or '\0')
+        fBase[len-endline]='\0';
+
+        // add new text to line storage
+        fGuiLine += fBase;
+
+        if (endline)
+        {
+            AddGuiLine(fGuiLine);
+            fGuiLine = "";
+
+            // Check whether text should be underlined
+            if (endline && TestBit(kIsUnderlined))
+            {
+                AddGuiLine("");
+                fGuiLines[fNumLines-1]->Append('-', fGuiLines[fNumLines-2]->Length());
+                ResetBit(kIsUnderlined);
+            }
+        }
+    }
+}
+
+void MLog::UpdateGui()
+{
+    if (fNumLines==0)
+        return;
+
+    // lock mutex
+    if (!LockUpdate("UpdateGui"))
+    {
+        Warning("UpdateGui", "Execution skipped");
+        return;
+    }
+
+    TGText &txt=*fGui->GetText();
+
+    // copy lines to TGListBox
+    for (int i=0; i<fNumLines; i++)
+    {
+        // Replace all tabs by 7 white spaces
+        fGuiLines[i]->ReplaceAll("\t", "       ");
+        txt.InsText(TGLongPosition(0, txt.RowCount()), *fGuiLines[i]);
+        delete fGuiLines[i];
+    }
+    delete [] fGuiLines;
+
+    fNumLines=0;
+
+    // cut text box top 1000 lines
+    //    while (txt.RowCount()>1000)
+    //        txt.DelLine(1);
+
+    // show last entry
+    fGui->Layout();
+    fGui->SetVsbPosition(txt.RowCount()-1);
+
+    // tell a main loop, that list box contents have changed
+    fGui->SetBit(kHasChanged);
+
+    // release mutex
+    UnLockUpdate("UpdateGui");
+}
+
+bool MLog::LockUpdate(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxGui->Lock()==13)
+    {
+        Info("LockUpdate", "%s - mutex is already locked by this thread\n", msg);
+        return false;
+    }
+#endif
+    return true;
+}
+
+bool MLog::UnLockUpdate(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxGui->UnLock()==13)
+    {
+        Info("UnLockUpdate", "%s - tried to unlock mutex locked by other thread\n", msg);
+        return false;
+    }
+#endif
+    return true;
+}
+
+bool MLog::Lock(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxStream->Lock()==13)
+    {
+        Error("Lock", "%s - mutex is already locked by this thread\n", msg);
+        return false;
+    }
+//    while (fMuxStream->Lock()==13)
+//        usleep(1);
+//    {
+//        Error("Lock", "%s - mutex is already locked by this thread\n", msg);
+//        return false;
+//    }
+#endif
+    return true;
+}
+
+bool MLog::UnLock(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxStream->UnLock()==13)
+    {
+        Error("UnLock", "%s - tried to unlock mutex locked by other thread\n", msg);
+        return false;
+    }
+#endif
+    return true;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is called to flush the buffer of the streaming devices
+//
+int MLog::sync()
+{
+    if (!LockUpdate("sync"))
+        usleep(1);
+    WriteBuffer();
+    UnLockUpdate("sync");
+
+    if (fDevice&eStdout)
+    {
+        if (!fIsNull && !TestBit(eNoColors))
+            cout << kReset;
+        cout.flush();
+    }
+
+    if (fDevice&eStderr)
+        cerr.flush();
+
+    if (fDevice&eFile && fOut)
+        fOut->flush();
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function comes from streambuf and should
+// output the buffer to the device (flush, endl)
+// or handle a buffer overflow (too many chars)
+// If a real overflow happens i contains the next
+// chars which doesn't fit into the buffer anymore.
+// If the buffer is not really filled i is EOF(-1).
+//
+int MLog::overflow(int i) // i=EOF means not a real overflow
+{
+    //
+    // no output if
+    //
+    if (fOutputLevel <= fDebugLevel)
+    {
+        if (!LockUpdate("overflow"))
+            usleep(1);
+
+        *fPPtr++ = (char)i;
+
+        if (fPPtr == fEPtr)
+            WriteBuffer();
+
+        UnLockUpdate("overflow");
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print usage information setup in Setup()
+//
+void MLog::Usage()
+{
+    //                 1         2         3         4         5         6         7         8
+    //        12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    *this << "   -v#                       Verbosity level # [default=2]" << endl;
+    *this << "   -a, --no-colors           Do not use Ansii color codes" << endl;
+    *this << "   --log[=file]              Write log-out to ascii-file [default: prgname.log]" << endl;
+    *this << "   --html[=file]             Write log-out to html-file [default: prgname.html]" << endl;
+    *this << "   --debug[=n]               Enable root debugging [default: gDebug=1]" << endl;
+    *this << "   --null                    Null output (supresses all output)" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup MLog and global debug output from command line arguments.
+//
+void MLog::Setup(MArgs &arg)
+{
+    // FXIME: This is not really at a place where it belongs to!
+    gDebug = arg.HasOption("--debug=") ? arg.GetIntAndRemove("--debug=") : 0;
+    if (gDebug==0 && arg.HasOnlyAndRemove("--debug"))
+        gDebug=1;
+
+    TString f1 = arg.GetStringAndRemove("--log=", "");
+    if (f1.IsNull() && arg.HasOnlyAndRemove("--log"))
+        f1 = MString::Format("%s.log", arg.GetName());
+    if (!f1.IsNull())
+    {
+        SetOutputFile(f1);
+        EnableOutputDevice(eFile);
+    }
+
+    TString f2 = arg.GetStringAndRemove("--html=", "");
+    if (f2.IsNull() && arg.HasOnlyAndRemove("--html"))
+        f2 = MString::Format("%s.html", arg.GetName());
+    if (!f2.IsNull())
+    {
+        MLogHtml *html = new MLogHtml(f2);
+        html->SetBit(kCanDelete);
+        AddPlugin(html);
+    }
+
+    const Bool_t null = arg.HasOnlyAndRemove("--null");
+    if (null)
+        SetNullOutput();
+
+    if (arg.HasOnlyAndRemove("--no-colors") || arg.HasOnlyAndRemove("-a"))
+        SetNoColors();
+
+    SetDebugLevel(arg.GetIntAndRemove("-v", 2));
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   MLog.VerbosityLevel: 0, 1, 2, 3, 4
+//   MLog.DebugLevel: 0, 1, 2, 3, 4
+//   MLog.NoColors
+//
+// Depending on your setup it might be correct to use something like:
+//   Job1.MLog.VerbosityLevel: 1
+//   Job1.DebugLevel: 2
+//   Job1.MLog.NoColors
+//
+void MLog::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    MParContainer mlog("MLog");
+
+    if (mlog.IsEnvDefined(env, prefix+"MLog", "VerbosityLevel", print))
+        SetDebugLevel(mlog.GetEnvValue(env, prefix+"MLog", "VerbosityLevel", 2));
+    else
+        if (mlog.IsEnvDefined(env, "MLog", "VerbosityLevel", print))
+            SetDebugLevel(mlog.GetEnvValue(env, "MLog", "VerbosityLevel", 2));
+
+    if (mlog.IsEnvDefined(env, prefix+"MLog", "DebugLevel", print))
+        gDebug = mlog.GetEnvValue(env, prefix+"MLog", "DebugLevel", 0);
+    else
+        if (mlog.IsEnvDefined(env, "MLog", "DebugLevel", print))
+            gDebug = mlog.GetEnvValue(env, "MLog", "DebugLevel", 0);
+
+    if (mlog.IsEnvDefined(env, prefix+"MLog", "NoColors", print))
+        SetNoColors(mlog.GetEnvValue(env, prefix+"MLog", "NoColors", kFALSE));
+    else
+        if (mlog.IsEnvDefined(env, "MLog", "NoColors", print))
+            SetNoColors(mlog.GetEnvValue(env, "MLog", "NoColors", kFALSE));
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   MLog.VerbosityLevel: 0, 1, 2, 3, 4
+//   MLog.DebugLevel: 0, 1, 2, 3, 4
+//   MLog.NoColors
+//
+// Depending on your setup it might be correct to use something like:
+//   Job1.MLog.VerbosityLevel: 1
+//   Job1.DebugLevel: 2
+//   Job1.MLog.NoColors
+//
+void MLog::WriteEnv(TEnv &, TString prefix, Bool_t) const
+{
+    if (!prefix.IsNull())
+        prefix += ".";
+    prefix += "MLog";
+
+    cout << "MLog::WriteEnv: not yet implemented!" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Create a new instance of an file output stream
+// an set the corresponding flag
+//
+void MLog::AllocateFile(const char *fname)
+{
+    // gcc 3.2:
+    const char *txt = "logXXXXXX";
+
+    TString n(fname ? fname : txt);
+    gSystem->ExpandPathName(n);
+
+    fOut = new ofstream(n.Data());
+
+    // switch off buffering
+    fOut->rdbuf()->pubsetbuf(0,0);
+
+    fOutAllocated = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// if fout was allocated by this instance of MLooging
+// delete it.
+//
+void MLog::DeallocateFile()
+{
+    if (fOutAllocated)
+        delete fOut;
+}
+
+// --------------------------------------------------------------------------
+//
+// if necessary delete the old in stance of the file
+// output stream and create a new one
+//
+void MLog::ReallocateFile(const char *fname)
+{
+    DeallocateFile();
+    AllocateFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// This function checks if a device should get enabled or disabled.
+//
+void MLog::CheckFlag(Flags_t chk, int flag)
+{
+    if (flag==-1)
+        return;
+
+    flag ? EnableOutputDevice(chk) : DisableOutputDevice(chk);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a plugin to which the output should be redirected, eg. MLogHtml
+// The user has to take care of its deletion. If the plugin is deleted
+// (and the kMustCleanup bit was not reset accidentaly) the plugin
+// is automatically removed from the list of active plugins.
+//
+// If MLog should take the ownership call plug->SetBit(kCanDelete);
+//
+void MLog::AddPlugin(MLogPlugin *plug)
+{
+    fPlugins->Add(plug);
+
+    // Make sure that it is recursively deleted from all objects in ListOfCleanups
+    plug->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns "yyyy-mm-dd user@host gROOT->GetName()[pid]"
+//
+TString MLog::Intro()
+{
+    UserGroup_t *user = gSystem->GetUserInfo();
+
+    TString rc;
+    rc += MTime(-1).GetSqlDateTime();
+    rc += " ";
+    rc += user->fUser;
+    rc += "@";
+    rc += gSystem->HostName();
+    rc += " ";
+    rc += gROOT->GetName();
+    rc += "[";
+    rc += gSystem->GetPid();
+    rc += "] ";
+
+    delete user;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether errors at this level should be ignored.
+//
+bool MLog::ErrorHandlerIgnore(Int_t level)
+{
+    // The default error handler function. It prints the message on stderr and
+    // if abort is set it aborts the application.
+   if (gErrorIgnoreLevel == kUnset) {
+      R__LOCKGUARD2(gErrorMutex);
+
+      gErrorIgnoreLevel = 0;
+      if (gEnv) {
+         TString lvl = gEnv->GetValue("Root.ErrorIgnoreLevel", "Info");
+         if (!lvl.CompareTo("Info",TString::kIgnoreCase))
+            gErrorIgnoreLevel = kInfo;
+         else if (!lvl.CompareTo("Warning",TString::kIgnoreCase))
+            gErrorIgnoreLevel = kWarning;
+         else if (!lvl.CompareTo("Error",TString::kIgnoreCase))
+            gErrorIgnoreLevel = kError;
+         else if (!lvl.CompareTo("Break",TString::kIgnoreCase))
+            gErrorIgnoreLevel = kBreak;
+         else if (!lvl.CompareTo("SysError",TString::kIgnoreCase))
+            gErrorIgnoreLevel = kSysError;
+         else if (!lvl.CompareTo("Fatal",TString::kIgnoreCase))
+            gErrorIgnoreLevel = kFatal;
+      }
+   }
+
+   return level < gErrorIgnoreLevel;
+}
+
+// --------------------------------------------------------------------------
+//
+// Output the root error message to the log-stream.
+//
+void MLog::ErrorHandlerPrint(Int_t level, const char *location, const char *msg)
+{
+    R__LOCKGUARD2(gErrorMutex);
+
+    if (level >= kError)
+        gLog << "ROOT:Error";
+    else
+        if (level >= kSysError)
+            gLog << "SysError";
+        else
+            if (level >= kBreak)
+                gLog << "\n *** Break ***";
+            else
+                if (level >= kFatal)
+                    gLog << "Fatal";
+                else
+                    if (level >= kWarning)
+                        gLog << "ROOT:Warning";
+                    else
+                        if (level >= kInfo)
+                            gLog << "ROOT:Info";
+
+    if (level >= kBreak && level < kSysError)
+        gLog << ": " << msg << std::endl;
+    else
+        if (location==0 || location[0]==0)
+            gLog << ": " << msg << std::endl;
+        else
+            gLog << " in <" << location << ">: " << msg << std::endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// A new error handler using gLog instead of stderr as output.
+// It is mainly a copy of root's DefaultErrorHandler
+// (see TError.h and TError.cxx)
+//
+void MLog::ErrorHandlerCol(Int_t level, Bool_t abort, const char *location, const char *msg)
+{
+    if (ErrorHandlerIgnore(level))
+        return;
+
+    // This is a really stupid hack/workaround to suppress these
+    // annoying errors in case of a log-scale set too early
+    if (level==kError && !strcmp(location, "THistPainter::PaintInit"))
+        level=kInfo+2;
+
+    // This is a really stupid hack/workaround to suppress these
+    // annoying errors in case of 0 number of points
+    if (level==kError && !strcmp(location, "TGraphPainter::PaintGraph"))
+        level=kInfo+2;
+
+    // This is a really stupid hack/workaround to suppress these
+    // annoying errors in case of 0 number of points
+    if (level==kWarning && !strcmp(location, "Fit"))
+        level=kInfo+2;
+
+    gLog << std::flush;
+
+    const Int_t store = gLog.GetOutputLevel();
+
+    if (level >= kInfo)
+        gLog << inf;
+    if (level==kInfo+1)
+        gLog << inf2;
+    if (level==kInfo+2)
+        gLog << inf3;
+    if (level >= kWarning)
+        gLog << warn;
+    if (level >= kError)
+        gLog << err;
+
+    ErrorHandlerPrint(level, location, msg);
+
+    gLog << std::flush;
+
+    gLog.SetOutputLevel(store);
+    if (!abort)
+        return;
+
+    gLog << err << "aborting" << std::endl;
+    if (gSystem) {
+        gSystem->StackTrace();
+        gLog.SetOutputLevel(store);
+        gSystem->Abort();
+    }
+    else
+    {
+        gLog.SetOutputLevel(store);
+        ::abort();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// A new error handler using gLog instead of stderr as output.
+// It is mainly a copy of root's DefaultErrorHandler
+// (see TError.h and TError.cxx)
+//
+void MLog::ErrorHandlerAll(Int_t level, Bool_t abort, const char *location, const char *msg)
+{
+    if (ErrorHandlerIgnore(level))
+        return;
+
+    gLog << std::flush << all;
+
+    ErrorHandlerPrint(level, location, msg);
+
+    gLog << std::flush;
+    if (!abort)
+        return;
+
+    gLog << err << "aborting" << std::endl;
+    if (gSystem) {
+        gSystem->StackTrace();
+        gSystem->Abort();
+    } else
+        ::abort();
+}
+
+// --------------------------------------------------------------------------
+//
+// Redirect the root ErrorHandler (see TError.h) output to gLog.
+//
+// The diffrent types are:
+//  kColor:      Use gLog colors
+//  kBlackWhite: Use all-qualifier (as in gLog << all << endl;)
+//  kDefault:    Set back to root's default error handler
+//               (redirect output to stderr)
+//
+void MLog::RedirectErrorHandler(ELogType typ)
+{
+    switch (typ)
+    {
+    case kColor:
+        SetErrorHandler(MLog::ErrorHandlerCol);
+        break;
+    case kBlackWhite:
+        SetErrorHandler(MLog::ErrorHandlerAll);
+        break;
+    case kDefault:
+        SetErrorHandler(DefaultErrorHandler);
+    }
+}
Index: branches/Mars_McMismatchStudy/mbase/MLog.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLog.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLog.h	(revision 17960)
@@ -0,0 +1,249 @@
+/* ======================================================================== *\
+!  $Name: not supported by cvs2svn $:$Id: MLog.h,v 1.38 2008-02-24 11:37:48 tbretz Exp $
+\* ======================================================================== */
+#ifndef MARS_MLog
+#define MARS_MLog
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+#ifndef ROOT_TSystem
+#include <TSystem.h>
+#endif
+
+#include <iostream>  // base classes for MLog
+
+class MArgs;
+
+class TEnv;
+class TMutex;
+class TGTextView;
+
+class MLogPlugin;
+
+class MLog : public std::streambuf, public std::ostream, public TObject
+{
+public:
+    typedef enum _flags {
+        eStdout   = 0x001,
+        eStderr   = 0x002,
+        eFile     = 0x004,
+        eGui      = 0x008,
+        eNoColors = 0x400  //BIT(15)
+    } Flags_t;
+
+    enum ELogBits {
+        kHasChanged = BIT(14)  // if gui has changed
+    };
+
+    enum ELogType {
+        kDefault,
+        kColor,
+        kBlackWhite
+    };
+
+private:
+    enum {
+        kIsUnderlined = BIT(15)//, kIsAutoIntro = BIT(16)
+    };
+    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;
+
+    static const int fgBufferSize = 160;  // two standard lines
+
+    char        fBuffer;      //!
+    char        fBase[fgBufferSize+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
+
+    std::ofstream *fOut;      //! possible file output stream
+    Bool_t      fOutAllocated; //! flag if fout is created by MLogging
+    TGTextView *fGui;          //! Text View output
+
+    Bool_t     fIsDirectGui;  //! Pipe text directly to the GUI (for single threaded environments)
+    TString  **fGuiLines;     //! Lines to pipe to gui
+    Int_t      fNumLines;     //!
+    TString    fGuiLine;      //!
+
+#ifdef _REENTRANT
+    TMutex *fMuxGui;          //! Mutex locking access of TGListBox
+    TMutex *fMuxStream;       //! Mutex locking access to streaming
+#endif
+
+    TList *fPlugins;
+
+    void Init();
+
+    void WriteBuffer();
+    int sync();
+    int overflow(int i); // i=EOF means not a real overflow
+
+    void AllocateFile(const char *f);
+    void DeallocateFile();
+    void ReallocateFile(const char *f);
+    void CheckFlag(Flags_t chk, int flag);
+    void Output(std::ostream &out, int len);
+    void AddGuiLine(const TString& line);
+
+    // User defined error handling (see TError.h)
+    static bool ErrorHandlerIgnore(Int_t level);
+    static void ErrorHandlerPrint(Int_t level, const char *location, const char *msg);
+    static void ErrorHandlerCol(Int_t level, Bool_t abort, const char *location, const char *msg);
+    static void ErrorHandlerAll(Int_t level, Bool_t abort, const char *location, const char *msg);
+
+public:
+
+    MLog(int i=eStdout);
+    MLog(std::ofstream &out);
+    MLog(TGTextView &out);
+    MLog(const char *fname, int flag=-1);
+
+    MLog(MLog const& log) : std::ios(), std::streambuf(), std::ostream((std::streambuf*)&log), TObject()
+    {
+        fOutputLevel = log.fOutputLevel;
+        fDebugLevel  = log.fDebugLevel;
+        fDevice      = log.fDevice;
+    }
+    ~MLog();
+
+    static TString Intro();
+    static void RedirectErrorHandler(ELogType typ=kColor);
+
+    bool LockUpdate(const char *msg);
+    bool UnLockUpdate(const char *msg);
+
+    bool Lock(const char *msg="");
+    bool UnLock(const char *msg="");
+
+    void EnableDirectGui()  { fIsDirectGui = kTRUE; }
+    void DisableDirectGui() { fIsDirectGui = kFALSE; }
+    void UpdateGui();
+
+    void Underline();
+
+    void SetDebugLevel(int i)           { fDebugLevel  =  i;   }
+    int  GetDebugLevel() const          { return fDebugLevel;  }
+    void SetOutputLevel(int i)          { fOutputLevel =  i;   }
+    int  GetOutputLevel() const         { return fOutputLevel; }
+    void SetOutputDevice(int i)         { fDevice      =  i;   }
+    void EnableOutputDevice(Flags_t f)  { fDevice     |=  f;   }
+    void DisableOutputDevice(Flags_t f) { fDevice     &= ~f;   }
+    void operator=(std::ofstream &sout) { SetOutputFile(sout); }
+    void operator=(TGTextView *sout)    { SetOutputGui(sout);  }
+    //void SetAutoIntro(Bool_t b=kTRUE)   { b ? SetBit(kIsAutoIntro) : SetBit(kIsAutoIntro); }
+
+    Bool_t IsNullOutput() const { return fIsNull; }
+    Bool_t IsOutputDeviceEnabled(int i) const { return fDevice & i; }
+
+    void SetOutputGui(TGTextView *sout, int flag=-1)
+    {
+        fGui = sout;
+        CheckFlag(eGui, flag);
+    }
+
+    void SetOutputFile(std::ofstream &sout, 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 = &sout;
+        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);
+    }
+
+    std::ofstream &GetOutputFile()
+    {
+        //
+        // Get the file output stream from MLogging
+        // if no file output stream is existing yet it will be created.
+        // For the creating a C-Temporary file name is used.
+        // if the stream is created here the user must not delete it
+        //
+        // What a pitty, but it seems, that there is now way to ask
+        // an ofstream for the corresponding file name. Elsewhise
+        // I would implement a GetFileName-function, too.
+        //
+        if (!fOut)
+            ReallocateFile(NULL);
+        return *fOut;
+    }
+
+    // FIXME: Switch off colors when on....
+    void SetNullOutput(Bool_t n=kTRUE) { fIsNull = n; }
+
+    void SetNoColors(Bool_t flag=kTRUE) { flag ? SetBit(eNoColors) : ResetBit(eNoColors); }
+
+    void Setup(MArgs &arg);
+    void Usage();
+
+    void ReadEnv(const TEnv &env, TString prefix="", Bool_t print=kFALSE);
+    void WriteEnv(TEnv &env, TString prefix="", Bool_t print=kFALSE) const;
+
+    MLog &Separator(TString str="", int outlvl=0)
+    {
+        if (!str.IsNull())
+        {
+            const Int_t l = (78-str.Length())/2-3;
+            str.Prepend("={ ");
+            str.Prepend('-', l<1?1:l);
+            str.Append(" }=");
+            str.Append('-', l<1?1:l);
+        }
+        if (str.Length()<78)
+            str.Append('-', 78-str.Length());
+
+        const int save = fOutputLevel;
+        SetOutputLevel(outlvl);
+        (*this) << str << std::endl;
+        fOutputLevel = save;
+
+        return *this;
+    }
+
+    void AddPlugin(MLogPlugin *plug);
+
+    ClassDef(MLog, 0) // This is what we call 'The logging system'
+};
+
+//
+// This is the definition of a global output stream, which by
+// default pipes all output to the stdout
+//
+R__EXTERN MLog gLog;
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MLogHtml.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogHtml.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogHtml.cc	(revision 17960)
@@ -0,0 +1,142 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MLogHtml
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MLogHtml.h"
+
+#include <string.h>  // necessary for Fedora core 2 with kernel 2.6.9-1.667 #1 and gcc 3.4.2
+#include <errno.h>   // necessary for Fedora core 2 with kernel 2.6.9-1.667 #1 and gcc 3.4.2
+
+#include <fstream>  // ofstream
+#include <iostream> // cout
+
+#include "MTime.h"
+
+ClassImp(MLogHtml);
+
+using namespace std;
+
+MLogHtml::MLogHtml(const char *name) : fUnderline(0), fColor(-1)
+{
+    fOut = new ofstream(name);
+    if (!*fOut)
+    {
+        delete fOut;
+        fOut = NULL;
+
+        cerr << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return;
+    }
+
+    // switch off buffering
+    fOut->rdbuf()->pubsetbuf(0,0);
+
+    MTime time;
+    time.Now();
+
+    *fOut << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" << endl;
+    *fOut << endl;
+    *fOut << "<html>" << endl;
+    *fOut << "<head>" << endl;
+    *fOut << "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" << endl;
+    *fOut << "    <meta name=\"Author\" content=\"Mars-MLogHtml" << MARSVER << "\">" << endl;
+    *fOut << "    <title>MARS - Logging, created " << time << "</title>" << endl;
+    *fOut << "</head>" << endl;
+    *fOut << endl;
+    *fOut << "<pre>" << endl;
+    //*fOut << "<body background=\"background.gif" text="#000000" bgcolor="#000099" link="#1122FF" vlink="#8888FF" alink="#FF0000">
+}
+
+MLogHtml::~MLogHtml()
+{
+    if (!fOut)
+        return;
+
+    *fOut << "</font>" << endl;
+    *fOut << "</pre>" << endl;
+    *fOut << endl;
+    *fOut << "</html>" << endl;
+
+    delete fOut;
+}
+
+void MLogHtml::Underline()
+{
+    if (!fOut)
+        return;
+
+    *fOut << "<u>";
+    fUnderline = kTRUE;
+}
+
+void MLogHtml::SetColor(Int_t col)
+{
+    if (!fOut)
+        return;
+
+    if (fColor>0 && fColor!=col)
+        *fOut << "</font>";
+
+    if (fColor==col)
+        return;
+
+    switch (col)
+    {
+    case 0:  break;
+    case 1:  *fOut << "<font color='maroon'>";  break;  // err
+    case 2:  *fOut << "<font color='#FF6600'>"; break;  // warn (olive?)
+    case 3:                                             // inf
+    case 4:                                             // inf2
+    case 5:  *fOut << "<font color='green'>";   break;  // inf3
+    default: *fOut << "<font color='navy'>";    break;  // all others (dbg)
+    }
+
+    fColor=col;
+}
+
+void MLogHtml::WriteBuffer(const char *str, int len)
+{
+    if (!fOut)
+    {
+        cout.write(str, len);
+        return;
+    }
+
+    TString txt(str, len);
+
+    txt.ReplaceAll(">", "&gt;");
+    txt.ReplaceAll("<", "&lt;");
+
+    fOut->write(txt.Data(), txt.Length());
+    if (fUnderline)
+    {
+        *fOut << "</u>";
+        fUnderline = kFALSE;
+    }
+}
Index: branches/Mars_McMismatchStudy/mbase/MLogHtml.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogHtml.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogHtml.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MLogHtml
+#define MARS_MLogHtml
+
+#ifndef MARS_MLogPlugin
+#include "MLogPlugin.h"
+#endif
+
+class MLogHtml : public MLogPlugin
+{
+private:
+    std::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: branches/Mars_McMismatchStudy/mbase/MLogManip.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogManip.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogManip.cc	(revision 17960)
@@ -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 "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: branches/Mars_McMismatchStudy/mbase/MLogManip.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogManip.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogManip.h	(revision 17960)
@@ -0,0 +1,95 @@
+#ifndef MARS_MLogManip
+#define MARS_MLogManip
+
+#include <iomanip>
+
+#ifndef MARS_MLog
+#include "MLog.h"
+#endif
+
+// --------------------- simple manipulators -----------------------
+
+enum MLogManip {
+    underline
+};
+
+inline std::ostream &operator<<(std::ostream &lout, MLogManip)
+{
+    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 inf2 = { 4 }; // use this for informations (green)
+const _Debug inf3 = { 5 }; // use this for informations (green)
+const _Debug dbg  = { 6 }; // 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: branches/Mars_McMismatchStudy/mbase/MLogPlugin.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogPlugin.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogPlugin.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MLogPlugin.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogPlugin.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogPlugin.h	(revision 17960)
@@ -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) { }
+    virtual void Underline() { }
+    virtual void WriteBuffer(const char *str, int len) = 0;
+
+    ClassDef(MLogPlugin, 0) // Base for a logger plugin
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MLogo.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogo.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogo.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MLogo.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLogo.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLogo.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MLut.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLut.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLut.cc	(revision 17960)
@@ -0,0 +1,416 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MLut
+//
+// This is a simple and easy-to-use implementation of a look-up table with
+// rows of different lengths.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MLut.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <stdlib.h>  // atoi (Ubuntu 8.10)
+
+#include <TRegexp.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayI.h"
+
+ClassImp(MLut);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Get the i-th entry in the routing table. Note, that i is not
+// range checked, but for any valid i a valid MArrayI is returned.
+//
+const MArrayI &MLut::GetRow(UInt_t i) const
+{
+    return *static_cast<MArrayI*>(UncheckedAt(i));
+}
+
+void MLut::Delete(Option_t *option)
+{
+    TObjArray::Delete(option);
+
+    fMaxEntries = 0;
+    fMinEntries = 0;
+
+    fMaxIndex = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if it is a default lut which would just map every entry to itself
+// An empty Lut is a default column
+//
+Bool_t MLut::IsDefaultCol() const
+{
+    if (IsEmpty())
+        return kTRUE;
+
+    if (!HasConstantLength() || fMaxEntries!=1)
+        return kFALSE;
+
+    // Loop over all rows
+    for (Int_t y=0; y<GetEntriesFast(); y++)
+        if (GetRow(y)[0]!=y)
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a default lut which just maps n-entris to themself
+//
+void MLut::SetDefaultCol(UInt_t n)
+{
+    Delete();
+
+    for (UInt_t y=0; y<n; y++)
+    {
+
+        MArrayI &idx = *new MArrayI(1);
+        idx[0] = y;
+        Add(&idx);
+    }
+
+    fMinEntries = 1;
+    fMaxEntries = 1;
+
+    fMaxIndex = n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if it is a default lut which would just map all entries to one.
+// An empty Lut is a default row
+//
+Bool_t MLut::IsDefaultRow() const
+{
+    if (IsEmpty())
+        return kTRUE;
+
+    if (GetEntriesFast()!=1)
+        return kFALSE;
+
+    const MArrayI &idx = GetRow(0);
+
+    // Loop over all rows
+    for (UInt_t x=0; x<idx.GetSize(); x++)
+        if (UInt_t(idx[x])!=x)
+            return kFALSE;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Setup a default lut which maps all n-entris to one
+//
+void MLut::SetDefaultRow(UInt_t n)
+{
+    Delete();
+
+    MArrayI &idx = *new MArrayI(n);
+
+    for (UInt_t y=0; y<n; y++)
+        idx[y] = y;
+
+    Add(&idx);
+
+    fMinEntries = n;
+    fMaxEntries = n;
+
+    fMaxIndex = n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the inverse lut of the current lut. The user is responsible
+// of deleting the allocated and returned MLut.
+//
+// For an example see Inverse()
+//
+MLut *MLut::GetInverse(Bool_t uniq) const
+{
+    MLut *lut = new MLut;
+    lut->SetInverse(*this, uniq);
+    return lut;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set this to the inverse lut of the given argument.
+//
+// For an example see Inverse()
+//
+void MLut::SetInverse(const MLut &lut, Bool_t uniq)
+{
+    if (&lut==this)
+    {
+        Invert(uniq);
+        return;
+    }
+
+    // Delete the current lut
+    Delete();
+
+    // Add as many MArrayI as needed
+    for (Int_t i=0; i<=lut.fMaxIndex; i++)
+        Add(new MArrayI);
+
+    // Get the number of rows in the given lut
+    const UInt_t num = lut.GetEntriesFast();
+
+    // Loop over all rows
+    for (UInt_t y=0; y<num; y++)
+    {
+        // Get the y-th row
+        const MArrayI &arr = lut.GetRow(y);
+
+        // Loop over all entries in this row
+        for (UInt_t x=0; x<arr.GetSize(); x++)
+        {
+            // If the entry is valid convert it to the right position in
+            // the new lut
+            if (arr[x]<0)
+                continue;
+
+            MArrayI &row = *static_cast<MArrayI*>(UncheckedAt(arr[x]));
+            if (uniq)
+                row.AddUniq(y);
+            else
+                row.Add(y);
+        }
+    }
+
+    // Reset the statistics
+    fMaxEntries = 0;
+    fMinEntries = 0;
+
+    // Loop over all new MArrayI
+    for (Int_t i=0; i<=lut.fMaxIndex; i++)
+    {
+        // Get i-th row
+        MArrayI &row = *static_cast<MArrayI*>(UncheckedAt(i));
+
+        // Sort the i-th row ascending
+        row.ReSort();
+
+        // Get the number of entries in the row
+        UInt_t n = row.GetSize();
+
+        // For convinience (to avoid empty lines in a file)
+        // add -1 to empty rows
+        if (n==0)
+        {
+            row.Add(-1);
+            n=1;
+        }
+
+        // Get the new min and max
+        if (n<fMinEntries || fMinEntries==0)
+            fMinEntries = n;
+        if (n>fMaxEntries)
+            fMaxEntries = n;
+    }
+
+    // set the new highest index in the table
+    fMaxIndex = num-1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Inverts the current lut, for example
+//
+//                         0: --
+//     0: 1 2     ---\     1: 0
+//     1: 2 3     ---/     2: 0 1
+//                         3: 1
+//
+void MLut::Invert(Bool_t uniq)
+{
+    MLut *lut = GetInverse(uniq);
+
+    // Keep fMaxIndex
+    TObjArray::Delete();
+
+    for (Int_t i=0; i<=fMaxIndex; i++)
+       Add(lut->Remove(lut->UncheckedAt(i)));
+
+    fMaxEntries = lut->fMaxEntries;
+    fMinEntries = lut->fMinEntries;
+    fMaxIndex   = lut->fMaxIndex;
+
+    delete lut;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a lut from a stream.
+//
+//  The row in the lut is just identical to the line in the stream.
+//  The entries in one line must be seperated by a whitespace.
+//  The lines can have a different number of entries.
+//
+//  Lines which first(!) character is a # are ignored (as they are not
+//  existing in the file)
+//
+Int_t MLut::ReadStream(istream &fin)
+{
+    static const TRegexp reg("[^ 1234567890]");
+
+    Delete();
+
+    Int_t l = 0;
+
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        l++;
+
+        if (line[0]=='#')
+            continue;
+
+        if (line.Contains(reg))
+        {
+            gLog << warn << "WARNING - MLut::ReadStream: Line #" << l << " contains invalid character... ignored." << endl;
+            continue;
+        }
+
+        // Split line by whitespaces
+        TObjArray *tokens = line.Tokenize(' ');
+
+        // Get number of entries in this row
+        const UInt_t n = tokens->GetEntries();
+
+        // Calculate minimum and maximum numbers of entries per row
+        if (n<fMinEntries || fMinEntries==0)
+            fMinEntries = n;
+        if (n>fMaxEntries)
+            fMaxEntries = n;
+
+        // create new entry for this row and add it to the array
+        MArrayI &idx = *new MArrayI(n);
+        Add(&idx);
+
+        // loop over all entries in this row
+        for (UInt_t i=0; i<n; i++)
+        {
+            // Convert strings to numbers
+            idx[i] = atoi((*tokens)[i]->GetName());
+
+            // Calculate maximum existing index
+            if (idx[i]>fMaxIndex)
+                fMaxIndex = idx[i];
+        }
+
+        // delete allocated TObjArray
+        delete tokens;
+    }
+
+    return GetEntries();
+}
+
+// --------------------------------------------------------------------------
+//
+// Write a lut to a stream.
+//
+Int_t MLut::WriteStream(ostream &out) const
+{
+    const Int_t n = GetEntriesFast();
+    for (int y=0; y<n; y++)
+    {
+       const MArrayI &arr = GetRow(y);
+
+       if (arr.GetSize()==0)
+           out << -1 << endl;
+
+       for (UInt_t x=0; x<arr.GetSize(); x++)
+           out << arr[x] << " ";
+       out << endl;
+    }
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a lut from a file (see also ReadStream)
+//
+Int_t MLut::ReadFile(const char *fname)
+{
+    TString expname(fname);
+    gSystem->ExpandPathName(expname);
+
+    ifstream fin(expname);
+    if (!fin)
+    {
+        gLog << err << "Cannot open file " << expname << ": ";
+        gLog << (errno!=0?strerror(errno):"Insufficient memory for decompression") << endl;
+        return -1;
+    }
+    return ReadStream(fin);
+}
+
+// --------------------------------------------------------------------------
+//
+// Write a lut to a file
+//
+Int_t MLut::WriteFile(const char *fname) const
+{
+    TString expname(fname);
+    gSystem->ExpandPathName(expname);
+
+    ofstream fout(expname);
+    if (!fout)
+    {
+        gLog << err << "Cannot open file " << expname << ": ";
+        gLog << (errno!=0?strerror(errno):"Insufficient memory for decompression") << endl;
+        return -1;
+    }
+
+    return WriteStream(fout);
+}
+
+void MLut::Print(const Option_t *o) const
+{
+    gLog << all;
+    WriteStream(gLog);
+}
Index: branches/Mars_McMismatchStudy/mbase/MLut.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MLut.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MLut.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MLut
+#define MARS_MLut
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#include <iosfwd>
+
+class MArrayI;
+
+class MLut : public TObjArray
+{
+private:
+    UInt_t fMinEntries;   // The minimum entries per row
+    UInt_t fMaxEntries;   // The maximum entries per row
+
+    Int_t  fMaxIndex;     // The maximum index fount in the lut
+
+    MLut *GetInverse(Bool_t uniq=kTRUE) const;
+
+public:
+    MLut() : fMinEntries(0), fMaxEntries(0), fMaxIndex(0) { SetOwner(); }
+
+    // TObjArry
+    void Delete(Option_t *option="");
+
+    // MLut Getter
+    const MArrayI &GetRow(UInt_t i) const;
+
+     Int_t GetNumRows() const { return GetEntriesFast(); }
+
+    UInt_t GetMaxEntries() const { return fMaxEntries; }
+     Int_t GetMaxIndex() const { return fMaxIndex; }
+
+    Bool_t HasConstantLength() const { return fMinEntries==fMaxEntries; }
+    Bool_t IsEmpty() const { return fMaxEntries==0; }
+    Bool_t IsDefaultCol() const;
+    Bool_t IsDefaultRow() const;
+
+    // MLut conversions
+    void SetInverse(const MLut &lut, Bool_t uniq=kTRUE);
+    void Invert(Bool_t uniq=kTRUE);
+
+    // Setter
+    void SetDefaultCol(UInt_t n);
+    void SetDefaultRow(UInt_t n);
+
+    // MLut I/O
+    Int_t ReadStream(std::istream &in);
+    Int_t WriteStream(std::ostream &out) const;
+
+    Int_t ReadFile(const char *fname);
+    Int_t WriteFile(const char *fname) const;
+
+    // TObject
+    void Print(const Option_t *o="") const;
+    void Print(const Option_t *o, Option_t *) const         { Print(o); }
+    void Print(const Option_t *o, Int_t) const              { Print(o); }
+    void Print(const Option_t *o, const char*, Int_t) const { Print(o); }
+    void Print(const Option_t *o, TPRegexp&, Int_t) const   { Print(o); }
+
+    ClassDef(MLut, 1) // A simple and fast easy-to-use look-up-table
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MMath.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MMath.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MMath.cc	(revision 17960)
@@ -0,0 +1,912 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMath
+//
+// Mars - Math package (eg Significances, etc)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMath.h"
+
+#include <stdlib.h> // atof (Ubuntu 8.10)
+
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TComplex
+#include <TComplex.h>
+#endif
+
+#ifndef ROOT_TRandom
+#include <TRandom.h>  // gRandom in RndmExp
+#endif
+
+#include "MString.h"
+
+//NamespaceImp(MMath);
+
+// --------------------------------------------------------------------------
+//
+// 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 s<0 or b<0 or alpha<0 or the argument of sqrt<0
+//
+// Here is some eMail written by Daniel Mazin about the meaning of the arguments:
+//
+//  > Ok. Here is my understanding:
+//  > According to Li&Ma paper (correctly cited in MMath.cc) alpha is the
+//  > scaling factor. The mathematics behind the formula 17 (and/or 9) implies
+//  > exactly this. If you scale OFF to ON first (using time or using any other
+//  > method), then you cannot use formula 17 (9) anymore. You can just try
+//  > the formula before scaling (alpha!=1) and after scaling (alpha=1), you
+//  > will see the result will be different.
+//
+//  > Here are less mathematical arguments:
+//
+//  >  1) the better background determination you have (smaller alpha) the more
+//  > significant is your excess, thus your analysis is more sensitive. If you
+//  > normalize OFF to ON first, you loose this sensitivity.
+//
+//  >  2) the normalization OFF to ON has an error, which naturally depends on
+//  > the OFF and ON. This error is propagating to the significance of your
+//  > excess if you use the Li&Ma formula 17 correctly. But if you normalize
+//  > first and use then alpha=1, the error gets lost completely, you loose
+//  > somehow the criteria of goodness of the normalization.
+//
+Double_t MMath::SignificanceLiMa(Double_t s, Double_t b, Double_t alpha)
+{
+    const Double_t sum = s+b;
+
+    if (s<0 || b<0 || alpha<=0)
+        return -1;
+
+    const Double_t l = s==0 ? 0 : s*TMath::Log(s/sum*(alpha+1)/alpha);
+    const Double_t m = b==0 ? 0 : b*TMath::Log(b/sum*(alpha+1)      );
+
+    return l+m<0 ? -1 : TMath::Sqrt((l+m)*2);
+}
+
+/*
+Double_t MMath::SignificanceLiMaErr(Double_t s, Double_t b, Double_t alpha)
+{
+    Double_t S = SignificanceLiMa(s, b, alpha);
+    if (S<0)
+        return -1;
+
+    const Double_t sum = s+b;
+
+
+    Double_t l = TMath::Log(s/sum*(alpha+1)/alpha)/TMath::Sqrt(2*S);
+    Double_t m = TMath::Log(s/sum*(alpha+1)/alpha)/TMath::Sqrt(2*S);
+
+
+    const Double_t sum = s+b;
+
+    if (s<0 || b<0 || alpha<=0)
+        return -1;
+
+    const Double_t l = s==0 ? 0 : s*TMath::Log(s/sum*(alpha+1)/alpha);
+    const Double_t m = b==0 ? 0 : b*TMath::Log(b/sum*(alpha+1)      );
+
+    return l+m<0 ? -1 : TMath::Sqrt((l+m)*2);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Calculates MMath::SignificanceLiMa(s, b, alpha). Returns 0 if the
+// calculation has failed. Otherwise the Li/Ma significance which was
+// calculated. If s<b a negative value is returned.
+//
+Double_t MMath::SignificanceLiMaSigned(Double_t s, Double_t b, Double_t alpha)
+{
+    const Double_t sig = SignificanceLiMa(s, b, alpha);
+    if (sig<=0)
+        return 0;
+
+    return TMath::Sign(sig, s-alpha*b);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Li/Ma (5) for the error of the excess, under the assumption that
+// the existance of a signal is already known. (basically signal/error
+// calculated by error propagation)
+//
+Double_t MMath::SignificanceExc(Double_t s, Double_t b, Double_t alpha)
+{
+    const Double_t error = ErrorExc(s, b, alpha);
+    if (error==0)
+        return 0;
+
+    const Double_t Ns = s - alpha*b;
+
+    return Ns/error;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the error of s-alpha*b by error propagation
+//
+Double_t MMath::ErrorExc(Double_t s, Double_t b, Double_t alpha)
+{
+    const Double_t sN = s + alpha*alpha*b;
+    return sN<0 ? 0 : TMath::Sqrt(sN);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns: 2/(sigma*sqrt(2))*integral[0,x](exp(-(x-mu)^2/(2*sigma^2)))
+//
+Double_t MMath::GaussProb(Double_t x, Double_t sigma, Double_t mean)
+{
+    if (x<mean)
+        return 0;
+
+    static const Double_t sqrt2 = TMath::Sqrt(2.);
+
+    const Double_t rc = TMath::Erf((x-mean)/(sigma*sqrt2));
+
+    if (rc<0)
+        return 0;
+    if (rc>1)
+        return 1;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns: 1 - exp((x/sigma)^2 / 2)
+//
+Double_t MMath::GaussProb2D(Double_t x, Double_t sigma)
+{
+    const Double_t xs = x/sigma;
+    return 1 - TMath::Exp(-xs*xs/2);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the "median" (at 68.3%) value of the distribution of
+// abs(a[i]-Median)
+//
+template <class Size, class Element>
+Double_t MMath::MedianDevImp(Size n, const Element *a, Double_t &med)
+{
+    static const Double_t prob = 0.682689477208650697; //MMath::GaussProb(1.0);
+
+    // Sanity check
+    if (n <= 0 || !a)
+        return 0;
+
+    // Get median of distribution
+    med = TMath::Median(n, a);
+
+    // Create the abs(a[i]-med) distribution
+    Double_t arr[n];
+    for (int i=0; i<n; i++)
+        arr[i] = (Double_t)TMath::Abs(Double_t(a[i])-med);
+
+    //return TMath::Median(n, arr)/0.67449896936; //MMath::GaussProb(x)=0.5
+
+    // Define where to divide (floor because the highest possible is n-1)
+    const Size div = TMath::FloorNint(Double_t(n)*prob);
+
+    // Calculate result
+    Double_t dev = TMath::KOrdStat(n, arr, div);
+    if (n%2 == 0)
+    {
+        dev += TMath::KOrdStat(n, arr, div-1);
+        dev /= 2;
+    }
+
+    return dev;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the "median" (at 68.3%) value of the distribution of
+// abs(a[i]-Median)
+//
+Double_t MMath::MedianDev(Long64_t n, const Short_t *a, Double_t &med)
+{
+    return MedianDevImp(n, a, med);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the "median" (at 68.3%) value of the distribution of
+// abs(a[i]-Median)
+//
+Double_t MMath::MedianDev(Long64_t n, const Int_t *a, Double_t &med)
+{
+    return MedianDevImp(n, a, med);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the "median" (at 68.3%) value of the distribution of
+// abs(a[i]-Median)
+//
+Double_t MMath::MedianDev(Long64_t n, const Float_t *a, Double_t &med)
+{
+    return MedianDevImp(n, a, med);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the "median" (at 68.3%) value of the distribution of
+// abs(a[i]-Median)
+//
+Double_t MMath::MedianDev(Long64_t n, const Double_t *a, Double_t &med)
+{
+    return MedianDevImp(n, a, med);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the "median" (at 68.3%) value of the distribution of
+// abs(a[i]-Median)
+//
+Double_t MMath::MedianDev(Long64_t n, const Long_t *a, Double_t &med)
+{
+    return MedianDevImp(n, a, med);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the "median" (at 68.3%) value of the distribution of
+// abs(a[i]-Median)
+//
+Double_t MMath::MedianDev(Long64_t n, const Long64_t *a, Double_t &med)
+{
+    return MedianDevImp(n, a, med);
+}
+
+Double_t MMath::MedianDev(Long64_t n, const Short_t  *a) { Double_t med; return MedianDevImp(n, a, med); }
+Double_t MMath::MedianDev(Long64_t n, const Int_t    *a) { Double_t med; return MedianDevImp(n, a, med); }
+Double_t MMath::MedianDev(Long64_t n, const Float_t  *a) { Double_t med; return MedianDevImp(n, a, med); }
+Double_t MMath::MedianDev(Long64_t n, const Double_t *a) { Double_t med; return MedianDevImp(n, a, med); }
+Double_t MMath::MedianDev(Long64_t n, const Long_t   *a) { Double_t med; return MedianDevImp(n, a, med); }
+Double_t MMath::MedianDev(Long64_t n, const Long64_t *a) { Double_t med; return MedianDevImp(n, a, med); }
+
+// ------------------------------------------------------------------------
+//
+// Re-sort an array. Intsead of returning an index (like TMath::Sort)
+// the array contents are sorted.
+//
+template <class Size, class Element> void MMath::ReSortImp(Size n, Element *a, Bool_t down)
+{
+    Element *cpy = new Element[n];
+    Size    *pos = new Size[n];
+
+    memcpy(cpy, a, n*sizeof(Element));
+
+    TMath::Sort(n, a, pos, down);
+
+    Size *idx = pos;
+
+    for (Element *ptr=a; ptr<a+n; ptr++)
+        *ptr = cpy[*idx++];
+
+    delete [] cpy;
+    delete [] pos;
+}
+
+void MMath::ReSort(Long64_t n, Short_t  *a, Bool_t down) { ReSortImp(n, a, down); }
+void MMath::ReSort(Long64_t n, Int_t    *a, Bool_t down) { ReSortImp(n, a, down); }
+void MMath::ReSort(Long64_t n, Float_t  *a, Bool_t down) { ReSortImp(n, a, down); }
+void MMath::ReSort(Long64_t n, Double_t *a, Bool_t down) { ReSortImp(n, a, down); }
+
+// --------------------------------------------------------------------------
+//
+// This function reduces the precision to roughly 0.5% of a Float_t by
+// changing its bit-pattern (Be carefull, in rare cases this function must
+// be adapted to different machines!). This is usefull to enforce better
+// compression by eg. gzip.
+//
+void MMath::ReducePrecision(Float_t &val)
+{
+    UInt_t &f = (UInt_t&)val;
+
+    f += 0x00004000;
+    f &= 0xffff8000;
+}
+
+// -------------------------------------------------------------------------
+//
+// Quadratic interpolation
+//
+// calculate the parameters of a parabula such that
+//    y(i) = a + b*x(i) + c*x(i)^2
+//
+// If the determinant==0 an empty TVector3 is returned.
+//
+TVector3 MMath::GetParab(const TVector3 &x, const TVector3 &y)
+{
+    const Double_t x1 = x(0);
+    const Double_t x2 = x(1);
+    const Double_t x3 = x(2);
+
+    const Double_t y1 = y(0);
+    const Double_t y2 = y(1);
+    const Double_t y3 = y(2);
+
+    const double det =
+        + x2*x3*x3 + x1*x2*x2 + x3*x1*x1
+        - x2*x1*x1 - x3*x2*x2 - x1*x3*x3;
+
+
+    if (det==0)
+        return TVector3();
+
+    const double det1 = 1.0/det;
+
+    const double ai11 = x2*x3*x3 - x3*x2*x2;
+    const double ai12 = x3*x1*x1 - x1*x3*x3;
+    const double ai13 = x1*x2*x2 - x2*x1*x1;
+
+    const double ai21 = x2*x2 - x3*x3;
+    const double ai22 = x3*x3 - x1*x1;
+    const double ai23 = x1*x1 - x2*x2;
+
+    const double ai31 = x3 - x2;
+    const double ai32 = x1 - x3;
+    const double ai33 = x2 - x1;
+
+    return TVector3((ai11*y1 + ai12*y2 + ai13*y3) * det1,
+                    (ai21*y1 + ai22*y2 + ai23*y3) * det1,
+                    (ai31*y1 + ai32*y2 + ai33*y3) * det1);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Interpolate the points with x-coordinates vx and y-coordinates vy
+// by a parabola (second order polynomial) and return the value at x.
+//
+Double_t MMath::InterpolParabLin(const TVector3 &vx, const TVector3 &vy, Double_t x)
+{
+    const TVector3 c = GetParab(vx, vy);
+    return c(0) + c(1)*x + c(2)*x*x;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Interpolate the points with x-coordinates vx=(-1,0,1) and
+// y-coordinates vy by a parabola (second order polynomial) and return
+// the value at x.
+//
+Double_t MMath::InterpolParabLin(const TVector3 &vy, Double_t x)
+{
+    const TVector3 c(vy(1), (vy(2)-vy(0))/2, vy(0)/2 - vy(1) + vy(2)/2);
+    return c(0) + c(1)*x + c(2)*x*x;
+}
+
+Double_t MMath::InterpolParabLog(const TVector3 &vx, const TVector3 &vy, Double_t x)
+{
+    const Double_t l0 = TMath::Log10(vx(0));
+    const Double_t l1 = TMath::Log10(vx(1));
+    const Double_t l2 = TMath::Log10(vx(2));
+
+    const TVector3 vx0(l0, l1, l2);
+    return InterpolParabLin(vx0, vy, TMath::Log10(x));
+}
+
+Double_t MMath::InterpolParabCos(const TVector3 &vx, const TVector3 &vy, Double_t x)
+{
+    const Double_t l0 = TMath::Cos(vx(0));
+    const Double_t l1 = TMath::Cos(vx(1));
+    const Double_t l2 = TMath::Cos(vx(2));
+
+    const TVector3 vx0(l0, l1, l2);
+    return InterpolParabLin(vx0, vy, TMath::Cos(x));
+}
+
+// --------------------------------------------------------------------------
+//
+// Analytically calculated result of a least square fit of:
+//    y = A*e^(B*x)
+// Equal weights
+//
+// It returns TArrayD(2) = { A, B };
+//
+// see: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
+//
+TArrayD MMath::LeastSqFitExpW1(Int_t n, Double_t *x, Double_t *y)
+{
+    Double_t sumxsqy  = 0;
+    Double_t sumylny  = 0;
+    Double_t sumxy    = 0;
+    Double_t sumy     = 0;
+    Double_t sumxylny = 0;
+    for (int i=0; i<n; i++)
+    {
+        sumylny  += y[i]*TMath::Log(y[i]);
+        sumxy    += x[i]*y[i];
+        sumxsqy  += x[i]*x[i]*y[i];
+        sumxylny += x[i]*y[i]*TMath::Log(y[i]);
+        sumy     += y[i];
+    }
+
+    const Double_t dev = sumy*sumxsqy - sumxy*sumxy;
+
+    const Double_t a = (sumxsqy*sumylny - sumxy*sumxylny)/dev;
+    const Double_t b = (sumy*sumxylny - sumxy*sumylny)/dev;
+
+    TArrayD rc(2);
+    rc[0] = TMath::Exp(a);
+    rc[1] = b;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Analytically calculated result of a least square fit of:
+//    y = A*e^(B*x)
+// Greater weights to smaller values
+//
+// It returns TArrayD(2) = { A, B };
+//
+// see: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
+//
+TArrayD MMath::LeastSqFitExp(Int_t n, Double_t *x, Double_t *y)
+{
+    // -------- Greater weights to smaller values ---------
+    Double_t sumlny  = 0;
+    Double_t sumxlny = 0;
+    Double_t sumxsq  = 0;
+    Double_t sumx    = 0;
+    for (int i=0; i<n; i++)
+    {
+        sumlny  += TMath::Log(y[i]);
+        sumxlny += x[i]*TMath::Log(y[i]);
+
+        sumxsq  += x[i]*x[i];
+        sumx    += x[i];
+    }
+
+    const Double_t dev = n*sumxsq-sumx*sumx;
+
+    const Double_t a = (sumlny*sumxsq - sumx*sumxlny)/dev;
+    const Double_t b = (n*sumxlny - sumx*sumlny)/dev;
+
+    TArrayD rc(2);
+    rc[0] = TMath::Exp(a);
+    rc[1] = b;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Analytically calculated result of a least square fit of:
+//    y = A+B*ln(x)
+//
+// It returns TArrayD(2) = { A, B };
+//
+// see: http://mathworld.wolfram.com/LeastSquaresFittingLogarithmic.html
+//
+TArrayD MMath::LeastSqFitLog(Int_t n, Double_t *x, Double_t *y)
+{
+    Double_t sumylnx  = 0;
+    Double_t sumy     = 0;
+    Double_t sumlnx   = 0;
+    Double_t sumlnxsq = 0;
+    for (int i=0; i<n; i++)
+    {
+        sumylnx  += y[i]*TMath::Log(x[i]);
+        sumy     += y[i];
+        sumlnx   += TMath::Log(x[i]);
+        sumlnxsq += TMath::Log(x[i])*TMath::Log(x[i]);
+    }
+
+    const Double_t b = (n*sumylnx-sumy*sumlnx)/(n*sumlnxsq-sumlnx*sumlnx);
+    const Double_t a = (sumy-b*sumlnx)/n;
+
+    TArrayD rc(2);
+    rc[0] = a;
+    rc[1] = b;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Analytically calculated result of a least square fit of:
+//    y = A*x^B
+//
+// It returns TArrayD(2) = { A, B };
+//
+// see: http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
+//
+TArrayD MMath::LeastSqFitPowerLaw(Int_t n, Double_t *x, Double_t *y)
+{
+    Double_t sumlnxlny  = 0;
+    Double_t sumlnx   = 0;
+    Double_t sumlny    = 0;
+    Double_t sumlnxsq   = 0;
+    for (int i=0; i<n; i++)
+    {
+        sumlnxlny  += TMath::Log(x[i])*TMath::Log(y[i]);
+        sumlnx     += TMath::Log(x[i]);
+        sumlny     += TMath::Log(y[i]);
+        sumlnxsq   += TMath::Log(x[i])*TMath::Log(x[i]);
+    }
+
+    const Double_t b = (n*sumlnxlny-sumlnx*sumlny)/(n*sumlnxsq-sumlnx*sumlnx);
+    const Double_t a = (sumlny-b*sumlnx)/n;
+
+    TArrayD rc(2);
+    rc[0] = TMath::Exp(a);
+    rc[1] = b;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the intersection of two lines defined by (x1;y1) and (x2;x2)
+// Returns the intersection point.
+//
+// It is assumed that the lines intersect. If there is no intersection
+// TVector2() is returned (which is not destinguishable from
+// TVector2(0,0) if the intersection is at the coordinate source)
+//
+// Formula from: http://mathworld.wolfram.com/Line-LineIntersection.html
+//
+TVector2 MMath::GetIntersectionPoint(const TVector2 &x1, const TVector2 &y1, const TVector2 &x2, const TVector2 &y2, Bool_t &rc)
+{
+    TMatrix d(2,2);
+    d[0][0] = x1.X()-y1.X();
+    d[0][1] = x2.X()-y2.X();
+    d[1][0] = x1.Y()-y1.Y();
+    d[1][1] = x2.Y()-y2.Y();
+
+    const Double_t denom = d.Determinant();
+    if (denom==0)
+    {
+        rc = false;
+        return TVector2();
+    }
+
+    rc = true;
+
+    TMatrix l1(2,2);
+    TMatrix l2(2,2);
+
+    l1[0][0] = x1.X();
+    l1[0][1] = y1.X();
+    l2[0][0] = x2.X();
+    l2[0][1] = y2.X();
+
+    l1[1][0] = x1.Y();
+    l1[1][1] = y1.Y();
+    l2[1][0] = x2.Y();
+    l2[1][1] = y2.Y();
+
+    TMatrix a(2,2);
+    a[0][0] = l1.Determinant();
+    a[0][1] = l2.Determinant();
+    a[1][0] = x1.X()-y1.X();
+    a[1][1] = x2.X()-y2.X();
+
+    const Double_t X = a.Determinant()/denom;
+
+    a[1][0] = x1.Y()-y1.Y();
+    a[1][1] = x2.Y()-y2.Y();
+
+    const Double_t Y = a.Determinant()/denom;
+
+    return TVector2(X, Y);
+}
+
+TVector2 MMath::GetIntersectionPoint(const TVector2 &x1, const TVector2 &y1, const TVector2 &x2, const TVector2 &y2)
+{
+    Bool_t rc;
+    return GetIntersectionPoint(x1, y1, x2, y2, rc);
+}
+
+// --------------------------------------------------------------------------
+//
+// Solves: x^2 + ax + b = 0;
+// Return number of solutions returned as x1, x2
+//
+Int_t MMath::SolvePol2(Double_t a, Double_t b, Double_t &x1, Double_t &x2)
+{
+    const Double_t r = a*a - 4*b;
+    if (r<0)
+        return 0;
+
+    if (r==0)
+    {
+        x1 = x2 = -a/2;
+        return 1;
+    }
+
+    const Double_t s = TMath::Sqrt(r);
+
+    x1 = (-a+s)/2;
+    x2 = (-a-s)/2;
+
+    return 2;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a helper function making the execution of SolverPol3 a bit faster
+//
+static inline Double_t ReMul(const TComplex &c1, const TComplex &th)
+{
+    const TComplex c2 = TComplex::Cos(th/3.);
+    return c1.Re() * c2.Re() - c1.Im() * c2.Im();
+}
+
+// --------------------------------------------------------------------------
+//
+// Solves: x^3 + ax^2 + bx + c = 0;
+// Return number of the real solutions, returned as z1, z2, z3
+//
+// Algorithm adapted from http://home.att.net/~srschmitt/cubizen.heml
+// Which is based on the solution given in
+//    http://mathworld.wolfram.com/CubicEquation.html
+//
+// -------------------------------------------------------------------------
+//
+// Exact solutions of cubic polynomial equations
+// by Stephen R. Schmitt Algorithm
+//
+// An exact solution of the cubic polynomial equation:
+//
+//   x^3 + a*x^2 + b*x + c = 0
+//
+// was first published by Gerolamo Cardano (1501-1576) in his treatise,
+// Ars Magna. He did not discoverer of the solution; a professor of
+// mathematics at the University of Bologna named Scipione del Ferro (ca.
+// 1465-1526) is credited as the first to find an exact solution. In the
+// years since, several improvements to the original solution have been
+// discovered. Zeno source code
+//
+// http://home.att.net/~srschmitt/cubizen.html
+//
+// % compute real or complex roots of cubic polynomial
+// function cubic( var z1, z2, z3 : real, a, b, c : real ) : real
+// 
+//     var Q, R, D, S, T : real
+//     var im, th : real
+// 
+//     Q := (3*b - a^2)/9
+//     R := (9*b*a - 27*c - 2*a^3)/54
+//     D := R^2 -Q^3                           % polynomial discriminant
+// 
+//     if (D >= 0) then                        % complex or duplicate roots
+// 
+//         S := sgn(R + sqrt(D))*abs(R + sqrt(D))^(1/3)
+//         T := sgn(R - sqrt(D))*abs(R - sqrt(D))^(1/3)
+// 
+//         z1 := -a/3 + (S + T)               % real root
+//         z2 := -a/3 - (S + T)/2             % real part of complex root
+//         z3 := -a/3 - (S + T)/2             % real part of complex root
+//         im := abs(sqrt(3)*(S - T)/2)       % complex part of root pair
+// 
+//     else                                    % distinct real roots
+// 
+//         th := arccos(R/sqrt( -Q^3))
+//         
+//         z1 := 2*sqrt(-Q)*cos(th/3) - a/3
+//         z2 := 2*sqrt(-Q)*cos((th + 2*pi)/3) - a/3
+//         z3 := 2*sqrt(-Q)*cos((th + 4*pi)/3) - a/3
+//         im := 0
+// 
+//     end if
+// 
+//     return im                               % imaginary part
+// 
+// end function
+//
+// see also http://en.wikipedia.org/wiki/Cubic_equation
+//
+Int_t MMath::SolvePol3(Double_t a, Double_t b, Double_t c,
+                       Double_t &x1, Double_t &x2, Double_t &x3)
+{
+    //    Double_t coeff[4] = { 1, a, b, c };
+    //    return TMath::RootsCubic(coeff, x1, x2, x3) ? 1 : 3;
+
+    const Double_t Q = (a*a - 3*b)/9;
+    const Double_t R = (9*b*a - 27*c - 2*a*a*a)/54;
+    const Double_t D = R*R - Q*Q*Q;             // polynomial discriminant
+
+    // ----- The single-real / duplicate-roots solution -----
+
+    // D<0:  three real roots
+    // D>0:  one real root
+    // D==0: maximum two real roots (two identical roots)
+
+    // R==0: only one unique root
+    // R!=0: two roots
+
+    if (D==0)
+    {
+        const Double_t r = MMath::Sqrt3(R);
+
+        x1 = r - a/3.;               // real root
+        if (R==0)
+            return 1;
+
+        x2 = 2*r - a/3.;               // real root
+        return 2;
+    }
+
+    if (D>0)                                    // complex or duplicate roots
+    {
+        const Double_t sqrtd = TMath::Sqrt(D);
+
+        const Double_t A = TMath::Sign(1., R)*MMath::Sqrt3(TMath::Abs(R)+sqrtd);
+
+        // The case A==0 cannot happen. This would imply D==0
+        // if (A==0)
+        // {
+        //     x1 = -a/3;
+        //     return 1;
+        // }
+
+        x1 = (A+Q/A)-a/3;
+
+        //const Double_t S = MMath::Sqrt3(R + sqrtd);
+        //const Double_t T = MMath::Sqrt3(R - sqrtd);
+        //x1 = (S+T) - a/3.;               // real root
+
+        return 1;
+
+        //z2 = (S + T)/2 - a/3.;            // real part of complex root
+        //z3 = (S + T)/2 - a/3.;            // real part of complex root
+        //im = fabs(sqrt(3)*(S - T)/2)      // complex part of root pair
+    }
+
+    // ----- The general solution with three roots ---
+
+    if (Q==0)
+        return 0;
+
+    if (Q>0) // This is here for speed reasons
+    {
+        const Double_t sqrtq = TMath::Sqrt(Q);
+        const Double_t rq    = R/TMath::Abs(Q);
+
+        const Double_t t = TMath::ACos(rq/sqrtq)/3;
+
+        static const Double_t sqrt3 = TMath::Sqrt(3.);
+
+        const Double_t sn = TMath::Sin(t)*sqrt3;
+        const Double_t cs = TMath::Cos(t);
+
+        x1 = 2*sqrtq *       cs  - a/3;
+        x2 =  -sqrtq * (sn + cs) - a/3;
+        x3 =   sqrtq * (sn - cs) - a/3;
+
+        /* --- Easier to understand but slower ---
+        const Double_t th1 = TMath::ACos(rq/sqrtq);
+        const Double_t th2 = th1 + TMath::TwoPi();
+        const Double_t th3 = th2 + TMath::TwoPi();
+
+        x1 = 2.*sqrtq * TMath::Cos(th1/3.) - a/3.;
+        x2 = 2.*sqrtq * TMath::Cos(th2/3.) - a/3.;
+        x3 = 2.*sqrtq * TMath::Cos(th3/3.) - a/3.;
+        */
+        return 3;
+    }
+
+    const TComplex sqrtq = TComplex::Sqrt(Q);
+    const Double_t rq    = R/TMath::Abs(Q);
+
+    const TComplex th1 = TComplex::ACos(rq/sqrtq);
+    const TComplex th2 = th1 + TMath::TwoPi();
+    const TComplex th3 = th2 + TMath::TwoPi();
+
+    // For ReMul, see bove
+    x1 = ReMul(2.*sqrtq, th1) - a/3.;
+    x2 = ReMul(2.*sqrtq, th2) - a/3.;
+    x3 = ReMul(2.*sqrtq, th3) - a/3.;
+
+    return 3;
+}
+
+// --------------------------------------------------------------------------
+//
+// Format a value and its error corresponding to the rules (note
+// this won't work if the error is more then eight orders smaller than
+// the value)
+//
+void MMath::Format(Double_t &v, Double_t &e)
+{
+    // Valid digits
+    Int_t i = TMath::FloorNint(TMath::Log10(v))-TMath::FloorNint(TMath::Log10(e));
+
+    // Check if error starts with 1 or 2. In this case use one
+    // more valid digit
+    TString error = MString::Format("%.0e", e);
+    if (error[0]=='1' || error[0]=='2')
+    {
+        i++;
+        error = MString::Format("%.1e", e);
+    }
+
+    const TString fmt = MString::Format("%%.%de", i);
+
+    v = MString::Format(fmt.Data(), v).Atof();
+    e = error.Atof();
+}
+
+Double_t MMath::RndmExp(Double_t tau)
+{
+    // returns an exponential deviate.
+    //
+    //          exp( -t/tau )
+
+    const Double_t x = gRandom->Rndm(); // uniform on ] 0, 1 ]
+
+    return -tau * TMath::Log(x);       // convert to exponential distribution
+}
Index: branches/Mars_McMismatchStudy/mbase/MMath.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MMath.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MMath.h	(revision 17960)
@@ -0,0 +1,95 @@
+#ifndef MARS_MMath
+#define MARS_MMath
+
+#ifndef	_MATH_H
+#include <math.h>  // Needed for darwin
+#endif
+
+#ifndef ROOT_TMath
+#include <TMath.h> // TMath is included here for convinience
+#endif
+
+class TVector2;
+class TVector3;
+class TArrayD;
+
+namespace MMath
+{
+    Double_t GaussProb(Double_t x, Double_t sigma=1, Double_t mean=0);
+    Double_t GaussProb2D(Double_t x, Double_t sigma=1);
+
+    template <class Size, class Element> void ReSortImp(Size n, Element *a, Bool_t down=kFALSE);
+    void ReSort(Long64_t n, Short_t  *a, Bool_t down=kFALSE);
+    void ReSort(Long64_t n, Int_t    *a, Bool_t down=kFALSE);
+    void ReSort(Long64_t n, Float_t  *a, Bool_t down=kFALSE);
+    void ReSort(Long64_t n, Double_t *a, Bool_t down=kFALSE);
+
+    template <class Size, class Element> Double_t MedianDevImp(Size n, const Element *a) { Double_t med; return MedianDevImp(n, a, med); }
+    template <class Size, class Element> Double_t MedianDevImp(Size n, const Element *a, Double_t &med);
+    Double_t  MedianDev(Long64_t n, const Short_t  *a, Double_t &med);
+    Double_t  MedianDev(Long64_t n, const Int_t    *a, Double_t &med);
+    Double_t  MedianDev(Long64_t n, const Float_t  *a, Double_t &med);
+    Double_t  MedianDev(Long64_t n, const Double_t *a, Double_t &med);
+    Double_t  MedianDev(Long64_t n, const Long_t   *a, Double_t &med);
+    Double_t  MedianDev(Long64_t n, const Long64_t *a, Double_t &med);
+    Double_t  MedianDev(Long64_t n, const Short_t  *a);
+    Double_t  MedianDev(Long64_t n, const Int_t    *a);
+    Double_t  MedianDev(Long64_t n, const Float_t  *a);
+    Double_t  MedianDev(Long64_t n, const Double_t *a);
+    Double_t  MedianDev(Long64_t n, const Long_t   *a);
+    Double_t  MedianDev(Long64_t n, const Long64_t *a);
+
+    Double_t Significance(Double_t s, Double_t b);
+    Double_t SignificanceSym(Double_t s, Double_t b);
+    Double_t SignificanceLiMa(Double_t s, Double_t b, Double_t alpha=1);
+    Double_t SignificanceLiMaSigned(Double_t s, Double_t b, Double_t alpha=1);
+    Double_t SignificanceExc(Double_t s, Double_t b, Double_t alpha=1);
+    Double_t ErrorExc(Double_t s, Double_t b, Double_t alpha=1);
+
+    void ReducePrecision(Float_t &val);
+
+    TVector3 GetParab(const TVector3 &x, const TVector3 &y);
+    Double_t InterpolParabLin(const TVector3 &vx, const TVector3 &vy, Double_t x);
+    Double_t InterpolParabLin(const TVector3 &vy, Double_t x);
+    Double_t InterpolParabLog(const TVector3 &vx, const TVector3 &vy, Double_t x);
+    Double_t InterpolParabCos(const TVector3 &vx, const TVector3 &vy, Double_t x);
+
+    TVector2 GetIntersectionPoint(const TVector2 &x1, const TVector2 &y1, const TVector2 &x2, const TVector2 &y2, Bool_t &rc);
+    TVector2 GetIntersectionPoint(const TVector2 &x1, const TVector2 &y1, const TVector2 &x2, const TVector2 &y2);
+
+    inline Int_t SolvePol1(Double_t c, Double_t d, Double_t &x1)
+    {
+        if (c==0)
+            return 0;
+
+        x1 = -d/c;
+        return 1;
+    }
+    Int_t SolvePol2(Double_t c, Double_t d, Double_t &x1, Double_t &x2);
+    inline Int_t SolvePol2(Double_t b, Double_t c, Double_t d, Double_t &x1, Double_t &x2)
+    {
+        return b==0 ? SolvePol1(c, d, x1) : SolvePol2(c/b, d/b, x1, x2);
+    }
+    Int_t SolvePol3(Double_t b, Double_t c, Double_t d, Double_t &x1, Double_t &x2, Double_t &x3);
+    inline Int_t SolvePol3(Double_t a, Double_t b, Double_t c, Double_t d, Double_t &x1, Double_t &x2, Double_t &x3)
+    {
+        return a==0 ? SolvePol2(b, c, d, x1, x2) : SolvePol3(b/a, c/a, d/a, x1, x2, x3);
+    }
+
+    TArrayD LeastSqFitExpW1(Int_t n, Double_t *x, Double_t *y);
+    TArrayD LeastSqFitExp(Int_t n, Double_t *x, Double_t *y);
+    TArrayD LeastSqFitLog(Int_t n, Double_t *x, Double_t *y);
+    TArrayD LeastSqFitPowerLaw(Int_t n, Double_t *x, Double_t *y);
+
+    inline Int_t ModF(Double_t dbl, Double_t &frac) { Double_t rc; frac = ::modf(dbl, &rc); return TMath::Nint(rc); }
+
+    inline Double_t Sqrt3(Double_t x) { return ::cbrt(x); }
+
+    inline Double_t Sgn(Double_t d) { return d<0 ? -1 : 1; }
+
+    void Format(Double_t &v, Double_t &e);
+
+    Double_t RndmExp(Double_t tau);
+}
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MObjLookup.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MObjLookup.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MObjLookup.cc	(revision 17960)
@@ -0,0 +1,95 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  5/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2008
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MObjLookup.h"
+
+#include <TNamed.h>
+#include <TObjString.h>
+
+ClassImp(MObjLookup);
+
+// --------------------------------------------------------------------------
+//
+// Delete all elements with kCenDelete set or all elements in case of
+// kIsOwener is set
+//
+MObjLookup::~MObjLookup()
+{
+    TExMapIter iter(&fMap);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+    Long_t key, value;
+#else
+    Long64_t key, value;
+#endif
+
+    while (iter.Next(key, value))
+    {
+        TObject *o = reinterpret_cast<TObject*>(value);
+        if (o->TestBit(kCanDelete) || TestBit(kIsOwner))
+            delete o;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a TObjString to the table
+//
+void MObjLookup::Add(Long_t key, const char *txt)
+{
+    TObject *o=new TObjString(txt);
+
+    o->SetBit(kCanDelete);
+
+    Add(key,o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a TNames to the table
+//
+void MObjLookup::Add(Long_t key, const char *name, const char *title)
+{
+    TObject *o=new TNamed(name, title);
+
+    o->SetBit(kCanDelete);
+
+    Add(key,o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the object corresponding to key. If no object is found,
+// fDefault is returned instead.
+//
+TObject *MObjLookup::GetObj(Long_t key) const
+{
+    TObject *o = reinterpret_cast<TObject*>(const_cast<TExMap&>(fMap).GetValue(key));
+    return o ? o : fDefault;
+}
Index: branches/Mars_McMismatchStudy/mbase/MObjLookup.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MObjLookup.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MObjLookup.h	(revision 17960)
@@ -0,0 +1,52 @@
+#ifndef MARS_MObjLookup
+#define MARS_MObjLookup
+
+#ifndef ROOT_TExMap
+#include <TExMap.h>
+#endif
+
+class MObjLookup : public TObject
+{
+private:
+    TExMap   fMap;
+    TObject *fDefault;
+
+    enum {
+        kIsOwner = BIT(14),
+    };
+
+public:
+    MObjLookup() : fDefault(0) { }
+    ~MObjLookup();
+
+    // Add a new object
+    void Add(Long_t key, TObject *obj) { fMap.Add(key, Long_t(obj)); }
+    void Add(Long_t key, const char *txt);
+    void Add(Long_t key, const char *name, const char *title);
+
+    // Get an object
+    TObject *GetObj(Long_t key) const;
+
+    TObject *operator[](Long_t key) const { return GetObj(key); }
+
+    const char *GetObjName(Long_t key) const { const TObject *o=GetObj(key); return o?o->GetName():NULL; }
+    const char *GetObjTitle(Long_t key) const { const TObject *o=GetObj(key); return o?o->GetTitle():NULL; }
+
+    // Number of entrues
+    Int_t GetSize() const { return fMap.GetSize(); }
+
+    // Owenership
+    void SetOnwer(Bool_t b=kTRUE) { b ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    // Default returned if no obj found (deletion is user responsibility)
+    void SetDefault(TObject *o) { fDefault = o; }
+    TObject *GetDefault() { return fDefault; }
+
+    // Direct access to the TExMap
+    const TExMap &GetMap() const { return fMap; }
+          TExMap &GetMap()       { return fMap; }
+
+    ClassDef(MObjLookup, 1) // A class providing a fast lookup table key(int)->TObject
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MParContainer.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParContainer.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParContainer.cc	(revision 17960)
@@ -0,0 +1,1198 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MParContainer
+//
+// The MParContainer class is the base class for all MARS parameter
+// containers. At the moment it is almost the same than ROOT's TNamed.
+// A TNamed contains the essential elements (name, title)
+// to identify a derived object in lists like our MParList or MTaskList.
+// The main difference is that the name and title isn't stored and read
+// to and from root files ("//!")
+//
+// MParContainer has several enhancements compared to TNamed:
+//  - GetDescriptor():        returns name and class type
+//  - GetUniqueName():        returns a unique name (used in StreamPrimitive)
+//  - SetLogStream(MLog *lg): Set a logging stream to which loggingis stored
+//  - Reset():                Reset content of class in an eventloop
+//  - IsReadyToSave():        The contents are ready to be saved to a file
+//  - IsSavedAsPrimitive():   A unique name for this instance is already
+//                            existing
+//  - SetVariables():         Can be overloaded if the containers stores
+//                            coefficients (to be used in fits)
+//  - SetDisplay():           Set a display for redirecting graphical output
+//  - GetNames():             Get Name/Title from instance and store it in
+//                            a TObjArray (used to store the names of the
+//                            conteiners in a file
+//  - SetNames():             vice versa
+//  - ReadEnv(), WriteEnv():  Function which is used for automatical setup
+//    IsEnvDefined()          from a TEnv file
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MParContainer.h"
+
+#include <ctype.h>        // isdigit
+#include <fstream>        // ofstream
+
+#include <TEnv.h>         // Env::Lookup
+#include <TClass.h>       // IsA
+#include <TObjArray.h>    // TObjArray
+#include <TBaseClass.h>   // GetClassPointer
+#include <TMethodCall.h>  // TMethodCall, AsciiWrite
+#include <TDataMember.h>  // TDataMember, AsciiWrite
+#include <TVirtualPad.h>  // gPad
+
+#include "MString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStatusDisplay.h"
+
+TList *gListOfPrimitives; // forard declaration in MParContainer.h
+
+#undef DEBUG
+//#define DEBUG
+
+ClassImp(MParContainer);
+
+using namespace std;
+
+TObjArray MParContainer::fgListMethodCall;
+
+MParContainer::MParContainer(const char *name, const char *title) :
+    fName(name), fTitle(title), fLog(&gLog), fDisplay(NULL), fReadyToSave(kFALSE)
+{
+    fgListMethodCall.SetOwner();
+}
+
+MParContainer::MParContainer(const TString &name, const TString &title) :
+    fName(name), fTitle(title), fLog(&gLog), fDisplay(NULL), fReadyToSave(kFALSE)
+{
+    fgListMethodCall.SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+//  MParContainer copy ctor
+//
+MParContainer::MParContainer(const MParContainer &named) : TObject()
+{
+    fName  = named.fName;
+    fTitle = named.fTitle;
+
+    fLog = named.fLog;
+
+    fReadyToSave = named.fReadyToSave;
+
+    fDisplay = named.fDisplay;
+}
+
+MParContainer::~MParContainer()
+{
+#ifdef DEBUG
+    if (fName.IsNull() || fName==(TString)"MTime")
+        return;
+
+    *fLog << all << "Deleting " << this << " " << GetDescriptor() << endl;
+    if (TestBit(kMustCleanup) && gROOT && gROOT->MustClean())
+    {
+        *fLog << "Recursive Remove..." << flush;
+        if (TestBit(kCanDelete))
+            *fLog << "kCanDelete..." << flush;
+        TIter Next(gROOT->GetListOfCleanups());
+        TObject *o=0;
+        while ((o=Next()))
+            *fLog << dbg << o->GetName() << " [" << o->ClassName() << "]" << endl;
+        *fLog << dbg << "Removing..." << flush;
+        gROOT->GetListOfCleanups()->RecursiveRemove(this);
+        *fLog << "Removed." << endl;
+    }
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+//  MParContainer assignment operator.
+//
+MParContainer& MParContainer::operator=(const MParContainer& rhs)
+{
+    if (this == &rhs)
+        return *this;
+
+    TObject::operator=(rhs);
+
+    fName  = rhs.fName;
+    fTitle = rhs.fTitle;
+
+    fLog = rhs.fLog;
+    fReadyToSave = rhs.fReadyToSave;
+
+    return *this;
+}
+
+// --------------------------------------------------------------------------
+//
+// Make a clone of an object using the Streamer facility.
+// If newname is specified, this will be the name of the new object
+//
+TObject *MParContainer::Clone(const char *newname) const
+{
+
+   MParContainer *named = (MParContainer*)TObject::Clone();
+   if (newname && strlen(newname)) named->SetName(newname);
+   return named;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Compare two MParContainer objects. Returns 0 when equal, -1 when this is
+//  smaller and +1 when bigger (like strcmp).
+//
+Int_t MParContainer::Compare(const TObject *obj) const
+{
+    if (this == obj) return 0;
+    return fName.CompareTo(obj->GetName());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Copy this to obj.
+//
+void MParContainer::Copy(TObject &obj)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+{
+    MParContainer &cont = (MParContainer&)obj;
+
+    TObject::Copy(obj);
+
+    cont.fName  = fName;
+    cont.fTitle = fTitle;
+
+    cont.fLog = fLog;
+    cont.fReadyToSave = fReadyToSave;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Encode MParContainer into output buffer.
+//
+void MParContainer::FillBuffer(char *&buffer)
+{
+    fName.FillBuffer(buffer);
+    fTitle.FillBuffer(buffer);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the name of the object. If the name of the object is not the
+// class name it returns the object name and in []-brackets the class name.
+//
+const TString MParContainer::GetDescriptor() const
+{
+    return GetDescriptor(*this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the name of the object. If the name of the object is not the
+// class name it returns the object name and in []-brackets the class name.
+//
+const TString MParContainer::GetDescriptor(const TObject &o)
+{
+    //
+    // Because it returns a (const char*) we cannot return a casted
+    // local TString. The pointer would - immediatly after return -
+    // point to a random memory segment, because the TString has gone.
+    //
+    return (TString)o.GetName()==o.ClassName() ? (TString)o.ClassName() :
+        MString::Format("%s [%s]", o.GetName(), o.ClassName());
+}
+
+// --------------------------------------------------------------------------
+//
+// Check down to base whether the class given in the argument
+// overwrites the function given by name.
+//
+// This function calls itself recursively. If you want to call it,
+// leave out the argument.
+//
+Bool_t MParContainer::Overwrites(const TClass *base, const TObject &obj, const char *name, TClass *cls)
+{
+    if (!cls)
+        cls = obj.IsA();
+
+    //
+    // Check whether we reached the base class MTask
+    //
+    if (cls==base)
+        return kFALSE;
+
+    //
+    // Check whether the class cls overwrites Process
+    //
+    if (cls->GetMethodAny(name))
+        return kTRUE;
+
+    //
+    // If the class itself doesn't overload it check all it's base classes
+    //
+    TBaseClass *basecls=NULL;
+    TIter NextBase(cls->GetListOfBases());
+    while ((basecls=(TBaseClass*)NextBase()))
+    {
+        if (Overwrites(base, obj, name, basecls->GetClassPointer()))
+            return kTRUE;
+    }
+
+    return kFALSE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  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;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Read an object from the current directory. If no name is given
+// the name of this object is used. The final object will have the
+// name of the object read from file.
+//
+Int_t MParContainer::Read(const char *name)
+{
+    const Int_t rc = TObject::Read(name?name:(const char*)fName);
+    if (name)
+        SetName(name);
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If you want to use Ascii-Input/-Output (eg. MWriteAsciiFile) of a
+//  container, overload this function.
+//
+void MParContainer::AsciiRead(istream &)
+{
+    *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 = const_cast<TDataMember*>(member)->GetterMethod(); //FIXME: Root
+    if (!call)
+    {
+        *fLog << warn << "Sorry, no getter method found for " << member->GetName() << endl;
+        return kFALSE;
+    }
+
+    // For debugging: out << member->GetName() << ":";
+
+    switch (call->ReturnType())
+    {
+    case TMethodCall::kLong:
+        Long_t l;
+        call->Execute((void*)this, l); // FIXME: const, root
+        out << l << " ";
+        return kTRUE;
+
+    case TMethodCall::kDouble:
+        Double_t d;
+        call->Execute((void*)this, d); // FIXME: const, root
+        out << (scale*d) << " ";
+        return kTRUE;
+
+    default:
+    //case TMethodCall::kString:
+    //case TMethodCall::kOther:
+        /* someone may want to enhance this? */
+        return kFALSE;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Write out a data member given by name to an output stream.
+//
+Bool_t MParContainer::WriteDataMember(ostream &out, const char *member, Double_t scale) const
+{
+    /*const*/ TClass *cls = IsA()->GetBaseDataMember(member);
+    if (!cls)
+        return kFALSE;
+
+    return WriteDataMember(out, cls->GetDataMember(member), scale);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Write out a data member from a given TList of TDataMembers.
+//  returns kTRUE when at least one member was successfully written
+//
+Bool_t MParContainer::WriteDataMember(ostream &out, const TList *list) const
+{
+    Bool_t rc = kFALSE;
+
+    TDataMember *data = NULL;
+
+    TIter Next(list);
+    while ((data=(TDataMember*)Next()))
+        rc |= WriteDataMember(out, data);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If you want to use Ascii-Input/-Output (eg. MWriteAsciiFile) of a
+//  container, you may overload this function. If you don't overload it
+//  the data member of a class are written to the file in the order of
+//  appearance in the class header (be more specfic: root dictionary)
+//  Only data members which are of integer (Bool_t, Int_t, ...) or
+//  floating point (Float_t, Double_t, ...) type are written.
+//  returns kTRUE when at least one member was successfully written
+//
+Bool_t MParContainer::AsciiWrite(ostream &out) const
+{
+    // *fLog << warn << "To use the the ascii output of " << GetName();
+    // *fLog << " you have to overload " << ClassName() << "::AsciiWrite." << endl;
+
+    Bool_t rc = WriteDataMember(out, IsA()->GetListOfDataMembers());
+
+    TIter NextBaseClass(IsA()->GetListOfBases());
+    TBaseClass *base;
+    while ((base = (TBaseClass*) NextBaseClass()))
+    {
+        /*const*/ TClass *cls = base->GetClassPointer();
+
+        if (!cls)
+            continue;
+
+        if (cls->GetClassVersion())
+            rc |= WriteDataMember(out, cls->GetListOfDataMembers());
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// This virtual function is called for all parameter containers which are
+// found in the parameter list automatically each time the tasklist is
+// executed.
+//
+// By overwriting this function you can invalidate the contents of a
+// container before each execution of the tasklist:
+//
+// For example:
+//   void MHillas::Reset()
+//   {
+//      fWidth = -1;
+//   }
+//
+// (While -1 is obviously a impossible value for fWidth you can immediatly
+// see - if you Print() the contents of this container - that MHillasCalc
+// has not caluclated the width in this runthrough of the tasklist)
+//
+// Overwriting MParConatiner::Reset() in your container makes it
+// unnecessary to call any Clear() or Reset() manually in your task and
+// you make sure, that you don't keep results of previous runs of your
+// tasklist by chance.
+//
+// MParContainer::Reset() itself does nothing.
+//
+void MParContainer::Reset()
+{
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the pointer to the TClass (from the root dictionary) which
+// corresponds to the class with name name.
+//
+// Make sure, that a new object of this type can be created.
+//
+// In case of failure return NULL
+//
+TClass *MParContainer::GetConstructor(const char *name) const
+{
+    //
+    // try to get class from root environment
+    //
+    TClass *cls = gROOT->GetClass(name);
+    Int_t rc = 0;
+    if (!cls)
+        rc =1;
+    else
+    {
+        if (!cls->Property())
+            rc = 5;
+        if (!cls->Size())
+            rc = 4;
+        if (!cls->IsLoaded())
+            rc = 3;
+        if (!cls->HasDefaultConstructor())
+            rc = 2;
+    }
+
+    if (!rc)
+        return cls;
+
+    *fLog << err << dbginf << GetDescriptor() << " - Cannot create new instance of class '" << name << "': ";
+    switch (rc)
+    {
+    case 1:
+        *fLog << "gROOT->GetClass() returned NULL." << endl;
+        return NULL;
+    case 2:
+        *fLog << "no default constructor." << endl;
+        return NULL;
+    case 3:
+        *fLog << "not loaded." << endl;
+        return NULL;
+    case 4:
+        *fLog << "zero size." << endl;
+        return NULL;
+    case 5:
+        *fLog << "no property." << endl;
+        return NULL;
+    }
+
+    *fLog << "rtlprmft." << endl;
+
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a new object of class 'name'. Make sure that the object
+// derives from the class base.
+//
+// In case of failure return NULL
+//
+// The caller is responsible of deleting the object!
+//
+MParContainer *MParContainer::GetNewObject(const char *name, TClass *base) const
+{
+    return base ? GetNewObject(name, base->GetName()) : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a new object of class 'name'. Make sure that the object
+// derives from the class base.
+//
+// In case of failure return NULL
+//
+// The caller is responsible of deleting the object!
+//
+MParContainer *MParContainer::GetNewObject(const char *name, const char *base) const
+{
+    TClass *cls = GetConstructor(name);
+    if (!cls || !base)
+        return NULL;
+
+    if (!cls->InheritsFrom(base))
+    {
+        *fLog << err;
+        *fLog << dbginf << GetDescriptor() << "Cannot create new instance of class '" << name << "': " << endl;
+        *fLog << "Class " << cls->GetName() << " doesn't inherit from " << base << endl;
+        return NULL;
+    }
+
+    //
+    // create the parameter container of the the given class type
+    //
+    TObject *obj = (TObject*)cls->New();
+    if (!obj)
+    {
+        *fLog << err;
+        *fLog << dbginf << GetDescriptor() << " - Cannot create new instance of class '" << name << "': " << endl;
+        *fLog << " - Class " << cls->GetName() << " has no default constructor." << endl;
+        *fLog << " - An abstract member functions of a base class is not overwritten." << endl;
+        return NULL;
+    }
+
+    return (MParContainer*)obj;
+}
+
+TMethodCall *MParContainer::GetterMethod(const char *name) const
+{
+    const TString n(name);
+    const Int_t pos1 = n.First('.');
+
+    const TString part1 = pos1<0 ? n : n(0, pos1);
+    const TString part2 = pos1<0 ? TString("") : n(pos1+1, n.Length());
+
+    TClass *cls = IsA()->GetBaseDataMember(part1);
+    if (cls)
+    {
+        TDataMember *member = cls->GetDataMember(part1);
+        if (!member)
+        {
+            *fLog << err << "Datamember '" << part1 << "' not in " << GetDescriptor() << endl;
+            return NULL;
+        }
+
+        // This handles returning references of contained objects, eg
+        // class X { TObject fO; TObject &GetO() { return fO; } };
+        if (!member->IsBasic() && !part2.IsNull())
+        {
+            cls = gROOT->GetClass(member->GetTypeName());
+            if (!cls)
+            {
+                *fLog << err << "Datamember " << part1 << " [";
+                *fLog << member->GetTypeName() << "] not in dictionary." << endl;
+                return NULL;
+            }
+            if (!cls->InheritsFrom(MParContainer::Class()))
+            {
+                *fLog << err << "Datamember " << part1 << " [";
+                *fLog << member->GetTypeName() << "] does not inherit from ";
+                *fLog << "MParContainer." << endl;
+                return NULL;
+            }
+
+            const MParContainer *sub = (MParContainer*)((ULong_t)this+member->GetOffset());
+            return sub->GetterMethod(part2);
+        }
+
+        if (member->IsaPointer())
+        {
+            *fLog << warn << "Data-member " << part1 << " is a pointer..." << endl;
+            *fLog << dbginf << "Not yet implemented!" << endl;
+            //TClass *test = gROOT->GetClass(member->GetTypeName());
+            return 0;
+        }
+
+        TMethodCall *call = member->GetterMethod();
+        if (call)
+            return call;
+    }
+
+    *fLog << inf << "No standard access for '" << part1 << "' in ";
+    *fLog << GetDescriptor() << " or one of its base classes." << endl;
+
+    TMethodCall *call = NULL;
+
+    *fLog << "Trying to find MethodCall '" << ClassName();
+    *fLog << "::" << part1 << "' instead..." << flush;
+    call = new TMethodCall(IsA(), part1, "");
+    if (call->GetMethod())
+    {
+        fgListMethodCall.Add(call);
+        *fLog << "found." << endl;
+        return call;
+    }
+    *fLog << endl;
+
+    delete call;
+
+    *fLog << "Trying to find MethodCall '" << ClassName();
+    *fLog << "::Get" << part1 << "' instead..." << flush;
+    call = new TMethodCall(IsA(), (TString)"Get"+part1, "");
+    if (call->GetMethod())
+    {
+        fgListMethodCall.Add(call);
+        *fLog << "found." << endl;
+        return call;
+    }
+    *fLog << endl;
+
+    delete call;
+
+    *fLog << err << "Sorry, no getter method found for " << part1 << endl;
+    return NULL;
+}
+
+void *MParContainer::DataMember(const char *member)
+{
+    TDataMember *m = IsA()->GetDataMember(member);
+    if (m)
+    {
+        const Long_t off = m->GetOffset();
+        if (off>0)
+            return reinterpret_cast<char*>(this)+off;
+    }
+
+    *fLog << err << "Data member '" << member << "' not found in " << GetDescriptor() << endl;
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MParContainer::SavePrimitive(ostream &out, Option_t *)
+{
+    static UInt_t uid = 0;
+
+    if (IsSavedAsPrimitive())
+        return;
+
+    SetUniqueID(uid++);
+    SetBit(kIsSavedAsPrimitive);
+
+    if (gListOfPrimitives && !gListOfPrimitives->FindObject(this))
+        gListOfPrimitives->Add(this);
+
+    StreamPrimitive(out);
+}
+
+void MParContainer::SavePrimitive(ofstream &out, Option_t *)
+{
+    SavePrimitive(static_cast<ostream&>(out));
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates the string written by SavePrimitive and returns it.
+//
+void MParContainer::StreamPrimitive(ostream &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();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if an object can be created through gROOT->GetClass(classname)
+// return the correspodning TClass or NULL if this is not possible.
+// A message containing the reason is returned in msg.
+//
+TClass *MParContainer::GetClass(const char *classname, TString &msg)
+{
+    TClass *cls = gROOT->GetClass(classname);
+    Int_t rcc = 0;
+    if (!cls)
+        rcc = 1;
+    else
+    {
+        if (!cls->Property())
+            rcc = 5;
+        if (!cls->Size())
+            rcc = 4;
+        if (!cls->IsLoaded())
+            rcc = 3;
+        if (!cls->HasDefaultConstructor())
+            rcc = 2;
+    }
+
+    // Everything is ok.
+    if (rcc==0)
+        return cls;
+
+    msg += "Cannot create instance of class '";
+    msg += classname;
+    msg += "': ";
+
+    switch (rcc)
+    {
+    case 1:
+        msg += "gROOT->GetClass() returned NULL.";
+        break;
+    case 2:
+        msg += "no default constructor.";
+        break;
+    case 3:
+        msg += "not loaded.";
+        break;
+    case 4:
+        msg += "zero size.";
+        break;
+    case 5:
+        msg += "no property.";
+        break;
+    default:
+        msg += "Unknown error.";
+        break;
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if an object can be created through gROOT->GetClass(classname)
+// return the correspodning TClass or NULL if this is not possible.
+// A message with the reason is ouput.
+//
+TClass *MParContainer::GetClass(const char *classname, MLog *log)
+{
+    TString msg;
+    TClass *cls = GetClass(classname, msg);
+
+    if (!cls && log)
+        *log << msg << endl;
+
+    return cls;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+// Return values:
+//  kTRUE:  Environment string found
+//  kFALSE: Environment string not found
+//  kERROR: Error occured, eg. environment invalid
+//
+// Overload this if you don't want to control the level of setup-string. In
+// this case ReadEnv gets called with the different possibilities, see TestEnv.
+//
+Int_t MParContainer::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (!IsEnvDefined(env, prefix, "", print))
+        return kFALSE;
+
+    *fLog << warn << "WARNING - " << fName << ": Resource " << prefix << " found, but no " << ClassName() << "::ReadEnv." << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MParContainer::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    if (!IsEnvDefined(env, prefix, "", print))
+        return kFALSE;
+
+    *fLog << warn << "WARNING - Resource " << prefix+fName << " found, but " << ClassName() << "::WriteEnv not overloaded." << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Take the prefix and call ReadEnv for:
+//   prefix.containername
+//   prefix.classname
+//   containername
+//   classname
+//
+//  The existance of an environment variable is done in this order. If
+//  ReadEnv return kTRUE the existance of the container setup is assumed and
+//  the other tests are skipped. If kFALSE is assumed the sequence is
+//  continued. In case of kERROR failing of the setup from a file is assumed.
+//
+// Overload this if you want to control the handling of level of setup-string
+// mentioned above. In this case ReadEnv gets never called if you don't call
+// it explicitly.
+//
+Int_t MParContainer::TestEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (print)
+        *fLog << all << "Testing Prefix+ContName: " << prefix+GetName() << endl;
+    Int_t rc = ReadEnv(env, prefix+GetName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Check For: Job4.MClassName.Varname
+    if (print)
+        *fLog << all << "Testing Prefix+ClassName: " << prefix+ClassName() << endl;
+    rc = ReadEnv(env, prefix+ClassName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Check For: ContainerName.Varname
+    if (print)
+        *fLog << all << "Testing ContName: " << GetName() << endl;
+    rc = ReadEnv(env, GetName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Check For: MClassName.Varname
+    if (print)
+        *fLog << all << "Testing ClassName: " << ClassName() << endl;
+    rc = ReadEnv(env, ClassName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Not found
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the given resource is defined. If there is a postfix, prefix
+// the postfix with a dot. Calls IsEnvDefined(env, name, print)
+//
+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);
+}
+
+// --------------------------------------------------------------------------
+//
+// If print==kTRUE print information about what's going on. This is necessary
+// to debug parsing of resource files. Check if a resource "name" is defined
+// and return kFALSE/kTRUE depending on the result.
+//
+Bool_t MParContainer::IsEnvDefined(const TEnv &env, TString name, Bool_t print) const
+{
+    if (print)
+        *fLog << all << GetDescriptor() << " - " << name << "... " << flush;
+
+    if (!const_cast<TEnv&>(env).Defined(name))
+    {
+        if (print)
+            *fLog << "not found." << endl;
+        return kFALSE;
+    }
+
+    if (print)
+        *fLog << "found." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the resource prefix+"."+postfix from env or deftl if not available.
+// If prefix IsNull search for postfix only.
+//
+Int_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, TString postfix, Int_t dflt) const
+{
+    return GetEnvValue(env, prefix.IsNull()?postfix:(prefix+"."+postfix), dflt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the resource prefix+"."+postfix from env or deftl if not available.
+// If prefix IsNull search for postfix only.
+//
+Double_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, TString postfix, Double_t dflt) const
+{
+    return GetEnvValue(env, prefix.IsNull()?postfix:(prefix+"."+postfix), dflt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the resource prefix+"."+postfix from env or deftl if not available.
+// If prefix IsNull search for postfix only.
+//
+const char *MParContainer::GetEnvValue(const TEnv &env, TString prefix, TString postfix, const char *dflt) const
+{
+    return GetEnvValue(env, prefix.IsNull()?postfix:(prefix+"."+postfix), dflt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the resource prefix from env or deftl if not available.
+//
+Int_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, Int_t dflt) const
+{
+    return const_cast<TEnv&>(env).GetValue(prefix, dflt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the resource prefix from env or deftl if not available.
+//
+Double_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, Double_t dflt) const
+{
+    return const_cast<TEnv&>(env).GetValue(prefix, dflt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the resource prefix from env or deftl if not available.
+//
+const char *MParContainer::GetEnvValue(const TEnv &env, TString prefix, const char *dflt) const
+{
+    return const_cast<TEnv&>(env).GetValue(prefix, dflt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the resource prefix+"."+postfix. If it is not available or
+// prefix IsNull check for the more common resource postfix. If none
+// is found return the default.
+//
+template <class T>
+T MParContainer::GetEnvValue2Imp(const TEnv &env, const TString &prefix, const TString &postfix, T dftl, Bool_t print) const
+{
+    // Check for a dedicated resource (prefix.postfix) first
+    if (!prefix.IsNull())
+    {
+        if (IsEnvDefined(env, prefix, postfix, print))
+            return GetEnvValue(env, prefix, postfix, dftl);
+    }
+
+    // check for a general resource (postfix)
+    if (IsEnvDefined(env, postfix, print))
+        return GetEnvValue(env, postfix, dftl);
+
+    // return default
+    return dftl;
+}
+
+// --------------------------------------------------------------------------
+//
+// see template GetEnvValue2Imp
+//
+const char *MParContainer::GetEnvValue2(const TEnv &env, const TString &prefix, const TString &postfix, const char *dftl, Bool_t print) const
+{
+    return GetEnvValue2Imp(env, prefix, postfix, dftl, print);
+}
+
+// --------------------------------------------------------------------------
+//
+// see template GetEnvValue2Imp
+//
+Int_t MParContainer::GetEnvValue2(const TEnv &env, const TString &prefix, const TString &postfix, Int_t dftl, Bool_t print) const
+{
+    return GetEnvValue2Imp(env, prefix, postfix, dftl, print);
+}
+
+// --------------------------------------------------------------------------
+//
+// see template GetEnvValue2Imp
+//
+Double_t MParContainer::GetEnvValue2(const TEnv &env, const TString &prefix, const TString &postfix, Double_t dftl, Bool_t print) const
+{
+    return GetEnvValue2Imp(env, prefix, postfix, dftl, print);
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a wrapper which checks the resource file for an id containing
+// a %d with different numbers of leading zeros (1 to 8).
+//
+// If athe entries in the resource file are not unambiguous a warning
+// is printed.
+//
+TString MParContainer::GetEnvValue3(const TEnv &env, const TString &prefix, TString id, UInt_t num) const
+{
+    id.ReplaceAll("%d", "%%0%dd");
+
+    TString rc;
+    for (int i=1; i<9; i++)
+    {
+        const TString form = MString::Format(id.Data(), i);
+        const TString res  = MString::Format(form.Data(), num);
+
+        const TString str  = GetEnvValue2(env, prefix, res, "");
+
+        if (str.IsNull())
+            continue;
+
+        if (rc.IsNull())
+            rc = str;
+        else
+            *fLog << warn << "Entry " << res << " ambigous (was also found with less leading zeros)... ignored." << endl;
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// If object to remove is fDisplay set fDisplay to NULL.
+// If object to remove is fLog     set fLog     to NULL.
+// Call TObject::RecursiveRemove
+//
+void MParContainer::RecursiveRemove(TObject *obj)
+{
+    if (obj==fDisplay)
+        fDisplay=NULL;
+
+    if (obj==fLog)
+        fLog=NULL;
+
+    if (fDisplay)
+        fDisplay->RecursiveRemove(obj);
+
+    if (fLog)
+        fLog->RecursiveRemove(obj);
+
+    TObject::RecursiveRemove(obj);
+}
+
Index: branches/Mars_McMismatchStudy/mbase/MParContainer.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParContainer.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParContainer.h	(revision 17960)
@@ -0,0 +1,203 @@
+#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
+{
+    friend class MParEmulated;
+private:
+    static TObjArray fgListMethodCall; //!
+
+protected:
+    TString fName;        // parameter container identifier (name)
+    TString fTitle;       // parameter container title
+
+    MLog   *fLog;         // The general log facility for this object, initialized with the global object
+
+    // This data member was added later, because for calculating the
+    // Checksum root (3.02/07) ignores ClassDef=0 all data members
+    // which are not persistent (//!) are used. To make the two
+    // class versions CheckSum-compatible (only getting rid of a
+    // warning) this member is persistent.
+    MStatusDisplay *fDisplay; //!
+
+private:
+    enum {
+        kIsSavedAsPrimitive = BIT(15)
+    };
+
+    Bool_t  fReadyToSave; // should be set to true if the contents of the container is changed somehow
+
+    TClass *GetConstructor(const char *name) const;
+
+public:
+    enum {
+        kEnableGraphicalOutput = BIT(16)
+    };
+
+    MParContainer(const char *name="", const char *title="");
+    MParContainer(const TString &name, const TString &title);
+    MParContainer(const MParContainer &named);
+    MParContainer& operator=(const MParContainer& rhs);
+    virtual ~MParContainer();
+
+    virtual TObject    *Clone(const char *newname="") const;
+    virtual Int_t       Compare(const TObject *obj) const;
+    virtual void        Copy(TObject &named)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+        ;
+    virtual void        FillBuffer(char *&buffer);
+
+    static const TString GetDescriptor(const TObject &o);
+
+    static Bool_t Overwrites(const TClass *base, const TObject &obj, const char *name, TClass *cls=NULL);
+
+    virtual const TString GetDescriptor() const;
+    virtual const TString GetUniqueName() const;
+    virtual const char   *GetName() const       { return fName.Data(); }
+    virtual const char   *GetTitle() const      { return fTitle.Data(); }
+    virtual ULong_t       Hash() const          { return fName.Hash(); }
+    virtual Bool_t        IsSortable() const    { return kTRUE; }
+
+    virtual void   SetName(const char *name); // *MENU*
+    virtual void   SetObject(const char *name, const char *title);
+    virtual void   SetTitle(const char *title=""); // *MENU*
+    virtual void   ls(Option_t *option="") const;
+    virtual void   Print(Option_t *option="") const;
+    virtual Int_t  Sizeof() const;
+    virtual void   SavePrimitive(std::ostream &out, Option_t *o="");
+    virtual void   SavePrimitive(std::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; }
+
+    virtual void StreamPrimitive(std::ostream &out) const;
+
+    virtual TMethodCall *GetterMethod(const char *name) const;
+    virtual void        *DataMember(const char *name);
+
+    Bool_t WriteDataMember(std::ostream &out, const char *member, Double_t scale=1) const;
+    Bool_t WriteDataMember(std::ostream &out, const TDataMember *member, Double_t scale=1) const;
+    Bool_t WriteDataMember(std::ostream &out, const TList *list) const;
+
+    virtual void AsciiRead(std::istream &fin);
+    virtual Bool_t AsciiWrite(std::ostream &out) const;
+
+    Int_t Read(const char *name=NULL);
+
+    virtual void GetNames(TObjArray &arr) const;
+    virtual void SetNames(TObjArray &arr);
+
+    virtual Int_t  TestEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    virtual Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    virtual Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+    Bool_t ReadEnv(const TEnv &env, Bool_t print=kFALSE) { return ReadEnv(env, "", print); }
+    Bool_t WriteEnv(TEnv &env, Bool_t print=kFALSE) const { return WriteEnv(env, "", print); }
+
+    Bool_t IsEnvDefined(const TEnv &env, TString prefix, TString postfix, Bool_t print) const;
+    Bool_t IsEnvDefined(const TEnv &env, TString name, Bool_t print) const;
+
+    Int_t       GetEnvValue(const TEnv &env, TString prefix, TString postfix, Int_t dflt) const;
+    Double_t    GetEnvValue(const TEnv &env, TString prefix, TString postfix, Double_t dflt) const;
+    const char *GetEnvValue(const TEnv &env, TString prefix, TString postfix, const char *dflt) const;
+
+    Int_t       GetEnvValue(const TEnv &env, TString prefix, Int_t dflt) const;
+    Double_t    GetEnvValue(const TEnv &env, TString prefix, Double_t dflt) const;
+    const char *GetEnvValue(const TEnv &env, TString prefix, const char *dflt) const;
+
+    template <class T> T GetEnvValue2Imp(const TEnv &env, const TString &prefix, const TString &postfix, T dflt, Bool_t print=kFALSE) const;
+    Int_t       GetEnvValue2(const TEnv &env, const TString &prefix, const TString &postfix, Int_t dflt, Bool_t print=kFALSE) const;
+    Double_t    GetEnvValue2(const TEnv &env, const TString &prefix, const TString &postfix, Double_t dflt, Bool_t print=kFALSE) const;
+    const char *GetEnvValue2(const TEnv &env, const TString &prefix, const TString &postfix, const char *dflt, Bool_t print=kFALSE) const;
+
+    TString     GetEnvValue3(const TEnv &env, const TString &prefix, TString id, UInt_t num) const;
+
+    MParContainer *GetNewObject(const char *name, const char *base) const;
+    MParContainer *GetNewObject(const char *name, TClass *base=MParContainer::Class()) const;
+
+    static TClass *GetClass(const char *classname, TString &msg);
+    static TClass *GetClass(const char *classname, MLog *log=NULL);
+
+    void RecursiveRemove(TObject *obj);
+
+    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: branches/Mars_McMismatchStudy/mbase/MParEmulated.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParEmulated.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParEmulated.cc	(revision 17960)
@@ -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 07/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MParEmulated
+//
+// Storage Container for emulated branches
+//
+// Thanks to roots streaming mechanism simple branches can be recreated
+// from a file. To read these kind of foreign branches the root system
+// allocates memory. We can get a pointer to this memory and the
+// offsets to the data, thus allowing to use this data and ecapsulate
+// it into the MARS environment. This is done using MParEmulated.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MParEmulated.h"
+
+#include <TClass.h>   // root >=5.20/00
+#include <TPRegexp.h>
+#include <TMethodCall.h>
+#include <TStreamerElement.h>
+#include <TVirtualCollectionProxy.h>
+#if ROOT_VERSION_CODE>ROOT_VERSION(5,12,00)
+#include <TVirtualStreamerInfo.h>
+#endif
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+ClassImp(MParEmulated);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParEmulated::MParEmulated(const char *name, const char *title)
+    : fPtr(0)
+{
+    fName  = name  ? name  : "MParEmulated";
+    fTitle = title ? title : "Parameter container emulating a class";
+}
+
+// --------------------------------------------------------------------------
+//
+// The default is to print all emulated data members. If an option is
+// given it is interpreted as TPRegexp (regular expression) and only
+// data members matching this regex are printed.
+//
+void MParEmulated::Print(Option_t *o) const
+{
+    TString opt(o);
+    if (opt.IsNull())
+        opt = ".*";
+
+    TPRegexp regex(opt);
+    Print(regex, fClassName, "", 0);
+}
+
+int MParEmulated::GetPInt(TVirtualCollectionProxy *proxy, Int_t offset) const
+{
+    const TVirtualCollectionProxy::TPushPop pp(proxy, fPtr);
+    return *reinterpret_cast<int*>((char*)proxy->At(0)+offset);
+}
+Int_t MParEmulated::GetPInt_t(TVirtualCollectionProxy *proxy, Int_t offset) const
+{
+    const TVirtualCollectionProxy::TPushPop pp(proxy, fPtr);
+    return *reinterpret_cast<Int_t*>((char*)proxy->At(0)+offset);
+}
+double MParEmulated::GetPDouble(TVirtualCollectionProxy *proxy, Int_t offset) const
+{
+    const TVirtualCollectionProxy::TPushPop pp(proxy, fPtr);
+    return *reinterpret_cast<double*>((char*)proxy->At(0)+offset);
+}
+unsigned long long MParEmulated::GetPULongLong(TVirtualCollectionProxy *proxy, Int_t offset) const
+{
+    const TVirtualCollectionProxy::TPushPop pp(proxy, fPtr);
+    return *reinterpret_cast<unsigned long long*>((char*)proxy->At(0)+offset);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the class with name clsname and its corresponding streamer info
+//
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,18,00)
+TStreamerInfo *MParEmulated::GetStreamerInfo(const TString &clsname, TVirtualCollectionProxy * &proxy, Int_t &offset) const
+#else
+TVirtualStreamerInfo *MParEmulated::GetStreamerInfo(const TString &clsname, TVirtualCollectionProxy * &proxy, Int_t &offset) const
+#endif
+{
+    TClass *cls = gROOT->GetClass(clsname);
+    if (!cls)
+    {
+        *fLog << err << dbginf << "ERROR - Class " << clsname << " not in dictionary." << endl;
+        return 0;
+    }
+
+    proxy = cls->GetCollectionProxy();
+    if (proxy)
+    {
+        cls = proxy->GetValueClass();
+
+        proxy->PushProxy(fPtr);
+        // proxy->GetSize()  // Number of elements in array
+        if (proxy->At(0))
+            offset = (char*)proxy->At(0)-(char*)fPtr;
+        proxy->PopProxy();
+
+    }
+
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,18,00)
+    TStreamerInfo *info = cls->GetStreamerInfo();
+#else
+    TVirtualStreamerInfo *info = cls->GetStreamerInfo();
+#endif
+    if (!info)
+    {
+        *fLog << err << dbginf << "ERROR - No TStreamerInfo for class " << clsname << "." << endl;
+        return 0;
+    }
+
+    return info;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the method call for the given method and offset, add method to
+// MParContainer::fgListmethodCall
+//
+TMethodCall *MParEmulated::GetMethodCall(const char *get, Int_t offset, TVirtualCollectionProxy *proxy) const
+{
+    TString name(get);
+    if (proxy)
+        name.Prepend("P");
+    name.Prepend("Get");
+
+    TMethodCall *call = new TMethodCall(MParEmulated::Class(), name, proxy?MString::Format("%p,%d", proxy, offset):MString::Format("%d", offset));
+    fgListMethodCall.Add(call);
+    return call;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the getter method for the given data member. Since we have no real
+// getter methods and no real data members we have to fake the TMethodCall.
+//
+TMethodCall *MParEmulated::GetterMethod(const char *name, TString clsname, Int_t offset) const
+{
+    TVirtualCollectionProxy *proxy = 0;
+
+    // Get the streamer info for the class and the offset to the
+    // first element of a possible array
+    Int_t arroff = 0;
+
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,18,00)
+    TStreamerInfo *info = GetStreamerInfo(clsname, proxy, arroff);
+#else
+    TVirtualStreamerInfo *info = GetStreamerInfo(clsname, proxy, arroff);
+#endif
+    if (!info)
+        return 0;
+
+    const TString arg(name);
+
+    const Ssiz_t p = arg.Last('.');
+
+    const TString nam = p<0 ? arg : arg(0, p);
+
+    // Get the streamer element to the data member and
+    // and the offset from the base of the object
+    Int_t off;
+    TStreamerElement *el = info->GetStreamerElement(nam, off);
+    if (!el)
+    {
+        *fLog << err << dbginf << "ERROR - No TStreamerElement for " << nam << " [" << clsname << "]" << endl;
+        return 0;
+    }
+
+    const TString type = el->GetTypeNameBasic();
+
+    if (type=="int")
+        return GetMethodCall("Int", arroff+offset+off, proxy);
+    if (type=="Int_t")
+        return GetMethodCall("Int_t", arroff+offset+off, proxy);
+    if (type=="unisgned long long")
+        return GetMethodCall("ULongLong", arroff+offset+off, proxy);
+    if (type=="double")
+    {
+        cout << name << ": " << arroff << " " << offset << " " << off << " " << fPtr << endl;
+
+        return GetMethodCall("Double", arroff+offset+off, proxy);
+    }
+
+    if (p<0)
+    {
+        *fLog << err << dbginf << "ERROR - Variable name missing for " << nam << "." << type << " [" << clsname << "]" << endl;
+        return 0;
+    }
+
+    const TString var = arg(p+1, arg.Length());
+    return GetterMethod(var, type, arroff+offset+off);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print the requested data from our memory using the streamer info.
+//
+void MParEmulated::Print(TPRegexp &regex, TString clsname, TString prefix, Int_t offset) const
+{
+    Int_t arroff = 0;
+
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,18,00)
+    TStreamerInfo *info = GetStreamerInfo(clsname, arroff);
+#else
+    TVirtualStreamerInfo *info = GetStreamerInfo(clsname, arroff);
+#endif
+    if (!info)
+        return;
+
+    TIter Next(info->GetElements());
+    TStreamerElement *el = 0;
+    while ((el=(TStreamerElement*)Next()))
+    {
+        const TString str = prefix+el->GetName();
+
+        if (str(regex).IsNull())
+            continue;
+
+        if (el->InheritsFrom(TStreamerBasicType::Class()))
+        {
+            const TString type(el->GetTypeNameBasic());
+
+            cout << fName << (arroff?"[0]":"") << "." << str << " [" << type << "]"  << " \t";
+            if (type=="int")
+                cout << GetInt(el->GetOffset()+arroff+offset);
+            if (type=="Int_t")
+                cout << GetInt_t(el->GetOffset()+arroff+offset);
+            if (type=="double")
+                cout << GetDouble(el->GetOffset()+arroff+offset);
+            if (type=="unsigned long long")
+                cout << GetULongLong(el->GetOffset()+arroff+offset);
+
+            cout << endl;
+            continue;
+        }
+
+        if (el->InheritsFrom(TStreamerObjectAny::Class()))
+        {
+            Print(regex, el->GetTypeNameBasic(), str+".",
+                  el->GetOffset()+arroff+offset);
+            continue;
+        }
+    }
+}
Index: branches/Mars_McMismatchStudy/mbase/MParEmulated.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParEmulated.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParEmulated.h	(revision 17960)
@@ -0,0 +1,57 @@
+#ifndef MARS_MParEmulated
+#define MARS_MParEmulated
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MParEmulated : public MParContainer
+{
+private:
+    Byte_t *fPtr;
+    TString fClassName;
+
+#ifndef __CINT__
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,18,00)
+    TStreamerInfo *GetStreamerInfo(const TString &cls, TVirtualCollectionProxy* &proxy, Int_t &offset) const;
+    TStreamerInfo *GetStreamerInfo(const TString &cls, Int_t &offset) const
+    {
+        TVirtualCollectionProxy *proxy = 0; return GetStreamerInfo(cls, proxy, offset);
+    }
+#else
+    TVirtualStreamerInfo *GetStreamerInfo(const TString &cls, TVirtualCollectionProxy* &proxy, Int_t &offset) const;
+    TVirtualStreamerInfo *GetStreamerInfo(const TString &cls, Int_t &offset) const
+    {
+        TVirtualCollectionProxy *proxy = 0; return GetStreamerInfo(cls, proxy, offset);
+    }
+#endif
+#endif
+    TMethodCall *GetMethodCall(const char *get, Int_t offset, TVirtualCollectionProxy *proxy=0) const;
+
+public:
+    MParEmulated(const char *name=0, const char *title=0);
+
+    void SetClassName(const char *name) { fClassName=name; }
+
+    Byte_t **GetPtr() { return &fPtr; }
+
+    int      GetInt(Int_t offset) const { return *reinterpret_cast<int*>(fPtr+offset); }
+    Int_t    GetInt_t(Int_t offset) const { return *reinterpret_cast<Int_t*>(fPtr+offset); }
+    double   GetDouble(Int_t offset) const { return *reinterpret_cast<double*>(fPtr+offset); }
+    unsigned long long GetULongLong(Int_t offset) const { return *reinterpret_cast<unsigned long long*>(fPtr+offset); }
+
+    int      GetPInt(TVirtualCollectionProxy *proxy, Int_t offset) const;
+    Int_t    GetPInt_t(TVirtualCollectionProxy *proxy, Int_t offset) const;
+    double   GetPDouble(TVirtualCollectionProxy *proxy, Int_t offset) const;
+    unsigned long long GetPULongLong(TVirtualCollectionProxy *proxy, Int_t offset) const;
+
+    TMethodCall *GetterMethod(const char *name, TString cls, Int_t offset=0) const;
+    TMethodCall *GetterMethod(const char *name) const { return GetterMethod(name, fClassName); }
+
+    void Print(TPRegexp &regex, TString classname, TString prefix, Int_t offset) const;
+    void Print(Option_t *o=0) const;
+
+    ClassDef(MParEmulated, 0) // Storage container for emulated classes from files
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MParEnv.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParEnv.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParEnv.cc	(revision 17960)
@@ -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 1/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MParEnv
+//
+// A wrapper container which allows to set a new container from the
+// resource file. Via SetClassName you can define which type of class
+// you want to allow (the given object must inherit from it).
+//
+// For further details see MParEnv::ReadEnv
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MParEnv.h"
+
+#include <TClass.h>
+#include <TInterpreter.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MParEnv);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParEnv::MParEnv(const char *name, const char *title) : fCont(0), fClassName("MParContainer"), fIsOwner(kFALSE)
+{
+    fName  = name  ? name  : "MParEnv";
+    fTitle = title ? title : "A wrapper container which allows to set a new container from the resource file";
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fOwner if we own the instance.
+//
+MParEnv::~MParEnv()
+{
+    if (fIsOwner)
+        delete fCont;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the descriptor of this instance.
+// Calls Print() of fCont if fCont is set.
+//
+void MParEnv::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << endl;
+    if (fCont)
+        fCont->Print();
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the class name fCont must inherit from. Check if the class name
+// inherits from MParContainer.
+// In case of success returns kTRUE, kFALSE otherwise.
+//
+Bool_t MParEnv::SetClassName(const char *name)
+{
+    TClass *cls = GetClass(name, fLog);
+    if (!cls)
+        return kFALSE;
+
+    if (!cls->InheritsFrom(MParContainer::Class()))
+    {
+        *fLog << err << "ERROR - " << name << " must inherit from MParContainer." << endl;
+        return kFALSE;
+    }
+
+    fClassName = name;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes fCont if we are owner.
+// Sets fCont to 0.
+// Checks if c inherits from fClassName.
+// Sets fIsOwner to kFALSE.
+// Sets fCont to c.
+// Sets name of c to fName.
+//
+void MParEnv::SetCont(MParContainer *c)
+{
+    if (fIsOwner && fCont)
+        delete fCont;
+    fCont=0;
+
+    if (!c)
+        return;
+
+    TClass *cls = GetClass(fClassName, fLog);
+    if (!c->InheritsFrom(cls))
+    {
+        *fLog << err << "ERROR - MParEnv::SetCont: " << c->ClassName() << "  doesn't inherit from " << fClassName << endl;
+        return;
+    }
+
+    fIsOwner = kFALSE;
+
+    fCont = c;
+    fCont->SetName(fName);
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks for Class and Constructor.
+//
+// First we check for
+//
+//   MParEnv.Class: MMyContainer
+//
+// which would create a new instance of MMyContainer which must inherit from
+// fClassName. The instance is created via TObject::New()
+//
+// If this was not found we check for
+//
+//   MParEnv.Constructor: MMyContainer(14, "Hallo", "Test");
+//
+// which calls the given constructor via gInterpreter->ProcessLine. Also here
+// the result must inherit from fClassName.
+//
+// After successfull creation of the new class (or if a class was set already
+// before and not overwritten in the resource file) the container's ReadEnv
+// is called.
+//
+// WARNING: Especially in the second case oyu can do weird thing which
+//          in principle can result in crashes. Please be extra-carefull.
+//
+Int_t MParEnv::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    MParContainer *cont = 0;
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Class", print))
+    {
+        rc = kTRUE;
+        TString cls = GetEnvValue(env, prefix, "Class", "");
+        cont = GetNewObject(cls, fClassName);
+    }
+
+    if (!cont && IsEnvDefined(env, prefix, "Constructor", print))
+    {
+        rc = kTRUE;
+        if (!gInterpreter)
+        {
+            *fLog << err << "ERROR - gInterpreter==NULL." << endl;
+            return kERROR;
+        }
+
+        TString line = GetEnvValue(env, prefix, "Constructor", "");
+
+        cont = (MParContainer*)gInterpreter->ProcessLine(TString("new ")+line);
+    }
+
+    if (!rc && !fCont) // FIXME: fAllowEmpty
+        return kFALSE;
+
+    if (rc)
+    {
+        SetCont(cont);
+        if (!fCont)
+        {
+            if (cont)
+                delete cont;
+            return kERROR;
+        }
+        fIsOwner = kTRUE;
+    }
+
+    const Int_t res = fCont->ReadEnv(env, prefix, print);
+    if (res==kERROR)
+        return kERROR;
+
+    return rc ? rc : res;
+}
Index: branches/Mars_McMismatchStudy/mbase/MParEnv.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParEnv.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParEnv.h	(revision 17960)
@@ -0,0 +1,32 @@
+#ifndef MARS_MParEnv
+#define MARS_MParEnv
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MParEnv : public MParContainer
+{
+private:
+    MParContainer *fCont;  // Pointer to the paremetr container
+
+    TString fClassName;    // Name of the Class fCont must inherit from
+    Bool_t  fIsOwner;      // Flag whether MParEnv owns fCont
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MParEnv(const char *name=NULL, const char *title=NULL);
+    ~MParEnv();
+
+    void SetCont(MParContainer *c=0);
+    MParContainer *GetCont() const { return fCont; }
+
+    Bool_t SetClassName(const char *cls="MParContainer");
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MParEnv, 1) // A wrapper container which allows to set a new container from the resource file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MParList.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParList.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParList.cc	(revision 17960)
@@ -0,0 +1,1009 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MParList                                                                //
+//                                                                         //
+// This class contains a list of different parameter containers.           //
+//                                                                         //
+// A parameter container is an object which is derived from                //
+// MParContainer.                                                          //
+//                                                                         //
+// Normally a parameter container is used for data exchange between two    //
+// tasks at runtime.                                                       //
+//                                                                         //
+// You can add every parameter container (Named object) to the             //
+// instance and access it from somewhere else via its Name.                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MParList.h"
+
+#include <fstream>     // ofstream, SavePrimitive
+
+#include <TNamed.h>
+#include <TClass.h>
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIter.h"
+#include "MParEnv.h"
+#include "MTaskList.h"
+
+ClassImp(MParList);
+
+using namespace std;
+
+static const TString gsDefName  = "MParList";
+static const TString gsDefTitle = "A list of Parameter Containers";
+
+// --------------------------------------------------------------------------
+//
+//  creates an empty list
+//
+void MParList::Init(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);
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  default constructor
+//  creates an empty list
+//
+MParList::MParList(const char *name, const char *title)
+{
+    Init(name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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(const MParList &ts, const char *name, const char *title) : MParContainer()
+{
+    Init(name, title);
+
+    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=0;
+    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 access 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->R__FOR_EACH(MParContainer, SetLogStream)(log);
+    MParContainer::SetLogStream(log);
+}
+
+void MParList::SetDisplay(MStatusDisplay *d)
+{
+    fContainer->R__FOR_EACH(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;
+
+    if (cont==this)
+    {
+        *fLog << err << dbginf << "Error: It is not allowed to add a parameter list to itself." << endl;
+        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 << err << dbginf << "Error: Cannot find parameter container after which the new one should be added!" << endl;
+            return kFALSE;
+        }
+    }
+
+    if (!cont->InheritsFrom(MParContainer::Class()))
+    {
+        *fLog << err << dbginf << "Error: Cantainer MUST derive from MParContainer!" << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf3 << "Adding " << name << " to " << GetName() << "... " << flush;
+
+    cont->SetBit(kMustCleanup);
+    fContainer->Add(cont);
+    *fLog << "done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all entries which derive from MParContainer
+// of the TObjArray to the list.
+//
+void MParList::AddToList(TObjArray *list)
+{
+    //
+    //  check if the object (you want to add) exists
+    //
+    if (!list)
+        return;
+
+    TIter Next(list);
+
+    TObject *cont = NULL;
+    while ((cont=Next()))
+    {
+        MParContainer *par = dynamic_cast<MParContainer*>(cont);
+        if (par)
+            AddToList(par);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  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 << inf2 << "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);
+
+    fContainer->RecursiveRemove(obj);
+
+    // if (!obj)
+    // {
+        //        *fLog << warn << "Object not found in list..." << endl;
+    //    return;
+    //}
+
+//    *fLog << inf << "MParContainer '" << cont->GetName() << "' removed..." << endl;
+
+    if (obj && IsOwner() && !fAutodelete->FindObject(obj))
+        delete obj;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call MParContainer::RecursiveRemove
+// Call fContainer->RecursiveRemove
+//
+void MParList::RecursiveRemove(TObject *obj)
+{
+    MParContainer::RecursiveRemove(obj);
+
+    if (obj==fContainer)
+        fContainer = NULL;
+
+    if (fContainer)
+        fContainer->RecursiveRemove(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
+{
+    TObject *obj = fContainer->FindObject(name);
+    const MParEnv *env = dynamic_cast<const MParEnv*>(obj);
+    return env ? env->GetCont() : obj;
+}
+
+// --------------------------------------------------------------------------
+//
+//  check if the object is in the list or not
+//
+TObject *MParList::FindObject(const TObject *obj) const
+{
+    TObject *ret = fContainer->FindObject(obj);
+    const MParEnv *env = dynamic_cast<const MParEnv*>(ret);
+    return env ? env->GetCont() : ret;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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 = FindObject(name);
+
+    if (!obj)
+        return NULL;
+
+    if (obj->InheritsFrom(classname))
+        return obj;
+
+    *fLog << dbginf << warn << "Found object '" << name << "' doesn't ";
+    *fLog << "inherit from " << "'" << classname << "' but from '";
+    *fLog << obj->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 = FindObject(obj);
+
+    if (!nobj)
+        return NULL;
+
+    if (nobj->InheritsFrom(classname))
+        return nobj;
+
+    *fLog << dbginf << warn << "Found object '" << nobj->GetName() << "' ";
+    *fLog << "doesn't inherit from " << "'" << classname << "'" << endl;
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Searches for the tasklist tlist (default: MTaskList) and returns
+//  a task with the given name found in this list. If one of both isn't
+//  found NULL is returned
+//
+MTask *MParList::FindTask(const char *name, const char *tlist) const
+{
+    TObject *l = FindObject(tlist, "MTaskList");
+    return (MTask*)(l ? l->FindObject(name) : NULL);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find a tasklist which contains a task with name name
+//
+MTaskList *MParList::FindTaskListWithTask(const char *name) const
+{
+    TIter Next(fContainer);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        MTaskList *l1 = dynamic_cast<MTaskList*>(o);
+        if (!l1)
+            continue;
+
+        MTaskList *l2 = l1->FindTaskList(name);
+        if (l2)
+            return l2;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find a tasklist which contains a task task
+//
+MTaskList *MParList::FindTaskListWithTask(const MTask *task) const
+{
+    TIter Next(fContainer);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        MTaskList *l1 = dynamic_cast<MTaskList*>(o);
+        if (!l1)
+            continue;
+
+        MTaskList *l2 = l1->FindTaskList(task);
+        if (l2)
+            return l2;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  returns the ClassName without anything which is behind that last ';' in
+//  string.
+//
+TString MParList::GetClassName(const char *classname)
+{
+    TString cname(classname);
+    const char *semicolon = strrchr(cname, ';');
+
+    if (semicolon)
+        cname.Remove(semicolon-cname);
+
+    return cname;
+}
+
+// --------------------------------------------------------------------------
+//
+//  returns the ObjectName. It is created from a class and object name.
+//  If no object name is given the objectname is the same than the
+//  class name. Leading dots are removed from the object name
+//
+TString MParList::GetObjectName(const char *classname, const char *objname)
+{
+    TString cname(classname);
+    const char *semicolon = strrchr(cname, ';');
+
+    TString oname(objname ? objname : classname);
+
+    if (semicolon)
+    {
+        //
+        // Remove leading dots from objectname (eg. "MMcTrig;5.")
+        //
+        Int_t sz = oname.Sizeof()-2;
+
+        while (sz>=0 && oname[sz]=='.')
+            oname.Remove(sz--);
+    }
+    return oname;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object in the list.
+//  'name' is the name of the object you are searching for.
+//  If the object doesn't exist we try to create one from the
+//  dictionary. If this isn't possible NULL is returned.
+//
+//  An object which was created automatically is deleted automatically in
+//  the destructor of the parameter list, too. This means, that if an
+//  object should survive (eg. Histograms) you MUST create it by yourself
+//  and add it to the parameter list.
+//
+//  By default (you don't specify an object name) the object name is
+//  the same as the classname
+//
+//  If the classname (default classname) is of the structure
+//  "Name;something" - containing a semicolon - evarything which is
+//  after the last appearance of a semicolon is stripped to get the
+//  Name of the Class. Normally this is used to number your objects.
+//  "Name;1", "Name;2", ... If a semicolon is detected leading dots
+//  are stripped from the object-name (eg. "name;5.")
+//
+// In words: Create object of type classname and set its name to objname.
+//           If an object with objname already exists return it.
+//
+MParContainer *MParList::FindCreateObj(const char *classname, const char *objname)
+{
+    //
+    // If now object name (name of the object to identify it in the
+    // List) is given use it's classname as the objectname
+    //
+
+    //
+    // Check if the classname is a 'numbered' name (like: "MTime;2")
+    // if so strip the number from the classname.
+    //
+    // Becareful: We check for the last occurance of a ';' only and we
+    // also don't check if a number follows or something else.
+    //
+    // Rem: I use a TString to make the code more readyble and to get
+    // the new object deleted automatically
+    //
+    TString cname = GetClassName(classname);
+    TString oname = GetObjectName(classname, objname);
+
+    //
+    // Try to find a object with this object name which is already
+    // in the List. If we can find one we are done.
+    //
+    MParContainer *pcont = (MParContainer*)FindObject(oname);
+
+    if (pcont)
+    {
+        if (pcont->InheritsFrom(cname))
+            return pcont;
+
+        *fLog << err << "Warning: Object '" << oname << "' found in list doesn't inherit from " << cname << "." << endl;
+        return NULL;
+    }
+
+    //
+    // if object is not existing in the list try to create one
+    //
+    *fLog << inf2 << "Object '" << oname << "' ";
+    if (oname!=cname)
+        *fLog << "[" << cname << "] ";
+    *fLog << "not yet in " << GetName() << "... creating." << endl;
+
+    //
+    // try to get class from root environment
+    //
+    *fLog << err;
+    TClass *cls = GetClass(cname, fLog);
+    if (!cls)
+        return NULL;
+
+    if (!cls->InheritsFrom(MParContainer::Class()))
+    {
+        *fLog << err << dbginf << "Cannot create new instance of class '" << cname << "': " << endl;
+        *fLog << "Class doesn't inherit from MParContainer." << endl;
+        return NULL;
+    }
+
+    //
+    // create the parameter container of the the given class type
+    //
+    pcont = (MParContainer*)cls->New();
+    if (!pcont)
+    {
+        *fLog << err << dbginf << "Cannot create new instance of class '" << cname << "': " << endl;
+        *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 *) 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->R__FOR_EACH(MParContainer, SetReadyToSave)(flag);
+    MParContainer::SetReadyToSave(flag);
+}
+
+// --------------------------------------------------------------------------
+//
+//   Reset all containers in the list
+//
+void MParList::Reset()
+{
+    fContainer->R__FOR_EACH(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 *)
+{
+    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
+    //
+    gLog << err;
+    TClass *cls = GetClass(cname, &gLog);
+    if (!cls)
+        return list;
+
+    if (!cls->InheritsFrom(MParContainer::Class()))
+    {
+        gLog << err << dbginf << "Cannot create new instance of class '" << cname << "': " << endl;
+        gLog << "Class doesn't inherit from MParContainer." << 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(ostream &out, Option_t *)
+{
+    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;
+    }
+}
+
+void MParList::SavePrimitive(ofstream &out, Option_t *o)
+{
+    SavePrimitive(static_cast<ostream&>(out), o);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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(ostream &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->R__FOR_EACH(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->R__FOR_EACH(MParContainer, SetNames)(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Int_t MParList::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (print)
+        *fLog << all << "MParList::ReadEnv: " << prefix << endl;
+
+    MParContainer *cont = NULL;
+
+    MIter Next(fContainer);
+    while ((cont=Next()))
+    {
+        if (cont->InheritsFrom("MTaskList"))
+        {
+            if (cont->ReadEnv(env, prefix, print)==kERROR)
+                return kERROR;
+            continue;
+        }
+
+        if (cont->TestEnv(env, prefix, print)==kERROR)
+            return kERROR;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MParList::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    MParContainer *cont = NULL;
+
+    MIter Next(fContainer);
+    while ((cont=Next()))
+        if (!cont->WriteEnv(env, prefix, print))
+            return kFALSE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Can be used to create an iterator over all containers, eg:
+//   MParList plist;
+//   TIter Next(plist); // Be aware: Use a object here rather than a pointer!
+//   TObject *o=0;
+//   while ((o=Next()))
+//   {
+//       [...]
+//   }
+//
+MParList::operator TIterator*() const
+{
+    return new TOrdCollectionIter(fContainer);
+}
Index: branches/Mars_McMismatchStudy/mbase/MParList.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParList.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParList.h	(revision 17960)
@@ -0,0 +1,112 @@
+#ifndef MARS_MParList
+#define MARS_MParList
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MParList                                                                //
+//                                                                         //
+// List of parameter containers (MParContainer)                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TClass;
+class TOrdCollection;
+
+class MLog;
+class MTask;
+class MTaskList;
+
+class MParList : public MParContainer
+{
+private:
+    TOrdCollection *fContainer;	 // Collection of Parameter and Data Containers
+    TOrdCollection *fAutodelete; //! All what this list contains is deleted in the destructor
+
+    static TString GetClassName(const char *classname);
+    static TString GetObjectName(const char *classname, const char *objname);
+
+    enum { kIsOwner = BIT(14) };
+
+    void StreamPrimitive(std::ostream &out) const;
+
+    void Init(const char *name, const char *title);
+
+public:
+    enum { kDoNotReset = BIT(17), kIsProcessing = BIT(18) };
+
+    MParList(const char *name=NULL, const char *title=NULL);
+    MParList(const MParList &ts, const char *name=NULL, const char *title=NULL);
+
+    virtual ~MParList();
+
+    Bool_t AddToList(MParContainer *obj, MParContainer *where = NULL);
+    void   AddToList(TObjArray *list);
+
+    Bool_t Replace(MParContainer *obj);
+    void   Remove(MParContainer *obj);
+
+    void SetLogStream(MLog *log);
+    void SetDisplay(MStatusDisplay *d);
+
+    TObject   *FindObject(const char *name) const;
+    TObject   *FindObject(const TObject *obj) const;
+
+    TObject   *FindObject(const char *name, const char *classname) const;
+    TObject   *FindObject(const TObject *obj, const char *classname) const;
+
+    MTask     *FindTask(const char *name, const char *tlist="MTaskList") const;
+    MTaskList *FindTaskListWithTask(const char *name) const;
+    MTaskList *FindTaskListWithTask(const MTask *task) const;
+
+    MParContainer *FindCreateObj(const char *classname, const char *objname=NULL);
+
+    TObjArray FindObjectList(const char *name, UInt_t first, const UInt_t last) const;
+    TObjArray FindObjectList(const char *name, const UInt_t num) const
+    {
+        return FindObjectList(name, 0, num);
+    }
+
+    TObjArray FindCreateObjList(const char *cname, UInt_t first, const UInt_t last, const char *oname=NULL);
+    TObjArray FindCreateObjList(const char *cname, const UInt_t num, const char *oname=NULL)
+    {
+        return FindCreateObjList(cname, 0, num, oname);
+    }
+
+    static TObjArray CreateObjList(const char *cname, UInt_t first, const UInt_t last, const char *oname=NULL);
+    static TObjArray CreateObjList(const char *cname, const UInt_t num, const char *oname=NULL)
+    {
+        return CreateObjList(cname, 0, num, oname);
+    }
+
+    void RecursiveRemove(TObject *obj);
+
+    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(std::ostream &out, Option_t *o="");
+    void SavePrimitive(std::ofstream &out, Option_t *o="");
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+    operator TIterator*() const;
+
+    ClassDef(MParList, 1) // list of parameter containers (MParContainer)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MParSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParSpline.cc	(revision 17960)
@@ -0,0 +1,331 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MParSpline
+//
+//  Parameter container to store a MParSpline
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MParSpline.h"
+
+#include <TF1.h>  // MParSpline
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MSpline3.h"
+
+ClassImp(MParSpline);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MParSpline::MParSpline(const char *name, const char *title) : fSpline(0)
+{
+    fName  = name  ? name  : "MParSpline";
+    fTitle = title ? title : "Parameter container to store a MSpline3";
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Xmin of the spline. 0 if fSpline==NULL
+//
+Double_t MParSpline::GetXmin() const
+{
+    return fSpline ? fSpline->GetXmin() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Xmax of the spline. 0 if fSpline==NULL
+//
+Double_t MParSpline::GetXmax() const
+{
+    return fSpline ? fSpline->GetXmax() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the width of the range in which the spline is defined.
+//
+Double_t MParSpline::GetWidth() const
+{
+    return fSpline ? fSpline->GetXmax()-fSpline->GetXmin() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the result of the spline at val.
+// The user is reposible to make sure that fSpline is valid (!=NULL)
+//
+Double_t MParSpline::Eval(Double_t val) const
+{
+    return fSpline->Eval(val);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fSpline and set to 0.
+//
+void MParSpline::Clear(Option_t *)
+{
+    if (fSpline)
+        delete fSpline;
+    fSpline=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a TGraph from a file and return a newly allocated MSpline3.
+//
+MSpline3 *MParSpline::ReadSpline(const char *fname) const
+{
+    *fLog << inf << "Reading spline from " << fname << endl;
+
+    TGraph g(fname);
+    if (g.GetN()==0)
+    {
+        *fLog << err << "ERROR - No data points from " << fname << "." << endl;
+        return 0;
+    }
+
+    // option: b1/e1 b2/e2   (first second derivative?)
+    // option: valbeg/valend (first second derivative?)
+
+    MSpline3 *s = new MSpline3(g);
+    s->SetTitle(fname);
+
+    return s;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes a spline from min to max with n points with 1.
+//
+/*
+void MParSpline::InitUnity(UInt_t n, Float_t min, Float_t max)
+{
+    // Delete the existing spline
+    Clear();
+
+    // We need at least two points (the edges)
+    if (n<2)
+        return;
+
+    // Initialize an array with the x-values
+    const MBinning bins(n-1, min, max);
+
+    // Initialize an array with all one
+    MArrayD y(n);
+    y.Reset(1);
+
+    // Set the spline
+    fSpline = new MSpline3(bins.GetEdges(), y.GetArray(), n);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Takes the existing fSpline and multiplies it with the given spline.
+// As x-points the values from fSpline are used.
+//
+void MParSpline::Multiply(const TSpline3 &spline)
+{
+    if (!fSpline)
+    {
+        Clear();
+        // WARNING WARNING WARNING: This is a very dangerous cast!
+        fSpline = (MSpline3*)spline.Clone();
+        return;
+    }
+
+    // Initialize a TGraph with the number of knots from a TSpline
+    TGraph g(fSpline->GetNp());
+
+    // Loop over all knots
+    for (int i=0; i<fSpline->GetNp(); i++)
+    {
+        // Get th i-th knot
+        Double_t x, y;
+        fSpline->GetKnot(i, x, y);
+
+        // Multiply y by the value from the given spline
+        y *= spline.Eval(x);
+
+        // push the point "back"
+        g.SetPoint(i, x, y);
+    }
+
+    // Clear the spline and initialize a new one from the updated TGraph
+    Clear();
+    fSpline = new MSpline3(g);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes a TSpline3 with n knots x and y. Call Multiply for it.
+//
+void MParSpline::Multiply(UInt_t n, const Double_t *x, const Double_t *y)
+{
+    const TSpline3 spline("Spline", const_cast<Double_t*>(x), const_cast<Double_t*>(y), n);
+    Multiply(spline);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a Spline from a file using ReadSpline.
+// Call Multiply for it.
+//
+void MParSpline::Multiply(const char *fname)
+{
+    const MSpline3 *spline = ReadSpline(fname);
+    if (!spline)
+        return;
+
+    Multiply(*spline);
+
+    delete spline;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a spline from a file and set fSpline accfordingly.
+//
+Bool_t MParSpline::ReadFile(const char *fname)
+{
+    MSpline3 *spline = ReadSpline(fname);
+    if (!spline)
+        return kFALSE;
+
+
+    // option: b1/e1 b2/e2   (first second derivative?)
+    // option: valbeg/valend (first second derivative?)
+
+    Clear();
+    fSpline = spline;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the spline to a function. For details see MSpline3
+//
+void MParSpline::SetFunction(const TF1 &f)
+{
+    // FIXME: Use TF1 directly? (In most cases this seems to be slower)
+
+    // option: b1/e1 b2/e2   (first second derivative?)
+    // option: valbeg/valend (first second derivative?)
+
+    // if (f.GetNpar()==0)
+    // No SUPPORT
+
+    Clear();
+    fSpline = new MSpline3(f);//, fRunHeader->GetFreqSampling()/1000.);
+    fSpline->SetTitle(f.GetTitle());
+
+    // FIXME: Make a boundary condition e1b1,0,0 (First der, at Xmin and Xmax==0)
+    // FIXME: Force the spline to be 0 at Xmin and Xmax?
+}
+
+Bool_t MParSpline::SetFunction(const char *func, Int_t n, Double_t xmin, Double_t xmax)
+{
+    // FIXME: Use TF1 directly? (In most cases this seems to be slower)
+    TF1 f("f", func, xmin, xmax);
+    f.SetNpx(n);
+
+    SetFunction(f);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FileName: reflectivity.txt
+// Function.Name: exp(-(x/2)^2/2)
+// Function.Npx:   25
+// Function.Xmin:  -8
+// Function.Xmax:   8
+//
+Int_t MParSpline::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FileName", print))
+    {
+        rc = kTRUE;
+        if (!ReadFile(GetEnvValue(env, prefix, "FileName", "")))
+            return kERROR;
+    }
+
+    if (IsEnvDefined(env, prefix, "Function.Name", print))
+    {
+        rc = kTRUE;
+
+        Int_t   npx  = 25;
+        Float_t xmin = -8;
+        Float_t xmax =  8;
+        TString func = "exp(-(x/2)^2/2)";
+
+        if (IsEnvDefined(env, prefix, "Function.Npx", print))
+            npx = GetEnvValue(env, prefix, "Function.Npx", npx);
+        if (IsEnvDefined(env, prefix, "Function.Xmin", print))
+            xmin = GetEnvValue(env, prefix, "Function.Xmin", xmin);
+        if (IsEnvDefined(env, prefix, "Function.Xmax", print))
+            xmax = GetEnvValue(env, prefix, "Function.Xmax", xmax);
+
+        SetFunction(GetEnvValue(env, prefix, "Function.Name", func), npx, xmin, xmax);
+    }
+    return rc;
+}
+
+void MParSpline::Paint(Option_t *)
+{
+    fSpline->SetMarkerStyle(kFullDotMedium);
+
+    if (!fSpline->GetHistogram())
+        fSpline->Paint();
+
+    TH1 *h = fSpline->GetHistogram();
+    if (!h)
+        return;
+
+    //h->SetXTitle("t [ns]");
+    //h->SetYTitle("a.u.");
+
+    fSpline->Paint("PC");
+}
+
+void MParSpline::RecursiveRemove(TObject *obj)
+{
+    if (obj==fSpline)
+        fSpline=0;
+
+    MParContainer::RecursiveRemove(obj);
+}
Index: branches/Mars_McMismatchStudy/mbase/MParSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParSpline.h	(revision 17960)
@@ -0,0 +1,58 @@
+#ifndef MARS_MParSpline
+#define MARS_MParSpline
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TF1;       // MParSpline
+class TSpline3;
+class MSpline3;
+
+class MParSpline : public MParContainer
+{
+private:
+    MSpline3 *fSpline;   // Spline hold by this container
+
+    // MParSpline
+    MSpline3 *ReadSpline(const char *fname) const;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MParSpline(const char *name=0, const char *title=0);
+    ~MParSpline()  { Clear(); }
+
+    // MParSpline
+    const MSpline3 *GetSpline() const { return fSpline; }
+
+    Double_t GetXmin() const;
+    Double_t GetXmax() const;
+    Double_t GetWidth() const;
+
+    Bool_t IsValid() const { return fSpline ? kTRUE : kFALSE; }
+
+    Double_t Eval(Double_t val) const;
+
+    void SetFunction(const TF1 &f);
+    Bool_t SetFunction(const char *func, Int_t n, Double_t xmin, Double_t xmax);
+
+    //void InitUnity(UInt_t n, Float_t min, Float_t max);
+
+    void Multiply(const TSpline3 &spline);
+    void Multiply(UInt_t n, const Double_t *x, const Double_t *y);
+    void Multiply(const char *fname);
+
+    Bool_t ReadFile(const char *fname);
+
+    // TObject
+    void Clear(Option_t *o="");
+    void Paint(Option_t *o="");
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MParSpline, 1) // Container to hold a MSpline3
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MParameters.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParameters.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParameters.cc	(revision 17960)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 03/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MParameterD, MParameterDerr, 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.
+//
+//
+// MParameterDerr - Version 2:
+//  - inherits from MParemeterD now, where fVal comes from
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MParameters.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MParameterD);
+ClassImp(MParameterI);
+ClassImp(MParameterDerr);
+//ClassImp(MParameter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParameterD::MParameterD(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MParameterD";
+    fTitle = title ? title : "Storgare container for general parameters (double)";
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParameterDerr::MParameterDerr(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MParameterDerr";
+    fTitle = title ? title : "Storgare container for general parameters (double) and its error";
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParameterI::MParameterI(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MParameterI";
+    fTitle = title ? title : "Storgare container for general parameters (integer)";
+}
+
+// --------------------------------------------------------------------------
+//
+// Print value of container.
+//
+void MParameterD::Print(Option_t *) const
+{
+    *fLog << all << GetDescriptor() << ":  Val=" << fVal << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print value and error of container.
+//
+void MParameterDerr::Print(Option_t *) const
+{
+    *fLog << all << GetDescriptor() << ":  Val=" << GetVal() << "  Err=" << fErr << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print value of container.
+//
+void MParameterI::Print(Option_t *) const
+{
+    *fLog << all << GetDescriptor() << ":  Val=" << fVal << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// MParameterD.Val: 55.7
+//
+Int_t MParameterD::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Val", print))
+    {
+        rc = kTRUE;
+        fVal = GetEnvValue(env, prefix, "Val", fVal);
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// MParameterD.Val: 55.7
+// MParameterD.Err: 12.3
+//
+Int_t MParameterDerr::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Int_t rc = MParameterD::ReadEnv(env, prefix, print);
+    if (rc==kERROR)
+        return kERROR;
+
+    if (IsEnvDefined(env, prefix, "Err", print))
+    {
+        rc = kTRUE;
+        fErr = GetEnvValue(env, prefix, "Err", fErr);
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// MParameterD.Val: 42
+//
+Int_t MParameterI::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Val", print))
+    {
+        rc = kTRUE;
+        fVal = GetEnvValue(env, prefix, "Val", fVal);
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mbase/MParameters.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MParameters.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MParameters.h	(revision 17960)
@@ -0,0 +1,131 @@
+#ifndef MARS_MParameters
+#define MARS_MParameters
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MParameterD : public MParContainer
+{
+private:
+    Double_t fVal;
+
+protected:
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MParameterD(const char *name=NULL, const char *title=NULL);
+
+    void SetVal(Double_t v) { fVal = v; }
+    Double_t GetVal() const { return fVal; }
+
+    void Print(Option_t *o="") const;
+
+    Double_t *GetPtr() { return &fVal; }
+
+    ClassDef(MParameterD, 1) // Container to hold a generalized parameters (double)
+};
+
+class MParameterDerr : public MParameterD
+{
+private:
+    Double_t fErr;
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MParameterDerr(const char *name=NULL, const char *title=NULL);
+
+    void SetVal(Double_t v)             { MParameterD::SetVal(v); }
+    void SetVal(Double_t v, Double_t e) { SetVal(v); fErr = e; }
+    Double_t GetErr() const { return fErr; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MParameterDerr, 2) // Container to hold a generalized parameters (double) and its Error
+};
+
+class MParameterI : public MParContainer
+{
+private:
+    Int_t fVal;
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MParameterI(const char *name=NULL, const char *title=NULL);
+
+    void SetVal(Int_t v) { fVal = v; }
+    Int_t GetVal() const { return fVal; }
+
+    void Print(Option_t *o="") const;
+
+    Int_t *GetPtr() { 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: branches/Mars_McMismatchStudy/mbase/MPrint.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MPrint.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MPrint.cc	(revision 17960)
@@ -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  10/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MPrint                                                                  //
+//                                                                          //
+//  This task calls the Print() function of a parameter container, to       //
+//  print some information event by event.                                  //
+//  Overload TObject::Print()                                               //
+//                                                                          //
+//  Input Containers:                                                       //
+//   MParContainer                                                          //
+//                                                                          //
+//  Output Containers:                                                      //
+//   -/-                                                                    //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MPrint.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MPrint);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes name and title of the object. It is called by all
+// constructors.
+//
+void MPrint::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPrint";
+    fTitle = title ? title : "Task to print a parameter container";
+
+    fObject = NULL;
+}
+
+MPrint::MPrint()
+{
+    Init(0, 0);
+    SetBit(kSeparator);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Remembers the name to search for in the parameter list
+//  of the object to be printed. The object must be derived from TObject and
+//  TObject::Print(Option_t *) const
+//  must be overloaded. You can also set an option string to use
+//  when calling TObject::Print
+//  If you want that the MPrint instance is removed from the tasklist
+//  if the container to be printed is not found in the PreProcess, call:
+//     MPrint::EnableSkip();
+//
+MPrint::MPrint(const char *obj, const char *option,
+               const char *name, const char *title)
+{
+    Init(name, title);
+    SetOption(option);
+
+    fObjName = obj;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Remember the pointer of the object which has to be
+//  printed. The object must be derived from TObject and
+//  TObject::Print(Option_t *) const
+//  must be overloaded. You can also set an option string to use
+//  when calling TObject::Print
+//  if the container to be printed is not found in the PreProcess, call:
+//     MPrint::EnableSkip();
+//
+MPrint::MPrint(const TObject *obj, const char *option,
+               const char* name, const char *title)
+{
+    Init(name, title);
+    SetOption(option);
+
+    fObject  = obj;
+    fObjName = obj->GetName();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Checks the parameter list for the existance of the parameter container. If
+//  the name of it was given in the constructor.
+//
+Int_t MPrint::PreProcess(MParList *pList)
+{
+    //
+    // The pointer is already given by the user.
+    //
+    if (fObject || TestBit(kSeparator))
+        return kTRUE;
+
+    //
+    // Try to find the parameter container with the given name in the list
+    //
+    fObject = pList->FindObject(fObjName);
+    if (fObject)
+        return kTRUE;
+
+    //
+    // If it couldn't get found stop Eventloop
+    //
+    if (TestBit(kSkip))
+    {
+        *fLog << warn << fObjName << " not found... removing task from list." << endl;
+        return kSKIP;
+    }
+    else
+    {
+        *fLog << err << fObjName << " not found... aborting." << endl;
+        return kFALSE;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calls overloaded TObject::Print
+//
+Int_t MPrint::Process()
+{
+    gLog << flush << all;
+    if (TestBit(kSeparator))
+        gLog.Separator() << endl;
+    else
+        fObject->Print(fOption);
+    return kTRUE;
+} 
+
Index: branches/Mars_McMismatchStudy/mbase/MPrint.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MPrint.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MPrint.h	(revision 17960)
@@ -0,0 +1,36 @@
+#ifndef MARS_MPrint
+#define MARS_MPrint
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MPrint : public MTask
+{
+private:
+    const TObject *fObject;  // pointer to container which has to be printed
+    TString fObjName;        // given name to search for in the parameterlist
+    TString fOption;         // Print option
+
+    enum { kSkip = BIT(14), kSeparator = BIT(15) };
+
+    void Init(const char *name, const char *title);
+
+public:
+    MPrint();
+    MPrint(const char *obj,    const char *option="", const char *name=NULL, const char *title=NULL);
+    MPrint(const TObject *obj, const char *option="", const char *name=NULL, const char *title=NULL);
+
+    void SetOption(Option_t *option) { fOption = option; }
+    void EnableSkip(Bool_t skip=kTRUE) { skip ? SetBit(kSkip) : ResetBit(kSkip); }
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    ClassDef(MPrint, 0) // Task to call Print() function
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/mbase/MProgressBar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MProgressBar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MProgressBar.cc	(revision 17960)
@@ -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, 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 <stdlib.h>         // rand (Ubuntu 8.10)
+
+#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: branches/Mars_McMismatchStudy/mbase/MProgressBar.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MProgressBar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MProgressBar.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MQuaternion.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MQuaternion.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MQuaternion.cc	(revision 17960)
@@ -0,0 +1,74 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MQuaternion
+//
+// The MQuaternion is derived from TQuaternion. A quaternion is a four vector
+// which can store space and time (like a lorentz vector).
+//
+// There are a few advantages of the TQuaternion class over the
+// TLorentzVector, namely the implementation of a direct algebra with
+// just the space part of the vector keeping the time as it is.
+// (This is useful, e.g, for rotations and shift just in space).
+//
+//  - You can construct the MQuaternion from a TQuaternion or a TVector3 and
+//    time.
+//  - Multiplying the MQuaternion with a TRotation with rotate just the
+//    space-part.
+//  - You can access the data members with X(), Y(), Z() and T()
+//  - To get the length or squared-length of the space-vector use R() and R2()
+//  - Access the 2D vector (x/y) with XYvector()
+//  - Thera are a few new function to propagate a MQuaternion along a trajectory
+//    in space and time (also expressed as an MQuaternion with a direction
+//    vector and a speed) Here we assume v>0.
+//
+//    + PropagateDz(MQuaternion &w, Double_t dz)
+//
+//      If dz is positive the position is propagated along the given trajectory
+//      in space (such that the z-component will increase by dz) and
+//      forward in time. If dz<0 the result is vice versa.
+//
+//    + PropagateZ0(MQuaternion &w)
+//
+//      This is an abbreviation for Propagate(w, -Z()). It propagates the
+//      position such that its z-component will vanish. If this is along
+//      the given trajectory time will increase if it is backward time
+//      will decrease.
+//
+//    + PropagateZ(MQuaternion &w, Double_t z)
+//
+//      This is an abbreviation for Propagate(w, z-Z()). It propagates the
+//      position such that its z-component will become z. If this is along
+//      the given trajectory time will increase if it is backward time
+//      will decrease.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MQuaternion.h"
+
+ClassImp(MQuaternion);
+
+using namespace std;
+
Index: branches/Mars_McMismatchStudy/mbase/MQuaternion.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MQuaternion.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MQuaternion.h	(revision 17960)
@@ -0,0 +1,138 @@
+#ifndef MARS_MQuaternion
+#define MARS_MQuaternion
+
+#if 1
+
+// We prefer to derive from TQuaternion instead of TLorantzVector
+// because TQuaternion implements vector algebra with just the 3D vector
+
+#ifndef ROOT_TQuaternion
+#include <math.h>
+#define sqrt ::sqrt
+#include <TQuaternion.h>
+#undef sqrt
+#endif
+
+class MQuaternion : public TQuaternion
+{
+public:
+    MQuaternion(const TQuaternion &q) : TQuaternion(q) { }
+    MQuaternion(const TVector3 &v, Double_t t=0) : TQuaternion(v, t) { }
+    void operator*=(const TRotation &r)
+    {
+        fVectorPart *= r;
+    }
+    Double_t X() const { return fVectorPart.X(); }
+    Double_t Y() const { return fVectorPart.Y(); }
+    Double_t Z() const { return fVectorPart.Z(); }
+    Double_t T() const { return fRealPart; }
+
+    // It seems to be a little bit faster than X*X+Y*Y
+    Double_t R2() const { return XYvector().Mod2(); }
+    Double_t R() const { return XYvector().Mod(); }
+
+    void PropagateDz(const MQuaternion &w, const Double_t dz)
+    {
+        *this += dz/w.Z()*w;
+    }
+
+    // Propagates the particle by a distance f in z along
+    // its trajectory w, if f is positive, in the opposite
+    // direction otherwise.
+    void PropagateZ(const MQuaternion &w, const Double_t z)
+    {
+        PropagateDz(w, z-Z());
+
+        // z=3400, Z= 1700, t=0, c=1    -=  3400/-5*-5     -= 3400       Z=0,    c>0
+        //                              +=  1700/-5*-5     += 1700       Z=1700, c>0
+        // z=3400, Z=-1700, t=0, c=1    -= -3400/-5*-5     -= -1700      Z=0, c<0
+
+        // z=3400, Z= 1700, t=0, c=1    -=  (3400-1700)/-5*-5     -= 3400       Z=0,    c>0
+    }
+
+    // Move the photon along its trajectory to the x/y plane
+    // so that z=0. Therefor stretch the vector until
+    // its z-component vanishes.
+    //p -= p.Z()/u.Z()*u;
+    void PropagateZ0(const MQuaternion &w)
+    {
+        // If z>0 we still have to move by a distance of z.
+        // If z<0 we have to move in the opposite direction.
+        //  --> z has the right sign for PropagateZ
+        PropagateDz(w, -Z());
+
+        // Z= 1700, t=0, c=1    -=  1700/-5*-5     -=  1700 +c     Z=0, c>0
+        // Z=-1700, t=0, c=1    -= -1700/-5*-5     -= -1700 -c     Z=0, c<0
+
+
+        // Z= 1700, t=0, c=1    -=  1700/ 5* 5     -=  1700 -c     Z=0, c<0
+        // Z=-1700, t=0, c=1    -= -1700/ 5* 5     -= -1700 +c     Z=0, c>0
+
+        //PropagateZ(w, Z());
+    }
+
+    TVector2 XYvector() const { return fVectorPart.XYvector(); }
+
+    //void Normalize() { fVectorPart *= TMath::Sqrt(1 - R2())/Z(); }
+
+    void NormalizeVector() { fVectorPart = fVectorPart.Unit(); }
+
+    ClassDef(MQuaternion, 1)
+};
+
+#else
+
+#ifndef ROOT_TLorentzVector
+#include <TLorentzVector.h>
+#endif
+
+class MQuaternion : public TLorentzVector
+{
+public:
+    //MQuaternion(const TLorentzVector &q) : TLorentzVector(q) { }
+    MQuaternion(const TVector3 &v, Double_t t=0) : TLorentzVector(v, t) { }
+    /*
+    void operator*=(const TRotation &r)
+    {
+        fVectorPart *= r;
+    }
+    Double_t X() const { return fVectorPart.X(); }
+    Double_t Y() const { return fVectorPart.Y(); }
+    Double_t Z() const { return fVectorPart.Z(); }
+    Double_t T() const { return fRealPart; }
+    */
+
+    // It seems to be a little bit faster than X*X+Y*Y
+    Double_t R2() const { return Perp2(); }
+    Double_t R() const { return Perp(); }
+
+    // Propagates the particle by a distance f in z along
+    // its trajectory w, if f is positive, in the opposite
+    // direction otherwise.
+    void PropagateZ(const MQuaternion &w, const Double_t f)
+    {
+        *this += f/TMath::Abs(w.Z())*w;
+    }
+
+    // Move the photon along its trajectory to the x/y plane
+    // so that z=0. Therefor stretch the vector until
+    // its z-component vanishes.
+    //p -= p.Z()/u.Z()*u;
+    void PropagateZ0(const MQuaternion &w)
+    {
+        // If z>0 we still have to move by a distance of z.
+        // If z<0 we have to move in th eopposite direction.
+        //  --> z has the right sign for PropagateZ
+        PropagateZ(w, Z());
+    }
+
+    TVector2 XYvector() const { return Vect().XYvector(); }
+
+    //void Normalize() { fVectorPart *= TMath::Sqrt(1 - R2())/Z(); }
+
+    ClassDef(MQuaternion, 0)
+};
+
+#endif
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MReadSocket.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MReadSocket.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MReadSocket.cc	(revision 17960)
@@ -0,0 +1,313 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): 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);
+
+        cout << TDatime().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: branches/Mars_McMismatchStudy/mbase/MReadSocket.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MReadSocket.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MReadSocket.h	(revision 17960)
@@ -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) : std::ios(), std::streambuf(), std::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: branches/Mars_McMismatchStudy/mbase/MReflection.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MReflection.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MReflection.cc	(revision 17960)
@@ -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  11/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReflection
+//
+// This is a fast way to create a rotation matrix which rotates a vector
+// by 180deg around another vector (normal vector of a reflection)
+// and changes its direction. This is nothing else than a reflection
+// on a surface.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReflection.h"
+
+
+ClassImp(MReflection);
+
+using namespace std;
+
Index: branches/Mars_McMismatchStudy/mbase/MReflection.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MReflection.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MReflection.h	(revision 17960)
@@ -0,0 +1,63 @@
+#ifndef MARS_MReflection
+#define MARS_MReflection
+
+#ifndef ROOT_TRotation
+#include <TRotation.h>
+#endif
+
+class MReflection : public TRotation
+{
+private:
+    MReflection(Double_t a, Double_t b, Double_t c,
+                Double_t d, Double_t e, Double_t f,
+                Double_t g, Double_t h, Double_t i)
+        : TRotation(a,b,c,d,e,f,g,h,i) { }
+
+    void Init(Double_t x, Double_t y, Double_t z)
+    {
+        // Normalize components of vector (including factor 2!)
+        const Double_t n = -2./(x*x + y*y + z*z);
+
+        // Expressed by the focal length
+        //const Double_t n = -1./(2*F*F);
+
+        // Construct rotation matrix to rotate the photon direction
+        // around the axis defined by the normal vector. (This is
+        // a simplified version of TVector3::Rotate(double, TVector3&)
+        // The minus-sign does the relfection, i.e. flips the
+        // direction of the vector.
+        static_cast<TRotation&>(*this) =
+            MReflection(
+                        1+n*x*x,   n*y*x,   n*z*x,
+                          n*x*y, 1+n*y*y,   n*z*y,
+                          n*x*z,   n*y*z, 1+n*z*z
+                       );
+
+        //
+        //  n = ( x / y (UInt_t)-1;/ z )  // Normalenvektor
+        //  V = ( X / Y / Z )  // Photon to be reflected
+        //
+        //  nV := -2 * ( x*X + y*Y + z*Z ) / ( x*x + y*y + z*z )
+        //
+        //  V' = nV * vec(n) + vec(V)
+        //
+
+        // return TVector2(X/Z, Y/Z);
+    }
+
+public:
+    // Normal vector of the reflecting surface
+    MReflection(const TVector3 &v)
+    {
+        Init(v.X(), v.Y(), v.Z());
+    }
+    // Normal vector of the reflecting surface
+    MReflection(Double_t x, Double_t y, Double_t z)
+    {
+        Init(x, y, z);
+    }
+
+    ClassDef(MReflection, 0) // A TRotation derivative describing the reflection by the normal vector of the surface
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MRunIter.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MRunIter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MRunIter.cc	(revision 17960)
@@ -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, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Javier Rico,  4/2004 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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 <iostream>
+
+#include <TMath.h>
+#include <TSystem.h>
+
+ClassImp(MRunIter);
+
+using namespace std;
+
+void MRunIter::SortRuns()
+{
+    const int n = GetNumRuns();
+
+    TArrayI idx(n);
+    TMath::Sort(n, fRuns.GetArray(), idx.GetArray(), kFALSE);
+
+    for (int i=0; i<n; i++)
+        idx[i] = fRuns[idx[i]];
+
+    fRuns = idx;
+}
+
+Int_t MRunIter::AddRun(UInt_t run, const char *path)
+{
+    TString p(path);
+
+    if (p.IsNull())
+        p = fPath;
+
+    if (p.IsNull())
+        p = ".";
+
+    // R. DeLosReyes and T. Bretz
+    // Changes to read the DAQ numbering format. Changes takes place
+    // between runs 35487 and 00035488 (2004_08_30)
+    const char *fmt;
+    if(fIsStandardFile)
+      {
+        fmt = "%05d-%s";
+        fIsRawFile = kFALSE;
+      }
+    else
+      fmt = run>35487 ? "*_%08d_*_%s" : "*_%05d_*_%s";
+
+    MDirIter NextR;
+    NextR.AddDirectory(p, Form(fmt, run,fIsRawFile?"*.raw":"*.root"), -1);
+
+    const TString name(NextR());
+    if (name.IsNull())
+        return 0;
+
+    AddRunNumber(run);
+
+    return AddDirectory(gSystem->DirName(name), gSystem->BaseName(name), -1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add runs specified in a character chain with the format:
+// run1,run2-run3,run4-run5,...
+// e.g  if runrange="100,105-107,110-112,115" 
+// runs 100,105,106,107,110,111,112 and 115 are included in the iterator list
+//
+Int_t MRunIter::AddRuns(const char* runrange, const char* path)
+{ 
+    const TString chcopy(runrange);
+  
+    Ssiz_t last=0;
+    Int_t  lowrun=-1;
+    UInt_t totdir=0;
+  
+    // loop over the elements of the character chain 
+    for (Int_t i=0;i<chcopy.Length();i++)
+    {
+        // look for a digit, a '-' or a ',' 
+        const char c=chcopy[i];
+        if (! ((c>='0' && c<='9') || c=='-' || c==','))
+            return totdir;
+        
+        // if '-' is found, save the previous number as initial run
+        if (c=='-' && lowrun<0 && i>last)
+        {
+            const TSubString chrun = chcopy(last,i-last);
+            lowrun=atoi(chrun.Data());	  	  
+            last=i+1;
+            continue;
+        }
+        // if ',' or the end of the string are found, save the previous run or run range
+        if (c==',' && i>last)
+        {
+            const TSubString chrun = chcopy(last,i-last);
+            const Int_t up=atoi(chrun.Data());
+            if(lowrun>=0 && lowrun<=up)
+                totdir+=AddRuns(lowrun,up,path);
+            else if(lowrun<0)
+                totdir+=AddRun(up,path);
+            
+            lowrun=-1;
+            last=i+1;
+            continue;
+        }
+  
+        // if find two continous separators exit
+        if ((c=='-' && i==last) || (c==',' && i==last))
+            return totdir;
+    }
+  
+    // save last run range
+    const TSubString chrun = chcopy(last,chcopy.Length()-last);
+    const Int_t upprun=atoi(chrun.Data());
+    if(lowrun>=0 && lowrun<=upprun)
+    {
+        totdir+=AddRuns(lowrun,upprun,path);
+        return totdir;
+    }
+  
+    if(lowrun<0)
+        totdir+=AddRun(upprun,path);
+  
+    return totdir;
+}
Index: branches/Mars_McMismatchStudy/mbase/MRunIter.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MRunIter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MRunIter.h	(revision 17960)
@@ -0,0 +1,78 @@
+#ifndef MARS_MRunIter
+#define MARS_MRunIter
+
+#ifndef MARS_MDirIter
+#include "MDirIter.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MRunIter : public MDirIter
+{
+private:
+    TString fPath;
+    TArrayI fRuns;
+
+    Bool_t fIsRawFile;
+    Bool_t fIsStandardFile;
+
+    void AddRunNumber(UInt_t run)
+    {
+        fRuns.Set(fRuns.GetSize()+1);
+        fRuns[fRuns.GetSize()-1] = run;
+
+        SortRuns();
+
+    }
+
+    void SortRuns();
+
+public:
+    MRunIter(const char *path=0) : fPath(path), fIsRawFile(0), fIsStandardFile(kFALSE) { }
+
+    void SetRawFile(Bool_t filetype) { fIsRawFile = filetype; }
+    void SetStandardFile(Bool_t filetype) { fIsStandardFile = filetype; }
+
+    Int_t AddRun(UInt_t run, const char *path=0);
+    Int_t AddRuns(const char* runrange, const char *path=0);
+    Int_t AddRuns(UInt_t from, UInt_t to, const char *path=0)
+    {
+        Int_t n = 0;
+
+        for (UInt_t i=from; i<=to; i++)
+            AddRun(i, path);
+
+        return n;
+    }
+
+    UInt_t GetNumRuns() const { return fRuns.GetSize(); }
+    const TArrayI &GetRuns() const { return fRuns; }
+
+    TString GetRunsAsString() const {
+        TString txt;
+        for (int i=0; i<fRuns.GetSize(); i++)
+        {
+            txt += "#";
+            txt += fRuns[i];
+            if (i!=fRuns.GetSize()-1)
+                txt += " ";
+        }
+        return txt;
+    }
+    TString GetRunsAsFileName() const {
+        TString txt;
+        for (int i=0; i<fRuns.GetSize(); i++)
+        {
+            txt += fRuns[i];
+            if (i!=fRuns.GetSize()-1)
+                txt += "_";
+        }
+        return txt;
+    }
+
+    ClassDef(MRunIter, 1) // Iterator for runs
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MSearch.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MSearch.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MSearch.cc	(revision 17960)
@@ -0,0 +1,212 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <stdlib.h>         // rand (Ubuntu 8.10)
+
+#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: branches/Mars_McMismatchStudy/mbase/MSearch.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MSearch.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MSearch.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mbase/MSpline3.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MSpline3.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MSpline3.cc	(revision 17960)
@@ -0,0 +1,290 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSpline3
+//
+// This is a extension of TSpline3. In addition to TSpline3 it allows access
+// to Xmin, Xman and Np. The construction is a bit simplified because no
+// title hase to be given (it can be given later by SetTitle anyway)
+// and is provides constructors which allow to scale the x-values by
+// pre-defined multiplier (e.g. frequency) to create the spline.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSpline3.h"
+
+#include <TF1.h>
+#include <TMath.h>
+
+#include "MArrayD.h"
+
+ClassImp(MSpline3);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MSpline3::MSpline3(const TF1 &f, const char *opt, Double_t valbeg, Double_t valend)
+    : TSpline3("MSpline3", f.GetXmin(), f.GetXmax(), &f, f.GetNpx(), opt, valbeg, valend)
+{
+}
+
+MSpline3::MSpline3(const TF1 &f, Double_t freq, const char *opt,Double_t valbeg, Double_t valend)
+    : TSpline3("MSpline3", f.GetXmin()*freq, f.GetXmax()*freq, ConvertFunc(f, freq).GetArray(), f.GetNpx(), opt, valbeg, valend)
+{
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is a helper to convert the x-values by multiplying with freq
+// before initializing the spline
+//
+TGraph *MSpline3::ConvertSpline(const TSpline &s, Float_t freq) const
+{
+    const UInt_t npx = s.GetNpx();
+
+    // WARNING: This is a stupid workaround because the TSpline3-
+    // constructor takes a pointer as input! It is not thread-safe!
+    static TGraph g;
+    g.Set(npx);
+
+    for (UInt_t i=0; i<npx; i++)
+    {
+        Double_t x, y;
+        s.GetKnot(i, x, y);
+        g.SetPoint(i, x*freq, y);
+    }
+
+    return &g;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is a helper to convert the x-values by multiplying with freq
+// before initializing the spline
+//
+TGraph *MSpline3::ConvertGraph(const TGraph &s, Float_t freq) const
+{
+    const UInt_t npx = s.GetN();
+
+    // WARNING: This is a stupid workaround because the TSpline3-
+    // constructor takes a pointer as input! It is not thread-safe!
+    static TGraph g;
+    g.Set(npx);
+
+    for (UInt_t i=0; i<npx; i++)
+    {
+        Double_t x, y;
+        s.GetPoint(i, x, y);
+        g.SetPoint(i, x*freq, y);
+    }
+
+    return &g;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is a helper to convert the x-values by multiplying with freq
+// before initializing the spline. The conversion from the function to
+// a discrete binning is done similar to the constructor of TSpline
+//
+MArrayD &MSpline3::ConvertFunc(const TF1 &f, Float_t freq) const
+{
+    const UInt_t npx = f.GetNpx();
+
+    // WARNING: This is a stupid workaround because the TSpline3-
+    // constructor takes a pointer as input! It is not thread-safe!
+    static MArrayD g;
+    g.Set(npx);
+
+    const Double_t step = (f.GetXmax()-f.GetXmin())/(npx-1);
+
+    for (UInt_t i=0; i<npx; ++i)
+    {
+        const Double_t x = f.GetXmin() + i*step;
+        g[i] = f.Eval(x);
+    }
+
+    return g;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the integral in the splines bin i up to x.
+//
+// The TSpline3 in the Interval [fX[i], fX[i+1]] is defined as:
+//
+//      dx = x-fX[i]
+//      y = fY + dx*fB + dx*dx*fC + dx*dx*dx*fD
+//
+// This yields the integral:
+//
+//   int(y) = dx*fY + 1/2*dx*dx*fB + 1/3*dx*dx*dx*fC + 1/4*dx*dx*dx*dx*fD
+//          = dx*(fY + dx*(1/2*fB + dx*(1/3*fC + dx*(1/4*fD))))
+//
+// Which gives for the integral range [fX[i], fX[i]+w]:
+//   int(fX[i]+w)-int(fX[i]) = w*(fY + w*(1/2*fB + w*(1/3*fC + w*(1/4*fD))))
+//
+// and for the integral range [fX[i]+w, fX[i+1]]:
+//   int(fX[i+1])-int(fX[i]+w) = `
+//     W*(fY + W*(1/2*fB + W*(1/3*fC + W*(1/4*fD)))) -
+//     w*(fY + w*(1/2*fB + w*(1/3*fC + w*(1/4*fD))))
+// with
+//     W := fX[i+1]-fX[i]
+//
+Double_t MSpline3::IntegralBin(Int_t i, Double_t x) const
+{
+    Double_t x0, y, b, c, d;
+    const_cast<MSpline3*>(this)->GetCoeff(i, x0, y, b, c, d);
+
+    const Double_t w = x-x0;
+
+    return w*(y + w*(b/2 + w*(c/3 + w*d/4)));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the integral of the spline's bin i.
+//
+Double_t MSpline3::IntegralBin(Int_t i) const
+{
+    Double_t x, y;
+
+    GetKnot(i+1, x, y);
+
+    return IntegralBin(i, x);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the integral from a to b
+//
+Double_t MSpline3::Integral(Double_t a, Double_t b) const
+{
+    const Int_t n = FindX(a);
+    const Int_t m = FindX(b);
+
+    Double_t sum = -IntegralBin(n, a);
+
+    for (int i=n; i<=m-1; i++)
+        sum += IntegralBin(i);
+
+    sum += IntegralBin(m, b);
+
+    return sum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the integral between Xmin and Xmax
+//
+Double_t MSpline3::Integral() const
+{
+    Double_t sum = 0;
+
+    for (int i=0; i<GetNp()-1; i++)
+        sum += IntegralBin(i);
+
+    return sum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the integral between Xmin and Xmax of int( f(x)*sin(x) )
+//
+// The x-axis is assumed to be in degrees
+//
+Double_t MSpline3::IntegralSolidAngle() const
+{
+    const Int_t n = GetNp();
+
+    MArrayD x(n);
+    MArrayD y(n);
+
+    for (int i=0; i<n; i++)
+    {
+        GetKnot(i, x[i], y[i]);
+
+        x[i] *= TMath::DegToRad();
+        y[i] *= TMath::Sin(x[i]);
+    }
+
+    return TMath::TwoPi()*MSpline3(x.GetArray(), y.GetArray(), n).Integral();
+}
+
+
+// FIXME: As soon as TSpline3 allows access to fPoly we can implement
+//        a much faster evaluation of the spline, especially in
+//        special conditions like in MAnalogSignal::AddPulse
+//        This will be the case for root > 5.22/00
+
+/*
+Double_t MSpline3::EvalFast(Double_t x) const
+{
+    // Eval this spline at x
+    const Int_t klow=FindFast(x);
+    return fPoly[klow].Eval(x);
+}
+
+Int_t MSpline3::FindFast(Double_t x) const
+{
+    //
+    // If out of boundaries, extrapolate
+    // It may be badly wrong
+
+    // if (x<=fXmin)
+    //     return 0;
+    //
+    // if (x>=fXmax)
+    //     return fNp-1;
+
+    //
+    // Equidistant knots, use histogramming
+    if (fKstep)
+        return TMath::Min(Int_t((x-fXmin)/fDelta),fNp-1);
+
+    //
+    // Non equidistant knots, binary search
+    Int_t klow = 0;
+    Int_t khig = fNp-1;
+
+    Int_t khalf;
+    while (khig-klow>1)
+        if(x>fPoly[khalf=(klow+khig)/2].X())
+            klow=khalf;
+        else
+            khig=khalf;
+
+    // This could be removed, sanity check
+    //if(!(fPoly[klow].X()<=x && x<=fPoly[klow+1].X()))
+    //    Error("Eval",
+    //          "Binary search failed x(%d) = %f < %f < x(%d) = %f\n",
+    //          klow,fPoly[klow].X(),x,fPoly[klow+1].X());
+
+    return klow;
+}
+*/
Index: branches/Mars_McMismatchStudy/mbase/MSpline3.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MSpline3.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MSpline3.h	(revision 17960)
@@ -0,0 +1,69 @@
+#ifndef MARS_MSpline3
+#define MARS_MSpline3
+
+#ifndef ROOT_TSpline
+#include <TSpline.h>
+#endif
+
+class MArrayD;
+
+class MSpline3 : public TSpline3
+{
+private:
+    TGraph  *ConvertSpline(const TSpline &s, Float_t freq) const;
+    TGraph  *ConvertGraph(const TGraph &s, Float_t freq) const;
+    MArrayD &ConvertFunc(const TF1 &f, Float_t freq) const;
+
+    Double_t IntegralBin(Int_t i, Double_t x) const;
+    Double_t IntegralBin(Int_t i) const;
+
+public:
+    MSpline3() { }
+
+    // None equidistant binning (evaluation a bit slower in case of many bins)
+    MSpline3(const TGraph &g,
+             const char *opt=0, Double_t valbeg=0, Double_t valend=0)
+       : TSpline3("MSpline3", &g, opt, valbeg, valend)
+    {
+    }
+
+    MSpline3(const TGraph &g, Double_t freq,
+             const char *opt=0, Double_t valbeg=0, Double_t valend=0)
+       : TSpline3("MSpline3", ConvertGraph(g, freq), opt, valbeg, valend)
+    {
+    }
+
+    MSpline3(const TSpline &s, Double_t freq,
+             const char *opt=0, Double_t valbeg=0, Double_t valend=0)
+       : TSpline3("MSpline3", ConvertSpline(s, freq), opt, valbeg, valend)
+    {
+    }
+
+    MSpline3(const Double_t x[], const Double_t y[], Int_t n, const char *opt=0,
+             Double_t valbeg=0, Double_t valend=0)
+       : TSpline3("MSpline3", const_cast<Double_t*>(x), const_cast<Double_t*>(y), n, opt, valbeg, valend)
+    {
+    }
+
+    // Equidistant binning (evaluation a bit faster in case of many bins)
+
+    // FIXME: In principle TF1 can be evaluated histogram like which should be faster
+    MSpline3(const TF1 &f, const char *opt=0,Double_t valbeg=0, Double_t valend=0);
+    MSpline3(const TF1 &f, Double_t freq, const char *opt=0,Double_t valbeg=0, Double_t valend=0);
+
+    Double_t GetXmin() const { return fXmin; }     // Minimum value of abscissa
+    Double_t GetXmax() const { return fXmax; }     // Maximum value of abscissa
+
+    Int_t GetNp() const { return fNp; }
+
+    TH1 *GetHistogram() const { return (TH1*)fHistogram; }
+
+    Double_t Integral(Double_t a, Double_t b) const;
+    Double_t Integral() const;
+
+    Double_t IntegralSolidAngle() const;
+
+    ClassDef(MSpline3, 1) // An extension of the TSpline3
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MStatusArray.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MStatusArray.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MStatusArray.cc	(revision 17960)
@@ -0,0 +1,675 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 03/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MStatusArray
+//
+//  Helper class for MStatusDisplay
+//
+// If you want to read a MStatusArray (normally with name MStatusDisplay)
+// it is recommended to do it like this:
+//     TFile f("myfile.root", "read");
+//     MStatusArray arr;
+//     arr.Read();
+//
+// If you want to use TFile::Get or TFile::GetObject you should switch off
+// addding Histograms automatically to the current directory first:
+//     TFile f("myfile.root", "read");
+//     TH1::AddDirectory(kFALSE);
+//     f.Get("MStatusDisplay");
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MStatusArray.h"
+
+#include <TH1.h>              // TH1::AddDirectoryStatus();
+#include <TFile.h>            // gFile
+#include <TClass.h>
+#include <TCanvas.h>
+
+#include <TGraph.h>           // For the TGraph workaround
+#include <TPaveText.h>        // For the TPaveText workaround
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParContainer.h"   // MParContainer::GetClass
+#include "MStatusDisplay.h"
+
+//#define DEBUG
+
+ClassImp(MStatusArray);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize the MStatusArray from an MStatusDisplay. Note, the contents
+// still owned by MStatusDisplay and will vanish if the display changes
+// or is deleted without further notice.
+//
+MStatusArray::MStatusArray(const MStatusDisplay &d) : TObjArray()
+{
+    d.FillArray(*this);
+}
+
+#ifdef DEBUG
+static void *ptr = 0;
+#endif
+
+// --------------------------------------------------------------------------
+//
+// Remove objects matching the id (the first character of their class
+// name) recuresively
+//
+Bool_t MStatusArray::RecursiveDelete(TVirtualPad *p, const char id) const
+{
+    if (!p)
+        return kTRUE;
+
+    // It seems that it is necessary to keep the ListOfPrimitve consistent
+    // while deleting - reason unknown.
+    TIter Next(p->GetListOfPrimitives());
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (!dynamic_cast<TVirtualPad*>(o) && (o->ClassName()[0]==id || id==0))
+        {
+            while (p->GetListOfPrimitives()->Remove(o));
+
+            // This is necessary because for unknown reasons TPaveText
+            // as a member of a class (e.g. MHRanForestGini) doesn't
+            // get removed from the pad if deleted, and therefore
+            // gets deleted twice (FIXME: To be investigated)
+            //if (dynamic_cast<TPaveText*>(o) && !o->TestBit(kCanDelete))
+            //    continue;
+
+#ifdef DEBUG
+            cout << "Start Delete " << o << " " << o->GetName() << " " << o->ClassName() << endl;
+#endif
+            delete o;
+
+#ifdef DEBUG
+            cout << "Done  Delete " << o<< endl;
+#endif
+            return kFALSE;
+        }
+
+        while (!RecursiveDelete(dynamic_cast<TVirtualPad*>(o), id));
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Make sure to set the kMustCleanup for all object in our tree
+// which will later be deleted when the array is destructed.
+//
+void MStatusArray::SetCleanup(TObject *obj) const
+{
+    if (!obj)
+        return;
+
+    TVirtualPad *pad = dynamic_cast<TVirtualPad*>(obj);
+
+    // Do not set the bit for pads because it would end in
+    // endless recursions
+    if (pad && !dynamic_cast<TCanvas*>(obj))
+        obj->ResetBit(kMustCleanup);
+    else
+    {
+        // If this is no pad or TCanvas set the kMustCleanup bit
+        // to make sure that the object is not by chance deleted twice.
+        obj->SetBit(kMustCleanup);
+
+        // Unfortunately, this can still happen to the fHistogram and
+        // fFunctions in a TGraph (because for some reason if a TGraph
+        // is stored twice in a file they might later share the same
+        // objects)
+        TGraph *g = dynamic_cast<TGraph*>(obj);
+        if (g)
+        {
+#ifdef DEBUG
+            cout << "Found TGraph " << g->GetName() << " " << g << " while deleting " << ptr << endl;
+#endif
+            if (g->GetHistogram())
+                g->GetHistogram()->SetBit(kMustCleanup);
+            if (g->GetListOfFunctions())
+                g->GetListOfFunctions()->SetBit(kMustCleanup);
+        }
+    }
+
+    if (!pad)
+        return;
+
+    // If object was a pad go one layer deeper
+    TIter Next(pad->GetListOfPrimitives());
+    TObject *o=0;
+    while ((o=Next()))
+        SetCleanup(o);
+}
+
+// This is a stupid C++ trick which allos us to access the
+// protected data-mebers of TGraph
+class MyGraph : public TGraph
+{
+public:
+    void ResetListOfFunctions()
+    {
+        fFunctions = 0;
+    }
+};
+
+void MStatusArray::RecursiveRemove(TCollection *col, TObject *obj)
+{
+    // First remove the object from the collection as often as possible
+    // (The collection is always a ListOfPrimitives(). This code is
+    // based on TCollection::RecursiveRemove and TPad::RecursiveRemove)
+    while (col->Remove(obj));
+
+    TObject *object=0;
+
+    // Loop over all objects in the collection
+    TIter Next(col);
+    while ((object=Next()))
+    {
+        // Check if this object is a pad. If it is a pad go one
+        // layer deeper.
+        TPad *pad = dynamic_cast<TPad*>(object);
+        if (pad)
+        {
+#ifdef DEBUG
+            cout << "Start RecursiveRemove in " << pad->GetName() << " " << pad << endl;
+#endif
+            RecursiveRemove(pad->GetListOfPrimitives(), obj);
+#ifdef DEBUG
+            cout << "Done  RecursiveRemove in " << pad->GetName() << " " << pad << endl;
+#endif
+            continue;
+        }
+
+        // If it is not a TPad check if it is a TGraph
+        TGraph *g = dynamic_cast<TGraph*>(object);
+        if (g/* && g!=ptr*/)
+        {
+#ifdef DEBUG
+            gLog << all << "MStatusArray::RecursiveRemove " << obj << " from TGraph " << g << endl;
+#endif
+
+            // If the object to be removed is the histogram from the
+            // TGraph the histogram got already deleted so we have to
+            // reset the pointer
+            if (g->GetHistogram()==obj)
+            {
+#ifdef DEBUG
+                gLog << all << "       SetHist(0)" << endl;
+#endif
+                g->SetHistogram(0);
+            }
+
+            // If the object to be removed is the ListOfFunction from the
+            // TGraph the ListOfFunction got already deleted so we have to
+            // reset the pointer. This is done by a stupid C++ trick
+            // (a derived class which can access the protected data mebers)
+            if (g->GetListOfFunctions()==obj)
+            {
+#ifdef DEBUG
+                gLog << all << "       SetFunc(0)" << endl;
+#endif
+                static_cast<MyGraph*>(g)->ResetListOfFunctions();
+            }
+        }
+
+#ifdef DEBUG
+        cout << " Call RecursiveRemove for " << object->GetName() << " " << object << endl;
+#endif
+
+        // Now we go on like TCollction would do calling the RecursiveRemove
+        // of the objects (which are no pads)
+        if (object->TestBit(TObject::kNotDeleted))
+            object->RecursiveRemove(obj);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Use our own implementation of RecursiveRemove.
+//
+void MStatusArray::RecursiveRemove(TObject *obj)
+{
+#ifdef DEBUG
+    cout << "RecursiveRemove " << obj << endl;
+#endif
+    RecursiveRemove(this, obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// The problem is that our objects (e.g. MHRate) can own histograms and
+// graphs (or other objects), which are data members rather than allocated
+// objects (pointers), and which are drawn into a pad. If such a pad gets
+// read from a file we have to set the kCanDelete bits for all objects
+// in all pads to ensure that they are properly deleted (since we
+// don't know who owns them). Unfortunately, this might result in the
+// data member deleted first and then second in the destructor of the
+// owning class. One simple workaround is to delete all our own objects
+// ("M*") first without touching the root objects ("T*") and delete the
+// remaining ones later. This might not work if teh owned objects are
+// MARS classes. Fortunately, none of our classes yets owns another of
+// our class not dynamically allocated. (This case is covered by
+// the RecursiveRemove facility).
+//
+// Furthermore TGraphs which are read from a file as a data member
+// of a class and which are drawn to a pad share the same fFunctions
+// and fHistogram. To avoid double deleting (the second TGraph won't
+// be signaled if the first one is deleted) we implement our own
+// RecursiveRemove facility. (This gets a bit better in root 5.28
+// because TGraph::RecursiveRemove will than also check fHistogram)
+//
+void MStatusArray::Delete(Option_t *)
+{
+    // Add this to the list of cleanups to ensure as many cleaning
+    // operations as possible are propagated
+    gROOT->GetListOfCleanups()->Add(this);
+
+    // First make sure that all kMustCleanup bits are set, esepcially
+    // the ones of TGraph::fHistogram and TGraph::fFunctions
+    TIter Next(this);
+    TObject *o=0;
+    while ((o=Next()))
+        SetCleanup(o);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+    // Now delete the MARS object first because we have full control
+    // of them
+    TIter Next2(this);
+    while ((o=Next2()))
+        while (!RecursiveDelete(dynamic_cast<TVirtualPad*>(o), 'M'));
+
+    // Now delete all root objects
+    TIter Next3(this);
+    while ((o=Next3()))
+        while (!RecursiveDelete(dynamic_cast<TVirtualPad*>(o)));
+#endif
+
+    // And delete all the rest
+    TObjArray::Delete();
+
+    // Remove it from the list again
+    gROOT->GetListOfCleanups()->Remove(this);
+}
+
+// --------------------------------------------------------------------------
+//
+// If o==NULL a new status display is created, otherwise the one with name o
+// is searched in gROOT->GetListOfSpecials().
+// In this display the contents of the MStatusArray is displayed.
+//
+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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Display the contents of the given tab in the display given as argument.
+//
+void MStatusArray::DisplayIn(MStatusDisplay &d, const char *tab) const
+{
+    d.Display(*this, tab);
+}
+
+TObject *MStatusArray::FindObjectInPad(TVirtualPad *pad, const char *object, TClass *cls) const
+{
+    TObject *o = NULL;//pad->FindObject(object);
+//    if (o && o->InheritsFrom(cls))
+//        return o;
+
+    TIter Next(pad->GetListOfPrimitives());
+    while ((o=Next()))
+    {
+        if (o->GetName()==(TString)object && o->InheritsFrom(cls))
+            return o;
+
+        if (o==pad || !o->InheritsFrom(TVirtualPad::Class()))
+            continue;
+
+        if ((o = FindObjectInPad((TVirtualPad*)o, object, cls)))
+            return o;
+//            if (o->InheritsFrom(cls))
+//                return o;
+    }
+    return 0;
+}
+
+TCanvas *MStatusArray::FindCanvas(const char *name) const
+{
+    TObject *o = TObjArray::FindObject(name);
+    if (!o)
+        return 0;
+
+    return o->InheritsFrom(TCanvas::Class()) ? (TCanvas*)o : 0;
+}
+
+
+TObject *MStatusArray::FindObjectInCanvas(const char *object, const char *base, const char *canvas) const
+{
+    gLog << err;
+    TClass *cls = MParContainer::GetClass(base, &gLog);
+    if (!cls)
+        return 0;
+
+    TCanvas *c = canvas ? FindCanvas(canvas) : 0;
+    if (canvas)
+    {
+        if (!c)
+        {
+            gLog << warn << "Canvas '" << canvas << "' not found..." << endl;
+            return 0;
+        }
+
+        TObject *o = FindObjectInPad(c, object, cls);
+        if (!o)
+        {
+            gLog << warn << "Object '" << object << "' [" << base << "] not found in canvas '" << canvas << "'..." << endl;
+            return 0;
+        }
+
+        return o; //o->InheritsFrom(cls) ? o : 0;
+    }
+
+    TObject *o=0;
+    TIter Next(this);
+    while ((o=Next()))
+    {
+        if (!o->InheritsFrom(TVirtualPad::Class()))
+            continue;
+
+        if ((o=FindObjectInPad((TVirtualPad*)c, object, cls)))
+            return o;
+    }
+
+    gLog << warn << "Object '" << object << "' [" << base << "] not found in canvas '" << canvas << "'..." << endl;
+    return NULL;
+}
+
+TObject *MStatusArray::FindObjectInCanvas(const char *object, const char *canvas) const
+{
+    return FindObjectInCanvas(object, object, canvas);
+}
+
+TObject *MStatusArray::FindObject(const char *object, const char *base) const
+{
+    return FindObjectInCanvas(object, base, 0);
+}
+
+TObject *MStatusArray::FindObject(const char *object) const
+{
+    return FindObjectInCanvas(object, object, 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print recursively all objects in this and sub-pads
+//
+void MStatusArray::PrintObjectsInPad(const TCollection *list, const TString &name, Int_t lvl) const
+{
+    TIter Next(list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        const Bool_t print = name.IsNull() || name==(TString)o->GetName();
+        if (print)
+        {
+            if (lvl>0)
+                gLog << setw(lvl) << ' ';
+            gLog << " " << o->ClassName() << ": " << o->GetName() << " <" << Next.GetOption() << "> (" << o << ") " << (int)o->TestBit(kCanDelete) << endl;
+        }
+
+        if (o->InheritsFrom(TVirtualPad::Class()))
+            PrintObjectsInPad(((TVirtualPad*)o)->GetListOfPrimitives(), print?TString():name, lvl+1);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Print recursively all objects in this and sub-pads. If !option.IsNull()
+// only objects in the corresponding pad are printed.
+//
+void MStatusArray::Print(Option_t *option) const
+{
+    gLog << all;
+
+    PrintObjectsInPad(this, TString(option));
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Make sure that kCanDelete is properly set for all directly contained
+// objects. Some kCanDelete bits might not be properly set or get lost when
+// the MParContainer is stored.
+//
+void MStatusArray::SetCanDelete(const TCollection *list) const
+{
+    TIter Next(list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(TVirtualPad::Class()))
+            SetCanDelete(((TVirtualPad*)o)->GetListOfPrimitives());
+        else
+            o->SetBit(kCanDelete|kMustCleanup);
+    }
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Set kCanDelete for all objects for which kMyCanDelete is set. This
+// is a STUPID workaruond for an ANNOYING root bug which is that
+// the streamer function of TH1 resets the KCanDelete bit after reading.
+//
+void MStatusArray::SetCanDelete(const TCollection *list) const
+{
+    TIter Next(list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(TVirtualPad::Class()))
+            SetCanDelete(((TVirtualPad*)o)->GetListOfPrimitives());
+        else
+        {
+            if (o->TestBit(kMyCanDelete) && o->InheritsFrom("TH1"))
+            {
+                o->SetBit(kCanDelete);
+                o->ResetBit(kMyCanDelete);
+            }
+        }
+    }
+}
+
+void MStatusArray::EnableTH1Workaround(const TCollection *list) const
+{
+    TIter Next(list?list:this);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(TVirtualPad::Class()))
+            EnableTH1Workaround(((TVirtualPad*)o)->GetListOfPrimitives());
+        else
+            if (o->InheritsFrom("TH1"))
+                o->SetBit(kCanDelete);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set kMyCanDelete for all objects for which kCanDelete is set. This
+// is a STUPID workaruond for an ANNOYING root bug which is that
+// the streamer function of TH1 resets the KCanDelete bit after reading.
+//
+void MStatusArray::SetMyCanDelete(const TCollection *list) const
+{
+    TIter Next(list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(TVirtualPad::Class()))
+            SetMyCanDelete(((TVirtualPad*)o)->GetListOfPrimitives());
+        else
+        {
+            if (o->TestBit(kMyCanDelete) && o->InheritsFrom("TH1"))
+                gLog << warn << "WARNING - MStatusArray::Write - " << o->GetName() << " [" << o->ClassName() << "] has BIT(30) already set!" << endl;
+
+            if (o->TestBit(kCanDelete) && o->InheritsFrom("TH1"))
+                o->SetBit(kMyCanDelete);
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset kMyCanDelete for all objects for which kMyCanDelete is set. This
+// is a STUPID workaruond for an ANNOYING root bug which is that
+// the streamer function of TH1 resets the KCanDelete bit after reading.
+//
+void MStatusArray::ResetMyCanDelete(const TCollection *list) const
+{
+    TIter Next(list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(TVirtualPad::Class()))
+            ResetMyCanDelete(((TVirtualPad*)o)->GetListOfPrimitives());
+        else
+        {
+            if (o->TestBit(kMyCanDelete) && o->InheritsFrom("TH1"))
+                o->ResetBit(kMyCanDelete);
+        }
+    }
+}
+
+MStatusArray::~MStatusArray()
+{
+    // This is the destructor from TObjArray...
+    // It must be here, because for some reason I don't know it
+    // is otherwise not correctly executed from the Interpreter
+    // (root 5.12/00f)
+    if (IsOwner())
+        Delete();
+
+    TStorage::Dealloc(fCont);
+
+    fCont = 0;
+    fSize = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Switch off adding histograms to current directory before reading.
+// Switch back
+//
+Int_t MStatusArray::Read(const char *name)
+{
+    // It seems that the contents are not properly deleted by TObjArray::Read
+    Delete();
+
+    SetOwner();
+
+    const TString keyname = name?name:"MStatusDisplay";
+
+    // Check if key exists (to suppress an error on the console
+    if (!gDirectory->GetListOfKeys())
+    {
+        gLog << inf << keyname << " [MStatusArray] not found (no open file?)" << endl;
+        return 0;
+    }
+
+    // Check if key exists (to suppress an error on the console
+    if (!gDirectory->GetListOfKeys()->FindObject(keyname))
+    {
+        gLog << inf << keyname << " [MStatusArray] not found." << endl;
+        return 0;
+    }
+
+    // Make sure newly read histograms are not added to the current directory
+    const Bool_t store = TH1::AddDirectoryStatus();
+    TH1::AddDirectory(kFALSE);
+    const Int_t rc = TObjArray::Read(keyname);
+    TH1::AddDirectory(store);
+
+    // All objects in the list (TNamed, TCanvas, etc) do not have
+    // the kCanDelete bit set. Make sure that it is set to make
+    // them deleted by the destructor of this list
+    TIter Next(this);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(TVirtualPad::Class()))
+        {
+            TIter Next2(((TVirtualPad*)o)->GetListOfPrimitives());
+            TObject *o2=0;
+            while ((o2=Next2()))
+                if (o2->InheritsFrom(MParContainer::Class()))
+                    o2->SetBit(kCanDelete);
+        }
+        o->SetBit(kCanDelete);
+    }
+
+    // Make sure that all kCanDelete bits are properly set
+    SetCanDelete(this);
+    SetOwner();
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Switch off adding histograms to current directory before reading.
+// Switch back
+//
+Int_t MStatusArray::Write(const char *name, Int_t option, Int_t bufsize) const
+{
+    SetMyCanDelete(this);
+    const Int_t rc = TObjArray::Write(name, option, bufsize);
+    ResetMyCanDelete(this);
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mbase/MStatusArray.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MStatusArray.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MStatusArray.h	(revision 17960)
@@ -0,0 +1,70 @@
+#ifndef MARS_MStatusArray
+#define MARS_MStatusArray
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class TClass;
+class TCanvas;
+class TVirtualPad;
+
+class MStatusDisplay;
+
+class MStatusArray : public TObjArray
+{
+private:
+    enum {
+        kMyCanDelete = BIT(30)
+    };
+
+    void     SetCleanup(TObject *obj) const;
+    Bool_t   RecursiveDelete(TVirtualPad *p, const char id=0) const;
+
+    void     SetCanDelete(const TCollection *list) const;
+    void     SetMyCanDelete(const TCollection *list) const;
+    void     ResetMyCanDelete(const TCollection *list) const;
+    void     PrintObjectsInPad(const TCollection *list, const TString &name, Int_t lvl=0) const;
+    TObject *FindObjectInPad(TVirtualPad *pad, const char *object, TClass *base) const;
+    void     RecursiveRemove(TCollection *c, TObject *o);
+
+public:
+    MStatusArray() : TObjArray() { }
+    MStatusArray(const MStatusDisplay &d);
+    ~MStatusArray();
+
+    TObject *DisplayIn(Option_t *o=0) const;         // *MENU*
+    void     DisplayIn(MStatusDisplay &d, const char *tab=0) const;
+    TObject *Display() const { return DisplayIn(); } // *MENU*
+
+    TCanvas *FindCanvas(const char *name) const;
+
+    TObject *FindObjectInCanvas(const char *object, const char *base, const char *canvas) const;
+    TObject *FindObjectInCanvas(const char *object, const char *canvas) const;
+
+    void Print(Option_t *o="") const;
+    void Print(const Option_t *o, Option_t *) const         { Print(o); }
+    void Print(const Option_t *o, Int_t) const              { Print(o); }
+    void Print(const Option_t *o, const char*, Int_t) const { Print(o); }
+    void Print(const Option_t *o, TPRegexp&, Int_t) const   { Print(o); }
+
+    TObject *FindObject(const char *object, const char *base) const;
+    TObject *FindObject(const char *object) const;
+    TObject *FindObject(const TObject *) const { return 0; }
+
+    Int_t Read(const char *name=NULL);
+    Int_t Write(const char *name=0, Int_t option=0, Int_t bufsize=0) const;
+    Int_t Write(const char *name=0, Int_t option=0, Int_t bufsize=0)
+    {
+        return const_cast<const MStatusArray*>(this)->Write(name, option, bufsize);
+    }
+
+    void EnableTH1Workaround(const TCollection *list=0) const;
+    void Delete(Option_t *option="");
+
+    void RecursiveRemove(TObject *o);
+
+    ClassDef(MStatusArray, 0) // Helper class for status display
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MStatusDisplay.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MStatusDisplay.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MStatusDisplay.cc	(revision 17960)
@@ -0,0 +1,3566 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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()/SaveAsPNG() or SaveAsC().
+// Direct printing to the default printer (via lpr) can be done by
+// PrintPS().
+//
+// 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 <errno.h>
+#include <stdlib.h>               // mktemp (Ubunto 8.10)
+
+#include <fstream>                // fstream
+
+#include <TH1.h>                  // TH1::AddDirectory
+#include <TPDF.h>                 // TPDF
+#include <TSVG.h>                 // TSVG
+#include <TEnv.h>                 // TEnv
+#include <TLine.h>                // TLine
+#include <TMath.h>
+#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 <TRegexp.h>              // TRegexp
+#include <TThread.h>              // TThread::Self()
+#include <TBrowser.h>             // TBrowser
+#include <TObjArray.h>            // TObjArray
+#include <TPostScript.h>          // TPostScript
+#include <TMethodCall.h>          // TMethodCall
+
+#include <TInterpreter.h>         // gInterpreter
+
+#include <TGTab.h>                // TGTab
+#include <TGLabel.h>              // TGLabel
+#include <TG3DLine.h>             // TGHorizontal3DLine
+#include <TGButton.h>             // TGPictureButton
+#include <TGTextView.h>           // TGTextView
+#include <TGComboBox.h>           // TGComboBox
+#include <TGStatusBar.h>          // TGStatusBar
+#include <TGFileDialog.h>         // TGFileDialog
+#include <TGProgressBar.h>        // TGHProgressBar
+#include <TGTextEditDialogs.h>    // TGPrintDialog
+#include <TRootEmbeddedCanvas.h>  // TRootEmbeddedCanvas
+
+#include "MString.h"
+
+#include "MLog.h"                 // MLog
+#include "MLogManip.h"            // inf, warn, err
+
+#include "MGList.h"               // MGList
+#include "MGMenu.h"               // MGMenu, TGMenu
+#include "MSearch.h"              // MSearch
+#include "MParContainer.h"        // MParContainer::GetDescriptor
+#include "MStatusArray.h"         // MStatusArray
+
+#if ROOT_VERSION_CODE <= ROOT_VERSION(5,22,00)
+#include "../mhbase/MH.h"
+#endif
+
+#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
+
+// --------------------------------------------------------------------------
+
+TGCompositeFrame *MStatusDisplay::GetTabContainer(const char *name) const
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,03,05)
+    if (!fTab)
+        return 0;
+
+   TGFrameElement *el;
+   TGTabElement *tab = 0;
+   TGCompositeFrame *comp = 0;
+
+   TIter next(fTab->GetList());
+   next();           // skip first container
+
+   while ((el = (TGFrameElement *) next())) {
+      el = (TGFrameElement *) next();
+      comp = (TGCompositeFrame *) el->fFrame;
+      next();
+      tab = (TGTabElement *)el->fFrame;
+      if (name == tab->GetText()->GetString()) {
+         return comp;
+      }
+   }
+
+   return 0;
+#else
+   return fTab ? fTab->GetTabContainer(name) : 0;
+#endif
+}
+
+TGTabElement *MStatusDisplay::GetTabTab(const char *name) const
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,03,05)
+    if (!fTab)
+        return 0;
+
+   TGFrameElement *el;
+   TGTabElement *tab = 0;
+
+   TIter next(fTab->GetList());
+   next();           // skip first container
+
+   while ((el = (TGFrameElement *) next())) {
+      next();
+      tab = (TGTabElement *)el->fFrame;
+      if (name == tab->GetText()->GetString()) {
+         return tab;
+      }
+   }
+
+   return 0;
+#else
+   return fTab ? fTab->GetTabTab(name) : 0;
+#endif
+}
+// --------------------------------------------------------------------------
+
+
+// --------------------------------------------------------------------------
+//
+// Add menu bar to the GUI
+//
+void MStatusDisplay::AddMenuBar()
+{
+    //
+    // File Menu
+    //
+    MGPopupMenu *filemenu = new MGPopupMenu(gClient->GetDefaultRoot());
+    filemenu->AddEntry("New &Canvas",       kFileCanvas);
+    filemenu->AddEntry("New &Browser",      kFileBrowser);
+    filemenu->AddEntry("New &Tab",          kFileTab);
+    filemenu->AddSeparator();
+
+    const TString fname(MString::Format("Save %s.", gROOT->GetName()));
+    MGPopupMenu *savemenu = new MGPopupMenu(gClient->GetDefaultRoot());
+    savemenu->AddEntry(MString::Format("%s&ps",  fname.Data()),  kFileSaveAsPS);
+    savemenu->AddEntry(MString::Format("%sp&df", fname.Data()),  kFileSaveAsPDF);
+    savemenu->AddEntry(MString::Format("%s&svg", fname.Data()),  kFileSaveAsSVG);
+    savemenu->AddSeparator();
+    savemenu->AddEntry(MString::Format("%sp&ng", fname.Data()),  kFileSaveAsPNG);
+    savemenu->AddEntry(MString::Format("%s&gif", fname.Data()),  kFileSaveAsGIF);
+    savemenu->AddEntry(MString::Format("%s&jpg", fname.Data()),  kFileSaveAsJPG);
+    savemenu->AddEntry(MString::Format("%s&xpm", fname.Data()),  kFileSaveAsXPM);
+    savemenu->AddEntry(MString::Format("%s&tiff",fname.Data()),  kFileSaveAsTIFF);
+    savemenu->AddEntry(MString::Format("%s&bmp", fname.Data()),  kFileSaveAsBMP);
+    savemenu->AddEntry(MString::Format("%sx&ml", fname.Data()),  kFileSaveAsXML);
+    savemenu->AddEntry(MString::Format("%scs&v", fname.Data()),  kFileSaveAsCSV);
+    savemenu->AddSeparator();
+    savemenu->AddEntry(MString::Format("%s&C",    fname.Data()), kFileSaveAsC);
+    savemenu->AddEntry(MString::Format("%s&root", fname.Data()), kFileSaveAsRoot);
+    savemenu->AddEntry(MString::Format("%s&root (plain)", fname.Data()), kFileSaveAsPlainRoot);
+    savemenu->Associate(this);
+
+    filemenu->AddEntry("&Open...",          kFileOpen);
+    filemenu->AddPopup("&Save", savemenu);
+    filemenu->AddEntry("Save &As...",       kFileSaveAs);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("&Reset",            kFileReset);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("&Print",            kFilePrint);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("C&lose",            kFileClose);
+    filemenu->AddEntry("E&xit",             kFileExit);
+    filemenu->Associate(this);
+
+    //
+    // Tab Menu
+    //
+    MGPopupMenu *tabmenu = new MGPopupMenu(gClient->GetDefaultRoot());
+    tabmenu->AddEntry("Next [&+]",          kTabNext);
+    tabmenu->AddEntry("Previous [&-]",      kTabPrevious);
+    tabmenu->AddSeparator();
+
+    const TString fname2(MString::Format("Save %s-i.", gROOT->GetName()));
+    MGPopupMenu *savemenu2 = new MGPopupMenu(gClient->GetDefaultRoot());
+    savemenu2->AddEntry(MString::Format("%s&ps",  fname2.Data()),  kTabSaveAsPS);
+    savemenu2->AddEntry(MString::Format("%sp&df", fname2.Data()),  kTabSaveAsPDF);
+    savemenu2->AddEntry(MString::Format("%s&svg", fname2.Data()),  kTabSaveAsSVG);
+    savemenu2->AddSeparator();
+    savemenu2->AddEntry(MString::Format("%sp&ng", fname2.Data()),  kTabSaveAsPNG);
+    savemenu2->AddEntry(MString::Format("%s&gif", fname2.Data()),  kTabSaveAsGIF);
+    savemenu2->AddEntry(MString::Format("%s&jpg", fname2.Data()),  kTabSaveAsJPG);
+    savemenu2->AddEntry(MString::Format("%s&xpm", fname2.Data()),  kTabSaveAsXPM);
+    savemenu2->AddEntry(MString::Format("%s&tiff",fname2.Data()),  kTabSaveAsTIFF);
+    savemenu2->AddEntry(MString::Format("%s&bmp", fname2.Data()),  kTabSaveAsBMP);
+    savemenu2->AddEntry(MString::Format("%sx&ml", fname2.Data()),  kTabSaveAsXML);
+    savemenu2->AddEntry(MString::Format("%scs&v", fname2.Data()),  kTabSaveAsCSV);
+    savemenu2->AddSeparator();
+    savemenu2->AddEntry(MString::Format("%s&C",    fname2.Data()), kTabSaveAsC);
+    savemenu2->AddEntry(MString::Format("%s&root", fname2.Data()), kTabSaveAsRoot);
+    savemenu2->Associate(this);
+
+    tabmenu->AddPopup("&Save", savemenu2);
+    tabmenu->AddEntry("Save tab &As...",    kTabSaveAs);
+    tabmenu->AddSeparator();
+    tabmenu->AddEntry("&Remove",            kTabRemove);
+    tabmenu->AddSeparator();
+    tabmenu->AddEntry("&Print",             kTabPrint);
+    tabmenu->Associate(this);
+
+    //
+    // Loop Menu
+    //
+    MGPopupMenu *loopmenu = new MGPopupMenu(gClient->GetDefaultRoot());
+    loopmenu->AddEntry("&Pause",       kLoopPause);
+    loopmenu->AddEntry("Single S&tep", kLoopStep);
+    loopmenu->AddSeparator();
+    loopmenu->AddEntry("&Stop",  kLoopStop);
+    loopmenu->Associate(this);
+
+    loopmenu->DisableEntry(kLoopStep);
+
+    //
+    // Loop Menu
+    //
+    MGPopupMenu *sizemenu = new MGPopupMenu(gClient->GetDefaultRoot());
+    sizemenu->AddEntry("Fit to 640x&480",   kSize640);
+    sizemenu->AddEntry("Fit to 768x&576",   kSize768);
+    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 1152x&864",  kSize1152);
+    sizemenu->AddEntry("Fit to 1280x&1024", kSize1280);
+    sizemenu->AddEntry("Fit to 1400x1050",  kSize1400);
+    sizemenu->AddEntry("Fit to 1600x1200",  kSize1600);
+    sizemenu->AddEntry("Fit to &Desktop",   kSizeOptimum);
+    sizemenu->Associate(this);
+
+    //
+    // Log Menu
+    //
+    MGPopupMenu *logmenu = new MGPopupMenu(gClient->GetDefaultRoot());
+    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->AddSeparator();
+    logmenu->AddEntry("&Print",         kLogPrint);
+    logmenu->Associate(this);
+
+    //
+    // Menu Bar
+    //
+    TGLayoutHints *layitem = new TGLayoutHints(kLHintsNormal, 0, 4, 0, 0);
+    fList->Add(layitem);
+
+    fMenuBar = new MGMenuBar(this, 1, 1, kHorizontalFrame);
+    fMenuBar->AddPopup("&File", filemenu, layitem);
+    fMenuBar->AddPopup("Lo&g",  logmenu,  layitem);
+    fMenuBar->AddPopup("&Size", sizemenu, layitem);
+    fMenuBar->AddPopup("&Tab",  tabmenu,  layitem);
+    fMenuBar->AddPopup("&Loop", loopmenu, layitem);
+    fMenuBar->BindKeys(this);
+    AddFrame(fMenuBar);
+
+    //
+    // 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(savemenu);
+    fList->Add(savemenu2);
+    fList->Add(filemenu);
+    fList->Add(loopmenu);
+    fList->Add(sizemenu);
+    fList->Add(fMenuBar);
+    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 list of tabs
+
+    TGComboBox *filter = new TGComboBox(f, kTabs);
+    fList->Add(filter);
+    filter->Associate(this);
+    filter->AddEntry("-=MARS=-", 0);
+    filter->Select(0);
+
+
+    TGLayoutHints *lay3 = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 10, 5);
+    fList->Add(lay3);
+    f->AddFrame(filter, lay3);
+
+    // Add MARS version
+    TGLabel *l = new TGLabel(f, MString::Format("Official Release: V%s", MARSVER));
+    fList->Add(l);
+
+    filter->SetWidth(5*l->GetWidth()/4);
+    filter->SetHeight(4*l->GetHeight()/3);
+    filter->GetListBox()->SetHeight(l->GetHeight()*16);
+
+    TGLayoutHints *layb = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 5, 5);
+    fList->Add(layb);
+    f->AddFrame(l, layb);
+
+    // Add root version
+    l = new TGLabel(f, MString::Format("Using ROOT v%s", ROOT_RELEASE));
+    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
+    l = new TGLabel(f, TDatime().AsString());
+    fList->Add(l);
+    f->AddFrame(l, lay);
+
+    // Add copyright notice
+    l = new TGLabel(f, MString::Format("(c) MARS Software Development, 2000-%d", TDatime().GetYear()));
+    fList->Add(l);
+    f->AddFrame(l, layb);
+
+    TGLayoutHints *layc = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 0, 5);
+    fList->Add(layc);
+
+    const char *txt = "<< Thomas Bretz >>";
+    l = new TGLabel(f, txt);
+    fList->Add(l);
+    f->AddFrame(l, layc);
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds the logbook tab to the GUI if it was not added previously.
+//
+// The logbook is updated four times a second only if the tab is visible.
+//
+// You can redirect an output to a MLog-logstream by calling SetLogStream().
+// To disable redirction call SetLogStream(NULL)
+//
+// if enable==kFALSE the stdout is disabled/enabled. Otherwise stdout
+// is ignored.
+//
+void MStatusDisplay::SetLogStream(MLog *log, Bool_t enable)
+{
+    if (gROOT->IsBatch())
+        return;
+
+    if (log && fLogBox==NULL)
+    {
+        fLogIdx = fTab->GetNumberOfTabs();
+
+        // Create Tab1
+        TGCompositeFrame *f = AddRawTab("-Logbook-");//fTab->AddTab("-Logbook-");
+
+        // Create Text View
+        fLogBox = new MGTextView(f, 1, 1); // , -1, 0, TGFrame::GetDefaultFrameBackground());
+        if (fFont)
+            fLogBox->SetFont(fFont);
+        //fLogBox->Associate(this);
+
+        // Add List box to the tab
+        TGLayoutHints *lay = new TGLayoutHints(kLHintsNormal|kLHintsExpandX|kLHintsExpandY,2,2,2,2);
+        f->AddFrame(fLogBox, lay);
+
+        // layout and map tab
+        Layout();
+        MapSubwindows();
+
+        // make it visible
+        // FIXME: This is a workaround, because TApplication::Run is not
+        //        thread safe against ProcessEvents. We assume, that if
+        //        we are not in the Main-Thread ProcessEvents() is
+        //        called by the TApplication Event Loop...
+        if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+            gClient->ProcessEventsFor(fTab);
+    }
+
+    if (log)
+    {
+        fLog = log;
+
+        log->SetOutputGui(fLogBox, kTRUE);
+        log->EnableOutputDevice(MLog::eGui);
+        if (!enable)
+            log->DisableOutputDevice(MLog::eStdout);
+
+        fLogTimer.Start();
+    }
+    else
+    {
+        fLogTimer.Stop();
+
+        fLog->DisableOutputDevice(MLog::eGui);
+        fLog->SetOutputGui(NULL);
+        if (!enable)
+            fLog->EnableOutputDevice(MLog::eStdout);
+
+        fLog = &gLog;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the Tabs and the predifined Tabs to the GUI
+//
+void MStatusDisplay::AddTabs()
+{
+    fTab = new TGTab(this, 300, 300);
+
+    AddMarsTab();
+
+    // Add fTab to Frame
+    TGLayoutHints *laytabs = new TGLayoutHints(kLHintsNormal|kLHintsExpandX|kLHintsExpandY, 5, 5, 5);
+    AddFrame(fTab, laytabs);
+
+    fList->Add(fTab);
+    fList->Add(laytabs);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the progress bar to the GUI. The Progress Bar range is set to
+// (0,1) as default.
+//
+void MStatusDisplay::AddProgressBar()
+{
+    TGLayoutHints *laybar=new TGLayoutHints(kLHintsExpandX, 5, 5, 5, 5);
+    fList->Add(laybar);
+
+    fBar=new TGHProgressBar(this);
+    fBar->SetRange(0, 1);
+    fBar->ShowPosition();
+    AddFrame(fBar, laybar);
+    fList->Add(fBar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the progress bar position between 0 and 1. The Progress bar range
+// is assumed to be (0,1)
+//
+void MStatusDisplay::SetProgressBarPosition(Float_t p, Bool_t upd)
+{
+    if (!gClient || gROOT->IsBatch())
+        return;
+
+    fBar->SetPosition(p);
+    if (upd)
+        gClient->ProcessEventsFor(fBar);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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[] = {38-2, 62-8, 10};
+
+    fStatusBar->SetParts(p, 3);
+
+    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::SetStatusLine(const char *txt, Int_t i)
+{
+    if (gROOT->IsBatch())
+        return;
+    fStatusBar->SetText(txt, i);
+
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        gClient->ProcessEventsFor(fStatusBar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Display information about the name of a container
+//
+void MStatusDisplay::SetStatusLine2(const MParContainer &cont)
+{
+    SetStatusLine2(MString::Format("%s: %s", cont.GetDescriptor().Data(), cont.GetTitle()));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get TGPopupMenu as defined by name from fMenuBar
+//
+TGPopupMenu *MStatusDisplay::GetPopup(const char *name)
+{
+    if (!fMenuBar)
+        return 0;
+
+    TGPopupMenu *m = fMenuBar->GetPopup(name);
+    if (!m)
+    {
+        *fLog << warn << name << " doesn't exist in menu bar." << endl;
+        return 0;
+    }
+
+    return m;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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.
+//
+// You can give either width or height. (Set the value not given to -1)
+// The other value is calculated accordingly. If width and height are
+// given height is ignored. If width=height=0 an optimum size from
+// the desktop size is calculated.
+//
+// Update time default: 10s
+//
+MStatusDisplay::MStatusDisplay(Int_t w, Int_t h, Long_t t)
+: TGMainFrame((TGWindow*)((gClient?gClient:new TGClient),NULL), 1, 1), fName("MStatusDisplay"), fLog(&gLog), fBar(NULL), 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()
+
+    // Make sure that the display is removed via RecursiveRemove
+    // from whereever possible.
+    SetBit(kMustCleanup);
+
+    //
+    // 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)
+    //
+    // In newer root versions gClient!=NULL in batch mode!
+    if (!gClient || !gClient->GetRoot() || gROOT->IsBatch()) // BATCH MODE
+    {
+        Resize(644, 484);
+        return;
+    }
+
+    AddMenuBar();
+    AddUserFrame();
+    AddTabs();
+    AddProgressBar();
+    AddStatusBar();
+
+    //
+    // set the smallest and biggest size of the Main frame
+    // and move it to its appearance position
+    SetWMSizeHints(566, 476, 2048, 1536, 1, 1);
+    MoveResize(rand()%100+566, rand()%100+476, 566, 476);
+    if (h>0)
+        SetDisplayHeight(h);
+    if (w>0)
+        SetDisplayWidth(w);
+    if (w==0 && h==0)
+        SetOptimumSize();
+
+    //
+    // Now do an automatic layout of the widgets and display the window
+    //
+    Layout();
+    MapSubwindows();
+
+    SetWindowName("Status Display");
+    SetIconName("Status Display");
+
+    MapWindow();
+
+    UpdateMemory();
+
+    // 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()
+{
+    fTimer.Stop();
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,01)
+    fTab = NULL; // See HandleEvent
+#endif
+
+    //
+    // Delete object from global object table so it cannot
+    // be deleted by chance a second time
+    //
+    gInterpreter->DeleteGlobal(this);
+
+    //
+    // This is a possibility for the user to check whether this
+    // object has already been deleted. It has been added
+    // to the list in the constructor.
+    //
+    gROOT->GetListOfSpecials()->Remove(this);
+
+    SetLogStream(NULL);
+
+    //
+    // Delete the list of objects corresponding to this object
+    //
+    delete fList;
+
+    //
+    // Delete the list of canvases used in batch mode
+    // instead of the Root Embedded Canvases in the TGTab
+    //
+    delete fBatch;
+
+    //
+    // Delete the font used for the logging window
+    //
+    if (fFont)
+        gVirtualX->DeleteFont(fFont);
+
+    //
+    // Delete mutex
+    //
+    delete fMutex;
+}
+
+// --------------------------------------------------------------------------
+//
+// Takes a TGCompositeFrame as argument. Searches for the first
+// TRootEmbeddedCanvas which is contained by it and returns a pointer
+// to the corresponding TCanvas. If it isn't found NULL is returned.
+//
+TRootEmbeddedCanvas *MStatusDisplay::GetEmbeddedCanvas(TGCompositeFrame &cf)
+{
+    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)
+{
+    TRootEmbeddedCanvas *ec = GetEmbeddedCanvas(cf);
+    return ec ? ec->GetCanvas() : NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the range of tabs containing valid canvases for the condition
+// num.
+//
+void MStatusDisplay::GetCanvasRange(Int_t &from, Int_t &to, Int_t num) const
+{
+    const Int_t max  = gROOT->IsBatch() ? fBatch->GetSize()+1 : fTab->GetNumberOfTabs();
+
+    from = num<0 ?   1 : num;
+    to   = num<0 ? max : num+1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetCanvas of the i-th Tab.
+//
+TCanvas *MStatusDisplay::GetCanvas(int i) const
+{
+    if (gROOT->IsBatch())
+        return (TCanvas*)fBatch->At(i-1);
+
+    if (i<0 || i>=fTab->GetNumberOfTabs())
+    {
+        *fLog << warn << "MStatusDisplay::GetCanvas: Out of range." << endl;
+        return NULL;
+    }
+
+    return GetCanvas(*fTab->GetTabContainer(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns j-th pad of the i-th Tab. 
+// Sets the pad to fill an entire window.
+//
+// This function can be used if single pad's out of an MStatusDisplay 
+// have to be stored to file. 
+//
+// ATTENTION: This function modifies the requested tab in MStatusDisplay itself!
+//
+TVirtualPad *MStatusDisplay::GetFullPad(const Int_t i, const Int_t j)
+{
+    if (!GetCanvas(i))
+    {
+        *fLog << warn << "MStatusDisplay::GetFullPad: i-th canvas not dound." << endl;
+        return NULL;
+    }
+
+    TVirtualPad *vpad = GetCanvas(i)->GetPad(j);
+    if (!vpad)
+    {
+        *fLog << warn << "MStatusDisplay::GetFullPad: Pad is out of range." << endl;
+        return NULL;
+    }
+
+    vpad->SetPad(0.,0.,1.,1.);
+    return vpad;
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches for a TRootEmbeddedCanvas in the TGCompositeFramme of the
+// Tab with the name 'name'. Returns the corresponding TCanvas or
+// NULL if something isn't found.
+//
+TCanvas *MStatusDisplay::GetCanvas(const TString &name) const
+{
+    if (gROOT->IsBatch())
+        return (TCanvas*)fBatch->FindObject(name);
+
+    TGFrameElement *f;
+    TIter Next(fTab->GetList());
+    while ((f=(TGFrameElement*)Next()))
+    {
+        TObject *frame = f->fFrame;
+        if (!frame->InheritsFrom(TGTabElement::Class()))
+            continue;
+
+        TGTabElement *tab = (TGTabElement*)frame;
+        if (tab->GetString()==name)
+            break;
+    }
+
+    // Search for the next TGCompositeFrame in the list
+    while ((f=(TGFrameElement*)Next()))
+    {
+        TObject *frame = f->fFrame;
+        if (frame->InheritsFrom(TGCompositeFrame::Class()))
+            return GetCanvas(*(TGCompositeFrame*)frame);
+    }
+
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls TCanvas::cd(), for the canvas returned by GetCanvas.
+//
+Bool_t MStatusDisplay::CdCanvas(const TString &name)
+{
+    TCanvas *c = GetCanvas(name);
+    if (!c)
+        return kFALSE;
+
+    c->cd();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of user added tabs (not that in batch mode this
+// exclude tabs without a canvas)
+//
+Int_t MStatusDisplay::GetNumTabs() const
+{
+    return gROOT->IsBatch() ? fBatch->GetEntries() : fTab->GetNumberOfTabs()-1;
+}
+
+TGCompositeFrame *MStatusDisplay::AddRawTab(const char *name)
+{
+    // Add new tab
+    TGCompositeFrame *f = fTab->AddTab(name);
+
+    TGComboBox *box = (TGComboBox*)fList->FindWidget(kTabs);
+    box->AddEntry(name, box->GetListBox()->GetNumberOfEntries());
+
+    // layout and map new tab
+    Layout();
+    MapSubwindows();
+    Layout();
+
+    UpdateMemory();
+
+    // 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 << inf3 << "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)
+    {
+        // Find the object which will get picked by the GetObjectInfo
+        // due to buffer overflows in many root-versions
+        // in TH1 and TProfile we have to work around and implement
+        // our own GetObjectInfo which make everything a bit more
+        // complicated.
+#if ROOT_VERSION_CODE > ROOT_VERSION(5,22,00)
+        SetStatusLine2(selected->GetObjectInfo(px,py));
+#else
+        TObjLink *link=0;
+        static_cast<TPad*>(gPad)->Pick(px, py, link);
+
+        const TObject *o = link ? link->GetObject() : 0;
+        if (o)
+            SetStatusLine2(MH::GetObjectInfo(px, py, *o));
+#endif
+    }
+
+    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, const char *title)
+{
+    /*
+    if (GetCanvas(name))
+    {
+        *fLog << warn;
+        *fLog << "WARNING - A canvas '" << name << "' is already existing in the Status Display." << endl;
+        *fLog << "          This can cause unexpected crahes!" << endl;
+    }*/
+
+    gROOT->SetSelectedPad(0);
+
+    if (gROOT->IsBatch())
+    {
+        // 4 = 2*default border width of a canvas
+        const UInt_t cw = GetWidth();
+        const UInt_t ch = 2*cw/3 + 25; // 25: Menu, etc
+
+        // The constructor of TCanvas adds the canvas to the global list
+        // of canvases gROOT->GetListOfCanvases(). If a canvas with an
+        // identical name exists already in this list, the canvas is
+        // deleted. In normal operation this might make sense and doesn't harm
+        // because the embedded canvases behave different.
+        // By creating the canvas without a name it is made sure that no
+        // older canvas/tab vanished silently from the system (deleted from
+        // the construtor). To make the handling of our canvases nevertheless
+        // work well the name is set later. The list of canvases is also
+        // part of the list of cleanups, thus fBatch need not to be added
+        // to the list of cleanups.
+        TCanvas *c = new TCanvas("", title?title:"", -cw, ch);
+        c->SetName(name);
+        c->SetFillColor(10); // White
+        c->SetFrameBorderMode(0);
+        c->SetBorderMode(0);
+        fBatch->Add(c);
+
+        *fLog << inf3 << "Adding Canvas '" << name << "' (" << c->GetWw() << "x";
+        *fLog << c->GetWh() << ", TCanvas=" << c << ")" << endl;
+
+        // Remove the canvas from the global list to make sure it is
+        // not found by gROOT->FindObject
+        //gROOT->GetListOfCanvases()->Remove(c);
+        //gROOT->GetListOfCleanups()->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(), kSunkenFrame);
+    f->AddFrame(ec, fLayCanvas);
+    fList->Add(ec);
+
+    // set background and border mode of the canvas
+    TCanvas &c = *ec->GetCanvas();
+
+    if (title)
+        c.SetTitle(title);
+
+    c.SetFillColor(10); // White
+    c.SetFrameBorderMode(0);
+    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*)");
+
+    // Make sure that root itself doesn't try to call GetObjectInfo
+    // This is now handled from EventsInfo. This is necessary
+    // due to the buffer overflow bug in GetObjectInfo of
+    // TProfile and TH1
+    c.ResetBit(TCanvas::kShowEventStatus);
+
+    // Remove the canvas from the global list to make sure it is
+    // not found by gROOT->FindObject
+    //gROOT->GetListOfCanvases()->Remove(&c);
+    //gROOT->GetListOfCleanups()->Add(&c);
+
+    TGComboBox *box = (TGComboBox*)fList->FindWidget(kTabs);
+    box->AddEntry(name, box->GetListBox()->GetNumberOfEntries());
+
+    // layout and map new tab
+    Layout();          // seems to layout the TGCompositeFrame
+    MapSubwindows();   // maps the TGCompositeFrame
+    Layout();          // layout the embedded canvas in the frame
+
+    UpdateMemory();
+
+    // 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 << inf3 << "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;
+
+    //
+    // 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
+        const TString str = MString::Format("%ld", (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;
+    }
+
+    TCanvas *c=GetCanvas(*f);
+    if (!c)
+        return;
+
+    const TString name  = c->GetName();
+    const TString title = c->GetTitle();
+
+    if (!gROOT->IsBatch())
+        fStatusBar->SetText(title, 0);
+
+    // It seems that we cannot use this because an update
+    // initiated by a gui event can interfere with the regular
+    // update from the timer and then ProcessEvents will
+    // end in an infinite loop.
+    // SetStatusLine1(title);
+
+
+    //
+    // 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
+    //
+    const Int_t rc = fMutex->TryLock();
+    if (rc==13)
+        gLog << warn << "MStatusDisplay::UpdateTab - mutex is already locked by this thread." << endl;
+
+    if (rc)
+        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();
+}
+
+TString MStatusDisplay::PrintDialog(TString &p, TString &c, TString &t, const char *ext)
+{
+    // If not in batch mode open a user dialog
+    if (!gROOT->IsBatch())
+    {
+        char *cprinter = StrDup(p);
+        char *ccmd     = StrDup(c);
+
+        Int_t rc=0;
+        new TGPrintDialog(fClient->GetRoot(), this, 400, 150, &cprinter, &ccmd, &rc);
+        if (rc)
+        {
+            p = cprinter; // default has been changed
+            c = ccmd;
+        }
+
+        delete [] cprinter;
+        delete [] ccmd;
+
+        if (!rc)
+            return "";
+    }
+
+    if (c.Contains("%f") && ext)
+    {
+        // Get temporary file name
+        TString name = "mars";
+
+        FILE *f = gSystem->TempFileName(name, t);
+        if (!f)
+        {
+            *fLog << warn << "MStatusDisplay::PrintDialog: Couldn't create temporary file in " << t << endl;
+            SetStatusLine2("failed!");
+            return "";
+        }
+        fclose(f);
+
+        // remove temp file
+        gSystem->Unlink(name);
+        name += ".";
+        name += ext;
+
+        t = name;
+    }
+
+    // compile command
+    TString cmd(c);
+
+    // if sprinter.IsNull we assume that everything around %p can
+    // be omitted and the program uses some kind of default
+    if (p.IsNull())
+    {
+        TString sub;
+        while (1)
+        {
+            sub = TString(cmd(TRegexp(" .*%p.* "))).Strip(TString::kBoth);
+            if (sub.IsNull())
+                break;
+
+            cmd.ReplaceAll(sub, "");
+        }
+    }
+
+    cmd.ReplaceAll("%p", p);
+    cmd.ReplaceAll("%f", t);
+
+    return cmd;
+}
+
+// --------------------------------------------------------------------------
+//
+// Saves the given canvas (pad) or all pads (num<0) as a temporary
+// postscript file and prints it.
+//
+// The default command line c is: lpr -P%p %f
+//   %p: printer name
+//   %f: temporary file name
+//
+// The default printer name p is: <empty>
+//
+// Both can be changed in .rootrc by:
+//   PrintPS.Printer
+//   PrintPS.Command
+//
+// Ant the location of the temporary file t can by changed by
+//   Print.Directory
+// the default is the system default directory (normally /tmp)
+//
+Int_t MStatusDisplay::PrintPS(Int_t num, const char *p, const char *c, const char *t)
+{
+    static TString sprinter = gEnv->GetValue("PrintPS.Printer", p&&*p?p:"");
+    static TString scmd     = gEnv->GetValue("PrintPS.Command", c&&*c?c:"lpr -P%p %f");
+
+    TString tmp = gEnv->GetValue("Print.Directory", t&&*t?t:gSystem->TempDirectory());
+
+    TString cmd = PrintDialog(sprinter, scmd, tmp, "ps");
+    if (cmd.IsNull())
+        return 0;
+
+    // set status lines
+    SetStatusLine1("Printing...");
+    SetStatusLine2("");
+
+    // print to temporary file
+    const Int_t pages = SaveAsPS(num, tmp);
+
+    // check
+    if (!pages)
+    {
+        *fLog << warn << "MStatusDisplay::Print: Sorry, couldn't save file as temporary postscript!" << endl;
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    // execute command
+    *fLog << dbg << "Executing: " << cmd << endl;
+    gSystem->Exec(cmd);
+
+    // remove temporary file
+    gSystem->Unlink(tmp);
+
+    SetStatusLine2(MString::Format("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;
+
+    // Repair the "Workaround" being in the RecursiveRemove list
+    // but not in a list checked by gROOT->FindObject
+    //gROOT->GetListOfCleanups()->Remove(c);
+    //gROOT->GetListOfCanvases()->Add(c);
+
+    // FIXME: Due to our workaround this is necessary for a successfull deletion
+    //c->cd();
+
+    const TString name(c->GetName());
+
+    f->RemoveFrame(ec);
+    delete fList->Remove(ec);
+
+    fTab->RemoveTab(i);
+    fTab->SetTab(0);
+
+    TGComboBox *box = (TGComboBox*)fList->FindWidget(kTabs);
+    box->RemoveEntry(i);
+    for (int j=i; j<box->GetListBox()->GetNumberOfEntries(); j++)
+    {
+        TGTextLBEntry *entry = (TGTextLBEntry *)box->GetListBox()->Select(j+1, kFALSE);
+        box->AddEntry(entry->GetText()->GetString(), j);
+        box->RemoveEntry(j+1);
+    }
+    box->GetListBox()->Select(0);
+
+    // Looks strange...
+    // const Int_t n = fTab->GetNumberOfTabs();
+    // fTab->SetTab(i<=n-1 ? i : i-1);
+
+    // layout and map new tab
+    Layout();          // seems to layout the TGCompositeFrame
+    MapSubwindows();   // maps the TGCompositeFrame
+    Layout();          // layout the embedded canvas in the frame
+
+    UpdateMemory();
+
+    // 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 you encounter unexpected crashes here, check if
+    // a canvas is existing twice in the list or has been
+    // deleted by accident. (Check AddTab)
+
+    if (gROOT->IsBatch())
+        return (Bool_t)fBatch->FindObject(c);
+
+    for (int i=1; i<fTab->GetNumberOfTabs(); i++)
+        if (c==GetCanvas(i))
+            return kTRUE;
+    return kFALSE;
+}
+
+/*
+    if (...)
+       fMenu->AddPopup("&CaOs", fCaOs, NULL);
+    else
+       fMenu->RemovePopup("CaOs");
+    fMenu->Resize(fMenu->GetDefaultSize());
+    MapSubwindows();
+    MapWindow();
+ */
+
+void MStatusDisplay::Reset()
+{
+    if (gROOT->IsBatch())
+    {
+        fBatch->Delete();
+        return;
+    }
+
+    for (int i=fTab->GetNumberOfTabs()-1; i>0; i--)
+        RemoveTab(i);
+}
+
+Bool_t MStatusDisplay::SaveLogAsPS(const char *n) const
+{
+    TString name(n);
+    AddExtension(name, "ps");
+
+    // Code taken from TGTextEdit::Print
+    const TString pipe = MString::Format("a2ps -o%s", name.Data());
+    FILE *p = gSystem->OpenPipe(pipe, "w");
+    if (!p)
+    {
+        *fLog << err << "ERROR - Couldn't open pipe " << pipe << ": " << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    TGText *text = fLogBox->GetText();
+
+    char   *buf1, *buf2;
+    Long_t  len;
+    ULong_t i = 0;
+    TGLongPosition pos;
+
+    Bool_t rc = kTRUE;
+
+    pos.fX = pos.fY = 0;
+    while (pos.fY < text->RowCount())
+    {
+        len = text->GetLineLength(pos.fY);
+        buf1 = text->GetLine(pos, len);
+        buf2 = new char[len + 2];
+        strncpy(buf2, buf1, (UInt_t)len);
+        buf2[len]   = '\n';
+        buf2[len+1] = '\0';
+        while (buf2[i] != '\0') {
+            if (buf2[i] == '\t') {
+                ULong_t j = i+1;
+                while (buf2[j] == 16 && buf2[j] != '\0')
+                    j++;
+                strcpy(buf2+i+1, buf2+j);
+            }
+            i++;
+        }
+
+        len = sizeof(char)*(strlen(buf2)+1);
+
+        const size_t ret = fwrite(buf2, len, 1, p);
+        delete [] buf1;
+        delete [] buf2;
+
+        if (ret!=1)
+        {
+            *fLog << err << "ERROR - fwrite to pipe " << pipe << " failed: " << strerror(errno) << endl;
+            rc = kFALSE;
+            break;
+        }
+
+        pos.fY++;
+    }
+    gSystem->ClosePipe(p);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the log text.
+//
+// The default command line c is: a2ps -P%p
+//   %p: printer name
+//
+// The default printer name p is: <empty>
+//
+// Both can be changed in .rootrc by:
+//   PrintText.Printer
+//   PrintText.Command
+//
+Bool_t MStatusDisplay::PrintLog(const char *p, const char *c)
+{
+    static TString sprinter = gEnv->GetValue("PrintText.Printer", p&&*p?p:"");
+    static TString scmd     = gEnv->GetValue("PrintText.Command", c&&*c?c:"a2ps -P%p");
+
+    TString tmp;
+    TString cmd = PrintDialog(sprinter, scmd, tmp);
+    if (cmd.IsNull())
+        return kFALSE;
+
+    // set status lines
+    SetStatusLine1("Printing...");
+    SetStatusLine2("");
+
+    // print to temporary file
+    if (!SaveLogAsPS(cmd))
+    {
+        *fLog << warn << "MStatusDisplay::PrintLog: Sorry, couldn't create postscript!" << endl;
+        SetStatusLine2("Failed!");
+        return kFALSE;
+    }
+
+    // execute command
+    *fLog << dbg << "Executing: " << cmd << endl;
+    gSystem->Exec(cmd);
+
+    SetStatusLine2("Done.");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_COMMAND, kCM_MENU  messages
+//
+Bool_t MStatusDisplay::ProcessMessageCommandMenu(Long_t id)
+{
+    switch (id)
+    {
+    case kLoopPause:
+        {
+            TGPopupMenu *m = GetPopup("Loop");
+            if (!m)
+                return kTRUE;
+
+            if (fStatus==kLoopNone)
+            {
+                fStatus = (Status_t)kLoopPause;
+                m->CheckEntry(kLoopPause);
+                m->EnableEntry(kLoopStep);
+                return kTRUE;
+            }
+            if (fStatus==kLoopPause)
+            {
+                fStatus = (Status_t)kLoopNone;
+                m->UnCheckEntry(kLoopPause);
+                m->DisableEntry(kLoopStep);
+                return kTRUE;
+            }
+        }
+        return kTRUE;
+
+    case kLoopStep:
+        fStatus = (Status_t)kLoopStep;
+        return kTRUE;
+
+    case kLoopStop:
+    case kFileClose:
+    case kFileExit:
+        if (id==kFileExit || id==kFileClose)
+            if (Close())
+                delete this;
+        fStatus = (Status_t)id;
+        return kTRUE;
+
+    case kFileCanvas:
+        new TCanvas;
+        return kTRUE;
+
+    case kFileBrowser:
+        new TBrowser;
+        return kTRUE;
+
+    case kFileTab:
+        AddTab(MString::Format("%d", fTab->GetNumberOfTabs()));
+        return kTRUE;
+
+    case kFileReset:
+        Reset();
+        return kTRUE;
+
+    case kFileOpen:
+        Open();
+        return kTRUE;
+
+    case kFileSaveAs:
+        SaveAs();
+        return kTRUE;
+
+    case kFileSaveAsPS:
+        SaveAsPS();
+        return kTRUE;
+
+    case kFileSaveAsPDF:
+        SaveAsPDF();
+        return kTRUE;
+
+    case kFileSaveAsSVG:
+        SaveAsSVG();
+        return kTRUE;
+
+    case kFileSaveAsPNG:
+        SaveAsPNG();
+        return kTRUE;
+
+    case kFileSaveAsGIF:
+        SaveAsGIF();
+        return kTRUE;
+
+    case kFileSaveAsXPM:
+        SaveAsXPM();
+        return kTRUE;
+
+    case kFileSaveAsJPG:
+        SaveAsJPG();
+        return kTRUE;
+
+    case kFileSaveAsTIFF:
+        SaveAsTIFF();
+        return kTRUE;
+
+    case kFileSaveAsBMP:
+        SaveAsBMP();
+        return kTRUE;
+
+    case kFileSaveAsXML:
+        SaveAsXML();
+        return kTRUE;
+
+    case kFileSaveAsCSV:
+        SaveAsCSV();
+        return kTRUE;
+
+    case kFileSaveAsC:
+        SaveAsC();
+        return kTRUE;
+
+    case kFileSaveAsRoot:
+        SaveAsRoot();
+        return kTRUE;
+
+    case kFileSaveAsPlainRoot:
+        SaveAsPlainRoot(kTRUE);
+        return kTRUE;
+
+    case kFilePrint:
+        PrintPS();
+        return kTRUE;
+
+    case kTabSaveAs:
+        SaveAs(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsPS:
+        SaveAsPS(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsPDF:
+        SaveAsPDF(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsSVG:
+        SaveAsSVG(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsPNG:
+        SaveAsPNG(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsGIF:
+        SaveAsGIF(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsXPM:
+        SaveAsXPM(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsJPG:
+        SaveAsJPG(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsTIFF:
+        SaveAsTIFF(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsBMP:
+        SaveAsBMP(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsXML:
+        SaveAsXML(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsCSV:
+        SaveAsCSV(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsC:
+        SaveAsC(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsPlainRoot:
+        SaveAsPlainRoot(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsRoot:
+        SaveAsRoot(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabPrint:
+        PrintPS(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:
+        SetDisplaySize(640, 480);
+        return kTRUE;
+    case kSize768:  
+        SetDisplaySize(768, 576);
+        return kTRUE;
+    case kSize800:  
+        SetDisplaySize(800, 600);
+        return kTRUE;
+    case kSize960:  
+        SetDisplaySize(960, 720);
+        return kTRUE;
+    case kSize1024: 
+        SetDisplaySize(1024, 768);
+        return kTRUE;
+    case kSize1152:
+        SetDisplaySize(1152, 864);
+        return kTRUE;
+    case kSize1280: 
+        SetDisplaySize(1280, 1024);
+        return kTRUE;
+    case kSize1400:
+        SetDisplaySize(1400, 1050);
+        return kTRUE;
+    case kSize1600:
+        SetDisplaySize(1600, 1200);
+        return kTRUE;
+    case kSizeOptimum:
+        SetOptimumSize();
+        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(MString::Format("%s.log", gROOT->GetName())))
+        {
+            *fLog << "done." << endl;
+            SetStatusLine2("done.");
+        }
+        else
+        {
+            *fLog << "failed!" << endl;
+            SetStatusLine2("Failed!");
+        }
+        return kTRUE;
+
+    case kLogAppend:
+        SetStatusLine1("Appending log...");
+        SetStatusLine2("");
+        *fLog << inf << "Appending log... " << flush;
+        if (fLogBox->GetText()->Append(MString::Format("%s.log", gROOT->GetName())))
+        {
+            *fLog << "done." << endl;
+            SetStatusLine2("done.");
+        }
+        else
+        {
+            *fLog << "failed!" << endl;
+            SetStatusLine2("Failed!");
+        }
+        return kTRUE;
+
+    case kLogPrint:
+        PrintLog();
+        return kTRUE;
+#ifdef DEBUG
+    default:
+        cout << "Command-Menu #" << id << endl;
+#endif
+    }
+    return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_COMMAND messages
+//
+Bool_t MStatusDisplay::ProcessMessageCommand(Long_t submsg, Long_t mp1, Long_t mp2)
+{
+    switch (submsg)
+    {
+    case kCM_MENU: // 1
+        return ProcessMessageCommandMenu(mp1); // mp2=userdata
+    case kCM_TAB:  // 8
+        /*
+         for (int i=0; i<fTab->GetNumberOfTabs(); i++)
+         fTab->GetTabContainer(i)->UnmapWindow();
+         */
+        UpdateTab(fTab->GetTabContainer(mp1));
+        //fTab->GetTabContainer(mp1)->MapWindow();
+
+        /*
+        if (mp1>0)
+            fMenu->AddPopup("&CaOs", fCaOs, NULL);
+        else
+            fMenu->RemovePopup("CaOs");
+        fMenu->Resize(fMenu->GetDefaultSize());
+        MapSubwindows();
+        MapWindow();
+        */
+        return kTRUE;
+    case kCM_COMBOBOX: // 7
+        if (mp1==kTabs)
+            fTab->SetTab(mp2);
+        return kTRUE;
+#ifdef DEBUG
+    case kCM_MENUSELECT: // 2
+        cout << "Command-Menuselect #" << mp1 << " (UserData=" << (void*)mp2 << ")" << endl;
+        return kTRUE;
+
+    case kCM_BUTTON: // 3
+        cout << "Command-Button." << endl;
+        return kTRUE;
+
+    case kCM_CHECKBUTTON: // 4
+        cout << "Command-CheckButton." << endl;
+        return kTRUE;
+
+    case kCM_RADIOBUTTON: // 5
+        cout << "Command-RadioButton." << endl;
+        return kTRUE;
+
+    case kCM_LISTBOX: // 6
+        cout << "Command-Listbox #" << mp1 << " (LineId #" << mp2 << ")" << endl;
+        return kTRUE;
+    default:
+        cout << "Command: " << "Submsg:" << submsg << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_TEXTVIEW messages
+//
+Bool_t MStatusDisplay::ProcessMessageTextview(Long_t /*submsg*/, Long_t /*mp1*/, Long_t /*mp2*/)
+{
+    // kC_TEXTVIEW, kTXT_ISMARKED, widget id, [true|false]                  //
+    // kC_TEXTVIEW, kTXT_DATACHANGE, widget id, 0                           //
+    // kC_TEXTVIEW, kTXT_CLICK2, widget id, position (y << 16) | x)         //
+    // kC_TEXTVIEW, kTXT_CLICK3, widget id, position (y << 16) | x)         //
+    // kC_TEXTVIEW, kTXT_F3, widget id, true                                //
+    // kC_TEXTVIEW, kTXT_OPEN, widget id, 0                                 //
+    // kC_TEXTVIEW, kTXT_CLOSE, widget id, 0                                //
+    // kC_TEXTVIEW, kTXT_SAVE, widget id, 0                                 //
+#ifdef DEBUG
+    switch (submsg)
+    {
+    case kTXT_ISMARKED:
+        cout << "Textview-IsMarked #" << mp1 << " " << (mp2?"yes":"no") << endl;
+        return kTRUE;
+
+    case kTXT_DATACHANGE:
+        cout << "Textview-DataChange #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_CLICK2:
+        cout << "Textview-Click2 #" << mp1 << " x=" << (mp2&0xffff) << " y= " << (mp2>>16) << endl;
+        return kTRUE;
+
+    case kTXT_CLICK3:
+        cout << "Textview-Click3 #" << mp1 << " x=" << (mp2&0xffff) << " y= " << (mp2>>16) << endl;
+        return kTRUE;
+
+    case kTXT_F3:
+        cout << "Textview-F3 #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_OPEN:
+        cout << "Textview-Open #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_CLOSE:
+        cout << "Textview-Close #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_SAVE:
+        cout << "Textview-Save #" << mp1 << endl;
+        return kTRUE;
+
+    default:
+        cout << "Textview: " << "Submsg:" << submsg << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+    }
+#endif
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_USER messages
+//
+Bool_t MStatusDisplay::ProcessMessageUser(Long_t submsg, Long_t mp1, Long_t mp2)
+{
+    // kS_START, case sensitive | backward<<1, char *txt
+    switch (submsg)
+    {
+    case kS_START:
+        fLogBox->Search((char*)mp2, !(mp1&2>>1), mp1&1);
+        return kTRUE;
+#ifdef DEBUG
+    default:
+        cout << "User: " << "Submsg:" << submsg << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the messages from the GUI
+//
+Bool_t MStatusDisplay::ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2)
+{
+    // Can be found in WidgetMessageTypes.h
+#ifdef DEBUG
+    cout << "Msg: " << GET_MSG(msg) << " Submsg:" << GET_SUBMSG(msg);
+    cout << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    switch (GET_MSG(msg))
+    {
+    case kC_COMMAND:  // 1
+        return ProcessMessageCommand(GET_SUBMSG(msg), mp1, mp2);
+
+    case kC_TEXTVIEW: // 9
+        return ProcessMessageTextview(GET_SUBMSG(msg), mp1, mp2);
+
+    case kC_USER:     // 1001
+        return ProcessMessageUser(GET_SUBMSG(msg), mp1, mp2);
+    }
+#ifdef DEBUG
+    cout << "Msg: " << GET_MSG(msg) << " Submsg:" << GET_SUBMSG(msg);
+    cout << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    return kTRUE;
+}
+
+Bool_t MStatusDisplay::Close()
+{
+    // Got close message for this MainFrame. Calls parent CloseWindow()
+    // (which destroys the window) and terminate the application.
+    // The close message is generated by the window manager when its close
+    // window menu item is selected.
+
+    // CloseWindow must be overwritten because otherwise CloseWindow
+    // and the destructor are calling DestroyWindow which seems to be
+    // in conflict with the TRootEmbeddedCanvas.
+
+    // FIXME: Make sure that the Status Display is deleted from every
+    //        where (eg Eventloop) first!
+
+    //gLog << dbg << fName << " is on heap: " << (int)IsOnHeap() << endl;
+
+    if (TestBit(kExitLoopOnExit) || TestBit(kExitLoopOnClose))
+    {
+        //gLog << dbg << "CloseWindow() calling ExitLoop." << endl;
+        gSystem->ExitLoop();
+    }
+
+    if (fIsLocked<=0 && IsOnHeap())
+        return kTRUE;
+
+    fStatus = kFileExit;
+    return kFALSE;
+}
+
+void MStatusDisplay::CloseWindow()
+{
+    if (Close())
+        delete this;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the memory display in the status bar
+//
+void MStatusDisplay::UpdateMemory() const
+{
+    const TString path = MString::Format("/proc/%d/status", gSystem->GetPid());
+    if (gSystem->AccessPathName(path, kFileExists))
+        return;
+
+    TEnv env(path);
+    const UInt_t kb = env.GetValue("VmSize", 0);
+    if (kb==0)
+        return;
+
+    char type = 'k';
+    Float_t val = kb;
+
+    if (val>999)
+    {
+        type = 'M';
+        val /= 1000;
+    }
+    if (val>999)
+    {
+        type = 'G';
+        val /= 1000;
+    }
+    const TString txt = MString::Format("%.1f%c", val, type);
+    fStatusBar->SetText(txt, 2);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+    UpdateMemory();
+
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Find an object in a canvas (uses MStatusArray as helper)
+//
+void MStatusDisplay::PrintContent(Option_t *o) const
+{
+    MStatusArray(*this).Print(o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Find an object in a canvas (uses MStatusArray as helper)
+//
+TObject *MStatusDisplay::FindObjectInCanvas(const char *obj, const char *base, const char *canv) const
+{
+    return MStatusArray(*this).FindObjectInCanvas(obj, base, canv);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draws a clone of a canvas into a new canvas. Taken from TCanvas.
+//
+void MStatusDisplay::DrawClonePad(TCanvas &newc, TCanvas &oldc) const
+{
+    //copy pad attributes
+    newc.Range(oldc.GetX1(),oldc.GetY1(),oldc.GetX2(),oldc.GetY2());
+    newc.SetTickx(oldc.GetTickx());
+    newc.SetTicky(oldc.GetTicky());
+    newc.SetGridx(oldc.GetGridx());
+    newc.SetGridy(oldc.GetGridy());
+    newc.SetLogx(oldc.GetLogx());
+    newc.SetLogy(oldc.GetLogy());
+    newc.SetLogz(oldc.GetLogz());
+    newc.SetBorderSize(oldc.GetBorderSize());
+    newc.SetBorderMode(oldc.GetBorderMode());
+    ((TAttLine&)oldc).Copy((TAttLine&)newc);
+    ((TAttFill&)oldc).Copy((TAttFill&)newc);
+    ((TAttPad&)oldc).Copy((TAttPad&)newc);
+
+    // This must be there: Otherwise GetDrawOption() won't work
+    TVirtualPad *padsav = gPad;
+    oldc.cd();
+
+    const Bool_t store = TH1::AddDirectoryStatus();
+    TH1::AddDirectory(kFALSE);
+
+    //copy primitives
+    TObject *obj;
+    TIter next(oldc.GetListOfPrimitives());
+    while ((obj=next()))
+    {
+        // Old line - I think it is not necessary anymore because of the cd()
+        //gROOT->SetSelectedPad(&newc);
+
+        // Now make a clone of the object
+        TObject *clone = obj->Clone();
+
+        // Clone also important bits (FIXME: Is this correct)
+        clone->SetBit(obj->TestBits(kCannotPick|kNoContextMenu));
+
+        // Now make sure that the clones are deleted at a later time
+        clone->SetBit(kCanDelete|kMustCleanup);
+
+        // FIXME: This is a workaround for the problem with the MAstroCatalog in
+        // MHFalseSource. It doesn't harm. We'll still try to find the reason
+        //if (clone->IsA()==TPad::Class())
+        //    gROOT->GetListOfCleanups()->Add(clone);
+
+        // Add the clone and its draw-option to the current pad
+        TVirtualPad *save2 = gPad;
+        gPad = &oldc; // Don't do this before Clone()!
+        newc.GetListOfPrimitives()->Add(clone, obj->GetDrawOption());
+        gPad = save2;
+    }
+    newc.Modified();
+    newc.Update();
+
+    TH1::AddDirectory(store);
+
+    padsav->cd();
+}
+
+// --------------------------------------------------------------------------
+//
+// Display the contexts of a TObjArray in the display (all canvases)
+//
+Bool_t MStatusDisplay::Display(const TObjArray &list, const char *tab)
+{
+    TIter Next(&list);
+
+    TObject *o=Next();
+    if (!o)
+    {
+        *fLog << err << "MStatusDisplay::Display: No entry in TObjArray." << endl;
+        return kFALSE;
+    }
+
+    // The first entry in the list is a TNamed which is expected to
+    // contain the status display title.
+    fTitle = o->GetTitle();
+
+    TCanvas *c;
+    while ((c=(TCanvas*)Next()))
+        //if (!GetCanvas(c->GetName()))
+        if (c->InheritsFrom(TCanvas::Class()))
+            if (!tab || c->GetName()==(TString)tab)
+                DrawClonePad(AddTab(c->GetName(), c->GetTitle()), *c);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads the contents of a saved MStatusDisplay from a file.
+//
+Int_t MStatusDisplay::Read(const char *name, const char *tab)
+{
+    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;
+
+    Int_t n = list.Read(name);
+
+    //
+    // If no status display was found with this name try to find canvases
+    // in the file and display them instead.
+    //
+    if (n==0)
+    {
+        // Either read the title from the file or create our own
+        TNamed *title=0;
+        gFile->GetObject("Title", title); // FIXME: Is the list allowed to take ownership?
+        list.Add(title ? title : new TNamed(GetName(), GetTitle()));
+
+        const Bool_t store = TH1::AddDirectoryStatus();
+        TH1::AddDirectory(kFALSE);
+
+        TIter Next(gFile->GetListOfKeys());
+        TObject *key = 0;
+        while ((key=Next()))
+        {
+            MStatusArray *arr=0;
+            gFile->GetObject(key->GetName(), arr);
+            if (arr)
+            {
+                Display(*arr, tab);
+                n++;
+                continue;
+            }
+
+            if (tab && key->GetName()!=(TString)tab)
+                continue;
+
+            TCanvas *c=0;
+            gFile->GetObject(key->GetName(), c);
+
+            // If key doesn't correspond to a TCanvas create a new canvas
+            // and draw the object itself instead.
+            if (!c)
+            {
+                TObject *obj = gFile->Get(key->GetName());
+
+                if (MParContainer::Overwrites(TObject::Class(), *obj, "Draw") ||
+                    MParContainer::Overwrites(TObject::Class(), *obj, "Paint"))
+                {
+                    AddTab(key->GetName(), key->GetTitle());
+                    obj->SetBit(kCanDelete);
+                    obj->Draw();
+                }
+                // FIXME: Is the object deleted?
+                continue;
+            }
+
+            // Add the canvas to the list
+            const TString name  = c->GetName();
+            const TString title = c->GetTitle();
+            if (title.IsNull() || name==title)
+                c->SetTitle(gFile->GetName());
+            list.Add(c);
+        }
+
+        TH1::AddDirectory(store);
+
+        if (list.GetEntries()<=1)
+        {
+            *fLog << warn << "MStatusDisplay::Read: No drawable objects read from " << gFile->GetName() << endl;
+            return 0;
+        }
+
+        *fLog << inf << "MStatusDisplay: " << list.GetEntries()-1 << " canvases directly read from file." << endl;
+    }
+
+
+    if (!Display(list, tab))
+    {
+        *fLog << err << "MStatusDisplay::Display: No entries found." << endl;
+        return 0;
+    }
+
+    if (n==0)
+        return list.GetEntries();
+
+    *fLog << inf << "MStatusDisplay: Key " << name << " with " << n << " keys read from file." << endl;
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all canvases to the MStatusArray
+//
+void MStatusDisplay::FillArray(MStatusArray &list, Int_t num) const
+{
+    Int_t from, to;
+    GetCanvasRange(from, to, num);
+
+    TCanvas *c;
+    for (int i=from; i<to; i++)
+        if ((c = GetCanvas(i)))
+            list.Add(c);
+}
+
+// --------------------------------------------------------------------------
+//
+// Writes the contents of a MStatusDisplay to a file.
+//
+Int_t MStatusDisplay::Write(Int_t num, const char *name, Option_t *opt) const
+{
+    if (!gFile)
+    {
+        *fLog << warn << "MStatusDisplay::Write: No file found. Please create a TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsOpen())
+    {
+        *fLog << warn << "MStatusDisplay::Write: File not open. Please open the TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsWritable())
+    {
+        *fLog << warn << "MStatusDisplay::Write: File not writable." << endl;
+        return 0;
+    }
+
+    if (num==0)
+    {
+        *fLog << warn << "MStatusDisplay::Write: Tab doesn't contain an embedded Canvas... skipped." << endl;
+        return 0;
+    }
+
+    if (!gROOT->IsBatch() && num>=fTab->GetNumberOfTabs())
+    {
+        *fLog << warn << "MStatusDisplay::Write: Tab doesn't exist... skipped." << endl;
+        return 0;
+    }
+    if (gROOT->IsBatch() && num>fBatch->GetSize())
+    {
+        *fLog << warn << "MStatusDisplay::Write: Tab doesn't exist... skipped." << endl;
+        return 0;
+    }
+
+    Int_t n = 0; // Number of keys written
+
+    TNamed named("Title", fTitle.Data());
+
+    if (TString(opt)=="plain")
+    {
+        // Get canvas range to store
+        Int_t from, to;
+        GetCanvasRange(from, to, num);
+
+        n += named.Write();
+
+        TCanvas *c;
+        for (int i=from; i<to; i++)
+            if ((c = GetCanvas(i)))
+                n += c->Write();
+    }
+    else
+    {
+        // Be careful: So far Display() assumes that the TNamed
+        // is the first entry in the list
+        MStatusArray list;
+        list.Add(&named);
+
+        FillArray(list, num);
+
+        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);
+}
+
+// --------------------------------------------------------------------------
+//
+// If the filename name doesn't end with ext, ext is added to the end.
+// If name.IsNull() "status" is assumed and the a number (>0) is added
+// as "status-6".
+// The extension is returned.
+//
+const TString &MStatusDisplay::AddExtension(TString &name, const TString &ext, Int_t num) const
+{
+    if (name.IsNull())
+    {
+        name = gROOT->GetName();
+        if (num>0)
+        {
+            name += "-";
+            name += num;
+        }
+    }
+
+    if (name.EndsWith("."+ext))
+        return ext;
+
+    name += ".";
+    name += ext;
+
+    return 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");
+
+    TString tmp(name+"XXXXXX");
+
+    // FIXME: Use mkstemp instead
+    if (!mktemp(const_cast<char*>(tmp.Data())))
+    {
+        *fLog << err << "ERROR - MStatusDisplay::UpdatePSHeader: mktemp failed." << endl;
+        return;
+    }
+
+    ifstream fin(name);
+    ofstream fout(tmp);
+    if (!fout)
+    {
+        *fLog << err << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return;
+    }
+
+    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(tmp, name);
+}
+
+// --------------------------------------------------------------------------
+//
+void MStatusDisplay::PSToolsRange(TVirtualPS &vps, Float_t psw, Float_t psh) const
+{
+    if (vps.InheritsFrom(TPostScript::Class()))
+        static_cast<TPostScript&>(vps).Range(psw, psh);
+    // if (vps.InheritsFrom(TPDF::Class()))
+    //     static_cast<TPDF&>(vps).Range(psw*0.69, psh*0.69);
+    // if (vps.InheritsFrom(TSVG::Class()))
+    //     static_cast<TSVG&>(vps).Range(psw, psh);
+}
+
+// --------------------------------------------------------------------------
+//
+void MStatusDisplay::PSToolsTextNDC(TVirtualPS &vps, Double_t u, Double_t v, const char *string) const
+{
+    if (vps.InheritsFrom(TPostScript::Class()))
+        static_cast<TPostScript&>(vps).TextNDC(u, v, string);
+    if (vps.InheritsFrom(TPDF::Class()))
+        static_cast<TPDF&>(vps).TextNDC(u, v, string);
+    // if (vps.InheritsFrom(TSVG::Class()))
+    //    static_cast<TSVG&>(vps).TextNDC(u, v, string);
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MStatusDisplay::InitWriteDisplay(Int_t num, TString &name, const TString &ext)
+{
+    SetStatusLine1(MString::Format("Writing %s file...",ext.Data()));
+    SetStatusLine2("Please be patient!");
+
+    if (!CheckTabForCanvas(num))
+    {
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    AddExtension(name, ext, num);
+
+    if (num<0)
+        *fLog << inf << "Open " << ext << "-File: " << name << endl;
+
+    return num;
+}
+
+// --------------------------------------------------------------------------
+//
+TCanvas *MStatusDisplay::InitWriteTab(Int_t num, TString &name)
+{
+    const Int_t i = TMath::Abs(num);
+
+    TCanvas *c = GetCanvas(i);
+    if (!c)
+    {
+        if (num<0)
+            *fLog << inf << " - ";
+        *fLog << "Tab #" << i << " doesn't contain an embedded Canvas... skipped." << endl;
+        return 0;
+    }
+
+    SetStatusLine2(MString::Format("Tab #%d", i));
+
+    //
+    // Paint canvas into root file
+    //
+    if (num<0 && !name.IsNull())
+    {
+        Bool_t found = kFALSE;
+        if (name.Index("%%%%name%%%%")>=0)
+        {
+            name.ReplaceAll("%%name%%", c->GetName());
+            found = kTRUE;
+        }
+
+        if (name.Index("%%%%title%%%%")>=0)
+        {
+            name.ReplaceAll("%%title%%", c->GetTitle());
+            found = kTRUE;
+        }
+
+        if (name.Index("%%%%tab%%%%")>=0)
+        {
+            name.ReplaceAll("%%tab%%", MString::Format("%d", i));
+            found = kTRUE;
+        }
+
+        if (!found)
+            name.Insert(name.Last('.'), MString::Format("-%d", i));
+    }
+
+    if (num<0)
+        *fLog << inf << " - ";
+    *fLog << inf << "Writing Tab #" << i;
+
+    if (!name.IsNull())
+        *fLog << " to " << name;
+
+    *fLog << ": " << c->GetName() << "... " << flush;
+
+    return c;
+}
+
+// This is a stupid workaround to get rid of the damned clipping
+// of the text. Who the hell needs clipping?
+class MyCanvas : public TCanvas
+{
+public:
+    void Scale(Double_t val)
+    {
+        fAbsXlowNDC = -val;
+        fAbsYlowNDC = -val;
+        fAbsWNDC    = 1+2*val;
+        fAbsHNDC    = 1+2*val;
+    }
+};
+
+// --------------------------------------------------------------------------
+//
+// Write some VGF (vector graphics format). Currently PS, PDF and SVG
+// is available. Specified by ext.
+//
+// In case of num<0 all tabs are written into the VGF 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 SaveAsVGF(name, ext)
+//
+// 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::SaveAsVGF(Int_t num, TString name, const TString addon, const TString ext)
+{
+    num = InitWriteDisplay(num, name, ext);
+    if (num==0)
+        return 0;
+
+    TPad       *padsav = (TPad*)gPad;
+    TVirtualPS *psave  = gVirtualPS;
+
+    TDatime d;
+
+    Int_t type = -1;
+
+    TVirtualPS *ps =0;
+    if (!ext.CompareTo("ps", TString::kIgnoreCase))
+    {
+        gStyle->SetColorModelPS(1);
+        ps = new TPostScript(name, 112);
+        type = 1;
+    }
+    if (!ext.CompareTo("pdf", TString::kIgnoreCase))
+    {
+        ps = new TPDF(name, 112);
+        type = 2;
+    }
+    if (!ext.CompareTo("svg", TString::kIgnoreCase))
+    {
+        ps = new TSVG(name, 112);
+        type = 3;
+    }
+
+    if (!ps)
+    {
+        *fLog << err << "Extension " << ext << " unknown..." << endl;
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    ps->SetBit(TPad::kPrintingPS);
+    if (type==1)
+        ps->PrintFast(13, "/nan {1} def ");
+
+    gVirtualPS = ps;
+
+    //
+    // Create some GUI elements for a page legend
+    //
+    TLine line;
+
+    int page = 1;
+
+    //
+    // Maintain tab numbers
+    //
+    Int_t from, to;
+    GetCanvasRange(from, to, num);
+
+    for (int i=from; i<to; i++)
+    {
+        TCanvas *c = InitWriteTab(num<0?-i:i);
+        if (c==0)
+            continue;
+
+        //
+        // Init page and page size, make sure, that the canvas in the file
+        // has the same Aspect Ratio than on the screen.
+        //
+        if (type==1 || i>from)
+            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;
+
+        PSToolsRange(*ps, psw, psh);
+
+        //
+        // Clone canvas and change background color and schedule for
+        // deletion
+        //
+
+        //const Bool_t store = c->IsBatch();
+        //c->SetBatch(kTRUE);
+        c->Paint();
+        //c->SetBatch(store);
+
+        //
+        // Change/fix the canvas coordinate system for the overlaying text.
+        // This is necessary because root clip everything away which is
+        // outside a predefined area, which is (0,0)/(1,1)
+        //
+        const Double_t height = 0.015;  // Text height
+        const Double_t off    = 0.005;  // Line offset from text
+
+        const Double_t bot = height+off;
+        const Double_t top = 1-bot;
+
+        static_cast<MyCanvas*>(c)->Scale(bot);
+
+        // If gPad is not set to c all follwing commands will
+        // get the wrong numbers for alignment
+        gPad = c;
+
+        // Separator Lines
+        line.PaintLineNDC(0.01, top, 0.99, top);
+        line.PaintLineNDC(0.01, bot, 0.99, bot);
+
+        //
+        // Print overlaying text (NDC = %)
+        //
+        // align phi col font size (11=left top)
+        const TString txt(addon.IsNull() ? fTitle : addon);
+
+        // Text Attributes
+        TAttText(11, 0, kBlack, 22, height).Copy(*ps);
+
+        // Text on top
+        ps->SetTextAlign(11); // left bottom
+        PSToolsTextNDC(*ps, 0.01, top+off, c->GetName());
+
+        ps->SetTextAlign(21); // cent bottom
+        PSToolsTextNDC(*ps, 0.50, top+off, TString("MARS V" MARSVER " - Modular Analysis and Reconstruction Software - ")+d.AsString());
+
+        ps->SetTextAlign(31); // right bottom
+        PSToolsTextNDC(*ps, 0.99, top+off, MString::Format("Page No.%i (%i)", page++, i));
+
+        // Text on bottom
+        ps->SetTextAlign(13); // left top
+        PSToolsTextNDC(*ps, 0.01, bot-off, c->GetTitle());
+
+        ps->SetTextAlign(23); // cent top
+        PSToolsTextNDC(*ps, 0.50, bot-off, txt);
+
+        ps->SetTextAlign(33); // right top
+        PSToolsTextNDC(*ps, 0.99, bot-off, MString::Format("(c) 2000-%d, Thomas Bretz", TDatime().GetYear()));
+
+        static_cast<MyCanvas*>(c)->Scale(0);
+
+        //
+        // Finish drawing page
+        //
+        *fLog << "done." << endl;
+    }
+
+    gPad = NULL; // Important!
+
+    ps->Close();
+    delete ps;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    if (type==1)
+    {
+        SetStatusLine2("Updating header of PS file...");
+
+        if (num<0)
+            *fLog << inf3 << " - Updating header of PS file... " << flush;
+        UpdatePSHeader(name);
+        if (num<0)
+            *fLog << inf3 << "done." << endl;
+    }
+#endif
+
+    gVirtualPS = psave;
+    if (padsav)
+        padsav->cd();
+
+    if (num<0)
+        *fLog << inf << "done." << endl;
+
+    SetStatusLine2(MString::Format("Done (%dpages)", page-1));
+
+    return page-1;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MStatusDisplay::SaveAsImage(Int_t num, TString name, TImage::EImageFileTypes type)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    if (gROOT->IsBatch())
+    {
+        *fLog << warn << "Sorry, writing image-files is not available in batch mode." << endl;
+        return 0;
+    }
+#endif
+
+    TString ext;
+    switch (type)
+    {
+    case TImage::kXpm:
+    case TImage::kZCompressedXpm:  ext = "xpm";     break;
+    case TImage::kPng:             ext = "png";     break;
+    case TImage::kJpeg:            ext = "jpg";     break;
+    case TImage::kGif:             ext = "gif";     break;
+    case TImage::kTiff:            ext = "tiff";    break;
+    case TImage::kBmp:             ext = "bmp";     break;
+    case TImage::kXml:             ext = "xml";     break;
+    //case TImage::kGZCompressedXpm: ext = "xpm.gz";  break;
+    //case TImage::kPpm:             ext = "ppm";     break;
+    //case TImage::kPnm:             ext = "pnm";     break;
+    //case TImage::kIco:             ext = "ico";     break;
+    //case TImage::kCur:             ext = "cur";     break;
+    //case TImage::kXcf:             ext = "xcf";     break;
+    //case TImage::kXbm:             ext = "xbm";     break;
+    //case TImage::kFits:            ext = "fits";    break;
+    //case TImage::kTga:             ext = "tga";     break;
+    default:
+        *fLog << warn << "Sorry, unknown or unsupported file type..." << endl;
+        return 0;
+    }
+
+    num = InitWriteDisplay(num, name, ext);
+    if (num==0)
+        return 0;
+
+    TPad *padsav = (TPad*)gPad;
+
+    Int_t counter = 0;
+
+    //
+    // Maintain tab numbers
+    //
+    Int_t from, to;
+    GetCanvasRange(from, to, num);
+
+    for (int i=from; i<to; i++)
+    {
+        TString writename(name);
+
+        TCanvas *c = InitWriteTab(num<0 ? -i : i, writename);
+        if (!c)
+            continue;
+
+        //
+        // Paint canvas into root file
+        //
+
+        // TImage *img = TImage::Create();
+        // img->FromPad(c);
+        // img->WriteImage(writename, type);
+        // delete img;
+
+        // FIXME: Not all file types are supported by Print()
+        c->Print(writename);
+
+        if (num<0)
+            *fLog << "done." << endl;
+
+        counter++;
+    }
+
+    if (padsav)
+        padsav->cd();
+
+    *fLog << inf << "done." << endl;
+
+    SetStatusLine2("Done.");
+
+    return counter>0;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MStatusDisplay::SaveAsC(Int_t num, TString name)
+{
+    num = InitWriteDisplay(num, name, "C");
+    if (num==0)
+        return kFALSE;
+
+    TPad *padsav = (TPad*)gPad;
+
+    Int_t counter = 0;
+
+    //
+    // Maintain tab numbers
+    //
+    Int_t from, to;
+    GetCanvasRange(from, to, num);
+
+    for (int i=from; i<to; i++)
+    {
+        TString writename(name);
+
+        TCanvas *c = InitWriteTab(num<0 ? -i : i, writename);
+        if (!c)
+            continue;
+
+        //
+        // Clone canvas and change background color and schedule for
+        // deletion
+        //
+        c->SaveSource(writename, "");
+
+        if (num<0)
+            *fLog << "done." << endl;
+
+        counter++;
+    }
+
+    if (padsav)
+        padsav->cd();
+
+    *fLog << inf << "done." << endl;
+
+    SetStatusLine2("Done.");
+
+    return counter>0;
+}
+
+// --------------------------------------------------------------------------
+//
+// In case of num<0 all tabs are written into a root file. As plain
+// TCanvas objects if plain==kTRUE otherwise in a MStatusArray. 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 SaveAsRoot(name)
+//
+Int_t MStatusDisplay::SaveAsRoot(Int_t num, TString name, Bool_t plain)
+{
+    num = InitWriteDisplay(num, name, "root");
+    if (num==0)
+        return -1;
+
+    TFile *fsave = gFile;
+    TFile file(name, "RECREATE", GetTitle(), 9);
+    const Int_t keys = Write(num, "MStatusDisplay", plain ? "plain" : "");
+    gFile = fsave;
+
+    SetStatusLine2("Done.");
+
+    return keys;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MStatusDisplay::SaveAsCSV(Int_t num, TString name, Char_t delim)
+{
+    num = InitWriteDisplay(num, name, "csv");
+    if (num==0)
+        return kFALSE;
+
+    gSystem->ExpandPathName(name);
+
+    ofstream fout(name);
+    if (!fout)
+    {
+        *fLog << err << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    fout << 0 << delim << GetName() << delim << GetTitle() << endl;
+
+    Int_t from, to;
+    GetCanvasRange(from, to, num);
+
+    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;
+        }
+
+        fout << i << delim << c->GetName() << delim << c->GetTitle() << endl;
+    }
+
+    SetStatusLine2("Done.");
+
+    return kTRUE;
+}
+
+/*
+Bool_t MStatusDisplay::SaveAsCSV(Int_t num, TString name)
+{
+    num = InitWriteDisplay(num, name, "csv");
+    if (num==0)
+        return kFALSE;
+
+    gSystem->ExpandPathName(name);
+
+    ofstream fout(name);
+    if (!fout)
+    {
+        *fLog << err << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    fout << "<?xml version=\"1.0\"?>" << endl;
+    fout << "<display name='" << GetName() << "'>" << endl;
+    fout << "   <file>" << name << "</file>" << endl;
+    fout << "   <status>" << endl;
+    fout << "      <name>" << GetName() << "</name>" << endl;
+    fout << "      <title>" << GetTitle() << "</title>" << endl;
+    fout << "   </status>" << endl;
+    fout << "   <tabs>" << endl;
+
+    fout << 0 << delim << GetName() << delim << GetTitle() << endl;
+
+    Int_t from, to;
+    GetCanvasRange(from, to, num);
+
+    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;
+        }
+
+        fout << "      <tab index='" << i << "'>" << endl;
+        fout << "         <index>" << i << "</index>" << endl;
+        fout << "         <name>" << c->GetName()  << "</name>" << endl;
+        fout << "         <title>" << c->GetName()  << "</title>" << endl;
+        fout << "      </tab>" << endl;
+    }
+
+    fout << "  </tabs>" << endl;
+    fout << "</display>" << endl;
+
+    SetStatusLine2("Done.");
+
+    return kTRUE;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+void MStatusDisplay::SaveAs(const char *c, const Option_t *o) const
+{
+#if ROOT_VERSION_CODE >= ROOT_VERSION(5,18,00)
+    TGObject::SaveAs(c, o);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Determin File type to save file as by extension. Allowed extensions are:
+//   root, ps, pdf, svg, gif, png, jpg, xpm, C
+//
+// returns -1 if file type is unknown. Otherwise return value of SaveAs*
+//
+Int_t MStatusDisplay::SaveAs(Int_t num, TString name)
+{
+    if (name.EndsWith(".root")) return SaveAsRoot(num, name); // kFileSaveAsRoot
+    if (name.EndsWith(".ps"))   return SaveAsPS(num, name);   // kFileSaveAsPS
+    if (name.EndsWith(".pdf"))  return SaveAsPDF(num, name);  // kFileSaveAsPDF
+    if (name.EndsWith(".svg"))  return SaveAsSVG(num, name);  // kFileSaveAsSVG
+    if (name.EndsWith(".gif"))  return SaveAsGIF(num, name);  // kFileSaveAsGIF
+    if (name.EndsWith(".png"))  return SaveAsPNG(num, name);  // kFileSaveAsPNG
+    if (name.EndsWith(".bmp"))  return SaveAsBMP(num, name);  // kFileSaveAsBMP
+    if (name.EndsWith(".xml"))  return SaveAsXML(num, name);  // kFileSaveAsXML
+    if (name.EndsWith(".jpg"))  return SaveAsJPG(num, name);  // kFileSaveAsJPG
+    if (name.EndsWith(".xpm"))  return SaveAsXPM(num, name);  // kFileSaveAsXPM
+    if (name.EndsWith(".csv"))  return SaveAsCSV(num, name);  // kFileSaveAsCSV
+    if (name.EndsWith(".tiff")) return SaveAsTIFF(num, name); // kFileSaveAsTIFF
+    if (name.EndsWith(".C"))    return SaveAsC(num, name);    // kFileSaveAsC
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Opens a save as dialog
+//
+Int_t MStatusDisplay::SaveAs(Int_t num)
+{
+    static const char *gSaveAsTypes[] =
+    {
+        "PostScript",   "*.ps",
+        "Acrobat pdf",  "*.pdf",
+        "SVG vector",   "*.svg",
+        "Gif files",    "*.gif",
+        "Png files",    "*.png",
+        "Gif files",    "*.gif",
+        "Jpeg files",   "*.jpeg",
+        "Xpm files",    "*.xpm",
+        "Bmp files",    "*.bmp",
+        "Xml files",    "*.xml",
+        "Tiff files",   "*.tiff",
+        "Csv files",    "*.csv",
+        "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 Int_t rc = SaveAs(num, fi.fFilename);
+    if (rc>=0)
+        return rc;
+
+    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, kFDOpen, &fi);
+
+    if (!fi.fFilename)
+        return 0;
+
+    dir = fi.fIniDir;
+
+    return Open(fi.fFilename);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Change width of display. The height is calculated accordingly.
+//
+void MStatusDisplay::SetDisplayWidth(UInt_t dw)
+{
+    if (gROOT->IsBatch())
+    {
+        SetCanvasWidth(dw);
+        return;
+    }
+
+    // 4 == 2*default border with of canvas
+    dw -= 4;
+
+    // Difference between canvas size and display size
+    const UInt_t cw = GetWidth() -fTab->GetWidth();
+    const UInt_t ch = GetHeight()-fTab->GetHeight()+fTab->GetTabHeight();
+
+    const UInt_t dh = TMath::Nint((dw - cw)/1.5 + ch);
+
+    Resize(dw, dh); // Set display size
+}
+
+// --------------------------------------------------------------------------
+//
+//  Change height of display. The width is calculated accordingly.
+//
+void MStatusDisplay::SetDisplayHeight(UInt_t dh)
+{
+    if (gROOT->IsBatch())
+    {
+        SetCanvasHeight(dh);
+        return;
+    }
+
+    // 4 == 2*default border with of canvas
+    dh -= 4;
+
+    // Difference between canvas size and display size
+    const UInt_t cw = GetWidth() -fTab->GetWidth();
+    const UInt_t ch = GetHeight()-fTab->GetHeight()+fTab->GetTabHeight();
+
+    const UInt_t dw = TMath::Nint((dh - ch)*1.5 + cw);
+
+    Resize(dw, dh); // Set display size
+}
+
+// --------------------------------------------------------------------------
+//
+//  Change width of canvas. The height is calculated accordingly.
+//
+void MStatusDisplay::SetCanvasWidth(UInt_t w)
+{
+    // 4 == 2*default border with of canvas
+    w += 4;
+
+    if (gROOT->IsBatch())
+    {
+        Resize(w, 3*w/2);
+        return;
+    }
+
+    // Difference between canvas size and display size
+    const UInt_t cw = GetWidth() -fTab->GetWidth();
+    const UInt_t ch = GetHeight()-fTab->GetHeight()+fTab->GetTabHeight();
+
+    const UInt_t h  = TMath::Nint(w/1.5 + ch);
+
+    Resize(w + cw, h); // Set display size
+}
+
+// --------------------------------------------------------------------------
+//
+//  Change height of canvas. The width is calculated accordingly.
+//
+void MStatusDisplay::SetCanvasHeight(UInt_t h)
+{
+    // 4 == 2*default border with of canvas
+    h += 4;
+
+    if (gROOT->IsBatch())
+    {
+        Resize(2*h/3, h);
+        return;
+    }
+
+    // Difference between canvas size and display size
+    const UInt_t cw = GetWidth() -fTab->GetWidth();
+    const UInt_t ch = GetHeight()-fTab->GetHeight()+fTab->GetTabHeight();
+
+    // 4 == 2*default border with of canvas
+    const UInt_t dw  = TMath::Nint((h+4)*1.5 + cw);
+
+    Resize(dw, h + ch); // Set display size
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate width and height of the display such that it fits into the
+// defined box.
+//
+void MStatusDisplay::SetDisplaySize(UInt_t w, UInt_t h)
+{
+    if (gROOT->IsBatch())
+        return;
+
+    SetDisplayHeight(h);
+
+    if (GetWidth()>w)
+        SetDisplayWidth(w);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate an optimum size for the display from the desktop size
+//
+void MStatusDisplay::SetOptimumSize()
+{
+    if (gROOT->IsBatch())
+        return;
+
+    const UInt_t w = TMath::Nint(0.95*gClient->GetDisplayWidth());
+    const UInt_t h = TMath::Nint(0.95*gClient->GetDisplayHeight());
+
+    SetDisplaySize(w, h);
+}
+
+
+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;
+
+    const Bool_t wchanged = w!=GetWidth()-fTab->GetWidth();
+    const Bool_t hchanged = h!=GetHeight()-fTab->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()+fTab->GetTabHeight();
+
+    // calculate new size of frame (canvas @ 2:3)
+    if (hchanged)
+        w = TMath::Nint((h-ch)*1.5+cw);
+    else
+        h = TMath::Nint((w-cw)/1.5+ch);
+
+    // resize frame
+    Resize(w, h);
+
+    return kTRUE;
+}
+
+Bool_t MStatusDisplay::HandleEvent(Event_t *event)
+{
+    // Instead  of doing this in CloseWindow (called from HandleEvent)
+    // we do it here. This makes sure, that handle event doesn't
+    // execute code after deleting this.
+    if (event->fType==kDestroyNotify)
+    {
+        if (Close())
+            delete this;
+//        Close();
+        return kTRUE;
+    }
+
+    const Bool_t rc = TGMainFrame::HandleEvent(event);
+
+    //
+    // This fixes a bug in older root versions which makes
+    // TCanvas crash if gPad==NULL. So we make sure, that
+    // gPad!=NULL -- be carfull, this may have other side
+    // effects.
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,01)
+    if (!gPad && fTab)
+        for (int i=0; i<fTab->GetNumberOfTabs(); i++)
+        {
+            TCanvas *c = GetCanvas(i);
+            if (c)
+            {
+                c->cd();
+                gLog << dbg << "MStatusDisplay::HandleEvent - Workaround: gPad=" << gPad << "." << endl;
+                break;
+            }
+        }
+#endif
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mbase/MStatusDisplay.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MStatusDisplay.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MStatusDisplay.h	(revision 17960)
@@ -0,0 +1,318 @@
+#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
+
+#ifndef ROOT_TImage
+#include <TImage.h>
+#endif
+
+class MLog;
+class MGList;
+class MGMenuBar;
+class MStatusArray;
+class MParContainer;
+
+class TPad;
+class TTimer;
+class TMutex;
+class TCanvas;
+class TVirtualPS;
+
+class TGTab;
+class TGTextView;
+class TGStatusBar;
+class TGPopupMenu;
+class TGTabElement;
+class TGProgressBar;
+class TGHProgressBar;
+class TGCompositeFrame;
+class TRootEmbeddedCanvas;
+
+class MStatusDisplay : public TGMainFrame
+{
+    friend class MStatusArray;
+public:
+    typedef enum {
+        // kFile
+        kFileBrowser, kFileCanvas, kFileTab, kFileOpen, kFileSave, kFileSaveAs,
+        kFileSaveAsPS, kFileSaveAsPDF, kFileSaveAsSVG, kFileSaveAsRoot,
+        kFileSaveAsPNG, kFileSaveAsGIF, kFileSaveAsJPG, kFileSaveAsXPM,
+        kFileSaveAsBMP, kFileSaveAsCSV, kFileSaveAsTIFF, kFileSaveAsPlainRoot,
+        kFileSaveAsXML, kFileSaveAsC, kFilePrint, kFilePrinterName,
+        kFileClose, kFileExit, kFileReset,
+        // kLoop
+        kLoopNone, kLoopPause, kLoopStep, kLoopStop,
+        // kTab
+        kTabSave, kTabSaveAs, kTabSaveAsPS, kTabSaveAsPDF, kTabSaveAsSVG,
+        kTabSaveAsRoot, kTabSaveAsPNG, kTabSaveAsGIF, kTabSaveAsJPG,
+        kTabSaveAsXPM, kTabSaveAsBMP, kTabSaveAsCSV, kTabSaveAsTIFF,
+        kTabSaveAsXML, kTabSaveAsC, kTabSaveAsPlainRoot,
+        kTabPrint, kTabNext, kTabPrevious, kTabRemove,
+        // kSize
+        kSize640, kSize768, kSize800, kSize960, kSize1024, kSize1152,
+        kSize1280, kSize1400, kSize1600, kSizeOptimum,
+        // kLog
+        kLogCopy, kLogClear, kLogSelect, kLogFind, kLogSave, kLogAppend,
+        kLogPrint,
+        // kPic
+        kPicMagic, kPicMars,
+        // kGui
+        kSearch, kTabs,
+        // kLastElement
+        kLastElement
+    } 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;
+
+    MGMenuBar   *fMenuBar;
+    TGStatusBar *fStatusBar;
+
+    Status_t fStatus;
+
+    Int_t fLogIdx;
+    TTimer fLogTimer;
+    TGTextView *fLogBox;
+
+    FontStruct_t fFont;
+
+    UInt_t fIsLocked;
+
+    TList *fBatch;          //!
+
+    // GUI setup
+    void AddMenuBar();
+    void AddUserFrame();
+    void AddTabs();
+    void AddProgressBar();
+    void AddStatusBar();
+    void AddMarsTab();
+    void AddLogTab();
+
+    // GUI event handling
+    Bool_t ProcessMessageCommandMenu(Long_t mp1);
+    Bool_t ProcessMessageCommand(Long_t submsg, Long_t mp1, Long_t mp2);
+    Bool_t ProcessMessageTextview(Long_t submsg, Long_t mp1, Long_t mp2);
+    Bool_t ProcessMessageUser(Long_t submsg, Long_t mp1, Long_t mp2);
+    Bool_t Close();
+    void   CloseWindow();
+    Bool_t HandleConfigureNotify(Event_t *);
+
+    // Access to the tabs
+    TGCompositeFrame *GetTabContainer(const char *name) const;
+    TGTabElement     *GetTabTab(const char *name) const;
+
+    // Display update
+    Bool_t HandleTimer(TTimer *timer=NULL);
+    void UpdateTab(TGCompositeFrame *f);
+    void UpdateMemory() const;
+
+    // Display helper functions
+    void RemoveTab(int i);
+    void SetStatusLine(const char *txt, Int_t idx);
+
+    // Menu helper functions
+    TGPopupMenu *GetPopup(const char *name);
+
+    // Drawing helper
+    void DrawClonePad(TCanvas &newc, TCanvas &oldc) const;
+    void GetCanvasRange(Int_t &from, Int_t &to, Int_t num=-1) const;
+
+    // MStatusArray interface
+    Bool_t Display(const TObjArray &list, const char *tab=0);
+    void FillArray(MStatusArray &list, Int_t num=-1) const;
+
+    // I/O helper function
+    const TString &AddExtension(TString &name, const TString &ext, Int_t num=-1) const;
+
+    TCanvas *InitWriteTab(Int_t num, TString &name);
+    TCanvas *InitWriteTab(Int_t num) { TString s; return InitWriteTab(num, s); }
+    Int_t    InitWriteDisplay(Int_t num, TString &name, const TString &ext);
+
+    void UpdatePSHeader(const TString &name) const;
+
+    Bool_t SaveAsImage(Int_t num, TString name, TImage::EImageFileTypes type);
+    Int_t  SaveAsVGF(Int_t num, TString name, const TString addon, const TString ext);
+
+    void PSToolsRange(TVirtualPS &vps, Float_t w, Float_t h) const;
+    void PSToolsTextNDC(TVirtualPS &vps, Double_t u, Double_t v, const char *string) const;
+    TString PrintDialog(TString &p, TString &c, TString &t, const char *ext=0);
+
+public:
+     MStatusDisplay(Int_t w=-1, Int_t h=-1, Long_t t=1000);
+     virtual ~MStatusDisplay();
+
+     // Name and title handling
+     virtual void SetName(const char *name) { fName = name; }
+     virtual void SetTitle(const char *title="") { SetTitle(title, kTRUE); }
+     virtual const char *GetName() const { return fName.Data(); }
+     virtual const char *GetTitle() const { return fTitle.Data(); }
+
+     virtual void SetTitle(const char *title, Bool_t replace)
+     {
+         if (fTitle.IsNull() || replace) fTitle = title;
+     }
+
+     // Getter / display access
+     Bool_t   HasCanvas(const TCanvas *c) const;
+     TCanvas *GetCanvas(int i) const;
+     TCanvas *GetCanvas(const TString &name) const;
+     TVirtualPad *GetFullPad(const Int_t canvas, const Int_t pad);
+
+     Bool_t CdCanvas(const TString &name);
+     Bool_t CheckTabForCanvas(int num) const;
+
+     TObject *FindObjectInCanvas(const char *obj, const char *base, const char *canv) const;
+     TObject *FindObjectInCanvas(const char *obj, const char *canv) const { return FindObjectInCanvas(obj, obj, canv); }
+     TObject *FindObject(const char *obj, const char *base) const { return FindObjectInCanvas(obj, base, 0); }
+     TObject *FindObject(const char *obj) const { return FindObjectInCanvas(obj, obj, 0); }
+     TObject *FindObject(const TObject *) const { return 0;  }
+
+     Int_t GetNumTabs() const;
+
+     void PrintContent(Option_t *o="") const;
+
+     // Display Manipulation
+     TCanvas &AddTab(const char *name, const char *title=0);
+     TGCompositeFrame *AddRawTab(const char *name);
+
+     void SetProgressBarPosition(Float_t p, Bool_t upd=kFALSE);
+     TGProgressBar *GetBar() const { return (TGProgressBar*)fBar; }
+
+     void SetStatusLine1(const char *txt) { SetStatusLine(txt, 0); }
+     void SetStatusLine2(const char *txt) { SetStatusLine(txt, 1); }
+     void SetStatusLine2(const MParContainer &cont);
+
+     void Reset();
+     void SetNoContextMenu(Bool_t flag=kTRUE);
+
+     // Update handling
+     void StartUpdate(Int_t millisec=-1);
+     void StopUpdate();
+     void SetUpdateTime(Long_t t);
+
+     void Update() { HandleTimer(&fTimer); HandleTimer(&fLogTimer); }
+
+     // Log stream interface
+     void SetLogStream(MLog *log, Bool_t enable=kFALSE);
+
+     // Size options
+     void SetCanvasWidth(UInt_t w);
+     void SetCanvasHeight(UInt_t h);
+
+     void SetDisplayWidth(UInt_t w);
+     void SetDisplayHeight(UInt_t h);
+
+     void SetOptimumSize();
+     void SetDisplaySize(UInt_t w, UInt_t h);
+
+     // Graphics output
+     Int_t  SaveAsPS(TString name="",  const TString addon="") { return SaveAsVGF(-1, name, addon, "ps"); }
+     Int_t  SaveAsPDF(TString name="", const TString addon="") { return SaveAsVGF(-1, name, addon, "pdf"); }
+     Int_t  SaveAsSVG(TString name="", const TString addon="") { return SaveAsVGF(-1, name, addon, "svg"); }
+     Bool_t SaveAsPNG(TString name="")  { return SaveAsPNG(-1, name); }
+     Bool_t SaveAsGIF(TString name="")  { return SaveAsGIF(-1, name); }
+     Bool_t SaveAsXPM(TString name="")  { return SaveAsXPM(-1, name); }
+     Bool_t SaveAsJPG(TString name="")  { return SaveAsJPG(-1, name); }
+     Bool_t SaveAsTIFF(TString name="") { return SaveAsTIFF(-1, name); }
+     Bool_t SaveAsBMP(TString name="")  { return SaveAsBMP(-1, name); }
+     Bool_t SaveAsXML(TString name="")  { return SaveAsXML(-1, name); }
+     Bool_t SaveAsC(TString name="")    { return SaveAsC(-1, name); }
+     Int_t  SaveAsRoot(TString name="") { return SaveAsRoot(-1, name); }
+     Int_t  SaveAsPlainRoot(TString name="") { return SaveAsRoot(-1, name, kTRUE); }
+     Int_t  SaveAs(TString name)        { return SaveAs(-1, name); }
+
+     Bool_t SaveAsCSV(TString name="", Char_t delim='\t') { return SaveAsCSV(-1, name, delim); }
+     Int_t  PrintPS() { return PrintPS(-1); }
+
+     void   SaveAs(const char *c, const Option_t *o) const;
+
+     Int_t  SaveAsPS(Int_t num, TString name="",  const TString addon="") { return SaveAsVGF(num, name, addon, "ps"); }
+     Int_t  SaveAsPDF(Int_t num, TString name="", const TString addon="") { return SaveAsVGF(num, name, addon, "pdf"); }
+     Int_t  SaveAsSVG(Int_t num, TString name="", const TString addon="") { return SaveAsVGF(num, name, addon, "svg"); }
+     Bool_t SaveAsPNG(Int_t num, TString name="")  { return SaveAsImage(num, name, TImage::kPng); }
+     Bool_t SaveAsGIF(Int_t num, TString name="")  { return SaveAsImage(num, name, TImage::kGif); }
+     Bool_t SaveAsXPM(Int_t num, TString name="")  { return SaveAsImage(num, name, TImage::kXpm); }
+     Bool_t SaveAsJPG(Int_t num, TString name="")  { return SaveAsImage(num, name, TImage::kJpeg); }
+     Bool_t SaveAsTIFF(Int_t num, TString name="") { return SaveAsImage(num, name, TImage::kTiff); }
+     Bool_t SaveAsBMP(Int_t num, TString name="")  { return SaveAsImage(num, name, TImage::kBmp); }
+     Bool_t SaveAsXML(Int_t num, TString name="")  { return SaveAsImage(num, name, TImage::kXml); }
+     Bool_t SaveAsC(Int_t num, TString name="");
+     Int_t  SaveAsRoot(Int_t num, TString name="", Bool_t plain=kFALSE);
+     Int_t  SaveAsPlainRoot(Int_t num, TString name="") { return SaveAsRoot(num, name, kTRUE); }
+     Int_t  SaveAs(Int_t num, TString name);
+
+     Bool_t SaveAsCSV(Int_t num, TString name="", Char_t delim='\t');
+     //Bool_t SaveAsXML(Int_t num, TString name="",);
+     Int_t  PrintPS(Int_t num, const char *p=0, const char *cmd=0, const char *tmp=0);
+     Bool_t PrintLog(const char *p=0, const char *c=0);
+
+     Bool_t SaveLogAsPS(const char *name) const;
+
+     // I/O
+     Int_t  SaveAs(Int_t num=-1);
+     Int_t  Open(TString fname, const char *name="MStatusDisplay");
+     Int_t  Open();
+
+     // Root I/O
+     Int_t Write(Int_t num, const char *name="MStatusDisplay", Option_t *opt="") const;
+
+     Int_t Read(const char *name, const char *tab);
+     Int_t Read(const char *name="MStatusDisplay") { return Read(name, 0); }
+     Int_t Write(const char *name=0, Int_t =0, Int_t =0) { return Write(-1, name?name:"MStatusDisplay"); }
+     Int_t Write(const char *name=0, Int_t =0, Int_t =0) const { return Write(-1, name?name:"MStatusDisplay"); }
+
+     // Eventloop interface
+     Status_t CheckStatus() const { return fStatus; }
+     void ClearStatus() { fStatus=kLoopPause; ProcessMessageCommandMenu(kLoopPause); }
+     void SetPause() { fStatus=kLoopNone; ProcessMessageCommandMenu(kLoopPause); }
+     void SetLoopStep() { SetPause(); fStatus = kLoopStep; }
+
+     void Lock() { fIsLocked++; }
+     void UnLock() { if (fIsLocked>0) fIsLocked--; }
+
+     // GUI event handling
+     void EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected);
+     Bool_t HandleEvent(Event_t *event);
+
+     // Public helper functions
+     static TRootEmbeddedCanvas *GetEmbeddedCanvas(TGCompositeFrame &cf);
+     static TCanvas *GetCanvas(TGCompositeFrame &f);
+
+     ClassDef(MStatusDisplay, 0)   // Window for a status display
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MString.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MString.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MString.cc	(revision 17960)
@@ -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, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MString
+// =======
+//
+// If you are using root Form() command you must be aware of the fact that
+// it uses a global buffer. This buffer is recreated depending on the
+// length which is necessary to form the string. This recreation is not
+// thread safe and it might result in crashes if used in multi-threaded
+// environments.
+//
+// To get around this problem MString implements a Print() member function
+// which form a string like Form does. This formation is done in a
+// internal buffer. Because this buffer must be recreated and
+// deleted each time Print() is called this might be slower than Form().
+// The advantage is, that the buffer is not global and a call to Print()
+// from different threads is safe. However accessing the same
+// M/TString-object must still be locked with a mutex.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MString.h"
+
+#include <stdarg.h>
+
+ClassImp(MString);
+
+// --------------------------------------------------------------------------
+//
+// Thread safe replacement for Form, use it like:
+//
+//  MString string;
+//  string.Print("MyString has %d bytes", 128);
+//
+// As a special feature the function returns the reference to the MString
+// so that you can directly work with it, eg.
+//
+//  string.Print("  MyString has %d bytes  ", 128).Strip(TString::kBoth);
+//
+MString &MString::Print(const char *fmt, va_list &ap)
+{
+    Int_t n=256;
+
+    char *ret=0;
+
+    while (1)
+    {
+        ret = new char[n+1];
+        Int_t sz = vsnprintf(ret, n, fmt, ap);
+        if (sz<=n)
+            break;
+
+        n *= 2;
+        delete [] ret;
+    };
+
+    va_end(ap);
+
+    *static_cast<TString*>(this) = ret;
+
+    delete [] ret;
+
+    return *this;
+}
+
+// --------------------------------------------------------------------------
+//
+// Thread safe replacement for Form, use it like:
+//
+//  MString string;
+//  string.Print("MyString has %d bytes", 128);
+//
+// As a special feature the function returns the reference to the MString
+// so that you can directly work with it, eg.
+//
+//  string.Print("  MyString has %d bytes  ", 128).Strip(TString::kBoth);
+//
+/*
+MString &MString::Print(const char *fmt, ...)
+{
+    va_list ap;
+    va_start(ap, fmt);
+
+    return Print(fmt, ap);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Thread safe replacement for Form, use it like:
+//
+//  MString string;
+//  string.Print("MyString has %d bytes", 128);
+//
+// As a special feature the function returns the reference to the MString
+// so that you can directly work with it, eg.
+//
+//  string.Print("  MyString has %d bytes  ", 128).Strip(TString::kBoth);
+//
+// The static version of this function returns a copy(!) of the resulting
+// M/TString.
+//
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,18,00)
+TString MString::Format(const char *fmt, ...)
+{
+    va_list ap;
+    va_start(ap, fmt);
+
+    MString ret;
+    ret.Print(fmt, ap);
+    return ret;
+}
+#endif
+
+// --------------------------------------------------------------------------
+//
+// This is my implementation for root versions prior to 5.12/00 where
+// TString::Form didn't exist.
+//
+/*
+void MString::Form(const char *fmt, ...)
+{
+    va_list ap;
+    va_start(ap, fmt);
+
+    Print(fmt, ap);
+}
+*/
Index: branches/Mars_McMismatchStudy/mbase/MString.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MString.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MString.h	(revision 17960)
@@ -0,0 +1,29 @@
+#ifndef MARS_MString
+#define MARS_MString
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+class MString : public TString
+{
+private:
+    MString &Print(const char *fmt, va_list &ap);
+//    MString &Print(const char *fmt, ...);
+
+public:
+    MString(const char *txt=0)  : TString(txt) { }
+    MString(const TString &txt) : TString(txt) { }
+
+#ifndef __CINT__
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,18,00)
+    static TString Format(const char *fmt, ...);
+#endif
+#endif
+
+    //void Form(const char *fmt, ...);
+
+    ClassDef(MString, 1) // Tool to make Form() thread safe against other TStrings for root prior 5.18.00
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MTask.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTask.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTask.cc	(revision 17960)
@@ -0,0 +1,540 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MTask
+//
+//   Base class for all tasks which can perfomed in a tasklist
+//   For each event processed in the eventloop all the different
+//   tasks in the tasklist will be processed.
+//
+//   So all tasks must inherit from this baseclass.
+//
+//   The inheritance from MInputStreamID is used to indicate the
+//   type of event that this task is for. If it is "All" it is executed
+//   independantly of the actual ID of the task list.
+//
+//   Inside this abstract class, there are three fundamental function:
+//
+//   - PreProcess():   executed before the eventloop starts. Here you
+//                     can initiate different things, open files, etc.
+//                     As an argument this function gets a pointer to the
+//                     parameter list. You can stop the execution by
+//                     returning kFALSE instead of kTRUE. If an error
+//                     occured and you return kFALSE make sure, that
+//                     any action is closed correctly and all newly
+//                     created object are deleted. The PostProcess in
+//                     such a case won't be executed by the Tasklist or
+//                     Eventloop.
+//
+//   - Process():      executed for each event in the eventloop. Do it
+//                     one task after the other (as they occur in the
+//                     tasklist). Only the tasks with a Stream ID
+//                     which matches the actual ID of the tasklist
+//                     are executed. A task can return kFALSE to
+//                     stop the execuition of the tasklist or
+//                     kCONTINUE to skip the pending tasks. If you want
+//                     to stop the eventloop and wants the eventloop to
+//                     return the status 'failed' return kERROR.
+//
+//   - ReInit()        The idea is, that
+//                       a) we have one file per run
+//                       b) each file contains so called run-headers which
+//                          stores information 'per run', eg MRawRunHeader
+//                          or the bad pixels
+//                       c) this information must be evaluated somehow each
+//                          time a new file is opened.
+//
+//                     If you use MReadMarsFile or MCT1ReadPreProc it is
+//                     called each time a new file has been opened and the
+//                     new run headers have been read before the first
+//                     event of these file is preprocessed.
+//
+//   - PostProcess():  executed after the eventloop. Here you can close
+//                     output files, start display of the run parameter,
+//                     etc. PostProcess is only executed in case of
+//                     PreProcess was successfull (returned kTRUE)
+//
+//
+//  Remark: Using a MTask in your tasklist doesn't make much sense,
+//          because it is doing nothing. However it is a nice tool
+//          to count something (exspecially if used together with a
+//          filter)
+//
+//
+//  Version 1:
+//  ----------
+//   - first version
+//
+//  Version 2:
+//  ----------
+//   - added fSerialNumber
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTask.h"
+
+#include <fstream>
+
+#include <TClass.h>
+#include <TBaseClass.h> // OverwritesProcess
+#include <TStopwatch.h> // TStopwatch
+
+#include "MString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MFilter.h"
+#include "MStatusDisplay.h"
+
+#undef DEBUG_PROCESS
+//#define DEBUG_PROCESS
+
+ClassImp(MTask);
+
+using namespace std;
+
+MTask::MTask(const char *name, const char *title)
+    : fFilter(NULL), fSerialNumber(0), fIsPreprocessed(kFALSE),
+    fStopwatch(0), fNumExecutions(0), fNumExec0(0), fAccelerator(0)
+{
+    fName  = name  ? name  : "MTask";
+    fTitle = title ? title : "Base class for all tasks (dummy task).";
+
+    fListOfBranches = new TList;
+    fListOfBranches->SetOwner();
+
+    fStopwatch = new TStopwatch;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete fStopwatch and fListOfBranches
+//
+MTask::~MTask()
+{
+    delete fStopwatch;
+    delete fListOfBranches;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize fFilter with filter and if not null add the result of
+// GetDataMember from the filter to the branch list.
+//
+void MTask::SetFilter(MFilter *filter)
+{
+    fFilter=filter;
+    if (!filter)
+        return;
+
+    fFilter->SetBit(kMustCleanup);    // Better is better ;-)
+    AddToBranchList(filter->GetDataMember());
+}
+
+// --------------------------------------------------------------------------
+//
+// This adds a branch to the list for the auto enabeling schmeme.
+// This makes it possible for MReadTree to decide which branches
+// are really needed for the eventloop. Only the necessary branches
+// are read from disk which speeds up the calculation enormously.
+//
+// You can use TRegExp expressions like "*.fEnergy", but the
+// recommended method is to call this function for exactly all
+// branches you want to have, eg:
+//  AddToBranchList("MMcTrig.fNumFirstLevel");
+//  AddToBranchList("MMcTrig;1.fNumFirstLevel");
+//  AddToBranchList("MMcTrig;2.fNumFirstLevel");
+//
+// We agreed on the convetion, that all branches are stored with
+// a trailing dot '.' so that always the Master Branch name
+// (eg. MMcTrig) is part of the branch name.
+//
+// Remark: The common place to call AddToBranchList is the
+//         constructor of the derived classes (tasks)
+//
+void MTask::AddToBranchList(const char *b)
+{
+    if (fListOfBranches->FindObject(b))
+        return;
+
+    fListOfBranches->Add(new TNamed(b, ""));
+}
+
+// --------------------------------------------------------------------------
+//
+// Using this overloaded member function you may cascade several branches
+// in acomma seperated list, eg: "MMcEvt.fTheta,MMcEvt.fEnergy"
+//
+// For moredetailed information see AddToBranchList(const char *b);
+//
+void MTask::AddToBranchList(const TString &str)
+{
+    TString s = str;
+
+    while (!s.IsNull())
+    {
+        Int_t fst = s.First(',');
+
+        if (fst<0)
+            fst = s.Length();
+
+        AddToBranchList((const char*)TString(s(0, fst)));
+
+        s.Remove(0, fst+1);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy constructor. Reset MInputStreamID, copy pointer to fFilter and
+// copy the contents of fListOfBranches
+//
+MTask::MTask(MTask &t) : MInputStreamID()
+{
+    fFilter = t.fFilter;
+    fListOfBranches->AddAll(t.fListOfBranches);
+}
+
+// --------------------------------------------------------------------------
+//
+// Mapper function for PreProcess.
+// Sets the preprocessed flag dependend on the return value of PreProcess.
+// Resets number of executions and cpu consumtion timer.
+// If task has already been preprocessed return kTRUE.
+//
+Int_t MTask::CallPreProcess(MParList *plist)
+{
+    if (fIsPreprocessed)
+        return kTRUE;
+
+    // This does not reset the counter!
+    fStopwatch->Reset();
+    fNumExec0 = fNumExecutions;
+
+    *fLog << all << GetDescriptor() << "... " << flush;
+    if (fDisplay)
+        fDisplay->SetStatusLine2(*this);
+
+    switch (PreProcess(plist))
+    {
+    case kFALSE:
+        return kFALSE;
+
+    case kTRUE:
+        fIsPreprocessed = kTRUE;
+        return kTRUE;
+
+    case kSKIP:
+        return kSKIP;
+    }
+
+    *fLog << err << dbginf << "PreProcess of " << GetDescriptor();
+    *fLog << " returned an unknown value... aborting." << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Mapper function for Process.
+// Executes Process dependent on the existance of a filter and its possible
+// return value.
+// If Process is executed, the execution counter is increased.
+// Count cpu consumption 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.
+    //
+    if (fFilter && !fFilter->IsConditionTrue())
+        return kTRUE;
+
+    if (!HasAccelerator(kAccDontTime))
+        fStopwatch->Start(kFALSE);
+
+    fNumExecutions++;
+
+#ifdef DEBUG_PROCESS
+    *fLog << all << flush << GetName() << "..." << flush;
+#endif
+
+    const Int_t rc = Process();
+
+#ifdef DEBUG_PROCESS
+    *fLog << all << flush << "done." << endl;
+#endif
+
+    if (!HasAccelerator(kAccDontTime))
+        fStopwatch->Stop();
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Mapper function for PreProcess.
+// Calls Postprocess dependent on the state of the preprocessed flag,
+// resets this flag.
+//
+Int_t MTask::CallPostProcess()
+{
+    if (!fIsPreprocessed)
+        return kTRUE;
+
+    fIsPreprocessed = kFALSE;
+
+    *fLog << all << GetDescriptor() << "... " << flush;
+    if (fDisplay)
+        fDisplay->SetStatusLine2(*this);
+
+    return PostProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+// This is reinit function
+//
+// This function is called asynchronously if the tasks in the tasklist need
+// reinitialization. This for example happens when the eventloop switches
+// from one group of events to another one (eg. switching between events
+// of different runs means reading a new run header and a new run header
+// may mean that some value must be reinitialized)
+//
+// the virtual implementation returns kTRUE
+//
+Bool_t MTask::ReInit(MParList *)
+{
+    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 *)
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is processed for every event in the eventloop
+//
+// the virtual implementation returns kTRUE
+//
+Int_t MTask::Process()
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is processed after the eventloop starts
+//
+// the virtual implementation returns kTRUE
+//
+Int_t MTask::PostProcess()
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the name of the object. If the name of the object is not the
+// class name it returns the object name and in []-brackets the class name.
+// If a serial number is set (!=0) the serial number is added to the
+// name (eg. ;1)
+//
+const TString MTask::GetDescriptor() const
+{
+    //
+    // Because it returns a (const char*) we cannot return a casted
+    // local TString. The pointer would - immediatly after return -
+    // point to a random memory segment, because the TString has gone.
+    //
+    if (fName==ClassName())
+        return fSerialNumber==0 ? (TString)ClassName() : MString::Format("%s;%d", ClassName(), fSerialNumber);
+
+    return fSerialNumber>0 ?
+        MString::Format("%s;%d [%s]", fName.Data(), fSerialNumber, ClassName()) :
+        MString::Format("%s [%s]",    fName.Data(), ClassName());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the total number of calls to since PreProcess(). If Process() was
+//  not called due to a set filter this is not counted.
+//
+UInt_t MTask::GetNumExecutions() const
+{
+    return fNumExecutions-fNumExec0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the total number of calls to Process() ever. If Process() was not
+//  called due to a set filter this is not counted.
+//
+UInt_t MTask::GetNumExecutionsTotal() const
+{
+    return fNumExecutions;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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 (!Overwrites("Process") && IsA()!=MTask::Class())
+        return;
+
+    *fLog << all << setfill(' ') << setw(lvl) << " ";
+
+    if (GetCpuTime()>0 && time>0 && GetCpuTime()>=0.001*time && !HasAccelerator(kAccDontTime))
+        *fLog << Form("%5.1f", GetCpuTime()/time*100) << "% ";
+    else
+        *fLog << "       ";
+
+    if (HasStreamId())
+        *fLog << GetStreamId() << ":";
+    *fLog << GetDescriptor();
+
+    if (GetNumExecutions()>0)
+        *fLog << "\t" << 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(ostream &out, Option_t *)
+{
+    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;
+}
+
+void MTask::SavePrimitive(ofstream &out, Option_t *o)
+{
+    SavePrimitive(static_cast<ostream&>(out), o);
+}
+
+void MTask::SetDisplay(MStatusDisplay *d)
+{
+    if (fFilter)
+        fFilter->SetDisplay(d);
+    MParContainer::SetDisplay(d);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is used to print the output in the PostProcess/Finalize.
+//  Or everywhere else in a nice fashioned and unified way.
+//
+void MTask::PrintSkipped(UInt_t n, const char *str)
+{
+    *fLog << " " << setw(7) << n << " (";
+    *fLog << Form("%5.1f", 100.*n/GetNumExecutions());
+    *fLog << "%) Evts skipped: " << str << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// If obj==fFilter set fFilter to NULL
+// Call MParcontainer::RecursiveRemove
+//
+void MTask::RecursiveRemove(TObject *obj)
+{
+    if (obj==fFilter)
+        fFilter=NULL;
+
+    if (fFilter)
+        fFilter->RecursiveRemove(obj);
+
+    MParContainer::RecursiveRemove(obj);
+}
Index: branches/Mars_McMismatchStudy/mbase/MTask.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTask.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTask.h	(revision 17960)
@@ -0,0 +1,131 @@
+#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
+{
+public:
+    enum {
+        kAccStandard  = 0,
+        kAccDontTime  = BIT(1),
+        kAccDontReset = BIT(2)
+    };
+
+private:
+    TList *fListOfBranches;     //! List of Branch names for auto enabeling scheme
+
+    MFilter *fFilter;           // Filter for conditional task execution
+    Byte_t   fSerialNumber;     // Serial number having more than one detector of the same type
+
+    Bool_t fIsPreprocessed;     //! Indicates the success of the PreProcessing (set by MTaskList)
+
+    TStopwatch *fStopwatch;     //! Count the execution time and number of executions
+    UInt_t      fNumExecutions; //! Number of executions (also counted by fStopwatch, but faster)
+    UInt_t      fNumExec0;      //! Total number of executions at PreProcess
+    Byte_t      fAccelerator;   //!
+
+    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 Overwrites(const char *name, TClass *cls=NULL) const { return MParContainer::Overwrites(MTask::Class(), *this, name, cls); }
+
+    // Filter functions
+    virtual void SetFilter(MFilter *filter);
+    const MFilter *GetFilter() const        { return fFilter; }
+    MFilter *GetFilter()                    { return fFilter; } // for MContinue only
+
+    // Display functions
+    void SetDisplay(MStatusDisplay *d);
+
+    // Acceleration Control
+    virtual void SetAccelerator(Byte_t acc=kAccStandard) { fAccelerator=acc; }
+    Byte_t GetAccelerator() const { return fAccelerator; }
+    Bool_t HasAccelerator(Byte_t acc) const { return fAccelerator&acc; }
+
+    // Function for parallel executions
+    static TString AddSerialNumber(const char *str, UInt_t num) { TString s(str); if (num==0) return s; s += ";"; s += num; return s; }
+    static TString AddSerialNumber(const TString &str, UInt_t num) { return AddSerialNumber((const char*)str, num); }
+    TString AddSerialNumber(const char *str) const { return AddSerialNumber(str, fSerialNumber); }
+    TString AddSerialNumber(const TString &str) const { return AddSerialNumber(str, fSerialNumber); }
+
+    virtual void SetSerialNumber(Byte_t num) { fSerialNumber = num;  }
+    Byte_t GetSerialNumber() const           { return fSerialNumber; }
+
+    const TString GetDescriptor() const;
+
+    // Task execution statistics
+    UInt_t   GetNumExecutions() const;
+    UInt_t   GetNumExecutionsTotal() const;
+    Double_t GetCpuTime() const;
+    Double_t GetRealTime() const;
+    virtual void PrintStatistics(const Int_t lvl=0, Bool_t title=kFALSE, Double_t time=0) const;
+    virtual void PrintSkipped(UInt_t n, const char *str);
+
+    // Task overwrite functions
+    virtual Bool_t ReInit(MParList *pList);
+
+    virtual Int_t CallPreProcess(MParList *plist);
+    virtual Int_t CallProcess();
+    virtual Int_t CallPostProcess();
+
+    void SavePrimitive(std::ostream &out, Option_t *o="");
+    void SavePrimitive(std::ofstream &out, Option_t *o="");
+
+    // TObject
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MTask, 2) //Abstract base class for a task
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MTaskEnv.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTaskEnv.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTaskEnv.cc	(revision 17960)
@@ -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, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTaskEnv
+//
+// This class is used if a task - at runtime - should be replaced or setup
+// from a resource file, eg.
+//
+//
+// resources.rc:
+//   MyTask: MThisIsMyClass
+//   MyTask.Resource1: yes
+//   MyTask.Resource2: 50
+//
+// macro.C:
+//   MTaskList list;
+//
+//   MDefaultTask def;
+//   MTaskEnv taskenv("MyTask");
+//   taskenv.SetDefault(&def);
+//
+//   list.AddToList(&taskenv);
+//   [...]
+//   evtloop.ReadEnv("resource.rc");
+//
+// In this case MTaskEnv will act like MDefaultTask if nothing is found in the
+// resource file. If the task is setup via the resource file like in the
+// example above it will act like a MThisIsMyClass setup with Resource1 and
+// Resource2.
+//
+//
+// You can also skip the task completely if you setup (in lower case letters!)
+//
+// resources.rc:
+//   MyTask: <dummy>
+//
+//
+// A third option is to setup a MTaskEnv to be skipped except a task is
+// initialized through the resource file:
+//   MTaskEnv taskenv("MyTask");
+//   taskenv.SetDefault(0);
+//
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   -/-
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTaskEnv.h"
+
+#include <TClass.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTaskEnv);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Takes name and title of the interactive task
+//
+MTaskEnv::MTaskEnv(const char *name, const char *title) : fTask(0)
+{
+    fName  = name  ? name  : "MTaskEnv";
+    fTitle = title ? title : "Task setup from Environment file";
+}
+
+MTaskEnv::~MTaskEnv()
+{
+    if (TestBit(kIsOwner))
+        delete fTask;
+}
+
+MTask *MTaskEnv::GetTask(const char *name) const
+{
+    MTask *task = (MTask*)GetNewObject(name, MTask::Class());
+    if (!task)
+        return NULL;
+
+    task->SetName(fName);
+    task->SetTitle(fTitle);
+
+    return task;
+}
+
+void MTaskEnv::SetDefault(const char *def)
+{
+    if (TestBit(kIsOwner) && fTask)
+        delete fTask;
+
+    fTask = GetTask(def);
+    if (!fTask)
+        *fLog << err << dbginf << "ERROR - No default Task setup..." << endl;
+
+    SetBit(kIsOwner);
+}
+
+Bool_t MTaskEnv::ReInit(MParList *list)
+{
+    *fLog << fTask->ClassName() << " <MTaskEnv>... " << flush;
+    return fTask->ReInit(list);
+}
+
+Int_t MTaskEnv::PreProcess(MParList *list)
+{
+    if (TestBit(kIsDummy))
+    {
+        *fLog << inf << "Dummy Task... skipped." << endl;
+        return kSKIP;
+    }
+
+    if (!fTask)
+    {
+        *fLog << err << GetDescriptor() << " - ERROR: No task setup." << endl;
+        return kFALSE;
+    }
+
+    *fLog << fTask->ClassName() << " <MTaskEnv>... " << flush;
+
+    fTask->SetAccelerator(GetAccelerator());
+    return fTask->CallPreProcess(list);
+}
+
+Int_t MTaskEnv::Process()
+{
+    return fTask->CallProcess();
+}
+
+Int_t MTaskEnv::PostProcess()
+{
+    *fLog << fTask->ClassName() << " <MTaskEnv>... " << flush;
+    return fTask->CallPostProcess();
+}
+
+Int_t MTaskEnv::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (!IsEnvDefined(env, prefix, print))
+        return fTask ? fTask->ReadEnv(env, prefix, print) : kFALSE;
+
+    TString task = GetEnvValue(env, prefix, "");
+    task.ReplaceAll("\015", "");
+    task = task.Strip(TString::kBoth);
+
+    if (task=="<dummy>")
+    {
+        if (TestBit(kIsOwner) && fTask)
+            delete fTask;
+        fTask = 0;
+        SetBit(kIsDummy);
+        return kTRUE;
+    }
+
+    fTask = GetTask(task.Data());
+    if (!fTask)
+    {
+        *fLog << err << GetDescriptor() << " - ERROR: No task matching '";
+        *fLog << task << "' could be setup." << endl;
+        return kERROR;
+    }
+
+    ResetBit(kIsDummy);
+    SetBit(kIsOwner);
+
+    return fTask->ReadEnv(env, prefix, print);
+}
+
+Bool_t MTaskEnv::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    return fTask->WriteEnv(env, prefix, print);
+}
Index: branches/Mars_McMismatchStudy/mbase/MTaskEnv.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTaskEnv.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTaskEnv.h	(revision 17960)
@@ -0,0 +1,44 @@
+#ifndef MARS_MTaskEnv
+#define MARS_MTaskEnv
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MFilter;
+class MTaskList;
+
+class MTaskEnv : public MTask
+{
+private:
+    MTask *fTask;
+
+    enum { kIsOwner = BIT(14), kIsDummy = BIT(15) };
+
+    MTask *GetTask(const char *name) const;
+
+    Bool_t ReInit(MParList *list);
+
+    Int_t  PreProcess(MParList *list);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+public:
+    MTaskEnv(const char *name=NULL, const char *title=NULL);
+    ~MTaskEnv();
+
+    void SetOwner(Bool_t b=kTRUE) { b ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    void SetDefault(MTask *task=0) { fTask = task; if (fTask) { fTask->SetName(fName); ResetBit(kIsDummy); } else SetBit(kIsDummy); }
+    void SetDefault(const char *def);
+
+    MTask *GetTask() { return fTask; }
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MTaskEnv, 0) // Task which can be setup from an environment file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MTaskInteractive.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTaskInteractive.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTaskInteractive.cc	(revision 17960)
@@ -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, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTaskInteractive
+//
+// If you want to create a new task inside a macro you will have to compile
+// your macro using macro.C++, because the root interpreter cannot use
+// uncompiled classes. To workaround this problem you can write simple
+// funcions (which can be handled by CINT) and use MTaskInteractive.
+//
+// This is a simple way to develop new code in a macro without need
+// to compile it.
+//
+// Example:
+//    Int_t Process()
+//    {
+//       gLog << "Processing..." << endl;
+//       return kTRUE;
+//    }
+//
+//    void main()
+//    {
+//       MTaskInteractive task;
+//       task.SetProcess(Process);
+//       MTaskList list;
+//       list.AddToList(&task);
+//    }
+//
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   -/-
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTaskInteractive.h"
+
+#include <Api.h>
+#include <TMethodCall.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTaskInteractive);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Takes name and title of the interactive task
+//
+MTaskInteractive::MTaskInteractive(const char *name, const char *title) :
+    fPreProcess(NULL), fProcess(NULL), fPostProcess(NULL), fReInit(NULL)
+{
+    fName  = name  ? name  : "MTaskInteractive";
+    fTitle = title ? title : "Interactive task";
+
+    fCall[0] = 0;
+    fCall[1] = 0;
+    fCall[2] = 0;
+    fCall[3] = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Free all resources.
+//
+MTaskInteractive::~MTaskInteractive()
+{
+    Free(0);
+    Free(1);
+    Free(2);
+    Free(3);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the function and returns its return value.
+// Called by PreProcess, Process, PostProcess and ReInit.
+//
+inline Int_t MTaskInteractive::Return(Int_t no, void *params)
+{
+    // Static function called when SetFCN is called in interactive mode
+    if (!fCall[no])
+    {
+        gLog << err << dbginf << "Return(" << no << ") - TMethodCall not set." << endl;
+        return kFALSE;
+    }
+
+    Long_t result;
+    fCall[no]->SetParamPtrs(params);
+    fCall[no]->Execute(result);
+
+    return result;
+}
+
+// --------------------------------------------------------------------------
+//
+// Generalized function to set the functions of your interactive task.
+// Called by SetPreProcess, SetProcess, SetPostProcess and SetReInit
+//
+Bool_t MTaskInteractive::Set(void *fcn, Int_t no, const char *params)
+{
+    // this function is called by CINT instead of the function above
+    if (!fcn)
+        return kFALSE;
+
+    char *funcname = G__p2f2funcname(fcn);
+    if (!funcname)
+        return kFALSE;
+
+    Free(no);
+
+    fCall[no] = new TMethodCall;
+    fCall[no]->InitWithPrototype(funcname, params);
+
+    gLog << inf << GetDescriptor() << ": Using " << funcname << " as ";
+    switch (no)
+    {
+    case 0:
+        gLog << "PreProcess";
+        break;
+    case 1:
+        gLog << "Process";
+        break;
+    case 2:
+        gLog << "PostProcess";
+        break;
+    case 3:
+        gLog << "ReInit";
+        break;
+
+    }
+    gLog << "-function." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+void MTaskInteractive::Free(Int_t no)
+{
+    if (!fCall[no])
+        return;
+    delete fCall[no];
+    fCall[no] = 0;
+}
Index: branches/Mars_McMismatchStudy/mbase/MTaskInteractive.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTaskInteractive.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTaskInteractive.h	(revision 17960)
@@ -0,0 +1,49 @@
+#ifndef MARS_MTaskInteractive
+#define MARS_MTaskInteractive
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MFilter;
+class MTaskList;
+
+class MTaskInteractive : public MTask
+{
+private:
+    TMethodCall *fCall[4];
+
+    Int_t  (*fPreProcess)(MParList *list);
+    Int_t  (*fProcess)();
+    Int_t  (*fPostProcess)();
+    Bool_t (*fReInit)(MParList *list);
+
+    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; }
+    Bool_t ReInit(MParList *list)     { if (fCall[3]) return Return(3, &list); return fReInit      ? (*fReInit)(list)     : 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); }
+    void SetReInit(Bool_t (*func)(MParList *list))    { fReInit      = func; Free(3); }
+
+    // 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; }
+    void SetReInit(void *fcn)      { Set(fcn, 3, "MParList*"); fReInit     =0; }
+
+    ClassDef(MTaskInteractive, 0) // Interactive task
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MTaskList.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTaskList.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTaskList.cc	(revision 17960)
@@ -0,0 +1,1141 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTaskList
+//
+// Collection of tasks.
+//
+// A tasklist is necessary to run the eventloop. It contains the scheduled
+// tasks, which should be executed in your program.
+//
+// To add a task use AddToList.
+//
+// The tasklist itself is a task, too. You can add a tasklist to another
+// tasklist. This makes sense, if you want to filter the execution of
+// more than one task of your tasklist using the same filter.
+//
+// The tasks in the list are idetified by their names. If more than one
+// task has the same name, the tasklist will still work correctly, but
+// you might run into trouble trying to get a pointer to a task by name
+// from the list.
+//
+// Remark: The Process function is only executed if the class of your task
+//         overloads Process() or if the task itself is a MTask. This
+//         means if you have a task without Process() (only PreProcess
+//         and PostProcess no time is lost during execution)
+//
+// Warning:
+//  Be carefull if you are writing your tasklist
+//  (eg. MWriteRootFile("file.root", "MTaskList")) to a file. You may
+//  not be able to initialize a new working tasklist from a file if
+//   a) Two Paramerer containers with the same names are existing in the
+//      MParList.
+//   b) You used a container somewhere which is not part of MParList.
+//      (eg. You specified a pointer to a MH container in MFillH which is
+//      not added to the parameter list.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTaskList.h"
+
+#include <fstream>           // ofstream, SavePrimitive
+
+#include <TSystem.h>         // gSystem
+#include <TOrdCollection.h>  // TOrdCollection
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIter.h"
+#include "MFilter.h"
+#include "MParList.h"
+#include "MInputStreamID.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MTaskList);
+
+using namespace std;
+
+//#define DEBUG_PROCESS
+#undef DEBUG_PROCESS
+
+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) : fTasks(0), fParList(0), fNumPasses(0), fNumPass(0)
+{
+    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(const MTaskList &ts) : MTask(), fNumPasses(ts.fNumPasses)
+{
+    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->R__FOR_EACH(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->R__FOR_EACH(MTask, SetDisplay)(d);
+    MTask::SetDisplay(d);
+}
+
+void MTaskList::SetAccelerator(Byte_t acc)
+{
+    fTasks->R__FOR_EACH(MTask, SetAccelerator)(acc);
+    MTask::SetAccelerator(acc);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the serial number for the all tasks in the list and the tasklist
+//  itself.
+//
+void MTaskList::SetSerialNumber(Byte_t num)
+{
+    fTasks->R__FOR_EACH(MTask, SetSerialNumber)(num);
+    MTask::SetSerialNumber(num);
+}
+
+Bool_t MTaskList::CheckAddToList(MTask *task, /*const char *type,*/ const MTask *where) const
+{
+    //
+    // Sanity check
+    //
+    if (!task)
+    {
+        *fLog << err << "ERROR - task argument=NULL." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Get Name of new task
+    //
+    const char *name = task->GetName();
+
+    //
+    // Check if the new task is already existing in the list
+    //
+    const TObject *objn = fTasks->FindObject(name);
+    const TObject *objt = fTasks->FindObject(task);
+
+    if (objn || objt)
+    {
+        //
+        // If the task is already in the list ignore it.
+        //
+        if (objt || objn==task)
+        {
+            *fLog << warn << dbginf << "Warning: Task '" << task->GetName() << ", 0x" << (void*)task;
+            *fLog << "' already existing in '" << GetName() << "'... ignoring." << endl;
+            return kTRUE;
+        }
+
+        //
+        // Otherwise add it to the list, but print a warning message
+        //
+        *fLog << warn << dbginf << "Warning: Task '" << task->GetName();
+        *fLog << "' already existing in '" << GetName() << "'." << endl;
+        *fLog << "You may not be able to get a pointer to this task by name." << endl;
+    }
+
+    if (!where)
+        return kTRUE;
+
+    if (fTasks->FindObject(where))
+        return kTRUE;
+
+    *fLog << err << dbginf << "Error: Cannot find task after which the new task should be scheduled!" << endl;
+    return kFALSE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// schedule task for execution, before 'where'.
+// 'type' is the event type which should be processed
+//
+Bool_t MTaskList::AddToListBefore(MTask *task, const MTask *where, const char *type)
+{
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    // FIXME: We agreed to put the task into list in an ordered way.
+    if (!CheckAddToList(task, /*type,*/ where))
+        return kFALSE;
+
+    const TString stream = type ? (TString)type : task->GetStreamId();
+
+    *fLog << inf3 << "Adding " << task->GetName() << " to " << GetName() << " for " << stream << "... " << flush;
+    task->SetStreamId(stream);
+    task->SetBit(kMustCleanup);
+    fTasks->AddBefore((TObject*)where, task);
+    *fLog << "done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// schedule task for execution, after 'where'.
+// 'type' is the event type which should be processed
+//
+Bool_t MTaskList::AddToListAfter(MTask *task, const MTask *where, const char *type)
+{
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    // FIXME: We agreed to put the task into list in an ordered way.
+    if (!CheckAddToList(task, /*type,*/ where))
+        return kFALSE;
+
+    const TString stream = type ? (TString)type : task->GetStreamId();
+
+    *fLog << inf3 << "Adding " << task->GetName() << " to " << GetName() << " for " << stream << "... " << flush;
+    task->SetStreamId(stream);
+    task->SetBit(kMustCleanup);
+    fTasks->AddAfter((TObject*)where, task);
+    *fLog << "done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// schedule task for execution, 'type' is the event type which should
+// be processed
+//
+Bool_t MTaskList::AddToList(MTask *task, const char *type)
+{
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    // FIXME: We agreed to put the task into list in an ordered way.
+    if (!CheckAddToList(task/*, type*/))
+        return kFALSE;
+
+    const TString stream = type ? (TString)type : task->GetStreamId();
+
+    *fLog << inf3 << "Adding " << task->GetName() << " to " << GetName() << " for " << stream << "... " << flush;
+    task->SetStreamId(stream);
+    task->SetBit(kMustCleanup);
+    fTasks->Add(task);
+    *fLog << "done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all objects in list to the tasklist. If some of them do not
+// inherit from MTask return kFALSE, also if AddToList returns an error
+// for one of the tasks
+//
+Bool_t MTaskList::AddToList(const TList &list, const char *tType)
+{
+    TIter Next(&list);
+    TObject *obj=0;
+    while ((obj=Next()))
+    {
+        if (!obj->InheritsFrom(MTask::Class()))
+        {
+            *fLog << err << "ERROR - Object " << obj->GetName() << " doesn't inherit from MTask..." << endl;
+            return kFALSE;
+        }
+
+        if (!AddToList(static_cast<MTask*>(obj), tType))
+            return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all objects in list to the tasklist after task where. If some of
+// them do not inherit from MTask return kFALSE, also if AddToListAfter
+// returns an error for one of the tasks
+//
+Bool_t MTaskList::AddToListAfter(const TList &list, const MTask *where, const char *tType)
+{
+    TIter Next(&list);
+    TObject *obj=0;
+    while ((obj=Next()))
+    {
+        if (!obj->InheritsFrom(MTask::Class()))
+        {
+            *fLog << err << "ERROR - Object " << obj->GetName() << " doesn't inherit from MTask..." << endl;
+            return kFALSE;
+        }
+
+        if (!AddToListAfter(static_cast<MTask*>(obj), where, tType))
+            return kFALSE;
+
+        where = static_cast<MTask*>(obj);
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all objects in list to the tasklist before task where. If some of
+// them do not inherit from MTask return kFALSE, also if AddToListBefore
+// returns an error for one of the tasks
+//
+Bool_t MTaskList::AddToListBefore(const TList &list, const MTask *where, const char *tType)
+{
+    TIter Next(&list);
+    TObject *obj=0;
+    while ((obj=Next()))
+    {
+        if (!obj->InheritsFrom(MTask::Class()))
+        {
+            *fLog << err << "ERROR - Object " << obj->GetName() << " doesn't inherit from MTask..." << endl;
+            return kFALSE;
+        }
+
+        if (!AddToListBefore(static_cast<MTask*>(obj), where, tType))
+            return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object in the list.
+//  'name' is the name of the object you are searching for.
+//
+TObject *MTaskList::FindObject(const char *name) const
+{
+    return fTasks->FindObject(name);
+}
+
+// --------------------------------------------------------------------------
+//
+//  check if the object is in the list or not
+//
+TObject *MTaskList::FindObject(const TObject *obj) const
+{
+    return fTasks->FindObject(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// find recursively a tasklist which contains a task with name task
+//
+MTaskList *MTaskList::FindTaskList(const char *task)
+{
+    TIter Next(fTasks);
+    TObject *o = 0;
+    while ((o=Next()))
+    {
+        if (strcmp(o->GetName(), task)==0)
+           return this;
+
+        MTaskList *l = dynamic_cast<MTaskList*>(o);
+        if (!l)
+            continue;
+
+        if ((l=l->FindTaskList(task)))
+            return l;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// find recursively a tasklist which contains a task task
+//
+MTaskList *MTaskList::FindTaskList(const MTask *task)
+{
+    TIter Next(fTasks);
+    TObject *o = 0;
+    while ((o=Next()))
+    {
+       if (o==task)
+          return this;
+
+        MTaskList *l = dynamic_cast<MTaskList*>(o);
+        if (!l)
+            continue;
+
+        if ((l=l->FindTaskList(task)))
+            return l;
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  removes a task from the list (used in PreProcess).
+//  if kIsOwner is set the task is deleted. (see SetOwner())
+//
+void MTaskList::Remove(MTask *task)
+{
+    if (!task)
+        return;
+
+    // First remove it from the list(s) so that a later RecursiveRemove
+    // cannot fint the task again
+    TObject *obj = fTasks->Remove(task);
+
+    // Now do a recursive remove on all other tasks.
+    fTasks->RecursiveRemove(task);
+
+    if (obj && TestBit(kIsOwner))
+        delete obj;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call MTask::RecursiveRemove
+// Call fTasks->RecursiveRemove
+//
+void MTaskList::RecursiveRemove(TObject *obj)
+{
+    MTask::RecursiveRemove(obj);
+
+    if (obj==fTasks)
+        fTasks=NULL;
+
+    if (fTasks)
+    {
+        fTasks->RecursiveRemove(obj);
+
+        // In theory this call is obsolete
+        fTasksProcess.RecursiveRemove(obj);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  do pre processing (before eventloop) of all tasks in the task-list
+//  Only if a task overwrites the Process function the task is
+//  added to the fTaskProcess-List. This makes the execution of the
+//  tasklist a little bit (only a little bit) faster, bacause tasks
+//  doing no Processing are not Processed.
+//
+Int_t MTaskList::PreProcess(MParList *pList)
+{
+    *fLog << all << "Preprocessing... " << flush;
+    if (fDisplay)
+    {
+        // Set status lines
+        fDisplay->SetStatusLine1("PreProcessing...");
+        fDisplay->SetStatusLine2("");
+    }
+
+    fParList = pList;
+
+    //
+    // Make sure, that the ReadyToSave flag is not reset from a tasklist
+    // running as a task in another tasklist.
+    //
+    const Bool_t noreset = fParList->TestBit(MParList::kDoNotReset);
+    if (!noreset)
+        fParList->SetBit(MParList::kDoNotReset);
+
+    //
+    //  create the Iterator over the tasklist
+    //
+    TIter Next(fTasks);
+
+    MTask *task=NULL;
+
+    //
+    // loop over all tasks for preproccesing
+    //
+    while ((task=(MTask*)Next()))
+    {
+        //
+        // PreProcess the task and check for it's return value.
+        //
+        switch (task->CallPreProcess(fParList))
+        {
+        case kFALSE:
+            return kFALSE;
+
+        case kTRUE:
+            // Handle GUI events (display changes, mouse clicks)
+            if (fDisplay)
+                gSystem->ProcessEvents();
+            continue;
+
+        case kSKIP:
+            Remove(task);
+            continue;
+        }
+
+        *fLog << err << dbginf << "PreProcess of " << task->GetDescriptor();
+        *fLog << " returned an unknown value... aborting." << endl;
+        return kFALSE;
+    }
+
+    *fLog << all << endl;
+
+    //
+    // Reset the ReadyToSave flag.
+    //
+    if (!noreset)
+    {
+        fParList->SetReadyToSave(kFALSE);
+        fParList->ResetBit(MParList::kDoNotReset);
+    }
+
+    //
+    // loop over all tasks to fill fTasksProcess
+    //
+    Next.Reset();
+    fTasksProcess.Clear();
+    while ((task=(MTask*)Next()))
+        if (task->IsA()==MTask::Class() || task->Overwrites("Process"))
+            fTasksProcess.Add(task);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  do reinit of all tasks in the task-list
+//
+Bool_t MTaskList::ReInit(MParList *pList)
+{ 
+    *fLog << all << "Reinit... " << flush;
+
+    if (!pList)
+        pList = fParList;
+
+    //
+    // Make sure, that the ReadyToSave flag is not reset from a tasklist
+    // running as a task in another tasklist.
+    //
+    const Bool_t noreset = pList->TestBit(MParList::kDoNotReset);
+    if (!noreset)
+        pList->SetBit(MParList::kDoNotReset);
+
+    //
+    //  create the Iterator over the tasklist
+    //
+    TIter Next(fTasks);
+
+    MTask *task=NULL;
+
+    //
+    // loop over all tasks for reinitialization
+    //
+    while ((task=(MTask*)Next()))
+    {
+        // Supress output if not necessary
+        if (!task->Overwrites("ReInit"))
+            continue;
+
+        *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;
+}
+
+Int_t MTaskList::ProcessTaskList()
+{
+    //
+    //  create the Iterator for the TaskList
+    //
+    TIter Next(&fTasksProcess);
+    MTask *task=NULL;
+
+#ifdef DEBUG_PROCESS
+    *fLog << all << "ProcessTaskList - " << GetDescriptor() << " - start." << endl;
+#endif
+
+    //
+    // loop over all tasks for processing
+    //
+    Int_t rc = kTRUE;
+    while ( (task=(MTask*)Next()) )
+    {
+#ifdef DEBUG_PROCESS
+        *fLog << all << "Process - " << (void*)task << " " << flush;
+        *fLog << task->GetDescriptor() << "... " << flush;
+#endif
+        //
+        // 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
+            //
+#ifdef DEBUG_PROCESS
+            *fLog << "true." << endl;
+#endif
+            continue;
+
+        case kFALSE:
+            //
+            // an error occured: stop eventloop
+            //
+            rc = kFALSE;
+            *fLog << inf << task->GetDescriptor() << " has stopped execution of " << GetDescriptor() << "." << endl;
+            break;
+
+        case kERROR:
+            //
+            // an error occured: stop eventloop and return: failed
+            //
+            *fLog << err << "Fatal error occured while Process() of " << task->GetDescriptor() << "... stopped." << endl;
+            rc = kERROR;
+            break;
+
+        case kCONTINUE:
+            //
+            // something occured: skip the rest of the tasks for this event
+            //
+#ifdef DEBUG_PROCESS
+            *fLog << "continue." << endl;
+#endif
+            rc = kCONTINUE;
+            break;
+
+        default:
+            *fLog << err << dbginf << "Unknown return value from MTask::Process()... stopped." << endl;
+            rc = kERROR;
+            break;
+        }
+        break;
+    }
+
+#ifdef DEBUG_PROCESS
+    *fLog << all << "ProcessTaskList - " << GetDescriptor() << " - done." << endl;
+#endif
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// do the event execution of all tasks in the task-list.
+//
+// If a task returns kCONTINUE, kCONTINUE is propagated if the
+// number of passes==0, otherwise kTRUE is returned instead.
+//
+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);
+        if (!HasAccelerator(kAccDontReset))
+            fParList->Reset();
+    }
+
+    // Initialize storage variable for the return code
+    Int_t rc = kTRUE;
+
+    // Execute the task list at least once
+    const UInt_t cnt = fNumPasses==0 ? 1 : fNumPasses;
+    for (fNumPass=0; fNumPass<cnt; fNumPass++)
+    {
+        // Execute the tasklist once
+        rc = ProcessTaskList();
+        // In cae of error or a stop-request leave loop
+        if (rc==kERROR || rc==kFALSE)
+            break;
+    }
+
+    // Reset to the default
+    if (!noreset)
+    {
+        fParList->SetReadyToSave(kFALSE);
+        fParList->ResetBit(MParList::kIsProcessing);
+    }
+
+    // If the number of passes==0 <default> propagete kCONTINUE
+    if (rc==kCONTINUE)
+        return fNumPasses==0 ? kCONTINUE : kTRUE;
+
+    // Return return code
+    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->R__FOR_EACH(MTask, PrintStatistics)(lvl+1, title, GetCpuTime());
+
+    if (lvl==0)
+        *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call 'Print()' of all tasks
+//
+void MTaskList::Print(Option_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(ostream &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->R__FOR_EACH(MParContainer, GetNames)(arr);
+}
+
+void MTaskList::SetNames(TObjArray &arr)
+{
+    MParContainer::SetNames(arr);
+    fTasks->R__FOR_EACH(MParContainer, SetNames)(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Int_t MTaskList::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (print)
+        *fLog << all << "MTaskList::ReadEnv: " << prefix << " (" << (int)print << ")" << endl;
+
+    MParContainer *cont = NULL;
+
+    MIter Next(fTasks);
+    while ((cont=Next()))
+    {
+        if (cont->InheritsFrom("MTaskList"))
+        {
+            if (cont->ReadEnv(env, prefix, print)==kERROR)
+                return kERROR;
+            continue;
+        }
+
+        if (cont->TestEnv(env, prefix, print)==kERROR)
+            return kERROR;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MTaskList::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    MParContainer *cont = NULL;
+
+    MIter Next(fTasks);
+    while ((cont=Next()))
+        if (!cont->WriteEnv(env, prefix, print))
+            return kFALSE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Removes a task from the tasklist. Returns kFALSE if the object was not
+// found in the list.
+//
+Bool_t MTaskList::RemoveFromList(MTask *task)
+{
+    TObject *obj = fTasks->Remove(task);
+
+    //
+    // If the task was found in the list try to remove it from the second
+    // list, too.
+    //
+    if (obj)
+        fTasksProcess.Remove(task);
+
+    return obj ? kTRUE : kFALSE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Removes all task of the TList from the tasklist. Returns kFALSE if any
+// of the objects was not an MTask or not found in the list.
+//
+Bool_t MTaskList::RemoveFromList(const TList &list)
+{
+    Bool_t rc = kTRUE;
+
+    TIter Next(&list);
+    TObject *obj=0;
+    while ((obj=Next()))
+    {
+        if (!obj->InheritsFrom(MTask::Class()))
+        {
+            *fLog << err << "ERROR - Object " << obj->GetName() << " doesn't inherit from MTask..." << endl;
+            rc = kFALSE;
+            continue;
+        }
+
+        if (!RemoveFromList(static_cast<MTask*>(obj)))
+            rc = kFALSE;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object with the same name in the list and replace it with
+//  the new one. If the kIsOwner flag is set and the object was not
+//  created automatically, the object is deleted.
+//
+Bool_t MTaskList::Replace(MTask *task)
+{
+    //
+    //  check if the object (you want to add) exists
+    //
+    if (!task)
+        return kFALSE;
+
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    MTask *obj = (MTask*)FindObject(task->GetName());
+    if (!obj)
+    {
+        *fLog << warn << "No object with the same name '";
+        *fLog << task->GetName() << "' in list... adding." << endl;
+        return AddToList(task);
+    }
+
+    if (task==obj)
+        return kTRUE;
+
+    *fLog << inf2 << "Replacing " << task->GetName() << " in " << GetName() << " for " << obj->GetStreamId() << "... " << flush;
+    task->SetStreamId(obj->GetStreamId());
+    task->SetBit(kMustCleanup);
+    fTasks->AddAfter((TObject*)obj, task);
+    *fLog << "done." << endl;
+
+    RemoveFromList(obj);
+
+    if (TestBit(kIsOwner))
+        delete obj;
+
+    //*fLog << inf << "MTask '" << task->GetName() << "' found and replaced..." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Can be used to create an iterator over all tasks, eg:
+//   MTaskList tlist;
+//   TIter Next(tlist); // Be aware: Use a object here rather than a pointer!
+//   TObject *o=0;
+//   while ((o=Next()))
+//   {
+//       [...]
+//   }
+//
+MTaskList::operator TIterator*() const
+{
+    return new TListIter(fTasks);
+}
Index: branches/Mars_McMismatchStudy/mbase/MTaskList.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTaskList.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTaskList.h	(revision 17960)
@@ -0,0 +1,106 @@
+#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
+
+    UInt_t fNumPasses;
+    UInt_t fNumPass; //!
+
+    enum { kIsOwner = BIT(14) };
+
+    void   Remove(MTask *task);
+    void   StreamPrimitive(std::ostream &out) const;
+    Bool_t CheckAddToList(MTask *task, /*const char *tType,*/ const MTask *where=NULL) const;
+    Int_t  ProcessTaskList();
+
+public:
+    MTaskList(const char *name=NULL, const char *title=NULL);
+    MTaskList(const MTaskList &ts);
+
+    ~MTaskList();
+
+    void SetLogStream(MLog *log);
+    void SetDisplay(MStatusDisplay *d);
+    void SetAccelerator(Byte_t acc=kAccStandard);
+    void SetNumPasses(UInt_t cnt=0) { fNumPasses=cnt; }
+
+    UInt_t GetNumPass() const { return fNumPass; }
+    UInt_t GetNumPasses() const { return fNumPasses; }
+
+    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");
+    Bool_t AddToList(const TList &list, const char *tType="All");
+    Bool_t AddToListAfter(const TList &list, const MTask *where, const char *tType="All");
+    Bool_t AddToListBefore(const TList &list, const MTask *where, const char *tType="All");
+
+    void SetSerialNumber(Byte_t num);
+
+    Bool_t Replace(MTask *obj);
+    Bool_t RemoveFromList(MTask *task);
+    Bool_t RemoveFromList(const TList &list);
+
+    TObject *FindObject(const char *name) const;
+    TObject *FindObject(const TObject *obj) const;
+
+    MTask *FindTask(const char *name) const
+    {
+        return (MTask*)FindObject(name);
+    }
+    MTask *FindTask(const MTask *obj) const
+    {
+        return (MTask*)FindObject(obj);
+    }
+    MTaskList *FindTaskList(const char *task);
+    MTaskList *FindTaskList(const MTask *task);
+
+    Bool_t ReInit(MParList *pList=NULL);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void Print(Option_t *opt = "") const;
+    void PrintStatistics(const Int_t lvl=0, Bool_t title=kFALSE, Double_t time=-1) const;
+    void SetOwner(Bool_t enable=kTRUE);
+
+    const TList *GetList() const { return fTasks; }
+
+    void GetNames(TObjArray &arr) const;
+    void SetNames(TObjArray &arr);
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+    void   RecursiveRemove(TObject *obj);
+
+    operator TIterator*() const;
+
+    ClassDef(MTaskList, 1) //collection of tasks to be performed in the eventloop
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MThread.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MThread.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MThread.cc	(revision 17960)
@@ -0,0 +1,102 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  1/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MThread
+//
+// Implementing a slightly simplified interface to multi-threading
+// based on TThread
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MThread.h"
+
+ClassImp(MThread);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Return the thread's state as string
+//
+TString MThread::GetThreadStateStr() const
+{
+    switch (fThread.GetState())
+    {
+    case TThread::kInvalidState:
+        return "Invalid - thread was not created properly";
+    case TThread::kNewState:
+        return "New - thread object exists but hasn't started";
+    case TThread::kRunningState:
+        return "Running - thread is running";
+    case TThread::kTerminatedState:
+        return "Terminated - thread has terminated but storage has not yet been reclaimed (i.e. waiting to be joined)";
+    case TThread::kFinishedState:
+        return "Finished - thread has finished";
+    case TThread::kCancelingState:
+        return "Canceling - thread in process of canceling";
+    case TThread::kCanceledState:
+        return "Canceled - thread has been canceled";
+    case TThread::kDeletingState:
+        return "Deleting - thread in process of deleting";
+    };
+    return "Unknown";
+}
+
+/*
+{
+    TMethodCall call(cl, "Name", 0);
+
+    if (!call.IsValid())
+        return 0;
+
+    //const char    *GetParams() const { return fParams.Data(); }
+    //const char    *GetProto() const { return fProto.Data(); }
+
+    switch (call.ReturnType())
+    {
+    case kLong:
+        break;
+    case kDouble:
+        break;
+    case kString:
+        break;
+    case kOther:
+        break;
+    case kNone:
+        break;
+    }
+
+    // NOTE execute functions are locked by a global mutex!!!
+
+   void     Execute(void *object);
+   void     Execute(void *object, Long_t &retLong);
+   void     Execute(void *object, Double_t &retDouble);
+   void     Execute(void *object, char **retText);
+
+   void     Execute();
+   void     Execute(Long_t &retLong);
+   void     Execute(Double_t &retDouble);
+}
+*/
Index: branches/Mars_McMismatchStudy/mbase/MThread.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MThread.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MThread.h	(revision 17960)
@@ -0,0 +1,81 @@
+#ifndef MARS_MThread
+#define MARS_MThread
+
+#ifndef ROOT_TThread
+#include <TThread.h>
+#endif
+
+class MThread // We don't want MThread to be derived from TObject
+{
+private:
+    TThread fThread;
+
+    Int_t fNumCleanups;
+
+    virtual void CleanUp() { }
+    static void MapCleanUp(void *arg)
+    {
+        MThread *th = (MThread*)arg;
+        th->CleanUp();
+    }
+
+    virtual Int_t Thread() = 0;
+    static void *MapThread(void *arg)
+    {
+        // GetPriority();     High: -1 - -20, Norm: 0, Low: 1-20
+        // pthread_setschedprio(SelfId(), priority);
+        // 0: ok,
+
+        TThread::CleanUpPush((void*)&MapCleanUp, arg);
+
+        MThread *th = (MThread*)arg;
+        return reinterpret_cast<void*>(th->Thread());
+    }
+
+public:
+    MThread(TThread::EPriority pri = TThread::kNormalPriority) :
+        fThread(MapThread, this, pri), fNumCleanups(0) { }
+    MThread(const char *thname, TThread::EPriority pri = TThread::kNormalPriority) :
+        fThread(thname, MapThread, this, pri), fNumCleanups(0) { }
+    virtual ~MThread() { }
+
+    // Setter: Thread control
+    Int_t RunThread(void *arg = 0) { return fThread.Run(arg); }
+
+    // Send cancel request and wait for cancellation
+    // 13 is returned if thread is not running,
+    // the return code of Join otherwise
+    Int_t CancelThread(void **ret = 0) {
+        const Int_t rc = fThread.Kill();
+        if (rc==13) // Thread not running
+            return rc;
+        return fThread.Join(ret);
+    }
+
+    // Int_t            Kill() { return fThread.Kill(); }
+    // Long_t           Join(void **ret = 0) { return fThread.Join(ret); }
+
+    // void             SetPriority(EPriority pri)
+    // void             Delete(Option_t *option="") { TObject::Delete(option); }
+
+    // Getter
+    TThread::EState  GetThreadState() const { return fThread.GetState(); }
+    TString          GetThreadStateStr() const;
+    Long_t           GetThreadId() const { return fThread.GetId(); }
+    // EPriority        GetPriority() const { return fPriority; }
+
+    Bool_t IsThreadRunning()  const { return fThread.GetState()==TThread::kRunningState; }
+    Bool_t IsThreadCanceled() const { return fThread.GetState()==TThread::kCancelingState; }
+
+    // This is a version of usleep which is a cancel point
+    static void Sleep(UInt_t us)
+    {
+        TThread::SetCancelOn();
+        usleep(us);
+        TThread::SetCancelOff();
+    }
+
+    ClassDef(MThread,0)  // A simplified interface to TThread
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/MTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTime.cc	(revision 17960)
@@ -0,0 +1,1182 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTime
+//
+// A generalized MARS time stamp.
+//
+//
+// We do not use floating point values here, because of several reasons:
+//  - having the times stored in integers only is more accurate and
+//    more reliable in comparison conditions
+//  - storing only integers gives similar bit-pattern for similar times
+//    which makes compression (eg gzip algorithm in TFile) more
+//    successfull
+//
+// Note, that there are many conversion function converting the day time
+// into a readable string. Also a direct interface to SQL time strings
+// is available.
+//
+// If you are using MTime containers as axis lables in root histograms
+// use GetAxisTime(). Make sure that you use the correct TimeFormat
+// on your TAxis (see GetAxisTime())
+//
+//
+// WARNING: Be carefull changing this class. It is also used in the
+//          MAGIC drive software cosy as VERY IMPORTANT stuff!
+//
+// Remarke: If you encounter strange behaviour, check the casting.
+//          Note, that on Linux machines ULong_t and UInt_t is the same.
+//
+//
+// Version 1:
+// ----------
+//  - first version
+//
+// Version 2:
+// ----------
+//  - removed fTimeStamp[2]
+//
+// Version 3:
+// ----------
+//  - removed fDurtaion - we may put it back when it is needed
+//  - complete rewrite of the data members (old ones completely replaced)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTime.h"
+
+#include <iomanip>
+
+#ifndef __USE_XOPEN
+#define __USE_XOPEN // on some systems needed for strptime
+#endif
+
+#include <time.h>     // struct tm
+#include <sys/time.h> // struct timeval
+
+#include <TTime.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MAstro.h"
+#include "MString.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
+const UInt_t MTime::kDaySec = 3600*24;         // [s] 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
+        d>2400000 ? SetJD(d) : SetMjd(d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Calls Set(y, m, d, h, min, s, ms, ns).
+// To check validity test for (*this)==MTime()
+//
+MTime::MTime(UShort_t y, Byte_t m, Byte_t d, Byte_t h, Byte_t min, Byte_t s, UShort_t ms, UInt_t ns)
+{
+    Set(y, m, d, h, min, s, ms, ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return date as year(y), month(m), day(d)
+//
+void MTime::GetDate(UShort_t &y, Byte_t &m, Byte_t &d) const
+{
+    MAstro::Mjd2Ymd((Long_t)fTime<0?fMjd-1:fMjd, y, m, d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return date as year(y), month(m), day(d). If the time is afternoon
+// (>=13:00:00) the date of the next day is returned.
+//
+void MTime::GetDateOfSunrise(UShort_t &y, Byte_t &m, Byte_t &d) const
+{
+    MAstro::Mjd2Ymd(fMjd, y, m, d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return date as year(y), month(m), day(d). If the time is afternoon
+// (>=13:00:00) the date of the next day is returned.
+//
+MTime MTime::GetDateOfSunrise() const
+{
+    UShort_t y;
+    Byte_t m;
+    Byte_t d;
+
+    MAstro::Mjd2Ymd(fMjd, y, m, d);
+
+    return MTime(y, m, d);
+}
+
+// --------------------------------------------------------------------------
+//
+// GetMoonPhase - calculate phase of moon as a fraction:
+//  Returns -1 if calculation failed
+//
+//  see MAstro::GetMoonPhase
+//
+Double_t MTime::GetMoonPhase() const
+{
+    return MAstro::GetMoonPhase(GetMjd());
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the Period to which the time belongs to. The Period is defined
+// as the number of synodic months ellapsed since the first full moon
+// after Jan 1st 1980 (which was @ MJD=44240.37917)
+//
+//   see MAstro::GetMoonPeriod
+//
+Double_t MTime::GetMoonPeriod() const
+{
+    return MAstro::GetMoonPeriod(GetMjd());
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the time corresponding to the moon period.
+//
+//   see MTime::GetMoonPeriod and MAstro::GetMoonPeriod
+//
+void MTime::SetMoonPeriod(Double_t p)
+{
+    SetMjd(MAstro::GetMoonPeriodMjd(p));
+}
+
+// --------------------------------------------------------------------------
+//
+// To get the moon period as defined for MAGIC observation we take the
+// nearest integer mjd, eg:
+//   53257.8 --> 53258
+//   53258.3 --> 53258
+ // Which is the time between 13h and 12:59h of the following day. To
+// this day-period we assign the moon-period at midnight. To get
+// the MAGIC definition we now substract 284.
+//
+// For MAGIC observation period do eg:
+//   GetMagicPeriod(53257.91042)
+// or
+//   MTime t;
+//   t.SetMjd(53257.91042);
+//   GetMagicPeriod(t.GetMjd());
+// or
+//   MTime t;
+//   t.Set(2004, 1, 1, 12, 32, 11);
+//   GetMagicPeriod(t.GetMjd());
+//
+// To get a floating point magic period use
+//   GetMoonPeriod()-284
+//
+//  see MAstro::GetMagicPeriod
+//
+Int_t MTime::GetMagicPeriod() const
+{
+    return MAstro::GetMagicPeriod(GetMjd());
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the start time (noon) of a MAGIC period
+//
+//   see MTime::GetMagicPeriod and MAstro::GetMagicPeriod
+//
+void MTime::SetMagicPeriodStart(Int_t p)
+{
+    SetMjd(MAstro::GetMagicPeriodStart(p));
+}
+
+UInt_t MTime::GetNightAsInt() const
+{
+    UShort_t y;
+    Byte_t m, d;
+
+    MAstro::Mjd2Ymd(fMjd+0.5, y, m, d);
+
+    return UInt_t(y)*10000 + UInt_t(m)*100 + 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/1970 0:00h
+// This is compatible with root's definition used in the constructor of
+// TDatime.
+//
+TDatime MTime::GetRootDatime() const
+{
+    return TDatime((UInt_t)((GetMjd()-40587)*kDaySec));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a time which is expressed in seconds since 01/01/1995 0:00h
+// This is compatible with root's definition used in TAxis.
+// Note, a TAxis always displayes (automatically) given times in
+// local time (while here we return UTC) such, that you may encounter
+// strange offsets. You can get rid of this by calling:
+//    TAxis::SetTimeFormat("[your-format] %F1995-01-01 00:00:00 GMT");
+// Note that an offset of 1970-01-01 does NOT work, because root
+// assumes that this is local time, tries to convert that to UTC,
+// which gives a negative unix time stamp in Europe, and ignores it.
+//
+Double_t MTime::GetAxisTime() const
+{
+    return (GetMjd()-49718)*kDaySec;
+}
+
+// --------------------------------------------------------------------------
+//
+// Counterpart of GetAxisTime
+//
+void MTime::SetAxisTime(Double_t time)
+{
+    SetMjd(time/kDaySec+49718);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set unix time (seconds since epoche 1970-01-01 00:00)
+//
+void MTime::SetUnixTime(Long64_t sec, ULong64_t usec)
+{
+    const Long64_t totsec = sec + usec/1000000;
+    const UInt_t   mjd    = totsec/kDaySec + 40587;
+
+    const UInt_t   ms     = totsec%kDaySec*1000 + (usec/1000)%1000;
+    const UInt_t   us     = usec%1000;
+
+    SetMjd(mjd, ms, us*1000);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to time expressed in a 'struct timeval'
+//
+void MTime::Set(const struct timeval &tv)
+{
+    SetUnixTime(tv.tv_sec, tv.tv_usec);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set this to the date of easter corresponding to the given year.
+// If calculation was not possible it is set to MTime()
+//
+// The date corresponding to the year of MTime(-1) is returned
+// if year<0
+//
+// The date corresponding to the Year() is returned if year==0.
+//
+//  for more information see: GetEaster and MAstro::GetEasterOffset()
+//
+void MTime::SetEaster(Short_t year)
+{
+    *this = GetEaster(year==0 ? Year() : year);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a time expressed in MJD, Time of Day (eg. 23:12.779h expressed
+// in milliseconds) and a nanosecond part.
+//
+Bool_t MTime::SetMjd(UInt_t mjd, ULong_t ms, UInt_t ns)
+{
+    // [d]  mjd  (eg. 52320)
+    // [ms] time (eg. 17h expressed in ms)
+    // [ns] time (ns part of time)
+
+    if (ms>kDay-1 || ns>999999)
+        return kFALSE;
+
+    const Bool_t am = ms<kHour*13; // day of sunrise?
+
+    fMjd     = am ? mjd : mjd + 1;
+    fTime    = (Long_t)(am ? ms  : ms-kDay);
+    fNanoSec = ns;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to given MJD (eg. 52080.0915449892)
+//
+void MTime::SetMjd(Double_t m)
+{
+    const UInt_t   mjd  = (UInt_t)TMath::Floor(m);
+    const Double_t frac = fmod(m, 1)*kDay; // [ms] Fraction of day
+    const UInt_t   ns   = (UInt_t)fmod(frac*1e6, 1000000);
+
+    SetMjd(mjd, (ULong_t)TMath::Floor(frac), ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to given time and date
+//
+Bool_t MTime::Set(UShort_t y, Byte_t m, Byte_t d, Byte_t h, Byte_t min, Byte_t s, UShort_t ms, UInt_t ns)
+{
+    if (h>23 || min>59 || s>59 || ms>999 || ns>999999)
+        return kFALSE;
+
+    const Int_t mjd = MAstro::Ymd2Mjd(y, m, d);
+    if (mjd<0)
+        return kFALSE;
+
+    const ULong_t tm = ((((h*60+min)*60)+s)*1000)+ms;
+
+    return SetMjd(mjd, tm, ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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(TString str)
+{
+    if (str.IsNull())
+        return kFALSE;
+
+    str.ReplaceAll("T", "");
+
+    if (str.Contains('.'))
+        str += "000";
+
+    UInt_t  y, mon, d, h, m, s, ms;
+
+    if (7==sscanf(str, "%04u-%02u-%02u %02u:%02u:%02u.%03u", &y, &mon, &d, &h, &m, &s, &ms))
+        return Set(y, mon, d, h, m, s, ms);
+
+    if (6==sscanf(str, "%04u-%02u-%02u %02u:%02u:%02u", &y, &mon, &d, &h, &m, &s))
+        return Set(y, mon, d, h, m, s);
+
+    if (5==sscanf(str, "%04u-%02u-%02u %02u:%02u", &y, &mon, &d, &h, &m))
+        return Set(y, mon, d, h, m);
+
+    if (4==sscanf(str, "%04u-%02u-%02u %02u", &y, &mon, &d, &h))
+        return Set(y, mon, d, h);
+
+    if (3==sscanf(str, "%04u-%02u-%02u", &y, &mon, &d))
+        return Set(y, mon, d);
+
+    return 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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to time expressed as float (yymmdd.ffff)
+//  for details see MAstro::Yymmdd2Mjd
+//
+void MTime::SetCorsikaTime(Float_t t)
+{
+    const UInt_t   yymmdd = (UInt_t)TMath::Floor(t);
+    const UInt_t   mjd    = MAstro::Yymmdd2Mjd(yymmdd);
+    const Double_t frac   = fmod(t, 1)*kDay; // [ms] Fraction of day
+    const UInt_t   ns     = (UInt_t)fmod(frac*1e6, 1000000);
+
+    SetMjd(mjd, (ULong_t)TMath::Floor(frac), ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)/kDaySec;
+
+    return fmod(sum, 1)*TMath::TwoPi();//+TMath::TwoPi();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Day of the week: Sun=0, Mon=1, ..., Sat=6
+//
+Byte_t MTime::WeekDay() const
+{
+    return TMath::FloorNint(GetMjd()+3)%7;
+} 
+
+// --------------------------------------------------------------------------
+//
+// Get the day of the year represented by day, month and year.
+// Valid return values range between 1 and 366, where January 1 = 1.
+//
+UInt_t MTime::DayOfYear() const
+{
+    MTime jan1st;
+    jan1st.Set(Year(), 1, 1);
+
+    const Double_t newyear = TMath::Floor(jan1st.GetMjd());
+    const Double_t mjd     = TMath::Floor(GetMjd());
+
+    return TMath::Nint(mjd-newyear)+1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Mjd of the first day (a monday) which belongs to week 1 of
+// the year give as argument. The returned Mjd might be a date in the
+// year before.
+//
+//  see also MTime::Week()
+//
+Int_t MTime::GetMjdWeek1(Short_t year)
+{
+    MTime t;
+    t.Set(year, 1, 4);
+
+    return (Int_t)t.GetMjd() + t.WeekDay() - 6;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the week of the year. Valid week values are between 1 and 53.
+// If for a january date a week number above 50 is returned the
+// week belongs to the previous year. If for a december data 1 is
+// returned the week already belongs to the next year.
+//
+// The year to which the week belongs is returned in year.
+//
+// Die Kalenderwochen werden für Jahre ab 1976 berechnet, da mit
+// Geltung vom 1. Januar 1976 der Wochenbeginn auf Montag festgelegt
+// wurde. Die erste Woche ist definiert als die Woche, in der
+// mindestens 4 der ersten 7 Januartage fallen (also die Woche, in der
+// der 4. Januar liegt). Beides wurde damals festgelegt in der DIN 1355
+// (1974). Inhaltlich gleich regelt das die Internationale Norm
+// ISO 8601 (1988), die von der Europäischen Union als EN 28601 (1992)
+// übernommen und in Deutschland als DIN EN 28601 (1993) umgesetzt
+// wurde.
+//
+Int_t MTime::Week(Short_t &year) const
+{
+    // Possibilities for Week 1:
+    //
+    //    Mo 4.Jan:   Mo  4. - So 10.    -0   6-6
+    //    Di 4.Jan:   Mo  3. - So  9.    -1   6-5
+    //    Mi 4.Jan:   Mo  2. - So  8.    -2   6-4
+    //    Do 4.Jan:   Mo  1. - So  7.    -3   6-3
+    //    Fr 4.Jan:   Mo 31. - So  6.    -4   6-2
+    //    Sa 4.Jan:   Mo 30. - So  5.    -5   6-1
+    //    So 4.Jan:   Mo 29. - So  4.    -6   6-0
+    //
+    const Int_t mjd2 = GetMjdWeek1(Year()-1);
+    const Int_t mjd0 = GetMjdWeek1(Year());
+    const Int_t mjd3 = GetMjdWeek1(Year()+1);
+
+    // Today
+    const Int_t mjd = (Int_t)GetMjd();
+
+    // Week belongs to last year, return week of last year
+    if (mjd<mjd0)
+    {
+        year = Year()-1;
+        return (mjd-mjd2)/7 + 1;
+    }
+
+    // Check if Week belongs to next year (can only be week 1)
+    if ((mjd3-mjd)/7==1)
+    {
+        year = Year()+1;
+        return 1;
+    }
+
+    // Return calculated Week
+    year = Year();
+    return (mjd-mjd0)/7 + 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Is the given year a leap year.
+// The calendar year is 365 days long, unless the year is exactly divisible
+// by 4, in which case an extra day is added to February to make the year
+// 366 days long. If the year is the last year of a century, eg. 1700, 1800,
+// 1900, 2000, then it is only a leap year if it is exactly divisible by
+// 400. Therefore, 1900 wasn't a leap year but 2000 was. The reason for
+// these rules is to bring the average length of the calendar year into
+// line with the length of the Earth's orbit around the Sun, so that the
+// seasons always occur during the same months each year.
+//
+Bool_t MTime::IsLeapYear() const
+{
+    const UInt_t y = Year();
+    return (y%4==0) && !((y%100==0) && (y%400>0));
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+#error __LINUX__ not set
+#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 MString::Format("%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)
+//
+// For dates before 1. 1.1902  a null string is returned
+// For dates after 31.12.2037 a null string is returned
+//
+// To change the localization use loc, eg loc = "da_DK", "de_DE".
+// Leaving the argument empty will just take the default localization.
+//
+// If loc is "", each part of the locale that should be modified is set
+// according  to the environment variables. The details are implementation
+// dependent.  For glibc, first (regardless of category), the  environment
+// variable  LC_ALL  is  inspected, next the environment variable with the
+// same name as the category (LC_COLLATE, LC_CTYPE, LC_MESSAGES,  LC_MONE?
+// TARY,  LC_NUMERIC,  LC_TIME) and finally the environment variable LANG.
+// The first existing environment variable is used.
+//
+// A  locale  name  is  typically  of the form language[_territory][.code?
+// set][@modifier], where language is an ISO 639 language code,  territory
+// is an ISO 3166 country code, and codeset is a character set or encoding
+// identifier like ISO-8859-1 or UTF-8.   For  a  list  of  all  supported
+// locales, try "locale -a", cf. locale(1).
+//
+TString MTime::GetStringFmt(const char *fmt, const char *loc) 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);
+
+    // If date<1902 strftime crahses on my (tbretz) laptop
+    // it doesn't crash in the DC.
+    //    if (y<1902 || y>2037)
+    //        return "";
+
+    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 = -1;
+
+    // -1: If dst, isdst is set to 1 but hour is not changed
+    //  0: If dst, hour is changed
+
+    // Get old local
+    const TString locale = setlocale(LC_TIME, 0);
+
+    // Set new local (e.g. Montag instead of Monday)
+    setlocale(LC_TIME, loc);
+
+    // recalculate tm_yday and tm_wday
+    mktime(&time);
+
+    // We get errors for example for 1910-01-01
+    //    if (mktime(&time)<0)
+    //        return "";
+
+    char ret[128];
+    const size_t rc = strftime(ret, 127, fmt, &time);
+
+    setlocale(LC_TIME, locale);
+
+    return rc ? ret : "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the time according to the format fmt.
+// Default is "%A %e.%B %Y %H:%M:%S"
+//
+// For more information see GetStringFmt
+//
+Bool_t MTime::SetStringFmt(const char *time, const char *fmt, const char *loc)
+{
+    if (!fmt)
+        fmt = "%A %e.%B %Y %H:%M:%S";
+
+    struct tm t;
+    memset(&t, 0, sizeof(struct tm));
+
+    const TString locale = setlocale(LC_TIME, 0);
+
+    setlocale(LC_TIME, loc);
+    strptime(time, fmt, &t);
+    setlocale(LC_TIME, locale);
+
+    return Set(t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyy-mm-dd hh:mm:ss"
+//
+TString MTime::GetSqlDateTime() const
+{
+    return GetStringFmt("%Y-%m-%d %H:%M:%S");
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyymmddhhmmss"
+//
+TString MTime::GetSqlTimeStamp() const
+{
+    return GetStringFmt("%Y%m%d%H%M%S");
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyymmdd_hhmmss"
+//
+TString MTime::GetFileName() const
+{
+    return GetStringFmt("%Y%m%d_%H%M%S");
+}
+
+// --------------------------------------------------------------------------
+//
+// Print MTime as string
+//
+void MTime::Print(Option_t *) const
+{
+    UShort_t yea, ms;
+    Byte_t mon, day, h, m, s;
+
+    GetDate(yea, mon, day);
+    GetTime(h, m, s, ms);
+
+    *fLog << all << GetDescriptor() << ": ";
+    *fLog << GetString() << MString::Format(" (+%dns)", fNanoSec) << endl;
+} 
+
+// --------------------------------------------------------------------------
+//
+// Calls Set(t[0], t[1], t[2], t[3], t[4], t[5], 0)
+//
+Bool_t MTime::SetBinary(const UInt_t t[6])
+{
+    return Set(t[0], t[1], t[2], t[3], t[4], t[5], 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Assign:
+//    t[0] = year;
+//    t[1] = month;
+//    t[2] = day;
+//    t[3] = hour;
+//    t[4] = minute;
+//    t[5] = second;
+//
+void MTime::GetBinary(UInt_t t[6]) const
+{
+    UShort_t yea, ms;
+    Byte_t mon, day, h, m, s;
+
+    GetDate(yea, mon, day);
+    GetTime(h, m, s, ms);
+
+    t[0] = yea;
+    t[1] = mon;
+    t[2] = day;
+    t[3] = h;
+    t[4] = m;
+    t[5] = s;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read seven bytes representing y, m, d, h, m, s
+//
+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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write seven bytes representing y, m, d, h, m, s
+//
+ostream &MTime::WriteBinary(ostream &out) const
+{
+    UShort_t y, ms;
+    Byte_t mon, d, h, m, s;
+
+    GetDate(y, mon, d);
+    GetTime(h, m, s, ms);
+
+    out.write((char*)&y,   2);
+    out.write((char*)&mon, 1);
+    out.write((char*)&d,   1);
+    out.write((char*)&h,   1);
+    out.write((char*)&m,   1);
+    out.write((char*)&s,   1); // Total=7
+
+    return out;
+}
+
+void MTime::AddMilliSeconds(UInt_t ms)
+{
+    fTime += ms;
+
+    fTime += 11*kHour;
+    fMjd  += (Long_t)fTime/kDay;
+    fTime  = (Long_t)fTime%kDay;
+    fTime -= 11*kHour;
+}
+
+void MTime::Plus1ns()
+{
+    fNanoSec++;
+
+    if (fNanoSec<1000000)
+        return;
+
+    fNanoSec = 0;
+    fTime += 1;
+
+    if ((Long_t)fTime<(Long_t)kDay*13)
+        return;
+
+    fTime = 11*kDay;
+    fMjd++;
+}   
+
+void MTime::Minus1ns()
+{
+    if (fNanoSec>0)
+    {
+        fNanoSec--;
+        return;
+    }
+
+    fTime -= 1;
+    fNanoSec = 999999;
+
+    if ((Long_t)fTime>=-(Long_t)kDay*11)
+        return;
+
+    fTime = 13*kDay-1;
+    fMjd--;
+}   
+
+/*
+MTime MTime::operator-(const MTime &tm1)
+{
+    const MTime &tm0 = *this;
+
+    MTime t0 = tm0>tm1 ? tm0 : tm1;
+    const MTime &t1 = tm0>tm1 ? tm1 : tm0;
+
+    if (t0.fNanoSec<t1.fNanoSec)
+    {
+        t0.fNanoSec += 1000000;
+        t0.fTime -= 1;
+    }
+
+    t0.fNanoSec -= t1.fNanoSec;
+    t0.fTime    -= t1.fTime;
+
+    if ((Long_t)t0.fTime<-(Long_t)kHour*11)
+    {
+        t0.fTime += kDay;
+        t0.fMjd--;
+    }
+
+    t0.fMjd -= t1.fMjd;
+
+    return t0;
+}
+
+void MTime::operator-=(const MTime &t)
+{
+    *this = *this-t;
+}
+
+MTime MTime::operator+(const MTime &t1)
+{
+    MTime t0 = *this;
+
+    t0.fNanoSec += t1.fNanoSec;
+
+    if (t0.fNanoSec>999999)
+    {
+        t0.fNanoSec -= 1000000;
+        t0.fTime += kDay;
+    }
+
+    t0.fTime += t1.fTime;
+
+    if ((Long_t)t0.fTime>=(Long_t)kHour*13)
+    {
+        t0.fTime -= kDay;
+        t0.fMjd++;
+    }
+
+    t0.fMjd += t1.fMjd;
+
+    return t0;
+}
+
+void MTime::operator+=(const MTime &t)
+{
+    *this = *this+t;
+}
+*/
+
+void MTime::SetMean(const MTime &t0, const MTime &t1)
+{
+    // This could be an operator+
+    *this = t0;
+
+    fNanoSec += t1.fNanoSec;
+
+    if (fNanoSec>999999)
+    {
+        fNanoSec -= 1000000;
+        fTime += kDay;
+    }
+
+    fTime += t1.fTime;
+
+    if ((Long_t)fTime>=(Long_t)kHour*13)
+    {
+        fTime -= kDay;
+        fMjd++;
+    }
+
+    fMjd += t1.fMjd;
+
+    // This could be an operator/
+    if ((Long_t)fTime<0)
+    {
+        fTime += kDay;
+        fMjd--;
+    }
+
+    Int_t reminder = fMjd%2;
+    fMjd /= 2;
+
+    fTime += reminder*kDay;
+    reminder = (Long_t)fTime%2;
+    fTime /= 2;
+
+    fNanoSec += reminder*1000000;
+    fNanoSec /= 2;
+
+    fTime += 11*kHour;
+    fMjd  += (Long_t)fTime/kDay;
+    fTime  = (Long_t)fTime%kDay;
+    fTime -= 11*kHour;
+}
+
+void MTime::SetMean(Double_t t0, Double_t t1)
+{
+    const Double_t mean = (t0+t1)*(0.5/kDaySec);
+    SetMjd(mean);
+}
+
+void MTime::AsciiRead(istream &fin)
+{
+    fin >> *this;
+}
+
+Bool_t MTime::AsciiWrite(ostream &out) const
+{
+    out << *this;
+    return out;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the day of easter for the given year.
+// MTime() is returned if this was not possible.
+//
+// In case of the default argument or the year less than zero
+// the date of eastern of the current year (the year corresponding to
+// MTime(-1)) is returned.
+//
+//  for more information see: MAstro::GetDayOfEaster()
+//
+MTime MTime::GetEaster(Short_t year)
+{
+    if (year<0)
+        year = MTime(-1).Year();
+
+    const Int_t day = MAstro::GetEasterOffset(year);
+    if (day<0)
+        return MTime();
+
+    MTime t;
+    t.Set(year, 3, 1);
+    t.SetMjd(t.GetMjd() + day);
+
+    return t;
+}
Index: branches/Mars_McMismatchStudy/mbase/MTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mbase/MTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/MTime.h	(revision 17960)
@@ -0,0 +1,274 @@
+#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
+
+#include <TMath.h>
+
+struct timeval;
+
+class MTime : public MParContainer
+{
+public:
+    static const UInt_t kHour;    // [ms] one hour
+    static const UInt_t kDay;     // [ms] one day
+    static const UInt_t kDaySec;  // [s] one day
+
+    enum {
+        kSunday, kMonday, kTuesday, kWednesday, kThursday, kFriday, kSaturday
+    };
+
+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();
+
+        SetSqlDateTime(name);
+    }
+    MTime(const struct timeval &tm)
+    {
+        Init(NULL, NULL);
+        Set(tm);
+    }
+    MTime(Double_t mjd);
+    MTime(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);
+    MTime(const MTime& t) : MParContainer(), fMjd(t.fMjd), fTime(t.fTime), fNanoSec(t.fNanoSec)
+    {
+        Init(NULL, NULL);
+    }
+
+    //static Int_t Hour() { return 3600; }
+    //static Int_t Day()  { return 3600;*24 }
+
+    void operator=(const MTime &t)
+    {
+        fMjd     = t.fMjd;
+        fTime    = t.fTime;
+        fNanoSec = t.fNanoSec;
+    }
+
+    void Clear(const Option_t *) { Clear(); }
+    void Clear() { fMjd=0; fTime=0; fNanoSec=0; }
+
+    void Print(Option_t *t=NULL) const;
+
+    void Now();
+
+    // Setter functions
+    Bool_t   Set(UShort_t y, Byte_t m, Byte_t d, Byte_t h=13, Byte_t min=0, Byte_t s=0, UShort_t ms=0, UInt_t ns=0);
+    void     Set(const struct timeval &tv);
+    Bool_t   SetString(const char *str);
+    Bool_t   SetSqlDateTime(TString str);
+    Bool_t   SetSqlTimeStamp(const char *str);
+    void     SetCT1Time(UInt_t mjd, UInt_t t1, UInt_t t0);
+    void     SetCorsikaTime(Float_t time);
+    Bool_t   SetStringFmt(const char *time, const char *fmt, const char *loc=0);
+    Bool_t   SetBinary(const UInt_t t[6]);
+    Bool_t   UpdMagicTime(Byte_t h, Byte_t m, Byte_t s, UInt_t ns);
+    Bool_t   SetMjd(UInt_t mjd, ULong_t ms, UInt_t ns=0);
+    void     SetMjd(Double_t m);
+    void     SetJD(Double_t jd) { SetMjd(jd-2400000.5); }
+    void     SetAxisTime(Double_t time);
+    void     SetMoonPeriod(Double_t p);
+    void     SetMagicPeriodStart(Int_t p);
+    void     SetUnixTime(Long64_t sec, ULong64_t usec=0);
+    void     SetEaster(Short_t year=0);
+
+    // Getter functions
+    Double_t GetJD() const { return GetMjd()+2400000.5; }
+    Double_t GetMjd() const;
+    Double_t GetGmst() const;
+    TString  GetString() const;
+    TString  GetStringFmt(const char *fmt=0, const char *loc=0) const;
+    TString  GetSqlDateTime() const;
+    TString  GetSqlTimeStamp() const;
+    TString  GetFileName() const;
+    void     GetBinary(UInt_t t[6]) const;
+    void     GetDate(UShort_t &y, Byte_t &m, Byte_t &d) const;
+    MTime    GetDateOfSunrise() const;
+    void     GetDateOfSunrise(UShort_t &y, Byte_t &m, Byte_t &d) const;
+    TTime    GetRootTime() const;
+    TDatime  GetRootDatime() const;
+    Double_t GetAxisTime() const;
+    Double_t GetMoonPhase() const;
+    Double_t GetMoonPeriod() const;
+    Int_t    GetMagicPeriod() const;
+    UInt_t   GetNightAsInt() 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; }
+    Byte_t WeekDay() const; // { return TMath::FloorNint(GetMjd()+3)%7; } // Return Day of the week: Sun=0, Mon=1, ..., Sat=6
+    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; }
+    UInt_t MilliSec() const { return (GetTime()+kDay)%1000; }
+    UInt_t MicroSec() const { return fNanoSec/1000+MilliSec()*1000; }
+    UInt_t NanoSec() const  { return fNanoSec+MilliSec()*1000000; }
+    Int_t  Week() const     { Short_t y; return Week(y); }
+    Int_t  Week(Short_t &year) const;
+    UInt_t DayOfYear() const;
+
+    Bool_t IsMidnight() const { return (Long_t)fTime==0 && fNanoSec==0; }
+    Bool_t IsLeapYear() const;
+
+    // I/O functions
+    std::istream &ReadBinary(std::istream &fin);
+    std::ostream &WriteBinary(std::ostream &out) const;
+
+    void AsciiRead(std::istream &fin);
+    Bool_t AsciiWrite(std::ostream &out) const;
+
+    // Conversion functions
+    operator double() const;   //[s]
+    double operator()() const; //[s]
+
+    Double_t    AsDouble() const    { return GetMjd(); }
+    //const char *AsString() const    { return GetString(); }
+    //const char *AsSQLString() const { return GetSqldateTime(); }
+
+    // Calculation functions
+    void AddMilliSeconds(UInt_t ms);
+    void Minus1ns();
+    void Plus1ns();
+    void SetMean(const MTime &t0, const MTime &t1);
+    void SetMean(Double_t t0, Double_t t1);
+    /*
+     MTime operator-(const MTime &tm1);
+     void operator-=(const MTime &t);
+     MTime operator+(const MTime &t1);
+     void operator+=(const MTime &t);
+     */
+
+    // Base comparison operators
+    bool operator<(const MTime &t) const;
+    bool operator>(const MTime &t) const;
+
+    // Derived comparison operators
+    bool operator<=(const MTime &t) const;
+    bool operator>=(const MTime &t) const;
+    bool operator==(const MTime &t) const;
+    bool operator!=(const MTime &t) const;
+    bool operator!() const;
+
+    static MTime GetEaster(Short_t year=-1);
+    static Int_t GetMjdWeek1(Short_t year);
+
+    ClassDef(MTime, 3)	//A generalized MARS time stamp
+};
+
+inline std::ostream &operator<<(std::ostream &out, const MTime &t)
+{
+    out << t.GetString();
+    return out;
+}
+
+inline std::istream &operator>>(std::istream &in, MTime &t)
+{
+    TString date, time;
+    date.ReadToDelim(in, ' ');
+    time.ReadToDelim(in, ' ');
+    t.SetString(Form("%s %s", date.Data(), time.Data()));
+    return in;
+}
+
+inline MTime::operator double() const   //[s]
+{
+    return ((Double_t)fMjd*kDay+(Long_t)fTime+fNanoSec/1e6)/1000;
+}
+
+inline double MTime::operator()() const //[s]
+{
+    return operator double();
+}
+
+inline bool MTime::operator<(const MTime &t) const
+{
+    if (fMjd<t.fMjd)
+        return true;
+    if (fMjd==t.fMjd && fTime<t.fTime)
+        return true;
+    if (fMjd==t.fMjd && fTime==t.fTime && fNanoSec<t.fNanoSec)
+        return true;
+    return false;
+}
+
+inline bool MTime::operator>(const MTime &t) const
+{
+    if (fMjd>t.fMjd)
+        return true;
+    if (fMjd==t.fMjd && fTime>t.fTime)
+        return true;
+    if (fMjd==t.fMjd && fTime==t.fTime && fNanoSec>t.fNanoSec)
+        return true;
+    return false;
+}
+
+inline bool MTime::operator<=(const MTime &t) const
+{
+    return !operator>(t);
+}
+
+inline bool MTime::operator>=(const MTime &t) const
+{
+    return !operator<(t);
+}
+
+inline bool MTime::operator==(const MTime &t) const
+{
+    return fNanoSec==t.fNanoSec && fTime==t.fTime && fMjd==t.fMjd;
+}
+
+inline bool MTime::operator!=(const MTime &t) const
+{
+    return fNanoSec!=t.fNanoSec || fTime!=t.fTime || fMjd!=t.fMjd;
+}
+
+inline bool MTime::operator!() const
+{
+    return fNanoSec==0 && (ULong_t)fTime==0 && fMjd==0;
+}
+
+#endif
Index: branches/Mars_McMismatchStudy/mbase/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mbase/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mbase/Makefile	(revision 17960)
@@ -0,0 +1,78 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mfileio -I../mfbase -I../mastro -I../mcore
+# mfileio:  MRead  (MEvtLoop)
+# mfbase:   MF     (MContinue)
+# mastro:   MAstro (MTime)
+
+CINT = Base
+
+SRCFILES = MAGIC.cc \
+	   MLogo.cc \
+           MArgs.cc \
+           MString.cc \
+           MMath.cc \
+           MSpline3.cc \
+           MReflection.cc \
+	   MQuaternion.cc \
+           MEnv.cc \
+	   MLog.cc \
+           MLogManip.cc \
+           MLogPlugin.cc \
+           MLogHtml.cc \
+	   MParSpline.cc \
+	   MParList.cc \
+           MParContainer.cc \
+	   MParEmulated.cc \
+	   MParEnv.cc \
+           MParameters.cc \
+	   MInputStreamID.cc \
+           MTask.cc \
+           MTaskEnv.cc \
+           MTaskInteractive.cc \
+	   MTaskList.cc \
+           MFilter.cc \
+           MEvtLoop.cc \
+           MProgressBar.cc \
+           MSearch.cc \
+           MIter.cc \
+           MDirIter.cc \
+           MReadSocket.cc \
+           MGGroupFrame.cc \
+           MGMenu.cc \
+           MGMap.cc \
+           MGList.cc \
+           MGTask.cc \
+           MStatusArray.cc \
+           MStatusDisplay.cc \
+	   MLut.cc \
+	   MArray.cc \
+	   MArrayB.cc \
+	   MArrayS.cc \
+	   MArrayD.cc \
+	   MArrayF.cc \
+	   MArrayI.cc \
+           MTime.cc \
+           MClone.cc \
+           MContinue.cc \
+           MPrint.cc \
+	   MThread.cc \
+           MObjLookup.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mcalib/CalibIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/CalibIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/CalibIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mcalib/CalibLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/CalibLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/CalibLinkDef.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MCalibColorSet+;
+#pragma link C++ class MCalibColorSteer+;
+#pragma link C++ class MCalibCalcFromPast+;
+#pragma link C++ class MCalibrationPattern+;
+#pragma link C++ class MCalibrationPatternDecode+;
+
+#pragma link C++ class MCalibrateData+;
+#pragma link C++ class MCalibrateFact+;
+#pragma link C++ class MCalibrateRelTimes+;
+
+#pragma link C++ class MCalibConstCam+;
+#pragma link C++ class MCalibConstPix+;
+
+#pragma link C++ class MCalibrationCam+;
+#pragma link C++ class MCalibrationPix+;
+#pragma link C++ class MCalibrationRelTimeCalc+;
+#pragma link C++ class MCalibrationRelTimeCam+;
+#pragma link C++ class MCalibrationRelTimePix+;
+#pragma link C++ class MCalibrationPulseTimeCam+;
+#pragma link C++ class MCalibrationQECamMagic+;
+#pragma link C++ class MCalibrationQECam+;
+#pragma link C++ class MCalibrationQEPix+;
+#pragma link C++ class MCalibrationTestCalc+;
+#pragma link C++ class MCalibrationTestCam+;
+#pragma link C++ class MCalibrationTestPix+;
+#pragma link C++ class MCalibrationChargeCalc+;
+#pragma link C++ class MCalibrationChargeCam+;
+#pragma link C++ class MCalibrationChargePix+;
+#pragma link C++ class MCalibrationBlindCam+;
+#pragma link C++ class MCalibrationBlindPix+;
+#pragma link C++ class MCalibrationBlindCamOneOldStyle+;
+#pragma link C++ class MCalibrationBlindCamTwoNewStyle+;
+#pragma link C++ class MCalibrationBlindCamThreeNewStyle+;
+#pragma link C++ class MCalibrationChargePINDiode+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibCalcFromPast.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibCalcFromPast.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibCalcFromPast.cc	(revision 17960)
@@ -0,0 +1,479 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 12/2004 <mailto:markus@ifae.es>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibCalcFromPast
+//
+//  Steers the occurrance of interlaced calibration events in one data run
+// 
+//  Input Containers:
+//   MParList
+//
+//  Output Containers:
+//
+// Class version 2:
+//  +  UInt_t  fNumPhesDump;         // Number of cams after which the number of phes gets averaged
+//  +  Float_t fMeanPhes;
+//  +  Float_t fMeanPhesRelVar;
+//  +  Bool_t  fUpdateNumPhes;       // Update the number of photo-electrons only after fNumPhesDump number of Cams
+//  +  TArrayF fPhes;
+//  +  TArrayF fPhesVar;
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibCalcFromPast.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+
+#include "MHCalibrationCam.h"
+
+#include "MBadPixelsCam.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargeCalc.h"
+#include "MCalibrationRelTimeCalc.h"
+#include "MCalibrateData.h"
+
+ClassImp(MCalibCalcFromPast);
+
+using namespace std;
+
+const UInt_t MCalibCalcFromPast::fgNumEventsDump = 500;
+const UInt_t MCalibCalcFromPast::fgNumPhesDump   = 10;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. 
+//
+// Sets:
+// - fNumEventsDump to fgNumEventsDump
+// - fNumPhesDump to fgNumPhesDump
+//
+MCalibCalcFromPast::MCalibCalcFromPast(const char *name, const char *title)
+    : fGeom(NULL), fParList(NULL), fRunHeader(NULL),
+    fCharge(NULL), fBlindCam(NULL), fQECam(NULL), fBadPixels(NULL),
+    fChargeCalc(NULL), fRelTimeCalc(NULL), fCalibrate(NULL),
+    fNumCam(0), fNumEvents(0), fUpdateWithFFactorMethod(kTRUE), fUpdateNumPhes(kTRUE),
+    fNumFails(0)
+{
+
+  fName  = name  ? name  : "MCalibCalcFromPast";
+  fTitle = title ? title : "Task to steer the processing of interlaced calibration events";
+
+  SetNumEventsDump();
+  SetNumPhesDump  ();
+}
+
+// -----------------------------------------------------------------------------------
+//
+Int_t MCalibCalcFromPast::PreProcess(MParList *pList)
+{
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "MGeomCam not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fParList = pList;
+  if (!fParList)
+    {
+      *fLog << err << "MParList not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!fRunHeader)
+  {
+      *fLog << err << "MRawRunHeader not found... abort." << endl;
+      return kFALSE;
+  }
+
+  // 
+  // Look for the MBadPixels Cam
+  //
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+  {
+      *fLog << err << "MBadPixelsCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  //
+  // Look for the MCalibrationQECam
+  //
+  fQECam = (MCalibrationQECam*)pList->FindObject("MCalibrationQECam");
+  if (!fQECam)
+  {
+      *fLog << err << "MCalibrationQECam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  // 
+  // Look for the MFillH-class "MHCalibrationBlindCam".
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationBlindCam")))
+  {
+      *fLog << inf << "Found MHCalibrationBlindCam ... " << flush;
+
+      fBlindCam = (MCalibrationBlindCam*)pList->FindCreateObj("MCalibrationBlindCam");
+      if (!fBlindCam)
+          return kFALSE;
+  }
+
+  //
+  // Look for the MFillH-class "MHCalibrationChargeCam". 
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationChargeCam")))
+  {
+
+    fCharge = (MCalibrationChargeCam*)pList->FindCreateObj("MCalibrationChargeCam");
+    if (!fCharge)
+        return kFALSE;
+
+    if (!fChargeCalc)
+      fChargeCalc   = (MCalibrationChargeCalc*)pList->FindObject("MCalibrationChargeCalc");
+    if (!fChargeCalc)
+      {
+        *fLog << err << "Could not find MCalibrationChargeCalc abort... " << endl;
+        return kFALSE;
+      }
+
+    if (!fCalibrate)
+      fCalibrate   = (MCalibrateData*)pList->FindObject("MCalibrateData");
+    if (!fCalibrate)
+      {
+        *fLog << err << "Could not find MCalibrateData abort... " << endl;
+        return kFALSE;
+      }
+    
+    *fLog << inf << "Found MHCalibrationChargeCam ... " << flush;
+
+  }
+
+  // 
+  // Look for the MFillH name "FillRelTimeCam".
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationRelTimeCam")))
+  {
+    if (!fRelTimeCalc)
+      fRelTimeCalc   = (MCalibrationRelTimeCalc*)pList->FindObject(AddSerialNumber("MCalibrationRelTimeCalc"));
+    if (!fRelTimeCalc)
+      {
+        *fLog << err << "Could not find MCalibrationRelTimeCalc abort... " << endl;
+        return kFALSE;
+      }
+
+    *fLog << inf << "Found MHCalibrationRelTimeCam ... " << flush;
+  }
+
+  fNumCam    = 0;
+  fNumEvents = 0;
+  fNumPhes   = 0;
+
+  fChargeCalc->SetUseExternalNumPhes(kFALSE);
+
+  if (fUpdateNumPhes)
+    {
+      fPhes.Set(fNumPhesDump);
+      fPhesVar.Set(fNumPhesDump);
+    }
+
+  fNumFails = 0;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set fNumEvents=0
+//
+// This is necessary because the calibration histograms do reset themself
+// if ReInit is called, so they are empty. MCalibCalcFromPast errornously
+// ignores how many events are in the histograms but count the number
+// itself.
+//
+Bool_t MCalibCalcFromPast::ReInit(MParList *pList)
+{
+    if (fNumEvents>0)
+        *fLog << inf << fNumEvents << " calibration events at the end of the last file have been skipped." << endl;
+
+    fNumEvents = 0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Initializes new containers in the 
+// - if the number of calibration events has reach fNumEventsDump.
+// - Executes Finalize() of the MCalibration*Calc classes in that case.
+// - Sets the latest MCalibrationChargeCam as update class into MCalibrateData
+// - clean MCalibration*Cams
+//
+Int_t MCalibCalcFromPast::Process()
+{
+  if (fNumEvents++ < fNumEventsDump)
+    return kTRUE;
+
+  // Replace the old cams by (empty) new ones
+  // MCalibrationChargeCam: fCharge
+  // MCalibrationQECam:     fIntensQE
+  // MCalibrationBlindCam:  fIntensBlind
+  fNumEvents = 0;
+  ReInitialize();
+
+  *fLog << all << "MCalibCalcFromPast: Calibration Update..." << flush;
+
+  //
+  // Finalize Possible calibration histogram classes...
+  //
+  *fLog << inf << "Finalize calibration histograms:" << endl;
+
+  // This fills the Cams which are cleared by
+  // ReInitialize with the result of the last calib cycle
+  Finalize("MHCalibrationChargeCam");
+  Finalize("MHCalibrationChargeBlindCam");
+  Finalize("MHCalibrationRelTimeCam");
+
+  //
+  // Finalize possible calibration calculation tasks
+  //
+  *fLog << endl;
+  *fLog << inf << "Finalize calibration calculations..." << endl;
+  if (fChargeCalc)
+    {
+        // Finalized Pedestals, Charges, Bad Pixels and all QE cams
+        if (!fChargeCalc->Finalize())
+        {
+            fNumFails++;
+            *fLog << warn << "WARNING - Finalization of charges failed the " << fNumFails << ". time..." << endl;
+            return kTRUE;
+        }
+
+        if (fUpdateNumPhes)
+        {
+          MCalibrationChargePix &avpix =(MCalibrationChargePix&)fCharge->GetAverageArea(0);
+          fPhes   [fNumPhes] = avpix.GetPheFFactorMethod();
+          fPhesVar[fNumPhes] = avpix.GetPheFFactorMethodVar();
+
+          fNumPhes++;
+
+          if (fNumPhes == fNumPhesDump)
+            {
+              fNumPhes = 0;
+              if (!UpdateMeanPhes())
+                {
+                  *fLog << warn << "Could not update mean number of photo-electrons. "
+                        << "Skip it until next update" << endl;
+                  fChargeCalc->SetUseExternalNumPhes(kFALSE);
+                }
+              else
+                {
+                  *fLog << inf << "New averaged number photo-electrons: " << fMeanPhes << endl;
+                  fChargeCalc->SetExternalNumPhes      ( fMeanPhes );
+                  fChargeCalc->SetExternalNumPhesRelVar( fMeanPhesRelVar );
+                  fChargeCalc->SetUseExternalNumPhes();
+                }
+            }
+        }
+    }
+
+  if (fRelTimeCalc)
+    fRelTimeCalc->Finalize();
+
+  if (fCalibrate)
+    return fCalibrate->UpdateConversionFactors(fUpdateWithFFactorMethod ? NULL : fCharge);
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Searches for name in the MParList and calls, if existing: 
+// - MHCalibrationCam::Finalize()
+// - MHCalibrationCam::ResetHists()
+//
+void MCalibCalcFromPast::Finalize(const char* name, Bool_t finalize)
+{
+    MHCalibrationCam *hist = (MHCalibrationCam*)fParList->FindObject(name, "MHCalibrationCam");
+    if (!hist)
+        return;
+
+    *fLog << inf << "Finalize " << name << ":" << endl;
+
+    if (finalize)
+        hist->Finalize();
+
+    hist->ResetHists();
+}
+
+// --------------------------------------------------------------------------
+//
+// Clear contents of cams
+//
+Bool_t MCalibCalcFromPast::ReInitialize()
+{
+  fNumCam++;
+
+  *fLog << inf << "MCalibCalcFromPast::ReInitialize #" << fNumCam << ": ";
+
+  const Int_t runnumber = fRunHeader->GetRunNumber();
+
+  // The "DeleteOldCam" function must not delete the first entry in
+  // the array because it is a special cam from the MParList. (see above)
+  *fLog << "MBadPixelsCam...";
+  fBadPixels->Clear();  // FIXME:::::: MERGE PreExcl!!!!
+  // IS IT REALLY NECESSARY?
+
+  *fLog << "MCalibrationQECam...";
+  fQECam->Clear();
+  fQECam->SetRunNumber(runnumber);
+  // IS IT REALLY NECESSARY?
+
+  if (fBlindCam)
+  {
+      *fLog << "MCalibrationBlindCam...";
+      fBlindCam->Clear();
+      fBlindCam->SetRunNumber(runnumber);
+  }
+  // IS IT REALLY NECESSARY?
+
+  // IF SIMPLE ENOUGH, REMOVE THE FUNCTION!
+
+  if (fCharge)
+  {
+      *fLog << "MCalibrationChargeCam...";
+      fCharge->Clear();
+      fCharge->SetRunNumber(runnumber);
+  }
+
+  *fLog << endl;
+
+  return kTRUE;
+
+}
+
+Int_t MCalibCalcFromPast::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    // Now we reset all histograms to make sure that the PostProcess
+    // of the following tasks doesn't try to finalize a partly empty
+    // histogram!
+    Finalize("MHCalibrationChargeCam",      kFALSE);
+    Finalize("MHCalibrationChargeBlindCam", kFALSE);
+    Finalize("MHCalibrationRelTimeCam",     kFALSE);
+
+    if (fChargeCalc)
+        fChargeCalc->ResetNumProcessed();
+
+    if (fNumCam==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << " " << setfill(' ') << setw(7) << fNumFails << " (" << Form("%5.1f", 100.*fNumFails/fNumCam) << "%) updates failed." << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+
+Bool_t MCalibCalcFromPast::UpdateMeanPhes()
+{
+    Double_t sumw = 0.;
+    Double_t sum  = 0.;
+
+    for (Int_t i=0; i<fPhes.GetSize(); i++)
+    {
+        const Float_t weight = 1./fPhesVar[i];
+        sum  += fPhes[i]*weight;
+        sumw += weight;
+    }
+
+    if (sumw < 0.000001)
+        return kFALSE;
+
+    if (sum < 0.000001)
+        return kFALSE;
+
+    fMeanPhes       = sum/sumw;
+    fMeanPhesRelVar = sumw/sum/sum;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MCalibCalcFromPast.UpdateWithFFactorMethod: Off, On
+//   MCalibCalcFromPast.NumEventsDump: 500
+//   MCalibCalcFromPast.UpdateNumPhes: yes/no
+//   MCalibCalcFromPast.NumPhesDump: 10
+//
+Int_t MCalibCalcFromPast::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "UpdateWithFFactorMethod", print))
+    {
+        rc = kTRUE;
+        SetUpdateWithFFactorMethod(GetEnvValue(env, prefix, "UpdateWithFFactorMethod", fUpdateWithFFactorMethod));
+    }
+
+    if (IsEnvDefined(env, prefix, "NumEventsDump", print))
+    {
+        SetNumEventsDump(GetEnvValue(env, prefix, "NumEventsDump", (Int_t)fNumEventsDump));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "UpdateNumPhes", print))
+    {
+        TString s = GetEnvValue(env, prefix, "UpdateNumPhes", "");
+        s.ToLower();
+        if (s.BeginsWith("no"))
+            SetUpdateNumPhes(kFALSE);
+        if (s.BeginsWith("yes"))
+            SetUpdateNumPhes(kTRUE);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "NumPhesDump", print))
+    {
+        SetNumPhesDump(GetEnvValue(env, prefix, "NumPhesDump", (Int_t)fNumPhesDump));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibCalcFromPast.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibCalcFromPast.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibCalcFromPast.h	(revision 17960)
@@ -0,0 +1,97 @@
+#ifndef MARS_MCalibCalcFromPast
+#define MARS_MCalibCalcFromPast
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MParList;
+class MGeomCam;
+class MRawRunHeader;
+class MPedCalcFromLoGain;
+class MCalibrationChargeCalc;
+class MCalibrationRelTimeCalc;
+class MCalibrateData;
+class MCalibrationChargeCam;
+class MCalibrationBlindCam;
+class MCalibrationQECam;
+
+class MBadPixelsCam;
+
+class MCalibCalcFromPast : public MTask
+{
+private:
+  static const UInt_t fgNumEventsDump;               //! Default for fNumEventsDump
+  static const UInt_t fgNumPhesDump;                 //! Default for fNumPhesDump
+  
+  MGeomCam                        *fGeom;            //! Camera Geometry
+  MParList                        *fParList;         //! Parameter List
+  MRawRunHeader                   *fRunHeader;       //! Run header storing the run number
+  MCalibrationChargeCam           *fCharge;          //! Intensity Charge Cam (to be created)
+
+  MCalibrationBlindCam            *fBlindCam;        //! Blind  Cam
+  MCalibrationQECam               *fQECam;           //! QE Cam
+  MBadPixelsCam                   *fBadPixels;       //! Bad Pixels Cam
+
+  MCalibrationChargeCalc          *fChargeCalc;      //! Charge Calibration Task
+  MCalibrationRelTimeCalc         *fRelTimeCalc;     //! Rel. Times Calibratio Task
+  MCalibrateData                  *fCalibrate;       //! Data Calibration Task
+                                                     
+  UInt_t fNumCam;              //! Number of currently used Calibration Cam
+  UInt_t fNumEventsDump;       // Number of event after which the MCalibrationCams gets updated
+  UInt_t fNumEvents;           //! Event counter only for calibration events
+  UInt_t fNumPhesDump;         // Number of cams after which the number of phes gets averaged
+  UInt_t fNumPhes;             //! Event counter for photo-electron updates
+
+  Float_t fMeanPhes;
+  Float_t fMeanPhesRelVar;
+
+  Bool_t fUpdateWithFFactorMethod; // Update the interlaced calib events with the full F-Factor method
+  Bool_t fUpdateNumPhes;           // Update the number of photo-electrons only after fNumPhesDump number of Cams
+
+  TArrayF fPhes;
+  TArrayF fPhesVar;
+
+  Int_t fNumFails;          //! How often got the update skipped?
+
+  // MTask
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();
+  Bool_t ReInit(MParList *pList);
+
+  // MCalibCalcFromPast
+  Bool_t ReInitialize();
+  void Finalize(const char* name, Bool_t finalize=kTRUE);
+
+  Bool_t UpdateMeanPhes();
+
+  // MParContainer
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+  MCalibCalcFromPast(const char *name=NULL, const char *title=NULL);
+
+  // Getter
+  UInt_t GetNumEventsDump() const   {  return fNumEventsDump;   }
+
+  // Setter
+  void SetNumEventsDump( const UInt_t i=fgNumEventsDump )   { fNumEventsDump = i; }
+  void SetNumPhesDump  ( const UInt_t i=fgNumPhesDump   )   { fNumPhesDump   = i; }
+  
+  void SetCalibrate    ( MCalibrateData          *c )  { fCalibrate   = c; }
+  void SetChargeCalc   ( MCalibrationChargeCalc  *c )  { fChargeCalc  = c; }
+  void SetRelTimeCalc  ( MCalibrationRelTimeCalc *c )  { fRelTimeCalc = c; }
+  void SetUpdateNumPhes      ( const Bool_t b=kTRUE )  { fUpdateNumPhes           = b;  }
+
+  void SetUpdateWithFFactorMethod(const Bool_t b=kTRUE){ fUpdateWithFFactorMethod = b; }
+  
+  ClassDef(MCalibCalcFromPast, 2) // Task to steer the processing of interlace calibration events
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibColorSet.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibColorSet.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibColorSet.cc	(revision 17960)
@@ -0,0 +1,590 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibColorSet
+//
+//  Sets the color for events depending on the color which was used for
+//  the run. This is a workaround for runs which were taken before the
+//  digital module could deliver the color 'per event'
+// 
+//  Input Containers:
+//   MRawRunHeader
+//
+//  Output Containers:
+//   MCalibrationPattern
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibColorSet.h"
+
+#include <stdlib.h>   // needed for atoi on some platforms
+
+#include <TRegexp.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationCam.h"
+#include "MCalibrationPattern.h"
+#include "MRawRunHeader.h"
+
+ClassImp(MCalibColorSet);
+
+using namespace std;
+
+const Int_t  MCalibColorSet::gkIFAEBoxInaugurationRun = 20113;
+const UInt_t MCalibColorSet::gkFirstRunWithFinalBits  = 45626;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. MGeomCamMagic is the default geometry.
+//
+MCalibColorSet::MCalibColorSet(const char *name, const char *title)
+    : fPattern(0), fHeader(0), fIsExplicitColor(kFALSE)
+{
+  fName  = name  ? name  : "MCalibColorSet";
+  fTitle = title ? title : "Task to set workaround missing colors calibration events";
+
+  Clear();
+}
+
+void MCalibColorSet::Clear(const Option_t *o)
+{
+  
+  fIsValid         = kFALSE;
+
+  if (fIsExplicitColor)
+    return;
+
+  fColor           = MCalibrationCam::kNONE;
+  fStrength        = -1.;
+}
+
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MCalibrationPattern
+//
+Int_t MCalibColorSet::PreProcess(MParList *pList)
+{
+
+  fPattern = (MCalibrationPattern*)pList->FindObject("MCalibrationPattern");
+  if (!fPattern)
+    {
+      *fLog << err << "MCalibrationPattern not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+  if (!fHeader)
+    {
+      *fLog << err << "MRawEvtHeader not found... abort." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if str contains regexp.
+// If so or pat to pattern and set color to col.
+// Otherwise do nothing.
+//
+// Normally this function is much to simple (more arguments than lines!)
+// but in this particular case it is worth to have it to avois chaotic
+// repitions of the same piece of code for many many times.
+//
+void MCalibColorSet::CheckAndSet(const TString &str, const char *regexp, MCalibrationCam::PulserColor_t col, Float_t strength)
+{
+    if (!str.Contains(TRegexp(regexp)))
+        return;
+
+    fStrength = strength;
+    fColor    = col;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+// - MRawRunHeader
+//
+// If Runnumber < gkIFAEBoxInaugurationRun, set colour pattern: 0
+//
+// If Runnumber > gkIFAEBoxInaugurationRun, search for colour in 
+// the project name: Set colour pattern according to the following 
+// convention: 
+//    Green: assume slot 1  ( 5 Leds Green)
+//    Blue:  assume slot 14 ( 5 Leds Blue )
+//    UV:    assume slot 12 ( 5 Leds UV   )
+//    CT1:   take  'slot 17'
+//
+Bool_t MCalibColorSet::ReInit(MParList *pList)
+{
+
+  Clear();
+
+  MRawRunHeader *header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!header)
+    {
+      *fLog << err << "MRawRunHeader not found... abort." << endl;
+      return kFALSE;
+    }
+  
+  //
+  // Consider the case that a pedestal run is interleaved in the calibration run sequence ... prepare
+  // to skip this run.
+  //
+  if (header->GetRunType() == MRawRunHeader::kRTPedestal)
+    {
+      *fLog << warn << "New run is a pedestal run... need intensity calibration to treat this case!" << endl;
+      fColor = MCalibrationCam::kNONE;
+      fPattern->SetPulserColor(fColor);
+      fIsValid = kTRUE;      
+      return kTRUE;
+    }
+ 
+  //
+  // Check if the color was set explicitly from outside
+  //
+  if (fIsExplicitColor)
+    {
+      fPattern->SetPulserColor(fColor);
+      fIsValid = kTRUE;
+      return kTRUE;
+    }
+
+  //
+  // 1) Do nothing if this is a MC run. Correct settings of all flags is assumed
+  // 2) Skip the rest if the run already contains the correct color information
+  //
+  if (header->IsMonteCarloRun() || header->GetRunNumber()>gkFirstRunWithFinalBits)
+      return kTRUE;
+
+  const Int_t num = header->GetRunNumber();
+
+  if (num<gkIFAEBoxInaugurationRun)
+    {
+      *fLog << inf << "Run taken before inauguration of IFAE-box... using CT1 pulser." << endl;
+      fColor    = MCalibrationCam::kCT1;
+      fStrength = 10.;
+      fPattern->SetPulserColor(fColor);
+      fPattern->SetPulserStrength(fStrength);
+      fIsValid  = kTRUE;
+      return kTRUE;
+    }
+  
+  fColor    = MCalibrationCam::kNONE;
+  fStrength = 0.;
+
+  switch (num)
+    {
+    case 22246:
+    case 22253:
+    case 25792:
+    case 26402:
+    case 34814:
+    case 35415:
+    case 39942:
+    case 39944:
+    case 44768:
+    case 44976:
+    case 45082:
+    case 45083:
+    case 45089:
+    case 45090:
+    case 45091:
+    case 45094:
+    case 45119:
+    case 45249:
+    case 45253:
+    case 45262:
+    case 45274:
+    case 45275:
+    case 45276:
+    case 45365:
+    case 45366:
+    case 45367:
+    case 45368:
+    case 45369:
+    case 45370:
+    case 45371:
+    case 45382:
+    case 45401:
+    case 45419:
+    case 45432:
+    case 45471:
+    case 45485:
+    case 45489:
+    case 45490:
+    case 45494:
+    case 45503:
+    case 45526:
+    case 45538:
+    case 45549:
+    case 45557:
+    case 45562:
+    case 45571:
+    case 45579:
+    case 45607:
+      //    case 31756:
+      fColor = MCalibrationCam::kBLUE;
+      fStrength = 1.;
+      break;
+      
+    case 30090:
+    case 31745:
+    case 31746:
+    case 31747:
+    case 31748:
+    case 34815:
+    case 20660:
+    case 20661:
+    case 26408:
+    case 26409:
+    case 26412:
+    case 26568:
+    case 26924:
+    case 44834:
+    case 45051:
+    case 45084:
+    case 45085:
+    case 45092:
+    case 45227:
+    case 45241:
+    case 45250:
+    case 45254:
+    case 45263:
+    case 45372:
+    case 45373:
+    case 45608:
+      fColor = MCalibrationCam::kGREEN;
+      fStrength = 5.;
+      break;
+      
+    case 39941:
+    case 39943:
+    case 44833:
+    case 45086:
+    case 45088:
+    case 45111:
+    case 45115:
+    case 45216:
+    case 45218:
+    case 45226:
+    case 45240:
+    case 45251:
+    case 45278:
+    case 45336:
+    case 45341:
+    case 45358:
+    case 45374:
+    case 45375:
+    case 45376:
+    case 45377:
+    case 45381:
+    case 45400:
+    case 45418:
+    case 45431:
+    case 45470:
+    case 45484:
+    case 45493:
+    case 45502:
+    case 45525:
+    case 45537:
+    case 45548:
+    case 45556:
+    case 45561:
+    case 45570:
+    case 45578:
+    case 45614:
+    case 45618:
+      fColor = MCalibrationCam::kUV;
+      fStrength = 10.;
+      break;
+      
+    case 43914:
+    case 43916:
+    case 43918:
+    case 43920:
+    case 43922:
+      fColor = MCalibrationCam::kCT1;
+      fStrength = 20.;
+      break;
+
+    case 27474:
+      *fLog << err << "Sorry, run 27474 was taken with CLOSED LIDS. It should not be used! " << endl;
+      return kFALSE;
+
+    case 40493:
+    case 45116:
+    case 45609:
+    case 45219:
+      *fLog << err << dec << "Sorry, run " << num 
+            << " was taken with a combination of colours used to flat-field ";
+      *fLog << err << "the camera. It cannot be used for the standard calibration " << endl;
+      return kFALSE;
+      
+    case 45605:
+      *fLog << err << "Sorry, run 45605 was taken with the continuous light source." << endl;
+      *fLog << err << "It cannot be used for calibration. Try to run a pedestal extraction on it." << endl;
+      return kFALSE;
+
+    case 45606:
+      *fLog << err << "Sorry, run 45606 was taken with mal-functionning pulser." << endl;
+      *fLog << err << "It cannot be used for calibration. Try to run a pedestal extraction on it." << endl;
+      return kFALSE;
+
+    }
+  
+  if (fColor != MCalibrationCam::kNONE)
+  {
+      *fLog << inf << "Color determined from the run-number... ";
+      switch (fColor)
+      {
+      case MCalibrationCam::kGREEN: *fLog << "Green."; break;
+      case MCalibrationCam::kBLUE:  *fLog << "Blue.";  break;
+      case MCalibrationCam::kUV:    *fLog << "UV.";    break;
+      case MCalibrationCam::kCT1:   *fLog << "CT1.";   break;
+      default: break;
+      }
+      *fLog << endl;
+      fPattern->SetPulserColor(fColor);
+      fIsValid  = kTRUE;
+      return kTRUE;
+  }
+
+  TString proj = header->GetProjectName();
+  proj.ToLower();
+
+  // Possible green combinations
+  CheckAndSet(proj, "0.1led[s]?gree", MCalibrationCam::kGREEN, 0.1);
+  CheckAndSet(proj, "1led[s]?gree",   MCalibrationCam::kGREEN, 1. );
+  CheckAndSet(proj, "2led[s]?gree",   MCalibrationCam::kGREEN, 2. );
+  CheckAndSet(proj, "3led[s]?gree",   MCalibrationCam::kGREEN, 3. );
+  CheckAndSet(proj, "5led[s]?gree",   MCalibrationCam::kGREEN, 5. );
+  CheckAndSet(proj, "6led[s]?gree",   MCalibrationCam::kGREEN, 6. );
+  CheckAndSet(proj, "7led[s]?gree",   MCalibrationCam::kGREEN, 7. );
+  CheckAndSet(proj, "8led[s]?gree",   MCalibrationCam::kGREEN, 8. );
+
+  // Possible blue combinations
+  CheckAndSet(proj, "0.1led[s]?blue", MCalibrationCam::kBLUE, 0.1);
+  CheckAndSet(proj, "1led[s]?blue",   MCalibrationCam::kBLUE,  1.);
+  CheckAndSet(proj, "2led[s]?blue",   MCalibrationCam::kBLUE,  2.);
+  CheckAndSet(proj, "3led[s]?blue",   MCalibrationCam::kBLUE,  3.);
+  CheckAndSet(proj, "5led[s]?blue",   MCalibrationCam::kBLUE,  5.);
+  CheckAndSet(proj, "6led[s]?blue",   MCalibrationCam::kBLUE,  6.);
+  CheckAndSet(proj, "7led[s]?blue",   MCalibrationCam::kBLUE,  7.);
+  CheckAndSet(proj, "8led[s]?blue",   MCalibrationCam::kBLUE,  8.);
+  CheckAndSet(proj, "10led[s]?blue",  MCalibrationCam::kBLUE, 10.);
+  CheckAndSet(proj, "15led[s]?blue",  MCalibrationCam::kBLUE, 15.);
+  CheckAndSet(proj, "20led[s]?blue",  MCalibrationCam::kBLUE, 20.);
+  CheckAndSet(proj, "21led[s]?blue",  MCalibrationCam::kBLUE, 21.);
+  CheckAndSet(proj, "22led[s]?blue",  MCalibrationCam::kBLUE, 22.);
+  CheckAndSet(proj, "23led[s]?blue",  MCalibrationCam::kBLUE, 23.);
+
+  // Possible UV combinations
+  CheckAndSet(proj, "1led[s]?uv",     MCalibrationCam::kUV,  1.);
+  CheckAndSet(proj, "2led[s]?uv",     MCalibrationCam::kUV,  2.);
+  CheckAndSet(proj, "3led[s]?uv",     MCalibrationCam::kUV,  3.);
+  CheckAndSet(proj, "5led[s]?uv",     MCalibrationCam::kUV,  5.);
+  CheckAndSet(proj, "6led[s]?uv",     MCalibrationCam::kUV,  6.);
+  CheckAndSet(proj, "7led[s]?uv",     MCalibrationCam::kUV,  7.);
+  CheckAndSet(proj, "8led[s]?uv",     MCalibrationCam::kUV,  8.);
+  CheckAndSet(proj, "10led[s]?uv",    MCalibrationCam::kUV, 10.);
+  CheckAndSet(proj, "11led[s]?uv",    MCalibrationCam::kUV, 11.);
+  CheckAndSet(proj, "12led[s]?uv",    MCalibrationCam::kUV, 12.);
+  CheckAndSet(proj, "13led[s]?uv",    MCalibrationCam::kUV, 13.);
+
+  // Possible slot combinations
+  TRegexp slot("slot");
+  if (proj.Contains(slot))
+  {
+      proj.ReplaceAll("slot","");
+      UInt_t nr = 0;
+      TRegexp slotnr("^[0-9]");
+
+      if (proj.Contains(slotnr))
+      {
+          proj.Replace(2,99,"");
+          proj.ReplaceAll("u","");
+          proj.ReplaceAll("v","");
+          proj.ReplaceAll("g","");
+          nr = atoi(proj.Data())-1;
+
+          fColor = nr < 2 ? MCalibrationCam::kGREEN :
+              ( nr < 3 )  ? MCalibrationCam::kBLUE :
+              ( nr < 5 )  ? MCalibrationCam::kUV :
+              ( nr < 11 ) ? MCalibrationCam::kBLUE :
+              ( nr < 13 ) ? MCalibrationCam::kUV :
+              ( nr < 14 ) ? MCalibrationCam::kBLUE :
+              ( nr < 16 ) ? MCalibrationCam::kGREEN :
+              MCalibrationCam::kCT1;
+
+	  switch (nr)
+	    {
+	    case 0: 
+	      fStrength = 5;
+	      break;
+	    case 1: 
+	      fStrength = 2.;
+	      break;
+	    case 2: 
+	      fStrength = 5.1;
+	      break;
+	    case 3: 
+	      fStrength = 1.;
+	      break;
+	    case 4: 
+	      fStrength = 2.;
+	      break;
+	    case 5: 
+	      fStrength = 5.2;
+	      break;
+	    case 6: 
+	      fStrength = 5.4;
+	      break;
+	    case 7: 
+	      fStrength = 2.;
+	      break;
+	    case 8: 
+	      fStrength = 0.2;
+	      break;
+	    case 9: 
+	      fStrength = 0.;
+	      break;
+	    case 10: 
+	      fStrength = 1.;
+	      break;
+	    case 11: 
+	      fStrength = 5.8;
+	      break;
+	    case 12: 
+	      fStrength = 5.1;
+	      break;
+	    case 13: 
+	      fStrength = 5.2;
+	      break;
+	    case 14: 
+	      fStrength = 1;
+	      break;
+	    case 15: 
+	      fStrength = 0.2;
+	      break;
+	    }
+      }
+  }
+
+  if (fColor == MCalibrationCam::kNONE)
+  {
+      CheckAndSet(proj, "gree", MCalibrationCam::kGREEN, 1.);
+      CheckAndSet(proj, "blue", MCalibrationCam::kBLUE,  1.);
+      CheckAndSet(proj, "uv",   MCalibrationCam::kUV,    1.);
+      CheckAndSet(proj, "ct1",  MCalibrationCam::kCT1,   1.);
+
+      if (fColor != MCalibrationCam::kNONE)
+          *fLog << inf << "Color determined from project-name (" << proj << ")... ";
+      else
+          if (proj.Contains("cl",TString::kIgnoreCase))
+          {
+              *fLog << err;
+              *fLog << "This run has been taken with the continuous light source." << endl;
+              *fLog << "It cannot be used for calibration. Try to run a pedestal extraction on it." << endl;
+              return kFALSE;
+          }
+  }
+  else
+      *fLog << inf << "Color and Intensity determined from project-name (" << proj << ")... ";
+
+  if (fColor == MCalibrationCam::kNONE)
+  {
+      *fLog << err;
+      *fLog << "Sorry, calibration run " << num << " was taken before the events could be" << endl;
+      *fLog << "flagged with a color by the digital modul and no color" << endl;
+      *fLog << "could be determined... abort." << endl;
+      return kFALSE;
+  }
+
+  switch (fColor)
+  {
+  case MCalibrationCam::kGREEN: *fLog << "Green.";  break;
+  case MCalibrationCam::kBLUE:  *fLog << "Blue.";   break;
+  case MCalibrationCam::kUV:    *fLog << "UV.";     break;
+  case MCalibrationCam::kCT1:   *fLog << "CT1.";    break;
+  default: break;
+  }
+  *fLog << endl;
+
+  fPattern->SetPulserColor(fColor);
+  fPattern->SetPulserStrength(fStrength);
+
+  fIsValid = kTRUE;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the pattern to MCalibrationPattern from outside, if fIsValid is set.
+//
+Int_t MCalibColorSet::Process()
+{
+
+  if (fIsValid)
+    {
+      if (fColor == MCalibrationCam::kNONE)
+        return kCONTINUE;
+
+      fPattern->SetPulserColor(fColor);
+      fPattern->SetPulserStrength(fStrength);
+    }
+  
+  return kTRUE;
+}
+
+Int_t MCalibColorSet::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (IsEnvDefined(env, prefix, "ExplicitColor", print))
+    {
+      TString dat = GetEnvValue(env, prefix, "ExplicitColor", "");
+      if (dat.BeginsWith("green", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kGREEN);
+      if (dat.BeginsWith("blue", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kBLUE);
+      if (dat.BeginsWith("uv", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kUV);
+      if (dat.BeginsWith("ct1", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kCT1);
+      rc = kTRUE;
+    }
+
+  return rc;
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibColorSet.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibColorSet.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibColorSet.h	(revision 17960)
@@ -0,0 +1,57 @@
+#ifndef MARS_MCalibColorSet
+#define MARS_MCalibColorSet
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MParList;
+class MCalibrationPattern;
+class MRawEvtHeader;
+
+class MCalibColorSet : public MTask
+{
+private:
+
+  static const Int_t gkIFAEBoxInaugurationRun; //! Run number of first IFAE box calibration (set to: 20113)
+  static const UInt_t gkFirstRunWithFinalBits; //! Run number of first functionning digital modules 
+  
+  MCalibrationPattern *fPattern;               //! Calibration Pattern with the pulse pattern information
+  MRawEvtHeader       *fHeader;                //! Event header with the project name
+  
+  MCalibrationCam::PulserColor_t fColor;       //  Pulser Color to be set
+  Float_t                        fStrength;    //  Pulser Strength to be set
+
+  Bool_t fIsValid;                             //  Have to set the pulse pattern?
+  Bool_t fIsExplicitColor;                     //  Is colour set explicitely from outside (for MC)? 
+  
+  void CheckAndSet(const TString &str, const char *regexp, MCalibrationCam::PulserColor_t col, Float_t strength);
+
+  Bool_t ReInit(MParList *pList);
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MCalibColorSet(const char *name=NULL, const char *title=NULL);
+  
+  void Clear(const Option_t *o="");
+
+  void SetExplicitColor( const MCalibrationCam::PulserColor_t col) 
+    {
+      fIsExplicitColor = kTRUE;
+      fColor    = col;
+      fStrength = 10.;
+    }
+  
+  ClassDef(MCalibColorSet, 0) // Task to workaround missing colors
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibColorSteer.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibColorSteer.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibColorSteer.cc	(revision 17960)
@@ -0,0 +1,352 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 09/2004 <mailto:markus@ifae.es>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibColorSteer
+//
+//  Steers the occurrance of different calibration colours in one calibration 
+//  run. 
+// 
+//  Input Containers:
+//   MCalibrationPattern
+//   MParList
+//
+//  Output Containers:
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibColorSteer.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MGeomCam.h"
+#include "MRawRunHeader.h"
+
+#include "MHCalibrationCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationBlindCam.h"
+#include "MBadPixelsCam.h"
+
+#include "MCalibrationPattern.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationBlindCam.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargeCalc.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimeCalc.h"
+
+ClassImp(MCalibColorSteer);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. 
+//
+MCalibColorSteer::MCalibColorSteer(const char *name, const char *title)
+    : fCalibPattern(NULL), fGeom(NULL), fParList(NULL), fCharge(NULL),
+      fBad(NULL), fChargeCalc(NULL), fRelTimeCalc(NULL), fHistCopy(kFALSE)
+{
+
+  fName  = name  ? name  : "MCalibColorSteer";
+  fTitle = title ? title : "Task to steer the processing of different colours in the calibration events";
+
+}
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MCalibrationPattern
+//  - MTaskList
+//
+Int_t MCalibColorSteer::PreProcess(MParList *pList)
+{
+
+  fCalibPattern = (MCalibrationPattern*)pList->FindObject("MCalibrationPattern");
+  if (!fCalibPattern)
+    {
+      *fLog << err << "MCalibrationPattern not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!fRunHeader)
+    {
+      *fLog << err << "MRawRunHeader not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "MGeomCam not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fParList = pList;
+  if (!fParList)
+    {
+      *fLog << err << "MParList not found... abort." << endl;
+      return kFALSE;
+    }
+
+  MTaskList *tlist = (MTaskList*)pList->FindObject("MTaskList");
+  if (!tlist)
+    {
+      *fLog << err << "MTaskList not found... abort." << endl;
+      return kFALSE;
+    }
+
+  // 
+  // Look for the MBadPixelsCam
+  //
+  fBad = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBad)
+  {
+      *fLog << err << "MBadPixelsCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  // 
+  // Look for the MCalibrationBlindCam
+  //
+  fBlindCam = (MCalibrationBlindCam*)pList->FindCreateObj("MCalibrationBlindCam");
+  if (!fBlindCam)
+      return kFALSE;
+
+  // 
+  // Look for the MFillH name "FillChargeCam".
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationChargeCam")))
+  {
+      *fLog << inf << "Found MHCalibrationChargeCam ... " << flush;
+
+      fCharge = (MCalibrationChargeCam*)pList->FindCreateObj("MCalibrationChargeCam");
+      if (!fCharge)
+          return kFALSE;
+
+      fQECam = (MCalibrationQECam*)pList->FindCreateObj("MCalibrationQECam");
+      if (!fQECam)
+          return kFALSE;
+
+      fChargeCalc = (MCalibrationChargeCalc*)tlist->FindObject("MCalibrationChargeCalc");
+      if (!fChargeCalc)
+      {
+          *fLog << err << "Could not find MCalibrationChargeCalc abort... " << endl;
+          return kFALSE;
+      }
+  }
+
+  // 
+  // Look for the MFillH name "FillRelTimeCam".
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationRelTimeCam")))
+  {
+
+    *fLog << inf << "Found MHCalibrationRelTimeCam ... " << flush;
+
+    fRelTimeCam = (MCalibrationRelTimeCam*)pList->FindCreateObj("MCalibrationRelTimeCam");
+    if (!fRelTimeCam)
+        return kFALSE;
+
+    fRelTimeCalc = (MCalibrationRelTimeCalc*)tlist->FindObject(AddSerialNumber("MCalibrationRelTimeCalc"));
+    if (!fRelTimeCalc)
+        return kFALSE;
+
+    // CALL ITS PrePorcess ???
+  }
+  
+  fColor = MCalibrationCam::kNONE;
+  fStrength = 0.;
+      
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads the pattern from MCalibrationPattern and clear
+// Cams, if the pattern has changed. Executes Finalize of the
+// MCalibration*Calc classes in that case.
+//
+Int_t MCalibColorSteer::Process()
+{
+
+  const MCalibrationCam::PulserColor_t col = fCalibPattern->GetPulserColor();
+  const Float_t strength                   = fCalibPattern->GetPulserStrength();
+
+  if (fColor ==MCalibrationCam::kNONE)
+    {
+      fColor = col;
+      fStrength = strength;
+      return kTRUE;
+    }
+
+  const Float_t strdiff = TMath::Abs(fStrength-strength);
+
+  if (col  == MCalibrationCam::kNONE || (col == fColor && strdiff < 0.05))
+    return kTRUE;
+
+  *fLog << inf << GetDescriptor() << " : Color - old=" << fColor << flush;
+  fColor = col;
+  *fLog << " / new=" << fColor << endl;
+
+  *fLog << inf << GetDescriptor() << " : Strength - old=" << fStrength << flush;
+  fStrength = strength;
+  *fLog << " / new=" << fStrength << endl;
+
+  //
+  // Finalize Possible calibration histogram classes...
+  //
+  *fLog << inf << GetDescriptor() << " : Finalize calibration histograms..." << flush;
+  if (Finalize("MHCalibrationChargeCam"))      *fLog << "MHCalibrationChargeCam...";
+  if (Finalize("MHCalibrationChargeBlindCam")) *fLog << "MHCalibrationChargeBlindCam...";
+  if (Finalize("MHCalibrationRelTimeCam"))     *fLog << "MHCalibrationRelTimeCam...";
+  if (Finalize("MHCalibrationTestCam"))        *fLog << "MHCalibrationChargeCam...";
+  if (Finalize("MHCalibrationTestTimeCam"))    *fLog << "MHCalibrationChargeCam...";
+
+  //
+  // Finalize possible calibration calculation tasks
+  //
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() << " : Finalize calibration calculations..." << flush;
+  if (fChargeCalc)
+    fChargeCalc->Finalize();
+  if (fRelTimeCalc)
+    fRelTimeCalc->Finalize();
+
+  ReInitialize();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads the pattern from MCalibrationPattern and clear
+// Cams, if the pattern has changed. Executes Finalize of the
+// MCalibration*Calc classes in that case.
+//
+Int_t MCalibColorSteer::PostProcess()
+{
+    //
+    // Finalize Possible calibration histogram classes...
+    //
+    *fLog << inf << "Finalize calibration histograms..." << flush;
+    if (Finalize("MHCalibrationChargeCam"))      *fLog << inf << "MHCalibrationChargeCam..." << flush;
+    if (Finalize("MHCalibrationChargeBlindCam")) *fLog << inf << "MHCalibrationChargeBlindCam..." << flush;
+    if (Finalize("MHCalibrationRelTimeCam"))     *fLog << inf << "MHCalibrationRelTimeCam..." << flush;
+    if (Finalize("MHCalibrationTestCam"))        *fLog << inf << "MHCalibrationChargeCam..." << flush;
+    if (Finalize("MHCalibrationTestTimeCam"))    *fLog << inf << "MHCalibrationChargeCam..." << flush;
+    *fLog << inf << "done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches for name in the MParList and calls, if existing: 
+// - MHCalibrationCam::Finalize()
+// - MHCalibrationCam::ResetHists()
+//
+Bool_t MCalibColorSteer::Finalize(const char* name)
+{
+
+  MHCalibrationCam *hist = (MHCalibrationCam*)fParList->FindObject(name);
+  if (!hist)
+      return kFALSE;
+
+  hist->Finalize();
+  //CopyHist(name);
+  hist->ResetHists();
+  hist->SetColor( fCalibPattern->GetPulserColor());
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Clear cams
+//
+Bool_t MCalibColorSteer::ReInitialize()
+{
+
+  *fLog << endl;
+
+  TString namep = GetNamePattern();
+
+  fBad->Clear(); // FIXME:::::: MERGE PreExcl!!!!
+
+  if (fQECam)
+      fQECam->Clear();
+
+  fBlindCam->Clear();
+  fBlindCam->SetPulserColor(fCalibPattern->GetPulserColor());
+
+  if (fRelTimeCam)
+  {
+      fRelTimeCam->Clear();
+      fRelTimeCam->SetPulserColor(fCalibPattern->GetPulserColor());
+  }
+
+  if (fCharge)
+  {
+      fCharge->Clear();
+      fCharge->SetPulserColor(fCalibPattern->GetPulserColor());
+  }
+
+  return kTRUE;
+
+}
+
+TString MCalibColorSteer::GetNamePattern()
+{
+
+  const Float_t strength = fCalibPattern->GetPulserStrength();
+  const MCalibrationCam::PulserColor_t col = fCalibPattern->GetPulserColor();
+
+  TString result = Form("%2.1f",strength);
+  
+  switch (col)
+    {
+    case MCalibrationCam::kCT1:
+      result += "CT1";
+      break;
+    case MCalibrationCam::kGREEN:
+      result += "GREEN";
+      break;
+    case MCalibrationCam::kBLUE:
+      result += "BLUE";
+      break;
+    case MCalibrationCam::kUV:
+      result += "UV";
+      break;
+    default:
+      break;
+    }
+  return result;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibColorSteer.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibColorSteer.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibColorSteer.h	(revision 17960)
@@ -0,0 +1,65 @@
+#ifndef MARS_MCalibColorSteer
+#define MARS_MCalibColorSteer
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+
+class MParList;
+class MGeomCam;
+class MCalibrationPattern;
+class MRawRunHeader;
+class MCalibrationChargeCalc;
+class MCalibrationChargeCam;
+class MCalibrationRelTimeCalc;
+class MCalibrationRelTimeCam;
+class MCalibrationBlindCam;
+class MCalibrationQECam;
+class MBadPixelsCam;
+
+class MCalibColorSteer : public MTask
+{
+private:
+  MCalibrationPattern             *fCalibPattern;    //!
+  MRawRunHeader                   *fRunHeader;       //!
+  MGeomCam                        *fGeom;            //!
+  MParList                        *fParList;         //!
+  MCalibrationChargeCam           *fCharge;          //!
+  MCalibrationRelTimeCam          *fRelTimeCam;      //!
+  MCalibrationBlindCam            *fBlindCam;        //!
+  MCalibrationQECam               *fQECam;           //!
+  MBadPixelsCam                   *fBad;             //!
+
+  MCalibrationChargeCalc          *fChargeCalc;      //!
+  MCalibrationRelTimeCalc         *fRelTimeCalc;     //!
+
+  MCalibrationCam::PulserColor_t   fColor;
+  Float_t                          fStrength;
+
+  Bool_t                           fHistCopy;        // Decide whether MHCalibrationCams will get copied
+
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();
+
+  Bool_t ReInitialize();
+  Bool_t Finalize(const char* name);
+
+  //void    CopyHist(const char* name);
+  TString GetNamePattern();
+
+public:
+    MCalibColorSteer(const char *name=NULL, const char *title=NULL);
+
+    void SetHistCopy(const Bool_t b=kTRUE) { fHistCopy = b; }
+
+    ClassDef(MCalibColorSteer, 1) // Task to steer the processing of multiple calibration colours
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibConstCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibConstCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibConstCam.cc	(revision 17960)
@@ -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): Markus Gaug    01/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalibConstCam
+//
+// Hold the temporary conversion factors for MCalibrateDatara
+//
+// Version 2:
+// ---------
+//   - fRunNumber
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibConstCam.h"
+#include "MCalibConstPix.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MCalibConstCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MCalibConstPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibConstCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibConstPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibConstCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibConstPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibConstCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+MCalibConstCam::MCalibConstCam(const char *name, const char *title)
+    : fBadPixels(0)
+{
+  fName  = name  ? name  : "MCalibConstCam";
+  fTitle = title ? title : "Temporary Storage for Calibration Constants";
+  
+  fArray            = new TClonesArray("MCalibConstPix", 1);
+  fAverageAreas     = new TClonesArray("MCalibConstPix", 1);
+  fAverageSectors   = new TClonesArray("MCalibConstPix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the following TClonesArray's of MCalibConstPix containers:
+// - fArray
+// - fAverageAreas
+// - fAverageSectors
+//  
+MCalibConstCam::~MCalibConstCam()
+{
+  delete fArray;
+  delete fAverageAreas;
+  delete fAverageSectors;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibConstCam::Copy(TObject &obj) const
+{
+
+  MParContainer::Copy(obj);
+
+  MCalibConstCam &cam = (MCalibConstCam&)obj;
+  
+  Int_t n = GetSize();
+  
+  if (n==0)
+    return;
+  
+  cam.InitSize(n);
+  for (int i=0; i<n; i++)
+    (*this)[i].Copy(cam[i]);
+
+  n = GetNumAverageArea();
+  cam.InitAverageAreas(n);
+  for (int i=0; i<n; i++)
+    GetAverageArea(i).Copy(cam.GetAverageArea(i));
+
+  n = GetNumAverageSector();
+  cam.InitAverageSectors(n);
+  for (int i=0; i<n; i++)
+    GetAverageSector(i).Copy(cam.GetAverageSector(i));
+}
+
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MCalibConstCam::Init(const MGeomCam &geom)
+{
+  InitSize          (geom.GetNumPixels() );
+  InitAverageAreas  (geom.GetNumAreas()  );
+  InitAverageSectors(geom.GetNumSectors());
+}
+
+// --------------------------------------------------------------------------
+//
+// This function returns the current size of the TClonesArray 
+// independently if the MCalibConstPix is filled with values or not.
+//
+// Get the size of the MCalibConstCam
+//
+Int_t MCalibConstCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageAreas
+// independently if the MCalibConstPix is filled with values or not.
+//
+const Int_t MCalibConstCam::GetNumAverageArea() const
+{
+  return fAverageAreas->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageSectors
+// independently if the MCalibConstPix is filled with values or not.
+//
+const Int_t MCalibConstCam::GetNumAverageSector() const
+{
+  return fAverageSectors->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MCalibConstPix &MCalibConstCam::operator[](Int_t i)
+{
+    return *static_cast<MCalibConstPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MCalibConstPix &MCalibConstCam::operator[](Int_t i) const
+{
+    return *static_cast<MCalibConstPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MCalibConstPix &MCalibConstCam::GetAverageArea(UInt_t i)
+{
+  return *static_cast<MCalibConstPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MCalibConstPix &MCalibConstCam::GetAverageArea(UInt_t i) const 
+{
+  return *static_cast<MCalibConstPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MCalibConstPix &MCalibConstCam::GetAverageSector(UInt_t i)
+{
+  return *static_cast<MCalibConstPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MCalibConstPix &MCalibConstCam::GetAverageSector(UInt_t i) const 
+{
+  return *static_cast<MCalibConstPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------
+//
+// Calls the ForEach macro for the TClonesArray fArray with the argument Clear()
+// 
+// Loops over the fAverageAreas, calling the function Clear() for 
+// every entry in fAverageAreas
+//
+// Loops over the fAverageSectors, calling the function Clear() for 
+// every entry in fAverageSectors
+// 
+void MCalibConstCam::Clear(Option_t *o)
+{
+    { fArray->R__FOR_EACH(TObject, Clear)(); }
+    { fAverageAreas->R__FOR_EACH(TObject, Clear)(); }
+    { fAverageSectors->R__FOR_EACH(TObject, Clear)(); }
+  
+}
+
+void MCalibConstCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    int id = 0;
+
+    TIter Next(fArray);
+    MCalibConstPix *pix;
+    while ((pix=(MCalibConstPix*)Next()))
+    {
+        *fLog << id 
+	      << Form(": Conversion Factor: %4.3f  Global F-Factor: %4.3f",pix->GetCalibConst(),pix->GetCalibFFactor()) 
+	      << endl;
+        id++;
+    }
+}
+
+
+Bool_t MCalibConstCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (GetSize() <= idx)
+        return kFALSE;
+
+    if (fBadPixels && (*fBadPixels)[idx].IsUnsuitable())
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+      val = (*this)[idx].GetCalibConst();
+      break;
+    case 1:
+      val = (*this)[idx].GetCalibFFactor();
+      break;
+    case 2:
+      val = (*this)[idx].GetCalibConst()*cam.GetPixRatio(idx);
+      break;
+    default:
+      return kFALSE;
+    }
+
+    return val>0.;
+}
+
+void MCalibConstCam::DrawPixelContent(Int_t idx) const
+{
+    *fLog << warn << "MCalibConstCam::DrawPixelContent - not available." << endl;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibConstCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibConstCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibConstCam.h	(revision 17960)
@@ -0,0 +1,68 @@
+#ifndef MARS_MCalibConstCam
+#define MARS_MCalibConstCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class MGeomCam;
+class MCalibConstPix;
+class MBadPixelsCam;
+
+class MCalibConstCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TClonesArray *fArray;           //-> Array of MCalibConstPix, one per pixel
+  TClonesArray *fAverageAreas;    //-> Array of MCalibConstPix, one per pixel area
+  TClonesArray *fAverageSectors;  //-> Array of MCalibConstPix, one per camera sector
+
+  //Int_t fRunNumber;               // Run number
+
+  MBadPixelsCam *fBadPixels;      //!
+
+public:
+
+  MCalibConstCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibConstCam();
+  
+  void Clear(Option_t *o="");
+  void Copy(TObject &object) const;
+  
+  // Getters 
+        MCalibConstPix &GetAverageArea     ( UInt_t i );
+  const MCalibConstPix &GetAverageArea     ( UInt_t i )  const;
+  const Int_t           GetNumAverageArea  ()            const;
+        MCalibConstPix &GetAverageSector   ( UInt_t i );
+  const MCalibConstPix &GetAverageSector   ( UInt_t i )  const;
+  const Int_t           GetNumAverageSector()            const;
+  Int_t                 GetSize            ()            const;
+
+        MCalibConstPix &operator[]         ( Int_t i  );
+  const MCalibConstPix &operator[]         ( Int_t i  )  const;
+
+  void  Init                           ( const MGeomCam &geom);
+  void  InitSize                       ( const UInt_t i ) { fArray->ExpandCreate(i);          }
+  void  InitAverageAreas               ( const UInt_t i ) { fAverageAreas->ExpandCreate(i);   }
+  void  InitAverageSectors             ( const UInt_t i ) { fAverageSectors->ExpandCreate(i); }
+
+  void Print(Option_t *o="") const;
+
+  // Setters
+  //void SetRunNumber(const Int_t n)    { fRunNumber = n; }
+  void SetBadPixels(MBadPixelsCam *b) { fBadPixels = b; }
+  
+  Bool_t GetPixelContent (Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void   DrawPixelContent(Int_t idx) const;
+
+  ClassDef(MCalibConstCam, 2)	// Temporary Storage for calibration constants
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibConstPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibConstPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibConstPix.cc	(revision 17960)
@@ -0,0 +1,42 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug    01/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalibConstPix
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MCalibConstPix.h"
+
+ClassImp(MCalibConstPix);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCalibConstPix::MCalibConstPix()
+{
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibConstPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibConstPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibConstPix.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MCalibConstPix
+#define MARS_MCalibConstPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCalibConstPix : public MParContainer
+{
+private:
+    Float_t fCalibConst;        // conversion factor (modified after each interlaced cal. update)
+    Float_t fCalibFFactor;      // global F-Factor   (modified after each interlaced cal. update)
+
+public:
+    MCalibConstPix();
+
+    // TObject
+    void Clear(Option_t *o="")
+    {
+        fCalibConst   = -1.;
+        fCalibFFactor = -1.;
+    }
+
+    void Copy(TObject &object) const
+    {
+        MCalibConstPix &pix =  (MCalibConstPix&)object;
+        pix.fCalibConst   = fCalibConst;
+        pix.fCalibFFactor = fCalibFFactor;
+    }
+
+    // Getters
+    Float_t GetCalibConst()   const { return fCalibConst;   }
+    Float_t GetCalibFFactor() const { return fCalibFFactor; }
+
+    // Setters
+    void SetCalibConst  ( const Float_t f )  { fCalibConst   = f; }
+    void SetCalibFFactor( const Float_t f )  { fCalibFFactor = f; }
+
+    ClassDef(MCalibConstPix, 1) // Temporay Storage Calibraion Constant of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrateData.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrateData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrateData.cc	(revision 17960)
@@ -0,0 +1,955 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez    12/2003 <mailto:jlopez@ifae.es>
+!   Author(s): Javier Rico     01/2004 <mailto:jrico@ifae.es>
+!   Author(s): Wolfgang Wittek 02/2004 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Markus Gaug     04/2004 <mailto:markus@ifae.es>
+!   Author(s): Hendrik Bartko  08/2004 <mailto:hbartko@mppmu.mpg.de>
+!   Author(s): Thomas Bretz    08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrateData
+//
+//   This task takes the integrated charge from MExtractedSignal and applies
+//   the calibration constants from MCalibrationCam to convert the summed FADC 
+//   slices into photons. The number of photons obtained is stored in MSignalCam. 
+//   Optionally, the calibration of pedestals from an MPedestalCam container into 
+//   an MPedPhotCam container can be chosen with the member functions 
+//   SetPedestalType(). Default is 'kRun', i.e. calibration of pedestals from a 
+//   dedicated pedestal run.
+//   In case, the chosen pedestal type is kRun or kEvent, in ReInit() the MPedPhotCam 
+//   container is filled using the information from MPedestalCam, MExtractedSignalCam, 
+//   MCalibrationChargeCam and MCalibrationQECam
+//
+//   Selection of different calibration methods is allowed through the 
+//   SetCalibrationMode() member function (default: kFfactor)
+//
+//   The calibration modes which exclude non-valid pixels are the following: 
+//
+//     kFfactor:    calibrates using the F-Factor method
+//     kBlindpixel: calibrates using the BlindPixel method
+//     kBlindpixel: calibrates using the BlindPixel method
+//     kFlatCharge: perform a charge flat-flatfielding. Outer pixels are area-corrected.
+//     kDummy:      calibrates with fixed conversion factors of 1 and errors of 0.
+//
+//   The calibration modes which include all pixels regardless of their validity is:
+//
+//     kNone:       calibrates with fixed conversion factors of 1 and errors of 0.
+//
+//   Use the kDummy and kNone methods ONLY FOR DEBUGGING!
+//
+//
+//   This class can calibrate data and/or pedestals. To switch off calibration of data
+//   set the Calibration Mode to kSkip. To switch on pedestal calibration call either
+//     SetPedestalFlag(MCalibrateData::kRun)    (calibration is done once in ReInit)
+//     SetPedestalFlag(MCalibrateData::kEvent)  (calibration is done for each event)
+//
+//   By calling AddPedestal() you can control the name of the
+//   MPedestalCam and/or MPedPhotCam container which is used.
+//
+//   Assume you want to calibrate "MPedestalCam" once and "MPedestalFromLoGain" [MPedestalCam]
+//   event-by-event, so:
+//     MCalibrateData cal1;
+//     cal1.SetCalibrationMode(MCalibrateData::kSkip);
+//     cal1.SetPedestalFlag(MCalibrateData::kRun);
+//     MCalibrateData cal2;
+//     cal2.SetCalibrationMode(MCalibrateData::kSkip);
+//     cal2.AddPedestal("FromLoGain");
+//     cal2.SetPedestalFlag(MCalibrateData::kEvent);
+//
+//
+//   Input Containers:
+//    [MPedestalCam]
+//    [MExtractedSignalCam]
+//    [MCalibrationChargeCam]
+//    [MCalibrationQECam]
+//    MBadPixelsCam
+//
+//   Output Containers:
+//    [MPedPhotCam]
+//    [MSignalCam]
+//
+// See also: MJCalibration, MJPedestal, MJExtractSignal, MJExtractCalibTest
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateData.h"
+
+#include <fstream>
+
+#include <TEnv.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MH.h"
+
+#include "MGeomCam.h"
+#include "MRawRunHeader.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+ 
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+ 
+#include "MCalibConstCam.h"
+#include "MCalibConstPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MSignalCam.h"
+
+ClassImp(MCalibrateData);
+
+using namespace std;
+
+const Float_t MCalibrateData::gkCalibConvMinLimit = 0.01;
+const Float_t MCalibrateData::gkCalibConvMaxLimit = 5.;
+
+const MCalibrateData::CalibrationMode_t MCalibrateData::gkDefault = kFfactor;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets all pointers to NULL
+// 
+// Initializes:
+// - fCalibrationMode to kDefault
+// - fPedestalFlag to kNo
+//
+MCalibrateData::MCalibrateData(CalibrationMode_t calmode,const char *name, const char *title) 
+    : fGeomCam(NULL),   fBadPixels(NULL), fCalibrations(NULL),
+      fQEs(NULL), fSignals(NULL), fCerPhotEvt(NULL), fCalibConstCam(NULL),
+    fPedestalFlag(kNo), fSignalType(kPhot), fRenormFactor(1.), fScaleFactor(1)
+{
+
+  fName  = name  ? name  : "MCalibrateData";
+  fTitle = title ? title : "Task to calculate the number of photons in one event";
+  
+  SetCalibrationMode(calmode);
+  
+  SetCalibConvMinLimit();
+  SetCalibConvMaxLimit();
+
+  fNamesPedestal.SetOwner();
+}
+
+void MCalibrateData::AddPedestal(const char *name)
+{
+    TString ped(name);
+    TString pho(name);
+    ped.Prepend("MPedestal");
+    pho.Prepend("MPedPhot");
+
+    fNamesPedestal.Add(new TNamed(ped, pho));
+}
+
+void MCalibrateData::AddPedestal(const char *pedestal, const char *pedphot)
+{
+    fNamesPedestal.Add(new TNamed(pedestal, pedphot));
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//
+//  - MGeomCam
+//  - MPedestalCam
+//  - MCalibrationChargeCam
+//  - MCalibrationQECam
+//  - MExtractedSignalCam
+//  - MBadPixelsCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedPhotCam
+//  - MSignalCam
+//
+Int_t MCalibrateData::PreProcess(MParList *pList)
+{
+    // input containers
+
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+    {
+        *fLog << err << AddSerialNumber("MBadPixelsCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    fSignals    = 0;
+    fCerPhotEvt = 0;
+    if (fCalibrationMode>kSkip)
+    {
+        fSignals = (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+        if (!fSignals)
+        {
+            *fLog << err << AddSerialNumber("MExtractedSignalCam") << " not found ... aborting" << endl;
+            return kFALSE;
+        }
+
+        fCerPhotEvt = (MSignalCam*)pList->FindCreateObj(AddSerialNumber("MSignalCam"));
+        if (!fCerPhotEvt)
+            return kFALSE;
+
+        fCalibConstCam = (MCalibConstCam*)pList->FindCreateObj(AddSerialNumber("MCalibConstCam"));
+        if (!fCalibConstCam)
+            return kFALSE;
+    }
+
+    fCalibrations = 0;
+    fQEs          = 0;
+    if (fCalibrationMode>kNone)
+    {
+        fCalibrations = (MCalibrationChargeCam*)pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+        if (!fCalibrations)
+        {
+            *fLog << err << AddSerialNumber("MCalibrationChargeCam") << " not found ... aborting." << endl;
+            return kFALSE;
+        }
+
+        fQEs = (MCalibrationQECam*)pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+        if (!fQEs)
+        {
+            *fLog << err << AddSerialNumber("MCalibrationQECam") << " not found ... aborting." << endl;
+            return kFALSE;
+        }
+
+    }
+
+    if (fNamesPedestal.GetSize()>0 && fPedestalFlag==kNo)
+    {
+        *fLog << warn << "Pedestal list contains entries, but mode is set to kNo... setting to kEvent." << endl;
+        fPedestalFlag = kEvent;
+    }
+
+    if (fPedestalFlag!=kNo)
+    {
+        if (fNamesPedestal.GetSize()==0)
+        {
+            *fLog << inf << "No container names specified... using default: MPedestalCam and MPedPhotCam." << endl;
+            AddPedestal();
+        }
+
+        fPedestalCams.Clear();
+        fPedPhotCams.Clear();
+
+        TIter Next(&fNamesPedestal);
+        TObject *o=0;
+        while ((o=Next()))
+        {
+            TObject *pedcam = pList->FindObject(AddSerialNumber(o->GetName()), "MPedestalCam");
+            if (!pedcam)
+            {
+                *fLog << err << AddSerialNumber(o->GetName()) << " [MPedestalCam] not found ... aborting" << endl;
+                return kFALSE;
+            }
+            TObject *pedphot = pList->FindCreateObj("MPedPhotCam", AddSerialNumber(o->GetTitle()));
+            if (!pedphot)
+                return kFALSE;
+
+            fPedestalCams.Add(pedcam);
+            fPedPhotCams.Add(pedphot);
+        }
+    }
+
+    switch (fSignalType)
+      {
+      case kPhe:
+          //
+          // Average QE for C-photons, for pixels in the inner pixel region ("area 0"),
+          // used later to convert from C-photons into "equivalent phes":
+          //
+
+          // Average areas not yet initialized? use default value
+          fRenormFactor = MCalibrationQEPix::gkDefaultAverageQE;
+          if (fQEs->GetAverageAreas() > 0)
+          {
+              MCalibrationQEPix& avqepix = (MCalibrationQEPix&)(fQEs->GetAverageArea(0));
+              fRenormFactor = avqepix.GetAverageQE();
+          }
+          break;
+
+      case kPhot:
+          fRenormFactor = 1.;
+          break;
+      }
+
+    fCalibConsts.Reset();
+    fCalibFFactors.Reset();
+    fHiLoConv.Reset();
+    fHiLoConvErr.Reset();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit searches for the following input containers:
+//
+//  - MGeomCam
+//
+// Check for validity of the selected calibration method, switch to a 
+// different one in case of need
+//
+// Fill the MPedPhotCam container using the information from MPedestalCam,
+// MExtractedSignalCam and MCalibrationCam
+//
+Bool_t MCalibrateData::ReInit(MParList *pList)
+{
+    MRawRunHeader *header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!header)
+    {
+        *fLog << err << "MRawRunHeader not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << "No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // Sizes might have changed
+    if (fPedestalFlag!=kNo)
+    {
+        TIter Next(&fPedestalCams);
+        MPedestalCam *cam=0;
+        while ((cam=(MPedestalCam*)Next()))
+        if ((Int_t)cam->GetSize() != fSignals->GetSize())
+        {
+            *fLog << err << "Size mismatch of " << cam->GetDescriptor() << " and MCalibrationCam... abort." << endl;
+            return kFALSE;
+        }
+    }
+
+    if(fCalibrationMode == kBlindPixel && !fQEs->IsBlindPixelMethodValid())
+    {
+        *fLog << warn << "Blind pixel calibration method not valid, switching to F-factor method" << endl;
+        fCalibrationMode = kFfactor;
+    }
+
+    if(fCalibrationMode == kPinDiode && !fQEs->IsPINDiodeMethodValid())
+    {
+        *fLog << warn << "PIN diode calibration method not valid, switching to F-factor method" << endl;
+        fCalibrationMode = kFfactor;
+    }
+
+    if(fCalibrationMode == kCombined && !fQEs->IsCombinedMethodValid())
+    {
+        *fLog << warn << "Combined calibration method not valid, switching to F-factor method" << endl;
+        fCalibrationMode = kFfactor;
+    }
+
+    //
+    // output information or warnings:
+    //
+    switch(fCalibrationMode)
+    {
+    case kBlindPixel:
+        break;
+    case kFfactor:
+        break;
+    case kPinDiode:
+        *fLog << err << "PIN Diode Calibration mode not yet available!" << endl;
+        return kFALSE;
+        break;
+    case kCombined:
+        *fLog << err << "Combined Calibration mode not yet available!" << endl;
+        return kFALSE;
+        break;
+    case kFlatCharge:
+        *fLog << warn << "WARNING - Flat-fielding charges - only for muon calibration!" << endl;
+        break;
+    case kDummy:
+        *fLog << warn << "WARNING - Dummy calibration, no calibration applied!" << endl;
+        break;
+    case kNone:
+        *fLog << warn << "WARNING - No calibration applied!" << endl;
+        break;
+    default:
+        *fLog << warn << "WARNING - Calibration mode value (" << fCalibrationMode << ") not known" << endl;
+        return kFALSE;
+    }
+
+    //
+    // output information or warnings:
+    //
+    switch (fSignalType)
+    {
+    case kPhe:
+        *fLog << inf << "Calibrating in units of equivalent (outer/inner=4) photo-electrons." << endl;
+        break;
+    case kPhot:
+        *fLog << inf << "Calibrating in units of photons." << endl;
+        break;
+    }
+
+    if (header->IsMonteCarloRun())
+    {
+        if (fScaleFactor!=1)
+            *fLog << warn << "WARNING - Additional scale factor for MonteCarlo run not unity but " << fScaleFactor << endl;
+    }
+    else
+    {
+        if (!fFileNameScale.IsNull())
+        {
+            if (gSystem->AccessPathName(fFileNameScale, kFileExists))
+            {
+                *fLog << err << "ERROR - Configuration file '" << fFileNameScale << "' doesn't exist... abort." << endl;
+                return kFALSE;
+            }
+
+            const Int_t   p   = header->GetRunStart().GetMagicPeriod();
+            const TString per = Form("%2d", p);
+
+            TEnv rc(fFileNameScale);
+            const Double_t scale = rc.GetValue(per, -1.);
+
+            if (scale<=0)
+            {
+                *fLog << err << "ERROR - No valid entry for scale factor found for period " << p << " in " << fFileNameScale << "... abort." << endl;
+                return kFALSE;
+            }
+
+            *fLog << inf << "New additional scale factor for period " << p << ": " << scale << endl;
+            fScaleFactor = scale;
+        }
+        else
+            *fLog << inf << "Additional scale factor set to: " << fScaleFactor << endl;
+    }
+
+    const Int_t npixels = fGeomCam->GetNumPixels();
+
+    if (fCalibrationMode > kNone)
+    {
+        if (fCalibrations->GetSize() != npixels)
+        {
+            *fLog << "Size mismatch between MGeomCam and MCalibrationChargeCam... abort!" << endl;
+            return kFALSE;
+        }
+
+        if (fBadPixels->GetSize() != npixels)
+        {
+            *fLog << "Size mismatch between MGeomCam and MBadPixelsCam... abort!" << endl;
+            return kFALSE;
+        }
+    }
+
+    fCalibConsts  .Set(npixels);
+    fCalibFFactors.Set(npixels);
+    fHiLoConv     .Set(npixels);
+    fHiLoConvErr  .Set(npixels);
+    
+    if (!UpdateConversionFactors())
+      return kFALSE;
+
+    if (TestPedestalFlag(kRun))
+        Calibrate(kFALSE, kTRUE);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the conversion factors and F-Factors from MCalibrationCams into 
+// the arrays. Later, the here pre-calcualted conversion factors get simply 
+// copied from memory. 
+//
+// This function can be called from outside in case that the MCalibrationCams 
+// have been updated...
+//
+Bool_t MCalibrateData::UpdateConversionFactors( const MCalibrationChargeCam *updatecam)
+{
+
+    *fLog << inf << GetDescriptor() << ": Updating Conversion Factors... " << endl;
+    
+    fCalibConsts.Reset();
+    fCalibFFactors.Reset();
+    fHiLoConv.Reset();
+    fHiLoConvErr.Reset();
+
+    //
+    // For the moment, we use only a dummy zenith for the calibration:
+    //
+    UInt_t skip = 0;
+
+    for (UInt_t pixidx=0; pixidx<fGeomCam->GetNumPixels(); pixidx++)
+      {
+
+        Float_t hiloconv     = 1.;
+        Float_t hiloconverr  = 0.;
+        Float_t calibConv    = 1.;
+        Float_t calibConvVar = 0.;
+        Float_t calibFFactor = 0.;
+
+        Float_t calibQE       = 1.;
+        Float_t calibQEVar    = 0.;
+
+        Float_t calibUpdate   = 1.;
+
+        if(fCalibrationMode!=kNone)
+          {
+            if ((*fBadPixels)[pixidx].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+              {
+                skip++;
+                continue; // calibConv will remain 0
+             }
+            
+            const MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*fCalibrations)[pixidx];
+            const MCalibrationChargePix &avpix = (MCalibrationChargePix&)fCalibrations->GetAverageArea(0);
+
+            hiloconv   = pix.GetConversionHiLo     ();
+            hiloconverr= pix.GetConversionHiLoSigma();
+
+            calibConv    = pix.GetMeanConvFADC2Phe();
+            calibConvVar = pix.GetMeanConvFADC2PheVar();
+            calibFFactor = pix.GetMeanFFactorFADC2Phot();
+
+            const MCalibrationQEPix &qe = (MCalibrationQEPix&)(*fQEs)[pixidx];
+
+            if (updatecam)
+              {
+                const MCalibrationChargePix &upix = (MCalibrationChargePix&)(*updatecam)[pixidx];
+
+                //
+                // Correct for the possible change in amplification of the individual pixels chain
+                // 
+                const Float_t pixmean = upix.GetConvertedMean();
+                calibUpdate = pixmean==0 ? 1 : pix.GetConvertedMean()/pixmean;
+
+                //
+                // Correct for global shifts in light emission
+                // 
+                const MCalibrationChargePix &ugpix = static_cast<const MCalibrationChargePix&>(updatecam->GetAverageArea(0));
+
+                const Float_t globmean = avpix.GetConvertedMean();
+                calibUpdate = globmean==0 ? 1 : ugpix.GetConvertedMean()/globmean;
+
+                const MBadPixelsPix &ubad  = static_cast<const MBadPixelsPix&>(updatecam->GetAverageBadArea(0));
+                if (ubad.IsUncalibrated(MBadPixelsPix::kChargeIsPedestal))
+                  {
+                    *fLog << warn << GetDescriptor() << ": Mean charge in inner pixels is smaller than 3 ped. RMS." << endl;
+                    *fLog << "Maybe calibration pulses have been lost!" << endl;
+                    calibUpdate = 1.;
+
+                  }
+              }
+            
+            switch(fCalibrationMode)
+              {
+              case kFlatCharge:
+                {
+                  calibConv    = avpix.GetConvertedMean() 
+                              / (pix.GetConvertedMean() * fGeomCam->GetPixRatio(pixidx));
+                  calibConvVar = (avpix.GetMeanRelVar() + pix.GetMeanRelVar()) * calibConv * calibConv;
+                  if (pix.IsFFactorMethodValid())
+                    {
+                      const Float_t convmin1 = qe.GetQECascadesFFactor()/pix.GetMeanConvFADC2Phe();
+                      if (convmin1 > 0)
+                        calibFFactor *= TMath::Sqrt(convmin1);
+                      else
+                        calibFFactor = -1.;
+                    }
+                  break;
+                }
+              case kBlindPixel:
+                if (!qe.IsBlindPixelMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesBlindPixel();
+                calibQEVar  = qe.GetQECascadesBlindPixelVar();
+                break;
+                
+              case kPinDiode:
+                if (!qe.IsPINDiodeMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesPINDiode();
+                calibQEVar  = qe.GetQECascadesPINDiodeVar();
+                break;
+                
+              case kFfactor:
+                if (!pix.IsFFactorMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesFFactor();
+                calibQEVar  = qe.GetQECascadesFFactorVar();
+                break;
+                
+              case kCombined:
+                if (!qe.IsCombinedMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesCombined();
+                calibQEVar  = qe.GetQECascadesCombinedVar();
+                break;
+                
+              case kDummy:
+                hiloconv    = 1.;
+                hiloconverr = 0.;
+                calibUpdate = 1.;
+                break;
+
+              default:
+                  break;
+              } /* switch calibration mode */
+          } /* if(fCalibrationMode!=kNone) */
+        else
+          {
+            calibConv  = 1./fGeomCam->GetPixRatio(pixidx);
+          }
+        
+        calibConv /= calibQE;
+
+        if (calibConv > 0.00001 && calibQE > 0.00001)
+          {
+            calibConvVar  = calibConvVar/(calibConv*calibConv) + calibQEVar/(calibQE*calibQE);
+            calibConvVar *= (calibConv*calibConv);
+          }
+
+	calibConv    *= fRenormFactor*fScaleFactor * calibUpdate;
+	calibFFactor *= TMath::Sqrt(fRenormFactor*fScaleFactor);
+
+        fHiLoConv     [pixidx] = hiloconv;
+        fHiLoConvErr  [pixidx] = hiloconverr;
+        fCalibConsts  [pixidx] = calibConv;
+        fCalibFFactors[pixidx] = calibFFactor;
+
+	if (calibConv < fCalibConvMinLimit || calibConv > fCalibConvMaxLimit)
+	  {
+	    (*fBadPixels)[pixidx].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);  
+	    calibConv    = -1.;
+	    calibFFactor = -1.;
+            *fLog << warn << GetDescriptor() << ": ";
+            *fLog << "Conv.factor " << calibConv << " of Pixel " << pixidx << " out of range ]";
+            *fLog << fCalibConvMinLimit << "," << fCalibConvMaxLimit << "[... set unsuitable. " << endl;
+	  }
+
+        MCalibConstPix &cpix  = (*fCalibConstCam)[pixidx];
+
+        cpix.SetCalibConst(calibConv);
+	cpix.SetCalibFFactor(calibFFactor);
+
+      } /*     for (Int_t pixidx=0; pixidx<fGeomCam->GetNumPixels(); pixidx++) */
+
+    fCalibConstCam->SetReadyToSave();
+
+    if (skip>fGeomCam->GetNumPixels()*0.9)
+    {
+        *fLog << err << GetDescriptor() << ": ERROR - ";
+        *fLog << "GetConversionFactor has skipped more than 90% of the " << fGeomCam->GetNumPixels() <<  " pixels... abort." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Apply the conversion factors and F-Factors from the arrays to the data. 
+//
+// The flags 'data' and 'pedestal' decide whether the signal and/or the pedetals
+// shall be calibrated, respectively. 
+//
+Int_t MCalibrateData::Calibrate(Bool_t data, Bool_t doped) const
+{
+    if (!data && !doped)
+        return kTRUE;
+
+    const UInt_t  npix       = fSignals->GetSize();
+
+    // The number of used slices are just a mean value
+    // the real number might change from event to event.
+    // (up to 50%!)
+    const Float_t slices     = fSignals->GetNumUsedHiGainFADCSlices();
+    const Float_t sqrtslices = TMath::Sqrt(slices);
+
+    Int_t numsatlo=0;
+    Int_t numsathi=0;
+
+    for (UInt_t pixidx=0; pixidx<npix; pixidx++)
+    {
+        MBadPixelsPix &bpix = (*fBadPixels)[pixidx];
+      
+        if (data)
+        {
+            const MExtractedSignalPix &sig = (*fSignals)[pixidx];
+
+            Float_t signal    = 0.;
+//            Float_t signalErr = 0.;
+            Bool_t  ok        = kFALSE;
+
+            // If hi-gain is not saturated and has successfully been
+            // extracted use the hi-gain arrival time
+            if (!sig.IsHiGainSaturated() && sig.IsHiGainValid())
+            {
+                signal = sig.GetExtractedSignalHiGain();
+                ok = kTRUE;
+            }
+            else
+            {
+                // Use lo-gain if it can be used
+                if (sig.IsLoGainValid() && fHiLoConv[pixidx]>0.5)
+                {
+                    signal    = sig.GetExtractedSignalLoGain()*fHiLoConv[pixidx];
+//                    signalErr = sig.GetExtractedSignalLoGain()*fHiLoConvErr[pixidx];
+                    ok = kTRUE;
+                }
+            }
+
+            // In this cases the signal extraction has failed.
+            if (!ok)
+                bpix.SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+
+            const Float_t nphot    = signal                         * fCalibConsts  [pixidx];
+            const Float_t nphotErr = TMath::Sqrt(TMath::Abs(nphot)) * fCalibFFactors[pixidx];
+
+            fCerPhotEvt->AddPixel(pixidx, nphot, nphotErr);
+
+            if (!bpix.IsUnsuitable())
+            {
+                if (sig.IsHiGainSaturated())
+                    numsathi++;
+
+                if (sig.IsLoGainSaturated())
+                    numsatlo++;
+            }
+        } /* if (data) */
+      
+        if (doped)
+        {
+            TIter NextPed(&fPedestalCams);
+            TIter NextPhot(&fPedPhotCams);
+
+            MPedestalCam *pedestal = 0;
+            MPedPhotCam  *pedphot  = 0;
+            
+            const Float_t pedmeancalib = slices    *fCalibConsts[pixidx];
+            const Float_t pedrmscalib  = sqrtslices*fCalibConsts[pixidx];
+
+            while ((pedestal=(MPedestalCam*)NextPed()) &&
+                   (pedphot =(MPedPhotCam*)NextPhot()))
+            {
+              // pedestals/(used FADC slices)   in [number of photons]
+              const Float_t mean = (*pedestal)[pixidx].GetPedestal()   *pedmeancalib;
+              const Float_t rms  = (*pedestal)[pixidx].GetPedestalRms()*pedrmscalib;
+
+              (*pedphot)[pixidx].Set(mean, rms);
+              pedphot->SetReadyToSave();
+              //break;
+            }
+        } /* if (pedestal) */
+    }
+
+    // Now we should take the bias (MPedPhotExtractor/Mean) and
+    // pedestal rms (MPedPhotExtractorRndm/Rms) and store it
+    // into MSignalPix
+
+    if (data)
+    {
+        fCerPhotEvt->SetNumPixelsSaturated(numsathi, numsatlo);
+        fCerPhotEvt->SetReadyToSave();
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the calibration factors to the extracted signal according to the 
+// selected calibration method
+//
+Int_t MCalibrateData::Process()
+{
+    return Calibrate(fCalibrationMode!=kSkip, TestPedestalFlag(kEvent));
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MCalibrateData::StreamPrimitive(ostream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (TestPedestalFlag(kEvent))
+        out << "   " << GetUniqueName() << ".EnablePedestalType(MCalibrateData::kEvent)" << endl;
+    if (TestPedestalFlag(kRun))
+        out << "   " << GetUniqueName() << ".EnablePedestalType(MCalibrateData::kRun)" << endl;
+
+    if (fCalibrationMode != gkDefault)
+    {
+        out << "   " << GetUniqueName() << ".SetCalibrationMode(MCalibrateData::";
+        switch (fCalibrationMode)
+        {
+        case kSkip:       out << "kSkip";               break;
+        case kNone:       out << "kNone";               break;
+        case kFlatCharge: out << "kFlatCharge";         break;
+        case kBlindPixel: out << "kBlindPixel";         break;
+        case kFfactor:    out << "kFfactor";            break;
+        case kPinDiode:   out << "kPinDiode";           break;
+        case kCombined:   out << "kCombined";           break;
+        case kDummy:      out << "kDummy";              break;
+        default:          out << (int)fCalibrationMode; break;
+        }
+        out << ")" << endl;
+    }
+
+    TIter Next(&fNamesPedestal);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        out << "   " << GetUniqueName() << ".AddPedestal(\"";
+        out << o->GetName() << "\", \"" << o->GetTitle() << "\");" << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MCalibrateDate.PedestalFlag: no,run,event
+//   MJPedestal.MCalibrateDate.CalibrationMode: skip,none,flatcharge,blindpixel,ffactor,pindiode,combined,dummy,default
+//
+Int_t MCalibrateData::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "PedestalFlag", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "PedestalFlag", "");
+        s.ToLower();
+        if (s.BeginsWith("no"))
+            SetPedestalFlag(kNo);
+        if (s.BeginsWith("run"))
+            SetPedestalFlag(kRun);
+        if (s.BeginsWith("event"))
+            SetPedestalFlag(kEvent);
+    }
+
+    if (IsEnvDefined(env, prefix, "CalibrationMode", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "CalibrationMode", "");
+        s.ToLower();
+        if (s.BeginsWith("skip"))
+            SetCalibrationMode(kSkip);
+        if (s.BeginsWith("none"))
+            SetCalibrationMode(kNone);
+        if (s.BeginsWith("flatcharge"))
+            SetCalibrationMode(kFlatCharge);
+        if (s.BeginsWith("blindpixel"))
+            SetCalibrationMode(kBlindPixel);
+        if (s.BeginsWith("ffactor"))
+            SetCalibrationMode(kFfactor);
+        if (s.BeginsWith("pindiode"))
+            SetCalibrationMode(kPinDiode);
+        if (s.BeginsWith("combined"))
+            SetCalibrationMode(kCombined);
+        if (s.BeginsWith("dummy"))
+            SetCalibrationMode(kDummy);
+        if (s.BeginsWith("default"))
+            SetCalibrationMode();
+    }
+
+    if (IsEnvDefined(env, prefix, "SignalType", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "SignalType", "");
+        s.ToLower();
+        if (s.BeginsWith("phot"))
+            SetSignalType(kPhot);
+        if (s.BeginsWith("phe"))
+            SetSignalType(kPhe);
+        if (s.BeginsWith("default"))
+            SetSignalType();
+    }
+
+    if (IsEnvDefined(env, prefix, "CalibConvMinLimit", print))
+    {
+        fCalibConvMinLimit = GetEnvValue(env, prefix, "CalibConvMinLimit", fCalibConvMinLimit);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "CalibConvMaxLimit", print))
+    {
+        fCalibConvMaxLimit = GetEnvValue(env, prefix, "CalibConvMaxLimit", fCalibConvMaxLimit);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "ScaleFactor", print))
+    {
+        fScaleFactor = GetEnvValue(env, prefix, "ScaleFactor", fScaleFactor);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "FileNameScale", print))
+    {
+        fFileNameScale = GetEnvValue(env, prefix, "FileNameScale", fFileNameScale);
+        rc = kTRUE;
+    }
+
+    return rc;
+}
+
+void MCalibrateData::Print(Option_t *o) const 
+{
+  
+  *fLog << all << GetDescriptor() << ":" << endl;
+  
+  for (UInt_t pixidx=0; pixidx<fGeomCam->GetNumPixels(); pixidx++)
+    {
+      *fLog << all
+            << "Pixel: " << Form("%3i",pixidx)
+            << "  CalibConst: " << Form("%4.2f",fCalibConsts[pixidx])
+            << "  F-Factor: "   << Form("%4.2f",fCalibFFactors[pixidx])
+            << "  HiLoConv: "   << Form("%4.2f",fHiLoConv[pixidx])
+            << endl;
+    }
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrateData.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrateData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrateData.h	(revision 17960)
@@ -0,0 +1,123 @@
+#ifndef MARS_MCalibrateData
+#define MARS_MCalibrateData
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+class MPedestalCam;
+class MPedPhotCam;
+class MSignalCam;
+class MCalibConstCam;
+class MExtractedSignalCam;
+
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+
+class MCalibrateData : public MTask
+{
+public:
+    enum CalibrationMode_t
+    {
+        kSkip       =  0,
+        kNone       =  1,
+        kFlatCharge =  2,
+        kBlindPixel =  3,
+        kFfactor    =  4,
+        kPinDiode   =  5,
+        kCombined   =  6,
+        kDummy      =  7
+    };
+
+    enum PedestalType_t
+    {
+        kNo    = BIT(0),
+        kRun   = BIT(1),
+        kEvent = BIT(2)
+    };
+
+    enum SignalType_t
+    {
+        kPhe,
+        kPhot
+    };
+
+    static const CalibrationMode_t gkDefault;
+
+private:
+  static const Float_t gkCalibConvMinLimit; //! Minimum limit for conv. factor
+  static const Float_t gkCalibConvMaxLimit; //! Maximum limit for conv. factor
+
+  Float_t  fCalibConvMinLimit;           // Minimum limit for conv. factor
+  Float_t  fCalibConvMaxLimit;           // Maximum limit for conv. factor
+    
+  MGeomCam                       *fGeomCam;       //! Camera geometry container
+  MBadPixelsCam                  *fBadPixels;     //! Bad Pixels information
+  MCalibrationChargeCam          *fCalibrations;  //! Calibration constants
+  MCalibrationQECam              *fQEs;           //! Quantum efficiencies
+  MExtractedSignalCam            *fSignals;       //! Integrated charge in FADCs counts
+  MSignalCam                     *fCerPhotEvt;    //! Cerenkov Photon Event used for calculation
+  MCalibConstCam                 *fCalibConstCam; //! Temporary calib consts storage
+  
+  CalibrationMode_t fCalibrationMode;    // Flag defining the calibration mode (CalibrationMode_t)
+  Byte_t   fPedestalFlag;                // Flags defining to calibrate the pedestal each event or each run
+  Byte_t   fSignalType;                  // Flag defining the signal type (kphot or kphe)
+  
+  Float_t  fRenormFactor;                // Possible renormalization factor for signals (-> phes)
+  Float_t  fScaleFactor;                 // Possible scale factor for signals
+
+  TString  fFileNameScale;               // File name for list of scale factors
+
+  TList   fNamesPedestal;                // Names of input and output pedestal conatainer
+  TList   fPedestalCams;                 //! List of pointers to input MPedestalCam
+  TList   fPedPhotCams;                  //! List of pointers to corresponding output MPedPhotCam
+
+  MArrayF fCalibConsts;                  //! Array of calibration constants for each pixel, calculated only once!
+  MArrayF fCalibFFactors;                //! Array of calibration F-Factors for each pixel, calculated only once!  
+  MArrayF fHiLoConv;                     //! Array of calibration constants for each pixel, calculated only once!
+  MArrayF fHiLoConvErr;                  //! Array of calibration F-Factors for each pixel, calculated only once!  
+
+  Int_t  Calibrate(Bool_t data, Bool_t pedestal) const;
+
+  Int_t  PreProcess(MParList *pList);
+  Bool_t ReInit(MParList *pList);
+  Int_t  Process();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  void   StreamPrimitive(std::ostream &out) const;
+
+public:
+    MCalibrateData(CalibrationMode_t calmode=gkDefault,
+                   const char *name=NULL, const char *title=NULL);
+
+  void   AddPedestal(const char *name="Cam");
+  void   AddPedestal(const char *pedestal, const char *pedphot);
+
+  void   EnablePedestalType(PedestalType_t i)     { fPedestalFlag |=  i;      }
+
+  //Int_t  GetSize() const { return fCalibConsts.GetSize(); }
+
+  void   Print(Option_t *o="") const;
+
+  void   SetPedestalFlag(PedestalType_t i=kRun)   { fPedestalFlag  =  i;      }
+  Bool_t TestPedestalFlag(PedestalType_t i) const { return fPedestalFlag&i ? kTRUE : kFALSE; }
+  
+  void   SetCalibrationMode ( CalibrationMode_t calmode=gkDefault) { fCalibrationMode=calmode; }
+  void   SetSignalType      ( SignalType_t      sigtype=kPhe    ) { fSignalType     =sigtype; }  
+
+  void   SetCalibConvMinLimit( const Float_t f=gkCalibConvMinLimit ) { fCalibConvMinLimit = f; }
+  void   SetCalibConvMaxLimit( const Float_t f=gkCalibConvMaxLimit ) { fCalibConvMaxLimit = f; }
+
+  void   SetScaleFactor(const Float_t f=1) { fScaleFactor=f; }
+
+  Bool_t UpdateConversionFactors( const MCalibrationChargeCam *updatecam=NULL);
+
+  ClassDef(MCalibrateData, 1)   // Task to calibrate FADC counts into photons or photo-electrons
+};
+
+#endif   /* MCalibrateData */
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrateFact.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrateFact.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrateFact.cc	(revision 17960)
@@ -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 10/2002 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalibrateFact
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateFact.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MSignalCam.h"
+#include "MBadPixelsCam.h"
+#include "MExtractedSignalPix.h"
+#include "MExtractedSignalCam.h"
+
+ClassImp(MCalibrateFact);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCalibrateFact::MCalibrateFact(const char *name, const char *title)
+    : fIn(0), fOut(0), fBadPixels(0),
+    fNameExtractedSignalCam("MExtractedSignalCam"),
+    fNameSignalCam("MSignalCam"),
+    fScale(1)
+{
+    fName  = name  ? name  : "MCalibrateFact";
+    fTitle = title ? title : "";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete the filter if it was created automatically
+//
+MCalibrateFact::~MCalibrateFact()
+{
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MCalibrateFact::PreProcess(MParList *plist)
+{
+    fIn = (MExtractedSignalCam*)plist->FindObject(fNameExtractedSignalCam, "MExtractedSignalCam");
+    if (!fIn)
+    {
+        *fLog << err << fNameExtractedSignalCam << " [MExtractedSignalCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fBadPixels = (MBadPixelsCam*)plist->FindCreateObj("MBadPixelsCam");
+    if (!fBadPixels)
+        return kFALSE;
+
+    fOut = (MSignalCam*)plist->FindCreateObj("MSignalCam", fNameSignalCam);
+    if (!fOut)
+        return kFALSE;
+
+    if (fScale!=1)
+        *fLog << inf << "Using additional scale factor of " << fScale << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MCalibrateFact::ReInit(MParList *plist)
+{
+    if (fCalibConst.GetSize()==0)
+    {
+        fCalibConst.Set(fIn->GetSize());
+        fCalibConst.Reset(1);
+    }
+
+    if (UInt_t(fIn->GetSize()) != fCalibConst.GetSize())
+    {
+        *fLog << err << "Size mismatch." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Int_t MCalibrateFact::Process()
+{
+    const UInt_t npix = fIn->GetSize();
+
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        const MExtractedSignalPix &sig = (*fIn)[idx];
+
+        const Double_t signal = sig.GetExtractedSignalHiGain();
+        const Bool_t   ok     = /*!sig.IsHiGainSaturated() &&*/ sig.IsHiGainValid();
+
+        const Double_t nphot = signal * fCalibConst[idx] * fScale;
+        fOut->AddPixel(idx, nphot, 0);
+
+        if (!ok)
+            (*fBadPixels)[idx].SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+
+        /*
+        if (!ok)
+        {
+            if (sig.IsHiGainSaturated())
+                numsathi++;
+
+            if (sig.IsLoGainSaturated())
+                numsatlo++;
+        }*/
+    }
+
+    //fOut->SetNumPixelsSaturated(numsathi, numsatlo);
+    //fOut->SetReadyToSave();
+
+    return kTRUE;
+
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrateFact.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrateFact.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrateFact.h	(revision 17960)
@@ -0,0 +1,48 @@
+#ifndef MARS_MCalibrateFact
+#define MARS_MCalibrateFact
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MSignalCam;
+class MBadPixelsCam;
+class MExtractedSignalCam;
+
+class MCalibrateFact : public MTask
+{
+private:
+    MExtractedSignalCam *fIn;
+    MSignalCam          *fOut;
+
+    MBadPixelsCam       *fBadPixels;
+
+    TString fNameExtractedSignalCam;
+    TString fNameSignalCam;
+
+    MArrayD fCalibConst;
+
+    Double_t fScale;
+
+    // MTask
+    Int_t  PreProcess(MParList *list);
+    Bool_t ReInit(MParList *list);
+    Int_t  Process();
+    //Int_t  PostProcess();
+
+public:
+    MCalibrateFact(const char *name=NULL, const char *title=NULL);
+    ~MCalibrateFact();
+
+    // MCalibrateFact
+    void SetCalibConst(const MArrayD &arr) { fCalibConst=arr; }
+    void SetScale(const Double_t &val) { fScale=val; }
+
+    ClassDef(MCalibrateFact, 0) //
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrateRelTimes.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrateRelTimes.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrateRelTimes.cc	(revision 17960)
@@ -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): Markus Gaug  04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrateRelTimes
+//
+//   This task takes the extracted arrival times from MArrivalTimeCam for each  
+//   pixel and applies the offset calibrated in MCalibrationRelTimeCam 
+//   The calibrated arrival time and its error gets stored in MSignalCam. 
+//
+//   Input Containers:
+//    MArrivalTimeCam 
+//    MCalibrationRelTimeCam
+//
+//   Output Containers:
+//    MSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateRelTimes.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimePix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MRawRunHeader.h"
+
+ClassImp(MCalibrateRelTimes);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrateRelTimes::MCalibrateRelTimes(const char *name, const char *title) 
+    : 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
+//
+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 ... ignoring." << endl;
+
+    fCalibrations = (MCalibrationRelTimeCam*)pList->FindObject(AddSerialNumber("MCalibrationRelTimeCam"));
+    if (!fCalibrations)
+    {
+        *fLog << err << AddSerialNumber("MCalibrationRelTimeCam") << " not found ... aborting." << endl;
+        return kFALSE;
+    }
+
+    fArrivalTime = (MSignalCam*)pList->FindCreateObj(AddSerialNumber("MSignalCam"));
+    if (!fArrivalTime)
+        return kFALSE;
+    
+    return kTRUE;
+}
+
+Bool_t MCalibrateRelTimes::ReInit(MParList *pList)
+{
+    MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!runheader)
+    {
+        *fLog << err << AddSerialNumber("MRawRunHeader") << " not found ... aborting." << endl;
+        return kFALSE;
+    }
+
+    fFreq = runheader->GetFreqSampling();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the calibration factors to the extracted signal according to the 
+// selected calibration method
+//
+Int_t MCalibrateRelTimes::Process()
+{
+    const UInt_t npix = fSignals->GetSize();
+
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        if (fBadPixels && (*fBadPixels)[idx].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            continue;
+
+        const MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*fCalibrations)[idx];
+        const MArrivalTimePix        &sig = (*fSignals)[idx];
+
+        const Float_t signal = sig.GetArrivalTime();
+        const Float_t offset = pix.GetTimeOffset();
+
+        // convert from slices to ns
+        const Float_t time = 1000*(signal-offset)/fFreq; // [ns]
+
+        (*fArrivalTime)[idx].SetArrivalTime(time);
+
+        // FIXME: Is this necessary or explicitly done by the signal-
+        // extractor (may depend on the fact whether independent
+        // extractor are or can be used for signal and arrival time)
+        if (fBadPixels && !sig.IsArrivalTimeValid())
+            (*fBadPixels)[idx].SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+    }
+
+    fArrivalTime->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrateRelTimes.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrateRelTimes.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrateRelTimes.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MCalibrateRelTimes
+#define MARS_MCalibrateRelTimes
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+class MCalibrationRelTimeCam;
+class MArrivalTimeCam;
+class MRawRunHeader;
+class MSignalCam;
+
+class MCalibrateRelTimes : public MTask
+{
+private:
+    MCalibrationRelTimeCam *fCalibrations; // Calibration rel. time constants
+    MBadPixelsCam          *fBadPixels;    // Bad Pixels information
+    MArrivalTimeCam        *fSignals;      // Extracted Arrival Time
+    MSignalCam             *fArrivalTime;  // Calibrated arrival times
+
+    UShort_t fFreq;                        //! [MHz] Sampling Frequency
+
+    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: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCam.cc	(revision 17960)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCam                                               
+//                                                               
+// Base class for Blind Pixels Calibration results. Derived classes intialize
+// the actual values of the MCalibrationBlindPix's. 
+//
+// Contains TOrdCollections for the following objects:
+// - fPixels:    Array of classes derived from MCalibrationBlindPix, one entry 
+//               per blind pixel. 
+//
+// All TOrdCollections have to enlarged by the corresponding calls to (e.g. in MGeomApply): 
+// - InitSize()
+//
+// See also: MCalibrationBlindCamOneOldStyle, MCalibrationBlindCamTwoNewStyle
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationBlindPix.h"
+
+#include <TOrdCollection.h>
+
+#include "MLogManip.h"
+
+ClassImp(MCalibrationBlindCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationBlindCam::MCalibrationBlindCam(Int_t nblind,const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationBlindCam";
+  fTitle = title ? title : "Calibration Information of blinded pixels in camera";
+
+  InitSize(nblind);
+
+}
+
+void MCalibrationBlindCam::Add(const UInt_t a, const UInt_t b)
+{
+
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationBlindPix,i);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Return true, if any of the blind pixels have an available photon flux
+//
+Bool_t MCalibrationBlindCam::IsFluxInsidePlexiglassAvailable() const
+{
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];      
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        return kTRUE;
+    }
+  
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns weighted average of the flux calculated by each blind pixel
+//
+Float_t MCalibrationBlindCam::GetFluxInsidePlexiglass() const
+{
+
+  Float_t flux    = 0.;
+  Float_t fluxvar = 0.;  
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        {
+          const Float_t weight = 1./ 
+                                bp.GetFluxInsidePlexiglassErr() 
+                                / bp.GetFluxInsidePlexiglassErr();
+          flux    += weight * bp.GetFluxInsidePlexiglass();
+          fluxvar += weight;
+        }
+    }
+  return fluxvar > 0.0001 ? flux / fluxvar : -1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns weighted variance of the flux calculated by each blind pixel
+//
+Float_t MCalibrationBlindCam::GetFluxInsidePlexiglassVar() const
+{
+
+  Float_t fluxvar = 0.;  
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        {
+          const Float_t weight = 1./ 
+                                bp.GetFluxInsidePlexiglassErr() 
+                                / bp.GetFluxInsidePlexiglassErr();
+          fluxvar += weight;
+        }
+    }
+  return fluxvar > 0.0001 ? 1. / fluxvar : -1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns weighted rel. variance of the flux calculated by each blind pixel
+//
+Float_t MCalibrationBlindCam::GetFluxInsidePlexiglassRelVar() const
+{
+
+  Float_t flux    = 0.;
+  Float_t fluxvar = 0.;  
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        {
+          const Float_t weight = 1./ 
+                                bp.GetFluxInsidePlexiglassErr() 
+                                / bp.GetFluxInsidePlexiglassErr();
+          flux    += weight * bp.GetFluxInsidePlexiglass();
+          fluxvar += weight;
+        }
+    }
+
+  return fluxvar > 0.0001 ? flux * fluxvar : -1.;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set color to this class and to the MCalibrationBlindPix's
+//
+void  MCalibrationBlindCam::SetPulserColor ( const MCalibrationCam::PulserColor_t col )
+{
+
+  fPulserColor = col;
+  fPixels->R__FOR_EACH(MCalibrationBlindPix, SetColor)(col);
+
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCam.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MCalibrationBlindCam
+#define MARS_MCalibrationBlindCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationBlindCam : public MCalibrationCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+
+public:
+  MCalibrationBlindCam(Int_t nblind=1,const char *name=NULL, const char *title=NULL);
+  
+  // Inits
+  void  Init ( const MGeomCam &geom ) {}
+
+  // Getter
+  Bool_t IsFluxInsidePlexiglassAvailable () const;
+
+  Float_t GetFluxInsidePlexiglass    () const;
+  Float_t GetFluxInsidePlexiglassVar () const;
+  Float_t GetFluxInsidePlexiglassRelVar() const;
+
+  // Setter
+  void  SetPulserColor( const MCalibrationCam::PulserColor_t col );
+  
+  ClassDef(MCalibrationBlindCam, 2) // Container Blind Pixels Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamOneOldStyle.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamOneOldStyle.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamOneOldStyle.cc	(revision 17960)
@@ -0,0 +1,176 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCamOneOldStyle                                               
+//                                                               
+// Blind Pixels Calibration camera until run 31693. The blind pixel camera 
+// consisted then only of one non-coated blind pixel with poorly known 
+// quantum efficiency read out in hardware ID 560.
+//
+// See also: MCalibrationBlindCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCamOneOldStyle.h"
+#include "MCalibrationBlindPix.h"
+
+ClassImp(MCalibrationBlindCamOneOldStyle);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - CreatePixs();
+// - CreateAreas();   
+// - CreateAtts();   
+// - CreateQEs();     
+// - CreateCollEffs();
+//
+MCalibrationBlindCamOneOldStyle::MCalibrationBlindCamOneOldStyle(const char *name)
+    : MCalibrationBlindCam(1,name,"One Blind Pixel in camera - old style")
+{
+
+  CreatePixs    ();    
+  CreateAreas   ();   
+  CreateAtts    ();   
+  CreateQEs     ();     
+  CreateCollEffs();
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Only one blind pixel with ID 559
+//
+void MCalibrationBlindCamOneOldStyle::CreatePixs() 
+{
+
+  (*this)[0].SetPixId(559);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Only one blind pixel with exactly 100 mm^2 area
+//
+void MCalibrationBlindCamOneOldStyle::CreateAreas() 
+{
+  
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+  pix.SetArea(100.);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known qe's: average of David measurments with 
+// 4% error.
+//
+void MCalibrationBlindCamOneOldStyle::CreateQEs() 
+{
+  
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+
+  Float_t qe[4];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.154;
+  qe[    MCalibrationCam::kBLUE  ] = 0.226;
+  qe[    MCalibrationCam::kUV    ] = 0.247;
+  qe[    MCalibrationCam::kCT1   ] = 0.247;
+
+  pix.SetQE(4,qe);  
+
+  Float_t qeerr[4];
+
+  qeerr[ MCalibrationCam::kGREEN ] = 0.005;
+  qeerr[ MCalibrationCam::kBLUE  ] = 0.007;
+  qeerr[ MCalibrationCam::kUV    ] = 0.01;
+  qeerr[ MCalibrationCam::kCT1   ] = 0.01;
+
+  pix.SetQEErr(4,qeerr);  
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known coll.eff's: email from Eckart with 
+// estimates depending on colour, but 5% error (maybe more??)
+//
+void MCalibrationBlindCamOneOldStyle::CreateCollEffs() 
+{
+
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+
+  Float_t colleff[4];
+
+  colleff[MCalibrationCam::kGREEN ] = 0.99;
+  colleff[MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[MCalibrationCam::kUV    ] = 0.90;
+  colleff[MCalibrationCam::kCT1   ] = 0.90;
+
+  pix.SetCollEff(4,colleff);  
+
+  Float_t collefferr[4];
+
+  collefferr[MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[MCalibrationCam::kUV    ] = 0.05;
+  collefferr[MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix.SetCollEffErr(4,collefferr);  
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with very well known attenuation 0.01 (datasheet delivered 
+// with filter, precision better than 1%
+//
+void MCalibrationBlindCamOneOldStyle::CreateAtts() 
+{
+
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+
+  Float_t att[4];
+
+  att[MCalibrationCam::kGREEN ] = 1.97;
+  att[MCalibrationCam::kBLUE  ] = 1.96;
+  att[MCalibrationCam::kUV    ] = 1.95;
+  att[MCalibrationCam::kCT1   ] = 1.95;
+
+  pix.SetAtt(4,att);
+
+  Float_t atterr[4];
+
+  atterr[MCalibrationCam::kGREEN ] = 0.01;
+  atterr[MCalibrationCam::kBLUE  ] = 0.01;
+  atterr[MCalibrationCam::kUV    ] = 0.01;
+  atterr[MCalibrationCam::kCT1   ] = 0.01;
+  
+  pix.SetAttErr(4,atterr);
+
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamOneOldStyle.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamOneOldStyle.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamOneOldStyle.h	(revision 17960)
@@ -0,0 +1,25 @@
+#ifndef MARS_MCalibrationBlindCamOneOldStyle
+#define MARS_MCalibrationBlindCamOneOldStyle
+
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+
+class MCalibrationBlindCamOneOldStyle : public MCalibrationBlindCam
+{
+private:
+
+  void CreatePixs();
+  void CreateAreas();
+  void CreateAtts();
+  void CreateQEs();
+  void CreateCollEffs();
+  
+public:
+
+  MCalibrationBlindCamOneOldStyle(const char *name=NULL);
+  
+  ClassDef(MCalibrationBlindCamOneOldStyle, 1) // Container Blind Pixel Calibration Results - until run 31693
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamThreeNewStyle.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamThreeNewStyle.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamThreeNewStyle.cc	(revision 17960)
@@ -0,0 +1,284 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCamThreeNewStyle                                               
+//                                                               
+// Blind Pixels Calibration camera after run 43308. The blind pixel camera 
+// consisted then of three non-coated blind pixels with very well known 
+// quantum efficiency read out in hardware ID 0,1 and 2 (stored in MRawEvtData2).
+//
+// See also: MCalibrationBlindCam, MHCalibrationChargeBlindCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCamThreeNewStyle.h"
+#include "MCalibrationBlindPix.h"
+
+ClassImp(MCalibrationBlindCamThreeNewStyle);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - CreatePixs();
+// - CreateAreas();   
+// - CreateAtts();   
+// - CreateQEs();     
+// - CreateCollEffs();
+//
+MCalibrationBlindCamThreeNewStyle::MCalibrationBlindCamThreeNewStyle(const char *name)
+    : MCalibrationBlindCam(3,name,"Three Blind Pixels in camera - new style")
+{
+  CreatePixs    ();    
+  CreateAreas   ();   
+  CreateAtts    ();   
+  CreateQEs     ();     
+  CreateCollEffs();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Three blind pixels with ID 0,1 and 2 (software)
+//
+void MCalibrationBlindCamThreeNewStyle::CreatePixs() 
+{
+
+  (*this)[0].SetPixId(0);
+  (*this)[1].SetPixId(1);
+  (*this)[2].SetPixId(2);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Three blind pixels with exactly 100 mm^2 area
+//
+void MCalibrationBlindCamThreeNewStyle::CreateAreas() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];
+  pix0.SetArea(100.);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  pix1.SetArea(100.);
+
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];
+  pix2.SetArea   (0.196);
+  pix2.SetAreaErr(0.008);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Three blind pixels with very well known qe's: David's measurments with 
+// 1% error.
+//
+void MCalibrationBlindCamThreeNewStyle::CreateQEs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t qe[4];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.166;
+  qe[    MCalibrationCam::kBLUE  ] = 0.240;
+  qe[    MCalibrationCam::kUV    ] = 0.273;
+  qe[    MCalibrationCam::kCT1   ] = 0.273;
+
+  pix0.SetQE(4,qe);  
+
+  Float_t qeerr[4];
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix0.SetQEErr(4,qeerr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.155;
+  qe[    MCalibrationCam::kBLUE  ] = 0.228;
+  qe[    MCalibrationCam::kUV    ] = 0.261;
+  qe[    MCalibrationCam::kCT1   ] = 0.261;
+
+  pix1.SetQE(4,qe);  
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix1.SetQEErr(4,qeerr);  
+
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.160;
+  qe[    MCalibrationCam::kBLUE  ] = 0.235;
+  qe[    MCalibrationCam::kUV    ] = 0.264;
+  qe[    MCalibrationCam::kCT1   ] = 0.264;
+
+  pix2.SetQE(4,qe);  
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix2.SetQEErr(4,qeerr);  
+
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known coll.eff's: email from Eckart with 
+// estimates depending on colour, but 5% error (maybe more??)
+//
+void MCalibrationBlindCamThreeNewStyle::CreateCollEffs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t colleff[4];
+
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix0.SetCollEff(4,colleff);  
+
+  Float_t collefferr[4];
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+
+  pix0.SetCollEffErr(4,collefferr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix1.SetCollEff(4,colleff);  
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix1.SetCollEffErr(4,collefferr);    
+
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];
+  
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix2.SetCollEff(4,colleff);  
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix2.SetCollEffErr(4,collefferr);    
+
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel has a very well known attenuation 0.01 (datasheet delivered 
+// with filter, precision better than 1%
+//
+// The second blind pixel is not yet so well known, the company does not reply.
+// Attenuation: 0.001 (datasheet not delivered with filter, precision guaranteed to 5%)
+//
+void MCalibrationBlindCamThreeNewStyle::CreateAtts() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t att[4];
+
+  att[MCalibrationCam::kGREEN ] = 1.97;
+  att[MCalibrationCam::kBLUE  ] = 1.96;
+  att[MCalibrationCam::kUV    ] = 1.95;
+  att[MCalibrationCam::kCT1   ] = 1.95;
+
+  pix0.SetAtt(4,att);
+
+  Float_t atterr[4];
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.01;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.01;
+  atterr[    MCalibrationCam::kUV    ] = 0.01;
+  atterr[    MCalibrationCam::kCT1   ] = 0.01;
+
+  pix0.SetAttErr(4,atterr);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];  
+
+  att[MCalibrationCam::kGREEN ] = 3.00;
+  att[MCalibrationCam::kBLUE  ] = 3.00;
+  att[MCalibrationCam::kUV    ] = 3.00;
+  att[MCalibrationCam::kCT1   ] = 3.00;
+
+  pix1.SetAtt(4,att);
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.15;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.15;
+  atterr[    MCalibrationCam::kUV    ] = 0.15;
+  atterr[    MCalibrationCam::kCT1   ] = 0.15;
+
+  pix1.SetAttErr(4,atterr);
+  
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];  
+
+  att[MCalibrationCam::kGREEN ] = 0.;
+  att[MCalibrationCam::kBLUE  ] = 0.;
+  att[MCalibrationCam::kUV    ] = 0.; 
+  att[MCalibrationCam::kCT1   ] = 0.;
+
+  pix2.SetAtt(4,att);
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.;
+  atterr[    MCalibrationCam::kUV    ] = 0.;
+  atterr[    MCalibrationCam::kCT1   ] = 0.;
+
+  pix2.SetAttErr(4,atterr);
+  
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamThreeNewStyle.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamThreeNewStyle.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamThreeNewStyle.h	(revision 17960)
@@ -0,0 +1,25 @@
+#ifndef MARS_MCalibrationBlindCamThreeNewStyle
+#define MARS_MCalibrationBlindCamThreeNewStyle
+
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+
+class MCalibrationBlindCamThreeNewStyle : public MCalibrationBlindCam
+{
+private:
+
+  void CreatePixs();
+  void CreateAreas();
+  void CreateAtts();
+  void CreateQEs();
+  void CreateCollEffs();
+  
+public:
+
+  MCalibrationBlindCamThreeNewStyle(const char *name=NULL);
+
+  ClassDef(MCalibrationBlindCamThreeNewStyle, 1) // Container Blind Pixel Calibration Results - after run 43307
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamTwoNewStyle.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamTwoNewStyle.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamTwoNewStyle.cc	(revision 17960)
@@ -0,0 +1,230 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCamTwoNewStyle                                               
+//                                                               
+// Blind Pixels Calibration camera after run 31693. The blind pixel camera 
+// consisted then of two non-coated blind pixel with very well known 
+// quantum efficiency read out in hardware ID 560 and 561.
+//
+// See also: MCalibrationBlindCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCamTwoNewStyle.h"
+#include "MCalibrationBlindPix.h"
+
+ClassImp(MCalibrationBlindCamTwoNewStyle);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - CreatePixs();
+// - CreateAreas();   
+// - CreateAtts();   
+// - CreateQEs();     
+// - CreateCollEffs();
+//
+MCalibrationBlindCamTwoNewStyle::MCalibrationBlindCamTwoNewStyle(const char *name)
+    : MCalibrationBlindCam(2,name,"Two Blind Pixels in camera - new style")
+{
+  CreatePixs    ();    
+  CreateAreas   ();   
+  CreateAtts    ();   
+  CreateQEs     ();     
+  CreateCollEffs();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Two blind pixels with ID 559 and 560 (software)
+//
+void MCalibrationBlindCamTwoNewStyle::CreatePixs() 
+{
+
+  (*this)[0].SetPixId(559);
+  (*this)[1].SetPixId(560);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Two blind pixels with exactly 100 mm^2 area
+//
+void MCalibrationBlindCamTwoNewStyle::CreateAreas() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];
+  pix0.SetArea(100.);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  pix1.SetArea(100.);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Two blind pixels with very well known qe's: David's measurments with 
+// 1% error.
+//
+void MCalibrationBlindCamTwoNewStyle::CreateQEs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t qe[4];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.166;
+  qe[    MCalibrationCam::kBLUE  ] = 0.240;
+  qe[    MCalibrationCam::kUV    ] = 0.273;
+  qe[    MCalibrationCam::kCT1   ] = 0.273;
+
+  pix0.SetQE(4,qe);  
+
+  Float_t qeerr[4];
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix0.SetQEErr(4,qeerr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.155;
+  qe[    MCalibrationCam::kBLUE  ] = 0.228;
+  qe[    MCalibrationCam::kUV    ] = 0.261;
+  qe[    MCalibrationCam::kCT1   ] = 0.261;
+
+  pix1.SetQE(4,qe);  
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix1.SetQEErr(4,qeerr);  
+
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known coll.eff's: email from Eckart with 
+// estimates depending on colour, but 5% error (maybe more??)
+//
+void MCalibrationBlindCamTwoNewStyle::CreateCollEffs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t colleff[4];
+
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix0.SetCollEff(4,colleff);  
+
+  Float_t collefferr[4];
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+
+  pix0.SetCollEffErr(4,collefferr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix1.SetCollEff(4,colleff);  
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix1.SetCollEffErr(4,collefferr);    
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel has a very well known attenuation 0.01 (datasheet delivered 
+// with filter, precision better than 1%
+//
+// The second blind pixel is not yet so well known, the company does not reply.
+// Attenuation: 0.001 (datasheet not delivered with filter, precision guaranteed to 5%)
+//
+void MCalibrationBlindCamTwoNewStyle::CreateAtts() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t att[4];
+
+  att[MCalibrationCam::kGREEN ] = 1.97;
+  att[MCalibrationCam::kBLUE  ] = 1.96;
+  att[MCalibrationCam::kUV    ] = 1.95;
+  att[MCalibrationCam::kCT1   ] = 1.95;
+
+  pix0.SetAtt(4,att);
+
+  Float_t atterr[4];
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.01;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.01;
+  atterr[    MCalibrationCam::kUV    ] = 0.01;
+  atterr[    MCalibrationCam::kCT1   ] = 0.01;
+
+  pix0.SetAttErr(4,atterr);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];  
+
+  att[MCalibrationCam::kGREEN ] = 3.00;
+  att[MCalibrationCam::kBLUE  ] = 3.00;
+  att[MCalibrationCam::kUV    ] = 3.00;
+  att[MCalibrationCam::kCT1   ] = 3.00;
+
+  pix1.SetAtt(4,att);
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.15;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.15;
+  atterr[    MCalibrationCam::kUV    ] = 0.15;
+  atterr[    MCalibrationCam::kCT1   ] = 0.15;
+
+  pix1.SetAttErr(4,atterr);
+  
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamTwoNewStyle.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamTwoNewStyle.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindCamTwoNewStyle.h	(revision 17960)
@@ -0,0 +1,25 @@
+#ifndef MARS_MCalibrationBlindCamTwoNewStyle
+#define MARS_MCalibrationBlindCamTwoNewStyle
+
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+
+class MCalibrationBlindCamTwoNewStyle : public MCalibrationBlindCam
+{
+private:
+
+  void CreatePixs();
+  void CreateAreas();
+  void CreateAtts();
+  void CreateQEs();
+  void CreateCollEffs();
+  
+public:
+
+  MCalibrationBlindCamTwoNewStyle(const char *name=NULL);
+
+  ClassDef(MCalibrationBlindCamTwoNewStyle, 1) // Container Blind Pixel Calibration Results - after run 31693
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindPix.cc	(revision 17960)
@@ -0,0 +1,553 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                               
+// MCalibrationBlindPix    
+//
+// Storage container of the fit results of the Blind Pixel signal 
+// (from MHCalibrationChargeBlindPix). 
+//
+// The Flux is calculated in photons per mm^2 in the camera plane. 
+//
+// Currently, the following numbers are implemented:
+// - fArea: 100 mm^2
+// - Average QE of Blind Pixel: 
+//    fQEGreen: 0.154
+//    fQEBlue : 0.226
+//    fQEUV   : 0.247
+//    fQECT1  : 0.247
+// - Average QE Error of Blind Pixel: 
+//    fQEGreenErr: 0.015;
+//    fQEBlueErr : 0.02;
+//    fQEUVErr   : 0.02;
+//    fQECT1Err  : 0.02;
+// - Attenuation factor Blind Pixel:
+//    fAttGreen :  1.97;
+//    fAttBlue  :  1.96;
+//    fAttUV    :  1.95;
+//    fAttCT1   :  1.95;
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindPix.h"
+
+#include <TMath.h>
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationBlindPix);
+
+using namespace std;
+
+const Float_t MCalibrationBlindPix::fgArea       = 100;
+const Float_t MCalibrationBlindPix::fgAttGreen   = 1.97;
+const Float_t MCalibrationBlindPix::fgAttBlue    = 1.96;
+const Float_t MCalibrationBlindPix::fgAttUV      = 1.95;
+const Float_t MCalibrationBlindPix::fgAttCT1     = 1.95;
+const Float_t MCalibrationBlindPix::fgAttErr     = 0.01;
+const Float_t MCalibrationBlindPix::fgQEGreen    = 0.154;
+const Float_t MCalibrationBlindPix::fgQEBlue     = 0.226;
+const Float_t MCalibrationBlindPix::fgQEUV       = 0.247;
+const Float_t MCalibrationBlindPix::fgQECT1      = 0.247;
+const Float_t MCalibrationBlindPix::fgQEErrGreen = 0.005;
+const Float_t MCalibrationBlindPix::fgQEErrBlue  = 0.007;
+const Float_t MCalibrationBlindPix::fgQEErrUV    = 0.01;
+const Float_t MCalibrationBlindPix::fgQEErrCT1   = 0.01;
+const Float_t MCalibrationBlindPix::fgCollEffGreen = 0.99; 
+const Float_t MCalibrationBlindPix::fgCollEffBlue  = 0.93; 
+const Float_t MCalibrationBlindPix::fgCollEffUV    = 0.90; 
+const Float_t MCalibrationBlindPix::fgCollEffCT1   = 0.90; 
+const Float_t MCalibrationBlindPix::fgCollEffErr   = 0.05; 
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Calls:
+// - Clear()
+//
+// For backward-compatibility reasons, quantum eff., coll. eff. and att. 
+// are intialized from the static members. This should, however, be 
+// overwritten by a class deriving from MCalibrationBlindCam. 
+//
+MCalibrationBlindPix::MCalibrationBlindPix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationBlindPix";
+  fTitle = title ? title : "Container of the fit results of the blind pixel";
+
+  Clear();
+
+  fArea = fgArea;
+  fAreaErr = 0.;
+
+  Float_t att[MCalibrationCam::gkNumPulserColors];
+
+  att [ MCalibrationCam::kGREEN ] = fgAttGreen; 
+  att [ MCalibrationCam::kBLUE  ] = fgAttBlue; 
+  att [ MCalibrationCam::kUV    ] = fgAttUV; 
+  att [ MCalibrationCam::kCT1   ] = fgAttCT1; 
+
+  SetAtt(MCalibrationCam::gkNumPulserColors,att);
+
+  Float_t atterr[MCalibrationCam::gkNumPulserColors];
+
+  atterr [ MCalibrationCam::kGREEN ] = fgAttErr; 
+  atterr [ MCalibrationCam::kBLUE  ] = fgAttErr; 
+  atterr [ MCalibrationCam::kUV    ] = fgAttErr; 
+  atterr [ MCalibrationCam::kCT1   ] = fgAttErr; 
+  
+  SetAttErr(MCalibrationCam::gkNumPulserColors,atterr);
+
+  Float_t qe[MCalibrationCam::gkNumPulserColors];
+
+  qe [ MCalibrationCam::kGREEN ] = fgQEGreen; 
+  qe [ MCalibrationCam::kBLUE  ] = fgQEBlue; 
+  qe [ MCalibrationCam::kUV    ] = fgQEUV; 
+  qe [ MCalibrationCam::kCT1   ] = fgQECT1; 
+
+  SetQE(MCalibrationCam::gkNumPulserColors,qe);  
+
+  Float_t qeerr[MCalibrationCam::gkNumPulserColors];
+
+  qeerr [ MCalibrationCam::kGREEN ] = fgQEErrGreen; 
+  qeerr [ MCalibrationCam::kBLUE  ] = fgQEErrBlue; 
+  qeerr [ MCalibrationCam::kUV    ] = fgQEErrUV; 
+  qeerr [ MCalibrationCam::kCT1   ] = fgQEErrCT1; 
+
+  SetQEErr(MCalibrationCam::gkNumPulserColors,qeerr);  
+
+  Float_t colleff[MCalibrationCam::gkNumPulserColors];
+
+  colleff [ MCalibrationCam::kGREEN ] = fgCollEffGreen; 
+  colleff [ MCalibrationCam::kBLUE  ] = fgCollEffBlue; 
+  colleff [ MCalibrationCam::kUV    ] = fgCollEffUV; 
+  colleff [ MCalibrationCam::kCT1   ] = fgCollEffCT1; 
+
+  SetCollEff(MCalibrationCam::gkNumPulserColors,colleff);  
+
+  Float_t collefferr[MCalibrationCam::gkNumPulserColors];
+
+  collefferr [ MCalibrationCam::kGREEN ] = fgCollEffErr; 
+  collefferr [ MCalibrationCam::kBLUE  ] = fgCollEffErr; 
+  collefferr [ MCalibrationCam::kUV    ] = fgCollEffErr; 
+  collefferr [ MCalibrationCam::kCT1   ] = fgCollEffErr; 
+
+  SetCollEffErr(MCalibrationCam::gkNumPulserColors,collefferr);  
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all variables to -1.
+// - the fColor to MCalibrationCam::kNONE
+//
+// Calls: 
+// - MCalibrationPix::Clear()
+//
+void MCalibrationBlindPix::Clear(Option_t *o)
+{
+
+  fFluxInsidePlexiglass    = -1.;
+  fFluxInsidePlexiglassVar = -1.;
+  fLambda                  = -1.;
+  fLambdaCheck             = -1.;
+  fLambdaVar               = -1.;
+  fMu0                     = -1.;
+  fMu0Err                  = -1.;
+  fMu1                     = -1.;
+  fMu1Err                  = -1.;
+  fSigma0                  = -1.;
+  fSigma0Err               = -1.;
+  fSigma1                  = -1.;
+  fSigma1Err               = -1.;
+
+  SetOscillating                   ( kFALSE );
+  SetExcluded                      ( kFALSE );
+  SetChargeFitValid                ( kFALSE );
+  SetPedestalFitOK                 ( kFALSE );
+  SetSinglePheFitOK                ( kFALSE );
+  SetFluxInsidePlexiglassAvailable ( kFALSE );
+  
+  SetColor(MCalibrationCam::kNONE);
+
+  MCalibrationPix::Clear();
+}
+
+void  MCalibrationBlindPix::SetFluxInsidePlexiglassAvailable( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kFluxInsidePlexiglassAvailable) : CLRBIT(fFlags,kFluxInsidePlexiglassAvailable);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the Oscillating Bit from outside 
+//
+void  MCalibrationBlindPix::SetOscillating( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kOscillating) : CLRBIT(fFlags,kOscillating);
+}
+
+// -----------------------------------------------------
+//
+// copy 'constructor'
+//
+void MCalibrationBlindPix::Copy(TObject& object) const
+{
+
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)object;
+
+  //
+  // Copy the data members
+  //
+  pix.fPixId      = fPixId;
+  pix.fFlags      = fFlags;
+  pix.fArea       = fArea;
+  pix.fAreaErr    = fAreaErr;                     
+  pix.fColor      = fColor;
+
+  //
+  // Copy arrays
+  //
+  pix.fAtt        = fAtt;
+  pix.fAttErr     = fAttErr;
+  pix.fQE         = fQE;
+  pix.fQEErr      = fQEErr;
+  pix.fCollEff    = fCollEff;
+  pix.fCollEffErr = fCollEffErr;
+
+  pix.fLambda                  = fLambda;
+  pix.fLambdaCheck             = fLambdaCheck;
+  pix.fLambdaCheckErr          = fLambdaCheckErr;
+  pix.fLambdaVar               = fLambdaVar;
+  pix.fFluxInsidePlexiglass    = fFluxInsidePlexiglass;
+  pix.fFluxInsidePlexiglassVar = fFluxInsidePlexiglassVar;
+  pix.fMu0       = fMu0;
+  pix.fMu0Err    = fMu0Err;
+  pix.fMu1       = fMu1;
+  pix.fMu1Err    = fMu1Err;
+  pix.fSigma0    = fSigma0;
+  pix.fSigma0Err = fSigma0Err;
+  pix.fSigma1    = fSigma1;
+  pix.fSigma1Err = fSigma1Err;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the ChargeFitValid Bit from outside 
+//
+void  MCalibrationBlindPix::SetChargeFitValid( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kChargeFitValid) : CLRBIT(fFlags,kChargeFitValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the PedestalFitValid Bit from outside 
+//
+void  MCalibrationBlindPix::SetPedestalFitOK( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kPedestalFitOK) : CLRBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the SinglePheFitValid Bit from outside 
+//
+void  MCalibrationBlindPix::SetSinglePheFitOK( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kSinglePheFitOK) : CLRBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxInsidePlexiglassVar is smaller than 0.
+// Return square root of fFluxInsidePlexiglassVar
+// 
+const Float_t MCalibrationBlindPix::GetFluxInsidePlexiglassErr() const
+{
+  if (fFluxInsidePlexiglassVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fFluxInsidePlexiglassVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxInsidePlexiglassVar is smaller than 0.
+// Return -1 if fFluxInsidePlexiglass    is 0.
+// Return fFluxInsidePlexiglassVar / fFluxInsidePlexiglass^2
+// 
+const Float_t MCalibrationBlindPix::GetFluxInsidePlexiglassRelVar() const
+{
+  if (fFluxInsidePlexiglassVar < 0.)
+    return -1.;
+
+  if (fFluxInsidePlexiglass == 0.)
+    return -1.;
+  
+  return fFluxInsidePlexiglassVar / (fFluxInsidePlexiglass * fFluxInsidePlexiglass) ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fLambdaVar is smaller than 0.
+// Return square root of fLambdaVar
+// 
+const Float_t MCalibrationBlindPix::GetLambdaErr() const
+{
+  if (fLambdaVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fLambdaVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fLambdaVar is smaller than 0.
+// Return -1 if fLambda    is 0.
+// Return fLambdaVar / (fLambda * fLambda )
+// 
+const Float_t  MCalibrationBlindPix::GetLambdaRelVar() const
+{
+  if (fLambdaVar < 0.)
+    return -1.;
+  
+  if (fLambda  == 0.)
+    return -1.;
+  
+  return fLambdaVar / fLambda / fLambda ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fAreaErr^2 / (fArea^2 )
+// 
+const Float_t MCalibrationBlindPix::GetAreaRelVar() const
+{
+  return fAreaErr*fAreaErr/fArea/fArea;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return TMath::Power(10,fAtt[fColor])
+//
+const Float_t MCalibrationBlindPix::GetAtt() const
+{
+  return TMath::Power(10,fAtt[fColor]);   
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fAttErr[fColor] is smaller than 0.
+// Error of TMath::Power(10,fAtt[fColor]) = TMath::Power(10,fAtt[fColor])*ln(10.)*fAttErr[fColor]
+// Return fAttErr^2 / (fAtt^2 )
+// 
+const Float_t MCalibrationBlindPix::GetAttRelVar() const
+{
+
+  const Float_t ferr = fAttErr[fColor];
+
+  if (ferr < 0.)
+    return -1.;
+  
+  return ferr*ferr*2.3;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fQE[fColor]
+//
+const Float_t MCalibrationBlindPix::GetQE() const
+{
+  return fQE[fColor];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fQEErr[fColor] is smaller than 0.
+// Return fQEErr^2 / (fQE^2 )
+// 
+const Float_t MCalibrationBlindPix::GetQERelVar() const
+{
+
+  if (fQEErr[fColor] < 0.)
+    return -1.;
+  
+  return fQEErr[fColor]* fQEErr[fColor] / GetQE() / GetQE();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fCollEff[fColor]
+//
+const Float_t MCalibrationBlindPix::GetCollEff() const
+{
+  return fCollEff[fColor];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fCollEffErr[fColor] is smaller than 0.
+// Return fCollEffErr^2 / (fCollEff^2 )
+// 
+const Float_t MCalibrationBlindPix::GetCollEffRelVar() const
+{
+
+  if (fCollEffErr[fColor] < 0.)
+    return -1.;
+  
+  return fCollEffErr[fColor]* fCollEffErr[fColor] / GetCollEff() / GetCollEff();
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kChargeFitValid
+//
+const Bool_t MCalibrationBlindPix::IsChargeFitValid()  const 
+{
+    return TESTBIT(fFlags,kChargeFitValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kOscillating
+//
+const Bool_t MCalibrationBlindPix::IsOscillating()  const 
+{
+    return TESTBIT(fFlags,kOscillating);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kPedestalFitValid
+//
+const Bool_t MCalibrationBlindPix::IsPedestalFitOK()  const 
+{
+    return TESTBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kSinglePheFitValid
+//
+const Bool_t MCalibrationBlindPix::IsSinglePheFitOK()  const 
+{
+    return TESTBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kFluxInsidePlexiglassAvailable
+//
+const Bool_t  MCalibrationBlindPix::IsFluxInsidePlexiglassAvailable()   const
+{
+  return TESTBIT(fFlags,kFluxInsidePlexiglassAvailable);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return kFALSE if IsChargeFitValid() is kFALSE
+//
+// Calculate fFluxInsidePlexiglass with the formula:
+// - fFluxInsidePlexiglass    = fLambda 
+//                            / GetCollEff()
+//                            / GetQE() 
+//                            * GetAtt()
+//                            / fArea 
+// - fFluxInsidePlexiglassVar = sqrt( fLambdaVar / ( fLambda * fLambda ) 
+//                             + GetQERelVar() 
+//                             + GetCollEffRelVar()
+//                             + GetAttRelVar()
+//                               ) * fFluxInsidePlexiglass * * fFluxInsidePlexiglass
+//
+// If the fFluxInsidePlexiglass is smaller than 0., return kFALSE
+// If the Variance is smaller than 0., return kFALSE
+//
+// SetFluxInsidePlexiglassAvailable() and return kTRUE
+//
+Bool_t MCalibrationBlindPix::CalcFluxInsidePlexiglass()
+{
+
+  if (IsChargeFitValid())
+    return kFALSE;
+  
+
+  //
+  // Start calculation of number of photons 
+  // The blind pixel has exactly 100 mm^2 area (with negligible error), 
+  //
+  fFluxInsidePlexiglass    = fLambda / GetQE() * GetAtt() / GetCollEff() / fArea;   
+
+  if (fFluxInsidePlexiglass < 0.)
+      return kFALSE;
+
+  fFluxInsidePlexiglassVar = GetLambdaRelVar() + GetQERelVar() + GetAttRelVar() + GetCollEffRelVar() + GetAreaRelVar();
+
+  //
+  // Finish calculation of errors -> convert from relative variance to absolute variance
+  //
+  fFluxInsidePlexiglassVar *= fFluxInsidePlexiglass * fFluxInsidePlexiglass;
+
+  if (fFluxInsidePlexiglassVar < 0.)
+      return kFALSE;
+
+  SetFluxInsidePlexiglassAvailable(kTRUE);  
+
+  *fLog << inf << GetDescriptor() 
+      << ": BlindPix #" << fPixId << ": Flux [ph/mm^2] inside Plexiglass: "
+      << Form("%5.3f +- %5.3f",fFluxInsidePlexiglass, GetFluxInsidePlexiglassErr()) << endl;
+
+  return kTRUE;
+}
+
+void MCalibrationBlindPix::Print(Option_t *opt) const
+{
+  
+  *fLog << all << GetDescriptor() 
+        << Form("BlindPixel: %3i"         ,GetPixId())
+        << Form("  Lambda: %4.2f +- %4.2f",GetLambda(),GetLambdaErr())
+        << Form("  Mu0: %4.2f +- %4.2f"   ,GetMu0(),   GetMu0Err())
+        << Form("  Mu1: %4.2f +- %4.2f"   ,GetMu1(),   GetMu1Err())
+        << Form("  Sigma0: %4.2f +- %4.2f",GetSigma0(),GetSigma0Err())
+        << Form("  Sigma1: %4.2f +- %4.2f",GetSigma1(),GetSigma1Err())
+        << endl;
+  *fLog << all
+        << " Pedestal Fit OK? :" << IsPedestalFitOK() 
+        << Form("  Lambda (Check): %4.2f +- %4.2f",GetLambdaCheck(),GetLambdaCheckErr())
+        << endl;
+  *fLog << all
+        << " Flux available? :" << IsFluxInsidePlexiglassAvailable() 
+        << Form("  Flux: %4.2f +- %4.2f",GetFluxInsidePlexiglass(),GetFluxInsidePlexiglassErr())
+        << endl;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationBlindPix.h	(revision 17960)
@@ -0,0 +1,146 @@
+#ifndef MARS_MCalibrationBlindPix
+#define MARS_MCalibrationBlindPix
+
+#ifndef ROOT_MArrayF
+#include <MArrayF.h>
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationBlindPix : public MCalibrationPix
+{
+private:
+
+  static const Float_t fgArea;         //! The Blind Pixel area in mm^2
+  static const Float_t fgAttGreen;     //! Attenuation Filter at 520 nm 
+  static const Float_t fgAttBlue ;     //! Attenuation Filter at 460 nm 
+  static const Float_t fgAttUV   ;     //! Attenuation Filter at 370 nm 
+  static const Float_t fgAttCT1  ;     //! Attenuation Filter at 370 nm
+  static const Float_t fgAttErr;       //! Error Att. Filter at all w.l.
+  static const Float_t fgQEGreen;      //! Quantum Efficiency at 520 nm
+  static const Float_t fgQEBlue ;      //! Quantum Efficiency at 460 nm
+  static const Float_t fgQEUV   ;      //! Quantum Efficiency at 370 nm
+  static const Float_t fgQECT1  ;      //! Quantum Efficiency at 370 nm
+  static const Float_t fgQEErrGreen;   //! Uncertainty QEUnCoated at 520 nm 
+  static const Float_t fgQEErrBlue;    //! Uncertainty QEUnCoated at 460 nm 
+  static const Float_t fgQEErrUV   ;   //! Uncertainty QEUnCoated at 370 nm 
+  static const Float_t fgQEErrCT1  ;   //! Uncertainty QEUnCoated at 370 nmu
+  static const Float_t fgCollEffGreen; //! Collecttion Efficiency
+  static const Float_t fgCollEffBlue;  //! Collecttion Efficiency
+  static const Float_t fgCollEffUV;    //! Collecttion Efficiency
+  static const Float_t fgCollEffCT1;   //! Collecttion Efficiency
+  static const Float_t fgCollEffErr;   //! Uncertainty Collection Efficiency
+
+  Float_t fArea;                       // Blind Pixel Area
+  Float_t fAreaErr;                    // Blind Pixel Area Error
+  MArrayF fAtt;                        // Attenuation filter (per color)
+  MArrayF fAttErr;                     // Error attnuation filter (per color)
+  MArrayF fQE;                         // Quantum eff. (per color)
+  MArrayF fQEErr;                      // Error Quantum eff. (per color)
+  MArrayF fCollEff;                    // Coll eff. (per color)
+  MArrayF fCollEffErr;                 // Error coll. eff. (per color)
+                                        
+  Float_t fLambda;                     // Mean Poisson fit
+  Float_t fLambdaCheck;                // Mean Pedestal Check (Gauss) fit
+  Float_t fLambdaCheckErr;             // Error mean pedestal Check fit
+  Float_t fLambdaVar;                  // Variance lambda Poisson fit
+  Float_t fFluxInsidePlexiglass;       // Number photons in INNER PIXEL inside the plexiglass
+  Float_t fFluxInsidePlexiglassVar;    // Variance number of photons in INNER PIXEL 
+  Float_t fMu0;                        // Position pedestal peak
+  Float_t fMu0Err;                     // Error pos. pedestal-peak
+  Float_t fMu1;                        // Position first photo-electron peak
+  Float_t fMu1Err;                     // Error pos. first photo-electon peak
+  Float_t fSigma0;                     // Width pedestal peak
+  Float_t fSigma0Err;                  // Error width pedestal peak
+  Float_t fSigma1;                     // Width first photo-electron peak  
+  Float_t fSigma1Err;                  // Error width first photo-electron peak  
+
+  enum { kOscillating, kPedestalFitOK, kSinglePheFitOK, kChargeFitValid, 
+         kFluxInsidePlexiglassAvailable };   // Possible validity flags 
+
+  MCalibrationCam::PulserColor_t fColor;     // Colour of the used pulser light
+
+public:
+
+  MCalibrationBlindPix(const char *name=NULL, const char *title=NULL);
+  
+  Bool_t CalcFluxInsidePlexiglass();
+  void   Clear(Option_t *o="");
+  void   Copy(TObject& object) const;
+  
+  // Getters
+  const Float_t GetAreaRelVar   () const;
+  const Float_t GetAtt          () const; 
+  const Float_t GetAttRelVar    () const; 
+  const Float_t GetQE           () const; 
+  const Float_t GetQERelVar     () const; 
+  const Float_t GetCollEff      () const;
+  const Float_t GetCollEffRelVar() const;   
+
+  const MCalibrationCam::PulserColor_t GetColor () const { return fColor;                }
+  const Float_t GetLambda                       () const { return fLambda;               }
+  const Float_t GetLambdaErr                    () const;
+  const Float_t GetLambdaRelVar                 () const;  
+  const Float_t GetLambdaCheck                  () const { return fLambdaCheck;          }
+  const Float_t GetLambdaCheckErr               () const { return fLambdaCheckErr;       }
+  const Float_t GetFluxInsidePlexiglass         () const { return fFluxInsidePlexiglass; }
+  const Float_t GetFluxInsidePlexiglassErr      () const;
+  const Float_t GetFluxInsidePlexiglassRelVar   () const;  
+  const Float_t GetMu0                          () const { return fMu0;                  }
+  const Float_t GetMu0Err                       () const { return fMu0Err;               }
+  const Float_t GetMu1                          () const { return fMu1;                  }
+  const Float_t GetMu1Err                       () const { return fMu1Err;               }
+  const Float_t GetSigma0                       () const { return fSigma0;               }
+  const Float_t GetSigma0Err                    () const { return fSigma0Err;            } 
+  const Float_t GetSigma1                       () const { return fSigma1;               }
+  const Float_t GetSigma1Err                    () const { return fSigma1Err;            }
+
+  const Bool_t  IsOscillating                   () const;
+  const Bool_t  IsChargeFitValid                () const;
+  const Bool_t  IsPedestalFitOK                 () const;
+  const Bool_t  IsSinglePheFitOK                () const;
+  const Bool_t  IsFluxInsidePlexiglassAvailable () const;
+
+  void Print(Option_t *opt=NULL) const;
+  
+  // Setters
+  void SetArea      ( Float_t f )               { fArea    = f; }
+  void SetAreaErr   ( Float_t f )               { fAreaErr = f; }  
+  
+  void SetAtt       ( Int_t n, Float_t *array ) { fAtt       .Set(n,array); }
+  void SetAttErr    ( Int_t n, Float_t *array ) { fAttErr    .Set(n,array); }
+  void SetQE        ( Int_t n, Float_t *array ) { fQE        .Set(n,array); }
+  void SetQEErr     ( Int_t n, Float_t *array ) { fQEErr     .Set(n,array); }
+  void SetCollEff   ( Int_t n, Float_t *array ) { fCollEff   .Set(n,array); }
+  void SetCollEffErr( Int_t n, Float_t *array ) { fCollEffErr.Set(n,array); }
+  
+  void SetColor          ( const MCalibrationCam::PulserColor_t color ) { fColor      = color; }
+  void SetLambda         ( const Float_t f )                            { fLambda         = f; }
+  void SetLambdaVar      ( const Float_t f )                            { fLambdaVar      = f; }
+  void SetLambdaCheck    ( const Float_t f )                            { fLambdaCheck    = f; }
+  void SetLambdaCheckErr ( const Float_t f )                            { fLambdaCheckErr = f; }
+  void SetMu0            ( const Float_t f )                            { fMu0            = f; }
+  void SetMu0Err         ( const Float_t f )                            { fMu0Err         = f; }
+  void SetMu1            ( const Float_t f )                            { fMu1            = f; }
+  void SetMu1Err         ( const Float_t f )                            { fMu1Err         = f; }
+  void SetSigma0         ( const Float_t f )                            { fSigma0         = f; }
+  void SetSigma0Err      ( const Float_t f )                            { fSigma0Err      = f; }
+  void SetSigma1         ( const Float_t f )                            { fSigma1         = f; }
+  void SetSigma1Err      ( const Float_t f )                            { fSigma1Err      = f; }
+
+  void SetOscillating    ( const Bool_t  b=kTRUE );
+  void SetChargeFitValid ( const Bool_t  b=kTRUE );
+  void SetPedestalFitOK  ( const Bool_t  b=kTRUE );
+  void SetSinglePheFitOK ( const Bool_t  b=kTRUE );
+  void SetFluxInsidePlexiglassAvailable( const Bool_t b=kTRUE);
+
+  ClassDef(MCalibrationBlindPix, 2)	// Container Calibration Results Blind Pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationCam.cc	(revision 17960)
@@ -0,0 +1,648 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationCam                                               
+//                                                               
+// Base class for Camera Calibration results. 
+//
+// Contains TOrdCollections for the following objects:
+// - fPixels:         Array of classes derived from MCalibrationPix, one entry 
+//                    per pixel. Has to be created
+// - fAverageAreas:   Array of classes derived from MCalibrationPix, one entry
+//                    per pixel AREA. Has to be created
+// - fAverageSectors: Array of classes derived from MCalibrationPix, one entry
+//                    per camera SECTOR. Has to be created
+//
+// - fAverageBadAreas: Array of classes derived from MBadPixelsPix, one entry
+//                     per pixel AREA. Is created automatically. 
+// - fAverageBadSectors: Array of classes derived from MBadPixelsPix, one entry
+//                    per camera SECTOR. Is created automatically.
+//
+// Previous Class Versions haven't been commented by the author!
+//
+// Class Version 6:
+// ----------------
+//  + added fRunNumber
+//
+// All TOrdCollections have to enlarged by the corresponding calls to (e.g. in MGeomApply): 
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors() 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationCam);
+
+using namespace std;
+
+const Int_t MCalibrationCam::gkNumPulserColors = 4;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set the following pointer to NULL:
+// - fPixels
+// - fAverageAreas
+// - fAverageSectors
+//
+// Initializes:
+// - fPulserColor to kNONE 
+// - fNumHiGainFADCSlices to 0.
+// - fNumLoGainFADCSlices to 0.
+//
+// Creates a TOrdCollection of MBadPixelsPix containers for the TOrdCollection's: 
+// - fAverageBadAreas
+// - fAverageBadSectors
+// all initialized to 1 entry
+//
+// Later, a call to InitAverageAreas() and InitAverageSectors() (or Init()) 
+// has to be performed in order to get the dimension correctly.
+//
+MCalibrationCam::MCalibrationCam(const char *name, const char *title)
+    : fRunNumber(-1), fPulserColor(kNONE)
+{
+
+  fPixels = new TOrdCollection;
+  fPixels->SetOwner();
+
+  fAverageAreas = new TOrdCollection;
+  fAverageAreas->SetOwner();
+  
+  fAverageSectors = new TOrdCollection;
+  fAverageSectors->SetOwner();
+
+  fAverageBadAreas = new TOrdCollection;
+  fAverageBadAreas->SetOwner();
+  
+  fAverageBadSectors = new TOrdCollection;
+  fAverageBadSectors->SetOwner();
+
+  fNumHiGainFADCSlices.Set(1);
+  fNumLoGainFADCSlices.Set(1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the following TOrdCollection's of MCalibrationPix containers (if exist):
+// - fPixels
+// - fAverageAreas
+// - fAverageSectors
+//  
+// Deletes the following TOrdCollection's of MBadPixelsPix containers (if exist):
+// - fAverageBadAreas
+// - fAverageBadSectors
+//
+MCalibrationCam::~MCalibrationCam()
+{
+
+  //
+  // delete fPixels should delete all Objects stored inside
+  //
+  if (fPixels)
+    delete fPixels;
+
+  if (fAverageAreas)
+    delete fAverageAreas;
+
+  if (fAverageSectors)
+    delete fAverageSectors;
+
+  if (fAverageBadAreas)
+    delete fAverageBadAreas;
+
+  if (fAverageBadSectors)
+    delete fAverageBadSectors;
+  
+}
+
+// --------------------------------------
+//
+// Calls the ForEach macro for the TOrdCollection fPixels with the argument Clear()
+// 
+// Loops over the fAverageAreas, calling the function Clear() for 
+// every entry in:
+// - fAverageAreas
+// - fAverageBadAreas
+// 
+// Loops over the fAverageSectors, calling the function Clear() for 
+// every entry in:
+// - fAverageSectors
+// - fAverageBadSectors
+// 
+void MCalibrationCam::Clear(Option_t *o)
+{
+    { fPixels        ->R__FOR_EACH(TObject, Clear)();  }
+    { fAverageAreas  ->R__FOR_EACH(TObject, Clear)();  }
+    { fAverageSectors->R__FOR_EACH(TObject, Clear)();  }
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibrationCam::Copy(TObject& object) const
+{
+  
+  MCalibrationCam &calib = (MCalibrationCam&)object;
+  
+  MParContainer::Copy(calib);
+  
+  calib.fPulserColor = fPulserColor;
+  
+  const Int_t n = GetSize();
+  if (n != 0)
+    {
+      calib.InitSize(n);
+      for (int i=0; i<n; i++)
+        (*this)[i].Copy(calib[i]);
+    }
+  
+  const Int_t n2 = GetAverageAreas();
+  if (n2 != 0)
+    {
+      calib.InitAverageAreas(n2);
+      for (int i=0; i<n2; i++)
+        {
+          GetAverageArea   (i).Copy(calib.GetAverageArea(i));
+          GetAverageBadArea(i).Copy(calib.GetAverageBadArea(i));
+          calib.fNumUnsuitable      [i] = fNumUnsuitable[i];
+          calib.fNumUnreliable      [i] = fNumUnreliable[i];
+          calib.fNumHiGainFADCSlices[i] = fNumHiGainFADCSlices[i];
+          calib.fNumLoGainFADCSlices[i] = fNumLoGainFADCSlices[i];
+        }
+    }
+  
+  const Int_t n3 = GetAverageSectors();
+  if (n3 != 0)
+    {
+      calib.InitAverageSectors(n3);
+      for (int i=0; i<n3; i++)
+        {
+          GetAverageSector   (i).Copy(calib.GetAverageSector(i));
+          GetAverageBadSector(i).Copy(calib.GetAverageBadSector(i));
+        }
+    }
+}
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollection using the 
+// virtual function Add().
+//
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationCam::InitSize(const UInt_t i)
+{
+
+  const UInt_t save = GetSize();
+
+  if (i==save)
+    return;
+  
+  if (i>save)
+    Add(save,i);
+}
+
+void MCalibrationCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationPix,i);
+}
+
+void MCalibrationCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationPix,i);
+}
+
+void MCalibrationCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationPix,i);
+}
+
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollections
+// - fAverageAreas
+// - fAverageBadAreas
+// using the virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationCam::InitAverageAreas(const UInt_t i)
+{
+
+  const UInt_t save = GetAverageAreas();
+
+  if (i==save)
+    return;
+  
+  fNumUnsuitable.Set(i);
+  fNumUnreliable.Set(i);
+  fNumHiGainFADCSlices.Set(i);
+  fNumLoGainFADCSlices.Set(i);
+
+  if (i < save)
+    return;
+
+  for (UInt_t j=save; j<i; j++)
+    fAverageBadAreas->AddAt(new MBadPixelsPix,j);
+  
+  AddArea(save,i);
+
+  for (UInt_t j=save; j<i; j++)
+    GetAverageArea(j).SetPixId(j);
+
+}
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollections
+// - fAverageSectors
+// - fAverageBadSectors
+// using the virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationCam::InitAverageSectors(const UInt_t i)
+{
+
+  const UInt_t save = GetAverageSectors();
+
+  if (i==save)
+    return;
+  
+  if (i < save)
+    return;
+
+  for (UInt_t j=save; j<i; j++)
+    fAverageBadSectors->AddAt(new MBadPixelsPix,j);
+  
+  AddSector(save,i);
+
+  for (UInt_t j=save; j<i; j++)
+    GetAverageSector(j).SetPixId(j);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MCalibrationCam::Init(const MGeomCam &geom)
+{
+  InitSize          (geom.GetNumPixels() );
+  InitAverageAreas  (geom.GetNumAreas()  );
+  InitAverageSectors(geom.GetNumSectors());
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the number of un-suitable pixels per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+Int_t MCalibrationCam::GetNumUnsuitable( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    {
+      Int_t num = 0;
+      for (Int_t i=0;i<fNumUnsuitable.GetSize();i++)
+        num += fNumUnsuitable[i];
+      return num;
+    }
+  
+  return aidx > fNumUnsuitable.GetSize() ? -1 : fNumUnsuitable[aidx]; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the number of un-reliable pixels per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+Int_t MCalibrationCam::GetNumUnreliable( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    {
+      Int_t num = 0;
+      for (Int_t i=0;i<fNumUnreliable.GetSize();i++)
+        num += fNumUnreliable[i];
+      return num;
+    }
+
+  return aidx > fNumUnreliable.GetSize() ? -1 : fNumUnreliable[aidx]; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mean number of High-Gain FADC slices per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+Float_t MCalibrationCam::GetNumHiGainFADCSlices( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    return -1;
+
+  return aidx > fNumHiGainFADCSlices.GetSize() ? -1 : fNumHiGainFADCSlices[aidx]; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mean number of Low-Gain FADC slices per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+Float_t MCalibrationCam::GetNumLoGainFADCSlices( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    return -1;
+
+  return aidx > fNumLoGainFADCSlices.GetSize() ? -1 : fNumLoGainFADCSlices[aidx]; 
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageAreas
+// independently if the MCalibrationPix is filled with values or not.
+//
+Int_t MCalibrationCam::GetAverageAreas() const
+{
+  return fAverageAreas->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageSectors
+// independently if the MCalibrationPix is filled with values or not.
+//
+Int_t MCalibrationCam::GetAverageSectors() const
+{
+  return fAverageSectors->GetSize();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MCalibrationPix &MCalibrationCam::operator[](UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fPixels->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MCalibrationPix &MCalibrationCam::operator[](UInt_t i) const
+{
+  return *static_cast<MCalibrationPix*>(fPixels->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fPixels 
+// independently if the MCalibrationPix is filled with values or not.
+//
+Int_t MCalibrationCam::GetSize() const
+{
+  return fPixels->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MCalibrationPix &MCalibrationCam::GetAverageArea(const UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fAverageAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MCalibrationPix &MCalibrationCam::GetAverageArea(const UInt_t i) const 
+{
+  return *static_cast<MCalibrationPix*>(fAverageAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MCalibrationPix &MCalibrationCam::GetAverageSector(const UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fAverageSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MCalibrationPix &MCalibrationCam::GetAverageSector(const UInt_t i) const 
+{
+  return *static_cast<MCalibrationPix*>(fAverageSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MBadPixelsPix &MCalibrationCam::GetAverageBadArea(const UInt_t i)
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MBadPixelsPix &MCalibrationCam::GetAverageBadArea(const UInt_t i) const 
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MBadPixelsPix &MCalibrationCam::GetAverageBadSector(const UInt_t i)
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MBadPixelsPix &MCalibrationCam::GetAverageBadSector(const UInt_t i) const 
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadSectors->At(i));
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+Bool_t MCalibrationCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx > GetSize())
+        return kFALSE;
+
+    const Float_t area = cam[idx].GetA();
+
+    if (area == 0)
+        return kFALSE;
+
+    if ((*this)[idx].IsExcluded())
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+        val = (*this)[idx].GetHiGainMean();
+        break;
+    case 1:
+        val = (*this)[idx].GetHiGainMeanErr();
+        break;
+    case 2:
+        val = (*this)[idx].GetHiGainSigma();
+        break;
+    case 3:
+        val = (*this)[idx].GetHiGainSigmaErr();
+        break;
+    case 4:
+        val = (*this)[idx].GetHiGainProb();
+        break;
+    case 5:
+        val = (*this)[idx].GetLoGainMean();
+        break;
+    case 6:
+        val = (*this)[idx].GetLoGainMeanErr();
+        break;
+    case 7:
+        val = (*this)[idx].GetLoGainSigma();
+        break;
+    case 8:
+        val = (*this)[idx].GetLoGainSigmaErr();
+        break;
+    default:
+        return kFALSE;
+    }
+
+    return val!=-1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MCalibrationPix::DrawClone()
+//
+void MCalibrationCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
+void MCalibrationCam::SetNumHiGainFADCSlices( const Float_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+
+  if (aidx < fNumHiGainFADCSlices.GetSize())
+    fNumHiGainFADCSlices[aidx] = i;  
+}
+
+void MCalibrationCam::SetNumLoGainFADCSlices( const Float_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+  if (aidx < fNumLoGainFADCSlices.GetSize())
+    fNumLoGainFADCSlices[aidx] = i; 
+}
+
+void MCalibrationCam::SetNumUnsuitable( const UInt_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+
+  if (aidx < fNumUnsuitable.GetSize())
+    fNumUnsuitable[aidx] = i;  
+}
+
+void MCalibrationCam::SetNumUnreliable( const UInt_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+  if (aidx < fNumUnreliable.GetSize())
+    fNumUnreliable[aidx] = i; 
+}
+
+TString MCalibrationCam::GetPulserColorStr(PulserColor_t col)
+{
+    TString str;
+    switch (col)
+    {
+    case kCT1:   str += "CT1";      break;
+    case kGREEN: str += "Green";    break;
+    case kBLUE:  str += "Blue";     break;
+    case kUV:    str += "UV";       break;
+    case kNONE:  str += "None";     break;
+    default:     str += "Unknown";  break;
+    }
+    str += " (";
+    str += (int)col;
+    str += ")";
+    return str;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationCam.h	(revision 17960)
@@ -0,0 +1,113 @@
+#ifndef MARS_MCalibrationCam
+#define MARS_MCalibrationCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TOrdCollection;
+
+class MCalibrationPix;
+class MBadPixelsPix;
+class MBadPixelsCam;
+class MGeomCam;
+
+class MCalibrationCam : public MParContainer, public MCamEvent
+{
+public:
+
+  enum PulserColor_t { 
+	kCT1  =0, 
+	kGREEN=1, 
+	kBLUE =2, 
+	kUV   =3, 
+	kNONE =4 
+	};                                  //! Possible Pulser colours
+  static const Int_t gkNumPulserColors;     //! Number of Pulser colours (now set to: 4)
+  
+protected:
+
+  TArrayI fNumUnsuitable;            // Number uncalibrated Pixels per area index 
+  TArrayI fNumUnreliable;            // Number unreliable   Pixels per area index 
+
+  TArrayF fNumHiGainFADCSlices;      // Number High-Gain FADC slices used by extractor      
+  TArrayF fNumLoGainFADCSlices;      // Number Low -Gain FADC slices used by extractor
+  
+  Int_t          fRunNumber;         // Store run number for interlaced calib. events
+  PulserColor_t  fPulserColor;        // Colour of the pulsed LEDs
+
+  TOrdCollection *fPixels;            //-> Array of MCalibrationPix, one per pixel
+  TOrdCollection *fAverageAreas;      // Array of MCalibrationPix, one per pixel area
+  TOrdCollection *fAverageSectors;    // Array of MCalibrationPix, one per camera sector
+  TOrdCollection *fAverageBadAreas;   // Array of MBadPixelsPix,   one per pixel area
+  TOrdCollection *fAverageBadSectors; // Array of MBadPixelsPix,   one per camera sector
+
+  virtual void Add(const UInt_t a, const UInt_t b);
+  virtual void AddArea(const UInt_t a, const UInt_t b);
+  virtual void AddSector(const UInt_t a, const UInt_t b);
+  
+  void  InitAverageSectors     ( const UInt_t i               );
+  virtual void  InitAverageAreas       ( const UInt_t i               );
+
+public:
+
+  MCalibrationCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationCam();
+  
+  void Clear           ( Option_t *o="");
+  void Copy(TObject& object) const;
+  
+  void DrawPixelContent( Int_t num) const;
+
+  // Getters
+        Int_t            GetAverageAreas        ()                     const;
+        MCalibrationPix &GetAverageArea         ( const UInt_t i     );
+  const MCalibrationPix &GetAverageArea         ( const UInt_t i     ) const;
+        MBadPixelsPix   &GetAverageBadArea      ( const UInt_t i     );
+  const MBadPixelsPix   &GetAverageBadArea      ( const UInt_t i     ) const;
+        Int_t            GetAverageSectors      ()                     const;
+        MCalibrationPix &GetAverageSector       ( const UInt_t i     );
+  const MCalibrationPix &GetAverageSector       ( const UInt_t i     ) const;  
+        MBadPixelsPix   &GetAverageBadSector    ( const UInt_t i     );
+  const MBadPixelsPix   &GetAverageBadSector    ( const UInt_t i     ) const;
+        Float_t          GetNumHiGainFADCSlices ( const Int_t aidx=0 ) const;
+        Float_t          GetNumLoGainFADCSlices ( const Int_t aidx=0 ) const;
+        Int_t            GetNumUnsuitable       ( const Int_t aidx=-1) const;
+        Int_t            GetNumUnreliable       ( const Int_t aidx=-1) const;
+
+        Bool_t           GetPixelContent        ( Double_t &val, Int_t idx, const MGeomCam &cam, 
+	                                          Int_t type=0       ) const;
+        PulserColor_t    GetPulserColor         ()                     const { return fPulserColor; }
+        Int_t            GetRunNumer            ()                     const { return fRunNumber;   }
+        Int_t            GetSize                ()                     const;
+
+        MCalibrationPix &operator[]             ( UInt_t i );
+  const MCalibrationPix &operator[]             ( UInt_t i )           const;
+
+  static TString GetPulserColorStr(PulserColor_t col);
+
+  // Inits
+  void  Init                   ( const MGeomCam &geom         );
+  void  InitSize               ( const UInt_t i               );
+
+  // Setters
+  void  SetNumHiGainFADCSlices ( const Float_t f, const Int_t aidx=0 );
+  void  SetNumLoGainFADCSlices ( const Float_t f, const Int_t aidx=0 );
+  void  SetNumUnsuitable       ( const UInt_t i,  const Int_t aidx   );  
+  void  SetNumUnreliable       ( const UInt_t i,  const Int_t aidx   ); 
+  virtual void  SetPulserColor ( const PulserColor_t col=kCT1 )  { fPulserColor = col; }
+  void  SetRunNumber           ( const Int_t run              )  { fRunNumber   = run; }
+   
+  ClassDef(MCalibrationCam, 6)	// Base class Container for Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCalc.cc	(revision 17960)
@@ -0,0 +1,2397 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationChargeCalc
+//
+//   Task to calculate the calibration conversion factors and quantum efficiencies 
+//   from the fit results to the summed FADC slice distributions delivered by 
+//   MCalibrationChargeCam, MCalibrationChargePix, MCalibrationChargeBlindPix and 
+//   MCalibrationChargePINDiode, calculated and filled by MHCalibrationChargeCam, 
+//   MHCalibrationChargePix, MHCalibrationChargeBlindPix and MHCalibrationChargePINDiode.
+//
+//   PreProcess(): Initialize pointers to MCalibrationChargeCam, MCalibrationChargeBlindPix
+//                 MCalibrationChargePINDiode and  MCalibrationQECam
+//
+//                 Initialize pulser light wavelength
+//               
+//   ReInit():     MCalibrationCam::InitSize(NumPixels) is called from MGeomApply (which allocates
+//                 memory in a TClonesArray of type MCalibrationChargePix)
+//                 Initializes pointer to MBadPixelsCam
+//
+//   Process():    Nothing to be done, histograms getting filled by MHCalibrationChargeCam
+//
+//   PostProcess(): - FinalizePedestals()
+//                  - FinalizeCharges()
+//                  - FinalizeFFactorMethod()
+//                  - FinalizeBadPixels()
+//                  - FinalizeBlindCam()
+//                  - FinalizePINDiode()
+//                  - FinalizeFFactorQECam()
+//                  - FinalizeBlindPixelQECam()
+//                  - FinalizePINDiodeQECam()
+//
+//  Input Containers:
+//   MCalibrationChargeCam
+//   MCalibrationChargeBlindPix
+//   MCalibrationChargePINDiode
+//   MCalibrationQECam
+//   MPedestalCam
+//   MBadPixelsCam
+//   MGeomCam
+//   MTime
+//
+//  Output Containers:
+//   MCalibrationChargeCam
+//   MCalibrationChargeBlindPix
+//   MCalibrationChargePINDiode
+//   MCalibrationQECam
+//   MBadPixelsCam
+//
+//
+//  Preliminary description of the calibration in photons (email from 12/02/04)
+//
+//  Why calibrating in photons:
+//  ===========================
+//  
+//  At the Barcelona meeting in 2002, we decided to calibrate the camera in
+//  photons. This for the following reasons:
+//  
+//  * The physical quantity arriving at the camera are photons. This is
+//    the direct physical information from the air shower. The photons
+//    have a flux and a spectrum.
+//  
+//  * The photon fluxes depend mostly on the shower energy (with
+//    corrections deriving from the observation conditions), while the photon
+//    spectra depend mostly on the observation conditions: zenith angle,
+//    quality of the air, also the impact parameter of the shower.
+//  
+//  * The photomultiplier, in turn, has different response properties
+//    (quantum efficiencies) for photons of different colour. (Moreover,
+//    different pixels have slightly different quantum efficiencies).
+//    The resulting number of photo-electrons is then amplified (linearly)
+//    with respect to the photo-electron flux.
+//  
+//  * In the ideal case, one would like to disentagle the effects
+//    of the observation conditions from the primary particle energy (which
+//    one likes to measure). To do so, one needs:
+//  
+//    1) A reliable calibration relating the FADC counts to the photo-electron
+//       flux -> This is accomplished with the F-Factor method.
+//  
+//    2) A reliable calibration of the wavelength-dependent quantum efficiency
+//       -> This is accomplished with the combination of the three methods,
+//          together with QE-measurements performed by David in order to do
+//          the interpolation.
+//  
+//    3) A reliable calibration of the observation conditions. This means:
+//       - Tracing the atmospheric conditions   -> LIDAR
+//       - Tracing the observation zenith angle -> Drive System
+//
+//    4) Some knowlegde about the impact parameter:
+//       - This is the only part which cannot be accomplished well with a
+//         single telescope. We would thus need to convolute the spectrum
+//         over the distribution of impact parameters.
+//  
+//  
+//  How an ideal calibration would look like:
+//  =========================================
+//  
+//  We know from the combined PIN-Diode and Blind-Pixel Method the response of
+//  each pixel to well-measured light fluxes in three representative
+//  wavelengths (green, blue, UV). We also know the response to these light
+//  fluxes in photo-electrons. Thus, we can derive:
+//  
+//  - conversion factors to photo-electrons
+//  - conversion factors to photons in three wavelengths.
+//  
+//  Together with David's measurements and some MC-simulation, we should be
+//  able to derive tables for typical Cherenkov-photon spectra - convoluted
+//  with the impact parameters and depending on the athmospheric conditions
+//  and the zenith angle (the "outer parameters").
+//  
+//  From these tables we can create "calibration tables" containing some
+//  effective quantum efficiency depending on these outer parameters and which
+//  are different for each pixel.
+//  
+//  In an ideal MCalibrate, one would thus have to convert first the FADC
+//  slices to Photo-electrons and then, depending on the outer parameters,
+//  look up the effective quantum efficiency and get the mean number of
+//  photons which is then used for the further analysis.
+//  
+//  How the (first) MAGIC calibration should look like:
+//  ===================================================
+//  
+//  For the moment, we have only one reliable calibration method, although
+//  with very large systematic errors. This is the F-Factor method. Knowing
+//  that the light is uniform over the whole camera (which I would not at all
+//  guarantee in the case of the CT1 pulser), one could in principle already
+//  perform a relative calibration of the quantum efficiencies in the UV.
+//  However, the spread in QE at UV is about 10-15% (according to the plot
+//  that Abelardo sent around last time. The spread in photo-electrons is 15%
+//  for the inner pixels, but much larger (40%) for the outer ones.
+//  
+//  I'm not sure if we can already say that we have measured the relative
+//  difference in quantum efficiency for the inner pixels and produce a first
+//  QE-table for each pixel. To so, I would rather check in other wavelengths
+//  (which we can do in about one-two weeks when the optical transmission of
+//  the calibration trigger is installed).
+//  
+//  Thus, for the moment being, I would join Thomas proposal to calibrate in
+//  photo-electrons and apply one stupid average quantum efficiency for all
+//  pixels. This keeping in mind that we will have much preciser information
+//  in about one to two weeks.
+//  
+//  
+//  What MCalibrate should calculate and what should be stored:
+//  ===========================================================
+//  
+//  It is clear that in the end, MCerPhotEvt will store photons.
+//  MCalibrationCam stores the conversionfactors to photo-electrons and also
+//  some tables of how to apply the conversion to photons, given the outer
+//  parameters. This is not yet implemented and not even discussed.
+//  
+//  To start, I would suggest that we define the "average quantum efficiency"
+//  (maybe something like 25+-3%) and apply them equally to all
+//  photo-electrons. Later, this average factor can be easily replaced by a
+//  pixel-dependent factor and later by a (pixel-dependent) table.
+//  
+//  
+//  ClassVersion 2:
+//   - Float_t fPheErrLimit;
+//   + Float_t fPheErrLowerLimit; // Lower limit acceptance nr. phe's w.r.t. area idx mean (in sigmas)
+//   + Float_t fPheErrUpperLimit; // Upper limit acceptance nr. phe's w.r.t. area idx mean (in sigmas)
+//
+//
+//  ClassVersion 3:
+//   + Bool_t  fUseExtractorRes;  // Include extractor resolution in F-Factor method
+//
+//  ClassVersion 4:
+//   +  Float_t fUnsuitablesLimit;                   // Limit for relative number of unsuitable pixels
+//   +  Float_t fUnreliablesLimit;                   // Limit for relative number of unreliable pixels
+//   +  Float_t fExternalNumPhes;                    // External mean number of photo-electrons set from outside
+//   +  Float_t fExternalNumPhesRelVar;              // External rel. var. number of photo-electrons set from outside  
+//
+//  ClassVersion 5:
+//   -  TString fOutputPath
+//   -  TString fOutputFile
+//
+//  ClassVersion 6:
+//   -  Bool_t fContinousCalibration
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargeCalc.h"
+
+#include <TSystem.h>
+#include <TH1.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMath.h"
+
+#include "MParList.h"
+
+#include "MCalibrationPattern.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+#include "MHCamera.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationChargeBlindCam.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationBlindPix.h"
+#include "MCalibrationBlindCam.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+#include "MExtractedSignalBlindPixel.h"
+#include "MExtractedSignalPINDiode.h"
+
+#include "MBadPixelsCam.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+ClassImp(MCalibrationChargeCalc);
+
+using namespace std;
+
+const Float_t MCalibrationChargeCalc::fgChargeLimit            = 4.5;
+const Float_t MCalibrationChargeCalc::fgChargeErrLimit         = 0.;
+const Float_t MCalibrationChargeCalc::fgChargeRelErrLimit      = 1.;
+const Float_t MCalibrationChargeCalc::fgLambdaErrLimit         = 0.2;
+const Float_t MCalibrationChargeCalc::fgLambdaCheckLimit       = 0.5;
+const Float_t MCalibrationChargeCalc::fgPheErrLowerLimit       = 6.0;
+const Float_t MCalibrationChargeCalc::fgPheErrUpperLimit       = 5.5;
+const Float_t MCalibrationChargeCalc::fgFFactorErrLimit        = 4.5;
+const Float_t MCalibrationChargeCalc::fgArrTimeRmsLimit        = 5.0;
+const Float_t MCalibrationChargeCalc::fgUnsuitablesLimit       = 0.1;
+const Float_t MCalibrationChargeCalc::fgUnreliablesLimit       = 0.3;
+
+const char *MCalibrationChargeCalc::fgNamePedestalCam = "MPedestalCam";
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets the pointer to fQECam and fGeom to NULL
+// 
+// Calls AddToBranchList for: 
+// - MRawEvtData.fHiGainPixId   
+// - MRawEvtData.fLoGainPixId   
+// - MRawEvtData.fHiGainFadcSamples
+// - MRawEvtData.fLoGainFadcSamples
+//
+// Initializes:
+// - fArrTimeRmsLimit     to fgArrTimeRmsLimit
+// - fChargeLimit         to fgChargeLimit
+// - fChargeErrLimit      to fgChargeErrLimit
+// - fChargeRelErrLimit   to fgChargeRelErrLimit
+// - fFFactorErrLimit     to fgFFactorErrLimit
+// - fLambdaCheckLimit    to fgLambdaCheckLimit
+// - fLambdaErrLimit      to fgLambdaErrLimit
+// - fNamePedestalCam     to fgNamePedestalCam
+// - fPheErrLowerLimit    to fgPheErrLowerLimit
+// - fPheErrUpperLimit    to fgPheErrUpperLimit
+// - fPulserColor         to MCalibrationCam::kCT1
+// - fOutputPath          to "."
+// - fOutputFile          to "ChargeCalibStat.txt"
+// - flag debug           to kFALSE
+// - IsUseExtractorRes    to kFALSE
+// - IsUseExternalNumPhes to kFALSE
+// - fExternalNumPhes     to 0.
+// - fExternalNumPhesRelVar to 0.
+//
+// Sets all checks
+//
+// Calls:
+// - Clear()
+//
+MCalibrationChargeCalc::MCalibrationChargeCalc(const char *name, const char *title)
+    : fPulserColor(MCalibrationCam::kNONE), fContinousCalibration(kFALSE),
+    fGeom(NULL), fSignal(NULL), fCalibPattern(NULL), fExtractor(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");
+  
+  SetArrTimeRmsLimit   ();
+  SetChargeLimit       ();
+  SetChargeErrLimit    ();  
+  SetChargeRelErrLimit ();
+  SetDebug       ( kFALSE );
+  SetFFactorErrLimit   ();
+  SetLambdaCheckLimit  ();
+  SetLambdaErrLimit    ();
+  SetNamePedestalCam   ();
+  SetPheErrLowerLimit  ();
+  SetPheErrUpperLimit  ();
+  SetUnsuitablesLimit  ();
+  SetUnreliablesLimit  ();
+  SetUseExtractorRes   ();
+  SetUseUnreliables    ();
+  SetUseExternalNumPhes(kFALSE);
+ 
+  SetExternalNumPhes      ();
+  SetExternalNumPhesRelVar();
+
+  SetCheckArrivalTimes     ();
+  SetCheckDeadPixels       ();
+  SetCheckDeviatingBehavior();
+  SetCheckExtractionWindow ();
+  SetCheckHistOverflow     ();
+  SetCheckOscillations     ();
+
+  Clear();
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - all variables to 0., 
+// - all flags to kFALSE
+// - all pointers to NULL
+// - the pulser colour to kNONE
+// - fBlindPixelFlags to 0
+// - fPINDiodeFlags   to 0
+//
+void MCalibrationChargeCalc::Clear(const Option_t *o)
+{
+  
+    fNumHiGainSamples          = 0.;
+    fNumLoGainSamples          = 0.;
+    fSqrtHiGainSamples         = 0.;
+    fSqrtLoGainSamples         = 0.;
+    fNumInnerFFactorMethodUsed = 0;
+
+    fNumProcessed              = 0;
+
+    fBadPixels   = NULL;
+    fCam         = NULL;
+    fHCam        = NULL;
+    fQECam       = NULL;
+    fBlindCam    = NULL;
+    fHBlindCam   = NULL;
+    fPINDiode    = NULL;
+    fPedestals   = NULL;
+
+    SetPulserColor ( MCalibrationCam::kNONE );
+
+    fStrength    = 0.;
+    fBlindPixelFlags.Set(0);
+    fPINDiodeFlags  .Set(0);
+    fResultFlags    .Set(0);
+}
+
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MPedestalCam
+//  - MCalibrationPattern
+//  - MExtractedSignalCam
+//
+Int_t MCalibrationChargeCalc::PreProcess(MParList *pList)
+{
+  
+  /*
+  if (IsInterlaced())
+    {
+      fTrigPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
+      if (!fTrigPattern)
+        {
+          *fLog << err << "MTriggerPattern not found... abort." << endl;
+          return kFALSE;
+        }
+    }
+  */
+
+  fCalibPattern = (MCalibrationPattern*)pList->FindObject("MCalibrationPattern");
+  if (!fCalibPattern)
+    {
+      *fLog << err << "MCalibrationPattern not found... abort." << endl;
+      return kFALSE;
+    }
+
+  // 
+  // Containers that have to be there.
+  //
+  fSignal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!fSignal)
+    {
+      *fLog << err << "MExtractedSignalCam not found... aborting" << endl;
+      return kFALSE;
+    }
+
+  if (fPedestals)
+    return kTRUE;
+
+  fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber(fNamePedestalCam), "MPedestalCam");
+  if (!fPedestals)
+    {
+      *fLog << err << fNamePedestalCam << " [MPedestalCam] not found... aborting" << endl;
+      return kFALSE;
+    }
+
+  // Obsolete... it is already set in the constructor isn't it?
+  fPulserColor = MCalibrationCam::kNONE;
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+//  - MGeomCam
+// -  MCalibrationChargeCam
+//  - MCalibrationQECam
+//  - MBadPixelsCam
+// 
+// Search for the following input containers and give a warning if not existing:
+//  - MCalibrationBlindPix
+//  - MCalibrationChargePINDiode
+//
+// It retrieves the following variables from MCalibrationChargeCam:
+//
+//  - fNumHiGainSamples 
+//  - fNumLoGainSamples 
+//
+// It defines the PixId of every pixel in:
+//
+// - MCalibrationChargeCam 
+// - MCalibrationQECam
+//
+// It sets all pixels in excluded which have the flag fBadBixelsPix::IsBad() set in:
+// 
+// - MCalibrationChargePix
+// - MCalibrationQEPix
+//
+// Sets the pulser colour and tests if it has not changed w.r.t. fPulserColor in:
+//
+// - MCalibrationChargeCam
+// - MCalibrationBlindPix (if existing)
+// - MCalibrationChargePINDiode (if existing)
+//
+Bool_t MCalibrationChargeCalc::ReInit(MParList *pList )
+{
+
+    //
+    // Geometry
+    //
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "No MGeomCam found... aborting." << endl;
+      return kFALSE;
+    }
+
+    //
+    // Charge histogram
+    //
+  fHCam = (MHCalibrationChargeCam*)pList->FindObject(AddSerialNumber("MHCalibrationChargeCam"));
+  if (!fHCam)
+    {
+      *fLog << err << "Cannot find MHCalibrationChargeCam ... abort." << endl;
+      *fLog << "Maybe you forget to call an MFillH for the MHCalibrationChargeCam before..." << endl;
+      return kFALSE;
+    }
+  
+    //
+    // MCalibrationChargeCam
+    //
+  fCam = (MCalibrationChargeCam*)pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+  if (!fCam)
+  {
+      *fLog << err << "Cannot find MCalibrationChargeCam ... abort." << endl;
+      *fLog << "Maybe you forget to call an MFillH for the MHCalibrationChargeCam before..." << endl;
+      return kFALSE;
+  }
+
+  //
+  // Blind pixel calibration
+  //
+  fBlindCam = (MCalibrationBlindCam*)pList->FindObject(AddSerialNumber("MCalibrationBlindCam"));
+  if (!fBlindCam)
+      *fLog << inf << "No MCalibrationBlindCam found... no Blind Pixel method!" << endl;
+
+  //
+  // Required containers
+  //
+  fQECam = (MCalibrationQECam*)pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+  if (!fQECam)
+  {
+      *fLog << err << "Cannot find MCalibrationQECam ... abort." << endl;
+      return kFALSE;
+  }
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+  if (!fBadPixels)
+  {
+      *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+      return kFALSE;
+  }
+  
+  // 
+  // Optional Containers 
+  //
+  fPINDiode = (MCalibrationChargePINDiode*)pList->FindObject("MCalibrationChargePINDiode");
+  if (!fPINDiode)
+    *fLog << inf << "No MCalibrationChargePINDiode found... no PIN Diode method!" << endl;
+
+  fHBlindCam = (MHCalibrationChargeBlindCam*)pList->FindObject(AddSerialNumber("MHCalibrationChargeBlindCam"));
+  if (!fHBlindCam)
+    *fLog << inf << "No MHCalibrationChargeBlindCam found... no Blind Pixel method!" << endl;
+
+
+  //
+  // Further initialization
+  //
+  if (IsDebug())
+  {
+      const UInt_t npixels = fGeom->GetNumPixels();
+      for (UInt_t i=0; i<npixels; i++)
+          (*fCam)[i].SetDebug();
+  }
+
+  fResultFlags.Set(fGeom->GetNumAreas());
+
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//  
+// Set the correct colour to the charge containers
+// 
+Int_t MCalibrationChargeCalc::Process()
+{
+
+  const MCalibrationCam::PulserColor_t col = fCalibPattern->GetPulserColor();
+
+  //
+  // If pulser color didn't change there is nothing to do
+  //
+  const Float_t strength = fCalibPattern->GetPulserStrength();
+  const Float_t strdiff  = TMath::Abs(strength-fStrength);
+  if (col == fPulserColor && strdiff < 0.05 )
+    {
+      fNumProcessed++;
+      return kTRUE;
+    }
+
+  //
+  // If there is no color is nothing to do
+  //
+  if (col == MCalibrationCam::kNONE)
+    return kTRUE;
+
+  //
+  // Now retrieve the colour and check if not various colours have been used
+  //
+  if (!fContinousCalibration && fPulserColor != MCalibrationCam::kNONE)
+  {
+      *fLog << warn << "Multiple colours used simultaneously!" << flush;
+      fHCam->Finalize();
+      if (fHBlindCam)
+          fHBlindCam->Finalize();
+
+      Finalize();
+
+      fHCam->ResetHists();
+      if (fHBlindCam)
+          fHBlindCam->ResetHists();
+
+      *fLog << inf << "Starting next calibration... " << flush;
+
+      fHCam->SetColor(col);
+      if (fHBlindCam)
+          fHBlindCam->SetColor(col);
+
+      fCam->SetPulserColor(col);
+      if (fBlindCam)
+          fBlindCam->SetPulserColor(col);
+  }
+
+  //
+  // Keep pulser color and strength in mind and output some information
+  //
+  fPulserColor = col;
+  fStrength    = strength;
+
+  *fLog << inf << "Found new colour ... " << flush;
+
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN: *fLog << "Green";  break;
+    case MCalibrationCam::kBLUE:  *fLog << "Blue";   break;
+    case MCalibrationCam::kUV:    *fLog << "UV";     break;
+    case MCalibrationCam::kCT1:   *fLog << "CT1";    break;
+    default: break;
+    }
+
+  *fLog << inf << " with strength: " << strength << endl;
+  
+  //
+  // Distribute new color to all containers
+  //
+  fCam->SetPulserColor(col);
+  if (fBlindCam)
+    fBlindCam->SetPulserColor(col);
+
+  fHCam->SetColor(col);
+  if (fHBlindCam)
+    fHBlindCam->SetColor(col);
+  if (fPINDiode)
+    fPINDiode->SetColor(col);
+
+  //
+  // Reset number of processed events
+  //
+  fNumProcessed = 0;
+  
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Return if number of executions is null.
+//
+Int_t MCalibrationChargeCalc::PostProcess()
+{
+
+  if (GetNumExecutions() < 1)
+    return kTRUE;
+
+  if (fPulserColor == MCalibrationCam::kNONE)
+  {
+      *fLog << err << "ERROR - No event was flagged with a pulser color... no calibration possible." << endl;
+      return kFALSE;
+  }
+
+  if (fNumProcessed == 0)
+    return kTRUE;
+
+  *fLog << endl;
+
+  return Finalize();
+}
+
+// ----------------------------------------------------------------------------------------------------
+//
+// Check for outliers. They are marked with
+// MBadPixelsPix::kFluctuatingArrivalTimes
+//
+// see also MCalibrationRelTimeCalc::FinalizeRelTimes
+//
+void MCalibrationChargeCalc::FinalizeAbsTimes()
+{
+    const Int_t npixels = fGeom->GetNumPixels();
+    const Int_t nareas  = fGeom->GetNumAreas();
+
+    // Create an array capable of holding all pixels
+    TArrayF arr(npixels);
+
+    for (Int_t aidx=0; aidx<nareas; aidx++)
+    {
+        Int_t n = 0;
+        for (Int_t i=0; i<npixels; i++)
+        {
+            // Check for this aidx only
+            if ((*fGeom)[i].GetAidx()!=aidx)
+                continue;
+
+            // check if pixel may not contain a valid value
+            if ((*fBadPixels)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+                continue;
+
+            // check if it was excluded for some reason
+            const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+            if (pix.IsExcluded())
+                continue;
+
+            // if TimePrecision is valid fill it into array
+            if (pix.GetAbsTimeRms()>0)
+                arr[n++] = pix.GetAbsTimeRms();
+        }
+
+        // Check the ratio of valid entries to the ratio of pixels
+        const Float_t ratio = 100*n/fGeom->GetNumPixWithAidx(aidx);
+        if (3*ratio<2)
+            *fLog << warn << "Area   " << setw(4) << aidx << ": Only " << ratio << "% pixels with valid time resolution found." << endl;
+
+        // Calculate median and median deviation
+        Double_t med;
+        const Double_t dev = MMath::MedianDev(n, arr.GetArray(), med);
+
+        // Calculate upper and lower limit
+        const Float_t lolim = TMath::Max(med-fArrTimeRmsLimit*dev, 0.);
+        const Float_t hilim = TMath::Max(med+fArrTimeRmsLimit*dev, 0.);
+
+        // Now find the outliers
+        for (Int_t i=0; i<npixels; i++)
+        {
+            // Search only within this aidx
+            if ((*fGeom)[i].GetAidx()!=aidx)
+                continue;
+
+            // skip pixels already known to be unsuitable
+            if ((*fBadPixels)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+                continue;
+
+            // check if a pixel has been excluded. This
+            const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+
+            // Check if time precision is valid (might be invalid
+            // for example in cae of empty histograms)
+            const Float_t res = pix.GetAbsTimeRms();
+            if (res<0) //FIXME!!! How does this happen?
+            {
+                *fLog << warn << "Pixel  " << setw(4) << i << ": Abs-time rms could not be calculated." << endl;
+                (*fBadPixels)[i].SetUncalibrated(MBadPixelsPix::kDeviatingAbsTimeResolution);
+                continue;
+            }
+
+            if (res==0)
+            {
+                *fLog << warn << "Pixel  " << setw(4) << i << ": Abs-time rms==0." << endl;
+                (*fBadPixels)[i].SetUncalibrated(MBadPixelsPix::kDeviatingAbsTimeResolution);
+                continue;
+            }
+
+            // Now compare to a lower and upper limit
+            if (res<=lolim || res>=hilim)
+            {
+                *fLog << warn << "Pixel  " << setw(4) << i << ": Deviation from abs-time rms: "
+                    << Form("%5.2f", res) << " out of range "
+                    << Form("[%4.2f,%4.2f]", lolim, hilim) << endl;
+
+                (*fBadPixels)[i].SetUncalibrated(MBadPixelsPix::kDeviatingAbsTimeResolution);
+            }
+        }
+    }
+}
+
+// -----------------------------------------------------------------------
+//
+// Return kTRUE if fPulserColor is kNONE
+//
+// First loop over pixels, average areas and sectors, call:
+//  - FinalizePedestals() 
+//  - FinalizeCharges()
+// for every entry. Count number of valid pixels in loop and return kFALSE
+// if there are none (the "Michele check").
+//
+// Call FinalizeBadPixels()
+//
+// Call FinalizeFFactorMethod() (second and third loop over pixels and areas)
+//
+// Call FinalizeBlindCam() 
+// Call FinalizePINDiode()
+//
+// Call  FinalizeFFactorQECam() (fourth loop over pixels and areas)
+// Call  FinalizeBlindPixelQECam() (fifth loop over pixels and areas)
+// Call  FinalizePINDiodeQECam() (sixth loop over pixels and areas)
+//
+// Call  FinalizeUnsuitablePixels()
+//  
+// Call MParContainer::SetReadyToSave() for fCam, fQECam, fBadPixels and
+//      fBlindCam and fPINDiode if they exist
+//
+// Print out some statistics
+//
+Int_t MCalibrationChargeCalc::Finalize()
+{
+    // The number of used slices are just a mean value
+    // the real number might change from event to event.
+    // (up to 50%!)
+
+  fNumHiGainSamples  =  fSignal->GetNumUsedHiGainFADCSlices();
+  fNumLoGainSamples  =  fSignal->GetNumUsedLoGainFADCSlices();
+
+  fSqrtHiGainSamples =  TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples =  TMath::Sqrt(fNumLoGainSamples);
+  
+  if (fPINDiode)
+    if (!fPINDiode->IsValid())
+      {
+        *fLog << warn << GetDescriptor() 
+              << ": MCalibrationChargePINDiode is declared not valid... no PIN Diode method! " << endl;
+        fPINDiode = NULL;
+      }
+
+  //
+  // First loop over pixels, call FinalizePedestals and FinalizeCharges
+  //
+  Int_t nvalid = 0;
+  for (Int_t pixid=0; pixid<fPedestals->GetSize(); pixid++)
+  {
+      //
+      // Check if the pixel has been excluded from the fits
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[pixid];
+      if (pix.IsExcluded())
+          continue;
+
+      FinalizePedestals((*fPedestals)[pixid], pix, (*fGeom)[pixid].GetAidx());
+
+      if (FinalizeCharges(pix, (*fBadPixels)[pixid], "Pixel  "))
+          nvalid++;
+  }
+
+  FinalizeAbsTimes();
+
+  *fLog << endl;  
+
+  //
+  // The Michele check ...
+  //
+  if (nvalid == 0)
+  {
+      if (!fContinousCalibration)
+      {
+        *fLog << warn << GetDescriptor() << ": All pixels have non-valid calibration. " 
+              << "Did you forget to fill the histograms "
+              << "(filling MHCalibrationChargeCam from MExtractedSignalCam using MFillH) ? " << endl;
+        *fLog << warn << GetDescriptor() << ": Or, maybe, you have used a pedestal run " 
+              << "instead of a calibration run " << endl;
+        return kFALSE;
+      }
+  }
+
+  for (UInt_t aidx=0; aidx<fGeom->GetNumAreas(); aidx++)
+    {
+
+      const MPedestalPix    &ped = fPedestals->GetAverageArea(aidx);
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)fCam->GetAverageArea(aidx);
+      const MArrayI &arr         = fHCam->GetAverageAreaNum();
+
+      FinalizePedestals(ped,pix,aidx);
+
+      //
+      // Correct for sqrt(number of valid pixels) in the pedestal RMS
+      // (already done for calibration sigma in MHCalibrationCam::CalcAverageSigma()
+      //
+      const Double_t sqrtnum = TMath::Sqrt((Double_t)arr[aidx]);
+
+      pix.SetPedRMS(pix.GetPedRms()*sqrtnum, pix.GetPedRmsErr()*sqrtnum);
+      pix.SetSigma (pix.GetSigma()/pix.GetFFactorFADC2Phe());
+
+      FinalizeCharges(pix, fCam->GetAverageBadArea(aidx),"area id");
+    }
+  
+  *fLog << endl;
+
+  for (UInt_t sector=0; sector<fGeom->GetNumSectors(); sector++)
+    {
+
+      const MPedestalPix     &ped = fPedestals->GetAverageSector(sector);
+
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)fCam->GetAverageSector(sector);
+      FinalizePedestals(ped,pix, 0);
+    }
+  
+  *fLog << endl;
+
+  //
+  // Finalize Bad Pixels
+  // 
+  FinalizeBadPixels();
+
+  // 
+  // Finalize F-Factor method
+  //
+  if (FinalizeFFactorMethod())
+    fCam->SetFFactorMethodValid(kTRUE);
+  else
+    {
+      *fLog << warn << "Could not calculate the photons flux from the F-Factor method " << endl;
+      fCam->SetFFactorMethodValid(kFALSE);
+      if (!fContinousCalibration)
+          return kFALSE;
+    }
+
+  *fLog << endl;
+
+  //
+  // Finalize Blind Pixel
+  //
+  fQECam->SetBlindPixelMethodValid(FinalizeBlindCam());
+
+  // 
+  // Finalize PIN Diode
+  //
+  fQECam->SetBlindPixelMethodValid(FinalizePINDiode());
+
+  //
+  // Finalize QE Cam
+  //
+  FinalizeFFactorQECam();
+  FinalizeBlindPixelQECam();
+  FinalizePINDiodeQECam();
+  FinalizeCombinedQECam();
+
+  //
+  // Re-direct the output to an ascii-file from now on:
+  //
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Fatal errors statistics:" << endl;  
+
+  PrintUncalibrated(MBadPixelsPix::kChargeIsPedestal,    
+                    Form("%s%2.1f%s","Signal less than ",fChargeLimit," Pedestal RMS:                "));
+  PrintUncalibrated(MBadPixelsPix::kChargeRelErrNotValid,
+                    Form("%s%2.1f%s","Signal Error bigger than ",fChargeRelErrLimit," times Mean Signal:   "));
+  PrintUncalibrated(MBadPixelsPix::kLoGainSaturation,    
+                    "Low Gain Saturation:                              ");
+//  PrintUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin,
+//                    Form("%s%2.1f%s","Mean Abs. Arr. Time in First ",1.," Bin(s):          "));
+//  PrintUncalibrated(MBadPixelsPix::kMeanTimeInLast2Bins,
+//                    Form("%s%2.1f%s","Mean Abs. Arr. Time in Last ",2.," Bin(s):           "));
+  PrintUncalibrated(MBadPixelsPix::kHiGainOverFlow,    
+                    "Pixels with High Gain Overflow:                   ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainOverFlow,    
+                    "Pixels with Low Gain Overflow :                   ");
+//  PrintUncalibrated(MBadPixelsPix::kFluctuatingArrivalTimes,
+//                    "Fluctuating Pulse Arrival Times:                  ");
+  PrintUncalibrated(MBadPixelsPix::kDeviatingAbsTimeResolution,
+                    Form("%s%2.1f%s ","Abs.time rms more than ", fArrTimeRmsLimit, " dev from median:      "));
+  PrintUncalibrated(MBadPixelsPix::kDeadPedestalRms,
+                    "Presumably dead from Pedestal Rms:                ");
+  PrintUncalibrated(MBadPixelsPix::kDeviatingNumPhes,
+                    "Deviating number of phes:                         ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainBlackout,
+                    "Too many blackout events in low gain:             ");
+  PrintUncalibrated(MBadPixelsPix::kPreviouslyExcluded,
+                    "Previously excluded:                              ");
+
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Unreliable errors statistics:" << endl;  
+
+  PrintUncalibrated(MBadPixelsPix::kChargeSigmaNotValid, 
+                    "Signal Sigma smaller than Pedestal RMS: ");
+  PrintUncalibrated(MBadPixelsPix::kHiGainOscillating,   
+                    "Changing Hi Gain signal over time:      ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainOscillating,   
+                    "Changing Lo Gain signal over time:      ");
+  PrintUncalibrated(MBadPixelsPix::kHiGainNotFitted,     
+                    "Unsuccesful Gauss fit to the Hi Gain:   ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainNotFitted,     
+                    "Unsuccesful Gauss fit to the Lo Gain:   ");
+  PrintUncalibrated(MBadPixelsPix::kDeviatingFFactor,    
+                    "Deviating F-Factor:                     ");
+
+  fCam->SetReadyToSave();
+  fQECam->SetReadyToSave();
+  fBadPixels->SetReadyToSave();
+
+  if (fBlindCam)
+    fBlindCam->SetReadyToSave();
+  if (fPINDiode)
+    fPINDiode->SetReadyToSave();
+
+  //
+  // Finalize calibration statistics
+  //
+  return FinalizeUnsuitablePixels();
+}
+
+// ----------------------------------------------------------------------------------
+//  
+// Retrieves pedestal and pedestal RMS from MPedestalPix 
+// Retrieves total entries from MPedestalCam
+// Sets pedestal*fNumHiGainSamples and pedestal*fNumLoGainSamples in MCalibrationChargePix
+// Sets pedRMS *fSqrtHiGainSamples and pedRMS *fSqrtLoGainSamples in MCalibrationChargePix
+//
+// If the flag MCalibrationPix::IsHiGainSaturation() is set, call also: 
+// - MCalibrationChargePix::CalcLoGainPedestal()
+//
+void MCalibrationChargeCalc::FinalizePedestals(const MPedestalPix &ped, MCalibrationChargePix &cal, const Int_t aidx)
+{
+  
+  //
+  // get the pedestals
+  //
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t prms   = ped.GetPedestalRms();
+  const Int_t   num    = fPedestals->GetNumSlices()*ped.GetNumEvents();
+  
+  //
+  // RMS error set by PedCalcFromLoGain, 0 in case MPedCalcPedRun was used.
+  //
+  const Float_t prmserr = num>0 ? prms/TMath::Sqrt(2.*num) : ped.GetPedestalRmsError();
+
+  //
+  // set them in the calibration camera
+  //
+  if (cal.IsHiGainSaturation())
+    {
+      cal.SetPedestal(pedes   * fNumLoGainSamples,
+                      prms    * fSqrtLoGainSamples,
+                      prmserr * fSqrtLoGainSamples);
+      cal.CalcLoGainPedestal(fNumLoGainSamples);
+    }
+  else
+    {
+
+      cal.SetPedestal(pedes   * fNumHiGainSamples,
+                      prms    * fSqrtHiGainSamples,
+                      prmserr * fSqrtHiGainSamples);
+    }
+  
+}
+
+// ----------------------------------------------------------------------------------------------------
+//
+// Check fit results validity. Bad Pixels flags are set if:
+//
+// 1) Pixel has a mean smaller than fChargeLimit*PedRMS    ( Flag: MBadPixelsPix::kChargeIsPedestal)
+// 2) Pixel has a mean error smaller than fChargeErrLimit  ( Flag: MBadPixelsPix::kChargeErrNotValid)
+// 3) Pixel has mean smaller than fChargeRelVarLimit times its mean error 
+//                                                         ( Flag: MBadPixelsPix::kChargeRelErrNotValid)
+// 4) Pixel has a sigma bigger than its Pedestal RMS       ( Flag: MBadPixelsPix::kChargeSigmaNotValid )
+// 
+// Further returns if flags: MBadPixelsPix::kUnsuitableRun is set
+// 
+// Calls MCalibrationChargePix::CalcReducedSigma() and sets flag:  MBadPixelsPix::kChargeIsPedestal 
+//       and returns kFALSE if not succesful. 
+// 
+// Calls MCalibrationChargePix::CalcFFactor() and sets flag: MBadPixelsPix::kDeviatingNumPhes) 
+//       and returns kFALSE if not succesful.
+//
+// Calls MCalibrationChargePix::CalcConvFFactor()and sets flag: MBadPixelsPix::kDeviatingNumPhes) 
+//       and returns kFALSE if not succesful.
+//
+Bool_t MCalibrationChargeCalc::FinalizeCharges(MCalibrationChargePix &cal, MBadPixelsPix &bad, const char* what)
+{
+
+  if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+    return kFALSE;
+
+  const TString desc = Form("%7s%4d: ", what, cal.GetPixId());
+
+  if (cal.GetMean()<0)
+  {
+      *fLog << warn << desc << "Charge not fitted." << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeIsPedestal);
+      return kFALSE;
+  }
+
+  if (cal.GetSigma()<0)
+  {
+      *fLog << warn << desc << "Charge Sigma invalid." << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeIsPedestal);
+      return kFALSE;
+  }
+
+  if (cal.GetMean() < fChargeLimit*cal.GetPedRms())
+    {
+      *fLog << warn << desc
+            << Form("Fitted Charge: %5.2f < %2.1f",cal.GetMean(),fChargeLimit)
+            << Form(" * Pedestal RMS %5.2f",cal.GetPedRms()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeIsPedestal);
+    }
+  
+   if (cal.GetMean() < fChargeRelErrLimit*cal.GetMeanErr()) 
+    {
+      *fLog << warn << desc
+            << Form("Fitted Charge: %4.2f < %2.1f",cal.GetMean(),fChargeRelErrLimit)
+            << Form(" * its error %4.2f",cal.GetMeanErr()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeRelErrNotValid );
+    }
+
+  if (cal.GetSigma() < cal.GetPedRms())
+    {
+      *fLog << warn << desc << "Sigma of Fitted Charge: "
+            << Form("%6.2f <",cal.GetSigma()) << " Ped. RMS="
+            << Form("%5.2f", cal.GetPedRms()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeSigmaNotValid );
+      return kFALSE;
+    }
+
+  if (!cal.CalcReducedSigma())
+    {
+      *fLog << warn << desc << "Could not calculate the reduced sigma" << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeSigmaNotValid );
+      return kFALSE;
+    }
+
+  if (!cal.CalcFFactor())
+    {
+      *fLog << warn << desc << "Could not calculate the F-Factor"<< endl;
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+      return kFALSE;
+    }
+
+  if (cal.GetPheFFactorMethod() < 0.)
+    {
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+      cal.SetFFactorMethodValid(kFALSE);
+      return kFALSE;
+    }
+
+  if (!cal.CalcConvFFactor())
+    {
+      *fLog << warn << desc << "Could not calculate the Conv. FADC counts to Phes"<< endl;
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      return kFALSE;
+    }
+
+  if (!IsUseExtractorRes())
+    return kTRUE;
+
+  if (!fExtractor)
+    {
+      *fLog << err << "Extractor resolution has been chosen, but no extractor is set. Cannot calibrate." << endl;
+      return kFALSE;
+    }
+
+  const Float_t resinphes = cal.IsHiGainSaturation()
+    ? cal.GetPheFFactorMethod()*fExtractor->GetResolutionPerPheLoGain()
+    : cal.GetPheFFactorMethod()*fExtractor->GetResolutionPerPheHiGain();
+
+  Float_t resinfadc = cal.IsHiGainSaturation()
+    ? resinphes/cal.GetMeanConvFADC2Phe()/cal.GetConversionHiLo()
+    : resinphes/cal.GetMeanConvFADC2Phe();
+
+  if (resinfadc > 3.0*cal.GetPedRms() )
+    {
+      *fLog << warn << desc << "Extractor Resolution " << Form("%5.2f", resinfadc) << " bigger than 3 Pedestal RMS "
+            << Form("%4.2f", cal.GetPedRms()) << endl;
+      resinfadc = 3.0*cal.GetPedRms();
+    }
+
+  if (!cal.CalcReducedSigma(resinfadc))
+    {
+        *fLog << warn << desc << "Could not calculate the reduced sigma" << endl;
+        bad.SetUncalibrated( MBadPixelsPix::kChargeSigmaNotValid );
+        return kFALSE;
+    }
+
+  if (!cal.CalcFFactor())
+    {
+        *fLog << warn << desc << "Could not calculate the F-Factor" << endl;
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+      return kFALSE;
+    }
+
+  if (cal.GetPheFFactorMethod() < 0.)
+    {
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+      cal.SetFFactorMethodValid(kFALSE);
+      return kFALSE;
+    }
+
+  if (!cal.CalcConvFFactor())
+    {
+      *fLog << warn << desc << "Could not calculate the conv. FADC cts to phes" << endl;
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------------------
+//
+// Sets pixel to MBadPixelsPix::kUnsuitableRun, if one of the following flags is set:
+// - MBadPixelsPix::kChargeIsPedestal
+// - MBadPixelsPix::kChargeRelErrNotValid 
+// - MBadPixelsPix::kMeanTimeInFirstBin 
+// - MBadPixelsPix::kMeanTimeInLast2Bins 
+// - MBadPixelsPix::kDeviatingNumPhes
+// - MBadPixelsPix::kHiGainOverFlow
+// - MBadPixelsPix::kLoGainOverFlow
+//
+// Sets pixel to MBadPixelsPix::kUnreliableRun, if one of the following flags is set:
+// - MBadPixelsPix::kChargeSigmaNotValid 
+//
+void MCalibrationChargeCalc::FinalizeBadPixels()
+{
+  
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      if (IsCheckDeadPixels())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kChargeIsPedestal))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun   );
+        }
+/*
+      if (IsCheckExtractionWindow())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kMeanTimeInFirstBin ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+          
+          if (bad.IsUncalibrated( MBadPixelsPix::kMeanTimeInLast2Bins ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+        }
+ */
+      if (IsCheckDeviatingBehavior())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kDeviatingNumPhes ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+        }
+
+      if (IsCheckHistOverflow())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kHiGainOverFlow   ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+
+          if (bad.IsUncalibrated( MBadPixelsPix::kLoGainOverFlow   ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+        }
+
+      if (IsCheckArrivalTimes())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kDeviatingAbsTimeResolution ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+          //if (bad.IsUncalibrated( MBadPixelsPix::kFluctuatingArrivalTimes ))
+          //  bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+        }
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kChargeSigmaNotValid ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+//
+// First loop: Calculate a mean and mean RMS of photo-electrons per area index 
+//             Include only pixels which are not MBadPixelsPix::kUnsuitableRun nor 
+//             MBadPixelsPix::kChargeSigmaNotValid (see FinalizeBadPixels()) and set 
+//             MCalibrationChargePix::SetFFactorMethodValid(kFALSE) in that case.
+//              
+// Second loop: Get mean number of photo-electrons and its RMS including 
+//              only pixels with flag MCalibrationChargePix::IsFFactorMethodValid() 
+//              and further exclude those deviating by more than fPheErrLimit mean 
+//              sigmas from the mean (obtained in first loop). Set 
+//              MBadPixelsPix::kDeviatingNumPhes if excluded.
+//
+//              For the suitable pixels with flag MBadPixelsPix::kChargeSigmaNotValid 
+//              set the number of photo-electrons as the mean number of photo-electrons
+//              calculated in that area index.
+// 
+//              Set weighted mean and variance of photo-electrons per area index in: 
+//              average area pixels of MCalibrationChargeCam (obtained from: 
+//              MCalibrationChargeCam::GetAverageArea() )
+// 
+//              Set weighted mean  and variance of photo-electrons per sector in:
+//              average sector pixels of MCalibrationChargeCam (obtained from: 
+//              MCalibrationChargeCam::GetAverageSector() )
+// 
+//
+// Third loop: Set mean number of photo-electrons and its RMS in the pixels
+//             only excluded as: MBadPixelsPix::kChargeSigmaNotValid 
+// 
+Bool_t MCalibrationChargeCalc::FinalizeFFactorMethod()
+{
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF lowlim        (nareas);
+  TArrayF upplim        (nareas);
+  TArrayD areavars      (nareas);
+  TArrayD areaweights   (nareas);
+  TArrayD sectorweights (nsectors);
+  TArrayD areaphes      (nareas);
+  TArrayD sectorphes    (nsectors);
+  TArrayI numareavalid  (nareas);
+  TArrayI numsectorvalid(nsectors);
+
+  //
+  // First loop: Get mean number of photo-electrons and the RMS
+  //             The loop is only to recognize later pixels with very deviating numbers
+  //
+  MHCamera camphes(*fGeom,"Camphes","Phes in Camera");
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+      
+      if (!pix.IsFFactorMethodValid())
+        continue;
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          pix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      if (bad.IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid))
+        continue;
+
+      if (!IsUseUnreliables())
+        if (bad.IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+          continue;
+
+      const Float_t nphe  = pix.GetPheFFactorMethod();
+      const Int_t   aidx  = (*fGeom)[i].GetAidx();
+      camphes.Fill(i,nphe);
+      camphes.SetUsed(i);
+      areaphes    [aidx] += nphe;
+      areavars    [aidx] += nphe*nphe;
+      numareavalid[aidx] ++;
+    } 
+
+  for (Int_t i=0; i<nareas; i++)
+    {
+      if (numareavalid[i] == 0)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid number of photo-electrons found "
+                << "in area index: " << i << endl;
+          continue;
+        }
+
+      if (numareavalid[i] == 1)
+        areavars[i] = 0.;
+      else
+        {
+          areavars[i] = (areavars[i] - areaphes[i]*areaphes[i]/numareavalid[i]) / (numareavalid[i]-1);
+          areaphes[i] /= numareavalid[i];
+        }
+      
+      if (areavars[i] < 0.)
+        {
+          *fLog << warn << "Area   " << setw(4) << i << ": No pixels with valid variance of photo-electrons found." << endl;
+          continue;
+        }
+
+      // FIXME: WHAT IS THIS FOR? It is overwritten!
+      lowlim[i] = areaphes[i] - fPheErrLowerLimit*TMath::Sqrt(areavars[i]);
+      upplim[i] = areaphes[i] + fPheErrUpperLimit*TMath::Sqrt(areavars[i]);
+ 
+
+      TH1D *hist = camphes.ProjectionS(TArrayI(),TArrayI(1,&i),"_py",100);
+      hist->Fit("gaus","Q0");
+      const Float_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+      const Float_t sigma = hist->GetFunction("gaus")->GetParameter(2);
+      const Int_t   ndf   = hist->GetFunction("gaus")->GetNDF();
+
+      if (IsDebug())
+        hist->DrawClone();
+
+      if (ndf < 5)
+        {
+            *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of photo-electrons " << endl;
+            *fLog << " in the camera with area index: " << i << endl;
+            *fLog << " Number of dof.: " << ndf << " is smaller than 5 " << endl;
+            *fLog << " Will use the simple mean and rms " << endl;
+            delete hist;
+            SetPheFitOK(i,kFALSE);
+            continue;
+        }
+      
+      const Double_t prob = hist->GetFunction("gaus")->GetProb();
+
+      if (prob < 0.001)
+        {
+            *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of photo-electrons " << endl;
+            *fLog << " in the camera with area index: " << i << endl;
+            *fLog << " Fit probability " << prob << " is smaller than 0.001 " << endl;
+            *fLog << " Will use the simple mean and rms " << endl;
+            delete hist;
+            SetPheFitOK(i,kFALSE);
+            continue;
+        }
+      
+      if (mean < 0.)
+        {
+            *fLog << inf  << "Area   " << setw(4) << i << ": Fitted mean number of phe smaller 0." << endl;
+            *fLog << warn << "Area   " << setw(4) << i << ": Will use the simple mean and rms " << endl;
+            SetPheFitOK(i,kFALSE);
+            delete hist;
+            continue;
+        }
+      
+      *fLog << inf << "Area   " << setw(4) << i << ": Mean number of phes: "
+            << Form("%7.2f+-%6.2f",mean,sigma) << endl;
+
+      lowlim[i] = mean - fPheErrLowerLimit*sigma;
+      upplim[i] = mean + fPheErrUpperLimit*sigma;
+
+      if (lowlim[i]<1)
+          lowlim[i] = 1;
+
+      delete hist;
+
+      SetPheFitOK(i,kTRUE);
+    }
+
+  *fLog << endl;
+
+  numareavalid.Reset();
+  areaphes    .Reset();
+  areavars    .Reset();
+  //
+  // Second loop: Get mean number of photo-electrons and its RMS excluding 
+  //              pixels deviating by more than fPheErrLimit sigma. 
+  //              Set the conversion factor FADC counts to photo-electrons
+  // 
+  for (Int_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+
+      if (!pix.IsFFactorMethodValid())
+        continue;
+
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      if (bad.IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid))
+        continue;
+
+      if (!IsUseUnreliables())
+        if (bad.IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+          continue;
+
+      const Float_t nvar  = pix.GetPheFFactorMethodVar();
+      if (nvar <= 0.)
+        {
+          pix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+      
+      const Int_t   aidx   = (*fGeom)[i].GetAidx();
+      const Int_t   sector = (*fGeom)[i].GetSector();
+      const Float_t area   = (*fGeom)[i].GetA();
+      const Float_t nphe   = pix.GetPheFFactorMethod();
+
+      if ( nphe < lowlim[aidx] || nphe > upplim[aidx] )
+        {
+            *fLog << warn << "Pixel  " << setw(4) << i << ": Num of phe "
+                << Form("%7.2f out of +%3.1f-%3.1f sigma limit ",nphe,fPheErrUpperLimit,fPheErrLowerLimit)
+                << Form("[%7.2f,%7.2f]",lowlim[aidx],upplim[aidx]) << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingNumPhes );
+
+          if (IsCheckDeviatingBehavior())
+                bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+          continue;
+        }
+      
+      areaweights   [aidx]   += nphe*nphe;
+      areaphes      [aidx]   += nphe;
+      numareavalid  [aidx]   ++;
+
+      if (aidx == 0)
+        fNumInnerFFactorMethodUsed++;
+
+      sectorweights [sector] += nphe*nphe/area/area;
+      sectorphes    [sector] += nphe/area;
+      numsectorvalid[sector] ++;
+    }
+
+  *fLog << endl;
+
+  for (Int_t aidx=0; aidx<nareas; aidx++)
+    {
+
+      MCalibrationChargePix &apix = (MCalibrationChargePix&)fCam->GetAverageArea(aidx);
+
+      if (numareavalid[aidx] == 1)
+        areaweights[aidx] = 0.;
+      else if (numareavalid[aidx] == 0)
+        {
+          areaphes[aidx]    = -1.;
+          areaweights[aidx] = -1.;
+        }
+      else
+        {
+          areaweights[aidx] = (areaweights[aidx] - areaphes[aidx]*areaphes[aidx]/numareavalid[aidx])
+                            / (numareavalid[aidx]-1);
+          areaphes[aidx]    /=  numareavalid[aidx];
+        }
+
+      if (areaweights[aidx] < 0. || areaphes[aidx] <= 0.)
+        {
+          *fLog << warn << "Area   " << setw(4) << aidx << ": Mean number phes could not be calculated: "
+                << " Mean: "  << areaphes[aidx] 
+                << " Var: " << areaweights[aidx]    << endl;
+          apix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      *fLog << inf << "Area   " << setw(4) << aidx << ": Average total phes: "
+            << Form("%7.2f +- %6.2f",areaphes[aidx],TMath::Sqrt(areaweights[aidx])) << endl;
+
+      apix.SetPheFFactorMethod   ( areaphes[aidx] );
+      apix.SetPheFFactorMethodVar( areaweights[aidx] / numareavalid[aidx] );      
+      apix.SetFFactorMethodValid ( kTRUE );
+
+    }
+
+  *fLog << endl;
+
+  for (Int_t sector=0; sector<nsectors; sector++)
+    {
+
+      if (numsectorvalid[sector] == 1)
+        sectorweights[sector] = 0.;
+      else if (numsectorvalid[sector] == 0)
+        {
+          sectorphes[sector]    = -1.;
+          sectorweights[sector] = -1.;
+        }
+      else
+        {
+          sectorweights[sector] = (sectorweights[sector] 
+                                   - sectorphes[sector]*sectorphes[sector]/numsectorvalid[sector]
+                                  ) 
+                                / (numsectorvalid[sector]-1.);
+          sectorphes[sector]     /=  numsectorvalid[sector];
+        }
+      
+      MCalibrationChargePix &spix = (MCalibrationChargePix&)fCam->GetAverageSector(sector);
+
+      if (sectorweights[sector] < 0. || sectorphes[sector] <= 0.)
+        {
+          *fLog << warn << "Sector " << setw(4) << sector
+                <<": Mean number phes/area could not be calculated:"
+                << " Mean: "  << sectorphes[sector] << " Var: " << sectorweights[sector]    << endl;
+          spix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      *fLog << inf << "Sector " << setw(4) << sector 
+            << ": Avg number phes/mm^2: "
+            << Form("%5.3f+-%4.3f",sectorphes[sector],TMath::Sqrt(sectorweights[sector]))
+            << endl;
+
+      spix.SetPheFFactorMethod   ( sectorphes[sector] );
+      spix.SetPheFFactorMethodVar( sectorweights[sector] / numsectorvalid[sector]);      
+      spix.SetFFactorMethodValid ( kTRUE );
+
+    }
+
+  //
+  // Third loop: Set mean number of photo-electrons and its RMS in the pixels
+  //             only excluded as: MBadPixelsPix::kChargeSigmaNotValid 
+  // 
+  for (Int_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      if (bad.IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid))
+        {
+          const Int_t            aidx = (*fGeom)[i].GetAidx();
+          MCalibrationChargePix &apix = (MCalibrationChargePix&)fCam->GetAverageArea(aidx);
+
+          pix.SetPheFFactorMethod   ( apix.GetPheFFactorMethod()    );
+          pix.SetPheFFactorMethodVar( apix.GetPheFFactorMethodVar() );
+
+          if (!pix.CalcConvFFactor())
+            {
+              *fLog << warn << GetDescriptor() 
+                    << "Pixel  " << setw(4) << pix.GetPixId()
+                    <<": Could not calculate the Conv. FADC counts to Phes"
+                    << endl;
+              bad.SetUncalibrated( MBadPixelsPix::kDeviatingNumPhes );
+              if (IsCheckDeviatingBehavior())
+                bad.SetUnsuitable  ( MBadPixelsPix::kUnsuitableRun    );
+            }
+
+        }
+    }
+  
+  return kTRUE;
+}
+
+
+
+// ------------------------------------------------------------------------
+//
+// Returns kFALSE if pointer to MCalibrationBlindCam is NULL
+//
+// The check returns kFALSE if:
+//
+// 1) fLambda and fLambdaCheck are separated relatively to each other by more than fLambdaCheckLimit
+// 2) BlindPixel has an fLambdaErr greater than fLambdaErrLimit
+// 
+// Calls:
+// - MCalibrationBlindPix::CalcFluxInsidePlexiglass()
+//
+Bool_t MCalibrationChargeCalc::FinalizeBlindCam()
+{
+  if (!fBlindCam)
+    return kFALSE;  
+
+  Int_t nvalid  = 0;
+
+  for (Int_t i=0; i<fBlindCam->GetSize(); i++)
+    {
+      
+      MCalibrationBlindPix &blindpix = (MCalibrationBlindPix&)(*fBlindCam)[i];
+
+      if (!blindpix.IsValid())
+        continue;
+      
+      const Float_t lambda      = blindpix.GetLambda();
+      const Float_t lambdaerr   = blindpix.GetLambdaErr();
+      const Float_t lambdacheck = blindpix.GetLambdaCheck();
+
+      if (2.*(lambdacheck-lambda)/(lambdacheck+lambda) > fLambdaCheckLimit)
+        {
+          *fLog << warn << "BlindPix " << i << ": Lambda="
+                << Form("%4.2f", lambda) << " and Lambda-Check="
+                << Form("%4.2f", lambdacheck) << " differ by more than "
+                << Form("%4.2f", fLambdaCheckLimit) << endl;
+          blindpix.SetValid(kFALSE);
+          continue;
+        }
+      
+      if (lambdaerr > fLambdaErrLimit) 
+        {
+            *fLog << warn << "BlindPix " << i << ": Error of Fitted Lambda="
+                << Form("%4.2f", lambdaerr) << " is greater than "
+                << Form("%4.2f", fLambdaErrLimit) << endl;
+          blindpix.SetValid(kFALSE);
+          continue;
+        }
+      
+      if (!blindpix.CalcFluxInsidePlexiglass())
+        {
+          *fLog << warn << "Could not calculate the flux of photons from Blind Pixel Nr." << i << endl;
+          blindpix.SetValid(kFALSE);
+          continue;
+        }
+      
+      nvalid++;
+    }
+
+  if (!nvalid)
+    return kFALSE;
+  
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns kFALSE if pointer to MCalibrationChargePINDiode is NULL
+//
+// The check returns kFALSE if:
+//
+// 1) PINDiode has a fitted charge smaller than fChargeLimit*PedRMS
+// 2) PINDiode has a fit error smaller than fChargeErrLimit
+// 3) PINDiode has a fitted charge smaller its fChargeRelErrLimit times its charge error
+// 4) PINDiode has a charge sigma smaller than its Pedestal RMS
+// 
+// Calls:
+// - MCalibrationChargePINDiode::CalcFluxOutsidePlexiglass()
+//
+Bool_t MCalibrationChargeCalc::FinalizePINDiode()
+{
+
+  if (!fPINDiode)
+    return kFALSE;  
+
+  if (fPINDiode->GetMean() < fChargeLimit*fPINDiode->GetPedRms())
+    {
+      *fLog << warn << "PINDiode   : Fitted Charge is smaller than "
+            << fChargeLimit << " Pedestal RMS." << endl;
+      return kFALSE;
+    }
+  
+  if (fPINDiode->GetMeanErr() < fChargeErrLimit) 
+    {
+        *fLog << warn << "PINDiode   : Error of Fitted Charge is smaller than "
+            << fChargeErrLimit << endl;
+      return kFALSE;
+    }
+      
+  if (fPINDiode->GetMean() < fChargeRelErrLimit*fPINDiode->GetMeanErr()) 
+    {
+        *fLog << warn << "PINDiode   : Fitted Charge is smaller than "
+            << fChargeRelErrLimit << "* its error" << endl;
+      return kFALSE;
+    }
+      
+  if (fPINDiode->GetSigma() < fPINDiode->GetPedRms())
+    {
+        *fLog << warn << "PINDiode   : Sigma of Fitted Charge smaller than Pedestal RMS" << endl;
+      return kFALSE;
+    }
+
+
+  if (!fPINDiode->CalcFluxOutsidePlexiglass())
+    {
+        *fLog << warn << "PINDiode   : Could not calculate the flux of photons, "
+            << "will skip PIN Diode Calibration " << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Calculate the average number of photons outside the plexiglass with the 
+// formula: 
+// 
+// av.Num.photons(area index) = av.Num.Phes(area index) 
+//                            / MCalibrationQEPix::GetDefaultQE(fPulserColor) 
+//                            / MCalibrationQEPix::GetPMTCollectionEff()
+//                            / MCalibrationQEPix::GetLightGuidesEff(fPulserColor)
+//                            / MCalibrationQECam::GetPlexiglassQE()
+//
+// Calculate the variance on the average number of photons assuming that the error on the 
+// Quantum efficiency is reduced by the number of used inner pixels, but the rest of the 
+// values keeps it ordinary error since it is systematic.
+//
+// Loop over pixels: 
+//
+// - Continue, if not MCalibrationChargePix::IsFFactorMethodValid() and set:
+//                    MCalibrationQEPix::SetFFactorMethodValid(kFALSE,fPulserColor)
+//
+// - Call MCalibrationChargePix::CalcMeanFFactor(av.Num.photons) and set: 
+//        MCalibrationQEPix::SetFFactorMethodValid(kFALSE,fPulserColor) if not succesful
+//
+// - Calculate the quantum efficiency with the formula:
+// 
+//   QE = ( Num.Phes / av.Num.photons ) * MGeomCam::GetPixRatio()
+//
+// - Set QE in MCalibrationQEPix::SetQEFFactor ( QE, fPulserColor );
+//
+// - Set Variance of QE in  MCalibrationQEPix::SetQEFFactorVar ( Variance, fPulserColor );
+// - Set bit MCalibrationQEPix::SetFFactorMethodValid(kTRUE,fPulserColor) 
+//
+// - Call MCalibrationQEPix::UpdateFFactorMethod()
+//
+void MCalibrationChargeCalc::FinalizeFFactorQECam()
+{
+
+  if (fNumInnerFFactorMethodUsed < 2)
+    {
+      *fLog << warn << GetDescriptor() 
+            << ": Could not calculate F-Factor Method: Less than 2 inner pixels valid! " << endl;
+      return;
+    }
+  
+  MCalibrationChargePix &avpix = (MCalibrationChargePix&)fCam->GetAverageArea(0);
+  MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    fQECam->GetAverageArea(0);
+
+  if (IsDebug())
+    *fLog << dbginf << "External Phes: " << fExternalNumPhes
+          << " Internal Phes: " << avpix.GetPheFFactorMethod() << endl;
+
+  const Float_t avphotons   = ( IsUseExternalNumPhes()
+                                ? fExternalNumPhes
+                                : avpix.GetPheFFactorMethod() )
+                           / qepix.GetDefaultQE(fPulserColor) 
+                           / qepix.GetPMTCollectionEff()
+                           / qepix.GetLightGuidesEff(fPulserColor)
+                           / fQECam->GetPlexiglassQE();
+
+  const Float_t avphotrelvar = ( IsUseExternalNumPhes()
+                                 ? fExternalNumPhesRelVar
+                                 : avpix.GetPheFFactorMethodRelVar() )
+                            + qepix.GetDefaultQERelVar(fPulserColor) / fNumInnerFFactorMethodUsed
+                            + qepix.GetPMTCollectionEffRelVar()
+                            + qepix.GetLightGuidesEffRelVar(fPulserColor)
+                            + fQECam->GetPlexiglassQERelVar();
+
+  const UInt_t nareas   = fGeom->GetNumAreas();
+
+  //
+  // Set the results in the MCalibrationChargeCam
+  //
+  fCam->SetNumPhotonsFFactorMethod (avphotons);
+
+  if (avphotrelvar > 0.)
+    fCam->SetNumPhotonsFFactorMethodErr(TMath::Sqrt( avphotrelvar * avphotons * avphotons));
+
+  TArrayF lowlim           (nareas);
+  TArrayF upplim           (nareas);
+  TArrayD avffactorphotons (nareas);
+  TArrayD avffactorphotvar (nareas);
+  TArrayI numffactor       (nareas);
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+
+  MHCamera camffactor(*fGeom,"Camffactor","F-Factor in Camera");
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*fCam)[i];
+      MCalibrationQEPix     &qpix  = (MCalibrationQEPix&)    (*fQECam)[i];
+
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+
+      const Float_t photons = avphotons / fGeom->GetPixRatio(i);
+      const Float_t qe      = pix.GetPheFFactorMethod() / photons ;
+
+      const Float_t qerelvar = avphotrelvar +  pix.GetPheFFactorMethodRelVar();
+
+      qpix.SetQEFFactor    ( qe            , fPulserColor );
+      qpix.SetQEFFactorVar ( qerelvar*qe*qe, fPulserColor );
+      qpix.SetFFactorMethodValid(  kTRUE   , fPulserColor );
+
+      if (!qpix.UpdateFFactorMethod( fQECam->GetPlexiglassQE() ))
+        *fLog << warn << GetDescriptor() 
+              << ": Cannot update Quantum efficiencies with the F-Factor Method" << endl;
+
+      //
+      // The following pixels are those with deviating sigma, but otherwise OK, 
+      // probably those with stars during the pedestal run, but not the cal. run.
+      //
+      if (!pix.CalcMeanFFactor( photons , avphotrelvar ))
+        {
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingFFactor );
+          if (IsCheckDeviatingBehavior())
+            bad.SetUnsuitable  ( MBadPixelsPix::kUnreliableRun    );
+          continue;
+        }
+
+      const Int_t aidx = (*fGeom)[i].GetAidx();
+      const Float_t ffactor = pix.GetMeanFFactorFADC2Phot();
+
+      camffactor.Fill(i,ffactor);
+      camffactor.SetUsed(i);
+
+      avffactorphotons[aidx] += ffactor;
+      avffactorphotvar[aidx] += ffactor*ffactor;
+      numffactor[aidx]++;
+    }
+
+  for (UInt_t i=0; i<nareas; i++)
+    {
+
+      if (numffactor[i] == 0)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid total F-Factor found "
+                << "in area index: " << i << endl;
+          continue;
+        }
+
+      avffactorphotvar[i] = (avffactorphotvar[i] - avffactorphotons[i]*avffactorphotons[i]/numffactor[i]) 
+                          / (numffactor[i]-1.);
+      avffactorphotons[i] = avffactorphotons[i] / numffactor[i];
+
+      if (avffactorphotvar[i] < 0.)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid variance of total F-Factor found "
+                << "in area index: " << i << endl;
+          continue;
+        }
+
+      lowlim  [i] = 1.;   // Lowest known F-Factor of a PMT
+      upplim  [i] = avffactorphotons[i] + fFFactorErrLimit*TMath::Sqrt(avffactorphotvar[i]);
+
+      TArrayI area(1);
+      area[0] = i;
+
+      TH1D *hist = camffactor.ProjectionS(TArrayI(),area,"_py",100);
+      hist->Fit("gaus","Q0");
+      const Float_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+      const Float_t sigma = hist->GetFunction("gaus")->GetParameter(2);
+      const Int_t   ndf   = hist->GetFunction("gaus")->GetNDF();
+
+      if (IsDebug())
+        camffactor.DrawClone();
+
+      if (ndf < 2)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the F-Factor " << endl;
+          *fLog << " in the camera with area index: " << i << endl;
+          *fLog << " Number of dof.: " << ndf << " is smaller than 2 " << endl;
+          *fLog << " Will use the simple mean and rms." << endl;
+          delete hist;
+          SetFFactorFitOK(i,kFALSE);
+          continue;
+        }
+      
+      const Double_t prob = hist->GetFunction("gaus")->GetProb();
+
+      if (prob < 0.001)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the F-Factor " << endl;
+          *fLog << " in the camera with area index: " << i << endl;
+          *fLog << " Fit probability " << prob << " is smaller than 0.001 " << endl;
+          *fLog << " Will use the simple mean and rms." << endl;
+          delete hist;
+          SetFFactorFitOK(i,kFALSE);
+         continue;
+        }
+
+      *fLog << inf << "Area   " << setw(4) << i <<": Mean F-Factor :"
+          << Form("%4.2f+-%4.2f",mean,sigma) << endl;
+
+      lowlim  [i] = 1.;
+      upplim  [i] = mean  + fFFactorErrLimit*sigma;
+
+      delete hist;
+
+      SetFFactorFitOK(i,kTRUE);
+    }
+  
+  *fLog << endl;
+  
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      const Float_t ffactor = pix.GetMeanFFactorFADC2Phot();
+      const Int_t   aidx   = (*fGeom)[i].GetAidx();
+
+      if ( ffactor < lowlim[aidx] || ffactor > upplim[aidx] )
+        {
+            *fLog << warn << "Pixel  " << setw(4) << i<< ": Overall F-Factor "
+                << Form("%5.2f",ffactor) << " out of range ["
+                << Form("%5.2f,%5.2f",lowlim[aidx],upplim[aidx]) << "]" << endl;
+
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingFFactor );
+          if (IsCheckDeviatingBehavior())
+            bad.SetUnsuitable  ( MBadPixelsPix::kUnreliableRun    );
+        }
+    }
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix  = (MCalibrationChargePix&)(*fCam)[i];
+      MCalibrationQEPix     &qpix = (MCalibrationQEPix&)(*fQECam)[i];
+
+      if ((*fBadPixels)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          qpix.SetFFactorMethodValid(kFALSE,fPulserColor);
+          pix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+    }
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Loop over pixels: 
+//
+// - Continue, if not MCalibrationBlindPix::IsFluxInsidePlexiglassAvailable() and set:
+//                    MCalibrationQEPix::SetBlindPixelMethodValid(kFALSE,fPulserColor)
+//
+// - Calculate the quantum efficiency with the formula:
+// 
+//   QE =  Num.Phes / MCalibrationBlindPix::GetFluxInsidePlexiglass() 
+//        / MGeomPix::GetA() * MCalibrationQECam::GetPlexiglassQE()
+//
+// - Set QE in MCalibrationQEPix::SetQEBlindPixel ( QE, fPulserColor );
+// - Set Variance of QE in  MCalibrationQEPix::SetQEBlindPixelVar ( Variance, fPulserColor );
+// - Set bit MCalibrationQEPix::SetBlindPixelMethodValid(kTRUE,fPulserColor) 
+//
+// - Call MCalibrationQEPix::UpdateBlindPixelMethod()
+//
+void MCalibrationChargeCalc::FinalizeBlindPixelQECam()
+{
+
+  if (!fBlindCam)
+    return;
+
+  //
+  // Set the results in the MCalibrationChargeCam
+  //
+  if (!fBlindCam->IsFluxInsidePlexiglassAvailable())
+    {
+  
+      const Float_t photons = fBlindCam->GetFluxInsidePlexiglass() * (*fGeom)[0].GetA()
+                           / fQECam->GetPlexiglassQE();
+      fCam->SetNumPhotonsBlindPixelMethod(photons);
+          
+      const Float_t photrelvar = fBlindCam->GetFluxInsidePlexiglassRelVar()
+                              + fQECam->GetPlexiglassQERelVar();
+ 
+      if (photrelvar > 0.)
+        fCam->SetNumPhotonsBlindPixelMethodErr(TMath::Sqrt( photrelvar * photons * photons));
+    }
+  
+  //
+  //  With the knowledge of the overall photon flux, calculate the 
+  //  quantum efficiencies after the Blind Pixel and PIN Diode method
+  //
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationQEPix &qepix = (MCalibrationQEPix&)(*fQECam)[i];
+      
+      if (!fBlindCam->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];
+      MGeom &geo = (*fGeom)[i];
+
+      const Float_t qe        = pix.GetPheFFactorMethod() 
+                             / fBlindCam->GetFluxInsidePlexiglass()
+                             / geo.GetA() 
+                             * fQECam->GetPlexiglassQE();
+
+      const Float_t qerelvar = fBlindCam->GetFluxInsidePlexiglassRelVar()
+                               + fQECam->GetPlexiglassQERelVar()
+                               + pix.GetPheFFactorMethodRelVar();
+
+      qepix.SetQEBlindPixel    ( qe            , fPulserColor );
+      qepix.SetQEBlindPixelVar ( qerelvar*qe*qe, fPulserColor );      
+      qepix.SetBlindPixelMethodValid(  kTRUE   , fPulserColor );
+
+      if (!qepix.UpdateBlindPixelMethod( fQECam->GetPlexiglassQE()))
+        *fLog << warn << GetDescriptor() 
+              << ": Cannot update Quantum efficiencies with the Blind Pixel Method" << endl;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Loop over pixels: 
+//
+// - Continue, if not MCalibrationChargePINDiode::IsFluxOutsidePlexiglassAvailable() and set:
+//                    MCalibrationQEPix::SetPINDiodeMethodValid(kFALSE,fPulserColor)
+//
+// - Calculate the quantum efficiency with the formula:
+// 
+//   QE =  Num.Phes / MCalibrationChargePINDiode::GetFluxOutsidePlexiglass() / MGeomPix::GetA()
+//
+// - Set QE in MCalibrationQEPix::SetQEPINDiode ( QE, fPulserColor );
+// - Set Variance of QE in  MCalibrationQEPix::SetQEPINDiodeVar ( Variance, fPulserColor );
+// - Set bit MCalibrationQEPix::SetPINDiodeMethodValid(kTRUE,fPulserColor) 
+//
+// - Call MCalibrationQEPix::UpdatePINDiodeMethod()
+//
+void MCalibrationChargeCalc::FinalizePINDiodeQECam()
+{
+  
+  const UInt_t npixels  = fGeom->GetNumPixels();
+
+  if (!fPINDiode)
+    return;
+
+  //
+  //  With the knowledge of the overall photon flux, calculate the 
+  //  quantum efficiencies after the PIN Diode method
+  //
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationQEPix &qepix = (MCalibrationQEPix&)(*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];
+      MGeom &geo = (*fGeom)[i];
+
+      const Float_t qe       =  pix.GetPheFFactorMethod()
+                               / fPINDiode->GetFluxOutsidePlexiglass() 
+                               / geo.GetA();
+
+      const Float_t qerelvar = fPINDiode->GetFluxOutsidePlexiglassRelVar() + pix.GetPheFFactorMethodRelVar();
+
+      qepix.SetQEPINDiode    ( qe            , fPulserColor );
+      qepix.SetQEPINDiodeVar ( qerelvar*qe*qe, fPulserColor );      
+      qepix.SetPINDiodeMethodValid(  kTRUE   , fPulserColor );
+
+      if (!qepix.UpdatePINDiodeMethod())
+        *fLog << warn << GetDescriptor() 
+              << ": Cannot update Quantum efficiencies with the PIN Diode Method" << endl;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Loop over pixels: 
+//
+// - Call MCalibrationQEPix::UpdateCombinedMethod()
+//
+void MCalibrationChargeCalc::FinalizeCombinedQECam()
+{
+  
+  const UInt_t npixels  = fGeom->GetNumPixels();
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationQEPix &qepix = (MCalibrationQEPix&)(*fQECam)[i];
+
+      if (!(*fBadPixels)[i].IsUnsuitable (MBadPixelsPix::kUnsuitableRun))
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      qepix.UpdateCombinedMethod();
+    }
+}
+
+// -----------------------------------------------------------------------------------------------
+//
+// - Print out statistics about BadPixels of type UnsuitableType_t 
+// - store numbers of bad pixels of each type in fCam
+//
+Bool_t MCalibrationChargeCalc::FinalizeUnsuitablePixels()
+{
+  
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Charge Calibration status:" << endl;
+  *fLog << dec << setfill(' ');
+
+  const Int_t nareas = fGeom->GetNumAreas();
+
+  TArrayI suit(nareas);
+  TArrayI unsuit(nareas);
+  TArrayI unrel(nareas);
+
+  Int_t unsuitcnt=0;
+  Int_t unrelcnt =0;
+
+  // Count number of succesfully calibrated pixels
+  for (Int_t aidx=0; aidx<nareas; aidx++)
+  {
+      suit[aidx]   = fBadPixels->GetNumSuitable(MBadPixelsPix::kUnsuitableRun,   fGeom, aidx);
+      unsuit[aidx] = fBadPixels->GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, fGeom, aidx);
+      unrel[aidx]  = fBadPixels->GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, fGeom, aidx);
+
+      unsuitcnt   += unsuit[aidx];
+      unrelcnt    += unrel[aidx];
+
+      fCam->SetNumUnsuitable(unsuit[aidx], aidx);
+      fCam->SetNumUnreliable(unrel[aidx],  aidx);
+  }
+
+  TArrayI counts(nareas);
+  for (Int_t i=0; i<fCam->GetSize(); i++)
+  {
+      const MCalibrationPix &pix = (*fCam)[i];
+      if (pix.IsHiGainSaturation())
+      {
+          const Int_t aidx = (*fGeom)[i].GetAidx();
+          counts[aidx]++;
+      }
+  }
+
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+  {
+      *fLog << " Successfully calibrated Pixels: Inner: "
+          << Form("%3i",suit[0])   << " Outer: " << Form("%3i",suit[1])   << endl;
+      *fLog << " Uncalibrated Pixels:            Inner: "
+          << Form("%3i",unsuit[0]) << " Outer: " << Form("%3i",unsuit[1]) << endl;
+      *fLog << " Unreliable Pixels:              Inner: "
+          << Form("%3i",unrel[0])  << " Outer: " << Form("%3i",unrel[1])  << endl;
+      *fLog << " High-gain saturated Pixels:     Inner: "
+          << Form("%3i",counts[0]) << " Outer: " << Form("%3i",counts[1]) << endl;
+      *fLog << endl;
+  }
+
+  if (unsuitcnt > fUnsuitablesLimit*fGeom->GetNumPixels())
+  {
+      *fLog << err << "Number of unsuitable pixels: " << 100.*unsuitcnt/fGeom->GetNumPixels()
+          << "% exceeds limit of " << fUnsuitablesLimit*100 << "%" <<  endl;
+      return kFALSE;
+  }
+
+  if (unrelcnt > fUnreliablesLimit*fGeom->GetNumPixels())
+  {
+      *fLog << err << "Relative number of unreliable pixels: " << 100.*unrelcnt/fGeom->GetNumPixels()
+          << "% exceeds limit of " << fUnreliablesLimit*100 << "%" << endl;
+      return kFALSE;
+  }
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------------------------------
+//
+// 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++)
+    {
+      if ((*fBadPixels)[i].IsUncalibrated(typ))
+        {
+          if (fGeom->GetPixRatio(i) == 1.)
+            countinner++;
+          else
+            countouter++;
+        }
+    }
+
+  *fLog << " " << setw(7) << text << "Inner: " << Form("%3i",countinner)
+      << " Outer: " << Form("%3i", countouter) << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the environment for the following data members:
+// - fChargeLimit
+// - fChargeErrLimit
+// - fChargeRelErrLimit
+// - fDebug
+// - fFFactorErrLimit
+// - fLambdaErrLimit
+// - fLambdaCheckErrLimit
+// - fPheErrLimit
+// 
+Int_t MCalibrationChargeCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+  if (IsEnvDefined(env, prefix, "ChargeLimit", print))
+    {
+      SetChargeLimit(GetEnvValue(env, prefix, "ChargeLimit", fChargeLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "ChargeErrLimit", print))
+    {
+      SetChargeErrLimit(GetEnvValue(env, prefix, "ChargeErrLimit", fChargeErrLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "ChargeRelErrLimit", print))
+    {
+      SetChargeRelErrLimit(GetEnvValue(env, prefix, "ChargeRelErrLimit", fChargeRelErrLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "Debug", print))
+    {
+      SetDebug(GetEnvValue(env, prefix, "Debug", IsDebug()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "ArrTimeRmsLimit", print))
+    {
+      SetArrTimeRmsLimit(GetEnvValue(env, prefix, "ArrTimeRmsLimit", fArrTimeRmsLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "FFactorErrLimit", print))
+    {
+      SetFFactorErrLimit(GetEnvValue(env, prefix, "FFactorErrLimit", fFFactorErrLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "LambdaErrLimit", print))
+    {
+      SetLambdaErrLimit(GetEnvValue(env, prefix, "LambdaErrLimit", fLambdaErrLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "LambdaCheckLimit", print))
+    {
+      SetLambdaCheckLimit(GetEnvValue(env, prefix, "LambdaCheckLimit", fLambdaCheckLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckDeadPixels", print))
+    {
+      SetCheckDeadPixels(GetEnvValue(env, prefix, "CheckDeadPixels", IsCheckDeadPixels()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckDeviatingBehavior", print))
+    {
+      SetCheckDeviatingBehavior(GetEnvValue(env, prefix, "CheckDeviatingBehavior", IsCheckDeviatingBehavior()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckExtractionWindow", print))
+    {
+      SetCheckExtractionWindow(GetEnvValue(env, prefix, "CheckExtractionWindow", IsCheckExtractionWindow()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckHistOverflow", print))
+    {
+      SetCheckHistOverflow(GetEnvValue(env, prefix, "CheckHistOverflow", IsCheckHistOverflow()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckOscillations", print))
+    {
+      SetCheckOscillations(GetEnvValue(env, prefix, "CheckOscillations", IsCheckOscillations()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckArrivalTimes", print))
+    {
+      SetCheckArrivalTimes(GetEnvValue(env, prefix, "CheckArrivalTimes", IsCheckArrivalTimes()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "PheErrLowerLimit", print))
+    {
+      SetPheErrLowerLimit(GetEnvValue(env, prefix, "PheErrLowerLimit", fPheErrLowerLimit));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "PheErrUpperLimit", print))
+    {
+      SetPheErrUpperLimit(GetEnvValue(env, prefix, "PheErrUpperLimit", fPheErrUpperLimit));
+      rc = kTRUE;
+    }
+   if (IsEnvDefined(env, prefix, "UseExtractorRes", print))
+     {
+       SetUseExtractorRes(GetEnvValue(env, prefix, "UseExtractorRes", IsUseExtractorRes()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "UseUnreliables", print))
+    {
+      SetUseUnreliables(GetEnvValue(env, prefix, "UseUnreliables", IsUseUnreliables()));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "UseExternalNumPhes", print))
+    {
+      SetUseExternalNumPhes(GetEnvValue(env, prefix, "UseExternalNumPhes", IsUseExternalNumPhes()));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "UnsuitablesLimit", print))
+    {
+      SetUnsuitablesLimit(GetEnvValue(env, prefix, "UnsuitablesLimit", fUnsuitablesLimit));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "UnreliablesLimit", print))
+    {
+       SetUnreliablesLimit(GetEnvValue(env, prefix, "UnreliablesLimit", fUnreliablesLimit));
+       rc = kTRUE;
+     }
+ 
+
+  return rc;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCalc.h	(revision 17960)
@@ -0,0 +1,223 @@
+#ifndef MARS_MCalibrationChargeCalc
+#define MARS_MCalibrationChargeCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPattern;
+class MPedestalCam;
+class MPedestalPix;
+class MCalibrationChargePINDiode;
+class MHCalibrationChargeBlindCam;
+class MCalibrationBlindCam;
+class MCalibrationChargePix;
+class MCalibrationChargeCam;
+class MHCalibrationChargeCam;
+class MCalibrationQECam;
+class MGeomCam;
+class MExtractedSignalCam;
+class MBadPixelsCam;
+class MExtractor;
+
+class MCalibrationChargeCalc : public MTask
+{
+private:
+
+  static const Float_t fgChargeLimit;          //! Default for fChargeLimit        (now set to: 2.5)
+  static const Float_t fgChargeErrLimit;       //! Default for fChargeErrLimit     (now set to: 0.)
+  static const Float_t fgChargeRelErrLimit;    //! Default for fChargeRelErrLimit  (now set to: 1.)
+  static const Float_t fgLambdaCheckLimit;     //! Default for fLambdaCheckLimit   (now set to: 0.2)
+  static const Float_t fgLambdaErrLimit;       //! Default for fLabmdaErrLimit     (now set to: 0.5)
+  static const Float_t fgPheErrLowerLimit;     //! Default for fPheErrLowerLimit   (now set to: 9.0)
+  static const Float_t fgPheErrUpperLimit;     //! Default for fPheErrUpperLimit   (now set to: 4.5)
+  static const Float_t fgFFactorErrLimit;      //! Default for fFFactorErrLimit    (now set to: 4.5)
+  static const Float_t fgArrTimeRmsLimit;      //! Default for fArrTimeRmsLimit    (now set to: 3.5)
+  static const Float_t fgUnsuitablesLimit;     //! Default for fUnsuitableLimit    (now set to: 0.1)
+  static const Float_t fgUnreliablesLimit;     //! Default for fUnreliableLimit    (now set to: 0.3)
+ 
+  static const char *fgNamePedestalCam;      //! "MPedestalCam"
+  
+  // Variables
+  Float_t fArrTimeRmsLimit;                    // Limit acceptance RMS of absolute arrival times
+  Float_t fChargeLimit;                        // Limit acceptance mean charge  (in units of PedRMS)
+  Float_t fChargeErrLimit;                     // Limit acceptance charge error (in abs. numbers)
+  Float_t fChargeRelErrLimit;                  // Limit acceptance rel. error mean (in abs. numbers)
+  Float_t fFFactorErrLimit;                    // Limit acceptance F-Factor w.r.t. area idx mean
+  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 fPheErrLowerLimit;                   // Lower limit acceptance nr. phe's w.r.t. area idx mean (in sigmas)
+  Float_t fPheErrUpperLimit;                   // Upper 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 
+  Float_t fUnsuitablesLimit;                   // Limit for relative number of unsuitable pixels
+  Float_t fUnreliablesLimit;                   // Limit for relative number of unreliable pixels
+
+  Float_t fExternalNumPhes;                    // External mean number of photo-electrons set from outside
+  Float_t fExternalNumPhesRelVar;              // External rel. var. number of photo-electrons set from outside  
+
+  MCalibrationCam::PulserColor_t fPulserColor; // Calibration LEDs colour 
+  Float_t fStrength;                           // Calibration LEDs strength 
+
+  Int_t   fNumInnerFFactorMethodUsed;          // Number of inner pixels used for F-Factor Method calibration
+
+  TString fNamePedestalCam;                    // Name of the 'MPedestalCam' container
+
+  Int_t   fNumProcessed;                       // Number of processed events (for Intensity calibration)
+
+  Bool_t fContinousCalibration;
+
+  // Pointers
+  MBadPixelsCam                  *fBadPixels;      //!  Bad Pixels
+  MCalibrationChargeCam          *fCam;            //!  Calibrated Charges results of all pixels
+  MHCalibrationChargeCam         *fHCam;           //!  Charges histograms of all pixels   
+  MCalibrationBlindCam           *fBlindCam;       //!  Calibrated Charges of the Blind Pixels
+  MHCalibrationChargeBlindCam    *fHBlindCam;      //!  Charges histograms of the Blind Pixels  
+  MCalibrationChargePINDiode     *fPINDiode;       //!  Calibrated Charges of the PIN Diode
+  MCalibrationQECam              *fQECam;          //!  Calibrated Quantum Efficiencies of all pixels 
+  MGeomCam                       *fGeom;           //!  Camera geometry
+  MExtractedSignalCam            *fSignal;         //! Extracted Signal
+  MCalibrationPattern            *fCalibPattern;   //! Calibration DM pattern
+  MPedestalCam                   *fPedestals;      //! Pedestals all pixels (calculated previously from ped.file)
+  MExtractor                     *fExtractor;      //! Signal Extractor
+
+  // enums
+  enum  Check_t
+    {
+      kCheckDeadPixels,
+      kCheckExtractionWindow,
+      kCheckHistOverflow,
+      kCheckDeviatingBehavior,
+      kCheckOscillations,
+      kCheckArrivalTimes
+    };                                         // Possible Checks
+
+  Byte_t fCheckFlags;                          // Bit-field to hold the possible check flags
+
+  enum  FitResult_t { kPheFitOK,
+                      kFFactorFitOK,
+                      kBlindPixelFitOK,
+                      kBlindPixelPedFitOK,
+                      kPINDiodeFitOK };        // Possible Fit Result flags
+
+  TArrayC fResultFlags;                        // Bit-fields for the fitting results   (one field per area index)
+  TArrayC fBlindPixelFlags;                    // Bit-fields for the blind pixel flags (one field per blind pixel)
+  TArrayC fPINDiodeFlags;                      // Bit-fields for the PIN Diode flags   (one field per PIN Diode  )
+
+  enum  { kDebug,
+          kUseExtractorRes,
+          kUseUnreliables,
+          kUseExternalNumPhes };               // Possible general flags
+
+  Byte_t fFlags;                               // Bit-field to hold the general flags
+
+  // functions
+  void   FinalizeBadPixels       ();
+  Bool_t FinalizeBlindCam        ();  
+  void   FinalizeBlindPixelQECam ();
+  Bool_t FinalizeCharges         ( MCalibrationChargePix &cal, MBadPixelsPix &bad, const char* what);
+  void   FinalizeCombinedQECam   ();
+  void   FinalizeFFactorQECam    ();  
+  Bool_t FinalizeFFactorMethod   ();
+  void   FinalizePedestals       ( const MPedestalPix    &ped, MCalibrationChargePix &cal, const Int_t aidx );
+  Bool_t FinalizePINDiode        ();
+  void   FinalizePINDiodeQECam   ();
+  Bool_t FinalizeUnsuitablePixels();
+
+  void FinalizeAbsTimes();
+
+  const char* GetOutputFile();
+
+  // Query checks
+  Bool_t IsCheckDeadPixels       () const { return TESTBIT(fCheckFlags,kCheckDeadPixels);        }
+  Bool_t IsCheckDeviatingBehavior() const { return TESTBIT(fCheckFlags,kCheckDeviatingBehavior); }
+  Bool_t IsCheckExtractionWindow () const { return TESTBIT(fCheckFlags,kCheckExtractionWindow);  }
+  Bool_t IsCheckHistOverflow     () const { return TESTBIT(fCheckFlags,kCheckHistOverflow);      }
+  Bool_t IsCheckOscillations     () const { return TESTBIT(fCheckFlags,kCheckOscillations);      }
+  Bool_t IsCheckArrivalTimes     () const { return TESTBIT(fCheckFlags,kCheckArrivalTimes);      }
+
+  Bool_t IsDebug                 () const { return TESTBIT(fFlags,kDebug);                       }
+  Bool_t IsUseExtractorRes       () const { return TESTBIT(fFlags,kUseExtractorRes);             }
+  Bool_t IsUseUnreliables        () const { return TESTBIT(fFlags,kUseUnreliables);              }
+  Bool_t IsUseExternalNumPhes    () const { return TESTBIT(fFlags,kUseExternalNumPhes);          }
+
+  void   PrintUncalibrated( MBadPixelsPix::UncalibratedType_t typ, const char *text) const;
+
+  // Global fit results
+  void   SetPheFitOK          (const Int_t aidx, const Bool_t b=kTRUE) { b ? SETBIT(fResultFlags[aidx], kPheFitOK) : CLRBIT(fResultFlags[aidx], kPheFitOK);      }
+  void   SetFFactorFitOK      (const Int_t aidx, const Bool_t b=kTRUE) { b ? SETBIT(fResultFlags[aidx], kFFactorFitOK) : CLRBIT(fResultFlags[aidx], kFFactorFitOK);  }
+  void   SetBlindPixelFitOK   (const Int_t  idx, const Bool_t b=kTRUE) { b ? SETBIT(fBlindPixelFlags[idx], kBlindPixelFitOK) : CLRBIT(fBlindPixelFlags[idx], kBlindPixelFitOK); }
+  void   SetBlindPixelPedFitOK(const Int_t  idx, const Bool_t b=kTRUE) { b ? SETBIT(fBlindPixelFlags[idx], kBlindPixelPedFitOK): CLRBIT(fBlindPixelFlags[idx], kBlindPixelPedFitOK); }
+  void   SetPINDiodeFitOK     (const Int_t  idx, const Bool_t b=kTRUE) { b ? SETBIT(fPINDiodeFlags[idx], kPINDiodeFitOK): CLRBIT(fPINDiodeFlags[idx], kPINDiodeFitOK); }
+
+  Int_t  PreProcess (MParList *pList);
+  Bool_t ReInit     (MParList *pList); 
+  Int_t  Process    ();
+  Int_t  PostProcess();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+  MCalibrationChargeCalc(const char *name=NULL, const char *title=NULL);
+
+  void Clear(const Option_t *o="");
+
+  void ResetNumProcessed() { fNumProcessed=0; }
+
+  Int_t Finalize();
+
+  void SetChargeLimit      (const Float_t f=fgChargeLimit      ) { fChargeLimit       = f; }
+  void SetChargeErrLimit   (const Float_t f=fgChargeErrLimit   ) { fChargeErrLimit    = f; }
+  void SetChargeRelErrLimit(const Float_t f=fgChargeRelErrLimit) { fChargeRelErrLimit = f; }
+
+  // Checks
+  void SetCheckArrivalTimes(const Bool_t b=kTRUE)      { b ? SETBIT(fCheckFlags,kCheckArrivalTimes)      : CLRBIT(fCheckFlags,kCheckArrivalTimes); }
+  void SetCheckDeadPixels(const Bool_t b=kTRUE)        { b ? SETBIT(fCheckFlags,kCheckDeadPixels)        : CLRBIT(fCheckFlags,kCheckDeadPixels); }
+  void SetCheckDeviatingBehavior(const Bool_t b=kTRUE) { b ? SETBIT(fCheckFlags,kCheckDeviatingBehavior) : CLRBIT(fCheckFlags,kCheckDeviatingBehavior); }
+  void SetCheckExtractionWindow(const Bool_t b=kTRUE)  { b ? SETBIT(fCheckFlags,kCheckExtractionWindow)  : CLRBIT(fCheckFlags,kCheckExtractionWindow); }
+  void SetCheckHistOverflow(const Bool_t b=kTRUE)      { b ? SETBIT(fCheckFlags,kCheckHistOverflow)      : CLRBIT(fCheckFlags,kCheckHistOverflow); }
+  void SetCheckOscillations(const Bool_t b=kTRUE)      { b ? SETBIT(fCheckFlags,kCheckOscillations)      : CLRBIT(fCheckFlags,kCheckOscillations); }
+  void SetDebug(const Bool_t b=kTRUE)                  { b ? SETBIT(fFlags, kDebug)                      : CLRBIT(fFlags, kDebug); }
+  void SetUseExtractorRes(const Bool_t b=kTRUE)        { b ? SETBIT(fFlags, kUseExtractorRes)            : CLRBIT(fFlags, kUseExtractorRes); }
+  void SetUseUnreliables(const Bool_t b=kTRUE)         { b ? SETBIT(fFlags, kUseUnreliables)             : CLRBIT(fFlags, kUseUnreliables); }
+  void SetUseExternalNumPhes(const Bool_t b=kTRUE)     { b ? SETBIT(fFlags, kUseExternalNumPhes)         : CLRBIT(fFlags, kUseExternalNumPhes); }
+
+  void SetContinousCalibration(const Bool_t b=kTRUE)   { fContinousCalibration = b; }
+
+  // pointers
+  void SetPedestals(MPedestalCam *cam) { fPedestals=cam; }
+  void SetExtractor(MExtractor   *ext) { fExtractor=ext; }
+
+  // limits
+  void SetArrTimeRmsLimit (const Float_t f=fgArrTimeRmsLimit ) { fArrTimeRmsLimit   = f; }
+  void SetFFactorErrLimit (const Float_t f=fgFFactorErrLimit ) { fFFactorErrLimit   = f; }
+  void SetLambdaErrLimit  (const Float_t f=fgLambdaErrLimit  ) { fLambdaErrLimit    = f; }
+  void SetLambdaCheckLimit(const Float_t f=fgLambdaCheckLimit) { fLambdaCheckLimit  = f; }
+  void SetUnsuitablesLimit(const Float_t f=fgUnsuitablesLimit) { fUnsuitablesLimit  = f; }
+  void SetUnreliablesLimit(const Float_t f=fgUnreliablesLimit) { fUnreliablesLimit  = f; }
+
+  // others
+  void SetExternalNumPhes      ( const Float_t f=0.                       ) { fExternalNumPhes       = f; }
+  void SetExternalNumPhesRelVar( const Float_t f=0.                       ) { fExternalNumPhesRelVar = f; }  
+  void SetNamePedestalCam      ( const char *name=fgNamePedestalCam       ) { fNamePedestalCam    = name; }
+  void SetPheErrLowerLimit     ( const Float_t f=fgPheErrLowerLimit       ) { fPheErrLowerLimit  = f;    }
+  void SetPheErrUpperLimit     ( const Float_t f=fgPheErrUpperLimit       ) { fPheErrUpperLimit  = f;    }    
+  void SetPulserColor          ( const MCalibrationCam::PulserColor_t col ) { fPulserColor       = col;  }
+
+  ClassDef(MCalibrationChargeCalc, 6)   // Task calculating Calibration Containers and Quantum Efficiencies
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCam.cc	(revision 17960)
@@ -0,0 +1,1181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationChargeCam                                               
+//                                                               
+// Storage container for charge calibration results from the signal distribution 
+// fits (see MHCalibrationChargeCam and MHCalibrationChargePix), the calculation 
+// of reduced sigmas and number of photo-electrons (this class) and conversion 
+// factors sum FADC slices to photo-electrons (see MCalibrationChargeCalc)
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationChargePix &avpix = (MCalibrationChargePix&)(*fChargeCam)[i]
+// 
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationChargePix &avpix = (MCalibrationChargePix&)fChargeCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationChargePix &avpix = (MCalibrationChargePix&)fChargeCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// Final numbers of uncalibrated or unreliable pixels can be retrieved via the commands:
+// GetNumUncalibrated(aidx) and GetNumUnreliable(aidx) where aidx is the area index (0 for 
+// inner and 1 for outer pixels in the MAGIC camera).
+//
+// The following "calibration" constants are used for the calibration of each pixel 
+// (see MCalibrate):
+//
+// - MCalibrationQEPix::GetMeanConvFADC2Phe(): The mean conversion factor from the 
+//   summed FADC slices to the number of photo-electrons (in first order independent 
+//   on colour and intensity)
+// - MCalibrationQEPix::GetMeanFFactorFADC2Phot(): The mean F-Factor of the total  
+//   readout chain dividing the signal to noise of the incoming number of photons 
+//   (= sqrt(number photons)) by the signal to noise of the outgoing summed FADC slices 
+//   signal (= MCalibrationPix::GetMean() / MCalibrationChargePix::GetRSigma() )
+//
+// The following calibration constants can be retrieved directly from this class:
+//
+// - GetConversionFactorFFactor    ( Int_t idx, Float_t &mean, Float_t &err, Float_t &sigma );
+//
+// where: 
+// - idx is the pixel software ID
+// - "mean" is the mean conversion constant, to be multiplied with the retrieved signal 
+//   in order to get a calibrated number of PHOTONS. 
+// - "err" is the pure statistical uncertainty about the MEAN
+// - "sigma", if mulitplied with the square root of signal, gives the approximate sigma of the 
+//   retrieved mean number of incident Cherenkov photons.
+//
+// Note, Conversion is ALWAYS (included the F-Factor method!) from summed FADC slices to PHOTONS.
+//
+// See also: MCalibrationChargePix, MCalibrationChargeCalc, MCalibrationQECam
+//           MHCalibrationChargePix, MHCalibrationChargeCam              
+//           MCalibrationBlindPix, MCalibrationChargePINDiode
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include <TMath.h>
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+#include "MHCamera.h"
+
+ClassImp(MCalibrationChargeCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls:
+// - Clear()
+//
+MCalibrationChargeCam::MCalibrationChargeCam(const char *name, const char *title)
+{
+  fName  = name  ? name  : "MCalibrationChargeCam";
+  fTitle = title ? title : "Storage container for the Calibration Information in the camera";
+  
+  Clear();
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Creates new MCalibrationCam only for the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//
+TObject *MCalibrationChargeCam::Clone(const char *) const
+{
+
+  //
+  // FIXME, this might be done faster and more elegant, by direct copy.
+  //
+  MCalibrationChargeCam *cam = new MCalibrationChargeCam(fName,fTitle);
+
+  cam->fNumUnsuitable        = fNumUnsuitable;
+  cam->fNumUnreliable        = fNumUnreliable;
+  cam->fNumHiGainFADCSlices  = fNumHiGainFADCSlices;
+  cam->fNumLoGainFADCSlices  = fNumLoGainFADCSlices;
+  cam->fPulserColor          = fPulserColor;
+
+  cam->fFlags                = fFlags;
+
+  cam->fNumPhotonsBlindPixelMethod      = fNumPhotonsBlindPixelMethod;
+  cam->fNumPhotonsFFactorMethod         = fNumPhotonsFFactorMethod;
+  cam->fNumPhotonsPINDiodeMethod        = fNumPhotonsPINDiodeMethod;
+  cam->fNumPhotonsBlindPixelMethodErr   = fNumPhotonsBlindPixelMethodErr;
+  cam->fNumPhotonsFFactorMethodErr      = fNumPhotonsFFactorMethodErr;
+  cam->fNumPhotonsPINDiodeMethodErr     = fNumPhotonsPINDiodeMethodErr;
+
+  for (Int_t i=0; i<GetSize(); i++)
+    cam->fPixels->AddAt((*this)[i].Clone(),i);
+  
+  for (Int_t i=0; i<GetAverageAreas(); i++)
+    {
+      cam->fAverageAreas->AddAt(GetAverageArea(i).Clone(),i);
+      cam->fAverageBadAreas->AddAt(GetAverageBadArea(i).Clone(),i);
+    }
+  for (Int_t i=0; i<GetAverageSectors(); i++)
+    {
+      cam->fAverageSectors->AddAt(GetAverageSector(i).Clone(),i);
+      cam->fAverageBadSectors->AddAt(GetAverageBadSector(i).Clone(),i);
+    }
+
+  return cam;
+}
+*/
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargePix's in the ranges from - to to fPixels
+//
+void MCalibrationChargeCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    {
+      fPixels->AddAt(new MCalibrationChargePix,i);
+      (*this)[i].SetPixId(i);
+    }
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargePix's in the ranges from - to to fAverageAreas
+//
+void MCalibrationChargeCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    {
+      fAverageAreas->AddAt(new MCalibrationChargePix,i);
+      GetAverageArea(i).SetPixId(i);
+    }
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargePix's in the ranges from - to to fAverageSectors
+//
+void MCalibrationChargeCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    {
+      fAverageSectors->AddAt(new MCalibrationChargePix,i);
+      GetAverageSector(i).SetPixId(i);
+    }
+}
+
+
+// --------------------------------------
+//
+// Sets all variable to 0.
+// Sets all flags to kFALSE
+// Calls MCalibrationCam::Clear()
+//
+void MCalibrationChargeCam::Clear(Option_t *o)
+{
+  // DO NOT RESET THE HI-/LO-GAIN CONSTANTS
+  SetFFactorMethodValid    ( kFALSE );
+
+  fNumPhotonsBlindPixelMethod    = 0.;
+  fNumPhotonsFFactorMethod       = 0.;
+  fNumPhotonsPINDiodeMethod      = 0.;
+  fNumPhotonsBlindPixelMethodErr = 0.;
+  fNumPhotonsFFactorMethodErr    = 0.;
+  fNumPhotonsPINDiodeMethodErr   = 0.;
+
+  MCalibrationCam::Clear();
+}
+
+// -----------------------------------------------
+//
+// 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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy High-gain vs. low-gain conversion factors from cam to this.
+//
+Bool_t MCalibrationChargeCam::MergeHiLoConversionFactors(const MCalibrationChargeCam &cam) const
+{
+
+  if (GetSize() != cam.GetSize())
+    {
+      *fLog << warn << "Sizes mismatch! Cannot merge high-gain vs. low-gain convertion factors" << endl;
+      return kFALSE;
+    }
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      ((MCalibrationChargePix&)(*this)[i]).SetConversionHiLo   (((MCalibrationChargePix&)cam[i]).GetConversionHiLo());
+      ((MCalibrationChargePix&)(*this)[i]).SetConversionHiLoErr(((MCalibrationChargePix&)cam[i]).GetConversionHiLoErr());
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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->IsFFactorMethodValid()) 
+	{                            
+
+          *fLog << all 
+                << Form("%s%3i","Pixel: ",pix->GetPixId())
+                << Form("%s%4.2f%s%4.2f","  Ped.Rms: ",pix->GetPedRms(),"+-",pix->GetPedRmsErr())
+		<< Form("%s%4.2f%s%4.2f","  Charge: " ,pix->GetConvertedMean(),"+-",pix->GetConvertedSigma())
+		<< Form("%s%4.2f%s%4.2f","  Red.Sigma: ",pix->GetConvertedRSigma(),"+-",pix->GetConvertedRSigmaErr())
+		<< Form("%s%4.2f%s%4.2f","  Num.Phes: ",pix->GetPheFFactorMethod(),"+-",pix->GetPheFFactorMethodErr()) 
+		<< Form("%s%4.2f%s%4.2f","  Conv.FADC2Phe: ",pix->GetMeanConvFADC2Phe(),"+-",pix->GetMeanConvFADC2PheErr())
+                << " Saturated? :" << pix->IsHiGainSaturation() 
+		<< Form("%s%4.2f%s%4.2f","  Conv.HiLo: ",pix->GetConversionHiLo(),"+-",pix->GetConversionHiLoErr())
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Previously Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationChargePix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+        *fLog << all << pix->GetPixId() << " ";
+        id++;
+
+        if (!(id % 25))
+          *fLog << endl;
+      }
+  }
+  
+  *fLog << all << endl;
+  *fLog << all << "New Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next5(fPixels);
+  while ((pix=(MCalibrationChargePix*)Next5()))
+  {
+      if (!pix->IsFFactorMethodValid() && !pix->IsExcluded())
+      {
+        *fLog << all << pix->GetPixId() << " ";
+        id++;
+
+        if (!(id % 25))
+          *fLog << endl;
+      }
+  }
+  
+  *fLog << endl;
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Areas:" << endl;
+  *fLog << all << endl;
+
+  TIter Next6(fAverageAreas);
+  while ((pix=(MCalibrationChargePix*)Next6()))
+  {
+    *fLog << all << Form("%s%3i","Area Idx: ",pix->GetPixId())
+          << "   Ped.  Rms: "            << pix->GetPedRms()        << " +- " << pix->GetPedRmsErr() 
+          << "   Mean signal: "          << pix->GetMean()    << " +- " << pix->GetMeanErr() 
+          << "   Sigma signal: "         << pix->GetSigma()    << " +- "<< pix->GetSigmaErr() 
+          << "   Reduced Sigma: "        << pix->GetRSigma() 
+          << "   Nr Phe's: "             << pix->GetPheFFactorMethod() 
+          << endl;
+  }
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Sectors:" << endl;
+  *fLog << all << endl;
+
+  TIter Next7(fAverageSectors);
+  while ((pix=(MCalibrationChargePix*)Next7()))
+  {
+    *fLog << all << Form("%s%3i","Sector: ",pix->GetPixId())
+          << "   Ped.  Rms: "            << pix->GetPedRms()        << " +- " << pix->GetPedRmsErr() 
+          << "   Mean signal: "          << pix->GetMean()    << " +- " << pix->GetMeanErr() 
+          << "   Sigma signal: "         << pix->GetSigma()    << " +- "<< pix->GetSigmaErr() 
+          << "   Reduced Sigma: "        << pix->GetRSigma() 
+          << "   Nr Phe's: "             << pix->GetPheFFactorMethod() 
+          << endl;
+  }
+  *fLog << all << endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Charge                              (see MCalibrationPix::GetMean())
+// 1: Error of fitted Charge                     (see MCalibrationPix::GetMeanErr())
+// 2: Sigma of fitted Charge                     (see MCalibrationPix::GetSigma())
+// 3: Error of Sigma of fitted Charge            (see MCalibrationPix::GetSigmaErr())
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Probability Gauss fit Charge distribution  (see MCalibrationPix::GetProb())
+// 5: Reduced Sigma of fitted Charge             (see MCalibrationChargePix::GetRSigma())
+// 6: Error Reduced Sigma of fitted Charge       (see MCalibrationChargePix::GetRSigmaErr())
+// 7: Reduced Sigma per Charge                   (see MCalibrationChargePix::GetRSigmaPerCharge())
+// 8: Error of Reduced Sigma per Charge          (see MCalibrationChargePix::GetRSigmaPerChargeErr())
+//
+// Results of the F-Factor calibration Method:
+// ===========================================
+//
+//  9: Nr. Photo-electrons from F-Factor Method  (see MCalibrationChargePix::GetPheFFactorMethod())
+// 10: Error Nr. Photo-el. from F-Factor Method  (see MCalibrationChargePix::GetPheFFactorMethodErr())
+// 11: Conversion factor   from F-Factor Method  (see MCalibrationChargePix::GetMeanConvFADC2Phe()
+// 12: Error conv. factor  from F-Factor Method  (see MCalibrationChargePix::GetMeanConvFADC2PheErr()
+// 13: Overall F-Factor    from F-Factor Method  (see MCalibrationChargePix::GetMeanFFactorFADC2Phot()
+// 14: Error F-Factor      from F-Factor Method  (see MCalibrationChargePix::GetMeanFFactorFADC2PhotErr()
+// 15: Pixels valid calibration F-Factor-Method  (see MCalibrationChargePix::IsFFactorMethodValid())           
+//
+// Results of the Low-Gain vs. High-Gain Conversion:
+// =================================================
+//
+// 16: Mean Signal Hi-Gain / Mean Signal Lo-Gain (see MCalibrationPix::GetHiLoMeansDivided())
+// 17: Error Signal High-Gain / Signal Low Gain  (see MCalibrationPix::GetHiLoMeansDividedErr())
+// 18: Sigma High-Gain / Sigma Low Gain          (see MCalibrationPix::GetHiLoSigmasDivided())
+// 19: Error Sigma High-Gain / Sigma Low Gain    (see MCalibrationPix::GetHiLoSigmasDividedErr())
+//                                                
+// Localized defects:                             
+// ==================
+//
+// 20: Excluded Pixels
+// 21: Number of pickup   events in the Hi Gain  (see MCalibrationPix::GetHiGainNumPickup())
+// 22: Number of pickup   events in the Lo Gain  (see MCalibrationPix::GetLoGainNumPickup())
+// 23: Number of blackout events in the Hi Gain  (see MCalibrationPix::GetHiGainNumBlackout())
+// 24: Number of blackout events in the Lo Gain  (see MCalibrationPix::GetLoGainNumBlackout())
+//
+// Other classifications of pixels:
+// ================================
+//
+// 25: Pixels with saturated High-Gain           (see MCalibrationPix::IsHiGainSaturation())
+//
+// Calculated absolute arrival times (very low precision!):
+// ========================================================
+//
+// 26: Absolute Arrival time of the signal       (see MCalibrationChargePix::GetAbsTimeMean())
+// 27: RMS Ab.  Arrival time of the signal       (see MCalibrationChargePix::GetAbsTimeRms())
+//
+// Used Pedestals:
+// ===============
+//
+// 28: Pedestal for entire signal extr. range    (see MCalibrationChargePix::Ped())
+// 29: Error Pedestal entire signal extr. range  (see MCalibrationChargePix::PedErr())
+// 30: Ped. RMS entire signal extraction range   (see MCalibrationChargePix::PedRms())
+// 31: Error Ped. RMS entire signal extr. range  (see MCalibrationChargePix::PedRmsErr())
+//
+// Special variables (for data check):
+// ====================================
+//
+// 32: HiGain RMS divided by Mean for every pixel (with inclusion of the excluded pixels)
+//
+Bool_t MCalibrationChargeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx > GetSize())
+        return kFALSE;
+
+    const Float_t area = cam[idx].GetA();
+    if (area == 0)
+        return kFALSE;
+
+    const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[idx];
+    switch (type)
+    {
+    case 0:
+        if (pix.IsExcluded() || pix.GetConvertedMeanErr()<0)
+            return kFALSE;
+        val = pix.GetConvertedMean();
+        return kTRUE;
+    case 1:
+        if (pix.IsExcluded() || pix.GetConvertedMeanErr()<0)
+            return kFALSE;
+        val = pix.GetConvertedMeanErr();
+        return kTRUE;
+    case 2:
+        if (pix.IsExcluded() || pix.GetConvertedSigmaErr()<0)
+            return kFALSE;
+        val = pix.GetConvertedSigma();
+        return kTRUE;
+    case 3:
+        if (pix.IsExcluded() || pix.GetConvertedSigmaErr()<0)
+            return kFALSE;
+        val = pix.GetConvertedSigmaErr();
+        return kTRUE;
+    case 4:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetProb();
+        return val>=0;
+    case 5:
+        if (!pix.IsFFactorMethodValid())
+            return kFALSE;
+        if (pix.GetRSigma() == -1.)
+            return kFALSE;
+        val = pix.GetConvertedRSigma();
+        break;
+    case 6:
+        if (!pix.IsFFactorMethodValid())
+            return kFALSE;
+        if (pix.GetRSigma() == -1.)
+            return kFALSE;
+        val = pix.GetConvertedRSigmaErr();
+        break;
+    case 7:
+        if (!pix.IsFFactorMethodValid())
+            return kFALSE;
+        val = pix.GetRSigmaPerCharge();
+        break;
+    case 8:
+        if (!pix.IsFFactorMethodValid())
+            return kFALSE;
+        val =  pix.GetRSigmaPerChargeErr();
+        break;
+    case 9:
+        //      if (!pix.IsFFactorMethodValid())
+        //        return kFALSE;
+        if (pix.IsExcluded() || pix.GetPheFFactorMethodErr()<0)
+            return kFALSE;
+        val = pix.GetPheFFactorMethod();
+        return kTRUE;
+    case 10:
+        //      if (!pix.IsFFactorMethodValid())
+        //        return kFALSE;
+        if (pix.IsExcluded() || pix.GetPheFFactorMethodErr()<=0)
+            return kFALSE;
+        val = pix.GetPheFFactorMethodErr();
+        return kTRUE;
+    case 11:
+        //      if (!pix.IsFFactorMethodValid())
+        //        return kFALSE;
+        if (pix.IsExcluded() || pix.GetMeanConvFADC2PheErr()<0)
+            return kFALSE;
+        val = pix.GetMeanConvFADC2Phe();
+        return kTRUE;
+    case 12:
+        //      if (!pix.IsFFactorMethodValid())
+        //        return kFALSE;
+        if (pix.IsExcluded() || pix.GetMeanConvFADC2PheErr()<=0)
+            return kFALSE;
+        val = pix.GetMeanConvFADC2PheErr();
+        return kTRUE;
+    case 13:
+        //      if (!pix.IsFFactorMethodValid())
+        //        return kFALSE;
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetMeanFFactorFADC2Phot();
+        break;
+    case 14:
+        //      if (!pix.IsFFactorMethodValid())
+        //        return kFALSE;
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetMeanFFactorFADC2PhotErr();
+        if (val <= 0.)
+            val = 0.00001;
+        break;
+    case 15:
+        if (pix.IsExcluded())
+            return kFALSE;
+        if (!pix.IsFFactorMethodValid())
+            return kFALSE;
+        val = 1;
+        return kTRUE;
+    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())
+            return kFALSE;
+        val = 1.;
+        return kTRUE;
+    case 21:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetHiGainNumPickup();
+        break;
+    case 22:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetLoGainNumPickup();
+        break;
+    case 23:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetHiGainNumBlackout();
+        break;
+    case 24:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetLoGainNumBlackout();
+        break;
+    case 25:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.IsHiGainSaturation();
+        break;
+    case 26:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetAbsTimeMean();
+        break;
+    case 27:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetAbsTimeRms();
+        break;
+    case 28:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetPed();
+        break;
+    case 29:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetPedErr();
+        break;
+    case 30:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetPedRms();
+        break;
+    case 31:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetPedErr()/2.;
+        break;
+    case 32:
+        if (pix.IsExcluded() || pix.GetRms()<0)
+            return kFALSE;
+        val = pix.GetMean() == 0. ? 0. : pix.GetRms()/pix.GetMean();
+        return kTRUE;
+    case 33:
+        if (pix.IsExcluded() || pix.GetRms()<0)
+            return kFALSE;
+        if (pix.GetMean() == 0.)
+            val = 0.;
+        else
+            val = pix.GetSigmaErr()/pix.GetMean() + pix.GetRms()*pix.GetMeanErr()/pix.GetMean()/pix.GetMean();
+        return kTRUE;
+    default:
+        return kFALSE;
+    }
+
+    return val!=-1.;
+}
+
+Bool_t MCalibrationChargeCam::GetConversionFactorFFactor(Int_t ipx, Float_t &mean, Float_t &ferr, Float_t &ffactor)
+{
+
+  MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[ipx];
+
+  Float_t conv = pix.GetMeanConvFADC2Phe();
+
+  if (conv < 0.)
+    return kFALSE;
+
+  mean    = conv;
+  ferr    = pix.GetMeanConvFADC2PheErr();
+  ffactor = pix.GetMeanFFactorFADC2Phot();
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average conversion factor FADC counts to photons for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). The MCalibrationQECam container is necessary for 
+// the quantum efficiency information. 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged conversion factors (default: -1.)
+// arr[1]: Error (rms) of averaged conversion factors (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedConvFADC2PhotPerArea  ( const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                           const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  MHCamera convcam(geom,"ConvFactors","Conversion Factors;Conv Factor [phot/FADC cnts];channels");
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+
+      if (bad && (*bad)[i].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes))
+        continue; 
+
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+      
+      const MCalibrationQEPix &qepix = (MCalibrationQEPix&)qecam[i];
+      if (!qepix.IsAverageQEFFactorAvailable())
+        continue;
+      
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t conv = pix.GetMeanConvFADC2Phe()/qepix.GetQECascadesFFactor();
+
+      mean  += conv;
+      mean2 += conv*conv;
+      nr    ++;
+
+      convcam.Fill(i,conv);
+      convcam.SetUsed(i);
+    }
+
+  Float_t mn  = nr   ? mean/nr : -1.;
+  Float_t sg  = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0.;
+
+  const Int_t aidx = (Int_t)ai;
+
+  TH1D *h = convcam.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+  h->SetDirectory(NULL);
+
+  TF1 *fit = NULL;
+
+  if (geom.InheritsFrom("MGeomCamMagic"))
+    {
+
+      fit = new TF1("fit","gaus",0.4,5.);
+      
+      // Fix the ranges, as found by Nadia
+      if(aidx == 0)
+        h->Fit(fit, "REQ0", "",0.4,1.5);
+      else
+        h->Fit(fit ,"REQ0", "",1.,5.);
+    }
+  else
+    {
+      h->Fit("gaus","Q0");
+      fit = h->GetFunction("gaus");
+    }
+
+  Float_t ci2   = fit->GetChisquare();
+  Float_t sigma = fit->GetParameter(2);
+  
+  if (ci2 > 500. || sigma > sg)
+    {
+      if (geom.InheritsFrom("MGeomCamMagic"))
+        {
+          // Fix the ranges, as found by Nadia
+          if(aidx == 0)
+            h->Fit(fit, "REQ0", "",0.4,1.5);
+          else
+            h->Fit(fit, "REQ0", "",1.,5.);
+        }
+      else
+        {
+          h->Fit("gaus","MREQ0");
+          fit = h->GetFunction("gaus");
+        }
+      
+      ci2   = fit->GetChisquare();
+      sigma = fit->GetParameter(2);
+    }
+  
+  const Int_t ndf = fit->GetNDF();
+
+  if (ci2 < 500. && sigma < sg && ndf > 2)
+    {
+      mn  = fit->GetParameter(1);
+      sg  = sigma;
+    }
+  
+  *fLog << inf << "Conversion Factors to photons area idx: " << aidx << ":" << endl;
+  *fLog << inf << "Mean: " << Form("%4.3f",mn) 
+        << "+-" << Form("%4.3f",fit->GetParError(1))
+        << "  Sigma: " << Form("%4.3f",sg) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+        << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+  
+  delete fit;
+  delete h;
+  gROOT->GetListOfFunctions()->Remove(fit);
+
+  TArrayF arr(2);
+  arr[0] = mn;
+  arr[1] = sg;
+
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average conversion factor FADC counts to equiv. photo-electrons for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). The MCalibrationQECam container is necessary for 
+// the quantum efficiency information. 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged conversion factors (default: -1.)
+// arr[1]: Error (rms) of averaged conversion factors (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedConvFADC2PhePerArea  ( const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                           const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  MHCamera convcam(geom,"ConvFactors","Conversion Factors;Conv Factor [phe/FADC cnts];channels");
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+
+      if (bad && (*bad)[i].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes))
+        continue; 
+
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+      
+      const MCalibrationQEPix &qepix = (MCalibrationQEPix&)qecam[i];
+      if (!qepix.IsAverageQEFFactorAvailable())
+        continue;
+      
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t conv = pix.GetMeanConvFADC2Phe()/qepix.GetQECascadesFFactor()*MCalibrationQEPix::gkDefaultAverageQE;
+
+      mean  += conv;
+      mean2 += conv*conv;
+      nr    ++;
+
+      convcam.Fill(i,conv);
+      convcam.SetUsed(i);
+    }
+
+  Float_t mn  = nr   ? mean/nr : -1.;
+  Float_t sg  = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0.;
+
+  const Int_t aidx = (Int_t)ai;
+
+  TH1D *h = convcam.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+  h->SetDirectory(NULL);
+
+  TF1 *fit = NULL;
+
+  if (geom.InheritsFrom("MGeomCamMagic"))
+    {
+
+      fit = new TF1("fit","gaus",0.01,1.);
+      
+      // Fix the ranges, as found by Nadia
+      if(aidx == 0)
+        {h->Fit("fit","REQ0", "",0.07,0.3);}
+      else
+        {h->Fit("fit","REQ0", "",0.15,1.0);}
+    }
+  else
+    {
+      h->Fit("gaus","Q0");
+      fit = h->GetFunction("gaus");
+    }
+
+  Float_t ci2   = fit->GetChisquare();
+  Float_t sigma = fit->GetParameter(2);
+  
+  if (ci2 > 500. || sigma > sg)
+    {
+      if (geom.InheritsFrom("MGeomCamMagic"))
+        {
+          // Fix the ranges, as found by Nadia
+          if(aidx == 0)
+            {h->Fit("fit","REQ0", "",0.07,0.3);}
+          else
+            {h->Fit("fit","REQ0", "",0.15,1.0);}
+        }
+      else
+        {
+          h->Fit("gaus","MREQ0");
+          fit = h->GetFunction("gaus");
+        }
+      
+      ci2   = fit->GetChisquare();
+      sigma = fit->GetParameter(2);
+    }
+  
+  const Int_t ndf = fit->GetNDF();
+
+  if (ci2 < 500. && sigma < sg && ndf > 2)
+    {
+      mn  = fit->GetParameter(1);
+      sg  = sigma;
+    }
+  
+  *fLog << inf << "Conversion Factors to equiv. photo-electrons area idx: " << aidx << ":" << endl;
+  *fLog << inf << "Mean: " << Form("%4.3f",mn) 
+        << "+-" << Form("%4.3f",fit->GetParError(1))
+        << "  Sigma: " << Form("%4.3f",sg) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+        << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+  
+  delete fit;
+  delete h;
+  gROOT->GetListOfFunctions()->Remove(fit);
+
+  TArrayF arr(2);
+  arr[0] = mn;
+  arr[1] = sg;
+
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average conversion factor FADC counts to photons for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index). The MCalibrationQECam container is necessary for 
+// the quantum efficiency information. 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged conversion factors (default: -1.)
+// arr[1]: Error (rms) of averaged conversion factors (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedConvFADC2PhotPerSector( const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                             const UInt_t sec, MBadPixelsCam *bad)
+{
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sector != sec)
+        continue;
+
+      const MCalibrationQEPix &qepix = (MCalibrationQEPix&)qecam[i];
+      if (!qepix.IsAverageQEFFactorAvailable())
+        continue;
+      
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t conv = pix.GetMeanConvFADC2Phe();
+      const Float_t qe = qepix.GetQECascadesFFactor();
+
+      mean  += conv/qe;
+      mean2 += conv*conv/qe/qe;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}  
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average mean arrival times for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged mean arrival times (default: -1.)
+// arr[1]: Error (rms) of averaged mean arrival times (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeMeanPerArea(const MGeomCam &geom,
+                                                                 const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t time = pix.GetAbsTimeMean();
+
+      mean  += time   ;
+      mean2 += time*time;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average mean arrival times for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index).
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged mean arrival times (default: -1.)
+// arr[1]: Error (rms) of averaged mean arrival times (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeMeanPerSector(const MGeomCam &geom,
+                                                                   const UInt_t sec, MBadPixelsCam *bad)
+{
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sector != sec)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t time = pix.GetAbsTimeMean();
+
+      mean  += time;
+      mean2 += time*time;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}  
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average arrival time RMSs for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged arrival time RMSs (default: -1.)
+// arr[1]: Error (rms) of averaged arrival time RMSs (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeRmsPerArea  ( const MGeomCam &geom,
+                                                                   const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t rms = pix.GetAbsTimeRms();
+
+      mean  += rms;
+      mean2 += rms*rms;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average arrival time RMSs for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index).
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged arrival time RMSs (default: -1.)
+// arr[1]: Error (rms) of averaged arrival time RMSs (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeRmsPerSector( const MGeomCam &geom, const UInt_t sec, MBadPixelsCam *bad)
+{
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sector != sec)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t rms = pix.GetAbsTimeRms();
+
+      mean  += rms;
+      mean2 += rms*rms;
+      nr    ++;
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+
+  return arr;
+}  
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargeCam.h	(revision 17960)
@@ -0,0 +1,78 @@
+#ifndef MARS_MCalibrationChargeCam
+#define MARS_MCalibrationChargeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationQECam;
+class MCalibrationChargeCam : public MCalibrationCam
+{
+private:
+  
+  Byte_t  fFlags;                         // Bit-field to hold the flags
+
+  Float_t fNumPhotonsBlindPixelMethod;    // Average nr. photons from Blind Pixel Method (Inner Pixel)
+  Float_t fNumPhotonsFFactorMethod;       // Average nr. photons from F-Factor Method (Inner Pixel)
+  Float_t fNumPhotonsPINDiodeMethod;      // Average nr. photons from PIN Diode Method (Inner Pixel)
+  Float_t fNumPhotonsBlindPixelMethodErr; // Error av. nr. photons from Blind Pixel Method
+  Float_t fNumPhotonsFFactorMethodErr;    // Error av. nr. photons from F-Factor Method
+  Float_t fNumPhotonsPINDiodeMethodErr;   // Error av. nr. photons from PIN Diode Method
+  
+  enum  { kFFactorMethodValid };
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+  
+public:
+
+  MCalibrationChargeCam(const char *name=NULL, const char *title=NULL);
+  
+  void   Clear ( Option_t *o="" );
+  
+  // Getters
+  Bool_t  GetConversionFactorFFactor( Int_t ipx, Float_t &mean, Float_t &err, Float_t &ffactor );
+  Bool_t  GetPixelContent           ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  Float_t GetNumPhotonsBlindPixelMethod   () const { return fNumPhotonsBlindPixelMethod;    }
+  Float_t GetNumPhotonsFFactorMethod      () const { return fNumPhotonsFFactorMethod;       }     
+  Float_t GetNumPhotonsPINDiodeMethod     () const { return fNumPhotonsPINDiodeMethod;      }    
+  Float_t GetNumPhotonsBlindPixelMethodErr() const { return fNumPhotonsBlindPixelMethodErr; }
+  Float_t GetNumPhotonsFFactorMethodErr   () const { return fNumPhotonsFFactorMethodErr;    }     
+  Float_t GetNumPhotonsPINDiodeMethodErr  () const { return fNumPhotonsPINDiodeMethodErr;   }    
+  Bool_t  IsFFactorMethodValid            () const;
+
+  TArrayF GetAveragedConvFADC2PhotPerArea    (const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedConvFADC2PhePerArea     (const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedConvFADC2PhotPerSector  (const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                              const UInt_t sec=0, MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeMeanPerArea  (const MGeomCam &geom,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeMeanPerSector(const MGeomCam &geom,
+                                              const UInt_t sec=0, MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeRmsPerArea   (const MGeomCam &geom,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeRmsPerSector (const MGeomCam &geom,
+                                              const UInt_t sec=0, MBadPixelsCam *bad=NULL);
+
+  Bool_t MergeHiLoConversionFactors(const MCalibrationChargeCam &cam) const;
+  
+  // Prints
+  void   Print(Option_t *o="") const;
+
+  // Setters   
+  void  SetFFactorMethodValid           ( const Bool_t  b=kTRUE );
+  void  SetNumPhotonsBlindPixelMethod   ( const Float_t f )  { fNumPhotonsBlindPixelMethod    = f; } 
+  void  SetNumPhotonsFFactorMethod      ( const Float_t f )  { fNumPhotonsFFactorMethod       = f; }      
+  void  SetNumPhotonsPINDiodeMethod     ( const Float_t f )  { fNumPhotonsPINDiodeMethod      = f; }   
+  void  SetNumPhotonsBlindPixelMethodErr( const Float_t f )  { fNumPhotonsBlindPixelMethodErr = f; } 
+  void  SetNumPhotonsFFactorMethodErr   ( const Float_t f )  { fNumPhotonsFFactorMethodErr    = f; }      
+  void  SetNumPhotonsPINDiodeMethodErr  ( const Float_t f )  { fNumPhotonsPINDiodeMethodErr   = f; }   
+  
+  ClassDef(MCalibrationChargeCam, 5) // Container Charge Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePINDiode.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePINDiode.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePINDiode.cc	(revision 17960)
@@ -0,0 +1,436 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                     
+// MCalibrationChargePINDiode       
+//                                  
+// Storage container of the fit results of the PIN Diode signal 
+// (from MHCalibrationChargePINDiode). The PIN Diode is not yet working, so 
+// is the documentation for the moment.
+//
+// The Flux is calculated in photons per mm^2 in the camera plane. 
+//
+// Currently, the following numbers are implemented:
+//
+// Area of PIN Diode   Ap: 63.5 +- 0.1 mm^2 
+// Transparency of window T: 0.88 +- 0.05
+//
+// Ratio of areas: 
+//
+// Distance of PIN Diode to pulser D1:   1.139  +- 0.005 m
+// Distance of Inner Pixel to pulser D2: 18.135 +- 0.015 m
+//
+//                          D1*D1
+// gkSolidAngleRatio   =   -------- = 7.06 * 10^-5
+//                         Ap*T*D2*D2
+//
+// gkSolidAngleRatioErr = 0.4 * 10^-5
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationChargePix.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationChargePINDiode);
+
+using namespace std;
+
+const Float_t MCalibrationChargePINDiode::fgChargeToPhotons    = -1.; 
+const Float_t MCalibrationChargePINDiode::fgChargeToPhotonsErr = -1.; 
+const Float_t MCalibrationChargePINDiode::gkAbsorptionWindow   = 0.88; 
+const Float_t MCalibrationChargePINDiode::gkSolidAngleRatio    = 0.0000705;
+const Float_t MCalibrationChargePINDiode::gkSolidAngleRatioErr = 0.000004;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEGreen    = 0.84;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEBlue     = 0.74;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEUV       = 0.40;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQECT1      = 0.40;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEGreenErr = 0.015;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEBlueErr  = 0.015;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEUVErr    = 0.015;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQECT1Err   = 0.015;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - fCalibFlags to 0
+// - fChargeToPhotons to fgChargeToPhotons
+// - fChargeToPhotonsVar to fgChargeToPhotonsErr*fgChargeToPhotonsErr
+// 
+// Calls:
+// - Clear()
+//
+MCalibrationChargePINDiode::MCalibrationChargePINDiode(const char *name, const char *title)
+    : fCalibFlags(0)
+{
+
+  fName  = name  ? name  : "MCalibrationChargePINDiode";
+  fTitle = title ? title : "Container of the fit results of MHCalibrationChargePINDiode";
+
+  SetChargeToPhotons();
+  SetChargeToPhotonsErr();
+
+  Clear();
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all variables to -1.
+//
+// Calls: 
+// - MCalibrationPix::Clear()
+//
+void MCalibrationChargePINDiode::Clear(Option_t *o)
+{
+
+  SetOscillating        ( kFALSE );
+  SetChargeFitValid     ( kFALSE );
+  SetTimeFitValid       ( kFALSE );
+  SetColor              ( MCalibrationCam::kNONE );
+    
+  fAbsTimeMean              =  -1.;
+  fAbsTimeRms               =  -1.;
+  fFluxOutsidePlexiglass    =  -1.;  
+  fFluxOutsidePlexiglassVar =  -1.;
+  fNumPhotons               =  -1.;
+  fNumPhotonsVar            =  -1.;
+  fPed                      =  -1.;
+  fPedRms                   =  -1.;
+  fRmsChargeMean            =  -1.;
+  fRmsChargeMeanErr         =  -1.;
+  fRmsChargeSigma           =  -1.;  
+  fRmsChargeSigmaErr        =  -1.;
+
+  MCalibrationPix::Clear();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the pedestals from outside
+//
+void MCalibrationChargePINDiode::SetPedestal(Float_t ped, Float_t pedrms)
+{
+
+  fPed    = ped;    
+  fPedRms = pedrms;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Oscillating Bit from outside 
+//
+void  MCalibrationChargePINDiode::SetOscillating( const Bool_t b)
+{
+    b ? SETBIT(fCalibFlags,kOscillating) : CLRBIT(fCalibFlags,kOscillating);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the ChargeFitValid Bit from outside 
+//
+void MCalibrationChargePINDiode::SetChargeFitValid(Bool_t b )    
+{ 
+  b ?  SETBIT(fCalibFlags, kChargeFitValid) : CLRBIT(fCalibFlags, kChargeFitValid); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the TimeFitValid Bit from outside 
+//
+void MCalibrationChargePINDiode::SetTimeFitValid(Bool_t b )    
+{ 
+  b ?  SETBIT(fCalibFlags, kTimeFitValid) : CLRBIT(fCalibFlags, kTimeFitValid); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the FluxOutsidePlexiglassAvailable Bit from outside 
+//
+void MCalibrationChargePINDiode::SetFluxOutsidePlexiglassAvailable (const Bool_t b)
+{
+  b ?  SETBIT(fCalibFlags, kFluxOutsidePlexiglassAvailable) 
+    : CLRBIT(fCalibFlags, kFluxOutsidePlexiglassAvailable); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxOutsidePlexiglassVar is smaller than 0.
+// Return square root of fFluxOutsidePlexiglassVar
+// 
+Float_t MCalibrationChargePINDiode::GetFluxOutsidePlexiglassErr() const
+{
+  if (fFluxOutsidePlexiglassVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fFluxOutsidePlexiglassVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxOutsidePlexiglassVar is smaller than 0.
+// Return -1 if fFluxOutsidePlexiglass is 0.
+// Return  fFluxOutsidePlexiglassVar / fFluxOutsidePlexiglass^2
+// 
+Float_t MCalibrationChargePINDiode::GetFluxOutsidePlexiglassRelVar() const
+{
+  if (fFluxOutsidePlexiglassVar < 0.)
+    return -1.;
+  
+  if (fFluxOutsidePlexiglass == 0.)
+    return -1.;
+  
+  return fFluxOutsidePlexiglassVar / (fFluxOutsidePlexiglass * fFluxOutsidePlexiglass );
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fNumPhotonsVar is smaller than 0.
+// Return square root of fNumPhotonsVar
+// 
+Float_t MCalibrationChargePINDiode::GetNumPhotonsErr() const
+{
+  if (fNumPhotonsVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fNumPhotonsVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fNumPhotonsVar is smaller than 0.
+// Return -1 if fNumPhotons    is 0.
+// Return fNumPhotonsVar / (fNumPhotons^2 )
+// 
+Float_t MCalibrationChargePINDiode::GetNumPhotonsRelVar() const
+{
+  if (fNumPhotonsVar < 0.)
+    return -1.;
+  
+  if (fNumPhotons  == 0.)
+    return -1.;
+  
+  return  fNumPhotonsVar / fNumPhotons / fNumPhotons ;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQEGreenErr is smaller than 0.
+// Return -1 if gkPINDiodeQEGreen    is 0.
+// Return gkPINDiodeQEGreenErr^2 / (gkPINDiodeQEGreen^2 )
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQEGreenRelVar() const
+{
+  if (gkPINDiodeQEGreenErr < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQEGreen  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQEGreenErr * gkPINDiodeQEGreenErr / gkPINDiodeQEGreen / gkPINDiodeQEGreen ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQEBlueErr is smaller than 0.
+// Return -1 if gkPINDiodeQEBlue    is 0.
+// Return gkPINDiodeQEBlueErr^2 / gkPINDiodeQEBlue^2
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQEBlueRelVar() const
+{
+  if (gkPINDiodeQEBlueErr < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQEBlue  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQEBlueErr * gkPINDiodeQEBlueErr / gkPINDiodeQEBlue / gkPINDiodeQEBlue ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQEUVErr is smaller than 0.
+// Return -1 if gkPINDiodeQEUV    is 0.
+// Return gkPINDiodeQEUVErr ^2 / gkPINDiodeQEUV^2 
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQEUVRelVar() const
+{
+  if (gkPINDiodeQEUVErr < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQEUV  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQEUVErr * gkPINDiodeQEUVErr / gkPINDiodeQEUV / gkPINDiodeQEUV ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQECT1Err is smaller than 0.
+// Return -1 if gkPINDiodeQECT1    is 0.
+// Return gkPINDiodeQECT1Err ^2 / gkPINDiodeQECT1^2
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQECT1RelVar() const
+{
+  if (gkPINDiodeQECT1Err < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQECT1  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQECT1Err * gkPINDiodeQECT1Err / gkPINDiodeQECT1 / gkPINDiodeQECT1 ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkSolidAngleRatioErr is smaller than 0.
+// Return -1 if gkSolidAngleRatio    is 0.
+// Return gkSolidAngleRatioErr ^2 / gkSolidAngleRatio^2
+// 
+const Float_t MCalibrationChargePINDiode::GetSolidAngleRatioRelVar() const
+{
+  if (gkSolidAngleRatioErr < 0.)
+    return -1.;
+  
+  if (gkSolidAngleRatio  == 0.)
+    return -1.;
+  
+  return gkSolidAngleRatioErr * gkSolidAngleRatioErr / gkSolidAngleRatio / gkSolidAngleRatio ;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Test bit kChargeFitValid
+//
+Bool_t MCalibrationChargePINDiode::IsChargeFitValid() const 
+{
+  return TESTBIT(fCalibFlags, kChargeFitValid);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kFluxOutsidePlexiglassAvailable
+//
+Bool_t  MCalibrationChargePINDiode::IsFluxOutsidePlexiglassAvailable()   const
+{
+  return TESTBIT(fFlags,kFluxOutsidePlexiglassAvailable);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Test bit kTimeFitValid
+//
+Bool_t MCalibrationChargePINDiode::IsTimeFitValid()   const 
+{
+  return TESTBIT(fCalibFlags, kTimeFitValid);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kOscillating
+//
+Bool_t MCalibrationChargePINDiode::IsOscillating()   const 
+{
+  return TESTBIT(fCalibFlags, kOscillating);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Return kFALSE if IsChargeFitValid() is kFALSE
+//
+// Calculate fFluxOutsidePlexiglass with the formula:
+// - fFluxOutsidePlexiglass    = fNumPhotons*gkSolidAngleRatio / gkPINDiodeQE (of the corr. colour) 
+// - fFluxOutsidePlexiglassVar = sqrt( fNumPhotonsVar / ( fNumPhotons * fNumPhotons ) 
+//                             + ( gkSolidAngleRatioErr * gkSolidAngleRatioErr / gkSolidAngleRatio / gkSolidAngleRatio )
+//                             + ( gkPINDiodeQEErr * gkPINDiodeQEErr / gkPINDiodeQE / gkPINDiodeQE )
+//                               ) * fFluxOutsidePlexiglass * * fFluxOutsidePlexiglass
+//
+// If the fFluxOutsidePlexiglass is smaller than 0., return kFALSE
+// If the Variance is smaller than 0., return kFALSE
+//
+// SetFluxOutsidePlexiglassAvailable() and return kTRUE
+//
+Bool_t MCalibrationChargePINDiode::CalcFluxOutsidePlexiglass()
+{
+
+  if (IsChargeFitValid())
+    return kFALSE;
+  
+  //
+  // Start calculation of number of photons per mm^2 on an inner pixel:
+  // Correct for the distance between camera and PIN Diode and for different areas.
+  //
+  switch (fColor)
+    {
+    case MCalibrationCam::kGREEN:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio           * gkPINDiodeQEGreen;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar()  + GetPINDiodeQEGreenRelVar();
+      break;
+    case MCalibrationCam::kBLUE:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio           * gkPINDiodeQEBlue;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar()  + GetPINDiodeQEBlueRelVar();
+      break; 
+    case MCalibrationCam::kUV:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio          * gkPINDiodeQEUV;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar() + GetPINDiodeQEUVRelVar();
+      break;
+    case MCalibrationCam::kCT1:
+    default:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio          * gkPINDiodeQECT1;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar() + GetPINDiodeQECT1RelVar();
+      break;
+    }
+
+  //
+  // Finish calculation of errors -> convert from relative variance to absolute variance
+  //
+  fFluxOutsidePlexiglassVar *= fFluxOutsidePlexiglass * fFluxOutsidePlexiglass;
+
+  if (fFluxOutsidePlexiglass < 0.)
+      return kFALSE;
+
+  if (fFluxOutsidePlexiglassVar < 0.)
+      return kFALSE;
+
+  SetFluxOutsidePlexiglassAvailable();  
+
+  *fLog << inf << endl;
+  *fLog << inf << " Mean Photon flux [ph/mm^2] outside Plexiglass: " 
+        << Form("%5.3f%s%5.3f",fFluxOutsidePlexiglass," +- ",GetFluxOutsidePlexiglassErr()) << endl;
+
+  return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePINDiode.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePINDiode.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePINDiode.h	(revision 17960)
@@ -0,0 +1,114 @@
+#ifndef MARS_MCalibrationChargePINDiode
+#define MARS_MCalibrationChargePINDiode
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationChargePINDiode : public MCalibrationPix
+{
+private:
+
+  static const Float_t fgChargeToPhotons;     //! Default for fChargeToPhotons
+  static const Float_t fgChargeToPhotonsErr;  //! Default for fChargeToPhotonsVar
+  static const Float_t gkPINDiodeQEGreen;     //! Quantum Efficiency at 520 nm
+  static const Float_t gkPINDiodeQEBlue;      //! Quantum Efficiency at 460 nm
+  static const Float_t gkPINDiodeQEUV;        //! Quantum Efficiency at 370 nm
+  static const Float_t gkPINDiodeQECT1;       //! Quantum Efficiency at 370 nm
+  static const Float_t gkPINDiodeQEGreenErr;  //! Uncertainty QE at 520 nm
+  static const Float_t gkPINDiodeQEBlueErr;   //! Uncertainty QE at 460 nm
+  static const Float_t gkPINDiodeQEUVErr;     //! Uncertainty QE at 370 nm
+  static const Float_t gkPINDiodeQECT1Err;    //! Uncertainty QE at 370 nmu
+  static const Float_t gkAbsorptionWindow;    //! Absorption of the protection window (incl. EMS-wires)
+  static const Float_t gkSolidAngleRatio;     //! Solid angles ratio PIN Diode - inner pixel
+  static const Float_t gkSolidAngleRatioErr;  //! Error solid angle ratio PIN Diode - inn. pix.
+
+  Float_t fAbsTimeMean;               // Mean Absolute Arrival Time
+  Float_t fAbsTimeRms;                // RMS Mean Absolute Arrival Time
+  Byte_t  fCalibFlags;                // Bit-field for the class-own bits
+  Float_t fChargeLimit;               // Limit (in units of PedRMS) for acceptance fitted mean charge
+  Float_t fChargeErrLimit;            // Limit (in units of PedRMS) for acceptance fitted charge sigma
+  Float_t fChargeRelErrLimit;         // Limit (in units of Error of fitted charge) for acceptance fitted mean  
+  Float_t fChargeToPhotons;           // Mean conv. PIN Diode charge to number of incident photons
+  Float_t fChargeToPhotonsVar;        // Variance of mean conv. PIN Diode charge to nr. incident photons
+  Float_t fNumPhotons;                // Number photons incidident on PIN Diode
+  Float_t fNumPhotonsVar;             // Variance nr. photons incid. on PIN Diode
+  Float_t fFluxOutsidePlexiglass;     // Mean number photons in INNER PIXEL outside plexiglass
+  Float_t fFluxOutsidePlexiglassVar;  // Error on nr. photons in INNER PIXEL outside plexiglass
+  Float_t fPed;                       // Mean pedestal (from MPedestalPix)
+  Float_t fPedRms;                    // Pedestal  RMS (from MPedestalPix)
+  Float_t fRmsChargeMean;             // Mean of RMS of summed FADC slices distribution 
+  Float_t fRmsChargeMeanErr;          // Error on Mean RMS summed FADC slices distribution 
+  Float_t fRmsChargeSigma;            // Sigma of RMS of summed FADC slices distribution    
+  Float_t fRmsChargeSigmaErr;         // Error on Sigma RMS summed FADC slices distribution 
+  MCalibrationCam::PulserColor_t fColor; // Colour of the pulsed LEDs
+
+  enum  { kOscillating,
+          kChargeFitValid, kTimeFitValid, 
+	  kFluxOutsidePlexiglassAvailable  }; // Possible bits to be set
+
+  const Float_t GetPINDiodeQEGreenRelVar() const; 
+  const Float_t GetPINDiodeQEBlueRelVar () const; 
+  const Float_t GetPINDiodeQEUVRelVar   () const; 
+  const Float_t GetPINDiodeQECT1RelVar  () const;
+  const Float_t GetSolidAngleRatioRelVar() const; 
+
+ public:
+
+  MCalibrationChargePINDiode(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationChargePINDiode() {}
+  
+  void   Clear(Option_t *o="");
+  Bool_t CalcFluxOutsidePlexiglass();
+
+  // Getters
+  Float_t GetAbsTimeMean                  () const { return fAbsTimeMean;           }
+  Float_t GetAbsTimeRms                   () const { return fAbsTimeRms;            }
+  MCalibrationCam::PulserColor_t GetColor () const { return fColor;                 }
+  Float_t GetFluxOutsidePlexiglass        () const { return fFluxOutsidePlexiglass; }
+  Float_t GetFluxOutsidePlexiglassErr     () const;
+  Float_t GetFluxOutsidePlexiglassRelVar  () const;  
+  Float_t GetNumPhotons                   () const { return fNumPhotons;            } 
+  Float_t GetNumPhotonsErr                () const;
+  Float_t GetNumPhotonsRelVar             () const;
+  Float_t GetPed                          () const { return fPed;                   }
+  Float_t GetPedRms                       () const { return fPedRms;                }
+
+  Bool_t  IsChargeFitValid                () const;
+  Bool_t  IsTimeFitValid                  () const;
+  Bool_t  IsOscillating                   () const;
+  Bool_t  IsFluxOutsidePlexiglassAvailable() const;
+  
+  // Setters
+  void SetAbsTimeMean        ( const Float_t f      )                 { fAbsTimeMean        = f;   }
+  void SetAbsTimeRms         ( const Float_t f      )                 { fAbsTimeRms         = f;   }
+  void SetChargeToPhotons    ( const Float_t f=fgChargeToPhotons    ) { fChargeToPhotons    = f;   }  
+  void SetChargeToPhotonsErr ( const Float_t f=fgChargeToPhotonsErr ) { fChargeToPhotonsVar = f*f; }  
+  void SetColor              ( const MCalibrationCam::PulserColor_t color) { fColor = color;   }
+  void SetPedestal           (       Float_t ped, Float_t pedrms    );
+  void SetRmsChargeMean      ( const Float_t f      )                 { fRmsChargeMean      = f;   }
+  void SetRmsChargeMeanErr   ( const Float_t f      )                 { fRmsChargeMeanErr   = f;   }
+  void SetRmsChargeSigma     ( const Float_t f      )                 { fRmsChargeSigma     = f;   }
+  void SetRmsChargeSigmaErr  ( const Float_t f      )                 { fRmsChargeSigmaErr  = f;   }
+  void SetOscillating        ( const Bool_t b=kTRUE );
+  void SetChargeFitValid     ( const Bool_t b=kTRUE );
+  void SetTimeFitValid       ( const Bool_t b=kTRUE );
+  void SetFluxOutsidePlexiglassAvailable ( const Bool_t b = kTRUE );
+
+  ClassDef(MCalibrationChargePINDiode, 1)	// Container Charge Calibration Results PIN Diode
+};
+
+#endif   /* MARS_MCalibrationChargePINDiode */
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePix.cc	(revision 17960)
@@ -0,0 +1,1098 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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-2008
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         
+// MCalibrationChargePix                                                   
+//                                                                         
+// Storage container of the calibrated Charge of one pixel.
+//                                                                         
+// The following values are initialized to meaningful values:
+//
+// - The Electronic Rms to 1.5 per FADC slice
+// - The uncertainty about the Electronic RMS to 0.3 per slice
+// - The F-Factor is assumed to have been measured in Munich to 1.13 - 1.17.
+//   with the Munich definition of the F-Factor, thus:
+//   F = Sigma(Out)/Mean(Out) * Mean(In)/Sigma(In)
+//   Mean F-Factor (gkFFactor)     = 1.15
+//   Error F-Factor (gkFFactorErr) = 0.02
+//
+// The following variables are calculated inside this class:
+// -  fLoGainPedRmsSquare and fLoGainPedRmsSquareVar (see CalcLoGainPedestal())
+// -  fRSigmaSquare and fRSigmaSquareVar             (see CalcReducedSigma()  )
+// -  fPheFFactorMethod and fPheFFactorMethodVar     (see CalcFFactor()       )
+// -  fMeanConvFADC2Phe and fMeanConvFADC2PheVar     (see CalcConvFFactor()  )
+//
+// The following variables are set by MHCalibrationChargeCam:
+// -  fAbsTimeMean and fAbsTimeRms
+// -  all variables in MCalibrationPix
+//
+// The following variables are set by MCalibrationChargeCalc:
+// - fPed, fPedVar and fPedRms                         
+// - fMeanConvFADC2Phe
+// - fConvFADC2PheVar 
+// - fSigmaConvFADC2Phe
+// - fTotalFFactorFFactorMethod 
+// - fTotalFFactorFFactorMethodVar 
+//
+// The following variables are not yet implemented:
+// - fConversionHiLo and fConversionHiLoVar (now set fixed to 10. +- 2.5)
+//
+//  Error of all variables are calculated by error-propagation. Note that internally, 
+//  all error variables contain Variances in order to save the CPU-intensive square rooting 
+// 
+//  Low-Gain variables are stored internally unconverted, i.e. directly from the summed 
+//  FADC slices extraction results, but can be retrieved converted to High-Gain amplifications 
+//  by calls to: GetConvertedMean() or GetConvertedSigma()
+//
+// Inline Functions:
+// -----------------
+//
+// GetPedRms(): Get the pedestals RMS: Test bit kHiGainSaturation:
+//  If yes, return square root of fLoGainPedRmsSquare (if greater than 0,
+//  otherwise -1.), If no,  return fPedRms
+//
+// GetConvertedMean(): Get the Low Gain Mean Charge converted to High Gain
+//  amplification: Returns fLoGainMean multiplied with fConversionHiLo if
+//  IsHiGainSaturation(), else return fHiGainMean
+//
+// GetConvertedSigma(): Get the Low Gain Sigma converted to High Gain
+//  amplification: Returns fLoGainSigma multiplied with fConversionHiLo
+//  if IsHiGainSaturation() else return fHiGainSigma
+//
+// GetConvertedRSigmaSquare(): 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
+//
+// GetPheFFactorMethodRelVar(): 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
+//
+// GetMeanConvFADC2PheErr(): 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
+//
+// 
+// See also: MCalibrationChargeCam, MCalibrationChargeCalc,
+//           MHCalibrationChargeCam, MHCalibrationChargePix
+//
+//
+// ClassVersion 3:
+//  + fNumSaturated
+//
+// Class Version 4:
+//  +  Float_t fConversionHiLoSigma;             // Sigma of conversion factor betw. Hi and Lo Gain
+//  -  Float_t fMeanConvFADC2PheVar;             // Variance conversion factor (F-factor method)
+//  +  Float_t fMeanConvFADC2PheStatVar;         // Variance conversion factor, only stat. error
+//  +  Float_t fMeanConvFADC2PheSystVar;         // Variance conversion factor, only syst. error
+//  -  Float_t fMeanFFactorFADC2PhotVar;         // Variance mean F-Factor photons (F-factor method)
+//  +  Float_t fMeanFFactorFADC2PhotVar;         // Variance mean F-Factor photons, only stat. error
+//  -  Float_t fPheFFactorMethod;                // Number Phe's calculated (F-factor method)
+//  -  Float_t fPheFFactorMethodVar;             // Variance number of Phe's (F-factor method)
+//  +  Float_t fPheFFactorMethod;                // Number Phe's calculated  with F-factor method)
+//  +  Float_t fPheFFactorMethodStatVar;         // Variance number of Phe's, only stat. error
+//  +  Float_t fPheFFactorMethodSystVar;         // Variance number of Phe's, only syst. error
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargePix.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MBadPixelsPix.h"
+
+ClassImp(MCalibrationChargePix);
+
+using namespace std;
+
+const Float_t MCalibrationChargePix::gkElectronicPedRms    = 1.0;
+const Float_t MCalibrationChargePix::gkElectronicPedRmsErr = 0.35;
+const Float_t MCalibrationChargePix::gkFFactor             = 1.15;
+const Float_t MCalibrationChargePix::gkFFactorErr          = 0.02;
+
+const Float_t MCalibrationChargePix::fgConversionHiLo         = 10.;
+const Float_t MCalibrationChargePix::fgConversionHiLoErr      = 0.05;
+const Float_t MCalibrationChargePix::fgConversionHiLoSigma    = 2.5;
+const Float_t MCalibrationChargePix::fgPheFFactorMethodLimit  = 1.;
+const Float_t MCalibrationChargePix::fgConvFFactorRelErrLimit = 0.85;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Sets:
+// - fCalibFlags to 0
+// - fConversionHiLo to fgConversionHiLo
+// - fConversionHiLoVar to square of fgConversionHiLoErr
+// - fConvFFactorelErrLimit to fgConvFFactorRelErrLimit*fgConvFFactorelErrLimit
+// - fPheFFactorLimit to fgPheFFactorLimit
+// 
+// Calls:
+// - Clear()
+//
+MCalibrationChargePix::MCalibrationChargePix(const char *name, const char *title)
+    : fCalibFlags(0), fNumSaturated(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.;
+  fPheFFactorMethodStatVar          =  -1.;
+  fPheFFactorMethodSystVar          =  -1.;
+
+  fMeanConvFADC2Phe                 =  -1.;
+  fMeanConvFADC2PheStatVar          =  -1.;
+  fMeanConvFADC2PheSystVar          =  -1.;
+  fMeanFFactorFADC2Phot             =  -1.;
+  fMeanFFactorFADC2PhotVar          =  -1.;  
+
+  fNumSaturated                     =   0;
+
+  MCalibrationPix::Clear();
+}
+
+// -----------------------------------------------------
+//
+void MCalibrationChargePix::Copy(TObject& object) const
+{
+  MCalibrationChargePix &pix = (MCalibrationChargePix&)object;
+  
+  MCalibrationPix::Copy(pix);
+
+  //
+  // Copy the data members
+  //
+  pix.fAbsTimeMean                = fAbsTimeMean              ;
+  pix.fAbsTimeRms                 = fAbsTimeRms               ;
+  pix.fCalibFlags                 = fCalibFlags               ;
+  pix.fConversionHiLo             = fConversionHiLo           ;
+  pix.fConversionHiLoVar          = fConversionHiLoVar        ;
+  pix.fConversionHiLoSigma        = fConversionHiLoSigma      ;
+  pix.fConvFFactorRelVarLimit     = fConvFFactorRelVarLimit   ;
+  pix.fLoGainPedRmsSquare         = fLoGainPedRmsSquare       ;
+  pix.fLoGainPedRmsSquareVar      = fLoGainPedRmsSquareVar    ;
+  pix.fMeanConvFADC2Phe           = fMeanConvFADC2Phe         ;
+  pix.fMeanConvFADC2PheStatVar    = fMeanConvFADC2PheStatVar  ;
+  pix.fMeanConvFADC2PheSystVar    = fMeanConvFADC2PheSystVar  ;
+  pix.fMeanFFactorFADC2Phot       = fMeanFFactorFADC2Phot     ;
+  pix.fMeanFFactorFADC2PhotVar    = fMeanFFactorFADC2PhotVar  ;
+  pix.fPed                        = fPed                      ;
+  pix.fPedVar                     = fPedVar                   ;
+  pix.fPedRms                     = fPedRms                     ;
+  pix.fPedRmsVar                  = fPedRmsVar                  ;
+  pix.fPheFFactorMethod           = fPheFFactorMethod           ;
+  pix.fPheFFactorMethodStatVar    = fPheFFactorMethodStatVar    ;
+  pix.fPheFFactorMethodSystVar    = fPheFFactorMethodSystVar    ;
+  pix.fPheFFactorMethodLimit      = fPheFFactorMethodLimit      ;
+  pix.fRSigmaSquare               = fRSigmaSquare               ;
+  pix.fRSigmaSquareVar            = fRSigmaSquareVar            ;
+  pix.fNumSaturated               = fNumSaturated               ;
+}                                  
+
+
+// --------------------------------------------------------------------------
+//
+// Set F-Factor Method Validity Bit from outside 
+//
+void MCalibrationChargePix::SetFFactorMethodValid(const Bool_t b )
+{ 
+  b ?  SETBIT(fCalibFlags, kFFactorMethodValid) : CLRBIT(fCalibFlags, kFFactorMethodValid); 
+}    
+
+// --------------------------------------------------------------------------
+//
+// Set pedestals from outside (done by MCalibrationChargeCalc)
+//
+void MCalibrationChargePix::SetPedestal(const Float_t ped, const Float_t pedrms, const Float_t pederr)
+{
+  fPed       = ped;    
+  fPedRms    = pedrms;
+  fPedVar    = pederr*pederr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set pedestals from outside (done by MCalibrationChargeCalc)
+//
+void MCalibrationChargePix::SetPed(const Float_t ped, const Float_t pederr)
+{
+  fPed       = ped;    
+  fPedVar    = pederr*pederr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set pedestals RMS from outside (done by MHCalibrationChargeCam)
+//
+void MCalibrationChargePix::SetPedRMS( const Float_t pedrms, const Float_t pedrmserr)
+{
+  fPedRms    = pedrms;
+  fPedRmsVar = pedrmserr*pedrmserr;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Get the conversion Error Hi-Gain to Low-Gain:
+//  If fConversionHiLoVar is smaller than 0 (i.e. has not yet
+//  been set), return -1.
+//  
+Float_t MCalibrationChargePix::GetConversionHiLoErr() const
+{
+    return fConversionHiLoVar<0 ? -1 : TMath::Sqrt(fConversionHiLoVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Error of the converted Low Gain Mean: Returns -1 if the
+// variable fLoGainMean or fLoGainMeanVar are smaller than 0. Returns the
+// square root of the quadratic sum of the relative variances of the
+// fLoGainMean and fConversionHiLo, mulitplied with GetConvertedMean() in
+// case of HiGain Saturation, else return GetMeanErr()
+//
+Float_t MCalibrationChargePix::GetConvertedMeanErr() const
+{
+    if (!IsHiGainSaturation())
+        return GetMeanErr();
+
+    const Float_t logainrelvar = GetLoGainMeanRelVar();
+    return logainrelvar<0 ? -1 : TMath::Sqrt(logainrelvar + GetConversionHiLoRelVar()) * GetConvertedMean();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Error of the converted Sigma: Returns -1 if the variable
+// fLoGainSigma or fLoGainSigmaVar are smaller than 0. if
+// IsHiGainSaturatio() returns the square root of the quadratic sum of the
+// relative variances of the fLoGainSigma and fConversionHiLo, mulitplied
+// with GetConvertedSigma() else returns GetSigmaErr()
+//
+Float_t MCalibrationChargePix::GetConvertedSigmaErr() const
+{
+    if (!IsHiGainSaturation())
+        return GetSigmaErr();
+
+    if (fLoGainSigmaVar<0 || fLoGainSigma<0)
+        return -1.;
+
+    const Float_t sigmaRelVar = fLoGainSigmaVar/(fLoGainSigma*fLoGainSigma);
+    return TMath::Sqrt(sigmaRelVar+GetConversionHiLoRelVar()) * GetConvertedSigma();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the converted reduced Sigma: If fRSigmaSquare is smaller than 0
+// (i.e. has not yet been set), return -1. Test bit kHiGainSaturation: If
+// yes, return square root of fRSigmaSquare, multiplied with
+// fConversionHiLo, If no , return square root of fRSigmaSquare
+//
+Float_t MCalibrationChargePix::GetConvertedRSigma() const
+{
+    if (fRSigmaSquare < 0)
+        return -1;
+
+    const Float_t rsigma = TMath::Sqrt(fRSigmaSquare);
+    return IsHiGainSaturation() ? rsigma*fConversionHiLo : rsigma ;
+}
+
+// --------------------------------------------------------------------------
+//
+Float_t MCalibrationChargePix::GetMeanConvFADC2PheErr() const
+{
+    return fMeanConvFADC2PheStatVar<0 ? -1 : TMath::Sqrt(fMeanConvFADC2PheStatVar);
+}
+
+// --------------------------------------------------------------------------
+//
+Float_t MCalibrationChargePix::GetMeanConvFADC2PheSystErr() const
+{
+    return fMeanConvFADC2PheSystVar<0 ? -1 : TMath::Sqrt(fMeanConvFADC2PheSystVar);
+}
+
+// --------------------------------------------------------------------------
+//
+Float_t MCalibrationChargePix::GetMeanConvFADC2PheTotErr() const
+{
+    if (fMeanConvFADC2PheSystVar<0 || fMeanConvFADC2PheStatVar<0)
+        return -1.;
+
+    return TMath::Sqrt(fMeanConvFADC2PheSystVar+fMeanConvFADC2PheStatVar);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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
+{
+    return fMeanFFactorFADC2PhotVar<0 ? -1. : TMath::Sqrt(fMeanFFactorFADC2PhotVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the conversion factor between higain and logain:
+// - If fConversionHiLo    is 0,              return -1.
+// - If fConversionHiLoVar is smaller than 0, return -1.
+// - Else returns: fConversionHiLoVar / fConversionHiLo^2
+//
+const Float_t MCalibrationChargePix::GetConversionHiLoRelVar() const 
+{
+
+  if (fConversionHiLoVar < 0.)
+    return -1.;
+
+  if (fConversionHiLo == 0.)
+    return -1.;
+
+  return fConversionHiLoVar / (fConversionHiLo * fConversionHiLo);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the electronics pedestal RMS
+// - returns rel. variance of gkElectronicPedRms
+//
+const Float_t MCalibrationChargePix::GetElectronicPedRmsRelVar() const 
+{
+  return gkElectronicPedRmsErr * gkElectronicPedRmsErr / gkElectronicPedRms / gkElectronicPedRms;
+}
+ 
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the conversion factor between higain and logain:
+// - If gkFFactor    is 0,              return -1.
+// - If gkFFactorErr is smaller than 0, return -1.
+// - Else returns: gkFFactorErr^2 / gkFFactor*^2
+//
+const Float_t MCalibrationChargePix::GetFFactorRelVar() const 
+{
+
+  if (gkFFactorErr < 0.)
+    return -1.;
+
+  if (gkFFactor == 0.)
+    return -1.;
+
+  return gkFFactorErr * gkFFactorErr / (gkFFactor * gkFFactor);
+}
+
+// --------------------------------------------------------------------------
+//
+Float_t MCalibrationChargePix::GetPedErr() const
+{
+    return TMath::Sqrt(fPedVar);
+}
+
+// --------------------------------------------------------------------------
+//
+Float_t MCalibrationChargePix::GetPedRms() const
+{
+    if (!IsHiGainSaturation())
+        return fPedRms;
+
+    return fLoGainPedRmsSquare<0 ? -1 : TMath::Sqrt(fLoGainPedRmsSquare);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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())
+      return fLoGainPedRmsSquareVar < 0. ? -1. :TMath::Sqrt(0.25*fLoGainPedRmsSquareVar/fLoGainPedRmsSquare);
+  else
+      return fPedVar < 0. ? -1. : TMath::Sqrt(fPedVar)/2.;
+}
+
+// --------------------------------------------------------------------------
+//
+// GetPheFFactorMethodErr(): 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
+{
+    return fPheFFactorMethodStatVar<0 ? -1 : TMath::Sqrt(fPheFFactorMethodStatVar);
+}
+
+// --------------------------------------------------------------------------
+//
+Float_t MCalibrationChargePix::GetPheFFactorMethodSystErr() const
+{
+    return fPheFFactorMethodSystVar<0 ? -1 : TMath::Sqrt(fPheFFactorMethodSystVar);
+}
+
+// --------------------------------------------------------------------------
+//
+Float_t MCalibrationChargePix::GetPheFFactorMethodTotErr() const
+{
+    if (fPheFFactorMethodStatVar<0 || fPheFFactorMethodSystVar<0)
+        return -1.;
+
+    return TMath::Sqrt(fPheFFactorMethodStatVar+fPheFFactorMethodSystVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the error of the converted reduced Sigma: 
+// - If fRSigmaSquareVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Calculate the absolute variance of the reduced sigma with the formula:
+//   reduced sigma variance = 0.25 * fRSigmaSquareVar / fRSigmaSquare
+// - Test bit kHiGainSaturation: 
+//   If yes, returns the square root of the quadratic sum of the relative variances of the 
+//           reduced sigma and fConversionHiLo, mulitplied with GetRSigma()
+//   Else returns the square root of rel. (0.25*fRSigmaSquareVar / fRSigmaSquare)
+//
+Float_t MCalibrationChargePix::GetConvertedRSigmaErr()  const
+{
+
+  if (fRSigmaSquareVar < 0)
+    return -1;
+
+  //
+  // SigmaSquareVar = 4. * Sigma * Sigma * Var(sigma)
+  // ==> Var(sigma) = 0.25 * SigmaSquareVar / (Sigma * Sigma)
+  //
+  const Float_t rsigmaVar = 0.25 * fRSigmaSquareVar / fRSigmaSquare;
+
+  if (IsHiGainSaturation())
+    return TMath::Sqrt(rsigmaVar/fRSigmaSquare + GetConversionHiLoRelVar()) * GetRSigma();
+  else
+    return TMath::Sqrt(rsigmaVar);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the reduced Sigma:
+// If fRSigmaSquare is smaller than 0 (i.e. has not yet been set),
+// return -1.
+//
+Float_t MCalibrationChargePix::GetRSigma() const
+{
+    return fRSigmaSquare<0 ? -1 : TMath::Sqrt(fRSigmaSquare);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the error of the reduced Sigma: 
+// - If fRSigmaSquareVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Calculate the absolute variance of the reduced sigma with the formula:
+//   reduced sigma variance = 0.25 * fRSigmaSquareVar / fRSigmaSquare
+//
+Float_t MCalibrationChargePix::GetRSigmaErr()  const
+{
+
+  if (fRSigmaSquareVar < 0)
+    return -1;
+
+  //
+  // SigmaSquareVar = 4. * Sigma * Sigma * Var(sigma)
+  // ==> Var(sigma) = 0.25 * SigmaSquareVar / (Sigma * Sigma)
+  //
+  return TMath::Sqrt(0.25 * fRSigmaSquareVar / fRSigmaSquare);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the reduced Sigma per Charge: 
+// - If GetRSigma() is smaller or equal 0. (i.e. has not yet been set), return -1.
+// - If GetMean() is 0. or -1. (i.e. has not yet been set), return -1.
+// - Return GetRSigma() / GetMean() 
+//
+Float_t MCalibrationChargePix::GetRSigmaPerCharge()  const 
+{
+  
+  const Float_t rsigma = GetRSigma();
+
+  if (rsigma <= 0)
+    return -1.;
+  
+
+  const Float_t mean   = GetMean();
+  
+  if (mean == 0. || mean == -1.)
+    return -1.;
+  
+  return rsigma / mean;
+} 
+
+
+// --------------------------------------------------------------------------
+//
+// Get the error of the reduced Sigma per Charge: 
+// - If GetRSigmaRelVar() is smaller or equal 0. (i.e. has not yet been set), return -1.
+// - If GetMeanRelVar() is smaller or equal 0. (i.e. has not yet been set), return -1.
+// - Return the propagated error of GetRSigmaPerCharge() 
+//
+Float_t MCalibrationChargePix::GetRSigmaPerChargeErr()  const 
+{
+  
+  const Float_t rsigmarelvar  = GetRSigmaRelVar();
+
+  if (rsigmarelvar <= 0)
+    return -1.;
+  
+
+  const Float_t meanrelvar   = GetMeanRelVar();
+  
+  if (meanrelvar <= 0.)
+    return -1.;
+  
+  return TMath::Sqrt(rsigmarelvar + meanrelvar) * GetRSigmaPerCharge();
+} 
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the reduced Sigma: 
+// - If fRSigmaSquareVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Calculate the relative variance of the reduced sigma squares with the formula:
+//   reduced sigma rel. variance = 0.25 * fRSigmaSquareVar / fRSigmaSquare / fRSigmaSquare
+// - Test bit kHiGainSaturation: 
+//   If yes, returns the sum of the relative variances of the reduced sigma and fConversionHiLo
+//   Else returns the relative variance of the reduced sigma
+//
+Float_t MCalibrationChargePix::GetRSigmaRelVar()  const
+{
+
+  if (fRSigmaSquareVar < 0)
+    return -1;
+
+  //
+  // SigmaSquareVar = 4. * Sigma * Sigma * Var(sigma)
+  // ==> Var(sigma) = 0.25 * SigmaSquareVar / (Sigma * Sigma)
+  //
+  return 0.25 * fRSigmaSquareVar / ( fRSigmaSquare * fRSigmaSquare );
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// 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(const Float_t extractorres)
+{
+
+  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 extractorresVar = extractorres * extractorres;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " HiGainSaturation: " << IsHiGainSaturation() 
+            << " Sigma: " << sigma 
+            << " Var.Sigma: " << sigmavar
+            << " PedRmsSquare: " << pedRmsSquare
+            << " pedRmsSquareVar: " << pedRmsSquareVar
+	    << " extractorresVar: " << extractorresVar
+            << endl;
+    }
+  
+  const Float_t sigmaSquare    =      sigma     * sigma;
+  const Float_t sigmaSquareVar = 4. * sigmavar  * sigmaSquare;
+
+  //
+  // Calculate the reduced sigmas
+  //
+  fRSigmaSquare = sigmaSquare - pedRmsSquare - extractorresVar;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Red.Sigma Square: " << fRSigmaSquare
+            << endl;
+    }
+  
+  if (fRSigmaSquare <= 0.)
+    {
+      if (IsDebug())
+        *fLog << warn 
+              << "WARNING: Cannot calculate the reduced sigma: smaller than 0 in pixel " 
+              << fPixId << endl;
+      return kFALSE;
+    }
+
+  
+  fRSigmaSquareVar = 4. * (sigmaSquareVar + pedRmsSquareVar);
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Var.Red.Sigma Square: " << fRSigmaSquareVar
+            << endl;
+    }
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------
+//
+// If fRSigmaSquare is smaller than 0 (i.e. has not yet been set),
+// return kFALSE
+//
+// Calculate the number of photo-electrons with the F-Factor method:
+// - Test bit IsHiGainSaturation() for the Mean Sum of FADC slices: 
+//   If yes, take fLoGainMean and fLoGainMeanVar 
+//   If no , take fHiGainMean and fHiGainMeanVar 
+//
+// - Test bit IsHiGainSaturation() for the pedRMS: 
+//   If yes, take fLoGainPedRmsSquare and fLoGainPedRmsSquareVar
+//   If no , take fPedRms and fPedVar
+//
+// - Calculate the number of photo-electrons with the formula:
+//   fPheFFactorMethod   = gkFFactor*gkFFactor * Mean * Mean  / fRSigmaSquare
+//
+// - Calculate the Variance on the photo-electrons with the formula:
+//   fPheFFactorMethodVar =  (  4. * gkFFactorErr * gkFFactorErr / ( gkFFactor * gkFFactor ) 
+//                            + 4. * Mean Var.   / ( Mean * Mean )
+//                            + fRSigmaSquareVar / fRSigmaSquare
+//                            ) * fPheFFactorMethod * fPheFFactorMethod
+//
+// - If fPheFFactorMethod is less than fPheFFactorMethodLimit, 
+//   set kFFactorMethodValid to kFALSE and return kFALSE
+//
+Bool_t MCalibrationChargePix::CalcFFactor()
+{
+    SetFFactorMethodValid(kFALSE);
+
+    if (fRSigmaSquare < 0.)
+        return kFALSE;
+  
+  //
+  // Square all variables in order to avoid applications of square root
+  //
+  const Float_t meanSquare          =     GetMean()    * GetMean();
+  const Float_t meanSquareRelVar    = 4.* GetMeanRelVar();
+
+  const Float_t ffactorsquare       =     gkFFactor    * gkFFactor;
+  const Float_t ffactorsquareRelVar = 4.* GetFFactorRelVar();
+
+  const Float_t rsigmaSquareRelVar  =     fRSigmaSquareVar / fRSigmaSquare / fRSigmaSquare;
+  //
+  // Calculate the number of phe's from the F-Factor method
+  // (independent on Hi Gain or Lo Gain)
+  //
+  fPheFFactorMethod = ffactorsquare * meanSquare / fRSigmaSquare;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " F-Factor Square: " << ffactorsquare
+            << " Mean Square: " << meanSquare
+            << " Red.Sigma Square: " << fRSigmaSquare
+            << " Photo-electrons: " << fPheFFactorMethod
+            << endl;
+    }
+
+  if (fPheFFactorMethod < fPheFFactorMethodLimit)
+    return kFALSE;
+  
+  //
+  // Calculate the Error of Nphe
+  //
+  const Float_t pheRelVar  = meanSquareRelVar + rsigmaSquareRelVar;
+  fPheFFactorMethodStatVar = pheRelVar * fPheFFactorMethod * fPheFFactorMethod;
+  fPheFFactorMethodSystVar = ffactorsquareRelVar * fPheFFactorMethod * fPheFFactorMethod;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Rel.Var.F-Factor Square: " << ffactorsquareRelVar
+            << " Rel.Var. Mean Square: " << meanSquareRelVar
+            << " Rel.Var. Red.Sigma Square: " << rsigmaSquareRelVar
+            << " Rel.Var. Photo-electrons: " << pheRelVar
+            << endl;
+    }
+
+  if (fPheFFactorMethodStatVar < 0. )
+    return kFALSE;
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------
+//
+// If fPheFFactorMethod is smaller than 0 (i.e. has not yet been set),
+// return kFALSE
+//
+// If GetCovertedMean() is smaller than 0 (i.e. has not yet been set),
+// return kFALSE
+//
+// Calculate fMeanConvFADC2Phe with the following formula:
+//
+//      fMeanConvFADC2Phe    =  fPheFFactorMethod / GetConvMean();
+//
+// Calculate the rel. variance of fMeanConvFADC2Phe, taking into account that 
+// in the calculation of the number of phe's one mean square has already been used. 
+// Now, dividing by another mean, one mean calcels out, one cannot directly propagate
+// the errors, but instead havs to take into account this cancellation:
+// 
+//     convrelvar = ffactorsquareRelVar + GetMeanRelVar() + rsigmaSquareRelVar;
+//
+// If confrelvar is smaller than 0. or greater than fConvFFactorRelVarLimit, 
+// return kFALSE
+// 
+// Calculate the variance of fMeanConvFADC2Phe with the formula:
+//
+//    fMeanConvFADC2PheVar =  convrelvar * fMeanConvFADC2Phe * fMeanConvFADC2Phe;
+// 
+// Set kFFactorMethodValid to kTRUE and 
+// return kTRUE
+//
+Bool_t MCalibrationChargePix::CalcConvFFactor()
+{
+  
+  if (fPheFFactorMethod <= 0.)
+    return kFALSE;
+
+  const Float_t convmean = GetConvertedMean();
+
+  if (convmean <= 0.)
+    return kFALSE;
+  
+  fMeanConvFADC2Phe    =  fPheFFactorMethod / convmean;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Converted Mean: " << convmean 
+            << " Conversion FADC2Phe: " << fMeanConvFADC2Phe
+            << endl;
+    }
+
+  const Float_t ffactorsquareRelVar = 4.* GetFFactorRelVar();
+  const Float_t rsigmaSquareRelVar  = fRSigmaSquareVar / fRSigmaSquare / fRSigmaSquare;
+  //
+  // In the calculation of the number of phe's one mean square has already been used. 
+  // Now, we divide by another mean, so one mean calcels out, we cannot directly propagate
+  // the errors, but have to take account of this cancellation:
+  // 
+  Float_t convrelvar = GetMeanRelVar() + rsigmaSquareRelVar;
+  if (IsHiGainSaturation())
+      convrelvar += GetConversionHiLoRelVar();
+
+  const Float_t limit = IsHiGainSaturation() ? fConvFFactorRelVarLimit * 4. : fConvFFactorRelVarLimit;
+
+  //
+  // Also have to take into account the pixels labelled MBadPixelsPix::kChargeSigmaNotValid which do not 
+  // have a fRSigmaSquareVar, calculate their error directly!
+  //
+  if (fRSigmaSquareVar < 0.)
+    convrelvar = GetMeanRelVar() + GetPheFFactorMethodRelVar();
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Rel.Var.Red.Sigma: " << rsigmaSquareRelVar
+            << " Rel.Var.Mean: " << GetMeanRelVar()
+            << " Rel.Var.F-Factor: " << ffactorsquareRelVar
+            << " Rel.Var.Conversion FADC2Phe: " << convrelvar
+            << endl;
+    }
+
+  if (convrelvar > limit || convrelvar < 0.)
+    {
+        *fLog << warn << "pixel  " << setw(4) << fPixId << ": Conv. F-Factor Method Rel. Var.: "
+            << Form("%4.3f out of limits: [0,%3.2f]",convrelvar,limit) << endl;
+        return kFALSE;
+    }
+  
+  fMeanConvFADC2PheStatVar = convrelvar * fMeanConvFADC2Phe  * fMeanConvFADC2Phe;
+  fMeanConvFADC2PheSystVar = ffactorsquareRelVar * fMeanConvFADC2Phe * fMeanConvFADC2Phe;
+  
+  SetFFactorMethodValid(kTRUE);
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//
+// If photflux is smaller or equal 0, return kFALSE
+//
+// Calculate the total F-Factor with the formula:
+//   fMeanFFactorFADC2Phot = Sqrt ( fRSigmaSquare ) / GetMean()  * sqrt(nphotons)
+//
+// Calculate the error of the total F-Factor
+//
+Bool_t MCalibrationChargePix::CalcMeanFFactor( const Float_t nphotons, const Float_t nphotonsrelvar )
+{
+
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Number photons: " << nphotons
+            << " Rel.Var.Number photons: " << nphotonsrelvar
+            << " Red.Sigma Square: " << fRSigmaSquare
+            << " Mean: " << GetMean()
+            << endl;
+    }
+
+
+  if (nphotons <= 0.)
+    {
+      *fLog << warn << GetDescriptor() << ": Assumed photon flux is smaller or equal 0." << endl;
+      return kFALSE;
+    }
+
+  if (nphotonsrelvar < 0.)
+    {
+      *fLog << warn << GetDescriptor() << ": Assumed photon flux variance is smaller than 0." << endl;
+      return kFALSE;
+    }
+
+  fMeanFFactorFADC2Phot =  TMath::Sqrt(fRSigmaSquare * nphotons) / GetMean() ;
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " F-Factor FADC2Phot: " << fMeanFFactorFADC2Phot
+            << endl;
+    }
+
+  if (fMeanFFactorFADC2Phot < 0.)
+    {
+      *fLog << warn << GetDescriptor() << ": F-Factor photons to FADC counts smaller than 0." << endl;
+      return kFALSE;
+    }
+  
+  const Float_t ffactorrelvar = 0.25 * fRSigmaSquareVar / ( fRSigmaSquare * fRSigmaSquare) 
+                              + GetMeanRelVar() 
+                              + 0.25 * nphotonsrelvar;
+  
+  fMeanFFactorFADC2PhotVar = ffactorrelvar * fMeanFFactorFADC2Phot * fMeanFFactorFADC2Phot;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Rel.Var.Red.Sigma: " << 0.25 * fRSigmaSquareVar / ( fRSigmaSquare * fRSigmaSquare) 
+            << " Rel.Var.Mean: " << GetMeanRelVar()
+            << " Rel.Var.photons: " << 0.25 * nphotonsrelvar
+            << " Rel.Var.F-Factor FADC2Phot: " << ffactorrelvar
+            << endl;
+    }
+
+  return kTRUE;
+}
+
+
+// ----------------------------------------------------------------------------
+// 
+// - If fPed    is smaller than 0 (i.e. has not yet been set), return.
+// - If fPedVar is smaller than 0 (i.e. has not yet been set), return.
+//
+// Calculate the electronic pedestal RMS with the formula:
+//  - elec. pedestal = gkElectronicPedRms * sqrt(logainsamples)
+// 
+// Calculate the night sky background ped. RMS contribution ("NSB") in the high-gain 
+// from the high gain Pedestal RMS with the formula:
+// - HiGain NSB square      = fPedRms * fPedRms - elec.ped.* elec.ped.
+// - Var(HiGain NSB square) = fPedVar * fPedRms * fPedRms + 4.*elecPedRmsVar * elec.ped.* elec.ped.
+//
+// If HiGain NSB square is smaller than 0., set it to zero. (but not the error!)
+//
+// Convert the NSB ped. RMS contribution to the low-gain with the formula:
+// - LoGain NSB square      =  HiGain NSB square / (fConversionHiLo*fConversionHiLo)
+// - Var(LoGain NSB square) = ( Var(HiGain NSB square) / (HiGain NSB square * HiGain NSB square)
+//                              + GetConversionHiLoRelVar()   
+//                            ) * LoGain NSB square * LoGain NSB square
+//
+// - Low Gain Ped RMS Square       = LoGain NSB square      + elec.ped. square
+//   Var (Low Gain Ped RMS Square) = Var(LoGain NSB square) + Var(elec.ped. square)
+//
+void MCalibrationChargePix::CalcLoGainPedestal(Float_t logainsamples)
+{
+
+  if (fPedRms < 0.)
+    return;
+
+  if (fPedVar < 0.)
+    return;
+
+  const Float_t elecPedRms     = gkElectronicPedRms * TMath::Sqrt(logainsamples);
+  const Float_t elecPedRmsVar  = GetElectronicPedRmsRelVar() * elecPedRms * elecPedRms;
+  
+  Float_t pedRmsSquare         = fPedRms * fPedRms;
+  Float_t pedRmsSquareVar      = fPedVar * pedRmsSquare; // fPedRmsErr = fPedErr/2.
+  
+  //
+  // We do not know the Low Gain Pedestal RMS, so we have to retrieve it 
+  // from the High Gain:  
+  //
+  // We extract the pure NSB contribution:
+  //
+  const Float_t elecRmsSquare    =    elecPedRms    * elecPedRms;
+  const Float_t elecRmsSquareVar = 4.*elecPedRmsVar * elecRmsSquare;
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Ped.Rms Square:  " << pedRmsSquare 
+            << " Elec.Rms Square: " << elecRmsSquare 
+            << " Ped.Rms.Square Var.: " << pedRmsSquareVar 
+            << " Elec.Rms Square Var.: " << elecRmsSquareVar 
+            << endl;
+    }
+  
+
+  Float_t higainNsbSquare     =  pedRmsSquare    - elecRmsSquare;
+  Float_t higainNsbSquareVar  = (pedRmsSquareVar + elecRmsSquareVar);
+
+  if (higainNsbSquare < 0.001)
+    higainNsbSquare = 0.;
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " HiGain NSB Square:  " << higainNsbSquare
+            << " Var.HiGain NSB Square:  " << higainNsbSquareVar
+            << endl;
+    }
+  
+  //
+  // Now, we divide the NSB by the conversion factor and 
+  // add it quadratically to the electronic noise
+  //
+  const Float_t conversionSquare        =     fConversionHiLo    * fConversionHiLo;
+  const Float_t conversionSquareRelVar  = 4.* GetConversionHiLoRelVar();
+
+  const Float_t logainNsbSquare         =   higainNsbSquare       / conversionSquare;
+  //
+  // Calculation of variance of: c = a/b
+  //                    Delta(c)^2 = ( Delta(a)^2 + a^2/b^2*(Delta(b)^2 )  / b^2
+  //
+  const Float_t logainNsbSquareVar      = ( higainNsbSquareVar 
+                                         + conversionSquareRelVar * higainNsbSquare * higainNsbSquare ) 
+                                          / conversionSquare / conversionSquare;
+    
+  fLoGainPedRmsSquare    = logainNsbSquare    + elecRmsSquare;
+  fLoGainPedRmsSquareVar = logainNsbSquareVar + elecRmsSquareVar;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " LoGain Ped Rms Square:  " << fLoGainPedRmsSquare
+            << " Var.Ped Rms Square:  " << fLoGainPedRmsSquareVar
+            << endl;
+    }
+  
+  
+}
+ 
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationChargePix.h	(revision 17960)
@@ -0,0 +1,167 @@
+#ifndef MARS_MCalibrationChargePix
+#define MARS_MCalibrationChargePix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationChargePix : public MCalibrationPix
+{
+private:
+
+  static const Float_t gkElectronicPedRms;     //! Electronic component of ped. RMS from opt. receiver on (now set to: 1.)
+  static const Float_t gkElectronicPedRmsErr;  //! Error Electr. component ped. RMS (now set to: 0.35)
+  static const Float_t gkFFactor;              //! Laboratory F-factor PMTs         (now set to: 1.15)
+  static const Float_t gkFFactorErr;           //! Laboratory F-factor Error PMTs   (now set to: 0.02)
+
+  static const Float_t fgConversionHiLo;         //! Default fConversionHiLo          (now set to: 10.)
+  static const Float_t fgConversionHiLoErr;      //! Default fConversionHiLoVar       (now set to: 2.5)
+  static const Float_t fgConversionHiLoSigma;    //! Default fConversionHiLoSigma     (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 fConversionHiLoSigma;             // Sigma of 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 fMeanConvFADC2PheStatVar;         // Variance conversion factor, only stat. error
+  Float_t fMeanConvFADC2PheSystVar;         // Variance conversion factor, only syst. error
+  Float_t fMeanFFactorFADC2Phot;            // Total mean F-Factor to photons (F-factor method)
+  Float_t fMeanFFactorFADC2PhotVar;         // Variance mean F-Factor photons, only stat. error
+  Float_t fPed;                             // Pedestal (from MPedestalPix) times number FADC slices
+  Float_t fPedVar;                          // Variance of pedestal 
+  Float_t fPedRms;                          // Pedestal RMS (from MPedestalPix) times sqrt nr. FADC slices
+  Float_t fPedRmsVar;                       // Pedestal RMS (from MPedestalPix) times sqrt nr. FADC slices
+  Float_t fPheFFactorMethod;                // Number Phe's calculated  with F-factor method)
+  Float_t fPheFFactorMethodStatVar;         // Variance number of Phe's, only stat. error
+  Float_t fPheFFactorMethodSystVar;         // Variance number of Phe's, only syst. error
+  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
+
+  Int_t   fNumSaturated;                    // Number of (high-gain) saturated events
+  
+  enum  { kFFactorMethodValid   };          // Possible bits to be set
+
+  const Float_t GetElectronicPedRmsRelVar() const;
+  const Float_t GetConversionHiLoRelVar()  const;
+  const Float_t GetFFactorRelVar()     const;
+  
+public:
+  MCalibrationChargePix(const char *name=NULL, const char *title=NULL);
+
+  // TObject
+  void Clear(Option_t *o="");
+  void Copy(TObject& object) const;
+
+  // Setter
+  /*
+  void SetConvFFactorRelErrLimit   ( const Float_t f=fgConvFFactorRelErrLimit) { fConvFFactorRelVarLimit = f*f;}
+  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 SetPheFFactorMethod      ( const Float_t f)                          { fPheFFactorMethod       = f; }
+  void SetPheFFactorMethodVar   ( const Float_t f)                          { fPheFFactorMethodVar    = f; }  
+  void SetPheFFactorMethodLimit ( const Float_t f=fgPheFFactorMethodLimit ) { fPheFFactorMethodLimit  = f; }
+  void SetNumSaturated          ( const Int_t   i)                          { fNumSaturated           = i; }
+  */
+  void SetFFactorMethodValid     (const Bool_t b = kTRUE );
+  void SetPedestal               (const Float_t ped, const Float_t pedrms, const Float_t pederr);
+  void SetPed                   ( const Float_t ped, const Float_t pederr);  
+  void SetPedRMS              ( const Float_t pedrms, const Float_t pedrmserr);  
+
+  void 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 SetConversionHiLoSigma    (const Float_t s=fgConversionHiLoSigma   ) { fConversionHiLoSigma    = s; }
+  void SetConvFFactorRelErrLimit (const Float_t f=fgConvFFactorRelErrLimit) { fConvFFactorRelVarLimit = f*f;}
+  void SetMeanConvFADC2Phe       (const Float_t f)                          { fMeanConvFADC2Phe       = f; }
+  void SetMeanConvFADC2PheVar    (const Float_t f)                          { fMeanConvFADC2PheStatVar= f; }
+  void SetMeanConvFADC2PheSystVar(const Float_t f)                          { fMeanConvFADC2PheSystVar= f; }
+  void SetMeanFFactorFADC2Phot   (const Float_t f)                          { fMeanFFactorFADC2Phot   = f; }
+  void SetNumSaturated           (const Int_t   i)                          { fNumSaturated           = i; }
+  void SetPheFFactorMethod       (const Float_t f)                          { fPheFFactorMethod       = f; }
+  void SetPheFFactorMethodVar    (const Float_t f)                          { fPheFFactorMethodStatVar= f; }
+  void SetPheFFactorMethodSystVar(const Float_t f)                          { fPheFFactorMethodSystVar= 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 GetConversionHiLoSigma() const { return fConversionHiLoSigma; }
+
+  Float_t GetConvertedMean      () const { return IsHiGainSaturation() ? fLoGainMean * fConversionHiLo : fHiGainMean; }
+  Float_t GetConvertedMeanErr   () const;
+
+  Float_t GetConvertedSigma() const { return IsHiGainSaturation() ? fLoGainSigma * fConversionHiLo : fHiGainSigma; }
+  Float_t GetConvertedSigmaErr() const;
+
+  Float_t GetConvertedRSigma() const;
+  Float_t GetConvertedRSigmaErr() const;
+  Float_t GetConvertedRSigmaSquare() const
+  {
+      if (fRSigmaSquare < 0)
+          return -1;
+      return IsHiGainSaturation() ? fRSigmaSquare*fConversionHiLo*fConversionHiLo : fRSigmaSquare ;
+  }
+
+  Float_t GetMeanConvFADC2Phe() const { return fMeanConvFADC2Phe; }
+  Float_t GetMeanConvFADC2PheErr() const;
+  Float_t GetMeanConvFADC2PheSystErr() const;
+  Float_t GetMeanConvFADC2PheTotErr() const;
+
+  Float_t GetFFactorFADC2Phe        () const { return gkFFactor;   }
+  Float_t GetMeanConvFADC2PheVar    () const { return fMeanConvFADC2PheStatVar; }
+  Float_t GetMeanConvFADC2PheSystVar() const { return fMeanConvFADC2PheSystVar; }
+
+  Float_t GetMeanFFactorFADC2Phot   () const { return fMeanFFactorFADC2Phot;    }
+  Float_t GetMeanFFactorFADC2PhotErr() const;
+  Float_t GetMeanFFactorFADC2PhotVar() const { return fMeanFFactorFADC2PhotVar; }
+
+  Int_t   GetNumSaturated           () const { return fNumSaturated;            }
+
+  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 GetPheFFactorMethodSystErr() const;
+  Float_t GetPheFFactorMethodTotErr() const;
+
+  Float_t GetPheFFactorMethodVar    () const { return fPheFFactorMethodStatVar; }
+  Float_t GetPheFFactorMethodSystVar() const { return fPheFFactorMethodSystVar; }
+  Float_t GetPheFFactorMethodRelVar () const { return fPheFFactorMethodStatVar<=0 ? -1 : fPheFFactorMethodStatVar / (fPheFFactorMethod * fPheFFactorMethod); }
+  Float_t GetPheFFactorMethodRelSystVar() const { return fPheFFactorMethodSystVar<=0 ? -1. : fPheFFactorMethodSystVar / (fPheFFactorMethod * fPheFFactorMethod); }
+
+  Float_t GetRSigma() const;
+  Float_t GetRSigmaErr() const;
+  Float_t GetRSigmaRelVar() const;
+  Float_t GetRSigmaPerCharge() const;
+  Float_t GetRSigmaPerChargeErr() const;
+
+  Bool_t IsFFactorMethodValid() const;
+
+  // Calculations
+  void   CalcLoGainPedestal(const Float_t logainsamples);
+  Bool_t CalcReducedSigma(const Float_t extractorres=0);
+  Bool_t CalcFFactor();
+  Bool_t CalcConvFFactor();
+  Bool_t CalcMeanFFactor(const Float_t nphotons, const Float_t nphotonsrelvar);
+  
+  ClassDef(MCalibrationChargePix, 4)	// Container Charge Calibration Results Pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoCam.cc	(revision 17960)
@@ -0,0 +1,271 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationHiLoCam                                               
+//                                                               
+// Storage container for ratio between higain and logain charge extraction
+// calibration results of the whole camera.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationHiLoPix &avpix = (MCalibrationHiLoPix&)(*fHiLoCam)[i]
+// 
+// The following "calibration" constants can be retrieved from each pixel:
+// - GetHiLoRatio(): The mean signal ratio between high-gain and low-gain
+// - GetHiLoRatioErr(): The Gauss sigma of histogrammed signal ratios
+//
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationHiLoPix &avpix = (MCalibrationHiLoPix&)fRelCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationHiLoPix &avpix = (MCalibrationHiLoPix&)fRelCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// See also: MHCalibrationHiLoPix, MHCalibrationHiLoCam              
+//                                                                         
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: HiLo Ratio
+// 1: Error of HiLo Ratio
+// 2: Sigma of HiLo Ratio == Resolution 
+// 3: Error of Sigma of HiLo Ratio
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationHiLoCam.h"
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationHiLoPix.h"
+
+ClassImp(MCalibrationHiLoCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationHiLoCam::MCalibrationHiLoCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationHiLoCam";
+  fTitle = title ? title : "Container for High Gain vs. Low Gain amplification ratio";
+  
+}
+
+void MCalibrationHiLoCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationHiLoPix,i);
+}
+
+
+void MCalibrationHiLoCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationHiLoPix,i);
+}
+
+void MCalibrationHiLoCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationHiLoPix,i);
+}
+
+void MCalibrationHiLoCam::PrintPix(const MCalibrationHiLoPix &pix, const char *type) const
+{
+    *fLog << all << setw(7) << type << Form("%4i", pix.GetPixId()) << ":   ";
+    *fLog << "   Ratio: " << Form("%4.2f", pix.GetHiLoChargeRatio());
+    *fLog << " +- " << Form("%4.2f", pix.GetHiLoChargeRatioErr());
+    *fLog << "   Sigma: " << Form("%4.2f", pix.GetHiLoChargeRatioSigma());
+    *fLog << " +- " << Form("%4.2f", pix.GetHiLoChargeRatioSigmaErr());
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not Valid
+//
+void MCalibrationHiLoCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << "Calibrated pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationHiLoPix *pix;
+  while ((pix=(MCalibrationHiLoPix*)Next()))
+      if (!pix->IsExcluded())
+      {
+          PrintPix(*pix, "Pixel");
+          id++;
+      }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationHiLoPix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+	  *fLog << all << pix->GetPixId() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationHiLoPix*)Next5()))
+      PrintPix(*pix, "Area");
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationHiLoPix*)Next5()))
+      PrintPix(*pix, "Sector");
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted HiLo
+// 1: Error of fitted HiLo
+// 2: Sigma of fitted HiLo
+// 3: Error of Sigma of fitted HiLo
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to HiLo distribution
+//
+Bool_t MCalibrationHiLoCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ MCalibrationHiLoPix &pix = (MCalibrationHiLoPix&)(*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatio();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioSigma();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioSigmaErr();
+      break;
+    case 4:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioProb();
+      break;
+    case 5:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiff();
+      break;
+    case 6:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffErr();
+      break;
+    case 7:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffSigma();
+      break;
+    case 8:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffSigmaErr();
+      break;
+    case 9:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffProb();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoCam.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MCalibrationHiLoCam
+#define MARS_MCalibrationHiLoCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationHiLoPix;
+
+class MCalibrationHiLoCam : public MCalibrationCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+
+  void PrintPix(const MCalibrationHiLoPix &pix, const char *type) const;
+
+public:
+
+  MCalibrationHiLoCam(const char *name=NULL, const char *title=NULL);
+
+  // Prints
+  void Print(Option_t *o="") const; //*MENU*
+
+  // Others
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  ClassDef(MCalibrationHiLoCam, 1)	// Container Rel. Arrival Time Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoPix.cc	(revision 17960)
@@ -0,0 +1,59 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalibrationHiLoPix
+//
+// Storage container for high-gain vs. low-gain charge calibration results
+// of one Pixel (PMT).
+// The following "calibration" constants can be retrieved:
+// - GetHiLoRatio(): The mean conversion High-gain vs. Low-gain
+//   with which the low-gain result has to be multiplied
+// - GetHiLoSigma(): The Gauss sigma of histogrammed High-gain vs.
+//   Low-gain ratios
+//
+// See also: MHCalibrationHiLoPix, MHCalibrationHiLoCam
+//
+// Class Version 2:
+//  + Float_t fOffsetPerSlice;  // Offset from fit (per FADC slice)
+//  + Float_t fGainRatio;       // Ratio of gains from fit
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationHiLoPix.h"
+
+ClassImp(MCalibrationHiLoPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MCalibrationHiLoPix::MCalibrationHiLoPix(const char *name, const char *title)
+  : fOffsetPerSlice(-9999.), fGainRatio(-1.)
+{
+
+  fName  = name  ? name  : "MCalibrationHiLoPix";
+  fTitle = title ? title : "Results of MHCalibrationHiLoPix ";
+
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationHiLoPix.h	(revision 17960)
@@ -0,0 +1,40 @@
+#ifndef MARS_MCalibrationHiLoPix
+#define MARS_MCalibrationHiLoPix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationHiLoPix : public MCalibrationPix
+{
+private:
+    Float_t fOffsetPerSlice;            // Offset from fit (per FADC slice)
+    Float_t fGainRatio;                 // Ratio of gains from fit
+
+public:
+  MCalibrationHiLoPix(const char *name=NULL, const char *title=NULL);
+
+  // Setter
+  void SetGainRatio     (const Float_t f) { fGainRatio      = f; }
+  void SetOffsetPerSlice(const Float_t f) { fOffsetPerSlice = f; }
+
+  // Getter
+  Float_t GetHiLoChargeRatio()         const { return GetHiGainMean();     }
+  Float_t GetHiLoChargeRatioErr()      const { return GetHiGainMeanErr();  }
+  Float_t GetHiLoChargeRatioSigma()    const { return GetHiGainSigma();    }
+  Float_t GetHiLoChargeRatioSigmaErr() const { return GetHiGainSigmaErr(); }
+  Float_t GetHiLoChargeRatioProb()     const { return GetHiGainProb();     }
+									   
+  Float_t GetHiLoTimeDiff()            const { return GetLoGainMean();     }
+  Float_t GetHiLoTimeDiffErr()         const { return GetLoGainMeanErr();  }
+  Float_t GetHiLoTimeDiffSigma()       const { return GetLoGainSigma();    }
+  Float_t GetHiLoTimeDiffSigmaErr()    const { return GetLoGainSigmaErr(); }
+  Float_t GetHiLoTimeDiffProb()        const { return GetLoGainProb();     }
+  Float_t GetGainRatio     ()          const { return fGainRatio;          }
+//  Float_t GetOffsetPerSlice()          const { return fOffsetPerSlice;     }
+
+  ClassDef(MCalibrationHiLoPix, 2)	// Container HiLo conversion Calibration Results Pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityCam.cc	(revision 17960)
@@ -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): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityCam                                               
+//                                                               
+// Base class for intensity calibration results 
+//
+// Contains TOrdCollections for the following objects:
+// - fCams:  Array of classes derived from MCalibrationCam, one entry 
+//           per calibration camera result.
+// - fHists: Array of classes derived from MHCalibrationPix, one entry
+//           per calibration camera result and area index
+//
+// See also: MCalibrationIntensityChargeCam, 
+//           MCalibrationCam, MCalibrationPix, MHCalibrationChargePix,
+//           MHCalibrationChargeCam, MCalibrationChargeBlindPix,
+//           MCalibrationChargePINDiode
+//
+// Inline Functions:
+// -----------------
+//
+// GetSize(): Returns the current size of the TOrdCollection fCams
+//  independently if the MCalibrationCam is filled with values or not.
+//
+// GetAverageAreas(): Returns the current size of the TOrdCollection
+//  fAverageAreas of the current camera.
+//
+// GetAverageArea(UInt_t i): Get i-th High Gain pixel Area from the
+//  current camera
+//
+// GetAverageArea(UInt_t i): Get i-th High Gain pixel Area from the
+//  current camera
+//
+// GetAverageBadArea(UInt_t i): Get i-th High Gain pixel Area from the
+//  current camera
+//
+// GetAverageBadArea(UInt_t i): Get i-th High Gain pixel Area from the
+//  current camera
+//
+// GetAverageSectors(): Returns the current size of the TOrdCollection
+//  fAverageSectors or the current camera
+//
+// GetAverageSector(UInt_t i): Get i-th High Gain Sector from the
+//  current camera
+//
+// GetAverageSector(UInt_t i): Get i-th High Gain Sector from the current
+//  camera
+//
+// GetAverageBadSector(UInt_t i): Get i-th High Gain Sector from the
+//  current camera
+//
+// GetAverageBadSector(UInt_t i): Get i-th High Gain Sector from the
+//  current camera
+//
+//
+// ClassVersion 2:
+//  + fHists
+//
+// ClassVersion 3:
+//  - MArrayD fOffsets;           //! Arrays of Higain-vs-LoGain fit result Offsets
+//  - MArrayD fSlopes;            //! Arrays of Higain-vs-LoGain fit result Slopes
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MHCalibrationCam.h"
+
+ClassImp(MCalibrationIntensityCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set the following pointer to NULL:
+// - fCams
+// - fHists
+//
+MCalibrationIntensityCam::MCalibrationIntensityCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityCam";
+  fTitle = title ? title : "Base container for the Intensity Calibration";
+
+  fCams = new TOrdCollection;
+  fCams->SetOwner();
+
+  fHists = new TOrdCollection;
+  fHists->SetOwner();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histograms if they exist
+//
+MCalibrationIntensityCam::~MCalibrationIntensityCam()
+{
+    delete fCams;
+    delete fHists;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new MHCalibrationCam to fHists
+//
+void MCalibrationIntensityCam::AddHist( const MHCalibrationCam *cam)
+{
+    const Int_t size = fHists->GetSize();
+    fHists->AddAt((TObject*)cam,size);
+
+    if (size != GetSize()-1)
+        *fLog << warn << "Histogram Cams and Calibration Cams size mismatch! " << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new MCalibrationCam to fCams, give it the name "name" and initialize
+// it with geom.
+//
+void MCalibrationIntensityCam::AddToList( const char* name, const MGeomCam &geom) 
+{
+  InitSize(GetSize()+1);
+  GetCam()->SetName(name);
+  GetCam()->Init(geom);
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibrationIntensityCam::Copy(TObject& object) const
+{
+    MCalibrationIntensityCam &calib = (MCalibrationIntensityCam&)object;
+
+    MParContainer::Copy(calib);
+
+    const UInt_t n = GetSize();
+    if (n != 0)
+    {
+        calib.InitSize(n);
+        for (UInt_t i=0; i<n; i++)
+        {
+            GetCam(i)->Copy(*(calib.GetCam(i)));
+            GetHist(i)->Copy(*(calib.GetHist(i)));
+        }
+    }
+}
+
+// -----------------------------------------------------
+//
+// Calls Clear() for all entries fCams
+//
+void MCalibrationIntensityCam::Clear(Option_t *o)
+{
+    fCams->R__FOR_EACH(MCalibrationCam, Clear)();
+    fHists->R__FOR_EACH(MHCalibrationCam, Clear)();
+}
+
+// -----------------------------------------------------
+//
+// Calls Print(o) for all entries fCams
+//
+void MCalibrationIntensityCam::Print(Option_t *o) const
+{
+    fCams->R__FOR_EACH(MCalibrationCam, Print)(o);
+    fHists->R__FOR_EACH(MHCalibrationCam, Print)(o);
+}
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollection using the 
+// virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationIntensityCam::InitSize(const UInt_t i)
+{
+
+  const UInt_t save = GetSize();
+
+  if (i==save)
+    return;
+  
+  if (i>save)
+    Add(save,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationCams in the ranges from - to. In order to initialize
+// from MCalibrationCam derived containers, overwrite this function
+//
+void MCalibrationIntensityCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationCam,i);
+}
+
+// -------------------------------------------------------------------
+//
+// If size is still 0, Intialize a first Cam.
+// Calls Init(geom) for all fCams
+//
+void MCalibrationIntensityCam::Init(const MGeomCam &geom)
+{
+  if (GetSize() == 0)
+    InitSize(1);
+
+  fCams->R__FOR_EACH(MCalibrationCam,Init)(geom);
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MCalibrationIntensityCam::CountNumEntries(const MCalibrationCam::PulserColor_t col) const
+{
+  
+  Int_t size = 0;
+
+  if (col == MCalibrationCam::kNONE)
+    return GetSize();
+  else
+    for (Int_t i=0;i<GetSize();i++)
+      {
+        const MCalibrationCam *cam = GetCam(i);
+        if (cam->GetPulserColor() == col)
+          size++;
+      }
+
+  return size;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+MCalibrationPix &MCalibrationIntensityCam::operator[](UInt_t i)
+{
+  return (*GetCam())[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+const MCalibrationPix &MCalibrationIntensityCam::operator[](UInt_t i) const 
+{
+  return (*GetCam())[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+/*
+MCalibrationCam *MCalibrationIntensityCam::GetCam(const char *name)
+{
+  return static_cast<MCalibrationCam*>(fCams->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+const MCalibrationCam *MCalibrationIntensityCam::GetCam(const char *name) const
+{
+  return static_cast<MCalibrationCam*>(fCams->FindObject(name));
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Get i-th histogram class 
+//
+MHCalibrationCam *MCalibrationIntensityCam::GetHist(Int_t i)
+{
+  return static_cast<MHCalibrationCam*>(i==-1 ? fHists->Last() : fHists->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th histogram class 
+//
+const MHCalibrationCam *MCalibrationIntensityCam::GetHist(Int_t i) const 
+{
+  return static_cast<MHCalibrationCam*>(i==-1 ? fHists->Last() : fHists->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get histogram class with name 'name' 
+//
+MHCalibrationCam *MCalibrationIntensityCam::GetHist(const char *name )
+{
+    return static_cast<MHCalibrationCam*>(fHists->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get histogram class with name 'name' 
+//
+const MHCalibrationCam *MCalibrationIntensityCam::GetHist(const char *name ) const 
+{
+  return static_cast<MHCalibrationCam*>(fHists->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls DrawPixelContent for the current entry in fCams
+//
+void MCalibrationIntensityCam::DrawPixelContent( Int_t num ) const
+{
+  return GetCam()->DrawPixelContent(num);
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityCam.h	(revision 17960)
@@ -0,0 +1,111 @@
+#ifndef MARS_MCalibrationIntensityCam
+#define MARS_MCalibrationIntensityCam
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+class MCalibrationPix;
+class MBadPixelsPix;
+class MGeomCam;
+class MHCalibrationCam;
+
+class MCalibrationIntensityCam : public MParContainer, public MCamEvent
+{
+protected:  
+  TOrdCollection *fCams;   // Array of MCalibrationCams, one per pulse colour and intensity
+  TOrdCollection *fHists;  // Array of MHCalibrationCam's, containing the mean charges per area histograms
+
+  virtual void Add(const UInt_t from, const UInt_t to);
+  virtual void InitSize( const UInt_t n );
+  
+public:
+  MCalibrationIntensityCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationIntensityCam();
+  
+  void  Clear ( Option_t *o="" );
+  void  Copy(TObject& object) const;  
+  
+  void AddToList(const char* name, const MGeomCam &geom);
+  void AddHist(const MHCalibrationCam *cam);
+
+  Int_t CountNumEntries(const MCalibrationCam::PulserColor_t col) const;
+
+  const Int_t GetSize() const  { return fCams->GetSize();  }
+
+  const Int_t            GetAverageAreas     ()            const   { return GetCam()->GetAverageAreas(); }
+        MCalibrationPix &GetAverageArea      ( UInt_t i )          { return GetCam()->GetAverageArea(i);  }
+  const MCalibrationPix &GetAverageArea      ( UInt_t i )  const   { return GetCam()->GetAverageArea(i);  }
+        MBadPixelsPix   &GetAverageBadArea   ( UInt_t i )          { return GetCam()->GetAverageBadArea(i); }  
+  const MBadPixelsPix   &GetAverageBadArea   ( UInt_t i )  const   { return GetCam()->GetAverageBadArea(i); }
+  const Int_t            GetAverageSectors   ()            const   { return GetCam()->GetAverageSectors();  }
+        MCalibrationPix &GetAverageSector    ( UInt_t i )          { return GetCam()->GetAverageSector(i);  }
+  const MCalibrationPix &GetAverageSector    ( UInt_t i )  const   { return GetCam()->GetAverageSector(i);  }
+        MBadPixelsPix   &GetAverageBadSector ( UInt_t i )          { return GetCam()->GetAverageBadSector(i); }
+  const MBadPixelsPix   &GetAverageBadSector ( UInt_t i )  const   { return GetCam()->GetAverageBadSector(i); }
+
+  MCalibrationCam *GetCam              ( Int_t i/*=-1*/)       {
+      return static_cast<MCalibrationCam*>(i==-1 ? fCams->Last() : fCams->At(i)); }
+  const MCalibrationCam *GetCam              ( Int_t i/*=-1*/) const {
+      return static_cast<MCalibrationCam*>(i==-1 ? fCams->Last() : fCams->At(i)); }
+
+  MCalibrationCam *GetCam() { return static_cast<MCalibrationCam*>(fCams->Last()); }
+  const MCalibrationCam *GetCam() const { return static_cast<MCalibrationCam*>(fCams->Last()); }
+
+//        MCalibrationCam *GetCam              ( const char *name );
+//  const MCalibrationCam *GetCam              ( const char *name ) const;
+
+  // The "DeleteOldCam" function must not delete the first entry in
+  // the array because it is a special cam from the MParList. (see above)
+  void DeleteOldCam(MCalibrationCam *cam) { /* if (fCams->IndexOf(cam)>0) delete fCams->Remove(cam);*/ }
+
+        MHCalibrationCam *GetHist            ( Int_t i=-1);      
+  const MHCalibrationCam *GetHist            ( Int_t i=-1) const;
+
+        MHCalibrationCam *GetHist            ( const char *name );      
+  const MHCalibrationCam *GetHist            ( const char *name ) const;
+
+        MCalibrationPix &operator[]          ( UInt_t i );
+  const MCalibrationPix &operator[]          ( UInt_t i )  const;
+ 
+  const Float_t GetNumHiGainFADCSlices ( const Int_t aidx=0 ) const { return GetCam()->GetNumHiGainFADCSlices(aidx); }
+  const Float_t GetNumLoGainFADCSlices ( const Int_t aidx=0 ) const { return GetCam()->GetNumLoGainFADCSlices(aidx); }
+  const Int_t   GetNumUnsuitable       ( const Int_t aidx=-1) const { return GetCam()->GetNumUnsuitable(aidx);       }
+  const Int_t   GetNumUnreliable       ( const Int_t aidx=-1) const { return GetCam()->GetNumUnreliable(aidx);       }
+  
+  // Inits
+  void  Init   ( const MGeomCam &geom );
+  
+   // Prints
+  void   Print(Option_t *o="")         const;
+
+  // Setters
+  void  SetNumHiGainFADCSlices( const Float_t f, const Int_t aidx=0) { GetCam()->SetNumHiGainFADCSlices(f,aidx); }
+  void  SetNumLoGainFADCSlices( const Float_t f, const Int_t aidx=0) { GetCam()->SetNumLoGainFADCSlices(f,aidx); }
+  void  SetNumUnsuitable      ( const UInt_t i,  const Int_t aidx  ) { GetCam()->SetNumUnsuitable(i,aidx);       }
+  void  SetNumUnreliable      ( const UInt_t i,  const Int_t aidx  ) { GetCam()->SetNumUnreliable(i,aidx);       }
+  void  SetPulserColor        ( const MCalibrationCam::PulserColor_t col=MCalibrationCam::kCT1) {
+                                                                       GetCam()->SetPulserColor(col);            }
+  void  SetCam( MCalibrationCam *cam, const Int_t i)                 {  fCams->PutAt(cam,i);  }
+  
+  // MCamEvent
+  Bool_t GetPixelContent( Double_t &val, Int_t idx, const MGeomCam &cam,Int_t type=0) const 
+	{ return GetCam()->GetPixelContent(val,idx,cam,type);  }
+  void DrawPixelContent( Int_t num) const;
+
+  ClassDef(MCalibrationIntensityCam, 3) // Base Container Intensity Calibration Results
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityChargeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityChargeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityChargeCam.cc	(revision 17960)
@@ -0,0 +1,1195 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityChargeCam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationChargeCam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibrationChargeCam,
+//           MCalibrationChargePix, MCalibrationChargeCalc, MCalibrationQECam
+//           MCalibrationBlindCam, MCalibrationChargePINDiode
+//           MHCalibrationChargePix, MHCalibrationChargeCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityChargeCam.h"
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TGraphErrors.h>
+#include <TOrdCollection.h>
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCamMagic.h"
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+ClassImp(MCalibrationIntensityChargeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityChargeCam::MCalibrationIntensityChargeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityChargeCam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+  
+  InitSize(1);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargeCam's in the ranges from - to. 
+//
+void MCalibrationIntensityChargeCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationChargeCam,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the number of photo-electrons vs. 
+// the extracted signal of pixel "pixid". 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phe(size);
+  TArrayF pheerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      phe[cnt]    = pix.GetPheFFactorMethod();
+      pheerr[cnt] = pix.GetPheFFactorMethodErr();
+      //
+      // For the calculation of Q, we have to use the 
+      // converted value!
+      //
+      sig   [cnt] = pix.GetConvertedMean();
+      sigerr[cnt] = pix.GetConvertedMeanErr();
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     sig.GetArray(),phe.GetArray(),
+                                     sigerr.GetArray(),pheerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("Q [FADC counts]");
+  gr->GetYaxis()->SetTitle("photo-electrons [1]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photo-electrons divided by 
+// the mean charge of that pixel vs. the mean number of photo-electrons.
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhePerCharge( const UInt_t pixid, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumValidEntries(pixid,col);
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phepersig(size);
+  TArrayF phepersigerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      // For the calculation of Q, we have to use the 
+      // converted value!
+      //
+      const Int_t aidx = geom[pixid].GetAidx();
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+
+      const Float_t q    = pix.GetConvertedMean();
+      const Float_t qerr = pix.GetConvertedMeanErr();
+      //
+      const Float_t phe    = apix.GetPheFFactorMethod();
+      const Float_t pheerr = apix.GetPheFFactorMethodErr();
+
+      sig[cnt]       = phe;
+      sigerr[cnt]    = pheerr;
+
+
+      phepersig[cnt] = q > 0.00001 ? phe/q : -1.;
+
+      Float_t var = 0.;
+
+      if (q > 0.00001 && phe > 0.00001)
+        {
+          var = pheerr * pheerr / phe / phe + qerr*qerr/q/q;
+          if (var > 0.00001)
+            var = TMath::Sqrt(var)*phepersig[cnt];
+        }
+      phepersigerr[cnt] = var;
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     sig.GetArray(),phepersig.GetArray(),
+                                     sigerr.GetArray(),phepersigerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("<photo-electrons> [1]");
+  gr->GetYaxis()->SetTitle("<phes> / <Q> [FADC cts^{-1}]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photo-electrons divided by 
+// the mean charge of that pixel vs. the mean number of photo-electrons.
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhePerChargePerArea( const Int_t aidx, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phepersig(size);
+  TArrayF phepersigerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t phe          = apix.GetPheFFactorMethod();
+      const Float_t pherelvar    = apix.GetPheFFactorMethodRelVar();
+      const Float_t pheerr       = apix.GetPheFFactorMethodErr();
+
+      sig[cnt]       = phe;
+      sigerr[cnt]    = pheerr;
+
+      Double_t sig1 = 0.;
+      Double_t sig2 = 0.;
+      Int_t    num  = 0;
+
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+          
+          sig1 += pix.GetConvertedMean();
+          sig2 += pix.GetConvertedMean() * pix.GetConvertedMean();
+          num++;
+        }
+      
+      if (num > 1)
+        {
+          sig1 /= num;
+
+          Double_t var = (sig2 - sig1*sig1*num) / (num-1);
+          var /= sig1*sig1;
+          var += pherelvar;
+
+          phepersig[cnt] = phe/sig1;
+          if (var > 0.)
+            phepersigerr[cnt] = TMath::Sqrt(var) * phepersig[cnt];
+          else
+            phepersigerr[cnt] = 0.;
+        }
+      else
+        {
+          phepersig[cnt]    = -1.;
+          phepersigerr[cnt] = 0.;
+        }
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     sig.GetArray(),phepersig.GetArray(),
+                                     sigerr.GetArray(),phepersigerr.GetArray());
+  gr->SetTitle(Form("Conv. Factors Area %d Average",aidx));
+  gr->GetXaxis()->SetTitle("<photo-electrons> [1]");
+  gr->GetYaxis()->SetTitle("<phes> / <Q> [FADC cts^{-1}]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the number of photo-electrons vs. 
+// the extracted signal over all pixels with area index "aidx". 
+//
+// The points represent the means of the pixels values, while the error bars
+// the sigma of the pixels values.  
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  TArrayF phe(size);
+  TArrayF pheerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(cam->GetAverageArea(aidx));
+
+      phe[cnt]    = pix.GetPheFFactorMethod();
+      pheerr[cnt] = pix.GetPheFFactorMethodErr();
+      //
+      // For the calculation of Q, we have to use the 
+      // converted value!
+      //
+      sig   [cnt] = pix.GetConvertedMean();
+      sigerr[cnt] = pix.GetConvertedMeanErr();
+
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                      sig.GetArray(),phe.GetArray(),
+                                      sigerr.GetArray(),pheerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Area Index ",aidx));
+  gr->GetXaxis()->SetTitle("Q [FADC counts]");
+  gr->GetYaxis()->SetTitle("photo-electrons [1]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the 'Razmik plot' of pixel "pixid". 
+// The Razmik plot shows the value of 'R' vs. 1/Q where:
+//
+//        sigma^2         F^2
+//  R =   -------    =  ------
+//         <Q>^2        <m_pe>
+//
+// and 1/Q is the inverse (mean) extracted signal
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetRazmikPlot( const UInt_t pixid )
+{
+  
+  const Int_t size = GetSize();
+  
+  TArrayF r(size);
+  TArrayF rerr(size);
+  TArrayF oneoverq(size);
+  TArrayF oneoverqerr(size);
+  
+  for (Int_t i=0;i<size;i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      // For the calculation of R, use the un-converted values, like 
+      // in the calibration, since: 
+      //                 C^2*sigma^2     sigma^2
+      //  R(lowgain) =   -----------  =  ------  = R
+      //                 C^2*<Q>^2       <Q>^2
+      //
+      const Float_t mean = pix.GetMean();
+      const Float_t meanerr = pix.GetMeanErr();
+      const Float_t rsigma = pix.GetRSigma();
+      const Float_t rsigmaerr = pix.GetRSigmaErr();
+      r[i]    = rsigma*rsigma/mean/mean;
+      const Float_t rrelvar = 4.*rsigmaerr*rsigmaerr/rsigma/rsigma + 4.*meanerr*meanerr/mean/mean;
+      rerr[i] = rrelvar * r[i] * r[i];
+      rerr[i] = rerr[i] <= 0 ? 0. : TMath::Sqrt(rerr[i]);
+      //
+      // For the calculation of 1/Q, we have to use the 
+      // converted value!
+      //
+      const Float_t q  = pix.GetConvertedMean();
+      const Float_t qe = pix.GetConvertedMeanErr();
+      oneoverq   [i] = 1./q;
+      oneoverqerr[i] = qe / (q * q);
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     oneoverq.GetArray(),r.GetArray(),
+                                     oneoverqerr.GetArray(),rerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("1/Q [FADC counts^{-1}]");
+  gr->GetYaxis()->SetTitle("\\sigma_{red}^{2}/Q^{2} [1]");
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a 2-dimensional histogram with the fit results of the 
+// 'Razmik plot' for each pixel of area index "aidx" (see GetRazmikPlot())
+// 
+// The results of the polynomial fit of grade 1 are: 
+//
+// x-axis: Offset (Parameter 0 of the polynomial)
+// y-axis: Slope  (Parameter 1 of the polynomial)
+//
+// The offset is a measure of how well-known the supposed additional contributions 
+// to the value "reduced sigma" are. Because a photo-multiplier is a linear instrument, 
+// the excess fluctuations are linear w.r.t. the signal amplitude and can be expressed by 
+// the proportionality constant F (the "F-Factor"). 
+// Adding noise from outside (e.g. night sky background) modifies the recorded noise, but 
+// not the mean extracted signal, due to the AC-coupling. Thus, noise contributions from outside
+// (e.g. calculating the pedestal RMS)have to be subtracted from the recorded signal fluctuations 
+// in order to retrieve the linearity relation: 
+//
+// sigma(signal)^2 / mean(signal)^2  = sigma^2 / <Q>^2 = F^2 / <n_phe>               (1) 
+//
+// Any systematic offset in the sigma(signal) will produce an offset in the "Razmik plot"), 
+// characterized by the Offset of the polynomial fit. Thus, in an ideal case, all pixels have their
+// "offset" centered very closely around zero.
+//
+// The "slope" is the proportionality constant F^2, multiplied with the conversion factor 
+// phe's to mean signal (because the "Razmik plot" plots the left side of eq. (1) w.r.t. 
+// 1/<Q> instead of 1/<n_phe>. However, the mean number of photo-electrons <n_phe> can be 
+// expressed by <Q> with the relation:
+//
+//  <n_phe> = c_phe * <Q>                                                            (2)
+//
+// Thus: 
+//
+// 1/<n_phe> = 1/c_phe * 1/<Q>                                                       (3) 
+// 
+// and:
+//
+// Slope = F^2 / c_phe
+//
+// In the ideal case of having equal photo-multipliers and a perfectly flat-fielded camera,
+// the "slope" -values should thus all be closely centered around F^2/c_phe. 
+// 
+TH2F *MCalibrationIntensityChargeCam::GetRazmikPlotResults( const Int_t aidx, const MGeomCam &geom)
+{
+  
+  TH2F *hist = new TH2F("hist","R vs. Inverse Charges - Fit results",45,-0.02,0.02,45,0.,30.);
+  hist->SetXTitle("Offset [FADC counts^{-1}]");
+  hist->SetYTitle("F^{2} / <n_phe>/<Q> [FADC count / phe]");  
+  hist->SetFillColor(kRed+aidx);
+
+  MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam();
+
+  for (Int_t npix=0;npix<cam->GetSize();npix++)
+    {
+
+      if (geom[npix].GetAidx() == aidx)
+        {
+          TGraph *gr = GetRazmikPlot(npix);
+          gr->Fit("pol1","Q");
+          hist->Fill(gr->GetFunction("pol1")->GetParameter(0),gr->GetFunction("pol1")->GetParameter(1));
+        }
+    }
+  return hist;
+}
+
+
+// --------------------------------------------------------------------
+//
+// Returns the number of camera entries matching the required colour 
+// and the requirement that pixel "pixid" has been correctly calibrated
+//
+Int_t MCalibrationIntensityChargeCam::CountNumValidEntries(const UInt_t pixid, const MCalibrationCam::PulserColor_t col) const
+{
+
+  Int_t nvalid = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      const MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+
+      if (col == MCalibrationCam::kNONE)
+        {
+          if (pix.IsFFactorMethodValid())
+            nvalid++;
+        }
+      else
+        {
+          if (cam->GetPulserColor() == col)
+            {
+              if (pix.IsFFactorMethodValid())
+                nvalid++;
+            }
+        }
+    }
+  
+  return nvalid;
+}
+
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the development of the number of 
+// photo-electrons vs. camera number for pixel 'pixid' 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetVarVsTime( const Int_t pixid , const Option_t *varname )
+{
+  
+  const Int_t size = GetSize();
+
+  if (size == 0)
+    return NULL;
+  
+  TString option(varname);
+  option.ToLower();
+
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  TArrayF var   (size);
+  TArrayF varerr(size);
+  
+  for (Int_t i=0;i<size;i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      nr[i]    = i;
+      nrerr[i] = 0.;
+      var[i]    = -1.;
+      varerr[i] = -1.;
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      if (option.Contains("rsigma"))
+        {
+          var   [i] = pix.GetRSigma();
+          varerr[i] = pix.GetRSigmaErr();
+        }
+      if (option.Contains("abstimemean"))
+        {
+          var   [i] = pix.GetAbsTimeMean();
+          varerr[i] = pix.GetAbsTimeRms();
+        }
+      if (option.Contains("abstimerms"))
+        {
+          var   [i] = pix.GetAbsTimeRms();
+          varerr[i] = pix.GetAbsTimeRms()/2.;
+        }
+      if (option.Contains("blackout"))
+        {
+          var   [i] = pix.GetNumBlackout();
+          varerr[i] = 0.;
+        }
+      if (option.Contains("pickup"))
+        {
+          var   [i] = pix.GetNumPickup();
+          varerr[i] = 0.;
+        }
+      if (option.Contains("outlier"))
+        {
+          var   [i] = pix.GetNumPickup() + pix.GetNumBlackout();
+          varerr[i] = 0.;
+        }
+      if (option.Contains("conversionhilo"))
+        {
+          var   [i] = pix.GetConversionHiLo();
+          varerr[i] = pix.GetConversionHiLoErr();
+        }
+      if (option.Contains("convertedmean"))
+        {
+          var   [i] = pix.GetConvertedMean();
+          varerr[i] = pix.GetConvertedMeanErr();
+        }
+      if (option.Contains("convertedsigma"))
+        {
+          var   [i] = pix.GetConvertedSigma();
+          varerr[i] = pix.GetConvertedSigmaErr();
+        }
+      if (option.Contains("convertedrsigma"))
+        {
+          var   [i] = pix.GetConvertedRSigma();
+          varerr[i] = pix.GetConvertedRSigmaErr();
+        }
+      if (option.Contains("meanconvfadc2phe"))
+        {
+          var   [i] = pix.GetMeanConvFADC2Phe();
+          varerr[i] = pix.GetMeanConvFADC2PheErr();
+        }
+      if (option.Contains("meanffactorfadc2phot"))
+        {
+          var   [i] = pix.GetMeanFFactorFADC2Phot();
+          varerr[i] = pix.GetMeanFFactorFADC2PhotErr();
+        }
+      if (option.Contains("ped"))
+        {
+          var   [i] = pix.GetPed();
+          varerr[i] = pix.GetPedErr();
+        }
+      if (option.Contains("pedrms"))
+        {
+          var   [i] = pix.GetPedRms();
+          varerr[i] = pix.GetPedRmsErr();
+        }
+      if (option.Contains("pheffactormethod"))
+        {
+          var   [i] = pix.GetPheFFactorMethod();
+          varerr[i] = pix.GetPheFFactorMethodErr();
+        }
+      if (option.Contains("rsigmapercharge"))
+        {
+          var   [i] = pix.GetRSigmaPerCharge();
+          varerr[i] = pix.GetRSigmaPerChargeErr();
+        }
+      if (option.Contains("conversionfactor"))
+        {
+          const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(0);
+          const Float_t mean = pix.GetConvertedMean();
+          const Float_t phe  = apix.GetPheFFactorMethod();
+
+          var[i]    = phe/mean;
+          varerr[i] = TMath::Sqrt(apix.GetPheFFactorMethodErr()*apix.GetPheFFactorMethodErr()/mean/mean
+                                  + phe*phe/mean/mean/mean/mean*pix.GetConvertedMeanErr()*pix.GetConvertedMeanErr());
+        }
+  }
+  
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),var.GetArray(),
+                                     nrerr.GetArray(),varerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  //  gr->GetYaxis()->SetTitle("<Q> [FADC cnts]");
+  return gr;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns a TGraphErrors with a pre-defined variable with name (handed over in 'opt')
+// per area index 'aidx' vs. the calibration camera number 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetVarPerAreaVsTime( const Int_t aidx, const MGeomCam &geom, const Option_t *varname)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+
+  TString option(varname);
+  option.ToLower();
+
+  TArrayF vararea(size);
+  TArrayF varareaerr(size);
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  
+  TH1D *h = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      Double_t variab   = 0.;
+      Double_t variab2  = 0.;
+      Double_t variance = 0.;
+      Int_t    num      = 0;
+      Float_t  pvar     = 0.;
+
+      MHCamera camcharge(geom,"CamCharge","Variable;;channels");
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+
+          pvar = 0.;
+          
+          if (option.Contains("rsigma"))
+              pvar = pix.GetRSigma();
+          if (option.Contains("abstimemean"))
+              pvar = pix.GetAbsTimeMean();
+          if (option.Contains("abstimerms"))
+              pvar = pix.GetAbsTimeRms();
+          if (option.Contains("conversionhilo"))
+              pvar = pix.GetConversionHiLo();
+          if (option.Contains("convertedmean"))
+              pvar = pix.GetConvertedMean();
+          if (option.Contains("convertedsigma"))
+              pvar = pix.GetConvertedSigma();
+          if (option.Contains("convertedrsigma"))
+              pvar = pix.GetConvertedRSigma();
+          if (option.Contains("meanconvfadc2phe"))
+              pvar = pix.GetMeanConvFADC2Phe();
+          if (option.Contains("meanffactorfadc2phot"))
+              pvar = pix.GetMeanFFactorFADC2Phot();
+          if (option.Contains("ped"))
+              pvar = pix.GetPed();
+          if (option.Contains("pedrms"))
+              pvar = pix.GetPedRms();
+          if (option.Contains("pheffactormethod"))
+              pvar = pix.GetPheFFactorMethod();
+          if (option.Contains("rsigmapercharge"))
+              pvar = pix.GetRSigmaPerCharge();
+          if (option.Contains("conversionfactor"))
+          {
+              const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+              pvar = apix.GetPheFFactorMethod()/pix.GetConvertedMean();
+          }
+
+
+          variab  += pvar;
+          variab2 += pvar*pvar;
+          num++;
+          
+          camcharge.Fill(j,pvar);
+          camcharge.SetUsed(j);
+        }
+      
+      if (num > 1)
+        {
+          variab  /= num;
+          variance = (variab2 - variab*variab*num) / (num-1);
+
+          vararea[i]    = variab;
+          varareaerr[i] = variance>0 ? TMath::Sqrt(variance/num) : 999999999.;
+
+          //
+          // Make also a Gauss-fit to the distributions. The RMS can be determined by 
+          // outlier, thus we look at the sigma and the RMS and take the smaller one, afterwards.
+          // 
+          h = camcharge.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+          h->SetDirectory(NULL);
+          h->Fit("gaus","QL");
+          TF1 *fit = h->GetFunction("gaus");
+
+          Float_t ci2   = fit->GetChisquare();
+          Float_t sigma = fit->GetParameter(2);
+
+          if (ci2 > 500. || sigma > varareaerr[i])
+            {
+              h->Fit("gaus","QLM");
+              fit = h->GetFunction("gaus");
+
+              ci2   = fit->GetChisquare();
+              sigma = fit->GetParameter(2);
+            }
+          
+          const Float_t mean  = fit->GetParameter(1);
+          const Float_t ndf   = fit->GetNDF();
+          
+          *fLog << inf << "Camera Nr: " << i << endl;
+          *fLog << inf << option.Data() << " area idx: " << aidx << " Results: " << endl;
+          *fLog << inf << "Mean: " << Form("%4.3f",mean) 
+                << "+-" << Form("%4.3f",fit->GetParError(1))
+                << "  Sigma: " << Form("%4.3f",sigma) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+                << "  Chisquare: " << Form("%4.3f",ci2) << "  NDF  : " << ndf << endl;
+          delete h;
+          gROOT->GetListOfFunctions()->Remove(fit);
+
+          if (sigma<varareaerr[i] && ndf>2 && ci2<500.)
+            {
+              vararea   [i] = mean;
+              varareaerr[i] = sigma/TMath::Sqrt((Float_t)num);
+            }
+        }
+      else
+        {
+          vararea[i]    = -1.;
+          varareaerr[i] = 0.;
+        }
+
+      nr[i] = i;
+      nrerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),vararea.GetArray(),
+                                     nrerr.GetArray(),varareaerr.GetArray());
+  gr->SetTitle(Form("%s Area %3i Average",option.Data(),aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  //  gr->GetYaxis()->SetTitle("<Q> [1]");      
+  return gr;
+}
+
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photon
+// vs. the calibration camera number. With the string 'method', different
+// calibration methods can be called.
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhotVsTime( const Option_t *method )
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+
+  TString option(method);
+
+  TArrayF photarr(size);
+  TArrayF photarrerr(size);
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      Float_t phot    = 0.;
+      Float_t photerr = 0.;
+
+      if (option.Contains("BlindPixel"))
+        {
+          phot    = cam->GetNumPhotonsBlindPixelMethod();
+          photerr = cam->GetNumPhotonsBlindPixelMethodErr();
+        }
+      if (option.Contains("FFactor"))
+        {
+          phot    = cam->GetNumPhotonsFFactorMethod();
+          photerr = cam->GetNumPhotonsFFactorMethodErr();
+        }
+      if (option.Contains("PINDiode"))
+        {
+          phot    = cam->GetNumPhotonsPINDiodeMethod();
+          photerr = cam->GetNumPhotonsPINDiodeMethodErr();
+        }
+
+      photarr[i]       = phot;
+      photarrerr[i]    = photerr;
+
+      nr[i] = i;
+      nrerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),photarr.GetArray(),
+                                     nrerr.GetArray(),photarrerr.GetArray());
+  gr->SetTitle("Photons Average");
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_{phot}> [1]");
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photo-electrons per 
+// area index 'aidx' vs. the calibration camera number 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhePerAreaVsTime( const Int_t aidx, const MGeomCam &geom)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phearea(size);
+  TArrayF pheareaerr(size);
+  TArrayF time(size);
+  TArrayF timeerr(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t phe          = apix.GetPheFFactorMethod();
+      const Float_t pheerr       = apix.GetPheFFactorMethodErr();
+
+      phearea[i]       = phe;
+      pheareaerr[i]    = pheerr;
+
+      time[i] = i;
+      timeerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     time.GetArray(),phearea.GetArray(),
+                                     timeerr.GetArray(),pheareaerr.GetArray());
+  gr->SetTitle(Form("Phes Area %d Average",aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_{phe}> [1]");
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the event-by-event averaged charge per 
+// area index 'aidx' vs. the calibration camera number 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetChargePerAreaVsTime( const Int_t aidx, const MGeomCam &geom)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF chargearea(size);
+  TArrayF chargeareaerr(size);
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t charge          = apix.GetConvertedMean();
+      const Float_t chargeerr       = apix.GetConvertedSigma();
+
+      chargearea[i]       = charge;
+      chargeareaerr[i]    = chargeerr;
+
+      nr[i]    = i;
+      nrerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),chargearea.GetArray(),
+                                     nrerr.GetArray(),chargeareaerr.GetArray());
+  gr->SetTitle(Form("Averaged Charges Area Idx %d",aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<Q> [FADC cnts]");      
+  return gr;
+}
+
+TH1F *MCalibrationIntensityChargeCam::GetVarFluctuations( const Int_t aidx, const MGeomCam &geom, const Option_t *varname )
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TString option(varname);
+  option.ToLower();
+  
+  TH1F *hist = new TH1F("hist",Form("%s - Rel. Fluctuations %s Pixel",option.Data(),aidx ? "Outer" : "Inner"),
+                        200,0.,100.);
+  hist->SetXTitle("Relative Fluctuation [%]");
+  hist->SetYTitle("Nr. channels [1]");  
+  hist->SetFillColor(kRed+aidx);
+
+  MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam();
+
+  //
+  // Loop over pixels
+  //
+  for (Int_t npix=0;npix<cam->GetSize();npix++)
+    {
+      if (geom[npix].GetAidx() != aidx)
+        continue;
+
+      Double_t variab   = 0.;
+      Double_t variab2  = 0.;
+      Double_t variance = 0.;
+      Int_t    num      = 0;
+      Float_t  pvar     = 0.;
+      Float_t  relrms   = 99.9;
+      //
+      // Loop over the Cams for each pixel
+      //
+      for (Int_t i=0; i<GetSize(); i++)
+        {
+          MCalibrationChargeCam *ccam = (MCalibrationChargeCam*)GetCam(i);
+          //
+          // Get the calibration pix from the calibration cam
+          //
+          MCalibrationChargePix &pix = (MCalibrationChargePix&)(*ccam)[npix];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+
+          if (option.Contains("rsigma"))
+            pvar = pix.GetRSigma();
+          if (option.Contains("abstimemean"))
+            pvar = pix.GetAbsTimeMean();
+          if (option.Contains("abstimerms"))
+            pvar = pix.GetAbsTimeRms();
+          if (option.Contains("conversionhilo"))
+            pvar = pix.GetConversionHiLo();
+          if (option.Contains("convertedmean"))
+            pvar = pix.GetConvertedMean();
+          if (option.Contains("convertedsigma"))
+            pvar = pix.GetConvertedSigma();
+          if (option.Contains("convertedrsigma"))
+            pvar = pix.GetConvertedRSigma();
+          if (option.Contains("meanconvfadc2phe"))
+            pvar = pix.GetMeanConvFADC2Phe();
+          if (option.Contains("meanffactorfadc2phot"))
+            pvar = pix.GetMeanFFactorFADC2Phot();
+          if (option.Contains("ped"))
+            pvar = pix.GetPed();
+          if (option.Contains("pedrms"))
+            pvar = pix.GetPedRms();
+          if (option.Contains("pheffactormethod"))
+            pvar = pix.GetPheFFactorMethod();
+          if (option.Contains("rsigmapercharge"))
+            pvar = pix.GetRSigmaPerCharge();
+          if (option.Contains("conversionfactor"))
+          {
+              const MCalibrationChargePix &apix = (MCalibrationChargePix&)ccam->GetAverageArea(0);
+              pvar = apix.GetPheFFactorMethod()/pix.GetConvertedMean();
+          }
+
+
+          variab  += pvar;
+          variab2 += pvar*pvar;
+          num++;
+        }
+
+      if (num > 1)
+        {
+          variab  /= num;
+          variance = (variab2 - variab*variab*num) / (num-1);
+
+          if (variance > 0.)
+            relrms = TMath::Sqrt(variance)/variab * 100.;
+        }
+      hist->Fill(relrms);
+    }
+  return hist;
+}
+
+void MCalibrationIntensityChargeCam::DrawRazmikPlot( const UInt_t pixid )
+{
+  TGraphErrors *gr = GetRazmikPlot(pixid );
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+
+}
+void MCalibrationIntensityChargeCam::DrawPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPheVsCharge(pixid,col);
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhePerCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPhePerCharge(pixid,MGeomCamMagic(),col); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhePerChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPhePerChargePerArea(aidx,MGeomCamMagic(),col); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPheVsChargePerArea(aidx,col); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawRazmikPlotResults( const Int_t aidx)
+{
+  TH2F *h = GetRazmikPlotResults(aidx,MGeomCamMagic()); 
+  h->SetBit(kCanDelete);
+  h->Draw();
+}
+
+void MCalibrationIntensityChargeCam::DrawChargePerAreaVsTime( const Int_t aidx)
+{
+  TGraphErrors *gr = GetChargePerAreaVsTime(aidx,MGeomCamMagic()); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhePerAreaVsTime( const Int_t aidx)
+{
+  TGraphErrors *gr = GetPhePerAreaVsTime(aidx,MGeomCamMagic()); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhotVsTime( const Option_t *method)
+{
+  TGraphErrors *gr = GetPhotVsTime(method); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+
+void MCalibrationIntensityChargeCam::DrawVarPerAreaVsTime( const Int_t aidx, const Option_t *varname )
+{
+  TGraphErrors *gr = GetVarPerAreaVsTime(aidx,MGeomCamMagic(),varname ); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawVarVsTime( const Int_t pixid , const Option_t *varname )
+{
+  TGraphErrors *gr = GetVarVsTime(pixid,varname ); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawVarFluctuations( const Int_t aidx, const Option_t *varname)
+{
+  TH1F *h = GetVarFluctuations( aidx,MGeomCamMagic(),varname); 
+  h->SetBit(kCanDelete);
+  h->Draw();
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityChargeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityChargeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityChargeCam.h	(revision 17960)
@@ -0,0 +1,69 @@
+#ifndef MARS_MCalibrationIntensityChargeCam
+#define MARS_MCalibrationIntensityChargeCam
+
+#ifndef MARS_MCalibrationIntensityCam
+#include "MCalibrationIntensityCam.h"
+#endif
+
+#ifndef MARS_MCalibrationChargeCam
+#include "MCalibrationChargeCam.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class TGraphErrors;
+class TH2F;
+class TH1F;
+class MGeomCam;
+class MCalibrationIntensityChargeCam : public MCalibrationIntensityCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+
+public:
+
+  MCalibrationIntensityChargeCam(const char *name=NULL, const char *title=NULL);
+
+  Int_t CountNumValidEntries(const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE) const;
+  
+  // Graphs
+
+  TGraphErrors *GetRazmikPlot( const UInt_t pixid );
+  TGraphErrors *GetPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TGraphErrors *GetPhePerCharge( const UInt_t pixid, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TGraphErrors *GetPhePerChargePerArea( const Int_t aidx, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TGraphErrors *GetPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TH2F         *GetRazmikPlotResults( const Int_t aidx, const MGeomCam &geom );
+
+  TGraphErrors *GetChargePerAreaVsTime( const Int_t aidx, const MGeomCam &geom );  
+  TGraphErrors *GetPhePerAreaVsTime( const Int_t aidx, const MGeomCam &geom );
+  TGraphErrors *GetPhotVsTime( const Option_t *method="FFactor" );
+
+  TGraphErrors *GetVarPerAreaVsTime( const Int_t aidx, const MGeomCam &geom, const Option_t *varname );
+  TGraphErrors *GetVarVsTime( const Int_t pixid , const Option_t *varname );
+  TH1F         *GetVarFluctuations( const Int_t aidx, const MGeomCam &geom, const Option_t *varname);
+  
+  // Draws
+  void DrawRazmikPlot( const UInt_t pixid );
+  void DrawPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);       // *MENU*
+  void DrawPhePerCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);      // *MENU*
+  void DrawPhePerChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE); // *MENU*
+  void DrawPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);  // *MENU*
+  void DrawRazmikPlotResults( const Int_t aidx );                          // *MENU*
+
+  void DrawChargePerAreaVsTime( const Int_t aidx);                         // *MENU*
+  void DrawPhePerAreaVsTime( const Int_t aidx );                           // *MENU*
+  void DrawPhotVsTime( const Option_t *method="FFactor");                  // *MENU*
+
+  void DrawVarPerAreaVsTime( const Int_t aidx, const Option_t *varname );  // *MENU*
+  void DrawVarVsTime( const Int_t pixid , const Option_t *varname );       // *MENU*
+  void DrawVarFluctuations( const Int_t aidx, const Option_t *varname);    // *MENU*
+  
+
+  ClassDef(MCalibrationIntensityChargeCam, 1) // Container Intensity Charge Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityConstCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityConstCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityConstCam.cc	(revision 17960)
@@ -0,0 +1,418 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   06/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityConstCam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationConstCam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibConstCam,
+//           MCalibrationChargePix, MCalibrationChargeCalc, MCalibrationQECam
+//           MHCalibrationPix, MHCalibrationCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityConstCam.h"
+#include "MCalibConstCam.h"
+#include "MCalibConstPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MLogManip.h"
+#include "MHCamera.h"
+
+#include <TH1D.h>
+#include <TF1.h>
+#include <TOrdCollection.h>
+#include <TGraphErrors.h>
+
+ClassImp(MCalibrationIntensityConstCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityConstCam::MCalibrationIntensityConstCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityConstCam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+  
+  fCams = new TOrdCollection;
+  fCams->SetOwner();
+  
+  InitSize(1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histograms if they exist
+//
+MCalibrationIntensityConstCam::~MCalibrationIntensityConstCam()
+{
+  if (fCams)
+    delete fCams;
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationConstCam's in the ranges from - to. 
+//
+void MCalibrationIntensityConstCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibConstCam,i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new MCalibConstCam to fCams, give it the name "name" and initialize
+// it with geom.
+//
+void MCalibrationIntensityConstCam::AddToList( const char* name, const MGeomCam &geom) 
+{
+  InitSize(GetSize()+1);
+  GetCam()->SetName(name);
+  GetCam()->Init(geom);
+}
+
+// -----------------------------------------------------
+//
+// Calls Clear() for all entries fCams
+//
+void MCalibrationIntensityConstCam::Clear(Option_t *o)
+{
+  fCams->R__FOR_EACH(MCalibConstCam, Clear)();
+}
+
+// -----------------------------------------------------
+//
+// Calls Print(o) for all entries fCams
+//
+void MCalibrationIntensityConstCam::Print(Option_t *o) const
+{
+  fCams->R__FOR_EACH(MCalibConstCam, Print)(o);
+}
+
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollection using the 
+// virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationIntensityConstCam::InitSize(const UInt_t i)
+{
+
+  const UInt_t save = GetSize();
+
+  if (i==save)
+    return;
+  
+  if (i>save)
+    Add(save,i);
+}
+
+// -------------------------------------------------------------------
+//
+// If size is still 0, Intialize a first Cam.
+// Calls Init(geom) for all fCams
+//
+void MCalibrationIntensityConstCam::Init(const MGeomCam &geom)
+{
+  if (GetSize() == 0)
+    InitSize(1);
+
+  fCams->R__FOR_EACH(MCalibConstCam,Init)(geom);
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fCams 
+// independently if the MCalibrationCam is filled with values or not.
+//
+const Int_t MCalibrationIntensityConstCam::GetSize() const 
+{
+  return fCams->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+MCalibConstPix &MCalibrationIntensityConstCam::operator[](UInt_t i)
+{
+  return (*GetCam())[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+const MCalibConstPix &MCalibrationIntensityConstCam::operator[](UInt_t i) const 
+{
+  return (*GetCam())[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+MCalibConstCam *MCalibrationIntensityConstCam::GetCam(Int_t i)
+{
+  return static_cast<MCalibConstCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+const MCalibConstCam *MCalibrationIntensityConstCam::GetCam(Int_t i) const 
+{
+  return static_cast<MCalibConstCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+
+Bool_t MCalibrationIntensityConstCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  if ((*fBadPixels)[idx].IsUnsuitable())
+    return kFALSE;
+  
+  return GetCam()->GetPixelContent(val,idx,cam,type);
+}
+
+TGraphErrors *MCalibrationIntensityConstCam::GetConvFactorPerAreaVsTime( const Int_t aidx, const MGeomCam &geom)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF convarea(size);
+  TArrayF convareaerr(size);
+  TArrayF time(size);
+  TArrayF timeerr(size);
+  
+  TH1D *h = 0;
+  MCalibConstCam *cam = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      cam = GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      Double_t variab   = 0.;
+      Double_t variab2  = 0.;
+      Double_t variance = 0.;
+      Int_t    num      = 0;
+      Float_t  pvar     = 0.;
+
+      MHCamera camconv(geom,"CamConv","Variable;;channels");
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibConstPix &pix = (*cam)[j];
+          //
+          // Use only pixels of a same area index
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+
+          pvar = pix.GetCalibConst();
+
+          if (pvar < 0)
+            continue;
+          
+          variab  += pvar;
+          variab2 += pvar*pvar;
+          num++;
+          
+          camconv.Fill(j,pvar);
+          camconv.SetUsed(j);
+        }
+      
+      if (num > 1)
+        {
+          variab  /= num;
+          variance = (variab2 - variab*variab*num) / (num-1);
+
+          convarea[i] = variab;
+          if (variance > 0.)
+            convareaerr[i] = TMath::Sqrt(variance);
+          else
+            convareaerr[i] = 999999999.;
+
+          //
+          // Make also a Gauss-fit to the distributions. The RMS can be determined by 
+          // outlier, thus we look at the sigma and the RMS and take the smaller one, afterwards.
+          // 
+          h = camconv.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",500);
+          h->SetDirectory(NULL);
+          h->Fit("gaus","QL");
+          TF1 *fit = h->GetFunction("gaus");
+
+          Float_t ci2   = fit->GetChisquare();
+          Float_t sigma = fit->GetParameter(2);
+
+          if (ci2 > 500. || sigma > convareaerr[i])
+            {
+              h->Fit("gaus","QLM");
+              fit = h->GetFunction("gaus");
+
+              ci2   = fit->GetChisquare();
+              sigma = fit->GetParameter(2);
+            }
+          
+          const Float_t mean    = fit->GetParameter(1);
+          const Float_t meanerr = fit->GetParError(1);
+          const Float_t ndf     = fit->GetNDF();
+          
+          *fLog << inf << "Camera Nr: " << i << endl;
+          *fLog << inf << " area idx: " << aidx << " Results: " << endl;
+          *fLog << inf << "Mean: " << Form("%4.3f",mean) 
+                << "+-" << Form("%4.3f",meanerr)
+                << "  Sigma: " << Form("%4.3f",sigma) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+                << "  Chisquare: " << Form("%4.3f",ci2) << "  NDF  : " << ndf << endl;          
+          delete h;
+          gROOT->GetListOfFunctions()->Remove(fit);
+
+          if (meanerr < convareaerr[i] && ndf > 2 && ci2/ndf < 10.)
+            {
+              convarea   [i] = mean;
+              convareaerr[i] = meanerr;
+            }
+          else
+            {
+              convareaerr[i] /= TMath::Sqrt((Float_t)num);
+            }
+        }
+      else
+        {
+          convarea[i]    = -1.;
+          convareaerr[i] = 0.;
+        }
+
+      time[i] = i;
+      timeerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                      time.GetArray(),convarea.GetArray(),
+                                      timeerr.GetArray(),convareaerr.GetArray());
+  gr->SetTitle(Form("Conversion Factors Area %3i Average",aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_{phe}>/<Q> [FADC cnt^{-1}]");      
+  return gr;
+}
+
+TGraph *MCalibrationIntensityConstCam::GetConvFactorVsTime ( const Int_t pixid )
+{
+  
+  const Int_t size = GetSize();
+
+  if (size == 0)
+    return NULL;
+  
+  TArrayF time(size);
+  TArrayF conv(size);
+  
+  MCalibConstCam *cam = 0;
+
+  for (Int_t i=0;i<size;i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      cam = GetCam(i);
+
+      if (cam->GetSize()-1 < pixid)
+        {
+          *fLog << err << "Pixel " << pixid << " out of range " << endl;
+          return NULL;
+        }
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibConstPix &pix = (*cam)[pixid];
+      //
+      time[i]    = i;
+      conv[i]    = pix.GetCalibConst();
+      //
+  }
+  
+  
+  TGraph *gr = new TGraph(size,time.GetArray(),conv.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_{phe}>/<Q> [FADC cnts^{-1}]");
+  return gr;
+
+  
+}
+
+void MCalibrationIntensityConstCam::DrawConvFactorPerAreaVsTime( const Int_t aidx )
+{
+
+  TGraphErrors *gr = GetConvFactorPerAreaVsTime(aidx,MGeomCamMagic()); 
+
+  if (gr)
+    {
+      gr->SetBit(kCanDelete);
+      gr->Draw("A*");
+    }
+}
+
+void MCalibrationIntensityConstCam::DrawConvFactorVsTime( const Int_t idx )
+{
+  TGraph *gr = GetConvFactorVsTime(idx); 
+  if (gr)
+    {
+      gr->SetBit(kCanDelete);
+      gr->Draw("A*");
+    }
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityConstCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityConstCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityConstCam.h	(revision 17960)
@@ -0,0 +1,76 @@
+#ifndef MARS_MCalibrationIntensityConstCam
+#define MARS_MCalibrationIntensityConstCam
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCalibConstCam
+#include "MCalibConstCam.h"
+#endif
+
+#ifndef MARS_MGeomCamMagic
+#include "MGeomCamMagic.h"
+#endif
+
+class MCalibConstPix;
+class MBadPixelsCam;
+class TOrdCollection;
+class TGraph;
+class TGraphErrors;
+
+class MCalibrationIntensityConstCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TOrdCollection *fCams;      // Array of MCalibConstCams, one per pulse colour and intensity
+  MBadPixelsCam  *fBadPixels; //! Pointer to current MBadPixelsCam
+
+  void Add(const UInt_t from, const UInt_t to);
+  void InitSize( const UInt_t n );
+
+public:
+
+  MCalibrationIntensityConstCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationIntensityConstCam();
+
+  void  Clear ( Option_t *o="" );
+  
+  void  AddToList( const char* name, const MGeomCam &geom);
+
+  const Int_t GetSize() const;
+
+        MCalibConstCam *GetCam              ( Int_t i=-1);
+  const MCalibConstCam *GetCam              ( Int_t i=-1) const;
+
+        MCalibConstPix &operator[]          ( UInt_t i );
+  const MCalibConstPix &operator[]          ( UInt_t i )  const;
+
+  // Inits
+  void  Init   ( const MGeomCam &geom );
+  
+   // Prints
+  void   Print(Option_t *o="")         const;
+
+  // Setters
+  void SetBadPixels( MBadPixelsCam *b )  { fBadPixels = b; }
+  
+  // MCamEvent
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent( Int_t num) const { return GetCam()->DrawPixelContent(num); }
+
+  // Posterior displays
+  TGraphErrors *GetConvFactorPerAreaVsTime( const Int_t aidx=0, const MGeomCam &geom=MGeomCamMagic());  
+  TGraph       *GetConvFactorVsTime      ( const Int_t pixid );
+
+  void DrawConvFactorPerAreaVsTime( const Int_t aidx=-1);          // *MENU*
+  void DrawConvFactorVsTime    ( const Int_t idx );          // *MENU*
+  
+  ClassDef(MCalibrationIntensityConstCam, 1) // Container Calibration Constants Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityRelTimeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityRelTimeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityRelTimeCam.cc	(revision 17960)
@@ -0,0 +1,484 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityRelTimeCam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationRelTimeCam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibrationRelTimeCam,
+//           MCalibrationRelTimePix, MCalibrationRelTimeCalc, MCalibrationQECam
+//           MHCalibrationRelTimePix, MHCalibrationRelTimeCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityRelTimeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationRelTimePix.h"
+#include "MCalibrationChargePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MHCamera.h"
+
+#include "MLogManip.h"
+
+#include <TOrdCollection.h>
+#include <TGraphErrors.h>
+#include <TH1D.h>
+#include <TF1.h>
+
+ClassImp(MCalibrationIntensityRelTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityRelTimeCam::MCalibrationIntensityRelTimeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityRelTimeCam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+  
+  InitSize(1);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationRelTimeCam's in the ranges from - to. 
+//
+void MCalibrationIntensityRelTimeCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationRelTimeCam,i);
+}
+
+TGraphErrors *MCalibrationIntensityRelTimeCam::GetTimeResVsCharge( const UInt_t pixid, const MCalibrationIntensityChargeCam &chargecam, const MCalibrationCam::PulserColor_t col)
+{
+
+  if (chargecam.GetSize() != GetSize())
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+
+  if (size != chargecam.CountNumEntries(col))
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch in colour between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+  
+  const Int_t nvalid = chargecam.CountNumValidEntries(pixid,col);
+
+  if (nvalid == 0)
+    {
+      *fLog << err << GetDescriptor() << ": Only un-calibrated events in pixel: " << pixid << endl;
+      return NULL;
+    }
+
+  TArrayF res(nvalid);
+  TArrayF reserr(nvalid);
+  TArrayF sig(nvalid);
+  TArrayF sigerr(nvalid);
+
+  const Float_t sqrt2   = 1.414;
+  const Float_t fadc2ns = 3.333;
+  
+  Int_t cnt = 0;
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam     = (MCalibrationChargeCam*)chargecam.GetCam(i);
+      MCalibrationRelTimeCam *relcam = (MCalibrationRelTimeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (relcam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)(*cam)[pixid];
+      MCalibrationRelTimePix &relpix = (MCalibrationRelTimePix&)(*relcam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      res[cnt]    = relpix.GetTimePrecision() / sqrt2 * fadc2ns;
+      reserr[cnt] = relpix.GetTimePrecisionErr() / sqrt2 * fadc2ns;
+      //
+      sig   [cnt] = pix.GetPheFFactorMethod();
+      sigerr[cnt] = pix.GetPheFFactorMethodErr();
+      cnt++;
+    }
+
+  TGraphErrors *gr = new TGraphErrors(nvalid,
+                                     sig.GetArray(),res.GetArray(),
+                                     sigerr.GetArray(),reserr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("<Photo-electrons> [1]");
+  gr->GetYaxis()->SetTitle("Time Resolution [ns]");      
+  return gr;
+}
+
+
+TGraphErrors *MCalibrationIntensityRelTimeCam::GetTimeResVsChargePerArea( const Int_t aidx,const MCalibrationIntensityChargeCam &chargecam, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+
+  if (size != chargecam.CountNumEntries(col))
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch in colour between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+
+  if (col == MCalibrationCam::kBLUE)
+    size -= 5;
+  if (col == MCalibrationCam::kNONE)
+    size -= 5;
+  
+  const Float_t sqrt2   = 1.414;
+  const Float_t fadc2ns = 3.333;
+  const Float_t norm    = fadc2ns / sqrt2;
+
+  TArrayD res(size);
+  TArrayD reserr(size);
+  TArrayD sig(size);
+  TArrayD sigerr(size);
+  
+  Int_t cnt = 0;
+
+  TH1D *h = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationRelTimeCam *relcam = (MCalibrationRelTimeCam*)GetCam(i);
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)chargecam.GetCam(i);
+
+      if (relcam->GetPulserColor() != col && col != MCalibrationCam::kNONE)
+        continue;
+
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Double_t phe          = (Double_t)apix.GetPheFFactorMethod();
+      const Double_t pheerr       = (Double_t)apix.GetPheFFactorMethodErr();
+
+      if (relcam->GetPulserColor() == MCalibrationCam::kBLUE)
+	if (aidx == 0)
+	  {
+	    if (phe > 100. && phe < 190.)
+	      continue;
+	  }
+	else
+	  {
+	    if (phe > 200. && phe < 480.)
+	      continue;
+	  }
+
+      if (relcam->GetPulserColor() == MCalibrationCam::kUV)
+	*fLog << inf << "NUMBER: " << i << endl;
+
+      sig[cnt]       = phe;
+      sigerr[cnt]    = pheerr;
+
+      Double_t resol  = 0.;
+      Double_t resol2 = 0.;
+      Double_t var    = 0.;
+      Int_t    num    = 0;
+
+      MHCamera camres(geom,"CamRes","Time Resolution;Time Resolution [ns];channels");
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[j];
+          const MCalibrationRelTimePix &relpix = (MCalibrationRelTimePix&)(*relcam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+          
+          const Double_t pres = (Double_t)relpix.GetTimePrecision();
+
+          resol  += pres;
+          resol2 += pres;
+          num++;
+          
+          camres.Fill(j,pres);
+          camres.SetUsed(j);
+        }
+      
+      if (num > 100)
+        {
+          resol /= num;
+          var  = (resol2 - resol*resol*num) / (num-1);
+
+          res[cnt] = resol;
+          if (var > 0.)
+            reserr[cnt] = TMath::Sqrt(var);
+          else
+            reserr[cnt] = 0.;
+
+          //
+          // Make also a Gauss-fit to the distributions. The RMS can be determined by 
+          // outlier, thus we look at the sigma and the RMS and take the smaller one, afterwards.
+          // 
+          h = camres.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+          h->SetDirectory(NULL);
+          h->Fit("gaus","QL");
+          TF1 *fit = h->GetFunction("gaus");
+
+          Double_t ci2   = fit->GetChisquare();
+          Double_t sigma = fit->GetParameter(2);
+
+          if (ci2 > 500. || sigma > reserr[cnt])
+            {
+              h->Fit("gaus","QLM");
+              fit = h->GetFunction("gaus");
+
+              ci2   = fit->GetChisquare();
+              sigma = fit->GetParameter(2);
+            }
+          
+          const Double_t mean  = fit->GetParameter(1);
+          const Int_t ndf      = fit->GetNDF();
+          
+          *fLog << inf << "Mean number photo-electrons: " << sig[cnt] << endl;
+          *fLog << inf << "Time Resolution area idx: " << aidx << " Results: " << endl;
+          *fLog << inf << "Mean: " << Form("%4.3f",mean) 
+                << "+-" << Form("%4.3f",fit->GetParError(1))
+                << "  Sigma: " << Form("%4.3f",sigma) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+                << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+
+          delete h;
+          gROOT->GetListOfFunctions()->Remove(fit);
+
+          if ((sigma < reserr[cnt] || reserr[cnt]<0.001) && ndf > 2)
+            {
+              res   [cnt] = mean;
+              reserr[cnt] = sigma;
+            }
+	  else
+	    *fLog << warn << "Do not take fit results, but Mean and RMS: " << Form("%4.3f",res[cnt]) << "+-" << Form("%4.3f",reserr[cnt]) << endl;
+
+          res[cnt]    *= norm;
+          reserr[cnt] *= norm;
+	  cnt++;
+        }
+   }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                      sig.GetArray(),res.GetArray(),
+                                      sigerr.GetArray(),reserr.GetArray());
+  gr->SetTitle(Form("%s%3i","Area Index ",aidx));
+  gr->GetXaxis()->SetTitle("<phes> [1]");
+  gr->GetYaxis()->SetTitle("Time Resolution [ns]");      
+  return gr;
+}
+
+TGraphErrors *MCalibrationIntensityRelTimeCam::GetTimeResVsSqrtPhePerArea( const Int_t aidx,const MCalibrationIntensityChargeCam &chargecam, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  const Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+
+  const Int_t asiz = chargecam.CountNumEntries(col);
+
+  if (size != asiz)
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch in colour between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+  
+  const Float_t sqrt2   = 1.414;
+  const Float_t fadc2ns = 3.333;
+  const Float_t norm    = fadc2ns / sqrt2;
+
+  TArrayF res(size);
+  TArrayF reserr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  TH1D *h = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationRelTimeCam *relcam = (MCalibrationRelTimeCam*)GetCam(i);
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)chargecam.GetCam(i);
+
+      if (relcam->GetPulserColor() != col && col != MCalibrationCam::kNONE)
+        continue;
+
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t phe          = apix.GetPheFFactorMethod();
+      const Float_t phesq        = phe > 0. ? TMath::Sqrt(phe) : 0.;
+      const Float_t phesqerr     = phe > 0. ? 0.5*apix.GetPheFFactorMethodErr()/phesq : 0.;
+
+      sig[cnt]       = phesq;
+      sigerr[cnt]    = phesqerr;
+
+      Double_t resol  = 0.;
+      Double_t resol2 = 0.;
+      Double_t var    = 0.;
+      Int_t    num    = 0;
+
+      MHCamera camres(geom,"CamRes","Time Resolution;Time Resolution [ns];channels");
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[j];
+          const MCalibrationRelTimePix &relpix = (MCalibrationRelTimePix&)(*relcam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+          
+          const Float_t pres = relpix.GetTimePrecision();
+
+          resol  += pres;
+          resol2 += pres;
+          num++;
+          
+          camres.Fill(j,pres);
+          camres.SetUsed(j);
+        }
+      
+      if (num > 1)
+        {
+          resol /= num;
+          var  = (resol2 - resol*resol*num) / (num-1);
+
+          res[cnt] = resol;
+          if (var > 0.)
+            reserr[cnt] = TMath::Sqrt(var);
+          else
+            reserr[cnt] = 0.;
+
+          //
+          // Make also a Gauss-fit to the distributions. The RMS can be determined by 
+          // outlier, thus we look at the sigma and the RMS and take the smaller one, afterwards.
+          // 
+          h = camres.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+          h->SetDirectory(NULL);
+          h->Fit("gaus","QL");
+          TF1 *fit = h->GetFunction("gaus");
+
+          Float_t ci2   = fit->GetChisquare();
+          Float_t sigma = fit->GetParameter(2);
+
+          if (ci2 > 500. || sigma > reserr[cnt])
+            {
+              h->Fit("gaus","QLM");
+              fit = h->GetFunction("gaus");
+
+              ci2   = fit->GetChisquare();
+              sigma = fit->GetParameter(2);
+            }
+          
+          const Float_t mean  = fit->GetParameter(1);
+          const Float_t ndf   = fit->GetNDF();
+
+          
+          *fLog << inf << "Sqrt Mean number photo-electrons: " << sig[cnt] << endl;
+          *fLog << inf << "Time Resolution area idx: " << aidx << " Results: " << endl;
+          *fLog << inf << "Mean: " << Form("%4.3f",mean) 
+                << "+-" << Form("%4.3f",fit->GetParError(1))
+                << "  Sigma: " << Form("%4.3f",sigma) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+                << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+
+          delete h;
+          gROOT->GetListOfFunctions()->Remove(fit);
+
+          if (sigma < reserr[cnt] && ndf > 2)
+            {
+              res   [cnt] = mean;
+              reserr[cnt] = sigma;
+            }
+
+          res[cnt]    *= norm;
+          reserr[cnt] *= norm;
+        }
+      else
+        {
+          res[cnt]    = -1.;
+          reserr[cnt] = 0.;
+        }
+      cnt++;
+   }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                      sig.GetArray(),res.GetArray(),
+                                      sigerr.GetArray(),reserr.GetArray());
+  gr->SetTitle(Form("%s%3i","Area Index ",aidx));
+  gr->GetXaxis()->SetTitle("Sqrt(<phes>) [1]");
+  gr->GetYaxis()->SetTitle("Time Resolution [ns]");      
+  return gr;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityRelTimeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityRelTimeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationIntensityRelTimeCam.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MCalibrationIntensityRelTimeCam
+#define MARS_MCalibrationIntensityRelTimeCam
+
+#ifndef MARS_MCalibrationIntensityCam
+#include "MCalibrationIntensityCam.h"
+#endif
+
+#ifndef MARS_MCalibrationIntensityChargeCam
+#include "MCalibrationIntensityChargeCam.h"
+#endif
+
+class TGraphErrors;
+class MCalibrationIntensityRelTimeCam : public MCalibrationIntensityCam
+{
+private:
+
+  void Add(const UInt_t from, const UInt_t to);
+
+public:
+
+  MCalibrationIntensityRelTimeCam(const char *name=NULL, const char *title=NULL);
+
+  TGraphErrors *GetTimeResVsCharge( const UInt_t pixid, const MCalibrationIntensityChargeCam &chargecam,
+                                    const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+
+  TGraphErrors *GetTimeResVsChargePerArea( const Int_t aidx, const MCalibrationIntensityChargeCam &chargecam,
+                                           const MGeomCam &geom,
+                                           const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+
+  TGraphErrors *GetTimeResVsSqrtPhePerArea( const Int_t aidx, const MCalibrationIntensityChargeCam &chargecam,
+                                           const MGeomCam &geom,
+                                           const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+
+  ClassDef(MCalibrationIntensityRelTimeCam, 1) // Container Intensity Rel.Times Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPattern.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPattern.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPattern.cc	(revision 17960)
@@ -0,0 +1,57 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz  12/2004 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationPattern
+//
+//  A container to store the decoded calibration pattern.
+//
+// The idea is, that this container will never change the meaning of its
+// variables, while the calibration pattern itself could.
+//
+// If new 'features' are necessary the decoding (MCalibrationPatternDecode)
+// must be changed to correctly decode the pattern into the existing
+// MCalibrationPattern. If new information is decoded you may have to
+// add new variables to this container. Don't forget to increase the
+// class version number (ClassDef) and document your change HERE.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPattern.h"
+
+ClassImp(MCalibrationPattern);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MCalibrationPattern::MCalibrationPattern(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCalibrationPattern";
+    fTitle = title ? title : "Container for decoded calibration pattern";
+
+    Reset();
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPattern.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPattern.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPattern.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MCalibrationPattern
+#define MARS_MCalibrationPattern
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPattern : public MParContainer
+{
+    friend class MCalibrationPatternDecode;
+
+public:
+
+    enum CLColor_t 
+      {
+        kCLUV       = BIT(0),
+        kCLGreen    = BIT(1),
+        kCLAmber    = BIT(2),
+        kCLRed      = BIT(3),
+        kCLRedAmber   = kCLRed & kCLAmber,
+        kCLRedGreen   = kCLRed & kCLGreen,
+        kCLRedUV      = kCLRed & kCLUV   ,
+        kCLAmberGreen = kCLAmber & kCLGreen,
+        kCLAmberUV    = kCLAmber & kCLUV   ,
+        kCLGreenUV    = kCLGreen & kCLUV   ,
+        kCLRedAmberGreen = kCLRedAmber & kCLGreen,
+        kCLRedGreenUV    = kCLRedGreen & kCLUV,
+        kCLAmberGreenUV  = kCLAmberGreen & kCLUV,
+        kCLAll           = kCLRedAmberGreen & kCLUV,
+	kCLNone    = BIT(4)
+      };
+    
+private:
+
+    UShort_t  fCLStrength;     // Continuous light strenth  
+    CLColor_t fCLColor;        // Color (combinations) of the continuous light
+    Float_t   fPulserStrength; // Strength of the pulsed light (in nr. of equiv. LEDs)
+    
+    MCalibrationCam::PulserColor_t fPulserColor; // Colour of the pulsed light
+
+public:
+
+    MCalibrationPattern(const char *name=0, const char *title=0);
+
+    void Reset() { fCLStrength=0; fCLColor=kCLNone; fPulserColor=MCalibrationCam::kNONE; fPulserStrength=0.; }
+
+    UShort_t   GetCLStrength()     const { return fCLStrength; }
+    CLColor_t  GetCLColor()        const { return fCLColor; }
+    Float_t    GetPulserStrength() const { return fPulserStrength; }
+
+    const MCalibrationCam::PulserColor_t GetPulserColor() const { return fPulserColor; }
+    TString GetPulserColorStr() const { return MCalibrationCam::GetPulserColorStr(fPulserColor); }
+
+    void SetPulserColor   ( const MCalibrationCam::PulserColor_t col) { fPulserColor = col; }
+    void SetPulserStrength( const Float_t strength ) { fPulserStrength = strength; }
+
+    ClassDef(MCalibrationPattern, 1) // Container storing the decoded calibration pattern
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPatternDecode.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPatternDecode.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPatternDecode.cc	(revision 17960)
@@ -0,0 +1,195 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz 12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationPatternDecode
+//
+//  Decodes the trigger pattern from MRawEvtData into MCalibrationPattern.
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+// This can be changed using the information about the file-type.
+//
+// Input:
+//   MRawEvtData
+//   MRawRunHeader
+//
+// Output:
+//   MCalibrationPattern
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPatternDecode.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MCalibrationPattern.h"
+
+ClassImp(MCalibrationPatternDecode);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MCalibrationPatternDecode::MCalibrationPatternDecode(const char *name, const char *title)
+    : fRunHeader(0), fEvtHeader(0), fPattern(0)
+{
+    fName  = name  ? name  : "MCalibrationPatternDecode";
+    fTitle = title ? title : "Task to decode Trigger Pattern";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MCalibrationPatternDecode::PreProcess(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+	*fLog << err << "MRawRunHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fEvtHeader = (MRawEvtHeader *)pList->FindObject("MRawEvtHeader");
+    if (!fEvtHeader)
+    {
+	*fLog << err << "MRawEvtHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fPattern = (MCalibrationPattern*)pList->FindCreateObj("MCalibrationPattern");
+    if (!fPattern)
+	return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+// This can be changed using the information about the file-type.
+//
+Int_t MCalibrationPatternDecode::Process()
+{
+    // No setting necessary because MCalibrationPattern::Reset() has
+    // been called just before
+    if (fRunHeader->GetFormatVersion()<5)
+        return kTRUE;
+
+    // Get calibration pattern from event header
+    const UInt_t pattern = fEvtHeader->GetCalibrationPattern();
+
+    const UInt_t str = (pattern    ) & 0x00ff;
+    const UInt_t col = (pattern>> 8) & 0x000f;
+    const UInt_t pat = (pattern>>16) & 0xffff;
+
+    fPattern->fCLStrength = str;
+    fPattern->fCLColor    = (MCalibrationPattern::CLColor_t)col;
+
+    // Set a default pattern
+    fPattern->fPulserColor =  MCalibrationCam::kNONE;
+
+    // This is a MC workaround because the CT1 bit cannot be set
+    // It would be bit 33 in the pattern which simple
+    // doesn't exist in a 32 bit integer.
+    if (fRunHeader->IsMonteCarloRun() && pat==0)
+        fPattern->fPulserColor =  MCalibrationCam::kCT1;
+
+    // Check the pattern
+    if ((pat & kGreenAndBlue) || (pat & kBlueAndUV) || (pat & kGreenAndUV))
+        fPattern->fPulserColor =  MCalibrationCam::kNONE;
+
+    // FIXME: This condition can never be true!
+    //if (pat & kCT1Pulser)
+    //    fPattern->fPulserColor =  MCalibrationCam::kCT1;
+
+    if (pat & kAnyUV)
+        fPattern->fPulserColor =  MCalibrationCam::kUV;
+
+    if (pat & kAnyGreen)
+        fPattern->fPulserColor =  MCalibrationCam::kGREEN;
+
+    if (pat & kAnyBlue)
+        fPattern->fPulserColor =  MCalibrationCam::kBLUE;
+
+    // Now decode the strength
+    fPattern->fPulserStrength = 0.;
+
+    switch (fPattern->fPulserColor)
+    {
+      case MCalibrationCam::kNONE:
+          break;
+
+      case MCalibrationCam::kGREEN:
+          if (pat & kSlot1Green)
+              fPattern->fPulserStrength += 5.0;
+          if (pat & kSlot2Green)
+              fPattern->fPulserStrength += 2.0;
+          if (pat & kSlot15Green)
+              fPattern->fPulserStrength += 1.0;
+          if (pat & kSlot16AttGreen)
+              fPattern->fPulserStrength += 0.2;
+          break;
+
+      case MCalibrationCam::kBLUE:
+          if (pat & kSlot3Blue)
+              fPattern->fPulserStrength += 5.1;
+          if (pat & kSlot6Blue)
+              fPattern->fPulserStrength += 5.2;
+          if (pat & kSlot7Blue)
+              fPattern->fPulserStrength += 5.4;
+          if (pat & kSlot8Blue)
+              fPattern->fPulserStrength += 2.0;
+          if (pat & kSlot9AttBlue)
+              fPattern->fPulserStrength += 0.25;
+          if (pat & kSlot10Blue)
+              fPattern->fPulserStrength += 0.0;
+          if (pat & kSlot11Blue)
+              fPattern->fPulserStrength += 1.0;
+          if (pat & kSlot14Blue)
+              fPattern->fPulserStrength += 5.8;
+          break;
+
+      case MCalibrationCam::kUV:
+          if (pat & kSlot4UV)
+              fPattern->fPulserStrength += 1.0;
+          if (pat & kSlot5UV)
+              fPattern->fPulserStrength += 2.0;
+          if (pat & kSlot12UV)
+              fPattern->fPulserStrength += 5.1;
+          if (pat & kSlot13UV)
+              fPattern->fPulserStrength += 5.2;
+          break;
+
+      case MCalibrationCam::kCT1:
+          fPattern->fPulserStrength = 20.;
+          break;
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPatternDecode.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPatternDecode.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPatternDecode.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MCalibrationPatternDecode
+#define MARS_MCalibrationPatternDecode
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MCalibrationPattern;
+
+class MCalibrationPatternDecode : public MTask
+{
+private:
+
+    enum PulserColorCode_t 
+      {
+        kSlot1Green     = BIT(0),
+        kSlot2Green     = BIT(1),
+        kSlot3Blue      = BIT(2),
+        kSlot4UV        = BIT(3),
+        kSlot5UV        = BIT(4),
+        kSlot6Blue      = BIT(5),
+        kSlot7Blue      = BIT(6),
+        kSlot8Blue      = BIT(7),
+        kSlot9AttBlue   = BIT(8),
+        kSlot10Blue     = BIT(9),
+        kSlot11Blue     = BIT(10),
+        kSlot12UV       = BIT(11),
+        kSlot13UV       = BIT(12),
+        kSlot14Blue     = BIT(13),
+        kSlot15Green    = BIT(14),
+        kSlot16AttGreen = BIT(15),
+//        kCT1Pulser      = BIT(16),
+        kAnyGreen       = kSlot1Green  | kSlot2Green | kSlot15Green | kSlot16AttGreen,
+        kAnyUV          = kSlot4UV     | kSlot5UV    | kSlot12UV    | kSlot13UV,
+        kAnyBlue        = kSlot3Blue   | kSlot6Blue  | kSlot7Blue   | kSlot8Blue 
+                        | kSlot9AttBlue| kSlot10Blue | kSlot11Blue  | kSlot14Blue, 
+        kGreenAndBlue   = kAnyGreen & kAnyBlue,
+        kBlueAndUV      = kAnyBlue  & kAnyUV,
+        kGreenAndUV     = kAnyGreen & kAnyUV,
+        kIFAEPulser     = kAnyGreen | kAnyBlue | kAnyUV/*,
+        kAny            = kAnyGreen | kAnyBlue | kAnyUV | kCT1Pulser*/
+      };
+
+    MRawRunHeader   *fRunHeader;
+    MRawEvtHeader   *fEvtHeader;
+    MCalibrationPattern *fPattern;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+
+    MCalibrationPatternDecode(const char *name=0, const char *title=0);
+
+    ClassDef(MCalibrationPatternDecode, 1) // Task to decode the Trigger Pattern
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPedCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPedCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPedCam.cc	(revision 17960)
@@ -0,0 +1,152 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationPedCam                                               
+//                                                               
+// Hold the pedestal Calibration results obtained from MHPedestalCam of the camera:
+//                                                               
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Pedestal
+// 1: Error of fitted Pedestal
+// 2: Sigma of fitted Pedestal
+// 3: Error of Sigma of fitted Pedestal
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Pedestal distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPedCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationPix.h"
+
+ClassImp(MCalibrationPedCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MCalibrationPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibrationRelTimeCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibrationRelTimeCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibrationRelTimeCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+MCalibrationPedCam::MCalibrationPedCam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCalibrationPedCam";
+    fTitle = title ? title : "Storage container for the Pedestal Calibration Results in the camera";
+
+}
+
+// --------------------------------------------------------------------------
+//
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Pedestal
+// 1: Error of fitted Pedestal
+// 2: Sigma of fitted Pedestal
+// 3: Error of Sigma of fitted Pedestal
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Pedestal distribution
+//
+Bool_t MCalibrationPedCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ if ((*this)[idx].IsExcluded())
+   return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      val = (*this)[idx].GetHiGainMean();
+      break;
+    case 1:
+      val = (*this)[idx].GetHiGainMeanErr();
+      break;
+    case 2:
+      val = (*this)[idx].GetHiGainSigma();
+      break;
+    case 3:
+      val = (*this)[idx].GetHiGainSigmaErr();
+      break;
+    case 4:
+      val = (*this)[idx].GetHiGainProb();
+      break;
+    case 5:
+      val = (*this)[idx].GetLoGainMean();
+      break;
+    case 6:
+      val = (*this)[idx].GetLoGainMeanErr();
+      break;
+    case 7:
+      val = (*this)[idx].GetLoGainSigma();
+      break;
+    case 8:
+      val = (*this)[idx].GetLoGainSigmaErr();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+  
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPedCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPedCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPedCam.h	(revision 17960)
@@ -0,0 +1,20 @@
+#ifndef MARS_MCalibrationPedCam
+#define MARS_MCalibrationPedCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPedCam : public MCalibrationCam
+{
+public:
+
+  MCalibrationPedCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationPedCam() {}
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  
+  ClassDef(MCalibrationPedCam, 1)	// Container Pedestal Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPix.cc	(revision 17960)
@@ -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): 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"
+
+#include <TMath.h>
+
+ClassImp(MCalibrationPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Sets:
+// - fPixId to -1
+// - fFlags to 0
+//
+// Calls:
+// - Clear()
+//
+MCalibrationPix::MCalibrationPix(const char *name, const char *title)
+    : fPixId(-1),
+      fFlags(0)
+{
+
+  fName  = name  ? name  : "MCalibrationPix";
+  fTitle = title ? title : "Container of the fit results of MHCalibrationPixs ";
+
+  Clear();
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all variables to -1
+// - all flags to kFALSE
+//
+void MCalibrationPix::Clear(Option_t *o)
+{
+
+  fHiGainNumBlackout   =  -1 ;
+  fHiGainNumPickup     =  -1 ;
+  fHiGainMean          =  -1.;
+  fHiGainMeanVar       =  -1.;
+  fHiGainProb          =  -1.;
+  fHiGainRms           =  -1.;
+  fHiGainSigma         =  -1.;
+  fHiGainSigmaVar      =  -1.;
+
+  fLoGainNumBlackout   =  -1 ;
+  fLoGainNumPickup     =  -1 ;
+  fLoGainMean          =  -1.;
+  fLoGainMeanVar       =  -1.;
+  fLoGainProb          =  -1.;
+  fLoGainRms           =  -1.;
+  fLoGainSigma         =  -1.;
+  fLoGainSigmaVar      =  -1.;
+
+  SetHiGainSaturation  ( kFALSE );
+  SetExcluded          ( kFALSE );
+  SetValid             ( kFALSE );
+  SetDebug             ( kFALSE );
+
+}
+
+
+// -----------------------------------------------------
+//
+// copy 'constructor'
+//
+void MCalibrationPix::Copy(TObject& object) const
+{
+
+  MCalibrationPix &pix = (MCalibrationPix&)object;
+
+  //
+  // Copy the data members
+  //
+  pix.fPixId             = fPixId;
+  pix.fFlags             = fFlags;
+  pix.fHiGainMean        = fHiGainMean;
+  pix.fHiGainMeanVar     = fHiGainMeanVar;
+  pix.fHiGainNumBlackout = fHiGainNumBlackout;
+  pix.fHiGainNumPickup   = fHiGainNumPickup;
+  pix.fHiGainSigma       = fHiGainSigma;
+  pix.fHiGainSigmaVar    = fHiGainSigmaVar;
+  pix.fHiGainProb        = fHiGainProb;
+  pix.fLoGainMean        = fLoGainMean;
+  pix.fLoGainMeanVar     = fLoGainMeanVar;
+  pix.fLoGainNumBlackout = fLoGainNumBlackout;
+  pix.fLoGainNumPickup   = fLoGainNumPickup;
+  pix.fLoGainSigma       = fLoGainSigma;
+  pix.fLoGainSigmaVar    = fLoGainSigmaVar;
+  pix.fLoGainProb        = fLoGainProb;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the Hi Gain Saturation Bit from outside
+//
+void MCalibrationPix::SetHiGainSaturation(Bool_t b)
+{
+    b ?  SETBIT(fFlags, kHiGainSaturation) : CLRBIT(fFlags, kHiGainSaturation); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Valid Bit from outside 
+//
+void MCalibrationPix::SetDebug(Bool_t b )
+{ 
+    b ?  SETBIT(fFlags, kDebug) : CLRBIT(fFlags, kDebug); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Excluded Bit from outside 
+//
+void MCalibrationPix::SetExcluded(Bool_t b )
+{ 
+    b ?  SETBIT(fFlags, kExcluded) : CLRBIT(fFlags, kExcluded); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Valid Bit from outside 
+//
+void MCalibrationPix::SetValid(Bool_t b )
+{ 
+    b ?  SETBIT(fFlags, kValid) : CLRBIT(fFlags, kValid); 
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Mean is smaller than 0.5
+// Return -1, if the HiGain Mean is -1.         (has not yet been set) 
+// Return fHiGainMean / fLoGainMean
+//
+Float_t MCalibrationPix::GetHiLoMeansDivided() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainMean <= 0.5)
+    return -1.;
+
+  if (fHiGainMean == -1.)
+    return -1.;
+  
+  return fHiGainMean / fLoGainMean;
+  
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Mean or its variance is smaller than 0.5 (has not yet been set)
+// Return -1, if the HiGain Mean or its variance is -1.         (has not yet been set) 
+// Return propagated error of GetHiLoMeansDivided()
+//
+Float_t MCalibrationPix::GetHiLoMeansDividedErr() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainMean <= 0.5)
+    return -1.;
+
+  if (fHiGainMean == -1.)
+    return -1.;
+  
+  if (fLoGainMeanVar <= 0.)
+    return -1.;
+
+  if (fHiGainMeanVar <= 0.)
+    return -1.;
+  
+  const Float_t lomeansquare = fLoGainMean * fLoGainMean;
+  const Float_t deltaHi = fHiGainMeanVar / lomeansquare;
+  const Float_t deltaLo = fLoGainMeanVar / (lomeansquare * lomeansquare) * fHiGainMean * fHiGainMean;
+
+  return TMath::Sqrt(deltaHi + deltaLo);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Sigma is smaller than 0.01 
+// Return -1, if the HiGain Sigma is -1.         (has not yet been set) 
+// Return fHiGainSigma / fLoGainSigma
+//
+Float_t MCalibrationPix::GetHiLoSigmasDivided() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainSigma <= 0.01)
+    return -1.;
+
+  if (fHiGainSigma == -1.)
+    return -1.;
+  
+  return fHiGainSigma / fLoGainSigma;
+  
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Sigma variance is smaller than 0.
+// Return -1, if the LoGain Sigma is smaller than 0.01
+// Return -1, if the HiGain Sigma or its variance is -1.         (has not yet been set) 
+// Return propagated error of GetHiLoSigmasDivided()
+//
+Float_t MCalibrationPix::GetHiLoSigmasDividedErr() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainSigma <= 0.01) 
+    return -1.;
+
+  if (fHiGainSigma == -1.)
+    return -1.;
+  
+  if (fLoGainSigmaVar <= 0.)
+    return -1.;
+
+  if (fHiGainSigmaVar <= 0.)
+    return -1.;
+  
+  const Float_t losigmasquare = fLoGainSigma * fLoGainSigma;
+  const Float_t deltaHi = fHiGainSigmaVar / losigmasquare;
+  const Float_t deltaLo = fLoGainSigmaVar / (losigmasquare * losigmasquare) * fHiGainSigma * fHiGainSigma;
+
+  return TMath::Sqrt(deltaHi + deltaLo);
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the Relative Variance of either High Gain or Low Gain Mean 
+// depending on IsHighGainSaturation()
+//
+// If variance is smaller than 0. return -1.
+//
+Float_t MCalibrationPix::GetMeanRelVar()  const
+{
+
+  if (IsHiGainSaturation())
+    if (fLoGainMeanVar < 0. || fLoGainMean < 0.)
+      return -1.;
+    else
+      return fLoGainMeanVar / (fLoGainMean * fLoGainMean);
+  else
+    if (fHiGainMeanVar < 0. || fHiGainMean < 0.)
+      return -1.;
+    else
+      return fHiGainMeanVar / (fHiGainMean * fHiGainMean);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Square of either High Gain or Low Gain Mean 
+// depending on IsHighGainSaturation()
+//
+Float_t MCalibrationPix::GetMeanSquare()  const
+{
+
+  if (IsHiGainSaturation())
+    return fLoGainMean == -1. ? -1. : fLoGainMean * fLoGainMean;
+  else
+    return fHiGainMean == -1. ? -1. : fHiGainMean * fHiGainMean;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the Relative Variance of either High Gain or Low Gain Sigma 
+// depending on IsHighGainSaturation()
+//
+// If variance is smaller than 0. return -1.
+//
+Float_t MCalibrationPix::GetSigmaRelVar()  const
+{
+
+  if (IsHiGainSaturation())
+    if (fLoGainSigmaVar < 0.)
+      return -1.;
+    else
+      return fLoGainSigmaVar / (fLoGainSigma * fLoGainSigma);
+  else
+    if (fHiGainSigmaVar < 0.)
+      return -1.;
+    else
+      return fHiGainSigmaVar / (fHiGainSigma * fHiGainSigma);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the High Gain Mean Error: Takes square root of fHiGainMeanVar
+//
+Float_t MCalibrationPix::GetHiGainMeanErr()  const
+{
+  if (fHiGainMeanVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fHiGainMeanVar);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the High Gain Sigma Error: Takes square root of fHiGainSigmaVar
+//
+Float_t MCalibrationPix::GetHiGainSigmaErr()  const
+{
+  if (fHiGainSigmaVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fHiGainSigmaVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Mean Error: Takes square root of fLoGainMeanVar
+//
+Float_t MCalibrationPix::GetLoGainMeanErr()  const
+{
+  if (fLoGainMeanVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fLoGainMeanVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Mean Rel Variance
+//
+Float_t MCalibrationPix::GetLoGainMeanRelVar()  const
+{
+  if (fLoGainMeanVar < 0.)
+    return -1.;
+  if (fLoGainMean   == 0.)
+    return -1.;
+
+  return fLoGainMeanVar / ( fLoGainMean * fLoGainMean);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the High Gain Mean Rel Variance
+//
+Float_t MCalibrationPix::GetHiGainMeanRelVar()  const
+{
+  if (fHiGainMeanVar < 0.)
+    return -1.;
+  if (fHiGainMean   == 0.)
+    return -1.;
+
+  return fHiGainMeanVar / ( fHiGainMean * fHiGainMean);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Sigma Error: Takes square root of fHiGainSigmaVar
+//
+Float_t MCalibrationPix::GetLoGainSigmaErr()  const
+{
+  if (fLoGainSigmaVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fLoGainSigmaVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kHiGainSaturation
+//
+Bool_t MCalibrationPix::IsHiGainSaturation()    const
+{ 
+  return TESTBIT(fFlags,kHiGainSaturation);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kDebug
+//
+Bool_t MCalibrationPix::IsDebug()     const
+{ 
+   return TESTBIT(fFlags,kDebug);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kExcluded
+//
+Bool_t MCalibrationPix::IsExcluded()     const
+{ 
+   return TESTBIT(fFlags,kExcluded);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kValid
+//
+Bool_t MCalibrationPix::IsValid()     const
+{ 
+   return TESTBIT(fFlags,kValid);  
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPix.h	(revision 17960)
@@ -0,0 +1,124 @@
+#ifndef MARS_MCalibrationPix
+#define MARS_MCalibrationPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCalibrationPix : public MParContainer
+{
+protected:
+
+  Int_t   fPixId;             // Software PixId (needed to get Id in calls to Next())
+  UInt_t  fFlags;             // Flag for the set bits
+  Float_t fHiGainMean;        // Mean from fit to high gain values
+  Float_t fHiGainMeanVar;     // Error of mean from fit to high gain values
+  Float_t fHiGainNumBlackout; // Number blackout events in high-gain
+  Float_t fHiGainNumPickup;   // Number pickup events in high-gain
+  Float_t fHiGainRms;         // Histogram RMS of the high gain values
+  Float_t fHiGainSigma;       // Sigma from fit to high gain values
+  Float_t fHiGainSigmaVar;    // Error of sigma from fit to high gain values
+  Float_t fHiGainProb;        // Probability of fit to high gain values
+  Float_t fLoGainMean;        // Mean from fit to high gain values
+  Float_t fLoGainMeanVar;     // Error of mean from fit to low gain values
+  Float_t fLoGainNumBlackout; // Number blackout events in low-gain
+  Float_t fLoGainNumPickup;   // Number pickup events in low-gain
+  Float_t fLoGainRms;         // Histogram RMS of the low-gain values  
+  Float_t fLoGainSigma;       // Sigma of from fit to low gain values
+  Float_t fLoGainSigmaVar;    // Error of sigma from fit to low gain values
+  Float_t fLoGainProb;        // Probability of fit to low gain values
+
+  enum { kHiGainSaturation, kExcluded, kValid, kDebug };   // Possible bits to be sets
+
+public:
+
+  MCalibrationPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationPix() {}
+  
+  void Clear(Option_t *o="");
+  void Copy(TObject& object) const;
+  
+  // Setter
+  void SetPixId( const Int_t i )   { fPixId = i; }
+
+  void SetHiGainMean        ( const Float_t f ) { fHiGainMean        = f; }
+  void SetHiGainMeanVar     ( const Float_t f ) { fHiGainMeanVar     = f; }
+  void SetHiGainNumBlackout ( const Float_t f ) { fHiGainNumBlackout = f; }
+  void SetHiGainNumPickup   ( const Float_t f ) { fHiGainNumPickup   = f; }
+  void SetHiGainProb        ( const Float_t f ) { fHiGainProb        = f; }
+  void SetHiGainRms         ( const Float_t f ) { fHiGainRms         = f; }
+  void SetHiGainSigma       ( const Float_t f ) { fHiGainSigma       = f; }  
+  void SetHiGainSigmaVar    ( const Float_t f ) { fHiGainSigmaVar    = f; }
+  void SetLoGainMean        ( const Float_t f ) { fLoGainMean        = f; }
+  void SetLoGainMeanVar     ( const Float_t f ) { fLoGainMeanVar     = f; }
+  void SetLoGainNumBlackout ( const Float_t f ) { fLoGainNumBlackout = f; }  
+  void SetLoGainNumPickup   ( const Float_t f ) { fLoGainNumPickup   = f; }
+  void SetLoGainProb        ( const Float_t f ) { fLoGainProb        = f; }
+  void SetLoGainRms         ( const Float_t f ) { fLoGainRms         = f; }
+  void SetLoGainSigma       ( const Float_t f ) { fLoGainSigma       = f; }
+  void SetLoGainSigmaVar    ( const Float_t f ) { fLoGainSigmaVar    = f; }
+  void SetMean       ( const Float_t f ) { IsHiGainSaturation() ? fLoGainMean        = f : fHiGainMean        = f      ; }
+  void SetMeanVar    ( const Float_t f ) { IsHiGainSaturation() ? fLoGainMeanVar     = f : fHiGainMeanVar     = f  ;  }
+  void SetNumBlackout( const Float_t f ) { IsHiGainSaturation() ? fLoGainNumBlackout = f : fHiGainNumBlackout = f ; }  
+  void SetNumPickup  ( const Float_t f ) { IsHiGainSaturation() ? fLoGainNumPickup   = f : fHiGainNumPickup   = f ; }
+  void SetProb       ( const Float_t f ) { IsHiGainSaturation() ? fLoGainProb        = f : fHiGainProb        = f      ; }
+  void SetSigma      ( const Float_t f ) { IsHiGainSaturation() ? fLoGainSigma       = f : fHiGainSigma       = f     ; }
+  void SetSigmaVar   ( const Float_t f ) { IsHiGainSaturation() ? fLoGainSigmaVar    = f : fHiGainSigmaVar    = f  ; }
+
+  void SetDebug           ( const Bool_t  b = kTRUE );  
+  void SetExcluded        ( const Bool_t  b = kTRUE );
+  void SetHiGainSaturation( const Bool_t  b = kTRUE );
+  void SetValid           ( const Bool_t  b = kTRUE );
+  
+  // Getters
+  Float_t GetHiGainMean       () const { return fHiGainMean   ;     }
+  Float_t GetHiGainMeanErr    () const;
+  Float_t GetHiGainMeanVar    () const { return fHiGainMeanVar;     }
+  Float_t GetHiGainMeanRelVar () const;
+  Float_t GetHiGainProb       () const { return fHiGainProb   ;     }
+  Float_t GetHiGainRms        () const { return fHiGainRms    ;     }  
+  Float_t GetHiGainSigma      () const { return fHiGainSigma  ;     }
+  Float_t GetHiGainSigmaErr   () const;
+  Float_t GetHiGainSigmaVar   () const { return fHiGainSigmaVar;    }
+  Float_t GetHiGainNumPickup  () const { return fHiGainNumPickup;   }
+  Float_t GetHiGainNumBlackout() const { return fHiGainNumBlackout; }  
+  Float_t GetHiLoMeansDivided         () const;
+  Float_t GetHiLoMeansDividedErr      () const;
+  Float_t GetHiLoSigmasDivided        () const;
+  Float_t GetHiLoSigmasDividedErr     () const;
+
+  virtual Float_t GetLoGainMean       () const { return fLoGainMean;        }
+  virtual Float_t GetLoGainMeanErr    () const;
+  virtual Float_t GetLoGainMeanVar    () const { return fLoGainMeanVar;     }
+  virtual Float_t GetLoGainMeanRelVar () const;  
+  virtual Float_t GetLoGainProb       () const { return fLoGainProb;        }
+  virtual Float_t GetLoGainRms        () const { return fLoGainRms  ;       }
+  virtual Float_t GetLoGainSigma      () const { return fLoGainSigma;       }  
+  virtual Float_t GetLoGainSigmaErr   () const;
+  virtual Float_t GetLoGainSigmaVar   () const { return fLoGainSigmaVar;    }
+  virtual Float_t GetLoGainNumPickup  () const { return fLoGainNumPickup;   }
+  virtual Float_t GetLoGainNumBlackout() const { return fLoGainNumBlackout; }  
+
+  Float_t GetMean       () const { return IsHiGainSaturation() ? GetLoGainMean()        : GetHiGainMean()     ;   }
+  Float_t GetMeanErr    () const { return IsHiGainSaturation() ? GetLoGainMeanErr()     : GetHiGainMeanErr()  ;   }
+  Float_t GetMeanRelVar () const;
+  Float_t GetMeanSquare () const;  
+  Float_t GetRms        () const { return IsHiGainSaturation() ? GetLoGainRms()         : GetHiGainRms()      ;   }
+  Float_t GetProb       () const { return IsHiGainSaturation() ? GetLoGainProb()        : GetHiGainProb()     ;   }
+  Float_t GetSigma      () const { return IsHiGainSaturation() ? GetLoGainSigma()       : GetHiGainSigma()    ;   }
+  Float_t GetSigmaErr   () const { return IsHiGainSaturation() ? GetLoGainSigmaErr()    : GetHiGainSigmaErr() ;   }
+  Float_t GetSigmaRelVar() const;
+  Float_t GetNumPickup  () const { return IsHiGainSaturation() ? GetLoGainNumPickup()   : GetHiGainNumPickup();   }
+  Float_t GetNumBlackout() const { return IsHiGainSaturation() ? GetLoGainNumBlackout() : GetHiGainNumBlackout(); }
+  Int_t   GetPixId      () const { return fPixId ;  }
+  
+  Bool_t  IsHiGainSaturation() const;
+  Bool_t  IsDebug   ()         const;
+  Bool_t  IsExcluded()         const;
+  Bool_t  IsValid   ()         const;
+
+  ClassDef(MCalibrationPix, 2)	// Base Container for Calibration Results Pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPulseTimeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPulseTimeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPulseTimeCam.cc	(revision 17960)
@@ -0,0 +1,239 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationPulseTimeCam                                               
+//                                                               
+// Storage container for relative arrival time calibration results         
+// of the whole camera.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationPix &avpix = (MCalibrationPix&)(*fPulseCam)[i]
+// 
+// The following "calibration" constants can be retrieved from each pixel:
+// - GetTimeOffset(): The mean offset in relative times, 
+//   has to be added to any calculated relative time in the camera. 
+// - GetTimePrecision(): The Gauss sigma of histogrammed relative arrival 
+//   times for the calibration run. Gives an estimate about the timing 
+//   resolution.
+//
+// ALL RELATIVE TIMES HAVE TO BE CALCULATED W.R.T. PIXEL IDX 1 
+// (HARDWARE NUMBER: 2) !!
+//
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationPix &avpix = (MCalibrationPix&)fPulseCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationPix &avpix = (MCalibrationPix&)fPulseCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// See also: MHCalibrationPix, MHCalibrationPulseTimeCam              
+//                                                                         
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Mean Time Offset
+// 1: Error of Mean Time Offset
+// 2: Sigma of Time Offset == Time Resolution 
+// 3: Error of Sigma of Time Offset
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Pulse. Arrival Time distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPulseTimeCam.h"
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MCalibrationPix.h"
+
+ClassImp(MCalibrationPulseTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationPulseTimeCam::MCalibrationPulseTimeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationPulseTimeCam";
+  fTitle = title ? title : "Container for Pulse Time Information";
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not Valid
+//
+void MCalibrationPulseTimeCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+
+  *fLog << all << "Calibrated pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationPix *pix;
+  while ((pix=(MCalibrationPix*)Next()))
+    {
+
+      if (!pix->IsExcluded()) 
+	{                            
+
+          *fLog << all 
+                << Form("Pix  %4i:  Mean Time: %4.2f+-%4.2f Time Jitter: %4.2f+-%4.2f",pix->GetPixId(),
+                        pix->GetMean(),pix->GetMeanErr(),pix->GetSigma(),pix->GetSigmaErr())
+		<< endl;
+          id++;
+	}
+    }
+
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+
+
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationPix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+	  *fLog << all << pix->GetPixId() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationPix*)Next5()))
+  {
+    *fLog << all 
+	  << Form("Pix  %4i:  Mean Time: %4.2f+-%4.2f Time Jitter: %4.2f+-%4.2f",pix->GetPixId(),
+		  pix->GetMean(),pix->GetMeanErr(),pix->GetSigma(),pix->GetSigmaErr())
+          << endl;
+  }
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationPix*)Next5()))
+  {
+    *fLog << all 
+	  << Form("Pix  %4i:  Mean Time: %4.2f+-%4.2f Time Jitter: %4.2f+-%4.2f",pix->GetPixId(),
+		  pix->GetMean(),pix->GetMeanErr(),pix->GetSigma(),pix->GetSigmaErr())
+          << endl;
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted PulseTime
+// 1: Error of fitted PulseTime
+// 2: Sigma of fitted PulseTime
+// 3: Error of Sigma of fitted PulseTime
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to PulseTime distribution
+//
+Bool_t MCalibrationPulseTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+  if (area == 0)
+    return kFALSE;
+
+  const MCalibrationPix &pix = static_cast<const MCalibrationPix&>((*this)[idx]);
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainMean();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainMeanErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainSigma();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainSigmaErr();
+      break;
+    case 4:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetProb();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationPulseTimeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationPulseTimeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationPulseTimeCam.h	(revision 17960)
@@ -0,0 +1,23 @@
+#ifndef MARS_MCalibrationPulseTimeCam
+#define MARS_MCalibrationPulseTimeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPulseTimeCam : public MCalibrationCam
+{
+public:
+
+  MCalibrationPulseTimeCam(const char *name=NULL, const char *title=NULL);
+
+  // Prints
+  void Print(Option_t *o="") const;
+  
+  // Others
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  ClassDef(MCalibrationPulseTimeCam, 2)	// Container Pulse Time Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationQECam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationQECam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationQECam.cc	(revision 17960)
@@ -0,0 +1,925 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationQECam                                               
+//                                                               
+// Storage container for the calibrated Quantum Efficiency of the whole camera.
+//
+// For a complete description of the quantum efficiency calibration process, 
+// see MCalibrationQEPix.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationQEPix &avpix = (MCalibrationQEPix&)(*fQECam)[i]
+// 
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationQEPix &avpix = (MCalibrationQEPix&)fQECam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationQEPix &avpix = (MCalibrationQEPix&)fQECam->GetAverageSector(i)
+//
+// The following "calibration" constants are used for the calibration of each pixel:
+//
+// - MCalibrationQEPix::GetQECascadesBlindPixel(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the Blind Pixel Method. 
+// - MCalibrationQEPix::GetQECascadesFFactor(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the F-Factor Method
+// - MCalibrationQEPix::GetQECascadesPINDiode(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the PIN Diode Method
+// - MCalibrationQEPix::GetQECascadesCombined(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the combination of the three methods
+//
+// The following "calibration" constants have been measured to obtain the above values:
+//
+// - MCalibrationQEPix::GetQEBlindPixel( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color 
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the Blind Pixel Method
+// - MCalibrationQEPix::GetQEFFactor( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the F-Factor Method
+// - MCalibrationQEPix::GetQEPINDiode( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color 
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the PIN Diode Method
+// - MCalibrationQEPix::GetQECombined( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color 
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the combination of the three methods
+//
+// See also: MCalibrationQEPix, MCalibrationChargeCam, MCalibrationChargeCalc
+//           MCalibrationChargeBlindPix, MCalibrationChargePINDiode, MCalibrationChargePix
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+#include <TOrdCollection.h>
+#include <TGraphErrors.h>
+#include <TH2D.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationQECam);
+
+using namespace std;
+
+const Float_t MCalibrationQECam::gkPlexiglassQE    = 0.92;
+const Float_t MCalibrationQECam::gkPlexiglassQEErr = 0.01;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationQECam::MCalibrationQECam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCalibrationQECam";
+    fTitle = title ? title : "Storage container for the calibrated Quantum Efficiency of the camera";
+
+    fFlags.Set(MCalibrationCam::gkNumPulserColors);
+
+    Clear();
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationQEPix's in the ranges from - to to fPixels
+//
+void MCalibrationQECam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationQEPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationQEPix's in the ranges from - to to fAverageAreas
+//
+void MCalibrationQECam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationQEPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationQEPix's in the ranges from - to to fAverageSectors
+//
+void MCalibrationQECam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationQEPix,i);
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets all bits to kFALSE
+// 
+// Calls:
+// - MCalibrationCam::Clear()
+//
+void MCalibrationQECam::Clear(Option_t *o)
+{
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kGREEN);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kGREEN);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kBLUE);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kBLUE);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kUV);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kUV);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kUV);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kUV);
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kCT1);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kCT1);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+
+  MCalibrationCam::Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibrationQECam::Copy(TObject& object) const
+{
+  
+  MCalibrationQECam &qecam = (MCalibrationQECam&)object;
+  
+  MCalibrationCam::Copy(qecam);
+  
+  qecam.fFlags        = fFlags;
+  qecam.fCorningBlues = fCorningBlues;
+  qecam.fCorningReds  = fCorningReds;
+  
+}
+
+// --------------------------------------------------------------------
+//
+// Types used by MCalibrate and MCalibrateData: 
+// ============================================
+//
+// 0: Mean Quantum Efficiency for cascades, obtained with the F-Factor method
+// 1: Error of the Mean QE for cascades, obtained with the F-Factor method
+// 2: Mean Quantum Efficiency for cascades, obtained with the Blind Pixel method
+// 3: Error of the Mean QE for cascades, obtained with the Blind Pixel method
+// 4: Mean Quantum Efficiency for cascades, obtained with the PIN Diode method
+// 5: Error of the Mean QE for cascades, obtained with the PIN Diode method
+// 6: Mean Quantum Efficiency for cascades, obtained with combination of the 3 methods
+// 7: Error of the Mean QE for cascades, obtained with combination of the 3 methods
+// 8: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+// 9: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+// 10: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+// 11: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationChargePix:
+// ===============================================================================
+//
+// 12: Mean Quantum Efficiency obtained with F-Factor Method ( color: kCT1)
+// 13: Error of the Mean QE obtained with F-Factor Method ( color: kCT1)
+// 14: Mean Quantum Efficiency obtained with F-Factor Method ( color: kGREEN)
+// 15: Error of the Mean QE obtained with F-Factor Method ( color: kGREEN)
+// 16: Mean Quantum Efficiency obtained with F-Factor Method ( color: kBLUE)
+// 17: Error of the Mean QE obtained with F-Factor Method ( color: kBLUE)
+// 18: Mean Quantum Efficiency obtained with F-Factor Method ( color: kUV)
+// 19: Error of the Mean QE obtained with F-Factor Method ( color: kUV)
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationChargeBlindPix:
+// ====================================================================================
+//
+// 20: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kCT1)
+// 21: Error of the Mean QE obtained with Blind Pixel Method ( color: kCT1)
+// 22: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kGREEN)
+// 23: Error of the Mean QE obtained with Blind Pixel Method ( color: kGREEN)
+// 24: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kBLUE)
+// 25: Error of the Mean QE obtained with Blind Pixel Method ( color: kBLUE)
+// 26: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kUV)
+// 27: Error of the Mean QE obtained with Blind Pixel Method ( color: kUV)
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationChargePINDiode:
+// ====================================================================================
+//
+// 28: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kCT1)
+// 29: Error of the Mean QE obtained with PIN Diode Method ( color: kCT1)
+// 30: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kGREEN)
+// 31: Error of the Mean QE obtained with PIN Diode Method ( color: kGREEN)
+// 32: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kBLUE)
+// 33: Error of the Mean QE obtained with PIN Diode Method ( color: kBLUE)
+// 34: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kUV)
+// 35: Error of the Mean QE obtained with PIN Diode Method ( color: kUV)
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationQEPix:
+// ===========================================================================
+//
+// 36: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kCT1)
+// 37: Error of the Mean QE obtained with combination of 3 methods ( color: kCT1)
+// 38: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kGREEN)
+// 39: Error of the Mean QE obtained with combination of 3 methods ( color: kGREEN)
+// 40: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kBLUE)
+// 41: Error of the Mean QE obtained with combination of 3 methods ( color: kBLUE)
+// 42: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kUV)
+// 43: Error of the Mean QE obtained with combination of 3 methods ( color: kUV)
+//
+Bool_t MCalibrationQECam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[idx];
+
+  if (pix.IsExcluded())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      if (!pix.IsAverageQEFFactorAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesFFactor();
+      break;
+    case 1:
+      if (!pix.IsAverageQEFFactorAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesFFactorErr();
+      break;
+    case 2:
+      if (!pix.IsAverageQEBlindPixelAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesBlindPixel();
+      break;
+    case 3:
+      if (!pix.IsAverageQEBlindPixelAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesBlindPixelErr();
+      break;
+    case 4:
+      if (!pix.IsAverageQEPINDiodeAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesPINDiode();
+      break;
+    case 5:
+      if (!pix.IsAverageQEPINDiodeAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesPINDiodeErr();
+      break;
+    case 6:
+      if (!pix.IsAverageQECombinedAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesCombined();
+      break;
+    case 7:
+      if (!pix.IsAverageQECombinedAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesCombinedErr();
+      break;
+    case 8:
+      if (pix.IsAverageQEFFactorAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 9:
+      if (pix.IsAverageQEBlindPixelAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 10:
+      if (pix.IsAverageQEPINDiodeAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 11:
+      if (pix.IsAverageQECombinedAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 12:
+      val = pix.GetQEFFactor(kCT1);
+      break;
+    case 13:
+      val = pix.GetQEFFactorErr(kCT1);
+      break;
+    case 14:
+      val = pix.GetQEFFactor(kGREEN);
+      break;
+    case 15:
+      val = pix.GetQEFFactorErr(kGREEN);
+      break;
+    case 16:
+      val = pix.GetQEFFactor(kBLUE);
+      break;
+    case 17:
+      val = pix.GetQEFFactorErr(kBLUE);
+      break;
+    case 18:
+      val = pix.GetQEFFactor(kUV);
+      break;
+    case 19:
+      val = pix.GetQEFFactorErr(kUV);
+      break;
+    case 20:
+      val = pix.GetQEBlindPixel(kCT1);
+      break;
+    case 21:
+      val = pix.GetQEBlindPixelErr(kCT1);
+      break;
+    case 22:
+      val = pix.GetQEBlindPixel(kGREEN);
+      break;
+    case 23:
+      val = pix.GetQEBlindPixelErr(kGREEN);
+      break;
+    case 24:
+      val = pix.GetQEBlindPixel(kBLUE);
+      break;
+    case 25:
+      val = pix.GetQEBlindPixelErr(kBLUE);
+      break;
+    case 26:
+      val = pix.GetQEBlindPixel(kUV);
+      break;
+    case 27:
+      val = pix.GetQEBlindPixelErr(kUV);
+      break;
+    case 28:
+      val = pix.GetQEPINDiode(kCT1);
+      break;
+    case 29:
+      val = pix.GetQEPINDiodeErr(kCT1);
+      break;
+    case 30:
+      val = pix.GetQEPINDiode(kGREEN);
+      break;
+    case 31:
+      val = pix.GetQEPINDiodeErr(kGREEN);
+      break;
+    case 32:
+      val = pix.GetQEPINDiode(kBLUE);
+      break;
+    case 33:
+      val = pix.GetQEPINDiodeErr(kBLUE);
+      break;
+    case 34:
+      val = pix.GetQEPINDiode(kUV);
+      break;
+    case 35:
+      val = pix.GetQEPINDiodeErr(kUV);
+      break;
+    case 36:
+      val = pix.GetQECombined(kCT1);
+      break;
+    case 37:
+      val = pix.GetQECombinedErr(kCT1);
+      break;
+    case 38:
+      val = pix.GetQECombined(kGREEN);
+      break;
+    case 39:
+      val = pix.GetQECombinedErr(kGREEN);
+      break;
+    case 40:
+      val = pix.GetQECombined(kBLUE);
+      break;
+    case 41:
+      val = pix.GetQECombinedErr(kBLUE);
+      break;
+    case 42:
+      val = pix.GetQECombined(kUV);
+      break;
+    case 43:
+      val = pix.GetQECombinedErr(kUV);
+      break;
+    default:
+      return kFALSE;
+    }
+  return val!=-1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPlexiglassQEErr is smaller than 0.
+// Return -1 if gkPlexiglassQE    is 0.
+// Return gkPlexiglassQEErr^2 / gkPlexiglassQE^2
+// 
+Float_t MCalibrationQECam::GetPlexiglassQERelVar() const
+{
+  if (gkPlexiglassQEErr < 0.)
+    return -1.;
+  
+  if (gkPlexiglassQE  == 0.)
+    return -1.;
+  
+  return gkPlexiglassQEErr * gkPlexiglassQEErr / gkPlexiglassQE / gkPlexiglassQE ;
+}
+
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kBlindPixelMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsBlindPixelMethodValid () const  
+{
+  if (IsBlindPixelMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kCombinedMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsCombinedMethodValid () const
+{
+  if (IsCombinedMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kFFactorMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsFFactorMethodValid () const
+{
+  if (IsFFactorMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kPINDiodeMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsPINDiodeMethodValid () const
+{
+  if (IsPINDiodeMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kBlindPixelMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsBlindPixelMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kBlindPixelMethodValid);
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kCombinedMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsCombinedMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kCombinedMethodValid);
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kFFactorMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsFFactorMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kFFactorMethodValid);
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kPINDiodeMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsPINDiodeMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the 
+// - MCalibrationQEPix::GetQECascadesFFactor() 
+// - MCalibrationQEPix::GetQECascadesBlindPixel() 
+// - MCalibrationQEPix::GetQECascadesPINDiode() 
+// - MCalibrationQEPix::GetQECascadesCombined()
+// for all pixels 
+//
+void MCalibrationQECam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, measured with F-Factor method:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationQEPix *pix;
+  while ((pix=(MCalibrationQEPix*)Next()))
+    {
+      
+      if (!pix->IsExcluded() && pix->IsAverageQEFFactorAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesFFactor()," +- ",pix->GetQECascadesFFactorErr())
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+  
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, " 
+        << "measured with Blind Pixel method:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next2(fPixels);
+    while ((pix=(MCalibrationQEPix*)Next2()))
+      {
+        
+      if (!pix->IsExcluded() && pix->IsAverageQEBlindPixelAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesBlindPixel()," +- ",pix->GetQECascadesBlindPixelErr())
+		<< endl;
+          id++;
+	}
+      }
+
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+  
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, " 
+        << "measured with PIN Diode method:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next3(fPixels);
+    while ((pix=(MCalibrationQEPix*)Next3()))
+      {
+        
+      if (!pix->IsExcluded() && pix->IsAverageQEPINDiodeAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesPINDiode()," +- ",pix->GetQECascadesPINDiodeErr())
+		<< endl;
+          id++;
+	}
+      }
+
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+
+    
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, " 
+        << "measured with combination of the 3 methods:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next4(fPixels);
+    while ((pix=(MCalibrationQEPix*)Next4()))
+      {
+        
+      if (!pix->IsExcluded() && pix->IsAverageQECombinedAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesCombined()," +- ",pix->GetQECascadesCombinedErr())
+		<< endl;
+          id++;
+	}
+      }
+
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next5(fPixels);
+  while ((pix=(MCalibrationQEPix*)Next5()))
+  {
+      if (pix->IsExcluded())
+      {
+	  *fLog << all << pix->GetPixId() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the Blind Pixel Method, 
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetBlindPixelMethodValid ( const Bool_t b ) 
+{
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kGREEN);
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kBLUE );
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kUV   );
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// ----------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the combination of the 3 methods
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetCombinedMethodValid ( const Bool_t b ) 
+{
+  SetCombinedMethodValid ( b, MCalibrationCam::kGREEN);
+  SetCombinedMethodValid ( b, MCalibrationCam::kBLUE );
+  SetCombinedMethodValid ( b, MCalibrationCam::kUV   );
+  SetCombinedMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the F-Factor Method
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetFFactorMethodValid ( const Bool_t b ) 
+{
+  SetFFactorMethodValid ( b, MCalibrationCam::kGREEN);
+  SetFFactorMethodValid ( b, MCalibrationCam::kBLUE );
+  SetFFactorMethodValid ( b, MCalibrationCam::kUV   );
+  SetFFactorMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the PIN Diode Method, 
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetPINDiodeMethodValid ( const Bool_t b ) 
+{
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kGREEN);
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kBLUE );
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kUV   );
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the Blind Pixel Method, 
+// for colour "col"
+// 
+void MCalibrationQECam::SetBlindPixelMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kBlindPixelMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kBlindPixelMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the combination of 3 methods
+// for colour "col"
+// 
+void MCalibrationQECam::SetCombinedMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kCombinedMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kCombinedMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the F-Factor Method, 
+// for colour "col"
+// 
+void MCalibrationQECam::SetFFactorMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kFFactorMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kFFactorMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the PIN Diode Method, 
+// for colour "col"
+// 
+void MCalibrationQECam::SetPINDiodeMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns a TGraphErrors correlating the corning blues with the 
+// calcualted quantum efficiency of each pixel, obtained with the F-Factor 
+// method.
+// 
+TGraphErrors *MCalibrationQECam::GetGraphQEvsCorningBlues() const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningBlues.GetSize() == 0)
+    {
+      *fLog << warn << "Size of intialized Cornings Blue is zero, please use MCalibrationQECamMagic" << endl;
+      return NULL;
+    }
+  
+  if (fCorningBlues.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TArrayD qes(size);
+  TArrayD qeerrs(size);
+  TArrayD corns(size);
+  TArrayD cornerrs(size);
+  
+  Int_t cnt = 0;
+  
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningBlues[i] > 0. && pix.GetQECascadesFFactorErr() > 0.)
+        {
+          qes   [i] = pix.GetQECascadesFFactor();
+          qeerrs[i] = pix.GetQECascadesFFactorErr();
+          corns [i] = fCorningBlues[i];
+          cornerrs[i] = 0.05;
+          cnt++;
+        }
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(cnt,
+                                     corns.GetArray(),qes.GetArray(),
+                                      cornerrs.GetArray(),qeerrs.GetArray());
+  return gr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns a TGraphErrors correlating the corning reds with the 
+// calcualted quantum efficiency of each pixel, obtained with the F-Factor 
+// method.
+// 
+TGraphErrors *MCalibrationQECam::GetGraphQEvsCorningReds() const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningReds.GetSize() == 0)
+    {
+      *fLog << warn << "Size of intialized Cornings Red is zero, please use MCalibrationQECamMagic" << endl;
+      return NULL;
+    }
+  
+  if (fCorningReds.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TArrayD qes(size);
+  TArrayD qeerrs(size);
+  TArrayD corns(size);
+  TArrayD cornerrs(size);
+
+  Int_t cnt = 0;
+
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningReds[i] > 0. && pix.GetQECascadesFFactorErr() > 0.)
+        {
+          qes     [i] = pix.GetQECascadesFFactor();
+          qeerrs  [i] = pix.GetQECascadesFFactorErr();
+          corns   [i] = fCorningReds[i];
+          cornerrs[i] = 0.05;
+          cnt++;
+        }
+      
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(cnt,
+                                      corns.GetArray(),qes.GetArray(),
+                                      cornerrs.GetArray(),qeerrs.GetArray());
+  
+  return gr;
+}
+
+TH2D *MCalibrationQECam::GetHistQEvsCorningBlues( const Int_t nbins, const Axis_t first, const Axis_t last ) const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningBlues.GetSize() == 0)
+    return NULL;
+  
+  if (fCorningBlues.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TH2D *h = new TH2D("hist","QE vs. Corning Blue",nbins,first,last,nbins,0.,0.35);
+  
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningBlues[i] > 0.)
+        h->Fill(fCorningBlues[i],pix.GetQECascadesFFactor());
+    }
+  
+  return h;
+}
+
+TH2D *MCalibrationQECam::GetHistQEvsCorningReds( const Int_t nbins, const Axis_t first, const Axis_t last ) const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningReds.GetSize() == 0)
+    return NULL;
+  
+  if (fCorningReds.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TH2D *h = new TH2D("hist","QE vs. Corning Red",nbins,first,last,nbins,0.,0.35);
+
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningReds[i] > 0.)
+        h->Fill(fCorningReds[i],pix.GetQECascadesFFactor());
+    }
+  
+  return h;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationQECam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationQECam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationQECam.h	(revision 17960)
@@ -0,0 +1,88 @@
+#ifndef MARS_MCalibrationQECam
+#define MARS_MCalibrationQECam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TGraphErrors;
+class TH2D;
+class MCalibrationQECam : public MCalibrationCam
+{
+private:
+
+  static const Float_t gkPlexiglassQE   ;  //! Quantum Efficiency Plexiglass (now set to: 0.96)
+  static const Float_t gkPlexiglassQEErr;  //! Uncertainty QE Plexiglass     (now set to: 0.01)
+
+  TArrayC fFlags;                          //  Contains validity bits 
+
+  enum { kBlindPixelMethodValid, kFFactorMethodValid,
+         kPINDiodeMethodValid, kCombinedMethodValid }; // Possible validity bits
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+
+  
+protected:
+
+  MArrayD fCorningBlues;                   // Corning blues of the pixels (if available) 
+  MArrayD fCorningReds;                    // Corning reds  of the pixels (if available) 
+
+public:
+
+  MCalibrationQECam(const char *name=NULL, const char *title=NULL);
+
+  void Clear( Option_t *o=""  );
+  void Copy ( TObject& object ) const;
+
+  TGraphErrors *GetGraphQEvsCorningBlues() const;
+  TGraphErrors *GetGraphQEvsCorningReds() const;  
+  
+  TH2D *GetHistQEvsCorningBlues( const Int_t nbins=50, const Axis_t first=6., const Axis_t last=17.) const;
+  TH2D *GetHistQEvsCorningReds( const Int_t nbins=50, const Axis_t first=0., const Axis_t last=25.) const;  
+  
+  // Others
+  Bool_t  GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0 ) const;
+
+  Float_t GetPlexiglassQE          () const { return gkPlexiglassQE; }
+  Float_t GetPlexiglassQERelVar    () const; 
+
+  const MArrayD &GetCorningBlues   () const { return fCorningBlues;  }
+  const MArrayD &GetCorningReds    () const { return fCorningReds;   }
+  
+  Bool_t  IsBlindPixelMethodValid  () const;
+  Bool_t  IsFFactorMethodValid     () const;  
+  Bool_t  IsCombinedMethodValid    () const;  
+  Bool_t  IsPINDiodeMethodValid    () const;  
+          
+  Bool_t  IsBlindPixelMethodValid  ( MCalibrationCam::PulserColor_t col ) const;
+  Bool_t  IsFFactorMethodValid     ( MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsCombinedMethodValid    ( MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsPINDiodeMethodValid    ( MCalibrationCam::PulserColor_t col ) const;  
+
+  // Prints
+  void    Print(Option_t *o="")       const;
+  
+  // Setters (without color only for MC!)
+  void    SetBlindPixelMethodValid ( const Bool_t  b=kTRUE );
+  void    SetBlindPixelMethodValid ( const Bool_t  b, MCalibrationCam::PulserColor_t col);
+  void    SetCombinedMethodValid   ( const Bool_t  b=kTRUE );
+  void    SetCombinedMethodValid   ( const Bool_t  b, MCalibrationCam::PulserColor_t col);
+  void    SetFFactorMethodValid    ( const Bool_t  b=kTRUE );  
+  void    SetFFactorMethodValid    ( const Bool_t  b, MCalibrationCam::PulserColor_t col);  
+  void    SetPINDiodeMethodValid   ( const Bool_t  b=kTRUE );  
+  void    SetPINDiodeMethodValid   ( const Bool_t  b, MCalibrationCam::PulserColor_t col);  
+
+  ClassDef(MCalibrationQECam, 2) // Container Quantum Efficieny Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationQECamMagic.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationQECamMagic.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationQECamMagic.cc	(revision 17960)
@@ -0,0 +1,1247 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationQECamMagic                                               
+//                                                               
+// Storage container for the calibrated Quantum Efficiency of the whole camera
+// with Corning Blue and Corning Red values initialized for the MAGIC camera.
+// The values are valid for the camera after July 5, 2004.
+//
+// The following plots display the distributions of the cornings: 
+// * The corning blue w.r.t. the pixel index:
+//   One can see the selection of pixels such that the highest corning blue values 
+//   are located towards the center of the camera.
+// * The corning red w.r.t. the pixel index:
+//   One can see that there is a population in the outmost ring of inner pixels
+//   with much lower corning reds. This characteristic is also valid for the 
+//   quantum efficiency in the green. 
+// * The corning blue vs. the corning red for the inner and outer pixels,
+//   respectively. The two populations are clearly visible for the inner pixels, 
+//   while for the outer ones, there is only one population with a bigger spread.
+//   The blue line marks the distinction of the two populations as used in 
+//   MCalibrationChargeCalc.
+//
+//Begin_Html
+/*
+<img src="images/Cornings.gif">
+*/
+//End_Html
+//
+// See also: MCalibrationQECam, MCalibrationQEPix, MCalibrationChargeCalc
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationQECamMagic.h"
+#include "MCalibrationQECam.h"
+
+ClassImp(MCalibrationQECamMagic);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationQECamMagic::MCalibrationQECamMagic(const char *name, const char *title)
+    : MCalibrationQECam(name,title)
+{
+  
+  CreateCorningReds();
+  CreateCorningBlues();
+
+}
+
+void MCalibrationQECamMagic::CreateCorningReds()
+{
+  
+  Double_t creds[577];
+
+  creds[0]   = -1.;
+  creds[1]   = 1.6;
+  creds[2]   = 8.7;
+  creds[3]   = 6.8;
+  creds[4]   = 10.3;
+  creds[5]   = 8.7;
+  creds[6]   = -1.;
+  creds[7]   = 1.3;
+  creds[8]   = 0.4;
+  creds[9]   = 7.7 ;
+  creds[10]  = 9.8;
+  creds[11]  = 5.9;
+  creds[12]  = 7.4;
+  creds[13]  = 7.4;
+  creds[14]  = 7.0;
+  creds[15]  = 7.2;
+  creds[16]  = 6.8;
+  creds[17]  = 6.9;
+  creds[18]  = 6.6;
+  creds[19]  = 1.8;
+  creds[20]  = 4.9;
+  creds[21]  = 7.1;
+  creds[22]  = 7.7;
+  creds[23]  = 8.9;
+  creds[24]  = 11.9;
+  creds[25]  = 1.6;
+  creds[26]  = 9.3;
+  creds[27]  = 5.8;
+  creds[28]  = 9.0;
+  creds[29]  = 6.5;
+  creds[30]  = 6.1;
+  creds[31]  = 8.1;
+  creds[32]  = 6.7;
+  creds[33]  = 7.0;
+  creds[34]  = 7.1;
+  creds[35]  = 7.8;
+  creds[36]  = 6.9;
+  creds[37]  = 0.9;
+  creds[38]  = 3.3;
+  creds[39]  = 7.1;
+  creds[40]  = 5.8;
+  creds[41]  = 4.4;
+  creds[42]  = 8.1;
+  creds[43]  = 6.0;
+  creds[44]  = 6.3;
+  creds[45]  = 6.0;
+  creds[46]  = 8.0;
+  creds[47]  = 0.6;
+  creds[48]  = 7.2;
+  creds[49]  = 5.6;
+  creds[50]  = 7.3;
+  creds[51]  = 8.0;
+  creds[52]  = 9.1;
+  creds[53]  = 1.4;
+  creds[54]  = 6.9;
+  creds[55]  = 9.1;
+  creds[56]  = 6.4;
+  creds[57]  = 6.1;
+  creds[58]  = 6.2;
+  creds[59]  = 7.7;
+  creds[60]  = 5.1;
+  creds[61]  = 7.9;
+  creds[62]  = 6.9;
+  creds[63]  = 3.3;
+  creds[64]  = 3.7;
+  creds[65]  = 5.8;
+  creds[66]  = 8.0;
+  creds[67]  = 7.3;
+  creds[68]  = 7.3;
+  creds[69]  = 9.1;
+  creds[70]  = 4.0;
+  creds[71]  = 8.2;
+  creds[72]  = 8.7;
+  creds[73]  = 9.1;
+  creds[74]  = 8.2;
+  creds[75]  = 9.0;
+  creds[76]  = 7.8;
+  creds[77]  = 7.5;
+  creds[78]  = 1.3;
+  creds[79]  = 6.9;
+  creds[80]  = 8.7;
+  creds[81]  = 7.6;
+  creds[82]  = 5.6;
+  creds[83]  = 10.4;
+  creds[84]  = 6.1;
+  creds[85]  = 0.9;
+  creds[86]  = 7.7;
+  creds[87]  = 7.4;
+  creds[88]  = 6.9;
+  creds[89]  = 7.0;
+  creds[90]  = 3.3;
+  creds[91]  = 7.1;
+  creds[92]  = 5.8;
+  creds[93]  = 7.2;
+  creds[94]  = 5.4;
+  creds[95]  = 7.4;
+  creds[96]  = 6.6;
+  creds[97]  = 0.0;
+  creds[98]  = 6.9;
+  creds[99]  = 7.3;
+  creds[100] = 8.7;
+  creds[101] = 6.5;
+  creds[102] = 5.8;
+  creds[103] = 6.1;
+  creds[104] = 6.6;
+  creds[105] = 8.7;
+  creds[106] = 6.8;
+  creds[107] = 7.0;
+  creds[108] = 7.4;
+  creds[109] = 7.1;
+  creds[110] = 8.8;
+  creds[111] = 7.0;
+  creds[112] = 8.3;
+  creds[113] = 3.5;
+  creds[114] = 7.4;
+  creds[115] = 8.7;
+  creds[116] = 7.6;
+  creds[117] = 7.6;
+  creds[118] = 6.6;
+  creds[119] = 5.9;
+  creds[120] = 6.8;
+  creds[121] = 0.4;
+  creds[122] = 7.5;
+  creds[123] = 5.7;
+  creds[124] = 1.6;
+  creds[125] = 6.2;
+  creds[126] = 7.4;
+  creds[127] = 7.3;
+  creds[128] = 8.5;
+  creds[129] = 6.9;
+  creds[130] = 7.3;
+  creds[131] = 6.8;
+  creds[132] = 6.6;
+  creds[133] = 6.5;
+  creds[134] = 5.7;
+  creds[135] = 5.8;
+  creds[136] = 6.2;
+  creds[137] = 5.8;
+  creds[138] = 6.1;
+  creds[139] = 7.2;
+  creds[140] = 6.0;
+  creds[141] = 7.7;
+  creds[142] = 6.7;
+  creds[143] = 4.3;
+  creds[144] = 7.2;
+  creds[145] = 7.0;
+  creds[146] = 7.4;
+  creds[147] = 5.4;
+  creds[148] = 6.5;
+  creds[149] = 5.9;
+  creds[150] = 5.5;
+  creds[151] = 7.0;
+  creds[152] = 7.0;
+  creds[153] = 6.5;
+  creds[154] = 5.6;
+  creds[155] = 5.6;
+  creds[156] = 7.8;
+  creds[157] = 7.2;
+  creds[158] = 5.7;
+  creds[159] = 5.9;
+  creds[160] = 5.9;
+  creds[161] = 5.8;
+  creds[162] = 1.2;
+  creds[163] = 7.9;
+  creds[164] = 7.7;
+  creds[165] = 9.5;
+  creds[166] = 6.4;
+  creds[167] = 6.6;
+  creds[168] = 7.1;
+  creds[169] = 6.3;
+  creds[170] = 7.4;
+  creds[171] = 4.0;
+  creds[172] = 6.2;
+  creds[173] = 6.4;
+  creds[174] = 3.8;
+  creds[175] = 7.5;
+  creds[176] = 8.0;
+  creds[177] = 7.0;
+  creds[178] = 6.0;
+  creds[179] = 6.5;
+  creds[180] = 7.1;
+  creds[181] = 4.7;
+  creds[182] = 9.7;
+  creds[183] = 6.1;
+  creds[184] = 6.7;
+  creds[185] = 6.2;
+  creds[186] = 6.7;
+  creds[187] = 6.1;
+  creds[188] = 4.9;
+  creds[189] = 5.8;
+  creds[190] = 6.4;
+  creds[191] = 6.5;
+  creds[192] = 7.1;
+  creds[193] = 8.1;
+  creds[194] = 5.5;
+  creds[195] = 7.1;
+  creds[196] = 6.5;
+  creds[197] = 6.7;
+  creds[198] = 7.0;
+  creds[199] = 7.5;
+  creds[200] = 6.5;
+  creds[201] = 6.5;
+  creds[202] = 6.8;
+  creds[203] = 5.6;
+  creds[204] = 6.9;
+  creds[205] = 6.6;
+  creds[206] = 7.4;
+  creds[207] = 6.1;
+  creds[208] = 6.8;
+  creds[209] = 8.1;
+  creds[210] = 7.6;
+  creds[211] = 6.2;
+  creds[212] = 6.9;
+  creds[213] = 5.8;
+  creds[214] = 7.0;
+  creds[215] = 5.7;
+  creds[216] = 4.1;
+  creds[217] = 2.4;
+  creds[218] = 1.1;
+  creds[219] = 6.5;
+  creds[220] = 5.9;
+  creds[221] = 6.4;
+  creds[222] = 7.3;
+  creds[223] = 7.5;
+  creds[224] = 1.2;
+  creds[225] = 4.2;
+  creds[226] = 6.4;
+  creds[227] = 6.9;
+  creds[228] = 7.1;
+  creds[229] = 4.4;
+  creds[230] = 7.4;
+  creds[231] = 6.9;
+  creds[232] = 5.3;
+  creds[233] = 2.0;
+  creds[234] = 6.3;
+  creds[235] = 7.6;
+  creds[236] = 8.2;
+  creds[237] = 9.1;
+  creds[238] = 6.3;
+  creds[239] = 5.9;
+  creds[240] = 7.2;
+  creds[241] = 5.4;
+  creds[242] = 9.1;
+  creds[243] = 5.3;
+  creds[244] = 5.0;
+  creds[245] = 7.2;
+  creds[246] = 4.5;
+  creds[247] = 5.3;
+  creds[248] = 9.0;
+  creds[249] = 5.9;
+  creds[250] = 9.1;
+  creds[251] = 7.4;
+  creds[252] = 4.8;
+  creds[253] = 5.5;
+  creds[254] = 3.9;
+  creds[255] = 7.1;
+  creds[256] = 6.3;
+  creds[257] = 4.3;
+  creds[258] = 6.2;
+  creds[259] = 5.1;
+  creds[260] = -1.;
+  creds[261] = 1.2;
+  creds[262] = 7.8;
+  creds[263] = 0.4;
+  creds[264] = 5.7;
+  creds[265] = 4.2;
+  creds[266] = 7.8;
+  creds[267] = 8.6;
+  creds[268] = 4.2;
+  creds[269] = 6.7;
+  creds[270] = 6.7;
+  creds[271] = 5.2;
+  creds[272] = 7.1;
+  creds[273] = 0.2;
+  creds[274] = 1.2;
+  creds[275] = 6.0;
+  creds[276] = 4.1;
+  creds[277] = 0.9;
+  creds[278] = 1.7;
+  creds[279] = 6.8;
+  creds[280] = 3.8;
+  creds[281] = 1.8;
+  creds[282] = 6.3;
+  creds[283] = 4.1;
+  creds[284] = 2.4;
+  creds[285] = 7.2;
+  creds[286] = 2.2;
+  creds[287] = 6.6;
+  creds[288] = 6.1;
+  creds[289] = 2.6;
+  creds[290] = 5.2;
+  creds[291] = 1.4;
+  creds[292] = 4.0;
+  creds[293] = 2.6;
+  creds[294] = 3.0;
+  creds[295] = 6.6;
+  creds[296] = 7.6;
+  creds[297] = 5.6;
+  creds[298] = 7.3;
+  creds[299] = 7.3;
+  creds[300] = 7.8;
+  creds[301] = 1.5;
+  creds[302] = 3.3;
+  creds[303] = 0.6;
+  creds[304] = 5.9;
+  creds[305] = 7.0;
+  creds[306] = 6.3;
+  creds[307] = 3.9;
+  creds[308] = 2.4;
+  creds[309] = 5.8;
+  creds[310] = 7.4;
+  creds[311] = 1.5;
+  creds[312] = 4.1;
+  creds[313] = 4.5;
+  creds[314] = 4.5;
+  creds[315] = 6.6;
+  creds[316] = 6.0;
+  creds[317] = 6.0;
+  creds[318] = 8.8;
+  creds[319] = 5.6;
+  creds[320] = 4.1;
+  creds[321] = 4.6;
+  creds[322] = 1.4;
+  creds[323] = 2.1;
+  creds[324] = 5.5;
+  creds[325] = 3.4;
+  creds[326] = 6.0;
+  creds[327] = 3.6;
+  creds[328] = 7.3;
+  creds[329] = 6.4;
+  creds[330] = 7.1;
+  creds[331] = 8.1;
+  creds[332] = 1.1;
+  creds[333] = 2.8;
+  creds[334] = 1.3;
+  creds[335] = 1.6;
+  creds[336] = 1.6;
+  creds[337] = 1.6;
+  creds[338] = 1.1;
+  creds[339] = 1.3;
+  creds[340] = 1.3;
+  creds[341] = 1.2;
+  creds[342] = 0.6;
+  creds[343] = 8.0;
+  creds[344] = 1.9;
+  creds[345] = -1.;
+  creds[346] = 2.4;
+  creds[347] = 1.4;
+  creds[348] = 6.1;
+  creds[349] = 1.9;
+  creds[350] = 1.6;
+  creds[351] = 1.5;
+  creds[352] = 1.0;
+  creds[353] = 1.4;
+  creds[354] = 1.3;
+  creds[355] = 1.1;
+  creds[356] = 1.1;
+  creds[357] = 1.4;
+  creds[358] = 1.8;
+  creds[359] = 1.1;
+  creds[360] = 1.6;
+  creds[361] = 1.4;
+  creds[362] = 1.4;
+  creds[363] = 7.9;
+  creds[364] = 2.0;
+  creds[365] = 1.4;
+  creds[366] = 7.6;
+  creds[367] = 1.1;
+  creds[368] = 1.4;
+  creds[369] = 1.3;
+  creds[370] = 0.8;
+  creds[371] = 3.4;
+  creds[372] = 0.9;
+  creds[373] = 6.2;
+  creds[374] = 0.4;
+  creds[375] = 1.1;
+  creds[376] = 1.4;
+  creds[377] = 1.2;
+  creds[378] = 1.4;
+  creds[379] = 2.2;
+  creds[380] = 2.0;
+  creds[381] = 1.6;
+  creds[382] = 2.2;
+  creds[383] = 8.5;
+  creds[384] = 1.9;
+  creds[385] = 1.0;
+  creds[386] = 1.8;
+  creds[387] = 5.8;
+  creds[388] = 1.1;
+  creds[389] = 2.4;
+  creds[390] = 2.4;
+  creds[391] = 4.6;
+  creds[392] = 1.2;
+  creds[393] = -1.;
+  creds[394] = 1.2;
+  creds[395] = 0.6;
+  creds[396] = 1.5;
+  creds[397] = 1.0;
+  creds[398] = 6.8;
+  creds[399] = 17.4;
+  creds[400] = 18.6;
+  creds[401] = 2.3;
+  creds[402] = 7.7;
+  creds[403] = 2.2;
+  creds[404] = 4.6;
+  creds[405] = 4.0;
+  creds[406] = 11.7;
+  creds[407] = 5.0;
+  creds[408] = 10.6;
+  creds[409] = 17.7;
+  creds[410] = 6.9;
+  creds[411] = 6.3;
+  creds[412] = 6.7;
+  creds[413] = 1.9;
+  creds[414] = 15.8;
+  creds[415] = 4.9;
+  creds[416] = 24.7;
+  creds[417] = 12.0;
+  creds[418] = 9.7;
+  creds[419] = 19.3;
+  creds[420] = 13.0;
+  creds[421] = 1.6;
+  creds[422] = 4.4;
+  creds[423] = 2.8;
+  creds[424] = 16.5;
+  creds[425] = 6.1;
+  creds[426] = 8.1;
+  creds[427] = 1.7;
+  creds[428] = 6.2;
+  creds[429] = 8.1;
+  creds[430] = 14.5;
+  creds[431] = 2.5;
+  creds[432] = 12.9;
+  creds[433] = 7.4;
+  creds[434] = 7.9;
+  creds[435] = 5.1;
+  creds[436] = 6.5;
+  creds[437] = 12.3;
+  creds[438] = 8.4;
+  creds[439] = 2.2;
+  creds[440] = 5.0;
+  creds[441] = 2.9;
+  creds[442] = 10.4;
+  creds[443] = 13.1;
+  creds[444] = 5.6;
+  creds[445] = 8.0;
+  creds[446] = 5.9;
+  creds[447] = 8.1;
+  creds[448] = 6.8;
+  creds[449] = 6.9;
+  creds[450] = 12.3;
+  creds[451] = 9.1;
+  creds[452] = 2.7;
+  creds[453] = 2.7;
+  creds[454] = 4.2;
+  creds[455] = 4.9;
+  creds[456] = 10.9;
+  creds[457] = 7.2;
+  creds[458] = 18.3;
+  creds[459] = 6.1;
+  creds[460] = 7.7;
+  creds[461] = 2.7;
+  creds[462] = 17.6;
+  creds[463] = 3.8;
+  creds[464] = 12.6;
+  creds[465] = 9.3;
+  creds[466] = 9.2;
+  creds[467] = 7.0;
+  creds[468] = 7.9;
+  creds[469] = 14.6;
+  creds[470] = 13.6;
+  creds[471] = 0.9;
+  creds[472] = 8.1;
+  creds[473] = 9.3;
+  creds[474] = 3.0;
+  creds[475] = 24.7;
+  creds[476] = 19.5;
+  creds[477] = 6.2;
+  creds[478] = 6.9;
+  creds[479] = 11.7;
+  creds[480] = 11.3;
+  creds[481] = 7.3;
+  creds[482] = 12.8;
+  creds[483] = 11.3;
+  creds[484] = 3.9;
+  creds[485] = 4.4;
+  creds[486] = 5.9;
+  creds[487] = 7.3;
+  creds[488] = 7.1;
+  creds[489] = 1.4;
+  creds[490] = 12.6;
+  creds[491] = 9.6;
+  creds[492] = 10.7;
+  creds[493] = 13.5;
+  creds[494] = 1.9;
+  creds[495] = 9.8;
+  creds[496] = 5.6;
+  creds[497] = 6.2;
+  creds[498] = 14.0;
+  creds[499] = 5.4;
+  creds[500] = 8.4;
+  creds[501] = 16.2;
+  creds[502] = 15.1;
+  creds[503] = 9.7;
+  creds[504] = 13.0;
+  creds[505] = 12.3;
+  creds[506] = 7.4;
+  creds[507] = 3.7;
+  creds[508] = 7.2;
+  creds[509] = 9.6;
+  creds[510] = 21.1;
+  creds[511] = 2.3;
+  creds[512] = 13.5;
+  creds[513] = 14.3;
+  creds[514] = 3.5;
+  creds[515] = 6.7;
+  creds[516] = 7.8;
+  creds[517] = 6.2;
+  creds[518] = 8.3;
+  creds[519] = 6.3;
+  creds[520] = 5.8;
+  creds[521] = 4.6;
+  creds[522] = 1.8;
+  creds[523] = 6.2;
+  creds[524] = 11.;
+  creds[525] = 1.8;
+  creds[526] = 5.4;
+  creds[527] = 8.5;
+  creds[528] = 12.9;
+  creds[529] = 4.3;
+  creds[530] = 15.5;
+  creds[531] = 1.7;
+  creds[532] = 3.2;
+  creds[533] = 9.9;
+  creds[534] = 4.8;
+  creds[535] = 8.0;
+  creds[536] = 9.9;
+  creds[537] = 4.4;
+  creds[538] = 5.6;
+  creds[539] = 13.5;
+  creds[540] = 11.7;
+  creds[541] = 18.7;
+  creds[542] = 6.5;
+  creds[543] = 11.7;
+  creds[544] = 12.7;
+  creds[545] = 4.2;
+  creds[546] = 7.3;
+  creds[547] = 14.9;
+  creds[548] = 6.8;
+  creds[549] = 4.8;
+  creds[550] = 7.1;
+  creds[551] = 6.2;
+  creds[552] = 2.3;
+  creds[553] = 16.9;
+  creds[554] = 6.8;
+  creds[555] = 14.6;
+  creds[556] = 20.5;
+  creds[557] = 7.0;
+  creds[558] = 5.7;
+  creds[559] = 6.6;
+  creds[560] = 13.5;
+  creds[561] = 11.0;
+  creds[562] = 4.2;
+  creds[563] = 10.6;
+  creds[564] = 6.5;
+  creds[565] = 6.5;
+  creds[566] = 1.7;
+  creds[567] = 8.2;
+  creds[568] = 5.1;
+  creds[569] = 5.6;
+  creds[570] = 9.1;
+  creds[571] = 0.6;
+  creds[572] = 19.1;
+  creds[573] = 5.7;
+  creds[574] = 6.0;
+  creds[575] = 3.9;
+  creds[576] = 2.6;
+
+  fCorningReds.Set(577,creds);
+}
+
+void MCalibrationQECamMagic::CreateCorningBlues()
+{
+ 
+  Double_t cblues[577];
+
+  cblues[0]   = -1.;
+  cblues[1]   = 12.0;
+  cblues[2]   = 12.2;
+  cblues[3]   = 12.6;
+  cblues[4]   = 12.7;
+  cblues[5]   = 12.8;
+  cblues[6]   = -1.;
+  cblues[7]   = 10.8;
+  cblues[8]   = 9.0;
+  cblues[9]   = 12.2;
+  cblues[10]  = 12.3;
+  cblues[11]  = 11.7;
+  cblues[12]  = 12.0;
+  cblues[13]  = 12.1;
+  cblues[14]  = 12.0;
+  cblues[15]  = 12.6;
+  cblues[16]  = 12.2;
+  cblues[17]  = 12.6;
+  cblues[18]  = 12.6;
+  cblues[19]  = 11.5;
+  cblues[20]  = 11.1;
+  cblues[21]  = 11.2;
+  cblues[22]  = 12.1;
+  cblues[23]  = 12.8;
+  cblues[24]  = 12.7;
+  cblues[25]  = 12.8;
+  cblues[26]  = 13.0;
+  cblues[27]  = 13.0;
+  cblues[28]  = 12.0;
+  cblues[29]  = 12.4;
+  cblues[30]  = 12.0;
+  cblues[31]  = 12.1;
+  cblues[32]  = 12.0;
+  cblues[33]  = 12.2;
+  cblues[34]  = 12.0;
+  cblues[35]  = 12.5;
+  cblues[36]  = 12.4;
+  cblues[37]  = 10.3;
+  cblues[38]  = 10.8;
+  cblues[39]  = 11.4;
+  cblues[40]  = 11.7;
+  cblues[41]  = 12.1;
+  cblues[42]  = 12.0;
+  cblues[43]  = 12.4;
+  cblues[44]  = 13.0;
+  cblues[45]  = 12.7;
+  cblues[46]  = 12.8;
+  cblues[47]  = 10.5;
+  cblues[48]  = 12.1;
+  cblues[49]  = 12.1;
+  cblues[50]  = 12.4;
+  cblues[51]  = 12.3;
+  cblues[52]  = 12.4;
+  cblues[53]  = 11.7;
+  cblues[54]  = 12.8;
+  cblues[55]  = 12.0;
+  cblues[56]  = 12.5;
+  cblues[57]  = 12.2;
+  cblues[58]  = 12.3;
+  cblues[59]  = 12.3;
+  cblues[60]  = 12.6;
+  cblues[61]  = 11.6;
+  cblues[62]  = 11.9;
+  cblues[63]  = 11.8;
+  cblues[64]  = 10.7;
+  cblues[65]  = 10.9;
+  cblues[66]  = 12.1;
+  cblues[67]  = 12.5;
+  cblues[68]  = 12.4;
+  cblues[69]  = 12.1;
+  cblues[70]  = 12.2;
+  cblues[71]  = 13.1;
+  cblues[72]  = 12.5;
+  cblues[73]  = 12.4;
+  cblues[74]  = 12.6;
+  cblues[75]  = 12.5;
+  cblues[76]  = 12.1;
+  cblues[77]  = 12.5;
+  cblues[78]  = 12.3;
+  cblues[79]  = 12.0;
+  cblues[80]  = 12.4;
+  cblues[81]  = 12.4;
+  cblues[82]  = 12.0;
+  cblues[83]  = 12.3;
+  cblues[84]  = 12.1;
+  cblues[85]  = 11.3;
+  cblues[86]  = 12.0;
+  cblues[87]  = 12.0;
+  cblues[88]  = 12.4;
+  cblues[89]  = 12.3;
+  cblues[90]  = 12.0;
+  cblues[91]  = 11.4;
+  cblues[92]  = 11.7;
+  cblues[93]  = 11.9;
+  cblues[94]  = 11.4;
+  cblues[95]  = 11.1;
+  cblues[96]  = 11.9;
+  cblues[97]  = 9.2;
+  cblues[98]  = 12.4;
+  cblues[99]  = 11.5;
+  cblues[100] = 12.3;
+  cblues[101] = 11.0;
+  cblues[102] = 12.0;
+  cblues[103] = 11.8;
+  cblues[104] = 12.5;
+  cblues[105] = 11.6;
+  cblues[106] = 12.3;
+  cblues[107] = 11.2;
+  cblues[108] = 12.4;
+  cblues[109] = 11.5;
+  cblues[110] = 12.1;
+  cblues[111] = 11.0;
+  cblues[112] = 12.1;
+  cblues[113] = 11.6;
+  cblues[114] = 12.0;
+  cblues[115] = 11.4;
+  cblues[116] = 12.0;
+  cblues[117] = 11.7;
+  cblues[118] = 12.6;
+  cblues[119] = 11.4;
+  cblues[120] = 12.3;
+  cblues[121] = 10.9;
+  cblues[122] = 12.1;
+  cblues[123] = 11.8;
+  cblues[124] = 12.2;
+  cblues[125] = 11.5;
+  cblues[126] = 12.1;
+  cblues[127] = 11.7;
+  cblues[128] = 11.4;
+  cblues[129] = 11.5;
+  cblues[130] = 11.2;
+  cblues[131] = 11.8;
+  cblues[132] = 11.3;
+  cblues[133] = 11.5;
+  cblues[134] = 11.1;
+  cblues[135] = 11.7;
+  cblues[136] = 11.2;
+  cblues[137] = 11.6;
+  cblues[138] = 11.8;
+  cblues[139] = 11.4;
+  cblues[140] = 11.6;
+  cblues[141] = 11.1;
+  cblues[142] = 11.9;
+  cblues[143] = 11.4;
+  cblues[144] = 11.5;
+  cblues[145] = 11.6;
+  cblues[146] = 11.9;
+  cblues[147] = 11.0;
+  cblues[148] = 11.6;
+  cblues[149] = 11.9;
+  cblues[150] = 11.5;
+  cblues[151] = 11.8;
+  cblues[152] = 11.4;
+  cblues[153] = 11.9;
+  cblues[154] = 11.0;
+  cblues[155] = 11.7;
+  cblues[156] = 11.9;
+  cblues[157] = -1.;
+  cblues[158] = 11.4;
+  cblues[159] = 11.0;
+  cblues[160] = 11.9;
+  cblues[161] = 11.6;
+  cblues[162] = 11.4;
+  cblues[163] = 11.6;
+  cblues[164] = 11.0;
+  cblues[165] = 11.6;
+  cblues[166] = 11.4;
+  cblues[167] = 11.5;
+  cblues[168] = 11.9;
+  cblues[169] = 10.9;
+  cblues[170] = 10.8;
+  cblues[171] = 10.3;
+  cblues[172] = 10.9;
+  cblues[173] = 11.4;
+  cblues[174] = 11.5;
+  cblues[175] = 11.7;
+  cblues[176] = 11.9;
+  cblues[177] = 11.6;
+  cblues[178] = 10.4;
+  cblues[179] = 11.6;
+  cblues[180] = 11.5;
+  cblues[181] = 11.7;
+  cblues[182] = 11.6;
+  cblues[183] = 11.7;
+  cblues[184] = 11.5;
+  cblues[185] = 11.7;
+  cblues[186] = 11.6;
+  cblues[187] = 11.3;
+  cblues[188] = 11.3;
+  cblues[189] = 11.2;
+  cblues[190] = 11.5;
+  cblues[191] = 11.7;
+  cblues[192] = 11.8;
+  cblues[193] = 11.2;
+  cblues[194] = 11.9;
+  cblues[195] = 11.3;
+  cblues[196] = 11.2;
+  cblues[197] = 11.0;
+  cblues[198] = 11.4;
+  cblues[199] = 11.5;
+  cblues[200] = 11.5;
+  cblues[201] = 11.7;
+  cblues[202] = 11.6;
+  cblues[203] = 11.7;
+  cblues[204] = 11.4;
+  cblues[205] = 11.6;
+  cblues[206] = 11.3;
+  cblues[207] = 11.5;
+  cblues[208] = 11.8;
+  cblues[209] = 11.6;
+  cblues[210] = 11.9;
+  cblues[211] = 11.2;
+  cblues[212] = 11.1;
+  cblues[213] = 11.4;
+  cblues[214] = 11.6;
+  cblues[215] = 11.3;
+  cblues[216] = 11.5;
+  cblues[217] = 10.1;
+  cblues[218] = 9.5;
+  cblues[219] = 10.0;
+  cblues[220] = 10.8;
+  cblues[221] = 10.4;
+  cblues[222] = 10.4;
+  cblues[223] = 10.3;
+  cblues[224] = 11.8;
+  cblues[225] = 10.4;
+  cblues[226] = 11.5;
+  cblues[227] = 10.3;
+  cblues[228] = 10.3;
+  cblues[229] = 10.6;
+  cblues[230] = 10.8;
+  cblues[231] = 10.6;
+  cblues[232] = 10.5;
+  cblues[233] = 10.5;
+  cblues[234] = 11.3;
+  cblues[235] = 11.7;
+  cblues[236] = 10.9;
+  cblues[237] = 10.6;
+  cblues[238] = 10.8;
+  cblues[239] = 10.7;
+  cblues[240] = 10.9;
+  cblues[241] = 10.5;
+  cblues[242] = 10.8;
+  cblues[243] = 11.1;
+  cblues[244] = 11.2;
+  cblues[245] = 10.6;
+  cblues[246] = 10.6;
+  cblues[247] = 10.9;
+  cblues[248] = 10.6;
+  cblues[249] = 10.3;
+  cblues[250] = 10.6;
+  cblues[251] = 10.7;
+  cblues[252] = 11.5;
+  cblues[253] = 11.8;
+  cblues[254] = 10.8;
+  cblues[255] = 10.4;
+  cblues[256] = 10.6;
+  cblues[257] = 10.6;
+  cblues[258] = 10.5;
+  cblues[259] = 10.3;
+  cblues[260] = -1.;
+  cblues[261] = 11.1;
+  cblues[262] = 10.7;
+  cblues[263] = 10.6;
+  cblues[264] = 10.5;
+  cblues[265] = 10.7;
+  cblues[266] = 10.3;
+  cblues[267] = 10.2;
+  cblues[268] = 10.4;
+  cblues[269] = 10.2;
+  cblues[270] = 11.4;
+  cblues[271] = 10.9;
+  cblues[272] = 11.5;
+  cblues[273] = 8.9;
+  cblues[274] = 8.3;
+  cblues[275] = 8.9;
+  cblues[276] = 13.7;
+  cblues[277] = 8.4;
+  cblues[278] = 9.6;
+  cblues[279] = 10.0;
+  cblues[280] = 9.0;
+  cblues[281] = 12.2;
+  cblues[282] = 9.9;
+  cblues[283] = 9.0;
+  cblues[284] = 10.0;
+  cblues[285] = 10.1;
+  cblues[286] = 9.5;
+  cblues[287] = 10.0;
+  cblues[288] = 10.8;
+  cblues[289] = 10.8;
+  cblues[290] = 10.3;
+  cblues[291] = 11.6;
+  cblues[292] = 9.8;
+  cblues[293] = 10.1;
+  cblues[294] = 9.8;
+  cblues[295] = 9.6;
+  cblues[296] = 9.2;
+  cblues[297] = 9.7;
+  cblues[298] = 10.2;
+  cblues[299] = 10.2;
+  cblues[300] = 10.9;
+  cblues[301] = 12.1;
+  cblues[302] = 10.0;
+  cblues[303] = 9.8;
+  cblues[304] = 9.6;
+  cblues[305] = 10.9;
+  cblues[306] = 10.3;
+  cblues[307] = 10.2;
+  cblues[308] = 9.4;
+  cblues[309] = 9.8;
+  cblues[310] = 10.8;
+  cblues[311] = 12.3;
+  cblues[312] = 9.6;
+  cblues[313] = 9.5;
+  cblues[314] = 9.0;
+  cblues[315] = 10.3;
+  cblues[316] = 10.4;
+  cblues[317] = 10.9;
+  cblues[318] = 9.9;
+  cblues[319] = 10.0;
+  cblues[320] = 10.1;
+  cblues[321] = 8.1;
+  cblues[322] = 12.1;
+  cblues[323] = 10.1;
+  cblues[324] = 10.1;
+  cblues[325] = 9.3;
+  cblues[326] = 10.1;
+  cblues[327] = 9.4;
+  cblues[328] = 9.6;
+  cblues[329] = 10.6;
+  cblues[330] = 10.7;
+  cblues[331] = 10.2;
+  cblues[332] = 11.5;
+  cblues[333] = 11.9;
+  cblues[334] = 11.9;
+  cblues[335] = 11.8;
+  cblues[336] = 13.1;
+  cblues[337] = 10.9;
+  cblues[338] = 10.4;
+  cblues[339] = 11.7;
+  cblues[340] = 11.5;
+  cblues[341] = 10.6;
+  cblues[342] = 9.5;
+  cblues[343] = 11.5;
+  cblues[344] = 11.9;
+  cblues[345] = -1.;
+  cblues[346] = 10.3;
+  cblues[347] = 8.0;
+  cblues[348] = 11.0;
+  cblues[349] = 12.1;
+  cblues[350] = 12.0;
+  cblues[351] = 12.1;
+  cblues[352] = 11.2;
+  cblues[353] = 11.2;
+  cblues[354] = 12.4;
+  cblues[355] = 11.0;
+  cblues[356] = 11.6;
+  cblues[357] = 11.4;
+  cblues[358] = 10.6;
+  cblues[359] = 11.0;
+  cblues[360] = 11.8;
+  cblues[361] = 12.4;
+  cblues[362] = 12.4;
+  cblues[363] = 12.2;
+  cblues[364] = 9.8;
+  cblues[365] = 11.7;
+  cblues[366] = 9.8;
+  cblues[367] = 11.4;
+  cblues[368] = 12.0;
+  cblues[369] = 11.7;
+  cblues[370] = 10.9;
+  cblues[371] = 11.2;
+  cblues[372] = 10.6;
+  cblues[373] = 10.0;
+  cblues[374] = 10.0;
+  cblues[375] = 10.6;
+  cblues[376] = 11.2;
+  cblues[377] = 12.0;
+  cblues[378] = 11.3;
+  cblues[379] = 12.5;
+  cblues[380] = 12.0;
+  cblues[381] = 11.4;
+  cblues[382] = 12.0;
+  cblues[383] = 13.6;
+  cblues[384] = 12.6;
+  cblues[385] = 10.9;
+  cblues[386] = 12.0;
+  cblues[387] = 10.0;
+  cblues[388] = 11.4;
+  cblues[389] = 11.6;
+  cblues[390] = 10.3;
+  cblues[391] = 8.5;
+  cblues[392] = 11.7;
+  cblues[393] = -1.;
+  cblues[394] = 12.1;
+  cblues[395] = 10.5;
+  cblues[396] = 12.1;
+  cblues[397] = 9.5;
+  cblues[398] = 9.9;
+  cblues[399] = 12.9;
+  cblues[400] = 12.4;
+  cblues[401] = 11.3;
+  cblues[402] = 10.8;
+  cblues[403] = 11.2;
+  cblues[404] = 9.2;
+  cblues[405] = 10.7;
+  cblues[406] = 13.6;
+  cblues[407] = 11.6;
+  cblues[408] = 11.2;
+  cblues[409] = 11.1;
+  cblues[410] = 11.6;
+  cblues[411] = 10.4;
+  cblues[412] = 12.0;
+  cblues[413] = 12.0;
+  cblues[414] = 10.6;
+  cblues[415] = 11.2;
+  cblues[416] = 11.6;
+  cblues[417] = 10.2;
+  cblues[418] = 11.3;
+  cblues[419] = 9.1;
+  cblues[420] = 11.6;
+  cblues[421] = 11.0;
+  cblues[422] = 10.6;
+  cblues[423] = 12.5;
+  cblues[424] = 12.0;
+  cblues[425] = 11.1;
+  cblues[426] = 11.5;
+  cblues[427] = 11.2;
+  cblues[428] = 10.2;
+  cblues[429] = 11.8;
+  cblues[430] = 10.8;
+  cblues[431] = 11.1;
+  cblues[432] = 11.0;
+  cblues[433] = 11.5;
+  cblues[434] = 11.9;
+  cblues[435] = 9.5;
+  cblues[436] = 11.3;
+  cblues[437] = 11.2;
+  cblues[438] = 11.4;
+  cblues[439] = 10.1;
+  cblues[440] = 11.0;
+  cblues[441] = 10.8;
+  cblues[442] = 9.3;
+  cblues[443] = 12.6;
+  cblues[444] = 9.9;
+  cblues[445] = 9.8;
+  cblues[446] = 10.4;
+  cblues[447] = 11.3;
+  cblues[448] = 12.0;
+  cblues[449] = 11.0;
+  cblues[450] = 11.7;
+  cblues[451] = 12.0;
+  cblues[452] = 9.1;
+  cblues[453] = 11.2;
+  cblues[454] = 10.6;
+  cblues[455] = 12.3;
+  cblues[456] = 10.9;
+  cblues[457] = 9.7;
+  cblues[458] = 11.2;
+  cblues[459] = 12.2;
+  cblues[460] = 12.5;
+  cblues[461] = 9.0;
+  cblues[462] = 11.6;
+  cblues[463] = 11.3;
+  cblues[464] = 10.8;
+  cblues[465] = 10.7;
+  cblues[466] = 12.1;
+  cblues[467] = 11.9;
+  cblues[468] = 12.2;
+  cblues[469] = 11.6;
+  cblues[470] = 11.5;
+  cblues[471] = 10.3;
+  cblues[472] = 11.8;
+  cblues[473] = 10.7;
+  cblues[474] = 10.4;
+  cblues[475] = 11.9;
+  cblues[476] = 11.2;
+  cblues[477] = 10.7;
+  cblues[478] = 10.4;
+  cblues[479] = 10.4;
+  cblues[480] = 11.3;
+  cblues[481] = 11.6;
+  cblues[482] = 10.1;
+  cblues[483] = 9.4;
+  cblues[484] = 12.3;
+  cblues[485] = 11.2;
+  cblues[486] = 9.6;
+  cblues[487] = 10.5;
+  cblues[488] = 11.7;
+  cblues[489] = 10.5;
+  cblues[490] = 11.5;
+  cblues[491] = 10.4;
+  cblues[492] = 12.1;
+  cblues[493] = 13.0;
+  cblues[494] = 10.9;
+  cblues[495] = 11.0;
+  cblues[496] = 11.0;
+  cblues[497] = 12.5;
+  cblues[498] = 12.3;
+  cblues[499] = 12.8;
+  cblues[500] = 12.2;
+  cblues[501] = 10.6;
+  cblues[502] = 11.6;
+  cblues[503] = 11.6;
+  cblues[504] = 11.6;
+  cblues[505] = 10.9;
+  cblues[506] = 11.9;
+  cblues[507] = 9.4;
+  cblues[508] = 12.1;
+  cblues[509] = 12.4;
+  cblues[510] = 11.6;
+  cblues[511] = 10.2;
+  cblues[512] = 11.4;
+  cblues[513] = 11.9;
+  cblues[514] = 9.6;
+  cblues[515] = 11.1;
+  cblues[516] = 12.3;
+  cblues[517] = 9.7;
+  cblues[518] = 12.4;
+  cblues[519] = 9.6;
+  cblues[520] = 10.6;
+  cblues[521] = 10.3;
+  cblues[522] = 11.1;
+  cblues[523] = 10.7;
+  cblues[524] = 13.3;
+  cblues[525] = 9.7;
+  cblues[526] = 10.8;
+  cblues[527] = 12.0;
+  cblues[528] = 12.3;
+  cblues[529] = 12.6;
+  cblues[530] = 11.9;
+  cblues[531] = 10.8;
+  cblues[532] = 10.2;
+  cblues[533] = 11.0;
+  cblues[534] = 10.8;
+  cblues[535] = 9.8;
+  cblues[536] = 11.6;
+  cblues[537] = 10.8;
+  cblues[538] = 9.9;
+  cblues[539] = 12.4;
+  cblues[540] = 10.4;
+  cblues[541] = 11.6;
+  cblues[542] = 11.1;
+  cblues[543] = 10.5;
+  cblues[544] = 11.1;
+  cblues[545] = 11.5;
+  cblues[546] = 11.6;
+  cblues[547] = 11.2;
+  cblues[548] = 9.7;
+  cblues[549] = 10.9;
+  cblues[550] = 11.7;
+  cblues[551] = 10.7;
+  cblues[552] = 10.2;
+  cblues[553] = 11.1;
+  cblues[554] = 10.2;
+  cblues[555] = 11.8;
+  cblues[556] = 12.2;
+  cblues[557] = 10.5;
+  cblues[558] = 11.2;
+  cblues[559] = 10.1;
+  cblues[560] = 12.3;
+  cblues[561] = 11.6;
+  cblues[562] = 9.9;
+  cblues[563] = 10.5;
+  cblues[564] = 11.3;
+  cblues[565] = 11.8;
+  cblues[566] = 10.7;
+  cblues[567] = 11.1;
+  cblues[568] = 11.8;
+  cblues[569] = 10.5;
+  cblues[570] = 11.8;
+  cblues[571] = 9.6;
+  cblues[572] = 11.1;
+  cblues[573] = 11.0;
+  cblues[574] = 11.8;
+  cblues[575] = 11.4;
+  cblues[576] = 10.2;
+
+  fCorningBlues.Set(577,cblues);
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationQECamMagic.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationQECamMagic.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationQECamMagic.h	(revision 17960)
@@ -0,0 +1,27 @@
+#ifndef MARS_MCalibrationQECamMagic
+#define MARS_MCalibrationQECamMagic
+
+#ifndef MARS_MCalibrationQECam
+#include "MCalibrationQECam.h"
+#endif
+
+class MCalibrationQECamMagic : public MCalibrationQECam
+{
+private:
+
+  void CreateCorningReds();
+  void CreateCorningBlues();
+
+public:
+
+  MCalibrationQECamMagic(const char *name=NULL, const char *title=NULL);
+
+  ClassDef(MCalibrationQECamMagic, 1) // Container Quantum Efficieny for MAGIC
+};
+
+#endif
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationQEPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationQEPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationQEPix.cc	(revision 17960)
@@ -0,0 +1,1374 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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(), GetQECascadesFFactor() or
+//     GetQECascadesPINDiode() returns then the normalization multiplied with an average QE
+//     folded into a cascades spectrum. This number should be dependent on zenith angle, but 
+//     this feature is not yet implemented, instead a fixed number gkDefaultAverageQE is used. 
+// 
+// The number gkDefaultAverageQE = 0.18 +- 0.02 can be obtained in the following way: 
+//
+// * Transmission probability Plexiglass: 0.92
+//
+// * Averaged QE coated PMTs: zenith     value
+//                              0.       0.237
+//                             20.       0.237
+//                             40.       0.236
+//                             60.       0.234
+// (from D.Paneque et al., NIM A 504, 2003, 109-115, see following figure with the 
+//  photon spectra at 2200 m altitude:)
+//
+//Begin_Html
+/*
+<img src="images/Photon_spectrum.png">
+*/
+//End_Html
+// 
+// * PMT photoelectron collection efficiency: 0.9
+// (from D.Paneque, email 14.2.2004)
+//
+// * Light guides efficiency: 0.94
+// (from D.Paneque, email 14.2.2004)
+// 
+// "Concerning the light guides effiency estimation... Daniel Ferenc 
+//  is preparing some work (simulations) to estimate it. Yet so far, he has 
+//  been busy with other stuff, and this work is still Unfinished.
+//
+//  The estimation I did comes from:
+//  1) Reflectivity of light guide walls is 85 % (aluminum)
+//  2) At ZERO degree light incidence, 37% of the light hits such walls 
+//    (0.15X37%= 5.6% of light lost)
+//  3) When increasing the light incidence angle, more and more light hits 
+//     the walls.
+//
+//  However, the loses due to larger amount of photons hitting the walls is more 
+//  or less counteracted by the fact that more and more photon trajectories cross 
+//  the PMT photocathode twice, increasing the effective sensitivity of the PMT.
+//
+//Begin_Html
+/*
+<img src="images/Normalized_Cherenkov_phe_spectrums_20deg_60deg_coatedPMT.png">
+*/
+//End_Html
+//
+// The plot shows the normalized spectrum of photo-electrons preceding from 
+// a typical spectrum of Cherenkov photons produced by an atmospheric shower. The 
+// green line is for observation zenith angles of 20 deg. and the red line for 
+// 60 deg. The overall effective QE drops from about 20.8 to about 19.8. 
+//
+// Jurgen Gebauer did some quick measurements about this issue. I attach a 
+// plot. You can see that the angular dependence is (more or less) in agreement with a 
+// CosTheta function (below 20-25 degrees), which is the variation of the entrance 
+// window cross section. So, in first approximation, no losses when increasing light 
+// incidence angle; and therefore, the factor 0.94.
+//
+//Begin_Html
+/*
+<img src="images/JuergensMeasurementWithCosThetaCurve.png">
+*/
+//End_Html
+//
+// The Quantum efficiencies for individual colours have been taken from: 
+// D. Paneque et al., A Method to enhance the sensitivity of photomultipliers 
+//                    of air Cherenkov Telescopes, NIM A 504, 2003, 109-115
+// (see following figure)
+//
+//Begin_Html
+/*
+<img src="images/QE_Paneque.png">
+*/
+//End_Html
+//
+// The Transmission of the Plexiglass window has been provided by Eckart and is 
+// displayed in the next plot. The above red curve has to be taken since it corresponds
+// to the glass type set on the camera.
+//
+//Begin_Html
+/*
+<img src="images/Transmission_Plexiglass.jpg">
+*/
+//End_Html
+//
+// See also: MJCalibration, MCalibrationChargeCalc, 
+//           MCalibrationChargeCam, MCalibrationChargePix, 
+//           MHCalibrationChargeCam, MHCalibrationChargePix,
+//           MHCalibrationChargePINDiode, MHCalibrationChargeBlindPix
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationQEPix.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationQEPix);
+
+using namespace std;
+
+const Float_t MCalibrationQEPix::gkDefaultQEGreen      = 0.192;
+const Float_t MCalibrationQEPix::gkDefaultQEBlue       = 0.27;
+const Float_t MCalibrationQEPix::gkDefaultQEUV         = 0.285;
+const Float_t MCalibrationQEPix::gkDefaultQECT1        = 0.285;
+const Float_t MCalibrationQEPix::gkDefaultQEGreenErr   = 0.007;
+const Float_t MCalibrationQEPix::gkDefaultQEBlueErr    = 0.01 ;
+const Float_t MCalibrationQEPix::gkDefaultQEUVErr      = 0.012;
+const Float_t MCalibrationQEPix::gkDefaultQECT1Err     = 0.012;
+const Float_t MCalibrationQEPix::gkDefaultAverageQE    = 0.184;     
+const Float_t MCalibrationQEPix::gkDefaultAverageQEErr = 0.02 ;  
+const Float_t MCalibrationQEPix::gkPMTCollectionEff    = 0.90 ;
+const Float_t MCalibrationQEPix::gkPMTCollectionEffErr = 0.05 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffGreen    = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffGreenErr = 0.03 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffBlue     = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffBlueErr  = 0.03 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffUV       = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffUVErr    = 0.03 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffCT1      = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffCT1Err   = 0.03 ;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Initializes all TArrays to MCalibrationCam::gkNumPulserColors
+//
+// Calls:
+// - Clear()
+//
+MCalibrationQEPix::MCalibrationQEPix(const char *name, const char *title)
+    :  fAverageQE ( gkDefaultAverageQE )
+{
+
+  fName  = name  ? name  : "MCalibrationQEPix";
+  fTitle = title ? title : "Container of the calibrated quantum efficiency ";
+
+  fQEBlindPixel    .Set( MCalibrationCam::gkNumPulserColors ); 
+  fQEBlindPixelVar .Set( MCalibrationCam::gkNumPulserColors );
+  fQECombined      .Set( MCalibrationCam::gkNumPulserColors );    
+  fQECombinedVar   .Set( MCalibrationCam::gkNumPulserColors ); 
+  fQEFFactor       .Set( MCalibrationCam::gkNumPulserColors );     
+  fQEFFactorVar    .Set( MCalibrationCam::gkNumPulserColors );  
+  fQEPINDiode      .Set( MCalibrationCam::gkNumPulserColors );    
+  fQEPINDiodeVar   .Set( MCalibrationCam::gkNumPulserColors );
+  fValidFlags      .Set( MCalibrationCam::gkNumPulserColors );
+
+  Clear();
+
+}
+
+// -----------------------------------------------------
+//
+// copy 'constructor'
+//
+void MCalibrationQEPix::Copy(TObject& object) const
+{
+
+  MCalibrationQEPix &pix = (MCalibrationQEPix&)object;
+
+  MCalibrationPix::Copy(pix);
+  //
+  // Copy the rest of the data members
+  //
+  pix.fQEBlindPixel      = fQEBlindPixel;
+  pix.fQEBlindPixelVar   = fQEBlindPixelVar;
+  pix.fQECombined        = fQECombined;
+  pix.fQECombinedVar     = fQECombinedVar;
+  pix.fQEFFactor         = fQEFFactor;
+  pix.fQEFFactorVar      = fQEFFactorVar;
+  pix.fQEPINDiode        = fQEPINDiode;
+  pix.fQEPINDiodeVar     = fQEPINDiodeVar;
+                                     
+  pix.fAvNormBlindPixel    = fAvNormBlindPixel;
+  pix.fAvNormBlindPixelVar = fAvNormBlindPixelVar;
+  pix.fAvNormCombined      = fAvNormCombined;
+  pix.fAvNormCombinedVar   = fAvNormCombinedVar;
+  pix.fAvNormFFactor       = fAvNormFFactor;
+  pix.fAvNormFFactorVar    = fAvNormFFactorVar;
+  pix.fAvNormPINDiode      = fAvNormPINDiode;
+  pix.fAvNormPINDiodeVar   = fAvNormPINDiodeVar;
+  pix.fAverageQE           = fAverageQE;
+
+  pix.fValidFlags          = fValidFlags;
+  pix.fAvailableFlags      = fAvailableFlags;
+  
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// Search all available QE's of a certain colour after the blind pixel method, 
+// compare them to the default QE of that colour and 
+// add up a weighted average (wav) and a sum of weights (sumw)
+//
+// FIXME: This has to be replaced by a decent fit the QE-spectrum!
+//
+void MCalibrationQEPix::AddAverageBlindPixelQEs(const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw )
+{
+
+  if (IsBlindPixelMethodValid (col))
+  {
+    const Float_t newavqe    =   GetQEBlindPixel      (col) / GetDefaultQE      (col) 
+                               / GetLightGuidesEff    (col) / GetPMTCollectionEff(); 
+    const Float_t newavqevar = ( GetQEBlindPixelRelVar(col) + GetDefaultQERelVar(col) 
+                               + GetLightGuidesEffRelVar(col) + GetPMTCollectionEffRelVar()  ) 
+                               * newavqe * newavqe;
+    const Float_t weight     = 1./newavqevar;
+
+    wav  += newavqe * weight;
+    sumw += weight;
+  }
+}
+
+
+// ----------------------------------------------------------------------------------------------
+// 
+// Search all available QE's of a certain colour after the F-Factor method, 
+// compare them to the default QE of that colour and 
+// add up a weighted average (wav) and a sum of weights (sumw)
+//
+// FIXME: This has to be replaced by a decent fit the QE-spectrum!
+//
+void MCalibrationQEPix::AddAverageFFactorQEs(const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw )
+{
+
+  if (IsFFactorMethodValid (col))
+  {
+    const Float_t newavqe    =   GetQEFFactor(col)       / GetDefaultQE (col) 
+                               / GetLightGuidesEff    (col) / GetPMTCollectionEff(); 
+    const Float_t newavqevar = ( GetQEFFactorRelVar(col) + GetDefaultQERelVar(col) 
+                               + GetLightGuidesEffRelVar(col) + GetPMTCollectionEffRelVar()  ) 
+                               * newavqe * newavqe;
+    const Float_t weight     = 1./newavqevar;
+
+    wav  += newavqe *weight;
+    sumw += weight;
+
+  }
+
+
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// Search all available QE's of a certain colour after the PIN Diode method, 
+// compare them to the default QE of that colour and 
+// add up a weighted average (wav) and a sum of weights (sumw)
+//
+// FIXME: This has to be replaced by a decent fit the QE-spectrum!
+//
+void MCalibrationQEPix::AddAveragePINDiodeQEs(const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw )
+{
+
+  if (IsPINDiodeMethodValid (col))
+  {
+    const Float_t newavqe    =   GetQEPINDiode(col)       / GetDefaultQE (col) 
+                               / GetLightGuidesEff    (col) / GetPMTCollectionEff(); 
+    const Float_t newavqevar = ( GetQEPINDiodeRelVar(col) + GetDefaultQERelVar(col) 
+                               + GetLightGuidesEffRelVar(col) + GetPMTCollectionEffRelVar()  ) 
+                               * newavqe * newavqe;
+    const Float_t weight     = 1./newavqevar;
+    wav  += newavqe *weight;
+    sumw += weight;
+  }
+}
+
+
+
+// ------------------------------------------------------------------------
+//
+// Sets all quantum efficiencies to the gkDefaultQE*
+// Sets all Variances to the square root of gkDefaultQE*Err
+// Sets all flags to kFALSE
+// Sets all fAvNorm-Variables to 1.;
+// Sets all fAvNorm-Variances to 0.;
+// 
+// Calls:
+// - MCalibrationPix::Clear()
+//
+void MCalibrationQEPix::Clear(Option_t *o)
+{
+
+  SetAverageQEBlindPixelAvailable ( kFALSE );
+  SetAverageQEFFactorAvailable    ( kFALSE );
+  SetAverageQECombinedAvailable   ( kFALSE );
+  SetAverageQEPINDiodeAvailable   ( kFALSE );
+
+  fQEBlindPixel    [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;  
+  fQEBlindPixelVar [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr;
+  fQEFFactor       [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;     
+  fQEFFactorVar    [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr;
+  fQECombined      [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;    
+  fQECombinedVar   [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr; 
+  fQEPINDiode      [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;    
+  fQEPINDiodeVar   [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kGREEN);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kGREEN);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+
+  fQEBlindPixel    [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;  
+  fQEBlindPixelVar [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr;
+  fQEFFactor       [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;     
+  fQEFFactorVar    [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr;
+  fQECombined      [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;    
+  fQECombinedVar   [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr; 
+  fQEPINDiode      [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;    
+  fQEPINDiodeVar   [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kBLUE);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kBLUE);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+
+  fQEBlindPixel    [ MCalibrationCam::kUV ] = gkDefaultQEUV;  
+  fQEBlindPixelVar [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr;
+  fQEFFactor       [ MCalibrationCam::kUV ] = gkDefaultQEUV;     
+  fQEFFactorVar    [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr;
+  fQECombined      [ MCalibrationCam::kUV ] = gkDefaultQEUV;    
+  fQECombinedVar   [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr; 
+  fQEPINDiode      [ MCalibrationCam::kUV ] = gkDefaultQEUV;    
+  fQEPINDiodeVar   [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kUV);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kUV);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kUV);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kUV);
+
+  fQEBlindPixel    [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;  
+  fQEBlindPixelVar [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err;
+  fQEFFactor       [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;     
+  fQEFFactorVar    [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err;
+  fQECombined      [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;    
+  fQECombinedVar   [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err; 
+  fQEPINDiode      [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;    
+  fQEPINDiodeVar   [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kCT1);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kCT1);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+
+  fAvNormBlindPixel     = -1.;     
+  fAvNormBlindPixelVar  = 0.;  
+  fAvNormCombined       = -1.;       
+  fAvNormCombinedVar    = 0.;    
+  fAvNormFFactor        = -1.;        
+  fAvNormFFactorVar     = 0.;     
+  fAvNormPINDiode       = -1.;       
+  fAvNormPINDiodeVar    = 0.;    
+
+  MCalibrationPix::Clear();
+}
+
+
+// -----------------------------------------------------------------
+//
+// Return the average Default QE
+//
+const Float_t MCalibrationQEPix::GetAverageQE() const
+{
+  return fAverageQE; 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the average Default QE
+//
+const Float_t MCalibrationQEPix::GetAverageQERelVar() 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 light guides efficiency depending on the pulser colour "col"
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEff
+//
+Float_t MCalibrationQEPix::GetLightGuidesEff( const MCalibrationCam::PulserColor_t col )  const
+{
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN:
+      return gkLightGuidesEffGreen;
+      break;
+    case MCalibrationCam::kBLUE:
+      return gkLightGuidesEffBlue;
+      break;
+    case MCalibrationCam::kUV:
+      return gkLightGuidesEffUV;
+      break;
+    case MCalibrationCam::kCT1:
+      return gkLightGuidesEffCT1;
+      break;
+    default:
+      return gkLightGuidesEffCT1;
+      break;
+    }
+  return -1.;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the relative variance of the light guides efficiency depending on the 
+// pulser colour "col"
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEffErr^2 / gkLightGuidesEff^2
+//
+Float_t MCalibrationQEPix::GetLightGuidesEffRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN:
+      return gkLightGuidesEffGreenErr * gkLightGuidesEffGreenErr / gkLightGuidesEffGreen / gkLightGuidesEffGreen;
+      break;
+    case MCalibrationCam::kBLUE:
+      return gkLightGuidesEffBlueErr  * gkLightGuidesEffBlueErr / gkLightGuidesEffBlue / gkLightGuidesEffBlue;
+      break;
+    case MCalibrationCam::kUV:
+      return gkLightGuidesEffUVErr  * gkLightGuidesEffUVErr / gkLightGuidesEffUV / gkLightGuidesEffUV;
+      break;
+    case MCalibrationCam::kCT1:
+      return gkLightGuidesEffCT1Err * gkLightGuidesEffCT1Err / gkLightGuidesEffCT1 / gkLightGuidesEffCT1;
+      break;
+    default: 
+      return gkLightGuidesEffCT1Err * gkLightGuidesEffCT1Err / gkLightGuidesEffCT1 / gkLightGuidesEffCT1;
+      break;
+    }
+  return -1.;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the light guides efficiency for Cherenkov spectra.
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEffBlue
+//
+Float_t MCalibrationQEPix::GetLightGuidesEff()  const
+{
+  return gkLightGuidesEffBlue;
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the relative variance of the light guides efficiency for Cherenkov spectra.
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEffBlueErr^2 / gkLightGuidesBlueEff^2
+//
+Float_t MCalibrationQEPix::GetLightGuidesEffRelVar()  const
+{
+  return gkLightGuidesEffBlueErr  * gkLightGuidesEffBlueErr / gkLightGuidesEffBlue / gkLightGuidesEffBlue;
+}
+
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the blind pixel method, 
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQEBlindPixel( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQEBlindPixel[col];
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the blind pixel method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEBlindPixelErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEBlindPixelVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQEBlindPixelVar[col]);
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the blind pixel method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEBlindPixelRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEBlindPixelVar[col] < 0.)
+    return -1.;
+  if (fQEBlindPixel[col] < 0.)
+      return -1.;
+  return fQEBlindPixelVar[col] / ( fQEBlindPixel[col] * fQEBlindPixel[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the combination of the three methods
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQECombined( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQECombined[col];
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the combination of the three methods
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQECombinedErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQECombinedVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQECombinedVar[col]);
+
+}
+
+
+// ----------------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the combination of 
+// the three methods, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQECombinedRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQECombinedVar[col] < 0.)
+    return -1.;
+  if (fQECombined[col] < 0.)
+      return -1.;
+  return fQECombinedVar[col] / ( fQECombined[col] * fQECombined[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the F-Factor method
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQEFFactor( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQEFFactor[col];
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the F-Factor method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEFFactorErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEFFactorVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQEFFactorVar[col]);
+
+}
+
+
+// ----------------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the F-Factor method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEFFactorRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEFFactorVar[col] < 0.)
+    return -1.;
+  if (fQEFFactor[col] < 0.)
+      return -1.;
+  return fQEFFactorVar[col] / ( fQEFFactor[col] * fQEFFactor[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the PIN-Diode method
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQEPINDiode( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQEPINDiode[col];
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the PIN Diode method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEPINDiodeErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEPINDiodeVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQEPINDiodeVar[col]);
+
+}
+
+// ----------------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the PIN Diode method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEPINDiodeRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEPINDiodeVar[col] < 0.)
+    return -1.;
+  if (fQEPINDiode[col] < 0.)
+      return -1.;
+  return fQEPINDiodeVar[col] / ( fQEPINDiode[col] * fQEPINDiode[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the averaged Quantum efficiency folded over the cascade spectrum, obtained 
+// with the blind pixel method and averaged over the results from the different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesBlindPixel()  const
+{
+  return fAvNormBlindPixel * GetAverageQE();
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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
+{
+  return ( GetAvNormBlindPixelRelVar()  + GetAverageQERelVar())
+    * GetQECascadesBlindPixel() * GetQECascadesBlindPixel();
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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
+{
+  const Float_t var = GetQECascadesBlindPixelVar();
+  
+  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
+{
+  return fAvNormCombined * GetAverageQE();
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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
+{
+  const Float_t var = GetQECascadesCombinedVar();
+  
+  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
+{
+  return ( GetAvNormCombinedRelVar()  + GetAverageQERelVar())
+    * GetQECascadesCombined() * GetQECascadesCombined();
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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
+{
+  return fAvNormFFactor * GetAverageQE();
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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
+{
+  const Float_t var = GetQECascadesFFactorVar();
+  
+  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
+{
+  return ( GetAvNormFFactorRelVar()  + GetAverageQERelVar())
+    * GetQECascadesFFactor() * GetQECascadesFFactor();
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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
+{
+  return fAvNormPINDiode * GetAverageQE();
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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
+{
+  const Float_t var = GetQECascadesPINDiodeVar();
+  
+  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
+{
+  return ( GetAvNormPINDiodeRelVar()  + GetAverageQERelVar())
+    * GetQECascadesPINDiode() * GetQECascadesPINDiode();
+}
+
+// -----------------------------------------------------------------
+//
+// Return the overall collection efficiency of the PMT
+//
+Float_t MCalibrationQEPix::GetPMTCollectionEff() const 
+{
+  return gkPMTCollectionEff; 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the collection efficiency of the PMT
+//
+Float_t MCalibrationQEPix::GetPMTCollectionEffRelVar() const 
+{
+  return gkPMTCollectionEffErr * gkPMTCollectionEffErr / gkPMTCollectionEff / gkPMTCollectionEff; 
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the blind pixel method
+//
+Bool_t MCalibrationQEPix::IsAverageQEBlindPixelAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQEBlindPixelAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the combination of the three methods
+//
+Bool_t MCalibrationQEPix::IsAverageQECombinedAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQECombinedAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the F-Factor method
+//
+Bool_t MCalibrationQEPix::IsAverageQEFFactorAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQEFFactorAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the PIN Diode method
+//
+Bool_t MCalibrationQEPix::IsAverageQEPINDiodeAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQEPINDiodeAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the blind pixel method
+//
+Bool_t MCalibrationQEPix::IsBlindPixelMethodValid () const
+{
+
+  if (IsBlindPixelMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the combination 
+// of the three methods
+//
+Bool_t MCalibrationQEPix::IsCombinedMethodValid () const
+{
+  if (IsCombinedMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the F-Factor method
+//
+Bool_t MCalibrationQEPix::IsFFactorMethodValid () const
+{
+  if (IsFFactorMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the PIN Diode method
+//
+Bool_t MCalibrationQEPix::IsPINDiodeMethodValid () const
+{
+  if (IsPINDiodeMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the Blind Pixel method
+//
+Bool_t MCalibrationQEPix::IsBlindPixelMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kBlindPixelMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the combination of 
+// the three methods
+//
+Bool_t MCalibrationQEPix::IsCombinedMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kCombinedMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the F-Factor method
+//
+Bool_t MCalibrationQEPix::IsFFactorMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kFFactorMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the PIN Diode method
+//
+Bool_t MCalibrationQEPix::IsPINDiodeMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kPINDiodeMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE Blind Pixel method available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQEBlindPixelAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQEBlindPixelAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQEBlindPixelAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE combination of three methods available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQECombinedAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQECombinedAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQECombinedAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE F-Factor method available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQEFFactorAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQEFFactorAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQEFFactorAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE PIN Diode method available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQEPINDiodeAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQEPINDiodeAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQEPINDiodeAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE Blind Pixel method available from colour "col"
+//
+void MCalibrationQEPix::SetBlindPixelMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kBlindPixelMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kBlindPixelMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE Combination of three methods available from colour "col"
+//
+void MCalibrationQEPix::SetCombinedMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kCombinedMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kCombinedMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE F-Factor method available from colour "col"
+//
+void MCalibrationQEPix::SetFFactorMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kFFactorMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kFFactorMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE PIN Diode method available from colour "col"
+//
+void MCalibrationQEPix::SetPINDiodeMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kPINDiodeMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kPINDiodeMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the Blind Pixel Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateBlindPixelMethod( const Float_t plex )
+{
+
+  Float_t weightedav = 0.;
+  Float_t sumweights = 0.;
+
+  AddAverageBlindPixelQEs(MCalibrationCam::kGREEN, weightedav, sumweights);
+  AddAverageBlindPixelQEs(MCalibrationCam::kBLUE , weightedav, sumweights);
+  AddAverageBlindPixelQEs(MCalibrationCam::kUV   , weightedav, sumweights);
+  AddAverageBlindPixelQEs(MCalibrationCam::kCT1  , weightedav, sumweights);
+
+  if (weightedav == 0. || sumweights == 0.)
+    return kFALSE;
+
+  fAvNormBlindPixel     = weightedav / plex / sumweights;
+  fAvNormBlindPixelVar  = 1./ sumweights;
+
+  SetAverageQEBlindPixelAvailable();
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the Combination of the three Methods: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateCombinedMethod()
+{
+  
+  fAvNormCombinedVar = 0.;
+  fAvNormCombined    = 0.;
+  
+  if (fAvNormBlindPixel > 0. && fAvNormBlindPixelVar > 0.)
+    {
+      const Float_t weight = 1./fAvNormBlindPixelVar;
+      fAvNormCombinedVar  += weight;
+      fAvNormCombined     += fAvNormBlindPixel*weight;
+    }
+  
+  if (fAvNormFFactor    > 0. && fAvNormFFactorVar > 0. )
+    {
+      const Float_t weight = 1./fAvNormFFactorVar;
+      fAvNormCombinedVar  += weight;
+      fAvNormCombined     += fAvNormFFactor*weight;
+    }
+  
+  if (fAvNormPINDiode > 0. && fAvNormPINDiodeVar > 0. )
+    {
+      const Float_t weight = 1./fAvNormPINDiodeVar;
+      fAvNormCombinedVar  += weight;
+      fAvNormCombined     += fAvNormPINDiode*weight;
+    }
+  
+  fAvNormCombined = ( fAvNormCombinedVar > 0.) ? -1. : fAvNormCombined/fAvNormCombinedVar ;
+  
+  if (fAvNormCombined > 0.)
+    SetAverageQECombinedAvailable();
+
+  return kTRUE;
+  
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the F-Factor Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateFFactorMethod( const Float_t plex )
+{
+
+  Float_t weightedav = 0.;
+  Float_t sumweights = 0.;
+
+  AddAverageFFactorQEs(MCalibrationCam::kGREEN, weightedav, sumweights);
+  AddAverageFFactorQEs(MCalibrationCam::kBLUE , weightedav, sumweights);
+  AddAverageFFactorQEs(MCalibrationCam::kUV   , weightedav, sumweights);
+  AddAverageFFactorQEs(MCalibrationCam::kCT1  , weightedav, sumweights);
+ 
+  if (weightedav == 0. || sumweights == 0.)
+    return kFALSE;
+
+  fAvNormFFactor     = weightedav / plex / sumweights;
+  fAvNormFFactorVar  = 1./ sumweights;
+  
+  SetAverageQEFFactorAvailable();
+
+  return kTRUE;
+  
+  
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the PIN Diode Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdatePINDiodeMethod()
+{
+  
+  Float_t weightedav = 0.;
+  Float_t sumweights = 0.;
+
+  AddAveragePINDiodeQEs(MCalibrationCam::kGREEN, weightedav, sumweights);
+  AddAveragePINDiodeQEs(MCalibrationCam::kBLUE , weightedav, sumweights);
+  AddAveragePINDiodeQEs(MCalibrationCam::kUV   , weightedav, sumweights);
+  AddAveragePINDiodeQEs(MCalibrationCam::kCT1  , weightedav, sumweights);
+
+  if (weightedav == 0. || sumweights == 0.)
+    return kFALSE;
+
+  fAvNormPINDiode     = weightedav / sumweights;
+  fAvNormPINDiodeVar  = 1./ sumweights ;
+
+  SetAverageQEPINDiodeAvailable();
+
+  return kTRUE;
+
+  
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationQEPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationQEPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationQEPix.h	(revision 17960)
@@ -0,0 +1,177 @@
+#ifndef MARS_MCalibrationQEPix
+#define MARS_MCalibrationQEPix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationQEPix : public MCalibrationPix
+{
+private:
+
+  static const Float_t gkDefaultQEGreen;      //! Default QE at 520 nm (now set to: 0.192)
+  static const Float_t gkDefaultQEBlue;       //! Default QE at 460 nm (now set to: 0.27 )
+  static const Float_t gkDefaultQEUV;         //! Default QE at 370 nm (now set to: 0.285)
+  static const Float_t gkDefaultQECT1;        //! Default QE at 370 nm (now set to: 0.285)
+  static const Float_t gkDefaultQEGreenErr;   //! Uncertainty Def. QE  at 520 nm (now set to: 0.05)
+  static const Float_t gkDefaultQEBlueErr;    //! Uncertainty Def. QE  at 460 nm (now set to: 0.07)
+  static const Float_t gkDefaultQEUVErr;      //! Uncertainty Def. QE  at 370 nm (now set to: 0.07)
+  static const Float_t gkDefaultQECT1Err;     //! Uncertainty Def. QE  at 370 nm (now set to: 0.07)
+  static const Float_t gkLightGuidesEffGreen;    //! Default Light guides efficiency at 520 nm
+  static const Float_t gkLightGuidesEffGreenErr; //! Uncertainty Def. Light guides efficiency at 520 nm
+  static const Float_t gkLightGuidesEffBlue;     //! Default Light guides efficiency at 460 nm
+  static const Float_t gkLightGuidesEffBlueErr;  //! Uncertainty Def. Light guides efficiency at 460 nm
+  static const Float_t gkLightGuidesEffUV;       //! Default Light guides efficiency at 370 nm
+  static const Float_t gkLightGuidesEffUVErr;    //! Uncertainty Def. Light guides efficiency at 370 nm
+  static const Float_t gkLightGuidesEffCT1;      //! Default Light guides efficiency at 370 nm
+  static const Float_t gkLightGuidesEffCT1Err;   //! Uncertainty Def. Light guides efficiency at 370 nm
+  static const Float_t gkPMTCollectionEff;    //! Default Collection efficiency of the PMTs
+  static const Float_t gkPMTCollectionEffErr; //! Uncertainty Def. Collection efficiency of the PMTs (0.01)
+  
+  MArrayF fQEBlindPixel;                     // Calibrated QEs    (Blind Pixel Method)
+  MArrayF fQEBlindPixelVar;                  // Variance cal. QEs (Blind Pixel Method)
+  MArrayF fQECombined;                       // Calibrated QEs    (Combined Method)
+  MArrayF fQECombinedVar;                    // Variance cal. QEs (Combined Method)
+  MArrayF fQEFFactor;                        // Calibrated QEs    (F-Factor Method)
+  MArrayF fQEFFactorVar;                     // Variance cal. QEs (F-Factor Method)
+  MArrayF fQEPINDiode;                       // Calibrated QEs    (PIN Diode Method)
+  MArrayF fQEPINDiodeVar;                    // Variance cal. QEs (PIN Diode Method)
+                                             
+  Float_t fAvNormBlindPixel;                 // Normalization w.r.t. default QE (Blind Pixel Method)
+  Float_t fAvNormBlindPixelVar;              // Variance norm. w.r.t. def. QE (Blind Pixel Method)
+  Float_t fAvNormCombined;                   // Normalization w.r.t. default QE (Combined Method)
+  Float_t fAvNormCombinedVar;                // Variance norm. w.r.t. def. QE (Combined Method)
+  Float_t fAvNormFFactor;                    // Normalization w.r.t. default QE (F-Factor Method)
+  Float_t fAvNormFFactorVar;                 // Variance norm. w.r.t. def. QE (F-Factor Method)
+  Float_t fAvNormPINDiode;                   // Normalization w.r.t. default QE (PIN Diode Method)
+  Float_t fAvNormPINDiodeVar;                // Variance norm. w.r.t. def. QE (PIN Diode Method)
+  Float_t fAverageQE;                        // Average QE for Cascade spectrum (default 0.18)
+
+  TArrayC fValidFlags;                       // Bit-field for valid flags, one array entry for each color
+  Byte_t  fAvailableFlags;                   // Bit-field for available flags
+  
+  enum { kBlindPixelMethodValid, kFFactorMethodValid, 
+	 kPINDiodeMethodValid, kCombinedMethodValid,
+         kAverageQEBlindPixelAvailable, kAverageQEFFactorAvailable,
+         kAverageQEPINDiodeAvailable, kAverageQECombinedAvailable  };
+
+  void  AddAverageBlindPixelQEs( const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw );
+  void  AddAverageFFactorQEs  ( const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw );
+  void  AddAveragePINDiodeQEs  ( const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw );
+
+  const Float_t GetAvNormBlindPixelRelVar()  const;
+  const Float_t GetAvNormCombinedRelVar()  const;
+  const Float_t GetAvNormFFactorRelVar()  const;
+  const Float_t GetAvNormPINDiodeRelVar()  const;  
+
+public:
+
+  static const Float_t gkDefaultAverageQE;    //! Default QE folded into Cascade spectrum (now set to: 0.18)
+  static const Float_t gkDefaultAverageQEErr; //! Uncertainty Def. QE Cascade spectrum    (now set to: 0.02)
+
+  MCalibrationQEPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationQEPix() {}
+  
+  void Clear(Option_t *o="");
+  void Copy (TObject& object) const;  
+
+  // Getters
+  const Float_t GetAverageQE() const;
+  const Float_t GetAverageQERelVar() const;
+  
+  Float_t GetDefaultQE                   ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetDefaultQERelVar             ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetLightGuidesEff              ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetLightGuidesEffRelVar        ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetLightGuidesEff              ()                   const;
+  Float_t GetLightGuidesEffRelVar        ()                   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 GetQECascadesBlindPixelErr     ()                   const;
+  Float_t GetQECascadesBlindPixelVar     ()                   const;
+  Float_t GetQECascadesCombined          ()                   const;  
+  Float_t GetQECascadesCombinedErr       ()                   const;
+  Float_t GetQECascadesCombinedVar       ()                   const;    
+  Float_t GetQECascadesFFactor           ()                   const;  
+  Float_t GetQECascadesFFactorErr        ()                   const;
+  Float_t GetQECascadesFFactorVar        ()                   const;    
+  Float_t GetQECascadesPINDiode          ()                   const;
+  Float_t GetQECascadesPINDiodeErr       ()                   const;
+  Float_t GetQECascadesPINDiodeVar       ()                   const;  
+  Float_t GetQECombined                  ( const MCalibrationCam::PulserColor_t col ) const;        
+  Float_t GetQECombinedErr               ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetQECombinedRelVar            ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQEFFactor                   ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQEFFactorErr                ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetQEFFactorRelVar             ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQEPINDiode                  ( const MCalibrationCam::PulserColor_t col ) const;        
+  Float_t GetQEPINDiodeErr               ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetQEPINDiodeRelVar            ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetPMTCollectionEff()                                                       const;
+  Float_t GetPMTCollectionEffRelVar()                                                 const;
+
+  Bool_t  IsAverageQEBlindPixelAvailable ()                                           const;
+  Bool_t  IsAverageQECombinedAvailable   ()                                           const;  
+  Bool_t  IsAverageQEFFactorAvailable    ()                                           const;  
+  Bool_t  IsAverageQEPINDiodeAvailable   ()                                           const;  
+  Bool_t  IsBlindPixelMethodValid        ()                                           const;
+  Bool_t  IsBlindPixelMethodValid        ( const MCalibrationCam::PulserColor_t col ) const;
+  Bool_t  IsCombinedMethodValid          ()                                           const;  
+  Bool_t  IsCombinedMethodValid          ( const MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsFFactorMethodValid           ()                                           const;  
+  Bool_t  IsFFactorMethodValid           ( const MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsPINDiodeMethodValid          ()                                           const;  
+  Bool_t  IsPINDiodeMethodValid          ( const MCalibrationCam::PulserColor_t col ) const;  
+
+  // Setters 
+  void SetAverageQE            ( const Float_t f )  { fAverageQE            = f; }
+  void SetAvNormBlindPixel     ( const Float_t f )  { fAvNormBlindPixel     = f; }      
+  void SetAvNormBlindPixelVar  ( const Float_t f )  { fAvNormBlindPixelVar  = f; }   
+  void SetAvNormCombined       ( const Float_t f )  { fAvNormCombined       = f; }        
+  void SetAvNormCombinedVar    ( const Float_t f )  { fAvNormCombinedVar    = f; }     
+  void SetAvNormFFactor        ( const Float_t f )  { fAvNormFFactor        = f; }         
+  void SetAvNormFFactorVar     ( const Float_t f )  { fAvNormFFactorVar     = f; }      
+  void SetAvNormPINDiode       ( const Float_t f )  { fAvNormPINDiode       = f; }        
+  void SetAvNormPINDiodeVar    ( const Float_t f )  { fAvNormPINDiodeVar    = f; }     
+  void SetAverageQEBlindPixelAvailable   ( const Bool_t b=kTRUE );
+  void SetAverageQECombinedAvailable     ( const Bool_t b=kTRUE );
+  void SetAverageQEFFactorAvailable      ( const Bool_t b=kTRUE );
+  void SetAverageQEPINDiodeAvailable     ( const Bool_t b=kTRUE );
+  void SetBlindPixelMethodValid          ( const Bool_t b, const MCalibrationCam::PulserColor_t col);
+  void SetCombinedMethodValid            ( const Bool_t b, const MCalibrationCam::PulserColor_t col);
+  void SetFFactorMethodValid             ( const Bool_t b, const MCalibrationCam::PulserColor_t col);  
+  void SetPINDiodeMethodValid            ( const Bool_t b, const MCalibrationCam::PulserColor_t col);  
+  void SetQEBlindPixel    ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEBlindPixel   [col] = f; }
+  void SetQEBlindPixelVar ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEBlindPixelVar[col] = f; }
+  void SetQECombined      ( Float_t f, MCalibrationCam::PulserColor_t col) { fQECombined     [col] = f; }
+  void SetQECombinedVar   ( Float_t f, MCalibrationCam::PulserColor_t col) { fQECombinedVar  [col] = f; }
+  void SetQEFFactor       ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEFFactor      [col] = f; }
+  void SetQEFFactorVar    ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEFFactorVar   [col] = f; }
+  void SetQEPINDiode      ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEPINDiode     [col] = f; }
+  void SetQEPINDiodeVar   ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEPINDiodeVar  [col] = f; }
+
+  // Updates
+  Bool_t  UpdateBlindPixelMethod( const Float_t plex );
+  Bool_t  UpdateCombinedMethod  ();
+  Bool_t  UpdateFFactorMethod   ( const Float_t plex );
+  Bool_t  UpdatePINDiodeMethod  ();
+
+  ClassDef(MCalibrationQEPix, 3)     // Container Quantum Efficieny Calibration Results Pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCalc.cc	(revision 17960)
@@ -0,0 +1,460 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationRelTimeCalc
+//
+//   Task to finalize the relative time calibration obtained 
+//   from the fit results to the summed FADC slice distributions delivered by 
+//   MCalibrationRelTimeCam, calculated and filled by MHCalibrationRelTimeCam, 
+//
+//   PreProcess(): Initialize pointers to MCalibrationRelTimeCam, 
+//               
+//   ReInit():     Initializes pointer to MBadPixelsCam
+//
+//   Process():    Nothing to be done, histograms getting filled by MHCalibrationChargeCam
+//
+//   PostProcess(): - FinalizeRelTimes()
+//                  - FinalizeBadPixels()
+//
+// Class Version 2:
+//  + Byte_t fCheckFlags; // Bit-field to hold the possible check flags
+//
+// ClassVersionb 3:
+//  -  TString fOutputPath;                           //  Path to the output file
+//  -  TString fOutputFile;                           //  Name of the output file
+//
+//
+//  Input Containers:
+//   MCalibrationRelTimeCam
+//   MBadPixelsCam
+//   MGeomCam
+//
+//  Output Containers:
+//   MCalibrationRelTimeCam
+//   MBadPixelsCam
+//
+//  
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationRelTimeCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMath.h"
+
+#include "MParList.h"
+
+#include "MStatusDisplay.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimePix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MCalibrationRelTimeCalc);
+
+using namespace std;
+
+const Float_t MCalibrationRelTimeCalc::fgRelTimeResolutionLimit = 5.0;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Sets all pointers to NULL
+// 
+// Initializes:
+// - fRelTimeResolutionLimit to fgRelTimeResolutionimit
+//
+// Calls:
+// - Clear()
+//
+MCalibrationRelTimeCalc::MCalibrationRelTimeCalc(const char *name, const char *title)
+    : fGeom(NULL), fFlags(0)
+{
+
+  fName  = name  ? name  : "MCalibrationRelTimeCalc";
+  fTitle = title ? title : "Task to finalize the relative time calibration";
+
+  SetCheckFitResults       ( kFALSE );
+  SetCheckDeviatingBehavior( kTRUE  );
+  SetCheckHistOverflow     ( kFALSE );
+  SetCheckOscillations     ( kFALSE );
+
+  SetRelTimeResolutionLimit();
+
+  Clear();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all pointers to NULL
+//
+void MCalibrationRelTimeCalc::Clear(const Option_t *o)
+{
+    fBadPixels  = NULL;
+    fCam        = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+//  - MGeomCam
+//  - MCalibrationRelTimeCam
+//  - MBadPixelsCam
+// 
+// It defines the PixId of every pixel in:
+//
+// - MCalibrationRelTimeCam 
+//
+// It sets all pixels in excluded which have the flag fBadBixelsPix::IsBad() set in:
+// 
+// - MCalibrationRelTimePix
+//
+Bool_t MCalibrationRelTimeCalc::ReInit(MParList *pList )
+{
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "No MGeomCam found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+  if (!fBadPixels)
+  {
+      *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+      return kFALSE;
+  }
+
+  fCam = (MCalibrationRelTimeCam*)pList->FindObject(AddSerialNumber("MCalibrationRelTimeCam"));
+  if (!fCam)
+  {
+      *fLog << err << "Cannot find MCalibrationRelTimeCam ... abort." << endl;
+      return kFALSE;
+  }
+
+  if (IsDebug())
+  {
+      const UInt_t npixels = fGeom->GetNumPixels();
+      for (UInt_t i=0; i<npixels; i++)
+          (*fCam)[i].SetDebug();
+  }
+
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Return if number of executions is null.
+//
+Int_t MCalibrationRelTimeCalc::PostProcess()
+{
+
+  if (GetNumExecutions()==0)
+    return kTRUE;
+
+  return Finalize();
+}
+
+// -----------------------------------------------------------------------
+//
+// First loop over pixels, average areas and sectors, call: 
+//  - FinalizeRelTimes()
+// for every entry. Count number of valid pixels in loop and return kFALSE
+// if there are none (the "Michele check").
+//
+// Call FinalizeBadPixels()
+//
+// Call MParContainer::SetReadyToSave() for fCam
+//
+// Print out some statistics
+//
+Int_t MCalibrationRelTimeCalc::Finalize()
+{
+  
+  //
+  // First loop over pixels, call FinalizePedestals and FinalizeRelTimes
+  //
+  FinalizeRelTimes();
+
+  //
+  // Finalize Bad Pixels
+  // 
+  FinalizeBadPixels();
+
+  //
+  // Finalize calibration statistics
+  //
+  FinalizeUnsuitablePixels();
+
+  fCam->SetReadyToSave();
+  fBadPixels->SetReadyToSave();
+
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Errors statistics:" << endl;  
+
+  PrintUncalibrated(MBadPixelsPix::kDeviatingRelTimeResolution,
+                    Form("%s%2.1f%s","Rel.time rms more than ", fRelTimeResolutionLimit, " dev from median:"));
+  PrintUncalibrated(MBadPixelsPix::kRelTimeOscillating,   
+                    "Pixels with changing Rel. Times over time:");
+  PrintUncalibrated(MBadPixelsPix::kRelTimeNotFitted,     
+                    "Pixels with unsuccesful Gauss fit to the times:");
+
+  return kTRUE;
+}
+
+
+// ----------------------------------------------------------------------------------------------------
+//
+// Check for outliers. They are marked with
+// MBadPixelsPix::kDeviatingTimeResolution
+//
+// see also MCalibrationChargeCalc::FinalizeAbsTimes
+//
+void MCalibrationRelTimeCalc::FinalizeRelTimes()
+{
+    const Int_t npixels = fGeom->GetNumPixels();
+    const Int_t nareas  = fGeom->GetNumAreas();
+
+    // Create an array capable of holding all pixels
+    TArrayF arr(npixels);
+
+    for (Int_t aidx=0; aidx<nareas; aidx++)
+    {
+        Int_t n = 0;
+        for (Int_t i=0; i<npixels; i++)
+        {
+            // Check for this aidx only
+            if ((*fGeom)[i].GetAidx()!=aidx)
+                continue;
+
+            // check if pixel may not contain a valid value
+            if ((*fBadPixels)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+                continue;
+
+            // check if it was excluded for some reason
+            const MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*fCam)[i];
+            if (pix.IsExcluded())
+                continue;
+
+            // if TimePrecision is valid fill it into array
+            if (pix.GetTimePrecision()>0)
+                arr[n++] = pix.GetTimePrecision();
+        }
+
+        // Check the ratio of valid entries to the ratio of pixels
+        const Float_t ratio = 100*n/fGeom->GetNumPixWithAidx(aidx);
+        if (3*ratio<2)
+            *fLog << warn << "Area   " << setw(4) << aidx << ": Only " << ratio << "% pixels with valid time resolution found." << endl;
+
+        // Calculate median and median deviation
+        Double_t med;
+        const Double_t dev = MMath::MedianDev(n, arr.GetArray(), med);
+
+        // Calculate upper and lower limit
+        const Float_t lolim = TMath::Max(med-fRelTimeResolutionLimit*dev, 0.);
+        const Float_t hilim = TMath::Max(med+fRelTimeResolutionLimit*dev, 0.);
+
+        // Now find the outliers
+        for (Int_t i=0; i<npixels; i++)
+        {
+            // Search only within this aidx
+            if ((*fGeom)[i].GetAidx()!=aidx)
+                continue;
+
+            // skip pixels already known to be unsuitable
+            if ((*fBadPixels)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+                continue;
+
+            // check if a pixel has been excluded. This
+            const MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*fCam)[i];
+
+            // Check if time precision is valid (might be invalid
+            // for example in cae of empty histograms)
+            const Float_t res = pix.GetTimePrecision();
+            if (res<0) //FIXME!!! How does this happen?
+            {
+                *fLog << warn << "Pixel  " << setw(4) << i << ": Rel-time rms could not be calculated." << endl;
+                (*fBadPixels)[i].SetUncalibrated(MBadPixelsPix::kDeviatingRelTimeResolution);
+                continue;
+            }
+
+            // Now compare to a lower and upper limit
+            if (res<=lolim || res>=hilim)
+            {
+                *fLog << warn << "Pixel  " << setw(4) << i << ": Deviation from rel-time rms: "
+                    << Form("%5.2f", res) << " out of range "
+                    << Form("[%4.2f,%4.2f]", lolim, hilim) << endl;
+
+                (*fBadPixels)[i].SetUncalibrated(MBadPixelsPix::kDeviatingRelTimeResolution);
+            }
+        }
+    }
+}
+
+
+// -----------------------------------------------------------------------------------
+//
+// Sets pixel to MBadPixelsPix::kUnsuitableRun, if one of the following flags is set:
+// - MBadPixelsPix::kRelTimeIsPedestal
+// - MBadPixelsPix::kRelTimeErrNotValid 
+// - MBadPixelsPix::kRelTimeRelErrNotValid 
+//
+void MCalibrationRelTimeCalc::FinalizeBadPixels()
+{
+
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      if (IsCheckDeviatingBehavior())
+          if (bad.IsUncalibrated(MBadPixelsPix::kDeviatingRelTimeResolution))
+              bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+
+      if (IsCheckFitResults())
+          if (bad.IsUncalibrated(MBadPixelsPix::kRelTimeNotFitted))
+              bad.SetUnsuitable(MBadPixelsPix::kUnreliableRun);
+
+      if (IsCheckOscillations())
+          if (bad.IsUncalibrated(MBadPixelsPix::kRelTimeOscillating))
+              bad.SetUnsuitable(MBadPixelsPix::kUnreliableRun);
+    }
+
+}
+
+
+// -----------------------------------------------------------------------------------------------
+//
+// - Print out statistics about BadPixels of type UnsuitableType_t 
+// - store numbers of bad pixels of each type in fIntensCam or fCam
+//
+void MCalibrationRelTimeCalc::FinalizeUnsuitablePixels()
+{
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << ": Rel. Times Calibration status:" << endl;
+    *fLog << dec;
+
+    const Int_t nareas = fGeom->GetNumAreas();
+
+    TArrayI unsuit(nareas);
+    TArrayI unrel(nareas);
+
+    for (int aidx=0; aidx<nareas; aidx++)
+    {
+        unsuit[aidx] += fBadPixels->GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, fGeom, aidx);
+        unrel[aidx]  += fBadPixels->GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, fGeom, aidx);
+        fCam->SetNumUnsuitable(unsuit[aidx], aidx);
+        fCam->SetNumUnreliable(unrel[aidx],  aidx);
+    }
+
+    if (fGeom->InheritsFrom("MGeomCamMagic"))
+    {
+        PrintUncalibrated("Uncalibrated Pixels:", unsuit[0], unsuit[1]);
+        PrintUncalibrated("Unreliable Pixels:",   unrel[0],  unrel[1]);
+    }
+}
+
+// -----------------------------------------------------------------------------------------------
+//
+// Print out statistics about BadPixels of type UncalibratedType_t 
+// 
+void MCalibrationRelTimeCalc::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++)
+    {
+        if ((*fBadPixels)[i].IsUncalibrated(typ))
+        {
+            if (fGeom->GetPixRatio(i) == 1.)
+                countinner++;
+            else
+                countouter++;
+        }
+    }
+
+    PrintUncalibrated(text, countinner, countouter);
+}
+
+void MCalibrationRelTimeCalc::PrintUncalibrated(const char *text, Int_t in, Int_t out) const
+{
+    *fLog << " " << setfill(' ') << setw(48) << setiosflags(ios::left) << text;
+    *fLog << " Inner: " << Form("%3i", in);
+    *fLog << " Outer: " << Form("%3i", out);
+    *fLog << resetiosflags(ios::left) << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// MCalibrationRelTimeCam.CheckFitResults: Yes
+// MCalibrationRelTimeCam.CheckDeviatingBehavior: Yes
+// MCalibrationRelTimeCam.CheckHistOverflow: Yes
+// MCalibrationRelTimeCam.CheckOscillations: Yes
+// 
+Int_t MCalibrationRelTimeCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "CheckFitResults", print))
+    {
+        SetCheckFitResults(GetEnvValue(env, prefix, "CheckFitResults", IsCheckFitResults()));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "CheckDeviatingBehavior", print))
+    {
+        SetCheckDeviatingBehavior(GetEnvValue(env, prefix, "CheckDeviatingBehavior", IsCheckDeviatingBehavior()));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "CheckHistOverflow", print))
+    {
+        SetCheckHistOverflow(GetEnvValue(env, prefix, "CheckHistOverflow", IsCheckHistOverflow()));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "CheckOscillations", print))
+    {
+        SetCheckOscillations(GetEnvValue(env, prefix, "CheckOscillations", IsCheckOscillations()));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "RelTimeResolutionLimit", print))
+    {
+        SetRelTimeResolutionLimit(GetEnvValue(env, prefix, "RelTimeResolutionLimit", fRelTimeResolutionLimit));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCalc.h	(revision 17960)
@@ -0,0 +1,103 @@
+#ifndef MARS_MCalibrationRelTimeCalc
+#define MARS_MCalibrationRelTimeCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalibrationRelTimeCalc
+//
+// Integrates the time slices of the all pixels of a calibration event
+// and substract the pedestal value
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+class MCalibrationRelTimeCam;
+class MGeomCam;
+class MBadPixelsCam;
+
+class MCalibrationRelTimeCalc : public MTask
+{
+private:
+
+  static const Float_t fgRelTimeResolutionLimit; //! Default for fRelTimeResolutionLimit (now set to: 0.75)
+ 
+  // Variables
+  Float_t fRelTimeResolutionLimit;               //  Limit acceptance rel. time resolution (in FADC slices)
+  
+  // Pointers
+  MBadPixelsCam              *fBadPixels;        //  Bad Pixels 
+  MCalibrationRelTimeCam     *fCam;              //  Calibrated RelTimes of all pixels 
+  MGeomCam                   *fGeom;             //! Camera geometry
+
+  // enums
+  enum  Check_t
+  {
+      kCheckHistOverflow,
+      kCheckDeviatingBehavior,
+      kCheckOscillations,
+      kCheckFitResults
+  };                                             // Possible Checks
+
+  Byte_t fCheckFlags;                            // Bit-field to hold the possible check flags
+
+  enum  { kDebug };                              //  Possible flags
+
+  Byte_t  fFlags;                                //  Bit-field for the general flags
+  
+  // functions
+  const char* GetOutputFile       ();
+  void   FinalizeAverageResolution();
+  void   FinalizeRelTimes         ();
+  void   FinalizeBadPixels        ();
+  void   FinalizeUnsuitablePixels ();
+
+  void   PrintUncalibrated(const char *text, Int_t in, Int_t out) const;
+  void   PrintUncalibrated(MBadPixelsPix::UncalibratedType_t typ, const char *text) const;
+
+  // Query checks
+  Bool_t IsCheckDeviatingBehavior() const { return TESTBIT(fCheckFlags,kCheckDeviatingBehavior); }
+  Bool_t IsCheckHistOverflow     () const { return TESTBIT(fCheckFlags,kCheckHistOverflow);      }
+  Bool_t IsCheckOscillations     () const { return TESTBIT(fCheckFlags,kCheckOscillations);      }
+  Bool_t IsCheckFitResults       () const { return TESTBIT(fCheckFlags,kCheckFitResults);        }
+
+  // MTask
+  Bool_t ReInit     (MParList *pList); 
+  Int_t  Process    () { return kTRUE; }
+  Int_t  PostProcess();
+
+  // MParContainer
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+  MCalibrationRelTimeCalc(const char *name=NULL, const char *title=NULL);
+
+  // TObject
+  void Clear(const Option_t *o="");
+
+  // MCalibrationRelTimeCalc
+  Int_t Finalize();
+  
+  // Getter
+  Bool_t IsDebug() const  {  return TESTBIT(fFlags,kDebug); }
+
+  // Setter
+  void SetRelTimeResolutionLimit( const Float_t f=fgRelTimeResolutionLimit ) { fRelTimeResolutionLimit = f; }
+
+  // Checks
+  void SetCheckFitResults(const Bool_t b=kTRUE)        { b ? SETBIT(fCheckFlags,kCheckFitResults) : CLRBIT(fCheckFlags,kCheckFitResults); }
+  void SetCheckDeviatingBehavior(const Bool_t b=kTRUE) { b ? SETBIT(fCheckFlags,kCheckDeviatingBehavior) : CLRBIT(fCheckFlags,kCheckDeviatingBehavior); }
+  void SetCheckHistOverflow(const Bool_t b=kTRUE)      { b ? SETBIT(fCheckFlags,kCheckHistOverflow) : CLRBIT(fCheckFlags,kCheckHistOverflow); }
+  void SetCheckOscillations(const Bool_t b=kTRUE)      { b ? SETBIT(fCheckFlags,kCheckOscillations) : CLRBIT(fCheckFlags,kCheckOscillations); }
+  void SetDebug(const Bool_t b=kTRUE)                  { b ? SETBIT(fFlags, kDebug) : CLRBIT(fFlags, kDebug); }
+
+  ClassDef(MCalibrationRelTimeCalc, 3)   // Task finalizing the relative time Calibration
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCam.cc	(revision 17960)
@@ -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): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationRelTimeCam                                               
+//                                                               
+// Storage container for relative arrival time calibration results         
+// of the whole camera.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationRelTimePix &avpix = (MCalibrationRelTimePix&)(*fRelCam)[i]
+// 
+// The following "calibration" constants can be retrieved from each pixel:
+// - GetTimeOffset(): The mean offset in relative times, 
+//   has to be added to any calculated relative time in the camera. 
+// - GetTimePrecision(): The Gauss sigma of histogrammed relative arrival 
+//   times for the calibration run. Gives an estimate about the timing 
+//   resolution.
+//
+// ALL RELATIVE TIMES HAVE TO BE CALCULATED W.R.T. PIXEL IDX 1 
+// (HARDWARE NUMBER: 2) !!
+//
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationRelTimePix &avpix = (MCalibrationRelTimePix&)fRelCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationRelTimePix &avpix = (MCalibrationRelTimePix&)fRelCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// See also: MHCalibrationRelTimePix, MHCalibrationRelTimeCam              
+//                                                                         
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Mean Time Offset
+// 1: Error of Mean Time Offset
+// 2: Sigma of Time Offset == Time Resolution 
+// 3: Error of Sigma of Time Offset
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Rel. Arrival Time distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MCalibrationRelTimePix.h"
+
+ClassImp(MCalibrationRelTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationRelTimeCam::MCalibrationRelTimeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationRelTimeCam";
+  fTitle = title ? title : "Container for Relative Time Calibration Information";
+  
+}
+
+void MCalibrationRelTimeCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationRelTimePix,i);
+}
+
+
+void MCalibrationRelTimeCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationRelTimePix,i);
+}
+
+void MCalibrationRelTimeCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationRelTimePix,i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not Valid
+//
+void MCalibrationRelTimeCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+
+  *fLog << all << "Calibrated pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationRelTimePix *pix;
+  while ((pix=(MCalibrationRelTimePix*)Next()))
+  {
+      if (!pix->IsExcluded())
+      {
+          *fLog << all
+              << "Pix  " << Form("%4i", pix->GetPixId()) << ":         "
+              << "   Offset: "
+              << Form("%4.2f +- %4.2f", pix->GetTimeOffset(), pix->GetTimeOffsetErr())
+              << "   Precision: "
+              << Form("%4.2f +- %4.2f", 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
+          << "Average Area   " << Form("%4i", pix->GetPixId()) << ":"
+          << "Offset: "
+          << Form("%4.2f +- %4.2f", pix->GetTimeOffset(), pix->GetTimeOffsetErr())
+          << "   Precision: "
+          << Form("%4.2f +- %4.2f", pix->GetTimePrecision(), pix->GetTimePrecisionErr())
+          << endl;
+  }
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationRelTimePix*)Next5()))
+  {
+      *fLog << all
+          << "Average Sector " << Form("%4i", pix->GetPixId()) << ":"
+          << "Offset: "
+          << Form("%4.2f +- %4.2f", pix->GetTimeOffset(), pix->GetTimeOffsetErr())
+          << "   Precision: "
+          << Form("%4.2f +- %4.2f", 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;
+
+    const Float_t area = cam[idx].GetA();
+    if (area == 0)
+        return kFALSE;
+
+    const MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*this)[idx];
+    switch (type)
+    {
+    case 0:
+        if (pix.IsExcluded() || pix.GetMeanErr()<0)
+            return kFALSE;
+        val = pix.GetMean();
+        return kTRUE;
+    case 1:
+        if (pix.IsExcluded() || pix.GetMeanErr()<0)
+            return kFALSE;
+        val = pix.GetMeanErr();
+        return kTRUE;
+    case 2:
+        if (pix.IsExcluded() || pix.GetSigmaErr()<0)
+            return kFALSE;
+        val = pix.GetSigma();
+        return kTRUE;
+    case 3:
+        if (pix.IsExcluded() || pix.GetSigmaErr()<0)
+            return kFALSE;
+        val = pix.GetSigmaErr();
+        return kTRUE;
+    case 4:
+        if (pix.IsExcluded())
+            return kFALSE;
+        val = pix.GetProb();
+        return val>=0;
+    default:
+        return kFALSE;
+    }
+
+  return kFALSE;
+
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimeCam.h	(revision 17960)
@@ -0,0 +1,29 @@
+#ifndef MARS_MCalibrationRelTimeCam
+#define MARS_MCalibrationRelTimeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationRelTimeCam : public MCalibrationCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+
+public:
+
+  MCalibrationRelTimeCam(const char *name=NULL, const char *title=NULL);
+
+  // Prints
+  void Print(Option_t *o="") const;
+  
+  // Others
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  ClassDef(MCalibrationRelTimeCam, 2)	// Container Rel. Arrival Time Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimePix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimePix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimePix.cc	(revision 17960)
@@ -0,0 +1,59 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrationRelTimePix                                                  //
+//                                                                         //
+// Storage container for relative arrival time calibration results         // 
+// of one Pixel (PMT).                                                     //
+// The following "calibration" constants can be retrieved:                 //
+// - GetTimeOffset(): The mean offset in relative times, 
+//   has to be added to any calculated relative time in the camera. 
+// - GetTimePrecision(): The Gauss sigma of histogrammed relative arrival 
+//   times for the calibration run. Gives an estimate about the timing 
+//   resolution.
+//
+// ALL RELATIVE TIMES HAVE TO BE CALCULATED W.R.T. PIXEL IDX 1 
+// (HARDWARE NUMBER: 2) !!
+//
+// See also: MHCalibrationRelTimePix, MHCalibrationRelTimeCam              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationRelTimePix.h"
+
+ClassImp(MCalibrationRelTimePix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MCalibrationRelTimePix::MCalibrationRelTimePix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationRelTimePix";
+  fTitle = title ? title : "Results of MHCalibrationRelTimePix ";
+
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimePix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimePix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationRelTimePix.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCalc.cc	(revision 17960)
@@ -0,0 +1,639 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  08/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationTestCalc
+//
+//   PreProcess(): Initialize pointers to MHCalibrationTestCam
+//               
+//   ReInit():     MCalibrationCam::InitSize(NumPixels) is called from MGeomApply (which allocates
+//                 memory in a TClonesArray of type MCalibrationChargePix)
+//                 Initializes pointer to MBadPixelsCam
+//
+//   Process():    Nothing to be done, histograms getting filled by MHCalibrationTestCam
+//
+//   PostProcess(): Print out interpolation results to file
+//
+//  Input Containers:
+//   MHCalibrationTestCam
+//   MBadPixelsCam
+//   MGeomCam
+//
+//  Output Containers:
+//   none
+//  
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationTestCalc.h"
+
+#include <TMath.h>
+#include <TSystem.h>
+
+#include <TH1.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+#include "MHCamera.h"
+
+#include "MHCalibrationTestCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MCalibrationTestCam.h"
+#include "MCalibrationTestPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MCalibrationTestCalc);
+
+using namespace std;
+
+const Float_t MCalibrationTestCalc::fgPhotErrLimit = 4.5;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets the pointer to fHTestCam and fGeom to NULL
+// Sets outputpath to "."
+// Sets outputfile to "TestCalibStat.txt"
+// Sets fPhotErrLimit to fgPhotErrLimit  
+//
+// Calls:
+// - Clear()
+//
+MCalibrationTestCalc::MCalibrationTestCalc(const char *name, const char *title)
+    : fBadPixels(NULL), fHTestCam(NULL), fCam(NULL), fGeom(NULL)
+{
+        
+  fName  = name  ? name  : "MCalibrationTestCalc";
+  fTitle = title ? title : "Task to output the results of MHCalibrationTestCam ";
+  
+  SetPhotErrLimit();
+
+  SetOutputPath();
+  SetOutputFile();
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+// - MGeomCam
+// - MHCalibrationTestCam
+// - MCalibrationTestCam
+// - MBadPixelsCam
+// 
+Bool_t MCalibrationTestCalc::ReInit(MParList *pList )
+{
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "No MGeomCam found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fHTestCam = (MHCalibrationTestCam*)pList->FindObject("MHCalibrationTestCam");
+  if (!fHTestCam)
+    {
+      *fLog << err << "Cannot find MHCalibrationTestCam... aborting" << endl;
+      *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationTestCam before..." << endl;
+      return kFALSE;
+    }
+
+  fCam = (MCalibrationTestCam*)pList->FindObject(AddSerialNumber("MCalibrationTestCam"));
+  if (!fCam)
+  {
+      *fLog << err << "Cannot find MCalibrationTestCam ... abort." << endl;
+      return kFALSE;
+  }
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+  if (!fBadPixels)
+  {
+      *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+      return kFALSE;
+  }
+
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Return if number of executions is null.
+//
+// Print out some statistics
+//
+Int_t MCalibrationTestCalc::PostProcess()
+{
+
+  if (GetNumExecutions()==0)
+    return kTRUE;
+
+  //
+  // Re-direct the output to an ascii-file from now on:
+  //
+  MLog asciilog;
+  asciilog.SetOutputFile(GetOutputFile(),kTRUE);
+  SetLogStream(&asciilog);
+  //
+  // Finalize calibration statistics
+  //
+  FinalizeCalibratedPhotons();
+  FinalizeNotInterpolated();
+  const Int_t maxbad = CalcMaxNumBadPixelsCluster();
+
+
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Pixel Interpolation status:" << endl;
+
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+  {
+      *fLog << " Not interpolateable Pixels:";
+      *fLog << " Inner: " << Form("%3i", fCam->GetNumUninterpolated(0));
+      *fLog << " Outer: " << Form("%3i", fCam->GetNumUninterpolated(1)) << endl;
+      *fLog << " Biggest not-interpolateable cluster: " << maxbad << endl;
+  }
+
+  fCam->SetNumUninterpolatedInMaxCluster(maxbad);
+
+  *fLog << endl;  
+  SetLogStream(&gLog);
+
+  return kTRUE;
+}
+
+
+// ------------------------------------------------------------------------
+//
+//
+// First loop: Calculate a mean and mean RMS of calibrated photons per area index 
+//             Include only MHCalibrationTestPix's which are not empty (not interpolated)
+//              
+// Second loop: Get weighted mean number of calibrated photons and its RMS
+//              excluding those deviating by more than fPhotErrLimit 
+//              sigmas from the mean (obtained in first loop). Set 
+//              MBadPixelsPix::kDeviatingNumPhots if excluded.
+// 
+void MCalibrationTestCalc::FinalizeCalibratedPhotons() const
+{
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  TArrayD lowlim      (nareas);
+  TArrayD upplim      (nareas);
+  TArrayD areaphotons (nareas); 
+  TArrayD sectorphotons(nsectors);
+  TArrayD areavars    (nareas); 
+  TArrayD sectorvars  (nsectors);
+  TArrayD fittedmean  (nareas); 
+  TArrayD fittedsigma (nareas);
+  TArrayI numareavalid(nareas); 
+  TArrayI numsectorvalid(nsectors);
+
+  //
+  // First loop: Get mean number of calibrated photons and the RMS
+  //             The loop is only to recognize later pixels with very deviating numbers
+  //
+  MHCamera camphotons(*fGeom,"Camphotons","Photons in Camera");
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MHCalibrationPix     &hist = (*fHTestCam)[i];
+      MCalibrationTestPix  &pix =  (MCalibrationTestPix&)(*fCam)[i];
+      //
+      // We assume that the pixels have been interpolated so far. 
+      // The MBadPixelsCam does not give any more information
+      //
+      if (hist.IsEmpty())
+        {
+          pix.SetExcluded();
+          continue;
+        }
+
+      const Double_t nphot    = hist.GetMean();
+      const Double_t nphoterr = hist.GetMeanErr();
+      const Int_t    aidx     = (*fGeom)[i].GetAidx();
+
+      camphotons.Fill(i,nphot);
+      camphotons.SetUsed(i);
+
+      pix.SetNumPhotons   ( nphot    );
+      pix.SetNumPhotonsErr( nphoterr );
+
+      areaphotons [aidx] += nphot;
+      areavars    [aidx] += nphot*nphot;
+      numareavalid[aidx] ++;
+    } 
+
+  for (UInt_t aidx=0; aidx<nareas; aidx++)
+    {
+      if (numareavalid[aidx] == 0)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid number of calibrated photons found "
+                << "in area index: " << aidx << endl;
+          continue;
+        }
+
+      if (numareavalid[aidx] == 1)
+        areavars[aidx]  = 0.;
+      else if (numareavalid[aidx] == 0)
+        {
+          areaphotons[aidx] = -1.;
+          areavars[aidx]    = -1.;
+        }
+      else
+        {
+          areavars[aidx]    = (areavars[aidx] - areaphotons[aidx]*areaphotons[aidx]/numareavalid[aidx]) 
+                            / (numareavalid[aidx]-1.);
+          areaphotons[aidx] = areaphotons[aidx] / numareavalid[aidx];
+        }
+      
+      if (areavars[aidx] < 0.)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid variance of calibrated photons found "
+                << "in area index: " << aidx << endl;
+          continue;
+        }
+
+      const Float_t areamean = areaphotons[aidx];
+      const Float_t areaerr  = TMath::Sqrt(areavars[aidx]);
+      
+      MCalibrationTestPix &avpix = (MCalibrationTestPix&)fCam->GetAverageArea(aidx);
+      avpix.SetNumPhotons   (areamean);
+      avpix.SetNumPhotonsErr(areaerr );
+
+      lowlim [aidx] = areamean - fPhotErrLimit*areaerr;
+      upplim [aidx] = areamean + fPhotErrLimit*areaerr;
+
+      TArrayI area(1);
+      area[0] = aidx;
+
+      TH1D *hist = camphotons.ProjectionS(TArrayI(),area,"_py",100);
+      hist->Fit("gaus","Q");
+      const Double_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+      const Double_t sigma = hist->GetFunction("gaus")->GetParameter(2);
+      const Int_t    ndf   = hist->GetFunction("gaus")->GetNDF();
+
+      if (ndf < 2)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of calibrated photons " 
+                << "in the camera with area index: " << aidx << endl;
+          *fLog << warn << GetDescriptor() << ": Number of dof.: " << ndf << " is smaller than 2 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+      
+      const Double_t prob = hist->GetFunction("gaus")->GetProb();
+
+      if (prob < 0.001)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of calibrated photons " 
+                << "in the camera with area index: " << aidx << endl;
+          *fLog << warn << GetDescriptor() << ": Fit probability " << prob 
+                << " is smaller than 0.001 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+      
+      fittedmean [aidx] = mean;
+      fittedsigma[aidx] = sigma;
+      
+      avpix.SetNumPhotons   (mean );
+      avpix.SetNumPhotonsErr(sigma);
+
+      lowlim  [aidx] = mean  - fPhotErrLimit*sigma;
+      upplim  [aidx] = mean  + fPhotErrLimit*sigma;
+
+      *fLog << inf << GetDescriptor() 
+            << ": Fitted number of calib. equiv. Cher. photons in area index " << aidx 
+            << ": "  << Form("%7.2f +- %6.2f",fittedmean[aidx],fittedsigma[aidx]) << endl;
+
+      delete hist;
+    }
+
+  *fLog << endl;
+
+  numareavalid.Reset();
+  areaphotons .Reset();
+  areavars    .Reset();
+
+  //
+  // Second loop: Get mean number of calibrated photons and its RMS excluding 
+  //              pixels deviating by more than fPhotErrLimit sigma. 
+  // 
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MHCalibrationPix &hist    = (*fHTestCam)[i];
+      MCalibrationTestPix  &pix =  (MCalibrationTestPix&) (*fCam)[i];
+
+      const Int_t    aidx         = (*fGeom)[i].GetAidx();
+      const Int_t    sector       = (*fGeom)[i].GetSector();
+      const Double_t nphot        = hist.GetMean();
+      const Double_t nphotpera    = nphot            / (*fGeom)[i].GetA();
+      const Double_t nphotperaerr = hist.GetMeanErr()/ (*fGeom)[i].GetA();
+
+      pix.SetNumPhotonsPerArea   ( nphotpera    );
+      pix.SetNumPhotonsPerAreaErr( nphotperaerr );
+
+      if ( nphot < lowlim[aidx] || nphot > upplim[aidx] )
+        {
+          *fLog << warn << GetDescriptor() << ": Number of photons: " 
+                << Form("%8.2f out of %3.1f sigma limit: ",nphot,fPhotErrLimit)
+                << Form("[%8.2f,%8.2f] pixel%4i",lowlim[aidx],upplim[aidx],i) << endl;
+          MBadPixelsPix &bad = (*fBadPixels)[i];
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingNumPhots );
+          bad.SetUnsuitable  ( MBadPixelsPix::kUnsuitableRun     );
+          continue;
+        }
+      
+      areavars     [aidx] += nphotpera*nphotpera;
+      areaphotons  [aidx] += nphotpera;
+      numareavalid [aidx] ++;
+
+      sectorvars    [sector] += nphotpera*nphotpera;
+      sectorphotons [sector] += nphotpera;
+      numsectorvalid[sector] ++;
+    } 
+
+  *fLog << endl;
+
+  for (UInt_t aidx=0; aidx<nareas; aidx++)
+    {
+      
+      if (numareavalid[aidx] == 1)
+        areavars[aidx] = 0.;
+      else if (numareavalid[aidx] == 0)
+        {
+          areaphotons[aidx] = -1.;
+          areavars[aidx]    = -1.;
+        }
+      else
+        {
+          areavars[aidx] = (areavars[aidx] - areaphotons[aidx]*areaphotons[aidx]/numareavalid[aidx]) 
+                         / (numareavalid[aidx]-1.);
+          areaphotons[aidx] /=  numareavalid[aidx];
+        }
+      
+
+      MCalibrationTestPix &avpix = (MCalibrationTestPix&)fCam->GetAverageArea(aidx);
+
+      if (areavars[aidx] < 0. || areaphotons[aidx] <= 0.)
+        {
+          *fLog << warn << GetDescriptor() 
+                << ": Mean number of photons per area in area index " 
+                << aidx << " could not be calculated! Mean: " << areaphotons[aidx] 
+                << " Variance: " << areavars[aidx] << endl;
+          avpix.SetExcluded();
+          continue;
+        }
+
+      const Float_t areaerr = TMath::Sqrt(areavars[aidx]);
+      
+      avpix.SetNumPhotonsPerArea   (areaphotons[aidx]);
+      avpix.SetNumPhotonsPerAreaErr(areaerr );
+
+      *fLog << inf << GetDescriptor() << ": Mean number of equiv. Cher. photons "
+            << "per area in area idx " << aidx << ": "  
+            << Form("%5.3f+-%5.4f  [ph/mm^2]",areaphotons[aidx],areaerr) << endl;
+    }
+
+  *fLog << endl;
+
+  for (UInt_t sector=0; sector<nsectors; sector++)
+    {
+      
+      if (numsectorvalid[sector] == 1)
+        sectorvars[sector] = 0.;
+      else if (numsectorvalid[sector] == 0)
+        {
+          sectorphotons[sector]  = -1.;
+          sectorvars[sector]     = -1.;
+        }
+      else
+        {
+          sectorvars[sector] = (sectorvars[sector] 
+                               - sectorphotons[sector]*sectorphotons[sector]/numsectorvalid[sector]
+                               ) 
+                             / (numsectorvalid[sector]-1.);
+          sectorphotons[sector] /=  numsectorvalid[sector];
+        }
+      
+      MCalibrationTestPix &avpix = (MCalibrationTestPix&)fCam->GetAverageSector(sector);
+
+      if (sectorvars[sector] < 0. || sectorphotons[sector] <= 0.)
+        {
+          *fLog << warn << GetDescriptor() 
+                << ": Mean number of calibrated photons per area in sector " 
+                << sector << " could not be calculated! Mean: " << sectorphotons[sector] 
+                << " Variance: " << sectorvars[sector] << endl;
+          avpix.SetExcluded();
+          continue;
+        }
+      
+  
+      const Float_t sectorerr = TMath::Sqrt(sectorvars[sector]);
+
+      avpix.SetNumPhotonsPerArea   (sectorphotons[sector]);
+      avpix.SetNumPhotonsPerAreaErr(sectorerr );
+
+      *fLog << inf << GetDescriptor() << ": Mean number of equiv. Cher. photons "
+            << "per area in sector " << sector << ":   "  
+            << Form("%5.3f+-%5.4f  [ph/mm^2]",sectorphotons[sector],sectorerr) << endl;
+    }
+
+  return;
+}
+
+
+// -----------------------------------------------------------------------------------------------
+//
+// Print out statistics about not interpolated pixels
+// 
+void MCalibrationTestCalc::FinalizeNotInterpolated() 
+{
+  
+  const Int_t areas  = fGeom->GetNumAreas();
+  TArrayI *newarr[areas];
+
+  for (Int_t aidx=0; aidx<areas; aidx++)
+    newarr[aidx] = new TArrayI(0);
+
+  for (Int_t i=0; i<fCam->GetSize(); i++)
+    {
+      const Int_t aidx = (*fGeom)[i].GetAidx();
+      MCalibrationTestPix &pix = (MCalibrationTestPix&)(*fCam)[i];
+      if (pix.IsExcluded())
+        {
+          const Int_t size = newarr[aidx]->GetSize();
+          newarr[aidx]->Set(size+1);
+          newarr[aidx]->AddAt(i,size);
+        }
+    }
+
+  Int_t num = 0;
+
+  for (Int_t aidx = 0; aidx<areas; aidx++)
+    {
+      *fLog << endl;
+      *fLog << " " << setw(7)
+            << "Not interpolated pixels by in area idx " << aidx << ": ";
+      for (Int_t i=0; i<newarr[aidx]->GetSize(); i++)
+        {
+          *fLog << newarr[aidx]->At(i) << " ";
+          num++;
+        }
+      fCam->SetNumUninterpolated(newarr[aidx]->GetSize(),aidx);
+      *fLog << endl;
+    }
+  
+  *fLog << " " << setw(7) << num << " total not interpolateable pixels " << endl;
+  
+}
+
+Int_t MCalibrationTestCalc::CalcMaxNumBadPixelsCluster()
+{
+
+  TArrayI arr(0);
+  
+  for (Int_t i=0; i<fCam->GetSize(); i++)
+    {
+      MCalibrationTestPix &pix = (MCalibrationTestPix&)(*fCam)[i];
+      if (pix.IsExcluded())
+        {
+        const Int_t s = arr.GetSize();
+        arr.Set(s+1);
+        arr[s] = i;
+        }
+    }
+  
+  const Int_t size = arr.GetSize();
+  
+  if (size == 0)
+    return 0;
+  
+  if (size == 1)
+    return 1;
+
+  TArrayI knownpixels(0);
+  Int_t clustersize    = 1;
+  Int_t oldclustersize = 0;
+  //
+  // Loop over the not-interpolateable pixels:
+  //
+  for (Int_t i=0; i<size; i++)
+    {
+
+      const Int_t id   = arr[i];
+      const Int_t knownsize = knownpixels.GetSize();
+      knownpixels.Set(knownsize+1);
+      knownpixels[knownsize] = id;
+      LoopNeighbours(arr, knownpixels, clustersize, id);
+      if (clustersize > oldclustersize)
+        oldclustersize = clustersize;
+      clustersize = 1;
+    }
+
+  return oldclustersize; 
+
+}
+
+
+void MCalibrationTestCalc::LoopNeighbours( const TArrayI &arr, TArrayI &knownpixels, Int_t &clustersize, const Int_t idx )
+{
+  
+  const MGeom &pix = (*fGeom)[idx];
+  const Byte_t neighbours = pix.GetNumNeighbors();
+
+  // 
+  // Loop over the next neighbours: 
+  // - Check if they are already in the list of known pixels
+  // - If not, call loopneighbours for the rest
+  // - grow clustersize for those
+  //
+  for (Int_t i=0;i<neighbours;i++)
+    {
+      const Int_t newid = pix.GetNeighbor(i);
+      Bool_t known = kFALSE;
+
+      for (Int_t j=knownpixels.GetSize()-1;j>=0;j--)
+        if (newid == knownpixels.At(j))
+          {
+            known = kTRUE;
+            break;
+          }
+      if (known)
+        continue;
+
+      for (Int_t k=0;k<arr.GetSize();k++)
+        if (newid == arr.At(k))
+          {
+            // This is an unknown, new pixel in the cluster!!
+            clustersize++;
+            const Int_t knownsize = knownpixels.GetSize();
+            knownpixels.Set(knownsize+1);
+            knownpixels[knownsize] = newid;
+            LoopNeighbours(arr, knownpixels, clustersize, newid);
+          }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the path for output file
+// 
+void MCalibrationTestCalc::SetOutputPath(TString path)
+{
+  fOutputPath = path;
+  if (fOutputPath.EndsWith("/"))
+    fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+void MCalibrationTestCalc::SetOutputFile(TString file)
+{ 
+  fOutputFile        = file; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the output file
+// 
+const char* MCalibrationTestCalc::GetOutputFile()
+{
+  return Form("%s/%s", (const char*)fOutputPath, (const char*)fOutputFile);
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCalc.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MCalibrationTestCalc
+#define MARS_MCalibrationTestCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrationTestCalc                                                   //
+//                                                                         //
+// Integrates the time slices of the all pixels of a calibration event     //
+// and substract the pedestal value                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MHCalibrationTestCam;
+class MCalibrationTestCam;
+class MBadPixelsCam;
+class MGeomCam;
+
+class MCalibrationTestCalc : public MTask
+{
+private:
+
+  static const Float_t fgPhotErrLimit;  //! Default for fPhotErrLimit (now set to: 4.)
+
+  // Variables
+  Float_t fPhotErrLimit;                // Limit acceptance nr. cal. phots w.r.t. area idx mean (in sigmas)
+
+  TString fOutputPath;                  // Path to the output file
+  TString fOutputFile;                  // Name of the output file
+  
+  // Pointers
+  MBadPixelsCam        *fBadPixels;     //! Bad Pixels
+  MHCalibrationTestCam *fHTestCam;      //! Calibrated Photons in the camera
+  MCalibrationTestCam  *fCam;           //! Storage Calibrated Photons in the camera
+  MGeomCam             *fGeom;          //! Camera geometry
+
+  // functions
+  const char* GetOutputFile();
+
+  void   FinalizeNotInterpolated();
+  void   FinalizeCalibratedPhotons() const;
+  Int_t  CalcMaxNumBadPixelsCluster();
+  void   LoopNeighbours( const TArrayI &arr, TArrayI &known, Int_t &clustersize, const Int_t idx );
+  
+  Bool_t ReInit     (MParList *pList); 
+  Int_t  PostProcess();
+
+public:
+
+  MCalibrationTestCalc(const char *name=NULL, const char *title=NULL);
+
+  void SetOutputFile  ( TString file="TestCalibStat.txt" );
+  void SetOutputPath  ( TString path="."                 );
+  void SetPhotErrLimit( const Float_t f=fgPhotErrLimit   ) { fPhotErrLimit = f; }  
+  
+  ClassDef(MCalibrationTestCalc, 1)   // Task retrieving the results of MHCalibrationTestCam
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCam.cc	(revision 17960)
@@ -0,0 +1,310 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationTestCam                                               
+//                                                               
+// Storage container for calibrated photons, with calibration applied on the 
+// same calibration run (see MHCalibrationTestCam and MHCalibrationTestPix).
+//
+// See also: MCalibrationTestPix, MCalibrationTestCalc, MCalibrationQECam
+//           MHCalibrationTestPix, MHCalibrationTestCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationTestCam.h"
+#include "MCalibrationTestPix.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+ClassImp(MCalibrationTestCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets all pointers to 0
+// 
+// Creates a TClonesArray of MCalibrationTestPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibrationTestCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationTestPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibrationTestCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationTestPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibrationTestCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+// Calls:
+// - Clear()
+//
+MCalibrationTestCam::MCalibrationTestCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationTestCam";
+  fTitle = title ? title : "Storage container for the Calibration Test Information in the camera";
+  
+  Clear();
+}
+
+// --------------------------------------
+//
+// Sets all variable to 0.
+// Sets all flags to kFALSE
+// Calls MCalibrationCam::Clear()
+//
+void MCalibrationTestCam::Clear(Option_t *o)
+{
+
+  fNumUninterpolatedInMaxCluster = 0; 
+
+  return;
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationTestPix's in the ranges from - to to fPixels
+//
+void MCalibrationTestCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationTestPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationTestPix's in the ranges from - to to fAverageAreas
+//
+void MCalibrationTestCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationTestPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationTestPix's in the ranges from - to to fAverageSectors
+//
+void MCalibrationTestCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationTestPix,i);
+}
+
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollections
+// - fAverageAreas
+// - fAverageBadAreas
+// using the virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationTestCam::InitAverageAreas(const UInt_t i)
+{
+
+  const UInt_t save = GetAverageAreas();
+
+  if (i==save)
+    return;
+  
+  fNumUninterpolated.Set(i);
+  
+  MCalibrationCam::InitAverageAreas(i);
+  
+  return;
+  
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not FitValid
+//
+void MCalibrationTestCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << "Calibrated (or interpolated) pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationTestPix *pix;
+  while ((pix=(MCalibrationTestPix*)Next()))
+    {
+      
+      if (!pix->IsExcluded()) 
+	{                            
+
+          *fLog << all 
+                << Form("%s%3i","Pixel: ",pix->GetPixId())
+		<< Form("%s%4.2f%s%4.2f","  Num.Photons: ",pix->GetNumPhotons(),"+-",pix->GetNumPhotonsErr()) 
+		<< Form("%s%4.2f%s%4.2f","  Num.Photons/mm^2: ",pix->GetNumPhotonsPerArea()
+                        ,"+-",pix->GetNumPhotonsPerAreaErr()) 
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Not interpolated pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationTestPix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+        *fLog << all << pix->GetPixId() << " ";
+        id++;
+
+        if (!(id % 25))
+          *fLog << endl;
+      }
+  }
+  
+  *fLog << endl;
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Areas:" << endl;
+  *fLog << all << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationTestPix*)Next5()))
+  {
+    *fLog << all << Form("%s%3i","Area Idx: ",pix->GetPixId())
+          << Form("%s%4.2f%s%4.2f","  Num.Photons: ",pix->GetNumPhotons(),"+-",pix->GetNumPhotonsErr()) 
+          << Form("%s%4.2f%s%4.2f","  Num.Photons/mm^2: ",pix->GetNumPhotonsPerArea()
+                  ,"+-",pix->GetNumPhotonsPerAreaErr()) 
+          << endl;
+  }
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Sectors:" << endl;
+  *fLog << all << endl;
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationTestPix*)Next6()))
+  {
+    *fLog << all << Form("%s%3i","Sector: ",pix->GetPixId())
+          << Form("%s%4.2f%s%4.2f","  Num.Photons: ",pix->GetNumPhotons(),"+-",pix->GetNumPhotonsErr()) 
+          << Form("%s%4.2f%s%4.2f","  Num.Photons/mm^2: ",pix->GetNumPhotonsPerArea()
+                  ,"+-",pix->GetNumPhotonsPerAreaErr()) 
+          << endl;
+  }
+  *fLog << all << endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// 0: Number Photons
+// 1: Error Number Photons
+// 2: Number photons per area
+// 3: Error Number Photons per area
+// 4: Pixels which are not interpolateable
+//
+Bool_t MCalibrationTestCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ MCalibrationTestPix &pix = (MCalibrationTestPix&)(*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotons();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotonsErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotonsPerArea();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotonsPerAreaErr();
+      break;
+    case 4:
+      if (!pix.IsExcluded())
+        return kFALSE;
+      val = 1;
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+}
+
+void  MCalibrationTestCam::SetNumUninterpolated( const UInt_t i, const Int_t aidx ) 
+{
+
+  if (aidx < 0)
+    return;
+
+  if (aidx < fNumUninterpolated.GetSize())
+    fNumUninterpolated[aidx] = i;  
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationTestCam.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MCalibrationTestCam
+#define MARS_MCalibrationTestCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationTestCam : public MCalibrationCam
+{
+private:
+  
+  TArrayI fNumUninterpolated;             // Number uninterpolated Pixels per area index 
+  Int_t   fNumUninterpolatedInMaxCluster; // Number of not interpolateable pixels in biggest cluster
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+  
+public:
+
+  MCalibrationTestCam(const char *name=NULL, const char *title=NULL);
+  
+  void Clear (Option_t *o="");
+  
+  const Int_t                GetNumUninterpolated ( Int_t aidx ) const { 
+	return fNumUninterpolated[aidx];  }
+  const Int_t                GetNumUninterplatedInMaxCluster ()  const { 
+	return fNumUninterpolatedInMaxCluster; }
+  Bool_t                     GetPixelContent      ( Double_t &val, Int_t idx, 
+	                                            const MGeomCam &cam, Int_t type=0) const;
+  
+  void  InitAverageAreas       ( const UInt_t i);
+
+  // Prints
+  void  Print (Option_t *o="") const;
+
+  // Setters   
+  void  SetNumUninterpolated            ( const UInt_t i, const Int_t aidx );
+  void  SetNumUninterpolatedInMaxCluster( const UInt_t i ) { fNumUninterpolatedInMaxCluster = i; }
+
+  // Draw
+  void DrawPixelContent( Int_t num) const {}
+  
+  ClassDef(MCalibrationTestCam, 1) // Container Test Calibration Results Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationTestPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationTestPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationTestPix.cc	(revision 17960)
@@ -0,0 +1,75 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   08/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                     
+// MCalibrationTestPix                                     
+//                                                     
+// Base Storage container for the test result of a calibration pixel. 
+// Holds calibrated number of photons, number of photons per area (mm^2) and 
+// their errors. Not interpolateable pixels are declared excluded.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationTestPix.h"
+
+ClassImp(MCalibrationTestPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Sets:
+// - fPixId to -1
+//
+// Calls:
+// - Clear()
+//
+MCalibrationTestPix::MCalibrationTestPix(const char *name, const char *title)
+    : fPixId(-1)
+{
+
+  fName  = name  ? name  : "MCalibrationTestPix";
+  fTitle = title ? title : "Container of the fit results of MHCalibrationTestPix ";
+
+  Clear();
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all data members to -1
+// - all excluded to kFALSE
+//
+void MCalibrationTestPix::Clear(Option_t *o)
+{
+
+  fNumPhotons           =  -1.;
+  fNumPhotonsErr        =  -1.;
+  fNumPhotonsPerArea    =  -1.;
+  fNumPhotonsPerAreaErr =  -1.;
+
+  SetExcluded          ( kFALSE );
+}
+
Index: branches/Mars_McMismatchStudy/mcalib/MCalibrationTestPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MCalibrationTestPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MCalibrationTestPix.h	(revision 17960)
@@ -0,0 +1,49 @@
+#ifndef MARS_MCalibrationTestPix
+#define MARS_MCalibrationTestPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCalibrationTestPix : public MParContainer
+{
+private:
+
+  Int_t   fPixId;                // Software PixId (needed to get Id in calls to Next())
+  Bool_t  fExcluded;             // If pixels is excluded or not (not interpolateable)
+
+  Float_t fNumPhotons;           // Number of calibrated photons
+  Float_t fNumPhotonsErr;        // Error Number of calibrated photons
+  Float_t fNumPhotonsPerArea;    // Number of calibrated photons per mm^2     
+  Float_t fNumPhotonsPerAreaErr; // Error Number of calibrated photons per mm^2
+
+public:
+
+  MCalibrationTestPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationTestPix() {}
+  
+  void Clear(Option_t *o="");
+  
+  // Getters
+  Float_t GetNumPhotons          () const { return fNumPhotons;           }
+  Float_t GetNumPhotonsErr       () const { return fNumPhotonsErr;        }
+  Float_t GetNumPhotonsPerArea   () const { return fNumPhotonsPerArea;    }
+  Float_t GetNumPhotonsPerAreaErr() const { return fNumPhotonsPerAreaErr; }
+  Int_t   GetPixId               () const { return fPixId;                }
+  
+  Bool_t  IsExcluded             () const { return fExcluded;             }
+
+  // Setters
+  void SetPixId               ( const Int_t   i )       { fPixId                = i; }
+  void SetExcluded            ( const Bool_t  b=kTRUE ) { fExcluded             = b; }
+  void SetNumPhotons          ( const Float_t f )       { fNumPhotons           = f; }          
+  void SetNumPhotonsErr       ( const Float_t f )       { fNumPhotonsErr        = f; }       
+  void SetNumPhotonsPerArea   ( const Float_t f )       { fNumPhotonsPerArea    = f; }   
+  void SetNumPhotonsPerAreaErr( const Float_t f )       { fNumPhotonsPerAreaErr = f; }
+
+
+  ClassDef(MCalibrationTestPix, 1)	// Container for Calibration Test Results Pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mcalib/MMcCalibrationCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MMcCalibrationCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MMcCalibrationCalc.cc	(revision 17960)
@@ -0,0 +1,360 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 12/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMcCalibrationCalc
+//
+//  Input Containers:
+//   MMcConfigRunHeader
+//   MRawRunHeader
+//   MMcFadcHeader
+//   MHillas
+//   MNewImagePar
+//   MMcEvt
+//
+//  Output Containers:
+//  (containers mus exist already, they are filled with new values).
+//   MCalibrationChargeCam
+//   MCalibrationQECam  
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcCalibrationCalc.h"
+
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargeCam.h"
+
+#include "MCalibrationQEPix.h"
+#include "MCalibrationQECam.h"
+
+#include "MGeomCam.h"
+#include "MRawRunHeader.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MHillas.h"
+#include "MImagePar.h"
+#include "MNewImagePar.h"
+
+#include "MMcEvt.hxx"
+#include "MMcFadcHeader.hxx"
+
+ClassImp(MMcCalibrationCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Default value for fMinSize is 1000 ADC counts. This must be
+// set in general by the user (SetMinSize), since it depends among other things
+// on the signal extractor used.
+//
+MMcCalibrationCalc::MMcCalibrationCalc(const char *name, const char *title): fMinSize(1000)
+{
+    fName  = name  ? name  : "MMcCalibrationCalc";
+    fTitle = title ? title : "Calculate and write conversion factors into MCalibrationChargeCam and MCalibrationQECam containers";
+}
+
+// --------------------------------------------------------------------------
+//
+// 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(AddSerialNumber("MRawRunHeader"));
+    if (!run)
+    {
+      *fLog << warn << "Warning - cannot check file type, " << AddSerialNumber("MRawRunHeader") 
+	    << " not found." << endl;
+      return kTRUE;
+    }
+
+    return  run->IsMonteCarloRun();
+}
+
+// --------------------------------------------------------------------------
+//
+// Look for all necessary containers and create histograms
+//
+Int_t MMcCalibrationCalc::PreProcess(MParList *pList)
+{
+    fADC2PhotEl = 0;
+    fPhot2PhotEl = 0;
+
+    fCalCam = (MCalibrationChargeCam*) pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+    if (!fCalCam)
+    {
+        *fLog << err << AddSerialNumber("MCalibrationChargeCam") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fQECam = (MCalibrationQECam*) pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+    if (!fQECam)
+    {
+        *fLog << err << AddSerialNumber("MCalibrationQECam") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHillas = (MHillas*) pList->FindObject(AddSerialNumber("MHillas"));
+    if ( !fHillas)
+    {
+        *fLog << err << AddSerialNumber("MHillas") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNew = (MNewImagePar*)pList->FindObject(AddSerialNumber("MNewImagePar"));
+    if (!fNew)
+    {
+        *fLog << err << AddSerialNumber("MNewImagePar") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPar = (MImagePar*)pList->FindObject(AddSerialNumber("MImagePar"));
+    if (!fPar)
+    {
+        *fLog << err << AddSerialNumber("MImagePar") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*) pList->FindObject(AddSerialNumber("MMcEvt"));
+    if (!fMcEvt)
+    {
+        *fLog << err << AddSerialNumber("MMcEvt") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Create histograms:
+    //
+
+    fHistADC2PhotEl = new TH1F(AddSerialNumber("ADC2PhotEl"), "log10(fPhotElfromShower/fSize)", 1500, -3., 3.);
+    fHistADC2PhotEl->SetXTitle("log_{10}(fPhotElfromShower / fSize) [photel/ADC count]");
+
+
+    fHistPhot2PhotEl = new TH1F(AddSerialNumber("Phot2PhotEl"), "Photon conversion efficiency", 1000, 0., 1.);
+    fHistPhot2PhotEl->SetXTitle("Overall photon conversion efficiency [photoelectron/photon]");
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the runtype.
+// Search for MGeomCam and MMcFadcHeader.
+//
+Bool_t MMcCalibrationCalc::ReInit(MParList *pList)
+{
+  //
+  // If it is no MC file display error and exit
+  //
+  if (!CheckRunType(pList))
+  {
+      *fLog << err << "MMcCalibrationCalc can only be used with MC files... aborting." << endl;
+      return kFALSE;
+  }
+
+  //
+  // Now check the existence of all necessary containers.
+  //
+  fGeom = (MGeomCam*) pList->FindObject(AddSerialNumber("MGeomCam"));
+  if (!fGeom)
+  {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fHeaderFadc = (MMcFadcHeader*)pList->FindObject(AddSerialNumber("MMcFadcHeader"));
+  if (!fHeaderFadc)
+  {
+      *fLog << err << AddSerialNumber("MMcFadcHeader") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  for (UInt_t ipix = 0; ipix < fGeom->GetNumPixels(); ipix++)
+  {
+      if (fHeaderFadc->GetPedestalRmsHigh(ipix) > 0 ||
+	  fHeaderFadc->GetPedestalRmsLow(ipix)  > 0 )
+      {
+          *fLog << err << "Trying to calibrate the data using a Camera file produced with added noise." << endl;
+          *fLog << "Please use a noiseless file for calibration... aborting." << endl << endl;
+	  return kFALSE;
+      }
+  }
+
+  // Now check the light collection for inner and outer pixels to
+  // calculate the ratio between the two. FIXME! Light collection
+  // depends on the incidence angle of the light w.r.t. the camera
+  // plane. For the moment we take the ratio for light impinging
+  // perpendicular to the camera plane.
+  //
+  MMcConfigRunHeader* mcconfig = (MMcConfigRunHeader*) pList->FindObject(AddSerialNumber("MMcConfigRunHeader"));
+  if (!mcconfig)
+    {
+      *fLog << err << AddSerialNumber("MMcConfigRunHeader") << " not found... aborting." << endl;
+      return kFALSE;
+    }
+  const TArrayF &innerlightcoll = mcconfig->GetLightCollectionFactor();
+  const TArrayF &outerlightcoll = mcconfig->GetLightCollectionFactorOuter();
+
+  // In principle outer pixels seem to have a different average light 
+  // collection efficiency than outer ones. We set here the factor between
+  // the two.
+
+  fOuterPixelsLightCollection = outerlightcoll[90] / innerlightcoll[90]; 
+  // (at angle = 90 deg)
+
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Obtain average ratio of photons in camera to image Size.
+//
+Int_t MMcCalibrationCalc::Process()
+{
+    //
+    // Exclude events with some high-gain saturated pixel
+    //
+    if (fPar->GetNumSatPixelsHG()>0)
+        return kTRUE;
+
+    const Float_t size = fHillas->GetSize(); 
+    const Float_t innersize = fNew->GetInnerSize();
+
+    // Size will at this point be in ADC counts (still uncalibrated)
+    //
+    // Exclude events with low Size (larger fluctuations)
+    //   
+
+    if (size < fMinSize)
+        return kTRUE;
+
+    //
+    // PATCH: Convert number of photoelectrons in camera to the approximate number 
+    // of photoelectrons that would have been registered if all pixels had the same
+    // light collection efficiency as inner ones (called here "corrected_photel").
+    //
+ 
+    const Float_t corrected_photel = (Float_t) fMcEvt->GetPhotElfromShower() /
+      (fOuterPixelsLightCollection + innersize / size * (1. - fOuterPixelsLightCollection));
+
+    fHistADC2PhotEl->Fill(TMath::Log10(corrected_photel/size));
+    fHistPhot2PhotEl->Fill( corrected_photel / (Float_t) fMcEvt->GetPassPhotCone() );
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the MCalibrationCam object
+//
+Int_t MMcCalibrationCalc::PostProcess()
+{
+    const Stat_t n = fHistADC2PhotEl->GetEntries();
+    if (n<1)
+    {
+        *fLog << err << "No events read... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPhot2PhotEl = fHistPhot2PhotEl->GetMean();   
+    // Average quantum efficiency. For now we will set this value for all pixels, although
+    // even in MC there may be differences from pixel to pixel, if the .dat file containing 
+    // QE vs lambda, input of the camera simulation, has different QE curves for different
+    // pixels. FIXME?
+
+    MCalibrationQEPix &avqepix = (MCalibrationQEPix&)(fQECam->GetAverageArea(0));
+    avqepix.SetAverageQE(fPhot2PhotEl); // Needed by MCalibrateData!
+
+    //
+    // Find peak of log10(photel/Size) histogram:
+    //
+    const Int_t reach = 2;
+    Stat_t summax = 0;
+    Int_t  mode   = 0;
+    for (Int_t ibin = 1+reach; ibin <= fHistADC2PhotEl->GetNbinsX()-reach; ibin++)
+    {
+        const Stat_t sum = fHistADC2PhotEl->Integral(ibin-reach, ibin+reach);
+
+        if (sum <= summax)
+            continue;
+
+        summax = sum;
+        mode = ibin;
+    }
+
+    fADC2PhotEl = TMath::Power(10, fHistADC2PhotEl->GetBinCenter(mode));
+
+    const Int_t num = fCalCam->GetSize();
+
+    for (int i=0; i<num; i++)
+    {
+        MCalibrationChargePix &calpix = (MCalibrationChargePix&)(*fCalCam)[i];
+	MCalibrationQEPix     &qepix  = (MCalibrationQEPix&)    (*fQECam) [i];
+
+	Float_t qe = fPhot2PhotEl;
+	if (fGeom->GetPixRatio(i) < 1.)
+	  qe *= fOuterPixelsLightCollection;
+	qepix.SetAverageQE(qe);
+
+	qepix.SetAvNormFFactor(1.);
+	// This factor should convert the default average QE for different colors to 
+        // average QE for a spectrum like that of Cherenkov light (see the documentration 
+	// of MCalibrationQEPix). 
+	// Here we obtain average QE using already a Cherenkov spectrum so AvNormFFactor
+	// must be 1.
+
+	
+	Float_t factor = fADC2PhotEl;
+
+	//
+	// We take into account the (possibly) different gain of outer pixels:
+	// FIXME: we are now assuming that all inner pixels have the same gain, and all 
+	// outer pixels have the same gain (different from inner ones though). This can 
+        // only be like this in camera 0.7, but might change in future versions of camera.
+	//
+
+	if (fGeom->GetPixRatio(i) < 1.)
+	  factor *= fHeaderFadc->GetAmplitud()/fHeaderFadc->GetAmplitudOuter();
+
+        calpix.SetMeanConvFADC2Phe(factor);
+        calpix.SetMeanConvFADC2PheVar(0.);
+
+        calpix.SetMeanFFactorFADC2Phot(0.);
+    }
+
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mcalib/MMcCalibrationCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/MMcCalibrationCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/MMcCalibrationCalc.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MMcCalibrationCalc
+#define MARS_MMcCalibrationCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MGeomCam;
+class MHillas;
+class MImagePar;
+class MNewImagePar;
+class MMcEvt;
+class MMcFadcHeader;
+
+class TH1F;
+
+class MMcCalibrationCalc : public MTask
+{
+private:
+    MCalibrationChargeCam     *fCalCam;
+    MCalibrationQECam         *fQECam;    
+    MGeomCam                  *fGeom;
+    MHillas                   *fHillas;
+    MNewImagePar              *fNew;
+    MImagePar                 *fPar;
+    MMcEvt                    *fMcEvt;
+    MMcFadcHeader             *fHeaderFadc;
+
+    Float_t fADC2PhotEl;   // Conversion factor (photel / ADC count). FOR INER PIXELS
+    Float_t fPhot2PhotEl;  // Conversion factor (photons / photoelectron) = average QE. FOR INER PIXELS
+    Long_t  fEvents;
+    Float_t fOuterPixelsLightCollection; // Light collection efficiency (plexiglas, light guide) of 
+                                         // outer pixels w.r.t inner ones
+
+    Float_t fMinSize; 
+    // Minimum SIZE (before calibration, ADC counts) an event must have to be considered in the
+    // calculation of the calibration constants.
+
+    TH1F*   fHistADC2PhotEl;
+    TH1F*   fHistPhot2PhotEl; // Histograms for monitoring the calibration.
+
+    Bool_t CheckRunType(MParList *pList) const;
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MMcCalibrationCalc(const char *name=NULL, const char *title=NULL);
+
+    TH1F*   GetHistADC2PhotEl() { return fHistADC2PhotEl; }
+    TH1F*   GetHistPhot2PhotEl() { return fHistPhot2PhotEl; }
+
+    void SetMinSize(Float_t x) { fMinSize = x; }
+
+    ClassDef(MMcCalibrationCalc, 0)   // Task which obtains, for MC files, the calibration factor from ADC counts to photons. 
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcalib/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mcalib/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcalib/Makefile	(revision 17960)
@@ -0,0 +1,70 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Calib
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mhcalib -I../mhbase \
+           -I../manalysis -I../mraw -I../mtools -I../mmc -I../mhist  \
+           -I../mimage -I../msignal -I../mbadpixels -I../mpedestal -I../mcore
+# mhbase:    MBinning MH 
+# mgui:      MCamEvent (McalibrationCam)
+# mgeom:     MGeomCam (McalibrationCam - necessary?)
+# manalysis: MExtractedSignal, MCerPhotEvt (move to mcalib?)
+# mraw:      MRawRunHeader, MRawEvtHeader, MRawEvtPixelIter (3xMCalibrationCalc)
+# mmc:       MMcFadcHeader, MMcEvt
+# mimage     MHillas
+
+SRCFILES = MCalibColorSet.cc \
+	   MCalibColorSteer.cc \
+	   MCalibCalcFromPast.cc \
+	   MCalibrateData.cc \
+	   MCalibrateFact.cc \
+	   MCalibConstCam.cc \
+	   MCalibConstPix.cc \
+	   MCalibrationPattern.cc \
+	   MCalibrationPatternDecode.cc \
+	   MCalibrateRelTimes.cc \
+           MCalibrationCam.cc \
+           MCalibrationPix.cc  \
+           MCalibrationPulseTimeCam.cc \
+           MCalibrationRelTimeCam.cc \
+           MCalibrationRelTimePix.cc \
+	   MCalibrationRelTimeCalc.cc \
+           MCalibrationQECamMagic.cc \
+           MCalibrationQECam.cc \
+           MCalibrationQEPix.cc  \
+	   MCalibrationTestCalc.cc \
+	   MCalibrationTestCam.cc \
+	   MCalibrationTestPix.cc \
+	   MCalibrationChargeCalc.cc \
+           MCalibrationChargeCam.cc \
+           MCalibrationChargePix.cc  \
+           MCalibrationBlindCam.cc  \
+           MCalibrationBlindPix.cc  \
+           MCalibrationBlindCamOneOldStyle.cc  \
+           MCalibrationBlindCamTwoNewStyle.cc  \
+           MCalibrationBlindCamThreeNewStyle.cc  \
+           MCalibrationChargePINDiode.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mcamera/CameraIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/CameraIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/CameraIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mcamera/CameraLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/CameraLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/CameraLinkDef.h	(revision 17960)
@@ -0,0 +1,22 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class 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 MCameraTH+;
+#pragma link C++ class MCameraTD+;
+#pragma link C++ class MCameraRecTemp+;
+#pragma link C++ class MCameraActiveLoad+;
+#pragma link C++ class MCameraCentralPix+;
+#pragma link C++ class MCameraCalibration+;
+#pragma link C++ class MCameraPowerSupply+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraAUX.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraAUX.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraAUX.cc	(revision 17960)
@@ -0,0 +1,39 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraAUX
+//
+// Class Version 2:
+//  + Float_t fTempCountingHouse1; // [deg C] Temperature sensor in the counting house 1
+//  + Float_t fTempCountingHouse2; // [deg C] Temperature sensor in the counting house 2
+//  + Float_t fTempCountingHouse3; // [deg C] Temperature sensor in the counting house 3
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraAUX.h"
+
+ClassImp(MCameraAUX);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mcamera/MCameraAUX.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraAUX.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraAUX.h	(revision 17960)
@@ -0,0 +1,42 @@
+#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
+
+    Float_t fTempCountingHouse1; // [deg C] Temperature sensor in the counting house 1
+    Float_t fTempCountingHouse2; // [deg C] Temperature sensor in the counting house 2
+    Float_t fTempCountingHouse3; // [deg C] Temperature sensor in the counting house 3
+
+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;  }
+
+    Float_t GetTempCountingHouse1() const { return fTempCountingHouse1; }
+    Float_t GetTempCountingHouse2() const { return fTempCountingHouse2; }
+    Float_t GetTempCountingHouse3() const { return fTempCountingHouse3; }
+
+    ClassDef(MCameraAUX, 2) // Container storing information about the Camera auxiliary system
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraActiveLoad.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraActiveLoad.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraActiveLoad.cc	(revision 17960)
@@ -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): Daniel Mazin, 04/2005 <mailto:mazin@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraActiveLoad
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraActiveLoad.h"
+
+ClassImp(MCameraActiveLoad);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mcamera/MCameraActiveLoad.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraActiveLoad.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraActiveLoad.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MCameraActiveLoad
+#define MARS_MCameraActiveLoad
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCameraActiveLoad : public MParContainer
+{
+    friend class MReportCamera;
+
+private:
+    Bool_t fStatus;               // Status of active loads (0xff means: n/a)
+
+    Float_t fVoltage360A;         // [V] Voltage of 360V power supply A
+    Float_t fIntens360A;          // [mA] Intensity of 360V power supply A
+    Float_t fVoltage360B;         // [V] Voltage of 360V power supply B
+    Float_t fIntens360B;          // [mA] Intensity of 360V power supply B
+    Float_t fVoltage175A;         // [V] Voltage of 175V power supply A
+    Float_t fIntens175A;          // [mA] Intensity of 175V power supply A
+    Float_t fVoltage175B;         // [V] Voltage of 175V power supply B
+    Float_t fIntens175B;          // [mA] Intensity of 175V power supply B
+
+public:
+    MCameraActiveLoad()
+    {
+        fName  = "MCameraActiveLoad";
+        fTitle = "Container storing information about the Camera Active Load system";
+    }
+
+    Bool_t  GetStatus() const      { return fStatus;      }
+
+    Float_t GetVoltage360A() const { return fVoltage360A; }
+    Float_t GetIntens360A() const  { return fIntens360A;  }
+    Float_t GetVoltage360B() const { return fVoltage360B; }
+    Float_t GetIntens360B() const  { return fIntens360B;  }
+    Float_t GetVoltage175A() const { return fVoltage175A; }
+    Float_t GetIntens175A() const  { return fIntens175A;  }
+    Float_t GetVoltage175B() const { return fVoltage175B; }
+    Float_t GetIntens175B() const  { return fIntens175B;  }
+
+    ClassDef(MCameraActiveLoad, 1) // Container storing information about the Active Loads of the Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraCalibration.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraCalibration.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraCalibration.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraCalibration.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraCalibration.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraCalibration.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraCentralPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraCentralPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraCentralPix.cc	(revision 17960)
@@ -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): Daniel Mazin, 04/2005 <mailto:mazin@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraCentralPix
+//
+// Class Version 2:
+// ----------------
+//   + Int_t fDC
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraCentralPix.h"
+
+ClassImp(MCameraCentralPix);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mcamera/MCameraCentralPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraCentralPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraCentralPix.h	(revision 17960)
@@ -0,0 +1,32 @@
+#ifndef MARS_MCameraCentralPix
+#define MARS_MCameraCentralPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCameraCentralPix : public MParContainer
+{
+    friend class MReportCamera;
+
+private:
+    Bool_t fStatus; // Status of central pixel
+
+    Int_t fDC;     // DC current in ADC counts
+
+public:
+    MCameraCentralPix() : fDC(0)
+    {
+        fName  = "MCameraCentralPix";
+        fTitle = "Container storing information about the Camera Central Pixel";
+    }
+
+    Bool_t GetStatus() const     { return fStatus; }
+    Bool_t GetStatusCPix() const { return fStatus; } // deprecated - for compatibility only
+
+    Int_t GetDC() const { return fDC; }
+
+    ClassDef(MCameraCentralPix, 2) // Container storing information about the Central Pixel status
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraCooling.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraCooling.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraCooling.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraCooling.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraCooling.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraCooling.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraDC.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraDC.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraDC.cc	(revision 17960)
@@ -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, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraDC (PRELIMINARY)
+//
+//
+// Version 2:
+// ----------
+//   + fStatus
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#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)
+    : fStatus(0), fArray(size)
+{
+    fName  = name  ? name  : "MCameraDC";
+    fTitle = title ? title : "Storage container for the pixel currents";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete a DC report context
+//
+Int_t MCameraDC::Interprete(TString &str, Int_t len)
+{
+    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 nn=sscanf(hex, "%4x", &c);
+        if (nn!=1)
+        {
+            *fLog << warn << "WARNING - Reading hexadecimal DC information." << endl;
+            return kCONTINUE;
+        }
+
+        fArray[i++] = 0.001*c;
+    }
+
+    str.Remove(0, pos-str.Data()); // Remove DC currents
+    str=str.Strip(TString::kLeading);
+
+    return str.IsNull() ? kTRUE : kCONTINUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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: branches/Mars_McMismatchStudy/mcamera/MCameraDC.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraDC.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraDC.h	(revision 17960)
@@ -0,0 +1,56 @@
+#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
+{
+    friend class MReportCamera;
+    friend class MReportCurrents;
+private:
+    Byte_t  fStatus; // CaCo monitored status of the High Voltage [0-9], Cam.HV.PS_state
+
+    TArrayF fArray;  // [nA] Unsigned Int!
+
+    Int_t Interprete(TString &str, Int_t len=0);
+
+public:
+    MCameraDC(Int_t size=577, const char *name=NULL, const char *title=NULL);
+
+    Byte_t GetStatus() const { return  fStatus; }
+
+    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
+    {
+        if (idx>=fArray.GetSize())
+            return kFALSE;
+
+        val = fArray[idx];
+        return val>0;
+    }
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MCameraDC, 2) // Storage Container for the Currents (PRELIMINARY)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraHV.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraHV.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraHV.cc	(revision 17960)
@@ -0,0 +1,39 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraHV
+//
+//
+// Class Version 2:
+//  + TString fFileName; // Filename for the HV settings
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraHV.h"
+
+ClassImp(MCameraHV);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mcamera/MCameraHV.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraHV.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraHV.h	(revision 17960)
@@ -0,0 +1,65 @@
+#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
+
+    TString fFileName;      // Filename for the HV settings
+
+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(); }
+
+    Double_t operator[](const UInt_t idx) { return fHV[idx]; }
+
+    void   DrawPixelContent(Int_t num) const { }
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+        if (idx>=fHV.GetSize())
+            return kFALSE;
+
+        val = fHV[idx];
+        return val>0;
+    }
+
+    ClassDef(MCameraHV, 2) // Container storing information about the Camera HV
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraLV.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraLV.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraLV.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraLV.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraLV.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraLV.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraLid.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraLid.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraLid.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraLid.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraLid.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraLid.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraLids.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraLids.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraLids.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraLids.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraLids.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraLids.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraPowerSupply.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraPowerSupply.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraPowerSupply.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraPowerSupply.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraPowerSupply.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraPowerSupply.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mcamera/MCameraRecTemp.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraRecTemp.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraRecTemp.cc	(revision 17960)
@@ -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, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Florian Goebel 11/2005 <mailto:fgoebel@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraRecTemp
+//
+// Class Version 2:
+// ----------------
+//   + Bool_t  fIsValid; // fTD contains valid information
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraRecTemp.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCameraRecTemp);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCameraRecTemp::MCameraRecTemp(Int_t size, const char *name, const char *title)
+    : fRecTemp(size), fIsValid(kTRUE)
+{
+    fName  = name  ? name  : "MCameraRecTemp";
+    fTitle = title ? title : "Storage container for the receiver board temperatures";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the receiver board temperature part of the report
+//
+Bool_t MCameraRecTemp::InterpreteRecTemp(TString &str)
+{
+    Int_t len;
+    for (Int_t i=0; i<76; i++)
+    {
+        const Int_t n=sscanf(str.Data(), "%f %n", &fRecTemp[i], &len);
+        str.Remove(0, len);
+
+        if (n==1)
+            continue;
+
+        if (n==0 && i==0)
+        {
+            *fLog << inf << "Receiver Board Temperatures empty." << endl;
+            Invalidate();
+            break;
+        }
+
+        *fLog << warn << "WARNING - Reading Receiver Board Temperature information." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Print the dc currents
+//
+void MCameraRecTemp::Print(Option_t *) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    for (int i=0; i<fRecTemp.GetSize(); i++)
+        *fLog << " " << fRecTemp[i];
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the minimum receiver board temperature
+//
+Float_t MCameraRecTemp::GetMin() const
+{
+    Float_t val = FLT_MAX;
+    for (int i=0; i<fRecTemp.GetSize(); i++)
+        val = TMath::Min(val, fRecTemp[i]);
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the maximum receiver board temperature
+//
+Float_t MCameraRecTemp::GetMax() const
+{
+    Float_t val = -FLT_MAX;
+    for (int i=0; i<fRecTemp.GetSize(); i++)
+        val = TMath::Max(val, fRecTemp[i]);
+    return val;
+}
Index: branches/Mars_McMismatchStudy/mcamera/MCameraRecTemp.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraRecTemp.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraRecTemp.h	(revision 17960)
@@ -0,0 +1,40 @@
+#ifndef MARS_MCameraRecTemp
+#define MARS_MCameraRecTemp
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MCameraRecTemp : public MParContainer
+{
+    friend class MReportCC;
+    friend class MReportRec;
+private:
+    TArrayF fRecTemp; // [deg C] receiver board temperatures
+    Bool_t  fIsValid; // fRecTemp contains valid information
+
+    Bool_t InterpreteRecTemp(TString &str);
+
+public:
+    MCameraRecTemp(Int_t size=76, const char *name=NULL, const char *title=NULL);
+
+    Float_t operator[](Int_t i) const { return fRecTemp[i]; }
+
+    void Invalidate() { fRecTemp.Reset(); fIsValid=kFALSE; }
+
+    void SetValid(Bool_t v=kTRUE) { fIsValid=v; }
+    Bool_t IsValid() const { return fIsValid; }
+
+    Float_t GetMin() const;
+    Float_t GetMax() const;
+
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MCameraRecTemp, 2) // Storage Container for Receiver Board Temperature
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraTD.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraTD.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraTD.cc	(revision 17960)
@@ -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, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Florian Goebel 11/2005 <mailto:fgoebel@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraTD
+//
+// Class Version 2:
+// ----------------
+//   + Bool_t  fIsValid; // fTD contains valid information
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraTD.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCameraTD);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCameraTD::MCameraTD(Int_t size, const char *name, const char *title)
+    : fTD(size), fIsValid(kTRUE)
+{
+    fName  = name  ? name  : "MCameraTD";
+    fTitle = title ? title : "Storage container for the pixel discriminator delays";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the TD (discriminator delays) part of the report
+//
+Bool_t MCameraTD::InterpreteTD(TString &str, Int_t ver)
+{
+    // Skip the TD (discriminator delays) part of the report (for old
+    // CC files with wrong or nonsense number of TD-Bytes)
+    if (ver<200412210)
+    {
+        Ssiz_t pr = str.First(' ');
+        if (pr<0)
+        {
+            *fLog << warn << "WARNING - No TD information found at all." << endl;
+            return kFALSE;
+        }
+        if (pr!=1000)
+        {
+            Invalidate();
+
+            str.Remove(0, pr);
+            str=str.Strip(TString::kLeading);
+            return kTRUE;
+        }
+    }
+
+    // Older files have less bytes (pixels) stored
+    const Int_t numpix = ver<200510250 ? 500 : 577;
+
+    const char *pos = str.Data();
+    const char *end = str.Data()+numpix*2;
+
+    Int_t i=0;
+    while (pos<end)
+    {
+        const Char_t hex[3] = { pos[0], pos[1], 0 };
+        pos += 2;
+
+        const Int_t n=sscanf(hex, "%2hhx", &fTD[i++]);
+        if (n==1)
+            continue;
+
+        *fLog << warn << "WARNING - Reading hexadecimal TD information." << endl;
+        return kFALSE;
+    }
+
+    SetValid();
+
+    str.Remove(0, end-str.Data()); // Remove TD
+    str=str.Strip(TString::kLeading);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the discrimintaor delays
+//
+void MCameraTD::Print(Option_t *) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    for (int i=0; i<fTD.GetSize(); i++)
+        *fLog << " " << (int)fTD[i];
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the discrimintaor delays
+//
+Byte_t MCameraTD::GetMin() const
+{
+    Byte_t val = 0xff;
+    for (int i=0; i<fTD.GetSize(); i++)
+        val = TMath::Min(val, fTD[i]);
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the discrimintaor delays
+//
+Byte_t MCameraTD::GetMax() const
+{
+    Byte_t val = 0;
+    for (int i=0; i<fTD.GetSize(); i++)
+        val = TMath::Max(val, fTD[i]);
+    return val;
+}
Index: branches/Mars_McMismatchStudy/mcamera/MCameraTD.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraTD.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraTD.h	(revision 17960)
@@ -0,0 +1,55 @@
+#ifndef MARS_MCameraTD
+#define MARS_MCameraTD
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+class MCameraTD : public MParContainer, public MCamEvent
+{
+    friend class MReportCC;
+    friend class MReportRec;
+private:
+    TArrayC fTD;      // [au] discriminator delays
+    Bool_t  fIsValid; // fTD contains valid information
+
+    Bool_t InterpreteTD(TString &str, Int_t ver);
+
+public:
+    MCameraTD(Int_t size=577, const char *name=NULL, const char *title=NULL);
+
+    Byte_t operator[](Int_t i) { return fTD[i]; }
+
+    Byte_t GetMin() const;
+    Byte_t GetMax() const;
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Invalidate() { fTD.Reset(); fIsValid=kFALSE; }
+
+    void SetValid(Bool_t v=kTRUE) { fIsValid=v; }
+    Bool_t IsValid() const { return fIsValid; }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+        if (idx>=fTD.GetSize())
+            return kFALSE;
+
+        val = fTD[idx];
+        return val>0;
+    }
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MCameraTD, 2) // Storage Container for Discriminator Delays
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/MCameraTH.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraTH.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraTH.cc	(revision 17960)
@@ -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): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Florian Goebel 11/2005 <mailto:fgoebel@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraTH
+//
+// Class Version 2:
+// ----------------
+//   + Bool_t  fIsValid; // fTH contains valid information
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraTH.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCameraTD.h"
+
+ClassImp(MCameraTH);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCameraTH::MCameraTH(Int_t size, const char *name, const char *title)
+    : fTH(size), fIsValid(kTRUE)
+{
+    fName  = name  ? name  : "MCameraTH";
+    fTitle = title ? title : "Storage container for the pixel discriminator threshold";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the TH (discriminator thresholds) part of the report
+//
+Bool_t MCameraTH::InterpreteTH(TString &str, Int_t ver, MCameraTD &td)
+{
+    // Skip the TH (discriminator thresholds) part of the report (for old
+    // CC files with wrong or nonsense number of TH-Bytes)
+    if (ver<200507190)
+    {
+        Ssiz_t pr = str.First(' ');
+        if (pr<0)
+        {
+            *fLog << warn << "WARNING - No TH information found at all." << endl;
+            return kFALSE;
+        }
+        if (pr!=1154)
+        {
+            td.Invalidate();
+
+            str.Remove(0, pr);
+            str=str.Strip(TString::kLeading);
+            return kTRUE;
+        }
+    }
+
+    const char *pos = str.Data();
+    const char *end = str.Data()+577*2;
+
+    Int_t i=0;
+    while (pos<end)
+    {
+        const Char_t hex[3] = { pos[0], pos[1], 0 };
+        pos += 2;
+
+        const Int_t n=sscanf(hex, "%2hhx", &fTH[i++]);
+        if (n==1)
+            continue;
+
+        *fLog << warn << "WARNING - Reading hexadecimal TH information." << endl;
+        return kFALSE;
+    }
+
+    SetValid();
+
+    str.Remove(0, end-str.Data()); // Remove TH
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the discriminator thresholds
+//
+void MCameraTH::Print(Option_t *) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    for (int i=0; i<fTH.GetSize(); i++)
+        *fLog << " " << (int)fTH[i];
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the discriminator thresholds
+//
+Byte_t MCameraTH::GetMin() const
+{
+    Byte_t val = 0xff;
+    for (int i=0; i<fTH.GetSize(); i++)
+        val = TMath::Min(val, fTH[i]);
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the discriminator thresholds
+//
+Byte_t MCameraTH::GetMax() const
+{
+    Byte_t val = 0;
+    for (int i=0; i<fTH.GetSize(); i++)
+        val = TMath::Max(val, fTH[i]);
+    return val;
+}
Index: branches/Mars_McMismatchStudy/mcamera/MCameraTH.h
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/MCameraTH.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/MCameraTH.h	(revision 17960)
@@ -0,0 +1,79 @@
+/* ======================================================================== *\
+!  $Name: not supported by cvs2svn $:$Id: MCameraTH.h,v 1.8 2008-06-14 14:19:03 tbretz Exp $
+\* ======================================================================== */
+#ifndef MARS_MCameraTH
+#define MARS_MCameraTH
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+class MCameraTD;
+
+class MCameraTH : public MParContainer, public MCamEvent
+{
+    friend class MReportCC;
+    friend class MReportRec;
+private:
+    TArrayC fTH;      // [au] discriminator thresholds
+    Bool_t  fIsValid; // fTH contains valid information
+
+    Bool_t InterpreteTH(TString &str, Int_t ver, MCameraTD &td);
+
+public:
+    MCameraTH(Int_t size=577, const char *name=NULL, const char *title=NULL);
+
+    Byte_t operator[](Int_t i) { return fTH[i]; }
+
+    Byte_t GetMin() const;
+    Byte_t GetMax() const;
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Invalidate() { fTH.Reset(); fIsValid=kFALSE; }
+
+    void SetValid(Bool_t v=kTRUE) { fIsValid=v; }
+    Bool_t IsValid() const { return fIsValid; }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+        if (idx>=fTH.GetSize())
+            return kFALSE;
+
+        // FIXME: This is a stupid workaround to describe the trigger area
+        //        and only valid for the MAGIC-I camera!
+        if (idx>=397 ||
+            (idx>=339 && idx<=345) ||
+            (idx>=279 && idx<=283) ||
+            (idx>=331 && idx<=334) ||
+            (idx>=394 && idx<=396) ||
+            (idx>=271 && idx<=273) ||
+            (idx>=329 && idx<=330) ||
+            (idx>=383 && idx<=389) ||
+            (idx>=319 && idx<=323) ||
+            (idx>=289 && idx<=293) ||
+            (idx>=350 && idx<=356) ||
+            (idx>=299 && idx<=303) ||
+            (idx>=361 && idx<=367) ||
+            (idx>=309 && idx<=313) ||
+            (idx>=372 && idx<=378))
+            return kFALSE;
+
+        val = fTH[idx];
+        return val>0;
+    }
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MCameraTH, 2) // Storage Container for the discriminator thresholds
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcamera/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mcamera/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcamera/Makefile	(revision 17960)
@@ -0,0 +1,45 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Camera
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui
+# mgui - MCameraDC <MCamEvent>
+
+SRCFILES = MCameraAUX.cc \
+	   MCameraCalibration.cc\
+	   MCameraCooling.cc \
+	   MCameraHV.cc \
+	   MCameraLV.cc \
+	   MCameraTH.cc \
+	   MCameraTD.cc \
+	   MCameraRecTemp.cc \
+	   MCameraDC.cc \
+	   MCameraLid.cc \
+	   MCameraLids.cc \
+	   MCameraActiveLoad.cc \
+	   MCameraCentralPix.cc \
+	   MCameraPowerSupply.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mcore/DrsCalib.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/DrsCalib.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/DrsCalib.h	(revision 17960)
@@ -0,0 +1,1542 @@
+#ifndef MARS_DrsCalib
+#define MARS_DrsCalib
+
+#include <math.h>   // fabs
+#include <errno.h>  // errno
+
+#ifndef MARS_fits
+#include "fits.h"
+#endif
+
+#ifndef MARS_ofits
+#include "ofits.h"
+#endif
+
+class DrsCalibrate
+{
+protected:
+    int64_t fNumEntries;
+
+    size_t fNumSamples;
+    size_t fNumChannels;
+
+    std::vector<int64_t> fSum;
+    std::vector<int64_t> fSum2;
+
+public:
+    DrsCalibrate() : fNumEntries(0), fNumSamples(0), fNumChannels(0)
+    {
+        fSum.reserve(1024*1440);
+        fSum2.reserve(1024*1440);
+    }
+
+    void Reset()
+    {
+        fNumEntries  = 0;
+        fNumSamples  = 0;
+        fNumChannels = 0;
+
+        fSum.clear();
+        fSum2.clear();
+    }
+
+    void InitSize(uint16_t channels, uint16_t samples)
+    {
+        fNumChannels = channels;
+        fNumSamples  = samples;
+
+        fSum.assign(samples*channels, 0);
+        fSum2.assign(samples*channels, 0);
+    }
+
+    void AddRel(const int16_t *val, const int16_t *start)
+    {
+        /*
+        for (size_t ch=0; ch<fNumChannels; ch++)
+        {
+            const int16_t &spos = start[ch];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*1024;
+            for (size_t i=0; i<1024; i++)
+            {
+                // Value is relative to trigger
+                // Abs is corresponding index relative to DRS pipeline
+                const size_t rel = pos +  i;
+                const size_t abs = pos + (spos+i)%1024;
+
+                const int64_t v = val[rel];
+
+                fSum[abs]  += v;
+                fSum2[abs] += v*v;
+            }
+        }*/
+
+        // This version is 2.5 times faster because the compilers optimization
+        // is not biased by the evaluation of %1024
+        for (size_t ch=0; ch<fNumChannels; ch++)
+        {
+            const int16_t &spos = start[ch];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*1024;
+
+            const int16_t *beg_val  = val          + pos;
+            int64_t       *beg_sum  = fSum.data()  + pos;
+            int64_t       *beg_sum2 = fSum2.data() + pos;
+
+            const int16_t *pval  = beg_val;          // val[rel]
+            int64_t       *psum  = beg_sum  + spos;  // fSum[abs]
+            int64_t       *psum2 = beg_sum2 + spos;  // fSum2[abs]
+
+            while (psum<beg_sum+1024)
+            {
+                const int64_t v = *pval++;
+
+                *psum++  += v;
+                *psum2++ += v*v;
+            }
+
+            psum  = beg_sum;
+            psum2 = beg_sum2;
+
+            while (pval<beg_val+1024)
+            {
+                const int64_t v = *pval++;
+
+                *psum++  += v;
+                *psum2++ += v*v;
+            }
+        }
+
+        fNumEntries++;
+    }
+
+    void AddRel(const int16_t *val,    const int16_t *start,
+                const int32_t *offset, const int64_t scale)
+    {
+        /*
+        for (size_t ch=0; ch<fNumChannels; ch++)
+        {
+            const int16_t spos = start[ch];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*1024;
+
+            for (size_t i=0; i<fNumSamples; i++)
+            {
+                // Value is relative to trigger
+                // Offset is relative to DRS pipeline
+                // Abs is corresponding index relative to DRS pipeline
+                const size_t rel = pos +  i;
+                const size_t abs = pos + (spos+i)%1024;
+
+                const int64_t v = int64_t(val[rel])*scale-offset[abs];
+
+                fSum[abs]  += v;
+                fSum2[abs] += v*v;
+            }
+        }*/
+
+        // This version is 2.5 times faster because the compilers optimization
+        // is not biased by the evaluation of %1024
+        for (size_t ch=0; ch<fNumChannels; ch++)
+        {
+            const int16_t &spos = start[ch];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*1024;
+
+            const int16_t *beg_val    = val          + pos;
+            const int32_t *beg_offset = offset       + pos;
+            int64_t       *beg_sum    = fSum.data()  + pos;
+            int64_t       *beg_sum2   = fSum2.data() + pos;
+
+
+            const int16_t *pval    = beg_val;            // val[rel]
+            const int32_t *poffset = beg_offset + spos;  // offset[abs]
+            int64_t       *psum    = beg_sum    + spos;  // fSum[abs]
+            int64_t       *psum2   = beg_sum2   + spos;  // fSum2[abs]
+
+            while (psum<beg_sum+1024)
+            {
+                const int64_t v = int64_t(*pval++)*scale - *poffset++;
+
+                *psum++  += v;
+                *psum2++ += v*v;
+            }
+
+            psum    = beg_sum;
+            psum2   = beg_sum2;
+            poffset = beg_offset;
+
+            while (pval<beg_val+1024)
+            {
+                const int64_t v = int64_t(*pval++)*scale - *poffset++;
+
+                *psum++  += v;
+                *psum2++ += v*v;
+            }
+        }
+
+        fNumEntries++;
+    }
+    /*
+    void AddAbs(const int16_t *val,    const  int16_t *start,
+                const int32_t *offset, const uint32_t scale)
+    {
+        for (size_t ch=0; ch<fNumChannels; ch++)
+        {
+            const int16_t spos = start[ch];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*fNumSamples;
+
+            for (size_t i=0; i<fNumSamples; i++)
+            {
+                // Value is relative to trigger
+                // Offset is relative to DRS pipeline
+                // Abs is corresponding index relative to DRS pipeline
+                const size_t rel = pos +  i;
+                const size_t abs = pos + (spos+i)%1024;
+
+                const int64_t v = int64_t(val[rel])*scale-offset[abs];
+
+                fSum[rel]  += v;
+                fSum2[rel] += v*v;
+            }
+        }
+
+        fNumEntries++;
+    }*/
+
+    void AddAbs(const int16_t *val,    const int16_t *start,
+                const int32_t *offset, const int64_t scale)
+    {
+        /*
+        // 1440 without tm, 1600 with tm
+        for (size_t ch=0; ch<fNumChannels; ch++)
+        {
+            const int16_t spos = start[ch];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*fNumSamples;
+            const size_t drs = ch>1439 ? ((ch-1440)*9+8)*1024 : ch*1024;
+
+            for (size_t i=0; i<fNumSamples; i++)
+            {
+                // Value is relative to trigger
+                // Offset is relative to DRS pipeline
+                // Abs is corresponding index relative to DRS pipeline
+                const size_t rel = pos +  i;
+                const size_t abs = drs + (spos+i)%1024;
+
+                const int64_t v = int64_t(val[rel])*scale-offset[abs];
+
+                fSum[rel]  += v;
+                fSum2[rel] += v*v;
+            }
+            }*/
+
+        // This version is 1.5 times faster because the compilers optimization
+        // is not biased by the evaluation of %1024
+        for (size_t ch=0; ch<fNumChannels; ch++)
+        {
+            const int16_t &spos = start[ch];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*fNumSamples;
+
+            const int32_t *beg_offset = offset       + ch*1024;
+            const int16_t *beg_val    = val          + pos;
+            int64_t *beg_sum          = fSum.data()  + pos;
+            int64_t *beg_sum2         = fSum2.data() + pos;
+
+
+            const int16_t *pval    = beg_val;             // val[rel]
+            const int32_t *poffset = beg_offset + spos;   // offset[abs]
+            int64_t *psum          = beg_sum;             // fSum[rel]
+            int64_t *psum2         = beg_sum2;            // fSum2[rel]
+
+            if (spos+fNumSamples>1024)
+            {
+                while (poffset<beg_offset+1024)
+                {
+                    const int64_t v = int64_t(*pval++)*scale - *poffset++;
+
+                    *psum++  += v;
+                    *psum2++ += v*v;
+                }
+
+                poffset = beg_offset;
+            }
+
+            while (psum<beg_sum+fNumSamples)
+            {
+                const int64_t v = int64_t(*pval++)*scale - *poffset++;
+
+                *psum++  += v;
+                *psum2++ += v*v;
+            }
+        }
+
+        fNumEntries++;
+    }
+
+
+    static void ApplyCh(float *vec, const int16_t *val, int16_t start, uint32_t roi,
+                        const int32_t *offset, const int64_t scaleabs,
+                        const int64_t *gain,   const int64_t scalegain)
+    {
+        if (start<0)
+        {
+            memset(vec, 0, roi);
+            return;
+        }
+        /*
+        for (size_t i=0; i<roi; i++)
+        {
+            // Value is relative to trigger
+            // Offset is relative to DRS pipeline
+            // Abs is corresponding index relative to DRS pipeline
+            const size_t abs = (start+i)%1024;
+
+            const int64_t v =
+                + int64_t(val[i])*scaleabs-offset[abs]
+                ;
+
+            const int64_t div = gain[abs];
+            vec[i] = div==0 ? 0 : double(v)*scalegain/div;
+        }
+        */
+
+        // This version is faster because the compilers optimization
+        // is not biased by the evaluation of %1024
+        // (Here we are dominated by numerics... improvement ~10%)
+        const int32_t *poffset = offset + start; // offset[abs]
+        const int64_t *pgain   = gain   + start; // gain[abs]
+        const int16_t *pval    = val;            // val[rel]
+        float         *pvec    = vec;            // vec[rel]
+
+        if (start+roi>1024)
+        {
+            while (poffset<offset+1024)
+            {
+                const int64_t v =
+                    + int64_t(*pval++)*scaleabs - *poffset++
+                    ;
+
+                *pvec++ = *pgain==0 ? 0 : double(v)*scalegain / *pgain;
+
+                pgain++;
+            }
+
+            poffset = offset;
+            pgain   = gain;
+        }
+
+        while (pvec<vec+roi)
+        {
+            const int64_t v =
+                + int64_t(*pval++)*scaleabs - *poffset++
+                ;
+
+            *pvec++ = *pgain==0 ? 0 : double(v)*scalegain / *pgain;
+
+            pgain++;
+        }
+    }
+
+    static void ApplyCh(float *vec, const int16_t *val, int16_t start, uint32_t roi,
+                        const int32_t *offset, const int64_t scaleabs,
+                        const int64_t *gain,   const int64_t scalegain,
+                        const int64_t *trgoff, const int64_t scalerel)
+    {
+        if (start<0)
+        {
+            memset(vec, 0, roi);
+            return;
+        }
+        /*
+        for (size_t i=0; i<roi; i++)
+        {
+            // Value is relative to trigger
+            // Offset is relative to DRS pipeline
+            // Abs is corresponding index relative to DRS pipeline
+            const size_t abs = (start+i)%1024;
+
+            const int64_t v =
+                + (int64_t(val[i])*scaleabs-offset[abs])*scalerel
+                - trgoff[i]
+                ;
+
+            const int64_t div = gain[abs]*scalerel;
+            vec[i] = div==0 ? 0 : double(v)*scalegain/div;
+        }
+        */
+        // (Here we are dominated by numerics... improvement ~10%)
+        const int32_t *poffset = offset + start; // offset[abs]
+        const int64_t *pgain   = gain   + start; // gain[abs]
+        const int16_t *pval    = val;            // val[rel]
+        const int64_t *ptrgoff = trgoff;         // trgoff[rel]
+        float         *pvec    = vec;            // vec[rel]
+
+        if (start+roi>1024)
+        {
+            while (poffset<offset+1024)
+            {
+                const int64_t v =
+                    + (int64_t(*pval++)*scaleabs - *poffset++)*scalerel
+                    - *ptrgoff++;
+                ;
+
+                const int64_t div = *pgain * scalerel;
+                *pvec++ = div==0 ? 0 : double(v)*scalegain / div;
+
+                pgain++;
+            }
+
+            poffset = offset;
+            pgain   = gain;
+        }
+
+        while (pvec<vec+roi)
+        {
+            const int64_t v =
+                + (int64_t(*pval++)*scaleabs - *poffset++)*scalerel
+                - *ptrgoff++;
+            ;
+
+            const int64_t div = *pgain * scalerel;
+            *pvec++ = div==0 ? 0 : double(v)*scalegain / div;
+
+            pgain++;
+        }
+    }
+
+    static double FindStep(const size_t ch0, const float *vec, int16_t roi, const int16_t pos, const uint16_t *map=NULL)
+    {
+        // We have about 1% of all cases which are not ahndled here,
+        // because the baseline jumps up just before the readout window
+        // and down just after it. In this cases we could determine the jump
+        // from the board time difference or throw the event away.
+        if (pos==0 || pos>=roi)
+            return 0;
+
+        double step = 0; // before
+        double rms  = 0; // before
+        int    cnt  = 0;
+
+        // Exclude TM channel
+        for (int p=0; p<8; p++)
+        {
+            const size_t hw = ch0+p;
+            const size_t sw = (map?map[hw]:hw)*roi + pos;
+
+            const double diff = vec[sw]-vec[sw-1];
+
+            step += diff;
+            rms  += (vec[sw]-vec[sw-1])*(vec[sw]-vec[sw-1]);
+
+            cnt++;
+        }
+
+        return cnt==0 ? 0 : step/cnt;
+    }
+
+    static void SubtractStep(const size_t ch0, const double avg, float *vec, int16_t roi, int32_t pos, const uint16_t *map=NULL)
+    {
+        if (pos==0 || pos>=roi)
+            return;
+
+        const int begin = avg>0 ? pos :   0;
+        const int end   = avg>0 ? roi : pos;
+
+        const double sub = fabs(avg);
+
+        for (int p=0; p<9; p++)
+        {
+            for (int j=begin; j<end; j++)
+            {
+                const size_t hw = ch0+p;
+                const size_t sw = (map?map[hw]:hw)*roi + j;
+
+                vec[sw] -= sub;
+            }
+        }
+    }
+
+    struct Step
+    {
+        Step() : avg(0), rms(0), pos(0), cnt(0) { }
+        double   avg;
+        double   rms;
+        double   pos;
+        uint16_t cnt;
+
+        static bool sort(const Step &s, const Step &r) { return s.avg<r.avg; }
+    };
+
+    static Step AverageSteps(const std::vector<Step>::iterator beg, const std::vector<Step>::iterator end)
+    {
+        Step rc;
+        for (auto it=beg; it!=end; it++)
+        {
+            rc.pos += it->pos;
+            rc.avg += it->avg;
+            rc.rms += it->avg*it->avg;
+        }
+
+        rc.cnt = end-beg;
+
+        rc.pos /= rc.cnt;
+        rc.avg /= rc.cnt;
+        rc.rms /= rc.cnt;
+        rc.rms -= rc.avg*rc.avg;
+        rc.rms  = rc.rms<0 ? 0 : sqrt(rc.rms);
+
+        return rc;
+    }
+
+
+    static Step CorrectStep(float *vec, uint16_t nch, uint16_t roi,
+                            const int16_t *prev, const int16_t *start,
+                            const int16_t offset, const uint16_t *map=NULL)
+    {
+
+        std::vector<Step> list;
+        list.reserve(nch);
+
+        // Fill steps into array
+        // Exclude broken pixels?
+        // Remove maximum and minimum patches (4max and 4min)?
+        for (size_t ch=0; ch<nch; ch += 9)
+        {
+            if (prev[ch]<0 || start[ch]<0)
+                continue;
+
+            const int16_t dist = (prev[ch]-start[ch]+1024+offset)%1024;
+            const double  step = FindStep(ch, vec, roi, dist, map);
+            if (step==0)
+                continue;
+
+            Step rc;
+            rc.pos = dist;
+            rc.avg = step;
+            list.push_back(rc);
+        }
+
+        if (list.empty())
+            return Step();
+
+        Step rc = AverageSteps(list.begin(), list.begin()+list.size());;
+
+        if (rc.avg==0)
+            return Step();
+
+        // std::cout << "   A0=" << rc.avg << "    rms=" << rc.rms << std::endl;
+        if (rc.rms>5)
+        {
+            sort(list.begin(), list.end(), Step::sort);
+
+            //for (auto it=list.begin(); it!=list.end(); it++)
+            //    std::cout << "     " << it->avg << std::endl;
+
+            const size_t skip = list.size()/10;
+            rc = AverageSteps(list.begin()+skip, list.begin()+list.size()-skip);
+
+            // std::cout << "   A1=" << rc.avg << "    rms=" << rc.rms << std::endl;
+        }
+
+        for (size_t ch=0; ch<nch; ch += 9)
+        {
+            const int16_t dist = (prev[ch]-start[ch]+1024+offset)%1024;
+            SubtractStep(ch, rc.avg, vec, roi, dist, map);
+        }
+
+        return rc;
+    }
+
+    static void RemoveSpikes(float *p, uint32_t roi)
+    {
+        if (roi<4)
+            return;
+
+        for (size_t i=1; i<roi-2; i++)
+        {
+            if (p[i]-p[i-1]>25 && p[i]-p[i+1]>25)
+            {
+                p[i] = (p[i-1]+p[i+1])/2;
+            }
+
+            if (p[i]-p[i-1]>22 && fabs(p[i]-p[i+1])<4 && p[i+1]-p[i+2]>22)
+            {
+                p[i] = (p[i-1]+p[i+2])/2;
+                p[i+1] = p[i];
+            }
+        }
+    }
+
+    static void RemoveSpikes2(float *p, uint32_t roi)//from Werner
+    {
+        if (roi<4)
+            return;
+
+        std::vector<float> Ameas(p, p+roi);
+
+        std::vector<float> diff(roi);
+        for (size_t i=1; i<roi-1; i++)
+            diff[i] = (p[i-1] + p[i+1])/2 - p[i];
+
+        //std::vector<float> N1mean(roi);
+        //for (size_t i=1; i<roi-1; i++)
+        //    N1mean[i] = (p[i-1] + p[i+1])/2;
+
+        const float fract = 0.8;
+
+        for (size_t i=0; i<roi-3; i++)
+        {
+            if (diff[i]<5)
+                continue;
+
+            if (Ameas[i+2] - (Ameas[i] + Ameas[i+3])/2 > 10)
+            {
+                p[i+1]=   (Ameas[i+3] - Ameas[i])/3 + Ameas[i];
+                p[i+2]= 2*(Ameas[i+3] - Ameas[i])/3 + Ameas[i];
+
+                i += 3;
+
+                continue;
+            }
+
+            if ( (diff[i+1]<-diff[i]*fract*2) && (diff[i+2]>10) )
+            {
+                p[i+1]    = (Ameas[i]+Ameas[i+2])/2;
+                diff[i+2] = (p[i+1] + Ameas[i+3])/2 - Ameas[i+2];
+
+                i += 2;
+            }
+
+            // const float x = Ameas[i] - N1mean[i];
+            // if (x > -5.)
+            //     continue;
+
+            // if (Ameas[i+2] - (Ameas[i] + Ameas[i+3])/2. > 10.)
+            // {
+            //     p[i+1]=   (Ameas[i+3] - Ameas[i])/3 + Ameas[i];
+            //     p[i+2]= 2*(Ameas[i+3] - Ameas[i])/3 + Ameas[i];
+            //     i += 3;
+            //     continue;
+            // }
+
+            // const float xp  = Ameas[i+1] - N1mean[i+1];
+            // const float xpp = Ameas[i+2] - N1mean[i+2];
+
+            // if ( (xp > -2.*x*fract) && (xpp < -10.) )
+            // {
+            //     p[i+1] = N1mean[i+1];
+            //     N1mean[i+2] = Ameas[i+1] - Ameas[i+3]/2;
+            //
+            //     i += 2;
+            // }
+        }
+    }
+
+    static void RemoveSpikes3(float *vec, uint32_t roi)//from Werner
+    {
+        if (roi<4)
+            return;
+
+        const float SingleCandidateTHR = -10.;
+        const float DoubleCandidateTHR =  -5.;
+
+        const std::vector<float> src(vec, vec+roi);
+ 
+        std::vector<float> diff(roi);
+        for (size_t i=1; i<roi-1; i++)
+            diff[i] = src[i] - (src[i-1] + src[i+1])/2;
+
+        // find the spike and replace it by mean value of neighbors
+        for (unsigned int i=1; i<roi-3; i++)
+        {
+            // Speed up (no leading edge)
+            if (diff[i]>=DoubleCandidateTHR)
+                continue;
+
+            //bool checkDouble = false;
+
+            // a single spike candidate
+            if (diff[i]<SingleCandidateTHR)
+            {
+                // check consistency with a single channel spike
+                if (diff[i+1] > -1.6*diff[i])
+                {
+                    vec[i+1] = (src[i] + src[i+2]) / 2;
+
+                    i += 2;
+
+                    /*** NEW ***/
+                    continue;
+                    /*** NEW ***/
+                }
+                /*
+                else
+                {
+                    // do nothing - not really a single spike,
+                    // but check if it is a double
+                    checkDouble = true;
+                }*/
+            }
+
+            // a double spike candidate
+            //if (diff[i]>DoubleCandidateTHR || checkDouble == 1)
+            { 
+                // check the consistency with a double spike
+                if ((diff[i+1] > -DoubleCandidateTHR) &&
+                    (diff[i+2] > -DoubleCandidateTHR))
+                {
+                    vec[i+1] =   (src[i+3] - src[i])/3 + src[i];
+                    vec[i+2] = 2*(src[i+3] - src[i])/3 + src[i];
+
+                    //vec[i]   = (src[i-1] + src[i+2]) / 2.;
+                    //vec[i+1] = (src[i-1] + src[i+2]) / 2.;
+
+                    //do not care about the next sample it was the spike
+                    i += 3;
+                }
+            }
+        } 
+    }
+
+    static void RemoveSpikes4(float *ptr, uint32_t roi)
+    {
+        if (roi<7)
+            return;
+
+        for (uint32_t i=0; i<roi-6; i++)
+        {
+            double d10, d21, d32, d43, d54;
+
+            // ============================================
+            d43 = ptr[i+4]-ptr[i+3];
+            d54 = ptr[i+5]-ptr[i+4];
+
+            if ((d43>35 && -d54>35) || (d43<-35 && -d54<-35))
+            {
+                ptr[i+4] = (ptr[i+3]+ptr[i+5])/2;
+            }
+
+            // ============================================
+            d32 = ptr[i+3]-ptr[i+2];
+            d54 = ptr[i+5]-ptr[i+4];
+
+            if ((d32>9   && -d54>13  && d32-d54>31)/* || (d32<-13 && -d54<-13 && d32+d54<-63)*/)
+            {
+                double avg0 = (ptr[i+2]+ptr[i+5])/2;
+                double avg1 = (ptr[i+3]+ptr[i+4])/2;
+
+                ptr[i+3] = ptr[i+3] - avg1+avg0;
+                ptr[i+4] = ptr[i+4] - avg1+avg0;
+            }
+
+            // ============================================
+            d21 = ptr[i+2]-ptr[i+1];
+            d54 = ptr[i+5]-ptr[i+4];
+
+            if (d21>15 && -d54>17)
+            {
+                double avg0 = (ptr[i+1]+ptr[i+5])/2;
+                double avg1 = (ptr[i+2]+ptr[i+3]+ptr[i+4])/3;
+
+                ptr[i+2] = ptr[i+2] - avg1+avg0;
+                ptr[i+3] = ptr[i+3] - avg1+avg0;
+                ptr[i+4] = ptr[i+4] - avg1+avg0;
+            }
+
+            // ============================================
+            d10 = ptr[i+1]-ptr[i];
+            d54 = ptr[i+5]-ptr[i+4];
+
+            if (d10>18 && -d54>20)
+            {
+                double avg0 = (ptr[i]+ptr[i+5])/2;
+                double avg1 = (ptr[i+1]+ptr[i+2]+ptr[i+3]+ptr[i+4])/4;
+
+                ptr[i+1] = ptr[i+1] - avg1+avg0;
+                ptr[i+2] = ptr[i+2] - avg1+avg0;
+                ptr[i+3] = ptr[i+3] - avg1+avg0;
+                ptr[i+4] = ptr[i+4] - avg1+avg0;
+            }
+        }
+    }
+
+    static void SlidingAverage(float *const vec, const uint32_t roi, const uint16_t w)
+    {
+        if (w==0 || w>roi)
+            return;
+
+        for (float *pix=vec; pix<vec+1440*roi; pix += roi)
+        {
+            for (float *ptr=pix; ptr<pix+roi-w; ptr++)
+            {
+                for (float *p=ptr+1; p<ptr+w; p++)
+                    *ptr += *p;
+                *ptr /= w;
+            }
+        }
+    }
+
+    std::pair<std::vector<double>,std::vector<double> > GetSampleStats() const
+    {
+        if (fNumEntries==0)
+            return make_pair(std::vector<double>(),std::vector<double>());
+
+        std::vector<double> mean(fSum.size());
+        std::vector<double> error(fSum.size());
+
+        std::vector<int64_t>::const_iterator it = fSum.begin();
+        std::vector<int64_t>::const_iterator i2 = fSum2.begin();
+        std::vector<double>::iterator        im = mean.begin();
+        std::vector<double>::iterator        ie = error.begin();
+
+        while (it!=fSum.end())
+        {
+            *im = /*cnt<fResult.size() ? fResult[cnt] :*/ double(*it)/fNumEntries;
+            *ie = sqrt(double(*i2*int64_t(fNumEntries) - *it * *it))/fNumEntries;
+
+            im++;
+            ie++;
+            it++;
+            i2++;
+        }
+
+
+        /*
+         valarray<double> ...
+
+         mean /= fNumEntries;
+         error = sqrt(error/fNumEntries - mean*mean);
+         */
+
+        return make_pair(mean, error);
+    }
+
+    void GetSampleStats(float *ptr, float scale) const
+    {
+        const size_t sz = fNumSamples*fNumChannels;
+
+        if (fNumEntries==0)
+        {
+            memset(ptr, 0, sizeof(float)*sz*2);
+            return;
+        }
+
+        std::vector<int64_t>::const_iterator it = fSum.begin();
+        std::vector<int64_t>::const_iterator i2 = fSum2.begin();
+
+        while (it!=fSum.end())
+        {
+            *ptr      = scale*double(*it)/fNumEntries;
+            *(ptr+sz) = scale*sqrt(double(*i2*fNumEntries - *it * *it))/fNumEntries;
+
+            ptr++;
+            it++;
+            i2++;
+        }
+    }
+
+    static double GetPixelStats(float *ptr, const float *data, uint16_t roi, uint16_t begskip=0, uint16_t endskip=0)
+    {
+        if (roi==0)
+            return -1;
+
+        // Skip first 10 samples
+        const uint beg = roi>begskip ? begskip : 0;
+        const uint end = roi-beg>endskip ? roi-endskip : roi;
+        const uint len = end-beg;
+
+        double max = 0;
+        double patch = 0;
+        for (uint i=0; i<1440; i++)
+        {
+            const float *vec = data+i*roi;
+
+            uint   pos  = beg;
+            double sum  = vec[beg];
+            double sum2 = vec[beg]*vec[beg];
+
+            for (uint j=beg+1; j<end; j++)
+            {
+                sum  += vec[j];
+                sum2 += vec[j]*vec[j];
+
+                if (vec[j]>vec[pos])
+                    pos = j;
+            }
+            sum  /= len;
+            sum2 /= len;
+            sum2 -= sum*sum;
+
+            if (i%9!=8)
+                patch += vec[pos];
+            else
+            {
+                if (patch > max)
+                    max = patch;
+                patch = 0;
+            }
+
+            *(ptr+0*1440+i) = sum;
+            *(ptr+1*1440+i) = sum2<0 ? 0 : sqrt(sum2);
+            *(ptr+2*1440+i) = vec[pos];
+            *(ptr+3*1440+i) = pos;
+        }
+
+        return max/8;
+    }
+
+    static void GetPixelMax(float *max, const float *data, uint16_t roi, int32_t first, int32_t last)
+    {
+        if (roi==0 || first<0 || last<0 || first>=roi || last>=roi || last<first)
+            return;
+
+        for (int i=0; i<1440; i++)
+        {
+            const float *beg = data+i*roi+first;
+            const float *end = data+i*roi+last;
+
+            const float *pmax = beg;
+
+            for (const float *ptr=beg+1; ptr<=end; ptr++)
+                if (*ptr>*pmax)
+                    pmax = ptr;
+
+            max[i] = *pmax;
+        }
+    }
+
+    const std::vector<int64_t> &GetSum() const { return fSum; }
+
+    int64_t GetNumEntries() const { return fNumEntries; }
+};
+
+class DrsCalibrateTime
+{
+public:
+    int64_t fNumEntries;
+
+    size_t fNumSamples;
+    size_t fNumChannels;
+
+    std::vector<std::pair<double, double>> fStat;
+
+public:
+    DrsCalibrateTime() : fNumEntries(0), fNumSamples(0), fNumChannels(0)
+    {
+        InitSize(160, 1024);
+    }
+
+    DrsCalibrateTime(const DrsCalibrateTime &p) : fNumEntries(p.fNumEntries), fNumSamples(p.fNumSamples), fNumChannels(p.fNumChannels), fStat(p.fStat)
+    {
+    }
+    virtual ~DrsCalibrateTime()
+    {
+    }
+
+    double Sum(uint32_t i) const { return fStat[i].first; }
+    double W(uint32_t i) const { return fStat[i].second; }
+
+    virtual void InitSize(uint16_t channels, uint16_t samples)
+    {
+        fNumChannels = channels;
+        fNumSamples  = samples;
+
+        fNumEntries  = 0;
+
+        fStat.clear();
+
+        fStat.resize(samples*channels);
+    }
+
+    void AddT(const float *val, const int16_t *start, signed char edge=0)
+    {
+        if (fNumSamples!=1024 || fNumChannels!=160)
+            return;
+
+        // Rising or falling edge detection has the advantage that
+        // we are much less sensitive to baseline shifts
+
+        for (size_t ch=0; ch<160; ch++)
+        {
+            const size_t tm = ch*9+8;
+
+            const int16_t spos = start[tm];
+            if (spos<0)
+                continue;
+
+            const size_t pos = ch*1024;
+
+            double  p_prev =  0;
+            int32_t i_prev = -1;
+
+            for (size_t i=0; i<1024-1; i++)
+            {
+                const size_t rel = tm*1024 + i;
+
+                const float &v0 = val[rel];  //-avg;
+                const float &v1 = val[rel+1];//-avg;
+
+                // If edge is positive ignore all falling edges
+                if (edge>0 && v0>0)
+                    continue;
+
+                // If edge is negative ignore all falling edges
+                if (edge<0 && v0<0)
+                    continue;
+
+                // Check if there is a zero crossing
+                if ((v0<0 && v1<0) || (v0>0 && v1>0))
+                    continue;
+
+                // Calculate the position p of the zero-crossing
+                // within the interval [rel, rel+1] relative to rel
+                // by linear interpolation.
+                const double p = v0==v1 ? 0.5 : v0/(v0-v1);
+
+                // If this was at least the second zero-crossing detected
+                if (i_prev>=0)
+                {
+                    // Calculate the distance l between the
+                    // current and the last zero-crossing
+                    const double l = i+p - (i_prev+p_prev);
+
+                    // By summation, the average length of each
+                    // cell is calculated. For the first and last
+                    // fraction of a cell, the fraction is applied
+                    // as a weight.
+                    const double w0 = 1-p_prev;
+                    fStat[pos+(spos+i_prev)%1024].first  += w0*l;
+                    fStat[pos+(spos+i_prev)%1024].second += w0;
+
+                    for (size_t k=i_prev+1; k<i; k++)
+                    {
+                        fStat[pos+(spos+k)%1024].first  += l;
+                        fStat[pos+(spos+k)%1024].second += 1;
+                    }
+
+                    const double w1 = p;
+                    fStat[pos+(spos+i)%1024].first  += w1*l;
+                    fStat[pos+(spos+i)%1024].second += w1;
+                }
+
+                // Remember this zero-crossing position
+                p_prev = p;
+                i_prev = i;
+            }
+        }
+        fNumEntries++;
+    }
+
+    void FillEmptyBins()
+    {
+        for (int ch=0; ch<160; ch++)
+        {
+            const auto beg = fStat.begin() + ch*1024;
+            const auto end = beg + 1024;
+
+            double   avg = 0;
+            uint32_t num = 0;
+            for (auto it=beg; it!=end; it++)
+            {
+                if (it->second<fNumEntries-0.5)
+                    continue;
+
+                avg += it->first / it->second;
+                num++;
+            }
+            avg /= num;
+
+            for (auto it=beg; it!=end; it++)
+            {
+                if (it->second>=fNumEntries-0.5)
+                    continue;
+
+                // {
+                //     result[i+1].first  = *is2;
+                //     result[i+1].second = *iw2;
+                // }
+                // else
+                // {
+                it->first  = avg*fNumEntries;
+                it->second = fNumEntries;
+                // }
+            }
+        }
+    }
+
+    DrsCalibrateTime GetComplete() const
+    {
+        DrsCalibrateTime rc(*this);
+        rc.FillEmptyBins();
+        return rc;
+    }
+
+    void CalcResult()
+    {
+        for (int ch=0; ch<160; ch++)
+        {
+            const auto beg = fStat.begin() + ch*1024;
+            const auto end = beg + 1024;
+
+            // First calculate the average length s of a single
+            // zero-crossing interval in the whole range [0;1023]
+            // (which is identical to the/ wavelength of the
+            // calibration signal)
+            double s = 0;
+            double w = 0;
+            for (auto it=beg; it!=end; it++)
+            {
+                s += it->first;
+                w += it->second;
+            }
+            s /= w;
+
+            // Dividing the average length s of the zero-crossing
+            // interval in the range [0;1023] by the average length
+            // in the interval [0;n] yields the relative size of
+            // the interval in the range [0;n].
+            //
+            // Example:
+            // Average [0;1023]: 10.00  (global interval size in samples)
+            // Average [0;512]:   8.00  (local interval size in samples)
+            //
+            // Globally, on average one interval is sampled by 10 samples.
+            // In the sub-range [0;512] one interval is sampled on average
+            // by 8 samples.
+            // That means that the interval contains 64 periods, while
+            // in the ideal case (each sample has the same length), it
+            // should contain 51.2 periods.
+            // So, the sampling position 512 corresponds to a time 640,
+            // while in the ideal case with equally spaces samples,
+            // it would correspond to a time 512.
+            //
+            // The offset (defined as 'ideal - real') is then calculated
+            // as 512*(1-10/8) = -128, so that the time is calculated as
+            // 'sampling position minus offset'
+            //
+            double sumw = 0;
+            double sumv = 0;
+            int n = 0;
+
+            // Sums about many values are numerically less stable than
+            // just sums over less. So we do the exercise from both sides.
+            // First from the left
+            for (auto it=beg; it!=end-512; it++, n++)
+            {
+                const double valv = it->first;
+                const double valw = it->second;
+
+                it->first = sumv>0 ? n*(1-s*sumw/sumv) : 0;
+
+                sumv += valv;
+                sumw += valw;
+            }
+
+            sumw = 0;
+            sumv = 0;
+            n = 1;
+
+            // Second from the right
+            for (auto it=end-1; it!=beg-1+512; it--, n++)
+            {
+                const double valv = it->first;
+                const double valw = it->second;
+
+                sumv += valv;
+                sumw += valw;
+
+                it->first = sumv>0 ? n*(s*sumw/sumv-1) : 0;
+            }
+
+            // A crosscheck has shown, that the values from the left
+            // and right perfectly agree over the whole range. This means
+            // the a calculation from just one side would be enough, but
+            // doing it from both sides might still make the numerics
+            // a bit more stable.
+        }
+    }
+
+    DrsCalibrateTime GetResult() const
+    {
+        DrsCalibrateTime rc(*this);
+        rc.CalcResult();
+        return rc;
+    }
+
+    double Offset(uint32_t ch, double pos) const
+    {
+        const auto p = fStat.begin() + ch*1024;
+
+        const uint32_t f = floor(pos);
+
+        const double v0 = p[f].first;
+        const double v1 = p[(f+1)%1024].first;
+
+        return v0 + fmod(pos, 1)*(v1-v0);
+    }
+
+    double Calib(uint32_t ch, double pos) const
+    {
+        return pos-Offset(ch, pos);
+    }
+};
+
+struct DrsCalibration
+{
+    std::vector<int32_t> fOffset;
+    std::vector<int64_t> fGain;
+    std::vector<int64_t> fTrgOff;
+
+    int64_t fNumOffset;
+    int64_t fNumGain;
+    int64_t fNumTrgOff;
+
+    uint32_t fStep;
+    uint16_t fRoi;   // Region of interest for trgoff
+    uint16_t fNumTm; // Number of time marker channels in trgoff
+
+    std::string fDateObs;
+    std::string fDateRunBeg[3];
+    std::string fDateRunEnd[3];
+    std::string fDateEnd;
+
+//    uint16_t fDAC[8];
+
+    DrsCalibration() :
+        fOffset(1440*1024, 0),
+        fGain(1440*1024, 4096),
+        fTrgOff (1600*1024, 0),
+        fNumOffset(1),
+        fNumGain(2000),
+        fNumTrgOff(1),
+        fStep(0),
+        fDateObs("1970-01-01T00:00:00"),
+        fDateEnd("1970-01-01T00:00:00")
+    {
+        for (int i=0; i<3; i++)
+        {
+            fDateRunBeg[i] = "1970-01-01T00:00:00";
+            fDateRunEnd[i] = "1970-01-01T00:00:00";
+        }
+    }
+
+    DrsCalibration(const DrsCalibration &cpy) :
+        fOffset(cpy.fOffset),
+        fGain(cpy.fGain),
+        fTrgOff(cpy.fTrgOff),
+        fNumOffset(cpy.fNumOffset),
+        fNumGain(cpy.fNumGain),
+        fNumTrgOff(cpy.fNumTrgOff),
+        fStep(cpy.fStep),
+        fRoi(cpy.fRoi),
+        fNumTm(cpy.fNumTm),
+        fDateObs(cpy.fDateObs),
+        fDateRunBeg(cpy.fDateRunBeg),
+        fDateRunEnd(cpy.fDateRunEnd),
+        fDateEnd(cpy.fDateEnd)
+    {
+    }
+
+    void Clear()
+    {
+        // Default gain:
+        // 0.575*[45590]*2.5V / 2^16 = 0.99999 V
+        fOffset.assign(1440*1024, 0);
+        fGain.assign  (1440*1024, 4096);
+        fTrgOff.assign(1600*1024, 0);
+
+        fNumOffset = 1;
+        fNumGain   = 2000;
+        fNumTrgOff = 1;
+
+        fStep = 0;
+
+        fDateObs = "1970-01-01T00:00:00";
+        fDateEnd = "1970-01-01T00:00:00";
+
+        for (int i=0; i<3; i++)
+        {
+            fDateRunBeg[i] = "1970-01-01T00:00:00";
+            fDateRunEnd[i] = "1970-01-01T00:00:00";
+        }
+    }
+
+    std::string ReadFitsImp(const std::string &str, std::vector<float> &vec)
+    {
+        fits file(str);
+        if (!file)
+        {
+            std::ostringstream msg;
+            msg << "Could not open file '" << str << "': " << strerror(errno);
+            return msg.str();
+        }
+
+        if (file.GetStr("TELESCOP")!="FACT")
+        {
+            std::ostringstream msg;
+            msg << "Reading '" << str << "' failed: Not a valid FACT file (TELESCOP not FACT in header)";
+            return msg.str();
+        }
+
+        if (!file.HasKey("STEP"))
+        {
+            std::ostringstream msg;
+            msg << "Reading '" << str << "' failed: Is not a DRS calib file (STEP not found in header)";
+            return msg.str();
+        }
+
+        if (file.GetNumRows()!=1)
+        {
+            std::ostringstream msg;
+            msg << "Reading '" << str << "' failed: Number of rows in table is not 1.";
+            return msg.str();
+        }
+
+        fStep      = file.GetUInt("STEP");
+        fNumOffset = file.GetInt("NBOFFSET");
+        fNumGain   = file.GetInt("NBGAIN");
+        fNumTrgOff = file.GetInt("NBTRGOFF");
+        fRoi       = file.GetUInt("NROI");
+        fNumTm     = file.HasKey("NTM") ? file.GetUInt("NTM") : 0;
+
+        if (file.HasKey("DATE-OBS"))
+            fDateObs   = file.GetStr("DATE-OBS");
+        if (file.HasKey("DATE-END"))
+            fDateEnd   = file.GetStr("DATE-END");
+
+        if (file.HasKey("RUN0-BEG"))
+            fDateRunBeg[0]= file.GetStr("RUN0-BEG");
+        if (file.HasKey("RUN1-BEG"))
+            fDateRunBeg[1]= file.GetStr("RUN1-BEG");
+        if (file.HasKey("RUN2-BEG"))
+            fDateRunBeg[2]= file.GetStr("RUN2-BEG");
+        if (file.HasKey("RUN0-END"))
+            fDateRunEnd[0]= file.GetStr("RUN0-END");
+        if (file.HasKey("RUN1-END"))
+            fDateRunEnd[1]= file.GetStr("RUN1-END");
+        if (file.HasKey("RUN2-END"))
+            fDateRunEnd[2]= file.GetStr("RUN2-END");
+/*
+        fDAC[0]    = file.GetUInt("DAC_A");
+        fDAC[1]    = file.GetUInt("DAC_B");
+        fDAC[4]    = file.GetUInt("DAC_C");
+*/
+        vec.resize(1440*1024*4 + (1440+fNumTm)*fRoi*2 + 4);
+
+        float *base = vec.data();
+
+        reinterpret_cast<uint32_t*>(base)[0] = fRoi;
+
+        file.SetPtrAddress("RunNumberBaseline",      base+1, 1);
+        file.SetPtrAddress("RunNumberGain",          base+2, 1);
+        file.SetPtrAddress("RunNumberTriggerOffset", base+3, 1);
+        file.SetPtrAddress("BaselineMean",           base+4+0*1024*1440,           1024*1440);
+        file.SetPtrAddress("BaselineRms",            base+4+1*1024*1440,           1024*1440);
+        file.SetPtrAddress("GainMean",               base+4+2*1024*1440,           1024*1440);
+        file.SetPtrAddress("GainRms",                base+4+3*1024*1440,           1024*1440);
+        file.SetPtrAddress("TriggerOffsetMean",      base+4+4*1024*1440,           fRoi*1440);
+        file.SetPtrAddress("TriggerOffsetRms",       base+4+4*1024*1440+fRoi*1440, fRoi*1440);
+        if (fNumTm>0)
+        {
+            file.SetPtrAddress("TriggerOffsetTMMean", base+4+4*1024*1440+ 2*fRoi*1440,              fRoi*fNumTm);
+            file.SetPtrAddress("TriggerOffsetTMRms",  base+4+4*1024*1440+ 2*fRoi*1440+ fRoi*fNumTm, fRoi*fNumTm);
+        }
+
+        if (!file.GetNextRow())
+        {
+            std::ostringstream msg;
+            msg << "Reading data from " << str << " failed.";
+            return msg.str();
+        }
+/*
+        fDAC[2] = fDAC[1];
+        fDAC[4] = fDAC[1];
+
+        fDAC[5] = fDAC[4];
+        fDAC[6] = fDAC[4];
+        fDAC[7] = fDAC[4];
+*/
+        fOffset.resize(1024*1440);
+        fGain.resize(1024*1440);
+
+        fTrgOff.resize(fRoi*(1440+fNumTm));
+
+        // Convert back to ADC counts: 256/125 = 4096/2000
+        // Convert back to sum (mean * num_entries)
+        for (int i=0; i<1024*1440; i++)
+        {
+            fOffset[i] = fNumOffset         *256*base[i+1024*1440*0+4]/125;
+            fGain[i]   = fNumOffset*fNumGain*256*base[i+1024*1440*2+4]/125;
+        }
+
+        for (int i=0; i<fRoi*1440; i++)
+            fTrgOff[i] = fNumOffset*fNumTrgOff*256*base[i+1024*1440*4+4]/125;
+
+        for (int i=0; i<fRoi*fNumTm; i++)
+            fTrgOff[i+1440*fRoi] = fNumOffset*fNumTrgOff*256*base[i+1024*1440*4+2*fRoi*1440+4]/125;
+
+
+        // DAC:  0..2.5V == 0..65535
+        // V-mV: 1000
+        //fNumGain *= 2500*50000;
+        //for (int i=0; i<1024*1440; i++)
+        //    fGain[i] *= 65536;
+        if (fStep==0)
+        {
+            for (int i=0; i<1024*1440; i++)
+                fGain[i] = fNumOffset*4096;
+        }
+        else
+        {
+            fNumGain *= 1953125;
+            for (int i=0; i<1024*1440; i++)
+                fGain[i] *= 1024;
+        }
+
+        // Now mark the stored DRS data as "officially valid"
+        // However, this is not thread safe. It only ensures that
+        // this data is not used before it is completely and correctly
+        // read.
+        fStep++;
+
+        return std::string();
+    }
+
+    std::string WriteFitsImp(const std::string &filename, const std::vector<float> &vec, uint32_t night=0) const
+    {
+        const size_t n = 1440*1024*4 + 1440*fRoi*2 + fNumTm*fRoi*2 + 3;
+
+        ofits file(filename.c_str());
+        if (!file)
+        {
+            std::ostringstream msg;
+            msg << "Could not open file '" << filename << "': " << strerror(errno);
+            return msg.str();
+        }
+
+        file.AddColumnInt("RunNumberBaseline");
+        file.AddColumnInt("RunNumberGain");
+        file.AddColumnInt("RunNumberTriggerOffset");
+
+        file.AddColumnFloat(1024*1440,   "BaselineMean",        "mV");
+        file.AddColumnFloat(1024*1440,   "BaselineRms",         "mV");
+        file.AddColumnFloat(1024*1440,   "GainMean",            "mV");
+        file.AddColumnFloat(1024*1440,   "GainRms",             "mV");
+        file.AddColumnFloat(fRoi*1440,   "TriggerOffsetMean",   "mV");
+        file.AddColumnFloat(fRoi*1440,   "TriggerOffsetRms",    "mV");
+        file.AddColumnFloat(fRoi*fNumTm, "TriggerOffsetTMMean", "mV");
+        file.AddColumnFloat(fRoi*fNumTm, "TriggerOffsetTMRms",  "mV");
+
+        file.SetDefaultKeys();
+        if (night>0)
+            file.SetInt("NIGHT", night, "Night as int");
+
+        file.SetStr("DATE-OBS", fDateObs, "First event of whole DRS calibration");
+        file.SetStr("DATE-END", fDateEnd, "Last event of whole DRS calibration");
+        file.SetStr("RUN0-BEG", fDateRunBeg[0], "First event of run 0");
+        file.SetStr("RUN1-BEG", fDateRunBeg[1], "First event of run 1");
+        file.SetStr("RUN2-BEG", fDateRunBeg[2], "First event of run 2");
+        file.SetStr("RUN0-END", fDateRunEnd[0], "Last event of run 0");
+        file.SetStr("RUN1-END", fDateRunEnd[1], "Last event of run 1");
+        file.SetStr("RUN2-END", fDateRunEnd[2], "Last event of run 2");
+
+        file.SetInt("STEP", fStep, "");
+
+        file.SetInt("ADCRANGE", 2000,    "Dynamic range of the ADC in mV");
+        file.SetInt("DACRANGE", 2500,    "Dynamic range of the DAC in mV");
+        file.SetInt("ADC",      12,      "Resolution of ADC in bits");
+        file.SetInt("DAC",      16,      "Resolution of DAC in bits");
+        file.SetInt("NPIX",     1440,    "Number of channels in the camera");
+        file.SetInt("NTM",      fNumTm,  "Number of time marker channels");
+        file.SetInt("NROI",     fRoi,    "Region of interest");
+
+        file.SetInt("NBOFFSET", fNumOffset,       "Num of entries for offset calibration");
+        file.SetInt("NBGAIN",   fNumGain/1953125, "Num of entries for gain calibration");
+        file.SetInt("NBTRGOFF", fNumTrgOff,       "Num of entries for trigger offset calibration");
+
+        // file.WriteKeyNT("DAC_A",    fData.fDAC[0],    "Level of DAC 0 in DAC counts")   ||
+        // file.WriteKeyNT("DAC_B",    fData.fDAC[1],    "Leval of DAC 1-3 in DAC counts") ||
+        // file.WriteKeyNT("DAC_C",    fData.fDAC[4],    "Leval of DAC 4-7 in DAC counts") ||
+
+        file.WriteTableHeader("DrsCalibration");
+
+        if (!file.WriteRow(vec.data()+1, n*sizeof(float)))
+        {
+            std::ostringstream msg;
+            msg << "Writing data to " << filename << " failed.";
+            return msg.str();
+        }
+
+        return std::string();
+    }
+
+
+    std::string ReadFitsImp(const std::string &str)
+    {
+        std::vector<float> vec;
+        return ReadFitsImp(str, vec);
+    }
+
+    bool IsValid() { return fStep>2; }
+
+    bool Apply(float *vec, const int16_t *val, const int16_t *start, uint32_t roi)
+    {
+        if (roi!=fRoi)
+        {
+            for (size_t ch=0; ch<1440; ch++)
+            {
+                const size_t pos = ch*roi;
+                const size_t drs = ch*1024;
+
+                DrsCalibrate::ApplyCh(vec+pos, val+pos, start[ch], roi,
+                                      fOffset.data()+drs, fNumOffset,
+                                      fGain.data()  +drs, fNumGain);
+            }
+
+            return false;
+        }
+
+        for (size_t ch=0; ch<1440; ch++)
+        {
+            const size_t pos = ch*fRoi;
+            const size_t drs = ch*1024;
+
+            DrsCalibrate::ApplyCh(vec+pos, val+pos, start[ch], roi,
+                                  fOffset.data()+drs, fNumOffset,
+                                  fGain.data()  +drs, fNumGain,
+                                  fTrgOff.data()+pos, fNumTrgOff);
+        }
+
+        for (size_t ch=0; ch<fNumTm; ch++)
+        {
+            const size_t pos = (ch+1440)*fRoi;
+            const size_t drs = (ch*9+8)*1024;
+
+            DrsCalibrate::ApplyCh(vec+pos, val+pos, start[ch], roi,
+                                  fOffset.data()+drs, fNumOffset,
+                                  fGain.data()  +drs, fNumGain,
+                                  fTrgOff.data()+pos, fNumTrgOff);
+        }
+
+        return true;
+    }
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/FITS.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/FITS.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/FITS.h	(revision 17960)
@@ -0,0 +1,185 @@
+/*
+ *
+ * FITS.h
+ *
+ * Global fits header
+ *
+ * Author: lyard
+ *
+ */
+
+#ifndef MARS_FITS
+#define MARS_FITS
+
+#include <stdint.h>
+#include <string.h>
+
+#include <vector>
+#include <string>
+
+#ifndef __CINT__
+#include <unordered_set>
+#endif
+
+namespace FITS
+{
+    static inline bool IsReservedKeyWord(const std::string &key)
+    {
+#ifndef __CINT__
+        static const std::unordered_set<std::string> keys =
+        {
+            "DATASUM",  "END",      "EXTNAME",  "PCOUNT",   "NAXIS",
+            "NAXIS1",   "NAXIS2",   "RAWSUM",   "SIMPLE",   "TFIELDS",
+            "THEAP",    "XTENSION", "ZHEAPPTR", "ZNAXIS1",  "ZNAXIS2",
+            "ZPCOUNT",  "ZRATIO",   "ZSHRINK",  "ZTABLE",   "ZTILELEN",
+        };
+
+        static const std::unordered_set<std::string> short_keys =
+        {
+            "TFORM", "TUNIT", "TTYPE", "ZCTYP", "ZFORM",
+        };
+
+        if (keys.find(key)!=keys.end())
+            return true;
+
+        const std::string five = key.substr(0, 5);
+        return short_keys.find(five)!=short_keys.end();
+#endif
+    }
+
+    static inline std::string CommentFromType(char type)
+    {
+        std::string comment;
+
+        switch (type)
+        {
+        case 'L': comment = "[1-byte BOOL]";  break;
+        case 'A': comment = "[1-byte CHAR]";  break;
+        case 'B': comment = "[1-byte BOOL]";  break;
+        case 'I': comment = "[2-byte INT]";   break;
+        case 'J': comment = "[4-byte INT]";   break;
+        case 'K': comment = "[8-byte INT]";   break;
+        case 'E': comment = "[4-byte FLOAT]"; break;
+        case 'D': comment = "[8-byte FLOAT]"; break;
+        case 'Q': comment = "[var. Length]"; break;
+        }
+
+        return comment;
+    }
+
+    static inline uint32_t SizeFromType(char type)
+    {
+        size_t size = 0;
+
+        switch (type)
+        {
+        case 'L': 
+        case 'A': 
+        case 'B': size =  1; break;
+        case 'I': size =  2; break;
+        case 'J': 
+        case 'E': size =  4; break;
+        case 'K': 
+        case 'D': size =  8; break;
+        case 'Q': size = 16; break;
+        }
+
+        return size;
+    }
+
+    //Identifier of the compression schemes processes
+    enum CompressionProcess_t
+    {
+        kFactRaw       = 0x0,
+        kFactSmoothing = 0x1,
+        kFactHuffman16 = 0x2
+    };
+
+    //ordering of the columns / rows
+    enum RowOrdering_t
+    {
+        kOrderByCol = 'C',
+        kOrderByRow = 'R'
+    };
+
+#ifdef __CINT__
+    // CINT doesn't like the packed attribute...
+    // Therefore we give another hint of the size of the structure
+    struct TileHeader  { char dummy[16]; };
+    struct BlockHeader { char dummy[10]; };
+#else
+    //Structure helper for tiles headers
+    struct TileHeader
+    {
+      char     id[4];
+      uint32_t numRows;
+      uint64_t size;
+
+      TileHeader() {}
+
+      TileHeader(uint32_t nRows,
+                 uint64_t s) : id({'T', 'I', 'L', 'E'}),
+                                 numRows(nRows),
+                                 size(s)
+      { };
+    } __attribute__((__packed__));
+
+    //Structure helper for blocks headers and compresion schemes
+    struct BlockHeader
+    {
+        uint64_t      size;
+        char          ordering;
+        unsigned char numProcs;
+        uint16_t      processings[];
+
+        BlockHeader(uint64_t      s=0,
+                    char          o=kOrderByRow,
+                    unsigned char n=1) : size(s),
+                                         ordering(o),
+                                         numProcs(n)
+        {
+        }
+    } __attribute__((__packed__));
+#endif
+
+    //Helper structure to simplify the initialization and handling of compressed blocks headers
+    struct Compression
+    {
+        BlockHeader header;
+        std::vector<uint16_t> sequence;
+
+        Compression(const std::vector<uint16_t> &seq, const RowOrdering_t &order=kOrderByCol)
+            : header(0, order, seq.size()), sequence(seq)
+        {
+        }
+
+        Compression(const CompressionProcess_t &compression=kFactRaw, const RowOrdering_t &order=kOrderByCol)
+            : header(0, order, 1), sequence(1)
+        {
+            sequence[0] = compression;
+        }
+
+#ifdef __MARS__ // needed for CINT
+        Compression(const int &compression)
+            : header(0, kOrderByCol, 1), sequence(1)
+        {
+            sequence[0] = compression;
+        }
+#endif
+
+        RowOrdering_t getOrdering() const { return RowOrdering_t(header.ordering); }
+        uint32_t getSizeOnDisk() const { return sizeof(BlockHeader) + sizeof(uint16_t)*header.numProcs; }
+        CompressionProcess_t getProc(uint32_t i) const { return CompressionProcess_t(sequence[i]); }
+        uint16_t getNumProcs() const { return header.numProcs; }
+
+        void SetBlockSize(uint64_t size) { header.size = size; }
+        void Memcpy(char *dest) const
+        {
+            memcpy(dest, &header, sizeof(BlockHeader));
+            memcpy(dest+sizeof(BlockHeader), sequence.data(), header.numProcs*sizeof(uint16_t));
+        }
+    };
+};
+
+#endif //_FITS_H_
+
Index: branches/Mars_McMismatchStudy/mcore/Interpolator2D.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/Interpolator2D.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/Interpolator2D.h	(revision 17960)
@@ -0,0 +1,502 @@
+// **************************************************************************
+/** @class Interpolator2D
+
+@brief Extra- and interpolate in 2D
+
+This class implements a kind of Delaunay triangulation. It calculated the
+Voronoi points and the corresponding Delaunay triangles. Within each
+triangle a bi-linear interpolation is provided.
+
+A special selection criterion is applied for points outside the grid,
+so that extrapolation is possible. Note that extrapolation of far away
+points (as in the 1D case) is not recommended.
+
+*/
+// **************************************************************************
+#ifndef FACT_Interpolator2D
+#define FACT_Interpolator2D
+
+#include <float.h>
+#include <math.h>
+#include <vector>
+#include <fstream>
+
+class Interpolator2D
+{
+public:
+    struct vec
+    {
+        double x;
+        double y;
+
+        vec(double _x=0, double _y=0) : x(_x), y(_y) { }
+
+        vec orto() const { return vec(-y, x); }
+
+        double dist(const vec &v) const { return hypot(x-v.x, y-v.y); }
+        double operator^(const vec &v) const { return x*v.y - y*v.x; }
+        vec operator-(const vec &v) const { return vec(x-v.x, y-v.y); }
+        vec operator+(const vec &v) const { return vec(x+v.x, y+v.y); }
+        vec operator/(double b)     const { return vec(x/b, y/b); }
+    };
+
+
+    struct point : vec
+    {
+        unsigned int i;
+        point(unsigned int _i, const vec &_v) : vec(_v), i(_i) { }
+        point(unsigned int _i=0, double _x=0, double _y=0) : vec(_x, _y), i(_i) { }
+    };
+
+    struct circle : point
+    {
+        point p[3];
+        double r;
+
+        static bool sameSide(const vec &p1, const vec &p2, const vec &a, const vec &b)
+        {
+            return ((b-a)^(p1-a))*((b-a)^(p2-a)) > 0;
+        }
+
+        bool isInsideTriangle(const vec &v) const
+        {
+            return sameSide(v, p[0], p[1], p[2]) && sameSide(v, p[1], p[0], p[2]) && sameSide(v, p[2], p[0], p[1]);
+        }
+
+        bool isInsideCircle(const vec &v) const
+        {
+            return dist(v) < r;
+        }
+    };
+
+    struct weight : point
+    {
+        circle c;
+        double w[3];
+    };
+
+private:
+    std::vector<point>  inputGrid;   /// positions of the data points (e.g. sensors)
+    std::vector<point>  outputGrid;  /// positions at which inter-/extrapolated values should be provided
+    std::vector<circle> circles;     /// the calculated circles/triangles
+    std::vector<weight> weights;     /// the weights used for the interpolation
+
+    // --------------------------------------------------------------------------
+    //
+    //! Calculate the collection of circles/triangles which describe the
+    //! input grid. This is the collection of circles which are calculated
+    //! from any three points and do not contain any other point of the grid.
+    //
+    void CalculateGrid()
+    {
+        circles.reserve(2*inputGrid.size());
+
+        // Loop over all triplets of points
+        for (auto it0=inputGrid.cbegin(); it0<inputGrid.cend(); it0++)
+        {
+            for (auto it1=inputGrid.cbegin(); it1<it0; it1++)
+            {
+                for (auto it2=inputGrid.cbegin(); it2<it1; it2++)
+                {
+                    // Calculate the circle through the three points
+
+                    // Vectors along the side of the corresponding triangle
+                    const vec v1 = *it1 - *it0;
+                    const vec v2 = *it2 - *it1;
+
+                    // Orthogonal vectors on the sides
+                    const vec n1 = v1.orto();
+                    const vec n2 = v2.orto();
+
+                    // Center point of two of the three sides
+                    const vec p1 = (*it0 + *it1)/2;
+                    const vec p2 = (*it1 + *it2)/2;
+
+                    // Calculate the crossing point of the two
+                    // orthogonal vectors originating in the
+                    // center of the sides.
+                    const double denom = n1^n2;
+                    if (denom==0)
+                        continue;
+
+                    const vec x(n1.x, n2.x);
+                    const vec y(n1.y, n2.y);
+
+                    const vec w(p1^(p1+n1), p2^(p2+n2));
+
+                    circle c;
+
+                    // This is the x and y coordinate of the circle
+                    // through the three points and the circle's radius.
+                    c.x = (x^w)/denom;
+                    c.y = (y^w)/denom;
+                    c.r = c.dist(*it1);
+
+                    // Check if any other grid point lays within this circle
+                    auto it3 = inputGrid.cbegin();
+                    for (; it3<inputGrid.cend(); it3++)
+                    {
+                        if (it3==it0 || it3==it1 || it3==it2)
+                            continue;
+
+                        if (c.isInsideCircle(*it3))
+                            break;
+                    }
+
+                    // If a point was found inside, reject the circle
+                    if (it3!=inputGrid.cend())
+                        continue;
+
+                    // Store the three points of the triangle
+                    c.p[0] = *it0;
+                    c.p[1] = *it1;
+                    c.p[2] = *it2;
+
+                    // Keep in list
+                    circles.push_back(c);
+                }
+            }
+        }
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    //! Calculate the weights corresponding to the points in the output grid.
+    //! Weights are calculated by bi-linear interpolation. For interpolation,
+    //! the triangle which contains the point and has the smallest radius
+    //! is searched. If this is not available in case of extrapolation,
+    //! the condition is relaxed and requires only the circle to contain
+    //! the point. If such circle is not available, the circle with the
+    //! closest center is chosen.
+    //
+    bool CalculateWeights()
+    {
+        weights.reserve(outputGrid.size());
+
+        // Loop over all points in the output grid
+        for (auto ip=outputGrid.cbegin(); ip<outputGrid.cend(); ip++)
+        {
+            double mindd = DBL_MAX;
+
+            auto mint = circles.cend();
+            auto minc = circles.cend();
+            auto mind = circles.cend();
+
+            for (auto ic=circles.cbegin(); ic<circles.cend(); ic++)
+            {
+                // Check if point is inside the triangle
+                if (ic->isInsideTriangle(*ip))
+                {
+                    if (mint==circles.cend() || ic->r<mint->r)
+                        mint = ic;
+                }
+
+                // If we have found such a triangle, no need to check for more
+                if (mint!=circles.cend())
+                    continue;
+
+                // maybe at least inside the circle
+                const double dd = ic->dist(*ip);
+                if (dd<ic->r)
+                {
+                    if (minc==circles.cend() || ic->r<minc->r)
+                        minc = ic;
+                }
+
+                // If we found such a circle, no need to check for more
+                if (minc!=circles.cend())
+                    continue;
+
+                // then look for the closest circle center
+                if (dd<mindd)
+                {
+                    mindd = dd;
+                    mind  = ic;
+                }
+            }
+
+            // Choose the best of the three options
+            const auto it = mint==circles.cend() ? (minc==circles.cend() ? mind : minc) : mint;
+            if (it==circles.cend())
+                return false;
+
+            // Calculate the bi-linear interpolation
+            const vec &p1 = it->p[0];
+            const vec &p2 = it->p[1];
+            const vec &p3 = it->p[2];
+
+            const double dy23 = p2.y - p3.y;
+            const double dy31 = p3.y - p1.y;
+            const double dy12 = p1.y - p2.y;
+
+            const double dx32 = p3.x - p2.x;
+            const double dx13 = p1.x - p3.x;
+            const double dx21 = p2.x - p1.x;
+
+            const double dxy23 = p2^p3;
+            const double dxy31 = p3^p1;
+            const double dxy12 = p1^p2;
+
+            const double det = dxy12 + dxy23 + dxy31;
+
+            const double w1 = (dy23*ip->x + dx32*ip->y + dxy23)/det;
+            const double w2 = (dy31*ip->x + dx13*ip->y + dxy31)/det;
+            const double w3 = (dy12*ip->x + dx21*ip->y + dxy12)/det;
+
+            // Store the original grid-point, the circle's parameters
+            // and the calculate weights
+            weight w;
+            w.x = ip->x;
+            w.y = ip->y;
+            w.c = *it;
+            w.w[0] = w1;
+            w.w[1] = w2;
+            w.w[2] = w3;
+
+            weights.push_back(w);
+        }
+
+        return true;
+    }
+
+public:
+    // --------------------------------------------------------------------------
+    //
+    //! Default constructor. Does nothing.
+    //
+    Interpolator2D()
+    {
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    //! Initialize the input grid (the points at which values are known).
+    //!
+    //! @param n
+    //!    number of data points
+    //!
+    //! @param x
+    //!    x coordinates of data points
+    //!
+    //! @param n
+    //!    y coordinates of data points
+    //
+    Interpolator2D(int n, double *x, double *y)
+    {
+        SetInputGrid(n, x, y);
+    }
+
+    Interpolator2D(const std::vector<Interpolator2D::vec> &v)
+    {
+        SetInputGrid(v);
+    }
+
+    const std::vector<Interpolator2D::weight> getWeights() const { return weights; }
+    const std::vector<Interpolator2D::point>  getInputGrid() const { return inputGrid; }
+    const std::vector<Interpolator2D::point>  getOutputGrid() const { return outputGrid; }
+
+    // --------------------------------------------------------------------------
+    //
+    //! helper function to read a grid from a simple file
+    //! (alternating x, y)
+    //!
+    //! @param filename
+    //!    filename of ascii file with data
+    //!
+    //! @returns
+    //!    a vector of point with the x and y values.
+    //!    in case of failure the vector is empty
+    //
+    static std::vector<Interpolator2D::vec> ReadGrid(const std::string &filename)
+    {
+        std::vector<Interpolator2D::vec> grid;
+
+        std::ifstream fin(filename);
+        if (!fin.is_open())
+            return std::vector<Interpolator2D::vec>();
+
+        while (1)
+        {
+            double x, y;
+            fin >> x;
+            fin >> y;
+            if (!fin)
+                break;
+
+            grid.emplace_back(x, y);
+        }
+
+        return fin.bad() ? std::vector<Interpolator2D::vec>() : grid;
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    //! Set a new input grid (the points at which values are known).
+    //! Invalidates the output grid and the calculated weights.
+    //! Calculates the triangles corresponding to the new grid.
+    //!
+    //! @param n
+    //!    number of data points
+    //!
+    //! @param x
+    //!    x coordinates of data points
+    //!
+    //! @param n
+    //!    y coordinates of data points
+    //
+    void SetInputGrid(unsigned int n, double *x, double *y)
+    {
+        circles.clear();
+        weights.clear();
+        outputGrid.clear();
+
+        inputGrid.clear();
+        inputGrid.reserve(n);
+        for (unsigned int i=0; i<n; i++)
+            inputGrid.emplace_back(i, x[i], y[i]);
+
+        CalculateGrid();
+    }
+
+    void SetInputGrid(const std::vector<Interpolator2D::vec> &v)
+    {
+        circles.clear();
+        weights.clear();
+        outputGrid.clear();
+
+        inputGrid.clear();
+        inputGrid.reserve(v.size());
+        for (unsigned int i=0; i<v.size(); i++)
+            inputGrid.emplace_back(i, v[i]);
+
+        CalculateGrid();
+    }
+
+    /*
+    void SetInputGrid(const std::vector<Interpolator2D::point> &v)
+    {
+        circles.clear();
+        weights.clear();
+        outputGrid.clear();
+
+        inputGrid.clear();
+        inputGrid.reserve(v.size());
+        for (unsigned int i=0; i<v.size(); i++)
+            inputGrid.emplace_back(v[i], i);
+
+        CalculateGrid();
+    }*/
+
+    bool ReadInputGrid(const std::string &filename)
+    {
+        const auto grid = ReadGrid(filename);
+        if (grid.empty())
+            return false;
+
+        SetInputGrid(grid);
+        return true;
+    }
+
+
+    // --------------------------------------------------------------------------
+    //
+    //! Set a new output grid (the points at which you want interpolated
+    //! or extrapolated values). Calculates new weights.
+    //!
+    //! @param n
+    //!    number of points
+    //!
+    //! @param x
+    //!    x coordinates of points
+    //!
+    //! @param n
+    //!    y coordinates of points
+    //!
+    //! @returns
+    //!    false if the calculation of the weights failed, true in
+    //!    case of success
+    //
+    bool SetOutputGrid(std::size_t n, double *x, double *y)
+    {
+        if (inputGrid.empty() && n==0)
+            return false;
+
+        weights.clear();
+
+        outputGrid.clear();
+        outputGrid.reserve(n);
+        for (std::size_t i=0; i<n; i++)
+            outputGrid.emplace_back(i, x[i], y[i]);
+
+        return CalculateWeights();
+    }
+
+    /*
+    bool SetOutputGrid(const std::vector<std::pair<double,double>> &v)
+    {
+        if (inputGrid.empty() || v.empty())
+            return false;
+
+        weights.clear();
+
+        outputGrid.clear();
+        outputGrid.reserve(v.size());
+        for (std::size_t i=0; i<v.size(); i++)
+            outputGrid.emplace_back(i, v[i].first, v[i].second);
+
+        return CalculateWeights();
+    }*/
+
+    bool SetOutputGrid(const std::vector<Interpolator2D::vec> &v)
+    {
+        if (inputGrid.empty())
+            return false;
+
+        weights.clear();
+
+        outputGrid.clear();
+        outputGrid.reserve(v.size());
+        for (std::size_t i=0; i<v.size(); i++)
+            outputGrid.emplace_back(i, v[i]);
+
+        return CalculateWeights();
+    }
+
+    bool ReadOutputGrid(const std::string &filename)
+    {
+        const auto grid = ReadGrid(filename);
+        if (grid.empty())
+            return false;
+
+        return SetOutputGrid(grid);
+    }
+
+
+    // --------------------------------------------------------------------------
+    //
+    //! Perform interpolation. 
+    //!
+    //! @param z
+    //!    Values at the coordinates of the input grid. The order
+    //!    must be identical.
+    //!
+    //! @returns
+    //!    A vector<double> is returned with the interpolated values in the
+    //!    same order than the putput grid. If the provided vector does
+    //!    not match the size of the inputGrid, an empty vector is returned.
+    //
+    std::vector<double> Interpolate(const std::vector<double> &z) const
+    {
+        if (z.size()!=inputGrid.size())
+            return std::vector<double>();
+
+        std::vector<double> rc;
+        rc.reserve(z.size());
+
+        for (auto it=weights.cbegin(); it<weights.cend(); it++)
+            rc.push_back(z[it->c.p[0].i] * it->w[0] + z[it->c.p[1].i] * it->w[1] + z[it->c.p[2].i] * it->w[2]);
+
+        return rc;
+    }
+};
+#endif
Index: branches/Mars_McMismatchStudy/mcore/MemoryManager.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/MemoryManager.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/MemoryManager.h	(revision 17960)
@@ -0,0 +1,167 @@
+#ifndef MARS_MemoryManager
+#define MARS_MemoryManager
+
+#ifndef __CINT__
+#include <forward_list>
+#else
+namespace std
+{
+    class mutex;
+    class condition_variable;
+    template<class T> class shared_ptr<T>;
+    template<class T> class forward_list<T>;
+}
+#endif
+
+class MemoryStock
+{
+    friend class MemoryChunk;
+    friend class MemoryManager;
+
+    size_t fChunkSize;
+    size_t fMaxMemory;
+
+    size_t fInUse;
+    size_t fAllocated;
+
+    size_t fMaxInUse;
+
+    std::mutex fMutexMem;
+    std::mutex fMutexCond;
+    std::condition_variable fCond;
+
+    std::forward_list<std::shared_ptr<char>> fMemoryStock;
+
+public:
+    MemoryStock(size_t chunk, size_t max) : fChunkSize(chunk), fMaxMemory(max<chunk?chunk:max),
+        fInUse(0), fAllocated(0), fMaxInUse(0)
+    {
+    }
+
+private:
+    std::shared_ptr<char> pop(bool block)
+    {
+        if (block)
+        {
+            // No free slot available, next alloc would exceed max memory:
+            // block until a slot is available
+            std::unique_lock<std::mutex> lock(fMutexCond);
+            while (fMemoryStock.empty() && fAllocated+fChunkSize>fMaxMemory)
+                fCond.wait(lock);
+        }
+        else
+        {
+            // No free slot available, next alloc would exceed max memory
+            // return an empty pointer
+            if (fMemoryStock.empty() && fAllocated+fChunkSize>fMaxMemory)
+                return std::shared_ptr<char>();
+        }
+
+        // We will return this amount of memory
+        // This is not 100% thread safe, but it is not a super accurate measure anyway
+        fInUse += fChunkSize;
+        if (fInUse>fMaxInUse)
+            fMaxInUse = fInUse;
+
+        if (fMemoryStock.empty())
+        {
+            // No free slot available, allocate a new one
+            fAllocated += fChunkSize;
+            return std::shared_ptr<char>(new char[fChunkSize]);
+        }
+
+        // Get the next free slot from the stack and return it
+        const std::lock_guard<std::mutex> lock(fMutexMem);
+
+        const auto mem = fMemoryStock.front();
+        fMemoryStock.pop_front();
+        return mem;
+    };
+
+    void push(const std::shared_ptr<char> &mem)
+    {
+        if (!mem)
+            return;
+
+        // Decrease the amont of memory in use accordingly
+        fInUse -= fChunkSize;
+
+        // If the maximum memory has changed, we might be over the limit.
+        // In this case: free a slot
+        if (fAllocated>fMaxMemory)
+        {
+            fAllocated -= fChunkSize;
+            return;
+        }
+
+        {
+            const std::lock_guard<std::mutex> lock(fMutexMem);
+            fMemoryStock.emplace_front(mem);
+        }
+
+        {
+            const std::lock_guard<std::mutex> lock(fMutexCond);
+            fCond.notify_one();
+        }
+    }
+};
+
+class MemoryChunk
+{
+    friend class MemoryManager;
+
+    std::shared_ptr<MemoryStock> fMemoryStock;
+    std::shared_ptr<char>        fPointer;
+
+    MemoryChunk(const std::shared_ptr<MemoryStock> &mem, bool block)
+        : fMemoryStock(mem)
+    {
+        fPointer = fMemoryStock->pop(block);
+    }
+
+public:
+    ~MemoryChunk()
+    {
+        fMemoryStock->push(fPointer);
+    }
+};
+
+class MemoryManager
+{
+    std::shared_ptr<MemoryStock> fMemoryStock;
+
+public:
+    MemoryManager(size_t chunk, size_t max) : fMemoryStock(std::make_shared<MemoryStock>(chunk, max))
+    {
+    }
+
+    std::shared_ptr<char> malloc(bool block=true)
+    {
+        const std::shared_ptr<MemoryChunk> chunk(new MemoryChunk(fMemoryStock, block));
+        return std::shared_ptr<char>(chunk, chunk->fPointer.get());
+    }
+
+    size_t getChunkSize() const { return fMemoryStock->fChunkSize; }
+    bool   setChunkSize(const size_t size)
+    {
+#ifdef __EXCEPTIONS
+        if (getInUse())
+            throw std::runtime_error("Cannot change the chunk size while there is memory in use");
+        if (getMaxMemory()<size)
+            throw std::runtime_error("Chunk size ("+std::to_string((long long int)size)+") larger than allowed memory ("+std::to_string((long long int)getMaxMemory())+")");
+#else
+        if (getInUse() || getMaxMemory()<size)
+            return false;
+#endif
+
+        fMemoryStock->fChunkSize = size;
+        return true;
+    }
+
+    size_t getMaxMemory() const { return fMemoryStock->fMaxMemory; }
+    size_t getInUse() const { return fMemoryStock->fInUse; }
+    size_t getAllocated() const { return fMemoryStock->fAllocated; }
+    size_t getMaxInUse() const { return fMemoryStock->fMaxInUse; }
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/PixelMap.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/PixelMap.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/PixelMap.h	(revision 17960)
@@ -0,0 +1,368 @@
+#ifndef FACT_PixelMap
+#define FACT_PixelMap
+
+#include <vector>
+#include <string>
+#include <fstream>
+#include <sstream>
+
+#ifdef DEBUG
+#include <iostream>  // cerr -- to be removed?
+#endif
+
+#ifdef __EXCEPTIONS
+#include <stdexcept>
+#endif
+
+#ifdef __MARS__
+#include "MLog.h"
+#include "MLogManip.h"
+#endif
+
+// FIXME: Replace 416 by BIAS::kNumChannels
+
+struct PixelMapEntry
+{
+    int   index;               /// Software index
+    int   cbpx;                /// Hardware index as CBPX
+    int   gapd;                /// gAPD index
+//    float Vgapd;               /// gAPD Bias voltage
+    int   hv_board;            /// Bias suppply board
+    int   hv_channel;
+
+    PixelMapEntry() : index(-1) { } /// Bias supply channel
+
+    int crate() const { return cbpx/1000; }
+    int board() const { return (cbpx/100)%10; }
+    int patch() const { return (cbpx/10)%10; }
+    int pixel() const { return cbpx%10; }
+    int hw() const    { return pixel()+patch()*9+board()*36+crate()*360; }
+    int group() const { return pixel()>3; }
+    int count() const { return pixel()>3 ? 5 : 4; }
+    int hv() const    { return hv_channel+hv_board*32; }
+
+    operator bool() const { return index>=0; }
+
+    static const PixelMapEntry &empty() { const static PixelMapEntry e; return e; }
+};
+
+class PixelMap : public std::vector<PixelMapEntry>
+{
+public:
+    PixelMap() : std::vector<PixelMapEntry>(1440)
+    {
+    }
+
+    bool Read(const std::string &fname)
+    {
+        std::ifstream fin(fname);
+
+        int l = 0;
+
+        std::string buf;
+        while (getline(fin, buf, '\n'))
+        {
+            if (l>1439)
+                break;
+
+            buf.erase(buf.find_last_not_of(' ')+1);         //surfixing spaces
+            buf.erase(0, buf.find_first_not_of(' '));       //prefixing spaces
+ 
+            if (buf.empty() || buf[0]=='#')
+                continue;
+
+            std::stringstream str(buf);
+
+            int     idummy;
+            float   fdummy;
+
+            PixelMapEntry entry;
+
+            str >> entry.index;
+            str >> entry.cbpx;
+            str >> idummy;
+            str >> idummy;
+            str >> entry.gapd;
+            str >> fdummy; //entry.Vgapd;
+            str >> entry.hv_board;
+            str >> entry.hv_channel;
+            //str >> fdummy;
+            //str >> fdummy;
+            //str >> fdummy;
+
+            if (entry.hv_channel+32*entry.hv_board>=416/*BIAS::kNumChannels*/)
+            {
+#ifdef DEBUG
+                cerr << "Invalid board/channel read from FACTmapV5.txt." << endl;
+#endif
+                return false;
+            }
+
+            (*this)[l++] = entry;
+        }
+
+        return l==1440;
+    }
+
+    const PixelMapEntry &index(int idx) const
+    {
+        for (std::vector<PixelMapEntry>::const_iterator it=begin(); it!=end(); it++)
+            if (it->index==idx)
+                return *it;
+#ifdef DEBUG
+        std::cerr << "PixelMap: index " << idx << " not found" << std::endl;
+#endif
+        return PixelMapEntry::empty();
+    }
+
+    const PixelMapEntry &cbpx(int c) const
+    {
+        for (std::vector<PixelMapEntry>::const_iterator it=begin(); it!=end(); it++)
+            if (it->cbpx==c)
+                return *it;
+#ifdef DEBUG
+        std::cerr << "PixelMap: cbpx " << c << " not found" << std::endl;
+#endif
+        return PixelMapEntry::empty();
+    }
+
+    const PixelMapEntry &cbpx(int c, int b, int p, int px) const
+    {
+        return cbpx(px + p*10 + b*100 + c*1000);
+    }
+
+    const PixelMapEntry &hw(int idx) const
+    {
+        return cbpx(idx/360, (idx/36)%10, (idx/9)%4, idx%9);
+    }
+
+    const PixelMapEntry &hv(int board, int channel) const
+    {
+        for (std::vector<PixelMapEntry>::const_iterator it=begin(); it!=end(); it++)
+            if (it->hv_board==board && it->hv_channel==channel)
+                return *it;
+#ifdef DEBUG
+        std::cerr << "PixelMap: hv " << board << "/" << channel << " not found" << std::endl;
+#endif
+        return PixelMapEntry::empty();
+    }
+
+    const PixelMapEntry &hv(int idx) const
+    {
+        return hv(idx/32, idx%32);
+    }
+
+    /*
+    float Vgapd(int board, int channel) const
+    {
+        float avg = 0;
+        int   num = 0;
+
+        for (std::vector<PixelMapEntry>::const_iterator it=begin(); it!=end(); it++)
+            if (it->hv_board==board && it->hv_channel==channel)
+            {
+                avg += it->Vgapd;
+                num ++;
+            }
+
+        return num==0 ? 0 : avg/num;
+    }
+
+    float Vgapd(int idx) const
+    {
+        return Vgapd(idx/32, idx%32);
+    }
+
+    std::vector<float> Vgapd() const
+    {
+        std::vector<float> avg(416);
+        std::vector<int>   num(416);
+
+        for (std::vector<PixelMapEntry>::const_iterator it=begin(); it!=end(); it++)
+        {
+            const int ch = it->hv_board*32 + it->hv_channel;
+
+            avg[ch] += it->Vgapd;
+            num[ch] ++;
+        }
+
+        for (int ch=0; ch<416; ch++)
+        {
+            if (num[ch])
+                avg[ch] /= num[ch];
+        }
+
+        return avg;
+    }*/
+};
+
+struct BiasMapEntry
+{
+    int   hv_board;            /// Bias suppply board
+    int   hv_channel;          /// Bias supply channel
+    float Vnom;                /// Channel bias voltage nominal
+    float Voff;                /// Channel bias voltage offset [V]
+    float Vslope;              /// Channel bias voltage slope  [Ohm]
+
+    BiasMapEntry() : hv_board(-1), Voff(0), Vslope(90000) { }
+
+    int hv() const { return hv_channel+hv_board*32; }
+
+    operator bool() const { return hv_board>=0; }
+
+    static const BiasMapEntry &empty() { const static BiasMapEntry e; return e; }
+};
+
+class BiasMap : public std::vector<BiasMapEntry>
+{
+public:
+    BiasMap() : std::vector<BiasMapEntry>(416)
+    {
+    }
+
+#ifndef __MARS__
+    void Retrieve(const std::string &database);
+#endif
+    bool Read(const std::string &fname)
+    {
+        std::ifstream fin(fname);
+
+        int l = 0;
+
+        std::string buf;
+        while (getline(fin, buf, '\n'))
+        {
+            if (l>416)
+                break;
+
+            buf.erase(buf.find_last_not_of(' ')+1);         //surfixing spaces
+            buf.erase(0, buf.find_first_not_of(' '));       //prefixing spaces
+
+            if (buf.empty() || buf[0]=='#')
+                continue;
+
+            std::stringstream str(buf);
+
+            BiasMapEntry entry;
+
+            str >> entry.hv_board;
+            str >> entry.hv_channel;
+            str >> entry.Vnom;
+            str >> entry.Voff;
+            str >> entry.Vslope;
+
+#ifdef __EXCEPTIONS
+            if (entry.hv_channel+32*entry.hv_board>=416)
+                throw std::runtime_error("Invalid board/channel read from "+fname+".");
+#endif
+#ifdef __MARS__
+            if (entry.hv_channel+32*entry.hv_board>=416)
+            {
+                gLog << err << "Invalid board/channel read from " << fname << "." << std::endl;
+                return false;
+            }
+#endif
+
+            (*this)[entry.hv()] = entry;
+
+            l++;
+        }
+
+#ifdef __EXCEPTIONS
+        if (l!=416)
+            throw std::runtime_error("Number of lines ("+std::to_string(l)+") read from "+fname+" does not match 416.");
+
+        if (size()!=416)
+            throw std::runtime_error("Number of entries read from "+fname+" does not match 416.");
+#endif
+
+#ifdef __MARS__
+        if (l!=416)
+        {
+            gLog << err  << "Number of lines read from " << fname << " does not match 416." << std::endl;
+            return false;
+        }
+
+        if (size()!=416)
+        {
+            gLog << "Number of entries read from " << fname << " does not match 416." << std::endl;
+            return false;
+        }
+#endif
+
+        return true;
+    }
+
+    const BiasMapEntry &hv(int board, int channel) const
+    {
+        for (std::vector<BiasMapEntry>::const_iterator it=begin(); it!=end(); it++)
+            if (it->hv_board==board && it->hv_channel==channel)
+                return *it;
+#ifdef DEBUG
+        std::cerr << "PixelMap: hv " << board << "/" << channel << " not found" << std::endl;
+#endif
+        return BiasMapEntry::empty();
+    }
+
+    const BiasMapEntry &hv(int idx) const
+    {
+        return hv(idx/32, idx%32);
+    }
+
+    const BiasMapEntry &hv(const PixelMapEntry &p) const
+    {
+        return hv(p.hv_board, p.hv_channel);
+    }
+
+    /*
+    float Vgapd(int board, int channel) const
+    {
+        const BiasMapEntry &entry = hv(board, channel);
+        return entry.Vnom - entry.Voff; // use this with GAPDmap_20111126.txt
+    }
+
+    float Vgapd(int idx) const
+    {
+        return Vgapd(idx/32, idx%32);
+    }*/
+
+    std::vector<float> Vgapd() const
+    {
+        std::vector<float> volt(416);
+
+        for (std::vector<BiasMapEntry>::const_iterator it=begin(); it!=end(); it++)
+        {
+            const int ch = it->hv_board*32 + it->hv_channel;
+	    volt[ch] = it->Vnom;
+        }
+
+        return volt;
+    }
+    std::vector<float> Voffset() const
+    {
+        std::vector<float> volt(416);
+
+        for (std::vector<BiasMapEntry>::const_iterator it=begin(); it!=end(); it++)
+        {
+            const int ch = it->hv_board*32 + it->hv_channel;
+	    volt[ch] = it->Voff;
+        }
+
+        return volt;
+    }
+
+    std::vector<float> Vslope() const
+    {
+        std::vector<float> slope(416);
+
+        for (std::vector<BiasMapEntry>::const_iterator it=begin(); it!=end(); it++)
+        {
+            const int ch = it->hv_board*32 + it->hv_channel;
+            slope[ch] = it->Vslope;
+        }
+
+        return slope;
+    }
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/Queue.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/Queue.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/Queue.h	(revision 17960)
@@ -0,0 +1,320 @@
+#ifndef FACT_Queue
+#define FACT_Queue
+
+#include <list>
+
+#ifndef __CINT__
+#include <thread>
+#include <condition_variable>
+#else
+namespace std
+{
+    class mutex;
+    class thread;
+    class condition_variable;
+    template<class T> class function<T>;
+}
+#endif
+
+
+// The second template argument must support:
+//    iterator it = begin();   // get the next element to be processed
+//    erase(it);               // erase the processed element from the queue
+//    push_back();             // add a new element to the queue
+//    emplace_back();          // emplace a new element to the queue
+//    splice();                // used to efficiently implement post with mutex
+
+template<class T, class List=std::list<T>>
+class Queue
+{
+    size_t fSize;                 // Only necessary for before C++11
+
+    List fList;
+
+    std::mutex fMutex;             // Mutex needed for the conditional
+    std::condition_variable fCond; // Conditional
+
+    enum state_t
+    {
+        kIdle,
+        kRun,
+        kStop,
+        kAbort,
+        kTrigger,
+        kPrompt
+
+    };
+
+    state_t fState;               // Stop signal for the thread
+
+    typedef std::function<bool(const T &)> callback;
+    callback fCallback;       // Callback function called by the thread
+
+    std::thread fThread;      // Handle to the thread
+
+    void Thread()
+    {
+        std::unique_lock<std::mutex> lock(fMutex);
+
+        // No filling allowed by default (the queue is
+        // always processed until it is empty)
+        size_t allowed = 0;
+
+        while (1)
+        {
+            while (fSize==allowed && fState==kRun)
+                fCond.wait(lock);
+
+            // Check if the State flag has been changed
+            if (fState==kAbort)
+                break;
+
+            if (fState==kStop && fList.empty())
+                break;
+
+            // If thread got just woken up, move back the state to kRun
+            if (fState==kTrigger)
+                fState = kRun;
+
+            // Could have been a fState==kTrigger case
+            if (fList.empty())
+                continue;
+
+            // During the unlocked state, fSize might change.
+            // The current size of the queue needs to be saved.
+            allowed = fSize;
+
+            // get the first entry from the (sorted) list
+            const auto it = fList.begin();
+
+            // Theoretically, we can loose a signal here, but this is
+            // not a problem, because then we detect a non-empty queue
+            lock.unlock();
+
+            // If the first event in the queue could not be processed,
+            // no further processing makes sense until a new event has
+            // been posted (or the number of events in the queue has
+            // changed)  [allowed>0], in the case processing was
+            // successfull [allowed==0], the next event will be processed
+            // immediately.
+
+            if (fCallback && fCallback(*it))
+                allowed = 0;
+
+            lock.lock();
+
+            // Whenever an event was successfully processed, allowed
+            // is equal to zero and thus the event will be popped
+            if (allowed>0)
+                continue;
+
+            fList.erase(it);
+            fSize--;
+        }
+
+        fList.clear();
+        fSize = 0;
+
+        fState = kIdle;
+    }
+
+public:
+    Queue(const callback &f, bool startup=true) : fSize(0), fState(kIdle), fCallback(f)
+    {
+        if (startup)
+            start();
+    }
+
+    Queue(const Queue<T,List>& q) : fSize(0), fState(kIdle), fCallback(q.fCallback)
+    {
+    }
+
+    Queue<T,List>& operator = (const Queue<T,List>& q)
+    {
+        fSize     = 0;
+        fState    = kIdle;
+        fCallback = q.fCallback;
+        return *this;
+    }
+
+#ifdef __MARS__ // Needed for the compilatio of the dictionary
+    Queue() : fSize(0), fState(kIdle)
+    {
+    }
+#endif
+
+    ~Queue()
+    {
+        wait(true);
+    }
+
+    bool start()
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState!=kIdle)
+            return false;
+
+        fState = kRun;
+        fThread = std::thread(std::bind(&Queue::Thread, this));
+        return true;
+    }
+
+    bool stop()
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState==kIdle)
+            return false;
+
+        fState = kStop;
+        fCond.notify_one();
+
+        return true;
+    }
+
+    bool abort()
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState==kIdle)
+            return false;
+
+        fState = kAbort;
+        fCond.notify_one();
+
+        return true;
+    }
+
+    bool wait(bool abrt=false)
+    {
+        {
+            const std::lock_guard<std::mutex> lock(fMutex);
+            if (fState==kIdle || fState==kPrompt)
+                return false;
+
+            if (fState==kRun)
+            {
+                fState = abrt ? kAbort : kStop;
+                fCond.notify_one();
+            }
+        }
+
+        fThread.join();
+        return true;
+    }
+
+    bool enablePromptExecution()
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState!=kIdle || fSize>0)
+            return false;
+
+        fState = kPrompt;
+        return true;
+    }
+
+    bool disablePromptExecution()
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState!=kPrompt)
+            return false;
+
+        fState = kIdle;
+        return true;
+    }
+
+    bool setPromptExecution(bool state)
+    {
+        return state ? enablePromptExecution() : disablePromptExecution();
+    }
+
+
+    bool post(const T &val)
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState==kPrompt)
+            return fCallback(val);
+
+        if (fState==kIdle)
+            return false;
+
+        fList.push_back(val);
+        fSize++;
+
+        fCond.notify_one();
+
+        return true;
+    }
+
+    bool notify()
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState!=kRun)
+            return false;
+
+        fState = kTrigger;
+        fCond.notify_one();
+
+        return true;
+    }
+
+#ifdef __GXX_EXPERIMENTAL_CXX0X__
+    template<typename... _Args>
+        bool emplace(_Args&&... __args)
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState==kPrompt)
+            return fCallback(T(__args...));
+
+        if (fState==kIdle)
+            return false;
+
+        fList.emplace_back(__args...);
+        fSize++;
+
+        fCond.notify_one();
+
+        return true;
+    }
+
+    bool post(T &&val) { return emplace(std::move(val)); }
+#endif
+
+#ifdef __GXX_EXPERIMENTAL_CXX0X__
+    bool move(List&& x, typename List::iterator i)
+#else
+    bool move(List& x, typename List::iterator i)
+#endif
+    {
+        const std::lock_guard<std::mutex> lock(fMutex);
+        if (fState==kIdle)
+            return false;
+
+        fList.splice(fList.end(), x, i);
+        fSize++;
+
+        fCond.notify_one();
+
+        return true;
+    }
+
+#ifdef __GXX_EXPERIMENTAL_CXX0X__
+    bool move(List& x, typename List::iterator i) { return move(std::move(x), i); }
+#endif
+
+    size_t size() const
+    {
+        return fSize;
+    }
+
+    bool empty() const
+    {
+        return fSize==0;
+    }
+
+    bool operator<(const Queue& other) const
+    {
+        return fSize < other.fSize;
+    }
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/checksum.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/checksum.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/checksum.h	(revision 17960)
@@ -0,0 +1,242 @@
+#ifndef MARS_checksum
+#define MARS_checksum
+
+#ifndef __CINT__
+#include <arpa/inet.h>
+#endif
+
+#include <stdint.h>
+
+class Checksum
+{
+public:
+    uint64_t buffer;
+
+    void reset() { buffer = 0; }
+    Checksum() : buffer(0) { }
+    Checksum(const Checksum &sum) : buffer(sum.buffer) { }
+    Checksum(uint64_t v) : buffer(((v>>16)&0xffff) | ((v&0xffff)<<32)) { }
+
+    uint32_t val() const { return (((buffer&0xffff)<<16) | ((buffer>>32)&0xffff)); }
+
+    bool valid() const { return buffer==0xffff0000ffff; }
+
+    void HandleCarryBits()
+    {
+        while (1)
+        {
+            const uint64_t carry = ((buffer>>48)&0xffff) | ((buffer&0xffff0000)<<16);
+            if (!carry)
+                break;
+
+            buffer = (buffer&0xffff0000ffff) + carry;
+        }
+    }
+
+    Checksum &operator+=(const Checksum &sum)
+    {
+        buffer += sum.buffer;
+        HandleCarryBits();
+        return *this;
+    }
+
+    Checksum operator+(Checksum sum) const
+    {
+        return (sum += *this);
+    }
+
+
+    bool add(const char *buf, size_t len, bool big_endian = true)
+    {
+        // Avoid overflows in carry bits
+        if (len>262140) // 2^18-4
+        {
+            add(buf, 262140);
+            return add(buf+262140, len-262140);
+        }
+
+        if (len%4>0)
+        {
+            std::ostringstream sout;
+            sout << "Length " << len << " not dividable by 4";
+
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        const uint16_t *sbuf = reinterpret_cast<const uint16_t *>(buf);
+
+        uint32_t *hilo  = reinterpret_cast<uint32_t*>(&buffer);
+
+
+        const uint16_t *end = sbuf + len/2;
+
+        if (big_endian)
+            addLoopSwapping(sbuf, end, hilo);
+        else
+            addLoop(sbuf, end, hilo);
+        /*const uint16_t *end = sbuf + len/2;
+        while (1)
+        {
+            if (sbuf==end)
+                break;
+
+            hilo[0] += ntohs(*sbuf++);
+
+            if (sbuf==end)
+                break;
+
+            hilo[1] += ntohs(*sbuf++);
+        }*/
+
+        HandleCarryBits();
+
+        return true;
+    }
+
+    void addLoopSwapping(const uint16_t *sbuf, const uint16_t *end, uint32_t* hilo)
+    {
+        /*
+        for (size_t i = 0; i < len/2; i++)
+        {
+            //swap the bytes of the 32 bits value. but...
+            //the hi and lo values are stored in fits-like order. do not swap them
+            hilo[i%2] += ntohs(sbuf[i]); //(sbuf[i]&0xff00)>>8 | (sbuf[i]&0x00ff)<<8;
+        }*/
+
+        // This is about as twice as fast as the loop above
+        // ntohs is CPU optimized, i%2 doesn't need to be computed
+        while (1)
+        {
+            if (sbuf==end)
+                break;
+
+            hilo[0] += ntohs(*sbuf++);
+
+            if (sbuf==end)
+                break;
+
+            hilo[1] += ntohs(*sbuf++);
+        }
+    }
+
+    void addLoop(const uint16_t *sbuf, const uint16_t *end, uint32_t* hilo)
+    {
+        while (1)
+        {
+            if (sbuf==end)
+                break;
+
+            hilo[0] += ntohs(*sbuf++);
+
+            if (sbuf==end)
+                break;
+
+            hilo[1] += ntohs(*sbuf++);
+        }
+    }
+
+    bool add(const std::vector<char> &v, bool big_endian = true)
+    {
+        return add(v.data(), v.size(), big_endian);
+    }
+
+    std::string str(bool complm=true) const
+    {
+        std::string rc(16,0);
+
+        const uint8_t exclude[13] =
+        {
+            0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
+            0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60
+        };
+
+        const uint32_t value = complm ? ~val() : val();   // complement each bit of the value
+
+        for (int ii = 0; ii < 4; ii++)
+        {
+            uint8_t byte = (value >> (24 - (8 * ii)));
+
+            const uint8_t quotient  = byte / 4 + '0';
+            const uint8_t remainder = byte % 4;
+
+            uint32_t ch[4] = { quotient+remainder, quotient, quotient, quotient };
+
+            // avoid ASCII  punctuation
+            while (1)
+            {
+                bool check = false;
+                for (int kk = 0; kk < 13; kk++)
+                {
+                    for (int jj = 0; jj < 4; jj += 2)
+                    {
+                        if (ch[jj] != exclude[kk] &&  ch[jj+1] != exclude[kk])
+                            continue;
+
+                        ch[jj]++;
+                        ch[jj+1]--;
+                        check++;
+                    }
+                }
+
+                if (!check)
+                    break;
+            }
+
+            for (int jj = 0; jj < 4; jj++)        // assign the bytes
+                rc[4*jj+ii] = ch[jj];
+        }
+
+        const char lastChar = rc[15];
+        for (int i=15;i>0;i--)
+            rc[i] = rc[i-1];
+        rc[0] = lastChar;
+        return rc;
+/*
+        uint8_t *p = reinterpret_cast<uint8_t*>(&value);
+        //swap the bytes of the value
+        uint8_t temp;
+        temp = p[0];
+        p[0] = p[3];
+        p[3] = temp;
+        temp = p[1];
+        p[1] = p[2];
+        p[2] = temp;
+
+        for (int i=0; i<4; i++)
+        {
+            rc[i+ 0] = '0' + p[i]/4 + p[i]%4;
+            rc[i+ 4] = '0' + p[i]/4;
+            rc[i+ 8] = '0' + p[i]/4;
+            rc[i+12] = '0' + p[i]/4;
+        }
+
+        while(1)
+        {
+            bool ok  = true;
+            for (int i=0; i<16-4; i++)
+            {
+                for (int j=0; j<13; j++)
+                    if (rc[i]==exclude[j] || rc[(i+4)%16]==exclude[j])
+                    {
+                        rc[i]++;
+                        rc[(i+4)%16]--;
+                        ok = false;
+                    }
+            }
+
+            if (ok)
+                break;
+        }
+
+
+        return rc;
+ */
+   }
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/factfits.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/factfits.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/factfits.h	(revision 17960)
@@ -0,0 +1,206 @@
+/*
+ * factfits.h
+ *
+ *  Created on: May 26, 2013
+ *      Author: lyard
+ */
+
+#ifndef MARS_FACTFITS
+#define MARS_FACTFITS
+
+#include "zfits.h"
+
+class factfits : public zfits
+{
+public:
+    // Default constructor
+    factfits(const std::string& fname, const std::string& tableName="", bool force=false) :
+        zfits(fname, tableName, force),
+        fOffsetCalibration(0),
+        fOffsetStartCellData(0),
+        fOffsetData(0),
+        fNumRoi(0)
+    {
+        if (init())
+            readDrsCalib(fname);
+    }
+
+    // Alternative constructor
+    factfits(const std::string& fname, const std::string& fout, const std::string& tableName, bool force=false) :
+        zfits(fname, fout, tableName, force),
+        fOffsetCalibration(0),
+        fOffsetStartCellData(0),
+        fOffsetData(0),
+        fNumRoi(0)
+    {
+        if (init())
+            readDrsCalib(fname);
+    }
+
+private:
+
+    void StageRow(size_t row, char* dest)
+    {
+        zfits::StageRow(row, dest);
+
+        // This file does not contain fact data or no calibration to be applied
+        if (fOffsetCalibration.empty())
+            return;
+
+        //re-get the pointer to the data to access the offsets
+        const uint8_t offset = (row*fTable.bytes_per_row)%4;
+
+        int16_t *startCell = reinterpret_cast<int16_t*>(fBufferRow.data() + offset + fOffsetStartCellData);
+        int16_t *data      = reinterpret_cast<int16_t*>(fBufferRow.data() + offset + fOffsetData);
+
+         /*
+         for (uint32_t i=0; i<1440*1024; i+=1024, startCell++)
+         {
+             if (*startCell < 0)
+             {
+                 data += fNumRoi;
+                 continue;
+             }
+             for (uint32_t j=0; j<fNumRoi; j++, data++)
+                 *data += fOffsetCalibration[i + (*startCell+j)%1024];
+         }
+         */
+
+        // This version is faster because the compilers optimization
+        // is not biased by the evaluation of %1024
+        for (int ch=0; ch<1440; ch++)
+        {
+            if (startCell[ch]<0)
+            {
+                data += fNumRoi;
+                continue;
+            }
+
+            const int16_t modStart = startCell[ch] % 1024;
+            const int16_t *off = fOffsetCalibration.data() + ch*1024;
+
+            const int16_t *cal = off+modStart;
+            const int16_t *end_stride = data+fNumRoi;
+
+            if (modStart+fNumRoi>1024)
+            {
+                while (cal<off+1024)
+                    *data++ += *cal++;
+
+                cal = off;
+            }
+            while (data<end_stride)
+                *data++ += *cal++;
+        }
+
+    }
+
+    bool init()
+    {
+        if (!HasKey("NPIX") || !HasKey("NROI"))
+            return false;
+
+        if (Get<uint16_t>("NPIX")!=1440)
+            return false;
+
+        fNumRoi = Get<uint16_t>("NROI");
+        if (fNumRoi>1024)
+            return false;
+
+        // check column details for Data
+        const Table::Columns::const_iterator it = fTable.cols.find("Data");
+        if (it==fTable.cols.end() || it->second.num!=1440*fNumRoi || it->second.type!='I')
+            return false;
+
+        // check column details for StartCellData
+        const Table::Columns::const_iterator is = fTable.cols.find("StartCellData");
+        if (is==fTable.cols.end() || is->second.num!=1440 || is->second.type!='I')
+            return false;
+
+        fOffsetStartCellData = is->second.offset;
+        fOffsetData          = it->second.offset;
+
+        return true;
+    }
+
+    //  Read the Drs calibration data
+    void readDrsCalib(const std::string& fileName)
+    {
+        //should not be mandatory, but improves the perfs a lot when reading not compressed, gzipped files
+        if (!IsCompressedFITS())
+            return;
+
+        zfits calib(fileName, "ZDrsCellOffsets");
+
+        if (calib.bad())
+        {
+            clear(rdstate()|std::ios::badbit);
+            return;
+        }
+
+        if (calib.eof())
+            return;
+
+        // Check correct size and format of table
+        if (calib.GetNumRows() != 1)
+        {
+            clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("Table 'ZDrsCellOffsets' found, but not with one row as expected");
+#else
+            gLog << ___err___ << "ERROR - Table 'ZDrsCellOffsets' found, but not with one row as expected" << std::endl;
+            return;
+#endif
+        }
+        if (calib.GetStr("TTYPE1") != "OffsetCalibration")
+        {
+            clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("Table 'ZDrsCellOffsets' found, but first column is not the one expected");
+#else
+            gLog << ___err___ << "ERROR - Table 'ZDrsCellOffsets' found, but first column is not the one expected" << std::endl;
+            return;
+#endif
+        }
+        bool isColumnPresent = false;
+        if (calib.HasKey("TFORM1") && calib.GetStr("TFORM1") == "1474560I") isColumnPresent = true;
+        if (calib.HasKey("ZFORM1") && calib.GetStr("ZFORM1") == "1474560I") isColumnPresent = true;
+        if (!isColumnPresent)  // 1024*1440
+        {
+            clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("Table 'ZDrsCellOffsets' has wrong column format (TFROM1)");
+#else
+            gLog << ___err___ << "ERROR - Table 'ZDrsCellOffsets' has wrong column format (TFORM1)" << std::endl;
+            return;
+#endif
+        }
+
+        fOffsetCalibration.resize(1024*1440);
+
+        calib.SetPtrAddress("OffsetCalibration", fOffsetCalibration.data());
+        if (calib.GetNextRow())
+            return;
+
+        clear(rdstate()|std::ios::badbit);
+
+#ifdef __EXCEPTIONS
+        throw std::runtime_error("Reading column 'OffsetCalibration' failed.");
+#else
+        gLog << ___err___ << "ERROR - Reading column 'OffsetCalibration' failed." << std::endl;
+#endif
+
+    }
+
+    std::vector<int16_t> fOffsetCalibration; ///< integer values of the drs calibration used for compression
+
+    size_t fOffsetStartCellData;
+    size_t fOffsetData;
+
+    uint16_t fNumRoi;
+
+#warning Time marker channels currently unhandled
+
+}; //class factfits
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/factofits.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/factofits.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/factofits.h	(revision 17960)
@@ -0,0 +1,364 @@
+/*
+ * factofits.h
+ *
+ *  Created on: Oct 16, 2013
+ *      Author: lyard
+ */
+
+#ifndef FACTOFITS_H_
+#define FACTOFITS_H_
+
+#define GCC_VERSION (__GNUC__ * 10000  + __GNUC_MINOR__ * 100  + __GNUC_PATCHLEVEL__)
+
+#include "zofits.h"
+#include "DrsCalib.h"
+
+class factofits : public zofits
+{
+    public:
+
+        /// constructors
+        factofits(uint32_t numTiles=DefaultMaxNumTiles(), uint32_t rowPerTile=DefaultNumRowsPerTile(),
+                  uint32_t maxMem=DefaultMaxMemory())
+            : zofits(numTiles, rowPerTile, maxMem)
+        {
+            fStartCellsOffset = -1;
+            fDataOffset       = -1;
+        }
+
+        factofits(const char *fname, uint32_t numTiles=DefaultMaxNumTiles(),
+                  uint32_t rowPerTile=DefaultNumRowsPerTile(), uint32_t maxMem=DefaultMaxMemory())
+            : zofits(fname, numTiles, rowPerTile, maxMem)
+        {
+            fStartCellsOffset = -1;
+            fDataOffset       = -1;
+        }
+
+        virtual ~factofits()
+        {
+        }
+
+        /// whether or not a calibration was given to the file writer
+        virtual bool IsOffsetCalibration()
+        {
+            return (fOffsetCalibration.size() != 0);
+        }
+
+        ///assign a given drs offset calibration
+        void SetDrsCalibration(const std::vector<float> &calib)
+        {
+            VerifyCalibrationSize(calib.size());
+
+            if (!IsOffsetCalibration())
+                fOffsetCalibration.resize(1440*1024);
+
+            for (uint32_t i=0; i<1440*1024; i++)
+                fOffsetCalibration[i] = (int16_t)(calib[i]*4096/2000);
+        }
+
+        ///assign a given drs offset calibration
+        void SetDrsCalibration(const std::vector<int16_t>& vec)
+        {
+            VerifyCalibrationSize(vec.size());
+
+            if (!IsOffsetCalibration())
+                fOffsetCalibration.resize(1440*1024);
+
+            for (uint32_t i=0; i<1440*1024; i++)
+                fOffsetCalibration[i] = vec[i];
+        }
+
+        ///assign a given drs offset calibration
+        void SetDrsCalibration(const DrsCalibration& drs)
+        {
+            if (drs.fNumOffset==0)
+                return;
+
+            VerifyCalibrationSize(drs.fOffset.size());
+
+            if (!IsOffsetCalibration())
+                fOffsetCalibration.resize(1440*1024);
+
+            for (uint32_t i=0; i<1024*1440; i++)
+                fOffsetCalibration[i] = drs.fOffset[i]/drs.fNumOffset;
+        }
+
+        ///Overload of the super function
+        bool WriteTableHeader(const char* name="DATA")
+        {
+            if (!zofits::WriteTableHeader(name))
+                return false;
+
+            if (!IsOffsetCalibration())
+                return true;
+
+            //retrieve the column storing the start cell offsets, if required.
+            for (auto it=fRealColumns.cbegin(); it!=fRealColumns.cend(); it++)
+            {
+                if (it->col.name == "StartCellData")
+                    fStartCellsOffset = it->col.offset;
+
+                if (it->col.name == "Data")
+                {
+                    fNumSlices  = it->col.num;
+                    fDataOffset = it->col.offset;
+                    if (fNumSlices % 1440 != 0)
+                    {
+#ifdef __EXCEPTIONS
+                        throw std::runtime_error("Number of data samples not a multiple of 1440.");
+#else
+                        gLog << ___warn___ << "WARNING - Number of data samples not a multiple of 1440. Doing it uncalibrated." << std::endl;
+#endif
+                        fOffsetCalibration.resize(0);
+                    }
+                    fNumSlices /= 1440;
+                }
+            }
+
+            if (fStartCellsOffset < 0)
+            {
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("FACT Calibration requested, but \"StartCellData\" column not found.");
+#else
+                gLog << ___warn___ << "WARNING - FACT Calibration requested, but \"StartCellData\" column not found. Doing it uncalibrated." << std::endl;
+#endif
+                //throw away the calibration data
+                fOffsetCalibration.resize(0);
+            }
+
+            if (fDataOffset < 0)
+            {
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("FACT Calibration requested, but \"Data\" column not found.");
+#else
+                gLog << ___warn___ << "WARNING - FACT Calibration requested, but \"Data\" column not found. Doing it uncalibrated." << std::endl;
+#endif
+                    //throw away the calibration data
+                fOffsetCalibration.resize(0);
+            }
+
+            return true;
+        }
+
+        ///Uncompressed version of the DrsCalibration table
+ /*       virtual bool WriteDrsOffsetsTable()
+        {
+            if (!IsOffsetCalibration())
+                return false;
+
+            ofits c;
+            c.SetStr("XTENSION", "BINTABLE"            , "binary table extension");
+            c.SetInt("BITPIX"  , 8                     , "8-bit bytes");
+            c.SetInt("NAXIS"   , 2                     , "2-dimensional binary table");
+            c.SetInt("NAXIS1"  , 1024*1440*2           , "width of table in bytes");
+            c.SetInt("NAXIS2"  , 1                     , "number of rows in table");
+            c.SetInt("PCOUNT"  , 0                     , "size of special data area");
+            c.SetInt("GCOUNT"  , 1                     , "one data group (required keyword)");
+            c.SetInt("TFIELDS" , 1                     , "number of fields in each row");
+            c.SetStr("CHECKSUM", "0000000000000000"    , "Checksum for the whole HDU");
+            c.SetStr("DATASUM" ,  "         0"         , "Checksum for the data block");
+            c.SetStr("EXTNAME" , "ZDrsCellOffsets"     , "name of this binary table extension");
+            c.SetStr("TTYPE1"  , "OffsetCalibration"   , "label for field   1");
+            c.SetStr("TFORM1"  , "1474560I"            , "data format of field: 2-byte INTEGER");
+            c.End();
+
+            vector<char> swappedOffsets;
+            swappedOffsets.resize(1024*1440*sizeof(int16_t));
+            revcpy<sizeof(int16_t)>(swappedOffsets.data(), (char*)(fOffsetCalibration.data()), 1024*1440);
+
+            Checksum datasum;
+            datasum.add(swappedOffsets.data(), sizeof(int16_t)*1024*1440);
+
+            std::ostringstream dataSumStr;
+            dataSumStr << datasum.val();
+            c.SetStr("DATASUM", dataSumStr.str());
+
+            datasum += c.WriteHeader(*this);
+
+            const off_t here_I_am = tellp();
+
+            c.SetStr("CHECKSUM", datasum.str());
+            c.WriteHeader(*this);
+
+            seekp(here_I_am);
+
+            write(swappedOffsets.data(), swappedOffsets.size());
+
+            AlignTo2880Bytes();
+
+            return good();
+        }*/
+
+        ///Actually write the drs calibration table
+        virtual bool WriteDrsOffsetsTable()
+        {
+            if (!IsOffsetCalibration())
+                return false;
+
+            const uint32_t catalog_size = sizeof(int64_t)*2;
+
+            ofits c;
+            c.SetStr("XTENSION", "BINTABLE"            , "binary table extension");
+            c.SetInt("BITPIX"  , 8                     , "8-bit bytes");
+            c.SetInt("NAXIS"   , 2                     , "2-dimensional binary table");
+            c.SetInt("NAXIS1"  , catalog_size           , "width of table in bytes");
+            c.SetInt("NAXIS2"  , 1                     , "number of rows in table");
+            c.SetInt("PCOUNT"  , 0                     , "size of special data area");
+            c.SetInt("GCOUNT"  , 1                     , "one data group (required keyword)");
+            c.SetInt("TFIELDS" , 1                     , "number of fields in each row");
+            c.SetStr("CHECKSUM", "0000000000000000"    , "Checksum for the whole HDU");
+            c.SetStr("DATASUM" ,  "         0"         , "Checksum for the data block");
+            c.SetStr("EXTNAME" , "ZDrsCellOffsets"     , "name of this binary table extension");
+            c.SetStr("TTYPE1"  , "OffsetCalibration"   , "label for field   1");
+            c.SetStr("ZFORM1"  , "1474560I"            , "data format of field: 2-byte INTEGER");
+            c.SetStr("TFORM1"  , "1QB"                 , "data format of variable length bytes");
+            c.SetStr("ZCTYP1"  , "FACT"                , "Compression type FACT");
+
+            c.SetBool( "ZTABLE",   true,            "Table is compressed");
+            c.SetInt(  "ZNAXIS1",  1024*1440*2,    "Width of uncompressed rows");
+            c.SetInt(  "ZNAXIS2",  1,               "Number of uncompressed rows");
+            c.SetInt(  "ZPCOUNT",  0,               "");
+            c.SetInt(  "ZHEAPPTR", catalog_size,               "");
+            c.SetInt(  "ZTILELEN", 1, "Number of rows per tile");
+            c.SetInt(  "THEAP",    catalog_size,               "");
+            c.SetStr(  "RAWSUM",   "         0",    "Checksum of raw little endian data");
+            c.SetFloat("ZRATIO",   0,               "Compression ratio");
+            c.SetInt(  "ZSHRINK",  1,               "Catalog shrink factor");
+            c.End();
+
+            c.WriteHeader(*this);
+
+            const off_t here_I_am = tellp();
+
+            //go after the catalog to compress and write the table data
+            seekp(here_I_am + catalog_size);
+
+            //calculate RAWSUM
+            Checksum rawsum;
+            rawsum.add((char*)(fOffsetCalibration.data()), 1024*1440*sizeof(int16_t));
+#if GCC_VERSION < 40603
+            c.SetStr("RAWSUM", std::to_string((long long unsigned int)(rawsum.val())));
+#else
+            c.SetStr("RAWSUM", std::to_string(rawsum.val()));
+#endif
+
+            //compress data and calculate final, compressed size
+            const uint32_t compressed_header_size = sizeof(FITS::TileHeader) + sizeof(FITS::BlockHeader) + 1*sizeof(uint16_t);
+            std::vector<char> compressed_calib(1024*1440*2 + compressed_header_size + 8); //+8 for checksum;
+            char* data_start = compressed_calib.data() + compressed_header_size;
+            uint32_t compressed_size = compressHUFFMAN16(data_start, (char*)(fOffsetCalibration.data()), 1024*1440, 2, 1);;
+            compressed_size += compressed_header_size;
+
+            //Write tile header
+            FITS::TileHeader th(0, 0);
+            std::vector<uint16_t> seq(1, FITS::kFactHuffman16);
+            FITS::Compression bh(seq, FITS::kOrderByRow);
+            th.numRows = 1;
+            th.size = compressed_size;
+            bh.SetBlockSize(compressed_size-sizeof(FITS::TileHeader));
+            memcpy(compressed_calib.data(), &(th), sizeof(FITS::TileHeader));
+            bh.Memcpy(compressed_calib.data()+sizeof(FITS::TileHeader));
+
+            //calculate resulting compressed datasum
+            Checksum datasum;
+            memset(compressed_calib.data()+compressed_size, 0, 8-compressed_size%8);
+            datasum.add(compressed_calib.data(), compressed_size + 8-compressed_size%8);
+
+            //write the catalog !
+            seekp(here_I_am);
+
+            std::vector<uint64_t> catalog(2,0);
+            catalog[0] = compressed_size-sizeof(FITS::TileHeader);
+            catalog[1] = sizeof(FITS::TileHeader);
+
+            std::vector<char> swappedCatalog(catalog_size);
+            revcpy<sizeof(int64_t)>(swappedCatalog.data(), (char*)(catalog.data()), 2);//catalog_size);
+            datasum.add(swappedCatalog.data(), catalog_size);
+
+            write(swappedCatalog.data(), catalog_size);
+
+            //update relevant keywords
+            c.SetFloat("ZRATIO", (float)(1024*1440*2)/(float)(compressed_size));
+            c.SetInt("PCOUNT", compressed_size + catalog_size);
+
+#if GCC_VERSION < 40603
+            c.SetStr("DATASUM", std::to_string((long long unsigned int)(datasum.val())));
+#else
+            c.SetStr("DATASUM", std::to_string(datasum.val()));
+#endif
+
+            datasum += c.WriteHeader(*this);
+
+            c.SetStr("CHECKSUM", datasum.str());
+
+            c.WriteHeader(*this);
+
+            //write the compressed data
+            seekp(here_I_am + catalog_size);
+            write(compressed_calib.data(), compressed_size);
+
+            AlignTo2880Bytes();
+
+            return good();
+        }
+        ///Apply the drs offset calibration (overload of super-method)
+        virtual void DrsOffsetCalibrate(char* target_location)
+        {
+            if (!IsOffsetCalibration())
+                return;
+
+            const int16_t* startCell = reinterpret_cast<int16_t*>(target_location + fStartCellsOffset);
+            int16_t*       data      = reinterpret_cast<int16_t*>(target_location + fDataOffset);
+
+            for (uint32_t ch=0; ch<1440; ch++)
+            {
+                if (startCell[ch] < 0)
+                {
+                    data += fNumSlices;
+                    continue;
+                }
+
+                const int16_t modStart = startCell[ch]%1024;
+                const int16_t *off     = fOffsetCalibration.data() + ch*1024;
+
+                const int16_t* cal        = off+modStart;
+                const int16_t* end_stride = data+fNumSlices;
+
+                if (modStart+fNumSlices > 1024)
+                {
+                    while (cal < off+1024)
+                        *data++ -= *cal++;
+                    cal = off;
+                }
+
+                while (data<end_stride)
+                    *data++ -= *cal++;
+            }
+        }
+
+private:
+        /// Checks if the size of the input calibration is ok
+        bool VerifyCalibrationSize(uint32_t size)
+        {
+            if (size == 1440*1024)
+                return true;
+
+            std::ostringstream str;
+            str << "Cannot load calibration with anything else than 1440 pixels and 1024 samples per pixel. Got a total size of " << size;
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(str.str());
+#else
+            gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+            return false;
+#endif
+         }
+
+        //Offsets calibration stuff.
+        std::vector<int16_t> fOffsetCalibration;  ///< The calibration itself
+        int32_t         fStartCellsOffset;   ///< Offset in bytes for the startcell data
+        int32_t         fDataOffset;         ///< Offset in bytes for the data
+        int32_t         fNumSlices;          ///< Number of samples per pixel per event
+
+}; //class factofits
+
+#endif /* FACTOFITS_H_ */
Index: branches/Mars_McMismatchStudy/mcore/fits.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/fits.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/fits.h	(revision 17960)
@@ -0,0 +1,1040 @@
+#ifndef MARS_fits
+#define MARS_fits
+
+#include <stdint.h>
+
+#include <map>
+#include <string>
+#include <fstream>
+#include <sstream>
+#include <algorithm>
+#include <stdexcept>
+
+#define GCC_VERSION (__GNUC__ * 10000  + __GNUC_MINOR__ * 100  + __GNUC_PATCHLEVEL__)
+
+#ifndef __CINT__
+#include <unordered_map>
+#else
+#define off_t size_t
+namespace std
+{
+    template<class T, class S> class unordered_map<T, S>;
+}
+#endif
+
+#if defined(__MARS__) || defined(__CINT__)
+#include "MLog.h"
+#include "MLogManip.h"
+#define ___err___   err
+#define ___warn___  warn
+#define ___all___   all
+#else
+#include <vector>
+#include <iomanip>
+#include <iostream>
+#ifndef gLog
+#define gLog std::cerr
+#define ___err___   ""
+#define ___warn___  ""
+#define ___all___   ""
+#endif
+#endif
+
+#if defined(HAVE_ZLIB) || defined(__CINT__)
+#include "izstream.h"
+#else
+#include <fstream>
+#define izstream ifstream
+#warning Support for zipped FITS files disabled.
+#endif
+
+#include "FITS.h"
+#include "checksum.h"
+
+class fits : public izstream
+{
+public:
+    //I know I know, you're going to yiell that this does not belong here.
+    //It will belong in the global scope eventually, and it makes the coding of zfits much simpler this way.
+    enum Compression_t
+    {
+        kCompUnknown,
+        kCompFACT
+    };
+
+    struct Entry
+    {
+        char        type;
+        std::string value;
+        std::string comment;
+        std::string fitsString;
+
+        template<typename T>
+            T Get() const
+        {
+            T t;
+
+            std::istringstream str(value);
+            str >> t;
+
+            return t;
+        }
+    };
+
+    struct Table
+    {
+        off_t offset;
+
+        bool is_compressed;
+
+        std::string name;
+        size_t bytes_per_row;
+        size_t num_rows;
+        size_t num_cols;
+        size_t total_bytes; // NAXIS1*NAXIS2
+
+        struct Column
+        {
+            size_t offset;
+            size_t num;
+            size_t size;
+            size_t bytes;  // num*size
+            char   type;
+            std::string unit;
+            Compression_t comp;
+        };
+
+        typedef std::map<std::string, Entry>  Keys;
+        typedef std::map<std::string, Column> Columns;
+        typedef std::vector<Column> SortedColumns;
+
+        Columns cols;
+        SortedColumns sorted_cols;
+        Keys    keys;
+
+        int64_t datasum;
+
+        std::string Trim(const std::string &str, char c=' ') const
+        {
+            // Trim Both leading and trailing spaces
+            const size_t pstart = str.find_first_not_of(c); // Find the first character position after excluding leading blank spaces
+            const size_t pend   = str.find_last_not_of(c);  // Find the first character position from reverse af
+
+            // if all spaces or empty return an empty string
+            if (std::string::npos==pstart || std::string::npos==pend)
+                return std::string();
+
+            return str.substr(pstart, pend-pstart+1);
+        }
+
+        bool Check(const std::string &key, char type, const std::string &value="") const
+        {
+            const Keys::const_iterator it = keys.find(key);
+            if (it==keys.end())
+            {
+                std::ostringstream str;
+                str << "Key '" << key << "' not found.";
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(str.str());
+#else
+                gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                return false;
+#endif
+            }
+
+            if (it->second.type!=type)
+            {
+                std::ostringstream str;
+                str << "Wrong type for key '" << key << "': expected " << type << ", found " << it->second.type << ".";
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(str.str());
+#else
+                gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                return false;
+#endif
+            }
+
+            if (!value.empty() && it->second.value!=value)
+            {
+                std::ostringstream str;
+                str << "Wrong value for key '" << key << "': expected " << value << ", found " << it->second.value << ".";
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(str.str());
+#else
+                gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                return false;
+#endif
+            }
+
+            return true;
+        }
+
+        Keys ParseBlock(const std::vector<std::string> &vec) const
+        {
+            Keys rc;
+
+            for (unsigned int i=0; i<vec.size(); i++)
+            {
+                const std::string key = Trim(vec[i].substr(0,8));
+                // Keywords without a value, like COMMENT / HISTORY
+                if (vec[i].substr(8,2)!="= ")
+                    continue;
+
+                char type = 0;
+
+                std::string com;
+                std::string val = Trim(vec[i].substr(10));
+
+                if (val[0]=='\'')
+                {
+                    // First skip all '' in the string
+                    size_t p = 1;
+                    while (1)
+                    {
+                        const size_t pp = val.find_first_of('\'', p);
+                        if (pp==std::string::npos)
+                            break;
+
+                        p = val[pp+1]=='\'' ? pp+2 : pp+1;
+                    }
+
+                    // Now find the comment
+                    const size_t ppp = val.find_first_of('/', p);
+
+                    // Set value, comment and type
+                    // comments could be just spaces. take care of this.
+                    if (ppp!=std::string::npos && val.size()!=ppp+1)
+                        com = Trim(val.substr(ppp+1));
+
+                    val  = Trim(val.substr(1, p-2));
+                    type = 'T';
+                }
+                else
+                {
+                    const size_t p = val.find_first_of('/');
+
+                    if (p!=std::string::npos && val.size()!=p+1)
+                        com = Trim(val.substr(p+2));
+
+                    val = Trim(val.substr(0, p));
+
+                    if (val.empty() || val.find_first_of('T')!=std::string::npos || val.find_first_of('F')!=std::string::npos)
+                        type = 'B';
+                    else
+                        type = val.find_last_of('.')==std::string::npos ? 'I' : 'F';
+                }
+
+                const Entry e = { type, val, com, vec[i] };
+
+                rc[key] = e;
+            }
+
+            return rc;
+        }
+
+        Table() : offset(0), is_compressed(false) { }
+        Table(const std::vector<std::string> &vec, off_t off) : offset(off),
+            keys(ParseBlock(vec))
+        {
+            is_compressed = HasKey("ZTABLE") && Check("ZTABLE", 'B', "T");
+
+            if (!Check("XTENSION", 'T', "BINTABLE") ||
+                !Check("NAXIS",    'I', "2")        ||
+                !Check("BITPIX",   'I', "8")        ||
+                !Check("GCOUNT",   'I', "1")        ||
+                !Check("EXTNAME",  'T')             ||
+                !Check("NAXIS1",   'I')             ||
+                !Check("NAXIS2",   'I')             ||
+                !Check("TFIELDS",  'I'))
+                return;
+
+            if (is_compressed)
+            {
+                if (!Check("ZNAXIS1", 'I') ||
+                    !Check("ZNAXIS2", 'I') ||
+                    !Check("ZPCOUNT", 'I', "0"))
+                    return;
+            }
+            else
+            {
+                if (!Check("PCOUNT", 'I', "0"))
+                    return;
+            }
+
+            total_bytes   = Get<size_t>("NAXIS1")*Get<size_t>("NAXIS2");
+            bytes_per_row = is_compressed ? Get<size_t>("ZNAXIS1") : Get<size_t>("NAXIS1");
+            num_rows      = is_compressed ? Get<size_t>("ZNAXIS2") : Get<size_t>("NAXIS2");
+            num_cols      = Get<size_t>("TFIELDS");
+            datasum       = Get<int64_t>("DATASUM", -1);
+            size_t bytes = 0;
+
+            const std::string tFormName = is_compressed ? "ZFORM" : "TFORM";
+            for (long long unsigned int i=1; i<=num_cols; i++)
+            {
+                const std::string num(std::to_string(i));
+
+                if (!Check("TTYPE"+num, 'T') ||
+                    !Check(tFormName+num, 'T'))
+                    return;
+
+                const std::string id   = Get<std::string>("TTYPE"+num);
+                const std::string fmt  = Get<std::string>(tFormName+num);
+                const std::string unit = Get<std::string>("TUNIT"+num, "");
+                const std::string comp = Get<std::string>("ZCTYP"+num, "");
+
+                Compression_t compress = kCompUnknown;
+                if (comp == "FACT")
+                    compress = kCompFACT;
+
+                std::istringstream sin(fmt);
+                int n = 0;
+                sin >> n;
+                if (!sin)
+                    n = 1;
+
+                const char type = fmt[fmt.length()-1];
+
+                size_t size = 0;
+                switch (type)
+                {
+                    // We could use negative values to mark floats
+                    // otheriwse we could just cast them to int64_t?
+                case 'L':                  // logical
+                case 'A':                  // char
+                case 'B': size = 1; break; // byte
+                case 'I': size = 2; break; // short
+                case 'J': size = 4; break; // int
+                case 'K': size = 8; break; // long long
+                case 'E': size = 4; break; // float
+                case 'D': size = 8; break; // double
+                // case 'X': size =  n; break; // bits (n=number of bytes needed to contain all bits)
+                // case 'C': size =  8; break; // complex float
+                // case 'M': size = 16; break; // complex double
+                // case 'P': size =  8; break; // array descriptor (32bit)
+                // case 'Q': size = 16; break; // array descriptor (64bit)
+                default:
+                    {
+                        std::ostringstream str;
+                        str << "FITS format TFORM='" << fmt << "' not yet supported.";
+#ifdef __EXCEPTIONS
+                        throw std::runtime_error(str.str());
+#else
+                        gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                        return;
+#endif
+                    }
+                }
+
+                const Table::Column col = { bytes, n, size, n*size, type, unit, compress};
+
+                cols[id] = col;
+                sorted_cols.emplace_back(col);
+                bytes  += n*size;
+            }
+
+            if (bytes!=bytes_per_row)
+            {
+                std::ostringstream str;
+                str << "Sum of bytes in columns [" << bytes << "] does not match (Z)NAXIS2 [" << bytes_per_row << "].";
+
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(str.str());
+#else
+                gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                return;
+#endif
+            }
+
+            name = Get<std::string>("EXTNAME");
+        }
+
+        void PrintKeys(bool display_all=false) const
+        {
+            for (Keys::const_iterator it=keys.cbegin(); it!=keys.cend(); it++)
+            {
+                if (!display_all && FITS::IsReservedKeyWord(it->first))
+                    continue;
+
+                gLog << ___all___ << std::setw(2) << it->second.type << '|' << it->first << '=' << it->second.value << '/' << it->second.comment << '|' << std::endl;
+            }
+        }
+
+        void PrintColumns() const
+        {
+            typedef std::map<std::pair<size_t, std::string>, Column> Sorted;
+
+            Sorted sorted;
+
+            for (Columns::const_iterator it=cols.cbegin(); it!=cols.cend(); it++)
+                sorted[std::make_pair(it->second.offset, it->first)] = it->second;
+
+            for (Sorted::const_iterator it=sorted.cbegin(); it!=sorted.cend(); it++)
+            {
+                gLog << ___all___ << std::setw(6) << it->second.offset << "| ";
+                gLog << it->second.num << 'x';
+                switch (it->second.type)
+                {
+                case 'A': gLog << "char(8)";    break;
+                case 'L': gLog << "bool(8)";    break;
+                case 'B': gLog << "byte(8)";    break;
+                case 'I': gLog << "short(16)";  break;
+                case 'J': gLog << "int(32)";    break;
+                case 'K': gLog << "int(64)";    break;
+                case 'E': gLog << "float(32)";  break;
+                case 'D': gLog << "double(64)"; break;
+                }
+                gLog << ": " << it->first.second << " [" << it->second.unit << "]" << std::endl;
+            }
+        }
+
+        operator bool() const { return !name.empty(); }
+
+        bool HasKey(const std::string &key) const
+        {
+            return keys.find(key)!=keys.end();
+        }
+
+        bool HasColumn(const std::string& col) const
+        {
+            return cols.find(col)!=cols.end();
+        }
+
+        const Columns &GetColumns() const
+        {
+            return cols;
+        }
+
+        const Keys &GetKeys() const
+        {
+            return keys;
+        }
+
+        // Values of keys are always signed
+        template<typename T>
+            T Get(const std::string &key) const
+        {
+            const Keys::const_iterator it = keys.find(key);
+            if (it==keys.end())
+            {
+                std::ostringstream str;
+                str << "Key '" << key << "' not found.";
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(str.str());
+#else
+                gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                return T();
+#endif
+            }
+            return it->second.Get<T>();
+        }
+
+        // Values of keys are always signed
+        template<typename T>
+            T Get(const std::string &key, const T &deflt) const
+        {
+            const Keys::const_iterator it = keys.find(key);
+            return it==keys.end() ? deflt :it->second.Get<T>();
+        }
+
+        size_t GetN(const std::string &key) const
+        {
+            const Columns::const_iterator it = cols.find(key);
+            return it==cols.end() ? 0 : it->second.num;
+        }
+	
+
+
+        // There may be a gap between the main table and the start of the heap:
+        // this computes the offset
+        streamoff GetHeapShift() const
+        {
+            if (!HasKey("ZHEAPPTR"))
+                return 0;
+
+            const size_t shift = Get<size_t>("ZHEAPPTR");
+            return shift <= total_bytes ? 0 : shift - total_bytes;
+        }
+
+        // return total number of bytes 'all inclusive'
+        streamoff GetTotalBytes() const
+        {
+            //get offset of special data area from start of main table
+            const streamoff shift = GetHeapShift();
+
+            //and special data area size
+            const streamoff size  = HasKey("PCOUNT") ? Get<streamoff>("PCOUNT") : 0;
+
+            // Get the total size
+            const streamoff total = total_bytes + size + shift;
+
+            // check for padding
+            if (total%2880==0)
+                return total;
+
+            // padding necessary
+            return total + (2880 - (total%2880));
+        }
+    };
+
+protected:
+    std::ofstream fCopy;
+    std::vector<std::string> fListOfTables; // List of skipped tables. Last table is open table
+
+    Table fTable;
+
+    typedef std::pair<void*, Table::Column> Address;
+    typedef std::vector<Address> Addresses;
+    //map<void*, Table::Column> fAddresses;
+    Addresses fAddresses;
+
+    typedef std::unordered_map<std::string, void*> Pointers;
+    Pointers fPointers;
+
+    std::vector<std::vector<char>> fGarbage;
+
+    std::vector<char> fBufferRow;
+    std::vector<char> fBufferDat;
+
+    size_t fRow;
+
+    Checksum fChkHeader;
+    Checksum fChkData;
+
+    bool ReadBlock(std::vector<std::string> &vec)
+    {
+        int endtag = 0;
+        for (int i=0; i<36; i++)
+        {
+            char c[81];
+            c[80] = 0;
+            read(c, 80);
+            if (!good())
+                break;
+
+            fChkHeader.add(c, 80);
+
+//            if (c[0]==0)
+//                return vector<string>();
+
+            std::string str(c);
+
+//            if (!str.empty())
+//                cout << setw(2) << i << "|" << str << "|" << (endtag?'-':'+') << endl;
+
+            if (endtag==2 || str=="END                                                                             ")
+            {
+                endtag = 2; // valid END tag found
+                continue;
+            }
+
+            if (endtag==1 || str=="                                                                                ")
+            {
+                endtag = 1; // end tag not found, but expected to be there
+                continue;
+            }
+
+            vec.emplace_back(str);
+        }
+
+        // Make sure that no empty vector is returned
+        if (endtag && vec.size()%36==0)
+            vec.emplace_back("END     = '' / ");
+
+        return endtag==2;
+    }
+
+    std::string Compile(const std::string &key, int16_t i=-1) const
+    {
+#if GCC_VERSION < 40603
+        return i<0 ? key : key+std::to_string((long long int)(i));
+#else
+        return i<0 ? key : key+std::to_string(i);
+#endif
+    }
+
+    void Constructor(const std::string &fname, std::string fout="", const std::string& tableName="", bool force=false)
+    {
+        char simple[10];
+        read(simple, 10);
+        if (!good())
+            return;
+
+        if (memcmp(simple, "SIMPLE  = ", 10))
+        {
+            clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("File is not a FITS file.");
+#else
+            gLog << ___err___ << "ERROR - File is not a FITS file." << std::endl;
+            return;
+#endif
+        }
+
+        seekg(0);
+
+        while (good())
+        {
+            std::vector<std::string> block;
+            while (1)
+            {
+                // If we search for a table, we implicitly assume that
+                // not finding the table is not an error. The user
+                // can easily check that by eof() && !bad()
+                peek();
+                if (eof() && !bad() && !tableName.empty())
+                {
+                    break;
+                }
+                // FIXME: Set limit on memory consumption
+                const int rc = ReadBlock(block);
+                if (!good())
+                {
+                    clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error("FITS file corrupted.");
+#else
+                    gLog << ___err___ << "ERROR - FITS file corrupted." << std::endl;
+                    return;
+#endif
+                }
+
+                if (block.size()%36)
+                {
+                    if (!rc && !force)
+                    {
+                        clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+                        throw std::runtime_error("END keyword missing in FITS header.");
+#else
+                        gLog << ___err___ << "ERROR - END keyword missing in FITS file... file might be corrupted." << std::endl;
+                        return;
+#endif
+                    }
+                    break;
+                }
+            }
+
+            if (block.empty())
+                break;
+
+            if (block[0].substr(0, 9)=="SIMPLE  =")
+            {
+                fChkHeader.reset();
+                continue;
+            }
+
+            if (block[0].substr(0, 9)=="XTENSION=")
+            {
+                fTable = Table(block, tellg());
+                fRow   = (size_t)-1;
+
+                if (!fTable)
+                {
+                    clear(rdstate()|std::ios::badbit);
+                    return;
+                }
+
+                const std::string &tname = fTable.Get<std::string>("EXTNAME");
+
+                fListOfTables.emplace_back(tname);
+
+                // Check for table name. Skip until eof or requested table are found.
+                // skip the current table?
+                if ((!tableName.empty() && tableName!=tname) || (tableName.empty() && "ZDrsCellOffsets"==tname))
+                {
+                    const streamoff skip = fTable.GetTotalBytes();
+                    seekg(skip, std::ios_base::cur);
+
+                    fChkHeader.reset();
+
+                    continue;
+                }
+
+                fBufferRow.resize(fTable.bytes_per_row + 8-fTable.bytes_per_row%4);
+                fBufferDat.resize(fTable.bytes_per_row);
+
+                break;
+            }
+        }
+
+        if (fout.empty())
+            return;
+
+        if (*fout.rbegin()=='/')
+        {
+            const size_t p = fname.find_last_of('/');
+            fout.append(fname.substr(p+1));
+        }
+
+        fCopy.open(fout);
+        if (!fCopy)
+        {
+            clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("Could not open output file.");
+#else
+            gLog << ___err___ << "ERROR - Failed to open output file." << std::endl;
+            return;
+#endif
+        }
+
+        const streampos p = tellg();
+        seekg(0);
+
+        std::vector<char> buf(p);
+        read(buf.data(), p);
+
+        fCopy.write(buf.data(), p);
+        if (!fCopy)
+            clear(rdstate()|std::ios::badbit);
+    }
+
+public:
+    fits(const std::string &fname, const std::string& tableName="", bool force=false) : izstream(fname.c_str())
+    {
+        Constructor(fname, "", tableName, force);
+        if ((fTable.is_compressed ||fTable.name=="ZDrsCellOffsets") && !force)
+        {
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("You are trying to read a compressed fits with the base fits class. Please use factfits instead.");
+#else
+            gLog << ___err___ << "ERROR - You are trying to read a compressed fits with the base fits class. Please use factfits instead." << std::endl;
+#endif
+            clear(rdstate()|std::ios::badbit);
+        }
+    }
+
+    fits(const std::string &fname, const std::string &fout, const std::string& tableName, bool force=false) : izstream(fname.c_str())
+    {
+        Constructor(fname, fout, tableName, force);
+        if ((fTable.is_compressed || fTable.name=="ZDrsCellOffsets") && !force)
+        {
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("You are trying to read a compressed fits with the base fits class. Please use factfits instead.");
+#else
+            gLog << ___err___ << "ERROR - You are trying to read a compressed fits with the base fits class. Please use factfits instead." << std::endl;
+#endif
+            clear(rdstate()|std::ios::badbit);
+        }
+    }
+
+    fits() : izstream()
+    {
+
+    }
+
+    ~fits()
+    {
+        std::copy(std::istreambuf_iterator<char>(*this),
+                  std::istreambuf_iterator<char>(),
+                  std::ostreambuf_iterator<char>(fCopy));
+    }
+
+    virtual void StageRow(size_t row, char* dest)
+    {
+        // if (row!=fRow+1) // Fast seeking is ensured by izstream
+        seekg(fTable.offset+row*fTable.bytes_per_row);
+        read(dest, fTable.bytes_per_row);
+        //fin.clear(fin.rdstate()&~ios::eofbit);
+    }
+
+    virtual void WriteRowToCopyFile(size_t row)
+    {
+        if (row==fRow+1)
+        {
+            const uint8_t offset = (row*fTable.bytes_per_row)%4;
+
+            fChkData.add(fBufferRow);
+            if (fCopy.is_open() && fCopy.good())
+                fCopy.write(fBufferRow.data()+offset, fTable.bytes_per_row);
+            if (!fCopy)
+                clear(rdstate()|std::ios::badbit);
+        }
+        else
+            if (fCopy.is_open())
+                clear(rdstate()|std::ios::badbit);
+    }
+
+    void ZeroBufferForChecksum(std::vector<char>& vec, const uint64_t extraZeros=0)
+    {
+        auto ib = vec.begin();
+        auto ie = vec.end();
+
+        *ib++ = 0;
+        *ib++ = 0;
+        *ib++ = 0;
+        *ib   = 0;
+
+        for (uint64_t i=0;i<extraZeros+8;i++)
+            *--ie = 0;
+    }
+
+    uint8_t ReadRow(size_t row)
+    {
+        // For the checksum we need everything to be correctly aligned
+        const uint8_t offset = (row*fTable.bytes_per_row)%4;
+
+        ZeroBufferForChecksum(fBufferRow);
+
+        StageRow(row, fBufferRow.data()+offset);
+
+        WriteRowToCopyFile(row);
+
+        fRow = row;
+
+        return offset;
+    }
+
+    template<size_t N>
+        void revcpy(char *dest, const char *src, const int &num)
+    {
+        const char *pend = src + num*N;
+        for (const char *ptr = src; ptr<pend; ptr+=N, dest+=N)
+            std::reverse_copy(ptr, ptr+N, dest);
+    }
+
+    virtual void MoveColumnDataToUserSpace(char *dest, const char *src, const Table::Column& c)
+    {
+        // Let the compiler do some optimization by
+        // knowing that we only have 1, 2, 4 and 8
+        switch (c.size)
+        {
+        case 1: memcpy   (dest, src, c.bytes); break;
+        case 2: revcpy<2>(dest, src, c.num);   break;
+        case 4: revcpy<4>(dest, src, c.num);   break;
+        case 8: revcpy<8>(dest, src, c.num);   break;
+        }
+    }
+
+    virtual bool GetRow(size_t row, bool check=true)
+    {
+        if (check && row>=fTable.num_rows)
+            return false;
+
+        const uint8_t offset = ReadRow(row);
+        if (!good())
+            return good();
+
+        const char *ptr = fBufferRow.data() + offset;
+
+        for (Addresses::const_iterator it=fAddresses.cbegin(); it!=fAddresses.cend(); it++)
+        {
+            const Table::Column &c = it->second;
+
+            const char *src = ptr + c.offset;
+            char *dest = reinterpret_cast<char*>(it->first);
+
+            MoveColumnDataToUserSpace(dest, src, c);
+        }
+
+        return good();
+    }
+
+    bool GetNextRow(bool check=true)
+    {
+        return GetRow(fRow+1, check);
+    }
+
+    virtual bool SkipNextRow()
+    {
+        seekg(fTable.offset+(++fRow)*fTable.bytes_per_row);
+        return good();
+    }
+
+    static bool Compare(const Address &p1, const Address &p2)
+    {
+        return p1.first>p2.first;
+    }
+
+    template<class T, class S>
+    const T &GetAs(const std::string &name)
+    {
+        return *reinterpret_cast<S*>(fPointers[name]);
+    }
+
+    void *SetPtrAddress(const std::string &name)
+    {
+        if (fTable.cols.count(name)==0)
+        {
+            std::ostringstream str;
+            str << "SetPtrAddress('" << name << "') - Column not found.";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(str.str());
+#else
+            gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+            return NULL;
+#endif
+        }
+
+        Pointers::const_iterator it = fPointers.find(name);
+        if (it!=fPointers.end())
+            return it->second;
+
+        fGarbage.emplace_back(fTable.cols[name].bytes);
+
+        void *ptr = fGarbage.back().data();
+
+        fPointers[name] = ptr;
+        fAddresses.emplace_back(ptr, fTable.cols[name]);
+        sort(fAddresses.begin(), fAddresses.end(), Compare);
+        return ptr;
+    }
+
+    template<typename T>
+    bool SetPtrAddress(const std::string &name, T *ptr, size_t cnt)
+    {
+        if (fTable.cols.count(name)==0)
+        {
+            std::ostringstream str;
+            str << "SetPtrAddress('" << name << "') - Column not found.";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(str.str());
+#else
+            gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+            return false;
+#endif
+        }
+
+        if (sizeof(T)!=fTable.cols[name].size)
+        {
+            std::ostringstream str;
+            str << "SetPtrAddress('" << name << "') - Element size mismatch: expected "
+                << fTable.cols[name].size << " from header, got " << sizeof(T);
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(str.str());
+#else
+            gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+            return false;
+#endif
+        }
+
+        if (cnt!=fTable.cols[name].num)
+        {
+            std::ostringstream str;
+            str << "SetPtrAddress('" << name << "') - Element count mismatch: expected "
+                << fTable.cols[name].num << " from header, got " << cnt;
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(str.str());
+#else
+            gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+            return false;
+#endif
+        }
+
+        // if (fAddresses.count(ptr)>0)
+        //     gLog << warn << "SetPtrAddress('" << name << "') - Pointer " << ptr << " already assigned." << endl;
+
+        //fAddresses[ptr] = fTable.cols[name];
+        fPointers[name] = ptr;
+        fAddresses.emplace_back(ptr, fTable.cols[name]);
+        sort(fAddresses.begin(), fAddresses.end(), Compare);
+        return true;
+    }
+
+    template<class T>
+    bool SetRefAddress(const std::string &name, T &ptr)
+    {
+        return SetPtrAddress(name, &ptr, sizeof(ptr)/sizeof(T));
+    }
+
+    template<typename T>
+    bool SetVecAddress(const std::string &name, std::vector<T> &vec)
+    {
+        return SetPtrAddress(name, vec.data(), vec.size());
+    }
+
+    template<typename T>
+        T Get(const std::string &key) const
+    {
+        return fTable.Get<T>(key);
+    }
+
+    template<typename T>
+        T Get(const std::string &key, const std::string &deflt) const
+    {
+        return fTable.Get<T>(key, deflt);
+    }
+
+    bool SetPtrAddress(const std::string &name, void *ptr, size_t cnt=0)
+    {
+        if (fTable.cols.count(name)==0)
+        {
+            std::ostringstream str;
+            str <<"SetPtrAddress('" << name << "') - Column not found.";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(str.str());
+#else
+            gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+            return false;
+#endif
+        }
+
+        if (cnt && cnt!=fTable.cols[name].num)
+        {
+            std::ostringstream str;
+            str << "SetPtrAddress('" << name << "') - Element count mismatch: expected "
+                << fTable.cols[name].num << " from header, got " << cnt;
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(str.str());
+#else
+            gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+            return false;
+#endif
+        }
+
+        // if (fAddresses.count(ptr)>0)
+        //     gLog << warn << "SetPtrAddress('" << name << "') - Pointer " << ptr << " already assigned." << endl;
+
+        //fAddresses[ptr] = fTable.cols[name];
+        fPointers[name] = ptr;
+        fAddresses.emplace_back(ptr, fTable.cols[name]);
+        sort(fAddresses.begin(), fAddresses.end(), Compare);
+        return true;
+    }
+
+    bool     HasKey(const std::string &key) const { return fTable.HasKey(key); }
+    bool     HasColumn(const std::string& col) const { return fTable.HasColumn(col);}
+    const Table::Columns &GetColumns() const { return fTable.GetColumns();}
+    const Table::SortedColumns& GetSortedColumns() const { return fTable.sorted_cols;}
+    const Table::Keys &GetKeys() const { return fTable.GetKeys();}
+
+    int64_t     GetInt(const std::string &key) const { return fTable.Get<int64_t>(key); }
+    uint64_t    GetUInt(const std::string &key) const { return fTable.Get<uint64_t>(key); }
+    double      GetFloat(const std::string &key) const { return fTable.Get<double>(key); }
+    std::string GetStr(const std::string &key) const { return fTable.Get<std::string>(key); }
+
+    size_t GetN(const std::string &key) const
+    {
+        return fTable.GetN(key);
+    }
+
+//    size_t GetNumRows() const { return fTable.num_rows; }
+    size_t GetRow() const { return fRow==(size_t)-1 ? 0 : fRow; }
+
+    operator bool() const { return fTable && fTable.offset!=0; }
+
+    void PrintKeys(bool all_keys=false) const { fTable.PrintKeys(all_keys); }
+    void PrintColumns() const { fTable.PrintColumns(); }
+
+    bool IsHeaderOk() const { return fTable.datasum<0?false:(fChkHeader+Checksum(fTable.datasum)).valid(); }
+    virtual bool IsFileOk() const { return (fChkHeader+fChkData).valid(); }
+
+    bool IsCompressedFITS() const { return fTable.is_compressed;}
+
+    virtual size_t GetNumRows() const
+    {
+        return fTable.Get<size_t>("NAXIS2");
+    }
+
+    virtual size_t GetBytesPerRow() const
+    {
+        return fTable.Get<size_t>("NAXIS1");
+    }
+
+    const std::vector<std::string> &GetTables() const
+    {
+        return fListOfTables;
+    }
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/huffman.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/huffman.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/huffman.h	(revision 17960)
@@ -0,0 +1,435 @@
+#ifndef FACT_huffman
+#define FACT_huffman
+
+#include <string.h>
+#include <stdint.h>
+
+#include <set>
+#include <string>
+#include <vector>
+
+#define MAX_SYMBOLS (1<<16)
+
+// ================================================================
+
+namespace Huffman
+{
+    static unsigned long numbytes_from_numbits(unsigned long numbits)
+    {
+        return numbits / 8 + (numbits % 8 ? 1 : 0);
+    }
+
+    struct TreeNode
+    {
+        TreeNode *parent;
+        union
+        {
+            struct
+            {
+                TreeNode *zero, *one;
+            };
+            uint16_t symbol;
+        };
+
+        size_t count;
+        bool isLeaf;
+
+        TreeNode(uint16_t sym, size_t cnt=0) : parent(0), isLeaf(true)
+        {
+            symbol = sym;
+            count  = cnt;
+        }
+
+        TreeNode(TreeNode *n0=0, TreeNode *n1=0) : parent(0), isLeaf(false)
+        {
+            count = n0 && n1 ?  n0->count + n1->count : 0;
+            zero  = n0 && n1 ? (n0->count > n1->count ? n0 : n1) : NULL;
+            one   = n0 && n1 ? (n0->count > n1->count ? n1 : n0) : NULL;
+
+            if (n0)
+                n0->parent = this;
+
+            if (n1)
+                n1->parent = this;
+        }
+
+        ~TreeNode()
+        {
+            if (isLeaf)
+                return;
+
+            if (zero)
+                delete zero;
+            if (one)
+                delete one;
+        }
+
+        bool operator() (const TreeNode *hn1, const TreeNode *hn2) const
+        {
+            return hn1->count < hn2->count;
+        }
+    };
+
+
+    struct Encoder
+    {
+        struct Code
+        {
+            size_t bits;
+            uint8_t numbits;
+
+            Code() : numbits(0) { }
+        };
+
+        size_t count;
+        Code lut[1<<16];
+
+        bool CreateEncoder(const TreeNode *n, size_t bits=0, uint8_t nbits=0)
+        {
+            if (n->isLeaf)
+            {
+#ifdef __EXCEPTIONS
+                if (nbits>sizeof(size_t)*8)
+                    throw std::runtime_error("Too many different symbols - this should not happen!");
+#else
+                if (nbits>sizeof(size_t)*8)
+                {
+                    count = 0;
+                    return false;
+                }
+#endif
+                lut[n->symbol].bits    = bits;
+                lut[n->symbol].numbits = nbits==0 ? 1 : nbits;
+                count++;
+                return true;
+            }
+
+            return
+                CreateEncoder(n->zero, bits,              nbits+1) &&
+                CreateEncoder(n->one,  bits | (1<<nbits), nbits+1);
+
+        }
+
+        void WriteCodeTable(std::string &out) const
+        {
+            out.append((char*)&count, sizeof(size_t));
+
+            for (uint32_t i=0; i<MAX_SYMBOLS; i++)
+            {
+                const Code &n = lut[i];
+                if (n.numbits==0)
+                    continue;
+
+                // Write the 2 byte symbol.
+                out.append((char*)&i, sizeof(uint16_t));
+                if (count==1)
+                    return;
+
+                // Write the 1 byte code bit length.
+                out.append((char*)&n.numbits, sizeof(uint8_t));
+
+                // Write the code bytes.
+                uint32_t numbytes = numbytes_from_numbits(n.numbits);
+                out.append((char*)&n.bits, numbytes);
+            }
+        }
+
+        void Encode(std::string &out, const uint16_t *bufin, size_t bufinlen) const
+        {
+            if (count==1)
+                return;
+
+            uint8_t curbyte = 0;
+            uint8_t curbit  = 0;
+
+            for (uint32_t i=0; i<bufinlen; ++i)
+            {
+                const uint16_t &symbol = bufin[i];
+
+                const Code *code = lut+symbol;
+
+                uint8_t nbits = code->numbits;
+                const uint8_t *bits = (uint8_t*)&code->bits;
+
+                while (nbits>0)
+                {
+                    // Number of bits available in the current byte
+                    const uint8_t free_bits = 8 - curbit;
+
+                    // Write bits to current byte
+                    curbyte |= *bits<<curbit;
+
+                    // If the byte has been filled, put it into the output buffer
+                    // If the bits exceed the current byte step to the next byte
+                    // and fill it properly
+                    if (nbits>=free_bits)
+                    {
+                        out += curbyte;
+                        curbyte = *bits>>free_bits;
+
+                        bits++;
+                    }
+
+                    // Adapt the number of available bits, the number of consumed bits
+                    // and the bit-pointer accordingly
+                    const uint8_t consumed = nbits>8 ? 8 : nbits;
+                    nbits  -= consumed;
+                    curbit += consumed;
+                    curbit %= 8;
+                }
+            }
+
+            // If the buffer-byte is half-full, also add it to the output buffer
+            if (curbit>0)
+                out += curbyte;
+        }
+
+        Encoder(const uint16_t *bufin, size_t bufinlen) : count(0)
+        {
+            uint64_t counts[MAX_SYMBOLS];
+            memset(counts, 0, sizeof(uint64_t)*MAX_SYMBOLS);
+
+            // Count occurances
+            for (const uint16_t *p=bufin; p<bufin+bufinlen; p++)
+                counts[*p]++;
+
+            // Copy all occuring symbols into a sorted list
+            std::multiset<TreeNode*, TreeNode> set;
+            for (int i=0; i<MAX_SYMBOLS; i++)
+                if (counts[i])
+                    set.insert(new TreeNode(i, counts[i]));
+
+            // Create the tree bottom-up
+            while (set.size()>1)
+            {
+                auto it = set.begin();
+
+                auto it1 = it++;
+                auto it2 = it;
+
+                TreeNode *nn = new TreeNode(*it1, *it2);
+
+                set.erase(it1, ++it2);
+
+                set.insert(nn);
+            }
+
+            // get the root of the tree
+            const TreeNode *root = *set.begin();
+
+            CreateEncoder(root);
+
+            // This will delete the whole tree
+            delete root;
+        }
+
+    };
+
+
+
+    struct Decoder
+    {
+        uint16_t symbol;
+        uint8_t nbits;
+        bool isLeaf;
+
+        Decoder *lut;
+
+        Decoder() : isLeaf(false), lut(NULL)
+        {
+        }
+
+        ~Decoder()
+        {
+            if (lut)
+                delete [] lut;
+        }
+
+        void Set(uint16_t sym, uint8_t n=0, size_t bits=0)
+        {
+            if (!lut)
+                lut = new Decoder[256];
+
+            if (n>8)
+            {
+                lut[bits&0xff].Set(sym, n-8, bits>>8);
+                return;
+            }
+
+            const int nn = 1<<(8-n);
+
+            for (int i=0; i<nn; i++)
+            {
+                const uint8_t key = bits | (i<<n);
+
+                lut[key].symbol = sym;
+                lut[key].isLeaf = true;
+                lut[key].nbits  = n;
+            }
+        }
+
+        void Build(const TreeNode &p, uint64_t bits=0, uint8_t n=0)
+        {
+            if (p.isLeaf)
+            {
+                Set(p.symbol, n, bits);
+                return;
+            }
+
+            Build(*p.zero, bits,          n+1);
+            Build(*p.one,  bits | (1<<n), n+1);
+        }
+
+        Decoder(const TreeNode &p) : symbol(0), isLeaf(false), lut(NULL)
+        {
+            Build(p);
+        }
+
+        const uint8_t *Decode(const uint8_t *in_ptr, const uint8_t *in_end,
+                              uint16_t *out_ptr, const uint16_t *out_end) const
+        {
+            Decoder const *p = this;
+
+            if (in_ptr==in_end)
+            {
+                while (out_ptr < out_end)
+                    *out_ptr++ = p->lut->symbol;
+                return in_ptr;
+            }
+
+            uint8_t curbit = 0;
+            while (in_ptr<in_end && out_ptr<out_end)
+            {
+                const uint16_t *two = (uint16_t*)in_ptr;
+
+                const uint8_t curbyte = (*two >> curbit);
+
+#ifdef __EXCEPTIONS
+                if (!p->lut)
+                    throw std::runtime_error("Unknown bitcode in stream!");
+#else
+                if (!p->lut)
+                    return NULL;
+#endif
+
+                p = p->lut + curbyte;
+                if (!p->isLeaf)
+                {
+                    in_ptr++;
+                    continue;
+                }
+
+                *out_ptr++ = p->symbol;
+                curbit += p->nbits;
+
+                p = this;
+
+                if (curbit>=8)
+                {
+                    curbit %= 8;
+                    in_ptr++;
+                }
+
+            }
+
+            return curbit ? in_ptr+1 : in_ptr;
+        }
+
+        Decoder(const uint8_t* bufin, int64_t &pindex) : isLeaf(false), lut(NULL)
+        {
+            // FIXME: Sanity check for size missing....
+
+            // Read the number of entries.
+            size_t count=0;
+            memcpy(&count, bufin + pindex, sizeof(count));
+            pindex += sizeof(count);
+
+            // Read the entries.
+            for (size_t i=0; i<count; i++)
+            {
+                uint16_t sym;
+                memcpy(&sym, bufin + pindex, sizeof(uint16_t));
+                pindex += sizeof(uint16_t);
+
+                if (count==1)
+                {
+                    Set(sym);
+                    break;
+                }
+
+                uint8_t numbits;
+                memcpy(&numbits, bufin + pindex, sizeof(uint8_t));
+                pindex += sizeof(uint8_t);
+
+                const uint8_t numbytes = numbytes_from_numbits(numbits);
+
+#ifdef __EXCEPTIONS
+                if (numbytes>sizeof(size_t))
+                    throw std::runtime_error("Number of bytes for a single symbol exceeds maximum.");
+#else
+                if (numbytes>sizeof(size_t))
+                {
+                    pindex = -1;
+                    return;
+                }
+#endif
+                size_t bits=0;
+                memcpy(&bits, bufin+pindex, numbytes);
+                pindex += numbytes;
+
+                Set(sym, numbits, bits);
+            }
+        }
+    };
+
+    inline bool Encode(std::string &bufout, const uint16_t *bufin, size_t bufinlen)
+    {
+        const Encoder encoder(bufin, bufinlen);
+
+#ifndef __EXCEPTIONS
+        if (encoder.count==0)
+            return false;
+#endif
+
+        bufout.append((char*)&bufinlen, sizeof(size_t));
+        encoder.WriteCodeTable(bufout);
+        encoder.Encode(bufout, bufin, bufinlen);
+
+        return true;
+    }
+
+    inline int64_t Decode(const uint8_t *bufin,
+                          size_t         bufinlen,
+                          std::vector<uint16_t> &pbufout)
+    {
+        int64_t i = 0;
+
+        // Read the number of data bytes this encoding represents.
+        size_t data_count = 0;
+        memcpy(&data_count, bufin, sizeof(size_t));
+        i += sizeof(size_t);
+
+
+        pbufout.resize(data_count);
+
+        const Decoder decoder(bufin, i);
+
+#ifndef __EXCEPTIONS
+        if (i==-1)
+            return -1;
+#endif
+
+        const uint8_t *in_ptr =
+            decoder.Decode(bufin+i, bufin+bufinlen,
+                           pbufout.data(), pbufout.data()+data_count);
+
+#ifndef __EXCEPTIONS
+        if (!in_ptr)
+            return -1;
+#endif
+
+        return in_ptr-bufin;
+    }
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/izstream.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/izstream.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/izstream.h	(revision 17960)
@@ -0,0 +1,170 @@
+#ifndef MARS_izstream
+#define MARS_izstream
+
+#include <string.h>
+
+#include <istream>
+#include <streambuf>
+
+#ifdef __CINT__
+typedef void *gzFile;
+#else
+#include <zlib.h>
+#endif
+
+class izstream : public std::streambuf, public std::istream
+{
+private:
+    static const int fgBufferSize = 2048*1024*2;
+
+    gzFile fFile;   // file handle for compressed file
+    char  *fBuffer; // data buffer
+
+    int underflow()
+    {
+        if (gptr() && gptr()<egptr())
+            return * reinterpret_cast<unsigned char *>(gptr());
+
+        if (!is_open())
+            return EOF;
+
+        // gptr()-eback(): if more than four bytes are already flushed
+        const int iputback = gptr()-eback()>4 ? 4 : gptr()-eback();
+
+        // Copy the last four bytes flushed into the putback area
+        memcpy(fBuffer+(4-iputback), gptr()-iputback, iputback);
+
+        // Fill the buffer starting at the current file position and reset buffer
+        // pointers by calling setg
+        const int num = gzread(fFile, fBuffer+4, fgBufferSize-4);
+        if (num <= 0) // ERROR or EOF
+            return EOF;
+
+        // reset buffer pointers
+        setg(fBuffer+(4-iputback), fBuffer+4, fBuffer+4+num);
+
+        // return next character
+        return *reinterpret_cast<unsigned char *>(gptr());
+    }
+
+
+public:
+    izstream() : std::istream(this), fFile(0)
+    {
+        fBuffer = new char[fgBufferSize];
+        setg(fBuffer+4, fBuffer+4, fBuffer+4);
+    }
+    izstream(const char *name) : std::istream(this), fFile(0)
+    {
+        fBuffer = new char[fgBufferSize];
+        setg(fBuffer+4, fBuffer+4, fBuffer+4);
+        open(name);
+    }
+    ~izstream() { izstream::close(); delete [] fBuffer; }
+
+    int is_open() { return fFile!=0; }
+
+    // --------------------------------------------------------------------------
+    //
+    // Open a file by name. Test if it is open like for an ifstream
+    // It doesn't matter whether the file is gzip compressed or not.
+    //
+    void open(const char* name)
+    {
+        if (is_open())
+        {
+            clear(rdstate()|std::ios::failbit);
+            return;
+        }
+
+        fFile = gzopen(name, "rb");
+        if (fFile == 0)
+        {
+            clear(rdstate()|std::ios::failbit);
+            return;
+        }
+    }
+    // --------------------------------------------------------------------------
+    //
+    // Close an open file.
+    //
+    void close()
+    {
+        if (!is_open())
+            return;
+
+        if (gzclose(fFile) != Z_OK)
+            clear(rdstate()|std::ios::failbit);
+
+        fFile = 0;
+    }
+
+    std::streambuf::pos_type seekoff(std::streambuf::off_type offset, std::ios_base::seekdir dir,
+                                     std::ios_base::openmode = std::ios_base::in)
+    {
+        // Using a switch instead results in:
+        //  In member function `virtual std::streampos izstream::seekoff(long int, std::_Ios_Seekdir, std::_Ios_Openmode)':
+        //  warning: enumeration value `_M_ios_seekdir_end' not handled in switch
+        //  warning: case value `0' not in enumerated type `_Ios_Seekdir'
+        //  warning: case value `1' not in enumerated type `_Ios_Seekdir'
+        //  warning: case value `2' not in enumerated type `_Ios_Seekdir'
+
+        if (dir==std::ios::end)
+        {
+            clear(rdstate()|std::ios::failbit);
+            return EOF;
+        }
+
+        // We only do relative seeking to avoid unnecessary decompression
+        // of the whole file
+        if (dir==std::ios::beg)
+            offset -= tellg();
+
+        // Calculate future position in streambuffer
+        const char *ptr = gptr()+offset;
+
+        // This is the number of bytes still available in the buffer
+        const size_t sbuf = egptr()-gptr();
+
+        // Check if the new position will still be in the buffer
+        // In this case the target data was already decompressed.
+        if (ptr>=eback() && ptr<egptr())
+        {
+            // Absolute position in z-stream
+            const z_off_t zpos = gztell(fFile)-sbuf; //gzseek(fFile, 0, SEEK_CUR);
+
+            gbump(offset);
+
+            return zpos+offset;
+        }
+
+        const streampos pos = gzseek(fFile, offset-sbuf, SEEK_CUR);
+
+        // Buffer is empty - force refilling
+        setg(fBuffer+4, fBuffer+4, fBuffer+4);
+
+        return pos<0 ? streampos(EOF) : pos;
+
+        /*
+         // SEEK_END not supported by zlib
+         if (dir==ios::end)
+         {
+             // Position in z-stream
+             const z_off_t zpos = gzseek(fFile, offset, SEEK_END);
+             if (zpos<0)
+                 return EOF;
+
+             return fill_buffer()==EOF ? EOF : zpos;
+         }
+         */
+        return EOF;
+    }
+
+    std::streambuf::pos_type seekpos(std::streambuf::pos_type pos,
+                                     std::ios_base::openmode = std::ios_base::in)
+    {
+        return seekoff(pos, std::ios::beg);
+    }
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/nova.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/nova.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/nova.h	(revision 17960)
@@ -0,0 +1,161 @@
+#ifndef MARS_Nova
+#define MARS_Nova
+
+#include <libnova/solar.h>
+#include <libnova/lunar.h>
+#include <libnova/rise_set.h>
+#include <libnova/transform.h>
+#include <libnova/angular_separation.h>
+
+namespace Nova
+{
+    typedef ln_lnlat_posn LnLatPosn;
+    typedef ln_rst_time   RstTime; // Note that times are in JD not Mjd
+    //typedef ln_hrz_posn   HrzPosn;
+    //typedef ln_equ_posn   EquPosn;
+
+    struct ZdAzPosn;
+    struct RaDecPosn;
+
+
+    // Warning: 0deg=South, 90deg=W
+    struct HrzPosn : public ln_hrz_posn
+    {
+        HrzPosn() { }
+        HrzPosn(const ZdAzPosn &);
+    };
+
+    struct ZdAzPosn
+    {
+        double zd; // [deg]
+        double az; // [deg]
+
+        ZdAzPosn(double z=0, double a=0) : zd(z), az(a) { }
+        ZdAzPosn(const HrzPosn &hrz) : zd(90-hrz.alt), az(hrz.az-180) { }
+
+        // This crahsed cint, but it could save up the dedicate structure HrzPosn :(
+        //operator HrzPosn() const { const HrzPosn p = { az-180, 90-zd}; return p; }
+    };
+
+    HrzPosn::HrzPosn(const ZdAzPosn &za) { alt = 90-za.zd; az = za.az-180; }
+
+
+    // Note that right ascension is stored in degree
+    struct EquPosn : public ln_equ_posn
+    {
+        EquPosn() { }
+        EquPosn(const RaDecPosn &);
+    };
+
+    struct RaDecPosn
+    {
+        double ra;  // [h]
+        double dec; // [deg]
+
+        RaDecPosn(double r=0, double d=0) : ra(r), dec(d) { }
+        RaDecPosn(const EquPosn &equ) : ra(equ.ra/15), dec(equ.dec) { }
+
+        // This crahsed cint, but it could save up the dedicate structure HrzPosn :(
+        //operator HrzPosn() const { const HrzPosn p = { az-180, 90-zd}; return p; }
+    };
+
+    EquPosn::EquPosn(const RaDecPosn &rd) { ra = rd.ra*15; dec = rd.dec; }
+
+
+
+    const LnLatPosn &ORM()
+    {
+        //static LnLatPosn obs;
+        //obs.lng = -(17.+53./60+26.525/3600);
+        //obs.lat =   28.+45./60+42.462/3600;
+        const static LnLatPosn obs = { -(17.+53./60+26.525/3600), 28.+45./60+42.462/3600 };
+        return obs;
+    }
+
+    HrzPosn GetHrzFromEqu(const EquPosn &equ, const LnLatPosn &obs, double jd)
+    {
+        HrzPosn hrz;
+        ln_get_hrz_from_equ(const_cast<EquPosn*>(&equ), const_cast<LnLatPosn*>(&obs), jd, &hrz);
+        return hrz;
+    }
+    HrzPosn GetHrzFromEqu(const EquPosn &equ, double jd)
+    {
+        return GetHrzFromEqu(equ, ORM(), jd);
+    }
+
+    EquPosn GetEquFromHrz(const HrzPosn &hrz, const LnLatPosn &obs, double jd)
+    {
+        EquPosn equ;
+        ln_get_equ_from_hrz(const_cast<HrzPosn*>(&hrz), const_cast<LnLatPosn*>(&obs), jd, &equ);
+        return equ;
+    }
+    EquPosn GetEquFromHrz(const HrzPosn &hrz, double jd)
+    {
+        return GetEquFromHrz(hrz, ORM(), jd);
+    }
+
+    RstTime GetSolarRst(double jd, const LnLatPosn &obs, double hrz=LN_SOLAR_STANDART_HORIZON)
+    {
+        RstTime rst;
+        ln_get_solar_rst_horizon(jd, const_cast<LnLatPosn*>(&obs), hrz, &rst);
+        return rst;
+    }
+    RstTime GetSolarRst(double jd, double hrz=LN_SOLAR_STANDART_HORIZON)
+    {
+        return GetSolarRst(jd, ORM(), hrz);
+    }
+
+    RstTime GetLunarRst(double jd, const LnLatPosn &obs=ORM())
+    {
+        RstTime rst;
+        ln_get_lunar_rst(jd, const_cast<LnLatPosn*>(&obs), &rst);
+        return rst;
+    }
+    EquPosn GetSolarEquCoords(double jd)
+    {
+        EquPosn equ;
+        ln_get_solar_equ_coords(jd, &equ);
+        return equ;
+    }
+
+    double GetLunarDisk(double jd)
+    {
+        return ln_get_lunar_disk(jd);
+    }
+
+    double GetLunarSdiam(double jd)
+    {
+        return ln_get_lunar_sdiam(jd);
+    }
+
+    double GetLunarPhase(double jd)
+    {
+        return ln_get_lunar_phase(jd);
+    }
+
+    EquPosn GetLunarEquCoords(double jd, double precision=0)
+    {
+        EquPosn equ;
+        ln_get_lunar_equ_coords_prec(jd, &equ, precision);
+        return equ;
+    }
+
+    double GetLunarEarthDist(double jd)
+    {
+        return ln_get_lunar_earth_dist(jd);
+    }
+
+    double GetAngularSeparation(const EquPosn &p1, const EquPosn &p2)
+    {
+        return ln_get_angular_separation(const_cast<EquPosn*>(&p1), const_cast<EquPosn*>(&p2));
+    }
+
+    double GetAngularSeparation(const HrzPosn &h1, const HrzPosn &h2)
+    {
+        EquPosn p1; p1.ra=h1.az; p1.dec=h1.alt;
+        EquPosn p2; p2.ra=h2.az; p2.dec=h2.alt;
+        return ln_get_angular_separation(&p1, &p2);
+    }
+}
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/ofits.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/ofits.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/ofits.h	(revision 17960)
@@ -0,0 +1,1115 @@
+#ifndef MARS_ofits
+#define MARS_ofits
+
+#include "FITS.h"
+#include "fits.h"
+
+#ifndef PACKAGE_NAME
+#define PACKAGE_NAME "n/a"
+#endif
+
+#ifndef PACKAGE_VERSION
+#define PACKAGE_VERSION "n/a"
+#endif
+
+#ifndef REVISION
+#define REVISION "n/a"
+#endif
+
+#ifdef __CINT__
+#define off_t size_t
+#endif
+
+// Sloppy:  allow / <--- left
+//          allow all characters (see specs for what is possible)
+
+// units: m kg s rad sr K A mol cd Hz J W V N Pa C Ohm S F Wb T Hlm lx
+
+
+class ofits : public std::ostream
+{
+protected:
+    std::filebuf fFilebuf;
+
+public:
+    struct Key
+    {
+        std::string key;
+        bool        delim;
+        std::string value;
+        std::string comment;
+        std::string fitsString;
+
+        off_t offset;   // offset in file
+
+        bool changed;   // For closing the file
+
+        Key() : delim(false), offset(0), changed(true) { }
+        Key(const std::string &s) : delim(false), fitsString(s), offset(0), changed(true) { }
+
+        std::string Trim(const std::string &str)
+        {
+            // Trim Both leading and trailing spaces
+            const size_t first = str.find_first_not_of(' '); // Find the first character position after excluding leading blank spaces
+            const size_t last  = str.find_last_not_of(' ');  // Find the first character position from reverse af
+
+            // if all spaces or empty return an empty string
+            if (std::string::npos==first || std::string::npos==last)
+                return std::string();
+
+            return str.substr(first, last-first+1);
+        }
+
+        bool FormatKey()
+        {
+            key = Trim(key);
+            if (key.empty())
+            {
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("Key name empty.");
+#else
+                gLog << ___err___ << "ERROR - Key name empty." << std::endl;
+                return false;
+#endif
+            }
+            if (key.size()>8)
+            {
+                std::ostringstream sout;
+                sout << "Key '" << key << "' exceeds 8 bytes.";
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(sout.str());
+#else
+                gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+                return false;
+#endif
+            }
+
+            //transform(key.begin(), key.end(), key.begin(), toupper);
+#if GCC_VERSION < 40603
+            for (std::string::const_iterator c=key.begin(); c<key.end(); c++)
+#else
+            for (std::string::const_iterator c=key.cbegin(); c<key.cend(); c++)
+#endif
+                if ((*c<'A' || *c>'Z') && (*c<'0' || *c>'9') && *c!='-' && *c!='_')
+                {
+                    std::ostringstream sout;
+                    sout << "Invalid character '" << *c << "' found in key '" << key << "'";
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error(sout.str());
+#else
+                    gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+                    return false;
+#endif
+                }
+
+            return true;
+        }
+
+        bool FormatComment()
+        {
+            comment = Trim(comment);
+
+#if GCC_VERSION < 40603
+            for (std::string::const_iterator c=key.begin(); c<key.end(); c++)
+#else
+            for (std::string::const_iterator c=key.cbegin(); c<key.cend(); c++)
+#endif
+                if (*c<32 || *c>126)
+                {
+                    std::ostringstream sout;
+                    sout << "Invalid character '" << *c << "' [" << int(*c) << "] found in comment '" << comment << "'";
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error(sout.str());
+#else
+                    gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+                    return false;
+#endif
+                }
+
+            return true;
+        }
+
+        bool check(bool trim=false)
+        {
+            if (!FormatKey())
+                return false;
+
+            if (!FormatComment())
+                return false;
+
+            size_t sz = CalcSize();
+            if (sz<=80)
+                return true;
+
+            if (!trim)
+            {
+                std::ostringstream sout;
+                sout << "Size " << sz << " of entry for key '" << key << "' exceeds 80 characters.";
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(sout.str());
+#else
+                gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+#endif
+                return false;
+            }
+
+            //looks like something went wrong. Maybe entry is too long ?
+            //try to remove the comment
+            comment = "";
+
+            sz = CalcSize();
+            if (sz<=80)
+            {
+#ifndef __EXCEPTIONS
+                std::ostringstream sout;
+                sout << "Size " << sz << " of entry for key '" << key << "' exceeds 80 characters... removed comment.";
+                gLog << ___warn___ << "WARNING - " << sout.str() << std::endl;
+#endif
+                return true;
+            }
+
+            std::ostringstream sout;
+            sout << "Size " << sz << " of entry for key '" << key << "' exceeds 80 characters even without comment.";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        size_t CalcSize() const
+        {
+            if (!delim)
+                return 10+comment.size();
+
+            return 10 + (value.size()<20?20:value.size()) + 3 + comment.size();
+        }
+
+        std::string Compile()
+        {
+            if (!fitsString.empty())
+                return fitsString;
+
+            std::ostringstream sout;
+            sout << std::left << std::setw(8) << key;
+
+            if (!delim)
+            {
+                sout << "  " << comment;
+                return sout.str();
+            }
+
+            sout << "= ";
+            sout << (!value.empty() && value[0]=='\''?std::left:std::right);
+            sout << std::setw(20) << value << std::left;
+
+            if (!comment.empty())
+                sout << " / " << comment;
+
+            return sout.str();
+        }
+
+        Checksum checksum;
+
+        void Out(std::ostream &fout)
+        {
+            if (!changed)
+                return;
+
+            std::string str = Compile();
+            str.insert(str.end(), 80-str.size(), ' ');
+
+            if (offset==0)
+                offset = fout.tellp();
+
+            //cout << "Write[" << offset << "]: " << key << "/" << value << endl;
+
+            fout.seekp(offset);
+            fout << str;
+
+            checksum.reset();
+            checksum.add(str.c_str(), 80);
+
+            changed = false;
+        }
+        /*
+        void Out(ostream &out)
+        {
+            std::string str = Compile();
+
+            str.insert(str.end(), 80-str.size(), ' ');
+
+            out << str;
+            changed = false;
+        }*/
+    };
+
+private:
+    std::vector<Key> fKeys;
+
+    std::vector<Key>::iterator findkey(const std::string &key)
+    {
+        for (auto it=fKeys.begin(); it!=fKeys.end(); it++)
+            if (key==it->key)
+                return it;
+
+        return fKeys.end();
+    }
+
+    bool Set(const std::string &key="", bool delim=false, const std::string &value="", const std::string &comment="")
+    {
+        // If no delimit add the row no matter if it alread exists
+        if (delim)
+        {
+            // if the row already exists: update it
+            auto it = findkey(key);
+            if (it!=fKeys.end())
+            {
+                it->value   = value;
+                it->changed = true;
+                return true;
+            }
+        }
+
+        if (fTable.num_rows>0)
+        {
+            std::ostringstream sout;
+            sout << "No new header key can be defined, rows were already written to the file... ignoring new key '" << key << "'";
+#ifdef __EXCEPTIONS
+                throw std::runtime_error(sout.str());
+#else
+                gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+                return false;
+#endif
+        }
+
+        Key entry;
+
+        entry.key     = key;
+        entry.delim   = delim;
+        entry.value   = value;
+        entry.comment = comment;
+
+        if (!entry.check(fCommentTrimming))
+            return false;
+
+        fKeys.emplace_back(entry);
+        return true;
+    }
+
+protected:
+    struct Table
+    {
+        off_t offset;
+
+        size_t bytes_per_row;
+        size_t num_rows;
+        size_t num_cols;
+
+        struct Column
+        {
+            std::string name;
+            size_t offset;
+            size_t num;
+            size_t size;
+            char   type;
+        };
+
+        std::vector<Column> cols;
+
+        Table() : offset(0), bytes_per_row(0), num_rows(0), num_cols(0)
+        {
+        }
+    };
+
+
+    Table fTable;
+
+    std::vector<char> fOutputBuffer;
+
+    std::vector<Table::Column>::const_iterator findcol(const std::string &name)
+    {
+        for (auto it=fTable.cols.cbegin(); it!=fTable.cols.cend(); it++)
+            if (name==it->name)
+                return it;
+
+        return fTable.cols.cend();
+    }
+
+    Checksum fDataSum;
+    Checksum fHeaderSum;
+
+    bool fCommentTrimming;
+    bool fManualExtName;
+
+public:
+    ofits()
+        : std::ostream(), fFilebuf(), fCommentTrimming(false), fManualExtName(false)
+    {
+        init(&fFilebuf);
+    }
+
+    ofits(const char *fname)
+        : std::ostream(), fFilebuf(), fCommentTrimming(false), fManualExtName(false)
+    {
+        init(&fFilebuf);
+        open(fname);
+    }
+
+#ifdef __GXX_EXPERIMENTAL_CXX0X__
+    ofits(const std::string &fname)
+        : std::ostream(), fCommentTrimming(false), fManualExtName(false)
+    {
+        init(&fFilebuf);
+        open(fname);
+    }
+#endif
+
+    virtual ~ofits()
+    {
+        if (is_open())
+            close();
+    }
+/*
+    filebuf *rdbuf() const
+    {
+        return const_cast<filebuf*>(&fFilebuf);
+    }
+*/
+    bool is_open()
+    {
+        return fFilebuf.is_open();
+    }
+
+    bool is_open() const
+    {
+        return fFilebuf.is_open();
+    }
+
+    virtual void open(const char *filename, bool addEXTNAMEKey=true)
+    {
+        fDataSum  = 0;
+        fHeaderSum = 0;
+
+        fTable = Table();
+        fKeys.clear();
+
+        SetStr("XTENSION", "BINTABLE", "binary table extension");
+        SetInt("BITPIX",  8, "8-bit bytes");
+        SetInt("NAXIS",   2, "2-dimensional binary table");
+        SetInt("NAXIS1",  0, "width of table in bytes");
+        SetInt("NAXIS2",  0, "number of rows in table");
+        SetInt("PCOUNT",  0, "size of special data area");
+        SetInt("GCOUNT",  1, "one data group (required keyword)");
+        SetInt("TFIELDS", 0, "number of fields in each row");
+        if (addEXTNAMEKey)
+            SetStr("EXTNAME", "", "name of extension table");
+        else
+            fManualExtName = true;
+        SetStr("CHECKSUM", "0000000000000000", "Checksum for the whole HDU");
+        SetStr("DATASUM",  "         0", "Checksum for the data block");
+
+        if (!fFilebuf.open(filename, ios_base::out|ios_base::trunc))
+            setstate(ios_base::failbit);
+        else
+            clear();
+    }
+
+    virtual void open(const std::string &filename, bool addEXTNAMEKey=true)
+    {
+        open(filename.c_str(), addEXTNAMEKey);
+    }
+
+    void AllowCommentsTrimming(bool allow)
+    {
+        fCommentTrimming = allow;
+    }
+
+    //Etienne: required to enable 1 to 1 reconstruction of files
+    bool SetKeyComment(const std::string& key, const std::string& comment)
+    {
+        auto it = findkey(key);
+        if (it==fKeys.end())
+            return false;
+
+        it->comment = comment;
+        it->changed = true;
+        return true;
+    }
+        /* tbretz, I removed that, because it does not comply
+         with the FITS standard, it omits all checks... it
+         neither checks if a row already exists, not
+         checks the chcracter set
+    bool SetKeyFromFitsString(const std::string& fitsString)
+    {
+        if (fTable.num_rows>0)
+        {
+            std::ostringstream sout;
+            sout << "No new header key can be defined, rows were already written to the file... ignoring new key '" << fitsString << "'";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        Key entry;
+        entry.fitsString = fitsString;
+        entry.changed = true;
+        fKeys.push_back(entry);
+        return true;
+}*/
+
+
+    bool CopyKeys(const fits &fin, bool update=false)
+    {
+        if (fTable.num_rows>0)
+        {
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("No header keys can be copied, rows were already written to the file... ignoring CopyKeys().");
+#else
+            gLog << ___err___ << "ERROR - No header key can be copyied, rows were already written to the file... ignoring CopyKeys()." << std::endl;
+            return false;
+#endif
+        }
+
+        const auto &keys = fin.GetKeys();
+
+        // We can assume that the keys are all valid
+        for (auto it=keys.cbegin(); it!=keys.cend(); it++)
+        {
+            const std::string &key = it->first;
+
+            if (FITS::IsReservedKeyWord(key))
+                continue;
+
+            const auto &entry = it->second;
+
+            // If no delimit add the row no matter if it alread exists
+            if (entry.fitsString[9]=='=')
+            {
+                // if the row already exists: remove it
+                const auto it2 = findkey(key);
+                if (it2!=fKeys.end())
+                {
+                    if (!update)
+                        continue;
+
+                    fKeys.erase(it2);
+                }
+            }
+
+            fKeys.emplace_back(entry.fitsString);
+        }
+
+        return true;
+    }
+
+
+    bool SetRaw(const std::string &key, const std::string &val, const std::string &comment)
+    {
+        return Set(key, true, val, comment);
+    }
+
+    bool SetBool(const std::string &key, bool b, const std::string &comment="")
+    {
+        return Set(key, true, b?"T":"F", comment);
+    }
+
+    bool AddEmpty(const std::string &key, const std::string &comment="")
+    {
+        return Set(key, true, "", comment);
+    }
+
+    bool SetStr(const std::string &key, std::string s, const std::string &comment="")
+    {
+        for (uint i=0; i<s.length(); i++)
+            if (s[i]=='\'')
+                s.insert(i++, "\'");
+
+        return Set(key, true, "'"+s+"'", comment);
+    }
+
+    bool SetInt(const std::string &key, int64_t i, const std::string &comment="")
+    {
+        std::ostringstream sout;
+        sout << i;
+
+        return Set(key, true, sout.str(), comment);
+    }
+
+    bool SetFloat(const std::string &key, double f, int p, const std::string &comment="")
+    {
+        std::ostringstream sout;
+
+        if (p<0)
+            sout << std::setprecision(-p) << fixed;
+        if (p>0)
+            sout << std::setprecision(p);
+        if (p==0)
+            sout << std::setprecision(f>1e-100 && f<1e100 ? 15 : 14);
+
+        sout << f;
+
+        std::string str = sout.str();
+
+        replace(str.begin(), str.end(), 'e', 'E');
+
+        if (str.find_first_of('E')==std::string::npos && str.find_first_of('.')==std::string::npos)
+            str += ".";
+
+        return Set(key, true, str, comment);
+    }
+
+    bool SetFloat(const std::string &key, double f, const std::string &comment="")
+    {
+        return SetFloat(key, f, 0, comment);
+    }
+
+    bool SetHex(const std::string &key, uint64_t i, const std::string &comment="")
+    {
+        std::ostringstream sout;
+        sout << std::hex << "0x" << i;
+        return SetStr(key, sout.str(), comment);
+    }
+
+    bool AddComment(const std::string &comment)
+    {
+        return Set("COMMENT", false, "", comment);
+    }
+
+    bool AddHistory(const std::string &comment)
+    {
+        return Set("HISTORY", false, "", comment);
+    }
+
+    void End()
+    {
+        Set("END");
+        while (fKeys.size()%36!=0)
+            fKeys.emplace_back();
+    }
+
+    //ETIENNE to be able to restore the file 1 to 1, I must restore the header keys myself
+    virtual bool AddColumn(uint32_t cnt, char typechar, const std::string &name, const std::string &unit, const std::string &comment="", bool addHeaderKeys=true)
+    {
+        if (tellp()<0)
+        {
+            std::ostringstream sout;
+            sout << "File not open... ignoring column '" << name << "'";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        if (tellp()>0)
+        {
+            std::ostringstream sout;
+            sout << "Header already written, no new column can be defined... ignoring column '" << name << "'";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        if (findcol(name)!=fTable.cols.cend())
+        {
+            std::ostringstream sout;
+            sout << "A column with the name '" << name << "' already exists.";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        typechar = toupper(typechar);
+
+        static const std::string allow("LABIJKEDQ");
+#if GCC_VERSION < 40603
+        if (std::find(allow.begin(), allow.end(), typechar)==allow.end())
+#else
+        if (std::find(allow.cbegin(), allow.cend(), typechar)==allow.end())
+#endif
+        {
+            std::ostringstream sout;
+            sout << "Column type '" << typechar << "' not supported.";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        std::ostringstream type;
+        type << cnt;
+        if (typechar=='Q')
+            type << "QB";
+        else
+            type << typechar;
+
+        fTable.num_cols++;
+
+        if (addHeaderKeys)
+        {
+#if GCC_VERSION < 40603
+            const std::string nc = std::to_string((long long int)(fTable.num_cols));
+#else
+            const std::string nc = std::to_string(fTable.num_cols);
+#endif
+            SetStr("TFORM"+nc, type.str(), "format of "+name+" "+FITS::CommentFromType(typechar));
+            SetStr("TTYPE"+nc, name, comment);
+            if (!unit.empty())
+                SetStr("TUNIT"+nc, unit, "unit of "+name);
+        }
+
+        const size_t size = FITS::SizeFromType(typechar);
+
+        Table::Column col;
+
+        col.name   = name;
+        col.type   = typechar;
+        col.num    = cnt;
+        col.size   = size;
+        col.offset = fTable.bytes_per_row;
+
+        fTable.cols.emplace_back(col);
+
+        fTable.bytes_per_row += size*cnt;
+
+        // Align to four bytes
+        fOutputBuffer.resize(fTable.bytes_per_row + 4-fTable.bytes_per_row%4);
+
+        return true;
+    }
+
+    virtual bool AddColumn(const FITS::Compression&, uint32_t cnt, char typechar, const std::string& name, const std::string& unit,  const std::string& comment="", bool addHeaderKeys=true)
+    {
+        return AddColumn(cnt, typechar, name, unit, comment, addHeaderKeys);
+    }
+
+    bool AddColumnShort(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'I', name, unit, comment); }
+    bool AddColumnInt(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'J', name, unit, comment); }
+    bool AddColumnLong(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'K', name, unit, comment); }
+    bool AddColumnFloat(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'E', name, unit, comment); }
+    bool AddColumnDouble(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'D', name, unit, comment); }
+    bool AddColumnChar(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'A', name, unit, comment); }
+    bool AddColumnByte(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'B', name, unit, comment); }
+    bool AddColumnBool(uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(cnt, 'L', name, unit, comment); }
+
+    bool AddColumnShort(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'I', name, unit, comment); }
+    bool AddColumnInt(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'J', name, unit, comment); }
+    bool AddColumnLong(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'K', name, unit, comment); }
+    bool AddColumnFloat(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'E', name, unit, comment); }
+    bool AddColumnDouble(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'D', name, unit, comment); }
+    bool AddColumnChar(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'A', name, unit, comment); }
+    bool AddColumnByte(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'B', name, unit, comment); }
+    bool AddColumnBool(const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(1, 'L', name, unit, comment); }
+
+    bool AddColumnShort(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'I', name, unit, comment); }
+    bool AddColumnInt(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'J', name, unit, comment); }
+    bool AddColumnLong(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'K', name, unit, comment); }
+    bool AddColumnFloat(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'E', name, unit, comment); }
+    bool AddColumnDouble(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'D', name, unit, comment); }
+    bool AddColumnChar(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'A', name, unit, comment); }
+    bool AddColumnByte(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'B', name, unit, comment); }
+    bool AddColumnBool(const FITS::Compression &comp, uint32_t cnt, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, cnt, 'L', name, unit, comment); }
+
+    bool AddColumnShort(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'I', name, unit, comment); }
+    bool AddColumnInt(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'J', name, unit, comment); }
+    bool AddColumnLong(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'K', name, unit, comment); }
+    bool AddColumnFloat(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'E', name, unit, comment); }
+    bool AddColumnDouble(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'D', name, unit, comment); }
+    bool AddColumnChar(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'A', name, unit, comment); }
+    bool AddColumnByte(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'B', name, unit, comment); }
+    bool AddColumnBool(const FITS::Compression &comp, const std::string &name, const std::string &unit="", const std::string &comment="")
+    { return AddColumn(comp, 1, 'L', name, unit, comment); }
+
+    /*
+    bool AddKey(string key, double d, const std::string &comment)
+    {
+        ostringstream out;
+        out << d;
+
+        std::string s = out.str();
+
+        replace(s.begin(), s.end(), "e", "E");
+
+        return AddKey(key, s, comment);
+        }*/
+
+
+    Checksum WriteHeader(std::ostream &fout)
+    {
+        Checksum sum;
+        uint32_t count=0;
+        for (auto it=fKeys.begin(); it!=fKeys.end(); it++)
+        {
+            it->Out(fout);
+            sum += it->checksum;
+            count++;
+        }
+        fout.flush();
+
+        return sum;
+    }
+
+    Checksum WriteHeader()
+    {
+        return WriteHeader(*this);
+    }
+
+    void FlushHeader()
+    {
+        const off_t pos = tellp();
+        WriteHeader();
+        seekp(pos);
+    }
+
+    Checksum WriteFitsHeader()
+    {
+        ofits h;
+
+        h.SetBool("SIMPLE", true, "file does conform to FITS standard");
+        h.SetInt ("BITPIX",    8, "number of bits per data pixel");
+        h.SetInt ("NAXIS",     0, "number of data axes");
+        h.SetBool("EXTEND", true, "FITS dataset may contain extensions");
+        h.SetStr ("CHECKSUM","0000000000000000", "Checksum for the whole HDU");
+        h.SetStr ("DATASUM", "         0", "Checksum for the data block");
+        h.AddComment("FITS (Flexible Image Transport System) format is defined in 'Astronomy");
+        h.AddComment("and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H");
+        h.End();
+
+        const Checksum sum = h.WriteHeader(*this);
+
+        h.SetStr("CHECKSUM", sum.str());
+
+        const size_t offset = tellp();
+        h.WriteHeader(*this);
+        seekp(offset);
+
+        return sum;
+    }
+
+    virtual bool WriteDrsOffsetsTable ()
+    {
+        return true;
+    }
+
+    virtual bool WriteCatalog()
+    {
+        return true;
+    }
+
+    virtual bool WriteTableHeader(const char *name="DATA")
+    {
+        if (tellp()>0)
+        {
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("File not empty anymore.");
+#else
+            gLog << ___err___ << "ERROR - File not empty anymore." << std::endl;
+            return false;
+#endif
+        }
+
+        fHeaderSum = WriteFitsHeader();
+
+        WriteDrsOffsetsTable();
+
+        if (!fManualExtName)
+            SetStr("EXTNAME", name);
+        SetInt("NAXIS1",  fTable.bytes_per_row);
+        SetInt("TFIELDS", fTable.cols.size());
+
+        End();
+
+        WriteHeader();
+
+        WriteCatalog();
+
+        return good();
+    }
+
+    template<size_t N>
+        void revcpy(char *dest, const char *src, int num)
+    {
+        const char *pend = src + num*N;
+        for (const char *ptr = src; ptr<pend; ptr+=N, dest+=N)
+            std::reverse_copy(ptr, ptr+N, dest);
+    }
+
+    virtual uint32_t GetBytesPerRow() const { return fTable.bytes_per_row; }
+
+    virtual bool WriteRow(const void *ptr, size_t cnt, bool byte_swap=true)
+    {
+        // FIXME: Make sure that header was already written
+        //        or write header now!
+        if (cnt!=fTable.bytes_per_row)
+        {
+            std::ostringstream sout;
+            sout << "WriteRow - Size " << cnt << " does not match expected size " << fTable.bytes_per_row;
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        // For the checksum we need everything to be correctly aligned
+        const uint8_t offset = fTable.offset%4;
+
+        char *buffer = fOutputBuffer.data() + offset;
+
+        auto ib = fOutputBuffer.begin();
+        auto ie = fOutputBuffer.rbegin();
+        *ib++ = 0;
+        *ib++ = 0;
+        *ib++ = 0;
+        *ib   = 0;
+
+        *ie++ = 0;
+        *ie++ = 0;
+        *ie++ = 0;
+        *ie   = 0;
+
+        if (!byte_swap)
+            memcpy(buffer, ptr, cnt);
+        else
+        {
+            for (auto it=fTable.cols.cbegin(); it!=fTable.cols.cend(); it++)
+            {
+                const char *src  = reinterpret_cast<const char*>(ptr) + it->offset;
+                char       *dest = buffer + it->offset;
+
+                // Let the compiler do some optimization by
+                // knowing the we only have 1, 2, 4 and 8
+                switch (it->size)
+                {
+                case 1: memcpy   (dest, src, it->num*it->size); break;
+                case 2: revcpy<2>(dest, src, it->num);          break;
+                case 4: revcpy<4>(dest, src, it->num);          break;
+                case 8: revcpy<8>(dest, src, it->num);          break;
+                }
+            }
+        }
+
+        write(buffer, cnt);
+        fDataSum.add(fOutputBuffer);
+
+        fTable.num_rows++;
+        fTable.offset += cnt;
+        return good();
+    }
+
+    template<typename N>
+    bool WriteRow(const std::vector<N> &vec)
+    {
+        return WriteRow(vec.data(), vec.size()*sizeof(N));
+    }
+
+    // Flushes the number of rows to the header on disk
+    virtual void FlushNumRows()
+    {
+        SetInt("NAXIS2", fTable.num_rows);
+        FlushHeader();
+    }
+
+    size_t GetNumRows() const { return fTable.num_rows; }
+
+    void AlignTo2880Bytes()
+    {
+        if (tellp()%(80*36)>0)
+        {
+            std::vector<char> filler(80*36-tellp()%(80*36));
+            write(filler.data(), filler.size());
+        }
+    }
+
+    Checksum UpdateHeaderChecksum()
+    {
+        std::ostringstream dataSumStr;
+        dataSumStr << fDataSum.val();
+        SetStr("DATASUM", dataSumStr.str());
+
+        const Checksum sum = WriteHeader();
+
+        //sum += headersum;
+
+        SetStr("CHECKSUM", (sum+fDataSum).str());
+
+        return WriteHeader();
+    }
+    virtual bool close()
+    {
+        if (tellp()<0)
+            return false;
+
+        AlignTo2880Bytes();
+
+        // We don't have to jump back to the end of the file
+        SetInt("NAXIS2", fTable.num_rows);
+
+        const Checksum chk = UpdateHeaderChecksum();
+
+        if (!fFilebuf.close())
+            setstate(ios_base::failbit);
+
+        if ((chk+fDataSum).valid())
+            return true;
+
+        std::ostringstream sout;
+        sout << "Checksum (" << std::hex << chk.val() << ") invalid.";
+#ifdef __EXCEPTIONS
+        throw std::runtime_error(sout.str());
+#else
+        gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+        return false;
+#endif
+    }
+
+    std::pair<std::string, int> GetChecksumData()
+    {
+        std::string datasum;
+        std::string checksum;
+        //cannot directly use the Get methods, because they are only in fits.h
+        for (std::vector<Key>::const_iterator it=fKeys.cbegin(); it!= fKeys.cend(); it++)
+        {
+            if (it->key == "CHECKSUM") checksum = it->value;
+            if (it->key == "DATASUM") datasum = it->value;
+        }
+        if (checksum[0] == '\'')
+            checksum = checksum.substr(1,checksum.size()-2);
+        if (datasum[0] == '\'')
+            datasum = datasum.substr(1, datasum.size()-2);
+        return std::make_pair(checksum, atoi(datasum.c_str()));
+    }
+
+    void SetDefaultKeys()
+    {
+        SetStr("TELESCOP", "FACT", "Telescope that acquired this data");
+        SetStr("CREATOR", typeid(*this).name(), "Class that wrote this file");
+        SetFloat("EXTREL", 1.0, "Release Number");
+        SetStr("COMPILED", __DATE__" " __TIME__, "Compile time");
+        SetStr("ORIGIN", "FACT", "Institution that wrote the file");
+        SetStr("TIMESYS", "UTC", "Time system");
+        SetStr("TIMEUNIT", "d", "Time given in days w.r.t. to MJDREF");
+        SetInt("MJDREF", 40587, "MJD to UNIX time (seconds since 1970/1/1)");
+        SetStr("PACKAGE", PACKAGE_NAME, "Package name");
+        SetStr("VERSION", PACKAGE_VERSION, "Package description");
+        SetStr("REVISION", REVISION, "SVN revision");
+
+        const time_t t0 = time(NULL);
+        const struct tm *tmp1 = gmtime(&t0);
+
+        std::string str(19, '\0');
+        if (tmp1 && strftime(const_cast<char*>(str.data()), 20, "%Y-%m-%dT%H:%M:%S", tmp1))
+            SetStr("DATE", str, "File creation date");
+    }
+};
+
+#if 0
+#include "fits.h"
+
+int main()
+{
+    using namespace std;
+
+    ofits h2("delme.fits");
+
+    h2.SetInt("KEY1", 1, "comment 1");
+    h2.AddColumnInt(2, "testcol1", "counts", "My comment");
+    h2.AddColumnInt("testcol2", "counts", "My comment");
+    //h2.AddColumnInt("testcol2", "counts", "My comment");
+    h2.SetInt("KEY2", 2, "comment 2");
+
+    /*
+     AddFloat("X0",           0.000123456, "number of fields in each row");
+     AddFloat("X1",           0, "number of fields in each row");
+     AddFloat("X2",      12345, "number of fields in each row");
+     AddFloat("X3",      123456.67890, "number of fields in each row");
+     AddFloat("X4", 1234567890123456789.12345678901234567890, "number of fields in each row");
+     AddFloat("X5", 1234567890.1234567890e20, "number of fields in each row");
+     AddFloat("X6", 1234567890.1234567890e-20, "number of fields in each row");
+     AddFloat("XB", 1234567890.1234567890e-111, "number of fields in each row");
+     AddFloat("X7", 1e-5, "number of fields in each row");
+     AddFloat("X8", 1e-6, "number of fields in each row");
+     //AddStr("12345678", "123456789012345678", "12345678901234567890123456789012345678901234567");
+     */
+    // -
+
+    h2.WriteTableHeader("TABLE_NAME");
+
+    for (int i=0; i<10; i++)
+    {
+        int j[3] = { i+10, i*10, i*100 };
+        h2.WriteRow(j, 3*sizeof(i));
+    }
+
+    //h2.AddColumnInt("testcol2", "counts", "My comment");
+    //h2.SetInt("KEY3", 2, "comment 2");
+    h2.SetInt("KEY2", 2, "comment 2xxx");
+    h2.SetInt("KEY1", 11);
+
+    h2.close();
+
+    cout << "---" << endl;
+
+    fits f("delme.fits");
+    if (!f)
+        throw std::runtime_error("xxx");
+
+    cout << "Header is valid: " << f.IsHeaderOk() << endl;
+
+    while (f.GetNextRow());
+
+    cout << "File   is valid: " << f.IsFileOk() << endl;
+
+    cout << "---" << endl;
+
+    return 0;
+}
+#endif
+
+#endif
Index: branches/Mars_McMismatchStudy/mcore/zfits.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/zfits.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/zfits.h	(revision 17960)
@@ -0,0 +1,692 @@
+/*
+ * zfits.h
+ *
+ *  Created on: May 16, 2013
+ *      Author: lyard
+ */
+
+#ifndef MARS_zfits
+#define MARS_zfits
+
+#include "fits.h"
+#include "huffman.h"
+
+#include "FITS.h"
+
+class zfits : public fits
+{
+public:
+
+    // Basic constructor
+    zfits(const std::string& fname, const std::string& tableName="", bool force=false)
+        : fCatalogInitialized(false), fNumTiles(0), fNumRowsPerTile(0), fCurrentRow(-1), fHeapOff(0), fTileSize(0)
+    {
+        open(fname.c_str());
+        Constructor(fname, "", tableName, force);
+//        InitCompressionReading();
+    }
+
+    // Alternative constructor
+    zfits(const std::string& fname, const std::string& fout, const std::string& tableName, bool force=false)
+        : fCatalogInitialized(false), fNumTiles(0), fNumRowsPerTile(0), fCurrentRow(-1), fHeapOff(0), fTileSize(0)
+    {
+        open(fname.c_str());
+        Constructor(fname, fout, tableName, force);
+//        InitCompressionReading();
+    }
+
+    //  Skip the next row
+    bool SkipNextRow()
+    {
+        if (!fTable.is_compressed)
+            return fits::SkipNextRow();
+
+        fRow++;
+        return true;
+    }
+
+    virtual bool IsFileOk() const
+    {
+        if (!HasKey("RAWSUM"))
+            return fits::IsFileOk();
+
+        const bool rawsum = GetStr("RAWSUM") == std::to_string((long long int)fRawsum.val());
+        return fits::IsFileOk() && rawsum;
+    };
+
+    size_t GetNumRows() const
+    {
+        return fTable.Get<size_t>(fTable.is_compressed ? "ZNAXIS2" : "NAXIS2");
+    }
+
+    size_t GetBytesPerRow() const
+    {
+        return fTable.Get<size_t>(fTable.is_compressed ? "ZNAXIS1" : "NAXIS1");
+    }
+
+protected:
+
+    //  Stage the requested row to internal buffer
+    //  Does NOT return data to users
+    virtual void StageRow(size_t row, char* dest)
+    {
+        if (!fTable.is_compressed)
+        {
+            fits::StageRow(row, dest);
+            return;
+        }
+        ReadBinaryRow(row, dest);
+    }
+
+private:
+
+    // Do what it takes to initialize the compressed structured
+    void InitCompressionReading()
+    {
+        fCatalogInitialized = true;
+
+        if (!fTable.is_compressed)
+            return;
+
+        //The constructor may have failed
+        if (!good())
+            return;
+
+        if (fTable.is_compressed)
+            for (auto it=fTable.sorted_cols.cbegin(); it!= fTable.sorted_cols.cend(); it++)
+            {
+                if (it->comp == kCompFACT)
+                    continue;
+
+                clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("Only the FACT compression scheme is handled by this reader.");
+#else
+                gLog << ___err___ << "ERROR - Only the FACT compression scheme is handled by this reader." << std::endl;
+                return;
+#endif
+            }
+
+        fColumnOrdering.resize(fTable.sorted_cols.size(), FITS::kOrderByRow);
+
+        //Get compressed specific keywords
+        fNumTiles       = fTable.is_compressed ? GetInt("NAXIS2") : 0;
+        fNumRowsPerTile = fTable.is_compressed ? GetInt("ZTILELEN") : 0;
+
+        //read the file's catalog
+        ReadCatalog();
+
+        //give it some space for uncompressing
+        AllocateBuffers();
+    }
+
+    // Copy decompressed data to location requested by user
+    void MoveColumnDataToUserSpace(char* dest, const char* src, const Table::Column& c)
+    {
+        if (!fTable.is_compressed)
+        {
+            fits::MoveColumnDataToUserSpace(dest, src, c);
+            return;
+        }
+
+        memcpy(dest, src, c.num*c.size);
+    }
+
+    bool  fCatalogInitialized;
+
+    std::vector<char> fBuffer;           ///<store the uncompressed rows
+    std::vector<char> fTransposedBuffer; ///<intermediate buffer to transpose the rows
+    std::vector<char> fCompressedBuffer; ///<compressed rows
+    std::vector<char> fColumnOrdering;   ///< ordering of the column's rows. Can change from tile to tile.
+
+    size_t fNumTiles;       ///< Total number of tiles
+    size_t fNumRowsPerTile; ///< Number of rows per compressed tile
+    int64_t fCurrentRow;    ///< current row in memory signed because we need -1
+    size_t fShrinkFactor;   ///< shrink factor
+
+    streamoff fHeapOff;           ///< offset from the beginning of the file of the binary data
+    streamoff fHeapFromDataStart; ///< offset from the beginning of the data table
+
+    std::vector<std::vector<std::pair<int64_t, int64_t>>> fCatalog;     ///< Catalog, i.e. the main table that points to the compressed data.
+    std::vector<size_t>                                   fTileSize;    ///< size in bytes of each compressed tile
+    std::vector<std::vector<size_t>>                      fTileOffsets; ///< offset from start of tile of a given compressed column
+
+    Checksum fRawsum;   ///< Checksum of the uncompressed, raw data
+
+    // Get buffer space
+    void AllocateBuffers()
+    {
+        uint32_t buffer_size = fTable.bytes_per_row*fNumRowsPerTile;
+        uint32_t compressed_buffer_size = fTable.bytes_per_row*fNumRowsPerTile +
+            //use a bit more memory for block headers. 256 char coding the compression sequence max.
+            fTable.num_cols*(sizeof(FITS::BlockHeader)+256) +
+            //a bit more for the tile headers
+            sizeof(FITS::TileHeader) +
+            //and a bit more for checksuming
+            8;
+
+        if (buffer_size % 4 != 0)
+            buffer_size += 4 - (buffer_size%4);
+
+        if (compressed_buffer_size % 4 != 0)
+            compressed_buffer_size += 4 - (compressed_buffer_size%4);
+
+        fBuffer.resize(buffer_size);
+
+        fTransposedBuffer.resize(buffer_size);
+        fCompressedBuffer.resize(compressed_buffer_size);
+    }
+
+    // Read catalog data. I.e. the address of the compressed data inside the heap
+    void ReadCatalog()
+    {
+        std::vector<char> readBuf(16);
+        fCatalog.resize(fNumTiles);
+
+        const streampos catalogStart = tellg();
+
+        fChkData.reset();
+
+        //do the actual reading
+        for (uint32_t i=0;i<fNumTiles;i++)
+            for (uint32_t j=0;j<fTable.num_cols;j++)
+            {
+                read(readBuf.data(), 2*sizeof(int64_t));
+                fChkData.add(readBuf);
+                //swap the bytes
+                int64_t tempValues[2] = {0,0};
+                revcpy<8>(reinterpret_cast<char*>(tempValues), readBuf.data(), 2);
+                if (tempValues[0] < 0 || tempValues[1] < 0)
+                {
+                    clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error("Negative value in the catalog");
+#else
+                    gLog << ___err___ << "ERROR - negative value in the catalog" << std::endl;
+                    return;
+#endif
+                }
+                //add catalog entry
+                fCatalog[i].emplace_back(tempValues[0], tempValues[1]);
+            }
+
+        //see if there is a gap before heap data
+        fHeapOff = tellg()+fTable.GetHeapShift();
+        fHeapFromDataStart = fNumTiles*fTable.num_cols*2*sizeof(int64_t) + fTable.GetHeapShift();
+
+        //check if the catalog has been shrinked
+        fShrinkFactor = HasKey("ZSHRINK") ? GetUInt("ZSHRINK") : 1;
+
+        if (fNumRowsPerTile%fShrinkFactor)
+        {
+            clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+            throw std::runtime_error("Rows per tile and shrink factor do not match");
+#else
+            gLog << ___err___ << "ERROR - Rows per tile and shrink factor do not match" << std::endl;
+            return;
+#endif
+        }
+
+        if (fShrinkFactor>0)
+            fNumRowsPerTile /= fShrinkFactor;
+
+        //compute the total size of each compressed tile
+        fTileSize.resize(fNumTiles);
+        fTileOffsets.resize(fNumTiles);
+        for (uint32_t i=0;i<fNumTiles;i++)
+        {
+            fTileSize[i] = 0;
+            for (uint32_t j=0;j<fTable.num_cols;j++)
+            {
+                fTileSize[i] += fCatalog[i][j].first;
+                fTileOffsets[i].emplace_back(fCatalog[i][j].second - fCatalog[i][0].second);
+            }
+        }
+
+        if (!fCopy.is_open())
+            return;
+
+        //write catalog and heap gap to target file
+        seekg(catalogStart);
+
+        const size_t catSize = fTable.GetHeapShift() + fTable.total_bytes;
+
+        std::vector<char> buf(catSize);
+        read(buf.data(), catSize);
+
+        fCopy.write(buf.data(), catSize);
+        if (!fCopy)
+            clear(rdstate()|std::ios::badbit);
+    }
+
+    //overrides fits.h method with empty one
+    //work is done in ReadBinaryRow because it requires volatile data from ReadBinaryRow
+    virtual void WriteRowToCopyFile(size_t row)
+    {
+        if (row == fRow+1)
+            fRawsum.add(fBufferRow);
+    }
+
+    // Compressed version of the read row, even files with shrunk catalogs
+    // can be read fully sequentially so that streaming, e.g. through
+    // stdout/stdin, is possible.
+    bool ReadBinaryRow(const size_t &rowNum, char *bufferToRead)
+    {
+        if (rowNum >= GetNumRows())
+            return false;
+
+        if (!fCatalogInitialized)
+            InitCompressionReading();
+
+        // Book keeping, where are we?
+        const int64_t requestedTile      = rowNum        / fNumRowsPerTile;
+        const int64_t currentTile        = fCurrentRow   / fNumRowsPerTile;
+
+        const int64_t requestedSuperTile = requestedTile / fShrinkFactor;
+        //const int64_t currentSuperTile   = currentTile   / fShrinkFactor;
+
+        const int64_t requestedSubTile   = requestedTile % fShrinkFactor;
+        //const int64_t currentSubTile     = currentTile   % fShrinkFactor;
+
+        // Is this the first tile we read at all?
+        const bool isFirstTile = fCurrentRow<0;
+
+        // Is this just the next tile in the sequence?
+        const bool isNextTile = requestedTile==currentTile+1 || isFirstTile;
+
+        fCurrentRow = rowNum;
+
+        // Do we have to read a new tile from disk?
+        if (requestedTile!=currentTile || isFirstTile)
+        {
+            //skip to the beginning of the tile
+            const int64_t superTileStart = fCatalog[requestedSuperTile][0].second - sizeof(FITS::TileHeader);
+
+            std::vector<size_t> offsets = fTileOffsets[requestedSuperTile];
+
+            // If this is a sub tile we might have to step forward a bit and
+            // seek for the sub tile. If we were just reading the previous one
+            // we can skip that.
+            if (!isNextTile || isFirstTile)
+            {
+                // step to the beginnig of the super tile
+                seekg(fHeapOff+superTileStart);
+
+                // If there are sub tiles we might have to seek through the super tile
+                for (uint32_t k=0; k<requestedSubTile; k++)
+                {
+                    // Read header
+                    FITS::TileHeader header;
+                    read((char*)&header, sizeof(FITS::TileHeader));
+
+                    // Skip to the next header
+                    seekg(header.size-sizeof(FITS::TileHeader), cur);
+                }
+            }
+
+            // this is now the beginning of the sub-tile we want to read
+            const int64_t subTileStart = tellg() - fHeapOff;
+            // calculate the 32 bits offset of the current tile.
+            const uint32_t offset = (subTileStart + fHeapFromDataStart)%4;
+
+            // start of destination buffer (padding comes later)
+            char *destBuffer = fCompressedBuffer.data()+offset;
+
+            // Store the current tile size once known
+            size_t currentTileSize = 0;
+
+            // If this is a request for a sub tile which is not cataloged
+            // recalculate the offsets from the buffer, once read
+            if (requestedSubTile>0)
+            {
+                // Read header
+                read(destBuffer, sizeof(FITS::TileHeader));
+
+                // Get size of tile
+                currentTileSize = reinterpret_cast<FITS::TileHeader*>(destBuffer)->size;
+
+                // now read the remaining bytes of this tile
+                read(destBuffer+sizeof(FITS::TileHeader), currentTileSize-sizeof(FITS::TileHeader));
+
+                // Calculate the offsets recursively
+                offsets[0] = 0;
+
+                //skip through the columns
+                for (size_t i=0; i<fTable.num_cols-1; i++)
+                {
+                    //zero sized column do not have headers. Skip it
+                    if (fTable.sorted_cols[i].num == 0)
+                    {
+                        offsets[i+1] = offsets[i];
+                        continue;
+                    }
+
+                    const char *pos = destBuffer + offsets[i] + sizeof(FITS::TileHeader);
+                    offsets[i+1] = offsets[i] + reinterpret_cast<const FITS::BlockHeader*>(pos)->size;
+                }
+            }
+            else
+            {
+                // If we are reading the first tile of a super tile, all information
+                // is already available.
+                currentTileSize = fTileSize[requestedSuperTile] + sizeof(FITS::TileHeader);
+                read(destBuffer, currentTileSize);
+            }
+
+
+            // If we are reading sequentially, calcualte checksum
+            if (isNextTile)
+            {
+                // Padding for checksum calculation
+                memset(fCompressedBuffer.data(),   0, offset);
+                memset(destBuffer+currentTileSize, 0, fCompressedBuffer.size()-currentTileSize-offset);
+                fChkData.add(fCompressedBuffer);
+            }
+
+            // Check if we are writing a copy of the file
+            if (isNextTile && fCopy.is_open() && fCopy.good())
+            {
+                fCopy.write(fCompressedBuffer.data()+offset, currentTileSize);
+                if (!fCopy)
+                    clear(rdstate()|std::ios::badbit);
+            }
+            else
+                if (fCopy.is_open())
+                    clear(rdstate()|std::ios::badbit);
+
+
+            // uncompress  the buffer
+            const uint32_t thisRoundNumRows = (GetNumRows()<fCurrentRow + fNumRowsPerTile) ? GetNumRows()%fNumRowsPerTile : fNumRowsPerTile;
+            if (!UncompressBuffer(offsets, thisRoundNumRows, offset+sizeof(FITS::TileHeader)))
+                return false;
+
+            // pointer to column (source buffer)
+            const char *src = fTransposedBuffer.data();
+
+            uint32_t i=0;
+            for (auto it=fTable.sorted_cols.cbegin(); it!=fTable.sorted_cols.cend(); it++, i++)
+            {
+                char *buffer = fBuffer.data() + it->offset; // pointer to column (destination buffer)
+
+                switch (fColumnOrdering[i])
+                {
+                case FITS::kOrderByRow:
+                    // regular, "semi-transposed" copy
+                    for (char *dest=buffer; dest<buffer+thisRoundNumRows*fTable.bytes_per_row; dest+=fTable.bytes_per_row) // row-by-row
+                    {
+                        memcpy(dest, src, it->bytes);
+                        src += it->bytes;  // next column
+                    }
+                    break;
+
+                case FITS::kOrderByCol:
+                    // transposed copy
+                    for (char *elem=buffer; elem<buffer+it->bytes; elem+=it->size) // element-by-element (arrays)
+                    {
+                        for (char *dest=elem; dest<elem+thisRoundNumRows*fTable.bytes_per_row; dest+=fTable.bytes_per_row) // row-by-row
+                        {
+                                memcpy(dest, src, it->size);
+                                src += it->size; // next element
+                        }
+                    }
+                    break;
+
+                default:
+                    clear(rdstate()|std::ios::badbit);
+
+                    std::ostringstream str;
+                    str << "Unkown column ordering scheme found (i=" << i << ", " << fColumnOrdering[i] << ")";
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error(str.str());
+#else
+                    gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                    return false;
+#endif
+                };
+            }
+        }
+
+        //Data loaded and uncompressed. Copy it to destination
+        memcpy(bufferToRead, fBuffer.data()+fTable.bytes_per_row*(fCurrentRow%fNumRowsPerTile), fTable.bytes_per_row);
+        return good();
+    }
+
+    // Read a bunch of uncompressed data
+    uint32_t UncompressUNCOMPRESSED(char*       dest,
+                                    const char* src,
+                                    uint32_t    numElems,
+                                    uint32_t    sizeOfElems)
+    {
+        memcpy(dest, src, numElems*sizeOfElems);
+        return numElems*sizeOfElems;
+    }
+
+    // Read a bunch of data compressed with the Huffman algorithm
+    uint32_t UncompressHUFFMAN16(char*       dest,
+                                 const char* src,
+                                 uint32_t    numChunks)
+    {
+        std::vector<uint16_t> uncompressed;
+
+        //read compressed sizes (one per row)
+        const uint32_t* compressedSizes = reinterpret_cast<const uint32_t*>(src);
+        src += sizeof(uint32_t)*numChunks;
+
+        //uncompress the rows, one by one
+        uint32_t sizeWritten = 0;
+        for (uint32_t j=0;j<numChunks;j++)
+        {
+            Huffman::Decode(reinterpret_cast<const unsigned char*>(src), compressedSizes[j], uncompressed);
+
+            memcpy(dest, uncompressed.data(), uncompressed.size()*sizeof(uint16_t));
+
+            sizeWritten += uncompressed.size()*sizeof(uint16_t);
+            dest        += uncompressed.size()*sizeof(uint16_t);
+            src         += compressedSizes[j];
+        }
+        return sizeWritten;
+    }
+
+    // Apply the inverse transform of the integer smoothing
+    uint32_t UnApplySMOOTHING(int16_t*   data,
+                              uint32_t   numElems)
+    {
+        //un-do the integer smoothing
+        for (uint32_t j=2;j<numElems;j++)
+            data[j] = data[j] + (data[j-1]+data[j-2])/2;
+
+        return numElems*sizeof(uint16_t);
+    }
+
+    // Data has been read from disk. Uncompress it !
+    bool UncompressBuffer(const std::vector<size_t> &offsets,
+                          const uint32_t &thisRoundNumRows,
+                          const uint32_t offset)
+    {
+        char *dest = fTransposedBuffer.data();
+
+        //uncompress column by column
+        for (uint32_t i=0; i<fTable.sorted_cols.size(); i++)
+        {
+            const fits::Table::Column &col = fTable.sorted_cols[i];
+            if (col.num == 0)
+                continue;
+
+            //get the compression flag
+            const int64_t compressedOffset = offsets[i]+offset;
+
+            const FITS::BlockHeader* head = reinterpret_cast<FITS::BlockHeader*>(&fCompressedBuffer[compressedOffset]);
+
+            fColumnOrdering[i] = head->ordering;
+
+            const uint32_t numRows = (head->ordering==FITS::kOrderByRow) ? thisRoundNumRows : col.num;
+            const uint32_t numCols = (head->ordering==FITS::kOrderByCol) ? thisRoundNumRows : col.num;
+
+            const char *src = fCompressedBuffer.data()+compressedOffset+sizeof(FITS::BlockHeader)+sizeof(uint16_t)*head->numProcs;
+
+            for (int32_t j=head->numProcs-1;j >= 0; j--)
+            {
+                uint32_t sizeWritten=0;
+
+                switch (head->processings[j])
+                {
+                case FITS::kFactRaw:
+                    sizeWritten = UncompressUNCOMPRESSED(dest, src, numRows*numCols, col.size);
+                    break;
+
+                case FITS::kFactSmoothing:
+                    sizeWritten = UnApplySMOOTHING(reinterpret_cast<int16_t*>(dest), numRows*numCols);
+                    break;
+
+                case FITS::kFactHuffman16:
+                    sizeWritten = UncompressHUFFMAN16(dest, src, numRows);
+                    break;
+
+                default:
+                    clear(rdstate()|std::ios::badbit);
+
+                    std::ostringstream str;
+                    str << "Unknown processing applied to data (col=" << i << ", proc=" << j << "/" << (int)head->numProcs;
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error(str.str());
+#else
+                    gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                    return false;
+#endif
+                }
+                //increment destination counter only when processing done.
+                if (j==0)
+                    dest+= sizeWritten;
+            }
+        }
+
+        return true;
+    }
+
+    void CheckIfFileIsConsistent(bool update_catalog=false)
+    {
+        //goto start of heap
+        const streamoff whereAreWe = tellg();
+        seekg(fHeapOff);
+
+        //init number of rows to zero
+        uint64_t numRows = 0;
+
+        //get number of columns from header
+        const size_t numCols = fTable.num_cols;
+
+        std::vector<std::vector<std::pair<int64_t, int64_t> > > catalog;
+
+        FITS::TileHeader tileHead;
+        FITS::BlockHeader columnHead;
+
+        streamoff offsetInHeap = 0;
+        //skip through the heap
+        while (true)
+        {
+            read((char*)(&tileHead), sizeof(FITS::TileHeader));
+            //end of file
+            if (!good())
+                break;
+
+            //padding or corrupt data
+            if (memcmp(tileHead.id, "TILE", 4))
+            {
+                clear(rdstate()|std::ios::badbit);
+                break;
+            }
+
+            //a new tile begins here
+            catalog.emplace_back();
+            offsetInHeap += sizeof(FITS::TileHeader);
+
+            //skip through the columns
+            for (size_t i=0;i<numCols;i++)
+            {
+                //zero sized column do not have headers. Skip it
+                if (fTable.sorted_cols[i].num == 0)
+                {
+                    catalog.back().emplace_back(0,0);
+                    continue;
+                }
+
+                //read column header
+                read((char*)(&columnHead), sizeof(FITS::BlockHeader));
+
+                //corrupted tile
+                if (!good())
+                    break;
+
+                catalog.back().emplace_back((int64_t)(columnHead.size),offsetInHeap);
+                offsetInHeap += columnHead.size;
+                seekg(fHeapOff+offsetInHeap);
+            }
+
+            //if we ain't good, this means that something went wrong inside the current tile.
+            if (!good())
+            {
+                catalog.pop_back();
+                break;
+            }
+            //current tile is complete. Add rows
+            numRows += tileHead.numRows;
+        }
+
+        if (numRows != fTable.num_rows)
+        {
+            clear(rdstate()|std::ios::badbit);
+            std::ostringstream str;
+            str << "Heap data does not agree with header: " << numRows << " calculated vs " << fTable.num_rows << " from header.";
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error(str.str());
+#else
+                    gLog << ___err___ << "ERROR - " << str.str() << std::endl;
+                    return;
+#endif
+        }
+
+        if (update_catalog)
+        {
+            fCatalog = catalog;
+            //clear the bad bit before seeking back (we hit eof)
+            clear();
+            seekg(whereAreWe);
+            return;
+        }
+
+        if (catalog.size() != fCatalog.size())
+        {
+                    clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error("Heap data does not agree with header.");
+#else
+                    gLog << ___err___ << "ERROR - Heap data does not agree with header." << std::endl;
+                    return;
+#endif
+        }
+
+        for (uint32_t i=0;i<catalog.size(); i++)
+            for (uint32_t j=0;j<numCols;j++)
+            {
+                if (catalog[i][j].first  != fCatalog[i][j].first ||
+                    catalog[i][j].second != fCatalog[i][j].second)
+                {
+                    clear(rdstate()|std::ios::badbit);
+#ifdef __EXCEPTIONS
+                    throw std::runtime_error("Heap data does not agree with header.");
+#else
+                    gLog << ___err___ << "ERROR - Heap data does not agree with header." << std::endl;
+                    return;
+#endif
+                }
+            }
+        //go back to start of heap
+        //clear the bad bit before seeking back (we hit eof)
+        clear();
+        seekg(whereAreWe);
+    }
+
+};//class zfits
+
+#endif 
Index: branches/Mars_McMismatchStudy/mcore/zofits.h
===================================================================
--- branches/Mars_McMismatchStudy/mcore/zofits.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcore/zofits.h	(revision 17960)
@@ -0,0 +1,1010 @@
+#ifndef FACT_zofits
+#define FACT_zofits
+
+/*
+ * zofits.h
+ *
+ *  FACT native compressed FITS writer
+ *      Author: lyard
+ */
+#include "ofits.h"
+#include "huffman.h"
+#include "Queue.h"
+#include "MemoryManager.h"
+
+#ifdef HAVE_BOOST_THREAD
+#include <boost/thread.hpp>
+#else
+#include <unistd.h>
+#endif
+
+#if defined(__CINT__) || !defined(__EXCEPTIONS)
+namespace std
+{
+    typedef void* exception_ptr;
+};
+#endif
+
+class zofits : public ofits
+{
+#ifdef __MARS__ // Needed by CINT to access the structures
+public:
+#endif
+        /// Overriding of the begin() operator to get the smallest item in the list instead of the true begin
+        template<class S>
+        struct QueueMin : std::list<S>
+        {
+            typename std::list<S>::iterator begin()
+            {
+                return min_element(std::list<S>::begin(), std::list<S>::end());
+            }
+        };
+
+#ifdef __CINT__
+        // CINT doesn't like the packed attribute...
+        // Therefore we give another hint of the size of the structure
+        struct CatalogEntry { char dummy[16]; };
+#else
+        //catalog types
+        struct CatalogEntry
+        {
+            CatalogEntry(int64_t f=0, int64_t s=0) : first(f), second(s) { }
+            int64_t first;   ///< Size of this column in the tile
+            int64_t second;  ///< offset of this column in the tile, from the start of the heap area
+        } __attribute__((__packed__));
+#endif
+
+        typedef std::vector<CatalogEntry> CatalogRow;
+        typedef std::list<CatalogRow>     CatalogType;
+
+        /// Parameters required to write a tile to disk
+        struct WriteTarget
+        {
+            bool operator < (const WriteTarget& other) const
+            {
+                return tile_num < other.tile_num;
+            }
+
+            WriteTarget() { }
+            WriteTarget(const WriteTarget &t, uint32_t sz) : tile_num(t.tile_num), size(sz), data(t.data) { }
+
+            uint32_t              tile_num; ///< Tile index of the data (to make sure that they are written in the correct order)
+            uint32_t              size;     ///< Size to write
+            std::shared_ptr<char> data;     ///< Memory block to write
+        };
+
+
+        /// Parameters required to compress a tile of data
+        struct CompressionTarget
+        {
+            CompressionTarget(CatalogRow& r) : catalog_entry(r)
+            {}
+
+            CatalogRow&           catalog_entry;   ///< Reference to the catalog entry to deal with
+            std::shared_ptr<char> src;             ///< Original data
+            std::shared_ptr<char> transposed_src;  ///< Transposed data
+            WriteTarget           target;          ///< Compressed data
+            uint32_t              num_rows;        ///< Number of rows to compress
+         };
+
+public:
+        /// static setter for the default number of threads to use. -1 means all available physical cores
+        static uint32_t DefaultNumThreads(const uint32_t &_n=-2) { static uint32_t n=0; if (int32_t(_n)>-2) n=_n; return n; }
+        static uint32_t DefaultMaxMemory(const uint32_t &_n=0) { static uint32_t n=1000000; if (_n>0) n=_n; return n; }
+        static uint32_t DefaultMaxNumTiles(const uint32_t &_n=0) { static uint32_t n=1000; if (_n>0) n=_n; return n; }
+        static uint32_t DefaultNumRowsPerTile(const uint32_t &_n=0) { static uint32_t n=100; if (_n>0) n=_n; return n; }
+
+        /// constructors
+        /// @param numTiles how many data groups should be pre-reserved ?
+        /// @param rowPerTile how many rows will be grouped together in a single tile
+        /// @param maxUsableMem how many bytes of memory can be used by the compression buffers
+        zofits(uint32_t numTiles    = DefaultMaxNumTiles(),
+               uint32_t rowPerTile  = DefaultNumRowsPerTile(),
+               uint32_t maxUsableMem= DefaultMaxMemory()) : ofits(),
+            fMemPool(0, size_t(maxUsableMem)*1000),
+            fWriteToDiskQueue(std::bind(&zofits::WriteBufferToDisk, this, std::placeholders::_1), false)
+        {
+            InitMemberVariables(numTiles, rowPerTile, size_t(maxUsableMem)*1000);
+            SetNumThreads(DefaultNumThreads());
+        }
+
+        /// @param fname the target filename
+        /// @param numTiles how many data groups should be pre-reserved ?
+        /// @param rowPerTile how many rows will be grouped together in a single tile
+        /// @param maxUsableMem how many bytes of memory can be used by the compression buffers
+        zofits(const char* fname,
+               uint32_t numTiles    = DefaultMaxNumTiles(),
+               uint32_t rowPerTile  = DefaultNumRowsPerTile(),
+               uint32_t maxUsableMem= DefaultMaxMemory()) : ofits(),
+            fMemPool(0, size_t(maxUsableMem)*1000),
+            fWriteToDiskQueue(std::bind(&zofits::WriteBufferToDisk, this, std::placeholders::_1), false)
+        {
+            InitMemberVariables(numTiles, rowPerTile, size_t(maxUsableMem)*1000);
+            SetNumThreads(DefaultNumThreads());
+            open(fname);
+        }
+
+        zofits(const std::string &fname,
+               uint32_t numTiles    = DefaultMaxNumTiles(),
+               uint32_t rowPerTile  = DefaultNumRowsPerTile(),
+               uint32_t maxUsableMem= DefaultMaxMemory()) : ofits(),
+            fMemPool(0, size_t(maxUsableMem)*1000),
+            fWriteToDiskQueue(std::bind(&zofits::WriteBufferToDisk, this, std::placeholders::_1), false)
+        {
+            InitMemberVariables(numTiles, rowPerTile, size_t(maxUsableMem)*1000);
+            SetNumThreads(DefaultNumThreads());
+            open(fname);
+        }
+
+        //initialization of member variables
+        /// @param nt number of tiles
+        /// @param rpt number of rows per tile
+        /// @param maxUsableMem max amount of RAM to be used by the compression buffers
+        void InitMemberVariables(const uint32_t nt=0, const uint32_t rpt=0, const uint64_t maxUsableMem=0)
+        {
+            fCheckOffset = 0;
+            fNumQueues   = 0;
+
+            fNumTiles       = nt==0 ? 1 : nt;
+            fNumRowsPerTile = rpt;
+
+            fRealRowWidth     = 0;
+            fCatalogOffset    = 0;
+            fCatalogSize      = 0;
+
+            fMaxUsableMem = maxUsableMem;
+#ifdef __EXCEPTIONS
+            fThreadsException = std::exception_ptr();
+#endif
+            fErrno = 0;
+        }
+
+        /// write the header of the binary table
+        /// @param name the name of the table to be created
+        /// @return the state of the file
+        virtual bool WriteTableHeader(const char* name="DATA")
+        {
+            reallocateBuffers();
+
+            SetInt("ZNAXIS1", fRealRowWidth);
+
+            ofits::WriteTableHeader(name);
+
+            fCompressionQueues.front().setPromptExecution(fNumQueues==0);
+            fWriteToDiskQueue.setPromptExecution(fNumQueues==0);
+
+            if (fNumQueues != 0)
+            {
+                //start the compression queues
+                for (auto it=fCompressionQueues.begin(); it!= fCompressionQueues.end(); it++)
+                    it->start();
+
+                //start the disk writer
+                fWriteToDiskQueue.start();
+            }
+
+            //mark that no tile has been written so far
+            fLatestWrittenTile = -1;
+
+            //no wiring error (in the writing of the data) has occured so far
+            fErrno = 0;
+
+            return good();
+        }
+
+        /// open a new file.
+        /// @param filename the name of the file
+        /// @param Whether or not the name of the extension should be added or not
+        void open(const char* filename, bool addEXTNAMEKey=true)
+        {
+            ofits::open(filename, addEXTNAMEKey);
+
+            //add compression-related header entries
+            SetBool( "ZTABLE",   true,            "Table is compressed");
+            SetInt(  "ZNAXIS1",  0,               "Width of uncompressed rows");
+            SetInt(  "ZNAXIS2",  0,               "Number of uncompressed rows");
+            SetInt(  "ZPCOUNT",  0,               "");
+            SetInt(  "ZHEAPPTR", 0,               "");
+            SetInt(  "ZTILELEN", fNumRowsPerTile, "Number of rows per tile");
+            SetInt(  "THEAP",    0,               "");
+            SetStr(  "RAWSUM",   "         0",    "Checksum of raw little endian data");
+            SetFloat("ZRATIO",   0,               "Compression ratio");
+            SetInt(  "ZSHRINK",  1,               "Catalog shrink factor");
+
+            fCatalogSize   = 0;
+            fRealRowWidth  = 0;
+            fCatalogOffset = 0;
+            fCatalogSize   = 0;
+            fCheckOffset   = 0;
+
+            fRealColumns.clear();
+            fCatalog.clear();
+            fCatalogSum.reset();
+            fRawSum.reset();
+        }
+
+        void open(const std::string &filename, bool addEXTNAMEKey=true)
+        {
+            open(filename.c_str(), addEXTNAMEKey);
+        }
+
+        /// Super method. does nothing as zofits does not know about DrsOffsets
+        /// @return the state of the file
+        virtual bool WriteDrsOffsetsTable()
+        {
+            return good();
+        }
+
+        /// Returns the number of bytes per uncompressed row
+        /// @return number of bytes per uncompressed row
+        uint32_t GetBytesPerRow() const
+        {
+            return fRealRowWidth;
+        }
+
+        /// Write the data catalog
+        /// @return the state of the file
+        bool WriteCatalog()
+        {
+            const uint32_t one_catalog_row_size = fTable.num_cols*2*sizeof(uint64_t);
+            const uint32_t total_catalog_size   = fNumTiles*one_catalog_row_size;
+
+            // swap the catalog bytes before writing
+            std::vector<char> swapped_catalog(total_catalog_size);
+
+            uint32_t shift = 0;
+            for (auto it=fCatalog.cbegin(); it!=fCatalog.cend(); it++)
+            {
+                revcpy<sizeof(uint64_t)>(swapped_catalog.data() + shift, (char*)(it->data()), fTable.num_cols*2);
+                shift += one_catalog_row_size;
+            }
+
+            if (fCatalogSize < fNumTiles)
+                memset(swapped_catalog.data()+shift, 0, total_catalog_size-shift);
+
+            // first time writing ? remember where we are
+            if (fCatalogOffset == 0)
+                fCatalogOffset = tellp();
+
+            // remember where we came from
+            const off_t where_are_we = tellp();
+
+            // write to disk
+            seekp(fCatalogOffset);
+            write(swapped_catalog.data(), total_catalog_size);
+
+            if (where_are_we != fCatalogOffset)
+                seekp(where_are_we);
+
+            // udpate checksum
+            fCatalogSum.reset();
+            fCatalogSum.add(swapped_catalog.data(), total_catalog_size);
+
+            return good();
+        }
+
+        /// Applies the DrsOffsets calibration to the data. Does nothing as zofits knows nothing about drsoffsets.
+        virtual void DrsOffsetCalibrate(char* )
+        {
+
+        }
+
+        CatalogRow& AddOneCatalogRow()
+        {
+            // add one row to the catalog
+            fCatalog.emplace_back(CatalogRow());
+            fCatalog.back().resize(fTable.num_cols);
+            for (auto it=fCatalog.back().begin(); it != fCatalog.back().end(); it++)
+                *it = CatalogEntry(0,0);
+
+            fCatalogSize++;
+
+            return fCatalog.back();
+        }
+
+        /// write one row of data
+        /// Note, in a multi-threaded environment (NumThreads>0), the return code should be checked rather
+        /// than the badbit() of the stream (it might have been set by a thread before the errno has been set)
+        /// errno will then contain the correct error number of the last error which happened during writing.
+        /// @param ptr the source buffer
+        /// @param the number of bytes to write
+        /// @return the state of the file. WARNING: with multithreading, this will most likely be the state of the file before the data is actually written
+        bool WriteRow(const void* ptr, size_t cnt, bool = true)
+        {
+            if (cnt != fRealRowWidth)
+            {
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("Wrong size of row given to WriteRow");
+#else
+                gLog << ___err___ << "ERROR - Wrong size of row given to WriteRow" << std::endl;
+                return false;
+#endif
+            }
+
+#ifdef __EXCEPTIONS
+            //check if something hapenned while the compression threads were working
+            //if so, re-throw the exception that was generated
+            if (fThreadsException != std::exception_ptr())
+                std::rethrow_exception(fThreadsException);
+#endif
+
+            //copy current row to pool or rows waiting for compression
+            char* target_location = fSmartBuffer.get() + fRealRowWidth*(fTable.num_rows%fNumRowsPerTile);
+            memcpy(target_location, ptr, fRealRowWidth);
+
+            //for now, make an extra copy of the data, for RAWSUM checksuming.
+            //Ideally this should be moved to the threads
+            //However, because the RAWSUM must be calculated before the tile is transposed, I am not sure whether
+            //one extra memcpy per row written is worse than 100 rows checksumed when the tile is full....
+            const uint32_t rawOffset = (fTable.num_rows*fRealRowWidth)%4;
+            char* buffer = fRawSumBuffer.data() + rawOffset;
+            auto ib = fRawSumBuffer.begin();
+            auto ie = fRawSumBuffer.rbegin();
+            *ib++ = 0;
+            *ib++ = 0;
+            *ib++ = 0;
+            *ib   = 0;
+
+            *ie++ = 0;
+            *ie++ = 0;
+            *ie++ = 0;
+            *ie   = 0;
+
+            memcpy(buffer, ptr, fRealRowWidth);
+
+            fRawSum.add(fRawSumBuffer, false);
+
+            fTable.num_rows++;
+
+            if (fTable.num_rows % fNumRowsPerTile != 0)
+            {
+                errno = fErrno;
+                return errno==0;
+            }
+
+            // use the least occupied queue
+            const auto imin = std::min_element(fCompressionQueues.begin(), fCompressionQueues.end());
+
+            if (!imin->emplace(InitNextCompression()))
+            {
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("The compression queues are not started. Did you close the file before writing this row?");
+#else
+                gLog << ___err___ << "The compression queues are not started. Did you close the file before writing this row?" << std::endl;
+                errno = 0;
+                return false;
+#endif
+            }
+
+            errno = fErrno;
+            return errno==0;
+        }
+
+        /// update the real number of rows
+        void FlushNumRows()
+        {
+            SetInt("NAXIS2", (fTable.num_rows + fNumRowsPerTile-1)/fNumRowsPerTile);
+            SetInt("ZNAXIS2", fTable.num_rows);
+            FlushHeader();
+        }
+
+        /// Setup the environment to compress yet another tile of data
+        /// @param target the struct where to host the produced parameters
+        CompressionTarget InitNextCompression()
+        {
+            CompressionTarget target(AddOneCatalogRow());
+
+            //fill up compression target
+            target.src            = fSmartBuffer;
+            target.transposed_src = fMemPool.malloc();
+            target.num_rows       = fTable.num_rows;
+
+            //fill up write to disk target
+            WriteTarget &write_target = target.target;
+            write_target.tile_num = (fTable.num_rows-1)/fNumRowsPerTile;
+            write_target.size     = 0;
+            write_target.data     = fMemPool.malloc();
+
+            //get a new buffer to host the incoming data
+            fSmartBuffer = fMemPool.malloc();
+
+            return target;
+        }
+
+        /// Shrinks a catalog that is too long to fit into the reserved space at the beginning of the file.
+        uint32_t ShrinkCatalog()
+        {
+            //add empty row to get either the target number of rows, or a multiple of the allowed size
+            for (uint32_t i=0;i<fCatalogSize%fNumTiles;i++)
+                AddOneCatalogRow();
+
+            //did we write more rows than what the catalog could host ?
+            if (fCatalogSize <= fNumTiles) // nothing to do
+                return 1;
+
+            //always exact as extra rows were added just above
+            const uint32_t shrink_factor = fCatalogSize / fNumTiles; 
+
+            //shrink the catalog !
+            uint32_t entry_id = 1;
+            auto it = fCatalog.begin();
+            it++;
+            for (; it != fCatalog.end(); it++)
+            {
+                if (entry_id >= fNumTiles)
+                    break;
+
+                const uint32_t target_id = entry_id*shrink_factor;
+
+                auto jt = it;
+                for (uint32_t i=0; i<target_id-entry_id; i++)
+                    jt++;
+
+                *it = *jt;
+
+                entry_id++;
+            }
+
+            const uint32_t num_tiles_to_remove = fCatalogSize-fNumTiles;
+
+            //remove the too many entries
+            for (uint32_t i=0;i<num_tiles_to_remove;i++)
+            {
+                fCatalog.pop_back();
+                fCatalogSize--;
+            }
+
+            //update header keywords
+            fNumRowsPerTile *= shrink_factor;
+
+            SetInt("ZTILELEN", fNumRowsPerTile);
+            SetInt("ZSHRINK",  shrink_factor);
+
+            return shrink_factor;
+        }
+
+        /// close an open file.
+        /// @return the state of the file
+        bool close()
+        {
+            // stop compression and write threads
+            for (auto it=fCompressionQueues.begin(); it != fCompressionQueues.end(); it++)
+                it->wait();
+
+            fWriteToDiskQueue.wait();
+
+            if (tellp() < 0)
+                return false;
+
+#ifdef __EXCEPTIONS
+            //check if something hapenned while the compression threads were working
+            //if so, re-throw the exception that was generated
+            if (fThreadsException != std::exception_ptr())
+                std::rethrow_exception(fThreadsException);
+#endif
+
+            //write the last tile of data (if any)
+            if (fErrno==0 && fTable.num_rows%fNumRowsPerTile!=0)
+            {
+                fWriteToDiskQueue.enablePromptExecution();
+                fCompressionQueues.front().enablePromptExecution();
+                fCompressionQueues.front().emplace(InitNextCompression());
+            }
+
+            AlignTo2880Bytes();
+
+            int64_t heap_size = 0;
+            int64_t compressed_offset = 0;
+            for (auto it=fCatalog.begin(); it!= fCatalog.end(); it++)
+            {
+                compressed_offset += sizeof(FITS::TileHeader);
+                heap_size         += sizeof(FITS::TileHeader);
+                for (uint32_t j=0; j<it->size(); j++)
+                {
+                    heap_size += (*it)[j].first;
+                    (*it)[j].second = compressed_offset;
+                    compressed_offset += (*it)[j].first;
+                    if ((*it)[j].first == 0)
+                        (*it)[j].second = 0;
+                }
+            }
+
+            const uint32_t shrink_factor = ShrinkCatalog();
+
+            //update header keywords
+            SetInt("ZNAXIS1", fRealRowWidth);
+            SetInt("ZNAXIS2", fTable.num_rows);
+
+            SetInt("ZHEAPPTR", fCatalogSize*fTable.num_cols*sizeof(uint64_t)*2);
+
+            const uint32_t total_num_tiles_written = (fTable.num_rows + fNumRowsPerTile-1)/fNumRowsPerTile;
+            const uint32_t total_catalog_width     = 2*sizeof(int64_t)*fTable.num_cols;
+
+            SetInt("THEAP",  total_num_tiles_written*total_catalog_width);
+            SetInt("NAXIS1", total_catalog_width);
+            SetInt("NAXIS2", total_num_tiles_written);
+            SetStr("RAWSUM", std::to_string((long long int)(fRawSum.val())));
+
+            const float compression_ratio = (float)(fRealRowWidth*fTable.num_rows)/(float)heap_size;
+            SetFloat("ZRATIO", compression_ratio);
+
+            //add to the heap size the size of the gap between the catalog and the actual heap
+            heap_size += (fCatalogSize - total_num_tiles_written)*fTable.num_cols*sizeof(uint64_t)*2;
+
+            SetInt("PCOUNT", heap_size, "size of special data area");
+
+            //Just for updating the fCatalogSum value
+            WriteCatalog();
+
+            fDataSum += fCatalogSum;
+
+            const Checksum checksm = UpdateHeaderChecksum();
+
+            if (!fFilebuf.close())
+                setstate(ios_base::failbit);
+
+            fSmartBuffer = std::shared_ptr<char>();
+
+            //restore the number of rows per tile in case the catalog has been shrinked
+            if (shrink_factor != 1)
+                fNumRowsPerTile /= shrink_factor;
+
+            if ((checksm+fDataSum).valid())
+                return true;
+
+            std::ostringstream sout;
+            sout << "Checksum (" << std::hex << checksm.val() << ") invalid.";
+#ifdef __EXCEPTIONS
+            throw std::runtime_error(sout.str());
+#else
+            gLog << ___err___ << "ERROR - " << sout.str() << std::endl;
+            return false;
+#endif
+        }
+
+        /// Overload of the ofits method. Just calls the zofits specific one with default, uncompressed options for this column
+        bool AddColumn(uint32_t cnt, char typechar, const std::string& name, const std::string& unit,
+                       const std::string& comment="", bool addHeaderKeys=true)
+        {
+            return AddColumn(FITS::kFactRaw, cnt, typechar, name, unit, comment, addHeaderKeys);
+        }
+
+        /// Overload of the simplified compressed version
+        bool AddColumn(const FITS::Compression &comp, uint32_t cnt, char typechar, const std::string& name,
+                       const std::string& unit, const std::string& comment="", bool addHeaderKeys=true)
+        {
+            if (!ofits::AddColumn(1, 'Q', name, unit, comment, addHeaderKeys))
+                return false;
+
+            const size_t size = FITS::SizeFromType(typechar);
+
+            Table::Column col;
+            col.name   = name;
+            col.type   = typechar;
+            col.num    = cnt;
+            col.size   = size;
+            col.offset = fRealRowWidth;
+
+            fRealRowWidth += size*cnt;
+
+            fRealColumns.emplace_back(col, comp);
+
+            SetStr("ZFORM"+std::to_string((long long int)(fRealColumns.size())), std::to_string((long long int)(cnt))+typechar, "format of "+name+" "+FITS::CommentFromType(typechar));
+            SetStr("ZCTYP"+std::to_string((long long int)(fRealColumns.size())), "FACT", "Compression type: FACT");
+
+            return true;
+        }
+
+        /// Get and set the actual number of threads for this object
+        int32_t GetNumThreads() const { return fNumQueues; }
+        bool SetNumThreads(uint32_t num)
+        {
+            if (tellp()>0)
+            {
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("Number of threads cannot be changed in the middle of writing a file");
+#else
+                gLog << ___err___ << "ERROR - Number of threads cannot be changed in the middle of writing a file" << std::endl;
+#endif
+                return false;
+            }
+
+            //get number of physically available threads
+#ifdef HAVE_BOOST_THREAD
+            unsigned int num_available_cores = boost::thread::hardware_concurrency();
+#else
+            unsigned int num_available_cores = std::thread::hardware_concurrency();
+            if (num_available_cores == 0)
+                num_available_cores = sysconf(_SC_NPROCESSORS_ONLN);
+#endif
+            // could not detect number of available cores from system properties...
+            if (num_available_cores == 0)
+                num_available_cores = 1;
+
+            // leave one core for the main thread and one for the writing
+            if (num > num_available_cores)
+                num = num_available_cores>2 ? num_available_cores-2 : 1;
+
+            fCompressionQueues.resize(num<1?1:num, Queue<CompressionTarget>(std::bind(&zofits::CompressBuffer, this, std::placeholders::_1), false));
+            fNumQueues = num;
+
+            return true;
+        }
+
+        uint32_t GetNumTiles() const { return fNumTiles; }
+        void SetNumTiles(uint32_t num) { fNumTiles=num; }
+
+protected:
+
+        /// Allocates the required objects.
+        void reallocateBuffers()
+        {
+            size_t total_block_head_size = 0;
+            for (auto it=fRealColumns.begin(); it!=fRealColumns.end(); it++)
+                total_block_head_size += it->block_head.getSizeOnDisk();
+
+            const size_t chunk_size = fRealRowWidth*fNumRowsPerTile + total_block_head_size + sizeof(FITS::TileHeader) + 8; //+8 for checksuming;
+            fMemPool.setChunkSize(chunk_size);
+            fSmartBuffer = fMemPool.malloc();
+            fRawSumBuffer.resize(fRealRowWidth + 4-fRealRowWidth%4); //for checksuming
+        }
+
+        /// Actually does the writing to disk (and checksuming)
+        /// @param src the buffer to write
+        /// @param sizeToWrite how many bytes should be written
+        /// @return the state of the file
+        bool writeCompressedDataToDisk(char* src, const uint32_t sizeToWrite)
+        {
+            char* checkSumPointer = src+4;
+            int32_t extraBytes = 0;
+            uint32_t sizeToChecksum = sizeToWrite;
+
+            //should we extend the array to the left ?
+            if (fCheckOffset != 0)
+            {
+                sizeToChecksum  += fCheckOffset;
+                checkSumPointer -= fCheckOffset;
+                memset(checkSumPointer, 0, fCheckOffset);
+            }
+
+            //should we extend the array to the right ?
+            if (sizeToChecksum%4 != 0)
+            {
+                extraBytes = 4 - (sizeToChecksum%4);
+                memset(checkSumPointer+sizeToChecksum, 0, extraBytes);
+                sizeToChecksum += extraBytes;
+            }
+
+            //do the checksum
+            fDataSum.add(checkSumPointer, sizeToChecksum);
+
+            fCheckOffset = (4 - extraBytes)%4;
+
+            //write data to disk
+            write(src+4, sizeToWrite);
+
+            return good();
+        }
+
+        /// Compress a given buffer based on the target. This is the method executed by the threads
+        /// @param target the struct hosting the parameters of the compression
+        /// @return number of bytes of the compressed data, or always 1 when used by the Queues
+        bool CompressBuffer(const CompressionTarget& target)
+        {
+            //Can't get this to work in the thread. Printed the adresses, and they seem to be correct.
+            //Really do not understand what's wrong...
+            //calibrate data if required
+            const uint32_t thisRoundNumRows  = (target.num_rows%fNumRowsPerTile) ? target.num_rows%fNumRowsPerTile : fNumRowsPerTile;
+            for (uint32_t i=0;i<thisRoundNumRows;i++)
+            {
+                char* target_location = target.src.get() + fRealRowWidth*i;
+                DrsOffsetCalibrate(target_location);
+            }
+#ifdef __EXCEPTIONS
+            try
+            {
+#endif
+                //transpose the original data
+                copyTransposeTile(target.src.get(), target.transposed_src.get(), target.num_rows);
+
+                //compress the buffer
+                const uint64_t compressed_size = compressBuffer(target.target.data.get(), target.transposed_src.get(), target.num_rows, target.catalog_entry);
+
+                //post the result to the writing queue
+                //get a copy so that it becomes non-const
+                fWriteToDiskQueue.emplace(target.target, compressed_size);
+
+#ifdef __EXCEPTIONS
+            }
+            catch (...)
+            {
+                fThreadsException = std::current_exception();
+                if (fNumQueues == 0)
+                    std::rethrow_exception(fThreadsException);
+            }
+#endif
+
+            return true;
+        }
+
+        /// Write one compressed tile to disk. This is the method executed by the writing thread
+        /// @param target the struct hosting the write parameters
+        bool WriteBufferToDisk(const WriteTarget& target)
+        {
+            //is this the tile we're supposed to write ?
+            if (target.tile_num != (uint32_t)(fLatestWrittenTile+1))
+                return false;
+
+            fLatestWrittenTile++;
+
+#ifdef __EXCEPTIONS
+            try
+            {
+#endif
+                //could not write the data to disk
+                if (!writeCompressedDataToDisk(target.data.get(), target.size))
+                    fErrno = errno;
+#ifdef __EXCEPTIONS
+            }
+            catch (...)
+            {
+                fThreadsException = std::current_exception();
+                if (fNumQueues == 0)
+                    std::rethrow_exception(fThreadsException);
+            }
+#endif
+            return true;
+        }
+
+        /// Compress a given buffer based on its source and destination
+        //src cannot be const, as applySMOOTHING is done in place
+        /// @param dest the buffer hosting the compressed data
+        /// @param src the buffer hosting the transposed data
+        /// @param num_rows the number of uncompressed rows in the transposed buffer
+        /// @param the number of bytes of the compressed data
+        uint64_t compressBuffer(char* dest, char* src, uint32_t num_rows, CatalogRow& catalog_row)
+        {
+            const uint32_t thisRoundNumRows = (num_rows%fNumRowsPerTile) ? num_rows%fNumRowsPerTile : fNumRowsPerTile;
+            uint32_t       offset           = 0;
+
+            //skip the checksum reserved area
+            dest += 4;
+
+            //skip the 'TILE' marker and tile size entry
+            uint64_t compressedOffset = sizeof(FITS::TileHeader);
+
+            //now compress each column one by one by calling compression on arrays
+            for (uint32_t i=0;i<fRealColumns.size();i++)
+            {
+                catalog_row[i].second = compressedOffset;
+
+                if (fRealColumns[i].col.num == 0)
+                    continue;
+
+                FITS::Compression& head = fRealColumns[i].block_head;
+
+                //set the default byte telling if uncompressed the compressed Flag
+                const uint64_t previousOffset = compressedOffset;
+
+                //skip header data
+                compressedOffset += head.getSizeOnDisk();
+
+                for (uint32_t j=0;j<head.getNumProcs();j++)//sequence.size(); j++)
+                {
+                    switch (head.getProc(j))
+                    {
+                    case FITS::kFactRaw:
+                        compressedOffset += compressUNCOMPRESSED(dest + compressedOffset, src  + offset, thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num);
+                        break;
+
+                    case FITS::kFactSmoothing:
+                        applySMOOTHING(src + offset, thisRoundNumRows*fRealColumns[i].col.num);
+                        break;
+
+                    case FITS::kFactHuffman16:
+                        if (head.getOrdering() == FITS::kOrderByCol)
+                            compressedOffset += compressHUFFMAN16(dest + compressedOffset, src  + offset, thisRoundNumRows, fRealColumns[i].col.size, fRealColumns[i].col.num);
+                        else
+                            compressedOffset += compressHUFFMAN16(dest + compressedOffset, src  + offset, fRealColumns[i].col.num, fRealColumns[i].col.size, thisRoundNumRows);
+                        break;
+                    }
+                }
+
+                //check if compressed size is larger than uncompressed
+                //if so set flag and redo it uncompressed
+                if ((head.getProc(0) != FITS::kFactRaw) && (compressedOffset - previousOffset > fRealColumns[i].col.size*fRealColumns[i].col.num*thisRoundNumRows+head.getSizeOnDisk()))// && two)
+                {
+                    //de-smooth !
+                    if (head.getProc(0) == FITS::kFactSmoothing)
+                        UnApplySMOOTHING(src+offset, fRealColumns[i].col.num*thisRoundNumRows);
+
+                    FITS::Compression he;
+
+                    compressedOffset = previousOffset + he.getSizeOnDisk();
+                    compressedOffset += compressUNCOMPRESSED(dest + compressedOffset, src + offset, thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num);
+
+                    he.SetBlockSize(compressedOffset - previousOffset);
+                    he.Memcpy(dest+previousOffset);
+
+                    offset += thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num;
+
+                    catalog_row[i].first = compressedOffset - catalog_row[i].second;
+                    continue;
+                }
+
+                head.SetBlockSize(compressedOffset - previousOffset);
+                head.Memcpy(dest + previousOffset);
+
+                offset += thisRoundNumRows*fRealColumns[i].col.size*fRealColumns[i].col.num;
+                catalog_row[i].first = compressedOffset - catalog_row[i].second;
+            }
+
+            const FITS::TileHeader tile_head(thisRoundNumRows, compressedOffset);
+            memcpy(dest, &tile_head, sizeof(FITS::TileHeader));
+
+            return compressedOffset;
+        }
+
+        /// Transpose a tile to a new buffer
+        /// @param src buffer hosting the regular, row-ordered data
+        /// @param dest the target buffer that will receive the transposed data
+        void copyTransposeTile(const char* src, char* dest, uint32_t num_rows)
+        {
+            const uint32_t thisRoundNumRows = (num_rows%fNumRowsPerTile) ? num_rows%fNumRowsPerTile : fNumRowsPerTile;
+
+            //copy the tile and transpose it
+            for (uint32_t i=0;i<fRealColumns.size();i++)
+            {
+                switch (fRealColumns[i].block_head.getOrdering())
+                {
+                case FITS::kOrderByRow:
+                    //regular, "semi-transposed" copy
+                    for (uint32_t k=0;k<thisRoundNumRows;k++)
+                    {
+                        memcpy(dest, src+k*fRealRowWidth+fRealColumns[i].col.offset, fRealColumns[i].col.size*fRealColumns[i].col.num);
+                        dest += fRealColumns[i].col.size*fRealColumns[i].col.num;
+                    }
+                    break;
+
+                case FITS::kOrderByCol:
+                    //transposed copy
+                    for (uint32_t j=0;j<fRealColumns[i].col.num;j++)
+                        for (uint32_t k=0;k<thisRoundNumRows;k++)
+                        {
+                            memcpy(dest, src+k*fRealRowWidth+fRealColumns[i].col.offset+fRealColumns[i].col.size*j, fRealColumns[i].col.size);
+                            dest += fRealColumns[i].col.size;
+                        }
+                    break;
+                };
+            }
+        }
+
+        /// Specific compression functions
+        /// @param dest the target buffer
+        /// @param src the source buffer
+        /// @param size number of bytes to copy
+        /// @return number of bytes written
+        uint32_t compressUNCOMPRESSED(char* dest, const char* src, uint32_t size)
+        {
+            memcpy(dest, src, size);
+            return size;
+        }
+
+        /// Do huffman encoding
+        /// @param dest the buffer that will receive the compressed data
+        /// @param src the buffer hosting the transposed data
+        /// @param numRows number of rows of data in the transposed buffer
+        /// @param sizeOfElems size in bytes of one data elements
+        /// @param numRowElems number of elements on each row
+        /// @return number of bytes written
+        uint32_t compressHUFFMAN16(char* dest, const char* src, uint32_t numRows, uint32_t sizeOfElems, uint32_t numRowElems)
+        {
+            std::string huffmanOutput;
+            uint32_t previousHuffmanSize = 0;
+
+            //if we have less than 2 elems to compress, Huffman encoder does not work (and has no point). Just return larger size than uncompressed to trigger the raw storage.
+            if (numRows < 2)
+                return numRows*sizeOfElems*numRowElems + 1000;
+
+            if (sizeOfElems < 2 )
+            {
+#ifdef __EXCEPTIONS
+                throw std::runtime_error("HUFMANN16 can only encode columns with 16-bit or longer types");
+#else
+                gLog << ___err___ << "ERROR - HUFMANN16 can only encode columns with 16-bit or longer types" << std::endl;
+                return 0;
+#endif
+            }
+
+            uint32_t huffmanOffset = 0;
+            for (uint32_t j=0;j<numRowElems;j++)
+            {
+                Huffman::Encode(huffmanOutput,
+                                reinterpret_cast<const uint16_t*>(&src[j*sizeOfElems*numRows]),
+                                numRows*(sizeOfElems/2));
+                reinterpret_cast<uint32_t*>(&dest[huffmanOffset])[0] = huffmanOutput.size() - previousHuffmanSize;
+                huffmanOffset += sizeof(uint32_t);
+                previousHuffmanSize = huffmanOutput.size();
+            }
+
+            const size_t totalSize = huffmanOutput.size() + huffmanOffset;
+
+            //only copy if not larger than not-compressed size
+            if (totalSize < numRows*sizeOfElems*numRowElems)
+                memcpy(&dest[huffmanOffset], huffmanOutput.data(), huffmanOutput.size());
+
+            return totalSize;
+        }
+
+        /// Applies Thomas' DRS4 smoothing
+        /// @param data where to apply it
+        /// @param numElems how many elements of type int16_t are stored in the buffer
+        /// @return number of bytes modified
+        uint32_t applySMOOTHING(char* data, uint32_t numElems)
+        {
+            int16_t* short_data = reinterpret_cast<int16_t*>(data);
+            for (int j=numElems-1;j>1;j--)
+                short_data[j] = short_data[j] - (short_data[j-1]+short_data[j-2])/2;
+
+            return numElems*sizeof(int16_t);
+        }
+
+        /// Apply the inverse transform of the integer smoothing
+        /// @param data where to apply it
+        /// @param numElems how many elements of type int16_t are stored in the buffer
+        /// @return number of bytes modified
+        uint32_t UnApplySMOOTHING(char* data, uint32_t numElems)
+        {
+            int16_t* short_data = reinterpret_cast<int16_t*>(data);
+            for (uint32_t j=2;j<numElems;j++)
+                short_data[j] = short_data[j] + (short_data[j-1]+short_data[j-2])/2;
+
+            return numElems*sizeof(uint16_t);
+        }
+
+
+
+        //thread related stuff
+        MemoryManager   fMemPool;           ///< Actual memory manager, providing memory for the compression buffers
+        int32_t         fNumQueues;         ///< Current number of threads that will be used by this object
+        uint64_t        fMaxUsableMem;      ///< Maximum number of bytes that can be allocated by the memory manager
+        int32_t         fLatestWrittenTile; ///< Index of the last tile written to disk (for correct ordering while using several threads)
+
+        std::vector<Queue<CompressionTarget>>     fCompressionQueues;  ///< Processing queues (=threads)
+        Queue<WriteTarget, QueueMin<WriteTarget>> fWriteToDiskQueue;   ///< Writing queue (=thread)
+
+        // catalog related stuff
+        CatalogType fCatalog;               ///< Catalog for this file
+        uint32_t    fCatalogSize;           ///< Actual catalog size (.size() is slow on large lists)
+        uint32_t    fNumTiles;              ///< Number of pre-reserved tiles
+        uint32_t    fNumRowsPerTile;        ///< Number of rows per tile
+        off_t       fCatalogOffset;         ///< Offset of the catalog from the beginning of the file
+
+        // checksum related stuff
+        Checksum fCatalogSum;    ///< Checksum of the catalog
+        Checksum fRawSum;        ///< Raw sum (specific to FACT)
+        int32_t  fCheckOffset;   ///< offset to the data pointer to calculate the checksum
+
+        // data layout related stuff
+        /// Regular columns augmented with compression informations
+        struct CompressedColumn
+        {
+            CompressedColumn(const Table::Column& c, const FITS::Compression& h) : col(c),
+                block_head(h)
+            {}
+#ifdef __MARS__ // Needed for the compilation ofthe dictionary
+            CompressedColumn() { }
+#endif
+            Table::Column col;             ///< the regular column entry
+            FITS::Compression block_head;  ///< the compression data associated with that column
+        };
+        std::vector<CompressedColumn> fRealColumns;     ///< Vector hosting the columns of the file
+        uint32_t                      fRealRowWidth;    ///< Width in bytes of one uncompressed row
+        std::shared_ptr<char>         fSmartBuffer;     ///< Smart pointer to the buffer where the incoming rows are written
+        std::vector<char>             fRawSumBuffer;    ///< buffer used for checksuming the incoming data, before compression
+
+        std::exception_ptr fThreadsException; ///< exception pointer to store exceptions coming from the threads
+        int                fErrno;            ///< propagate errno to main thread
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcorsika/CorsikaIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/CorsikaIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/CorsikaIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mcorsika/CorsikaLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/CorsikaLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/CorsikaLinkDef.h	(revision 17960)
@@ -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 MCorsikaRunHeader+;
+#pragma link C++ class MCorsikaEvtHeader+;
+#pragma link C++ class MCorsikaRead+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaEvtHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaEvtHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaEvtHeader.cc	(revision 17960)
@@ -0,0 +1,197 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 11/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCorsikaEvtHeader 
+//
+// Class Version 2:
+// ----------------
+//  - UInt_t fParticleID
+//
+//
+// Class Version 3:
+// ----------------
+//  - UInt_t fNumReuse
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCorsikaEvtHeader.h"
+#include "MCorsikaFormat.h"
+
+#include <iomanip>
+#include <fstream>
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+//#include "MMcEvt.hxx"
+
+ClassImp(MCorsikaEvtHeader);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Create the array to store the data.
+//
+MCorsikaEvtHeader::MCorsikaEvtHeader(const char *name, const char *title)
+    : fNumReuse((UInt_t)-1), fX(0), fY(0)
+{
+    fName  = name  ? name  : "MCorsikaEvtHeader";
+    fTitle = title ? title : "Raw Event Header Information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Impact (distance of ground incident point from telescope axis)
+//
+// Distance d between a point q and a line u (via p):
+//   d = | ( vec(q) - vec(p) ) x vec(u) |  /  | vec(u) |
+//
+// If p = 0
+//
+//   ==>   d = | vec(q) x vec(u) |  /  | vec(u) |
+//          w :=  q = (x/y/0)
+//          v :=  u = (Alt/Az)
+//
+// For Alt/Az = Theta/Phi:
+//
+//  x = r sin(theta) cos(phi)
+//  y = r sin(theta) sin(phi)
+//  z = r cos(theta)
+//
+//                   (   -q3*u2    )   ( -cos(theta)*y                                     )
+// vec(q) x vec(u) = (    q3*u1    ) = (  cos(theta)*x                                     )
+//                   ( q1*u2-q2*u1 )   ( sin(theta) cos(phi) * y - sin(theta) sin(phi) * x )
+//
+//   ==> d = sqrt( cos(theta)^2 (x^2  + y^2 ) +
+//                 sin(theta)^2 ( cos(phi) y + sin(phi) x)^2 )
+//
+Double_t MCorsikaEvtHeader::GetImpact() const
+{
+    const Double_t c = TMath::Cos(fZd);
+    const Double_t s = TMath::Sin(fZd);
+
+    const Double_t p = TMath::Cos(fAz)*fX - TMath::Sin(fAz)*fY;
+
+    return TMath::Sqrt(c*c*(fX*fX + fY*fY) + s*s* p*p);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This member function prints all Data of one Event to *fLog.
+//
+void MCorsikaEvtHeader::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << "Event Number:              " << dec << fEvtNumber << " (reused=" << fNumReuse << ")" << endl;
+//    *fLog << "Particle ID:               " << MMcEvt::GetParticleName(fParticleID) << endl;
+    *fLog << "Energy:                    " << fTotalEnergy << "GeV" << endl;
+    *fLog << "Starting Altitude:         " << fStartAltitude << "g/cm" << UTF8::kSquare << endl;
+    *fLog << "Number of 1st Target:      " << fFirstTargetNum << endl,
+    *fLog << "Height of 1st Interaction: " << fFirstInteractionHeight/100. << "m" << endl;
+    *fLog << "Momentum X/Y/Z (GeV/c):    " << fMomentumX << "/" << fMomentumY << "/" << fMomentumZ << endl;
+    *fLog << "Zenith/Azimuth Angle:      " << fZd*TMath::RadToDeg() << UTF8::kDeg << "/" << fAz*TMath::RadToDeg() << UTF8::kDeg << endl;
+    *fLog << "Impact X/Y:                " << fX/100. << "m/" << fY/100. << "m  (r=" << TMath::Hypot(fX, fY)/100. << "m)" << endl;
+    *fLog << "Weighted Num Photons:      " << fWeightedNumPhotons << endl;
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the EVTH information from the input parameter f
+//
+Int_t MCorsikaEvtHeader::ReadEvt(Float_t * f)
+{
+
+    fEvtNumber  = TMath::Nint(f[0]);
+//    fParticleID = TMath::Nint(f[1]);
+
+    fTotalEnergy            = f[2];
+    fStartAltitude          = f[3];
+    fFirstTargetNum         = f[4];
+    fFirstInteractionHeight = f[5]; // FIXME: Could be negative
+
+    // Pointing opposite particle direction
+    // (x=north, y=west, z=upwards)
+    //fMomentumX = f[6];
+    //fMomentumY = f[7];
+    //fMomentumZ = f[8];
+    // Pointing along particle direction
+    // (x=east, y=north, z=upwards)
+    fMomentumX =  f[7];
+    fMomentumY = -f[6];
+    fMomentumZ = -f[8];  // Does this minus make sense?!
+
+    fZd        = f[9];
+    fAz        = TMath::Pi()-f[10];
+
+    // f[96] // Number of reuse of event [max=20]
+    fTotReuse = TMath::Nint(f[96]);
+    if (fTotReuse > 20)
+      {
+      *fLog << err << "Number of reuse of shower is " << fTotReuse 
+                   << " But maximum implemented: 20" << endl;
+      return kERROR;
+      }
+
+    memcpy(fTempX, f +97, 20*sizeof(Float_t));
+    memcpy(fTempY, f+117, 20*sizeof(Float_t));
+
+
+    // FIXME: Check fNumReuse<20
+//    fX =  f[117 + fNumReuse];
+//    fY = -f[ 97 + fNumReuse];
+
+    fWeightedNumPhotons = 0;
+
+    return kTRUE;
+}
+
+
+// this member function is for reading the event end block
+
+Int_t MCorsikaEvtHeader::ReadEvtEnd(MCorsikaFormat * fInFormat)
+{
+    Float_t f[272];
+    if (!fInFormat->Read(f, 272 * sizeof(Float_t)))
+        return kERROR;
+
+    const UInt_t evtnum = TMath::Nint(f[0]);
+    if (evtnum!=fEvtNumber)
+    {
+        *fLog << err << "ERROR - Mismatch in stream: Event number in EVTE (";
+        *fLog << evtnum << ") doesn't match EVTH (" << fEvtNumber << ")." << endl;
+        return kERROR;
+    }
+
+    // FIXME: What's the meaning of this if in case of reusing the event this number
+    //        exists only once?
+    fWeightedNumPhotons = f[1];
+
+    return fInFormat->Eof() ? kERROR : kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaEvtHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaEvtHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaEvtHeader.h	(revision 17960)
@@ -0,0 +1,88 @@
+#ifndef MARS_MCorsikaEvtHeader
+#define MARS_MCorsikaEvtHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MCorsikaFormat;
+
+class MCorsikaEvtHeader : public MParContainer
+{
+private:
+    UInt_t   fEvtNumber;              // Event number
+    UInt_t   fNumReuse;               // Counter of the reuse of the same shower
+    UInt_t   fTotReuse;               //! number of reuse of the same shower     
+//    UInt_t   fParticleID;             // Particle ID (see MMcEvtBasic or CORSIKA manual)
+    Float_t  fTotalEnergy;            // [GeV] 
+
+    Float_t  fStartAltitude;          // [g/cm²]
+    Float_t  fFirstTargetNum;         // Number of first target if fixed
+    Float_t  fFirstInteractionHeight; // [cm] z coordinate, first intercation height
+
+    Float_t  fMomentumX;              // [GeV/c] "+west"    "-east"
+    Float_t  fMomentumY;              // [GeV/c] "+south"   "-north" (north denotes the magnet north which is defined to be in the geografic north!)
+    Float_t  fMomentumZ;              // [GeV/c] "+upwards" "-downwards"
+
+    Float_t  fZd;                     // [rad] Zenith distance
+    Float_t  fAz;                     // [rad] Azimuth (north=0; east=90) (north denotes the magnet north which is defined to be in the geografic north!)
+
+    Float_t  fX;                      // [cm] Position of telescope on ground x / - impact parameter x
+    Float_t  fY;                      // [cm] Position of telescope on gorund y / - impact parameter y
+
+    Float_t  fWeightedNumPhotons;     // weighted number of photons arriving at observation level
+
+    Float_t fTempX[20];               //! Temporary storage for impact parameter
+    Float_t fTempY[20];               //! Temporary storage for impact parameter
+
+public:
+    MCorsikaEvtHeader(const char *name=NULL, const char *title=NULL);
+
+    //void Clear(Option_t * = NULL);
+    void Print(Option_t * = NULL) const;
+
+    UInt_t GetEvtNumber() const { return fEvtNumber; }
+    UInt_t GetNumReuse() const { return fNumReuse; }
+    UInt_t GetTotReuse() const { return fTotReuse; }
+//    UInt_t GetParticleID() const { return fParticleID; }
+
+    TVector3 GetMomentum() const { return TVector3(fMomentumX, fMomentumY, fMomentumZ); }
+    TVector2 GetImpactPos() const { return TVector2(fX, fY); }
+
+    Float_t GetTotalEnergy() const { return fTotalEnergy; }
+    Float_t GetFirstInteractionHeight() const { return fFirstInteractionHeight; }
+
+    Float_t GetZd() const { return fZd; }
+    Float_t GetAz() const { return fAz; }
+
+    Float_t GetX() const { return fX; }
+    Float_t GetY() const { return fY; }
+
+    Double_t GetImpact() const;
+
+    void GetArrayOffset(Int_t arrayIdx, Float_t & xArrOff, Float_t & yArrOff)
+                     {xArrOff = fTempY[arrayIdx]; yArrOff=-fTempX[arrayIdx]; }
+    void SetTelescopeOffset(Int_t arrayIdx, Float_t xTelOff, Float_t yTelOff)
+                     {fNumReuse = arrayIdx; fX = xTelOff; fY = yTelOff;}
+
+    void IncNumReuse() { fNumReuse++; }
+    void ResetNumReuse() { fNumReuse=0; }
+
+    void InitXY() { fX=fTempY[fNumReuse]; fY=-fTempX[fNumReuse]; }
+    void AddXY(Float_t x, Float_t y) { fX+=x; fY+=y; }
+
+    Int_t ReadEvt(Float_t * f);                 // read in event header block
+    Int_t ReadEvtEnd(MCorsikaFormat *informat); // read in event end block
+
+    ClassDef(MCorsikaEvtHeader, 3) // Parameter Conatiner for raw EVENT HEADER
+}; 
+
+#endif
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaFormat.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaFormat.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaFormat.cc	(revision 17960)
@@ -0,0 +1,256 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Reiner Rohlfs 2010
+!   Author(s): Thomas Bretz  2010 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MCorsikaFormat
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCorsikaFormat.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include "MLogManip.h"
+
+
+using namespace std;
+
+
+const unsigned int MCorsikaFormat::kSyncMarker = 0xd41f8a37;
+
+// --------------------------------------------------------------------------
+//
+MCorsikaFormat *MCorsikaFormat::CorsikaFormatFactory(const char * fileName)
+{
+    ifstream * fileIn = new ifstream(fileName);
+
+    const Bool_t noexist = !(*fileIn);
+    if (noexist)
+    {
+        gLog << err << "Cannot open file " << fileName << ": ";
+        gLog << (errno!=0?strerror(errno):"Insufficient memory for decompression") << endl;
+        delete fileIn;
+        return NULL;
+    }
+
+    char *buffer = new char[5];
+    memset(buffer, 0, 5);
+    fileIn->read(buffer, 4);
+    fileIn->seekg(-4, ios::cur);
+
+    if (strcmp(buffer, "RUNH") == 0)
+    {
+        delete [] buffer;
+        return new MCorsikaFormatRaw(fileIn);
+    }
+
+    if (*reinterpret_cast<unsigned int*>(buffer) == kSyncMarker)
+    {
+        delete [] buffer;
+        return new MCorsikaFormatEventIO(fileIn);
+    }
+
+    gLog << err << "File " << fileName <<
+            " is neither a CORSIKA raw nor EventIO file" << endl;
+    delete fileIn;
+    delete [] buffer;
+
+    return NULL;
+}
+
+Bool_t MCorsikaFormat::Read(void *ptr, Int_t i) const
+{
+   fIn->read((char*)ptr, i);
+   return !fIn->fail();
+
+}
+// --------------------------------------------------------------------------
+//
+Bool_t MCorsikaFormat::Eof() const
+{
+    return fIn->eof();
+}
+
+// --------------------------------------------------------------------------
+//
+MCorsikaFormat::~MCorsikaFormat() 
+{
+    delete fIn;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// After a call to this function, the file pointer is located after the   
+// header of the block. As the event block has no header it is located    
+// at the beginning of this block, which is as the beginning of the data  
+Bool_t MCorsikaFormatRaw::NextBlock(Int_t   readState,
+                                    Int_t & blockType, 
+                                    Int_t & blockVersion,
+                                    Int_t & blockIdentifier, 
+                                    Int_t & blockLength) const
+{
+
+    int blockHeader;
+    fIn->read((char*)&blockHeader, 4);
+    if (fIn->eof())
+        return kFALSE;
+
+    blockVersion = 0;
+    blockIdentifier = 0;
+    blockLength     = 272 * 4;
+
+    switch(blockHeader)
+      {
+      case 1213093202 : // RUNH
+         blockType = 1200;
+         break;
+      case 1162761554 : // RUNE
+         blockType = 1210;
+         break;
+      case 1213486661 : // EVTH
+         if (readState != 10)
+            blockType = 1202;
+         else
+            {
+            blockType = 1105;
+            fIn->seekg(-4, ios::cur);
+            blockLength += 4;
+            }
+         break;
+      case 1163155013 : // EVTE
+         blockType = 1209;
+         break;
+      default:          // the events, they don't have a specific header
+         blockType = 1105;
+         fIn->seekg(-4, ios::cur);
+         blockLength += 4;
+      }            
+    return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+Bool_t MCorsikaFormatRaw::SeekEvtEnd()
+{
+    // Search subblockwise backward (Block: 5733*4 = 21*273*4)
+    for (int i=1; i<22; i++)
+    {
+        fIn->seekg(-i*273*4, ios::end);
+
+        char runh[5]="\0\0\0\0";
+        fIn->read(runh, 4);
+
+        if (!strcmp(runh, "RUNE"))
+        {
+//            fIn->seekg(-4, ios::cur);
+            return kTRUE;
+        }
+    }
+    
+    return kTRUE;
+}
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+Bool_t MCorsikaFormatEventIO::NextBlock(Int_t   readState,
+                                        Int_t & blockType, 
+                                        Int_t & blockVersion,
+                                        Int_t & blockIdentifier, 
+                                        Int_t & blockLength) const
+{
+// we read - synchronisation markerif not subBlock
+//         - type / version field
+//         - identification field
+//         - length
+//         - unknown field
+//         - id (first 4 bytes of data field)
+
+   if (readState == 4)
+//   if (subBlock)
+      {
+      // this is a sub-block
+      int blockHeader[3];
+      fIn->read((char*)blockHeader, 3 * sizeof(int));
+
+      if (fIn->eof())
+         return kFALSE;
+
+
+      blockType       = blockHeader[0] & 0xFFFF;
+      blockVersion    = (blockHeader[0] & 0xFFF00000) >> 20;
+      blockIdentifier = blockHeader[1];
+      blockLength     = blockHeader[2] & 0x3FFFFFFF;
+      }
+   else
+      {
+       int blockHeader[4];
+       fIn->read((char*)blockHeader, 4 * sizeof(int));
+
+       if (fIn->eof())
+           return kFALSE;
+
+
+       blockType       = blockHeader[1] & 0xFFFF;
+       blockVersion    = (blockHeader[1] & 0xFFF00000) >> 20;
+       blockIdentifier = blockHeader[2];
+       blockLength     = blockHeader[3] & 0x3FFFFFFF;
+
+       if (blockType == 1200  || blockType == 1210 ||
+           blockType == 1202  || blockType == 1209    )
+           {
+           // read the "old" corsika header plus additional 4 unknown byte
+           char tmp[8];
+           fIn->read(tmp, 8);
+           blockLength -= 8;
+           }
+    
+      }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MCorsikaFormatEventIO::SeekEvtEnd()
+{
+
+    // the RUNE block it at the very end of the file.
+    fIn->seekg(-32, ios::end);
+
+    unsigned int blockHeader[4];
+    fIn->read((char*)blockHeader, 4 * sizeof(int));
+
+    if ( blockHeader[0]               == kSyncMarker &&
+        (blockHeader[1] & 0xffff)     == 1210        &&
+        (blockHeader[3] & 0x3fffffff) == 16)
+    {
+        // this seams to be a RUNE (1210)  block
+        fIn->seekg( 8, ios::cur);
+        return kTRUE;
+    }
+
+    return kFALSE;
+}
+
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaFormat.h
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaFormat.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaFormat.h	(revision 17960)
@@ -0,0 +1,79 @@
+#ifndef MARS_MDataFormat
+#define MARS_MDataFormat
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_Rtypes
+#include <Rtypes.h>
+#endif
+
+#include <iosfwd>
+#include <fstream>
+
+class MCorsikaFormat
+{
+protected:
+   std::istream  *fIn;
+
+public:
+    static const unsigned int kSyncMarker;
+
+   MCorsikaFormat(std::istream * in)
+        : fIn(in) { }
+   virtual ~MCorsikaFormat();
+
+   virtual Bool_t NextBlock(Int_t   readState, Int_t & blockType, Int_t & blockVersion,
+                            Int_t & blockIdentifier, Int_t & blockLength) const = 0;
+
+           void   Seek(std::streampos offset)    {fIn->seekg(offset, std::ios::cur);}
+
+   virtual Bool_t SeekEvtEnd() = 0;
+
+   virtual Bool_t IsEventioFormat() const = 0;
+
+   virtual Bool_t Eof() const;
+
+           Bool_t Read(void *ptr, Int_t i) const;
+
+   static MCorsikaFormat *CorsikaFormatFactory(const char *fileName);
+};
+
+
+class MCorsikaFormatRaw : public MCorsikaFormat
+{
+private:
+
+public:
+   MCorsikaFormatRaw(std::istream * in)
+        : MCorsikaFormat(in) {}
+
+   Bool_t NextBlock(Int_t   readState, Int_t & blockType, Int_t & blockVersion,
+                    Int_t & blockIdentifier, Int_t & blockLength) const;
+
+   Bool_t SeekEvtEnd();
+
+   Bool_t IsEventioFormat() const {return kFALSE;}
+};
+
+
+class MCorsikaFormatEventIO : public MCorsikaFormat
+{
+
+public:
+    MCorsikaFormatEventIO(std::istream *in)
+        : MCorsikaFormat(in) {}
+
+
+    Bool_t NextBlock(Int_t   readState, Int_t & blockType, Int_t & blockVersion,
+                     Int_t & blockIdentifier, Int_t & blockLength) const;
+
+    Bool_t SeekEvtEnd();
+
+    Bool_t IsEventioFormat() const { return kTRUE; }
+
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaRead.cc	(revision 17960)
@@ -0,0 +1,693 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+               Reiner Rohlfs 11/2010 <mailto:Reiner.Rohlfs@unige.ch>
+!
+!   Copyright: Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MCorsikaRead
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MCorsikaRunHeader
+//   MCorsikaEvtHeader
+//   MPhotonEvent
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCorsikaRead.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+#include "MCorsikaFormat.h"
+#include "MCorsikaRunHeader.h"
+#include "MCorsikaEvtHeader.h"
+
+#include "MPhotonEvent.h"
+
+ClassImp(MCorsikaRead);
+
+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.
+//
+MCorsikaRead::MCorsikaRead(const char *fname, const char *name, const char *title)
+    : fRunHeader(0), fEvtHeader(0), fEvent(0), fTelescopeIdx(-1), fArrayIdx(-1), 
+    fForceMode(kFALSE), fFileNames(0), fNumFile(0), fNumEvents(0), 
+    fNumTotalEvents(0), fInFormat(0), fParList(0), fNumTelescopes(1), fReadState(0)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Read task to read DAQ binary files";
+
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname!=NULL)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream.
+//
+MCorsikaRead::~MCorsikaRead()
+{
+    delete fFileNames;
+    if (fInFormat)
+        delete fInFormat;
+}
+
+/*
+Byte_t MCorsikaRead::IsFileValid(const char *name)
+{
+    MZlib fin(name);
+    if (!fin)
+        return 0;
+
+    Byte_t c[4];
+    fin.read((char*)c, 4);
+    if (!fin)
+        return 0;
+
+    if (c[0]!=0xc0)
+        return 0;
+
+    if (c[1]==0xc0)
+        return 1;
+
+    if (c[1]==0xc1)
+        return 2;
+
+    return 0;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Add a new file to a list of files to be processed, Returns the number
+// of files added. (We can enhance this with a existance chack and
+// wildcard support)
+//
+Int_t MCorsikaRead::AddFile(const char *fname, Int_t entries)
+{
+    TNamed *name = new TNamed(fname, "");
+    fFileNames->AddLast(name);
+    return 1;
+
+}
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Int_t MCorsikaRead::OpenNextFile(Bool_t print)
+{
+
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fInFormat)
+       delete fInFormat;
+    fInFormat = NULL;
+
+    //
+    // Check for the existance of a next file to read
+    //
+    TObject *file = fFileNames->At(fNumFile);
+    if (!file)
+        return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const char *name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    fInFormat = MCorsikaFormat::CorsikaFormatFactory(expname);
+    delete [] expname;
+
+    if (fInFormat == NULL)
+        return kERROR;
+
+    *fLog << inf << "Open file: '" << name << "'" << endl;
+
+    if (fDisplay)
+    {
+       // Show the number of the last event after
+       // which we now open a new file
+       TString txt = GetFileName();
+       txt += " @ ";
+       txt += GetNumExecutions()-1;
+       fDisplay->SetStatusLine2(txt);
+    }
+
+    fNumFile++;
+
+    if (!fParList)
+        return kTRUE;
+
+    //
+    // Search for MTaskList
+    //
+    MTask *tlist = (MTask*)fParList->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << err << dbginf << "MTaskList not found... abort." << endl;
+        return kERROR;
+    }
+
+    //
+    // A new file has been opened and new headers have been read.
+    //  --> ReInit tasklist
+    //
+    return tlist->ReInit(fParList) ? kTRUE : kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return file name of current file.
+//
+TString MCorsikaRead::GetFullFileName() const
+{
+    const TObject *file = fFileNames->At(fNumFile-1);
+    return file ? file->GetName() : "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Restart with the first file
+//
+Bool_t MCorsikaRead::Rewind()
+{
+    fNumFile=0;
+    fNumEvents=0;
+    return OpenNextFile()==kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the total number of events from all input files and stores
+// the number in fNumTotalEvents.                                       
+//
+Bool_t MCorsikaRead::CalcNumTotalEvents()
+{
+    fNumTotalEvents = 0;
+
+    Bool_t rc = kTRUE;
+
+    while (1)
+    {
+        switch (OpenNextFile(kFALSE))
+        {
+        case kFALSE:
+            break;
+        case kERROR:
+            rc = kFALSE;
+            break;
+        case kTRUE:
+
+            // read run header(1200), telescope position(1201) and 
+            // first event header(1202)
+            Bool_t status = kTRUE;
+            Int_t blockType, blockVersion, blockIdentifier, blockLength;
+            while (status && 
+                   fInFormat->NextBlock(fReadState/* == 4*/, blockType, blockVersion, 
+                              blockIdentifier, blockLength))
+               {
+               if (blockType == 1200)
+                  status = fRunHeader->ReadEvt(fInFormat);
+
+               else if(blockType == 1201)
+                   status = ReadTelescopePosition();
+
+               else if (blockType == 1202)
+                  {
+                  Float_t buffer[272];
+                  status = fInFormat->Read(buffer, 272 * sizeof(Float_t));
+                  status = fRunHeader->ReadEventHeader(buffer);
+                  break;
+                  }
+               else
+                  fInFormat->Seek(blockLength);
+               }
+                  
+            if (status != kTRUE)
+               return status;
+
+            if (!fInFormat->SeekEvtEnd())
+            {
+               *fLog << (fForceMode?warn:err) << "Error: RUNE section not found in file." << endl;
+               if (!fForceMode)
+                  return fForceMode ? kTRUE : kFALSE;
+            }
+
+            if (!fRunHeader->ReadEvtEnd(fInFormat, kTRUE))
+            {
+               *fLog << (fForceMode?warn:err) << "Error: Reading RUNE section failed." << endl;
+               if (!fForceMode)
+                  return kFALSE;
+            }
+
+            fNumTotalEvents += fRunHeader->GetNumEvents()*fRunHeader->GetNumReuse()*
+                (fTelescopeIdx<0 ? fNumTelescopes : 1);
+            continue;
+        }
+        break;
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads the the position of all telescopes in one array
+//
+Int_t MCorsikaRead::ReadTelescopePosition()
+{
+   if (!fInFormat->Read(&fNumTelescopes, 4)) return kERROR;
+
+   if (fTelescopeIdx>=fNumTelescopes)
+   {
+      *fLog << err << "ERROR - Requested telescope index " << fTelescopeIdx << 
+            " exceeds number of telescopes " << fNumTelescopes << " in file." << endl;
+      return kERROR;
+   }
+
+   fTelescopeX.Set(fNumTelescopes);
+   fTelescopeY.Set(fNumTelescopes);
+   fTelescopeZ.Set(fNumTelescopes);
+   fTelescopeR.Set(fNumTelescopes);
+
+   if (!fInFormat->Read(fTelescopeX.GetArray(), 4*fNumTelescopes)) return kERROR;
+   if (!fInFormat->Read(fTelescopeY.GetArray(), 4*fNumTelescopes)) return kERROR;
+   if (!fInFormat->Read(fTelescopeZ.GetArray(), 4*fNumTelescopes)) return kERROR;
+   if (!fInFormat->Read(fTelescopeR.GetArray(), 4*fNumTelescopes)) return kERROR;
+
+   *fLog << all;
+   *fLog << "Number of telescopes: " << fNumTelescopes << " (using ";
+   if (fTelescopeIdx>=0)
+      *fLog << "telescope " << fTelescopeIdx;
+   else
+      *fLog << "all telescopes";
+   *fLog << ")" << endl;
+
+   const Int_t lo = fTelescopeIdx<0 ? 0              : fTelescopeIdx;
+   const Int_t up = fTelescopeIdx<0 ? fNumTelescopes : fTelescopeIdx+1;
+
+   for (int i=lo; i<up; i++)
+   {
+      *fLog << all << "Telescope #" << setw(4) << i << " [X/Y/Z (R)]: ";
+      *fLog << setw(7) << fTelescopeX[i] << "/";
+      *fLog << setw(7) << fTelescopeY[i] << "/";
+      *fLog << setw(7) << fTelescopeZ[i] << "  (R=" << setw(4) << fTelescopeR[i] << ")" << endl;
+   }
+
+   fNumTelescope = 0;
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads the header of the next block. Depending on the current fReadState
+// and the block-type of the new header the methods decides wether 
+// to continue the reading (kCONTINEU), to exit the Process() method (kTRUE)
+// or to try to read a new file (kFALSE).
+// Return codes:
+//   - kFALSE :   end of file was detected and no new header was read
+//   - kTRU:      A EventEnd was already found (fReadStatus == 3) and
+//                the current header is not the RunEnd
+//   - kCONTINUE: all other cases.
+Int_t MCorsikaRead::ReadNextBlockHeader()
+{
+   if (fInFormat->NextBlock(fReadState/* == 4*/, fBlockType, fBlockVersion, 
+                            fBlockIdentifier, fBlockLength)               == kFALSE)
+      // end of file
+      return kFALSE;
+/*
+    gLog << "Next fBlock:  type=" << fBlockType << " version=" << fBlockVersion;
+    gLog << " identifier=" << fBlockIdentifier << " length=" << fBlockLength; 
+    gLog << " readState= " << fReadState << endl;
+*/   
+   if (fReadState == 3 && fBlockType != 1210)
+      // fReadState == 3    means we have read the event end 
+      //                    most of the time we can now save our data. BUT:
+      // bBlockType != 1210 means the next block is not RUNE, 
+      //                    we want to read the RUNE block, before we 
+      //                    save everything (last events and RUNE) 
+      return kTRUE;
+
+   if (fBlockType == 1204 && fReadState != 2)
+      // next is a new set of telescope arrays, we store the previous ones
+      // but not if this is the first one (fReadState != 2)
+      return kTRUE;
+
+   return kCONTINUE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MCorsikaRunHeader <output>   if not found it is created
+//   MCorsikaEvtHeader <output>   if not found it is created
+//   MCorsikaEvtData <output>     if not found it is created
+//   MCorsikaCrateArray <output>  if not found it is created
+//   MCorsikaEvtTime <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 MCorsikaRead::PreProcess(MParList *pList)
+{
+    //
+    // open the input stream
+    // first of all check if opening the file in the constructor was
+    // successfull
+    //
+    fParList = 0;
+
+    //
+    //  check if all necessary containers exist in the Parameter list.
+    //  if not create one and add them to the list
+    //
+    fRunHeader = (MCorsikaRunHeader*)pList->FindCreateObj("MCorsikaRunHeader");
+    if (!fRunHeader)
+        return kFALSE;
+
+    fEvtHeader = (MCorsikaEvtHeader*)pList->FindCreateObj("MCorsikaEvtHeader");
+    if (!fEvtHeader)
+        return kFALSE;
+
+    fEvent = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent");
+    if (!fEvent)
+        return kFALSE;
+
+    *fLog << inf << "Calculating number of total events..." << flush;
+    if (!CalcNumTotalEvents())
+        return kFALSE;
+    *fLog << inf << " " << fNumTotalEvents << " found." << endl;
+
+    fNumFile=0;
+    fNumEvents=0;
+
+    fParList = pList;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The Process reads one event from the binary file:
+//  - The event header is read
+//  - the run header is read (only once per file)
+//  - the raw data information of one event is read
+//
+Int_t MCorsikaRead::Process()
+{
+   while (1)  // loop for multiple input files
+   {
+      if (fInFormat)
+      {
+
+      while (1)  // loop per input block
+         {
+
+         if (fReadState == 4)
+            {
+            fTopBlockLength -= fBlockLength + 12;
+            if (fTopBlockLength <= 0)
+               // all data of a top block are read, go back to normal state
+               fReadState = 15; // not used
+            }
+
+
+         Int_t status = kTRUE;
+         switch (fBlockType)
+            {
+            case 1200:       // the run header
+               status = fRunHeader->ReadEvt(fInFormat);
+               fReadState = 1;  // RUNH is read
+               break;
+
+            case 1201:       // telescope position
+               status = ReadTelescopePosition();
+               break;
+
+            case 1202:  // the event header
+               Float_t buffer[272];
+               if (!fInFormat->Read(buffer, 272 * sizeof(Float_t))) 
+                  return kFALSE;
+
+               if (fReadState == 1)  // first event after RUN header
+                  {
+                  fRunHeader->ReadEventHeader(buffer);
+                  fRunHeader->Print();
+                  }
+
+               status = fEvtHeader->ReadEvt(buffer);
+               if (fArrayIdx >= (Int_t)fEvtHeader->GetTotReuse())
+                  {
+                  *fLog << err << "ERROR - Requested array index " << fArrayIdx << 
+                        " exceeds number of arrays " << fEvtHeader->GetTotReuse() << 
+                        " in file." << endl;
+                  return kERROR;
+                  }
+
+               fReadState = 2;
+               break;
+
+            case 1204: // top level block for one array (only for eventio data)
+               if (fArrayIdx < 0 || fArrayIdx == fBlockIdentifier)
+                  { 
+                  fReadState = 4;
+                  fTopBlockLength = fBlockLength;
+                  }
+               else
+                  // skip this array of telescopes
+                  fInFormat->Seek(fBlockLength);
+
+               break;
+
+
+            case 1205: // eventio data
+               {
+               Int_t telIdx   = fBlockIdentifier % 1000;
+               if (fBlockVersion == 0                               &&
+                     (fTelescopeIdx < 0 || fTelescopeIdx ==  telIdx)     )
+                  {
+                  status = fEvent->ReadEventIoEvt(fInFormat);
+
+                  Int_t arrayIdx = fBlockIdentifier / 1000;
+                  Float_t xArrOff, yArrOff;
+                  fEvtHeader->GetArrayOffset(arrayIdx, xArrOff, yArrOff);
+                  fEvtHeader->SetTelescopeOffset(arrayIdx, 
+                                                   xArrOff + fTelescopeY[telIdx], 
+                                                   yArrOff - fTelescopeX[telIdx] );
+                  fEvent->AddXY(xArrOff + fTelescopeY[telIdx], 
+                                 yArrOff - fTelescopeX[telIdx]);
+                  fEvent->SimWavelength(fRunHeader->GetWavelengthMin(), 
+                                          fRunHeader->GetWavelengthMax());
+                  }
+               else
+                  // skip this telescope
+                  fInFormat->Seek(fBlockLength);
+               }
+               break;
+
+            case 1209:  // the event end
+               status = fEvtHeader->ReadEvtEnd(fInFormat);
+               
+               if (fReadState == 10 || fReadState == 2)
+                  {
+                  // corsika events
+                  fEvtHeader->ResetNumReuse();
+                  fEvtHeader->InitXY();
+                  fBlockType = 1109;  // save corsika events
+                  continue;
+                  }
+
+               fReadState = 3;  // event closed, run still open
+               break;
+
+
+            case 1210:  // the run end
+               status = fRunHeader->ReadEvtEnd(fInFormat, kTRUE);
+               fNumEvents += fRunHeader->GetNumEvents();
+               //fRunHeader->SetReadyToSave();
+               fReadState = 5;           // back to  starting point
+               // this may be the last block in the file. 
+               // We exit to write the header into the file
+               fBlockLength = 0;
+               fBlockType   = 0; // not available type 
+               return kTRUE;
+               break;
+
+
+            case 1105:  // event block of raw format
+               if (fReadState == 2 || fReadState == 10)
+                  {
+                  Int_t oldSize = fRawEvemtBuffer.size();
+                  fRawEvemtBuffer.resize(oldSize + fBlockLength / sizeof(Float_t));
+                  status = fInFormat->Read(&fRawEvemtBuffer[oldSize], fBlockLength); 
+                  fReadState = 10;
+                  }
+               else
+                  fInFormat->Seek(fBlockLength);
+               break;
+
+
+            case 1109:  // save corsika events
+               fEvtHeader->InitXY();
+               status = fEvent->ReadCorsikaEvt(&fRawEvemtBuffer[0], 
+                                               fRawEvemtBuffer.size() / 7, 
+                                               fEvtHeader->GetNumReuse()+1);
+               fEvtHeader->IncNumReuse();
+
+               if (fEvtHeader->GetNumReuse() == fRunHeader->GetNumReuse())
+                  {
+                  // this was the last reuse. Set fBlockType to EVTE to save
+                  // it the next time.
+                  fRawEvemtBuffer.resize(0);
+
+                  fReadState = 3;
+                  fBlockType = 1209;
+                  }
+               else
+                  // save this reuse
+                  return status;
+
+               break;               
+
+            default:
+               // unknown block, we skip it
+               fReadState = 15;
+               fInFormat->Seek(fBlockLength);
+
+            }
+
+         if (status != kTRUE)
+            // there was an error while data were read
+            return status;
+
+         Int_t headerStatus =  ReadNextBlockHeader();
+         if (headerStatus == kFALSE) 
+            // end of file
+            break;
+         if (headerStatus == kTRUE)
+            // we shall quit this loop
+            return kTRUE;
+
+            // else continue
+         }
+
+      }
+
+      //
+      // If an event could not be read from file try to open new file
+      //
+      const Int_t rc = OpenNextFile();
+      if (rc!=kTRUE)
+          return rc;
+
+      if (ReadNextBlockHeader() == kFALSE)
+         return kFALSE;
+   }
+   return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Close the file. Check whether the number of read events differs from
+//  the number the file should containe (MCorsikaRunHeader). Prints a warning
+//  if it doesn't match.
+//
+Int_t MCorsikaRead::PostProcess()
+{
+
+    const UInt_t n = fNumEvents*fRunHeader->GetNumReuse()*(fTelescopeIdx<0?fNumTelescopes:1);
+
+    //
+    // Sanity check for the number of events
+    //
+    if (n==GetNumExecutions()-1 || GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << warn << dec;
+    *fLog << "Warning - number of read events (" << GetNumExecutions()-1;
+    *fLog << ") doesn't match number in run header(s) (";
+    *fLog << fRunHeader->GetNumReuse() << "*" << fNumEvents << "=" << n << ")." << endl;
+
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaRead.h	(revision 17960)
@@ -0,0 +1,98 @@
+#ifndef MARS_MCorsikaRead
+#define MARS_MCorsikaRead
+
+#include <vector>
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TList;
+//class MZlib;
+class MTaskList;
+
+class MCorsikaRunHeader;
+class MCorsikaEvtHeader;
+class MPhotonEvent;
+class MCorsikaFormat;
+
+class MCorsikaRead : public MRead
+{
+private:
+    MCorsikaRunHeader *fRunHeader;  //! run header information container to fill from file
+    MCorsikaEvtHeader *fEvtHeader;  //! event header information container to fill from file
+    MPhotonEvent      *fEvent;      //! event information
+
+    Int_t           fTelescopeIdx;  // Index of telescope to be extracted
+    Int_t           fArrayIdx;      // Index of telescope-array to be extracted
+    Bool_t          fForceMode;     // Force mode skipping defect RUNE
+
+    TList    *fFileNames;      // list of file names
+    UInt_t    fNumFile;        //! number of next file
+    UInt_t    fNumEvents;      //! input stream (file to read from)
+    UInt_t    fNumTotalEvents; //! total number of events in all files
+
+    MCorsikaFormat *fInFormat; //! access to input corsika data
+
+    MParList *fParList;        //! tasklist to call ReInit from
+
+    Int_t  fNumTelescopes;     //! Number of telescopes in array
+    Int_t  fNumTelescope;      //! Number of telescope currently being read
+    TArrayF fTelescopeX;       //! x pos (measured towards north, unit: cm)
+    TArrayF fTelescopeY;       //! y pos (measured towards west,  unit: cm)
+    TArrayF fTelescopeZ;       //! z pos (from detection level,   unit: cm)
+    TArrayF fTelescopeR;       //! Radii of spheres around tel. (unit: cm)
+
+    Int_t   fBlockType;        //! block type of the just read block header
+    Int_t   fBlockVersion;     //! block version of the just read block header 
+    Int_t   fBlockIdentifier;  //! block identifier of the just read block header
+    Int_t   fBlockLength;      //! block length from the just read block header
+
+    Int_t   fReadState;        //! 0: nothing read yet 
+                               //  1: RUNH is already read
+                               //  2: EVTH is already read
+                               //  3: EVTE is already read, run still open
+                               //  4: inside of a top level block (1205)
+                               //  5: RUNE is already read
+                               // 10: raw events are currently read
+                               // 15: undefined status
+    Int_t   fTopBlockLength;   // remaining length of the current top-level block 1204
+
+    std::vector<Float_t>  fRawEvemtBuffer;     //! buffer of raw event data
+    //UInt_t    fInterleave;
+    //Bool_t    fForce;
+
+
+    Int_t  OpenNextFile(Bool_t print=kTRUE);
+    Bool_t CalcNumTotalEvents();
+    Int_t  ReadTelescopePosition();
+    Int_t  ReadNextBlockHeader();
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+
+public:
+    MCorsikaRead(const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MCorsikaRead();
+
+    void SetForceMode(Bool_t b=kTRUE) { fForceMode=b; }
+    void SetTelescopeIdx(Int_t idx)   { fTelescopeIdx = idx; }
+    void SetArrayIdx(Int_t idx)       { fArrayIdx = idx; }
+
+    TString GetFullFileName() const;
+
+    Int_t  AddFile(const char *fname, Int_t entries=-1);
+    Bool_t Rewind();
+    UInt_t GetEntries() { return fNumTotalEvents/*/fInterleave*/; }
+
+    ClassDef(MCorsikaRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaRunHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaRunHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaRunHeader.cc	(revision 17960)
@@ -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 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+               Qi Zhe,      06/2007 <mailto:qizhe@astro.uni-wuerzburg.de>
+
+!   Copyright: Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCorsikaRunHeader
+//
+// Root storage container for the RUN HEADER information
+//
+// Class Version 2:
+// ----------------
+//  + UInt_t fParticleID
+//  + Float_t fImpactMax
+//  + Float_t fMagneticFieldX
+//  + Float_t fMagneticFieldZ
+//  + Float_t fMagneticFieldAz
+//  + Float_t fAtmosphericLayers[5]
+//  + Float_t fAtmosphericCoeffA[5]
+//  + Float_t fAtmosphericCoeffB[5]
+//  + Float_t fAtmosphericCoeffC[5]
+//  + UInt_t  fCerenkovFlag
+//
+// Class Version 3:
+// ----------------
+//  + UInt_t  fNumReuse
+//
+////////////////////////////////////////////////////////////////////////////
+
+#include "MCorsikaRunHeader.h"
+#include "MCorsikaFormat.h"
+
+#include <fstream>
+#include <iomanip>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MCorsikaRunHeader);
+
+using namespace std;
+
+const Double_t MCorsikaRunHeader::fgEarthRadius = 637131500; // [cm] Earth radius as defined in CORSIKA
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates array which stores the pixel assignment.
+//
+//
+MCorsikaRunHeader::MCorsikaRunHeader(const char *name, const char *title)
+    : fNumObsLevel(0), fImpactMax(-1), fZdMin(0), fZdMax(-1),
+    fAzMin(0), fAzMax(0),  fViewConeInnerAngle(0), fViewConeOuterAngle(-1)
+{
+    fName  = name  ? name  : "MCorsikaRunHeader";
+    fTitle = title ? title : "Raw Run Header Information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Read in one run header from the binary file
+//
+Bool_t MCorsikaRunHeader::ReadEvt(MCorsikaFormat * fInFormat)
+{
+    Float_t f[272];
+    if (!fInFormat->Read(f, 272 * sizeof(Float_t)))
+        return kFALSE;
+
+    fRunNumber = TMath::Nint(f[0]);
+    fNumEvents = 0;
+
+    fRunStart.SetCorsikaTime(f[1]);
+
+    fProgramVersion = f[2];
+    fNumObsLevel    = TMath::Nint(f[3]);
+
+    if (fNumObsLevel!=1)
+    {
+        *fLog << err << "ERROR - Currently only one observation level is allowed." << endl;
+        return kFALSE;
+    }
+
+    memset(fObsLevel, 0, 10*4);
+    memcpy(fObsLevel, f+4, fNumObsLevel*4);
+
+    fSlopeSpectrum  = f[14];
+    fEnergyMin      = f[15];
+    fEnergyMax      = f[16];
+
+    // Implemented in CORSIKA Version >= 6.822
+    fImpactMax = -1;
+
+    // CORSIKA scattering in a disc on the ground
+    if (f[246]>0 && f[247]==0)
+    {
+        *fLog << warn << "WARNING - Events scattered in a disc on the ground." << endl;
+        fImpactMax = f[246];
+    }
+
+    // MMCS scattering in a disc perpendicular to the shower axis
+    if (f[246]==0 && f[247]>0)
+        fImpactMax = f[247];
+
+    // CORSIKA scattering in a rectangle on the ground
+    if (f[246]>0 && f[247]>0)
+        *fLog << warn << "WARNING - Events scattered in a rectangle on the ground." << endl;
+
+    // Implemented in CORSIKA Version >= 6.822
+    memcpy(fAtmosphericLayers, f+248, 5*4);
+
+    memcpy(fAtmosphericCoeffA, f+253, 5*4);
+    memcpy(fAtmosphericCoeffB, f+258, 5*4);
+    memcpy(fAtmosphericCoeffC, f+263, 5*4);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read in one event header. It is called for the first event header after  
+// a run header                                                             
+//
+Bool_t MCorsikaRunHeader::ReadEventHeader(Float_t * g)
+{
+
+    // -------------------- Read first event header -------------------
+
+    // FIXME: Add sanity checks!
+
+    // f[76] Cherenkov flag:
+    //        bit(1) : CERENKOV option compiled in
+    //        bit(2) : IACT option compiled in
+    //        bit(3) : CEFFIC option compiled in
+    //        bit(4) : ATMEXT option compiled in
+    //        bit(5) : ATMEXT option used with refraction enabled
+    //        bit(6) : VOLUMEDET option compiled in
+    //        bit(7) : CURVED option compiled in
+    //        bit(9) : SLATN option compiled in
+    //        11-21  : table number for externam athmosphere (but<1024)
+    //
+    // f[78]  Curved athmosphere? (0=flat, 1=curved)
+    // f[84]  cherenkov bunch size
+    // f[93]  flag for additinal muon information of particle output file
+    // f[145] Muon multiple scattering flag
+
+
+    fNumReuse = TMath::Nint(g[96]);  // Number i of uses of each cherenkov event
+
+    fParticleID = TMath::Nint(g[1]);
+
+    // MAGNETIC FIELD: x/z-component of earth magnetic field in muT
+    fMagneticFieldX  =  g[69];  // x-component ( BX)
+    fMagneticFieldZ  = -g[70];  // z-component (-BZ)
+    fMagneticFieldAz =  g[91];  // Azimuth angle of magnetic north expressed in telescope coordinates
+
+    // WITH rounding: unbelievable!
+    fCerenkovFlag = TMath::Nint(g[75]);
+
+    fZdMin = g[79];                // lower edge of theta in °
+    fZdMax = g[80];                // upper edge of theta in °
+    fAzMin = 180-g[81];            // lower edge of phi   in °
+    fAzMax = 180-g[82];            // upper edge of phi   in °
+    // FIXME: Correct for direction of magnetic field!
+
+    if (TMath::Nint(g[83])!=1)
+        *fLog << warn << "WARNING - Cherenkov bunch size not 1, but " << g[83] << endl;
+
+    // g[84] Number of cherenkov detectors in x
+    // g[85] Number of cherenkov detectors in y
+    // g[86] Grid spacing x
+    // g[87] Grid spacing y
+    // g[88] Length of detectors in x
+    // g[89] Length of detectors in y
+
+    fImpactMax = -1;
+/*
+    // This is a trick to use CERARY for storage of the
+    // maximum simulated impact
+    if (TMath::Nint(g[84])==1 && TMath::Nint(g[85])==1 &&
+        TMath::Nint(g[88])==1 && TMath::Nint(g[89])==1 &&
+        g[86]==g[87])
+        fImpactMax = g[86];
+ */
+    fWavelengthMin = g[94];        // Cherenkov bandwidth lower end in nm
+    fWavelengthMax = g[95];        // Cherenkov bandwidth upper end in nm
+
+    fViewConeInnerAngle = g[151];  // inner angle of view cone (°)
+    fViewConeOuterAngle = g[152];  // outer angle of view cone (°)
+
+    return kTRUE;
+}
+
+Bool_t MCorsikaRunHeader::ReadEvtEnd(MCorsikaFormat * fInFormat, Bool_t runNumberVerify)
+{
+    Float_t f[2];
+    if (!fInFormat->Read(f, 2 * sizeof(Float_t)))
+        return kFALSE;
+
+    if (runNumberVerify)
+      {
+       const UInt_t runnum = TMath::Nint(f[0]);
+       if (runnum!=fRunNumber)
+       {
+           *fLog << err << "ERROR - Mismatch in stream: Run number in RUNE (";
+           *fLog << runnum << ") doesn't match RUNH (" << fRunNumber << ")." << endl;
+           return kFALSE;
+       }
+      }
+
+    fNumEvents = TMath::Nint(f[1]);
+
+    return kTRUE;
+}
+
+Bool_t MCorsikaRunHeader::SeekEvtEnd(istream &fin)
+{
+    // Search subblockwise backward (Block: 5733*4 = 21*273*4)
+    for (int i=1; i<22; i++)
+    {
+        fin.seekg(-i*273*4, ios::end);
+
+        char runh[4];
+        fin.read(runh, 4);
+
+        if (!memcmp(runh, "RUNE", 4))
+        {
+            fin.seekg(-4, ios::cur);
+            return kTRUE;
+        }
+    }
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// print run header information on *fLog. The option 'header' supresses
+// the pixel index translation table.
+//
+void MCorsikaRunHeader::Print(Option_t *t) const
+{
+    *fLog << all << endl;
+    *fLog << "Run Number:     " << fRunNumber << "  (" << fRunStart.GetStringFmt("%d.%m.%Y") << ", V" << fProgramVersion << ")" << endl;
+    *fLog << "Particle ID:    " << MMcEvt::GetParticleName(fParticleID) << endl;
+    if (fNumEvents>0)
+        *fLog << "Num Events:     " << fNumEvents << " (reuse " << fNumReuse << " times)" << endl;
+    *fLog << "Obs Level:     ";
+    for (Byte_t i=0; i<fNumObsLevel; i++)
+        *fLog << " " << fObsLevel[i]/100. << "m";
+    *fLog << endl;
+
+    *fLog << "MagneticField:  X/Z=(" << fMagneticFieldX << "/";
+    *fLog << fMagneticFieldZ << ")" << UTF8::kMu << "T  Az=" << fMagneticFieldAz*TMath::RadToDeg() << UTF8::kDeg << "  (magnetic North w.r.t. North)" << endl;
+
+    *fLog << "Spectrum:       Slope=" << fSlopeSpectrum << "  (" << fEnergyMin << "GeV-" << fEnergyMax << "GeV)" <<  endl;
+    *fLog << "Wavelength:     " << fWavelengthMin << "nm - " << fWavelengthMax << "nm" << endl;
+
+    if (fImpactMax>0)
+        *fLog << "ImpactMax:      " << fImpactMax << "cm" << endl;
+    if (fViewConeOuterAngle>0)
+        *fLog << "ViewCone:       " << fViewConeInnerAngle << UTF8::kDeg << " - " << fViewConeOuterAngle << UTF8::kDeg << endl;
+
+    if (fZdMax>=0)
+    {
+        *fLog << "Zd/Az:          " << fZdMin << UTF8::kDeg;
+        if (fZdMin==fZdMax)
+            *fLog << " (fixed)";
+        else
+            *fLog << "-" << fZdMax << UTF8::kDeg;
+        *fLog << " / " << fAzMin << UTF8::kDeg;
+        if (fAzMin==fAzMax)
+            *fLog << " (fixed)";
+        else
+            *fLog << "-" << fAzMax << UTF8::kDeg;
+        *fLog << "  w.r.t. magnetic North." << endl;
+    }
+
+    if (fImpactMax>0)
+        *fLog << "Max.sim.Impact: " << fImpactMax << "cm" << endl;
+
+    *fLog << "Options used:  ";
+    if (Has(kCerenkov))
+        *fLog << " CERENKOV";
+    if (Has(kIact))
+        *fLog << " IACT";
+    if (Has(kCeffic))
+        *fLog << " CEFFIC";
+    if (Has(kAtmext))
+        *fLog << " ATMEXT" << GetNumAtmosphericModel();
+    if (Has(kRefraction))
+        *fLog << " +Refraction";
+    if (Has(kVolumedet))
+        *fLog << " VOLUMEDET";
+    if (Has(kCurved))
+        *fLog << " CURVED";
+    if (Has(kSlant))
+        *fLog << " SLANT";
+    *fLog << endl;
+
+    if (HasLayers())
+    {
+        *fLog << "Atm.Layers:    ";
+        for (int i=0; i<5; i++)
+            *fLog << " " << fAtmosphericLayers[i];
+    }
+    *fLog << "Atm.Coeff A:   ";
+    for (int i=0; i<5; i++)
+        *fLog << " " << fAtmosphericCoeffA[i];
+    *fLog << endl;
+    *fLog << "Atm.Coeff B:   ";
+    for (int i=0; i<5; i++)
+        *fLog << " " << fAtmosphericCoeffB[i];
+    *fLog << endl;
+    *fLog << "Atm.Coeff C:   ";
+    for (int i=0; i<5; i++)
+        *fLog << " " << fAtmosphericCoeffC[i];
+    *fLog << endl;
+
+
+}
+
Index: branches/Mars_McMismatchStudy/mcorsika/MCorsikaRunHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/MCorsikaRunHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/MCorsikaRunHeader.h	(revision 17960)
@@ -0,0 +1,135 @@
+#ifndef MARS_MCorsikaRunHeader
+#define MARS_MCorsikaRunHeader
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MRunHeader                                                        //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MCorsikaFormat;
+
+class MCorsikaRunHeader : public MParContainer
+{
+    friend class MCorsikaEvtHeader;
+public:
+    enum CerenkovFlag_t
+    {
+        kCerenkov   = BIT(0),
+        kIact       = BIT(1),
+        kCeffic     = BIT(2),
+        kAtmext     = BIT(3),
+        kRefraction = BIT(4),
+        kVolumedet  = BIT(5),
+        kCurved     = BIT(6),
+        kSlant      = BIT(8)
+    };
+
+private:
+    static const Double_t fgEarthRadius; // Take same Earth radius as in CORSIKA (cm)
+
+    UInt_t  fRunNumber;               // Run number
+    UInt_t  fNumReuse;                // Number of how many times the same shower is used
+    UInt_t  fParticleID;              // Particle ID (see MMcEvtBasic or CORSIKA manual)
+    UInt_t  fNumEvents;               // Number of events
+    MTime   fRunStart;                // Date of begin (yymmdd)
+    Float_t fProgramVersion;          // Version of program
+
+    Byte_t  fNumObsLevel;             // Number of observation levels
+    Float_t fObsLevel[10];            // Observation levels [cm]
+
+    Float_t fImpactMax;               // [cm] Maximum simulated impact
+
+    Float_t fSlopeSpectrum;           // Slope of energy spectrum
+    Float_t fEnergyMin;               // Lower limit of energy range
+    Float_t fEnergyMax;               // Upper limit of energy range
+
+    Float_t fZdMin;                   // [rad] Zenith distance
+    Float_t fZdMax;                   // [rad] Zenith distance
+    Float_t fAzMin;                   // [rad] Azimuth (north=0; east=90)
+    Float_t fAzMax;                   // [rad] Azimuth (north=0; east=90) (north denotes the magnet north which is defined to be in the geografic north!)
+
+    Float_t fMagneticFieldX;          // [muT] x-component of earth magnetic field (ceres coordinate system)
+    Float_t fMagneticFieldZ;          // [muT] z-component of earth magnetic field (ceres coordinate system)
+    Float_t fMagneticFieldAz;         // [rad] Azimuth angle of magnetic north expressed in telescope coordinates
+
+    Float_t fWavelengthMin;           // [nm] Wavelength bandwidth lo edge
+    Float_t fWavelengthMax;           // [nm] Wavelength bandwidth up edge
+
+    Float_t fViewConeInnerAngle;      // [deg]
+    Float_t fViewConeOuterAngle;      // [deg]
+
+    Float_t fAtmosphericLayers[5];    // [cm]    ATMLAY (see Corsika Manual for details)
+    Float_t fAtmosphericCoeffA[5];    // [g/cm²] AATM   (see Corsika Manual for details)
+    Float_t fAtmosphericCoeffB[5];    // [g/cm²] BATM   (see Corsika Manual for details)
+    Float_t fAtmosphericCoeffC[5];    // [cm]    CATM   (see Corsika Manual for details)
+
+    UInt_t fCerenkovFlag;
+
+public:
+    MCorsikaRunHeader(const char *name=NULL, const char *title=NULL);
+
+    // Getter
+    UInt_t GetRunNumber() const { return fRunNumber; }
+    UInt_t GetParticleID() const { return fParticleID; }
+    UInt_t GetNumEvents() const { return fNumEvents; }
+    UInt_t GetNumReuse() const { return fNumReuse; }
+
+    const MTime &GetRunStart() const { return fRunStart; }
+
+    Float_t GetProgramVersion() const { return fProgramVersion; }
+
+    Float_t GetZdMin() const { return fZdMin; }
+    Float_t GetZdMax() const { return fZdMax; }
+
+    Float_t GetAzMin() const { return fAzMin; }
+    Float_t GetAzMax() const { return fAzMax; }
+
+    Float_t GetWavelengthMin() const { return fWavelengthMin; }
+    Float_t GetWavelengthMax() const { return fWavelengthMax; }
+
+    Float_t GetSlopeSpectrum() const { return fSlopeSpectrum; }
+    Float_t GetEnergyMin() const { return fEnergyMin; }
+    Float_t GetEnergyMax() const { return fEnergyMax; }
+
+    Float_t GetImpactMax() const { return fImpactMax; }
+
+    Float_t GetMagneticFieldX() const  { return fMagneticFieldX; }
+    Float_t GetMagneticFieldZ() const  { return fMagneticFieldZ; }
+    Float_t GetMagneticFieldAz() const { return fMagneticFieldAz; }
+
+    Float_t GetViewConeInnerAngle() const { return fViewConeInnerAngle; }
+    Float_t GetViewConeOuterAngle() const { return fViewConeOuterAngle; }
+    Bool_t HasViewCone() const { return fViewConeOuterAngle>0; }
+
+    Float_t GetObsLevel(UInt_t i=0) const { return i>9 ? -1 : fObsLevel[i]; }
+
+    Bool_t Has(CerenkovFlag_t opt) const { return fCerenkovFlag&opt ? 1 : 0; }
+
+    static Double_t EarthRadius() { return fgEarthRadius; }
+
+    // Preliminary!
+    Bool_t HasLayers() const { return fAtmosphericLayers[4]>0; }
+
+    const Float_t *GetAtmosphericLayers() const { return fAtmosphericLayers; }
+    const Float_t *GetAtmosphericCoeffA() const { return fAtmosphericCoeffA; }
+    const Float_t *GetAtmosphericCoeffB() const { return fAtmosphericCoeffB; }
+    const Float_t *GetAtmosphericCoeffC() const { return fAtmosphericCoeffC; }
+
+    UInt_t GetNumAtmosphericModel() const { return (fCerenkovFlag>>10)&0x3ff; }
+
+    // I/O
+    Bool_t ReadEvt(MCorsikaFormat * fInFormat);
+    Bool_t ReadEventHeader(Float_t * g);
+    Bool_t ReadEvtEnd(MCorsikaFormat * fInFormat, Bool_t runNumberVerify);
+    Bool_t SeekEvtEnd(std::istream &fin);
+
+    // TObject
+    void Print(Option_t *t=NULL) const;
+
+    ClassDef(MCorsikaRunHeader, 3)	// storage container for general info
+};
+#endif
Index: branches/Mars_McMismatchStudy/mcorsika/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mcorsika/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mcorsika/Makefile	(revision 17960)
@@ -0,0 +1,34 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Corsika
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mfileio -I../mmc -I../msim -I../mgui
+
+SRCFILES = MCorsikaRunHeader.cc \
+	   MCorsikaFormat.cc \
+	   MCorsikaEvtHeader.cc \
+           MCorsikaRead.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mdata/DataIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/DataIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/DataIncl.h	(revision 17960)
@@ -0,0 +1,10 @@
+#ifndef __CINT__
+
+//#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include <TGListBox.h>
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mdata/DataLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/DataLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/DataLinkDef.h	(revision 17960)
@@ -0,0 +1,18 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class 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+;
+
+#pragma link C++ class MDataPhrase+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mdata/MData.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MData.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mdata/MData.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MData.h	(revision 17960)
@@ -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; //*MENU*
+    Bool_t AsciiWrite(std::ostream &out) const;
+
+    ClassDef(MData, 0) // A Base class for a generalized value
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdata/MDataArray.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataArray.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataArray.cc	(revision 17960)
@@ -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): Thomas Bretz  08/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   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 <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDataPhrase.h"
+
+ClassImp(MDataArray);
+
+using namespace std;
+
+static const TString gsDefName  = "MDataArray";
+static const TString gsDefTitle = "Array to store MData cntainers";
+
+// --------------------------------------------------------------------------
+//
+// Default 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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy Constructor
+//
+MDataArray::MDataArray(MDataArray &a, const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    gROOT->GetListOfCleanups()->Add(&fList);
+    fList.SetBit(kMustCleanup);
+
+    TIter Next(&a.fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+        AddEntry(data->GetRule());
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new data rule as a new entry (MDataPhrase)
+//
+void MDataArray::AddEntry(const TString rule)
+{
+    TObject *obj = new MDataPhrase(rule);
+    obj->SetBit(kCanDelete);
+    fList.Add(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new data as a new entry (MData). If the destructor of MDataArray
+// should delete the object set its bit kCanDelete
+//
+void MDataArray::AddEntry(MData *data)
+{
+    data->SetBit(kMustCleanup);
+    fList.Add(data);
+}
+
+// --------------------------------------------------------------------------
+//
+// Try to find a MData which has the same rule (GetRule()).
+// Be carefull: This may already fail if the rule is A*B and you are
+// searching for B*A - FIXME: A more intelligent comaparton (based on
+// IsEqual()) should be developed.
+//
+// Returns the index in the array, -1 if rule was not found.
+//
+Int_t MDataArray::FindRule(const char *rule) const
+{
+    const MDataPhrase data(rule);
+    if (!data.IsValid())
+        return -1;
+
+    const TString r(data.GetRule());
+
+    TIter Next(&fList);
+    const MData *d = NULL;
+    while ((d=(MData*)Next()))
+        if (d->GetRule()==r)
+            return fList.IndexOf(d);
+
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the i-th entry
+//
+MData &MDataArray::operator[](Int_t i) const
+{
+    return (MData&)*((TObjArray)fList)[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data value of the i-th entry
+//
+Double_t MDataArray::operator()(Int_t i) const
+{
+    return (*this)[i].GetValue();
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcesses all members in the list
+//
+Bool_t MDataArray::PreProcess(const MParList *plist)
+{
+    if (fList.GetSize()==0)
+    {
+        *fLog << err << "Error - No Column specified... aborting." << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+        if (!data->PreProcess(plist))
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the rules for all entries of the array
+//
+void MDataArray::Print(Option_t *opt) const
+{
+    Int_t n=0;
+
+    const Int_t w = 1+(Int_t)TMath::Log10(fList.GetEntries());
+
+    TIter Next(&fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+    {
+        *fLog << all << " " << fName << "[" << setw(w) << n++ << "] = " << flush;
+        data->Print();
+        *fLog << endl;
+    }
+}
+
+Bool_t MDataArray::AsciiWrite(ostream &out) const
+{
+    ((TObjArray)fList).R__FOR_EACH(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(ostream &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.R__FOR_EACH(MData, SetVariables)(arr);
+}
Index: branches/Mars_McMismatchStudy/mdata/MDataArray.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataArray.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataArray.h	(revision 17960)
@@ -0,0 +1,68 @@
+#ifndef MARS_MDataArray
+#define MARS_MDataArray
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MDataArray
+//
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+class MData;
+class MParList;
+
+class MDataArray : public MParContainer
+{
+    TObjArray fList;
+
+    void StreamPrimitive(std::ostream &out) const;
+
+public:
+    MDataArray(const char *name=NULL, const char *title=NULL);
+    MDataArray(MDataArray &a, const char *name=NULL, const char *title=NULL);
+
+    void AddEntry(const TString rule);
+    void AddEntry(MData *data);
+
+    Int_t FindRule(const char *rule) const;
+
+    MData &operator[](Int_t i) const;
+    Double_t operator()(Int_t i) const;
+
+    void GetData(TVector &v) const;
+
+    void operator>>(TVector &v) const
+    {
+        GetData(v);
+    }
+
+    TString GetRule(int i) const;
+
+    Bool_t PreProcess(const MParList *plist);
+
+    TString GetDataMember() const;
+
+    void Print(Option_t *opt = "") const; //*MENU*
+    Bool_t AsciiWrite(std::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: branches/Mars_McMismatchStudy/mdata/MDataChain.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataChain.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataChain.cc	(revision 17960)
@@ -0,0 +1,938 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MDataChain
+// ==========
+//
+// With this chain you can concatenate simple mathematical operations on
+// members of mars containers.
+//
+//
+// Rules
+// -----
+//
+// In the constructor you can give rule, like
+//   "HillasSource.fDist / MHillas.fLength"
+// Where MHillas/HillasSource is the name of the parameter container in
+// the parameter list and fDist/fLength is the name of the data members
+// in the containers. The result will be fDist divided by fLength.
+//
+// In case you want to access a data-member which is a data member object
+// you can acces it with (Remark: it must derive from MParContainer):
+//   "MCameraLV.fPowerSupplyA.fVoltagePos5V"
+//
+// You can also use parantheses:
+//   "HillasDource.fDist / (MHillas.fLength + MHillas.fWidth)"
+//
+//
+// Operators
+// ---------
+//
+// The allowed operations are: +, -, *, /, %, ^ and ** for ^
+//
+// While a%b returns the floating point reminder of a/b.
+// While a^b returns a to the power of b
+//
+// Priority
+// --------
+//
+//  The priority of the operators is build in as:
+//    ^ (highest),  %, *, /, +, -
+//
+//  Priorities are evaluated before parsing the rule by inserting
+//  artificial paranthesis. If you find ANY problem with this please
+//  report it immediatly! It is highly recommended to check the result!
+//
+// You can also use mathmatical operators, eg:
+//   "5*log10(MMcEvt.fEnergy*MHillas.fSize)"
+//
+// The allowed operators are:
+//   exp(x)    e^x
+//   log(x)    natural logarithm of x
+//   pow10(x)  10^x
+//   log2(x)   logarithm of x to base two
+//   log10(x)  logarithm of x to base ten
+//   cos(x)    cosine of x
+//   sin(x)    sine of x
+//   tan(x)    tangent of x
+//   cosh(x)   hyperbolic cosine of x
+//   sinh(x)   hyperbolic sine of x
+//   tanh(x)   hyperbolic tangent of x
+//   acosh(x)  arc hyperbolic cosine of x
+//   asinh(x)  arc hyperbolic sine of x
+//   atanh(x)  arc hyperbolic tangent of x
+//   acos(x)   arc cosine (inverse cosine) of x
+//   asin(x)   arc sine (inverse sine) of x
+//   atan(x)   arc tangent (inverse tangent) of x
+//   sqrt(x)   square root of x
+//   sqr(x)    square of x
+//   abs(x)    absolute value of x, |x|
+//   floor(x)  round down to the nearest integer (floor(9.9)=9)
+//   ceil(x)   round up   to the nearest integer (floor(9.1)=10)
+//   round(x)  round      to the nearest integer
+//   r2d(x)    transform radians to degrees
+//   d2r(x)    transform degrees to radians
+//   rand(x)   returns a uniform deviate on the interval ( 0, x ].
+//             (gRandom->Uniform(x) is returned)
+//   randp(x)  returns gRandom->Poisson(x)
+//   rande(x)  returns gRandom->Exp(x)
+//   randi(x)  returns gRandom->Integer(x)
+//   randg(x)  returns gRandom->Gaus(0, x)
+//   randl(x)  returns gRandom->Landau(0, x)
+//   isnan(x)  return 1 if x is NaN (Not a Number) otherwise 0
+//   finite(x) return 1 if the number is a valid double (not NaN, inf)
+//
+// NaN (Not a Number) means normally a number which is to small to be
+// stored in a floating point variable (eg. 0<x<1e-56 or similar) or
+// a number which function is not defined (like asin(1.5))
+//
+// inf is the symbol for an infinite number.
+//
+//
+// Constants
+// ---------
+//
+// Constants are implemented in ParseDataMember, namely:
+//   kPi:       TMath::Pi()
+//   kRad2Deg:  180/kPi
+//   kDeg2Rad:  kPi/180
+//
+// You can also defined constants which are defined in TMath by:
+//   kLn10       for   static Double_t TMath::Ln10();
+//   kLogE       for   static Double_t TMath::LogE();
+//   kRadToDeg   for   static Double_t TMath::RadToDeg();
+//   kDegToRad   for   static Double_t TMath::DegToRad();
+//   ...
+//
+// Remark:
+//  In older root versions only Pi() and E() are implemented
+//  in TMath.
+//
+//
+// Variable Parameters
+// ------------------------
+// If you want to use variables, eg for fits you can use [0], [1], ...
+// These values are initialized with 0 and set by calling
+// SetVariables().
+//
+//
+// Multi-argument functions
+// ------------------------
+// You can use multi-argument functions, too. The access is implemented
+// via TFormula, which slows down thing a lot. If you can avoid usage
+// of such expression you accelerate the access a lot. Example:
+//   "TMath::Hypot(MHillas.fMeanX, MHillas.MeanY)"
+//   "pow(MHillas.fMeanX*MHillas.MeanY, -1.2)"
+// It should be possible to use all functions which are accessible
+// via the root-dictionary.
+//
+//
+// REMARK:
+//  - All the random functions are returning 0 if gRandom==0
+//  - You may get better results if you are using a TRandom3
+//
+// To Do:
+//  - The possibility to use other objects inheriting from MData
+//    is missing.
+//  - By automatic pre-adding parantheses to the rule it would be possible
+//    to implement priorities for operators.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MDataChain.h"
+
+#include <ctype.h>        // isalnum, ...
+#include <stdlib.h>       // strtod, ...
+
+#include <TMath.h>
+#include <TClass.h>
+#include <TRegexp.h>
+#include <TRandom.h>
+#include <TMethodCall.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDataList.h"
+#include "MDataValue.h"
+#include "MDataMember.h"
+#include "MDataFormula.h"
+#include "MDataElement.h"
+
+ClassImp(MDataChain);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Constructor which takes a rule and a surrounding operator as argument
+//
+MDataChain::MDataChain(const char *rule, OperatorType_t op)
+    : fOperatorType(op)
+{
+    fName  = "MDataChain";
+    fTitle = rule;
+
+    fMember=ParseString(rule);
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor taking a rule as an argument. For more details see
+// class description
+//
+MDataChain::MDataChain(const char *rule, const char *name, const char *title)
+    : fMember(NULL), fOperatorType(kENoop)
+{
+    fName  = name  ? name  : "MDataChain";
+    fTitle = title ? title : rule;
+
+    if (TString(rule).IsNull())
+        return;
+
+    *fLog << inf << "Parsing rule... " << flush;
+    if (!(fMember=ParseString(rule)))
+    {
+        *fLog << err << dbginf << "Parsing '" << rule << "' failed." << endl;
+        return;
+    }
+    *fLog << inf << "found: " << GetRule() << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcesses all members in the list
+//
+Bool_t MDataChain::PreProcess(const MParList *pList)
+{
+    return fMember ? fMember->PreProcess(pList) : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether at least one member has the ready-to-save flag.
+//
+Bool_t MDataChain::IsReadyToSave() const
+{
+    *fLog << all << "fM=" << fMember << "/" << (int)fMember->IsReadyToSave() << " " << endl;
+    return fMember ? fMember->IsReadyToSave() : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete filters.
+//
+MDataChain::~MDataChain()
+{
+    if (fMember)
+        delete fMember;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the number of alphanumeric characters (including '.' and ';')
+// in the given string
+//
+Int_t MDataChain::IsAlNum(TString txt)
+{
+    int l = txt.Length();
+    for (int i=0; i<l; i++)
+    {
+        if (!isalnum(txt[i]) && txt[i]!='.' && txt[i]!=':' && txt[i]!=';' &&
+	    /*txt[i]!='['&&txt[i]!=']'&&*/
+            ((txt[i]!='-' && txt[i]!='+') || i!=0))
+            return i;
+    }
+
+    return l;
+}
+
+Int_t MDataChain::GetBracket(TString txt, char open, char close)
+{
+    Int_t first=1;
+    for (int cnt=0; first<txt.Length(); first++)
+    {
+        if (txt[first]==open)
+            cnt++;
+        if (txt[first]==close)
+            cnt--;
+        if (cnt==-1)
+            break;
+    }
+    return first;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compare a given text with the known operators. If no operator match
+// kENoop is retunred, otherwise the corresponding OperatorType_t
+//
+MDataChain::OperatorType_t MDataChain::ParseOperator(TString txt) const
+{
+    txt.ToLower();
+
+    if (txt=="abs")    return kEAbs;
+    if (txt=="fabs")   return kEAbs;
+    if (txt=="log")    return kELog;
+    if (txt=="log2")   return kELog2;
+    if (txt=="log10")  return kELog10;
+    if (txt=="sin")    return kESin;
+    if (txt=="cos")    return kECos;
+    if (txt=="tan")    return kETan;
+    if (txt=="sinh")   return kESinH;
+    if (txt=="cosh")   return kECosH;
+    if (txt=="tanh")   return kETanH;
+    if (txt=="asin")   return kEASin;
+    if (txt=="acos")   return kEACos;
+    if (txt=="atan")   return kEATan;
+    if (txt=="asinh")  return kEASinH;
+    if (txt=="acosh")  return kEACosH;
+    if (txt=="atanh")  return kEATanH;
+    if (txt=="sqrt")   return kESqrt;
+    if (txt=="sqr")    return kESqr;
+    if (txt=="exp")    return kEExp;
+    if (txt=="pow10")  return kEPow10;
+    if (txt=="sgn")    return kESgn;
+    if (txt=="floor")  return kEFloor;
+    if (txt=="r2d")    return kERad2Deg;
+    if (txt=="d2r")    return kEDeg2Rad;
+    if (txt=="rand")   return kERandom;
+    if (txt=="randp")  return kERandomP;
+    if (txt=="rande")  return kERandomE;
+    if (txt=="randi")  return kERandomI;
+    if (txt=="randg")  return kERandomG;
+    if (txt=="randl")  return kERandomL;
+    if (txt=="isnan")  return kEIsNaN;
+    if (txt=="finite") return kEFinite;
+    if (txt[0]=='-')   return kENegative;
+    if (txt[0]=='+')   return kEPositive;
+
+    return kENoop;
+}
+
+// --------------------------------------------------------------------------
+//
+// Here the names of data members are interpreted. This can be used to
+// check for constants.
+//
+MData *MDataChain::ParseDataMember(TString txt)
+{
+    //txt.ToLower();
+
+    if (txt=="kRad2Deg") return new MDataValue(kRad2Deg);
+    if (txt=="kDeg2Rad") return new MDataValue(1./kRad2Deg);
+
+    if (!txt.BeginsWith("k"))
+        return new MDataMember(txt.Data());
+
+    const TString name = txt(1, txt.Length());
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,01,00)
+    TMethodCall call(TMath::Class(), name, "");
+#else
+    static TClass *const tmath = TClass::GetClass("TMath");
+    TMethodCall call(tmath, name, "");
+#endif
+
+    switch (call.ReturnType())
+    {
+    case TMethodCall::kLong:
+        Long_t l;
+        call.Execute(l);
+        return new MDataValue(l);
+    case TMethodCall::kDouble:
+        Double_t d;
+        call.Execute(d);
+        return new MDataValue(d);
+    default:
+        break;
+    }
+
+    return new MDataMember(txt.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove all whitespaces
+// Replace all kind of double +/- by a single + or -
+//
+void MDataChain::SimplifyString(TString &txt) const
+{
+    txt.ReplaceAll(" ",  "");
+    txt.ReplaceAll("**", "^");
+
+    while (txt.Contains("--") || txt.Contains("++") ||
+           txt.Contains("+-") || txt.Contains("-+"))
+    {
+        txt.ReplaceAll("--", "+");
+        txt.ReplaceAll("++", "+");
+        txt.ReplaceAll("-+", "-");
+        txt.ReplaceAll("+-", "-");
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add Parenthesis depending on the priority of the operators. The
+// priorities are defined by the default of the second argument.
+//
+void MDataChain::AddParenthesis(TString &test, const TString op) const
+{
+    // Signiture of an exponential number 1e12
+    static const TRegexp rexp("[.0123456789]e[+-][0123456789]");
+
+    const TString low = op(1, op.Length());
+    if (low.Length()==0)
+        return;
+
+    int offset = 0;
+    while (1)
+    {
+        const TString check = test(offset, test.Length());
+        if (check.IsNull())
+            break;
+
+        const Ssiz_t pos = check.First(op[0]);
+        if (pos<0)
+            break;
+
+        int cnt=0;
+
+        int i;
+        for (i=pos-1; i>=0; i--)
+        {
+            if (check[i]==')')
+                cnt++;
+            if (check[i]=='(')
+                cnt--;
+            if (cnt>0 || low.First(check[i])<0)
+                continue;
+
+            // Check if operator belongs to an exponential number
+            const TString sub(check(i-2, 4));
+            if (!sub(rexp).IsNull())
+                continue;
+            break;
+        }
+
+        cnt=0;
+        int j;
+        for (j=pos; j<check.Length(); j++)
+        {
+            if (check[j]=='(')
+                cnt++;
+            if (check[j]==')')
+                cnt--;
+            if (cnt>0 || low.First(check[j])<0)
+                continue;
+
+            // Check if operator belongs to an exponential number
+            const TString sub(check(j-2, 4));
+            if (!sub(rexp).IsNull())
+                continue;
+            break;
+        }
+
+        const TString sub = test(offset+i+1, j-i-1);
+
+        // Check if it contains operators,
+        // otherwise we can simply skip it
+        if (sub.First("%^/*+-")>=0)
+        {
+            test.Insert(offset+j,   ")");
+            test.Insert(offset+i+1, "(");
+            offset += 2;
+        }
+        offset += j+1;
+    }
+
+    AddParenthesis(test, low);
+}
+
+// --------------------------------------------------------------------------
+//
+// Core of the data chain. Here the chain is constructed out of the rule.
+//
+MData *MDataChain::ParseString(TString txt, Int_t level)
+{
+    if (level==0)
+    {
+        SimplifyString(txt);
+        AddParenthesis(txt);
+    }
+
+    MData *member0=NULL;
+
+    char type=0;
+    int nlist = 0;
+
+    while (!txt.IsNull())
+    {
+        MData *newmember = NULL;
+
+        txt = txt.Strip(TString::kBoth);
+
+        switch (txt[0])
+        {
+        case '(':
+            {
+                //
+                // Search for the corresponding parantheses
+                //
+                const Int_t first=GetBracket(txt, '(', ')');
+                if (first==txt.Length())
+                {
+                    *fLog << err << dbginf << "Syntax Error: ')' missing." << endl;
+                    if (member0)
+                        delete member0;
+                    return NULL;
+                }
+
+                //
+                // Make a copy of the 'interieur' and delete the substring
+                // including the brackets
+                //
+                TString sub = txt(1, first-1);
+                txt.Remove(0, first+1);
+
+                //
+                // Parse the substring
+                //
+                newmember = ParseString(sub, level+1);
+                if (!newmember)
+                {
+                    *fLog << err << dbginf << "Parsing '" << sub << "' failed." << endl;
+                    if (member0)
+                        delete member0;
+                    return NULL;
+                }
+            }
+            break;
+
+        case ')':
+            *fLog << err << dbginf << "Syntax Error: Too many ')'" << endl;
+            if (member0)
+                delete member0;
+            return NULL;
+
+        case '+':
+        case '-':
+        case '*':
+        case '/':
+        case '%':
+        case '^':
+            if (member0)
+            {
+                //
+                // Check for the type of the symbol
+                //
+                char is = txt[0];
+                txt.Remove(0, 1);
+
+                //
+                // If no filter is available or the available filter
+                // is of a different symbols we have to create a new
+                // data list with the new symbol
+                //
+                if (/*!member0->InheritsFrom(MDataMember::Class()) ||*/ type!=is)
+                {
+                    MDataList *list = new MDataList(is);
+                    list->SetName(Form("List_%c_%d", is, 10*level+nlist++));
+
+                    list->SetOwner();
+                    list->AddToList(member0);
+
+                    member0 = list;
+
+                    type = is;
+                }
+                continue;
+            }
+
+            if (txt[0]!='-' && txt[0]!='+')
+            {
+                *fLog << err << dbginf << "Syntax Error: First argument of '";
+                *fLog << txt[0] << "' opartor missing." << endl;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+
+            // FALLTHROU
+
+        case '0':
+        case '1':
+        case '2':
+        case '3':
+        case '4':
+        case '5':
+        case '6':
+        case '7':
+        case '8':
+        case '9':
+        case '[':
+        case ']':
+            if ((txt[0]!='-' && txt[0]!='+') || isdigit(txt[1]) || txt[1]=='.')
+            {
+                if (!txt.IsNull() && txt[0]=='[')
+                {
+                    Int_t first = GetBracket(txt, '[', ']');
+                    TString op  = txt(1, first-1);
+                    txt.Remove(0, first+1);
+
+                    newmember = new MDataValue(0, atoi(op));
+                    break;
+                }
+
+                char *end;
+                Double_t num = strtod(txt.Data(), &end);
+                if (!end || txt.Data()==end)
+                {
+                    *fLog << err << dbginf << "Error trying to convert '" << txt << "' to value." << endl;
+                    if (member0)
+                        delete member0;
+                    return NULL;
+                }
+
+                txt.Remove(0, end-txt.Data());
+
+                newmember = new MDataValue(num);
+                break;
+            }
+
+            // FALLTHROUH
+
+        default:
+            int i = IsAlNum(txt);
+
+            if (i==0)
+            {
+                *fLog << err << dbginf << "Syntax Error: Name of data member missing in '" << txt << "'" << endl;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+
+            TString text = txt(0, i);
+
+            txt.Remove(0, i);
+            txt = txt.Strip(TString::kBoth);
+
+            if (!txt.IsNull() && txt[0]=='[')
+            {
+                Int_t first = GetBracket(txt, '[', ']');
+                TString op  = txt(1, first-1);
+                txt.Remove(0, first+1);
+
+                newmember = new MDataElement(text, atoi(op));
+                break;
+            }
+            if ((txt.IsNull() || txt[0]!='(') && text[0]!='-' && text[0]!='+')
+            {
+                newmember = ParseDataMember(text.Data());
+                break;
+            }
+
+            OperatorType_t op = ParseOperator(text);
+
+            Int_t first = GetBracket(txt, '(', ')');
+            TString sub = op==kENegative || op==kEPositive ? text.Remove(0,1) + txt : txt(1, first-1);
+            txt.Remove(0, first+1);
+
+            if (op==kENoop)
+            {
+                newmember = new MDataFormula(Form("%s(%s)", (const char*)text, (const char*)sub));
+                if (newmember->IsValid())
+                    break;
+
+                *fLog << err << dbginf << "Syntax Error: Operator '" << text << "' unknown." << endl;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+
+            newmember = new MDataChain(sub, op);
+            if (!newmember->IsValid())
+            {
+                *fLog << err << dbginf << "Syntax Error: Error parsing contents '" << sub << "' of operator " << text << endl;
+                delete newmember;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+        }
+
+        if (!member0)
+        {
+            member0 = newmember;
+            continue;
+        }
+
+        if (!member0->InheritsFrom(MDataList::Class()))
+            continue;
+
+        ((MDataList*)member0)->AddToList(newmember);
+    }
+
+    return member0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the value described by the rule
+//
+Double_t MDataChain::GetValue() const
+{
+    if (!fMember)
+    {
+        //*fLog << warn << "MDataChain not valid." << endl;
+        return 0;
+    }
+
+    const Double_t val = fMember->GetValue();
+
+    switch (fOperatorType)
+    {
+    case kEAbs:      return TMath::Abs(val);
+    case kELog:      return TMath::Log(val);
+    case kELog2:     return TMath::Log2(val);
+    case kELog10:    return TMath::Log10(val);
+    case kESin:      return TMath::Sin(val);
+    case kECos:      return TMath::Cos(val);
+    case kETan:      return TMath::Tan(val);
+    case kESinH:     return TMath::SinH(val);
+    case kECosH:     return TMath::CosH(val);
+    case kETanH:     return TMath::TanH(val);
+    case kEASin:     return TMath::ASin(val);
+    case kEACos:     return TMath::ACos(val);
+    case kEATan:     return TMath::ATan(val);
+    case kEASinH:    return TMath::ASinH(val);
+    case kEACosH:    return TMath::ACosH(val);
+    case kEATanH:    return TMath::ATanH(val);
+    case kESqrt:     return TMath::Sqrt(val);
+    case kESqr:      return val*val;
+    case kEExp:      return TMath::Exp(val);
+    case kEPow10:    return TMath::Power(10, val);
+    case kESgn:      return val<0 ? -1 : 1;
+    case kENegative: return -val;
+    case kEPositive: return val;
+    case kEFloor:    return TMath::Floor(val);
+    case kECeil:     return TMath::Ceil(val);
+    case kERound:    return TMath::Nint(val);
+    case kERad2Deg:  return val*180/TMath::Pi();
+    case kEDeg2Rad:  return val*TMath::Pi()/180;
+    case kERandom:   return gRandom ? gRandom->Uniform(val)      : 0;
+    case kERandomP:  return gRandom ? gRandom->Poisson(val)      : 0;
+    case kERandomE:  return gRandom ? gRandom->Exp(val)          : 0;
+    case kERandomI:  return gRandom ? gRandom->Integer((int)val) : 0;
+    case kERandomG:  return gRandom ? gRandom->Gaus(0, val)   : 0;
+    case kERandomL:  return gRandom ? gRandom->Landau(0, val) : 0;
+    case kEIsNaN:    return TMath::IsNaN(val);
+    case kEFinite:   return TMath::Finite(val);
+    case kENoop:     return val;
+    }
+
+    *fLog << warn << "No Case for " << fOperatorType << " available." << endl;
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Builds a rule from all the chain members. This is a rule which could
+// be used to rebuild the chain.
+//
+TString MDataChain::GetRule() const
+{
+    if (!fMember)
+        return "<n/a>";
+
+    TString str;
+
+    Bool_t bracket = fOperatorType!=kENoop && !fMember->InheritsFrom(MDataList::Class());
+
+    switch (fOperatorType)
+    {
+    case kEAbs:      str += "abs"   ; break;
+    case kELog:      str += "log"   ; break;
+    case kELog2:     str += "log2"  ; break;
+    case kELog10:    str += "log10" ; break;
+    case kESin:      str += "sin"   ; break;
+    case kECos:      str += "cos"   ; break;
+    case kETan:      str += "tan"   ; break;
+    case kESinH:     str += "sinh"  ; break;
+    case kECosH:     str += "cosh"  ; break;
+    case kETanH:     str += "tanh"  ; break;
+    case kEASin:     str += "asin"  ; break;
+    case kEACos:     str += "acos"  ; break;
+    case kEATan:     str += "atan"  ; break;
+    case kEASinH:    str += "asinh" ; break;
+    case kEACosH:    str += "acosh" ; break;
+    case kEATanH:    str += "atanh" ; break;
+    case kESqrt:     str += "sqrt"  ; break;
+    case kESqr:      str += "sqr"   ; break;
+    case kEExp:      str += "exp"   ; break;
+    case kEPow10:    str += "pow10" ; break;
+    case kESgn:      str += "sgn"   ; break;
+    case kENegative: str += "-"     ; break;
+    case kEPositive: str += "+"     ; break;
+    case kEFloor:    str += "floor" ; break;
+    case kECeil:     str += "ceil"  ; break;
+    case kERound:    str += "round" ; break;
+    case kERad2Deg:  str += "r2d"   ; break;
+    case kEDeg2Rad:  str += "d2r"   ; break;
+    case kERandom:   str += "rand"  ; break;
+    case kERandomP:  str += "randp" ; break;
+    case kERandomE:  str += "rande" ; break;
+    case kERandomI:  str += "randi" ; break;
+    case kERandomG:  str += "randg" ; break;
+    case kERandomL:  str += "randl" ; break;
+    case kEIsNaN:    str += "isnan" ; break;
+    case kEFinite:   str += "finite"; break;
+    case kENoop:
+        break;
+    }
+
+    if (bracket)
+        str += "(";
+
+    str += fMember->GetRule();
+
+    if (bracket)
+        str += ")";
+
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MDataChain::GetDataMember() const
+{
+    return fMember ? fMember->GetDataMember() : TString();
+}
+
+void MDataChain::SetVariables(const TArrayD &arr)
+{
+    if (fMember)
+        fMember->SetVariables(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup data chain.
+//
+// Assuming your MDataChain is called (Set/GetName): MyData
+//
+// Now setup the condition, eg:
+//     MyData.Rule: log10(MHillas.fSize)
+// or
+//     MyData.Rule: log10(MHillas.fSize) - 4.1
+//
+// If you want to use more difficult rules you can split the
+// condition into subrules. Subrules are identified
+// by {}-brackets. Avoid trailing 0's! For example:
+//
+//     MyData.Rule: log10(MHillas.fSize) + {0} - {1}
+//     MyData.0: 5.5*MHillas.fSize
+//     MyData.1: 2.3*log10(MHillas.fSize)
+//
+// The numbering must be continous and start with 0. You can use
+// a subrules more than once. All {}-brackets are simply replaced
+// by the corresponding conditions. The rules how conditions can
+// be written can be found in the class description of MDataChain.
+//
+Int_t MDataChain::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (!IsEnvDefined(env, prefix, "Rule", print))
+        return rc;
+
+    TString rule = GetEnvValue(env, prefix, "Rule", "");
+    rule.ReplaceAll(" ", "");
+
+    Int_t idx=0;
+    while (1)
+    {
+        TString cond;
+        if (IsEnvDefined(env, prefix, Form("%d", idx), print))
+        {
+            cond += "(";
+            cond += GetEnvValue(env, prefix, Form("%d", idx), "");
+            cond += ")";
+        }
+
+        if (cond.IsNull())
+            break;
+
+        rule.ReplaceAll(Form("{%d}", idx), cond);
+        idx++;
+    }
+
+    if (fMember)
+    {
+        delete fMember;
+        fMember = 0;
+    }
+
+    if (rule.IsNull())
+    {
+        *fLog << warn << "MDataChain::ReadEnv - ERROR: Empty rule found." << endl;
+        return kERROR;
+    }
+
+    if (!(fMember=ParseString(rule)))
+    {
+        *fLog << err << "MDataChain::ReadEnv - ERROR: Parsing '" << rule << "' failed." << endl;
+        return kERROR;
+    }
+
+    if (print)
+    {
+        *fLog << inf << "found: ";
+        fMember->Print();
+        *fLog << endl;
+    }
+
+    return kTRUE;
+}
+/*
+void MDataChain::ReconstructElements()
+{
+    if (!fMember)
+        return;
+
+    if (fMember->InheritsFrom(MDataElement::Class()))
+    {
+        MData *data = ((MDataElement*)fMember)->CloneColumn();
+        delete fMember;
+        fMember = data;
+    }
+
+    fMember->ReconstructElements();
+}
+*/
Index: branches/Mars_McMismatchStudy/mdata/MDataChain.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataChain.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataChain.h	(revision 17960)
@@ -0,0 +1,75 @@
+#ifndef MARS_MDataChain
+#define MARS_MDataChain
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MDataList                                                              //
+//                                                                         //
+//  List of several filters                                                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class MDataChain : public MData
+{
+private:
+    MData *fMember; // Filter
+
+    // PLEASE, always add new enums to the end of the enumeration,
+    // otherwise you would break loading old data chains...
+    typedef enum {
+        kENoop,
+        kELog, kELog2, kELog10,
+        kEAbs,
+        kESin, kECos, kETan, kESinH, kECosH, kETanH,
+        kEASin, kEACos, kEATan, kEASinH, kEACosH, kEATanH,
+        kESqrt, kESqr, kEPow10, kEExp,
+        kESgn,
+        kEPositive,
+        kENegative,
+        kEFloor, kECeil, kERound,
+        kERad2Deg, kEDeg2Rad, kERandom,
+        kERandomP, kERandomE, kERandomI, kERandomG, kERandomL,
+        kEIsNaN, kEFinite
+    } OperatorType_t;
+
+    OperatorType_t fOperatorType;
+
+    OperatorType_t ParseOperator(TString txt) const;
+
+    Int_t IsAlNum(TString txt);
+    Int_t GetBracket(TString txt, char open, char close);
+
+    void   SimplifyString(TString &txt) const;
+    void   AddParenthesis(TString &test, const TString op="^%*/+-") const;
+    MData *ParseString(TString txt, Int_t level=0);
+    MData *ParseDataMember(TString txt);
+
+    MDataChain(const char *rule, OperatorType_t op);
+
+public:
+    MDataChain(const char *rule=NULL, const char *name=NULL, const char *title=NULL);
+    ~MDataChain();
+
+    // MData
+    Double_t GetValue() const;
+
+    Bool_t IsValid() const { return fMember ? kTRUE : kFALSE; }
+    Bool_t PreProcess(const MParList *plist);
+
+    TString GetRule() const;
+    TString GetDataMember() const;
+    //void    ReconstructElements() { if (fMember) fMember->ReconstructElements(); }
+
+    // MParContainer
+    Bool_t IsReadyToSave() const;
+    void SetVariables(const TArrayD &arr);
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MDataChain, 1) // A chain/concatenation of MData objects
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdata/MDataElement.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataElement.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataElement.cc	(revision 17960)
@@ -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  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 <stdlib.h>   // atoi (Ubuntu 8.10)
+
+#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)
+{
+    if (fNumCol>=0)
+        return;
+
+    const Int_t pos = fMatrixName.First('[');
+    if (pos<=0)
+        return;
+
+    fNumCol     = atoi(fMatrixName.Data()+pos+1);
+    fMatrixName = fMatrixName(0, pos);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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: branches/Mars_McMismatchStudy/mdata/MDataElement.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataElement.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataElement.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mdata/MDataFormula.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataFormula.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataFormula.cc	(revision 17960)
@@ -0,0 +1,321 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): 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);
+
+        args.Remove(0, len+1);
+        pos1 += len;
+
+        txt.Replace(txt.Index(arg), len, Form("[%d]", num++));
+    }
+
+    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;
+    // Must have a name otherwise all axis labels disappear like a miracle
+    fFormula->SetName(fName.IsNull()?"TFormula":fName.Data());
+
+    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()->Remove(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->GetTitle(); //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.R__FOR_EACH(MData, SetVariables)(arr);
+}
+
Index: branches/Mars_McMismatchStudy/mdata/MDataFormula.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataFormula.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataFormula.h	(revision 17960)
@@ -0,0 +1,43 @@
+#ifndef MARS_MDataFormula
+#define MARS_MDataFormula
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class TFormula;
+class MParList;
+
+class MDataFormula : public MData
+{
+private:
+    TFormula      *fFormula;    // TFormula
+    TOrdCollection fMembers;	// List of arguments
+
+    TString Parse(const char *rule);
+
+public:
+    MDataFormula(const char *rule=0, const char *name=0, const char *title=0);
+    MDataFormula(MDataFormula &ts);
+    ~MDataFormula();
+
+    Bool_t IsValid() const;// { return fFormula ? kTRUE : kFALSE; }
+    Bool_t IsReadyToSave() const;
+
+    Double_t GetValue() const;
+    Bool_t PreProcess(const MParList *plist);
+
+    //    void Print(Option_t *opt = "") const;
+    TString GetRule() const;
+    //    TString GetDataMember() const;
+
+    void SetVariables(const TArrayD &arr);
+
+    ClassDef(MDataFormula, 1) // A concatenation of MData objects by one operator
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdata/MDataList.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataList.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataList.cc	(revision 17960)
@@ -0,0 +1,403 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MDataList
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MDataList.h"
+
+#include <math.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 MDataPhrase
+//
+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.R__FOR_EACH(MData, SetVariables)(arr);
+}
Index: branches/Mars_McMismatchStudy/mdata/MDataList.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataList.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataList.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mdata/MDataMember.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataMember.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataMember.cc	(revision 17960)
@@ -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): 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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if accessing fCall is safe
+//
+Bool_t MDataMember::CheckGet() const
+{
+    if (!fObject)
+    {
+        *fLog << err << "ERROR - MDataMember::Get: fObject not initialized ";
+        *fLog << "(not PreProcessed)... returning 0." << endl;
+        return kFALSE;
+    }
+
+    if (!fCall)
+    {
+        *fLog << err << "ERROR - MDataMemberGet: No TMethodCall for " << fDataMember << " of ";
+        *fLog << fObject->GetName() << " available... returning 0." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the value you requested
+//
+Double_t MDataMember::GetValue() const
+{
+    if (!CheckGet())
+        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 << "ERROR - MDataMember::GetValue: " << fObject->GetName();
+        *fLog << "." << fDataMember << " has unkown type (=";
+        *fLog << fCall->ReturnType() << ")... returning 0." << endl;
+        return 0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the string you requested
+//
+const char *MDataMember::GetString() const
+{
+    if (!CheckGet())
+        return NULL;
+
+    switch (fCall->ReturnType())
+    {
+    case TMethodCall::kString:
+        {
+            char *c=NULL;
+            fCall->Execute(fObject, &c);
+            return c;
+        }
+
+    default:
+        *fLog << err << "DataMember " << fDataMember << " of ";
+        *fLog << fObject->GetName() << " not a char*... returning NULL." << endl;
+        return NULL;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 can be used in a MDataPhrase 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: branches/Mars_McMismatchStudy/mdata/MDataMember.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataMember.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataMember.h	(revision 17960)
@@ -0,0 +1,53 @@
+#ifndef MARS_MDataMember
+#define MARS_MDataMember
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MDataMember                                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class MDataMember : public MData
+{
+private:
+    TString fDataMember;
+
+    MParContainer *fObject; //! A pointer to the container from the paramater list
+    TMethodCall   *fCall;   //! The corresponding method call to the member function
+
+    enum { kIsInt = BIT(14) };
+
+    Bool_t CheckGet() const;
+
+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;
+    const char *GetString() 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, 2) // MData object corresponding to a single data member of a Mars container
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdata/MDataPhrase.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataPhrase.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataPhrase.cc	(revision 17960)
@@ -0,0 +1,789 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MDataPhrase
+//
+// A MDataPhrase is a wrapper for TFormula. It supports access to data-
+// members and/or member functions acessible from the parameter list
+// via MDataMember. It supports access to elements of a MMatrix through
+// the parameter list via MDataElement and it sipports variables set
+// by SetVariables via MDataValue.
+//
+// The parsing is done by TFormula. For more information which functions
+// are supported see TFormula, TFormulaPrimitives and TFormulaMathInterface.
+//
+// The support is done by replacing the parameters with access to the
+// parameter list by parameters like [0], [1],... When evaluating
+// the TFormula first the parameters are evaluated and passed to
+// TFormula. Each parameter is evaluated only once and, if necessary,
+// passed more than once to TFormula. To store the MData* classes used
+// for parameter access a TObjArray is used. Its advantage is, that
+// it has an UncheckedAt function which saves some time, because
+// no obsolete sanity checks must be done accessing the array.
+//
+// Because everything supported by TFormula is also supported by
+// MDataPhrase also conditional expression are supported.
+//
+// For supported functions see TFormulaPrimitive and TMathInterface.
+//
+// Examples:
+//
+//   Gaus, Gausn, Landau, Landaun, Pol0-Pol10, Pow2-Pow5
+//
+// 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"
+// (THIS FEATURE IS CURRENTLY NOT SUPPORTED)
+//
+// You can also use parantheses:
+//   "HillasDource.fDist / (MHillas.fLength + MHillas.fWidth)"
+//
+// Additional implementations:
+//
+//   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
+// ---------
+//
+// Most constants you might need can be found in TMath, eg:
+//  TMath::Pi(), TMath::TwoPi(), TMath::Ln10(), TMath::LogE()
+//  TMath::RadToDeg(), TMath::DegToRad();
+//
+//
+// 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(), eg
+//   [0]*MHillas.fArea
+//
+//
+// Multi-argument functions
+// ------------------------
+// You can use multi-argument functions, too. Example:
+//   "TMath::Hypot(MHillas.fMeanX, MHillas.MeanY)"
+//   "pow(MHillas.fMeanX*MHillas.MeanY, -1.2)"
+//
+//
+//
+// To Do:
+//  - The possibility to use other objects inheriting from MData
+//    is missing.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataPhrase.h"
+
+#include <TMath.h>
+#include <TArrayI.h>
+#include <TPRegexp.h>
+#include <TFormula.h>
+#if ROOT_VERSION_CODE >= ROOT_VERSION(5,26,00)
+#include <TFormulaPrimitive.h>
+#endif
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayD.h"
+
+#include "MDataValue.h"
+#include "MDataMember.h"
+#include "MDataElement.h"
+
+ClassImp(MDataPhrase);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Check for the existance of the expression [idx] in the string
+// phrase. If existing a corresponding new MDataValue is added to
+// fMembers and index is increased by one.
+//
+// This makes the use of user-defined variables in the phrase possible.
+//
+Int_t MDataPhrase::CheckForVariable(const TString &phrase, Int_t idx)
+{
+    TString mods;
+    TArrayI pos;
+
+    while (1)
+    {
+        // \\A: matches the beginning of the string like ^ does
+        // \\Z: matches the end       of the string like $ does
+        // \\W: matches any non-word character [^a-zA-Z_0-9]
+        TPRegexp reg(Form("(\\A|\\W)\\[0*%d\\](\\W|\\Z)", idx));
+        if (reg.Match(phrase, mods, 0, 130, &pos)==0)
+            break;
+
+        // [idx] already existing. Add a corresponding MDataValue
+        fMembers.AddLast(new MDataValue(0, idx));
+        idx++;
+    }
+
+    return idx;
+}
+
+// --------------------------------------------------------------------------
+//
+// Replace all expressions expr (found by a regular expression \\b%s\\b
+// with %s being the expression) in the string phrase by [idx].
+//
+// The length of [idx] is returned.
+//
+Int_t MDataPhrase::Substitute(TString &phrase, const TString &expr, Int_t idx) const
+{
+    const TString arg = Form("[%d]", idx);
+
+    TPRegexp reg(expr);
+
+    TString mods;
+    TArrayI pos;
+
+    Int_t p = 0;
+    while (1)
+    {
+        // check whether argument is found
+        if (reg.Match(phrase, mods, p, 130, &pos)==0)
+            break;
+
+        // Replace expression by argument [idx]
+        phrase.Replace(pos[0], pos[1]-pos[0], arg, arg.Length());
+
+        // Jump behind the new string which was just inserted
+        p = pos[0]+arg.Length();
+    }
+    return arg.Length();
+}
+
+TString MDataPhrase::Parse(TString phrase)
+{
+    // This is for backward compatibility with MDataChain
+    phrase.ReplaceAll("gRandom->", "TRandom::");
+    phrase.ReplaceAll("kRad2Deg",  "TMath::RadToDeg()");
+    phrase.ReplaceAll("kDeg2Rad",  "TMath::DegToRad()");
+    phrase.ReplaceAll(" ", "");
+
+    int idx=0;
+    int p =0;
+
+    TString mods;
+    TArrayI pos;
+/*
+    // Find all functions...
+    // The first \\w+ should also allow ::
+    TPRegexp reg = TPRegexp("[[:word:]:]+\\([^()]*\\)");
+    while (1)
+    {
+        //idx = CheckForVariables(phrase, idx);
+
+        if (reg.Match(phrase, mods, p, 130, &pos)==0)
+            break;
+
+        const Int_t len = pos[1]-pos[0];
+
+        // This is the full function with its argument(s)
+        const TString term = phrase(pos[0], len);
+
+        // Now get rid of the argument(s)
+        const TPRegexp reg3("\\([^()]+\\)");
+
+        TString func(term);
+        reg3.Substitute(func, "");
+
+        // Seems to be a special case whic is not handles by
+        // TFormulaPrimitive by known by TFormula
+        if (func.BeginsWith("TRandom::"))
+        {
+            p = pos[0]+pos[1];
+            continue;
+        }
+
+        // check whether the function is available
+        if (TFormulaPrimitive::FindFormula(func))
+        {
+            p = pos[0]+pos[1];
+            continue;
+        }
+
+        cout << "Unknown: " << func  << endl;
+        // p = pos[0]+pos[1];
+        return;
+    }
+*/
+
+    p   = 0;
+
+    // Find all data-members in expression such as
+    // MTest.fDataMember. Because also floating point
+    // numbers can contain a dot the result has to
+    // be checked carefully
+    // \\w: matches any word character [a-zA-Z_0-9]
+    TPRegexp reg = TPRegexp("\\w+[.]\\w+");
+    TPRegexp ishex("^0x[[:xdigit:]]+$");
+
+    while (1)
+    {
+        // If some indices are already existing
+        // initialize them by a flexible MDataValue
+        idx = CheckForVariable(phrase, idx);
+
+        // Check whether expression is found
+        if (reg.Match(phrase, mods, p, 130, &pos)==0)
+            break;
+
+        // Get expression from phrase
+        const TString expr = phrase(pos[0], pos[1]-pos[0]);
+
+        // Also hex-numbers and floats fullfill our condition...
+        // FIXME: WHY HEX NUMBERS?
+        if (!expr(ishex).IsNull() || expr.IsFloat())
+        {
+            p = pos[1];
+            continue;
+        }
+
+        // Add a corresponding MDataMember to our list
+        fMembers.AddLast(new MDataMember(expr));
+
+        // Find other occurances of arg by this regexp
+        // and start next search behind first match
+        const TString regexp = Form("\\b%s\\b", expr.Data());
+        p = pos[0] + Substitute(phrase, regexp, idx);
+
+        // Step forward to the next argument
+        idx++;
+    }
+
+    p = 0;
+
+    // Now check for matrix elemets as M[5]
+    reg = TPRegexp("\\w+\\[\\d+\\]");
+    while (1)
+    {
+        // If some indices are already existing
+        // initialize them by a MDataValue
+        idx = CheckForVariable(phrase, idx);
+
+        // Check whether expression is found
+        if (reg.Match(phrase, mods, p, 130, &pos)==0)
+            break;
+
+        // Get expression from phrase
+        TString expr = phrase(pos[0], pos[1]-pos[0]);
+
+        // Add a corresponding MDataMember to our list
+        fMembers.AddLast(new MDataElement(expr));
+
+        // Make the expression "Regular expression proofed"
+        expr.ReplaceAll("[", "\\[");
+        expr.ReplaceAll("]", "\\]");
+
+        // Find other occurances of arg by this regexp
+        // and start next search behind first match
+        const TString regexp = Form("\\b%s", expr.Data());
+        p = pos[0] + Substitute(phrase, regexp, idx);
+
+        // Step forward to the next argument
+        idx++;
+    }
+    /*
+
+    // * HOW DO WE PROCESS THE FILTERS?
+    // * DO WE NEED THIS FOR MData derived classes? Is there any need for it?
+    // * MAYBE FIRST FILTERS (MF?) MUST REPLACE {name[class]} BEFORE
+    //   THE DATA PHRASSE IS CREATED?
+    // --> MFDataPhrase must have a list of MFilter. In Process first
+    //     all self created MFilter are processed (see MF). Then
+    //     they are evaluated and the result is given to the MDataPhrase.
+    //     Can this be done using MDataMember? We replace {Name[class]}
+    //     by Name.IsExpressionTrue and we need a way that MDataPhrase
+    //     gets the coresponding pointer.
+    // --> Alternatively we can create a MDataPhrase which allows
+    //     Pre/Processing
+    //
+    // We convert {Name[Class]} to Name.IsExpressionTrue. To process these
+    // data/filters we need a request from MFDataPhrase (new virtual
+    // memeber function?)
+    //
+    // {} Is alreaqdy used in ReadEnv.
+    //
+    // Enhance ReadEnv to allow Cut1.5 to be just a class.
+    //
+    // The difference between MFDataPhrase is
+    //   MFDataPhrase only knows MDataPhrase, while
+    //   MF also knows a filter-class.
+    //
+
+    p = 0;
+
+    // And now we check for other phrases or filters
+    // They are defined by a [, a pribtable character and
+    // any numer of word characters (a-zA-Z0-9_) and a closing ]
+    reg = TPRegexp("{[A-Za-z}\\w+(\\[[A-Za-z]\\w+\\])?}");
+    while (1)
+    {
+        // If some indices are already existing
+        // initialize them by a MDataValue
+        idx = CheckForVariable(phrase, idx);
+
+        // Check whether expression is found
+        if (reg.Match(phrase, mods, p, 130, &pos)==0)
+            break;
+
+        // Get expression from phrase
+        TString expr = phrase(pos[0], pos[1]-pos[0]);
+
+        // Zerlegen: {Name[Class]}
+
+        // Create a new MData object of kind
+        MData *dat = (MData*)GetNewObject(cls, MData::Class());
+        if (!dat)
+            return "";
+        dat->SetName(name);
+
+        // Add a corresponding MDataMember to our list
+        fMembers.AddLast(dat);
+
+        // Make the expression "Regular expression proofed"
+        expr.ReplaceAll("[", "\\[");
+        expr.ReplaceAll("]", "\\]");
+
+        // Find other occurances of arg by this regexp
+        // and start next search behind first match
+        p = pos[0] + Substitute(phrase, expr, idx);
+
+        // Step forward to the next argument
+        idx++;
+    }
+ */
+    // Now we have to check if there are additional indices [idx]
+    // This is mainly important if the rule has indices only!
+    while (1)
+    {
+        const Int_t newidx = CheckForVariable(phrase, idx);
+        if (newidx == idx)
+            break;
+    }
+
+    return phrase;
+}
+
+// --------------------------------------------------------------------------
+//
+// Clear Formula and corresponding data members
+//
+void MDataPhrase::Clear(Option_t *)
+{
+    fMembers.Delete();
+    if (!fFormula)
+        return;
+
+    delete fFormula;
+    fFormula = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a new phrase/rule. Returns kTRUE on sucess, kFALSE otherwise
+//
+Bool_t MDataPhrase::SetRule(const TString &rule)
+{
+    Clear();
+
+    const TString txt=Parse(rule);
+    if (txt.IsNull())
+    {
+        Clear();
+        return kFALSE;
+    }
+
+    fFormula = new TFormula;
+
+    // Must have a name otherwise all axis labels disappear like a miracle
+    fFormula->SetName(fName.IsNull()?"TFormula":fName.Data());
+    if (fFormula->Compile(txt))
+    {
+        *fLog << err << dbginf << "Syntax Error: TFormula::Compile failed..."<< endl;
+        *fLog << " Full Rule:   " << rule << endl;
+        *fLog << " Parsed Rule: " << txt << endl;
+        Clear();
+        return kFALSE;
+    }
+
+    gROOT->GetListOfFunctions()->Remove(fFormula);
+
+    return kTRUE;
+}
+
+namespace MFastFun {
+   //
+   // Namespace with basic primitive functions registered by TFormulaPrimitive
+   // all function registerd by TFormulaPrimitive can be used in TFormula
+   //
+    Double_t Nint(Double_t x){return TMath::Nint(x);}
+    Double_t Sign(Double_t x){return x<0?-1:+1;}
+    Double_t IsNaN(Double_t x){return TMath::IsNaN(x);}
+    Double_t Finite(Double_t x){return TMath::Finite(x);}
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Set a rule (phrase), see class description for more
+// details. Set a name and title. If no title is given it is set to the rule.
+//
+MDataPhrase::MDataPhrase(const char *rule, const char *name, const char *title) : fFormula(0)
+{
+    // More in TFormulaPrimitive.cxx
+    // More in TFormulaMathInterface
+    if (!TFormulaPrimitive::FindFormula("isnan"))
+    {
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("log2",   "log2",   (TFormulaPrimitive::GenFunc10)TMath::Log2));
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("fabs",   "fabs",   (TFormulaPrimitive::GenFunc10)TMath::Abs));
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("floor",  "floor",  (TFormulaPrimitive::GenFunc10)TMath::Floor));
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("ceil",   "ceil",   (TFormulaPrimitive::GenFunc10)TMath::Ceil));
+
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("nint",   "nint",   (TFormulaPrimitive::GenFunc10)MFastFun::Nint));
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("round",  "round",  (TFormulaPrimitive::GenFunc10)MFastFun::Nint));
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("sgn",    "sgn",    (TFormulaPrimitive::GenFunc10)MFastFun::Sign));
+
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("isnan",  "isnan",  (TFormulaPrimitive::GenFunc10)MFastFun::IsNaN));
+        TFormulaPrimitive::AddFormula(new TFormulaPrimitive("finite", "finite", (TFormulaPrimitive::GenFunc10)MFastFun::Finite));
+    }
+
+    //    TFormulaPrimitive is used to get direct acces to the function pointers
+    //    GenFunc     -  pointers  to the static function
+    //    TFunc       -  pointers  to the data member functions
+    //
+    //    The following sufixes are currently used, to describe function arguments:
+    //    ------------------------------------------------------------------------
+    //    G     - generic layout - pointer to double (arguments), pointer to double (parameters)
+    //    10    - double
+    //    110   - double, double
+    //    1110  - double, double, double
+
+    fName  = name  ? name  : "MDataPhrase";
+    fTitle = title ? title : rule;
+
+    fMembers.SetOwner();
+
+    if (rule)
+        SetRule(rule);
+}
+
+// --------------------------------------------------------------------------
+//
+//   Destructor
+//
+MDataPhrase::~MDataPhrase()
+{
+    if (fFormula)
+        delete fFormula;
+}
+
+// --------------------------------------------------------------------------
+//
+//   CopyConstructor
+//
+MDataPhrase::MDataPhrase(MDataPhrase &ts)
+{
+    TFormula *f = ts.fFormula;
+
+    fName  = "MDataPhrase";
+    fTitle = f ? f->GetExpFormula() : (TString)"";
+
+    fFormula = f ? (TFormula*)f->Clone() : 0;
+    gROOT->GetListOfFunctions()->Remove(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.
+//
+Double_t MDataPhrase::Eval(const Double_t *x) const
+{
+    const Int_t n = fMembers.GetEntriesFast();
+
+    if (fMembers.GetSize()<n)
+    {
+        *fLog << err << "ERROR - MDataPhrase::GetValue: Size mismatch!" << endl;
+        return 0;
+    }
+
+    // This is to get rid of the cost-qualifier for this->fStorage
+    Double_t *arr = fStorage.GetArray();
+
+    // Evaluate parameters (the access with TObjArray::UncheckedAt is
+    // roughly two times faster than with a TIter and rougly three
+    // times than accessing a TOrdCollection. However this might still
+    // be quite harmless compared to the time needed by GetValue)
+    for (Int_t i=0; i<n; i++)
+        arr[i] = static_cast<MData*>(fMembers.UncheckedAt(i))->GetValue();
+
+    // Evaluate function
+    return fFormula->EvalPar(x, arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns kTRUE if all members of fMemebers are valid and fFormula!=NULL
+//
+Bool_t MDataPhrase::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 MDataPhrase::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 MDataPhrase::PreProcess(const MParList *plist)
+{
+    if (!fFormula)
+    {
+        *fLog << err << "Error - So far no valid phrase was setup." << endl;
+        return kFALSE;
+    }
+
+    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;
+        }
+
+    // For speed reasons MArrayD instead of TArrayD is used
+    // (no range check is done when accessing). The storage is
+    // allocated (Set) only when its size is changing. If GetValue
+    // is called many times this should improve the speed significantly
+    // because the necessary memory is already allocated and doesn't need
+    // to be freed. (Just a static variable is not enough, because there
+    // may be several independant objects of this class)
+    fStorage.Set(fMembers.GetSize());
+
+    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 MDataPhrase::GetRule() const
+{
+    if (!fFormula)
+        return "<empty>";
+
+    TString rule = fFormula->GetTitle(); //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;
+}
+
+// --------------------------------------------------------------------------
+//
+// This returns the rule as seen/interpreted by the TFormula. Mainly
+// for debugging purposes
+//
+TString MDataPhrase::GetRuleRaw() const
+{
+    if (!fFormula)
+        return "<empty>";
+
+    return fFormula->GetExpFormula();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the value converted to a Bool_t
+//
+Bool_t MDataPhrase::GetBool() const
+{
+    return TMath::Nint(GetValue())!=0;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MDataPhrase::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 MDataPhrase::SetVariables(const TArrayD &arr)
+{
+    fMembers.R__FOR_EACH(MData, SetVariables)(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup data phrase.
+//
+// Assuming your MDataChain is called (Set/GetName): MyData
+//
+// Now setup the condition, eg:
+//     MyData.Rule: log10(MHillas.fSize)
+// or
+//     MyData.Rule: log10(MHillas.fSize) - 4.1
+//
+// If you want to use more difficult rules you can split the
+// condition into subrules. Subrules are identified
+// by {}-brackets. Avoid trailing 0's! For example:
+//
+//     MyData.Rule: log10(MHillas.fSize) + {0} - {1}
+//     MyData.0: 5.5*MHillas.fSize
+//     MyData.1: 2.3*log10(MHillas.fSize)
+//
+// The numbering must be continous and start with 0. You can use
+// a subrules more than once. All {}-brackets are simply replaced
+// by the corresponding conditions. The rules how conditions can
+// be written can be found in the class description of MDataChain.
+//
+Int_t MDataPhrase::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (!IsEnvDefined(env, prefix, "Rule", print))
+        return rc;
+
+    TString rule = GetEnvValue(env, prefix, "Rule", "");
+
+    Int_t idx=0;
+    while (1)
+    {
+        TString cond;
+        if (IsEnvDefined(env, prefix, Form("%d", idx), print))
+        {
+            cond += "(";
+            cond += GetEnvValue(env, prefix, Form("%d", idx), "");
+            cond += ")";
+        }
+
+        if (cond.IsNull())
+            break;
+
+        rule.ReplaceAll(Form("{%d}", idx), cond);
+        idx++;
+    }
+
+    if (rule.IsNull())
+    {
+        *fLog << warn << "MDataPhrase::ReadEnv - ERROR: Empty rule found." << endl;
+        return kERROR;
+    }
+
+    if (!SetRule(rule))
+        return kERROR;
+
+    if (print)
+        *fLog << inf << "found: " << GetRule() << endl;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mdata/MDataPhrase.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataPhrase.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataPhrase.h	(revision 17960)
@@ -0,0 +1,67 @@
+#ifndef MARS_MDataPhrase
+#define MARS_MDataPhrase
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TFormula;
+class MParList;
+
+class MDataPhrase : public MData
+{
+private:
+    TFormula *fFormula;  // TFormula (its a pointer to be able to have no expression)
+    TObjArray fMembers;	 // List of arguments
+
+    MArrayD   fStorage;  //! Temporary storage used in GetValue (only!)
+
+    Int_t   CheckForVariable(const TString &phrase, Int_t idx);
+    Int_t   Substitute(TString &phrase, const TString &expr, Int_t idx) const;
+    TString Parse(TString phrase);
+
+public:
+    MDataPhrase(const char *rule=0, const char *name=0, const char *title=0);
+    MDataPhrase(MDataPhrase &ts);
+    ~MDataPhrase();
+
+    // TObject
+    void     Clear(Option_t *o="");
+
+    // MParContainer
+    Bool_t   IsReadyToSave() const;
+    void     SetVariables(const TArrayD &arr);
+    Int_t    ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MData
+    Bool_t   IsValid() const;
+    Bool_t   HasValidRule() const { return fFormula ? kTRUE : kFALSE; }
+    Double_t GetValue() const { return Eval((Double_t*)NULL); }
+    Double_t Eval(const Double_t *x) const;
+    Double_t Eval(Double_t x, Double_t y=0, Double_t z=0, Double_t t=0) const
+    {
+        const Double_t xx[4] = { x, y, z, t };
+        return Eval(xx);
+    }
+    TString  GetRule() const;
+    TString  GetRuleRaw() const;
+    Bool_t   PreProcess(const MParList *plist);
+    //    void Print(Option_t *opt = "") const;
+    //    TString GetDataMember() const;
+
+    // MDataPhrase
+    Bool_t   GetBool() const;
+    Bool_t   SetRule(const TString &phrase);
+
+    ClassDef(MDataPhrase, 1) // MDataPhrase is basically a mapper for TFormula supporting Mars features
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdata/MDataValue.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataValue.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataValue.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mdata/MDataValue.h
===================================================================
--- branches/Mars_McMismatchStudy/mdata/MDataValue.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/MDataValue.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mdata/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mdata/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdata/Makefile	(revision 17960)
@@ -0,0 +1,34 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mhbase
+
+CINT     = Data
+
+SRCFILES = MData.cc \
+	   MDataPhrase.cc \
+	   MDataArray.cc \
+           MDataElement.cc \
+	   MDataMember.cc \
+	   MDataValue.cc \
+	   MDataList.cc \
+	   MDataChain.cc \
+           MDataFormula.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
+
Index: branches/Mars_McMismatchStudy/mdrs/DrsLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/DrsLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/DrsLinkDef.h	(revision 17960)
@@ -0,0 +1,19 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MDrsCalibApply+;
+#pragma link C++ class MDrsCalibResult+;
+
+#pragma link C++ class MDrsCalibration+;
+#pragma link C++ class MDrsCalibrationTime+;
+
+#pragma link C++ class MHDrsCalibration+;
+#pragma link C++ class MHDrsCalibrationTime+;
+#pragma link C++ class MHDrsCalibrationCheck+;
+
+#pragma link C++ class MCalibrateDrsTimes+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mdrs/MCalibrateDrsTimes.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MCalibrateDrsTimes.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MCalibrateDrsTimes.cc	(revision 17960)
@@ -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 2013 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2013
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrateDrsTimes
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateDrsTimes.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MSignalCam.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"
+
+#include "MDrsCalibrationTime.h"
+
+ClassImp(MCalibrateDrsTimes);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrateDrsTimes::MCalibrateDrsTimes(const char *name, const char *title) 
+    : fRunHeader(NULL), fCalib(NULL), fBadPixels(NULL), fSignals(NULL),
+    fArrivalTime(NULL), fArrivalTimeU(NULL), fNameArrivalTime("MArrivalTimeCam"),
+    fNameCalibrated("MSignalCam"), fNameUncalibrated(""), fIsTimeMarker(kFALSE)
+{
+    fName  = name  ? name  : "MCalibrateDrsTimes";
+    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
+//
+Int_t MCalibrateDrsTimes::PreProcess(MParList *pList)
+{
+    fSignals = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber(fNameArrivalTime), "MArrivalTimeCam");
+    if (!fSignals)
+    {
+        *fLog << err << AddSerialNumber("MArrivalTimeCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    fRaw = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRaw)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+        *fLog << warn << AddSerialNumber("MBadPixelsCam") << " not found ... ignoring." << endl;
+
+    fCalib = (MDrsCalibrationTime*)pList->FindObject("MDrsCalibrationTime");
+    if (!fCalib)
+        *fLog << warn << "MDrsCalibrationTime not found... no calibratuon will be applied." << endl;
+
+    fArrivalTime = (MSignalCam*)pList->FindCreateObj(AddSerialNumber("MSignalCam"), fNameCalibrated);
+    if (!fArrivalTime)
+        return kFALSE;
+
+    if (!fNameUncalibrated.IsNull())
+    {
+        fArrivalTimeU = (MSignalCam*)pList->FindCreateObj("MSignalCam", fNameUncalibrated);
+        if (!fArrivalTimeU)
+            return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Bool_t MCalibrateDrsTimes::ReInit(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << AddSerialNumber("MRawRunHeader") << " not found ... aborting." << endl;
+        return kFALSE;
+    }
+
+    fFreq = fRunHeader->GetFreqSampling();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the calibration factors to the extracted signal according to the 
+// selected calibration method
+//
+Int_t MCalibrateDrsTimes::Process()
+{
+    const UInt_t npix = fSignals->GetSize();
+
+    const UShort_t *idx = fRaw->GetPixelIds();
+    const int16_t  *start = reinterpret_cast<int16_t*>(fRaw->GetStartCells());
+
+    for (UInt_t hw=(fIsTimeMarker?8:0); hw<npix; hw+=(fIsTimeMarker?9:1))
+    //for (UInt_t hw=8; hw<npix; hw+=9)
+    {
+        const UInt_t sw = idx[hw];
+
+        if (start[hw]<0)
+        {
+            if (fBadPixels)
+                (*fBadPixels)[sw].SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+            continue;
+        }
+
+        if (fBadPixels && !fIsTimeMarker && (*fBadPixels)[sw].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            continue;
+
+        const Float_t signal = (*fSignals)[sw].GetArrivalTime();
+        const Float_t offset = fCalib ? fCalib->GetOffset(hw, start[hw], signal) : 0;
+        const Float_t delay  = fCalib ? fCalib->GetDelay(sw) : 0;
+
+        //if (fIsTimeMarker)
+        //    offset = fCalib ? fCalib->GetDelay(hw, start[hw], signal) : 0;
+
+        // convert from slices to ns
+        const Float_t utime = 1000*(signal       )/fFreq-delay; // [ns]
+        const Float_t time  = 1000*(signal-offset)/fFreq-delay; // [ns]
+
+        /*
+        (*fArrivalTime)[sw].SetArrivalTime(time);
+        if (fArrivalTimeU)
+            (*fArrivalTimeU)[sw].SetArrivalTime(utime);
+            */
+
+        for (UInt_t j=hw-(fIsTimeMarker?8:0); j<=hw; j++)
+        {
+            (*fArrivalTime)[idx[j]].SetArrivalTime(time);
+            if (fArrivalTimeU)
+                (*fArrivalTimeU)[idx[j]].SetArrivalTime(utime);
+        }
+    }
+
+    fArrivalTime->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mdrs/MCalibrateDrsTimes.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MCalibrateDrsTimes.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MCalibrateDrsTimes.h	(revision 17960)
@@ -0,0 +1,52 @@
+#ifndef MARS_MCalibrateDrsTimes
+#define MARS_MCalibrateDrsTimes
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+class MDrsCalibrationTime;
+class MArrivalTimeCam;
+class MRawRunHeader;
+class MRawEvtData;
+class MSignalCam;
+
+class MCalibrateDrsTimes : public MTask
+{
+private:
+    MRawRunHeader       *fRunHeader;
+    MRawEvtData         *fRaw;
+    MDrsCalibrationTime *fCalib; // Calibration rel. time constants
+    MBadPixelsCam       *fBadPixels;    // Bad Pixels information
+    MArrivalTimeCam     *fSignals;      // Extracted Arrival Time
+    MSignalCam          *fArrivalTime;  // Calibrated arrival times
+    MSignalCam          *fArrivalTimeU; // Uncalibrated arrival times
+
+    UShort_t fFreq;                        //! [MHz] Sampling Frequency
+
+    TString fNameArrivalTime;
+    TString fNameCalibrated;
+    TString fNameUncalibrated;
+
+    Bool_t fIsTimeMarker;
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MCalibrateDrsTimes(const char *name=NULL, const char *title=NULL);
+
+    void SetNameArrivalTime(const char *name) { fNameArrivalTime = name; }
+    void SetNameCalibrated(const char *name) { fNameCalibrated = name; }
+    void SetNameUncalibrated(const char *name) { fNameUncalibrated = name; }
+
+    void SetTimeMarker(Bool_t tm=kTRUE) { fIsTimeMarker = tm; }
+
+    ClassDef(MCalibrateDrsTimes, 0)   // Task to calculate calibrated relative arrival times
+};
+ 
+
+#endif
Index: branches/Mars_McMismatchStudy/mdrs/MDrsCalibApply.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MDrsCalibApply.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MDrsCalibApply.cc	(revision 17960)
@@ -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, 2013<mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2013
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MDrsCalibApply
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MDrsCalibApply.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MArrayB.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MDrsCalibration.h"
+#include "MPedestalSubtractedEvt.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MDrsCalibApply);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MDrsCalibApply::MDrsCalibApply(const char *name, const char *title)
+    : fRawEvt(NULL), fDrsCalib(NULL), fSignal(NULL), fResult(0),
+    fMaxNumPrevEvents(5), fRemoveSpikes(3), fSlidingAverage(0)
+{
+    fName  = name  ? name  : "MDrsCalibApply";
+    fTitle = title ? title : "Class to subtract pedestal";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MDrsCalibApplyedEvt
+//
+Int_t MDrsCalibApply::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fDrsCalib = (MDrsCalibration*)pList->FindObject("MDrsCalibration");
+    if (!fDrsCalib)
+        *fLog << warn << "No DRS calibration container (MDrsCalibration) found... skipping." << endl;
+
+    else
+        *fLog << inf << "DRS calibration will be applied." << endl;
+
+    fResult = 0;
+    if (fMaxNumPrevEvents>0)
+    {
+        fPrevStart.clear();
+        fResult = (MDrsCalibResult*)pList->FindCreateObj("MDrsCalibResult");
+        if (!fResult)
+            return kFALSE;
+    }
+
+    fSignal = (MPedestalSubtractedEvt*)pList->FindCreateObj("MPedestalSubtractedEvt");//, AddSerialNumber(fNamePedestalSubtractedEvt));
+    if (!fSignal)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Bool_t MDrsCalibApply::ReInit(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fDrsCalib)
+        return kTRUE;
+
+    if (fDrsCalib->fRoi>0 && fDrsCalib->fRoi != fRunHeader->GetNumSamplesHiGain())
+    {
+        *fLog << warn << "Slice number of DRS calibration " << fDrsCalib->fRoi << " and run-header " << fRunHeader->GetNumSamplesHiGain() << " don't match...\n";
+        *fLog << "secondary baseline correction will not be applied." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MDrsCalibApply::Process()
+{
+    // Please note:
+    //   - for data with only hi-gain samples numl is 0
+    //   - for data with hi- and lo-gain samples
+    //     numl is 0 if read from a raw-data file or a new MC root-file(?)
+    //     numl is not 0 if read from an old MC root-file
+
+    // Total number of samples
+    const Int_t roi = fRawEvt->GetNumHiGainSamples();
+
+    // Check if event is empty (presumably MC event -- sanity check)
+    if (roi==0)
+        return kCONTINUE;
+
+    // Check for consistency (our simulation can do weird things!)
+    if (roi!=fRunHeader->GetNumSamplesHiGain())
+    {
+        *fLog << err << "MDrsCalibApply::Process: ERROR - Number of samples in event ";
+        *fLog << "(hi=" << roi << ")" << endl << " doesn't match number in run-header ";
+        *fLog << "(" << fRunHeader->GetNumSamplesHiGain() << ")" << endl;
+        *fLog << " In case you are processing real data you have just found a bug." << endl;
+        *fLog << " If you process Monte Carlo data, it means probably that the length" << endl;
+        *fLog << " of the arrays in MRawEvtData are inconsistent with the run-header." << endl;
+        return kERROR;
+    }
+
+    if (fRawEvt->GetNumLoGainSamples()+fRunHeader->GetNumSamplesLoGain()>0)
+    {
+        *fLog << err << "MDrsCalibApply::Process: ERROR - Data must not contain lo gain slices." << endl;
+        return kERROR;
+    }
+
+    // initialize fSignal
+    fSignal->InitSamples(roi);
+
+    if (!fDrsCalib)  // FIXME: Do a fake (none) calibration
+        return kTRUE;
+
+    const int16_t *val = reinterpret_cast<int16_t*>(fRawEvt->GetSamples());
+
+    const int32_t *offset = fDrsCalib->fOffset.data();
+    const int64_t *gain   = fDrsCalib->fGain.data();
+    const int64_t *trgoff = fDrsCalib->fTrgOff.data();
+
+    const uint64_t scaleabs  = fDrsCalib->fNumOffset;
+    const uint64_t scalegain = fDrsCalib->fNumGain;
+    const uint64_t scalerel  = fDrsCalib->fNumTrgOff;
+
+    const int16_t *start = reinterpret_cast<int16_t*>(fRawEvt->GetStartCells());
+
+    Float_t *vec = fSignal->GetSamples(0);
+
+    const UShort_t *idx = fRawEvt->GetPixelIds();
+    for (size_t ch=0; ch<fRawEvt->GetNumPixels(); ch++)
+    {
+        const size_t drs = ch*1024;
+        const size_t hw  = ch*roi;
+        const size_t sw  = idx[ch]*roi;
+
+        DrsCalibrate::ApplyCh(vec+sw, val+hw, start[ch], roi,
+                              offset+drs, scaleabs,
+                              gain  +drs, scalegain,
+                              trgoff+hw,  scalerel);
+    }
+
+    if (fResult)
+    {
+        fResult->fData.resize(fPrevStart.size()*2);
+
+        int i=0;
+        for (auto it=fPrevStart.begin(); it!=fPrevStart.end(); it++)
+        {
+            fResult->fData[i++] = DrsCalibrate::CorrectStep(vec, fRawEvt->GetNumPixels(), roi, it->data(), start, roi+10, idx);
+            fResult->fData[i++] = DrsCalibrate::CorrectStep(vec, fRawEvt->GetNumPixels(), roi, it->data(), start, 3,      idx);
+        }
+
+        fPrevStart.push_front(vector<Short_t>(start, start+fRawEvt->GetNumPixels()));
+        if (fPrevStart.size()>fMaxNumPrevEvents)
+            fPrevStart.pop_back();
+    }
+
+    switch (fRemoveSpikes)
+    {
+    case 1:
+        for (size_t ch=0; ch<fRawEvt->GetNumPixels(); ch++)
+            DrsCalibrate::RemoveSpikes(vec+ch*roi, roi);
+        break;
+    case 2:
+        for (size_t ch=0; ch<fRawEvt->GetNumPixels(); ch++)
+            DrsCalibrate::RemoveSpikes2(vec+ch*roi, roi);
+        break;
+    case 3:
+        for (size_t ch=0; ch<fRawEvt->GetNumPixels(); ch++)
+            DrsCalibrate::RemoveSpikes3(vec+ch*roi, roi);
+        break;
+    case 4:
+        for (size_t ch=0; ch<fRawEvt->GetNumPixels(); ch++)
+            DrsCalibrate::RemoveSpikes4(vec+ch*roi, roi);
+        break;
+    }
+
+
+    if (fSlidingAverage)
+        DrsCalibrate::SlidingAverage(vec, roi, fSlidingAverage);
+
+    fSignal->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mdrs/MDrsCalibApply.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MDrsCalibApply.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MDrsCalibApply.h	(revision 17960)
@@ -0,0 +1,65 @@
+#ifndef MARS_MDrsCalibApply
+#define MARS_MDrsCalibApply
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_DrsCalib
+#include "DrsCalib.h"
+#endif
+
+#include <list>
+
+class MRawRunHeader;
+class MRawEvtData;
+class MPedestalSubtractedEvt;
+class MDrsCalibration;
+
+class MDrsCalibResult: public MParContainer
+{
+    friend class MDrsCalibApply;
+
+public:
+    std::vector<DrsCalibrate::Step> fData;
+
+    MDrsCalibResult()
+    {
+        fName = "MDrsCalibResult";
+    }
+
+    const std::vector<DrsCalibrate::Step> &GetData() const { return fData; }
+
+    ClassDef(MDrsCalibResult, 0)
+};
+
+class MDrsCalibApply : public MTask
+{
+private:
+    MRawRunHeader          *fRunHeader;      //! Run Header
+    MRawEvtData            *fRawEvt;         //! Input Raw data
+    MDrsCalibration        *fDrsCalib;       //! DRS4 calibration data
+    MPedestalSubtractedEvt *fSignal;         //! Output container
+    MDrsCalibResult        *fResult;         //! Output container
+
+    std::list<std::vector<Short_t>> fPrevStart; //! History for start cells of previous events
+
+    UShort_t fMaxNumPrevEvents;
+    UShort_t fRemoveSpikes;
+    UShort_t fSlidingAverage;
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MDrsCalibApply(const char *name=NULL, const char *title=NULL);
+
+    void SetMaxNumPrevEvents(UShort_t n)  { fMaxNumPrevEvents = n; }
+    void SetRemoveSpikes(int typ=1) { fRemoveSpikes = typ; }
+    void SetSlidingAverage(UShort_t w) { fSlidingAverage = w; }
+
+    ClassDef(MDrsCalibApply, 0)   // Class to subtract pedestal including AB-noise
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdrs/MDrsCalibration.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MDrsCalibration.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MDrsCalibration.cc	(revision 17960)
@@ -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  07/2011 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2013
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHDrsCalibration
+//
+// This class contains a list of MHFadcPix.
+//
+///////////////////////////////////////////////////////////////////////
+#include "MDrsCalibration.h"
+
+#include <fstream>
+#include <sstream>
+#include <limits.h>
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MGeomCam.h"
+
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MHCamera.h"
+
+#include <TH2.h>
+
+ClassImp(MDrsCalibration);
+
+using namespace std;
+
+void MDrsCalibration::Plot()
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    //AppendPad();
+
+    pad->Divide(2,2);
+
+    MH::SetPalette();
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetRightMargin(0.15);
+
+    TH2F h1("Physcial", "Primary baseline (physical pipeline)", 1440, -0.5, 1439.5, 1024, -0.5, 1023.5);
+    h1.SetStats(kFALSE);
+    h1.SetXTitle("Pixel");
+    h1.SetYTitle("Cell");
+    h1.SetZTitle("mV");
+    h1.GetYaxis()->SetTitleOffset(1.2);
+    h1.GetZaxis()->SetTitleOffset(1.2);
+    for (int p=0; p<1440; p++)
+        for (int c=0; c<1024; c++)
+            h1.SetBinContent(p+1, c+1, fOffset[p*1024+c]);
+    h1.Scale(125./fNumOffset/256);
+    h1.DrawCopy("colz");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetRightMargin(0.15);
+
+    TH2F h2("Gain", "Gain measurement (physcial pipeline)", 1440, -0.5, 1439.5, 1024, -0.5, 1023.5);
+    h2.SetStats(kFALSE);
+    h2.SetXTitle("Pixel");
+    h2.SetYTitle("Cell");
+    h2.SetZTitle("mV");
+    h2.GetYaxis()->SetTitleOffset(1.2);
+    h2.GetZaxis()->SetTitleOffset(1.2);
+    for (int p=0; p<1440; p++)
+        for (int c=0; c<1024; c++)
+            h2.SetBinContent(p+1, c+1, fGain[p*1024+c]);
+    h2.Scale(125.*1953125/(fNumOffset*fNumGain)/256/1024);
+    h2.DrawCopy("colz");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetRightMargin(0.15);
+
+    TH2F h3("Logical", "Secondary baseline (logical pipeline)", 1440, -0.5, 1439.5, fRoi, -0.5, fRoi-0.5);
+    h3.SetStats(kFALSE);
+    h3.SetXTitle("Pixel");
+    h3.SetYTitle("Channel");
+    h3.SetZTitle("mV");
+    h3.GetYaxis()->SetTitleOffset(1.2);
+    h3.GetZaxis()->SetTitleOffset(1.2);
+    for (int p=0; p<1440; p++)
+        for (int c=0; c<fRoi; c++)
+            h3.SetBinContent(p+1, c+1, fTrgOff[p*fRoi+c]);
+    h3.Scale(125./(fNumOffset*fNumTrgOff)/256);
+    h3.GetYaxis()->SetRangeUser(4, fRoi-4);
+    h3.DrawCopy("colz");
+
+    pad->cd(4);
+    gPad->SetFrameBorderMode(0);
+}
Index: branches/Mars_McMismatchStudy/mdrs/MDrsCalibration.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MDrsCalibration.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MDrsCalibration.h	(revision 17960)
@@ -0,0 +1,49 @@
+#ifndef MARS_MDrsCalibration
+#define MARS_MDrsCalibration
+
+// -------------------------------------------------------------------
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TSystem
+#include <TSystem.h>
+#endif
+
+#ifndef MARS_MLogManip
+#include "MLogManip.h"
+#endif
+
+#ifndef MARS_DrsCalib
+#include "DrsCalib.h"
+#endif
+
+
+class MDrsCalibration : public MParContainer, public DrsCalibration
+{
+public:
+    MDrsCalibration(const char *name=0, const char *title=0)
+    {
+        fName  = name  ? name  : "MDrsCalibration";
+        fTitle = title ? title : "";
+    }
+
+    bool ReadFits(TString str)
+    {
+        gSystem->ExpandPathName(str);
+
+        const std::string msg = ReadFitsImp(str.Data());
+        if (msg.empty())
+            return true;
+
+        *fLog << err << msg << std::endl;
+        return false;
+    }
+
+    void Plot();
+
+    ClassDef(MDrsCalibration, 1)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdrs/MDrsCalibrationTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MDrsCalibrationTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MDrsCalibrationTime.cc	(revision 17960)
@@ -0,0 +1,49 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2013 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2013
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHDrsCalibration
+//
+///////////////////////////////////////////////////////////////////////
+#include "MDrsCalibrationTime.h"
+
+#include <TH1.h>
+
+ClassImp(MDrsCalibrationTime);
+
+using namespace std;
+
+bool MDrsCalibrationTime::SetDelays(const TH1 &cam)
+{
+    if (cam.GetDimension()!=1)
+        return false;
+
+    fDelays.assign(cam.GetNbinsX(), 0);
+
+    for (int i=0; i<cam.GetNbinsX(); i++)
+        fDelays[i] = cam.GetBinContent(i+1);
+
+    return true;
+}
Index: branches/Mars_McMismatchStudy/mdrs/MDrsCalibrationTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MDrsCalibrationTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MDrsCalibrationTime.h	(revision 17960)
@@ -0,0 +1,53 @@
+#ifndef MARS_MDrsCalibrationTime
+#define MARS_MDrsCalibrationTime
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_DrsCalib
+#include "DrsCalib.h"
+#endif
+
+class TH1;
+
+class MDrsCalibrationTime : public MParContainer, public DrsCalibrateTime
+{
+    std::vector<double> fDelays;
+
+public:
+    MDrsCalibrationTime(const char *name=0, const char *title=0)
+    {
+        fName  = name ? name : "MDrsCalibrationTime";
+        fTitle = title ? title : "";
+    }
+
+    void InitSize(uint16_t channels, uint16_t samples)
+    {
+        //fDelays.clear();
+        //fDelays.resize(channels);
+
+        DrsCalibrateTime::InitSize(channels, samples);
+    }
+
+    void SetCalibration(const DrsCalibrateTime &cal)
+    {
+        *static_cast<DrsCalibrateTime*>(this) = cal;
+    }
+
+    bool SetDelays(const TH1 &cam);
+
+    double GetOffset(int hw, int spos, float tm) const
+    {
+        return Offset(hw/9, fmod(tm+spos, 1024)) - Offset(hw/9, spos);
+    }
+
+    double GetDelay(int sw) const
+    {
+        return fDelays.size()==0 ? 0 : fDelays[sw];
+    }
+
+    ClassDef(MDrsCalibrationTime, 2) // A list of histograms storing the Fadc spektrum of one pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mdrs/MHDrsCalibration.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MHDrsCalibration.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MHDrsCalibration.cc	(revision 17960)
@@ -0,0 +1,385 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 2013 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2013
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHDrsCalibration
+//
+// This class contains a list of MHFadcPix.
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHDrsCalibration.h"
+
+#include <fstream>
+#include <sstream>
+#include <limits.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MGeomCam.h"
+#include "MBinning.h"
+
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MHCamera.h"
+#include "MDrsCalibration.h"
+
+#include <TH2.h>
+#include <TMath.h>
+
+ClassImp(MHDrsCalibration);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  default constructor
+//  creates an a list of histograms for all pixels and both gain channels
+//
+MHDrsCalibration::MHDrsCalibration(const char *name, const char *title) : fRun(0),
+fEvt(0), fResult(0), fBuffer(1440*1024*6+160*1024*2+4),
+fStep(-1), fScale(0), fNumPixels(0), fNumSamples(0)
+{
+    //
+    // set the name and title of this object
+    //
+    fName  = name  ? name  : "MHDrsCalibration";
+    fTitle = title ? title : "Container for ADC spectra histograms";
+
+    for (int i=1024*1440*2+4; i<1024*1440*3+4; i++)
+        fBuffer[i] = 2000./4096; // Set mean to 0.5
+}
+
+// --------------------------------------------------------------------------
+//
+// To setup the object we get the number of pixels from a MGeomCam object
+// in the Parameter list.
+//
+Bool_t MHDrsCalibration::SetupFill(const MParList *pList)
+{
+    fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    switch (++fStep)
+    {
+    case 0:
+        SetTitle("DRS average baseline (physical pipeline);;ADC signal [mV];");
+        break;
+    case 1:
+        SetTitle("DRS average gain (baseline subtracted, physical pipeline);;ADC signal [mV];");
+        break;
+    case 2:
+        SetTitle("DRS average trigger offset (baseline subtracted, logical pipeline);;ADC signal [mV];");
+        break;
+    }
+
+    if (!MHCamEvent::SetupFill(pList))
+        return kFALSE;
+
+    fSum->ResetBit(MHCamera::kProfile);
+
+    fData.Reset();
+
+    fScale = 1;
+
+    *fLog << warn << "WARNING --- oulier detection needed!" << endl;
+
+    return kTRUE;
+}
+
+Bool_t MHDrsCalibration::ReInit(MParList *pList)
+{
+/*    fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }*/
+
+    fEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fEvt)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fEvt->HasStartCells())
+    {
+        *fLog << err << "MRawEvtData has no start cells stored... aborting." << endl;
+        return kFALSE;
+    }
+
+    // FIXME: check consistency...?
+
+    if (fEvt->GetNumPixels()==0 || fEvt->GetNumSamples()==0)
+    {
+        *fLog << err << "MRawEvtData contains either no pixels or no samples... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fStep>=3)
+    {
+        *fLog << err << "DRS calibration already finished." << endl;
+        return kFALSE;
+    }
+
+
+    fData.InitSize(fEvt->GetNumPixels(), fEvt->GetNumSamples());
+
+    fResult = (MDrsCalibration*)pList->FindCreateObj("MDrsCalibration");
+    if (!fResult)
+        return kFALSE;
+
+    if (fStep==1 || fStep==2)
+        fScale = fResult->fNumOffset;
+
+    fNumPixels  = fEvt->GetNumPixels();
+    fNumSamples = fEvt->GetNumSamples();
+
+    if (fStep<2 && fNumSamples!=1024)
+    {
+        *fLog << err << "Only 1024 samples are supported for step " << fStep << "... file has " << fNumSamples << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+Int_t MHDrsCalibration::Fill(const MParContainer *par, const Stat_t w)
+{
+
+    if (fStep==0)
+    {
+        fData.AddRel(reinterpret_cast<int16_t*>(fEvt->GetSamples()),
+                     reinterpret_cast<int16_t*>(fEvt->GetStartCells()));
+    }
+    if (fStep==1)
+    {
+        fData.AddRel(reinterpret_cast<int16_t*>(fEvt->GetSamples()),
+                     reinterpret_cast<int16_t*>(fEvt->GetStartCells()),
+                     fResult->fOffset.data(),
+                     fResult->fNumOffset);
+    }
+    if (fStep==2)
+    {
+        fData.AddAbs(reinterpret_cast<int16_t*>(fEvt->GetSamples()),
+                     reinterpret_cast<int16_t*>(fEvt->GetStartCells()),
+                     fResult->fOffset.data(),
+                     fResult->fNumOffset);
+    }
+
+    /*
+    if (fStep==3)
+    {
+        fData.AddAbs(reinterpret_cast<int16_t*>(fEvt->GetSamples()),
+                     reinterpret_cast<int16_t*>(fEvt->GetStartCells()),
+                     fResult->fOffset.data(),
+                     fResult->fNumOffset);
+    }*/
+
+    return kTRUE;
+}
+
+void MHDrsCalibration::InitHistogram()
+{
+    if (!fEvt)
+        return;
+
+    // Be carefull: the contents of fData are not cloned!
+    pair<vector<double>,vector<double> > p = fData.GetSampleStats();
+
+    vector<double> &mean = p.first;
+    vector<double> &rms  = p.second;
+
+    if (mean.size()==0)
+        return;
+
+    fSum->Reset();
+
+    for (size_t ch=0; ch<fNumPixels; ch++)
+    {
+        double m = 0;
+        double r = 0;
+        for (size_t i=0; i<fNumSamples; i++)
+        {
+            m += mean[ch*fNumSamples+i];
+            r += rms [ch*fNumSamples+i];
+        }
+
+        fSum->AddBinContent(fEvt->GetPixelIds()[ch]+1, m);
+        fSum->SetBinError(fEvt->GetPixelIds()[ch]+1,   r);
+    }
+
+    fSum->Scale(1./fNumSamples/fScale*2000/4096);  // 0.5mV/ADC count
+    fSum->SetEntries(fData.GetNumEntries());
+    fSum->SetAllUsed();
+}
+
+template<typename T>
+Bool_t MHDrsCalibration::CopyData(vector<T> &dest) const
+{
+    const vector<int64_t> &sum = fData.GetSum();
+    dest.resize(sum.size());
+
+    for (size_t ch=0; ch<fNumPixels; ch++)
+        for (size_t i=0; i<fNumSamples; i++)
+        {
+            if (sum[ch*fNumSamples+i]>UINT_MAX)
+            {
+                *fLog << err << "ERROR - Sum over slices exceeded maximum allowed range." << endl;
+                return kFALSE;
+            }
+            dest[ch*fNumSamples+i] = sum[ch*fNumSamples+i];
+        }
+
+    return kTRUE;
+}
+
+Bool_t MHDrsCalibration::Finalize()
+{
+    if (!fResult)
+        return kTRUE;
+
+    fResult->fRoi   = fNumSamples;
+    fResult->fStep  = fStep;
+    fResult->fNumTm = 0;
+
+    // ==========================================================================
+    if (fStep==0)
+    {
+        fResult->fNumOffset = fData.GetNumEntries();
+        if (!CopyData(fResult->fOffset))
+            return kFALSE;
+
+        //--------------------------------------------
+        for (int i=0; i<1024*1440; i++)
+            fResult->fGain[i] = 4096*fData.GetNumEntries();
+
+        // Scale ADC data from 12bit to 2000mV
+        fData.GetSampleStats(fBuffer.data()+4, 2000./4096);
+        reinterpret_cast<uint32_t*>(fBuffer.data())[1] = fRun->GetFileNumber();
+    }
+
+    // ==========================================================================
+    if (fStep==1)
+    {
+        fResult->fNumGain = fData.GetNumEntries();//*fResult->fNumCellOffset;
+        if (!CopyData(fResult->fGain))
+            return kFALSE;
+
+        //---------------------------------------------
+        // DAC:  0..2.5V == 0..65535            2500*50000   625*50000  625*3125
+        // V-mV: 1000                           ----------   ---------  --------
+        //fNumGain *= 2500*50000;                  65536       16384      1024
+        //for (int i=0; i<1024*1440; i++)
+        //    fGain[i] *= 65536;
+        fResult->fNumGain *= 1953125;
+        for (unsigned int i=0; i<fNumPixels*fNumSamples; i++)
+            fResult->fGain[i] *= 1024;
+
+        // Scale ADC data from 12bit to 2000mV
+        fData.GetSampleStats(fBuffer.data()+1024*1440*2+4, 2000./4096/fResult->fNumOffset);//0.5);
+        reinterpret_cast<uint32_t*>(fBuffer.data())[2] = fRun->GetFileNumber();
+    }
+
+    // ==========================================================================
+    if (fStep==2)
+    {
+        fResult->fNumTrgOff = fData.GetNumEntries();//*fResult->fNumCellOffset;
+        if (!CopyData(fResult->fTrgOff))
+            return kFALSE;
+
+        //--------------------------------------------
+        // Scale ADC data from 12bit to 2000mV
+        fData.GetSampleStats(fBuffer.data()+1024*1440*4+4, 2000./4096/fResult->fNumOffset);//0.5);
+        reinterpret_cast<uint32_t*>(fBuffer.data())[0] = fNumSamples;
+        reinterpret_cast<uint32_t*>(fBuffer.data())[3] = fRun->GetFileNumber();
+    }
+
+    // --------------------------------------
+
+    InitHistogram();
+
+    if (fOutputPath.IsNull())
+        return kTRUE;
+
+    const std::string fname(Form("%s/%d_%03d.drs.fits", fOutputPath.Data(),
+                                 fRun->GetRunNumber(), fRun->GetFileNumber()));
+
+    const Bool_t exists = !gSystem->AccessPathName(fname.c_str(), kFileExists);
+    if (exists)
+    {
+        *fLog << err << "File '" << fname << "' already exists." << endl;
+        return kFALSE;
+    }
+
+    const std::string msg = fResult->WriteFitsImp(fname, fBuffer);
+
+    if (msg.empty())
+    {
+        *fLog << inf << "Wrote DRS calibration file " << fname << endl;
+        return kTRUE;
+    }
+
+    *fLog << err << "Error writing to " << fname << ": " << msg << endl;
+    return kFALSE;
+}
+
+void MHDrsCalibration::Paint(Option_t *o)
+{
+    InitHistogram();
+    MHCamEvent::Paint(o);
+}
+
+Short_t MHDrsCalibration::GetNumUnderflows(float lvl) const
+{
+    if (!fResult)
+        return -1;
+
+    short cnt = 0;
+
+    for (int drs=0; drs<160; drs++)
+    {
+        const int p = drs*9*1024;
+
+        double avg = 0;
+        for (int i=0; i<1024*9; i++)
+            avg += fResult->fOffset[p+i];
+
+        avg /= 1024*9*fResult->fNumOffset;
+
+        if (avg/1000<lvl)
+            cnt++;
+    }
+
+    return cnt;
+
+}
Index: branches/Mars_McMismatchStudy/mdrs/MHDrsCalibration.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MHDrsCalibration.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MHDrsCalibration.h	(revision 17960)
@@ -0,0 +1,70 @@
+#ifndef MARS_MHDrsCalibration
+#define MARS_MHDrsCalibration
+
+#ifndef MARS_MHCamEvent
+#include "MHCamEvent.h"
+#endif
+
+#ifndef MARS_DrsCalib
+#include "DrsCalib.h"
+#endif
+
+class MRawRunHeader;
+class MRawEvtData;
+struct MDrsCalibration;
+
+class MHDrsCalibration : public MHCamEvent
+{
+private:
+    MRawRunHeader   *fRun;      //!
+    MRawEvtData     *fEvt;      //!
+    MDrsCalibration *fResult;   //!
+
+    std::vector<float> fBuffer; //! Compilation bufer for writing output files
+    DrsCalibrate       fData;   //!
+
+    Short_t fStep;
+
+    Double_t fScale;
+
+    UInt_t fNumPixels;
+    UInt_t fNumSamples;
+
+    TString fOutputPath;
+
+    void InitHistogram();
+
+    template<typename T>
+        Bool_t CopyData(std::vector<T> &dest) const;
+
+public:
+    MHDrsCalibration(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    Bool_t ResetSecondaryBaseline()
+    {
+        if (fStep!=2)
+            return kFALSE;
+
+        for (int i=1024*1440*4+4; i<1440*1024*6+160*1024*2+4; i++)
+            fBuffer[i] = 0;
+
+        fStep=1;
+
+        return kTRUE;
+    }
+
+    void SetOutputPath(const char *path) { fOutputPath = path; }
+
+    void Paint(Option_t *o="");
+
+    Short_t GetNumUnderflows(float lvl) const;
+
+    ClassDef(MHDrsCalibration, 1) // A list of histograms storing the Fadc spektrum of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationCheck.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationCheck.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationCheck.cc	(revision 17960)
@@ -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 2012 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2013
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHDrsCalibration
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHDrsCalibrationCheck.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+#include "MHCamera.h"
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MHDrsCalibrationCheck);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  default constructor
+//  creates an a list of histograms for all pixels and both gain channels
+//
+MHDrsCalibrationCheck::MHDrsCalibrationCheck(const char *name, const char *title) :
+    fEvt(0)
+{
+    //
+    // set the name and title of this object
+    //
+    fName  = name  ? name  : "MHDrsCalibrationCheck";
+    fTitle = title ? title : "Container for ADC spectra histograms";
+}
+
+// --------------------------------------------------------------------------
+//
+// To setup the object we get the number of pixels from a MGeomCam object
+// in the Parameter list.
+//
+Bool_t MHDrsCalibrationCheck::SetupFill(const MParList *pList)
+{
+    SetTitle("Noise (DRS calibration applied);;ADC signal [mV];");
+
+    if (!MHCamEvent::SetupFill(pList))
+        return kFALSE;
+
+    fSum->ResetBit(MHCamera::kProfile);
+
+    *fLog << warn << "WARNING --- oulier detection needed!" << endl;
+
+    return kTRUE;
+}
+
+Bool_t MHDrsCalibrationCheck::ReInit(MParList *pList)
+{
+    MRawRunHeader *h = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!h)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNumSamples = h->GetNumSamples();
+    fNumPixels  = h->GetNumPixel();
+
+    fEvt = (MPedestalSubtractedEvt*)pList->FindObject("MPedestalSubtractedEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MPedestalSubtractedEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSum1.resize(fNumPixels*fNumSamples);
+    fSum2.resize(fNumPixels*fNumSamples);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+Int_t MHDrsCalibrationCheck::Fill(const MParContainer *par, const Stat_t w)
+{
+    for (size_t ch=0; ch<fNumPixels*fNumSamples; ch++)
+    {
+        const double val = fEvt->GetSamples(0)[ch];
+
+        fSum1[ch] += val;
+        fSum2[ch] += val*val;
+    }
+
+    return kTRUE;
+}
+
+
+void MHDrsCalibrationCheck::InitHistogram()
+{
+    if (!fEvt)
+        return;
+
+    fSum->Reset();
+
+    for (size_t ch=0; ch<fNumPixels; ch++)
+    {
+        double m = 0;
+        double r = 0;
+        for (size_t i=0; i<fNumSamples; i++)
+        {
+            const int idx = i + ch*fNumSamples;
+
+            const double avg  = fSum1[idx] / GetNumExecutions();
+            const double avg2 = fSum2[idx] / GetNumExecutions();
+            const double rms  = sqrt(avg2 - avg*avg);
+
+            m += avg;
+            r += rms;
+        }
+
+        fSum->AddBinContent(ch+1, m);
+        fSum->SetBinError(ch+1,   r);
+    }
+
+    fSum->Scale(1./fNumSamples);  // 0.5mV/ADC count
+    fSum->SetEntries(GetNumExecutions());
+    fSum->SetAllUsed();
+}
+
+Bool_t MHDrsCalibrationCheck::Finalize()
+{
+    InitHistogram();
+
+    return kTRUE;
+}
+
+void MHDrsCalibrationCheck::Paint(Option_t *o)
+{
+    InitHistogram();
+    MHCamEvent::Paint(o);
+}
Index: branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationCheck.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationCheck.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationCheck.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MHDrsCalibrationCheck
+#define MARS_MHDrsCalibrationCheck
+
+#ifndef MARS_MHCamEvent
+#include "MHCamEvent.h"
+#endif
+
+class MPedestalSubtractedEvt;
+
+class MHDrsCalibrationCheck : public MHCamEvent
+{
+private:
+    MPedestalSubtractedEvt *fEvt;     //!
+
+    std::vector<double> fSum1;
+    std::vector<double> fSum2;
+
+    UInt_t fNumPixels;
+    UInt_t fNumSamples;
+
+    void InitHistogram();
+
+public:
+    MHDrsCalibrationCheck(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    void Paint(Option_t *o="");
+
+    ClassDef(MHDrsCalibrationCheck, 1) // A list of histograms storing the Fadc spektrum of one pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationTime.cc	(revision 17960)
@@ -0,0 +1,232 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 2013 <mailto:tbretz@phys.ethz.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2014
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHDrsCalibrationTime
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHDrsCalibrationTime.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStatusDisplay.h"
+
+#include "MPedestalSubtractedEvt.h"
+
+#include "MParList.h"
+#include "MRawEvtData.h"
+
+#include "MBinning.h"
+
+ClassImp(MHDrsCalibrationTime);
+
+using namespace std;
+
+MHDrsCalibrationTime::MHDrsCalibrationTime(const char *name, const char *title) :
+fRaw(0), fEvt(0), fCal(0)
+
+{
+    //
+    // set the name and title of this object
+    //
+    fName  = name  ? name  : "MHDrsCalibrationTime";
+    fTitle = title ? title : "Container for ADC spectra histograms";
+
+    MBinning bx( 160, -0.5,  159.5);
+    MBinning by(1024, -0.5, 1023.5);
+
+    MH::SetBinning(&fHist, &by, &bx);
+
+    fHist.SetName("Offset");
+    fHist.SetTitle("DRS cell time offset");
+
+    fHist.SetXTitle("Absolute position in pipeline");
+    fHist.SetYTitle("DRS time marker channel");
+    fHist.SetZTitle("\\Delta t / slices");
+
+    fHist.SetStats(kFALSE);
+    fHist.SetContour(99);
+    fHist.SetDirectory(0);
+}
+
+Bool_t MHDrsCalibrationTime::SetupFill(const MParList *pList)
+{
+    /*
+    SetTitle("DRS bla bla;;ADC signal [mV];");
+
+    if (!MHCamEvent::SetupFill(pList))
+        return kFALSE;
+
+    fSum->ResetBit(MHCamera::kProfile);
+    */
+
+
+    fData.Reset();
+
+    return kTRUE;
+}
+
+Bool_t MHDrsCalibrationTime::ReInit(MParList *pList)
+{
+    fRaw = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRaw)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fRaw->HasStartCells())
+    {
+        *fLog << err << "MRawEvtData has no start cells stored... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fRaw->GetNumPixels()==0 || fRaw->GetNumSamples()==0)
+    {
+        *fLog << err << "MRawEvtData contains either no pixels or no samples... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MPedestalSubtractedEvt*)pList->FindObject("MPedestalSubtractedEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MPedestalSubtractedEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fRaw->GetNumSamples()!=1024)
+    {
+        *fLog << err << "Only 1024 samples are supported for the time calibration" << endl;
+        return kFALSE;
+    }
+
+    fCal = (MDrsCalibrationTime*)pList->FindCreateObj("MDrsCalibrationTime");
+    if (!fCal)
+        return kFALSE;
+
+    fData.InitSize(160, 1024);
+
+    return kTRUE;
+}
+
+Int_t MHDrsCalibrationTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    fData.AddT(fEvt->GetSamples(0),
+               reinterpret_cast<int16_t*>(fRaw->GetStartCells()), +1);
+
+    return kTRUE;
+}
+
+void MHDrsCalibrationTime::InitHistogram()
+{
+    DrsCalibrateTime t = fData.GetResult();
+    if (t.fNumEntries==0)
+        return;
+
+    for (int p=0; p<160; p++)
+        for (int s=0; s<1024; s++)
+            fHist.SetBinContent(s+1, p+1, t.fStat[p*t.fNumSamples+s].first);
+}
+
+void MHDrsCalibrationTime::PlotAll()
+{
+    if (!fDisplay)
+        return;
+
+    InitHistogram();
+
+    for (int b=0; b<10; b++)
+    {
+        TCanvas &c = fDisplay->AddTab(Form("B%d", b));
+
+        c.Divide(2,2);
+
+        for (int i=0; i<4; i++)
+        {
+            c.cd(i+1);
+
+            gPad->SetGrid();
+            gPad->SetBorderMode(0);
+            gPad->SetFrameBorderMode(0);
+            gPad->SetRightMargin(0.01);
+
+            const int col[] = { kBlack, kRed, kBlue, kGreen };
+
+            for (int crate=0; crate<4; crate++)
+            {
+                TH1 *h = fHist.ProjectionX(Form("%d-%d-%d", crate, b, i), crate*40+b*4+i+1, crate*40+b*4+i+1);
+                h->SetName(Form("Crate%d", crate));
+                h->SetTitle(Form("Board %d, Chip %d (All four crates)", b, i));
+                h->SetXTitle("Slice");
+                h->SetYTitle("\\Delta t / slices");
+                h->SetMinimum(-10);
+                h->SetMaximum(10);
+                h->SetStats(kFALSE);
+                h->SetDirectory(0);
+                h->SetMarkerStyle(kFullDotMedium);
+                h->SetMarkerColor(col[crate]);
+                h->SetLineColor(col[crate]);
+                h->DrawCopy(crate==0 ? "hist p" : "hist P same");
+            }
+        }
+    }
+
+    // 4 crates
+    // 10 boards
+    // 4 chips
+}
+
+void MHDrsCalibrationTime::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+    AppendPad("");
+
+    pad->Divide(1,1);
+
+    pad->cd(1);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+
+    fHist.Draw("colz");
+}
+
+
+void MHDrsCalibrationTime::Paint(Option_t *o)
+{
+    MH::SetPalette();
+    InitHistogram();
+}
+
+Bool_t MHDrsCalibrationTime::Finalize()
+{
+    //    InitHistogram();
+    fCal->SetCalibration(fData.GetResult());
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/MHDrsCalibrationTime.h	(revision 17960)
@@ -0,0 +1,51 @@
+#ifndef MARS_MHDrsCalibrationTime
+#define MARS_MHDrsCalibrationTime
+
+#ifndef MARS_DrsCalibrationTime
+#include "MDrsCalibrationTime.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MRawEvtData;
+class MDrsCalibrationTime;
+class MPedestalSubtractedEvt;
+
+class MHDrsCalibrationTime : public MH
+{
+private:
+    TH2F fHist;
+
+    MRawEvtData            *fRaw;     //!
+    MPedestalSubtractedEvt *fEvt;     //!
+    MDrsCalibrationTime    *fCal;     //!
+
+    MDrsCalibrationTime fData; //
+
+    void InitHistogram();
+
+    template<typename T>
+        Bool_t CopyData(std::vector<T> &dest) const;
+
+public:
+    MHDrsCalibrationTime(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    void Draw(Option_t *o="");
+    void Paint(Option_t *o="");
+
+    void PlotAll();
+
+    //const MDrsCalibration &GetCalib() const { return fData; }
+
+    ClassDef(MHDrsCalibrationTime, 1) // A list of histograms storing the Fadc spektrum of one pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mdrs/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mdrs/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mdrs/Makefile	(revision 17960)
@@ -0,0 +1,39 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Drs
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = \
+	-I. -I../mbase -I../mgeom -I../mbadpixels -I../mraw -I../msignal \
+	-I../mhbase -I../mcore -I../mhist -I../mgui -I../mpedestal
+
+SRCFILES = MCalibrateDrsTimes.cc \
+	   MDrsCalibApply.cc \
+	   MHDrsCalibration.cc \
+	   MDrsCalibration.cc \
+	   MDrsCalibrationTime.cc \
+	   MHDrsCalibrationCheck.cc \
+	   MHDrsCalibrationTime.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/melectronics/ElectronicsIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/ElectronicsIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/ElectronicsIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/melectronics/ElectronicsLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/ElectronicsLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/ElectronicsLinkDef.h	(revision 17960)
@@ -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 APD+;
+#pragma link C++ class Afterpulse;
+#pragma link C++ class MAnalogSignal+;
+#pragma link C++ class MDigitalSignal+;
+#pragma link C++ class MAnalogChannels+;
+
+#endif
Index: branches/Mars_McMismatchStudy/melectronics/MAnalogChannels.cc
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MAnalogChannels.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MAnalogChannels.cc	(revision 17960)
@@ -0,0 +1,148 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MAnalogChannels
+//
+// A collection of MAnalogSignals with a simplified access interface.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAnalogChannels.h"
+
+#include <TObjArray.h>
+
+#include "MAnalogSignal.h"
+
+ClassImp(MAnalogChannels);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Default constructor
+//
+MAnalogChannels::MAnalogChannels(const char *name, const char *title)
+: fArray(0), fValidRangeMin(0), fValidRangeMax(0)
+{
+    fName  = name  ? name  : "MAnalogChannels";
+    fTitle = title ? title : "Parameter container for a collection of analog signals";
+}
+
+// ------------------------------------------------------------------------
+//
+// Constructor. Calls Init(n, len)
+//
+MAnalogChannels::MAnalogChannels(Int_t n, Int_t len, const char *name, const char *title)
+: fArray(0), fValidRangeMin(0), fValidRangeMax(0)
+{
+    fName  = name  ? name  : "MAnalogChannels";
+    fTitle = title ? title : "Parameter container for a collection of analog signals";
+
+    Init(n, len);
+}
+
+// ------------------------------------------------------------------------
+//
+// delete fArray
+//
+void MAnalogChannels::Clear(Option_t *o)
+{
+    if (fArray)
+    {
+        delete fArray;
+        fArray = 0;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Initializes n channels with a length of n sampling points.
+//
+// FIXME: We could improve speed by only increasing the arrays?
+//
+void MAnalogChannels::Init(UInt_t n, UInt_t len)
+{
+    Clear();
+
+    fArray = new TObjArray(n);
+    fArray->SetOwner();
+
+    for (UInt_t i=0; i<n; i++)
+        fArray->AddAt(new MAnalogSignal(len), i);
+}
+
+// ------------------------------------------------------------------------
+//
+// return an unchecked reference to the i-th channel.
+//
+MAnalogSignal &MAnalogChannels::operator[](UInt_t i)
+{
+    return *static_cast<MAnalogSignal*>(fArray->UncheckedAt(i));
+}
+
+// ------------------------------------------------------------------------
+//
+// return an unchecked pointer to the i-th channel.
+//
+MAnalogSignal *MAnalogChannels::operator()(UInt_t i)
+{
+    return  static_cast<MAnalogSignal*>(fArray->UncheckedAt(i));
+}
+
+// ------------------------------------------------------------------------
+//
+// Return an unchecked const reference to the i-th channel.
+//
+const MAnalogSignal &MAnalogChannels::operator[](UInt_t i) const
+{
+    return *static_cast<MAnalogSignal*>(fArray->UncheckedAt(i));
+}
+
+// ------------------------------------------------------------------------
+//
+// Return an unchecked const pointer to the i-th channel.
+//
+const MAnalogSignal *MAnalogChannels::operator()(UInt_t i) const
+{
+    return  static_cast<MAnalogSignal*>(fArray->UncheckedAt(i));
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the number of channels.
+//
+UInt_t MAnalogChannels::GetNumChannels() const
+{
+    return fArray ? fArray->GetEntriesFast() : 0;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the number of samples per channel
+//
+UInt_t MAnalogChannels::GetNumSamples() const
+{
+    return operator()(0) ? operator()(0)->GetSize() : 0;
+}
Index: branches/Mars_McMismatchStudy/melectronics/MAnalogChannels.h
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MAnalogChannels.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MAnalogChannels.h	(revision 17960)
@@ -0,0 +1,51 @@
+#ifndef MARS_MAnalogChannels
+#define MARS_MAnalogChannels
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TObjArray;
+class MAnalogSignal;
+
+class MAnalogChannels : public MParContainer
+{
+private:
+    TObjArray *fArray;
+
+    Int_t fValidRangeMin;
+    Int_t fValidRangeMax;
+
+public:
+    MAnalogChannels(const char *name=0, const char *title=0);
+    MAnalogChannels(Int_t n, Int_t len, const char *name=0, const char *title=0);
+    ~MAnalogChannels()
+    {
+        Clear();
+    }
+
+    void Clear(Option_t *o="");
+
+    void Init(UInt_t n, UInt_t len);
+
+    void InitNumChannels(UInt_t n) { Init(n, GetNumSamples());  }
+    void InitLenChannels(UInt_t l) { Init(GetNumChannels(), l); }
+
+    MAnalogSignal &operator[](UInt_t i);
+    MAnalogSignal *operator()(UInt_t i);
+
+    const MAnalogSignal &operator[](UInt_t i) const;
+    const MAnalogSignal *operator()(UInt_t i) const;
+
+    UInt_t GetNumChannels() const;
+    UInt_t GetNumSamples() const;
+
+    void SetValidRange(Int_t min, Int_t max) { fValidRangeMin=min; fValidRangeMax=max; }
+
+    Int_t GetValidRangeMin() const { return fValidRangeMin; }
+    Int_t GetValidRangeMax() const { return fValidRangeMax; }
+
+    ClassDef(MAnalogChannels, 1) // Parameter container for a collection of analog signals
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/melectronics/MAnalogSignal.cc
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MAnalogSignal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MAnalogSignal.cc	(revision 17960)
@@ -0,0 +1,286 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MAnalogSignal
+//
+// This is the equivalent to an analog signal. The signal is stored by
+// a sampling in equidistant bins.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAnalogSignal.h"
+
+#include <TF1.h>
+#include <TRandom.h>
+#include <TObjArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MSpline3.h"
+#include "MDigitalSignal.h"
+
+#include "MExtralgoSpline.h"
+
+ClassImp(MAnalogSignal);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Set the array length and the length of the buffers.
+//
+void MAnalogSignal::Set(UInt_t n)
+{
+    // FIXME: Maybe we move this before initializing the spline
+    // with a check?
+    fDer1.Set(n);
+    fDer2.Set(n);
+
+    MArrayF::Set(n);
+}
+
+// ------------------------------------------------------------------------
+//
+// Evaluate the spline an add the result between t+xmin and t+xmax
+// (xmin and xmax are the limits of the spline) to the signal.
+// The spline is evaluated at the bin-center of the analog signal
+// and multiplied by f.
+//
+// Return kTRUE if the full range of the spline could be added to the
+// analog signal, kFALSE otherwise.
+//
+Bool_t MAnalogSignal::AddPulse(const MSpline3 &spline, Float_t t, Float_t f)
+{
+    // FIXME: This could be improved using a MExtralgoSpline with
+    //        the identical stepping as the signal and we could use
+    //        the integral instead of the pure y-value if we want.
+
+    // Both in units of the sampling frequency
+    const Float_t start = t+spline.GetXmin();
+    const Float_t end   = t+spline.GetXmax();
+
+    Int_t  first = TMath::CeilNint(start);
+    UInt_t last  = TMath::CeilNint(end); // Ceil:< Floor:<=
+
+    Bool_t rc = kTRUE;
+    if (first<0)
+    {
+        first=0;
+        rc = kFALSE;
+    }
+    if (last>GetSize())
+    {
+        last=GetSize();
+        rc = kFALSE;
+    }
+
+    // FIXME: As soon as we have access to TSpline3::fPoly we can
+    //        gain a lot in execution speed here.
+
+    Float_t *arr = GetArray();
+    for (UInt_t i=first; i<last; i++)
+        arr[i] += spline.Eval(i-t)*f;
+
+    return rc;
+}
+
+// ------------------------------------------------------------------------
+//
+// Evaluate the spline an add the result between t+xmin and t+xmax
+// (xmin and xmax are the limits of the TF1) to the signal.
+// The spline is evaluated at the bin-center of the analog signal
+// and multiplied by f.
+//
+// Return kTRUE if the full range of the function could be added to the
+// analog signal, kFALSE otherwise.
+//
+Bool_t MAnalogSignal::AddPulse(const TF1 &func, Float_t t, Float_t f)
+{
+    // Both in units of the sampling frequency
+    const Float_t start = t+func.GetXmin();
+    const Float_t end   = t+func.GetXmax();
+
+    Int_t  first = TMath::CeilNint(start);
+    UInt_t last  = TMath::CeilNint(end); // Ceil:< Floor:<=
+
+    Bool_t rc = kTRUE;
+    if (first<0)
+    {
+        first=0;
+        rc = kFALSE;
+    }
+    if (last>GetSize())
+    {
+        last=GetSize();
+        rc = kFALSE;
+    }
+
+    // FIXME: As soon as we have access to TSpline3::fPoly we can
+    //        gain a lot in execution speed here.
+
+    Float_t *arr = GetArray();
+    for (UInt_t i=first; i<last; i++)
+        arr[i] += func.Eval(i-t)*f;
+
+    return rc;
+}
+
+// ------------------------------------------------------------------------
+//
+// Add a second analog signal. Just by addining it bin by bin.
+//
+void MAnalogSignal::AddSignal(const MAnalogSignal &s, Int_t delay,
+                              Float_t dampingFactor )
+{
+    Add(s.GetArray(), s.fN, delay, dampingFactor);
+}
+
+
+// Deprecated. Use MSimRandomPhotons instead
+void MAnalogSignal::AddRandomPulses(const MSpline3 &spline, Float_t num)
+{
+    // Average number (1./freq) of pulses per slice
+
+    const Float_t start =   0   -spline.GetXmin();
+    const Float_t end   = (fN-1)-spline.GetXmax();
+
+    const UInt_t first = TMath::CeilNint(start);
+    const UInt_t last  = TMath::CeilNint(end); // Ceil:< Floor:<=
+
+    Double_t d = first;
+
+    while (d<last)
+    {
+        d += gRandom->Exp(num);
+        AddPulse(spline, d);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Add a random gaussian with amplitude and offset to every bin
+// of the analog signal. The default offset is 0. The default amplitude 1.
+//
+void MAnalogSignal::AddGaussianNoise(Float_t amplitude, Float_t offset)
+{
+    for (Float_t *ptr = GetArray(); ptr<GetArray()+fN; ptr++)
+        *ptr += gRandom->Gaus(offset, amplitude);
+}
+
+// ------------------------------------------------------------------------
+//
+// The signal is evaluated using the spline MExtralgoSpline.
+// Searching upwards from the beginning all points are calculated at
+// which the spline is equal to threshold. After a rising edge
+// a leading edge is searched. From this an MDigitalSignal is
+// created and added to an newly created TObjArray. If len<0 then
+// the signal length is equal to the time above threshold, otherwise
+// the length is fixed to len. The start of the digital signal is the
+// rising edge. If due to fixed length two digital signal overlap the
+// digital signals are combined into one signal.
+//
+// For numerical reasons we have to avoid to find the same x-value twice.
+// Therefor a "dead-time" of 1e-4 is implemented after each edge.
+//
+// The user is responsible of deleting the TObjArray.
+//
+TObjArray *MAnalogSignal::Discriminate(Float_t threshold, Double_t start, Double_t end, Float_t len) const
+{
+    TObjArray *ttl = new TObjArray;
+    ttl->SetOwner();
+
+    // The time after which we start searching for a falling or leading
+    // edge at threshold after a leading or falling edge respectively.
+    // This value has mainly numerical reasons. If starting the search
+    // too early we might end up in an endless loop finding the same
+    // value again and again. This just means that a glitch above or
+    // below the threshold which is shorter than this value can
+    // stay unnoticed. This shouldn't hurt.
+    const Double_t deadtime = 1e-4;
+
+    // FIXME: Are local maximum/minima handled correctly?
+
+    const MExtralgoSpline sp(GetArray(), fN, fDer1.GetArray(), fDer2.GetArray());
+
+    Double_t x1 = 0;
+    Double_t x2 = start;  // Start searching at x2
+
+    while (1)
+    {
+        // Search for the next rising edge (starting at x2)
+        while (1)
+        {
+            x1 = sp.SearchYup(x2+deadtime, threshold);
+            if (x1<0 || x1>=end)
+                return ttl;
+
+            const Bool_t rising = sp.Deriv1(x1)>0;
+            if (rising)
+                break;
+
+            x2 = x1;
+        }
+
+        // Search for the next falling edge (starting at x1)
+        while (1)
+        {
+            x2 = sp.SearchYup(x1+deadtime, threshold);
+            if (x2<0)
+                x2 = end;
+            if (x2>=end)
+                break;
+
+            const Bool_t falling = sp.Deriv1(x2)<0;
+            if (falling)
+                break;
+
+            x1 = x2;
+        }
+
+        // We found a rising and a falling edge
+        MDigitalSignal *sig = new MDigitalSignal(x1, len>0?len:x2-x1);
+
+        // In case of a fixed length we have to check for possible overlapping
+        if (len>0 && ttl->GetEntriesFast()>0)
+        {
+            // FIXME: What if in such a case the electronics is just dead?
+            MDigitalSignal *last = static_cast<MDigitalSignal*>(ttl->Last());
+            // Combine both signals to one if they overlap
+            if (last->Combine(*sig))
+            {
+                // Both signals overlap and have been combined into the existing one
+                delete sig;
+                continue;
+            }
+            // The signals don't overlap we add the new signal as usual
+        }
+
+        // Add the new signal to the list of signals
+        ttl->Add(sig);
+    }
+
+    return ttl;
+}
Index: branches/Mars_McMismatchStudy/melectronics/MAnalogSignal.h
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MAnalogSignal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MAnalogSignal.h	(revision 17960)
@@ -0,0 +1,36 @@
+#ifndef MARS_MAnalogSignal
+#define MARS_MAnalogSignal
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class TF1;
+class MSpline3;
+
+class MAnalogSignal : public MArrayF/*TObject*/
+{
+private:
+    MArrayF fDer1; //! Buffer for the derivatives of the corresponding spline
+    MArrayF fDer2; //! Buffer for the derivatives of the corresponding spline
+
+public:
+    MAnalogSignal(UInt_t n) { Set(n); }
+
+    void   Set(UInt_t n);
+    Bool_t AddPulse(const MSpline3 &spline, Float_t t, Float_t f=1);
+    Bool_t AddPulse(const TF1 &f1, Float_t t, Float_t f=1);
+    void   AddSignal(const MAnalogSignal &s, Int_t delay=0,Float_t dampingFact=1.0);
+
+    // Deprecated. Use MSimRandomPhotons instead
+    void AddRandomPulses(const MSpline3 &spline, Float_t num);
+
+    void AddGaussianNoise(Float_t amplitude=1, Float_t offset=0);
+
+    TObjArray *Discriminate(Float_t threshold, Double_t start, Double_t end, Float_t len=-1) const;
+    TObjArray *Discriminate(Float_t threshold, Float_t len=-1) const { return Discriminate(threshold, 0, fN-1, len); }
+
+    ClassDef(MAnalogSignal, 1) // Storage class for an analog signal
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/melectronics/MAvalanchePhotoDiode.cc
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MAvalanchePhotoDiode.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MAvalanchePhotoDiode.cc	(revision 17960)
@@ -0,0 +1,604 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  APD
+//
+// All times in this class are relative times. Therefor the unit for the
+// time is not intrinsically fixed. In fact the dead-time and recovery-
+// time given in the constructor must have the same units. This is what
+// defines the unit of the times given in the function and the unit of
+// rates given.
+// For example, if recovery and dead time are given in nanoseconds the
+// all times must be in nanoseconds and rates are given per nanosecond,
+// i.e. GHz.
+//
+//  Hamamatsu 30x30 cells:  APD(30, 0.2, 3, 35)
+//  Hamamatsu 60x60 cells:  APD(60, 0.2, 3, 8.75)
+//
+//
+// The implementation of afterpulsing is based on
+//    A.Du, F.Retiere
+//    After-pulsing and cross-talk in multi-pixel photon counters
+//    NIM A, Volume 596, Issue 3, p. 396-401
+//
+//
+// Example:
+//
+//    APD apd(ncells, crosstalk, deadtime, recovery);
+//    apd.SetAfterpulseProb(0.14, 0.11);
+//
+//    while (1)
+//    {
+//        // Make the chip "empty" from the influence of external photons
+//        // It also sets fTime to 0.
+//        apd.Init(freq); // freq of external noise (eg. nsb)
+//
+//        // Now call this function for each external photon you have. The
+//        // times are relative to the the time you get by apd.GetTime()
+//        // set automatically after the call to apd.Init().
+//        for (int i=0; i<nphot; i++)
+//            apd.HitRandomCellRelative(dt);
+//
+//        [...]
+//
+//        // Process and produce afterpulses until a time, wrt to GetTime(),
+//        // given by the end of your simulated window. Note that this
+//        // does not produce noise. This must have been properly simulated
+//        // up to this time already.
+//        apd.IncreaseTime(dtend);
+//
+//        // Now you can excess the afterpulses by
+//        TIter Next(&a->GetListOfAfterpulses());
+//        Afterpulse *ap = 0;
+//        while ((ap=static_cast<Afterpulse*>(Next())))
+//        {
+//           if (apd.GetTime()>=dtend)
+//              continue;
+//
+//           cout << "Amplitude:    " << ap->GetAmplitude() << endl;
+//           cout << "Arrival Time: " << ap->GetTime()      << endl;
+//        }
+//     }
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAvalanchePhotoDiode.h"
+
+#include <TRandom.h>
+
+#include "MMath.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(APD);
+
+using namespace std;
+
+/*
+class MyProfile : public TProfile2D
+{
+public:
+    void AddBinEntry(Int_t cell) { fBinEntries.fArray[cell]++; }
+};
+*/
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+//    n     is the number od cells in x or y. The APD is assumed to
+//          be square.
+//    prob  is the crosstalk probability, i.e., the probability that a
+//          photon which produced an avalanche will create another
+//          photon in a neighboring cell
+//    dt    is the deadtime, i.e., the time in which the APD cell will show
+//          no response to a photon after a hit
+//    rt    is the recovering tims, i.e. the exponential (e^(-dt/rt))
+//          with which the cell is recovering after being dead
+//
+//    prob, dt and ar can be set to 0 to switch the effect off.
+//    0 is also the dfeault for all three.
+//
+APD::APD(Int_t n, Float_t prob, Float_t dt, Float_t rt)
+    : fHist("APD", "", n, 0.5, n+0.5, n, 0.5, n+0.5),
+    fCrosstalkProb(prob), fDeadTime(dt), fRecoveryTime(rt),
+    fTime(-1)
+{
+    fHist.SetDirectory(0);
+
+    fAfterpulses.SetOwner();
+
+    fAfterpulseProb[0] = 0;
+    fAfterpulseProb[1] = 0;
+
+    fAfterpulseTau[0] = 15;
+    fAfterpulseTau[1] = 85;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is the time a chips needs after an external signal to relax to
+// a "virgin" state, i.e. without no influence of the external pulse
+// above the given threshold.
+//
+// It takes into account the dead time of the cell, the relaxation time
+// and the two afterpulse distributions. However, in most cases the
+// afterpulse distribution will dominate (except they are switched off by
+// a zero probability).
+//
+// FIXME: Maybe the calculation of the relaxation time could be optimized?
+//
+Float_t APD::GetRelaxationTime(Float_t threshold) const
+{
+    // Calculate time until the probability of one of these
+    // events falls below the threshold probability.
+    const Double_t rt0 = - TMath::Log(threshold)*fRecoveryTime;
+    const Double_t rt1 = fAfterpulseProb[0]>0 ? -TMath::Log(threshold/fAfterpulseProb[0])*fAfterpulseTau[0] : 0;
+    const Double_t rt2 = fAfterpulseProb[1]>0 ? -TMath::Log(threshold/fAfterpulseProb[1])*fAfterpulseTau[1] : 0;
+
+    // Probability not between t and inf, but between t and t+dt
+    // -tau * log ( p / ( 1 - exp(- dt/tau) ) ) = t
+
+    return fDeadTime + TMath::Max(rt0, TMath::Max(rt1, rt2));
+}
+
+// --------------------------------------------------------------------------
+//
+// This is the recursive implementation of a hit. If a photon hits a cell
+// at x and y (must be a valid cell!) at time t, at first we check if the
+// cell is still dead. If it is not dead we calculate the signal height
+// from the recovery time. Now we check with the crosstalk probability
+// whether another photon is created. If another photon is created we
+// calculate randomly which of the four neighbor cells are hit.
+// If the cell is outside the APD the photon is ignored. As many
+// new photons are created until our random number is below the crosstak-
+// probability.
+//
+// For each photon the possible afterpulses of two distributions are
+// created and added to the list of afterpulses. This is done by calling
+// GenerateAfterpulse for the two afterpulse-distributions.
+//
+// The total height of the signal (in units of photons) is returned.
+// Note, that this can be a fractional number.
+//
+// This function looks a bit fancy accessing the histogram and works around
+// a few histogram functions. This is a speed optimization which works
+// around a lot of sanity checks which are obsolete in our case.
+//
+// The default time is 0.
+//
+Float_t APD::HitCellImp(Int_t x, Int_t y, Float_t t)
+{
+    //        if (x<1 || x>fHist.GetNbinsX() ||
+    //            y<1 || y>fHist.GetNbinsY())
+    //            return 0;
+#ifdef DEBUG
+    cout << "Hit: " << t << endl;
+#endif
+
+    // Number of the x/y cell in the one dimensional array
+    // const Int_t cell = fHist.GetBin(x, y);
+    const Int_t cell = x + (fHist.GetNbinsX()+2)*y;
+
+    // Getting a reference to the float is the fastes way to
+    // access the bin-contents in fArray
+    Float_t &cont = fHist.GetArray()[cell];
+
+    // Calculate the time since the last breakdown
+    // const Double_t dt = t-fHist.GetBinContent(x, y)-fDeadTime; //
+    const Float_t dt = t-cont-fDeadTime;
+
+    // Photons within the dead time are just ignored
+    if (/*hx.GetBinContent(x,y)>0 &&*/ dt<=0)
+    {
+#ifdef DEBUG
+        cout << "Dead: " << t << " " << cont << " " << dt << endl;
+#endif
+        return 0;
+    }
+    // The signal height (in units of one photon) produced after dead time
+    // depends on the recovery of the cell - described by an exponential.
+    const Float_t weight = fRecoveryTime<=0 ? 1. : 1-TMath::Exp(-dt/fRecoveryTime);
+
+    // Now we know the charge in the cell and we can generate
+    // the afterpulses with both time-constants
+    GenerateAfterpulse(cell, 0, weight, t);
+    GenerateAfterpulse(cell, 1, weight, t);
+
+    // The probability that the cell emits a photon causing crosstalk
+    // scales as the signal height.
+    const Float_t prob = weight*fCrosstalkProb;
+
+    // Set the contents to the time of the last breakdown (now)
+    cont = t; // fHist.SetBinContent(x, y, t)
+
+    // Counter for the numbers of produced photons
+    Float_t n = weight;
+
+    // Get random number of emitted and possible converted crosstalk photons
+    const UInt_t rndm = gRandom->Poisson(prob);
+
+    for (UInt_t i=0; i<rndm; i++)
+    {
+        // Get a random neighbor which is hit.
+        switch (gRandom->Integer(4))
+        {
+        case 0: if (x<fHist.GetNbinsX()) n += HitCellImp(x+1, y, t); break;
+        case 1: if (x>1)                 n += HitCellImp(x-1, y, t); break;
+        case 2: if (y<fHist.GetNbinsY()) n += HitCellImp(x, y+1, t); break;
+        case 3: if (y>1)                 n += HitCellImp(x, y-1, t); break;
+        }
+    }
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if x and y is a valid cell. If not return 0, otherwise
+// HitCelImp(x, y, t). HitCellImp generates Crosstalk and Afterpulses.
+//
+// The default time is 0.
+//
+Float_t APD::HitCell(Int_t x, Int_t y, Float_t t)
+{
+    if (x<1 || x>fHist.GetNbinsX() ||
+        y<1 || y>fHist.GetNbinsY())
+        return 0;
+
+    return HitCellImp(x, y, t);
+}
+
+// --------------------------------------------------------------------------
+//
+// Determine randomly (uniformly) a cell which was hit. Return
+// HitCellImp for this cell and the given time. HitCellImp
+// generates Crosstalk and Afterpulses
+//
+// The default time is 0.
+//
+// If you want t w.r.t. fTime use HitRandomCellRelative istead.
+//
+Float_t APD::HitRandomCell(Float_t t)
+{
+    const UInt_t nx  = fHist.GetNbinsX();
+    const UInt_t ny  = fHist.GetNbinsY();
+
+    const UInt_t idx = gRandom->Integer(nx*ny);
+
+    const UInt_t x   = idx%nx;
+    const UInt_t y   = idx/nx;
+
+    return HitCellImp(x+1, y+1, t);
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets all cells with a contents which is well before the time t such that
+// the chip is "virgin". Therefore all cells are set to a time which
+// is twice the deadtime before the given time and 1000 times the recovery
+// time.
+//
+// The afterpulse list is deleted.
+//
+// If deadtime and recovery time are 0 then t-1 is set.
+//
+// Sets fTime to t
+//
+// The default time is 0.
+//
+void APD::FillEmpty(Float_t t)
+{
+    const Int_t n = (fHist.GetNbinsX()+2)*(fHist.GetNbinsY()+2);
+
+    const Double_t tm = fDeadTime<=0 && fRecoveryTime<=0 ? t-1 : t-2*fDeadTime-1000*fRecoveryTime;
+
+    for (int i=0; i<n; i++)
+        fHist.GetArray()[i] = tm;
+
+    fHist.SetEntries(1);
+
+    fAfterpulses.Delete();
+
+    fTime = t;
+}
+
+// --------------------------------------------------------------------------
+//
+// First call FillEmpty for the given time t. Then fill each cell by
+// by calling HitCellImp with time t-gRandom->Exp(n/rate) with n being
+// the total number of cells. This the time at which the cell was last hit.
+//
+// Sets fTime to t
+//
+// If the argument t is omitted it defaults to 0.
+//
+// Since after calling this function the chip should reflect the
+// status at the new time fTime=t, all afterpulses are processed
+// until this time. However, the produced random pulses might have produced
+// new new afterpulses.
+//
+// All afterpulses before the new timestamp are deleted.
+//
+// WARNING: Note that this might not correctly reproduce afterpulses
+//          produced by earlier pulese.
+//
+void APD::FillRandom(Float_t rate, Float_t t)
+{
+    FillEmpty(t);
+
+    const Int_t nx = fHist.GetNbinsX();
+    const Int_t ny = fHist.GetNbinsY();
+
+    const Double_t f = (nx*ny)/rate;
+
+    // FIXME: Dead time is not taken into account,
+    //        possible earlier afterpulses are not produced.
+
+    for (int x=1; x<=nx; x++)
+        for (int y=1; y<=ny; y++)
+            HitCellImp(x, y, t-MMath::RndmExp(f));
+
+    // Deleting of the afterpulses before fHist.GetMinimum() won't
+    // speed things because we have to loop over them once in any case
+
+    ProcessAfterpulses(fHist.GetMinimum(), t);
+    DeleteAfterpulses(t);
+
+    fTime = t;
+}
+
+// --------------------------------------------------------------------------
+//
+// Shift all times including fTime to dt (ie. add -dt to all times)
+// This allows to set a user-defined T0 or shift T0 to fTime=0.
+//
+// However, T0<0 is not allowed (dt cannot be greater than fTime)
+//
+void APD::ShiftTime(Double_t dt)
+{
+    if (dt>fTime)
+    {
+        gLog << warn << "APD::ShiftTime: WARNING - requested time shift results in fTime<0... ignored." << endl;
+        return;
+    }
+
+    // If reset was requested shift all times by end backwards
+    // so that fTime is now 0
+    const Int_t n = (fHist.GetNbinsX()+2)*(fHist.GetNbinsY()+2);
+    for (int i=0; i<n; i++)
+        fHist.GetArray()[i] -= dt;
+
+    fTime -= dt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evolve the chip from fTime to fTime+dt if it with a given frequency
+// freq. Returns the total signal "recorded".
+//
+// fTime is set to the fTime+dt.
+//
+// If you want to evolve over a default relaxation time (relax the chip
+// from a signal) use Relax instead.
+//
+// Since after calling this function the chip should reflect the
+// status at the new time fTime=fTime+dt, all afterpulses are processed
+// until this time. However, evolving the chip until this time might
+// have produced new afterpulses.
+//
+// All afterpulses before the new timestamp are deleted.
+//
+Float_t APD::Evolve(Double_t freq, Double_t dt)
+{
+    const Double_t end = fTime+dt;
+
+    Float_t hits = 0;
+ 
+    if (freq>0)
+    {
+        const Double_t avglen = 1./freq;
+
+        Double_t time = fTime;
+        while (1)
+        {
+            const Double_t deltat = MMath::RndmExp(avglen);
+            if (time+deltat>end)
+                break;
+
+            time += deltat;
+
+            hits += HitRandomCell(time);
+        }
+    }
+
+    // Deleting of the afterpulses before fTime won't speed things
+    // because we have to loop over them once in any case
+
+    ProcessAfterpulses(fTime, dt);
+    DeleteAfterpulses(end);
+
+    fTime = end;
+
+    return hits;
+}
+
+// --------------------------------------------------------------------------
+//
+// Retunrs the number of cells which have a time t<=fDeadTime, i.e. which are
+// dead.
+// The default time is 0.
+//
+// Note that if you want to get a correct measure of teh number of dead cells
+// at the time t, this function will only produce a valid count if the
+// afterpulses have been processed up to this time.
+//
+Int_t APD::CountDeadCells(Float_t t) const
+{
+    const Int_t nx = fHist.GetNbinsX();
+    const Int_t ny = fHist.GetNbinsY();
+
+    Int_t n=0;
+    for (int x=1; x<=nx; x++)
+        for (int y=1; y<=ny; y++)
+            if ((t-fHist.GetBinContent(x, y))<=fDeadTime)
+                n++;
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returs the number of cells which have a time t<=fDeadTime+fRecoveryTime.
+// The default time is 0.
+//
+// Note that if you want to get a correct measure of teh number of dead cells
+// at the time t, this function will only produce a valid count if the
+// afterpulses have been processed up to this time.
+//
+Int_t APD::CountRecoveringCells(Float_t t) const
+{
+    const Int_t nx = fHist.GetNbinsX();
+    const Int_t ny = fHist.GetNbinsY();
+
+    Int_t n=0;
+    for (int x=1; x<=nx; x++)
+        for (int y=1; y<=ny; y++)
+        {
+            Float_t dt = t-fHist.GetBinContent(x, y);
+            if (dt>fDeadTime && dt<=fDeadTime+fRecoveryTime)
+                n++;
+        }
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Generate an afterpulse originating from the given cell and a pulse with
+// charge. The afterpulse distribution to use is specified by
+// the index. The "current" time to which the afterpulse delay refers must
+// be given by t.
+//
+// A generated Afterpulse is added to the list of afterpulses
+//
+void APD::GenerateAfterpulse(UInt_t cell, Int_t idx, Double_t charge, Double_t t)
+{
+    // The cell had a single avalanche with signal height weight.
+    // This cell now can produce an afterpulse photon/avalanche.
+    const Double_t p = gRandom->Uniform();
+
+    // It's probability scales with the charge of the pulse
+    if (p>charge*fAfterpulseProb[idx])
+        return;
+
+    // Afterpulses come with a well defined time-constant
+    // after the normal pulse
+    const Double_t dt = MMath::RndmExp(fAfterpulseTau[idx]);
+
+    fAfterpulses.Add(new Afterpulse(cell, t+dt));
+
+#ifdef DEBUG
+    cout << "Add : " << t << " + " << dt << " = " << t+dt << endl;
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Process afterpulses between time and time+dt. All afterpulses in the list
+// before t=time are ignored. All afterpulses between t=time and
+// t=time+dt are processed through HitCellImp. Afterpulses after and
+// equal t=time+dt are skipped.
+//
+// Since the afterpulse list is a sorted list newly generated afterpulses
+// are always inserted into the list behind the current entry. Consequently,
+// afterpulses generated by afterpulses will also be processed correctly.
+//
+// Afterpulses with zero amplitude are deleted from the list. All other after
+// pulses remain in the list for later evaluation.
+//
+void APD::ProcessAfterpulses(Float_t time, Float_t dt)
+{
+#ifdef DEBUG
+    cout << "Process afterpulses from " << time << " to " << time+dt << endl;
+#endif
+
+    const Float_t end = time+dt;
+
+    TObjLink *lnk = fAfterpulses.FirstLink();
+    while (lnk)
+    {
+        Afterpulse &ap = *static_cast<Afterpulse*>(lnk->GetObject());
+
+        // Skip afterpulses which have been processed already
+        // or which we do not have to process anymore
+        if (ap.GetTime()<time || ap.GetAmplitude()>0)
+        {
+            lnk = lnk->Next();
+            continue;
+        }
+
+        // No afterpulses left in correct time window
+        if (ap.GetTime()>=end)
+           break;
+
+        // Process afterpulse through HitCellImp
+        const Float_t ampl = ap.Process(*this);
+
+        // Step to the next entry already, the current one might get deleted
+        lnk = lnk->Next();
+
+        if (ampl!=0)
+            continue;
+
+#ifdef DEBUG
+        cout << "Del : " << ap.GetTime() << " (" << ampl << ")" << endl;
+#endif
+
+        // The afterpulse "took place" within the dead time of the
+        // pixel ==> No afterpulse, no crosstalk.
+        delete fAfterpulses.Remove(&ap);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete all afterpulses before and equal to t=time from the list
+//
+void APD::DeleteAfterpulses(Float_t time)
+{
+    TIter Next(&fAfterpulses);
+
+    Afterpulse *ap = 0;
+
+    while ((ap = static_cast<Afterpulse*>(Next())))
+    {
+        if (ap->GetTime()>=time)
+            break;
+
+        delete fAfterpulses.Remove(ap);
+    }
+}
Index: branches/Mars_McMismatchStudy/melectronics/MAvalanchePhotoDiode.h
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MAvalanchePhotoDiode.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MAvalanchePhotoDiode.h	(revision 17960)
@@ -0,0 +1,166 @@
+#ifndef MARS_MAvalanchePhotoDiode
+#define MARS_MAvalanchePhotoDiode
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TSortedList
+#include <TSortedList.h>
+#endif
+
+class APD : public TObject  // FIXME: Derive from TH2?
+{
+    friend class Afterpulse;
+
+private:
+    TH2F fHist;
+
+    TSortedList fAfterpulses;   //! List of produced afterpulses
+
+    Float_t fCrosstalkProb;     // Probability that a converted photon creates another one in a neighboring cell
+    Float_t fDeadTime;          // Deadtime of a single cell after a hit
+    Float_t fRecoveryTime;      // Recoverytime after Deadtime (1-exp(-t/fRecoveryTime)
+    Float_t fAfterpulseProb[2]; // Afterpulse probabilities
+    Float_t fAfterpulseTau[2];  // Afterpulse time constants
+
+    Float_t fTime;              // A user settable time of the system
+
+    // The implementation of the cell behaviour (crosstalk and afterpulses)
+    Float_t HitCellImp(Int_t x, Int_t y, Float_t t=0);
+
+    // Processing of afterpulses
+    void GenerateAfterpulse(UInt_t cell, Int_t idx, Double_t charge, Double_t t);
+    void ProcessAfterpulses(Float_t time, Float_t dt);
+    void DeleteAfterpulses(Float_t time);
+
+public:
+    APD(Int_t n, Float_t prob=0, Float_t dt=0, Float_t rt=0);
+
+    // --- Setter and Getter ----
+
+    // Set the afterpulse probability and time-constant of distribution 1 and 2
+    void SetAfterpulse1(Double_t p, Double_t tau) { fAfterpulseProb[0]=p; fAfterpulseTau[0]=tau; }
+    void SetAfterpulse2(Double_t p, Double_t tau) { fAfterpulseProb[1]=p; fAfterpulseTau[1]=tau; }
+
+    // Set the afterpulse probability for distribution 1 and 2
+    void SetAfterpulseProb(Double_t p1, Double_t p2) { fAfterpulseProb[0]=p1; fAfterpulseProb[1]=p2; }
+
+    // Getter functions
+    Float_t GetCellContent(Int_t x, Int_t y) const { return fHist.GetBinContent(x, y); }
+    Int_t   GetNumCellsX() const { return fHist.GetNbinsX(); }
+
+    Float_t GetCrosstalkProb() const { return fCrosstalkProb; }
+    Float_t GetDeadTime() const { return fDeadTime; }
+    Float_t GetRecoveryTime() const { return fRecoveryTime; }
+    Float_t GetTime() const { return fTime; }
+
+    Float_t GetRelaxationTime(Float_t threshold=0.001) const;
+
+    Float_t GetLastHit() const { return fHist.GetMaximum(); }
+
+    TSortedList &GetListOfAfterpulses() { return fAfterpulses; }
+
+    // Functions for easy production of statistics about the cells
+    Int_t CountDeadCells(Float_t t=0) const;
+    Int_t CountRecoveringCells(Float_t t=0) const;
+
+    // --- Lower level user interface ---
+
+    // Implementation to hit a specified or random cell
+    Float_t HitCell(Int_t x, Int_t y, Float_t t=0);
+    Float_t HitRandomCell(Float_t t=0);
+
+    // Functions to produce virgin chips or just effected by constant rates
+    void FillEmpty(Float_t t=0);
+    void FillRandom(Float_t rate, Float_t t=0);
+
+    // Produce random pulses with the given rate over a time dt.
+    // Processes afterpulses until the new time and deletes previous
+    // afterpulses.
+    Float_t Evolve(Double_t freq, Double_t dt);
+
+    // Delete Afterpulses before fTime. This might be wanted after
+    // a call to Evolve or Relax to maintain memeory usage.
+    void DeleteAfterpulses() { DeleteAfterpulses(fTime); }
+
+    // --- High level user interface ---
+
+    // This fills a G-APD with a rough estimated state at a given time
+    // T=0. It then evolves the time over the ralaxation time. If the
+    // chip is not virgin (i.e. fTime<0) the random filling is omitted
+    void Init(Float_t rate) { if (fTime<0) FillRandom(rate); Relax(rate); ShiftTime(); }
+
+    // Shifts all times including fTime by dt backwards (adds -dt)
+    // This is convenient because you can set the current time (fTime) to 0
+    void ShiftTime(Double_t dt);
+    void ShiftTime() { ShiftTime(fTime); }
+
+    // Functions producing photons hitting cells. It is meant to add
+    // many photons with an arrival time t after fTime. The photons
+    // must be sorted in time first to ensure proper treatment of the
+    // afterpulses.
+    Float_t HitRandomCellRelative(Float_t t=0) { ProcessAfterpulses(fTime, t); return HitRandomCell(fTime+t); }
+
+    // Produce random pulses with a given frequency until the influence
+    // of the effects of the G-APD (relaxation time, afterpulses) are
+    // below the given threshold. (Calls Evolve())
+    // FIXME: Maybe the calculation of the relaxation time could be optimized?
+    Float_t Relax(Double_t freq, Float_t threshold=0.001) { return Evolve(freq, GetRelaxationTime(threshold)); }
+
+    // Issue afterpulses until fTime+dt and set fTime to fTime+dt
+    // This is needed to create all afterpulses from external pulses
+    // and afterpulses until the time fTime+dt. This makes mainly
+    // the list of afterpulses complete until fTime+dt
+    void IncreaseTime(Float_t dt) { ProcessAfterpulses(fTime, dt); fTime += dt; }
+
+    // TObject
+    void Draw(Option_t *o="") { fHist.Draw(o); }
+    void DrawCopy(Option_t *o="") { fHist.DrawCopy(o); }
+
+    ClassDef(APD, 1) // An object representing a Geigermode APD
+};
+
+class Afterpulse : public TObject
+{
+private:
+    UInt_t  fCellIndex;  // Index of G-APD cell the afterpulse belongs to
+
+    Float_t fTime;       // Time at which the afterpulse avalanch broke through
+    Float_t fAmplitude;  // Amplitude (crosstalk!) the pulse produced
+
+    Int_t Compare(const TObject *obj) const
+    {
+        return static_cast<const Afterpulse*>(obj)->fTime>fTime ? -1 : 1;
+    }
+
+    Bool_t IsSortable() const { return kTRUE; }
+
+public:
+    Afterpulse(UInt_t idx, Float_t t) : fCellIndex(idx), fTime(t), fAmplitude(0) { }
+
+    UInt_t GetCellIndex() const { return fCellIndex; }
+
+    Float_t GetTime() const { return fTime; }
+    Float_t GetAmplitude() const { return fAmplitude; }
+
+    Float_t Process(APD &apd)
+    {
+        // Do not process afterpulses twice (e.g. HitRelative + IncreaseTime)
+        // This should not happen anyway
+        //        if (fAmplitude>0)
+        //            return fAmplitude;
+
+        const UInt_t nx  = apd.GetNumCellsX()+2;
+
+        const UInt_t x = fCellIndex%nx;
+        const UInt_t y = fCellIndex/nx;
+
+        fAmplitude = apd.HitCellImp(x, y, fTime);
+
+        return fAmplitude;
+    }
+    ClassDef(Afterpulse, 1) // An Afterpulse object
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/melectronics/MDigitalSignal.cc
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MDigitalSignal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MDigitalSignal.cc	(revision 17960)
@@ -0,0 +1,129 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MDigitalSignal
+//
+// A digital signal with a start time and length.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MDigitalSignal.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MDigitalSignal);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Initialize a new signal with a coincidence (and) of the two given
+// signals.
+//
+MDigitalSignal::MDigitalSignal(const MDigitalSignal &ttl1, const MDigitalSignal &ttl2) : fIndex(-1)
+{
+    const Double_t new0 = TMath::Max(ttl1.fStart,              ttl2.fStart);
+    const Double_t new1 = TMath::Min(ttl1.fStart+ttl1.fLength, ttl2.fStart+ttl2.fLength);
+
+    fStart  = new0;
+    fLength = new1-new0;
+}
+
+// ------------------------------------------------------------------------
+//
+// Compare the start time of two signal.
+//
+// Returns:
+//    0) Both signals have identical start time
+//    1) the argument starts earlier than this
+//   -1) The argument starts later than this
+//
+Int_t MDigitalSignal::Compare(const TObject *obj) const
+{
+    const MDigitalSignal &ttl = *static_cast<const MDigitalSignal*>(obj);
+
+    if (ttl.fStart>fStart)
+        return -1;
+
+    if (ttl.fStart<fStart)
+        return 1;
+
+    return 0;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return whether two signals overlap.
+//
+Bool_t MDigitalSignal::Overlap(const TObject &obj) const
+{
+    const MDigitalSignal &ttl = static_cast<const MDigitalSignal&>(obj);
+
+    return fStart<=ttl.fStart+ttl.fLength && ttl.fStart<=fStart+fLength;
+}
+
+// ------------------------------------------------------------------------
+//
+// Combine a new (overlapping) signal with this signal to one signal.
+// If they don't overlap kFALSE is returned, kTRUE otherwise.
+//
+Bool_t MDigitalSignal::Combine(const TObject &obj)
+{
+    if (!Overlap(obj))
+        return kFALSE;
+
+    const MDigitalSignal &ttl = static_cast<const MDigitalSignal&>(obj);
+
+    const Double_t new0 = TMath::Min(fStart,         ttl.fStart);
+    const Double_t new1 = TMath::Max(fStart+fLength, ttl.fStart+ttl.fLength);
+
+    fStart  = new0;
+    fLength = new1-new0;
+
+    return kTRUE;
+}
+
+/*
+Bool_t Overlay(const TObject &obj)
+{
+    const TTL &ttl = static_cast<const TTL&>(obj);
+
+    const Double_t new0 = TMath::Max(fStart,         ttl.fStart);
+    const Double_t new1 = TMath::Min(fStart+fLength, ttl.fStart+ttl.fLength);
+
+    fStart  = new0;
+    fLength = new1-new0;
+
+    return IsValid();
+}*/
+
+
+void MDigitalSignal::Print(Option_t *o) const
+{
+    gLog << all << Form("%.2f,%.2f ", fStart, fStart+fLength) << endl;
+}
Index: branches/Mars_McMismatchStudy/melectronics/MDigitalSignal.h
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MDigitalSignal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MDigitalSignal.h	(revision 17960)
@@ -0,0 +1,68 @@
+#ifndef MARS_MDigitalSignal
+#define MARS_MDigitalSignal
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+
+//#include <climits>
+
+class MDigitalSignal : public TObject
+{
+    Double_t fStart;
+    Double_t fLength;
+
+    Int_t fIndex;
+
+public:
+    MDigitalSignal(Double_t start=0, Double_t len=1e12/*FLT_MAX*/) : fStart(start), fLength(len), fIndex(-1)
+    {
+    }
+
+    MDigitalSignal(const MDigitalSignal &ttl) : TObject(ttl), fStart(ttl.fStart), fLength(ttl.fLength), fIndex(ttl.fIndex)
+    {
+    }
+
+    MDigitalSignal(const MDigitalSignal &ttl1, const MDigitalSignal &ttl2);
+
+    // Setter
+    void SetIndex(Int_t idx=-1) { fIndex=idx; }
+
+    // Getter
+    Bool_t IsValid() const { return fLength>0; }
+
+    Double_t GetStart() const  { return fStart; }
+    Double_t GetEnd() const    { return fStart+fLength; }
+    Double_t GetLength() const { return fLength; }
+
+    Int_t GetIndex() const { return fIndex; }
+    Bool_t IsConnected() const { return fIndex>=0; }
+
+    // TObject
+    Bool_t IsSortable() const { return kTRUE; }
+    Int_t  Compare(const TObject *obj) const;
+    void   Print(Option_t *o="") const;
+
+    // MDigitalSignal
+    Bool_t Overlap(const TObject &obj) const;
+    Bool_t Combine(const TObject &obj);
+
+    MDigitalSignal GetCoincidence(const MDigitalSignal &ttl) const
+    {
+        return MDigitalSignal(*this, ttl);
+    }
+
+    const MDigitalSignal operator&&(const MDigitalSignal &ttl) const
+    {
+        return GetCoincidence(ttl);
+    }
+    const MDigitalSignal operator||(const MDigitalSignal &ttl) const
+    {
+        MDigitalSignal cpy(ttl);
+        return !cpy.Combine(*this) ? MDigitalSignal(0, -1) : cpy;
+    }
+
+    ClassDef(MDigitalSignal, 1) // A digital signal with a start time and a length
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/melectronics/MPulseShape.cc
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MPulseShape.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MPulseShape.cc	(revision 17960)
@@ -0,0 +1,221 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MPulseShape
+//
+// This container describes the pulse shape of a pulse.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MPulseShape.h"
+
+#include <TF1.h>
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MSpline3.h"
+
+ClassImp(MPulseShape);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MPulseShape::MPulseShape(const char* name, const char *title)
+: fSpline(0), fFunction("exp(-(x/2)^2/2)"), fNpx(25), fXmin(-8), fXmax(8)
+{
+    fName  = name  ? name  : "MPulseShape";
+    fTitle = title ? title : "";
+
+    SetFunction(fFunction, fNpx, fXmin, fXmax);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Call Clear()
+//
+MPulseShape::~MPulseShape()
+{
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete fSpline if set and set it to 0
+//
+void MPulseShape::Clear(Option_t *)
+{
+    if (fSpline)
+        delete fSpline;
+    fSpline=0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the width of the range in which the spline is defined.
+//
+Float_t MPulseShape::GetPulseWidth() const
+{
+    return fSpline ? fSpline->GetXmax()-fSpline->GetXmin() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the lower edge of the range in which the spline is defined.
+//
+Float_t MPulseShape::GetXmin() const
+{
+    return fSpline ? fSpline->GetXmin() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the upper edge of the range in which the spline is defined.
+//
+Float_t MPulseShape::GetXmax() const
+{
+    return fSpline ? fSpline->GetXmax() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Read the intended pulse shape from a file and initialize the spline
+// accordingly
+//
+Bool_t MPulseShape::ReadFile(const char *fname)
+{
+    if (fname)
+        fFileName = fname;
+
+    *fLog << inf << "Reading pulse shape from " << fFileName << endl;
+
+    const TGraph g(fFileName);
+    if (g.GetN()==0)
+    {
+        *fLog << err << "ERROR - No data points from " << fFileName << "." << endl;
+        return kFALSE;
+    }
+
+    // option: b1/e1 b2/e2   (first second derivative?)
+    // option: valbeg/valend (first second derivative?)
+
+    Clear();
+    fSpline = new MSpline3(g);//, fRunHeader->GetFreqSampling()/1000.);
+    fSpline->SetTitle("MPulseShape");
+
+    // FIXME: Make a boundary condition e1b1,0,0 (First der, at Xmin and Xmax==0)
+    // FIXME: Force the spline to be 0 at Xmin and Xmax?
+
+    return kTRUE;
+}
+
+void MPulseShape::SetFunction(const TF1 &f)
+{
+    // FIXME: Use TF1 directly? (In most cases this seems to be slower)
+
+    // option: b1/e1 b2/e2   (first second derivative?)
+    // option: valbeg/valend (first second derivative?)
+
+    // if (f.GetNpar()==0)
+    // No SUPPORT
+
+    Clear();
+    fSpline = new MSpline3(f);//, fRunHeader->GetFreqSampling()/1000.);
+    fSpline->SetTitle("MPulseShape");
+
+    // FIXME: Make a boundary condition e1b1,0,0 (First der, at Xmin and Xmax==0)
+    // FIXME: Force the spline to be 0 at Xmin and Xmax?
+
+    fFunction = f.GetTitle();
+}
+
+Bool_t MPulseShape::SetFunction(const char *func, Int_t n, Double_t xmin, Double_t xmax)
+{
+    // FIXME: Use TF1 directly? (In most cases this seems to be slower)
+    TF1 f("f", func, xmin, xmax);
+    f.SetNpx(n);
+
+    SetFunction(f);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FileName: pulse-shape.txt
+// Function.Name: gaus
+// Function.Npx:    50
+// Function.Xmin:  -5
+// Function.Xmax:   5
+//
+Int_t MPulseShape::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FileName", print))
+    {
+        rc = kTRUE;
+        SetFileName(GetEnvValue(env, prefix, "FileName", fFileName));
+        if (!fFileName.IsNull())
+            if (ReadFile(fFileName))
+                return kERROR;
+    }
+
+    if (IsEnvDefined(env, prefix, "Function.Name", print))
+    {
+        rc = kTRUE;
+
+        if (IsEnvDefined(env, prefix, "Function.Npx", print))
+            fNpx = GetEnvValue(env, prefix, "Function.Npx", fNpx);
+        if (IsEnvDefined(env, prefix, "Function.Xmin", print))
+            fXmin = GetEnvValue(env, prefix, "Function.Xmin", fXmin);
+        if (IsEnvDefined(env, prefix, "Function.Xmax", print))
+            fXmax = GetEnvValue(env, prefix, "Function.Xmax", fXmax);
+
+        SetFunction(GetEnvValue(env, prefix, "Function.Name", fFunction), fNpx, fXmin, fXmax);
+    }
+
+    return rc;
+}
+
+void MPulseShape::Paint(Option_t *)
+{
+    fSpline->SetMarkerStyle(kFullDotMedium);
+
+    if (!fSpline->GetHistogram())
+        fSpline->Paint();
+
+    TH1 *h = fSpline->GetHistogram();
+    if (!h)
+        return;
+
+    h->SetXTitle("t [ns]");
+    h->SetYTitle("a.u.");
+
+    fSpline->Paint("PC");
+}
Index: branches/Mars_McMismatchStudy/melectronics/MPulseShape.h
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/MPulseShape.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/MPulseShape.h	(revision 17960)
@@ -0,0 +1,49 @@
+#ifndef MARS_MPulseShape
+#define MARS_MPulseShape
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TF1;
+class MSpline3;
+
+class MPulseShape : public MParContainer
+{
+private:
+    MSpline3          *fSpline;     // Spline to describe the pulse shape
+
+    TString fFileName;              // File name of a file describing the pulse shape
+
+    TString fFunction;              // Function describing the pulse shape
+    Int_t   fNpx;                   // Number of sampling points
+    Float_t fXmin;                  // lower edge of sampling
+    Float_t fXmax;                  // upper edge of sampling
+
+    Bool_t ReadFile(const char *fname);
+    Bool_t SetFunction(const char *func, Int_t n, Double_t xmin, Double_t xmax);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+public:
+    MPulseShape(const char *name=0, const char *title=0);
+    ~MPulseShape();
+
+    void SetFunction(const TF1 &f);
+    void SetFunction(const char *f)  { fFunction=f; fFileName=""; }
+    void SetFileName(const char *n)  { fFileName=n; fFunction=""; }
+
+    void Clear(Option_t *o="");
+    void Paint(Option_t *o="");
+
+    MSpline3 *GetSpline() const { return fSpline; }
+
+    Float_t GetPulseWidth() const;
+    Float_t GetXmin() const;
+    Float_t GetXmax() const;
+
+    ClassDef(MPulseShape, 1) // Parameter container to hold the setup for a pulse shape
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/melectronics/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/melectronics/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/melectronics/Makefile	(revision 17960)
@@ -0,0 +1,34 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Electronics
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mextralgo
+
+SRCFILES = MAvalanchePhotoDiode.cc \
+           MAnalogSignal.cc \
+           MAnalogChannels.cc \
+	   MDigitalSignal.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/merpp.cc
===================================================================
--- branches/Mars_McMismatchStudy/merpp.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/merpp.cc	(revision 17960)
@@ -0,0 +1,295 @@
+#include <TObjectTable.h>
+#include <TClass.h>
+
+#include "MArgs.h"
+#include "MArray.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MJMerpp.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 with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " merpp [options] [tel:]seqnumber  [outpath [inpath]]" << endl;
+    gLog << " merpp [options] [tel:]seqnumber  outpath sumfile.txt" << endl;
+    gLog << " merpp [options] seqfile.txt      [outpath [inpath]]" << endl;
+    gLog << " merpp [options] seqfile.txt      outpath sumfile.txt" << endl;
+//    gLog << " merpp [options] mysql           [outpath [inpath]]" << endl;
+//    gLog << " merpp [options] mysql           outpath sumfile.txt" << endl;
+    gLog << " merpp [options] infile.raw[.gz]  [outfile.root]" << endl;
+    gLog << " merpp [options] infile.fits[.gz] [outfile.root]" << endl;
+    gLog << " merpp [options] infile.rep       [outfile.root]" << endl;
+    gLog << " merpp [options] infile.txt       outfile.root" << endl;
+    gLog << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   [tel:]seqnumber           Telescope and sequence number to mbe merpped." << endl;
+    gLog << "   inpath                    The input  path where the CC files   are." << endl;
+    gLog << "   outpath                   The output path where the outputfile are or stored." << endl;
+    gLog << "   sumfile.txt               A central control report summary file (--summary can be omitted)." << endl;
+    gLog << "   infile.raw[.gz]           Magic DAQ binary file." << endl;
+    gLog << "   infile.rep                Magic Central Control report file." << endl;
+    gLog << "   infile.txt                Magic DC currents file." << endl;
+    gLog << "   outfile.root              Merpped root file." << endl;
+//    gLog << "   mysql                     mysql://user:password@host/database/tel:sequence" << endl;
+    gLog << endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+//    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+//    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+//    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+//    gLog << "   --debug-env=3             Debug setting resources from resource file and command line" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << endl;
+    gLog << " File Options:" << endl;
+    gLog << "   -c#                       Compression level #=1..9 [default=2]" << endl;
+    gLog << "   -f                        Force overwrite of an existing file" << endl;
+    gLog << "   -u, --update              Update an existing file." << endl;
+    gLog << endl;
+    gLog << " Raw Data Options:" << endl;
+    gLog << "   -ff                       Force merpp to ignore broken events and don't stop" << endl;
+    gLog << "   --interleave=#            Process only each i-th event [default=1]" << endl;
+    gLog << endl;
+    gLog << " Report/Currents File Options:" << endl;
+    gLog << "   --auto-time-start         Take time automatically from MRawRunHeader" << endl;
+    gLog << "                                (overwrites --start=, update only)" << endl;
+    gLog << "   --auto-time-stop          Take time automatically from MRawRunHeader" << endl;
+    gLog << "                                (overwrites --stop=, update only)" << endl;
+    gLog << "   --auto-time               Abbrev. for --auto-time-start and auto-time-stop" << endl;
+    gLog << "   --start=\"time\"          Start event time (format see MTime::SetSqlDateTime, update only)" << endl;
+    gLog << "   --stop=\"time\"           Stop  event time (format see MTime::SetSqlDateTime, update only)" << endl;
+    gLog << endl;
+    gLog << " Report Options:" << endl;
+    gLog << "   --rep-run=#               Only data corresponding to this run number as" << endl;
+    gLog << "                                taken from the RUN-REPORT is extracted" << endl;
+    gLog << "   --rep-file=#              Only data corresponding to this file number as" << endl;
+    gLog << "                                taken from the RUN-REPORT is extracted" << endl;
+    gLog << "   --header-run=#            Allow only run-control .rep-files with this" << endl;
+    gLog << "                                run number in there header" << endl;
+    gLog << "   --header-file=#           Allow only run-control .rep-files with this" << endl;
+    gLog << "                                file number in there header" << endl;
+    gLog << "   --telescope=#             Allow only run-control .rep-files with this" << endl;
+    gLog << "                                telescope number in there header" << endl;
+    gLog << "   --sumfile                 Check for an all night summary file" << endl;
+    gLog << "                                (from .rep header)" << endl;
+    gLog << "   --allfiles                Don't check file type <default>" << endl << endl;
+    gLog << "   --only=Name               Read only reports described by MReportName. See the" << endl;
+    gLog << "                                mreport-directory for available classes." << endl;
+    gLog << "   --dev-null                Suppress output of files (for test purpose)" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl;
+    gLog << endl;
+    gLog << " Compatibility (deprecated):" << endl;
+    gLog << "   --run=#                   See --rep-run (overwritten by --rep-run)" << endl;
+    gLog << "   --runfile=#               See --header-run (overwritten by --header-run)" << endl << endl;
+    gLog << " REMARK: - At the moment you can process a .raw _or_ a .rep file, only!" << endl;
+    gLog << "         - 'date/time' has the format 'yyyy-mm-dd/hh:mm:ss.mmm'" << endl << endl;
+}
+
+static bool HasExtension(const TString &name)
+{
+    return
+        name.EndsWith(".rep")  || name.EndsWith(".txt")    ||
+        name.EndsWith(".raw")  || name.EndsWith(".raw.gz") ||
+        name.EndsWith(".root") ||
+        name.EndsWith(".fits") || name.EndsWith(".fits.gz");
+}
+
+int main(const int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    arg.RemoveRootArgs();
+
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+    const Int_t   kComprlvl      = arg.GetIntAndRemove("-c", 2);
+    const Bool_t  kInterleave    = arg.GetIntAndRemove("--interleave=", 1);
+    const Bool_t  kOverwrite     = arg.HasOnlyAndRemove("-f");
+    const Bool_t  kForceProc     = arg.HasOnlyAndRemove("-ff");
+    const Int_t   run            = arg.GetIntAndRemove("--run=", -1);
+    const Int_t   kRunNumber     = arg.GetIntAndRemove("--rep-run=", run);
+    const Int_t   kFileNumber    = arg.GetIntAndRemove("--rep-file=", -1);
+    const Bool_t  kAutoTime      = arg.HasOnlyAndRemove("--auto-time");
+    const Bool_t  kAutoTimeStart = arg.HasOnlyAndRemove("--auto-time-start") || kAutoTime;
+    const Bool_t  kAutoTimeStop  = arg.HasOnlyAndRemove("--auto-time-stop")  || kAutoTime;
+    const Int_t   runfile        = arg.GetIntAndRemove("--runfile=", -1);
+          Int_t   kHeaderRun     = arg.GetIntAndRemove("--header-run=", runfile);
+    const Int_t   kHeaderFile    = arg.GetIntAndRemove("--header-file=", -1);
+    const Int_t   kTelescope     = arg.GetIntAndRemove("--telescope=", -1);
+          Bool_t  kUpdate        = arg.HasOnlyAndRemove("--update") || arg.HasOnlyAndRemove("-u");
+    const TString kOnly          = arg.GetStringAndRemove("--only", "");
+    const Bool_t  kNullOut    = arg.HasOnlyAndRemove("--dev-null");
+
+//    Int_t  kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+//    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    MTime kTimeStart(arg.GetStringAndRemove("--start="));
+    MTime kTimeStop(arg.GetStringAndRemove("--stop="));
+
+    if (arg.HasOnlyAndRemove("--sumfile"))
+        kHeaderRun  = 0;
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 2;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()<1 || arg.GetNumArguments()>3)
+    {
+        Usage();
+        return 2;
+    }
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    const Int_t narg = arg.GetNumArguments();
+
+    const TString arg0 = arg.GetArgumentStr(0);
+    const TString arg1 = arg.GetArgumentStr(1);
+    const TString arg2 = arg.GetArgumentStr(2);
+
+    const Bool_t isseq =
+        (narg==1 && arg0.EndsWith(".txt")) ||
+        (narg==2 && !HasExtension(arg1))   ||
+        (narg==3);
+
+    TString sequence, kNamein, kNameout;
+    if (isseq)
+    {
+        sequence = arg0;
+        kNameout = arg1;
+        kNamein  = arg2;
+
+        if (arg2.EndsWith(".txt"))  // set --summary
+        {
+            gLog << inf << "Summary file option switched on automatically due to file extension." << endl;
+            kHeaderRun = 0;
+        }
+
+        kUpdate = kTRUE;
+    }
+    else
+    {
+        kNamein  = arg0;
+        kNameout = arg1.IsNull() ? arg0(0, arg0.Last('.')) : arg1(0, arg1.Last('.'));
+
+        if (!kNameout.EndsWith(".root"))
+            kNameout += ".root";
+    }
+
+    //
+    // Initialize Non-GUI (batch) mode
+    //
+    gROOT->SetBatch();
+
+    //
+    // Ignore TObject Streamer (bits, uniqueid) for MArray and MParContainer
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    {
+        MJMerpp merpp(Form("MJMerpp %s", gSystem->BaseName(arg0.Data())));
+        merpp.SetOverwrite(kOverwrite);
+        merpp.SetCompression(kComprlvl);
+        merpp.SetUpdate(kUpdate);
+        merpp.SetInterleave(kInterleave);
+        merpp.SetForceProcessing(kForceProc);
+        merpp.SetConstrainHeader(kTelescope, kHeaderRun, kHeaderFile);
+        merpp.SetConstrainRunRep(kRunNumber, kFileNumber);
+        merpp.SetOnly(kOnly);
+        merpp.SetTime(kTimeStart, kTimeStop);
+        merpp.SetAutoTime(kAutoTimeStart, kAutoTimeStop);
+        merpp.SetNullOut(kNullOut);
+        //merpp.SetEnvDebug(kDebugEnv);
+        //merpp.SetEnv(&env);
+        //merpp.SetDisplay(d);;
+
+        merpp.SetPathIn(kNamein);
+        merpp.SetPathOut(kNameout);
+
+        const Int_t rc = sequence.IsNull() ? merpp.Process() : merpp.ProcessSeq(sequence);
+        if (rc>0)
+        {
+            gLog << err << "Merpp failed." << endl << endl;
+            return rc;
+        }
+
+        //if (kDebugEnv>0)
+        //    env.PrintUntouched();
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/mextralgo/ExtralgoIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mextralgo/ExtralgoIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mextralgo/ExtralgoIncl.h	(revision 17960)
@@ -0,0 +1,5 @@
+#ifndef __CINT__
+
+#include "../mbase/MArrayF.h"
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mextralgo/ExtralgoLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mextralgo/ExtralgoLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mextralgo/ExtralgoLinkDef.h	(revision 17960)
@@ -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 MExtralgoSpline+;
+#pragma link C++ class MExtralgoDigitalFilter+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mextralgo/MExtralgoDigitalFilter.cc
===================================================================
--- branches/Mars_McMismatchStudy/mextralgo/MExtralgoDigitalFilter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mextralgo/MExtralgoDigitalFilter.cc	(revision 17960)
@@ -0,0 +1,483 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko, 09/2004 <mailto:hbartko@mppmu.mpg.de> 
+!   Author(s): Thomas Bretz, 08/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtralgoDigitalFilter
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtralgoDigitalFilter.h"
+
+#include <TMath.h>
+#include <TRandom.h>
+
+using namespace std;
+
+Float_t MExtralgoDigitalFilter::ExtractNoise() const
+{
+    const Int_t pos  = gRandom->Integer(fNum-fWindowSize+1);
+    const Int_t frac = gRandom->Integer(fWeightsPerBin);
+
+    return Eval(fWeightsAmp, pos, frac-fWeightsPerBin/2);
+}
+
+// -----------------------------------------------------------------------------
+//
+// Calculates the chi2 of the fit, once the weights have been iterated.
+// Argument: time, obtained after a call to EvalDigitalFilterHiGain
+//
+Float_t MExtralgoDigitalFilter::GetChisq(const Int_t maxp, const Int_t frac, const Float_t sum) const
+{
+    /*
+    TMatrix g (windowh,1);
+    TMatrix gt(windowh,1);
+    TMatrix y (windowh,1);
+
+    const Float_t etau   = fFineAdjustHi*sumhi;
+    const Float_t t_fine = TMath::Abs(fFineAdjustHi)< 1./fBinningResolutionHiGain ? -fFineAdjustHi : 0.;
+
+    //   if (t_fine==0.)
+    //     return -1.;
+
+    if (fDebug)
+        gLog << all << " fMaxPHi: " << fMaxPHi << " fIterPHi " << fIterPHi << " t_fine: " << t_fine << endl;
+
+    //
+    // Slide with a window of size windowh over the sample
+    // and calculate the arrays by interpolating the pulse shape using the
+    // fine-tuned time information.
+    //
+    for (Int_t sample=0; sample &lt; windowh; sample++)
+    {
+        const Int_t idx = fArrBinningResHalfHiGain[sample] + fIterPHi;
+        const Int_t ids = fMaxPHi + sample;
+
+        y [sample][0]     = fHiGainSignalDF[ids];
+        g [sample][0]     = t_fine >= 0
+            ? (fPulseShapeHiGain[idx]    + t_fine*(fPulseShapeHiGain[idx+1]   -fPulseShapeHiGain[idx])  )*sumhi
+            : (fPulseShapeHiGain[idx]    + t_fine*(fPulseShapeHiGain[idx]     -fPulseShapeHiGain[idx-1]))*sumhi;
+        gt[sample][0]     = t_fine >= 0
+            ? (fPulseShapeDotHiGain[idx] + t_fine*(fPulseShapeDotHiGain[idx+1]-fPulseShapeDotHiGain[idx])   )*etau
+            : (fPulseShapeDotHiGain[idx] + t_fine*(fPulseShapeDotHiGain[idx]  -fPulseShapeDotHiGain[idx-1]) )*etau;
+    }
+
+    TMatrix second = y - g - gt;
+    TMatrix first(TMatrix::kTransposed,second);
+    TMatrix chisq = first * ((*fBHiInv)*second);
+
+    return chisq[0][0]/(windowh-2);
+    */
+/*
+
+    TMatrix S(fWindowSize, 1); // Signal (start==start of window)
+    for (int i=0; i<fWindowSize; i++)
+        S[i][0] = fVal[i+maxp];
+
+    TMatrix g(fWindowSize, 1);
+    //TMatrix gT(fWindowSize, 1);
+
+    for (int i=0; i<fWindowSize; i++)
+    {
+        Int_t idx = fWeightsPerBin*i + frac;
+
+        // FIXME: Maybe we could do an interpolation on time-fineadj?
+        //Float_t slope  = fPulseShapeHiGain[idx+1]   -fPulseShapeHiGain[idx];
+        //Float_t slopet = fPulseShapeDotHiGain[idx+1]-fPulseShapeDotHiGain[idx];
+
+        g[i][0] = fPulseShapeHiGain[idx]   *sumhi;
+        //gT[i][0] = fPulseShapeHiGainDot[idx]*tau;
+    }
+
+    TMatrix Ainv; // Autocorrelation Matrix (inverted)
+
+    TMatrix m = S - g;// - gT;
+    TMatrix mT(TMatrix::kTransposed, m);
+
+    TMatrix chisq = mT * (Ainv*m);
+
+    return chisq[0][0]/(fWindowSize-2);
+  */
+
+    Double_t sumc = 0;
+
+    TMatrix d(fWindowSize, 1); // Signal (start==start of window)
+    for (int i=0; i<fWindowSize; i++)
+    {
+        d[i][0] = fVal[i+maxp]/sum - fPulseShape[fWeightsPerBin*i + frac];
+        sumc += d[i][0]*d[i][0];
+    }
+
+/*
+    TMatrix Ainv; // Autocorrelation Matrix (inverted)
+
+    TMatrix dT(TMatrix::kTransposed, d);
+
+    TMatrix chisq = dT * (*fAinv*d);
+  */
+    return sumc;//chisq[0][0]/(fWindowSize-2);
+}
+
+Int_t MExtralgoDigitalFilter::AlignExtractionWindow(Int_t &maxp, Int_t &frac, const Double_t ampsum)
+{
+    // Align extraction window to signal position
+
+    const Double_t timesum = Eval(fWeightsTime, maxp, frac);
+
+    // Because fWeightsPerBin/2 doesn't correspond to the center
+    // of a bin the time-values extracted are slightly positive.
+    // They are roughly between -0.45 and 0.55
+    const Double_t binoffset = TMath::Even(fWeightsPerBin) ? 0.5 : 0;
+
+    // This is the time offset from the extraction position
+    Double_t tmoffset = (frac+binoffset)/fWeightsPerBin + timesum/ampsum;
+
+    // Convert the residual fraction of one slice into an
+    // offset position in the extraction weights
+    const Int_t integ = TMath::FloorNint(tmoffset+0.5);
+
+    /*
+    if (integ>0)
+        tmoffset=0.49-0.05;
+    if (integ<0)
+        tmoffset=-0.49-0.05;
+    integ=0;
+    */
+
+    // move the extractor by an offset number of slices
+    // determined by the extracted time
+    maxp -= integ;
+
+    frac  = TMath::FloorNint((tmoffset-integ)*fWeightsPerBin);
+
+    // Align maxp into available range (TO BE CHECKED)
+    AlignIntoLimits(maxp, frac);
+
+    return integ;
+}
+
+void MExtralgoDigitalFilter::Extract(Int_t maxpos)
+{
+    fSignal    =  0; // default is: no pulse found
+    fTime      = -2; // default is: out if range (--> random)
+    fSignalDev =  0; // default is: valid
+    fTimeDev   =  0; // default is: valid
+
+    // FIXME: How to handle saturation?
+
+    Double_t maxamp = -FLT_MAX;
+    Int_t    maxp   = -1;
+
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    // For the case of an even number of weights/bin there is
+    // no central bin.So we create an artificial central bin.
+    for (Int_t i=0; i<fNum-fWindowSize+1; i++)
+    {
+        const Double_t sumamp = Eval(fWeightsAmp, i);
+        if (sumamp>maxamp)
+        {
+            maxamp = sumamp;
+            maxp   = i;
+        }
+    }
+
+    /*
+     // This could be for a fast but less accurate extraction....
+     maxamp = Eval(fWeightsAmp, maxpos-fWindowSize/2);
+     maxp   = maxpos-fWindowSize/2;
+     */
+
+    // The number of available slices were smaller than the
+    // extraction window size of the extractor
+    if (maxp<0)
+    {
+        fSignalDev = -1;  // means: is invalid
+        fTimeDev   = -1;  // means: is invalid
+        return;
+    }
+
+    // For some reason (by chance or because all slices contain 0)
+    // maxamp is 0. This means the signal is zero and no arrival
+    // time can be extracted (but both informations are valid)
+    if (maxamp==0)
+        return;
+
+    Int_t frac = 0;
+    const Int_t shift = AlignExtractionWindow(maxp, frac, maxamp);
+
+    // For safety we do another iteration if we have
+    // shifted the extraction window
+    if (TMath::Abs(shift)>0)
+        AlignExtractionWindow(maxp, frac);
+
+    // Now we have found the "final" position: extract time and charge
+    const Double_t sumamp = Eval(fWeightsAmp, maxp, frac);
+
+    fSignal = sumamp;
+    if (sumamp == 0)
+        return;
+
+    const Double_t sumtime = Eval(fWeightsTime, maxp, frac);
+
+    // This is used to align the weights to bins between
+    // -0.5/fWeightsPerBin and 0.5/fWeightsPerBin instead of
+    // 0 and 1./fWeightsPerBin
+    const Double_t binoffset = TMath::Even(fWeightsPerBin) ? 0.5 : 0;
+
+    fTime = maxp /*- 0.5*/ -  Double_t(frac+binoffset)/fWeightsPerBin;
+
+    // To let the lowest value which can be safely extracted be>0:
+    // Take also a possible offset from timefineadjust into account
+    //  Sould it be: fTime += fWindowSize/2; ???
+
+    // HERE we should add the distance from the beginning of the
+    // extraction window to the leading edge!
+    fTime += 0.5 + 0.5/fWeightsPerBin;
+    // Define in each extractor a lowest and highest extracted value!
+
+    const Float_t timefineadjust = sumtime/sumamp;
+
+    //if (TMath::Abs(timefineadjust) < 0.2)
+        fTime -= timefineadjust;
+}
+
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TMatrixD.h>
+#include <TArrayF.h>
+#include <iostream>
+#include <TSpline.h>
+#include <TProfile.h>
+
+Int_t MExtralgoDigitalFilter::CalculateWeights(TH1 &shape, const TH2 &autocorr, TArrayF &weightsamp, TArrayF &weightstime, Int_t wpb)
+{
+    const Int_t weightsperbin = wpb<=0?shape.GetNbinsX()/autocorr.GetNbinsX():wpb;
+
+    if (wpb<=0 && weightsperbin*autocorr.GetNbinsX()!=shape.GetNbinsX())
+    {
+        cout << "ERROR - Number of bins mismatch..." << endl;
+        cout << "        Shape: " << shape.GetNbinsX() << endl;
+        cout << "        ACorr: " << autocorr.GetNbinsX() << endl;
+        return -1;
+    }
+
+    const TAxis &axe = *shape.GetXaxis();
+
+    const Int_t first = axe.GetFirst()/weightsperbin;
+    const Int_t last  = axe.GetLast() /weightsperbin;
+
+    const Int_t width = last-first;
+
+    cout << "Range:  " << first << " <= bin < " << last << endl;
+    cout << "Window: " << width << endl;
+    cout << "W/Bin:  " << weightsperbin << endl;
+
+    // ---------------------------------------------
+
+    const Float_t sum = shape.Integral(first*weightsperbin, last*weightsperbin-1)/weightsperbin;
+    shape.Scale(1./sum);
+
+    cout << "Sum:    " << sum << endl;
+
+//    TGraph gr(&shape);
+//    TSpline5 val("Signal", &gr);
+
+    // FIXME: DELETE!!!
+    TH1 &derivative = *static_cast<TH1*>(shape.Clone());
+    derivative.SetDirectory(0);
+    derivative.Reset();
+
+    for (int i=0; i<derivative.GetNbinsX(); i++)
+    {
+//       const Float_t x = derivative.GetBinCenter(i+1);
+//       derivative.SetBinContent(i+1, val.Derivative(x));
+
+        const Float_t binm = shape.GetBinContent(i+1-1);
+        const Float_t binp = shape.GetBinContent(i+1+1);
+
+        const Float_t der = (binp-binm)/2./shape.GetBinWidth(1);
+
+        derivative.SetBinContent(i+1, der);
+
+        if (derivative.InheritsFrom(TProfile::Class()))
+            static_cast<TProfile&>(derivative).SetBinEntries(i+1,1);
+    }
+
+    // ---------------------------------------------
+
+    TMatrixD B(width, width);
+    for (Int_t i=0; i<width; i++)
+        for (Int_t j=0; j<width; j++)
+            B[i][j]=autocorr.GetBinContent(i+1/*first*/, j+1/*first*/);
+
+    const TMatrixD Binv(TMatrixD::kInverted, B);
+
+    // ---------------------------------------------
+
+    weightsamp.Set(width*weightsperbin);
+    weightstime.Set(width*weightsperbin);
+
+    for (Int_t i=0; i<weightsperbin; i++)
+    {
+        TMatrixD g(width, 1);
+        TMatrixD d(width, 1);
+
+        for (Int_t bin=0; bin<width; bin++)
+        {
+            const Int_t idx = weightsperbin*(bin+first) + i;
+
+            g[bin][0]=shape.GetBinContent(idx+1);
+            d[bin][0]=derivative.GetBinContent(idx+1);
+        }
+
+        const TMatrixD gT(TMatrixD::kTransposed, g);
+        const TMatrixD dT(TMatrixD::kTransposed, d);
+
+        const TMatrixD denom  = (gT*(Binv*g))*(dT*(Binv*d)) - (dT*(Binv*g))*(dT*(Binv*g));
+
+        if (denom[0][0]==0)
+        {
+            cout << "ERROR - Division by zero: denom[0][0]==0 for i=" << i << "." << endl;
+            return -1;
+        }
+
+        const TMatrixD w_amp  = (dT*(Binv*d))*(gT*Binv) - (gT*(Binv*d))*(dT*Binv);
+        const TMatrixD w_time = (gT*(Binv*g))*(dT*Binv) - (gT*(Binv*d))*(gT*Binv);
+
+        for (Int_t bin=0; bin<width; bin++)
+        {
+            const Int_t idx = weightsperbin*bin + i;
+
+            weightsamp[idx]  = w_amp [0][bin]/denom[0][0];
+            weightstime[idx] = w_time[0][bin]/denom[0][0];
+        }
+    }
+
+    return first*weightsperbin;
+}
+
+Int_t MExtralgoDigitalFilter::CalculateWeights2(TH1 &shape, const TH2 &autocorr, TArrayF &weightsamp, TArrayF &weightstime, Int_t wpb)
+{
+    const Int_t weightsperbin = wpb<=0?shape.GetNbinsX()/autocorr.GetNbinsX():wpb;
+
+    if (wpb<=0 && weightsperbin*autocorr.GetNbinsX()!=shape.GetNbinsX())
+    {
+        cout << "ERROR - Number of bins mismatch..." << endl;
+        cout << "        Shape: " << shape.GetNbinsX() << endl;
+        cout << "        ACorr: " << autocorr.GetNbinsX() << endl;
+        return -1;
+    }
+
+    const TAxis &axe = *shape.GetXaxis();
+
+    const Int_t first = axe.GetFirst()/weightsperbin;
+    const Int_t last  = axe.GetLast() /weightsperbin;
+
+    const Int_t width = last-first;
+
+    cout << "Range:  " << first << " <= bin < " << last << endl;
+    cout << "Window: " << width << endl;
+    cout << "W/Bin:  " << weightsperbin << endl;
+
+    // ---------------------------------------------
+
+    const Float_t sum = shape.Integral(first*weightsperbin, last*weightsperbin-1)/weightsperbin;
+    shape.Scale(1./sum);
+
+    TGraph gr(&shape);
+    TSpline5 val("Signal", &gr);
+
+    // FIXME: DELETE!!!
+    TH1 &derivative = *static_cast<TH1*>(shape.Clone());
+    derivative.SetDirectory(0);
+    derivative.Reset();
+
+    for (int i=0; i<derivative.GetNbinsX(); i++)
+    {
+        const Float_t x = derivative.GetBinCenter(i+1);
+        derivative.SetBinContent(i+1, val.Derivative(x));
+
+     /*
+        const Float_t binm = shape.GetBinContent(i+1-1);
+        const Float_t binp = shape.GetBinContent(i+1+1);
+
+        const Float_t der = (binp-binm)/2./shape.GetBinWidth(1);
+
+        derivative.SetBinContent(i+1, der);
+      */
+    }
+
+    // ---------------------------------------------
+
+    TMatrixD B(width, width);
+    for (Int_t i=0; i<width; i++)
+        for (Int_t j=0; j<width; j++)
+            B[i][j]=autocorr.GetBinContent(i+first, j+first);
+    B.Invert();
+
+    // ---------------------------------------------
+
+    weightsamp.Set(width*weightsperbin);
+    weightstime.Set(width*weightsperbin);
+
+    for (Int_t i=0; i<weightsperbin; i++)
+    {
+        TMatrixD g(width, 1);
+        TMatrixD d(width, 1);
+
+        for (Int_t bin=0; bin<width; bin++)
+        {
+            const Int_t idx = weightsperbin*(bin+first) + i;
+
+            g[bin][0]=shape.GetBinContent(idx+1);
+            d[bin][0]=derivative.GetBinContent(idx+1);
+        }
+
+        const TMatrixD gT(TMatrixD::kTransposed, g);
+        const TMatrixD dT(TMatrixD::kTransposed, d);
+
+        const TMatrixD denom  = (gT*(B*g))*(dT*(B*d)) - (dT*(B*g))*(dT*(B*g));
+
+        if (denom[0][0]==0)
+        {
+            cout << "ERROR - Division by zero: denom[0][0]==0 for i=" << i << "." << endl;
+            return -1;
+        }
+
+        const TMatrixD w_amp  = (dT*(B*d))*(gT*B) - (gT*(B*d))*(dT*B);
+        const TMatrixD w_time = (gT*(B*g))*(dT*B) - (gT*(B*d))*(gT*B);
+
+        for (Int_t bin=0; bin<width; bin++)
+        {
+            const Int_t idx = weightsperbin*bin + i;
+
+            weightsamp[idx]  = w_amp [0][bin]/denom[0][0];
+            weightstime[idx] = w_time[0][bin]/denom[0][0];
+        }
+    }
+    return first*weightsperbin;
+}
Index: branches/Mars_McMismatchStudy/mextralgo/MExtralgoDigitalFilter.h
===================================================================
--- branches/Mars_McMismatchStudy/mextralgo/MExtralgoDigitalFilter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mextralgo/MExtralgoDigitalFilter.h	(revision 17960)
@@ -0,0 +1,132 @@
+#ifndef MARS_MExtralgoDigitalFilter
+#define MARS_MExtralgoDigitalFilter
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+
+class TH1;
+class TH2;
+class TH1F;
+class TH2F;
+class TArrayF;
+
+class MExtralgoDigitalFilter
+{
+private:
+    // Input
+    const Float_t *fVal;
+    Int_t fNum;
+
+    Float_t const *fWeightsAmp;
+    Float_t const *fWeightsTime;
+    Float_t const *fPulseShape;
+
+    const TMatrix *fAinv;
+
+    const Int_t fWeightsPerBin; // Number of weights per data bin
+    const Int_t fWindowSize;
+
+    // Result
+    Float_t fTime;
+    Float_t fTimeDev;
+    Float_t fSignal;
+    Float_t fSignalDev;
+
+    Float_t GetChisq(const Int_t maxp, const Int_t frac, const Float_t sum) const;
+
+    inline Double_t ChiSq(const Double_t sum, const Int_t startv, const Int_t startw=0) const
+    {
+        //
+        // Slide with a window of size windowsize over the sample
+        // and multiply the entries with the corresponding weights
+        //
+        Double_t chisq = 0;
+
+        // Shift the start of the weight to the center of sample 0
+        Float_t const *w = fPulseShape + startw;
+
+        const Float_t *beg = fVal+startv;
+        for (Float_t const *pex=beg; pex<beg+fWindowSize; pex++)
+        {
+            const Double_t c = *w - *pex/sum;
+            chisq += c*c;
+            w += fWeightsPerBin;
+        }
+        return chisq;
+    }
+
+    // Weights: Weights to evaluate
+    // Startv: Index of first bin of data
+    // startw: Offset on the weights
+    inline Double_t Eval(Float_t const *weights, const Int_t startv, const Int_t startw=0) const
+    {
+        //
+        // Slide with a window of size windowsize over the sample
+        // and multiply the entries with the corresponding weights
+        //
+        Double_t sum = 0;
+
+        // Shift the start of the weight to the center of sample 0
+        Float_t const *w = weights + startw;
+
+        const Float_t *beg = fVal+startv;
+        for (Float_t const *pex=beg; pex<beg+fWindowSize; pex++)
+        {
+            sum += *w * *pex;
+            w += fWeightsPerBin;
+        }
+        return sum;
+    }
+
+    inline void AlignIntoLimits(Int_t &maxp, Int_t &frac) const
+    {
+        // Align maxp into available range (TO BE CHECKED)
+        if (maxp < 0)
+        {
+            maxp = 0;
+            frac = fWeightsPerBin/2-1; // Assume peak at the end of the last slice
+        }
+        if (maxp > fNum-fWindowSize)
+        {
+            maxp = fNum-fWindowSize;
+            frac = -fWeightsPerBin/2; // Assume peak at the beginning of the first slice
+        }
+    }
+
+    Int_t AlignExtractionWindow(Int_t &maxp, Int_t &frac, const Double_t ampsum);
+    void  AlignExtractionWindow(Int_t &maxp, Int_t &frac)
+    {
+        const Double_t amp = Eval(fWeightsAmp, maxp, frac);
+        if (amp!=0)
+            AlignExtractionWindow(maxp, frac, amp);
+    }
+
+public:
+    MExtralgoDigitalFilter(Int_t res, Int_t windowsize, Float_t *wa, Float_t *wt, Float_t *ps=0, TMatrix *ainv=0)
+        : fVal(0), fNum(0), fWeightsAmp(wa+res/2), fWeightsTime(wt+res/2),
+        fPulseShape(ps), fAinv(ainv), fWeightsPerBin(res), fWindowSize(windowsize),
+        fTime(0), fTimeDev(-1), fSignal(0), fSignalDev(-1)
+    {
+    }
+
+    void SetData(Int_t n, Float_t const *val) { fNum=n; fVal=val; }
+
+    Float_t GetTime() const          { return fTime; }
+    Float_t GetSignal() const        { return fSignal; }
+
+    Float_t GetTimeDev() const       { return fTimeDev; }
+    Float_t GetSignalDev() const     { return fSignalDev; }
+
+    void GetSignal(Float_t &sig, Float_t &dsig) const { sig=fSignal; dsig=fSignalDev; }
+    void GetTime(Float_t &sig, Float_t &dsig) const   { sig=fTime; dsig=fTimeDev; }
+
+    Float_t ExtractNoise() const;
+    void Extract(Int_t maxpos=-1);
+
+    static Int_t CalculateWeights(TH1 &shape, const TH2 &autocorr, TArrayF &wa, TArrayF &wt, Int_t wpb=-1);
+    static Int_t CalculateWeights2(TH1 &shape, const TH2 &autocorr, TArrayF &wa, TArrayF &wt, Int_t wpb=-1);
+};
+
+
+#endif
Index: branches/Mars_McMismatchStudy/mextralgo/MExtralgoSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/mextralgo/MExtralgoSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mextralgo/MExtralgoSpline.cc	(revision 17960)
@@ -0,0 +1,383 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzbrug.de>
+!   Author(s): Markus Gaug 09/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2002-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtralgoSpline
+//
+//   Fast Spline extractor using a cubic spline algorithm, adapted from 
+//   Numerical Recipes in C++, 2nd edition, pp. 116-119.
+//   
+//   The coefficients "ya" are here denoted as "fVal" corresponding to
+//   the FADC value subtracted by the clock-noise corrected pedestal.
+//
+//   The coefficients "y2a" get immediately divided 6. and are called here 
+//   fDer2 although they are now not exactly the second derivative
+//   coefficients any more.
+// 
+//   The calculation of the cubic-spline interpolated value "y" on a point 
+//   "x" along the FADC-slices axis becomes: EvalAt(x)
+//
+//   The coefficients fDer2 are calculated with the simplified
+//   algorithm in InitDerivatives.
+//
+//   This algorithm takes advantage of the fact that the x-values are all
+//   separated by exactly 1 which simplifies the Numerical Recipes algorithm.
+//   (Note that the variables fDer are not real first derivative coefficients.)
+//
+//   Note, this spline is not optimized to be evaluated many many times, but
+//   it is optimized to be initialized very fast with new values again and
+//   again.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtralgoSpline.h"
+
+#include <iostream>
+#include <TRandom.h>
+
+#include "../mbase/MMath.h"
+#include "../mbase/MArrayF.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Calculate the first and second derivative for the splie.
+//
+// The coefficients are calculated such that
+//   1) fVal[i] = Eval(i, 0)
+//   2) Eval(i-1, 1)==Eval(i, 0)
+//
+// In other words: The values with the index i describe the spline
+// between fVal[i] and fVal[i+1]
+//
+void MExtralgoSpline::InitDerivatives() const
+{
+    if (fNum<2)
+        return;
+
+    // Look up table for coefficients
+    static MArrayF lut;
+
+    // If the lut is not yet large enough: resize and reclaculate
+    if (fNum>(Int_t)lut.GetSize())
+    {
+        lut.Set(fNum);
+
+        lut[0] = 0.;
+        for (Int_t i=1; i<fNum-1; i++)
+            lut[i] = -1.0/(lut[i-1] + 4);
+    }
+
+    // Calculate the coefficients used to get reproduce the first and
+    // second derivative.
+    fDer1[0] = 0.;
+    for (Int_t i=1; i<fNum-1; i++)
+    {
+        const Float_t d1 = fVal[i+1] - 2*fVal[i] + fVal[i-1];
+        fDer1[i] = (fDer1[i-1]-d1)*lut[i];
+    }
+
+    fDer2[fNum-1] = 0.;
+    for (Int_t k=fNum-2; k>=0; k--)
+        fDer2[k] = lut[k]*fDer2[k+1] + fDer1[k];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the two results x1 and x2 of f'(x)=0 for the third order
+// polynomial (spline) in the interval i. Return the number of results.
+// (0 if the fist derivative does not have a null-point)
+//
+Int_t MExtralgoSpline::EvalDerivEq0(const Int_t i, Double_t &x1, Double_t &x2) const
+{
+    const Double_t difder = fDer2[i+1]-fDer2[i];
+    const Double_t difval = fVal[i+1] -fVal[i];
+
+    return MMath::SolvePol2(3*difder, 6*fDer2[i], difval-2*fDer2[i]-fDer2[i+1], x1, x2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Solve the polynomial
+//
+//    y = a*x^3 + b*x^2 + c*x + d'
+//    0 = a*x^3 + b*x^2 + c*x + d' - y
+//
+// to find y in the i-th bin. Return the result as x1, x2, x3 and the return
+// code from MMath::SolvPol3.
+//
+Int_t MExtralgoSpline::SolvePol3(Int_t i, Double_t y, Double_t &x1, Double_t &x2, Double_t &x3) const
+{
+    // y = a*x^3 + b*x^2 + c*x + d'
+    // 0 = a*x^3 + b*x^2 + c*x + d' - y
+
+    // Calculate coefficients
+    const Double_t a = fDer2[i+1]-fDer2[i];
+    const Double_t b = 3*fDer2[i];
+    const Double_t c = fVal[i+1]-fVal[i] -2*fDer2[i]-fDer2[i+1];
+    const Double_t d = fVal[i] - y;
+
+    // If the first derivative is nowhere==0 and it is increasing
+    // in one point, and the value we search is outside of the
+    // y-interval... it cannot be there
+    // if (c>0 && (d>0 || fVal[i+1]<y) && b*b<3*c*a)
+    //     return -2;
+
+    return MMath::SolvePol3(a, b, c, d, x1, x2, x3);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the highest x value in [min;max[ at which the spline in
+// the bin i is equal to y
+//
+// min and max must be in the range [0;1]
+//
+// The default for min is 0, the default for max is 1
+// The default for y is 0
+//
+Double_t MExtralgoSpline::FindYdn(Int_t i, Double_t y, Double_t min, Double_t max) const
+{
+    Double_t x1, x2, x3;
+    const Int_t rc = SolvePol3(i, y, x1, x2, x3);
+
+    Double_t x = -1;
+
+    if (rc>0 && x1>=min && x1<max && x1>x)
+        x = x1;
+    if (rc>1 && x2>=min && x2<max && x2>x)
+        x = x2;
+    if (rc>2 && x3>=min && x3<max && x3>x)
+        x = x3;
+
+    return x<0 ? -2 : x+i;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the lowest x value in [min;max[ at which the spline in
+// the bin i is equal to y
+//
+// min and max must be in the range [0;1]
+//
+// The default for min is 0, the default for max is 1
+// The default for y is 0
+//
+Double_t MExtralgoSpline::FindYup(Int_t i, Double_t y, Double_t min, Double_t max) const
+{
+    Double_t x1, x2, x3;
+    const Int_t rc = SolvePol3(i, y, x1, x2, x3);
+
+    Double_t x = 2;
+
+    if (rc>0 && x1>min && x1<=max && x1<x)
+        x = x1;
+    if (rc>1 && x2>min && x2<=max && x2<x)
+        x = x2;
+    if (rc>2 && x3>min && x3<=max && x3<x)
+        x = x3;
+
+    return x>1 ? -2 : x+i;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search analytically downward for the value y of the spline, starting
+// at x, until x==0. If y is not found or out of range -2 is returned.
+//
+Double_t MExtralgoSpline::SearchYdn(Double_t x, Double_t y) const
+{
+    if (x>=fNum-1)
+        x = fNum-1.0001;
+
+    Int_t i = TMath::FloorNint(x);
+    if (i<0)
+        return -3;
+
+    Double_t rc = FindYdn(i, y, 0, x-i);
+    while (--i>=0 && rc<0)
+        rc = FindYdn(i, y);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search analytically upwards for the value y of the spline, starting
+// at x, until x==fNum-1. If y is not found or out of range -2 is returned.
+//
+Double_t MExtralgoSpline::SearchYup(Double_t x, Double_t y) const
+{
+    if (x<0)
+        x = 0.0001;
+
+    Int_t i = TMath::FloorNint(x);
+    if (i>fNum-2)
+        return -3;
+
+    Double_t rc = FindYup(i, y, x-i, 1.);
+    while (++i<fNum-1 && rc<0)
+        rc = FindYup(i, y);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do a range check an then calculate the integral from start-fRiseTime
+// to start+fFallTime. An extrapolation of 0.5 slices is allowed.
+//
+Float_t MExtralgoSpline::CalcIntegral(Float_t pos) const
+{
+    // We allow extrapolation of 1/2 slice.
+    const Float_t min = fRiseTime;        //-0.5+fRiseTime;
+    const Float_t max = fNum-1-fFallTime; //fNum-0.5+fFallTime;
+
+    if (pos<min)
+        pos = min;
+    if (pos>max)
+        pos = max;
+
+    return EvalInteg(pos-fRiseTime, pos+fFallTime);
+}
+
+Float_t MExtralgoSpline::CalcIntegral(Float_t beg, Float_t width) const
+{
+    Float_t end = beg + width;
+
+    if (beg<0)
+    {
+        end -= beg;
+        beg = 0;
+    }
+
+    if (end>fNum-1)
+    {
+        beg -= (end-fNum-1);
+        end  = fNum-1;
+    }
+
+    return EvalInteg(beg, end);
+}
+
+MArrayF MExtralgoSpline::GetIntegral(bool norm) const
+{
+    MArrayF val(fNum);
+
+    //val[0] = 0;
+
+    Double_t integ = 0;
+    for (int i=0; i<fNum-1; i++)
+    {
+        integ += EvalInteg(i);
+
+        val[i+1] = integ;
+    }
+
+    if (norm)
+        for (int i=0; i<fNum-1; i++)
+            val[i+1] /= val[fNum-1];
+
+    return val;
+}
+
+Float_t MExtralgoSpline::ExtractNoise()
+{
+    if (fNum<5)
+        return 0;
+
+    if (!(fExtractionType&kIntegral))
+    {
+        const Int_t   pos = gRandom->Integer(fNum-1);
+        const Float_t nsx = gRandom->Uniform();
+        return Eval(pos, nsx);
+    }
+    else
+    {
+        const Float_t pos = gRandom->Uniform(fNum-1-fRiseTime-fFallTime)+fRiseTime;
+        return CalcIntegral(pos);
+    }
+}
+
+void MExtralgoSpline::Extract(Int_t maxbin, Bool_t width)
+{
+    fSignal    =  0;
+    fTime      =  0;
+    fWidth     =  0;
+    fSignalDev = -1;
+    fTimeDev   = -1;
+    fWidthDev  = -1;
+
+    if (fNum<2)
+        return;
+
+    Float_t maxpos;
+    // FIXME: Check the default if no maximum found!!!
+    GetMaxAroundI(maxbin, maxpos, fHeight);
+
+    const Float_t h = (fExtractionType&kTimeRel) ? fHeight*fHeightTm : fHeightTm;
+
+    switch (fExtractionType)
+    {
+    case kAmplitude:
+        fSignal    = fHeight;
+        fTime      = maxpos;
+        fSignalDev = 0;  // means: is valid
+        fTimeDev   = 0;
+        break;
+
+    case kAmplitudeAbs:
+    case kAmplitudeRel:
+        fSignal    = fHeight;
+        fTime      = SearchYdn(maxpos, h);
+        fSignalDev = 0;  // means: is valid
+        fTimeDev   = 0;
+        break;
+
+    case kIntegralAbs:
+    case kIntegralRel:
+        fSignal    = CalcIntegral(maxpos);
+        fTime      = SearchYdn(maxpos, h);
+        fSignalDev = 0;  // means: is valid
+        fTimeDev   = 0;
+        break;
+
+    case kIntegralDyn:
+        fTime      = SearchYdn(maxpos, h);
+        fWidth     = SearchYup(maxpos, h)-fTime;
+        fSignal    = CalcIntegral(fTime, fWidth);
+        fTimeDev   = 0;
+        fWidthDev  = 0;
+        fSignalDev = 0;
+        break;
+
+    case kIntegralFixed:
+        fTime      = SearchYdn(maxpos, h);
+        fSignal    = CalcIntegral(fTime-fRiseTime, fRiseTime+fFallTime);
+        fTimeDev   = 0;
+        fSignalDev = 0;
+        break;
+    }
+}
Index: branches/Mars_McMismatchStudy/mextralgo/MExtralgoSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/mextralgo/MExtralgoSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mextralgo/MExtralgoSpline.h	(revision 17960)
@@ -0,0 +1,386 @@
+#ifndef MARS_MExtralgoSpline
+#define MARS_MExtralgoSpline
+
+#ifndef ROOT_TMath
+#include <TMath.h>
+#endif
+
+class MArrayF;
+class TComplex;
+
+class MExtralgoSpline
+{
+private:
+    enum
+    {
+        kIntegral   = BIT(0),
+        kTimeRel    = BIT(1),
+        kMaximum    = BIT(2),
+        kDynWidth   = BIT(3),
+        kFixedWidth = BIT(4),
+    };
+public:  
+    enum ExtractionType_t
+    {
+        // For backward compatibility
+        kAmplitudeAbs  = 0,                    // Height of maximum, absolute height leading edge
+        kAmplitudeRel  = kTimeRel,             // Height of maximum, relative height leading edge
+        kAmplitude     = kMaximum,             // Position and height of maximum
+        kIntegralAbs   = kIntegral,            // Integral, absolute height leading edge
+        kIntegralRel   = kIntegral|kTimeRel,   // Integral, relative height leading edge
+        kIntegralDyn   = kTimeRel|kDynWidth,   // Integrate between leading edge and falling edge
+        kIntegralFixed = kTimeRel|kFixedWidth, // Integrate between leading edge minus fRiseTime and plus fFallTime
+    };
+
+private:
+    ExtractionType_t fExtractionType;
+
+private:
+    //Bool_t fIsOwner; // Owner of derivatives....
+
+    // Input
+    Float_t const *fVal;
+    const Int_t    fNum;
+
+    Float_t *fDer1;
+    Float_t *fDer2;
+
+    Float_t fRiseTime;
+    Float_t fFallTime;
+
+    Float_t fHeightTm;
+
+    // Result
+    Float_t fTime;
+    Float_t fTimeDev;
+    Float_t fWidth;
+    Float_t fWidthDev;
+    Float_t fSignal;
+    Float_t fSignalDev;
+    Float_t fHeight;
+
+    Double_t ReMul(const TComplex &c1, const TComplex &th) const;
+
+    inline Float_t Eval(Float_t val, Float_t a, Float_t deriv) const
+    {
+        return a*val + (a*a*a-a)*deriv;
+    }
+
+    // Evaluate value of spline in the interval i with x=[0;1[
+    inline Float_t Eval(const Int_t i, const Float_t x) const
+    {
+        // Eval(i,x) =  (fDer2[i+1]-fDer2[i])*x*x*x + 3*fDer2[i]*x*x +
+        //              (fVal[i+1]-fVal[i] -2*fDer2[i]-fDer2[i+1])*x + fVal[i];
+
+        // x := [0; 1[
+        return Eval(fVal[i], 1-x, fDer2[i]) + Eval(fVal[i+1], x, fDer2[i+1]);
+    }
+
+    // Evaluate first derivative of spline in the interval i with x=[0;1[
+    inline Double_t EvalDeriv1(const Int_t i, const Float_t x) const
+    {
+        // x := [0; 1[
+        const Double_t difval = fVal[i+1]-fVal[i];
+        const Double_t difder = fDer2[i+1]-fDer2[i];
+
+        //return 3*difder*x*x + 6*fDer2[i]*x - 2*fDer2[i] - fDer2[i+1] + difval;
+        return 3*difder*x*x + (6*x - 2)*fDer2[i] - fDer2[i+1] + difval;
+    }
+
+    // Evaluate second derivative of spline in the interval i with x=[0;1[
+    inline Double_t EvalDeriv2(const Int_t i, const Float_t x) const
+    {
+        // x := [0; 1[
+        return 6*(fDer2[i+1]*x + fDer2[i]*(1-x));
+    }
+
+    Int_t SolvePol3(Int_t i, Double_t y, Double_t &x1, Double_t &x2, Double_t &x3) const;
+    Double_t FindYdn(Int_t i, Double_t y=0, Double_t min=0, Double_t max=1) const;
+    Double_t FindYup(Int_t i, Double_t y=0, Double_t min=0, Double_t max=1) const;
+    //Double_t FindY(Int_t i, Bool_t downwards, Double_t y=0, Double_t min=0, Double_t max=1) const;
+
+    Int_t EvalDerivEq0(const Int_t i, Double_t &x1, Double_t &x2) const;
+/*
+    inline void EvalDerivEq0(const Int_t i, Float_t &rc1, Float_t &rc2) const
+    {
+        // --- ORIGINAL CODE ---
+        Double_t sumder = fDer2[i]+fDer2[i+1];
+        Double_t difder = fDer2[i]-fDer2[i+1];
+
+        Double_t sqt1  = sumder*sumder - fDer2[i]*fDer2[i+1];
+        Double_t sqt2  = difder*(fVal[i+1]-fVal[i]);
+        Double_t sqt3  = sqrt(3*sqt1 + 3*sqt2);
+        Double_t denom = -3*(fDer2[i+1]-fDer2[i]);
+
+        rc1 = (3*fDer2[i] + sqt3)/denom;
+        rc2 = (3*fDer2[i] - sqt3)/denom;
+
+        // --- NEW CODE ---
+        Double_t sumder = fDer2[i]+fDer2[i+1];
+        Double_t difder = fDer2[i]-fDer2[i+1];
+
+        Double_t sqt1  = sumder*sumder - fDer2[i]*fDer2[i+1];
+        Double_t sqt2  = difder*(fVal[i+1]-fVal[i]);
+        Double_t sqt3  = sqt1+sqt2<0 ? 0 : sqrt((sqt1 + sqt2)/3);
+
+        rc1 = (fDer2[i] + sqt3)/difder;
+        rc2 = (fDer2[i] - sqt3)/difder;
+    }*/
+
+    // Calculate the "Stammfunktion" of the Eval-function
+    inline Double_t EvalPrimitive(Int_t i, Float_t x) const
+    {
+        Align(i, x);
+
+        if (x==0)
+            return -fDer2[i]/4;
+
+        if (x==1)
+            return (fVal[i+1] + fVal[i])/2 - fDer2[i+1]/4 - fDer2[i]/2;
+
+        const Double_t x2  = x*x;
+        const Double_t x4  = x2*x2;
+        const Double_t x1  = 1-x;
+        const Double_t x14 = x1*x1*x1*x1;
+
+        return x2*fVal[i+1]/2 + (x4/2-x2)*fDer2[i+1]/2 + (x-x2/2)*fVal[i] + (x2/2-x-x14/4)*fDer2[i];
+
+    }
+
+    inline void Align(Int_t &i, Float_t &x) const
+    {
+        if (i<0)
+        {
+            x += i;
+            i=0;
+        }
+        if (i>=fNum-1)
+        {
+            x += i-(fNum-2);
+            i=fNum-2;
+        }
+    }
+
+    // Calculate the intgeral of the Eval-function in
+    // bin i from 0 <= a < b < 1
+    inline Double_t EvalInteg(Int_t i, Float_t a, Float_t b) const
+    {
+        return EvalPrimitive(i, b)-EvalPrimitive(i, a);
+    }
+
+    // Identical to EvalInteg(i, 0, 1) but much faster
+    // Be carefull: NO RANGECHECK!
+    inline Double_t EvalInteg(Int_t i) const
+    {
+        return (fVal[i+1] + fVal[i])/2 - (fDer2[i+1] + fDer2[i])/4;
+    }
+
+    // Identical to sum of EvalInteg(i, 0, 1) for i=a to i=b-1,
+    // but much faster
+    // It is identical to EvalInteg(fVal[a], fVal[b])
+    // Be carefull: NO RANGECHECK!
+    inline Double_t EvalInteg(Int_t a, Int_t b) const
+    {
+       /*
+        Double_t sum = 0;
+        for (int i=a; i<b; i++)
+            sum += EvalInteg(i);
+
+        return sum;
+        */
+
+        if (a==b)
+            return 0;
+
+        Double_t sum=0;
+        for (const Float_t *ptr=fDer2+a+1; ptr<fDer2+b; ptr++)
+            sum -= *ptr;
+
+        sum -= (fDer2[a]+fDer2[b])/2;
+
+        sum /= 2;
+
+        for (const Float_t *ptr=fVal+a+1; ptr<fVal+b; ptr++)
+            sum += *ptr;
+
+        sum += (fVal[a]+fVal[b])/2;
+
+        return sum;
+    }
+
+    // Calculate the intgeral of the Eval-function betwen x0 and x1
+    inline Double_t EvalInteg(Float_t x0, Float_t x1) const
+    {
+        // RANGE CHECK MISSING!
+
+        const Int_t min = TMath::CeilNint(x0);
+        const Int_t max = TMath::FloorNint(x1);
+
+        // This happens if x0 and x1 are in the same interval
+        if (min>max)
+            return EvalInteg(max, x0-max, x1-max);
+
+        // Sum complete intervals
+        Double_t sum = EvalInteg(min, max);
+
+        // Sum the incomplete intervals at the beginning and end
+        sum += EvalInteg(min-1, 1-(min-x0), 1);
+        sum += EvalInteg(max,   0, x1-max);
+
+        // return result
+        return sum;
+    }
+
+    // We search for the maximum from x=i-1 to x=i+1
+    // (Remeber: i corresponds to the value in bin i, i+1 to the
+    //  next bin and i-1 to the last bin)
+    inline void GetMaxAroundI(Int_t i, Float_t &xmax, Float_t &ymax) const
+    {
+        Float_t xmax1=0, xmax2=0;
+        Float_t ymax1=0, ymax2=0;
+
+        Bool_t rc1 = i>0      && GetMax(i-1, xmax1, ymax1);
+        Bool_t rc2 = i<fNum-1 && GetMax(i,   xmax2, ymax2);
+
+        // In case the medium bin is the first or last bin
+        // take the lower or upper edge of the region into account.
+        if (i==0)
+        {
+            xmax1 = 0;
+            ymax1 = fVal[0];
+            rc1 = kTRUE;
+        }
+        if (i>=fNum-1)
+        {
+            xmax2 = fNum-1;
+            ymax2 = fVal[fNum-1];
+            rc2 = kTRUE;
+        }
+
+        // Take a default in case no maximum is found
+        // FIXME: Check THIS!!!
+        xmax=i;
+        ymax=fVal[i];
+
+        if (rc1)
+        {
+            ymax = ymax1;
+            xmax = xmax1;
+        }
+        else
+            if (rc2)
+            {
+                ymax = ymax2;
+                xmax = xmax2;
+            }
+
+        if (rc2 && ymax2>ymax)
+        {
+            ymax = ymax2;
+            xmax = xmax2;
+        }
+    }
+
+    inline Bool_t GetMax(Int_t i, Float_t &xmax, Float_t &ymax, Float_t min=0, Float_t max=1) const
+    {
+        // Find analytical maximum in the bin i in the interval [min,max[
+
+        Double_t x1=-1;  // This initialisation should not really be
+        Double_t x2=-1;  // necessary but makes valgriund happy.
+
+        if (!EvalDerivEq0(i, x1, x2))
+            return kFALSE;
+
+        const Bool_t ismax1 = x1>=min && x1<max && EvalDeriv2(i, x1)<0;
+        const Bool_t ismax2 = x2>=min && x2<max && EvalDeriv2(i, x2)<0;
+
+        if (!ismax1 && !ismax2)
+            return kFALSE;
+
+        if (ismax1 && !ismax2)
+        {
+            xmax = i+x1;
+            ymax = Eval(i, x1);
+            return kTRUE;
+        }
+
+        if (!ismax1 && ismax2)
+        {
+            xmax = i+x2;
+            ymax = Eval(i, x2);
+            return kTRUE;
+        }
+
+        // Somehting must be wrong...
+        return kFALSE;
+    }
+
+    void InitDerivatives() const;
+    Float_t CalcIntegral(Float_t start) const;
+    Float_t CalcIntegral(Float_t beg, Float_t width) const;
+
+public:
+    MExtralgoSpline(const Float_t *val, Int_t n, Float_t *der1, Float_t *der2)
+        : fExtractionType(kIntegralRel), fVal(val), fNum(n), fDer1(der1), fDer2(der2), fHeightTm(0.5), fTime(0), fTimeDev(-1), fSignal(0), fSignalDev(-1)
+    {
+        InitDerivatives();
+    }
+
+    void SetRiseFallTime(Float_t rise, Float_t fall) { fRiseTime=rise; fFallTime=fall; }
+    void SetExtractionType(ExtractionType_t typ)     { fExtractionType = typ; }
+    void SetHeightTm(Float_t h)                      { fHeightTm = h; }
+
+    Float_t GetTime() const      { return fTime; }
+    Float_t GetWidth() const     { return fWidth; }
+    Float_t GetSignal() const    { return fSignal; }
+    Float_t GetHeight() const    { return fHeight; }
+
+    Float_t GetTimeDev() const   { return fTimeDev; }
+    Float_t GetWidthDev() const  { return fWidthDev; }
+    Float_t GetSignalDev() const { return fSignalDev; }
+
+    void GetSignal(Float_t &sig, Float_t &dsig) const { sig=fSignal; dsig=fSignalDev; }
+    void GetWidth(Float_t &sig, Float_t &dsig) const  { sig=fWidth; dsig=fWidthDev; }
+    void GetTime(Float_t &sig, Float_t &dsig) const   { sig=fTime; dsig=fTimeDev; }
+
+    Float_t ExtractNoise(/*Int_t iter*/);
+    void Extract(Int_t maxpos, Bool_t width=kFALSE);
+
+    Float_t EvalAt(const Float_t x) const;
+    Float_t Deriv1(const Float_t x) const;
+
+    Double_t SearchYdn(Double_t maxpos, Double_t y) const;
+    Double_t SearchYup(Double_t maxpos, Double_t y) const;
+
+    Double_t SearchYdn(Float_t y) const { return SearchYdn(fNum, y); }
+    Double_t SearchYup(Float_t y) const { return SearchYup(0,    y); }
+
+    MArrayF GetIntegral(bool norm=false) const;
+
+    Float_t GetIntegral(Float_t beg, Float_t end) const
+    {
+        return CalcIntegral(beg, end-beg);
+    }
+};
+
+inline Float_t MExtralgoSpline::EvalAt(const Float_t x) const
+{
+    Int_t   i = TMath::FloorNint(x);
+    Float_t f = x-i;
+
+    Align(i, f);
+
+    return Eval(i, f);
+}
+
+inline Float_t MExtralgoSpline::Deriv1(const Float_t x) const
+{
+    Int_t   i = TMath::FloorNint(x);
+    Float_t f = x-i;
+
+    Align(i, f);
+
+    return EvalDeriv1(i, f);
+}
+
+#endif
Index: branches/Mars_McMismatchStudy/mextralgo/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mextralgo/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mextralgo/Makefile	(revision 17960)
@@ -0,0 +1,32 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Extralgo
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES =  -I.
+
+SRCFILES = MExtralgoSpline.cc \
+	   MExtralgoDigitalFilter.cc 
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mfbase/FBaseIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/FBaseIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/FBaseIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mfbase/FBaseLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/FBaseLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/FBaseLinkDef.h	(revision 17960)
@@ -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 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 MFDataPhrase+;
+#pragma link C++ class MFRealTimePeriod+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mfbase/MF.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MF.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MF.cc	(revision 17960)
@@ -0,0 +1,579 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MF                                                              
+//
+// With this filter you can filter in all variables from Mars parameter
+// containers.
+//
+// In the constructor you can give the filter rule, like
+//   "MHillas.fLength < 15"
+// Where MHillas is the name of the parameter container in the parameter
+// list and fLength is the name of the data member which should be used
+// for the filter rule. If the name of the container is use specified
+// (MyHillas) the name to give would be:
+//   "MyHillas.fLength < 15"
+//
+// Also more difficult rules are allowed, like:
+//   "MHillas.fWidth<0.5 && MHillas.fLength<0.6"
+//
+// You can also use parantheses:
+//   "MHillas.fSize>200 || (MHillas.fWidth<0.5 && MHillas.fLength<0.6)"
+//
+// If you want to use mathematic expressions (as defined in MDataChain)
+// you must encapsulate it in {}-parantheses, eg:
+//   "{log10(MHillas.fSize)}>3"
+//
+// For more details on available functions and expressions see MDataChain!
+//
+// The allowed logigal conditionals are:
+//   &&: logical and
+//   ||: logical or
+//   ^:  exclusive or
+//
+// As conditional signs, for now, only:
+//   <, >
+// are allowed.
+//
+//   -------->  '==' is NOT supported!
+//
+//
+// Warning: There is no priority rule build in. So better use parantheses
+//   to get correct results. The rule is parsed/evaluated from the left
+//   to the right, which means:
+//
+//   "MHillas.fSize>200 || MHillas.fWidth<0.5 && MHillas.fLength<0.6"
+//
+//    is parses as
+//
+//   "(MHillas.fSize>200 || MHillas.fWidth<0.5) && MHillas.fLength<0.6"
+//
+//
+// FIXME: The possibility to use also complete filters is missing.
+//        Maybe we can use gInterpreter->Calc("") for this.
+//        gROOT->ProcessLineFast("line");
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MF.h"
+
+#include <ctype.h>        // isalnum, ...
+#include <stdlib.h>       // strtod, ...
+#include <fstream>        // ofstream, ...
+
+#include <TMethodCall.h>
+
+#include "MParList.h"
+
+//#include "MFilterList.h"
+#include "MFDataPhrase.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), fAllowEmpty(kFALSE)
+{
+    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) : fAllowEmpty(kFALSE)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    *fLog << inf << "Parsing filter rule... " << flush;
+    fF = new MFDataPhrase(text);
+    /*
+    if (!(fF=ParseString(text, 1)))
+    {
+        *fLog << err << dbginf << "Parsing '" << text << "' failed." << endl;
+        return;
+    }
+    */
+    *fLog << inf << "found: ";
+    fF->Print();
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete filters.
+//
+MF::~MF()
+{
+    if (fF)
+        delete fF;
+}
+/*
+// --------------------------------------------------------------------------
+//
+// Returns the number of alphanumeric characters (including '.')
+// in the given string
+//
+Int_t MF::IsAlNum(TString txt) const
+{
+    int l = txt.Length();
+    for (int i = 0; i<l; i++)
+        if (!isalnum(txt[i]) && txt[i]!='.' && txt[i]!=';')
+            return i;
+
+    return l;
+}
+
+MFilter *MF::ParseRule(TString &txt, MFilter *filter0, Int_t level) const
+{
+    // For backward compatibility
+    txt.ReplaceAll("{", "(");
+    txt.ReplaceAll("}", ")");
+
+    const Int_t fg = txt.First('>');
+    const Int_t lg = txt.First('>');
+    const Int_t fl = txt.First('<');
+    const Int_t ll = txt.First('<');
+
+    if (fg<0 && fl<0)
+    {
+        MFilter *f = (MFilter*)GetNewObject(txt, MFilter::Class());
+        if (!f)
+        {
+            *fLog << err << dbginf << "Syntax Error: '" << txt << "' is neither a MFilter nor conditional sign found." << endl;
+            return NULL;
+        }
+        // FIXME: Search object through list...?
+        txt = "";
+        return f;
+    }
+
+    if (fg>=0 && fl>=0)
+    {
+        *fLog << err << dbginf << "Syntax Error: Two coditional signs found in " << txt << endl;
+        *fLog << "Currently you have to enclose all conditions in parantheses, like: \"(x<y) && (z<5)\"" << endl;
+        return NULL;
+    }
+    if (fg!=lg || fl!=ll)
+    {
+        *fLog << err << dbginf << "Syntax Error: Coditional sign found twice " << txt << endl;
+        return NULL;
+    }
+
+    const Int_t cond = fg<0 ? fl : fg;
+
+    const TString rule1 = txt(0, cond);
+    const TString rule2 = txt(cond+1, txt.Length());
+
+    Int_t lvl = gLog.GetDebugLevel();
+    gLog.SetDebugLevel(1);
+    MFilter *f = new MFDataChain(rule1.Data(), txt[cond], rule2.Data());
+    f->SetName(Form("Chain%02d%c", level, txt[cond]));
+    gLog.SetDebugLevel(lvl);
+
+    txt = "";
+    return f;
+}
+// --------------------------------------------------------------------------
+//
+// Parse a text string. Returns a corresponding filter of filter list.
+//
+MFilter *MF::ParseString(TString txt, Int_t level)
+{
+    MFilter *filter0=NULL;
+
+    TString type;
+    int nlist = 0;
+
+    while (!txt.IsNull())
+    {
+        MFilter *newfilter = NULL;
+
+        txt = txt.Strip(TString::kBoth);
+
+        //fLog << all << setw(level) << " " << "Text: " << level << " '" << txt << "'" << endl;
+
+        switch (txt[0])
+        {
+        case '(':
+            {
+                //
+                // Search for the corresponding parantheses
+                //
+                Int_t first=1;
+                for (int cnt=0; first<txt.Length(); first++)
+                {
+                    if (txt[first]=='(')
+                        cnt++;
+                    if (txt[first]==')')
+                        cnt--;
+
+                    if (cnt==-1)
+                        break;
+                }
+
+                if (first==txt.Length())
+                {
+                    *fLog << err << dbginf << "Syntax Error: ')' missing." << endl;
+                    if (filter0)
+                        delete filter0;
+                    return NULL;
+                }
+
+                //
+                // Make a copy of the 'interieur' and delete the substringä
+                // including the parantheses
+                //
+                TString sub = txt(1, first-1);
+                txt.Remove(0, first+1);
+
+                //
+                // Parse the substring
+                //
+                newfilter = ParseString(sub, level+1);
+                if (!newfilter)
+                {
+                    *fLog << err << dbginf << "Parsing '" << sub << "' failed." << endl;
+                    if (filter0)
+                        delete filter0;
+                    return NULL;
+                }
+            }
+            break;
+
+        case ')':
+            *fLog << err << dbginf << "Syntax Error: Too many ')'" << endl;
+            if (filter0)
+                delete filter0;
+            return NULL;
+
+
+        case '&':
+        case '|':
+        case '^':
+            if (filter0)
+            {
+                //
+                // Check for the type of the conditional
+                //
+                TString is = txt[0];
+                txt.Remove(0, 1);
+
+                if (is==txt[0] && is!='^')
+                {
+                    is += txt[0];
+                    txt.Remove(0, 1);
+                }
+
+                //
+                // If no filter is available or the available filter
+                // is of a different conditional we have to create a new
+                // filter list with the new conditional
+                //
+                if (!filter0->InheritsFrom(MFilterList::Class()) || type!=is)
+                {
+                    MFilterList *list = new MFilterList(is);
+                    list->SetName(Form("List_%s_%d", (const char*)is, 10*level+nlist++));
+
+                    list->SetOwner();
+                    list->AddToList(filter0);
+                    filter0 = list;
+
+                    type = is;
+                }
+                continue;
+            }
+
+            *fLog << err << dbginf << "Syntax Error: First argument of condition missing." << endl;
+            if (filter0)
+                delete filter0;
+            return NULL;
+
+        default:
+            newfilter = ParseRule(txt, filter0, level++);
+            if (!newfilter)
+            {
+                if (filter0)
+                    delete filter0;
+                return NULL;
+            }
+        }
+
+        if (!filter0)
+        {
+            filter0 = newfilter;
+            continue;
+        }
+
+        if (!filter0->InheritsFrom(MFilterList::Class()))
+            continue;
+
+        ((MFilterList*)filter0)->AddToList(newfilter);
+    }
+
+    return filter0;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// PreProcess all filters.
+//
+Int_t MF::PreProcess(MParList *plist)
+{
+    if (!fF)
+    {
+        if (IsAllowEmpty())
+            return kTRUE;
+
+        *fLog << err << dbginf << "No filter rule available." << endl;
+        return kFALSE;
+    }
+
+    fF->SetAccelerator(GetAccelerator());
+
+    if (!fF->CallPreProcess(plist))
+    {
+        *fLog << err << dbginf << "PreProcessing filters in ";
+        *fLog << fName << " failed." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process all filters.
+//
+Int_t MF::Process()
+{
+    return fF ? fF->CallProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Postprocess all filters.
+//
+Int_t MF::PostProcess()
+{
+    return fF ? fF->CallPostProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the result of the filter rule. If no filter available the
+// condition is always true
+//
+Bool_t MF::IsExpressionTrue() const
+{
+    return fF ? fF->IsConditionTrue() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MF::GetDataMember() const
+{
+  return fF ? fF->GetDataMember() : (TString)"";
+}
+
+void MF::StreamPrimitive(ostream &out) const
+{
+    out << "   MF " << GetUniqueName();
+
+    if (!fF)
+    {
+        out << ";" << endl;
+        return;
+    }
+
+    out << "(\"" << fF->GetRule() << "\"";
+        if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the rule.
+// if now filter is set up '<n/a>' is printed.
+//
+void MF::Print(Option_t *opt) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    if (fF)
+        fF->Print();
+    else
+        *fLog << "<n/a>";
+    *fLog << endl << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+//
+// Assuming your MF-filter is called (Set/GetName): MyFilter
+//
+// First you can setup whether the filter is inverted or not:
+//     MyFilter.Inverted: yes, no  <default=no>
+//
+// Now setup the condition, eg:
+//     MyFilter.Condition: MHillas.fSize<1000
+// or
+//     MyFilter.Condition: MHillas.fSize>500 && MHillas.fSize<10000
+//
+// If you want to use more difficult filters you can split the
+// condition into subcondistions. Subcondistions are identified
+// by {}-brackets. Avoid trailing 0's! For example:
+//
+//     MyFilter.Condition: MHillas.fSize>500 && {0} && {1}
+//     MyFilter.0: MHillas.fSize>1000
+//     MyFilter.1: MHillas.fSize<10000
+//
+// The numbering must be continous and start with 0. You can use
+// a subcondition more than once. All {}-brackets are simply replaced
+// by the correspodning conditions. The rules how conditions can
+// be written can be found in the class description of MF and MDataChain.
+//
+Int_t MF::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+    /*
+     // It is assumed that each filter itself calls MFilter::ReadEnv
+     // to process the Inverted directive
+     Bool_t rc = MFilter::ReadEnv(env, prefix, print);
+     if (rc==kERROR)
+        return kERROR;
+        */
+    if (IsEnvDefined(env, prefix, "Condition", print))
+    {
+        TString rule = GetEnvValue(env, prefix, "Condition", "");
+        rule.ReplaceAll(" ", "");
+
+        Int_t idx=0;
+        while (1)
+        {
+            TString cond;
+            if (IsEnvDefined(env, prefix, Form("%d", idx), print))
+            {
+                cond += "(";
+                cond += GetEnvValue(env, prefix, Form("%d", idx), "");
+                cond += ")";
+            }
+
+            if (cond.IsNull())
+                break;
+
+            rule.ReplaceAll(Form("{%d}", idx), cond);
+            idx++;
+        }
+
+        if (fF)
+        {
+            delete fF;
+            fF = 0;
+        }
+
+        if (rule.IsNull())
+        {
+            *fLog << warn << GetDescriptor() << " ::ReadEnv - WARNING: Empty condition found." << endl;
+            SetAllowEmpty();
+            return kTRUE;
+        }
+
+        SetAllowEmpty(kFALSE);
+
+        const Int_t fg = rule.First('>');
+        const Int_t fl = rule.First('<');
+        const Int_t fe = rule.First('=');
+
+        if (fg<0 && fl<0 && fe<0)
+        {
+            MFilter *f = (MFilter*)GetNewObject(rule, MFilter::Class());
+            if (!f)
+            {
+                *fLog << err << dbginf << "Syntax Error: '" << rule << "' is neither a MFilter nor conditional sign found." << endl;
+                return kERROR;
+            }
+            fF = f;
+        }
+        else
+            fF = new MFDataPhrase(rule);
+        /*
+        if (!(fF=ParseString(rule, 1)))
+        {
+            *fLog << err << "MF::ReadEnv - ERROR: Parsing '" << rule << "' failed." << endl;
+            return kERROR;
+        }
+        */
+        if (print)
+        {
+            *fLog << inf << "found: ";
+            fF->Print();
+            *fLog << endl;
+        }
+    }
+    else
+    {
+        if (!fF)
+        {
+            *fLog << warn << GetDescriptor() << " ::ReadEnv - WARNING: No condition found." << endl;
+            SetAllowEmpty();
+            return kFALSE;
+        }
+    }
+
+    // This is a workaround, because MFilter::ReadEnv and fF->ReadEnv
+    // might check for "Inverted" in this case both gets inverted
+    // and double-inversion is no inversion
+    /*
+    if (IsEnvDefined(env, prefix, "Inverted", print))
+        if (GetEnvValue(env, prefix, "Inverted", kFALSE)==kTRUE)
+            SetInverted(kFALSE);*/
+
+    return fF->ReadEnv(env, prefix, print);
+}
Index: branches/Mars_McMismatchStudy/mfbase/MF.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MF.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MF.h	(revision 17960)
@@ -0,0 +1,65 @@
+#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
+    Bool_t fAllowEmpty;              // Not a Bit to be stored
+/*
+    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(std::ostream &out) const;
+
+public:
+    MF();
+    MF(const char *text, const char *name=NULL, const char *title=NULL);
+    ~MF();
+
+    // MF
+    void SetAllowEmpty(Bool_t b=kTRUE) { fAllowEmpty = b; }
+    Bool_t IsAllowEmpty() const { return fAllowEmpty; }
+
+    // MFilter
+    TString GetRule() const { return fF ? fF->GetRule() : MFilter::GetRule(); }
+    TString GetDataMember() const;
+
+    Bool_t IsExpressionTrue() const;
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // TObject
+    void Print(Option_t *opt="") const;
+
+    // MParContainer
+    void SetVariables(const TArrayD &arr) { if (fF) fF->SetVariables(arr); }
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MF, 1) // A Filter for cuts in any data member
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfbase/MFDataChain.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFDataChain.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFDataChain.cc	(revision 17960)
@@ -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  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 MDataPhrase).
+//
+// 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 "MDataPhrase.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 MDataPhrase(cond))
+{
+    fName  = name  ? name  : "MFDataChain";
+    fTitle = title ? title : "Filter using any data member of a class";
+
+    //AddToBranchList(member);
+
+    fFilterType = (type=='<' ? kELowerThan : kEGreaterThan);
+
+    if (type!='<' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '>' specified... using '>'." << endl;
+}
+
+MFDataChain::~MFDataChain()
+{
+    if (fCond)
+        delete fCond;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataChain::PreProcess(MParList *plist)
+{
+    if (!fCond)
+    {
+        *fLog << "No condition available - don't call default constructor!" << endl;
+        return kFALSE;
+    }
+    return fData.PreProcess(plist) && fCond->PreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataChain::Process()
+{
+    const Double_t data = fData.GetValue();
+    const Double_t cond = fCond->GetValue();
+
+    switch (fFilterType)
+    {
+    case kELowerThan:
+        fResult = (data < cond);
+        return kTRUE;
+    case kEGreaterThan:
+        fResult = (data > cond);
+        return kTRUE;
+    }
+
+    return kFALSE;
+}
+
+void MFDataChain::Print(Option_t *) const
+{
+    *fLog << GetRule() << flush;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Crahses if default constructor called.
+//
+void MFDataChain::StreamPrimitive(ostream &out) const
+{
+    out << "   MFDataChain " << GetUniqueName() << "(\"";
+    out << fData.GetRule() << "\", '";
+    out << (fFilterType==kELowerThan?"<":">");
+    out << "', ";
+
+    if (fCond->InheritsFrom(MDataValue::Class()))
+        out << ((MDataValue*)fCond)->GetValue();
+    else
+        out << "\"" << fCond->GetRule() << "\"";
+
+    out << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Crahses if default constructor called.
+//
+TString MFDataChain::GetRule() const
+{
+    TString ret(fData.GetRule());
+    ret += fFilterType==kELowerThan?"<":">";
+
+    TString str;
+    str += fCond->GetRule();
+    ret += str.Strip(TString::kBoth);
+    return ret;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Crahses if default constructor called.
+//
+TString MFDataChain::GetDataMember() const
+{
+    if (!fData.IsValid())
+        return "";
+
+    TString ret(fData.GetDataMember());
+    ret += ",";
+    ret += fCond->GetDataMember();
+    return ret;
+}
Index: branches/Mars_McMismatchStudy/mfbase/MFDataChain.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFDataChain.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFDataChain.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MFDataChain
+#define MARS_MFDataChain
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFDataChain                                                                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+#ifndef MARS_MDataChain
+#include "MDataChain.h"
+#endif
+
+class MParList;
+
+class MFDataChain : public MFilter
+{
+private:
+    MDataChain fData;
+    MData     *fCond;
+
+    typedef enum { kELowerThan, kEGreaterThan } FilterType_t;
+    FilterType_t fFilterType;
+
+    Bool_t  fResult;           //!
+
+    void StreamPrimitive(std::ostream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MFDataChain(const char *name=NULL, const char *title=NULL);
+    MFDataChain(const char *rule, const char type, const Double_t val,
+                const char *name=NULL, const char *title=NULL);
+    MFDataChain(const char *rule, const char type, const char *cond,
+                const char *name=NULL, const char *title=NULL);
+    ~MFDataChain();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    void Print(Option_t *opt = "") const;
+
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    void SetVariables(const TArrayD &arr)
+    {
+        fData.SetVariables(arr);
+        if (fCond)
+            fCond->SetVariables(arr);
+    }
+
+    ClassDef(MFDataChain, 1) // A Filter for cuts in any data member
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfbase/MFDataMember.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFDataMember.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFDataMember.cc	(revision 17960)
@@ -0,0 +1,173 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  01/2002 <mailto:tbretz@astro.uni-wueruburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MFDataMember                                                              
+//
+// With this filter you can filter in all variables from Mars parameter
+// containers.
+//
+// In the constructor you can give the filter variable, like
+//   "MHillas.fLength"
+// Where MHillas is the name of the parameter container in the parameter
+// list and fLength is the name of the data member which should be used
+// for the filter rule. If the name of the container is use specified
+// (MyHillas) the name to give would be:
+//   "MyHillas.fLength"
+//
+// For example:
+//   MFDataMember filter("MHillas.fLength", '<', 150);
+//
+// You can test '<', '>' and '='. Warning: Using '=' may give strange results
+// in case you are comparing floating point values.
+//
+// In case the data member is detected to be an integer value, both
+// the data member and the val given as argument in the constructor
+// are castet to Long_t.
+//
+// To test != use the SetInverted() member function.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFDataMember.h"
+
+#include <fstream>
+
+#include <TMethodCall.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFDataMember);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MFDataMember::MFDataMember(const char *member, const char type, const Double_t val,
+                           const char *name, const char *title)
+    : fData(member), fValue(val)
+{
+    fName  = name  ? name  : "MFDataMember";
+    fTitle = title ? title : "Filter using any data member of a class";
+
+    AddToBranchList(member);
+
+    switch (type)
+    {
+    case '>': fFilterType = kEGreaterThan; break;
+    case '<': fFilterType = kELowerThan;   break;
+    case '=': fFilterType = kEEqual;       break;
+    default:  fFilterType = kEGreaterThan; break;
+    }
+
+    if (type!='<' && type!='=' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '=' nor '>' specified... using '>'." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataMember::PreProcess(MParList *plist)
+{
+    return fData.PreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataMember::Process()
+{
+    if (fData.IsInt())
+    {
+        switch (fFilterType)
+        {
+        case kELowerThan:
+            fResult = ((Long_t)fData.GetValue() < (Long_t)fValue);
+            return kTRUE;
+        case kEGreaterThan:
+            fResult = ((Long_t)fData.GetValue() > (Long_t)fValue);
+            return kTRUE;
+        case kEEqual:
+            fResult = ((Long_t)fData.GetValue() == (Long_t)fValue);
+            return kTRUE;
+        }
+    }
+    else
+    {
+        switch (fFilterType)
+        {
+        case kELowerThan:
+            fResult = (fData.GetValue() < fValue);
+            return kTRUE;
+        case kEGreaterThan:
+            fResult = (fData.GetValue() > fValue);
+            return kTRUE;
+        case kEEqual:
+            fResult = (fData.GetValue() == fValue);
+            return kTRUE;
+        }
+    }
+
+    return kFALSE;
+}
+
+void MFDataMember::Print(Option_t *) const
+{
+    *fLog << GetRule() << flush;
+}
+
+void MFDataMember::StreamPrimitive(ostream &out) const
+{
+    out << "   MFDataMember " << GetUniqueName() << "(\"";
+    out << fData.GetRule() << "\", '";
+    switch (fFilterType)
+    {
+    case kEGreaterThan: out << '>'; break;
+    case kELowerThan:   out << '<'; break;
+    case kEEqual:       out << '='; break;
+    }
+    out << "', " << fValue << ");" << endl;
+}
+
+TString MFDataMember::GetRule() const
+{
+    TString ret = fData.GetRule();
+    switch (fFilterType)
+    {
+    case kEGreaterThan: ret +='>'; break;
+    case kELowerThan:   ret +='<'; break;
+    case kEEqual:       ret +='='; break;
+    }
+
+    TString str;
+    str += fValue;
+
+    return ret+str.Strip(TString::kBoth);
+}
+
+TString MFDataMember::GetDataMember() const
+{
+    return fData.GetDataMember();
+}
Index: branches/Mars_McMismatchStudy/mfbase/MFDataMember.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFDataMember.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFDataMember.h	(revision 17960)
@@ -0,0 +1,48 @@
+#ifndef MARS_MFDataMember
+#define MARS_MFDataMember
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+#ifndef MARS_MDataMember
+#include "MDataMember.h"
+#endif
+
+class MParList;
+
+class MFDataMember : public MFilter
+{
+private:
+    MDataMember fData;
+
+    typedef enum { kELowerThan, kEGreaterThan, kEEqual } FilterType_t;
+    FilterType_t fFilterType;
+
+    Bool_t  fResult;           //!
+    Double_t fValue;
+
+    void StreamPrimitive(std::ostream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    enum {
+        kIsInt = BIT(14)
+    };
+    MFDataMember(const char *member, const char type, const Double_t val,
+                 const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    void Print(Option_t *opt = "") const;
+
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    void SetVariables(const TArrayD &arr) { fData.SetVariables(arr); }
+
+    ClassDef(MFDataMember, 1) // A Filter for cuts in any data member
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfbase/MFDataPhrase.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFDataPhrase.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFDataPhrase.cc	(revision 17960)
@@ -0,0 +1,366 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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)"
+//
+// For more details on available functions and expressions see MDataChain!
+//
+// The allowed logigal conditionals are:
+//   &&: logical and
+//   ||: logical or
+//   ^:  exclusive or
+//
+// As conditional signs, for now, only:
+//   <, >
+// are allowed.
+//
+//
+// 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");
+//
+//
+// Class Version 2:
+// ----------------
+//  + Bool_t fDefault
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFDataPhrase.h"
+
+#include <fstream>        // ofstream, ...
+
+#include <TMethodCall.h>
+
+#include "MParList.h"
+
+#include "MDataPhrase.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFDataPhrase);
+
+using namespace std;
+
+const TString MFDataPhrase::gsDefName  = "MFDataPhrase";
+const TString MFDataPhrase::gsDefTitle = "Filter setup by a text-rule";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Don't use.
+//
+MFDataPhrase::MFDataPhrase()
+    : fData(NULL), fAllowEmpty(kFALSE), fDefault(kTRUE)
+{
+    fName  = gsDefName.Data();
+    fTitle = gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. For the text describing the filter rule please see
+// the class description above.
+//
+MFDataPhrase::MFDataPhrase(const char *text, const char *name, const char *title)
+    : fData(NULL), fAllowEmpty(kFALSE), fDefault(kTRUE)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    if (!text)
+        return;
+
+    *fLog << inf << "Parsing filter rule... " << flush;
+    fData=new MDataPhrase(text);
+    *fLog << inf << "found: ";
+    fData->Print();
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete filters.
+//
+MFDataPhrase::~MFDataPhrase()
+{
+    if (fData)
+        delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcess all filters.
+//
+Int_t MFDataPhrase::PreProcess(MParList *plist)
+{
+    if (!fData)
+    {
+        if (IsAllowEmpty())
+            return kTRUE;
+
+        *fLog << err << dbginf << "No filter rule available." << endl;
+        return kFALSE;
+    }
+
+//    fData->SetAccelerator(GetAccelerator());
+
+    if (!fData->PreProcess(plist))
+    {
+        *fLog << err << dbginf << "PreProcessing filters in ";
+        *fLog << fName << " failed." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process all filters.
+//
+Int_t MFDataPhrase::Process()
+{
+    fResult = fData ? fData->GetValue()>0.5 : fDefault;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Postprocess all filters.
+//
+Int_t MFDataPhrase::PostProcess()
+{
+    return kTRUE;
+}
+
+TString MFDataPhrase::GetRule() const
+{
+    return fData ? fData->GetRule() : MFilter::GetRule();
+}
+
+void MFDataPhrase::SetVariables(const TArrayD &arr)
+{
+    if (fData)
+        fData->SetVariables(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the result of the filter rule. If no filter available the
+// condition is always true
+//
+Bool_t MFDataPhrase::IsExpressionTrue() const
+{
+    return fResult;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MFDataPhrase::GetDataMember() const
+{
+  return fData ? fData->GetDataMember() : (TString)"";
+}
+
+void MFDataPhrase::StreamPrimitive(ostream &out) const
+{
+    out << "   MF " << GetUniqueName();
+
+    if (!fData)
+    {
+        out << ";" << endl;
+        return;
+    }
+
+    out << "(\"" << fData->GetRule() << "\"";
+        if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the rule.
+// if now filter is set up '<n/a>' is printed.
+//
+void MFDataPhrase::Print(Option_t *opt) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    if (fData)
+        fData->Print();
+    else
+        *fLog << "<n/a>" << endl;
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+//
+// Assuming your MF-filter is called (Set/GetName): MyFilter
+//
+// First you can setup whether the filter is inverted or not:
+//     MyFilter.Inverted: yes, no  <default=no>
+//
+// Now setup the condition, eg:
+//     MyFilter.Condition: MHillas.fSize<1000
+// or
+//     MyFilter.Condition: MHillas.fSize>500 && MHillas.fSize<10000
+//
+// If you want to use more difficult filters you can split the
+// condition into subcondistions. Subcondistions are identified
+// by {}-brackets. Avoid trailing 0's! For example:
+//
+//     MyFilter.Condition: MHillas.fSize>500 && {0} && {1}
+//     MyFilter.0: MHillas.fSize>1000
+//     MyFilter.1: MHillas.fSize<10000
+//
+// The numbering must be continous and start with 0. You can use
+// a subcondition more than once. All {}-brackets are simply replaced
+// by the correspodning conditions. The rules how conditions can
+// be written can be found in the class description MDataPhrase.
+//
+Int_t MFDataPhrase::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Int_t rc1 = MFilter::ReadEnv(env, prefix, print);
+    if (rc1==kERROR)
+        return kERROR;
+
+    if (IsEnvDefined(env, prefix, "Condition", print))
+    {
+        TString rule = GetEnvValue(env, prefix, "Condition", "");
+        rule.ReplaceAll(" ", "");
+
+        Int_t idx=0;
+        while (1)
+        {
+            TString cond;
+            if (IsEnvDefined(env, prefix, Form("%d", idx), print))
+            {
+                cond += "(";
+                cond += GetEnvValue(env, prefix, Form("%d", idx), "");
+                cond += ")";
+            }
+
+            if (cond.IsNull())
+                break;
+
+            rule.ReplaceAll(Form("{%d}", idx), cond);
+            idx++;
+        }
+
+        if (fData)
+        {
+            delete fData;
+            fData = 0;
+        }
+
+        if (rule.IsNull())
+        {
+            *fLog << warn << GetDescriptor() << " ::ReadEnv - WARNING: Empty condition found." << endl;
+            SetAllowEmpty();
+            return kTRUE;
+        }
+
+        SetAllowEmpty(kFALSE);
+
+        fData = new MDataPhrase(rule);
+        /*
+        if (!(fF=ParseString(rule, 1)))
+        {
+            *fLog << err << "MFDataPhrase::ReadEnv - ERROR: Parsing '" << rule << "' failed." << endl;
+            return kERROR;
+        }
+        */
+        if (print)
+        {
+            *fLog << inf << "found: ";
+            fData->Print();
+            *fLog << endl;
+        }
+
+        rc1 = kTRUE;
+    }
+    else
+    {
+        if (!fData)
+        {
+            *fLog << warn << GetDescriptor() << " ::ReadEnv - WARNING: No condition found." << endl;
+            SetAllowEmpty();
+            return kFALSE;
+        }
+    }
+
+    const Int_t rc2 = fData->ReadEnv(env, prefix, print);
+    if (rc2==kERROR)
+        return kERROR;
+
+    // This is a workaround, because MFilter::ReadEnv and fF->ReadEnv
+    // might check for "Inverted" in this case both gets inverted
+    // and double-inversion is no inversion
+    /*
+    if (IsEnvDefined(env, prefix, "Inverted", print))
+        if (GetEnvValue(env, prefix, "Inverted", kFALSE)==kTRUE)
+            SetInverted(kFALSE);*/
+
+    return rc1 || rc2;
+}
Index: branches/Mars_McMismatchStudy/mfbase/MFDataPhrase.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFDataPhrase.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFDataPhrase.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MFDataPhrase
+#define MARS_MFDataPhrase
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MData;
+class MParList;
+class TMethodCall;
+
+class MFDataPhrase : public MFilter
+{
+private:
+    static const TString gsDefName;  //!
+    static const TString gsDefTitle; //!
+
+    MData *fData;
+    Bool_t fAllowEmpty;              // Not a Bit to be stored
+    Bool_t fDefault;                 // Default for empty case
+
+    Bool_t fResult; //!
+
+    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(std::ostream &out) const;
+
+public:
+    MFDataPhrase();
+    MFDataPhrase(const char *text, const char *name=NULL, const char *title=NULL);
+    ~MFDataPhrase();
+
+    // MF
+    void SetAllowEmpty(Bool_t b=kTRUE) { fAllowEmpty = b; }
+    Bool_t IsAllowEmpty() const { return fAllowEmpty; }
+
+    void SetDefault(Bool_t b) { fDefault = b;    }
+    Bool_t GetDefault() const { return fDefault; }
+
+    // MFilter
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    Bool_t IsExpressionTrue() const;
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // TObject
+    void Print(Option_t *opt="") const;
+
+    // MParContainer
+    void SetVariables(const TArrayD &arr);
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MFDataPhrase, 2) // A Filter for cuts in any data member
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfbase/MFEventSelector.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFEventSelector.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFEventSelector.cc	(revision 17960)
@@ -0,0 +1,216 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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);
+    }
+
+    if (fNumSelectEvts<0)
+    {
+        fSelRatio = 1;
+        *fLog << inf << "No selection will be done - all events selected." << endl;
+        return kTRUE;
+    }
+
+    // Calculate selection probability
+    fSelRatio = (Double_t)fNumSelectEvts/fNumTotalEvts;
+
+    *fLog << inf << "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)
+        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;
+        if (fNumSelectEvts>0)
+            fSelRatio = -1;
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mfbase/MFEventSelector.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFEventSelector.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFEventSelector.h	(revision 17960)
@@ -0,0 +1,39 @@
+#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
+
+    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: branches/Mars_McMismatchStudy/mfbase/MFEventSelector2.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFEventSelector2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFEventSelector2.cc	(revision 17960)
@@ -0,0 +1,596 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz,   01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek 11/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MFEventSelector2
+//
+// This is a filter to make a selection of events from a file, according to
+// a certain requested distribution in a given parameter (or combination
+// of parameters). The distribution is passed to the class through a histogram
+// of the relevant parameter(s) contained in an object of type MH3. The filter
+// will return true or false in each event such that the final distribution
+// of the parameter(s) for the events surviving the filter is the desired one. 
+// The selection of which events are kept in each bin of the parameter(s) is 
+// made at random (obviously the selection probability depends on the 
+// values of the parameters, and is dictated by the input histogram).
+//
+// This procedure requires the determination of the original distribution
+// of the given parameters for the total sample of events on the input file.
+// If the event loop contains a filter with name "FilterSelector2", this
+// filter will be applied when determining the original distribution.
+//
+// See Constructor for more instructions and also the example below:
+//
+// --------------------------------------------------------------------
+//
+// void select()
+// {
+//     MParList plist;
+//     MTaskList tlist;
+// 
+//     MStatusDisplay *d=new MStatusDisplay;
+// 
+//     plist.AddToList(&tlist);
+// 
+//     MReadTree read("Events", "myinputfile.root");
+//     read.DisableAutoScheme();
+//     // Accelerate execution...
+//     // read.EnableBranch("MMcEvt.fTelescopeTheta");
+// 
+//     // create nominal distribution (theta converted into degrees)
+//     MH3 nomdist("r2d(MMcEvt.fTelescopeTheta)");
+//     MBinning binsx;
+//     binsx.SetEdges(5, 0, 45);   // five bins from 0deg to 45deg
+//     MH::SetBinning(&nomdist.GetHist(), &binsx);
+//
+//     // use this to create a nominal distribution in 2D
+//     //  MH3 nomdist("r2d(MMcEvt.fTelescopeTheta)", "MMcEvt.fEnergy");
+//     //  MBinning binsy;
+//     //  binsy.SetEdgesLog(5, 10, 10000);
+//     //  MH::SetBinning((TH2*)&nomdist.GetHist(), &binsx, &binsy);
+//
+//     // Fill the nominal distribution with whatever you want:
+//     for (int i=0; i<nomdist.GetNbins(); i++)
+//         nomdist.GetHist().SetBinContent(i, i*i);
+// 
+//     MFEventSelector2 test(nomdist);
+//     test.SetNumMax(9999);  // total number of events selected
+//     MContinue cont(&test);
+// 
+//     MEvtLoop run;
+//     run.SetDisplay(d);
+//     run.SetParList(&plist);
+//     tlist.AddToList(&read);
+//     tlist.AddToList(&cont);
+// 
+//     if (!run.Eventloop())
+//         return;
+// 
+//     tlist.PrintStatistics();
+// }
+// 
+// --------------------------------------------------------------------
+//
+// The random number is generated using gRandom->Rndm(). You may
+// control this procedure using the global object gRandom.
+//
+// Because of the random numbers this works best for huge samples...
+//
+// Don't try to use this filter for the reading task or as a selector
+// in the reading task: This won't work!
+//
+// Remark: You can also use the filter together with MContinue
+//
+//
+// FIXME: Merge MFEventSelector and MFEventSelector2
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFEventSelector2.h"
+
+#include <TRandom.h>        // gRandom
+#include <TCanvas.h>        // TCanvas
+
+#include "MH3.h"            // MH3
+#include "MRead.h"          // MRead
+#include "MEvtLoop.h"       // MEvtLoop
+#include "MTaskList.h"      // MTaskList
+#include "MBinning.h"       // MBinning
+#include "MContinue.h"      // 
+#include "MFillH.h"         // MFillH
+#include "MParList.h"       // MParList
+#include "MStatusDisplay.h" // MStatusDisplay
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFEventSelector2);
+
+using namespace std;
+
+const TString MFEventSelector2::gsDefName  = "MFEventSelector2";
+const TString MFEventSelector2::gsDefTitle = "Filter to select events with a given distribution";
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Takes a reference to an MH3 which gives you
+//  1) The nominal distribution. The distribution is renormalized, so
+//     that the absolute values do not matter. To crop the distribution
+//     to a nominal value of total events use SetNumMax
+//  2) The parameters histogrammed in MH3 are those on which the
+//     event selector will work, eg
+//       MH3 hist("MMcEvt.fTelescopeTheta", "MMcEvt.fEnergy");
+//     Would result in a redistribution of Theta and Energy.
+//  3) Rules are also accepted in the argument of MH3, for instance: 
+//       MH3 hist("MMcEvt.fTelescopeTheta");
+//     would result in redistributing Theta, while
+//       MH3 hist("cos(MMcEvt.fTelescopeTheta)");
+//     would result in redistributing cos(Theta).
+//
+//  If the reference distribution doesn't contain entries (GetEntries()==0)
+//     the original distribution will be used as the nominal distribution;
+//     note that also in this case a dummy nominal distribution has to be
+//     provided in the first argument (the dummy distribution defines the
+//     variable(s) of interest, their binnings and their requested ranges;
+//     events outside these ranges won't be accepted).
+//
+//  Set default name of filter to be applied when determining the original
+//  distribution for all data on the input file to "FilterSelector2"
+//
+MFEventSelector2::MFEventSelector2(MH3 &hist, const char *name, const char *title)
+    : fHistOrig(NULL), fHistNom(&hist), fHistRes(NULL),
+    fDataX(hist.GetRule('x')), fDataY(hist.GetRule('y')),
+    fDataZ(hist.GetRule('z')), fNumMax(-1), fCanvas(0),
+    fFilterName("FilterSelector2"), fHistIsProbability(kFALSE),
+    fUseOrigDist(kTRUE)
+{
+    fName  = name  ? (TString)name  : gsDefName;
+    fTitle = title ? (TString)title : gsDefTitle;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fHistRes if instatiated
+//
+MFEventSelector2::~MFEventSelector2()
+{
+    if (fHistRes)
+        delete fHistRes;
+}
+
+//---------------------------------------------------------------------------
+//
+// Recreate a MH3 from fHistNom used as a template. Copy the Binning
+// from fHistNom to the new histogram, and return a pointer to the TH1
+// base class of the MH3.
+//
+TH1 &MFEventSelector2::InitHistogram(MH3* &hist)
+{
+    // if fHistRes is already allocated delete it first
+    if (hist)
+        delete hist;
+
+    // duplicate the fHistNom histogram
+    hist = static_cast<MH3*>(fHistNom->New());
+
+    // copy binning from one histogram to the other one
+    MH::SetBinning(hist->GetHist(), fHistNom->GetHist());
+
+    return hist->GetHist();
+}
+
+// --------------------------------------------------------------------------
+//
+// Try to read the present distribution from the file. Therefore the
+// Reading task of the present loop is used in a new eventloop.
+//
+Bool_t MFEventSelector2::ReadDistribution(MRead &read, MFilter *filter)
+{
+    if (read.GetEntries() > kMaxUInt) // FIXME: LONG_MAX ???
+    {
+        *fLog << err << "kIntMax exceeded." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator("MFEventSelector2::ReadDistribution");
+    *fLog << " - Start of eventloop to generate the original distribution..." << endl;
+
+    if (filter != NULL)
+        *fLog << " - filter used: " << filter->GetDescriptor() << endl;
+
+
+    MEvtLoop run("ReadDistribution");
+
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    run.SetParList(&plist);
+
+    MBinning binsx("BinningMH3X");
+    MBinning binsy("BinningMH3Y");
+    MBinning binsz("BinningMH3Z");
+    binsx.SetEdges(fHistNom->GetHist(), 'x');
+    binsy.SetEdges(fHistNom->GetHist(), 'y');
+    binsz.SetEdges(fHistNom->GetHist(), 'z');
+    plist.AddToList(&binsx);
+    plist.AddToList(&binsy);
+    plist.AddToList(&binsz);
+
+    MFillH fill(fHistOrig);
+    fill.SetName("FillHistOrig");
+    fill.SetBit(MFillH::kDoNotDisplay);
+    tlist.AddToList(&read);
+
+    MContinue contfilter(filter);
+    if (filter != NULL)
+    {
+      contfilter.SetName("ContFilter");
+      tlist.AddToList(&contfilter);
+    }
+
+    tlist.AddToList(&fill);
+    run.SetDisplay(fDisplay);
+    if (!run.Eventloop())
+    {
+        *fLog << err << dbginf << "Evtloop failed... abort." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    *fLog << inf;
+    *fLog << "MFEventSelector2::ReadDistribution:" << endl;
+    *fLog << " - Original distribution has " << fHistOrig->GetHist().GetEntries() << " entries." << endl;
+    *fLog << " - End of eventloop to generate the original distribution." << endl;
+    fLog->Separator();
+
+    return read.Rewind();
+}
+
+// --------------------------------------------------------------------------
+//
+// After reading the histograms the arrays used for the random event
+// selection are created. If a MStatusDisplay is set the histograms are
+// displayed there.
+//
+void MFEventSelector2::PrepareHistograms()
+{
+    TH1 &ho = fHistOrig->GetHist();
+
+    //-------------------
+    // if requested
+    // set the nominal distribution equal to the original distribution
+
+    const Bool_t 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 and filter task.
+//
+Int_t MFEventSelector2::PreProcess(MParList *parlist)
+{
+    memset(fCounter, 0, sizeof(fCounter));
+
+    MTaskList *tasklist = (MTaskList*)parlist->FindObject("MTaskList");
+    if (!tasklist)
+    {
+        *fLog << err << "MTaskList not found... abort." << endl;
+        return kFALSE;
+    }
+
+    if (!PreProcessData(parlist))
+        return kFALSE;
+
+    fHistNom->SetTitle(fHistIsProbability ? "ProbabilityDistribution" : 
+                                            "Users Nominal Distribution");
+
+    if (fHistIsProbability)
+        return kTRUE;
+
+    InitHistogram(fHistOrig);
+    InitHistogram(fHistRes);
+
+    fHistOrig->SetTitle("Primary Distribution");
+    fHistRes->SetTitle("Resulting Distribution");
+
+    // Initialize online display if requested
+    fCanvas = fDisplay ? &fDisplay->AddTab(GetName()) : NULL;
+    if (fCanvas)
+        fHistOrig->Draw();
+
+    // Generate primary distribution
+    MRead *read = (MRead*)tasklist->FindObject("MRead");
+    if (!read)
+    {
+        *fLog << err << "MRead not found in tasklist... abort." << endl;
+        return kFALSE;
+    }
+
+    MFilter *filter = (MFilter*)tasklist->FindObject(fFilterName);
+    if (!filter || !filter->InheritsFrom(MFilter::Class()))
+    {
+        *fLog << inf << "No filter will be used when making the original distribution" << endl;
+        filter = NULL;
+    }
+
+    if (!ReadDistribution(*read, filter))
+        return kFALSE;
+
+    // Prepare histograms and arrays for selection
+    PrepareHistograms();
+
+    *fLog << all << "PreProcess..." << flush;
+
+    if (filter != NULL)
+    {
+      const Int_t rcf = filter->CallPreProcess(parlist);
+      if (rcf!=kTRUE)
+        return rcf;
+    }
+
+    const Int_t rcr = read->CallPreProcess(parlist);
+    return rcr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Part of Process(). Select() at the end checks whether a selection should
+// be done or not. Under-/Overflowbins are rejected.
+//
+Bool_t MFEventSelector2::Select(Int_t bin)
+{
+    // under- and overflow bins are not accepted
+    if (bin<0)
+        return kFALSE;
+
+    Bool_t rc = kFALSE;
+
+    if (gRandom->Rndm()*fIs[bin]<=fNom[bin])
+    {
+        // how many events do we still want to read in this bin
+        fNom[bin]--;
+        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]--;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MFEventSelector2::SelectProb(Int_t ibin) const
+{
+    //
+    // If value is outside histogram range, accept event
+    //
+    return ibin<0 ? kTRUE : 
+           fHistNom->GetHist().GetBinContent(ibin+1) > gRandom->Uniform();
+}
+
+// --------------------------------------------------------------------------
+//
+// fIs[i] contains the distribution of the events still to be read from
+// the file. fNom[i] contains the number of events in each bin which
+// are requested.
+// The events are selected by:
+//     gRandom->Rndm()*fIs[bin]<=fNom[bin]
+//
+Int_t MFEventSelector2::Process()
+{
+    // get x,y and z (0 if fData not valid)
+    const Double_t valx=fDataX.GetValue();
+    const Double_t valy=fDataY.GetValue();
+    const Double_t valz=fDataZ.GetValue();
+
+    // don't except the event if it is outside the axis range
+    // of the requested distribution
+    const Int_t ibin = fHistNom->FindFixBin(valx, valy, valz)-1;
+    if (!fHistIsProbability)
+    {
+      if (ibin < 0)
+      {
+        fResult = kFALSE;
+        fCounter[1]++;
+        return kTRUE;
+      }
+    }
+
+    // check whether a selection should be made
+    fResult = fHistIsProbability ? SelectProb(ibin) : Select(ibin);
+    if (!fResult)
+    {
+      fCounter[2]++;
+      return kTRUE;
+    }
+
+    fCounter[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)((Float_t)(fCounter[1]*100)/(Float_t)(GetNumExecutions())+0.5)
+              << "%) Events not selected due to under/over flow" << endl;
+
+        *fLog << " " << setw(7) << fCounter[2] << " (" << setw(3)
+              << (int)((Float_t)(fCounter[2]*100)/(Float_t)(GetNumExecutions())+0.5)
+              << "%) Events not selected due to requested distribution" 
+              << endl;
+
+        *fLog << " " << fCounter[0] << " ("
+              << (int)((Float_t)(fCounter[0]*100)/(Float_t)(GetNumExecutions())+0.5)
+              << "%) Events selected" << endl;
+        *fLog << endl;
+    }
+
+    //---------------------------------
+
+    if (fDisplay && fDisplay->HasCanvas(fCanvas))
+    {
+        fCanvas->cd(4);
+        fHistRes->DrawClone("nonew");
+        fCanvas->Modified();
+        fCanvas->Update();
+    }
+
+    return kTRUE;
+}
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mfbase/MFEventSelector2.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFEventSelector2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFEventSelector2.h	(revision 17960)
@@ -0,0 +1,75 @@
+#ifndef MARS_MFEventSelector2
+#define MARS_MFEventSelector2
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFEventSelector2                                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+#ifndef MARS_MDataChain
+#include "MDataChain.h"
+#endif
+
+class TH1;
+class TCanvas;
+
+class MH3;
+class MRead;
+
+class MFEventSelector2 : public MFilter
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    MH3       *fHistOrig; // original distribution of the events
+    MH3       *fHistNom;  // nominal distribution
+    MH3       *fHistRes;  // resulting distribution
+    MDataChain fDataX;    // data rule for the x-axis
+    MDataChain fDataY;    // data rule for the y-axis
+    MDataChain fDataZ;    // data rule for the z-axis
+    Long_t     fNumMax;   // Maximum number of selected events
+    TArrayL    fIs;       //! array storing the original distribution
+    TArrayL    fNom;      //! array storing the nominal distribution
+    TCanvas   *fCanvas;   //! canvas for online display
+
+    TString    fFilterName; // name of the MFilter object to be used when determining the original distribution
+
+    Bool_t fResult;
+    Bool_t fHistIsProbability;
+    Bool_t fUseOrigDist;    // flag indicating that in the selection the original distribution is not changed
+
+    Int_t  fCounter[3];
+
+    TH1   &InitHistogram(MH3* &hist);
+    Bool_t ReadDistribution(MRead &read, MFilter *filter);
+    void   PrepareHistograms();
+    Bool_t PreProcessData(MParList *parlist);
+    Bool_t Select(Int_t bin);
+    Bool_t SelectProb(Int_t bin) const;
+
+    Int_t PreProcess(MParList *parlist);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MFEventSelector2(MH3 &hist, const char *name=NULL, const char *title=NULL);
+    ~MFEventSelector2();
+
+    MH3 *GetHistOrig() { return fHistOrig; }
+
+    void SetNumMax(Long_t max=-1) { fNumMax = max; }
+    void SetHistIsProbability(Bool_t b=kTRUE) { fHistIsProbability=b; }
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    ClassDef(MFEventSelector2, 0) // FIXME!
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfbase/MFRealTimePeriod.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFRealTimePeriod.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFRealTimePeriod.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfbase/MFRealTimePeriod.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFRealTimePeriod.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFRealTimePeriod.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfbase/MFilterList.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFilterList.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFilterList.cc	(revision 17960)
@@ -0,0 +1,509 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFilterList
+//
+// A filter list can be used to concatenate filter (derived from MFilter)
+// by a logical or bitwise operator. For more details see the constructor.
+//
+// The list is setup by adding filters to the list calling AddToList().
+// For example in the case of the default constructor ("&&") all results
+// are logically and'd together and the result of this and is returned.
+//
+// Because the meaning of all filters can be inverted calling SetInverted()
+// which is defined in the base class MFilter you can use this list to
+// invert the meaning of a filter, by eg:
+//
+//    MF anyfilter("MHillas.fAlpha");
+//
+//    MFilterList alist;
+//    alist.AddToList(&anyfilter);
+//
+//    alist.SetInverted();
+//
+//  or do
+//
+//    MFilterList alist(&anyfilter);
+//
+//
+// Adding the filterlist to the eventloop will process all contained filters.
+// Doing this as early as possible is a simple way of processing all filters.
+//
+// If you want to make the list delete all contained filters you may make
+// the list owner of the filters by calling SetOwner()
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFilterList.h"
+
+#include <fstream>
+
+#include <TString.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIter.h"
+
+ClassImp(MFilterList);
+
+using namespace std;
+
+static const TString gsDefName  = "MFilterList";
+static const TString gsDefTitle = "List combining filters logically.";
+
+// --------------------------------------------------------------------------
+//
+// Wrapper to simplify constructors.
+//
+void MFilterList::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    gROOT->GetListOfCleanups()->Add(&fFilters);
+    fFilters.SetBit(kMustCleanup);
+
+    fFilterType = kEAnd;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Default Constructor.
+//
+//   Specify the boolean operation which is used to evaluate the
+//   result of this list. If no operation is specified "land" is
+//   used.
+//
+//   Options:
+//      and,  &  : is a bitwise and
+//      or,   |  : is a bitwise or
+//      xor,  ^  : is a bitwise exclusive or
+//      land, && : is a logical and
+//      lor,  || : is a logical or
+//
+//   The bitwise operators are implemented for convinience. They may not
+//   make much sense. Maybe IsExpressionTrue should change its return
+//   type from Bool_t to Int_t.
+//
+MFilterList::MFilterList(const char *type, const char *name, const char *title)
+{
+    Init(name, title);
+
+    TString str(type);
+
+    if (!str.CompareTo("OR", TString::kIgnoreCase)  || !str.CompareTo("|"))
+        fFilterType = kEOr;
+    if (!str.CompareTo("XOR", TString::kIgnoreCase) || !str.CompareTo("^"))
+        fFilterType = kEXor;
+    if (!str.CompareTo("LAND", TString::kIgnoreCase) || !str.CompareTo("&&"))
+        fFilterType = kELAnd;
+    if (!str.CompareTo("LOR", TString::kIgnoreCase) || !str.CompareTo("||"))
+        fFilterType = kELOr;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Constructor.
+//
+// Setup an '&&' filter list, adds the filter to the list and
+// call MFilterList::SetInverted()
+//
+// To be used as a logical NOT.
+//
+MFilterList::MFilterList(MFilter *f, const char *name, const char *title)
+{
+    Init(name, title);
+
+    SetInverted();
+    AddToList(f);
+}
+
+// --------------------------------------------------------------------------
+//
+//   CopyConstructor
+//
+MFilterList::MFilterList(MFilterList &ts)
+{
+    fFilters.AddAll(&ts.fFilters);
+    fFilterType = ts.fFilterType;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Evaluates and returns the result of the filter list.
+//  The expression is evaluated step by step, eg:
+//  ((filter[0] # filter[1]) # filter[3]) # filter[4])
+//  The '#' stands for the boolean operation which is specified in
+//  the constructor.
+//
+Bool_t MFilterList::IsExpressionTrue() const
+{
+    TIter Next(&fFilters);
+
+    MFilter *filter=(MFilter*)Next();
+
+    if (!filter)
+        return kTRUE;
+
+    Bool_t rc = filter->IsConditionTrue();
+
+    //
+    // loop over all filters
+    //
+    switch (fFilterType)
+    {
+    case kEAnd:
+        while ((filter=(MFilter*)Next()))
+            rc &= filter->IsConditionTrue();
+        break;
+
+    case kEOr:
+        while ((filter=(MFilter*)Next()))
+            rc |= filter->IsConditionTrue();
+        break;
+
+    case kEXor:
+        while ((filter=(MFilter*)Next()))
+            rc ^= filter->IsConditionTrue();
+        break;
+
+    case kELAnd:
+        while ((filter=(MFilter*)Next()))
+            rc = (rc && filter->IsConditionTrue());
+        break;
+
+    case kELOr:
+        while ((filter=(MFilter*)Next()))
+            rc = (rc || filter->IsConditionTrue());
+        break;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to add a new filter to the list call this function with the
+// pointer to the filter to be added. 
+//
+Bool_t MFilterList::AddToList(MFilter *filter)
+{
+    if (!filter)
+        return kTRUE;
+
+    const char *name = filter->GetName();
+
+    if (fFilters.FindObject(filter))
+    {
+        *fLog << warn << dbginf << "Filter " << filter << " already existing... skipped." << endl;
+        return kTRUE;
+    }
+
+    if (fFilters.FindObject(name))
+        *fLog << inf << "MFilterList::AddToList - '" << name << "' exists in List already..." << endl;
+
+    *fLog << inf << "Adding " << name << " to " << GetName() << "... " << flush;
+
+    filter->SetBit(kMustCleanup);
+    fFilters.Add(filter);
+
+    *fLog << "Done." << endl;
+
+    AddToBranchList(filter->GetDataMember());
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to add a new filters from a TCollection to the list call
+// this function.
+//
+Bool_t MFilterList::AddToList(const TCollection &col)
+{
+    TIter Next(&col);
+    MFilter *f=0;
+    Int_t idx=0;
+    while ((f=(MFilter*)Next()))
+    {
+        if (!f->InheritsFrom(MFilter::Class()))
+        {
+            *fLog << warn << "WARNING - An object in TCollection doesn't inherit from MFilter... ignored." << endl;
+            continue;
+        }
+
+        f->SetName(Form("F%d", idx++));
+        if (!AddToList(f))
+            return kFALSE;
+    }
+    return kTRUE;
+}
+
+void MFilterList::SetAccelerator(Byte_t acc)
+{
+    fFilters.R__FOR_EACH(MTask, SetAccelerator)(acc);
+    MFilter::SetAccelerator(acc);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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()))
+    {
+        filter->SetAccelerator(GetAccelerator());
+        if (!filter->CallPreProcess(pList))
+        {
+            *fLog << err << "Error - Preprocessing Filter ";
+            *fLog << filter->GetName() << " in " << fName << endl;
+            return kFALSE;
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit all filters in the list
+//
+Bool_t MFilterList::ReInit(MParList *pList)
+{
+    TIter Next(&fFilters);
+
+    MFilter *filter=NULL;
+
+    //
+    // loop over all filters
+    //
+    while ((filter=(MFilter*)Next()))
+    {
+        if (!filter->ReInit(pList))
+        {
+            *fLog << err << "Error - ReInit 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(ostream &out) const
+{
+    out << "   MFilterList " << ToLower(fName) << "(\"";
+
+    switch (fFilterType)
+    {
+    case kEAnd:
+        out << "&";
+        break;
+
+    case kEOr:
+        out  << "|";
+        break;
+
+    case kEXor:
+        out  << "^";
+        break;
+
+    case kELAnd:
+        out << "&&";
+        break;
+
+    case kELOr:
+        out << "||";
+        break;
+    }
+
+    out << "\"";
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl << endl;
+
+    MIter Next(&fFilters);
+
+    MParContainer *cont = NULL;
+    while ((cont=Next()))
+    {
+        cont->SavePrimitive(out, "");
+
+        out << "   " << ToLower(fName) << ".AddToList(&";
+        out << cont->GetUniqueName() << ");" << endl << endl;
+    }
+}
+
+TString MFilterList::GetRule(Option_t *opt) const
+{
+    TString str(opt);
+    const Bool_t verbose = str.Contains("V", TString::kIgnoreCase);
+
+    TString ret = "(";
+
+    TIter Next(&fFilters);
+
+    MFilter *filter=(MFilter*)Next();
+
+    //
+    // loop over all filters
+    //
+    if (!filter)
+        return "<empty>";
+
+    ret += filter->GetRule();
+
+    while ((filter=(MFilter*)Next()))
+    {
+        switch (fFilterType)
+        {
+        case kEAnd:
+            ret += (verbose?" and ":" & ");
+            break;
+
+        case kEOr:
+            ret += (verbose?" or ":" | ");
+            break;
+
+        case kEXor:
+            ret += (verbose?" xor ":" ^ ");
+            break;
+
+        case kELAnd:
+            ret += (verbose?" land ":" && ");
+            break;
+
+        case kELOr:
+            ret += (verbose?" lor ":" || ");
+            break;
+        }
+
+        ret += filter->GetRule();
+    }
+
+    return ret+")";
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members existing in this array in a comma-seperated list
+// (This is mainly used for MTask::AddToBranchList)
+//
+TString MFilterList::GetDataMember() const
+{
+    TString str;
+
+    TIter Next(&fFilters);
+    MFilter *filter = NULL;
+    while ((filter=(MFilter*)Next()))
+    {
+        if (filter->GetDataMember().IsNull())
+            continue;
+
+        str += ",";
+        str += filter->GetDataMember();
+    }
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over all set filters and distribute arr to their SetVariables.
+// Make sure, that the values are unique (not two filters using the
+// same index in the array with different meanings)
+//
+void MFilterList::SetVariables(const TArrayD &arr)
+{
+    fFilters.R__FOR_EACH(MFilter, SetVariables)(arr);
+}
Index: branches/Mars_McMismatchStudy/mfbase/MFilterList.h
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/MFilterList.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/MFilterList.h	(revision 17960)
@@ -0,0 +1,71 @@
+#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(std::ostream &out) const;
+
+    void Init(const char *name, const char *title);
+
+public:
+    MFilterList(const char *type="&&", const char *name=NULL, const char *title=NULL);
+    MFilterList(MFilter *f, const char *name=NULL, const char *title=NULL);
+    MFilterList(MFilterList &ts);
+    ~MFilterList()
+    {
+        if (TestBit(kIsOwner))
+            fFilters.SetOwner();
+    }
+
+    Bool_t AddToList(MFilter *filter);
+    Bool_t AddToList(const TCollection &col);
+    void SetOwner(Bool_t enable=kTRUE) { enable ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    Bool_t IsExpressionTrue() const;
+
+    void Print(Option_t *opt = "") const;
+
+    TString GetRule() const { return GetRule(""); }
+    TString GetRule(Option_t *opt) const;
+    TString GetDataMember() const;
+
+    Int_t GetNumEntries() const { return fFilters.GetEntries(); }
+
+    Bool_t ReInit(MParList *plist);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    void SetAccelerator(Byte_t acc=kAccStandard);
+
+    void SetVariables(const TArrayD &arr);
+
+    ClassDef(MFilterList, 1)		// List to combine several filters logically
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfbase/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mfbase/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfbase/Makefile	(revision 17960)
@@ -0,0 +1,32 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mdata -I../mfileio -I../mhbase
+
+CINT     = FBase
+
+SRCFILES = MF.cc \
+	   MFDataPhrase.cc \
+           MFilterList.cc \
+           MFEventSelector.cc \
+           MFEventSelector2.cc \
+	   MFDataChain.cc \
+	   MFDataMember.cc \
+           MFRealTimePeriod.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mfileio/FileIOIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/FileIOIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/FileIOIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mfileio/FileIOLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/FileIOLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/FileIOLinkDef.h	(revision 17960)
@@ -0,0 +1,22 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class 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 MReadFiles+;
+#pragma link C++ class MReadScanFile+;
+
+#pragma link C++ class MRootFileBranch+;
+
+#pragma link C++ class MWriteFile+;
+#pragma link C++ class MWriteAsciiFile+;
+#pragma link C++ class MWriteRootFile+;
+#pragma link C++ class MWriteFitsFile+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MChain.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MChain.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MChain.cc	(revision 17960)
@@ -0,0 +1,71 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MChain
+//
+// Helper class for MReadTree
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MChain.h"
+
+ClassImp(MChain);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// This is the code from TChain::LoadTree but skips the
+// notification in LoadTree. If LoadTree raises the notification
+// a flag is set and the notification is done by hand. This
+// is done to be able to catch the return value from Notify. If
+// it has not been successfull -15 is returned.
+// This is to support return values from Notify()/Reinit().
+// The status can be checked afterward by HasError/HasFatalError/GetError
+//
+Long64_t MChain::LoadTree(Long64_t entry)
+{
+    TObject *notify = GetNotify();
+
+    SetNotify(this);
+
+    Long64_t rc = TChain::LoadTree(entry);
+
+    // <0: LoadTree failed
+    // =0: LoadTree was ok
+    // >0: Notify failed
+    fLastError = rc;
+
+    if (rc>=0 && fNotified && notify)
+    {
+        fLastError = notify->Notify() ? 0 : kFatalError;
+        if (fLastError==kFatalError)
+            rc = -15;
+    }
+
+    SetNotify(notify);
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mfileio/MChain.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MChain.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MChain.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MChain
+#define MARS_MChain
+
+#ifndef ROOT_TChain
+#include <TChain.h>
+#endif
+
+class MChain : public TChain
+{
+public:
+    // Taken from TChain::LoadTree --- may have to be updated for different root versions
+    enum {
+        kCannotAccessTree = -4,  // Tree not found in file
+        kCannotAccessFile = -3,  // File access impossible
+        kOutOfRange       = -2,  // Event doesn't exist
+        kNoError          =  0,  // LoadTree succeeded
+        kFatalError       =  1   // LoadTree succeeded, but Notify() returned fatal error
+    };
+
+private:
+    Bool_t   fNotified;
+    Long64_t fLastError; // <0: LoadTree failed, =0: LoadTree was ok, >0: Notify failed
+
+public:
+    MChain() : TChain(), fNotified(kFALSE), fLastError(0) {}
+    MChain(const char *name, const char *title="") : TChain(name, title), fNotified(kFALSE), fLastError(0) {}
+
+    // Restart from scratch
+    void ResetTree() { fTree = 0; fTreeNumber = -1; }
+
+    // Function to be notified and setting the notifier
+    virtual Bool_t Notify() { fNotified = kTRUE; return kTRUE; }
+    virtual void   SetNotify(TObject *obj) { fNotify = obj; fNotified = kFALSE; }
+
+    // Overwrite LoadTree (for different root versions)
+    Int_t    LoadTree(Int_t entry) { return (Int_t)LoadTree((Long64_t)entry); }
+    Long64_t LoadTree(Long64_t entry);
+
+    // Handling for last error of LoadTree
+    Long64_t GetLastError() const { return fLastError; };
+    Bool_t   HasFatalError() const { return fLastError==kFatalError; }
+    Bool_t   HasError() const { return fLastError==0 ? kFALSE : kTRUE; }
+
+    ClassDef(MChain, 1) // Class derived from TChain to give access to Notify-return value
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MFitsArray.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MFitsArray.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MFitsArray.cc	(revision 17960)
@@ -0,0 +1,195 @@
+#include "MAGIC.h"
+#include "MLogManip.h"
+
+#include "MFitsArray.h"
+
+#include <TDataMember.h>
+#include <TClonesArray.h>
+#include <TClass.h>
+#include <TList.h>
+
+using namespace std;
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// Opens the FITS table of this TClonesArray. This should be done after all    
+// columns are initialized. baseFileName is the name of the group, this        
+// children table belongs to. dataName is the name of the TClonesArray         
+// variable in the MParContainer - class.                                      
+//                                                                             
+Bool_t MArrayHelperBase::OpenFitsTable(const char * baseFileName, 
+                                         const char * dataName, 
+                                         const char * option, MLog * log )
+{
+   // get the baseFileName without extension                     
+   char fileNameNoExt[strlen(baseFileName) + 1];
+   strcpy(fileNameNoExt, baseFileName);
+   // remove the extension                                       
+   char * pos = strrchr(fileNameNoExt, '.');
+   if (pos) *pos = 0;
+
+   // add the dataName to the file name define the table name:   
+   // result will be something like:                             
+   // baseFileName_dataName.fits[dataName]                       
+   TString dol = fileNameNoExt;
+   TString fileName;
+   dol += "_";
+   dol += dataName;
+   dol += ".fits";
+   fileName = dol;
+//   dol += "[";
+//   dol += dataName;
+//   dol += "]";
+
+//   try {
+
+      if (strcmp(option, "RECREATE") == 0)
+         // remove the file
+         unlink(fileName.Data());
+
+      // create the file with the FITS table and all its columns    
+      //FIXME I must implement a constructor and set fFitsTable to NULL
+      //Otherwise I cannot safely destroy the object (in the destructor, also to be implemented)
+      fFitsTable = new ofits();
+      fFitsTable->open(dol.Data());
+
+//      }
+//   catch (exception & e)
+//      {
+//      *log << err << e.what() << endl;
+//      return kFALSE;
+ //     }
+   return kTRUE;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// Determines the size of the buffer to store all data of the clonesArray -    
+// Class, which should be written to a FITS table. The buffer is allocated.    
+//                                                                             
+// status is set to kFALSE if some data cannot be stored in a FITS table,      
+// for example more than 1 dimensional arrays.                                 
+MClonesArrayHelper::MClonesArrayHelper(TClonesArray * clonesArray, MLog * log, 
+                                       Bool_t & status)
+  :  fClonesArray(clonesArray) 
+{
+   status = kTRUE;
+
+   // get size of buffer
+   fDataBufferSize = 0;
+   fStartOfData    = 0x7fffffff;
+
+   TList * dataMembers = fClonesArray->GetClass()->GetListOfDataMembers();
+   TIter next(dataMembers);
+   TDataMember * dataMember;
+
+   while ((dataMember = (TDataMember*)next()) != NULL)
+      {
+      if (!dataMember->IsPersistent())
+         continue;
+
+      if (dataMember->Property() & ( G__BIT_ISENUM | G__BIT_ISSTATIC))
+         continue;
+
+      if (strcmp(dataMember->GetTrueTypeName(), "TClass*") == 0)
+         continue;
+
+      // is it an array of more than 1 dimension?
+      if (dataMember->GetArrayDim() > 1)
+         {
+         *log << err << "Two and more dimensional arrays of member variables"
+                         " are not supported." << endl;
+         *log <<        "See variable " << dataMember->GetName() << 
+                         " in container " << fClonesArray->GetClass()->GetName() <<  endl;
+         status = kFALSE;
+         return;
+         }
+
+
+      // get the position, where the current variable ends.
+      Int_t endPos;
+      if (dataMember->GetArrayDim() == 1)
+         endPos = dataMember->GetOffset() + (dataMember->GetUnitSize() * 
+                                             dataMember->GetMaxIndex(0)  );
+      else
+         endPos = dataMember->GetOffset() + dataMember->GetUnitSize();
+
+      if (endPos > fDataBufferSize)
+         fDataBufferSize = endPos;
+
+      if (dataMember->GetOffset() < fStartOfData)
+         fStartOfData = dataMember->GetOffset();
+      }      
+
+   fDataBuffer = new Byte_t[fDataBufferSize];
+
+}
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// the fClonesArray, the size of the data buffer and the fits Table are        
+// copied. A new buffer is allocated. Note: the fArraySize is not copied.      
+// Anyhow only its pointer is needed, which will change during this copy       
+//                                                                             
+MClonesArrayHelper::MClonesArrayHelper(const MClonesArrayHelper & clHelper)
+   : fClonesArray(clHelper.fClonesArray)
+{
+   fFitsTable       = clHelper.fFitsTable;
+   fDataBufferSize  = clHelper.fDataBufferSize;
+   fStartOfData     = clHelper.fStartOfData;
+   fDataBuffer      = new Byte_t[fDataBufferSize];
+}
+
+
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// Writes all currently stored classes in the fClonesArray, i. e. writes 0 to  
+// may rows to the FITS table.                                                 
+// fArraySize is updated with the number of new row, written to the FITS       
+// table. Therefore the parent FITS table must be updated after calling this   
+// method.                                                                     
+//                                                                             
+void MClonesArrayHelper::Write()
+{
+   // get number of classes in fClonesArray.                                 
+   fArraySize = fClonesArray->GetLast() + 1;
+
+   for (UInt_t idx = 0; idx < fArraySize; idx++)
+      {
+      // copy the data of one class to fDataBuffer                           
+      memcpy(fDataBuffer, (*fClonesArray)[idx], fDataBufferSize);
+
+      // now the data can be written from the fDataBuffer to the FITS table  
+      fFitsTable->WriteRow(fDataBuffer, fDataBufferSize);
+      }
+}
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// resize the clone array (fClonesArray) and reads fArraySize data sets from   
+// the FITS file into the fClonesArray.                                        
+// The number of data sets must be determined before calling this function,    
+// i.e. the parent FITS table must be read before calling this method.         
+Int_t MClonesArrayHelper::Read()
+{
+ /*  fClonesArray->ExpandCreate(fArraySize);
+
+   for (int idx = 0; idx < fArraySize; idx++)
+      {
+      // read the data in the buffer
+      if (!fFitsTable.Read())
+         {
+         gLog << "Expecting more entries in " << fFitsTable.GetFileName() << endl;
+         return kERROR;
+         }
+      // copy the data of one class from fDataBuffer into the class
+      memcpy( (Byte_t*)((*fClonesArray)[idx]) + fStartOfData, 
+              fDataBuffer + fStartOfData, fDataBufferSize - fStartOfData);
+      }
+*/
+   return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mfileio/MFitsArray.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MFitsArray.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MFitsArray.h	(revision 17960)
@@ -0,0 +1,118 @@
+#ifndef MARS_MFitsArray
+#define MARS_MFitsArray
+
+//#include "astroroot.h"
+//#include "fitsio.h"
+#ifndef MARS_fits
+#include "fits.h"
+#endif
+
+#ifndef MARS_ofits
+#include "ofits.h"
+#endif
+
+class TClonesArray;
+class MLog;
+
+///////////////////////////////////////////////////////////////////////////////
+// A base class for arrays, which has to be written into their own FITS table  
+class MArrayHelperBase
+{
+protected:
+
+   // the FITS table to which the data are written                      
+   ofits*     fFitsTable;
+   
+   // number of elements in fClonesArray / MArrayX / TArrayX  during 
+   // one write operation. This number is written into a column of   
+   // the parent FITS table.                                         
+   UInt_t           fArraySize;
+
+public:
+   ofits* GetFitsTable()     {return fFitsTable;}
+   UInt_t *      GetArraySizePtr()  {return &fArraySize;}
+
+   Bool_t  OpenFitsTable(const char * baseFileName, const char * dataName, 
+                         const char * option, MLog * log);
+
+   virtual void  InitCol() {}
+
+   virtual Int_t Read() = 0;
+   virtual void  Write() = 0;
+
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// A class to write data of one TClonesArray into one FITS table.              
+class MClonesArrayHelper : public MArrayHelperBase
+{
+   // data of this TClonesArray are written to fFitsTable               
+   TClonesArray *  fClonesArray;  
+
+
+
+   // fFitsTable writes during one fFitsTable.Write() call data which   
+   // are currently stored in this buffer. That means the data pointers 
+   // of fFitsTable for each column point to this data buffer.          
+   Byte_t *        fDataBuffer;
+
+   // the size of fDataBufferer.                                        
+   Int_t           fDataBufferSize;
+
+   // the first used byte in fDataBuffer                                
+   Int_t           fStartOfData;
+
+public:
+   MClonesArrayHelper(TClonesArray * clonesArray, MLog * log, Bool_t & status);
+   MClonesArrayHelper(const MClonesArrayHelper & clHelper);
+
+   ~MClonesArrayHelper()   {delete [] fDataBuffer;}
+
+   void  *       GetDataBuffer()    {return fDataBuffer;}
+
+   Int_t   Read();
+   void    Write();
+
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes to write and read data of MArray* classes                           
+template<class BaseT, class ClassT>
+   class MArrayHelper : public MArrayHelperBase
+{
+   ClassT   *  fArrayClass;
+
+   BaseT       fDataBuffer;
+   char        fDataType[10];
+
+public:
+   MArrayHelper(ClassT * arrayClass, const char * dataType)
+      {fArrayClass = arrayClass;
+       strcpy(fDataType, dataType);}
+
+   void    InitCol()
+   {
+       //FIXME ETIENNE HERE
+//       fFitsTable.InitCol("Data", fDataType, &fDataBuffer);
+//       fFitsTable->AddColumn(
+//       fFitsTables[tableName]->AddColumn(count, typeChar, truncatedName, unit, truncatedComment);
+
+   }
+
+   Int_t   Read() { return 0;}
+   void    Write()
+   {
+       fArraySize = fArrayClass->GetSize();
+       for (UInt_t idx = 0; idx < fArraySize; idx++)
+       {
+          fDataBuffer = (*fArrayClass)[idx];
+//FIXME ETIENNE HERE
+          //          fFitsTable.Write();
+       }
+   }
+
+
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mfileio/MRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MRead.cc	(revision 17960)
@@ -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): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRead
+//
+// Base class for all reading tasks
+//
+// You can set a selector. Depending on the impelementation in the derived
+// class it can be used to skip events, if the filter return kFALSE.
+// Make sure that the selector (filter) doesn't need information which
+// doesn't exist before reading an event!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRead.h"
+
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+
+ClassImp(MRead);
+
+using namespace std;
+
+Bool_t MRead::Rewind()
+{
+    *fLog << err << "ERROR - Rewind() not implemented for " << GetDescriptor() << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the name of the file we are actually reading from.
+//
+TString MRead::GetFileName() const
+{
+    TString name(GetFullFileName());
+    if (name.IsNull())
+        return "<n/a>";
+    return gSystem->BaseName(name);
+}
+
+Int_t MRead::AddFiles(MDirIter &files)
+{
+    files.Reset();
+
+    Int_t rc = 0;
+
+    TString str;
+    while (!(str=files.Next()).IsNull())
+    {
+        const Int_t num = AddFile(str);
+        if (num<0)
+            *fLog << warn << "Warning: AddFile(\"" << str << "\") returned " << num << "... skipped." << endl;
+        else
+            rc += num;
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   File0, File1, File2, ..., File10, ..., File100, ...
+//
+// Searching stops if the first key isn't found in the TEnv
+//
+// Enclosing quotation marks (") are removed
+//
+// Number of entries at the moment not supported
+//
+Int_t MRead::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    //
+    // Search (beginning with 0) all keys
+    //
+    int i=0;
+    while (1)
+    {
+        TString idx = "File";
+        idx += i;
+
+        // Output if print set to kTRUE
+        if (!IsEnvDefined(env, prefix, idx, print))
+            break;
+
+        // Try to get the file name
+        TString name = GetEnvValue(env, prefix, idx, "");
+        if (name.IsNull())
+        {
+            *fLog << warn << prefix+"."+idx << " empty." << endl;
+            continue;
+        }
+
+        if (name.BeginsWith("\"") && name.EndsWith("\""))
+        {
+            name.Remove(name.Last('\"'), 1);
+            name.Remove(name.First('\"'), 1);
+        }
+
+        *fLog << inf << "Add File: " << name << endl;
+
+        AddFile(name);
+        i++;
+    }
+
+    return i!=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the file exists and has read permission. Derived classes
+// should also check whether its file type is correct.
+//
+// Returning 0 means: file doesn't exist.
+// A returned number corresponds to different file types (1 if only
+// one exists)
+//
+Byte_t MRead::IsFileValid(const char *name)
+{
+    return !gSystem->AccessPathName(name, kFileExists) ? 1 : 0;
+}
Index: branches/Mars_McMismatchStudy/mfileio/MRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MRead.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MRead
+#define MARS_MRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MFilter;
+class MDirIter;
+
+class MRead : public MTask
+{
+private:
+    MFilter *fSelector;
+
+public:
+    MRead() : fSelector(NULL) {}
+
+    virtual UInt_t  GetEntries() = 0;
+    virtual TString GetFileName() const;
+    virtual TString GetFullFileName() const = 0;
+    virtual Bool_t  Rewind();
+
+    static Byte_t IsFileValid(const char *name);
+
+    void SetSelector(MFilter *f) { fSelector = f; }
+    MFilter *GetSelector() { return fSelector; }
+
+    virtual Int_t AddFile(const char */*fname*/, Int_t /*entries*/=-1) { return -1; }
+    Int_t AddFiles(MDirIter &dir);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    ClassDef(MRead, 0)	// Base class for a reading task
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MReadFiles.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadFiles.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadFiles.cc	(revision 17960)
@@ -0,0 +1,266 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 7/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadFiles
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadFiles.h"
+
+#include <errno.h>
+
+#include <TObjString.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "izstream.h"
+#include "MDirIter.h"
+
+ClassImp(MReadFiles);
+
+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.
+//
+MReadFiles::MReadFiles(const char *fname, const char *name, const char *title)
+    : fNumFile(0), fNumLine(0), fParList(0), fIn(0)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Reads a Reflector output file";
+
+    //
+    // remember file name for opening the file in the preprocessor
+    //
+    fFileNames.SetOwner();
+
+    if (fname)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MReadFiles::~MReadFiles()
+{
+    if (fIn)
+        delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call Close() and reset fNumLine and fNumFile
+//
+Bool_t MReadFiles::Rewind()
+{
+    Close();
+
+    fNumFile = 0;
+    fNumLine = 0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a line from the file, return kFALSE if stream is at the end,
+// kTRUE in case of success. Increase fNumLine in case of success.
+//
+Bool_t MReadFiles::ReadLine(TString &line)
+{
+    line.ReadLine(*fIn);
+    if (!*fIn)
+        return kFALSE;
+
+    fNumLine++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Close an open stream and set fIn to NULL
+//
+void MReadFiles::Close()
+{
+    if (fIn)
+        delete fIn;
+
+    fIn = NULL;
+    fFileName = "";
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MReadFiles::OpenNextFile(Int_t num)
+{
+    // First close an open file, if any
+    Close();
+
+    if (num>=0)
+        fNumFile=num;
+
+    // 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;
+    }
+
+    // open the file which is the first one in the chain
+    fFileName = fFileNames.At(fNumFile)->GetName();
+
+    *fLog << inf << "Open file: " << fFileName << endl;
+
+    // open a stream to a zipped or unzipped file
+    fIn = new izstream(fFileName);
+    if (!*fIn)
+    {
+        *fLog << err << "Cannot open file " << fFileName << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    //*fLog << inf;
+    //fLog->Separator(fFileName);
+
+    fNumFile++;
+    fNumLine=0;
+
+    // return stream status
+    return *fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open next file (the first one) and call AnalyzeHeader.
+// Rewind() afterwards.
+//
+Int_t MReadFiles::PreProcess(MParList *plist)
+{
+    fParList = plist;
+
+    Rewind();
+
+    if (!OpenNextFile())
+        return kFALSE;
+
+    if (!AnalyzeHeader(*plist))
+        return kFALSE;
+
+    Rewind();
+
+    return kTRUE;
+}
+
+Int_t MReadFiles::Process()
+{
+    // if no file open or there was a failure
+    if (!fIn || !*fIn)
+    {
+        // try to open the next file
+        if (!OpenNextFile())
+            return kFALSE;
+
+        // read the header from the file
+        if (!ReadHeader())
+            return kERROR;
+
+        // after reading the header ReInit tasklist
+        if (!ReInit(fParList))
+            return kERROR;
+    }
+
+    // Read one event
+    return ReadEvent();
+}
+
+Int_t MReadFiles::PostProcess()
+{
+    Close();
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Check if the file is accessible
+//
+Bool_t MReadFiles::CheckFile(TString name) const
+{
+    gSystem->ExpandPathName(name);
+
+    if (IsFileValid(name))
+        return kTRUE;
+
+    *fLog << err;
+    *fLog << "ERROR - File " << name<< " not accessible!" << endl;
+    return kFALSE;;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain. Wildcards as accepted
+// by MDirIter are allowed.
+//
+Int_t MReadFiles::AddFile(const char *txt, int)
+{
+    const TString dir  = gSystem->DirName(txt);
+    const TString base = gSystem->BaseName(txt);
+
+    Int_t num = 0;
+
+    MDirIter Next(dir, base);
+    while (1)
+    {
+        const TString fname = Next();
+        if (fname.IsNull())
+            break;
+
+        if (!CheckFile(fname))
+            continue;
+
+        if (fFileNames.FindObject(fname))
+            *fLog << warn << "WARNING - " << fname << " already in list." << endl;
+
+        *fLog << inf2 << fname << " added to list." << endl;
+        fFileNames.AddLast(new TObjString(fname));
+        num++;
+    }
+
+    if (num>1)
+        *fLog << inf2 << num << " files added to list." << endl;
+
+    if (num==0)
+        *fLog << warn << "WARNING - No files found at " << txt << endl;
+
+    return num;
+}
Index: branches/Mars_McMismatchStudy/mfileio/MReadFiles.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadFiles.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadFiles.h	(revision 17960)
@@ -0,0 +1,56 @@
+#ifndef MARS_MReadFiles
+#define MARS_MReadFiles
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class izstream;
+
+class MReadFiles : public MRead
+{
+private:
+    TList     fFileNames;  // Array which stores the \0-terminated filenames
+
+    TString   fFileName;   // Currently open file
+
+    UInt_t    fNumFile;    // File number in sequence
+    UInt_t    fNumLine;    // Line number in file
+
+    MParList *fParList;    //! Parlist for reinitialization
+
+    virtual Bool_t AnalyzeHeader(MParList &plist)=0;
+    virtual Bool_t ReadHeader()=0;
+    virtual Int_t  ReadEvent()=0;
+
+protected:
+    izstream *fIn;         // the inputfile
+
+    // MReadFiles
+    Bool_t ReadLine(TString &line);
+
+    UInt_t GetNumLine() const { return fNumLine; }
+
+    Bool_t OpenNextFile(Int_t num=-1);
+    Bool_t CheckFile(TString name) const;
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MReadFiles(const char *filename=NULL, const char *name=NULL,
+               const char *title=NULL);
+    ~MReadFiles();
+
+    Int_t AddFile(const char *fname, int i=0);
+
+    Bool_t  Rewind();
+    void    Close();
+    TString GetFullFileName() const { return fFileName; }
+
+    ClassDef(MReadFiles, 0) // Base class to read a chain of files
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MReadMarsFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadMarsFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadMarsFile.cc	(revision 17960)
@@ -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): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadMarsFile
+//
+// This task works more or less like MReadTree, but in addition PreProcess
+// reads all the information from the 'RunHeader' tree.
+//
+// Warning: Until now this works only for 'one run header per file'
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadMarsFile.h"
+
+#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MRawRunHeader.h"
+
+#include "MMcRunHeader.hxx"
+
+ClassImp(MReadMarsFile);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. Don't use it.
+//
+MReadMarsFile::MReadMarsFile() : fRun(NULL)
+{
+    fName  = "MRead";
+    fTitle = "Read tree and run headers from Mars file.";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. It creates a MReadTree object to read the
+//  RunHeaders and disables Auto Scheme for this tree.
+//
+MReadMarsFile::MReadMarsFile(const char *tname, const char *fname,
+                             const char *name, const char *title)
+    : MReadTree(tname, fname)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Read tree and run headers from Mars file.";
+
+    //
+    // open the input stream
+    //
+    fRun = new MReadTree("RunHeaders", fname, "RunHeaders");
+
+    //
+    // This disables the auto scheme. because reading new runheader is done
+    // at a low frequency we don't loose time if we always read all
+    // runheaders
+    //
+    fRun->DisableAutoScheme();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deleted the MReadTree object for the RunHeaders
+//
+MReadMarsFile::~MReadMarsFile()
+{
+    delete fRun;
+}
+
+Byte_t MReadMarsFile::IsFileValid(const char *name)
+{
+    ifstream fin(name);
+    if (!fin)
+        return 0;
+
+    Char_t c[4];
+    fin.read(c, 4);
+    if (!fin)
+        return 0;
+
+    if (!(c[0]=='r'&& c[1]=='o' && c[2]=='o' && c[3]=='t'))
+        return 0;
+
+    TFile f(name, "READ");
+
+    TTree *t = (TTree*)f.Get("Events");
+    if (!t)
+        return 0;
+
+    // FIXME: Replace numbers by enum! Maybe use bits?
+    if (t->FindBranch("MRawEvtData."))
+        return t->FindBranch("MMcEvt.") ? 2 : 1;
+
+    if (t->FindBranch("MCerPhotEvt."))
+        return t->FindBranch("MMcEvt.") ? 4 : 3;
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  see MReadTree::AddFile, too. The file is also added to the chain for
+//  the run headers. If adding file gives a different result for both
+//  chains -1 is returned, otherwise the number of files which were added.
+//
+Int_t MReadMarsFile::AddFile(const char *fname, Int_t entries)
+{
+    //
+    // FIXME! A check is missing whether the file already exists or not.
+    //
+    //
+    // returns the number of file which were added
+    //
+    if (!fRun)
+        return -1;
+
+    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!
+
+    const Int_t rc = fRun->Process();
+    if (rc!=kTRUE)
+    {
+        *fLog << err << "ERROR - Cannot read new runheaders #" << idx;
+        *fLog << " after reading event #" << GetNumEntry();
+        *fLog << " (MReadTree::Process() returned rc=" << rc << ")" << 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 (!rawheader->IsValid())
+    {
+        *fLog << warn << "WARNING - The run header (MRawRunHeader) read from the file returns not IsValid()." << endl;
+        *fLog << "          Please check if the file contents are ok." << endl;
+        rawheader->Print("header");
+    }
+
+    const MMcRunHeader *mcheader = (MMcRunHeader*)fParList->FindObject("MMcRunHeader");
+    if (mcheader)
+    {
+        if (mcheader->GetCamVersion()==50)
+        {
+            *fLog << warn << "WARNING - You are using a file created with Camera 0.5." << endl;
+            *fLog << "In this camera version some events have undefined Impact-Values" << endl;
+            *fLog << "(MMcEvt::fImpact) Please don't use it for MC studies using the" << endl;
+            *fLog << "impact parameter." << endl;
+        }
+    }
+
+    MTaskList *tlist = (MTaskList*)fParList->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << err << dbginf << "ERROR - MTaskList not found in Parameter List." << endl;
+        return kFALSE;
+    }
+
+    if (tlist->ReInit())
+        return kTRUE;
+
+    //MReadTree::Notify();
+
+    *fLog << err << "ERROR - ReInit of '" << tlist->GetDescriptor() << "' failed." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  PreProcessed the MReadTree to read the run headers and its base class.
+//  see MReadTree::PreProcess for more information
+//
+Int_t MReadMarsFile::PreProcess(MParList *pList)
+{
+    if (!fRun)
+    {
+        *fLog << err << "Error - Cannot use MReadMarsFile instantiated with default constructor... aborting." << endl;
+        return kFALSE;
+    }
+
+    fParList = pList;
+
+    if (!fRun->PreProcess(pList))
+    {
+        *fLog << err << "Error - PreProcessing MReadMarsFile::fRun... aborting." << endl;
+        return kFALSE;
+    }
+
+    // Check if really one file conatains one RunHeader
+    // (FIXME: Do the check more properly)
+    if ((Int_t)fRun->GetEntries() < fRun->GetNumFiles())
+    {
+        *fLog << err << "Error - Number of files exceeds number of RunHeaders... aborting." << endl;
+        return kFALSE;
+    }
+
+    if ((Int_t)fRun->GetEntries() > fRun->GetNumFiles())
+    {
+        *fLog << err << "Error - Number of RunHeaders exceeds number of files... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRun->SetEventNum(0); 
+    const Int_t rc = fRun->Process();
+    if (rc!=kTRUE)
+    {
+        *fLog << err << "ERROR - Cannot read runheaders of first file.";
+        *fLog << " (MReadTree::Process() returned rc=" << rc << ")" << endl;
+        return kFALSE;
+    }
+
+    return MReadTree::PreProcess(pList);
+}
Index: branches/Mars_McMismatchStudy/mfileio/MReadMarsFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadMarsFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadMarsFile.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MReadMarsFile
+#define MARS_MReadMarsFile
+
+#ifndef MARS_MReadTree
+#include "MReadTree.h"
+#endif
+
+class MParList;
+class MTaskList;
+
+class MReadMarsFile : public MReadTree
+{
+private:
+    MReadTree *fRun;
+    MParList  *fParList;  //! Parlist for reinitialization
+
+    Bool_t Notify();
+
+    Int_t PreProcess(MParList *pList);
+  
+public:
+    MReadMarsFile();
+    MReadMarsFile(const char *treename, const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MReadMarsFile();
+
+    static Byte_t IsFileValid(const char *name);
+
+    void SortFiles();
+
+    Int_t AddFile(const char *fname, Int_t entries=-1);
+
+    Bool_t Rewind() { if (fRun) fRun->Rewind(); MReadTree::Rewind(); return kTRUE; }
+
+    ClassDef(MReadMarsFile, 1)	// Reads a tree from file(s) and the information from the 'RunHeader'-tree
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MReadReports.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadReports.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadReports.cc	(revision 17960)
@@ -0,0 +1,496 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 fTrees;
+    delete fChains;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of entries in all trees.
+//
+UInt_t MReadReports::GetEntries()
+{
+    UInt_t n=0;
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+        n += tree->GetEntries();
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// In case of a Master Tree GetFileName() of the MReadMarsFile is returned.
+// If no master is available "<MReadReports>" is returned.
+//
+TString MReadReports::GetFullFileName() const
+{
+    if (!TestBit(kHasMaster))
+        return "<MReadReports>";
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+        if (tree->InheritsFrom("MReadMarsFile"))
+            return tree->GetFileName();
+
+    return "<n/a>";
+
+}
+
+void MReadReports::AddToBranchList(const char *name)
+{
+    MTask::AddToBranchList(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Schedule the contents of this tree for reading. As a default the time
+// branch which is used for the ordering is assumed to by "MTime"+tree.
+// If this is not the case you can overwrite the default specifying the
+// name in time.
+//
+// All calls to AddTree _must_ be BEFORE the calls to AddFile!
+//
+// To be done: A flag(?) telling whether the headers can be skipped.
+//
+void MReadReports::AddTree(const char *tree, const char *time, Type_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==kMaster && TestBit(kHasMaster))
+    {
+        *fLog << warn << GetDescriptor() << " already has a master tree... ignored." << endl;
+        master = kStandard;
+    }
+
+    MReadTree *t = master==kMaster ? new MReadMarsFile(tree) : new MReadTree(tree);
+    t->SetName(tree);
+    t->SetTitle(time?time:"");
+    if (master==kMaster)
+        SetBit(kHasMaster);
+    if (master==kRequired)
+        t->SetBit(kIsRequired);
+
+    if (!fEnableAutoScheme)
+        t->DisableAutoScheme();
+
+    //FIXME!
+    //t->DisableAutoScheme();
+
+    fTrees->AddToList(t);
+    //    return kTRUE;
+}
+
+MReadTree *MReadReports::GetReader(const char *tree) const
+{
+    return (MReadTree*)fTrees->FindObject(tree);
+}
+
+// --------------------------------------------------------------------------
+//
+// Schedule a file or several files (using widcards) for reading.
+//
+// All calls to AddTree _must_ be BEFORE the calls to AddFile!
+//
+Int_t MReadReports::AddFile(const char *fname, Int_t entries)
+{
+    Int_t n=0;
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+        n += tree->AddFile(fname, entries);
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Count the number of required trees and store the number if fNumRequired.
+// Reset the kIsProcessed bit.
+//
+void MReadReports::ForceRequired()
+{
+    fNumRequired = 0;
+
+    TIter Next(fTrees->GetList());
+    TObject *o=0;
+    while ((o=Next()))
+        if (o->TestBit(kIsRequired))
+        {
+            o->ResetBit(kIsProcessed);
+            fNumRequired++;
+        }
+
+    *fLog << dbg << "Number of required trees: " << fNumRequired << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Find MTaskList and store a pointer to it in fList.
+// Delete all entries in fChains.
+// Create all chains to read the time in the trees in advance.
+// Enable only the time-branch in this chains.
+// PreProcess fTrees (a MTaskList storing MReadTree tasks for reading)
+//
+Int_t MReadReports::PreProcess(MParList *plist)
+{
+    fChains->Delete();
+
+    Int_t i=0;
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+    {
+        if (!((TChain*)tree->fChain)->GetFile())
+        {
+            *fLog << warn << "No files or no tree '" << tree->GetName() << "'... skipped." << endl;
+            fTrees->RemoveFromList(tree);
+            continue;
+        }
+
+        if (tree->GetEntries()==0)
+        {
+            *fLog << warn << "No events in tree '" << tree->GetName() << "'... skipped." << endl;
+            fTrees->RemoveFromList(tree);
+            continue;
+        }
+
+        TString tn(tree->GetTitle());
+        if (tn.IsNull())
+        {
+            tn += "MTime";
+            tn += tree->GetName();
+            tn += ".";
+        }
+
+        TString tn2(tn);
+        tn2 += "*";
+
+        // FIXME: Should be tree->AddToBranchList such that
+        //        each run a new 'table' is created, but
+        //        MRead is searching for MTaskList in the
+        //        parameter list.
+        //AddToBranchList((const char*)tn2);
+
+        //
+        // SetBranchStatus wants to have a pointer to a pointer
+        //
+        MTime **tx = new MTime*;
+        *tx = 0;//new MTime;
+
+        TChain *c=new TChain(tree->GetName());
+
+        c->SetBranchStatus("*", 0);
+        c->SetBranchAddress(tn, tx);
+        c->SetBranchStatus(tn2, 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);
+    fPosEntry.Reset();
+
+    // Force that with the next call to Process the required events are read
+    ForceRequired();
+    //fFirstReInit=kTRUE;
+
+    // Preprocess all tasks in fTrees
+    return fTrees->CallPreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// If this is not the first ReInit after PreProcess force the required
+// trees to be read first (call FirstRequired())
+//
+/*
+Bool_t MReadReports::ReInit(MParList *plist)
+{
+    if (!fFirstReInit)
+        ForceRequired();
+    fFirstReInit=kFALSE;
+    return kTRUE;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Return the number of the tree which is the next one to be read.
+// The condition for this decision is the time-stamp.
+//
+Int_t MReadReports::FindNextTime()
+{
+    TIter NextC(fChains);
+    TChain *c=0;
+
+    Int_t nmin=0;
+    MTime tmin(**GetTime((TChain*)NextC()));
+
+    Int_t i=0;
+
+    while ((c=(TChain*)NextC()))
+    {
+        MTime &t = **GetTime(c);
+        i++;
+
+        if (t >= tmin)
+            continue;
+
+        tmin = t;
+        nmin = i;
+    }
+    return nmin;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of the tree which is the next one to be read.
+// The condition for this decision kIsRequired but not kIsProcessed is set.
+//
+Int_t MReadReports::FindNextRequired()
+{
+    Int_t n = 0;
+
+    TIter Next(fTrees->GetList());
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        if (o->TestBit(kIsRequired) && !o->TestBit(kIsProcessed))
+        {
+            o->SetBit(kIsProcessed);
+            fNumRequired--;
+            *fLog << dbg << "Reading from tree " << n << " " << o->GetName() << endl;
+            return n;
+        }
+        n++;
+    }
+
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the MTime corresponding to this TChain...
+//
+MTime** MReadReports::GetTime(TChain *c) const
+{
+    TChainElement *e=(TChainElement*)c->GetStatus()->At(1);
+    return (MTime**)e->GetBaddress();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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())
+    {
+        // Find the next tree to read from checking the time-stamps
+        // of the next events which would be read
+        const Int_t nmin=FindNext();
+        if (nmin<0)
+        {
+            *fLog << err << "MReadReports::Process: ERROR - Determination of next tree failed... abort." << endl;
+            return kERROR;
+        }
+
+        // Read the event from this tree
+        MTask *task = static_cast<MTask*>(fTrees->GetList()->At(nmin));
+        const Int_t rc = task->CallProcess();
+
+        // Read the time-stamp of the next event
+        TChain *chain = static_cast<TChain*>(fChains->At(nmin));
+        const Int_t cnt = chain->GetEntry(++fPosEntry[nmin]);
+
+        // In case there is no further time-stamp of an error reading the
+        // event we remove this time-stamp from the list of time-stamps to
+        // be checked for reading the next events, because there is none.
+        if (cnt<=0 || rc==kFALSE)
+        {
+            *fLog << inf << "Removing chain " << chain->GetName() << " from list" << flush;
+
+            // Find index of chain to be removed
+            const Int_t idx = fChains->IndexOf(chain);
+            *fLog << " (" << idx << ")" << flush;
+
+            delete *GetTime(chain);        // Delete MTime*
+            *fLog << "." << flush;
+            delete fChains->Remove(chain); // Remove chain from TList
+            *fLog << "." << flush;
+
+            // Change array accordingly
+            if (fPosEntry.GetSize()>1)
+            {
+                for (int i=idx; i<fPosEntry.GetSize()-1; i++)
+                    fPosEntry[i] = fPosEntry[i+1];
+                fPosEntry[fPosEntry.GetSize()-1] = 0;
+            }
+
+            // FIXME: Maybe MTaskList should have a member function to
+            //        reorder the tasks?
+
+            // Move this task to the end of the list so that nmin still
+            // corresponds to the correct task in the list.
+            const_cast<TList*>(fTrees->GetList())->Remove(task);
+            *fLog << "." << flush;
+            const_cast<TList*>(fTrees->GetList())->AddLast(task);
+            *fLog << "done." << endl;
+        }
+
+        // If something else than kFALSE (means: stop reading from this
+        // tree) has happened we return the return code of the processing
+        if (rc!=kFALSE)
+            return rc;
+    }
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PostProcess all MReadTree tasks in fTrees.
+//
+Int_t MReadReports::PostProcess()
+{
+    return fTrees->CallPostProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+// PrintStatistics of this task and of the MReadTree tasks in fTress
+//
+void MReadReports::PrintStatistics(const Int_t lvl, Bool_t title, Double_t time) const
+{
+    MRead::PrintStatistics(lvl, title, time);
+    fTrees->PrintStatistics(lvl+1, title, GetCpuTime());
+}
Index: branches/Mars_McMismatchStudy/mfileio/MReadReports.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadReports.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadReports.h	(revision 17960)
@@ -0,0 +1,78 @@
+#ifndef MARS_MReadReports
+#define MARS_MReadReports
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class TChain;
+class MTime;
+class MTaskList;
+class MReadTree;
+
+class MReadReports : public MRead
+{
+public:
+    enum Type_t {
+        kStandard,
+        kMaster,
+        kRequired
+    };
+
+private:
+    MTaskList *fTrees;    // Hold the trees which are scheduled for reading
+    TList     *fChains;   // Hold TChains to read the times in advance
+
+    TArrayL    fPosEntry; // Store the position in each tree/chain
+    TArrayL    fPosTree;  // Number of Tree in file.
+
+    Bool_t     fEnableAutoScheme;
+    Int_t      fNumRequired;
+    //Bool_t     fFirstReInit;
+
+    void    ForceRequired();
+    MTime** GetTime(TChain *c) const;
+    Int_t   FindNextTime();
+    Int_t   FindNextRequired();
+    Int_t   FindNext() { return fNumRequired==0 ? FindNextTime() : FindNextRequired(); }
+
+    UInt_t  GetEntries();
+    TString GetFullFileName() const;
+
+    //Bool_t  ReInit(MParList *plist);
+    Int_t   PreProcess(MParList *plist);
+    Int_t   Process();
+    Int_t   PostProcess();
+
+    enum {
+        kHasMaster   = BIT(14),
+        kIsRequired  = BIT(22),
+        kIsProcessed = BIT(23)
+    };
+
+public:
+    MReadReports(); 
+    ~MReadReports(); 
+
+    void  AddTree(const char *tree, const char *time=NULL, Type_t master=kStandard);
+    void  AddTree(const char *tree, Type_t master)
+    {
+        AddTree(tree, NULL, master);
+    }
+    Int_t AddFile(const char *fname, Int_t entries=-1);
+    void  AddToBranchList(const char *name);
+
+    void  PrintStatistics(const Int_t lvl=0, Bool_t title=kFALSE, Double_t time=0) const;
+
+    void  EnableAutoScheme(Bool_t e=kTRUE) { fEnableAutoScheme = e; } // Must be called BEFORE AddTree!
+
+    MReadTree *GetReader(const char *tree) const;
+
+    ClassDef(MReadReports, 0) // Reads events and reports from a root file ordered in time
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MReadRflFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadRflFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadRflFile.cc	(revision 17960)
@@ -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, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadRflFile
+//
+// Reads a output file of the reflector program
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadRflFile.h"
+
+#include "structures_rfl.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MZlib.h"
+
+#include "MParList.h"
+
+#include "MRflEvtData.h"
+#include "MRflEvtHeader.h"
+#include "MRflRunHeader.h"
+#include "MRflSinglePhoton.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);
+    }
+    else
+    {
+        RflEventHeader revth;
+        fIn->read((char*)&revth, sizeof(RflEventHeader));
+        fEvtHeader->SetEvtNumber((int)revth.EvtNumber);
+        fEvtHeader->SetEnergy((int)revth.Etotal);
+        fEvtHeader->SetMomentum(revth.p[0], revth.p[1], revth.p[2]);
+        fEvtHeader->SetCorePosition(revth.CorePos[0][0], revth.CorePos[1][0]);
+        
+        fEvtHeader->SetHeightFirstInt((Float_t)revth.zFirstInt);
+
+        fEvtHeader->SetPhi((Float_t)revth.telescopePhi);
+        fEvtHeader->SetTheta((Float_t)revth.telescopeTheta);
+
+        fEvtHeader->SetNmax((Float_t)revth.longi_Nmax);
+        fEvtHeader->SetT0((Float_t)revth.longi_t0);
+        fEvtHeader->SetTmax((Float_t)revth.longi_tmax);
+        fEvtHeader->SetChi2((Float_t)revth.longi_chi2);
+
+        fEvtHeader->SetEFraction((Float_t)revth.elec_cph_fraction);
+        fEvtHeader->SetMFraction((Float_t)revth.muon_cph_fraction);
+        fEvtHeader->SetOFraction((Float_t)revth.other_cph_fraction);
+    }
+
+    return (bool)*fIn;
+}
+
+int MReadRflFile::ReadFlag()
+{
+    char flag[SIZE_OF_FLAGS];
+    fIn->read(flag, SIZE_OF_FLAGS);
+
+    if (!fIn)
+        return kError;
+
+    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;
+
+                // FIXME: fRunHeader->Read(fIn);
+                //        fRunHeader->Print();
+
+                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;
+                *fLog << " Energy Range:  " << rrunh.ELowLim << "GeV to " << rrunh.EUppLim << "GeV" << endl;
+                *fLog << " Energy Slope:  " << rrunh.SlopeSpec << endl;
+                *fLog << " Wobble Mode:   " << rrunh.wobble_mode << endl;
+                *fLog << " Atm. Model:    " << rrunh.atmospheric_model << endl;
+                // *fLog << " Theta Range:   " << rrunh.ThetaMin << "deg to " << rrunh.ThetaMax << "deg" << endl;
+                // *fLog << " Phi Range:     " << rrunh.PhiMin << "deg to " << rrunh.PhiMax << "deg" << endl;
+                // *fLog << " View Cone Rad: " << rrunh.ViewconeRadius << "deg" << endl;
+                break;
+            }
+
+            *fLog << err << "Error! found end of file... But no EOF flag. Exiting." << endl;
+            return kError;
+        }/*
+        else
+        {
+            *fLog << err << "ERROR - Reflector versions <= 0.5 are not supported!" << 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::ReadEvent()
+{
+    for (;;)
+    {
+        switch (EvalFlag())
+        {
+        case kError:
+            return kFALSE;
+
+        case kEndOfFile:
+            Close();
+            return kCONTINUE; // FIXME: CHECK
+//            if (!OpenNextFile())
+//                return kFALSE;
+            /* FALLTHROU */
+        case kStartOfRun:
+        case kEndOfRun:
+            continue;
+
+        case kStartOfEvtData:
+            break;
+        }
+        break;
+    }
+
+    if (!ReadEvtHeader())
+        return kFALSE;
+
+    return ReadEvtData();
+}
+
+/*
+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;
+
+    return MReadFiles::PreProcess(plist);
+}
+
+Bool_t MReadRflFile::ReadHeader()
+{
+    fCurrentVersion = ReadVersion();
+    if (fCurrentVersion<0)
+    {
+        *fLog << err << "ERROR reading signature." << endl;
+        return kFALSE;
+    }
+    *fLog << inf << "Version " << fCurrentVersion << endl << endl;
+
+    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) : MReadFiles(fname, name, title)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Reads a Reflector output file";
+}
+
+Bool_t MReadRflFile::SearchFor(Int_t runno, Int_t eventno)
+{
+    if (!fEvtHeader)
+        return kFALSE;
+
+    Rewind();
+
+    while (1)
+    {
+        fEvtData->Reset();
+        if (!Process())
+            return kFALSE;
+
+        if (fEvtHeader->GetEvtNumber()==eventno &&
+            fRunHeader->GetRunNumber()==runno)
+            return kTRUE;
+    }
+
+    Close();
+}
Index: branches/Mars_McMismatchStudy/mfileio/MReadRflFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadRflFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadRflFile.h	(revision 17960)
@@ -0,0 +1,55 @@
+#ifndef MARS_MReadRflFile
+#define MARS_MReadRflFile
+
+#ifndef MARS_MReadFiles
+#include "MReadFiles.h"
+#endif
+
+class MRflEvtData;
+class MRflEvtHeader;
+class MRflRunHeader;
+
+class MReadRflFile : public MReadFiles
+{
+private:
+    enum {
+        kError,
+        kEndOfFile,
+        kStartOfRun,
+        kEndOfRun,
+        kStartOfEvtData,
+        kEndOfEvtData,
+        kUndefined
+    };
+
+    MRflEvtData   *fEvtData;    //!
+    MRflEvtHeader *fEvtHeader;  //!
+    MRflRunHeader *fRunHeader;  //!
+
+    Float_t fCurrentVersion;    //! Version of currently open rfl file
+
+    // MReadRflFile
+    float  ReadVersion();
+    Bool_t ReadEvtHeader();
+    Bool_t ReadEvtData();
+    int    ReadFlag();
+    Bool_t FlagIsA(const  char *s1, const char *flag);
+    Int_t  EvalFlag();
+
+    // MReadFiles
+    Int_t  ReadEvent();
+    Bool_t ReadHeader();
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+
+public:
+    MReadRflFile(const char *filename=NULL, const char *name=NULL,
+                 const char *title=NULL);
+
+    Bool_t SearchFor(Int_t runno, Int_t eventno);
+
+    ClassDef(MReadRflFile, 0) // Reads reflector files
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MReadScanFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadScanFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadScanFile.cc	(revision 17960)
@@ -0,0 +1,232 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 7/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadFiles
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadScanFile.h"
+
+#include <stdlib.h> // atoi (Ubuntu 8.10)
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParameters.h"
+#include "MParList.h"
+
+ClassImp(MReadScanFile);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Check if str only contains '*'
+//
+Bool_t MReadScanFile::IsDelimiter(const TString &str) const
+{
+    const char *end = str.Data()+str.Length()+1;
+    char const *ptr = str.Data();
+
+    while (*ptr++=='*');
+
+    if (ptr==end)
+        return kTRUE;
+
+    *fLog << err << "ERROR - Synatx error in line " << GetNumLine() << "... delimiter expected." << endl;
+    *fLog << "'" << str << "'" << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a line, check if it is a delimiter line and check its length.
+//
+Bool_t MReadScanFile::ReadDelimiter()
+{
+    TString str;
+    if (!ReadLine(str))
+        return kFALSE;
+    if (!IsDelimiter(str))
+        return kFALSE;
+
+    return kTRUE;
+
+/*
+
+    if (fLength<0)
+        fLength = str.Length();
+
+    if (fLength==str.Length())
+        return kTRUE;
+
+    *fLog << err << "ERROR - Delimiter line " << GetNumLine() << " has wrong length." << endl;
+    return kFALSE;
+    */
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the header. Do some action if necessary. Leave the stream pointer
+// behind the header.
+//
+Bool_t MReadScanFile::ReadHeader()
+{
+    if (!ReadDelimiter())
+        return kFALSE;
+
+    // FIXME: Check header here
+    TString str;
+    if (!ReadLine(str))
+        return kFALSE;
+    cout << str << endl;
+
+    if (!ReadDelimiter())
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Int_t MReadScanFile::ReadEvent()
+{
+    // If end-of-file go on reading next event in next file
+    TString str;
+    if (!ReadLine(str))
+        return Process();
+/*
+    if (fLength!=str.Length())
+    {
+        *fLog << err << "ERROR - Line " << GetNumLine() << " has wrong length." << endl;
+        return kERROR;
+    }
+ */
+    // Line is not properly formatted by TTree::Scan
+    if (str[0]!='*')
+    {
+        *fLog << err << "Line " << GetNumLine() << " doens't start with a '*'" << endl;
+        return kERROR;
+    }
+
+    // Line is the delimiter at the end of the file
+    // FIXME: Could we concatenate files here into one file?!
+    if (str[1]=='*')
+        return IsDelimiter(str) ? Process() : kERROR;
+
+    // Read and interpete the data
+    const char *end = str.Data()+str.Length();
+    char const *ptr = str.Data()+1;
+
+    TIter Next (&fList);
+    MParameterD *d = 0;
+
+    while (ptr && ptr<end)
+    {
+        // We have more columns in the file than conatiners
+        d = static_cast<MParameterD*>(Next());
+        if (!d)
+        {
+            *fLog << err << "Line " << GetNumLine() << " has too many fields." << endl;
+            return kERROR;
+        }
+
+        // set interpreted value
+        d->SetVal(atof(ptr));
+
+        // go on with the next column
+        ptr = strchr(ptr, '*')+1;
+    }
+
+    // we didn't find enough columns
+    if (ptr<end)
+    {
+        *fLog << err << "Line " << GetNumLine() << " has too less fields." << endl;
+        return kERROR;
+    }
+
+    // everything's ok
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Analyzse the header. Starts reading at the beginning of the file.
+// Leaves the stream pointer at the end of the header.
+// Add needed MParContainers to parlist or check for them.
+//
+Bool_t MReadScanFile::AnalyzeHeader(MParList &plist)
+{
+    fList.Clear("nodelete");
+
+    fLength = -1;
+    if (!ReadDelimiter())
+        return kFALSE;
+ 
+    TString line;
+    if (!ReadLine(line))
+        return kFALSE;
+/*
+    if (fLength!=str.Length())
+    {
+        *fLog << err << "ERROR - Line " << GetNumLine() << " has wrong length." << endl;
+        return kFALSE;
+    }
+ */
+ 
+    TObjArray *arr = line.Tokenize('*');
+
+    TIter Next(arr);
+    TObject *o = 0;
+    while ((o=Next()))
+    {
+        TString name = TString(o->GetName()).Strip(TString::kBoth);
+        name.ReplaceAll(".", "_");
+
+        MParContainer *p = plist.FindCreateObj("MParameterD", name);
+        if (!p)
+        {
+            delete arr;
+            return kFALSE;
+        }
+
+        fList.AddLast(p);
+    }
+
+    delete arr;
+
+    return ReadDelimiter();
+}
+
+Int_t MReadScanFile::PostProcess()
+{
+    fList.Clear("nodelete");
+    return kTRUE;
+}
+
+UInt_t MReadScanFile::GetEntries()
+{
+    *fLog << err << "Unkown number of entries" << endl;
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/mfileio/MReadScanFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadScanFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadScanFile.h	(revision 17960)
@@ -0,0 +1,34 @@
+#ifndef MARS_MReadScanFile
+#define MARS_MReadScanFile
+
+#ifndef MARS_MReadFiles
+#include "MReadFiles.h"
+#endif
+
+class MParList;
+
+class MReadScanFile : public MReadFiles
+{
+private:
+    TList fList;
+
+    Int_t fLength;
+
+    Bool_t IsDelimiter(const TString &str) const;
+    Bool_t ReadDelimiter();
+
+    Bool_t AnalyzeHeader(MParList &plist);
+    Bool_t ReadHeader();
+    Int_t  ReadEvent();
+    Int_t  PostProcess();
+
+public:
+    MReadScanFile(const char *filename=NULL, const char *name=NULL,
+                  const char *title=NULL) : MReadFiles(filename, name, title), fLength(-1) { }
+
+    UInt_t GetEntries();
+
+    ClassDef(MReadScanFile, 0) // Reads files written with TTree::Scan
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MReadTree.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadTree.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadTree.cc	(revision 17960)
@@ -0,0 +1,1233 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadTree
+//
+// This tasks opens all branches in a specified tree and creates the
+// corresponding parameter containers if not already existing in the
+// parameter list.
+//
+// The Process function reads one events from the tree. To go through the
+// events of one tree make sure that the event number is increased from
+// outside. It makes also possible to go back by decreasing the number.
+//
+// If you don't want to start reading the first event you have to call
+// MReadTree::SetEventNum after instantiating your MReadTree-object.
+//
+// To make reading much faster (up to a factor of 10 to 20) you can
+// ensure that only the data you are really processing is enabled by
+// calling MReadTree::UseLeaf.
+//
+// If the chain switches from one file to another file all
+// TObject::Notify() functions are called of TObject objects which were
+// added to the Notifier list view MReadTree::AddNotify. If MReadTree
+// is the owner (viw MReadTree::SetOwner) all this objects are deleted
+// by the destructor of MReadTree
+//
+//
+// ToDo:
+// -----
+//  - Auto Scheme and Branch choosing doesn't work for memory trees
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadTree.h"
+
+#include <fstream>
+
+#include <TFile.h>           // TFile::GetName
+#include <TSystem.h>         // gSystem->ExpandPath
+#include <TLeaf.h>
+#include <TChainElement.h>
+#include <TFriendElement.h>
+#include <TOrdCollection.h>
+
+#include "MChain.h"
+#include "MFilter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MParameters.h"
+#include "MParEmulated.h"
+#include "MStatusDisplay.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MReadTree);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. Use this constructor (ONLY) if you want to
+//  access a memory tree (a TTree not stored in a file) created by
+//  MWriteRootFile or manually.
+//
+MReadTree::MReadTree(TTree *tree)
+    : fNumEntry(0), fNumEntries(0), fBranchChoosing(kFALSE), fAutoEnable(kTRUE)
+{
+    fName  = "MRead";
+    fTitle = "Task to loop over all events in one single tree";
+
+    fVetoList = new TList;
+    fVetoList->SetOwner();
+
+    fNotify = new TList;
+
+    fChain = NULL;
+
+    fTree = tree;
+    SetBit(kChainWasChanged);
+
+    if (fTree)
+        fAutoEnable = kFALSE;
+    /*
+    if (!fTree)
+        return;
+
+    TIter Next(fTree->GetListOfBranches());
+    TBranch *b=0;
+    while ((b=(TBranch*)Next()))
+        b->ResetAddress();
+    */
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. It creates an TChain instance which represents the
+//  the Tree you want to read and adds the given file (if you gave one).
+//  More files can be added using MReadTree::AddFile.
+//  Also an empty veto list is created. This list is used if you want to
+//  veto (disable or "don't enable") a branch in the tree, it vetos also
+//  the creation of the corresponding object.
+//  An empty list of TObjects are also created. This objects are called
+//  at any time the TChain starts to read from another file.
+//
+MReadTree::MReadTree(const char *tname, const char *fname,
+                     const char *name, const char *title)
+    : fNumEntry(0), fNumEntries(0), fBranchChoosing(kFALSE), fAutoEnable(kTRUE)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Task to loop over all events in one single tree";
+
+    fVetoList = new TList;
+    fVetoList->SetOwner();
+
+    fNotify = new TList;
+
+    //
+    // open the input stream
+    //
+    fChain = new MChain(tname);
+    fTree = fChain;
+
+    // root 3.02:
+    // In TChain::Addfile remove the limitation that the file name must contain
+    // the string ".root". ".root" is necessary only in case one wants to specify
+    // a Tree in a subdirectory of a Root file with eg, the format:
+
+    if (fname)
+        AddFile(fname);
+}
+
+Bool_t MReadTree::IsOwned(const TChainElement &e) const
+{
+    // We cannot be the owner, because it is a basic type like Int, etc.
+    if (!e.GetBaddressIsPtr())
+        return kFALSE;
+
+    // We cannot be the owener, because there is no class
+    // we could have created
+    if (TString(e.GetBaddressClassName()).IsNull())
+        return kFALSE;
+
+    // Let's hope the best that we are the owner
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. It deletes the TChain and veto list object
+//
+MReadTree::~MReadTree()
+{
+    //
+    // Delete all the pointers to pointers to the objects where the
+    // branche data gets stored. FIXME: When PreProcessed twice this
+    // creates a memory leak!
+    //
+    if (fChain) // FIXME: MEMORY LEAK for fTree!=0
+    {
+        TIter Next(fChain->GetStatus());
+
+        // Pointers which we delete must be
+        //  1) Really pointers
+        //  2) Have a class name (belong to a loaded class)
+        TChainElement *element = NULL;
+        while ((element=(TChainElement*)Next()))
+            if (IsOwned(*element))
+                delete (void**)element->GetBaddress();
+
+        //
+        // Delete the chain and the veto list
+        //
+        delete fChain;
+    }
+
+    /* This is AND MUST be done in PostProcess. See there for more details
+    else
+    {
+        TIter Next(fTree->GetListOfBranches());
+
+        TBranch *element = NULL;
+        while ((element=(TBranch*)Next()))
+            if (element->GetAddress())
+                delete (MParContainer**)element->GetAddress();
+        }
+    */
+
+    delete fNotify;
+    delete fVetoList;
+}
+
+Byte_t MReadTree::IsFileValid(const char *name)
+{
+    ifstream fin(name);
+    if (!fin)
+        return 0;
+
+    Char_t c[4];
+    fin.read(c, 4);
+    if (!fin)
+        return 0;
+
+    return c[0]=='r'&& c[1]=='o' && c[2]=='o' && c[3]=='t' ? 1 : 0;
+}
+
+void MReadTree::GetListOfBranches(TList &list) const
+{
+    list.AddAll(fTree->GetListOfBranches());
+
+    TIter NextF(fTree->GetListOfFriends());
+    TFriendElement *e = 0;
+    while ((e=(TFriendElement*)NextF()))
+        list.AddAll(e->GetTree()->GetListOfBranches());
+}
+
+// --------------------------------------------------------------------------
+//
+// 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()
+{
+    Int_t entries = -1;
+
+    TList list;
+    GetListOfBranches(list);
+
+    TIter Next(&list);
+    TBranch *b = NULL;
+    while ((b=(TBranch*)Next()))
+    {
+        if (entries>=0 && entries!=(Int_t)b->GetEntries())
+        {
+            *fLog << err << "ERROR - File corruption detected:" << endl;
+            *fLog << "  Due to several circumstances  (such at a bug in MReadTree or wrong usgae of" << endl;
+            *fLog << "  the file  UPDATE  mode)  you may have produced a file in which at least two" << endl;
+            *fLog << "  branches have different number of  entries.  Sorry, but this combination of" << endl;
+            *fLog << "  branches, trees and files is unusable." << endl;
+            return kFALSE;
+        }
+
+        entries = (Int_t)b->GetEntries();
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the owner flag is set all TObjects which are scheduled via
+//  AddNotify are deleted by the destructor of MReadTree
+//
+void MReadTree::SetOwner(Bool_t flag)
+{
+    flag ? fNotify->SetBit(kIsOwner) : fNotify->ResetBit(kIsOwner);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function is called each time MReadTree changes the file to read
+//  from. It calls all TObject::Notify() functions which are scheduled
+//  via AddNotify.
+//
+//  For unknown reasons root stores the SetAutoDelete-Flag in
+//  a branch having a custom streamer (eg. MRawEvtData).
+//  It is not allowed that a container which is in the parameter
+//  list gets a new address. Therefor we reset all the autodel flags.
+//
+//  MAKE SURE THAT ALL YOUR CUSTOM STREAMERS TAKE CARE OF ALL MEMORY
+//
+Bool_t MReadTree::Notify()
+{
+    //
+    // Do a consistency check for all branches
+    //
+    if (!CheckBranchSize())
+        return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Next file #" << GetFileIndex();
+    *fLog << " '" << GetFileName() << "' (next evt #";
+    *fLog << GetNumEntry()-1 << ")" << endl;
+
+    if (fDisplay)
+    {
+        TString txt = GetFileName();
+        txt += " @ ";
+        txt += GetNumEntry()-1;
+        fDisplay->SetStatusLine2(txt);
+    }
+
+    //
+    // For unknown reasons root stores the SetAutoDelete-Flag in
+    // a branch having a custom streamer (eg. MRawEvtData).
+    // It is not allowed that a container which is in the parameter
+    // list gets a new address. Therefor we reset all the autodel flags.
+    //
+    // MAKE SURE THAT ALL YOUR CUSTOM STREAMERS TAKE CARE OF ALL MEMORY
+    //
+    TIter NextB(fTree->GetListOfBranches());
+    TBranch *b=0;
+    while ((b=(TBranch*)NextB()))
+        if (b->IsAutoDelete())
+        {
+            *fLog << warn << "Branch " << b->GetName() << "->IsAutoDelete() set... resetting." << endl;
+            b->SetAutoDelete(kFALSE);
+        }
+
+    if (!fNotify)
+        return kTRUE;
+
+    TIter NextN(fNotify);
+    TObject *o=NULL;
+    while ((o=NextN()))
+        if (!o->Notify())
+        {
+            *fLog << err << "Calling Notify() for object " << o->GetName() << " failed... abort." << endl;
+            return kFALSE;
+        }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If you want to read the given tree over several files you must add
+//  the files here before PreProcess is called. Be careful: If the tree
+//  doesn't have the same contents (branches) it may confuse your
+//  program (trees which are are not existing in later files are not read
+//  anymore, tree wich are not existing in the first file are never read)
+//
+//  Name may use the wildcarding notation, eg "xxx*.root" means all files
+//  starting with xxx in the current file system directory.
+//
+//  AddFile returns the number of files added to the chain.
+//
+//  For more information see TChain::Add
+//
+Int_t MReadTree::AddFile(const char *fname, Int_t entries)
+{
+    if (!fChain)
+    {
+        *fLog << err << "MReadTree::AddFile - ERROR: You cannot add a file, because MReadTree" << endl;
+        *fLog <<        "  is supposed to read its tree from memory or its default or its" << endl;
+        *fLog <<        "  default constructor was called (no tree name was given)." << endl;
+        return 0;
+    }
+
+    TString newname(fname); // char-array must overcome comming block
+    gSystem->ExpandPathName(newname);
+
+    //
+    // FIXME! A check is missing whether the file already exists or not.
+    //
+    const Int_t numfiles = fChain->Add(newname, entries<0?TChain::kBigNumber:entries);
+
+    //TIter Next(fChain->GetListOfFriends());
+    //TFriendElement *el = 0;
+    //while ((el=(TFriendElement*)Next()))
+    //    static_cast<TChain*>(el->GetTree())->Add(newname, entries<0?TChain::kBigNumber:entries);
+
+    if (numfiles>0)
+    {
+        SetBit(kChainWasChanged);
+        if (numfiles>1)
+            *fLog << inf3 << GetDescriptor() << ": Added " << fname << " <" << numfiles << ">" << endl;
+    }
+    else
+        *fLog << warn << GetDescriptor() << ": WARNING - No files found at " << newname << endl;
+
+    return numfiles;
+}
+
+Bool_t MReadTree::AddFriend(TChain &c)
+{
+//    if (!fChain)
+//    {
+//        *fLog << err << "MReadTree::AddFriend - ERROR: You cannot add a friend, because MReadTree" << endl;
+//        *fLog <<        "  is supposed to read its tree from memory or its default or its" << endl;
+//        *fLog <<        "  default constructor was called (no tree name was given)." << endl;
+//        return 0;
+//    }
+
+    return fChain->AddFriend(&c, "")!=0;
+}
+
+/*
+ // --------------------------------------------------------------------------
+ //
+ //
+ Int_t MReadTree::AddFile(const TChainElement &obj)
+ {
+     return AddFile(obj.GetTitle(), obj.GetEntries());
+ }
+*/
+
+// --------------------------------------------------------------------------
+//
+// Adds all files from another MReadTree to this instance
+//
+// Returns the number of file which were added
+//
+Int_t MReadTree::AddFiles(const MReadTree &read)
+{
+    if (!fChain)
+    {
+        *fLog << err << "MReadTree::AddFiles - ERROR: You cannot add a file, because MReadTree" << endl;
+        *fLog <<        "                             handles a memory based tree or its default" << endl;
+        *fLog <<        "                             constructor was called." << endl;
+        return 0;
+    }
+
+    const Int_t rc = fChain->Add(read.fChain);
+
+    if (rc>0)
+        SetBit(kChainWasChanged);
+
+    /*
+     Int_t rc = 0;
+
+     TIter Next(read.fChain->GetListOfFiles());
+     TObject *obj = NULL;
+     while ((obj=Next()))
+         rc += AddFile(*(TChainElement*)obj);
+    */
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Sort the files by their file-names
+//
+void MReadTree::SortFiles()
+{
+    if (fChain)
+        fChain->GetListOfFiles()->Sort();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function is called if Branch choosing method should get enabled.
+//  Branch choosing means, that only the enabled branches are read into
+//  memory. To use an enableing scheme we have to disable all branches first.
+//  This is done, if this function is called the first time.
+//
+void MReadTree::EnableBranchChoosing()
+{
+    if (fBranchChoosing)
+        return;
+
+    *fLog << inf << GetDescriptor() << ": Branch choosing enabled (only enabled branches are read)." << endl;
+    fTree->SetBranchStatus("*", kFALSE); // *CHANGED-fChain-to-fTree*
+    fBranchChoosing = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The first time this function is called all branches are disabled.
+// The given branch is enabled. By enabling only the branches you
+// are processing you can speed up your calculation many times (up to
+// a factor of 10 or 20)
+//
+void MReadTree::EnableBranch(const char *name)
+{
+    if (!fChain)
+    {
+        *fLog << warn << "MReadTree::EnableBranch - WARNING: EnableBranch doesn't work with memory based trees... ignored." << endl;
+        return;
+    }
+
+    if (fChain->GetListOfFiles()->GetEntries()==0)
+    {
+        *fLog << err << "Chain contains no file... Branch '";
+        *fLog << name << "' ignored." << endl;
+        return;
+    }
+
+    EnableBranchChoosing();
+
+    TNamed branch(name, "");
+    SetBranchStatus(&branch, kTRUE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set branch status of branch name
+//
+void MReadTree::SetBranchStatus(const char *name, Bool_t status)
+{
+    fTree->SetBranchStatus(name, status); // *CHANGED-fChain-to-fTree*
+
+    *fLog << inf << (status ? "Enabled" : "Disabled");
+    *fLog << " subbranch '" << name << "'." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether a branch with the given name exists in the chain
+// and sets the branch status of this branch corresponding to status.
+//
+void MReadTree::SetBranchStatus(TObject *branch, Bool_t status)
+{
+    //
+    // Get branch name
+    //
+    const char *name = branch->GetName();
+
+    //
+    // Check whether this branch really exists
+    //
+    TString bn(name);
+    if (bn.EndsWith("*"))
+        bn.Remove(bn.Length()-1);
+
+    if (fTree->GetBranch(bn)) // *CHANGED-fChain-to-fTree*
+        SetBranchStatus(name, status);
+
+    //
+    // Remove trailing '.' if one and try to enable the subbranch without
+    // the master branch name. This is to be compatible with older mars
+    // and camera files.
+    //
+    const char *dot = strrchr(name, '.');
+    if (!dot)
+        return;
+
+    if (fTree->GetBranch(dot+1)) // *CHANGED-fChain-to-fTree*
+        SetBranchStatus(dot+1, status);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the status of all branches in the list to status.
+//
+void MReadTree::SetBranchStatus(const TList *list, Bool_t status)
+{
+    //
+    // Loop over all subbranches in this master branch
+    //
+    TIter Next(list);
+
+    TObject *obj;
+    while ((obj=Next()))
+        SetBranchStatus(obj, status);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is the implementation of the Auto Enabling Scheme.
+//  For more information see MTask::AddBranchToList.
+//  This function loops over all tasks and its filters in the tasklist
+//  and enables all branches which are requested by the tasks and its
+//  filters.
+//
+//  To enable 'unknown' branches which are not in the branchlist of
+//  the tasks you can call EnableBranch
+//
+void MReadTree::EnableBranches(MParList *plist)
+{
+    //
+    // check whether branch choosing must be switched on
+    //
+    EnableBranchChoosing();
+
+    //
+    // request the tasklist from the parameter list.
+    // FIXME: Tasklist can have a different name
+    //
+    const MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << warn << GetDescriptor() << "Cannot use auto enabeling scheme for branches. 'MTaskList' not found." << endl;
+        return;
+    }
+
+    //
+    // This loop is not necessary. We could do it like in the commented
+    // loop below. But this loop makes sure, that we don't try to enable
+    // one branch several times. This would not harm, but we would get
+    // an output for each attempt. To have several outputs for one subbranch
+    // may confuse the user, this we don't want.
+    // This loop creates a new list of subbranches and for each branch
+    // which is added we check before whether it already exists or not.
+    //
+    TList list;
+
+    MTask *task;
+    TIter NextTask(tlist->GetList());
+    while ((task=(MTask*)NextTask()))
+    {
+        TObject *obj;
+
+        TIter NextTBranch(task->GetListOfBranches());
+        while ((obj=NextTBranch()))
+            if (!list.FindObject(obj->GetName()))
+                list.Add(obj);
+
+        const MFilter *filter = task->GetFilter();
+
+        if (!filter)
+            continue;
+
+        TIter NextFBranch(filter->GetListOfBranches());
+        while ((obj=NextFBranch()))
+            if (!list.FindObject(obj->GetName()))
+                list.Add(obj);
+    }
+
+    SetBranchStatus(&list, kTRUE);
+/*
+    //
+    // Loop over all tasks iand its filters n the task list.
+    //
+    MTask *task;
+    TIter NextTask(tlist->GetList());
+    while ((task=(MTask*)NextTask()))
+    {
+        SetBranchStatus(task->GetListOfBranches(), kTRUE);
+
+        const MFilter *filter = task->GetFilter();
+        if (!filter)
+           continue;
+
+        SetBranchStatus(filter->GetListOfBranches(), kTRUE);
+
+    }
+*/
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the chain has been changed (by calling AddFile or using a file
+//  in the constructors argument) the number of entries is newly
+//  calculated from the files in the chain - this may take a while.
+//  The number of entries is returned.
+//
+UInt_t MReadTree::GetEntries()
+{
+    if (TestBit(kChainWasChanged))
+    {
+        // *CHANGED-fChain-to-fTree*
+        *fLog << inf << "Scanning chain " << fTree->GetName() << "... " << flush;
+        fNumEntries = (UInt_t)fTree->GetEntries();
+        *fLog << fNumEntries << " events found." << endl;
+        ResetBit(kChainWasChanged);
+    }
+    return fNumEntries==TChain::kBigNumber ? 0 : fNumEntries;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The disables all subbranches of the given master branch.
+//
+void MReadTree::DisableSubBranches(TBranch *branch)
+{
+    //
+    // This is not necessary, it would work without. But the output
+    // may confuse the user...
+    //
+    if (fAutoEnable || fBranchChoosing)
+        return;
+
+    SetBranchStatus(branch->GetListOfBranches(), kFALSE);
+}
+
+MParContainer *MReadTree::FindCreateObj(MParList &plist, const char *cname, const char *name)
+{
+    MParContainer *pcont=plist.FindCreateObj(cname, name);
+    if (!pcont)
+    {
+        //
+        // if class is not existing in the (root) environment
+        // we cannot proceed reading this branch
+        //
+        *fLog << err << dbginf << "ERROR - Class '" << cname;
+        *fLog << "' for " << name << " not existing in dictionary. Branch skipped." << endl;
+        return 0;
+    }
+
+    fParList.Add(pcont);
+    return pcont;
+}
+
+void *MReadTree::GetParameterPtr(MParList &plist, const TString &name, const char *parname)
+{
+    if (name=="Int_t"   || name=="UInt_t"   ||
+        name=="Short_t" || name=="UShort_t" ||
+        name=="Char_t"  || name=="UChar_t"  ||
+        name=="Bool_t")
+    {
+        MParameterI *par = (MParameterI*)FindCreateObj(plist, "MParameterI", parname);
+        return par ? par->GetPtr() : 0;
+    }
+
+    if (name=="Float_t" || name=="Double_t")
+    {
+        MParameterD *par = (MParameterD*)FindCreateObj(plist, "MParameterD", parname);
+        return par ? par->GetPtr() : 0;
+    }
+
+    // MParContainer **pcont= new MParContainer*;
+    // return FindCreateObj(plist, name, parname);
+
+    MParEmulated *par = (MParEmulated*)FindCreateObj(plist, "MParEmulated", parname);
+    if (!par)
+        return 0;
+
+    par->SetClassName(name);
+    return par->GetPtr();
+}
+
+Bool_t MReadTree::SetBranchAddress(TBranch &b, void *ptr, const char *prefix, const char *type)
+{
+    if (!ptr)
+    {
+        DisableSubBranches(&b);
+        return kFALSE;
+    }
+
+    if (fChain)
+    {
+        TChainElement *element = (TChainElement*)fChain->GetStatus()->FindObject(b.GetName());
+        if (element && IsOwned(*element))
+            *fLog << warn << "WARNING - Branch address for " << b.GetName() << " was already setup by the user." << endl;
+    }
+
+    const TString bname = b.GetName();
+    const TString cname = type ? type : b.GetClassName();
+
+    fTree->SetBranchAddress(bname, ptr);
+
+    *fLog << inf2 << prefix << " address '" << bname << "' ";
+    if (bname!=cname)
+        *fLog << "[" << cname << "] ";
+    *fLog << "setup for reading." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The PreProcess loops (till now) over the branches in the given tree.
+//  It checks if the corresponding containers (containers with the same
+//  name than the branch name) are existing in the Parameter Container List.
+//  If not, a container of objec type 'branch-name' is created (everything
+//  after the last semicolon in the branch name is stripped). Only
+//  branches which don't have a veto (see VetoBranch) are enabled If the
+//  object isn't found in the root dictionary (a list of classes known by the
+//  root environment) the branch is skipped and an error message is printed
+//  out.
+//  If a selector is specified it is preprocessed after the
+//  MReadTree::PreProcess
+//
+Int_t MReadTree::PreProcess(MParList *pList)
+{
+    fTaskList = (MTaskList*)pList->FindObject("MTaskList");
+    if (!fTaskList)
+        *fLog << warn << "WARNING - Standard tasklist MTaskList not found... ignoring Stream-ID." << endl;
+
+    if (!fTree || !fChain)
+    {
+        *fLog << err << "ERROR - Something went terribly wrong!" << endl;
+        *fLog <<        "        Maybe you called the default constructor?" << endl;
+        *fLog <<        "        Did you forget to give a tree name in the constructor?" << endl;
+        return kFALSE;
+    }
+
+    //
+    // Make sure, that all the following calls doesn't result in
+    // Notifications. This may be dangerous, because the notified
+    // tasks are not preprocessed.
+    //
+    fTree->SetNotify(NULL); //*CHANGED-fChain-to-fTree*
+
+    //
+    // It seems, that TFile and TTree are not completely independant if
+    // many times the same file is opened (MReadReports) and some of
+    // the files in the chains don't have one tree. TChain::fTreeNumber
+    // is already set before LoadTree from GetFile is called and
+    // it crashes. ResetTree makes sure, that the tree number is -1
+    //
+    if (fChain) // *CHANGED-fChain-to-fTree*
+        fChain->ResetTree();
+    // Maybe this would be enough, but the above might be safer...
+    //if (fChain->GetTreeNumber()==0)
+    //    fChain->ResetTree();
+
+    //
+    // check for files and for the tree!
+    //
+    if (fChain && !fChain->GetFile()) // *CHANGED-fChain-to-fTree*
+    {
+        *fLog << err << GetDescriptor() << ": No file or no tree with name " << fChain->GetName() << " in file." << endl;
+        return kFALSE;
+    }
+
+    //
+    // get number of events in this tree
+    //
+    if (!GetEntries())
+    {
+        *fLog << err << GetDescriptor() << ": No entries found in file(s)" << endl;
+        return kFALSE;
+    }
+
+    //
+    // output logging information
+    //
+    *fLog << inf << fNumEntries << " entries found in file(s)." << endl;
+
+    // Get all branches of this tree and all friends
+    TList blist;
+    GetListOfBranches(blist);
+
+    //
+    // Get all branches of this tree and
+    // create the Iterator to loop over all branches
+    //
+    TIter Next(&blist); // *CHANGED-fChain-to-fTree*
+    TBranch *branch=NULL;
+
+    Int_t num=0;
+
+    //
+    // loop over all tasks for processing
+    //
+    while ( (branch=(TBranch*)Next()) )
+    {
+        //
+        // Get Name of Branch and Object
+        //
+        const char *bname = branch->GetName();
+
+        TString oname(bname);
+        if (oname.EndsWith("."))
+            oname.Remove(oname.Length()-1);
+
+        //
+        // Check if enabeling the branch is allowed
+        //
+        if (fVetoList->FindObject(oname))
+        {
+            *fLog << inf << "Master branch " << bname << " has veto... skipped." << endl;
+            DisableSubBranches(branch);
+            continue;
+        }
+
+        // Branch already setup/ FIXME: WHAT IF THIS IS A TREE???
+        if (fChain && fChain->GetStatus()->FindObject(branch->GetName()))
+        {
+            *fLog << warn << "WARNING - Branch " << branch->GetName() << " already setup." << endl;
+            continue;
+        }
+
+        // Get the corresponding class
+        const TString classname = branch->GetClassName();
+
+        TClass *cls = gROOT->GetClass(classname);
+        if (!cls)
+        {
+            // FIXME: With or without dot?
+            TLeaf *l = branch->GetLeaf(branch->GetName()); // FIXME: 1st leaf?
+            if (!l)
+                continue;
+
+            void *ptr = GetParameterPtr(*pList, l->GetTypeName(), oname);
+            if (SetBranchAddress(*branch, ptr, "Leaf", l->GetTypeName()))
+                num++;
+
+            continue;
+        }
+
+        // The class is known in the dictionary and loaded!
+        if (!cls->IsLoaded() || !cls->InheritsFrom(MParContainer::Class()))
+        {
+            void *ptr = GetParameterPtr(*pList, classname, oname);
+            if (SetBranchAddress(*branch, ptr, "Emulated branch"))
+                num++;
+        }
+        else
+        {
+            MParContainer **pcont= new MParContainer*;
+            *pcont=FindCreateObj(*pList, classname, oname);
+            if (SetBranchAddress(*branch, pcont, "Master branch"))
+                num++;
+        }
+    }
+
+    *fLog << inf2 << GetDescriptor() << " setup " << num << " master branches addresses." << endl;
+
+    //
+    // If auto enabling scheme isn't disabled, do auto enabling
+    //
+    if (fAutoEnable)
+        EnableBranches(pList);
+
+    //
+    // Now we can start notifying. Reset tree makes sure, that TChain thinks
+    // that the correct file is not yet initialized and reinitilizes it
+    // as soon as the first event is read. This is necessary to call
+    // the notifiers when the first event is read, but after the
+    // PreProcess-function.
+    //
+    if (fChain)
+        fChain->ResetTree(); // *CHANGED-fChain-to-fTree*
+
+    fTree->SetNotify(this); // *CHANGED-fChain-to-fTree*
+
+    const Int_t rc = GetSelector() ? GetSelector()->CallPreProcess(pList) : kTRUE;
+    if (rc!=kTRUE || fChain)
+        return rc;
+
+    return Notify();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the ready to save flag of all containers which branchaddresses are
+//  set for. This is necessary to copy data.
+//
+void MReadTree::SetReadyToSave(Bool_t flag)
+{
+    fParList.R__FOR_EACH(MParContainer, SetReadyToSave)(flag);
+
+    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.
+//
+Int_t MReadTree::Process()
+{
+    if (GetSelector())
+    {
+        //
+        // Make sure selector is processed
+        //
+        if (!GetSelector()->CallProcess())
+        {
+            *fLog << err << dbginf << "Processing Selector failed." << endl;
+            return kFALSE;
+        }
+
+        //
+        // Skip Event
+        //
+        if (!GetSelector()->IsConditionTrue())
+        {
+            fNumEntry++;
+            return kCONTINUE;
+        }
+    }
+
+    const Bool_t rc = fTree->GetEntry(fNumEntry++) != 0; // *CHANGED-fChain-to-fTree*
+
+    if (fTaskList)
+        fTaskList->SetStreamId(fTree->GetName()); // *CHANGED-fChain-to-fTree*
+
+    if (rc)
+    {
+        SetReadyToSave();
+        return kTRUE;
+    }
+
+    if (fChain)
+    {
+//        cout << "LE: " << (int)fChain->GetLastError() << endl;
+
+        switch (fChain->GetLastError())
+        {
+        case MChain::kFatalError:
+            *fLog << err << GetDescriptor() << " - ERROR: Notify() failed." << endl;
+            return kERROR;
+        case MChain::kCannotAccessFile:
+            *fLog << err << GetDescriptor() << " - ERROR: TChain::LoadTree is unable to access requested file." << endl;
+            return kERROR;
+        case MChain::kCannotAccessTree:
+            *fLog << err << GetDescriptor() << " - ERROR: TChain::LoadTree is unable to access requested tree." << endl;
+            return kERROR;
+        case MChain::kOutOfRange: // no more events available
+            return kFALSE;
+        case MChain::kNoError:    // go on!
+            return kTRUE;
+        }
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If a selector is given the selector is post processed
+//
+Int_t MReadTree::PostProcess()
+{
+    // In the case of a memory tree I don't know how we can
+    // make a decision in PreProcess between a self allocated
+    // memory address or a pending address set long before.
+    // So we delete the stuff in PostProcess and not the destructor
+    // (which might seg fault if PreProcess has never been called)
+    if (!fChain)
+    {
+        TIter Next(fTree->GetListOfBranches());
+        TBranch *b=0;
+        while ((b=(TBranch*)Next()))
+        {
+            if (b->GetAddress())
+            {
+                delete b->GetAddress();
+                b->ResetAddress();
+            }
+        }
+    }
+
+    return GetSelector() ? GetSelector()->CallPostProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Event with the current EventNumber fNumEntry
+//
+Bool_t MReadTree::GetEvent()
+{
+    Bool_t rc = fTree->GetEntry(fNumEntry) != 0; // *CHANGED-fChain-to-fTree*
+
+    if (rc)
+        SetReadyToSave();
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Decrease the number of the event which is read by Process() next
+// by one or more
+//
+Bool_t MReadTree::DecEventNum(UInt_t dec)
+{
+    if (fNumEntry-dec >= GetEntries())
+    {
+        *fLog << warn << GetDescriptor() << ": DecEventNum, WARNING - Event " << fNumEntry << "-";
+        *fLog << dec << "=" << (Int_t)fNumEntry-dec << " out of Range (>=";
+        *fLog << GetEntries() << ")." << endl;
+        return kFALSE;
+    }
+
+    fNumEntry -= dec;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Increase the number of the event which is read by Process() next
+// by one or more
+//
+Bool_t MReadTree::IncEventNum(UInt_t inc)
+{
+    if (fNumEntry+inc >= GetEntries())
+    {
+        *fLog << warn << GetDescriptor() << ": IncEventNum, WARNING - Event " << fNumEntry << "+";
+        *fLog << inc << "=" << (Int_t)fNumEntry+inc << " out of Range (>=";
+        *fLog << GetEntries() << ")." << endl;
+        return kFALSE;
+    }
+
+    fNumEntry += inc;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function makes Process() read event number nr next
+//
+// Remark: You can use this function after instatiating you MReadTree-object
+//         to set the event number from which you want to start reading.
+//
+Bool_t MReadTree::SetEventNum(UInt_t nr)
+{
+    if (nr!=0 && nr >= GetEntries())
+    {
+        *fLog << warn << GetDescriptor() << ": SetEventNum, WARNING - " << nr << " out of Range." << endl;
+        return kFALSE;
+    }
+
+    fNumEntry = nr;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  For the branch with the given name:
+//   1) no object is automatically created
+//   2) the branch address for this branch is not set
+//      (because we lack the object, see 1)
+//   3) The whole branch (exactly: all its subbranches) are disabled
+//      this means are not read in memory by TTree:GetEntry
+//
+void MReadTree::VetoBranch(const char *name)
+{
+    fVetoList->Add(new TNamed(name, ""));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the name of the file we are actually reading from.
+//
+TString MReadTree::GetFullFileName() const
+{
+    const TFile *file = fChain ? fChain->GetFile() : fTree->GetCurrentFile();
+
+    if (!file)
+        return "<unknown>";
+
+    return file->GetName();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get number of files in chain. (-1 is returned if chain is not
+// initialized.
+//
+Int_t MReadTree::GetNumFiles() const
+{
+    if (!fChain)
+        return -1;
+
+    return fChain->GetListOfFiles()->GetEntries();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the number of the file in the chain, -1 in case of an error
+//
+Int_t MReadTree::GetFileIndex() const
+{
+    return fChain ? fChain->GetTreeNumber() : 0;
+    /*
+    const TString filename = fChain->GetFile()->GetName();
+
+    int i=0;
+    TObject *file = NULL;
+
+    TIter Next(fChain->GetListOfFiles());
+    while ((file=Next()))
+    {
+        if (filename==gSystem->ExpandPathName(file->GetTitle()))
+            return i;
+        i++;
+    }
+    return -1;
+    */
+}
+
+// --------------------------------------------------------------------------
+//
+//  This schedules a TObject which Notify() 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(ostream &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: branches/Mars_McMismatchStudy/mfileio/MReadTree.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MReadTree.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MReadTree.h	(revision 17960)
@@ -0,0 +1,110 @@
+#ifndef MARS_MReadTree
+#define MARS_MReadTree
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MChain;
+class TChain;
+class TChainElement;
+class TBranch;
+class TTree;
+class MTaskList;
+
+class MReadTree : public MRead
+{
+    friend class MReadReports;
+
+private:
+    MChain *fChain;            // Pointer to tree==fTree (only if fTree inherits from MChain)
+    TTree  *fTree;             // Pointer to tree
+
+    UInt_t  fNumEntry;         // Number of actual entry in chain
+    UInt_t  fNumEntries;       // Number of Events in chain
+
+    Bool_t  fBranchChoosing;   // Flag for branch choosing method
+    Bool_t  fAutoEnable;       // Flag for auto enabeling scheme
+
+    TList  *fVetoList;         //-> List of Branches which are not allowed to get enabled
+    TList  *fNotify;           //-> List of TObjects to notify when switching files
+
+    MTaskList *fTaskList;      // Tasklist to set StreamId
+    TList      fParList;
+
+    enum { kChainWasChanged = BIT(14) };
+    // MReadReports::kIsRequired  = BIT(22)
+    // MReadReports::kIsProcessed = BIT(23)
+
+private:
+    void SetBranchStatus(const TList *list, Bool_t status);
+    void SetBranchStatus(TObject *branch, Bool_t status);
+    void SetBranchStatus(const char *name, Bool_t status);
+
+    Bool_t IsOwned(const TChainElement &e) const;
+
+    void GetListOfBranches(TList &list) const;
+    MParContainer *FindCreateObj(MParList &plist, const char *cname, const char *name);
+    void *GetParameterPtr(MParList &plist, const TString &bb, const char *parname);
+    Bool_t SetBranchAddress(TBranch &b, void *ptr, const char *prefix, const char *type=0);
+
+    void DisableSubBranches(TBranch *b);
+    void EnableBranches(MParList *plist);
+    void EnableBranchChoosing();
+
+    Bool_t CheckBranchSize();
+
+    virtual void SetReadyToSave(Bool_t flag=kTRUE);
+    virtual void StreamPrimitive(std::ostream &out) const;
+
+    enum { kIsOwner = BIT(14) };
+    // MReadReports::kIsRequired  = BIT(22)
+    // MReadReports::kIsProcessed = BIT(23)
+
+public:
+    MReadTree(TTree *tree=0);
+    MReadTree(const char *treename, const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MReadTree();
+
+    static Byte_t IsFileValid(const char *name);
+
+    virtual void SortFiles();
+
+    void   DisableAutoScheme() { fAutoEnable = kFALSE; }
+    void   EnableBranch(const char *name);
+    void   VetoBranch(const char *name);
+
+    Bool_t GetEvent();
+
+    Bool_t DecEventNum(UInt_t dec=1); // decrease number of event (position in tree)
+    Bool_t IncEventNum(UInt_t inc=1); // increase number of event (position in tree)
+    Bool_t SetEventNum(UInt_t nr);    // set number of event (position in tree)
+
+    UInt_t GetNumEntry() const { return fNumEntry; }
+    UInt_t GetEntries();
+
+    //TString GetFileName() const;
+    TString GetFullFileName() const;
+    Int_t   GetFileIndex() const;
+    Int_t   GetNumFiles() const;
+
+    virtual void AddNotify(TObject *obj);
+    virtual void SetOwner(Bool_t flag=kTRUE);
+
+    virtual Int_t AddFile(const char *fname, Int_t entries=-1);
+    virtual Int_t AddFiles(const MReadTree &read);
+    Int_t AddFiles(MDirIter &dir) { return MRead::AddFiles(dir); }
+    Bool_t AddFriend(TChain &c);
+
+    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: branches/Mars_McMismatchStudy/mfileio/MTopFitsGroup.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MTopFitsGroup.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MTopFitsGroup.cc	(revision 17960)
@@ -0,0 +1,27 @@
+
+#include "MTopFitsGroup.h"
+
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// Attaches the table to this FITS group                                       
+// Note: This FITS group as well as the table must be open, before calling     
+//       this method!                                                          
+void MTopFitsGroup::Attach(ofits* table)
+{
+//   fTopGroup.SetChild(table);
+//   fTopGroup.Write();
+}
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// Opens "table" with the next child in this group.                            
+// If table is an already open FITS table, then that table we be closed,       
+// before the new child is assigned to "table"                                 
+Bool_t MTopFitsGroup::GetNextChild(ofits* table)
+{
+//   fTopGroup.SetChild(table);
+//   return fTopGroup.Read();
+    return false;
+}
+
Index: branches/Mars_McMismatchStudy/mfileio/MTopFitsGroup.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MTopFitsGroup.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MTopFitsGroup.h	(revision 17960)
@@ -0,0 +1,70 @@
+#ifndef MARS_MTopFitsGroup
+#define MARS_MTopFitsGroup
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#ifndef MARS_fits
+#include "fits.h"
+#endif
+
+#ifndef MARS_ofits
+#include "ofits.h"
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// An unique id of files. It is sortable, i. e. can be uses as a key in maps   
+class MUniqueFileId
+{
+   dev_t       fst_dev;   // id of the device of this file                  
+   ino_t       fst_ino;   // inode number of the file on the device fst_dev 
+
+public:
+  MUniqueFileId(dev_t st_dev, ino_t st_ino)
+      : fst_dev(st_dev), fst_ino(st_ino) {}
+   
+   bool operator < (const MUniqueFileId & fileId) const
+      { if (fst_dev == fileId.fst_dev)
+           return fst_ino < fileId.fst_ino;
+        return fst_dev < fileId.fst_dev;   }
+
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// All information of one open Top Level FITS group                            
+class MTopFitsGroup
+{  
+   // filename of the group, but expanded by ROOT                         
+   // ( see gSystem->ExpandPathName() )                                   
+   TString     fFileName;  
+
+   // the top level group as AstroROOT-2 data structure                   
+   ofits*    fTopGroup;
+
+   // number of usage of this group by different MWriteFitsFile instances 
+   Int_t       fNumOpen;     
+
+public:
+   MTopFitsGroup(const char * fileName, ofits* file) : fFileName(fileName),
+                                          fTopGroup(file),
+                                          fNumOpen(1)
+   {}
+
+   void   IncreaseUsage()               {++fNumOpen;}
+   void   DecreaseUsage()               {--fNumOpen;}
+   Int_t  GetNumUsage()                 {return fNumOpen;}
+
+   void   Attach(ofits* table);
+   Bool_t GetNextChild(ofits* table);
+
+   ofits*  GetGroup()        {return fTopGroup;}
+   const TString &GetFileName() const {return fFileName;}
+
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mfileio/MWriteAsciiFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteAsciiFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteAsciiFile.cc	(revision 17960)
@@ -0,0 +1,319 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 06/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MWriteAsciiFile
+//
+// If you want to store a single container into an Ascii file you have
+// to use this class. You must know the name of the file you wanne write
+// (you should know it) and the name of the container you want to write.
+// This can be the name of the class or a given name, which identifies
+// the container in a parameter container list (MParList).
+// The container is written to the ascii file if its ReadyToSave flag is
+// set (MParContainer)
+//
+// You can write more than one container in one line of the file, see
+// AddContainer.
+//
+// You can also write single data members of a container (like fWidth
+// of MHillas). For more details see AddContainer. Make sure, that a
+// getter method for the data member exist. The name of the method
+// must be the same than the data member itself, but the f must be
+// replaced by a Get.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MWriteAsciiFile.h"
+
+#include <fstream>
+
+#include <TMethodCall.h> // TMethodCall, AsciiWrite
+
+#include "MIter.h"
+
+#include "MDataList.h"   // MDataList
+#include "MDataPhrase.h" // MDataPhrase
+#include "MDataValue.h"  // MDataValue
+#include "MDataMember.h" // MDataMember
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MWriteAsciiFile);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Init. Replaces the same code used in all constructors.
+//
+void MWriteAsciiFile::Init(const char *filename, const char *name, const char *title)
+{
+    fName  = name  ? name  : "MWriteAsciiFile";
+    fTitle = title ? title : "Task to write one container to an ascii file";
+
+    fNameFile = filename;
+
+    fOut = new ofstream(fNameFile);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the name of the ascii output file 'filename' and the name
+// of the container you want to write. (Normally this is the name
+// of the class (eg. MHillas) but it can also be a different name which
+// identifies the container in the parameter list.
+// Because you cannot write more than one container there is no Add-function
+// like in MWriteRootFile.
+//
+//  For Example: MWriteAsciiFile("file.txt", "MHillas");
+//
+MWriteAsciiFile::MWriteAsciiFile(const char *filename, const char *contname,
+                                 const char *name, const char *title)
+{
+    Init(filename, name, title);
+
+    if (contname)
+       AddColumns(contname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify a the name of the ascii output file 'filename' and a pointer to
+// the container you want to write. 
+// Because you cannot write more than one container there is no Add-function
+// like in MWriteRootFile.
+//
+//  For Example: MHillas hillas;
+//               MWriteAsciiFile("file.txt", &hillas);
+//
+//
+MWriteAsciiFile::MWriteAsciiFile(const char *filename, MParContainer *cont,
+                                 const char *name, const char *title)
+{
+    Init(filename, name, title);
+
+    if (cont)
+        AddColumns(cont);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete the output file if necessary (it is closed
+// automatically by its destructor.
+//
+MWriteAsciiFile::~MWriteAsciiFile()
+{
+    fAutoDel.SetOwner();
+    delete fOut;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return open state of the file
+//
+Bool_t MWriteAsciiFile::IsFileOpen() const
+{
+    return (bool)(*fOut);
+}
+
+// --------------------------------------------------------------------------
+//
+// Tries to get all containers from the ParList which were given by name
+// adds them to the list of pointers to the container which should be
+// written to the ascii file.
+//
+Bool_t MWriteAsciiFile::GetContainer(MParList *plist)
+{
+    TObject *obj=NULL;
+
+    TIter Next(&fList);
+    while ((obj=Next()))
+    {
+        //
+        // MData is the highest class in the inheritance tree
+        //
+        if (obj->InheritsFrom(MData::Class()))
+        {
+            if (!((MData*)obj)->PreProcess(plist))
+                return kFALSE;
+            continue;
+        }
+
+        //
+        // MParContainer is the next class in the inheritance tree
+        //
+        if (obj->InheritsFrom(MParContainer::Class()))
+            continue;
+
+        //
+        // It is neither a MData nor a MParContainer, it must be a TNamed
+        //
+        TObject *o = plist->FindObject(obj->GetName());
+        if (!o)
+            return kFALSE;
+
+        fList[fList.IndexOf(obj)] = o;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the containers are ready for writing. If so write them.
+// The containers are written in one line, one after each other.
+// If not all containers are written (because of the IsReadyToSave-flag)
+// a warning message is print.
+//
+Bool_t MWriteAsciiFile::CheckAndWrite()
+{
+    MParContainer *obj = NULL;
+
+    //
+    // Check for the Write flag
+    //
+    Bool_t write = kFALSE;
+    MIter Next(&fList);
+    while ((obj=Next()))
+        if (obj->IsReadyToSave())
+        {
+            write = kTRUE;
+            break;
+        }
+
+    //
+    // Do not write if not at least one ReadyToSave-flag set
+    //
+    if (!write)
+        return kTRUE;
+
+    Bool_t written = kFALSE;
+    Int_t num = fList.GetEntries();
+
+    Next.Reset();
+    while ((obj=Next()))
+    {
+        if (written)
+            *fOut << " ";
+
+        //
+        // Write container to file
+        //
+        if (!obj->AsciiWrite(*fOut))
+            continue;
+
+        //
+        // Store that at least one container was written
+        //
+        written = kTRUE;
+
+        num--;
+    }
+
+    if (written)
+    {
+        *fOut << endl;
+
+        if (num!=0)
+            *fLog << warn << "WARNING - Number of objects written mismatch!" << endl;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a rule to be written as a column to the ascii file.
+// For more information about rules see MDataPhrase.
+//
+//  eg: MWriteAsciiFile::AddColumn("log10(MHillas.fEnergy)/2")
+//
+void MWriteAsciiFile::AddColumn(const TString rule)
+{
+    MDataPhrase *chain = new MDataPhrase(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: branches/Mars_McMismatchStudy/mfileio/MWriteAsciiFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteAsciiFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteAsciiFile.h	(revision 17960)
@@ -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:
+    std::ofstream *fOut; //! ascii file
+
+    TString fNameFile;   // name of the ascii file
+
+    TObjArray fList;     // list of rules and containers to be written
+    TObjArray fAutoDel;  //! List of object to be deleted in the destructor
+
+    virtual Bool_t CheckAndWrite();
+    virtual Bool_t IsFileOpen() const;
+    virtual Bool_t GetContainer(MParList *pList);
+    virtual const char *GetFileName() const { return fNameFile; }
+
+    void Init(const char *filename, const char *name, const char *title);
+
+public:
+    MWriteAsciiFile(const char *filename, const char *contname,
+                    const char *name=NULL, const char *title=NULL);
+    MWriteAsciiFile(const char *filename, MParContainer *cont=NULL,
+                    const char *name=NULL, const char *title=NULL);
+    ~MWriteAsciiFile();
+
+    void AddColumn(const TString rule);
+    void AddColumn(MParContainer *cont, const TString member="", Double_t scale=1);
+    void AddColumns(const TString name);
+    void AddColumns(MParContainer *cont);
+
+    ClassDef(MWriteAsciiFile, 0) // Class to write data into an ascii file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MWriteFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteFile.cc	(revision 17960)
@@ -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): 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
+    //
+    return GetContainer(pList);
+    /*
+    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: branches/Mars_McMismatchStudy/mfileio/MWriteFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteFile.h	(revision 17960)
@@ -0,0 +1,27 @@
+#ifndef MARS_MWriteFile
+#define MARS_MWriteFile
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MWriteFile : public MTask
+{
+protected:
+    Bool_t ReInit(MParList *pList);
+
+private:
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    virtual Bool_t      IsFileOpen() const = 0;
+    virtual Bool_t      CheckAndWrite() = 0;
+    virtual Bool_t      GetContainer(MParList *pList) = 0;
+    virtual const char *GetFileName() const = 0;
+
+
+    ClassDef(MWriteFile, 0)	// Base class for tasks to write single containers to several output formats
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MWriteFitsFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteFitsFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteFitsFile.cc	(revision 17960)
@@ -0,0 +1,1248 @@
+#include <TDataMember.h>
+#include <TClonesArray.h>
+
+#include "MLogManip.h"
+
+#include "MArrayS.h"
+#include "MArrayB.h"
+#include "MArrayF.h"
+
+#include "MRead.h"
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MWriteRootFile.h"
+
+#include "MWriteFitsFile.h"
+#include "MFitsArray.h"
+
+#include "MTime.h"
+
+//for find
+#include <algorithm>
+
+ClassImp(MWriteFitsFile);
+
+using namespace std;
+
+map<MUniqueFileId, MTopFitsGroup> MWriteFitsFile::fTopFitsGroups;
+
+
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// if fileMode == kSingleFile                                                  
+//    Opens the top level group file, if it was not already opened by an other 
+//    instance of MWriteFitsFile.                                              
+// if fileMode == kMultiFiles                                                  
+//    fname defines the rules to build the output filenames from the current   
+//    input filename. The files are opened in the ReInit() method.             
+//                                                                             
+// opt = RECREATE : an existing file will be deleted                           
+//     = NEW      : an already existing file will not be deleted and the new   
+//                  file is not created. Check with IsFileOpen() if the new    
+//                  top level group could be opened.                           
+// name will be the name of the group                                          
+// title will be written as keyword TITLE into the header                      
+//                                                                             
+MWriteFitsFile::MWriteFitsFile(const char *fname,
+                               FILE_MODE fileMode,
+                               const Option_t *opt,
+                               const char *name,
+                               const char *title)
+{
+   fOpenOption = opt;
+   if (name && name[0] != 0)
+      fGroupName = name;
+   else
+      fGroupName = "MARS";
+
+   if (title)
+      fTitle = title;
+
+   iTopFitsGroup = fTopFitsGroups.end();
+
+   if (fileMode == kMultiFiles)
+      fRule = fname;
+   else
+       *fLog << err << "The new version of MWriteFitsFile does not support multiple tables in one file. Please use kMultiFiles instead" << endl;
+      //ETIENNE DEPREC
+      // iTopFitsGroup will be set by OpenTopLevelGroup, if a top level   
+      // group can be assigned to this MWriteFitsFile.                    
+      //OpenTopLevelGroup(fname);
+}
+
+MWriteFitsFile::MWriteFitsFile(const Int_t comp,
+                               const char* rule,
+                               const Option_t* option,
+                               const char* ftitle,
+                               const char* name,
+                               const char* title)
+{
+    fOpenOption = option;
+    if (name && name[0] != 0)
+        fGroupName = name;
+    else
+        fGroupName = "MARS";
+    if (title) fTitle = ftitle;
+    iTopFitsGroup = fTopFitsGroups.end();
+    //always kMultiFiles
+    fRule = rule;
+}
+// ----------------------------------------------------------------------------
+//                                                                             
+// Closes the top level group, it is is not used by an other instance of       
+// MWriteFitsFile.                                                             
+//                                                         std::map<TString, std::ofits*>
+MWriteFitsFile::~MWriteFitsFile()
+{
+    for (std::map<TString, ofits*>::iterator it=fFitsTables.begin(); it!= fFitsTables.end();it++)
+    {
+        if (it->second != NULL)
+        {
+            it->second->close();
+            delete it->second;
+        }
+    }
+//   CloseTopLevelGroup();
+   DeleteArrayHelper();
+}
+
+// ----------------------------------------------------------------------------
+//                                                                             
+// If the same file is already used by an other instance of MWriteFitsFile,    
+// the user counter is increasesd.                                             
+// Else: If the file exist and option is "RECREATE", the file is deleted and   
+//       recreated.                                                            
+// Finally the file with an empty group file is created.                       
+//                                                                             
+void MWriteFitsFile::OpenTopLevelGroup(const char * fname)
+{
+   // get rid of environment variables, ~, ... in filename
+   char * expandedFileName = gSystem->ExpandPathName(fname);
+
+   // get unique identifier of the new file
+   struct stat fileId;
+   if (stat(expandedFileName, &fileId) == 0)
+      {
+      // file exist already
+      iTopFitsGroup = fTopFitsGroups.find(MUniqueFileId(fileId.st_dev, fileId.st_ino));
+      if (iTopFitsGroup != fTopFitsGroups.end())
+         {
+          *fLog << err << "You are trying to use an already existing file. Please choose a different file name (" << fname << ")" << endl;
+          exit(0);
+         // this group is already open. we use it as well
+         *fLog << inf2 << "Found open file '" << GetFileName() << "'... re-using." << endl;
+         iTopFitsGroup->second.IncreaseUsage();
+         delete [] expandedFileName;
+         return;
+         } 
+
+      // file exist, but we cannot use
+      if (fOpenOption == "RECREATE") 
+         // remove the file
+         unlink(expandedFileName);
+
+      else if (fOpenOption == "NEW")
+         {
+         *fLog << err << "File '" << expandedFileName << "' exist already." << endl;
+         delete [] expandedFileName;
+         return;
+         }
+      else
+         {
+         *fLog << err << "Unsupported option (" << fOpenOption.Data() << ") to open file " <<
+                          expandedFileName << endl;
+         delete [] expandedFileName;
+         return;
+         }
+      }
+
+   // file does not yet exist or was deleted
+
+//   try {
+//      AstroRootGroup topGroup;
+//      char wrTitle[fTitle.Length() + 1];
+//      if (fTitle.Length() > 0)
+//         {
+//         strcpy(wrTitle, fTitle.Data());
+//         topGroup.InitAttr("TITLE", "A", wrTitle);
+//         }
+
+   //ETIENNE do not open top level group as using one file per table
+   //I kept this code active anyway, because it is checked elsewhere in the code that iTopFitsGroup is set.
+        ofits* topGroup = NULL;
+//      ofits* topGroup = new ofits();
+//      TString dol = expandedFileName;
+//      topGroup->open(dol.Data());
+
+
+      // store this new file in fTopFitsGroups and get the iterator to the  
+      // new group                                                          
+      stat(expandedFileName, &fileId);
+      iTopFitsGroup = fTopFitsGroups.insert(pair<MUniqueFileId, MTopFitsGroup>
+                           (MUniqueFileId(fileId.st_dev, fileId.st_ino),
+                           MTopFitsGroup(expandedFileName, topGroup)        )).first; 
+
+   delete [] expandedFileName;
+
+}
+
+// --------------------------------------------------------------------------
+//                                                                           
+// Reduces the use - counter of the top level group. Closes the group        
+// table, if the counter is 0, i.e. no other MWriteFitsFile instance uses    
+// the same top level group.                                                 
+//
+
+void MWriteFitsFile::CloseTopLevelGroup()
+{
+   if (iTopFitsGroup != fTopFitsGroups.end())
+      {
+      iTopFitsGroup->second.DecreaseUsage();
+      if (iTopFitsGroup->second.GetNumUsage() <= 0)
+         fTopFitsGroups.erase(iTopFitsGroup);
+
+      iTopFitsGroup = fTopFitsGroups.end();
+      }
+}
+
+// --------------------------------------------------------------------------
+//                                                                           
+// returns the name of the top level group file. It may be expanded if the   
+// name, given by the user, contained environment variables of the ~ sign.   
+// If no top level group is open, "no_open_file" is returned.                
+//                                                                           
+const char * MWriteFitsFile::GetFileName() const            
+{
+   if (IsFileOpen())
+      return iTopFitsGroup->second.GetFileName().Data();
+   else
+      return "no_open_file";
+}
+
+// --------------------------------------------------------------------------
+//                                                                           
+// 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 FITS table to which the    
+// container should be written (Remark: one table can hold more than one     
+// container). The default is the same name as the container name.           
+// If "mus"t is set to kTRUE (the default), then the container must exist    
+// in the parameterlist. The container will be ignored, if "must" is set to  
+// kFALSE and the container does not exist in the parameterlist.             
+//                                                                           
+void MWriteFitsFile::AddContainer(const char *cName,
+                                  const char *tName,
+                                  Bool_t must, UInt_t max)
+{
+   if (cName == NULL || strlen(cName) == 0)
+      {
+      *fLog << warn << "Warning - container name in method MWriteFitsFile::"
+                       "AddContainer not defined... ignored" << endl;
+      return;
+      }
+
+   // if tName is not defined, we use cName as the table name  
+   TString tableName;
+   if (tName == NULL || strlen(tName) == 0)
+      tableName = cName;
+   else
+      tableName = tName;
+
+   // try to insert this container to the list of sub-tables. Write a     
+   // warning, if the same container name was already defined and ignore  
+   // this one.                                                           
+   if (fSubTables[tableName].insert( pair<TString, MFitsSubTable>
+                             (cName, MFitsSubTable(must))).second == false) 
+      {
+      *fLog << warn << "Warning - Container '"<< cName <<"' in table '" <<
+                       tableName.Data() << "' already scheduled... ignored." << endl;
+      }
+}
+
+// --------------------------------------------------------------------------
+//                                                                           
+// Add a new Container to list of containers which should be written to the  
+// file. tname is the name of the FITS table to which the                    
+// container should be written (Remark: one table can hold more than one     
+// container). The default is the same name as the container name.           
+// "must" is ignored. It is just for compatibility with MWriteRootFiles.     
+//                                                                           
+void MWriteFitsFile::AddContainer(MParContainer *cont, const char *tName, 
+                                  Bool_t must, UInt_t max)
+{
+   if (cont == NULL)
+      {
+      *fLog << warn << "Warning - container in method MWriteFitsFile::"
+                       "AddContainer not defined... ignored" << endl;
+      return;
+      }
+
+   TString tableName;
+   if (tName == NULL || strlen(tName) == 0)
+      tableName = cont->IsA()->GetName();
+   else
+      tableName = tName;
+
+   TString cName = cont->IsA()->GetName();
+   if (fSubTables[tableName].insert( pair<TString, MFitsSubTable>
+                             (cName, MFitsSubTable(cont, must))).second == false) 
+      {
+      *fLog << warn << "Warning - Container '"<< cName.Data() <<
+                       "' in table '" << tableName.Data() << 
+                       "' already scheduled... ignored." << endl;
+      }
+}
+
+// --------------------------------------------------------------------------
+//
+// Tries to open the given output file.
+//
+Int_t MWriteFitsFile::PreProcess(MParList *pList)
+{
+   if (fRule.Length() != 0)
+      // the file is not yet open
+      return kTRUE;
+    //
+    // 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();
+
+}
+
+Int_t MWriteFitsFile::PostProcess()
+{
+    bool rc = true;
+    for (std::map<TString, ofits*>::iterator it=fFitsTables.begin(); it!= fFitsTables.end();it++)
+    {
+        rc &= it->second->close();
+        delete it->second;
+        it->second = NULL;
+    }
+
+    return rc;
+}
+
+void MWriteFitsFile::SetupHeaderKeys(MRawRunHeader &header)
+{
+    const MTime now(-1);
+    SetHeaderKey("ISMC",true,"Bool if File is Montecarlo File");
+    SetHeaderKey("TELESCOP", "FACT", "");
+    SetHeaderKey("PACKAGE", "MARS Cheobs", "");
+    SetHeaderKey("VERSION", "1.0", "");
+    SetHeaderKey("CREATOR", "Ceres", "");
+    SetHeaderKey("EXTREL", 1., "");
+    SetHeaderKey("COMPILED", __DATE__" " __TIME__, "");
+    //SetHeaderKey("REVISION", "0", "");
+    SetHeaderKey("ORIGIN", "FACT", "");
+    SetHeaderKey("DATE", now.GetStringFmt("%Y-%m-%dT%H:%M:%S").Data(), "");
+    SetHeaderKey("NIGHT", now.GetNightAsInt(), "");
+    SetHeaderKey("TIMESYS", "UTC", "");
+    SetHeaderKey("TIMEUNIT", "d", "");
+    SetHeaderKey("MJDREF", 40587, "");
+    //SetHeaderKey("BLDVER", 1, "");
+    SetHeaderKey("RUNID", header.GetRunNumber(), "");
+    SetHeaderKey("NBOARD", 40, "");
+    SetHeaderKey("NPIX", header.GetNumPixel(), "");
+    SetHeaderKey("NROI", header.GetNumSamplesHiGain(), "");
+    SetHeaderKey("NROITM", 0, "");
+    SetHeaderKey("TMSHIFT", 0, "");
+    SetHeaderKey("CAMERA", "MGeomCamFACT", "Montecarlo File");
+    SetHeaderKey("DAQ", "DRS4", "Montecarlo File");
+
+    // FTemme: ADCRANGE and ADC have to be calculated, using the values for
+    // the fadctype.
+//    SetHeaderKey("ADCRANGE", 2000, "Dynamic range in mV");
+//    SetHeaderKey("ADC", 12, "Resolution in bits");
+
+    switch(header.GetRunType())
+    {
+    case MRawRunHeader::kRTData|MRawRunHeader::kRTMonteCarlo:
+        SetHeaderKey("RUNTYPE", "data", "");
+        break;
+    case MRawRunHeader::kRTPedestal|MRawRunHeader::kRTMonteCarlo:
+        SetHeaderKey("RUNTYPE", "pedestal", "");
+        break;
+    case MRawRunHeader::kRTCalibration|MRawRunHeader::kRTMonteCarlo:
+        SetHeaderKey("RUNTYPE", "calibration", "");
+        break;
+    }
+//    SetHeaderKey("ID", 777, "Board  0: Board ID");
+//    SetHeaderKey("FMVER", 532, "Board  0: Firmware Version");
+//    SetHeaderKey("DNA", "0", "");
+//    SetHeaderKey("BOARD", 0, "");
+//    SetHeaderKey("PRESC", 40, "");
+//    SetHeaderKey("PHASE", 0, "");
+//    SetHeaderKey("DAC0", 26500, "");
+//    SetHeaderKey("DAC1", 0, "");
+//    SetHeaderKey("DAC2", 0, "");
+//    SetHeaderKey("DAC3", 0, "");
+//    SetHeaderKey("DAC4", 28800, "");
+//    SetHeaderKey("DAC5", 28800, "");
+//    SetHeaderKey("DAC6", 28800, "");
+//    SetHeaderKey("DAC7", 28800, "");
+    SetHeaderKey("REFCLK", header.GetFreqSampling(), "");
+    SetHeaderKey("DRSCALIB", false, "");
+//    SetHeaderKey("TSTARTI", 0, "");
+//    SetHeaderKey("TSTARTF", 0., "");
+//    SetHeaderKey("TSTOPI", 0, "");
+//    SetHeaderKey("TSTOPF", 0., "");
+//    SetHeaderKey("DATE-OBS", "1970-01-01T00:00:00", "");
+//    SetHeaderKey("DATE-END", "1970-01-01T00:00:00", "");
+//    SetHeaderKey("NTRG", 0, "");
+//    SetHeaderKey("NTRGPED", 0, "");
+//    SetHeaderKey("NTRGLPE", 0, "");
+//    SetHeaderKey("NTRGTIM", 0, "");
+//    SetHeaderKey("NTRGLPI", 0, "");
+//    SetHeaderKey("NTRGEXT1", 0, "");
+//    SetHeaderKey("NTRGEXT2", 0, "");
+//    SetHeaderKey("NTRGMISC", 0, "");
+}
+
+template<>
+std::string MWriteFitsFile::GetFitsString(const double& value)
+{
+    std::ostringstream returnVal;
+    returnVal << std::setprecision(value>1e-100 && value<1e100 ? 15 : 14) << value;
+    std::string temp = returnVal.str();
+    std::replace(temp.begin(), temp.end(), 'e', 'E');
+    if (temp.find_first_of('E')==std::string::npos && temp.find_first_of('.')==std::string::npos)
+        temp += ".";
+    return temp;
+}
+template<>
+std::string MWriteFitsFile::GetFitsString(const float& value)
+{
+    return GetFitsString((double)(value));
+}
+// --------------------------------------------------------------------------
+//                                                                           
+// Opens all FITS files for all container, which were registered with the    
+// AddContainer() - methods. The container is taken from the pList, if it    
+// was registered just by its name.                                          
+// Calling the AddContainer() after calling this method will not add new     
+// containers to the list.                                                   
+//                                                                           
+Bool_t  MWriteFitsFile::GetContainer(MParList *pList)
+{
+   if (iTopFitsGroup == fTopFitsGroups.end())
+      // something went wrong while the top level group was created
+      return kFALSE;
+
+
+   // remove the extension from the filename
+   // this has been disabled for now
+   char fileNameNoExt[strlen(GetFileName()) + 1];
+   strcpy(fileNameNoExt, GetFileName());
+//   char * pos = strrchr(fileNameNoExt, '.');
+//   if (pos) *pos = 0;
+//*fLog << inf <<"Filename no ext: " << fileNameNoExt << endl;
+   // loop over all FITS tables which have to be created.
+   map<TString, map<TString, MFitsSubTable> >::iterator i_table =
+      fSubTables.begin();
+   while (i_table != fSubTables.end())
+      {
+
+      ofits* fitsTable = new ofits();
+      fitsTable->AllowCommentsTrimming(true);
+      TString dol = fileNameNoExt;
+      //get rid of the ".root" extension in the file name (if any)
+      if (dol(dol.Length()-5, dol.Length()) == ".root")
+      {
+          dol = dol(0, dol.Length()-5);
+      }
+      if (dol(dol.Length()-5, dol.Length()) == ".fits")
+      {
+          dol = dol(0, dol.Length()-5);
+      }
+      dol += "_";
+      dol += i_table->first;
+      dol += ".fits";
+      fitsTable->open(dol.Data());
+      *fLog << inf << "Opening FITS file: " << dol.Data() << endl;
+      fFitsTables[i_table->first] = fitsTable;
+      fTableObjectCreated[i_table->first] = true;
+      fTableHeaderWritten[i_table->first] = false;
+
+      // loop over all containers, which define a sub-table of the current table
+      Int_t num = 0;
+      map<TString, MFitsSubTable>::iterator i_subTable = i_table->second.begin();
+      while (i_subTable != i_table->second.end())
+         {
+
+         MFitsSubTable & subTable = i_subTable->second;
+         if (subTable.GetContainer() == NULL)
+            {
+            // container address is not yet known
+            const char * cname = i_subTable->first.Data();
+            MParContainer *cont = (MParContainer*)pList->FindObject(cname);
+            if (!cont)
+               {
+               // no corresponding container is available in pList
+               if (subTable.MustHave())
+                  {
+                  *fLog << err << "Cannot find parameter container '" << cname << "'." << endl;
+                  return kFALSE;
+                  }
+
+               // we can ignore this container, delete it from the map
+               *fLog << inf2 << "Unnecessary parameter container '" << cname << "' not found..." << endl;
+               map<TString, MFitsSubTable>::iterator i_tmp = i_subTable;
+               i_subTable++;
+               i_table->second.erase(i_tmp);
+               continue;
+               }
+
+            // we have our container address and can use it
+            subTable.SetContainer(cont);
+            }
+
+         // initialize all columns of the sub-table, defined by the current container
+         TClass * cl = i_subTable->second.GetContainer()->IsA();
+         if (!InitColumns(i_table->first, TString(cl->GetName()) + ".",  fitsTable, 
+                          i_subTable->second.GetContainer(), cl)     ) 
+            return kFALSE;
+
+         char attrName[10];
+         sprintf(attrName, "CLNAME%d", num);
+         num++;
+
+         InitAttr(attrName,
+                  "A",
+                  (void*)i_subTable->first.Data(),
+                  NULL,
+                  "MARS container name",
+                  fitsTable);
+
+         i_subTable++;
+         }
+
+      // in case not all sub-tables were removed, we can now create the FITS table
+      if (i_table->second.size() > 0)
+         {
+         // create the DOL of the table. It will be something like:     
+         // fileNameNoExt_dataName.fits[dataName]                       
+         TString dol = fileNameNoExt;
+         dol += "_";
+         dol += i_table->first;
+         dol += ".fits";
+
+         if (fOpenOption == "RECREATE") 
+            // remove the file
+            unlink(dol.Data());
+
+         dol += "[";
+         dol += i_table->first;
+         dol += "]";
+//         *fLog << err << "Reiner would have opened fits file: " << dol.Data() << endl;
+         //exit(0);
+         //fitsTable->open(dol.Data());
+
+         // attach the new table to the top level group
+         //TODO make sure that this attach below is not needed...
+         //iTopFitsGroup->second.Attach(fitsTable);
+         }
+               
+      i_table++;
+      }
+   
+   return kTRUE;
+}
+void MWriteFitsFile::InitAttr(const char* attrName,
+                              const char* dataType,
+                              void* var,
+                              const char* unit,
+                              const char* comment,
+                              ofits* outFile)
+{
+    if (outFile == NULL)
+        return;
+    string dts(dataType);
+    string ans(attrName);
+    string cs;
+    if (comment != NULL)
+        cs = string(comment);
+    else
+        cs = "";
+    ostringstream val;
+    if ((dts == "bool") || (dts == "Bool_t") || (dts == "L"))
+    {
+        outFile->SetBool(ans, ((bool*)(var))[0], cs);
+        return;
+    }
+    if ((dts == "char") || (dts == "Char_t") || (dts == "S"))
+    {
+        val << ((char*)(var))[0];
+        outFile->SetStr(ans, val.str(), cs);
+        return;
+    }
+    if ((dts == "unsigned char") || (dts == "UChar_t") || (dts == "B"))
+    {
+        val << ((unsigned char*)(var))[0];
+        outFile->SetStr(ans, val.str(), cs);
+        return;
+    }
+    if ((dts == "short") || (dts == "Short_t") || (dts == "I"))
+    {
+        val << ((short*)(var))[0];
+        outFile->SetStr(ans, val.str(), cs);
+        return;
+    }
+    if ((dts == "unsigned short") || (dts == "UShort_t") || (dts == "U"))
+    {
+        val << ((unsigned short*)(var))[0];
+        outFile->SetStr(ans, val.str(), cs);
+        return;
+    }
+    if ((dts == "int") || (dts == "Int_t") || (dts == "V"))
+    {
+        outFile->SetInt(ans, ((int*)(var))[0], cs);
+        return;
+    }
+    if ((dts == "unsigned int") || (dts == "UInt_t") || (dts == "V"))
+    {
+        outFile->SetInt(ans, ((unsigned int*)(var))[0], cs);
+        return;
+    }
+    if ((dts == "long long") || (dts == "Long64_t") || (dts == "K"))
+    {
+        outFile->SetInt(ans, ((long long*)(var))[0], cs);
+        return;
+    }
+    if ((dts == "unsigned long long") || (dts == "ULong64_t") || (dts == "W"))
+    {
+        val << ((unsigned long long*)(var))[0];
+        outFile->SetStr(ans, val.str(), cs);
+        return;
+    }
+    if ((dts == "float") || (dts == "TFloat_t") || (dts == "E"))
+    {
+        outFile->SetFloat(ans, ((float*)(var))[0], cs);
+        return;
+    }
+    if ((dts == "double") || (dts == "TDouble_t") || (dts == "D"))
+    {
+        outFile->SetFloat(ans, ((double*)(var))[0], cs);
+        return;
+    }
+    if ((dts == "char*") || (dts == "A"))
+    {
+        outFile->SetStr(ans, string((char*)(var)), cs);
+        return;
+    }
+    //trigger error
+    *fLog << err << "Format string not recognized while adding header entry " << ans << " with type " << dts << endl;
+}
+// --------------------------------------------------------------------------
+//                                                                           
+// This method is called when new data should be written to the FITS table.  
+// In general only one row is written. (There are exceptions for Arrays).    
+// A new row to a FITS table is written if at least for one container        
+// (one sub-table) the ReadyToSave - flag is set.                            
+//                                                                           
+Bool_t MWriteFitsFile::CheckAndWrite()
+{
+//   try {
+
+      // loop over all tables
+      map<TString, map<TString, MFitsSubTable> >::iterator i_table =
+         fSubTables.begin();
+      while (i_table != fSubTables.end())
+         {
+         // is this table open?
+         if (fFitsTables.find(i_table->first) != fFitsTables.end())
+            {
+
+            // loop over all sub-tables
+            map<TString, MFitsSubTable>::iterator i_subTable = i_table->second.begin();
+            while (i_subTable != i_table->second.end())
+               {
+
+               if (i_subTable->second.GetContainer()->IsReadyToSave())
+                  {
+                  // first write the TClonesArray and set the size of the arrays
+                  list<MArrayHelperBase*> & clHelper = fClHelper[i_table->first];
+                  list<MArrayHelperBase*>::iterator i_clHelper = clHelper.begin();
+                  while (i_clHelper != clHelper.end())
+                     {
+                     // write all entries in the TClonesArray in its FITS table
+  //removed this write because I do it elsewhere. is that alright ?
+ //                    (*i_clHelper)->Write();
+                     i_clHelper++;
+                     }
+
+                  // write one line to this table
+                  writeOneRow(i_table->first);
+//                  fFitsTables[i_table->first].Write();
+                  break;
+                  }
+               i_subTable++;
+               }
+            }
+
+         i_table++;
+         }
+//      }
+//   catch (exception &e)
+ //     {
+ //     *fLog << err << e.what() << endl;
+ //     return kFALSE;
+ //     }
+
+   return kTRUE;
+}
+
+string MWriteFitsFile::Trim(const string &str)
+{
+    // Trim Both leading and trailing spaces
+    const size_t first = str.find_first_not_of(' '); // Find the first character position after excluding leading blank spaces
+    const size_t last  = str.find_last_not_of(' ');  // Find the first character position from reverse af
+
+    // if all spaces or empty return an empty string
+    if (string::npos==first || string::npos==last)
+        return string();
+
+    return str.substr(first, last-first+1);
+}
+
+Bool_t MWriteFitsFile::VetoColumn(const std::string& colName)
+{
+    for (std::vector<string>::iterator it=fVetoedColumns.begin(); it != fVetoedColumns.end(); it++)
+        if (*it == colName)
+        {
+            *fLog << warn << "Warning: column " << colName << " is being vetoed twice" << endl;
+            return kFALSE;
+        }
+    fVetoedColumns.push_back(colName);
+    return kTRUE;
+}
+
+Bool_t MWriteFitsFile::SetBytesPerSample(const std::string& colName, uint32_t numBytes)
+{
+    for (map<string, uint32_t>::iterator it=fBytesPerSamples.begin(); it!=fBytesPerSamples.end(); it++)
+        if (it->first == colName)
+        {
+            *fLog << warn << "Warning: column " << colName << " bytes per sample is being redefined twice" << endl;
+            return kFALSE;
+        }
+    if (numBytes != 1 && numBytes != 2 && numBytes != 4 && numBytes != 8)
+    {
+        *fLog << warn << "Only powers of two are allowed for types re-mapping." << endl;
+        return kFALSE;
+    }
+    fBytesPerSamples[colName] = numBytes;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//                                                                           
+// Initialize all columns in "fitsTable" of the class "classDef". The data   
+// of this class are stored in a buffer, beginning at "baseAdr".             
+//                                                                           
+Bool_t MWriteFitsFile::InitColumns(const TString & tableName, 
+                                   const TString & parentVarName,
+                                   ofits* fitsTable,
+                                   void * baseAdr,
+                                   TClass * classDef)
+{
+    // get all data members of the class
+   TList * dataMembers = classDef->GetListOfDataMembers();
+   TIter next(dataMembers);
+   TDataMember * dataMember;
+
+   // loop over all data members
+   while ((dataMember = (TDataMember*)next()) != NULL)
+      {
+      if (!dataMember->IsPersistent())
+         // don't store this variable
+         continue;
+
+      if (dataMember->Property() & ( G__BIT_ISENUM | G__BIT_ISSTATIC))
+         // we cannot store this
+         continue;
+
+      if (strcmp(dataMember->GetTrueTypeName(), "TClass*") == 0)
+         // we don't want to store this. 
+         continue;
+
+      // is it an array of more than 1 dimension?
+      if (dataMember->GetArrayDim() > 1)
+         {
+         *fLog << err << "Two and more dimensional arrays of member variables"
+                         " are not supported." << endl;
+         *fLog <<        "See variable " << dataMember->GetName() << 
+                         " in container " << classDef->GetName() <<  endl;
+         return kFALSE;
+         }
+
+
+      // replace � by **2 in the comment field
+      string comment(dataMember->GetTitle());
+      string::size_type pos1, pos2;
+      if ((pos1 = comment.find(178)) != string::npos)
+         comment.replace(pos1, 1, "**2");
+
+      // get the optional mapping to the fits column names
+      string fitsOptions="";
+      string unit="unit";
+
+      pos1 = comment.find("{fits: ");
+      pos2 = comment.find('}');
+      std::map<string, string> fitsTokens;
+      if (pos1 != string::npos && pos2 != string::npos)
+      {
+          fitsOptions=comment.substr(pos1+7, (pos2-pos1)-7);
+          //do we have more than one option ?
+          string::size_type pos3= fitsOptions.find_first_of(';');
+          string::size_type pos4 = string::npos;
+          string key="";
+          string value="";
+          string keyValue="";
+          while (pos3 != string::npos)
+          {//we have at least 2 options left
+ //             *fLog << err << "fitsOptions: " << fitsOptions << endl;
+              keyValue = fitsOptions.substr(0,pos3);
+ //             *fLog << err << "keyValue: " << keyValue << endl;
+              pos4 = keyValue.find('=');
+              if (pos4 == string::npos)
+              {
+                  *fLog << err << "Error while parsing comment \"" << comment << "\" from variable " << parentVarName + dataMember->GetName() << endl;
+                  return kFALSE;
+              }
+              key = Trim(keyValue.substr(0, pos4));
+              value = Trim(keyValue.substr(pos4+1, pos3));
+              fitsTokens[key] = value;
+ //             *fLog << err << "key: " << key << " value: " << value << endl;
+              fitsOptions = fitsOptions.substr(pos3+1, fitsOptions.size());
+              pos3 = fitsOptions.find_first_of(';');
+          }
+//          *fLog << err << "fitsOptions: " << fitsOptions << endl;
+          keyValue = fitsOptions;
+          pos4 = keyValue.find('=');
+          if (pos4 == string::npos)
+          {
+              *fLog << err << "Error while parsing comment \"" << comment << "\" from variable " << parentVarName + dataMember->GetName() << endl;
+              return kFALSE;
+          }
+          key = Trim(keyValue.substr(0, pos4));
+          value = Trim(keyValue.substr(pos4+1, pos3));
+          fitsTokens[key] = value;
+//          *fLog << err << "key: " << key << " value: " << value << endl;
+      }
+
+      TString colName = parentVarName + dataMember->GetName();
+
+      if (fitsTokens.find("unit") != fitsTokens.end())
+          unit = fitsTokens["unit"];
+      if (fitsTokens.find("name") != fitsTokens.end())
+          colName = fitsTokens["name"];
+
+      //check for column veto
+      if (std::find(fVetoedColumns.begin(), fVetoedColumns.end(), colName.Data())!=fVetoedColumns.end())
+      {
+          *fLog << inf << "Vetoing column " << colName.Data() << endl;
+          continue;
+      }
+
+      // set the array size
+      TString dataType = dataMember->GetTrueTypeName();
+
+      uint32_t dataLength = 0;
+      switch (dataMember->GetArrayDim())
+      {
+          case 0:
+              dataLength = 1;
+              break;
+          case 1:
+              dataLength = dataMember->GetMaxIndex(0);
+              break;
+          default:
+              *fLog << err << "n-dimensional array should have been discarded already " << colName.Data();
+              break;
+      };
+//      if (dataLength == 0)
+//          continue;
+
+      if (dataMember->Property() & G__BIT_ISCLASS)
+         {
+         // special treatment for classes
+          uint32_t arraySize = 0;
+          TString typeName;
+
+          if (strncmp(dataMember->GetTrueTypeName(), "MArray", 6) == 0)
+          {
+              if (strcmp(dataMember->GetTrueTypeName(), "MArrayS*") == 0)
+              {
+                  typeName = "UShort_t";
+                  arraySize = (*((MArrayS**)((char*)baseAdr + dataMember->GetOffset())))->GetSize();
+                  InitSingleColumn(tableName,
+                                   arraySize,
+                                   typeName.Data(),
+                                   (char*)(*((MArrayS**)((char*)baseAdr + dataMember->GetOffset())))->GetArray(),
+                                   colName.Data(),
+                                   unit,
+                                   comment);
+              }
+              else if (strcmp(dataMember->GetTrueTypeName(), "MArrayB*") == 0)
+              {
+                      typeName = "UChar_t";
+                      arraySize = (*((MArrayB**)((char*)baseAdr + dataMember->GetOffset())))->GetSize();
+                      InitSingleColumn(tableName,
+                                     arraySize,
+                                     typeName.Data(),
+                                     (char*)(*((MArrayB**)((char*)baseAdr + dataMember->GetOffset())))->GetArray(),
+                                     colName.Data(),
+                                     unit,
+                                     comment);
+              }
+              else if (strcmp(dataMember->GetTrueTypeName(), "MArrayF*") == 0)
+              {
+                      typeName = "TFloat_t";
+                      arraySize = (*((MArrayF**)((char*)baseAdr + dataMember->GetOffset())))->GetSize();
+                      InitSingleColumn(tableName,
+                                     arraySize,
+                                     typeName.Data(),
+                                     (char*)(*((MArrayF**)((char*)baseAdr + dataMember->GetOffset())))->GetArray(),
+                                     colName.Data(),
+                                     unit,
+                                     comment);
+              }
+
+              else {
+                  *fLog << err << dataMember->GetTrueTypeName() << " not yet implemented." << endl;
+                  return kFALSE;
+              }
+
+
+              continue;
+          }
+         else if (strcmp(dataMember->GetTrueTypeName(), "TClonesArray") == 0)
+            {
+             *fLog << warn << "I'm skipping the TClonesArray for now" << endl;
+             continue;
+            // each TClonesArray requires a FITS table by itself.
+            MClonesArrayHelper * clHelper;
+
+            TClonesArray * cloneArray = (TClonesArray*)((char*)baseAdr + dataMember->GetOffset());
+            Bool_t status;
+            clHelper = new MClonesArrayHelper(cloneArray, fLog, status);
+            if (!status)   return status;
+
+            fClHelper[tableName].push_back(clHelper);
+
+            // add one column in the parent table of the TClonesArray to store the  
+            // number of entries in the TClonesArray.
+            InitSingleColumn(tableName,
+                             1,
+                             "UInt_t",
+                             clHelper->GetArraySizePtr(),
+                             colName.Data(),
+                             unit,
+                             comment);
+
+            // initialize the columns of the new FITS table, which will store the   
+            // data entries of the TClonesArray                                     
+            if (InitColumns(TString("noName"),
+                            colName + "_",
+                            fitsTable,
+                            clHelper->GetDataBuffer(),
+                            cloneArray->GetClass())
+                    == kFALSE)
+               return kFALSE;
+
+            // the columns are initialized. We can create the FITS table
+            if (clHelper->OpenFitsTable(GetFileName(), dataMember->GetName(), 
+                                       fOpenOption, fLog)                        == kFALSE)
+               return kFALSE;
+            }
+
+         else
+            {
+            // the current container has a variable of an other class. We create 
+            // also columns of this other class in the same table                
+            TClass * newClassDef = TClass::GetClass(dataMember->GetTrueTypeName(), kFALSE, kTRUE);
+            if (newClassDef)
+               {
+               if (InitColumns(tableName, colName + ".", fitsTable, (char*)baseAdr + dataMember->GetOffset(),
+                        newClassDef) == kFALSE)
+                  return kFALSE;
+               }
+            else
+               *fLog << warn << "Cannot write data of class " << colName + "." + dataMember->GetTrueTypeName() << endl;
+            }
+         continue;
+         } 
+
+         InitSingleColumn(tableName,
+                          dataLength,
+                          dataType.Data(),
+                          (char*)baseAdr + dataMember->GetOffset(),
+                          colName.Data(),
+                          unit,
+                          comment);
+
+      }
+   return kTRUE;
+}
+void MWriteFitsFile::InitSingleColumn(const TString& tableName,
+                                      uint32_t count,
+                                      const string& typeName,
+                                      void* dataPointer,
+                                      const string& columnName,
+                                      const string& unit,
+                                      const string& comment)
+{
+    if (!fTableObjectCreated[tableName])
+    {
+        *fLog << err << "ERROR: Cannot init column " << columnName << " before assigning object: " << tableName << endl;
+        return;
+    }
+    int typeFound = 0;
+    char typeChar = '0';
+    if ((typeName == "bool") || (typeName == "Bool_t") || (typeName == "L"))
+    {
+        typeChar = 'L';
+        typeFound++;
+    }
+    if ((typeName == "char") || (typeName == "Char_t") || (typeName == "S"))
+    {
+        typeChar = 'A';
+        typeFound++;
+    }
+    if ((typeName == "unsigned char") || (typeName == "UChar_t") || (typeName == "B"))
+    {
+        typeChar = 'A';
+//        *fLog << warn << "Converting unsigned char to char in fits file" << endl;
+        typeFound++;
+    }
+    if ((typeName == "short") || (typeName == "Short_t") || (typeName == "I"))
+    {
+        typeChar = 'I';
+        typeFound++;
+    }
+    if ((typeName == "unsigned short") || (typeName == "UShort_t") || (typeName == "U"))
+    {
+        typeChar = 'I';
+//        *fLog << warn << "Converting unsigned short to short in fits file" << endl;
+        typeFound++;
+    }
+    if ((typeName == "int") || (typeName == "Int_t") || (typeName == "V"))
+    {
+        typeChar = 'J';
+        typeFound++;
+    }
+    if ((typeName == "unsigned int") || (typeName == "UInt_t") || (typeName == "V"))
+    {
+        typeChar = 'J';
+//        *fLog << warn << "Converting unsigned int to int in fits file" << endl;
+        typeFound++;
+    }
+    if ((typeName == "long long") || (typeName == "Long64_t") || (typeName == "K"))
+    {
+        typeChar = 'K';
+        typeFound++;
+    }
+    if ((typeName == "unsigned long long") || (typeName == "ULong64_t") || (typeName == "W"))
+    {
+        typeChar = 'K';
+//        *fLog << warn << "Converting unsigned long to long in fits file" << endl;
+        typeFound++;
+    }
+    if ((typeName == "float") || (typeName=="TFloat_t") || (typeName == "E"))
+    {
+        typeChar = 'E';
+        typeFound++;
+    }
+    if ((typeName == "double") || (typeName == "TDouble_t") || (typeName == "D"))
+    {
+        typeChar = 'D';
+        typeFound++;
+    }
+//    if ((typeName == "char*") || (typeName == "A"))
+//    {
+//        typeFound++;
+//    }
+    if (typeFound != 1)
+    {
+        *fLog << err << "We have a problem with the data type: " << typeName << endl;
+        return;
+    }
+    uint32_t colWidth = 0;
+    switch (typeChar)
+    {
+        case 'L':  colWidth = 1*count; break;
+        case 'A':  colWidth = 1*count; break;
+        case 'B':  colWidth = 1*count; break;
+        case 'I':  colWidth = 2*count; break;
+        case 'J':  colWidth = 4*count; break;
+        case 'K':  colWidth = 8*count; break;
+        case 'E':  colWidth = 4*count; break;
+        case 'D':  colWidth = 8*count; break;
+        default:
+            *fLog << err << "ERROR: typeChar could not be resolved to an actual type" << endl;
+    };
+    //check for type remapping here
+    if (fBytesPerSamples.find(columnName) != fBytesPerSamples.end())
+    {
+        if (typeChar != 'A')
+        {
+            *fLog << err << "Attempt to remap type " << typeChar << " to " << fBytesPerSamples[columnName] << " is only allowed on bytes (variable name: " << columnName << "). Ignoring column" << endl;
+            return;
+        }
+        uint32_t bytesPerSample = fBytesPerSamples.find(columnName)->second;
+        if (colWidth%bytesPerSample != 0)
+        {
+            *fLog << err << "Type remapping cannot be done using " << bytesPerSample << " bytes per sample on an array of char of size " << colWidth << ". Ignoring column " << columnName << endl;
+            return;
+        }
+        switch (bytesPerSample)
+        {
+            case 1: count = count/1; typeChar = 'A'; break;
+            case 2: count = count/2; typeChar = 'I'; break;
+            case 4: count = count/4; typeChar = 'J'; break;
+            case 8: count = count/8; typeChar = 'K'; break;
+            default:
+                *fLog << err << "ERROR: num bytes per sample = " << bytesPerSample << " should have been forbidden already" << endl;
+        }
+
+    }
+
+    fDataPointers[tableName].push_back(dataPointer);
+    fTypeChars[tableName].push_back(typeChar);
+    fColSizes[tableName].push_back(count);
+    fColWidth[tableName].push_back(colWidth);
+
+    //FIXME ofits does not allow for much liberty regarding the size of the column names.
+    //Truncating them badly here, will probably cause other problems -> Modify ofits.h instead
+    string truncatedName=columnName.substr((columnName.size()>40)?columnName.size()-40:0,columnName.size());
+    string truncatedComment = comment.substr((comment.size()>10)?comment.size()-10:0,comment.size());
+//    *fLog << warn << "In table " << tableName << " Adding column |" << truncatedName << "| |" << truncatedComment << "| |" << count << "| |" << typeChar;
+//    *fLog << warn << "| Real: "<< columnName << " comment: " << comment << endl;
+    fFitsTables[tableName]->AddColumn(count, typeChar, truncatedName, unit, truncatedComment);
+}
+
+void MWriteFitsFile::writeOneRow(const TString& tableName)
+{
+    if (!fTableHeaderWritten[tableName])
+    {
+        for (vector<ofits::Key>::const_iterator it = fHeaderKeys.begin(); it != fHeaderKeys.end(); it++)
+            fFitsTables[tableName]->SetRaw(it->key, it->value, it->comment);
+        fFitsTables[tableName]->WriteTableHeader(tableName.Data());
+        fTableHeaderWritten[tableName] = true;
+    }
+    if (!fTableObjectCreated[tableName])
+    {
+        *fLog << err << "This is not good. Please initialize the fits table before writing to it: " << tableName << endl;
+        return;
+    }
+    //first calculate the size of one row
+    uint32_t rowWidth = 0;
+    for (uint32_t i=0;i<fTypeChars[tableName].size();i++)
+        rowWidth += fColWidth[tableName][i];
+    unsigned char* tempBuffer = new unsigned char[rowWidth];
+    //then copy the data to be written contiguously
+    uint32_t bytesCounter = 0;
+    for (uint32_t i=0;i<fDataPointers[tableName].size();i++)
+    {
+        memcpy(&tempBuffer[bytesCounter], fDataPointers[tableName][i], fColWidth[tableName][i]);
+        bytesCounter+=fColWidth[tableName][i];
+    }
+    if (fFitsTables[tableName]->WriteRow(tempBuffer, bytesCounter) == false)
+        *fLog << err << "Error while writing to FITS table " << tableName << endl;
+    else
+        fFitsTables[tableName]->FlushNumRows();
+
+    delete[] tempBuffer;
+}
+Bool_t MWriteFitsFile::ReInit(MParList *pList)
+{
+   if (fRule.Length() == 0)
+      // there is not rule defined. We keep the old file
+      return MWriteFile::ReInit(pList);
+
+   MRead *read = (MRead*)pList->FindTask("MRead");
+   if (!read)
+   {
+       *fLog << err;
+       *fLog << "ERROR: No Task 'MRead' found in the tasklist.  This task is" << endl;
+       *fLog << "  necessary to  get the filename.  Without a read-filename" << endl;
+       *fLog << "  no output-filename can be created... abort." << endl;
+       *fLog << endl;
+       return kFALSE;
+   }
+
+
+   // close the current files
+   CloseTopLevelGroup();
+   for (std::map<TString,ofits*>::iterator it=fFitsTables.begin(); it!=fFitsTables.end(); it++)
+   {
+       (it->second)->close();
+       delete it->second;
+   }
+   fFitsTables.clear();
+   fDataPointers.clear();
+   fTypeChars.clear();
+   fColSizes.clear();
+   fColWidth.clear();
+   fTableObjectCreated.clear();
+   fTableHeaderWritten.clear();
+   DeleteArrayHelper();
+   fClHelper.clear();
+
+   // get new filename
+   const TString readFileName = read->GetFullFileName();
+   const TString newname = MWriteRootFile::SubstituteName(fRule, readFileName);
+
+   // create new files
+   OpenTopLevelGroup(newname.Data());
+   if (!IsFileOpen())
+      return kFALSE;
+
+
+   MRawRunHeader* header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+   SetupHeaderKeys(*header);
+
+   if (GetContainer(pList) == kFALSE)
+      return kFALSE;
+
+   // do, what has to be done in ReInit.
+   return MWriteFile::ReInit(pList);
+
+}
+
+void MWriteFitsFile::DeleteArrayHelper()
+{
+   map<TString, list<MArrayHelperBase *> >::iterator i_helper1 = fClHelper.begin();
+   while (i_helper1 != fClHelper.end())
+      {
+      list<MArrayHelperBase *>::iterator i_helper2 = i_helper1->second.begin();
+      while(i_helper2 != i_helper1->second.end())
+         {
+         delete *i_helper2;
+
+         i_helper2++;
+         }
+
+      i_helper1++;
+      }
+}
Index: branches/Mars_McMismatchStudy/mfileio/MWriteFitsFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteFitsFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteFitsFile.h	(revision 17960)
@@ -0,0 +1,276 @@
+#ifndef MARS_MWreitFitsFile
+#define MARS_MWreitFitsFile
+
+#include <list>
+#include <vector>
+#include <map>
+
+#ifndef ROOT_TClass
+#include <TClass.h>
+#endif
+
+#ifndef MARS_MLogManip
+#include "MLogManip.h"
+#endif
+
+#ifndef MARS_MWriteFile
+#include "MWriteFile.h"
+#endif
+
+#ifndef MARS_MTopFitsGroup
+#include "MTopFitsGroup.h"
+#endif
+
+#ifndef MARS_MFitsArray
+#include "MFitsArray.h"
+#endif
+
+#ifndef MARS_MRawRunHeader
+#include "MRawRunHeader.h"
+#endif
+
+class MRawRunHeader;
+
+///////////////////////////////////////////////////////////////////////////////
+// Information of one MParContainer, which data should be written into all or  
+// just a few columns of one FITS table                                        
+class MFitsSubTable
+{
+   // the container, which data should be written to the FITS sub-table.   
+   MParContainer  *fContainer; 
+
+   // used only if the Container is defined by its name.                   
+   // if kTRUE  must exist in the MParList of the program                  
+   // if kFALSE the container is ignored. if it is not in the              
+   //           MParList of the program                                    
+   Bool_t         fMust;
+
+public:
+   MFitsSubTable( Bool_t must)
+      : fContainer(NULL), fMust(must)
+      {}
+
+   MFitsSubTable(MParContainer * container,  Bool_t must)
+      : fContainer(container),  fMust(must)
+      {}
+
+  
+   MFitsSubTable(const MFitsSubTable & subTable)
+      : fContainer(subTable.fContainer), fMust(subTable.fMust)
+      {}
+
+   Bool_t            MustHave()           {return fMust;}
+   MParContainer *   GetContainer()       {return fContainer;}
+   void              SetContainer(MParContainer * cont)
+                                          {fContainer = cont;}
+
+};
+
+
+
+///////////////////////////////////////////////////////////////////////////////
+// A class to write data of MParContainer into FITS files.                     
+class MWriteFitsFile : public MWriteFile
+{
+private:
+   // all (global) currently open top FITS groups.                      
+   // Note: several instances of MWriteFitsFile can write to the same   
+   //       top level FITS group (a top level FITS group corresponds to 
+   //       one ROOT file)                                              
+   static std::map<MUniqueFileId, MTopFitsGroup>    fTopFitsGroups;
+
+   // pointer to the top level FITS group of this instance              
+   std::map<MUniqueFileId, MTopFitsGroup>::iterator iTopFitsGroup;
+
+   // the key (TString) of following maps is the FITS table name, which 
+   // corresponds to one TTree                                          
+
+   // all main FITS table. Children tables to store data of             
+   // TClonesArray are not in this map.
+   //ETIENNE ofits objects cannot be copied. So store pointers instead
+   std::map<TString, ofits*>                       fFitsTables;
+
+   // all information needed to write data of TClonesArray to their      
+   // own FITS table. Note: one parent FTIS table may have several       
+   // children tables, each for one TClonesArray.                        
+   std::map<TString, std::list<MArrayHelperBase *> >    fClHelper;
+
+   // all information about the MParContainer, which data are stored     
+   // in the same FITS table. The key of map<TString, MFitsSubTable>     
+   // is the class name of the MParContainer                             
+   std::map<TString, std::map<TString, MFitsSubTable> > fSubTables;
+
+   std::map<TString, std::vector<void*> >    fDataPointers;
+   std::map<TString, std::vector<char> >     fTypeChars;
+   std::map<TString, std::vector<uint32_t> > fColSizes;
+   std::map<TString, std::vector<uint32_t> > fColWidth;
+   std::map<TString, bool> fTableObjectCreated;
+   std::map<TString, bool> fTableHeaderWritten;
+
+   void DeleteArrayHelper();
+
+   // rule to construct an output file-name from the input-filename      
+   TString fRule;  
+
+   TString fOpenOption; // RECREATE or NEW
+   TString fGroupName;  // name of top level group
+   TString fTitle;      // title of top level group
+
+   void OpenTopLevelGroup(const char * fname);
+   void CloseTopLevelGroup();
+
+   Bool_t InitColumns(const TString & tableName,
+                      const TString & parentVarName,
+                      ofits* fitsTable,
+                      void * baseAdr,
+                      TClass * classDef);
+   void InitSingleColumn(const TString& tableName,
+                         uint32_t count,
+                         const std::string& typeName,
+                         void* dataPointer,
+                         const std::string& columnName,
+                         const std::string& unit,
+                         const std::string& comment);
+   void writeOneRow(const TString& tableName);
+   void InitAttr(const char* attrName,
+                 const char* dataType,
+                 void* var,
+                 const char* unit=NULL,
+                 const char* comment=NULL,
+                 ofits* outFile=NULL);
+
+   // MWrite
+   Bool_t      IsFileOpen() const  
+                              {return iTopFitsGroup != fTopFitsGroups.end();}
+   Bool_t      CheckAndWrite();
+   Bool_t      GetContainer(MParList *pList);
+   const char *GetFileName() const;
+
+   Int_t       PreProcess(MParList *pList);
+   Int_t       PostProcess();
+
+   void        SetupHeaderKeys(MRawRunHeader &header);
+
+   //Header keys related stuff
+   template<typename _T>
+   std::string GetFitsString(const _T& value)
+   {
+       std::ostringstream returnVal;
+       std::string typeName = typeid(_T).name();
+       if (typeName == "i" || typeName == "j" || //int
+           typeName == "s" || typeName == "t" || //short
+           typeName == "l" || typeName == "m" || //long
+           typeName == "x" || typeName == "y")   //long long
+           returnVal << value;
+
+       if (typeName == "b")
+       {
+           if (value) returnVal << "T"; else returnVal << "F";
+       }
+       if (typeName == "Ss" || typeName == "PKc" ||
+           (typeName.size() >= 4 && typeName[0] == 'A' && typeName[typeName.size()-1] == 'c' && typeName[typeName.size()-2] == '_'))
+       {
+           returnVal << value;
+           std::string temp = returnVal.str();
+           returnVal.str("");
+           for (std::string::iterator c=temp.begin(); c<temp.end(); c++)
+               if (*c=='\'')
+                   temp.insert(c++, '\'');
+           returnVal << "'" << temp << "'";
+       }
+       if (returnVal.str() == "")
+           *fLog << warn << "WARNING: could not construct fits string from \"" << value << "\" typename: " << typeName << std::endl;
+       return returnVal.str();
+   }
+
+public:
+   template<typename _T>
+   bool SetHeaderKey(const std::string& key,
+                     const _T& value,
+                     const std::string& comment="")
+   {
+       //check if header was already written
+       for (std::map<TString, bool>::iterator it=fTableHeaderWritten.begin(); it!= fTableHeaderWritten.end(); it++)
+           if (it->second == true)
+               return false;
+       //headers were not written yet. Add one key
+       std::vector<ofits::Key>::iterator it = fHeaderKeys.begin();
+       //check if the value had been set beforel
+       for (;it!=fHeaderKeys.end();it++)
+       {
+           if (it->key == key)
+           {
+               it->value = GetFitsString(value);
+               it->comment = comment;
+               break;
+           }
+       }
+       //did we find the key ?
+       if (it == fHeaderKeys.end())
+       {//no ? add it !
+           ofits::Key temp;
+           temp.key = key;
+           temp.value = GetFitsString(value);
+           temp.comment = comment;
+           fHeaderKeys.push_back(temp);
+       }
+       return true;
+   }
+private:
+   std::vector<ofits::Key> fHeaderKeys;
+
+   std::string Trim(const std::string &str);
+
+   // MTask
+   Bool_t ReInit(MParList *pList);
+
+   std::vector<std::string> fVetoedColumns;
+   std::map<std::string, uint32_t> fBytesPerSamples;
+
+
+public:
+
+   //Veto a type-mapping functions and variables
+   Bool_t VetoColumn(const std::string& colName);
+   Bool_t SetBytesPerSample(const std::string& colName, uint32_t numBytes);
+
+   enum FILE_MODE {
+      kMultiFiles,
+      kSingleFile
+      } ;
+
+    MWriteFitsFile(const char *fname,
+                   FILE_MODE fileMode = kMultiFiles,
+                   const Option_t *opt="RECREATE",
+                   const char *name=NULL,
+                   const char *title=NULL);
+    //Similar contructor to what MWriteRootFiles takes.
+    //Some of the args are not used: comp as they does not make sense in FITS
+    MWriteFitsFile(const Int_t comp,
+                   const char* rule,
+                   const Option_t* option="RECREATE",
+                   const char* fTitle="Untitled",
+                   const char* name=NULL,
+                   const char* title=NULL);
+
+   ~MWriteFitsFile();
+
+
+   void AddContainer(const char *cName,   const char *tName=NULL, Bool_t must=kTRUE, UInt_t max=0);
+   void AddContainer(MParContainer *cont, const char *tName=NULL, Bool_t must=kTRUE, UInt_t max=0);
+
+
+   void AddTree(const char *name, Bool_t force=kTRUE)
+   {
+       AddContainer(Form("MReport%s", name), name, force);
+       AddContainer(Form("MTime%s", name),   name, force);
+   }
+
+   ClassDef(MWriteFitsFile, 0)   
+};
+//Specializations for float and doubles (because of the precision handling, I could not deal with it in the main function
+template<>
+std::string MWriteFitsFile::GetFitsString(const double& value);
+template<>
+std::string MWriteFitsFile::GetFitsString(const float& value);
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/MWriteRootFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteRootFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteRootFile.cc	(revision 17960)
@@ -0,0 +1,1195 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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: Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MWriteRootFile
+//
+// This is a writer to store several containers to a root file.
+// The containers are added with AddContainer.
+// To understand how it works, see base class MWriteFile
+//
+// Warning: Look at the Warning in MTaskList.
+//
+// There is a special mode of operation which opens a new file for each new
+// file read by the reading task (opening the new file is initiated by
+// ReInit()) For more details see the corresponding constructor.
+//
+// Memory based trees
+// ------------------
+// It is possible to store the data into memory (TTrees) instead of
+// writing the data into a file. To do this either call the default
+// constructor or specify 'memory' as option in the constructor.
+//
+// Afterwards the tree can be found using
+// gROOT->GetListOfFiles()->FindObject("treename")
+//
+// Currently(!) the tree is not deleted at all! Please make sure to
+// delete it if it is not used anymore - otherwise you could wast a LOT
+// of memory. Please consider that this behaviour might change in the
+// future.
+//
+// Such trees are usefull if you want to use more basic root-tools
+// like TMultiLayerPerceptron or TEventList.
+//
+// If you want to process such memory based Trees using Mars make sure,
+// that you don't need data from the RunHeader tree because you can
+// only use MReadTree but not MReadMarsFile with such a tree.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MWriteRootFile.h"
+
+#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+#include <TPRegexp.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRead.h"
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+ClassImp(MRootFileBranch);
+ClassImp(MWriteRootFile);
+
+using namespace std;
+
+const TString MWriteRootFile::gsDefName  = "MWriteRootFile";
+const TString MWriteRootFile::gsDefTitle = "Task which writes a root-output file";
+
+void MWriteRootFile::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    //
+    // Set the Arrays the owner of its entries. This means, that the
+    // destructor of the arrays will delete all its entries.
+    //
+    fBranches.SetOwner();
+    fCopies.SetOwner();
+
+    //
+    // Believing the root user guide, TTree instances are owned by the
+    // directory (file) in which they are. This means we don't have to
+    // care about their destruction.
+    //
+    //fTrees.SetOwner();
+
+    gROOT->GetListOfCleanups()->Add(this); // To remove fOut if deleted
+    SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+// Try to get the file from gROOT->GetListOfFiles. (In case the file name
+// is /dev/null we look for a file with name /dev/null and the given title)
+// If it is found fOut is set to it and returned.
+// Otherwise a new file is opened and returned.
+//
+TFile *MWriteRootFile::OpenFile(const char *name, Option_t *option, const char *title, Int_t comp)
+{
+    TFile *file = 0;
+
+    if (TString(name)=="/dev/null")
+    {
+        TIter Next(gROOT->GetListOfFiles());
+        TObject *obj = 0;
+        while ((obj=Next()))
+            if (TString(obj->GetName())=="/dev/null" && TString(obj->GetTitle())==title)
+            {
+                *fLog << inf2 << "Found open file '/dev/null' <Title=" << title << ">... re-using." << endl;
+                file = dynamic_cast<TFile*>(obj);
+                break;
+            }
+    }
+    else
+    {
+        file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(name));
+
+        // If the file was not found with its name try its expanded name
+        if (!file)
+        {
+            TString fqp(name);
+            gSystem->ExpandPathName(fqp);
+            file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(fqp));
+        }
+
+        if (file)
+        {
+            *fLog << inf2;
+            *fLog << "Found open file '" << name << "'... re-using." << endl;
+            *fLog << inf3;
+            *fLog << "Make sure that you do NOT write to trees which are" << endl;
+            *fLog << "scheduled already by a different MWriteRootFile..." << endl;
+        }
+    }
+
+    if (!file)
+    {
+        file = new TFile(name, option, title, comp);
+        if (!file->IsOpen())
+        {
+            delete file;
+            return NULL;
+        }
+
+        *fLog << inf3 << "File '" << name << "' ";
+        if (!TString(title).IsNull())
+            *fLog << "<Title=" << title << "> ";
+        *fLog << "opened [" << option << "]" << endl;
+
+        file->SetOption(option); // IMPORTANT!
+        file->SetBit(kMustCleanup);
+        ResetBit(kIsNotOwner);
+        return file;
+    }
+
+    fOut = file;
+    fOut->SetBit(kMustCleanup);
+    SetBit(kIsNotOwner);
+
+    return fOut;
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It is there to support some root stuff.
+// Don't use it.
+//
+MWriteRootFile::MWriteRootFile() : fOut(NULL)
+{
+    Init();
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this constructor to run in a special mode.
+//
+// In this mode for each input file a new output file is written. This
+// happens in ReInit.
+//
+// comp:        Compression Level (see TFile, TBranch)
+// rule:        Rule to create output file name (see SubstituteName())
+// overwrite:   Allow newly created file to overwrite old files ("RECREATE")
+// ftitle:      File title stored in the file (see TFile)
+// name, title: Name and title of this object
+//
+// Until the first file is opened a dummy file with name /dev/null is
+// opened to allow creation of trees and branches in the file.
+// To distinguish between different /dev/null-files the given title is used.
+//
+MWriteRootFile::MWriteRootFile(const Int_t comp,
+                               const char *rule,
+                               const Option_t *option,
+                               const char *ftitle,
+                               const char *name,
+                               const char *title) : fSplitRule(rule)
+{
+    Init(name, title);
+
+    const Bool_t hasrule = fSplitRule.BeginsWith("s/") && fSplitRule.EndsWith("/");
+    if (!hasrule)
+        fSplitRule = "";
+
+    //
+    // Open a TFile in dummy mode! This is necessary to be able to create
+    // the trees and branches, which are then (in ReInit) moved to
+    // a valid file. (Stupid workaround - but does a good job)
+    //
+    const TString fname = hasrule ? "/dev/null" : rule;
+    fOut = OpenFile(fname, option, ftitle, comp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the name of the root file. You can also give an option ("UPDATE"
+// and "RECREATE" would make sense only) as well as the file title and
+// compression factor. To a more detaild description of the options see
+// TFile.
+//
+// To create a memory based TTree use
+//   fname  = name of TTree
+//   option = "memory"
+// Make sure you do not read from a tree with the same name!
+//
+MWriteRootFile::MWriteRootFile(const char *fname,
+                               const Option_t *option,
+                               const char *ftitle,
+                               const Int_t comp,
+                               const char *name,
+                               const char *title) : fOut(NULL)
+{
+    Init(name, title);
+
+    TString opt(option);
+    opt.ToLower();
+
+    //
+    // Check if we are writing to memory
+    //
+    if (opt=="memory")
+    {
+        fSplitRule = fname;
+        return;
+    }
+
+    //
+    // If no name is given we open the TFile in some kind of dummy mode...
+    //
+    TString str(fname);
+    if (str.IsNull())
+    {
+        fOut = new TFile("/dev/null", "READ", ftitle, comp);
+        fOut->SetBit(kMustCleanup);
+        return;
+    }
+
+    if (!str.EndsWith(".root", TString::kIgnoreCase))
+        str += ".root";
+
+    //
+    // Open the rootfile
+    //
+    fOut = OpenFile(str, opt, ftitle, comp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Prints some statistics about the file to the screen. And closes the file
+// properly.
+//
+void MWriteRootFile::Close()
+{
+    //
+    // Print some statistics to the looging out.
+    //
+    if (fOut && !TestBit(kIsNotOwner))
+    {
+        Print();
+
+        //
+        // If the file is still open (no error) write the keys. This is necessary
+        // for appearance of the all trees and branches.
+        //
+        if (IsFileOpen())
+            fOut->Write();
+
+        //
+        // Delete the file. This'll also close the file (if open)
+        //
+        *fLog << inf3 << "Closing file " << fOut->GetName() << "." << endl;
+        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
+        //
+    }
+
+    fOut = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// call Close()
+//
+MWriteRootFile::~MWriteRootFile()
+{
+    Close();
+}
+
+// --------------------------------------------------------------------------
+//
+// Prints all trees with the actually number of written entries to log-out.
+//
+void MWriteRootFile::Print(Option_t *) const
+{
+    if (!fOut)
+        return;
+
+    *fLog << all << underline << "File: " << GetFileName() << dec << endl;
+
+    Bool_t cont = kFALSE;
+
+    TObject *obj;
+    TIter NextBranch(&fBranches);
+    while ((obj=NextBranch()))
+    {
+        MRootFileBranch *b = (MRootFileBranch*)obj;
+
+        if (!b->GetTree() || b->GetTree()->TestBit(kIsNewTree))
+            continue;
+
+        TBranch *branch = b->GetBranch();
+
+        TString name = b->GetTree()->GetName();
+        name += '.';
+        name += branch->GetName();
+
+        *fLog << " + " << name.Strip(TString::kTrailing, '.') << ": \t" << (ULong_t)branch->GetEntries() << " entries." << endl;
+        cont = kTRUE;
+    }
+
+    TTree *t = NULL;
+    TIter NextTree(&fTrees);
+    while ((t=(TTree*)NextTree()))
+        if (t->TestBit(kIsNewTree))
+        {
+            *fLog << " + " << t->GetName() << ": \t" << (ULong_t)t->GetEntries() << " entries." << endl;
+            cont = kTRUE;
+        }
+
+    TIter NextKey(fOut->GetList());
+    
+    while ((obj=NextKey()))
+    {
+        if (!obj->InheritsFrom(TTree::Class()))
+            continue;
+
+        if (fTrees.FindObject(obj) && obj->TestBit(kIsNewTree))
+            continue;
+
+        *fLog << " - " << obj->GetName() << ": \t" << (ULong_t)((TTree*)obj)->GetEntries() << " entries." << endl;
+        cont = kTRUE;
+    }
+
+    if (!cont)
+        *fLog << "  No contents." << 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, Long64_t max)
+{
+    if (!fOut && !tname)
+        tname = fSplitRule;
+
+    TIter Next(&fBranches);
+    TObject *o=0;
+    while ((o=Next()))
+        if (TString(o->GetName())==TString(tname) && TString(o->GetTitle())==TString(cname))
+        {
+            *fLog << warn;
+            *fLog << "WARNING - Container '" << cname << "' in Tree '" << tname << "' already scheduled... ignored." << endl;
+            return;
+        }
+
+    //
+    // create a new entry in the list of branches to write and
+    // add the entry to the list.
+    //
+    MRootFileBranch *entry = new MRootFileBranch(AddSerialNumber(cname), tname, must, max);
+    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, Long64_t max)
+{
+    if (!fOut && !tname)
+        tname = fSplitRule;
+
+    TIter Next(&fBranches);
+    TObject *o=0;
+    while ((o=Next()))
+        if (TString(o->GetName())==TString(tname) &&
+            static_cast<MRootFileBranch*>(o)->GetContainer()==cont)
+        {
+            *fLog << warn;
+            *fLog << "WARNING - Container " << cont << " in Tree '" << tname << "' already scheduled... ignored." << endl;
+            return;
+        }
+
+    //
+    // create a new entry in the list of branches to write and
+    // add the entry to the list.
+    //
+    MRootFileBranch *entry = new MRootFileBranch(cont, tname, must, max);
+    fBranches.AddLast(entry);
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to copy a full tree (or some branches of some trees)
+// completely from one file to another one you can use this
+//
+void MWriteRootFile::AddCopySource(const char *tname, const char *bname, Bool_t force)
+{
+    TObject *obj = new TNamed(tname, bname?bname:"*");
+    if (force)
+        obj->SetBit(kForced);
+
+    fCopies.Add(obj);
+    fCopies.Sort();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new Container to list of containers which should be written to the
+// file. Give the pointer to the container. tname is the name of the tree to
+// which the container should be written (Remark: one tree can hold more than
+// one container). The default is the same name as the container name.
+// You can slso specify a title for the tree. This is only
+// used the first time this tree in 'mentioned'. As default the title
+// is the name of the tree.
+//
+Bool_t MWriteRootFile::GetContainer(MParList *pList)
+{
+    //
+    // loop over all branches which are 'marked' as branches to get written.
+    //
+    MRootFileBranch *entry;
+
+    TIter Next(&fBranches);
+    while ((entry=(MRootFileBranch*)Next()))
+    {
+        //
+        // Get the pointer to the container. If the pointer is NULL it seems,
+        // that the user identified the container by name.
+        //
+        MParContainer *cont = entry->GetContainer();
+        if (!cont)
+        {
+            //
+            // Get the name and try to find a container with this name
+            // in the parameter list.
+            //
+            const char *cname = entry->GetContName();
+            cont = (MParContainer*)pList->FindObject(cname);
+            if (!cont)
+            {
+                //
+                // No corresponding container is found
+                //
+                if (entry->MustHave())
+                {
+                    *fLog << err << "Cannot find parameter container '" << cname << "'." << endl;
+                    return kFALSE;
+                }
+
+                *fLog << inf2 << "Unnecessary parameter container '" << cname << "' not found..." << endl;
+                delete fBranches.Remove(entry);
+                continue;
+            }
+
+            //
+            // The container is found. Put the pointer into the entry.
+            //
+            entry->SetContainer(cont);
+        }
+
+        //
+        // Get container name, tree name and tree title of this entry.
+        //
+        const char *cname = cont->GetName();
+        const char *tname = entry->GetName();
+        const TString ttitle(Form("Tree containing %s", cont->GetDescriptor().Data()));
+
+        //
+        // if the tree name is NULL this idetifies it to use the default:
+        // the container name.
+        //
+        if (tname[0] == '\0')
+            tname = cname;
+
+        //
+        // Check if the tree is already existing (part of the file or memory)
+        //
+        TTree *tree = fOut ? (TTree*)fOut->Get(tname) : dynamic_cast<TTree*>(gROOT->FindObject(tname));
+        if (!fOut && tree)
+        {
+            if (tree->GetCurrentFile())
+            {
+                *fLog << err;
+                *fLog << "ERROR - You are trying to write data into a memory stored root tree," << endl;
+                *fLog << "        because you either called the default constructor  or  have" << endl;
+                *fLog << "        instantiated MWriteRootFile using the write option 'memory'." << endl;
+                *fLog << "        This  tree   '" << tname << "'   is  already  existing  in" << endl;
+                *fLog << "        memory  (gROOT->FindObject)  and is already belonging  to a" << endl;
+                *fLog << "        file (" << tree->GetCurrentFile()->GetName() << ")." << endl;
+                *fLog << "        This can  - for example -  happen if you are reading from a" << endl;
+                *fLog << "        tree with the same name.  The easiest solution in this case" << endl;
+                *fLog << "        is to change the name of the tree you want to write to." << endl;
+                *fLog << endl;
+                return kFALSE;
+            }
+            *fLog << inf << "Tree '" << tname << "' found already in Memory... using." << endl;
+        }
+
+        if (!tree)
+        {
+            //
+            // if the tree doesn't exist create a new tree. Use the tree
+            // name as title if title is NULL.
+            // And add the tree to the list of trees
+            //
+            TDirectory *save = gDirectory;
+            if (fOut)
+                fOut->cd();
+            else
+                gROOT->cd();
+
+            tree = new TTree(tname, ttitle, fOut ? 99 : 1);
+            fTrees.AddLast(tree);
+
+            //
+            // If the tree does not already exist in the file mark this
+            // tree as a branch created by MWriteRootFile
+            //
+            tree->SetBit(kIsNewTree);
+
+            *fLog << inf << "Tree " << tname << " created in " << gDirectory->GetName() << endl;
+
+            gDirectory = save;
+        }
+
+        //
+        // In case the file is opened as 'UPDATE' the tree may still not
+        // be in the list. Because it neither was created previously,
+        // nor this time, so the corresponding entries is marked as a
+        // single branch to be filled. --> Add it to the list of trees.
+        //
+        if (!fTrees.FindObject(tree))
+            fTrees.AddLast(tree);
+
+        //
+        // Now we have a valid tree. Search the list of trees for this tree
+        // Add a pointer to the entry in the tree list to this branch-entry
+        //
+        entry->SetTree(tree);
+
+        TString branchname(cname);
+        branchname.Append(".");
+
+        //
+        // Try to get the branch from the file. 
+        // If the branch already exists the user specified one branch twice.
+        //
+        TBranch *branch = tree->GetBranch(branchname);
+        if (branch)
+        {
+            *fLog << inf << "Branch '" << cname << "' already existing... updating." << endl;
+            branch->SetAddress(entry->GetAddress());
+
+            if (!fSplitRule.IsNull() && fOut)
+            {
+                *fLog << warn << endl;
+                *fLog << "WARNING: You are updating an existing branch. For this case" << endl;
+                *fLog << "         file-splitting mode  is  not  allowed...  disabled!" << endl;
+                *fLog << endl;
+                fSplitRule = "";
+            }
+        }
+        else
+        {
+            //
+            // Create a new branch in the actual tree. The branch has the name
+            // container name. The type of the container is given by the
+            // ClassName entry in the container. The Address is the address of a
+            // pointer to the container (gotten from the branch entry). As
+            // Basket size we specify a (more or less) common default value.
+            // The containers should be written in Splitlevel=1
+            //
+            *fLog << inf << "Creating Branch '" << cname << "' ";
+            if ((TString)cname!=(TString)cont->ClassName())
+                *fLog << "[" << cont->ClassName() << "] ";
+            *fLog << "in tree " << tree->GetName() << "... " << flush;
+
+            branch = tree->Branch(branchname, cont->ClassName(), entry->GetAddress());
+
+            //
+            // If the branch couldn't be created we have a problem.
+            //
+            if (!branch)
+            {
+                *fLog << endl;
+                *fLog << err << "Unable to create branch '" << cname << "'." << endl;
+                return kFALSE;
+            }
+
+            *fLog << "done." << endl;
+
+            if (!tree->TestBit(kIsNewTree) && !fSplitRule.IsNull())
+            {
+                *fLog << warn << endl;
+                *fLog << "WARNING:   You  have  created  a new branch  in  an existing tree." << endl;
+                *fLog << "     For this case file-splitting mode is not allowed... disabled!" << endl;
+                *fLog << endl;
+                fSplitRule= "";
+            }
+        }
+
+        //
+        // Tell the entry also which branch belongs to it (this is necessary
+        // for branches belonging to already existing tree, UPDATE-mode)
+        //
+        entry->SetBranch(branch);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks all given containers (branch entries) for the write flag.
+// If the write flag is set the corresponding Tree is marked to get filled.
+// All Trees which are marked to be filled are filled with all their
+// branches.
+// In case of a file opened in 'UPDATE' mode, single branches can be
+// filled, too. WARNING - for the moment there is no check whether
+// you filled the correct number of events into the branch, so that
+// each of the other branches in the tree has the correct corresponding
+// number of new entries in the new branch!
+// Be carefull: If only one container (corresponding to a branch) of a tree
+// has the write flag, all containers in this tree are filled!
+//
+Bool_t MWriteRootFile::CheckAndWrite()
+{
+    // This is the special case if we only copy a tre but do not
+    // write containers to it
+    const Int_t n = fTrees.GetEntriesFast();
+    if (n==0)
+        return kTRUE;
+
+    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 (b->GetMaxEntries()==b->GetTree()->GetEntries())
+            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 - MWriteRootFile: Zero bytes written to branch '" << b->GetBranch()->GetName() << "'... abort." << endl;
+                return kFALSE;
+            }
+        }
+    }
+
+    //
+    // Loop over all tree entries
+    //
+    for (int idx=0; idx<n; idx++)
+    {
+        TTree *t = (TTree*)fTrees[idx];
+        if (!t)
+        {
+            *fLog << err << "ERROR - MWriteRootFile: The Tree with index " << idx << endl;
+            *fLog << " in fTrees is NULL. This should never happen. Please send" << endl;
+            *fLog << " a bug report." << endl;
+            return kFALSE;
+        }
+
+        //
+        // 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 - MWriteRootFiole: Zero bytes written to tree '" << t->GetName() << "'... abort." << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // If we are writing into memory we don't split into seperate files
+    //
+    if (!fOut || TestBit(kIsNotOwner))
+        return kTRUE;
+
+    //
+    // For more information see TTree:ChangeFile()
+    //
+    TTree *t0 = (TTree*)fTrees[0];
+    if (!t0 || fOut==t0->GetCurrentFile())
+        return kTRUE;
+
+    // FIXME: THIS IS EMITTED FOR ALL CONSEQUTIVE EVENTS!
+    *fLog << warn << endl;
+    *fLog << "WARNING - MWriteRootFile:   Root's  TTree/TFile   has  opened   a  new  file" << endl;
+    *fLog << "  automatically.  You can change this behaviour using TTree::SetMaxTreeSize." << endl;
+    *fLog << "  You won't be able to read splitted  files  correctly with MReadMarsFile if" << endl;
+    *fLog << "  they have more than one entry in 'RunHeaders' or you try to read more than" << endl;
+    *fLog << "  one of such sequences at once." << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open a new file with the name fname. Move all trees and branches from the
+// old file to the new file.
+//
+Bool_t MWriteRootFile::ChangeFile(const char *fname)
+{
+    const Int_t   compr = fOut ? fOut->GetCompressionLevel() : 0;
+    const TString title = fOut ? fOut->GetTitle()            : "";
+    const TString opt   = fOut ? fOut->GetOption()           : "";
+
+    // Open new file with old setup
+    TFile *newfile = OpenFile(fname, opt, title, compr);
+    if (newfile && newfile==fOut)
+    {
+        *fLog << inf << "Found open file '" << fname << "'... using." << endl;
+        return kTRUE;
+    }
+    if (!newfile)
+    {
+        *fLog << err << "ERROR - Cannot open new file '" << fname << "'" << endl;
+         return kFALSE;
+    }
+
+    if (!fOut)
+    {
+        *fLog << err << "ERROR - MWriteRootFile::ChangeFile... something went terribly wrong!" << endl;
+        *fLog <<        "        fname: " << fname << endl;
+        *fLog <<        "        Please start debugging!" << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Open new file " << fname << " (Title=" << title << ", Option=" << opt << ", Compression=" << compr << ")" << endl;
+
+    // Print statistics of old file
+    const TString n = GetFileName();
+    if (!n.IsNull() && n!=TString("/dev/null"))
+        Print();
+
+    if (fOut->IsOpen())
+        fOut->Write();
+
+    // Move all trees from the old file to the new file
+    TObject *obj=0;
+    while ((obj = fOut->GetList()->First()))
+    {
+        // Remove obj from old file (otherwise deleting
+        // the old file will delete the objs)
+        fOut->GetList()->Remove(obj);
+
+        // If this is not a tree do nothing.
+        if (!obj->InheritsFrom(TTree::Class()))
+            continue;
+
+        // process all trees in the old file
+        TTree *t = (TTree*)obj;
+
+        // reset and move to new file (this is done implicitly for all branches)
+        t->Reset();
+        t->SetDirectory(newfile);
+    }
+
+    // Close/delete the old file (keys already written above)
+    *fLog << inf3 << "Closing file " << fOut->GetName() << "." << endl;
+    delete fOut;
+ 
+    // Replace current with new file
+    fOut = newfile;
+
+    // Change current directory to new file
+    gFile = fOut;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// A rule looks like:
+//   "s/source/destination/"
+//
+// For more details on regular expression see a proper documentation,
+// for example, "man 7 regex" if installed, or TPRegexp.
+//
+// Here is an example:
+//
+// Example:
+//   inputfile: /data/MAGIC/Period016/rootdata/20040621_23210_D_Mkn421_E.root
+//   rule:      /([0-9]+_[0-9]+)_D_(.*[.]root)/\\/outpath\\/$1_Y_$2/
+//   outfile:   /outpath/20040621_23210_Y_Mkn421_E.root
+//
+// Please make sure that all / in your rules are correctly escaped, i.e.
+// in the string stored in memory it must look like \/ and in the string
+// your set in your program it must look \\/.
+//
+// Note, that this function has been made static to allow your to
+// test your split rules, i.e. regular expressions.
+//
+TString MWriteRootFile::SubstituteName(const char *regexp, TString fname)
+{
+    // Remove the path from the filename
+    if (fname.Last('/')>=0)
+        fname.Remove(0, fname.Last('/')+1);
+
+    // Regular expression to split the rule into its contents
+    static const TString sed("s/((\\\\/|[^/])*)/((\\\\/|[^/])*)/([gimosxd]*)");
+
+    // Do splitting
+    TObjArray *subStrL = TPRegexp(sed).MatchS(regexp);
+    if (subStrL->GetEntries()!=6)
+    {
+        gLog << err << "ERROR - SubstituteName: Evaluating regexp " << regexp << " failed." << endl;
+        subStrL->Print();
+        delete subStrL;
+        return "";
+    }
+
+    /*const*/ TString reg = (*subStrL)[1]->GetName(); // Regular expression to search for
+    /*const*/ TString tar = (*subStrL)[3]->GetName(); // Regular expression for replacing
+      const   TString mod = (*subStrL)[5]->GetName(); // Possible modifiers (e.g. 'a')
+
+    delete subStrL;
+
+    // Unescpae slashes in paths
+    reg.ReplaceAll("\\/", "/");
+    tar.ReplaceAll("\\/", "/");
+
+    // Do substitution
+    const Int_t nrSub = TPRegexp(reg).Substitute(fname, tar, mod);
+    if (nrSub==0)
+    {
+        gLog << err << "ERROR - Substituting due to SplitRule failed." << endl;
+        gLog << " Source FileName:  " << fname << endl;
+        gLog << " Search  Rexexp:   " << reg   << endl;
+        gLog << " Replace Rexexp:   " << tar   << endl;
+        gLog << " Modifiers:        " << mod   << endl;
+        return "";
+    }
+
+    return fname;
+}
+
+// --------------------------------------------------------------------------
+//
+// Writes a copy of the TTree t to the currently open file using
+// TTree::CloneTree()
+//
+void MWriteRootFile::CopyTree(TTree &t) const
+{
+    TString out = "Copy of tree ";
+    out += t.GetName();
+    out += " in progress...";
+
+    if (fDisplay)
+        fDisplay->SetStatusLine2(out);
+
+    *fLog << inf << out << flush;
+
+    // When a new file has been opened the old clone (if existing) has
+    // been moved to the new file. We could now use CopyTree but then
+    // we would have to unpack all data and repack it. Instead
+    // we delete the moved old tree.
+    //  FIXME: In priciple we could delete a "wrong" tree with the same name.
+    //         Should we flag the clones and delete them in ChangeFile?
+    TObject *old = fOut->GetList()->Remove(fOut->GetList()->FindObject(t.GetName()));
+    delete old;
+
+    // Now we clone the tree without unpacking and repacking.
+    // When it has not been moved it will be deleted in the TFile destructor
+    /*TTree *clone =*/ t.CloneTree(-1, "fast");
+    //clone->Write();
+    //delete clone;
+
+    *fLog << "done." << endl;
+
+    if (fDisplay)
+    {
+        out += " done.";
+        fDisplay->SetStatusLine2(out);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Make all copies requested from the currently open file into the new
+// file.
+//
+Bool_t MWriteRootFile::MakeCopies(const char *fname) const
+{
+    if (fCopies.GetEntries()==0)
+        return kTRUE;
+
+    TFile *file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(fname));
+    if (!file)
+    {
+        *fLog << err << "ERROR - MakeCopies: File " << fname << " not found in gROOT->GetListOfFiles()... abort." << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&fCopies);
+    TObject *o=0;
+    TTree   *t=0;
+
+    fOut->cd();
+    while ((o=Next()))
+    {
+        TTree *gettree = dynamic_cast<TTree*>(file->Get(o->GetName()));
+        if (!gettree)
+        {
+            const Bool_t force = o->TestBit(kForced);
+            if (force)
+                *fLog << err << "ERROR - ";
+            else
+                *fLog << inf3;
+
+            *fLog << "MakeCopies: Tree " << o->GetName() << " not found in file " << fname << ".";
+            if (force)
+                *fLog << ".. abort.";
+            *fLog << endl;
+
+            if (force)
+                return kFALSE;
+
+            continue;
+        }
+
+        gettree->SetBranchStatus(o->GetTitle(), 1);
+
+        // First Execution
+        if (t==gettree)
+            continue;
+
+        // Check if its the first call
+        if (t)
+            CopyTree(*t);
+        t = gettree;
+    }
+
+    if (t)
+        CopyTree(*t);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit. If file splitting is not allowed call MWriteFile::ReInit.
+//
+// In other cases get MRead from the TaskList (splitting is switched of if
+// this is impossible).
+//
+// Convert the input- into a new output file-name.
+//
+// Open a new file, change all trees to the new file (calling ChangeFile()),
+// and close the old one.
+//
+// Call MWriteFile::ReInit()
+//
+Bool_t MWriteRootFile::ReInit(MParList *pList)
+{
+    MRead *read = (MRead*)pList->FindTask("MRead");
+    if (fSplitRule.IsNull() && fCopies.GetEntries()>0 && fOut)
+    {
+        if (!read)
+        {
+            *fLog << err;
+            *fLog << "ERROR: No Task 'MRead' found in the tasklist.  This task is" << endl;
+            *fLog << "  necessary to  get the filename.  Without  a filename file" << endl;
+            *fLog << "  AddCopySource cannot be used... abort." << endl;
+            *fLog << endl;
+            return kFALSE;
+        }
+        if (!MakeCopies(read->GetFullFileName()))
+            return kFALSE;
+
+    }
+
+    if (fSplitRule.IsNull() || !(fOut || TestBit(kIsNotOwner)))
+        return MWriteFile::ReInit(pList);
+
+    if (!read)
+    {
+        *fLog << warn;
+        *fLog << "WARNING: No Task 'MRead' found in the tasklist.  This task is" << endl;
+        *fLog << "  necessary  to  get  the filename.  Without  a filename file" << endl;
+        *fLog << "  file splitting is not allowed... disabled!" << endl;
+        *fLog << endl;
+        fSplitRule = "";
+        return kTRUE;
+    }
+
+
+    const TString oldname = read->GetFullFileName();
+    const TString newname = SubstituteName(fSplitRule, oldname);
+    if (!ChangeFile(newname))
+        return kFALSE;
+
+    if (!MakeCopies(oldname))
+        return kFALSE;
+
+    return MWriteFile::ReInit(pList);
+}
+
+// --------------------------------------------------------------------------
+//
+// return open state of the root file. If the file is 'memory' kTRUE is
+// returned.
+//
+Bool_t MWriteRootFile::IsFileOpen() const
+{
+    if (!fOut)
+        return kTRUE;
+
+    const char *n = fOut->GetName();
+    return n==0 || *n==0 ? kTRUE : fOut->IsOpen();
+}
+
+// --------------------------------------------------------------------------
+//
+// return name of the root-file. If the file is "memory" "<memory>" is
+// returned.
+//
+const char *MWriteRootFile::GetFileName() const
+{
+    if (!fOut)
+        return "<memory>";
+
+    const char *n = fOut->GetName();
+    return n==0 || *n==0 ? "<dummy>" : n;
+}
+
+// --------------------------------------------------------------------------
+//
+// cd into file. See TFile::cd(). If the file is "memory" kTRUE is returned.
+//
+Bool_t MWriteRootFile::cd(const char *path)
+{
+    return fOut ? fOut->cd(path) : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If the output file is deleted set fOut to NULL.
+// Call MTask::RecursiveRemove
+//
+void MWriteRootFile::RecursiveRemove(TObject *obj)
+{
+    if (obj==fOut)
+        fOut=NULL;
+
+    MWriteFile::RecursiveRemove(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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(ostream &out) const
+{
+    out << "   MWriteRootFile " << GetUniqueName();
+    if (fOut)
+    {
+        out << "(\"";
+        out << fOut->GetName() << "\", \"";
+        out << fOut->GetOption() << "\", \"";
+        out << fOut->GetTitle() << "\", ";
+        out << fOut->GetCompressionLevel();
+        out << ")";
+    }
+    out << ";" << endl;
+
+    if (fName!=gsDefName)
+        out << "   " << GetUniqueName() << ".SetName(\"" << fName << "\");" << endl;
+    if (fTitle!=gsDefTitle)
+        out << "   " << GetUniqueName() << ".SetTitle(\"" << fTitle << "\");" << endl;
+
+    MRootFileBranch *entry;
+    TIter Next(&fBranches);
+    while ((entry=(MRootFileBranch*)Next()))
+    {
+        out << "   " << GetUniqueName() << ".AddContainer(";
+
+        if  (entry->GetContainer())
+        {
+            entry->GetContainer()->SavePrimitive(out);
+            out << "&" << entry->GetContainer()->GetUniqueName();
+        }
+        else
+            out << "\"" << entry->GetContName() << "\"";
+
+        out << ", \"" << entry->GetName() << "\"";
+        if (!entry->MustHave())
+            out << ", kFALSE";
+
+        out <<");" << endl;
+    }
+}
+
Index: branches/Mars_McMismatchStudy/mfileio/MWriteRootFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/MWriteRootFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/MWriteRootFile.h	(revision 17960)
@@ -0,0 +1,158 @@
+#ifndef MARS_MWriteRootFile
+#define MARS_MWriteRootFile
+
+#ifndef MARS_MWriteFile
+#include "MWriteFile.h"
+#endif
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class TFile;
+class TTree;
+class TBranch;
+
+class MRootFileBranch : public TNamed
+{
+private:
+    TTree         *fTree;       //!
+    TBranch       *fBranch;     //!
+
+    MParContainer *fContainer;
+
+    Bool_t         fMust;
+    Long64_t       fMaxEntries;
+
+    void Init(const char *name, Bool_t must)
+    {
+        SetName(name?name:"");
+        fMust = must;
+    }
+
+public:
+    MRootFileBranch() : fTree(NULL), fBranch(NULL), fContainer(NULL), fMust(0), fMaxEntries(0)
+    {
+        Init(NULL, kFALSE);
+        fTitle = "";
+    }
+
+    MRootFileBranch(const char *cname, const char *tname=NULL, Bool_t must=kFALSE, Long64_t max=-1)
+        : fTree(NULL), fBranch(NULL), fContainer(NULL), fMust(0), fMaxEntries(max)
+    {
+        Init(tname, must);
+        fTitle = cname;
+    }
+
+    MRootFileBranch(MParContainer *cont, const char *tname=NULL, Bool_t must=kFALSE, Long64_t max=-1)
+        : fTree(NULL), fBranch(NULL), fMust(0), fMaxEntries(max)
+    {
+        Init(tname, must);
+        fTitle = "";
+        fContainer = cont;
+    }
+
+    TTree         *GetTree() const       { return fTree; }
+    MParContainer *GetContainer() const  { return fContainer; }
+    void          *GetAddress()          { return &fContainer; }
+    TBranch       *GetBranch() const     { return fBranch; }
+    const char    *GetContName() const   { return fTitle; }
+    Bool_t         MustHave() const      { return fMust; }
+    Long64_t         GetMaxEntries() const { return fMaxEntries; }
+
+    void SetContainer(MParContainer *cont) { fContainer = cont; }
+    void SetTree(TTree *tree)              { fTree = tree; }
+    void SetBranch(TBranch *branch)        { fBranch = branch; }
+
+    ClassDef(MRootFileBranch, 1) // Storage container for MWriteRootFile to store TBranch informations
+};
+
+class MWriteRootFile : public MWriteFile
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    TFile *fOut;             // Current file
+
+    TObjArray fBranches;     // List of Branch setup (MRootFileBranch)
+    TObjArray fTrees;        //! List of trees
+    TObjArray fCopies;       // Branches and tree to copy
+
+    TString fSplitRule;      // file splitting allowed if rule existing (done in ReInit)
+
+    enum {
+        kIsNotOwner = BIT(14), // MWriteRootFile is not owner of fOut
+        kFillTree   = BIT(14),
+        kForced     = BIT(14), // Used for flag in fCopies
+        // Be carefull these bits are already in use!
+        // TBranch::kAutoDelete = BIT(15)
+        // TBranchElement::kDeleteObject = BIT(16)
+        // TTree::kFriendLock = BIT(17)
+        kIsNewTree  = BIT(23)
+    };
+
+    // File handling
+    void    Close();
+    Bool_t  ChangeFile(const char *fname);
+    TFile  *OpenFile(const char *name, Option_t *option, const char *title, Int_t comp);
+    void    CopyTree(TTree &t) const;
+    Bool_t  MakeCopies(const char *oldname) const;
+
+    // MWrite
+    Bool_t      CheckAndWrite();
+    Bool_t      IsFileOpen() const;
+    Bool_t      GetContainer(MParList *pList);
+    const char *GetFileName() const;
+
+    // MTask
+    Bool_t ReInit(MParList *pList);
+    void   StreamPrimitive(std::ostream &out) const;
+
+    // Constructor
+    void Init(const char *name=0, const char *title=0);
+
+public:
+    MWriteRootFile();
+    MWriteRootFile(const Int_t comp,
+                   const char *rule,
+                   const Option_t *opt="RECREATE",
+                   const char *ftitle="Untitled",
+                   const char *name=NULL,
+                   const char *title=NULL);
+    MWriteRootFile(const char *fname,
+                   const Option_t *opt="RECREATE",
+                   const char *ftitle="Untitled",
+                   const Int_t comp=2,
+                   const char *name=NULL,
+                   const char *title=NULL);
+    ~MWriteRootFile();
+
+    void AddContainer(const char *cname,   const char *tname=NULL, Bool_t must=kTRUE, Long64_t max=-1);
+    void AddContainer(MParContainer *cont, const char *tname=NULL, Bool_t must=kTRUE, Long64_t max=-1);
+    void AddCopySource(const char *tname, const char *bname=NULL, Bool_t force=kTRUE);
+    void AddCopySource(const char *tname, Bool_t force)
+    {
+        AddCopySource(tname, NULL, force);
+    }
+
+    void AddTree(const char *name, Bool_t force=kTRUE)
+    {
+        AddContainer(Form("MReport%s", name), name, force);
+        AddContainer(Form("MTime%s", name),   name, force);
+    }
+
+    void Print(Option_t *t=NULL) const;
+
+    Bool_t cd(const char *path=0);
+
+    void RecursiveRemove(TObject *obj);
+
+    static TString SubstituteName(const char *regexp, TString fname);
+
+    ClassDef(MWriteRootFile, 1)	// Task to write data into a root file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfileio/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/Makefile	(revision 17960)
@@ -0,0 +1,43 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mraw -I../mmc -I../mreflector -I../mgui \
+	   -I../mdata -I../mbadpixels -I../msim -I../mcore
+#mraw:       MRawRunHeader (MReadMaraFile)
+#mmc:        MMcRunHeader  (MReadMarsFile)
+#mreflector: MRfl*         (MReadRflFile)
+#mgui:       MCamEvent     (MReadRflFile)
+#mdata:      MData*        (MWriteAsciiFile)
+
+CINT     = FileIO
+
+SRCFILES = MRead.cc \
+           MChain.cc \
+	   MReadTree.cc \
+           MReadFiles.cc \
+           MReadReports.cc \
+           MReadMarsFile.cc \
+           MReadScanFile.cc \
+           MWriteFile.cc \
+           MWriteAsciiFile.cc \
+           MWriteRootFile.cc \
+           MWriteFitsFile.cc \
+           MTopFitsGroup.cc \
+           MFitsArray.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mfileio/defines.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/defines.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/defines.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfileio/structures_rfl.h
===================================================================
--- branches/Mars_McMismatchStudy/mfileio/structures_rfl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfileio/structures_rfl.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfilter/FilterIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/FilterIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/FilterIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mfilter/FilterLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/FilterLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/FilterLinkDef.h	(revision 17960)
@@ -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 MFTriggerLvl1+;
+#pragma link C++ class MFTriggerLvl2+;
+#pragma link C++ class MFGeomag+;
+#pragma link C++ class MFDeltaT+;
+#pragma link C++ class MFParticleId+;
+#pragma link C++ class MFEvtNumber+;
+
+#pragma link C++ class MFSoftwareTrigger+;
+#pragma link C++ class MFCosmics+;
+#pragma link C++ class MFMagicCuts+;
+
+#pragma link C++ class MFEnergySlope+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mfilter/MFCosmics.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFCosmics.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFCosmics.cc	(revision 17960)
@@ -0,0 +1,295 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  02/2004 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   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).
+//
+//   In the PostProcess we...
+//    a) check the ratio of events which were accepted against
+//       fMinAcceptedFraction.
+//    b) check the ratio of events which were rejected against
+//       fMaxAcceptedFraction.
+//
+//  Input Containers:
+//   MRawEvtData
+//   MPedestalCam
+//   MBadPixelsCam
+//   MExtractedSignalCam
+//
+//  Output Containers:
+//   -/-
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MFCosmics.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MFCosmics);
+
+using namespace std;
+
+const TString MFCosmics::fgNamePedestalCam = "MPedestalCam";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MFCosmics::MFCosmics(const char *name, const char *title)
+    : fPedestals(NULL), fSignals(NULL), fBadPixels(NULL), fRawEvt(NULL),
+    fNamePedestalCam(fgNamePedestalCam), fMaxEmptyPixels(0.2),
+    fMinAcceptedFraction(0), fMaxAcceptedFraction(1)
+{
+    fName  = name  ? name  : "MFCosmics";
+    fTitle = title ? title : "Filter to reject cosmics";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//  - MExtractedSignalCam
+//
+Int_t MFCosmics::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+      *fLog << err << "MRawEvtData not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindObject(fNamePedestalCam, "MPedestalCam");
+    if (!fPedestals)
+    {
+        *fLog << err << fNamePedestalCam << " [MPedestalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+    if (!fBadPixels)
+    {
+        *fLog << err << "MBadPixelsCam 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)
+{
+    // The number here is just an average number. The real number
+    // might change from event to event (up to 50%!)
+    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();
+
+        if ((*fBadPixels)[idx].IsUnsuitable())
+            continue;
+
+        const MExtractedSignalPix &sig = (*fSignals)[idx];
+        if (!sig.IsHiGainValid())
+            continue;
+
+        allpix++;
+
+        //
+        // Check whether the pixel has a saturating hi-gain. In
+        // this case the extracted hi-gain might be empty.
+        //
+        if (sig.IsHiGainSaturated())
+            continue;
+
+        const MPedestalPix  &ped = (*fPedestals)[idx];
+
+        const Float_t pedrms = ped.GetPedestalRms()*fSqrtHiGainSamples;
+        const Float_t sumhi  = sig.GetExtractedSignalHiGain();
+
+        //
+        // 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 discarded.
+    //
+    return cosmicpix > fMaxEmptyPixels*allpix;
+}
+
+// ---------------------------------------------------------
+//
+//   In the PostProcess we...
+//    a) check the ratio of events which were accepted against
+//       fMinAcceptedFraction.
+//    b) check the ratio of events which were rejected against
+//       fMaxAcceptedFraction.
+//
+//   return failure (kFALSE) if condition is not fullfilled.
+//
+Int_t MFCosmics::PostProcess()
+{
+    const UInt_t n = GetNumExecutions();
+    if (n==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/n);
+    *fLog << "%) Detected cosmics " ;
+    *fLog << " (with fMaxEmptyPixels = " << fMaxEmptyPixels*100 << "%)" << endl;
+
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/n);
+    *fLog << "%) No cosmics!" << endl;
+    *fLog << endl;
+
+    if (fCut[0]<fMinAcceptedFraction*n)
+    {
+        *fLog << err << "ERROR - Fraction of accepted events " << Form("%.1f", fCut[0]*100./n);
+        *fLog << "% underrun " << fMinAcceptedFraction*100 << "%... abort." << endl;
+        return kFALSE;
+    }
+    if (fCut[0]>fMaxAcceptedFraction*n)
+    {
+        *fLog << err << "ERROR - Fraction of accepted events " << Form("%.1f", fCut[0]*100./n);
+        *fLog << "% exceeded " << fMaxAcceptedFraction*100 << "%... abort." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MFCosmics.MaxEmptyPixels:    0.2
+//   MFCosmics.MaxAcceptedFraction: 1
+//   MFCosmics.MinAcceptedFraction: 0
+//
+Int_t MFCosmics::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "MaxEmptyPixels", print))
+    {
+        rc = kTRUE;
+        SetMaxEmptyPixels(GetEnvValue(env, prefix, "MaxEmptyPixels", fMaxEmptyPixels));
+    }
+    if (IsEnvDefined(env, prefix, "MaxAcceptedFraction", print))
+    {
+        rc = kTRUE;
+        SetMaxAcceptedFraction(GetEnvValue(env, prefix, "MaxAcceptedFraction", fMaxAcceptedFraction));
+    }
+    if (IsEnvDefined(env, prefix, "MinAcceptedFraction", print))
+    {
+        rc = kTRUE;
+        fMinAcceptedFraction = GetEnvValue(env, prefix, "MinAcceptedFraction", fMinAcceptedFraction);
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFCosmics.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFCosmics.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFCosmics.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MFCosmics
+#define MARS_MFCosmics
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MRawEvtData;
+
+class MPedestalCam;
+class MBadPixelsCam;
+class MExtractedSignalCam;
+
+class MFCosmics : public MFilter
+{
+private:
+    static const TString fgNamePedestalCam;
+
+    MPedestalCam        *fPedestals; // Pedestals of all pixels in the camera
+    MExtractedSignalCam *fSignals;   // Calibration events of all pixels in the camera
+    MBadPixelsCam       *fBadPixels; // Bad pixel used for exclusions
+
+    MRawEvtData         *fRawEvt;    // raw event data (time slices)
+
+    TString fNamePedestalCam;
+
+    Int_t   fCut[2];
+    Bool_t  fResult;
+
+    Float_t fMaxEmptyPixels;         // Maximum number of empty pixels before declaring event as cosmic
+    Float_t fSqrtHiGainSamples;      // Square root of the number of used Hi-Gain Samples
+
+    Float_t fMinAcceptedFraction;      // return error if exceeded
+    Float_t fMaxAcceptedFraction;      // return error if exceeded
+
+    // MFCosmics
+    Bool_t CosmicsRejection() const;
+
+    // MTask
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MFilter
+    Bool_t IsExpressionTrue() const { return fResult; }
+  
+public:
+    MFCosmics(const char *name=NULL, const char *title=NULL);
+
+    void    SetMaxEmptyPixels(const Float_t n) { fMaxEmptyPixels = n;    }
+    Float_t GetMaxEmptyPixels() const          { return fMaxEmptyPixels; }
+
+    void    SetMaxAcceptedFraction(const Float_t n) { fMaxAcceptedFraction = n;    }
+    void    SetMinAcceptedFraction(const Float_t n) { fMinAcceptedFraction = n;    }
+
+    void    SetNamePedestalCam(const char *name) { fNamePedestalCam = name; }
+
+    ClassDef(MFCosmics, 0)   // Filter to perform a cosmics rejection
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/mfilter/MFDeltaT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFDeltaT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFDeltaT.cc	(revision 17960)
@@ -0,0 +1,165 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  09/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFDeltaT
+//
+//  for more details see Construtor and Process()
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFDeltaT.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MFDeltaT);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor. First argument is the upper limit of the filter (default=0.5).
+// Second argument is the name of the parameter container storing the time.
+// (default="MTime")
+//
+MFDeltaT::MFDeltaT(Float_t max, const char *time,
+                   const char *name, const char *title)
+{
+    Init(name, title, max, time);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Initializes upper limit of the filter (default=0.5)
+// and name of the parameter container storing the time (default="MTime")
+//
+MFDeltaT::MFDeltaT(const char *name, const char *title)
+{
+    Init(name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+void MFDeltaT::Init(const char *name, const char *title,
+                    Float_t max, const char *time)
+{
+    fName  = name  ? name  : "MFDeltaT";
+    fTitle = title ? title : "Filter for time differences of consecutive events";
+
+    fUpperLimit = max;
+    fNameTime   = time;
+
+    fErrors.Set(6);
+
+    AddToBranchList(Form("%s.*", (const char*)fNameTime));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return result of conditional
+//
+Bool_t MFDeltaT::IsExpressionTrue() const
+{
+    return fResult;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for fNameTime [MTime]
+//
+Int_t MFDeltaT::PreProcess(MParList *pList)
+{
+    fErrors.Reset();
+
+    fTime = (MTime*)pList->FindObject(fNameTime, "MTime");
+    if (fTime)
+        return kTRUE;
+
+    *fLog << err << fNameTime << " [MTime] not found... aborting." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the condition. The condition is true if the time difference
+// between two consecutive events are >0 or <= upper limit.
+//
+Int_t MFDeltaT::Process()
+{
+    fResult = kFALSE;
+
+    Int_t i=0;
+
+    if (GetNumExecutions()>1)
+    {
+        if (*fTime-fLastTime>fUpperLimit)
+            i=1;
+        if (*fTime<fLastTime)
+            i=2;
+        if (*fTime==fLastTime)
+            i=3;
+        if (fTime->IsMidnight())
+            i=4;
+        if (*fTime==MTime())
+            i=5;
+    }
+
+    fLastTime = *fTime;
+
+    fResult = i==0;
+    fErrors[i]++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print some statistics.
+//
+Int_t MFDeltaT::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " filter statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    PrintSkipped(fErrors[2], "Delta-T  < 0");
+    PrintSkipped(fErrors[3], "Delta-T == 0");
+    PrintSkipped(fErrors[1], Form("Delta-T  > %.2fs", fUpperLimit));
+    PrintSkipped(fErrors[4], "MTime is midnight");
+    PrintSkipped(fErrors[5], "MTime not initialized");
+    *fLog << " " << (int)fErrors[0] << " (";
+    *fLog << Form("%5.1f", 100.*fErrors[0]/GetNumExecutions());
+    *fLog << "%) Evts fullfilled filter condition!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFDeltaT.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFDeltaT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFDeltaT.h	(revision 17960)
@@ -0,0 +1,50 @@
+#ifndef MARS_MFDeltaT
+#define MARS_MFDeltaT
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MTime;
+class MParList;
+
+class MFDeltaT : public MFilter
+{
+private:
+    MTime  *fTime;     //!
+    TString fNameTime;
+
+    Float_t fUpperLimit;
+
+    MTime  fLastTime;  //!
+    Bool_t fResult;    //!
+
+    TArrayI fErrors;
+
+    void Init(const char *name, const char *title, Float_t max=0.5, const char *time="MTime");
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MFDeltaT(Float_t max, const char *time="MTime", const char *name=0, const char *title=0);
+    MFDeltaT(const char *name=0, const char *title=0);
+
+    void SetUpperLimit(Float_t max) { fUpperLimit=max; }
+    Float_t GetUpperLimit() const { return fUpperLimit; }
+
+    Bool_t IsExpressionTrue() const;
+
+    ClassDef(MFDeltaT, 1) // A Filter for time differences of consecutive events
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfilter/MFEnergySlope.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFEnergySlope.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFEnergySlope.cc	(revision 17960)
@@ -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): Antonio Stamerra  02/2003 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   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 <TMath.h>
+#include <TRandom.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+ClassImp(MFEnergySlope);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor
+//
+MFEnergySlope::MFEnergySlope(const char *name, const char *title):
+    fNewSlope(-1), fMcMinEnergy(-1.), fMcMaxEnergy(-1.)
+{
+    fName  = name  ? name  : "MFEnergySlope";
+    fTitle = title ? title : "Filter to select energy with given slope";
+}
+
+// --------------------------------------------------------------------------
+//
+//     Constructor
+//
+MFEnergySlope::MFEnergySlope(Float_t slope, const char *name, const char *title):
+    fNewSlope(TMath::Abs(slope)), fMcMinEnergy(-1.), fMcMaxEnergy(-1.)
+{
+    fName  = name  ? name  : "MFEnergySlope";
+    fTitle = title ? title : "Filter to select energy with given slope";
+}
+
+// --------------------------------------------------------------------------
+//
+//     Constructor
+//
+MFEnergySlope::MFEnergySlope(Float_t slope, Float_t emin, const char *name, const char *title):
+    fNewSlope(TMath::Abs(slope)), fMcMinEnergy(emin), fMcMaxEnergy(-1.)
+{
+    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)
+{
+    if (fNewSlope<0)
+    {
+        *fLog << err << "New slope still undefined... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Preprocess
+//  
+//  MC slope and min/max energy are read
+//  Normalization factor is computed
+//
+Bool_t MFEnergySlope::ReInit(MParList *pList)
+{
+    MMcCorsikaRunHeader *runheader = (MMcCorsikaRunHeader*)pList->FindObject("MMcCorsikaRunHeader");
+    if (!runheader)
+    {
+        *fLog << err << "MMcCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Read info from0 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();
+
+    // Slope is used with positive values in the code
+    if (fNewSlope < 0)
+        fNewSlope *= -1;
+    if (fMcSlope < 0)
+        fMcSlope *= -1;
+
+    // Calculate normalization factor
+    fN0 = TMath::Power(fNewSlope>fMcSlope ? fMcMinEnergy : fMcMaxEnergy, fNewSlope-fMcSlope);
+
+    // Print some infos
+    *fLog << inf;
+    *fLog << "Fetched MC info:" << endl;
+    *fLog << "  Change E Slope from " << -fMcSlope << " (" << fMcMinEnergy << " < E < ";
+    *fLog << fMcMaxEnergy << ") to " << -fNewSlope << endl;
+    *fLog << "  Norm factor: " << fN0 << endl;
+
+    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;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//   MFEnergySlope.NewSlope: -2.8
+//
+Int_t MFEnergySlope::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NewSlope", print))
+    {
+        rc = kTRUE;
+        SetNewSlope(GetEnvValue(env, prefix, "NewSlope", fNewSlope));
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFEnergySlope.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFEnergySlope.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFEnergySlope.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MFEnergySlope
+#define MARS_MFEnergySlope
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MParList;
+class MMcCorsikaRunHeader;
+
+class MFEnergySlope : public MFilter
+{
+private:
+    //Int_t fNumSelectedEvts; // counter for number of selected events
+
+    MMcEvt *fEvt;           //! Events used to determin energy slope
+
+    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
+
+    Bool_t  fResult;        //! Result returned by IsExpressionTrue
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+    // MFilter
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+public:
+    MFEnergySlope(const char *name=NULL, const char *title=NULL);
+    MFEnergySlope(Float_t slope, const char *name=NULL, const char *title=NULL);
+    MFEnergySlope(Float_t slope, Float_t emin, const char *name=NULL, const char *title=NULL);
+
+    // Setter
+    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; }
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    ClassDef(MFEnergySlope, 0) // A Filter to select events with a given energy slope
+};
+
+#endif
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mfilter/MFEvtNumber.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFEvtNumber.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFEvtNumber.cc	(revision 17960)
@@ -0,0 +1,184 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 3/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFEvtNumber
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFEvtNumber.h"
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+
+ClassImp(MFEvtNumber);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor
+//
+MFEvtNumber::MFEvtNumber(const char *name, const char *title):
+    fFileName(""), fTreeName("Events"), fSelector("")
+{
+    fName  = name  ? name  : "MFEvtNumber";
+    fTitle = title ? title : "Filter to select events by run- and evt-number";
+}
+
+// --------------------------------------------------------------------------
+//
+// return the event id. It is a binary compilation of run- and evt-number
+//
+ULong_t MFEvtNumber::GetEvtId() const
+{
+    return Compile(fRun->GetRunNumber(), fEvt->GetDAQEvtNumber());
+}
+
+// --------------------------------------------------------------------------
+//
+//   Preprocess
+//  
+//  MC slope and min/max energy are read
+//  Normalization factor is computed
+//
+Int_t MFEvtNumber::PreProcess(MParList *plist)
+{
+    fResult = kTRUE;
+
+    if (fFileName.IsNull())
+    {
+        *fLog << inf << "No input file given... skipped." << endl;
+        return kSKIP;
+    }
+
+    fRun = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fEvt = (MRawEvtHeader*)plist->FindObject("MRawEvtHeader");
+    if (!fEvt)
+    {
+        *fLog << err << "MRawEvtHeader not found ... aborting." << endl;
+        return kFALSE;
+    }
+
+    TFile file(fFileName);
+    if (file.IsZombie())
+    {
+        *fLog << err << "Cannot open file " << fFileName << "... aborting." << endl;
+        return kFALSE;
+    }
+
+    TTree *t = dynamic_cast<TTree*>(file.Get(fTreeName));
+    if (!t)
+    {
+        *fLog << err << "Tree " << fTreeName << " not found in file " << fFileName << "... aborting." << endl;
+        return kFALSE;
+    }
+
+    t->SetEstimate(t->GetEntries());
+
+    if (t->Draw("RunNumber.fVal:EvtNumber.fVal", fSelector, "goff")<0)
+    {
+        *fLog << err << "Could not retrieve event-list from tree " << fTreeName << " in file " << fFileName << " selecting " << fSelector << "... aborting." << endl;
+        return kFALSE;
+    }
+
+    const Long64_t n = t->GetSelectedRows();
+
+    if (n<=0)
+    {
+        *fLog << err << "Could not retrieve event-list from tree " << fTreeName << " in file " << fFileName << " selecting " << fSelector << "... aborting." << endl;
+        return kFALSE;
+    }
+
+    const Double_t *v1 = t->GetV1();
+    const Double_t *v2 = t->GetV2();
+
+
+    *fLog << inf << "Found " << n << " events fulfilling " << fSelector << "." << endl;
+
+    for (Long64_t i=0; i<n; i++)
+        fList.Add(Compile((ULong64_t)v1[i], (ULong64_t)v2[i]), 1);
+
+    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 MFEvtNumber::Process()
+{
+    if (fFileName.IsNull())
+        return kTRUE;
+
+    fResult = fList.GetValue(GetEvtId()) ? kTRUE : kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//   MFEvtNumber.FileName: filename.root
+//   MFEvtNumber.TreeName: Events
+//   MFEvtNumber.Selector: ThetaSquared<0.04
+//
+Int_t MFEvtNumber::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FileName", print))
+    {
+        rc = kTRUE;
+        SetFileName(GetEnvValue(env, prefix, "FileName", fFileName));
+    }
+    if (IsEnvDefined(env, prefix, "TreeName", print))
+    {
+        rc = kTRUE;
+        SetFileName(GetEnvValue(env, prefix, "TreeName", fTreeName));
+    }
+    if (IsEnvDefined(env, prefix, "Selector", print))
+    {
+        rc = kTRUE;
+        SetSelector(GetEnvValue(env, prefix, "Selector", fSelector));
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFEvtNumber.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFEvtNumber.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFEvtNumber.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MFEvtNumber
+#define MARS_MFEvtNumber
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef ROOT_TExMap
+#include <TExMap.h>
+#endif
+
+class MRawRunHeader;
+class MRawEvtHeader;
+
+class MFEvtNumber : public MFilter
+{
+private:
+    MRawRunHeader *fRun;    //! MRawRunHeader with run-number of event
+    MRawEvtHeader *fEvt;    //! MRawEvtHeader with evt-number of event
+
+    Bool_t  fResult;        //! Result returned by IsExpressionTrue
+
+    TString fFileName;      // File name of the file with the even-/run-number
+    TString fTreeName;      // Tree name of the file with the even-/run-number
+
+    TString fSelector;      // Selector to choose run-/evt-number from file
+
+    TExMap  fList;          // List with all event-/run-numbers
+
+    ULong_t Compile(ULong64_t run, ULong64_t evt) const { return (run<<32)|evt; }
+    ULong_t GetEvtId() const;
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+    // MFilter
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+public:
+    MFEvtNumber(const char *name=NULL, const char *title=NULL);
+
+    // Setter
+    void SetFileName(const char *name) { fFileName=name; }
+    void SetTreeName(const char *name) { fTreeName=name; }
+    void SetSelector(const char *sel)  { fSelector=sel; }
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    ClassDef(MFEvtNumber, 0) // Filter to select events by run- and evt-number
+};
+
+#endif
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mfilter/MFGeomag.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFGeomag.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFGeomag.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfilter/MFGeomag.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFGeomag.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFGeomag.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfilter/MFMagicCuts.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFMagicCuts.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFMagicCuts.cc	(revision 17960)
@@ -0,0 +1,710 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFMagicCuts
+//
+//  Predefinitions:
+//  ---------------
+//      width/length = MHillas.fWidth/MHillas.fLength
+//      area         = MHillas.GetArea*fMm2Deg*fMm2Deg
+//      lgsize       = log10(MHillas.fSize)
+//
+//      leakage1     = log10(MNewImagePar.fLeakage1+1)
+//
+//      alpha        = MHillasSrc.fAlpha
+//      dist         = MHillasSrc.fDist*fMm2Deg
+//      m3long       = MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)*fMm2Deg
+//      slope        = MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/fMm2Deg
+//
+//      antialpha    = MHillasSrcAnti.fAlpha
+//      antidist     = MHillasSrcAnti.fDist*fMm2Deg
+//      antim3long   = MHillasExt.fM3Long*sign(MHillasSrcAnti.fCosDeltaAlpha)*fMm2Deg
+//      antislope    = MHillasExt.fSlopeLong*sign(MHillasSrcAnti.fCosDeltaAlpha)/fMm2Deg
+//
+//      had          = Hadronness.fVal
+//
+//  Coefficients/Cuts:
+//  ------------------
+//
+//    c[0],  c[5], c[6], c[7],  c[8], c[9]:
+//          xi          = c[0] + c[8]*slope + c[9]*leak +
+//                        (lgsize>c[10])*c[11]*(lgsize-c[10])^2;
+//          p           = xi*(1-width/length);
+//          sign1       = m3long-c[5]
+//          sign2       = (dist-c[7])*c[6]-slope
+//          disp        = sign1<0 ||sign2<0 ? -disp : disp
+//          thetasq     = disp^2 + dist^2 - 2*disp*dist*cos(alpha)
+//
+//    And the values with respect to the antisource position respectively.
+//
+//
+//    c[1]:
+//          thetasq < c[1]*c[1]
+//
+//    AreaCut:
+//    c[2], c[3], c[4]:
+//          A = c[2]*(1 - c[4]*(lgsize-c[3])*(lgsize-c[3]))
+//          area < A
+//
+//    HadronnessCut:
+//    c[13], c[14]:
+//          had       <= c[13]
+//          10^lgsize >= c[14]
+//
+//
+//  Options:
+//  --------
+//
+//   HadronnessCut:
+//    - none/nocut: No area cut
+//    - area:       Area cut <default>
+//    - hadronness: Cut in size and hadronness (c[10], c[11])
+//    - all:        area + hadronness
+//
+//   ThetaCut:
+//    - none/nocut: no theta cut <default>
+//    - on:         cut in theta only
+//    - off:        anti-cut in anti-theta only
+//    - wobble:     same as on|off (both)
+//
+//   CalcDisp:
+//    - yes:        Disp is calculated as defined above <default>
+//    - no:         abs(Disp.fVal) from the parameter list is used instead
+//
+//   CalcGhostbuster:
+//    - yes:        The ghostbuster is calculated as defined above <default>
+//    - no:         Ghostbuster.fVal<c[12] is used as ghostbusting condition
+//
+//
+// Class Version 2:
+// ----------------
+//  + Bool_t fCalcDisp;        // Should we use Disp from the parameterlist?
+//  + Bool_t fCalcGhostbuster; // Should we use Ghostbuster from the parameterlist?
+//
+//
+//  Input Container:
+//  ------
+//   MGeomCam
+//   MHillas
+//   MHillasExt
+//   MNewImagePar
+//   MHillasSrc
+//   [MHillasSrcAnti [MHillasSrc]]
+//   [Disp [MParameterD]]
+//   [Ghostbuster [MParameterD]]
+//
+//  Output:
+//  -------
+//   ThetaSquared [MParameterD]    // stores thetasq
+//   Disp [MParameterD]            // stores -p*sign(MHillasSrc.fCosDeltaAlpha)
+//   ThetaSquaredCut [MParameterD] // stores c[1]*c[1]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFMagicCuts.h"
+
+#include <fstream>
+#include <errno.h> 
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMath.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MHillas.h"
+#include "MHillasSrc.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MParameters.h"
+
+ClassImp(MFMagicCuts);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+MFMagicCuts::MFMagicCuts(const char *name, const char *title)
+    : fGeom(0), fHil(0), fHilSrc(0), fHilAnti(0), fHilExt(0), fNewImgPar(0),
+    fThetaSq(0), fDisp(0), fHadronness(0), fMatrix(0), fVariables(20),
+    fThetaCut(kNone), fHadronnessCut(kArea), fCalcDisp(kTRUE),
+    fCalcGhostbuster(kTRUE)
+{
+    fName  = name  ? name  : "MFMagicCuts";
+    fTitle = title ? title : "Class to evaluate the MagicCuts";
+
+    fMatrix = NULL;
+
+    AddToBranchList("MHillas.fWidth");
+    AddToBranchList("MHillas.fLength");
+    AddToBranchList("MHillas.fSize");
+    AddToBranchList("MHillasSrc.fAlpha");
+    AddToBranchList("MHillasSrc.fDist");
+    AddToBranchList("MHillasSrc.fCosDeltaAlpha");
+    AddToBranchList("MHillasSrcAnti.fAlpha");
+    AddToBranchList("MHillasSrcAnti.fDist");
+    AddToBranchList("MHillasSrcAnti.fCosDeltaAlpha");
+    AddToBranchList("MHillasExt.fM3Long");
+    AddToBranchList("MHillasExt.fSlopeLong");
+    AddToBranchList("MNewImagePar.fLeakage1");
+    AddToBranchList("Hadronness.fVal");
+    AddToBranchList("Disp.fVal");
+    AddToBranchList("Ghostbuster.fVal");
+}
+
+// --------------------------------------------------------------------------
+//
+// The theta cut value GetThetaSqCut() is propageted to the parameter list
+// as 'ThetaSquaredCut' as MParameterD so that it can be used somewhere else.
+//
+Int_t MFMagicCuts::PreProcess(MParList *pList)
+{
+    fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fThetaSq = (MParameterD*)pList->FindCreateObj("MParameterD", "ThetaSquared");
+    if (!fThetaSq)
+        return kFALSE;
+
+    if (!fCalcDisp)
+        fDisp = (MParameterD*)pList->FindObject("Disp", "MParameterD");
+    else
+        fDisp = (MParameterD*)pList->FindCreateObj("MParameterD", "Disp");
+    if (!fDisp)
+    {
+        *fLog << err << "Disp [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fCalcGhostbuster)
+        fGhostbuster = (MParameterD*)pList->FindObject("Ghostbuster", "MParameterD");
+    else
+        fGhostbuster = (MParameterD*)pList->FindCreateObj("MParameterD", "Ghostbuster");
+    if (!fGhostbuster)
+    {
+        *fLog << err << "Ghostbuster [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // propagate Theta cut to the parameter list
+    // so that it can be used somewhere else
+    MParameterD *thetacut = (MParameterD*)pList->FindCreateObj("MParameterD", "ThetaSquaredCut");
+    if (!thetacut)
+        return kFALSE;
+    thetacut->SetVal(GetThetaSqCut());
+
+    Print();
+
+    if (fMatrix)
+        return kTRUE;
+
+    //-----------------------------------------------------------
+
+    fHil = (MHillas*)pList->FindObject("MHillas");
+    if (!fHil)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject("MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << "MHillasExt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewImgPar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewImgPar)
+    {
+        *fLog << err << "MNewImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject("MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << "MHillasSrc not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fThetaCut&kOff)
+    {
+        fHilAnti = (MHillasSrc*)pList->FindObject("MHillasSrcAnti", "MHillasSrc");
+        if (!fHilAnti)
+        {
+            *fLog << warn << "MHillasSrcAnti [MHillasSrc] not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    if (fHadronnessCut&kHadronness)
+    {
+        fHadronness = (MParameterD*)pList->FindObject("Hadronness", "MParameterD");
+        if (!fHadronness)
+        {
+            *fLog << warn << "Hadronness [MParameterD] not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MFMagicCuts::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 MFMagicCuts::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+//    fMap[kELength] = fMatrix->AddColumn("MHillas.fLength*MGeomCam.fConvMm2Deg");
+//    fMap[kEWidth]  = fMatrix->AddColumn("MHillas.fWidth*MGeomCam.fConvMm2Deg");
+
+    fMap[kEWdivL]   = fMatrix->AddColumn("MHillas.fWidth/MHillas.fLength");
+    fMap[kESize]    = fMatrix->AddColumn("log10(MHillas.fSize)");
+    fMap[kEArea]    = fMatrix->AddColumn("MHillas.GetArea*MGeomCam.fConvMm2Deg*MGeomCam.fConvMm2Deg");
+
+    fMap[kELeakage] = fMatrix->AddColumn("log10(MNewImagePar.fLeakage1+1)");
+
+    fMap[kEAlpha]   = fMatrix->AddColumn("MHillasSrc.fAlpha");
+    fMap[kEDist]    = fMatrix->AddColumn("MHillasSrc.fDist*MGeomCam.fConvMm2Deg");
+    fMap[kEM3Long]  = fMatrix->AddColumn("MHillasExt.fM3Long*sign(MHillasSrc.fCosDeltaAlpha)*MGeomCam.fConvMm2Deg");
+
+    fMap[kESign]    = fMatrix->AddColumn("sign(MHillasSrc.fCosDeltaAlpha)");
+
+    fMap[kESlope]   = fMatrix->AddColumn("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg");
+
+    if (!fCalcDisp)
+        fMap[kEDisp] = fMatrix->AddColumn("abs(Disp.fVal)");
+
+    if (!fCalcGhostbuster)
+        fMap[kEGhostbuster] = fMatrix->AddColumn("Ghostbuster.fVal");
+
+    if (fThetaCut&kOff)
+    {
+        fMap[kEAlphaAnti]  = fMatrix->AddColumn("MHillasSrcAnti.fAlpha");
+        fMap[kEDistAnti]   = fMatrix->AddColumn("MHillasSrcAnti.fDist*MGeomCam.fConvMm2Deg");
+        fMap[kEM3LongAnti] = fMatrix->AddColumn("MHillasExt.fM3Long*sign(MHillasSrcAnti.fCosDeltaAlpha)*MGeomCam.fConvMm2Deg");
+        fMap[kESlopeAnti]  = fMatrix->AddColumn("MHillasExt.fSlopeLong*sign(MHillasSrcAnti.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg");
+    }
+
+    if (fHadronnessCut&kHadronness)
+        fMap[kEHadronness] = fMatrix->AddColumn("Hadronness.fVal");
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns theta squared based on the formula:
+//    p := c*(1-width/length)
+//    return d*d + p*p - 2*d*p*cos(a*TMath::DegToRad());
+//
+// If par!=NULL p is stored in this MParameterD
+//
+Double_t MFMagicCuts::GetThetaSq(Double_t p, Double_t d, Double_t a) const
+{
+    // wl = width/l [1]
+    // d  = dist    [deg]
+    // a  = alpha   [deg]
+    return d*d + p*p - 2*d*p*TMath::Cos(a*TMath::DegToRad());
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns squared cut value in theta: fVariables[1]^2
+//
+Double_t MFMagicCuts::GetThetaSqCut() const
+{
+    return fVariables[1]*fVariables[1];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return abs(Disp.fVal) if disp calculation is switched off.
+// Otherwise return (c0+c6*leak^c7)*(1-width/length)
+//
+Double_t MFMagicCuts::GetDisp(Double_t slope, Double_t lgsize) const
+{
+    if (!fCalcDisp)
+        return fMatrix ? GetVal(kEDisp) : TMath::Abs(fDisp->GetVal());
+
+    // Get some variables
+    const Double_t wdivl = fMatrix ? GetVal(kEWdivL)   : fHil->GetWidth()/fHil->GetLength();
+    const Double_t leak  = fMatrix ? GetVal(kELeakage) : TMath::Log10(fNewImgPar->GetLeakage1()+1);
+
+    // For simplicity
+    const Double_t *c = fVariables.GetArray();
+
+    // As rule for root or MDataPhrase:
+    //   ((M[3]>[3])*[4]*(M[3]-[3])^2 + [2]*M[2] + [1]*M[1] + [0])*M[0]
+    //
+    Double_t xi = c[0] + c[8]*slope + c[9]*leak;
+    if (lgsize>c[10])
+        xi += (lgsize-c[10])*(lgsize-c[10])*c[11];
+
+    const Double_t disp = xi*(1-wdivl);
+
+    return disp;
+}
+
+Bool_t MFMagicCuts::IsGhost(Double_t m3long, Double_t slope, Double_t dist) const
+{
+    // For simplicity
+    const Double_t *c = fVariables.GetArray();
+
+    if (!fCalcGhostbuster)
+        return (fMatrix ? GetVal(kEGhostbuster) : fGhostbuster->GetVal())<c[12];
+
+    // Do Ghostbusting with slope and m3l
+    const Bool_t sign1 = m3long < c[5];
+    const Bool_t sign2 = slope  > (dist-c[7])*c[6];
+
+    return sign1 || sign2;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical magic-cuts
+//
+Int_t MFMagicCuts::Process()
+{
+    // For simplicity
+    const Double_t *c = fVariables.GetArray();
+
+    const Float_t fMm2Deg = fGeom->GetConvMm2Deg();
+
+    // Default if we return before the end
+    fResult = kFALSE;
+
+    // Value for Theta cut (Disp parametrization)
+    const Double_t cut  = GetThetaSqCut();
+
+    // ------------------- Most efficient cut -----------------------
+    // ---------------------- Theta cut ON --------------------------
+    const Double_t dist   = fMatrix ? GetVal(kEDist)   : fHilSrc->GetDist()*fMm2Deg;
+    const Double_t alpha  = fMatrix ? GetVal(kEAlpha)  : fHilSrc->GetAlpha();
+    const Double_t m3long = fMatrix ? GetVal(kEM3Long) : fHilExt->GetM3Long()*TMath::Sign(fMm2Deg, fHilSrc->GetCosDeltaAlpha());
+    const Double_t slope  = fMatrix ? GetVal(kESlope)  : fHilExt->GetSlopeLong()/TMath::Sign(fMm2Deg, fHilSrc->GetCosDeltaAlpha());
+    const Double_t sign   = fMatrix ? GetVal(kESign)   : MMath::Sgn(fHilSrc->GetCosDeltaAlpha());
+    const Double_t lgsize = fMatrix ? GetVal(kESize)   : TMath::Log10(fHil->GetSize());
+
+    // Calculate disp including sign
+    const Double_t disp  = GetDisp(slope, lgsize);
+    const Double_t ghost = IsGhost(m3long, slope, dist);
+
+    const Double_t p = ghost ? -disp : disp;
+
+    // Align sign of disp along shower axis like m3long
+    fDisp->SetVal(-p*sign);
+
+    // FIXME: Allow to use ThetaSq from INPUT!
+
+    // Calculate corresponding Theta^2
+    const Double_t thetasq = GetThetaSq(p, dist, alpha);
+    fThetaSq->SetVal(thetasq);
+
+    // Perform theta cut
+    if (fThetaCut&kOn && thetasq >= cut)
+        return kTRUE;
+
+    // --------------------- Efficient  cut -------------------------
+    // ---------------------- Area/M3l cut --------------------------
+    if (fHadronnessCut&kArea)
+    {
+        const Double_t area = fMatrix ? GetVal(kEArea) : fHil->GetArea()*fMm2Deg*fMm2Deg;
+        const Double_t A    = (c[2]*c[4]>0 ? (lgsize>c[3]) : (lgsize<c[3])) ?
+            c[2] : c[2]*(1 - c[4]*(lgsize-c[3])*(lgsize-c[3]));
+        //const Double_t A    = lgsize>c[3] ? c[2] : c[2] - c[4]/c[2]*(lgsize-c[3])*(lgsize-c[3]));
+        if (area>=A)
+            return kTRUE;
+    }
+
+    if (fHadronnessCut&kAreaLin)
+    {
+        const Double_t area = fMatrix ? GetVal(kEArea) : fHil->GetArea()*fMm2Deg*fMm2Deg;
+        const Double_t A    = c[2] + c[4]*(lgsize-c[3]);
+        if (area>=A)
+            return kTRUE;
+    }
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    if (fHadronnessCut&kHadronness)
+    {
+        const Double_t had = fMatrix ? GetVal(kEHadronness) : fHadronness->GetVal();
+        if (had>c[13])
+            return kTRUE;
+
+        if (TMath::Power(10, lgsize)<c[14])
+            return kTRUE;
+    }
+
+    // ------------------- Least efficient cut -----------------------
+    // ---------------------- Theta cut OFF --------------------------
+
+    if (fThetaCut&kOff)
+    {
+        const Double_t distanti    = fMatrix ? GetVal(kEDistAnti)   : fHilAnti->GetDist()*fMm2Deg;
+        const Double_t alphaanti   = fMatrix ? GetVal(kEAlphaAnti)  : fHilAnti->GetAlpha();
+        const Double_t m3lanti     = fMatrix ? GetVal(kEM3LongAnti) : fHilExt->GetM3Long()*TMath::Sign(fMm2Deg, fHilAnti->GetCosDeltaAlpha());
+        const Double_t slopeanti   = fMatrix ? GetVal(kESlopeAnti)  : fHilExt->GetSlopeLong()/TMath::Sign(fMm2Deg, fHilAnti->GetCosDeltaAlpha());
+
+        const Double_t dispanti  = GetDisp(slopeanti, lgsize);
+        const Double_t ghostanti = IsGhost(m3lanti, slopeanti, lgsize);
+
+        const Double_t panti = ghostanti ? -dispanti : dispanti;
+
+        // Align disp along source direction depending on third moment
+        const Double_t thetasqanti = GetThetaSq(panti, distanti, alphaanti);
+
+        if (thetasqanti<cut)
+            return kTRUE;
+
+        // This cut throws away gamma-like events which would be assigned to the
+        // anti-source. It is not necessary but it offers the possibility to
+        // fill the MHDisp plot in one run (Having a hole instead of eg. Crab
+        // the data can be rotated and subtracted)
+    }
+
+    fResult = kTRUE;
+
+    return kTRUE;
+}
+
+void MFMagicCuts::SetVariables(const TArrayD &arr)
+{
+    fVariables = arr;
+}
+
+TString MFMagicCuts::GetParam(Int_t i) const
+{
+    if (i>=fVariables.GetSize())
+        return "";
+
+    return Form("Param[%2d]=%+f", i, fVariables[i]);
+}
+
+void MFMagicCuts::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << setiosflags(ios::left) << endl;
+
+    *fLog << "Using Theta cut: ";
+    switch (fThetaCut)
+    {
+    case kNone:
+        *fLog << "none" << endl;
+        break;
+    case kOn:
+        *fLog << "on" << endl;
+        break;
+    case kOff:
+        *fLog << "off" << endl;
+        break;
+    case kWobble:
+        *fLog << "on and off (wobble)" << endl;
+        break;
+    }
+    *fLog << "Using hadronness cut: ";
+    switch (fHadronnessCut)
+    {
+    case kNoCut:
+        *fLog << "none" << endl;
+        break;
+    case kArea:
+        *fLog << "area" << endl;
+        break;
+    case kHadronness:
+        *fLog << "hadronness" << endl;
+        break;
+    case kAreaLin:
+        *fLog << "arealin" << endl;
+        break;
+    case kAll:
+        *fLog << "all" << endl;
+        break;
+    }
+    if (fCalcDisp)
+        *fLog << "Disp is calculated from c0, c8-c11." << endl;
+    else
+        *fLog << "Disp.fVal from the parameter list is used as disp." << endl;
+    if (fCalcGhostbuster)
+        *fLog << "Ghostbusting is calculated from c5-c7." << endl;
+    else
+        *fLog << "Ghostbuster.fVal from the parameter list is used for ghostbusting." << endl;
+
+    *fLog << "Filter is" << (IsInverted()?"":" not") << " inverted." << endl;
+
+    const Int_t n = fVariables.GetSize();
+    for (int i=0; i<n; i+=3)
+    {
+        *fLog << setw(25) << GetParam(i);
+        *fLog << setw(25) << GetParam(i+1);
+        *fLog << setw(25) << GetParam(i+2);
+        *fLog << endl;
+    }
+    *fLog << setiosflags(ios::right);
+}
+
+Bool_t MFMagicCuts::CoefficentsRead(const char *fname)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    for (int i=0; i<fVariables.GetSize(); i++)
+    {
+        fin >> fVariables[i];
+        if (!fin)
+        {
+            *fLog << err << "ERROR - Not enough coefficients in file " << fname << endl;
+            return kERROR;
+        }
+    }
+    return kTRUE;
+}
+
+Bool_t MFMagicCuts::CoefficentsWrite(const char *fname) const
+{
+    ofstream fout(fname);
+    if (!fout)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    for (int i=0; i<fVariables.GetSize(); i++)
+        fout << setw(11) << fVariables[i] << endl;
+
+    return kTRUE;
+}
+
+Int_t MFMagicCuts::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (MFilter::ReadEnv(env, prefix, print)==kERROR)
+        return kERROR;
+
+
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "ThetaCut", print))
+    {
+        TString str = GetEnvValue(env, prefix, "ThetaCut", "");
+        str.ToLower();
+        str=str.Strip(TString::kBoth);
+
+        if (str==(TString)"nocut" || str==(TString)"none")
+            fThetaCut = kNone;
+        if (str==(TString)"on")
+            fThetaCut = kOn;
+        if (str==(TString)"off")
+            fThetaCut = kOff;
+        if (str==(TString)"wobble")
+            fThetaCut = kWobble;
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "HadronnessCut", print))
+    {
+        TString str = GetEnvValue(env, prefix, "HadronnessCut", "");
+        str.ToLower();
+        str=str.Strip(TString::kBoth);
+
+        if (str==(TString)"nocut" || str==(TString)"none")
+            fHadronnessCut = kNoCut;
+        if (str==(TString)"area")
+            fHadronnessCut = kArea;
+        if (str==(TString)"hadronness")
+            fHadronnessCut = kHadronness;
+        if (str==(TString)"all")
+            fHadronnessCut = kAll;
+
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "CalcDisp", print))
+    {
+        fCalcDisp = GetEnvValue(env, prefix, "CalcDisp", fCalcDisp);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "CalcGhostbuster", print))
+    {
+        fCalcGhostbuster = GetEnvValue(env, prefix, "CalcGhostbuster", fCalcGhostbuster);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "File", print))
+    {
+        const TString fname = GetEnvValue(env, prefix, "File", "");
+        if (!CoefficentsRead(fname))
+            return kERROR;
+
+        return kTRUE;
+    }
+
+    for (int i=0; i<fVariables.GetSize(); i++)
+    {
+        if (IsEnvDefined(env, prefix, Form("Param%d", i), print))
+        {
+            // It is important that the last argument is a floating point
+            fVariables[i] = GetEnvValue(env, prefix, Form("Param%d", i), 0.0);
+            rc = kTRUE;
+        }
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFMagicCuts.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFMagicCuts.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFMagicCuts.h	(revision 17960)
@@ -0,0 +1,119 @@
+#ifndef MARS_MFMagicCuts
+#define MARS_MFMagicCuts
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MParList;
+
+class MGeomCam;
+class MHillas;
+class MHillasSrc;
+class MHillasExt;
+class MNewImagePar;
+class MParameterD;
+class MPointingPos;
+class MHMatrix;
+
+class MFMagicCuts : public MFilter
+{
+public:
+    // Possible kind of theta cuts
+    enum ThetaCut_t {
+        kNone  =BIT(0),
+        kOn    =BIT(1),
+        kOff   =BIT(2),
+        kWobble=kOn|kOff
+    };
+    // Possible kind of hadronness cuts
+    enum HadronnessCut_t {
+        kNoCut     =BIT(0),
+        kArea      =BIT(1),
+        kHadronness=BIT(2),
+        kAreaLin   =BIT(3),
+        kAll       =kArea|kHadronness
+    };
+
+private:
+    // Elements for mapping. kLastElement must not be used and must be
+    // the last on in the list. It is used as counter for fMap.
+    enum {
+        kESize, kEAlpha, kEAlphaAnti, kEArea, kEDist, kEDistAnti,
+        kEM3Long, kEM3LongAnti, kEWdivL, kELeakage, kESlope,
+        kESlopeAnti, kEHadronness, kESign, kEDisp, kEGhostbuster,
+        kLastElement
+    };
+
+    MGeomCam       *fGeom;              //! Conversion factor from mm to deg
+    MHillas        *fHil;               //! Pointer to MHillas container
+    MHillasSrc     *fHilSrc;            //! Pointer to MHillasSrc container
+    MHillasSrc     *fHilAnti;           //! Pointer to MHillasSrc container called MHillasSrcAnti
+    MHillasExt     *fHilExt;            //! Pointer to MHillasExt container
+    MNewImagePar   *fNewImgPar;         //! Pointer to MHillasExt container
+    MParameterD    *fThetaSq;           //! Pointer to MParameterD container called ThetaSq
+    MParameterD    *fDisp;              //! Pointer to MParameterD container called Disp
+    MParameterD    *fGhostbuster;       //! Pointer to MParameterD container called Ghostbuster
+    MParameterD    *fHadronness;        //! Pointer to MParameterD container called Hadronness
+
+    Bool_t          fResult;            //! Result of the filter evaluation
+
+    Int_t           fMap[kLastElement]; //! Mapping table for fast optimization
+    MHMatrix       *fMatrix;            //! Matrix thorugh which the mapped elements are accessed
+
+    TArrayD         fVariables;         // Coefficients of cuts
+
+    ThetaCut_t      fThetaCut;          // Which kind of theta cut should be evaluated
+    HadronnessCut_t fHadronnessCut;     // Which kind of hadronness cut should be evaluated
+    Bool_t          fCalcDisp;          // Should we use Disp from the parameterlist?
+    Bool_t          fCalcGhostbuster;   // Should we use Ghostbuster from the parameterlist?
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    // MFilter
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    // MFMagicCuts
+    Double_t GetDisp(Double_t slope, Double_t lgsize) const;
+    Bool_t   IsGhost(Double_t m3long, Double_t slope, Double_t dist) const;
+    Double_t GetVal(Int_t i) const;
+    TString  GetParam(Int_t i) const;
+    Double_t GetThetaSq(Double_t p, Double_t d, Double_t a) const;
+
+public:
+    MFMagicCuts(const char *name=NULL, const char *title=NULL);
+
+    // Getter
+    Double_t GetThetaSqCut() const;
+
+    // Setter
+    void   SetThetaCut(ThetaCut_t c) { fThetaCut=c; }
+    void   SetHadronnessCut(HadronnessCut_t c) { fHadronnessCut=c; }
+    void   SetCalcDisp(Bool_t b=kTRUE) { fCalcDisp=b; }
+    void   SetCalcGhostbuster(Bool_t b=kTRUE) { fCalcGhostbuster=b; }
+
+    // MFMagicCuts
+    void   InitMapping(MHMatrix *mat);
+    void   StopMapping() { InitMapping(NULL); }
+
+    Bool_t CoefficentsRead(const char *fname);
+    Bool_t CoefficentsWrite(const char *fname) const;
+
+    // MParContainer
+    void   SetVariables(const TArrayD &arr);
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // TObject
+    void   Print(Option_t *o="") const;
+
+    ClassDef(MFMagicCuts, 2) // A filter to evaluate the MagicCuts
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfilter/MFParticleId.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFParticleId.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFParticleId.cc	(revision 17960)
@@ -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(ostream &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: branches/Mars_McMismatchStudy/mfilter/MFParticleId.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFParticleId.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFParticleId.h	(revision 17960)
@@ -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(std::ostream &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: branches/Mars_McMismatchStudy/mfilter/MFSoftwareTrigger.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFSoftwareTrigger.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFSoftwareTrigger.cc	(revision 17960)
@@ -0,0 +1,509 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFSoftwareTrigger
+//
+//  This is a class to evaluate a software trigger
+//
+//  The number of required pixels is setup by:
+//   SetNumNeighbors(4)   // default
+//
+//  The Threshold is setup by:
+//    SetThreshold(5)     // default
+//
+//  Time window for coincidence:
+//    SetTimeWindow(3.3)
+// To switch off time-coincidence use
+//    SetTimeWindow(-1)
+//   or
+//    SetTimeWindow()
+//
+//  kSinglePixelsNeighbors <default>
+//  ----------------------
+//    Checks whether there is at least one pixel above threshold which
+//    has fNumNeighbors direct neighbors which are also above threshold.
+//    The outermost ring of pixels is ignord. Only 'used' pixels are
+//    taken into account.
+//
+//  kAnyPattern 
+//  -----------
+//    Checks whether it find a cluster of pixels above fThreshold which
+//    has a size bigger/equal than fNumNeighbors. The layout (pattern) of
+//    the cluster is ignored. Unmapped pixels are ignored.
+//
+//  WARNING: Using trigger type kAllPattern resets the BIT(21) bit
+//           of all pixels in MSignalCam
+//
+//
+//  Input:
+//    MSignalCam
+//    MGeomCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFSoftwareTrigger.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeom.h"
+#include "MGeomCam.h"
+
+#include "MSignalCam.h"
+//#include "MArrivalTime.h"
+
+ClassImp(MFSoftwareTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFSoftwareTrigger::MFSoftwareTrigger(const char *name, const char *title)
+    : fCam(NULL), fEvt(NULL), fThreshold(5),
+    fTimeWindow(1.7), fNumNeighbors(4), fType(kSinglePixelNeighbors)
+{
+    fName  = name  ? name  : "MFSoftwareTrigger";
+    fTitle = title ? title : "Filter for software trigger";
+}
+
+// --------------------------------------------------------------------------
+//
+// This function recursively finds all pixels of one island and sets
+// BIT(14) for the pixel.
+//
+//  1) Check whether a pixel with the index idx exists, is unused
+//     and has not yet BIT(14) set
+//  2) Set BIT(14) to the pixel
+//  3) Loop over all its neighbors taken from the geometry geom. For all
+//     neighbors recursively call this function (CountPixels)
+//  4) Sum the number of valid neighbors newly found
+//
+// Returns the size of the cluster
+//
+Int_t MFSoftwareTrigger::CountPixels(Int_t idx, Float_t tm0) const
+{
+    // get the pixel information of a pixel with this index
+    MSignalPix &pix = (*fEvt)[idx];
+
+    // If pixel already assigned to a cluster
+    if (pix.TestBit(kWasChecked))
+        return 0;
+
+    if (pix.IsPixelUnmapped())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix.SetBit(kWasChecked);
+
+    // Get the size of this pixel and check threshold
+    const Double_t size = pix.GetNumPhotons()*fCam->GetPixRatio(idx);
+    if (size<fThreshold)
+        return 0;
+
+    const Float_t tm1 = pix.GetArrivalTime();
+    if (TMath::Abs(tm1-tm0)>fTimeWindow)
+        return 0;
+
+    //pix.SetBit(kAboveThreshold);
+
+    Int_t num = 1;
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeom &gpix = (*fCam)[idx];
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        num += CountPixels(gpix.GetNeighbor(i), tm1);
+
+    // return size of this (sub)cluster
+    return num;
+}
+/*
+Int_t MFSoftwareTrigger::CountCoincidencePixels(Int_t idx) const
+{
+    // Try to get the pixel information of a pixel with this index
+    MSignalPix *pix = fEvt->GetPixById(idx);
+
+    // If a pixel with this index is not existing... do nothing.
+    if (!pix)
+        return 0;
+
+    // If pixel already assigned to a cluster
+    if (pix->TestBit(kWasChecked))
+        return 0;
+
+    if (pix->IsPixelUnmapped())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix->SetBit(kWasChecked);
+
+    // Get the size of this pixel and check threshold
+    const Double_t size = pix->GetNumPhotons();
+    if (size<fThreshold)
+        return 0;
+
+    Int_t num = 1;
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeomPix &gpix = (*fCam)[idx];
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        num += CountPixels(gpix.GetNeighbor(i));
+
+    // return size of this (sub)cluster
+    return num;
+}
+*/
+void MFSoftwareTrigger::ResetBits(Int_t bits) const
+{
+    TObject *obj=0;
+
+    TIter Next(*fEvt);
+    while ((obj=Next()))
+        obj->ResetBit(bits);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if there is at least one pixel which fullfills the condition
+//
+Bool_t MFSoftwareTrigger::ClusterTrigger() const
+{
+    ResetBits(kWasChecked);
+
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        const MSignalPix &pix = (*fEvt)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // Check if trigger condition is fullfilled for this pixel
+        if (CountPixels(idx, pix.GetArrivalTime()) >= fNumNeighbors)
+            return kTRUE;
+    }
+
+/*
+    // Reset bit
+    MSignalPix *pix=0;
+
+    // We could loop over all indices which looks more straight
+    // forward but should be a lot slower (assuming zero supression)
+    TIter Next(*fEvt);
+    while ((pix=static_cast<MSignalPix*>(Next())))
+    {
+        // Check if trigger condition is fullfilled for this pixel
+        const Int_t idx = pix->GetPixId();
+        if (CountPixels(idx, (*fTme)[idx]) >= fNumNeighbors)
+            return kTRUE;
+    }
+  */
+    return kFALSE;
+}
+/*
+Int_t MFSoftwareTrigger::CheckCoincidence(Int_t idx, Float_t tm0) const
+{
+    // Try to get the pixel information of a pixel with this index
+    MSignalPix *pix = fEvt->GetPixById(idx);
+
+    // If a pixel with this index is not existing... do nothing.
+    if (!pix)
+        return 0;
+
+    // If pixel already assigned to a cluster
+    if (pix->TestBit(kWasChecked))
+        return 0;
+
+    if (pix->IsPixelUnmapped())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix->SetBit(kWasChecked);
+
+    const Double_t size = pix->GetNumPhotons();
+    if (size<fThreshold)
+        return 0;
+
+    const Float_t tm1 = (*fTme)[idx];
+    if (TMath::Abs(tm1-tm0)>fTimeWindow)
+        return 0;
+
+    pix->SetBit(kIsCoincident);
+
+
+    Int_t num = 1;
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeomPix &gpix = (*fCam)[idx];
+
+    Int_t cnt = 0;
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+    {
+        const Int_t rc = CheckCoincidence(gpix.GetNeighbor(i), tm0);
+        if (fEvt->GetPixById(gpix.GetNeighbor(i))->TestBit(kIsCoincident))
+            cnt++;
+        num += rc;
+    }
+
+    // return size of this (sub)cluster
+    return cnt<2 ? 0 : num;
+
+}
+
+Bool_t MFSoftwareTrigger::MagicLvl1Trigger() const
+{
+    // Reset bit
+    MSignalPix *pix=0;
+
+    // We could loop over all indices which looks more straight
+    // forward but should be a lot slower (assuming zero supression)
+    TIter Next(*fEvt);
+    while ((pix=static_cast<MSignalPix*>(Next())))
+    {
+        ResetBits(kWasChecked|kIsCoincident);
+
+        const Int_t idx = pix->GetPixId();
+        if (CheckCoincidence(idx, (*fTme)[idx])<fNumNeighbors)
+            continue;
+
+        return kTRUE;
+    }
+    return kFALSE;
+}
+*/
+
+const MSignalPix *MFSoftwareTrigger::CheckPixel(Int_t i) const
+{
+    const MSignalPix &pix = (*fEvt)[i];
+
+    if (!pix.IsPixelUsed())
+        return NULL;
+
+    if (pix.GetNumPhotons()*fCam->GetPixRatio(i)<fThreshold)
+        return NULL;
+
+    if ((*fCam)[i].IsInOutermostRing())
+        return NULL;
+
+    return &pix;
+}
+
+// --------------------------------------------------------------------------
+//
+// Software single pixel coincidence trigger
+//
+Bool_t MFSoftwareTrigger::SwTrigger() const
+{
+    const Int_t entries = fEvt->GetNumPixels();
+ 
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MSignalPix *pix0 = CheckPixel(i);
+        if (!pix0)
+            continue;
+
+        Int_t num = 1;
+
+        const MGeom &gpix = (*fCam)[i];
+
+        const Int_t nneighbors = gpix.GetNumNeighbors();
+        for (Int_t n=0; n<nneighbors; n++)
+        {
+            const Int_t idx1 = gpix.GetNeighbor(n);
+
+            const MSignalPix *pix1 = CheckPixel(idx1);
+            if (!pix1)
+                continue;
+
+            const Float_t t0 = pix0->GetArrivalTime();
+            const Float_t t1 = pix1->GetArrivalTime();
+
+            if (TMath::Abs(t0-t1)>fTimeWindow)
+                continue;
+
+            if (++num==fNumNeighbors)
+                return kTRUE;
+        }
+    }
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Request pointer to MSignalCam and MGeomCam from paremeter list
+//
+Int_t MFSoftwareTrigger::PreProcess(MParList *pList)
+{
+    fEvt = (MSignalCam*)pList->FindObject("MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << "MSignalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    memset(fCut, 0, sizeof(fCut));
+
+    switch (fType)
+    {
+    case kSinglePixelNeighbors:
+        if (fNumNeighbors<2)
+            *fLog << inf << "Software trigger switched off (fNumNeighbors<2)." << endl;
+        else
+            *fLog << inf << fNumNeighbors << " required above " << fThreshold << " within " << fTimeWindow << "ns." << endl;
+        break;
+    case kAnyPattern:
+        *fLog << inf << "Cluster trigger switched on." << endl;
+        break;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate software trigger
+//
+Int_t MFSoftwareTrigger::Process()
+{
+    switch (fType)
+    {
+    case kSinglePixelNeighbors:
+        fResult = fNumNeighbors>1 ? SwTrigger() : kTRUE;
+        break;
+    case kAnyPattern:
+        fResult = ClusterTrigger();
+        break;
+    }
+
+    fCut[fResult ? 0 : 1]++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Basic selections.
+//
+Int_t MFSoftwareTrigger::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    TString type;
+    switch (fType)
+    {
+    case kSinglePixelNeighbors:
+        type = " single pixel trigger";
+        break;
+    case kAnyPattern:
+        type = " any pattern trigger";
+        break;
+    }
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << " Threshold=" << fThreshold << ", Number=" << (int)fNumNeighbors;
+    if (fTimeWindow>0)
+        *fLog << ", Time Window=" << fTimeWindow << "ns";
+    *fLog << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << " " << setw(7) << fCut[0] << " (" << setw(3) ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions());
+    *fLog << "%) Evts fullfilled" << type << endl;
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions());
+    *fLog << "%) Evts didn't fullfill" << type << "."  << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MFSoftwareTrigger.Threshold:    5
+//   MFSoftwareTrigger.NumNeighbors: 4
+//   MFSoftwareTrigger.TimeWindow: 3.3
+//   MFSoftwareTrigger.TriggerType: SinglePixel, AnyPattern
+//
+// To switch off time-coincidence use
+//   MFSoftwareTrigger.TimeWindow: -1
+//
+Int_t MFSoftwareTrigger::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Threshold", print))
+    {
+        rc = kTRUE;
+        SetThreshold(GetEnvValue(env, prefix, "Threshold", fThreshold));
+    }
+    if (IsEnvDefined(env, prefix, "NumNeighbors", print))
+    {
+        rc = kTRUE;
+        SetNumNeighbors(GetEnvValue(env, prefix, "NumNeighbors", fNumNeighbors));
+    }
+    if (IsEnvDefined(env, prefix, "TimeWindow", print))
+    {
+        rc = kTRUE;
+        SetTimeWindow(GetEnvValue(env, prefix, "TimeWindow", fTimeWindow));
+    }
+
+    if (IsEnvDefined(env, prefix, "TriggerType", print))
+    {
+        TString dat = GetEnvValue(env, prefix, "TriggerType", "");
+        dat = dat.Strip(TString::kBoth);
+        dat.ToLower();
+
+        if (dat == (TString)"singlepixel")
+            SetTriggerType(kSinglePixelNeighbors);
+        if (dat == (TString)"anypattern")
+            SetTriggerType(kAnyPattern);
+
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFSoftwareTrigger.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFSoftwareTrigger.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFSoftwareTrigger.h	(revision 17960)
@@ -0,0 +1,72 @@
+#ifndef MARS_MFSoftwareTrigger
+#define MARS_MFSoftwareTrigger
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MGeomCam;
+class MSignalCam;
+class MSignalPix;
+class MArrivalTime;
+
+class MFSoftwareTrigger : public MFilter
+{
+public:
+    enum TriggerType_t {
+        kSinglePixelNeighbors,
+        kAnyPattern/*,
+        kMagicLvl1*/
+    };
+
+private:
+    const MGeomCam     *fCam; // Camera Geometry
+    const MSignalCam   *fEvt; // Cerenkov Photon Event
+    const MArrivalTime *fTme;
+
+    Float_t     fThreshold;     // nuber of minimum required photons
+    Float_t     fTimeWindow;    // Window for time coincidence
+    Byte_t      fNumNeighbors;  // number of required neighbours
+
+    Int_t       fCut[2];
+
+    Bool_t      fResult;
+
+    TriggerType_t fType;
+
+    enum {
+        kWasChecked     = BIT(21),
+        kAboveThreshold = BIT(22),
+        kIsCoincident   = BIT(23)
+    };
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void ResetBits(Int_t bits) const;
+    const MSignalPix *CheckPixel(Int_t i) const;
+    Bool_t SwTrigger() const;
+    Bool_t SwCoincidence() const;
+    //Int_t CheckCoincidence(Int_t idx, Float_t tm0) const;
+    //Bool_t MagicLvl1Trigger() const;
+    Int_t  CountPixels(Int_t idx, Float_t tm) const;
+    Bool_t ClusterTrigger() const;
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+public:
+    MFSoftwareTrigger(const char *name=NULL, const char *title=NULL);
+
+    void SetThreshold(Float_t min)          { fThreshold    = min; }
+    void SetNumNeighbors(Byte_t num)        { fNumNeighbors = num; }
+    void SetTimeWindow(Float_t win=-1)      { fTimeWindow   = win; }
+    void SetTriggerType(TriggerType_t type) { fType = type; }
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MFSoftwareTrigger, 0) // Filter for software trigger
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfilter/MFSupercuts.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFSupercuts.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFSupercuts.cc	(revision 17960)
@@ -0,0 +1,321 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFSupercuts
+//
+//   this class calculates the hadronness for the supercuts
+//   the parameters of the supercuts are taken
+//                  from the container MSupercuts
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFSupercuts.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "TFile.h"
+#include "TArrayD.h"
+
+#include "MParList.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MGeomCam.h"
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFSupercuts);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+
+MFSupercuts::MFSupercuts(const char *name, const char *title)
+    : fHil(0), fHilSrc(0), fHilExt(0), fNewPar(0), fMatrix(0), fVariables(84)
+{
+    fName  = name  ? name  : "MFSupercuts";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fMatrix = NULL;
+
+    AddToBranchList("MHillas.fWidth");
+    AddToBranchList("MHillas.fLength");
+    AddToBranchList("MHillasSrc.fDist");
+    AddToBranchList("MHillas.fSize");
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFSupercuts::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    if (fMatrix)
+        return kTRUE;
+
+    //-----------------------------------------------------------
+    fHil = (MHillas*)pList->FindObject("MHillas");
+    if (!fHil)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject("MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << "MHillasExt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject("MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << "MHillasSrc not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << "MNewImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+/*
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+  */
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MFSupercuts::GetVal(Int_t i) const
+{
+    return (*fMatrix)[fMap[i]];
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+void MFSupercuts::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    //fMap[0]  = fMatrix->AddColumn("MPointingPos.fZd");
+    fMap[0]  = fMatrix->AddColumn("MHillas.fWidth*MGeomCam.fConvMm2Deg");
+    fMap[1]  = fMatrix->AddColumn("MHillas.fLength*MGeomCam.fConvMm2Deg");
+    fMap[2]  = fMatrix->AddColumn("MHillasSrc.fDist*MGeomCam.fConvMm2Deg");
+    fMap[3]  = fMatrix->AddColumn("log10(MHillas.fSize)");
+    //fMap[7]  = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+    /*
+     fMap[8]  = fMatrix->AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+     fMap[9]  = fMatrix->AddColumn("MNewImagePar.fConc");
+     fMap[10] = fMatrix->AddColumn("MNewImagePar.fLeakage1");
+     */
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculation of upper and lower limits
+//
+Double_t MFSupercuts::CtsMCut(const Double_t* a,  Double_t ls, Double_t ct,
+                                    Double_t ls2, Double_t dd2) const
+{
+    // define cut-function
+    //
+    //    dNOMLOGSIZE = 5.0 (=log(150.0)
+    //    dNOMCOSZA   = 1.0
+    //
+    //      a: array of cut parameters
+    //     ls: log(SIZE) - dNOMLOGSIZE
+    //    ls2: ls^2
+    //     ct: Cos(ZA.) - dNOMCOSZA
+    //    dd2: DIST^2
+    const Double_t limit =
+        a[0] + a[1] * dd2 + a[2] * ct  +
+        ls  * (a[3] + a[4] * dd2 + a[5] * ct) +
+        ls2 * (a[6] + a[7] * dd2);
+
+    return limit;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical supercuts 
+// 
+//          set hadronness to 0.25 if cuts are fullfilled
+//                            0.75 otherwise
+//
+Int_t MFSupercuts::Process()
+{
+    //  const Double_t kNomLogSize = 4.1;
+    //  const Double_t kNomCosZA   = 1.0;
+
+    //  const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();
+    //  const Double_t meanx   = fMatrix ? GetVal(4) : fHil->GetMeanX()*fMm2Deg;
+    //  const Double_t meany   = fMatrix ? GetVal(5) : fHil->GetMeanY()*fMm2Deg;
+    //  const Double_t asym0   = fMatrix ? GetVal(8) : TMath::Sign(fHilExt->GetM3Long(), fHilSrc->GetCosDeltaAlpha());;
+    //  const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+    //  const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+    //  const Double_t asym    = asym0   * fMm2Deg;
+
+    const Double_t width   = fMatrix ? GetVal(0) : fHil->GetWidth()*fMm2Deg;
+    const Double_t length  = fMatrix ? GetVal(1) : fHil->GetLength()*fMm2Deg;
+    const Double_t dist    = fMatrix ? GetVal(2) : fHilSrc->GetDist()*fMm2Deg;
+    const Double_t lgsize  = fMatrix ? GetVal(3) : log10(fHil->GetSize());
+
+    const Double_t dist2     = dist*dist;
+    const Double_t lgsize2   = lgsize * lgsize;
+    const Double_t cost      = 0; // cos(theta*TMath::DegToRad()) - kNomCosZA;
+
+    fResult =
+        // Length cuts
+        length > CtsMCut(fVariables.GetArray()+ 0, lgsize, cost, lgsize2, dist2) &&
+        length < CtsMCut(fVariables.GetArray()+ 8, lgsize, cost, lgsize2, dist2) &&
+        // Width cuts
+        width  > CtsMCut(fVariables.GetArray()+16, lgsize, cost, lgsize2, dist2) &&
+        width  < CtsMCut(fVariables.GetArray()+24, lgsize, cost, lgsize2, dist2) &&
+        // Dist cuts
+        dist   > CtsMCut(fVariables.GetArray()+32, lgsize, cost, lgsize2, dist2) &&
+        dist   < CtsMCut(fVariables.GetArray()+40, lgsize, cost, lgsize2, dist2);
+
+        /*
+         asym    < CtsMCut(&fVariables[42], dmls, dmcza, dmls2, dd2) &&
+         asym    > CtsMCut(&fVariables[49], dmls, dmcza, dmls2, dd2) &&
+
+         conc    < CtsMCut(&fVariables[56], dmls, dmcza, dmls2, dd2) &&
+         conc    > CtsMCut(&fVariables[63], dmls, dmcza, dmls2, dd2) &&
+
+         leakage < CtsMCut(&fVariables[70], dmls, dmcza, dmls2, dd2) &&
+         leakage > CtsMCut(&fVariables[77], dmls, dmcza, dmls2, dd2))
+         */
+
+    return kTRUE;
+}
+
+TString MFSupercuts::GetDataMember() const
+{
+    return "MHillas.fWidth,MHillas.fLength,MHillasSrc.fDist,MHillas.fSize";
+}
+
+void MFSupercuts::SetVariables(const TArrayD &arr)
+{
+    fVariables = arr;
+}
+
+Bool_t MFSupercuts::CoefficentsRead(const char *fname)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    for (int i=0; i<fVariables.GetSize(); i++)
+    {
+        fin >> fVariables[i];
+        if (!fin)
+        {
+            *fLog << err << "ERROR - Not enough coefficients in file " << fname << endl;
+            return kERROR;
+        }
+    }
+    return kTRUE;
+}
+
+Bool_t MFSupercuts::CoefficentsWrite(const char *fname) const
+{
+    ofstream fout(fname);
+    if (!fout)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    for (int i=0; i<fVariables.GetSize(); i++)
+        fout << setw(11) << fVariables[i] << endl;
+
+    return kTRUE;
+}
+
+Int_t MFSupercuts::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (MFilter::ReadEnv(env, prefix, print)==kERROR)
+        return kERROR;
+
+    if (IsEnvDefined(env, prefix, "File", print))
+    {
+        const TString fname = GetEnvValue(env, prefix, "File", "");
+        if (!CoefficentsRead(fname))
+            return kERROR;
+
+        return kTRUE;
+    }
+
+    Bool_t rc = kFALSE;
+    for (int i=0; i<fVariables.GetSize(); i++)
+    {
+        if (IsEnvDefined(env, prefix, Form("Param%d", i), print))
+        {
+            fVariables[i] = GetEnvValue(env, prefix, Form("Param%d", i), 0);
+            rc = kTRUE;
+        }
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFSupercuts.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFSupercuts.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFSupercuts.h	(revision 17960)
@@ -0,0 +1,67 @@
+#ifndef MARS_MFSupercuts
+#define MARS_MFSupercuts
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MParList;
+class MHillas;
+class MHillasSrc;
+class MHillasExt;
+class MNewImagePar;
+class MCerPhotEvt;
+class MGeomCam;
+class MHadronness;
+class MHMatrix;
+
+class MFSupercuts : public MFilter
+{
+private:
+    MHillas       *fHil;        //!
+    MHillasSrc    *fHilSrc;     //!
+    MHillasExt    *fHilExt;     //!
+    MNewImagePar  *fNewPar;     //!
+
+    Double_t       fMm2Deg;     //!
+    Bool_t fResult;             //!
+
+    Int_t     fMap[11];         //!
+    MHMatrix *fMatrix;          //!
+
+    TArrayD fVariables;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    Double_t GetVal(Int_t i) const;
+
+    Double_t CtsMCut(const Double_t* a, Double_t ls, Double_t ct,
+                     Double_t ls2, Double_t dd2) const;
+
+    TString GetDataMember() const;
+    //TString GetRule() const { return "<MFSupercuts>"; }
+
+public:
+    MFSupercuts(const char *name=NULL, const char *title=NULL);
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping() { InitMapping(NULL); }
+
+    void SetVariables(const TArrayD &arr);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    Bool_t CoefficentsRead(const char *fname);
+    Bool_t CoefficentsWrite(const char *fname) const;
+
+    ClassDef(MFSupercuts, 0) // A filter to evaluate the Supercuts
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl1.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl1.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl1.cc	(revision 17960)
@@ -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(ostream &out) const
+{
+    if (fMcTrig)
+        fMcTrig->SavePrimitive(out);
+
+    out << "   MFTriggerLvl1 " << GetUniqueName() << "(";
+
+    if (fMcTrig)
+        out << "&" << fMcTrig->GetUniqueName();
+    else
+        out << "\"" << fContName << "\"";
+
+    out << ", '" << (fFilterType==kELowerThan?"<":">") << "', " << fValue << ");" << endl;
+
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl1.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl1.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl1.h	(revision 17960)
@@ -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(std::ostream &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: branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl2.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl2.cc	(revision 17960)
@@ -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(ostream &out) const
+{
+   if (fcell)
+        fcell->SavePrimitive(out);
+
+    out << "   MFTriggerLvl2 " << GetUniqueName() << "(";
+
+    if (fcell)
+        out << "&" << fcell->GetUniqueName();
+    else
+        out << "\"" << fContName << "\"";
+
+    out << ", '" << (fFilterType==kELowerThan?"<":">") << "', " << fValue << ");" << endl;
+
+}
Index: branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl2.h
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/MFTriggerLvl2.h	(revision 17960)
@@ -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(std::ostream &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: branches/Mars_McMismatchStudy/mfilter/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/Makefile	(revision 17960)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mfbase -I../mraw -I../mdata \
+           -I../manalysis -I../mpointing -I../mfileio -I../mgeom \
+           -I../mimage -I../mgui -I../mmc -I../mhbase -I../msignal \
+           -I../mpedestal -I../mbadpixels -I../mcalib
+
+CINT     = Filter
+
+SRCFILES = MFTriggerLvl1.cc \
+	   MFTriggerLvl2.cc \
+           MFMagicCuts.cc \
+	   MFGeomag.cc \
+	   MFEvtNumber.cc \
+           MFDeltaT.cc \
+	   MFParticleId.cc \
+           MFSoftwareTrigger.cc \
+           MFCosmics.cc \
+	   MFEnergySlope.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mfilter/gcminus.txt
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/gcminus.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/gcminus.txt	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfilter/gcplus.txt
===================================================================
--- branches/Mars_McMismatchStudy/mfilter/gcplus.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfilter/gcplus.txt	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mfit/MTFitLoop.cc
===================================================================
--- branches/Mars_McMismatchStudy/mfit/MTFitLoop.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfit/MTFitLoop.cc	(revision 17960)
@@ -0,0 +1,238 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTFitLoop
+//
+// This class optimized parameters which are calculated in an eventloop.
+// For this it is unimportant whether the loop reads from a file a
+// matrix or from somewhere else...
+//
+// The parameters which are optimized must be stored in a MParContainer
+// which overwrites SetVariables(). Eg. a MDataPhrase or MF overwrites
+// SetVariables(). In a MF all arguments given as [0], [1] are
+// set by SetVariables (in MDataValue).
+//  eg: In you loop you have a cut like this:
+//      MF filter("MHillas.fWidth<[0]");
+//      filter.SetName("MyParameters");
+//
+//  Now for each time the eventloop is executed
+//  (MEvtLoop::Eventloop(fNumEvents)) the parameters from TMinuit are
+//  passed to MF::SetVariables and changed.
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTFitLoop.h"
+
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TStopwatch.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MParameters.h"
+
+#include "MRead.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTFitLoop);
+
+using namespace std;
+
+//------------------------------------------------------------------------
+//
+// fcn calculates the function to be minimized (using TMinuit::Migrad)
+//
+void MTFitLoop::fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    MTFitLoop *optim = (MTFitLoop*)gMinuit->GetObjectFit();
+
+    TMinuit *minuit = gMinuit;
+    f = optim->Fcn(npar, gin, par, iflag);
+    gMinuit = minuit;
+
+}
+Double_t MTFitLoop::Fcn(Int_t &npar, Double_t *gin, Double_t *par, Int_t iflag)
+{
+    MParList *plist = fEvtLoop->GetParList();
+
+    MParameterD   *eval = (MParameterD*)  plist->FindCreateObj("MParameterD", fFitParameter);
+    MParContainer *pars = (MParContainer*)plist->FindObject(fParametersName);
+
+    MRead *read = (MRead*)plist->FindObject("MTaskList")->FindObject("MRead");
+    if (read)
+        read->Rewind();
+
+    if (fDebug>=1)
+    {
+        Double_t fmin, fedm, errdef;
+        Int_t n1, n2, istat;
+        gMinuit->mnstat(fmin, fedm, errdef, n1, n2, istat);
+        *fLog << inf << underline << "Minimization Status so far:" << endl;
+        *fLog << " Calls:     " << gMinuit->fNfcn << endl;
+        *fLog << " Func min:  " << fmin << endl;
+        *fLog << " Found edm: " << fedm << endl;
+        *fLog << " ErrDef:    " << errdef << endl;
+        *fLog << " Status:    ";
+        switch (istat)
+        {
+        case 0:  *fLog << "n/a" << endl; break;
+        case 1:  *fLog << "approximation only, not accurate" << endl; break;
+        case 2:  *fLog << "full matrix, but forced positive-definite" << endl; break;
+        case 3:  *fLog << "full accurate covariance matrix" << endl; break;
+        default: *fLog << "undefined" << endl; break;
+        }
+    }
+
+    if (fDebug>=0)
+    {
+        *fLog << inf << "Set(" << gMinuit->fMaxpar << "): ";
+        for (Int_t i=0; i<gMinuit->fMaxpar; i++)
+            *fLog << par[i] << " ";
+        *fLog << endl;
+    }
+ 
+    pars->SetVariables(TArrayD(gMinuit->fMaxpar, par));
+
+    if (fDebug<3)
+        gLog.SetNullOutput(kTRUE);
+    fEvtLoop->Eventloop(fNumEvents);
+    if (fDebug<3)
+        gLog.SetNullOutput(kFALSE);
+
+    const Double_t f = eval->GetVal();
+
+    if (fDebug>=0)
+        *fLog << inf << "F=" << f << endl;
+
+    if (fDebug>=1)
+        fEvtLoop->GetTaskList()->PrintStatistics();
+
+    return f;
+}
+
+MTFitLoop::MTFitLoop(Int_t num) : fNum(num), fMaxIterations(1000)
+{
+    fDebug     = -1;
+    fNumEvents = -1;
+}
+
+void MTFitLoop::Optimize(MEvtLoop &loop, TArrayD &pars)
+{
+    *fLog << inf << "Event loop was setup" << endl;
+    MParList *parlist = loop.GetParList();
+    if (!parlist)
+        return;
+
+//    MParContainer *pars = (MParContainer*)parlist->FindObject(fParametersName);
+//    if (!pars)
+//        return;
+
+    fEvtLoop = &loop;
+
+//    MParContainer &parameters = *pars;
+
+    TMinuit *minsave = gMinuit;
+
+    gMinuit = new TMinuit(pars.GetSize());
+    gMinuit->SetPrintLevel(-1);
+    gMinuit->SetMaxIterations(fMaxIterations);
+
+    gMinuit->SetFCN(fcn);
+    gMinuit->SetObjectFit(this);
+
+     // For chisq fits call this // seems to be something like %)
+     //
+     // The default tolerance is 0.1, and the minimization will stop");
+     // when the estimated vertical distance to the minimum (EDM) is");
+     // less than 0.001*[tolerance]*UP (see [SET ERRordef]).");
+     //
+    if (gMinuit->SetErrorDef(1))
+    {
+        *fLog << err << dbginf << "SetErrorDef failed." << endl;
+        return;
+    }
+
+    //
+    // Set starting values and step sizes for parameters
+    //
+    for (Int_t i=0; i<pars.GetSize(); i++)
+    {
+        TString name = "par[";
+        name += i;
+        name += "]";
+        Double_t vinit = pars[i];
+        Double_t step  = fabs(pars[i]/3);
+
+        Double_t limlo = 0; // limlo=limup=0: no limits
+        Double_t limup = 2*vinit;
+
+        Bool_t rc = gMinuit->DefineParameter(i, name, vinit, step, 0, limup);
+        if (!rc)
+            continue;
+
+        *fLog << err << dbginf << "Error in defining parameter #" << i << endl;
+        return;
+    }
+
+    for (int i=0; i<pars.GetSize() && i<fFixedParams.GetSize(); i++)
+        if (fFixedParams[i]!=0)
+            gMinuit->FixParameter(i);
+
+    // Now ready for minimization step:
+
+    TStopwatch clock;
+    clock.Start();
+    const Bool_t rc = gMinuit->Migrad();
+    clock.Stop();
+    clock.Print();
+
+    if (rc)
+    {
+        *fLog << err << dbginf << "Migrad failed." << endl;
+        return;
+    }
+
+    *fLog << inf << "Resulting Chisq: " << gMinuit->fAmin << endl;
+
+    //
+    // Update values of fA, fB:
+    //
+    for (Int_t i=0; i<pars.GetSize(); i++)
+    {
+        Double_t x1, x2;
+        gMinuit->GetParameter(i,x1,x2);
+        pars[i] = x1;
+        cout << i << ": " << pars[i] << endl;
+    }
+
+    //list.SetVariables(pars);
+
+    gMinuit = minsave;
+}
Index: branches/Mars_McMismatchStudy/mfit/MTFitLoop.h
===================================================================
--- branches/Mars_McMismatchStudy/mfit/MTFitLoop.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mfit/MTFitLoop.h	(revision 17960)
@@ -0,0 +1,50 @@
+#ifndef MARS_MTFitLoop
+#define MARS_MTFitLoop
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+class MEvtLoop;
+
+class MTFitLoop : public MParContainer
+{
+private:
+    Int_t fDebug;     // -1 no output, 0 MTFitLoop output, 1 PrintStatistics output
+    Int_t fNumEvents;
+
+    static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag);
+    virtual Double_t Fcn(Int_t &npar, Double_t *gin, Double_t *par, Int_t iflag);
+
+    MEvtLoop *fEvtLoop;
+
+    TString   fParametersName;
+    TString   fFitParameter;
+
+    TArrayC   fFixedParams;
+
+    Int_t fNum;
+    Int_t fMaxIterations;
+
+public:
+    MTFitLoop(const Int_t num=0);
+
+    void Optimize(MEvtLoop &loop, TArrayD &pars);
+
+    void SetNameParameters(const char *parm) { fParametersName = parm; }
+    void SetFitParameter(const char *parm)   { fFitParameter   = parm; }
+
+    void SetFixedParameters(const TArrayC &c) { fFixedParams = c; }
+    void SetMaxIterations(Int_t maxiter=500) {fMaxIterations = maxiter;} // for debugging
+
+    void SetDebug(Int_t n)     { fDebug = n; }
+    void SetNumEvents(Int_t n) { fNumEvents = n; }
+
+    ClassDef(MTFitLoop, 0) // Class which can optimize a value (chi^2, significance, etc) calculated in an eventloop
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/GeomIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/GeomIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/GeomIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mgeom/GeomLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/GeomLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/GeomLinkDef.h	(revision 17960)
@@ -0,0 +1,31 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MGeom+;
+#pragma link C++ class MGeomPix+;
+#pragma link C++ class MGeomRectangle+;
+#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 MGeomCamDwarf+;
+#pragma link C++ class MGeomCamFact+;
+#pragma link C++ class MGeomCamFACT+;
+#pragma link C++ class MGeomCamMagic+;
+#pragma link C++ class MGeomCamMagicII+;
+#pragma link C++ class MGeomCamSquare+;
+//#pragma link C++ class MGeomCamMagicHG+;
+//#pragma link C++ class MGeomCamMagic919+;
+//#pragma link C++ class MGeomCamMagic1183+;
+
+//#pragma link C++ class MGeomCamECO1000+;
+//#pragma link C++ class MGeomCamECO1000HG+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/MGeom.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeom.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeom.cc	(revision 17960)
@@ -0,0 +1,213 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MGeom
+//
+// This container stores the geometry (position) information of
+// a single pixel together with the information about next neighbors.
+//
+//
+// Version 1:
+// ----------
+//  - first implementation (previously part of MGeomPix)
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeom.h"
+
+#include <TMath.h>
+#include <TVector2.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes one pixel
+//
+MGeom::MGeom(Float_t x, Float_t y, UInt_t s, UInt_t a)
+    : fX(x), fY(y), fA(0), fSector(s), fAidx(a), fUserBits(0)
+{
+    //  default constructor
+    SetNeighbors();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return position as TVector2(fX, fY)
+//
+TVector2 MGeom::GetP() const
+{
+    return TVector2(fX, fY);
+}
+
+void MGeom::SetP(const TVector2 &v)
+{
+    fX = v.X();
+    fY = v.Y();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MGeom::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;
+
+    // FIXME
+    fNumNeighbors<5 ? SETBIT(fUserBits, kIsInOutermostRing) : CLRBIT(fUserBits, kIsInOutermostRing);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the kIsOuterRing flag if this pixel has a outermost pixel
+//  as Next Neighbor and don't have the kIsOutermostRing flag itself.
+//
+void MGeom::CheckOuterRing(const MGeomCam &cam)
+{
+    if (IsInOutermostRing())
+        return;
+
+    CLRBIT(fUserBits, kIsInOuterRing);
+
+    for (int i=0; i<fNumNeighbors; i++)
+        if (cam[fNeighbors[i]].IsInOutermostRing())
+        {
+            SETBIT(fUserBits, kIsInOuterRing);
+            return;
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the geometry information of one pixel.
+//
+void MGeom::Print(Option_t *opt) const
+{
+    //   information about a pixel
+    gLog << all << MParContainer::GetDescriptor(*this) << ":  x/y=" << fX << "/" << fY << "mm ";
+    gLog << "A= " << fA << "mm" << UTF8::kSquare << " (";
+    for (int i=0; i<fNumNeighbors; i++)
+        gLog << fNeighbors[i] << (i<fNumNeighbors-1?",":"");
+    gLog << ")";
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Return distance of center to coordinate origin: hypot(fX,fY)
+//
+Float_t MGeom::GetDist() const
+{
+    return TMath::Hypot(fX, fY);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return distance of center to center of pix: hypot(fX-pix.fX,fY-pix.fY)
+//
+Float_t MGeom::GetDist(const MGeom &pix) const
+{
+    return TMath::Hypot(fX-pix.fX, fY-pix.fY);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return distance squared of center to center of pix:
+//  (fX-pix.fX)^2+(fY-pix.fY)^2
+//
+Float_t MGeom::GetDist2(const MGeom &pix) const
+{
+    const Double_t dx = fX-pix.fX;
+    const Double_t dy = fY-pix.fY;
+    return dx*dx + dy*dy;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return angle defined by the center and the center of pix:
+//  atan2(fX-pix.fX,fY-pix.fY)
+//
+Float_t MGeom::GetAngle(const MGeom &pix) const
+{
+    return TMath::ATan2(fX - pix.GetX(), fY - pix.GetY());
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the direction of the pixel pix w.r.t. this pixel.
+// Remark: This function assumes a simple geometry.
+//
+Int_t MGeom::GetDirection(const MGeom &pix) const
+{
+    const Double_t phi = GetAngle(pix)*TMath::RadToDeg();
+
+    if (phi<-165) return kTop;
+    if (phi<-105) return kRightTop;
+    if (phi< -75) return kRight;
+    if (phi< -15) return kRightBottom;
+    if (phi<  15) return kBottom;
+    if (phi<  75) return kLeftBottom;
+    if (phi< 105) return kLeft;
+    if (phi< 165) return kLeftTop;
+
+    return kTop;
+}
+
+// ------------------------------------------------------------------------
+//
+// This implementation is based on the use of DistanceToPrimitive
+// (capital T) which should be implemented in user coordinates.
+//
+Int_t MGeom::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    const Double_t x = gPad->AbsPixeltoX(px);
+    const Double_t y = gPad->AbsPixeltoY(py);
+
+    return IsInside(x, y) ? -1 : 999999;
+}
+
Index: branches/Mars_McMismatchStudy/mgeom/MGeom.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeom.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeom.h	(revision 17960)
@@ -0,0 +1,112 @@
+#ifndef MARS_MGeom
+#define MARS_MGeom
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+
+class MGeomCam;
+
+class TAttLine;
+class TAttFill;
+class TVector2;
+
+class MGeom : public TObject
+{
+public:
+    enum {
+        kRightTop,
+        kRight,
+        kRightBottom,
+        kLeftBottom,
+        kLeft,
+        kLeftTop,
+        kTop,
+        kBottom
+    };
+
+private:
+    enum {
+        kIsInOutermostRing = 0,
+        kIsInOuterRing     = 1,
+    };
+
+protected:
+    Float_t fX;            // [mm]   the x coordinate of the center
+    Float_t fY;            // [mm]   the y coordinate of the center
+    Float_t fA;            // [mm^2] Area of the pixel
+
+    UInt_t fSector;        // Number of sector the pixels corresponds to
+    UInt_t fAidx;          // Area index of the pixel
+
+protected:
+    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)
+
+    Byte_t fUserBits;
+
+public:
+    MGeom(Float_t x=0, Float_t y=0, UInt_t s=0, UInt_t aidx=0);
+
+    void Copy(TObject &obj) const
+    {
+        MGeom &pix = (MGeom&)obj;
+        pix.fX = fX;
+        pix.fY = fY;
+        pix.fA = fA;
+        pix.fNumNeighbors = fNumNeighbors;
+        pix.fSector = fSector;
+        pix.fAidx = fAidx;
+        pix.fUserBits = fUserBits;
+        for (int i=0; i<6; i++)
+            pix.fNeighbors[i] = fNeighbors[i];
+
+        TObject::Copy(obj);
+    }
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Set(Float_t x, Float_t y, UInt_t s=0, UInt_t aidx=0) { fX=x; fY=y; fSector=s; fAidx=aidx; }
+    void SetP(Float_t x, Float_t y) { fX=x; fY=y; }
+    void SetP(const TVector2 &v);
+
+    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; }
+
+    virtual Float_t GetL() const = 0;    // Length of a side to a neighbor
+    virtual Float_t GetT() const = 0;    // Maximum elongation
+
+    UInt_t  GetSector() const { return fSector; }
+
+    TVector2 GetP() const;
+
+    Float_t GetDist() const;
+    Float_t GetDist(const MGeom &pix) const;
+    Float_t GetDist2(const MGeom &pix) const;
+    Float_t GetAngle(const MGeom &pix) const;
+
+    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(fUserBits, kIsInOutermostRing); }
+    Bool_t IsInOuterRing() const     { return TESTBIT(fUserBits, kIsInOuterRing); }
+
+    virtual Bool_t IsInside(Float_t px, Float_t py) const = 0;
+    Int_t  GetDirection(const MGeom &pix) const;
+
+    Int_t DistancetoPrimitive(Int_t px, Int_t py);
+
+    virtual void PaintPrimitive(const TAttLine &line, const TAttFill &fill, Double_t scalexy=1, Double_t scaled=1) const = 0;
+
+    ClassDef(MGeom, 1) // Geometry class describing the basics of a pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCam.cc	(revision 17960)
@@ -0,0 +1,714 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 01/2001
+!   Author(s): Markus Gaug      03/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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
+//  - added fNumSectors
+//
+// Version 4:
+// ----------
+//  - added fMaxRadius
+//  - added fMinRadius
+//
+// Version 5:
+// ----------
+//  - added fNumPixInSector
+//  - added fNumPixWithAidx
+//  - removed fNumSectors
+//  - removed fNumAreas
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MGeomCam.h"
+
+#include <TMath.h>      // TMath
+#include <TClass.h>     // IsA()->New()
+#include <TArrayI.h>    // TArrayI
+#include <TVector2.h>   // TVector2
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeom.h"
+
+ClassImp(MGeomCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 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();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// To make sure that everything is correctly initialized when
+// cloned we call InitGeometry after cloning. This repairs
+// a few I/O problems mainly with files written with older
+// MARS versions (see also StreamerWorkaround)
+//
+TObject *MGeomCam::Clone(const char *newname) const
+{
+    MGeomCam *clone = (MGeomCam*)MParContainer::Clone(newname);
+    clone->InitGeometry();
+    return clone;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy function. It does intentionally (see workaround in Streamer)
+// not copy name and title.
+//
+void MGeomCam::Copy(TObject &o) const
+{
+    MGeomCam &c = (MGeomCam&)o;
+
+    c.fNumPixels      = fNumPixels;
+    c.fCamDist        = fCamDist;
+    c.fConvMm2Deg     = fConvMm2Deg;
+
+    c.fMaxRadius      = fMaxRadius;
+    c.fMinRadius      = fMinRadius;
+    c.fPixRatio       = fPixRatio;
+    c.fPixRatioSqrt   = fPixRatioSqrt;
+
+    c.fNumPixInSector = fNumPixInSector;
+    c.fNumPixWithAidx = fNumPixWithAidx;
+
+    Int_t n = fPixels.GetEntriesFast();
+    Int_t m = c.fPixels.GetEntriesFast();
+
+    c.fPixels.Delete();
+    c.fPixels.Expand(n);
+
+    for (int i=m; i<n; i++)
+        c.fPixels.AddAt(fPixels[i]->Clone(), 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!
+//
+MGeom &MGeomCam::operator[](Int_t i)
+{
+    return *static_cast<MGeom*>(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!
+//
+MGeom &MGeomCam::operator[](Int_t i) const
+{
+    return *static_cast<MGeom*>(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.R__FOR_EACH(MGeom, CheckOuterRing)(*this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the highest sector index+1 of all pixels, please make sure
+// the the sector numbers are continous.
+//
+void MGeomCam::CalcNumSectors()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const Int_t s = (*this)[i].GetSector();
+
+        if (s>=fNumPixInSector.GetSize())
+            fNumPixInSector.Set(s+1);
+
+        fNumPixInSector[s]++;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the highest area index+1 of all pixels, please make sure
+// the the area indices are continous.
+//
+void MGeomCam::CalcNumAreas()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const Int_t s = (*this)[i].GetAidx();
+
+        if (s>=fNumPixWithAidx.GetSize())
+            fNumPixWithAidx.Set(s+1);
+
+        fNumPixWithAidx[s]++;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the maximum radius of the camera. This is ment for GUI layout.
+//
+void MGeomCam::CalcMaxRadius()
+{
+    fMaxRadius.Set(GetNumAreas()+1);
+    fMinRadius.Set(GetNumAreas()+1);
+
+    for (UInt_t i=0; i<GetNumAreas()+1; i++)
+    {
+        fMaxRadius[i] = 0.;
+        fMinRadius[i] = FLT_MAX;
+    }
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*this)[i];
+
+        const UInt_t  s = pix.GetAidx();
+
+        const Float_t d = pix.GetT();
+        const Float_t r = pix.GetDist();
+
+        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;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// sort neighbours from angle of -180 degree to -180 degree
+//
+// where right side of main pixel contains negative degrees
+// and left side positive degrees
+//
+// angle measured from top (0 degree) to bottom (180 degree)
+//             ^  -     |     +         //
+//             |      _ | _             //
+//             |     / \|/ \            //
+//  30 degree -+-   |   |   |           //
+//             |   / \ / \ / \          //
+//  90 degree -+- |   | X |   |         //
+//             |   \ / \ / \ /          //
+// 150 degree -+-   |   |   |           //
+//             |     \_/|\_/            //
+//             |        |               //
+//             |  -     |     +         //
+//             ------------------>      //
+//                                      //
+void MGeomCam::SortNeighbors()
+{
+    for (unsigned int i=0; i<fNumPixels; i++)
+    {
+        MGeom &gpix = (*this)[i];
+
+        Double_t phi[6];
+        Int_t    idx[7] = { 0, 0, 0, 0, 0, 0, -1 };
+
+        const Int_t n2 = gpix.GetNumNeighbors();
+        for (int j=0; j<n2; j++)
+        {
+            idx[j] = gpix.GetNeighbor(j);
+            phi[j] = (*this)[idx[j]].GetAngle(gpix);
+        }
+
+        Int_t sort[6] = { 6, 6, 6, 6, 6, 6 };
+
+        TMath::Sort(n2, phi, sort, kFALSE);
+
+        gpix.SetNeighbors(idx[sort[0]], idx[sort[1]], idx[sort[2]],
+                          idx[sort[3]], idx[sort[4]], idx[sort[5]]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the total area of the camera
+//
+Float_t MGeomCam::GetA() const
+{
+    Double_t A = 0;
+    for (unsigned int i=0; i<fNumPixels; i++)
+        A += (*this)[i].GetA();
+
+    return A;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the distance between the pixels i and j. -1 if an index
+// doesn't exist. The default for j is 0. Assuming that 0 is the index
+// for a central pixel you can get the distance to the camera center.
+//
+Float_t MGeomCam::GetDist(UShort_t i, UShort_t j) const
+{
+    if (i>=fNumPixels || j>=fNumPixels)
+        return -1;
+
+    return (*this)[i].GetDist((*this)[j]);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the angle between of pixels i wrt pixel j (default=0). The angle
+// is returned in the range between -pi and pi (atan2) and 2*pi if i or j
+// is out of range.
+//
+Float_t MGeomCam::GetAngle(UShort_t i, UShort_t j) const
+{
+    if (i>=fNumPixels || j>=fNumPixels)
+        return TMath::TwoPi();
+
+    return (*this)[i].GetAngle((*this)[j]);
+}
+
+// --------------------------------------------------------------------------
+//
+// The maximum possible distance from the origin.
+//
+Float_t MGeomCam::GetMaxRadius() const
+{
+    return fMaxRadius[0];
+}
+
+// --------------------------------------------------------------------------
+//
+// The minimum possible distance from the origin.
+//
+Float_t MGeomCam::GetMinRadius() const
+{
+    return fMinRadius[0];
+}
+
+// --------------------------------------------------------------------------
+//
+// Have to call the radii of the subcameras starting to count from 1
+//
+Float_t MGeomCam::GetMaxRadius(const Int_t i) const
+{
+    return i<0 || i>=(Int_t)GetNumAreas() ? -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<0 || i>=(Int_t)GetNumAreas() ? -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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the photon which is flying along the trajectory u has passed
+// (or will pass) the frame of the camera (and consequently get
+// absorbed). The position p and direction u must be in the
+// telescope coordinate frame, which is z parallel to the focal plane,
+// x to the right and y upwards, looking from the mirror towards the camera.
+//
+// The units are cm.
+//
+Bool_t MGeomCam::HitFrame(MQuaternion p, const MQuaternion &u, Double_t margin) const
+{
+    if (margin<0)
+        return HitFrame(p, u);
+
+    // z is defined from the mirror (0) to the camera (z>0).
+    // Thus we just propagate to the focal plane (z=fDist)
+    p.PropagateZ(u, GetCameraDist()*100); // m->cm
+    return p.R()<margin;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the position given in the focal plane (so z can be ignored)
+// is a position which might hit the detector. It is meant to be a rough
+// and fast estimate not a precise calculation. All positions dicarded
+// must not hit the detector. All positions accepted might still miss
+// the detector.
+//
+Bool_t MGeomCam::HitDetector(const MQuaternion &v, Double_t offset) const
+{
+    const Double_t max = fMaxRadius[0]/10+offset; // cm --> mm
+    return v.R2()<max*max;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints the Geometry information of all pixels in the camera.
+//  With the option "simple" you can suppress the output of the contents
+//  of the individual pixels.
+//
+void MGeomCam::Print(Option_t *o) const
+{
+    //
+    //   Print Information about the Geometry of the camera
+    //
+    *fLog << all << " Number of Pixels (" << GetTitle() << "): " << fNumPixels << endl;
+    *fLog << " Number of Sectors: " << GetNumSectors() << "  Area-Indices: " << GetNumAreas() << endl;
+    *fLog << " Min.Radius: " << GetMinRadius() << "  Max.Radius: " << GetMaxRadius() << endl;
+
+    if (!TString(o).Contains("simple", TString::kIgnoreCase))
+        fPixels.Print();
+} 
+
+// --------------------------------------------------------------------------
+//
+//  Return the pixel index corresponding to the coordinates given in x, y.
+//  The coordinates are given in pixel units (millimeters)
+//  If no pixel exists return -1;
+//
+Int_t MGeomCam::GetPixelIdxXY(Float_t x, Float_t y) const
+{
+    for (unsigned int i=0; i<fNumPixels; i++)
+        if ((*this)[i].IsInside(x, y))
+            return i;
+
+    return -1;
+}
+
+Int_t MGeomCam::GetPixelIdx(const TVector2 &v) const
+{
+    return GetPixelIdxXY(v.X(), v.Y());
+}
+
+Int_t MGeomCam::GetPixelIdxDeg(const TVector2 &v) const
+{
+    return GetPixelIdxXYdeg(v.X(), v.Y());
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all indices to arr of all neighbors around pix in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TArrayI &arr, const MGeom &pix, Float_t r) const
+{
+    arr.Set(GetNumPixels());
+
+    Int_t n = 0;
+
+    for (unsigned int i=0; i<GetNumPixels(); i++)
+    {
+        if (r>TMath::Hypot(pix.GetX()-(*this)[i].GetX(), pix.GetY()-(*this)[i].GetY()))
+            arr[n++] = i;
+    }
+
+    arr.Set(n);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all indices to arr of all neighbors around idx in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TArrayI &arr, UInt_t idx, Float_t r) const
+{
+    if (idx>=GetNumPixels())
+    {
+        arr.Set(0);
+        return;
+    }
+
+    const MGeom &pix = (*this)[idx];
+    GetNeighbors(arr, pix, r);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all pixels to list of all neighbors around pix in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TList &arr, const MGeom &pix, Float_t r) const
+{
+    for (unsigned int i=0; i<GetNumPixels(); i++)
+    {
+        if (r>TMath::Hypot(pix.GetX()-(*this)[i].GetX(), pix.GetY()-(*this)[i].GetY()))
+            arr.Add(fPixels.UncheckedAt(i));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all pixels to list of all neighbors around idx in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TList &arr, UInt_t idx, Float_t r) const
+{
+    if (idx>=GetNumPixels())
+        return;
+
+    const MGeom &pix = (*this)[idx];
+    GetNeighbors(arr, pix, r);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return direction of p2 w.r.t. p1. For more details
+// see MGeom::GetDirection
+//
+Int_t MGeomCam::GetDirection(UInt_t p1, UInt_t p2) const
+{
+    if (p1>fNumPixels || p2>fNumPixels)
+        return -1;
+
+    return operator[](p1).GetDirection(operator[](p2));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get index of neighbor of pixel idx in direction dir, if existing.
+//
+Int_t MGeomCam::GetNeighbor(UInt_t idx, Int_t dir) const
+{
+    if (idx>fNumPixels)
+        return -1;
+
+    const MGeom &pix=operator[](idx);
+
+    //
+    // search for the neighbor in the given direction
+    //
+    for (int i=0; i<pix.GetNumNeighbors(); i++)
+        if (GetDirection(idx, pix.GetNeighbor(i))==dir)
+            return pix.GetNeighbor(i);
+
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the next neighbor information from a table into the pixel
+//  objects. An overloaded function must call SortNeighbors()
+//  at the end.
+//
+// All pixels with a center withing 1.75*GetT() are considered neighbors,
+// Only six neighbors are allowed.
+//
+void MGeomCam::CreateNN()
+{
+    TArrayI nn(6);
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        MGeom &pix = (*this)[i];
+
+        Int_t k = 0;
+        nn.Reset(-1);
+
+        for (UInt_t j=0; j<GetNumPixels(); j++)
+        {
+            if (i==j)
+                continue;
+
+            if (pix.GetDist((*this)[j])>pix.GetT()*1.75)
+                continue;
+
+            if (k==6)
+            {
+                *fLog << err << "ERROR - MGeomCam::CreateNN: Pixel " << j << " has too many neighbors." << endl;
+                break;
+            }
+
+            nn[k++] = j;
+        }
+
+        pix.SetNeighbors(nn[0], nn[1], nn[2], nn[3], nn[4], nn[5]);
+    }
+
+    SortNeighbors();
+}
+
+// --------------------------------------------------------------------------
+//
+// This workaround reproduces (as much as possible) the contents
+// of fPixels which got lost writing MGeomCam in which the
+// fPixels were filles with the []-operator instead of AddAt
+// and a root version previous to 5.18.
+// You try to read broken contents from file if fNumPixels is empty
+// but fNumPixels>0.
+// If you ever read broken contents from a split branch you
+// MUST call this function after reading.
+//
+// Furthermore since we moved all contents of MGeomPix to its
+// new base class the contents of fNeighbors is not read anymore
+// although all other contents is read correctly. Therefore we have
+// top recreate the neighbor table.
+//
+void MGeomCam::StreamerWorkaround()
+{
+    if (fNumPixels==0)
+        return;
+
+
+    if (!fPixels.IsEmpty())
+    {
+        CreateNN();
+        return;
+    }
+
+    const TObject *cam = (TObject*)IsA()->New();
+    cam->Copy(*this);
+    delete cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a custom made streamer. Due to a bug in TObjArray::operator[]
+// old root-versions didn't correctly store the contents of the TObjArray.
+// If such a file is detected (TObjArray empty) a new MGeomCam is created
+// with IsA()->New() and its contents is copied to this. Unfortunately
+// this won't work for all MGeomCam derivatives which need arguments
+// in the constructor and MGeomCam itself (no derivative). Fortunately
+// in prodoction we have never stored anything else than MGeomCamMagic yet.
+// The bug in root can be worked around using AddAt instead of operator[].
+//
+void MGeomCam::Streamer(TBuffer &b)
+{
+    if (b.IsReading())
+    {
+        MGeomCam::Class()->ReadBuffer(b, this);
+        StreamerWorkaround();
+    }
+    else
+        MGeomCam::Class()->WriteBuffer(b, this);
+}
+
+// --------------------------------------------------------------------------
+//
+// This deletes the pixel i and sets it to a clone of pix.
+// If i>=fNumPixels it is just ignored.
+//
+void MGeomCam::SetAt(UInt_t i, const MGeom &pix)
+{
+    if (i>=fNumPixels)
+        return;
+
+    if (fPixels[i])
+        delete fPixels.RemoveAt(i);
+
+    // For root versions <5.18 AddAt is mandatory, for newer
+    // root-version the []-operator can be used safely
+    fPixels.AddAt(pix.Clone(), i);
+}
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCam.h	(revision 17960)
@@ -0,0 +1,134 @@
+#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
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+#ifndef MARS_MQuaternion
+#include "MQuaternion.h"
+#endif
+
+class TVector2;
+class TArrayI;
+class MGeom;
+
+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)
+
+    TArrayS   fNumPixInSector;  // Number of pixels in sector
+    TArrayS   fNumPixWithAidx;  // Number of pixels with one pixel sizes
+
+//    Int_t     fNumSectors;      // Number of sectors
+//    Int_t     fNumAreas;        // Number of different pixel sizes
+
+    void CalcMaxRadius();
+    void CalcNumSectors();
+    void CalcNumAreas();
+    void InitOuterRing();
+
+    virtual void CreateNN();
+
+protected:
+    void SortNeighbors();
+
+public:
+    MGeomCam(UInt_t npix=0, Float_t dist=1, const char *name=NULL, const char *title=NULL);
+    MGeomCam(const MGeomCam &cam) : MParContainer(cam) { cam.Copy(*this); }
+
+    TObject *Clone(const char *name="") const;
+    void Copy(TObject &o) const;
+
+    // FIXME, workaround: this function is made public just to allow
+    // the use of some camera files from the 0.7 beta version in which the 
+    // array containing pixel ratios is not initialized.
+    void CalcPixRatio();
+
+    // FIXME, workaround broken streaming
+    void StreamerWorkaround();
+
+    void InitGeometry()
+    {
+        CreateNN();
+        CalcNumSectors();
+        CalcNumAreas();
+        CalcMaxRadius();
+        CalcPixRatio();
+        InitOuterRing();
+    }
+
+    Float_t GetCameraDist() const { return fCamDist; }
+    Float_t GetConvMm2Deg() const { return fConvMm2Deg; }
+
+    UInt_t  GetNumPixels()  const { return fNumPixels; }
+
+    Float_t GetMaxRadius() const;
+    Float_t GetMinRadius() const;
+    Float_t GetMaxRadius(const Int_t i) const;
+    Float_t GetMinRadius(const Int_t i) const;
+
+    Float_t GetDist(UShort_t i, UShort_t j=0) const;
+    Float_t GetAngle(UShort_t i, UShort_t j=0) const;
+
+    Float_t GetA() const;
+
+    Float_t GetPixRatio(UInt_t i) const;
+    Float_t GetPixRatioSqrt(UInt_t i) const;
+
+    UInt_t  GetNumSectors() const { return fNumPixInSector.GetSize(); }
+    UInt_t  GetNumAreas() const { return fNumPixWithAidx.GetSize(); }
+
+    UShort_t GetNumPixInSector(UInt_t i) const { return (UShort_t)fNumPixInSector[i]; }
+    UShort_t GetNumPixWithAidx(UInt_t i) const { return (UShort_t)fNumPixWithAidx[i]; }
+
+    MGeom &operator[](Int_t i);
+    MGeom &operator[](Int_t i) const;
+
+    Int_t GetPixelIdx(const TVector2 &v) const;
+    Int_t GetPixelIdxDeg(const TVector2 &v) const;
+    Int_t GetPixelIdxXY(Float_t x, Float_t y) const;
+    Int_t GetPixelIdxXYdeg(Float_t x, Float_t y) const
+    {
+        return GetPixelIdxXY(x/fConvMm2Deg, y/fConvMm2Deg);
+    }
+
+    void GetNeighbors(TArrayI &arr, UInt_t idx,          Float_t r) const;
+    void GetNeighbors(TList &arr,   UInt_t idx,          Float_t r) const;
+    void GetNeighbors(TArrayI &arr, const MGeom &pix, Float_t r) const;
+    void GetNeighbors(TList &arr,   const MGeom &pix, Float_t r) const;
+
+    Int_t GetDirection(UInt_t p1, UInt_t p2) const;
+    Int_t GetNeighbor(UInt_t idx, Int_t dir) const;
+
+    virtual Bool_t HitFrame(MQuaternion, const MQuaternion &) const { return kFALSE; }
+            Bool_t HitFrame(MQuaternion p, const MQuaternion &u, Double_t margin) const;
+    virtual Bool_t HitDetector(const MQuaternion &p, Double_t offset=0) const;
+
+    void Print(Option_t *opt=NULL) const;
+
+    void SetAt(UInt_t i, const MGeom &pix);
+
+    ClassDef(MGeomCam, 5)  // Geometry base class for the camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1.cc	(revision 17960)
@@ -0,0 +1,39 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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
+//
+// Class Version 2:
+// ----------------
+//  - derived from MGeoMCamDwarf
+//
+////////////////////////////////////////////////////////////////////////////
+
+#include "MGeomCamCT1.h"
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1.h	(revision 17960)
@@ -0,0 +1,20 @@
+#ifndef MARS_MGeomCamCT1
+#define MARS_MGeomCamCT1
+
+#ifndef MARS_MGeomCamDwarf
+#include "MGeomCamDwarf.h"
+#endif
+
+class MGeomCamCT1 : public MGeomCamDwarf
+{
+public:
+    MGeomCamCT1(const char *name=NULL) : MGeomCamDwarf(6, 21, 4.88, name)
+    {
+        SetTitle("Geometry information of HEGRA CT1 Camera");
+    }
+
+    ClassDef(MGeomCamCT1, 2) // Geometry class for the CT1 camera
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1Daniel.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1Daniel.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1Daniel.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1Daniel.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1Daniel.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamCT1Daniel.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamDwarf.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamDwarf.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamDwarf.cc	(revision 17960)
@@ -0,0 +1,241 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Michael Backes 03/2007 <mailto:michael.backes@udo.edu>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamDwarf
+//
+// This class stores the geometry information of the Dwarf camera.
+//    MGeomCamDwarf cam;        // Creates the 313 pixel dwarf camera
+//
+// It can also be used to create a hexagonal camera with identical sized
+// pixels and n rings (while the central pixel is counted as ring 0).
+//    MGeomCamDwarf cam(9, 21); // Creates the CT3 camera
+//
+// Or it can be used to create a roundish camera, similar to a
+// hexagonal camera, but the edges filled with additional pixels
+// inside a circle.
+//    MGeomCamDwarf cam(209.5, 13.2);
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamDwarf.h"
+
+#include <TMath.h>
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamDwarf);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Dwarf camera has 313 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamDwarf::MGeomCamDwarf(const char *name)
+    : MGeomCam(CalcNumPix(9.5), 4.57, name, "Geometry information of Dwarf Camera")
+{
+    CreateCam(21, 9.5);
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this to create a camera with a roundish shape and a radius rad in
+// millimeter containing the pixel centers. The pixel will have a diameter
+// diameter in millimeters, and a distance dist in meters.
+//
+MGeomCamDwarf::MGeomCamDwarf(Double_t rad, Double_t diameter, Double_t dist, const char *name)
+    : MGeomCam(CalcNumPix(diameter<=0 ? rad : rad/diameter), dist, name, "Geometry information for a roundish camera")
+{
+    CreateCam(diameter, diameter<=0 ? rad : rad/diameter);
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this to create a camera with a hexagonal shape and rings rings.
+// The first ring around the central pixel is 1. The pixel will have a
+// diameter diameter in millimeters, and a distance dist in meters.
+//
+MGeomCamDwarf::MGeomCamDwarf(Int_t rings, Double_t diameter, Double_t dist, const char *name)
+    : MGeomCam(CalcNumPix(rings), dist, name, "Geometry information for a hexagonal camera")
+{
+    CreateCam(diameter, rings);
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the photon which is flying along the trajectory u has passed
+// (or will pass) the frame of the camera (and consequently get
+// absorbed). The position p and direction u must be in the
+// telescope coordinate frame, which is z parallel to the focal plane,
+// x to the right and y upwards, looking from the mirror towards the camera.
+//
+// The units are cm.
+//
+Bool_t MGeomCamDwarf::HitFrame(MQuaternion p, const MQuaternion &u) const
+{
+    // Add 10% to the max radius and convert from mm to cm
+    // FIXME: Why does the compiler complain without this cast?
+    return static_cast<const MGeomCam*>(this)->HitFrame(p, u, GetMaxRadius()*0.11);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate in the direction 0-5 (kind of sector) in the ring-th ring
+// the x and y coordinate of the i-th pixel. The units are unity,
+// distance to (0,0) is retruned.
+//
+Int_t MGeomCamDwarf::CalcNumPix(Int_t rings)
+{
+    //
+    //  add the first pixel to the list
+    //
+    Int_t cnt = 1;
+
+    for (Int_t ring=0; ring<rings; ring++)
+        cnt += 6*(ring+1);
+
+    return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate in the direction 0-5 (kind of sector) in the ring-th ring
+// the x and y coordinate of the i-th pixel. The unitx are unity,
+// distance to (0,0) is retruned.
+//
+// Due to possible rounding errors we need to use exactly the same
+// algorithm as for creating the pixels!
+//
+Int_t MGeomCamDwarf::CalcNumPix(Double_t rad)
+{
+    const Double_t r2 = rad*rad;
+
+    //
+    //  add the first pixel to the list
+    //
+    Int_t cnt  = 1;
+    Int_t ring = 1;
+    while (1)
+    {
+        Int_t n = 0;
+
+        //
+        // calc. coords for this ring counting from the
+        // starting number to the ending number
+        //
+        for (Int_t dir=MGeomPix::kDirNE; dir<=MGeomPix::kDirSE; dir++)
+        {
+            for (int i=0; i<ring; i++)
+            {
+                Double_t x, y;
+                if (MGeomPix::CalcXY(dir, ring, i, x, y)<r2)
+                    n++;
+            }
+        }
+
+        if (n==0)
+            return cnt;
+
+        ring++;
+        cnt += n;
+    }
+
+    return cnt;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information for a hexagonal camera
+//
+void MGeomCamDwarf::CreateCam(Double_t diameter, Int_t rings)
+{
+    //    units for diameter are mm
+
+    //
+    //  add the first pixel to the list
+    //
+    SetAt(0, MGeomPix(0, 0, diameter));
+
+    Int_t cnt  = 1;
+
+    for (int ring=1; ring<=rings; ring++)
+    {
+        for (Int_t dir=MGeomPix::kDirNE; dir<=MGeomPix::kDirSE; dir++)
+        {
+            for (int i=0; i<ring; i++)
+            {
+                Double_t x, y;
+                MGeomPix::CalcXY(dir, ring, i, x, y);
+                SetAt(cnt++, MGeomPix(x*diameter, y*diameter, diameter));
+            }
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information for a roundish camera
+//
+void MGeomCamDwarf::CreateCam(Double_t diameter, Double_t rad)
+{
+    //    units for diameter are mm
+
+    const Double_t r2 = rad*rad;
+
+    //
+    //  add the first pixel to the list
+    //
+    SetAt(0, MGeomPix(0, 0, diameter));
+
+    Int_t cnt  = 1;
+    Int_t ring = 1;
+
+    while (1)
+    {
+        Int_t n = 0;
+
+        for (Int_t dir=MGeomPix::kDirNE; dir<=MGeomPix::kDirSE; dir++)
+        {
+            for (int i=0; i<ring; i++)
+            {
+                Double_t x, y;
+                if (MGeomPix::CalcXY(dir, ring, i, x, y)<r2)
+                    SetAt(cnt+n++, MGeomPix(x*diameter, y*diameter, diameter));
+            }
+        }
+
+        if (n==0)
+            return;
+
+        ring++;
+        cnt += n;
+    }
+}
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamDwarf.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamDwarf.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamDwarf.h	(revision 17960)
@@ -0,0 +1,28 @@
+#ifndef MARS_MGeomCamDwarf
+#define MARS_MGeomCamDwarf
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamDwarf : public MGeomCam
+{
+private:
+    static Int_t CalcNumPix(Double_t rad);
+    static Int_t CalcNumPix(Int_t rings);
+
+    void CreateCam(Double_t diameter, Double_t rad);
+    void CreateCam(Double_t diameter, Int_t rings);
+
+public:
+    // 223
+    MGeomCamDwarf(Double_t rad, Double_t diameter=16, Double_t dist=4.92, const char *name=NULL);
+    MGeomCamDwarf(Int_t  rings, Double_t diameter=16, Double_t dist=4.92, const char *name=NULL);
+    MGeomCamDwarf(const char *name=NULL);
+
+    Bool_t HitFrame(MQuaternion p, const MQuaternion &u) const;
+
+    ClassDef(MGeomCamDwarf, 1) // Geometry class for the Dwarf camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000HG.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000HG.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000HG.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000HG.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000HG.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamECO1000HG.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamFACT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamFACT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamFACT.cc	(revision 17960)
@@ -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 08/2010 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamFACT
+//
+// This class stores the geometry information of the final FACT camera.
+//    MGeomCamFACT cam;        // Creates the final FACT camera
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamFACT.h"
+
+#include <TMath.h>
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamFACT);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MGeomCamFACT::MGeomCamFACT(const char *name)
+    : MGeomCam(1440, 4.90, name, "Geometry information of the final FACT Camera")
+{
+    CreateCam();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+MGeomCamFACT::MGeomCamFACT(Double_t dist, const char *name)
+    : MGeomCam(1440, dist, name, "Geometry information of the final FACT Camera")
+{
+    CreateCam();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the photon which is flying along the trajectory u has passed
+// (or will pass) the frame of the camera (and consequently get
+// absorbed). The position p and direction u must be in the
+// telescope coordinate frame, which is z parallel to the focal plane,
+// x to the right and y upwards, looking from the mirror towards the camera.
+//
+// The units are cm.
+//
+Bool_t MGeomCamFACT::HitFrame(MQuaternion p, const MQuaternion &u) const
+{
+    // z is defined from the mirror (0) to the camera (z>0).
+    // Thus we just propagate to the focal plane (z=fDist)
+    //p -= 1700./u.Z()*u;
+    p.PropagateZ(u, GetCameraDist()*100); // m->cm
+
+    // Add 10% to the max radius and convert from mm to cm
+    return p.R()<GetMaxRadius()*0.11;//TMath::Abs(p.X())<65 && TMath::Abs(p.Y())<65;
+}
+
+// --------------------------------------------------------------------------
+//
+void MGeomCamFACT::CreateCam()
+{
+    const static Int_t dir[6] =
+    {
+        MGeomPix::kDirSE,
+        MGeomPix::kDirNE,
+        MGeomPix::kDirN,
+        MGeomPix::kDirNW,
+        MGeomPix::kDirSW,
+        MGeomPix::kDirS
+    };
+
+    const Int_t    rings    = 23;
+    const Double_t diameter = 9.5;
+
+    //
+    //  add the first pixel to the list
+    //
+    const MGeomPix pix0(-0.5*diameter, 0, diameter);
+    SetAt(0, pix0);
+
+    Int_t cnt  = 1;
+    for (int ring=1; ring<=rings; ring++)
+    {
+        for (Int_t s=0; s<6; s++)
+        {
+            for (int i=1; i<=ring; i++)
+            {
+                Double_t x, y;
+                const Double_t d2 = MGeomPix::CalcXY(dir[s], ring, i, x, y);
+                if (d2 - x > 395.75)
+                    continue;
+
+                const MGeomPix pix((x-0.5)*diameter, -y*diameter, diameter);
+                SetAt(cnt++, pix);
+
+                if (cnt!=1416)
+                    continue;
+
+                const MGeomPix pix1(6.5*diameter, -y*diameter, diameter);
+                const MGeomPix pix2(6.5*diameter,  y*diameter, diameter);
+                SetAt(1438, pix1);
+                SetAt(1439, pix2);
+            }
+        }
+    }
+}
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamFACT.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamFACT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamFACT.h	(revision 17960)
@@ -0,0 +1,26 @@
+#ifndef MARS_MGeomCamFACT
+#define MARS_MGeomCamFACT
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamFACT : public MGeomCam
+{
+private:
+    enum { kDirCenter, kDirNE, kDirNW, kDirW, kDirSW, kDirSE, kDirE };
+
+    static Double_t CalcXY(Int_t dir, Int_t ring, Int_t i, Double_t &x, Double_t &y);
+
+    void CreateCam();
+
+public:
+    MGeomCamFACT(const char *name=NULL);
+    MGeomCamFACT(Double_t dist, const char *name=NULL);
+
+    Bool_t HitFrame(MQuaternion p, const MQuaternion &u) const;
+
+    ClassDef(MGeomCamFACT, 1) // Geometry class for the final FACT camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamFact.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamFact.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamFact.cc	(revision 17960)
@@ -0,0 +1,154 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamFact
+//
+// This class stores the geometry information of the Fact camera.
+//    MGeomCamFact cam;       
+//
+// The idea is to have always four rectangular shaped pixels in
+// a rectangle, but the rectangles orderes such that the structure
+// is a closed package (hexagonal) structure. The rectangles are
+// created in width and hight such that this hexagonal structure can be
+// maintained.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamFact.h"
+
+
+#include <TMath.h>
+
+#include "MGeomCamDwarf.h"
+#include "MGeomRectangle.h"
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamFact);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Fact camera
+//
+MGeomCamFact::MGeomCamFact(const char *name)
+    : MGeomCam(0, 4.8887, name, "Geometry information of Fact Camera")
+{
+    CreateGeometry(MGeomCamDwarf(209.5, 13.2, 4.8887));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this to create a camera with a roundish shape and a radius rad in
+// millimeter containing the four-pixel centers. The four-pixel will have
+// a diameter diameter in millimeters, and a distance dist in meters.
+//
+MGeomCamFact::MGeomCamFact(Double_t rad, Double_t diameter, Double_t dist, const char *name)
+    : MGeomCam(0, dist, name, "Geometry information for a FACT camera")
+{
+    CreateGeometry(MGeomCamDwarf(rad, diameter, dist));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this to create a camera with a hexagonal shape and rings rings.
+// The first ring around the central pixel is 1. The four-pixel will have a
+// diameter diameter in millimeters, and a distance dist in meters.
+//
+MGeomCamFact::MGeomCamFact(Int_t rings, Double_t diameter, Double_t dist, const char *name)
+    : MGeomCam(0, dist, name, "Geometry information for a FACT camera")
+{
+    CreateGeometry(MGeomCamDwarf(rings, diameter, dist));
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the photon which is flying along the trajectory u has passed
+// (or will pass) the frame of the camera (and consequently get
+// absorbed). The position p and direction u must be in the
+// telescope coordinate frame, which is z parallel to the focal plane,
+// x to the right and y upwards, looking from the mirror towards the camera.
+//
+// The units are cm.
+//
+Bool_t MGeomCamFact::HitFrame(MQuaternion p, const MQuaternion &u) const
+{
+    // z is defined from the mirror (0) to the camera (z>0).
+    // Thus we just propagate to the focal plane (z=fDist)
+    //p -= 1700./u.Z()*u;
+    p.PropagateZ(u, GetCameraDist()*100); // m->cm
+
+    // Add 10% to the max radius and convert from mm to cm
+    return p.R()<GetMaxRadius()*0.11;//TMath::Abs(p.X())<65 && TMath::Abs(p.Y())<65;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates four rectangular pixels within a pixel of a camera with
+// hexagonal pixels
+//
+void MGeomCamFact::CreateGeometry(const MGeomCam &hex)
+{
+    const Double_t dx = static_cast<MGeomPix&>(hex[0]).GetDx()/4;
+    const Double_t dy = static_cast<MGeomPix&>(hex[0]).GetDy()/4;
+
+    MGeomCam cam(hex.GetNumPixels()*4, hex.GetCameraDist());
+
+    for (UInt_t i=0; i<hex.GetNumPixels(); i++)
+    {
+        const MGeom &pix = hex[i];
+
+        for (int j=0; j<4; j++)
+        {
+            Double_t x = pix.GetX();
+            Double_t y = pix.GetY();
+
+            switch (j)
+            {
+            case 0:
+                x -= dx;
+                y -= dy;
+                break;
+            case 1:
+                x += dx;
+                y -= dy;
+                break;
+            case 2:
+                x -= dx;
+                y += dy;
+                break;
+            case 3:
+                x += dx;
+                y += dy;
+                break;
+            }
+
+            cam.SetAt(i*4+j, MGeomRectangle(x, y, dx*2, dy*2));
+        }
+    }
+
+    cam.InitGeometry();
+    cam.Copy(*this);
+}
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamFact.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamFact.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamFact.h	(revision 17960)
@@ -0,0 +1,24 @@
+#ifndef MARS_MGeomCamFact
+#define MARS_MGeomCamFact
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamFact : public MGeomCam
+{
+private:
+    void CreateGeometry(const MGeomCam &hex);
+
+public:
+    // 223
+    MGeomCamFact(Double_t rad, Double_t diameter=16, Double_t dist=4.92, const char *name=NULL);
+    MGeomCamFact(Int_t  rings, Double_t diameter=16, Double_t dist=4.92, const char *name=NULL);
+    MGeomCamFact(const char *name=NULL);
+
+    Bool_t HitFrame(MQuaternion p, const MQuaternion &u) const;
+
+    ClassDef(MGeomCamFact, 1) // Geometry class for the Fact camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic.cc	(revision 17960)
@@ -0,0 +1,944 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagic
+//
+// This class stores the geometry information of the Magic camera.
+// All information are copied from tables, see source code.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagic.h"
+
+#include <TMath.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();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Magic camera has 577 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN. You can give the distance dist from
+//  the mirror center to the focal plane.
+//
+MGeomCamMagic::MGeomCamMagic(Double_t dist, const char *name)
+    : MGeomCam(577, dist, name, "Geometry information of Magic Camera")
+{
+    CreateCam();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the photon which is flying along the trajectory u has passed
+// (or will pass) the frame of the camera (and consequently get
+// absorbed). The position p and direction u must be in the
+// telescope coordinate frame, which is z parallel to the focal plane,
+// x to the right and y upwards, looking from the mirror towards the camera.
+//
+Bool_t MGeomCamMagic::HitFrame(MQuaternion p, const MQuaternion &u) const
+{
+    // z is defined from the mirror (0) to the camera (z>0).
+    // Thus we just propagate to the focal plane (z=fDist)
+    p.PropagateZ(u, GetCameraDist()*100);
+
+    return TMath::Abs(p.X())<65 && TMath::Abs(p.Y())<65;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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 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++)
+        SetAt(i, MGeomPix(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]);
+
+    SortNeighbors();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Magic camera has 913 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamMagicII::MGeomCamMagicII(const char *name)
+    : MGeomCamDwarf(505., 30, 17, name)
+{
+    SetTitle("Geometry information of Magic II Camera");
+    Rotate();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Magic II camera has 913 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN. You can give the distance dist from
+//  the mirror center to the focal plane.
+//
+MGeomCamMagicII::MGeomCamMagicII(Double_t dist, const char *name)
+    : MGeomCamDwarf(505., 30, dist, name)
+{
+    SetTitle("Geometry information of Magic II Camera");
+    Rotate();
+}
+
+// --------------------------------------------------------------------------
+//
+// Rotate all pixels by 30deg
+//
+void MGeomCamMagicII::Rotate()
+{
+    const Double_t phi = 30*TMath::DegToRad();
+
+    const TVector2 v(TMath::Cos(phi), TMath::Sin(phi));
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        MGeomPix &pix = static_cast<MGeomPix&>(operator[](i));
+
+        pix.SetP(pix.GetP()*v, pix.GetP()^v);
+        pix.SetPhi(phi);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the photon which is flying along the trajectory u has passed
+// (or will pass) the frame of the camera (and consequently get
+// absorbed). The position p and direction u must be in the
+// telescope coordinate frame, which is z parallel to the focal plane,
+// x to the right and y upwards, looking from the mirror towards the camera.
+//
+Bool_t MGeomCamMagicII::HitFrame(MQuaternion p, const MQuaternion &u) const
+{
+    // z is defined from the mirror (0) to the camera (z>0).
+    // Thus we just propagate to the focal plane (z=fDist)
+    p.PropagateZ(u, GetCameraDist()*100);
+
+    return TMath::Abs(p.X())<65 && TMath::Abs(p.Y())<65;
+}
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic.h	(revision 17960)
@@ -0,0 +1,38 @@
+#ifndef MARS_MGeomCamMagic
+#define MARS_MGeomCamMagic
+
+#ifndef MARS_MGeomCamDwarf
+#include "MGeomCamDwarf.h"
+#endif
+
+class MGeomCamMagic : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamMagic(const char *name=NULL);
+    MGeomCamMagic(Double_t dist, const char *name=NULL);
+
+    Bool_t HitFrame(MQuaternion p, const MQuaternion &u) const;
+
+    ClassDef(MGeomCamMagic, 1)		// Geometry class for the Magic camera
+};
+
+class MGeomCamMagicII : public MGeomCamDwarf
+{
+private:
+    void Rotate();
+
+public:
+    MGeomCamMagicII(const char *name=NULL);
+    MGeomCamMagicII(Double_t dist, const char *name=NULL);
+
+    Bool_t HitFrame(MQuaternion p, const MQuaternion &u) const;
+
+    ClassDef(MGeomCamMagicII, 1)		// Geometry class for the Magic camera
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic1183.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic1183.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic1183.cc	(revision 17960)
@@ -0,0 +1,1787 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagic1183
+//
+// This class stores the geometry information of a possible Magic-2 camera,
+// which only has small pixels.
+// All information are copied from tables, see source code.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagic1183.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamMagic1183);
+
+// --------------------------------------------------------------------------
+//
+//  This Magic camera has 1183 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamMagic1183::MGeomCamMagic1183(const char *name)
+    : MGeomCam(1183, 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 MGeomCamMagic1183::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[1183] = {
+    0, 30, 15, -15, -30, -15, 15, 60, 45, 30, 
+    0, -30, -45, -60, -45, -30, 0, 30, 45, 90, 
+    75, 60, 45, 15, -15, -45, -60, -75, -90, -75, 
+    -60, -45, -15, 15, 45, 60, 75, 120, 105, 90, 
+    75, 60, 30, 0, -30, -60, -75, -90, -105, -120, 
+    -105, -90, -75, -60, -30, 0, 30, 60, 75, 90, 
+    105, 150, 135, 120, 105, 90, 75, 45, 15, -15, 
+    -45, -75, -90, -105, -120, -135, -150, -135, -120, -105, 
+    -90, -75, -45, -15, 15, 45, 75, 90, 105, 120, 
+    135, 180, 165, 150, 135, 120, 105, 90, 60, 30, 
+    0, -30, -60, -90, -105, -120, -135, -150, -165, -180, 
+    -165, -150, -135, -120, -105, -90, -60, -30, 0, 30, 
+    60, 90, 105, 120, 135, 150, 165, 210, 195, 180, 
+    165, 150, 135, 120, 105, 75, 45, 15, -15, -45, 
+    -75, -105, -120, -135, -150, -165, -180, -195, -210, -195, 
+    -180, -165, -150, -135, -120, -105, -75, -45, -15, 15, 
+    45, 75, 105, 120, 135, 150, 165, 180, 195, 240, 
+    225, 210, 195, 180, 165, 150, 135, 120, 90, 60, 
+    30, 0, -30, -60, -90, -120, -135, -150, -165, -180, 
+    -195, -210, -225, -240, -225, -210, -195, -180, -165, -150, 
+    -135, -120, -90, -60, -30, 0, 30, 60, 90, 120, 
+    135, 150, 165, 180, 195, 210, 225, 270, 255, 240, 
+    225, 210, 195, 180, 165, 150, 135, 105, 75, 45, 
+    15, -15, -45, -75, -105, -135, -150, -165, -180, -195, 
+    -210, -225, -240, -255, -270, -255, -240, -225, -210, -195, 
+    -180, -165, -150, -135, -105, -75, -45, -15, 15, 45, 
+    75, 105, 135, 150, 165, 180, 195, 210, 225, 240, 
+    255, 300, 285, 270, 255, 240, 225, 210, 195, 180, 
+    165, 150, 120, 90, 60, 30, 0, -30, -60, -90, 
+    -120, -150, -165, -180, -195, -210, -225, -240, -255, -270, 
+    -285, -300, -285, -270, -255, -240, -225, -210, -195, -180, 
+    -165, -150, -120, -90, -60, -30, 0, 30, 60, 90, 
+    120, 150, 165, 180, 195, 210, 225, 240, 255, 270, 
+    285, 330, 315, 300, 285, 270, 255, 240, 225, 210, 
+    195, 180, 165, 135, 105, 75, 45, 15, -15, -45, 
+    -75, -105, -135, -165, -180, -195, -210, -225, -240, -255, 
+    -270, -285, -300, -315, -330, -315, -300, -285, -270, -255, 
+    -240, -225, -210, -195, -180, -165, -135, -105, -75, -45, 
+    -15, 15, 45, 75, 105, 135, 165, 180, 195, 210, 
+    225, 240, 255, 270, 285, 300, 315, 360, 345, 330, 
+    315, 300, 285, 270, 255, 240, 225, 210, 195, 180, 
+    150, 120, 90, 60, 30, 0, -30, -60, -90, -120, 
+    -150, -180, -195, -210, -225, -240, -255, -270, -285, -300, 
+    -315, -330, -345, -360, -345, -330, -315, -300, -285, -270, 
+    -255, -240, -225, -210, -195, -180, -150, -120, -90, -60, 
+    -30, 0, 30, 60, 90, 120, 150, 180, 195, 210, 
+    225, 240, 255, 270, 285, 300, 315, 330, 345, 390, 
+    375, 360, 345, 330, 315, 300, 285, 270, 255, 240, 
+    225, 210, 195, 165, 135, 105, 75, 45, 15, -15, 
+    -45, -75, -105, -135, -165, -195, -210, -225, -240, -255, 
+    -270, -285, -300, -315, -330, -345, -360, -375, -390, -375, 
+    -360, -345, -330, -315, -300, -285, -270, -255, -240, -225, 
+    -210, -195, -165, -135, -105, -75, -45, -15, 15, 45, 
+    75, 105, 135, 165, 195, 210, 225, 240, 255, 270, 
+    285, 300, 315, 330, 345, 360, 375, 420, 405, 390, 
+    375, 360, 345, 330, 315, 300, 285, 270, 255, 240, 
+    225, 210, 180, 150, 120, 90, 60, 30, 0, -30, 
+    -60, -90, -120, -150, -180, -210, -225, -240, -255, -270, 
+    -285, -300, -315, -330, -345, -360, -375, -390, -405, -420, 
+    -405, -390, -375, -360, -345, -330, -315, -300, -285, -270, 
+    -255, -240, -225, -210, -180, -150, -120, -90, -60, -30, 
+    0, 30, 60, 90, 120, 150, 180, 210, 225, 240, 
+    255, 270, 285, 300, 315, 330, 345, 360, 375, 390, 
+    405, 450, 435, 420, 405, 390, 375, 360, 345, 330, 
+    315, 300, 285, 270, 255, 240, 225, 195, 165, 135, 
+    105, 75, 45, 15, -15, -45, -75, -105, -135, -165, 
+    -195, -225, -240, -255, -270, -285, -300, -315, -330, -345, 
+    -360, -375, -390, -405, -420, -435, -450, -435, -420, -405, 
+    -390, -375, -360, -345, -330, -315, -300, -285, -270, -255, 
+    -240, -225, -195, -165, -135, -105, -75, -45, -15, 15, 
+    45, 75, 105, 135, 165, 195, 225, 240, 255, 270, 
+    285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 
+    435, 480, 465, 450, 435, 420, 405, 390, 375, 360, 
+    345, 330, 315, 300, 285, 270, 255, 240, 210, 180, 
+    150, 120, 90, 60, 30, 0, -30, -60, -90, -120, 
+    -150, -180, -210, -240, -255, -270, -285, -300, -315, -330, 
+    -345, -360, -375, -390, -405, -420, -435, -450, -465, -480, 
+    -465, -450, -435, -420, -405, -390, -375, -360, -345, -330, 
+    -315, -300, -285, -270, -255, -240, -210, -180, -150, -120, 
+    -90, -60, -30, 0, 30, 60, 90, 120, 150, 180, 
+    210, 240, 255, 270, 285, 300, 315, 330, 345, 360, 
+    375, 390, 405, 420, 435, 450, 465, 510, 495, 480, 
+    465, 450, 435, 420, 405, 390, 375, 360, 345, 330, 
+    315, 300, 285, 270, 255, 225, 195, 165, 135, 105, 
+    75, 45, 15, -15, -45, -75, -105, -135, -165, -195, 
+    -225, -255, -270, -285, -300, -315, -330, -345, -360, -375, 
+    -390, -405, -420, -435, -450, -465, -480, -495, -510, -495, 
+    -480, -465, -450, -435, -420, -405, -390, -375, -360, -345, 
+    -330, -315, -300, -285, -270, -255, -225, -195, -165, -135, 
+    -105, -75, -45, -15, 15, 45, 75, 105, 135, 165, 
+    195, 225, 255, 270, 285, 300, 315, 330, 345, 360, 
+    375, 390, 405, 420, 435, 450, 465, 480, 495, 510, 
+    495, 480, 465, 450, 435, 420, 405, 390, 375, 360, 
+    345, 330, 315, 300, 285, 210, 180, 150, 120, 90, 
+    60, 30, 0, -30, -60, -90, -120, -150, -180, -210, 
+    -240, -300, -315, -330, -345, -360, -375, -390, -405, -420, 
+    -435, -450, -465, -480, -495, -510, -525, -510, -495, -480, 
+    -465, -450, -435, -420, -405, -390, -375, -360, -345, -330, 
+    -315, -300, -285, -210, -180, -150, -120, -90, -60, -30, 
+    0, 30, 60, 90, 120, 150, 180, 210, 240, 300, 
+    315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 
+    465, 480, 495, 510, 525, 495, 480, 465, 450, 435, 
+    420, 405, 390, 375, 360, 345, 330, 135, 105, 75, 
+    45, 15, -15, -45, -75, -105, -135, -165, -195, -360, 
+    -375, -390, -405, -420, -435, -450, -465, -480, -495, -510, 
+    -525, -495, -480, -465, -450, -435, -420, -405, -390, -375, 
+    -360, -345, -330, -135, -105, -75, -45, -15, 15, 45, 
+    75, 105, 135, 165, 195, 360, 375, 390, 405, 420, 
+    435, 450, 465, 480, 495, 510, 525, 480, 465, 450, 
+    435, 420, 405, 390, 375, 360, 60, 30, 0, -30, 
+    -60, -90, -120, -150, -180, -420, -435, -450, -465, -480, 
+    -495, -510, -525, -540, -480, -465, -450, -435, -420, -405, 
+    -390, -375, -360, -60, -30, 0, 30, 60, 90, 120, 
+    150, 180, 420, 435, 450, 465, 480, 495, 510, 525, 
+    540, 465, 450, 435, 420, 405, -15, -45, -75, -105, 
+    -135, -480, -495, -510, -525, -540, -465, -450, -435, -420, 
+    -405, 15, 45, 75, 105, 135, 480, 495, 510, 525, 
+    540, 450, 435, -90, -120, -540, -555, -450, -435, 90, 
+    120, 540, 555
+  };
+
+  const float ytemp[1183] = {
+    0, 0, 25.9808, 25.9808, 0, 
+    -25.9808, -25.9808, 0, 25.9808, 51.9615, 
+    51.9615, 51.9615, 25.9808, 0, -25.9808, 
+    -51.9615, -51.9615, -51.9615, -25.9808, 0, 
+    25.9808, 51.9615, 77.9423, 77.9423, 77.9423, 
+    77.9423, 51.9615, 25.9808, 0, -25.9808, 
+    -51.9615, -77.9423, -77.9423, -77.9423, -77.9423, 
+    -51.9615, -25.9808, 0, 25.9808, 51.9615, 
+    77.9423, 103.923, 103.923, 103.923, 103.923, 
+    103.923, 77.9423, 51.9615, 25.9808, 0, 
+    -25.9808, -51.9615, -77.9423, -103.923, -103.923, 
+    -103.923, -103.923, -103.923, -77.9423, -51.9615, 
+    -25.9808, 0, 25.9808, 51.9615, 77.9423, 
+    103.923, 129.904, 129.904, 129.904, 129.904, 
+    129.904, 129.904, 103.923, 77.9423, 51.9615, 
+    25.9808, 0, -25.9808, -51.9615, -77.9423, 
+    -103.923, -129.904, -129.904, -129.904, -129.904, 
+    -129.904, -129.904, -103.923, -77.9423, -51.9615, 
+    -25.9808, 0, 25.9808, 51.9615, 77.9423, 
+    103.923, 129.904, 155.885, 155.885, 155.885, 
+    155.885, 155.885, 155.885, 155.885, 129.904, 
+    103.923, 77.9423, 51.9615, 25.9808, 0, 
+    -25.9808, -51.9615, -77.9423, -103.923, -129.904, 
+    -155.885, -155.885, -155.885, -155.885, -155.885, 
+    -155.885, -155.885, -129.904, -103.923, -77.9423, 
+    -51.9615, -25.9808, 0, 25.9808, 51.9615, 
+    77.9423, 103.923, 129.904, 155.885, 181.865, 
+    181.865, 181.865, 181.865, 181.865, 181.865, 
+    181.865, 181.865, 155.885, 129.904, 103.923, 
+    77.9423, 51.9615, 25.9808, 0, -25.9808, 
+    -51.9615, -77.9423, -103.923, -129.904, -155.885, 
+    -181.865, -181.865, -181.865, -181.865, -181.865, 
+    -181.865, -181.865, -181.865, -155.885, -129.904, 
+    -103.923, -77.9423, -51.9615, -25.9808, 0, 
+    25.9808, 51.9615, 77.9423, 103.923, 129.904, 
+    155.885, 181.865, 207.846, 207.846, 207.846, 
+    207.846, 207.846, 207.846, 207.846, 207.846, 
+    207.846, 181.865, 155.885, 129.904, 103.923, 
+    77.9423, 51.9615, 25.9808, 0, -25.9808, 
+    -51.9615, -77.9423, -103.923, -129.904, -155.885, 
+    -181.865, -207.846, -207.846, -207.846, -207.846, 
+    -207.846, -207.846, -207.846, -207.846, -207.846, 
+    -181.865, -155.885, -129.904, -103.923, -77.9423, 
+    -51.9615, -25.9808, 0, 25.9808, 51.9615, 
+    77.9423, 103.923, 129.904, 155.885, 181.865, 
+    207.846, 233.827, 233.827, 233.827, 233.827, 
+    233.827, 233.827, 233.827, 233.827, 233.827, 
+    233.827, 207.846, 181.865, 155.885, 129.904, 
+    103.923, 77.9423, 51.9615, 25.9808, 0, 
+    -25.9808, -51.9615, -77.9423, -103.923, -129.904, 
+    -155.885, -181.865, -207.846, -233.827, -233.827, 
+    -233.827, -233.827, -233.827, -233.827, -233.827, 
+    -233.827, -233.827, -233.827, -207.846, -181.865, 
+    -155.885, -129.904, -103.923, -77.9423, -51.9615, 
+    -25.9808, 0, 25.9808, 51.9615, 77.9423, 
+    103.923, 129.904, 155.885, 181.865, 207.846, 
+    233.827, 259.808, 259.808, 259.808, 259.808, 
+    259.808, 259.808, 259.808, 259.808, 259.808, 
+    259.808, 259.808, 233.827, 207.846, 181.865, 
+    155.885, 129.904, 103.923, 77.9423, 51.9615, 
+    25.9808, 0, -25.9808, -51.9615, -77.9423, 
+    -103.923, -129.904, -155.885, -181.865, -207.846, 
+    -233.827, -259.808, -259.808, -259.808, -259.808, 
+    -259.808, -259.808, -259.808, -259.808, -259.808, 
+    -259.808, -259.808, -233.827, -207.846, -181.865, 
+    -155.885, -129.904, -103.923, -77.9423, -51.9615, 
+    -25.9808, 0, 25.9808, 51.9615, 77.9423, 
+    103.923, 129.904, 155.885, 181.865, 207.846, 
+    233.827, 259.808, 285.788, 285.788, 285.788, 
+    285.788, 285.788, 285.788, 285.788, 285.788, 
+    285.788, 285.788, 285.788, 285.788, 259.808, 
+    233.827, 207.846, 181.865, 155.885, 129.904, 
+    103.923, 77.9423, 51.9615, 25.9808, 0, 
+    -25.9808, -51.9615, -77.9423, -103.923, -129.904, 
+    -155.885, -181.865, -207.846, -233.827, -259.808, 
+    -285.788, -285.788, -285.788, -285.788, -285.788, 
+    -285.788, -285.788, -285.788, -285.788, -285.788, 
+    -285.788, -285.788, -259.808, -233.827, -207.846, 
+    -181.865, -155.885, -129.904, -103.923, -77.9423, 
+    -51.9615, -25.9808, 0, 25.9808, 51.9615, 
+    77.9423, 103.923, 129.904, 155.885, 181.865, 
+    207.846, 233.827, 259.808, 285.788, 311.769, 
+    311.769, 311.769, 311.769, 311.769, 311.769, 
+    311.769, 311.769, 311.769, 311.769, 311.769, 
+    311.769, 311.769, 285.788, 259.808, 233.827, 
+    207.846, 181.865, 155.885, 129.904, 103.923, 
+    77.9423, 51.9615, 25.9808, 0, -25.9808, 
+    -51.9615, -77.9423, -103.923, -129.904, -155.885, 
+    -181.865, -207.846, -233.827, -259.808, -285.788, 
+    -311.769, -311.769, -311.769, -311.769, -311.769, 
+    -311.769, -311.769, -311.769, -311.769, -311.769, 
+    -311.769, -311.769, -311.769, -285.788, -259.808, 
+    -233.827, -207.846, -181.865, -155.885, -129.904, 
+    -103.923, -77.9423, -51.9615, -25.9808, 0, 
+    25.9808, 51.9615, 77.9423, 103.923, 129.904, 
+    155.885, 181.865, 207.846, 233.827, 259.808, 
+    285.788, 311.769, 337.75, 337.75, 337.75, 
+    337.75, 337.75, 337.75, 337.75, 337.75, 
+    337.75, 337.75, 337.75, 337.75, 337.75, 
+    337.75, 311.769, 285.788, 259.808, 233.827, 
+    207.846, 181.865, 155.885, 129.904, 103.923, 
+    77.9423, 51.9615, 25.9808, 0, -25.9808, 
+    -51.9615, -77.9423, -103.923, -129.904, -155.885, 
+    -181.865, -207.846, -233.827, -259.808, -285.788, 
+    -311.769, -337.75, -337.75, -337.75, -337.75, 
+    -337.75, -337.75, -337.75, -337.75, -337.75, 
+    -337.75, -337.75, -337.75, -337.75, -337.75, 
+    -311.769, -285.788, -259.808, -233.827, -207.846, 
+    -181.865, -155.885, -129.904, -103.923, -77.9423, 
+    -51.9615, -25.9808, 0, 25.9808, 51.9615, 
+    77.9423, 103.923, 129.904, 155.885, 181.865, 
+    207.846, 233.827, 259.808, 285.788, 311.769, 
+    337.75, 363.731, 363.731, 363.731, 363.731, 
+    363.731, 363.731, 363.731, 363.731, 363.731, 
+    363.731, 363.731, 363.731, 363.731, 363.731, 
+    363.731, 337.75, 311.769, 285.788, 259.808, 
+    233.827, 207.846, 181.865, 155.885, 129.904, 
+    103.923, 77.9423, 51.9615, 25.9808, 0, 
+    -25.9808, -51.9615, -77.9423, -103.923, -129.904, 
+    -155.885, -181.865, -207.846, -233.827, -259.808, 
+    -285.788, -311.769, -337.75, -363.731, -363.731, 
+    -363.731, -363.731, -363.731, -363.731, -363.731, 
+    -363.731, -363.731, -363.731, -363.731, -363.731, 
+    -363.731, -363.731, -363.731, -337.75, -311.769, 
+    -285.788, -259.808, -233.827, -207.846, -181.865, 
+    -155.885, -129.904, -103.923, -77.9423, -51.9615, 
+    -25.9808, 0, 25.9808, 51.9615, 77.9423, 
+    103.923, 129.904, 155.885, 181.865, 207.846, 
+    233.827, 259.808, 285.788, 311.769, 337.75, 
+    363.731, 389.711, 389.711, 389.711, 389.711, 
+    389.711, 389.711, 389.711, 389.711, 389.711, 
+    389.711, 389.711, 389.711, 389.711, 389.711, 
+    389.711, 389.711, 363.731, 337.75, 311.769, 
+    285.788, 259.808, 233.827, 207.846, 181.865, 
+    155.885, 129.904, 103.923, 77.9423, 51.9615, 
+    25.9808, 0, -25.9808, -51.9615, -77.9423, 
+    -103.923, -129.904, -155.885, -181.865, -207.846, 
+    -233.827, -259.808, -285.788, -311.769, -337.75, 
+    -363.731, -389.711, -389.711, -389.711, -389.711, 
+    -389.711, -389.711, -389.711, -389.711, -389.711, 
+    -389.711, -389.711, -389.711, -389.711, -389.711, 
+    -389.711, -389.711, -363.731, -337.75, -311.769, 
+    -285.788, -259.808, -233.827, -207.846, -181.865, 
+    -155.885, -129.904, -103.923, -77.9423, -51.9615, 
+    -25.9808, 0, 25.9808, 51.9615, 77.9423, 
+    103.923, 129.904, 155.885, 181.865, 207.846, 
+    233.827, 259.808, 285.788, 311.769, 337.75, 
+    363.731, 389.711, 415.692, 415.692, 415.692, 
+    415.692, 415.692, 415.692, 415.692, 415.692, 
+    415.692, 415.692, 415.692, 415.692, 415.692, 
+    415.692, 415.692, 415.692, 415.692, 389.711, 
+    363.731, 337.75, 311.769, 285.788, 259.808, 
+    233.827, 207.846, 181.865, 155.885, 129.904, 
+    103.923, 77.9423, 51.9615, 25.9808, 0, 
+    -25.9808, -51.9615, -77.9423, -103.923, -129.904, 
+    -155.885, -181.865, -207.846, -233.827, -259.808, 
+    -285.788, -311.769, -337.75, -363.731, -389.711, 
+    -415.692, -415.692, -415.692, -415.692, -415.692, 
+    -415.692, -415.692, -415.692, -415.692, -415.692, 
+    -415.692, -415.692, -415.692, -415.692, -415.692, 
+    -415.692, -415.692, -389.711, -363.731, -337.75, 
+    -311.769, -285.788, -259.808, -233.827, -207.846, 
+    -181.865, -155.885, -129.904, -103.923, -77.9423, 
+    -51.9615, -25.9808, 0, 25.9808, 51.9615, 
+    77.9423, 103.923, 129.904, 155.885, 181.865, 
+    207.846, 233.827, 259.808, 285.788, 311.769, 
+    337.75, 363.731, 389.711, 415.692, 441.673, 
+    441.673, 441.673, 441.673, 441.673, 441.673, 
+    441.673, 441.673, 441.673, 441.673, 441.673, 
+    441.673, 441.673, 441.673, 441.673, 441.673, 
+    441.673, 441.673, 415.692, 389.711, 363.731, 
+    337.75, 311.769, 285.788, 259.808, 233.827, 
+    207.846, 181.865, 155.885, 129.904, 103.923, 
+    77.9423, 51.9615, 25.9808, 0, -25.9808, 
+    -51.9615, -77.9423, -103.923, -129.904, -155.885, 
+    -181.865, -207.846, -233.827, -259.808, -285.788, 
+    -311.769, -337.75, -363.731, -389.711, -415.692, 
+    -441.673, -441.673, -441.673, -441.673, -441.673, 
+    -441.673, -441.673, -441.673, -441.673, -441.673, 
+    -441.673, -441.673, -441.673, -441.673, -441.673, 
+    -441.673, -441.673, -441.673, -415.692, -389.711, 
+    -363.731, -337.75, -311.769, -285.788, -259.808, 
+    -233.827, -207.846, -181.865, -155.885, -129.904, 
+    -103.923, -77.9423, -51.9615, -25.9808, 51.9615, 
+    77.9423, 103.923, 129.904, 155.885, 181.865, 
+    207.846, 233.827, 259.808, 285.788, 311.769, 
+    337.75, 363.731, 389.711, 415.692, 441.673, 
+    467.654, 467.654, 467.654, 467.654, 467.654, 
+    467.654, 467.654, 467.654, 467.654, 467.654, 
+    467.654, 467.654, 467.654, 467.654, 467.654, 
+    467.654, 415.692, 389.711, 363.731, 337.75, 
+    311.769, 285.788, 259.808, 233.827, 207.846, 
+    181.865, 155.885, 129.904, 103.923, 77.9423, 
+    51.9615, 25.9808, -51.9615, -77.9423, -103.923, 
+    -129.904, -155.885, -181.865, -207.846, -233.827, 
+    -259.808, -285.788, -311.769, -337.75, -363.731, 
+    -389.711, -415.692, -441.673, -467.654, -467.654, 
+    -467.654, -467.654, -467.654, -467.654, -467.654, 
+    -467.654, -467.654, -467.654, -467.654, -467.654, 
+    -467.654, -467.654, -467.654, -467.654, -415.692, 
+    -389.711, -363.731, -337.75, -311.769, -285.788, 
+    -259.808, -233.827, -207.846, -181.865, -155.885, 
+    -129.904, -103.923, -77.9423, -51.9615, -25.9808, 
+    129.904, 155.885, 181.865, 207.846, 233.827, 
+    259.808, 285.788, 311.769, 337.75, 363.731, 
+    389.711, 415.692, 493.634, 493.634, 493.634, 
+    493.634, 493.634, 493.634, 493.634, 493.634, 
+    493.634, 493.634, 493.634, 493.634, 363.731, 
+    337.75, 311.769, 285.788, 259.808, 233.827, 
+    207.846, 181.865, 155.885, 129.904, 103.923, 
+    77.9423, -129.904, -155.885, -181.865, -207.846, 
+    -233.827, -259.808, -285.788, -311.769, -337.75, 
+    -363.731, -389.711, -415.692, -493.634, -493.634, 
+    -493.634, -493.634, -493.634, -493.634, -493.634, 
+    -493.634, -493.634, -493.634, -493.634, -493.634, 
+    -363.731, -337.75, -311.769, -285.788, -259.808, 
+    -233.827, -207.846, -181.865, -155.885, -129.904, 
+    -103.923, -77.9423, 207.846, 233.827, 259.808, 
+    285.788, 311.769, 337.75, 363.731, 389.711, 
+    415.692, 519.615, 519.615, 519.615, 519.615, 
+    519.615, 519.615, 519.615, 519.615, 519.615, 
+    311.769, 285.788, 259.808, 233.827, 207.846, 
+    181.865, 155.885, 129.904, 103.923, -207.846, 
+    -233.827, -259.808, -285.788, -311.769, -337.75, 
+    -363.731, -389.711, -415.692, -519.615, -519.615, 
+    -519.615, -519.615, -519.615, -519.615, -519.615, 
+    -519.615, -519.615, -311.769, -285.788, -259.808, 
+    -233.827, -207.846, -181.865, -155.885, -129.904, 
+    -103.923, 285.788, 311.769, 337.75, 363.731, 
+    389.711, 545.596, 545.596, 545.596, 545.596, 
+    545.596, 259.808, 233.827, 207.846, 181.865, 
+    155.885, -285.788, -311.769, -337.75, -363.731, 
+    -389.711, -545.596, -545.596, -545.596, -545.596, 
+    -545.596, -259.808, -233.827, -207.846, -181.865, 
+    -155.885, 363.731, 389.711, 571.577, 571.577, 
+    207.846, 181.865, -363.731, -389.711, -571.577, 
+    -571.577, -207.846, -181.865
+  };
+
+  const float rtemp[1183] = {
+	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, // 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 // 1183
+};
+
+    //
+    //   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 MGeomCamMagic1183::CreateNN()
+{
+  const Short_t nn[1183][6] = {       // Neighbours of [pixid=0-1182]
+    { 1, 2, 3, 4, 5, 6 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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 },
+    { 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, 1014, -1, -1 },
+    { 721, 722, 817, 819, 919, -1 },
+    { 722, 723, 818, 820, 919, 920 },
+    { 723, 724, 819, 821, 920, 921 },
+    { 724, 725, 820, 822, 921, 922 },
+    { 725, 726, 821, 823, 922, 923 },
+    { 726, 727, 822, 824, 923, 924 },
+    { 727, 728, 823, 825, 924, 925 },
+    { 728, 729, 824, 826, 925, 926 },
+    { 729, 730, 825, 827, 926, 927 },
+    { 730, 731, 826, 828, 927, 928 },
+    { 731, 732, 827, 829, 928, 929 },
+    { 732, 733, 828, 830, 929, 930 },
+    { 733, 734, 829, 831, 930, 931 },
+    { 734, 735, 830, 832, 931, 932 },
+    { 735, 736, 831, 833, 932, 933 },
+    { 736, 737, 832, 834, 933, 934 },
+    { 737, 833, 835, 934, -1, -1 },
+    { 737, 738, 834, 836, 935, -1 },
+    { 738, 739, 835, 837, 935, 936 },
+    { 739, 740, 836, 838, 936, 937 },
+    { 740, 741, 837, 839, 937, 938 },
+    { 741, 742, 838, 840, 938, 939 },
+    { 742, 743, 839, 841, 939, 940 },
+    { 743, 744, 840, 842, 940, 941 },
+    { 744, 745, 841, 843, 941, 942 },
+    { 745, 746, 842, 844, 942, 943 },
+    { 746, 747, 843, 845, 943, 944 },
+    { 747, 748, 844, 846, 944, 945 },
+    { 748, 749, 845, 847, 945, 946 },
+    { 749, 750, 846, 848, 946, 947 },
+    { 750, 751, 847, 849, 947, 948 },
+    { 751, 752, 848, 850, 948, 949 },
+    { 752, 753, 849, 851, 949, 950 },
+    { 753, 850, 852, 950, -1, -1 },
+    { 753, 754, 851, 853, 951, -1 },
+    { 754, 755, 852, 854, 951, 952 },
+    { 755, 756, 853, 855, 952, 953 },
+    { 756, 757, 854, 856, 953, 954 },
+    { 757, 758, 855, 857, 954, 955 },
+    { 758, 759, 856, 858, 955, 956 },
+    { 759, 760, 857, 859, 956, 957 },
+    { 760, 761, 858, 860, 957, 958 },
+    { 761, 762, 859, 861, 958, 959 },
+    { 762, 763, 860, 862, 959, 960 },
+    { 763, 764, 861, 863, 960, 961 },
+    { 764, 765, 862, 864, 961, 962 },
+    { 765, 766, 863, 865, 962, 963 },
+    { 766, 767, 864, 866, 963, 964 },
+    { 767, 768, 865, 867, 964, 965 },
+    { 768, 769, 866, 868, 965, 966 },
+    { 769, 867, 869, 966, -1, -1 },
+    { 769, 770, 868, 870, 967, -1 },
+    { 770, 771, 869, 871, 967, 968 },
+    { 771, 772, 870, 872, 968, 969 },
+    { 772, 773, 871, 873, 969, 970 },
+    { 773, 774, 872, 874, 970, 971 },
+    { 774, 775, 873, 875, 971, 972 },
+    { 775, 776, 874, 876, 972, 973 },
+    { 776, 777, 875, 877, 973, 974 },
+    { 777, 778, 876, 878, 974, 975 },
+    { 778, 779, 877, 879, 975, 976 },
+    { 779, 780, 878, 880, 976, 977 },
+    { 780, 781, 879, 881, 977, 978 },
+    { 781, 782, 880, 882, 978, 979 },
+    { 782, 783, 881, 883, 979, 980 },
+    { 783, 784, 882, 884, 980, 981 },
+    { 784, 785, 883, 885, 981, 982 },
+    { 785, 884, 886, 982, -1, -1 },
+    { 785, 786, 885, 887, 983, -1 },
+    { 786, 787, 886, 888, 983, 984 },
+    { 787, 788, 887, 889, 984, 985 },
+    { 788, 789, 888, 890, 985, 986 },
+    { 789, 790, 889, 891, 986, 987 },
+    { 790, 791, 890, 892, 987, 988 },
+    { 791, 792, 891, 893, 988, 989 },
+    { 792, 793, 892, 894, 989, 990 },
+    { 793, 794, 893, 895, 990, 991 },
+    { 794, 795, 894, 896, 991, 992 },
+    { 795, 796, 895, 897, 992, 993 },
+    { 796, 797, 896, 898, 993, 994 },
+    { 797, 798, 897, 899, 994, 995 },
+    { 798, 799, 898, 900, 995, 996 },
+    { 799, 800, 899, 901, 996, 997 },
+    { 800, 801, 900, 902, 997, 998 },
+    { 801, 901, 903, 998, -1, -1 },
+    { 801, 802, 902, 904, 999, -1 },
+    { 802, 803, 903, 905, 999, 1000 },
+    { 803, 804, 904, 906, 1000, 1001 },
+    { 804, 805, 905, 907, 1001, 1002 },
+    { 805, 806, 906, 908, 1002, 1003 },
+    { 806, 807, 907, 909, 1003, 1004 },
+    { 807, 808, 908, 910, 1004, 1005 },
+    { 808, 809, 909, 911, 1005, 1006 },
+    { 809, 810, 910, 912, 1006, 1007 },
+    { 810, 811, 911, 913, 1007, 1008 },
+    { 811, 812, 912, 914, 1008, 1009 },
+    { 812, 813, 913, 915, 1009, 1010 },
+    { 813, 814, 914, 916, 1010, 1011 },
+    { 814, 815, 915, 917, 1011, 1012 },
+    { 815, 816, 916, 918, 1012, 1013 },
+    { 721, 816, 817, 917, 1013, 1014 },
+    { 818, 819, 920, -1, -1, -1 },
+    { 819, 820, 919, 921, -1, -1 },
+    { 820, 821, 920, 922, 1015, -1 },
+    { 821, 822, 921, 923, 1015, 1016 },
+    { 822, 823, 922, 924, 1016, 1017 },
+    { 823, 824, 923, 925, 1017, 1018 },
+    { 824, 825, 924, 926, 1018, 1019 },
+    { 825, 826, 925, 927, 1019, 1020 },
+    { 826, 827, 926, 928, 1020, 1021 },
+    { 827, 828, 927, 929, 1021, 1022 },
+    { 828, 829, 928, 930, 1022, 1023 },
+    { 829, 830, 929, 931, 1023, 1024 },
+    { 830, 831, 930, 932, 1024, 1025 },
+    { 831, 832, 931, 933, 1025, 1026 },
+    { 832, 833, 932, 934, 1026, -1 },
+    { 833, 834, 933, -1, -1, -1 },
+    { 835, 836, 936, -1, -1, -1 },
+    { 836, 837, 935, 937, -1, -1 },
+    { 837, 838, 936, 938, 1027, -1 },
+    { 838, 839, 937, 939, 1027, 1028 },
+    { 839, 840, 938, 940, 1028, 1029 },
+    { 840, 841, 939, 941, 1029, 1030 },
+    { 841, 842, 940, 942, 1030, 1031 },
+    { 842, 843, 941, 943, 1031, 1032 },
+    { 843, 844, 942, 944, 1032, 1033 },
+    { 844, 845, 943, 945, 1033, 1034 },
+    { 845, 846, 944, 946, 1034, 1035 },
+    { 846, 847, 945, 947, 1035, 1036 },
+    { 847, 848, 946, 948, 1036, 1037 },
+    { 848, 849, 947, 949, 1037, 1038 },
+    { 849, 850, 948, 950, 1038, -1 },
+    { 850, 851, 949, -1, -1, -1 },
+    { 852, 853, 952, -1, -1, -1 },
+    { 853, 854, 951, 953, -1, -1 },
+    { 854, 855, 952, 954, 1039, -1 },
+    { 855, 856, 953, 955, 1039, 1040 },
+    { 856, 857, 954, 956, 1040, 1041 },
+    { 857, 858, 955, 957, 1041, 1042 },
+    { 858, 859, 956, 958, 1042, 1043 },
+    { 859, 860, 957, 959, 1043, 1044 },
+    { 860, 861, 958, 960, 1044, 1045 },
+    { 861, 862, 959, 961, 1045, 1046 },
+    { 862, 863, 960, 962, 1046, 1047 },
+    { 863, 864, 961, 963, 1047, 1048 },
+    { 864, 865, 962, 964, 1048, 1049 },
+    { 865, 866, 963, 965, 1049, 1050 },
+    { 866, 867, 964, 966, 1050, -1 },
+    { 867, 868, 965, -1, -1, -1 },
+    { 869, 870, 968, -1, -1, -1 },
+    { 870, 871, 967, 969, -1, -1 },
+    { 871, 872, 968, 970, 1051, -1 },
+    { 872, 873, 969, 971, 1051, 1052 },
+    { 873, 874, 970, 972, 1052, 1053 },
+    { 874, 875, 971, 973, 1053, 1054 },
+    { 875, 876, 972, 974, 1054, 1055 },
+    { 876, 877, 973, 975, 1055, 1056 },
+    { 877, 878, 974, 976, 1056, 1057 },
+    { 878, 879, 975, 977, 1057, 1058 },
+    { 879, 880, 976, 978, 1058, 1059 },
+    { 880, 881, 977, 979, 1059, 1060 },
+    { 881, 882, 978, 980, 1060, 1061 },
+    { 882, 883, 979, 981, 1061, 1062 },
+    { 883, 884, 980, 982, 1062, -1 },
+    { 884, 885, 981, -1, -1, -1 },
+    { 886, 887, 984, -1, -1, -1 },
+    { 887, 888, 983, 985, -1, -1 },
+    { 888, 889, 984, 986, 1063, -1 },
+    { 889, 890, 985, 987, 1063, 1064 },
+    { 890, 891, 986, 988, 1064, 1065 },
+    { 891, 892, 987, 989, 1065, 1066 },
+    { 892, 893, 988, 990, 1066, 1067 },
+    { 893, 894, 989, 991, 1067, 1068 },
+    { 894, 895, 990, 992, 1068, 1069 },
+    { 895, 896, 991, 993, 1069, 1070 },
+    { 896, 897, 992, 994, 1070, 1071 },
+    { 897, 898, 993, 995, 1071, 1072 },
+    { 898, 899, 994, 996, 1072, 1073 },
+    { 899, 900, 995, 997, 1073, 1074 },
+    { 900, 901, 996, 998, 1074, -1 },
+    { 901, 902, 997, -1, -1, -1 },
+    { 903, 904, 1000, -1, -1, -1 },
+    { 904, 905, 999, 1001, -1, -1 },
+    { 905, 906, 1000, 1002, 1075, -1 },
+    { 906, 907, 1001, 1003, 1075, 1076 },
+    { 907, 908, 1002, 1004, 1076, 1077 },
+    { 908, 909, 1003, 1005, 1077, 1078 },
+    { 909, 910, 1004, 1006, 1078, 1079 },
+    { 910, 911, 1005, 1007, 1079, 1080 },
+    { 911, 912, 1006, 1008, 1080, 1081 },
+    { 912, 913, 1007, 1009, 1081, 1082 },
+    { 913, 914, 1008, 1010, 1082, 1083 },
+    { 914, 915, 1009, 1011, 1083, 1084 },
+    { 915, 916, 1010, 1012, 1084, 1085 },
+    { 916, 917, 1011, 1013, 1085, 1086 },
+    { 917, 918, 1012, 1014, 1086, -1 },
+    { 817, 918, 1013, -1, -1, -1 },
+    { 921, 922, 1016, -1, -1, -1 },
+    { 922, 923, 1015, 1017, -1, -1 },
+    { 923, 924, 1016, 1018, 1087, -1 },
+    { 924, 925, 1017, 1019, 1087, 1088 },
+    { 925, 926, 1018, 1020, 1088, 1089 },
+    { 926, 927, 1019, 1021, 1089, 1090 },
+    { 927, 928, 1020, 1022, 1090, 1091 },
+    { 928, 929, 1021, 1023, 1091, 1092 },
+    { 929, 930, 1022, 1024, 1092, 1093 },
+    { 930, 931, 1023, 1025, 1093, 1094 },
+    { 931, 932, 1024, 1026, 1094, 1095 },
+    { 932, 933, 1025, 1095, -1, -1 },
+    { 937, 938, 1028, -1, -1, -1 },
+    { 938, 939, 1027, 1029, -1, -1 },
+    { 939, 940, 1028, 1030, 1096, -1 },
+    { 940, 941, 1029, 1031, 1096, 1097 },
+    { 941, 942, 1030, 1032, 1097, 1098 },
+    { 942, 943, 1031, 1033, 1098, 1099 },
+    { 943, 944, 1032, 1034, 1099, 1100 },
+    { 944, 945, 1033, 1035, 1100, 1101 },
+    { 945, 946, 1034, 1036, 1101, 1102 },
+    { 946, 947, 1035, 1037, 1102, 1103 },
+    { 947, 948, 1036, 1038, 1103, 1104 },
+    { 948, 949, 1037, 1104, -1, -1 },
+    { 953, 954, 1040, -1, -1, -1 },
+    { 954, 955, 1039, 1041, -1, -1 },
+    { 955, 956, 1040, 1042, 1105, -1 },
+    { 956, 957, 1041, 1043, 1105, 1106 },
+    { 957, 958, 1042, 1044, 1106, 1107 },
+    { 958, 959, 1043, 1045, 1107, 1108 },
+    { 959, 960, 1044, 1046, 1108, 1109 },
+    { 960, 961, 1045, 1047, 1109, 1110 },
+    { 961, 962, 1046, 1048, 1110, 1111 },
+    { 962, 963, 1047, 1049, 1111, 1112 },
+    { 963, 964, 1048, 1050, 1112, 1113 },
+    { 964, 965, 1049, 1113, -1, -1 },
+    { 969, 970, 1052, -1, -1, -1 },
+    { 970, 971, 1051, 1053, -1, -1 },
+    { 971, 972, 1052, 1054, 1114, -1 },
+    { 972, 973, 1053, 1055, 1114, 1115 },
+    { 973, 974, 1054, 1056, 1115, 1116 },
+    { 974, 975, 1055, 1057, 1116, 1117 },
+    { 975, 976, 1056, 1058, 1117, 1118 },
+    { 976, 977, 1057, 1059, 1118, 1119 },
+    { 977, 978, 1058, 1060, 1119, 1120 },
+    { 978, 979, 1059, 1061, 1120, 1121 },
+    { 979, 980, 1060, 1062, 1121, 1122 },
+    { 980, 981, 1061, 1122, -1, -1 },
+    { 985, 986, 1064, -1, -1, -1 },
+    { 986, 987, 1063, 1065, -1, -1 },
+    { 987, 988, 1064, 1066, 1123, -1 },
+    { 988, 989, 1065, 1067, 1123, 1124 },
+    { 989, 990, 1066, 1068, 1124, 1125 },
+    { 990, 991, 1067, 1069, 1125, 1126 },
+    { 991, 992, 1068, 1070, 1126, 1127 },
+    { 992, 993, 1069, 1071, 1127, 1128 },
+    { 993, 994, 1070, 1072, 1128, 1129 },
+    { 994, 995, 1071, 1073, 1129, 1130 },
+    { 995, 996, 1072, 1074, 1130, 1131 },
+    { 996, 997, 1073, 1131, -1, -1 },
+    { 1001, 1002, 1076, -1, -1, -1 },
+    { 1002, 1003, 1075, 1077, -1, -1 },
+    { 1003, 1004, 1076, 1078, 1132, -1 },
+    { 1004, 1005, 1077, 1079, 1132, 1133 },
+    { 1005, 1006, 1078, 1080, 1133, 1134 },
+    { 1006, 1007, 1079, 1081, 1134, 1135 },
+    { 1007, 1008, 1080, 1082, 1135, 1136 },
+    { 1008, 1009, 1081, 1083, 1136, 1137 },
+    { 1009, 1010, 1082, 1084, 1137, 1138 },
+    { 1010, 1011, 1083, 1085, 1138, 1139 },
+    { 1011, 1012, 1084, 1086, 1139, 1140 },
+    { 1012, 1013, 1085, 1140, -1, -1 },
+    { 1017, 1018, 1088, -1, -1, -1 },
+    { 1018, 1019, 1087, 1089, -1, -1 },
+    { 1019, 1020, 1088, 1090, 1141, -1 },
+    { 1020, 1021, 1089, 1091, 1141, 1142 },
+    { 1021, 1022, 1090, 1092, 1142, 1143 },
+    { 1022, 1023, 1091, 1093, 1143, 1144 },
+    { 1023, 1024, 1092, 1094, 1144, 1145 },
+    { 1024, 1025, 1093, 1095, 1145, -1 },
+    { 1025, 1026, 1094, -1, -1, -1 },
+    { 1029, 1030, 1097, -1, -1, -1 },
+    { 1030, 1031, 1096, 1098, -1, -1 },
+    { 1031, 1032, 1097, 1099, 1146, -1 },
+    { 1032, 1033, 1098, 1100, 1146, 1147 },
+    { 1033, 1034, 1099, 1101, 1147, 1148 },
+    { 1034, 1035, 1100, 1102, 1148, 1149 },
+    { 1035, 1036, 1101, 1103, 1149, 1150 },
+    { 1036, 1037, 1102, 1104, 1150, -1 },
+    { 1037, 1038, 1103, -1, -1, -1 },
+    { 1041, 1042, 1106, -1, -1, -1 },
+    { 1042, 1043, 1105, 1107, -1, -1 },
+    { 1043, 1044, 1106, 1108, 1151, -1 },
+    { 1044, 1045, 1107, 1109, 1151, 1152 },
+    { 1045, 1046, 1108, 1110, 1152, 1153 },
+    { 1046, 1047, 1109, 1111, 1153, 1154 },
+    { 1047, 1048, 1110, 1112, 1154, 1155 },
+    { 1048, 1049, 1111, 1113, 1155, -1 },
+    { 1049, 1050, 1112, -1, -1, -1 },
+    { 1053, 1054, 1115, -1, -1, -1 },
+    { 1054, 1055, 1114, 1116, -1, -1 },
+    { 1055, 1056, 1115, 1117, 1156, -1 },
+    { 1056, 1057, 1116, 1118, 1156, 1157 },
+    { 1057, 1058, 1117, 1119, 1157, 1158 },
+    { 1058, 1059, 1118, 1120, 1158, 1159 },
+    { 1059, 1060, 1119, 1121, 1159, 1160 },
+    { 1060, 1061, 1120, 1122, 1160, -1 },
+    { 1061, 1062, 1121, -1, -1, -1 },
+    { 1065, 1066, 1124, -1, -1, -1 },
+    { 1066, 1067, 1123, 1125, -1, -1 },
+    { 1067, 1068, 1124, 1126, 1161, -1 },
+    { 1068, 1069, 1125, 1127, 1161, 1162 },
+    { 1069, 1070, 1126, 1128, 1162, 1163 },
+    { 1070, 1071, 1127, 1129, 1163, 1164 },
+    { 1071, 1072, 1128, 1130, 1164, 1165 },
+    { 1072, 1073, 1129, 1131, 1165, -1 },
+    { 1073, 1074, 1130, -1, -1, -1 },
+    { 1077, 1078, 1133, -1, -1, -1 },
+    { 1078, 1079, 1132, 1134, -1, -1 },
+    { 1079, 1080, 1133, 1135, 1166, -1 },
+    { 1080, 1081, 1134, 1136, 1166, 1167 },
+    { 1081, 1082, 1135, 1137, 1167, 1168 },
+    { 1082, 1083, 1136, 1138, 1168, 1169 },
+    { 1083, 1084, 1137, 1139, 1169, 1170 },
+    { 1084, 1085, 1138, 1140, 1170, -1 },
+    { 1085, 1086, 1139, -1, -1, -1 },
+    { 1089, 1090, 1142, -1, -1, -1 },
+    { 1090, 1091, 1141, 1143, -1, -1 },
+    { 1091, 1092, 1142, 1144, 1171, -1 },
+    { 1092, 1093, 1143, 1145, 1171, 1172 },
+    { 1093, 1094, 1144, 1172, -1, -1 },
+    { 1098, 1099, 1147, -1, -1, -1 },
+    { 1099, 1100, 1146, 1148, -1, -1 },
+    { 1100, 1101, 1147, 1149, 1173, -1 },
+    { 1101, 1102, 1148, 1150, 1173, 1174 },
+    { 1102, 1103, 1149, 1174, -1, -1 },
+    { 1107, 1108, 1152, -1, -1, -1 },
+    { 1108, 1109, 1151, 1153, -1, -1 },
+    { 1109, 1110, 1152, 1154, 1175, -1 },
+    { 1110, 1111, 1153, 1155, 1175, 1176 },
+    { 1111, 1112, 1154, 1176, -1, -1 },
+    { 1116, 1117, 1157, -1, -1, -1 },
+    { 1117, 1118, 1156, 1158, -1, -1 },
+    { 1118, 1119, 1157, 1159, 1177, -1 },
+    { 1119, 1120, 1158, 1160, 1177, 1178 },
+    { 1120, 1121, 1159, 1178, -1, -1 },
+    { 1125, 1126, 1162, -1, -1, -1 },
+    { 1126, 1127, 1161, 1163, -1, -1 },
+    { 1127, 1128, 1162, 1164, 1179, -1 },
+    { 1128, 1129, 1163, 1165, 1179, 1180 },
+    { 1129, 1130, 1164, 1180, -1, -1 },
+    { 1134, 1135, 1167, -1, -1, -1 },
+    { 1135, 1136, 1166, 1168, -1, -1 },
+    { 1136, 1137, 1167, 1169, 1181, -1 },
+    { 1137, 1138, 1168, 1170, 1181, 1182 },
+    { 1138, 1139, 1169, 1182, -1, -1 },
+    { 1143, 1144, 1172, -1, -1, -1 },
+    { 1144, 1145, 1171, -1, -1, -1 },
+    { 1148, 1149, 1174, -1, -1, -1 },
+    { 1149, 1150, 1173, -1, -1, -1 },
+    { 1153, 1154, 1176, -1, -1, -1 },
+    { 1154, 1155, 1175, -1, -1, -1 },
+    { 1158, 1159, 1178, -1, -1, -1 },
+    { 1159, 1160, 1177, -1, -1, -1 },
+    { 1163, 1164, 1180, -1, -1, -1 },
+    { 1164, 1165, 1179, -1, -1, -1 },
+    { 1168, 1169, 1182, -1, -1, -1 },
+    { 1169, 1170, 1181, -1, -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic1183.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic1183.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic1183.h	(revision 17960)
@@ -0,0 +1,21 @@
+#ifndef MARS_MGeomCamMagic1183
+#define MARS_MGeomCamMagic1183
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamMagic1183 : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamMagic1183(const char *name=NULL);
+
+    ClassDef(MGeomCamMagic1183, 1)	 // Geometry class for Magic-2 camera with only small pixels
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic919.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic919.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic919.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic919.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic919.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagic919.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagicHG.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagicHG.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagicHG.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamMagicHG.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamMagicHG.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamMagicHG.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCamSquare.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamSquare.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamSquare.cc	(revision 17960)
@@ -0,0 +1,92 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamSquare
+//
+// This class stores the geometry information of a camera with square
+// pixels
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamSquare.h"
+
+#include "MMath.h"
+
+#include "MGeomRectangle.h"
+
+ClassImp(MGeomCamSquare);
+
+// --------------------------------------------------------------------------
+//
+//  Square camera with 144 pixels in a distance of 4.96m with a
+// layout of 12x12
+//
+MGeomCamSquare::MGeomCamSquare(const char *name)
+    : MGeomCam(144, 4.96, name, "Geometry information of a square camera")
+{
+    CreateCam(12, 12, 7);
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  For geometry and Next Neighbor info see
+//  CreateCam
+//
+MGeomCamSquare::MGeomCamSquare(Short_t x, Short_t y, Double_t diameter, Double_t dist, const char *name)
+    : MGeomCam(x*y, dist, name, "Geometry information of a square camera")
+{
+    CreateCam(x, y, diameter);
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the photon which is flying along the trajectory u has passed
+// (or will pass) the frame of the camera (and consequently get
+// absorbed). The position p and direction u must be in the
+// telescope coordinate frame, which is z parallel to the focal plane,
+// x to the right and y upwards, looking from the mirror towards the camera.
+//
+Bool_t MGeomCamSquare::HitFrame(MQuaternion p, const MQuaternion &u) const
+{
+    // z is defined from the mirror (0) to the camera (z>0).
+    // Thus we just propagate to the focal plane (z=fDist)
+    //p -= 1700./u.Z()*u;
+    p.PropagateZ(u, GetCameraDist()*100);
+
+    return TMath::Abs(p.X())*10<GetMaxRadius() && TMath::Abs(p.Y())*10<GetMaxRadius();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information from a table into the pixel objects.
+//
+void MGeomCamSquare::CreateCam(Short_t nx, Short_t ny, Double_t diameter)
+{
+    for (Short_t x=0; x<nx; x++)
+        for (Short_t y=0; y<ny; y++)
+            SetAt(x*ny+y, MGeomRectangle((0.5*nx-x-0.5)*diameter, (0.5*ny-y-0.5)*diameter, diameter));
+}
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCamSquare.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCamSquare.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCamSquare.h	(revision 17960)
@@ -0,0 +1,23 @@
+#ifndef MARS_MGeomCamSquare
+#define MARS_MGeomCamSquare
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamSquare : public MGeomCam
+{
+private:
+    void CreateCam(Short_t x, Short_t y, Double_t diameter);
+
+public:
+    MGeomCamSquare(Short_t x, Short_t y, Double_t diameter=7, Double_t dist=4.92, const char *name=NULL);
+    MGeomCamSquare(const char *name=NULL);
+
+    Bool_t HitFrame(MQuaternion p, const MQuaternion &u) const;
+
+    ClassDef(MGeomCamSquare, 1)	// Geometry class for a square pixel camera
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mgeom/MGeomCorsikaCT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCorsikaCT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCorsikaCT.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomCorsikaCT.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomCorsikaCT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomCorsikaCT.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomMirror.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomMirror.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomMirror.cc	(revision 17960)
@@ -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): 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 <TMath.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: branches/Mars_McMismatchStudy/mgeom/MGeomMirror.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomMirror.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomMirror.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomPMT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomPMT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomPMT.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomPMT.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomPMT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomPMT.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgeom/MGeomPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomPix.cc	(revision 17960)
@@ -0,0 +1,427 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MGeomPix
+//
+// This container stores the geometry (position) information of
+// a single pixel together with the information about next neighbors.
+//
+//
+// Version 1:
+// ----------
+//  - first implementation
+//
+// Version 2:
+// ----------
+//  - added fA
+//
+// Version 3:
+// ----------
+//  - added fAidx
+//
+// Version 4:
+// ----------
+//  - added fUserBits
+//
+// Version 5:
+// ----------
+//  - now derives from MGeom to which some data members have been moved
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomPix.h"
+
+#include <TMath.h>
+#include <TVector2.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MHexagon.h"
+
+ClassImp(MGeomPix);
+
+using namespace std;
+
+const Float_t MGeomPix::gsTan30 = TMath::Sqrt(3)/3;  //TMath::Tan(TMath::DegToRad()*30);
+const Float_t MGeomPix::gsTan60 = TMath::Sqrt(3);    //TMath::Tan(TMath::DegToRad()*60);
+
+const Float_t MGeomPix::gsCos60 = 0.5;               //TMath::Cos(TMath::DegToRad()*60);
+const Float_t MGeomPix::gsSin60 = TMath::Sqrt(3)/2;  //TMath::Sin(TMath::DegToRad()*60);
+
+// --------------------------------------------------------------------------
+//
+// Initializes one pixel
+//
+MGeomPix::MGeomPix(Float_t x, Float_t y, Float_t r, UInt_t s, UInt_t a)
+    : MGeom(x, y, s, a), fCosPhi(1), fSinPhi(0)
+{
+    SetD(r);
+    SetNeighbors();
+}
+
+void MGeomPix::SetPhi(Double_t phi)
+{
+    fCosPhi = TMath::Cos(phi);
+    fSinPhi = TMath::Sin(phi);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the geometry information of one pixel.
+//
+void MGeomPix::Print(Option_t *opt) const
+{
+    MGeom::Print(opt);
+    gLog << " d=" << fD << "mm" << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// Implementation of PaintPrimitive drwaing a hexagonal pixel
+//
+void MGeomPix::PaintPrimitive(const TAttLine &line, const TAttFill &fill, Double_t scalexy, Double_t scaled) const
+{
+    const_cast<TAttLine&>(line).Modify();  //Change line attributes only if necessary
+    const_cast<TAttFill&>(fill).Modify();  //Change fill area attributes only if necessary
+
+    const Double_t fx       = fX*scalexy;
+    const Double_t fy       = fY*scalexy;
+    const Double_t fd       = fD*scaled;
+
+    const Double_t c        = fd*fCosPhi;
+    const Double_t s        = fd*fSinPhi;
+
+    const Double_t gsCos60c = gsCos60*c;
+    const Double_t gsCos60s = gsCos60*s;
+
+    const Double_t gsSin60c = gsSin60*c/3;
+    const Double_t gsSin60s = gsSin60*s/3;
+
+    const Double_t gsTan30c = gsTan30*c;
+    const Double_t gsTan30s = gsTan30*s;
+
+
+    Double_t x[7] = {
+         gsCos60c-gsSin60s,  -gsTan30s,  -gsCos60c-gsSin60s,
+        -gsCos60c+gsSin60s,   gsTan30s,   gsCos60c+gsSin60s
+    };
+
+    Double_t y[7] = {
+         gsCos60s+gsSin60c,   gsTan30c,  -gsCos60s+gsSin60c,
+        -gsCos60s-gsSin60c,  -gsTan30c,   gsCos60s-gsSin60c,
+    };
+
+    for (Int_t i=0; i<6; i++)
+    {
+        // FIXME: Do not rotate fX/fY.
+        //        Instead implement MGeomCam::Rotate or similar.
+        x[i] += fx;
+        y[i] += fy;
+    }
+
+    x[6] = x[0];
+    y[6] = y[0];
+
+    //
+    //   paint the pixel
+    //
+    if (fill.GetFillColor())
+        gPad->PaintFillArea(6, x, y);
+
+    if (line.GetLineStyle())
+        gPad->PaintPolyLine(7, x, y);
+}
+
+// ------------------------------------------------------------------------
+//
+// 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
+{
+
+    //const Double_t disthex = 999999;//TMath::Sqrt(dx*dx + dy*dy);
+
+    const Double_t dh = fD/2;
+
+    //
+    //  compute the distance of the Point to the center of the Hexagon
+    //
+    const Double_t dx = px-fX;
+    const Double_t dy = py-fY;
+
+    // FIXME: Derotate
+
+    // DX = dx*cos(-phi) - dy*sin(-phi)
+    // DY = dx*sin(-phi) + dy*cos(-phi)
+
+    const Double_t x =  dx*fCosPhi + dy*fSinPhi;
+
+    if (TMath::Abs(x) > dh)
+        return kFALSE; // return disthex
+
+    const Double_t y = -dx*fSinPhi + dy*fCosPhi;
+
+    const Double_t xc = x*gsCos60;  // 1/2
+    const Double_t ys = y*gsSin60;  // sqrt(3)/2
+
+    //
+    // 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(xc + ys) > dh)
+        return kFALSE; // return disthex
+
+    if  (TMath::Abs(xc - ys) > dh)
+        return kFALSE; // return disthex
+
+    return kTRUE; // return -1
+
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate in the direction 0-5 (kind of sector) in the ring-th ring
+// the x and y coordinate of the i-th pixel. The unitx are unity,
+// distance to (0,0) is retruned.
+//
+Double_t MGeomPix::CalcXY(Int_t dir, Int_t ring, Int_t i, Double_t &x, Double_t &y)
+{
+    switch (dir)
+    {
+    case kDirCenter: // Center
+        x = 0;
+        y = 0;
+        break;
+
+    case kDirNE: // Direction North East
+        x = ring-i*0.5;
+        y = i*gsSin60;
+        break;
+
+    case kDirN: // Direction North
+        x = ring*0.5-i;
+        y = ring*gsSin60;
+        break;
+
+    case kDirNW: // Direction North West
+        x = -(ring+i)*0.5;
+        y = (ring-i)*gsSin60;
+        break;
+
+    case kDirSW: // Direction South West
+         x = 0.5*i-ring;
+         y = -i*gsSin60;
+         break;
+
+    case kDirS: // Direction South
+         x = i-ring*0.5;
+         y = -ring*gsSin60;
+         break;
+
+    case kDirSE: // Direction South East
+        x = (ring+i)*0.5;
+        y = (-ring+i)*gsSin60;
+        break;
+    }
+    return x*x + y*y;
+}
+
+// ==============================================================================
+/*
+#include <TOrdCollection.h>
+#include "MMath.h" 
+#include "../mgui/MHexagon.h" // MHexagon::fgDx
+
+// ------------------------------------------------------------------------
+//
+// Small helper class to allow fast sorting of TVector2 by angle
+//
+class HVector2 : public TVector2
+{
+    Double_t fAngle;
+public:
+    HVector2() : TVector2()  { }
+    HVector2(const TVector2 &v) : TVector2(v)  { }
+    HVector2(Double_t x, Double_t y) : TVector2 (x, y) { }
+    void CalcAngle() { fAngle = Phi(); }
+    Bool_t IsSortable() const { return kTRUE; }
+    Int_t Compare(const TObject *obj) const { return ((HVector2*)obj)->fAngle>fAngle ? 1 : -1; }
+    Double_t GetAngle() const { return fAngle; }
+};
+
+// ------------------------------------------------------------------------
+//
+// Calculate the edge points of the intersection area of two hexagons.
+// The points are added as TVector2 to the TOrdCollection.
+// The user is responsible of delete the objects.
+//
+void MGeomPix::GetIntersectionBorder(TOrdCollection &col, const MGeomPix &hex) const
+{
+//    if (fPhi!=0)
+//    {
+//        gLog << warn << "MGeomPix::GetIntersectionBorder: Only phi=0 supported yet." << endl;
+//        return;
+//    }
+
+    Bool_t inside0[6], inside1[6];
+
+    HVector2 v0[6];
+    HVector2 v1[6];
+
+    Int_t cnt0=0;
+    Int_t cnt1=0;
+
+    // Calculate teh edges of each hexagon and whether this edge
+    // is inside the other hexgon or not
+    for (int i=0; i<6; i++)
+    {
+        const Double_t x0 = fX+MHexagon::fgDx[i]*fD;
+        const Double_t y0 = fY+MHexagon::fgDy[i]*fD;
+
+        const Double_t x1 = hex.fX+MHexagon::fgDx[i]*hex.fD;
+        const Double_t y1 = hex.fY+MHexagon::fgDy[i]*hex.fD;
+
+        v0[i].Set(x0, y0);
+        v1[i].Set(x1, y1);
+
+        inside0[i] = hex.DistanceToPrimitive(x0, y0) < 0;
+        inside1[i] = DistanceToPrimitive(x1, y1)     < 0;
+
+        if (inside0[i])
+        {
+            col.Add(new HVector2(v0[i]));
+            cnt0++;
+        }
+        if (inside1[i])
+        {
+            col.Add(new HVector2(v1[i]));
+            cnt1++;
+        }
+    }
+
+    if (cnt0==0 || cnt1==0)
+        return;
+
+    // No calculate which vorder lines intersect
+    Bool_t iscross0[6], iscross1[6];
+    for (int i=0; i<6; i++)
+    {
+        iscross0[i] = (inside0[i] && !inside0[(i+1)%6]) || (!inside0[i] && inside0[(i+1)%6]);
+        iscross1[i] = (inside1[i] && !inside1[(i+1)%6]) || (!inside1[i] && inside1[(i+1)%6]);
+    }
+
+    // Calculate the border points of our intersection area
+    for (int i=0; i<6; i++)
+    {
+        // Skip non intersecting lines
+        if (!iscross0[i])
+            continue;
+
+        for (int j=0; j<6; j++)
+        {
+            // Skip non intersecting lines
+            if (!iscross1[j])
+                continue;
+
+            const TVector2 p = MMath::GetIntersectionPoint(v0[i], v0[(i+1)%6], v1[j], v1[(j+1)%6]);
+            if (hex.DistanceToPrimitive(p.X(), p.Y())<1e-9)
+                col.Add(new HVector2(p));
+        }
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Calculate the overlapping area of the two hexagons.
+//
+Double_t MGeomPix::CalcOverlapArea(const MGeomPix &cam) const
+{
+//    if (fPhi!=0)
+//    {
+//        gLog << warn << "MGeomPix::CalcOverlapArea: Only phi=0 supported yet." << endl;
+//        return -1;
+//    }
+
+    TOrdCollection col;
+    col.SetOwner();
+
+    GetIntersectionBorder(col, cam);
+
+    // Check if there is an intersection to proceed with
+    const Int_t n = col.GetEntries();
+    if (n==0)
+        return 0;
+
+    // Calculate the center of gravity
+    TVector2 cog;
+
+    TIter Next(&col);
+    HVector2 *v=0;
+    while ((v=(HVector2*)Next()))
+        cog += *v;
+    cog /= n;
+
+    // Shift the figure to its center-og-gravity and
+    // calculate the angle of the connection line between the
+    // border points of our intersesction area and its cog
+    Next.Reset();
+    while ((v=(HVector2*)Next()))
+    {
+        *v -= cog;
+        v->CalcAngle();
+    }
+
+    // Sort these points by this angle
+    col.Sort();
+
+    // Now sum up the area of all the triangles between two
+    // following points and the cog.
+    Double_t A = 0;
+    for (int i=0; i<n; i++)
+    {
+        // Vectors from cog to two nearby border points
+        const HVector2 *v1 = (HVector2*)col.At(i);
+        const HVector2 *v2 = (HVector2*)col.At((i+1)%n);
+
+        // Angle between both vectors
+        const Double_t a = fmod(v1->GetAngle()-v2->GetAngle()+TMath::TwoPi(), TMath::TwoPi());
+
+        // Length of both vectors
+        const Double_t d1 = v1->Mod();
+        const Double_t d2 = v2->Mod();
+
+        A += d1*d2/2*sin(a);
+    }
+    return A;
+}
+*/
Index: branches/Mars_McMismatchStudy/mgeom/MGeomPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomPix.h	(revision 17960)
@@ -0,0 +1,67 @@
+#ifndef MARS_MGeomPix
+#define MARS_MGeomPix
+
+#ifndef MARS_MGeom
+#include "MGeom.h"
+#endif
+
+class MGeomPix : public MGeom
+{ 
+public:
+    static const Float_t gsTan60; // tan(60/kRad2Deg);
+    static const Float_t gsTan30; // tan(30/kRad2Deg);
+
+    static const Float_t gsCos60; // cos(60/kRad2Deg);
+    static const Float_t gsSin60; // sin(30/kRad2Deg);
+
+private:
+    Float_t fD;            // [mm]   the d coordinate of the pixel (dist between two parallel sides)
+
+    Double_t fCosPhi;
+    Double_t fSinPhi;
+
+    // Store fD*fCosPhi  ???
+    // Store fD*fSinPhi  ???
+    // Store array and check if initialized before needed?
+
+public:
+    // Helper to calculate hexagonal geometry
+    enum { kDirCenter, kDirNE, kDirN, kDirNW, kDirSW, kDirS, kDirSE };
+
+    static Double_t CalcXY(Int_t dir, Int_t ring, Int_t i, Double_t &x, Double_t &y);
+
+    // MGeomPix
+    MGeomPix(Float_t x=0, Float_t y=0, Float_t d=1, UInt_t s=0, UInt_t aidx=0);
+
+    // TObject
+    void Copy(TObject &obj) const
+    {
+        MGeomPix &pix = (MGeomPix&)obj;
+
+        pix.fD = fD;
+
+        MGeom::Copy(obj);
+        TObject::Copy(obj);
+    }
+
+    void Print(Option_t *opt=NULL) const;
+
+    // Setter
+    void SetD(Float_t d=1) { fD=d; fA=d*d*gsSin60; }
+    void SetPhi(Double_t phi=0);
+
+    Float_t GetD() const  { return fD; }         // Distance between two parallel sides
+    Float_t GetL() const  { return fD*gsTan30; } // Length of one of the parallel sides
+    Float_t GetT() const  { return fD/gsTan60; } // Half distance between two opposite edges (traverse)
+
+    Float_t GetDx() const { return fD; }         // Distance of two rows in x-direction (without rotation)
+    Float_t GetDy() const { return fD*gsSin60; } // Distance of two rows in y-direction (without rotation)
+
+    // Helper
+    Bool_t  IsInside(Float_t px, Float_t py) const;
+    void    PaintPrimitive(const TAttLine &line, const TAttFill &fill, Double_t scalexy=1, Double_t scaled=1) const;
+
+    ClassDef(MGeomPix, 5) // Geometry class describing the geometry of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/MGeomRectangle.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomRectangle.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomRectangle.cc	(revision 17960)
@@ -0,0 +1,123 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MGeomRectangle
+//
+// This container describes the geometry of a rectangualr shaped pixel
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomRectangle.h"
+
+#include <TBox.h>
+#include <TMath.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MGeomRectangle);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes one pixel
+//
+MGeomRectangle::MGeomRectangle(Float_t x, Float_t y, Float_t w, Float_t h, UInt_t s, UInt_t a)
+    : MGeom(x, y, s, a)
+{
+    //  default constructor
+    SetSize(w, h<0 ? w : h);
+    SetNeighbors();
+}
+
+// ------------------------------------------------------------------------
+//
+// compute the distance of a point (px,py) to the Hexagon center in
+// MGeomPix coordinates. Return kTRUE if inside.
+//
+Bool_t MGeomRectangle::IsInside(Float_t px, Float_t py) const
+{
+    if (TMath::Abs(px-fX)>fW/2)
+        return kFALSE;
+
+    if (TMath::Abs(py-fY)>fH/2)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Implementation of PaintPrimitive drwaing a rectangular pixel
+//
+void MGeomRectangle::PaintPrimitive(const TAttLine &line, const TAttFill &fill, Double_t scalexy, Double_t scaled) const
+{
+    const Double_t w = fW*scaled/2;
+    const Double_t h = fH*scaled/2;
+    const Double_t x = fX*scalexy;
+    const Double_t y = fY*scalexy;
+
+    const_cast<TAttLine&>(line).Modify();  //Change line attributes only if necessary
+    const_cast<TAttFill&>(fill).Modify();  //Change fill area attributes only if necessary
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,18,00)
+    if (fill.GetFillColor())
+        gPad->PaintBox(x-w, y-h, x+w, y+h);
+    if (line.GetLineStyle())
+        gPad->PaintBox(x-w, y-h, x+w, y+h, "s");
+#else
+    gPad->PaintBox(x-w, y-h, x+w, y+h, "l");
+#endif
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the distance from the center to one of the two opposite edges.
+//
+Float_t MGeomRectangle::GetT() const
+{
+    return TMath::Hypot(fW, fH)/2;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the average length of the sides
+//
+Float_t MGeomRectangle::GetL() const
+{
+    return (fW+fH)/2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the geometry information of one pixel.
+//
+void MGeomRectangle::Print(Option_t *opt) const
+{
+    MGeom::Print(opt);
+    gLog << " w=" << fW << "mm h=" << fH << "mm" << endl;
+}
Index: branches/Mars_McMismatchStudy/mgeom/MGeomRectangle.h
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/MGeomRectangle.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/MGeomRectangle.h	(revision 17960)
@@ -0,0 +1,43 @@
+#ifndef MARS_MGeomRectangle
+#define MARS_MGeomRectangle
+
+#ifndef MARS_MGeom
+#include "MGeom.h"
+#endif
+
+class MGeomRectangle : public MGeom
+{
+private:
+    Float_t fW;
+    Float_t fH;
+
+public:
+    MGeomRectangle(Float_t x=0, Float_t y=0, Float_t w=1, Float_t h=-1, UInt_t s=0, UInt_t aidx=0);
+
+    void Copy(TObject &obj) const
+    {
+        MGeomRectangle &pix = (MGeomRectangle&)obj;
+
+        pix.fW = fW;
+        pix.fH = fH;
+
+        MGeom::Copy(obj);
+        TObject::Copy(obj);
+    }
+
+    void    SetSize(Float_t w, Float_t h=-1) { fW=w; fH=h<0?fW:h; fA=fW*fH; }
+
+    Float_t GetW() const { return fW; }
+    Float_t GetH() const { return fH; }
+    Float_t GetT() const;
+    Float_t GetL() const;
+
+    Bool_t  IsInside(Float_t px, Float_t py) const;
+    void    PaintPrimitive(const TAttLine &line, const TAttFill &fill, Double_t scalexy=1, Double_t scaled=1) const;
+
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MGeomRectangle, 1) // Geometry class describing the rectangular geometry of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mgeom/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mgeom/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgeom/Makefile	(revision 17960)
@@ -0,0 +1,51 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Geom
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../MBase
+
+SRCFILES = MGeom.cc \
+           MGeomPix.cc \
+           MGeomRectangle.cc \
+           MGeomCam.cc \
+           MGeomCamCT1.cc \
+           MGeomCamDwarf.cc \
+           MGeomCamFact.cc \
+           MGeomCamFACT.cc \
+           MGeomCamMagic.cc \
+           MGeomCamSquare.cc \
+           MGeomCorsikaCT.cc \
+	   MGeomMirror.cc \
+	   MGeomPMT.cc
+
+
+#           MGeomCamCT1Daniel  \
+#           MGeomCamMagicHG    \
+#           MGeomCamMagic919   \
+#           MGeomCamMagic1183  \
+#           MGeomCamECO1000    \
+#           MGeomCamECO1000HG  \
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mgui/GuiIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mgui/GuiIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgui/GuiIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mgui/GuiLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mgui/GuiLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgui/GuiLinkDef.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mgui/MCamEvent.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgui/MCamEvent.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgui/MCamEvent.cc	(revision 17960)
@@ -0,0 +1,131 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MCamEvent
+//
+// A base class describing an event in the camera.
+//
+// If GetPixelContent returns kFALSE, it must not touch 'val'.
+//
+// You can derive a class in addition to TObject from MCamEvent, too.
+//
+// MCamEvent MUST be after TObject:
+//  ALLOWED:   class MyClass : public TObject, public MCamEvent
+//  FORBIDDEN: class MyClass : public MCamEvent, public TObject
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCamEvent.h"
+
+#include <TMath.h>
+
+#include "MGeomCam.h"
+#include "MArrayD.h"
+
+ClassImp(MCamEvent);
+
+// --------------------------------------------------------------------------
+//
+// You can overwrite this function if you want the container to be
+// initialized by MGeomApply with the geometry. If it is not overloaded
+// it calls InitSize with the corresponding pixel number. If this information
+// is enough for you it is enough to overload InitSize.
+//
+void MCamEvent::Init(const MGeomCam &geom)
+{
+    InitSize(geom.GetNumPixels());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the median of all corresponding GetPixelContent
+//
+Double_t MCamEvent::GetCameraMedian(const MGeomCam &cam, Int_t type) const
+{
+    Int_t num = 0;
+
+    MArrayD arr(cam.GetNumPixels());
+    for (unsigned int i=0; i<cam.GetNumPixels(); i++)
+    {
+        Double_t val;
+        if (!GetPixelContent(val, i, cam, type))
+            continue;
+
+        arr[num++] = val;
+    }
+
+    return TMath::Median(num, arr.GetArray());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the mean of all corresponding GetPixelContent
+//
+Double_t MCamEvent::GetCameraMean(const MGeomCam &cam, Int_t type) const
+{
+    return GetCameraStat(cam, type)[0];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the rms of all corresponding GetPixelContent
+//
+Double_t MCamEvent::GetCameraRMS(const MGeomCam &cam, Int_t type) const
+{
+    return GetCameraStat(cam, type)[1];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the rms of all corresponding GetPixelContent
+//
+TArrayD MCamEvent::GetCameraStat(const MGeomCam &cam, Int_t type) const
+{
+    Int_t    num = 0;
+    Double_t sum = 0;
+    Double_t sq  = 0;
+
+    for (unsigned int i=0; i<cam.GetNumPixels(); i++)
+    {
+        Double_t val;
+        if (!GetPixelContent(val, i, cam, type))
+            continue;
+
+        sum += val;
+        sq  += val;
+        num ++;
+    }
+
+    if (num==0)
+        return 0;
+
+    sum /= num;
+    sq  /= num;
+
+    TArrayD stat(2);
+    stat[0] = sum;
+    stat[1] = TMath::Sqrt(sq-sum*sum);
+    return stat;
+}
Index: branches/Mars_McMismatchStudy/mgui/MCamEvent.h
===================================================================
--- branches/Mars_McMismatchStudy/mgui/MCamEvent.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgui/MCamEvent.h	(revision 17960)
@@ -0,0 +1,30 @@
+#ifndef MARS_MCamEvent
+#define MARS_MCamEvent
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MGeomCam;
+
+class MCamEvent
+{
+public:
+    virtual ~MCamEvent() { }
+
+    virtual Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const = 0;
+    virtual void   DrawPixelContent(Int_t num) const = 0;
+
+    virtual void   Init(const MGeomCam &geom);
+    virtual void   InitSize(const UInt_t) { } // Used by MGeomApply see Init()
+
+    virtual Double_t GetCameraMean(const MGeomCam &cam, Int_t type=0) const;
+    virtual Double_t GetCameraMedian(const MGeomCam &cam, Int_t type=0) const;
+    virtual Double_t GetCameraRMS(const MGeomCam &cam, Int_t type=0) const;
+    virtual TArrayD  GetCameraStat(const MGeomCam &cam, Int_t type=0) const;
+
+    ClassDef(MCamEvent, 0) // A camera event
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mgui/MHexagon.cc
===================================================================
--- branches/Mars_McMismatchStudy/mgui/MHexagon.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgui/MHexagon.cc	(revision 17960)
@@ -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  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHexagon
+//
+// Class Version 2:
+//  - added fPhi
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHexagon.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TVector2.h>       // TVector2
+#include <TVirtualPad.h>    // gPad
+#include <TOrdCollection.h> // TOrdCollection
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMath.h"
+
+ClassImp(MHexagon);
+
+using namespace std;
+
+const Double_t MHexagon::fgCos60 = 0.5;        // TMath::Cos(60/TMath::RadToDeg());
+const Double_t MHexagon::fgSin60 = sqrt(3.)/2; // TMath::Sin(60/TMath::RadToDeg());
+
+const Double_t MHexagon::fgDx[6] = { fgCos60,   0.,          -fgCos60,  -fgCos60,   0.,            fgCos60 };
+const Double_t MHexagon::fgDy[6] = { fgSin60/3, fgSin60*2/3, fgSin60/3, -fgSin60/3, -fgSin60*2/3, -fgSin60/3 };
+
+// ------------------------------------------------------------------------
+//
+//   default constructor for MHexagon
+//
+MHexagon::MHexagon()
+{
+}
+
+// ------------------------------------------------------------------------
+//
+//    normal constructor for MHexagon
+//
+MHexagon::MHexagon(Float_t x, Float_t y, Float_t d, Float_t phi)
+: TAttLine(1, 1, 1), TAttFill(0, 1001), fX(x), fY(y), fD(d), fPhi(phi)
+{
+}
+
+// ------------------------------------------------------------------------
+//
+//    copy constructor for MHexagon
+//
+MHexagon::MHexagon(const MHexagon &hexagon) : TObject(hexagon), TAttLine(hexagon), TAttFill(hexagon)
+{
+    fX   = hexagon.fX;
+    fY   = hexagon.fY;
+    fD   = hexagon.fD;
+    fPhi = hexagon.fPhi;
+} 
+
+// ------------------------------------------------------------------------
+//
+//     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;
+    hex.fPhi = fPhi;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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)
+{
+    //FIXME: Rotation phi missing!
+
+    //
+    //  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);
+
+    TVector2 v(TMath::Abs(px-pxhex), TMath::Abs(py-pyhex));
+    // FIXME: fPhi or -fPhi?
+    v = v.Rotate(-fPhi);             // FIXME: Replace with a precalculates sin/cos vector
+
+    const Double_t x = TMath::Abs(v.X());
+    const Double_t y = TMath::Abs(v.Y());
+
+    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) const
+{
+    //FIXME: Rotation phi missing!
+
+    //
+    //  compute the distance of the Point to the center of the Hexagon
+    //
+    //const Double_t dx = px-fX;
+    //const Double_t dy = py-fY;
+
+    TVector2 v(px-fX, py-fY);
+    // FIXME: fPhi or -fPhi?
+    v = v.Rotate(-fPhi);             // FIXME: Replace with a precalculates sin/cos vector
+
+    const Double_t dx = v.X();
+    const Double_t dy = v.Y();
+
+    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 Double_t dx2 = dx*fgCos60 + dy*fgSin60;
+
+    if  (TMath::Abs(dx2) > fD/2.)
+      return disthex;
+
+    const Double_t dx3 = dx*fgCos60 - dy*fgSin60;
+
+    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, Float_t phi)
+{ 
+    MHexagon *newhexagon = new MHexagon(x, y, d, phi);
+
+    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, fPhi);
+}
+
+// ------------------------------------------------------------------------
+//
+//  draw this hexagon with the coordinates
+//
+void MHexagon::PaintHexagon(Float_t inX, Float_t inY, Float_t inD, Float_t phi)
+{ 
+    //
+    //  calculate the positions of the pixel corners
+    //
+    Double_t x[7], y[7];
+    for (Int_t i=0; i<7; i++)
+    {
+        TVector2 v(fgDx[i%6], fgDy[i%6]);
+
+        v = v.Rotate(phi); // FIXME: Replace with a precalculates sin/cos vector
+
+        x[i] = inX + v.X()*inD;
+        y[i] = inY + v.Y()*inD;
+    }
+
+    TAttLine::Modify();    // Change line attributes only if neccessary
+    TAttFill::Modify();    // Change fill attributes only if neccessary
+
+    //
+    //   paint the pixel
+    //
+    if (GetFillColor())
+        gPad->PaintFillArea(6, x, y);
+
+    if (GetLineStyle())
+        gPad->PaintPolyLine(7, 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 phi=" << TMath::RadToDeg() << "deg" << 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(ostream &out, Option_t *)
+{
+#if ROOT_VERSION_CODE >= ROOT_VERSION(5,12,00)
+    if (gROOT->ClassSaved(Class()))
+       out << "   ";
+    else
+       out << "   MHexagon *";
+
+    out << "hexagon = new MHexagon(" << fX << "," << fY << "," << fD << "," << fPhi << ");" << endl;
+
+    SaveFillAttributes(out, "hexagon");
+    SaveLineAttributes(out, "hexagon");
+
+    out << "   hexagon->Draw();" << endl;
+#endif
+}
+
+void MHexagon::SavePrimitive(ofstream &out, Option_t *)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    if (gROOT->ClassSaved(Class()))
+       out << "   ";
+    else
+       out << "   MHexagon *";
+
+    out << "hexagon = new MHexagon(" << fX << "," << fY << "," << fD << "," << fPhi << ");" << endl;
+
+    SaveFillAttributes(out, "hexagon");
+    SaveLineAttributes(out, "hexagon");
+
+    out << "   hexagon->Draw();" << endl;
+#else
+    MHexagon::SavePrimitive(static_cast<ostream&>(out), "");
+#endif
+}
Index: branches/Mars_McMismatchStudy/mgui/MHexagon.h
===================================================================
--- branches/Mars_McMismatchStudy/mgui/MHexagon.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgui/MHexagon.h	(revision 17960)
@@ -0,0 +1,86 @@
+#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 TOrdCollection;
+
+class MHexagon : public TObject, public TAttLine, public TAttFill
+{
+private:
+    static const Double_t fgCos60;
+    static const Double_t fgSin60;
+
+public:
+    static const Double_t fgDx[6];   // X coordinate of the six edges
+    static const Double_t fgDy[6];   // Y coordinate of the six edges
+
+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
+
+    Float_t fPhi; // Rotation angle
+
+public:
+
+    MHexagon();
+    MHexagon(Float_t x, Float_t y, Float_t d, Float_t phi=0);
+    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 void  DrawHexagon(Float_t x, Float_t y, Float_t d, Float_t phi=0);
+
+    //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, Float_t phi=0);
+    virtual void  Print(Option_t *Option="") const; // *MENU*
+    virtual void  SavePrimitive(std::ostream &out, Option_t *);
+    virtual void  SavePrimitive(std::ofstream &out, Option_t *);
+
+    Float_t GetX() const { return fX; }
+    Float_t GetY() const { return fY; }
+    Float_t GetD() const { return fD; }
+    Float_t GetPhi() const { return fPhi; }
+
+    ClassDef(MHexagon, 2)    // A hexagon for MAGIC
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mgui/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mgui/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mgui/Makefile	(revision 17960)
@@ -0,0 +1,32 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Gui
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgeom
+
+SRCFILES = MHexagon.cc \
+	   MCamEvent.cc
+           
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mhbase/HBaseIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/HBaseIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/HBaseIncl.h	(revision 17960)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mhbase/HBaseLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/HBaseLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/HBaseLinkDef.h	(revision 17960)
@@ -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 MHn+;
+#pragma link C++ class MHArray+;
+#pragma link C++ class MHMatrix+;
+
+#pragma link C++ class MBinning+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mhbase/MBinning.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MBinning.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MBinning.cc	(revision 17960)
@@ -0,0 +1,687 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MBinning
+//
+// This is a MParCOntainer storing a binning for a histogram. Doing this
+// you are able to distribute a single binning to several histograms
+// in your parameter list.
+//
+// In some classes the title of the container is used to set the
+// axis-title of the corresponding axis in your histogram.
+//
+// For all the features supported see the function descriptions in
+//  MBinning and MH
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MBinning.h"
+
+#include <ctype.h>      // tolower
+#include <fstream>
+
+#include <TH1.h>        // InheritsFrom
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MH.h"
+
+ClassImp(MBinning);
+
+using namespace std;
+
+const TString MBinning::gsDefName  = "MBinning";
+const TString MBinning::gsDefTitle = "Container describing the binning of an axis";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title only. Typically you won't
+// need to change this.
+//
+MBinning::MBinning(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetEdges(10, 0, 1);
+    fType = kIsDefault;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy Constructor. If necessary give also name and title.
+//
+MBinning::MBinning(const MBinning &bins, const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetEdges(bins);
+}
+
+// --------------------------------------------------------------------------
+//
+// Instantiate MBinning with nbins number of bins between lo (lower edge)
+// and hi (upper edge), name name and title title.
+//
+MBinning::MBinning(Int_t nbins, Axis_t lo, Axis_t hi, const char *name, const char *opt, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetEdges(nbins, lo, hi, opt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize Binning from an axis of a TH1. If no title given,
+// a title combined from the axis titles and the TH1 title is
+// used.
+//
+MBinning::MBinning(const TH1 &h, const Char_t axis, const char *name, const char *title)
+{
+    fName  = name  ? name : gsDefName.Data();
+    fTitle = title ? Form("%s;%s;%s;%s", h.GetTitle(),
+                          h.GetXaxis()->GetTitle(),
+                          h.GetYaxis()->GetTitle(),
+                          h.GetZaxis()->GetTitle()) : gsDefTitle.Data();
+
+    SetEdges(h, axis);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize Binning from TAxis.
+//
+MBinning::MBinning(const TAxis &axis, const char *name, const char *title)
+{
+    fName  = name  ? name : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetEdges(axis);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize Binning from TArrayD.
+//
+MBinning::MBinning(const TArrayD &axis, const char *name, const char *title)
+{
+    fName  = name  ? name : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetEdges(axis);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search in the parameter list for the binning with name "name". If found,
+// set the edges and title accordingly. Default is name of object.
+// return kTRUE if object found, kFALSE otherwise.
+//
+Bool_t MBinning::SetEdges(const MParList &list, const char *name)
+{
+    MBinning *bins = (MBinning*)list.FindObject(name ? name : fName.Data(), "MBinning");
+    if (!bins)
+        return kFALSE;
+
+    SetEdges(*bins);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the edges stored in MBinning from the TAxis axe
+//
+void MBinning::SetEdges(const TAxis &axe)
+{
+    const TArrayD &arr = *axe.GetXbins();
+    if (arr.GetSize()>0)
+    {
+        SetEdges(arr);
+        return;
+    }
+
+    SetEdges(axe.GetNbins(), axe.GetXmin(), axe.GetXmax());
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new upper edge to the edges stored in MBinning. The new upper
+// edge must be greater than the current greatest. Using this you can
+// enhance a histogram bin-by-bin, eg:
+//   TH1F h("", "", 2, 0, 1);
+//   MBinning b;
+//   b.SetEdges(h);
+//   b.AddEdge(2);
+//   b.Apply(h);
+//   b.AddEdge(3);
+//   b.Apply(h);
+//   [...]
+//
+void MBinning::AddEdge(Axis_t up)
+{
+    const UInt_t n = fEdges.GetSize();
+
+    if (up<=fEdges[n-1])
+    {
+        *fLog << warn << dbginf << "WARNING - New upper edge not greater than old upper edge... ignored." << endl;
+        return;
+    }
+
+    fEdges.Set(n+1);
+    fEdges[n] = up;
+
+    fType = kIsUserArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Removes the first edge
+//
+void MBinning::RemoveFirstEdge()
+{
+    const Int_t n = fEdges.GetSize();
+    for (int i=0; i<n-1; i++)
+        fEdges[i] = fEdges[i+1];
+    fEdges.Set(n-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Removes the last edge
+//
+void MBinning::RemoveLastEdge()
+{
+    fEdges.Set(fEdges.GetSize()-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the edges in MBinning from a histogram-axis. Which axis is
+// specified by axis ('x', 'y', 'z')
+//
+void MBinning::SetEdges(const TH1 &h, const Char_t axis)
+{
+    switch (tolower(axis))
+    {
+    case 'x':
+        SetEdges(*h.GetXaxis());
+        return;
+    case 'y':
+        SetEdges(*h.GetYaxis());
+        return;
+    case 'z':
+        SetEdges(*h.GetZaxis());
+        return;
+    default:
+        *fLog << warn << "MBinning::SetEdges: Axis '" << axis << "' unknown... using x." << endl;
+        SetEdges(*h.GetXaxis());
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the number of bins <nbins> (not the number of edges), the
+// lowest <lo> and highest <up> Edge (of your histogram)
+//
+void MBinning::SetEdgesLin(Int_t nbins, Axis_t lo, Axis_t up)
+{
+    if (nbins<=0)
+    {
+        *fLog << warn << "WARNING - Number of bins cannot be <= 0... reset to 1." << endl;
+        nbins = 1;
+    }
+
+    if (up<lo)
+    {
+        *fLog << warn << "WARNING - Upper edge must be greater than lower edge... exchanging." << endl;
+
+        const Axis_t dummy(lo);
+        lo = up;
+        up = dummy;
+    }
+
+    const Double_t binsize = nbins<=0 ? 0 : (up-lo)/nbins;
+    fEdges.Set(nbins+1);
+    for (int i=0; i<=nbins; i++)
+        fEdges[i] = binsize*i + lo;
+
+    fType = kIsLinear;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set edged from text. With the following structure:
+//
+//     n lo hi [type [title]]
+//
+//  n:  number of bins
+//  lo: lowest edge
+//  hi: highest edge
+//  type: "lin" <default>, "log", "cos", "asin" (without quotationmarks)
+//  title: Whatever the title might be
+//
+// For example:
+//   SetEdgesRaw("12 0 1 lin This is the title");
+//
+Bool_t MBinning::SetEdgesRaw(const char *txt)
+{
+    Int_t   nbins  = 0;
+    Float_t loedge = 0;
+    Float_t upedge = 0;
+    Int_t   len    = 0;
+    if (3!=sscanf(txt, " %d %f %f %n", &nbins, &loedge, &upedge, &len))
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Not enough arguments... ignored." << endl;
+        return kFALSE;
+    }
+
+    if (loedge>=upedge)
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Lowest edge >= highest edge... ignored." << endl;
+        return kFALSE;
+    }
+
+    TString str(txt);
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    TString typ(str);
+    Ssiz_t pos = str.First(' ');
+    if (pos>=0)
+    {
+        typ = str(0, pos);
+        str.Remove(0, pos);
+        str = str.Strip(TString::kBoth);
+        if (typ!=(TString)"lin" && typ!=(TString)"log" && typ!=(TString)"cos" && typ!=(TString)"asin")
+        {
+            *fLog << warn << GetDescriptor() << "::SetEdges: Type " << typ << " unknown... ignored." << endl;
+            return kFALSE;
+        }
+    }
+
+    SetEdges(nbins, loedge, upedge, typ.Data());
+
+    if (!str.IsNull())
+        fTitle = str;
+
+    return kTRUE;
+}
+/*
+// --------------------------------------------------------------------------
+//
+// Set edged from text. With the following structure:
+//
+//     n= lo= hi= type= title="my title"
+//
+//  n:  number of bins
+//  lo: lowest edge
+//  hi: highest edge
+//  type: "lin" <default>, "log", "cos" (without quotationmarks)
+//  title: Whatever the title might be
+//
+// For example:
+//   SetEdgesRaw("12 0 1 lin This is the title");
+//
+Bool_t MBinning::SetEdgesRaw(const char *txt)
+{
+    Int_t   nbins  = 0;
+    Float_t loedge = 0;
+    Float_t upedge = 0;
+    Int_t   len    = 0;
+    if (3!=sscanf(txt, " %d %f %f %n", &nbins, &loedge, &upedge, &len))
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Not enough arguments... ignored." << endl;
+        return kFALSE;
+    }
+
+    if (loedge>=upedge)
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Lowest edge >= highest edge... ignored." << endl;
+        return kFALSE;
+    }
+
+    TString str(txt);
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    TString typ;
+    Ssiz_t pos = str.First(' ');
+    if (pos>=0)
+    {
+        typ = str(0, pos);
+        if (typ!=(TString)"lin" && typ!=(TString)"log" && typ!=(TString)"cos")
+        {
+            *fLog << warn << GetDescriptor() << "::SetEdges: Type " << typ << " unknown... ignored." << endl;
+            return kFALSE;
+        }
+    }
+
+    SetEdges(nbins, loedge, upedge, typ.Data());
+
+    str = str.Strip(TString::kBoth);
+
+    if (!str.IsNull())
+        fTitle = str;
+
+    return kTRUE;
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Calls SetEdgesLog if opt contains "log"
+// Calls SetEdgesCos if opt contains "cos"
+// Calls SetEdges in all other cases
+//
+void MBinning::SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up, const char *opt)
+{
+    const TString o(opt);
+    if (o.Contains("log", TString::kIgnoreCase))
+    {
+        SetEdgesLog(nbins, lo, up);
+        return;
+    }
+    if (o.Contains("asin", TString::kIgnoreCase))
+    {
+        SetEdgesASin(nbins, lo, up);
+        return;
+    }
+    if (o.Contains("cos", TString::kIgnoreCase))
+    {
+        SetEdgesCos(nbins, lo, up);
+        return;
+    }
+    SetEdges(nbins, lo, up);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the number of bins <nbins> (not the number of edges), the
+// lowest <lo> and highest <up> Edge (of your histogram)
+//
+void MBinning::SetEdgesLog(Int_t nbins, Axis_t lo, Axis_t up)
+{
+    // if (lo==0) ...
+    if (nbins<=0)
+    {
+        *fLog << warn << "WARNING - Number of bins cannot be <= 0... reset to 1." << endl;
+        nbins = 1;
+    }
+
+    if (up<lo)
+    {
+        *fLog << warn << "WARNING - Upper edge must be greater than lower edge... exchanging." << endl;
+
+        const Axis_t dummy(lo);
+        lo = up;
+        up = dummy;
+    }
+
+    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(Int_t nbins, Axis_t lo, Axis_t up)
+{
+    if (nbins<=0)
+    {
+        *fLog << warn << "WARNING - Number of bins cannot be <= 0... reset to 1." << endl;
+        nbins = 1;
+    }
+
+    if (up<lo)
+    {
+        *fLog << warn << "WARNING - Upper edge must be greater than lower edge... exchanging." << endl;
+
+        const Axis_t dummy(lo);
+        lo = up;
+        up = dummy;
+    }
+
+    // if (lo==0) ...
+    const Axis_t ld = lo/kRad2Deg;
+    const Axis_t ud = up/kRad2Deg;
+
+    const Double_t cld = ld<0 ? cos(ld)-1 : 1-cos(ld);
+    const Double_t cud = ud<0 ? cos(ud)-1 : 1-cos(ud);
+
+    SetEdgesASin(nbins, cld, cud);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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::SetEdgesASin(Int_t nbins, Axis_t lo, Axis_t up)
+{
+    if (nbins<=0)
+    {
+        *fLog << warn << "WARNING - Number of bins cannot be <= 0... reset to 1." << endl;
+        nbins = 1;
+    }
+
+    if (up<lo)
+    {
+        *fLog << warn << "WARNING - Upper edge must be greater than lower edge... exchanging." << endl;
+
+        const Axis_t dummy(lo);
+        lo = up;
+        up = dummy;
+    }
+
+    const Double_t binsize = nbins<=0 ? 0 : (up-lo)/nbins;
+    fEdges.Set(nbins+1);
+    for (int i=0; i<=nbins; i++)
+    {
+        const Double_t a = binsize*i + lo;
+        fEdges[i] = a<0 ? -acos(1+a)*kRad2Deg : acos(1-a)*kRad2Deg;
+    }
+
+    fType = kIsCosinic;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply this binning to the given histogram.
+// (By definition this works only for 1D-histograms. For 2D- and 3D-
+//  histograms use MH::SetBinning directly)
+//
+void MBinning::Apply(TH1 &h) const
+{
+    if (h.InheritsFrom("TH2") || h.InheritsFrom("TH3"))
+    {
+        *fLog << warn << "MBinning::Apply: '" << h.GetName() << "' is not a basic TH1 object... no binning applied." << endl;
+        return;
+    }
+
+    MH::SetBinning(h, *this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print binning.
+//
+void MBinning::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ": nbins=" << GetNumBins() << " [";
+    *fLog << GetEdgeLo() << ", " << GetEdgeHi() << "] <";
+    switch (fType)
+    {
+    case kIsDefault:     *fLog << "default"; break;
+    case kIsLinear:      *fLog << "linear"; break;
+    case kIsLogarithmic: *fLog << "logarithmic"; break;
+    case kIsCosinic:     *fLog << "consinic"; break;
+    case kIsUserArray:   *fLog << "user-array"; break;
+    }
+    *fLog << ">";
+
+    if (fTitle!=gsDefTitle)
+        *fLog << " title=" << fTitle;
+
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MBinning::StreamPrimitive(ostream &out) const
+{
+    out << "   MBinning " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl;
+
+    if (IsDefault())
+        return;
+
+    if (IsLinear() || IsLogarithmic() || IsCosinic())
+    {
+        out << "   " << GetUniqueName() << ".SetEdges";
+        if (IsLogarithmic())
+            out << "Log";
+        if (IsCosinic())
+            out << "Cos";
+        out << "(" << GetNumBins() << ", " << GetEdgeLo() << ", " << GetEdgeHi() << ");" << endl;
+        return;
+    }
+
+    out << "   {" << endl;
+    out << "      TArrayD dummy;" << endl;
+    for (int i=0; i<GetNumEdges(); i++)
+        out << "      dummy[" << i << "]=" << GetEdges()[i] << ";" << endl;
+    out << "      " << GetUniqueName() << ".SetEdges(dummy);" << endl;
+    out << "   }" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Allows reading a binning from resource files. The structure is as follows
+//
+Int_t MBinning::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    UInt_t  nbins  = GetNumBins();
+    Float_t edgelo = GetEdgeLo();
+    Float_t edgehi = GetEdgeHi();
+    TString type;
+    if (IsEnvDefined(env, prefix, "NumBins", print))
+    {
+        nbins = GetEnvValue(env, prefix, "NumBins", GetNumBins());
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "EdgeLo", print))
+    {
+        edgelo = GetEnvValue(env, prefix, "EdgeLo", GetEdgeLo());
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "EdgeHi", print))
+    {
+        edgehi = GetEnvValue(env, prefix, "EdgeHi", GetEdgeHi());
+        rc = kTRUE;
+    }
+    if (rc==kTRUE && (type==kIsUserArray || type==kIsDefault))
+        type = kIsLinear;
+
+    if (IsEnvDefined(env, prefix, "Type", print))
+    {
+        type = GetEnvValue(env, prefix, "Type", "lin");
+        if (type!=(TString)"lin" && type!=(TString)"log" && type!=(TString)"cos" && type!=(TString)"acos")
+        {
+            *fLog << warn << GetDescriptor() << "::ReadEnv - WARNING: Type is not lin, log nor cos... assuming lin." << endl;
+            type = "lin";
+        }
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Edges", print))
+    {
+        if (rc==kTRUE)
+            *fLog << warn << GetDescriptor() << "::ReadEnv - WARNING: 'Edges' found... ignoring any 'NumBins', 'EdgeLo' and 'EdgeHi'" << endl;
+
+        const TString etype = GetEnvValue(env, prefix, "Edges", "");
+        //type = kIsUserArray;
+        /* MISSING */
+        rc = kTRUE;
+        *fLog << err << " SORRY USER ARRAY NOT YET IMPLEMENTED" << endl;
+        return kERROR;
+    }
+
+    const Bool_t raw = IsEnvDefined(env, prefix, "Raw", print);
+    //const Bool_t fullbins    = IsEnvDefined(env, prefix, "Binning", print);
+    if (!raw && /*!fullbins &&*/ rc==kTRUE)
+        SetEdges(nbins, edgelo, edgehi, type.Data());
+
+    if (rc==kTRUE)
+        *fLog << warn << GetDescriptor() << "::ReadEnv - WARNING: 'Binning' found... ignoring any 'NumBins', 'EdgeLo', 'EdgeHi' and 'Edges'" << endl;
+
+    if (IsEnvDefined(env, prefix, "Title", print))
+    {
+        fTitle = GetEnvValue(env, prefix, "Title", gsDefTitle.Data());
+        rc = kTRUE;
+    }
+
+    if (raw)
+    {
+        const TString txt = GetEnvValue(env, prefix, "Raw", "");
+        if (!SetEdgesRaw(txt.Data()))
+            return kERROR;
+    }
+/*
+    if (fullbins)
+    {
+        TString txt = GetEnvValue(env, prefix, "Binning", "");
+        SetEdgesRaw(txt.Data());
+    }
+   */
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mhbase/MBinning.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MBinning.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MBinning.h	(revision 17960)
@@ -0,0 +1,122 @@
+#ifndef MARS_MBinning
+#define MARS_MBinning
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TH1;
+class TAxis;
+
+class MParList;
+
+class MBinning : public MParContainer
+{
+public:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+private:
+
+    TArrayD fEdges;
+
+    Byte_t  fType;
+
+    void StreamPrimitive(std::ostream &out) const;
+
+    enum {
+        kIsDefault,
+        kIsLinear,
+        kIsLogarithmic,
+        kIsCosinic,
+        kIsUserArray
+    };
+
+public:
+    MBinning(const char *name=NULL, const char *title=NULL);
+    MBinning(Int_t nbins, Axis_t lo, Axis_t hi, const char *name=0, const char *opt="", const char *title=NULL);
+    MBinning(const MBinning &bins, const char *name=NULL, const char *title=NULL);
+    MBinning(const TH1 &h, const Char_t axis='x', const char *name=0, const char *title=0);
+    MBinning(const TAxis &a, const char *name=0, const char *title=0);
+    MBinning(const TArrayD &a, const char *name=0, const char *title=0);
+
+    void Copy(TObject &named) const
+    {
+        MBinning &bins = (MBinning&)named;
+        bins.SetEdges(*this);
+    }
+
+    void SetEdges(const TArrayD &arr)
+    {
+        fEdges = arr;
+        fType  = kIsUserArray;
+    }
+
+    Bool_t SetEdges(const MParList &list, const char *name=0);
+    Bool_t SetEdgesRaw(const char *txt);
+    //Bool_t SetEdges(const char *txt);
+    void SetEdges(const TAxis &axe);
+    void SetEdges(const MBinning &bins) { SetEdges(bins.fEdges); fType = bins.fType; fTitle = bins.fTitle; }
+    void SetEdges(const TH1 &h, const Char_t axis='x');
+    void SetEdges(Int_t nbins, const Axis_t lo, const Axis_t up) { SetEdgesLin(nbins, lo, up); }
+    void SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up, const char *opt);
+    void SetEdgesLin(Int_t nbins, Axis_t lo, Axis_t up);
+    void SetEdgesLog(Int_t nbins, Axis_t lo, Axis_t up);
+    void SetEdgesCos(Int_t nbins, Axis_t lo, Axis_t up);
+    void SetEdgesASin(Int_t nbins, Axis_t lo, Axis_t up);
+
+    Int_t FindLoEdge(Double_t val) const
+    {
+        if (val<GetEdgeLo() || val>=GetEdgeHi())
+            return -1;
+
+	for (int i=1; i<fEdges.GetSize(); i++)
+        {
+            if (fEdges[i] >= val)
+                return i-1;
+        }
+        return -1;
+    }
+    Int_t FindHiEdge(Double_t val) const
+    {
+        const Int_t i = FindLoEdge(val);
+        return i<0 ? -1 : i+1;
+    }
+
+    Double_t GetEdgeLo() const { return fEdges[0]; }
+    Double_t GetEdgeHi() const { return fEdges[fEdges.GetSize()-1]; }
+
+    Int_t GetNumEdges() const  { return fEdges.GetSize(); }
+    Int_t GetNumBins() const   { return fEdges.GetSize()-1; }
+
+    const Double_t *GetEdges() const { return fEdges.GetArray(); }
+    const TArrayD &GetEdgesD() const { return fEdges; }
+
+    Double_t operator[](Int_t i) const { return fEdges[i]; }
+
+    void AddEdge(Axis_t up);
+    void RemoveFirstEdge();
+    void RemoveLastEdge();
+
+    Bool_t IsLinear() const      { return fType==kIsLinear; }
+    Bool_t IsLogarithmic() const { return fType==kIsLogarithmic; }
+    Bool_t IsCosinic() const     { return fType==kIsCosinic; }
+    Bool_t IsDefault() const     { return fType==kIsDefault; }
+    Bool_t IsUserArray() const   { return fType==kIsUserArray; }
+
+    Bool_t HasTitle() const      { return gsDefTitle!=fTitle; }
+
+    void Apply(TH1 &) const;
+
+    void Print(Option_t *o="") const; //*MENU*
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MBinning, 1) //Container to store the binning of a histogram
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhbase/MFillH.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MFillH.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MFillH.cc	(revision 17960)
@@ -0,0 +1,669 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  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 MParameterD container stored
+// in the parameter list or a pointer to it as an argument.
+//
+//
+//  WARNING:
+//   Because MFillH is a generalized task to fill histograms it doesn't
+//   know about which branches from a file are necessary to fill the
+//   histograms. If you are reading data from a file which is directly
+//   filled into a histogram via MFillH, please call either
+//   MReadTree::DisableAutoScheme() or enable the necessary branches by
+//   yourself, using MReadTree::EnableBranch()
+//
+//   Checkout the Warning in MTaskList.
+//
+//  Version 3:
+//  ----------
+//   - added fTitleTab
+//
+//  Version 2:
+//  ----------
+//   - added fNumExcutions
+//
+//
+//  Input Containers:
+//   A parameter container
+//
+//  Output Containers:
+//   A histogram container
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MFillH.h"
+
+#include <fstream>
+
+#include <TClass.h>
+#include <TCanvas.h>
+
+#include "MDataPhrase.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+#include "MH.h"
+#include "MHArray.h"
+
+#include "MParameters.h"
+
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+ClassImp(MFillH);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes name and title of the object. It is called by all
+// constructors.
+//
+void MFillH::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFillH";
+    fTitle = title ? title : "Task to fill Mars histograms";
+
+    fH            = NULL;
+    fParContainer = NULL;
+
+    fIndex  = NULL;
+    fCanvas = NULL;
+
+    fWeight     = NULL;
+    fWeightName = "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. This is to support some root-stuff.
+// Never try to use it yourself!
+//
+MFillH::MFillH()
+{
+    Init(NULL, NULL);
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor.
+//
+// 1) - par is the name of the parameter container which should be filled into
+//      the histogram
+//    - hist is the name of the histogram container (which must have been
+//      derived from MH)
+//
+//    In this case MH::Fill is called with a pointer to the corresponding
+//    histogram instance.
+//
+// 2) - hist is the name and/or type of the histogram.
+//      1) The name and type is identical, eg: "MHHillas"
+//      2) They are not identical, eg: "MyHistogram [MHHillas]"
+//         This searches for a class instance of MHHillas with the name
+//         "MyHistogram". If it doesn't exist one is created.
+//
+//    In this case PreProcess calls MH::SetupFill with a pointer to the
+//    parameter list and MH::Fill is called with a NULL-pointer.
+//
+MFillH::MFillH(const char *hist, const char *par, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fHName = hist;
+    fParContainerName = par;
+
+    AddToBranchList(Form("%s.*", (const char*)ExtractName(hist)));
+    if (par)
+        AddToBranchList(Form("%s.*", (const char*)ExtractName(par)));
+
+    if (title)
+        return;
+
+    fTitle = Form("Fill %s", fHName.Data());
+    if (fParContainerName.IsNull())
+        return;
+
+    fTitle += Form(" from %s", fParContainerName.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor.
+//
+// 1) - par is a pointer to the instance of your parameter container from which
+//      the data should be used to fill the histogram.
+//    - hist is the name of the histogram container (which must have been
+//      derived from MH)
+//
+//    In this case MH::Fill is called with a pointer to the corresponding
+//    histogram instance.
+//
+// 2) - hist is the name and/or type of the histogram.
+//      1) The name and type is identical, eg: "MHHillas"
+//      2) They are not identical, eg: "MyHistogram [MHHillas]"
+//         This searches for a class instance of MHHillas with the name
+//         "MyHistogram". If it doesn't exist one is created. Everything
+//         which is between the first '[' and the last ']' in the string
+//         is used as the histogram type.
+//
+//    In this case PreProcess calls MH::SetupFill with a pointer to the
+//    parameter list and MH::Fill is called with a NULL-pointer.
+//
+//
+MFillH::MFillH(const char *hist, MParContainer *par, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fHName = hist;
+    fParContainer = par;
+    if (par)
+        fParContainerName = par->GetName();
+
+    AddToBranchList(Form("%s.*", (const char*)ExtractName(hist)));
+    if (par)
+        AddToBranchList(Form("%s.*", par->GetName()));
+
+    if (!title)
+        fTitle = Form("Fill %s from %s", fName.Data(), par?par->GetDescriptor().Data():"NULL");
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+    if (hist)
+        fHName = hist->GetName();
+    fParContainerName = par;
+
+    if (fH)
+        AddToBranchList(fH->GetDataMember());
+    if (par)
+        AddToBranchList(Form("%s.*", (const char*)ExtractName(par)));
+
+    if (title)
+        return;
+
+    fTitle = Form("Fill %s", hist ? hist->GetDescriptor().Data() : "NULL");
+    if (!par)
+        return;
+
+    fTitle += Form(" from %s", fParContainerName.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor.
+//
+// - par is a pointer to the instance of your parameter container from which
+//   the data should be used to fill the histogram.
+// - hist is the name of the histogram container (which must have been
+//   derived from MH)
+//
+MFillH::MFillH(MH *hist, MParContainer *par, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fH = hist;
+    if (hist)
+        fHName = hist->GetName();
+    fParContainer = par;
+    if (par)
+        fParContainerName = par->GetName();
+
+    if (fH)
+        AddToBranchList(fH->GetDataMember());
+    if (par)
+        AddToBranchList(Form("%s.*", par->GetName()));
+
+    if (!title)
+        fTitle = Form("Fill %s from %s",
+                      hist?hist->GetDescriptor().Data():"NULL",
+                      par ? par->GetDescriptor().Data():"NULL");
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MDataPhrase. 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
+// "MRawRunHeader::fRunNumber" you would get one histogram per run-number)
+//
+void MFillH::SetRuleForIdx(const TString rule)
+{
+    fIndex = new MDataPhrase(rule);
+    fIndex->SetBit(kCanDelete);
+}
+
+// --------------------------------------------------------------------------
+//
+// If the histogram to be filles is a MHArray you can specify a MData-object
+// The return value of the object is casted to int. Each int acts as a key.
+// For each (new) key a new histogram is created in the array. (eg for
+// MDataMember("MRawEvtHeader::fRunNumber") you would get one histogram per
+// run-number)
+//
+void MFillH::SetRuleForIdx(MData *data)
+{
+    fIndex = data;
+}
+
+// --------------------------------------------------------------------------
+//
+// Extracts the name of the histogram from the MFillH argument
+//
+TString MFillH::ExtractName(const char *name) const
+{
+    TString type = name;
+
+    const Ssiz_t first = type.First('[');
+    const Ssiz_t last  = type.First(']');
+
+    if (!first || !last || first>=last)
+        return type;
+
+    return type.Remove(first).Strip(TString::kBoth);
+}
+
+// --------------------------------------------------------------------------
+//
+// Extracts the class-name of the histogram from the MFillH argument
+//
+TString MFillH::ExtractClass(const char *name) const
+{
+    TString type = name;
+
+    const Ssiz_t first = type.First('[');
+    const Ssiz_t last  = type.First(']');
+
+    if (!first || !last || first>=last)
+        return type;
+
+    const Ssiz_t length = last-first-1;
+
+    TString strip = fHName(first+1, length);
+    return strip.Strip(TString::kBoth);
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this to set a draw option used when drawing automatically to the
+// status display.
+//
+void MFillH::SetDrawOption(Option_t *option)
+{
+    fDrawOption = option;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new tab in a status display with the name of the MH class,
+// if fDisplay is set and the MH-class overwrites the Draw function
+//
+// If the draw-option contains 'same' (case insensitive) a tab with the
+// same name as the one which would be created is searched and the
+// MH is drawn to this canvas. If it is not found a new tab is created.
+//
+Bool_t MFillH::DrawToDisplay()
+{
+    fCanvas = NULL;
+
+    if (!fDisplay)
+        return kTRUE;
+
+    if (!fH->OverwritesDraw())
+        return kTRUE;
+
+    if (TestBit(kDoNotDisplay))
+        return kTRUE;
+
+    const TString tabname = fNameTab.IsNull() ? fH->GetName() : fNameTab.Data();
+
+    fCanvas = 0;
+    if (fDrawOption.Contains("same", TString::kIgnoreCase))
+    {
+        fCanvas = fDisplay->GetCanvas(tabname);
+        if (!fCanvas)
+            *fLog << warn << "WARNING - 'same' option given, but no tab with name '" << tabname << "' found." << endl;
+    }
+
+    if (!fCanvas)
+    {
+        const TString tabtitle = fTitleTab.IsNull() ? fH->GetTitle() : fTitleTab.Data();
+        fCanvas = &fDisplay->AddTab(tabname, tabtitle);
+    }
+
+    fCanvas->cd();
+    fH->Draw(fDrawOption);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks the parameter list for the existance of the parameter container. If
+// the name of it was given in the constructor. It checks also for the
+// existance of the histogram container in the parameter list if a name was
+// given. If it is not available it tried to create a histogram container
+// with the same type as the given object name.
+//
+Int_t MFillH::PreProcess(MParList *pList)
+{
+    if (fIndex)
+    {
+        if (!fIndex->PreProcess(pList))
+        {
+            *fLog << all << "PreProcessing of Index rule failed... aborting." << endl;
+            return kFALSE;
+        }
+
+        if (!fIndex->IsValid())
+        {
+            *fLog << all << "Given Index rule invalid... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // If the user defined the use of a weight: search for it.
+    //
+    if (!fWeight && !fWeightName.IsNull())
+    {
+        fWeight = (MParameterD*)pList->FindObject(fWeightName, "MParameterD");
+
+	if (!fWeight)
+        {
+            *fLog << err << fWeightName << " [MParameterD] not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // Try to get the histogram container with name fHName from list
+    // or create one with this name
+    //
+    if (!fH)
+    {
+        const TString cls  = ExtractClass(fHName);
+        const TString name = ExtractName(fHName);
+
+        TObject *obj=NULL;
+        if (cls==name)
+            obj = pList->FindObject(fHName);
+
+        if (!obj)
+        {
+            /*
+            if (cls==name)
+            *fLog << inf << "Object '" << fHName << "' not found in parlist... creating." << endl;
+            */
+            obj = pList->FindCreateObj(cls, name);
+        }
+
+        if (!obj)
+            return kFALSE;
+
+        //
+        // We were successfull getting it. Check whether it really inherits
+        // from MH, FindCreateObj does only check for inheritance from
+        // 'type'.
+        //
+        TClass *tcls = fIndex ? MHArray::Class() : MH::Class();
+        if (!obj->InheritsFrom(tcls))
+        {
+            *fLog << err << obj->GetName() << " doesn't inherit ";
+            *fLog << "from " << tcls->GetName() << " - cannot be used for MFillH...";
+            *fLog << "aborting." << endl;
+            return kFALSE;
+        }
+
+        fH = (MH*)obj;
+    }
+
+    //
+    // Now we have the histogram container available. Try to Setup Fill.
+    //
+    fH->SetSerialNumber(GetSerialNumber());
+    fH->SetNumExecutions(0);
+    if (!fH->SetupFill(pList))
+    {
+        *fLog << (TestBit(kCanSkip) ? warn : err);
+        *fLog << (TestBit(kCanSkip) ? "WARNING" : "ERROR");
+        *fLog << " - Calling SetupFill for " << fH->GetDescriptor() << "...";
+        *fLog << (TestBit(kCanSkip) ? "skipped." : "aborting.") << endl;
+
+        return TestBit(kCanSkip) ? kSKIP : kFALSE;
+    }
+
+    //
+    // If also a parameter container is already set we are done.
+    //
+    if (fParContainer)
+        return DrawToDisplay();
+
+    //
+    // This case means, that the MH sets up its container to be filled
+    // by itself. Check there if it has something to be filled with!
+    //
+    if (fParContainerName.IsNull())
+    {
+        fParContainer = NULL;
+        return DrawToDisplay();
+    }
+
+    fParContainer = (MParContainer*)pList->FindObject(fParContainerName);
+    if (fParContainer)
+        return DrawToDisplay();
+
+    if (TestBit(kCanSkip))
+    {
+        *fLog << warn << fParContainerName << " [MParContainer] not found... skipped." << endl;
+        return kSKIP;
+    }
+
+    *fLog << err << fParContainerName << " [MParContainer] not found... aborting." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call the ReInit function of the contained Histogram
+//
+Bool_t MFillH::ReInit(MParList *pList)
+{
+    return fH->ReInit(pList);
+} 
+
+// --------------------------------------------------------------------------
+//
+// Fills the data from the parameter conatiner into the histogram container
+//
+Int_t MFillH::Process()
+{
+    if (fIndex)
+        ((MHArray*)fH)->SetIndexByKey(fIndex->GetValue());
+    /*
+     const Int_t key = (Int_t)fIndex->GetValue();
+     const Int_t idx = fMapIdx->Add(key);
+     ((MHArray*)fH)->SetIndex(idx);
+     */
+
+//    TVirtualPad *save = gPad;
+//    if (fCanvas)
+//        fCanvas->cd();
+
+    fH->SetNumExecutions(GetNumExecutions());
+    const Int_t rc = fH->Fill(fParContainer, fWeight?fWeight->GetVal():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()
+{
+    // Return if fH was never initialized.
+    if (!fH)
+        return kTRUE;
+
+    //
+    // Now all data is in the histogram. Maybe some final action is
+    // necessary.
+    //
+    if (!fH->Finalize())
+    {
+        *fLog << err << "ERROR - Calling Finalize for ";
+        *fLog << fH->GetDescriptor() << "... aborting." << endl;
+        return kFALSE;
+    }
+
+    fH->SetReadyToSave();
+
+    //
+    // Check whether fDisplay has previously been used (fCanvas),
+    // fDisplay is still open and the corresponding Canvas/Tab is
+    // still existing.
+    //
+    if (fDisplay && fDisplay->HasCanvas(fCanvas))
+    {
+        const TString opt(MString::Format("nonew %s", fDrawOption.Data()));
+        // fCanvas->cd();
+        // fCanvas->Clear();
+
+        // Remove the old class to prevent clashes calling
+        // Paint-functions when the display is updated
+        fCanvas->GetListOfPrimitives()->Remove(fH);
+        fCanvas->GetListOfPrimitives()->Add(fH->Clone(), opt);
+        fCanvas->Modified();
+        fCanvas->Update();
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MFillH::StreamPrimitive(ostream &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: branches/Mars_McMismatchStudy/mhbase/MFillH.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MFillH.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MFillH.h	(revision 17960)
@@ -0,0 +1,84 @@
+#ifndef MARS_MFillH
+#define MARS_MFillH
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MH;
+class MMap;
+class MData;
+class MParameterD;
+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;
+    TString fTitleTab;
+
+    MParameterD *fWeight;         //! Pointer to the container storing a weight
+    TString fWeightName;          // Name of a container storing a weight
+
+    MData *fIndex;                // MData object describing the 'key' to an automatic index for an MHArray
+    MMap  *fMapIdx;               //! Map to map key-index-pair for an MHArray (MMap see MFillH.cc)
+
+    TCanvas *fCanvas;             //! Canvas used to update a MStatusDisplay at the end of a loop
+
+    TString fDrawOption;          // Draw option for status display
+
+    TString ExtractName(const char *name) const;
+    TString ExtractClass(const char *name) const;
+
+    void Init(const char *name, const char *title);
+
+    void StreamPrimitive(std::ostream &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="", const char *t="") { fNameTab = n; fTitleTab = t; }
+    void SetTitleTab(const char *t="") { fTitleTab = t; }
+
+    void SetRuleForIdx(const TString rule);
+    void SetRuleForIdx(MData *rule);
+
+    void ResetWeight() { fWeight=0; fWeightName=""; }
+    void SetWeight(MParameterD *w)   { fWeight = w; }
+    void SetWeight(const char *name="MWeight") { fWeightName = name; }
+
+    void      SetDrawOption(Option_t *option="");
+    Option_t *GetDrawOption() const { return fDrawOption; }
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    TCanvas *GetCanvas() { return fCanvas; }
+
+    ClassDef(MFillH, 3) // Task to fill a histogram with data from a parameter container
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/mhbase/MH.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MH.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MH.cc	(revision 17960)
@@ -0,0 +1,1911 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2010
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  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 <TColor.h>
+#include <TMath.h>
+#include <TClass.h>
+#include <TStyle.h>       // TStyle::GetScreenFactor
+#include <TGaxis.h>
+#include <TCanvas.h>
+#include <TLegend.h>
+#include <TPaveStats.h>
+#include <TBaseClass.h>
+#include <THashList.h>
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+#include <THLimitsFinder.h>
+#endif
+#include <TProfile2D.h>  // root > 5.18
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+#include "MParList.h"
+#include "MParContainer.h"
+
+#include "MBinning.h"
+
+#include "MArrayD.h"
+#include "MArrayF.h"
+
+ClassImp(MH);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title only. Typically you won't
+// need to change this.
+//
+MH::MH(const char *name, const char *title)
+    : fSerialNumber(0), fNumExecutions(0)
+
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MH";
+    fTitle = title ? title : "Base class for Mars histograms";
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to use the automatic filling of your derived class you
+// must overload this function. If it is not overloaded you cannot use
+// FillH with this class. The argument is a pointer to a container
+// in your paremeter list which is specified in the MFillH constructor.
+// If you are not going to use it you should at least add
+//   Bool_t MH::Fill(const MParContainer *) { return kTRUE; }
+// to your class definition.
+//
+Int_t MH::Fill(const MParContainer *par, const Stat_t w)
+{
+    *fLog << warn << GetDescriptor() << ": Fill not overloaded! Can't be used!" << endl;
+    return kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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) const
+{
+    *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 += MString::Format(" <%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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search in gPad for all objects with the name name and remove all of them
+// (TList::Remove)
+//
+void MH::RemoveFromPad(const char *name)
+{
+    if (!gPad)
+        return;
+
+    TList *list = gPad->GetListOfPrimitives();
+    if (!list)
+        return;
+
+    TObject *obj = 0;
+    while ((obj = gPad->FindObject(name)))
+        list->Remove(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// If labels are set for this axis the correct MBinning corresponding
+// to the existing label range is returned (this is necessary to
+// maintain the correct number of bins in the histogram)
+// otherwise the given binning is returned.
+//
+MBinning MH::GetBinningForLabels(TAxis &x, const MBinning *bins)
+{
+    if (!x.GetLabels())
+        return *bins;
+
+    const Int_t n = TMath::Max(x.GetLabels()->GetEntries(), 1);
+    return MBinning(n, 0, n);
+}
+
+// --------------------------------------------------------------------------
+//
+// If Labels are set this function deletes the fXbins Array from
+// the axis (which makes the axis a variable bin-size axis)
+// and sets the Nbins, Xmin and Xmax according to the number of labels.
+//
+void MH::RestoreBinningForLabels(TAxis &x)
+{
+    if (!x.GetLabels())
+        return;
+
+    const Int_t n = TMath::Max(x.GetLabels()->GetEntries(), 1);
+    x.Set(n, 0, n);
+
+    const_cast<TArrayD*>(x.GetXbins())->Set(0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies a given binning to a 1D-histogram. In case the axis has labels
+// (e.g. GetXaxis()->GetLabels()) the binning is set according to the
+// labels.
+//
+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
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    // All this is reset by TAxis::Set
+    const TAttAxis att(x);
+    const Bool_t   tm(x.GetTimeDisplay());
+    const TString  tf(x.GetTimeFormat());
+
+    //
+    // This is a necessary workaround if one wants to set
+    // non-equidistant bins after the initialization
+    // TH1D::fNcells must be set correctly.
+    //
+    h.SetBins(binsx.GetNumBins(), 0, 1);
+
+    //
+    // Set the binning of the current histogram to the binning
+    // in one of the two given histograms
+    //
+    x.Set(binsx.GetNumBins(), binsx.GetEdges());
+
+    // All this is reset by TAxis::Set
+    att.Copy(x);
+    x.SetTimeDisplay(tm);
+    x.SetTimeFormat(tf);
+#else
+    if (!x.GetLabels())
+        h.SetBins(binsx.GetNumBins(), binsx.GetEdges());
+#endif
+
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    x.SetTitle(xtitle);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies given binnings to the two axis of a 2D-histogram.
+// In case the axis has labels (e.g. GetXaxis()->GetLabels())
+// the binning is set according to the labels.
+//
+void MH::SetBinning(TH2 &h, const MBinning &binsx, const MBinning &binsy)
+{
+    TAxis &x = *h.GetXaxis();
+    TAxis &y = *h.GetYaxis();
+
+    const MBinning bx(GetBinningForLabels(x, &binsx));
+    const MBinning by(GetBinningForLabels(y, &binsy));
+
+    //
+    // 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
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    // All this is reset by TAxis::Set
+    const TAttAxis attx(x);
+    const TAttAxis atty(y);
+    const Bool_t   tmx(x.GetTimeDisplay());
+    const Bool_t   tmy(y.GetTimeDisplay());
+    const TString  tfx(x.GetTimeFormat());
+    const TString  tfy(y.GetTimeFormat());
+
+    //
+    // This is a necessary workaround if one wants to set
+    // non-equidistant bins after the initialization
+    // TH1D::fNcells must be set correctly.
+    //
+    h.SetBins(bx.GetNumBins(), 0, 1,
+              by.GetNumBins(), 0, 1);
+
+    //
+    // Set the binning of the current histogram to the binning
+    // in one of the two given histograms
+    //
+    x.Set(bx.GetNumBins(), bx.GetEdges());
+    y.Set(by.GetNumBins(), by.GetEdges());
+
+    // All this is reset by TAxis::Set
+    attx.Copy(x);
+    atty.Copy(y);
+    x.SetTimeDisplay(tmx);
+    y.SetTimeDisplay(tmy);
+    x.SetTimeFormat(tfx);
+    y.SetTimeFormat(tfy);
+#else
+    if (h.InheritsFrom(TProfile2D::Class()))
+    {
+        h.SetBins(bx.GetNumBins(), 0, 1,
+                  by.GetNumBins(), 0, 1);
+
+        h.SetBinsLength();
+
+        x.Set(bx.GetNumBins(), bx.GetEdges());
+        y.Set(by.GetNumBins(), by.GetEdges());
+    }
+    else
+        h.SetBins(bx.GetNumBins(), bx.GetEdges(),
+                  by.GetNumBins(), by.GetEdges());
+#endif
+
+    RestoreBinningForLabels(x);
+    RestoreBinningForLabels(y);
+
+#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
+// In case the axis has labels (e.g. GetXaxis()->GetLabels())
+// the binning is set according to the labels.
+//
+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();
+
+    const MBinning bx(GetBinningForLabels(x, &binsx));
+    const MBinning by(GetBinningForLabels(y, &binsy));
+    const MBinning bz(GetBinningForLabels(z, &binsz));
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    TString xtitle = x.GetTitle();
+    TString ytitle = y.GetTitle();
+    TString ztitle = z.GetTitle();
+#endif
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    // All this is reset by TAxis::Set
+    const TAttAxis attx(x);
+    const TAttAxis atty(y);
+    const TAttAxis attz(z);
+    const Bool_t   tmx(x.GetTimeDisplay());
+    const Bool_t   tmy(y.GetTimeDisplay());
+    const Bool_t   tmz(z.GetTimeDisplay());
+    const TString  tfx(x.GetTimeFormat());
+    const TString  tfy(y.GetTimeFormat());
+    const TString  tfz(z.GetTimeFormat());
+#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(bx.GetNumBins(), 0, 1,
+              by.GetNumBins(), 0, 1,
+              bz.GetNumBins(), 0, 1);
+
+    //
+    // Set the binning of the current histogram to the binning
+    // in one of the two given histograms
+    //
+    x.Set(bx.GetNumBins(), bx.GetEdges());
+    y.Set(by.GetNumBins(), by.GetEdges());
+    z.Set(bz.GetNumBins(), bz.GetEdges());
+
+    RestoreBinningForLabels(x);
+    RestoreBinningForLabels(y);
+    RestoreBinningForLabels(z);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    // All this is reset by TAxis::Set
+    attx.Copy(x);
+    atty.Copy(y);
+    attz.Copy(z);
+    x.SetTimeDisplay(tmx);
+    y.SetTimeDisplay(tmy);
+    z.SetTimeDisplay(tmz);
+    x.SetTimeFormat(tfx);
+    y.SetTimeFormat(tfy);
+    z.SetTimeFormat(tfz);
+#endif
+
+#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::CopyBinning(const TH1 &x, TH1 &h)
+{
+    if (h.InheritsFrom(TH3::Class()) && x.InheritsFrom(TH3::Class()))
+    {
+        SetBinning(static_cast<TH3&>(h), *x.GetXaxis(), *x.GetYaxis(), *x.GetZaxis());
+        return;
+    }
+    if (h.InheritsFrom(TH3::Class()) || x.InheritsFrom(TH3::Class()))
+        return;
+    if (h.InheritsFrom(TH2::Class()) && x.InheritsFrom(TH2::Class()))
+    {
+        SetBinning(static_cast<TH2&>(h), *x.GetXaxis(), *x.GetYaxis());
+        return;
+    }
+    if (h.InheritsFrom(TH2::Class()) || x.InheritsFrom(TH2::Class()))
+        return;
+    if (h.InheritsFrom(TH1::Class()) && x.InheritsFrom(TH1::Class()))
+    {
+        SetBinning(h, *x.GetXaxis());
+        return;
+    }
+}
+
+void MH::RemoveFirstBin(TH1 &h)
+{
+    if (h.InheritsFrom(TH2::Class()) || h.InheritsFrom(TH3::Class()))
+        return;
+
+    const Bool_t haserr = h.GetSumw2N()>0;
+
+    const Int_t n0 = h.GetNbinsX();
+    if (n0<2)
+        return;
+
+    TArrayD val(n0-1);
+    TArrayD er(haserr ? n0-1 : 0);
+    for (int i=1; i<n0; i++)
+    {
+        val[i-1] = h.GetBinContent(i+1);
+        if (haserr)
+            er[i-1] = h.GetBinError(i+1);
+    }
+
+    MBinning bins;
+    bins.SetEdges(h, 'x');
+    bins.RemoveFirstEdge();
+    bins.Apply(h);
+
+    h.Reset();
+
+    for (int i=1; i<n0; i++)
+    {
+        h.SetBinContent(i, val[i-1]);
+        if (haserr)
+            h.SetBinError(i, er[i-1]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Multiplies all entries in a TArrayD by a float f
+//
+void MH::ScaleArray(TArrayD &bins, Double_t f)
+{
+    for (int i=0; i<bins.GetSize(); i++)
+        bins[i] *= f;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scales the binning of a TAxis by a float f
+//
+TArrayD MH::ScaleAxis(TAxis &axe, Double_t f)
+{
+    TArrayD arr(axe.GetNbins()+1);
+
+    for (int i=1; i<=axe.GetNbins()+1; i++)
+        arr[i-1] = axe.GetBinLowEdge(i);
+
+    ScaleArray(arr, f);
+
+    return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scales the binning of one, two or three axis of a histogram by a float f
+//
+void MH::ScaleAxis(TH1 &h, Double_t fx, Double_t fy, Double_t fz)
+{
+    if (h.InheritsFrom(TH3::Class()))
+    {
+        SetBinning(static_cast<TH3&>(h),
+                   ScaleAxis(*h.GetXaxis(), fx),
+                   ScaleAxis(*h.GetYaxis(), fy),
+                   ScaleAxis(*h.GetZaxis(), fz));
+        return;
+    }
+
+    if (h.InheritsFrom(TH2::Class()))
+    {
+        SetBinning(static_cast<TH2&>(h),
+                   ScaleAxis(*h.GetXaxis(), fx),
+                   ScaleAxis(*h.GetYaxis(), fy));
+        return;
+    }
+
+    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.
+// If the binning is found, but it IsDefault() kTRUE is returned, but
+// no binning is applied.
+//
+Bool_t MH::ApplyBinning(const MParList &plist, const 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;
+    }
+
+    if (bins->IsDefault())
+    {
+        gLog << inf << "Object 'Binning" << name << "' [MBinning] is default... binning unchanged." << endl;
+        return kTRUE;
+    }
+
+    SetBinning(h, *bins);
+    return kTRUE;
+}
+
+Bool_t MH::ApplyBinning(const MParList &plist, const TString x, const TString y, TH2 &h)
+{
+    const MBinning *binsx = (MBinning*)plist.FindObject("Binning"+x);
+    const MBinning *binsy = (MBinning*)plist.FindObject("Binning"+y);
+
+    if (!binsx && !binsy)
+    {
+        gLog << inf << "Neither 'Binning" << x << "' nor 'Binning" << y;
+        gLog << "' [MBinning] found... no binning applied." << endl;
+        return kFALSE;
+    }
+
+    if (!binsx)
+        gLog << inf << "Object 'Binning" << x << "' [MBinning] not found... binning unchanged." << endl;
+    if (!binsy)
+        gLog << inf << "Object 'Binning" << y << "' [MBinning] not found... binning unchanged." << endl;
+
+    if (binsx && binsx->IsDefault())
+    {
+        gLog << inf << "Object 'Binning" << x << "' [MBinning] is default... binning unchanged." << endl;
+        binsx = 0;
+    }
+
+    if (binsy && binsy->IsDefault())
+    {
+        gLog << inf << "Object 'Binning" << y << "' [MBinning] is default... binning unchanged." << endl;
+        binsy = 0;
+    }
+
+    MBinning binsxx, binsyy;
+    binsxx.SetEdges(h, 'x');
+    binsyy.SetEdges(h, 'y');
+
+    SetBinning(h, binsx?*binsx:binsxx, binsy?*binsy:binsyy);
+
+    return kTRUE;
+}
+
+Bool_t MH::ApplyBinning(const MParList &plist, const TString x, const TString y, const TString z, TH3 &h)
+{
+    const MBinning *binsx = (MBinning*)plist.FindObject("Binning"+x);
+    const MBinning *binsy = (MBinning*)plist.FindObject("Binning"+y);
+    const MBinning *binsz = (MBinning*)plist.FindObject("Binning"+z);
+
+    if (!binsx && !binsy && !binsz)
+    {
+        gLog << inf << "Neither 'Binning" << x << "', 'Binning" << y;
+        gLog << "' nor 'Binning" << z << "' [MBinning] found... ";
+        gLog << "no binning applied." << endl;
+        return kFALSE;
+    }
+
+    if (!binsx)
+        gLog << inf << "Object 'Binning" << x << "' [MBinning] not found... binning unchanged." << endl;
+    if (!binsy)
+        gLog << inf << "Object 'Binning" << y << "' [MBinning] not found... binning unchanged." << endl;
+    if (!binsz)
+        gLog << inf << "Object 'Binning" << z << "' [MBinning] not found... binning unchanged." << endl;
+
+    if (binsx && binsx->IsDefault())
+    {
+        gLog << inf << "Object 'Binning" << x << "' [MBinning] is default... binning unchanged." << endl;
+        binsx = 0;
+    }
+
+    if (binsy && binsy->IsDefault())
+    {
+        gLog << inf << "Object 'Binning" << y << "' [MBinning] is default... binning unchanged." << endl;
+        binsy = 0;
+    }
+
+    if (binsz && binsz->IsDefault())
+    {
+        gLog << inf << "Object 'Binning" << z << "' [MBinning] is default... binning unchanged." << endl;
+        binsy = 0;
+    }
+
+    MBinning binsxx, binsyy, binszz;
+    binsxx.SetEdges(h, 'x');
+    binsyy.SetEdges(h, 'y');
+    binszz.SetEdges(h, 'z');
+
+    SetBinning(h, binsx?*binsx:binsxx, binsy?*binsy:binsyy, binsz?*binsz:binszz);
+
+    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 Int_t nx = h.GetXaxis()->GetNbins();
+    const Int_t ny = h.GetYaxis()->GetNbins();
+    const Int_t nz = h.GetZaxis()->GetNbins();
+
+    for (int iz=1; iz<=nz; iz++)
+        for (int iy=1; iy<=ny; iy++)
+            for (int ix=1; ix<=nx; 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 = 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 = dynamic_cast<TPaveStats*>(gPad->FindObject("stats"));
+    if (!s1)
+        s1 = dynamic_cast<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 = hist2.DrawCopy("sames");
+    gPad->Update();
+
+    //
+    // Draw Legend
+    //
+    TPaveStats *s2 = dynamic_cast<TPaveStats*>(gPad->FindObject("stats"));
+    if (!s2)
+        s2 = dynamic_cast<TPaveStats*>(hist2.GetListOfFunctions()->FindObject("stats"));
+
+    if (s2)
+    {
+        TLegend &l = *new TLegend(s2->GetX1NDC(),
+                                  s2->GetY1NDC()-0.015-(s2->GetY2NDC()-s2->GetY1NDC())/2,
+                                  s2->GetX2NDC(),
+                                  s2->GetY1NDC()-0.01
+                                 );
+        l.AddEntry(h1, h1->GetTitle());
+        l.AddEntry(h2, h2->GetTitle());
+        l.SetTextSize(s2->GetTextSize());
+        l.SetTextFont(s2->GetTextFont());
+        l.SetBorderSize(s2->GetBorderSize());
+        l.SetBit(kCanDelete);
+        l.Draw();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draws the two given histograms. Uses title as the pad title.
+// Also layout the two statistic boxes and a legend.
+//
+void MH::DrawSame(TH1 &hist1, TH1 &hist2, const TString title, Bool_t same)
+{
+    //
+    // Draw first histogram
+    //
+    hist1.Draw(same?"same":"");
+    gPad->SetBorderMode(0);
+    gPad->Update();
+
+    if (hist1.GetEntries()>0 && hist2.GetEntries()>0)
+    {
+        const Double_t maxbin1 = hist1.GetBinContent(hist1.GetMaximumBin());
+        const Double_t maxbin2 = hist2.GetBinContent(hist2.GetMaximumBin());
+        const Double_t minbin1 = hist1.GetBinContent(hist1.GetMinimumBin());
+        const Double_t minbin2 = hist2.GetBinContent(hist2.GetMinimumBin());
+
+        const Double_t max = TMath::Max(maxbin1, maxbin2);
+        const Double_t min = TMath::Min(minbin1, minbin2);
+
+        if (max!=min)
+        {
+            hist1.SetMaximum(max>0?max*1.05:max*0.95);
+            hist1.SetMinimum(max>0?min*0.95:min*1.05);
+        }
+    }
+
+    TPaveText *t = (TPaveText*)gPad->FindObject("title");
+    if (t)
+    {
+        t->SetName((TString)"MHTitle");     // rename object
+        t->Clear();                         // clear old lines
+        t->AddText((TString)" "+title+" "); // add the new title
+        t->SetBit(kCanDelete);              // make sure object is deleted
+
+        //
+        // FIXME: This is a stupid workaround to hide the redrawn
+        // (see THistPainter::PaintTitle) title
+        //
+        gPad->Modified();  // indicates a change
+        gPad->Update();    // recreates the original title
+        t->Pop();          // bring our title on top
+    }
+
+    //
+    // Rename first statistics box
+    //
+    // Where to get the TPaveStats depends on the root version
+    TPaveStats *s1 = dynamic_cast<TPaveStats*>(gPad->FindObject("stats"));
+    if (!s1)
+        s1 = dynamic_cast<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 = dynamic_cast<TPaveStats*>(gPad->FindObject("stats"));
+    if (!s2)
+        s2 = dynamic_cast<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();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+//
+TH1I* MH::ProjectArray(const TArrayF &array, Int_t nbins, 
+                       const char* name, const char* title)
+{
+    const Int_t size = array.GetSize();
+
+    TH1I *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(name);
+    if (h1obj && h1obj->InheritsFrom("TH1I"))
+    {
+        h1 = (TH1I*)h1obj;
+        h1->Reset();
+    }
+
+    Double_t min = size>0 ? array[0] : 0;
+    Double_t max = size>0 ? array[0] : 1;
+
+    // first loop over array to find the min and max
+    for (Int_t i=1; i<size;i++)
+    {
+        max = TMath::Max((Double_t)array[i], max);
+        min = TMath::Min((Double_t)array[i], min);
+    }
+
+    Int_t newbins = 0;
+    FindGoodLimits(nbins, newbins, min, max, kFALSE);
+
+    if (!h1)
+    {
+        h1 = new TH1I(name, title, nbins, min, max);
+        h1->SetXTitle("");
+        h1->SetYTitle("Counts");
+        h1->SetDirectory(NULL);
+    }
+
+    // Second loop to fill the histogram
+    for (Int_t i=0;i<size;i++)
+        h1->Fill(array[i]);
+
+    return h1;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+//
+TH1I* MH::ProjectArray(const TArrayD &array, Int_t nbins, const char* name, const char* title)
+{
+    const Int_t size = array.GetSize();
+
+    Double_t min = size>0 ? array[0] : 0;
+    Double_t max = size>0 ? array[0] : 1;
+
+    TH1I *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(name);
+    if (h1obj && h1obj->InheritsFrom("TH1I"))
+    {
+        h1 = (TH1I*)h1obj;
+        h1->Reset();
+    }
+
+    // first loop over array to find the min and max
+    for (Int_t i=1; i<size;i++)
+    {
+        max = TMath::Max(array[i], max);
+        min = TMath::Min(array[i], min);
+    }
+
+    Int_t newbins = 0;
+    FindGoodLimits(nbins, newbins, min, max, kFALSE);
+
+    if (!h1)
+    {
+      h1 = new TH1I(name, title, newbins, min, max);
+      h1->SetXTitle("");
+      h1->SetYTitle("Counts");
+      h1->SetDirectory(NULL);
+    }
+    
+    // Second loop to fill the histogram
+    for (Int_t i=0;i<size;i++)
+        h1->Fill(array[i]);
+
+    return h1;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+//
+TH1I* MH::ProjectArray(const MArrayF &array, Int_t nbins, 
+                       const char* name, const char* title)
+{
+    return ProjectArray(TArrayF(array.GetSize(),array.GetArray()), nbins, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+//
+TH1I* MH::ProjectArray(const MArrayD &array, Int_t nbins, const char* name, const char* title)
+{
+    return ProjectArray(TArrayD(array.GetSize(),array.GetArray()), nbins, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a workaround for rrot-version <5.13/04 to get correct
+// binomial errors even if weights have been used, do:
+//    h->Divide(h1, h2, 5, 2, "b");
+//    MH::SetBinomialErrors(*h, *h1, *h2, 5, 2);
+//
+// see http://root.cern.ch/phpBB2/viewtopic.php?p=14818
+// see http://savannah.cern.ch/bugs/?20722
+//
+void MH::SetBinomialErrors(TH1 &hres, const TH1 &h1, const TH1 &h2, Double_t c1, Double_t c2)
+{
+    for (Int_t binx=0; binx<=hres.GetNbinsX()+1; binx++)
+    {
+        const Double_t b1 = h1.GetBinContent(binx);
+        const Double_t b2 = h2.GetBinContent(binx);
+        const Double_t e1 = h1.GetBinError(binx);
+        const Double_t e2 = h2.GetBinError(binx);
+
+        //const Double_t w  = c2*b2 ? (c1*b1)/(c2*b2) : 0;
+        //const Double_t rc = ((1-2*w)*e1*e1+w*w*e2*e2)/(b2*b2);
+
+        if (b2==0)
+        {
+            hres.SetBinError(binx, 0);
+            continue;
+        }
+
+        const Double_t c = c2==0 ? 1 : c1/c2;
+        const Double_t u = b2==0 ? 0 : b1/b2;
+
+        const Double_t rc = c*((1-2*u)*e1*e1+u*u*e2*e2)/(b2*b2);
+
+        hres.SetBinError(binx, TMath::Sqrt(TMath::Abs(rc)));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the first and last bin of the histogram which is not 0
+//
+void MH::GetRange(const TH1 &h, Int_t &lo, Int_t &hi)
+{
+    lo = 0;
+    hi = 1;
+
+    for (int i=1; i<=h.GetNbinsX(); i++)
+    {
+        if (lo==0 && h.GetBinContent(i)>0)
+            lo = i;
+
+        if (h.GetBinContent(i)>0)
+            hi = i;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the lower edge of the first and the upper edge of the last bin
+// of the histogram which is not 0
+//
+void MH::GetRangeUser(const TH1 &h, Axis_t &lo, Axis_t &hi)
+{
+    Int_t f, l;
+    GetRange(h, f, l);
+
+    lo = h.GetBinLowEdge(f);
+    hi = h.GetBinLowEdge(l+1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the first and last column (x-bin) of the histogram which is not 0.
+// Therefor a proper projection is produced if the argument is a TH2.
+//
+// TH3 are not yet supported
+//
+void MH::GetRangeX(const TH1 &hist, Int_t &lo, Int_t &hi)
+{
+    if (hist.InheritsFrom(TH3::Class()))
+        return;
+
+    if (hist.InheritsFrom(TH2::Class()))
+    {
+        TH1 *pro = static_cast<const TH2&>(hist).ProjectionX();
+        GetRange(*pro, lo, hi);
+        delete pro;
+        return;
+    }
+
+    GetRange(hist, lo, hi);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the first and last row (y-bin) of the histogram which is not 0.
+// Therefor a proper projection is produced if the argument is a TH2.
+//
+// TH3 are not yet supported
+//
+void MH::GetRangeY(const TH1 &hist, Int_t &lo, Int_t &hi)
+{
+    if (hist.InheritsFrom(TH3::Class()))
+        return;
+
+    if (hist.InheritsFrom(TH2::Class()))
+    {
+        TH1 *pro = static_cast<const TH2&>(hist).ProjectionY();
+        GetRange(*pro, lo, hi);
+        delete pro;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the lower edge of the first and the upper edge of the last bin
+// of the histogram h returned by GetRangeX
+//
+void MH::GetRangeUserX(const TH1 &h, Axis_t &lo, Axis_t &hi)
+{
+    Int_t f, l;
+    GetRangeX(h, f, l);
+
+    lo = h.GetXaxis()->GetBinLowEdge(f);
+    hi = h.GetXaxis()->GetBinLowEdge(l+1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the lower edge of the first and the upper edge of the last bin
+// of the histogram h returned by GetRangeY
+//
+void MH::GetRangeUserY(const TH1 &h, Axis_t &lo, Axis_t &hi)
+{
+    Int_t f, l;
+    GetRangeY(h, f, l);
+
+    lo = h.GetYaxis()->GetBinLowEdge(f);
+    hi = h.GetYaxis()->GetBinLowEdge(l+1);
+}
+
+// --------------------------------------------------------------------------
+//
+// See MTask::PrintSkipped
+//
+void MH::PrintSkipped(UInt_t n, const char *str)
+{
+    *fLog << " " << setw(7) << n;
+    if (GetNumExecutions()>0)
+    {
+        *fLog << " (" << MString::Format("%5.1f", 100.*n/GetNumExecutions());
+        *fLog << "%)" << str << endl;
+    }
+    //*fLog << " Evts skipped: " << str << endl;
+}
+
+#ifdef CreateGradientColorTable
+#error CreateGradientColorTable already defined
+#endif
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,18,00)
+#define CreateGradientColorTable gStyle->CreateGradientColorTable
+#else
+#define CreateGradientColorTable TColor::CreateGradientColorTable
+#endif
+
+// --------------------------------------------------------------------------
+//
+// Calls gStyle->SetPalette. Allowed palettes are:
+//  pretty
+//  deepblue:  darkblue -> lightblue
+//  lightblue: black -> blue -> white
+//  greyscale: black -> white
+//  glow1:     black -> darkred -> orange -> yellow -> white
+//  glow2:
+//  glowsym:   lightblue -> blue -> black -> darkred -> orange -> yellow -> white
+//  redish:    darkred -> lightred
+//  bluish:    darkblue -> lightblue
+//  small1:
+//
+// If the palette name contains 'inv' the order of the colors is inverted.
+//
+// The second argument determines the number of colors for the palette.
+// The default is 50. 'pretty' always has 50 colors.
+//
+// (Remark: Drawing 3D object like TH2D with surf3 allows a maximum
+//          of 99 colors)
+//
+void MH::SetPalette(TString paletteName, Int_t ncol)
+{
+    Bool_t found=kFALSE;
+
+    paletteName.ToLower();
+
+    const Bool_t inverse = paletteName.Contains("inv");
+
+    if (paletteName.Contains("pretty"))
+    {
+        gStyle->SetPalette(1, 0);
+        ncol=50;
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("deepblue"))
+    {
+        Double_t s[5] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
+        Double_t r[5] = { 0.00, 0.09, 0.18, 0.09, 0.00 };
+        Double_t g[5] = { 0.01, 0.02, 0.39, 0.68, 0.97 };
+        Double_t b[5] = { 0.17, 0.39, 0.62, 0.79, 0.97 };
+        CreateGradientColorTable(5, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("lightblue"))
+    {
+        Double_t s[5] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
+        Double_t r[5] = { 0.00, 0.09, 0.18, 0.09, 0.00 };
+        Double_t g[5] = { 0.00, 0.02, 0.40, 0.70, 1.00 };
+        Double_t b[5] = { 0.00, 0.27, 0.51, 0.81, 1.00 };
+        CreateGradientColorTable(5, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("greyscale"))
+    {
+        double s[2] = {0.00, 1.00};
+        double r[2] = {0.00, 1.00};
+        double g[2] = {0.00, 1.00};
+        double b[2] = {0.00, 1.00};
+        CreateGradientColorTable(2, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("glow1"))
+    {
+        double s[5] = {0., 0.10, 0.45, 0.75, 1.00};
+        double r[5] = {0., 0.35, 0.85, 1.00, 1.00};
+        double g[5] = {0., 0.10, 0.20, 0.73, 1.00};
+        double b[5] = {0., 0.03, 0.06, 0.00, 1.00};
+        CreateGradientColorTable(5, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("glow2"))
+    {
+        double s[4] = {0.00, 0.50, 0.75, 1.00};
+        double r[4] = {0.24, 0.67, 1.00, 1.00};
+        double g[4] = {0.03, 0.04, 0.80, 1.00};
+        double b[4] = {0.03, 0.04, 0.00, 1.00};
+        CreateGradientColorTable(4, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("glowsym"))
+    {
+        double s[8] = {0.00, 0.17, 0.39, 0.50, 0.55, 0.72, 0.88, 1.00};
+        double r[8] = {0.09, 0.18, 0.09, 0.00, 0.35, 0.85, 1.00, 1.00};
+        double g[8] = {0.70, 0.40, 0.02, 0.00, 0.10, 0.20, 0.73, 1.00};
+        double b[8] = {0.81, 0.51, 0.27, 0.00, 0.03, 0.06, 0.00, 1.00};
+        CreateGradientColorTable(8, s, r, g, b, ncol);
+        found=kTRUE;
+    }/*
+    if (paletteName.Contains("glows2"))
+    {
+        double s[10] = {0.00, 0.17, 0.35, 0.50, 0.65, 0.73, 0.77, 0.85, 0.92, 1.00};
+        double r[10] = {0.09, 0.18, 0.09, 0.00, 0.00, 0.20, 0.55, 0.85, 1.00, 1.00};
+        double g[10] = {0.81, 0.51, 0.27, 0.00, 0.00, 0.05, 0.10, 0.20, 0.73, 1.00};
+        double b[10] = {0.70, 0.40, 0.02, 0.00, 0.27, 0.40, 0.35, 0.16, 0.03, 1.00};
+        gStyle->CreateGradientColorTable(10, s, r, g, b, ncol);
+        found=kTRUE;
+    }*/
+
+    if (paletteName.Contains("redish"))
+    {
+        double s[3] = {0., 0.5, 1.};
+        double r[3] = {0., 1.0, 1.};
+        double g[3] = {0., 0.0, 1.};
+        double b[3] = {0., 0.0, 1.};
+        CreateGradientColorTable(3, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("bluish"))
+    {
+        double s[3] = {0., 0.5, 1.};
+        double r[3] = {0., 0.0, 1.};
+        double g[3] = {0., 0.0, 1.};
+        double b[3] = {0., 1.0, 1.};
+        CreateGradientColorTable(3, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (paletteName.Contains("small1"))
+    {
+        double s[4] = {0.00, 0.50, 0.95, 1.};
+        double r[4] = {0.04, 0.28, 0.98, 1.};
+        double g[4] = {0.28, 0.93, 0.03, 1.};
+        double b[4] = {0.79, 0.11, 0.03, 1.};
+        CreateGradientColorTable(4, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+    if (paletteName.Contains("pepe"))
+    {
+        double s[5] = {0.0, 0.6, 0.7, 0.9, 1.0 };
+        double r[5] = {0.1, 0.1, 1.0, 1.0, 1.0 };
+        double g[5] = {0.1, 0.1, 0.0, 1.0, 1.0 };
+        double b[5] = {0.2, 0.7, 0.0, 0.3, 0.9 };
+        CreateGradientColorTable(5, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+    if (paletteName.Contains("temp"))
+    {
+        Double_t s[7] = { 0.00, 0.30, 0.45, 0.75, 0.88, 0.95, 1.00 };
+        Double_t r[7] = { 0.00, 0.00, 0.30, 0.60, 1.00, 1.00, 1.00 };
+        Double_t g[7] = { 0.00, 0.00, 0.00, 0.00, 0.20, 1.00, 1.00 };
+        Double_t b[7] = { 0.10, 0.60, 0.30, 0.00, 0.20, 0.00, 1.00 };
+        CreateGradientColorTable(7, s, r, g, b, ncol);
+        found=kTRUE;
+    }
+
+    if (inverse)
+    {
+        TArrayI c(ncol);
+        for (int i=0; i<ncol; i++)
+            c[ncol-i-1] = gStyle->GetColorPalette(i);
+        gStyle->SetPalette(ncol, c.GetArray());
+    }
+
+    if (!found)
+        gLog << warn << "MH::SetPalette: Palette " << paletteName << " unknown... ignored." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Unfortunately in TH1::GetObjectInfo the buffer is just 64 characters
+// which is sometimes to small. This is just a copy of the code but the
+// buffer has been increased to 128 which should fairly be enough.
+//
+//  Necessary for root <= 5.22/00
+//
+char *MH::GetObjectInfoH(Int_t px, Int_t py, const TH1 &h)
+{
+   const TH1 *fH = &h;
+   const TAxis *fXaxis = h.GetXaxis();
+   const TAxis *fYaxis = h.GetYaxis();
+
+   //   Redefines TObject::GetObjectInfo.
+   //   Displays the histogram info (bin number, contents, integral up to bin
+   //   corresponding to cursor position px,py
+
+   if (!gPad) return (char*)"";
+
+   static char info[128];
+   Double_t x  = gPad->PadtoX(gPad->AbsPixeltoX(px));
+   Double_t y  = gPad->PadtoY(gPad->AbsPixeltoY(py));
+   Double_t x1 = gPad->PadtoX(gPad->AbsPixeltoX(px+1));
+   const char *drawOption = fH->GetDrawOption();
+   Double_t xmin, xmax, uxmin,uxmax;
+   Double_t ymin, ymax, uymin,uymax;
+   if (fH->GetDimension() == 2) {
+      if (gPad->GetView() || strncmp(drawOption,"cont",4) == 0
+                          || strncmp(drawOption,"CONT",4) == 0) {
+         uxmin=gPad->GetUxmin();
+         uxmax=gPad->GetUxmax();
+         xmin = fXaxis->GetBinLowEdge(fXaxis->GetFirst());
+         xmax = fXaxis->GetBinUpEdge(fXaxis->GetLast());
+         x = xmin +(xmax-xmin)*(x-uxmin)/(uxmax-uxmin);
+         uymin=gPad->GetUymin();
+         uymax=gPad->GetUymax();
+         ymin = fYaxis->GetBinLowEdge(fYaxis->GetFirst());
+         ymax = fYaxis->GetBinUpEdge(fYaxis->GetLast());
+         y = ymin +(ymax-ymin)*(y-uymin)/(uymax-uymin);
+      }
+   }
+   Int_t binx,biny,binmin,binx1;
+   if (gPad->IsVertical()) {
+      binx   = fXaxis->FindFixBin(x);
+      binmin = fXaxis->GetFirst();
+      binx1  = fXaxis->FindFixBin(x1);
+      // special case if more than 1 bin in x per pixel
+      if (binx1-binx>1 && fH->GetDimension() == 1) {
+         Double_t binval=fH->GetBinContent(binx);
+         Int_t binnear=binx;
+         for (Int_t ibin=binx+1; ibin<binx1; ibin++) {
+            Double_t binvaltmp = fH->GetBinContent(ibin);
+            if (TMath::Abs(y-binvaltmp) < TMath::Abs(y-binval)) {
+               binval=binvaltmp;
+               binnear=ibin;
+            }
+         }
+         binx = binnear;
+      }
+   } else {
+      x1 = gPad->PadtoY(gPad->AbsPixeltoY(py+1));
+      binx   = fXaxis->FindFixBin(y);
+      binmin = fXaxis->GetFirst();
+      binx1  = fXaxis->FindFixBin(x1);
+      // special case if more than 1 bin in x per pixel
+      if (binx1-binx>1 && fH->GetDimension() == 1) {
+         Double_t binval=fH->GetBinContent(binx);
+         Int_t binnear=binx;
+         for (Int_t ibin=binx+1; ibin<binx1; ibin++) {
+            Double_t binvaltmp = fH->GetBinContent(ibin);
+            if (TMath::Abs(x-binvaltmp) < TMath::Abs(x-binval)) {
+               binval=binvaltmp;
+               binnear=ibin;
+            }
+         }
+         binx = binnear;
+      }
+   }
+   if (fH->GetDimension() == 1) {
+      Double_t integ = 0;
+      for (Int_t bin=binmin;bin<=binx;bin++) {integ += fH->GetBinContent(bin);}
+      sprintf(info,"(x=%g, y=%g, binx=%d, binc=%g, Sum=%g)",x,y,binx,fH->GetBinContent(binx),integ);
+   } else {
+      biny = fYaxis->FindFixBin(y);
+      sprintf(info,"(x=%g, y=%g, binx=%d, biny=%d, binc=%g)",x,y,binx,biny,fH->GetCellContent(binx,biny));
+   }
+   return info;
+}
+
+// --------------------------------------------------------------------------
+//
+// Unfortunately in TProfile::GetObjectInfo the buffer is just 64 characters
+// which is sometimes to small. This is just a copy of the code but the
+// buffer has been increased to 128 which should fairly be enough.
+//
+//  Necessary for root <= 5.22/00
+//
+char *MH::GetObjectInfoP(Int_t px, Int_t py, const TProfile &p)
+{
+    if (!gPad) return (char*)"";
+    static char info[128];
+    Double_t x  = gPad->PadtoX(gPad->AbsPixeltoX(px));
+    Double_t y  = gPad->PadtoY(gPad->AbsPixeltoY(py));
+    Int_t binx   = p.GetXaxis()->FindFixBin(x);
+    sprintf(info,"(x=%g, y=%g, binx=%d, binc=%g, bine=%g, binn=%d)", x, y, binx, p.GetBinContent(binx), p.GetBinError(binx), (Int_t)p.GetBinEntries(binx));
+    return info;
+}
+
+// --------------------------------------------------------------------------
+//
+// Unfortunately TH1::GetObjectInfo and TProfile::GetObjectInfo can
+// result in buffer ovwerflows therefor we have to re-implement these
+// function by our own.
+//
+//  Necessary for root <= 5.22/00
+//
+char *MH::GetObjectInfo(Int_t px, Int_t py, const TObject &o)
+{
+    if (!o.InheritsFrom(TH1::Class()))
+        return o.GetObjectInfo(px, py);
+
+    if (o.InheritsFrom(TProfile::Class()))
+        return GetObjectInfoP(px, py, static_cast<const TProfile&>(o));
+
+    if (o.InheritsFrom("MHCamera"))
+        return o.GetObjectInfo(px, py);
+
+    if (o.InheritsFrom(TH1::Class()))
+        return GetObjectInfoH(px, py, static_cast<const TH1&>(o));
+
+    return const_cast<char*>("MH::GetObjectInfo: unknown class.");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the pad-range such that at the smallest width it is still
+// two times max and that the displayed "pixels" (i.e. its coordinate
+// system) have the width to height ratio of aspect.
+//
+void MH::SetPadRange(Float_t max, Float_t aspect)
+{
+    if (!gPad)
+        return;
+
+    const Float_t w = gPad->GetWw();
+    const Float_t h = gPad->GetWh();
+
+    if (w>aspect*h)
+    {
+        const Double_t dx = ((w/h-aspect)/2+1)*max;
+        gPad->Range(-dx, -max, dx, max);
+    }
+    else
+    {
+        const Double_t dy = ((h/w-1./aspect)/2+1)*max;
+        gPad->Range(-max, -dy, max, dy);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the range of a pad in a way that the coordinates fit into the pad
+// without abberation.
+//
+void MH::SetPadRange(Float_t x0, Float_t y0, Float_t x1, Float_t y1)
+{
+    if (!gPad)
+        return;
+
+    const Float_t w = x1-x0;                              // Width  in user coordinates
+    const Float_t h = y1-y0;                              // Hieght in user coordinates
+
+    const Float_t ww = gPad->GetWw()*gPad->GetAbsWNDC();  // Width  of pad in pixels
+    const Float_t hh = gPad->GetWh()*gPad->GetAbsHNDC();  // Height of pad in pixels
+
+    if (ww/hh > w/h)
+    {
+        const Double_t dx = (ww/hh-w/h)/2*h;
+
+        gPad->Range(x0-dx, y0, x1+dx, y1);
+    }
+    else
+    {
+        const Double_t dy = (hh/ww-h/w)/2*w;
+
+        gPad->Range(x0, y0-dy, x1, y1+dy);
+    }
+}
Index: branches/Mars_McMismatchStudy/mhbase/MH.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MH.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MH.h	(revision 17960)
@@ -0,0 +1,162 @@
+#ifndef MARS_MH
+#define MARS_MH
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TH1;
+class TH1I;
+class TH1D;
+class TH2;
+class TH3;
+class TAxis;
+class TArrayF;
+class TArrayD;
+class MArrayF;
+class MArrayD;
+class TCanvas;
+class TProfile;
+
+class MBinning;
+class MParList;
+#include <TH2.h>
+#include <TH3.h>
+class MH : public MParContainer
+{
+private:
+    Byte_t fSerialNumber;   // Serial number (eg of telecope)
+    UInt_t fNumExecutions;  // Number of calls to Fill function
+
+    static MBinning GetBinningForLabels(TAxis &x, const MBinning *bins);
+    static void RestoreBinningForLabels(TAxis &x);
+
+public:
+    MH(const char *name=NULL, const char *title=NULL);
+
+    virtual void SetSerialNumber(Byte_t num) { fSerialNumber = num; }
+    Byte_t  GetSerialNumber() const { return fSerialNumber; }
+    TString AddSerialNumber(const char *str) const { TString s(str); if (fSerialNumber==0) return s; s += ";"; s += fSerialNumber; return s; }
+    TString AddSerialNumber(const TString &str) const { return AddSerialNumber((const char*)str); }
+
+    UInt_t GetNumExecutions() const { return fNumExecutions; }
+    void SetNumExecutions(UInt_t n) { fNumExecutions=n; }
+
+    void PrintSkipped(UInt_t n, const char *str);
+
+    Bool_t OverwritesDraw(TClass *cls=NULL) const;
+
+    virtual Bool_t SetupFill(const MParList *) { return kTRUE; }
+    virtual Bool_t ReInit(MParList *) { return kTRUE; }
+    virtual Int_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) const;
+
+    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);
+
+    static void RemoveFromPad(const char *name);
+
+    // Functions to applay new binnings to histograms
+    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 CopyBinning(const TH1 &x, TH1 &h);
+
+    static Bool_t ApplyBinning(const MParList &plist, const TString x, TH1 &h);
+    static Bool_t ApplyBinning(const MParList &plist, const TString x, TString y, TH2 &h);
+    static Bool_t ApplyBinning(const MParList &plist, const TString x, TString y, TString z, TH3 &h);
+
+    // Warpper functions not to break macros (new functions take references)
+    static void SetBinning(TH1 *h, const MBinning *binsx) { SetBinning(*h, *binsx); }
+    static void SetBinning(TH2 *h, const MBinning *binsx, const MBinning *binsy) { SetBinning(*h, *binsx, *binsy); }
+    static void SetBinning(TH3 *h, const MBinning *binsx, const MBinning *binsy, const MBinning *binsz) { SetBinning(*h, *binsx, *binsy, *binsz); }
+
+    static void SetBinning(TH1 *h, const TArrayD &binsx) { SetBinning(*h, binsx); }
+    static void SetBinning(TH2 *h, const TArrayD &binsx, const TArrayD &binsy) { SetBinning(*h, binsx, binsy); }
+    static void SetBinning(TH3 *h, const TArrayD &binsx, const TArrayD &binsy, const TArrayD &binsz)  { SetBinning(*h, binsx, binsy, binsz); }
+
+    static void SetBinning(TH1 *h, const TAxis *binsx) { SetBinning(*h, *binsx); }
+    static void SetBinning(TH2 *h, const TAxis *binsx, const TAxis *binsy) { SetBinning(*h, *binsx, *binsy); }
+    static void SetBinning(TH3 *h, const TAxis *binsx, const TAxis *binsy, const TAxis *binsz) { SetBinning(*h, *binsx, *binsy, *binsz); }
+
+    static Bool_t ApplyBinning(const MParList &plist, TString x, TH1 *h) { return ApplyBinning(plist, x, *h); }
+    static Bool_t ApplyBinning(const MParList &plist, TString x, TString y, TH2 *h) { return ApplyBinning(plist, x, y, *h); }
+    static Bool_t ApplyBinning(const MParList &plist, TString x, TString y, TString z, TH3 *h) { return ApplyBinning(plist, x, y, z, *h); }
+
+    // Other helpers for histogram treatment
+    static void SetBinomialErrors(TH1 &hres, const TH1 &h1, const TH1 &h2, Double_t c1=1, Double_t c2=1);
+
+    static void RemoveFirstBin(TH1 &h);
+
+    static void    ScaleArray(TArrayD &bins, Double_t f);
+    static TArrayD ScaleAxis(TAxis &axe, Double_t f);
+    static void    ScaleAxis(TH1 &bins, Double_t fx=1, Double_t fy=1, Double_t fz=1);
+
+    static Double_t GetBinCenterLog(const TAxis &axe, Int_t nbin);
+
+    static void DrawSameCopy(const TH1 &hist1, const TH1 &hist2, const TString title);
+    static void DrawSame(TH1 &hist1, TH1 &hist2, const TString title, Bool_t same=kFALSE);
+
+    TObject *Clone(const char *name="") const;
+
+    TObject *DrawClone(Option_t *opt, Int_t w, Int_t h) const;
+    TObject *DrawClone(Option_t *opt="") const
+    {
+        return MH::DrawClone(opt, 625, 440);
+    }
+
+    static TVirtualPad *GetNewPad(TString &opt);
+
+    static void FindGoodLimits(Int_t nbins, Int_t &newbins, Double_t &xmin, Double_t &xmax, Bool_t isInteger);
+    static Double_t GetMinimumGT(const TH1 &h, Double_t gt=0);
+    static Int_t StripZeros(TH1 &h, Int_t nbins);
+
+    static TH1I* ProjectArray(const TArrayF &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    static TH1I* ProjectArray(const TArrayD &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    static TH1I* ProjectArray(const MArrayF &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    static TH1I* ProjectArray(const MArrayD &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    
+    static void GetRangeUser(const TH1 &hist, Axis_t &lo, Axis_t &hi);
+    static void GetRangeUserX(const TH1 &hist, Axis_t &lo, Axis_t &hi);
+    static void GetRangeUserY(const TH1 &hist, Axis_t &lo, Axis_t &hi);
+    static void GetRange(const TH1 &hist, Int_t &lo, Int_t &hi);
+    static void GetRangeX(const TH1 &hist, Int_t &lo, Int_t &hi);
+    static void GetRangeY(const TH1 &hist, Int_t &lo, Int_t &hi);
+
+    static TObject *FindObjectInPad(const char *name, TVirtualPad *pad=NULL);
+
+    static void SetPalette(TString paletteName="pretty", Int_t ncol=50);
+    static void SetPadRange(Float_t max, Float_t aspect=1);
+    static void SetPadRange(Float_t x0, Float_t y0, Float_t x1, Float_t y1);
+
+    static char *GetObjectInfoH(Int_t px, Int_t py, const TH1 &h);
+    static char *GetObjectInfoP(Int_t px, Int_t py, const TProfile &p);
+    static char *GetObjectInfo(Int_t px, Int_t py, const TObject &o);
+    char *GetObjectInfo(Int_t px, Int_t py) const { return MParContainer::GetObjectInfo(px, py); }
+
+    ClassDef(MH, 2) //A base class for Mars histograms
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhbase/MH3.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MH3.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MH3.cc	(revision 17960)
@@ -0,0 +1,1511 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 TH1D, TH2D or TH3D 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"
+//
+// If you want to use a different unit for histogramming use SetScaleX,
+// SetScaleY and SetScaleZ.
+//
+//
+// Binning/Binning  name
+// =====================
+//
+// 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 the binning should have a different name than the histogram name
+// the binning name can be added to the name, eg.:
+//    SetName("MyHistName;MyXBins;MyYBins")
+// Instead of BinningMyHistName[XYZ] the parameter list will be searched
+// for BinningMyXBinning, BinningMyYBins and BinningMyHistNameZ
+//
+// If you don't want to use a MBinning object from the parameter list
+// you can also set one directly, for example
+//    MBinning bins(10, 0, 1);
+//    mh3.SetBinningX(&bins);
+// You must not delete the MBinning object before the class has been
+// PreProcessed.
+//
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given the rule for this axis is used.
+// 2) If the MBinning used for this axis has a non-default Title
+//    (MBinning::HasTitle) this title is used for the corresponding axis
+// 3) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyHist;x[mm];y[cm];Counts");
+//
+//
+// Labels
+// ======
+//
+// To use labels at an axis you have to initialize this for the axis
+// by either calling InitLabels(Labels_t) or setiting a DefaultLabel.
+// For the axis for which the labels have been initialized the
+// number returned by the given corresponding phrase is converted
+// to int with TMath::Nint and used as a label. If you want to replace
+// this id by a named label you can call DefineLabel to do that.
+// Several ids can be replaced by the same label. If you define
+// named labels for every label which was not defined the default
+// is used, if any, otherwise an unnamed label is created.
+//
+// In the case of an axis with labels the axis-title cannot be
+// set via a MBinning, because the MBinning is not evaluated.
+//
+// Please note that for some reason not all combinations of
+// labels, dimensions and weights are available in the root-
+// histogram classes. Please check the MH3::Fill function to see
+// whether your combination is supported.
+//
+//
+// Examples:
+// =========
+//
+//   1) MH3 myhist("MHillas.fLength");
+//      myhist.SetName("MyHist");
+//      myhist.SetScaleX(geomcam.GetConvMm2Deg()); //convert length to degree
+//      MBinning bins("BinningMyHistX", "Title for my x-axis [Hz]");
+//      bins.SetEdges(10, 0, 150);
+//      plist.AddToList(&bins);
+//
+//   2) MH3 myhist("MHillas.fLength");
+//      myhist.SetName("MyHist;MyX");
+//      myhist.SetTitle("Histogram Title;X-Title [mm];Counts");
+//      MBinning bins("BinningMyX");
+//      bins.SetEdges(10, 0, 150);
+//      plist.AddToList(&bins);
+//
+//   3) MH3 myhist("MTriggerPatter.GetUnprescaled");
+//      myhist.SetWeight("1./MRawRunHeader.GetRunLength");
+//      myhist.SetTitle("Rate of the trigger pattern [Hz];Run Number;Trigger Pattern;Rate [Hz]");
+//      myhist.InitLabels(MH3::kLabelsXY);
+//      myhist.DefaultLabelY("UNKNOWN");     // Lvl1
+//      myhist.DefineLabelY( 1, "Trig");     // Lvl1
+//      myhist.DefineLabelY( 2, "Cal");      // Cal
+//      myhist.DefineLabelY( 4, "Trig");     // Lvl2
+//      myhist.DefineLabelY( 8, "Ped");      // Ped
+//
+//
+// Class Version 1:
+// ----------------
+//   - MData      *fData[3];
+//   + MData      *fData[4];
+//
+// Class Version 2:
+// ----------------
+//   - MDataChain *fData[3];        // Object from which the data is filled
+//   + MData      *fData[3];        // Object from which the data is filled
+//
+// Class Version 3:
+// ----------------
+//   - Byte_t   fStyleBits
+//   + MBinning fBins[3]
+//
+// Class Version 5:
+// ----------------
+//   + TFormula *fConversion
+//
+// Class Version 6:
+// ----------------
+//   + MData      *fWeight;
+//
+// Class Version 7:
+// ----------------
+//   +    MData      *fData[4]
+//   +    Double_t    fScale[4]
+//   -    MData      *fData[3]
+//   -    Double_t    fScale[3]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MH3.h"
+
+#include <ctype.h>    // tolower
+#include <stdlib.h>   // atoi (Ubuntu 8.10)
+#include <fstream>
+
+#include <TMath.h>
+#include <TFormula.h>
+
+#include <THashList.h>
+#include <TObjString.h>
+
+//#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include <TH2.h>
+#include <TH3.h>
+#include <TProfile.h>
+#include <TProfile2D.h>
+#include <TProfile3D.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MDataPhrase.h"
+
+ClassImp(MH3);
+
+using namespace std;
+
+const TString MH3::gsDefName  = "MH3";
+const TString MH3::gsDefTitle = "Container for a n-D Mars Histogram";
+
+// --------------------------------------------------------------------------
+//
+// Set fStyleBits to 0, Reset fBins to NULL, fScale to 1, set name and title
+// to gsDefName and gsDefTitle and if fHist!=NULL UseCurrentStyle and
+// SetDirectory(0)
+//
+void MH3::Init()
+{
+    fStyleBits = 0;
+
+    fWeight  = NULL;
+
+    fData[0] = NULL;
+    fData[1] = NULL;
+    fData[2] = NULL;
+    fData[3] = NULL;
+
+    fBins[0] = NULL;
+    fBins[1] = NULL;
+    fBins[2] = NULL;
+
+    fScale[0] = 1;
+    fScale[1] = 1;
+    fScale[2] = 1;
+    fScale[3] = 1;
+
+    fConversion = NULL;
+
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    if (!fHist)
+        return;
+
+    fHist->UseCurrentStyle();
+    fHist->SetDirectory(NULL);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MH3::MH3(const Int_t dim, Type_t type) : fDimension(dim), fHist(NULL)
+{
+    // FIXME?
+    switch (type)
+    {
+    case kHistogram:
+        if (fDimension>3)
+            fDimension=3;
+        break;
+    case kProfile:
+    case kProfileSpread:
+        fDimension = -TMath::Abs(fDimension);
+        if (fDimension<-2)
+            fDimension = -2;
+        break;
+    }
+
+    switch (fDimension)
+    {
+    case 1:
+        fHist = new TH1D;
+        fHist->SetYTitle("Counts");
+        break;
+    case -1:
+        fHist = new TProfile;
+        fHist->SetYTitle("Average");
+        if (type==kProfileSpread)
+            static_cast<TProfile*>(fHist)->SetErrorOption("s");
+        break;
+    case 2:
+        fHist = new TH2D;
+        fHist->SetZTitle("Counts");
+        break;
+    case -2:
+        fHist = new TProfile2D;
+        fHist->SetZTitle("Average");
+        static_cast<TProfile2D*>(fHist)->BuildOptions(0, 0, type==kProfileSpread?"s":"");
+        break;
+    case 3:
+        fHist = new TH3D;
+        break;
+    case -3:
+        fHist = new TProfile2D;
+        fHist->SetZTitle("Average");
+        static_cast<TProfile2D*>(fHist)->BuildOptions(0, 0, type==kProfileSpread?"s":"");
+        break;
+    }
+
+    Init();
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates an TH1D. memberx is filled into the X-bins. For a more detailed
+// description see the class description above.
+//
+MH3::MH3(const char *memberx, Type_t type) : fDimension(1)
+{
+    fHist = new TH1D;
+    fHist->SetYTitle("Counts");
+
+    Init();
+
+    fData[0] = new MDataPhrase(memberx);
+}
+
+// --------------------------------------------------------------------------
+//
+// Adapt a given histogram
+//
+MH3::MH3(const TH1 &h1) : fDimension(1)
+{
+    if (h1.InheritsFrom(TH3::Class()))
+        fDimension = 3;
+    if (h1.InheritsFrom(TH2::Class()))
+        fDimension = 2;
+
+    if (h1.InheritsFrom(TProfile3D::Class()))
+    {
+        fDimension = -3;
+        *fLog << warn << "WARNING - MH3::MH3(TH1&) does not support TProfile3D." << endl;
+    }
+    if (h1.InheritsFrom(TProfile2D::Class()))
+        fDimension = -2;
+    if (h1.InheritsFrom(TProfile::Class()))
+        fDimension = -1;
+
+    fHist = (TH1*)h1.Clone();
+
+    Init(); // Before without SeUseCurrentStyle!
+
+    switch (fDimension)
+    {
+    case 3:
+    case -2:
+        fData[2] = new MDataPhrase(h1.GetZaxis()->GetTitle());
+    case 2:
+    case -1:
+        fData[1] = new MDataPhrase(h1.GetYaxis()->GetTitle());
+    case 1:
+        fData[0] = new MDataPhrase(h1.GetXaxis()->GetTitle());
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates an TH2D. 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, Type_t type)
+    : fDimension(type==kHistogram?2:-1)
+{
+
+    switch (fDimension)
+    {
+    case 2:
+        fHist = static_cast<TH1*>(new TH2D);
+        break;
+    case -1:
+        fHist = static_cast<TH1*>(new TProfile);
+        if (type==kProfileSpread)
+            static_cast<TProfile*>(fHist)->SetErrorOption("s");
+
+        break;
+    }
+
+    fHist->SetZTitle(fDimension>0?"Counts":"Average");
+
+    Init();
+
+    fData[0] = new MDataPhrase(memberx);
+    fData[1] = new MDataPhrase(membery);
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates an TH3D. 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, Type_t type)
+    : fDimension(type==kHistogram?3:-2)
+{
+    switch (fDimension)
+    {
+    case 3:
+        fHist = static_cast<TH1*>(new TH3D);
+        break;
+    case -2:
+        fHist = static_cast<TH1*>(new TProfile2D);
+        static_cast<TProfile2D*>(fHist)->BuildOptions(0, 0, type==kProfileSpread?"s":"");
+    }
+
+    Init();
+
+    fData[0] = new MDataPhrase(memberx);
+    fData[1] = new MDataPhrase(membery);
+    fData[2] = new MDataPhrase(memberz);
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates an TH3D. memberx is filled into the X-bins. membery is filled
+// into the Y-bins. membery is filled into the Z-bins. Weight is used as a
+// weight for the profile histogram. For a more detailed description see the
+// class description above.
+//
+MH3::MH3(const char *memberx, const char *membery, const char *memberz, const char *weight, Type_t type)
+    : fDimension(-3)
+{
+    fHist = static_cast<TH1*>(new TProfile3D);
+    static_cast<TProfile3D*>(fHist)->BuildOptions(0, 0, type==kProfileSpread?"s":"");
+
+    Init();
+
+    fData[0] = new MDataPhrase(memberx);
+    fData[1] = new MDataPhrase(membery);
+    fData[2] = new MDataPhrase(memberz);
+    fData[3] = new MDataPhrase(weight);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histogram
+//
+MH3::~MH3()
+{
+    if (fHist)
+        delete fHist;
+
+    if (fConversion)
+        delete fConversion;
+
+    if (fWeight)
+        delete fWeight;
+
+    for (int i=0; i<4; i++)
+        if (fData[i])
+            delete fData[i];
+
+    for (int i=0; i<3; i++)
+        if (fLabels[i].GetDefault())
+            delete fLabels[i].GetDefault();
+}
+
+// --------------------------------------------------------------------------
+//
+// You can set a weight as a phrase additionally to the one given
+// as an argument to Fill (most likely from MFillH). The two weights
+// are multiplied together.
+//
+void MH3::SetWeight(const char *phrase)
+{
+    if (fWeight)
+        delete fWeight;
+    fWeight = new MDataPhrase(phrase);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a function which is applied to the histogram before it is displayed.
+// Note, that it only effects the displayed histogram.
+//
+//   e.g. SetConversion("sqrt(x)");
+//
+Bool_t MH3::SetConversion(const char *func)
+{
+    if (TString(func).IsNull())
+    {
+        delete fConversion;
+        fConversion = 0;
+        return kTRUE;
+    }
+
+    fConversion = new TFormula;
+
+    // Must have a name otherwise all axis labels disappear like a miracle
+    fConversion->SetName("ConversionFunction");
+    if (fConversion->Compile(func))
+    {
+        *fLog << err << dbginf << "Syntax Error: TFormula::Compile failed for " << func << endl;
+        delete fConversion;
+        fConversion = 0;
+        return kFALSE;
+    }
+
+    gROOT->GetListOfFunctions()->Remove(fConversion);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The axis label is centered and the labeling of the axis is initialized.
+//
+// This function must not be called after any label has been created!
+//
+void MH3::InitLabels(TAxis &x) const
+{
+    x.CenterTitle();
+    x.SetBinLabel(1, "");
+    x.LabelsOption("h");  // FIXME: Is "a" thread safe? (Paint and Fill?)
+    x.GetLabels()->Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Depending on the bits set the InitLabels(TAxis&) function for
+// the corresponding axes are called. In any case the kCanRebin bit
+// is set.
+//
+// This function must not be called after any label has been created!
+//
+void MH3::InitLabels(Labels_t type) const
+{
+    if (!fHist)
+        return;
+
+    if (type&kLabelsX && fHist->GetXaxis())
+        InitLabels(*fHist->GetXaxis());
+
+    if (type&kLabelsY && fHist->GetYaxis())
+        InitLabels(*fHist->GetYaxis());
+
+    if (type&kLabelsZ && fHist->GetZaxis())
+        InitLabels(*fHist->GetZaxis());
+
+    if (type&kLabelsXYZ)
+        fHist->SetBit(TH1::kCanRebin);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the corresponding Labels_t describing for which axis
+// axis-labels are switched on.
+//
+MH3::Labels_t MH3::GetLabels() const
+{
+    UInt_t type = kNoLabels;
+    if (fHist->GetXaxis() && fHist->GetXaxis()->GetLabels())
+        type |= kLabelsX;
+    if (fHist->GetYaxis() && fHist->GetYaxis()->GetLabels())
+        type |= kLabelsY;
+    if (fHist->GetZaxis() && fHist->GetZaxis()->GetLabels())
+        type |= kLabelsZ;
+    return (Labels_t)type;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the LabelsDeflate from the histogram for all axes.
+// LabelsDeflate will just do nothing if the axis has no labels
+// initialized.
+//
+void MH3::DeflateLabels() const
+{
+    fHist->LabelsDeflate("X");
+    fHist->LabelsDeflate("Y");
+    fHist->LabelsDeflate("Z");
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the named label corresponding to the given value
+// and the given axis. The names are defined with the
+// DefineLabel-functions. if no name is defined the value
+// is converted to a string with %d and TMath::Nint.
+// If names are defined, but not for the given value, the default
+// label is returned instead. If no default is defined the
+// %d-converted string is returned.
+//
+const char *MH3::GetLabel(Int_t axe, Double_t val) const
+{
+    const Int_t v = TMath::Nint(val);
+
+    if (fLabels[axe].GetSize())
+    {
+        const char *l = fLabels[axe].GetObjName(v);
+        if (l)
+            return l;
+    }
+
+    return Form("%d", v);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members used by the data chain to be used in
+// MTask::AddBranchToList
+//
+TString MH3::GetDataMember() const
+{
+    TString str=fData[0]->GetDataMember();
+
+    for (int i=1; i<4; i++)
+        if (fData[i])
+        {
+            str += ";";
+            str += fData[i]->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)
+    if (!TestBit(kDoNotReset))
+        fHist->Reset();
+
+    // Tokenize name into name and binnings names
+    TObjArray *tok = fName.Tokenize(";");
+
+    const TString name = (*tok)[0] ? (*tok)[0]->GetName() : fName.Data();
+
+    TString bx = (*tok)[1] ? (*tok)[1]->GetName() : Form("%sX", name.Data());
+    TString by = (*tok)[2] ? (*tok)[2]->GetName() : Form("%sY", name.Data());
+    TString bz = (*tok)[3] ? (*tok)[3]->GetName() : Form("%sZ", name.Data());
+
+    bx.Prepend("Binning");
+    by.Prepend("Binning");
+    bz.Prepend("Binning");
+
+    delete tok;
+
+    MBinning *binsx = NULL;
+    MBinning *binsy = NULL;
+    MBinning *binsz = NULL;
+
+    const Labels_t labels = GetLabels();
+
+    switch (TMath::Abs(fDimension))
+    {
+    case 3:
+        if (fData[2])
+            fHist->SetZTitle(fData[2]->GetTitle());
+        if (!(labels&kLabelsZ))
+        {
+            binsz = fBins[2] ? fBins[2] : (MBinning*)plist->FindObject(bz, "MBinning");
+            if (!binsz)
+            {
+                *fLog << err << dbginf << "MBinning '" << bz << "' not found... aborting." << endl;
+                return kFALSE;
+            }
+            if (binsz->HasTitle())
+                fHist->SetZTitle(binsz->GetTitle());
+            if (binsz->IsLogarithmic())
+                fHist->SetBit(kIsLogz);
+        }
+    case 2:
+        if (fData[1])
+            fHist->SetYTitle(fData[1]->GetTitle());
+        if (!(labels&kLabelsY))
+        {
+            binsy = fBins[1] ? fBins[1] : (MBinning*)plist->FindObject(by, "MBinning");
+            if (!binsy)
+            {
+                *fLog << err << dbginf << "MBinning '" << by << "' not found... aborting." << endl;
+                return kFALSE;
+            }
+            if (binsy->HasTitle())
+                fHist->SetYTitle(binsy->GetTitle());
+            if (binsy->IsLogarithmic())
+                fHist->SetBit(kIsLogy);
+        }
+    case 1:
+        if (fData[0]!=NULL)
+            fHist->SetXTitle(fData[0]->GetTitle());
+        if (!(labels&kLabelsX))
+        {
+            binsx = fBins[0] ? fBins[0] : (MBinning*)plist->FindObject(bx, "MBinning");
+            if (!binsx)
+            {
+                if (fDimension==1)
+                    binsx = (MBinning*)plist->FindObject("Binning"+fName, "MBinning");
+
+                if (!binsx)
+                {
+                    *fLog << err << dbginf << "Neither '" << bx << "' nor 'Binning" << fName << "' found... aborting." << endl;
+                    return kFALSE;
+                }
+            }
+            if (binsx->HasTitle())
+                fHist->SetXTitle(binsx->GetTitle());
+            if (binsx->IsLogarithmic())
+                fHist->SetBit(kIsLogx);
+        }
+    }
+
+    // PreProcess existing fData members
+    for (int i=0; i<4; i++)
+        if (fData[i] && !fData[i]->PreProcess(plist))
+            return kFALSE;
+
+    if (fWeight && !fWeight->PreProcess(plist))
+        return kFALSE;
+
+    TString title(fDimension>0?"Histogram":"Profile");
+    title += " for ";
+    title += name;
+    title += Form(" (%dD)", TMath::Abs(fDimension));
+
+    fHist->SetName(name);
+    fHist->SetTitle(fTitle==gsDefTitle ? title : fTitle);
+    fHist->SetDirectory(0);
+
+    // This is for the case we have set lables
+    const MBinning def(1, 0, 1);
+    if (!binsx)
+        binsx = const_cast<MBinning*>(&def);
+    if (!binsy)
+        binsy = const_cast<MBinning*>(&def);
+    if (!binsz)
+        binsz = const_cast<MBinning*>(&def);
+
+    // set binning
+    switch (TMath::Abs(fDimension))
+    {
+    case 1:
+        SetBinning(*fHist, *binsx);
+        return kTRUE;
+    case 2:
+        SetBinning(static_cast<TH2&>(*fHist), *binsx, *binsy);
+        return kTRUE;
+    case 3:
+        SetBinning(static_cast<TH3&>(*fHist), *binsx, *binsy, *binsz);
+        return kTRUE;
+    }
+
+    *fLog << err << "ERROR - MH3 has " << TMath::Abs(fDimension) << " dimensions!" << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the histogram ant the MH3 container
+//
+void MH3::SetName(const char *name)
+{
+    if (fHist)
+    {
+        if (gPad)
+        {
+            const TString pfx(MString::Format("%sProfX", fHist->GetName()));
+            const TString pfy(MString::Format("%sProfY", fHist->GetName()));
+
+            TProfile *p = 0;
+            if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfx))))
+                p->SetName(MString::Format("%sProfX", name));
+            if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfy))))
+                p->SetName(MString::Format("%sProfY", name));
+        }
+
+        fHist->SetName(name);
+        fHist->SetDirectory(0);
+
+    }
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the histogram ant the MH3 container
+//
+void MH3::SetTitle(const char *title)
+{
+    if (fHist)
+        fHist->SetTitle(title);
+    MParContainer::SetTitle(title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills the one, two or three data members into our histogram
+//
+Int_t MH3::Fill(const MParContainer *par, const Stat_t ww)
+{
+    // Get Information about labels (UInt_t, to supress warning about
+    // unhandeled cases in switch)
+    const UInt_t type = GetLabels();
+
+    // Get values for axis
+    Double_t x=0;
+    Double_t y=0;
+    Double_t z=0;
+    Double_t t=0;
+    Double_t w=ww;
+
+    switch (fDimension)
+    {
+    case -3:
+        t = fData[3]->GetValue()*fScale[3];
+    case -2:
+    case  3:
+        z = fData[2]->GetValue()*fScale[2];
+    case -1:
+    case  2:
+        y = fData[1]->GetValue()*fScale[1];
+    case  1:
+        x = fData[0]->GetValue()*fScale[0];
+    }
+
+    if (fWeight)
+        w *= fWeight->GetValue();
+
+    // If label option is set, convert value to label
+    TString labelx, labely, labelz;
+    if (type&kLabelsX)
+        labelx = GetLabel(0, x);
+    if (type&kLabelsY)
+        labely = GetLabel(1, y);
+    if (type&kLabelsZ)
+        labelz = GetLabel(2, z);
+
+    // Fill histogram
+    switch (fDimension)
+    {
+    case  3:
+        switch (type)
+        {
+        case kNoLabels:
+            static_cast<TH3*>(fHist)->Fill(x,      y,      z,      w);
+            return kTRUE;
+        case kLabelsX:
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,32,01)
+            static_cast<TH3*>(fHist)->Fill(labelx, y,      z);
+#endif
+            return kTRUE;
+        case kLabelsY:
+            static_cast<TH3*>(fHist)->Fill(x,      labely, z,      w);
+            return kTRUE;
+        case kLabelsZ:
+            static_cast<TH3*>(fHist)->Fill(x,      y,      labelz, w);
+            return kTRUE;
+        case kLabelsXY:
+            static_cast<TH3*>(fHist)->Fill(labelx, labely, z,      w);
+            return kTRUE;
+        case kLabelsXZ:
+            static_cast<TH3*>(fHist)->Fill(labelx, y,      labelz, w);
+            return kTRUE;
+        case kLabelsYZ:
+            static_cast<TH3*>(fHist)->Fill(x,      labely, labelz, w);
+            return kTRUE;
+        case kLabelsXYZ:
+            static_cast<TH3*>(fHist)->Fill(labelx, labely, labelz, w);
+            return kTRUE;
+        }
+        break;
+    case  2:
+        switch (type)
+        {
+        case kNoLabels:
+            static_cast<TH2*>(fHist)->Fill(x,      y,      w);
+            return kTRUE;
+        case kLabelsX:
+            static_cast<TH2*>(fHist)->Fill(x,      labely, w);
+            return kTRUE;
+        case kLabelsY:
+            static_cast<TH2*>(fHist)->Fill(labelx, y,      w);
+            return kTRUE;
+        case kLabelsXY:
+            static_cast<TH2*>(fHist)->Fill(labelx, labely, w);
+            return kTRUE;
+        }
+        break;
+    case 1:
+        switch (type)
+        {
+        case kNoLabels:
+            fHist->Fill(x,      w);
+            return kTRUE;
+        case kLabelsX:
+            fHist->Fill(labelx, w);
+            return kTRUE;
+        }
+        break;
+    case -1:
+        switch (type)
+        {
+        case kNoLabels:
+            static_cast<TProfile*>(fHist)->Fill(x,      y, w);
+            return kTRUE;
+        case kLabelsX:
+            static_cast<TProfile*>(fHist)->Fill(labelx, y, w);
+            return kTRUE;
+        }
+        break;
+    case -2:
+        switch (type)
+        {
+        case kNoLabels:
+            static_cast<TProfile2D*>(fHist)->Fill(x,      y,      z, w);
+            return kTRUE;
+        case kLabelsX:
+            static_cast<TProfile2D*>(fHist)->Fill(labelx, y,      z);
+            return kTRUE;
+        case kLabelsY:
+            static_cast<TProfile2D*>(fHist)->Fill(x,      labely, z);
+            return kTRUE;
+        case kLabelsXY:
+            static_cast<TProfile2D*>(fHist)->Fill(labelx, labely, z);
+            return kTRUE;
+        }
+        break;
+    case  -3:
+        switch (type)
+        {
+        case kNoLabels:
+            static_cast<TProfile3D*>(fHist)->Fill(x, y, z, t, w);
+            return kTRUE;
+        default:
+            *fLog << err << "ERROR - Labels not supported in TProfile3D." << endl;
+        }
+        break;
+    }
+
+    *fLog << err << "MH3::Fill: ERROR - A fatal error occured." << endl;
+    return kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+// If an auto range bit is set the histogram range of the corresponding
+// axis is set to show only the non-empty bins (with a single empty bin
+// on both sides)
+//
+Bool_t MH3::Finalize()
+{
+    DeflateLabels();
+
+    Bool_t autorangex=TESTBIT(fStyleBits, 0);
+    Bool_t autorangey=TESTBIT(fStyleBits, 1);
+    //Bool_t autorangez=TESTBIT(fStyleBits, 2);
+
+    Int_t lo, hi;
+    if (autorangex)
+    {
+        GetRangeX(*fHist, lo, hi);
+        fHist->GetXaxis()->SetRange(lo-2, hi+1);
+    }
+    if (autorangey)
+    {
+        GetRangeY(*fHist, lo, hi);
+        fHist->GetYaxis()->SetRange(lo-2, hi+1);
+    }
+    /*
+    if (autorangez)
+    {
+        GetRangeZ(*fHist, lo, hi);
+        fHist->GetZaxis()->SetRange(lo-2, hi+1);
+    }
+    */
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the conversion function to the contents stored in fHist and
+// store the result in h.
+//
+// In the case of a TProfile we keep it a TProfile to keep the mean and
+// rms in y displayed. To get the error correctly we have to reverse
+// the calculation done in TProfile::GetBinError of course.
+//
+void MH3::Convert(TH1 &h) const
+{
+    const Bool_t prof = h.InheritsFrom(TProfile::Class()) || h.InheritsFrom(TProfile2D::Class()) || h.InheritsFrom(TProfile3D::Class());
+
+    for (Int_t z=0; z<=h.GetNbinsZ()+1; z++)
+        for (Int_t y=0; y<=h.GetNbinsY()+1; y++)
+            for (Int_t x=0; x<=h.GetNbinsX()+1; x++)
+            {
+                h.SetBinContent(x, y, z, fConversion->Eval(fHist->GetBinContent(x, y, z)));
+
+                if (prof)
+                    h.SetBinError(x, y, z, TMath::Hypot(fConversion->Eval(fHist->GetBinContent(x, y, z)),
+                                                        fConversion->Eval(fHist->GetBinError(  x, y, z))));
+                else
+                    h.SetBinError(x, y, z, fConversion->Eval(fHist->GetBinError(x, y, z)));
+            }
+
+    TProfile *p1 = dynamic_cast<TProfile*>(fHist);
+    if (p1)
+        for (Int_t i=0; i<p1->GetSize(); i++)
+            static_cast<TProfile&>(h).SetBinEntries(i, p1->GetBinEntries(i)>0 ? 1 : 0);
+
+    TProfile2D *p2 = dynamic_cast<TProfile2D*>(fHist);
+    if (p2)
+        for (Int_t i=0; i<p2->GetSize(); i++)
+            static_cast<TProfile2D&>(h).SetBinEntries(i, p2->GetBinEntries(i)>0 ? 1 : 0);
+
+    TProfile3D *p3 = dynamic_cast<TProfile3D*>(fHist);
+    if (p3)
+        for (Int_t i=0; i<p3->GetSize(); i++)
+            static_cast<TProfile3D&>(h).SetBinEntries(i, p3->GetBinEntries(i)>0 ? 1 : 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// FIXME
+//
+void MH3::Paint(Option_t *o)
+{
+    TProfile *p=0;
+
+    if (TMath::Abs(fDimension)==2)
+        MH::SetPalette("pretty");
+
+    if (fConversion)
+    {
+        TH1 *h = 0;
+        if ((h=dynamic_cast<TH1*>(gPad->FindObject(fHist->GetName()))))
+            Convert(*h);
+    }
+
+    const TString pfx(MString::Format("%sProfX", fHist->GetName()));
+    if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfx))))
+    {
+        Int_t col = p->GetLineColor();
+        p = ((TH2*)fHist)->ProfileX(pfx, -1, -1, "s");
+        p->SetLineColor(col);
+    }
+
+    const TString pfy(MString::Format("%sProfY", fHist->GetName()));
+    if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfy))))
+    {
+        Int_t col = p->GetLineColor();
+        p = ((TH2*)fHist)->ProfileY(pfy, -1, -1, "s");
+        p->SetLineColor(col);
+    }
+/*
+    if (fHist->TestBit(kIsLogx) && fHist->GetEntries()>0) gPad->SetLogx();
+    if (fHist->TestBit(kIsLogy) && fHist->GetEntries()>0) gPad->SetLogy();
+    if (fHist->TestBit(kIsLogz) && fHist->GetEntries()>0) gPad->SetLogz();
+    */
+}
+
+// --------------------------------------------------------------------------
+//
+// If Xmax is < 3000*Xmin SetMoreLogLabels is called. If Xmax<5000
+// the exponent is switched off (SetNoExponent)
+//
+void MH3::HandleLogAxis(TAxis &axe) const
+{
+    if (axe.GetXmax()>3000*axe.GetXmin())
+        return;
+
+    axe.SetMoreLogLabels();
+    if (axe.GetXmax()<5000)
+        axe.SetNoExponent();
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the histogram into it.
+//
+// Possible options are:
+//   PROFX: Draw a x-profile into the histogram (for 2D histograms only)
+//   PROFY: Draw a y-profile into the histogram (for 2D histograms only)
+//   ONLY:  Draw the profile histogram only (for 2D histograms only)
+//   BLUE:  Draw the profile in blue color instead of the histograms
+//          line color
+//
+// If the kIsLog?-Bit is set the axis is displayed lkogarithmically.
+// eg this is set when applying a logarithmic MBinning
+//
+// Be careful: The histogram belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MH3::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(fHist);
+    pad->SetBorderMode(0);
+    pad->SetGridx();
+    pad->SetGridy();
+
+    AppendPad();
+
+    if (fHist->TestBit(kIsLogx))
+    {
+        pad->SetLogx();
+        HandleLogAxis(*fHist->GetXaxis());
+    }
+    if (fHist->TestBit(kIsLogy))
+    {
+        pad->SetLogy();
+        HandleLogAxis(*fHist->GetYaxis());
+    }
+    if (fHist->TestBit(kIsLogz))
+    {
+        pad->SetLogz();
+        HandleLogAxis(*fHist->GetZaxis());
+    }
+
+    fHist->SetFillStyle(4000);
+
+    TString str(opt);
+    str.ToLower();
+    str.ReplaceAll(" ", "");
+
+    if (GetLabels())
+    {
+        if (str.IsNull() && fDimension==2)
+            str = "colz";
+
+        if (str.Contains("box", TString::kIgnoreCase) && fDimension==2)
+            fHist->SetLineColor(kBlue);
+    }
+
+    const Bool_t only  = str.Contains("only")  && TMath::Abs(fDimension)==2;
+    const Bool_t same  = str.Contains("same")  && TMath::Abs(fDimension)<3;
+    const Bool_t blue  = str.Contains("blue")  && TMath::Abs(fDimension)==2;
+    const Bool_t profx = str.Contains("profx") && TMath::Abs(fDimension)==2;
+    const Bool_t profy = str.Contains("profy") && TMath::Abs(fDimension)==2;
+
+    str.ReplaceAll("only",  "");
+    str.ReplaceAll("blue",  "");
+    str.ReplaceAll("profx", "");
+    str.ReplaceAll("profy", "");
+
+    if (same && TMath::Abs(fDimension)==1)
+    {
+        fHist->SetLineColor(kBlue);
+        fHist->SetMarkerColor(kBlue);
+    }
+
+
+    TH1 *h = fHist;
+
+    if (fConversion)
+    {
+        h = static_cast<TH1*>(fHist->Clone());
+
+        h->SetDirectory(0);
+        h->SetBit(kCanDelete);
+
+        Convert(*h);
+    }
+
+    // FIXME: We may have to remove all our own options from str!
+    if (!only)
+        h->Draw(str);
+
+    TProfile *p=0;
+    if (profx)
+    {
+        const TString pfx(MString::Format("%sProfX", h->GetName()));
+
+        if (same && (p=dynamic_cast<TProfile*>(gPad->FindObject(pfx))))
+            *fLog << warn << "TProfile " << pfx << " already in pad." << endl;
+
+        p = ((TH2*)h)->ProfileX(pfx, -1, -1, "s");
+        p->UseCurrentStyle();
+        p->SetLineColor(blue ? kBlue : h->GetLineColor());
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+        p->SetXTitle(h->GetXaxis()->GetTitle());
+        p->SetYTitle(h->GetYaxis()->GetTitle());
+        p->Draw(only&&!same?"":"same");
+    }
+    if (profy)
+    {
+        const TString pfy(MString::Format("%sProfY", h->GetName()));
+
+        if (same && (p=dynamic_cast<TProfile*>(gPad->FindObject(pfy))))
+            *fLog << warn << "TProfile " << pfy << " already in pad." << endl;
+
+        p = ((TH2*)h)->ProfileY(pfy, -1, -1, "s");
+        p->UseCurrentStyle();
+        p->SetLineColor(blue ? kBlue : h->GetLineColor());
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+        p->SetYTitle(h->GetXaxis()->GetTitle());
+        p->SetXTitle(h->GetYaxis()->GetTitle());
+        p->Draw(only&&!same?"":"same");
+    }
+
+    //AppendPad("log");
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MH3::StreamPrimitive(ostream &out) const
+{
+    TString name = GetUniqueName();
+
+    out << "   MH3 " << name << "(\"";
+    out << fData[0]->GetRule() << "\"";
+    if (fDimension>1 || fDimension<0)
+        out << ", \"" << fData[1]->GetRule() << "\"";
+    if (fDimension>2 || fDimension<-1)
+        out << ", \"" << fData[2]->GetRule() << "\"";
+
+    out << ");" << endl;
+
+    if (fName!=gsDefName)
+        out << "   " << name << ".SetName(\"" << fName << "\");" << endl;
+
+    if (fTitle!=gsDefTitle)
+        out << "   " << name << ".SetTitle(\"" << fTitle << "\");" << endl;
+
+    if (fWeight)
+        out << "   " << name << ".SetWeight(\"" << fWeight->GetRule() << "\");" << endl;
+
+    switch (fDimension)
+    {
+    case -3:
+        if (fScale[3]!=1)
+            out << "   " << name << ".SetScaleT(" << fScale[3] << ");" << endl;
+    case -2:
+    case 3:
+        if (fScale[2]!=1)
+            out << "   " << name << ".SetScaleZ(" << fScale[2] << ");" << endl;
+    case -1:
+    case 2:
+        if (fScale[1]!=1)
+            out << "   " << name << ".SetScaleY(" << fScale[1] << ");" << endl;
+    case 1:
+        if (fScale[0]!=1)
+            out << "   " << name << ".SetScaleX(" << fScale[0] << ");" << endl;
+    }
+}
+
+MH3::Type_t MH3::GetType() const
+{
+    switch (fDimension)
+    {
+    case -1:
+        return TString(static_cast<TProfile*>(fHist)->GetErrorOption())=="s" ? kProfileSpread : kProfile;
+    case -2:
+        return TString(static_cast<TProfile2D*>(fHist)->GetErrorOption())=="s" ? kProfileSpread : kProfile;
+    case -3:
+        return TString(static_cast<TProfile3D*>(fHist)->GetErrorOption())=="s" ? kProfileSpread : kProfile;
+    }
+    return kHistogram;
+}
+
+// --------------------------------------------------------------------------
+//
+// Used to rebuild a MH3 object of the same type (data members,
+// dimension, ...)
+//
+MParContainer *MH3::New() const
+{
+    // FIXME: TREAT THE NEW OPTIONS CORRECTLY (PROFILE, LABELS)
+
+    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:
+        case -1:
+            h=new MH3(fData[0]->GetRule(), fData[1]->GetRule(), GetType());
+            break;
+        case 3:
+        case -2:
+            h=new MH3(fData[0]->GetRule(), fData[1]->GetRule(), fData[2]->GetRule(), GetType());
+            break;
+        case -3:
+            h=new MH3(fData[0]->GetRule(), fData[1]->GetRule(), fData[2]->GetRule(), fData[3]->GetRule());
+            break;
+        }
+
+    switch (fDimension)
+    {
+    case -3:
+        h->SetScaleZ(fScale[3]);
+    case -2:
+    case 3:
+        h->SetScaleZ(fScale[2]);
+    case 2:
+    case -1:
+        h->SetScaleY(fScale[1]);
+    case 1:
+        h->SetScaleX(fScale[0]);
+    }
+
+    if (fWeight)
+        h->SetWeight(fWeight->GetRule());
+
+    return h;
+}
+
+// --------------------------------------------------------------------------
+//
+// FIXME
+//
+TString MH3::GetRule(const Char_t axis) const
+{
+    switch (tolower(axis))
+    {
+    case 'x':
+    case 'X':
+        return fData[0] ? fData[0]->GetRule() : TString("");
+    case 'y':
+    case 'Y':
+        return fData[1] ? fData[1]->GetRule() : TString("");
+    case 'z':
+    case 'Z':
+        return fData[2] ? fData[2]->GetRule() : TString("");
+    case 't':
+    case 'T':
+        return fData[3] ? fData[3]->GetRule() : TString("");
+    case 'w':
+    case 'W':
+        return fWeight  ? fWeight->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 (TMath::Abs(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:
+    case -2:
+        binz = axez.FindFixBin(z);
+        if (binz>axez.GetLast() || binz<axez.GetFirst())
+            return -1;
+    case 2:
+    case -1:
+        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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the MObjLookup corresponding to the axis/character.
+// Note that only lower-case charecters (x, y, z) are supported.
+// If for the axis no labels were set, the corresponding
+// InitLabels is called.
+//
+MObjLookup *MH3::GetLabels(char axe)
+{
+    if (!fHist)
+        return 0;
+
+    TAxis *x = 0;
+
+    switch (axe)
+    {
+    case 'x':
+        x = fHist->GetXaxis();
+        break;
+    case 'y':
+        x = fHist->GetYaxis();
+        break;
+    case 'z':
+        x = fHist->GetZaxis();
+        break;
+    }
+
+    if (!x)
+        return 0;
+
+    const Int_t idx = axe-'x';
+
+    if (!x->GetLabels())
+        switch (idx)
+        {
+        case 0:
+            InitLabels(kLabelsX);
+            break;
+        case 1:
+            InitLabels(kLabelsY);
+            break;
+        case 2:
+            InitLabels(kLabelsZ);
+            break;
+        }
+
+    return &fLabels[idx];
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a default label which is used if no other is found in the list
+// of labels. if a default was set already it is overwritten. If the
+// axis has not yet been initialized to use labels it it now.
+//
+void MH3::DefaultLabel(char axe, const char *name)
+{
+    MObjLookup *arr = GetLabels(axe);
+    if (!arr)
+        return;
+
+    if (arr->GetDefault())
+    {
+        delete arr->GetDefault();
+        arr->SetDefault(0);
+    }
+
+    if (name)
+        arr->SetDefault(new TObjString(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Define a name for a label. More than one label can have the same
+// name. If the axis has not yet been initialized to use labels
+// it it now.
+//
+void MH3::DefineLabel(char axe, Int_t label, const char *name)
+{
+    MObjLookup *arr = GetLabels(axe);
+
+    if (!arr || !name)
+        return;
+
+    if (arr->GetObj(label)!=arr->GetDefault())
+        return;
+
+    arr->Add(label, name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Define names for labels, like
+//    1=Trig;2=Cal;4=Ped;8=Lvl2
+// More than one label can have the same name. If the axis has not
+// yet been initialized to use labels it it now.
+//
+// A default cannot be set here. Use DefaultLabel instead.
+//
+void MH3::DefineLabels(char axe, const TString &labels)
+{
+    TObjArray *arr = labels.Tokenize(';');
+
+    for (int i=0; i<arr->GetEntries(); i++)
+    {
+        const char *s = (*arr)[0]->GetName();
+        const char *v = strchr(s, '=');
+
+        if (v)
+            DefineLabel(axe, atoi(s), v+1);
+    }
+
+    delete arr;
+}
+
+void MH3::RecursiveRemove(TObject *obj)
+{
+    if (obj==fHist)
+        fHist = 0;
+
+    MH::RecursiveRemove(obj);
+}
Index: branches/Mars_McMismatchStudy/mhbase/MH3.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MH3.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MH3.h	(revision 17960)
@@ -0,0 +1,184 @@
+#ifndef MARS_MH3
+#define MARS_MH3
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MObjLookup
+#include "MObjLookup.h"
+#endif
+
+class TH1;
+class MData;
+class MBinning;
+class TFormula;
+
+class MH3 : public MH
+{
+public:
+    enum Labels_t {
+        kNoLabels  = 0,
+        kLabelsX   = BIT(0),
+        kLabelsY   = BIT(1),
+        kLabelsZ   = BIT(2),
+        kLabelsXY  = kLabelsX|kLabelsY,
+        kLabelsXZ  = kLabelsX|kLabelsZ,
+        kLabelsYZ  = kLabelsY|kLabelsZ,
+        kLabelsXYZ = kLabelsX|kLabelsY|kLabelsZ,
+    };
+
+    enum Type_t {
+        kHistogram     = 0,
+        kProfile       = 1,
+        kProfileSpread = kProfile | 2,
+    };
+
+    enum {
+        kDoNotReset = BIT(20)
+    };
+
+
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    // Helper for constructor
+    void        Init();
+
+    // Helper for dealing with labeled histograms
+    MObjLookup *GetLabels(char axe);
+    void        InitLabels(TAxis &x) const;
+    void        DeflateLabels() const;
+    Labels_t    GetLabels() const;
+    const char *GetLabel(Int_t axe, Double_t val) const;
+
+    // Get type
+    Type_t GetType() const;
+
+    // Helper for conversion
+    void Convert(TH1 &h) const;
+
+    MObjLookup fLabels[3];       //! Lookup table to conflate and name labels
+
+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
+    MData      *fData[4];        // Object from which the data is filled
+    MData      *fWeight;         // Additional weight
+    MBinning   *fBins[3];        // Binning set omitting the parlist access
+    Double_t    fScale[4];       // Scale for the three axis (eg unit)
+    Byte_t      fStyleBits;      // Set the range of a histogram automatically in Finalize
+
+    TFormula   *fConversion;     // Conversion function for displaying the histogram
+
+    void HandleLogAxis(TAxis &axe) const;
+
+    void StreamPrimitive(std::ostream &out) const;
+
+
+    enum {
+        kIsLogx     = BIT(17),
+        kIsLogy     = BIT(18),
+        kIsLogz     = BIT(19)
+    };
+
+public:
+    MH3(const Int_t dim=0, Type_t type=MH3::kHistogram);
+    MH3(const TH1 &h1);
+    MH3(const char *memberx, Type_t type=MH3::kHistogram);
+    MH3(const char *memberx, const char *membery, Type_t type=MH3::kHistogram);
+    MH3(const char *memberx, const char *membery, const char *memberz, Type_t type=MH3::kHistogram);
+    MH3(const char *memberx, const char *membery, const char *memberz, const char *weight, Type_t type=MH3::kProfile);
+    ~MH3();
+
+    // Setter
+    void SetScaleX(Double_t scale) { fScale[0] = scale; }
+    void SetScaleY(Double_t scale) { fScale[1] = scale; }
+    void SetScaleZ(Double_t scale) { fScale[2] = scale; }
+    void SetScaleT(Double_t scale) { fScale[3] = scale; }
+    void SetScale(Double_t x, Double_t y=1, Double_t z=1, Double_t t=1) { SetScaleX(x); SetScaleY(y); SetScaleZ(z); SetScaleT(t); }
+
+    void SetLogx(Bool_t b=kTRUE) { b ? fHist->SetBit(kIsLogx) : fHist->ResetBit(kIsLogx); }
+    void SetLogy(Bool_t b=kTRUE) { b ? fHist->SetBit(kIsLogy) : fHist->ResetBit(kIsLogy); }
+    void SetLogz(Bool_t b=kTRUE) { b ? fHist->SetBit(kIsLogz) : fHist->ResetBit(kIsLogz); }
+    void SetLog(Bool_t x=kTRUE, Bool_t y=kTRUE, Bool_t z=kTRUE) { SetLogx(x); SetLogy(y); SetLogz(z); }
+
+    void SetAutoRangeX(Bool_t b=kTRUE) { b ? SETBIT(fStyleBits, 0) : CLRBIT(fStyleBits, 0); }
+    void SetAutoRangeY(Bool_t b=kTRUE) { b ? SETBIT(fStyleBits, 1) : CLRBIT(fStyleBits, 1); }
+    void SetAutoRangeZ(Bool_t b=kTRUE) { b ? SETBIT(fStyleBits, 2) : CLRBIT(fStyleBits, 2); }
+    void SetAutoRange(Bool_t x=kTRUE, Bool_t y=kTRUE, Bool_t z=kTRUE) { SetAutoRangeX(x); SetAutoRangeY(y); SetAutoRangeZ(z); }
+
+    void SetBinningX(MBinning *x) { fBins[0] = x; }
+    void SetBinningY(MBinning *y) { fBins[1] = y; }
+    void SetBinningZ(MBinning *z) { fBins[2] = z; }
+    void SetBinnings(MBinning *x=0, MBinning *y=0, MBinning *z=0) { SetBinningX(x); SetBinningY(y); SetBinningZ(z); }
+
+    void Sumw2() const { if (fHist) fHist->Sumw2(); }
+
+    void InitLabels(Labels_t labels) const;
+
+    void DefaultLabel(char axe, const char *name=0);
+    void DefaultLabelX(const char *name=0) { DefaultLabel('x', name); }
+    void DefaultLabelY(const char *name=0) { DefaultLabel('y', name); }
+    void DefaultLabelZ(const char *name=0) { DefaultLabel('z', name); }
+
+    void DefineLabel(char axe, Int_t label=0, const char *name=0);
+    void DefineLabelX(Int_t label, const char *name) { DefineLabel('x', label, name); }
+    void DefineLabelY(Int_t label, const char *name) { DefineLabel('y', label, name); }
+    void DefineLabelZ(Int_t label, const char *name) { DefineLabel('z', label, name); }
+
+    void DefineLabels(char axe, const TString &labels);
+    void DefineLabelsX(const TString &labels) { DefineLabels('x', labels); }
+    void DefineLabelsY(const TString &labels) { DefineLabels('y', labels); }
+    void DefineLabelsZ(const TString &labels) { DefineLabels('z', labels); }
+
+    void SetWeight(const char *phrase);
+
+    Bool_t SetConversion(const char *func="");
+
+    // Getter
+    Int_t GetDimension() const { return TMath::Abs(fDimension); }
+    Int_t GetNbins() const;
+    Int_t FindFixBin(Double_t x, Double_t y=0, Double_t z=0) const;
+
+    TH1 &GetHist() { return *fHist; }
+    const TH1 &GetHist() const { return *fHist; }
+
+    TString GetDataMember() const;
+    TString GetRule(const Char_t axis='x') const;
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    TH1 *GetHistByName(const TString name="") const { return fHist; }
+    TObject *FindObject(const TObject *obj) const { return 0; }
+    TObject *FindObject(const char *name) const
+    {
+        return (TObject*)GetHistByName(name);
+    }
+
+    // MParContainer
+    MParContainer *New() const;
+
+    // TObject
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    const char *GetTitle() const { return fHist ? fHist->GetTitle() : static_cast<const char *>(fTitle); }
+    const TString &GetFullTitle() const { return fTitle; }
+
+    void Draw(Option_t *opt=NULL);
+    void Paint(Option_t *opt="");
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MH3, 7) // Generalized 1/2/3D-histogram for Mars variables
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhbase/MHArray.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MHArray.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MHArray.cc	(revision 17960)
@@ -0,0 +1,773 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <TClass.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.
+//
+Int_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 kERROR;
+    }
+
+    if (fIdx==n)
+        if (!CreateH())
+            return kERROR;
+
+    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: branches/Mars_McMismatchStudy/mhbase/MHArray.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MHArray.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MHArray.h	(revision 17960)
@@ -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);
+    Int_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: branches/Mars_McMismatchStudy/mhbase/MHMatrix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MHMatrix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MHMatrix.cc	(revision 17960)
@@ -0,0 +1,1315 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 (MDataPhrase).
+// 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 <TMath.h>
+
+#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();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Initializes the columns of the matrix with the entries
+//  from a MDataArray
+//
+MHMatrix::MHMatrix(const TMatrix &m, MDataArray *mat, const char *name, const char *title)
+    : fNumRows(m.GetNrows()), fM(m), 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 MDataPhrase.
+// 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)
+{
+    const Int_t idx = fData ? fData->FindRule(rule) : -1;
+    if (idx>=0)
+        return idx;
+
+    if (IsValid(fM))
+    {
+        *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 (IsValid(fM))
+    {
+        *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;
+}
+
+void MHMatrix::AddColumns(const TCollection &list)
+{
+    TIter Next(&list);
+    TObject *obj = 0;
+    while ((obj=Next()))
+        AddColumn(obj->GetName());
+}
+
+
+// --------------------------------------------------------------------------
+//
+// 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 (!IsValid(fM))
+    {
+        fM.ResizeTo(1, fData->GetNumEntries());
+        return;
+    }
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
+    TMatrix m(fM);
+#endif
+
+    // If we exceed ~50MB of memory we start growing slower
+    const Int_t n = fM.GetNrows()>10000000/fM.GetNcols() ? TMath::Nint(fM.GetNrows()*1.2) : fM.GetNrows()*2;
+    fM.ResizeTo(n, 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
+//
+Int_t MHMatrix::Fill(const MParContainer *par, const Stat_t w)
+{
+    AddRow();
+
+    for (int col=0; col<fData->GetNumEntries(); col++)
+        fM(fNumRows-1, col) = (*fData)(col);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Resize the matrix to a number of rows which corresponds to the number of
+// rows which have really been filled with values.
+//
+Bool_t MHMatrix::Finalize()
+{
+    //
+    // It's not a fatal error so we don't need to stop PostProcessing...
+    //
+    if (fData->GetNumEntries()==0 || fNumRows<1)
+        return kTRUE;
+
+    if (fNumRows != fM.GetNrows())
+    {
+        TMatrix m(fM);
+        CopyCrop(fM, m, fNumRows);
+    }
+
+    return kTRUE;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Draw clone of histogram. So that the object can be deleted
+// and the histogram is still visible in the canvas.
+// The cloned object are deleted together with the canvas if the canvas is
+// destroyed. If you want to handle destroying the canvas you can get a
+// pointer to it from this function
+//
+TObject *MHMatrix::DrawClone(Option_t *opt) const
+{
+    TCanvas &c = *MH::MakeDefCanvas(fHist);
+
+    //
+    // This is necessary to get the expected bahviour of DrawClone
+    //
+    gROOT->SetSelectedPad(NULL);
+
+    fHist->DrawCopy(opt);
+
+    TString str(opt);
+    if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileX();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+    if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileY();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+
+    c.Modified();
+    c.Update();
+
+    return &c;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the histogram into it.
+// Be careful: The histogram belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHMatrix::Draw(Option_t *opt)
+{
+    if (!gPad)
+        MH::MakeDefCanvas(fHist);
+
+    fHist->Draw(opt);
+
+    TString str(opt);
+    if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileX();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+    if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileY();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+
+    gPad->Modified();
+    gPad->Update();
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Prints the meaning of the columns and the contents of the matrix.
+// Becareful, this can take a long time for matrices with many rows.
+// Use the option 'size' to print the size of the matrix.
+// Use the option 'cols' to print the culumns
+// Use the option 'data' to print the contents
+//
+void MHMatrix::Print(Option_t *o) const
+{
+    TString str(o);
+
+    *fLog << all << flush;
+
+    if (str.Contains("size", TString::kIgnoreCase))
+    {
+        *fLog << GetDescriptor() << ": NumColumns=" << fM.GetNcols();
+        *fLog << " NumRows=" << fM.GetNrows() << endl;
+    }
+
+    if (!fData && str.Contains("cols", TString::kIgnoreCase))
+        *fLog << "Sorry, no column information available." << endl;
+
+    if (fData && str.Contains("cols", TString::kIgnoreCase))
+    {
+        fData->SetName(fName);
+        fData->Print();
+    }
+
+    if (str.Contains("data", TString::kIgnoreCase))
+        fM.Print();
+}
+
+// --------------------------------------------------------------------------
+//
+const TMatrix *MHMatrix::InvertPosDef()
+{
+    TMatrix m(fM);
+
+    const Int_t rows = m.GetNrows();
+    const Int_t cols = m.GetNcols();
+
+    for (int x=0; x<cols; x++)
+    {
+        Double_t avg = 0;
+        for (int y=0; y<rows; y++)
+            avg += fM(y, x);
+
+        avg /= rows;
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(5,00,00)
+        TMatrixFColumn(m, x) += -avg;
+#else
+        TMatrixColumn(m, x) += -avg;
+#endif
+    }
+
+    TMatrix *m2 = new TMatrix(m, TMatrix::kTransposeMult, m);
+
+    Double_t det;
+    m2->Invert(&det);
+    if (det==0)
+    {
+        *fLog << err << "ERROR - MHMatrix::InvertPosDef failed (Matrix is singular)." << endl;
+        delete m2;
+        return NULL;
+    }
+
+    // m2->Print();
+
+    return m2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculated the distance of vector evt from the reference sample
+// represented by the covariance metrix m.
+//  - If n<0 the kernel method is applied and
+//    -log(sum(epx(-d/h))/n) is returned.
+//  - For n>0 the n nearest neighbors are summed and
+//    sqrt(sum(d)/n) is returned.
+//  - if n==0 all distances are summed
+//
+Double_t MHMatrix::CalcDist(const TMatrix &m, const TVector &evt, Int_t num) const
+{
+    if (num==0) // may later be used for another method
+    {
+        TVector d = evt;
+        d *= m;
+        return TMath::Sqrt(d*evt);
+    }
+
+    const Int_t rows = fM.GetNrows();
+    const Int_t cols = fM.GetNcols();
+
+    TArrayD dists(rows);
+
+    //
+    // Calculate:  v^T * M * v
+    //
+    for (int i=0; i<rows; i++)
+    {
+        TVector col(cols);
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        col = TMatrixRow(fM, i);
+#else
+        col = TMatrixFRow_const(fM, i);
+#endif
+        TVector d = evt;
+        d -= col;
+
+        TVector d2 = d;
+        d2 *= m;
+
+        dists[i] = d2*d; // square of distance
+
+        //
+        // This corrects for numerical uncertanties in cases of very
+        // small distances...
+        //
+        if (dists[i]<0)
+            dists[i]=0;
+    }
+
+    TArrayI idx(rows);
+    TMath::Sort(dists.GetSize(), dists.GetArray(), idx.GetArray(), kFALSE);
+
+    Int_t from = 0;
+    Int_t to   = TMath::Abs(num)<rows ? TMath::Abs(num) : rows;
+    //
+    // This is a zero-suppression for the case a test- and trainings
+    // sample is identical. This would result in an unwanted leading
+    // zero in the array. To suppress also numerical uncertanties of
+    // zero we cut at 1e-5. Due to Rudy this should be enough. If
+    // you encounter problems we can also use (eg) 1e-25
+    //
+    if (dists[idx[0]]<1e-5)
+    {
+        from++;
+        to ++;
+        if (to>rows)
+            to = rows;
+    }
+
+    if (num<0)
+    {
+        //
+        // Kernel function sum (window size h set according to literature)
+        //
+        const Double_t h    = TMath::Power(rows, -1./(cols+4));
+        const Double_t hwin = h*h*2;
+
+        Double_t res = 0;
+        for (int i=from; i<to; i++)
+            res += TMath::Exp(-dists[idx[i]]/hwin);
+
+        return -TMath::Log(res/(to-from));
+    }
+    else
+    {
+        //
+        // Nearest Neighbor sum
+        //
+        Double_t res = 0;
+        for (int i=from; i<to; i++)
+            res += dists[idx[i]];
+
+        return TMath::Sqrt(res/(to-from));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls calc dist. In the case of the first call the covariance matrix
+// fM2 is calculated.
+//  - If n<0 it is divided by (nrows-1)/h while h is the kernel factor.
+//
+Double_t MHMatrix::CalcDist(const TVector &evt, Int_t num)
+{
+    if (!IsValid(fM2))
+    {
+        if (!IsValid(fM))
+        {
+            *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(ostream &out) const
+{
+    Bool_t data = fData && !TestBit(kIsOwner);
+
+    if (data)
+    {
+        fData->SavePrimitive(out);
+        out << endl;
+    }
+
+    out << "   MHMatrix " << GetUniqueName();
+
+    if (data || fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(";
+        if (data)
+            out << "&" << fData->GetUniqueName();
+        if (fName!=gsDefName || fTitle!=gsDefTitle)
+        {
+            if (data)
+                out << ", ";
+            out << "\"" << fName << "\"";
+            if (fTitle!=gsDefTitle)
+                out << ", \"" << fTitle << "\"";
+        }
+    }
+    out << ");" << endl;
+
+    if (fData && TestBit(kIsOwner))
+        for (int i=0; i<fData->GetNumEntries(); i++)
+            out << "   " << GetUniqueName() << ".AddColumn(\"" << (*fData)[i].GetRule() << "\");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+const TArrayI MHMatrix::GetIndexOfSortedColumn(Int_t ncol, Bool_t desc) const
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TMatrixColumn col(fM, ncol);
+#else
+    TMatrixFColumn_const col(fM, ncol);
+#endif
+
+    const Int_t n = fM.GetNrows();
+
+    TArrayF array(n);
+
+    for (int i=0; i<n; i++)
+        array[i] = col(i);
+
+    TArrayI idx(n);
+    TMath::Sort(n, array.GetArray(), idx.GetArray(), desc);
+
+    return idx;
+}
+
+// --------------------------------------------------------------------------
+//
+void MHMatrix::SortMatrixByColumn(Int_t ncol, Bool_t desc)
+{
+    TArrayI idx = GetIndexOfSortedColumn(ncol, desc);
+
+    const Int_t n = fM.GetNrows();
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+
+    TMatrix m(n, fM.GetNcols());
+    for (int i=0; i<n; i++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(m, i) = vold = TMatrixRow(fM, idx[i]);
+#else
+        TMatrixFRow(m, i) = TMatrixFRow_const(fM, idx[i]);
+#endif
+    fM = m;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MHMatrix::Fill(MParList *plist, MTask *read, MFilter *filter)
+{
+    //
+    // Read data into Matrix
+    //
+    const Bool_t is = plist->IsOwner();
+    plist->SetOwner(kFALSE);
+
+    MTaskList tlist;
+    plist->Replace(&tlist);
+
+    MFillH fillh(this);
+
+    tlist.AddToList(read);
+
+    if (filter)
+    {
+        tlist.AddToList(filter);
+        fillh.SetFilter(filter);
+    }
+
+    tlist.AddToList(&fillh);
+
+    //MProgressBar bar;
+    MEvtLoop evtloop("MHMatrix::Fill-EvtLoop");
+    evtloop.SetParList(plist);
+    //evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+        return kFALSE;
+
+    tlist.PrintStatistics();
+
+    plist->Remove(&tlist);
+    plist->SetOwner(is);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the matrix.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MHMatrix::GetDataMember() const
+{
+    return fData ? fData->GetDataMember() : TString("");
+}
+
+// --------------------------------------------------------------------------
+//
+//
+void MHMatrix::ReduceNumberOfRows(UInt_t numrows, const TString opt)
+{
+    UInt_t rows = fM.GetNrows();
+
+    if (rows==numrows)
+    {
+        *fLog << warn << "Matrix has already the correct number of rows..." << endl;
+        return;
+    }
+
+    Float_t ratio = (Float_t)numrows/fM.GetNrows();
+
+    if (ratio>=1)
+    {
+        *fLog << warn << "Matrix cannot be enlarged..." << endl;
+        return;
+    }
+
+    Double_t sum = 0;
+
+    UInt_t oldrow = 0;
+    UInt_t newrow = 0;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+    while (oldrow<rows)
+    {
+        sum += ratio;
+
+        if (newrow<=(unsigned int)sum)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+            TMatrixRow(fM, newrow++) = vold = TMatrixRow(fM, oldrow);
+#else
+            TMatrixFRow(fM, newrow++) = TMatrixFRow_const(fM, oldrow);
+#endif
+
+        oldrow++;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+//  Used in DefRefMatrix to display the result graphically
+//
+void MHMatrix::DrawDefRefInfo(const TH1 &hth, const TH1 &hthd, const TH1 &thsh, Int_t refcolumn)
+{
+    //
+    // Fill a histogram with the distribution after raduction
+    //
+    TH1F hta;
+    hta.SetDirectory(NULL);
+    hta.SetName("hta");
+    hta.SetTitle("Distribution after reduction");
+    CopyBinning(hth, hta);
+
+    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);
+    hth.DrawCopy();   // real histogram before
+
+    th1->cd(2);
+    hta.DrawCopy();   // histogram after
+
+    th1->cd(3);
+    hthd.DrawCopy();  // correction factors
+
+    th1->cd(4);
+    thsh.DrawCopy();  // target
+}
+
+// ------------------------------------------------------------------------
+//
+//  Resizes th etarget matrix to rows*source.GetNcol() and copies
+//  the data from the first (n)rows or the source into the target matrix.
+//
+void MHMatrix::CopyCrop(TMatrix &target, const TMatrix &source, Int_t rows)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector v(source.GetNcols());
+#endif
+    target.ResizeTo(rows, source.GetNcols());
+    for (Int_t ir=0; ir<rows; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(target, ir) = v = TMatrixRow(source, ir);
+#else
+        TMatrixFRow(target, ir) = TMatrixFRow_const(source, ir);
+#endif
+}
+
+// ------------------------------------------------------------------------
+//
+// Define the reference matrix
+//   refcolumn  number of the column (starting at 0) containing the variable,
+//              for which a target distribution may be given;
+//   thsh       histogram containing the target distribution of the variable
+//   nmaxevts   the number of events the reference matrix should have after 
+//              the renormalization
+//   rest       a TMatrix conatining the resulting (not choosen)
+//              columns of the primary matrix. Maybe NULL if you
+//              are not interested in this
+//
+Bool_t MHMatrix::DefRefMatrix(const UInt_t refcolumn, const TH1F &thsh,
+                              Int_t nmaxevts, TMatrix *rest)
+{
+    if (!IsValid(fM))
+    {
+        *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");
+    CopyBinning(thsh, hth);
+    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");
+    CopyBinning(thsh, hthd);
+    hthd.SetDirectory(NULL);
+    hthd.Divide(&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());
+#if ROOT_VERSION_CODE > ROOT_VERSION(5,00,00)
+    v = TMatrixFColumn_const(fM, refcolumn);
+#else
+    v = TMatrixColumn(fM, refcolumn);
+#endif
+    //v += -frombin;
+    //v *= 1/dbin;
+
+    //
+    // select events (distribution after renormalization)
+    //
+    Int_t ir;
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+    for (ir=0; ir<nrows; ir++)
+    {
+        // const Int_t indref = (Int_t)v(ind[ir]);
+        const Int_t indref = hthd.FindBin(v(ind[ir])) - 1;
+        cumulweight[indref] += hthd.GetBinContent(indref+1);
+        if (cumulweight[indref]<=0.5)
+        {
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+            TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+            TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+            continue;
+        }
+
+        cumulweight[indref] -= 1.;
+        if (++evtcount1 >=  nmaxevts)
+            break;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mnewtmp, evtcount1) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mnewtmp, evtcount1) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+    }
+
+    for (/*empty*/; ir<nrows; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+
+    //
+    // reduce size
+    //
+    // matrix fM having the requested distribution
+    // and the requested number of rows;
+    // this is the matrix to be used in the g/h separation
+    //
+    CopyCrop(fM, mnewtmp, evtcount1);
+    fNumRows = evtcount1;
+
+    if (evtcount1 < nmaxevts)
+        *fLog << warn << "Reference sample contains less events (" << evtcount1 << ") than requested (" << nmaxevts << ")" << endl;
+
+    if (TestBit(kEnableGraphicalOutput))
+        DrawDefRefInfo(hth, hthd, thsh, refcolumn);
+
+    if (rest)
+        CopyCrop(*rest, mrest, evtcount2);
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns a array containing randomly sorted indices
+//
+void MHMatrix::GetRandomArrayI(TArrayI &ind) const
+{
+    const Int_t rows = ind.GetSize();
+
+    TArrayF ranx(rows);
+
+    TRandom3 rnd(0);
+    for (Int_t i=0; i<rows; i++)
+        ranx[i] = rnd.Rndm(i);
+
+    TMath::Sort(rows, ranx.GetArray(), ind.GetArray(), kTRUE);
+}
+
+// ------------------------------------------------------------------------
+//
+// Define the reference matrix
+//   nmaxevts   maximum number of events in the reference matrix
+//   rest       a TMatrix conatining the resulting (not choosen)
+//              columns of the primary matrix. Maybe NULL if you
+//              are not interested in this
+//
+//              the target distribution will be set
+//              equal to the real distribution; the events in the reference
+//              matrix will then be simply a random selection of the events 
+//              in the original matrix.
+//
+Bool_t MHMatrix::DefRefMatrix(Int_t nmaxevts, TMatrix *rest)
+{
+    if (!IsValid(fM))
+    {
+        *fLog << err << dbginf << "Matrix not initialized" << endl;
+        return kFALSE;
+    }
+
+    if (nmaxevts>fM.GetNrows())
+    {
+      *fLog << dbginf << "No.of requested events (" << nmaxevts 
+            << ") exceeds no.of available events (" << fM.GetNrows() 
+            << ")" << endl;
+        *fLog << dbginf 
+              << "        set no.of requested events = no.of available events" 
+              << endl;
+        nmaxevts = fM.GetNrows();
+    }
+
+    if (nmaxevts<0)
+    {
+        *fLog << err << dbginf << "Number of requested events < 0" << endl;
+        return kFALSE;
+    }
+
+    if (nmaxevts==0)
+        nmaxevts = fM.GetNrows();
+
+    const Int_t nrows = fM.GetNrows();
+    const Int_t ncols = fM.GetNcols();
+
+    //
+    // get random access
+    //
+    TArrayI ind(nrows);
+    GetRandomArrayI(ind);
+
+    //
+    // define  new matrix
+    //
+    Int_t evtcount1 = 0;
+    Int_t evtcount2 = 0;
+
+    TMatrix mnewtmp(nrows, ncols);
+    TMatrix mrest(nrows, ncols);
+
+    //
+    // select events (distribution after renormalization)
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+    for (Int_t ir=0; ir<nmaxevts; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mnewtmp, evtcount1++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mnewtmp, evtcount1++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+
+    for (Int_t ir=nmaxevts; ir<nrows; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+
+    //
+    // reduce size
+    //
+    // matrix fM having the requested distribution
+    // and the requested number of rows;
+    // this is the matrix to be used in the g/h separation
+    //
+    CopyCrop(fM, mnewtmp, evtcount1);
+    fNumRows = evtcount1;
+
+    if (evtcount1 < nmaxevts)
+        *fLog << warn << "The reference sample contains less events (" << evtcount1 << ") than requested (" << nmaxevts << ")" << endl;
+
+    if (!rest)
+        return kTRUE;
+
+    CopyCrop(*rest, mrest, evtcount2);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// overload TOject member function read 
+// in order to reset the name of the object read
+//
+Int_t MHMatrix::Read(const char *name)
+{
+    Int_t ret = TObject::Read(name);
+    SetName(name);
+
+    return ret;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   Column0, Column1, Column2, ..., Column10, ..., Column100, ...
+//
+// Searching stops if the first key isn't found in the TEnv. Empty
+// columns are not allowed
+//
+// eg.
+//     MHMatrix.Column0: cos(MMcEvt.fTelescopeTheta)
+//     MHMatrix.Column1: MHillasSrc.fAlpha
+//
+Int_t MHMatrix::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (IsValid(fM))
+    {
+        *fLog << err << "ERROR - matrix is already in use. Can't add a new column from TEnv... skipped." << endl;
+        return kERROR;
+    }
+
+    if (TestBit(kIsLocked))
+    {
+        *fLog << err << "ERROR - matrix is locked. Can't add new column from TEnv... skipped." << endl;
+        return kERROR;
+    }
+
+    //
+    // Search (beginning with 0) all keys
+    //
+    int i=0;
+    while (1)
+    {
+        TString idx = "Column";
+        idx += i;
+
+        // Output if print set to kTRUE
+        if (!IsEnvDefined(env, prefix, idx, print))
+            break;
+
+        // Try to get the file name
+        TString name = GetEnvValue(env, prefix, idx, "");
+        if (name.IsNull())
+        {
+            *fLog << warn << prefix+"."+idx << " empty." << endl;
+            continue;
+        }
+
+        if (i==0)
+        {
+            if (fData)
+            {
+                *fLog << inf << "Removing all existing columns in " << GetDescriptor() << endl;
+                fData->Delete();
+            }
+            else
+            {
+                fData = new MDataArray;
+                SetBit(kIsOwner);
+            }
+        }
+
+        fData->AddEntry(name);
+        i++;
+    }
+
+    return i!=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// ShuffleEvents. Shuffles the order of the matrix rows.
+// 
+//
+void MHMatrix::ShuffleRows(UInt_t seed)
+{
+    TRandom rnd(seed);
+
+    TVector v(fM.GetNcols());
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector tmp(fM.GetNcols());
+#endif
+    for (Int_t irow = 0; irow<fNumRows; irow++)
+    {
+        const Int_t jrow = rnd.Integer(fNumRows);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        v = TMatrixRow(fM, irow);
+        TMatrixRow(fM, irow) = tmp = TMatrixRow(fM, jrow);
+        TMatrixRow(fM, jrow) = v;
+#else
+        v = TMatrixFRow_const(fM, irow);
+        TMatrixFRow(fM, irow) = TMatrixFRow_const(fM, jrow);
+        TMatrixFRow(fM, jrow) = v;
+#endif
+    }
+
+    *fLog << warn << GetDescriptor() << ": Attention! Matrix rows have been shuffled." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reduces the number of rows to the given number num by cutting out the
+// last rows.
+//
+void MHMatrix::ReduceRows(UInt_t num)
+{
+    if ((Int_t)num>=fM.GetNrows())
+    {
+        *fLog << warn << GetDescriptor() << ": Warning - " << num << " >= rows=" << fM.GetNrows() << endl;
+        return;
+    }
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
+    const TMatrix m(fM);
+#endif
+    fM.ResizeTo(num, fM.GetNcols());
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
+    TVector tmp(fM.GetNcols());
+    for (UInt_t irow=0; irow<num; irow++)
+        TMatrixRow(fM, irow) = tmp = TMatrixRow(m, irow);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove rows which contains numbers not fullfilling TMath::Finite
+//
+Bool_t MHMatrix::RemoveInvalidRows()
+{
+    TMatrix m(fM);
+
+    const Int_t ncol=fM.GetNcols();
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(ncol);
+#endif
+
+    int irow=0;
+
+    for (int i=0; i<m.GetNrows(); i++)
+    {
+#if ROOT_VERSION_CODE > ROOT_VERSION(5,00,00)
+        const TMatrixFRow_const &row = TMatrixFRow_const(m, i);
+#else
+        const TMatrixRow &row = TMatrixRow(m, i);
+#endif
+        // finite (-> math.h) checks for NaN as well as inf
+        int jcol;
+        for (jcol=0; jcol<ncol; jcol++)
+            if (!TMath::Finite(row(jcol)))
+                break;
+
+        if (jcol==ncol)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+            TMatrixRow(fM, irow++) = vold = row;
+#else
+            TMatrixFRow(fM, irow++) = row;
+#endif
+        else
+            *fLog << warn << "Warning - MHMatrix::RemoveInvalidRows: row #" << i<< " removed." << endl;
+    }
+
+    // Do not use ResizeTo (in older root versions this doesn't save the contents
+    ReduceRows(irow);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the row pointed to by fNumRow into TVector v
+//
+void MHMatrix::GetRow(TVector &v) const
+{
+    Int_t ncols = fM.GetNcols();
+
+    v.ResizeTo(ncols);
+
+    while (ncols--)
+        v(ncols) = fM(fRow, ncols);
+}
Index: branches/Mars_McMismatchStudy/mhbase/MHMatrix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MHMatrix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MHMatrix.h	(revision 17960)
@@ -0,0 +1,141 @@
+#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
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+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 IsValid(const TMatrix &m) const
+    {
+        return m.GetNrows()>0 && m.IsValid();
+    }
+
+    Bool_t SetupFill(const MParList *pList);
+
+    Int_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(std::ostream &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(const TMatrix &m, MDataArray *arr, 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);
+    void AddColumns(const TCollection &list);
+
+    //MDataArray *GetColumns() { return fData; }
+    const MDataArray *GetColumns() const { return fData; }
+    MDataArray *GetColumns() { return fData; }
+
+    const TMatrix &GetM() const { return fM; }
+
+    Bool_t IsValid() const { return IsValid(fM); }
+    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); }
+
+    void GetRow(TVector &v) const;
+    void operator>>(TVector &v) const
+    {
+        GetRow(v);
+    }
+
+    Bool_t Fill(MParList *plist, MTask *read, MFilter *filter=NULL);
+
+    TString GetDataMember() const;
+
+    void ReduceNumberOfRows(UInt_t numrows, const TString opt);
+    Bool_t RemoveInvalidRows();
+
+    Int_t Read(const char *name);
+
+    Bool_t DefRefMatrix(const UInt_t refcolumn, const TH1F &thsh,
+                        Int_t nmaxevts=0, TMatrix *mrest=NULL);
+    Bool_t DefRefMatrix(Int_t nmaxevts=0, TMatrix *mrest=NULL);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    void ShuffleRows(UInt_t seed);
+    void ReduceRows(UInt_t num);
+
+    ClassDef(MHMatrix, 1) // Multidimensional Matrix (TMatrix) to store events
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mhbase/MHn.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MHn.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MHn.cc	(revision 17960)
@@ -0,0 +1,655 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHn
+//
+//
+// Initialization
+// --------------
+//
+// MHn is a histogram class which derives from MH as all Mars histogram
+// classes do, i.e. to fill the histogram use MFillH. (Example below)
+//
+// After instantisation of MHn add the histograms of your interest using
+// AddHist. Before the next AddHist is called you can now set the options
+// of your histogram using InitName, InitTitle, SetLog, SetAutoRange,
+// SetScale and SetDrawOption.
+//
+//
+// Layout
+// ------
+//
+// The layout of the histograms on the screen depends on the number of
+// initialized histograms and the option SetLayout. For details see below.
+//
+//  SetLayout(MHn::kSimple)
+//       < default >          SetLayout(MHn::kComplex)
+// ========================= ==========================
+//    +-----------------+
+//    |1                |
+//    |                 |
+//    |                 |
+//    |                 |
+//    |                 |
+//    +-----------------+
+//
+//    +-----------------+        +--------+--------+
+//    |1                |        |1       |2       |
+//    |                 |        |        |        |
+//    +-----------------+        |        |        |
+//    |2                |        |        |        |
+//    |                 |        |        |        |
+//    +-----------------+        +--------+--------+
+//
+//    +--------+--------+        +-----+-----+-----+
+//    |1       |2       |        |1    |3          |
+//    |        |        |        |     |           |
+//    +--------+--------+        +-----+           +
+//    |3       |        |        |2    |           |
+//    |        |        |        |     |           |
+//    +--------+--------+        +-----+-----+-----+
+//
+//    +--------+--------+        +------+----------+
+//    |1       |2       |        |1     |4         |
+//    |        |        |        +------+          |
+//    +--------+--------+        |2     |          |
+//    |3       |4       |        +------+          |
+//    |        |        |        |3     |          |
+//    +--------+--------+        +------+----------+
+//
+//    +-----+-----+-----+        +--------+--------+
+//    |1    |2    |3    |        |1       |2       |
+//    |     |     |     |        +--------+--------|
+//    +-----+-----+-----+        |3       |4       |
+//    |4    |5    |     |        +--------+        |
+//    |     |     |     |        |5       |        |
+//    +-----+-----+-----+        +--------+--------+
+//
+//    +-----+-----+-----+        +--------+--------+
+//    |1    |2    |3    |        |1       |2       |
+//    |     |     |     |        +--------+--------+
+//    +-----+-----+-----+        |3       |4       |
+//    |4    |5    |6    |        +--------+--------+
+//    |     |     |     |        |5       |6       |
+//    +-----+-----+-----+        +--------+--------+
+//
+//
+// For example:
+// ------------
+//    // Instatiate the MHn class with default name and title
+//    MHn hres("Energy2", "Energy Residual (lg E_{est} - lg E_{mc})");
+//
+//    // Initialize your first histogram (here a 2D histogram with x- and y-axis)
+//    hres.AddHist("MMcEvt.fEnergy", "log10(MEnergyEst.fVal)-log10(MMcEvt.fEnergy)");
+//    // Initialize the name of the histogram (ResEmc) and the title of the
+//    // binnings ((here BinningEnergy for x-axis and BinningEnergyResidual for y-axis)
+//    hres.InitName("ResEmc;Energy;EnergyResidual");
+//    // Initialize the title of the histogram and the axis titles
+//    hres.InitTitle(";E_{mc} [GeV];\\Delta lg E;");
+//    // Initialize the draw option for the histogram
+//    hres.SetDrawOption("colz profx");
+//    // for more details on the options and more options see below
+//    // or the class reference of MH3
+//
+//    // Initialize a second histogram
+//    hres.AddHist("MPointingPos.fZd", "log10(MEnergyEst.fVal)-log10(MMcEvt.fEnergy)");
+//    hres.InitName("ResTheta;Theta;EnergyResidual");
+//    hres.InitTitle(";Zd [\\circ];\\Delta lg E;");
+//    hres.SetDrawOption("colz profx");
+//
+//    // Note that only AddHist is mandatory. All other options can be omitted
+//
+//    // Initialize the filling task which can now be added to the tasklist
+//    MFillH fill(&hres);
+//    ...
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHn.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MH3.h"
+#include "MString.h"
+
+ClassImp(MHn);
+
+using namespace std;
+
+MHn::MHn(const char *name, const char *title) : fLayout(kSimple), fNum(0)
+{
+    fName  = name  ? name  : "MHn";
+    fTitle = title ? title : "Generalized histogram class for up to six histograms";
+
+    memset(fHist, 0, 6*sizeof(MH3*));
+}
+
+MHn::~MHn()
+{
+    for (int i=0; i<fNum; i++)
+        if (fHist[i])
+            delete fHist[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// If a histogram with the same name is found, the pad-number with a
+// training underscore is added.
+//
+// FIXME: How do we handle identical names with different axes?
+//
+void MHn::InitHist()
+{
+    TString name = fName;
+
+    for (int i=0; i<fNum; i++)
+        if (name==fHist[i]->GetName())
+        {
+            name += MString::Format("_%d", fNum);
+            break;
+        }
+
+    fHist[fNum]->SetName(fName);
+    fHist[fNum]->SetTitle(fTitle);
+
+    fHist[fNum]->SetAutoRangeX();
+
+    fNum++;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new 1D-MH3 histogram. An internal pointer is set to it, so that
+// InitName and InitTitle can be used for this histogram until a new
+// histogram is added using AddHist
+//
+//  e.g. AddHist("MHillas.fSize")
+//
+Bool_t MHn::AddHist(const char *memberx)
+{
+    if (fNum==8)
+    {
+        *fLog << err << "ERROR - MHn doesn't support more than six histograms... AddHist ignored." << endl;
+        return kFALSE;
+    }
+
+    fHist[fNum] = new MH3(memberx);
+
+    InitHist();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new 2D-MH3 histogram. An internal pointer is set to it, so that
+// InitName and InitTitle can be used for this histogram until a new
+// histogram is added using AddHist
+//
+//  e.g. AddHist("MHillas.fLength", "MHillas.fSize")
+//
+Bool_t MHn::AddHist(const char *memberx, const char *membery, MH3::Type_t type)
+{
+    if (fNum==8)
+    {
+        *fLog << err << "ERROR - MHn doesn't support more than six histograms... AddHist ignored." << endl;
+        return kFALSE;
+    }
+
+    fHist[fNum] = new MH3(memberx, membery, type);
+
+    InitHist();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new 3D-MH3 histogram. An internal pointer is set to it, so that
+// InitName and InitTitle can be used for this histogram until a new
+// histogram is added using AddHist
+//
+//  e.g. AddHist("MHillas.fWidth", "MHillas.fLength", "MHillas.fSize")
+//
+Bool_t MHn::AddHist(const char *memberx, const char *membery, const char *memberz, MH3::Type_t type)
+{
+    if (fNum==8)
+    {
+        *fLog << err << "ERROR - MHn doesn't support more than six histograms... AddHist ignored." << endl;
+        return kFALSE;
+    }
+
+    fHist[fNum] = new MH3(memberx, membery, memberz, type);
+
+    InitHist();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new 3D-MH3 histogram. An internal pointer is set to it, so that
+// InitName and InitTitle can be used for this histogram until a new
+// histogram is added using AddHist
+//
+//  e.g. AddHist("MHillas.fWidth", "MHillas.fLength", "MHillas.fSize", "MWeight.fVal")
+//
+Bool_t MHn::AddHist(const char *memberx, const char *membery, const char *memberz, const char *weight)
+{
+    if (fNum==8)
+    {
+        *fLog << err << "ERROR - MHn doesn't support more than six histograms... AddHist ignored." << endl;
+        return kFALSE;
+    }
+
+    fHist[fNum] = new MH3(memberx, membery, memberz, weight);
+
+    InitHist();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the draw option of the n-th MH3. See MH3 for more details of the
+// meaning of it.
+//
+Bool_t MHn::SetDrawOption(Int_t n, const char *opt)
+{
+    if (n<0 || n>=fNum)
+    {
+        *fLog << err << "ERROR - Histogram " << n << " not yet initialized... SetDrawOption ignored." << endl;
+        return kFALSE;
+    }
+
+    fDrawOption[n] = opt;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the n-th MH3. See MH3 for more details of the meaning
+// of the name. If the given name starts with a semicolon fName is prepend
+// to the string.
+//
+Bool_t MHn::InitName(Int_t n, const char *nam)
+{
+    if (n<0 || n>=fNum)
+    {
+        *fLog << err << "ERROR - Histogram " << n << " not yet initialized... InitName ignored." << endl;
+        return kFALSE;
+    }
+
+    TString name = TString(nam).Strip(TString::kBoth);
+
+    if (name[0]==';')
+        name.Prepend(fName);
+
+    fHist[n]->SetName(name);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the n-th MH3. See MH3 for more details of the meaning
+// of the title. If the given title starts with a semicolon fTitle is prepend
+// to the string.
+//
+Bool_t MHn::InitTitle(Int_t n, const char *tit)
+{
+    if (n<0 || n>=fNum)
+    {
+        *fLog << err << "ERROR - Histogram " << n << " not yet initialized... InitTitle ignored." << endl;
+        return kFALSE;
+    }
+
+    TString title = TString(tit).Strip(TString::kBoth);
+
+    if (title[0]==';')
+        title.Prepend(fTitle);
+
+    fHist[n]->SetTitle(title);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set additional scale factors for the current histogram
+//
+void MHn::SetScale(Double_t x, Double_t y, Double_t z) const
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->SetScale(x, y, z);
+}
+
+// --------------------------------------------------------------------------
+//
+// Enable or disable displaying log-scale for the current histogram.
+// Normally it is retrieved from the corresponding MBinning
+//
+void MHn::SetLog(Bool_t x, Bool_t y, Bool_t z) const
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->SetLog(x, y, z);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the axis range in Finalize automatically to the histogram region
+// containing contents. This is the default for the x-axis.
+// This function can be used to enable this behaviour also for the other
+// axis, or disable it for the x-axis of the current histogram.
+//
+void MHn::SetAutoRange(Bool_t x, Bool_t y, Bool_t z) const
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->SetAutoRange(x, y, z);
+}
+
+// --------------------------------------------------------------------------
+//
+// Call Sumw2 for trhe current histogram, enabling errors.
+//
+void MHn::Sumw2() const
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->Sumw2();
+}
+
+// --------------------------------------------------------------------------
+//
+// Force the given binning(s) for the current histogram. The binnings
+// do not get owned. The user is responsible for deleting them.
+//
+void MHn::SetBinnings(MBinning *x, MBinning *y, MBinning *z) const
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->SetBinnings(x, y, z);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::InitLabels for the current histogram
+//
+void MHn::InitLabels(MH3::Labels_t labels) const
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->InitLabels(labels);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefaultLabelX for the current histogram
+//
+void MHn::DefaultLabelX(const char *name)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefaultLabelX(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefaultLabelY for the current histogram
+//
+void MHn::DefaultLabelY(const char *name)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefaultLabelY(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefaultLabelZ for the current histogram
+//
+void MHn::DefaultLabelZ(const char *name)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefaultLabelZ(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefineLabelX for the current histogram
+//
+void MHn::DefineLabelX(Int_t label, const char *name)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefineLabelX(label, name);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefineLabelY for the current histogram
+//
+void MHn::DefineLabelY(Int_t label, const char *name)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefineLabelY(label, name);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefineLabelZ for the current histogram
+//
+void MHn::DefineLabelZ(Int_t label, const char *name)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefineLabelZ(label, name);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefineLabelsX for the current histogram
+//
+void MHn::DefineLabelsX(const TString &labels)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefineLabelsX(labels);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefineLabelsY for the current histogram
+//
+void MHn::DefineLabelsY(const TString &labels)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefineLabelsY(labels);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::DefineLabelsZ for the current histogram
+//
+void MHn::DefineLabelsZ(const TString &labels)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->DefineLabelsZ(labels);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::SetWeight for the current histogram
+//
+void MHn::SetWeight(const char *phrase)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->SetWeight(phrase);
+}
+
+// --------------------------------------------------------------------------
+//
+// call MH3::SetConversion for the current histogram
+//
+void MHn::SetConversion(const char *func)
+{
+    if (fHist[fNum-1])
+        fHist[fNum-1]->SetConversion(func);
+}
+
+// --------------------------------------------------------------------------
+//
+// Call SetupFill for all initialized histograms
+//
+Bool_t MHn::SetupFill(const MParList *plist)
+{
+    for (int i=0; i<fNum; i++)
+    {
+        TestBit(kDoNotReset) ? fHist[i]->SetBit(kDoNotReset) : fHist[i]->ResetBit(kDoNotReset);
+
+        if (!fHist[i]->SetupFill(plist))
+            return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call Fill for all initialized histograms
+//
+Int_t MHn::Fill(const MParContainer *par, const Stat_t w)
+{
+    for (int i=0; i<fNum; i++)
+    {
+        const Int_t rc = fHist[i]->Fill(par, w);
+        if (rc!=kTRUE)
+            return rc;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call Finalize for all initialized histograms
+//
+Bool_t MHn::Finalize()
+{
+    for (int i=0; i<fNum; i++)
+        if (!fHist[i]->Finalize())
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+void MHn::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    const Bool_t same = TString(opt).Contains("same");
+
+    if (!same)
+    {
+        AppendPad();
+
+        const Int_t id = fNum + fLayout*10;
+
+        switch (id)
+        {
+        case 0:   // 0
+        case 10:  // 0
+            return;
+        case 1:   // 1
+        case 11:  // 1
+            break;
+
+        case 2:   // 2
+            pad->Divide(1,2, 1e-5, 1e-5);
+            break;
+        case 3:   // 3
+            pad->Divide(2,2, 1e-5, 1e-5);
+            delete pad->GetPad(4);
+            break;
+         case 4:   // 4
+            pad->Divide(2,2, 1e-5, 1e-5);
+            break;
+        case 5:   // 5
+            pad->Divide(3,2, 1e-5, 1e-5);
+            delete pad->GetPad(6);
+            break;
+        case 6:   // 6
+            pad->Divide(3,2, 1e-5, 1e-5);
+            break;
+
+        case 12:  // 2
+            pad->Divide(2,1, 1e-5, 1e-5);
+            break;
+        case 13:  // 3
+            pad->Divide(2,2, 1e-5, 1e-5);
+            pad->GetPad(1)->SetPad(0.01, 0.505, 0.33, 0.99);
+            pad->GetPad(2)->SetPad(0.01, 0.01,  0.33, 0.495);
+            pad->GetPad(3)->SetPad(0.34, 0.01,  0.99, 0.99);
+            delete pad->GetPad(4);
+            break;
+        case 14:  // 4
+            pad->Divide(2,2, 1e-5, 1e-5);
+            break;
+        case 15:  // 5
+            pad->Divide(2,3, 1e-5, 1e-5);
+            pad->GetPad(4)->SetPad(0.51, 0.01, 0.99, 0.65);
+            delete pad->GetPad(6);
+            break;
+        case 16:  // 6
+            pad->Divide(2,3);
+            break;
+        }
+    }
+
+    for (int i=0; i<fNum; i++)
+    {
+        TString dopt(fDrawOption[i]);
+        if (same)
+            dopt += " same";
+
+        pad->cd(i+1);
+        fHist[i]->Draw(dopt);
+    }
+}
+
+void MHn::RecursiveRemove(TObject *obj)
+{
+    for (int i=0; i<6; i++)
+    {
+        if (!fHist[i])
+            continue;
+
+        if (obj==fHist[i])
+            fHist[i] = 0;
+        else
+            fHist[i]->RecursiveRemove(obj);
+    }
+
+    MH::RecursiveRemove(obj);
+}
Index: branches/Mars_McMismatchStudy/mhbase/MHn.h
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/MHn.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/MHn.h	(revision 17960)
@@ -0,0 +1,88 @@
+#ifndef MARS_MHn
+#define MARS_MHn
+
+#ifndef MARS_MH3
+#include "MH3.h"
+#endif
+
+class MHn : public MH
+{
+public:
+    enum Layout_t { kSimple, kComplex };
+
+    enum { kDoNotReset = BIT(20) };
+
+protected:
+    MH3    *fHist[6];        // Possible six histograms
+    TString fDrawOption[6];  // Possible corresponding draw options
+
+    Layout_t fLayout;        // Specifier for the layout in the canvas
+
+    Int_t fNum;              // Number of initialized histograms
+
+    void InitHist();
+
+    Bool_t InitName(Int_t n,  const char *name);
+    Bool_t InitTitle(Int_t n, const char *title);
+    Bool_t SetDrawOption(Int_t n, const char *opt);
+
+public:
+    MHn(const char *name=NULL, const char *title=NULL);
+    ~MHn();
+
+    // Setter
+    void SetLayout(Layout_t t) { fLayout = t; }
+    void SetDrawOption(const char *opt) { SetDrawOption(fNum-1, opt); }
+
+    Bool_t AddHist(const char *memberx);
+    Bool_t AddHist(const char *memberx, const char *membery, MH3::Type_t type=MH3::kHistogram);
+    Bool_t AddHist(const char *memberx, const char *membery, const char *memberz, MH3::Type_t type=MH3::kHistogram);
+    Bool_t AddHist(const char *memberx, const char *membery, const char *memberz, const char *weight);
+
+    void InitName(const char *n)  { InitName(fNum-1, n); }
+    void InitTitle(const char *t) { InitTitle(fNum-1, t); }
+
+    // General interfact to MH3
+    void SetScale(Double_t x, Double_t y=1, Double_t z=2) const;
+    void SetLog(Bool_t x=kTRUE, Bool_t y=kTRUE, Bool_t z=kTRUE) const;
+    void SetAutoRange(Bool_t x=kTRUE, Bool_t y=kTRUE, Bool_t z=kTRUE) const;
+    void SetBinnings(MBinning *x=0, MBinning *y=0, MBinning *z=0) const;
+    void Sumw2() const;
+
+    // Interface to labels of MH3
+    void InitLabels(MH3::Labels_t labels) const;
+
+    void DefaultLabelX(const char *name=0);
+    void DefaultLabelY(const char *name=0);
+    void DefaultLabelZ(const char *name=0);
+
+    void DefineLabelX(Int_t label, const char *name);
+    void DefineLabelY(Int_t label, const char *name);
+    void DefineLabelZ(Int_t label, const char *name);
+
+    void DefineLabelsX(const TString &labels);
+    void DefineLabelsY(const TString &labels);
+    void DefineLabelsZ(const TString &labels);
+
+    // Set additonal weights for MH3 
+    void SetWeight(const char *phrase);
+
+    // Set a conversion function for displaying the histogram
+    void SetConversion(const char *func="");
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    // TObject
+    //void SetColors() const;
+    void Draw(Option_t *opt=NULL);
+    //void Paint(Option_t *opt="");
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MHn, 1) // Generalized histogram class for up to six histograms
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhbase/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mhbase/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhbase/Makefile	(revision 17960)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HBase
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mdata
+
+SRCFILES = MFillH.cc \
+           MBinning.cc \
+           MH.cc \
+           MH3.cc \
+	   MHn.cc \
+           MHArray.cc \
+           MHMatrix.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mhcalib/HCalibIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/HCalibIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/HCalibIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mhcalib/HCalibLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/HCalibLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/HCalibLinkDef.h	(revision 17960)
@@ -0,0 +1,25 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHCalibrationCam+;
+#pragma link C++ class MHCalibrationPix+;
+#pragma link C++ class MHCalibrationChargeCam+;
+#pragma link C++ class MHCalibrationChargePix+;
+#pragma link C++ class MHCalibrationChargeBlindCam+;
+#pragma link C++ class MHCalibrationChargeBlindPix+;
+#pragma link C++ class MHCalibrationChargePINDiode+;
+#pragma link C++ class MHCalibrationRelTimeCam+;
+//#pragma link C++ class MHCalibrationTestCam+;
+//#pragma link C++ class MHCalibrationTestTimeCam+;
+#pragma link C++ class MHCalibrationPulseTimeCam+;
+//#pragma link C++ class MHCalibrationHiLoCam+;
+//#pragma link C++ class MHCalibrationHiLoPix+;
+//#pragma link C++ class MHPedestalCam+;
+//#pragma link C++ class MHPedestalPix+;
+
+#pragma link C++ class MHGausEvents+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationCam.cc	(revision 17960)
@@ -0,0 +1,1618 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationCam                                               
+//
+// Base class for camera calibration classes. Incorporates the TOrdCollection's:
+// - fHiGainArray (for calibrated High Gains per pixel)
+// - fLoGainArray (for calibrated Low Gains per pixel) 
+// - fAverageHiGainAreas (for averaged High Gains events per camera area index)
+// - fAverageLoGainAreas (for averaged High Gains events per camera area index)
+// - fAverageHiGainSectors (for averaged High Gains events per camera sector )
+// - fAverageLoGainSectors (for averaged High Gains events per camera sector )
+// These TOrdCollection's are called by their default constructors, thus no objects 
+// are created, until the derived class does so. 
+//
+// The corresponding operators: [],() and the operators GetAverageHiGainArea(), 
+// GetAverageLoGainArea(), GetAverageHiGainSector() and GetAverageLoGainSector() 
+// have to be cast to the corresponding class. It is assumed that all classes 
+// dealing with calibration pixels derive from MHCalibrationPix.
+//
+// The following flag can be set:
+// - SetAverageing() for calculating the event-by-event averages.
+// - SetDebug()      for debug output.
+// - SetLoGain()     for the case that low-gain slices are available, but 
+//                       MRawRunHeader::GetNumLoGainSlices() gives still 0.
+// - SetCheckSize()  for testing the sizes of the f*Arrays in ReInit() if they 
+//                       are coinciding with the equiv. sizes in MGeomCam
+//
+// The flag kLoGain steers if the low-gain signal is treated at all or not.
+// The flag kAverageing steers if the event-by-event averages are treated at all.
+//
+// Class Version 5:
+//  + Double_t fLowerFitLimitHiGain;          // Lower limit for the fit range for the hi-gain hist
+//  + Double_t fUpperFitLimitHiGain;          // Upper limit for the fit range for the hi-gain hist
+//  + Double_t fLowerFitLimitLoGain;          // Lower limit for the fit range for the lo-gain hist
+//  + Double_t fUpperFitLimitLoGain;          // Upper limit for the fit range for the lo-gain hist
+//  + Bool_t   fIsHiGainFitRanges;            // Are high-gain fit ranges defined?
+//  + Bool_t   fIsLoGainFitRanges;            // Are low-gain fit ranges defined?
+//
+// Class Version 5:
+//  + Int_t   fMaxNumEvts;                    // Max Number of events
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationCam.h"
+#include "MHCalibrationPix.h"
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TText.h>
+#include <TPaveText.h>
+#include <TOrdCollection.h>
+#include <TROOT.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+
+ClassImp(MHCalibrationCam);
+
+using namespace std;
+
+const Double_t MHCalibrationCam::fgLowerFitLimitHiGain = 0;
+const Double_t MHCalibrationCam::fgUpperFitLimitHiGain = 0;
+const Double_t MHCalibrationCam::fgLowerFitLimitLoGain = 0;
+const Double_t MHCalibrationCam::fgUpperFitLimitLoGain = 0;
+
+const Int_t   MHCalibrationCam::fgPulserFrequency  = 500;
+const Float_t MHCalibrationCam::fgProbLimit        = 0.0001;
+const Float_t MHCalibrationCam::fgOverflowLimit    = 0.005;
+const Int_t   MHCalibrationCam::fgMaxNumEvts       = 4096;
+
+const TString MHCalibrationCam::gsHistName   = "Hist";
+const TString MHCalibrationCam::gsHistTitle  = "";
+const TString MHCalibrationCam::gsHistXTitle = "";
+const TString MHCalibrationCam::gsHistYTitle = "Nr. events";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Initializes and sets owner of:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+// Initializes:
+// - fPulserFrequency to fgPulserFrequency
+// - fProbLimit       to fgProbLimit
+// - fOverflowLimit   to fgOverflowLimit
+//
+// - SetAveregeing  (kTRUE);
+// - SetDebug       (kFALSE);
+// - SetLoGain      (kTRUE);
+//-  SetOscillations(kTRUE);
+//-  SetSizeCheck   (kTRUE);
+//-  SetInterlaced  (kFALSE);
+//-  SetLowerFitLimitHiGain();
+//-  SetUpperFitLimitHiGain();
+//-  SetLowerFitLimitLoGain();
+//-  SetUpperFitLimitLoGain();
+//
+MHCalibrationCam::MHCalibrationCam(const char *name, const char *title)
+    :  fIsHiGainFitRanges(kFALSE), fIsLoGainFitRanges(kFALSE),
+    fHistName(gsHistName),fHistTitle(gsHistTitle),
+    fHistXTitle(gsHistXTitle),fHistYTitle(gsHistYTitle),
+    fCurrentNumEvts(0), fColor(MCalibrationCam::kNONE),
+    fBadPixels(NULL), fCam(NULL), fGeom(NULL),
+    fRunHeader(NULL)
+{
+
+    fHiGainArray = new TOrdCollection;
+    fHiGainArray->SetOwner();
+
+    fLoGainArray = new TOrdCollection;
+    fLoGainArray->SetOwner();
+
+    fAverageHiGainAreas = new TOrdCollection;
+    fAverageHiGainAreas->SetOwner();
+
+    fAverageLoGainAreas = new TOrdCollection;
+    fAverageLoGainAreas->SetOwner();
+
+    fAverageHiGainSectors = new TOrdCollection;
+    fAverageHiGainSectors->SetOwner();
+
+    fAverageLoGainSectors = new TOrdCollection;
+    fAverageLoGainSectors->SetOwner();
+
+    SetPulserFrequency();
+    SetProbLimit();
+    SetOverflowLimit();
+    SetMaxNumEvts();
+
+    SetAverageing  (kTRUE);
+    SetDebug       (kFALSE);
+    SetLoGain      (kTRUE);
+    SetOscillations(kTRUE);
+    SetSizeCheck   (kTRUE);
+    SetIsReset     (kTRUE);
+
+    SetLowerFitLimitHiGain();
+    SetUpperFitLimitHiGain();
+    SetLowerFitLimitLoGain();
+    SetUpperFitLimitLoGain();
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the TOrdCollection of:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+MHCalibrationCam::~MHCalibrationCam()
+{
+
+  delete fHiGainArray;
+  delete fLoGainArray;
+
+  delete fAverageHiGainAreas;
+  delete fAverageLoGainAreas;
+
+  delete fAverageHiGainSectors;
+  delete fAverageLoGainSectors;
+  /*
+
+  Remove ( fHiGainArray );
+  Remove ( fLoGainArray );
+
+  Remove ( fAverageHiGainAreas );
+  Remove ( fAverageLoGainAreas );
+
+  Remove ( fAverageHiGainSectors );
+  Remove ( fAverageLoGainSectors );
+  */
+
+}
+
+Bool_t MHCalibrationCam::IsLoGain() const
+{
+    if (!fRunHeader)
+        return TESTBIT(fFlags,kLoGain);
+    return TESTBIT(fFlags,kLoGain) && fRunHeader->GetNumSamplesLoGain()>0;
+}
+
+void MHCalibrationCam::Remove(TOrdCollection *col)
+{
+
+  if (!col)
+    return;
+
+  TOrdCollectionIter Next(col);
+  
+  Int_t count = 0;
+
+  while (MHCalibrationPix *obj = (MHCalibrationPix*)Next())
+    {
+      *fLog << ++count << " " << obj << flush;
+      if (obj && obj->IsOnHeap())
+        {
+          obj->Draw();
+          delete obj;
+        }
+    }
+  
+  delete col;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns size of fHiGainArray
+//
+const Int_t MHCalibrationCam::GetSize() const
+{
+  return fHiGainArray->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel (pixel number)
+//
+MHCalibrationPix &MHCalibrationCam::operator[](UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fHiGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel (pixel number)
+//
+const MHCalibrationPix &MHCalibrationCam::operator[](UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fHiGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel (pixel number)
+//
+MHCalibrationPix  &MHCalibrationCam::operator()(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fLoGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel (pixel number)
+//
+const MHCalibrationPix  &MHCalibrationCam::operator()(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fLoGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageHiGainAreas
+// independently if the MHCalibrationPix is filled with values or not.
+//
+const Int_t MHCalibrationCam::GetAverageAreas() const
+{
+  return fAverageHiGainAreas->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area (area number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageHiGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area (area number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix *>(fAverageHiGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel Area (area number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel Area (area number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageHiGainSectors
+// independently if the MHCalibrationPix is filled with values or not.
+//
+const Int_t MHCalibrationCam::GetAverageSectors() const
+{
+  return fAverageHiGainSectors->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector (sector number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageHiGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector (sector number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fAverageHiGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain Sector (sector number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain Sector (sector number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls ResetHistTitles()
+//
+// Calls Reset() for each entry in:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+void MHCalibrationCam::ResetHists()
+{
+  SetIsReset();
+
+  fCurrentNumEvts = 0;
+  
+  ResetHistTitles();
+
+  if (fHiGainArray)
+    { fHiGainArray->R__FOR_EACH(MHCalibrationPix,Reset)();  }
+
+  if (IsAverageing())
+    {
+      if (fAverageHiGainAreas)
+        { fAverageHiGainAreas->R__FOR_EACH(MHCalibrationPix,Reset)();  }
+      if (fAverageHiGainSectors)
+        { fAverageHiGainSectors->R__FOR_EACH(MHCalibrationPix,Reset)();  }
+    }
+
+  if (!IsLoGain())
+    return;
+
+  if (fLoGainArray)
+    { fLoGainArray->R__FOR_EACH(MHCalibrationPix,Reset)();  }
+  if (IsAverageing())
+    {
+      if (fAverageLoGainAreas)
+        { fAverageLoGainAreas->R__FOR_EACH(MHCalibrationPix,Reset)();  }
+      if (fAverageLoGainSectors)
+        { fAverageLoGainSectors->R__FOR_EACH(MHCalibrationPix,Reset)();  }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Resets the histogram titles for each entry in:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+void MHCalibrationCam::ResetHistTitles()
+{
+  
+  TH1F *h;
+
+  if (fHiGainArray)
+    for (Int_t i=0;i<fHiGainArray->GetSize(); i++)
+      {
+        MHCalibrationPix &pix = (*this)[i];        
+        h = pix.GetHGausHist();
+        h->SetName (Form("H%sHiGainPix%04d",fHistName.Data(),i));
+        h->SetTitle(Form("%s High Gain Pixel %04d Runs: ",fHistTitle.Data(),i));
+        h->SetXTitle(fHistXTitle.Data());
+        h->SetYTitle(fHistYTitle.Data());
+      }
+  
+  if (IsAverageing())
+    {
+      if (fAverageHiGainAreas)
+        for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageHiGainArea(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("H%sHiGainArea%d",fHistName.Data(),j));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+            if (fGeom->InheritsFrom("MGeomCamMagic"))
+                h->SetTitle(Form("%s averaged on event-by-event basis %s High Gain Runs: ",
+                                 fHistTitle.Data(), j==0 ? "Inner Pixels" : "Outer Pixels"));
+            else
+                h->SetTitle(Form("%s averaged on event-by-event basis High Gain Area Idx %d Runs: ",
+                                 fHistTitle.Data(), j));
+          }
+      
+      if (fAverageHiGainSectors)
+        for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageHiGainSector(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("H%sHiGainSector%02d",fHistName.Data(),j));
+            h->SetTitle(Form("%s averaged on event-by-event basis High Gain Sector %02d Runs: ",
+                             fHistTitle.Data(), j));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+          }
+    }
+  
+  if (!IsLoGain())
+    return;
+  
+  if (fLoGainArray)
+    for (Int_t i=0;i<fLoGainArray->GetSize(); i++)
+      {
+        MHCalibrationPix &pix = (*this)(i);        
+        h = pix.GetHGausHist();
+        h->SetName (Form("H%sLoGainPix%04d",fHistName.Data(),i));
+        h->SetTitle(Form("%s Low Gain Pixel %04d Runs: ", fHistTitle.Data(),i));
+        h->SetXTitle(fHistXTitle.Data());
+        h->SetYTitle(fHistYTitle.Data());
+      }
+  
+  if (IsAverageing())
+    {
+      if (fAverageLoGainAreas)
+        for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageLoGainArea(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("H%sLoGainArea%d", fHistName.Data(), j));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+            if (fGeom->InheritsFrom("MGeomCamMagic"))
+                h->SetTitle(Form("%s averaged on event-by-event basis %s Low Gain Runs: ",
+                                 fHistTitle.Data(), j==0 ? "Inner Pixels" : "Outer Pixels"));
+            else
+                h->SetTitle(Form("%s averaged on event-by-event basis Low Gain Area Idx %d Runs: ",
+                                 fHistTitle.Data(), j));
+          }
+      
+      if (fAverageLoGainSectors)
+        for (Int_t j=0; j<fAverageLoGainSectors->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageLoGainSector(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("H%sLoGainSector%02d",fHistName.Data(),j));
+            h->SetTitle(Form("%s averaged on event-by-event basis Low Gain Sector %02d Runs: ",
+                             fHistTitle.Data(), j));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+          }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MGeomCam
+//
+// Calls SetupHists(const MParList *pList)
+//
+// Calls Delete-Function of:
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+//
+Bool_t MHCalibrationCam::SetupFill(const MParList *pList)
+{
+  
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+  {
+      *fLog << err << GetDescriptor() 
+            << ": MGeomCam not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!fRunHeader)
+  {
+    *fLog << warn << GetDescriptor() 
+          << ": MRawRunHeader not found... will not store run numbers." << endl;
+  }
+
+  fCurrentNumEvts = 0;
+
+  return SetupHists(pList);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Searches MRawEvtHeader to find the correct pulser colour
+//
+// 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
+// 
+// Retrieves the run numbers from MRawRunHeader and stores them in fRunNumbers
+//
+Bool_t MHCalibrationCam::ReInit(MParList *pList)
+{
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+  {
+      /*
+      fBadPixels = (MBadPixelsCam*)pList->FindCreateObj(AddSerialNumber("MBadPixelsCam"));
+      if (!fBadPixels)
+          return kFALSE;
+
+          fBadPixels->InitSize(npixels);
+          */
+      *fLog << err << "MBadPixelsCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  if (IsAverageing())
+    {
+      //
+      // The function TArrayF::Set() already sets all entries to 0.
+      //
+      fAverageAreaNum.        Set(nareas);
+      fAverageAreaSat.        Set(nareas);           
+      fAverageAreaSigma.      Set(nareas);      
+      fAverageAreaSigmaVar.   Set(nareas);   
+      fAverageAreaRelSigma.   Set(nareas);   
+      fAverageAreaRelSigmaVar.Set(nareas);
+      fAverageSectorNum.      Set(nsectors);
+      
+      for (Int_t aidx=0; aidx<nareas; aidx++)
+        fAverageAreaNum[aidx] = 0;
+      
+      for (Int_t sector=0; sector<nsectors; sector++)
+        fAverageSectorNum[sector] = 0;
+  
+      for (Int_t i=0; i<npixels; i++)
+        {
+
+          if ((*fBadPixels)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            continue;
+          
+          fAverageAreaNum  [(*fGeom)[i].GetAidx()  ]++;
+          fAverageSectorNum[(*fGeom)[i].GetSector()]++;
+        }
+    }
+
+  //
+  // Because ReInit has been called, a new run number is added
+  //
+  fRunNumbers.Set(fRunNumbers.GetSize()+1);
+
+  if (fRunHeader)
+    {
+      fRunNumbers[fRunNumbers.GetSize()-1] = fRunHeader->GetRunNumber();
+      if (IsLoGain())
+        SetLoGain(fRunHeader->GetNumSamplesLoGain());
+    }
+
+  fCurrentNumEvts = 0;
+
+  if (!ReInitHists(pList))
+    return kFALSE;
+
+  ResetHistTitles();
+
+  if (!fRunHeader)
+    return kTRUE;
+  
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      TH1F *h = (*this)[i].GetHGausHist();
+      h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+    }
+
+  if (IsLoGain())
+    for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+      {
+        TH1F *h = (*this)(i).GetHGausHist();
+        h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+      }
+  
+  if (!IsAverageing())
+    return kTRUE;
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      TH1F *h = GetAverageHiGainArea(j).GetHGausHist();
+      h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+    }
+  
+  if (IsLoGain())
+    for (Int_t j=0; j<nareas; j++)
+      {
+        TH1F *h = GetAverageLoGainArea(j).GetHGausHist();
+        h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+      }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      TH1F *h = GetAverageHiGainSector(j).GetHGausHist();
+      h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+    }
+  
+  if (IsLoGain())
+    for (Int_t j=0; j<nsectors; j++)
+      {
+        TH1F *h = GetAverageLoGainSector(j).GetHGausHist();
+        h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+      }
+  
+  return kTRUE;
+}
+
+//--------------------------------------------------------------------------------------
+//
+// Initializes the High Gain Arrays:
+// 
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set X-axis and Y-axis titles with fHistXTitle and fHistYTitle
+//   * Call InitHists
+//
+void MHCalibrationCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationPix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                 Form("%s High Gain Pixel %4d",fHistTitle.Data(),i)),i);
+        
+        MHCalibrationPix &pix = (*this)[i];          
+        pix.SetBinning(fNbins, fFirst, fLast);
+        pix.SetProbLimit(fProbLimit);
+        
+        InitHists(pix, (*fBadPixels)[i], i);
+
+	if (fCam)
+	  (*fCam)[i].SetPixId(i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHCalibrationPix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                        Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationPix &pix = GetAverageHiGainArea(j);
+
+        pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas), fFirst, fLast);
+
+        if (fGeom && fGeom->InheritsFrom("MGeomCamMagic"))
+          {
+            pix.InitBins();
+            pix.SetEventFrequency(fPulserFrequency);
+          }
+        else
+          InitHists(pix, fCam->GetAverageBadArea(j),j);
+      }
+  }
+
+  if (fAverageHiGainSectors->GetSize()==0)
+    {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+          fAverageHiGainSectors->AddAt(new MHCalibrationPix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                            Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+          MHCalibrationPix &pix = GetAverageHiGainSector(j);
+
+          pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nsectors), fFirst, fLast);
+
+          InitHists(pix, fCam->GetAverageBadSector(j),j);
+      }
+  }
+}
+
+//--------------------------------------------------------------------------------------
+//
+// Return, if IsLoGain() is kFALSE 
+//
+// Initializes the Low Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set X-axis and Y-axis titles with fHistXTitle and fHistYTitle
+//   * Call InitHists
+//
+void MHCalibrationCam::InitLoGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+
+  if (!IsLoGain())
+    return;
+
+  if (fLoGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fLoGainArray->AddAt(new MHCalibrationPix(Form("%sLoGainPix%04d",fHistName.Data(),i),
+                                                 Form("%s Low Gain Pixel%04d",fHistTitle.Data(),i)),i);
+        
+        MHCalibrationPix &pix = (*this)(i);          
+        pix.SetBinning(fNbins, fFirst, fLast);
+        pix.SetProbLimit(fProbLimit);
+        
+        InitHists(pix, (*fBadPixels)[i], i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageLoGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageLoGainAreas->AddAt(new MHCalibrationPix(Form("%sLoGainArea%d",fHistName.Data(),j),
+                                                        Form("%s Low Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationPix &pix = GetAverageLoGainArea(j);
+        
+        pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas), fFirst, fLast);
+        
+        if (fGeom && fGeom->InheritsFrom("MGeomCamMagic"))
+          {
+            pix.InitBins();
+            pix.SetEventFrequency(fPulserFrequency);
+          }
+        else
+          InitHists(pix, fCam->GetAverageBadArea(j),j);
+      }
+  }
+
+  if (fAverageLoGainSectors->GetSize()==0)
+    {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+          fAverageLoGainSectors->AddAt(new MHCalibrationPix(Form("%sLoGainSector%02d",fHistName.Data(),j),
+                                                            Form("%s Low Gain Sector %02d",fHistTitle.Data(),j)),j);
+          MHCalibrationPix &pix = GetAverageLoGainSector(j);
+
+          pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nsectors), fFirst, fLast);
+          
+          InitHists(pix, fCam->GetAverageBadSector(j),j);
+      }
+  }
+}
+
+//--------------------------------------------------------------------------------
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Return kFALSE, if sizes of the TOrdCollections do not match npixels, nareas or nsectors
+// 
+// Call FillHists()
+//
+Int_t MHCalibrationCam::Fill(const MParContainer *par, const Stat_t w)
+{
+  if (fCurrentNumEvts >= fMaxNumEvts)
+    return kTRUE;
+
+  fCurrentNumEvts++;
+
+  SetIsReset(kFALSE);
+
+  if (!IsSizeCheck())
+  {
+      const Bool_t rc = FillHists(par,w);
+      return rc ? kTRUE : kERROR;
+  }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  
+  //
+  // Hi-Gain OrdCollections
+  //
+  if (fHiGainArray->GetSize() != npixels)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of pixels... abort." << endl;
+      return kERROR;
+    }
+  
+  if (IsLoGain())
+    {
+      if (fLoGainArray->GetSize() != npixels)
+        {
+          *fLog << err << "ERROR - Size mismatch in number of pixels... abort." << endl;
+          return kERROR;
+        }
+    }
+  
+  if (!IsAverageing())
+    return FillHists(par,w);
+
+  if (fAverageHiGainAreas->GetSize() != nareas)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of areas ... abort." << endl;
+      return kERROR;
+    }
+  
+  if (fAverageHiGainSectors->GetSize() != nsectors)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of sectors ... abort." << endl;
+      return kERROR;
+    }
+  
+  if (IsLoGain())
+    {
+      
+      if (fAverageLoGainAreas->GetSize() != nareas)
+        {
+          *fLog << err << "ERROR - Size mismatch in number of areas ... abort." << endl;
+          return kERROR;
+        }
+      
+      if (fAverageLoGainSectors->GetSize() != nsectors)
+        {
+          *fLog << err << "ERROR - Size mismatch in number of sectors ... abort." << endl;
+          return kERROR;
+        }
+    }
+
+  const Bool_t rc = FillHists(par, w);
+
+  return rc ? kTRUE : kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+// 0) Ask if fHiGainArray and fLoGainArray have been initialized, 
+//    otherwise return kFALSE.
+// 1) FinalizeHists()
+// 2) FinalizeBadPixels()
+// 3) CalcAverageSigma()
+//
+Bool_t MHCalibrationCam::Finalize()
+{
+  if (IsReset())
+    return kTRUE;
+
+  if (GetNumExecutions() < 2)
+    return kTRUE;
+
+  *fLog << inf << GetDescriptor() << ": Number of events used to fill histograms == " << fCurrentNumEvts << endl;
+
+  if (fHiGainArray->GetSize() == 0 && fLoGainArray->GetSize() == 0)
+    {
+      *fLog << err << GetDescriptor() 
+            << ": ERROR - Both (HiGain and LoGain) histogram arrays have not been initialized... abort." << endl;
+      return kFALSE;
+    }
+  
+  for (Int_t i=0; i<fAverageHiGainAreas->GetSize(); i++)
+    {
+      TH1F *h = GetAverageHiGainArea(i).GetHGausHist();
+      switch (fColor)
+        {
+        case MCalibrationCam::kNONE: 
+          break;
+        case MCalibrationCam::kBLUE: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"BLUE "));
+          break;
+        case MCalibrationCam::kGREEN: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"GREEN "));
+          break;
+        case MCalibrationCam::kUV: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"UV "));
+          break;
+        case MCalibrationCam::kCT1: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"CT1-Pulser "));
+          break;
+        }
+    }
+
+  for (Int_t i=0; i<fAverageLoGainAreas->GetSize(); i++)
+    {
+      TH1F *h = GetAverageLoGainArea(i).GetHGausHist();
+      switch (fColor)
+        {
+        case MCalibrationCam::kNONE: 
+          break;
+        case MCalibrationCam::kBLUE: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"BLUE "));
+          break;
+        case MCalibrationCam::kGREEN: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"GREEN "));
+          break;
+        case MCalibrationCam::kUV: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"UV "));
+          break;
+        case MCalibrationCam::kCT1: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"CT1-Pulser "));
+          break;
+        }
+    }
+  
+  if (!FinalizeHists())
+    return kFALSE;
+
+
+  FinalizeBadPixels();
+  CalcAverageSigma();
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------
+//
+// If MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun):
+// - calls MHCalibrationPix::SetExcluded()
+//
+// Calls:
+// - MHGausEvents::InitBins()
+// - MHCalibrationPix::ChangeHistId(i)
+// - MHCalibrationPix::SetEventFrequency(fPulserFrequency)
+// 
+void MHCalibrationCam::InitHists(MHCalibrationPix &hist, MBadPixelsPix &bad, const Int_t i)
+{
+
+  if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+    hist.SetExcluded();
+
+  hist.InitBins();
+  hist.SetEventFrequency(fPulserFrequency);
+}
+
+// -------------------------------------------------------------
+//
+// - Searches for the Calibration*Cam corresponding to 'name'.
+// - Initializes the MCalibration*Cam, if not yet done.
+// 
+Bool_t MHCalibrationCam::InitCams( MParList *plist, const TString name )
+{
+
+  TString ordname = "MCalibration";
+  ordname += name;
+  ordname += "Cam";
+
+  fCam = (MCalibrationCam*)plist->FindObject(AddSerialNumber(ordname));
+  if (!fCam)
+  {
+      fCam = (MCalibrationCam*)plist->FindCreateObj(AddSerialNumber(ordname));
+      if (!fCam)
+          return kFALSE;
+
+      fCam->Init(*fGeom);
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls FitHiGainHists for every entry in:
+// - fHiGainArray
+// - fAverageHiGainAreas
+// - fAverageHiGainSectors
+// 
+void MHCalibrationCam::FitHiGainArrays(MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                                       MBadPixelsPix::UncalibratedType_t fittyp, 
+                                       MBadPixelsPix::UncalibratedType_t osctyp)
+{
+  fIsHiGainFitRanges = TMath::Abs(fUpperFitLimitHiGain - fLowerFitLimitHiGain) > 1E-5;
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      MCalibrationPix &pix    = calcam[i];
+      MBadPixelsPix   &bad    = badcam[i];
+      
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageHiGainArea(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageArea(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadArea(j);        
+
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+  }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageSector(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadSector(j);        
+
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls FitLoGainHists for every entry in:
+// - fLoGainArray
+// - fAverageLoGainAreas
+// - fAverageLoGainSectors
+// 
+void MHCalibrationCam::FitLoGainArrays(MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                                            MBadPixelsPix::UncalibratedType_t fittyp, 
+                                            MBadPixelsPix::UncalibratedType_t osctyp)
+{
+  fIsLoGainFitRanges = TMath::Abs(fUpperFitLimitLoGain - fLowerFitLimitLoGain) > 1E-5;
+
+  if (!IsLoGain())
+    return;
+
+  for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)(i);
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      MCalibrationPix &pix    = calcam[i];
+      MBadPixelsPix   &bad    = badcam[i];
+      
+      FitLoGainHists(hist,pix,bad,fittyp,osctyp);
+      
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageLoGainArea(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageArea(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadArea(j);        
+      
+      FitLoGainHists(hist,pix,bad,fittyp,osctyp);
+  }
+  
+  for (Int_t j=0; j<fAverageLoGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageLoGainSector(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageSector(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadSector(j);        
+      
+      FitLoGainHists(hist,pix,bad,fittyp,osctyp);
+    }
+}
+
+//------------------------------------------------------------
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels
+//
+void MHCalibrationCam::CalcAverageSigma()
+{
+  if (!IsAverageing())
+    return;
+
+  MCalibrationCam *cam = fCam;
+  if (!cam)
+    return;
+
+  for (UInt_t j=0; j<fGeom->GetNumAreas(); j++)
+    {
+
+      MCalibrationPix &pix    = cam->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];
+    }
+
+  for (UInt_t j=0; j<fGeom->GetNumSectors(); j++)
+    {
+      MCalibrationPix &pix    = cam->GetAverageSector(j);
+
+      const Float_t numsqr    = TMath::Sqrt((Float_t)fAverageSectorNum[j]);
+      pix.SetSigma   (pix.GetSigma() * numsqr);
+      pix.SetSigmaVar(pix.GetSigmaErr() * pix.GetSigmaErr() * numsqr);
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// Returns if the histogram is empty and sets the following flag:
+// - MBadPixelsPix::SetUnsuitable(MBadPixelsPix::kUnsuitableRun)
+//
+// Fits the histograms with a Gaussian, in case of failure 
+// calls MHCalibrationPix::RepeatFit(), in case of repeated failure 
+// calls MHCalibrationPix::BypassFit() and sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t fittyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   )
+// 
+// Creates the fourier spectrum and tests MHGausEvents::IsFourierSpectrumOK(). 
+// In case no, sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t osctyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun     )
+//
+// Retrieves the results and store them in MCalibrationPix
+//
+void MHCalibrationCam::FitHiGainHists(MHCalibrationPix &hist, 
+                                      MCalibrationPix &pix, 
+                                      MBadPixelsPix &bad, 
+                                      MBadPixelsPix::UncalibratedType_t fittyp,
+                                      MBadPixelsPix::UncalibratedType_t osctyp)
+{
+  if (hist.IsEmpty())
+  {
+      //*fLog << warn << "Pixel  " << setw(4) << pix.GetPixId() << ": Hi-Gain histogram empty." << endl;
+      //bad.SetUncalibrated( fittyp );
+      return;
+  }
+  if (hist.IsOnlyOverflow())
+  {
+      *fLog << warn << "Pixel  " << setw(4) << pix.GetPixId() << ": Hi-Gain histogram contains only overflows (Check Binning!)." << endl;
+      bad.SetUncalibrated( fittyp );
+      return;
+  }
+  if (hist.IsOnlyUnderflow())
+  {
+      *fLog << warn << "Pixel  " << setw(4) << pix.GetPixId() << ": Hi-Gain histogram contains only underflows (Check Binning!)." << endl;
+      bad.SetUncalibrated( fittyp );
+      return;
+  }
+
+  //
+  // 2) Fit the Hi Gain histograms with a Gaussian
+  //
+  if (fIsHiGainFitRanges)
+  {
+      if (!hist.FitGaus("R",fLowerFitLimitHiGain,fUpperFitLimitHiGain))
+          bad.SetUncalibrated( fittyp );
+  }
+  else
+      if (!hist.FitGaus())
+          //
+          // 3) In case of failure set the bit Fitted to false and take histogram means and RMS
+          //
+          if (!hist.RepeatFit())
+          {
+              hist.BypassFit();
+              bad.SetUncalibrated( fittyp );
+          }
+
+ 
+  //
+  // 4) Check for oscillations
+  // 
+  if (IsOscillations())
+    {
+      hist.CreateFourierSpectrum();
+  
+      if (!hist.IsFourierSpectrumOK())
+        bad.SetUncalibrated( osctyp );
+    }
+  
+  //
+  // 5) Retrieve the results and store them in this class
+  //
+  pix.SetHiGainMean       ( hist.GetMean()      );
+  pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+  pix.SetHiGainRms        ( hist.GetHistRms()   );
+  pix.SetHiGainSigma      ( hist.GetSigma()     );
+  pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+  pix.SetHiGainProb       ( hist.GetProb()      );
+  pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+  pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << GetDescriptor() << ": ID " << GetName() 
+            << " "<<pix.GetPixId()
+            << " HiGainSaturation: "   << pix.IsHiGainSaturation() 
+            << " HiGainMean: "         << hist.GetMean    ()
+            << " HiGainMeanErr: "      << hist.GetMeanErr ()
+            << " HiGainMeanSigma: "    << hist.GetSigma   ()
+            << " HiGainMeanSigmaErr: " << hist.GetSigmaErr()
+            << " HiGainMeanProb: "     << hist.GetProb    ()
+            << " HiGainNumBlackout: "  << hist.GetBlackout()
+            << " HiGainNumPickup  : "  << hist.GetPickup  ()
+            << endl;
+    }
+
+}
+
+
+// ---------------------------------------------------------------------------
+//
+// Returns if the histogram is empty and sets the following flag:
+// - MBadPixelsPix::SetUnsuitable(MBadPixelsPix::kUnsuitableRun)
+//
+// Fits the histograms with a Gaussian, in case of failure 
+// calls MHCalibrationPix::RepeatFit(), in case of repeated failure 
+// calls MHCalibrationPix::BypassFit() and sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t fittyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   )
+// 
+// Creates the fourier spectrum and tests MHGausEvents::IsFourierSpectrumOK(). 
+// In case no, sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t osctyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun     )
+//
+// Retrieves the results and store them in MCalibrationPix
+//
+void MHCalibrationCam::FitLoGainHists(MHCalibrationPix &hist, 
+                                      MCalibrationPix &pix, 
+                                      MBadPixelsPix &bad, 
+                                      MBadPixelsPix::UncalibratedType_t fittyp,
+                                      MBadPixelsPix::UncalibratedType_t osctyp)
+{
+
+  if (hist.IsEmpty())
+  {
+      //*fLog << warn << "Pixel   " << setw(4) << pix.GetPixId() << ": Lo-Gain histogram empty." << endl;
+      //bad.SetUncalibrated( fittyp ); // FIXME: Combine with HiGain!
+      return;
+  }
+  if (hist.IsOnlyOverflow())
+  {
+      *fLog << warn << "Pixel  " << setw(4) << pix.GetPixId() << ": Lo-Gain histogram contains only overflows (Check Binning!)." << endl;
+      bad.SetUncalibrated( fittyp );
+      return;
+  }
+  if (hist.IsOnlyUnderflow())
+  {
+      *fLog << warn << "Pixel  " << setw(4) << pix.GetPixId() << ": Lo-Gain histogram contains only underflows (Check Binning!)." << endl;
+      bad.SetUncalibrated( fittyp );
+      return;
+  }
+
+  //
+  // 2) Fit the Hi Gain histograms with a Gaussian
+  //
+  if (fIsLoGainFitRanges)
+  {
+      if (!hist.FitGaus("R",fLowerFitLimitLoGain,fUpperFitLimitLoGain))
+          bad.SetUncalibrated( fittyp );
+  }
+  else
+      if (!hist.FitGaus())
+          //
+          // 3) In case of failure set the bit Fitted to false and take histogram means and RMS
+          //
+          if (!hist.RepeatFit())
+          {
+              hist.BypassFit();
+              if (pix.IsHiGainSaturation())
+                  bad.SetUncalibrated( fittyp );
+          }
+
+  //
+  // 4) Check for oscillations
+  // 
+  if (IsOscillations())
+    {
+      hist.CreateFourierSpectrum();
+      
+      if (!hist.IsFourierSpectrumOK())
+        bad.SetUncalibrated( osctyp );
+    }
+  
+  //
+  // 5) Retrieve the results and store them in this class
+  //
+  pix.SetLoGainMean       ( hist.GetMean()      );
+  pix.SetLoGainMeanVar    ( hist.GetMeanErr()  * hist.GetMeanErr()   );
+  pix.SetLoGainRms        ( hist.GetHistRms()   );
+  pix.SetLoGainSigma      ( hist.GetSigma()     );
+  pix.SetLoGainSigmaVar   ( hist.GetSigmaErr() * hist.GetSigmaErr()  );
+  pix.SetLoGainProb       ( hist.GetProb()      );
+  pix.SetLoGainNumBlackout( hist.GetBlackout()  );
+  pix.SetLoGainNumPickup  ( hist.GetPickup()    );
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << GetDescriptor() << "ID: " << hist.GetName() 
+            << " "<<pix.GetPixId()
+            << " HiGainSaturation: "   << pix.IsHiGainSaturation()
+            << " LoGainMean: "         << hist.GetMean    ()
+            << " LoGainMeanErr: "      << hist.GetMeanErr ()
+            << " LoGainMeanSigma: "    << hist.GetSigma   ()
+            << " LoGainMeanSigmaErr: " << hist.GetSigmaErr()
+            << " LoGainMeanProb: "     << hist.GetProb    ()
+            << " LoGainNumBlackout: "  << hist.GetBlackout()
+            << " LoGainNumPickup  : "  << hist.GetPickup  ()
+            << endl;
+    }
+
+}
+
+
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationCam::Draw(const Option_t *opt)
+{
+
+  if (!IsAverageing())
+    return;
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  pad->Divide(IsLoGain() ? 2 : 1,nareas);
+
+  for (Int_t i=0; i<nareas;i++) 
+    {
+
+      pad->cd(IsLoGain() ? 2*(i+1)-1 : i+1);
+      GetAverageHiGainArea(i).Draw(opt);
+
+      if (!fAverageAreaSat[i])
+        DrawAverageSigma(fAverageAreaSat[i], i,
+                         fAverageAreaSigma[i],    fAverageAreaSigmaVar[i],
+                         fAverageAreaRelSigma[i], fAverageAreaRelSigmaVar[i]);
+
+      if (IsLoGain())
+        {
+          pad->cd(2*(i+1));
+          GetAverageLoGainArea(i).Draw(opt);
+        }
+      
+      if (fAverageAreaSat[i])
+        DrawAverageSigma(fAverageAreaSat[i], i,
+                         fAverageAreaSigma[i], fAverageAreaSigmaVar[i],
+                         fAverageAreaRelSigma[i], fAverageAreaRelSigmaVar[i]);
+    }
+      
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays a TPaveText with the re-normalized sigmas of the average area
+//
+void MHCalibrationCam::DrawAverageSigma(Bool_t sat, Bool_t inner,
+                                        Float_t sigma, Float_t sigmavar,
+                                        Float_t relsigma, Float_t relsigmavar) const
+{
+  
+    if (sigma==0 || sigmavar<0 || relsigmavar<0)
+        return;
+
+      TPaveText *text = new TPaveText(sat? 0.1 : 0.35,0.7,sat ? 0.4 : 0.7,1.0);
+      text->SetTextSize(0.05);
+      text->SetBit(kCanDelete);
+      text->Draw("");
+
+      const TString line1 = Form("%s Pixels %s Gain",
+                                 inner?"Outer" : "Inner", sat?"Low":"High");
+      const TString line2 = Form("#sigma per pix: %2.2f #pm %2.2f", sigma, TMath::Sqrt(sigmavar));
+      const TString line3 = Form("Rel. #sigma per pix: %2.2f #pm %2.2f", relsigma, TMath::Sqrt(relsigmavar));
+
+      text->AddText(line1.Data());
+      text->AddText(line2.Data());
+      text->AddText(line3.Data());
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Available options
+//  Debug
+//  LoGain
+//  Oscillations
+//  SizeCheck
+//  Averageing
+//  Nbins
+//  First
+//  Last
+//  ProbLimit
+//  OverflowLimit
+//  PulserFrequency
+//  LowerFitLimitHiGain
+//  UpperFitLimitHiGain
+//  LowerFitLimitLoGain
+//  UpperFitLimitLoGain
+//
+Int_t MHCalibrationCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+  if (IsEnvDefined(env, prefix, "Debug", print))
+    {
+      SetDebug(GetEnvValue(env, prefix, "Debug", IsDebug()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "LoGain", print))
+    {
+      SetDebug(GetEnvValue(env, prefix, "LoGain", IsLoGain()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "Oscillations", print))
+    {
+      SetOscillations(GetEnvValue(env, prefix, "Oscillations", IsOscillations()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "SizeCheck", print))
+    {
+      SetSizeCheck(GetEnvValue(env, prefix, "SizeCheck", IsSizeCheck()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "Averageing", print))
+    {
+      SetAverageing(GetEnvValue(env, prefix, "Averageing", IsAverageing()));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "Nbins", print))
+    {
+      fNbins = GetEnvValue(env, prefix, "Nbins", fNbins);
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "First", print))
+    {
+      fFirst = GetEnvValue(env, prefix, "First", fFirst);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "Last", print))
+    {
+      fLast = GetEnvValue(env, prefix, "Last", fLast);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "ProbLimit", print))
+    {
+      SetProbLimit(GetEnvValue(env, prefix, "ProbLimit", fProbLimit));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "MaxNumEvts", print))
+    {
+      SetMaxNumEvts(GetEnvValue(env, prefix, "MaxNumEvts", fMaxNumEvts));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "OverflowLimit", print))
+    {
+      SetOverflowLimit(GetEnvValue(env, prefix, "OverflowLimit", fOverflowLimit));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "PulserFrequency", print))
+    {
+      SetPulserFrequency(GetEnvValue(env, prefix, "PulserFrequency", fPulserFrequency));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "LowerFitLimitHiGain", print))
+    {
+      SetLowerFitLimitHiGain(GetEnvValue(env, prefix, "LowerFitLimitHiGain", fLowerFitLimitHiGain));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "UpperFitLimitHiGain", print))
+    {
+      SetUpperFitLimitHiGain(GetEnvValue(env, prefix, "UpperFitLimitHiGain", fUpperFitLimitHiGain));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "LowerFitLimitLoGain", print))
+    {
+      SetLowerFitLimitLoGain(GetEnvValue(env, prefix, "LowerFitLimitLoGain", fLowerFitLimitLoGain));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "UpperFitLimitLoGain", print))
+    {
+      SetUpperFitLimitLoGain(GetEnvValue(env, prefix, "UpperFitLimitLoGain", fUpperFitLimitLoGain));
+      rc = kTRUE;
+    }
+
+  
+  return rc;
+}
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationCam.h	(revision 17960)
@@ -0,0 +1,249 @@
+#ifndef MARS_MHCalibrationCam
+#define MARS_MHCalibrationCam
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class TText;
+class TOrdCollection;
+
+class MHCalibrationPix;
+class MGeomCam;
+class MRawRunHeader;
+class MCalibrationCam;
+class MCalibrationPix;
+class MBadPixelsCam;
+class MBadPixelsPix;
+
+class MHCalibrationCam : public MH, public MCamEvent
+{
+  
+private:
+  static const Double_t fgLowerFitLimitHiGain; //! Default for fLowerFitLimitHiGain
+  static const Double_t fgUpperFitLimitHiGain; //! Default for fUpperFitLimitHiGain
+  static const Double_t fgLowerFitLimitLoGain; //! Default for fLowerFitLimitLoGain
+  static const Double_t fgUpperFitLimitLoGain; //! Default for fUpperFitLimitLoGain
+
+  static const Int_t   fgPulserFrequency;  //! Default for fPulserFrequency
+  static const Float_t fgProbLimit;        //! Default for fProbLimit
+  static const Float_t fgOverflowLimit;    //! Default for fOverflowLimit
+  static const Int_t   fgMaxNumEvts;       //! Default for fMaxNumEvts
+  
+  static const TString gsHistName;         //! Default Histogram names
+  static const TString gsHistTitle;        //! Default Histogram titles
+  static const TString gsHistXTitle;       //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;       //! Default Histogram y-axis titles
+  
+protected:
+
+  Int_t   fNbins;                         // Number of bins        
+  Axis_t  fFirst;                         // Lower histogram limit 
+  Axis_t  fLast;                          // Upper histogram limit 
+ 
+  Float_t fProbLimit;                     // Limit for acceptance of probability of Gauss-Fit
+  Float_t fOverflowLimit;                 // Part of maximum allowed overflow events
+
+  Double_t fLowerFitLimitHiGain;          // Lower limit for the fit range for the hi-gain hist
+  Double_t fUpperFitLimitHiGain;          // Upper limit for the fit range for the hi-gain hist
+  Double_t fLowerFitLimitLoGain;          // Lower limit for the fit range for the lo-gain hist
+  Double_t fUpperFitLimitLoGain;          // Upper limit for the fit range for the lo-gain hist
+
+  Bool_t   fIsHiGainFitRanges;            // Are high-gain fit ranges defined?
+  Bool_t   fIsLoGainFitRanges;            // Are low-gain fit ranges defined?
+  
+  TString fHistName;                      //! Histogram names
+  TString fHistTitle;                     //! Histogram titles
+  TString fHistXTitle;                    //! Histogram x-axis titles
+  TString fHistYTitle;                    //! Histogram y-axis titles
+  
+  Float_t fNumHiGainSaturationLimit;      // Rel. amount sat. higain FADC slices until pixel is called saturated 
+  Float_t fNumLoGainSaturationLimit;      // Rel. amount sat. logain FADC slices until pixel is called saturated
+
+  Int_t   fMaxNumEvts;                    // Max Number of events
+  Int_t   fCurrentNumEvts;                //! Current number of events
+  
+  MArrayI fRunNumbers;                    // Numbers of runs used
+
+  MArrayF fAverageAreaRelSigma;           // Re-normalized relative sigmas in average pixels per area
+  MArrayF fAverageAreaRelSigmaVar;        // Variance Re-normalized relative sigmas in average pixels per area 
+  MArrayI fAverageAreaSat;                // Number of saturated slices in average pixels per area
+  MArrayF fAverageAreaSigma;              // Re-normalized sigmas in average pixels per area
+  MArrayF fAverageAreaSigmaVar;           // Variance Re-normalized sigmas in average pixels per area
+  MArrayI fAverageAreaNum;                // Number of pixels in average pixels per area
+  MArrayI fAverageSectorNum;              // Number of pixels in average pixels per sector
+
+  TOrdCollection *fAverageHiGainAreas;    // Array of calibration pixels, one per pixel area
+  TOrdCollection *fAverageHiGainSectors;  // Array of calibration pixels, one per camera sector
+  TOrdCollection *fAverageLoGainAreas;    // Array of calibration pixels, one per pixel area
+  TOrdCollection *fAverageLoGainSectors;  // Array of calibration pixels, one per camera sector
+
+  MCalibrationCam::PulserColor_t fColor;  // Colour of the pulsed LEDs
+
+  MBadPixelsCam    *fBadPixels;           //! Bad Pixels storage container
+  MCalibrationCam  *fCam;                 //! Calibration Cam with the results
+  MGeomCam         *fGeom;                //! Camera geometry
+  MRawRunHeader    *fRunHeader;           //! Run Header
+  
+  TOrdCollection *fHiGainArray;           // Array of calibration pixels, one per pixel
+  TOrdCollection *fLoGainArray;           // Array of calibration pixels, one per pixel
+
+  Int_t  fPulserFrequency;                // Light pulser frequency
+
+  enum {
+      kDebug,
+      kLoGain,
+      kAverageing,
+      kOscillations,
+      kSizeCheck,
+      kIsReset
+  };     // Possible global flags
+   
+  Byte_t  fFlags;                         // Bit-field to hold the global flags
+  
+  virtual Bool_t SetupHists ( const MParList *pList ) { return kTRUE; }
+  virtual Bool_t ReInitHists(       MParList *pList ) { return kTRUE; }
+  virtual Bool_t FillHists  ( const MParContainer *par, const Stat_t w=1) { return kTRUE; }
+  virtual Bool_t FinalizeHists()                      { return kTRUE;  }
+  
+  virtual void   FinalizeBadPixels() { }
+  
+  virtual void   CalcAverageSigma();
+  
+  virtual void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  virtual void   InitLoGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  
+  virtual void   ResetHistTitles();
+  
+  void DrawAverageSigma( Bool_t sat, Bool_t inner,
+                         Float_t sigma, Float_t sigmaerr,
+                         Float_t relsigma, Float_t relsigmaerr) const; 
+  
+  void FitHiGainArrays ( MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+  
+  void FitHiGainHists  ( MHCalibrationPix &hist, 
+                         MCalibrationPix &pix, 
+                         MBadPixelsPix &bad, 
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+  
+  void FitLoGainArrays ( MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+  
+  void FitLoGainHists  ( MHCalibrationPix &hist, 
+                         MCalibrationPix &pix, 
+                         MBadPixelsPix &bad, 
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+
+  void   InitHists     ( MHCalibrationPix &hist, MBadPixelsPix &bad, const Int_t i);
+  Bool_t InitCams      ( MParList *plist, const TString name );
+  
+  Bool_t IsLoGain() const;
+  Bool_t IsAverageing  () const  { return TESTBIT(fFlags,kAverageing);   }
+  Bool_t IsDebug       () const  { return TESTBIT(fFlags,kDebug);        }  
+  Bool_t IsOscillations() const  { return TESTBIT(fFlags,kOscillations); }
+  Bool_t IsSizeCheck   () const  { return TESTBIT(fFlags,kSizeCheck);    }
+  Bool_t IsReset       () const  { return TESTBIT(fFlags,kIsReset);      }
+
+  void ToggleFlag(Bool_t b, Byte_t flag) { b ? SETBIT(fFlags, flag) : CLRBIT(fFlags,flag); }
+
+  void   Remove  ( TOrdCollection *col );
+  
+  Int_t  ReadEnv ( const TEnv &env, TString prefix, Bool_t print );
+
+public:
+
+  MHCalibrationCam(const char *name=NULL, const char *title=NULL);
+  virtual ~MHCalibrationCam();
+
+  Bool_t SetupFill(const MParList *pList);
+  Bool_t ReInit   (      MParList *pList);
+  Int_t  Fill     (const MParContainer *par, const Stat_t w=1);
+  Bool_t Finalize ( );
+
+  virtual void ResetHists();
+
+  // Draw
+  void   Draw(const Option_t *opt);       // *MENU*
+
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const { return kTRUE; }
+  void   DrawPixelContent( Int_t num )  const  {}
+
+  const MArrayI           &GetAverageAreaNum     ()          const { return fAverageAreaNum; }
+  const Int_t              GetAverageAreas       ()          const;	 
+        MHCalibrationPix  &GetAverageHiGainArea  (UInt_t i);
+  const MHCalibrationPix  &GetAverageHiGainArea  (UInt_t i)  const;
+        MHCalibrationPix  &GetAverageLoGainArea  (UInt_t i);
+  const MHCalibrationPix  &GetAverageLoGainArea  (UInt_t i)  const;
+        MHCalibrationPix  &GetAverageHiGainSector(UInt_t i);
+  const MHCalibrationPix  &GetAverageHiGainSector(UInt_t i)  const;
+        MHCalibrationPix  &GetAverageLoGainSector(UInt_t i);
+  const MHCalibrationPix  &GetAverageLoGainSector(UInt_t i)  const;
+  const MArrayI           &GetAverageSectorNum    ()         const { return fAverageSectorNum; }
+  const Int_t              GetAverageSectors      ()         const;
+  const MCalibrationCam::PulserColor_t GetColor   ()     const  { return fColor;                    }
+  const Float_t        GetNumHiGainSaturationLimit()     const  { return fNumHiGainSaturationLimit; }
+  const Float_t        GetNumLoGainSaturationLimit()     const  { return fNumLoGainSaturationLimit; }
+  const MArrayI       &GetRunNumbers         ()          const { return fRunNumbers;            }
+  const Int_t          GetSize               ()          const;
+
+        MHCalibrationPix  &operator[]            (UInt_t i);
+  const MHCalibrationPix  &operator[]            (UInt_t i)  const;
+        MHCalibrationPix  &operator()            (UInt_t i);
+  const MHCalibrationPix  &operator()            (UInt_t i)  const;
+ 
+  void SetColor(const MCalibrationCam::PulserColor_t color) { fColor = color; }
+
+  void SetAverageing(const Bool_t b=kTRUE)   { ToggleFlag(b,kAverageing); }
+  void SetDebug(const Bool_t b=kTRUE)        { ToggleFlag(b,kDebug); }
+  void SetLoGain(const Bool_t b=kTRUE)       { ToggleFlag(b,kLoGain); }
+  void SetOscillations(const Bool_t b=kTRUE) { ToggleFlag(b,kOscillations); }
+  void SetSizeCheck(const Bool_t b=kTRUE)    { ToggleFlag(b,kSizeCheck); }
+  void SetIsReset(const Bool_t b=kTRUE)      { ToggleFlag(b,kIsReset); }
+
+  void SetHistName  ( const char *name )  { fHistName  = name;  }
+  void SetHistTitle ( const char *name )  { fHistTitle = name;  }
+  void SetHistXTitle( const char *name )  { fHistXTitle = name; }
+  void SetHistYTitle( const char *name )  { fHistYTitle = name; }
+
+  void SetLowerFitLimitHiGain( const Double_t d=fgLowerFitLimitHiGain)  {  fLowerFitLimitHiGain = d;  }
+  void SetUpperFitLimitHiGain( const Double_t d=fgUpperFitLimitHiGain)  {  fUpperFitLimitHiGain = d;  }
+  void SetLowerFitLimitLoGain( const Double_t d=fgLowerFitLimitLoGain)  {  fLowerFitLimitLoGain = d;  }
+  void SetUpperFitLimitLoGain( const Double_t d=fgUpperFitLimitLoGain)  {  fUpperFitLimitLoGain = d;  }
+   
+  void SetBinning(Int_t n, Axis_t lo, Axis_t up) { fNbins=n; fFirst=lo; fLast=up; }
+
+  void SetMaxNumEvts              ( const Int_t  i=fgMaxNumEvts ) { fMaxNumEvts  = i; }
+
+  void SetProbLimit               ( const Float_t f=fgProbLimit) { fProbLimit = f; }    
+
+  void SetNumLoGainSaturationLimit( const Float_t lim )    { fNumLoGainSaturationLimit  = lim; }
+  void SetNumHiGainSaturationLimit( const Float_t lim )    { fNumHiGainSaturationLimit  = lim; }
+  void SetOverflowLimit        ( const Float_t f=fgOverflowLimit ) { fOverflowLimit = f; }
+  void SetPulserFrequency      ( const Int_t   i=fgPulserFrequency )   { fPulserFrequency  = i; }
+  
+  ClassDef(MHCalibrationCam, 6)	// Base Histogram class for Calibration Camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindCam.cc	(revision 17960)
@@ -0,0 +1,520 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationChargeBlindCam                                               
+//
+// Histogram class for blind pixels in the camera. Incorporates the TObjArray's:
+// - fBlindPixelsArray (for calibrated High Gains per pixel)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeBlindCam.h"
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalBlindPixel.h"
+
+#include "MCalibrationBlindPix.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+
+ClassImp(MHCalibrationChargeBlindCam);
+
+using namespace std;
+const Int_t     MHCalibrationChargeBlindCam::fgNbins    =  128;
+const Axis_t    MHCalibrationChargeBlindCam::fgFirst    = -0.5;
+const Axis_t    MHCalibrationChargeBlindCam::fgLast     =  511.5;
+const Axis_t    MHCalibrationChargeBlindCam::fgSPheCut  =  20.;
+const TString   MHCalibrationChargeBlindCam::gsHistName   = "ChargeBlind";
+const TString   MHCalibrationChargeBlindCam::gsHistTitle  = "Signals Blind";
+const TString   MHCalibrationChargeBlindCam::gsHistXTitle = "Signal [FADC counts]";
+const TString   MHCalibrationChargeBlindCam::gsHistYTitle = "Nr. events";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// - fFitFunc to kEPoisson4
+// - fNbins   to fgNbins
+// - fFirst   to fgFirst
+// - fLast    to fgLast 
+// - fSPheCut to fgSPheCut
+// 
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - SetAverageing  (kFALSE);
+// - SetLoGain      (kFALSE);
+// - SetOscillations(kFALSE);
+// - SetSizeCheck   (kFALSE);
+//
+MHCalibrationChargeBlindCam::MHCalibrationChargeBlindCam(const char *name, const char *title)
+    : fRawEvt(NULL)
+{
+
+  fName  = name  ? name  : "MHCalibrationChargeBlindCam";
+  fTitle = title ? title : "Class to fille the blind pixel histograms";
+
+  SetSPheCut();
+
+  SetBinning(fgNbins, fgFirst, fgLast);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetAverageing  (kFALSE);
+  SetLoGain      (kFALSE);
+  SetOscillations(kFALSE);
+  SetSizeCheck   (kFALSE);
+
+  SetFitFunc(MHCalibrationChargeBlindPix::kEPoisson4);
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MRawEvtData
+//
+Bool_t MHCalibrationChargeBlindCam::SetupHists(const MParList *pList)
+{
+
+  fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+  if (!fRawEvt)
+  {
+      *fLog << err << dbginf << "MRawEvtData not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MExtractedSignalBlindPixel
+// - MCalibrationChargeCam or MCalibrationBlindCam
+//
+// Initializes the number of used FADC slices from MExtractedSignalCam 
+// into MCalibrationChargeCam and test for changes in that variable
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the High Gain Arrays:
+//
+// - Expand fHiGainArrays to nblindpixels
+// 
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Call InitHists
+//
+Bool_t MHCalibrationChargeBlindCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,"Blind"))
+    return kFALSE;
+
+  MExtractedSignalBlindPixel *signal = 
+    (MExtractedSignalBlindPixel*)pList->FindObject(AddSerialNumber("MExtractedSignalBlindPixel"));
+  if (!signal)
+  {
+      *fLog << err << "MExtractedSignalBlindPixel not found... abort." << endl;
+      return kFALSE;
+  }
+
+  const Int_t nblindpixels = signal->GetNumBlindPixels();
+  const Int_t samples      = signal->GetNumFADCSamples();
+  const Int_t integ        = signal->IsExtractionType( MExtractBlindPixel::kIntegral );
+  
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<nblindpixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationChargeBlindPix(Form("%s%s%d",fHistName.Data(),"Pix",i),
+                                                  Form("%s%s%d",fHistTitle.Data()," Pixel ",i)),i);
+
+        MHCalibrationChargeBlindPix &pix = (MHCalibrationChargeBlindPix&)(*this)[i];
+
+        const Axis_t last = integ ? ((fLast+0.5)*samples)-0.5 : fLast;
+
+        pix.SetBinning(fNbins, fFirst, last);
+        pix.SetSinglePheCut ( integ ? fSPheCut * samples        : fSPheCut );
+        pix.SetFitFunc      ( integ ? MHCalibrationChargeBlindPix::kEPoisson5 : fFitFunc );
+
+        pix.InitBins();
+
+      }
+  }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Resets the histogram titles for each entry in:
+// - fHiGainArray
+//
+void MHCalibrationChargeBlindCam::ResetHistTitles()
+{
+  
+  TH1F *h;
+
+  if (fHiGainArray)
+    for (Int_t i=0;i<fHiGainArray->GetSize(); i++)
+      {
+        MHCalibrationPix &pix = (*this)[i];        
+        h = pix.GetHGausHist();
+        h->SetName (Form("%s%s%s%d","H",fHistName.Data(),"Pix",i));
+        h->SetTitle(Form("%s%s%d%s",fHistTitle.Data()," Pixel ",i," Runs: "));  
+        h->SetXTitle(fHistXTitle.Data());
+        h->SetYTitle(fHistYTitle.Data());
+      }
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalBlindPixel:
+// - number of blind pixels
+//
+// Retrieves from MExtractedSignalBlindPixel:
+// - number of FADC samples
+// - extracted signal 
+// - blind Pixel ID
+//
+// Resizes (if necessary):
+// - fASinglePheFADCSlices to sum of HiGain and LoGain samples
+// - fAPedestalFADCSlices to sum of HiGain and LoGain samples
+//
+// Fills the following histograms:
+// - MHGausEvents::FillHistAndArray(signal)
+//
+// Creates MRawEvtPixelIter, jumps to blind pixel ID, 
+// fills the vectors fASinglePheFADCSlices and fAPedestalFADCSlices 
+// with the full FADC slices, depending on the size of the signal w.r.t. fSinglePheCut
+//
+Bool_t MHCalibrationChargeBlindCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalBlindPixel *signal = (MExtractedSignalBlindPixel*)par;
+  if (!signal)
+    {
+      *fLog << err << "No argument in MExtractedSignalBlindCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const Int_t nblindpixels  = signal->GetNumBlindPixels();
+  
+  if (GetSize() != nblindpixels)
+    {
+      gLog << err << "ERROR - Size mismatch... abort." << endl;
+      return kFALSE;
+    }
+
+  Float_t slices = (Float_t)signal->GetNumFADCSamples();
+  
+  if (slices == 0.)
+    {
+      *fLog << err << dbginf
+	    << "Number of used signal slices in MExtractedSignalBlindPix "
+	    << "is zero  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  for (Int_t i=0; i<nblindpixels; i++)
+    {
+
+      //
+      // Signal extraction and histogram filling
+      // If filter has been applied, sig has been set to -1.
+      //
+      const Float_t sig = signal->GetExtractedSignal(i);
+      
+      if (sig < -0.5)
+        continue;
+
+      MHCalibrationChargeBlindPix &hist = (MHCalibrationChargeBlindPix&)(*this)[i];
+
+      hist.FillHist(sig);
+      //
+      // In order to study the single-phe posistion, we extract the slices
+      //
+      const Int_t blindpixIdx = signal->GetBlindPixelIdx(i);
+      
+      MRawEvtPixelIter pixel(fRawEvt);
+      pixel.Jump(blindpixIdx);
+/*
+      if (sig > fSPheCut)
+        hist.FillSinglePheFADCSlices(pixel);
+      else
+        hist.FillPedestalFADCSlices(pixel);
+  */
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For all TObjArray's (including the averaged ones), the following steps are performed: 
+//
+// 1) Returns if the pixel is excluded.
+// 2) Tests saturation. In case yes, set the flag: MCalibrationPix::SetHiGainSaturation()
+//    or the flag: MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturated )
+// 3) Store the absolute arrival times in the MCalibrationChargePix's. If flag 
+//    MCalibrationPix::IsHiGainSaturation() is set, the Low-Gain arrival times are stored, 
+//    otherwise the Hi-Gain ones.
+// 4) Calls to MHCalibrationCam::FitHiGainArrays() and MCalibrationCam::FitLoGainArrays() 
+//    with the flags:
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating )
+//
+Bool_t MHCalibrationChargeBlindCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      MHCalibrationChargeBlindPix &hist = (MHCalibrationChargeBlindPix&)(*this)[i];
+      
+      TH1F *h = hist.GetHGausHist();
+
+      switch (fColor)
+        {
+        case MCalibrationCam::kNONE: 
+          break;
+        case MCalibrationCam::kBLUE: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"BLUE "));
+          break;
+        case MCalibrationCam::kGREEN: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"GREEN "));
+          break;
+        case MCalibrationCam::kUV: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"UV "));
+          break;
+        case MCalibrationCam::kCT1: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"CT1-Pulser "));
+          break;
+        }
+      
+      Stat_t overflow = h->GetBinContent(h->GetNbinsX()+1);
+      if (overflow > 0.1)
+        {
+          *fLog << warn << GetDescriptor()
+                << ": Histogram Overflow occurred " << overflow 
+                << " times in blind pixel: " << i << endl;
+        }
+
+      overflow = h->GetBinContent(0);
+      if (overflow > 0.1)
+        {
+          *fLog << warn << GetDescriptor()
+                << ": Histogram Underflow occurred " << overflow
+                << " times in blind pixel: " << i << endl;
+        }
+
+      FitBlindPixel(hist, (MCalibrationBlindPix&)(*fCam)[i]);
+    }
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns kFALSE, if empty
+//
+// - Creates the fourier spectrum and sets bit MHGausEvents::IsFourierSpectrumOK()
+// - Retrieves the pedestals from MExtractedSignalBlindPixel
+// - Normalizes fASinglePheFADCSlices and fAPedestalFADCSlices
+// - Executes FitPedestal()
+// - Executes FitSinglePhe()
+// - Retrieves fit results and stores them in MCalibrationBlindPix
+// 
+void MHCalibrationChargeBlindCam::FitBlindPixel(MHCalibrationChargeBlindPix &hist, MCalibrationBlindPix &pix)
+{
+
+  if (hist.IsEmpty())
+  {
+    *fLog << err << GetDescriptor() << " ID: " << hist.GetName()
+	  << " My histogram has not been filled !! " << endl;
+      return;
+  }
+
+  //hist.FinalizeSinglePheSpectrum();
+  
+  hist.FitPedestal();
+
+  pix.SetValid(kTRUE);
+
+  if (hist.FitSinglePhe())
+    pix.SetSinglePheFitOK();
+  else
+    pix.SetValid(hist.IsPedestalFitOK());
+
+  pix.SetLambda      ( hist.GetLambda   () );
+  pix.SetLambdaVar   ( hist.GetLambdaErr()*hist.GetLambdaErr() );
+  pix.SetMu0         ( hist.GetMu0      () );
+  pix.SetMu0Err      ( hist.GetMu0Err   () );
+  pix.SetMu1         ( hist.GetMu1      () );
+  pix.SetMu1Err      ( hist.GetMu1Err   () );
+  pix.SetSigma0      ( hist.GetSigma0   () );
+  pix.SetSigma0Err   ( hist.GetSigma0Err() );
+  pix.SetSigma1      ( hist.GetSigma1   () );
+  pix.SetSigma1Err   ( hist.GetSigma1Err() );
+  pix.SetProb        ( hist.GetProb     () );
+
+  pix.SetLambdaCheck    ( hist.GetLambdaCheck()    );
+  pix.SetLambdaCheckErr ( hist.GetLambdaCheckErr() );
+}
+
+// --------------------------------------------------------------------------
+//
+// This Clone-function has to be different from the MHCalibrationCam 
+// Clone function since it does not store and display the averaged values 
+// (in fAverageAreas), but the blind pixels stored in fHiGainArray. 
+//
+// Creates new MHCalibrationChargeBlindCam and
+// Clones MHCalibrationChargeBlindPix's individually
+//
+#if 0
+TObject *MHCalibrationChargeBlindCam::Clone(const char *name) const
+{
+
+  MHCalibrationChargeBlindCam *cam = new MHCalibrationChargeBlindCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+  cam->fFitFunc                = fFitFunc;
+
+  const Int_t nhi = fHiGainArray->GetSize();
+  
+  for (int i=0; i<nhi; i++)
+    cam->fHiGainArray->AddAt((*this)[i].Clone(),i);
+
+  return cam;
+}
+#endif
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationChargeBlindCam::Draw(Option_t *opt)
+{
+
+  const Int_t size = fHiGainArray->GetSize();
+
+  if (size == 0)
+    return;
+  
+  TString option(opt);
+  option.ToLower();
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  switch (size)
+    {
+    case 1: 
+      break;
+    case 2:
+      pad->Divide(2,1);
+      break;
+    case 3:
+    case 4:
+      pad->Divide(2,2);
+      break;
+    default:
+      pad->Divide(size/2+1,size/2+1);
+      break;
+    }
+
+  for (Int_t i=0; i<size;i++) 
+    {
+      pad->cd(i+1);
+      (*this)[i].Draw(option);
+    }
+
+  pad->Modified();
+  pad->Update();
+
+}
+
+Int_t MHCalibrationChargeBlindCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (MHCalibrationCam::ReadEnv(env,prefix,print))
+    rc = kTRUE;
+  
+  if (IsEnvDefined(env, prefix, "SPheCut", print))
+    {
+      SetSPheCut(GetEnvValue(env, prefix, "SPheCut", fSPheCut));
+      rc = kTRUE;
+    }
+  
+  // FIXME: GetEnvValue does not work with enums yet
+  /*
+  if (IsEnvDefined(env, prefix, "FitFunc", print))
+    {
+      SetFitFunc((Int_t)GetEnvValue(env, prefix, "FitFunc", fFitFunc));
+      rc = kTRUE;
+  }
+  */
+  return rc;
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindCam.h	(revision 17960)
@@ -0,0 +1,69 @@
+
+#ifndef MARS_MHCalibrationChargeBlindCam
+#define MARS_MHCalibrationChargeBlindCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MHCalibrationChargeBlindPix
+#include "MHCalibrationChargeBlindPix.h"
+#endif
+
+class MRawEvtData;
+class MCalibrationBlindPix;
+class MHCalibrationChargeBlindPix;
+class MHCalibrationChargeBlindCam : public MHCalibrationCam
+{
+private:
+
+  static const Int_t   fgNbins;        //! Default for fNBins new style blind pixel (now set to:  128   )
+  static const Axis_t  fgFirst;        //! Default for fFirst new style blind pixel (now set to: - 0.5 )
+  static const Axis_t  fgLast;         //! Default for fLast  new style blind pixel (now set to: 511.5 )
+
+  static const Axis_t  fgSPheCut;      //! Default for fSinglePheCut new style blind pixel (now set to: 20)
+  
+  static const TString gsHistName;     //! Default Histogram names
+  static const TString gsHistTitle;    //! Default Histogram titles
+  static const TString gsHistXTitle;   //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;   //! Default Histogram y-axis titles
+
+  Axis_t fSPheCut;                    // Signal value upon which event considered as single-phe
+  
+  MRawEvtData *fRawEvt;               //!  Raw event data
+
+  MHCalibrationChargeBlindPix::FitFunc_t fFitFunc; // The actual fit function type
+  
+  Bool_t SetupHists   (const MParList *pList );
+  Bool_t ReInitHists  (      MParList *pList );
+  Bool_t FillHists    (const MParContainer *par, const Stat_t w=1 );
+  Bool_t FinalizeHists();
+
+  void   ResetHistTitles();
+  void   FitBlindPixel( MHCalibrationChargeBlindPix &hist, MCalibrationBlindPix &pix);
+
+  Int_t ReadEnv        ( const TEnv &env, TString prefix, Bool_t print);  
+  
+public:
+
+  MHCalibrationChargeBlindCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeBlindCam() {}
+  
+  // Draw
+  void  Draw(Option_t *opt="");
+  void  SetFitFunc( const MHCalibrationChargeBlindPix::FitFunc_t func )  { fFitFunc = func;  }
+  void  SetSPheCut( const Axis_t    a   =fgSPheCut )  { fSPheCut = a;     }    
+  
+  ClassDef(MHCalibrationChargeBlindCam, 1)	// Histogram class for Blind Pixel Calibration
+};
+
+#endif
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindPix.cc	(revision 17960)
@@ -0,0 +1,1304 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargeBlindPix
+//
+//  Histogram class for the charge calibration of the Blind Pixel.
+//  Stores and fits the charges and stores the averaged assumed pedestal and 
+//  single-phe FADC slice entries. Charges are taken from MExtractedSignalBlindPix.
+//  Performs the Single Photo-electron fit to extract the Poisson mean and its errors.
+//
+//  Different fits can be chosen with the function SetFitFunc().
+//
+//  The fit result is accepted under the condition that:
+//  1) the Probability is greater than fProbLimit (default 0.001 == 99.7%)
+//  2) at least fNumSinglePheLimit events are found in the single Photo-electron peak
+//
+//  The single FADC slice entries are averaged and stored in fASinglePheFADCSlices, if 
+//  their sum exceeds fSinglePheCut, otherwise in fAPedestalFADCSlices.
+//
+//  Used numbers are the following:
+//
+//  Electronic conversion factor:
+//   Assume, we have N_e electrons at the anode, 
+//   thus a charge of N_e*e (e = electron charge) Coulomb.
+//
+//   This charge is AC coupled and runs into a R_pre = 50 Ohm resistency. 
+//   The corresponding current is amplified by a gain factor G_pre = 400 
+//   (the precision of this value still has to be checked !!!) and again AC coupled to 
+//   the output. 
+//   The corresponding signal goes through the whole transmission and 
+//   amplification chain and is digitized in the FADCs. 
+//   The conversion Signal Area to FADC counts (Conv_trans) has been measured 
+//   by David and Oscar to be approx. 3.9 pVs^-1
+//
+//   Thus: Conversion FADC counts to Number of Electrons at Anode: 
+//         FADC counts = (1/Conv_tran) * G_pre * R_pre *  e * N_e = 8 * 10^-4 N_e. 
+//
+//   Also: FADC counts = 8*10^-4 * GAIN * N_phe
+//
+//   In the blind pixel, there is an additional pre-amplifier with an amplification of 
+//   about 10. Therefore, we have for the blind pixel:
+//
+//
+//   FADC counts (Blind Pixel) = 8*10^-3 * GAIN * N_phe
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeBlindPix.h"
+
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TPaveText.h>
+#include <TPaveStats.h>
+#include <TGraph.h>
+
+#include <TVector.h>
+#include <TF1.h>
+#include <TH1.h>
+#include <TH2D.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MHCalibrationChargeBlindPix);
+
+using namespace std;
+
+const Double_t MHCalibrationChargeBlindPix::gkElectronicAmp      = 0.008;
+const Double_t MHCalibrationChargeBlindPix::gkElectronicAmpErr   = 0.002;
+const Float_t  MHCalibrationChargeBlindPix::gkSignalInitializer  = -9999.;
+const Float_t  MHCalibrationChargeBlindPix::fgNumSinglePheLimit  =  50.;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNumSinglePheLimit (fgNumSinglePheLimit)
+// - the default number of bins after stripping (30)
+//
+// Initializes:
+// - all pointers to NULL
+// - fASinglePheFADCSlices(0);
+// - fAPedestalFADCSlices(0);
+//
+// Calls:
+// - Clear()
+//
+MHCalibrationChargeBlindPix::MHCalibrationChargeBlindPix(const char *name, const char *title)
+    :  fSinglePheFit(NULL), 
+       fFitLegend(NULL),
+       fHSinglePheFADCSlices(NULL), fHPedestalFADCSlices(NULL)
+{
+
+    fName  = name  ? name  : "MHCalibrationChargeBlindPix";
+    fTitle = title ? title : "Statistics of the FADC sums of Blind Pixel calibration events";
+
+    //fASinglePheFADCSlices.ResizeTo(1);
+    //fAPedestalFADCSlices.ResizeTo(1);
+
+    SetNumSinglePheLimit();
+    SetProbLimit(0.001);
+    SetBinsAfterStripping(0);
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Destructor. 
+//
+// Deletes (if Pointer is not NULL):
+// 
+// - fFitLegend 
+// - fHSinglePheFADCSlices
+// - fHPedestalFADCSlices    
+// - fSinglePheFit
+// 
+MHCalibrationChargeBlindPix::~MHCalibrationChargeBlindPix()
+{
+
+  //
+  // The next two lines are important for the case that 
+  // the class has been stored to a file and is read again. 
+  // In this case, the next two lines prevent a segm. violation
+  // in the destructor
+  //
+  gROOT->GetListOfFunctions()->Remove(fSinglePheFit);
+
+  if (fSinglePheFit)
+      delete fSinglePheFit;
+  
+  if (fFitLegend)
+    delete fFitLegend;
+
+  if (fHSinglePheFADCSlices)
+    delete fHSinglePheFADCSlices;
+
+  if (fHPedestalFADCSlices)
+    delete fHPedestalFADCSlices;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - all variables to 0., except the fit result variables to gkSignalInitializer
+// - all flags to kFALSE
+// - all pointers to NULL
+// - the default fit function (kEPoisson5)
+//
+// Deletes: 
+// - all pointers unequal NULL
+//
+// Calls:
+// - MHCalibrationChargePix::Clear()
+//
+void MHCalibrationChargeBlindPix::Clear(Option_t *o)
+{
+
+  fLambda    = gkSignalInitializer;
+  fMu0       = gkSignalInitializer;
+  fMu1       = gkSignalInitializer;
+  fSigma0    = gkSignalInitializer;
+  fSigma1    = gkSignalInitializer;
+  fLambdaErr = gkSignalInitializer;
+  fMu0Err    = gkSignalInitializer;
+  fMu1Err    = gkSignalInitializer;
+  fSigma0Err = gkSignalInitializer;
+  fSigma1Err = gkSignalInitializer;
+
+  fLambdaCheck    = gkSignalInitializer;
+  fLambdaCheckErr = gkSignalInitializer;
+  
+  fFitFunc = kEPoisson5;
+
+  fNumSinglePhes    = 0;
+  fNumPedestals     = 0;
+
+  fChisquare        = 0.;
+  fNDF              = 0 ;
+  fProb             = 0.;
+
+  SetSinglePheFitOK ( kFALSE );
+  SetPedestalFitOK  ( kFALSE );
+
+  if (fFitLegend)
+  {
+    delete fFitLegend;
+    fFitLegend = NULL;
+  }
+
+  if (fSinglePheFit)
+  {
+    delete fSinglePheFit;
+    fSinglePheFit = NULL;
+  }
+
+  if (fHSinglePheFADCSlices)
+  {
+    delete fHSinglePheFADCSlices;
+    fHSinglePheFADCSlices = NULL;
+  }
+
+  if (fHPedestalFADCSlices)
+  {
+    delete fHPedestalFADCSlices;
+    fHPedestalFADCSlices = NULL;
+  }
+
+  MHCalibrationPix::Clear();
+  return;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Our own clone function is necessary since root 3.01/06 or Mars 0.4
+// I don't know the reason. 
+//
+// Creates new MHCalibrationCam
+//
+TObject *MHCalibrationChargeBlindPix::Clone(const char *) const
+{
+
+    MHCalibrationChargeBlindPix *pix = new MHCalibrationChargeBlindPix();
+    this->Copy(*pix);
+
+    this->fHGausHist.Copy(pix->fHGausHist);
+    this->fSinglePheFit->Copy(*(pix->fSinglePheFit));
+    this->fHSinglePheFADCSlices->Copy(*(pix->fHSinglePheFADCSlices));
+    this->fHPedestalFADCSlices->Copy(*(pix->fHPedestalFADCSlices));
+    
+
+    return pix;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Set bit kSinglePheFitOK from outside
+//
+void MHCalibrationChargeBlindPix::SetSinglePheFitOK (const Bool_t b ) 
+{
+    b ? SETBIT(fFlags,kSinglePheFitOK) : CLRBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set bit kPedestalFitOK from outside
+//
+void MHCalibrationChargeBlindPix::SetPedestalFitOK(const Bool_t b)
+{
+    b ? SETBIT(fFlags,kPedestalFitOK) : CLRBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Ask for status of bit kSinglePheFitOK 
+//
+const Bool_t  MHCalibrationChargeBlindPix::IsSinglePheFitOK()     const 
+{
+    return TESTBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Ask for status of bit kPedestalFitOK 
+//
+const Bool_t  MHCalibrationChargeBlindPix::IsPedestalFitOK()  const
+{
+    return TESTBIT(fFlags,kPedestalFitOK);
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Normalizes fASinglePheFADCSlices and fAPedestalFADCSlices
+//
+void MHCalibrationChargeBlindPix::FinalizeSinglePheSpectrum() 
+{
+  
+  if (fNumSinglePhes > 1)
+      for (Int_t i=0;i<fASinglePheFADCSlices.GetNrows();i++)
+	  fASinglePheFADCSlices[i] = fASinglePheFADCSlices[i]/fNumSinglePhes;
+  if (fNumPedestals > 1)
+      for (Int_t i=0;i<fAPedestalFADCSlices.GetNrows();i++)
+        fAPedestalFADCSlices[i]  = fAPedestalFADCSlices[i]/fNumPedestals;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks again for the size and fills fASinglePheFADCSlices with the FADC slice entries
+// 
+void MHCalibrationChargeBlindPix::FillSinglePheFADCSlices(const MRawEvtPixelIter &iter)
+{
+
+  const Int_t n = iter.GetNumHiGainSamples() + iter.GetNumLoGainSamples();
+
+  if (fASinglePheFADCSlices.GetNrows() < n)
+      fASinglePheFADCSlices.ResizeTo(n);
+  
+  Int_t i=0;
+  
+  Byte_t *start = iter.GetHiGainSamples();
+  Byte_t *end   = start + iter.GetNumHiGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fASinglePheFADCSlices(i) = fASinglePheFADCSlices(i) + (Float_t)*ptr;
+
+  start = iter.GetLoGainSamples();
+  end   = start + iter.GetNumLoGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fASinglePheFADCSlices(i) = fASinglePheFADCSlices(i) + (Float_t)*ptr;
+
+  fNumSinglePhes++;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks again for the size and fills fAPedestalFADCSlices with the FADC slice entries
+// 
+void MHCalibrationChargeBlindPix::FillPedestalFADCSlices(const MRawEvtPixelIter &iter)
+{
+
+  const Int_t n = iter.GetNumHiGainSamples() + iter.GetNumLoGainSamples();
+
+  if (fAPedestalFADCSlices.GetNrows() < n)
+      fAPedestalFADCSlices.ResizeTo(n);
+
+  Int_t i = 0;
+  Byte_t *start = iter.GetHiGainSamples();
+  Byte_t *end   = start + iter.GetNumHiGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fAPedestalFADCSlices(i) = fAPedestalFADCSlices(i)+ (Float_t)*ptr;
+
+  start = iter.GetLoGainSamples();
+  end   = start + iter.GetNumLoGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fAPedestalFADCSlices(i) = fAPedestalFADCSlices(i)+ (Float_t)*ptr;
+
+  fNumPedestals++;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Task to simulate single phe spectrum with the given parameters
+// 
+Bool_t MHCalibrationChargeBlindPix::SimulateSinglePhe(Double_t lambda, Double_t mu0, Double_t mu1, Double_t sigma0, Double_t sigma1) 
+{
+
+  gRandom->SetSeed();
+
+  if (fHGausHist.GetIntegral() != 0)
+    {
+      *fLog << err << "Histogram " << fHGausHist.GetTitle() << " is already filled. " << endl;
+      *fLog << err << "Create new class MHCalibrationBlindPixel for simulation! " << endl;
+      return kFALSE;
+    }
+
+  if (!InitFit())
+    return kFALSE;
+
+  for (Int_t i=0;i<10000; i++) 
+    fHGausHist.Fill(fSinglePheFit->GetRandom());
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Get the ranges from the stripped histogram
+// - choose reasonable start values for the fit
+// - initialize the fit function depending on fFitFunc
+// - initialize parameter names and limits depending on fFitFunc
+//
+Bool_t MHCalibrationChargeBlindPix::InitFit()
+{
+  
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetFirst());
+  Axis_t rmax = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetLast()); 
+
+  if (rmin < 0.)
+      rmin = 0.;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  // otherwise the fit goes gaga because of high number of dimensions ...
+  //
+  const Stat_t   entries      = fHGausHist.Integral("width");
+  const Double_t lambda_guess = 0.5;
+  //const Double_t maximum_bin  = fHGausHist.GetBinCenter(fHGausHist.GetMaximumBin());
+  const Double_t norm         = entries/TMath::Sqrt(TMath::TwoPi());
+
+  //
+  // Initialize the fit function
+  //
+  switch (fFitFunc)
+    {
+    case kEPoisson4:
+      fSinglePheFit = new TF1("SinglePheFit",&PoissonKto4,rmin,rmax,6);
+      rmin += 6.5;
+      break;
+    case kEPoisson5:
+      fSinglePheFit = new TF1("SinglePheFit",&PoissonKto5,rmin,rmax,6);
+      rmin = 0.;
+      break;
+    case kEPoisson6:
+      fSinglePheFit = new TF1("SinglePheFit",&PoissonKto6,rmin,rmax,6);
+      break;
+    case kEPolya:
+      fSinglePheFit = new TF1("SinglePheFit",&Polya,rmin,rmax,8);
+      break;
+    case kEMichele:
+      fSinglePheFit = new TF1("SinglePheFit",&FitFuncMichele,rmin,rmax,9);
+      break;
+    default:
+      *fLog << warn << "WARNING: Could not find Fit Function for Blind Pixel " << endl;
+      return kFALSE;
+      break;
+    }
+
+  if (!fSinglePheFit) 
+  {
+      *fLog << warn << dbginf << "WARNING: Could not create fit function for Single Phe fit" << endl;
+      return kFALSE;
+  }
+
+  //
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  // 
+  gROOT->GetListOfFunctions()->Remove(fSinglePheFit);
+  
+  const Double_t mu_0_guess = 13.5;
+  const Double_t si_0_guess = 2.5;
+  const Double_t mu_1_guess = 30.;
+  const Double_t si_1_guess = si_0_guess + si_0_guess;
+  // Michele
+  const Double_t lambda_1cat_guess = 1.00;
+  const Double_t lambda_1dyn_guess = lambda_1cat_guess/10.;
+  const Double_t mu_1cat_guess = 50.;
+  const Double_t mu_1dyn_guess = 17.;
+  const Double_t si_1cat_guess = si_0_guess + si_0_guess;
+  const Double_t si_1dyn_guess = si_0_guess + si_0_guess/2.;
+  // Polya
+  const Double_t excessPoisson_guess = 0.5;
+  const Double_t delta1_guess     = 8.;
+  const Double_t delta2_guess     = 5.;
+  const Double_t electronicAmp_guess  = gkElectronicAmp;
+  const Double_t electronicAmp_limit  = gkElectronicAmpErr;
+
+  //
+  // Initialize boundaries and start parameters
+  //
+  switch (fFitFunc)
+    {
+      
+    case kEPoisson4:
+	fSinglePheFit->SetParNames(  "#lambda",   "#mu_{0}",    "#mu_{1}", "#sigma_{0}",  "#sigma_{1}","Area");
+        fSinglePheFit->SetParameters(lambda_guess,mu_0_guess,mu_1_guess,si_0_guess,si_1_guess,norm);
+	fSinglePheFit->SetParLimits(0,0.,2.);
+        fSinglePheFit->SetParLimits(1,10.,17.);
+	fSinglePheFit->SetParLimits(2,17.,50.);
+        fSinglePheFit->SetParLimits(3,1.,5.);
+	fSinglePheFit->SetParLimits(4,5.,30.);
+	fSinglePheFit->SetParLimits(5,norm-(0.5*norm),norm+(0.7*norm));
+	break;
+    case kEPoisson5:
+    case kEPoisson6:
+      fSinglePheFit->SetParNames("#lambda","#mu_{0}","#mu_{1}","#sigma_{0}","#sigma_{1}","Area");
+      fSinglePheFit->SetParameters(lambda_guess,mu_0_guess,800.,si_0_guess,500.,norm);
+      fSinglePheFit->SetParLimits(0,0.,2.);
+      fSinglePheFit->SetParLimits(1,0.,100.);
+      fSinglePheFit->SetParLimits(2,300.,1500.);
+      fSinglePheFit->SetParLimits(3,30.,250.);
+      fSinglePheFit->SetParLimits(4,100.,1000.);
+      fSinglePheFit->SetParLimits(5,norm/1.5,norm*1.5);
+      break;
+
+    case kEPolya:
+        fSinglePheFit->SetParameters(lambda_guess, excessPoisson_guess,
+                                     delta1_guess,delta2_guess,
+                                     electronicAmp_guess,
+                                     10.,
+                                     norm, 
+                                     0.);
+      fSinglePheFit->SetParNames("#lambda","b_{tot}",
+                                 "#delta_{1}","#delta_{2}",
+                                 "amp_{e}","#sigma_{0}",
+                                 "Area", "#mu_{0}");
+      fSinglePheFit->SetParLimits(0,0.,1.);
+      fSinglePheFit->SetParLimits(1,0.,1.); 
+      fSinglePheFit->SetParLimits(2,6.,12.);    
+      fSinglePheFit->SetParLimits(3,3.,8.);    
+      fSinglePheFit->SetParLimits(4,electronicAmp_guess-electronicAmp_limit,
+                                    electronicAmp_guess+electronicAmp_limit);    
+      fSinglePheFit->SetParLimits(5,0.,40.);
+      fSinglePheFit->SetParLimits(6,norm-0.1,norm+0.1);
+      fSinglePheFit->SetParLimits(7,-10.,10.);
+      break;
+    case kEMichele:
+      fSinglePheFit->SetParNames("#lambda_{cat}","#lambda_{dyn}",
+                                 "#mu_{0}","#mu_{1cat}","#mu_{1dyn}",
+                                 "#sigma_{0}","#sigma_{1cat}","#sigma_{1dyn}",
+                                 "Area");
+      fSinglePheFit->SetParameters(lambda_1cat_guess, lambda_1dyn_guess, 
+                                   mu_0_guess, mu_1cat_guess,mu_1dyn_guess,
+                                   si_0_guess, si_1cat_guess,si_1dyn_guess,
+                                   norm);
+      fSinglePheFit->SetParLimits(0,0.01,2.0);
+      fSinglePheFit->SetParLimits(1,0.,0.5); 
+      fSinglePheFit->SetParLimits(2,10.,16.);    
+      fSinglePheFit->SetParLimits(3,25.,50.);    
+      fSinglePheFit->SetParLimits(4,16.,18.5);    
+      fSinglePheFit->SetParLimits(5,1.,5.);    
+      fSinglePheFit->SetParLimits(6,10.,50.);    
+      fSinglePheFit->SetParLimits(7,5.,10.);    
+      fSinglePheFit->SetParLimits(8,norm/2.,norm*2.5);
+      break;
+
+    default:
+      *fLog << warn << "WARNING: Could not find Fit Function for Blind Pixel " << endl;
+      return kFALSE;
+      break;
+    }
+
+  fSinglePheFit->SetRange(rmin,rmax);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Retrieve the parameters depending on fFitFunc
+// - Retrieve probability, Chisquare and NDF
+//
+void MHCalibrationChargeBlindPix::ExitFit()
+{
+  
+
+  //
+  // Finalize
+  //
+  switch (fFitFunc)
+    {
+      
+    case kEPoisson4:
+    case kEPoisson5:
+    case kEPoisson6:
+    case kEPoisson7:
+      fLambda = fSinglePheFit->GetParameter(0);
+      fMu0    = fSinglePheFit->GetParameter(1);
+      fMu1    = fSinglePheFit->GetParameter(2);
+      fSigma0 = fSinglePheFit->GetParameter(3);
+      fSigma1 = fSinglePheFit->GetParameter(4);
+      
+      fLambdaErr = fSinglePheFit->GetParError(0);
+      fMu0Err    = fSinglePheFit->GetParError(1);
+      fMu1Err    = fSinglePheFit->GetParError(2);
+      fSigma0Err = fSinglePheFit->GetParError(3);
+      fSigma1Err = fSinglePheFit->GetParError(4);
+      break;
+    case kEPolya:
+      fLambda =  fSinglePheFit->GetParameter(0);
+      fMu0    =  fSinglePheFit->GetParameter(7);
+      fMu1    = 0.;
+      fSigma0 =  fSinglePheFit->GetParameter(5);
+      fSigma1 = 0.;
+
+      fLambdaErr = fSinglePheFit->GetParError(0);
+      fMu0Err    = fSinglePheFit->GetParError(7);
+      fMu1Err    = 0.;
+      fSigma0Err = fSinglePheFit->GetParError(5);
+      fSigma1Err = 0.;
+    case kEMichele:
+      fLambda =  fSinglePheFit->GetParameter(0);
+      fMu0    =  fSinglePheFit->GetParameter(2);
+      fMu1    =  fSinglePheFit->GetParameter(3);
+      fSigma0 =  fSinglePheFit->GetParameter(5);
+      fSigma1 =  fSinglePheFit->GetParameter(6);
+
+      fLambdaErr = fSinglePheFit->GetParError(0);
+      fMu0Err    = fSinglePheFit->GetParError(2);
+      fMu1Err    = fSinglePheFit->GetParError(3);
+      fSigma0Err = fSinglePheFit->GetParError(5);
+      fSigma1Err = fSinglePheFit->GetParError(6);
+      break;
+    default:
+      break;
+    }
+
+  fProb      = fSinglePheFit->GetProb();
+  fChisquare = fSinglePheFit->GetChisquare();
+  fNDF       = fSinglePheFit->GetNDF();
+
+  *fLog << all << "Results of the Blind Pixel Fit: "              << endl;
+  *fLog << all << "Chisquare:   " << fChisquare                   << endl;
+  *fLog << all << "DoF:         " << fNDF                         << endl;
+  *fLog << all << "Probability: " << fProb                        << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// - Executes InitFit()
+// - Fits the fHGausHist with fSinglePheFit
+// - Executes ExitFit()
+//
+// The fit result is accepted under condition:
+// 1) The results are not nan's
+// 2) The NDF is not smaller than fNDFLimit (5)
+// 3) The Probability is greater than fProbLimit (default 0.001 == 99.9%)
+// 4) at least fNumSinglePheLimit events are in the single Photo-electron peak
+//
+Bool_t MHCalibrationChargeBlindPix::FitSinglePhe(Option_t *opt) 
+{
+
+  if (!InitFit())
+      return kFALSE;
+
+  fHGausHist.Fit(fSinglePheFit,opt);
+
+  ExitFit();
+
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (5)
+  // 3) The Probability is greater than fProbLimit (default 0.001 == 99.9%)
+  // 4) at least fNumSinglePheLimit events are in the single Photo-electron peak
+  //
+  // !Finitite means either infinite or not-a-number
+  if (   !TMath::Finite(fLambda)
+      || !TMath::Finite(fLambdaErr)
+      || !TMath::Finite(fProb)
+      || !TMath::Finite(fMu0)
+      || !TMath::Finite(fMu0Err)
+      || !TMath::Finite(fMu1)
+      || !TMath::Finite(fMu1Err)
+      || !TMath::Finite(fSigma0)
+      || !TMath::Finite(fSigma0Err)
+      || !TMath::Finite(fSigma1)
+      || !TMath::Finite(fSigma1Err)
+      || fNDF  < GetNDFLimit()
+      || fProb < GetProbLimit() )
+    return kFALSE;
+
+  const Stat_t   entries      = fHGausHist.Integral("width");
+  const Float_t  numSinglePhe = TMath::Exp(-1.0*fLambda)*fLambda*entries;
+  
+  if (numSinglePhe < fNumSinglePheLimit) 
+    {
+      *fLog << warn << "WARNING - Statistics is too low: Only " << numSinglePhe
+            << " in the Single Photo-Electron peak " << endl;
+      return kFALSE;
+    } 
+  else
+    *fLog << all << numSinglePhe << " in Single Photo-Electron peak " << endl;
+  
+  SetSinglePheFitOK();
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Retrieves limits for the fit
+// - Fits the fHGausHist with Gauss 
+// - Retrieves the results to fLambdaCheck and fLambdaCheckErr
+// - Sets a flag IsPedestalFitOK()
+//
+void MHCalibrationChargeBlindPix::FitPedestal  (Option_t *opt)
+{
+
+  // Perform the cross-check fitting only the pedestal:
+  const Axis_t rmin    = 0.;
+  //  const Axis_t rmax    = fHGausHist.GetBinCenter(fHGausHist.GetMaximumBin());
+  const Axis_t rmax = fSinglePheCut;
+
+  FitGaus(opt, rmin, rmax);
+
+  const Stat_t   entries = fHGausHist.Integral("width");
+  const Double_t pedarea = fFGausFit->Integral(0.,fSinglePheCut);
+
+  fLambdaCheck     = TMath::Log(entries/pedarea);
+  // estimate the error by the error of the obtained area from the Gauss-function:
+  fLambdaCheckErr  = fFGausFit->GetParError(0)/fFGausFit->GetParameter(0);
+  
+  SetPedestalFitOK(IsGausFitOK());
+  return;
+}
+
+ 
+// -------------------------------------------------------------------------
+//
+// Draw a legend with the fit results
+//
+void MHCalibrationChargeBlindPix::DrawLegend(Option_t *opt)
+{
+
+  TString option(opt);
+
+  if (!fFitLegend)
+  {
+      fFitLegend = new TPaveText(0.05,0.05,0.95,0.95);
+      fFitLegend->SetLabel(Form("%s%s", "Results of the single PhE Fit (",
+				(fFitFunc ==  kEPoisson4) ? "Poisson(k=4))" : 
+				(fFitFunc ==  kEPoisson5) ? "Poisson(k=5))" : 
+				(fFitFunc ==  kEPoisson6) ? "Poisson(k=6))" :
+				(fFitFunc ==  kEPolya   ) ? "Polya(k=4))"   : 
+				(fFitFunc ==  kEMichele ) ?  "Michele)"     
+                                                                                       : " none )" ));
+      fFitLegend->SetTextSize(0.05);
+  }
+  else
+      fFitLegend->Clear();
+
+  const TString line1 = 
+      Form("Mean: #lambda = %2.2f #pm %2.2f",fLambda,fLambdaErr);
+  TText *t1 = fFitLegend->AddText(line1.Data());
+  t1->SetBit(kCanDelete);
+      
+  const TString line6 =
+      Form("Mean #lambda_{check} = %2.2f #pm %2.2f",fLambdaCheck,fLambdaCheckErr);
+  TText *t2 = fFitLegend->AddText(line6.Data());
+  t2->SetBit(kCanDelete);
+
+  if (option.Contains("datacheck"))
+    {
+      if (fLambda + 3.*fLambdaErr < fLambdaCheck - 3.*fLambdaCheckErr 
+          || 
+          fLambda - 3.*fLambdaErr > fLambdaCheck + 3.*fLambdaCheckErr )
+        {
+          TText *t = fFitLegend->AddText("#lambda and #lambda_{check} more than 3#sigma apart!");
+          t->SetBit(kCanDelete);
+        }
+    }
+  else
+    {
+
+      const TString line2 = 
+        Form("Pedestal: #mu_{0} = %2.2f #pm %2.2f",fMu0,fMu0Err);
+      TText *t3 = fFitLegend->AddText(line2.Data());
+      t3->SetBit(kCanDelete);
+      
+      const TString line3 =
+        Form("Width Pedestal: #sigma_{0} = %2.2f #pm %2.2f",fSigma0,fSigma0Err);
+      TText *t4 = fFitLegend->AddText(line3.Data());
+      t4->SetBit(kCanDelete);
+      
+      const TString line4 =
+        Form("1^{st} Phe-peak: #mu_{1} = %2.2f #pm %2.2f",fMu1,fMu1Err);
+      TText *t5 = fFitLegend->AddText(line4.Data());
+      t5->SetBit(kCanDelete);
+      
+      const TString line5 =
+        Form("Width 1^{st} Phe-peak: #sigma_{1} = %2.2f #pm %2.2f",fSigma1,fSigma1Err);
+      TText *t6 = fFitLegend->AddText(line5.Data());
+      t6->SetBit(kCanDelete);
+    }
+  
+  const TString line7 =
+    Form("#chi^{2} / N_{dof}: %4.2f / %3i",fChisquare,fNDF);
+  TText *t7 = fFitLegend->AddText(line7.Data());
+  t7->SetBit(kCanDelete);
+  
+  const TString line8 =
+      Form("Probability: %6.4f ",fProb);
+  TText *t8 = fFitLegend->AddText(line8.Data());
+  t8->SetBit(kCanDelete);
+  
+  if (IsSinglePheFitOK())
+  {
+      TText *t = fFitLegend->AddText("Result of the Fit: OK");
+      t->SetBit(kCanDelete);
+  }
+  else
+  {
+      TText *t = fFitLegend->AddText("Result of the Fit: NOT OK");
+      t->SetBit(kCanDelete);
+  }
+
+  fFitLegend->SetFillColor(IsSinglePheFitOK() ? 80 : 2);
+  fFitLegend->Draw();
+  
+  return;
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+// The following options can be chosen:
+//
+// "": displays the fHGausHist, the fits, the legend and fASinglePheFADCSlices and fAPedestalFADCSlices
+// "all": executes additionally MHGausEvents::Draw(), with option "fourierevents"
+// "datacheck" display the fHGausHist, the fits and the legend
+//
+void MHCalibrationChargeBlindPix::Draw(Option_t *opt) 
+{
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+
+  TVirtualPad *oldpad = gPad ? gPad : MH::MakeDefCanvas(this,900, 600);
+  TVirtualPad *pad    = NULL;
+
+  if (option.Contains("all"))
+  {
+      option.ReplaceAll("all","");
+      oldpad->Divide(2,1);
+      win = 2;
+      oldpad->cd(1);
+      TVirtualPad *newpad = gPad;
+      pad = newpad;
+      pad->Divide(2,2);
+      pad->cd(1);
+  }
+  else if (option.Contains("datacheck"))
+    {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+      fHGausHist.SetStats(0);
+    }
+  else
+  {
+      pad = oldpad;
+      pad->Divide(2,2);
+      pad->cd(1);
+  }
+
+  if (!IsEmpty() && !IsOnlyOverflow() && !IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.Draw(); 
+  if (fFGausFit )
+  {
+      fFGausFit->SetLineColor(kBlue);
+      fFGausFit->Draw("same");
+      if (!option.Contains("datacheck"))
+        {
+          TLine *line = new TLine(fSinglePheCut, 0., fSinglePheCut, 10.);
+          line->SetBit(kCanDelete);
+          line->SetLineColor(kBlue);
+          line->SetLineWidth(3);
+          line->DrawLine(fSinglePheCut, 0., fSinglePheCut, 2.);
+        }
+  }
+  
+  if (fSinglePheFit)
+  {    
+    fSinglePheFit->SetFillStyle(0);
+    fSinglePheFit->SetLineWidth(3);
+    fSinglePheFit->SetLineColor(IsSinglePheFitOK() ? kGreen : kRed);          
+    fSinglePheFit->Draw("same");
+  }
+
+  pad->cd(2);
+  DrawLegend(option.Data());
+
+  if (option.Contains("datacheck"))
+    return;
+/*
+  pad->cd(3);
+  if (fASinglePheFADCSlices.GetNrows()!=1)
+    {
+      if (fHSinglePheFADCSlices)
+        delete fHSinglePheFADCSlices;
+
+      fHSinglePheFADCSlices = new TH1F(fASinglePheFADCSlices);
+      fHSinglePheFADCSlices->SetName("SinglePheFADCSlices");
+      fHSinglePheFADCSlices->SetTitle(Form("%s%4.1f","Assumed Single Phe FADC Slices, Sum > ",fSinglePheCut));
+      fHSinglePheFADCSlices->SetXTitle("FADC slice number");
+      fHSinglePheFADCSlices->SetYTitle("FADC counts");
+      const Int_t nbins = fHSinglePheFADCSlices->GetNbinsX();
+      TH2D *nulls = new TH2D("Nulls",fHSinglePheFADCSlices->GetTitle(),nbins,0.,
+                            fHSinglePheFADCSlices->GetXaxis()->GetBinCenter(nbins),
+                            100,0.,50.);
+      nulls->SetDirectory(NULL);
+      nulls->SetBit(kCanDelete);
+      nulls->GetXaxis()->SetTitle(fHSinglePheFADCSlices->GetXaxis()->GetTitle());
+      nulls->GetYaxis()->SetTitle(fHSinglePheFADCSlices->GetYaxis()->GetTitle());  
+      nulls->GetXaxis()->CenterTitle();
+      nulls->GetYaxis()->CenterTitle();
+      nulls->SetStats(0);
+      nulls->Draw();
+      fHSinglePheFADCSlices->Draw("same");
+    }
+  
+  pad->cd(4);
+  if (fAPedestalFADCSlices.GetNrows()!=1)
+    {
+
+      if (fHPedestalFADCSlices)
+        delete fHPedestalFADCSlices;
+      
+      fHPedestalFADCSlices = new TH1F(fAPedestalFADCSlices);
+      fHPedestalFADCSlices->SetName("PedestalFADCSlices");
+      fHPedestalFADCSlices->SetTitle(Form("%s%4.1f","Pedestal FADC Slices, Sum < ",fSinglePheCut));
+      fHPedestalFADCSlices->SetXTitle("FADC slice number");
+      fHPedestalFADCSlices->SetYTitle("FADC counts");
+      const Int_t nbins = fHPedestalFADCSlices->GetNbinsX();
+      TH2D *nullp = new TH2D("Nullp",fHPedestalFADCSlices->GetTitle(),nbins,0.,
+                            fHPedestalFADCSlices->GetXaxis()->GetBinCenter(nbins),
+                            100,0.,50.);
+      nullp->SetDirectory(NULL);
+      nullp->SetBit(kCanDelete);
+      nullp->GetXaxis()->SetTitle(fHPedestalFADCSlices->GetXaxis()->GetTitle());
+      nullp->GetYaxis()->SetTitle(fHPedestalFADCSlices->GetYaxis()->GetTitle());  
+      nullp->GetXaxis()->CenterTitle();
+      nullp->GetYaxis()->CenterTitle();
+      nullp->SetStats(0);
+      nullp->Draw();
+      fHPedestalFADCSlices->Draw("same");
+    }
+  */
+  if (win < 2)
+  return;
+
+  oldpad->cd(2);
+  MHCalibrationPix::Draw("fourierevents");
+}
+
+Double_t MHCalibrationChargeBlindPix::FitFuncMichele(Double_t *x, Double_t *par)
+{
+    Double_t lambda1cat = par[0];
+    Double_t lambda1dyn = par[1];
+    Double_t mu0        = par[2];
+    Double_t mu1cat     = par[3];
+    Double_t mu1dyn     = par[4];
+    Double_t sigma0     = par[5];
+    Double_t sigma1cat  = par[6];
+    Double_t sigma1dyn  = par[7];
+
+    Double_t sumcat = 0.;
+    Double_t sumdyn = 0.;
+    Double_t arg    = 0.;
+
+    if (lambda1cat < lambda1dyn)
+        return FLT_MAX;
+
+    if (mu1cat    < mu0)
+        return FLT_MAX;
+
+    if (mu1dyn    < mu0)
+        return FLT_MAX;
+
+    if (mu1cat < mu1dyn)
+        return FLT_MAX;
+
+    if (sigma0 < 0.0001)
+        return FLT_MAX;
+
+    if (sigma1cat < sigma0)
+        return FLT_MAX;
+
+    if (sigma1dyn < sigma0)
+        return FLT_MAX;
+
+    Double_t mu2cat = (2.*mu1cat)-mu0;
+    Double_t mu2dyn = (2.*mu1dyn)-mu0;
+    Double_t mu3cat = (3.*mu1cat)-(2.*mu0);
+    Double_t mu3dyn = (3.*mu1dyn)-(2.*mu0);
+
+    Double_t sigma2cat = TMath::Sqrt((2.*sigma1cat*sigma1cat) - (sigma0*sigma0));
+    Double_t sigma2dyn = TMath::Sqrt((2.*sigma1dyn*sigma1dyn) - (sigma0*sigma0));
+    Double_t sigma3cat = TMath::Sqrt((3.*sigma1cat*sigma1cat) - (2.*sigma0*sigma0));
+    Double_t sigma3dyn = TMath::Sqrt((3.*sigma1dyn*sigma1dyn) - (2.*sigma0*sigma0));
+
+    Double_t lambda2cat = lambda1cat*lambda1cat;
+    Double_t lambda2dyn = lambda1dyn*lambda1dyn;
+    Double_t lambda3cat = lambda2cat*lambda1cat;
+    Double_t lambda3dyn = lambda2dyn*lambda1dyn;
+
+    // k=0:
+    arg = (x[0] - mu0)/sigma0;
+    sumcat = TMath::Exp(-0.5*arg*arg)/sigma0;
+    sumdyn = sumcat;
+
+    // k=1cat:
+    arg = (x[0] - mu1cat)/sigma1cat;
+    sumcat += lambda1cat*TMath::Exp(-0.5*arg*arg)/sigma1cat;
+    // k=1dyn:
+    arg = (x[0] - mu1dyn)/sigma1dyn;
+    sumdyn += lambda1dyn*TMath::Exp(-0.5*arg*arg)/sigma1dyn;
+
+    // k=2cat:
+    arg = (x[0] - mu2cat)/sigma2cat;
+    sumcat += 0.5*lambda2cat*TMath::Exp(-0.5*arg*arg)/sigma2cat;
+    // k=2dyn:
+    arg = (x[0] - mu2dyn)/sigma2dyn;
+    sumdyn += 0.5*lambda2dyn*TMath::Exp(-0.5*arg*arg)/sigma2dyn;
+
+
+    // k=3cat:
+    arg = (x[0] - mu3cat)/sigma3cat;
+    sumcat += 0.1666666667*lambda3cat*TMath::Exp(-0.5*arg*arg)/sigma3cat;
+    // k=3dyn:
+    arg = (x[0] - mu3dyn)/sigma3dyn;
+    sumdyn += 0.1666666667*lambda3dyn*TMath::Exp(-0.5*arg*arg)/sigma3dyn;
+
+    sumcat = TMath::Exp(-1.*lambda1cat)*sumcat;
+    sumdyn = TMath::Exp(-1.*lambda1dyn)*sumdyn;
+
+    return par[8]*(sumcat+sumdyn)/2.;
+}
+
+Double_t MHCalibrationChargeBlindPix::PoissonKto4(Double_t *x, Double_t *par)
+{
+    Double_t lambda = par[0];
+
+    Double_t sum = 0.;
+    Double_t arg = 0.;
+
+    Double_t mu0 = par[1];
+    Double_t mu1 = par[2];
+
+    if (mu1 < mu0)
+        return FLT_MAX;
+
+    Double_t sigma0 = par[3];
+    Double_t sigma1 = par[4];
+
+    if (sigma0 < 0.0001)
+        return FLT_MAX;
+
+    if (sigma1 < sigma0)
+        return FLT_MAX;
+
+    Double_t mu2 = (2.*mu1)-mu0;
+    Double_t mu3 = (3.*mu1)-(2.*mu0);
+    Double_t mu4 = (4.*mu1)-(3.*mu0);
+
+    Double_t sigma2 = TMath::Sqrt((2.*sigma1*sigma1) - (sigma0*sigma0));
+    Double_t sigma3 = TMath::Sqrt((3.*sigma1*sigma1) - (2.*sigma0*sigma0));
+    Double_t sigma4 = TMath::Sqrt((4.*sigma1*sigma1) - (3.*sigma0*sigma0));
+
+    Double_t lambda2 = lambda*lambda;
+    Double_t lambda3 = lambda2*lambda;
+    Double_t lambda4 = lambda3*lambda;
+
+    // k=0:
+    arg = (x[0] - mu0)/sigma0;
+    sum = TMath::Exp(-0.5*arg*arg)/sigma0;
+
+    // k=1:
+    arg = (x[0] - mu1)/sigma1;
+    sum += lambda*TMath::Exp(-0.5*arg*arg)/sigma1;
+
+    // k=2:
+    arg = (x[0] - mu2)/sigma2;
+    sum += 0.5*lambda2*TMath::Exp(-0.5*arg*arg)/sigma2;
+
+    // k=3:
+    arg = (x[0] - mu3)/sigma3;
+    sum += 0.1666666667*lambda3*TMath::Exp(-0.5*arg*arg)/sigma3;
+
+    // k=4:
+    arg = (x[0] - mu4)/sigma4;
+    sum += 0.041666666666667*lambda4*TMath::Exp(-0.5*arg*arg)/sigma4;
+
+    return TMath::Exp(-1.*lambda)*par[5]*sum;
+}
+
+Double_t MHCalibrationChargeBlindPix::PoissonKto5(Double_t *x, Double_t *par)
+{
+    Double_t lambda = par[0];
+
+    Double_t sum = 0.;
+    Double_t arg = 0.;
+
+    Double_t mu0 = par[1];
+    Double_t mu1 = par[2];
+
+    if (mu1 < mu0)
+        return FLT_MAX;
+
+    Double_t sigma0 = par[3];
+    Double_t sigma1 = par[4];
+
+    if (sigma0 < 0.0001)
+        return FLT_MAX;
+
+    if (sigma1 < sigma0)
+        return FLT_MAX;
+
+
+    Double_t mu2 = (2.*mu1)-mu0;
+    Double_t mu3 = (3.*mu1)-(2.*mu0);
+    Double_t mu4 = (4.*mu1)-(3.*mu0);
+    Double_t mu5 = (5.*mu1)-(4.*mu0);
+
+    Double_t sigma2 = TMath::Sqrt((2.*sigma1*sigma1) - (sigma0*sigma0));
+    Double_t sigma3 = TMath::Sqrt((3.*sigma1*sigma1) - (2.*sigma0*sigma0));
+    Double_t sigma4 = TMath::Sqrt((4.*sigma1*sigma1) - (3.*sigma0*sigma0));
+    Double_t sigma5 = TMath::Sqrt((5.*sigma1*sigma1) - (4.*sigma0*sigma0));
+
+    Double_t lambda2 = lambda*lambda;
+    Double_t lambda3 = lambda2*lambda;
+    Double_t lambda4 = lambda3*lambda;
+    Double_t lambda5 = lambda4*lambda;
+
+    // k=0:
+    arg = (x[0] - mu0)/sigma0;
+    sum = TMath::Exp(-0.5*arg*arg)/sigma0;
+
+    // k=1:
+    arg = (x[0] - mu1)/sigma1;
+    sum += lambda*TMath::Exp(-0.5*arg*arg)/sigma1;
+
+    // k=2:
+    arg = (x[0] - mu2)/sigma2;
+    sum += 0.5*lambda2*TMath::Exp(-0.5*arg*arg)/sigma2;
+
+    // k=3:
+    arg = (x[0] - mu3)/sigma3;
+    sum += 0.1666666667*lambda3*TMath::Exp(-0.5*arg*arg)/sigma3;
+
+    // k=4:
+    arg = (x[0] - mu4)/sigma4;
+    sum += 0.041666666666667*lambda4*TMath::Exp(-0.5*arg*arg)/sigma4;
+
+    // k=5:
+    arg = (x[0] - mu5)/sigma5;
+    sum += 0.008333333333333*lambda5*TMath::Exp(-0.5*arg*arg)/sigma5;
+
+    return TMath::Exp(-1.*lambda)*par[5]*sum;
+}
+
+Double_t MHCalibrationChargeBlindPix::PoissonKto6(Double_t *x, Double_t *par)
+{
+    Double_t lambda = par[0];
+
+    Double_t sum = 0.;
+    Double_t arg = 0.;
+
+    Double_t mu0 = par[1];
+    Double_t mu1 = par[2];
+
+    if (mu1 < mu0)
+        return FLT_MAX;
+
+    Double_t sigma0 = par[3];
+    Double_t sigma1 = par[4];
+
+    if (sigma0 < 0.0001)
+        return FLT_MAX;
+
+    if (sigma1 < sigma0)
+        return FLT_MAX;
+
+
+    Double_t mu2 = (2.*mu1)-mu0;
+    Double_t mu3 = (3.*mu1)-(2.*mu0);
+    Double_t mu4 = (4.*mu1)-(3.*mu0);
+    Double_t mu5 = (5.*mu1)-(4.*mu0);
+    Double_t mu6 = (6.*mu1)-(5.*mu0);
+
+    Double_t sigma2 = TMath::Sqrt((2.*sigma1*sigma1) - (sigma0*sigma0));
+    Double_t sigma3 = TMath::Sqrt((3.*sigma1*sigma1) - (2.*sigma0*sigma0));
+    Double_t sigma4 = TMath::Sqrt((4.*sigma1*sigma1) - (3.*sigma0*sigma0));
+    Double_t sigma5 = TMath::Sqrt((5.*sigma1*sigma1) - (4.*sigma0*sigma0));
+    Double_t sigma6 = TMath::Sqrt((6.*sigma1*sigma1) - (5.*sigma0*sigma0));
+
+    Double_t lambda2 = lambda*lambda;
+    Double_t lambda3 = lambda2*lambda;
+    Double_t lambda4 = lambda3*lambda;
+    Double_t lambda5 = lambda4*lambda;
+    Double_t lambda6 = lambda5*lambda;
+
+    // k=0:
+    arg = (x[0] - mu0)/sigma0;
+    sum = TMath::Exp(-0.5*arg*arg)/sigma0;
+
+    // k=1:
+    arg = (x[0] - mu1)/sigma1;
+    sum += lambda*TMath::Exp(-0.5*arg*arg)/sigma1;
+
+    // k=2:
+    arg = (x[0] - mu2)/sigma2;
+    sum += 0.5*lambda2*TMath::Exp(-0.5*arg*arg)/sigma2;
+
+    // k=3:
+    arg = (x[0] - mu3)/sigma3;
+    sum += 0.1666666667*lambda3*TMath::Exp(-0.5*arg*arg)/sigma3;
+
+    // k=4:
+    arg = (x[0] - mu4)/sigma4;
+    sum += 0.041666666666667*lambda4*TMath::Exp(-0.5*arg*arg)/sigma4;
+
+    // k=5:
+    arg = (x[0] - mu5)/sigma5;
+    sum += 0.008333333333333*lambda5*TMath::Exp(-0.5*arg*arg)/sigma5;
+
+    // k=6:
+    arg = (x[0] - mu6)/sigma6;
+    sum += 0.001388888888889*lambda6*TMath::Exp(-0.5*arg*arg)/sigma6;
+
+    return TMath::Exp(-1.*lambda)*par[5]*sum;
+}
+
+Double_t MHCalibrationChargeBlindPix::Polya(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;
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeBlindPix.h	(revision 17960)
@@ -0,0 +1,150 @@
+#ifndef MARS_MHCalibrationChargeBlindPix
+#define MARS_MHCalibrationChargeBlindPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+#include <TMath.h>
+
+#ifndef ROOT_TF1
+#include <TF1.h>
+#endif
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+class TH1F;
+class TPaveText;
+class TText;
+class MExtractedSignalBlindPixel;
+class MRawEvtPixelIter;
+
+class MHCalibrationChargeBlindPix : public MHCalibrationPix
+{
+private:
+
+  static const Float_t  fgNumSinglePheLimit; //! Default for fNumSinglePheLimit (now set to: 50)
+  static const Float_t  gkSignalInitializer; //! Signal initializer (-9999.)
+  
+  static const Double_t gkElectronicAmp;     // Electronic Amplification after the PMT (in FADC counts/N_e)
+  static const Double_t gkElectronicAmpErr;  // Error of the electronic amplification
+
+  Float_t fSinglePheCut;                     // Value of summed FADC slices upon which event considered as single-phe
+  Float_t fNumSinglePheLimit;                // Minimum number of single-phe events 
+
+//  TVector fASinglePheFADCSlices;             //! Averaged FADC slice entries supposed single-phe events
+//  TVector fAPedestalFADCSlices;              //! Averaged FADC slice entries supposed pedestal   events
+ 
+  TF1 *fSinglePheFit;                        // Single Phe Fit (Gaussians convoluted with Poisson) 
+
+  UInt_t  fNumSinglePhes;                    // Number of entries in fASinglePheFADCSlices 
+  UInt_t  fNumPedestals;                     // Number of entries in fAPedestalFADCSlices  
+
+  Double_t  fLambda;                         // Poisson mean from Single-phe fit 
+  Double_t  fLambdaCheck;                    // Poisson mean from Pedestal fit alone
+  Double_t  fMu0;                            // Mean of the pedestal
+  Double_t  fMu1;                            // Mean of single-phe peak
+  Double_t  fSigma0;                         // Sigma of the pedestal
+  Double_t  fSigma1;                         // Sigma of single-phe peak
+  Double_t  fLambdaErr;                      // Error of Poisson mean from Single-phe fit 
+  Double_t  fLambdaCheckErr;                 // Error of Poisson mean from Pedestal fit alone 
+  Double_t  fMu0Err;                         // Error of  Mean of the pedestal    
+  Double_t  fMu1Err;                         // Error of  Mean of single-phe peak 
+  Double_t  fSigma0Err;                      // Error of  Sigma of the pedestal   
+  Double_t  fSigma1Err;                      // Error of  Sigma of single-phe peak
+  Double_t  fChisquare;                      // Chisquare of single-phe fit 
+  Int_t     fNDF;                            // Ndof of single-phe fit 
+  Double_t  fProb;                           // Probability of singleo-phe fit
+				     
+  Byte_t    fFlags;                          // Bit-field for the flags
+  enum { kSinglePheFitOK, kPedestalFitOK };  // Possible bits to be set
+
+  static Double_t FitFuncMichele(Double_t *x, Double_t *par);
+  static Double_t PoissonKto4(Double_t *x, Double_t *par);
+  static Double_t PoissonKto5(Double_t *x, Double_t *par);
+  static Double_t PoissonKto6(Double_t *x, Double_t *par);
+  static Double_t Polya(Double_t *x, Double_t *par);
+
+public:
+
+  enum FitFunc_t { kEPoisson4, kEPoisson5,
+                   kEPoisson6, kEPoisson7,
+                   kEPolya, kEMichele };    // Possible fit functions types 
+
+private:  
+
+  FitFunc_t fFitFunc;
+  
+  TPaveText *fFitLegend;                     //! Some legend to display the fit results
+  TH1F      *fHSinglePheFADCSlices;          // A histogram created and deleted only in Draw()
+  TH1F      *fHPedestalFADCSlices;           // A histogram created and deleted only in Draw()
+
+  // Fit
+  Bool_t InitFit();
+  void   ExitFit();  
+  
+  void DrawLegend(Option_t *opt="");
+  
+public:
+
+  MHCalibrationChargeBlindPix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeBlindPix();
+
+  void Clear(Option_t *o="");  
+  void Reset() {}
+  
+  // Getters
+  const Double_t GetLambda        ()  const { return fLambda;         }
+  const Double_t GetLambdaCheck   ()  const { return fLambdaCheck;    }
+  const Double_t GetMu0           ()  const { return fMu0;            }
+  const Double_t GetMu1           ()  const { return fMu1;            }
+  const Double_t GetSigma0        ()  const { return fSigma0;         }
+  const Double_t GetSigma1        ()  const { return fSigma1;         }
+  const Double_t GetLambdaErr     ()  const { return fLambdaErr;      }
+  const Double_t GetLambdaCheckErr()  const { return fLambdaCheckErr; }
+  const Double_t GetMu0Err        ()  const { return fMu0Err;         }
+  const Double_t GetMu1Err        ()  const { return fMu1Err;         }
+  const Double_t GetSigma0Err     ()  const { return fSigma0Err;      }
+  const Double_t GetSigma1Err     ()  const { return fSigma1Err;      }
+  const Float_t  GetSinglePheCut  ()  const { return fSinglePheCut;   }
+ 
+//  TVector &GetASinglePheFADCSlices()             { return fASinglePheFADCSlices;  }
+//  const TVector &GetASinglePheFADCSlices() const { return fASinglePheFADCSlices;  }
+
+//  TVector &GetAPedestalFADCSlices()              { return fAPedestalFADCSlices;  }
+//  const TVector &GetAPedestalFADCSlices()  const { return fAPedestalFADCSlices;  }
+
+  const Bool_t  IsSinglePheFitOK()         const;
+  const Bool_t  IsPedestalFitOK()          const;
+  
+  // Setters
+  void SetFitFunc        ( const FitFunc_t func )                   { fFitFunc = func;  }
+  void SetSinglePheCut      ( const Float_t cut = 0.               )    { fSinglePheCut      = cut;  }
+  void SetNumSinglePheLimit ( const Float_t lim =fgNumSinglePheLimit )    { fNumSinglePheLimit = lim;  }
+
+  void SetSinglePheFitOK    ( const Bool_t b=kTRUE);
+  void SetPedestalFitOK     ( const Bool_t b=kTRUE);
+  
+  // Fill histos
+//  void  FillSinglePheFADCSlices(const MRawEvtPixelIter &iter);
+//  void  FillPedestalFADCSlices( const MRawEvtPixelIter &iter);
+//  void  FinalizeSinglePheSpectrum();
+  
+  // Draws
+  void Draw(Option_t *opt="");
+
+  // Fits
+  Bool_t FitSinglePhe (Option_t *opt="RL0+Q");
+  void   FitPedestal  (Option_t *opt="RL0+Q");
+
+  // Simulation
+  Bool_t SimulateSinglePhe(const Double_t lambda,
+                           const Double_t mu0,    const Double_t mu1,
+                           const Double_t sigma0, const Double_t sigma1);
+  
+  ClassDef(MHCalibrationChargeBlindPix, 1)  // Histogram class for Charge Blind Pixel Calibration
+};
+
+#endif  /* MARS_MHCalibrationChargeBlindPix */
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeCam.cc	(revision 17960)
@@ -0,0 +1,1434 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationChargeCam                                               
+//
+// Fills the extracted signals of MExtractedSignalCam into the MHCalibrationPix-classes 
+// MHCalibrationChargeHiGainPix and MHCalibrationChargeLoGainPix for every:
+//
+// - Pixel, stored in the TOrdCollection's MHCalibrationCam::fHiGainArray and 
+//   MHCalibrationCam::fLoGainArray
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageLoGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainSectors and 
+//   MHCalibrationCam::fAverageLoGainSectors
+// 
+// Every signal is taken from MExtractedSignalCam and filled into a histogram and 
+// an array, in order to perform a Fourier analysis (see MHGausEvents). 
+// The signals are moreover averaged on an event-by-event basis and written into 
+// the corresponding average pixels.
+//
+// Additionally, the (FADC slice) position of the maximum is stored in an Absolute 
+// Arrival Time histogram. This histogram serves for a rough cross-check if the 
+// signal does not lie at or outside the edges of the extraction window. 
+//
+// The Charge histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) or  
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted ) and 
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// If more than fNumHiGainSaturationLimit (default: 15%) 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.
+//
+// Class Version 2:
+//  + Float_t fNumLoGainBlackoutLimit; // Rel. amount blackout logain events until pixel is declared unsuitable
+//
+// Class Version 3:
+//  - 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
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeCam.h"
+
+#include <TOrdCollection.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TF1.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TGraph.h>
+#include <TEnv.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHCalibrationChargePix.h"
+#include "MHCalibrationPix.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalSubtractedEvt.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MHCalibrationChargeCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationChargeCam::fgChargeHiGainNbins =  500;
+const Axis_t  MHCalibrationChargeCam::fgChargeHiGainFirst = -98.;
+const Axis_t  MHCalibrationChargeCam::fgChargeHiGainLast  =  1902.;
+const Int_t   MHCalibrationChargeCam::fgChargeLoGainNbins =  500;
+const Axis_t  MHCalibrationChargeCam::fgChargeLoGainFirst = -99.;
+const Axis_t  MHCalibrationChargeCam::fgChargeLoGainLast  =  901.;
+const Float_t MHCalibrationChargeCam::fgProbLimit         = 0.00000001;
+const TString MHCalibrationChargeCam::gsHistName          = "Charge";
+const TString MHCalibrationChargeCam::gsHistTitle         = "Signals";
+const TString MHCalibrationChargeCam::gsHistXTitle        = "Signal [FADC counts]";
+const TString MHCalibrationChargeCam::gsHistYTitle        = "Nr. events";
+const TString MHCalibrationChargeCam::gsAbsHistName       = "AbsTime";
+const TString MHCalibrationChargeCam::gsAbsHistTitle      = "Abs. Arr. Times";
+const TString MHCalibrationChargeCam::gsAbsHistXTitle     = "Time [FADC slices]";
+const TString MHCalibrationChargeCam::gsAbsHistYTitle     = "Nr. events";
+const Float_t MHCalibrationChargeCam::fgNumHiGainSaturationLimit = 0.15;
+const Float_t MHCalibrationChargeCam::fgNumLoGainSaturationLimit = 0.005;
+const Float_t MHCalibrationChargeCam::fgNumLoGainBlackoutLimit   = 0.05;
+const Float_t MHCalibrationChargeCam::fgLoGainBlackoutLimit      = 3.5;
+const Float_t MHCalibrationChargeCam::fgLoGainPickupLimit        = 3.5;
+const Float_t MHCalibrationChargeCam::fgTimeLowerLimit           = 1.;
+const Float_t MHCalibrationChargeCam::fgTimeUpperLimit           = 3.;
+const TString MHCalibrationChargeCam::fgReferenceFile = "mjobs/calibrationref.rc";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Initializes:
+// - fNumHiGainSaturationLimit to fgNumHiGainSaturationLimit
+// - fNumLoGainSaturationLimit to fgNumLoGainSaturationLimit
+// - fTimeLowerLimit           to fgTimeLowerLimit 
+// - fTimeUpperLimit           to fgTimeUpperLimit 
+// - fNumLoGainBlackoutLimit   to fgNumLoGainBlackoutLimit
+//
+// - fNbins to fgChargeHiGainNbins
+// - fFirst to fgChargeHiGainFirst
+// - fLast  to fgChargeHiGainLast 
+//
+// - fLoGainNbins to fgChargeLoGainNbins
+// - fLoGainFirst to fgChargeLoGainFirst
+// - fLoGainLast  to fgChargeLoGainLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fAbsHistName   to gsAbsHistName  
+// - fAbsHistTitle  to gsAbsHistTitle 
+// - fAbsHistXTitle to gsAbsHistXTitle
+// - fAbsHistYTitle to gsAbsHistYTitle
+//
+MHCalibrationChargeCam::MHCalibrationChargeCam(const char *name, const char *title)
+    : fRawEvt(NULL), fSignal(NULL)
+{
+
+  fName  = name  ? name  : "MHCalibrationChargeCam";
+  fTitle = title ? title : "Class to fill the calibration histograms ";
+  
+  SetNumHiGainSaturationLimit(fgNumHiGainSaturationLimit);
+  SetNumLoGainSaturationLimit(fgNumLoGainSaturationLimit);
+
+  SetNumLoGainBlackoutLimit  (fgNumLoGainBlackoutLimit);
+
+  SetTimeLowerLimit();
+  SetTimeUpperLimit();
+
+  SetBinning(fgChargeHiGainNbins, fgChargeHiGainFirst, fgChargeHiGainLast );
+  SetBinningLoGain(fgChargeLoGainNbins, fgChargeLoGainFirst, fgChargeLoGainLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetAbsHistName  (gsAbsHistName  .Data());
+  SetAbsHistTitle (gsAbsHistTitle .Data());
+  SetAbsHistXTitle(gsAbsHistXTitle.Data());
+  SetAbsHistYTitle(gsAbsHistYTitle.Data());
+
+  SetReferenceFile();
+
+  fInnerRefCharge = 278.;
+  fOuterRefCharge = 282.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationChargeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationChargeCam *cam = MParList::FindObject("MHCalibrationChargeCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationChargeCam::Clone(const char *) const
+{
+
+  MHCalibrationChargeCam *cam = new MHCalibrationChargeCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+  cam->fLoGainNbins            = fLoGainNbins;
+  cam->fLoGainFirst            = fLoGainFirst;
+  cam->fLoGainLast             = fLoGainLast;
+  cam->fReferenceFile          = fReferenceFile;
+  cam->fInnerRefCharge         = fInnerRefCharge;
+  cam->fOuterRefCharge         = fOuterRefCharge;
+
+  //
+  // Copy the MArrays
+  //
+  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
+  cam->fAverageAreaRelSigmaVar = fAverageAreaRelSigmaVar;
+  cam->fAverageAreaSat         = fAverageAreaSat;
+  cam->fAverageAreaSigma       = fAverageAreaSigma;
+  cam->fAverageAreaSigmaVar    = fAverageAreaSigmaVar;
+  cam->fAverageAreaNum         = fAverageAreaNum;
+  cam->fAverageSectorNum       = fAverageSectorNum;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+      cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  if (IsLoGain())
+    {
+      
+      const Int_t navlo = fAverageLoGainAreas->GetSize();
+      for (int i=0; i<navlo; i++)
+        cam->fAverageLoGainAreas->AddAt(GetAverageLoGainArea(i).Clone(),i);
+
+    }
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MRawEvtData
+//
+Bool_t MHCalibrationChargeCam::SetupHists(const MParList *pList)
+{
+    fRawEvt = (MPedestalSubtractedEvt*)pList->FindObject("MPedestalSubtractedEvt");
+    if (!fRawEvt)
+    {
+        *fLog << err << dbginf << "MPedestalSubtractedEvt 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
+//
+// Calls:
+// - InitHiGainArrays()
+// - InitLoGainArrays()
+// 
+// Sets:
+// - fSumhiarea   to nareas 
+// - fSumloarea   to nareas 
+// - fTimehiarea  to nareas 
+// - fTimeloarea  to nareas
+// - fSumhisector to nsectors 
+// - fSumlosector to nsectors 
+// - fTimehisector to nsectors 
+// - fTimelosector to nsectors
+// - fSathiarea   to nareas 
+// - fSatloarea   to nareas
+// - fSathisector to nsectors 
+// - fSatlosector to nsectors
+//
+Bool_t MHCalibrationChargeCam::ReInitHists(MParList *pList)
+{
+
+  fSignal = (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+  if (!fSignal)
+  {
+      *fLog << err << "MExtractedSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  if (!InitCams(pList,"Charge"))
+    return kFALSE;
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  //
+  // In case of the intense blue, double the range
+  //
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+    if ( fColor == MCalibrationCam::kBLUE)
+      SetBinning(fLoGainNbins, fLoGainFirst, 2.*fLoGainLast - fLoGainFirst);
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fSumhiarea  .Set(nareas); 
+  fSumloarea  .Set(nareas); 
+  fTimehiarea .Set(nareas); 
+  fTimeloarea .Set(nareas);
+  fSumhisector.Set(nsectors); 
+  fSumlosector.Set(nsectors); 
+  fTimehisector.Set(nsectors); 
+  fTimelosector.Set(nsectors);
+
+  fSathiarea  .Set(nareas); 
+  fSatloarea  .Set(nareas);
+  fSathisector.Set(nsectors); 
+  fSatlosector.Set(nsectors);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the High Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationChargePix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of Abs Times histogram from  fAbsNbins, fAbsFirst and fAbsLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set Abs Times Histgram names and titles from fAbsHistName and fAbsHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of Abs Times Histogram from fAbsHistXTitle and fAbsHistYTitle
+//   * Call InitHists
+//
+//
+void MHCalibrationChargeCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+  
+  TH1F *h;
+
+  const Int_t higainsamples = fRunHeader->GetNumSamplesHiGain();
+
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationChargePix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                       Form("%s High Gain Pixel%04d",fHistTitle.Data(),i)),i);
+
+        MHCalibrationChargePix &pix = (MHCalibrationChargePix&)(*this)[i];
+
+        pix.SetBinning(fNbins, fFirst, fLast);
+        pix.SetProbLimit(fProbLimit);
+
+        pix.SetBinningAbsTime(higainsamples, -0.5, higainsamples-0.5);
+
+        InitHists(pix,(*fBadPixels)[i], i);
+
+        h = pix.GetHAbsTime();
+
+        h->SetName (Form("H%sHiGainPix%04d",fAbsHistName.Data(),i));
+        h->SetTitle(Form("%s High Gain Pixel %04d",fAbsHistTitle.Data(),i));
+        h->SetXTitle(fAbsHistXTitle.Data());
+        h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHCalibrationChargePix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                  Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+
+        MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageHiGainArea(j);
+
+        pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas),
+                       fFirst, fLast);
+
+        pix.SetBinningAbsTime(higainsamples, -0.5, higainsamples-0.5);
+
+        InitHists(pix, fCam->GetAverageBadArea(j),j);
+
+        h =  pix.GetHAbsTime();
+
+        h->SetName (Form("H%sHiGainArea%d",fAbsHistName.Data(),j));
+        h->SetTitle(Form("%s%s%d",fAbsHistTitle.Data(),
+                         " averaged on event-by-event basis High Gain Area Idx ",j));
+        h->SetXTitle(fAbsHistXTitle.Data());
+        h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+  
+  if (fAverageHiGainSectors->GetSize()==0)
+  {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+	  fAverageHiGainSectors->AddAt(new MHCalibrationChargePix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                      Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+
+          MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageHiGainSector(j);
+
+          pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas),
+                         fFirst, fLast);
+
+          pix.SetBinningAbsTime(higainsamples, -0.5, higainsamples-0.5);
+
+          InitHists(pix, fCam->GetAverageBadSector(j),j);
+
+          h =  pix.GetHAbsTime();
+
+          h->SetName (Form("H%sHiGainSector%02d",fAbsHistName.Data(),j));
+          h->SetTitle(Form("%s%s%02d",fAbsHistTitle.Data(),
+                           " averaged on event-by-event basis High Gain Area Sector ",j));
+          h->SetXTitle(fAbsHistXTitle.Data());
+          h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+}
+
+//--------------------------------------------------------------------------------------
+//
+// Return, if IsLoGain() is kFALSE 
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the Low Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationChargePix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of Abs Times histogram from  fAbsNbins, fAbsFirst and fAbsLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set Abs Times Histgram names and titles from fAbsHistName and fAbsHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of Abs Times Histogram from fAbsHistXTitle and fAbsHistYTitle
+//   * Call InitHists
+//
+void MHCalibrationChargeCam::InitLoGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+
+  if (!IsLoGain())
+    return;
+
+
+  const Int_t logainsamples = fRunHeader->GetNumSamplesLoGain();
+
+  TH1F *h;
+
+  if (fLoGainArray->GetSize()==0 )
+    {
+      for (Int_t i=0; i<npixels; i++)
+        {
+          fLoGainArray->AddAt(new MHCalibrationChargePix(Form("%sLoGainPix%04d",fHistName.Data(),i),
+                                       Form("%s Low Gain Pixel %04d",fHistTitle.Data(),i)),i);
+
+          MHCalibrationChargePix &pix = (MHCalibrationChargePix&)(*this)(i);
+
+          pix.SetBinning(fLoGainNbins, fLoGainFirst, fLoGainLast);
+          pix.SetProbLimit(fProbLimit);
+
+          pix.SetBinningAbsTime(logainsamples, -0.5, logainsamples-0.5);
+          pix.SetPickupLimit(fgLoGainPickupLimit);
+          pix.SetBlackoutLimit(fgLoGainBlackoutLimit);
+
+          InitHists(pix,(*fBadPixels)[i], i);
+
+          h = pix.GetHAbsTime();
+          
+          h->SetName (Form("H%sLoGainPix%04d",fAbsHistName.Data(),i));
+          h->SetTitle(Form("%s Low Gain Pixel %04d",fAbsHistTitle.Data(),i));
+          h->SetXTitle(fAbsHistXTitle.Data());
+          h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+
+  if (fAverageLoGainAreas->GetSize()==0)
+    {
+      for (Int_t j=0; j<nareas; j++)
+        {
+	  fAverageLoGainAreas->AddAt(new MHCalibrationChargePix(Form("%sLoGainArea%d",fHistName.Data(),j),
+                                       Form("%s Low Gain Area Idx %d",fHistTitle.Data(),j)),j);
+
+          MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageLoGainArea(j);
+
+          pix.SetBinning(fLoGainNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas),
+                         fLoGainFirst, fLoGainLast);
+
+          pix.SetBinningAbsTime(logainsamples, -0.5, logainsamples-0.5);
+          
+          InitHists(pix, fCam->GetAverageBadArea(j),j);
+
+          h =  pix.GetHAbsTime();
+          
+          h->SetName (Form("H%sLoGainArea%02d",fAbsHistName.Data(),j));
+          h->SetTitle(Form("%s%s%02d",fAbsHistTitle.Data(),
+                           " averaged on event-by-event basis Low Gain Area Idx ",j));
+          h->SetXTitle(fAbsHistXTitle.Data());
+          h->SetYTitle(fAbsHistYTitle.Data());
+        }
+    }
+  
+
+  if (fAverageLoGainSectors->GetSize()==0 && IsLoGain())
+  {
+    for (Int_t j=0; j<nsectors; j++)
+      {
+        fAverageLoGainSectors->AddAt(new MHCalibrationChargePix(Form("%sLoGainSector%02d",fHistName.Data(),j),
+                                                        Form("%s Low Gain Sector %02d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageLoGainSector(j);
+        
+        pix.SetBinning(fLoGainNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas),
+                       fLoGainFirst, fLoGainLast);
+        
+        pix.SetBinningAbsTime(logainsamples, -0.5, logainsamples-0.5);
+        
+        InitHists(pix, fCam->GetAverageBadSector(j),j);
+
+        h =  pix.GetHAbsTime();
+        
+        h->SetName (Form("H%sLoGainSector%02d",fAbsHistName.Data(),j));
+        h->SetTitle(Form("%s%s%02d",fAbsHistTitle.Data(),
+                           " averaged on event-by-event basis Low Gain Area Sector ",j));
+        h->SetXTitle(fAbsHistXTitle.Data());
+        h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalCam:
+// - first used LoGain FADC slice
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Fill Charges histograms (MHGausEvents::FillHistAndArray()) with:
+// - MExtractedSignalPix::GetExtractedSignalHiGain();
+// - MExtractedSignalPix::GetExtractedSignalLoGain();
+//
+// 2) Set number of saturated slices (MHCalibrationChargePix::AddSaturated()) with:
+// - MExtractedSignalPix::IsHiGainSaturated();
+// - 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 Int_t hifirst = fSignal->GetFirstUsedSliceHiGain();
+  const Int_t hilast  = fSignal->GetLastUsedSliceHiGain();
+  const Int_t lofirst = fSignal->GetFirstUsedSliceLoGain();
+  const Int_t lolast  = fSignal->GetLastUsedSliceLoGain();
+
+  fSumhiarea  .Reset(); 
+  fSumloarea  .Reset(); 
+  fTimehiarea .Reset(); 
+  fTimeloarea .Reset();
+  fSumhisector.Reset(); 
+  fSumlosector.Reset(); 
+  fTimehisector.Reset(); 
+  fTimelosector.Reset();
+
+  fSathiarea  .Reset(); 
+  fSatloarea  .Reset();
+  fSathisector.Reset(); 
+  fSatlosector.Reset();
+
+  for (UInt_t i=0; i<npixels; i++)
+  {
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[i];
+      if (histhi.IsExcluded())
+	continue;
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      const MExtractedSignalPix &pix = (*signal)[i];
+
+      const Int_t sathi = pix.IsHiGainSaturated() ? 1 : 0;
+      histhi.AddSaturated(sathi);
+      if (sathi)
+      {
+          fSathiarea[aidx]++;
+          fSathisector[sector]++;
+      }
+
+      if (pix.IsHiGainValid())
+      {
+          const Float_t sumhi = pix.GetExtractedSignalHiGain();
+          if (IsOscillations())
+              histhi.FillHistAndArray(sumhi);
+          else
+              histhi.FillHist(sumhi);
+
+          fSumhiarea[aidx]     += sumhi;
+          fSumhisector[sector] += sumhi;
+      }
+
+      if (!IsLoGain())
+          continue;
+
+      MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(i);
+
+      const Int_t satlo = pix.IsLoGainSaturated() ? 1 : 0;
+      histlo.AddSaturated(satlo);
+      if (satlo)
+      {
+          fSatloarea[aidx]++;
+          fSatlosector[sector]++;
+      }
+
+      /*
+       // Previously:
+       fSatloarea[aidx]     += pix.GetNumHiGainSaturated();
+       fSatlosector[sector] += pix.GetNumHiGainSaturated();
+       */
+
+      if (pix.IsLoGainValid())
+      {
+          const Float_t sumlo = pix.GetExtractedSignalLoGain();
+
+          if (IsOscillations())
+              histlo.FillHistAndArray(sumlo);
+          else
+              histlo.FillHist(sumlo);
+
+          fSumloarea[aidx]     += sumlo;
+          fSumlosector[sector] += sumlo;
+      }
+  }
+
+  const Int_t num = fRawEvt->GetNumPixels();
+  const Int_t nhi = fRunHeader->GetNumSamplesHiGain();
+  for (int pixid=0; pixid<num; pixid++)
+  {
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[pixid];
+      if (histhi.IsExcluded())
+         continue;
+
+      const Float_t timehi = fRawEvt->GetMaxPos(pixid, hifirst, hilast)+hifirst;
+      histhi.FillAbsTime(timehi);
+
+      const Int_t aidx   = (*fGeom)[pixid].GetAidx();
+      const Int_t sector = (*fGeom)[pixid].GetSector();
+
+      fTimehiarea  [aidx]   += timehi;
+      fTimehisector[sector] += timehi;
+
+      if (IsLoGain())
+        {
+          MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(pixid);
+
+          const Float_t timelo = fRawEvt->GetMaxPos(pixid, nhi+lofirst, nhi+lolast)+lofirst;
+          histlo.FillAbsTime(timelo);
+
+          fTimeloarea[aidx] += timelo;
+          fTimelosector[sector] += timelo;
+        }
+  }
+
+  for (UInt_t j=0; j<nareas; j++)
+    {
+
+      const Int_t npix = fAverageAreaNum[j];
+
+      if (npix == 0)
+        continue;
+
+      MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainArea(j);
+
+      if (IsOscillations())
+        hipix.FillHistAndArray(fSumhiarea [j]/npix);
+      else
+        hipix.FillHist(fSumhiarea[j]/npix);
+      
+      hipix.AddSaturated    ((Float_t)fSathiarea [j]/npix > 0.5 ? 1 : 0); 
+      hipix.FillAbsTime     (fTimehiarea[j]/npix);
+
+      if (IsLoGain())
+        {
+          MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainArea(j);
+          if (IsOscillations())
+            lopix.FillHistAndArray(fSumloarea [j]/npix);
+          else
+            lopix.FillHist(fSumloarea [j]/npix);
+          lopix.AddSaturated    ((Float_t)fSatloarea [j]/npix > 0.5 ? 1 : 0); 
+          lopix.FillAbsTime     (fTimeloarea[j]/npix);
+        }
+    }
+
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+
+      const Int_t npix = fAverageSectorNum[j];
+
+      if (npix == 0)
+        continue;
+
+      MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainSector(j);
+
+      if (IsOscillations())      
+        hipix.FillHistAndArray(fSumhisector [j]/npix);
+      else
+        hipix.FillHist(fSumhisector [j]/npix);
+
+      hipix.AddSaturated    ((Float_t)fSathisector[j]/npix > 0.5 ? 1 : 0); 
+      hipix.FillAbsTime     (fTimehisector[j]/npix);
+
+      if (IsLoGain())
+        {
+          MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainSector(j);
+
+          if (IsOscillations())      
+            lopix.FillHistAndArray(fSumlosector [j]/npix);
+          else
+            lopix.FillHist(fSumlosector [j]/npix);
+            
+          lopix.AddSaturated    ((Float_t)fSatlosector[j]/npix > 0.5 ? 1 : 0); 
+          lopix.FillAbsTime     (fTimelosector[j]/npix);
+        }
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Returns if the pixel is excluded.
+// 2) Tests saturation. In case yes, set the flag: MCalibrationPix::SetHiGainSaturation()
+//    or the flag: MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturated )
+// 3) Store the absolute arrival times in the MCalibrationChargePix's. If flag 
+//    MCalibrationPix::IsHiGainSaturation() is set, the Low-Gain arrival times are stored, 
+//    otherwise the Hi-Gain ones.
+// 4) Calls to MHCalibrationCam::FitHiGainArrays() and MCalibrationCam::FitLoGainArrays() 
+//    with the flags:
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating )
+//
+Bool_t MHCalibrationChargeCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  TH1F *h = NULL;
+
+  const Int_t hifirst = fSignal->GetFirstUsedSliceHiGain();
+  const Int_t hilast  = fSignal->GetLastUsedSliceHiGain();
+  const Int_t lofirst = fSignal->GetFirstUsedSliceLoGain();
+  const Int_t lolast  = fSignal->GetLastUsedSliceLoGain();
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[i];
+      if (histhi.IsExcluded())
+	continue;
+
+      MCalibrationChargePix  &pix = (MCalibrationChargePix&)(*fCam)[i];
+
+      const Int_t numsat = histhi.GetSaturated();
+
+      pix.SetNumSaturated(numsat);
+
+      if (numsat > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          if (IsOscillations())
+            histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      h = histhi.GetHGausHist();
+
+      Stat_t overflow = h->GetBinContent(h->GetNbinsX()+1);
+      if (overflow > fOverflowLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          *fLog << warn
+                << "HiGain Hist-overflow " << overflow
+                << " times in: " << histhi.GetName() << " (w/o saturation!) " << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kHiGainOverFlow ); 
+        }
+
+      overflow = h->GetBinContent(0);
+      if (overflow >  fOverflowLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          *fLog << warn
+                << "HiGain Hist-underflow " << overflow
+                << " times in pix: " << histhi.GetName() << " (w/o saturation!) " << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kHiGainOverFlow ); 
+        }
+
+      FinalizeAbsTimes(histhi, pix, bad, hifirst, hilast);
+    }
+
+  if (IsLoGain())
+    for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+      {
+        
+        MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(i);
+        
+        if (histlo.IsExcluded())
+	  continue;
+
+        MBadPixelsPix &bad = (*fBadPixels)[i];
+        if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+          {
+              *fLog << warn << "Pixel  " << setw(4) << i << ": More than " << Form("%.1f%%", fNumLoGainSaturationLimit*100) << " lo-gains saturated." << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainSaturation ); 
+            if (IsOscillations())
+              histlo.CreateFourierSpectrum();
+            continue;
+          }
+
+        MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i] ;
+        if (!pix.IsHiGainSaturation())
+            continue;
+        
+        h = histlo.GetHGausHist();
+
+        Stat_t overflow = h->GetBinContent(h->GetNbinsX()+1);
+        if (overflow >  fOverflowLimit*histlo.GetHGausHist()->GetEntries())
+          {
+              *fLog << warn
+                  << "LoGain Hist-overflow " << overflow
+                  << " times in: " << histlo.GetName() << " (w/o saturation!) " << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainOverFlow ); 
+          }
+
+        overflow = h->GetBinContent(0);
+        if (overflow > fOverflowLimit*histlo.GetHGausHist()->GetEntries())
+          {
+            *fLog << warn
+                  << "LoGain Hist-underflow " << overflow
+                  << " times in: " << histlo.GetName() << " (w/o saturation!) " << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainOverFlow ); 
+          }
+        
+        FinalizeAbsTimes(histlo, pix, bad, lofirst, lolast);
+      }
+
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)GetAverageHiGainArea(j);      
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)fCam->GetAverageArea(j);
+
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          if (IsOscillations())
+            histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      MBadPixelsPix &bad = fCam->GetAverageBadArea(j);
+      FinalizeAbsTimes(histhi, pix, bad, hifirst, hilast);
+   }
+
+  if (IsLoGain())
+    for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+      {
+        
+        MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)GetAverageLoGainArea(j);      
+
+        if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+          {
+              *fLog << warn << "Area   " << setw(4) << j << ": More than " << Form("%.1f%%", fNumLoGainSaturationLimit*100) << " lo-gains saturated." << endl;
+            if (IsOscillations())
+                histlo.CreateFourierSpectrum();
+            continue;
+          }
+        
+        MCalibrationChargePix &pix = (MCalibrationChargePix&)fCam->GetAverageArea(j);
+        if (pix.IsHiGainSaturation())
+          {
+            MBadPixelsPix &bad = fCam->GetAverageBadArea(j);
+            FinalizeAbsTimes(histlo, pix, bad, lofirst, lolast);
+          }
+
+      }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)GetAverageHiGainSector(j);      
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)fCam->GetAverageSector(j);
+
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          if (IsOscillations())
+            histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      MBadPixelsPix &bad = fCam->GetAverageBadSector(j);
+      FinalizeAbsTimes(histhi, pix, bad, hifirst, hilast);
+    }
+  
+  if (IsLoGain())
+    for (Int_t j=0; j<fAverageLoGainSectors->GetSize(); j++)
+      {
+
+        MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)GetAverageLoGainSector(j);      
+        MBadPixelsPix          &bad    = fCam->GetAverageBadSector(j);
+
+        if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+          {
+              *fLog << warn << "Sector " << setw(4) << j << ": More than " << Form("%.1f%%", fNumLoGainSaturationLimit*100) << " lo-gains saturated." << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainSaturation ); 
+            if (IsOscillations())
+              histlo.CreateFourierSpectrum();
+            continue;
+          }
+
+        MCalibrationChargePix &pix = (MCalibrationChargePix&)fCam->GetAverageSector(j);
+        if (pix.IsHiGainSaturation())
+          FinalizeAbsTimes(histlo, pix, bad, lofirst, lolast);
+      }
+  
+  //
+  // Perform the fitting for the High Gain (done in MHCalibrationCam)
+  //
+  FitHiGainArrays(*fCam, *fBadPixels,
+                  MBadPixelsPix::kHiGainNotFitted,
+                  MBadPixelsPix::kHiGainOscillating);
+  
+  //
+  // Perform the fitting for the Low Gain (done in MHCalibrationCam)
+  //
+  if (IsLoGain())
+    FitLoGainArrays(*fCam, *fBadPixels,
+                    MBadPixelsPix::kLoGainNotFitted,
+                    MBadPixelsPix::kLoGainOscillating);
+
+  //
+  // Check for pixels which have the high-gain saturated, but the low-gain
+  // switch not applied in sufficient cases. Have to exclude these pixels,
+  // although they not abnormal. They simply cannot be calibrated...
+  //
+  for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+  {
+
+      MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(i);
+      if (histlo.IsExcluded())
+          continue;
+
+      MCalibrationChargePix  &pix = (MCalibrationChargePix&)(*fCam)[i];
+      if (!pix.IsHiGainSaturation())
+          continue;
+
+      //
+      // Now,treat only low-gain calibrated pixels:
+      //
+      const Double_t lim = fNumLoGainBlackoutLimit*histlo.GetHGausHist()->GetEntries();
+      if (histlo.GetBlackout() <= lim)
+          continue;
+
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+      bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+      bad.SetUncalibrated(MBadPixelsPix::kLoGainBlackout);
+  }
+
+  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, 
+                                              Int_t first, Int_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+1;// + fTimeLowerLimit;
+    const Float_t upperlimit = (Float_t)last -1;// - fTimeUpperLimit;
+
+    // FIXME: instead of checking whether the maximum is in the first or
+    //        last extracted slice we should check whether the extractor
+    //        was able to properly extract the signal!!!
+
+    if (mean<lowerlimit)
+    {
+        *fLog << warn << hist.GetName() << ": Mean Arr.Time: "
+            << Form("%4.1f < %4.1f (first used fadc sl+1)", mean, lowerlimit) << endl;
+        bad.SetUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin);
+    }
+
+    if (mean>upperlimit)
+    {
+        *fLog << warn << hist.GetName() << ": Mean Arr.Time: "
+            << Form("%4.1f > %4.1f (last used fadc sl-1)", mean, upperlimit) << 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::kLoGainNotFitted))
+          if (pix.IsHiGainSaturation())
+              bad.SetUnsuitable(MBadPixelsPix::kUnreliableRun);
+
+      if (bad.IsUncalibrated(MBadPixelsPix::kLoGainSaturation))
+          bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+
+      if (IsOscillations())
+        {
+            if (bad.IsUncalibrated(MBadPixelsPix::kHiGainOscillating))
+                if (!pix.IsHiGainSaturation())
+                    bad.SetUnsuitable(MBadPixelsPix::kUnreliableRun);
+
+            if (bad.IsUncalibrated(MBadPixelsPix::kLoGainOscillating))
+                if (pix.IsHiGainSaturation())
+                    bad.SetUnsuitable(MBadPixelsPix::kUnreliableRun);
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationChargeCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationChargeCam::Draw(const Option_t *opt)
+{
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TString option(opt);
+  option.ToLower();
+
+  if (!option.Contains("datacheck"))
+    {
+      MHCalibrationCam::Draw(opt);
+      return;
+    }
+
+  // 
+  // From here on , the datacheck - Draw
+  //
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+  pad->Divide(1,nareas);
+
+  //
+  // Loop over inner and outer pixels
+  //  
+  for (Int_t i=0; i<nareas;i++) 
+  {
+       pad->cd(i+1);
+
+       MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainArea(i);
+
+       //
+       // Ask for Hi-Gain saturation
+       //
+       if (hipix.GetSaturated() > fNumHiGainSaturationLimit*hipix.GetHGausHist()->GetEntries() && IsLoGain())
+       {
+           if (i>=fAverageLoGainAreas->GetSize())
+               continue;
+
+           MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainArea(i);
+           DrawDataCheckPixel(lopix,i ? fOuterRefCharge : fInnerRefCharge);
+       }
+       else
+           DrawDataCheckPixel(hipix,i ? fOuterRefCharge : fInnerRefCharge);
+  }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Draw the average pixel for the datacheck:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationChargeCam::DrawDataCheckPixel(MHCalibrationChargePix &pix, const Float_t refline)
+{
+    if (pix.IsEmpty())
+        return;
+
+    TVirtualPad *pad = gPad;
+    pad->Divide(1,2, 1e-10, 1e-10);
+    pad->cd(1);
+
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+    if (!pix.IsEmpty() && !pix.IsOnlyOverflow() && !pix.IsOnlyUnderflow())
+        gPad->SetLogy();
+
+    TH1F  *hist = pix.GetHGausHist();
+    TAxis *xaxe = hist->GetXaxis();
+    TAxis *yaxe = hist->GetYaxis();
+    xaxe->CenterTitle();
+    yaxe->CenterTitle();
+    xaxe->SetTitleSize(0.07);
+    yaxe->SetTitleSize(0.07);
+    xaxe->SetTitleOffset(0.7);
+    yaxe->SetTitleOffset(0.55);
+    xaxe->SetLabelSize(0.06);
+    yaxe->SetLabelSize(0.06);
+    xaxe->SetTitle(hist->GetXaxis()->GetTitle());
+    yaxe->SetTitle(hist->GetYaxis()->GetTitle());
+    xaxe->SetRange(hist->GetMaximumBin()-50, hist->GetMaximumBin()+50);
+
+    gStyle->SetOptFit();
+
+    hist->Draw();
+
+    TF1 *fit = pix.GetFGausFit();
+    if (fit)
+    {
+        switch (fColor)
+        {
+        case MCalibrationCam::kGREEN:
+            fit->SetLineColor(kGreen);
+            break;
+        case MCalibrationCam::kBLUE:
+            fit->SetLineColor(kBlue);
+            break;
+        case MCalibrationCam::kUV:
+            fit->SetLineColor(51);
+            break;
+        case MCalibrationCam::kCT1:
+            fit->SetLineColor(6);
+            break;
+        default:
+            fit->SetLineColor(kRed);
+        }
+        fit->Draw("same");
+    }
+
+    DisplayRefLines(hist,refline);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+
+    pix.CreateGraphEvents();
+    TGraph *gr = pix.GetGraphEvents();
+    if (gr)
+    {
+        TH1F *null2 = gr->GetHistogram();
+
+        null2->SetMinimum(pix.GetMean()-10.*pix.GetSigma());
+        null2->SetMaximum(pix.GetMean()+10.*pix.GetSigma());
+        null2->SetStats(kFALSE);
+
+        //
+        // set the labels bigger
+        //
+        TAxis *xaxe2 = null2->GetXaxis();
+        TAxis *yaxe2 = null2->GetYaxis();
+        xaxe2->CenterTitle();
+        yaxe2->CenterTitle();
+        xaxe2->SetTitleSize(0.07);
+        yaxe2->SetTitleSize(0.07);
+        xaxe2->SetTitleOffset(0.7);
+        yaxe2->SetTitleOffset(0.55);
+        xaxe2->SetLabelSize(0.06);
+        yaxe2->SetLabelSize(0.06);
+        xaxe2->SetRangeUser(0, pix.GetEvents()->GetSize()/pix.GetEventFrequency());
+    }
+    pix.DrawEvents();
+
+    //  newpad->cd(3);
+    //  pix.DrawPowerSpectrum(*newpad,4);
+}
+
+void  MHCalibrationChargeCam::DisplayRefLines(const TH1F *hist, const Float_t refline) const
+{
+    TLine *line = new TLine(refline, 0, refline, hist->GetMaximum());
+    line->SetLineColor(51);
+    line->SetLineStyle(2);
+    line->SetLineWidth(3);
+    line->SetBit(kCanDelete);
+    line->Draw();
+
+    TLegend *leg = new TLegend(0.8,0.01,0.99,0.15);
+    leg->AddEntry(line, "10 Leds UV", "l");
+    leg->SetBit(kCanDelete);
+    leg->Draw();
+}
+
+Int_t MHCalibrationChargeCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Int_t rc = MHCalibrationCam::ReadEnv(env,prefix,print);
+  if (rc==kERROR)
+    return kERROR;
+
+  if (IsEnvDefined(env, prefix, "HiGainNbins", print))
+    {
+      fNbins = GetEnvValue(env, prefix, "HiGainNbins", fNbins);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "HiGainFirst", print))
+    {
+      fFirst = GetEnvValue(env, prefix, "HiGainFirst", fFirst);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "HiGainLast", print))
+    {
+      fLast = GetEnvValue(env, prefix, "HiGainLast", fLast);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "LoGainNbins", print))
+    {
+      fLoGainNbins = GetEnvValue(env, prefix, "LoGainNbins", fLoGainNbins);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "LoGainFirst", print))
+    {
+      fLoGainFirst = GetEnvValue(env, prefix, "LoGainFirst", fLoGainFirst);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "LoGainLast", print))
+    {
+      fLoGainLast = GetEnvValue(env, prefix, "LoGainLast", fLoGainLast);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "TimeLowerLimit", print))
+    {
+      SetTimeLowerLimit(GetEnvValue(env, prefix, "TimeLowerLimit", fTimeLowerLimit));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "TimeUpperLimit", print))
+    {
+      SetTimeUpperLimit(GetEnvValue(env, prefix, "TimeUpperLimit", fTimeUpperLimit));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "ReferenceFile", print))
+    {
+      SetReferenceFile(GetEnvValue(env,prefix,"ReferenceFile",fReferenceFile.Data()));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "NumHiGainSaturationLimit", print))
+  {
+      SetNumHiGainSaturationLimit(GetEnvValue(env, prefix, "NumHiGainSaturationLimit", fNumHiGainSaturationLimit));
+      rc = kTRUE;
+  }
+
+  if (IsEnvDefined(env, prefix, "NumLoGainSaturationLimit", print))
+  {
+      SetNumLoGainSaturationLimit(GetEnvValue(env, prefix, "NumLoGainSaturationLimit", fNumLoGainSaturationLimit));
+      rc = kTRUE;
+  }
+
+  if (IsEnvDefined(env, prefix, "NumLoGainBlackoutLimit", print))
+  {
+      SetNumLoGainBlackoutLimit(GetEnvValue(env, prefix, "NumLoGainBlackoutLimit", fNumLoGainBlackoutLimit));
+      rc = kTRUE;
+  }
+
+  TEnv refenv(fReferenceFile);
+
+  fInnerRefCharge = refenv.GetValue("InnerRefCharge",fInnerRefCharge);
+  fOuterRefCharge = refenv.GetValue("OuterRefCharge",fOuterRefCharge);
+
+  return rc;
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargeCam.h	(revision 17960)
@@ -0,0 +1,141 @@
+#ifndef MARS_MHCalibrationChargeCam
+#define MARS_MHCalibrationChargeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TH1F;
+class MExtractedSignalCam;
+class MCalibrationChargePix;
+class MHCalibrationChargePix;
+class MPedestalSubtractedEvt;
+
+class MHCalibrationChargeCam : public MHCalibrationCam
+{
+private:
+
+  static const Int_t   fgChargeHiGainNbins;          //! Nr. bins of HiGain Histograms
+  static const Axis_t  fgChargeHiGainFirst;          //! First Bin of HiGain Histograms
+  static const Axis_t  fgChargeHiGainLast;           //! Last Bin of HiGain Histograms
+  static const Int_t   fgChargeLoGainNbins;          //! First Bin of LoGain Histograms
+  static const Axis_t  fgChargeLoGainFirst;          //! First Bin of LoGain Histograms
+  static const Axis_t  fgChargeLoGainLast;           //! Last Bin of LoGain Histograms
+  static const Float_t fgProbLimit;                  //! The default for fProbLimit
+  
+  static const TString fgReferenceFile;              //! default for fReferenceFile
+
+  static const TString gsHistName;                   //! Default Histogram names
+  static const TString gsHistTitle;                  //! Default Histogram titles
+  static const TString gsHistXTitle;                 //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;                 //! Default Histogram y-axis titles
+  
+  static const TString gsAbsHistName;                //! Default Histogram names abs.times
+  static const TString gsAbsHistTitle;               //! Default Histogram titles abs.times
+  static const TString gsAbsHistXTitle;              //! Default Histogram x-axis titles abs.times
+  static const TString gsAbsHistYTitle;              //! Default Histogram y-axis titles abs.times
+  
+  static const Float_t fgNumHiGainSaturationLimit;   //! Default for fNumHiGainSaturationLimit
+  static const Float_t fgNumLoGainSaturationLimit;   //! Default for fNumLoGainSaturationLimit
+  static const Float_t fgNumLoGainBlackoutLimit;     //! Default for fNumLoGainBlackoutLimit (now at: 0.05)
+
+  static const Float_t fgLoGainBlackoutLimit;        //! Default for low-gain blackout limit (now at: 3.5)
+  static const Float_t fgLoGainPickupLimit;          //! Default for low-gian pickup limit   (now at: 3.5)
+
+  static const Float_t fgTimeLowerLimit;             //! Default for fTimeLowerLimit
+  static const Float_t fgTimeUpperLimit;             //! Default for fTimeUpperLimit
+  
+  Int_t   fLoGainNbins;                              // Number of LoGain bins
+  Axis_t  fLoGainFirst;                              // Lower histogram limit low gain
+  Axis_t  fLoGainLast;                               // Upper histogram limit low gain
+
+  Float_t fNumLoGainBlackoutLimit;                   // Rel. amount blackout logain events until pixel is declared unsuitable
+
+  TString fAbsHistName;                              // Histogram names abs.times
+  TString fAbsHistTitle;                             // Histogram titles abs. times
+  TString fAbsHistXTitle;                            // Histogram x-axis titles abs. times
+  TString fAbsHistYTitle;                            // Histogram y-axis titles abs. times
+  
+  TString fReferenceFile;                            // File name containing the reference values
+
+  Float_t fInnerRefCharge;                           // The reference mean arrival time inner pixels
+  Float_t fOuterRefCharge;                           // The reference mean arrival time outer pixels
+
+  MArrayD fSumhiarea  ;                              //!
+  MArrayD fSumloarea  ;                              //!
+  MArrayD fTimehiarea ;                              //!
+  MArrayD fTimeloarea ;                              //!
+  MArrayD fSumhisector;                              //!
+  MArrayD fSumlosector;                              //!
+  MArrayD fTimehisector;                             //!
+  MArrayD fTimelosector;                             //!
+
+  MArrayI fSathiarea  ;                              //!
+  MArrayI fSatloarea  ;                              //!
+  MArrayI fSathisector;                              //!
+  MArrayI fSatlosector;                              //!
+
+  Float_t fTimeLowerLimit;                           // Limit dist. to first signal slice (in units of FADC slices) 
+  Float_t fTimeUpperLimit;                           // Limit dist. to last signal slice  (in units of FADC slices) 
+  
+  MPedestalSubtractedEvt *fRawEvt;                   //!  Raw event data
+  MExtractedSignalCam    *fSignal;                   //!
+
+  Bool_t SetupHists(const MParList *pList);
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+
+  void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  void   InitLoGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+
+  void   FinalizeAbsTimes (MHCalibrationChargePix &hist, MCalibrationChargePix &pix, MBadPixelsPix &bad,
+                           Int_t first, Int_t last);
+  Bool_t FinalizeHists();
+  void   FinalizeBadPixels();
+
+  void   DrawDataCheckPixel(MHCalibrationChargePix &pix, const Float_t refline);
+  void   DisplayRefLines   ( const TH1F *hist,           const Float_t refline) const;
+
+  Int_t ReadEnv        ( const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MHCalibrationChargeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeCam() {}
+  
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  // Draw
+  void   Draw(const Option_t *opt);
+
+  void SetAbsHistName   ( const char *name )  { fAbsHistName   = name; }
+  void SetAbsHistTitle  ( const char *name )  { fAbsHistTitle  = name; }
+  void SetAbsHistXTitle ( const char *name )  { fAbsHistXTitle = name; }
+  void SetAbsHistYTitle ( const char *name )  { fAbsHistYTitle = name; }
+
+  void SetBinningLoGain(Int_t n, Axis_t lo, Axis_t up) { fLoGainNbins=n; fLoGainFirst=lo; fLoGainLast=up; }
+
+  void SetNumLoGainBlackoutLimit( const Float_t f=fgNumLoGainBlackoutLimit ) { fNumLoGainBlackoutLimit = f; }
+
+  void SetReferenceFile ( const TString ref=fgReferenceFile ) { fReferenceFile  = ref; }
+
+  void SetTimeLowerLimit( const Float_t f=fgTimeLowerLimit )  { fTimeLowerLimit = f; }
+  void SetTimeUpperLimit( const Float_t f=fgTimeUpperLimit )  { fTimeUpperLimit = f; }
+
+  // MHCamEvent
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const { return kTRUE; }
+  void   DrawPixelContent( Int_t num )  const;    
+
+  ClassDef(MHCalibrationChargeCam, 3)	// Histogram class for Charge Camera Calibration
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePINDiode.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePINDiode.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePINDiode.cc	(revision 17960)
@@ -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): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargePINDiode
+//
+//  Histogram class for the charge calibration of the PIN Diode. 
+//  Stores and fits the charges, the RMS of the charges  and stores the 
+//  location of the maximum FADC slice. Charges are taken from MExtractedSignalPINDiode.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargePINDiode.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MExtractedSignalPINDiode.h"
+#include "MCalibrationChargePINDiode.h"
+
+ClassImp(MHCalibrationChargePINDiode);
+
+using namespace std;
+
+const Axis_t  MHCalibrationChargePINDiode::fgAbsTimeFirst    = -0.5;
+const Axis_t  MHCalibrationChargePINDiode::fgAbsTimeLast     = 29.5;
+const Int_t   MHCalibrationChargePINDiode::fgAbsTimeNbins    = 30;
+const Axis_t  MHCalibrationChargePINDiode::fgChargeFirst     = -0.5;
+const Axis_t  MHCalibrationChargePINDiode::fgChargeLast      = 1999.5;
+const Int_t   MHCalibrationChargePINDiode::fgChargeNbins     = 2000;
+const Int_t   MHCalibrationChargePINDiode::fgRmsChargeNbins  = 200;
+const Axis_t  MHCalibrationChargePINDiode::fgRmsChargeFirst  = 0.;
+const Axis_t  MHCalibrationChargePINDiode::fgRmsChargeLast   = 200.;  
+const Float_t MHCalibrationChargePINDiode::fgTimeLowerLimit  = 3.;
+const Float_t MHCalibrationChargePINDiode::fgTimeUpperLimit  = 4.;
+const TString MHCalibrationChargePINDiode::gsHistName          = "Charge";
+const TString MHCalibrationChargePINDiode::gsHistTitle         = "Signals";
+const TString MHCalibrationChargePINDiode::gsHistXTitle        = "Signal [FADC counts]";
+const TString MHCalibrationChargePINDiode::gsHistYTitle        = "Nr. events";
+const TString MHCalibrationChargePINDiode::gsAbsHistName       = "AbsTime";
+const TString MHCalibrationChargePINDiode::gsAbsHistTitle      = "Abs. Arr. Times";
+const TString MHCalibrationChargePINDiode::gsAbsHistXTitle     = "Time [FADC slices]";
+const TString MHCalibrationChargePINDiode::gsAbsHistYTitle     = "Nr. events";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fAbsTimeFirst        (fgAbsTimeFirst)
+// - the default number for fAbsTimeLast         (fgAbsTimeLast)
+// - the default number for fAbsTimeNbins        (fgAbsTimeNbins)
+// - the default number for MHGausEvents::fNbins (fgChargeNbins)
+// - the default number for MHGausEvents::fFirst (fgChargeFirst)
+// - the default number for MHGausEvents::fLast  (fgChargeLast)
+// - the default number for fRmsChargeNbins      (fgRmsChargeNbins)
+// - the default number for fRmsChargeFirst      (fgRmsChargeFirst)
+// - the default number for fRmsChargeLast       (fgRmsChargeLast)
+// - the default number for fTimeLowerLimit      (fgTimeLowerLimit)
+// - the default number for fTimeUpperLimit      (fgTimeUpperLimit)
+//
+// - the default name of the  fHGausHist      ("HCalibrationChargePINDiode")
+// - the default title of the fHGausHist      ("Distribution of Summed FADC slices PIN Diode")
+// - the default x-axis title for fHGausHist  ("Sum FADC Slices")
+// - the default y-axis title for fHGausHist  ("Nr. of events")
+// - the default name of the  fHAbsTime       ("HAbsTimePINDiode")
+// - the default title of the fHAbsTime       ("Distribution of Absolute Arrival Times PIN Diode")
+// - the default x-axis title for fHAbsTime   ("Absolute Arrival Time [FADC slice nr]")
+// - the default y-axis title for fHAbsTime   ("Nr. of events")
+// - the default name of the  fHRmsCharge     ("HRmsChargePINDiode")
+// - the default title of the fHRmsCharge     ("Distribution of Variances of summed FADC slices PIN Diode")
+// - the default x-axis title for fHRmsCharge ("RMS (sum) [FADC slices]")
+// - the default y-axis title for fHRmsCharge ("Nr. of events")
+// - the default directory of the fHRmsCharge (NULL)
+// - the current style for fHRmsCharge (NULL)
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fAbsHistName   to gsAbsHistName  
+// - fAbsHistTitle  to gsAbsHistTitle 
+// - fAbsHistXTitle to gsAbsHistXTitle
+// - fAbsHistYTitle to gsAbsHistYTitle
+//
+// Initializes:
+// - fHRmsCharge()
+// - all pointers to NULL
+//
+// Calls:
+// - Clear()
+//
+MHCalibrationChargePINDiode::MHCalibrationChargePINDiode(const char *name, const char *title)
+    : fPINDiode(NULL), fSigPIN(NULL), fHRmsCharge()
+{
+
+  fName  = name  ? name  : "MHCalibrationChargePINDiode";
+  fTitle = title ? title : "Fill the FADC sums of the PINDiode events and perform the fits";
+
+  SetBinning(fgChargeNbins, fgChargeFirst, fgChargeLast);
+  SetBinningAbsTime(fgAbsTimeNbins, fgAbsTimeFirst, fgAbsTimeLast);
+  SetBinningRmsCharge(fgRmsChargeNbins, fgRmsChargeFirst, fgRmsChargeLast);
+
+  SetTimeLowerLimit();
+  SetTimeUpperLimit();
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetAbsHistName  (gsAbsHistName  .Data());
+  SetAbsHistTitle (gsAbsHistTitle .Data());
+  SetAbsHistXTitle(gsAbsHistXTitle.Data());
+  SetAbsHistYTitle(gsAbsHistYTitle.Data());
+
+  fHRmsCharge.SetName("HRmsChargePINDiode");
+  fHRmsCharge.SetTitle("Distribution of Variances of summed FADC slices PIN Diode");  
+  fHRmsCharge.SetXTitle("RMS (sum) [FADC slices]");
+  fHRmsCharge.SetYTitle("Nr. of events");
+  fHRmsCharge.UseCurrentStyle();
+  fHRmsCharge.SetDirectory(NULL); 
+
+  Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes Binning of the following histograms:
+// - fHGausHist.SetBins(fNbins,fFirst,fLast);
+// - fHAbsTime.SetBins(fAbsTimeNbins,fAbsTimeFirst,fAbsTimeLast);
+// - fHRmsCharge.SetBins(fRmsChargeNbins,fRmsChargeFirst,fRmsChargeLast);
+//
+Bool_t MHCalibrationChargePINDiode::SetupFill(const MParList *pList) 
+{
+
+  TH1F *h = GetHGausHist();
+
+  h->SetName (fHistName.Data());
+  h->SetTitle(fHistTitle.Data());  
+  h->SetXTitle(fHistXTitle.Data());
+  h->SetYTitle(fHistYTitle.Data());
+  
+  h = GetHAbsTime();
+
+  h->SetName (fAbsHistName.Data());
+  h->SetTitle(fAbsHistTitle.Data());
+  h->SetXTitle(fAbsHistXTitle.Data());
+  h->SetYTitle(fAbsHistYTitle.Data());
+  
+  MHCalibrationPix::InitBins();
+
+  fHAbsTime.  SetBins(fAbsTimeNbins,  fAbsTimeFirst,  fAbsTimeLast);
+  fHRmsCharge.SetBins(fRmsChargeNbins,fRmsChargeFirst,fRmsChargeLast);
+
+  fExclusionMean  = 0;
+  fExclusionSigma = 0;  
+  fExclusionChi2  = 0;
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MExtractedSignalPINDiode
+// - MCalibrationChargePINDiode
+//
+Bool_t MHCalibrationChargePINDiode::ReInit(MParList *pList)
+{
+  
+  fSigPIN = (MExtractedSignalPINDiode*)pList->FindCreateObj("MExtractedSignalPINDiode");
+  if (!fSigPIN)
+      return kFALSE;
+
+  fPINDiode = (MCalibrationChargePINDiode*)pList->FindCreateObj("MCalibrationChargePINDiode");
+  if (!fPINDiode)
+      return kFALSE;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalPINDiode:
+// - Number of used FADC samples via MExtractedSignalPINDiode::GetNumFADCSamples()
+// - Extracted signal via            MExtractedSignalPINDiode::GetExtractedSignal()
+// - Signal Rms                      MExtractedSignalPINDiode::GetExtractedRms()
+// - Arrival Time                    MExtractedSignalPINDiode::GetExtractedTime()
+//
+// Fills the following histograms:
+// - MHGausEvents::FillHistAndArray(signal)
+// - MHCalibrationChargePix::FillAbsTime(time);
+// - FillRmsCharge(rms);
+//
+Int_t MHCalibrationChargePINDiode::Fill(const MParContainer *par, const Stat_t w)
+{
+
+  const MExtractedSignalPINDiode *extractor = dynamic_cast<const MExtractedSignalPINDiode*>(par);
+  if (!extractor)
+    {
+      *fLog << err << "No argument in MExtractedSignalPINDiode::Fill... abort." << endl;
+      return kERROR;
+    }
+  
+  const Float_t signal = (float)extractor->GetExtractedSignal();
+  const Float_t time   = extractor->GetExtractedTime();
+  const Float_t sigma  = extractor->GetExtractedSigma();
+  const Float_t chi2   = extractor->GetExtractedChi2();
+
+  if (time < 3. || time > 24.)
+    {
+      fExclusionMean++;
+      return kTRUE;
+    }
+  
+  if (sigma < 5. || sigma > 18.)
+    {
+      fExclusionSigma++;
+      return kTRUE;
+    }
+  
+  if (chi2  > 0.35)
+    {
+      fExclusionChi2++;
+      return kTRUE;
+    }
+  
+  FillHistAndArray(signal);
+  FillAbsTime(time);
+  FillRmsCharge(sigma);
+
+  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();
+
+  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);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills fHRmsCharge with q
+// Returns kFALSE, if overflow or underflow occurred, else kTRUE
+//
+Bool_t MHCalibrationChargePINDiode::FillRmsCharge(const Float_t q)
+{
+  return fHRmsCharge.Fill(q) > -1;
+}
+
+// -----------------------------------------------------------
+//
+// Fits -- not yet implemented
+//
+Bool_t MHCalibrationChargePINDiode::FitRmsCharge(Option_t *option)
+{
+  return 1;
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+// The following options can be chosen:
+//
+// "": displays the fHGausHist with fits and fHRmsCharge
+// "all": executes additionally MHCalibrationPix::Draw(), with option "fourierevents"
+//
+void MHCalibrationChargePINDiode::Draw(const Option_t *opt)
+{
+
+  TString option(opt);
+  option.ToLower();
+  
+//  Int_t win = 1;
+
+  TVirtualPad *oldpad = gPad ? gPad : MH::MakeDefCanvas(this,900, 600);
+  TVirtualPad *pad    = NULL;
+
+  oldpad->SetBorderMode(0);
+    
+  if (option.Contains("all"))
+  {
+      option.ReplaceAll("all","");
+      oldpad->Divide(2,1);
+//      win = 2;
+      oldpad->cd(1);
+      TVirtualPad *newpad = gPad;
+      pad = newpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  else
+  {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+
+  if (IsEmpty())
+    return;
+
+  if (!IsOnlyOverflow() && !IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.Draw(opt); 
+  if (fFGausFit)
+  {
+      fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+      fFGausFit->Draw("same");
+  }
+
+  pad->cd(2);
+  fHRmsCharge.Draw(opt);
+
+  oldpad->cd(2);
+  MHCalibrationPix::Draw("fourierevents");
+}
+
+
+
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePINDiode.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePINDiode.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePINDiode.h	(revision 17960)
@@ -0,0 +1,119 @@
+#ifndef MARS_MHCalibrationChargePINDiode
+#define MARS_MHCalibrationChargePINDiode
+
+
+#ifndef MARS_MHCalibrationChargePix
+#include "MHCalibrationChargePix.h"
+#endif
+
+class TH1F;
+class MExtractedSignalPINDiode;
+class MCalibrationChargePINDiode;
+class MHCalibrationChargePINDiode : public MHCalibrationChargePix
+{
+private:
+
+  static const Axis_t  fgAbsTimeFirst;    //! Default for fAbsTimeFirst    (now set to: -0.5  )
+  static const Axis_t  fgAbsTimeLast;     //! Default for fAbsTimeLast     (now set to: 29.5  )
+  static const Int_t   fgAbsTimeNbins;    //! Default for fAbsTimeNBins    (now set to: 30    )
+  static const Int_t   fgChargeNbins;     //! Default for fNBins           (now set to: 200   )
+  static const Axis_t  fgChargeFirst;     //! Default for fFirst           (now set to: -0.5  )
+  static const Axis_t  fgChargeLast;      //! Default for fLast            (now set to: 199.5 )
+  static const Int_t   fgRmsChargeNbins;  //! Default for fRmsChargeNBins  (now set to: 100   )
+  static const Axis_t  fgRmsChargeFirst;  //! Default for fRmsChargeFirst  (now set to: 0.    )
+  static const Axis_t  fgRmsChargeLast;   //! Default for fRmsChargeLast   (now set to: 100.  )
+  static const Float_t fgTimeLowerLimit;  //! Default for fTimeLowerLimit    (now set to: 1.) 
+  static const Float_t fgTimeUpperLimit;  //! Default for fTimeUpperLimit    (now set to: 2.)
+
+  static const TString gsHistName;        //! Default Histogram names
+  static const TString gsHistTitle;       //! Default Histogram titles
+  static const TString gsHistXTitle;      //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;      //! Default Histogram y-axis titles
+  
+  static const TString gsAbsHistName;     //! Default Histogram names abs.times
+  static const TString gsAbsHistTitle;    //! Default Histogram titles abs.times
+  static const TString gsAbsHistXTitle;   //! Default Histogram x-axis titles abs.times
+  static const TString gsAbsHistYTitle;   //! Default Histogram y-axis titles abs.times
+  
+  TString fHistName;                      // Histogram names
+  TString fHistTitle;                     // Histogram titles
+  TString fHistXTitle;                    // Histogram x-axis titles
+  TString fHistYTitle;                    // Histogram y-axis titles
+  
+  TString fAbsHistName;                   // Histogram names abs.times
+  TString fAbsHistTitle;                  // Histogram titles abs. times
+  TString fAbsHistXTitle;                 // Histogram x-axis titles abs. times
+  TString fAbsHistYTitle;                 // Histogram y-axis titles abs. times
+  
+  MCalibrationChargePINDiode *fPINDiode;  //! Storage container of the results
+  MExtractedSignalPINDiode   *fSigPIN;    //! Storage container of extracted signal
+
+  TH1F fHRmsCharge;                       //  Histogram containing Variance of summed FADC slices
+
+  Axis_t  fRmsChargeFirst;                //  Lower bound bin used for the fHRmsCharge
+  Axis_t  fRmsChargeLast;                 //  Upper bound bin used for the fHRmsCharge
+  Int_t   fRmsChargeNbins;                //  Number of  bins used for the fHRmsCharge
+  Float_t fRmsChargeMean;                 //  Mean of the Gauss fit               
+  Float_t fRmsChargeMeanErr;              //  Error of the mean of the Gauss fit 
+  Float_t fRmsChargeSigma;                //  Sigma of the Gauss fit             
+  Float_t fRmsChargeSigmaErr;             //  Error of the sigma of the Gauss fit
+  Float_t fTimeLowerLimit;                //  Limit dist. to first signal slice (units: FADC slices) 
+  Float_t fTimeUpperLimit;                //  Limit dist. to last signal slice  (units: FADC slices) 
+
+  Int_t   fExclusionMean;                 //  Number of events excluded by deviating mean
+  Int_t   fExclusionSigma;                //  Number of events excluded by deviating sigma
+  Int_t   fExclusionChi2;                 //  Number of events excluded by deviating chi2
+  
+public:
+
+  MHCalibrationChargePINDiode(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargePINDiode(){}
+
+  Bool_t SetupFill(const MParList *pList);
+  Bool_t ReInit   (      MParList *pList);
+  Int_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; }
+
+  Int_t       GetExclusionMean()      const { return fExclusionMean;     }
+  Int_t       GetExclusionSigma()     const { return fExclusionSigma;    }
+  Int_t       GetExclusionChi2()      const { return fExclusionChi2;     }
+  
+  
+  // Fill histos
+  Bool_t FillRmsCharge(const Float_t q);
+
+  // Fits
+  Bool_t FitRmsCharge(Option_t *option="RQ0");
+
+  // Setters
+  void SetBinningRmsCharge(Int_t n, Axis_t lo, Axis_t up) { fRmsChargeNbins=n; fRmsChargeFirst=lo; fRmsChargeLast=up; }
+
+  void SetTimeLowerLimit ( const Float_t f=fgTimeLowerLimit     ) { fTimeLowerLimit = f;     }
+  void SetTimeUpperLimit ( const Float_t f=fgTimeUpperLimit     ) { fTimeUpperLimit = f;     }
+
+  void SetAbsHistName  ( const char *name )  { fAbsHistName  = name;  }
+  void SetAbsHistTitle ( const char *name )  { fAbsHistTitle = name;  }
+  void SetAbsHistXTitle( const char *name )  { fAbsHistXTitle = name; }
+  void SetAbsHistYTitle( const char *name )  { fAbsHistYTitle = name; }
+   
+  void SetHistName  ( const char *name )  { fHistName  = name;  }
+  void SetHistTitle ( const char *name )  { fHistTitle = name;  }
+  void SetHistXTitle( const char *name )  { fHistXTitle = name; }
+  void SetHistYTitle( const char *name )  { fHistYTitle = name; }
+   
+  ClassDef(MHCalibrationChargePINDiode, 2)  // Histogram class for Charge PIN Diode Calibration 
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePix.cc	(revision 17960)
@@ -0,0 +1,255 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargePix
+//
+//  Histogram class for the charge calibration. 
+//  Stores and fits the charges and stores the location of the maximum FADC 
+//  slice. Charges are taken from MExtractedSignalPix.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargePix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TGraph.h>
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCalibrationChargePix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default x-axis title for fHAbsTime ("Absolute Arrival Time [FADC slice nr]")
+// - the default y-axis title for fHAbsTime ("Nr. of events"); 
+// - the default directory of the fHAbsTime (NULL)
+// - the current style for fHAbsTime
+//
+// Initializes:
+// - fHAbsTime()
+//
+// Calls:
+// - Clear();
+//
+MHCalibrationChargePix::MHCalibrationChargePix(const char *name, const char *title)
+    : fHAbsTime(), 
+      fAbsTimeNbins(1), fAbsTimeFirst(0.), fAbsTimeLast(1.)
+{ 
+  
+  fName  = name  ? name  : "MHCalibrationChargePix";
+  fTitle = title ? title : "Statistics of the FADC sums of calibration events";
+
+  fHAbsTime.UseCurrentStyle();
+  fHAbsTime.SetDirectory(NULL); 
+
+  Clear();
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - fHGausHist.SetBins(fNbins,fFirst,fLast);
+// - fHAbsTime.SetBins(fAbsTimeNbins,fAbsTimeFirst,fAbsTimeLast);
+//
+void MHCalibrationChargePix::InitBins()
+{
+  MHGausEvents::InitBins();
+  fHAbsTime.SetBins(fAbsTimeNbins,fAbsTimeFirst,fAbsTimeLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// Empty function to overload MHGausEvents::Reset()
+//
+void MHCalibrationChargePix::Reset()
+{
+  MHGausEvents::Reset();
+  fHAbsTime.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// returns fHGausHist.Integral("width")
+//
+const Float_t MHCalibrationChargePix::GetIntegral() const 
+{ 
+   return fHGausHist.Integral("width");  
+}
+
+// --------------------------------------------------------------------------
+//
+// returns fHAbsTime.GetMean()
+//
+const Float_t MHCalibrationChargePix::GetAbsTimeMean() const 
+{
+  return fHAbsTime.GetMean();
+}
+
+// --------------------------------------------------------------------------
+//
+// returns fHAbsTime.GetRMS()
+//
+const Float_t MHCalibrationChargePix::GetAbsTimeRms()  const 
+{
+  return fHAbsTime.GetRMS();
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills fHAbsTime with t
+// Returns kFALSE, if overflow or underflow occurred, else kTRUE
+//
+Bool_t MHCalibrationChargePix::FillAbsTime(Float_t t)
+{
+  return fHAbsTime.Fill(t) > -1;
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// The following options can be chosen:
+//
+// "": displays the fHGausHist and the fHAbsTime
+// "all": executes additionally MHCalibrationPix::Draw(), with options
+//
+// The following picture shows a typical outcome of call to Draw("all"): 
+// One the left side:
+// - The distribution of the values with the Gauss fit are shown (points connected 
+//   with each other). The line is green, thus the Gauss fit has a probability higher 
+//   than 0.5%.
+// - The distribution of the positions of the maximum (abs. arrival times) 
+//   is displayed. Most of the events have an arrival time of slice 7 (==hardware:8)
+//
+// On the right side:
+// - The first plot shows the distribution of the values with the Gauss fit
+//   with error bars
+// - The second plot shows the TGraph with the events vs. time
+// - The third plot shows the fourier transform and a peak at 100 Hz.
+// - The fourth plot shows the projection of the fourier components and an exponential 
+//   fit, with the result that the observed deviation is not statistical, but signficant with a 
+//   probability smaller than 0.5%. 
+//
+//Begin_Html
+/*
+<img src="images/MHCalibrationChargePixDraw.gif">
+*/
+//End_Html
+//
+void MHCalibrationChargePix::Draw(const Option_t *opt)
+{
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+  
+  TVirtualPad *oldpad = gPad ? gPad : MH::MakeDefCanvas(this,600, 600);
+  TVirtualPad *pad    = NULL;
+
+  if (option.Contains("all"))
+  {
+      option.ReplaceAll("all","");
+      oldpad->Divide(2,1);
+      win = 2;
+      oldpad->cd(1);
+      TVirtualPad *newpad = gPad;
+      pad = newpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  else if (option.Contains("datacheck"))
+    {
+      MHCalibrationPix::Draw("events");
+      return;
+    }
+  else 
+  {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  /*
+  else
+    {
+      option.ReplaceAll("time","");
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+    }
+  */
+  if (!IsEmpty() && !IsOnlyOverflow() && !IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.GetXaxis()->SetLabelSize(0.06);
+  fHGausHist.GetYaxis()->SetLabelSize(0.07);
+  fHGausHist.GetXaxis()->SetLabelOffset(0.01);
+  fHGausHist.GetYaxis()->SetLabelOffset(0.01);
+  fHGausHist.GetXaxis()->SetTitleSize(0.065);
+  fHGausHist.GetYaxis()->SetTitleSize(0.07);
+  fHGausHist.GetXaxis()->SetTitleOffset(0.6);
+  fHGausHist.GetYaxis()->SetTitleOffset(0.6);
+  fHGausHist.Draw(); 
+  if (fFGausFit)
+  {
+      fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+      fFGausFit->Draw("same");
+  }
+
+  pad->cd(2);
+  gPad->SetTicks();
+
+  fHAbsTime.GetXaxis()->SetLabelSize(0.06);
+  fHAbsTime.GetYaxis()->SetLabelSize(0.07);
+  fHAbsTime.GetXaxis()->SetLabelOffset(0.01);
+  fHAbsTime.GetYaxis()->SetLabelOffset(0.01);
+  fHAbsTime.GetXaxis()->SetTitleSize(0.065);
+  fHAbsTime.GetYaxis()->SetTitleSize(0.07);
+  fHAbsTime.GetXaxis()->SetTitleOffset(0.6);
+  fHAbsTime.GetYaxis()->SetTitleOffset(0.6);
+  fHAbsTime.Draw();
+
+  if (win < 2)
+      return;
+
+  oldpad->cd(2);
+  MHCalibrationPix::Draw("fourierevents");
+
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationChargePix.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MHCalibrationChargePix
+#define MARS_MHCalibrationChargePix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+class MHCalibrationChargePix : public MHCalibrationPix
+{
+
+protected:
+
+  TH1F     fHAbsTime;      // Histogram containing the absolute arrival times 
+                          
+  Int_t    fAbsTimeNbins;  // Number of  bins used for the fHAbsTime 
+  Axis_t   fAbsTimeFirst;  // Lower bound bin used for the fHAbsTime
+  Axis_t   fAbsTimeLast;   // Upper bound bin used for the fHAbsTime
+
+public:
+
+  MHCalibrationChargePix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargePix() {}
+
+  void Reset();  
+  void InitBins();
+  
+  // Setters
+  void SetBinningAbsTime(Int_t n, Axis_t lo, Axis_t up) { fAbsTimeNbins=n; fAbsTimeFirst=lo; fAbsTimeLast=up; }
+
+  // Getters
+        TH1F *GetHAbsTime()       { return &fHAbsTime;  }
+  const TH1F *GetHAbsTime() const { return &fHAbsTime;  }
+
+  const Float_t  GetAbsTimeMean() const;
+  const Float_t  GetAbsTimeRms() const;
+  const Float_t  GetIntegral() const;
+
+  // Fill histos
+  Bool_t FillAbsTime(const Float_t t);
+
+  // Draws
+  void Draw(Option_t *opt="");
+
+  ClassDef(MHCalibrationChargePix, 1)     // Base Histogram class for Charge Pixel Calibration
+};
+
+#endif /* MARS_MHCalibrationChargePix */
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoCam.cc	(revision 17960)
@@ -0,0 +1,1079 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!              
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                        
+// MHCalibrationHiLoCam                                                
+//                                                                        
+// Fills the extracted high-gain low-gain charge ratios of MArrivalTimeCam into 
+// the MHCalibrationPix-classes MHCalibrationPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray  
+//   or MHCalibrationCam::fHiGainArray, respectively, depending if 
+//   MArrivalTimePix::IsLoGainUsed() is set.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors 
+//   and MHCalibrationCam::fAverageHiGainSectors 
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiLoNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the 
+// projected fourier components follow an exponential distribution. 
+// In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiLoOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MCalibrationHiLoCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationHiLoCam.h"
+
+#include <TOrdCollection.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TF1.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TGraph.h>
+#include <TProfile.h>
+
+#include "MHCalibrationHiLoPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationHiLoCam.h"
+#include "MCalibrationHiLoPix.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MHCalibrationHiLoCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationHiLoCam::fgNbins    = 175;
+const Axis_t  MHCalibrationHiLoCam::fgFirst    = -5.1;
+const Axis_t  MHCalibrationHiLoCam::fgLast     = 29.9;
+const Float_t MHCalibrationHiLoCam::fgProbLimit = 0.;
+const Int_t   MHCalibrationHiLoCam::fgHivsLoNbins = 90;
+const Axis_t  MHCalibrationHiLoCam::fgHivsLoFirst = 95.;
+const Axis_t  MHCalibrationHiLoCam::fgHivsLoLast  = 995.;
+const Axis_t  MHCalibrationHiLoCam::fgLowerFitLimitProfile = 480.;
+const Axis_t  MHCalibrationHiLoCam::fgUpperFitLimitProfile = 680.;
+const TString MHCalibrationHiLoCam::gsHistName  = "HiLo";
+const TString MHCalibrationHiLoCam::gsHistTitle = "HiGain vs. LoGain";
+const TString MHCalibrationHiLoCam::gsHistXTitle = "Amplification Ratio [1]";
+const TString MHCalibrationHiLoCam::gsHistYTitle = "Nr. events";
+const TString MHCalibrationHiLoCam::gsHivsLoHistName   = "HivsLo";
+const TString MHCalibrationHiLoCam::gsHivsLoHistTitle  = "High-gain vs. Low-gain Charge";
+const TString MHCalibrationHiLoCam::gsHivsLoHistXTitle = "Q High-Gain [FADC counts]";
+const TString MHCalibrationHiLoCam::gsHivsLoHistYTitle = "Q Low-Gain [FADC counts]";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor.
+//
+// Sets: 
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fLowerLimt  to fgLowerLim
+// - fUpperLimt  to fgUpperLim
+//
+MHCalibrationHiLoCam::MHCalibrationHiLoCam(const char *name, const char *title) 
+  : fArrTimes(NULL), fHivsLoResults("Results","Fit Results high-gain vs. low-gain",
+				    200,-10.,10.,200,0.,20.),
+    fUsedLoGainSlices(0)
+{
+
+  fName  = name  ? name  : "MHCalibrationHiLoCam";
+  fTitle = title ? title : "Histogram class for the high-gain vs. low-gain amplification ratio calibration";
+
+  SetNbins(fgNbins);
+  SetFirst(fgFirst);
+  SetLast (fgLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetHivsLoNbins(fgHivsLoNbins);
+  SetHivsLoFirst(fgHivsLoFirst);
+  SetHivsLoLast (fgHivsLoLast );
+
+  SetLowerFitLimitProfile();
+  SetUpperFitLimitProfile();
+
+  SetHivsLoHistName  (gsHivsLoHistName  .Data());
+  SetHivsLoHistTitle (gsHivsLoHistTitle .Data());
+  SetHivsLoHistXTitle(gsHivsLoHistXTitle.Data());
+  SetHivsLoHistYTitle(gsHivsLoHistYTitle.Data());
+
+  SetOscillations(kFALSE);
+  
+  fHivsLoResults.GetXaxis()->SetTitle("Offset per FADC slices [FADC cnts]");
+  fHivsLoResults.GetYaxis()->SetTitle("Gains ratio [1]");
+  fHivsLoResults.SetDirectory(0);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationHiLoCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationHiLoCam *cam = MParList::FindObject("MHCalibrationHiLoCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationHiLoCam::Clone(const char *) const
+{
+
+  MHCalibrationHiLoCam *cam = new MHCalibrationHiLoCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+
+  //
+  // Copy the MArrays
+  //
+  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
+  cam->fAverageAreaRelSigmaVar = fAverageAreaRelSigmaVar;
+  cam->fAverageAreaSat         = fAverageAreaSat;
+  cam->fAverageAreaSigma       = fAverageAreaSigma;
+  cam->fAverageAreaSigmaVar    = fAverageAreaSigmaVar;
+  cam->fAverageAreaNum         = fAverageAreaNum;
+  cam->fAverageSectorNum       = fAverageSectorNum;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+  const Int_t navlo   =  fAverageLoGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  for (int i=0; i<navlo; i++)
+    cam->fAverageLoGainAreas->AddAt(GetAverageLoGainArea(i).Clone(),i);
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MCalibrationHiLoCam
+//
+// Searches pointer to:
+// - MExtractedSignalCam
+// - MArrivalTimeCam
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// - MHCalibrationCam::InitLoGainArrays()
+// 
+// Sets:
+// - fSumarea   to nareas
+// - fSumsector to nareas
+// - fNumarea   to nareas
+// - fNumsector to nareas
+//
+Bool_t MHCalibrationHiLoCam::ReInitHists(MParList *pList)
+{
+
+  fCam = (MCalibrationCam*)pList->FindObject(AddSerialNumber("MCalibrationHiLoCam"));
+  if (!fCam)
+    {
+      fCam = (MCalibrationCam*)pList->FindCreateObj(AddSerialNumber("MCalibrationHiLoCam"));
+      if (!fCam)
+	  return kFALSE;
+      fCam->Init(*fGeom);
+    }
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!signal)
+  {
+      *fLog << err << "MExtractedSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  fUsedLoGainSlices = signal->GetNumUsedLoGainFADCSlices();
+
+  fArrTimes = (MArrivalTimeCam*)pList->FindObject("MArrivalTimeCam");
+  if (!fArrTimes)
+  {
+      *fLog << warn << "MArrivalTimeCam not found... cannot calibrated arrival times between "
+	    <<"high and low-gain" << endl;
+      SetLoGain(kFALSE);
+  }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fSumareahi  .Set(nareas); 
+  fSumsectorhi.Set(nsectors); 
+  fNumareahi  .Set(nareas); 
+  fNumsectorhi.Set(nsectors); 
+  if (IsLoGain())
+    {
+      fSumarealo  .Set(nareas); 
+      fSumsectorlo.Set(nsectors); 
+      fNumarealo  .Set(nareas); 
+      fNumsectorlo.Set(nsectors); 
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the High Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationHiLoPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of Abs Times histogram from  fAbsNbins, fAbsFirst and fAbsLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set Abs Times Histgram names and titles from fAbsHistName and fAbsHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of Abs Times Histogram from fAbsHistXTitle and fAbsHistYTitle
+//   * Call InitHists
+//
+//
+void MHCalibrationHiLoCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+  
+  TProfile *h;
+
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationHiLoPix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                       Form("%s High Gain Pixel%04d",fHistTitle.Data(),i)),i);
+
+        MHCalibrationHiLoPix &pix = (MHCalibrationHiLoPix&)(*this)[i];
+
+        pix.SetNbins(fNbins);
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+
+        pix.SetProbLimit(fProbLimit);
+
+        pix.SetHivsLoNbins(fHivsLoNbins);
+        pix.SetHivsLoFirst(fHivsLoFirst);
+        pix.SetHivsLoLast (fHivsLoLast);
+
+        InitHists(pix,(*fBadPixels)[i],i);
+
+	if (fCam)
+	  (*fCam)[i].SetPixId(i);
+
+        h = pix.GetHivsLo();
+
+        h->SetName (Form("H%sHiGainPix%04d",fHivsLoHistName.Data(),i));
+        h->SetTitle(Form("%s High Gain Pixel %04d",fHivsLoHistTitle.Data(),i));
+        h->SetXTitle(fHivsLoHistXTitle.Data());
+        h->SetYTitle(fHivsLoHistYTitle.Data());
+        h->SetDirectory(0);
+      }
+  }
+
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHCalibrationHiLoPix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                  Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationHiLoPix &pix = (MHCalibrationHiLoPix&)GetAverageHiGainArea(j);
+        
+        pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        
+        pix.SetHivsLoNbins(fHivsLoNbins);
+        pix.SetHivsLoFirst(fHivsLoFirst);
+        pix.SetHivsLoLast (fHivsLoLast);
+
+        InitHists(pix, fCam->GetAverageBadArea(j), j);
+
+	if (fCam)
+	  fCam->GetAverageArea(j).SetPixId(j);
+
+        h =  pix.GetHivsLo();
+        
+        h->SetName (Form("H%sHiGainArea%d",fHivsLoHistName.Data(),j));
+        h->SetTitle(Form("%s averaged on event-by-event basis High Gain Area Idx %d",
+                         fHivsLoHistTitle.Data(), j));
+        h->SetXTitle(fHivsLoHistXTitle.Data());
+        h->SetYTitle(fHivsLoHistYTitle.Data());
+        h->SetDirectory(0);
+      }
+  }
+  
+  if (fAverageHiGainSectors->GetSize()==0)
+  {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+	  fAverageHiGainSectors->AddAt(new MHCalibrationHiLoPix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                      Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+
+          MHCalibrationHiLoPix &pix = (MHCalibrationHiLoPix&)GetAverageHiGainSector(j);
+
+          pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+
+          pix.SetHivsLoNbins(fHivsLoNbins);
+          pix.SetHivsLoFirst(fHivsLoFirst);
+          pix.SetHivsLoLast (fHivsLoLast);
+          
+          InitHists(pix, fCam->GetAverageBadSector(j), j);
+
+	  if (fCam)
+	    fCam->GetAverageSector(j).SetPixId(j);
+
+          h =  pix.GetHivsLo();
+          
+          h->SetName (Form("H%sHiGainSector%02d",fHivsLoHistName.Data(),j));
+          h->SetTitle(Form("%s averaged on event-by-event basis High Gain Area Sector %02d",
+                           fHivsLoHistTitle.Data(),j));
+          h->SetXTitle(fHivsLoHistXTitle.Data());
+          h->SetYTitle(fHivsLoHistYTitle.Data());
+          h->SetDirectory(0);
+      }
+  }
+}
+
+//--------------------------------------------------------------------------------------
+//
+// Return, if IsLoGain() is kFALSE 
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the Low Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationHiLoPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of HivsLo Times histogram from  fHivsLoNbins, fHivsLoFirst and fHivsLoLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set HivsLo Times Histgram names and titles from fHivsLoHistName and fHivsLoHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of HivsLo Times Histogram from fHivsLoHistXTitle and fHivsLoHistYTitle
+//   * Call InitHists
+//
+void MHCalibrationHiLoCam::InitLoGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+  if (!IsLoGain())
+    return;
+
+  TProfile *h;
+
+  if (fLoGainArray->GetSize()==0 )
+    {
+      for (Int_t i=0; i<npixels; i++)
+        {
+          fLoGainArray->AddAt(new MHCalibrationHiLoPix(Form("%sLoGainPix%04d",fHistName.Data(),i),
+                                       Form("%s Low Gain Pixel %04d",fHistTitle.Data(),i)),i);
+
+          MHCalibrationHiLoPix &pix = (MHCalibrationHiLoPix&)(*this)(i);
+
+          pix.SetNbins(fNbins);
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+          
+          pix.SetProbLimit(fProbLimit);
+
+          pix.SetHivsLoNbins(fHivsLoNbins);
+          pix.SetHivsLoFirst(fHivsLoFirst);
+          pix.SetHivsLoLast (fHivsLoLast );
+          
+          InitHists(pix,(*fBadPixels)[i],i);
+
+          h = pix.GetHivsLo();
+          
+          h->SetName (Form("H%sLoGainPix%04d",fHivsLoHistName.Data(),i));
+          h->SetTitle(Form("%s Low Gain Pixel %04d",fHivsLoHistTitle.Data(),i));
+          h->SetXTitle(fHivsLoHistXTitle.Data());
+          h->SetYTitle(fHivsLoHistYTitle.Data());
+          h->SetDirectory(0);
+      }
+  }
+
+  if (fAverageLoGainAreas->GetSize()==0)
+    {
+      for (Int_t j=0; j<nareas; j++)
+        {
+	  fAverageLoGainAreas->AddAt(new MHCalibrationHiLoPix(Form("%sLoGainArea%d",fHistName.Data(),j),
+                                       Form("%s Low Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+          MHCalibrationHiLoPix &pix = (MHCalibrationHiLoPix&)GetAverageLoGainArea(j);
+          
+          pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+          
+          pix.SetHivsLoNbins(fHivsLoNbins);
+          pix.SetHivsLoFirst(fHivsLoFirst);
+          pix.SetHivsLoLast (fHivsLoLast );
+          
+          InitHists(pix, fCam->GetAverageBadArea(j), j);
+
+          h =  pix.GetHivsLo();
+          
+          h->SetName (Form("H%sLoGainArea%02d",fHivsLoHistName.Data(),j));
+          h->SetTitle(Form("%s%s%02d",fHivsLoHistTitle.Data(),
+                           " averaged on event-by-event basis Low Gain Area Idx ",j));
+          h->SetXTitle(fHivsLoHistXTitle.Data());
+          h->SetYTitle(fHivsLoHistYTitle.Data());
+          h->SetDirectory(0);
+        }
+    }
+  
+
+  if (fAverageLoGainSectors->GetSize()==0 && IsLoGain())
+  {
+    for (Int_t j=0; j<nsectors; j++)
+      {
+        fAverageLoGainSectors->AddAt(new MHCalibrationHiLoPix(Form("%sLoGainSector%02d",fHistName.Data(),j),
+                                                        Form("%s Low Gain Sector %02d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationHiLoPix &pix = (MHCalibrationHiLoPix&)GetAverageLoGainSector(j);
+        
+        pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        
+        pix.SetHivsLoNbins(fHivsLoNbins);
+        pix.SetHivsLoFirst(fHivsLoFirst);
+        pix.SetHivsLoLast (fHivsLoLast);
+        
+        InitHists(pix, fCam->GetAverageBadSector(j), j);
+
+        h =  pix.GetHivsLo();
+        
+        h->SetName (Form("H%sLoGainSector%02d",fHivsLoHistName.Data(),j));
+        h->SetTitle(Form("%s%s%02d",fHivsLoHistTitle.Data(),
+                           " averaged on event-by-event basis Low Gain Area Sector ",j));
+        h->SetXTitle(fHivsLoHistXTitle.Data());
+        h->SetYTitle(fHivsLoHistYTitle.Data());
+        h->SetDirectory(0);
+      }
+  }
+}
+
+
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MExtractedSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills histograms (MHGausEvents::FillHistAndArray()) with:
+// - MExtractedSignalPix::GetExtractedSignalHiGain(pixid) / MExtractedSignalPix::GetExtractedSignalLoGain;
+//   if the high-gain signal does not show high-gain saturation, but the low-gain
+//   has been extracted.
+// - MArrivalTimePix::GetArrivalTimeHiGain(pixid) / MArrivalTimePix::GetArrivalTimeLoGain;
+//   if the high-gain signal does not show high-gain saturation, but the low-gain
+//   has been extracted.
+//
+Bool_t MHCalibrationHiLoCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)par;
+  if (!signal)
+    {
+      gLog << err << "No argument in MExtractedSignal::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  fSumareahi  .Reset();
+  fSumsectorhi.Reset(); 
+  fNumareahi  .Reset(); 
+  fNumsectorhi.Reset(); 
+  fSumarealo  .Reset();
+  fSumsectorlo.Reset(); 
+  fNumarealo  .Reset(); 
+  fNumsectorlo.Reset(); 
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+      const MExtractedSignalPix &pix = (*signal)[i];
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      const Float_t siglo = pix.GetExtractedSignalLoGain();
+
+      //
+      // Skip all pixels with:
+      // - Saturated high-gain
+      // - Not extracted low-gain 
+      //   (see MExtractTimeAndCharge::fLoGainSwitch for setting the criteria)
+      //
+      if (siglo < 0.5 || pix.IsHiGainSaturated())
+	continue;
+
+      const Float_t sighi = pix.GetExtractedSignalHiGain();
+
+      //      *fLog << err << sighi << "  " << siglo << endl;
+      const Float_t ratio = sighi / siglo;
+      
+      MHCalibrationHiLoPix &histhi = (MHCalibrationHiLoPix&)(*this)[i];
+
+      histhi.FillHist(ratio);
+      histhi.FillHivsLo(sighi,siglo);
+
+      if (IsAverageing())
+	{
+	  MHCalibrationHiLoPix &histhi2 = (MHCalibrationHiLoPix&)GetAverageHiGainArea(aidx);
+	  histhi2.FillHivsLo(sighi,siglo);
+	}
+
+      fSumareahi  [aidx]   += ratio;
+      fNumareahi  [aidx]   ++;
+      fSumsectorhi[sector] += ratio;
+      fNumsectorhi[sector] ++;
+
+      if (IsLoGain())
+	{
+	  const MArrivalTimePix &tix = (*fArrTimes)[i];
+	  MHCalibrationPix &histlo = (*this)(i);	  
+
+	  const Float_t diff = tix.GetArrivalTimeLoGain() - tix.GetArrivalTimeHiGain();
+
+	  histlo.FillHist(diff);
+	  fSumarealo  [aidx]   += diff;
+	  fNumarealo  [aidx]   ++;
+	  fSumsectorlo[sector] += diff;
+	  fNumsectorlo[sector] ++;
+	}
+    }
+
+  if (!IsAverageing())
+      return kTRUE;
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+
+      MHCalibrationHiLoPix &histhi = (MHCalibrationHiLoPix&)GetAverageHiGainArea(j);
+      
+      if (IsOscillations())
+	histhi.FillHistAndArray(fNumareahi[j] == 0 ? 0. : fSumareahi[j]/fNumareahi[j]);
+      else
+	histhi.FillHist(fNumareahi[j] == 0 ? 0. : fSumareahi[j]/fNumareahi[j]);
+
+      if (IsLoGain())
+	{
+	  MHCalibrationPix &histlo = GetAverageLoGainArea(j);
+	  if (IsOscillations())
+	    histlo.FillHistAndArray(fNumarealo[j] == 0 ? 0. : fSumarealo[j]/fNumarealo[j]);
+	  else
+	    histlo.FillHist(fNumarealo[j] == 0 ? 0. : fSumarealo[j]/fNumarealo[j]);
+	}
+    }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);
+
+      if (IsOscillations())
+	hist.FillHistAndArray(fNumsectorhi[j] == 0 ? 0. : fSumsectorhi[j]/fNumsectorhi[j]);
+      else
+	hist.FillHist(fNumsectorhi[j] == 0 ? 0. : fSumsectorhi[j]/fNumsectorhi[j]);
+
+      if (IsLoGain())
+	{
+
+	  MHCalibrationPix &histlo = GetAverageLoGainSector(j);
+
+	  if (IsOscillations())
+	    histlo.FillHistAndArray(fNumsectorlo[j] == 0 ? 0. : fSumsectorlo[j]/fNumsectorlo[j]);
+	  else
+	    histlo.FillHist(fNumsectorlo[j] == 0 ? 0. : fSumsectorlo[j]/fNumsectorlo[j]);
+	}
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with flags:
+//   MBadPixelsPix::kHiLoNotFitted and MBadPixelsPix::kHiLoOscillating
+// - MHCalibrationCam::FitLoGainArrays() with flags:
+//   MBadPixelsPix::kHiLoNotFitted and MBadPixelsPix::kHiLoOscillating
+// 
+Bool_t MHCalibrationHiLoCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  MCalibrationCam *hilocam = fCam;
+
+  const Int_t nareas   = fAverageHiGainAreas->GetSize();
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationHiLoPix &hist = (MHCalibrationHiLoPix&)(*this)[i];
+
+      if (hist.IsExcluded())
+        continue;
+      
+      CheckOverflow(hist);
+
+      TProfile *h = hist.GetHivsLo();
+      h->Fit("pol1","RQ","",fLowerFitLimitProfile,fUpperFitLimitProfile);
+
+      TF1 *fit = h->GetFunction("pol1");
+
+      const Float_t gainr  = fit->GetParameter(1) > 0.001 
+          ? 1./fit->GetParameter(1) : 0.;
+
+      // The number of used slices are just a mean value
+      // the real number might change from event to event.
+      // (up to 50%!)
+      const Float_t offset = fit->GetParameter(0)/fUsedLoGainSlices;
+
+      fHivsLoResults.Fill(offset,gainr);
+      
+      MCalibrationHiLoPix &pix = (MCalibrationHiLoPix&)(*fCam)[i];
+      pix.SetOffsetPerSlice(offset);
+      pix.SetGainRatio     (gainr );
+
+    }
+
+  //
+  // Check histogram overflow
+  //
+  if (IsAverageing())
+  {
+      for (Int_t j=0; j<nareas; j++)
+          CheckOverflow(GetAverageHiGainArea(j));
+
+      for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+          CheckOverflow(GetAverageHiGainSector(j));
+  }
+
+
+  FitHiGainArrays(*hilocam, *fBadPixels,
+                  MBadPixelsPix::kHiLoNotFitted,
+                  MBadPixelsPix::kHiLoOscillating);
+  
+  if (!IsLoGain())
+    return kTRUE;
+
+  for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)(i);
+
+      if (hist.IsExcluded())
+        continue;
+      
+      CheckOverflow(hist);
+    }
+
+  if (IsAverageing())
+  {
+      for (Int_t j=0; j<nareas; j++)
+        {
+	  
+	  MHCalibrationHiLoPix &hist = (MHCalibrationHiLoPix&)GetAverageHiGainArea(j);
+	  //
+	  // Check histogram overflow
+	  // 
+	  CheckOverflow(hist);
+	  
+	  TProfile *h = hist.GetHivsLo();
+	  h->Fit("pol1","RQ","",fLowerFitLimitProfile,fUpperFitLimitProfile);
+
+	  TF1 *fit = h->GetFunction("pol1");
+	  
+	  const Float_t gainr  = fit->GetParameter(1) > 0.001 
+	    ? 1./fit->GetParameter(1) : 0.;
+
+          // The number of used slices are just a mean value
+          // the real number might change from event to event.
+          // (up to 50%!)
+	  const Float_t offset = fit->GetParameter(0)/fUsedLoGainSlices;
+	  
+	  MCalibrationHiLoPix &pix = (MCalibrationHiLoPix&)fCam->GetAverageArea(0);
+	  pix.SetOffsetPerSlice(offset);
+	  pix.SetGainRatio     (gainr );
+
+        }
+      
+      for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+        {
+	  
+          MHCalibrationHiLoPix &hist = (MHCalibrationHiLoPix&)GetAverageHiGainSector(j);      
+          //
+          // Check histogram overflow
+          // 
+          CheckOverflow(hist);
+
+	  TProfile *h = hist.GetHivsLo();
+	  h->Fit("pol1","RQ","",fLowerFitLimitProfile,fUpperFitLimitProfile);
+
+	  TF1 *fit = h->GetFunction("pol1");
+	  
+	  const Float_t gainr  = fit->GetParameter(1) > 0.001 
+	    ? 1./fit->GetParameter(1) : 0.;
+
+          // The number of used slices are just a mean value
+          // the real number might change from event to event.
+          // (up to 50%!)
+	  const Float_t offset = fit->GetParameter(0)/fUsedLoGainSlices;
+	  
+	  MCalibrationHiLoPix &pix = (MCalibrationHiLoPix&)fCam->GetAverageSector(0);
+	  pix.SetOffsetPerSlice(offset);
+	  pix.SetGainRatio     (gainr );
+
+        }
+  }
+
+  FitLoGainArrays(*hilocam, *fBadPixels,
+                  MBadPixelsPix::kHiLoNotFitted,
+                  MBadPixelsPix::kHiLoOscillating);
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets all pixels to MBadPixelsPix::kUnreliableRun, if following flags are set:
+// - MBadPixelsPix::kHiLoNotFitted
+// - MBadPixelsPix::kHiLoOscillating
+//
+void MHCalibrationHiLoCam::FinalizeBadPixels()
+{
+
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kHiLoNotFitted ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kHiLoOscillating))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+      
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Mean High-Gain Low-Gain Charge Ratio in FADC slices  (MHGausEvents::GetMean()
+// 1: Error Mean High-Gain Low-Gain Charge Ratio in FADC slices   (MHGausEvents::GetMeanErr()
+// 2: Sigma fitted High-Gain Low-Gain Charge Ratio in FADC slices (MHGausEvents::GetSigma()
+// 3: Error Sigma High-Gain Low-Gain Charge Ratio in FADC slices  (MHGausEvents::GetSigmaErr()
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit              (calls: MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                               (calls: MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK                       (calls: MHGausEvents::IsFourierSpectrumOK())
+//
+Bool_t MHCalibrationHiLoCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pixhi = (*this)[idx];
+  const MHCalibrationPix &pixlo = (*this)(idx);
+
+  switch (type)
+    {
+    case 0:
+      val = pixhi.GetMean();
+      break;
+    case 1:
+      val = pixhi.GetMeanErr();
+      break;
+    case 2:
+      val = pixhi.GetSigma();
+      break;
+    case 3:
+      val = pixhi.GetSigmaErr();
+      break;
+    case 4:
+      val = pixhi.GetProb();
+      break;
+    case 5:
+      if (!pixhi.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pixhi.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    case 7:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetMean();
+      break;
+    case 8:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetMeanErr();
+      break;
+    case 9:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetSigma();
+      break;
+    case 10:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetSigmaErr();
+      break;
+    case 11:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetProb();
+      break;
+    case 12:
+      if (!IsLoGain())
+	break;
+      if (!pixlo.IsGausFitOK())
+        val = 1.;
+      break;
+    case 13:
+      if (!IsLoGain())
+	break;
+      if (!pixlo.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationHiLoCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+void MHCalibrationHiLoCam::CheckOverflow( MHCalibrationPix &pix )
+{
+
+  if (pix.IsExcluded())
+    return;
+
+  TH1F *hist = pix.GetHGausHist();
+  
+  Stat_t overflow = hist->GetBinContent(hist->GetNbinsX()+1);
+  if (overflow > fOverflowLimit*hist->GetEntries())
+    {
+      *fLog << warn << "Hist-overflow " << overflow
+            << " times in " << pix.GetName() << endl;
+    }
+  
+  overflow = hist->GetBinContent(0);
+  if (overflow > fOverflowLimit*hist->GetEntries())
+    {
+      *fLog << warn << "Hist-underflow " << overflow
+            << " times in " << pix.GetName()  << endl;
+    }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both amplification ratio as time difference
+//
+void MHCalibrationHiLoCam::Draw(const Option_t *opt)
+{
+
+  if (!IsAverageing())
+    return;
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  pad->Divide(IsLoGain() ? 2 : 1,nareas);
+
+  for (Int_t i=0; i<nareas;i++) 
+    {
+
+      pad->cd(IsLoGain() ? 2*(i+1)-1 : i+1);
+
+      GetAverageHiGainArea(i).Draw(opt);
+
+      if (IsLoGain())
+        {
+          pad->cd(2*(i+1));
+
+          TH1F *hist = GetAverageLoGainArea(i).GetHGausHist();
+          hist->SetXTitle("Extracted Time Difference [FADC sl.]");
+          GetAverageLoGainArea(i).Draw(opt);
+        }
+    }
+}
+
+Int_t MHCalibrationHiLoCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (MHCalibrationCam::ReadEnv(env,prefix,print))
+    rc = kTRUE;
+   
+  if (IsEnvDefined(env, prefix, "LowerFitLimitProfile", print))
+    {
+      SetLowerFitLimitProfile(GetEnvValue(env, prefix, "LowerFitLimitProfile", fLowerFitLimitProfile));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "UpperFitLimitProfile", print))
+    {
+      SetUpperFitLimitProfile(GetEnvValue(env, prefix, "UpperFitLimitProfile", fUpperFitLimitProfile));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "HivsLoNbins", print))
+    {
+      SetHivsLoNbins(GetEnvValue(env, prefix, "HivsLoNbins", fHivsLoNbins));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "HivsLoFirst", print))
+    {
+      SetHivsLoFirst(GetEnvValue(env, prefix, "HivsLoFirst", fHivsLoFirst));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "HivsLoLast", print))
+    {
+      SetHivsLoLast(GetEnvValue(env, prefix, "HivsLoLast", fHivsLoLast));
+      rc = kTRUE;
+    }
+  
+  return rc;
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoCam.h	(revision 17960)
@@ -0,0 +1,118 @@
+#ifndef MARS_MHCalibrationHiLoCam
+#define MARS_MHCalibrationHiLoCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+#ifndef ROOT_TH2F
+#include <TH2F.h>
+#endif
+
+class MGeomCam;
+class MArrivalTimeCam;
+class MHCalibrationHiLoPix;
+
+class MHCalibrationHiLoCam : public MHCalibrationCam
+{
+private:
+   static const Int_t   fgNbins;                //! Default number of bins        (now set to: 900   )
+   static const Axis_t  fgFirst;                //! Default lower histogram limit (now set to: -13.5 )
+   static const Axis_t  fgLast;                 //! Default upper histogram limit (now set to:  13.5 )
+   static const Float_t fgProbLimit;            //! The default for fProbLimit    (now set to: 0.0)
+
+   static const Int_t   fgHivsLoNbins;          //! Default number of bins        (now set to: 900   )
+   static const Axis_t  fgHivsLoFirst;          //! Default lower histogram limit (now set to: -13.5 )
+   static const Axis_t  fgHivsLoLast;           //! Default upper histogram limit (now set to:  13.5 )
+
+   static const Axis_t  fgLowerFitLimitProfile; //! Default for fLowerFitLimitProfile    (now set to: 480. )
+   static const Axis_t  fgUpperFitLimitProfile; //! Default for fUpperFitLimitProfile    (now set to: 680. )
+
+   static const TString gsHistName;          //! Default Histogram names
+   static const TString gsHistTitle;         //! Default Histogram titles
+   static const TString gsHistXTitle;        //! Default Histogram x-axis titles
+   static const TString gsHistYTitle;        //! Default Histogram y-axis titles
+
+   static const TString gsHivsLoHistName;    //! Default  names hi vs. lo profile
+   static const TString gsHivsLoHistTitle;   //! Default  titles hi vs. lo profile
+   static const TString gsHivsLoHistXTitle;  //! Default  x-axis titles hi vs. lo profile
+   static const TString gsHivsLoHistYTitle;  //! Default  y-axis titles hi vs. lo profile
+
+   TString fHivsLoHistName;                  //  names hi vs. lo profile
+   TString fHivsLoHistTitle;                 //  titles hi vs. lo profile
+   TString fHivsLoHistXTitle;                //  x-axis titles hi vs. lo profile
+   TString fHivsLoHistYTitle;                //  y-axis titles hi vs. lo profile
+
+   Int_t   fHivsLoNbins;                     // Number of HivsLo bins
+   Axis_t  fHivsLoFirst;                     // Lower histogram limit low gain
+   Axis_t  fHivsLoLast;                      // Upper histogram limit low gain
+
+   Axis_t  fLowerFitLimitProfile;            // Lower limit for hi-vs. logain fit
+   Axis_t  fUpperFitLimitProfile;            // Upper limit for hi-vs. logain fit
+
+   MArrayD fSumareahi  ;                     //
+   MArrayD fSumsectorhi;                     //
+   MArrayI fNumareahi  ;                     //
+   MArrayI fNumsectorhi;                     //
+   MArrayD fSumarealo  ;                     //
+   MArrayD fSumsectorlo;                     //
+   MArrayI fNumarealo  ;                     //
+   MArrayI fNumsectorlo;                     //
+
+   MArrivalTimeCam *fArrTimes;               //! Pointer to arrival times
+
+   TH2F    fHivsLoResults;                   // Results from pol1-fit
+
+   Float_t fUsedLoGainSlices;                // Used low-gain FADC slices
+   Bool_t ReInitHists(MParList *pList);
+   Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+   Bool_t FinalizeHists();
+   void   FinalizeBadPixels();
+
+   void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+   void   InitLoGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+
+   void   FinalizeHivsLo (MHCalibrationHiLoPix &hist);
+
+   void   CheckOverflow( MHCalibrationPix &pix);
+
+   Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+  MHCalibrationHiLoCam(const char *name=NULL, const char *title=NULL);
+
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  TH2F &GetHivsLoResults() { return fHivsLoResults; }
+
+  void SetHivsLoHistName   ( const char *name )  { fHivsLoHistName   = name; }
+  void SetHivsLoHistTitle  ( const char *name )  { fHivsLoHistTitle  = name; }
+  void SetHivsLoHistXTitle ( const char *name )  { fHivsLoHistXTitle = name; }
+  void SetHivsLoHistYTitle ( const char *name )  { fHivsLoHistYTitle = name; }
+
+  void SetHivsLoNbins      ( const Int_t  i=fgHivsLoNbins   ) { fHivsLoNbins   = i; }
+  void SetHivsLoFirst      ( const Axis_t f=fgHivsLoFirst   ) { fHivsLoFirst   = f; }
+  void SetHivsLoLast       ( const Axis_t f=fgHivsLoLast    ) { fHivsLoLast    = f; }
+
+  void SetLowerFitLimitProfile( const Axis_t f=fgLowerFitLimitProfile ) { fLowerFitLimitProfile = f; }
+  void SetUpperFitLimitProfile( const Axis_t f=fgUpperFitLimitProfile ) { fUpperFitLimitProfile = f; }
+
+  // Draw
+  void   Draw(const Option_t *opt);       // *MENU*
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  ClassDef(MHCalibrationHiLoCam, 1)	// Histogram class for High Gain vs. Low Gain Calibration
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoPix.cc	(revision 17960)
@@ -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): Markus Gaug 06/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationHiLoPix
+//
+//  Histogram class for the charge calibration. 
+//  Stores and fits the charges and stores the location of the maximum FADC 
+//  slice. HiLos are taken from MExtractedSignalPix.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationHiLoPix.h"
+
+#include <TF1.h>
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TGraph.h>
+#include <TStyle.h>
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCalibrationHiLoPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default x-axis title for fHivsLo ("High-gain Charge [FADC slices]")
+// - the default y-axis title for fHivsLo ("Low-gain Charge [FADC slices]"); 
+// - the default directory of the fHivsLo (NULL)
+// - the current style for fHivsLo
+//
+// Initializes:
+// - fHivsLo()
+//
+// Calls:
+// - Clear();
+//
+MHCalibrationHiLoPix::MHCalibrationHiLoPix(const char *name, const char *title)
+    : fHivsLo(), 
+      fHivsLoNbins(1), fHivsLoFirst(0.), fHivsLoLast(1.)
+{ 
+  
+  fName  = name  ? name  : "MHCalibrationHiLoPix";
+  fTitle = title ? title : "High-gain vs. Low-gain intercalibration";
+
+  fHivsLo.UseCurrentStyle();
+  fHivsLo.SetDirectory(NULL); 
+
+  Clear();
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - fHGausHist.SetBins(fNbins,fFirst,fLast);
+// - fHivsLo.SetBins(fHivsLoNbins,fHivsLoFirst,fHivsLoLast);
+//
+void MHCalibrationHiLoPix::InitBins()
+{
+  MHGausEvents::InitBins();
+  fHivsLo.SetBins(fHivsLoNbins,fHivsLoFirst,fHivsLoLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// Empty function to overload MHGausEvents::Reset()
+//
+void MHCalibrationHiLoPix::Reset()
+{
+  MHGausEvents::Reset();
+  fHivsLo.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// returns probability of fit. If fit does not exist, 
+// returns -1. 
+//
+const Float_t MHCalibrationHiLoPix::GetHivsLoProb() const 
+{ 
+  const TF1 *fit = fHivsLo.GetFunction("pol1");
+  return fit ? fit->GetProb() : -1.;  
+}
+
+// --------------------------------------------------------------------------
+//
+// returns parameter 0 of fit. If fit does not exist,
+// returns -1.
+//
+const Float_t MHCalibrationHiLoPix::GetHivsLoP0() const 
+{
+  const TF1 *fit = fHivsLo.GetFunction("pol1");
+  return fit ? fit->GetParameter(0) : -1.;  
+}
+
+// --------------------------------------------------------------------------
+//
+// returns parameter 1 of fit. If fit does not exist,
+// returns -1.
+//
+const Float_t MHCalibrationHiLoPix::GetHivsLoP1() const 
+{
+  const TF1 *fit = fHivsLo.GetFunction("pol1");
+  return fit ? fit->GetParameter(1) : -1.;  
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills fHivsLo with t
+// Returns kFALSE, if overflow or underflow occurred, else kTRUE
+//
+Bool_t MHCalibrationHiLoPix::FillHivsLo(Float_t t,Float_t w)
+{
+  return fHivsLo.Fill(t,w) > -1;
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// The following options can be chosen:
+//
+// "": displays the fHGausHist and the fHivsLo
+// "all": executes additionally MHCalibrationPix::Draw(), with options
+//
+// The following picture shows a typical outcome of call to Draw("all"): 
+// One the left side:
+// - The distribution of the values with the Gauss fit are shown (points connected 
+//   with each other). The line is green, thus the Gauss fit has a probability higher 
+//   than 0.5%.
+// - The distribution of the positions of the maximum (abs. arrival times) 
+//   is displayed. Most of the events have an arrival time of slice 7 (==hardware:8)
+//
+// On the right side:
+// - The first plot shows the distribution of the values with the Gauss fit
+//   with error bars
+// - The second plot shows the TGraph with the events vs. time
+// - The third plot shows the fourier transform and a peak at 100 Hz.
+// - The fourth plot shows the projection of the fourier components and an exponential 
+//   fit, with the result that the observed deviation is not statistical, but signficant with a 
+//   probability smaller than 0.5%. 
+//
+//Begin_Html
+/*
+<img src="images/MHCalibrationHiLoPixDraw.gif">
+*/
+//End_Html
+//
+void MHCalibrationHiLoPix::Draw(const Option_t *opt)
+{
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+  
+  TVirtualPad *oldpad = gPad ? gPad : MH::MakeDefCanvas(this,600, 600);
+  TVirtualPad *pad    = NULL;
+
+  if (option.Contains("all"))
+  {
+      option.ReplaceAll("all","");
+      oldpad->Divide(2,1);
+      win = 2;
+      oldpad->cd(1);
+      TVirtualPad *newpad = gPad;
+      pad = newpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  else if (option.Contains("datacheck"))
+    {
+      MHCalibrationPix::Draw("events");
+      return;
+    }
+  else 
+  {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  /*
+  else
+    {
+      option.ReplaceAll("time","");
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+    }
+  */
+  if (!IsEmpty() && !IsOnlyOverflow() && !IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.GetXaxis()->SetLabelSize(0.06);
+  fHGausHist.GetYaxis()->SetLabelSize(0.07);
+  fHGausHist.GetXaxis()->SetLabelOffset(0.01);
+  fHGausHist.GetYaxis()->SetLabelOffset(0.01);
+  fHGausHist.GetXaxis()->SetTitleSize(0.065);
+  fHGausHist.GetYaxis()->SetTitleSize(0.07);
+  fHGausHist.GetXaxis()->SetTitleOffset(0.6);
+  fHGausHist.GetYaxis()->SetTitleOffset(0.6);
+  fHGausHist.Draw(); 
+  if (fFGausFit)
+  {
+      fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+      fFGausFit->Draw("same");
+  }
+
+  pad->cd(2);
+  gPad->SetTicks();
+  gStyle->SetOptFit();
+
+  fHivsLo.GetXaxis()->SetLabelSize(0.06);
+  fHivsLo.GetYaxis()->SetLabelSize(0.07);
+  fHivsLo.GetXaxis()->SetLabelOffset(0.01);
+  fHivsLo.GetYaxis()->SetLabelOffset(0.01);
+  fHivsLo.GetXaxis()->SetTitleSize(0.065);
+  fHivsLo.GetYaxis()->SetTitleSize(0.07);
+  fHivsLo.GetXaxis()->SetTitleOffset(0.6);
+  fHivsLo.GetYaxis()->SetTitleOffset(0.6);
+  fHivsLo.Draw();
+
+  if (win < 2)
+      return;
+
+  oldpad->cd(2);
+  MHCalibrationPix::Draw("fourierevents");
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationHiLoPix.h	(revision 17960)
@@ -0,0 +1,52 @@
+#ifndef MARS_MHCalibrationHiLoPix
+#define MARS_MHCalibrationHiLoPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+
+class MHCalibrationHiLoPix : public MHCalibrationPix
+{
+
+ private:
+
+  TProfile fHivsLo;        // Profile containing the high-gain vs. low-gain value
+                          
+  Int_t    fHivsLoNbins;  // Number of  bins used for the fHHivsLo 
+  Axis_t   fHivsLoFirst;  // Lower bound bin used for the fHHivsLo
+  Axis_t   fHivsLoLast;   // Upper bound bin used for the fHHivsLo
+
+public:
+
+  MHCalibrationHiLoPix(const char *name=NULL, const char *title=NULL);
+
+  void Reset();  
+  void InitBins();
+  
+  // Setters 
+  virtual void SetHivsLoNbins(const Int_t  bins )  { fHivsLoNbins = bins;  }
+  virtual void SetHivsLoFirst(const Axis_t first)  { fHivsLoFirst = first; }
+  virtual void SetHivsLoLast( const Axis_t last )  { fHivsLoLast  = last;  }
+
+  // Getters
+  TProfile       *GetHivsLo()            { return &fHivsLo;  }
+  const TProfile *GetHivsLo()      const { return &fHivsLo;  }
+
+  const Float_t  GetHivsLoP0()     const;
+  const Float_t  GetHivsLoP1()     const;
+  const Float_t  GetHivsLoProb()   const;
+
+  // Fill histos
+  Bool_t FillHivsLo(const Float_t t, const Float_t w);
+
+  // Draws
+  void Draw(Option_t *opt="");
+
+  ClassDef(MHCalibrationHiLoPix, 1)     // Base Histogram class for HiLo Pixel Calibration
+};
+
+#endif /* MARS_MHCalibrationHiLoPix */
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPix.cc	(revision 17960)
@@ -0,0 +1,239 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationPix
+//
+//  A base class for events which are believed to follow a Gaussian distribution 
+//  with time, e.g. calibration events, observables containing white noise, ...
+//
+//  MHCalibrationPix derives from MHGausEvents, thus all features of 
+//  MHGausEvents can be used by a class deriving from MHCalibrationPix
+//
+//  As an additional feature to MHGausEvents, this class offers to skip the fitting 
+//  to set mean, sigma and its errors directly from the histograms with the function 
+//  BypassFit()
+//
+//  See also: MHGausEvents
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationPix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TMath.h>
+#include <TGraph.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCalibrationPix);
+
+using namespace std;
+
+const Float_t  MHCalibrationPix::fgBlackoutLimit        = 5.;
+const Float_t  MHCalibrationPix::fgPickupLimit          = 5.;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+// Sets: 
+// - the default number for fPickupLimit           (fgPickupLimit)
+// - the default number for fBlackoutLimit         (fgBlackoutLimit)
+//
+// Initializes:
+// - all variables to 0.
+//
+MHCalibrationPix::MHCalibrationPix(const char *name, const char *title)
+{ 
+
+  fName  = name  ? name  : "MHCalibrationPix";
+  fTitle = title ? title : "Calibration histogram events";
+
+  Clear();
+  
+  SetBlackoutLimit();
+  SetPickupLimit();
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Clear(), can be overloaded.
+//
+// Sets:
+// - all other pointers to NULL
+// - all variables to 0., except fPixId to -1 
+// - all flags to kFALSE
+// 
+// - all pointers
+//
+void MHCalibrationPix::Clear(Option_t *o)
+{
+
+  MHGausEvents::Clear();
+  fSaturated         = 0;
+}
+
+void MHCalibrationPix::Reset()
+{
+  
+  MHGausEvents::Reset();
+  fSaturated = 0;
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Bypasses the Gauss fit by taking mean and RMS from the histogram
+//
+// Errors are determined in the following way:
+// MeanErr  = RMS / Sqrt(entries)
+// SigmaErr = RMS / (2.*Sqrt(entries) )
+//
+void MHCalibrationPix::BypassFit()
+{
+
+  const Stat_t entries = fHGausHist.GetEntries();
+  
+  if (entries <= 0.)
+    {
+      *fLog << warn << GetDescriptor() 
+            << ": Cannot bypass fit. Number of entries smaller or equal 0 in pixel: " << GetName() << endl;
+      return;
+    }
+  
+  fMean     = fHGausHist.GetMean();
+  fMeanErr  = fHGausHist.GetRMS() / TMath::Sqrt(entries);
+  fSigma    = fHGausHist.GetRMS() ;
+  fSigmaErr = fHGausHist.GetRMS() / TMath::Sqrt(entries) / 2.;
+}
+
+// -------------------------------------------------------------------------------
+//
+// Return the number of "blackout" events, which are events with values higher 
+// than fBlackoutLimit sigmas from the mean
+//
+//
+const Double_t MHCalibrationPix::GetBlackout() const 
+{
+  
+  if ((fMean == 0.) && (fSigma == 0.))
+    return -1.;
+
+  const Int_t first = fHGausHist.GetXaxis()->GetFirst();
+  const Int_t last  = fHGausHist.GetXaxis()->FindBin(fMean-fBlackoutLimit*fSigma);
+
+  if (first >= last)
+    return 0.;
+  
+  return fHGausHist.Integral(first, last);
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Return the number of "pickup" events, which are events with values higher 
+// than fPickupLimit sigmas from the mean
+//
+//
+const Double_t MHCalibrationPix::GetPickup() const 
+{
+  if (!IsValid())
+    return -1.;
+
+  const Int_t first = fHGausHist.GetXaxis()->FindBin(fMean+fPickupLimit*fSigma);
+  const Int_t last  = fHGausHist.GetXaxis()->GetLast();
+
+  if (first >= last)
+    return 0.;
+  
+  return fHGausHist.Integral(first, last);
+}
+
+// -----------------------------------------------------------------------------
+//
+// If flag IsGausFitOK() is set (histogram already successfully fitted), 
+// returns kTRUE
+// 
+// If both fMean and fSigma are still zero, call FitGaus() 
+// 
+// Repeats the Gauss fit in a smaller range, defined by: 
+// 
+// min = GetMean() - fBlackoutLimit * GetSigma();
+// max = GetMean() + fPickupLimit   * GetSigma();
+//
+// The fit results are retrieved and stored in class-own variables.  
+//
+// A flag IsGausFitOK() is set according to whether the fit probability 
+// is smaller or bigger than fProbLimit, whether the NDF is bigger than 
+// fNDFLimit and whether results are NaNs.
+//
+Bool_t MHCalibrationPix::RepeatFit(const Option_t *option)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  if (!IsValid())
+    return FitGaus();
+
+  //
+  // Get new fitting ranges
+  //
+  Axis_t rmin = GetMean() - fBlackoutLimit * GetSigma();
+  Axis_t rmax = GetMean() + fPickupLimit   * GetSigma();
+
+  Axis_t hmin = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetFirst());
+  Axis_t hmax = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetLast()) ;
+
+  fFGausFit->SetRange(hmin < rmin ? rmin : hmin , hmax > rmax ? rmax : hmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  fMean     = fFGausFit->GetParameter(1);
+  fSigma    = fFGausFit->GetParameter(2);
+  fMeanErr  = fFGausFit->GetParError(1) ; 
+  fSigmaErr = fFGausFit->GetParError(2) ; 
+  fProb     = fFGausFit->GetProb()      ;      
+
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 3) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  if (   !TMath::Finite( fMean     )
+      || !TMath::Finite( fMeanErr  )
+      || !TMath::Finite( fProb     )
+      || !TMath::Finite( fSigma    )
+      || !TMath::Finite( fSigmaErr )
+      || fFGausFit->GetNDF() < GetNDFLimit()
+      || fProb < GetProbLimit() )
+    return kFALSE;
+  
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+
+}
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPix.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MHCalibrationPix
+#define MARS_MHCalibrationPix
+
+#ifndef MARS_MHGausEvents
+#include "MHGausEvents.h"
+#endif
+
+class MHCalibrationPix : public MHGausEvents
+{
+private:
+
+  const static Float_t  fgBlackoutLimit; //! Default for fBlackoutLimit (now set to: 5. )
+  const static Float_t  fgPickupLimit;   //! Default for fPickupLimit   (now set to: 5. )
+  
+protected:
+
+  Float_t  fBlackoutLimit;               // Lower nr sigmas from mean until event is considered blackout
+  Int_t    fSaturated;                   // Number of events classified as saturated
+  Float_t  fPickupLimit;                 // Upper nr sigmas from mean until event is considered pickup
+
+public:
+
+  MHCalibrationPix(const char* name=NULL, const char* title=NULL);
+
+  void  Clear(Option_t *o="");
+  void  Reset();
+  
+  // Getters
+  const Double_t GetBlackout() const;
+  const Double_t GetPickup() const;
+  const Int_t    GetSaturated() const { return fSaturated;      }
+
+  // Fits
+  Bool_t RepeatFit(const Option_t *option="RQ0"); // Repeat fit within limits defined by fPickupLimit
+  void   BypassFit();                             // Take mean and RMS from the histogram
+  
+  // Setters
+  void  AddSaturated        ( const Int_t    i                   ) { fSaturated     += i;   }
+  void  SetBlackoutLimit    ( const Float_t  lim=fgBlackoutLimit ) { fBlackoutLimit  = lim; }
+  void  SetPickupLimit      ( const Float_t  lim=fgPickupLimit   ) { fPickupLimit    = lim; }
+
+  ClassDef(MHCalibrationPix, 1) // Base class for calibration events 
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPulseTimeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPulseTimeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPulseTimeCam.cc	(revision 17960)
@@ -0,0 +1,672 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationPulseTimeCam                                               
+//
+// Fills the extracted signals of MExtractedSignalCam into the MHCalibrationPix-classes 
+// MHCalibrationPulseTimeHiGainPix and MHCalibrationPulseTimeLoGainPix for every:
+//
+// - Pixel, stored in the TOrdCollection's MHCalibrationCam::fHiGainArray and 
+//   MHCalibrationCam::fLoGainArray
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageLoGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainSectors and 
+//   MHCalibrationCam::fAverageLoGainSectors
+// 
+// Every signal is taken from MExtractedSignalCam and filled into a histogram and 
+// an array, in order to perform a Fourier analysis (see MHGausEvents). 
+// The signals are moreover averaged on an event-by-event basis and written into 
+// the corresponding average pixels.
+//
+// Additionally, the (FADC slice) position of the maximum is stored in an Absolute 
+// Arrival Time histogram. This histogram serves for a rough cross-check if the 
+// signal does not lie at or outside the edges of the extraction window. 
+//
+// The PulseTime histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) or  
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted ) and 
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// Unless more than fNumHiGainSaturationLimit (default: 1%) of the overall FADC 
+// slices show saturation, the following flag is set:
+// - MCalibrationPulseTimePix::SetHiGainSaturation();
+// In that case, the calibration constants are derived from the low-gain results.
+//
+// If more than fNumLoGainSaturationLimit (default: 1%) of the overall 
+// low-gain FADC slices saturate, the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturation ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    )
+// 
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum and investigates if the projected fourier components follow an exponential 
+// distribution. In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating ) or
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun     )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MCalibrationPulseTimeCam:
+//
+// - MCalibrationPix::SetHiGainSaturation() 
+// - MCalibrationPix::SetHiGainMean()
+// - MCalibrationPix::SetHiGainMeanErr()
+// - MCalibrationPix::SetHiGainSigma()
+// - MCalibrationPix::SetHiGainSigmaErr()
+// - MCalibrationPix::SetHiGainProb()
+// - MCalibrationPix::SetHiGainNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//
+//
+// ClassVersion 2:
+// ---------------
+//   - Byte_t fSaturationLimit
+//   - Byte_t fLowerSignalLimit
+//   + UInt_t fSaturationLimit
+//   + UInt_t fLowerSignalLimit
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationPulseTimeCam.h"
+
+#include <TEnv.h>
+#include <TLine.h>
+#include <TGraph.h>
+#include <TLegend.h>
+#include <TCanvas.h>
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MArrayD.h"
+#include "MRawRunHeader.h"
+#include "MExtractedSignalCam.h"
+#include "MPedestalSubtractedEvt.h"
+
+#include "MCalibrationPix.h"
+#include "MHCalibrationPix.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MBadPixelsCam.h"
+
+ClassImp(MHCalibrationPulseTimeCam);
+
+using namespace std;
+
+const UInt_t  MHCalibrationPulseTimeCam::fgSaturationLimit   = 245;
+const UInt_t  MHCalibrationPulseTimeCam::fgLowerSignalLimit  =  85;
+const Int_t   MHCalibrationPulseTimeCam::fgNumPixelsRequired =   3;
+const Int_t   MHCalibrationPulseTimeCam::fgHiGainNbins =  20;
+const Axis_t  MHCalibrationPulseTimeCam::fgHiGainFirst =  -0.5;
+const Axis_t  MHCalibrationPulseTimeCam::fgHiGainLast  =  19.5;
+const Float_t MHCalibrationPulseTimeCam::fgProbLimit   = 0.001;
+const TString MHCalibrationPulseTimeCam::gsHistName    = "PulseTime";
+const TString MHCalibrationPulseTimeCam::gsHistTitle   = "Extracted Times";
+const TString MHCalibrationPulseTimeCam::gsHistXTitle  = "Time [FADC slices]";
+const TString MHCalibrationPulseTimeCam::gsHistYTitle  = "Nr. events";
+const TString MHCalibrationPulseTimeCam::fgReferenceFile = "mjobs/signalref.rc";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// - fNbins to fgHiGainNbins
+// - fFirst to fgHiGainFirst
+// - fLast  to fgHiGainLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fSaturationLimit to fgSaturationLimit
+// - fLowerSignalLimit to fgLowerSignalLimit
+// - fNumPixelsRequired to fgNumPixelsRequired
+//
+MHCalibrationPulseTimeCam::MHCalibrationPulseTimeCam(const char *name, const char *title)
+    : fSignalCam(NULL), fBadPixels(NULL)
+{
+
+  fName  = name  ? name  : "MHCalibrationPulseTimeCam";
+  fTitle = title ? title : "Class to fill the extracted pulse times for cosmics ";
+
+  SetBinning(fgHiGainNbins, fgHiGainFirst, fgHiGainLast);
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetReferenceFile();
+  SetLoGain(kFALSE);
+  SetOscillations(kFALSE);
+
+  SetSaturationLimit();
+  SetLowerSignalLimit();
+  SetNumPixelsRequired();
+
+  fInnerRefTime = 5.;
+  fOuterRefTime = 5.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationPulseTimeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationPulseTimeCam *cam = MParList::FindObject("MHCalibrationPulseTimeCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationPulseTimeCam::Clone(const char *) const
+{
+
+  MHCalibrationPulseTimeCam *cam = new MHCalibrationPulseTimeCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+  cam->fReferenceFile          = fReferenceFile;
+  cam->fInnerRefTime           = fInnerRefTime;
+  cam->fOuterRefTime           = fOuterRefTime;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MRawEvtData
+//
+Bool_t MHCalibrationPulseTimeCam::SetupHists(const MParList *pList)
+{
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+  {
+      *fLog << warn << GetDescriptor() << "MBadPixelsCam not found... " << endl;
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MExtractedSignalCam
+// - MCalibrationPulseTimeCam
+// - MBadPixelsCam
+//
+// Initializes the number of used FADC slices from MExtractedSignalCam 
+// into MCalibrationPulseTimeCam and test for changes in that variable
+//
+// Calls:
+// - InitHiGainArrays()
+// 
+// Sets:
+// - fSumhiarea   to nareas 
+// - fSumloarea   to nareas 
+// - fSumhisector to nsectors 
+// - fSumlosector to nsectors 
+//
+Bool_t MHCalibrationPulseTimeCam::ReInitHists(MParList *pList)
+{
+  fSignalCam = (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+  if (!fSignalCam)
+  {
+      *fLog << err << "MExtractedSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  if (!InitCams(pList,"PulseTime"))
+    return kFALSE;
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+
+  return kTRUE;
+}
+
+void MHCalibrationPulseTimeCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+
+  const Int_t samples = fRunHeader->GetNumSamples();
+  SetBinning(samples, -0.5, samples-0.5);
+
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationPix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                 Form("%s High Gain Pixel %4d",fHistTitle.Data(),i)),i);
+
+        MHCalibrationPix &pix = (*this)[i];
+        pix.SetBinning(fNbins, fFirst, fLast);
+
+        InitHists(pix, (*fBadPixels)[i], i);
+
+	if (fCam)
+	  (*fCam)[i].SetPixId(i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHCalibrationPix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                        Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+
+        MHCalibrationPix &pix = GetAverageHiGainArea(j);
+        pix.SetBinning(fNbins, fFirst, fLast);
+
+        InitHists(pix, fCam->GetAverageBadArea(j), j);
+      }
+  }
+
+  if (fAverageHiGainSectors->GetSize()==0)
+    {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+          fAverageHiGainSectors->AddAt(new MHCalibrationPix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                            Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+          MHCalibrationPix &pix = GetAverageHiGainSector(j);
+          pix.SetBinning(fNbins, fFirst, fLast);
+
+          InitHists(pix, fCam->GetAverageBadSector(j), j);
+      }
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalCam:
+// - first used LoGain FADC slice
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Fill PulseTimes histograms (MHGausEvents::FillHistAndArray()) with:
+// - MExtractedSignalPix::GetExtractedSignalHiGain();
+// - MExtractedSignalPix::GetExtractedSignalLoGain();
+//
+Bool_t MHCalibrationPulseTimeCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+    MPedestalSubtractedEvt *evt = (MPedestalSubtractedEvt*)par;
+    if (!evt)
+    {
+        *fLog << err << "No argument in MHCalibrationPulseTimeCam::Fill... abort." << endl;
+        return kFALSE;
+    }
+
+    const UInt_t nareas   = fGeom->GetNumAreas();
+    const UInt_t nsectors = fGeom->GetNumSectors();
+
+    MArrayD sumarea(nareas);
+    MArrayD sumsector(nsectors);
+
+    fAverageAreaNum.Reset();
+    fAverageSectorNum.Reset();
+
+    const Int_t npix = evt->GetNumPixels();
+    for (int idx=0; idx<npix; idx++)
+    {
+        if (fBadPixels)
+            if ((*fBadPixels)[idx].IsUnsuitable())
+                continue;
+
+        // Check for saturation
+        if (evt->GetSaturation(idx, fSaturationLimit*fRunHeader->GetScale())>0)
+            continue;
+
+        // Get position of maximum
+        Float_t max;
+        const Int_t pos = evt->GetMax(idx, fSignalCam->GetFirstUsedSliceHiGain(),
+                                      fSignalCam->GetLastUsedSliceHiGain(), max);
+
+        if (max<fLowerSignalLimit)
+            continue;
+
+        const Int_t maxpos = pos-1;
+
+        (*this)[idx].FillHist(maxpos);
+
+        const Int_t aidx   = (*fGeom)[idx].GetAidx();
+        const Int_t sector = (*fGeom)[idx].GetSector();
+
+        sumarea[aidx]     += maxpos;
+        sumsector[sector] += maxpos;
+
+        fAverageAreaNum[aidx]++;
+        fAverageSectorNum[sector]++;
+    }
+
+    for (UInt_t j=0; j<nareas; j++)
+    {
+        if (fAverageAreaNum[j]<fNumPixelsRequired)
+            continue;
+
+        sumarea[j] /= fAverageAreaNum[j];
+
+        if (IsOscillations())
+            GetAverageHiGainArea(j).FillHistAndArray(sumarea[j]);
+        else
+            GetAverageHiGainArea(j).FillHist(sumarea[j]);
+    }
+
+    for (UInt_t j=0; j<nsectors; j++)
+    {
+        if (fAverageSectorNum[j]<fNumPixelsRequired)
+            continue;
+
+        sumsector[j] /= fAverageSectorNum[j];
+
+        if (IsOscillations())
+            GetAverageHiGainSector(j).FillHistAndArray(sumsector[j]);
+        else
+            GetAverageHiGainSector(j).FillHist(sumsector[j]);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Returns if the pixel is excluded.
+// 2) Tests saturation. In case yes, set the flag: MCalibrationPix::SetHiGainSaturation()
+//    or the flag: MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturated )
+// 3) Store the absolute arrival times in the MCalibrationPulseTimePix's. If flag 
+//    MCalibrationPix::IsHiGainSaturation() is set, the Low-Gain arrival times are stored, 
+//    otherwise the Hi-Gain ones.
+// 4) Calls to MHCalibrationCam::FitHiGainArrays() and MCalibrationCam::FitLoGainArrays() 
+//    with the flags:
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating )
+//
+Bool_t MHCalibrationPulseTimeCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  //
+  // Perform the fitting for the High Gain (done in MHCalibrationCam)
+  // 
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+
+      MHCalibrationPix &hist = (*this)[i];
+      if (hist.IsExcluded())
+        continue;
+
+      CalcHists(hist, (*fCam)[i]);
+    }
+
+  if (!IsAverageing())
+    return kTRUE;
+
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+      CalcHists(GetAverageHiGainArea(j), fCam->GetAverageArea(j));
+
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+      CalcHists(GetAverageHiGainSector(j), fCam->GetAverageSector(j));
+
+  return kTRUE;
+}
+
+void MHCalibrationPulseTimeCam::CalcHists(MHCalibrationPix &hist, MCalibrationPix &pix) const
+{
+
+  if (hist.IsEmpty())
+  {
+      *fLog << warn << hist.GetName() << ": Histogram empty." << endl;
+      return;
+  }
+  if (hist.IsOnlyOverflow())
+  {
+      *fLog << warn << hist.GetName() << ": Histogram contains only overflows." << endl;
+      return;
+  }
+  if (hist.IsOnlyUnderflow())
+  {
+      *fLog << warn << hist.GetName() << ": Histogram contains only underflows." << endl;
+      return;
+  }
+
+  hist.BypassFit();
+
+  pix.SetHiGainMean       ( hist.GetMean()      );
+  pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+  pix.SetHiGainRms        ( hist.GetHistRms()   );
+  pix.SetHiGainSigma      ( hist.GetSigma()     );
+  pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << GetDescriptor() << ": ID " << GetName() 
+            << " "<<pix.GetPixId()
+            << " Mean: "         << hist.GetMean    ()
+            << " MeanErr: "      << hist.GetMeanErr ()
+            << " MeanSigma: "    << hist.GetSigma   ()
+            << " MeanSigmaErr: " << hist.GetSigmaErr()
+            << " Prob: "         << hist.GetProb    ()
+            << endl;
+    }
+}
+
+Double_t MHCalibrationPulseTimeCam::GetNumEvents() const
+{
+    return GetAverageAreas()>0 ? GetAverageHiGainArea(0).GetEntries() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationPulseTimeCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationPulseTimeCam::Draw(const Option_t *opt)
+{
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TString option(opt);
+  option.ToLower();
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+  pad->SetBorderMode(0);
+  pad->Divide(1,nareas, 1e-10, 1e-10);
+
+  //
+  // Loop over inner and outer pixels
+  //
+  for (Int_t i=0; i<nareas;i++)
+     {
+       pad->cd(i+1);
+
+       MHCalibrationPix &hipix = GetAverageHiGainArea(i);
+       DrawDataCheckPixel(hipix,i ? fOuterRefTime : fInnerRefTime);
+     }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Draw the average pixel for the datacheck:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationPulseTimeCam::DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline)
+{
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+
+    TH1F *hist = pix.GetHGausHist();
+
+    //
+    // set the labels bigger
+    //
+    TAxis *xaxe = hist->GetXaxis();
+    TAxis *yaxe = hist->GetYaxis();
+    xaxe->CenterTitle();
+    yaxe->CenterTitle();
+    xaxe->SetTitleSize(0.06);
+    yaxe->SetTitleSize(0.076);
+    xaxe->SetTitleOffset(0.6);
+    yaxe->SetTitleOffset(0.65);
+    xaxe->SetLabelSize(0.06);
+    yaxe->SetLabelSize(0.06);
+    xaxe->SetTitle(hist->GetXaxis()->GetTitle());
+    yaxe->SetTitle(hist->GetYaxis()->GetTitle());
+    xaxe->SetRange(hist->GetMaximumBin()-30, hist->GetMaximumBin()+30);
+
+    hist->Draw();
+
+    DisplayRefLines(hist, refline);
+}
+
+void  MHCalibrationPulseTimeCam::DisplayRefLines(const TH1F *hist, const Float_t refline) const
+{
+    TLine *line = new TLine(refline, 0, refline, hist->GetMaximum());
+    line->SetLineColor(106);
+    line->SetLineStyle(2);
+    line->SetLineWidth(3);
+    line->SetBit(kCanDelete);
+    line->Draw();
+
+    TLegend *leg = new TLegend(0.8,0.35,0.99,0.65);
+    leg->AddEntry(line, "Reference", "l");
+    leg->SetBit(kCanDelete);
+    leg->Draw();
+}
+
+Int_t MHCalibrationPulseTimeCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Int_t rc = MHCalibrationCam::ReadEnv(env,prefix,print);
+  if (rc==kERROR)
+      return kERROR;
+
+  if (IsEnvDefined(env, prefix, "SaturationLimit", print))
+    {
+      SetSaturationLimit(GetEnvValue(env, prefix, "SaturationLimit", (Int_t)fSaturationLimit));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "LowerSignalLimit", print))
+    {
+      SetLowerSignalLimit(GetEnvValue(env, prefix, "LowerSignalLimit", (Int_t)fLowerSignalLimit));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "NumPixelsRequired", print))
+    {
+      SetNumPixelsRequired(GetEnvValue(env,prefix,"NumPixelsRequired",fNumPixelsRequired));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "ReferenceFile", print))
+    {
+      SetReferenceFile(GetEnvValue(env,prefix,"ReferenceFile",fReferenceFile.Data()));
+      rc = kTRUE;
+    }
+
+  TEnv refenv(fReferenceFile);
+
+  fInnerRefTime = refenv.GetValue("InnerRefTime",fInnerRefTime);
+  fOuterRefTime = refenv.GetValue("OuterRefTime",fOuterRefTime);
+
+  return rc;
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPulseTimeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPulseTimeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationPulseTimeCam.h	(revision 17960)
@@ -0,0 +1,84 @@
+#ifndef MARS_MHCalibrationPulseTimeCam
+#define MARS_MHCalibrationPulseTimeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+class TH1F;
+class MRawEvtData;
+class MExtractedSignalCam;
+class MHCalibrationChargePix;
+
+class MHCalibrationPulseTimeCam : public MHCalibrationCam
+{
+private:
+
+  static const UInt_t  fgSaturationLimit;      //! Default for fSaturationLimit (now set to: 245)
+  static const UInt_t  fgLowerSignalLimit;     //! Default for fLowerSignalLimit
+  static const Int_t   fgNumPixelsRequired;    //! Default for fNumPixelsRequired
+
+  static const Int_t   fgHiGainNbins;          //! Nr. bins of HiGain Histograms  (now set to:  550  )
+  static const Axis_t  fgHiGainFirst;          //! First Bin of HiGain Histograms (now set to: -100.5)
+  static const Axis_t  fgHiGainLast;           //! Last Bin of HiGain Histograms  (now set to:  999.5)
+  static const Float_t fgProbLimit;            //! The default for fProbLimit    (now set to: 0.00001)
+
+  static const TString fgReferenceFile;        //! default for fReferenceFile ("mjobs/calibrationref.rc")
+
+  static const TString gsHistName;             //! Default Histogram names
+  static const TString gsHistTitle;            //! Default Histogram titles
+  static const TString gsHistXTitle;           //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;           //! Default Histogram y-axis titles
+
+  UInt_t  fSaturationLimit;                    // Highest FADC slice value until being declared saturated
+  UInt_t  fLowerSignalLimit;                   // Lower signal limit for pulse time extraction
+  Int_t   fNumPixelsRequired;                  // Minimum Number of pixels required for averageing
+
+  TString fReferenceFile;                      // File name containing the reference values
+
+  Float_t fInnerRefTime;                       // The reference mean arrival time inner pixels
+  Float_t fOuterRefTime;                       // The reference mean arrival time outer pixels
+
+  MExtractedSignalCam *fSignalCam;             //! Signal cam for extraction range
+  MBadPixelsCam *fBadPixels;                   //! Bad Pixels
+  
+  void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+
+  Bool_t SetupHists(const MParList *pList);
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+
+  Bool_t FinalizeHists();
+
+  void   DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline);
+  void   DisplayRefLines   ( const TH1F *hist,           const Float_t refline) const;
+  void   CalcHists         (MHCalibrationPix &hist, MCalibrationPix &pix) const;
+
+  Int_t ReadEnv        ( const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MHCalibrationPulseTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationPulseTimeCam() {}
+
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  // Draw
+  void   Draw(const Option_t *opt);
+
+  void SetReferenceFile    ( const TString ref=fgReferenceFile     ) { fReferenceFile     = ref; }
+  void SetSaturationLimit  ( const UInt_t  lim=fgSaturationLimit   ) { fSaturationLimit   = lim; }
+  void SetLowerSignalLimit ( const UInt_t  lim=fgLowerSignalLimit  ) { fLowerSignalLimit  = lim; }
+  void SetNumPixelsRequired( const Byte_t  lim=fgNumPixelsRequired ) { fNumPixelsRequired = lim; }
+
+  Double_t GetNumEvents() const;
+
+
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const { return kTRUE; }
+  void   DrawPixelContent( Int_t num )  const;    
+
+  ClassDef(MHCalibrationPulseTimeCam, 2)	// Histogram class for Pulse Time Checks
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationRelTimeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationRelTimeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationRelTimeCam.cc	(revision 17960)
@@ -0,0 +1,861 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!              
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHCalibrationRelTimeCam
+//
+// Fills the extracted relative arrival times of MArrivalTimeCam into
+// the MHCalibrationPix-classes MHCalibrationPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray
+//   or MHCalibrationCam::fHiGainArray, respectively, depending if
+//   MArrivalTimePix::IsLoGainUsed() is set.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors
+//   and MHCalibrationCam::fAverageHiGainSectors
+//
+// Every relative time is calculated as the difference between the individual
+// pixel arrival time and the one of pixel 1 (hardware number: 2).
+// The relative times are filled into a histogram and an array, in order to perform
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors
+// and the fit probability are extracted. If none of these values are NaN's and
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%),
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean
+// - MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+//   In case this does not make the fit valid, the histogram means and RMS's are
+//   taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kRelTimeNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    )
+//
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup)
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the
+// projected fourier components follow an exponential distribution.
+// In case that the probability of the exponential fit is less than
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kRelTimeOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MCalibrationRelTimeCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationRelTimeCam.h"
+#include "MHCalibrationPix.h"
+
+#include <TEnv.h>
+#include <TMath.h>
+
+#include <TOrdCollection.h>
+
+#include <TStyle.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TCanvas.h>
+
+#include <TF1.h>
+#include <TGraph.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimePix.h"
+#include "MCalibrationPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MHCalibrationRelTimeCam);
+
+using namespace std;
+
+const Float_t MHCalibrationRelTimeCam::fgNumHiGainSaturationLimit = 0.25;
+//const UInt_t  MHCalibrationRelTimeCam::fgReferencePixel = 1;
+const Int_t   MHCalibrationRelTimeCam::fgNbins      = 400;
+const Axis_t  MHCalibrationRelTimeCam::fgFirst      = -9.975;
+const Axis_t  MHCalibrationRelTimeCam::fgLast       = 10.025;
+const Float_t MHCalibrationRelTimeCam::fgProbLimit  = 0.0;
+const TString MHCalibrationRelTimeCam::gsHistName   = "RelTime";
+const TString MHCalibrationRelTimeCam::gsHistTitle  = "Arr. Times";
+const TString MHCalibrationRelTimeCam::gsHistXTitle = "Arr. Time [FADC slices]";
+const TString MHCalibrationRelTimeCam::gsHistYTitle = "Nr. events";
+const TString MHCalibrationRelTimeCam::fgReferenceFile = "mjobs/calibrationref.rc";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor.
+//
+// Sets: 
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHCalibrationRelTimeCam::MHCalibrationRelTimeCam(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MHCalibrationRelTimeCam";
+  fTitle = title ? title : "Histogram class for the relative time calibration of the camera";
+
+  SetNumHiGainSaturationLimit(fgNumHiGainSaturationLimit);
+
+//  SetReferencePixel();
+
+  SetBinning(fgNbins, fgFirst, fgLast);
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetReferenceFile();
+
+  fInnerRefTime  = 2.95;   
+  fOuterRefTime  = 3.6;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationRelTimeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationRelTimeCam *cam = MParList::FindObject("MHCalibrationRelTimeCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationRelTimeCam::Clone(const char *) const
+{
+
+  MHCalibrationRelTimeCam *cam = new MHCalibrationRelTimeCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+
+  cam->fReferenceFile          = fReferenceFile;
+  cam->fInnerRefTime           = fInnerRefTime;
+  cam->fOuterRefTime           = fOuterRefTime;
+
+  //
+  // Copy the MArrays
+  //
+  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
+  cam->fAverageAreaRelSigmaVar = fAverageAreaRelSigmaVar;
+  cam->fAverageAreaSat         = fAverageAreaSat;
+  cam->fAverageAreaSigma       = fAverageAreaSigma;
+  cam->fAverageAreaSigmaVar    = fAverageAreaSigmaVar;
+  cam->fAverageAreaNum         = fAverageAreaNum;
+  cam->fAverageSectorNum       = fAverageSectorNum;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  if (IsLoGain())
+    {
+      
+      const Int_t navlo = fAverageLoGainAreas->GetSize();
+      for (int i=0; i<navlo; i++)
+        cam->fAverageLoGainAreas->AddAt(GetAverageLoGainArea(i).Clone(),i);
+
+    }
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MCalibrationRelTimeCam
+//
+// Searches pointer to:
+// - MArrivalTimeCam
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// - MHCalibrationCam::InitLoGainArrays()
+// 
+// Sets:
+// - fSumareahi   to nareas
+// - fSumarealo   to nareas
+// - fSumsectorhi to nareas
+// - fSumsectorlo to nareas
+// - fNumareahi   to nareas
+// - fNumarealo   to nareas
+// - fNumsectorhi to nareas
+// - fNumsectorlo to nareas
+//
+Bool_t MHCalibrationRelTimeCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,"RelTime"))
+    return kFALSE;
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fSumareahi  .Set(nareas); 
+  fSumarealo  .Set(nareas);
+  fSumsectorhi.Set(nsectors); 
+  fSumsectorlo.Set(nsectors);
+  fNumareahi  .Set(nareas); 
+  fNumarealo  .Set(nareas);
+  fNumsectorhi.Set(nsectors); 
+  fNumsectorlo.Set(nsectors);
+
+  return kTRUE;
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MArrivalTimeCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain or LoGain histograms (MHGausEvents::FillHistAndArray()), respectively
+// depending on MArrivalTimePix::IsLoGainUsed(), with:
+// - MArrivalTimePix::GetArrivalTime(pixid) - MArrivalTimePix::GetArrivalTime(1);
+//   (i.e. the time difference between pixel i and pixel 1 (hardware number: 2) )
+//
+Bool_t MHCalibrationRelTimeCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MArrivalTimeCam *arrtime = (MArrivalTimeCam*)par;
+  if (!arrtime)
+    {
+      gLog << err << "No argument in MArrivalTime::Fill... abort." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  fSumareahi  .Reset();
+  fSumarealo  .Reset();
+  fSumsectorhi.Reset();
+  fSumsectorlo.Reset();
+  fNumareahi  .Reset();
+  fNumarealo  .Reset();
+  fNumsectorhi.Reset();
+  fNumsectorlo.Reset();
+
+  TArrayF arr(npixels);
+  Int_t n = 0;
+  for (Int_t i=0; i<npixels; i++)
+  {
+      if ((*fGeom)[i].GetAidx()>0)
+          continue;
+
+      const MArrivalTimePix &pix = (*arrtime)[i];
+      if (pix.IsHiGainValid() && !pix.IsHiGainSaturated())
+          arr[n++] = pix.GetArrivalTimeHiGain();
+  }
+
+  const Float_t reftime = TMath::Median(n, arr.GetArray());
+
+  for (Int_t i=0; i<npixels; i++)
+  {
+      MHCalibrationPix &histhi = (*this)[i];
+      if (histhi.IsExcluded())
+          continue;
+
+      const MArrivalTimePix &pix = (*arrtime)[i];
+
+      // If hi-gain arrival time has been extracted successfully
+      // fill hi-gain histograms and arrays
+      if (pix.IsHiGainValid() && !pix.IsHiGainSaturated())
+      {
+          const Float_t time = pix.GetArrivalTimeHiGain();
+
+          if (IsOscillations())
+              histhi.FillHistAndArray(time-reftime);
+          else
+              histhi.FillHist(time-reftime);
+
+          const Int_t aidx   = (*fGeom)[i].GetAidx();
+          const Int_t sector = (*fGeom)[i].GetSector();
+
+          fSumareahi  [aidx]   += time;
+          fNumareahi  [aidx]   ++;
+          fSumsectorhi[sector] += time;
+          fNumsectorhi[sector] ++;
+      }
+
+      if (!pix.IsHiGainSaturated())
+          continue;
+
+      histhi.AddSaturated(1);
+/*
+      // If lo-gain arrival time has been extracted successfully,
+      // the hi-gain has saturated and the lo-gain is switched on
+      // fill hi-gain histograms and arrays
+      if (pix.IsLoGainValid() && IsLoGain())
+      {
+          const Float_t time = pix.GetArrivalTimeLoGain();
+
+          // FIXME: We need the reference time of the lo-gains!
+
+          MHCalibrationPix &histlo = (*this)(i);
+          if (IsOscillations())
+              histlo.FillHistAndArray(time-reftime);
+          else
+              histlo.FillHist(time-reftime);
+
+          fSumarealo  [aidx]   += time;
+          fNumarealo  [aidx]   ++;
+          fSumsectorlo[sector] += time;
+          fNumsectorlo[sector] ++;
+      }*/
+  }
+
+  for (Int_t j=0; j<nareas; j++)
+  {
+      if (fNumareahi[j]>0)
+      {
+          MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+          if (IsOscillations())
+              histhi.FillHistAndArray(fSumareahi[j]/fNumareahi[j]);
+          else
+              histhi.FillHist(fSumareahi[j]/fNumareahi[j]);
+      }
+
+      if (IsLoGain() && fNumarealo[j]>0)
+      {
+          MHCalibrationPix &histlo = GetAverageLoGainArea(j);
+          if (IsOscillations())
+              histlo.FillHistAndArray(fSumarealo[j]/fNumarealo[j]);
+          else
+              histlo.FillHist(fSumarealo[j]/fNumarealo[j]);
+      }
+  }
+
+  for (Int_t j=0; j<nsectors; j++)
+  {
+      if (fNumsectorhi[j]>0)
+      {
+          MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+          if (IsOscillations())
+              histhi.FillHistAndArray(fSumsectorhi[j]/fNumsectorhi[j]);
+          else
+              histhi.FillHist(fSumsectorhi[j]/fNumsectorhi[j]);
+      }
+
+      if (IsLoGain() && fNumsectorlo[j]>0)
+      {
+          MHCalibrationPix &histlo = GetAverageLoGainSector(j);
+          if (IsOscillations())
+              histlo.FillHistAndArray(fSumsectorlo[j]/fNumsectorlo[j]);
+          else
+              histlo.FillHist(fSumsectorlo[j]/fNumsectorlo[j]);
+      }
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with flags:
+//   MBadPixelsPix::kRelTimeNotFitted and MBadPixelsPix::kRelTimeOscillating
+// - MHCalibrationCam::FitLoGainArrays() with flags:
+//   MBadPixelsPix::kRelTimeNotFitted and MBadPixelsPix::kRelTimeOscillating
+// 
+Bool_t MHCalibrationRelTimeCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  const Int_t nsectors = fAverageHiGainSectors->GetSize();
+
+  TArrayI satarea(nareas);
+  TArrayI satsect(nsectors);
+  fNumareahi  .Reset(); 
+  fNumsectorhi.Reset(); 
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &histhi = (*this)[i];
+
+      if (histhi.IsExcluded())
+        continue;
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      fNumareahi[aidx]++;
+      fNumsectorhi[sector]++;
+
+      //
+      // Check saturation
+      // 
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*fCam)[i] ;
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          histhi.SetExcluded();
+          satarea[aidx]++;
+          satsect[sector]++;
+        }
+      else
+        if (IsLoGain())
+          (*this)(i).SetExcluded();
+
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(histhi);
+      if (IsLoGain())
+        CheckOverflow((*this)(i));
+
+    }
+
+  for (Int_t j=0; j<nareas; j++)
+    {
+
+      MHCalibrationPix     &histhi = GetAverageHiGainArea(j);
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)fCam->GetAverageArea(j);
+
+      if (satarea[j] > 0.5*fNumareahi[j])
+        {
+          pix.SetHiGainSaturation();
+          histhi.SetExcluded();
+        }
+      else
+        if (IsLoGain())
+          GetAverageLoGainArea(j).SetExcluded();
+
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(histhi);
+      if (IsLoGain())
+        CheckOverflow(GetAverageLoGainArea(j));
+   }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);      
+
+      if (satsect[j] > 0.5*fNumsectorhi[j])
+        {
+          MCalibrationRelTimePix  &pix = (MCalibrationRelTimePix&)fCam->GetAverageSector(j) ;
+          pix.SetHiGainSaturation();
+          histhi.SetExcluded();
+        }
+      else
+        if (IsLoGain())        
+          GetAverageLoGainSector(j).SetExcluded();
+
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(histhi);
+      if (IsLoGain())
+        CheckOverflow(GetAverageLoGainSector(j));
+    }
+
+  FitHiGainArrays(*fCam, *fBadPixels,
+                  MBadPixelsPix::kRelTimeNotFitted,
+                  MBadPixelsPix::kRelTimeOscillating);
+
+  if (IsLoGain())
+    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 in FADC slices (MHGausEvents::GetMean()
+// 1: Error  Mean  Relative Arrival Time in FADC slices (MHGausEvents::GetMeanErr()
+// 2: Sigma fitted Relative Arrival Time in FADC slices (MHGausEvents::GetSigma()
+// 3: Error Sigma  Relative Arrival Time in FADC slices (MHGausEvents::GetSigmaErr()
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit  (MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                    (MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK            (MHGausEvents::IsFourierSpectrumOK())
+//
+Bool_t MHCalibrationRelTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pix = (*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      val = pix.GetMean();
+      break;
+    case 1:
+      val = pix.GetMeanErr();
+      break;
+    case 2:
+      val = pix.GetSigma();
+      break;
+    case 3:
+      val = pix.GetSigmaErr();
+      break;
+    case 4:
+      val = pix.GetProb();
+      break;
+    case 5:
+      if (!pix.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pix.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationRelTimeCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationRelTimeCam::Draw(const Option_t *opt)
+{
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TString option(opt);
+  option.ToLower();
+
+  if (!option.Contains("datacheck"))
+    {
+      MHCalibrationCam::Draw(opt);
+      return;
+    }
+
+  // 
+  // From here on , the datacheck - Draw
+  //
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+  pad->Divide(1,nareas);
+
+  //
+  // Loop over inner and outer pixels
+  //  
+  for (Int_t i=0; i<nareas;i++) 
+     {
+       
+       pad->cd(i+1);
+       
+       MHCalibrationPix &hipix = GetAverageHiGainArea(i);
+       //
+       // Ask for Hi-Gain saturation
+       //
+       if (hipix.IsExcluded() && IsLoGain())
+        {
+           MHCalibrationPix &lopix = GetAverageLoGainArea(i);
+           DrawDataCheckPixel(lopix,i ? fOuterRefTime+1.5 : fInnerRefTime+1.5);
+         }
+       else
+         DrawDataCheckPixel(hipix,i ? fOuterRefTime : fInnerRefTime);
+    }      
+}
+
+void MHCalibrationRelTimeCam::CheckOverflow( MHCalibrationPix &pix ) const
+{
+    if (pix.IsExcluded())
+        return;
+
+    const TH1F &hist = *pix.GetHGausHist();
+
+    const Int_t   n   = hist.GetNbinsX();
+    const Float_t max = fOverflowLimit*hist.GetEntries();
+
+    const Stat_t overflow = hist.GetBinContent(n+1);
+    if (overflow > max)
+    {
+        *fLog << warn << overflow << " overflows above " << hist.GetBinLowEdge(n);
+        *fLog << " in " << pix.GetName() << " (w/o saturation!) " << endl;
+    }
+  
+    const Stat_t underflow = hist.GetBinContent(0);
+    if (underflow > max)
+    {
+        *fLog << warn << underflow << " underflows below " << hist.GetBinLowEdge(1);
+        *fLog << " in " << pix.GetName() << " (w/o saturation!) " << endl;
+    }
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Draw the average pixel for the datacheck:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationRelTimeCam::DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline)
+{
+    if (pix.IsEmpty())
+        return;
+
+    TVirtualPad *pad = gPad;
+    pad->Divide(1,2, 1e-10, 1e-10);
+    pad->cd(1);
+
+    gPad->SetBorderMode(0);
+
+    gPad->SetTicks();
+    if (!pix.IsEmpty() && !pix.IsOnlyOverflow() && !pix.IsOnlyUnderflow())
+        gPad->SetLogy();
+
+    TH1F *hist = pix.GetHGausHist();
+  
+    //
+    // set the labels bigger
+    //
+    TAxis *xaxe = hist->GetXaxis();
+    TAxis *yaxe = hist->GetYaxis();
+    xaxe->CenterTitle();
+    yaxe->CenterTitle();
+    xaxe->SetTitleSize(0.07);
+    yaxe->SetTitleSize(0.07);
+    xaxe->SetTitleOffset(0.65);
+    yaxe->SetTitleOffset(0.55);
+    xaxe->SetLabelSize(0.06);
+    yaxe->SetLabelSize(0.06);
+    xaxe->SetTitle(hist->GetXaxis()->GetTitle());
+    yaxe->SetTitle(hist->GetYaxis()->GetTitle());
+    xaxe->SetRange(hist->GetMaximumBin()-1500, hist->GetMaximumBin()+1500);
+
+    hist->Draw();
+
+    gStyle->SetOptFit();
+
+    TF1 *fit = pix.GetFGausFit();
+
+    if (fit)
+    {
+        switch (fColor)
+        {
+        case MCalibrationCam::kGREEN:
+            fit->SetLineColor(kGreen);
+            break;
+        case MCalibrationCam::kBLUE:
+            fit->SetLineColor(kBlue);
+            break;
+        case MCalibrationCam::kUV:
+            fit->SetLineColor(106);
+            break;
+        case MCalibrationCam::kCT1:
+            fit->SetLineColor(006);
+            break;
+        default:
+            fit->SetLineColor(kRed);
+        }
+        fit->Draw("same");
+    }
+
+    DisplayRefLines(hist, refline);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+
+    pix.CreateGraphEvents();
+    TGraph *gr = pix.GetGraphEvents();
+    if (gr)
+    {
+        TH1F *null2 = gr->GetHistogram();
+
+        null2->SetMinimum(pix.GetMean()-10.*pix.GetSigma());
+        null2->SetMaximum(pix.GetMean()+10.*pix.GetSigma());
+
+        //
+        // set the labels bigger
+        //
+        TAxis *xaxe2 = null2->GetXaxis();
+        TAxis *yaxe2 = null2->GetYaxis();
+        xaxe2->CenterTitle();
+        yaxe2->CenterTitle();
+        xaxe2->SetTitleSize(0.07);
+        yaxe2->SetTitleSize(0.07);
+        xaxe2->SetTitleOffset(0.65);
+        yaxe2->SetTitleOffset(0.55);
+        xaxe2->SetLabelSize(0.06);
+        yaxe2->SetLabelSize(0.06);
+        xaxe2->SetRangeUser(0.,pix.GetEvents()->GetSize()/pix.GetEventFrequency());
+    }
+
+    pix.DrawEvents();
+}
+
+void  MHCalibrationRelTimeCam::DisplayRefLines(const TH1F *hist, const Float_t refline) const
+{
+    TLine *line = new TLine(refline, 0, refline, hist->GetMaximum());
+    line->SetLineColor(kGreen);
+    line->SetLineStyle(2);
+    line->SetLineWidth(3);
+    line->SetBit(kCanDelete);
+    line->Draw();
+
+    TLegend *leg = new TLegend(0.75,0.01,0.99,0.3);
+    leg->SetBit(kCanDelete);
+    leg->AddEntry(line, "Trigger Calibration", "l");
+    leg->Draw();
+}
+
+Int_t MHCalibrationRelTimeCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "ReferenceFile", print))
+    {
+        SetReferenceFile(GetEnvValue(env, prefix, "ReferenceFile", fReferenceFile.Data()));
+        rc = kTRUE;
+    }
+
+    TEnv refenv(fReferenceFile);
+
+    fInnerRefTime = refenv.GetValue("InnerRefTime", fInnerRefTime);
+    fOuterRefTime = refenv.GetValue("OuterRefTime", fOuterRefTime);
+
+    return MHCalibrationCam::ReadEnv(env,prefix,print) ? kTRUE : rc;
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationRelTimeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationRelTimeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationRelTimeCam.h	(revision 17960)
@@ -0,0 +1,81 @@
+#ifndef MARS_MHCalibrationRelTimeCam
+#define MARS_MHCalibrationRelTimeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TH1F;
+class MGeomCam;
+class MHCalibrationRelTimeCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Float_t fgNumHiGainSaturationLimit;   //! The default for fNumHiGainSaturationLimit (now at: 0.25)
+  static const Int_t   fgNbins;                      //! Default number of bins        (now set to: 900   )
+  static const Axis_t  fgFirst;                      //! Default lower histogram limit (now set to: -13.5 )
+  static const Axis_t  fgLast;                       //! Default upper histogram limit (now set to:  13.5 )
+  static const Float_t fgProbLimit;                  //! The default for fProbLimit    (now set to: 0.0)  
+  
+  static const TString gsHistName;                   //! Default Histogram names
+  static const TString gsHistTitle;                  //! Default Histogram titles
+  static const TString gsHistXTitle;                 //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;                 //! Default Histogram y-axis titles
+  
+  static const TString fgReferenceFile;              //! default for fReferenceFile ("mjobs/calibrationref.rc")
+
+  Float_t fInnerRefTime;                             // The reference mean arrival time inner pixels
+  Float_t fOuterRefTime;                             // The reference mean arrival time outer pixels
+
+  TString  fReferenceFile;                           // File name containing the reference values
+
+  MArrayD fSumareahi  ;                              //
+  MArrayD fSumarealo  ;                              //
+  MArrayD fSumsectorhi;                              //
+  MArrayD fSumsectorlo;                              //
+  MArrayI fNumareahi  ;                              //
+  MArrayI fNumarealo  ;                              //
+  MArrayI fNumsectorhi;                              //
+  MArrayI fNumsectorlo;                              //
+
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  void   FinalizeBadPixels();
+
+  void   CheckOverflow(MHCalibrationPix &pix) const;
+  void   DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline);
+  void   DisplayRefLines( const TH1F *hist, const Float_t refline) const;
+
+  Int_t  ReadEnv ( const TEnv &env, TString prefix, Bool_t print );
+  
+public:
+
+  MHCalibrationRelTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationRelTimeCam() {}
+
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  // Setters
+  void  SetReferenceFile ( const TString ref=fgReferenceFile ) { fReferenceFile  = ref; }
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  // Draw
+  void Draw(const Option_t *opt);
+
+  ClassDef(MHCalibrationRelTimeCam, 1)	// Histogram class for Relative Time Camera Calibration
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestCam.cc	(revision 17960)
@@ -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): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!              
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                        
+// MHCalibrationTestCam                                                
+//                                                                        
+// Fills the calibrated signal from an MSignalCam into 
+// MHCalibrationPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray  
+//   or MHCalibrationCam::fHiGainArray, respectively.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors 
+//   and MHCalibrationCam::fAverageHiGainSectors 
+//
+// The signals are filled into a histogram and an array, in order to perform 
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an 
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the 
+// projected fourier components follow an exponential distribution. 
+// In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into an MCalibrationCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationTestCam.h"
+
+#include "MHCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MHCalibrationTestCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationTestCam::fgNbins    = 1000;
+const Axis_t  MHCalibrationTestCam::fgFirst    = -1.;
+const Axis_t  MHCalibrationTestCam::fgLast     = 1999.;
+const Float_t MHCalibrationTestCam::fgProbLimit  = 0.00000001;
+const TString MHCalibrationTestCam::gsHistName   = "Test";
+const TString MHCalibrationTestCam::gsHistTitle  = "Calibrated Calibration Signals";  
+const TString MHCalibrationTestCam::gsHistXTitle = "Nr. Photons";
+const TString MHCalibrationTestCam::gsHistYTitle = "Nr. events";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHCalibrationTestCam::MHCalibrationTestCam(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MHCalibrationTestCam";
+  fTitle = title ? title : "Histogram class for testing the calibration";
+  
+  SetBinning(fgNbins, fgFirst, fgLast);
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetLoGain(kFALSE);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MSignalCam
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// 
+// Sets: 
+// - SetLoGain(kFALSE);
+// - fMeanMeanPhotPerArea to nareas
+// - fRmsMeanPhotPerArea  to nareas
+// - fMeanSigmaPhotPerArea to nareas
+// - fRmsSigmaPhotPerArea  to nareas
+//
+Bool_t MHCalibrationTestCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,"Test"))
+    return kFALSE;
+
+
+  MSignalCam *signal = (MSignalCam*)pList->FindObject("MSignalCam");
+  if (!signal)
+  {
+      *fLog << err << "MSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fMeanMeanPhotPerArea.Set(nareas);   
+  fRmsMeanPhotPerArea .Set(nareas); 
+  fMeanSigmaPhotPerArea.Set(nareas);  
+  fRmsSigmaPhotPerArea.Set(nareas);
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain histograms (MHGausEvents::FillHistAndArray())
+// with:
+// - MSignalPix::GetNumPhotons(pixid);
+//
+Bool_t MHCalibrationTestCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MSignalCam *calibration = (MSignalCam*)par;
+  if (!calibration)
+    {
+      gLog << err << "No argument in MHCalibrationTestCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF sumareahi  (nareas); 
+  TArrayF sumsectorhi(nsectors);
+  TArrayI numareahi  (nareas); 
+  TArrayI numsectorhi(nsectors);
+  
+  for (Int_t i=0; i<npixels; i++)
+    {
+
+      const MSignalPix &pix = (*calibration)[i];
+
+      const Float_t signal = pix.GetNumPhotons();
+      if (signal < 0.0001)
+          continue;
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      (*this)[i].FillHistAndArray(signal);
+
+      sumareahi  [aidx]   += signal;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += signal;
+      numsectorhi[sector] ++;
+    }
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+    }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with flags:
+//   MBadPixelsPix::kTestNotFitted and MBadPixelsPix::kTestOscillating
+// 
+Bool_t MHCalibrationTestCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  TArrayI numaidx;
+  numaidx.Set(fGeom->GetNumAreas());
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+      
+      if (hist.IsEmpty())
+        continue;
+
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          hist.BypassFit();
+      
+      hist.CreateFourierSpectrum();
+      
+      const Float_t area = (*fGeom)[i].GetA();
+      const Int_t   aidx = (*fGeom)[i].GetAidx();
+
+      fMeanMeanPhotPerArea[aidx]  += hist.GetMean() / area;
+      fRmsMeanPhotPerArea [aidx]  += hist.GetMean() / area * hist.GetMean()  / area;
+      fMeanSigmaPhotPerArea[aidx] += hist.GetSigma()/ area;
+      fRmsSigmaPhotPerArea [aidx] += hist.GetSigma()/ area * hist.GetSigma() / area;
+      numaidx[aidx]++;
+    }
+
+
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainArea(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          hist.BypassFit();
+      
+      hist.CreateFourierSpectrum();
+      
+      fRmsMeanPhotPerArea [j]  -= fMeanMeanPhotPerArea [j]*fMeanMeanPhotPerArea [j]/numaidx[j];
+      fRmsSigmaPhotPerArea[j]  -= fMeanSigmaPhotPerArea[j]*fMeanSigmaPhotPerArea[j]/numaidx[j];
+
+      fMeanMeanPhotPerArea [j]  /=  numaidx[j];
+      fMeanSigmaPhotPerArea[j]  /=  numaidx[j];
+      fRmsMeanPhotPerArea  [j]  /=  numaidx[j]-1.;
+      fRmsSigmaPhotPerArea [j]  /=  numaidx[j]-1.; 
+
+      if (fRmsMeanPhotPerArea  [j] > 0.)
+        fRmsMeanPhotPerArea  [j]  =  TMath::Sqrt(fRmsMeanPhotPerArea  [j]);
+      if (fRmsSigmaPhotPerArea [j] > 0.)
+        fRmsSigmaPhotPerArea [j]  =  TMath::Sqrt(fRmsSigmaPhotPerArea [j]);
+  }
+
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainSector(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          hist.BypassFit();
+
+      hist.CreateFourierSpectrum();
+    }
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Mean Test Calibration (MHGausEvents::GetMean())
+// 1: Error Mean Test Calibration  (MHGausEvents::GetMeanErr())
+// 2: Sigma fitted Test Calibration (MHGausEvents::GetSigma())
+// 3: Error Sigma Test Calibration (MHGausEvents::GetSigmaErr())
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit              (calls: MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                               (calls: MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK                       (calls: MHGausEvents::IsFourierSpectrumOK())
+//
+// Converted values:
+// =================
+//
+// 7:  Fitted Mean Test Calibration   (MHGausEvents::GetMean())     by MGeomPix::GetA()
+// 8:  Fitted Mean Error Calibration  (MHGausEvents::GetMeanErr())  by MGeomPix::GetA()
+// 9:  Fitted Sigma Test Calibration  (MHGausEvents::GetSigma())    by MGeomPix::GetA()
+// 10: Fitted Sigma Error Calibration (MHGausEvents::GetSigmaErr()) by MGeomPix::GetA()
+//
+Bool_t MHCalibrationTestCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pix = (*this)[idx];
+
+  if (pix.IsEmpty())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      val = pix.GetMean();
+      break;
+    case 1:
+      val = pix.GetMeanErr();
+      break;
+    case 2:
+      val = pix.GetSigma();
+      break;
+    case 3:
+      val = pix.GetSigmaErr();
+      break;
+    case 4:
+      val = pix.GetProb();
+      break;
+    case 5:
+      if (!pix.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pix.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    case 7:
+      val = pix.GetMean()/cam[idx].GetA();
+      break;
+    case 8:
+      val = pix.GetMeanErr()/cam[idx].GetA();
+      break;
+    case 9:
+      val = pix.GetSigma()/cam[idx].GetA();
+      break;
+    case 10:
+      val = pix.GetSigmaErr()/cam[idx].GetA();
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationTestCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+
+//------------------------------------------------------------
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels
+//
+void MHCalibrationTestCam::CalcAverageSigma()
+{
+  
+  for (UInt_t j=0; j<fGeom->GetNumAreas(); j++)
+    {
+  
+      MHCalibrationPix &hist    = GetAverageHiGainArea(j);
+
+      const Float_t numsqr    = TMath::Sqrt((Float_t)fAverageAreaNum[j]);
+      fAverageAreaSigma[j]    = hist.GetSigma    () * numsqr;
+      fAverageAreaSigmaVar[j] = hist.GetSigmaErr () * hist.GetSigmaErr() * numsqr;
+
+      fAverageAreaRelSigma   [j]  = fAverageAreaSigma[j]    / hist.GetMean();
+      fAverageAreaRelSigmaVar[j]  = fAverageAreaSigmaVar[j] / (fAverageAreaSigma[j]*fAverageAreaSigma[j]);
+      fAverageAreaRelSigmaVar[j] += hist.GetMeanErr()*hist.GetMeanErr()/hist.GetMean()/hist.GetMean();
+      fAverageAreaRelSigmaVar[j] *= fAverageAreaRelSigma[j];
+    }
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestCam.h	(revision 17960)
@@ -0,0 +1,58 @@
+#ifndef MARS_MHCalibrationTestCam
+#define MARS_MHCalibrationTestCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include <MArrayF.h>
+#endif
+#ifndef MARS_MArrayI
+#include <MArrayI.h>
+#endif
+
+class MHCalibrationTestCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Int_t   fgNbins;        //! Default for fNBins  (now set to: 2000  )
+  static const Axis_t  fgFirst;        //! Default for fFirst  (now set to: -0.5  )
+  static const Axis_t  fgLast;         //! Default for fLast   (now set to: 1999.5)
+  static const Float_t fgProbLimit;    //! The default for fProbLimit (now set to: 0.0000001)  
+  
+  static const TString gsHistName;     //! Default Histogram names
+  static const TString gsHistTitle;    //! Default Histogram titles
+  static const TString gsHistXTitle;   //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;   //! Default Histogram y-axis titles
+  
+  MArrayF fMeanMeanPhotPerArea;
+  MArrayF fRmsMeanPhotPerArea   ;
+  MArrayF fMeanSigmaPhotPerArea;
+  MArrayF fRmsSigmaPhotPerArea   ;
+
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+
+public:
+
+  MHCalibrationTestCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationTestCam() {}
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  const Float_t  GetMeanMeanPhotPerArea  ( const Int_t aidx ) const { return fMeanMeanPhotPerArea  [aidx]; }
+  const Float_t  GetMeanSigmaPhotPerArea ( const Int_t aidx ) const { return fMeanSigmaPhotPerArea [aidx]; }
+  const Float_t  GetRmsMeanPhotPerArea   ( const Int_t aidx ) const { return fRmsMeanPhotPerArea   [aidx]; }
+  const Float_t  GetRmsSigmaPhotPerArea  ( const Int_t aidx ) const { return fRmsSigmaPhotPerArea  [aidx]; }
+
+  void CalcAverageSigma();
+  
+  ClassDef(MHCalibrationTestCam, 1)	// Histogram class for Relative Time Camera Calibration
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestPix.cc	(revision 17960)
@@ -0,0 +1,98 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationTestPix
+//
+//  Histogram class for the charge calibration. 
+//  Stores and fits the charges and stores the location of the maximum FADC 
+//  slice. Tests are taken from MExtractedSignalPix.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationTestPix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TGraph.h>
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCalibrationTestPix);
+
+using namespace std;
+
+const Int_t   MHCalibrationTestPix::fgChargeNbins     = 4000;
+const Axis_t  MHCalibrationTestPix::fgChargeFirst     = -0.5;
+const Axis_t  MHCalibrationTestPix::fgChargeLast      = 39999.5;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins        (fgChargeNbins)
+// - the default number for fFirst        (fgChargeFirst)
+// - the default number for fLast         (fgChargeLast)
+//
+// - the default name of the  fHGausHist ("HCalibrationTest")
+// - the default title of the fHGausHist ("Distribution of calibrated FADC slices Pixel ")
+// - the default x-axis title for fHGausHist ("Sum FADC Slices")
+// - the default y-axis title for fHGausHist ("Nr. of events")
+//
+// Calls:
+// - Clear();
+//
+MHCalibrationTestPix::MHCalibrationTestPix(const char *name, const char *title)
+{ 
+  
+  fName  = name  ? name  : "MHCalibrationTestPix";
+  fTitle = title ? title : "Statistics of the calibrated FADC sums of calibration events";
+
+  SetNbins ( fgChargeNbins );
+  SetFirst ( fgChargeFirst );
+  SetLast  ( fgChargeLast  );
+
+  fHGausHist.SetName("HCalibrationTest");
+  fHGausHist.SetTitle("Distribution of calibrated Photons Pixel ");  
+  fHGausHist.SetXTitle("Nr. Photons");
+  fHGausHist.SetYTitle("Nr. of events");
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// returns fHGausHist.Integral("width")
+//
+const Float_t MHCalibrationTestPix::GetIntegral() const 
+{ 
+   return fHGausHist.Integral("width");  
+}
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestPix.h	(revision 17960)
@@ -0,0 +1,27 @@
+#ifndef MARS_MHCalibrationTestPix
+#define MARS_MHCalibrationTestPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+class MHCalibrationTestPix : public MHCalibrationPix
+{
+
+private:
+
+  static const Int_t   fgChargeNbins;        // Default for fNBins          (now set to: 2000  )
+  static const Axis_t  fgChargeFirst;        // Default for fFirst          (now set to: -0.5  )
+  static const Axis_t  fgChargeLast;         // Default for fLast           (now set to: 1999.5)
+
+public:
+
+  MHCalibrationTestPix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationTestPix() {}
+
+  const Float_t  GetIntegral()          const;
+  
+  ClassDef(MHCalibrationTestPix, 1)     // Base Histogram class for Test Pixel Calibration
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestTimeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestTimeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestTimeCam.cc	(revision 17960)
@@ -0,0 +1,419 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!              
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                        
+// MHCalibrationTestTimeCam                                                
+//                                                                        
+// Fills the calibrated signal from an MArrivalTime into 
+// MHCalibrationTestTimePix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray  
+//   or MHCalibrationCam::fHiGainArray, respectively.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors 
+//   and MHCalibrationCam::fAverageHiGainSectors 
+//
+// The signals are filled into a histogram and an array, in order to perform 
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an 
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the 
+// projected fourier components follow an exponential distribution. 
+// In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into an MCalibrationCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationTestTimeCam.h"
+
+#include "MHCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MHCalibrationTestTimeCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationTestTimeCam::fgNbins      = 300;
+const Axis_t  MHCalibrationTestTimeCam::fgFirst      = -0.025;
+const Axis_t  MHCalibrationTestTimeCam::fgLast       = 14.975;
+const Float_t MHCalibrationTestTimeCam::fgProbLimit  = 0.00000001;
+const TString MHCalibrationTestTimeCam::gsHistName   = "TestTime";
+const TString MHCalibrationTestTimeCam::gsHistTitle  = "Calibrated Calibration Arrival Times";  
+const TString MHCalibrationTestTimeCam::gsHistXTitle = "Arrival Time [FADC slices]";
+const TString MHCalibrationTestTimeCam::gsHistYTitle = "Nr. events";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHCalibrationTestTimeCam::MHCalibrationTestTimeCam(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MHCalibrationTestTimeCam";
+  fTitle = title ? title : "Histogram class for testing the calibration of arrival times";
+
+  SetBinning(fgNbins, fgFirst, fgLast);
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetLoGain(kFALSE);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MArrivalTime
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// 
+// Sets: 
+// - SetLoGain(kFALSE);
+//
+Bool_t MHCalibrationTestTimeCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,""))
+    return kFALSE;
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  return kTRUE;
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MArrivalTime:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain histograms (MHGausEvents::FillHistAndArray())
+// with:
+// - MArrivalTime::GetArrivalTime(pixid) - MArrivalTime::GetArrivalTime(1);
+//   (i.e. the time difference between pixel i and pixel 1 (hardware number: 2) )
+//
+Bool_t MHCalibrationTestTimeCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MSignalCam *calibration = (MSignalCam*)par;
+  if (!calibration)
+    {
+      gLog << err << "No argument in MHCalibrationRelTimeCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF sumareahi  (nareas); 
+  TArrayF sumsectorhi(nsectors);
+  TArrayI numareahi  (nareas); 
+  TArrayI numsectorhi(nsectors);
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+
+      MHCalibrationPix &histhi = (*this)[i];
+
+      if (histhi.IsExcluded())
+	continue;
+
+      const Float_t  time = (*calibration)[i].GetArrivalTime();
+      const Int_t  aidx   = (*fGeom)[i].GetAidx();
+      const Int_t  sector = (*fGeom)[i].GetSector();
+
+      histhi.FillHistAndArray(time) ;
+      sumareahi  [aidx]   += time;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += time;
+      numsectorhi[sector] ++;
+    }
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+
+    }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+Bool_t MHCalibrationTestTimeCam::FinalizeHists()
+{
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          {
+            hist.BypassFit();
+          }
+      
+      hist.CreateFourierSpectrum();
+      
+    }
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainArea(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          {
+            hist.BypassFit();
+          }
+      
+      hist.CreateFourierSpectrum();
+      
+
+  }
+
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainSector(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          {
+            hist.BypassFit();
+          }
+      hist.CreateFourierSpectrum();
+      
+
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+void MHCalibrationTestTimeCam::FinalizeBadPixels()
+{
+
+}
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Mean Time Calibration (MHGausEvents::GetMean())
+// 1: Error Mean Time Calibration  (MHGausEvents::GetMeanErr())
+// 2: Sigma fitted Time Calibration (MHGausEvents::GetSigma())
+// 3: Error Sigma Time Calibration (MHGausEvents::GetSigmaErr())
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit              (calls: MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                               (calls: MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK                       (calls: MHGausEvents::IsFourierSpectrumOK())
+//
+Bool_t MHCalibrationTestTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pix = (*this)[idx];
+
+  if (pix.IsExcluded())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      val = pix.GetMean();
+      break;
+    case 1:
+      val = pix.GetMeanErr();
+      break;
+    case 2:
+      val = pix.GetSigma();
+      break;
+    case 3:
+      val = pix.GetSigmaErr();
+      break;
+    case 4:
+      val = pix.GetProb();
+      break;
+    case 5:
+      if (!pix.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pix.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationTestTimeCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+
+//------------------------------------------------------------
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels
+//
+void MHCalibrationTestTimeCam::CalcAverageSigma()
+{
+  
+  for (UInt_t j=0; j<fGeom->GetNumAreas(); j++)
+    {
+  
+      MHCalibrationPix &hist    = GetAverageHiGainArea(j);
+
+      const Float_t numsqr    = TMath::Sqrt((Float_t)fAverageAreaNum[j]);
+      fAverageAreaSigma[j]    = hist.GetSigma    () * numsqr;
+      fAverageAreaSigmaVar[j] = hist.GetSigmaErr () * hist.GetSigmaErr() * numsqr;
+
+      fAverageAreaRelSigma   [j]  = fAverageAreaSigma[j]    / hist.GetMean();
+      fAverageAreaRelSigmaVar[j]  = fAverageAreaSigmaVar[j] / (fAverageAreaSigma[j]*fAverageAreaSigma[j]);
+      fAverageAreaRelSigmaVar[j] += hist.GetMeanErr()*hist.GetMeanErr()/hist.GetMean()/hist.GetMean();
+      fAverageAreaRelSigmaVar[j] *= fAverageAreaRelSigma[j];
+    }
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestTimeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestTimeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHCalibrationTestTimeCam.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHCalibrationTestTimeCam
+#define MARS_MHCalibrationTestTimeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+class MHCalibrationTestTimeCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Int_t   fgNbins;        //! Default for fNBins  (now set to: 600  )
+  static const Axis_t  fgFirst;        //! Default for fFirst  (now set to: -0.5 )
+  static const Axis_t  fgLast;         //! Default for fLast   (now set to: 29.5 )
+  static const Float_t fgProbLimit;    //! Default for fProbLimit (now set to: 0.000001)  
+  
+  static const TString gsHistName;     //! Default Histogram names
+  static const TString gsHistTitle;    //! Default Histogram titles
+  static const TString gsHistXTitle;   //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;   //! Default Histogram y-axis titles
+  
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  void    FinalizeBadPixels();
+  
+public:
+
+  MHCalibrationTestTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationTestTimeCam() {}
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  void CalcAverageSigma();
+  
+  ClassDef(MHCalibrationTestTimeCam, 0)	// Histogram class for Relative Time Camera Calibration
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHGausEvents.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHGausEvents.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHGausEvents.cc	(revision 17960)
@@ -0,0 +1,817 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHGausEvents
+//
+//  A base class for events which are believed to follow a Gaussian distribution 
+//  with time, e.g. calibration events, observables containing white noise, ...
+//
+//  MHGausEvents derives from MH, thus all features of MH can be used by a class 
+//  deriving from MHGausEvents, especially the filling functions. 
+//
+//  The central objects are: 
+//
+//  1) The TH1F fHGausHist: 
+//     ====================
+//   
+//     It is created with a default name and title and resides in directory NULL.
+//     - Any class deriving from MHGausEvents needs to apply a binning to fHGausHist
+//       (e.g. by setting the variables fNbins, fFirst, fLast and calling the function 
+//       InitBins() or by directly calling fHGausHist.SetBins(..) )
+//     - The histogram is filled with the functions FillHist() or FillHistAndArray(). 
+//     - The histogram can be fitted with the function FitGaus(). This involves stripping 
+//       of all zeros at the lower and upper end of the histogram and re-binning to 
+//       a new number of bins, specified in the variable fBinsAfterStripping.      
+//     - The fit result's probability is compared to a reference probability fProbLimit
+//       The NDF is compared to fNDFLimit and a check is made whether results are NaNs. 
+//       Accordingly, a flag IsGausFitOK() is set.
+//     - One can repeat the fit within a given amount of sigmas from the previous mean 
+//       (specified by the variables fPickupLimit and fBlackoutLimit) with the function RepeatFit()
+// 
+//  2) The TArrayF fEvents:
+//     ==========================
+// 
+//     It is created with 0 entries and not expanded unless FillArray() or FillHistAndArray()
+//     are called.
+//     - A first call to FillArray() or FillHistAndArray() initializes fEvents by default 
+//       to 512 entries. 
+//     - Any later call to FillArray() or FillHistAndArray() fills up the array. 
+//       Reaching the limit, the array is expanded by a factor 2.
+//     - The array can be fourier-transformed into the array fPowerSpectrum. 
+//       Note that any FFT accepts only number of events which are a power of 2. 
+//       Thus, fEvents is cut to the next power of 2 smaller than its actual number of entries. 
+//       Be aware that you might lose information at the end of your analysis. 
+//     - Calling the function CreateFourierSpectrum() creates the array fPowerSpectrum 
+//       and its projection fHPowerProbability which in turn is fit to an exponential. 
+//     - The fit result's probability is compared to a referenc probability fProbLimit 
+//       and accordingly the flag IsExpFitOK() is set.
+//     - The flag IsFourierSpectrumOK() is set accordingly to IsExpFitOK(). 
+//       Later, a closer check will be installed. 
+//     - You can display all arrays by calls to: CreateGraphEvents() and 
+//       CreateGraphPowerSpectrum() and successive calls to the corresponding Getters.
+//
+// To see an example, have a look at: Draw()
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHGausEvents.h"
+
+#include <TMath.h>
+#include <TH1.h>
+#include <TF1.h>
+#include <TGraph.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TRandom.h>
+
+#include "MFFT.h"
+#include "MString.h"
+#include "MArrayF.h"
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHGausEvents);
+
+using namespace std;
+
+const Int_t    MHGausEvents::fgNDFLimit             = 2;
+const Float_t  MHGausEvents::fgProbLimit            = 0.001;
+const Int_t    MHGausEvents::fgPowerProbabilityBins = 30;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+// Sets: 
+// - the default Probability Bins for fPowerProbabilityBins (fgPowerProbabilityBins)
+// - the default Probability Limit for fProbLimit  (fgProbLimit)
+// - the default NDF Limit for fNDFLimit           (fgNDFLimit)
+// - the default number of bins after stripping for fBinsAfterStipping (fgBinsAfterStipping)
+// - the default name of the fHGausHist            ("HGausHist")
+// - the default title of the fHGausHist           ("Histogram of Events with Gaussian Distribution")
+// - the default directory of the fHGausHist       (NULL)
+// - the default for fNbins (100)
+// - the default for fFirst (0.)
+// - the default for fLast  (100.)
+//
+// Initializes:
+// - fEvents to 0 entries
+// - fHGausHist()
+// - all other pointers to NULL
+// - all variables to 0.
+// - all flags to kFALSE
+//
+MHGausEvents::MHGausEvents(const char *name, const char *title)
+    : fEventFrequency(0), fFlags(0),
+      fHPowerProbability(NULL), 
+      fPowerSpectrum(NULL),
+      fFExpFit(NULL),
+      fGraphEvents(NULL), fGraphPowerSpectrum(NULL),
+      fFirst(0.), fLast(100.), fNbins(100), fFGausFit(NULL)
+{ 
+
+  fName  = name  ? name  : "MHGausEvents";
+  fTitle = title ? title : "Events with expected Gaussian distributions";
+
+  Clear();
+  
+  SetBinsAfterStripping();
+  SetNDFLimit();
+  SetPowerProbabilityBins();
+  SetProbLimit();
+
+  fHGausHist.SetName("HGausHist");
+  fHGausHist.SetTitle("Histogram of Events with Gaussian Distribution");
+  // important, other ROOT will not draw the axes:
+  fHGausHist.UseCurrentStyle();
+  fHGausHist.SetDirectory(NULL);
+  TAxis *yaxe = fHGausHist.GetYaxis();
+  yaxe->CenterTitle();
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Default Destructor. 
+//
+// Deletes (if Pointer is not NULL):
+// 
+// - fHPowerProbability
+// - fPowerSpectrum     
+// - fGraphEvents
+// - fGraphPowerSpectrum
+// 
+// - fFGausFit 
+// - fFExpFit
+//
+MHGausEvents::~MHGausEvents()
+{
+
+  //
+  // The next two lines are important for the case that 
+  // the class has been stored to a file and is read again. 
+  // In this case, the next two lines prevent a segm. violation
+  // in the destructor
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+  gROOT->GetListOfFunctions()->Remove(fFExpFit);
+  
+  // delete fits
+  if (fFGausFit)
+      delete fFGausFit; 
+  
+  if (fFExpFit)
+      delete fFExpFit;
+
+  // delete histograms
+  if (fHPowerProbability)
+    delete fHPowerProbability;
+
+  // delete arrays
+  if (fPowerSpectrum)  
+    delete fPowerSpectrum;     
+
+  // delete graphs
+  if (fGraphEvents)
+    delete fGraphEvents;
+
+  if (fGraphPowerSpectrum)
+    delete fGraphPowerSpectrum;
+}
+      
+// --------------------------------------------------------------------------
+//
+// Default Clear(), can be overloaded.
+//
+// Sets:
+// - all other pointers to NULL
+// - all variables to 0. and keep fEventFrequency
+// - all flags to kFALSE
+// 
+// Deletes (if not NULL):
+// - all pointers
+//
+void MHGausEvents::Clear(Option_t *o)
+{
+
+  SetGausFitOK        ( kFALSE );
+  SetExpFitOK         ( kFALSE );
+  SetFourierSpectrumOK( kFALSE );
+  SetExcluded         ( kFALSE );
+
+  fMean              = 0.;
+  fSigma             = 0.;
+  fMeanErr           = 0.;
+  fSigmaErr          = 0.;
+  fProb              = 0.;
+
+  fCurrentSize       = 0;
+
+  if (fHPowerProbability)
+    {
+      delete fHPowerProbability;
+      fHPowerProbability = NULL;
+    }
+
+  // delete fits
+  if (fFGausFit)
+    {
+      delete fFGausFit; 
+      fFGausFit = NULL;
+    }
+  
+  if (fFExpFit)
+    {
+      delete fFExpFit;
+      fFExpFit = NULL;
+    }
+  
+  // delete arrays
+  if (fPowerSpectrum)  
+    {
+      delete fPowerSpectrum;     
+      fPowerSpectrum = NULL;
+    }
+
+  // delete graphs
+  if (fGraphEvents)
+    {
+      delete fGraphEvents;
+      fGraphEvents = NULL;
+    }
+
+  if (fGraphPowerSpectrum)
+    {
+      delete fGraphPowerSpectrum;
+      fGraphPowerSpectrum = NULL;
+    }
+}
+
+// -------------------------------------------------------------------
+//
+// Create the fourier spectrum using the class MFFT.
+// The result is projected into a histogram and fitted by an exponential
+//
+void MHGausEvents::CreateFourierSpectrum()
+{
+
+  if (fFExpFit)
+    return;
+
+  if (fEvents.GetSize() < 8)
+    {
+      *fLog << warn << "Cannot create Fourier spectrum in: " << fName 
+            << ". Number of events smaller than 8 " << endl;
+      return;
+    }
+  
+  //
+  // The number of entries HAS to be a potence of 2, 
+  // so we can only cut out from the last potence of 2 to the rest. 
+  // Another possibility would be to fill everything with 
+  // zeros, but that gives a low frequency peak, which we would 
+  // have to cut out later again. 
+  //
+  // So, we have to live with the possibility that at the end 
+  // of the calibration run, something has happened without noticing 
+  // it...
+  //
+  
+  // This cuts only the non-used zero's, but MFFT will later cut the rest
+  fEvents.StripZeros();
+
+  if (fEvents.GetSize() < 8)
+    {
+      /*
+      *fLog << warn << "Cannot create Fourier spectrum. " << endl;
+      *fLog << warn << "Number of events (after stripping of zeros) is smaller than 8 " 
+            << "in pixel: " << fPixId << endl;
+      */
+      return;
+    }
+
+  MFFT fourier;
+
+  fPowerSpectrum     = fourier.PowerSpectrumDensity(&fEvents);
+  fHPowerProbability = ProjectArray(*fPowerSpectrum, fPowerProbabilityBins,
+                                    MString::Format("PowerProb%s", GetName()),
+                                    "Probability of Power occurrance");
+  fHPowerProbability->SetXTitle("P(f)");
+  fHPowerProbability->SetYTitle("Counts");
+  fHPowerProbability->GetYaxis()->CenterTitle();
+  fHPowerProbability->SetDirectory(NULL);
+  fHPowerProbability->SetBit(kCanDelete);  
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Double_t xmax = fHPowerProbability->GetXaxis()->GetXmax();
+
+  fFExpFit = new TF1("","exp([0]-[1]*x)",0.,xmax);
+  fFExpFit->SetName("FExpFit");
+  gROOT->GetListOfFunctions()->Remove(fFExpFit);
+
+
+  const Double_t slope_guess  = (TMath::Log(fHPowerProbability->GetEntries())+1.)/xmax;
+  const Double_t offset_guess = slope_guess*xmax;
+
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFExpFit);
+  fFExpFit->SetParameters(offset_guess, slope_guess);
+  fFExpFit->SetParNames("Offset","Slope");
+  fFExpFit->SetParLimits(0,offset_guess/2.,2.*offset_guess);
+  fFExpFit->SetParLimits(1,slope_guess/1.5,1.5*slope_guess);
+  fFExpFit->SetRange(0.,xmax);
+
+  fHPowerProbability->Fit(fFExpFit,"RQL0");
+  
+  if (GetExpProb() > fProbLimit)
+    SetExpFitOK(kTRUE);
+  
+  //
+  // For the moment, this is the only check, later we can add more...
+  //
+  SetFourierSpectrumOK(IsExpFitOK());
+
+  return;
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Create a graph to display the array fEvents
+// If the variable fEventFrequency is set, the x-axis is transformed into real time.
+//
+void MHGausEvents::CreateGraphEvents()
+{
+
+  fEvents.StripZeros();
+
+  const Int_t n = fEvents.GetSize();
+  if (n==0)
+    return;
+
+  const Float_t freq = fEventFrequency ? fEventFrequency : 1;
+
+  MArrayF xaxis(n);
+  for (Int_t i=0; i<n; i++)
+      xaxis[i] = (Float_t)i/freq;
+
+  fGraphEvents = new TGraph(n, xaxis.GetArray(), fEvents.GetArray());
+  fGraphEvents->SetTitle("Evolution of Events with time");
+  fGraphEvents->GetXaxis()->SetTitle(fEventFrequency ? "Time [s]" : "Event Nr.");
+  fGraphEvents->GetYaxis()->SetTitle(fHGausHist.GetXaxis()->GetTitle());
+  fGraphEvents->GetYaxis()->CenterTitle();
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Create a graph to display the array fPowerSpectrum
+// If the variable fEventFrequency is set, the x-axis is transformed into real frequency.
+//
+void MHGausEvents::CreateGraphPowerSpectrum()
+{
+
+  fPowerSpectrum->StripZeros();
+
+  const Int_t n = fPowerSpectrum->GetSize();
+
+  const Float_t freq = fEventFrequency ? fEventFrequency : 1;
+
+  MArrayF xaxis(n);
+  for (Int_t i=0; i<n; i++)
+      xaxis[i] = 0.5*(Float_t)i*freq/n;
+
+  fGraphPowerSpectrum = new TGraph(n, xaxis.GetArray(), fPowerSpectrum->GetArray());
+  fGraphPowerSpectrum->SetTitle("Power Spectrum Density");
+  fGraphPowerSpectrum->GetXaxis()->SetTitle(fEventFrequency ? "Frequency [Hz]" : "Frequency");
+  fGraphPowerSpectrum->GetYaxis()->SetTitle("P(f)");
+  fGraphPowerSpectrum->GetYaxis()->CenterTitle();
+
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// The following options can be chosen:
+//
+// "EVENTS": displays a TGraph of the array fEvents
+// "FOURIER": display a TGraph of the fourier transform of fEvents 
+//            displays the projection of the fourier transform with the fit
+//
+// The following picture shows a typical outcome of call to Draw("fourierevents"): 
+// - The first plot shows the distribution of the values with the Gauss fit
+//   (which did not succeed, in this case, for obvious reasons)
+// - The second plot shows the TGraph with the events vs. time
+// - The third plot shows the fourier transform and a small peak at about 85 Hz.
+// - The fourth plot shows the projection of the fourier components and an exponential 
+//   fit, with the result that the observed deviation is still statistical with a 
+//   probability of 0.5%. 
+//
+//Begin_Html
+/*
+<img src="images/MHGausEventsDraw.gif">
+*/
+//End_Html
+//
+void MHGausEvents::Draw(const Option_t *opt)
+{
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this,600, 600);
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win   = 1;
+  Int_t nofit = 0;
+
+  if (option.Contains("events"))
+    win += 1;
+  if (option.Contains("fourier"))
+    win += 2;
+  
+  if (IsEmpty())
+    win--;
+
+  if (option.Contains("nofit"))
+    {
+      option.ReplaceAll("nofit","");
+      nofit++;
+    }
+  
+  pad->SetBorderMode(0);
+  if (win > 1)
+    pad->Divide(1,win);
+
+  Int_t cwin = 1;
+
+  gPad->SetTicks();
+
+  if (!IsEmpty())
+    {
+      pad->cd(cwin++);
+
+      if (!IsOnlyOverflow() && !IsOnlyUnderflow())
+        gPad->SetLogy();
+
+      fHGausHist.Draw(option);
+
+      if (!nofit)
+        if (fFGausFit)
+          {
+            fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+            fFGausFit->Draw("same");
+          }
+    }
+  
+  if (option.Contains("events"))
+    {
+      pad->cd(cwin++);
+      DrawEvents();
+    }
+  if (option.Contains("fourier"))      
+    {
+      pad->cd(cwin++);
+      DrawPowerSpectrum();
+      pad->cd(cwin);
+      DrawPowerProjection();
+    }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// DrawEvents:
+//
+// Will draw the graph with the option "A", unless the option:
+// "SAME" has been chosen 
+//
+void MHGausEvents::DrawEvents(Option_t *opt)
+{
+  
+  if (!fGraphEvents)
+    CreateGraphEvents();
+
+  if (!fGraphEvents)
+    return;
+
+  fGraphEvents->SetBit(kCanDelete);
+  fGraphEvents->SetTitle("Events with time");
+
+  TString option(opt);
+  option.ToLower();
+
+  if (option.Contains("same"))
+    {
+      option.ReplaceAll("same","");      
+      fGraphEvents->Draw(option+"L");
+    }
+  else
+    fGraphEvents->Draw(option+"AL");  
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// DrawPowerSpectrum
+//
+// Will draw the fourier spectrum of the events sequence with the option "A", unless the option:
+// "SAME" has been chosen 
+//
+void MHGausEvents::DrawPowerSpectrum(Option_t *option)
+{
+
+  TString opt(option);
+  
+  if (!fPowerSpectrum)
+    CreateFourierSpectrum();
+
+  if (fPowerSpectrum)
+    {
+      if (!fGraphPowerSpectrum)
+        CreateGraphPowerSpectrum();
+
+      if (!fGraphPowerSpectrum)
+        return;
+      
+      if (opt.Contains("same"))
+        {
+          opt.ReplaceAll("same","");      
+          fGraphPowerSpectrum->Draw(opt+"L");
+        }
+      else
+        {
+          fGraphPowerSpectrum->Draw(opt+"AL");  
+          fGraphPowerSpectrum->SetBit(kCanDelete);
+        }
+    }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// DrawPowerProjection
+//
+// Will draw the projection of the fourier spectrum onto the power probability axis
+// with the possible options of TH1D
+//
+void MHGausEvents::DrawPowerProjection(Option_t *option)
+{
+  
+  TString opt(option);
+
+  if (!fHPowerProbability)
+    CreateFourierSpectrum();
+
+  if (fHPowerProbability && fHPowerProbability->GetEntries() > 0)
+    {
+      gPad->SetLogy();
+      fHPowerProbability->Draw(opt.Data());
+      if (fFExpFit)
+        {
+          fFExpFit->SetLineColor(IsExpFitOK() ? kGreen : kRed);
+          fFExpFit->Draw("same");
+        }
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill fEvents with f
+// If size of fEvents is 0, initializes it to 512
+// If size of fEvents is smaller than fCurrentSize, double the size
+// Increase fCurrentSize by 1
+//
+void MHGausEvents::FillArray(const Float_t f)
+{
+
+  if (fEvents.GetSize() == 0)
+    fEvents.Set(512);
+
+  if (fCurrentSize >= fEvents.GetSize())
+    fEvents.Set(fEvents.GetSize()*2);
+  
+  fEvents.AddAt(f,fCurrentSize++);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fills fHGausHist with f
+// Returns kFALSE, if overflow or underflow occurred, else kTRUE
+//
+Bool_t MHGausEvents::FillHist(const Float_t f)
+{
+  return fHGausHist.Fill(f) > -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Executes:
+// - FillArray()
+// - FillHist()
+//
+Bool_t MHGausEvents::FillHistAndArray(const Float_t f)
+{
+
+  FillArray(f);
+  return FillHist(f);
+}
+
+// -------------------------------------------------------------------
+//
+// Fit fGausHist with a Gaussian after stripping zeros from both ends 
+// and rebinned to the number of bins specified in fBinsAfterStripping
+//
+// The fit results are retrieved and stored in class-own variables.  
+//
+// A flag IsGausFitOK() is set according to whether the fit probability 
+// is smaller or bigger than fProbLimit, whether the NDF is bigger than 
+// fNDFLimit and whether results are NaNs.
+//
+Bool_t MHGausEvents::FitGaus(Option_t *option, const Double_t xmin, const Double_t xmax)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  //
+  // First, strip the zeros from the edges which contain only zeros and rebin 
+  // to fBinsAfterStripping bins. If fBinsAfterStripping is 0, reduce bins only by 
+  // a factor 10.
+  //
+  // (ATTENTION: The Chisquare method is more sensitive, 
+  // the _less_ bins, you have!)
+  //
+  StripZeros(fHGausHist,
+             fBinsAfterStripping ? fBinsAfterStripping 
+             : (fNbins > 1000 ? fNbins/10 : 0));
+  
+  TAxis *axe = fHGausHist.GetXaxis();
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetFirst()) : xmin;
+  Axis_t rmax = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetLast())  : xmax;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Stat_t   entries     = fHGausHist.Integral(axe->FindBin(rmin),axe->FindBin(rmax),"width");
+  const Double_t mu_guess    = fHGausHist.GetBinCenter(fHGausHist.GetMaximumBin());
+  const Double_t sigma_guess = fHGausHist.GetRMS();
+  const Double_t area_guess  = entries/TMath::Sqrt(TMath::TwoPi())/sigma_guess;
+
+  fFGausFit = new TF1("GausFit","gaus",rmin,rmax);
+
+  if (!fFGausFit) 
+    {
+    *fLog << warn << dbginf << "WARNING: Could not create fit function for Gauss fit " 
+          << "in: " << fName << endl;
+    return kFALSE;
+    }
+  
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+
+  fFGausFit->SetParameters(area_guess,mu_guess,sigma_guess);
+  fFGausFit->SetParNames("Area","#mu","#sigma");
+  fFGausFit->SetParLimits(0,0.,area_guess*25.);
+  fFGausFit->SetParLimits(1,rmin,rmax);
+  fFGausFit->SetParLimits(2,0.,rmax-rmin);
+  fFGausFit->SetRange(rmin,rmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  fMean     = fFGausFit->GetParameter(1);
+  fSigma    = fFGausFit->GetParameter(2);
+  fMeanErr  = fFGausFit->GetParError(1);
+  fSigmaErr = fFGausFit->GetParError(2);
+  fProb     = fFGausFit->GetProb();
+
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not NaN's  (not a number)
+  // 2) The results are all finite
+  // 3) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 4) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  // !Finitite means either infinite or not-a-number
+  if (   !TMath::Finite(fMean)
+      || !TMath::Finite(fMeanErr)
+      || !TMath::Finite(fProb)
+      || !TMath::Finite(fSigma)
+      || !TMath::Finite(fSigmaErr)
+      || fFGausFit->GetNDF() < fNDFLimit 
+      || fProb < fProbLimit )
+    return kFALSE;
+
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Default InitBins, can be overloaded.
+//
+// Executes:
+// - fHGausHist.SetBins(fNbins,fFirst,fLast)
+//
+void MHGausEvents::InitBins()
+{
+  //  const TAttAxis att(fHGausHist.GetXaxis());
+  fHGausHist.SetBins(fNbins,fFirst,fLast);
+  //  att.Copy(fHGausHist.GetXaxis());
+}
+
+// -----------------------------------------------------------------------------------
+// 
+// A default print
+//
+void MHGausEvents::Print(const Option_t *o) const 
+{
+  
+  *fLog << all                                                        << endl;
+  *fLog << all << "Results of the Gauss Fit in: " << fName            << endl;
+  *fLog << all << "Mean: "             << GetMean()                   << endl;
+  *fLog << all << "Sigma: "            << GetSigma()                  << endl;
+  *fLog << all << "Chisquare: "        << GetChiSquare()              << endl;
+  *fLog << all << "DoF: "              << GetNdf()                    << endl;
+  *fLog << all << "Probability: "      << GetProb()                   << endl;
+  *fLog << all                                                        << endl;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default Reset(), can be overloaded.
+//
+// Executes:
+// - Clear()
+// - fHGausHist.Reset()
+// - fEvents.Set(0)
+// - InitBins()
+//
+void MHGausEvents::Reset()
+{
+
+  Clear();
+  fHGausHist.Reset();
+  fEvents.Set(0);
+  InitBins();
+}
+
+// ----------------------------------------------------------------------------
+//
+// Simulates Gaussian events and fills them  into the histogram and the array
+// In order to do a fourier analysis, call CreateFourierSpectrum()
+//
+void  MHGausEvents::SimulateGausEvents(const Float_t mean, const Float_t sigma, const Int_t nevts)
+{
+
+  if (!IsEmpty())
+    *fLog << warn << "The histogram is already filled, will superimpose simulated events on it..." << endl;
+  
+  for (Int_t i=0;i<nevts;i++) {
+    const Double_t ran = gRandom->Gaus(mean,sigma);
+    FillHistAndArray(ran);
+  }
+  
+}
Index: branches/Mars_McMismatchStudy/mhcalib/MHGausEvents.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHGausEvents.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHGausEvents.h	(revision 17960)
@@ -0,0 +1,177 @@
+#ifndef MARS_MHGausEvents
+#define MARS_MHGausEvents
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOF_TF1
+#include <TF1.h>
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class TVirtualPad;
+class TGraph;
+class TH1F;
+class TH1I;
+class TF1;
+
+class MHGausEvents : public MH
+{
+private:
+
+  const static Int_t   fgNDFLimit;             //! Default for fNDFLimit             (now set to: 2)
+  const static Float_t fgProbLimit;            //! Default for fProbLimit            (now set to: 0.001)
+  const static Int_t   fgPowerProbabilityBins; //! Default for fPowerProbabilityBins (now set to: 20)
+
+private:
+
+  Int_t    fBinsAfterStripping;        // Bins for the Gauss Histogram after stripping off the zeros at both ends
+  UInt_t   fCurrentSize;               // Current size of the array fEvents
+  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
+  MArrayF *fPowerSpectrum;             //! Fourier transform of fEvents
+
+  enum  { kGausFitOK,
+          kExpFitOK,
+          kFourierSpectrumOK,
+          kExcluded };                 // Bits for information about fit results 
+  
+  MArrayF  fEvents;                    // Array which holds the entries of GausHist
+  TF1     *fFExpFit;                   // Exponential fit for FHPowerProbability
+  TGraph  *fGraphEvents;               //! TGraph to display the event array 
+  TGraph  *fGraphPowerSpectrum;        //! TGraph to display the power spectrum array 
+  Axis_t   fFirst;                     // Lower histogram edge  for fHGausHist (used by InitBins()) 
+  Axis_t   fLast;                      // Upper histogram edge  for fHGausHist (used by InitBins()) 
+  Int_t    fNbins;                     // Number histogram bins for fHGausHist (used by InitBins())
+  Int_t    fNDFLimit;                  // NDF limit for judgement if fit is OK
+  Float_t  fProbLimit;                 // Probability limit for judgement if fit is OK 
+
+protected:
+  TF1     *fFGausFit;                  // Gauss fit for fHGausHist
+  TH1F     fHGausHist;                 // Histogram to hold the Gaussian distribution
+
+  Double_t fMean;                      // Mean of the Gauss fit
+  Double_t fMeanErr;                   // Error of the mean of the Gauss fit
+  Double_t fSigma;                     // Sigma of the Gauss fit
+  Double_t fSigmaErr;                  // Error of the sigma of the Gauss fit
+  Double_t fProb;                      // Probability of the Gauss fit 
+
+  // Setters
+  void  SetBinsAfterStripping   ( const Int_t nbins=0   )                    { fBinsAfterStripping  =nbins; }
+  void  SetPowerProbabilityBins ( const Int_t nbins=fgPowerProbabilityBins ) { fPowerProbabilityBins=nbins; }
+
+public:
+
+  MHGausEvents(const char* name=NULL, const char* title=NULL);
+  ~MHGausEvents();
+
+  void Clear(Option_t *o="");
+  void Reset();  
+
+  void CreateFourierSpectrum();         
+  void CreateGraphEvents();             
+  void CreateGraphPowerSpectrum(); 
+
+  // Draws
+  void Draw               ( Option_t *option="" ); // *MENU*
+  void DrawEvents         ( Option_t *option="" ); // *MENU*
+  void DrawPowerSpectrum  ( Option_t *option="" ); // *MENU*
+  void DrawPowerProjection( Option_t *option="" ); // *MENU*
+
+  // Fill
+  void   FillArray        ( const Float_t f ); 
+  Bool_t FillHist         ( const Float_t f ); 
+  Bool_t FillHistAndArray ( const Float_t f ); 
+  
+  // Fits
+  Bool_t FitGaus          ( Option_t *option="RQ0",         
+			    const Double_t xmin=0., 
+			    const Double_t xmax=0.); // *MENU*
+  
+  // Inits
+  virtual void InitBins();
+  
+  // Getters
+  const Double_t GetEntries()            const { return fHGausHist.GetEntries(); }
+  const Double_t GetChiSquare()          const { return ( fFGausFit ? fFGausFit->GetChisquare() : 0.); }
+  const Double_t GetExpChiSquare()       const { return ( fFExpFit  ? fFExpFit->GetChisquare()  : 0.); }
+  const Int_t    GetExpNdf()             const { return ( fFExpFit  ? fFExpFit->GetNDF()        : 0 ); }
+  const Double_t GetExpProb()            const { return ( fFExpFit  ? fFExpFit->GetProb()       : 0.); }
+        MArrayF *GetEvents()                   { return &fEvents;            }  
+  const MArrayF *GetEvents()             const { return &fEvents;            }
+  const Float_t  GetEventFrequency ()    const { return fEventFrequency;     }
+        TF1     *GetFExpFit()                  { return fFExpFit;            }
+  const TF1     *GetFExpFit()            const { return fFExpFit;            } 
+        TF1     *GetFGausFit()                 { return fFGausFit;           }
+  const TF1     *GetFGausFit()           const { return fFGausFit;           } 
+        TGraph  *GetGraphEvents()              { return fGraphEvents;        }
+  const Double_t GetFirst()              const { return fFirst;              }
+  const Double_t GetLast ()              const { return fLast ;              }  
+  const TGraph  *GetGraphEvents()        const { return fGraphEvents;        }
+        TGraph  *GetGraphPowerSpectrum()       { return fGraphPowerSpectrum; }
+  const TGraph  *GetGraphPowerSpectrum() const { return fGraphPowerSpectrum; }
+        TH1F    *GetHGausHist()                { return &fHGausHist;         }
+  const TH1F    *GetHGausHist()          const { return &fHGausHist;         } 
+        TH1I    *GetHPowerProbability()        { return fHPowerProbability;  }
+  const TH1I    *GetHPowerProbability()  const { return fHPowerProbability;  } 
+  const Double_t GetHistRms()            const { return fHGausHist.GetRMS(); }
+  const Double_t GetMean()               const { return fMean;               }
+  const Double_t GetMeanErr()            const { return fMeanErr;            }
+  const Int_t    GetNdf()                const { return ( fFGausFit ? fFGausFit->GetNDF()       : 0);  }
+  const Int_t    GetNbins()              const { return fNbins;              }
+  const Double_t GetOffset()             const { return ( fFExpFit  ? fFExpFit->GetParameter(0) : 0.); }
+        MArrayF *GetPowerSpectrum()            { return fPowerSpectrum;      }  
+  const MArrayF *GetPowerSpectrum()      const { return fPowerSpectrum;      }
+  const Double_t GetProb()               const { return fProb;               }
+  const Double_t GetSigma()              const { return fSigma;              }
+  const Double_t GetSigmaErr()           const { return fSigmaErr;           }
+  const Double_t GetSlope()              const { return ( fFExpFit  ? fFExpFit->GetParameter(1) : 0.); }
+  const Int_t    GetNDFLimit()           const { return fNDFLimit; }
+  const Float_t  GetProbLimit()          const { return fProbLimit; }
+
+  const Bool_t   IsValid()               const { return fMean!=0 || fSigma!=0; }
+  const Bool_t   IsExcluded()            const { return TESTBIT(fFlags,kExcluded);          }
+  const Bool_t   IsExpFitOK()            const { return TESTBIT(fFlags,kExpFitOK);          }
+  const Bool_t   IsEmpty()               const { return !(fHGausHist.GetEntries());         }
+  const Bool_t   IsFourierSpectrumOK()   const { return TESTBIT(fFlags,kFourierSpectrumOK); }
+  const Bool_t   IsGausFitOK()           const { return TESTBIT(fFlags,kGausFitOK);         }
+  const Bool_t   IsOnlyOverflow()        const { return fHGausHist.GetEntries()>0 && fHGausHist.GetEntries() == fHGausHist.GetBinContent(fNbins+1); }
+  const Bool_t   IsOnlyUnderflow()       const { return fHGausHist.GetEntries()>0 && fHGausHist.GetEntries() == fHGausHist.GetBinContent(0);        }
+
+  // Prints
+  void Print(const Option_t *o="") const;       // *MENU*
+  
+  // Setters
+  void  SetEventFrequency   ( const Float_t  f                   ) { fEventFrequency = f;   }
+  void  SetExcluded         ( const Bool_t   b=kTRUE             ) { b ? SETBIT(fFlags,kExcluded)  : CLRBIT(fFlags,kExcluded); }
+  void  SetExpFitOK         ( const Bool_t   b=kTRUE             ) { b ? SETBIT(fFlags,kExpFitOK)  : CLRBIT(fFlags,kExpFitOK); }
+  void  SetFourierSpectrumOK( const Bool_t   b=kTRUE             ) { b ? SETBIT(fFlags,kFourierSpectrumOK) : CLRBIT(fFlags,kFourierSpectrumOK); }
+  void  SetGausFitOK        ( const Bool_t   b=kTRUE             ) { b ? SETBIT(fFlags,kGausFitOK) : CLRBIT(fFlags,kGausFitOK);}
+  void  SetMean             ( const Double_t d                   ) { fMean           = d;   }
+  void  SetMeanErr          ( const Double_t d                   ) { fMeanErr        = d;   }
+  void  SetNDFLimit         ( const Int_t    lim=fgNDFLimit      ) { fNDFLimit       = lim; }  
+  void  SetProb             ( const Double_t d                   ) { fProb           = d;   }
+  void  SetProbLimit        ( const Float_t  lim=fgProbLimit     ) { fProbLimit      = lim; }
+  void  SetSigma            ( const Double_t d                   ) { fSigma          = d;   }
+  void  SetSigmaErr         ( const Double_t d                   ) { fSigmaErr       = d;   }
+
+  void SetBinning(Int_t i, Axis_t lo, Axis_t up) { fNbins=i; fFirst=lo; fLast=up; }
+
+  // Simulates
+  void  SimulateGausEvents(const Float_t mean, const Float_t sigma, const Int_t nevts=4096);     // *MENU*
+
+  ClassDef(MHGausEvents, 4) // Base class for events with Gaussian distributed values
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/MHPedestalCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHPedestalCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHPedestalCam.cc	(revision 17960)
@@ -0,0 +1,846 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPedestalCam
+//
+// Fills the extracted pedestals of MExtractedSignalCam into
+// the MHCalibrationPix-classes MHPedestalPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray
+//   or MHCalibrationCam::fHiGainArray, respectively
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors
+//   and MHCalibrationCam::fAverageHiGainSectors
+//
+// Every pedestal is directly taken from MExtractedSignalCam, filled by the
+// appropriate extractor.
+//
+// The pedestals are filled into a histogram and an array, in order to perform
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors
+// and the fit probability are extracted. If none of these values are NaN's and
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%),
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are
+// taken directly (see MHCalibrationPix::BypassFit()).
+//
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup)
+//
+// The number of summed FADC slices is taken to re-normalize
+// the result to a pedestal per pixel with the formulas (see MHPedestalPix::Renorm()):
+// - Mean Pedestal        / slice = Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice = Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice = Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice = Sigma Pedestal Error / Sqrt (Number slices)
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the
+// projected fourier components follow an exponential distribution.
+//
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MPedestalCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of
+// the number involved pixels in order to be able to compare it to the average of
+// sigmas in the camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalCam.h"
+#include "MHPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationPix.h"
+
+#include "MBadPixelsCam.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include <TH1F.h>
+#include <TOrdCollection.h>
+
+ClassImp(MHPedestalCam);
+
+using namespace std;
+
+const Int_t   MHPedestalCam::fgNbins      =  50;
+const Axis_t  MHPedestalCam::fgFirst      = -57.5;
+const Axis_t  MHPedestalCam::fgLast       = 192.5;
+const TString MHPedestalCam::gsHistName   = "Pedestal";
+const TString MHPedestalCam::gsHistTitle  = "Pedestal";
+const TString MHPedestalCam::gsHistXTitle = "Charge [FADC slices]";
+const TString MHPedestalCam::gsHistYTitle = "Nr. events";
+const TString MHPedestalCam::fgNamePedestalCam = "MPedestalCam";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes:
+// - fExtractHiGainSlices to 0.
+// - the event frequency to 1200 Hz.
+// - the fRenormflag to kFALSE
+//
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHPedestalCam::MHPedestalCam(const char *name, const char *title) 
+    : fNamePedestalCamOut(fgNamePedestalCam), fNumEvents(0), 
+      fExtractHiGainSlices(0.), fPedestalsOut(NULL)
+{
+
+  fName  = name  ? name  : "MHPedestalCam";
+  fTitle = title ? title : "Class to fill the pedestal histograms";
+  
+  SetPulserFrequency(1200);
+  SetRenorm(kFALSE);
+  SetLoGain(kFALSE);
+
+  SetBinning(fgNbins, fgFirst, fgLast);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetFitStart();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationCam::ResetHists()
+//
+// Resets:
+// - fSum
+// - fSumSquare
+// - fAreaSum
+// - fAreaSumSquare
+// - fAreaNum
+// - fSectorSum
+// - fSectorSumSquare
+// - fSectorNum
+//
+void MHPedestalCam::ResetHists()
+{
+  
+  MHCalibrationCam::ResetHists();
+  
+  fNumEvents = 0;
+  
+  // If the size is yet set, set the size
+  if (fSum.GetSize()>0)
+    {
+      // Reset contents of arrays.
+      fSum.Reset();
+      fSumSquare.Reset();
+      
+      fAreaSum. Reset();
+      fAreaSumSquare.Reset();
+      fAreaNum.Reset();
+      
+      fSectorSum. Reset();
+      fSectorSumSquare.Reset();
+      fSectorNum.Reset();
+    }
+}
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationChargeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHPedestalCam *cam = MParList::FindObject("MHPedestalCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHPedestalCam::Clone(const char *) const
+{
+
+  MHPedestalCam *cam = new MHPedestalCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MPedestalCam
+// - MExtractedSignalCam
+//
+// Searches or creates:
+// - MCalibrationPedCam
+//
+// Retrieves from MExtractedSignalCam:
+// - number of used High Gain FADC slices (MExtractedSignalCam::GetNumUsedHiGainFADCSlices())
+//
+// Initializes, if empty to MGeomCam::GetNumPixels():
+// - MHCalibrationCam::fHiGainArray
+//
+// Initializes, if empty to MGeomCam::GetNumAreas() for:
+// - MHCalibrationCam::fAverageHiGainAreas
+//
+// Initializes, if empty to MGeomCam::GetNumSectors() for:
+// - MHCalibrationCam::fAverageHiGainSectors
+// 
+// Calls MHCalibrationCam::InitPedHists() for every entry in:
+// - MHCalibrationCam::fHiGainArray
+// - MHCalibrationCam::fAverageHiGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors
+//
+// Sets Titles and Names for the Histograms 
+// - MHCalibrationCam::fAverageHiGainAreas
+// 
+Bool_t MHPedestalCam::ReInitHists(MParList *pList)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!signal && fRenorm)
+    {
+      *fLog << err << "Cannot find MExtractedSignalCam, but re-normalization switched on..."
+            << " Cannot find number of used slices ...abort." << endl;
+      return kFALSE;
+    }
+  
+
+  if (!fPedestalsOut)
+    fPedestalsOut = (MPedestalCam*)pList->FindObject(AddSerialNumber(fNamePedestalCamOut),"MPedestalCam");
+
+  if (!fPedestalsOut)
+    {
+      *fLog << err << "Cannot find nor create outgoing MPedestalCam ..." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  fCam = (MCalibrationCam*)pList->FindObject("MCalibrationPedCam", "MCalibrationCam");
+  if (!fCam)
+  {
+      fCam = (MCalibrationCam*)pList->FindCreateObj("MCalibrationCam", AddSerialNumber("MCalibrationPedCam"));
+      if (!fCam)
+          return kFALSE;
+
+      fCam->Init(*fGeom);
+  }
+  
+  InitHiGainArrays(npixels,nareas,nsectors);
+
+  if (fSum.GetSize()==0)
+    {
+      fSum.       Set(npixels);
+      fSumSquare.      Set(npixels);
+      fAreaSum.   Set(nareas);
+      fAreaSumSquare.  Set(nareas);
+      fAreaNum.  Set(nareas);
+      fSectorSum. Set(nsectors);
+      fSectorSumSquare.Set(nsectors);
+      fSectorNum.Set(nsectors);
+    }
+
+  fNumEvents = 0;
+
+  if (!signal)
+    return kTRUE;
+  
+  
+  Float_t sliceshi = signal->GetNumUsedHiGainFADCSlices();
+  
+  if (sliceshi == 0.)
+    {
+      *fLog << err << "Number of used signal slices in MExtractedSignalCam is zero  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  if (fExtractHiGainSlices != 0. && sliceshi != fExtractHiGainSlices )
+    {
+      *fLog << err << "Number of used High Gain signal slices changed in MExtractedSignalCam  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  fExtractHiGainSlices = sliceshi;
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() 
+        << ": Number of found High Gain signal slices: " << fExtractHiGainSlices << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes the High Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationChargePix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of Abs Times histogram from  fAbsNbins, fAbsFirst and fAbsLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set Abs Times Histgram names and titles from fAbsHistName and fAbsHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of Abs Times Histogram from fAbsHistXTitle and fAbsHistYTitle
+//   * Call InitHists
+//
+//
+void MHPedestalCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+  
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHPedestalPix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                       Form("%s High Gain Pixel%04d",fHistTitle.Data(),i)),i);
+
+        MHPedestalPix &pix = (MHPedestalPix&)(*this)[i];
+        pix.SetBinning(fNbins, fFirst, fLast);
+        pix.SetProbLimit(fProbLimit);
+
+        InitHists(pix, (*fBadPixels)[i], i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHPedestalPix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                  Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+
+        MHPedestalPix &pix = (MHPedestalPix&)GetAverageHiGainArea(j);
+
+        pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas),
+                       fFirst, fLast);
+        
+        InitHists(pix, fCam->GetAverageBadArea(j), j);
+
+      }
+  }
+  
+  if (fAverageHiGainSectors->GetSize()==0)
+  {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+	  fAverageHiGainSectors->AddAt(new MHPedestalPix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                      Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+
+          MHPedestalPix &pix = (MHPedestalPix&)GetAverageHiGainSector(j);
+
+          pix.SetBinning(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas),
+                         fFirst, fLast);
+
+          InitHists(pix, fCam->GetAverageBadSector(j), j);
+
+      }
+  }
+}
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MExtractedSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain histograms (MHGausEvents::FillHistAndArray()), respectively
+// with the signals MExtractedSignalCam::GetExtractedSignalHiGain().
+//
+Bool_t MHPedestalCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MPedestalCam *pedestal = (MPedestalCam*)par;
+  if (!pedestal)
+    {
+      *fLog << err << "No argument in MHPedestalCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  MArrayF sumareahi(nareas);
+  MArrayF sumsectorhi(nsectors);
+  MArrayI numareahi(nareas);
+  MArrayI numsectorhi(nsectors);
+
+  for (UInt_t i=0; i<npixels; i++)
+  {
+
+      MHCalibrationPix &histhi = (*this)[i];
+
+      if (histhi.IsExcluded())
+          continue;
+
+      const MPedestalPix &ped = (*pedestal)[i];
+
+      const Float_t pedes = ped.GetPedestal();
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      histhi.FillHistAndArray(pedes) ;
+
+      fSum[i]            += pedes;
+      fAreaSum[aidx]     += pedes;
+      fSectorSum[sector] += pedes;      
+
+      const Float_t sqrsum  = pedes*pedes;
+      fSumSquare[i]            += sqrsum;
+      fAreaSumSquare[aidx]     += sqrsum;
+      fSectorSumSquare[sector] += sqrsum;      
+
+      sumareahi  [aidx]   += pedes;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += pedes;
+      numsectorhi[sector] ++;
+
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+    }
+  
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+    }
+  
+  fNumEvents++;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with Bad Pixels flags 0
+// 
+Bool_t MHPedestalCam::FinalizeHists()
+{
+  
+  if (fNumEvents <= 1)
+    {
+      *fLog << err << GetDescriptor()
+            << ": Number of processed events smaller or equal to 1" << endl;
+      return kFALSE;
+    }
+  
+  FitHists();
+
+  if (fRenorm)
+    RenormResults();
+
+  return kTRUE;
+  
+}
+
+void MHPedestalCam::FitHists()
+{
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHPedestalPix &hist = (MHPedestalPix&)(*this)[i];
+      MCalibrationPix &pix   = (*fCam)[i];
+      
+      //
+      // 1) Store calculated means and variances in the low-gain slices
+      //
+      pix.SetLoGainMean    ( fSum[i] / fNumEvents  );
+      const Double_t diff = fSumSquare[i] - fSum[i]*fSum[i]/fNumEvents;
+      pix.SetLoGainSigma   ( diff > 0. ? TMath::Sqrt( diff / (fNumEvents-1) ) : 0.);
+      pix.SetLoGainMeanVar ( pix.GetLoGainSigma() * pix.GetLoGainSigma() / fNumEvents  );
+      pix.SetLoGainSigmaVar( pix.GetLoGainMeanVar() / 4. );
+
+      if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+        continue;
+      
+      //
+      // 2) Fit the Hi Gain histograms with a Gaussian
+      //
+      //      if (i%100)
+      //        hist.FitTripleGaus();
+      //      else
+      TH1F *gaush = hist.GetHGausHist();
+      hist.FitGaus("RQ0",fFitStart,gaush->GetBinCenter(gaush->GetXaxis()->GetLast()));
+      //
+      // 4) Check for oscillations
+      // 
+      if (IsOscillations())
+        hist.CreateFourierSpectrum();
+      //
+      // 5) Retrieve the results and store them in this class
+      //
+      pix.SetHiGainMean       ( hist.GetMean()      );
+      pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+      pix.SetHiGainRms        ( hist.GetHistRms()   );
+      pix.SetHiGainSigma      ( hist.GetSigma()     );
+      pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+      pix.SetHiGainProb       ( hist.GetProb()      );
+      pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+      pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageHiGainArea(j);      
+      MCalibrationPix  &pix  = fCam->GetAverageArea(j);
+
+      if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+        continue;
+      
+      //
+      // 2) Fit the Hi Gain histograms with a Gaussian
+      //
+      TH1F *gaush = hist.GetHGausHist();
+      hist.FitGaus("RQ0",fFitStart,gaush->GetBinCenter(gaush->GetXaxis()->GetLast()));
+      //
+      // 4) Check for oscillations
+      // 
+      if (IsOscillations())
+        hist.CreateFourierSpectrum();
+      //
+      // 5) Retrieve the results and store them in this class
+      //
+      pix.SetHiGainMean       ( hist.GetMean()      );
+      pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+      pix.SetHiGainRms        ( hist.GetHistRms()   );
+      pix.SetHiGainSigma      ( hist.GetSigma()     );
+      pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+      pix.SetHiGainProb       ( hist.GetProb()      );
+      pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+      pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+      //
+      // 6) Store calculated means and variances in the low-gain slices
+      //
+      const ULong_t aevts = fNumEvents * fAreaNum[j];
+      if (aevts <= 1)
+        continue;
+
+      pix.SetLoGainMean ( fAreaSum[j] / aevts  );
+      const Double_t diff = fAreaSumSquare[j] - fAreaSum[j]*fAreaSum[j]/aevts ;
+      pix.SetLoGainSigma( diff > 0. ? TMath::Sqrt( diff / (aevts-1) ) : 0.);
+    }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);      
+      MCalibrationPix  &pix  = fCam->GetAverageSector(j);
+
+      if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+        continue;
+      
+      //
+      // 2) Fit the Hi Gain histograms with a Gaussian
+      //
+      TH1F *gaush = hist.GetHGausHist();
+      hist.FitGaus("RQ0",fFitStart,gaush->GetBinCenter(gaush->GetXaxis()->GetLast()));
+      //
+      // 4) Check for oscillations
+      // 
+      if (IsOscillations())
+        hist.CreateFourierSpectrum();
+      //
+      // 5) Retrieve the results and store them in this class
+      //
+      pix.SetHiGainMean       ( hist.GetMean()      );
+      pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+      pix.SetHiGainRms        ( hist.GetHistRms()   );
+      pix.SetHiGainSigma      ( hist.GetSigma()     );
+      pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+      pix.SetHiGainProb       ( hist.GetProb()      );
+      pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+      pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+      //
+      // 6) Store calculated means and variances in the low-gain slices
+      //
+      const ULong_t sevts = fNumEvents * fSectorNum[j];
+      if (sevts <= 1)
+        continue;
+
+      pix.SetLoGainMean ( fSectorSum[j] / sevts  );
+      const Double_t diff = fSectorSumSquare[j] - fSectorSum[j]*fSectorSum[j]/sevts ;
+      pix.SetLoGainSigma( diff > 0. ? TMath::Sqrt( diff / (sevts-1) ) : 0.);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Renormalizes the pedestal fit results by the following formulae:
+//
+// - Mean Pedestal        / slice -> Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice -> Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice -> Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice -> Sigma Pedestal Error / Sqrt (Number slices)
+// 
+void MHPedestalCam::RenormResults()
+{
+
+  //
+  // One never knows...
+  //
+  if (fExtractHiGainSlices <= 0)
+    return;
+
+  const Float_t sqslices = TMath::Sqrt(fExtractHiGainSlices);
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MCalibrationPix &pix = (*fCam)[i];
+      MPedestalPix    &ped = (*fPedestalsOut)[i];
+      pix.SetHiGainMean     ( pix.GetHiGainMean()     / fExtractHiGainSlices  );
+      pix.SetLoGainMean     ( pix.GetLoGainMean()     / fExtractHiGainSlices  );
+
+      ped.SetPedestal(pix.GetHiGainMean());
+      //
+      // Mean error goes with PedestalRMS/Sqrt(entries) -> scale with sqrt(slices)
+      // 
+      pix.SetHiGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices );
+      pix.SetLoGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices );
+
+      //
+      // Sigma goes like PedestalRMS -> scale with sqrt(slices)    
+      //
+      pix.SetHiGainSigma    ( pix.GetHiGainSigma()    / sqslices  );
+      pix.SetLoGainSigma    ( pix.GetLoGainSigma()    / sqslices  );
+
+      ped.SetPedestalRms(pix.GetHiGainSigma());
+      //
+      // Sigma error goes like PedestalRMS/2.(entries) -> scale with sqrt(slices)
+      //
+      pix.SetHiGainSigmaVar ( pix.GetHiGainSigmaVar() / fExtractHiGainSlices );
+      pix.SetLoGainSigmaVar ( pix.GetLoGainSigmaVar() / fExtractHiGainSlices );
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MCalibrationPix  &pix  = fCam->GetAverageArea(j);
+      pix.SetHiGainMean     ( pix.GetHiGainMean()     / fExtractHiGainSlices  );
+      pix.SetLoGainMean     ( pix.GetLoGainMean()     / fExtractHiGainSlices  );
+      pix.SetHiGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices  );
+      pix.SetHiGainSigma    ( pix.GetHiGainSigma()    / sqslices  );
+      pix.SetLoGainSigma    ( pix.GetLoGainSigma()    / sqslices  );
+      pix.SetHiGainSigmaVar ( pix.GetHiGainSigmaVar() / fExtractHiGainSlices  );
+  }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      MCalibrationPix  &pix  = fCam->GetAverageSector(j);
+      pix.SetHiGainMean     ( pix.GetHiGainMean()     / fExtractHiGainSlices  );
+      pix.SetLoGainMean     ( pix.GetLoGainMean()     / fExtractHiGainSlices  );
+      pix.SetHiGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices  );
+      pix.SetHiGainSigma    ( pix.GetHiGainSigma()    / sqslices  );
+      pix.SetLoGainSigma    ( pix.GetLoGainSigma()    / sqslices  );
+      pix.SetHiGainSigmaVar ( pix.GetHiGainSigmaVar() / fExtractHiGainSlices  );
+    }
+
+}
+
+
+// ------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Charge
+// 1: Error of fitted Charge
+// 2: Sigma of fitted Charge
+// 3: Error of Sigma of fitted Charge
+//
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Charge distribution
+// 5: Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 6: Error of the Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 7: Relative difference of the error of the mean pedestal (per slice) - calculated and fitted
+// 8: Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 9: Error of Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 10: Relative difference of the error of the pedestal RMS (per slice) - calculated and fitted
+//
+// Localized defects:
+// ==================
+//
+// 11: Gaus fit not OK
+// 12: Fourier spectrum not OK
+//
+Bool_t MHPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  if ((*this)[idx].IsExcluded())
+    return kFALSE;
+
+  const MPedestalPix &ppix = (*fPedestalsOut)[idx];
+
+  const Float_t ped = ppix.GetPedestal();
+  const Float_t rms = ppix.GetPedestalRms();
+
+  const Float_t entsqr =  TMath::Sqrt((Float_t)fPedestalsOut->GetNumSlices()*ppix.GetNumEvents());
+
+  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: branches/Mars_McMismatchStudy/mhcalib/MHPedestalCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHPedestalCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHPedestalCam.h	(revision 17960)
@@ -0,0 +1,82 @@
+#ifndef MARS_MHPedestalCam
+#define MARS_MHPedestalCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MGeomCam;
+class MPedestalCam;
+class MHPedestalCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Int_t   fgNbins;           //! Default number of bins        (now set to: 100  )
+  static const Axis_t  fgFirst;           //! Default lower histogram limit (now set to: -50. )
+  static const Axis_t  fgLast;            //! Default upper histogram limit (now set to:  50. )
+                                           
+  static const TString gsHistName;        //! Default Histogram names
+  static const TString gsHistTitle;       //! Default Histogram titles
+  static const TString gsHistXTitle;      //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;      //! Default Histogram y-axis titles
+
+  static const TString fgNamePedestalCam; //! "MPedestalCam"
+  
+  TString fNamePedestalCamOut;            // Name of the 'MPedestalCam' container with results
+
+  ULong_t fNumEvents;                     // Number of processed events
+  
+  Float_t fExtractHiGainSlices;           // Number of FADC slices used for high gain signal extraction
+  Float_t fExtractLoGainSlices;           // Number of FADC slices used for low  gain signal extraction
+
+  MPedestalCam *fPedestalsOut;            //! Pedestal Cam with results
+   
+  Bool_t  fRenorm;                        // Flag if the results will be re-normalized
+
+  Axis_t  fFitStart;                      // Charge value to start the fitting procedure
+  
+  MArrayD fSum;                           //! sum of values  
+  MArrayD fSumSquare;                     //! sum of squared values
+  MArrayD fAreaSum;                       //! averaged sum of values per area idx
+  MArrayD fAreaSumSquare;                 //! averaged sum of squared values per area idx
+  MArrayI fAreaNum;                       //! number of valid pixel with area idx
+  MArrayI fSectorNum;                     //! number of valid pixel with sector idx
+  MArrayD fSectorSum;                     //! averaged sum of values per sector
+  MArrayD fSectorSumSquare;               //! averaged sum of squared values per sector
+  
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  
+  void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  
+  void RenormResults();
+  void FitHists();
+
+public:
+
+  MHPedestalCam(const char *name=NULL, const char *title=NULL);
+
+ // Clone
+  TObject *Clone(const char *name="") const;
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  void ResetHists();
+
+  void SetFitStart          ( const Axis_t a=-0.5  ) { fFitStart = a;  }
+  void SetNamePedestalCamOut( const char *name     ) { fNamePedestalCamOut = name; }
+  void SetPedestalsOut      ( MPedestalCam *cam    ) { fPedestalsOut = cam; }
+  void SetRenorm            ( const Bool_t b=kTRUE ) { fRenorm = b; }
+  
+  ClassDef(MHPedestalCam, 1)	// Histogram class for Charge Camera Pedestals 
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhcalib/MHPedestalPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHPedestalPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHPedestalPix.cc	(revision 17960)
@@ -0,0 +1,238 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHPedestalPix
+//
+//  A base class for events which are believed to follow a Gaussian distribution 
+//  with time, e.g. calibration events, observables containing white noise, ...
+//
+//  MHPedestalPix derives from MHGausEvents, thus all features of 
+//  MHGausEvents can be used by a class deriving from MHPedestalPix
+//
+//  As an additional feature to MHGausEvents, this class offers to skip the fitting 
+//  to set mean, sigma and its errors directly from the histograms with the function 
+//  BypassFit()
+//
+//  See also: MHGausEvents
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalPix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TGraph.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHPedestalPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+MHPedestalPix::MHPedestalPix(const char *name, const char *title)
+{ 
+
+  fName  = name  ? name  : "MHPedestalPix";
+  fTitle = title ? title : "Pedestal histogram events";
+
+}
+
+// -------------------------------------------------------------------------------
+//
+// Fits the histogram to a double Gauss.
+//
+//
+Bool_t MHPedestalPix::FitDoubleGaus(const Double_t xmin, const Double_t xmax, Option_t *option)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  StripZeros(&fHGausHist,0);
+  
+  TAxis *axe = fHGausHist.GetXaxis();
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetFirst()) : xmin;
+  Axis_t rmax = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetLast())  : xmax;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Stat_t   entries     = fHGausHist.Integral(axe->FindBin(rmin),axe->FindBin(rmax),"width");
+  const Double_t sigma_guess = fHGausHist.GetRMS();
+  const Double_t area_guess  = entries/TMath::Sqrt(TMath::TwoPi())/sigma_guess;
+
+  fFGausFit = new TF1("GausFit","gaus(0)+gaus(3)",rmin,rmax);
+
+  if (!fFGausFit) 
+    {
+    *fLog << warn << dbginf << "WARNING: Could not create fit function for Gauss fit " 
+          << "in: " << fName << endl;
+    return kFALSE;
+    }
+  
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+
+  fFGausFit->SetParameters(area_guess/2.,0.,sigma_guess/2.,area_guess/2.,25.,sigma_guess/2.);
+  fFGausFit->SetParNames("Area_{0}","#mu_{0}","#sigma_{0}","Area_{1}","#mu_{1}","#sigma_{1}");
+  fFGausFit->SetParLimits(0,0.,area_guess*5.);
+  fFGausFit->SetParLimits(1,rmin,0.);
+  fFGausFit->SetParLimits(2,0.,rmax-rmin);
+  fFGausFit->SetParLimits(3,0.,area_guess*10.);
+  fFGausFit->SetParLimits(4,0.,rmax/2.);
+  fFGausFit->SetParLimits(5,0.,rmax-rmin);
+  fFGausFit->SetRange(rmin,rmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  SetMean     (fFGausFit->GetParameter(4)-fFGausFit->GetParameter(1));
+  SetSigma    (TMath::Sqrt(fFGausFit->GetParameter(5)*fFGausFit->GetParameter(5)
+                           +fFGausFit->GetParameter(2)*fFGausFit->GetParameter(2)));
+  SetMeanErr  (TMath::Sqrt(fFGausFit->GetParError(4)*fFGausFit->GetParError(4)
+                           +fFGausFit->GetParError(1)*fFGausFit->GetParError(1)));
+  SetSigmaErr (TMath::Sqrt(fFGausFit->GetParError(5)*fFGausFit->GetParError(5)
+                           +fFGausFit->GetParError(2)*fFGausFit->GetParError(2)));
+  SetProb     (fFGausFit->GetProb());
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 3) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  // !Finitite means either infinite or not-a-number
+  if (   !TMath::Finite(GetMean())
+      || !TMath::Finite(GetMeanErr())
+      || !TMath::Finite(GetProb())
+      || !TMath::Finite(GetSigma())
+      || !TMath::Finite(GetSigmaErr())
+      || fProb < GetProbLimit())
+    return kFALSE;
+  
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+}
+
+  
+// -------------------------------------------------------------------------------
+//
+// Fits the histogram to a triple Gauss.
+//
+Bool_t MHPedestalPix::FitTripleGaus(const Double_t xmin, const Double_t xmax, Option_t *option)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  StripZeros(&fHGausHist,0);
+  
+  TAxis *axe = fHGausHist.GetXaxis();
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetFirst()) : xmin;
+  Axis_t rmax = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetLast())  : xmax;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Stat_t   entries     = fHGausHist.Integral(axe->FindBin(rmin),axe->FindBin(rmax),"width");
+  const Double_t sigma_guess = fHGausHist.GetRMS();
+  const Double_t area_guess  = entries/TMath::Sqrt(TMath::TwoPi())/sigma_guess;
+
+  fFGausFit = new TF1("GausFit","gaus(0)+gaus(3)+gaus(6)",rmin,rmax);
+
+  if (!fFGausFit) 
+    {
+    *fLog << warn << dbginf << "WARNING: Could not create fit function for Gauss fit " 
+          << "in: " << fName << endl;
+    return kFALSE;
+    }
+  
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+
+  fFGausFit->SetParameters(10.,-4.0,1.5,70.,1.5,6.,5.,7.,7.);
+  fFGausFit->SetParNames("Area_{0}","#mu_{0}","#sigma_{0}","Area_{1}","#mu_{1}","#sigma_{1}","Area_{2}","#mu_{2}","#sigma_{2}");
+  fFGausFit->SetParLimits(0,0.,area_guess*2.5);
+  fFGausFit->SetParLimits(1,-9.0,-2.2);
+  fFGausFit->SetParLimits(2,-1.0,15.);
+  fFGausFit->SetParLimits(3,0.,area_guess*10.);
+  fFGausFit->SetParLimits(4,-4.5,2.);
+  fFGausFit->SetParLimits(5,0.,(rmax-rmin)/3.);
+  fFGausFit->SetParLimits(6,0.,area_guess*5.);
+  fFGausFit->SetParLimits(7,6.,20.);
+  fFGausFit->SetParLimits(8,5.,40.);
+  fFGausFit->SetRange(rmin,rmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  SetMean     (fFGausFit->GetParameter(4)-fFGausFit->GetParameter(1));
+  SetSigma    (TMath::Sqrt(fFGausFit->GetParameter(5)*fFGausFit->GetParameter(5)
+                           +fFGausFit->GetParameter(2)*fFGausFit->GetParameter(2)));
+  SetMeanErr  (TMath::Sqrt(fFGausFit->GetParError(4)*fFGausFit->GetParError(4)
+                           +fFGausFit->GetParError(1)*fFGausFit->GetParError(1)));
+  SetSigmaErr (TMath::Sqrt(fFGausFit->GetParError(5)*fFGausFit->GetParError(5)
+                           +fFGausFit->GetParError(2)*fFGausFit->GetParError(2)));
+  SetProb     (fFGausFit->GetProb());
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 3) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  // !Finitite means either infinite or not-a-number
+  if (   !TMath::Finite(GetMean())
+      || !TMath::Finite(GetMeanErr())
+      || !TMath::Finite(GetProb())
+      || !TMath::Finite(GetSigma())
+      || !TMath::Finite(GetSigmaErr())
+      || fProb < GetProbLimit() )
+    return kFALSE;
+  
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+}
+
+  
Index: branches/Mars_McMismatchStudy/mhcalib/MHPedestalPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/MHPedestalPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/MHPedestalPix.h	(revision 17960)
@@ -0,0 +1,25 @@
+#ifndef MARS_MHPedestalPix
+#define MARS_MHPedestalPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+class MHPedestalPix : public MHCalibrationPix
+{
+public:
+
+  MHPedestalPix(const char* name=NULL, const char* title=NULL);
+
+    // Fits
+  Bool_t FitDoubleGaus(  const Double_t xmin=0., 
+                         const Double_t xmax=0.,
+                         Option_t *option="RQ0");   
+  Bool_t FitTripleGaus(  const Double_t xmin=0., 
+                         const Double_t xmax=0.,
+                         Option_t *option="RQ0");   
+
+  ClassDef(MHPedestalPix, 1) // Base class for histogrammed pedestal events 
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhcalib/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mhcalib/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhcalib/Makefile	(revision 17960)
@@ -0,0 +1,54 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HCalib
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase  -I../mgui -I../mgeom -I../mhbase -I../mcalib \
+           -I../manalysis -I../mraw -I../mtools -I../mmc -I../mhist  \
+           -I../mimage -I../msignal -I../mbadpixels -I../mpedestal 
+
+# mhbase:    MBinning MH 
+# mgui:      MCamEvent (McalibrationCam)
+# mgeom:     MGeomCam (McalibrationCam - necessary?)
+# mcalib:    MCalibration*Cam
+# manalysis: MExtractedSignal, MCerPhotEvt (move to mcalib?)
+# mraw:      MRawRunHeader, MRawEvtHeader, MRawEvtPixelIter (3xMCalibrationCalc)
+# mmc:       MMcFadcHeader, MMcEvt
+# mimage     MHillas
+
+SRCFILES = MHCalibrationCam.cc \
+           MHCalibrationPix.cc \
+           MHCalibrationChargeCam.cc \
+           MHCalibrationChargePix.cc \
+           MHCalibrationChargeBlindCam.cc \
+           MHCalibrationChargeBlindPix.cc \
+           MHCalibrationChargePINDiode.cc \
+           MHCalibrationRelTimeCam.cc \
+           MHCalibrationPulseTimeCam.cc \
+	   MHGausEvents.cc 
+
+#           MHPedestalCam.cc \
+#           MHPedestalPix.cc \
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mhflux/FluxIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/FluxIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/FluxIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mhflux/FluxLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/FluxLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/FluxLinkDef.h	(revision 17960)
@@ -0,0 +1,22 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MAlphaFitter+;
+
+#pragma link C++ class MHPhi+;
+#pragma link C++ class MHDisp+;
+#pragma link C++ class MHAlpha+;
+//#pragma link C++ class MHAlphaTime+;
+#pragma link C++ class MHThetaSq+;
+#pragma link C++ class MHThetaSqN+;
+#pragma link C++ class MHEnergyEst+;
+#pragma link C++ class MHFalseSource+;
+#pragma link C++ class MHEffectiveOnTime+;
+#pragma link C++ class MHCollectionArea+;
+#pragma link C++ class MHThreshold+;
+#pragma link C++ class MMcSpectrumWeight+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MAlphaFitter.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MAlphaFitter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MAlphaFitter.cc	(revision 17960)
@@ -0,0 +1,977 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MAlphaFitter
+//
+// Create a single Alpha-Plot. The alpha-plot is fitted online. You can
+// check the result when it is filles in the MStatusDisplay
+// For more information see MHFalseSource::FitSignificance
+//
+// For convinience (fit) the output significance is stored in a
+// container in the parlisrt
+//
+// Version 2:
+// ----------
+//  + Double_t fSignificanceExc;  // significance of a known excess
+//
+// Version 3:
+// ----------
+//  + TArrayD fErrors;  // errors of coefficients
+//
+// Version 4:
+// ----------
+//  + Double_t fErrorExcess;
+//  - Double_t fSignificanceExc;
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAlphaFitter.h"
+
+#include <TF1.h>
+#include <TH1.h>
+#include <TH3.h>
+
+#include <TRandom.h>
+#include <TFeldmanCousins.h>
+
+#include <TLine.h>
+#include <TLatex.h>
+#include <TVirtualPad.h>
+
+#include "MMath.h"
+#include "MString.h"
+
+#include "MLogManip.h"
+
+ClassImp(MAlphaFitter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MAlphaFitter::MAlphaFitter(const char *name, const char *title) : fSigInt(15),
+    fSigMax(75), fBgMin(45), fBgMax(85), fScaleMin(40), fScaleMax(80),
+    fPolynomOrder(2), fFitBackground(kTRUE), fFunc(0),
+    fScaleMode(kOffRegion), fScaleUser(1), fStrategy(kSignificance)
+{
+    fName  = name  ? name  : "MAlphaFitter";
+    fTitle = title ? title : "Fit alpha";
+
+    SetSignalFunction(kGauss);
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor
+//
+MAlphaFitter::~MAlphaFitter()
+{
+    delete fFunc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Re-initializes fFunc either according to SignalFunc_t
+//
+void MAlphaFitter::SetSignalFunction(SignalFunc_t func)
+{
+    if (gROOT->GetListOfFunctions()->FindObject(""))
+    {
+        gLog << err << "MAlphaFitter::SetSignalFunction -- '' found!" << endl;
+        return;
+    }
+
+    delete fFunc;
+    fFunc = 0;
+
+    switch (func)
+    {
+    case kGauss:
+        fFunc=new TF1("", MString::Format("gaus(0) + pol%d(3)", fPolynomOrder).Data());
+        break;
+    case kThetaSq:
+        if (fPolynomOrder>0)
+            fPolynomOrder = 1;
+        fFunc=new TF1("", "[0]*exp(-0.5*((sqrt(x)-[1])/[2])^2) + expo(3)");
+        break;
+    }
+
+    fSignalFunc=func;
+
+    fFunc->SetName("Dummy");
+    gROOT->GetListOfFunctions()->Remove(fFunc);
+
+    fCoefficients.Set(3+fPolynomOrder+1);
+    fCoefficients.Reset();
+
+    fErrors.Set(3+fPolynomOrder+1);
+    fErrors.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset variables which belong to results. Reset the arrays.
+//
+void MAlphaFitter::Clear(Option_t *o)
+{
+    fSignificance=0;
+    fErrorExcess=0;
+    fEventsExcess=0;
+    fEventsSignal=0;
+    fEventsBackground=0;
+
+    fChiSqSignal=0;
+    fChiSqBg=0;
+    fIntegralMax=0;
+    fScaleFactor=1;
+
+    fCoefficients.Reset();
+    fErrors.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns fFunc->Eval(d) or 0 if fFunc==NULL
+//
+Double_t MAlphaFitter::Eval(Double_t d) const
+{
+    return fFunc ? fFunc->Eval(d) : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function implementes the fit to the off-data as used in Fit()
+//
+Bool_t MAlphaFitter::FitOff(TH1D &h, Int_t paint)
+{
+    if (h.GetEntries()==0)
+        return kFALSE;
+
+    // First fit a polynom in the off region
+    fFunc->FixParameter(0, 0);
+    fFunc->FixParameter(1, 0);
+    fFunc->FixParameter(2, 1);
+    fFunc->ReleaseParameter(3);
+    if (fPolynomOrder!=1)
+        fFunc->FixParameter(4, 0);
+
+    for (int i=5; i<fFunc->GetNpar(); i++)
+        if (fFitBackground)
+            fFunc->ReleaseParameter(i);
+        else
+            fFunc->SetParameter(i, 0);
+
+    if (!fFitBackground)
+        return kTRUE;
+
+    if (fSignalFunc==kThetaSq)
+    {
+        const Double_t sum = h.Integral(1, 3)/3;
+        const Double_t a   = sum<=1 ? 0 : TMath::Log(sum);
+        const Double_t b   = -1.7;
+
+        // Do a best-guess
+        fFunc->SetParameter(3, a);
+        fFunc->SetParameter(4, b);
+    }
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    //           E  Perform better Errors estimation using Minos technique
+    if (h.Fit(fFunc, "NQI", "", fBgMin, fBgMax))
+        return kFALSE;
+
+    fChiSqBg = fFunc->GetChisquare()/fFunc->GetNDF();
+
+    fCoefficients.Set(fFunc->GetNpar(), fFunc->GetParameters());
+    fErrors.Set(fFunc->GetNpar());
+    for (int i=3; i<fFunc->GetNpar(); i++)
+        fErrors[i] = fFunc->GetParError(i);
+
+    // ------------------------------------
+
+    if (paint)
+    {
+        if (paint==2)
+        {
+            fFunc->SetLineColor(kBlack);
+            fFunc->SetLineWidth(1);
+        }
+        else
+        {
+            fFunc->SetRange(0, 90);
+            fFunc->SetLineColor(kRed);
+            fFunc->SetLineWidth(2);
+        }
+        fFunc->Paint("same");
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the result of the fit and set the corresponding data members
+//
+void MAlphaFitter::FitResult(const TH1D &h)
+{
+    const Double_t alphaw = h.GetXaxis()->GetBinWidth(1);
+
+    const Int_t bin = h.GetXaxis()->FindFixBin(fSigInt*0.999);
+
+    fIntegralMax      = h.GetBinLowEdge(bin+1);
+    fEventsBackground = fFunc->Integral(0, fIntegralMax)/alphaw;
+    fEventsSignal     = h.Integral(1, bin);
+    fEventsExcess     = fEventsSignal-fEventsBackground;
+    fSignificance     = MMath::SignificanceLiMaSigned(fEventsSignal, fEventsBackground);
+    fErrorExcess      = MMath::ErrorExc(fEventsSignal, fEventsBackground);
+
+    // !Finitite includes IsNaN
+    if (!TMath::Finite(fSignificance))
+        fSignificance=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a preliminary implementation of a alpha-fit procedure for
+// all possible source positions. It will be moved into its own
+// more powerfull class soon.
+//
+// The fit function is "gaus(0)+pol2(3)" which is equivalent to:
+//   [0]*exp(-0.5*((x-[1])/[2])^2) + [3] + [4]*x + [5]*x^2
+// or
+//   A*exp(-0.5*((x-mu)/sigma)^2) + a + b*x + c*x^2
+//
+// Parameter [1] is fixed to 0 while the alpha peak should be
+// symmetric around alpha=0.
+//
+// Parameter [4] is fixed to 0 because the first derivative at
+// alpha=0 should be 0, too.
+//
+// In a first step the background is fitted between bgmin and bgmax,
+// while the parameters [0]=0 and [2]=1 are fixed.
+//
+// In a second step the signal region (alpha<sigmax) is fittet using
+// the whole function with parameters [1], [3], [4] and [5] fixed.
+//
+// The number of excess and background events are calculated as
+//   s = int(hist,    0, 1.25*sigint)
+//   b = int(pol2(3), 0, 1.25*sigint)
+//
+// The Significance is calculated using the Significance() member
+// function.
+//
+Bool_t MAlphaFitter::Fit(TH1D &h, Bool_t paint)
+{
+    Clear();
+
+    // Check for the region which is not filled...
+    // if (alpha0==0)
+    //     return kFALSE;
+
+    // Perform fit to the off-data
+    if (!FitOff(h, paint))
+        return kFALSE;
+
+    fFunc->ReleaseParameter(0);  // It is also released by SetParLimits later on
+    //func.ReleaseParameter(1);  // It is also released by SetParLimits later on
+    fFunc->ReleaseParameter(2);
+    for (int i=3; i<fFunc->GetNpar(); i++)
+        fFunc->FixParameter(i, fFunc->GetParameter(i));
+
+
+    // Do not allow signals smaller than the background
+    const Double_t alpha0 = h.GetBinContent(1);
+    const Double_t s      = fSignalFunc==kGauss ? fFunc->GetParameter(3) : TMath::Exp(fFunc->GetParameter(3));
+    const Double_t A      = alpha0-s;
+    //const Double_t dA     = TMath::Abs(A);
+    //fFunc->SetParLimits(0, -dA*4, dA*4);  // SetParLimits also releases the parameter
+    fFunc->SetParLimits(2, 0, 90);        // SetParLimits also releases the parameter
+
+    // Now fit a gaus in the on region on top of the polynom
+    fFunc->SetParameter(0, A);
+    fFunc->SetParameter(2, fSigMax*0.75);
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    //           E  Perform better Errors estimation using Minos technique
+    h.Fit(fFunc, "NQI", "", 0, fSigMax);
+
+    fChiSqSignal = fFunc->GetChisquare()/fFunc->GetNDF();
+    fCoefficients.Set(fFunc->GetNpar(), fFunc->GetParameters());
+    for (int i=0; i<3; i++)
+        fErrors[i] = fFunc->GetParError(i);
+    //const Bool_t ok = NDF>0 && chi2<2.5*NDF;
+
+    // ------------------------------------
+    if (paint)
+    {
+        fFunc->SetLineColor(kGreen);
+        fFunc->SetLineWidth(2);
+        fFunc->Paint("same");
+    }
+    // ------------------------------------
+
+    //const Double_t s = fFunc->Integral(0, fSigInt)/alphaw;
+    fFunc->SetParameter(0, 0);
+    fFunc->SetParameter(2, 1);
+    //const Double_t b = fFunc->Integral(0, fSigInt)/alphaw;
+    //fSignificance = MMath::SignificanceLiMaSigned(s, b);
+
+    // Calculate the fit result and set the corresponding data members
+    FitResult(h);
+
+    return kTRUE;
+}
+
+Double_t MAlphaFitter::DoOffFit(const TH1D &hon, const TH1D &hof, Bool_t paint)
+{
+    if (fSignalFunc!=kThetaSq)
+        return 0;
+
+    // ----------------------------------------------------------------------------
+
+    const Int_t bin = hon.GetXaxis()->FindFixBin(fSigInt*0.999);
+
+    MAlphaFitter fit(*this);
+    fit.EnableBackgroundFit();
+    fit.SetBackgroundFitMin(0);
+
+    // produce a histogram containing the off-samples from on-source and
+    // off-source in the off-source region and the on-data in the source-region
+    TH1D h(hof);
+    h.SetDirectory(0);
+    h.Add(&hon);
+
+    h.Scale(0.5);
+    for (int i=1; i<=bin+3; i++)
+    {
+        h.SetBinContent(i, hof.GetBinContent(i));
+        h.SetBinError(  i, hof.GetBinError(i));
+    }
+
+    // Now fit the off-data
+    if (!fit.FitOff(h, paint?2:0)) // FIXME: Show fit!
+        return -1;
+
+    // Calculate fit-result
+    fit.FitResult(h);
+
+    // Do a gaussian error propagation to calculated the error of
+    // the background estimated from the fit
+    const Double_t ea = fit.fErrors[3];
+    const Double_t eb = fit.fErrors[4];
+    const Double_t a  = fit.fCoefficients[3];
+    const Double_t b  = fit.fCoefficients[4];
+
+    const Double_t t  = fIntegralMax;
+
+    const Double_t ex  = TMath::Exp(t*b);
+    const Double_t eab = TMath::Exp(a)/b;
+
+    const Double_t eA = ex-1;
+    const Double_t eB = t*ex - eA/b;
+
+    const Double_t w  = h.GetXaxis()->GetBinWidth(1);
+
+    // Error of estimated background
+    const Double_t er = TMath::Abs(eab)*TMath::Hypot(eA*ea, eB*eb)/w;
+
+    // Calculate arbitrary scale factor from propagated error from the
+    // condition: sqrt(alpha*background) = est.background/est.error
+    // const Double_t bg = hof.Integral(1, bin);
+    // const Double_t sc = bg * er*er / (fit2.GetEventsBackground()*fit2.GetEventsBackground());
+    // Assuming that bg and fit2.GetEventsBackground() are rather identical:
+    const Double_t sc = er*er / fit.fEventsBackground;
+
+
+    /*
+     cout << MMath::SignificanceLiMaSigned(hon.Integral(1, bin), fit.GetEventsBackground()/sc, sc) << " ";
+     cout << sc << " " << fit.GetEventsBackground() << " ";
+     cout << fit.fChiSqBg << endl;
+     */
+    return sc;
+}
+
+Bool_t MAlphaFitter::Fit(const TH1D &hon, const TH1D &hof, Double_t alpha, Bool_t paint)
+{
+    TH1D h(hon);
+    h.SetDirectory(0);
+    h.Add(&hof, -1); // substracts also number of entries!
+    h.SetEntries(hon.GetEntries());
+
+    MAlphaFitter fit(*this);
+    fit.SetPolynomOrder(0);
+    if (alpha<=0 || !fit.Fit(h, paint))
+        return kFALSE;
+
+    fChiSqSignal  = fit.fChiSqSignal;
+    fChiSqBg      = fit.fChiSqBg;
+    fCoefficients = fit.fCoefficients;
+    fErrors       = fit.fErrors;
+
+    // ----------------------------------------------------------------------------
+
+    const Double_t scale = DoOffFit(hon, hof, paint);
+    if (scale<0)
+        return kFALSE;
+
+    // ----------------------------------------------------------------------------
+
+    const Int_t bin = hon.GetXaxis()->FindFixBin(fSigInt*0.999);
+
+    fIntegralMax      = hon.GetBinLowEdge(bin+1);
+    fEventsBackground = hof.Integral(1, bin);
+    fEventsSignal     = hon.Integral(1, bin);
+    fEventsExcess     = fEventsSignal-fEventsBackground;
+    fScaleFactor      = alpha;
+    fSignificance     = MMath::SignificanceLiMaSigned(fEventsSignal, fEventsBackground/alpha, alpha);
+    fErrorExcess      = MMath::ErrorExc(fEventsSignal, fEventsBackground/alpha, alpha);
+
+    // !Finitite includes IsNaN
+    if (!TMath::Finite(fSignificance))
+        fSignificance=0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the upper limit for fEventsSignal number of observed events
+// and fEventsBackground number of background events.
+//
+// Therefor TFeldmanCousin is used.
+//
+// The Feldman-Cousins method as described in PRD V57 #7, p3873-3889
+//
+Double_t MAlphaFitter::CalcUpperLimit() const
+{
+    // get a FeldmanCousins calculation object with the default limits
+    // of calculating a 90% CL with the minimum signal value scanned
+    // = 0.0 and the maximum signal value scanned of 50.0
+    TFeldmanCousins f;
+    f.SetMuStep(0.05);
+    f.SetMuMax(100);
+    f.SetMuMin(0);
+    f.SetCL(90);
+
+    return f.CalculateUpperLimit(fEventsSignal, fEventsBackground);
+}
+
+void MAlphaFitter::PaintResult(Float_t x, Float_t y, Float_t size, Bool_t draw) const
+{
+    const Double_t w  = GetGausSigma();
+    const Double_t m  = fIntegralMax;
+
+    const Int_t    l1 = w<=0 ? 0 : (Int_t)TMath::Ceil(-TMath::Log10(w));
+    const Int_t    l2 = m<=0 ? 0 : (Int_t)TMath::Ceil(-TMath::Log10(m));
+    const TString fmt = MString::Format("\\sigma_{L/M}=%%.1f  \\omega=%%.%df\\circ  E=%%d B=%%d  x<%%.%df  \\tilde\\chi_{b}=%%.1f  \\tilde\\chi_{s}=%%.1f  c=%%.1f  f=%%.2f",
+                                        l1<1?1:l1+1, l2<1?1:l2+1);
+    const TString txt = MString::Format(fmt.Data(), fSignificance, w, (int)fEventsExcess,
+                                        (int)fEventsBackground, m, fChiSqBg, fChiSqSignal,
+                                        fCoefficients[3], fScaleFactor);
+
+    // This is totaly weired but the only way to get both options
+    // working with this nonsense implementation of TLatex
+    TLatex text(x, y, txt);
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(size);
+    if (draw)
+        text.DrawLatex(x, y, txt);
+    else
+        text.Paint();
+
+    TLine line;
+    line.SetLineColor(14);
+    if (draw)
+        line.DrawLine(m, gPad->GetUymin(), m, gPad->GetUymax());
+    else
+        line.PaintLine(m, gPad->GetUymin(), m, gPad->GetUymax());
+}
+
+void MAlphaFitter::Copy(TObject &o) const
+{
+    MAlphaFitter &f = static_cast<MAlphaFitter&>(o);
+
+    // Setup
+    f.fSigInt       = fSigInt;
+    f.fSigMax       = fSigMax;
+    f.fBgMin        = fBgMin;
+    f.fBgMax        = fBgMax;
+    f.fScaleMin     = fScaleMin;
+    f.fScaleMax     = fScaleMax;
+    f.fPolynomOrder = fPolynomOrder;
+    f.fFitBackground= fFitBackground;
+    f.fSignalFunc   = fSignalFunc;
+    f.fScaleMode    = fScaleMode;
+    f.fScaleUser    = fScaleUser;
+    f.fStrategy     = fStrategy;
+    f.fCoefficients.Set(fCoefficients.GetSize());
+    f.fCoefficients.Reset();
+    f.fErrors.Set(fCoefficients.GetSize());
+    f.fErrors.Reset();
+
+    // Result
+    f.fSignificance     = fSignificance;
+    f.fErrorExcess      = fErrorExcess;
+    f.fEventsExcess     = fEventsExcess;
+    f.fEventsSignal     = fEventsSignal;
+    f.fEventsBackground = fEventsBackground;
+    f.fChiSqSignal      = fChiSqSignal;
+    f.fChiSqBg          = fChiSqBg;
+    f.fIntegralMax      = fIntegralMax;
+    f.fScaleFactor      = fScaleFactor;
+
+    // Function
+    delete f.fFunc;
+
+    f.fFunc = new TF1(*fFunc);
+    f.fFunc->SetName("Dummy");
+    gROOT->GetListOfFunctions()->Remove(f.fFunc);
+}
+
+void MAlphaFitter::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": Fitting..." << endl;
+    *fLog << " ...signal to " << fSigMax << " (integrate into bin at " << fSigInt << ")" << endl;
+    *fLog << " ...signal function: ";
+    switch (fSignalFunc)
+    {
+    case kGauss:       *fLog << "gauss(x)/pol" << fPolynomOrder; break;
+    case kThetaSq:     *fLog << "gauss(sqrt(x))/expo";  break;
+    }
+    *fLog << endl;
+    if (!fFitBackground)
+        *fLog << " ...no background." << endl;
+    else
+    {
+        *fLog << " ...background from " << fBgMin << " to " << fBgMax << endl;
+        *fLog << " ...polynom order " << fPolynomOrder << endl;
+        *fLog << " ...scale mode: ";
+        switch (fScaleMode)
+        {
+        case kNone:        *fLog << "none.";         break;
+        case kEntries:     *fLog << "entries.";      break;
+        case kIntegral:    *fLog << "integral.";     break;
+        case kOffRegion:   *fLog << "off region (integral between " << fScaleMin << " and " << fScaleMax << ")"; break;
+        case kBackground:  *fLog << "background (integral between " << fBgMin    << " and " << fBgMax    << ")"; break;
+        case kLeastSquare: *fLog << "least square (N/A)"; break;
+        case kUserScale:   *fLog << "user def (" << fScaleUser << ")"; break;
+        }
+        *fLog << endl;
+    }
+
+    if (TString(o).Contains("result"))
+    {
+        *fLog << "Result:" << endl;
+        *fLog << " - Significance (Li/Ma)    " << fSignificance << endl;
+        *fLog << " - Excess Events           " << fEventsExcess << endl;
+        *fLog << " - Signal Events           " << fEventsSignal << endl;
+        *fLog << " - Background Events       " << fEventsBackground << endl;
+        *fLog << " - E/sqrt(B>=Alpha)        " << fEventsExcess/TMath::Sqrt(TMath::Max(fEventsBackground,fScaleFactor)) << endl;
+        *fLog << " - Chi^2/ndf (Signal)      " << fChiSqSignal << endl;
+        *fLog << " - Chi^2/ndf (Background)  " << fChiSqBg << endl;
+        *fLog << " - Signal integrated up to " << fIntegralMax << "°" << endl;
+        *fLog << " - Off Scale Alpha (Off)   " << fScaleFactor << endl;
+    }
+}
+
+Bool_t MAlphaFitter::FitEnergy(const TH3D &hon, UInt_t bin, Bool_t paint)
+{
+    const TString name(MString::Format("TempAlphaEnergy%06d", gRandom->Integer(1000000)));
+
+    TH1D *h = hon.ProjectionZ(name, 0, hon.GetNbinsX()+1, bin, bin, "E");
+    h->SetDirectory(0);
+
+    const Bool_t rc = Fit(*h, paint);
+
+    delete h;
+
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitTheta(const TH3D &hon, UInt_t bin, Bool_t paint)
+{
+    const TString name(MString::Format("TempAlphaTheta%06d", gRandom->Integer(1000000)));
+
+    TH1D *h = hon.ProjectionZ(name, bin, bin, 0, hon.GetNbinsY()+1, "E");
+    h->SetDirectory(0);
+
+    const Bool_t rc = Fit(*h, paint);
+
+    delete h;
+
+    return rc;
+}
+/*
+Bool_t MAlphaFitter::FitTime(const TH3D &hon, UInt_t bin, Bool_t paint)
+{
+    const TString name(Form("TempAlphaTime%06d", gRandom->Integer(1000000)));
+
+    hon.GetZaxis()->SetRange(bin,bin);
+    TH1D *h = (TH1D*)hon.Project3D("ye");
+    hon.GetZaxis()->SetRange(-1,-1);
+
+    h->SetDirectory(0);
+
+    const Bool_t rc = Fit(*h, paint);
+    delete h;
+    return rc;
+}
+*/
+Bool_t MAlphaFitter::FitAlpha(const TH3D &hon, Bool_t paint)
+{
+    const TString name(MString::Format("TempAlpha%06d", gRandom->Integer(1000000)));
+
+    TH1D *h = hon.ProjectionZ(name, 0, hon.GetNbinsX()+1, 0, hon.GetNbinsY()+1, "E");
+    h->SetDirectory(0);
+
+    const Bool_t rc = Fit(*h, paint);
+
+    delete h;
+
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitEnergy(const TH3D &hon, const TH3D &hof, UInt_t bin, Bool_t paint)
+{
+    const TString name1(MString::Format("TempAlpha%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(MString::Format("TempAlpha%06d_off", gRandom->Integer(1000000)));
+
+    TH1D *h1 = hon.ProjectionZ(name1, 0, hon.GetNbinsX()+1, bin, bin, "E");
+    h1->SetDirectory(0);
+
+    TH1D *h0 = hof.ProjectionZ(name0, 0, hof.GetNbinsX()+1, bin, bin, "E");
+    h0->SetDirectory(0);
+
+    const Bool_t rc = ScaleAndFit(*h1, h0, paint);
+
+    delete h0;
+    delete h1;
+
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitTheta(const TH3D &hon, const TH3D &hof, UInt_t bin, Bool_t paint)
+{
+    const TString name1(MString::Format("TempAlpha%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(MString::Format("TempAlpha%06d_off", gRandom->Integer(1000000)));
+
+    TH1D *h1 = hon.ProjectionZ(name1, bin, bin, 0, hon.GetNbinsY()+1, "E");
+    h1->SetDirectory(0);
+
+    TH1D *h0 = hof.ProjectionZ(name0, bin, bin, 0, hof.GetNbinsY()+1, "E");
+    h0->SetDirectory(0);
+
+    const Bool_t rc = ScaleAndFit(*h1, h0, paint);
+
+    delete h0;
+    delete h1;
+
+    return rc;
+}
+/*
+Bool_t MAlphaFitter::FitTime(const TH3D &hon, const TH3D &hof, UInt_t bin, Bool_t paint)
+{
+    const TString name1(Form("TempAlphaTime%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(Form("TempAlphaTime%06d_off", gRandom->Integer(1000000)));
+
+    hon.GetZaxis()->SetRange(bin,bin);
+    TH1D *h1 = (TH1D*)hon.Project3D("ye");
+    hon.GetZaxis()->SetRange(-1,-1);
+    h1->SetDirectory(0);
+
+    hof.GetZaxis()->SetRange(bin,bin);
+    TH1D *h0 = (TH1D*)hof.Project3D("ye");
+    hof.GetZaxis()->SetRange(-1,-1);
+    h0->SetDirectory(0);
+
+    const Bool_t rc = ScaleAndFit(*h1, h0, paint);
+
+    delete h0;
+    delete h1;
+
+    return rc;
+}
+*/
+
+Bool_t MAlphaFitter::FitAlpha(const TH3D &hon, const TH3D &hof, Bool_t paint)
+{
+    const TString name1(MString::Format("TempAlpha%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(MString::Format("TempAlpha%06d_off", gRandom->Integer(1000000)));
+
+    TH1D *h1 = hon.ProjectionZ(name1, 0, hon.GetNbinsX()+1, 0, hon.GetNbinsY()+1, "E");
+    h1->SetDirectory(0);
+
+    TH1D *h0 = hof.ProjectionZ(name0, 0, hof.GetNbinsX()+1, 0, hof.GetNbinsY()+1, "E");
+    h0->SetDirectory(0);
+
+    const Bool_t rc = ScaleAndFit(*h1, h0, paint);
+
+    delete h0;
+    delete h1;
+
+    return rc;
+}
+
+Bool_t MAlphaFitter::ApplyScaling(const TH3D &hon, TH3D &hof, UInt_t bin) const
+{
+    const TString name1(MString::Format("TempAlpha%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(MString::Format("TempAlpha%06d_off", gRandom->Integer(1000000)));
+
+    TH1D *h1 = hon.ProjectionZ(name1, 0, hon.GetNbinsX()+1, bin, bin, "E");
+    h1->SetDirectory(0);
+
+    TH1D *h0 = hof.ProjectionZ(name0, 0, hof.GetNbinsX()+1, bin, bin, "E");
+    h0->SetDirectory(0);
+
+    const Double_t scale = Scale(*h0, *h1);
+
+    delete h0;
+    delete h1;
+
+    for (int x=0; x<=hof.GetNbinsX()+1; x++)
+        for (int z=0; z<=hof.GetNbinsZ()+1; z++)
+        {
+            hof.SetBinContent(x, bin, z, hof.GetBinContent(x, bin, z)*scale);
+            hof.SetBinError(  x, bin, z, hof.GetBinError(  x, bin, z)*scale);
+        }
+
+    return scale>0;
+}
+
+Bool_t MAlphaFitter::ApplyScaling(const TH3D &hon, TH3D &hof) const
+{
+    for (int y=0; y<=hof.GetNbinsY()+1; y++)
+        ApplyScaling(hon, hof, y);
+
+    return kTRUE;
+}
+
+Double_t MAlphaFitter::Scale(TH1D &of, const TH1D &on) const
+{
+    Float_t scaleon = 1;
+    Float_t scaleof = 1;
+    switch (fScaleMode)
+    {
+    case kNone:
+        return 1;
+
+    case kEntries:
+        scaleon = on.GetEntries();
+        scaleof = of.GetEntries();
+        break;
+
+    case kIntegral:
+        scaleon = on.Integral();
+        scaleof = of.Integral();
+        break;
+
+    case kOffRegion:
+        {
+            const Int_t min = on.GetXaxis()->FindFixBin(fScaleMin);
+            const Int_t max = on.GetXaxis()->FindFixBin(fScaleMax);
+            scaleon = on.Integral(min, max);
+            scaleof = of.Integral(min, max);
+        }
+        break;
+
+    case kBackground:
+        {
+            const Int_t min = on.GetXaxis()->FindFixBin(fBgMin);
+            const Int_t max = on.GetXaxis()->FindFixBin(fBgMax);
+            scaleon = on.Integral(min, max);
+            scaleof = of.Integral(min, max);
+        }
+        break;
+
+    case kUserScale:
+        scaleon = fScaleUser;
+        break;
+
+        // This is just to make some compiler happy
+    default:
+        return 1;
+    }
+
+    if (scaleof!=0)
+    {
+        of.Scale(scaleon/scaleof);
+        return scaleon/scaleof;
+    }
+    else
+    {
+        of.Reset();
+        return 0;
+    }
+}
+
+Double_t MAlphaFitter::GetMinimizationValue() const
+{
+    switch (fStrategy)
+    {
+    case kSignificance:
+        return -GetSignificance();
+    case kSignificanceChi2:
+        return -GetSignificance()/GetChiSqSignal();
+    case kSignificanceLogExcess:
+        if (GetEventsExcess()<1)
+            return 0;
+        return -GetSignificance()*TMath::Log10(GetEventsExcess());
+    case kSignificanceSqrtExcess:
+        if (GetEventsExcess()<1)
+            return 0;
+        return -GetSignificance()*TMath::Sqrt(GetEventsExcess());
+    case kSignificanceExcess:
+        return -GetSignificance()*GetEventsExcess();
+    case kExcess:
+        return -GetEventsExcess();
+    case kGaussSigma:
+        return GetGausSigma();
+    case kWeakSource:
+        if (GetEventsExcess()<1)
+            return 0;
+        return -GetEventsExcess()/TMath::Sqrt(TMath::Max(GetEventsBackground(), GetEventsBackground()));
+    case kWeakSourceLogExcess:
+        if (GetEventsExcess()<1)
+            return 0;
+        return -GetEventsExcess()/TMath::Sqrt(TMath::Max(GetEventsBackground(), GetEventsBackground()))*TMath::Log10(GetEventsExcess());
+    }
+    return 0;
+}
+
+Int_t MAlphaFitter::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    //void SetScaleUser(Float_t scale)       { fScaleUser = scale; fScaleMode=kUserScale; }
+    //void SetScaleMode(ScaleMode_t mode)    { fScaleMode    = mode; }
+
+    if (IsEnvDefined(env, prefix, "SignalIntegralMax", print))
+    {
+        SetSignalIntegralMax(GetEnvValue(env, prefix, "SignalIntegralMax", fSigInt));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "SignalFitMax", print))
+    {
+        SetSignalIntegralMax(GetEnvValue(env, prefix, "SignalFitMax", fSigMax));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "BackgroundFitMax", print))
+    {
+        SetBackgroundFitMax(GetEnvValue(env, prefix, "BackgroundFitMax", fBgMax));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "BackgroundFitMin", print))
+    {
+        SetBackgroundFitMin(GetEnvValue(env, prefix, "BackgroundFitMin", fBgMin));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ScaleMin", print))
+    {
+        SetScaleMin(GetEnvValue(env, prefix, "ScaleMin", fScaleMin));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ScaleMax", print))
+    {
+        SetScaleMax(GetEnvValue(env, prefix, "ScaleMax", fScaleMax));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "PolynomOrder", print))
+    {
+        SetPolynomOrder(GetEnvValue(env, prefix, "PolynomOrder", fPolynomOrder));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "MinimizationStrategy", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "MinimizationStrategy", "");
+        txt = txt.Strip(TString::kBoth);
+        txt.ToLower();
+        if (txt==(TString)"significance")
+            fStrategy = kSignificance;
+        if (txt==(TString)"significancechi2")
+            fStrategy = kSignificanceChi2;
+        if (txt==(TString)"significanceexcess")
+            fStrategy = kSignificanceExcess;
+        if (txt==(TString)"excess")
+            fStrategy = kExcess;
+        if (txt==(TString)"gausssigma" || txt==(TString)"gaussigma")
+            fStrategy = kGaussSigma;
+        if (txt==(TString)"weaksource")
+            fStrategy = kWeakSource;
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Scale", print))
+    {
+        fScaleUser = GetEnvValue(env, prefix, "Scale", fScaleUser);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ScaleMode", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "ScaleMode", "");
+        txt = txt.Strip(TString::kBoth);
+        txt.ToLower();
+        if (txt==(TString)"none")
+            fScaleMode = kNone;
+        if (txt==(TString)"entries")
+            fScaleMode = kEntries;
+        if (txt==(TString)"integral")
+            fScaleMode = kIntegral;
+        if (txt==(TString)"offregion")
+            fScaleMode = kOffRegion;
+        if (txt==(TString)"background")
+            fScaleMode = kBackground;
+        if (txt==(TString)"leastsquare")
+            fScaleMode = kLeastSquare;
+        if (txt==(TString)"userscale")
+            fScaleMode = kUserScale;
+        if (txt==(TString)"fixed")
+            FixScale();
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "SignalFunction", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "SignalFunction", "");
+        txt = txt.Strip(TString::kBoth);
+        txt.ToLower();
+        if (txt==(TString)"gauss" || txt==(TString)"gaus")
+            SetSignalFunction(kGauss);
+        if (txt==(TString)"thetasq")
+            SetSignalFunction(kThetaSq);
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MAlphaFitter.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MAlphaFitter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MAlphaFitter.h	(revision 17960)
@@ -0,0 +1,211 @@
+#ifndef MARS_MAlphaFitter
+#define MARS_MAlphaFitter
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TF1;
+class TH1D;
+class TH3D;
+
+class MAlphaFitter : public MParContainer
+{
+public:
+    enum ScaleMode_t {
+        kNone,         // No scaling
+        kEntries,      // scale by the number of entries in on and off
+        kIntegral,     // scale by the integral in on and off
+        kOffRegion,    // scale by the integral between fScaleMin, fScaleMax in on and off
+        kBackground,   // scale by the integral between fBgMin, fBgMax in on and off
+        kLeastSquare,  // not yet implemented
+        kUserScale     // scale by fixed factor set by SetScaleUser
+    };
+    enum Strategy_t {
+        kSignificance,
+        kSignificanceChi2,
+        kSignificanceLogExcess,
+        kSignificanceSqrtExcess,
+        kSignificanceExcess,
+        kExcess,
+        kGaussSigma,
+        kWeakSource,
+        kWeakSourceLogExcess
+    };
+    enum SignalFunc_t {
+        kGauss, kThetaSq
+    };
+
+private:
+    // Fitting Setup
+    Float_t fSigInt;            // minimum of range to fit the signal
+    Float_t fSigMax;            // maximum of range to fit the signal
+    Float_t fBgMin;             // minimum of range to fit the background
+    Float_t fBgMax;             // minimum of range to fit the background
+    Float_t fScaleMin;          // minimum of range to determin the scale factor of the background
+    Float_t fScaleMax;          // maximum of range to determin the scale factor of the background
+    Int_t   fPolynomOrder;      // order of polyom to be fitted to the background
+    Bool_t  fFitBackground;     // Backround fit: yes/no
+    SignalFunc_t fSignalFunc;   // Type of signal function
+    // Result
+    Double_t fSignificance;     // significance of an unknown signal (Li/Ma 17)
+    Double_t fErrorExcess;      // Simple error propagation
+    Double_t fEventsExcess;     // calculated number of excess events (signal-bg)
+    Double_t fEventsSignal;     // calculated number of signal events
+    Double_t fEventsBackground; // calculated number of bg events (fScaleFactor already applied)
+
+    Double_t fChiSqSignal;      // Reduced (chi^2/NDF) chisq of signal fit
+    Double_t fChiSqBg;          // Reduced (chi^2/NDF) chisq of bg fit
+    Double_t fIntegralMax;      // Calculated bin border to which it was integrated
+    Double_t fScaleFactor;      // Scale factor determined for off-data
+
+    TArrayD fCoefficients;      // Fit result
+    TArrayD fErrors;            // Fit errors
+
+    // Function
+    TF1 *fFunc;                 // fit function (gauss + polynom)
+
+    // Scaling setup
+    ScaleMode_t fScaleMode;     // scaling mode
+    Double_t    fScaleUser;     // user scale factor
+
+    // Minimization strategy
+    Strategy_t fStrategy;       // How to calc minimization value
+
+    Double_t DoOffFit(const TH1D &hon, const TH1D &hof, Bool_t paint);
+    Bool_t   FitOff(TH1D &h, Int_t paint);
+    void     FitResult(const TH1D &h);
+
+public:
+    // Implementing the function yourself is only about 5% faster
+    MAlphaFitter(const char *name=0, const char *title=0);
+    MAlphaFitter(const MAlphaFitter &f) : MParContainer(f), fFunc(0)
+    {
+        f.Copy(*this);
+    }
+    ~MAlphaFitter();
+
+    // TObject
+    void Clear(Option_t *o="");
+    void Print(Option_t *o="") const; //*MENU*
+    void Copy(TObject &o) const;
+
+    // Setter
+    void SetScaleUser(Float_t scale)       { fScaleUser = scale; fScaleMode=kUserScale; }
+    void SetScaleMode(ScaleMode_t mode)    { fScaleMode    = mode; }
+    void SetMinimizationStrategy(Strategy_t mode) { fStrategy = mode; }
+    void SetSignalIntegralMax(Float_t s)   { fSigInt       = s; }
+    void SetSignalFitMax(Float_t s)        { fSigMax       = s; }
+    void SetBackgroundFitMin(Float_t s)    { fBgMin        = s; }
+    void SetBackgroundFitMax(Float_t s)    { fBgMax        = s; }
+    void SetScaleMin(Float_t s)            { fScaleMin     = s; }
+    void SetScaleMax(Float_t s)            { fScaleMax     = s; }
+    void SetPolynomOrder(Int_t s)
+    {
+        if (s==fPolynomOrder)
+            return;
+
+        fPolynomOrder = s;
+
+        SetSignalFunction(fSignalFunc);
+    }
+    void SetSignalFunction(SignalFunc_t func);
+
+    void EnableBackgroundFit(Bool_t b=kTRUE) { fFitBackground=b; }
+
+    void FixScale()
+    {
+        fScaleMode = kUserScale;
+        fScaleUser = fScaleFactor;
+    }
+
+    // Getter
+    Double_t GetSignalIntegralMax() const  { return fSigInt; }
+
+    Double_t GetEventsExcess() const       { return fEventsExcess; }
+    Double_t GetEventsSignal() const       { return fEventsSignal; }
+    Double_t GetEventsBackground() const   { return fEventsBackground; }
+
+    Double_t GetSignificance() const       { return fSignificance; }
+    Double_t GetErrorExcess() const        { return fErrorExcess; }
+    Double_t GetChiSqSignal() const        { return fChiSqSignal; }
+    Double_t GetChiSqBg() const            { return fChiSqBg; }
+    Double_t GetScaleFactor() const        { return fScaleFactor; }
+    Double_t GetMinimizationValue() const;
+
+    ScaleMode_t GetScaleMode() const       { return fScaleMode; }
+
+    Double_t GetGausSigma() const          { return fCoefficients[2]; }
+    Double_t GetGausMu() const             { return fCoefficients[1]; }
+    Double_t GetGausA() const              { return fCoefficients[0]; }
+    Double_t GetCoefficient(Int_t i) const { return fCoefficients[i]; }
+    const TArrayD &GetCoefficients() const { return fCoefficients; }
+    const TArrayD &GetErrors() const       { return fErrors; }
+    Double_t Eval(Double_t d) const;
+
+    Double_t CalcUpperLimit() const;
+
+    // Interface to fit
+    Bool_t Fit(TH1D &h, Bool_t paint=kFALSE);
+    Bool_t Fit(const TH1D &on, const TH1D &off, Double_t alpha, Bool_t paint=kFALSE);
+    Bool_t Fit(TH1D &on, TH1D *off, Double_t alpha, Bool_t paint=kFALSE)
+    {
+        return off ? Fit(on, *off, alpha, paint) : Fit(on, paint);
+    }
+    Bool_t Fit(TH1D &on, TH1D *off, Bool_t paint=kFALSE)
+    {
+        return off ? Fit(on, *off, 1, paint) : Fit(on, paint);
+    }
+    Bool_t ScaleAndFit(TH1D &on, TH1D *off, Bool_t paint=kFALSE)
+    {
+        const Double_t alpha = off ? Scale(*off, on) : 1;
+        return off ? Fit(on, *off, alpha, paint) : Fit(on, paint);
+    }
+
+    Bool_t FitAlpha(const TH3D &h, Bool_t paint=kFALSE);
+    Bool_t FitEnergy(const TH3D &h, UInt_t bin, Bool_t paint=kFALSE);
+    Bool_t FitTheta(const TH3D &h,  UInt_t bin, Bool_t paint=kFALSE);
+    //Bool_t FitTime(const TH3D &h,  UInt_t bin, Bool_t paint=kFALSE);
+
+    Bool_t FitAlpha(const TH3D &on, const TH3D &off, Bool_t paint=kFALSE);
+    Bool_t FitEnergy(const TH3D &on, const TH3D &off, UInt_t bin, Bool_t paint=kFALSE);
+    Bool_t FitTheta(const TH3D &on, const TH3D &off, UInt_t bin, Bool_t paint=kFALSE);
+    //Bool_t FitTime(const TH3D &on, const TH3D &off, UInt_t bin, Bool_t paint=kFALSE);
+
+    Bool_t FitAlpha(const TH3D &on, const TH3D *off, Bool_t paint=kFALSE)
+    {
+        return off ? FitAlpha(on, *off, paint) : FitAlpha(on, paint);
+    }
+    Bool_t FitEnergy(const TH3D &on, const TH3D *off, UInt_t bin, Bool_t paint=kFALSE)
+    {
+        return off ? FitEnergy(on, *off, bin, paint) : FitEnergy(on, bin, paint);
+    }
+    Bool_t FitTheta(const TH3D &on, const TH3D *off, UInt_t bin, Bool_t paint=kFALSE)
+    {
+        return off ? FitTheta(on, *off, bin, paint) : FitTheta(on, bin, paint);
+    }/*
+    Bool_t FitTime(const TH3D &on, const TH3D *off, UInt_t bin, Bool_t paint=kFALSE)
+    {
+        return off ? FitTime(on, *off, bin, paint) : FitTime(on, bin, paint);
+    }*/
+
+    Double_t Scale(TH1D &off, const TH1D &on) const;
+
+    Bool_t ApplyScaling(const TH3D &hon, TH3D &hof, UInt_t bin) const;
+    Bool_t ApplyScaling(const TH3D &hon, TH3D &hof) const;
+
+    // Interface to result
+    void PaintResult(Float_t x=0.04, Float_t y=0.94, Float_t size=0.035, Bool_t draw=kFALSE) const;
+    void DrawResult(Float_t x=0.04, Float_t y=0.94, Float_t size=0.035) const { PaintResult(x, y, size, kTRUE); }
+
+    // MTask
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MAlphaFitter, 4)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHAlpha.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHAlpha.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHAlpha.cc	(revision 17960)
@@ -0,0 +1,1156 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHAlpha
+//
+// Create a single Alpha-Plot. The alpha-plot is fitted online. You can
+// check the result when it is filles in the MStatusDisplay
+// For more information see MHFalseSource::FitSignificance
+//
+// For convinience (fit) the output significance is stored in a
+// container in the parlisrt
+//
+// PRELIMINARY!
+//
+//
+// ToDo:
+// =====
+//
+//   - Replace time-binning by histogram (which is enhanced bin-wise)
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHAlpha.h"
+
+#include <TStyle.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TPaveStats.h>
+
+#include "MSrcPosCam.h"
+#include "MHillas.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 "MString.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)
+    : fNameParameter("MHillasSrc"), fParameter(0),
+    fOffData(0), fResult(0), fSigma(0), fEnergy(0), fBin(0),
+    fPointPos(0), fTimeEffOn(0), fTime(0), fNumTimeBins(10),
+    fHillas(0), fMatrix(0), fSkipHistTime(kFALSE), fSkipHistTheta(kFALSE),
+    fSkipHistEnergy(kFALSE), fForceUsingSize(kFALSE)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHAlpha";
+    fTitle = title ? title : "Alpha plot";
+
+    fHist.SetName("Alpha");
+    fHist.SetTitle("Alpha");
+    fHist.SetXTitle("\\Theta [deg]");
+    //fHist.SetYTitle("E_{est} [GeV]");
+    fHist.SetZTitle("|\\alpha| [\\circ]");
+    fHist.SetDirectory(NULL);
+    fHist.UseCurrentStyle();
+
+    // Main histogram
+    fHistTime.SetName("Alpha");
+    fHistTime.SetXTitle("|\\alpha| [\\circ]");
+    fHistTime.SetYTitle("Counts");
+    fHistTime.UseCurrentStyle();
+    fHistTime.SetDirectory(NULL);
+
+    fHEnergy.SetName("Excess");
+    //fHEnergy.SetTitle(" N_{exc} vs. E_{est} ");
+    //fHEnergy.SetXTitle("E_{est} [GeV]");
+    fHEnergy.SetYTitle("N_{exc}");
+    fHEnergy.SetDirectory(NULL);
+    fHEnergy.UseCurrentStyle();
+
+    fHTheta.SetName("ExcessTheta");
+    fHTheta.SetTitle(" N_{exc} vs. \\Theta ");
+    fHTheta.SetXTitle("\\Theta [\\circ]");
+    fHTheta.SetYTitle("N_{exc}");
+    fHTheta.SetDirectory(NULL);
+    fHTheta.UseCurrentStyle();
+    fHTheta.SetMinimum(0);
+
+    // effective on time versus time
+    fHTime.SetName("ExcessTime");
+    fHTime.SetTitle(" N_{exc} vs. Time ");
+    fHTime.SetXTitle("Time");
+    fHTime.SetYTitle("N_{exc} [s]");
+    fHTime.UseCurrentStyle();
+    fHTime.SetDirectory(NULL);
+    fHTime.GetYaxis()->SetTitleOffset(1.2);
+    fHTime.GetXaxis()->SetLabelSize(0.033);
+    fHTime.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTime.GetXaxis()->SetTimeDisplay(1);
+    fHTime.SetMinimum(0);
+    fHTime.Sumw2();
+
+    MBinning binsa, binse, binst;
+    binsa.SetEdges(18, 0, 90);
+    binse.SetEdgesLog(15, 10, 100000);
+    binst.SetEdgesASin(67, -0.005, 0.665);
+    binse.Apply(fHEnergy);
+    binst.Apply(fHTheta);
+    binsa.Apply(fHistTime);
+
+    MH::SetBinning(fHist, binst, binse, binsa);
+}
+
+Float_t MHAlpha::FitEnergyBins(Bool_t paint)
+{
+    // Do not store the 'final' result in fFit
+    MAlphaFitter fit(fFit);
+
+    const Int_t n = fHist.GetNbinsY();
+
+    fHEnergy.SetEntries(0);
+
+    Float_t mean = 0;
+    Int_t   num  = 0;
+    for (int i=1; i<=n; i++)
+    {
+        if (!fit.FitEnergy(fHist, fOffData, i))
+            continue;
+
+        // FIXME: Calculate UL!
+        if (fit.GetEventsExcess()<=0)
+            continue;
+
+        fHEnergy.SetBinContent(i, fit.GetEventsExcess());
+        fHEnergy.SetBinError(i, fit.GetErrorExcess());
+
+        mean += fit.GetEventsExcess()*fit.GetEventsExcess()/fit.GetErrorExcess()/fit.GetErrorExcess();
+        num++;
+    }
+    return TMath::Sqrt(mean)/num;
+}
+
+void MHAlpha::FitThetaBins(Bool_t paint)
+{
+    // Do not store the 'final' result in fFit
+    MAlphaFitter fit(fFit);
+
+    const Int_t n = fHist.GetNbinsX();
+
+    fHTheta.SetEntries(0);
+
+    for (int i=1; i<=n; i++)
+    {
+        if (!fit.FitTheta(fHist, fOffData, i))
+            continue;
+
+        // FIXME: Calculate UL!
+        if (fit.GetEventsExcess()<=0)
+            continue;
+
+        fHTheta.SetBinContent(i, fit.GetEventsExcess());
+        fHTheta.SetBinError(i, fit.GetErrorExcess());
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the value from fParemeter which should be filled into the plots
+//
+Double_t MHAlpha::GetVal() const
+{
+    return static_cast<const MHillasSrc*>(fParameter)->GetAlpha();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Store the pointer to the parameter container storing the plotted value
+// (here MHillasSrc) in fParameter.
+//
+// return whether it was found or not.
+//
+Bool_t MHAlpha::GetParameter(const MParList &pl)
+{
+    fParameter = (MParContainer*)pl.FindObject(fNameParameter, "MHillasSrc");
+    if (fParameter)
+        return kTRUE;
+
+    *fLog << err << fNameParameter << " [MHillasSrc] not found... abort." << endl;
+    return kFALSE;
+}
+
+Bool_t MHAlpha::SetupFill(const MParList *pl)
+{
+    fHist.Reset();
+    fHEnergy.Reset();
+    fHTheta.Reset();
+    fHTime.Reset();
+
+    const TString off(MString::Format("%sOff", fName.Data()));
+    if (fName!=off && fOffData==NULL)
+    {
+        const TString desc(MString::Format("%s [%s] found... using ", off.Data(), ClassName()));
+        MHAlpha *hoff = (MHAlpha*)pl->FindObject(off, ClassName());
+        if (!hoff)
+            *fLog << inf << "No " << desc << "current data only!" << endl;
+        else
+        {
+            *fLog << inf << desc << "on-off mode!" << endl;
+            SetOffData(*hoff);
+        }
+    }
+
+    if (!GetParameter(*pl))
+        return kFALSE;
+
+    fHillas = 0;
+    fEnergy = fForceUsingSize ? 0 : (MParameterD*)pl->FindObject("MEnergyEst", "MParameterD");
+    if (!fEnergy)
+    {
+        *fLog << warn << "MEnergyEst [MParameterD] not found... " << flush;
+
+        if (!fHillas)
+            fHillas = (MHillas*)pl->FindObject("MHillas");
+        if (fHillas)
+            *fLog << "using SIZE instead!" << endl;
+        else
+            *fLog << "ignored." << endl;
+
+        fHEnergy.SetTitle(" N_{exc} vs. Size ");
+        fHEnergy.SetXTitle("Size [phe]");
+        fHist.SetYTitle("Size [phe]");
+    }
+    else
+    {
+        fHEnergy.SetTitle(" N_{exc} vs. E_{est} ");
+        fHEnergy.SetXTitle("E_{est} [GeV]");
+        fHist.SetYTitle("E_{est} [GeV]");
+    }
+
+    fPointPos = (MPointingPos*)pl->FindObject("MPointingPos");
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... ignored." << endl;
+
+    fTimeEffOn = (MTime*)pl->FindObject("MTimeEffectiveOnTime", "MTime");
+    if (!fTimeEffOn)
+        *fLog << warn << "MTimeEffectiveOnTime [MTime] not found... ignored." << endl;
+    else
+        *fTimeEffOn = MTime(); // FIXME: How to do it different?
+
+    fTime = (MTime*)pl->FindObject("MTime");
+    if (!fTime)
+        *fLog << warn << "MTime not found... ignored." << endl;
+
+    fResult = (MParameterD*)const_cast<MParList*>(pl)->FindCreateObj("MParameterD", "MinimizationValue");
+    if (!fResult)
+        return kFALSE;
+    fSigma = (MParameterD*)const_cast<MParList*>(pl)->FindCreateObj("MParameterD", "GaussSigma");
+    if (!fSigma)
+        return kFALSE;
+    fBin = (MParameterI*)const_cast<MParList*>(pl)->FindCreateObj("MParameterI", "Bin");
+    if (!fBin)
+        return kFALSE;
+
+    //fExcess = (MParameterD*)const_cast<MParList*>(pl)->FindCreateObj("MParameterD", "MExcess");
+    //if (!fExcess)
+    //    return kFALSE;
+
+    fLastTime = MTime();
+    fNumRebin = fNumTimeBins;
+
+    MBinning binst, binse, binsa;
+    binst.SetEdges(fOffData ? *fOffData : fHist, 'x');
+    binse.SetEdges(fOffData ? *fOffData : fHist, 'y');
+    binsa.SetEdges(fOffData ? *fOffData : fHist, 'z');
+    if (!fOffData)
+    {
+        if (!fPointPos)
+            binst.SetEdges(1, 0, 60);
+        else
+            binst.SetEdges(*pl, "BinningTheta");
+
+        if (!fEnergy && !fHillas)
+            binse.SetEdges(1, 10, 100000);
+        else
+            if (fEnergy)
+                binse.SetEdges(*pl, "BinningEnergyEst");
+            else
+                binse.SetEdges(*pl, "BinningSize");
+
+        binsa.SetEdges(*pl, MString::Format("Binning%s", ClassName()+2));
+    }
+    else
+    {
+        fHEnergy.SetTitle(fOffData->GetTitle());
+        fHEnergy.SetXTitle(fOffData->GetYaxis()->GetTitle());
+        fHist.SetYTitle(fOffData->GetYaxis()->GetTitle());
+    }
+
+    binse.Apply(fHEnergy);
+    binst.Apply(fHTheta);
+    binsa.Apply(fHistTime);
+    MH::SetBinning(fHist, binst, binse, binsa);
+
+    MAlphaFitter *fit = (MAlphaFitter*)pl->FindObject("MAlphaFitter");
+    if (!fit)
+        *fLog << warn << "MAlphaFitter not found... ignored." << endl;
+    else
+        fit->Copy(fFit);
+
+    *fLog << inf;
+    fFit.Print();
+
+    return kTRUE;
+}
+
+void MHAlpha::InitAlphaTime(const MTime &t)
+{
+    //
+    // If this is the first call we have to initialize the time-histogram
+    //
+    const MBinning bins(1, t.GetAxisTime()-60, t.GetAxisTime());
+    bins.Apply(fHTime);
+
+    fLastTime=t;
+}
+
+void MHAlpha::UpdateAlphaTime(Bool_t final)
+{
+    if (!fTimeEffOn)
+        return;
+
+    if (!final)
+    {
+        if (fLastTime==MTime() && *fTimeEffOn!=MTime())
+        {
+            InitAlphaTime(*fTimeEffOn);
+            return;
+        }
+
+        if (fLastTime!=*fTimeEffOn)
+        {
+            fLastTime=*fTimeEffOn;
+            fNumRebin--;
+        }
+
+        if (fNumRebin>0)
+            return;
+    }
+
+    // Check new 'last time'
+    MTime *time = final ? fTime : fTimeEffOn;
+
+    if (time->GetAxisTime()<=fHTime.GetXaxis()->GetXmax())
+    {
+        *fLog << warn << "WARNING - New time-stamp " << *time << " lower" << endl;
+        *fLog << "than upper edge of histogram... skipped." << endl;
+        *fLog << "This should not happen. Maybe you started you eventloop with" << endl;
+        *fLog << "an already initialized time stamp MTimeEffectiveOnTime?" << endl;
+        fNumRebin++;
+        return;
+    }
+
+    // Fit time histogram
+    MAlphaFitter fit(fFit);
+
+    TH1D *h = fOffData ? fOffData->ProjectionZ("ProjTimeTemp", 0, fOffData->GetNbinsX()+1, 0, fOffData->GetNbinsY()+1, "E") : 0;
+    const Bool_t rc = fit.ScaleAndFit(fHistTime, h);
+
+    if (h)
+        delete h;
+
+    if (!rc)
+        return;
+
+    // Reset Histogram
+    fHistTime.Reset();
+    fHistTime.SetEntries(0);
+
+    //
+    // Prepare Histogram
+    //
+    if (final)
+        time->Plus1ns();
+
+    // Enhance binning
+    MBinning bins;
+    bins.SetEdges(fHTime, 'x');
+    bins.AddEdge(time->GetAxisTime());
+    bins.Apply(fHTime);
+
+    //
+    // Fill histogram
+    //
+    // Get number of bins
+    const Int_t n = fHTime.GetNbinsX();
+
+    fHTime.SetBinContent(n, fit.GetEventsExcess());
+    fHTime.SetBinError(n,   fit.GetErrorExcess());
+
+    //*fLog << inf3 << *fTimeEffOn << " (" << n << "): " << fit.GetEventsExcess() << endl;
+
+    fNumRebin = fNumTimeBins;
+}
+
+void MHAlpha::SetBin(Int_t ibin)
+{
+    // Is this necessary?
+    // Could be speed up up searching for it only once.
+    const Float_t max     = fFit.GetSignalIntegralMax();
+    const Int_t bin0      = fHist.GetZaxis()->FindFixBin(max);
+
+    const Int_t nbinsx    = fHist.GetNbinsX();
+    const Int_t nbinsy    = fHist.GetNbinsY();
+    const Int_t nxy       = (nbinsx+2)*(nbinsy+2);
+
+    const Int_t binz      = ibin/nxy;
+
+    const Bool_t issignal = binz>0 && binz<bin0;
+
+    fBin->SetVal(issignal ? binz : -binz);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Int_t MHAlpha::Fill(const MParContainer *par, const Stat_t w)
+{
+    Double_t alpha, energy, theta;
+    Double_t size=-1;
+
+    if (fMatrix)
+    {
+        alpha  = fMap[0]<0 ? GetVal() : (*fMatrix)[fMap[0]];
+        energy = fMap[1]<0 ? -1 : (*fMatrix)[fMap[1]];
+        size   = fMap[2]<0 ? -1 : (*fMatrix)[fMap[2]];
+        //<0 ? 1000 : (*fMatrix)[fMap[1]];
+        theta  = 0;
+
+        if (energy<0)
+            energy=size;
+        if (size<0)
+            size=energy;
+
+        if (energy<0 && size<0)
+            energy = size = 1000;
+    }
+    else
+    {
+        alpha  = GetVal();
+
+        if (fHillas)
+            size = fHillas->GetSize();
+        energy = fEnergy   ? fEnergy->GetVal() : (fHillas?fHillas->GetSize():1000);
+        theta  = fPointPos ? fPointPos->GetZd() : 0;
+    }
+
+    // enhance histogram if necessary
+    UpdateAlphaTime();
+
+    // Fill histograms
+    const Int_t ibin = fHist.Fill(theta, energy, TMath::Abs(alpha), w);
+    SetBin(ibin);
+
+    if (!fSkipHistTime)
+        fHistTime.Fill(TMath::Abs(alpha), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Paint the integral and the error on top of the histogram
+//
+void MHAlpha::PaintText(Double_t val, Double_t error) const
+{
+    TLatex text(0.45, 0.94, MString::Format("N_{exc} = %.1f \\pm %.1f", val, error));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Paint the integral and the error on top of the histogram
+//
+void MHAlpha::PaintText(const TH1D &h) const
+{
+    Double_t sumv = 0;
+    Double_t sume = 0;
+
+    for (int i=0; i<h.GetNbinsX(); i++)
+    {
+        sumv += h.GetBinContent(i+1);
+        sume += h.GetBinError(i+1);
+    }
+    PaintText(sumv, sume);
+}
+// --------------------------------------------------------------------------
+//
+// Update the projections
+//
+void MHAlpha::Paint(Option_t *opt)
+{
+    // Note: Any object cannot be added to a pad twice!
+    //       The object is searched by gROOT->FindObject only in
+    //       gPad itself!
+    TVirtualPad *padsave = gPad;
+
+    TH1D *h0=0;
+
+    TString o(opt);
+
+    if (o==(TString)"proj")
+    {
+        TPaveStats *st=0;
+        for (int x=0; x<4; x++)
+        {
+            TVirtualPad *p=padsave->GetPad(x+1);
+            if (!p || !(st = (TPaveStats*)p->GetPrimitive("stats")))
+                continue;
+
+            if (st->GetOptStat()==11)
+                continue;
+
+            const Double_t y1 = st->GetY1NDC();
+            const Double_t y2 = st->GetY2NDC();
+            const Double_t x1 = st->GetX1NDC();
+            const Double_t x2 = st->GetX2NDC();
+
+            st->SetY1NDC((y2-y1)/3+y1);
+            st->SetX1NDC((x2-x1)/3+x1);
+            st->SetOptStat(11);
+        }
+
+        padsave->cd(1);
+
+        TH1D *hon = (TH1D*)gPad->FindObject("Proj");
+        if (hon)
+        {
+            TH1D *dum = fHist.ProjectionZ("dumab", 0, fHist.GetNbinsX()+1, 0, fHist.GetNbinsY()+1);
+            dum->SetDirectory(0);
+            hon->Reset();
+            hon->Add(dum);
+            delete dum;
+
+            if (fOffData)
+            {
+                TH1D *hoff = (TH1D*)gPad->FindObject("ProjOff");
+                if (hoff)
+                {
+                    TH1D *dum = fOffData->ProjectionZ("dumxy", 0, fOffData->GetNbinsX()+1, 0, fOffData->GetNbinsY()+1);
+                    dum->SetDirectory(0);
+                    hoff->Reset();
+                    hoff->Add(dum);
+                    delete dum;
+
+                    const Double_t alpha = fFit.Scale(*hoff, *hon);
+
+                    hon->SetMaximum();
+                    hon->SetMaximum(TMath::Max(hon->GetMaximum(), hoff->GetMaximum())*1.05);
+
+                    // BE CARFEULL: This is a really weird workaround!
+                    hoff->SetMaximum(alpha);
+
+                    // For some reason the line-color is resetted
+                    hoff->SetLineColor(kRed);
+
+                    if ((h0=(TH1D*)gPad->FindObject("ProjOnOff")))
+                    {
+                        h0->Reset();
+                        h0->Add(hoff, hon, -1);
+                        const Float_t min = h0->GetMinimum()*1.05;
+                        hon->SetMinimum(min<0 ? min : 0);
+                    }
+
+                }
+            }
+            else
+                hon->SetMinimum(0);
+        }
+        FitEnergyBins();
+        FitThetaBins();
+    }
+
+    if (o==(TString)"variable")
+        if ((h0 = (TH1D*)gPad->FindObject("Proj")))
+        {
+            // Check whether we are dealing with on-off analysis
+            TH1D *hoff = (TH1D*)gPad->FindObject("ProjOff");
+
+            // BE CARFEULL: This is a really weird workaround!
+            const Double_t scale = !hoff || hoff->GetMaximum()<0 ? 1 : hoff->GetMaximum();
+
+            // Do not store the 'final' result in fFit
+            MAlphaFitter fit(fFit);
+            fit.Fit(*h0, hoff, scale, kTRUE);
+            fit.PaintResult();
+        }
+
+    if (o==(TString)"time")
+        PaintText(fHTime);
+
+    if (o==(TString)"theta")
+    {
+        TH1 *h = (TH1*)gPad->FindObject(MString::Format("%s_x", fHist.GetName()));
+        if (h)
+        {
+            TH1D *h2 = (TH1D*)fHist.Project3D("dum_x");
+            h2->SetDirectory(0);
+            h2->Scale(fHTheta.Integral()/h2->Integral());
+            h->Reset();
+            h->Add(h2);
+            delete h2;
+        }
+        PaintText(fHTheta);
+    }
+
+    if (o==(TString)"energy")
+    {
+        TH1 *h = (TH1*)gPad->FindObject(MString::Format("%s_y", fHist.GetName()));
+        if (h)
+        {
+            TH1D *h2 = (TH1D*)fHist.Project3D("dum_y");
+            h2->SetDirectory(0);
+            h2->Scale(fHEnergy.Integral()/h2->Integral());
+            h->Reset();
+            h->Add(h2);
+            delete h2;
+        }
+        PaintText(fHEnergy);
+
+        if (fHEnergy.GetMaximum()>1)
+        {
+            gPad->SetLogx();
+            gPad->SetLogy();
+        }
+    }
+
+    gPad = padsave;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHAlpha::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+    /*
+    if (TString(opt).Contains("sizebins", TString::kIgnoreCase))
+    {
+        AppendPad("sizebins");
+        return;
+    }
+    */
+
+    // Do the projection before painting the histograms into
+    // the individual pads
+    AppendPad("proj");
+
+    pad->SetBorderMode(0);
+    pad->Divide(2,2);
+
+    TH1D *h=0;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+
+    h = fHist.ProjectionZ("Proj", 0, fHist.GetNbinsX()+1, 0, fHist.GetNbinsY()+1, "E");
+    h->SetBit(TH1::kNoTitle);
+    h->SetStats(kTRUE);
+    h->SetXTitle(fHist.GetZaxis()->GetTitle());
+    h->SetYTitle("Counts");
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(0);
+    h->SetBit(kCanDelete);
+    h->Draw("");
+
+    if (fOffData)
+    {
+        // To get green on-data
+        //h->SetMarkerColor(kGreen);
+        //h->SetLineColor(kGreen);
+
+        h = fOffData->ProjectionZ("ProjOff", 0, fOffData->GetNbinsX()+1, 0, fOffData->GetNbinsY()+1, "E");
+        h->SetBit(TH1::kNoTitle);
+        h->SetXTitle(fHist.GetZaxis()->GetTitle());
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(0);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kRed);
+        h->SetLineColor(kRed);
+        //h->SetFillColor(18);
+        h->Draw("same"/*"bar same"*/);
+
+        // This is the only way to make it work...
+        // Clone and copy constructor give strange crashes :(
+        h = fOffData->ProjectionZ("ProjOnOff", 0, fOffData->GetNbinsX()+1, 0, fOffData->GetNbinsY()+1, "E");
+        h->SetBit(TH1::kNoTitle);
+        h->SetXTitle(fHist.GetZaxis()->GetTitle());
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(0);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kBlue);
+        h->SetLineColor(kBlue);
+        h->Draw("same");
+
+        TLine lin;
+        lin.SetLineStyle(kDashed);
+        lin.DrawLine(h->GetXaxis()->GetXmin(), 0, h->GetXaxis()->GetXmax(), 0);
+    }
+
+    // After the Alpha-projection has been drawn. Fit the histogram
+    // and paint the result into this pad
+    AppendPad("variable");
+
+    if (fHEnergy.GetNbinsX()>1 || fHEnergy.GetBinContent(1)>0)
+    {
+        pad->cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        fHEnergy.Draw();
+
+        AppendPad("energy");
+
+        h = (TH1D*)fHist.Project3D("y");
+        h->SetBit(TH1::kNoTitle|TH1::kNoStats);
+        h->SetXTitle("E [GeV]");
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(kFullDotSmall);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kCyan);
+        h->SetLineColor(kCyan);
+        h->Draw("Psame");
+    }
+    else
+        delete pad->GetPad(2);
+
+    if ((fTimeEffOn && fTime) || fHTime.GetNbinsX()>1 || fHTime.GetBinError(1)>0)
+    {
+        pad->cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        fHTime.Draw();
+        AppendPad("time");
+    }
+    else
+        delete pad->GetPad(3);
+
+    if (fHTheta.GetNbinsX()>1 || fHTheta.GetBinContent(1)>0)
+    {
+        pad->cd(4);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gPad->SetBorderMode(0);
+        fHTheta.Draw();
+
+        AppendPad("theta");
+
+        h = (TH1D*)fHist.Project3D("x");
+        h->SetBit(TH1::kNoTitle|TH1::kNoStats);
+        h->SetXTitle("\\theta [\\circ]");
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(kFullDotSmall);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kCyan);
+        h->SetLineColor(kCyan);
+        h->Draw("Psame");
+    }
+    else
+        delete pad->GetPad(4);
+}
+
+void MHAlpha::DrawAll(Bool_t newc)
+{
+    if (!newc && !fDisplay)
+        return;
+
+    // FIXME: Do in Paint if special option given!
+    TCanvas &c = newc ? *new TCanvas : fDisplay->AddTab("SizeBins");
+    Int_t n = fHist.GetNbinsY();
+    Int_t nc = (Int_t)(TMath::Sqrt((Float_t)n-1)+1);
+    c.Divide(nc, nc, 1e-10, 1e-10);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+
+    // Do not store the 'final' result in fFit
+    MAlphaFitter fit(fFit);
+
+    for (int i=1; i<=fHist.GetNbinsY(); i++)
+    {
+        c.cd(i);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+
+        TH1D *hon = fHist.ProjectionZ("Proj", 0, fHist.GetNbinsX()+1, i, i, "E");
+        hon->SetBit(TH1::kNoTitle);
+        hon->SetStats(kTRUE);
+        hon->SetXTitle(fHist.GetZaxis()->GetTitle());
+        hon->SetYTitle("Counts");
+        hon->SetDirectory(NULL);
+        hon->SetMarkerStyle(0);
+        hon->SetBit(kCanDelete);
+        hon->Draw("");
+
+        TH1D *hof = 0;
+        Double_t alpha = 1;
+
+        if (fOffData)
+        {
+            hon->SetMarkerColor(kGreen);
+
+            hof = fOffData->ProjectionZ("ProjOff", 0, fOffData->GetNbinsX()+1, i, i, "E");
+            hof->SetBit(TH1::kNoTitle|TH1::kNoStats);
+            hof->SetXTitle(fHist.GetZaxis()->GetTitle());
+            hof->SetYTitle("Counts");
+            hof->SetDirectory(NULL);
+            hof->SetMarkerStyle(0);
+            hof->SetBit(kCanDelete);
+            hof->SetMarkerColor(kRed);
+            hof->SetLineColor(kRed);
+            hof->Draw("same");
+
+            alpha = fit.Scale(*hof, *hon);
+
+            hon->SetMaximum();
+            hon->SetMaximum(TMath::Max(hon->GetMaximum(), hof->GetMaximum())*1.05);
+
+            TH1D *diff = new TH1D(*hon);
+            diff->Add(hof, -1);
+            diff->SetBit(TH1::kNoTitle);
+            diff->SetXTitle(fHist.GetZaxis()->GetTitle());
+            diff->SetYTitle("Counts");
+            diff->SetDirectory(NULL);
+            diff->SetMarkerStyle(0);
+            diff->SetBit(kCanDelete);
+            diff->SetMarkerColor(kBlue);
+            diff->SetLineColor(kBlue);
+            diff->Draw("same");
+
+            TLine lin;
+            lin.SetLineStyle(kDashed);
+            lin.DrawLine(diff->GetXaxis()->GetXmin(), 0, diff->GetXaxis()->GetXmax(), 0);
+
+            const Float_t min = diff->GetMinimum()*1.05;
+            hon->SetMinimum(min<0 ? min : 0);
+        }
+
+        if (hof ? fit.Fit(*hon, *hof, alpha) : fit.Fit(*hon))
+        {
+            *fLog << dbg << "Bin " << i << ": sigmaexc=" << fit.GetEventsExcess()/fit.GetErrorExcess() << " omega=" << fit.GetGausSigma() << " events=" << fit.GetEventsExcess() << " scale=" << fit.GetScaleFactor() << endl;
+            fit.DrawResult();
+        }
+        /*
+        if (fit.FitEnergy(fHist, fOffData, i, kTRUE))
+        {
+            fHEnergy.SetBinContent(i, fit.GetEventsExcess());
+            fHEnergy.SetBinError(i, fit.GetEventsExcess()*0.2);
+        }*/
+    }
+
+}
+
+void MHAlpha::DrawNicePlot(Bool_t newc, const char *title, const char *watermark, Int_t binlo, Int_t binhi)
+{
+    if (!newc && !fDisplay)
+        return;
+
+    if (!fOffData)
+        return;
+
+    // Open and setup canvas/pad
+    TCanvas &c = newc ? *new TCanvas : fDisplay->AddTab("ThetsSq");
+
+    c.SetBorderMode(0);
+    c.SetFrameBorderMode(0);
+    c.SetFillColor(kWhite);
+
+    c.SetLeftMargin(0.12);
+    c.SetRightMargin(0.01);
+    c.SetBottomMargin(0.16);
+    c.SetTopMargin(0.18);
+
+    c.SetGridy();
+
+    gStyle->SetOptStat(0);
+
+    // Get on-data
+    TH1D *hon = (TH1D*)fHist.ProjectionZ("Proj", 0, fHist.GetNbinsX()+1, binlo, binhi, "E");
+    hon->SetDirectory(NULL);
+    hon->SetBit(kCanDelete);
+    hon->SetMarkerSize(0);
+    hon->SetLineWidth(2);
+    hon->SetLineColor(kBlack);
+    hon->SetMarkerColor(kBlack);
+
+    // Get off-data
+    TH1D *hoff = 0;
+    if (fOffData)
+    {
+        hoff = (TH1D*)fOffData->ProjectionZ("ProjOff", 0, fHist.GetNbinsX()+1, binlo, binhi, "E");
+        hoff->SetDirectory(NULL);
+        hoff->SetBit(kCanDelete);
+        hoff->SetFillColor(17);
+        hoff->SetMarkerSize(0);
+        hoff->SetLineColor(kBlack);
+        hoff->SetMarkerColor(kBlack);
+    }
+
+    // Setup plot which is drawn first
+    TH1D *h = hoff ? hoff : hon;
+    h->GetXaxis()->SetLabelSize(0.06);
+    h->GetXaxis()->SetTitleSize(0.06);
+    h->GetXaxis()->SetTitleOffset(0.95);
+    h->GetYaxis()->SetLabelSize(0.06);
+    h->GetYaxis()->SetTitleSize(0.06);
+    h->GetYaxis()->CenterTitle();
+    h->SetYTitle("Counts");
+    h->SetTitleSize(0.07);
+    h->SetTitle("");
+
+    const Double_t imax = fFit.GetSignalIntegralMax();
+    if (imax<1)
+        h->GetXaxis()->SetRangeUser(0, 0.6*0.6);
+
+    // scale off-data
+
+    MAlphaFitter fit(fFit);
+    fit.ScaleAndFit(*hon, hoff);
+
+    hon->SetMinimum(0);
+    hoff->SetMinimum(0);
+
+    // draw data
+    if (hoff)
+    {
+        hoff->SetMaximum(TMath::Max(hon->GetMaximum(),hoff->GetMaximum())*1.1);
+        hoff->Draw("bar");
+        hon->Draw("same");
+    }
+    else
+    {
+        hon->SetMaximum();
+        hon->Draw();
+    }
+
+    // draw a preliminary tag
+    TLatex text;
+    text.SetTextColor(kWhite);
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.07);
+    text.SetTextAngle(2.5);
+
+    TString wm(watermark);
+    if (binlo>=1 || binhi<hon->GetNbinsX())
+    {
+        wm += wm.IsNull() ? "(" : " (";
+        if (binlo>=1)
+            wm += MString::Format("%.1fGeV", fHist.GetYaxis()->GetBinLowEdge(binlo));
+        wm += "-";
+        if (binhi<hon->GetNbinsX())
+            wm += MString::Format("%.1fGeV", fHist.GetYaxis()->GetBinLowEdge(binhi+1));
+        wm += ")";
+    }
+    if (!wm.IsNull())
+        text.DrawLatex(0.45, 0.2, wm);
+    //enum { kTextNDC = BIT(14) };
+
+    // draw line showing cut
+    TLine line;
+    line.SetLineColor(14);
+    line.SetLineStyle(7);
+    line.DrawLine(imax, 0, imax, h->GetMaximum());
+
+    // Add a title above the plot
+    TPaveText *pave=new TPaveText(0.12, 0.83, 0.99, 0.975, "blNDC");
+    pave->SetBorderSize(1);
+    pave->SetLabel(title);
+
+    TText *ptxt = pave->AddText(" ");
+    ptxt->SetTextAlign(23);
+
+    ptxt = pave->AddText(MString::Format("Significance %.1f\\sigma,  off-scale %.2f",
+                                         fit.GetSignificance(), fit.GetScaleFactor()));
+    ptxt->SetTextAlign(23);
+
+    ptxt = pave->AddText(MString::Format("%.1f excess events,  %.1f background events",
+                                         fit.GetEventsExcess(), fit.GetEventsBackground()));
+    ptxt->SetTextAlign(23);
+    pave->SetBit(kCanDelete);
+    pave->Draw();
+}
+
+Bool_t MHAlpha::Finalize()
+{
+    if (!FitAlpha())
+    {
+        *fLog << warn << "MAlphaFitter - Fit failed..." << endl;
+        return kTRUE;
+    }
+
+    // Store the final result in fFit
+    *fLog << all;
+    fFit.Print("result");
+
+    fResult->SetVal(fFit.GetMinimizationValue());
+    fSigma->SetVal(fFit.GetGausSigma());
+
+    if (!fSkipHistEnergy)
+    {
+        *fLog << inf3 << "Processing energy bins..." << endl;
+        FitEnergyBins();
+    }
+    if (!fSkipHistTheta)
+    {
+        *fLog << inf3 << "Processing theta bins..." << endl;
+        FitThetaBins();
+    }
+    if (!fSkipHistTime)
+    {
+        *fLog << inf3 << "Processing time bins..." << endl;
+        UpdateAlphaTime(kTRUE);
+        MH::RemoveFirstBin(fHTime);
+    }
+
+    if (fOffData)
+        DrawAll(kFALSE);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of
+// MMcEvt. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MHHadronness::Fill
+// will take the values from the matrix instead of the containers.
+//
+// It takes fSkipHist* into account!
+//
+void MHAlpha::InitMapping(MHMatrix *mat, Int_t type)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn(GetParameterRule());
+    fMap[1] = -1;
+    fMap[2] = -1;
+    fMap[3] = -1;
+    fMap[4] = -1;
+
+    if (!fSkipHistEnergy)
+    {
+        fMap[1] = type==0 ? fMatrix->AddColumn("MEnergyEst.fVal") : -1;
+        fMap[2] = type==0 ? -1 : fMatrix->AddColumn("MHillas.fSize");
+    }
+
+    if (!fSkipHistTheta)
+        fMap[3] = fMatrix->AddColumn("MPointingPos.fZd");
+
+   // if (!fSkipHistTime)
+   //     fMap[4] = fMatrix->AddColumn("MTime.GetAxisTime");
+}
+
+void MHAlpha::StopMapping()
+{
+    fMatrix = NULL; 
+}
+
+void MHAlpha::ApplyScaling()
+{
+    if (!fOffData)
+        return;
+
+    fFit.ApplyScaling(fHist, *const_cast<TH3D*>(fOffData));
+}
+
+Int_t MHAlpha::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumTimeBins", print))
+    {
+        SetNumTimeBins(GetEnvValue(env, prefix, "NumTimeBins", fNumTimeBins));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ForceUsingSize", print))
+    {
+        fForceUsingSize = GetEnvValue(env, prefix, "ForceUsingSize", fForceUsingSize);
+        rc = kTRUE;
+    }
+    return rc;
+}
+
+Int_t MHAlpha::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    // If pad has no subpad return (we are in one of the subpads)
+    if (gPad->GetPad(1)==NULL)
+        return 9999;
+
+    // If pad has a subpad we are in the main pad. Check its value.
+    return gPad->GetPad(1)->DistancetoPrimitive(px,py)==0 ? 0 : 9999;
+}
+
+void MHAlpha::RecursiveRemove(TObject *obj)
+{
+    if (obj==fOffData)
+        fOffData = 0;
+
+    MH::RecursiveRemove(obj);
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHAlpha.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHAlpha.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHAlpha.h	(revision 17960)
@@ -0,0 +1,162 @@
+#ifndef MARS_MHAlpha
+#define MARS_MHAlpha
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+#ifndef MARS_MAlphaFitter
+#include "MAlphaFitter.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+class MParList;
+class MParameterD;
+class MParameterI;
+class MHillas;
+class MHMatrix;
+class MPointingPos;
+
+class MHAlpha : public MH
+{
+protected:
+    TH3D    fHist;              // Alpha vs. theta and energy
+    TH1D    fHistTime;          //! temporary histogram to get alpha vs. time
+
+    TString fNameParameter;
+
+    MParContainer *fParameter;  //!
+
+    const TH3D *fOffData;
+
+    MAlphaFitter fFit;          // SEEMS THAT STREAMER HAS SOME PROBLEMS... MAYBE IF FUNC IS USED AT THE SAME TIME FOR FITS (PAINT)
+
+private:
+    TH1D fHEnergy;              // excess events vs energy
+    TH1D fHTheta;               // excess events vs theta
+    TH1D fHTime;                // excess events vs time;
+
+    MParameterD   *fResult;     //!
+    MParameterD   *fSigma;      //!
+    MParameterD   *fEnergy;     //!
+    MParameterI   *fBin;        //!
+    MPointingPos  *fPointPos;   //!
+
+    MTime   *fTimeEffOn;        //! Time to steer filling of fHTime
+    MTime   *fTime;             //! Event-Time to finalize fHTime
+    MTime    fLastTime;         //! Last fTimeEffOn
+
+    UShort_t fNumTimeBins;      // Number of time bins to fill together
+    UShort_t fNumRebin;         //!
+
+    //const TString fNameProjAlpha;  //! This should make sure, that gROOT doen't confuse the projection with something else
+protected:
+    MHillas  *fHillas;          //!
+    MHMatrix *fMatrix;          //!
+    Int_t fMap[15];             //!
+
+    Bool_t fSkipHistTime;
+    Bool_t fSkipHistTheta;
+    Bool_t fSkipHistEnergy;
+    Bool_t fForceUsingSize;
+
+private:
+     Float_t FitEnergyBins(Bool_t paint=kFALSE);
+    void FitThetaBins(Bool_t paint=kFALSE);
+
+    void UpdateAlphaTime(Bool_t final=kFALSE);
+    void InitAlphaTime(const MTime &t);
+    void FinalAlphaTime(MBinning &bins);
+
+    void SetBin(Int_t bin);
+
+    void PaintText(Double_t val, Double_t error) const;
+    void PaintText(const TH1D &h) const;
+
+    Int_t DistancetoPrimitive(Int_t px, Int_t py);
+
+    virtual Bool_t      GetParameter(const MParList &pl);
+    virtual Double_t    GetVal() const;
+    virtual const char *GetParameterRule() const
+    {
+        return "MHillasSrc.fAlpha";
+    }
+
+public:
+    MHAlpha(const char *name=NULL, const char *title=NULL);
+
+    // MH
+    Bool_t SetupFill(const MParList *pl);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    // MHAlpha
+    const TH3D &GetHist() const { return fHist; }
+    const MAlphaFitter &GetAlphaFitter() const { return fFit; }
+
+    const TH1D &GetHEnergy() const { return fHEnergy; }
+
+    const TH3D *GetOffData() const { return fOffData; }
+
+    // Setter
+    void SetNameParameter(const char *name) { fNameParameter=name; }
+    virtual void SetOffData(const MHAlpha &h)
+    {
+        fOffData        = &h.fHist;
+        fForceUsingSize =  h.fForceUsingSize;
+        fNumTimeBins    =  h.fNumTimeBins;
+    }
+    void SetNumTimeBins(UShort_t n) { fNumTimeBins = n; }
+/*
+    void SetSizeCuts(Float_t min, Float_t max)   { fSizeMin=min; fSizeMax=max; }
+    void SetSizeMin(Float_t min)                 { fSizeMin=min; }
+    void SetSizeMax(Float_t max)                 { fSizeMax=max; }
+    void SetEnergyCuts(Float_t min, Float_t max) { fEnergyMin=min; fEnergyMax=max; }
+    void SetEnergyMin(Float_t min)               { fEnergyMin=min; }
+    void SetEnergyMax(Float_t max)               { fEnergyMax=max; }
+
+    void SetCuts(const MHAlpha &h) {
+        fSizeMin = h.fSizeMin; fEnergyMin = h.fEnergyMin;
+        fSizeMax = h.fSizeMax; fEnergyMax = h.fEnergyMax;
+    }
+    */
+
+    void SkipHistTime(Bool_t b=kTRUE)   { fSkipHistTime=b; }
+    void SkipHistTheta(Bool_t b=kTRUE)  { fSkipHistTheta=b; }
+    void SkipHistEnergy(Bool_t b=kTRUE) { fSkipHistEnergy=b; }
+    void ForceUsingSize(Bool_t b=kTRUE) { fForceUsingSize=b; }
+
+    Bool_t FitAlpha()
+    {
+        return fFit.FitAlpha(fHist, fOffData);
+    }
+
+    void DrawNicePlot(const char *title="MAGIC Telescope observation", const char *watermark="preliminary", Int_t binlo=-1, Int_t binhi=9999) { DrawNicePlot(kTRUE, title, watermark, binlo, binhi); } //*MENU*
+    void DrawNicePlot(Bool_t newc, const char *title=0, const char *watermark=0, Int_t binlo=-1, Int_t binhi=9999);
+    void DrawAll() { DrawAll(kTRUE); } //*MENU*
+    void DrawAll(Bool_t newc);
+
+    virtual void InitMapping(MHMatrix *mat, Int_t type=0);
+    void StopMapping();
+
+    void ApplyScaling();
+
+    // TObject
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+    void RecursiveRemove(TObject *obj);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MHAlpha, 1) // Alpha-Plot which is fitted online
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHCollectionArea.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHCollectionArea.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHCollectionArea.cc	(revision 17960)
@@ -0,0 +1,489 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCollectionArea
+//
+//  Class Version 2:
+//  ----------------
+//   + added //! to fMcEvt which was missing before
+//   - removed obsolete data member fEnergy
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCollectionArea.h" 
+
+#include <TMath.h>
+
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TPaveStats.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+#include "MBinning.h"
+
+#include "MMcEvt.hxx"
+#include "MMcRunHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+#include "MParList.h"
+#include "MParameters.h"
+
+ClassImp(MHCollectionArea);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHCollectionArea::MHCollectionArea(const char *name, const char *title)
+    : fMcEvt(0), fHeader(0), fMcAreaRadius(-1),
+    fTotalNumSimulatedShowers(0), fAllEvtsTriggered(kFALSE),
+    fIsExtern(kFALSE)
+{ 
+    //   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  : "MHCollectionArea";
+    fTitle = title ? title : "Collection Area vs. Energy/Theta";
+
+    fHistSel.SetName("SelEvts");
+    fHistSel.SetTitle("Number of Events after cuts");
+    fHistSel.SetXTitle("\\Theta [deg]");
+    fHistSel.SetYTitle("E [GeV]");
+    fHistSel.SetDirectory(NULL);
+    fHistSel.UseCurrentStyle();
+    fHistSel.SetLineColor(kBlue);
+
+    fHistAll.SetName("AllEvts");
+    fHistAll.SetTitle("Number of events produced");
+    fHistAll.SetXTitle("\\Theta [deg]");
+    fHistAll.SetYTitle("E_{mc} [GeV]");
+    fHistAll.SetDirectory(NULL);
+    fHistAll.UseCurrentStyle();
+
+    fHEnergy.SetName("CollEnergy");
+    fHEnergy.SetTitle("Collection Area");
+    fHEnergy.SetXTitle("E [GeV]");
+    fHEnergy.SetYTitle("A_{eff} [m^{2}]");
+    fHEnergy.SetDirectory(NULL);
+    fHEnergy.UseCurrentStyle();
+
+    MBinning binsa, binse, binst;
+    binse.SetEdgesLog(21, 6.3, 100000);
+    binst.SetEdgesASin(67, -0.005, 0.665);
+
+    binse.Apply(fHEnergy);
+
+    MH::SetBinning(fHistSel, binst, binse);
+    MH::SetBinning(fHistAll, binst, binse);
+
+    // For some unknown reasons this must be called after
+    // the binning has been initialized at least once
+    fHistSel.Sumw2();
+    fHistAll.Sumw2();
+    fHEnergy.Sumw2();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Area defined by fMcAreaRadius
+//
+Double_t MHCollectionArea::GetCollectionAreaAbs() const
+{
+    return TMath::Pi()*fMcAreaRadius*fMcAreaRadius;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHCollectionArea::CalcEfficiency()
+{
+    TH1D *hsel = fHistSel.ProjectionY("Spy", -1, -1, "E");;
+    TH1D *hall = fHistAll.ProjectionY("Apy", -1, -1, "E");
+
+    //
+    // Impact parameter range.
+    //
+    const Float_t totalarea = GetCollectionAreaAbs();//TMath::Pi() * (r2*r2 - r1*r1);
+
+    // "b" option: calculate binomial errors
+    // Do not use totalarea inside the binomial error calculation:
+    //  it is not a weight.
+    fHEnergy.Divide(hsel, hall, 1, 1, "b");
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,13,04)
+    MH::SetBinomialErrors(fHEnergy, *hsel, *hall);
+#endif
+    if (fMcAreaRadius>0)
+        fHEnergy.Scale(totalarea);
+
+    delete hsel;
+    delete hall;
+}
+
+
+Bool_t MHCollectionArea::SetupFill(const MParList *pl)
+{
+    fHistSel.Reset();
+    if (!fIsExtern)
+        fHistAll.Reset();
+
+    fHeader = (MMcRunHeader*)pl->FindObject("MMcRunHeader");
+    if (!fHeader)
+    {
+        *fLog << err << "MMcRunHeader not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pl->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... abort." << endl;
+        return kFALSE;
+    }
+    /*
+    fEnergy = (MParameterD*)pl->FindObject("MEnergyEst", "MParameterD");
+    if (!fEnergy)
+    {
+        *fLog << err << "MEnergyEst [MParameterD] not found... abort." << endl;
+        return kFALSE;
+    }
+    */
+    MBinning binst, binse;
+    binst.SetEdges(fHistAll, 'x');
+    binse.SetEdges(fHistAll, 'y');
+
+    //if (!fIsExtern)
+    {
+        MBinning *bins = (MBinning*)pl->FindObject("BinningTheta", "MBinning");
+        if (bins)
+            binst.SetEdges(*bins);
+
+        bins = (MBinning*)pl->FindObject("BinningEnergyEst", "MBinning");
+        if (bins)
+            binse.SetEdges(*bins);
+    }
+
+    binse.Apply(fHEnergy);
+
+    MH::SetBinning(fHistSel, binst, binse);
+    MH::SetBinning(fHistAll, binst, binse);
+
+    fMcAreaRadius   = -1;
+    fCorsikaVersion =  0;
+
+    return kTRUE;
+}
+
+void MHCollectionArea::GetImpactMax()
+{
+    if (fHeader->GetImpactMax()<=fMcAreaRadius*100 || fHeader->GetImpactMax()<0)
+        return;
+
+    fMcAreaRadius = 0.01*fHeader->GetImpactMax(); // cm->m
+    *fLog << inf << "Maximum simulated impact: " << fMcAreaRadius << "m" << endl;
+}
+
+Bool_t MHCollectionArea::ReInit(MParList *plist)
+{
+    GetImpactMax();
+
+    if (fCorsikaVersion!=0 && fCorsikaVersion!=fHeader->GetCorsikaVersion())
+    {
+        *fLog << warn;
+        *fLog << "Warning - Read files have different Corsika versions..." << endl;
+        *fLog << "          Last file=" << fCorsikaVersion << "   New file=" << fHeader->GetCorsikaVersion() << endl;
+    }
+    fCorsikaVersion = fHeader->GetCorsikaVersion();
+
+    if (fIsExtern)
+        return kTRUE;
+
+    fTotalNumSimulatedShowers += fHeader->GetNumSimulatedShowers();
+    *fLog << inf << "Total Number of Simulated showers: " << fTotalNumSimulatedShowers << endl;
+
+    fAllEvtsTriggered |= fHeader->GetAllEvtsTriggered();
+    *fLog << inf << "Only triggered events avail: " << (fAllEvtsTriggered?"yes":"no") << endl;
+
+    MMcCorsikaRunHeader *crh = (MMcCorsikaRunHeader*)plist->FindObject("MMcCorsikaRunHeader");
+    if (!crh)
+    {
+        *fLog << err << "MMcCorsikaRunHeader not found... abort." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Calculate approximately the original number of events in each
+    // energy bin:
+    //
+    const Float_t emin = crh->GetELowLim();
+    const Float_t emax = crh->GetEUppLim();
+    const Float_t expo = 1 + crh->GetSlopeSpec();
+    const Float_t k = fHeader->GetNumSimulatedShowers() /
+        (pow(emax,expo) - pow(emin,expo));
+
+    const Int_t nbiny = fHistAll.GetNbinsY();
+
+    TAxis &axe = *fHistAll.GetYaxis();
+    for (Int_t i = 1; i <= nbiny; 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.;
+        for (int j=0; j<TMath::Nint(events); j++)
+            fHistAll.Fill(0., energy);
+        // you have  MMcRunHeader.fShowerThetaMin and MMcRunHeader.fShowerThetaMax
+    }
+
+    return kTRUE;
+}
+
+void MHCollectionArea::Paint(Option_t *option)
+{
+    // This is a workaround to support also older files
+    if (TString(option)=="paint3")
+        return;
+
+    if (TString(option)=="paint4")
+    {
+        if (fMcAreaRadius<=0)
+            return;
+
+        const TString txt = MString::Format("r_{max}=%.0fm --> A_{max}=%.0fm^{2}",
+                                            fMcAreaRadius, GetCollectionAreaAbs());
+
+        TLatex text(0.31, 0.95, txt);
+        text.SetBit(TLatex::kTextNDC);
+        text.SetTextSize(0.04);
+        text.Paint();
+        return;
+    }
+
+    TVirtualPad *pad;
+
+    TPaveStats *st=0;
+    for (int x=0; x<4; x++)
+    {
+        pad=gPad->GetPad(x+1);
+        if (!pad || !(st = (TPaveStats*)pad->GetPrimitive("stats")))
+            continue;
+
+        if (st->GetOptStat()==11)
+            continue;
+
+        const Double_t y1 = st->GetY1NDC();
+        const Double_t y2 = st->GetY2NDC();
+        const Double_t x1 = st->GetX1NDC();
+        const Double_t x2 = st->GetX2NDC();
+
+        st->SetY1NDC((y2-y1)/3+y1);
+        st->SetX1NDC((x2-x1)/3+x1);
+        st->SetOptStat(11);
+    }
+
+    pad = gPad;
+
+    TH1 *h1=0, *h2=0;
+
+    pad->cd(1);
+    if (gPad->FindObject("ProjSelX"))
+        fHistSel.ProjectionX("ProjSelX", -1, -1, "E");
+
+    pad->cd(2);
+    if (gPad->FindObject("ProjAllY"))
+        h1=fHistAll.ProjectionY("ProjAllY", -1, -1, "E");
+    if (gPad->FindObject("ProjSelY"))
+        h2=fHistSel.ProjectionY("ProjSelY", -1, -1, "E");
+
+    if (h1 && h1->GetMaximum()>0)
+    {
+        gPad->SetLogx();
+        gPad->SetLogy();
+    }
+
+    pad->cd(3);
+    TH1 *h=dynamic_cast<TH1*>(gPad->FindObject("Efficiency"));
+    if (h1 && h2 && h)
+    {
+            h->Divide(h2, h1, 1, 1, "b");
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,13,04)
+            MH::SetBinomialErrors(*h, *h2, *h1);
+#endif
+            h->SetMinimum(0);
+    }
+
+    pad->cd(4);
+    CalcEfficiency();
+    if (fHEnergy.GetMaximum()>0)
+    {
+        gPad->SetLogx();
+        gPad->SetLogy();
+    }
+}
+
+void MHCollectionArea::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+    // Do the projection before painting the histograms into
+    // the individual pads
+    AppendPad();
+
+    pad->SetBorderMode(0);
+    pad->Divide(2,2);
+
+    TH1 *h=0, *h1=0, *h2=0;
+
+    if (fHistSel.GetNbinsX()>1)
+    {
+        pad->cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        /*
+        h = fHistAll.ProjectionX("ProjAllX", -1, -1, "E");
+        h->SetXTitle("\\Theta [\\circ]");
+        h->SetDirectory(NULL);
+        h->SetLineColor(kGreen);
+        h->SetBit(kCanDelete);
+        h->Draw();
+        */
+        h = fHistSel.ProjectionX("ProjSelX", -1, -1, "E");
+        h->SetXTitle("\\Theta [\\circ]");
+        h->SetDirectory(NULL);
+        h->SetLineColor(kRed);
+        h->SetBit(kCanDelete);
+        h->Draw("hist"/*"same"*/);
+    }
+    else
+        delete pad->GetPad(1);
+
+    if (fHistSel.GetNbinsY()>1)
+    {
+        pad->cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+
+        h1 = fHistAll.ProjectionY("ProjAllY", -1, -1, "E");
+        h1->SetDirectory(NULL);
+        h1->SetLineColor(kGreen);
+        h1->SetXTitle("E [GeV]");
+        h1->SetBit(kCanDelete);
+        h1->Draw();
+
+        h2 = fHistSel.ProjectionY("ProjSelY", -1, -1, "E");
+        h2->SetDirectory(NULL);
+        h2->SetLineColor(kRed);
+        h2->SetBit(kCanDelete);
+        h2->Draw("same");
+    }
+    else
+        delete pad->GetPad(2);
+
+    if (h1 && h2)
+    {
+        pad->cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gPad->SetLogx();
+        h = h2->DrawCopy();
+        h->Divide(h2, h1, 1, 1, "b");
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,13,04)
+        MH::SetBinomialErrors(*h, *h2, *h1);
+#endif
+        h->SetNameTitle("Efficiency", "Efficiency");
+        h->SetDirectory(NULL);
+        //AppendPad("paint3");
+    }
+    else
+        delete pad->GetPad(4);
+
+    if (fHEnergy.GetNbinsX()>1)
+    {
+        pad->cd(4);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        fHEnergy.Draw();
+        AppendPad("paint4");
+    }
+    else
+        delete pad->GetPad(4);
+}
+
+Int_t MHCollectionArea::Fill(const MParContainer *par, const Stat_t weight)
+{
+    // This is not perfect because it selects the maximum impact only
+    // from the selected events. Hoever, it will get overwritten
+    // in finalize anyway.
+    const Double_t impact = fMcEvt->GetImpact()*0.01; // cm->m
+    if (impact>fMcAreaRadius)
+        fMcAreaRadius = impact;
+
+    const Double_t energy = fMcEvt->GetEnergy();
+    const Double_t theta  = fMcEvt->GetTelescopeTheta()*TMath::RadToDeg();
+
+    fHistSel.Fill(theta, energy, weight);
+
+    return kTRUE;
+}
+
+Bool_t MHCollectionArea::Finalize()
+{
+    GetImpactMax();
+
+    *fLog << all << "Maximum simulated impact found: " << fMcAreaRadius << "m" << endl;
+
+    CalcEfficiency();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHCollectionArea.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHCollectionArea.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHCollectionArea.h	(revision 17960)
@@ -0,0 +1,70 @@
+#ifndef MARS_MHCollectionArea
+#define MARS_MHCollectionArea
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MParameterD;
+class MMcRunHeader;
+
+class MHCollectionArea : public MH
+{
+private:
+    MMcEvt *fMcEvt;             //!
+    MMcRunHeader *fHeader;      //!
+    //MParameterD *fEnergy;     //!
+
+    TH2D fHistSel;
+    TH2D fHistAll;
+
+    TH1D fHEnergy;
+
+    Float_t fMcAreaRadius; // [m] Radius of circle within which the cores of Corsika events have been uniformly distributed.
+
+    UInt_t fTotalNumSimulatedShowers;
+    UInt_t fCorsikaVersion;
+    Bool_t fAllEvtsTriggered;
+    Bool_t fIsExtern;
+
+    void GetImpactMax();
+    void Calc(TH2D &hsel, TH2D &hall);
+    void CalcEfficiency();
+
+public:
+    MHCollectionArea(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t weight=1);
+    Bool_t Finalize();
+
+    void Draw(Option_t *option="");
+    void Paint(Option_t *option="");
+
+    void SetHistAll(const TH2D &h) { h.Copy(fHistAll); fIsExtern=kTRUE; }
+
+    TH2D &GetHistAll()             { return fHistAll; }
+    const TH2D &GetHistAll() const { return fHistAll; }
+    const TH2D &GetHistSel() const { return fHistSel; }
+    const TH1D &GetHEnergy() const { return fHEnergy; }
+
+    Double_t GetEntries() const { return fHistAll.Integral(); }
+    Double_t GetCollectionAreaEff() const { return fHEnergy.Integral(); }
+    Double_t GetCollectionAreaAbs() const;
+
+    void SetMcAreaRadius(Float_t x) { fMcAreaRadius = x; }
+
+    ClassDef(MHCollectionArea, 2)  // Data Container to calculate Collection Area
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHDisp.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHDisp.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHDisp.cc	(revision 17960)
@@ -0,0 +1,785 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHDisp
+//
+// Create a false source plot using disp.
+//
+// Currently the use of this class requires to be after MFMagicCuts
+// in the tasklist. Switching of the M3L cut in MFMagicCuts is recommended.
+//
+// Class Version 3:
+// ----------------
+//  + Double_t fScaleMin;    // [deg] Minimum circle for integration of off-data for scaling
+//  + Double_t fScaleMax;    // [deg] Maximum circle for integration of off-data for scaling
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHDisp.h"
+
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include <TF1.h>
+#include <TF2.h>
+#include <TProfile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMath.h"
+#include "MString.h"
+#include "MBinning.h"
+
+#include "MParList.h"
+#include "MParameters.h"
+
+#include "MHillas.h"
+#include "MSrcPosCam.h"
+#include "MPointingPos.h"
+#include "MPointingDev.h"
+
+ClassImp(MHDisp);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHDisp::MHDisp(const char *name, const char *title)
+    : fDisp(0), fDeviation(0), fSrcAnti(0), fHalf(kFALSE), fSmearing(-1),
+    fWobble(kFALSE), fScaleMin(0.325), fScaleMax(0.475)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHDisp";
+    fTitle = title ? title : "3D-plot using Disp vs x, y";
+
+    fHist.SetName("Alpha");
+    fHist.SetTitle("3D-plot of ThetaSq vs x, y");
+    fHist.SetXTitle("dx [\\circ]");
+    fHist.SetYTitle("dy [\\circ]");
+    fHist.SetZTitle("Eq.cts");
+
+    fHist.SetDirectory(NULL);
+    fHistBg.SetDirectory(NULL);
+    fHistBg1.SetDirectory(NULL);
+    fHistBg2.SetDirectory(NULL);
+
+    fHist.SetBit(TH1::kNoStats);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningFalseSource) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+//
+Bool_t MHDisp::SetupFill(const MParList *plist)
+{
+    if (!MHFalseSource::SetupFill(plist))
+        return kFALSE;
+
+    fDisp = (MParameterD*)plist->FindObject("Disp", "MParameterD");
+    if (!fDisp)
+    {
+        *fLog << err << "Disp [MParameterD] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    if (fWobble)
+    {
+        fSrcAnti = (MSrcPosCam*)plist->FindObject("MSrcPosAnti", "MSrcPosCam");
+        if (!fSrcAnti)
+        {
+            *fLog << err << "MSrcPosAnti [MSrcPosCam] not found... abort." << endl;
+            return kFALSE;
+        }
+
+        *fLog << inf << "Wobble mode initialized. " << endl;
+    }
+
+    fDeviation = (MPointingDev*)plist->FindObject("MPointingDev");
+    if (!fDeviation)
+        *fLog << warn << "MPointingDev not found... ignored." << endl;
+
+    MBinning binsx, binsy;
+    binsx.SetEdges(fHist, 'x');
+    binsy.SetEdges(fHist, 'y');
+    MH::SetBinning(fHistBg, binsx, binsy);
+
+    if (!fHistOff)
+    {
+        MH::SetBinning(fHistBg1, binsx, binsy);
+        MH::SetBinning(fHistBg2, binsx, binsy);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Int_t MHDisp::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MHillas *hil = dynamic_cast<const MHillas*>(par);
+    if (!hil)
+    {
+        *fLog << err << "MHDisp::Fill: No container specified!" << endl;
+        return kERROR;
+    }
+
+    // Get camera rotation angle
+    Double_t rho = 0;
+    if (fTime && fObservatory && fPointPos)
+        rho = fPointPos->RotationAngle(*fObservatory, *fTime, fDeviation);
+
+    // Vector of length disp in direction of shower
+    // Move origin of vector to center-of-gravity of shower and derotate
+    TVector2 pos1 = hil->GetMean()*fMm2Deg + hil->GetNormAxis()*fDisp->GetVal();
+
+    const TVector2 src = fSrcPos->GetXY()*fMm2Deg;
+
+    Double_t w0 = 1;
+    if (fWobble)
+    {
+        const TVector2 anti = fSrcAnti->GetXY()*fMm2Deg;
+
+        // Skip off-data not in the same half than the source (here: anti-source)
+        // Could be replaced by some kind of theta cut...
+        if (!fHistOff)
+        {
+            Double_t r = anti.Mod()>0.2*1.7 ? 0.2*1.7 : anti.Mod();
+
+            // In wobble mode processing the off-data, the anti-source
+            // position is our source position. Check if this is a possible
+            // gamma. If it is, do not fill it into our off-data histogram
+            if ((pos1-anti).Mod()<r)
+                return kTRUE;
+
+            // Because afterwards the plots are normalized with the number
+            // of entries the  non-overlap  region corresponds to half the
+            // contents, the overlap region  to  full contents.  By taking
+            // the mean of both distributions  we get the same result than
+            // we would have gotten using full  off-events with a slightly
+            // increased uncertainty
+            // FIXME: The delta stuff could be replaced by a 2*antitheta cut...
+            //w0 = delta>25 ? 1 : 2;
+
+            w0 = (pos1+anti).Mod()<r ? 2 : 1;
+        }
+
+        // When processing off-data the anti-source is the real source
+        const TVector2 srcpos = fHistOff ? src : anti;
+
+        // Define by the source position which histogram to fill
+        if (TMath::Abs(srcpos.DeltaPhi(fFormerSrc))*TMath::RadToDeg()>90)
+            fHalf = !fHalf;
+        fFormerSrc = srcpos;
+    }
+
+    // If on-data: Derotate source and P. Translate P to center.
+    TVector2 m;
+    if (fHistOff)
+    {
+        // Derotate all position around camera center by -rho
+        // Move origin of vector to center-of-gravity of shower and derotate
+        pos1=pos1.Rotate(-rho);
+
+        // Shift the source position to 0/0
+        if (fSrcPos)
+        {
+            // m: Position of the camera center in the FS plot
+            m = src.Rotate(-rho);
+            pos1 -= m;
+        }
+    }
+
+    // -------------------------------------------------
+    //  The following algorithm may look complicated...
+    //            It is optimized for speed
+    // -------------------------------------------------
+
+    // Define a vector used to calculate rotated x and y component
+    const TVector2 rot(TMath::Sin(rho), TMath::Cos(rho));
+
+    // Fold event position with the PSF and fill it into histogram
+    const TAxis &axex = *fHist.GetXaxis();
+    const TAxis &axey = *fHist.GetYaxis();
+
+    const Int_t nx = axex.GetNbins();
+    const Int_t ny = axey.GetNbins();
+
+    // normg: Normalization for Gauss [sqrt(2*pi)*sigma]^2
+    const Double_t weight = axex.GetBinWidth(1)*axey.GetBinWidth(1)*w*w0;
+    const Double_t psf    = 2*fSmearing*fSmearing;
+    const Double_t pi2    = fSmearing * TMath::Pi()/2;
+    const Double_t normg  = pi2*pi2 * TMath::Sqrt(TMath::TwoPi()) / weight;
+    const Int_t    bz     = fHist.GetZaxis()->FindFixBin(0);
+
+    TH2 &hbg = fHalf ? fHistBg1 : fHistBg2;
+
+    const Bool_t smear = fSmearing>0;
+    if (!smear)
+    {
+        if (!fHistOff)
+            hbg.Fill(pos1.X(), pos1.Y(), w*w0);
+        else
+            fHist.Fill(pos1.X(), pos1.Y(), 0.0, w*w0);
+    }
+
+    // To calculate significance map smear with 2*theta-cut and
+    // do not normalize gauss, for event map use theta-cut/2 instead
+    if (smear || fHistOff)
+    {
+        for (int x=1; x<=nx; x++)
+        {
+            const Double_t cx = axex.GetBinCenter(x);
+            const Double_t px = cx-pos1.X();
+
+            for (int y=1; y<=ny; y++)
+            {
+                const Double_t cy = axey.GetBinCenter(y);
+                const Double_t sp = Sq(px, cy-pos1.Y());
+                if (smear)
+                {
+                    const Double_t dp = sp/psf;
+
+                    // Values below 1e-3 (>3.5sigma) are not filled into the histogram
+                    if (dp<4)
+                    {
+                        const Double_t rc = TMath::Exp(-dp)/normg;
+                        if (!fHistOff)
+                            hbg.AddBinContent(hbg.GetBin(x, y), rc);
+                        else
+                            fHist.AddBinContent(fHist.GetBin(x, y, bz), rc);
+                    }
+                }
+
+                if (!fHistOff)
+                    continue;
+
+                // If we are filling the signal already (fHistOff!=NULL)
+                // we also fill the background by projecting the
+                // background in the camera into the sky plot.
+                const TVector2 v = TVector2(cx+m.X(), cy+m.Y());
+
+                // Speed up further: Xmax-fWobble
+                if (v.Mod()>axex.GetXmax()) // Gains 10% speed
+                    continue;
+
+                const Int_t    bx = axex.FindFixBin(v^rot);
+                const Int_t    by = axey.FindFixBin(v*rot);
+                const Double_t bg = fHistOff->GetBinContent(bx, by, bz);
+
+                fHistBg.AddBinContent(fHistBg.GetBin(x, y), bg);
+            }
+        }
+    }
+
+    if (fHistOff)
+        fHistBg.SetEntries(fHistBg.GetEntries()+1);
+
+    if (!smear)
+        return kTRUE;
+
+    if (!fHistOff)
+        hbg.SetEntries(hbg.GetEntries()+1);
+    else
+        fHist.SetEntries(fHist.GetEntries()+1);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compile the background in camera coordinates from the two background
+// histograms
+//
+Bool_t MHDisp::Finalize()
+{
+    if (fHistOff)
+        return kTRUE;
+
+    const Int_t bz = fHist.GetZaxis()->FindFixBin(0);
+
+    const Double_t n1 = fHistBg1.GetEntries();
+    const Double_t n2 = fHistBg2.GetEntries();
+
+    for (int x=1; x<=fHist.GetNbinsX(); x++)
+        for (int y=1; y<=fHist.GetNbinsY(); y++)
+        {
+            const Int_t bin1 = fHistBg1.GetBin(x, y);
+
+            const Double_t rc =
+                (n1==0?0:fHistBg1.GetBinContent(bin1)/n1)+
+                (n2==0?0:fHistBg2.GetBinContent(bin1)/n2);
+
+            fHist.SetBinContent(x, y, bz, rc/2);
+        }
+
+    fHist.SetEntries(n1+n2);
+
+    // Result corresponds to one smeared background event
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Make sure that if the scale is changed by the context menu all subpads
+// are redrawn.
+//
+void MHDisp::Update()
+{
+    TVirtualPad *pad = gPad;
+    for (int i=1; i<=6; i++)
+    {
+        if (pad->GetPad(i))
+            pad->GetPad(i)->Modified();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the mean signal in h around (0,0) in a distance between
+// 0.325 and 0.475deg
+//
+Double_t MHDisp::GetOffSignal(TH1 &h) const
+{
+    const TAxis &axex = *h.GetXaxis();
+    const TAxis &axey = *h.GetYaxis();
+
+    Int_t    cnt = 0;
+    Double_t sum = 0;
+    for (int x=0; x<h.GetNbinsX(); x++)
+        for (int y=0; y<h.GetNbinsY(); y++)
+        {
+            const Double_t d = TMath::Hypot(axex.GetBinCenter(x+1), axey.GetBinCenter(y+1));
+            if (d>fScaleMin && d<fScaleMax)
+            {
+                sum += h.GetBinContent(x+1,y+1);
+                cnt++;
+            }
+        }
+
+    return sum/cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill h2 with the radial profile of h1 around (x0, y0)
+//
+void MHDisp::Profile(TH1 &h2, const TH2 &h1, Axis_t x0, Axis_t y0) const
+{
+    const TAxis &axex = *h1.GetXaxis();
+    const TAxis &axey = *h1.GetYaxis();
+
+    h2.Reset();
+
+    for (int x=1; x<=axex.GetNbins(); x++)
+        for (int y=1; y<=axey.GetNbins(); y++)
+        {
+            const Double_t dx = axex.GetBinCenter(x)-x0;
+            const Double_t dy = axey.GetBinCenter(y)-y0;
+
+            const Double_t r  = TMath::Hypot(dx, dy);
+
+            h2.Fill(r, h1.GetBinContent(x, y));
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove contents of histogram around a circle.
+//
+void MHDisp::MakeDot(TH2 &h2) const
+{
+    const TAxis &axex = *h2.GetXaxis();
+    const TAxis &axey = *h2.GetYaxis();
+
+    const Double_t rmax = (fWobble ? axex.GetXmax()/*-0.7*/ : axex.GetXmax()) - axex.GetBinWidth(1);
+
+    for (int x=1; x<=axex.GetNbins(); x++)
+        for (int y=1; y<=axey.GetNbins(); y++)
+        {
+            const Int_t bin = h2.GetBin(x,y);
+
+            const Double_t px = h2.GetBinCenter(x);
+            const Double_t py = h2.GetBinCenter(y);
+
+            if (rmax<TMath::Hypot(px, py))
+                h2.SetBinContent(bin, 0);
+            //else
+            //    if (h2.GetBinContent(bin)==0)
+            //        h2.SetBinContent(bin, 1e-10);
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate from signal and background the significance map
+//
+void MHDisp::MakeSignificance(TH2 &s, const TH2 &h1, const TH2 &h2, const Double_t scale) const
+{
+    const TAxis &axex = *s.GetXaxis();
+    const TAxis &axey = *s.GetYaxis();
+
+    const Int_t nx = axex.GetNbins();
+    const Int_t ny = axey.GetNbins();
+
+    const Int_t n = TMath::Nint(0.2/axex.GetBinWidth(1));
+
+    const Double_t sc = h2.GetEntries()/fHistOff->GetEntries();
+
+    for (int x=1; x<=nx; x++)
+        for (int y=1; y<=ny; y++)
+        {
+            Double_t S=0;
+
+            // Only calculate significances for pixels far enough
+            // from the border to get all expected pixels.
+            if (TMath::Hypot((float)x-0.5*nx, (float)y-0.5*ny)<0.5*axex.GetNbins()-n)
+            {
+                Double_t sig=0;
+                Double_t bg =0;
+
+                // Integral a region of n pixels around x/y
+                for (int dx=-n; dx<=n; dx++)
+                    for (int dy=-n; dy<=n; dy++)
+                    {
+                        if (TMath::Hypot((float)dx, (float)dy)>n)
+                            continue;
+
+                        const Int_t  bin = s.GetBin(x+dx,y+dy);
+
+                        sig += h1.GetBinContent(bin);
+                        bg  += h2.GetBinContent(bin);
+                    }
+
+                // Scale such, that the statistical error corresponds to
+                // the amount of off-data used to determin the background
+                // model, not to the background itself. This gives
+                // significances as calculated from the theta-sq plot.
+                S = sig>0 ? MMath::SignificanceLiMaSigned(sig, bg*scale/sc, sc) : 0;
+            }
+
+            s.SetBinContent(x, y, S);
+        }
+}
+
+void MHDisp::Profile1D(const char *name, const TH2 &h) const
+{
+    if (!gPad)
+        return;
+
+    TH1D *hrc = dynamic_cast<TH1D*>(gPad->FindObject(name));
+    if (!hrc)
+        return;
+
+    hrc->Reset();
+
+    //const_cast<TH2&>(h).SetMaximum();
+    const Double_t max = h.GetMaximum();
+
+    MBinning(51, -max*1.1, max*1.1).Apply(*hrc);
+
+    for (int x=1; x<=h.GetXaxis()->GetNbins(); x++)
+        for (int y=1; y<=h.GetXaxis()->GetNbins(); y++)
+        {
+            const Int_t   bin  = h.GetBin(x,y);
+            const Double_t sig = h.GetBinContent(bin);
+            if (sig!=0)
+                hrc->Fill(sig);
+        }
+
+    gPad->SetLogy(hrc->GetMaximum()>0);
+
+    if (!fHistOff || hrc->GetRMS()<0.1)
+        return;
+
+    // ---------- Fix mean ----------
+    // TF1 *g = (TF1*)gROOT->GetFunction("gaus");
+    // g->FixParameter(1, 0);
+    // hrc->Fit("gaus", "BQI");
+
+    hrc->Fit("gaus", "QI");
+
+    TF1 *f = hrc->GetFunction("gaus");
+    if (f)
+    {
+        f->SetLineWidth(1);
+        f->SetLineColor(kBlue);
+    }
+}
+
+void MHDisp::Paint(Option_t *o)
+{
+    // Compile Background if necessary
+    Finalize();
+
+    // Paint result
+    TVirtualPad *pad = gPad;
+
+    pad->cd(1);
+
+    // Project on data onto yx-plane
+    fHist.GetZaxis()->SetRange(0,9999);
+    TH2 *h1=(TH2*)fHist.Project3D("yx_on");
+
+    // Set Glow-palette (PaintSurface doesn't allow more than 99 colors)
+    MH::SetPalette(fHistOff?"glowsym":"glow1", 99);
+    h1->SetContour(99);
+
+    TH2 *hx=0;
+
+    Double_t scale = 1;
+    if (fHistOff)
+    {
+        // Project off data onto yx-plane and subtract it from on-data
+        fHistOff->GetZaxis()->SetRange(0,9999);
+        TH2 *h=(TH2*)fHistOff->Project3D("yx_off");
+
+        const Double_t h1off = GetOffSignal(*h1);
+        const Double_t hoff  = GetOffSignal(fHistBg);
+
+        scale = hoff==0 ? -1 : -h1off/hoff;
+
+        hx = (TH2*)pad->GetPad(4)->FindObject("Alpha_yx_sig");
+        if (hx)
+        {
+            hx->SetContour(99);
+            MakeSignificance(*hx, *h1, fHistBg, TMath::Abs(scale));
+            MakeDot(*hx);
+            MakeSymmetric(hx);
+        }
+
+        h1->Add(&fHistBg, scale);
+
+        MakeDot(*h1);
+        MakeSymmetric(h1);
+
+        delete h;
+    }
+
+    pad->cd(3);
+    TH1 *h2 = (TH1*)gPad->FindObject("RadProf");
+
+    TString opt(o);
+    opt.ToLower();
+
+    if (h1 && h2)
+    {
+        Int_t ix, iy, iz;
+        h1->GetMaximumBin(ix, iy, iz);
+
+        const Double_t x0 = h1->GetXaxis()->GetBinCenter(ix);
+        const Double_t y0 = h1->GetYaxis()->GetBinCenter(iy);
+        //const Double_t w0 = h1->GetXaxis()->GetBinWidth(1);
+
+        Profile(*h2, *h1, 0, 0);
+        //Profile(*h2, *h1, x0, y0);
+
+        if (h2->GetEntries()>0)
+        {
+            // Replace with MAlphaFitter?
+            TF1 func("fcn", "gaus + [3]*x*x + [4]");
+            func.SetLineWidth(1);
+            func.SetLineColor(kBlue);
+
+            func.SetParLimits(2, h2->GetBinWidth(1), 1.0);
+
+            func.SetParameter(0, h2->GetBinContent(1));
+            func.FixParameter(1, 0);
+            func.SetParameter(2, 0.12);
+            if (fHistOff)
+                func.FixParameter(3, 0);
+            func.SetParameter(4, 0);//h2->GetBinContent(20));
+            h2->Fit(&func, "IQ", "", 0, 1.0);
+
+            h2->SetTitle(MString::Format("P=(%.2f\\circ/%.2f\\circ) \\omega=%.2f\\circ f=%.2f",
+                                         x0, y0, func.GetParameter(2), TMath::Abs(scale)));
+        }
+    }
+
+    pad->cd(5);
+    if (h1)
+        Profile1D("Exc", *h1);
+
+    pad->cd(6);
+    if (hx)
+        Profile1D("Sig", *hx);
+}
+
+void MHDisp::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    const Int_t col = pad->GetFillColor();
+    pad->SetBorderMode(0);
+
+    AppendPad(o);
+
+    // ----- Pad number 4 -----
+    TString name = MString::Format("%s_4", pad->GetName());
+    TPad *p = new TPad(name,name, 0.525/*0.5025*/, 0.3355, 0.995, 0.995, col, 0, 0);
+    p->SetNumber(4);
+    p->Draw();
+    p->cd();
+
+    TH1 *h3 = fHist.Project3D("yx_sig");
+    h3->SetTitle("Significance Map");
+    h3->SetDirectory(NULL);
+    h3->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h3->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h3->SetMinimum(0);
+    h3->Draw("colz");
+    h3->SetBit(kCanDelete);
+
+    if (fHistOff)
+        GetCatalog()->Draw("mirror same *");
+
+    // ----- Pad number 1 -----
+    pad->cd();
+    name = MString::Format("%s_1", pad->GetName());
+    p = new TPad(name,name, 0.005, 0.3355, 0.475/*0.4975*/, 0.995, col, 0, 0);
+    p->SetNumber(1);
+    p->Draw();
+    p->cd();
+
+    h3 = fHist.Project3D("yx_on");
+    h3->SetTitle("Distribution of equivalent events");
+    h3->SetDirectory(NULL);
+    h3->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h3->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h3->SetMinimum(0);
+    h3->Draw("colz");
+    h3->SetBit(kCanDelete);
+
+    if (fHistOff)
+        GetCatalog()->Draw("mirror same *");
+
+    // ----- Pad number 2 -----
+    pad->cd();
+    name = MString::Format("%s_2", pad->GetName());
+    p = new TPad(name,name, 0.005, 0.005, 0.2485, 0.3315, col, 0, 0);
+    p->SetNumber(2);
+    p->Draw();
+    p->cd();
+    h3->Draw("surf3");
+
+    // ----- Pad number 3 -----
+    pad->cd();
+    name = MString::Format("%s_3", pad->GetName());
+    p = new TPad(name,name, 0.2525, 0.005, 0.4985, 0.3315, col, 0, 0);
+    p->SetNumber(3);
+    p->SetGrid();
+    p->Draw();
+    p->cd();
+
+    const Double_t maxr = TMath::Hypot(h3->GetXaxis()->GetXmax(), h3->GetYaxis()->GetXmax());
+    const Int_t    nbin = (h3->GetNbinsX()+h3->GetNbinsY())/2;
+    TProfile *h = new TProfile("RadProf", "Radial Profile", nbin, 0, maxr);
+    h->SetDirectory(0);
+    //TH1F *h = new TH1F("RadProf", "Radial Profile", nbin, 0, maxr);
+    //h->Sumw2();
+    h->SetXTitle("\\vartheta [\\circ]");
+    h->SetYTitle("<cts>/\\Delta R");
+    h->SetBit(kCanDelete);
+    h->Draw();
+
+    // ----- Pad number 5 -----
+    pad->cd();
+    name = MString::Format("%s_5", pad->GetName());
+    p = new TPad(name,name, 0.5025, 0.005, 0.7485, 0.3315, col, 0, 0);
+    p->SetNumber(5);
+    p->SetGrid();
+    p->Draw();
+    p->cd();
+
+    h3 = new TH1D("Exc", "Distribution of excess events", 10, -1, 1);
+    h3->SetDirectory(NULL);
+    h3->SetXTitle("N");
+    h3->SetYTitle("Counts");
+    h3->Draw();
+    h3->SetBit(kCanDelete);
+
+    // ----- Pad number 6 -----
+    pad->cd();
+    name = MString::Format("%s_6", pad->GetName());
+    p = new TPad(name,name, 0.7525, 0.005, 0.9995, 0.3315, col, 0, 0);
+    p->SetNumber(6);
+    p->SetGrid();
+    p->Draw();
+    p->cd();
+
+    h3 = new TH1D("Sig", "Distribution of significances", 10, -1, 1);
+    h3->SetDirectory(NULL);
+    h3->SetXTitle("N");
+    h3->SetYTitle("Counts");
+    h3->Draw();
+    h3->SetBit(kCanDelete);
+}
+
+// --------------------------------------------------------------------------
+//
+// The following resources are available:
+//
+//    MHDisp.Smearing: 0.1
+//    MHDisp.Wobble:   on/off
+//
+Int_t MHDisp::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Int_t rc = MHFalseSource::ReadEnv(env, prefix, print);
+    if (rc==kERROR)
+        return kERROR;
+
+    if (IsEnvDefined(env, prefix, "Smearing", print))
+    {
+        rc = kTRUE;
+        SetSmearing(GetEnvValue(env, prefix, "Smearing", fSmearing));
+    }
+    if (IsEnvDefined(env, prefix, "Wobble", print))
+    {
+        rc = kTRUE;
+        SetWobble(GetEnvValue(env, prefix, "Wobble", fWobble));
+    }
+    if (IsEnvDefined(env, prefix, "ScaleMin", print))
+    {
+        rc = kTRUE;
+        SetScaleMin(GetEnvValue(env, prefix, "ScaleMin", fScaleMin));
+    }
+    if (IsEnvDefined(env, prefix, "ScaleMax", print))
+    {
+        rc = kTRUE;
+        SetScaleMax(GetEnvValue(env, prefix, "ScaleMax", fScaleMax));
+    }
+
+    return rc;
+}
+
Index: branches/Mars_McMismatchStudy/mhflux/MHDisp.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHDisp.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHDisp.h	(revision 17960)
@@ -0,0 +1,102 @@
+#ifndef MARS_MHDisp
+#define MARS_MHDisp
+
+#ifndef MARS_MHFalseSource
+#include "MHFalseSource.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+class MParList;
+class MHillasExt;
+class MHillasSrc;
+class MParameterD;
+class MPointingDev;
+class MSrcPosCam;
+
+class MHDisp : public MHFalseSource
+{
+private:
+    MParameterD  *fDisp;      //!
+    MPointingDev *fDeviation; //!
+    //MSrcPosCam   *fAxis;      //!
+    MSrcPosCam   *fSrcAnti; //!
+
+
+    TH2D         fHistBg;
+    TH2D         fHistBg1;
+    TH2D         fHistBg2;
+
+    TVector2     fFormerSrc;
+    Bool_t       fHalf;
+
+    Double_t     fSmearing;    // [deg] Width of Gaus to fold with the events
+    Bool_t       fWobble;      // This is for Wobble-Mode observations
+
+    Double_t     fScaleMin;    // [deg] Minimum circle for integration of off-data for scaling
+    Double_t     fScaleMax;    // [deg] Maximum circle for integration of off-data for scaling
+
+    // MHDisp
+    Double_t GetOffSignal(TH1 &h) const;
+
+    void Update();
+
+    void Profile1D(const char *name, const TH2 &h) const;
+    void Profile(TH1 &h2, const TH2 &h1, Axis_t x0=0, Axis_t y0=0) const;
+    void MakeSignificance(TH2 &s, const TH2 &h1, const TH2 &h2, const Double_t scale=1) const;
+    void MakeDot(TH2 &h2) const;
+
+    Double_t Sq(Double_t x, Double_t y) const { return x*x+y*y; }
+
+public:
+    MHDisp(const char *name=NULL, const char *title=NULL);
+
+    // MHDisp
+    void SetSmearing(Double_t s=-1) { fSmearing=s; }
+    void SetWobble(Bool_t w=kTRUE)  { fWobble=w;   }
+
+    void SetScaleMin(Double_t scale) { fScaleMin = scale; Update(); } //*MENU* *ARGS={scale=>fScaleMin}
+    void SetScaleMax(Double_t scale) { fScaleMax = scale; Update(); } //*MENU* *ARGS={scale=>fScaleMax}
+    void SetScale(Double_t min, Double_t max) { fScaleMin = min; fScaleMax = max; Update(); } //*MENU* *ARGS={min=>fScaleMin,max=>fScaleMax}
+
+    Double_t GetScaleMin() { return fScaleMin; }
+    Double_t GetScaleMax() { return fScaleMax; }
+
+    // MHFalseSource (to be moved!)
+    void SetOffData(const MHFalseSource &fs)
+    {
+        MHFalseSource::SetOffData(fs);
+        if (dynamic_cast<const MHDisp*>(&fs))
+        {
+            const MHDisp &h = dynamic_cast<const MHDisp&>(fs);
+            fWobble   = h.fWobble;
+            fSmearing = h.fSmearing;
+
+            h.fHistBg1.Copy(fHistBg1);
+            h.fHistBg2.Copy(fHistBg2);
+
+            fHistBg1.SetDirectory(0);
+            fHistBg2.SetDirectory(0);
+        }
+    }
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    // TObject
+    void Paint(Option_t *o="");
+    void Draw(Option_t *o="");
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MHDisp, 3) //Class to provide a Disp map
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHEffectiveOnTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHEffectiveOnTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHEffectiveOnTime.cc	(revision 17960)
@@ -0,0 +1,1085 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek, 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHEffectiveOnTime
+//
+//  Filling this you will get the effective on-time versus theta and
+//  observation time.
+//
+//  From this histogram the effective on-time is determined by a fit.
+//  The result of the fit (see Fit()) and the fit-parameters (like chi^2)
+//  are stored in corresponding histograms
+//
+//  To determin the efective on time a poisson fit is done. For more details
+//  please have a look into the source code of FitH() it should be simple
+//  to understand. In this function a Delta-T distribution is fitted, while
+//  Delta-T is the time between two consecutive events.
+//
+//  The fit is done for projections of a 2D histogram in Theta and Delta T.
+//  So you get the effective on time versus theta.
+//
+//  To get the effective on-time versus time a histogram is filled with
+//  the Delta-T distribution of a number of events set by SetNumEvents().
+//  The default is 12000 (roughly 1min at 200Hz)
+//
+//  For each "time-bin" the histogram is fitted and the resulting effective
+//  on-time is stored in the fHTimeEffOn histogram. Each entry in this
+//  histogram is the effective observation time between the upper and
+//  lower edges of the bins.
+//
+//  In addition the calculated effective on time is stored in a
+//  "MEffectiveOnTime [MParameterDerr]" and the corresponding time-stamp
+//  (the upper edge of the bin) "MTimeEffectiveOnTime [MTime]"
+//
+//  The class takes two binnings from the Parameter list; if these binnings
+//  are not available the defaultbinning is used:
+//      MBinning("BinningDeltaT"); // Units of seconds
+//      MBinning("BinningTheta");  // Units of degrees
+//
+//
+//  Usage:
+//  ------
+//    MFillH fill("MHEffectiveOnTime", "MTime");
+//    tlist.AddToList(&fill);
+//
+//
+//  Input Container:
+//    MPointingPos
+//    MRawRunHeader
+//    MTime
+//
+//  Output Container:
+//    MEffectiveOnTime [MParameterDerr]
+//    MTimeEffectiveOnTime [MTime]
+//
+//
+//  Class version 2:
+//  ----------------
+//   +  UInt_t fFirstBin;
+//   +  UInt_t fNumEvents;
+//   -  Int_t fNumEvents;
+//
+//  Class version 3:
+//  ----------------
+//   +  Double_t fTotalTime;
+//
+//  Class version 4:
+//  ----------------
+//   +  Double_t fEffOnTime;    //[s] On time as fitted from the DeltaT distribution
+//   +  Double_t fEffOnTimeErr; //[s] On time error as fitted from the DeltaT distribution
+//
+// ==========================================================================
+// Dear Colleagues,
+//
+// for the case that we are taking calibration events interleaved with
+// cosmics events the calculation of the effective observation time has to
+// be modified. I have summarized the proposed procedures in the note at the
+// end of this message. The formulas have been checked by a simulation.
+//
+// Comments are welcome.
+//
+// Regards,  Wolfgang
+// --------------------------------------------------------------------------
+//                                                       Wolfgang Wittek
+//                                                         2 Dec. 2004
+//
+// Calculation of the effective observation time when cosmics and calibration
+// events are taken simultaneously.
+// --------------------------------
+//
+// I. Introduction
+// ---------------
+// It is planned to take light calibration events (at a certain fixed frequency
+// lambda_calib) interlaced with cosmics events. The advantages of this
+// procedure are :
+//
+// - the pedestals, which would be determined from the cosmics, could be
+//   used for both the calibration and the cosmics events
+//
+// - because calibration and cosmics events are taken quasi simultaneously,
+//   rapid variations (in the order of a few minutes) of base lines and of the
+//   photon/ADC conversion factors could be recognized and taken into account
+//
+// The effective observation time T_eff is defined as that time range, within
+// which the recorded number of events N_cosmics would be obtained under ideal
+// conditions (only cosmics, no dead time, no calibration events, ...).
+//
+// In the absence of calibration events the effective observation time can
+// be determined from the distribution of time differences 'dt' between
+// successive cosmics events (see first figure in the attached ps file).
+// The exponential slope 'lambda' of this distribution is the ideal cosmics
+// event rate. If 'N_cosmics' is the total number of recorded cosmics events,
+// T_eff is obtained by
+//
+//    T_eff = N_cosmics / lambda
+//
+// In the case of a finite dead time 'dead', the distribution (for dt > dead) is
+// still exponential with the same slope 'lambda'. 'lambda' should be determined
+// in a region of 'dt' which is not affected by the dead time, i.e. at not too
+// low 'dt'.
+//
+//
+//
+// II. Problems in the presence of calibration events
+// --------------------------------------------------
+// If calibration events are taken interlaced with cosmics, and if the dead time
+// is negligible, the distribution of time differences 'dt' between cosmics can
+// be used for calculating the effective observation time, as if the calibration
+// events were not present.
+//
+// In the case of a non-negligible dead time 'dead', however, the distribution of
+// time differences between cosmics is distorted, because a cosmics event may be
+// lost due to the dead time after a calibration event. Even if the time
+// intervals are ignored which contain a calibration event,
+//
+//
+//        ---|---------o--------|--------->  t
+//
+//        cosmics    calib    cosmics
+//
+//            <---------------->           <==== time interval to be ignored
+//
+//
+// the distribution of 'dt' is still distorted, because there would be no
+// 'dt' with dt > tau_calib = 1/lambda_calib. The distribution would also be
+// distorted in the region dt < tau_calib, due to calibration events occuring
+// shortly after cosmics events. As a result, the slope of the distribution of
+// 'dt' would not reflect the ideal cosmics event rate (see second figure; the
+// values assumed in the simulation are lambda = 200 Hz, lambda_calib = 50
+// Hz, dead = 0.001 sec, total time = 500 sec, number of generated cosmics
+// events = 100 000).
+//
+//
+// Note also that some calibration events will not be recorded due to the dead
+// time after a cosmics event.
+//
+//
+// III. Proposed procedures
+// ------------------------
+//
+// A) The ideal event rate 'lambda' may be calculated from the distribution of
+// the time difference 'dt_first' between a calibration event and the first
+// recorded cosmics event after the calibration event. In the region
+//
+//     dead < dt_first < tau_calib
+//
+// the probability distribution of dt_first is given by
+//
+//     p(dt_first) = c * exp(-lambda*dt_first)
+//
+// where c is a normalization constant. 'lambda' can be obtained by a simple
+// exponential fit to the experimental distribution of dt_first (see third
+// figure). The fit range should start well above the average value of the dead
+// time 'dead'.
+//
+//
+// B) One may consider those time intervals between recorded cosmics events, which
+// are completely contained in the region
+//
+//    t_calib < t < t_calib + tau_calib
+//
+// where t_calib is the time of a recorded calibration event.
+//
+//
+//          <--------------- tau_calib ----------->
+//
+//
+//           0   1  2   3 4  5   6  7    8  9   10
+//      --|-o---|-|---|--|-|----|--|---|---|-|----o-|---|-|--------->  t
+//          ^                                     ^
+//          |                                     |
+//        t_calib                               t_calib + tau_calib
+//
+//
+// In this example, of the time intervals 0 to 10 only the intervals 1 to 9
+// should be retained and plotted. The distribution of the length 'dt' of these
+// intervals in the region
+//
+//     dead < dt < tau_calib
+//
+// is given by
+//
+//     p(dt) = c * (tau_calib-dt-dead) * exp(-lambda*dt)
+//
+// A fit of this expression to the experimental distribution of 'dt' yields
+// 'lambda' (see fourth figure). For 'dead' an average value of the dead time
+// should be chosen, and the fit range should end well before dt = tau_calib-dead.
+//
+//
+// Method A has the advantage that the p(dt_first) does not depend on 'dead'.
+// 'dead' has to be considered when defining the fit range, both in method A and
+// in method B. In method B the event statistics is larger leading to a smaller
+// fitted error of 'lambda' than method A (see the figures).
+//
+//
+// The effective observation time is again obtained by
+//
+//    T_eff = N_cosmics / lambda
+//
+// where N_cosmics is the total number of recorded cosmics events. Note that
+// N_cosmics is equal to
+//
+//    N_cosmics = N_tot - N_calib
+//
+// where N_tot is the total number of recorded events (including the calibration
+// events) and N_calib is the number of recorded calibration events.
+//
+// Note that if time intervals are discarded for the determination of lambda,
+// the corresponding cosmics events need not and should not be discarded.
+//
+//
+// IV. Procedure if the calibration events are taken in bunches
+// ------------------------------------------------------------
+// In November 2004 the rate of calibration events is not constant. The events
+// are taken in 200 Hz bunches every second, such that the rate is 200 Hz for
+// 0.25 sec, followed by a gap of 0.75 sec. Then follows the next 200 Hz bunch.
+//
+// In this case it is proposed to consider for the calculation of 'lambda' only
+// the cosmics events within the gaps of 0.75 sec. For these cosmics events one
+// of the methods described in III. can be applied.
+//
+//
+// V. Alternative pocedure
+// -----------------------
+// The effective observation time can also be determined from the total
+// observation time and the total dead time. The latter is written out by the DAQ.
+// In this case it has to be made sure that the dead time is available in Mars
+// when the effective observation time is calculated.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHEffectiveOnTime.h"
+
+#include <TF1.h>
+#include <TMinuit.h>
+#include <TRandom.h>
+
+#include <TLatex.h>
+#include <TGaxis.h>
+#include <TCanvas.h>
+#include <TPaveStats.h>
+
+#include "MTime.h"
+#include "MString.h"
+#include "MParameters.h"
+#include "MPointingPos.h"
+#include "MRawRunHeader.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHEffectiveOnTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It initializes all histograms.
+//
+MHEffectiveOnTime::MHEffectiveOnTime(const char *name, const char *title)
+    : fPointPos(0), fTime(0), fParam(0), fIsFinalized(kFALSE), 
+    fNumEvents(200*60), fFirstBin(3), fTotalTime(-1),
+    fEffOnTime(-1), fEffOnTimeErr(0)
+    //fNumEvents(2*60), fFirstBin(1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHEffectiveOnTime";
+    fTitle = title ? title : "Histogram to determin effective On-Time vs Time and Zenith Angle";
+
+    // Main histogram
+    fH2DeltaT.SetName("DeltaT");
+    fH2DeltaT.SetXTitle("\\Delta t [s]");
+    fH2DeltaT.SetYTitle("\\Theta [\\circ]");
+    fH2DeltaT.SetZTitle("Count");
+    fH2DeltaT.UseCurrentStyle();
+    fH2DeltaT.SetDirectory(NULL);
+
+    // Main histogram
+    fH1DeltaT.SetName("DeltaT");
+    fH1DeltaT.SetXTitle("\\Delta t [s]");
+    fH1DeltaT.SetYTitle("Counts");
+    fH1DeltaT.UseCurrentStyle();
+    fH1DeltaT.SetDirectory(NULL);
+
+    // effective on time versus theta
+    fHThetaEffOn.SetName("EffOnTheta");
+    fHThetaEffOn.SetTitle("Effective On Time T_{eff}");
+    fHThetaEffOn.SetXTitle("\\Theta [\\circ]");
+    fHThetaEffOn.SetYTitle("T_{eff} [s]");
+    fHThetaEffOn.UseCurrentStyle();
+    fHThetaEffOn.SetDirectory(NULL);
+    fHThetaEffOn.GetYaxis()->SetTitleOffset(1.2);
+    fHThetaEffOn.GetYaxis()->SetTitleColor(kBlue);
+    fHThetaEffOn.SetLineColor(kBlue);
+    //fHEffOn.Sumw2();
+
+    // effective on time versus time
+    fHTimeEffOn.SetName("EffOnTime");
+    fHTimeEffOn.SetTitle("Effective On Time T_{eff}");
+    fHTimeEffOn.SetXTitle("Time");
+    fHTimeEffOn.SetYTitle("T_{eff} [s]");
+    fHTimeEffOn.UseCurrentStyle();
+    fHTimeEffOn.SetDirectory(NULL);
+    fHTimeEffOn.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeEffOn.GetXaxis()->SetLabelSize(0.033);
+    fHTimeEffOn.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeEffOn.GetXaxis()->SetTimeDisplay(1);
+    fHTimeEffOn.GetYaxis()->SetTitleColor(kBlue);
+    fHTimeEffOn.SetLineColor(kBlue);
+
+    // chi2 probability
+    fHThetaProb.SetName("ProbTheta");
+    fHThetaProb.SetTitle("\\chi^{2} Probability of Fit");
+    fHThetaProb.SetXTitle("\\Theta [\\circ]");
+    fHThetaProb.SetYTitle("p [%]");
+    fHThetaProb.UseCurrentStyle();
+    fHThetaProb.SetDirectory(NULL);
+    fHThetaProb.GetYaxis()->SetTitleOffset(1.2);
+    fHThetaProb.SetMaximum(101);
+    fHThetaProb.GetYaxis()->SetTitleColor(kBlue);
+    fHThetaProb.SetLineColor(kBlue);
+
+    // chi2 probability
+    fHTimeProb.SetName("ProbTime");
+    fHTimeProb.SetTitle("\\chi^{2} Probability of Fit");
+    fHTimeProb.SetXTitle("Time");
+    fHTimeProb.SetYTitle("p [%]");
+    fHTimeProb.UseCurrentStyle();
+    fHTimeProb.SetDirectory(NULL);
+    fHTimeProb.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeProb.GetXaxis()->SetLabelSize(0.033);
+    fHTimeProb.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeProb.GetXaxis()->SetTimeDisplay(1);
+    fHTimeProb.SetMaximum(101);
+    fHTimeProb.GetYaxis()->SetTitleColor(kBlue);
+    fHTimeProb.SetLineColor(kBlue);
+
+    // lambda versus theta
+    fHThetaLambda.SetName("LambdaTheta");
+    fHThetaLambda.SetTitle("Slope (Rate) vs Theta");
+    fHThetaLambda.SetXTitle("\\Theta [\\circ]");
+    fHThetaLambda.SetYTitle("\\lambda [s^{-1}]");
+    fHThetaLambda.UseCurrentStyle();
+    fHThetaLambda.SetDirectory(NULL);
+    fHThetaLambda.SetLineColor(kGreen);
+
+    // lambda versus time
+    fHTimeLambda.SetName("LambdaTime");
+    fHTimeLambda.SetTitle("Slope (Rate) vs Time");
+    fHTimeLambda.SetXTitle("\\Time [\\circ]");
+    fHTimeLambda.SetYTitle("\\lambda [s^{-1}]");
+    fHTimeLambda.UseCurrentStyle();
+    fHTimeLambda.SetDirectory(NULL);
+    fHTimeLambda.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeLambda.GetXaxis()->SetLabelSize(0.033);
+    fHTimeLambda.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeLambda.GetXaxis()->SetTimeDisplay(1);
+    fHTimeLambda.SetLineColor(kGreen);
+
+    // NDoF versus theta
+    fHThetaNDF.SetName("NDofTheta");
+    fHThetaNDF.SetTitle("Number of Degrees of freedom vs Theta");
+    fHThetaNDF.SetXTitle("\\Theta [\\circ]");
+    fHThetaNDF.SetYTitle("NDoF [#]");
+    fHThetaNDF.UseCurrentStyle();
+    fHThetaNDF.SetDirectory(NULL);
+    fHThetaNDF.SetLineColor(kGreen);
+
+    // NDoF versus time
+    /*
+    fHTimeNDF.SetName("NDofTime");
+    fHTimeNDF.SetTitle("Number of Degrees of freedom vs Time");
+    fHTimeNDF.SetXTitle("Time");
+    fHTimeNDF.SetYTitle("NDoF [#]");
+    fHTimeNDF.UseCurrentStyle();
+    fHTimeNDF.SetDirectory(NULL);
+    fHTimeNDF.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeNDF.GetXaxis()->SetLabelSize(0.033);
+    fHTimeNDF.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeNDF.GetXaxis()->SetTimeDisplay(1);
+    fHTimeNDF.SetLineColor(kBlue);
+    */
+    // setup binning
+    MBinning btheta("BinningTheta");
+    btheta.SetEdgesASin(67, -0.005, 0.665);
+
+    MBinning btime("BinningDeltaT");
+    btime.SetEdges(50, 0, 0.1);
+
+    MH::SetBinning(fH2DeltaT, btime, btheta);
+
+    btime.Apply(fH1DeltaT);
+
+    btheta.Apply(fHThetaEffOn);
+    btheta.Apply(fHThetaLambda);
+    btheta.Apply(fHThetaNDF);
+    btheta.Apply(fHThetaProb);
+    //btheta.Apply(fHChi2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHEffectiveOnTime::SetupFill(const MParList *plist)
+{
+   fPointPos = (MPointingPos*)plist->FindObject("MPointingPos");
+   if (!fPointPos)
+   {
+       *fLog << err << dbginf << "MPointingPos not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   // FIXME: Remove const-qualifier from base-class!
+   fTime = (MTime*)const_cast<MParList*>(plist)->FindCreateObj("MTime", "MTimeEffectiveOnTime");
+   if (!fTime)
+       return kFALSE;
+   fParam = (MParameterDerr*)const_cast<MParList*>(plist)->FindCreateObj("MParameterDerr", "MEffectiveOnTime");
+   if (!fParam)
+       return kFALSE;
+
+   const MBinning* binsdtime = (MBinning*)plist->FindObject("BinningDeltaT");
+   const MBinning* binstheta = (MBinning*)plist->FindObject("BinningTheta");
+   if (binsdtime)
+       binsdtime->Apply(fH1DeltaT);
+   if (binstheta)
+   {
+       binstheta->Apply(fHThetaEffOn);
+       binstheta->Apply(fHThetaLambda);
+       binstheta->Apply(fHThetaNDF);
+       binstheta->Apply(fHThetaProb);
+       //binstheta->Apply(fHChi2);
+   }
+   if (binstheta && binsdtime)
+       SetBinning(fH2DeltaT, *binsdtime, *binstheta);
+
+   fTotalTime = 0;
+
+   fEffOnTime    = -1;
+   fEffOnTimeErr =  0;
+
+   return kTRUE;
+}
+
+Bool_t MHEffectiveOnTime::ReInit(MParList *pList)
+{
+    MRawRunHeader *header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!header)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTotalTime += header->GetRunLength();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fit a single Delta-T distribution. See source code for more details
+//
+Bool_t MHEffectiveOnTime::FitH(TH1D *h, Double_t *res, Bool_t paint) const
+{
+    // Count also events in under-/overflowbins
+    const Double_t Nm = h->Integral(0, h->GetNbinsX()+1);
+
+    // FIXME: Do fit only if contents of bin has changed
+    if (Nm<=0 || h->GetBinContent(1)<=0)
+        return kFALSE;
+
+    // determine range (yq[0], yq[1]) of time differences
+    // where fit should be performed;
+    // require a fraction >=xq[0] of all entries to lie below yq[0]
+    //     and a fraction <=xq[1] of all entries to lie below yq[1];
+    // within the range (yq[0], yq[1]) there must be no empty bin;
+    // choose pedestrian approach as long as GetQuantiles is not available
+    Double_t xq[2] = { 0.6, 0.95 }; // previously 0.99
+    Double_t yq[2];
+    h->GetQuantiles(2, yq, xq);
+
+    //
+    // Determine a good starting value for the slope
+    //
+    const TAxis  &axe = *h->GetXaxis();
+    const UInt_t ibin = axe.FindFixBin(yq[1]);
+    const Double_t x1 = axe.GetBinCenter(ibin<=fFirstBin?fFirstBin+1:ibin);
+    const Double_t x0 = axe.GetBinCenter(fFirstBin);
+    const Double_t y1 = h->GetBinContent(ibin)>1 ? TMath::Log(h->GetBinContent(ibin)) : 0;
+    const Double_t y0 = TMath::Log(h->GetBinContent(fFirstBin));
+
+    // Estimated slope
+    const Float_t m = -(y1-y0)/(x1-x0);
+
+    //
+    // Setup exponential function for the fit:
+    //
+    // parameter 0 = rate [Hz]
+    // parameter 1 = normalization
+    //
+    TF1 func("Exp", " exp([1]-[0]*x)");
+
+    func.SetParameter(0, m);       // Hz
+    func.SetParameter(1, log(h->GetBinContent(1)));       // Hz
+
+    // We set a limit to make sure that almost empty histograms which
+    // are fitted dont't produce hang ups or crashes
+    func.SetParLimits(0, 0, 15000); // Hz
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    //           L  Use log-likelihood (better for low statistics)
+    h->Fit(&func, "NIQEL", "", h->GetBinLowEdge(fFirstBin)/*yq[0]*/, yq[1]);
+
+    const Double_t chi2 = func.GetChisquare();
+    const Double_t prob = func.GetProb();
+    const Int_t    NDF  = func.GetNDF();
+
+    // was fit successful ?
+    const Bool_t ok = prob>0.001; //NDF>0 && chi2<3*NDF;
+
+    if (paint)
+    {
+        func.SetLineWidth(2);
+        func.SetLineColor(ok ? kGreen : kRed);
+        func.Paint("same");
+    }
+
+    // The effective on time is the "real rate" (slope of the exponential)
+    // divided by the total number of events (histogram integral including 
+    // under- and overflows)
+    const Double_t lambda = func.GetParameter(0);
+    const Double_t dldl   = func.GetParError(0)*func.GetParError(0);
+    const Double_t teff   = lambda==0 ? 0 : Nm / lambda;
+    const Double_t dteff  = lambda==0 ? 0 : teff * TMath::Sqrt(dldl/(lambda*lambda) + 1.0/Nm);
+    const Double_t dl     = TMath::Sqrt(dldl);
+
+    // the effective on time is Nm/lambda
+    res[0] = teff;
+    res[1] = dteff;
+
+    // plot chi2-probability of fit
+    res[2] = prob*100;
+
+    // lambda of fit
+    res[3] = lambda;
+    res[4] = dl;
+
+    // NDoF of fit
+    res[5] = NDF;
+
+    // Chi2
+    res[6] = chi2;
+
+    return ok;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fit a all bins of the distribution in theta. Store the result in the
+// Theta-Histograms
+//
+void MHEffectiveOnTime::FitThetaBins()
+{
+    fHThetaEffOn.Reset();
+    fHThetaProb.Reset();
+    fHThetaLambda.Reset();
+    fHThetaNDF.Reset();
+
+    // Use a random name to make sure the object is unique
+    const TString name = MString::Format("CalcTheta%d", (UInt_t)gRandom->Uniform(999999999));
+
+    // nbins = number of Theta bins
+    const Int_t nbins = fH2DeltaT.GetNbinsY();
+
+    TH1D *h=0;
+    for (int i=1; i<=nbins; i++)
+    {
+        //        TH1D &h = *hist->ProjectionX("Calc-theta", i, i);
+        h = fH2DeltaT.ProjectionX(name, i, i, "E");
+
+        Double_t res[7] = {0, 0, 0, 0, 0, 0, 0};
+        //if (!FitH(h, res))
+        //    continue;
+        FitH(h, res);
+
+        if (res[0]==0)
+            continue;
+
+        // the effective on time is Nm/lambda
+        fHThetaEffOn.SetBinContent(i, res[0]);
+        fHThetaEffOn.SetBinError  (i, res[1]);
+
+        // plot chi2-probability of fit
+        fHThetaProb.SetBinContent(i, res[2]);
+
+        // plot chi2/NDF of fit
+        //fHChi2.SetBinContent(i, res[3]);
+
+        // lambda of fit
+        fHThetaLambda.SetBinContent(i, res[3]);
+        fHThetaLambda.SetBinError  (i, res[4]);
+
+        // NDoF of fit
+        fHThetaNDF.SetBinContent(i, res[5]);
+
+        // Rdead (from fit) is the fraction from real time lost by the dead time
+        //fHRdead.SetBinContent(i, Rdead);
+        //fHRdead.SetBinError  (i,dRdead);
+    }
+
+    // Histogram is reused via gROOT->FindObject()
+    // Need to be deleted only once
+    if (h)
+        delete h;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fit the single-time-bin histogram. Store the result in the
+// Time-Histograms
+//
+void MHEffectiveOnTime::FitTimeBin()
+{
+    //
+    // Fit histogram
+    //
+    Double_t res[7];
+    if (!FitH(&fH1DeltaT, res))
+        return;
+
+    // Reset Histogram
+    fH1DeltaT.Reset();
+
+    //
+    // Prepare Histogram
+    //
+
+    // Get number of bins
+    const Int_t n = fHTimeEffOn.GetNbinsX();
+
+    // Enhance binning
+    MBinning bins;
+    bins.SetEdges(fHTimeEffOn, 'x');
+    bins.AddEdge(fLastTime.GetAxisTime());
+    bins.Apply(fHTimeEffOn);
+    bins.Apply(fHTimeProb);
+    bins.Apply(fHTimeLambda);
+    //bins.Apply(fHTimeNDF);
+
+    //
+    // Fill histogram
+    //
+    fHTimeEffOn.SetBinContent(n, res[0]);
+    fHTimeEffOn.SetBinError(n, res[1]);
+
+    fHTimeProb.SetBinContent(n, res[2]);
+
+    fHTimeLambda.SetBinContent(n, res[3]);
+    fHTimeLambda.SetBinError(n, res[4]);
+
+    //fHTimeNDF.SetBinContent(n, res[5]);
+
+    //
+    // Now prepare output
+    //
+    fParam->SetVal(res[0], res[1]);
+    fParam->SetReadyToSave();
+
+    *fTime = fLastTime;
+
+    // Include the current event
+    fTime->Plus1ns();
+
+    *fLog << inf2 << fLastTime << ":  Val=" << res[0] << "  Err=" << res[1] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the histogram
+//
+Int_t MHEffectiveOnTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MTime *time = dynamic_cast<const MTime*>(par);
+    if (!time)
+    {
+        *fLog << err << "ERROR - MHEffectiveOnTime::Fill without argument or container doesn't inherit from MTime... abort." << endl;
+        return kERROR;
+    }
+
+    //
+    // If this is the first call we have to initialize the time-histogram
+    //
+    if (fLastTime==MTime())
+    {
+        MBinning bins;
+        bins.SetEdges(1, time->GetAxisTime()-fNumEvents/200, time->GetAxisTime());
+        bins.Apply(fHTimeEffOn);
+        bins.Apply(fHTimeProb);
+        bins.Apply(fHTimeLambda);
+        //bins.Apply(fHTimeNDF);
+
+        fParam->SetVal(0, 0);
+        fParam->SetReadyToSave();
+
+        *fTime = *time;
+
+        // Make this 1ns before the first event!
+        fTime->Minus1ns();
+    }
+
+    //
+    // Fill time difference into the histograms
+    //
+    const Double_t dt = *time-fLastTime;
+    fLastTime = *time;
+
+    fH2DeltaT.Fill(dt, fPointPos->GetZd(), w);
+    fH1DeltaT.Fill(dt, w);
+
+    //
+    // If we reached the event number limit for the time-bins fit the
+    // histogram - if it fails try again when 1.6% more events available
+    //
+    const UInt_t n = (UInt_t)fH1DeltaT.GetEntries();
+    if (n>=fNumEvents && n%(fNumEvents/60)==0)
+        FitTimeBin();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fit the theta projections of the 2D histogram and the 1D Delta-T
+// distribution
+//
+Bool_t MHEffectiveOnTime::Finalize()
+{
+    FitThetaBins();
+    FitTimeBin();
+
+
+    TH1D *h = fH2DeltaT.ProjectionX("FinalizeProjDeltaT", -1, -1, "E");
+    Double_t res[7];
+    if (FitH(h, res))
+    {
+        fEffOnTime    = res[0];
+        fEffOnTimeErr = res[1];
+    }
+    delete h;
+
+
+    fIsFinalized = kTRUE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Paint the integral and the error on top of the histogram
+//
+void MHEffectiveOnTime::PaintText(Double_t val, Double_t error, Double_t range) const
+{
+    TLatex text;
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+
+    TString txt = MString::Format("T_{eff} = %.1fs \\pm %.1fs", val, error);
+    if (range>0)
+        txt += MString::Format("     T_{axe} = %.1fs", range);
+    if (fTotalTime>0)
+        txt += MString::Format("     T_{max} = %.1fs", fTotalTime);
+
+    text.SetText(0.35, 0.94, txt);
+    text.Paint();
+}
+
+void MHEffectiveOnTime::PaintText(Double_t *res) const
+{
+    TLatex text(0.27, 0.94, MString::Format("T_{eff}=%.1fs\\pm%.1fs  \\lambda=%.1f\\pm%.1fHz  p=%.1f%%  \\chi^{2}/%d=%.1f",
+                                            res[0], res[1], res[3], res[4], res[2], (int)res[5], res[6]/res[5]));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+void MHEffectiveOnTime::PaintProb(TH1 &h) const
+{
+    Double_t sum = 0;
+    Int_t    n = 0;
+    for (int i=0; i<h.GetNbinsX(); i++)
+        if (h.GetBinContent(i+1)>0)
+        {
+            sum += h.GetBinContent(i+1);
+            n++;
+        }
+
+    if (n==0)
+        return;
+
+    TLatex text(0.47, 0.94, MString::Format("\\bar{p} = %.1f%%", sum/n));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+void MHEffectiveOnTime::UpdateRightAxis(TH1 &h)
+{
+    const Double_t max = h.GetMaximum()*1.1;
+    if (max==0)
+        return;
+
+    h.SetNormFactor(h.Integral()*gPad->GetUymax()/max);
+
+    TGaxis *axis = (TGaxis*)gPad->FindObject("RightAxis");
+    if (!axis)
+        return;
+
+    axis->SetX1(gPad->GetUxmax());
+    axis->SetX2(gPad->GetUxmax());
+    axis->SetY1(gPad->GetUymin());
+    axis->SetY2(gPad->GetUymax());
+    axis->SetWmax(max);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prepare painting the histograms
+//
+void MHEffectiveOnTime::Paint(Option_t *opt)
+{
+    TH1D *h=0;
+    TPaveStats *st=0;
+
+    TString o(opt);
+    if (o==(TString)"fit")
+    {
+        TVirtualPad *pad = gPad;
+
+        for (int x=0; x<2; x++)
+            for (int y=0; y<3; y++)
+            {
+                TVirtualPad *p=gPad->GetPad(x+1)->GetPad(y+1);
+                if (!(st = dynamic_cast<TPaveStats*>(p->GetPrimitive("stats"))))
+                    continue;
+
+                if (st->GetOptStat()==11)
+                    continue;
+
+                const Double_t y1 = st->GetY1NDC();
+                const Double_t y2 = st->GetY2NDC();
+                const Double_t x1 = st->GetX1NDC();
+                const Double_t x2 = st->GetX2NDC();
+
+                st->SetY1NDC((y2-y1)/3+y1);
+                st->SetX1NDC((x2-x1)/3+x1);
+                st->SetOptStat(11);
+            }
+
+        pad->GetPad(1)->cd(1);
+        if ((h = (TH1D*)gPad->FindObject("ProjDeltaT"/*fNameProjDeltaT*/)))
+        {
+            h = fH2DeltaT.ProjectionX("ProjDeltaT"/*fNameProjDeltaT*/, -1, -1, "E");
+            if (h->GetEntries()>0)
+                gPad->SetLogy();
+        }
+
+        pad->GetPad(2)->cd(1);
+        if ((h = (TH1D*)gPad->FindObject("ProjTheta"/*fNameProjTheta*/)))
+            fH2DeltaT.ProjectionY("ProjTheta"/*fNameProjTheta*/, -1, -1, "E");
+
+        if (!fIsFinalized)
+            FitThetaBins();
+        return;
+    }
+    if (o==(TString)"paint")
+    {
+        if ((h = (TH1D*)gPad->FindObject("ProjDeltaT"/*fNameProjDeltaT*/)))
+        {
+            Double_t res[7];
+            if (FitH(h, res, kTRUE))
+                PaintText(res);
+        }
+        return;
+    }
+
+    if (o==(TString)"timendf")
+    {
+        //    UpdateRightAxis(fHTimeNDF);
+        // FIXME: first bin?
+        PaintProb(fHTimeProb);
+    }
+
+    if (o==(TString)"thetandf")
+    {
+        UpdateRightAxis(fHThetaNDF);
+        // FIXME: first bin?
+        PaintProb(fHThetaProb);
+    }
+
+    h=0;
+
+    Double_t range=-1;
+    if (o==(TString)"theta")
+    {
+        h = &fHThetaEffOn;
+        UpdateRightAxis(fHThetaLambda);
+    }
+    if (o==(TString)"time")
+    {
+        h = &fHTimeEffOn;
+        UpdateRightAxis(fHTimeLambda);
+        range = h->GetXaxis()->GetXmax() - h->GetXaxis()->GetXmin();
+    }
+
+    if (!h)
+        return;
+
+    Double_t error = 0;
+    for (int i=0; i<h->GetXaxis()->GetNbins(); i++)
+        error += h->GetBinError(i);
+
+    PaintText(h->Integral(), error, range);
+}
+
+void MHEffectiveOnTime::DrawRightAxis(const char *title)
+{
+    TGaxis *axis = new TGaxis(gPad->GetUxmax(), gPad->GetUymin(),
+                              gPad->GetUxmax(), gPad->GetUymax(),
+                              0, 1, 510, "+L");
+    axis->SetName("RightAxis");
+    axis->SetTitle(title);
+    axis->SetTitleOffset(0.9);
+    axis->SetTextColor(kGreen);
+    axis->CenterTitle();
+    axis->SetBit(kCanDelete);
+    axis->Draw();
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHEffectiveOnTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("fit");
+
+    pad->Divide(2, 1, 1e-10, 1e-10);
+
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1, 3, 1e-10, 1e-10);
+    pad->GetPad(1)->cd(1);
+    gPad->SetBorderMode(0);
+    h = fH2DeltaT.ProjectionX("ProjDeltaT"/*fNameProjDeltaT*/, -1, -1, "E");
+    h->SetTitle("Distribution of \\Delta t [s]");
+    h->SetXTitle("\\Delta t [s]");
+    h->SetYTitle("Counts");
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(kFullDotMedium);
+    h->SetBit(kCanDelete);
+    h->Draw();
+    AppendPad("paint");
+
+    pad->GetPad(1)->cd(2);
+    gPad->SetBorderMode(0);
+    fHTimeProb.Draw();
+    AppendPad("timendf");
+    //fHTimeNDF.Draw("same");
+    //DrawRightAxis("NDF");
+
+    pad->GetPad(1)->cd(3);
+    gPad->SetBorderMode(0);
+    fHTimeEffOn.Draw();
+    AppendPad("time");
+    fHTimeLambda.Draw("same");
+    DrawRightAxis("\\lambda [s^{-1}]");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1, 3, 1e-10, 1e-10);
+
+    pad->GetPad(2)->cd(1);
+    gPad->SetBorderMode(0);
+    h = fH2DeltaT.ProjectionY("ProjTheta"/*fNameProjTheta*/, -1, -1, "E");
+    h->SetTitle("Distribution of  \\Theta [\\circ]");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("Counts");
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(kFullDotMedium);
+    h->SetBit(kCanDelete);
+    h->GetYaxis()->SetTitleOffset(1.1);
+    h->Draw();
+
+    pad->GetPad(2)->cd(2);
+    gPad->SetBorderMode(0);
+    fHThetaProb.Draw();
+    AppendPad("thetandf");
+    fHThetaNDF.Draw("same");
+    DrawRightAxis("NDF");
+
+    pad->GetPad(2)->cd(3);
+    gPad->SetBorderMode(0);
+    fHThetaEffOn.Draw();
+    AppendPad("theta");
+    fHThetaLambda.Draw("same");
+    DrawRightAxis("\\lambda [s^{-1}]");
+}
+
+// --------------------------------------------------------------------------
+//
+// The following resources are available:
+//
+//    MHEffectiveOnTime.FistBin:   3
+//    MHEffectiveOnTime.NumEvents: 12000
+//
+Int_t MHEffectiveOnTime::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FirstBin", print))
+    {
+        rc = kTRUE;
+        SetFirstBin(GetEnvValue(env, prefix, "FirstBin", (Int_t)fFirstBin));
+    }
+    if (IsEnvDefined(env, prefix, "NumEvents", print))
+    {
+        rc = kTRUE;
+        SetNumEvents(GetEnvValue(env, prefix, "NumEvents", (Int_t)fNumEvents));
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHEffectiveOnTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHEffectiveOnTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHEffectiveOnTime.h	(revision 17960)
@@ -0,0 +1,100 @@
+#ifndef MARS_MHEffectiveOnTime
+#define MARS_MHEffectiveOnTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+#ifndef ROOT_TF1
+#include <TF1.h>
+#endif
+
+class MTime;
+class MPointingPos;
+class MParameterDerr;
+
+class MParList;
+
+class MHEffectiveOnTime : public MH
+{
+private:
+    MPointingPos   *fPointPos; //! Container to get the zenith angle from
+    MTime           fLastTime; //! Time-Stamp of last event
+
+    MTime          *fTime;     //! Time-Stamp of "effective on-time" event
+    MParameterDerr *fParam;    //! Output container for effective on-time
+
+    TH2D fH2DeltaT;      // Counts vs Delta T and Theta
+    TH1D fH1DeltaT;      //! Counts vs Delta T (for a time interval)
+
+    TH1D fHThetaEffOn;   // Effective On time versus Theta
+    TH1D fHThetaProb;    // Chisq prob fit of Effective On time versus Theta
+    TH1D fHThetaNDF;     // NDF vs Theta
+    TH1D fHThetaLambda;  // Slope (rate) vs Theta
+
+    TH1D fHTimeEffOn;    // Effective On time versus Time
+    TH1D fHTimeProb;     // Chisq prob fit of Effective On time versus Time
+    TH1D fHTimeLambda;   // Slope (rate) vs Time
+
+    Bool_t fIsFinalized; // Flag telling you whether fHThetaEffOn is the final result
+
+    UInt_t fNumEvents;   // Number of events to be used for a bin in time
+    UInt_t fFirstBin;    // For bin for fit
+
+    Double_t fTotalTime;    //[s] Total time accumulated from run-header
+    Double_t fEffOnTime;    //[s] On time as fitted from the DeltaT distribution
+    Double_t fEffOnTimeErr; //[s] On time error as fitted from the DeltaT distribution
+
+    // MHEffectiveOnTime
+    Bool_t FitH(TH1D *h, Double_t *res, Bool_t paint=kFALSE) const;
+    void FitThetaBins();
+    void FitTimeBin();
+    void PaintProb(TH1 &h) const;
+    void PaintText(Double_t val, Double_t error, Double_t range=-1) const;
+    void PaintText(Double_t *res) const;
+    void DrawRightAxis(const char *title);
+    void UpdateRightAxis(TH1 &h);
+    void PrintStatistics();
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MHEffectiveOnTime(const char *name=NULL, const char *title=NULL);
+
+    // Setter
+    void SetNumEvents(Int_t i) { fNumEvents=i; }
+    void SetFirstBin(Int_t i)  { fFirstBin=i;  }
+
+    // Getter
+    Double_t GetTotalTime() const { return fTotalTime; }
+    Double_t GetEffOnTime() const { return fEffOnTime; }
+
+    const TH1D &GetHEffOnTheta() const { return fHThetaEffOn; }
+    const TH1D &GetHEffOnTime() const { return fHTimeEffOn; }
+
+    const TH2D &GetH2DeltaT() const { return fH2DeltaT; }
+
+    // TObject
+    void Draw(Option_t *option="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHEffectiveOnTime, 4) // Histogram to determin effective On-Time vs Time and Zenith Angle
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhflux/MHEnergyEst.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHEnergyEst.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHEnergyEst.cc	(revision 17960)
@@ -0,0 +1,615 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 4/2002 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Abelardo Moralejo 5/2003 <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz 1/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHEnergyEst
+//
+//  calculates the migration matrix E-est vs. E-true
+//  for different bins in Theta
+//
+//  Class Version 2:
+//  - fHResolution
+//  + fHResolutionEst
+//  + fHResolutionMC
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHEnergyEst.h"
+
+#include <TF1.h>
+#include <TLine.h>
+#include <TMath.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TProfile.h>
+#include <TPaveStats.h>
+
+#include "MString.h"
+
+#include "MMcEvt.hxx"
+
+#include "MBinning.h"
+#include "MParList.h"
+#include "MParameters.h"
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHEnergyEst);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram.
+//
+MHEnergyEst::MHEnergyEst(const char *name, const char *title)
+    : fMcEvt(0), fEnergy(0), fResult(0), fMatrix(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHEnergyEst";
+    fTitle = title ? title : "Histogram for the result of the energy reconstruction";
+
+    //fNameEnergy = "MEnergyEst";
+    //fNameResult = "MinimizationValue";
+
+    fHEnergy.SetDirectory(NULL);
+    fHEnergy.SetName("EnergyEst");
+    fHEnergy.SetTitle("Histogram in E_{est}, E_{mc} and \\Theta");
+    fHEnergy.SetXTitle("E_{est} [GeV]");
+    fHEnergy.SetYTitle("E_{mc} [GeV]");
+    fHEnergy.SetZTitle("\\Theta [\\circ]");
+
+    fHResolutionEst.SetDirectory(NULL);
+    fHResolutionEst.SetName("ResEnergyEst");
+    fHResolutionEst.SetTitle("Histogram in \\Delta E/E_{est} vs E_{est}");
+    fHResolutionEst.SetXTitle("E_{est} [GeV]");
+    fHResolutionEst.SetYTitle("1-E_{mc}/E_{est}");
+
+    fHResolutionMC.SetDirectory(NULL);
+    fHResolutionMC.SetName("ResEnergyMC");
+    fHResolutionMC.SetTitle("Histogram in \\Delta E/E_{mc} vs E_{mc}");
+    fHResolutionMC.SetXTitle("E_{mc} [GeV]");
+    fHResolutionMC.SetYTitle("E_{est}/E_{mc}-1");
+
+    fHImpact.SetDirectory(NULL);
+    fHImpact.SetName("Impact");
+    fHImpact.SetTitle("\\Delta E/E vs Impact parameter");
+    fHImpact.SetXTitle("Impact parameter [m]");
+    fHImpact.SetYTitle("E_{est}/E_{mc}-1");
+
+    MBinning binsi, binse, binst, binsr;
+    binse.SetEdgesLog(21, 6.3, 100000);
+    binst.SetEdgesASin(51, -0.005, 0.505);
+    binsr.SetEdges(75, -1.75, 1.75);
+
+    // Use the binning in impact to do efficiency studies
+    binsi.SetEdges(1, 0, 1000);
+
+    SetBinning(fHEnergy, binse, binse, binst);
+    SetBinning(fHImpact, binsi, binsr);
+
+    SetBinning(fHResolutionEst, binse, binsr);
+    SetBinning(fHResolutionMC,  binse, binsr);
+
+    // For some unknown reasons this must be called after
+    // the binning has been initialized at least once
+    fHEnergy.Sumw2();
+    fHImpact.Sumw2();
+    fHResolutionEst.Sumw2();
+    fHResolutionMC.Sumw2();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histograms
+//
+Bool_t MHEnergyEst::SetupFill(const MParList *plist)
+{
+    if (!fMatrix)
+    {
+        fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+        if (!fMcEvt)
+        {
+            *fLog << err << "MMcEvt not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fEnergy = (MParameterD*)plist->FindObject("MEnergyEst", "MParameterD");
+    if (!fEnergy)
+    {
+        *fLog << err << "MEnergyEst [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fResult = (MParameterD*)const_cast<MParList*>(plist)->FindCreateObj("MParameterD", "MinimizationValue");
+    if (!fResult)
+        return kFALSE;
+
+    MBinning binst, binse, binsi, binsr;
+    binse.SetEdges(fHEnergy, 'x');
+    binst.SetEdges(fHEnergy, 'z');
+    binsi.SetEdges(fHImpact, 'x');
+    binsr.SetEdges(fHImpact, 'y');
+
+    binst.SetEdges(*plist, "BinningTheta");
+    binse.SetEdges(*plist, "BinningEnergyEst");
+    binsi.SetEdges(*plist, "BinningImpact");
+    binsr.SetEdges(*plist, "BinningEnergyRes");
+
+    SetBinning(fHEnergy, binse, binse, binst);
+    SetBinning(fHImpact, binsi, binsr);
+
+    SetBinning(fHResolutionEst, binse, binsr);
+    SetBinning(fHResolutionMC,  binse, binsr);
+
+    fChisq = 0;
+    fBias  = 0;
+
+    fHEnergy.Reset();
+    fHImpact.Reset();
+
+    fHResolutionEst.Reset();
+    fHResolutionMC.Reset();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+//
+Int_t MHEnergyEst::Fill(const MParContainer *par, const Stat_t w)
+{
+    const Double_t eest  = fEnergy->GetVal();
+    const Double_t etru  = fMatrix ? GetVal(0) : fMcEvt->GetEnergy();
+    const Double_t imp   = fMatrix ? GetVal(1) : fMcEvt->GetImpact()/100;
+    const Double_t theta = fMatrix ? GetVal(2) : fMcEvt->GetTelescopeTheta()*TMath::RadToDeg();
+
+    const Double_t resEst  = (eest-etru)/eest;
+    const Double_t resMC   = (eest-etru)/etru;
+
+    fHEnergy.Fill(eest, etru, theta, w);
+    fHImpact.Fill(imp, resEst, w);
+
+    fHResolutionEst.Fill(eest, resEst, w);
+    fHResolutionMC.Fill(etru, resMC, w);
+
+    // For the fit we use a different quantity
+    //const Double_t res = TMath::Log10(eest/etru);
+    const Double_t res = eest-etru;
+
+    fChisq += res*res;
+    fBias  += res;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Divide chisq and bias by number of executions
+// Print result
+//
+Bool_t MHEnergyEst::Finalize()
+{
+    fChisq /= GetNumExecutions();
+    fBias  /= GetNumExecutions();
+
+    fResult->SetVal(fChisq);
+
+    *fLog << all << endl;
+    Print();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print result
+//
+void MHEnergyEst::Print(Option_t *o) const
+{
+    const Double_t res = TMath::Sqrt(fChisq-fBias*fBias);
+    if (!TMath::Finite(res))
+    {
+        *fLog << all << "MHEnergyEst::Print: ERROR - Resolution is not finite (eg. NaN)." << endl;
+        return;
+    }
+
+    TH1D *h = (TH1D*)fHResolutionEst.ProjectionY("Dummy", -1, -1, "s");
+    h->Fit("gaus", "Q0", "", -1.0, 0.25);
+
+    TF1 *f = h->GetFunction("gaus");
+
+    *fLog << all << "F=" << fChisq << endl;
+    *fLog << "Results from Histogram:" << endl;
+    *fLog << " Mean  of Delta E/E: " << Form("%+4.2f%%", 100*h->GetMean()) << endl;
+    *fLog << " RMS   of Delta E/E: " << Form("%4.2f%%",  100*h->GetRMS()) << endl;
+    *fLog << "Results from Histogram-Fit:" << endl;
+    if (!f)
+        *fLog << " <fit did not succeed>" << endl;
+    else
+    {
+        *fLog << " Bias  of Delta E/E: " << Form("%+4.2f%%", 100*f->GetParameter(1)) << endl;
+        *fLog << " Sigma of Delta E/E: " << Form("%4.2f%%",  100*f->GetParameter(2)) << endl;
+        *fLog << " Res   of Delta E/E: " << Form("%4.2f%%",  100*TMath::Hypot(f->GetParameter(1), f->GetParameter(2))) << endl;
+    }
+
+    delete h;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Correction Coefficients (weights)
+// hist = E_mc/E_est
+//
+void MHEnergyEst::GetWeights(TH1D &hist) const
+{
+    // Project into EnergyEst_ey
+    // the "e" ensures that errors are calculated
+    TH1D *h1 = (TH1D*)fHEnergy.Project3D("rtlprmft_ex"); // E_Est
+    TH1D *h2 = (TH1D*)fHEnergy.Project3D("rtlprmft_ey"); // E_mc
+
+    h2->Copy(hist);
+    hist.Divide(h1);
+
+    delete h1;
+    delete h2;
+
+    hist.SetNameTitle("EnergyRatio", "Ratio between estimated and monte carlo energy");
+    hist.SetXTitle("E [GeV]");
+    hist.SetYTitle("N_{mc}/N_{est} [1]");
+    hist.SetDirectory(0);
+}
+
+void MHEnergyEst::Paint(Option_t *opt)
+{
+    TVirtualPad *pad = gPad;
+
+    pad->cd(1);
+
+    TH1 *hx=0;
+    TH1 *hy=0;
+
+    if (pad->GetPad(1))
+    {
+        pad->GetPad(1)->cd(1);
+
+        if ((hx = dynamic_cast<TH1*>(gPad->FindObject("EnergyEst_ex"))))
+        {
+            hx->GetSumw2()->Set(0); // Workaround. Otherwise we get a warning because it is recreated
+            hx = fHEnergy.Project3D("ex");
+        }
+
+        if ((hy = dynamic_cast<TH1*>(gPad->FindObject("EnergyEst_ey"))))
+        {
+            hy->GetSumw2()->Set(0); // Workaround. Otherwise we get a warning because it is recreated
+            hy = fHEnergy.Project3D("ey");
+        }
+
+        if (hx && hy)
+        {
+            hx->SetLineColor(kBlue);
+            hx->SetMarkerColor(kBlue);
+            hy->SetMaximum();
+            hy->SetMaximum(TMath::Max(hx->GetMaximum(), hy->GetMaximum())*1.2);
+            if (hy->GetMaximum()>0)
+                gPad->SetLogy();
+        }
+
+        if (pad->GetPad(1)->GetPad(2))
+        {
+            pad->GetPad(1)->GetPad(2)->cd(1);
+            if ((hx = dynamic_cast<TH1*>(gPad->FindObject("EnergyEst_ez"))))
+            {
+                hx->GetSumw2()->Set(0); // Workaround. Otherwise we get a warning because it is recreated
+                fHEnergy.Project3D("ez");
+            }
+
+            pad->GetPad(1)->GetPad(2)->cd(2);
+            if (gPad->FindObject("ResEnergyEst_py"))
+            {
+                hx = (TH1D*)fHResolutionEst.ProjectionY("_py", -1, -1, "e");
+                TPaveStats *stats = dynamic_cast<TPaveStats*>(hx->FindObject("stats"));
+                if (stats)
+                {
+                    stats->SetBit(BIT(17)); // TStyle.cxx: kTakeStyle=BIT(17)
+                    stats->SetX1NDC(0.63);
+                    stats->SetY1NDC(0.68);
+                }
+
+                if (hx->GetEntries()>0)
+                {
+                    hx->Fit("gaus", "Q", "", -0.25, 1.0);
+                    if (hx->GetFunction("gaus"))
+                    {
+                        hx->GetFunction("gaus")->SetLineColor(kBlue);
+                        hx->GetFunction("gaus")->SetLineWidth(2);
+                        gPad=NULL;
+                        gStyle->SetOptFit(101);
+                    }
+                }
+            }
+        }
+    }
+
+    if (pad->GetPad(2))
+    {
+        pad->GetPad(2)->cd(1);
+        if (gPad->FindObject("EnergyEst_yx"))
+        {
+            TH2D *hyx = static_cast<TH2D*>(fHEnergy.Project3D("yx"));
+            UpdateProf(*hyx, kTRUE);
+        }
+
+        TLine *l = (TLine*)gPad->FindObject("TLine");
+        if (l)
+        {
+            const Float_t min = TMath::Max(fHEnergy.GetXaxis()->GetXmin(), fHEnergy.GetYaxis()->GetXmin());
+            const Float_t max = TMath::Min(fHEnergy.GetXaxis()->GetXmax(), fHEnergy.GetYaxis()->GetXmax());
+
+            l->SetX1(min);
+            l->SetX2(max);
+            l->SetY1(min);
+            l->SetY2(max);
+        }
+
+        pad->GetPad(2)->cd(2);
+        UpdateProf(fHResolutionMC, kFALSE);
+
+        pad->GetPad(2)->cd(3);
+        UpdateProf(fHResolutionEst, kFALSE);
+    }
+}
+
+void MHEnergyEst::UpdateProf(TH2 &h, Bool_t logy)
+{
+    const TString pname = MString::Format("Prof%s", h.GetName());
+
+    if (!gPad->FindObject(pname))
+        return;
+
+    TH1D *hx = h.ProfileX(pname, -1, -1, "s");
+    hx->SetLineColor(kBlue);
+    hx->SetMarkerColor(kBlue);
+
+    if (logy && hx->GetMaximum()>0)
+        gPad->SetLogy();
+}
+
+TH1 *MHEnergyEst::MakeProj(const char *how)
+{
+    TH1 *p = fHEnergy.Project3D(how);
+    p->SetDirectory(NULL);
+    p->SetBit(kCanDelete);
+    p->SetBit(TH1::kNoStats);
+    p->SetMarkerStyle(kFullDotMedium);
+    p->SetLineColor(kBlue);
+
+    return p;
+}
+
+TH1 *MHEnergyEst::MakeProf(TH2 &h)
+{
+    TH1 *p = h.ProfileX(MString::Format("Prof%s", h.GetName()), -1, -1, "s");
+    p->SetDirectory(NULL);
+    p->SetBit(kCanDelete);
+    p->SetLineWidth(2);
+    p->SetLineColor(kBlue);
+    p->SetFillStyle(4000);
+    p->SetStats(kFALSE);
+
+    return p;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHEnergyEst::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+    // Do the projection before painting the histograms into
+    // the individual pads
+    AppendPad("");
+
+    pad->SetBorderMode(0);
+    pad->Divide(2, 1, 1e-10, 1e-10);
+
+    TH1 *h;
+
+    // ----------------------------------------
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+
+    gPad->Divide(1, 2, 1e-10, 1e-10);
+
+    TVirtualPad *pad2 = gPad;
+
+    // ----------------------------------------
+
+    pad2->cd(1);
+    gPad->SetBorderMode(0);
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+    gPad->SetLogx();
+
+    h = MakeProj("ey");
+    h->SetTitle("Energy disribution: Monte Carlo E_{mc} (black), Estimated E_{est} (blue)");
+    h->SetXTitle("E [GeV]"); // E_mc
+    h->SetYTitle("Counts");
+    h->Draw();
+
+    h->GetXaxis()->SetMoreLogLabels();
+    h->GetXaxis()->SetNoExponent();
+
+    h = MakeProj("ex");
+    h->SetLineColor(kBlue);
+    h->SetMarkerColor(kBlue);
+    h->Draw("same");
+
+    // ----------------------------------------
+
+    pad2->cd(2);
+    gPad->SetBorderMode(0);
+
+    TVirtualPad *pad3 = gPad;
+    pad3->Divide(2, 1, 1e-10, 1e-10);
+    pad3->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    h = MakeProj("ez");
+    h->SetTitle("Zenith Angle Distribution");
+    h->GetXaxis()->SetMoreLogLabels();
+    h->GetXaxis()->SetNoExponent();
+    h->Draw();
+
+    // ----------------------------------------
+
+    pad3->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    h = fHResolutionEst.ProjectionY("_py");
+    h->SetTitle("Distribution of \\Delta E/E_{est}");
+    h->SetDirectory(NULL);
+    h->SetBit(kCanDelete);
+    h->GetXaxis()->SetRangeUser(-1.3, 1.3);
+    h->Draw();
+    // ----------------------------------------
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+
+    gPad->Divide(1, 3, 1e-10, 1e-10);
+    pad2 = gPad;
+
+    // ----------------------------------------
+
+    pad2->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    gPad->SetLogx();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    // Results in crashes....
+    //gROOT->GetListOfCleanups()->Add(gPad); // WHY?
+
+    TH2D *h2 = (TH2D*)fHEnergy.Project3D("yx");
+    h2->SetDirectory(NULL);
+    h2->SetBit(kCanDelete);
+    h2->SetFillColor(kBlue);
+    h2->SetTitle("Estimated energy E_{mc} vs Monte Carlo energy E_{est}");
+
+    h2->Draw("");
+    MakeProf(*h2)->Draw("E0 same");
+
+    h2->GetXaxis()->SetMoreLogLabels();
+    h2->GetXaxis()->SetNoExponent();
+
+    TLine line;
+    line.DrawLine(0,0,1,1);
+
+    line.SetLineColor(kBlue);
+    line.SetLineWidth(2);
+    line.SetLineStyle(kDashed);
+
+    // ----------------------------------------
+
+    pad2->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHResolutionMC.Draw();
+    MakeProf(fHResolutionMC)->Draw("E0 same");
+
+    fHResolutionMC.GetXaxis()->SetMoreLogLabels();
+    fHResolutionMC.GetXaxis()->SetNoExponent();
+
+    line.DrawLine(fHResolutionMC.GetXaxis()->GetXmin(), 0, fHResolutionMC.GetXaxis()->GetXmax(), 0);
+
+    // ----------------------------------------
+
+    pad2->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHResolutionEst.Draw();
+    MakeProf(fHResolutionEst)->Draw("E0 same");
+
+    fHResolutionEst.GetXaxis()->SetMoreLogLabels();
+    fHResolutionEst.GetXaxis()->SetNoExponent();
+
+    line.DrawLine(fHResolutionEst.GetXaxis()->GetXmin(), 0, fHResolutionEst.GetXaxis()->GetXmax(), 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MHEnergyEst::GetVal(Int_t i) const
+{
+    return (*fMatrix)[fMap[i]];
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam2::Process
+// will take the values from the matrix instead of the containers.
+//
+void MHEnergyEst::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MMcEvt.fEnergy");
+    fMap[1] = fMatrix->AddColumn("MMcEvt.fImpact/100");
+    fMap[2] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta*kRad2Deg");
+}
+
+void MHEnergyEst::StopMapping()
+{
+    fMatrix = NULL; 
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHEnergyEst.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHEnergyEst.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHEnergyEst.h	(revision 17960)
@@ -0,0 +1,69 @@
+#ifndef MARS_MHEnergyEst
+#define MARS_MHEnergyEst
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MParList;
+class MParameterD;
+class MHMatrix;
+
+class MHEnergyEst : public MH
+{
+private:
+    //TString      fNameEnergy;
+    //TString      fNameResult;
+
+    MMcEvt      *fMcEvt;  //!
+    MParameterD *fEnergy; //!
+    MParameterD *fResult; //!
+
+    Int_t        fMap[100]; // FIXME!
+    MHMatrix    *fMatrix; //!
+
+    TH3D fHEnergy;
+    TH2D fHResolutionEst;
+    TH2D fHResolutionMC;
+    TH2D fHImpact;
+
+    Double_t fChisq;
+    Double_t fBias;
+
+    TH1 *MakeProj(const char *how);
+    TH1 *MakeProf(TH2 &h);
+    void UpdateProf(TH2 &h, Bool_t logy);
+
+    Double_t GetVal(Int_t i) const;
+    void     CalcChisq(Double_t &chisq, Double_t &prob) const;
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+public:
+    MHEnergyEst(const char *name=NULL, const char *title=NULL);
+
+    const TH3D &GetHEnergy() const { return fHEnergy; }
+    void GetWeights(TH1D &hist) const;
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping();
+
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+    void Print(Option_t *o="") const;
+
+    ClassDef(MHEnergyEst, 2) // Histogram for the result of the energy reconstruction
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHFalseSource.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHFalseSource.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHFalseSource.cc	(revision 17960)
@@ -0,0 +1,1429 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHFalseSource
+//
+// Create a false source plot. For the Binning in x,y the object MBinning
+// "BinningFalseSource" is taken from the paremeter list.
+//
+// The binning in alpha is currently fixed as 18bins from 0 to 90deg.
+//
+// If MTime, MObservatory and MPointingPos is available in the paremeter
+// list each image is derotated.
+//
+// MHFalseSource fills a 3D histogram with alpha distribution for
+// each (derotated) x and y position.
+//
+// Only a radius of 1.2deg around the camera center is taken into account.
+//
+// The displayed histogram is the projection of alpha<fAlphaCut into
+// the x,y plain and the projection of alpha>90-fAlphaCut
+//
+// By using the context menu (find it in a small region between the single
+// pads) you can change the AlphaCut 'online'
+//
+// Each Z-Projection (Alpha-histogram) is scaled such, that the number
+// of entries fits the maximum number of entries in all Z-Projections.
+// This should correct for the different acceptance in the center
+// and at the vorder of the camera. This, however, produces more noise
+// at the border.
+//
+// Here is a slightly simplified version of the algorithm:
+// ------------------------------------------------------
+//    MHillas hil; // Taken as second argument in MFillH
+//
+//    MSrcPosCam src;
+//    MHillasSrc hsrc;
+//    hsrc.SetSrcPos(&src);
+//
+//    for (int ix=0; ix<nx; ix++)
+//        for (int iy=0; iy<ny; iy++)
+//        {
+//            TVector2 v(cx[ix], cy[iy]); //cx center of x-bin ix
+//            if (rho!=0)                 //cy center of y-bin iy
+//                v=v.Rotate(rho);         //image rotation angle
+//
+//            src.SetXY(v);               //source position in the camera
+//
+//            if (!hsrc.Calc(hil))        //calc source dependant hillas
+//                return;
+//
+//            //fill absolute alpha into histogram
+//            const Double_t alpha = hsrc.GetAlpha();
+//            fHist.Fill(cx[ix], cy[iy], TMath::Abs(alpha), w);
+//        }
+//    }
+//
+// Use MHFalse Source like this:
+// -----------------------------
+//    MFillH fill("MHFalseSource", "MHillas");
+// or
+//    MHFalseSource hist;
+//    hist.SetAlphaCut(12.5);  // The default value
+//    hist.SetBgmean(55);      // The default value
+//    MFillH fill(&hist, "MHillas");
+//
+// To be implemented:
+// ------------------
+//  - a switch to use alpha or |alpha|
+//  - taking the binning for alpha from the parlist (binning is
+//    currently fixed)
+//  - a possibility to change the fit-function (eg using a different TF1)
+//  - a possibility to change the fit algorithm (eg which paremeters
+//    are fixed at which time)
+//  - use a different varaible than alpha
+//  - a possiblity to change the algorithm which is used to calculate
+//    alpha (or another parameter) is missing (this could be done using
+//    a tasklist somewhere...)
+//  - a more clever (and faster) algorithm to fill the histogram, eg by
+//    calculating alpha once and fill the two coils around the mean
+//  - more drawing options...
+//  - Move Significance() to a more 'general' place and implement
+//    also different algorithms like (Li/Ma)
+//  - implement fit for best alpha distribution -- online (Paint)
+//  - currently a constant pointing position is assumed in Fill()
+//  - the center of rotation need not to be the camera center
+//  - ERRORS on each alpha bin to estimate the chi^2 correctly!
+//    (sqrt(N)/binwidth) needed for WOlfgangs proposed caluclation
+//    of alpha(Li/Ma)
+//  - use the g/h-separation filters from the tasklists ("Cut1") as filters
+//    two
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHFalseSource.h"
+
+#include <TF1.h>
+#include <TF2.h>
+#include <TH2.h>
+#include <TLatex.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TRandom.h>
+#include <TEllipse.h>
+#include <TPaveText.h>
+#include <TStopwatch.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillas.h"
+#include "MHillasSrc.h"
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MAstroCatalog.h"
+#include "MAstroSky2Local.h"
+#include "MStatusDisplay.h"
+
+#include "MMath.h"
+#include "MAlphaFitter.h"
+
+#include "MString.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHFalseSource);
+
+using namespace std;
+
+//class MHillasExt;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHFalseSource::MHFalseSource(const char *name, const char *title)
+    : fTime(0), fPointPos(0), fObservatory(0), fMm2Deg(-1), fAlphaCut(12.5),
+    fBgMean(55), fMinDist(-1), fMaxDist(-1), fMinDW(-1), fMaxDW(-1),
+    fHistOff(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHFalseSource";
+    fTitle = title ? title : "3D-plot of Alpha vs x, y";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetName("Alpha");
+    fHist.SetTitle("3D-plot of Alpha vs x, y");
+    fHist.SetXTitle("x [\\circ]");
+    fHist.SetYTitle("y [\\circ]");
+    fHist.SetZTitle("\\alpha [\\circ]");
+}
+
+void MHFalseSource::MakeSymmetric(TH1 *h)
+{
+    h->SetMinimum();
+    h->SetMaximum();
+
+    const Float_t min = TMath::Abs(h->GetMinimum());
+    const Float_t max = TMath::Abs(h->GetMaximum());
+
+    const Float_t absmax = TMath::Max(min, max)*1.002;
+
+    h->SetMaximum( absmax);
+    h->SetMinimum(-absmax);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the alpha cut (|alpha|<fAlphaCut) which is use to estimate the
+// number of excess events
+//
+void MHFalseSource::SetAlphaCut(Float_t alpha)
+{
+    if (alpha<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    fAlphaCut = TMath::Abs(alpha);
+
+    Modified();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set mean alpha around which the off sample is determined
+// (fBgMean-fAlphaCut/2<|fAlpha|<fBgMean+fAlphaCut/2) which is use
+// to estimate the number of off events
+//
+void MHFalseSource::SetBgMean(Float_t alpha)
+{
+    if (alpha<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    fBgMean = TMath::Abs(alpha);
+
+    Modified();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningFalseSource) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+//
+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();
+
+    const TString off(MString::Format("%sOff", fName.Data()));
+    if (fName!=off && fHistOff==NULL)
+    {
+        const TString desc(MString::Format("%s [%s] found... using ", off.Data(), ClassName()));
+        MHFalseSource *hoff = (MHFalseSource*)plist->FindObject(off, ClassName());
+        if (!hoff)
+            *fLog << inf << "No " << desc << "current data only!" << endl;
+        else
+        {
+            *fLog << inf << desc << "on-off mode!" << endl;
+            SetOffData(*hoff);
+        }
+    }
+
+    if (fHistOff)
+        MH::CopyBinning(*fHistOff, fHist);
+    else
+    {
+        MBinning binsa(18, 0, 90);
+        binsa.SetEdges(*plist, "BinningAlpha");
+
+        const MBinning *bins = (MBinning*)plist->FindObject("BinningFalseSource");
+        if (!bins || bins->IsDefault())
+        {
+            const Float_t r = (geom ? geom->GetMaxRadius()/3 : 200)*fMm2Deg;
+
+            const MBinning b(20, -r, r);
+            SetBinning(fHist, b, b, binsa);
+        }
+        else
+            SetBinning(fHist, *bins, *bins, binsa);
+    }
+
+    fPointPos = (MPointingPos*)plist->FindObject(AddSerialNumber("MPointingPos"));
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... no derotation." << endl;
+
+    fTime = (MTime*)plist->FindObject(AddSerialNumber("MTime"));
+    if (!fTime)
+        *fLog << warn << "MTime not found... no derotation." << endl;
+
+    fSrcPos = (MSrcPosCam*)plist->FindObject(AddSerialNumber("MSrcPosCam"));
+    if (!fSrcPos)
+        *fLog << warn << "MSrcPosCam not found... no translation." << endl;
+
+    fObservatory = (MObservatory*)plist->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+        *fLog << warn << "MObservatory not found... no derotation." << endl;
+
+    MPointingPos *point = (MPointingPos*)plist->FindObject("MSourcePos", "MPointingPos");
+    if (!point)
+        point = fPointPos;
+
+    // FIXME: Because the pointing position could change we must check
+    // for the current pointing position and add a offset in the
+    // Fill function!
+    fRa  = point ? point->GetRa()  :  0;
+    fDec = point ? point->GetDec() : 90;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Int_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 kERROR;
+    }
+
+    // Get max radius...
+    const Double_t maxr = 0.98*TMath::Abs(fHist.GetBinCenter(1));
+
+    // Get camera rotation angle
+    Double_t rho = 0;
+    if (fTime && fObservatory && fPointPos)
+        rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+    //if (fPointPos)
+    //    rho = fPointPos->RotationAngle(*fObservatory);
+
+    // Create necessary containers for calculation
+    MSrcPosCam src;
+    MHillasSrc hsrc;
+    hsrc.SetSrcPos(&src);
+
+    // Get number of bins and bin-centers
+    const Int_t nx = fHist.GetNbinsX();
+    const Int_t ny = fHist.GetNbinsY();
+    Axis_t cx[nx];
+    Axis_t cy[ny];
+    fHist.GetXaxis()->GetCenter(cx);
+    fHist.GetYaxis()->GetCenter(cy);
+
+    for (int ix=0; ix<nx; ix++)
+    {
+        for (int iy=0; iy<ny; iy++)
+        {
+            // check distance... to get a circle plot
+            if (TMath::Hypot(cx[ix], cy[iy])>maxr)
+                continue;
+
+            // rotate center of bin
+            // precalculation of sin/cos doesn't accelerate
+            TVector2 v(cx[ix], cy[iy]);
+            if (rho!=0)
+                v=v.Rotate(rho);
+
+            // convert degrees to millimeters
+            v *= 1./fMm2Deg;
+
+            if (fSrcPos)
+                v += fSrcPos->GetXY();
+
+            src.SetXY(v);
+
+            // Source dependant hillas parameters
+            if (hsrc.Calc(*hil/*, ext*/)>0)
+            {
+                *fLog << warn << "Calculation of MHillasSrc failed for x=" << cx[ix] << " y=" << cy[iy] << endl;
+                return kFALSE;
+            }
+
+            // FIXME: This should be replaced by an external MFilter
+            //        and/or MTaskList
+            // Source dependant distance cut
+            if (fMinDist>0 && hsrc.GetDist()*fMm2Deg<fMinDist)
+                continue;
+            if (fMaxDist>0 && hsrc.GetDist()*fMm2Deg>fMaxDist)
+                continue;
+
+            if (fMaxDW>0 && hsrc.GetDist()>fMaxDW*hil->GetWidth())
+                continue;
+            if (fMinDW<0 && hsrc.GetDist()<fMinDW*hil->GetWidth())
+                continue;
+
+            // Fill histogram
+            const Double_t alpha = hsrc.GetAlpha();
+            fHist.Fill(cx[ix], cy[iy], TMath::Abs(alpha), w);
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Create projection for off data, taking sum of bin contents of
+// range (fBgMean-fAlphaCut/2, fBgMean+fAlphaCut) Making sure to take
+// the same number of bins than for on-data
+//
+void MHFalseSource::ProjectOff(const TH3D &src, TH2D *h2, TH2D *hall)
+{
+    TAxis &axe = *src.GetZaxis();
+
+    // Find range to cut (left edge and width)
+    const Int_t f = axe.FindBin(fBgMean-fAlphaCut/2);
+    const Int_t l = axe.FindBin(fAlphaCut)+f-1;
+
+    axe.SetRange(f, l);
+    const Float_t cut1 = axe.GetBinLowEdge(f);
+    const Float_t cut2 = axe.GetBinUpEdge(l);
+    h2->SetTitle(MString::Format("Distribution of %.1f\\circ<|\\alpha|<%.1f\\circ in x,y", cut1, cut2));
+
+    // Get projection for range
+    TH2D *p = (TH2D*)src.Project3D("yx_off_NULL");
+
+    // Reset range
+    axe.SetRange(0,9999);
+
+//#if ROOT_VERSION_CODE < ROOT_VERSION(4,02,00)
+    // Move contents from projection to h2
+    h2->Reset();
+    h2->Add(p, hall->GetMaximum());
+    h2->Divide(hall);
+
+    // Delete p
+    delete p;
+/*#else
+    p->Scale(all->GetMaximum());
+    p->Divide(all);
+#endif*/
+
+    // Set Minimum as minimum value Greater Than 0
+    h2->SetMinimum(GetMinimumGT(*h2));
+}
+
+// --------------------------------------------------------------------------
+//
+// Create projection for on data, taking sum of bin contents of
+// range (0, fAlphaCut)
+//
+void MHFalseSource::ProjectOn(const TH3D &src, TH2D *h3, TH2D *hall)
+{
+    TAxis &axe = *src.GetZaxis();
+
+    // Find range to cut
+    axe.SetRangeUser(0, fAlphaCut);
+    const Float_t cut = axe.GetBinUpEdge(axe.GetLast());
+    h3->SetTitle(MString::Format("Distribution of |\\alpha|<%.1f\\circ in x,y", cut));
+
+    // Get projection for range
+    TH2D *p = (TH2D*)src.Project3D("yx_on_NULL");
+
+    // Reset range
+    axe.SetRange(0,9999);
+
+//#if ROOT_VERSION_CODE < ROOT_VERSION(4,02,00)
+    // Move contents from projection to h3
+    h3->Reset();
+    h3->Add(p, hall->GetMaximum());
+    h3->Divide(hall);
+
+    // Delete p
+    delete p;
+/*#else
+    p->Scale(all->GetMaximum());
+    p->Divide(all);
+#endif*/
+
+    // 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
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,02,00)
+    TH2D *p = (TH2D*)fHist.Project3D("yx_all");
+
+    // Move contents from projection to h3
+    h3->Reset();
+    h3->Add(p);
+    delete p;
+#else
+    fHist.Project3D("yx_all");
+#endif
+
+    // Set Minimum as minimum value Greater Than 0
+    h3->SetMinimum(GetMinimumGT(*h3));
+}
+
+void MHFalseSource::ProjectOnOff(TH2D *h2, TH2D *h0)
+{
+    ProjectOn(*fHistOff, h2, h0);
+
+    TH2D h;
+    MH::SetBinning(h, *h2);
+
+    // Divide by number of entries in off region (of off-data)
+    ProjectOff(*fHistOff, &h, h0);
+    h2->Divide(&h);
+
+    // Multiply by number of entries in off region (of on-data)
+    ProjectOff(fHist, &h, h0);
+    h2->Multiply(&h);
+
+    // Recalculate Minimum
+    h2->SetMinimum(GetMinimumGT(*h2));
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the projections and paint them
+//
+void MHFalseSource::Paint(Option_t *opt)
+{
+    // Set pretty color palette
+    gStyle->SetPalette(1, 0);
+
+    TVirtualPad *padsave = gPad;
+
+    TH1D* h1;
+    TH2D* h0;
+    TH2D* h2;
+    TH2D* h3;
+    TH2D* h4;
+    TH2D* h5;
+
+    // Update projection of all-events
+    padsave->GetPad(2)->cd(3);
+    if ((h0 = (TH2D*)gPad->FindObject("Alpha_yx_all")))
+        ProjectAll(h0);
+
+    // Update projection of on-events
+    padsave->GetPad(1)->cd(1);
+    if ((h3 = (TH2D*)gPad->FindObject("Alpha_yx_on")))
+        ProjectOn(fHist, h3, h0);
+
+    // Update projection of off-events
+    padsave->GetPad(1)->cd(3);
+    if ((h2 = (TH2D*)gPad->FindObject("Alpha_yx_off")))
+    {
+        if (!fHistOff)
+            ProjectOff(fHist, h2, h0);
+        else
+            ProjectOnOff(h2, h0);
+    }
+
+    padsave->GetPad(2)->cd(2);
+    if ((h5 = (TH2D*)gPad->FindObject("Alpha_yx_diff")))
+    {
+        h5->Add(h2, h3, -1);
+        MakeSymmetric(h5);
+    }
+
+    // Update projection of significance
+    padsave->GetPad(1)->cd(2);
+    if (h2 && h3 && (h4 = (TH2D*)gPad->FindObject("Alpha_yx_sig")))
+    {
+        const Int_t nx = h4->GetXaxis()->GetNbins();
+        const Int_t ny = h4->GetYaxis()->GetNbins();
+
+        Int_t maxx=nx/2;
+        Int_t maxy=ny/2;
+
+        Int_t max = h4->GetBin(nx, ny);
+
+        h4->SetEntries(0);
+        for (int ix=1; ix<=nx; ix++)
+            for (int iy=1; iy<=ny; iy++)
+            {
+                const Int_t n = h4->GetBin(ix, iy);
+
+                const Double_t s = h3->GetBinContent(n);
+                const Double_t b = h2->GetBinContent(n);
+
+                const Double_t sig = MMath::SignificanceLiMaSigned(s, b);
+
+                h4->SetBinContent(n, sig);
+
+                if (sig>h4->GetBinContent(max) && sig>0/* && (ix-nx/2)*(ix-nx/2)+(iy-ny/2)*(iy-ny/2)<nr*nr/9*/)
+                {
+                    max = n;
+                    maxx=ix;
+                    maxy=iy;
+                }
+            }
+
+        MakeSymmetric(h4);
+
+        // Update projection of 'the best alpha-plot'
+        padsave->GetPad(2)->cd(1);
+        if ((h1 = (TH1D*)gPad->FindObject("Alpha_z")) && max>0)
+        {
+            const Double_t x = h4->GetXaxis()->GetBinCenter(maxx);
+            const Double_t y = h4->GetYaxis()->GetBinCenter(maxy);
+            const Double_t s = h4->GetBinContent(max);
+
+            // This is because a 3D histogram x and y are vice versa
+            // Than for their projections
+            TH1 *h = fHist.ProjectionZ("Alpha_z", maxx, maxx, maxy, maxy);
+            h->SetTitle(MString::Format("Distribution of \\alpha for x=%.2f y=%.2f (S_{max}=%.1f\\sigma)", x, y, s));
+
+            TH1D *ho=0;
+            if ((ho = (TH1D*)gPad->FindObject("AlphaOff_z")))
+            {
+                fHistOff->ProjectionZ("AlphaOff_z", maxx, maxx, maxy, maxy);
+
+                /* ============= local scaling ================ */
+                const Int_t f = ho->GetXaxis()->FindFixBin(fBgMean-1.5*fAlphaCut);
+                const Int_t l = ho->GetXaxis()->FindFixBin(fAlphaCut*3)+f-1;
+                ho->Scale(h1->Integral(f, l)/ho->Integral(f, l));
+
+
+                //h0->Scale(h1->GetEntries()/h0->GetEntries());
+
+                /* ============= global scaling ================
+                const Int_t f = fHistOff->GetZaxis()->FindFixBin(fBgMean-1.5*fAlphaCut);
+                const Int_t l = fHistOff->GetZaxis()->FindFixBin(fAlphaCut*3)+f-1;
+
+                Double_t c0 = fHist.Integral(0, 9999, 0, 9999, f, l);
+                Double_t c1 = fHistOff->Integral(0, 9999, 0, 9999, f, l);
+
+                h0->Scale(c0/c1);
+                */
+            }
+        }
+    }
+
+    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
+{
+    const Double_t maxr = TMath::Abs(fHist.GetBinLowEdge(1))*TMath::Sqrt(2);
+
+    // Create catalog...
+    MAstroCatalog *stars = new MAstroCatalog;
+    stars->SetMarkerColor(kWhite);
+    stars->SetLimMag(9);
+    stars->SetGuiActive(kFALSE);
+    stars->SetRadiusFOV(maxr);
+    stars->SetRaDec(fRa*TMath::DegToRad()*15, fDec*TMath::DegToRad());
+    stars->ReadBSC("bsc5.dat");
+
+    stars->SetBit(kCanDelete);
+    return stars;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHFalseSource::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(1, 2, 1e-10, 0.03);
+
+//    TObject *catalog = GetCatalog();
+
+    // Initialize upper part
+    pad->cd(1);
+    // Make sure that the catalog is deleted only once
+    // Normally this is not done by root, because it is not necessary...
+    // but in this case it is necessary, because the catalog is
+    // deleted by the first pad and the second one tries to do the same!
+//    gROOT->GetListOfCleanups()->Add(gPad);
+    gPad->SetBorderMode(0);
+    gPad->Divide(3, 1);
+
+    // PAD #1
+    pad->GetPad(1)->cd(1);
+    gPad->SetBorderMode(0);
+    fHist.GetZaxis()->SetRangeUser(0,fAlphaCut);
+    TH1 *h3 = fHist.Project3D("yx_on");
+    fHist.GetZaxis()->SetRange(0,9999);
+    h3->SetDirectory(NULL);
+    h3->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h3->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h3->Draw("colz");
+    h3->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // PAD #2
+    pad->GetPad(1)->cd(2);
+    gPad->SetBorderMode(0);
+    fHist.GetZaxis()->SetRange(0,0);
+    TH1 *h4 = fHist.Project3D("yx_sig"); // Do this to get the correct binning....
+    fHist.GetZaxis()->SetRange(0,9999);
+    h4->SetTitle("Significance");
+    h4->SetDirectory(NULL);
+    h4->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h4->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h4->Draw("colz");
+    h4->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // PAD #3
+    pad->GetPad(1)->cd(3);
+    gPad->SetBorderMode(0);
+    TH1 *h2 = 0;
+    if (fHistOff)
+    {
+        fHistOff->GetZaxis()->SetRangeUser(0,fAlphaCut);
+        h2 = fHistOff->Project3D("yx_off");
+        fHistOff->GetZaxis()->SetRange(0,9999);
+    }
+    else
+    {
+        fHist.GetZaxis()->SetRangeUser(fBgMean-fAlphaCut/2, fBgMean+fAlphaCut/2);
+        h2 = fHist.Project3D("yx_off");
+        fHist.GetZaxis()->SetRange(0,9999);
+    }
+    h2->SetDirectory(NULL);
+    h2->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h2->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h2->Draw("colz");
+    h2->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // Initialize lower part
+    pad->cd(2);
+    // Make sure that the catalog is deleted only once
+//    gROOT->GetListOfCleanups()->Add(gPad);
+    gPad->SetBorderMode(0);
+    gPad->Divide(3, 1);
+
+    // PAD #4
+    pad->GetPad(2)->cd(1);
+    gPad->SetBorderMode(0);
+    TH1 *h1 = fHist.ProjectionZ("Alpha_z");
+    h1->SetDirectory(NULL);
+    h1->SetTitle("Distribution of \\alpha");
+    h1->SetXTitle(fHist.GetZaxis()->GetTitle());
+    h1->SetYTitle("Counts");
+    h1->Draw();
+    h1->SetBit(kCanDelete);
+    if (fHistOff)
+    {
+        h1->SetLineColor(kGreen);
+
+        h1 = fHistOff->ProjectionZ("AlphaOff_z");
+        h1->SetDirectory(NULL);
+        h1->SetTitle("Distribution of \\alpha");
+        h1->SetXTitle(fHistOff->GetZaxis()->GetTitle());
+        h1->SetYTitle("Counts");
+        h1->Draw("same");
+        h1->SetBit(kCanDelete);
+        h1->SetLineColor(kRed);
+    }
+
+    // PAD #5
+    pad->GetPad(2)->cd(2);
+    gPad->SetBorderMode(0);
+    TH1 *h5 = (TH1*)h3->Clone("Alpha_yx_diff");
+    h5->Add(h2, -1);
+    h5->SetTitle("Difference of on- and off-distribution");
+    h5->SetDirectory(NULL);
+    h5->Draw("colz");
+    h5->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // PAD #6
+    pad->GetPad(2)->cd(3);
+    gPad->SetBorderMode(0);
+    TH1 *h0 = fHist.Project3D("yx_all");
+    h0->SetDirectory(NULL);
+    h0->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h0->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h0->Draw("colz");
+    h0->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+}
+
+// --------------------------------------------------------------------------
+//
+// Everything which is in the main pad belongs to this class!
+//
+Int_t MHFalseSource::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set all sub-pads to Modified()
+//
+void MHFalseSource::Modified()
+{
+    if (!gPad)
+        return;
+
+    TVirtualPad *padsave = gPad;
+    padsave->Modified();
+    padsave->GetPad(1)->cd(1);
+    gPad->Modified();
+    padsave->GetPad(1)->cd(3);
+    gPad->Modified();
+    padsave->GetPad(2)->cd(1);
+    gPad->Modified();
+    padsave->GetPad(2)->cd(2);
+    gPad->Modified();
+    padsave->GetPad(2)->cd(3);
+    gPad->Modified();
+    gPad->cd();
+}
+
+// --------------------------------------------------------------------------
+//
+// The following resources are available:
+//
+//    MHFalseSource.DistMin: 0.5
+//    MHFalseSource.DistMax: 1.4
+//    MHFalseSource.DWMin:   0.1
+//    MHFalseSource.DWMax:   0.3
+//
+Int_t MHFalseSource::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "DistMin", print))
+    {
+        rc = kTRUE;
+        SetMinDist(GetEnvValue(env, prefix, "DistMin", fMinDist));
+    }
+    if (IsEnvDefined(env, prefix, "DistMax", print))
+    {
+        rc = kTRUE;
+        SetMaxDist(GetEnvValue(env, prefix, "DistMax", fMaxDist));
+    }
+
+    if (IsEnvDefined(env, prefix, "DWMin", print))
+    {
+        rc = kTRUE;
+        SetMinDW(GetEnvValue(env, prefix, "DWMin", fMinDist));
+    }
+    if (IsEnvDefined(env, prefix, "DWMax", print))
+    {
+        rc = kTRUE;
+        SetMaxDW(GetEnvValue(env, prefix, "DWMax", fMaxDist));
+    }
+
+    return rc;
+}
+
+static Double_t FcnGauss2d(Double_t *x, Double_t *par)
+{
+    TVector2 v = TVector2(x[0], x[1]).Rotate(par[5]*TMath::DegToRad());
+
+    const Double_t g0 = TMath::Gaus(v.X(), par[1], par[2]);
+    const Double_t g1 = TMath::Gaus(v.Y(), par[3], par[4]);
+
+    //Gaus(Double_t x, Double_t mean=0, Double_t sigma=1, Bool_t norm=kFALSE);
+    return par[0]*g0*g1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a preliminary implementation of a alpha-fit procedure for
+// all possible source positions. It will be moved into its own
+// more powerfull class soon.
+//
+// The fit function is "gaus(0)+pol2(3)" which is equivalent to:
+//   [0]*exp(-0.5*((x-[1])/[2])^2) + [3] + [4]*x + [5]*x^2
+// or
+//   A*exp(-0.5*((x-mu)/sigma)^2) + a + b*x + c*x^2
+//
+// Parameter [1] is fixed to 0 while the alpha peak should be
+// symmetric around alpha=0.
+//
+// Parameter [4] is fixed to 0 because the first derivative at
+// alpha=0 should be 0, too.
+//
+// In a first step the background is fitted between bgmin and bgmax,
+// while the parameters [0]=0 and [2]=1 are fixed.
+//
+// In a second step the signal region (alpha<sigmax) is fittet using
+// the whole function with parameters [1], [3], [4] and [5] fixed.
+//
+// The number of excess and background events are calculated as
+//   s = int(0, sigint, gaus(0)+pol2(3))
+//   b = int(0, sigint,         pol2(3))
+//
+// The Significance is calculated using the Significance() member
+// function.
+//
+void MHFalseSource::FitSignificance(Float_t sigint, Float_t sigmax, Float_t bgmin, Float_t bgmax, Byte_t polynom)
+{
+//    TObject *catalog = GetCatalog();
+
+    TH1D h0a("A",          "", 50,   0, 4000);
+    TH1D h4a("chisq1",     "", 50,   0,   35);
+    //TH1D h5a("prob1",      "", 50,   0,  1.1);
+    TH1D h6("signifcance", "", 50, -20,   20);
+
+    TH1D h1("mu",    "Parameter \\mu",    50,   -1,    1);
+    TH1D h2("sigma", "Parameter \\sigma", 50,    0,   90);
+    TH1D h3("b",     "Parameter b",       50, -0.1,  0.1);
+
+    TH1D h0b("a",         "Parameter a (red), A (blue)", 50, 0, 4000);
+    TH1D h4b("\\chi^{2}", "\\chi^{2} (red, green) / significance (black)", 50, 0, 35);
+    //TH1D h5b("prob",      "Fit probability: Bg(red), F(blue)", 50, 0, 1.1);
+
+    h0a.SetLineColor(kBlue);
+    h4a.SetLineColor(kBlue);
+    //h5a.SetLineColor(kBlue);
+    h0b.SetLineColor(kRed);
+    h4b.SetLineColor(kRed);
+    //h5b.SetLineColor(kRed);
+
+    TH1 *hist  = fHist.Project3D("yx_fit");
+    hist->SetDirectory(0);
+    TH1 *hists = fHist.Project3D("yx_fit");
+    hists->SetDirectory(0);
+    TH1 *histb = fHist.Project3D("yx_fit");
+    histb->SetDirectory(0);
+    hist->Reset();
+    hists->Reset();
+    histb->Reset();
+    hist->SetNameTitle("Significance",
+                       MString::Format("Fit Region: Signal<%.1f\\circ, %.1f\\circ<Bg<%.1f\\circ",
+                                       sigmax, bgmin, bgmax));
+    hists->SetName("Excess");
+    histb->SetName("Background");
+    hist->SetXTitle(fHist.GetXaxis()->GetTitle());
+    hists->SetXTitle(fHist.GetXaxis()->GetTitle());
+    histb->SetXTitle(fHist.GetXaxis()->GetTitle());
+    hist->SetYTitle(fHist.GetYaxis()->GetTitle());
+    hists->SetYTitle(fHist.GetYaxis()->GetTitle());
+    histb->SetYTitle(fHist.GetYaxis()->GetTitle());
+
+    const Double_t w = fHist.GetZaxis()->GetBinWidth(1);
+
+    TArrayD maxpar;
+
+    /*  func.SetParName(0, "A");
+     *  func.SetParName(1, "mu");
+     *  func.SetParName(2, "sigma");
+    */
+
+    const Int_t nx = hist->GetXaxis()->GetNbins();
+    const Int_t ny = hist->GetYaxis()->GetNbins();
+    //const Int_t nr = nx*nx+ny*ny;
+
+    Double_t maxalpha0=0;
+    Double_t maxs=3;
+
+    Int_t maxx=0;
+    Int_t maxy=0;
+
+    TStopwatch clk;
+    clk.Start();
+
+    *fLog << inf;
+    *fLog << "Signal fit:     alpha < " << sigmax << endl;
+    *fLog << "Integration:    alpha < " << sigint << endl;
+    *fLog << "Background fit: " << bgmin << " < alpha < " << bgmax << endl;
+    *fLog << "Polynom order:  " << (int)polynom << endl;
+    *fLog << "Fitting False Source Plot..." << flush;
+
+    TH1 *h0 = fHist.Project3D("yx_entries");
+    Float_t entries = h0->GetMaximum();
+    delete h0;
+
+    MAlphaFitter fit;
+    fit.SetSignalIntegralMax(sigint);
+    fit.SetSignalFitMax(sigmax);
+    fit.SetBackgroundFitMin(bgmin);
+    fit.SetBackgroundFitMax(bgmax);
+    fit.SetPolynomOrder(polynom);
+
+    TH1D *h=0, *hoff=0;
+    Double_t scale = 1;
+    for (int ix=1; ix<=nx; ix++)
+        for (int iy=1; iy<=ny; iy++)
+        {
+            // This is because a 3D histogram x and y are vice versa
+            // Than for their projections
+            h = fHist.ProjectionZ("AlphaFit", ix, ix, iy, iy);
+
+            if (h->GetEntries()==0)
+                continue;
+
+            // This is a quick hack to correct for the lower acceptance at
+            // the edge of the camera
+            h->Scale(entries/h->GetEntries());
+
+            if (fHistOff)
+            {
+                hoff = fHistOff->ProjectionZ("AlphaFitOff", ix, ix, iy, iy);
+                // This is a quick hack to correct for the lower acceptance at
+                // the edge of the camera
+                hoff->Scale(entries/h->GetEntries());
+                scale = fit.Scale(*hoff, *h);
+            }
+
+            if (!fit.Fit(*h, hoff, scale))
+                continue;
+
+            const Double_t alpha0 = h->GetBinContent(1);
+            if (alpha0>maxalpha0)
+                maxalpha0=alpha0;
+ 
+            // Fill results into some histograms
+            h0a.Fill(fit.GetGausA());        // gaus-A
+            h0b.Fill(fit.GetCoefficient(3)); // 3
+            h1.Fill(fit.GetGausMu());        // mu
+            h2.Fill(fit.GetGausSigma());     // sigma-gaus
+            if (polynom>1 && !fHistOff)
+                h3.Fill(fit.GetCoefficient(5));
+            h4b.Fill(fit.GetChiSqSignal());
+
+            const Double_t sig = fit.GetSignificance();
+            const Double_t b   = fit.GetEventsBackground();
+            const Double_t s   = fit.GetEventsSignal();
+
+            const Int_t n = hist->GetBin(ix, iy);
+            hists->SetBinContent(n, s-b);
+            histb->SetBinContent(n, b);
+
+            hist->SetBinContent(n, sig);
+            if (sig!=0)
+                h6.Fill(sig);
+
+            if (sig>maxs)
+            {
+                maxs = sig;
+                maxx = ix;
+                maxy = iy;
+                maxpar = fit.GetCoefficients();
+            }
+        }
+
+    *fLog << "Done." << endl;
+
+    h0a.GetXaxis()->SetRangeUser(0, maxalpha0*1.5);
+    h0b.GetXaxis()->SetRangeUser(0, maxalpha0*1.5);
+
+    hists->SetTitle(MString::Format("Excess events for \\alpha<%.0f\\circ (N_{max}=%d)", sigint, (int)hists->GetMaximum()));
+    histb->SetTitle(MString::Format("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, 1e-10, 1e-10);
+    c->cd(1);
+    gPad->SetBorderMode(0);
+    hists->Draw("colz");
+    hists->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    hist->Draw("colz");
+    hist->SetBit(kCanDelete);
+
+
+    const Double_t maxr = 0.9*TMath::Abs(fHist.GetBinCenter(1));
+    TF2 f2d("Gaus-2D", FcnGauss2d, -maxr, maxr, -maxr, maxr, 6);
+    f2d.SetLineWidth(1);
+    f2d.SetParName(0, "Max   sigma");
+    f2d.SetParName(1, "Mean_1  deg");
+    f2d.SetParName(2, "Sigma_1 deg");
+    f2d.SetParName(3, "Mean_2  deg");
+    f2d.SetParName(4, "Sigma_2 deg");
+    f2d.SetParName(5, "Phi     deg");
+    f2d.SetParLimits(1, -maxr/2, maxr/2); // mu_1
+    f2d.SetParLimits(3, -maxr/2, maxr/2); // mu_2
+    f2d.SetParLimits(2, 0, maxr);         // sigma_1
+    f2d.SetParLimits(4, 0, maxr);         // sigma_2
+    f2d.SetParLimits(5, 0, 45);           // phi
+    f2d.SetParameter(0, maxs);            // A
+    f2d.SetParameter(1, hist->GetXaxis()->GetBinCenter(maxx)); // mu_1
+    f2d.SetParameter(2, 0.1);             // sigma_1
+    f2d.SetParameter(3, hist->GetYaxis()->GetBinCenter(maxy)); // mu_2
+    f2d.SetParameter(4, 0.1);             // sigma_2
+    f2d.FixParameter(5, 0);               // phi
+    hist->Fit(&f2d, "NI0R");
+    f2d.DrawCopy("cont2same");
+
+
+//    catalog->Draw("mirror same *");
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    histb->Draw("colz");
+    histb->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+    c->cd(4);
+    gPad->Divide(1,3, 0, 0);
+    TVirtualPad *p=gPad;
+    p->SetBorderMode(0);
+    p->cd(1);
+    gPad->SetBorderMode(0);
+    h0b.DrawCopy();
+    h0a.DrawCopy("same");
+    p->cd(2);
+    gPad->SetBorderMode(0);
+    h3.DrawCopy();
+    p->cd(3);
+    gPad->SetBorderMode(0);
+    h2.DrawCopy();
+    c->cd(6);
+    gPad->Divide(1,2, 0, 0);
+    TVirtualPad *q=gPad;
+    q->SetBorderMode(0);
+    q->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetBorderMode(0);
+    h4b.DrawCopy();
+    h4a.DrawCopy("same");
+    h6.DrawCopy("same");
+    q->cd(2);
+    gPad->SetBorderMode(0);
+    //h5b.DrawCopy();
+    //h5a.DrawCopy("same");
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    if (maxx>0 && maxy>0)
+    {
+        const TString title = MString::Format(" \\alpha for x=%.2f y=%.2f (S_{max}=%.1f\\sigma) ",
+                                              hist->GetXaxis()->GetBinCenter(maxx),
+                                              hist->GetYaxis()->GetBinCenter(maxy), maxs);
+
+        h = fHist.ProjectionZ("AlphaFit", maxx, maxx, maxy, maxy);
+        h->Scale(entries/h->GetEntries());
+
+        h->SetDirectory(NULL);
+        h->SetNameTitle("Result \\alpha", title);
+        h->SetBit(kCanDelete);
+        h->SetXTitle("\\alpha [\\circ]");
+        h->SetYTitle("Counts");
+        h->Draw();
+
+        if (fHistOff)
+        {
+            h->SetLineColor(kGreen);
+
+            TH1D *hof=fHistOff->ProjectionZ("AlphaFitOff", maxx, maxx, maxy, maxy);
+            hof->Scale(entries/hof->GetEntries());
+
+            fit.Scale(*(TH1D*)hof, *(TH1D*)h);
+
+            hof->SetLineColor(kRed);
+            hof->SetDirectory(NULL);
+            hof->SetNameTitle("Result \\alpha", title);
+            hof->SetBit(kCanDelete);
+            hof->SetXTitle("\\alpha [\\circ]");
+            hof->SetYTitle("Counts");
+            hof->Draw("same");
+
+            TH1D *diff = (TH1D*)h->Clone("AlphaFitOnOff");
+            diff->Add(hof, -1);
+            diff->SetLineColor(kBlue);
+            diff->SetNameTitle("Result On-Off \\alpha", title);
+            diff->SetBit(kCanDelete);
+            diff->SetXTitle("\\alpha [\\circ]");
+            diff->SetYTitle("Counts");
+            diff->Draw("same");
+
+            h->SetMinimum(diff->GetMinimum()<0 ? diff->GetMinimum()*1.2 : 0);
+
+            TLine l;
+            l.DrawLine(0, 0, 90, 0);
+        }
+
+        TF1 f1("f1", MString::Format("gaus(0) + pol%d(3)", fHistOff ? 0 : polynom).Data(), 0, 90);
+        TF1 f2("f2", MString::Format("gaus(0) + pol%d(3)", fHistOff ? 0 : polynom).Data(), 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, MString::Format("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, MString::Format("A=%.2f", maxpar[0]))->SetTextAlign(11);
+        leg->AddText(0.06, 0.34, MString::Format("\\sigma=%.2f", maxpar[2]))->SetTextAlign(11);
+        leg->AddText(0.06, 0.14, MString::Format("\\mu=%.2f (fix)", maxpar[1]))->SetTextAlign(11);
+        leg->AddText(0.60, 0.54, MString::Format("a=%.2f", maxpar[3]))->SetTextAlign(11);
+        leg->AddText(0.60, 0.34, MString::Format("b=%.2f (fix)", maxpar[4]))->SetTextAlign(11);
+        if (polynom>1)
+            leg->AddText(0.60, 0.14, MString::Format("c=%.2f", !fHistOff?maxpar[5]:0))->SetTextAlign(11);
+        leg->SetBit(kCanDelete);
+        leg->Draw();
+
+        q->cd(2);
+
+        TGraph *g = new TGraph;
+        g->SetPoint(0, 0, 0);
+
+        Int_t max=0;
+        Float_t maxsig=0;
+        for (int i=1; i<89; i++)
+        {
+            const Double_t s = f1.Integral(0, (float)i)/w;
+            const Double_t b = f2.Integral(0, (float)i)/w;
+
+            const Double_t sig = MMath::SignificanceLiMaSigned(s, b);
+
+            g->SetPoint(g->GetN(), i, sig);
+
+            if (sig>maxsig)
+            {
+                max = i;
+                maxsig = sig;
+            }
+        }
+
+        g->SetNameTitle("SigVs\\alpha", "Significance vs \\alpha");
+        g->GetHistogram()->SetXTitle("\\alpha_{0} [\\circ]");
+        g->GetHistogram()->SetYTitle("Significance");
+        g->SetBit(kCanDelete);
+        g->Draw("AP");
+
+        leg = new TPaveText(0.35, 0.10, 0.90, 0.25, "brNDC");
+        leg->SetBorderSize(1);
+        leg->SetTextSize(0.1);
+        leg->AddText(MString::Format("S_{max}=%.1f\\sigma at \\alpha_{max}=%d\\circ", maxsig, max));
+        leg->SetBit(kCanDelete);
+        leg->Draw();
+    }
+}
+
+void MHFalseSource::DrawNicePlot() const
+{
+    Int_t newc = kTRUE;
+    Float_t zoom = 0.95;
+    Int_t col = kBlue+180;
+
+    if (!newc && !fDisplay)
+        return;
+
+    TH1 *h = dynamic_cast<TH1*>(FindObjectInPad("Alpha_yx_on"));
+    if (!h)
+        return;
+
+    // Open and setup canvas/pad
+    TCanvas &c = newc ? *new TCanvas("Excess", "Excess Plot", TMath::Nint(500.), TMath::Nint(500*0.77/0.89)) : fDisplay->AddTab("ThetsSq");
+
+    //c.SetPad(0.15, 0, 0.90, 1);
+
+    c.SetBorderMode(0);
+    c.SetFrameBorderMode(0);
+    c.SetFillColor(kWhite);
+
+    c.SetLeftMargin(0.11);
+    c.SetRightMargin(0.12);
+    c.SetBottomMargin(0.10);
+    c.SetTopMargin(0.01);
+
+    TH1 *h1 = (TH1*)h->Clone("");
+    h1->SetDirectory(0);
+    h1->SetTitle("");
+    h1->SetContour(99);
+    h1->SetBit(TH1::kNoStats);
+    h1->SetBit(TH1::kCanDelete);
+
+    if (h1->FindObject("stats"))
+        delete h1->FindObject("stats");
+
+    TAxis &x = *h1->GetXaxis();
+    TAxis &y = *h1->GetYaxis();
+    TAxis &z = *h1->GetZaxis();
+
+    x.SetRangeUser(-zoom, zoom);
+    y.SetRangeUser(-zoom, zoom);
+
+    x.SetTitleOffset(1.1);
+    y.SetTitleOffset(1.3);
+
+    x.SetTickLength(0.025);
+    y.SetTickLength(0.025);
+
+    x.SetAxisColor(kWhite);
+    y.SetAxisColor(kWhite);
+
+    x.CenterTitle();
+    y.CenterTitle();
+
+    x.SetTitle("Offset [#circ]");
+    y.SetTitle("Offset [#circ]");
+
+    x.SetDecimals();
+    y.SetDecimals();
+    z.SetDecimals();
+
+    MH::SetPalette("glowsym", 99);
+
+    const Float_t max = TMath::Max(h1->GetMinimum(), h1->GetMaximum());
+
+    h1->SetMinimum(-max);
+    h1->SetMaximum(max);
+
+    h1->Draw("colz");
+
+    // ------
+    // Convert pave coordinates from NDC to Pad coordinates.
+
+    gPad->Update();
+
+    Float_t x0 = 0.80;
+    Float_t y0 = 0.88;
+
+    Double_t dx  = gPad->GetX2() - gPad->GetX1();
+    Double_t dy  = gPad->GetY2() - gPad->GetY1();
+
+    // Check if pave initialisation has been done.
+    // This operation cannot take place in the Pave constructor because
+    // the Pad range may not be known at this time.
+    Float_t px = gPad->GetX1() + x0*dx;
+    Float_t py = gPad->GetY1() + y0*dy;
+    // -------
+
+    TEllipse *el = new TEllipse(px, py, 0.12, 0.12, 0, 360, 0);
+    el->SetFillStyle(4100);
+    el->SetFillColor(kBlack);
+    el->SetLineWidth(2);
+    el->SetLineColor(kWhite);
+    el->SetBit(kCanDelete);
+    el->Draw();
+
+    TString str1("el.SetX1(gPad->GetX1()+0.9*(gPad->GetX2()-gPad->GetX1()));");
+    TString str2("el.SetY1(gPad->GetY1()+0.9*(gPad->GetY2()-gPad->GetY1()));");
+
+    str1.ReplaceAll("el.", MString::Format("((TEllipse*)%p)->", el));
+    str2.ReplaceAll("el.", MString::Format("((TEllipse*)%p)->", el));
+
+    str1.ReplaceAll("0.9", MString::Format("%f", x0));
+    str2.ReplaceAll("0.9", MString::Format("%f", y0));
+
+    TLatex tex;
+    tex.SetBit(TText::kTextNDC);
+    tex.SetTextColor(kWhite);
+    tex.SetTextAlign(22);
+    tex.SetTextSize(0.04);
+    tex.SetTextAngle(0);
+    tex.DrawLatex(x0, y0, "psf");
+
+    TPad *pad = new TPad("pad", "Catalog Pad",
+                         c.GetLeftMargin(), c.GetBottomMargin(),
+                         1-c.GetRightMargin(), 1-c.GetTopMargin());
+
+    pad->SetFillStyle(4000);
+    pad->SetFillColor(kBlack);
+    pad->SetBorderMode(0);
+    pad->SetFrameBorderMode(0);
+    pad->SetBit(kCanDelete);
+    pad->Draw();
+
+    pad->Range(x.GetBinLowEdge(x.GetFirst()),
+               y.GetBinLowEdge(y.GetFirst()),
+               x.GetBinLowEdge(x.GetLast()+1),
+               y.GetBinLowEdge(y.GetLast()+1));
+
+    TString str3("pad->Range(x.GetBinLowEdge(x.GetFirst()),"
+                 "y.GetBinLowEdge(y.GetFirst()),"
+                 "x.GetBinLowEdge(x.GetLast()+1),"
+                 "y.GetBinLowEdge(y.GetLast()+1));");
+
+    str3.ReplaceAll("x.", MString::Format("((TAxis*)%p)->", &x));
+    str3.ReplaceAll("y.", MString::Format("((TAxis*)%p)->", &y));
+    // str3.ReplaceAll("pad", Form("((TPad*)(%p))", pad));
+
+    c.AddExec("SetPosX", str1);
+    c.AddExec("SetPosY", str2);
+    c.AddExec("Resize",  str3);
+
+    pad->cd();
+    gROOT->SetSelectedPad(0);
+
+    MAstroCatalog *cat = (MAstroCatalog*)GetCatalog();
+
+    cat->GetAttLineSky().SetLineColor(col);
+    cat->GetAttLineSky().SetLineWidth(2);
+    cat->GetAttLineSky().SetLineStyle(7);
+
+    cat->GetList()->Clear();
+    cat->SetBit(kCanDelete);
+    //    cat->AddObject(MAstro::Hms2Hor(12,17,52)*TMath::Pi()/12, TMath::DegToRad()*MAstro::Dms2Deg(30,7,0),   6, "1ES1215+303");
+    //    cat->AddObject(MAstro::Hms2Hor(12,18,27)*TMath::Pi()/12, TMath::DegToRad()*MAstro::Dms2Deg(29,48,46), 6, "Mrk766");
+
+    cat->Draw("mirror same");
+
+    /*
+     Int_t col = kBlue+180;
+
+     TLatex tex;
+     tex.SetTextColor(col);
+     tex.SetTextAlign(21);
+     tex.SetTextSize(0.04);
+     tex.DrawLatex(-0.79, -0.8, "43.0\\circ");
+     tex.DrawLatex(-0.78,  0.2, "42.0\\circ");
+
+     tex.SetTextAngle(-90);
+     tex.DrawLatex(-0.45, -0.55, "22.00h");
+     tex.DrawLatex( 0.30, -0.55, "22.07h");
+     */
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHFalseSource.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHFalseSource.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHFalseSource.h	(revision 17960)
@@ -0,0 +1,105 @@
+#ifndef MARS_MHFalseSource
+#define MARS_MHFalseSource
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+class TH2D;
+
+class MParList;
+class MTime;
+class MSrcPosCam;
+class MPointingPos;
+class MObservatory;
+
+class MHFalseSource : public MH
+{
+protected:
+    MTime         *fTime;        //! container to take the event time from
+    MPointingPos  *fPointPos;    //! container to take pointing position from
+    MSrcPosCam    *fSrcPos;      //! container for sopurce position in camera
+    MObservatory  *fObservatory; //! conteiner to take observatory location from
+
+    Float_t fMm2Deg;             // conversion factor for display in degrees
+
+private:
+    Float_t fAlphaCut;           // Alpha cut
+    Float_t fBgMean;             // Background mean
+
+    Float_t fMinDist;            // Min dist
+    Float_t fMaxDist;            // Max dist
+
+    Float_t fMinDW;              // Minimum distance in percent of dist
+    Float_t fMaxDW;              // Maximum distance in percent of dist
+
+protected:
+    TH3D    fHist;               // Alpha vs. x and y
+
+    const TH3D *fHistOff;
+
+    Double_t fRa;
+    Double_t fDec;
+
+    TObject *GetCatalog() const;
+    void MakeSymmetric(TH1 *h);
+
+private:
+    Int_t DistancetoPrimitive(Int_t px, Int_t py);
+    void Modified();
+
+    void ProjectAll(TH2D *h);
+    void ProjectOff(const TH3D &src, TH2D *h, TH2D *all);
+    void ProjectOn(const TH3D &src, TH2D *h, TH2D *all);
+    void ProjectOnOff(TH2D *h, TH2D *all);
+
+public:
+    MHFalseSource(const char *name=NULL, const char *title=NULL);
+
+    void FitSignificance(Float_t sigint=10, Float_t sigmax=75, Float_t bgmin=45, Float_t bgmax=85, Byte_t polynom=2); //*MENU*
+    void FitSignificanceStd() { FitSignificance(); } //*MENU*
+
+    void SetMinDist(Float_t dist) { fMinDist = dist; } // Absolute minimum distance
+    void SetMaxDist(Float_t dist) { fMaxDist = dist; } // Absolute maximum distance
+    void SetMinDW(Float_t ratio)  { fMinDW = ratio; }  // Minimum ratio between length/dist
+    void SetMaxDW(Float_t ratio)  { fMaxDW = ratio; }  // Maximum ratio between length/dist
+
+    void SetAlphaCut(Float_t alpha); //*MENU*
+    void SetAlphaPlus5()  { SetAlphaCut(fAlphaCut+5); } //*MENU*
+    void SetAlphaMinus5() { SetAlphaCut(fAlphaCut-5); } //*MENU*
+
+    void SetBgMean(Float_t alpha); //*MENU*
+    void SetBgMeanPlus5()  { SetBgMean(fBgMean+5); } //*MENU*
+    void SetBgMeanMinus5() { SetBgMean(fBgMean-5); } //*MENU*
+
+    virtual void SetOffData(const MHFalseSource &fs) {
+        fHistOff  = &fs.fHist;
+        fMinDist  =  fs.fMinDist;
+        fMaxDist  =  fs.fMaxDist;
+        fMaxDW    =  fs.fMaxDW;
+        fMinDW    =  fs.fMinDW;
+        fAlphaCut =  fs.fAlphaCut;
+        fBgMean   =  fs.fBgMean;
+    }
+
+    void DrawNicePlot() const; //*MENU*
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    // TObject
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+
+    ClassDef(MHFalseSource, 1) //3D-histogram in alpha, x and y
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHPhi.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHPhi.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHPhi.cc	(revision 17960)
@@ -0,0 +1,497 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPhi
+//
+// Plot delta phi the angle between the reconstructed shower origin and
+// the source position.
+//
+// More detail can be found at:
+// http://www.astro.uni-wuerzburg.de/results/ringmethod/
+//
+// Class Version 2:
+//   + TH1D fHPhi;             // Phi plot of the signal w.r.t. source
+//   + TH1D fHPhiOff;          // Phi plot of the signal w.r.t. source+180deg
+//   + TH1D fHTemplate;        // Template how the background should look in the ideal case
+// 
+//   + TH1D fHInhom;           // Phi plot off the signal w.r.t. source (out of the ring with the signal)
+//   + TH1D fHInhomOff;        // Phi plot off the signal w.r.t. source+180deg (out of the ring with the signal)
+// 
+//   + Int_t   fNumBinsSignal; // Number of bins for signal region
+//   + Float_t fThetaCut;      // Theta cut
+//   + Float_t fDistSrc;       // Nominal distance of source from center in wobble
+// 
+//   + Bool_t  fUseAntiPhiCut; // Whether to use a anti-phi cut or not
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHPhi.h"
+
+#include <TCanvas.h>
+#include <TVector2.h>
+#include <TLatex.h>
+#include <TLine.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MSrcPosCam.h"
+#include "MParameters.h"
+#include "MGeomCam.h"
+#include "MBinning.h"
+#include "MMath.h"
+
+ClassImp(MHPhi);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHPhi::MHPhi(const char *name, const char *title)
+    : fHillas(0), fSrcPos(0), fDisp(0),
+    fNumBinsSignal(2), fThetaCut(0.23), fDistSrc(0.4),
+    fUseAntiPhiCut(kTRUE)
+{
+    fName  = name  ? name  : "MHPhi";
+    fTitle = title ? title : "Graphs for rate data";
+
+    // Init Graphs
+    fHPhi.SetNameTitle("Phi", "\\Delta\\Phi-Distribution");
+    fHPhi.SetXTitle("\\Delta\\Phi' [\\circ]");
+    fHPhi.SetYTitle("Counts");
+
+    fHPhi.SetMinimum(0);
+    fHPhi.SetDirectory(0);
+    fHPhi.Sumw2();
+    fHPhi.SetBit(TH1::kNoStats);
+    fHPhi.SetMarkerStyle(kFullDotMedium);
+    fHPhi.SetLineColor(kBlue);
+    fHPhi.SetMarkerColor(kBlue);
+    fHPhi.GetYaxis()->SetTitleOffset(1.3);
+
+    fHPhiOff.SetMinimum(0);
+    fHPhiOff.SetDirectory(0);
+    fHPhiOff.Sumw2();
+    fHPhiOff.SetBit(TH1::kNoStats);
+    fHPhiOff.SetLineColor(kRed);
+    fHPhiOff.SetMarkerColor(kRed);
+
+    fHTemplate.SetMinimum(0);
+    fHTemplate.SetDirectory(0);
+    fHTemplate.SetBit(TH1::kNoStats);
+    fHTemplate.SetLineColor(kGreen);
+
+    fHInhom.SetNameTitle("Inhomogeneity", "\\Delta\\Phi-Distribution");
+    fHInhom.SetXTitle("\\Delta\\Phi' [\\circ]");
+    fHInhom.SetYTitle("Counts");
+    fHInhom.Sumw2();
+    fHInhom.SetMinimum(0);
+    fHInhom.SetDirectory(0);
+    fHInhom.SetBit(TH1::kNoStats);
+    fHInhom.GetYaxis()->SetTitleOffset(1.3);
+
+    fHInhomOff.Sumw2();
+    fHInhomOff.SetMinimum(0);
+    fHInhomOff.SetDirectory(0);
+    fHInhomOff.SetBit(TH1::kNoStats);
+    fHInhomOff.SetLineColor(kRed);
+    fHInhomOff.SetMarkerColor(kRed);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHPhi::SetupFill(const MParList *plist)
+{
+    fHillas = (MHillas*)plist->FindObject("MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << "MHillas not found... abort." << endl;
+        return kFALSE;
+    }
+    fSrcPos = (MSrcPosCam*)plist->FindObject("MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << "MSrcPosCam not found... abort." << endl;
+        return kFALSE;
+    }
+    fDisp = (MParameterD*)plist->FindObject("Disp", "MParameterD");
+    if (!fDisp)
+    {
+        *fLog << err << "Disp [MParameterD] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fConvMm2Deg = geom->GetConvMm2Deg();
+
+    MParameterD *cut = (MParameterD*)plist->FindObject("ThetaSquaredCut", "MParameterD");
+    if (!cut)
+        *fLog << warn << "ThetaSquareCut [MParameterD] not found... using default theta<" << fThetaCut << "." << endl;
+    else
+        fThetaCut = TMath::Sqrt(cut->GetVal());
+
+    const Double_t w  = TMath::ATan(fThetaCut/fDistSrc);
+    const Float_t  sz = TMath::RadToDeg()*w/fNumBinsSignal;
+    const Int_t    n  = TMath::Nint(TMath::Ceil(180/sz));
+
+    MBinning(n+3, 0, (n+3)*sz).Apply(fHPhi);
+    MBinning(n+3, 0, (n+3)*sz).Apply(fHPhiOff);
+    MBinning(n+3, 0, (n+3)*sz).Apply(fHTemplate);
+    MBinning(n+3, 0, (n+3)*sz).Apply(fHInhom);
+    MBinning(n+3, 0, (n+3)*sz).Apply(fHInhomOff);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MMuonCalibPar and
+// MMuonSearchPar container.
+//
+Int_t MHPhi::Fill(const MParContainer *par, const Stat_t weight)
+{
+    // Here we calculate an upper phi cut to take a
+    // possible anti-theta cut into account
+    const Double_t ulim = fUseAntiPhiCut ? 180-fHPhi.GetBinLowEdge(fNumBinsSignal+1)*1.1 : 180;
+
+    // Calculate the shower origin and the source position in units of deg
+    const TVector2 pos = fHillas->GetMean()*fConvMm2Deg + fHillas->GetNormAxis()*fDisp->GetVal();
+    const TVector2 src = fSrcPos->GetXY()*fConvMm2Deg;
+
+    // Calculate radial distance between shower origin and source
+    const Double_t d = pos.Mod() - src.Mod();
+
+    // define an upper and lower cut for the radial distance between both
+    const Double_t dR = fThetaCut;
+    const Double_t dr = fThetaCut*0.913;
+
+    // calculate the phi-angle of the shower origin w.r.t. the source position
+    const Double_t delta = src.DeltaPhi(pos)*TMath::RadToDeg();
+
+    // Define the radii of the upper and lower ring border
+    const Double_t R = src.Mod()+dR;
+    const Double_t r = src.Mod()-dr;
+
+    // Calculate a scale to scale all source positions to the
+    // nominal distance to center
+    const Double_t scale = src.Mod()/fDistSrc;
+
+    // Fill a phi-histograms with all events outside the ring
+    // Take the upper phi cut into account
+    if ((d<-dr || d>dR)/*TMath::Abs(d)>fThetaCut*1.2*/ && TMath::Abs(delta)<ulim)
+    {
+        fHInhom.Fill(TMath::Abs(delta)*scale,  weight);
+        fHInhomOff.Fill((ulim-TMath::Abs(delta))*scale,  weight);
+    }
+
+    // Now forget about all events which are not inside the ring
+    if (d<-dr || d>dR)
+        return kTRUE;
+
+    // Fill the histograms for on and off with the scaled phi
+    // only if we are below the upper phi cut
+    if (TMath::Abs(delta)<ulim)
+    {
+        fHPhi.Fill(         TMath::Abs(delta)*scale,  weight);
+        fHPhiOff.Fill((ulim-TMath::Abs(delta))*scale, weight);
+    }
+
+    // Calculate the maximum scaled phi taking the upper phi cut into account
+    const Double_t max = scale*ulim;
+
+    // Fill a template, this is how the phi-plot would look like
+    // without a signal and for an ideal camera.
+    const Int_t n = fHTemplate.GetNbinsX();
+    TArrayD arr(n);
+    for (int i=1; i<=n; i++)
+    {
+        const Double_t hi = fHTemplate.GetBinLowEdge(i+1);
+        const Double_t lo = fHTemplate.GetBinLowEdge(i);
+
+        // Decide whether the bin is fully contained in the upper phi-cut or
+        // the maximum possible phi is inside the bin
+        if (hi<max)
+            arr[i-1] = 1;
+        else
+            if (lo<max) // if its inside calculate the ratio
+                arr[i-1] = (max-lo)/fHTemplate.GetBinWidth(i+1);
+            else
+                break;
+    }
+
+    // The template is scaled with the current ring width. The upper phi-
+    // cut must not be taken into account because it is just a constant
+    // for all events.
+    const Double_t sum = arr.GetSum();
+    for (int i=1; i<=n; i++)
+        fHTemplate.AddBinContent(i, (R*R-r*r)*arr[i-1]/sum);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This displays the TGraph like you expect it to be (eg. time on the axis)
+// It should also make sure, that the displayed time always is UTC and
+// not local time...
+//
+void MHPhi::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("update");
+
+    pad->Divide(2,2);
+
+    // --------------------------
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+
+    fHPhi.Draw();
+    fHPhiOff.Draw("same");
+
+    TH1D *h1 = new TH1D(fHTemplate);
+    h1->SetName("Template");
+    h1->SetBit(kCanDelete);
+    h1->SetDirectory(0);
+    h1->Draw("same");
+
+    AppendPad("result1");
+
+    // --------------------------
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+
+    fHInhom.Draw();
+    fHInhomOff.Draw("same");
+
+    TH1D *h2 = new TH1D(fHTemplate);
+    h2->SetName("Template");
+    h2->SetBit(kCanDelete);
+    h2->SetDirectory(0);
+    h2->Draw("same");
+
+    // --------------------------
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+
+    fHPhi.Draw();
+    TH1D *h4 = new TH1D(fHInhom);
+    h4->SetName("Inhomogeneity");
+    h4->SetBit(kCanDelete);
+    h4->SetDirectory(0);
+    h4->Draw("same");
+
+    h1->Draw("same");
+
+    // --------------------------
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+
+    TH1D *h3 = new TH1D(fHPhi);
+    h3->SetName("Result");
+    h3->SetBit(kCanDelete);
+    h3->SetDirectory(0);
+    h3->Draw();
+
+    h1->Draw("same");
+
+    AppendPad("result4");
+
+    // --------------------------
+}
+
+void MHPhi::PaintUpdate() const
+{
+    TVirtualPad *pad1 = gPad->GetPad(1);
+    TVirtualPad *pad2 = gPad->GetPad(2);
+    TVirtualPad *pad3 = gPad->GetPad(3);
+    TVirtualPad *pad4 = gPad->GetPad(4);
+
+    const Double_t i2 = fHInhom.Integral();
+/*
+    Double_t sig2 = 0;
+    Double_t bg2  = 0;
+    Double_t f2   = 1;
+*/
+    TH1D *htemp = pad1 ? dynamic_cast<TH1D*>(pad1->FindObject("Template")) : NULL;
+    if (htemp)
+    {
+        fHTemplate.Copy(*htemp);
+        htemp->SetName("Template");
+        htemp->SetDirectory(0);
+
+        Double_t sc1 = 1;
+        Double_t sc2 = 1;
+
+        TH1D *res = pad4 ? dynamic_cast<TH1D*>(pad4->FindObject("Result")) : NULL;
+        if (res)
+        {
+            fHPhi.Copy(*res);
+
+            const Double_t i0 = res->Integral(fNumBinsSignal+1, 9999);
+            const Double_t i1 = fHInhom.Integral(fNumBinsSignal+1, 9999);
+            const Double_t i3 = htemp->Integral();
+            const Double_t i4 = htemp->Integral(fNumBinsSignal+1, 9999);
+
+            // Scale inhomogeneity to match the phi-plot in the off-region
+            sc1 = i1==0 ? 0 : i0/i1;
+            // Scale inhomogeneity to match the phi-plot in the off-region
+            sc2 = i3==0 ? 0 : i2/i3;
+
+            res->Add(&fHInhom, -sc1);
+            res->Add(htemp,     sc1*sc2);
+            res->SetName("Result");
+            res->SetDirectory(0);
+
+            htemp->Scale(i4==0 ? 0 : i0/i4);
+
+            //sig2 = res->Integral(1, fNumBinsSignal);
+            //bg2  = fHPhi.Integral(fNumBinsSignal+1, 9999);
+            //f2   = htemp->Integral(1, fNumBinsSignal)/i4;
+        }
+
+        TH1D *hinhom = pad3 ? dynamic_cast<TH1D*>(pad3->FindObject("Inhomogeneity")) : NULL;
+        if (hinhom)
+        {
+            fHInhom.Copy(*hinhom);
+            hinhom->SetName("Inhomogeneity");
+            hinhom->SetDirectory(0);
+            hinhom->Scale(sc1);
+        }
+    }
+
+    htemp = pad2 ? dynamic_cast<TH1D*>(pad2->FindObject("Template")) : NULL;
+    if (htemp)
+    {
+        const Double_t integ = htemp->Integral();
+
+        fHTemplate.Copy(*htemp);
+        htemp->Scale(integ==0 ? 0 : i2/integ);
+        htemp->SetName("Template");
+        htemp->SetDirectory(0);
+    }
+}
+
+void MHPhi::PaintText(const TH1D &res) const
+{
+    const Double_t cut  = res.GetBinLowEdge(fNumBinsSignal+1);
+
+    const Double_t sig  = res.Integral(1, fNumBinsSignal);
+    const Double_t bg   = res.Integral(fNumBinsSignal+1, 9999);
+
+    const Double_t f    = fHTemplate.Integral(1, fNumBinsSignal)/fHTemplate.Integral(fNumBinsSignal+1, 9999);
+
+    const Double_t S0   = MMath::SignificanceLiMaSigned(sig,  bg*f);
+    const Double_t S    = MMath::SignificanceLiMaSigned(sig,  bg, f);
+
+    const TString fmt = Form("\\sigma_{L/M}=%.1f (\\sigma_{0}=%.1f)  \\Delta\\Phi_{on}<%.1f\\circ  E=%.0f  B=%.0f  f=%.2f",
+                             S, S0, cut, sig-bg*f, bg*f, f);
+
+    const Double_t b = bg             *f/fNumBinsSignal;
+    const Double_t e = TMath::Sqrt(bg)*f/fNumBinsSignal;
+
+    TLatex text(0.275, 0.95, fmt);
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.042);
+    text.Paint();
+
+    TLine line;
+    line.SetLineColor(14);
+    line.PaintLine(cut, gPad->GetUymin(), cut, gPad->GetUymax());
+
+    // Here we calculate an upper phi cut to take a
+    // possible anti-theta cut into account
+    const Double_t ulim = fUseAntiPhiCut ? 180-fHPhi.GetBinLowEdge(fNumBinsSignal+1)*1.1 : 180;
+    line.SetLineStyle(kDotted);
+    line.PaintLine(ulim, gPad->GetUymin(), ulim, gPad->GetUymax());
+
+    line.SetLineStyle(kSolid);
+    line.SetLineColor(kBlack);
+    line.PaintLine(0, b, cut, b);
+    line.PaintLine(cut/2, b-e, cut/2, b+e);
+    line.SetLineStyle(kDashed);
+    line.PaintLine(cut, b, fHPhi.GetXaxis()->GetXmax(), b);
+
+    TMarker m;
+    m.SetMarkerStyle(kFullDotMedium);
+    m.PaintMarker(cut/2, b);
+}
+
+void MHPhi::Paint(Option_t *o)
+{
+    TString opt(o);
+    if (opt=="update")
+        PaintUpdate();
+    if (opt=="result1")
+        PaintText(fHPhi);
+    if (opt=="result4")
+    {
+        TH1D *res = gPad ? dynamic_cast<TH1D*>(gPad->FindObject("Result")) : NULL;
+        if (res)
+            PaintText(*res);
+    }
+}
+
+Int_t MHPhi::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumBinsSignal", print))
+    {
+        SetNumBinsSignal(GetEnvValue(env, prefix, "NumBinsSignal", (Int_t)fNumBinsSignal));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "UseAntiPhiCut", print))
+    {
+        SetUseAntiPhiCut(GetEnvValue(env, prefix, "UseAntiPhiCut", (Int_t)fUseAntiPhiCut));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHPhi.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHPhi.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHPhi.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MHPhi
+#define MARS_MHPhi
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MHillas;
+class MSrcPosCam;
+class MParameterD;
+
+class MHPhi : public MH
+{
+private:
+    TH1D fHPhi;             // Phi plot of the signal w.r.t. source
+    TH1D fHPhiOff;          // Phi plot of the signal w.r.t. source+180deg
+    TH1D fHTemplate;        // Template how the background should look in the ideal case
+
+    TH1D fHInhom;           // Phi plot off the signal w.r.t. source (out of the ring with the signal)
+    TH1D fHInhomOff;        // Phi plot off the signal w.r.t. source+180deg (out of the ring with the signal)
+
+    MHillas     *fHillas;   //! Pointer to input container "MHillas"
+    MSrcPosCam  *fSrcPos;   //! Pointer to input container "MSrcPosCam"
+    MParameterD *fDisp;     //! Pointer to input container "Disp"
+
+    Double_t fConvMm2Deg;   //! Conversion factor from camera geometry
+
+    Int_t   fNumBinsSignal; // Number of bins for signal region
+    Float_t fThetaCut;      // Theta cut
+    Float_t fDistSrc;       // Nominal distance of source from center in wobble
+
+    Bool_t  fUseAntiPhiCut; // Whether to use a anti-phi cut or not
+
+    // Paint
+    void PaintUpdate() const;
+    void PaintText(const TH1D &res) const;
+
+    // MH
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+public:
+    MHPhi(const char *name=NULL, const char *title=NULL);
+
+    // Setter
+    void SetNumBinsSignal(UInt_t n)       { fNumBinsSignal=TMath::Max(n, 1U); }
+    void SetUseAntiPhiCut(Bool_t b=kTRUE) { fUseAntiPhiCut=b; }
+
+    // TObject
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *opt="");
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    ClassDef(MHPhi, 2) // Histogram for ring-method
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mhflux/MHThetaSq.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHThetaSq.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHThetaSq.cc	(revision 17960)
@@ -0,0 +1,220 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHThetaSq
+//
+// This is a MHAlpha using "ThetaSquared [MParameterD]" as 'alpha'
+//
+// The default binning is determined from the integration range set in
+// MAlphaFitter.
+//
+// For more detailes see MHAlpha.
+//
+// Version 2:
+// ---------
+//  + UInt_t fNumBinsSignal;
+//  + UInt_t fNumBinsTotal;
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHThetaSq.h"
+
+#include "MParameters.h"
+#include "MHMatrix.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MParameters.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHThetaSq);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHThetaSq::MHThetaSq(const char *name, const char *title)
+    : MHAlpha(name, title), fNumBinsSignal(3), fNumBinsTotal(75)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHThetaSq";
+    fTitle = title ? title : "Theta Squared plot";
+
+    fNameParameter = "ThetaSquared";
+
+    fHist.SetName("Theta");
+    fHist.SetTitle("Theta");
+    fHist.SetZTitle("\\vartheta^{2} [deg^{2}]");
+    fHist.SetDirectory(NULL);
+
+    // Main histogram
+    fHistTime.SetName("Theta");
+    fHistTime.SetXTitle("\\vartheta^{2} [deg^{2}]");
+    fHistTime.SetDirectory(NULL);
+
+    //fHistTime.SetYTitle("\\theta^{2] [deg^{2}]");
+    /*
+    TArrayD arr(50);
+    for (int i=1; i<50; i++)
+        arr[i] = sqrt((arr[i-1]+1)*(arr[i-1]+1) + 1.1)-1;
+    */
+    MBinning binsa, binse, binst;
+    binsa.SetEdges(75, 0, 1.5);
+    //binsa.SetEdges(arr);
+    binse.SetEdgesLog(15, 10, 100000);
+    binst.SetEdgesASin(67, -0.005, 0.665);
+    binsa.Apply(fHistTime);
+
+    MH::SetBinning(fHist, binst, binse, binsa);
+}
+
+// --------------------------------------------------------------------------
+//
+// Overwrites the binning in Alpha (ThetaSq) with a binning for which
+// the upper edge of the 5th bin (bin=5) fit the signal integration window.
+// In total 75 bins are setup.
+//
+// In case of fOffData!=NULL the binnings are taken later from fOffData anyhow.
+//
+Bool_t MHThetaSq::SetupFill(const MParList *pl)
+{
+    // Default is from default fitter
+    // if a user defined fitter is in the parlist: use this range
+    MAlphaFitter *fit = (MAlphaFitter*)pl->FindObject("MAlphaFitter");
+    if (!fit)
+        fit = &fFit;
+
+    MParameterD *cut = (MParameterD*)pl->FindObject("ThetaSquaredCut", "MParameterD");
+    if (cut)
+        fit->SetSignalIntegralMax(cut->GetVal());
+
+    // Get Histogram binnings
+    MBinning binst, binse;
+    binst.SetEdges(fHist, 'x');
+    binse.SetEdges(fHist, 'y');
+
+    // Calculate bining which fits alpha-cut
+    const Double_t intmax = fit->GetSignalIntegralMax();
+    const UInt_t   nbins  = fNumBinsTotal;
+    const UInt_t   nsig   = fNumBinsSignal;
+
+    MBinning binsa(nbins, 0, nbins*intmax/nsig);
+
+    // Apply binning
+    binsa.Apply(fHistTime);
+    MH::SetBinning(fHist, binst, binse, binsa);
+
+    // Remark: Binnings might be overwritten in MHAlpha::SetupFill
+    return MHAlpha::SetupFill(pl);
+}
+
+// --------------------------------------------------------------------------
+//
+// Store the pointer to the parameter container storing the plotted value
+// (here ThetaSq) in fParameter.
+//
+// return whether it was found or not.
+//
+Bool_t MHThetaSq::GetParameter(const MParList &pl)
+{
+    fParameter = (MParContainer*)pl.FindObject(fNameParameter, "MParameterD");
+    if (fParameter)
+        return kTRUE;
+
+    *fLog << err << fNameParameter << " [MParameterD] not found... abort." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the value from fParemeter which should be filled into the plots
+//
+Double_t MHThetaSq::GetVal() const
+{
+    return static_cast<const MParameterD*>(fParameter)->GetVal();
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of
+// MMcEvt. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MHHadronness::Fill
+// will take the values from the matrix instead of the containers.
+//
+// It takes fSkipHist* into account!
+//
+void MHThetaSq::InitMapping(MHMatrix *mat, Int_t type)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = -1;
+    fMap[1] = -1;
+    fMap[2] = -1;
+    fMap[3] = -1;
+    fMap[4] = -1;
+
+    if (!fSkipHistEnergy)
+    {
+        fMap[1] = type==0 ? fMatrix->AddColumn("MEnergyEst.fVal") : -1;
+        fMap[2] = type==0 ? -1 : fMatrix->AddColumn("MHillas.fSize");
+    }
+
+    if (!fSkipHistTheta)
+        fMap[3] = fMatrix->AddColumn("MPointingPos.fZd");
+
+   // if (!fSkipHistTime)
+   //     fMap[4] = fMatrix->AddColumn("MTime.GetAxisTime");
+}
+
+Int_t MHThetaSq::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Int_t rc = MHAlpha::ReadEnv(env, prefix, print);
+    if (rc==kERROR)
+        return kERROR;
+
+    if (IsEnvDefined(env, prefix, "NumBinsSignal", print))
+    {
+        SetNumBinsSignal(GetEnvValue(env, prefix, "NumBinsSignal", (Int_t)fNumBinsSignal));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "NumBinsTotal", print))
+    {
+        SetNumBinsTotal(GetEnvValue(env, prefix, "NumBinsTotal", (Int_t)fNumBinsTotal));
+        rc = kTRUE;
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHThetaSq.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHThetaSq.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHThetaSq.h	(revision 17960)
@@ -0,0 +1,39 @@
+#ifndef MARS_MHThetaSq
+#define MARS_MHThetaSq
+
+#ifndef MARS_MHAlpha
+#include "MHAlpha.h"
+#endif
+
+class MTaskList;
+
+class MHThetaSq : public MHAlpha
+{
+private:
+    UInt_t fNumBinsSignal;
+    UInt_t fNumBinsTotal;
+
+    Bool_t      GetParameter(const MParList &pl);
+    Double_t    GetVal() const;
+    const char *GetParameterRule() const
+    {
+        return "ThetaSquared.fVal";
+    }
+
+    Bool_t SetupFill(const MParList *pl);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+public:
+    MHThetaSq(const char *name=NULL, const char *title=NULL);
+
+    void InitMapping(MHMatrix *mat, Int_t type=0);
+
+    void SetNumBinsSignal(UInt_t n) { fNumBinsSignal=TMath::Max(n, 1U); }
+    void SetNumBinsTotal(UInt_t n)  { fNumBinsTotal =TMath::Max(n, 1U); }
+
+    ClassDef(MHThetaSq, 2) // Theta-Plot which is fitted online
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHThetaSqN.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHThetaSqN.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHThetaSqN.cc	(revision 17960)
@@ -0,0 +1,403 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHThetaSqN
+//
+// For more detailes see MHAlpha.
+//
+// How to use this class:
+//  - in your ganymed.rc add:
+//      MJCut.NameHist: MHThetaSqN
+//  - setup the number of off-source regions in your ganymed.rc by:
+//      MHThetaSqN.NumOffSourcePos: 2
+//  - switch on/off whether an off-theta cut should be done:
+//      MHThetaSqN.DoOffCut: Yes,No
+//  - and if necessary switch off the Theta cut in your Magic cuts:
+//      Cut1.ThetaCut: None
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHThetaSqN.h"
+
+#include <TVector2.h>
+
+#include "MParameters.h"
+#include "MSrcPosCam.h"
+#include "MGeomCam.h"
+#include "MHMatrix.h"
+#include "MHillas.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MParameters.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHThetaSqN);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHThetaSqN::MHThetaSqN(const char *name, const char *title)
+    : MHAlpha(name, title), fDisp(0), fSrcPosCam(0), fSignificanceCutLevel(1.7),
+    fNumBinsSignal(3), fNumBinsTotal(75), fNumOffSourcePos(3), fDoOffCut(kTRUE),
+    fCounter(4)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHThetaSqN";
+    fTitle = title ? title : "Theta Squared plot";
+
+    fNameParameter = "ThetaSquared";
+
+    fHist.SetName("Theta");
+    fHist.SetTitle("Theta");
+    fHist.SetZTitle("\\vartheta^{2} [deg^{2}]");
+    fHist.SetDirectory(NULL);
+
+    // Main histogram
+    fHistTime.SetName("Theta");
+    fHistTime.SetXTitle("\\vartheta^{2} [deg^{2}]");
+    fHistTime.SetDirectory(NULL);
+
+    MBinning binsa, binse, binst;
+    binsa.SetEdges(75, 0, 1.5);
+    //binsa.SetEdges(arr);
+    binse.SetEdgesLog(15, 10, 100000);
+    binst.SetEdgesASin(67, -0.005, 0.665);
+    binsa.Apply(fHistTime);
+
+    MH::SetBinning(fHist, binst, binse, binsa);
+
+    fParameter = new MParameterD;
+}
+
+MHThetaSqN::~MHThetaSqN()
+{
+    delete fParameter;
+}
+
+// --------------------------------------------------------------------------
+//
+// Overwrites the binning in Alpha (ThetaSq) with a binning for which
+// the upper edge of the 5th bin (bin=5) fit the signal integration window.
+// In total 75 bins are setup.
+//
+// In case of fOffData!=NULL the binnings are taken later from fOffData anyhow.
+//
+Bool_t MHThetaSqN::SetupFill(const MParList *pl)
+{
+    // Default is from default fitter
+    // if a user defined fitter is in the parlist: use this range
+    MAlphaFitter *fit = (MAlphaFitter*)pl->FindObject("MAlphaFitter");
+    if (!fit)
+        fit = &fFit;
+
+    MParameterD *cut = (MParameterD*)pl->FindObject("ThetaSquaredCut", "MParameterD");
+    if (cut)
+        fit->SetSignalIntegralMax(cut->GetVal());
+
+    // Get Histogram binnings
+    MBinning binst, binse;
+    binst.SetEdges(fHist, 'x');
+    binse.SetEdges(fHist, 'y');
+
+    // Calculate bining which fits alpha-cut
+    const Double_t intmax = fit->GetSignalIntegralMax();
+    const UInt_t   nbins  = fNumBinsTotal;
+    const UInt_t   nsig   = fNumBinsSignal;
+
+    MBinning binsa(nbins, 0, nbins*intmax/nsig);
+
+    // Apply binning
+    binsa.Apply(fHistTime);
+    MH::SetBinning(fHist, binst, binse, binsa);
+
+    // Remark: Binnings might be overwritten in MHAlpha::SetupFill
+    if (!MHAlpha::SetupFill(pl))
+        return kFALSE;
+
+    fDisp = (MParameterD*)pl->FindObject("Disp", "MParameterD");
+    if (!fDisp)
+    {
+        *fLog << err << "Disp [MParameterD] not found... abort." << endl;
+        return kFALSE;
+    }
+    fHillas = (MHillas*)pl->FindObject("MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << "MHillas not found... abort." << endl;
+        return kFALSE;
+    }
+    fSrcPosCam = (MSrcPosCam*)pl->FindObject("MSrcPosCam");
+    if (!fSrcPosCam)
+    {
+        *fLog << err << "MSrcPosCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fGeom = (MGeomCam*)pl->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    if (fFit.GetScaleMode()==MAlphaFitter::kNone)
+        fFit.SetScaleUser(1./fNumOffSourcePos);
+
+    fThetaSqCut = fSignificanceCutLevel*fFit.GetSignalIntegralMax()/1.7;
+
+    fCounter.Reset();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the value from fParemeter which should be filled into the plots
+//
+Double_t MHThetaSqN::GetVal() const
+{
+    return static_cast<const MParameterD*>(fParameter)->GetVal();
+}
+
+// --------------------------------------------------------------------------
+//
+// Abbreviation to set the value used by MHAlpha to fill the histogram
+//
+void MHThetaSqN::SetVal(Double_t val)
+{
+    static_cast<MParameterD*>(fParameter)->SetVal(val);
+}
+
+// --------------------------------------------------------------------------
+//
+// Abbreviation to set the value used by MHAlpha to fill the histogram
+//
+TVector2 MHThetaSqN::GetVec(const TVector2 &v, Int_t n1) const
+{
+    if (!fMatrix)
+        return v;
+
+    return TVector2( (*fMatrix)[fMap[n1]], (*fMatrix)[fMap[n1+1]] );
+}
+
+Int_t MHThetaSqN::Fill(const MParContainer *par, const Stat_t weight)
+{
+    const Double_t fMm2Deg = fGeom->GetConvMm2Deg();
+
+    const TVector2 norm(GetVec(fHillas->GetNormAxis(), 6));
+    const TVector2 mean(GetVec(fHillas->GetMean(),     8));
+
+    const TVector2 org = mean*fMm2Deg + norm*fDisp->GetVal();
+
+    // In the case we are filling off-data src0 contains the anti-source position
+    TVector2 src0(GetVec(fSrcPosCam->GetXY(), 10)*fMm2Deg);
+    if (!fOffData)
+        src0 *= -1;
+
+    const UInt_t  n   = fNumOffSourcePos+1;
+    const Float_t rad = TMath::TwoPi()/n;
+
+    // Calculate distance (theta-sq) to all (off-)source regions
+    TArrayD dist(n);
+    for (UInt_t i=0; i<n; i++)
+    {
+        const TVector2 src = const_cast<TVector2&>(src0).Rotate(i*rad);
+        dist[i] = (src-org).Mod2();
+    }
+
+    // Processing off-data
+    // Check if event's origin is in the on-regions
+    if (!fOffData && fDoOffCut && dist[0]<fThetaSqCut)
+        return kTRUE;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        //   off: is in src region   on: is in off regions
+        /// if (!fOffData && i==0) || (fOffData && i!=0)
+        if ((bool)fOffData ^ (i==0) )
+            continue;
+
+        Stat_t w = weight;
+
+        // Processing on-data
+        if (fOffData && fDoOffCut)
+        {
+            /*
+             static int cnt=0;
+             if (dist[1+(cnt++%fNumOffSourcePos)]<fFit.GetSignalIntegralMax())
+                continue;
+             */
+
+            // Check if event's origin is in one of the off-regions
+            for (UInt_t j=1; j<n; j++)
+                if (dist[j]<fThetaSqCut)
+                {
+                    w *= (float)(fNumOffSourcePos-1)/fNumOffSourcePos;
+                    break;
+                }
+        }
+
+        SetVal(dist[i]);
+
+        const Int_t rc = MHAlpha::Fill(NULL, w);
+        if (rc!=kTRUE)
+            return rc;
+    }
+
+    if (!fOffData)
+    {
+        // off    0.4deg    0.3deg
+        //  5: 0.200  ~86%   0.150
+        //  4: 0.235  ~92%   0.176
+        //  3: 0.283  ~96%   0.212
+        //  2: 0.346  ~98%   0.260
+
+        const Double_t dis = src0.Mod()*TMath::Sin(rad/2);
+        const Double_t cut = TMath::Sqrt(fFit.GetSignalIntegralMax());
+        if (dis<cut)
+        {
+            *fLog << warn << "WARNING - Source regions overlap: distance ";
+            *fLog << dis << " less than theta-sq cut " << cut << "!" << endl;
+            if (dis*1.7<cut*1.0)
+                fCounter[3]++;
+            else
+                if (dis*1.7<cut*1.5)
+                    fCounter[2]++;
+                else
+                    fCounter[1]++;
+
+        }
+        else
+            fCounter[0]++;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print execution statistics
+//
+Bool_t MHThetaSqN::Finalize()
+{
+    if (GetNumExecutions()>0)
+    {
+        *fLog << inf << endl;
+        *fLog << GetDescriptor() << " execution statistics:" << endl;
+        PrintSkipped(fCounter[3], "Region distance below 1.0sigma (68.3%)");
+        PrintSkipped(fCounter[2], "Region distance below 1.5sigma (86.6%)");
+        PrintSkipped(fCounter[1], "Region distance below 1.7sigma (91.1%)");
+        *fLog << " " << (int)fCounter[0] << " (" << Form("%5.1f", 100.*fCounter[0]/GetNumExecutions()) << "%) Evts ok!" << endl;
+        //*fLog << " " << (int)fCounter[0] << " (" << Form("%5.1f", 100.*fCounter[0]/GetNumExecutions()) << "%) Evts survived calculation!" << endl;
+        *fLog << endl;
+    }
+
+    return MHAlpha::Finalize();
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of
+// MMcEvt. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MHHadronness::Fill
+// will take the values from the matrix instead of the containers.
+//
+// It takes fSkipHist* into account!
+//
+void MHThetaSqN::InitMapping(MHMatrix *mat, Int_t type)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = -1;
+    fMap[1] = -1;
+    fMap[2] = -1;
+    fMap[3] = -1;
+    fMap[4] = -1;
+
+    if (!fSkipHistEnergy)
+    {
+        fMap[1] = type==0 ? fMatrix->AddColumn("MEnergyEst.fVal") : -1;
+        fMap[2] = type==0 ? -1 : fMatrix->AddColumn("MHillas.fSize");
+    }
+
+    if (!fSkipHistTheta)
+        fMap[3] = fMatrix->AddColumn("MPointingPos.fZd");
+
+    fMap[5]  = -1;
+    fMap[6]  = fMatrix->AddColumn("MHillas.fCosDelta");
+    fMap[7]  = fMatrix->AddColumn("MHillas.fSinDelta");
+    fMap[8]  = fMatrix->AddColumn("MHillas.fMeanX");
+    fMap[9]  = fMatrix->AddColumn("MHillas.fMeanY");
+    fMap[10] = fMatrix->AddColumn("MSrcPosCam.fX");
+    fMap[11] = fMatrix->AddColumn("MSrcPosCam.fY");
+}
+
+Int_t MHThetaSqN::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Int_t rc = MHAlpha::ReadEnv(env, prefix, print);
+    if (rc==kERROR)
+        return kERROR;
+
+    if (IsEnvDefined(env, prefix, "NumBinsSignal", print))
+    {
+        SetNumBinsSignal(GetEnvValue(env, prefix, "NumBinsSignal", (Int_t)fNumBinsSignal));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "NumBinsTotal", print))
+    {
+        SetNumBinsTotal(GetEnvValue(env, prefix, "NumBinsTotal", (Int_t)fNumBinsTotal));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "NumOffSourcePos", print))
+    {
+        SetNumOffSourcePos(GetEnvValue(env, prefix, "NumOffSourcePos", (Int_t)fNumOffSourcePos));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "DoOffCut", print))
+    {
+        SetDoOffCut(GetEnvValue(env, prefix, "DoOffCut", fDoOffCut));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "SignificanceCutLevel", print))
+    {
+        SetSignificanceCutLevel(GetEnvValue(env, prefix, "SignificanceCutLevel", fSignificanceCutLevel));
+        rc = kTRUE;
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHThetaSqN.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHThetaSqN.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHThetaSqN.h	(revision 17960)
@@ -0,0 +1,74 @@
+#ifndef MARS_MHThetaSqN
+#define MARS_MHThetaSqN
+
+#ifndef MARS_MHAlpha
+#include "MHAlpha.h"
+#endif
+
+class TVector2;
+
+class MGeomCam;
+class MTaskList;
+class MSrcPosCam;
+
+class MHThetaSqN : public MHAlpha
+{
+private:
+    MGeomCam    *fGeom;      //! conversion mm to deg
+    MParameterD *fDisp;      //!
+    MSrcPosCam  *fSrcPosCam; //!
+
+    Double_t fThetaSqCut;    //!
+    Double_t fSignificanceCutLevel;
+
+    UInt_t fNumBinsSignal;
+    UInt_t fNumBinsTotal;
+    UInt_t fNumOffSourcePos;
+
+    Bool_t fDoOffCut;
+
+    TArrayI fCounter;        //!
+
+    // MHThetaSqN
+    TVector2 GetVec(const TVector2 &v, Int_t n1) const;
+    void     SetVal(Double_t val);
+
+    // MHAlpha
+    Bool_t   GetParameter(const MParList &pl) { return kTRUE; }
+    Double_t GetVal() const;
+    void SetOffData(const MHAlpha &h)
+    {
+        const MHThetaSqN &t = (MHThetaSqN&)h;
+
+        fDoOffCut        = t.fDoOffCut;
+        fNumOffSourcePos = t.fNumOffSourcePos;
+
+        MHAlpha::SetOffData(h);
+    }
+
+    // MH
+    Bool_t SetupFill(const MParList *pl);
+    Int_t  Fill(const MParContainer *par, const Stat_t weight);
+    Bool_t Finalize();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+public:
+    MHThetaSqN(const char *name=NULL, const char *title=NULL);
+    ~MHThetaSqN();
+
+    void InitMapping(MHMatrix *mat, Int_t type=0);
+
+    void SetNumBinsSignal(UInt_t n)      { fNumBinsSignal  =TMath::Max(n, 1U); }
+    void SetNumBinsTotal(UInt_t n)       { fNumBinsTotal   =TMath::Max(n, 1U); }
+    void SetNumOffSourcePos(UInt_t n=3)  { fNumOffSourcePos=TMath::Max(n, 1U); }
+
+    void SetSignificanceCutLevel(Double_t l=1.7) { fSignificanceCutLevel=l; }
+
+    void SetDoOffCut(Bool_t b=kTRUE)     { fDoOffCut = b; }
+
+    ClassDef(MHThetaSqN, 1) // Theta-Plot which is fitted online
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MHThreshold.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHThreshold.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHThreshold.cc	(revision 17960)
@@ -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  12/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHThreshold
+//
+// Class to calculate the threshold of your analysis.
+//
+// It fills a histogram dN/dE vs E with a fine binning. The threshold is
+// determined as the logarithmic center of the bin with the maximum
+// content.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHThreshold.h" 
+
+#include <TMath.h>
+
+#include <TF1.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TPaveStats.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+#include "MBinning.h"
+
+#include "MMcEvt.hxx"
+
+#include "MParList.h"
+
+ClassImp(MHThreshold);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHThreshold::MHThreshold(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  : "MHThreshold";
+    fTitle = title ? title : "Histogram to determin the threshold";
+
+    fHEnergy.SetName("Threshold");
+    fHEnergy.SetTitle("Energy Threshold");
+    fHEnergy.SetXTitle("E [GeV]");
+    fHEnergy.SetYTitle("dN/dE [GeV^{-1}]");
+    fHEnergy.SetDirectory(NULL);
+    fHEnergy.UseCurrentStyle();
+
+    MBinning binse(50, 20, 50000, "", "log");
+    binse.Apply(fHEnergy);
+
+    fHEnergy.Sumw2();
+}
+
+Bool_t MHThreshold::SetupFill(const MParList *pl)
+{
+    fMcEvt = (MMcEvt*)pl->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... abort." << endl;
+        return kFALSE;
+    }
+
+    ApplyBinning(*pl, "Threshold", fHEnergy);
+
+    return kTRUE;
+}
+
+void MHThreshold::Paint(Option_t *option)
+{
+    if (fHEnergy.GetEntries()==0)
+        return;
+
+    TH1D h(fHEnergy);
+    h.SetDirectory(0);
+
+#if ROOT_VERSION_CODE<ROOT_VERSION(5,20,00)
+    Int_t min=1;
+    while (min<h.GetNbinsX() && h.GetBinContent(min)==0)
+        min++;
+    Int_t max=h.GetNbinsX();
+    while (max>min && h.GetBinContent(max)==0)
+        max--;
+
+    if (max-min<5)
+        return;
+
+    h.Smooth(1, min, max);
+#else
+    h.Smooth(1);
+#endif
+
+    const Int_t bin  =  h.GetMaximumBin();
+    const TAxis &axe = *h.GetXaxis();
+
+    // Assume that the energy binning is logarithmic
+    const Axis_t maxe = TMath::Sqrt(axe.GetBinLowEdge(bin)*axe.GetBinUpEdge(bin));
+
+    TLatex text(0.30, 0.95, MString::Format("E_{max}=%dGeV (%dGeV,%dGeV)", TMath::Nint(maxe),
+                                            TMath::Nint(axe.GetBinLowEdge(bin)),
+                                            TMath::Nint(axe.GetBinUpEdge(bin))));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+void MHThreshold::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+    // Do the projection before painting the histograms into
+    // the individual pads
+    pad->SetBorderMode(0);
+
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    fHEnergy.Draw();
+
+    AppendPad();
+}
+
+Int_t MHThreshold::Fill(const MParContainer *par, const Stat_t weight)
+{
+    const Double_t energy = fMcEvt->GetEnergy();
+
+    fHEnergy.Fill(energy, weight/energy);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MHThreshold.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MHThreshold.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MHThreshold.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MHThreshold
+#define MARS_MHThreshold
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MMcEvt;
+
+class MHThreshold : public MH
+{
+private:
+    const MMcEvt *fMcEvt; //! Pointer to MC energy
+
+    TH1D fHEnergy;
+
+public:
+    MHThreshold(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t weight=1);
+
+    void Draw(Option_t *option="");
+    void Paint(Option_t *option="");
+
+    ClassDef(MHThreshold, 1)  // Data Container to calculate threshold
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhflux/MMcSpectrumWeight.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MMcSpectrumWeight.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MMcSpectrumWeight.cc	(revision 17960)
@@ -0,0 +1,697 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Marcos Lopez 10/2003 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMcSpectrumWeight
+//               
+//  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. If the new spectrum will be a power law, just introduce the slope
+//       of this power law.
+//    2. If the new spectrum will have a general shape:
+//       The new spectrum is passed as a char* (SetFormula())
+//
+//  Method:
+//  -------
+//
+//   - Corsika spectrum: dN/dE = A * E^(a)
+//     with a = fOldSlope, 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))
+//
+//
+//  If using SetFormula you can specify formulas accepted by TF1, eg:
+//      pow(X, -2.6)
+//  (Rem: all capital (!) 'X' are replaced by the corresponding %s.fEnergy
+//        automatically)
+//
+//  For more details of the setup see MMcSpectrumWeight::ReadEnv
+//
+//
+//  Input Containers:
+//    MMcEvt
+//    MMcCorsikaRunHeader
+//    [MPointingPos]
+//    [MHillas]
+//
+//  Output Container:
+//    MWeight [MParameterD]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMcSpectrumWeight.h"
+
+#include <TF1.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TSpline.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+#include "MParList.h"
+#include "MParameters.h"
+
+#include "MHillas.h"
+#include "MPointingPos.h"
+
+#include "MMcEvt.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+ClassImp(MMcSpectrumWeight);
+
+using namespace std;
+
+void MMcSpectrumWeight::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcSpectrumWeight";
+    fTitle = title ? title : "Task to calculate weights to change the energy spectrum"; 
+
+    AddToBranchList("MMcEvt.fEnergy");
+
+    fNameWeight  = "MWeight";
+    fNameMcEvt   = "MMcEvt";
+
+    fNewSlope    = -99;
+    fOldSlope    = -99;
+
+    fEnergyMin   = -1;
+    fEnergyMax   = -2;
+
+    fNorm        =  1;
+    fNormEnergy  = -1;
+
+    fAllowChange = kFALSE;
+
+    fFunc        = NULL;
+    fMcEvt       = NULL;
+    fHillas      = NULL;
+    fWeight      = NULL;
+    fWeightsZd   = NULL;
+    fWeightsSize = NULL;
+    fPointing    = NULL;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Default Constructor.
+//
+MMcSpectrumWeight::MMcSpectrumWeight(const char *name, const char *title)
+{
+    Init(name,title);
+} 
+
+// ---------------------------------------------------------------------------
+//
+// Destructor. If necessary delete fFunc
+//
+MMcSpectrumWeight::~MMcSpectrumWeight()
+{
+    if (fFunc)
+        delete fFunc;
+//    if (fWeightsSize)
+//        delete fWeightsSize;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Search for
+//   - fNameMcEvt [MMcEvtBasic]
+//
+// Find/Create:
+//   - fNameWeight [MWeight]
+//
+Int_t MMcSpectrumWeight::PreProcess(MParList *pList)
+{
+    fMcEvt = (MMcEvt*)pList->FindObject(fNameMcEvt, "MMcEvtBasic");
+    if (!fMcEvt)
+    {
+        *fLog << err << fNameMcEvt << " [MMcEvtBasic] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fWeight = (MParameterD*)pList->FindCreateObj("MParameterD", fNameWeight);
+    if (!fWeight)
+        return kFALSE;
+
+    if (fWeightsZd)
+    {
+        fPointing = (MPointingPos*)pList->FindObject("MPointingPos");
+        if (!fPointing)
+        {
+            *fLog << err << "MPointingPos not found... abort." << endl;
+            return kFALSE;
+        }
+    }
+
+    if (fWeightsSize)
+    {
+        fHillas = (MHillas*)pList->FindObject("MHillas");
+        if (!fHillas)
+        {
+            *fLog << err << "MHillas not found... abort." << endl;
+            return kFALSE;
+        }
+    }
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Replace {fNameMcEvt}.fEnergy by "(x)" and return the result.
+//
+TString MMcSpectrumWeight::ReplaceX(TString str) const
+{
+    return str.ReplaceAll(MString::Format("%s.fEnergy", fNameMcEvt.Data()), "(x)");
+}
+
+// ---------------------------------------------------------------------------
+//
+// Return the function corresponding to the mc spectrum with
+// slope fOldSlope: pow({fNameMcEvt}.fEnergy, fOldSlope)
+//
+// The slope is returned as %.3f
+//
+TString MMcSpectrumWeight::GetFormulaSpecOld(const char *name) const
+{
+    return MString::Format("pow(%s.fEnergy, %.3f)", name, fOldSlope);
+}
+
+// ---------------------------------------------------------------------------
+//
+// Return the function corresponding to the new spectrum with
+// slope fNewSlope: pow({fNameMcEvt}.fEnergy, fNewSlope)
+//
+// The slope is returned as %.3f
+//
+// If a different formula is set (SetFormula()) this formula is returned
+// unchanged.
+//
+TString MMcSpectrumWeight::GetFormulaSpecNew(const char *name) const
+{
+    TString str = fFormula.IsNull() ? MString::Format("pow(%s.fEnergy, %.3f)", name, fNewSlope) : fFormula;
+    if (!fFormula.IsNull())
+        str.ReplaceAll("X", MString::Format("(%s.fEnergy)", name));
+
+    return str;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Return the formula to calculate weights.
+// Is is compiled by
+//   o1 = integral(fEnergyMin, fEnergyMax, GetFormulaSpecOldX());
+//   n1 = integral(fEnergyMin, fEnergyMax, GetFormulaSpecNewX());
+//   o2 = CalcSpecOld(fNormEnergy);
+//   n2 = CalcSpecNew(fNormEnergy);
+//
+//   result (fNormEnergy<0):
+//      fNorm*o1/n1*GetFormulaNewSpec()/GetFormulaOldSpec()
+//
+//   result (fNormEnergy>=0):
+//      fNorm*o2/n2*GetFormulaNewSpec()/GetFormulaOldSpec()
+//
+// fNorm is 1 by default but can be overwritten using SetNorm()
+//
+// If the formulas GetFormulaSpecOldX() and GetFormulaSpecNewX()
+// are equal only fNorm is returned.
+//
+// The normalization constant is returned as %.16e
+//
+// Example: 0.3712780019*(pow(MMcEvt.fEnergy,-2.270))/(pow(MMcEvt.fEnergy,-2.600))
+//
+TString MMcSpectrumWeight::GetFormulaWeights(const char *name) const
+{
+    if (GetFormulaSpecOld()==GetFormulaSpecNew())
+        return MString::Format("%.16e", fNorm);
+
+    const Double_t iold = fNormEnergy<0 ? GetSpecOldIntegral() : CalcSpecOld(fNormEnergy);
+    const Double_t inew = fNormEnergy<0 ? GetSpecNewIntegral() : CalcSpecNew(fNormEnergy);
+
+    const Double_t norm = fNorm*iold/inew;
+
+    return MString::Format("%.16e*(%s)/(%s)", norm, GetFormulaSpecNew(name).Data(), GetFormulaSpecOld(name).Data());
+}
+
+// ---------------------------------------------------------------------------
+//
+// Returns the integral between fEnergyMin and fEnergyMax of
+// GetFormulaSpecNewX() describing the destination spectrum
+//
+Double_t MMcSpectrumWeight::GetSpecNewIntegral(Double_t emin, Double_t emax) const
+{
+    TF1 funcnew("Dummy", GetFormulaSpecNewX().Data());
+    return funcnew.Integral(emin, emax);
+}
+
+// ---------------------------------------------------------------------------
+//
+// Returns the integral between fEnergyMin and fEnergyMax of
+// GetFormulaSpecOldX() describing the simulated spectrum
+//
+Double_t MMcSpectrumWeight::GetSpecOldIntegral(Double_t emin, Double_t emax) const
+{
+    TF1 funcold("Dummy", GetFormulaSpecOldX().Data());
+    return funcold.Integral(emin, emax);
+}
+
+// ---------------------------------------------------------------------------
+//
+// Returns the value of GetFormulaSpecNewX() at the energy e describing
+// the destination spectrum
+//
+Double_t MMcSpectrumWeight::CalcSpecNew(Double_t e) const
+{
+    TF1 funcnew("Dummy", GetFormulaSpecNewX().Data());
+    return funcnew.Eval(e);
+}
+
+// ---------------------------------------------------------------------------
+//
+// Returns the value of GetFormulaSpecOldX() at the energy e describing
+// the simulated spectrum
+//
+Double_t MMcSpectrumWeight::CalcSpecOld(Double_t e) const
+{
+    TF1 funcnew("Dummy", GetFormulaSpecOldX().Data());
+    return funcnew.Eval(e);
+}
+
+void MMcSpectrumWeight::SetWeightsSize(TH1D *h)
+{
+    fWeightsSize=h;
+    /*
+    if (h==0)
+    {
+        fWeightsSize=0;
+        return;
+    }
+
+    if (fWeightsSize)
+        delete fWeightsSize;
+
+    const Double_t xmin = TMath::Log10(h->GetXaxis()->GetXmin());
+    const Double_t xmax = TMath::Log10(h->GetXaxis()->GetXmax());
+    const Double_t xnum = h->GetNbinsX()+1;
+
+    fWeightsSize = new TSpline3("WeightsSize", xmin, xmax,
+                                h->GetArray()+1, xnum);*/
+}
+
+// ---------------------------------------------------------------------------
+//
+// Initialize fEnergyMin, fEnergymax and fOldSlope from MMcCorsikaRunHeader
+// by GetELowLim(), GetEUppLim() and GetSlopeSpec().
+//
+// If fEnergyMax>fEnergyMin (means: the values have already been
+// initialized) and !fAllowChange the consistency of the new values
+// with the present values is checked with a numerical precision of 1e-10.
+// If one doesn't match kFALSE is returned.
+//
+// If the mc slope is -1 kFALSE is returned.
+//
+// If the new slope for the spectrum is -1 it is set to the original MC
+// slope.
+//
+// fFunc is set to the formula returned by GetFormulaWeightsX()
+//
+Bool_t MMcSpectrumWeight::Set(const MMcCorsikaRunHeader &rh)
+{
+    if (fEnergyMax>fEnergyMin && !fAllowChange)
+    {
+        if (TMath::Abs(fEnergyMax-rh.GetEUppLim())>1e-10)
+        {
+            *fLog << err;
+            *fLog << "ERROR - The maximum simulated Monte Carlo energy is not allowed to change ";
+            *fLog << "(" << fEnergyMax << " --> " << rh.GetEUppLim() << ")... abort." << endl;
+            return kFALSE;
+        }
+
+        if (TMath::Abs(fOldSlope-rh.GetSlopeSpec())>1e-10)
+        {
+            *fLog << err;
+            *fLog << "ERROR - The slope of the Monte Carlo is not allowed to change ";
+            *fLog << "(" << fOldSlope << " --> " << rh.GetSlopeSpec() << ")... abort." << endl;
+            return kFALSE;
+        }
+
+        // No change happened
+        if (TMath::Abs(fEnergyMin-rh.GetELowLim())<=1e-10)
+            return kTRUE;
+
+        // The lower energy limit has changed
+        *fLog << warn;
+        *fLog << "The minimum simulated Monte Carlo energy has changed from ";
+        *fLog << fEnergyMin << "GeV to " << rh.GetELowLim() << "GeV." << endl;
+        fEnergyMin = rh.GetELowLim();
+    }
+
+    if (fNormEnergy<0 && fEnergyMin>0 && TMath::Abs(fEnergyMin-rh.GetELowLim())>1e-10)
+    {
+        *fLog << err;
+        *fLog << "You try to use changing minimum simulated Monte Carlo energies" << endl;
+        *fLog << "together with a normalization calculated from the integral." << endl;
+        *fLog << "This is not yet supported. Please switch to a normalization" << endl;
+        *fLog << "at a dedicated energy by specifying the energy" << endl;
+        *fLog << "    MMcSpectrumWeight.NormEnergy: 500" << endl;
+        *fLog << "in your sponde.rc." << endl;
+        return kFALSE;
+    }
+
+    fOldSlope  = rh.GetSlopeSpec();
+    fEnergyMin = rh.GetELowLim();
+    fEnergyMax = rh.GetEUppLim();
+
+    if (fNewSlope==-99 && fFormula.IsNull())
+    {
+        *fLog << inf << "A new slope for the power law has not yet been defined... using " << fOldSlope << "." << endl;
+        fNewSlope = fOldSlope;
+    }
+
+    if (fFunc)
+        delete fFunc;
+
+    if (GetFormulaSpecOld()==GetFormulaSpecNew())
+        *fLog << inf << "No spectral change requested..." << endl;
+    else
+    {
+        *fLog << inf << "Weighting from slope " << fOldSlope << " to ";
+        if (fFormula.IsNull())
+            *fLog << "slope " << fNewSlope << "." << endl;
+        else
+            *fLog << GetFormulaSpecNewX() << endl;
+    }
+
+    fFunc = new TF1("", GetFormulaWeightsX().Data());
+    fFunc->SetName("SpectralWeighs");
+    gROOT->GetListOfFunctions()->Remove(fFunc);
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+// completes a simulated spectrum starting at an energy fEnergyMin down to
+// an energy emin.
+//
+// It is assumed that the contents of MMcSpectrumWeight for the new spectrum
+// correctly describe the spectrum within the histogram, and fEnergyMin
+// and fEnergyMax correctly describe the range.
+//
+// If scale is given the histogram statistics is further extended by the
+// new spectrum according to the scale factor (eg. 1.2: by 20%)
+//
+// In the 1D case it is assumed that the x-axis is a zenith angle binning.
+// In the 2D case the x-axis is assumed to be zenith angle, the y-axis
+// to be energy.
+//
+void MMcSpectrumWeight::CompleteEnergySpectrum(TH1 &h, Double_t emin, Double_t scale) const
+{
+    if (h.InheritsFrom(TH3::Class()))
+    {
+        return;
+    }
+
+    if (fEnergyMin < emin)
+    {
+        *fLog << err << "ERROR - MMcSpctrumWeight::CompleteEnergySpectrum: fEnergyMin (";
+        *fLog << fEnergyMin << ") smaller than emin (" << emin << ")." << endl;
+        return;
+    }
+
+    // Total number of events for the new spectrum in the same
+    // energy range as the current histogram is filled
+    const Double_t norm = GetSpecNewIntegral();
+
+    // Check if it is only a histogram in ZA
+    if (!h.InheritsFrom(TH2::Class()))
+    {
+        // Warning: Simply scaling the zenith angle distribution might
+        // increase fluctuations for low statistics.
+        const Double_t f = GetSpecNewIntegral(emin, fEnergyMax)/norm;
+        h.Scale(f*scale);
+        return;
+    }
+
+    const TAxis &axey = *h.GetYaxis();
+
+    // Find energy range between the minimum energy to be filled (emin)
+    // and the minimum energy corresponding to the data filled into
+    // this histogram (fEnergyMin)
+    const Int_t first = axey.FindFixBin(emin);
+    const Int_t last  = axey.FindFixBin(fEnergyMin); // data range min energy
+    const Int_t max   = axey.FindFixBin(fEnergyMax); // data range max energy
+
+    for (int x=1; x<=h.GetNbinsX(); x++)
+    {
+        // Ratio between the number of events in the zenith angle
+        // bin corresponding to x and the new spectrum.
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,26,00)
+        const Double_t f = h.Integral(x, x, -1, 9999)/norm;
+#else
+        const Double_t f = h.Integral(x, x)/norm;
+#endif
+
+        // Fill histogram with the "new spectrum" between
+        // emin and fEnergyMin.
+        if (emin<fEnergyMin)
+            for (int y=first; y<=last; y++)
+            {
+                // Check if the bin is only partly filled by the energy range
+                const Double_t lo = axey.GetBinLowEdge(y)  <emin       ? emin       : axey.GetBinLowEdge(y);
+                const Double_t hi = axey.GetBinLowEdge(y+1)>fEnergyMin ? fEnergyMin : axey.GetBinLowEdge(y+1);
+
+                // Add the new spectrum extending the existing spectrum
+                h.AddBinContent(h.GetBin(x, y), f*GetSpecNewIntegral(lo, hi));
+            }
+
+        // If scale is >1 we also have to increse the statistics f the
+        // histogram according to scale.
+        if (scale>1)
+            for (int y=first; y<=max; y++)
+            {
+                // Check if the bin is only partly filled by the energy range
+                const Double_t lo = axey.GetBinLowEdge(y)  <emin       ? emin       : axey.GetBinLowEdge(y);
+                const Double_t hi = axey.GetBinLowEdge(y+1)>fEnergyMax ? fEnergyMax : axey.GetBinLowEdge(y+1);
+
+                // Use the analytical solution to scale the histogram
+                h.AddBinContent(h.GetBin(x, y), f*GetSpecNewIntegral(lo, hi)*(scale-1));
+            }
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// The current contants are printed
+//
+void MMcSpectrumWeight::Print(Option_t *o) const
+{
+    const TString opt(o);
+
+    const Bool_t hasnew = opt.Contains("new") || opt.IsNull();
+    const Bool_t hasold = opt.Contains("old") || opt.IsNull();
+
+    *fLog << all << GetDescriptor() << endl;
+
+    if (hasold)
+    {
+        *fLog << " Simulated energy range:   " << fEnergyMin << "GeV - " << fEnergyMax << "GeV" << endl;
+        *fLog << " Simulated spectral slope: ";
+        if (fOldSlope==-99)
+            *fLog << "undefined" << endl;
+        else
+            *fLog << fOldSlope << endl;
+    }
+    if (hasnew)
+    {
+        *fLog << " New spectral slope:       ";
+        if (fNewSlope==-99)
+            *fLog << "undefined/no change" << endl;
+        else
+            *fLog << fNewSlope << endl;
+    }
+    *fLog << " Additional user norm.:    " << fNorm << endl;
+    *fLog << " Spectra are normalized:   " << (fNormEnergy<0?"by integral":MString::Format("at %.1fGeV", fNormEnergy)) << endl;
+    if (hasold)
+    {
+        *fLog << " Old Spectrum:             ";
+        if (fNewSlope==-99)
+            *fLog << "undefined";
+        else
+            *fLog << GetFormulaSpecOldX();
+        if (fEnergyMin>=0 && fEnergyMax>0)
+            *fLog << "   (I=" << GetSpecOldIntegral() << ")";
+        *fLog << endl;
+    }
+    if (hasnew)
+    {
+        *fLog << " New Spectrum:             ";
+        if (fNewSlope==-99 && fFormula.IsNull())
+            *fLog << "undefined/no change";
+        else
+            *fLog << GetFormulaSpecNewX();
+        if (fEnergyMin>=0 && fEnergyMax>0)
+            *fLog << "   (I=" << GetSpecNewIntegral() << ")";
+        *fLog << endl;
+    }
+    if (fFunc)
+        *fLog << " Weight func:              " << fFunc->GetTitle()   << endl;
+}
+
+// ----------------------------------------------------------------------------
+//
+// Executed each time a new root file is loaded
+// We will need fOldSlope and fE{Upp,Low}Lim to calculate the weights
+//
+Bool_t MMcSpectrumWeight::ReInit(MParList *plist)
+{
+    MMcCorsikaRunHeader *rh = (MMcCorsikaRunHeader*)plist->FindObject("MMcCorsikaRunHeader");
+    if (!rh)
+    {
+        *fLog << err << "MMcCorsikaRunHeader not found... abort." << endl;
+        return kFALSE;
+    }
+
+    return Set(*rh);
+}
+
+/*
+ * This could be used to improve the Zd-weighting within a bin.
+ * Another option is to use more bins, or both.
+ * Note that it seems unnecessary, because the shape within the
+ * theta-bins should be similar in data and Monte Carlo... hopefully.
+ *
+void MMcSpectrumWeight::InitZdWeights()
+{
+    TH2D w(*fWeightsZd);
+
+    for (int i=1; i<=w.GetNbinsX(); i++)
+    {
+         const Double_t tmin = w.GetBinLowEdge(i)  *TMath::DegToRad();
+         const Double_t tmax = w.GetBinLowEdge(i+1)*TMath::DegToRad();
+
+         const Double_t wdth  = tmax-tmin;
+         const Double_t integ = cos(tmin)-cos(tmax);
+
+         w.SetBinContent(i, w.GetBinContent(i)*wdth/integ);
+    }
+
+    //  const Int_t i = fWeightsZd->GetXaxis()->FindFixBin(fPointing->GetZd());
+    //  const Double_t theta = fPointing->GetZd()*TMath::DegToRad();
+    //  w = sin(theta)*w.GetBinContent(i);
+}
+*/
+
+// ----------------------------------------------------------------------------
+//
+// Fill the result of the evaluation of fFunc at fEvEvt->GetEnergy
+// into the weights container.
+//
+Int_t MMcSpectrumWeight::Process()
+{
+    Double_t w = 1;
+
+    if (fWeightsZd)
+    {
+        const Int_t i = fWeightsZd->GetXaxis()->FindFixBin(fPointing->GetZd());
+        w = fWeightsZd->GetBinContent(i);
+    }
+    if (fWeightsSize)
+    {
+        const Int_t i = fWeightsSize->GetXaxis()->FindFixBin(fHillas->GetSize());
+        w *= fWeightsSize->GetBinContent(i);
+       // w *= fWeightsSize->Eval(TMath::Log10(fHillas->GetSize()));
+    }
+
+    const Double_t e = fMcEvt->GetEnergy();
+
+    fWeight->SetVal(fFunc->Eval(e)*w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//
+//   MMcSpectrumWeight.NewSlope:   -2.6
+//    The new slope of the spectrum
+//
+//   MMcSpectrumWeight.Norm:        1.0
+//    An additional artificial scale factor
+//
+//   MMcSpectrumWeight.NormEnergy:  200
+//    To normalize at a given energy instead of the integral
+//
+//   MMcSpectrumWeight.Formula:     pow(X, -2.6)
+//    A formula to which the spectrum is weighted (use a capital X for
+//    the energy)
+//
+Int_t MMcSpectrumWeight::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NewSlope", print))
+    {
+        rc = kTRUE;
+        SetNewSlope(GetEnvValue(env, prefix, "NewSlope", fNewSlope));
+    }
+    if (IsEnvDefined(env, prefix, "Norm", print))
+    {
+        rc = kTRUE;
+        SetNorm(GetEnvValue(env, prefix, "Norm", fNorm));
+    }
+    if (IsEnvDefined(env, prefix, "NormEnergy", print))
+    {
+        rc = kTRUE;
+        SetNormEnergy(GetEnvValue(env, prefix, "NormEnergy", fNormEnergy));
+    }
+    if (IsEnvDefined(env, prefix, "Formula", print))
+    {
+        rc = kTRUE;
+        SetFormula(GetEnvValue(env, prefix, "Formula", fFormula));
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mhflux/MMcSpectrumWeight.h
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/MMcSpectrumWeight.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/MMcSpectrumWeight.h	(revision 17960)
@@ -0,0 +1,111 @@
+#ifndef MARS_MMcSpectrumWeight
+#define MARS_MMcSpectrumWeight
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TF1;
+class TH1;
+class TH1D;
+class TSpline3;
+class MParList;
+class MMcEvt;
+class MHillas;
+class MParameterD;
+class MPointingPos;
+class MMcCorsikaRunHeader;
+
+class MMcSpectrumWeight : public MTask
+{
+private:
+    const MMcEvt  *fMcEvt;   // Pointer to the container with the MC energy
+    const MHillas *fHillas;
+    MParameterD   *fWeight;  // Pointer to the output MWeight container
+    MPointingPos  *fPointing;
+
+    TString fNameWeight;    // Name of the MWeight container
+    TString fNameMcEvt;     // Name of the MMcEvt container
+
+    TF1      *fFunc;        // Function calculating the weights
+    TH1      *fWeightsZd;   // Set additional ZA weights
+    TH1      *fWeightsSize; // Set additional ZA weights
+//    TSpline3 *fWeightsSize;
+
+    Double_t fOldSlope;     // Slope of energy spectrum generated with Corsika
+    Double_t fNewSlope;     // Slope of the new spectrum (if it is a power law)
+
+    Double_t fEnergyMin;    // Minimum energy simulated
+    Double_t fEnergyMax;    // Maximum energy simulated
+
+    Double_t fNorm;         // Normalization constant (additional normalization constant)
+    Double_t fNormEnergy;   // Energy at which the spectra are normalized (default -1 means the integral is used)
+
+    TString fFormula;       // Text Formula for new spectrum: eg. "pow(MMcEvt.fEnergy, -2.0)"
+
+    Bool_t fAllowChange;
+
+    // MMcSpectrumWeight
+    void Init(const char *name, const char *title);
+    TString ReplaceX(TString) const;
+
+    // MTask
+    Bool_t ReInit(MParList *plist); 
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MMcSpectrumWeight(const char *name=NULL, const char *title=NULL);
+    ~MMcSpectrumWeight();
+
+    // Setter
+    void SetNameWeight(const char *n="MWeight") { fNameWeight = n; }
+    void SetNameMcEvt(const char *n="MMcEvt") { fNameMcEvt = n; }
+    void SetNewSlope(Double_t s=-1) { fNewSlope = s; }
+    void SetNorm(Double_t s=1) { fNorm = s; }
+    void SetNormEnergy(Double_t s=1) { fNormEnergy = s; }
+    void SetFormula(const char *f="") { fFormula = f; }
+    void SetEnergyRange(Double_t min=-2, Double_t max=-1) { fEnergyMin=min; fEnergyMax=max; }
+    void SetOldSlope(Double_t s=-2.6) { fOldSlope=s; }
+    void SetWeightsZd(TH1 *h=0) { fWeightsZd = h; }
+    void SetWeightsSize(TH1D *h=0);
+
+    Bool_t Set(const MMcCorsikaRunHeader &h);
+
+    // Getter
+    TString GetFormulaSpecOld(const char *name) const;
+    TString GetFormulaSpecNew(const char *name) const;
+    TString GetFormulaWeights(const char *name) const;
+    TString GetFormulaSpecOld() const { return GetFormulaSpecOld(fNameMcEvt); }
+    TString GetFormulaSpecNew() const { return GetFormulaSpecNew(fNameMcEvt); }
+    TString GetFormulaWeights() const { return GetFormulaWeights(fNameMcEvt); }
+
+    TString GetFormulaSpecOldX() const { return ReplaceX(GetFormulaSpecOld()); }
+    TString GetFormulaSpecNewX() const { return ReplaceX(GetFormulaSpecNew()); }
+    TString GetFormulaWeightsX() const { return ReplaceX(GetFormulaWeights()); }
+
+    Double_t GetSpecNewIntegral(Double_t emin, Double_t emax) const;
+    Double_t GetSpecOldIntegral(Double_t emin, Double_t emax) const;
+
+    Double_t GetSpecNewIntegral() const { return GetSpecNewIntegral(fEnergyMin, fEnergyMax); }
+    Double_t GetSpecOldIntegral() const { return GetSpecOldIntegral(fEnergyMin, fEnergyMax); }
+
+    Double_t CalcSpecNew(Double_t e) const;
+    Double_t CalcSpecOld(Double_t e) const;
+
+    Double_t GetEnergyMin() const { return fEnergyMin; }
+    Double_t GetEnergyMax() const { return fEnergyMax; }
+
+    // Functions
+    void CompleteEnergySpectrum(TH1 &h, Double_t emin, Double_t scale=0) const;
+
+    // TObject
+    void Print(Option_t *o="") const;
+
+    ClassDef(MMcSpectrumWeight, 0) // Task to calculate weights to change the energy spectrum
+};
+
+#endif 
Index: branches/Mars_McMismatchStudy/mhflux/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mhflux/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhflux/Makefile	(revision 17960)
@@ -0,0 +1,45 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Flux
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mraw -I../manalysis      \
+	   -I../mgui -I../mgeom -I../mdata -I../mfilter -I../mimage \
+           -I../mmain -I../mmc -I../mreflector -I../mpointing       \
+           -I../mastro -I../mpedestal -I../msignal -I../mbadpixels
+
+SRCFILES = MAlphaFitter.cc \
+	   MHAlpha.cc \
+           MHThetaSq.cc \
+           MHThetaSqN.cc \
+           MHPhi.cc \
+           MHDisp.cc \
+           MHFalseSource.cc \
+	   MHEnergyEst.cc \
+	   MHEffectiveOnTime.cc \
+           MHCollectionArea.cc \
+           MHThreshold.cc \
+           MMcSpectrumWeight.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mhft/HftIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/HftIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/HftIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mhft/HftLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/HftLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/HftLinkDef.h	(revision 17960)
@@ -0,0 +1,14 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHexagonalFT+;
+#pragma link C++ class MHexagonalFTCalc+;
+#pragma link C++ class MHexagonFreqSpace+;
+
+#pragma link C++ class MGeomCamMagicXT+;
+#pragma link C++ class MGeomCamMagicEnhance+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mhft/MGeomCamMagicEnhance.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MGeomCamMagicEnhance.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MGeomCamMagicEnhance.cc	(revision 17960)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 12/2004  <mailto:>
+!   Author(s): Thomas Bretz, 12/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagicEnhance
+//
+// This task takes MSignalCam assuming that it is related to the Magic
+// camera geometry. By deviding and interpolation it resamples MSignalCam
+// such, that afterwards it is related to a geometry MGeomCamMagicXT
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagicEnhance.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MArrayD.h"
+
+ClassImp(MGeomCamMagicEnhance);
+
+using namespace std;
+
+const char *MGeomCamMagicEnhance::fgNameSignalCamIn  = "MSignalCam";
+const char *MGeomCamMagicEnhance::fgNameSignalCamOut = "MSignalCam";
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - empty
+//
+MGeomCamMagicEnhance::MGeomCamMagicEnhance(const char *name, const char *title)
+    : fNameSignalCamIn(fgNameSignalCamIn), fNameSignalCamOut(fgNameSignalCamOut),
+    fEvtIn(0), fEvtOut(0)
+{
+    fName  = name  ? name  : "MGeomCamMagicEnhance";
+    fTitle = title ? title : "Task to convert MSignalCam from MGeomCamMagic to MGeomCamMagicXT";
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Search for MSignalCam input and output container.
+//
+Int_t MGeomCamMagicEnhance::PreProcess(MParList *plist)
+{
+    fEvtIn = (MSignalCam*)plist->FindObject(fNameSignalCamIn, "MSignalCam");
+    if (!fEvtIn)
+    {
+        *fLog << err << fNameSignalCamIn << " [MSignalCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fEvtOut = (MSignalCam*)plist->FindCreateObj("MSignalCam", fNameSignalCamOut);
+    if (!fEvtOut)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Convert MCerPhotEvent into a new MArrayD depending on the new geometry
+//
+MArrayD MGeomCamMagicEnhance::Convert() const
+{
+    Double_t dEvt[577];
+    for (int i = 0; i<577; ++i)
+        dEvt[i] = (*fEvtIn)[i].GetNumPhotons();
+
+    MArrayD dEvent(1141);
+    memcpy(dEvent.GetArray(), dEvt, 577*sizeof(Double_t));
+
+    int k = 397; // alter Pixelindex
+    int m = 397; // neuer Index nach einem Durchlauf
+
+    double* pEvent = dEvent.GetArray() + 397;
+
+    for( int i = 0 ; i < 4 ; ++i )
+    {
+        for( int j = 0; j < 6; ++j )
+            for( int h = 0; h < 6 + i; ++h )
+            {
+                if( !j && !h )
+                    *(pEvent++) = 0.25*0.5*( dEvt[ m ] + dEvt[ m + (6 + i)*6 - 1 ] );
+
+                *(pEvent++) = 0.25*dEvt[ k ];
+
+                if(!(j == 5 && h == 5 + i)){
+                    if( i && h != 5 + i){
+                        *(pEvent++) = 0.25*1/3.*( dEvt[ k ] + dEvt[ k + 1 ] + dEvt[ k - (5 + i)*6 - j ] );
+                    }else
+                        *(pEvent++) = 0.25*0.5*( dEvt[ k ] + dEvt[ k + 1 ] );
+                }
+                k++;
+            }
+
+        k = m;
+
+        for( int j = 0; j < 6; ++j )
+            for( int h = 0; h < 6 + i; ++h )
+            {
+                if( !h && !j ){
+                    if( i != 3)
+                        *(pEvent++) = 0.25*0.25*( dEvt[ m ] + dEvt[ m + (6 + i)*6 - 1 ] + dEvt[ m + (6 + i)*6 ] + dEvt[ m + 12*i + 77 /*m + (6 + i)*6 + (6 + i + 1)*6 - 1*/ ] );
+                    else
+                        *(pEvent++) = 0.25*0.5*( dEvt[ m ] + dEvt[ m + (6 + i)*6 - 1 ] );
+                }
+
+                if( !h && j ){
+                    if( i != 3 ){
+                        *(pEvent++) = 0.25*0.25*( dEvt[ k - 1 ] + dEvt[ k ] + dEvt[ k + (6 + i)*6 + j - 1 ] + dEvt[ k + (6 + i)*6 + j ] );
+                    }else
+                        *(pEvent++) = 0.25*0.5*( dEvt[ k - 1 ] + dEvt[ k ] );
+                }
+
+                *(pEvent++) = 0.25*dEvt[ k ];
+                *(pEvent++) = 0.25*dEvt[ k ];
+
+                k++;
+
+            }
+
+        m += (6 + i)*6;
+    }
+
+    return dEvent;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Call Convert and copy result into output MSignalCam
+//
+Int_t MGeomCamMagicEnhance::Process()
+{
+    // Convert old stylish magic camera into new enhanced version
+    const MArrayD res(Convert());
+
+    // Copy result into output MSignalCam
+    fEvtOut->InitSize(res.GetSize());
+
+    for (UInt_t i=0; i<res.GetSize(); i++)
+        fEvtOut->AddPixel(i, res[i], 0);
+
+    //fEvtOut->FixSize();
+    fEvtOut->SetReadyToSave();
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mhft/MGeomCamMagicEnhance.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MGeomCamMagicEnhance.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MGeomCamMagicEnhance.h	(revision 17960)
@@ -0,0 +1,39 @@
+#ifndef MARS_MGeomCamMagicEnhance
+#define MARS_MGeomCamMagicEnhance
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MArrayD;
+class MSignalCam;
+
+class MGeomCamMagicEnhance : public MTask
+{
+private:
+    static const char *fgNameSignalCamIn;
+    static const char *fgNameSignalCamOut;
+
+    TString fNameSignalCamIn;
+    TString fNameSignalCamOut;
+
+    MSignalCam *fEvtIn;
+    MSignalCam *fEvtOut;
+
+    MArrayD Convert() const;
+
+    Int_t PreProcess(MParList *p);
+    Int_t Process();
+
+    void CleanFreqSpace(MArrayD &re, MArrayD &im);
+
+public:
+    MGeomCamMagicEnhance(const char *name=0, const char *title=0);
+
+    void SetNameSignalCamIn(const char *n) { fNameSignalCamIn = n; }
+    void SetNameSignalCamOut(const char *n) { fNameSignalCamOut = n; }
+
+    ClassDef(MGeomCamMagicEnhance, 0) //Task to convert MSignalCam from MGeomCamMagic to MGeomCamMagicXT
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mhft/MGeomCamMagicXT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MGeomCamMagicXT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MGeomCamMagicXT.cc	(revision 17960)
@@ -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): Christoph Kolodziejski, 12/2004  <mailto:>
+!   Author(s): Thomas Bretz, 12/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagicXT
+//
+// This class stores the geometry information of the 'extended' Magic
+// camera. The extended geometry has also small pixels in the outer region.
+// To convert MCerPhotEvt from MGeomCamMagic to MGeomCamMagicXT use
+// MGeomCamMagicExtend.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagicXT.h"
+
+ClassImp(MGeomCamMagicXT);
+
+// --------------------------------------------------------------------------
+//
+//  Magic camera has 577 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamMagicXT::MGeomCamMagicXT(const char *name)
+    : MGeomCamDwarf(19, 30, 17, name)
+{
+}
Index: branches/Mars_McMismatchStudy/mhft/MGeomCamMagicXT.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MGeomCamMagicXT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MGeomCamMagicXT.h	(revision 17960)
@@ -0,0 +1,17 @@
+#ifndef MARS_MGeomCamMagicXT
+#define MARS_MGeomCamMagicXT
+
+#ifndef MARS_MGeomCamDwarf
+#include "MGeomCamDwarf.h"
+#endif
+
+class MGeomCamMagicXT : public MGeomCamDwarf
+{
+public:
+    MGeomCamMagicXT(const char *name=NULL);
+
+    ClassDef(MGeomCamMagicXT, 1) // Geometry class for the 'extended' Magic camera
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhft/MHexagonFFT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonFFT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonFFT.cc	(revision 17960)
@@ -0,0 +1,578 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 11/2004  <mailto:>
+!   Author(s): Thomas Bretz, 11/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHexagonFFT.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHexagonFFT);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor
+//  Initializes random number generator and default variables
+//
+MHexagonFFT::MHexagonFFT()
+{
+}
+
+/*
+void MHexagonFFT::Prepare(Int_t num, Float_t scale)
+{
+    //Int_t    num   = 34;
+    //Double_t scale = dist_y/dist_x;
+
+    Int_t    cnt   = 108*num*num;
+
+    psire.Set(num*num);
+    psiim.Set(num*num);
+
+//    for(int j=0; j<num; j++)
+//    {
+//        for(int n=0; n<num; n++)
+//        {
+//            if (arr_k_m_id[j][n]<0)
+//                continue;
+//
+//            Double_t sumre=0;
+//            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<34-k; m++)
+                {
+                    //Int_t new_ID=arr_k_m_id[k][m];
+                    //if (new_ID<0)
+                    //    continue;
+
+                    Double_t dx = 0.5*(m-k)/num;
+                    Double_t dy = 0.5*(m+k)/num*scale;
+
+                    dx *= TMath::TwoPi()/3;
+                    dy *= TMath::TwoPi()/fgSqrt3;
+
+                    const Double_t cos1 = cos(dy*(j+n));
+                    const Double_t cos2 = cos(dy*j);
+                    const Double_t cos3 = cos(dy*n);
+
+                    //Alternatie nach Paper:
+                    psire[m*num+k] = 0.5*(
+                        +cos1*cos(dx*(j-n))
+                        +cos2*cos(dx*(j+2*n))
+                        +cos3*cos(dx*(2*j+n)));
+
+                    psiim[m*num+k] = 0.5*(
+                        +cos1*sin(dx*(j-n))
+                        +cos2*sin(dx*(j+2*n))
+                        -cos3*sin(dx*(2*j+n)));
+
+
+//                    psi_im *= i_inv;
+//
+//                    Double_t factor = (i_inv==1?1.:P_j_n(k,m));
+//
+//                    sumre += factor * (inre[new_ID]*psi_re - inim[new_ID]*psi_im);
+//                    sumim += factor * (inre[new_ID]*psi_im + inim[new_ID]*psi_re);
+}
+            }
+
+//            Double_t factor = (i_inv==1?1.:P_j_n(j,n)/cnt);
+//
+//            outre[arr_k_m_id[j][n]] = factor * sumre;
+//            outim[arr_k_m_id[j][n]] = factor * sumim;
+//        }
+//    }
+}
+*/
+
+void MHexagonFFT::Prepare(Float_t scale, Int_t num)
+{
+    static const Double_t fgSqrt3 = TMath::Sqrt(3.);
+
+    fNum = num;
+
+    MArrayD fCosX(num*num*num*3);
+    MArrayD fCosY(num*num*num*3);
+    MArrayD fSin(num*num*num*3);
+
+    for(int j=0; j<3*num; j++)
+    {
+        for(int k=0; k<num; k++)
+        {
+            for(int m=0; m<num-k; m++)
+            {
+                Double_t dx = 0.5*(m-k)/num;
+                Double_t dy = 0.5*(m+k)/num*scale;
+
+                dx *= TMath::TwoPi()/3;
+                dy *= TMath::TwoPi()/fgSqrt3;
+
+                const Int_t idx = (m*num + k)*3*num;
+
+                fCosX[idx+j] = TMath::Cos(dx*j);
+                fCosY[idx+j] = TMath::Cos(dy*j);
+                fSin [idx+j] = TMath::Sin(dx*j);
+            }
+        }
+    }
+
+    //fPsiRe.Set(num*num*num*num);
+    //fPsiIm.Set(num*num*num*num);
+    fPsi.Set(num*num*num*num*2);
+
+    Int_t lim = num*(num+1)/2;
+
+    fM.Set(lim);
+    fK.Set(lim);
+    fP.Set(lim);
+    fIdx.Set(lim);
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            int idx0 = num-n-1;
+            int idx1 = idx0*(idx0+1)/2 + j;
+
+            fM[idx1]=n;
+            fK[idx1]=j;
+
+            fP[idx1]=P(j,n);
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<num-k; m++)
+                {
+                    const Int_t idx = (m*num + k)*3*num;
+
+                    const Float_t cos1 = fCosY[idx+j+n];
+                    const Float_t cos2 = fCosY[idx+j];
+                    const Float_t cos3 = fCosY[idx+n];
+
+                    int idx2 = num-m-1;
+                    int idx3 = idx2*(idx2+1)/2 + k;
+                    const Int_t id1 = idx1*lim + idx3;
+
+                    //fPsiRe[id1]
+                    Double_t fPsiRe
+                        = 2*(
+                          +cos1*fCosX[idx+TMath::Abs(j-n)]
+                          +cos2*fCosX[idx+j+2*n]
+                          +cos3*fCosX[idx+2*j+n]);
+
+                    //fPsiIm[id1] = 2*(
+                    Double_t fPsiIm = 2*(
+                          +cos1*fSin[idx+TMath::Abs(j-n)]*TMath::Sign(1, j-n)
+                          +cos2*fSin[idx+j+2*n]
+                          -cos3*fSin[idx+2*j+n]);
+
+                    fPsi[id1*2]   = fPsiRe;//fPsiRe[id1];
+                    fPsi[id1*2+1] = fPsiIm;//fPsiIm[id1];
+                }
+            }
+
+        }
+    }
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        int n = fM[idx1];
+        int j = fK[idx1];
+
+        int idx0;
+        for (idx0=0; idx0<lim; idx0++)
+            if (fM[idx0]==j && fK[idx0]==n)
+                break;
+
+        fIdx[idx1]=idx0;
+    }
+
+}
+/*
+void MHexagonFFT::DGT4(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd)
+{
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+    Int_t lim = num*(num+1)/2;
+
+    Float_t *endp = fP.GetArray()+lim;
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        if (fK[idx1]>fM[idx1] && fwd)
+            continue;
+
+        Double_t sumre=0;
+        Double_t sumim=0;
+
+        Float_t  *psi = fPsi.GetArray() + idx1*lim*2;
+        Float_t  *p   = fP.GetArray();
+        Double_t *im  = inim.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        while (p<endp)
+        {
+            const Float_t factor1 = (fwd?*p:1.);
+
+            const Float_t psire = *psi++;
+            const Float_t psiim = *psi++;
+
+            sumre     += factor1 * (*re * psire - *im * psiim);
+            if (fwd)
+                sumim += factor1 * (*re * psiim + *im * psire);
+
+            im++;
+            re++;
+            p++;
+        }
+
+        const Double_t factor2 = fwd?fP[idx1]/cnt:1.;
+
+        outre[idx1] =  factor2 * sumre;
+        outim[idx1] = -factor2 * sumim;
+    }
+
+    if (!fwd)
+        return;
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        if (fK[idx1]<fM[idx1])
+            continue;
+
+        outre[idx1] =  outre[fIdx[idx1]];
+        outim[idx1] = -outim[fIdx[idx1]];
+    }
+    }*/
+
+void MHexagonFFT::TransformFastFWD(const MArrayD &inre,
+                                   MArrayD &outre,
+                                   MArrayD &outim) const
+{
+    const UInt_t num = fP.GetSize();
+
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonFFT prepared for different size." << endl;
+        return;
+    }
+
+    outre.Set(num);
+    outim.Set(num);
+
+    const Int_t cnt = 108*fNum*fNum;
+
+    const Float_t *endp = fP.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        if (fK[idx1]>fM[idx1])
+            continue;
+
+        Double_t sumre=0;
+        Double_t sumim=0;
+
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Float_t  *p   = fP.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        // 1st access to psi: const Float_t psire = *psi++;
+        // 2nd access to psi: const Float_t psiim = *psi++;
+        // sumre += f * *psire;
+        // sumim += f * *psiim;
+        while (p<endp)
+        {
+            const Double_t f = *p++ * *re++;
+
+            sumre += f * *psi++;
+            sumim += f * *psi++;
+        }
+
+        const Double_t factor2 = fP[idx1]/cnt;
+
+        outre[fIdx[idx1]] =   outre[idx1] =  factor2 * sumre;
+        outim[fIdx[idx1]] = -(outim[idx1] = -factor2 * sumim);
+
+        /*
+         outre[idx1] =  factor2 * sumre;
+         outim[idx1] = -factor2 * sumim;
+
+         outre[fIdx[idx1]] =  outre[idx1];
+         outim[fIdx[idx1]] = -outim[idx1];
+         */
+    }
+    /*
+     for (UInt_t idx1=0; idx1<num; idx1++)
+     {
+        if (fK[idx1]<fM[idx1])
+           continue;
+
+        outre[idx1] =  outre[fIdx[idx1]];
+        outim[idx1] = -outim[fIdx[idx1]];
+     }
+     */
+}
+
+void MHexagonFFT::TransformFastBWD(const MArrayD &inre,
+                                   const MArrayD &inim,
+                                   MArrayD &outre) const
+{
+    const UInt_t num = fP.GetSize();
+
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonFFT prepared for different size." << endl;
+        return;
+    }
+    if (inim.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonFFT prepared for different size." << endl;
+        return;
+    }
+    outre.Set(num);
+
+
+    const Double_t *endre = inre.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Double_t *im  = inim.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        Double_t sumre=0;
+        while (re<endre)
+        {
+            const Float_t psire = *psi++;
+            const Float_t psiim = *psi++;
+
+            sumre += *re++ * psire - *im++ * psiim;
+        }
+
+        outre[idx1] = sumre;
+    }
+}
+/*
+void MHexagonFFT::DGT3(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd)
+{
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            Int_t lim = num*(num+1)/2;
+            for (int idx0=0; idx0<lim; idx0++)
+
+//            for(int k=0; k<num; k++)
+            {
+                int m = fM[idx0];
+                int k = fK[idx0];
+            //                for(int m=0; m<num-k; m++)
+
+                {
+                    const Int_t id = k*num + m;
+                    const Int_t id1 = (((id*num)+n)*num+j)*2;
+
+                    //Alternatie nach Paper:
+                    const Float_t psire = fPsi[id1];   //fPsiRe[(id*num+n)*num+j];
+                    const Float_t psiim = fPsi[id1+1]; //fPsiIm[(id*num+n)*num+j]*inv;
+
+                    const Float_t factor1 = fwd==1?P(k,m):1.;
+
+                    sumre += factor1 * (inre[id]*psire - inim[id]*psiim);
+                    if (fwd)
+                        sumim += factor1 * (inre[id]*psiim + inim[id]*psire);
+                }
+            }
+
+            const Double_t factor2 = fwd==1?P(j,n)/cnt:1.;
+
+            outre[j*num+n] =  factor2 * sumre;
+            outim[j*num+n] = -factor2 * sumim;
+
+            if (!fwd)
+                continue;
+
+            outre[n*num+j] =  factor2 * sumre;
+            outim[n*num+j] =  factor2 * sumim;
+        }
+    }
+}
+
+void MHexagonFFT::DGT2(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd)
+{
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+    Int_t inv = fwd?-1:1;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<num-k; m++)
+                {
+                    const Int_t idx = (m*num + k)*3*num;
+
+                    const Float_t cos1 = fCosY[idx+j+n];
+                    const Float_t cos2 = fCosY[idx+j];
+                    const Float_t cos3 = fCosY[idx+n];
+
+                    //Alternatie nach Paper:
+                    const Float_t psire = 2*(
+                          +cos1*fCosX[idx+TMath::Abs(j-n)]
+                          +cos2*fCosX[idx+j+2*n]
+                          +cos3*fCosX[idx+2*j+n]);
+
+                    const Float_t psiim = 2*inv*(
+                          +cos1*fSin[idx+TMath::Abs(j-n)]*TMath::Sign(1, j-n)
+                          +cos2*fSin[idx+j+2*n]
+                          -cos3*fSin[idx+2*j+n]);
+
+                    const Float_t factor = (fwd==1?P(k,m):1.);
+
+                    sumre += factor * (inre[k*num+m]*psire - inim[k*num+m]*psiim);
+                    sumim += factor * (inre[k*num+m]*psiim + inim[k*num+m]*psire);
+                }
+            }
+
+            const Double_t factor = (fwd==1?P(j,n)/cnt:1.);
+
+            outre[j*num+n] = factor * sumre;
+            outim[j*num+n] = factor * sumim;
+
+            if (fwd)
+            {
+                outre[n*num+j] =  factor * sumre;
+                outim[n*num+j] = -factor * sumim;
+            }
+        }
+    }
+}
+*/
+void MHexagonFFT::TransformSlow(const MArrayD &inre, const MArrayD &inim,
+                                MArrayD &outre,      MArrayD &outim,
+                                Float_t scale,       Bool_t fwd)
+{
+    static const Double_t fgSqrt3 = TMath::Sqrt(3.);
+
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+    Int_t inv = fwd?-1:1;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<num-k; m++)
+                {
+                    Double_t dx = 0.5*(m-k)/num;
+                    Double_t dy = 0.5*(m+k)/num*scale;
+
+                    dx *= TMath::TwoPi()/3;
+                    dy *= TMath::TwoPi()/fgSqrt3;
+
+                    const Double_t cos1 = TMath::Cos(dy*(j+n));
+                    const Double_t cos2 = TMath::Cos(dy*j);
+                    const Double_t cos3 = TMath::Cos(dy*n);
+
+                    //Alternatie nach Paper:
+                    const Double_t psire = 2*(
+                        +cos1*TMath::Cos(dx*(j-n))
+                        +cos2*TMath::Cos(dx*(j+2*n))
+                        +cos3*TMath::Cos(dx*(2*j+n)));
+
+                    const Double_t psiim = 2*inv*(
+                        +cos1*TMath::Sin(dx*(j-n))
+                        +cos2*TMath::Sin(dx*(j+2*n))
+                        -cos3*TMath::Sin(dx*(2*j+n)));
+
+                    const Double_t factor = (fwd==1?P(k,m):1.);
+
+                    sumre += factor * (inre[k*num+m]*psire - inim[k*num+m]*psiim);
+                    sumim += factor * (inre[k*num+m]*psiim + inim[k*num+m]*psire);
+                }
+            }
+
+            const Double_t factor = (fwd==1?P(j,n)/cnt:1.);
+
+            outre[j*num+n] = factor * sumre;
+            outim[j*num+n] = factor * sumim;
+
+            if (fwd)
+            {
+                outre[n*num+j] =  factor * sumre;
+                outim[n*num+j] = -factor * sumim;
+            }
+        }
+    }
+}
Index: branches/Mars_McMismatchStudy/mhft/MHexagonFFT.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonFFT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonFFT.h	(revision 17960)
@@ -0,0 +1,78 @@
+#ifndef MARS_MHexagonFFT
+#define MARS_MHexagonFFT
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef ROOT_MArrayI
+#include "MArrayI.h"
+#endif
+
+class MHexagonFFT : public TObject
+{
+private:
+    static float P(int j, int n)
+    {
+        const Int_t a = (j+n)%34 ? 0 : 1;
+        const Int_t b = j%34     ? 0 : 1;
+        const Int_t c = n%34     ? 0 : 1;
+
+        return 6./((1+a)*(1+b+c));
+    }
+
+    Int_t fNum;
+
+    MArrayF fPsi;
+
+    MArrayI fM;
+    MArrayI fK;
+
+    MArrayF fP;
+
+    MArrayI fIdx;
+
+public:
+    MHexagonFFT();
+    MHexagonFFT(Float_t scale, Int_t num)
+    {
+        Prepare(scale, num);
+    }
+
+    void Prepare(Float_t scale, Int_t num);
+
+    void TransformFastFWD(const MArrayD &inre, MArrayD &outre, MArrayD &outim) const;
+    void TransformFastBWD(const MArrayD &inre, const MArrayD &inim, MArrayD &outre) const;
+
+    void TransformSlow(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd=kTRUE);
+    /*
+    void DGT2(const MArrayD &inre,
+             const MArrayD &inim,
+             MArrayD &outre,
+             MArrayD &outim,
+             Float_t scale,
+             Bool_t fwd=kTRUE);
+    void DGT3(const MArrayD &inre,
+             const MArrayD &inim,
+             MArrayD &outre,
+             MArrayD &outim,
+             Float_t scale,
+             Bool_t fwd=kTRUE);
+    void DGT4(const MArrayD &inre,
+             const MArrayD &inim,
+             MArrayD &outre,
+             MArrayD &outim,
+             Float_t scale,
+             Bool_t fwd=kTRUE);
+    */
+    ClassDef(MHexagonFFT,0)
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mhft/MHexagonFreqSpace.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonFreqSpace.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonFreqSpace.cc	(revision 17960)
@@ -0,0 +1,177 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 08/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHexagonFreqSpace
+//
+// This is a generalized class storing camera data. It stores real and
+// imaginary part of the triangular frequency space of the MHexagonalFT.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHexagonFreqSpace.h"
+
+#include "MMath.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+
+ClassImp(MHexagonFreqSpace);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MCerPhotPix object for each pixel in the event
+//
+MHexagonFreqSpace::MHexagonFreqSpace(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHexagonFreqSpace";
+    fTitle = title ? title : "Storage container for fourier space camera";
+}
+
+Double_t MHexagonFreqSpace::GetAbs(UInt_t idx) const
+{
+    return TMath::Hypot(fDataRe[idx], fDataIm[idx]);
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// This is not yet implemented like it should.
+//
+
+void MHexagonFreqSpace::Draw(Option_t* option) 
+{
+    //
+    //   FIXME!!! Here the Draw function of the CamDisplay
+    //   should be called to add the CamDisplay to the Pad.
+    //   The drawing should be done in MCamDisplay::Paint
+    //
+
+    //    MGeomCam *geom = fType ? new MGeomCamMagic : new MGeomCamCT1;
+    //    MCamDisplay *disp = new MCamDisplay(geom);
+    //    delete geom;
+    //    disp->DrawPhotNum(this);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Returns the contents of the pixel.
+//  type 0: sqrt(re^2+im^2)
+//  type 1: re
+//  type 2: im
+//
+Bool_t MHexagonFreqSpace::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx<0 || (UInt_t)idx>=fDataRe.GetSize())
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+        val = TMath::Hypot(fDataRe[idx], fDataIm[idx]);
+        break;
+    case 1:
+        val = fDataRe[idx];
+        break;
+    case 2:
+        val = fDataIm[idx];
+        break;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set real and imaginary part from MArrayD re and im. The size of both
+// arrays must be identical.
+//
+void MHexagonFreqSpace::Set(const MArrayD &re, const MArrayD &im)
+{
+    if (re.GetSize()!=im.GetSize())
+        return;
+/*
+    fDataRe.Set(re.GetSize());
+    fDataIm.Set(re.GetSize());
+    for(unsigned int j=0; j<re.GetSize(); j++)
+    {
+        fDataRe[j]=re[j];
+        fDataIm[j]=im[j];
+    }
+  */
+    fDataRe = re;
+    fDataIm = im;
+}
+
+void MHexagonFreqSpace::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MHexagonFreqSpace::DrawPixelContent - not available." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Create a new geometry based on the size num. which is the number
+// of pixels in the triangle.
+//
+// It is YOUR responsibility to make sure that the allocated MGeomCam is
+// deleted elsewhere!
+//
+// WARNING:
+// ========
+// * Currently there are some basic problems with MGeomCam -- so please don't
+// wonder if you encounter strange behaviour, especially using this
+// kind of MGeomCam as a data member in MHCamera which is itself a data
+// member of some other class.
+// This maybe fixed soon by intoducing a MGeomCamTriangle.
+// * The created geometry does not contain ANY valid neighbor information yet.
+//
+MGeomCam *MHexagonFreqSpace::NewGeomCam(UShort_t num)
+{
+    static const Double_t fgTan30 = TMath::Tan(30*TMath::DegToRad())*3;
+
+    MGeomCam *cam = new MGeomCam(num, 1);
+
+    num = (int)((1.+sqrt(1.+8.*num))/2.)-1;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            int idx1 = (j+n)*(j+n+1)/2 + j;
+
+            cam->SetAt(idx1, MGeomPix(n-j, (n+j-num/2)*fgTan30, 2));
+            (*cam)[idx1].SetNeighbors();
+        }
+    }
+    cam->InitGeometry();
+    return cam;
+}
Index: branches/Mars_McMismatchStudy/mhft/MHexagonFreqSpace.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonFreqSpace.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonFreqSpace.h	(revision 17960)
@@ -0,0 +1,39 @@
+#ifndef MARS_MHexagonFreqSpace
+#define MARS_MHexagonFreqSpace
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef ROOT_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MGeomCam;
+
+class MHexagonFreqSpace : public MParContainer, public MCamEvent
+{
+private:
+    MArrayD fDataRe;  //
+    MArrayD fDataIm;  //
+
+public:
+    MHexagonFreqSpace(const char *name=NULL, const char *title=NULL);
+    ~MHexagonFreqSpace() { }
+
+    void Set(const MArrayD &re, const MArrayD &im);
+
+    Double_t GetAbs(UInt_t idx) const;
+
+    static MGeomCam *NewGeomCam(UShort_t num);
+    MGeomCam *NewGeomCam() const { return NewGeomCam(fDataRe.GetSize()); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MHexagonFreqSpace, 1) // Generalized storage class for camera data in hexagonal frequency space (triangle)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhft/MHexagonalFT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonalFT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonalFT.cc	(revision 17960)
@@ -0,0 +1,465 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 11/2004  <mailto:>
+!   Author(s): Thomas Bretz, 11/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHexagonalFT
+//
+// This is a class representating a (fast) fourier transformation explicitly
+// for hexagonal geometries as described in astro-ph/0409388.
+//
+//
+// WARNING:
+// ========
+// Be carefull using the fast transformation (Prepare())! The precalculation
+// consumes a lot of memory. fPsi has the size of 2*n^4 (while n is the
+// number of rows in fourier space). For the enhanced MAGIC camery fPsi has
+// the size 27691682*sizeof(float) = 105.6MB (Std MAGIC: ~12MB)
+//
+// The runtime is more or less determined by the speed of accessing a
+// huge amount of memory (see above) sequentially.
+//
+//
+// Coordinate systems:
+// ===================
+//
+//  original hexagonal structure     enhanced hexagonal structure
+//  ----------------------------     ----------------------------
+//
+//                            structure
+//                            ---------
+//
+//                h h h                  f f h h h f f
+//               h h h h                  f h h h h f
+//              h h h h h       ----->     h h h h h
+//               h h h h                    h h h h
+//                h h h                      h h h
+//                                            f f
+//                                             f
+//
+//                            numbering
+//                            ---------
+//                d c b                  m n o p q r s
+//               e 4 3 a                  g h i j k l
+//              f 5 1 2 9       ----->     b c d e f
+//               g 6 7 8                    7 8 9 a
+//                h i j                      4 5 6
+//                                            2 3
+//                                             1
+//
+// In reality the fourier space looks like because of symmetries:
+//
+//            real part                 imaginary part
+//            ---------                 --------------
+//          m n o p o n m          m   n   o   0  -o  -n  -m
+//           g h i i h g             g   h   i  -i  -h  -g
+//            b c d c b                b   c   0  -c  -b
+//             7 8 8 7                   7   8  -8  -7
+//              4 5 4                      4   0  -4
+//               2 2                         2  -2
+//                1                            0
+//
+//         column: GetK()                  row: GetM()
+//         --------------                  -----------
+//          6 5 4 3 2 1 0                 0 1 2 3 4 5 6
+//           5 4 3 2 1 0                   0 1 2 3 4 5
+//            4 3 2 1 0                     0 1 2 3 4
+//             3 2 1 0                       0 1 2 3
+//              2 1 0                         0 1 2
+//               1 0                           0 1
+//                0                             0
+//
+//       row: GetRow() (m+k)        column: GetCol() (m-k)
+//       -------------------        ----------------------
+//          6 6 6 6 6 6 6         -6  -4  -2   0   2   4   6
+//           5 5 5 5 5 5            -5  -3  -1   1   3   5
+//            4 4 4 4 4               -4  -2   0   2   4
+//             3 3 3 3                  -3  -1   1   3
+//              2 2 2                     -2   0   2
+//               1 1                        -1   1
+//                0                            0
+//
+//
+// The coordinates of the pixels in the triangle are:
+//
+//    Double_t dx; // Distance of too pixels in x
+//    Double_t dy; // Distance of to pixel rows in y
+//    Int_t idx;   // Index of pixel in triangle (see above)
+//
+//    const Float_t x = dx*GetCol(idx);
+//    const Float_t y = dy*Int_t(GetRow(idx)-2*GetNumRows()/3);
+//
+// You can use MGeomCam::GetPixelIdxXY(x, y) to get the corresponding index
+// in space space.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHexagonalFT.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayD.h"
+
+ClassImp(MHexagonalFT);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - empty
+//
+MHexagonalFT::MHexagonalFT()
+{
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - num is the number of lines the fourier space has.
+//  It calls Prepare to fill the arrays with the necessary coefficients.
+//
+//  Here are some simple rules to calculate parameters in a hexagonal space:
+//
+// Number of Rings (r) ---> Number of Pixels (p)
+// p = 3*r*(r-1)+1
+//
+// Number of Pixels (p) ---> Number of Rings (r)
+// p = (sqrt(9+12*(p-1))+3)/6
+//
+// Number of pixels at one border == number of rings (r)
+// Row of border                  == number of rings (r)
+//
+// Number of rows to get a triangle: 3r-2
+//
+MHexagonalFT::MHexagonalFT(Int_t num)
+{
+    Prepare(num);
+}
+
+// ---------------------------------------------------------------------------
+//
+// Calculate the contents of: fM, fK, fP, fIdx and fPsi.
+//
+// While fPsi are the fourier coefficients, fM and fK are the hexagonal x and
+// y coordinates of the pixel corresponding to the index i which is the
+// common index of all arrays. fP is P(i,j) for all pixels.
+//
+// fIdx is also filled and used for reverse mapping. Due to the geometry
+// the right and left side of the fourier space triangle has identical
+// values. fIdx 'maps' the indices from the right to the left side.
+//
+void MHexagonalFT::Prepare(Int_t num)
+{
+    fNumRows = num;
+
+    fPsi.Set(num*num*num*num*2);
+
+    Int_t lim = num*(num+1)/2;
+
+    fM.Set(lim);
+    fK.Set(lim);
+    fP.Set(lim);
+    fIdx.Set(lim);
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n+j<num; n++)
+        {
+            int idx1 = (j+n)*(j+n+1)/2 + j;
+
+            fM[idx1]=n;
+            fK[idx1]=j;
+
+            fP[idx1]=P(j,n);
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m+k<num; m++)
+                {
+                    const Double_t dx = TMath::Pi()*(m-k)/(num-1)/3;
+                    const Double_t dy = TMath::Pi()*(m+k)/(num-1);
+
+                    const Double_t cos1 = TMath::Cos(dy*(j+n));
+                    const Double_t cos2 = TMath::Cos(dy*j);
+                    const Double_t cos3 = TMath::Cos(dy*n);
+
+                    const Double_t psire = 2*(
+                        +cos1*TMath::Cos(dx*(j-n))
+                        +cos2*TMath::Cos(dx*(j+2*n))
+                        +cos3*TMath::Cos(dx*(2*j+n)));
+
+                    const Double_t psiim = 2*(
+                        +cos1*TMath::Sin(dx*(j-n))
+                        +cos2*TMath::Sin(dx*(j+2*n))
+                        -cos3*TMath::Sin(dx*(2*j+n)));
+
+                    const Int_t idx3 = (k+m)*(k+m+1)/2 + k;
+                    const Int_t id1  = idx1*lim + idx3;
+
+                    fPsi[id1*2]   = psire;
+                    fPsi[id1*2+1] = psiim;
+                }
+            }
+        }
+    }
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        int n = fM[idx1];
+        int j = fK[idx1];
+
+        int idx0;
+        for (idx0=0; idx0<lim; idx0++)
+            if (fM[idx0]==j && fK[idx0]==n)
+                break;
+
+        fIdx[idx1]=idx0;
+    }
+
+}
+
+// ---------------------------------------------------------------------------
+//
+// Do a fast forward tranformation. Because all coefficients are
+// precalculated, the tranformation is reduced to a simple pointer based
+// loop over the coeffiecients multiplied with the corresponding input
+// values.
+//
+// Parameters:
+//  inre: array storing the real part of the input (eg. pixel contents)
+// outre: array storing the real part of the output
+// outim: array storing the imaginary part of the output
+//
+// inre must be of the size of the fourier space triangle. The pixel
+// contents must have been mapped into this new space with the proper
+// pixel indices. The size of outre and outim is set accordingly.
+//
+// After initialization (Prepare()) you can get the size of the arrays with
+// GetNumKnots()
+//
+// For the definition of the coordinate system see class description
+//
+void MHexagonalFT::TransformFastFWD(const MArrayD &inre, MArrayD &outre,
+                                    MArrayD &outim) const
+{
+    const UInt_t num = fP.GetSize();
+
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonalFT prepared for different size." << endl;
+        return;
+    }
+
+    outre.Set(num);
+    outim.Set(num);
+
+    const Int_t cnt = 108*(fNumRows-1)*(fNumRows-1);
+
+    const Float_t *endp = fP.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        if (fK[idx1]>fM[idx1])
+            continue;
+
+        Double_t sumre=0;
+        Double_t sumim=0;
+
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Float_t  *p   = fP.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        // 1st access to psi: const Float_t psire = *psi++;
+        // 2nd access to psi: const Float_t psiim = *psi++;
+        // sumre += f * *psire;
+        // sumim += f * *psiim;
+        while (p<endp)
+        {
+            const Double_t f = *p++ * *re++;
+
+            sumre += f * *psi++;
+            sumim += f * *psi++;
+        }
+
+        const Double_t factor2 = fP[idx1]/cnt;
+
+        outre[fIdx[idx1]] =  (outre[idx1] =  factor2 * sumre);
+        outim[fIdx[idx1]] = -(outim[idx1] = -factor2 * sumim);
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// Do a fast backward tranformation. Because all coefficients are
+// precalculated, the tranformation is reduced to a simple pointer based
+// loop over the coeffiecients multiplied with the corresponding input
+// values.
+//
+// Parameters:
+//  inre: outre of TransformFastBwd
+//  inim: outim of TransformFastBwd
+// outre: backward tranformed real part of the resulting
+//
+// inre and inim must be of the size of the fourier space triangle. The
+// pixel contents must have been mapped into this new space with the proper
+// pixel indices. The size of outre is set accordingly.
+//
+// After initialization (Prepare()) you can get the size of the arrays with
+// GetNumKnots()
+//
+// For the definition of the coordinate system see class description
+//
+void MHexagonalFT::TransformFastBWD(const MArrayD &inre, const MArrayD &inim,
+                                    MArrayD &outre) const
+{
+    const UInt_t num = fP.GetSize();
+
+    // Sanity check: check size of arrays
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonalFT prepared for different size." << endl;
+        return;
+    }
+    if (inim.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonalFT prepared for different size." << endl;
+        return;
+    }
+    outre.Set(num);
+
+    const Double_t *endre = inre.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Double_t *im  = inim.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        Double_t sumre=0;
+        while (re<endre)
+        {
+            const Float_t psire = *psi++;
+            const Float_t psiim = *psi++;
+
+            sumre += *re++ * psire - *im++ * psiim;
+        }
+
+        outre[idx1] = sumre;
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// This is a slow (direct) version of the tranformation. It is identical
+// for forward and backward tranformation.
+//
+// The whole calculation is done straight forward without any precalculation.
+//
+// Parameters:
+//  inre:  real part of input
+//  inim:  imaginary part of input
+//  outre: real part of output
+//  outim: imaginary part of output
+//  fwd:   kTRUE for forward, kFALSE for backward transformations
+//
+// After initialization (Prepare()) you can get the size of the arrays with
+// GetNumKnots()
+//
+// For the definition of the coordinate system see class description
+//
+// It is currently not tested!
+//
+void MHexagonalFT::TransformSlow(const MArrayD &inre, const MArrayD &inim,
+                                 MArrayD &outre,      MArrayD &outim,
+                                 Bool_t fwd)
+{
+    static const Double_t fgSqrt3 = TMath::Sqrt(3.);
+    static const Double_t fgTan30 = TMath::Tan(30*TMath::DegToRad())*3;
+
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*(num-1)*(num-1);
+    Int_t inv = fwd?-1:1;
+
+    // FIXME: For p(j,n)
+    fNumRows = num;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n+j<num; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m+k<num; m++)
+                {
+                    Double_t dx = 0.5*(m-k)/num;
+                    Double_t dy = 0.5*(m+k)/num*fgTan30;
+
+                    dx *= TMath::TwoPi()/3;
+                    dy *= TMath::TwoPi()/fgSqrt3;
+
+                    const Double_t cos1 = TMath::Cos(dy*(j+n));
+                    const Double_t cos2 = TMath::Cos(dy*j);
+                    const Double_t cos3 = TMath::Cos(dy*n);
+
+                    //Alternatie nach Paper:
+                    const Double_t psire = 2*(
+                        +cos1*TMath::Cos(dx*(j-n))
+                        +cos2*TMath::Cos(dx*(j+2*n))
+                        +cos3*TMath::Cos(dx*(2*j+n)));
+
+                    const Double_t psiim = 2*inv*(
+                        +cos1*TMath::Sin(dx*(j-n))
+                        +cos2*TMath::Sin(dx*(j+2*n))
+                        -cos3*TMath::Sin(dx*(2*j+n)));
+
+                    const Double_t factor = (fwd==1?P(k,m):1.);
+
+                    sumre += factor * (inre[k*num+m]*psire - inim[k*num+m]*psiim);
+                    sumim += factor * (inre[k*num+m]*psiim + inim[k*num+m]*psire);
+                }
+            }
+
+            const Double_t factor = (fwd==1?P(j,n)/cnt:1.);
+
+            outre[j*num+n] = factor * sumre;
+            outim[j*num+n] = factor * sumim;
+
+            if (fwd)
+            {
+                outre[n*num+j] =  factor * sumre;
+                outim[n*num+j] = -factor * sumim;
+            }
+        }
+    }
+}
+
+
Index: branches/Mars_McMismatchStudy/mhft/MHexagonalFT.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonalFT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonalFT.h	(revision 17960)
@@ -0,0 +1,69 @@
+#ifndef MARS_MHexagonalFT
+#define MARS_MHexagonalFT
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef ROOT_MArrayI
+#include "MArrayI.h"
+#endif
+
+class MArrayD;
+class MGeomCam;
+
+class MHexagonalFT : public TObject
+{
+private:
+    
+    int Delta(int i) const
+    {
+        return i==0 || i==(Int_t)fNumRows-1 ? 1 : 0;
+    } // Delta(i) = kronecker(i%(fNumRows-1), 0)
+    float P(int j, int n) const
+    {
+        const Int_t a = Delta(j+n);
+        const Int_t b = Delta(j);
+        const Int_t c = Delta(n);
+
+        return 6./((1+a)*(1+b+c));
+    } // Definition of P(i,j) see paper
+
+    UInt_t fNumRows;
+
+    MArrayF fPsi;
+
+    MArrayI fM;
+    MArrayI fK;
+
+    MArrayF fP;
+
+    MArrayI fIdx;
+
+public:
+    MHexagonalFT();
+    MHexagonalFT(Int_t num);
+
+    void Prepare(Int_t num);
+
+    void TransformFastFWD(const MArrayD &inre, MArrayD &outre, MArrayD &outim) const;
+    void TransformFastBWD(const MArrayD &inre, const MArrayD &inim, MArrayD &outre) const;
+
+    void TransformSlow(const MArrayD &inre, const MArrayD &inim,
+                       MArrayD &outre, MArrayD &outim, Bool_t fwd=kTRUE);
+
+    UInt_t GetNumKnots() const { return fP.GetSize(); } // Return number of knots in triangle
+    UInt_t GetNumRows() const  { return fNumRows; }     // return number of rows in triangle
+
+    UInt_t M(UShort_t i) const { return fM[i]; } // return m-axis-index of absolute index i
+    UInt_t K(UShort_t i) const { return fK[i]; } // return k-axis-index of absolute index i
+
+    Int_t GetRow(UShort_t i) const { return fM[i]+fK[i]; } // return row-index of absolute index i
+    Int_t GetCol(UShort_t i) const { return fM[i]-fK[i]; } // return col-index of absolute index i
+
+    ClassDef(MHexagonalFT,0) // general hexagonal fourier transformation
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mhft/MHexagonalFTCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonalFTCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonalFTCalc.cc	(revision 17960)
@@ -0,0 +1,321 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 11/2004  <mailto:>
+!   Author(s): Thomas Bretz, 11/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHexagonalFTCalc
+//
+// Task to perform forward transformation, cuts in fourier space and
+// backward tranformation.
+//
+// If you don't want to copy the rsult back to any MSignalCam call
+// SetNameSignalCamOut()
+//
+// Currently - this will change in the future! - there are two output
+// containers:
+//  - MHexagonalFreqSpace1
+//      real      part: input values in triangle space
+//      imaginary part: output values in triangle space
+//
+//  - MHexagonalFreqSpace2
+//      real      part: real part of frequency space
+//      imaginary part: imaginary part of frequency space
+//
+// To be done:
+// Flags to perform forward/backward trafo only to be able to cut outside!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHexagonalFTCalc.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MHexagonFreqSpace.h"
+
+#include "MArrayD.h"
+
+ClassImp(MHexagonalFTCalc);
+
+using namespace std;
+
+const char *MHexagonalFTCalc::fgNameGeomCam       = "MGeomCam";
+const char *MHexagonalFTCalc::fgNameSignalCamIn  = "MSignalCam";
+const char *MHexagonalFTCalc::fgNameSignalCamOut = "MSignalCam";
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - empty. Initialize
+//   fMaxAmplitude   = 0.08
+//   fMaxRowFraction = 0.75
+//
+MHexagonalFTCalc::MHexagonalFTCalc(const char *name, const char *title)
+    : fNameGeomCam(fgNameGeomCam),
+    fNameSignalCamIn(fgNameSignalCamIn), fNameSignalCamOut(fgNameSignalCamOut),
+    fEvtIn(0), fEvtOut(0), 
+    fMaxAmplitude(0.08), fMaxRowFraction(0.75), fSkipBwdTrafo(kFALSE)
+{
+    fName  = name  ? name  : "MHexagonalFTCalc";
+    fTitle = title ? title : "Task to calculate Hexagonal Fourier Transformation";
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Search for all necessary containers.
+//
+// Do a forward transformation for a flat camera, eg:
+//
+//    0 0 1 0 0
+//     0 1 1 0
+//      1 1 1
+//       1 1
+//        1
+//
+// The result (fOffset) is treated as a offset in the fourier space comming
+// from the fact that the camera doesn't extend the whole triangle.
+//
+// Before cutting in the fourier space it is substracted. After cutting it
+// is added again. Scaling is done by the constant-frequency-pixel (index 0)
+//
+// Create the LookUpTable which tells you which fourier space (triangle)
+// pixel index corresponds to which camera pixel index.
+//
+Int_t MHexagonalFTCalc::PreProcess(MParList *plist)
+{
+    fEvtIn = (MSignalCam*)plist->FindObject(fNameSignalCamIn, "MSignalCam");
+    if (!fEvtIn)
+    {
+        *fLog << err << fNameSignalCamIn << " [MSignalCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fEvtOut=0;
+    if (!fNameSignalCamOut.IsNull())
+    {
+        fEvtOut = (MSignalCam*)plist->FindCreateObj(fNameSignalCamOut, "MSignalCam");
+        if (!fEvtOut)
+            return kFALSE;
+    }
+
+    fFreq1 = (MHexagonFreqSpace*)plist->FindCreateObj("MHexagonFreqSpace","MHexagonFreqSpace1");
+    if (!fFreq1)
+        return kFALSE;
+    fFreq2 = (MHexagonFreqSpace*)plist->FindCreateObj("MHexagonFreqSpace","MHexagonFreqSpace2");
+    if (!fFreq2)
+        return kFALSE;
+
+    MGeomCam *geom = (MGeomCam*)plist->FindObject(fNameGeomCam, "MGeomCam");
+    if (!geom)
+    {
+        *fLog << err << fNameGeomCam << " [MGeomCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    // Number of Rings (r) ---> Number of Pixels (p)
+    // p = 3*r*(r-1)+1
+
+    // Number of Pixels (p) ---> Number of Rings (r)
+    // p = (sqrt(9+12*(p-1))+3)/6
+
+    // Number of pixels at one border == number of rings (r)
+    // Row of border                  == number of rings (r)
+
+    // Number of rows to get a triangle: 3r-2
+
+    // One additional line on all three sides, number of rows: 3r-2+3 = 3r+1
+    Int_t num = 0;
+    for (UInt_t i=0; i<geom->GetNumPixels(); i++)
+        if ((*geom)[i].GetAidx()==0)
+            num++;
+
+    cout << "Number of pixels with Area Idx==0: " << num << endl;
+
+    const Int_t numrows = (Int_t)((sqrt(9.+12.*(num-1))+3)/2+1); //61;//34;
+    fHFT.Prepare(numrows);
+
+    cout << "Number of rows: " << numrows << endl;
+
+    const Int_t lim = fHFT.GetNumKnots();
+
+    fOffset.Set(lim);
+    fOffset.Reset();
+
+    //fMap.Set(lim);
+    //for (int i=0; i<lim; i++)
+    //    fMap[i]=-1;
+
+    const Double_t dx = (*geom)[2].GetX(); // -(*geom)[0].GetX()
+    const Double_t dy = (*geom)[2].GetY(); // -(*geom)[0].GetY()
+
+    for (int i=0; i<lim; i++)
+    {
+        const Float_t x = dx*fHFT.GetCol(i);
+        const Float_t y = dy*Int_t(fHFT.GetRow(i)-2*fHFT.GetNumRows()/3);
+
+        const Int_t idx = geom->GetPixelIdxXY(x, y);
+        if (idx<0)
+            continue;
+
+        if ((*geom)[idx].GetAidx()==0)
+        {
+            //fMap[idx]  = i;
+            fOffset[i] = 1;
+        }
+    }
+
+    fFreq1->Set(MArrayD(lim), MArrayD(lim));
+    fFreq2->Set(MArrayD(lim), MArrayD(lim));
+
+    // Calculate fourier tranformation of a constant field for all
+    // 'valid' pixels
+    MArrayD freqre;
+    MArrayD freqim;
+    fHFT.TransformFastFWD(fOffset, freqre, freqim);
+    fOffset = freqre;
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Do cuts in frequence space (fOffset already sustracted), eg:
+// fMaxRowFraction = 0.5
+// fMaxAmplitude   = 0.3
+//
+//    0.1  0.2    0.1   0.3   0.4            0    0      0     0     0
+//       0.4   0.3   0.2   0.1                  0     0     0     0
+//          0.6   0.4   0.8      ----->           0.6    0    0.8
+//             0.4   0.9                              0    0.9
+//                 0                                     0
+//
+// The result (fOffset) is treated as a offset in the fourier space comming
+// from the fact that the camera doesn't extend the whole triangle.
+//
+// Before cutting in the fourier space it is substracted. After cutting it
+// is added again. Scaling is done by the constant-frequency-pixel (index 0)
+//
+void MHexagonalFTCalc::CleanFreqSpace(MArrayD &outre, MArrayD &outim)
+{
+    // Do cut in frequency space
+    for (unsigned int i=0; i<outre.GetSize(); i++)
+    {
+        if (fHFT.GetRow(i)>(Int_t)fHFT.GetNumRows()*fMaxRowFraction)
+            outre[i]=outim[i]=0;
+        if (TMath::Hypot(outre[i], outim[i])<fMaxAmplitude)
+            outre[i]=outim[i]=0;
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// - Copy input MSignalCam using the pixel mapping into an array
+// - Do forward transformation
+// - substract fourier offset
+// - perform cuts in fourier space
+// - add fourier offset
+// - do backward tranformation
+// - copy result back into output MSignalCam
+//
+Int_t MHexagonalFTCalc::Process()
+{
+    const Int_t lim = fHFT.GetNumKnots();
+
+    MArrayD re(lim);
+
+    //    MSignalPix *pix=0;
+    //    MSignalCamIter Next(fEvtIn, kFALSE);
+    //    while ((pix = (MSignalPix*)Next()))
+    // Copy data from MSignalCam into array
+    const UInt_t npix = fEvtIn->GetNumPixels();
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        //const Int_t idx = pix->GetPixId();
+        //if (fMap[idx]>=0)
+        re[idx] = (*fEvtIn)[idx].GetNumPhotons();
+    }
+
+    MArrayD freqre, freqim;
+
+    // Do forward transformation
+    fHFT.TransformFastFWD(re, freqre, freqim);
+
+    // Substract the 'structure of the hexagon'
+    Double_t scale = TMath::Abs(freqre[0]/fOffset[0]);
+    for (int i=0; i<lim; i++)
+        freqre[i] -= scale*fOffset[i];
+
+    // Put result in output container
+    fFreq2->Set(freqre, freqim);
+
+    // ----------------------------------------------------
+    // Do we need a backward transformation?
+    // ----------------------------------------------------
+    if (fSkipBwdTrafo)
+        return kTRUE;
+
+    // Clean image in frequency space
+    CleanFreqSpace(freqre, freqim);
+
+    // Add the 'structure of the hexagon'
+    for (int i=0; i<lim; i++)
+        freqre[i] += scale*fOffset[i];
+
+
+    MArrayD out;
+
+    // Do backward transformation
+    fHFT.TransformFastBWD(freqre, freqim, out);
+
+    // Write output into Mars container
+    fFreq1->Set(re, out);
+
+    // ----------------------------------------------------
+    // Do we have to copy the result back into MSignalCam?
+    // ----------------------------------------------------
+    if (!fEvtOut)
+        return kTRUE;
+
+    fEvtOut->InitSize(lim); // necessary?
+    for (int i=0; i<lim; i++)
+    {
+        //const Int_t map = fMap[i];
+        //if (map>=0)
+        fEvtOut->AddPixel(i, out[i]);
+    }
+    //fEvtOut->FixSize();
+    fEvtOut->SetReadyToSave();
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mhft/MHexagonalFTCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mhft/MHexagonalFTCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/MHexagonalFTCalc.h	(revision 17960)
@@ -0,0 +1,67 @@
+#ifndef MARS_MHexagonalFTCalc
+#define MARS_MHexagonalFTCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MHexagonalFT
+#include "MHexagonalFT.h"
+#endif
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MArrayD;
+class MSignalCam;
+class MHexagonFreqSpace;
+
+class MHexagonalFTCalc : public MTask
+{
+private:
+    static const char *fgNameGeomCam;       // Default name of used geometry
+    static const char *fgNameSignalCamIn;  // Default name of used input MSignalCam
+    static const char *fgNameSignalCamOut; // Default name of used output MSignalCam
+
+    TString fNameGeomCam;       // name of used geometry
+    TString fNameSignalCamIn;  // name of used input MSignalCam
+    TString fNameSignalCamOut; // name of used output MSignalCam
+
+    MSignalCam       *fEvtIn;  // input MSignalCam
+    MSignalCam       *fEvtOut; // output MSignalCam
+
+    MHexagonFreqSpace *fFreq1;  //!
+    MHexagonFreqSpace *fFreq2;  //!
+
+    Float_t fMaxAmplitude;      // Maximum amplitude to cut
+    Float_t fMaxRowFraction;    // Maximum fraction of rows (frequency space) to remove
+
+    Bool_t fSkipBwdTrafo;       // flag whether backward trafo should be done
+
+    MHexagonalFT       fHFT;    // Fourier transformation
+
+    MArrayI fMap;    //! Pixel mapping between space space and frequency space
+    MArrayD fOffset; //! Fourier transformation of a constant 1 for all 'valid' pixels
+
+    Int_t PreProcess(MParList *p);
+    Int_t Process();
+
+    void CleanFreqSpace(MArrayD &re, MArrayD &im);
+
+public:
+    MHexagonalFTCalc(const char *name=0, const char *title=0);
+
+    void SetSkipBwdTrafo(Bool_t b=kTRUE) { fSkipBwdTrafo=b; } // Don't do a backward transoformation
+
+    const MHexagonalFT &GetHFT() const { return fHFT; }       // return the MHexagonalFT object used
+
+    void SetNameGeomCam(const char *n) { fNameGeomCam = n; }       // name of camera geometry used 
+    void SetNameSignalCamIn(const char *n)     { fNameSignalCamIn = n; }  // name of input MSignalCam used
+    void SetNameSignalCamOut(const char *n="") { fNameSignalCamOut = n; } // name of ouput MSignalCam used
+
+    void SetMaxAmplitude(Float_t max) { fMaxAmplitude=max; } // amplitude to cut at
+    void SetMaxRowFraction(Float_t max) { fMaxRowFraction=max; } // row (frequency) to cut at
+
+    ClassDef(MHexagonalFTCalc,0)//Task to calculate Hexagonal Fourier Transformation
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mhft/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mhft/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhft/Makefile	(revision 17960)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Hft
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../msignal
+
+#manalysis: MChisqEval (MParameters)
+
+SRCFILES = MHexagonalFT.cc \
+           MHexagonalFTCalc.cc \
+   	   MHexagonFreqSpace.cc \
+           MGeomCamMagicXT.cc \
+           MGeomCamMagicEnhance.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mhist/HistIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/HistIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/HistIncl.h	(revision 17960)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mhist/HistLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/HistLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/HistLinkDef.h	(revision 17960)
@@ -0,0 +1,25 @@
+#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 MHCamEventRot+;
+#pragma link C++ class MHTriggerLvl0+;
+
+#pragma link C++ class MHStarMap+;
+
+//#pragma link C++ class MHCompProb+;
+#pragma link C++ class MHHadronness+;    
+
+#pragma link C++ class MHCamera+;
+
+#pragma link C++ class MHRate+;
+#pragma link C++ class MHWeather+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mhist/MHCamEvent.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCamEvent.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCamEvent.cc	(revision 17960)
@@ -0,0 +1,472 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHCamEvent
+//
+// A histogram to store the sum of camera events. This can be photons,
+// currents or enything else derived from MCamEvent
+//
+// Setup
+// =====
+//
+// To count how often a certain pixel is above or below a threshold do:
+//    MHCamEvent::SetThreshold(5.5);  // Default=LowerBound
+//    MHCamEvent::SetThreshold(5.5, MHCamEvent::kIsUpperBound);
+//
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given 'a.u.' is used.
+// 2) If the title of MHCamEvent is different from the default,
+//    it is used as histogram title. You can use this to set the
+//    axis title, too. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyHist;;y[cm];Counts");
+//    Make sure to set an empty x-axis title.
+//
+// For example:
+//   MHCamEvent myhist("Titele;;y [cm]");
+//
+// Class Version 3:
+// ----------------
+//  + fNameSub
+//  + fIsRatio
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCamEvent.h"
+
+#include <TF1.h>
+#include <TPaveStats.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+#include "MParList.h"
+#include "MCamEvent.h"
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MHCamEvent);
+
+using namespace std;
+
+const TString MHCamEvent::gsDefName  = "MHCamEvent";
+const TString MHCamEvent::gsDefTitle = "Average of MCamEvents";
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task
+//
+void MHCamEvent::Init(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fNameGeom = "MGeomCam";
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task. Set fType to 0
+//
+MHCamEvent::MHCamEvent(const char *name, const char *title)
+: fSum(NULL), fErr(NULL), fEvt(NULL), fSub(0), fType(0), fErrorSpread(kTRUE), fErrorRelative(kFALSE),
+fThreshold(0), fUseThreshold(0), fIsRatio(false)
+{
+    Init(name, title);
+
+    fSum = new MHCamera;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task. Set fType to type
+//
+MHCamEvent::MHCamEvent(Int_t type, const char *name, const char *title)
+: fSum(NULL), fErr(NULL), fEvt(NULL), fSub(0), fType(type), fErrorSpread(kTRUE), fErrorRelative(kFALSE),
+fThreshold(0), fUseThreshold(0), fIsRatio(false)
+{
+    Init(name, title);
+
+    fSum = new MHCamera;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHCamEvent::~MHCamEvent()
+{
+    if (fSum)
+        delete fSum;
+}
+
+Bool_t MHCamEvent::InitGeom(const MParList &plist)
+{
+    MGeomCam *cam = (MGeomCam*)plist.FindObject(fNameGeom, "MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << fNameGeom << " [MGeomCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    // combine name
+    const TString name = fNameEvt.IsNull() ? fName : fNameEvt;
+
+    fSum->SetGeometry(*cam, name+";avg");
+    if (fTitle!=gsDefTitle)
+        fSum->SetTitle(fTitle);
+    if (!fTitle.Contains(";"))
+        fSum->SetYTitle("a.u.");
+
+    if (fErr)
+        fErr->SetGeometry(*fSum->GetGeometry(), fErr->GetName(), fErr->GetTitle());
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 = dynamic_cast<MCamEvent*>(plist->FindObject(fNameEvt, "MCamEvent"));
+    if (!fEvt)
+    {
+        if (!fNameEvt.IsNull())
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameEvt <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << inf << GetDescriptor() << ": Assuming to get MCamEvent from Fill()..." << endl;
+    }
+
+    fSub = 0;
+    if (!fNameSub.IsNull())
+    {
+        fSub = dynamic_cast<MCamEvent*>(plist->FindObject(fNameSub, "MCamEvent"));
+        if (!fSub)
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameSub <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << inf << GetDescriptor() << ": Will subtract '" << fNameSub << "'" << endl;
+    }
+
+    fSum->Reset();
+
+    fNumReInit = 0;
+
+    if (!InitGeom(*plist))
+        return kFALSE;
+
+    if (fUseThreshold!=kCollectMin && fUseThreshold!=kCollectMax)
+        fSum->SetBit(MHCamera::kProfile);
+    if (!fErrorSpread)
+        fSum->SetBit(MHCamera::kErrorMean);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The geometry read from the RunHeaders might have changed. This does not
+// effect anything in PreProcess. So we set a new geometry. We don't move
+// this away from PreProcess to support also loops without calling ReInit.
+//
+Bool_t MHCamEvent::ReInit(MParList *plist)
+{
+    return fNumReInit++==0 ? InitGeom(*plist) : kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCamEvent-Container.
+//
+Int_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 kERROR;
+    }
+
+    switch (fUseThreshold)
+    {
+    case kNoBound:
+        if (fSub)
+        {
+            if (fIsRatio)
+                fSum->AddCamRatio(*evt, *fSub, fType, w);
+            else
+                fSum->AddCamDifference(*evt, *fSub, fType, w);
+        }
+        else
+            fSum->AddCamContent(*evt, fType, w);
+        break;
+
+    case kIsLowerBound:
+    case kIsUpperBound:
+        fSum->CntCamContent(*evt, fThreshold, fType, fUseThreshold>0);
+        break;
+
+    case kCollectMin:
+        fSum->SetMinCamContent(*evt, /*fThreshold,*/ fType);
+        break;
+
+    case kCollectMax:
+        fSum->SetMaxCamContent(*evt, /*fThreshold,*/ fType);
+        break;
+
+    case kMeanShift:
+        fSum->AddMeanShift(*evt, fType, w);
+        break;
+
+    case kMedianShift:
+        fSum->AddMedianShift(*evt, fType, w);
+        break;
+
+    default:
+        *fLog << err << "ERROR - MHCamEvent::Fill: Unknown type." << endl;
+        return kERROR;
+    }
+
+    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) const
+{
+    return fSum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the camera histogram to a clone of cam
+//
+void MHCamEvent::SetHist(const MHCamera &cam)
+{
+    if (fSum)
+        delete fSum;
+
+    fSum = static_cast<MHCamera*>(cam.Clone());
+}
+
+TString MHCamEvent::Format(const char *ext) const
+{
+    TString n = fSum->GetName();
+
+    const Ssiz_t pos = n.Last(';');
+    if (pos<0)
+        return "";
+
+    n  = n(0, pos);
+    n += ";";
+    n += ext;
+    return n;
+}
+
+void MHCamEvent::Paint(Option_t *opt)
+{
+    TVirtualPad *pad = gPad;
+
+    pad->cd(2);
+    if (gPad->FindObject("proj"))
+    {
+        TH1 *h=fSum->Projection("proj");
+        if (h->GetMaximum()>0)
+            gPad->SetLogy();
+
+        if (TString(opt).Contains("gaus", TString::kIgnoreCase))
+        {
+            // Create a copy of the function if it is not yet there
+            if (!h->GetFunction("gaus"))
+                h->Fit("gaus", "q");
+
+            TF1 *f = h->GetFunction("gaus");
+            if (f)
+            {
+                f->SetParameters(h->GetMean(), h->GetRMS(), h->GetMaximum());
+                f->SetLineWidth(1);
+                h->Fit("gaus", "q");
+            }
+
+            TPaveStats *s1 = dynamic_cast<TPaveStats*>(h->GetListOfFunctions()->FindObject("stats"));
+            if (s1)
+            {
+                if (s1->GetOptStat()==1111)
+                    s1->SetOptStat(1000000001);
+                s1->SetOptFit(1);
+            }
+        }
+    }
+
+    pad->cd(5);
+    if (gPad->FindObject("rad"))
+        fSum->RadialProfile("rad");
+
+    pad->cd(6);
+    if (gPad->FindObject("az"))
+        fSum->AzimuthProfile("az");
+
+    pad->cd(4);
+    gPad->cd(1);
+    MHCamera *cam = (MHCamera*)gPad->FindObject("err");
+    if (cam)
+        cam->SetCamContent(*fSum, fErrorRelative ? 2 : 1);
+}
+
+void MHCamEvent::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    const Int_t col = pad->GetFillColor();
+    pad->SetBorderMode(0);
+
+    AppendPad(opt);
+
+    TString name = MString::Format("%s_1", pad->GetName());
+    TPad *p = new TPad(name,name,0.005, 0.5, 0.66, 0.995,col,0,0);
+    p->SetFrameBorderMode(0);
+    p->SetNumber(1);
+    p->Draw();
+    p->cd();
+    fSum->Draw("EPhist");
+
+    pad->cd();
+    name = MString::Format("%s_2", pad->GetName());
+    p = new TPad(name,name,0.66, 0.5, 0.995, 0.995,col,0,0);
+    p->SetFrameBorderMode(0);
+    p->SetNumber(2);
+    p->Draw();
+    p->cd();
+    TH1 *h = fSum->Projection("proj", 50);
+    h->SetTitle("Projection");
+    h->SetBit(kCanDelete);
+    h->Draw();
+
+    pad->cd();
+    name = MString::Format("%s_3", pad->GetName());
+    p = new TPad(name,name,0.005, 0.005, 3./8, 0.5,col,0,0);
+    p->SetFrameBorderMode(0);
+    p->SetNumber(3);
+    p->Draw();
+    p->cd();
+    fSum->Draw();
+
+    pad->cd();
+    name = MString::Format("%s_4", pad->GetName());
+    p = new TPad(name,name,3./8, 0.005, 6./8-0.005, 0.5,col,0,0);
+    p->SetFrameBorderMode(0);
+    p->SetNumber(4);
+    p->Draw();
+    p->cd();
+
+    TString e = "Sqrt(Variance)";
+    if (fSum->TestBit(MHCamera::kErrorMean))
+        e += "/Sqrt(n_{i})";
+    if (fErrorRelative)
+        e += "/v_{i}";
+
+    fErr = new MHCamera(*fSum->GetGeometry());
+    fErr->SetName("err");
+    fErr->SetTitle(e);
+    fErr->SetYTitle(fSum->GetYaxis()->GetTitle());
+    fErr->SetCamContent(*fSum, fErrorRelative ? 2 : 1);
+    fErr->SetBit(kMustCleanup);
+    fErr->SetBit(kCanDelete);
+    fErr->Draw();
+
+    pad->cd();
+    name = MString::Format("%s_5", pad->GetName());
+    p = new TPad(name,name,6./8,0.25,0.995,0.5,col,0,0);
+    p->SetFrameBorderMode(0);
+    p->SetNumber(5);
+    p->Draw();
+    p->cd();
+    h = (TH1*)fSum->RadialProfile("rad", 20);
+    h->SetTitle("Radial Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+
+    pad->cd();
+    name = MString::Format("%s_6", pad->GetName());
+    p = new TPad(name,name,6./8,0.005,0.995,0.25,col,0,0);
+    p->SetFrameBorderMode(0);
+    p->SetNumber(6);
+    p->Draw();
+    p->cd();
+    h = (TH1*)fSum->AzimuthProfile("az", 30);
+    h->SetTitle("Azimuth Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+}
+
+
+void MHCamEvent::RecursiveRemove(TObject *obj)
+{
+    if (obj==fErr)
+        fErr = 0;
+    if (obj==fSum)
+        fSum = 0;
+
+    MH::RecursiveRemove(obj);
+}
Index: branches/Mars_McMismatchStudy/mhist/MHCamEvent.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCamEvent.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCamEvent.h	(revision 17960)
@@ -0,0 +1,83 @@
+#ifndef MARS_MHCamEvent
+#define MARS_MHCamEvent
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHCamera;
+class MCamEvent;
+
+class MHCamEvent : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+protected:
+    MHCamera  *fSum;       // storing the sum
+    MHCamera  *fErr;       //! storing the err
+    MCamEvent *fEvt;       //! the current event
+    MCamEvent *fSub;       //! the event to be subtracted
+
+    TString fNameEvt;      // Name of MCamEvent to fill into histogram
+    TString fNameSub;      // Name of MCamEvent to fill into histogram
+    TString fNameGeom;     // Name of geometry container
+
+    Int_t fType;           // Type to used for calling GetPixelContent
+    Bool_t fErrorSpread;   // kFALSE==mean, kTRUE==spread
+    Bool_t fErrorRelative; // Display relative error?
+
+    Float_t fThreshold;    // Count pixel above/below this threshold
+    Char_t fUseThreshold;  // Use a threshold? Which direction has it?
+
+    Bool_t fIsRatio;       // If NameSub is set: Use Ratio or difference
+
+    Int_t fNumReInit;      //!
+
+    TString Format(const char *ext) const;
+
+    void   Init(const char *name, const char *title);
+    Bool_t InitGeom(const MParList &plist);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+public:
+    enum { kIsLowerBound=1, kIsUpperBound=-1, kNoBound=0, kCollectMin=-2, kCollectMax=2, kMedianShift=3, kMeanShift=4 };
+
+    MHCamEvent(const char *name=NULL, const char *title=NULL);
+    MHCamEvent(Int_t type, const char *name=NULL, const char *title=NULL);
+    ~MHCamEvent();
+
+    void SetNameEvt(const TString name)  { fNameEvt = name; }
+    void SetNameSub(const TString name, Bool_t ratio=kFALSE)  { fNameSub = name; fIsRatio = ratio;  }
+    void SetNameGeom(const TString name) { fNameGeom = name; }
+    void SetType(Int_t type) { fType = type; }
+
+    void SetHist(const MHCamera &cam);
+    MHCamera *GetHist() { return fSum; }
+    const MHCamera *GetHist() const { return fSum; }
+
+    TH1 *GetHistByName(const TString name="") const;
+
+    void Paint(Option_t *o="");
+    void Draw(Option_t *o="");  //*MENU*
+
+    void PrintOutliers(Float_t s) const;
+
+    void SetThreshold(Float_t f=0, Char_t direction=kIsLowerBound) { fThreshold = f; fUseThreshold=direction; }
+    void SetCollectMin() { fUseThreshold=kCollectMin; }
+    void SetCollectMax() { fUseThreshold=kCollectMax; }
+    void SetMedianShift() { fUseThreshold=kMedianShift; }
+    void SetMeanShift() { fUseThreshold=kMeanShift; }
+    void SetErrorSpread(Bool_t b=kTRUE) { fErrorSpread = b; }
+    void SetErrorRelative(Bool_t b=kTRUE) { fErrorRelative = b; }
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MHCamEvent, 3) // Histogram to sum camera events
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhist/MHCamEventRot.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCamEventRot.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCamEventRot.cc	(revision 17960)
@@ -0,0 +1,278 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHCamEventRot
+//
+// Derotate MCamEvent before filling a 2D histogram.
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given 'a.u.' or 'counts'is used.
+// 2) If the corresponding MBinning has no default title. This title
+//    is used for the z-axis
+// 3) If the title of MHCamEvent is different from the default,
+//    it is used as histogram title. You can use this to set the
+//    axis title, too. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyHist;;;z[photons]");
+//    The x- and y-axis title is ignored.
+//
+// For example:
+//   MHCamEventRot myhist("Title;;;z[photons]");
+//
+//
+// To be done: * Set the sky position of the center of the display and
+//               correct if the pointing position of the telescope is
+//               different.
+//             * Make it quadratic like MHCamera
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCamEventRot.h"
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TMath.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TPaveText.h>
+#include <TStopwatch.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillasSrc.h"
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MAstroCatalog.h"
+#include "MAstroSky2Local.h"
+#include "MStatusDisplay.h"
+#include "MMath.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+#include "MCamEvent.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCamEventRot);
+
+using namespace std;
+
+const TString MHCamEventRot::gsDefName  = "MHCamEventRot";
+const TString MHCamEventRot::gsDefTitle = "Plot showing derotated MCamEvent data";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHCamEventRot::MHCamEventRot(const char *name, const char *title)
+    : fTime(0), fPointPos(0), fObservatory(0), fType(0), fNameTime("MTime"),
+    fThreshold(0), fUseThreshold(kNoBound)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetName("Derot");
+    fHist.SetTitle("2D-plot of MCamEvents (derotated)");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningCamEvent) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+// 
+Bool_t MHCamEventRot::SetupFill(const MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningCamEvent");
+    if (!bins)
+    {
+        const Float_t r = fGeom->GetMaxRadius()*fGeom->GetConvMm2Deg();
+
+        const MBinning b(41, -r, r);
+        SetBinning(fHist, b, b);
+    }
+    else
+        SetBinning(fHist, *bins, *bins);
+
+    fPointPos = (MPointingPos*)plist->FindObject(AddSerialNumber("MPointingPos"));
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... no derotation." << endl;
+
+    fTime = (MTime*)plist->FindObject(AddSerialNumber(fNameTime));
+    if (!fTime)
+        *fLog << warn << "MTime not found... no derotation." << endl;
+
+    fObservatory = (MObservatory*)plist->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+        *fLog << warn << "MObservatory not found... no derotation." << endl;
+
+    // FIXME: Because the pointing position could change we must check
+    // for the current pointing position and add a offset in the
+    // Fill function!
+    if (fPointPos)
+    {
+        fRa  = fPointPos->GetRa();
+        fDec = fPointPos->GetDec();
+    }
+
+    if (bins && bins->HasTitle())
+        fHist.SetZTitle(bins->GetTitle());
+    else
+        if (fTitle!=gsDefTitle)
+        {
+            fHist.SetTitle(fTitle);
+            fHist.SetXTitle("x [\\circ]");
+            fHist.SetYTitle("y [\\circ]");
+        }
+        else
+            if (!fTitle.Contains(";"))
+                fHist.SetZTitle(fUseThreshold==kNoBound?"a.u.":"Counts");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Int_t MHCamEventRot::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCamEvent *evt = dynamic_cast<const MCamEvent*>(par);
+    if (!evt)
+    {
+        *fLog << err << "MHCamEventRot::Fill: No container specified!" << endl;
+        return kERROR;
+    }
+
+    // Get max radius...
+    // const Double_t maxr = fGeom->GetMaxRadius()*fGeom->GetConvMm2Deg();
+
+    // Get camera rotation angle
+    Double_t rho = 0;
+    if (fTime && fObservatory && fPointPos)
+        rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+    //if (fPointPos)
+    //    rho = fPointPos->RotationAngle(*fObservatory);
+
+    // Get number of bins and bin-centers
+    const Int_t nx = fHist.GetNbinsX();
+    const Int_t ny = fHist.GetNbinsY();
+    Axis_t cx[nx];
+    Axis_t cy[ny];
+    fHist.GetXaxis()->GetCenter(cx);
+    fHist.GetYaxis()->GetCenter(cy);
+
+    for (int ix=0; ix<nx; ix++)
+    {
+        for (int iy=0; iy<ny; iy++)
+        {
+            // check distance... to get a circle plot
+            //if (TMath::Hypot(cx[ix], cy[iy])>maxr)
+            //    continue;
+
+            // rotate center of bin
+            TVector2 v(cx[ix], cy[iy]);
+            if (rho!=0)
+                v=v.Rotate(rho);
+
+            // FIXME: slow! Create Lookup table instead!
+            const Int_t idx = fGeom->GetPixelIdxDeg(v);
+
+            Double_t val;
+            if (idx<0 || !evt->GetPixelContent(val, idx, *fGeom, fType))
+                continue;
+
+            // Fill histogram
+            if (fUseThreshold!=kNoBound)
+            {
+                if ((val>fThreshold && fUseThreshold==kIsLowerBound) ||
+                    (val<fThreshold && fUseThreshold==kIsUpperBound))
+                    fHist.Fill(cx[ix], cy[iy]);
+            }
+            else
+                fHist.Fill(cx[ix], cy[iy], val);
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the MAstroCatalog corresponding to fRa, fDec. The limiting magnitude
+// is set to 9, while the fov is equal to the current fov of the false
+// source plot.
+//
+TObject *MHCamEventRot::GetCatalog()
+{
+    const Double_t maxr = 0.98*TMath::Abs(fHist.GetBinCenter(1));
+
+    // Create catalog...
+    MAstroCatalog stars;
+    stars.SetLimMag(9);
+    stars.SetGuiActive(kFALSE);
+    stars.SetRadiusFOV(maxr);
+    stars.SetRaDec(fRa*TMath::DegToRad()*15, fDec*TMath::DegToRad());
+    stars.ReadBSC("bsc5.dat");
+
+    TObject *o = (MAstroCatalog*)stars.Clone();
+    o->SetBit(kCanDelete);
+
+    return o;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHCamEventRot::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    // draw the 2D histogram Sigmabar versus Theta
+    fHist.Draw(opt);
+    TObject *catalog = GetCatalog();
+    catalog->Draw("mirror same");
+}
Index: branches/Mars_McMismatchStudy/mhist/MHCamEventRot.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCamEventRot.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCamEventRot.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MHCamEventRot
+#define MARS_MHCamEventRot
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class TH2D;
+
+class MGeomCam;
+class MParList;
+class MTime;
+class MPointingPos;
+class MObservatory;
+
+class MHCamEventRot : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    MGeomCam      *fGeom;        //! container storing the camera geometry
+    MTime         *fTime;        //! container to take the event time from
+    MPointingPos  *fPointPos;    //! container to take pointing position from
+    MObservatory  *fObservatory; //! conteiner to take observatory location from
+
+    TH2D    fHist;               // Alpha vs. x and y
+
+    Int_t fType;                 // Type to used for calling GetPixelContent
+
+    Double_t fRa;
+    Double_t fDec;
+
+    TString fNameTime;
+
+    Float_t fThreshold;          // Count pixel above/below this threshold
+    Char_t fUseThreshold;        // Use a threshold? Which direction has it?
+
+    TObject *GetCatalog();
+
+public:
+    enum { kIsLowerBound=1, kIsUpperBound=-1, kNoBound=0 };
+
+    MHCamEventRot(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name) const { return const_cast<TH2D*>(&fHist); }
+
+    void SetNameTime(const char *name) { fNameTime=name; }
+
+    void Draw(Option_t *option="");
+
+    void SetThreshold(Float_t f, Char_t direction=kIsLowerBound) { fThreshold = f; fUseThreshold=direction; }
+
+    ClassDef(MHCamEventRot, 1) //2D-histogram in MCamEvent data (derotated)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhist/MHCamera.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCamera.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCamera.cc	(revision 17960)
@@ -0,0 +1,2549 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHCamera
+//
+// Camera Display, based on a TH1D. Pleas be carefull using the
+// underlaying TH1D.
+//
+// To change the scale to a logarithmic scale SetLogy() of the Pad.
+//
+// You can correct for the abberation. Assuming that the distance
+// between the mean position of the light distribution and the position
+// of a perfect reflection on a perfect mirror in the distance r on
+// the camera plane is dr it is  d = a*dr  while a is the abberation
+// constant (for the MAGIC mirror it is roughly 0.0713). You can
+// set this constant by calling SetAbberation(a) which results in a
+// 'corrected' display (all outer pixels are shifted towards the center
+// of the camera to correct for this abberation)
+//
+// Be carefull: Entries in this context means Entries/bin or Events
+//
+// FIXME? Maybe MHCamera can take the fLog object from MGeomCam?
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHCamera.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TBox.h>
+#include <TArrow.h>
+#include <TLatex.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TArrayF.h>
+#include <TRandom.h>
+#include <TPaveText.h>
+#include <TPaveStats.h>
+#include <TClonesArray.h>
+#include <THistPainter.h>
+#include <THLimitsFinder.h>
+#include <TProfile.h>
+#include <TH1.h>
+#include <TF1.h>
+#include <TCanvas.h>
+#include <TLegend.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MH.h"
+#include "MString.h"
+#include "MBinning.h"
+
+#include "MGeom.h"
+#include "MGeomCam.h"
+
+#include "MCamEvent.h"
+
+#include "MArrayD.h"
+#include "MMath.h"    // MMath::GaussProb
+
+ClassImp(MHCamera);
+
+using namespace std;
+
+void MHCamera::Init()
+{
+    Sumw2();
+
+    UseCurrentStyle();
+
+    SetDirectory(NULL);
+
+    SetLineColor(kGreen);
+    SetMarkerStyle(kFullDotMedium);
+    SetXTitle("Pixel Index");
+
+    fNotify  = new TList;
+    fNotify->SetBit(kMustCleanup);
+    gROOT->GetListOfCleanups()->Add(fNotify);
+
+    /*
+    TVirtualPad *save = gPad;
+    gPad = 0;
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,01,06)
+    SetPalette(1, 0);
+#endif
+    */
+/*
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,04,00)
+    SetPrettyPalette();
+#elese
+    // WORAROUND - FIXME: Calling it many times becomes slower and slower
+    SetInvDeepBlueSeaPalette();
+#endif
+    gPad = save;
+*/
+}
+
+// ------------------------------------------------------------------------
+//
+//  Default Constructor. To be used by the root system ONLY.
+//
+MHCamera::MHCamera() : TH1D(), fGeomCam(NULL), fAbberation(0)
+{
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+//  Constructor. Makes a clone of MGeomCam. Removed the TH1D from the
+// current directory. Calls Sumw2(). Set the histogram line color
+// (for error bars) to Green and the marker style to kFullDotMedium.
+//
+MHCamera::MHCamera(const MGeomCam &geom, const char *name, const char *title)
+: fGeomCam(NULL), fAbberation(0)
+{
+    //fGeomCam = (MGeomCam*)geom.Clone();
+    SetGeometry(geom, name, title);
+    Init();
+
+    //
+    // root 3.02
+    //  * base/inc/TObject.h:
+    //    register BIT(8) as kNoContextMenu. If an object has this bit set it will
+    //    not get an automatic context menu when clicked with the right mouse button.
+}
+
+// ------------------------------------------------------------------------
+//
+// Clone the MHCamera via TH1D::Clone and make sure that the new object is
+// not removed from the current directory.
+//
+TObject *MHCamera::Clone(const char *newname) const
+{
+    MHCamera *rc = static_cast<MHCamera*>(TH1D::Clone(newname));
+    rc->SetDirectory(NULL);
+
+    // fGeomCam need special treatment due to its TObjArray
+    if (rc->fGeomCam && fGeomCam)
+    {
+        delete rc->fGeomCam;
+        rc->fGeomCam = static_cast<MGeomCam*>(fGeomCam->Clone());
+    }
+
+    return rc;
+}
+
+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();
+
+    if (fGeomCam)
+        delete fGeomCam;
+    fGeomCam = (MGeomCam*)geom.Clone();
+
+    fUsed.Set(geom.GetNumPixels());
+    fUsed.Reset();
+
+    fBinEntries.Set(geom.GetNumPixels()+2);
+    fBinEntries.Reset();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes the cloned fGeomCam and the notification list.
+//
+MHCamera::~MHCamera()
+{
+    if (fGeomCam)
+      delete fGeomCam;
+    if (fNotify)
+      delete fNotify;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return kTRUE for sector<0. Otherwise return kTRUE only if the specified
+// sector idx matches the sector of the pixel with index idx.
+//
+Bool_t MHCamera::MatchSector(Int_t idx, const TArrayI &sector, const TArrayI &aidx) const
+{
+    const MGeom &pix = (*fGeomCam)[idx];
+    return FindVal(sector, pix.GetSector()) && FindVal(aidx, pix.GetAidx());
+}
+
+// ------------------------------------------------------------------------
+//
+// Taken from TH1D::Fill(). Uses the argument directly as bin index.
+// Doesn't increment the number of entries.
+//
+//   -*-*-*-*-*-*-*-*Increment bin with abscissa X by 1*-*-*-*-*-*-*-*-*-*-*
+//                   ==================================
+//
+//    if x is less than the low-edge of the first bin, the Underflow bin is incremented
+//    if x is greater than the upper edge of last bin, the Overflow bin is incremented
+//
+//    If the storage of the sum of squares of weights has been triggered,
+//    via the function Sumw2, then the sum of the squares of weights is incremented
+//    by 1 in the bin corresponding to x.
+//
+//   -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
+Int_t MHCamera::Fill(Axis_t x)
+{
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,05,00)
+   if (fBuffer) return BufferFill(x,1);
+#endif
+   const Int_t bin = (Int_t)x+1;
+   AddBinContent(bin);
+   fBinEntries[bin]++;
+   if (fSumw2.fN)
+       fSumw2.fArray[bin]++;
+
+   if (bin<=0 || bin>fNcells-2)
+       return -1;
+
+   fTsumw++;
+   fTsumw2++;
+   fTsumwx  += x;
+   fTsumwx2 += x*x;
+   return bin;
+}
+
+// ------------------------------------------------------------------------
+//
+// Taken from TH1D::Fill(). Uses the argument directly as bin index.
+// Doesn't increment the number of entries.
+//
+//   -*-*-*-*-*-*Increment bin with abscissa X with a weight w*-*-*-*-*-*-*-*
+//               =============================================
+//
+//    if x is less than the low-edge of the first bin, the Underflow bin is incremented
+//    if x is greater than the upper edge of last bin, the Overflow bin is incremented
+//
+//    If the storage of the sum of squares of weights has been triggered,
+//    via the function Sumw2, then the sum of the squares of weights is incremented
+//    by w^2 in the bin corresponding to x.
+//
+//   -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
+Int_t MHCamera::Fill(Axis_t x, Stat_t w)
+{
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,05,00)
+   if (fBuffer) return BufferFill(x,w);
+#endif
+   const Int_t bin = (Int_t)x+1;
+   AddBinContent(bin, w);
+   fBinEntries[bin]++;
+   if (fSumw2.fN)
+       fSumw2.fArray[bin] += w*w;
+
+   if (bin<=0 || bin>fNcells-2)
+       return -1;
+
+   const Stat_t z = (w > 0 ? w : -w);
+   fTsumw   += z;
+   fTsumw2  += z*z;
+   fTsumwx  += z*x;
+   fTsumwx2 += z*x*x;
+   return bin;
+}
+
+// ------------------------------------------------------------------------
+//
+// Use x and y in millimeters
+//
+Int_t MHCamera::Fill(Axis_t x, Axis_t y, Stat_t w)
+{
+    if (fNcells<=1 || IsFreezed())
+        return -1;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        if (!(*fGeomCam)[idx].IsInside(x, y))
+            continue;
+
+        SetUsed(idx);
+        return Fill(idx, w);
+    }
+    return -1;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this if you want to change the display status (displayed or not)
+// for all pixels. val==0 means that the pixel is not displayed.
+//
+void MHCamera::SetUsed(const TArrayC &arr)
+{
+    if (fNcells-2 != arr.GetSize())
+    {
+        gLog << warn << "WARNING - MHCamera::SetUsed: array size mismatch... ignored." << endl;
+        return;
+    }
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        arr[idx] ? SetUsed(idx) : ResetUsed(idx);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the mean value of all entries which are used if all=kFALSE and
+// of all entries if all=kTRUE if sector<0. If sector>=0 only
+// entries with match the given sector are taken into account.
+//
+Stat_t MHCamera::GetMeanSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t ball) const
+{
+    if (fNcells<=1)
+        return 0;
+
+    Int_t n=0;
+
+    Stat_t mean = 0;
+    for (int i=0; i<fNcells-2; i++)
+    {
+        if ((ball || IsUsed(i)) && MatchSector(i, sector, aidx))
+        {
+            if (TestBit(kProfile) && fBinEntries[i+1]==0)
+                continue;
+
+            mean += TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+            n++;
+        }
+    }
+
+    return n==0 ? 0 : mean/n;
+}
+
+UInt_t MHCamera::GetNumUsedSector(const TArrayI &sector, const TArrayI &aidx) const
+{
+    if (fNcells<=1)
+        return 0;
+
+    Int_t n=0;
+ 
+    for (int i=0; i<fNcells-2; i++)
+    {
+        if (!IsUsed(i) || !MatchSector(i, sector, aidx))
+            continue;
+
+        if (TestBit(kProfile) && fBinEntries[i+1]==0)
+            continue;
+        n++;
+    }
+
+    // return Median of the profile data
+    return n;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the median 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::GetMedianSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t ball) const
+{
+    if (fNcells<=1)
+        return 0;
+
+    TArrayD arr(fNcells-2);
+    Int_t n=0;
+ 
+    for (int i=0; i<fNcells-2; i++)
+    {
+        if ((ball || IsUsed(i)) && MatchSector(i, sector, aidx))
+        {
+            if (TestBit(kProfile) && fBinEntries[i+1]==0)
+                continue;
+
+            arr[n++] = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+        }
+    }
+
+    // return Median of the profile data
+    return TMath::Median(n, arr.GetArray());
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the sqrt variance of all entries which are used if all=kFALSE and
+// of all entries if all=kTRUE if sector<0. If sector>=0 only
+// entries with match the given sector are taken into account.
+//
+Stat_t MHCamera::GetRmsSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t ball) 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 ((ball || IsUsed(i)) && MatchSector(i, sector, aidx))
+        {
+            if (TestBit(kProfile) && fBinEntries[i+1]==0)
+                continue;
+
+            const Double_t val = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+
+            sum += val;
+            sq  += val*val;
+            n++;
+        }
+    }
+
+    if (n==0)
+        return 0;
+
+    sum /= n;
+    sq  /= n;
+
+    return TMath::Sqrt(sq-sum*sum);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the median value (divided by MMath::GausProb(1.0)=68.3%) of the
+// distribution of abs(y[i]-Median). This is my Median equivalent of the RMS.
+// Return the deviation 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::GetDevSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t ball) const
+{
+    if (fNcells<=1)
+        return 0;
+
+    TArrayD arr(fNcells-2);
+    Int_t n=0;
+ 
+    for (int i=0; i<fNcells-2; i++)
+    {
+        if ((ball || IsUsed(i)) && MatchSector(i, sector, aidx))
+        {
+            if (TestBit(kProfile) && fBinEntries[i+1]==0)
+                continue;
+
+            arr[n++] = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+        }
+    }
+
+    // return Median of the profile data
+    return MMath::MedianDev(n, arr.GetArray());
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 ball) const
+{
+    if (fMinimum != -1111)
+        return fMinimum;
+
+    if (fNcells<=1)
+        return 0;
+
+    Double_t minimum=FLT_MAX;
+
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        if (TestBit(kProfile) && fBinEntries[i+1]==0)
+            continue;
+
+        const Double_t val = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+        if (MatchSector(i, sector, aidx) && (ball || IsUsed(i)) && val<minimum && TMath::Finite(val))
+            minimum = val;
+    }
+
+    return minimum;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the maximum contents of all pixels (if all is set, otherwise
+// only of all 'used' pixels), fMaximum if fMaximum set. If sector>=0
+// only pixels with matching sector number are taken into account.
+//
+Double_t MHCamera::GetMaximumSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t ball) const
+{
+    if (fMaximum!=-1111)
+        return fMaximum;
+
+    if (fNcells<=1)
+        return 1;
+
+    Double_t maximum=-FLT_MAX;
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        if (TestBit(kProfile) && fBinEntries[i+1]==0)
+            continue;
+
+        const Double_t val = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+        if (MatchSector(i, sector, aidx) && (ball || IsUsed(i)) && val>maximum && TMath::Finite(val))
+            maximum = val;
+    }
+
+    return maximum;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the number of bins (excluding under- and overflow) for which
+// GetBinContent returns a value > t
+//
+Int_t MHCamera::GetNumBinsAboveThreshold(Double_t t) const
+{
+    Int_t n = 0;
+    for (Int_t i=0; i<fNcells-2; i++)
+        if (GetBinContent(i+1)>t)
+            n++;
+
+    return n;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the number of bins (excluding under- and overflow) for which
+// GetBinContent returns a value < t
+//
+Int_t MHCamera::GetNumBinsBelowThreshold(Double_t t) const
+{
+    Int_t n = 0;
+    for (Int_t i=0; i<fNcells-2; i++)
+        if (GetBinContent(i+1)>t)
+            n++;
+
+    return n;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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))
+//   'text'        Draw GetBinContent as char
+//   'integer'     Draw GetBinContent as integer (TMath::Nint)
+//   'float'       Draw GetBinContent as float
+//   'proj'        Display the y-projection of the histogram
+//   'pal0'        Use Pretty palette
+//   'pal1'        Use Deep Blue Sea palette
+//   'pal2'        Use Inverse Depp Blue Sea palette
+//   'same'        Draw trandparent pixels on top of an existing pad. This
+//                 makes it possible to draw the camera image on top of an
+//                 existing TH2, but also allows for distorted camera images
+//
+void MHCamera::Draw(Option_t *option)
+{
+    const Bool_t hassame = TString(option).Contains("same", TString::kIgnoreCase) && gPad;
+
+    // root 3.02:
+    // gPad->SetFixedAspectRatio()
+    const Color_t col = gPad ? gPad->GetFillColor() : 16;
+    TVirtualPad  *pad = gPad ? gPad : MH::MakeDefCanvas("CamDisplay", "Mars Camera Display", 656, 600);
+
+    if (!hassame)
+    {
+        pad->SetBorderMode(0);
+        pad->SetFillColor(col);
+
+        //
+        // Create an own pad for the MHCamera-Object which can be
+        // resized in paint to keep the correct aspect ratio
+        //
+        // The margin != 0 is a workaround for a problem in root 4.02/00
+        //pad->Divide(1, 1, 1e-10, 1e-10, col);
+        //pad->cd(1);
+        //gPad->SetBorderMode(0);
+    }
+
+    AppendPad(option);
+    //fGeomCam->AppendPad();
+
+    //
+    // Do not change gPad. The user should not see, that Draw
+    // changes gPad...
+    //
+//    if (!hassame)
+//        pad->cd();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 "_proj" is given "_proj" is appended to the name
+// of the MHCamera and the corresponding histogram is searched using
+// gROOT->FindObject and updated with the present projection.
+//
+// It is the responsibility of the user to make sure, that the newly
+// created histogram is freed correctly.
+//
+// Currently the new histogram is restrictred to 50 bins.
+// Maybe a optimal number can be calulated from the number of
+// bins on the x-axis of the MHCamera?
+//
+// The code was taken mainly from TH2::ProjectX such the interface
+// is more or less the same than to TH2-projections.
+//
+// If sector>=0 only entries with matching sector index are taken
+// into account.
+//
+TH1D *MHCamera::ProjectionS(const TArrayI &sector, const TArrayI &aidx, const char *name, const Int_t nbins) const
+{
+
+    // Create the projection histogram
+    TString pname(name);
+    if (pname=="_proj")
+    {
+        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::Class())) {
+        h1 = (TH1D*)h1obj;
+        h1->Reset();
+    }
+
+    if (!h1)
+    {
+        h1 = new TH1D;
+        h1->UseCurrentStyle();
+        h1->SetName(pname);
+        h1->SetTitle(GetTitle());
+        h1->SetDirectory(0);
+        h1->SetXTitle(GetYaxis()->GetTitle());
+        h1->SetYTitle("Counts");
+        //h1->Sumw2();
+    }
+
+    Double_t min = GetMinimumSectors(sector, aidx);
+    Double_t max = GetMaximumSectors(sector, aidx);
+
+    if (min==max && max>0)
+        min=0;
+    if (min==max && min<0)
+        max=0;
+
+    Int_t newbins=0;
+    THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+
+    MBinning bins(nbins, min, max);
+    bins.Apply(*h1);
+
+    // Fill the projected histogram
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        if (IsUsed(idx) && MatchSector(idx, sector, aidx) && TMath::Finite(GetBinContent(idx+1)))
+            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 (pname=="_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::Class())) {
+        h1 = (TProfile*)h1obj;
+        h1->Reset();
+    }
+
+    if (!h1)
+    {
+        h1 = new TProfile;
+        h1->UseCurrentStyle();
+        h1->SetName(pname);
+        h1->SetTitle(GetTitle());
+        h1->SetDirectory(0);
+        h1->SetXTitle("Radius from camera center [mm]");
+        h1->SetYTitle(GetYaxis()->GetTitle());
+    }
+
+    const Double_t m2d = fGeomCam->GetConvMm2Deg();
+
+    Double_t min = 0.;
+    Double_t max = fGeomCam->GetMaxRadius()*m2d;
+
+    Int_t newbins=0;
+
+    THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+
+    MBinning bins(nbins, min, max);
+    bins.Apply(*h1);
+  
+    // Fill the projected histogram
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        if (IsUsed(idx) && MatchSector(idx, sector, aidx) && TMath::Finite(GetBinContent(idx+1)))
+            h1->Fill(TMath::Hypot((*fGeomCam)[idx].GetX(),(*fGeomCam)[idx].GetY())*m2d,
+                     GetBinContent(idx+1));
+    return h1;
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Creates a TH1D which contains the projection of the contents of the
+// MHCamera onto the azimuth angle in the camera. 
+//
+// If no name is given the newly allocated histogram is removed from
+// the current directory calling SetDirectory(0) in any other case
+// the newly created histogram is removed from the current directory
+// and added to gROOT such the gROOT->FindObject can find the histogram.
+//
+// If the standard name "_az" is given "_az" is appended to the name
+// of the MHCamera and the corresponding histogram is searched using
+// gROOT->FindObject and updated with the present projection.
+//
+// It is the responsibility of the user to make sure, that the newly
+// created histogram is freed correctly.
+//
+// Currently the new histogram is restrictred to 60 bins.
+// Maybe a optimal number can be calulated from the number of
+// bins on the x-axis of the MHCamera?
+//
+// The code was taken mainly from TH2::ProjectX such the interface
+// is more or less the same than to TH2-projections.
+//
+TProfile *MHCamera::AzimuthProfileA(const TArrayI &aidx, const char *name, const Int_t nbins) const
+{
+    // Create the projection histogram
+    TString pname(name);
+    if (pname=="_az")
+    {
+        pname.Prepend(GetName());
+        if (aidx.GetSize()>0)
+        {
+            pname += ";";
+            for (int i=0; i<aidx.GetSize(); i++)
+                pname += aidx[i];
+        }
+    }
+
+    TProfile *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(pname);
+    if (h1obj && h1obj->InheritsFrom(TProfile::Class())) {
+        h1 = (TProfile*)h1obj;
+        h1->Reset();
+    }
+
+    if (!h1)
+    {
+
+        h1 = new TProfile;
+        h1->UseCurrentStyle();
+        h1->SetName(pname);
+        h1->SetTitle(GetTitle());
+        h1->SetDirectory(0);
+        h1->SetXTitle("Azimuth in camera [deg]");
+        h1->SetYTitle(GetYaxis()->GetTitle());
+    }
+
+    //Double_t min = 0;
+    //Double_t max = 360;
+
+    //Int_t newbins=0;
+    //THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+
+    MBinning bins(nbins, 0, 360);
+    bins.Apply(*h1);
+
+    // Fill the projected histogram
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        if (IsUsed(idx) && MatchSector(idx, TArrayI(), aidx) && TMath::Finite(GetPixContent(idx)))
+            h1->Fill(TMath::ATan2((*fGeomCam)[idx].GetY(),(*fGeomCam)[idx].GetX())*TMath::RadToDeg()+180,
+                     GetPixContent(idx));
+
+    }
+
+    return h1;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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();
+
+    TAttLine line(kBlack, kSolid, 1);
+    TAttFill fill;
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        fill.SetFillStyle(issame || (IsTransparent() && !IsUsed(i)) ? 0 : 1001);
+
+        if (!issame)
+        {
+            const Bool_t isnan = !TMath::Finite(fArray[i+1]);
+            if (!IsUsed(i) || !iscol || isnan)
+            {
+                fill.SetFillColor(10);
+
+                if (isnan)
+                    gLog << warn << "MHCamera::Update: " << GetName() << " <" << GetTitle() << "> - Pixel Index #" << i << " contents is not finite..." << endl;
+            }
+            else
+                fill.SetFillColor(GetColor(GetBinContent(i+1), min, max, islog));
+        }
+
+        const MGeom &pix = (*fGeomCam)[i];
+
+        Double_t scale = 1;//conv/(fAbberation+1);
+
+        if (!isbox && !IsUsed(i) && TestBit(kNoUnused))
+            continue;
+
+        if (isbox && (!IsUsed(i) || !TMath::Finite(fArray[i+1])))
+            continue;
+
+        if (isbox)
+        {
+            scale = (GetBinContent(i+1)-min)/(max-min);
+            if (scale>1)
+                scale=1;
+        }
+
+        pix.PaintPrimitive(line, fill, conv, scale/(fAbberation+1));
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// 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", "");
+        opt.ReplaceAll("box", "");
+        opt.ReplaceAll("pixelindex", "");
+        opt.ReplaceAll("sectorindex", "");
+        opt.ReplaceAll("abscontent", "");
+        opt.ReplaceAll("content", "");
+        opt.ReplaceAll("integer", "");
+        opt.ReplaceAll("float", "");
+        opt.ReplaceAll("proj", "");
+        opt.ReplaceAll("pal0", "");
+        opt.ReplaceAll("pal1", "");
+        opt.ReplaceAll("pal2", "");
+        opt.ReplaceAll("nopal", "");
+        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();
+
+    if (!fGeomCam)
+        return;
+
+    if (!hassame)
+    {
+        // Maintain aspect ratio
+        const Float_t r = fGeomCam->GetMaxRadius();
+
+        MH::SetPadRange(-r*1.02, -r*1.02, TestBit(kNoLegend) ? r : 1.15*r, r*1.2);
+
+        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();
+            }
+        }
+    }
+
+    const Bool_t pal1  = opt.Contains("pal1");
+    const Bool_t pal2  = opt.Contains("pal2");
+    const Bool_t nopal = opt.Contains("nopal");
+
+    if (!pal1 && !pal2 && !nopal)
+        SetPrettyPalette();
+
+    if (pal1)
+        SetDeepBlueSeaPalette();
+
+    if (pal2)
+        SetInvDeepBlueSeaPalette();
+
+    // Update Contents of the pixels and paint legend
+    Update(gPad->GetLogy(), hasbox, hascol, hassame);
+
+    if (!hassame)
+        PaintAxisTitle();
+
+    if (opt.Contains("pixelindex"))
+    {
+        PaintIndices(0);
+        return;
+    }
+    if (opt.Contains("sectorindex"))
+    {
+        PaintIndices(1);
+        return;
+    }
+    if (opt.Contains("abscontent"))
+    {
+        PaintIndices(3);
+        return;
+    }
+    if (opt.Contains("content"))
+    {
+        PaintIndices(2);
+        return;
+    }
+    if (opt.Contains("pixelentries"))
+    {
+        PaintIndices(4);
+        return;
+    }
+    if (opt.Contains("text"))
+    {
+        PaintIndices(5);
+        return;
+    }
+    if (opt.Contains("integer"))
+    {
+        PaintIndices(6);
+        return;
+    }
+    if (opt.Contains("float"))
+    {
+        PaintIndices(7);
+        return;
+    }
+}
+
+void MHCamera::SetDrawOption(Option_t *option)
+{
+    // This is a workaround. For some reason MHCamera is
+    // stored in a TObjLink instead of a TObjOptLink
+    if (!option || !gPad)
+        return;
+
+    TListIter next(gPad->GetListOfPrimitives());
+    delete gPad->FindObject("Tframe");
+    TObject *obj;
+    while ((obj = next()))
+        if (obj == this && (TString)next.GetOption()!=(TString)option)
+        {
+            gPad->GetListOfPrimitives()->Remove(this);
+            gPad->GetListOfPrimitives()->AddFirst(this, option);
+            return;
+        }
+}
+
+// ------------------------------------------------------------------------
+//
+// 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);
+
+        const Int_t n = GetContour()==0?50:GetContour();
+
+        TArrayI c(n);
+        for (int i=0; i<n; i++)
+            c[n-i-1] = gStyle->GetColorPalette(i);
+        gStyle->SetPalette(n, c.GetArray());
+    }
+    else
+        gStyle->SetPalette(ncolors, colors);
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Changes the palette of the displayed camera histogram.
+//
+// Change to the right pad first - otherwise GetDrawOption() might fail.
+//
+void MHCamera::SetPrettyPalette()
+{
+    TString opt(GetDrawOption());
+
+    if (!opt.Contains("hist", TString::kIgnoreCase))
+        SetPalette(1, 0);
+
+    opt.ReplaceAll("pal1", "");
+    opt.ReplaceAll("pal2", "");
+
+    SetDrawOption(opt);
+}
+
+// ------------------------------------------------------------------------
+//
+// Changes the palette of the displayed camera histogram.
+//
+// Change to the right pad first - otherwise GetDrawOption() might fail.
+//
+void MHCamera::SetDeepBlueSeaPalette()
+{
+    TString opt(GetDrawOption());
+
+    if (!opt.Contains("hist", TString::kIgnoreCase))
+        SetPalette(51, 0);
+
+    opt.ReplaceAll("pal1", "");
+    opt.ReplaceAll("pal2", "");
+    opt += "pal1";
+
+    SetDrawOption(opt);
+}
+
+// ------------------------------------------------------------------------
+//
+// Changes the palette of the displayed camera histogram.
+//
+// Change to the right pad first - otherwise GetDrawOption() might fail.
+//
+void MHCamera::SetInvDeepBlueSeaPalette()
+{
+    TString opt(GetDrawOption());
+
+    if (!opt.Contains("hist", TString::kIgnoreCase))
+        SetPalette(52, 0);
+
+    opt.ReplaceAll("pal1", "");
+    opt.ReplaceAll("pal2", "");
+    opt += "pal2";
+
+    SetDrawOption(opt);
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint indices (as text) inside the pixels. Depending of the type-
+// argument we paint:
+//  0: pixel number
+//  1: sector number
+//  2: content
+//  5: Assume GetBinContent is a char
+//
+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;
+    if (type!=5)
+        txt.SetTextFont(122);
+    txt.SetTextAlign(22);   // centered/centered
+
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        const MGeom &h = (*fGeomCam)[i];
+
+        TString num;
+        switch (type)
+        {
+        case 0: num += i; break;
+        case 1: num += h.GetSector(); break;
+        case 2: num += TMath::Nint((fArray[i+1]-min)/(max-min)); break;
+        case 3: num += TMath::Nint(fArray[i+1]); break;
+        case 4: num += fBinEntries[i+1]; break;
+        case 5: num  = (char)TMath::Nint(GetBinContent(i+1)); break;
+        case 6: num += TMath::Nint(GetBinContent(i+1)); break;
+        case 7: num += GetBinContent(i+1); 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.GetT()/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::AddMeanShift(const MCamEvent &event, Int_t type, Stat_t w)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    const Double_t mean = event.GetCameraMean(*fGeomCam, type);
+
+    // 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-mean)*w); // FIXME: Slow!
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+//
+void MHCamera::AddMedianShift(const MCamEvent &event, Int_t type, Stat_t w)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    const Double_t median = event.GetCameraMedian(*fGeomCam, type);
+
+    // 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-median)*w); // FIXME: Slow!
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+//
+void MHCamera::AddCamContent(const MCamEvent &event, Int_t type, Stat_t w)
+{
+    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*w); // FIXME: Slow!
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+void MHCamera::AddCamDifference(const MCamEvent &event1, const MCamEvent &event2, Int_t type, Stat_t weight)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val1=0;
+        if (!event1.GetPixelContent(val1, idx, *fGeomCam, type))
+            continue;
+
+        Double_t val2=0;
+        if (!event2.GetPixelContent(val2, idx, *fGeomCam, type))
+            continue;
+
+        SetUsed(idx);
+        Fill(idx, (val1-val2)*weight); // FIXME: Slow!
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+void MHCamera::AddCamRatio(const MCamEvent &event1, const MCamEvent &event2, Int_t type, Stat_t weight)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val1=0;
+        if (!event1.GetPixelContent(val1, idx, *fGeomCam, type))
+            continue;
+
+        Double_t val2=0;
+        if (!event2.GetPixelContent(val2, idx, *fGeomCam, type))
+            continue;
+
+        if (val2==0)
+            continue;
+
+        SetUsed(idx);
+        Fill(idx, weight*val1/val2); // FIXME: Slow!
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+//
+void MHCamera::SetCamError(const MCamEvent &evt, Int_t type)
+{
+
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=0;
+        if (evt.GetPixelContent(val, idx, *fGeomCam, type)/* && !IsUsed(idx)*/)
+            SetUsed(idx);
+
+        SetBinError(idx+1, val); // FIXME: Slow!
+    }
+}
+
+Stat_t MHCamera::GetBinContent(Int_t bin) const
+{
+    if (fBuffer) ((TH1D*)this)->BufferEmpty();
+    if (bin < 0) bin = 0;
+    if (bin >= fNcells) bin = fNcells-1;
+    if (!fArray) return 0;
+
+    if (!TestBit(kProfile))
+        return Stat_t (fArray[bin]);
+
+    if (fBinEntries.fArray[bin] == 0) return 0;
+    return fArray[bin]/fBinEntries.fArray[bin];
+}
+
+// ------------------------------------------------------------------------
+//
+// In the case the kProfile flag is set the spread of the bin is returned.
+// If you want to have the mean error instead set the kErrorMean bit via
+//  SetBit(kErrorMean) first.
+//
+Stat_t MHCamera::GetBinError(Int_t bin) const
+{
+    if (!TestBit(kProfile))
+        return TH1D::GetBinError(bin);
+
+    const UInt_t n = (UInt_t)fBinEntries[bin];
+
+    if (n==0)
+        return 0;
+
+    const Double_t sqr = fSumw2.fArray[bin] / n;
+    const Double_t val = fArray[bin]        / n;
+
+    const Double_t spread = sqr>val*val ? TMath::Sqrt(sqr - val*val) : 0;
+
+    return TestBit(kErrorMean) ? spread/TMath::Sqrt(n) : spread;
+
+    /*
+    Double_t rc = 0;
+    if (TestBit(kSqrtVariance) && GetEntries()>0) // error on the mean
+    {
+        const Double_t error = fSumw2.fArray[bin]/GetEntries();
+        const Double_t val   = fArray[bin]/GetEntries();
+        rc = val*val>error ? 0 : TMath::Sqrt(error - val*val);
+    }
+    else
+        rc = TH1D::GetBinError(bin);
+
+    return Profile(rc);*/
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MHCamera on top of the present contents.
+// Type:
+//  0) bin content
+//  1) errors
+//  2) rel. errors
+//
+void MHCamera::AddCamContent(const MHCamera &d, Int_t type)
+{
+    if (fNcells!=d.fNcells || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        if (d.IsUsed(idx))
+            SetUsed(idx);
+
+    switch (type)
+    {
+    case 1:
+        // Under-/Overflow bins not handled!
+        for (Int_t idx=0; idx<fNcells-2; idx++)
+            if (d.IsUsed(idx))
+                Fill(idx, d.GetBinError(idx+1));
+        fEntries++;
+        break;
+    case 2:
+        // Under-/Overflow bins not handled!
+        for (Int_t idx=0; idx<fNcells-2; idx++)
+            if (d.GetBinContent(idx+1)!=0 && d.IsUsed(idx))
+                Fill(idx, TMath::Abs(d.GetBinError(idx+1)/d.GetBinContent(idx+1)));
+        fEntries++;
+        break;
+    default:
+        if (TestBit(kProfile)!=d.TestBit(kProfile))
+            gLog << warn << "WARNING - You have tried to call AddCamContent for two different kind of histograms (kProfile set or not)." << endl;
+
+        // environment
+        fEntries += d.fEntries;
+        fTsumw   += d.fTsumw;
+        fTsumw2  += d.fTsumw2;
+        fTsumwx  += d.fTsumwx;
+        fTsumwx2 += d.fTsumwx2;
+        // Bin contents
+        for (Int_t idx=1; idx<fNcells-1; idx++)
+        {
+            if (!d.IsUsed(idx-1))
+                continue;
+
+            fArray[idx]          += d.fArray[idx];
+            fBinEntries[idx]     += d.fBinEntries[idx];
+            fSumw2.fArray[idx]   += d.fSumw2.fArray[idx];
+        }
+        // Underflow bin
+        fArray[0]                += d.fArray[0];
+        fBinEntries[0]           += d.fBinEntries[0];
+        fSumw2.fArray[0]         += d.fSumw2.fArray[0];
+        // Overflow bin
+        fArray[fNcells-1]        += d.fArray[fNcells-1];
+        fBinEntries[fNcells-1]   += d.fBinEntries[fNcells-1];
+        fSumw2.fArray[fNcells-1] += d.fSumw2.fArray[fNcells-1];
+        break;
+/*    default:
+        if (TestBit(kProfile)!=d.TestBit(kProfile))
+            gLog << warn << "WARNING - You have tried to call AddCamContent for two different kind of histograms (kProfile set or not)." << endl;
+
+        for (Int_t idx=0; idx<fNcells-2; idx++)
+            Fill(idx, d.GetBinContent(idx+1));
+        break;*/
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a TArrayD on top of the present contents.
+//
+void MHCamera::AddCamContent(const TArrayD &event, const TArrayC *used)
+{
+    if (event.GetSize()!=fNcells-2 || IsFreezed())
+        return;
+
+    if (used && used->GetSize()!=fNcells-2)
+        return;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Fill(idx, event[idx]); // FIXME: Slow!
+
+        if (!used || (*used)[idx])
+            SetUsed(idx);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MArrayD on top of the present contents.
+//
+void MHCamera::AddCamContent(const MArrayD &event, const TArrayC *used)
+{
+    if (event.GetSize()!=(UInt_t)(fNcells-2) || IsFreezed())
+        return;
+
+    if (used && used->GetSize()!=fNcells-2)
+        return;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Fill(idx, event[idx]); // FIXME: Slow!
+
+        if (!used || (*used)[idx])
+            SetUsed(idx);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold
+//   (in case isabove is set to kTRUE == default)
+// 1 is added to each pixel if the contents of MCamEvent<threshold
+//   (in case isabove is set to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::CntCamContent(const MCamEvent &event, Double_t threshold, Int_t type, Bool_t isabove)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=threshold;
+        const Bool_t rc = event.GetPixelContent(val, idx, *fGeomCam, type);
+        if (rc)
+            SetUsed(idx);
+
+        const Bool_t cond =
+            ( isabove && val>threshold) ||
+            (!isabove && val<threshold);
+
+        Fill(idx, rc && cond ? 1 : 0);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// - the contents of the pixels in event are added to each pixel
+//   if the pixel of thresevt<threshold (in case isabove is set
+//   to kTRUE == default)
+// - the contents of the pixels in event are  added to each pixel
+//   if the pixel of thresevt<threshold (in case isabove is set
+//   to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::CntCamContent(const MCamEvent &event, Int_t type1, const MCamEvent &thresevt, Int_t type2, Double_t threshold, Bool_t isabove)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t th=0;
+        if (!thresevt.GetPixelContent(th, idx, *fGeomCam, type2))
+            continue;
+
+        if ((isabove && th>threshold) || (!isabove && th<threshold))
+            continue;
+
+        Double_t val=th;
+        if (event.GetPixelContent(val, idx, *fGeomCam, type1))
+        {
+            SetUsed(idx);
+            Fill(idx, val);
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold
+//   (in case isabove is set to kTRUE == default)
+// 1 is added to each pixel if the contents of MCamEvent<threshold
+//   (in case isabove is set to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::CntCamContent(const MCamEvent &event, TArrayD threshold, Int_t type, Bool_t isabove)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=threshold[idx];
+        if (event.GetPixelContent(val, idx, *fGeomCam, type)/* && !IsUsed(idx)*/)
+        {
+            SetUsed(idx);
+
+            if (val>threshold[idx] && isabove)
+                Fill(idx);
+            if (val<threshold[idx] && !isabove)
+                Fill(idx);
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a TArrayD on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold
+//
+void MHCamera::CntCamContent(const TArrayD &event, Double_t threshold, Bool_t ispos)
+{
+    if (event.GetSize()!=fNcells-2 || IsFreezed())
+        return;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        if (event[idx]>threshold)
+            Fill(idx);
+
+        if (!ispos || fArray[idx+1]>0)
+            SetUsed(idx);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold
+//   (in case isabove is set to kTRUE == default)
+// 1 is added to each pixel if the contents of MCamEvent<threshold
+//   (in case isabove is set to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::SetMaxCamContent(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;
+        const Bool_t rc = event.GetPixelContent(val, idx, *fGeomCam, type);
+        if (!rc)
+            continue;
+
+        if (!IsUsed(idx))
+        {
+            fArray[idx+1] = val;
+            SetUsed(idx);
+            fBinEntries.fArray[idx+1]=1;
+        }
+        else
+            if (val>fArray[idx+1])
+                fArray[idx+1] = val;
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold
+//   (in case isabove is set to kTRUE == default)
+// 1 is added to each pixel if the contents of MCamEvent<threshold
+//   (in case isabove is set to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::SetMinCamContent(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;
+        const Bool_t rc = event.GetPixelContent(val, idx, *fGeomCam, type);
+        if (!rc)
+            continue;
+
+        if (!IsUsed(idx))
+        {
+            fArray[idx+1] = val;
+            SetUsed(idx);
+            fBinEntries.fArray[idx+1]=1;
+        }
+        else
+            if (val<fArray[idx+1])
+                fArray[idx+1] = val;
+    }
+    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);
+
+    fUsed.Reset();
+    fBinEntries.Reset();
+
+    for (Int_t i=0; i<fNcells; i++)
+        fArray[i] = 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)
+{
+    //
+    //   first treat the over- and under-flows
+    //
+    const Int_t ncol = GetContour()==0?50:GetContour();
+
+    const Int_t maxcolidx = ncol-1;
+
+    if (!TMath::Finite(val)) // FIXME: gLog!
+        return maxcolidx/2;
+
+    if (val >= max)
+        return gStyle->GetColorPalette(maxcolidx);
+
+    if (val <= min)
+        return gStyle->GetColorPalette(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 = TMath::FloorNint(ratio*ncol);
+    return gStyle->GetColorPalette(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();
+
+    if (!TestBit(kNoScale))
+    {
+        TArrow arr;
+        arr.PaintArrow(-range*.99, -range*.99, -range*.60, -range*.99, 0.010);
+        arr.PaintArrow(-range*.99, -range*.99, -range*.99, -range*.60, 0.010);
+
+        TString text;
+        text += (int)(range*.3);
+        text += "mm";
+
+        TText newtxt2;
+        newtxt2.SetTextSize(0.04);
+        newtxt2.PaintText(-range*.95, -range*.95, text);
+
+        text = MString::Format("%.2f\\circ", range*(0.99-0.60)*fGeomCam->GetConvMm2Deg());
+        text = text.Strip(TString::kLeading);
+
+        TLatex latex;
+        latex.PaintLatex(-range*.95, -range*.85, 0, 0.04, text);
+    }
+
+    if (!TestBit(kNoLegend))
+    {
+        TPaveStats *stats = GetStatisticBox();
+
+        const Float_t hndc   = 0.88 - (stats ? stats->GetY1NDC() : 1);
+        const Float_t H      = (0.80-hndc)*range;
+        const Float_t offset = hndc*range;
+
+        const Int_t ncol = GetContour()==0 ? 50 : GetContour();
+
+        const Float_t h = 2./ncol;
+        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);
+        const Int_t   firsts = step/48*3 < 1e-8 ? 8 : (Int_t)floor(log10(step/48*3));
+        const TString opt    = MString::Format("%%.%if", firsts>0 ? 0 : TMath::Abs(firsts));
+/*
+        for (Int_t i=0; i<ncol+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));
+            }
+            */
+        const MBinning bins(25, min, max, islog&&min>0?"log":"lin");
+
+        for (Int_t i=0; i<=25; i++)
+            newtxt.PaintText(range+1.5*w, H*(i*ncol/25*h-1)-offset, MString::Format(opt, bins[i]));
+
+        for (Int_t i=0; i<ncol; i++)
+        {
+            newbox.SetFillColor(gStyle->GetColorPalette(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(ostream &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;
+    */
+}
+
+void MHCamera::SavePrimitive(ofstream &out, Option_t *)
+{
+    MHCamera::SavePrimitive(static_cast<ostream&>(out), "");
+}
+
+// ------------------------------------------------------------------------
+//
+// 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;
+
+    for (Int_t i=0; i<fNcells-2; i++)
+        if ((*fGeomCam)[i].DistancetoPrimitive(TMath::Nint(px*conv), TMath::Nint(py*conv))<=0)
+            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))
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,22,00)
+        return MH::GetObjectInfoH(px, py, *this);
+#else
+        return TH1D::GetObjectInfo(px, py);
+#endif
+
+    static char info[128];
+
+    const Int_t idx=GetPixelIndex(px, py);
+
+    if (idx<0)
+        return TObject::GetObjectInfo(px, py);
+
+    sprintf(info, "Software Pixel Idx: %d (Hardware Id=%d) c=%.1f <%s>",
+            idx, idx+1, GetBinContent(idx+1), IsUsed(idx)?"on":"off");
+    return info;
+}
+
+// ------------------------------------------------------------------------
+//
+// Add a MCamEvent which should be displayed when the user clicks on a
+// pixel.
+// Warning: The object MUST inherit from TObject AND MCamEvent
+//
+void MHCamera::AddNotify(TObject *obj)
+{
+    // Make sure, that the object derives from MCamEvent!
+    MCamEvent *evt = dynamic_cast<MCamEvent*>(obj);
+    if (!evt)
+    {
+        gLog << err << "ERROR: MHCamera::AddNotify - TObject doesn't inherit from MCamEvent... ignored." << endl;
+        return;
+    }
+
+    // Make sure, that it is deleted from the list too, if the obj is deleted
+    obj->SetBit(kMustCleanup);
+
+    // Add object to list
+    fNotify->Add(obj);
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MHCamera::ExecuteEvent(Int_t event, Int_t px, Int_t py)
+{
+    if (TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+    {
+        TH1D::ExecuteEvent(event, px, py);
+        return;
+    }
+    //if (event==kMouseMotion && fStatusBar)
+    //    fStatusBar->SetText(GetObjectInfo(px, py), 0);
+    if (event!=kButton1Down)
+        return;
+
+    const Int_t idx = GetPixelIndex(px, py);
+    if (idx<0)
+        return;
+
+    gLog << all << GetTitle() << " <" << GetName() << ">" << dec << endl;
+    gLog << "Software Pixel Idx: " << idx << endl;
+    gLog << "Hardware Pixel Id:  " << idx+1 << endl;
+    gLog << "Contents:           " << GetBinContent(idx+1);
+    if (GetBinError(idx+1)>0)
+        gLog << " +/- " << GetBinError(idx+1);
+    gLog << "  <" << (IsUsed(idx)?"on":"off") << ">  n=" << fBinEntries[idx+1] << endl;
+
+    if (fNotify && fNotify->GetSize()>0)
+    {
+        // FIXME: Is there a simpler and more convinient way?
+
+        // The name which is created here depends on the instance of
+        // MHCamera and on the pad on which it is drawn --> The name
+        // is unique. For ExecuteEvent gPad is always correctly set.
+        const TString name = MString::Format("%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 ? fGeomCam->GetNumPixels() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a projection of MHCamera onto the y-axis values. Depending on the 
+// variable fit, the following fits are performed:
+//
+// 0: No fit, simply draw the projection
+// 1: Single Gauss (for distributions flat-fielded over the whole camera)
+// 2: Double Gauss (for distributions different for inner and outer pixels)
+// 3: Triple Gauss (for distributions with inner, outer pixels and outliers)
+// 4: flat         (for the probability distributions)
+// (1-4:) Moreover, sectors 6,1 and 2 of the camera and sectors 3,4 and 5 are 
+//        drawn separately, for inner and outer pixels.
+// 5: Fit Inner and Outer pixels separately by a single Gaussian 
+//                 (only for MAGIC cameras)
+// 6: Fit Inner and Outer pixels separately by a single Gaussian and display 
+//                 additionally the two camera halfs separately (for MAGIC camera)
+// 7: Single Gauss with TLegend to show the meaning of the colours
+//
+void MHCamera::DrawProjection(Int_t fit) const
+{
+    if (fit==5 || fit==6)
+    {
+        const UInt_t n = fGeomCam->GetNumAreas();
+
+        TVirtualPad *pad = gPad;
+        pad->Divide(n, 1, 1e-5, 1e-5);;
+
+        for (UInt_t i=0; i<n; i++)
+        {
+            pad->cd(i+1);
+            gPad->SetBorderMode(0);
+            gPad->SetRightMargin(0.025);
+            gPad->SetTicks();
+
+            TH1D &h = *ProjectionS(TArrayI(), TArrayI(1, (Int_t*)&i),
+                                   MString::Format("%s_%d", GetName(), i));
+            h.SetTitle(MString::Format("%s %d", GetTitle(), i));
+            h.SetDirectory(NULL);
+            h.SetBit(kCanDelete);
+            h.Draw();
+
+            TAxis *xaxe = h.GetXaxis();
+            TAxis *yaxe = h.GetYaxis();
+
+            xaxe->CenterTitle();
+            yaxe->CenterTitle();
+            xaxe->SetTitleSize(0.06);
+            yaxe->SetTitleSize(0.06);
+            xaxe->SetTitleOffset(0.8);
+            yaxe->SetTitleOffset(0.85);
+            xaxe->SetLabelSize(0.05);
+            yaxe->SetLabelSize(0.05);
+            if (i>0)
+                yaxe->SetTitle("");
+
+            if (fit==5)
+                continue;
+
+            h.Fit("gaus", "Q");
+
+            TF1 *f = h.GetFunction("gaus");
+            if (f)
+            {
+                f->SetLineWidth(2);
+                f->SetLineColor(kBlue);
+            }
+        }
+        return;
+    }
+
+    TH1D *obj2 = (TH1D*)Projection(GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+
+    if (fit==0)
+        return;
+
+    const Double_t xmin  = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+    const Double_t xmax  = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+    const Double_t integ = obj2->Integral("width")/2.5;
+    const Double_t max   = obj2->GetMaximum();
+    const Double_t mean  = obj2->GetMean();
+    const Double_t rms   = obj2->GetRMS();
+    const Double_t width = xmax-xmin;
+
+    const char *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 char *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: // Single gauss
+        f = new TF1("sgaus", "gaus", xmin, xmax);
+        f->SetLineColor(kBlue);
+        f->SetBit(kCanDelete);
+        f->SetParNames("Max", "#mu", "#sigma");
+        f->SetParameters(max, mean, rms);
+        f->SetParLimits(0, 0,    max*2);
+        f->SetParLimits(1, xmin, xmax);
+        f->SetParLimits(2, 0,    width/1.5);
+
+        obj2->Fit(f, "QLR");
+        break;
+
+    case 2: // Double gauss
+        f = new TF1("dgaus", dgausformula, xmin, xmax);
+        f->SetLineColor(kBlue);
+        f->SetBit(kCanDelete);
+        f->SetParNames("A_{tot}", "#mu1", "#sigma1", "A2", "#mu2", "#sigma2");
+        f->SetParameters(integ, (xmin+mean)/2., width/4.,
+                         integ/width/2., (xmax+mean)/2., width/4.);
+        // The left-sided Gauss
+        f->SetParLimits(0, integ-1.5,        integ+1.5);
+        f->SetParLimits(1, xmin+(width/10.), mean);
+        f->SetParLimits(2, 0,                width/2.);
+        // The right-sided Gauss
+        f->SetParLimits(3, 0,    integ);
+        f->SetParLimits(4, mean, xmax-(width/10.));
+        f->SetParLimits(5, 0,    width/2.);
+        obj2->Fit(f,"QLRM");
+        break;
+
+    case 3: // Triple gauss
+        f = new TF1("tgaus", tgausformula, xmin,xmax);
+        f->SetLineColor(kBlue);
+        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, (xmin+mean)/2, width/4.,
+                         integ/width/3., (xmax+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, xmin+(width/10.), mean);
+        f->SetParLimits(2, width/15.,        width/2.);
+        // The right-sided Gauss
+        f->SetParLimits(3, 0.,               integ);
+        f->SetParLimits(4, mean,             xmax-(width/10.));
+        f->SetParLimits(5, width/15.,        width/2.);
+        // The Gauss describing the outliers
+        f->SetParLimits(6, 0.,               integ);
+        f->SetParLimits(7, xmin,             xmax);
+        f->SetParLimits(8, width/4.,         width/1.5);
+        obj2->Fit(f,"QLRM");
+        break;
+
+    case 4:
+        obj2->Fit("pol0", "Q");
+        if (obj2->GetFunction("pol0"))
+            obj2->GetFunction("pol0")->SetLineColor(kBlue);
+        break;
+
+    case 9:
+        break;
+
+    default:
+        obj2->Fit("gaus", "Q");
+        if (obj2->GetFunction("gaus"))
+            obj2->GetFunction("gaus")->SetLineColor(kBlue);
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a projection of MHCamera vs. the radius from the central pixel. 
+//
+// The inner and outer pixels are drawn separately, both fitted by a polynomial
+// of grade 1.
+//
+void MHCamera::DrawRadialProfile() const
+{
+    TProfile *obj2 = (TProfile*)RadialProfile(GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+/*
+    if (GetGeomCam().InheritsFrom("MGeomCamMagic"))
+    {
+        TArrayI s0(6);
+        s0[0] = 1;
+        s0[1] = 2;
+        s0[2] = 3;
+        s0[3] = 4;
+        s0[4] = 5;
+        s0[5] = 6;
+
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TProfile *half[2];
+        half[0] = RadialProfileS(s0, inner, MString::Format("%sInner",GetName()));
+        half[1] = RadialProfileS(s0, outer, MString::Format("%sOuter",GetName()));
+
+        for (Int_t i=0; i<2; i++)
+        {
+            Double_t min = GetGeomCam().GetMinRadius(i);
+            Double_t max = GetGeomCam().GetMaxRadius(i);
+
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->Draw("same");
+            half[i]->Fit("pol1","Q","",min,max);
+            half[i]->GetFunction("pol1")->SetLineColor(kRed+i);
+            half[i]->GetFunction("pol1")->SetLineWidth(1);
+        }
+    }
+*/
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a projection of MHCamera vs. the azimuth angle inside the camera.
+//
+// The inner and outer pixels are drawn separately. 
+// The general azimuth profile is fitted by a straight line
+//
+void MHCamera::DrawAzimuthProfile() const
+{
+    TProfile *obj2 = (TProfile*)AzimuthProfile(GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+    obj2->Fit("pol0","Q","");
+    if (obj2->GetFunction("pol0"))
+        obj2->GetFunction("pol0")->SetLineWidth(1);
+/*
+    if (GetGeomCam().InheritsFrom("MGeomCamMagic"))
+    {
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TProfile *half[2];
+        half[0] = AzimuthProfileA(inner, MString::Format("%sInner",GetName()));
+        half[1] = AzimuthProfileA(outer, MString::Format("%sOuter",GetName()));
+
+        for (Int_t i=0; i<2; i++)
+        {
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->SetMarkerSize(0.5);
+            half[i]->Draw("same");
+        }
+    }
+*/
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the MHCamera into the MStatusDisplay: 
+// 
+// 1) Draw it as histogram (MHCamera::DrawCopy("hist")
+// 2) Draw it as a camera, with MHCamera::SetPrettyPalette() set. 
+// 3) If "rad" is not zero, draw its values vs. the radius from the camera center. 
+//    (DrawRadialProfile())
+// 4) Depending on the variable "fit", draw the values projection on the y-axis
+//    (DrawProjection()):
+//    0: don't draw
+//    1: Draw fit to Single Gauss (for distributions flat-fielded over the whole camera)
+//    2: Draw and fit to Double Gauss (for distributions different for inner and outer pixels)
+//    3: Draw and fit to Triple Gauss (for distributions with inner, outer pixels and outliers)
+//    4: Draw and fit to Polynomial grade 0: (for the probability distributions)
+//    >4: Draw and don;t fit.
+//
+void MHCamera::CamDraw(TCanvas &c, const Int_t x, const Int_t y, 
+                       const Int_t fit, const Int_t rad, const Int_t azi,
+                       TObject *notify)
+{
+    c.cd(x);
+    gPad->SetBorderMode(0);
+    gPad->SetRightMargin(0.02);
+    gPad->SetTicks();
+    MHCamera *obj1=(MHCamera*)DrawCopy("hist");
+    obj1->SetDirectory(NULL);
+    obj1->SetStats(kFALSE);
+
+    if (notify)
+        obj1->AddNotify(notify);
+
+    c.cd(x+y);
+    gPad->SetBorderMode(0);
+    obj1->SetPrettyPalette();
+    obj1->Draw();
+
+    Int_t cnt = 2;
+
+    if (rad)
+    {
+        c.cd(x+2*y);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        DrawRadialProfile();
+        cnt++;
+    }
+
+    if (azi)
+    {
+        c.cd(x+cnt*y);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        DrawAzimuthProfile();
+        cnt++;
+    }
+
+    if (fit<0)
+        return;
+
+    c.cd(x + cnt*y);
+    gPad->SetBorderMode(0);
+    gPad->SetRightMargin(0.025);
+    gPad->SetTicks();
+    DrawProjection(fit);
+}
Index: branches/Mars_McMismatchStudy/mhist/MHCamera.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCamera.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCamera.h	(revision 17960)
@@ -0,0 +1,491 @@
+/* ======================================================================== *\
+!  $Name: not supported by cvs2svn $:$Id: MHCamera.h,v 1.69 2009-02-11 12:25:42 tbretz Exp $
+\* ======================================================================== */
+#ifndef MARS_MHCamera
+#define MARS_MHCamera
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef ROOT_MArrayD
+#include <MArrayD.h>
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef ROOT_TCanvas
+#include <TCanvas.h>
+#endif
+
+class TPaveStats;
+class TProfile;
+
+class MGeomCam;
+class MCamEvent;
+class MRflEvtData;
+class MCerPhotEvt;
+class MImgCleanStd;
+
+class MHCamera : public TH1D
+{
+public:
+    enum {
+        // DO NOT USE BIT(14) (MStatusArray WORKAROUND!)
+        // BIT(15)/BIT(16)/BIT(17) used by TH1
+        kProfile            = BIT(18), // FIXME: When changing change max/min!
+        kFreezed            = BIT(19),
+        kNoLegend           = BIT(20),
+        kNoScale            = BIT(21),
+        kNoUnused           = BIT(22),
+        kErrorMean          = BIT(23)/*,  // NO MORE BITS ALLOWED!
+        kSqrtVariance       = BIT(21),
+        kSinglePixelProfile = BIT(22)*/
+    };
+protected:
+    MGeomCam      *fGeomCam;     // pointer to camera geometry (y-axis)
+    TArrayC        fUsed;        // array containing flags
+    TArrayI        fBinEntries;  // number of entries per bin
+
+    TList         *fNotify;      //!
+
+//#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,03)
+    Bool_t         fFreezed;     //! Just a dummy!!!! ([Set,Is]Freezed)
+//#endif
+
+    Float_t fAbberation;
+
+    void Init();
+/*
+    Stat_t Profile(Stat_t val) const
+    {
+        if (!TestBit(kProfile))
+            return val;
+
+        const Stat_t n = TH1D::GetEntries();
+        return n>0 ? val/n : val;
+    }
+  */
+    Int_t GetColor(Float_t val, Float_t min, Float_t max, Bool_t islog);
+
+    void  PaintIndices(Int_t type);
+    void  Update(Bool_t islog, Bool_t isbox, Bool_t iscol, Bool_t issame);
+    void  UpdateLegend(Float_t min, Float_t max, Bool_t islog);
+
+    TPaveStats *GetStatisticBox();
+
+    Int_t GetPixelIndex(Int_t px, Int_t py, Float_t conv=1) const;
+
+    void PaintAxisTitle();
+
+    enum {
+        kIsUsed = BIT(1)
+    };
+
+    void   ResetUsed(Int_t idx)    { CLRBIT(fUsed[idx], kIsUsed); }
+
+    Bool_t FindVal(const TArrayI &arr, Int_t val) const
+    {
+        const Int_t n = arr.GetSize();
+        if (n==0)
+            return kTRUE;
+
+        const Int_t *p = arr.GetArray();
+        const Int_t *end = p+n;
+        while (p<end)
+            if (val==*p++)
+                return kTRUE;
+
+        return kFALSE;
+    }
+    Bool_t MatchSector(Int_t idx, const TArrayI &sector, const TArrayI &aidx) const;
+
+    // This is a trick to remove TH1 entries from the context menu
+    TH1 *Rebin(Int_t =2, const char * ="", const Double_t * =0) { return this; }
+    TH1 *Rebin(Int_t =2, const char * ="") { return this; }
+    void DrawPanel() {}
+
+    Int_t Fill(Axis_t x);
+    Int_t Fill(const char *, Stat_t) { return -1; }
+    void  FillN(Int_t, const Axis_t *, const Double_t *, Int_t =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();
+
+    TObject *Clone(const char *newname="") const;
+
+    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(fUsed[idx], kIsUsed); }
+    void   SetUsed(Int_t idx)      { SETBIT(fUsed[idx], kIsUsed); }
+    void   SetAllUsed()            { fUsed.Reset(BIT(kIsUsed)); }
+
+    UInt_t GetNumUsedSector(const TArrayI &sector, const TArrayI &aidx) const;
+    UInt_t GetNumUsed() const { return GetNumUsedSector(TArrayI(), TArrayI()); }
+    UInt_t GetNumUsedSector(Int_t sector, Int_t aidx) const
+    {
+        return GetNumUsedSector(TArrayI(1, &sector), TArrayI(1, &aidx));
+    }
+
+
+    Int_t Fill(Axis_t x, Axis_t y, Stat_t w);
+    Int_t Fill(Axis_t x, Stat_t w);
+
+    //void     AddPixContent(Int_t idx) const { AddBinContent(idx+1); }
+    //void     AddPixContent(Int_t idx, Stat_t w) const { AddBinContent(idx+1, w); }
+
+    // This is a trick to remove TH1 entries from the context menu
+    /*
+     void Add(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1) { TH1::Add(h1, h2, c1, c2); }
+     void Add(TF1 *h1, Double_t c1=1) { TH1::Add(h1, c1); }
+     void Add(const TH1 *h1, Double_t c1=1) { TH1::Add(h1, c1); }
+     void Divide(TF1 *f1, Double_t c1=1) { TH1::Divide(f1, c1); }
+     void Divide(const TH1 *h1) { TH1::Divide(h1); }
+     void Divide(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option="") { TH1::Divide(h1, h2, c1, c2, option); }
+     void Multiply(TF1 *h1, Double_t c1=1) { TH1::Multiply(h1, c1); }
+     void Multiply(const TH1 *h1) { TH1::Multiply(h1); }
+     void Multiply(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option="") { TH1::Multiply(h1, h2, c1, c2, option); }
+     */
+
+    void FitPanel() { TH1::FitPanel(); }
+
+    virtual Double_t GetPixContent(Int_t idx) const { return GetBinContent(idx+1); }
+    virtual void     AddCamDifference(const MCamEvent &evt, const MCamEvent &evt2, Int_t type=0, Stat_t weight=1);
+    virtual void     AddCamRatio(const MCamEvent &evt, const MCamEvent &evt2, Int_t type=0, Stat_t weight=1);
+    virtual void     AddCamContent(const MCamEvent &evt, Int_t type=0, Stat_t weight=1);
+    virtual void     AddCamContent(const MHCamera &evt, Int_t type=0);
+    virtual void     AddCamContent(const TArrayD &arr, const TArrayC *used=NULL);
+    virtual void     AddCamContent(const MArrayD &arr, const TArrayC *used=NULL);
+    virtual void     SetCamContent(const MCamEvent &evt, Int_t type=0)           { Reset(); AddCamContent(evt, type); }
+    virtual void     SetCamContent(const MHCamera &cam, Int_t type=0)            { Reset(); AddCamContent(cam, type); }
+    virtual void     SetCamContent(const TArrayD &evt, const TArrayC *used=NULL) { Reset(); AddCamContent(evt, used); }
+    virtual void     SetCamContent(const MArrayD &evt, const TArrayC *used=NULL) { Reset(); AddCamContent(evt, used); }
+
+    virtual void     SetCamError(const MCamEvent &evt, Int_t type=0);
+    virtual void     SetUsed(const TArrayC &arr);
+
+    virtual void     AddMedianShift(const MCamEvent &evt, Int_t type=0, Stat_t weight=1);
+    virtual void     AddMeanShift(const MCamEvent &evt, Int_t type=0, Stat_t weight=1);
+
+    virtual void     CntCamContent(const MCamEvent &evt, Double_t threshold, Int_t type=0, Bool_t isabove=kTRUE);
+    virtual void     CntCamContent(const MCamEvent &evt, TArrayD threshold, Int_t type=0, Bool_t isabove=kTRUE);
+    virtual void     CntCamContent(const TArrayD &evt, Double_t threshold, Bool_t ispos=kTRUE);
+    virtual void     CntCamContent(const MCamEvent &event, Int_t type1, const MCamEvent &thresevt, Int_t type2, Double_t threshold, Bool_t isabove);
+
+    virtual void     SetMaxCamContent(const MCamEvent &evt, Int_t type=0);
+    virtual void     SetMinCamContent(const MCamEvent &evt, Int_t type=0);
+
+    Stat_t   GetBinContent(Int_t bin) const;
+    Stat_t   GetBinContent(Int_t binx, Int_t) const { return GetBinContent(binx); }
+    Stat_t   GetBinContent(Int_t binx, Int_t, Int_t) const { return GetBinContent(binx); }
+    Stat_t   GetBinError(Int_t bin) const;
+    Stat_t   GetBinError(Int_t binx, Int_t) const { return GetBinError(binx); }
+    Stat_t   GetBinError(Int_t binx, Int_t, Int_t) const { return GetBinError(binx); }
+
+    Double_t GetMinimum(Bool_t ball) const { return GetMinimumSectors(TArrayI(), TArrayI(), ball); }
+    Double_t GetMaximum(Bool_t ball) const { return GetMaximumSectors(TArrayI(), TArrayI(), ball); }
+
+    Double_t GetMinimum(Double_t /*gt*/) const { return GetMinimumSectors(TArrayI(), TArrayI(), kFALSE); } // FIXME: To be done: Minimum greater than
+    Double_t GetMaximum(Double_t /*lt*/) const { return GetMaximumSectors(TArrayI(), TArrayI(), kFALSE); } // FIXME: To be done: Maximum lower than
+
+    Double_t GetMinimum() const { return GetMinimum(0.0); } // FIXME: To be done: Minimum greater than
+    Double_t GetMaximum() const { return GetMaximum(0.0); } // FIXME: To be done: Maximum lower than
+
+    Double_t GetMinimumSector(Int_t sector, Int_t aidx, Bool_t ball=kFALSE) const
+    {
+        return GetMinimumSectors(TArrayI(1, &sector), TArrayI(1, &aidx), ball);
+    }
+    Double_t GetMaximumSector(Int_t sector, Int_t aidx, Bool_t ball=kFALSE) const
+    {
+        return GetMaximumSectors(TArrayI(1, &sector), TArrayI(1, &aidx), ball);
+    }
+    Double_t GetMinimumSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t ball=kFALSE) const;
+    Double_t GetMaximumSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t ball=kFALSE) const;
+
+    Int_t    GetNumBinsAboveThreshold(Double_t t=0) const;
+    Int_t    GetNumBinsBelowThreshold(Double_t t=0) 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*
+
+    void     Print(Option_t *) const;
+    void     Paint(Option_t *option="");
+    void     Draw(Option_t *option="");
+    void     DrawProjection (Int_t fit=0) const;
+    void     DrawRadialProfile()           const;
+    void     DrawAzimuthProfile()          const;
+
+    void     SavePrimitive(std::ostream &out, Option_t *);
+    void     SavePrimitive(std::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     SetDrawOption(Option_t *option); //*MENU*
+
+    void     SetPalette(Int_t ncolors, Int_t *colors);
+
+    void     SetPrettyPalette(); // *MENU*
+    void     SetDeepBlueSeaPalette(); // *MENU*
+    void     SetInvDeepBlueSeaPalette(); // *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     SetErrorSpread(Bool_t f=kTRUE) { f ? ResetBit(kErrorMean) : SetBit(kErrorMean); } // *TOGGLE* *GETTER=IsErrorSpread
+    Bool_t   IsErrorSpread() const { return !TestBit(kErrorMean); }
+
+    void     SetAbberation(Float_t f=0.0713) { fAbberation=f; } // *MENU*
+
+    void     SetAutoScale() { fMinimum = fMaximum = -1111; } // *MENU*
+    void     SetMinMax(Double_t min=-1111, Double_t max=-1111) { SetMinimum(min); SetMaximum(max); } // *MENU*
+
+    void     AddNotify(TObject *event);
+
+    Stat_t   GetMean(Bool_t ball) const   { return GetMeanSectors(TArrayI(), TArrayI(), ball); }
+    Stat_t   GetMedian(Bool_t ball) const { return GetMedianSectors(TArrayI(), TArrayI(), ball); }
+    Stat_t   GetRMS(Bool_t ball)  const   { return GetRmsSectors(TArrayI(), TArrayI(), ball); }
+    Stat_t   GetDev(Bool_t ball)  const   { return GetDevSectors(TArrayI(), TArrayI(), ball); }
+
+    Stat_t   GetMean(Int_t=0) const   { return GetMeanSectors(TArrayI(), TArrayI(), kFALSE); }
+    Stat_t   GetMedian(Int_t=0) const { return GetMedianSectors(TArrayI(), TArrayI(), kFALSE); }
+    Stat_t   GetRMS(Int_t=0)  const   { return GetRmsSectors(TArrayI(), TArrayI(), kFALSE); }
+    Stat_t   GetDev(Int_t=0)  const   { return GetRmsSectors(TArrayI(), TArrayI(), kFALSE); }
+
+    Stat_t   GetMeanSector(Int_t sector, Int_t aidx, Bool_t ball=kFALSE) const
+    {
+        return GetMeanSectors(TArrayI(1, &sector), TArrayI(1, &aidx), ball);
+    }
+    Stat_t   GetMedianSector(Int_t sector, Int_t aidx, Bool_t ball=kFALSE) const
+    {
+        return GetMedianSectors(TArrayI(1, &sector), TArrayI(1, &aidx), ball);
+    }
+    Stat_t   GetRmsSector(Int_t sector, Int_t aidx, Bool_t ball=kFALSE) const
+    {
+        return GetRmsSectors(TArrayI(1, &sector), TArrayI(1, &aidx), ball);
+    }
+    Stat_t   GetDevSector(Int_t sector, Int_t aidx, Bool_t ball=kFALSE) const
+    {
+        return GetDevSectors(TArrayI(1, &sector), TArrayI(1, &aidx), ball);
+    }
+
+    Stat_t   GetMeanSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all=kFALSE) const;
+    Stat_t   GetMedianSectors(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;
+    Stat_t   GetDevSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all=kFALSE) const;
+
+    UInt_t   GetNumPixels() const;
+
+    TH1D    *Projection(const char *name="_proj", const Int_t nbins=50) const
+    {
+        return ProjectionS(TArrayI(), TArrayI(), name,nbins);
+    }
+    TH1D    *ProjectionS(Int_t sector, Int_t aidx, const char *name="_proj", const Int_t nbins=50) const
+    {
+        return ProjectionS(TArrayI(1, &sector), TArrayI(1, &aidx), name, nbins);
+    }
+    TH1D    *ProjectionS(const TArrayI &sector, const TArrayI &aidx, const char *name="_proj", const Int_t nbins=50) const;
+
+    TProfile *RadialProfile(const char *name="_rad", Int_t nbins=25) const { return  RadialProfileS(TArrayI(), TArrayI(), name, nbins);}
+    TProfile *RadialProfileS(Int_t sector, Int_t aidx, const char *name="_rad", const Int_t nbins=25) const
+    {
+        return RadialProfileS(TArrayI(1, &sector), TArrayI(1, &aidx), name, nbins);
+    }
+    TProfile *RadialProfileS(const TArrayI &sector, const TArrayI &aidx, const char *name="_rad", const Int_t nbins=25) const;
+
+    TProfile *AzimuthProfile(const char *name="_az", Int_t nbins=25) const { return  AzimuthProfileA(TArrayI(), name, nbins);  }
+    TProfile *AzimuthProfile(Int_t aidx, const char *name="_az", const Int_t nbins=25) const
+    {
+        return AzimuthProfileA(TArrayI(1, &aidx), name, nbins);
+    }
+    TProfile *AzimuthProfileA(const TArrayI &aidx, const char *name="_az", const Int_t nbins=25) const;
+    
+    void CamDraw(TCanvas &c, const Int_t x, const Int_t y, 
+                 const Int_t fit, const Int_t rad=0, const Int_t azi=0,
+                 TObject *notify=NULL);             
+    
+    const MGeomCam &GetGeomCam() const { return *fGeomCam; }
+
+    ClassDef(MHCamera, 1) // Displays the magic camera
+};
+
+#endif
+
+/* ------------ OK ---------------
+ virtual void     Browse(TBrowser *b);
+ virtual void     FillRandom(const char *fname, Int_t ntimes=5000);
+ virtual void     FillRandom(TH1 *h, Int_t ntimes=5000);
+
+ virtual Int_t    GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum=0);
+ virtual Axis_t   GetRandom();
+ virtual void     GetStats(Stat_t *stats) const;
+ virtual Stat_t   GetSumOfWeights() const;
+ virtual Int_t    GetSumw2N() const {return fSumw2.fN;}
+ virtual Stat_t   GetRMS(Int_t axis=1) const;
+
+ virtual Int_t    GetNbinsX() const {return fXaxis.GetNbins();}
+ virtual Int_t    GetNbinsY() const {return fYaxis.GetNbins();}
+ virtual Int_t    GetNbinsZ() const {return fZaxis.GetNbins();}
+
+ // ------------- to check -------------------
+
+ virtual Double_t ComputeIntegral();
+ virtual Int_t    DistancetoPrimitive(Int_t px, Int_t py);
+ virtual void     Draw(Option_t *option="");
+ virtual TH1     *DrawCopy(Option_t *option="") const;
+ virtual TH1     *DrawNormalized(Option_t *option="", Double_t norm=1) const;
+ virtual Int_t    BufferEmpty(Bool_t deleteBuffer=kFALSE);
+ virtual void     Eval(TF1 *f1, Option_t *option="");
+ virtual void     ExecuteEvent(Int_t event, Int_t px, Int_t py);
+ virtual void     FillN(Int_t ntimes, const Axis_t *x, const Double_t *w, Int_t stride=1);
+ virtual void     FillN(Int_t, const Axis_t *, const Axis_t *, const Double_t *, Int_t) {;}
+ virtual Int_t    FindBin(Axis_t x, Axis_t y=0, Axis_t z=0);
+ virtual TObject *FindObject(const char *name) const;
+ virtual TObject *FindObject(const TObject *obj) const;
+ virtual Int_t    Fit(const char *formula ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0); // *MENU*
+ virtual Int_t    Fit(TF1 *f1 ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0);
+ virtual void     FitPanel(); // *MENU*
+ TH1             *GetAsymmetry(TH1* h2, Double_t c2=1, Double_t dc2=0);
+ Int_t            GetBufferLength() const {return (Int_t)fBuffer[0];}
+ Int_t            GetBufferSize  () const {return fBufferSize;}
+ const   Double_t *GetBuffer() const {return fBuffer;}
+ static  Int_t    GetDefaultBufferSize();
+ virtual Double_t *GetIntegral() {return fIntegral;}
+
+ TList           *GetListOfFunctions() const { return fFunctions; }
+
+ virtual Int_t    GetNdivisions(Option_t *axis="X") const;
+ virtual Color_t  GetAxisColor(Option_t *axis="X") const;
+ virtual Color_t  GetLabelColor(Option_t *axis="X") const;
+ virtual Style_t  GetLabelFont(Option_t *axis="X") const;
+ virtual Float_t  GetLabelOffset(Option_t *axis="X") const;
+ virtual Float_t  GetLabelSize(Option_t *axis="X") const;
+ virtual Float_t  GetTitleOffset(Option_t *axis="X") const;
+ virtual Float_t  GetTitleSize(Option_t *axis="X") const;
+ virtual Float_t  GetTickLength(Option_t *axis="X") const;
+ virtual Float_t  GetBarOffset() const {return Float_t(0.001*Float_t(fBarOffset));}
+ virtual Float_t  GetBarWidth() const  {return Float_t(0.001*Float_t(fBarWidth));}
+ virtual Int_t    GetContour(Double_t *levels=0);
+ virtual Double_t GetContourLevel(Int_t level) const;
+ virtual Double_t GetContourLevelPad(Int_t level) const;
+
+ virtual void     GetCenter(Axis_t *center) const {fXaxis.GetCenter(center);}
+ TDirectory      *GetDirectory() const {return fDirectory;}
+ virtual Stat_t   GetEntries() const;
+ virtual TF1     *GetFunction(const char *name) const;
+ virtual Int_t    GetDimension() const { return fDimension; }
+ virtual void     GetLowEdge(Axis_t *edge) const {fXaxis.GetLowEdge(edge);}
+ virtual Double_t GetMaximum() const;
+ virtual Int_t    GetMaximumBin() const;
+ virtual Int_t    GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const;
+ virtual Double_t GetMaximumStored() const {return fMaximum;}
+ virtual Double_t GetMinimum() const;
+ virtual Int_t    GetMinimumBin() const;
+ virtual Int_t    GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const;
+ virtual Double_t GetMinimumStored() const {return fMinimum;}
+ virtual Stat_t   GetMean(Int_t axis=1) const;
+ virtual Double_t GetNormFactor() const {return fNormFactor;}
+ virtual char    *GetObjectInfo(Int_t px, Int_t py) const;
+ Option_t        *GetOption() const {return fOption.Data();}
+
+ TVirtualHistPainter *GetPainter();
+
+ TAxis   *GetXaxis() const;
+ TAxis   *GetYaxis() const;
+ TAxis   *GetZaxis() const;
+ virtual Stat_t   Integral(Option_t *option="") const;
+ virtual Stat_t   Integral(Int_t binx1, Int_t binx2, Option_t *option="") const;
+ virtual Stat_t   Integral(Int_t, Int_t, Int_t, Int_t, Option_t * ="") const {return 0;}
+ virtual Stat_t   Integral(Int_t, Int_t, Int_t, Int_t, Int_t, Int_t, Option_t * ="" ) const {return 0;}
+ virtual Double_t KolmogorovTest(TH1 *h2, Option_t *option="") const;
+ virtual void     LabelsDeflate(Option_t *axis="X");
+ virtual void     LabelsInflate(Option_t *axis="X");
+ virtual void     LabelsOption(Option_t *option="h", Option_t *axis="X");
+ virtual Int_t    Merge(TCollection *list);
+ virtual void     Multiply(TF1 *h1, Double_t c1=1);
+ virtual void     Multiply(const TH1 *h1);
+ virtual void     Multiply(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option=""); // *MENU*
+ virtual void     Paint(Option_t *option="");
+ virtual void     Print(Option_t *option="") const;
+ virtual void     PutStats(Stat_t *stats);
+ virtual TH1     *Rebin(Int_t ngroup=2, const char*newname="");  // *MENU*
+ virtual void     RebinAxis(Axis_t x, Option_t *axis="X");
+ virtual void     Rebuild(Option_t *option="");
+ virtual void     RecursiveRemove(TObject *obj);
+ virtual void     Reset(Option_t *option="");
+ virtual void     SavePrimitive(ofstream &out, Option_t *option);
+ virtual void     Scale(Double_t c1=1);
+ virtual void     SetAxisColor(Color_t color=1, Option_t *axis="X");
+ virtual void     SetAxisRange(Axis_t xmin, Axis_t xmax, Option_t *axis="X");
+ virtual void     SetBarOffset(Float_t offset=0.25) {fBarOffset = Short_t(1000*offset);}
+ virtual void     SetBarWidth(Float_t width=0.5) {fBarWidth = Short_t(1000*width);}
+ virtual void     SetBinContent(Int_t bin, Stat_t content);
+ virtual void     SetBinContent(Int_t binx, Int_t biny, Stat_t content);
+ virtual void     SetBinContent(Int_t binx, Int_t biny, Int_t binz, Stat_t content);
+ virtual void     SetBinError(Int_t bin, Stat_t error);
+ virtual void     SetBinError(Int_t binx, Int_t biny, Stat_t error);
+ virtual void     SetBinError(Int_t binx, Int_t biny, Int_t binz, Stat_t error);
+ virtual void     SetBins(Int_t nx, Axis_t xmin, Axis_t xmax);
+ virtual void     SetBins(Int_t nx, Axis_t xmin, Axis_t xmax, Int_t ny, Axis_t ymin, Axis_t ymax);
+ virtual void     SetBins(Int_t nx, Axis_t xmin, Axis_t xmax, Int_t ny, Axis_t ymin, Axis_t ymax,
+ Int_t nz, Axis_t zmin, Axis_t zmax);
+ virtual void     SetBinsLength(Int_t = -1) { } //refefined in derived classes
+ virtual void     SetBuffer(Int_t buffersize, Option_t *option="");
+ virtual void     SetCellContent(Int_t binx, Int_t biny, Stat_t content);
+ virtual void     SetCellError(Int_t binx, Int_t biny, Stat_t content);
+ virtual void     SetContent(const Stat_t *content);
+ virtual void     SetContour(Int_t nlevels, const Double_t *levels=0);
+ virtual void     SetContourLevel(Int_t level, Double_t value);
+ static  void     SetDefaultBufferSize(Int_t buffersize=1000);
+ virtual void     SetDirectory(TDirectory *dir);
+ virtual void     SetEntries(Stat_t n) {fEntries = n;};
+ virtual void     SetError(const Stat_t *error);
+ virtual void     SetLabelColor(Color_t color=1, Option_t *axis="X");
+ virtual void     SetLabelFont(Style_t font=62, Option_t *axis="X");
+ virtual void     SetLabelOffset(Float_t offset=0.005, Option_t *axis="X");
+ virtual void     SetLabelSize(Float_t size=0.02, Option_t *axis="X");
+
+ virtual void     SetMaximum(Double_t maximum=-1111); // *MENU*
+ virtual void     SetMinimum(Double_t minimum=-1111); // *MENU*
+ virtual void     SetName(const char *name); // *MENU*
+ virtual void     SetNameTitle(const char *name, const char *title);
+ virtual void     SetNdivisions(Int_t n=510, Option_t *axis="X");
+ virtual void     SetNormFactor(Double_t factor=1) {fNormFactor = factor;}
+ virtual void     SetStats(Bool_t stats=kTRUE);
+ virtual void     SetOption(Option_t *option=" ") {fOption = option;}
+ virtual void     SetTickLength(Float_t length=0.02, Option_t *axis="X");
+ virtual void     SetTitleOffset(Float_t offset=1, Option_t *axis="X");
+ virtual void     SetTitleSize(Float_t size=0.02, Option_t *axis="X");
+ virtual void     SetTitle(const char *title);
+ virtual void     SetXTitle(const char *title) {fXaxis.SetTitle(title);}
+ virtual void     SetYTitle(const char *title) {fYaxis.SetTitle(title);}
+ virtual void     SetZTitle(const char *title) {fZaxis.SetTitle(title);}
+ virtual void     Smooth(Int_t ntimes=1); // *MENU*
+ static  void     SmoothArray(Int_t NN, Double_t *XX, Int_t ntimes=1);
+ static Double_t  SmoothMedian(Int_t n, Double_t *a);
+ virtual void     Sumw2();
+ void             UseCurrentStyle();
+
+ ClassDef(TH1,4)  //1-Dim histogram base class
+};
+
+*/
Index: branches/Mars_McMismatchStudy/mhist/MHCerPhotEvt.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCerPhotEvt.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCerPhotEvt.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHCerPhotEvt.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCerPhotEvt.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCerPhotEvt.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHCompProb.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCompProb.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCompProb.cc	(revision 17960)
@@ -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 "MDataPhrase.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)
+{
+    MDataPhrase &chain = *new MDataPhrase(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: branches/Mars_McMismatchStudy/mhist/MHCompProb.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHCompProb.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHCompProb.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHEvent.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHEvent.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHEvent.cc	(revision 17960)
@@ -0,0 +1,440 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <TPaveText.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+
+#include "MHCamera.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MGeomCam.h"
+#include "MSignalCam.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"
+#include "MImgCleanStd.h"
+#include "MTriggerPattern.h"
+
+ClassImp(MHEvent);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MHEvent::MHEvent(EventType_t type) : fHist(NULL), fType(type),
+    fMinimum(-1111), fMaximum(-1111)
+{
+    fName = "MHEvent";
+    fTitle = "Single Event display task";
+
+    fClone   = new MRawEvtData("MHEventData");
+    fTrigCpy = new MTriggerPattern;
+}
+
+// --------------------------------------------------------------------------
+//
+MHEvent::~MHEvent()
+{
+    if (fHist)
+        delete fHist;
+
+    delete fClone;
+    delete fTrigCpy;
+}
+
+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");
+    fTime        = (MTime*)plist->FindObject("MTime");
+    fTrigger     = (MTriggerPattern*)plist->FindObject("MTriggerPattern");
+
+    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);
+
+    fHist->SetMinimum(fMinimum);
+    fHist->SetMaximum(fMaximum);
+
+    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 kEvtSignalUncleaned:
+        fHist->SetName("Signal");
+        fHist->SetYTitle("S [au]");
+        break;
+    case kEvtPedestal:
+        fHist->SetName("Pedestal");
+        fHist->SetYTitle("P [au]");
+        break;
+    case kEvtPedestalRMS:
+        fHist->SetName("Pedestal RMS");
+        fHist->SetYTitle("\\sigma_{P} [au]");
+        break;
+    case kEvtPedPhot:
+        fHist->SetName("Pedestal");
+        fHist->SetYTitle("P [\\gamma]");
+        break;
+    case kEvtPedPhotRMS:
+        fHist->SetName("Pedestal RMS");
+        fHist->SetYTitle("\\sigma_{P} [\\gamma]");
+        break;
+    case kEvtCleaningLevels:
+        if (!fImgCleanStd)
+        {
+            *fLog << err << "MImgCleanStd not found... aborting." << endl;
+            return kFALSE;
+        }
+        fHist->SetName("CleanLevels");
+        fHist->SetYTitle("L");
+        break;
+    case kEvtCleaningData:
+        fHist->SetName("CleanData");
+        fHist->SetYTitle("L");
+        break;
+     case kEvtIdxMax:
+        fHist->SetName("Max Slice Idx");
+        fHist->SetYTitle("t [slice id]");
+	fHist->SetPrettyPalette();
+        break;
+     case kEvtArrTime:
+     case kEvtArrTimeCleaned:
+        fHist->SetName("Arrival Time");
+        fHist->SetYTitle("t [slice id]");
+	fHist->SetPrettyPalette();
+        break;
+     case kEvtTrigPix:
+        fHist->SetName("Triggered pix");
+        fHist->SetYTitle("ON/OFF");
+        fHist->SetPrettyPalette();
+        break;
+     case kEvtIslandIndex:
+        fHist->SetName("Island Index");
+        fHist->SetYTitle("Index");
+	fHist->SetPrettyPalette();
+        break;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The geometry read from the RunHeaders might have changed. This does not
+// effect anything in PreProcess. So we set a new geometry. We don't move
+// this away from PreProcess to support also loops without calling ReInit.
+//
+Bool_t MHEvent::ReInit(MParList *plist)
+{
+    MGeomCam *cam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHist->SetGeometry(*cam);
+
+    return kTRUE;
+}
+
+Int_t MHEvent::Fill(const MParContainer *par, const Stat_t weight)
+{
+    if (fHist->IsFreezed())
+        return kTRUE;
+
+    if (!par)
+    {
+        *fLog << err << "ERROR - par==NULL... abort." << endl;
+        return kERROR;
+    }
+
+    const MCamEvent *event = dynamic_cast<const MCamEvent*>(par);
+    if (!event)
+    {
+        *fLog << err << par->GetDescriptor() << " doesn't inherit from MCamEvent... abort." << endl;
+        return kERROR;
+    }
+
+    if (fTrigger)
+        fTrigger->Copy(*fTrigCpy);
+
+    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 kEvtSignalUncleaned:
+        fHist->SetCamContent(*event, 12);
+        break;
+    case kEvtPedestal:
+        fHist->SetCamContent(*event, 0);
+        break;
+    case kEvtPedestalRMS:
+        fHist->SetCamContent(*event, 2);
+        break;
+    case kEvtPedPhot:
+        fHist->SetCamContent(*event, 4);
+        break;
+    case kEvtPedPhotRMS:
+        fHist->SetCamContent(*event, 5);
+        break;
+    case kEvtCleaningLevels:
+        {
+            TArrayF lvl(2);
+            lvl[0] = fImgCleanStd->GetCleanLvl2();
+            lvl[1] = fImgCleanStd->GetCleanLvl1();
+            fHist->SetCamContent(*event, 0);
+            fHist->SetLevels(lvl);
+        }
+        break;
+    case kEvtCleaningData:
+        fHist->SetCamContent(*event, 0);
+        break;
+//    case kEvtIdxMax:
+//        fHist->SetCamContent(*event, 3/*5*/);
+//        break;
+    case kEvtArrTime:
+        fHist->SetCamContent(*event, 6);
+        break; 
+    case kEvtArrTimeCleaned:
+        fHist->SetCamContent(*event, 8);
+        break; 
+    case kEvtTrigPix:
+        fHist->SetCamContent(*event, 0);
+        break; 
+    case kEvtIslandIndex:
+        fHist->SetCamContent(*event, 5);
+        break;
+    default:
+        *fLog << "ERROR - Case " << (int)fType << " not implemented..." << endl;
+    }
+
+    TString s;
+    if (fRawEvtHeader)
+    {
+        s += "Event #";
+        s += fRawEvtHeader->GetDAQEvtNumber();
+    }
+
+    if (fRawEvtHeader && fRawRunHeader)
+        s += " FileId #";
+
+    if (fRawEvtHeader)
+        s += fRawRunHeader->GetStringID();
+
+    if (fTime)
+    {
+        s += " (";
+        s += fTime->GetString();
+        s += ")";
+    }
+
+    if (fMcEvt)
+        s = fMcEvt->GetDescription(s);
+
+    gPad=NULL;
+    fHist->SetTitle(s);
+
+    return kTRUE;
+}
+
+void MHEvent::Paint(Option_t *o)
+{
+    TVirtualPad *pad = gPad;
+
+    if (TString(o).IsNull())
+    {
+        pad->GetPad(2)->cd(1);
+        if (gPad->FindObject("Proj"))
+        {
+            TH1 *h=fHist->Projection("Proj");
+            if (h->GetMaximum()>0)
+                gPad->SetLogy();
+        }
+
+        pad->GetPad(2)->cd(2);
+        if (gPad->FindObject("ProfRad"))
+            fHist->RadialProfile("ProfRad");
+
+        pad->GetPad(2)->cd(3);
+        if (gPad->FindObject("ProfAz"))
+            fHist->AzimuthProfile("ProfAz");
+    }
+
+    if (TString(o)=="1")
+    {
+        const Double_t r = fHist->GetGeometry()->GetMaxRadius();
+        TPaveText s4(0.82*r, -r, 0.90*r, -0.92*r, "br");
+        TPaveText s3(0.74*r, -r, 0.82*r, -0.92*r, "br");
+        TPaveText s2(0.66*r, -r, 0.74*r, -0.92*r, "br");
+        TPaveText s1(0.58*r, -r, 0.66*r, -0.92*r, "br");
+        TPaveText s0(0.50*r, -r, 0.58*r, -0.92*r, "br");
+        s0.SetBorderSize(1);
+        s1.SetBorderSize(1);
+        s2.SetBorderSize(1);
+        s3.SetBorderSize(1);
+        s4.SetBorderSize(1);
+        s0.AddText("P");
+        s1.AddText("C");
+        s2.AddText("1");
+        s3.AddText("2");
+        s4.AddText("S");
+
+        const Byte_t pat = fTrigCpy->GetUnprescaled();
+
+        s0.SetFillColor(pat&MTriggerPattern::kPedestal    ? kBlue : kWhite);
+        s1.SetFillColor(pat&MTriggerPattern::kCalibration ? kBlue : kWhite);
+        s2.SetFillColor(pat&MTriggerPattern::kTriggerLvl1 ? kBlue : kWhite);
+        s3.SetFillColor(pat&MTriggerPattern::kTriggerLvl2 ? kBlue : kWhite);
+        s4.SetFillColor(pat&MTriggerPattern::kSumTrigger  ? kBlue : kWhite);
+
+        s0.Paint();
+        s1.Paint();
+        s2.Paint();
+        s3.Paint();
+        s4.Paint();
+    }
+}
+
+void MHEvent::Draw(Option_t *)
+{
+    if (!fHist)
+    {
+        *fLog << warn << "MHEvent::Draw - fHist==NULL not initialized." << endl;
+        return;
+    }
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    pad->Divide(2,1);
+
+    pad->cd(1);
+    gPad->SetPad(0.01, 0.01, 0.75, 0.99);
+    gPad->SetBorderMode(0);
+    fHist->Draw();
+
+    AppendPad("1");
+
+    pad->cd(2);
+    gPad->SetPad(0.75, 0.01, 0.99, 0.99);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,3);
+
+    pad = gPad;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+
+    TH1 *h = fHist->Projection("Proj", 50);
+    h->SetTitle("Projection");
+    h->SetBit(kCanDelete);
+    h->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+
+    h = (TH1*)fHist->RadialProfile("ProfRad", 20);
+    h->SetTitle("Radial Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = (TH1*)fHist->AzimuthProfile("ProfAz", 30);
+    h->SetTitle("Azimuth Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+}
+
Index: branches/Mars_McMismatchStudy/mhist/MHEvent.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHEvent.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHEvent.h	(revision 17960)
@@ -0,0 +1,75 @@
+#ifndef MARS_MHEvent
+#define MARS_MHEvent
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHCamera;
+class MRawEvtData;
+class MRawRunHeader;
+class MRawEvtHeader;
+
+class MTime;
+class MMcEvt;
+class MMcTrig;
+class MSignalCam;
+class MImgCleanStd;
+class MTriggerPattern;
+
+class MHEvent : public MH
+{
+public:
+    enum EventType_t {
+        kEvtSignalRaw, kEvtSignalDensity, kEvtSignalUncleaned,
+        kEvtPedestal, kEvtPedestalRMS,
+        kEvtPedPhot, kEvtPedPhotRMS,
+        kEvtCleaningLevels, kEvtCleaningData,
+        kEvtIdxMax, kEvtArrTime, kEvtArrTimeCleaned,
+        kEvtTrigPix, kEvtIslandIndex
+    };
+
+private:
+    MRawEvtData      *fRawEvtData;    //!
+    MRawRunHeader    *fRawRunHeader;  //!
+    MRawEvtHeader    *fRawEvtHeader;  //!
+
+    MTime            *fTime;          //!
+    MMcEvt           *fMcEvt;         //!
+    MMcTrig          *fMcTrig;        //!
+    MSignalCam       *fCerPhotEvt;    //!
+    MImgCleanStd     *fImgCleanStd;   //!
+    MTriggerPattern  *fTrigger;       //!
+
+    MRawEvtData      *fClone;         //->
+    MTriggerPattern  *fTrigCpy;       //->
+
+    MHCamera *fHist;
+
+    EventType_t fType;
+
+    Double_t fMinimum;
+    Double_t fMaximum;
+
+    TH1 *GetHistByName(const TString name) const { return (TH1*)fHist; }
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t weight=1);
+    Bool_t ReInit(MParList *par);
+
+public:
+    MHEvent(EventType_t type=kEvtSignalRaw);
+    ~MHEvent();
+
+    void SetMinimum(Double_t min=-1111) { fMinimum=min; }
+    void SetMaximum(Double_t max=-1111) { fMaximum=max; }
+
+    MHCamera *GetHist() { return fHist; }
+
+    void Draw(Option_t *o="");
+    void Paint(Option_t *o="");
+
+    ClassDef(MHEvent, 1)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhist/MHFadcCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFadcCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFadcCam.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHFadcCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFadcCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFadcCam.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHFadcPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFadcPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFadcPix.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHFadcPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFadcPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFadcPix.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHFindSignificance.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFindSignificance.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFindSignificance.cc	(revision 17960)
@@ -0,0 +1,2052 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek,  July 2003      <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHFindSignificance
+//
+// determines the significance of a gamma signal in an |alpha| plot
+// 
+//
+// Input : TH1 histogram of |alpha| : with 0 < |alpha| < 90 degrees
+//         alphamin, alphamax :     defining the background region
+//         alphasig           :     defining the signal region for which
+//                                  the significance is calculated
+//         degree : the degree of the polynomial to be fitted to the background
+//                  ( a0 + a1*x + a2*x**2 + a3*x**3 + ...) 
+//
+// Output : 
+//
+//   - polynomial which describes the background in the background region
+//   - the number of events in the signal region (Non)
+//     the number of background events in the signal region (Nbg)
+//   - the number of excess events in the signal region (Nex = Non - Nbg)
+//   - thew effective number of background events (Noff), and gamma :
+//     Nbg = gamma * Noff
+//   - the significance of the gamma signal according to Li & Ma               
+//
+//
+// call member function 'FindSigma' 
+//      to fit the background and to determine the significance  
+//
+// call the member function 'SigmaVsAlpha'
+//      to determine the significance as a function of alphasig
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHFindSignificance.h"
+
+#include <fstream>
+#include <math.h>
+
+#include <TArrayD.h>
+#include <TArrayI.h>
+#include <TH1.h>
+#include <TF1.h>
+#include <TCanvas.h>
+#include <TFitter.h>
+#include <TMinuit.h>
+#include <TPaveText.h>
+#include <TStyle.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMinuitInterface.h"
+
+
+ClassImp(MHFindSignificance);
+
+using namespace std;
+
+const TString MHFindSignificance::gsDefName  = "MHFindSignificance";
+const TString MHFindSignificance::gsDefTitle = "Find Significance in alpha plot";
+
+
+
+// --------------------------------------------------------------------------
+//
+// fcnpoly
+//
+// calculates the chi2 for the fit of the polynomial function 'poly' 
+// to the histogram 'fhist'
+//
+// it is called by CallMinuit() (which is called in FitPolynomial()) 
+//
+// bins of fhist with huge errors are ignored in the calculation of the chi2
+// (the huge errors were set in 'FitPolynomial()')
+//
+
+static void fcnpoly(Int_t &npar, Double_t *gin, Double_t &f, 
+                    Double_t *par, Int_t iflag)
+{
+    TH1 *fhist = (TH1*)gMinuit->GetObjectFit();
+    TF1 *fpoly = fhist->GetFunction("Poly");    
+
+
+    //-------------------------------------------
+
+    Double_t chi2 = 0.0;
+
+    Int_t nbins = fhist->GetNbinsX();
+    Int_t mbins = 0;
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      Double_t content = fhist->GetBinContent(i);
+      Double_t error   = fhist->GetBinError(i);
+      Double_t center  = fhist->GetBinCenter(i);
+
+      //-----------------------------
+      // ignore unwanted points
+      if (error > 1.e19)
+        continue;
+
+      if (content <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero content; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      if (error <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero error; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      //-----------------------------
+      mbins++;
+
+      Double_t fu;
+      fu = fpoly->EvalPar(&center, par);
+
+      // the fitted function must not be negative
+      if (fu <= 0.0)
+      {
+        chi2 = 1.e10;
+        break;
+      }
+
+      Double_t temp = (content - fu) / error;
+      chi2 += temp*temp;
+    }
+
+    //-------------------------------------------
+
+    f = chi2;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+// --------------------------------------------------------------------------
+//
+// fcnpolygauss
+//
+// calculates the chi2 for the fit of the (polynomial+Gauss) function 
+// 'PolyGauss' to the histogram 'fhist'
+//
+// it is called by CallMinuit() (which is called in FitGaussPoly()) 
+//
+// bins of fhist with huge errors are ignored in the calculation of the chi2
+// (the huge errors were set in 'FitGaussPoly()')
+//
+
+static void fcnpolygauss(Int_t &npar, Double_t *gin, Double_t &f, 
+                         Double_t *par, Int_t iflag)
+{
+    TH1 *fhist = (TH1*)gMinuit->GetObjectFit();
+    TF1 *fpolygauss = fhist->GetFunction("PolyGauss");    
+
+
+    //-------------------------------------------
+
+    Double_t chi2 = 0.0;
+
+    Int_t nbins = fhist->GetNbinsX();
+    Int_t mbins = 0;
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      Double_t content = fhist->GetBinContent(i);
+      Double_t error   = fhist->GetBinError(i);
+      Double_t center  = fhist->GetBinCenter(i);
+
+      //-----------------------------
+      // ignore unwanted points
+      if (error > 1.e19)
+        continue;
+
+      if (content <= 0.0)
+      {
+        gLog << "fcnpolygauss : bin with zero content; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      if (error <= 0.0)
+      {
+        gLog << "fcnpolygauss : bin with zero error; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      //-----------------------------
+      mbins++;
+
+      Double_t fu;
+      fu = fpolygauss->EvalPar(&center, par);
+
+      // the fitted function must not be negative
+      if (fu <= 0.0)
+      {
+        chi2 = 1.e10;
+        break;
+      }
+
+      Double_t temp = (content - fu) / error;
+      chi2 += temp*temp;
+    }
+
+    //-------------------------------------------
+
+    f = chi2;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Constructor
+//
+MHFindSignificance::MHFindSignificance(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fSigVsAlpha = NULL;
+
+    fPoly   = NULL;
+    fGPoly  = NULL;
+    fGBackg = NULL;
+
+    fHist     = NULL;
+    fHistOrig = NULL;
+
+    // allow rebinning of the alpha plot
+    fRebin = kTRUE;
+
+    // allow reducing the degree of the polynomial
+    fReduceDegree = kTRUE;
+
+    fCanvas = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. 
+//
+// =====>  it is not clear why one obtains sometimes a segmentation violation
+//         when the destructor is active     <=======================
+//
+// therefore the 'return'statement
+//
+
+MHFindSignificance::~MHFindSignificance()
+{
+  return;
+
+  *fLog << "destructor of MHFindSignificance is called" << endl;
+ 
+    //delete fHist;
+
+    delete fSigVsAlpha;
+    delete fPoly;
+    delete fGPoly;
+    delete fGBackg;
+    //delete fCanvas;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fRebin 
+//
+//  if flag is kTRUE rebinning of the alpha plot is allowed
+//
+//
+void MHFindSignificance::SetRebin(Bool_t b)
+{
+  fRebin = b;
+
+  *fLog << "MHFindSignificance::SetRebin; flag fRebin set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fReduceDegree 
+//
+//  if flag is kTRUE reducing of the degree of the polynomial is allowed
+//
+//
+void MHFindSignificance::SetReduceDegree(Bool_t b)
+{
+  fReduceDegree = b;
+
+  *fLog << "MHFindSignificance::SetReduceDegree; flag fReduceDegree set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  FindSigma
+//
+//  calls FitPolynomial     to fit the background in the background region
+//  calls DetExcess         to determine the number of excess events
+//                          using an extrapolation of the polynomial
+//                          into the signal region
+//  calls SigmaLiMa         to determine the significance of the gamma signal
+//                          in the range |alpha| < alphasig
+//  calls FitGaussPoly      to fit a (polynomial+Gauss) function in the
+//                          whole |alpha| region
+//
+//
+Bool_t MHFindSignificance::FindSigma(TH1 *fhist,  Double_t alphamin,
+       Double_t alphamax, Int_t degree, Double_t alphasig, 
+       Bool_t drawpoly,   Bool_t fitgauss, Bool_t print)
+{
+  //*fLog << "MHFindSignificance::FindSigma;" << endl;
+
+  fHistOrig = fhist;
+
+  fHist = (TH1*)fHistOrig->Clone();
+  fHist->SetName(fhist->GetName());
+  if ( !fHist )
+  {
+    *fLog << "MHFindSignificance::FindSigma; Clone of histogram could not be generated" 
+          << endl;
+    return kFALSE;
+  }
+  
+  fHist->Sumw2();
+  //fHist->SetNameTitle("Alpha", "alpha plot");
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+  fHist->UseCurrentStyle();
+
+  fAlphamin = alphamin;
+  fAlphamax = alphamax;
+  fAlphammm = (alphamin+alphamax)/2.0;
+  fDegree   = degree;
+  fAlphasig = alphasig;
+
+  fDraw     = drawpoly;
+  fFitGauss = fitgauss;
+
+
+  //--------------------------------------------
+  // fit a polynomial in the background region
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling FitPolynomial()" << endl;
+  if ( !FitPolynomial() )
+  {
+    *fLog << "MHFindSignificance::FindSigma; FitPolynomial failed"
+	  << endl;  
+    return kFALSE;
+  }
+
+
+  //--------------------------------------------
+  // calculate the number of excess events in the signal region
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling DetExcess()" << endl;
+  if ( !DetExcess() )
+  {
+    *fLog << "MHFindSignificance::FindSigma; DetExcess failed"
+	  << endl;  
+    return kFALSE;
+  }
+
+
+  //--------------------------------------------
+  // calculate the significance of the excess
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling SigmaLiMa()" << endl;
+  Double_t siglima = 0.0;
+  if ( !SigmaLiMa(fNon, fNoff, fGamma, &siglima) )
+  {
+    *fLog << "MHFindSignificance::FindSigma; SigmaLiMa failed"
+	  << endl;  
+    return kFALSE;
+  }
+  fSigLiMa = siglima;
+
+  //--------------------------------------------
+  // calculate the error of the number of excess events
+
+  fdNex = fNex / fSigLiMa;
+
+
+  //--------------------------------------------
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling PrintPoly()" << endl;
+  if (print)
+    PrintPoly();
+
+
+  //--------------------------------------------
+  // fit a (polynomial + Gauss) function
+
+  if (fFitGauss)
+  {
+    //--------------------------------------------------
+    // delete objects from this fit
+    // in order to have independent starting conditions for the next fit
+
+      delete gMinuit;
+      gMinuit = NULL;
+    //--------------------------------------------------
+
+      //*fLog << "MHFindSignificance::FindSigma;  calling FitGaussPoly()" 
+      //      << endl;
+    if ( !FitGaussPoly() )
+    {
+      *fLog << "MHFindSignificance::FindSigma; FitGaussPoly failed"  
+      	    << endl;  
+      return kFALSE;
+    }
+
+    if (print)
+    {
+      //*fLog << "MHFindSignificance::FindSigma;  calling PrintPolyGauss()" 
+      //      << endl;
+      PrintPolyGauss();
+    }
+  }
+
+  //--------------------------------------------------
+  // draw the histogram if requested
+
+  if (fDraw)
+  {
+    //*fLog << "MHFindSignificance::FindSigma;  calling DrawFit()" << endl;
+    if ( !DrawFit() )
+    {
+      *fLog << "MHFindSignificance::FindSigma; DrawFit failed"  
+      	    << endl;  
+      return kFALSE;
+    }
+  }
+
+
+  //--------------------------------------------------
+  // delete objects from this fit
+  // in order to have independent starting conditions for the next fit
+
+    delete gMinuit;
+    gMinuit = NULL;
+  //--------------------------------------------------
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  SigmaVsAlpha  (like FindSigma. However, alphasig is scanned and
+//                 the significance is plotted versus alphasig)
+//
+//  calls FitPolynomial     to fit the background in the background region
+//
+//  scan alphasig; for a given alphasig :
+//       calls DetExcess    to determine the number of excess events
+//       calls SigmaLiMa    to determine the significance of the gamma signal
+//                          in the range fAlphalow < |alpha| < alphasig
+//
+
+Bool_t MHFindSignificance::SigmaVsAlpha(TH1 *fhist,  Double_t alphamin,
+                    Double_t alphamax, Int_t degree, Bool_t print)
+{
+  //*fLog << "MHFindSignificance::SigmaVsAlpha;" << endl;
+
+  fHistOrig = fhist;
+
+  fHist = (TH1*)fHistOrig->Clone();
+  fHist->SetName(fhist->GetName());
+  fHist->Sumw2();
+  //fHist->SetNameTitle("alpha", "alpha plot");
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+  fHist->UseCurrentStyle();
+
+  fAlphamin = alphamin;
+  fAlphamax = alphamax;
+  fAlphammm = (alphamin+alphamax)/2.0;
+  fDegree   = degree;
+
+
+  //--------------------------------------------
+  // fit a polynomial in the background region
+
+  //*fLog << "MHFindSignificance::SigmaVsAlpha  calling FitPolynomial()" 
+  //      << endl;
+  if ( !FitPolynomial() )  
+    {
+      *fLog << "MHFindSignificance::SigmaVsAlpha;  FitPolynomial() failed" 
+            << endl;
+      return kFALSE;
+    }
+
+
+  //--------------------------------------------
+  // loop over different signal regions
+
+  Int_t    nsteps    =  15;
+
+  fSigVsAlpha = new TH1D("SigVsAlpha","Sigma vs Alpha", nsteps, 0.0, alphamin);
+  fSigVsAlpha->SetXTitle("upper edge of signal region in |alpha|  [\\circ]");
+  fSigVsAlpha->SetYTitle("Significance of gamma signal");
+
+  for (Int_t i=1; i<=nsteps; i++)
+  {
+    fAlphasig = fSigVsAlpha->GetBinCenter(i);
+
+    if ( !DetExcess() )
+    {
+      *fLog << "MHFindSignificance::SigmaVsAlpha;  DetExcess() failed" << endl;
+      continue;
+    }
+
+    Double_t siglima = 0.0;
+    if ( !SigmaLiMa(fNon, fNoff, fGamma, &siglima) )
+    {
+      *fLog << "MHFindSignificance::SigmaVsAlpha;  SigmaLiMa() failed" << endl;
+      continue;
+    }
+
+    fdNex = fNex / siglima;
+    fSigVsAlpha->SetBinContent(i, siglima);
+
+    if (print)
+      PrintPoly();
+  }
+
+  //--------------------------------------------
+  // plot significance versus alphasig
+ 
+  TCanvas *ccc = new TCanvas("SigVsAlpha", "Sigma vs Alpha", 600, 600);
+ 
+  gROOT->SetSelectedPad(NULL);
+  gStyle->SetPadLeftMargin(0.05);
+
+  ccc->cd();
+  fSigVsAlpha->DrawCopy();
+
+  ccc->Modified();
+  ccc->Update();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  FitPolynomial
+//
+//  - create a clone 'fHist' of the |alpha| distribution 'fHistOrig'
+//  - fit a polynomial of degree 'fDegree' to the alpha distribution 
+//    'fHist' in the region alphamin < |alpha| < alphamax
+//
+//  in pathological cases the histogram is rebinned before fitting
+//     (this is done only if fRebin is kTRUE)
+//
+//  if the highest coefficient of the polynomial is compatible with zero
+//     the fit is repeated with a polynomial of lower degree
+//     (this is done only if fReduceDegree is kTRUE)
+//
+//
+Bool_t MHFindSignificance::FitPolynomial()
+{
+  //--------------------------------------------------
+  // check the histogram :
+  //       - calculate initial values of the parameters
+  //       - check for bins with zero entries
+  //       - set minimum errors
+  //       - save the original errors
+  //       - set errors huge outside the fit range
+  //         (in 'fcnpoly' points with huge errors will be ignored)
+
+
+  Double_t dummy = 1.e20;
+
+  Double_t mean;
+  Double_t rms;
+  Double_t nclose;
+  Double_t nfar;
+  Double_t a2init = 0.0;
+  TArrayD  saveError;
+
+  Int_t nbins;
+  Int_t nrebin = 1;
+
+  //----------------   start while loop for rebinning   -----------------
+  while(1)
+  {
+
+  fNzero   = 0;
+  fMbins   = 0;
+  fMlow    = 0;
+  fNbgtot  = 0.0;
+
+  fAlphami =  10000.0;
+  fAlphamm =  10000.0;
+  fAlphama = -10000.0;
+
+  mean   = 0.0;
+  rms    = 0.0;
+  nclose = 0.0;
+  nfar   = 0.0;
+
+  nbins = fHist->GetNbinsX();
+  saveError.Set(nbins);
+
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    saveError[i-1] = fHist->GetBinError(i);
+
+    // bin should be completely contained in the fit range
+    // (fAlphamin, fAlphamax)
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+
+    if ( xlo >= fAlphamin-fEps  &&  xlo <= fAlphamax+fEps  &&
+	 xup >= fAlphamin-fEps  &&  xup <= fAlphamax+fEps     )
+    {
+      fMbins++;
+
+      if ( xlo < fAlphami )
+        fAlphami = xlo;
+
+      if ( xup > fAlphama )
+        fAlphama = xup;
+
+      Double_t content = fHist->GetBinContent(i);
+      fNbgtot += content;
+
+      mean += content;
+      rms  += content*content;
+
+      // count events in low-alpha and high-alpha region
+      if ( xlo >= fAlphammm-fEps  &&  xup >= fAlphammm-fEps)
+      {
+        nfar   += content;
+        if ( xlo < fAlphamm )
+          fAlphamm = xlo;
+        if ( xup < fAlphamm )
+          fAlphamm = xup; 
+      }
+      else
+      {
+        nclose += content;
+        if ( xlo > fAlphamm )
+          fAlphamm = xlo;
+        if ( xup > fAlphamm )
+          fAlphamm = xup; 
+      }
+
+      // count bins with zero entry
+      if (content <= 0.0)
+        fNzero++;
+     
+      // set minimum error
+      if (content < 9.0)
+      {
+        fMlow += 1;
+        fHist->SetBinError(i, 3.0);
+      }
+
+      //*fLog << "Take : i, content, error = " << i << ",  " 
+      //      << fHist->GetBinContent(i) << ",  "
+      //      << fHist->GetBinError(i)   << endl;
+
+      continue;
+    }    
+    // bin is not completely contained in the fit range : set error huge
+
+    fHist->SetBinError(i, dummy);
+
+    //*fLog << "Omit : i, content, error = " << i << ",  " 
+    //      << fHist->GetBinContent(i) << ",  " << fHist->GetBinError(i) 
+    //      << endl;
+
+  }
+
+  // mean of entries/bin in the fit range
+  if (fMbins > 0)
+  {
+    mean /= ((Double_t) fMbins);
+    rms  /= ((Double_t) fMbins);
+  }
+
+  rms = sqrt( rms - mean*mean );
+
+  // if there are no events in the background region
+  //    there is no reason for rebinning
+  //    and this is the condition for assuming a constant background (= 0)
+  if (mean <= 0.0)
+    break;
+
+  Double_t helpmi = fAlphami*fAlphami*fAlphami;
+  Double_t helpmm = fAlphamm*fAlphamm*fAlphamm;
+  Double_t helpma = fAlphama*fAlphama*fAlphama;
+  Double_t help   =   (helpma-helpmm) * (fAlphamm-fAlphami)    
+	            - (helpmm-helpmi) * (fAlphama-fAlphamm);
+  if (help != 0.0)
+    a2init =  ( (fAlphamm-fAlphami)*nfar - (fAlphama-fAlphamm)*nclose )
+                * 1.5 * fHist->GetBinWidth(1) / help;
+  else
+    a2init = 0.0;
+
+
+  //--------------------------------------------
+  // rebin the histogram
+  //   - if a bin has no entries 
+  //   - or if there are too many bins with too few entries
+  //   - or if the new bin width would exceed half the size of the 
+  //     signal region
+
+  if ( !fRebin  ||
+       ( fNzero <= 0 && (Double_t)fMlow<0.05*(Double_t)fMbins )  || 
+       (Double_t)(nrebin+1)/(Double_t)nrebin * fHist->GetBinWidth(1) 
+                                                           > fAlphasig/2.0 )
+  {
+    //*fLog << "before break" << endl;
+    break;
+  }
+
+  nrebin += 1;
+  TString histname = fHist->GetName();
+  delete fHist;
+  fHist = NULL;
+
+  *fLog << "MHFindSignificance::FitPolynomial; rebin the |alpha| plot, grouping "
+        << nrebin << " bins together" << endl;
+
+  // TH1::Rebin doesn't work properly
+  //fHist = fHistOrig->Rebin(nrebin, "Rebinned");
+  // use private routine RebinHistogram()
+  fHist = new TH1F;
+  fHist->Sumw2();
+  fHist->SetNameTitle(histname, histname);
+  fHist->UseCurrentStyle();
+
+  // do rebinning such that x0 remains a lower bin edge
+  Double_t x0 = 0.0;
+  if ( !RebinHistogram(x0, nrebin) )
+  {
+    *fLog << "MHFindSignificance::FitPolynomial; RebinHistgram() failed" 
+          << endl;
+    return kFALSE;
+  }
+
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+
+  }
+  //----------------   end of while loop for rebinning   -----------------
+
+
+  // if there are still too many bins with too few entries don't fit
+  // and assume a constant background
+
+  fConstantBackg = kFALSE;
+  if ( fNzero > 0  ||  (Double_t)fMlow>0.05*(Double_t)fMbins ) 
+  {
+    *fLog << "MHFindSignificance::FitPolynomial; polynomial fit not possible,  fNzero, fMlow, fMbins = "
+          << fNzero << ",  " << fMlow << ",  " << fMbins << endl;
+    *fLog << "                    assume a constant background" << endl;
+
+    fConstantBackg = kTRUE;
+    fDegree        = 0;
+
+    TString funcname = "Poly";
+    Double_t xmin =   0.0;
+    Double_t xmax =  90.0;
+
+    TString formula = "[0]";
+
+    fPoly = new TF1(funcname, formula, xmin, xmax);
+    TList *funclist = fHist->GetListOfFunctions();
+    funclist->Add(fPoly);
+
+    //--------------------
+    Int_t nparfree = 1;
+    fChisq         = 0.0; 
+    fNdf           = fMbins - nparfree;
+    fProb          = 0.0;
+    fIstat         = 0;
+
+    fValues.Set(1);
+    fErrors.Set(1);
+
+    Double_t val, err;
+    val = mean;
+    err = sqrt( mean / (Double_t)fMbins );
+
+    fPoly->SetParameter(0, val);
+    fPoly->SetParError (0, err);
+
+    fValues[0] = val;
+    fErrors[0] = err; 
+
+    fEma[0][0]  = err*err;
+    fCorr[0][0] = 1.0;
+    //--------------------
+
+    //--------------------------------------------------
+    // reset the errors of the points in the histogram
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      fHist->SetBinError(i, saveError[i-1]);
+    }
+
+
+    return kTRUE;
+  }
+
+
+  //===========   start loop for reducing the degree   ==================
+  //              of the polynomial
+  while (1)
+  {
+      //--------------------------------------------------
+      // prepare fit of a polynomial :   (a0 + a1*x + a2*x**2 + a3*x**3 + ...)
+
+      TString funcname = "Poly";
+      Double_t xmin =   0.0;
+      Double_t xmax =  90.0;
+
+      TString formula = "[0]";
+      TString bra1     = "+[";
+      TString bra2     =    "]";
+      TString xpower   = "*x";
+      TString newpower = "*x";
+      for (Int_t i=1; i<=fDegree; i++)
+      {
+          formula += bra1;
+          formula += i;
+          formula += bra2;
+          formula += xpower;
+
+          xpower += newpower;
+      }
+
+      //*fLog << "FitPolynomial : formula = " << formula << endl;
+
+      fPoly = new TF1(funcname, formula, xmin, xmax);
+      TList *funclist = fHist->GetListOfFunctions();
+      funclist->Add(fPoly);
+
+      //------------------------
+      // attention : the dimensions must agree with those in CallMinuit()
+      const UInt_t npar = fDegree+1;
+
+      TString parname[npar];
+      TArrayD vinit(npar);
+      TArrayD  step(npar);
+      TArrayD limlo(npar);
+      TArrayD limup(npar);
+      TArrayI   fix(npar);
+
+      vinit[0] =   mean;
+      vinit[2] = a2init;
+
+      for (UInt_t j=0; j<npar; j++)
+      {
+          parname[j]  = "p";
+          parname[j] += j+1;
+
+          step[j] = vinit[j] != 0.0 ? TMath::Abs(vinit[j]) / 10.0 : 0.000001;
+      }
+
+      // limit the first coefficient of the polynomial to positive values
+      // because the background must not be negative
+      limup[0] = fHist->GetEntries();
+
+      // use the subsequernt loop if you want to apply the
+      // constraint : uneven derivatives (at alpha=0) = zero
+      for (UInt_t j=1; j<npar; j+=2)
+      {
+          vinit[j] = 0;
+          step[j]  = 0;
+          fix[j]   = 1;
+      }
+
+      //*fLog << "FitPolynomial : before CallMinuit()" << endl;
+
+      MMinuitInterface inter;
+      const Bool_t rc = inter.CallMinuit(fcnpoly, parname, vinit, step,
+                                         limlo, limup, fix, fHist, "Migrad",
+                                         kFALSE);
+
+      //*fLog << "FitPolynomial : after CallMinuit()" << endl;
+
+      if (rc != 0)
+      {
+          //  *fLog << "MHFindSignificance::FitPolynomial; polynomial fit failed"
+          //        << endl;
+          //  return kFALSE;
+      }
+
+
+      //-------------------
+      // get status of minimization
+      Double_t fmin   = 0;
+      Double_t fedm   = 0;
+      Double_t errdef = 0;
+      Int_t    npari  = 0;
+      Int_t    nparx  = 0;
+
+      if (gMinuit)
+          gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, fIstat);
+
+      *fLog << "MHFindSignificance::FitPolynomial; fmin, fedm, errdef, npari, nparx, fIstat = "
+            << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+            << ",  " << nparx << ",  " << fIstat << endl;
+
+
+      //-------------------
+      // store the results
+
+      Int_t nparfree = gMinuit!=NULL ? gMinuit->GetNumFreePars() : 0;
+      fChisq         = fmin;
+      fNdf           = fMbins - nparfree;
+      fProb          = TMath::Prob(fChisq, fNdf);
+
+
+      // get fitted parameter values and errors
+      fValues.Set(npar);
+      fErrors.Set(npar);
+
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          Double_t val, err;
+          if (gMinuit)
+              gMinuit->GetParameter(j, val, err);
+
+          fPoly->SetParameter(j, val);
+          fPoly->SetParError(j, err);
+
+          fValues[j] = val;
+          fErrors[j] = err;
+      }
+
+
+      //--------------------------------------------------
+      // if the highest coefficient (j0) of the polynomial
+      // is consistent with zero reduce the degree of the polynomial
+
+      Int_t j0 = 0;
+      for (Int_t j=fDegree; j>1; j--)
+      {
+          // ignore fixed parameters
+          if (fErrors[j] == 0)
+              continue;
+
+          // this is the highest coefficient
+          j0 = j;
+          break;
+      }
+
+      if (!fReduceDegree || j0==0 || TMath::Abs(fValues[j0]) > fErrors[j0])
+          break;
+
+      // reduce the degree of the polynomial
+      *fLog << "MHFindSignificance::FitPolynomial; reduce the degree of the polynomial from "
+          << fDegree << " to " << (j0-2) << endl;
+      fDegree = j0 - 2;
+
+      funclist->Remove(fPoly);
+      //if (fPoly)
+      delete fPoly;
+      fPoly = NULL;
+
+      // delete the Minuit object in order to have independent starting
+      // conditions for the next minimization
+      //if (gMinuit)
+      delete gMinuit;
+      gMinuit = NULL;
+  }
+  //===========   end of loop for reducing the degree   ==================
+  //              of the polynomial
+
+
+  //--------------------------------------------------
+  // get the error matrix of the fitted parameters
+
+
+  if (fIstat >= 1)
+  {
+      // error matrix was calculated
+      if (gMinuit)
+          gMinuit->mnemat(&fEmat[0][0], fNdim);
+
+      // copy covariance matrix into a matrix which includes also the fixed
+      // parameters
+      TString  name;
+      Double_t bnd1, bnd2, val, err;
+      Int_t    jvarbl;
+      Int_t    kvarbl;
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          if (gMinuit)
+              gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+          for (Int_t k=0; k<=fDegree; k++)
+          {
+              if (gMinuit)
+                  gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+              fEma[j][k] = jvarbl==0 || kvarbl==0 ? 0 : fEmat[jvarbl-1][kvarbl-1];
+          }
+      }
+  }
+  else
+  {
+      // error matrix was not calculated, construct it
+      *fLog << "MHFindSignificance::FitPolynomial; error matrix not defined"
+          << endl;
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          for (Int_t k=0; k<=fDegree; k++)
+              fEma[j][k] = 0;
+
+          fEma[j][j] = fErrors[j]*fErrors[j];
+      }
+  }
+
+
+  //--------------------------------------------------
+  // calculate correlation matrix
+  for (Int_t j=0; j<=fDegree; j++)
+      for (Int_t k=0; k<=fDegree; k++)
+      {
+          const Double_t sq = fEma[j][j]*fEma[k][k];
+          fCorr[j][k] = sq==0 ? 0 : fEma[j][k] / TMath::Sqrt(fEma[j][j]*fEma[k][k]);
+      }
+
+
+  //--------------------------------------------------
+  // reset the errors of the points in the histogram
+  for (Int_t i=1; i<=nbins; i++)
+      fHist->SetBinError(i, saveError[i-1]);
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReBinHistogram
+//
+// rebin the histogram 'fHistOrig' by grouping 'nrebin' bins together 
+// put the result into the histogram 'fHist'
+// the rebinning is made such that 'x0' remains a lower bound of a bin
+//
+
+Bool_t MHFindSignificance::RebinHistogram(Double_t x0, Int_t nrebin)
+{
+  //-----------------------------------------
+  // search bin i0 which has x0 as lower edge
+
+  Int_t i0 = -1;
+  Int_t nbold = fHistOrig->GetNbinsX();
+  for (Int_t i=1; i<=nbold; i++)
+  {
+      if (TMath::Abs(fHistOrig->GetBinLowEdge(i) - x0) < 1.e-4 )
+      {
+          i0 = i;
+          break;
+      }
+  }
+
+  if (i0 == -1)
+  {
+    i0 = 1;
+    *fLog << "MHFindsignificance::Rebin; no bin found with " << x0
+          << " as lower edge,  start rebinning with bin 1" << endl;
+  }
+
+  Int_t istart = i0 - nrebin * ( (i0-1)/nrebin );
+
+  //-----------------------------------------
+  // get new bin edges
+
+  const Int_t    nbnew = (nbold-istart+1) / nrebin;
+  const Double_t xmin  = fHistOrig->GetBinLowEdge(istart);
+  const Double_t xmax  = xmin + (Double_t)nbnew * nrebin * fHistOrig->GetBinWidth(1);
+  fHist->SetBins(nbnew, xmin, xmax);
+
+  *fLog << "MHFindSignificance::ReBin; x0, i0, nbold, nbnew, xmin, xmax = "
+        << x0 << ",  " << i0 << ",  " << nbold << ",  " << nbnew << ",  "
+        << xmin << ",  " << xmax << endl;
+
+  //-----------------------------------------
+  // get new bin entries
+
+  for (Int_t i=1; i<=nbnew; i++)
+  {
+      Int_t j = nrebin*(i-1) + istart;
+
+      Double_t content = 0;
+      Double_t error2  = 0;
+      for (Int_t k=0; k<nrebin; k++)
+      {
+          content += fHistOrig->GetBinContent(j+k);
+          error2  += fHistOrig->GetBinError(j+k) * fHistOrig->GetBinError(j+k);
+      }
+      fHist->SetBinContent(i, content);
+      fHist->SetBinError  (i, sqrt(error2));
+  }
+  fHist->SetEntries( fHistOrig->GetEntries() );
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  FitGaussPoly
+//
+//  fits a (Gauss + polynomial function) to the alpha distribution 'fhist' 
+//
+//
+Bool_t MHFindSignificance::FitGaussPoly()
+{
+  *fLog << "Entry FitGaussPoly" << endl;
+
+  //--------------------------------------------------
+  // check the histogram :
+  //       - calculate initial values of the parameters
+  //       - check for bins with zero entries
+  //       - set minimum errors
+  //       - save the original errors
+  //       - set errors huge outside the fit range
+  //         (in 'fcnpoly' points with huge errors will be ignored)
+
+
+  Double_t dummy = 1.e20;
+
+  fGNzero   = 0;
+  fGMbins   = 0;
+
+  //------------------------------------------
+  // if a constant background has been assumed (due to low statistics)
+  // fit only in the signal region
+  if ( !fConstantBackg )
+  {
+    fAlphalow = 0.0;
+    fAlphahig = fAlphamax;
+  }
+  else
+  {
+    fAlphalow = 0.0;
+    fAlphahig = 2.0*fAlphasig>25.0 ? 25.0 : 2.0*fAlphasig;
+  }
+  //------------------------------------------
+
+
+  fAlphalo =  10000.0;
+  fAlphahi = -10000.0;
+
+
+  Int_t nbins = fHist->GetNbinsX();
+  TArrayD saveError(nbins);
+
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    saveError[i-1] = fHist->GetBinError(i);
+
+    // bin should be completely contained in the fit range
+    // (fAlphalow, fAlphahig)
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+
+    if ( xlo >= fAlphalow-fEps  &&  xlo <= fAlphahig+fEps  &&
+	 xup >= fAlphalow-fEps  &&  xup <= fAlphahig+fEps     )
+    {
+      fGMbins++;
+
+      if ( xlo < fAlphalo )
+        fAlphalo = xlo;
+
+      if ( xup > fAlphahi )
+        fAlphahi = xup;
+
+      Double_t content = fHist->GetBinContent(i);
+
+
+      // count bins with zero entry
+      if (content <= 0.0)
+        fGNzero++;
+     
+      // set minimum error
+      if (content < 9.0)
+        fHist->SetBinError(i, 3.0);
+
+      //*fLog << "Take : i, content, error = " << i << ",  " 
+      //      << fHist->GetBinContent(i) << ",  "
+      //      << fHist->GetBinError(i)   << endl;
+
+      continue;
+    }    
+    // bin is not completely contained in the fit range : set error huge
+
+    fHist->SetBinError(i, dummy);
+
+    //*fLog << "Omit : i, content, error = " << i << ",  " 
+    //      << fHist->GetBinContent(i) << ",  " << fHist->GetBinError(i) 
+    //      << endl;
+
+  }
+
+
+  // if a bin has no entries don't fit
+  if (fGNzero > 0)
+  {
+    *fLog << "MHFindSignificance::FitGaussPoly; out of " << fGMbins 
+          << " bins there are " << fGNzero
+          << " bins with zero entry" << endl;
+
+    fGPoly = NULL;
+    return kFALSE;
+  }
+
+
+  //--------------------------------------------------
+  // prepare fit of a (polynomial+Gauss) :   
+  // (a0 + a1*x + a2*x**2 + a3*x**3 + ...) + A*exp( -0.5*((x-x0)/sigma)**2 )
+
+  TString funcname = "PolyGauss";
+  Double_t xmin =   0.0;
+  Double_t xmax =  90.0;
+
+  TString xpower   = "*x";
+  TString newpower = "*x";
+
+  TString formulaBackg = "[0]";
+  for (Int_t i=1; i<=fDegree; i++)
+      formulaBackg += Form("+[%d]*x^%d", i, i);
+
+  const TString formulaGauss = 
+        Form("[%d]/[%d]*exp(-0.5*((x-[%d])/[%d])^2)",
+             fDegree+1, fDegree+3, fDegree+2, fDegree+3);
+
+  TString formula = formulaBackg;
+  formula += "+";
+  formula += formulaGauss;
+
+  *fLog << "FitGaussPoly : formulaBackg = " << formulaBackg << endl;
+  *fLog << "FitGaussPoly : formulaGauss = " << formulaGauss << endl;
+  *fLog << "FitGaussPoly : formula = " << formula << endl;
+
+  fGPoly = new TF1(funcname, formula, xmin, xmax);
+  TList *funclist = fHist->GetListOfFunctions();
+  funclist->Add(fGPoly);
+
+  fGBackg = new TF1("Backg", formulaBackg, xmin, xmax);
+  funclist->Add(fGBackg);
+
+  //------------------------
+  // attention : the dimensions must agree with those in CallMinuit()
+  Int_t npar = fDegree+1 + 3;
+
+  TString parname[npar];
+  TArrayD vinit(npar);
+  TArrayD  step(npar); 
+  TArrayD limlo(npar); 
+  TArrayD limup(npar); 
+  TArrayI   fix(npar);
+
+
+  // take as initial values for the polynomial 
+  // the result from the polynomial fit
+  for (Int_t j=0; j<=fDegree; j++)
+    vinit[j] = fPoly->GetParameter(j);
+
+  Double_t sigma = 8;
+  vinit[fDegree+1] = 2.0 * fNex * fHist->GetBinWidth(1) / TMath::Sqrt(TMath::Pi()*2);
+  vinit[fDegree+2] = 0;
+  vinit[fDegree+3] = sigma;
+
+  *fLog << "FitGaussPoly : starting value for Gauss-amplitude = " 
+        << vinit[fDegree+1] << endl;
+
+  for (Int_t j=0; j<npar; j++)
+  {
+      parname[j]  = "p";
+      parname[j] += j+1;
+
+      step[j] = vinit[j]!=0 ? TMath::Abs(vinit[j]) / 10.0 : 0.000001;
+  }
+
+  // limit the first coefficient of the polynomial to positive values
+  // because the background must not be negative
+  limup[0] = fHist->GetEntries()*10;
+
+  // limit the sigma of the Gauss function
+  limup[fDegree+3] = 20;
+
+
+  // use the subsequernt loop if you want to apply the
+  // constraint : uneven derivatives (at alpha=0) = zero
+  for (Int_t j=1; j<=fDegree; j+=2)
+  {
+      vinit[j] = 0;
+      step[j]  = 0;
+      fix[j]   = 1;
+  }
+
+  // fix position of Gauss function
+  vinit[fDegree+2] = 0;
+  step[fDegree+2]  = 0;
+  fix[fDegree+2]   = 1;
+   
+  // if a constant background has been assumed (due to low statistics)
+  // fix the background
+  if (fConstantBackg)
+  {
+      step[0] = 0;
+      fix[0]  = 1;
+  }
+
+  MMinuitInterface inter;
+  const Bool_t rc = inter.CallMinuit(fcnpolygauss, parname, vinit, step,
+                                     limlo, limup, fix, fHist, "Migrad",
+                                     kFALSE);
+
+  if (rc != 0)
+  {
+  //  *fLog << "MHFindSignificance::FitGaussPoly; (polynomial+Gauss) fit failed"
+  //        << endl;
+  //  return kFALSE;
+  }
+
+
+  //-------------------
+  // get status of the minimization
+  Double_t fmin;
+  Double_t fedm;
+  Double_t errdef;
+  Int_t    npari;
+  Int_t    nparx;
+
+  if (gMinuit)
+    gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, fGIstat);
+
+  *fLog << "MHFindSignificance::FitGaussPoly; fmin, fedm, errdef, npari, nparx, fGIstat = "
+        << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+        << ",  " << nparx << ",  " << fGIstat << endl;
+
+
+  //-------------------
+  // store the results
+
+  Int_t nparfree  = gMinuit!=NULL ? gMinuit->GetNumFreePars() : 0;
+  fGChisq         = fmin; 
+  fGNdf           = fGMbins - nparfree;
+  fGProb          = TMath::Prob(fGChisq, fGNdf);
+
+
+  // get fitted parameter values and errors
+  fGValues.Set(npar);
+  fGErrors.Set(npar);
+
+  for (Int_t j=0; j<npar; j++)
+  {
+    Double_t val, err;
+    if (gMinuit)
+      gMinuit->GetParameter(j, val, err);
+
+    fGPoly->SetParameter(j, val);
+    fGPoly->SetParError(j, err);
+
+    fGValues[j] = val;
+    fGErrors[j] = err; 
+
+    if (j <=fDegree)
+    {
+      fGBackg->SetParameter(j, val);
+      fGBackg->SetParError(j, err);
+    }
+  }
+
+  fSigmaGauss  = fGValues[fDegree+3];
+  fdSigmaGauss = fGErrors[fDegree+3];
+  // fitted total number of excess events 
+  fNexGauss = fGValues[fDegree+1] * TMath::Sqrt(TMath::Pi()*2) /
+                                         (fHist->GetBinWidth(1)*2 );
+  fdNexGauss = fNexGauss * fGErrors[fDegree+1]/fGValues[fDegree+1];
+
+  //--------------------------------------------------
+  // get the error matrix of the fitted parameters
+
+
+  if (fGIstat >= 1)
+  {
+    // error matrix was calculated
+    if (gMinuit)
+      gMinuit->mnemat(&fGEmat[0][0], fGNdim);
+
+    // copy covariance matrix into a matrix which includes also the fixed
+    // parameters
+    TString  name;
+    Double_t bnd1, bnd2, val, err;
+    Int_t    jvarbl;
+    Int_t    kvarbl;
+    for (Int_t j=0; j<npar; j++)
+    {
+        if (gMinuit)
+            gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+        for (Int_t k=0; k<npar; k++)
+        {
+            if (gMinuit)
+                gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+            fGEma[j][k] = jvarbl==0 || kvarbl==0 ? 0 : fGEmat[jvarbl-1][kvarbl-1];
+        }
+    }
+  }
+  else
+  {
+    // error matrix was not calculated, construct it
+    *fLog << "MHFindSignificance::FitPolynomial; error matrix not defined" 
+          << endl;
+    for (Int_t j=0; j<npar; j++)
+    {
+        for (Int_t k=0; k<npar; k++)
+            fGEma[j][k] = 0;
+
+        fGEma[j][j] = fGErrors[j]*fGErrors[j];
+    }
+  }
+
+
+  //--------------------------------------------------
+  // calculate correlation matrix
+  for (Int_t j=0; j<npar; j++)
+  {
+    for (Int_t k=0; k<npar; k++)
+    {
+        const Double_t sq = fGEma[j][j]*fGEma[k][k];
+        fGCorr[j][k] = sq==0 ? 0 : fGEma[j][k] / sqrt( fGEma[j][j]*fGEma[k][k] );
+    }
+  }
+
+
+  //--------------------------------------------------
+  // reset the errors of the points in the histogram
+  for (Int_t i=1; i<=nbins; i++)
+    fHist->SetBinError(i, saveError[i-1]);
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  DetExcess
+//
+//  using the result of the polynomial fit (fValues), DetExcess determines
+//
+//  - the total number of events in the signal region (fNon)
+//  - the number of backgound events in the signal region (fNbg)
+//  - the number of excess events (fNex)
+//  - the effective number of background events (fNoff), and fGamma :
+//    fNbg = fGamma * fNoff;  fdNbg = fGamma * sqrt(fNoff);
+//
+//  It assumed that the polynomial is defined as
+//               a0 + a1*x + a2*x**2 + a3*x**3 + ..
+//
+//  and that the alpha distribution has the range 0 < alpha < 90 degrees
+//
+
+Bool_t MHFindSignificance::DetExcess()
+{
+  //*fLog << "MHFindSignificance::DetExcess;" << endl;
+
+  //--------------------------------------------
+  // calculate the total number of events (fNon) in the signal region
+
+  fNon  = 0.0;
+  fdNon = 0.0;
+
+  Double_t alphaup = -1000.0; 
+  Double_t binwidth = fHist->GetBinWidth(1);
+
+  Int_t nbins = fHist->GetNbinsX();
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+ 
+    // bin must be completely contained in the signal region
+    if ( xlo <= (fAlphasig+fEps)  &&  xup <= (fAlphasig+fEps)    )
+    {
+      Double_t width = fabs(xup-xlo);
+      if (fabs(width-binwidth) > fEps)
+      {
+        *fLog << "MHFindSignificance::DetExcess; alpha plot has variable binning, which is not allowed" 
+          << endl;
+        return kFALSE;
+      }
+
+      if (xup > alphaup)
+        alphaup = xup;
+
+      fNon  += fHist->GetBinContent(i);
+      fdNon += fHist->GetBinError(i) * fHist->GetBinError(i);
+    }
+  }
+  fdNon = sqrt(fdNon);
+
+  // the actual signal range is :
+  if (alphaup == -1000.0)
+    return kFALSE;
+
+  fAlphasi = alphaup;
+
+  //*fLog << "fAlphasi, fNon, fdNon, binwidth, fDegree = " << fAlphasi << ",  "
+  //      << fNon << ",  " << fdNon << ",  " << binwidth << ",  "
+  //      << fDegree << endl;
+
+  //--------------------------------------------
+  // calculate the number of background events (fNbg) in the signal region
+  // and its error (fdNbg) 
+
+  Double_t fac = 1.0/binwidth;
+
+  fNbg         = 0.0;
+  Double_t altothejplus1 = fAlphasi;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    fNbg += fValues[j] * altothejplus1 / ((Double_t)(j+1));
+    altothejplus1 *= fAlphasi;
+  }
+  fNbg *= fac;
+
+  // derivative of Nbg 
+  Double_t facj;
+  Double_t fack;
+
+  Double_t sum = 0.0;
+  altothejplus1 = fAlphasi;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    facj = altothejplus1 / ((Double_t)(j+1));
+
+    Double_t altothekplus1 = fAlphasi;    
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      fack = altothekplus1 / ((Double_t)(k+1));
+
+      sum   += facj * fack * fEma[j][k];
+      altothekplus1 *= fAlphasi;
+    }
+    altothejplus1 *= fAlphasi;
+  }
+  sum  *= fac*fac;
+
+  if (sum < 0.0)
+  {
+    *fLog << "MHFindsignificance::DetExcess; error squared is negative" 
+          << endl;
+    return kFALSE;
+  }
+
+  fdNbg = sqrt(sum);
+
+
+  //--------------------------------------------
+  // AS A CHECK :
+  // calculate the number of background events (fNbgtotFitted) in the 
+  // background region, and its error (fdNbgtotFitted) 
+  // expect fdnbg to be approximately equal to sqrt(fNbgtotFitted)
+
+  Double_t fNmi = 0.0;
+  altothejplus1 = fAlphami;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    fNmi += fValues[j] * altothejplus1 / ((Double_t)(j+1));
+    altothejplus1 *= fAlphami;
+  }
+  fNmi *= fac;
+
+  Double_t fNma = 0.0;
+  altothejplus1 = fAlphama;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    fNma += fValues[j] * altothejplus1 / ((Double_t)(j+1));
+    altothejplus1 *= fAlphama;
+  }
+  fNma *= fac;
+
+  fNbgtotFitted  = fNma - fNmi;
+
+  //----------------------
+
+  sum = 0.0;
+  Double_t altothejma = fAlphama;
+  Double_t altothejmi = fAlphami;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    facj = (altothejma-altothejmi) / ((Double_t)(j+1));
+
+    Double_t altothekma = fAlphama;    
+    Double_t altothekmi = fAlphami;    
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      fack = (altothekma-altothekmi) / ((Double_t)(k+1));
+
+      sum   += facj * fack * fEma[j][k];
+      altothekma *= fAlphama;
+      altothekmi *= fAlphami;
+    }
+    altothejma *= fAlphama;
+    altothejmi *= fAlphami;
+  }
+  sum  *= fac*fac;
+
+  fdNbgtotFitted = sqrt(sum);
+  if ( fabs(fdNbgtotFitted - sqrt(fNbgtotFitted)) > 0.2 * sqrt(fNbgtotFitted) )
+  {
+    *fLog << "MHFindSignificance::DetExcess; error of calculated number of background events (in the background region) does not agree with the expectation :"
+          << endl;
+    *fLog << "                    fNbgtotFitted, fdNbgtotFitted = " 
+          << fNbgtotFitted << ",  " << fdNbgtotFitted
+          << ",  expected : " << sqrt(fNbgtotFitted) << endl;         
+  } 
+
+
+  //--------------------------------------------
+  // calculate the number of excess events in the signal region
+
+  fNex = fNon - fNbg;
+
+  //--------------------------------------------
+  // calculate the effective number of background events (fNoff) , and fGamma :
+  // fNbg = fGamma * fNoff;   dfNbg = fGamma * sqrt(fNoff);
+
+  if (fNbg < 0.0)
+  {
+    *fLog << "MHFindSignificamce::DetExcess; number of background events is negative,  fNbg, fdNbg = "
+          << fNbg  << ",  " << fdNbg << endl;
+
+    fGamma = 1.0;
+    fNoff  = 0.0;
+    return kFALSE;
+  }
+
+  if (fNbg > 0.0)
+  {
+    fGamma = fdNbg*fdNbg / fNbg;
+    fNoff  =  fNbg*fNbg  / (fdNbg*fdNbg);
+  }
+  else
+  {
+    fGamma = 1.0;
+    fNoff  = 0.0;
+  }
+
+  //*fLog << "Exit DetExcess()" << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  SigmaLiMa
+//
+//  calculates the significance according to Li & Ma
+//  ApJ 272 (1983) 317
+//
+Bool_t MHFindSignificance::SigmaLiMa(Double_t non,   Double_t noff, 
+                                     Double_t gamma, Double_t *siglima)
+{
+  if (gamma <= 0.0  ||  non <= 0.0  ||  noff <= 0.0)
+  {
+    *siglima = 0.0;
+    return kFALSE;
+  }
+
+  Double_t help1 = non  * log( (1.0+gamma)*non  / (gamma*(non+noff)) );
+  Double_t help2 = noff * log( (1.0+gamma)*noff / (       non+noff ) );
+  *siglima = sqrt( 2.0 * (help1+help2) );
+
+  Double_t nex = non - gamma*noff;
+  if (nex < 0.0)
+    *siglima = - *siglima;
+
+  //*fLog << "MHFindSignificance::SigmaLiMa; non, noff, gamma, *siglima = "
+  //      << non << ",  " << noff << ",  " << gamma << ",  " << *siglima << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MHFindSignificance::DrawFit(const Option_t *opt)
+{
+    if (fHist == NULL)
+      *fLog << "MHFindSignificance::DrawFit; fHist = NULL" << endl;
+
+
+    //TCanvas *fCanvas = new TCanvas("Alpha", "Alpha plot", 600, 600);
+//      fCanvas = new TCanvas(fHist->GetName(), "Alpha plot", 600, 600);
+
+    TVirtualPad *c = gPad ? gPad : MakeDefCanvas(this);
+
+    //gStyle->SetOptFit(1011);
+
+    gROOT->SetSelectedPad(NULL);    
+    gStyle->SetPadLeftMargin(0.1);
+
+//      fCanvas->cd();
+    c->cd();
+
+
+    if (fHist)
+    {
+      fHist->DrawCopy();
+    }
+
+    TF1 *fpoly = fHist->GetFunction("Poly");    
+    if (fpoly == NULL)
+      *fLog << "MHFindSignificance::DrawFit; fpoly = NULL" << endl;
+
+    if (fpoly)
+    {
+      // 2, 1 is red and solid
+      fpoly->SetLineColor(2);
+      fpoly->SetLineStyle(1);
+      fpoly->SetLineWidth(2);
+      fpoly->DrawCopy("same");
+    }
+
+    if (fFitGauss)
+    {
+      TF1 *fpolygauss = fHist->GetFunction("PolyGauss");    
+      if (fpolygauss == NULL)
+        *fLog << "MHFindSignificance::DrawFit; fpolygauss = NULL" << endl;
+
+      if (fpolygauss)
+      {
+        // 4, 1 is blue and solid
+        fpolygauss->SetLineColor(4);
+        fpolygauss->SetLineStyle(1);
+        fpolygauss->SetLineWidth(4);
+        fpolygauss->DrawCopy("same");
+      }
+
+      TF1 *fbackg = fHist->GetFunction("Backg");    
+      if (fbackg == NULL)
+        *fLog << "MHFindSignificance::DrawFit; fbackg = NULL" << endl;
+
+      if (fbackg)
+      {
+        // 6, 4 is pink and dotted
+        fbackg->SetLineColor(4);
+        fbackg->SetLineStyle(4);
+        fbackg->SetLineWidth(4);
+        fbackg->DrawCopy("same");
+      }
+    }
+
+
+    //-------------------------------
+    // print results onto the figure
+    TPaveText *pt = new TPaveText(0.30, 0.35, 0.70, 0.90, "NDC");
+    char tx[100];
+
+    sprintf(tx, "Results of polynomial fit (order %2d) :", fDegree);
+    TText *t1 = pt->AddText(tx);
+    t1->SetTextSize(0.03);
+    t1->SetTextColor(2);
+
+    sprintf(tx, "   (%6.2f< |alpha| <%6.2f [\\circ])", fAlphami, fAlphama);
+    pt->AddText(tx);
+
+    sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+            fChisq, fNdf, fProb);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nbgtot(fit) = %8.1f #pm %8.1f", 
+            fNbgtotFitted, fdNbgtotFitted);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nbgtot(meas) = %8.1f", fNbgtot);
+    pt->AddText(tx);
+
+
+    //sprintf(tx, "     ");
+    //pt->AddText(tx);
+
+    //--------------
+    sprintf(tx, "Results for |alpha|< %6.2f [\\circ] :", fAlphasi);
+    TText *t6 = pt->AddText(tx);
+    t6->SetTextSize(0.03);
+    t6->SetTextColor(8);
+
+    sprintf(tx, "   Non = %8.1f #pm %8.1f", fNon, fdNon);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nex = %8.1f #pm %8.1f", fNex, fdNex);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nbg = %8.1f #pm %8.1f,    gamma = %6.1f", 
+            fNbg, fdNbg, fGamma);
+    pt->AddText(tx);
+
+    Double_t ratio = fNbg>0.0 ? fNex/fNbg : 0.0;
+    sprintf(tx, "   Significance = %6.2f,    Nex/Nbg = %6.2f", 
+            fSigLiMa, ratio);
+    pt->AddText(tx);
+
+    //sprintf(tx, "     ");
+    //pt->AddText(tx);
+
+    //--------------
+    if (fFitGauss)
+    {
+      sprintf(tx, "Results of (polynomial+Gauss) fit  :");
+      TText *t7 = pt->AddText(tx);
+      t7->SetTextSize(0.03);
+      t7->SetTextColor(4);
+
+      sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+              fGChisq, fGNdf, fGProb);
+      pt->AddText(tx);
+
+      sprintf(tx, "   Sigma of Gauss = %8.1f #pm %8.1f  [\\circ]", 
+              fSigmaGauss, fdSigmaGauss);
+      pt->AddText(tx);
+
+      sprintf(tx, "   total no.of excess events = %8.1f #pm %8.1f", 
+              fNexGauss, fdNexGauss);
+      pt->AddText(tx);
+    }
+    //--------------
+
+    pt->SetFillStyle(0);
+    pt->SetBorderSize(0);
+    pt->SetTextAlign(12);
+
+    pt->Draw();
+
+//      fCanvas->Modified();
+//      fCanvas->Update();
+    c->Modified();
+    c->Update();
+
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Print the results of the polynomial fit to the alpha distribution
+// 
+//
+void MHFindSignificance::PrintPoly(Option_t *o) 
+{
+  *fLog << "---------------------------" << endl;
+  *fLog << "MHFindSignificance::PrintPoly :" << endl; 
+
+  *fLog << "fAlphami, fAlphama, fDegree, fAlphasi = "
+        << fAlphami << ",  " << fAlphama << ",  " << fDegree << ",  " 
+        << fAlphasi << endl;
+
+  *fLog << "fMbins, fNzero, fIstat = " << fMbins << ",  "
+        << fNzero << ",  " << fIstat << endl;
+
+  *fLog << "fChisq, fNdf, fProb = " << fChisq << ",  " 
+        << fNdf << ",  " << fProb << endl; 
+
+  *fLog << "fNon, fNbg, fdNbg, fNbgtot, fNbgtotFitted, fdNbgtotFitted = "
+        << fNon << ",  " << fNbg << ",  " << fdNbg << ",  " << fNbgtot 
+        << ",  " << fNbgtotFitted << ",  " << fdNbgtotFitted << endl;
+
+  Double_t sigtoback = fNbg>0.0 ? fNex/fNbg : 0.0;
+  *fLog << "fNex, fdNex, fGamma, fNoff, fSigLiMa, sigtoback = "
+        << fNex << ",  " << fdNex << ",  " << fGamma << ",  " << fNoff 
+        << ",  " << fSigLiMa << ",  " << sigtoback << endl;
+
+  //------------------------------------
+  // get errors
+
+  /*
+  Double_t eplus; 
+  Double_t eminus; 
+  Double_t eparab; 
+  Double_t gcc;
+  Double_t errdiag;
+
+
+  if ( !fConstantBackg )
+  {
+    *fLog << "parameter value     error     eplus     eminus    eparab   errdiag   gcc"
+          << endl; 
+
+    for (Int_t j=0; j<=fDegree; j++)
+    {
+      if (gMinuit)
+        gMinuit->mnerrs(j, eplus, eminus, eparab, gcc);
+      errdiag = sqrt(fEma[j][j]);
+      *fLog << j << "  " << fValues[j] << "  "   << fErrors[j] << "  "
+            << eplus     << "  "       << eminus << "  " << eparab     << "  " 
+            <<  errdiag  << "  "       << gcc    << endl;
+    }
+  }  
+  else
+  {
+    *fLog << "parameter value     error     errdiag "
+          << endl; 
+
+    for (Int_t j=0; j<=fDegree; j++)
+    {
+      errdiag = sqrt(fEma[j][j]);
+      *fLog << j << "  " << fValues[j] << "  "   << fErrors[j] << "  "
+            <<  errdiag  << endl;
+    }
+  }  
+  */
+
+  //----------------------------------------
+  /*
+  *fLog << "Covariance matrix :" << endl;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      *fLog << fEma[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "Correlation matrix :" << endl;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      *fLog << fCorr[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+  */
+
+  *fLog << "---------------------------" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the results of the (polynomial+Gauss) fit to the alpha distribution
+// 
+//
+void MHFindSignificance::PrintPolyGauss(Option_t *o) 
+{
+  *fLog << "---------------------------" << endl;
+  *fLog << "MHFindSignificance::PrintPolyGauss :" << endl; 
+
+  *fLog << "fAlphalo, fAlphahi = "
+        << fAlphalo << ",  " << fAlphahi << endl;
+
+  *fLog << "fGMbins, fGNzero, fGIstat = " << fGMbins << ",  "
+        << fGNzero << ",  " << fGIstat << endl;
+
+  *fLog << "fGChisq, fGNdf, fGProb = " << fGChisq << ",  " 
+        << fGNdf << ",  " << fGProb << endl; 
+
+
+  //------------------------------------
+  // get errors
+
+  Double_t eplus; 
+  Double_t eminus; 
+  Double_t eparab; 
+  Double_t gcc;
+  Double_t errdiag;
+
+  *fLog << "parameter value     error     eplus     eminus    eparab   errdiag   gcc"
+        << endl; 
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    if (gMinuit)
+      gMinuit->mnerrs(j, eplus, eminus, eparab, gcc);
+    errdiag = sqrt(fGEma[j][j]);
+    *fLog << j << "  " << fGValues[j] << "  "   << fGErrors[j] << "  "
+          << eplus     << "  "       << eminus << "  " << eparab     << "  " 
+          <<  errdiag  << "  "       << gcc    << endl;
+  }
+
+  
+  *fLog << "Covariance matrix :" << endl;
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=(fDegree+3); k++)
+    {
+      *fLog << fGEma[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "Correlation matrix :" << endl;
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=(fDegree+3); k++)
+    {
+      *fLog << fGCorr[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "---------------------------" << endl;
+}
+
+//============================================================================
+
Index: branches/Mars_McMismatchStudy/mhist/MHFindSignificance.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFindSignificance.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFindSignificance.h	(revision 17960)
@@ -0,0 +1,211 @@
+#ifndef MARS_MHFindSignificance
+#define MARS_MHFindSignificance
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TF1;
+class TH1;
+class TCanvas;
+
+class MHFindSignificance : public MH
+{
+private:
+
+    TH1  *fHistOrig;  // original plot of |alpha| (0.0 to 90.0 degrees)
+    TH1  *fHist;      // copy of fHistOrig or rebinned histogram
+
+    TH1D    *fSigVsAlpha;
+
+    Double_t fAlphamin;  // requested lower limit of fit range
+    Double_t fAlphammm;  // center of fit range
+    Double_t fAlphamax;  // requested lower limit of fit range
+
+    Double_t fAlphami;  // actual lower limit of fit range 
+    Double_t fAlphamm;  // actual center of fit range 
+    Double_t fAlphama;  // actual upper limit of fit range
+
+    Double_t fAlphasig; // requested signal range
+    Double_t fAlphasi;  // actual signal range
+
+    Double_t fAlphalow; // requested lower edge of signal range
+    Double_t fAlphalo;  // actual lower edge of signal range
+
+    Double_t fAlphahig; // requested upper edge of background range
+    Double_t fAlphahi;  // actual upper edge of background range
+ 
+    // number of events in signal region
+    Double_t fNon;     // total number of events in signal region
+    Double_t fNbg;     // number of background events in signal region
+    Double_t fNex;     // number of excess events in signal region
+
+    Double_t fdNon;
+    Double_t fdNbg;
+    Double_t fdNex;
+
+    // number of events in background region
+    Double_t fNbgtot;  // total number of events in background region
+    Double_t fNbgtotFitted;  // fitted total no. of events in background region
+    Double_t fdNbgtotFitted; // fitted error of this number
+
+    // effective number of background events
+    Double_t fNoff;
+    Double_t fGamma;   // Nbg = Non - gamma * Noff
+
+    Double_t fSigLiMa; // significance of gamma signal according to Li & Ma
+
+    const static Double_t fEps = 1.e-4;  // tolerance for floating point comparisons
+
+    Bool_t fDraw;          // if true : draw plots
+    Bool_t fFitGauss;      // if true : do the (polynomial+Gauss fit)
+    Bool_t fRebin;         // if true : allow rebinning of the alpha plot    
+    Bool_t fReduceDegree;  // if true : allow reducing of the order of the polynomial
+
+    Bool_t fConstantBackg; // if set true if background fit is not possible
+                           // due to low statistics
+
+    TCanvas  *fCanvas;
+
+    Double_t fNexGauss;    // total number of excess events 
+                           // (from fitted Gauss function)
+    Double_t fdNexGauss;   // error of the total number of excess events
+ 
+    Double_t fSigmaGauss;  // sigma of fitted Gauss function
+    Double_t fdSigmaGauss; // error of this sigma
+
+    //--------------------
+    TF1      *fPoly;   // polynomial function
+    Int_t    fFitBad;  // if != 0 fit failed
+    Int_t    fDegree;  // degree of polynomial to be fitted to the background
+    Int_t    fNdf;     // number of degrees of freedom of polynomial fit
+    Double_t fChisq;   // chi squared of polynomial fit
+    Double_t fProb;    // chi squared probability ofg polynomial fit 
+
+    TArrayD fValues;
+    TArrayD fErrors;
+
+    const static Int_t    fNdim = 6;
+    Double_t fEmat[fNdim][fNdim];
+    Double_t fEma [fNdim][fNdim];
+    Double_t fCorr[fNdim][fNdim];
+
+    Int_t  fMbins;     // number of bins in the fit range
+    Int_t  fMlow;      // number of bins in the fit range with too few entries
+    Int_t  fNzero;     // number of bins in the fit range with zero entry
+    Int_t  fIstat;
+
+    //--------------------
+
+    //--------------------
+    TF1      *fGPoly;   // (Gauss+polynomial) function
+    TF1      *fGBackg;  // polynomial part of (Gauss+polynomial) function
+    Int_t    fGFitBad;  // if != 0 fit failed
+    Int_t    fGDegree;  // degree of polynomial to be fitted to the background
+    Int_t    fGNdf;     // number of degrees of freedom of polynomial fit
+    Double_t fGChisq;   // chi squared of polynomial fit
+    Double_t fGProb;    // chi squared probability ofg polynomial fit 
+
+    TArrayD fGValues;
+    TArrayD fGErrors;
+
+    const static Int_t    fGNdim = 9;
+    Double_t fGEmat[fGNdim][fGNdim];
+    Double_t fGEma[fGNdim][fGNdim];
+    Double_t fGCorr[fGNdim][fGNdim];
+
+    Int_t  fGMbins;     // number of bins in the fit range
+    Int_t  fGNzero;     // numnber of bins in the fit range with zero entry
+    Int_t  fGIstat;
+
+    //--------------------
+
+    static const TString gsDefName;  //! Default Name
+    static const TString gsDefTitle; //! Default Title
+
+    Bool_t DetExcess(); 
+    Bool_t FitPolynomial();
+    Bool_t FitGaussPoly();
+    Bool_t RebinHistogram(Double_t x0, Int_t nrebin);
+
+public:
+    MHFindSignificance(const char *name=NULL, const char *title=NULL);
+    ~MHFindSignificance();
+
+    Bool_t FindSigma(TH1 *fhist,  Double_t alphamin, Double_t alphamax, 
+                     Int_t degree, Double_t alphasig, 
+                     Bool_t drawpoly, Bool_t fitgauss, Bool_t print);
+
+    Bool_t SigmaLiMa(Double_t non, Double_t noff, Double_t gamma,
+                     Double_t *siglima);
+
+    Bool_t SigmaVsAlpha(TH1 *fhist,   Double_t alphamin, Double_t alphamax, 
+                        Int_t degree, Bool_t print);
+
+    Double_t GetSignificance()   { return fSigLiMa; }
+
+    Bool_t DrawFit(Option_t *opt=NULL);
+
+    Int_t    GetDegree()     const { return fDegree;  }
+    Double_t GetProb()       const { return fProb;    }
+    Int_t    GetNdf()        const { return fNdf;     }
+    Double_t GetGamma()      const { return fGamma;   }
+    Double_t GetNon()        const { return fNon;     }
+    Double_t GetNex()        const { return fNex;     }
+    Double_t GetNbg()        const { return fNbg;     }
+    Double_t GetSigLiMa()    const { return fSigLiMa; }
+    Int_t    GetMbins()      const { return fMbins;   }
+    Double_t GetAlphasi()    const { return fAlphasi; }
+
+    TH1* GetHist() const { return fHist;}
+    Double_t GetdNon() const { return fNon;}
+    Double_t GetdNbg() const {return fNbg; } 
+    Double_t GetdNex()        const { return fdNex;     }
+    Double_t GetNoff() const {return fNoff;}
+    Double_t GetChisq() const {return fChisq;}
+    Double_t GetNbgtotFitted() const {return fNbgtotFitted;}
+    Double_t GetdNbgtotFitted() const {return fNbgtotFitted;}
+    Double_t GetNbgtot() const {return fNbgtot;}
+    Double_t GetSigmaGauss() const {return fSigmaGauss;}
+    Double_t GetdSigmaGauss() const {return fdSigmaGauss;}
+    Double_t GetNexGauss() const {return fNexGauss;}
+    Double_t GetdNexGauss() const {return fdNexGauss;}
+    TF1*    GetGBackg()     const { return fGBackg;  }
+    TF1*    GetGPoly()      const { return fGPoly;   }
+    TF1*    GetPoly()       const { return fPoly;    }
+
+
+    void SetRebin(Bool_t b=kTRUE);
+    void SetReduceDegree(Bool_t b=kTRUE);
+
+    void PrintPoly(Option_t *opt=NULL);
+    void PrintPolyGauss(Option_t *opt=NULL);
+
+    ClassDef(MHFindSignificance, 1) // Determine significance from alpha plot
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mhist/MHFlux.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFlux.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFlux.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHFlux.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHFlux.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHFlux.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhist/MHHadronness.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHHadronness.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHHadronness.cc	(revision 17960)
@@ -0,0 +1,580 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHHadronness
+//
+// This is histogram is a way to evaluate the quality of a gamma/hadron
+// seperation method. It is filled from a MHadronness container, which
+// stores a hadroness for the current event. The Value must be in the
+// range [0,1]. To fill the histograms correctly the information
+// whether it is a gamma or hadron (not a gamma) must be available from
+// a MMcEvt container.
+//
+// In the constructor you can change the number of used bns for the
+// evaluation.
+//
+// The meaning of the histograms (Draw, DrawClone) are the following:
+//  * Upper Left Corner:
+//    - black: histogram of all hadronesses for gammas
+//    - red:   histogram of all hadronesses for non gammas
+//  * Upper Right Corner:
+//    - black: acceptance of gammas (Ag) vs. the hadroness
+//    - red:   acceptance of non gammas (Ah) vs. the hadroness
+//  * Bottom Left Corner:
+//    Naive quality factor: Ag/sqrt(Ah)
+//  * Bottom Right Corner:
+//    - black: Acceptance Gammas vs. Acceptance Hadrons
+//    - blue cross: minimum of distance to (0, 1)
+//
+// As a default MHHadronness searches for the container "MHadronness".
+// This can be overwritten by a different pointer specified in the
+// Fill function (No type check is done!) Use a different name in
+// MFillH.
+//
+// If you are using filtercuts which gives you only two discrete values
+// of the hadronness (0.25 and 0.75) you may want to use MHHadronness(2).
+// If you request Q05() from such a MHHadronness instance you will get
+// Acc_g/sqrt(Acc_h)
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHHadronness.h"
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TMath.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MHMatrix.h"
+#include "MParameters.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MHHadronness);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms, nbins is the number of bins used for the evaluation.
+// The default is 100 bins.
+//
+MHHadronness::MHHadronness(Int_t nbins, const char *name, const char *title)
+    : fMatrix(NULL)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHHadronness";
+    fTitle = title ? title : "Gamma/Hadron Separation Quality Histograms";
+
+    fGraph = new TGraph;
+    fGraph->SetTitle("Acceptance Gammas vs. Hadrons");
+    fGraph->SetMarkerStyle(kFullDotSmall);
+
+    fGhness = new TH1D("Ghness", "Acceptance vs. Hadronness (Gammas)",  nbins, 0, 1.0001);
+    fPhness = new TH1D("Phness", "Acceptance vs. Hadronness (Hadrons)", nbins, 0, 1.0001);
+    fGhness->SetXTitle("Hadronness");
+    fPhness->SetXTitle("Hadronness");
+    fGhness->SetYTitle("Acceptance");
+    fPhness->SetYTitle("Acceptance");
+    fPhness->SetLineColor(kRed);
+    fGhness->SetDirectory(NULL);
+    fPhness->SetDirectory(NULL);
+    
+    fIntGhness = new TH1D("AccGammas",  "Integral Acceptance vs. Hadronness (Gammas)", nbins, 0, 1);
+    fIntPhness = new TH1D("AccHadrons", "Integral Acceptance vs. Hadronness (Hadrons)", nbins, 0, 1);
+    fIntGhness->SetXTitle("Hadronness");
+    fIntPhness->SetXTitle("Hadronness");
+    fIntGhness->SetYTitle("Acceptance");
+    fIntPhness->SetYTitle("Acceptance");
+    fIntGhness->SetMaximum(1);
+    fIntPhness->SetMaximum(1);
+    fIntGhness->SetMinimum(0);
+    fIntPhness->SetMinimum(0);
+    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 = (MParameterD*)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.
+//
+Int_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 kERROR;
+    }
+
+    const MParameterD &had = par ? *(MParameterD*)par : *fHadronness;
+
+    const Double_t h = TMath::Min(TMath::Max(had.GetVal(), 0.), 1.);
+
+    if (!TMath::Finite(h))
+        return kTRUE;  // Use kCONTINUE with extreme care!
+
+    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: branches/Mars_McMismatchStudy/mhist/MHHadronness.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHHadronness.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHHadronness.h	(revision 17960)
@@ -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 MParameterD;
+class MHMatrix;
+
+class MHHadronness : public MH
+{
+private:
+    const MMcEvt      *fMcEvt;      //!
+    const MParameterD *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);
+    Int_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: branches/Mars_McMismatchStudy/mhist/MHRate.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHRate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHRate.cc	(revision 17960)
@@ -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, 07/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHRate
+//
+// Display information about software trigger rate
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHRate.h"
+
+#include <TCanvas.h>
+#include <TGaxis.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MTime.h"
+#include "MEventRate.h"
+#include "MPointingPos.h"
+#include "MBinning.h"
+
+ClassImp(MHRate);
+
+using namespace std;
+
+void MHRate::ResetGraph(TGraph &g) const
+{
+    g.Set(1);
+    g.SetPoint(0, 0, 0); // Dummy Point
+    g.SetEditable();     // Used as flag: First point? yes/no
+}
+
+void MHRate::InitGraph(TGraph &g) const
+{
+    ResetGraph(g);
+    g.SetMarkerStyle(kFullDotMedium);
+}
+
+void MHRate::AddPoint(TGraph &g, Double_t x, Double_t y) const
+{
+    if (g.IsEditable())
+    {
+        g.RemovePoint(0);
+        g.SetEditable(kFALSE);
+    }
+
+    g.SetPoint(g.GetN(), x, y);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHRate::MHRate(const char *name, const char *title)
+: /*fTime(0),*/ fPointPos(0), fEvtRate(0)
+{
+    fName  = name  ? name  : "MHRate";
+    fTitle = title ? title : "Graphs for rate data";
+
+    // Init Graphs
+    fRateTime.SetNameTitle("RateTime", "Rate vs Time");
+    fRateZd.SetNameTitle("RateZd", "Rate vs Zenith distance");
+    fRate.SetNameTitle("Rate", "Distribution of Rate");
+
+    InitGraph(fRateTime);
+
+    fRateZd.SetXTitle("Zd [\\circ]");
+    fRateZd.SetYTitle("Rate [Hz]");
+
+    fRate.SetXTitle("Rate [Hz]");
+    fRate.SetYTitle("Counts");
+
+    fRate.SetDirectory(0);
+    fRateZd.SetDirectory(0);
+
+    fRateZd.SetMarkerStyle(kFullDotMedium);
+    fRateZd.SetBit(TH1::kNoStats);
+
+    MBinning b;
+    b.SetEdges(120, 0, 1200);
+    b.Apply(fRate);
+
+    b.SetEdgesASin(67, -0.005, 0.665);
+    b.Apply(fRateZd);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHRate::SetupFill(const MParList *plist)
+{
+    fEvtRate = (MEventRate*)plist->FindObject("MEventRate");
+    if (!fEvtRate)
+    {
+        *fLog << err << "MEventRate not found... abort." << endl;
+        return kFALSE;
+    }
+    fPointPos = (MPointingPos*)plist->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointingPos not found... abort." << endl;
+        return kFALSE;
+    }
+
+    // Reset Graphs
+    ResetGraph(fRateTime);
+
+    fCounter = 0;
+    fMean    = 0;
+    fLast    = MTime();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MMuonCalibPar and
+// MMuonSearchPar container.
+//
+Int_t MHRate::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MTime *t = dynamic_cast<const MTime*>(par);
+    if (!t)
+    {
+        *fLog << err <<"MHRate::Fill - ERROR: MTime not given as argument... abort." << endl;
+        return kERROR;
+    }
+
+    const Double_t rate = fEvtRate->GetRate();
+    if (rate<0)
+        return kTRUE;
+
+    const Double_t tm   = t->GetAxisTime();
+
+    if (fLast==MTime())
+        fLast = MTime();
+
+    fMean += rate;
+    fCounter++;
+
+    if ((double)*t > (double)fLast+5 && fCounter>0)
+    {
+        AddPoint(fRateTime, tm, fMean/fCounter);
+        fMean     = 0;
+        fCounter = 0;
+        fLast = *t;
+    }
+
+    fRateZd.Fill(fPointPos->GetZd(), rate);
+    fRate.Fill(rate);
+
+    return kTRUE;
+}
+
+void MHRate::DrawGraph(TGraph &g, const char *y) const
+{
+    // If this is set to early the plot remains empty in root 5.12/00
+    if (g.GetN()>0)
+        g.SetMinimum(0);
+
+    // This is not done automatically anymore since root 5.12/00
+    // and it is necessary to force a proper update of the axis.
+    TH1 *h = g.GetHistogram();
+    if (h)
+    {
+        delete h;
+        g.SetHistogram(0);
+        h = g.GetHistogram();
+    }
+
+    if (h)
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetLabelSize(0.033);
+        axe->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+        axe->SetTimeDisplay(1);
+        axe->SetTitle("Time");
+        if (y)
+            h->SetYTitle(y);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Update position of an axis on the right side of the histogram
+/*
+void MHRate::UpdateRightAxis(TGraph &g) const
+{
+    TH1 &h = *g.GetHistogram();
+
+    const Double_t max = h.GetMaximum();
+    if (max==0)
+        return;
+
+    TGaxis *axis = (TGaxis*)gPad->FindObject("RightAxis");
+    if (!axis)
+        return;
+
+    axis->SetX1(g.GetXaxis()->GetXmax());
+    axis->SetX2(g.GetXaxis()->GetXmax());
+    axis->SetY1(gPad->GetUymin());
+    axis->SetY2(gPad->GetUymax());
+    axis->SetWmax(max);
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Draw an axis on the right side of the histogram
+//
+/*
+void MHRate::DrawRightAxis(const char *title) const
+{
+    TGaxis *axis = new TGaxis(gPad->GetUxmax(), gPad->GetUymin(),
+                              gPad->GetUxmax(), gPad->GetUymax(),
+                              0, 1, 510, "+L");
+    axis->SetName("RightAxis");
+    axis->SetTitle(title);
+    axis->SetTitleOffset(0.9);
+    axis->SetTextColor(kRed);
+    axis->SetBit(kCanDelete);
+    axis->Draw();
+}
+*/
+// --------------------------------------------------------------------------
+//
+// This displays the TGraph like you expect it to be (eg. time on the axis)
+// It should also make sure, that the displayed time always is UTC and
+// not local time...
+//
+void MHRate::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    gPad->SetLogy();
+    fRate.Draw();
+    //fHumidity.Draw("AP");
+    //fTemperature.Draw("P");
+    //DrawRightAxis("T [\\circ C]");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fRateTime.Draw("AP");
+    //fSolarRadiation.Draw("AP");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fRateZd.Draw();
+
+    if (pad->GetPad(4))
+        delete pad->GetPad(4);
+
+    /*
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fWindSpeed.Draw("AP");*/
+}
+
+void MHRate::Paint(Option_t *o)
+{
+    DrawGraph(fRateTime, "f [Hz]");
+    /*
+    gPad->cd(1);
+
+    if (gPad)
+    {
+        fHumidity.GetHistogram()->GetYaxis()->SetTitleColor(kBlue);
+        UpdateRightAxis(fTemperature);
+    }*/
+}
Index: branches/Mars_McMismatchStudy/mhist/MHRate.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHRate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHRate.h	(revision 17960)
@@ -0,0 +1,58 @@
+#ifndef MARS_MHRate
+#define MARS_MHRate
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TGraph
+#include <TGraph.h>
+#endif
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+//class MTime;
+class MEventRate;
+class MPointingPos;
+
+class MHRate : public MH
+{
+private:
+    TGraph   fRateTime;      // Graph of rate versus time
+    TProfile fRateZd;        // Profile of rate vs Zd
+    TH1D     fRate;          // Rate histogram
+
+    //MTime        *fTime;   //!
+    MPointingPos *fPointPos; //!
+    MEventRate   *fEvtRate;  //!
+
+    MTime fLast;             //!
+
+    Double_t fMean;          //!
+    Int_t    fCounter;       //!
+
+    void ResetGraph(TGraph &g) const;
+    void InitGraph(TGraph &g) const;
+    void AddPoint(TGraph &g, Double_t x, Double_t y) const;
+    void DrawGraph(TGraph &g, const char *y=0) const;
+    //void UpdateRightAxis(TGraph &g) const;
+    //void DrawRightAxis(const char *title) const;
+
+public:
+    MHRate(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHRate, 1) // Histogram to display information about rate
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mhist/MHStarMap.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHStarMap.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHStarMap.cc	(revision 17960)
@@ -0,0 +1,419 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    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;
+
+        const MBinning b(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
+//
+Int_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: branches/Mars_McMismatchStudy/mhist/MHStarMap.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHStarMap.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHStarMap.h	(revision 17960)
@@ -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);
+    Int_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) const { 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: branches/Mars_McMismatchStudy/mhist/MHTriggerLvl0.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHTriggerLvl0.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHTriggerLvl0.cc	(revision 17960)
@@ -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.
+//
+Int_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 kERROR;
+    }
+
+    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) const
+{
+    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: branches/Mars_McMismatchStudy/mhist/MHTriggerLvl0.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHTriggerLvl0.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHTriggerLvl0.h	(revision 17960)
@@ -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);
+    Int_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="") const;
+
+    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: branches/Mars_McMismatchStudy/mhist/MHWeather.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHWeather.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHWeather.cc	(revision 17960)
@@ -0,0 +1,356 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHWeather
+//
+// Display weather and pyrometer data and the corresponding event rate
+//
+// Class Version 2:
+// ----------------
+//  - fSolarRadiation
+//  + fCloudiness
+//  + fTempSky
+//  + fTempAir
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHWeather.h"
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+#include <TGaxis.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MTime.h"
+#include "MReportCC.h"
+#include "MReportPyrometer.h"
+#include "MEventRate.h"
+
+ClassImp(MHWeather);
+
+using namespace std;
+
+void MHWeather::ResetGraph(TGraph &g) const
+{
+    g.Set(1);
+    g.SetPoint(0, 0, 0); // Dummy Point
+    g.SetEditable();     // Used as flag: First point? yes/no
+}
+
+void MHWeather::InitGraph(TGraph &g) const
+{
+    ResetGraph(g);
+    g.SetMarkerStyle(kFullDotMedium);
+}
+
+void MHWeather::AddPoint(TGraph &g, Double_t x, Double_t y) const
+{
+    if (g.IsEditable())
+    {
+        g.RemovePoint(0);
+        g.SetEditable(kFALSE);
+    }
+
+    g.SetPoint(g.GetN(), x, y);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHWeather::MHWeather(const char *name, const char *title)
+: fReportCC(0), fReportPyro(0), fRate(0)
+{
+    fName  = name  ? name  : "MHWeather";
+    fTitle = title ? title : "Graphs for weather data";
+
+    // Init Graphs
+
+    fHumidity.SetNameTitle("Humidity", "Humidity");
+    fTemperature.SetNameTitle("Temperature", "Temperature (red=weather station, black=pyrometer, blue=sky)");
+    fWindSpeed.SetNameTitle("WindSpeed", "Wind Speed");
+
+    fEventRate.SetNameTitle("EventRate", "Event Rate at CC-REPORT time");
+
+    fCloudiness.SetNameTitle("Cloudiness", "Cloudiness / Humidity");
+    fTempAir.SetNameTitle("TempAir", "Air temperature from Pyrometer");
+    fTempSky.SetNameTitle("TempSky", "Sky temperature from Pyrometer");
+
+    InitGraph(fHumidity);
+    InitGraph(fTemperature);
+    InitGraph(fWindSpeed);
+
+    InitGraph(fEventRate);
+
+    InitGraph(fCloudiness);
+    InitGraph(fTempAir);
+    InitGraph(fTempSky);
+
+    fHumidity.SetMarkerColor(kBlue);
+    fTemperature.SetMarkerColor(kRed);
+    fTempSky.SetMarkerColor(kBlue);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHWeather::SetupFill(const MParList *plist)
+{
+    // Remark: This is called twice in the star-eventloop!
+    fReportCC = (MReportCC*)plist->FindObject("MReportCC");
+    if (!fReportCC)
+    {
+        *fLog << warn << "MReportCC not found... abort." << endl;
+        return kFALSE;
+    }
+    fRate = (MEventRate*)plist->FindObject("MEventRate");
+    if (!fRate)
+    {
+        *fLog << warn << "MEventRate not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fReportPyro = (MReportPyrometer*)plist->FindObject("MReportPyrometer");
+    if (!fReportPyro)
+        *fLog << warn << "MReportPyrometer not found..." << endl;
+
+    // Reset Graphs
+    ResetGraph(fHumidity);
+    ResetGraph(fTemperature);
+    ResetGraph(fWindSpeed);
+    ResetGraph(fEventRate);
+    ResetGraph(fCloudiness);
+    ResetGraph(fTempAir);
+    ResetGraph(fTempSky);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MMuonCalibPar and
+// MMuonSearchPar container.
+//
+Int_t MHWeather::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MTime *t = dynamic_cast<const MTime*>(par);
+    if (!t)
+    {
+        *fLog << err <<"MHWeather::Fill - ERROR: MTime not given as argument... abort." << endl;
+        return kERROR;
+    }
+
+    const Double_t tm = t->GetAxisTime();
+
+    AddPoint(fEventRate, tm, fRate->GetRate());
+
+    if (TString(t->GetName())=="MTimeCC")
+    {
+        AddPoint(fTemperature, tm, fReportCC->GetTemperature());
+        AddPoint(fHumidity,    tm, fReportCC->GetHumidity());
+        AddPoint(fWindSpeed,   tm, fReportCC->GetWindSpeed());
+    }
+
+    if (TString(t->GetName())=="MTimePyrometer" && fReportPyro)
+    {
+        AddPoint(fCloudiness, tm, fReportPyro->GetCloudiness());
+        AddPoint(fTempAir,    tm, fReportPyro->GetTempAir());
+        AddPoint(fTempSky,    tm, fReportPyro->GetTempSky()-200);
+    }
+
+    return kTRUE;
+}
+
+void MHWeather::DrawGraph(TGraph &g, const char *y) const
+{
+    TH1 *h = g.GetHistogram();
+    if (h)
+    {
+        delete h;
+        g.SetHistogram(0);
+        h = g.GetHistogram();
+    }
+    if (h)
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetLabelSize(0.033);
+        axe->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+        axe->SetTimeDisplay(1);
+        axe->SetTitle("Time");
+        if (y)
+            h->SetYTitle(y);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Update position of an axis on the right side of the histogram
+//
+void MHWeather::UpdateRightAxis(TGraph &g) const
+{
+    TH1 &h = *g.GetHistogram();
+
+    const Double_t max = h.GetMaximum();
+    if (max==0)
+        return;
+
+    TGaxis *axis = (TGaxis*)gPad->FindObject("RightAxis");
+    if (!axis)
+        return;
+
+    axis->SetX1(g.GetXaxis()->GetXmax());
+    axis->SetX2(g.GetXaxis()->GetXmax());
+    axis->SetY1(gPad->GetUymin());
+    axis->SetY2(gPad->GetUymax());
+    axis->SetWmax(max);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw an axis on the right side of the histogram
+//
+void MHWeather::DrawRightAxis(const char *title, Int_t col) const
+{
+    TGaxis *axis = new TGaxis(gPad->GetUxmax(), gPad->GetUymin(),
+                              gPad->GetUxmax(), gPad->GetUymax(),
+                              0, 1, 510, "+L");
+    axis->SetBit(TAxis::kRotateTitle);
+    axis->SetName("RightAxis");
+    axis->SetTitle(title);
+    axis->SetTitleOffset(1.2);
+    axis->SetTextColor(col);
+    axis->SetLabelColor(col);
+    axis->SetBit(kCanDelete);
+    axis->Draw();
+}
+
+// --------------------------------------------------------------------------
+//
+// This displays the TGraph like you expect it to be (eg. time on the axis)
+// It should also make sure, that the displayed time always is UTC and
+// not local time...
+//
+void MHWeather::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fTemperature.Draw("AP");
+    fTempAir.Draw("P");
+    fTempSky.Draw("P");
+    DrawRightAxis("T_{sky}-200 [K]", kBlue);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+     fHumidity.Draw("AP");
+    fCloudiness.Draw("P");
+    DrawRightAxis("Cloudiness [%]");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fWindSpeed.Draw("AP");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fEventRate.Draw("AP");
+}
+
+void MHWeather::Paint(Option_t *o)
+{
+    // If this is set to early the plot remains empty in root 5.12/00
+    if (fHumidity.GetN()>0)
+    {
+        fHumidity.SetMinimum(0);
+        fHumidity.SetMaximum(100);
+    }
+    if (fCloudiness.GetN()>0)
+    {
+        fCloudiness.SetMinimum(0);
+        fCloudiness.SetMaximum(100);
+    }
+
+    if (fTemperature.GetN()>0)
+    {
+        fTemperature.SetMinimum(-2.5);
+        fTemperature.SetMaximum(27.5);
+    }
+    if (fTempSky.GetN()>0)
+    {
+        fTempSky.SetMinimum(-2.5);
+        fTempSky.SetMaximum(27.5);
+    }
+    if (fWindSpeed.GetN()>0)
+        fWindSpeed.SetMinimum(0);
+    if (fEventRate.GetN()>0)
+        fEventRate.SetMinimum(0);
+
+    DrawGraph(fHumidity,    "Humidity [%]");
+    DrawGraph(fTemperature, "T [\\circ C]");
+    DrawGraph(fWindSpeed,   "km/h");
+    DrawGraph(fEventRate,   "f [Hz]");
+    DrawGraph(fCloudiness,  "Cloudiness [%]");
+    DrawGraph(fTempAir,     "T [\\circ C]");
+    DrawGraph(fTempSky,     "T_{sky}-200 [K]");
+
+    TVirtualPad *p = gPad;
+
+    p->cd(1);
+    if (gPad)
+    {
+        fTemperature.GetYaxis()->SetLabelColor(kRed);
+        fTemperature.GetYaxis()->SetTitleColor(kRed);
+        UpdateRightAxis(fTemperature); // Primary axis
+    }
+
+    p->cd(2);
+    if (gPad)
+    {
+        fHumidity.GetYaxis()->SetLabelColor(kBlue);
+        fHumidity.GetYaxis()->SetTitleColor(kBlue);
+        fHumidity.GetYaxis()->SetTitleOffset(1.2);
+        UpdateRightAxis(fHumidity);    // Primary axis
+    }
+}
Index: branches/Mars_McMismatchStudy/mhist/MHWeather.h
===================================================================
--- branches/Mars_McMismatchStudy/mhist/MHWeather.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/MHWeather.h	(revision 17960)
@@ -0,0 +1,56 @@
+#ifndef MARS_MHWeather
+#define MARS_MHWeather
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TGraph
+#include <TGraph.h>
+#endif
+
+class MReportCC;
+class MReportPyrometer;
+class MEventRate;
+
+class MHWeather : public MH
+{
+private:
+    TGraph fHumidity;        // Humidity from weather station
+    TGraph fTemperature;     // Temperature from weather station
+    TGraph fWindSpeed;       // Wind Speed from weather station
+
+    TGraph fEventRate;       // Event rate from event times
+
+    TGraph fCloudiness;      // Cloudiness from Pyrometer
+    TGraph fTempAir;         // Temperature of the air from Pyrometer
+    TGraph fTempSky;         // Temperature of the sky from Pyrometer
+
+    MReportCC        *fReportCC;    //! CC report with data from weather station
+    MReportPyrometer *fReportPyro;  //! Pyrometer report
+    MEventRate       *fRate;        //! Event rate
+
+    void ResetGraph(TGraph &g) const;
+    void InitGraph(TGraph &g) const;
+    void AddPoint(TGraph &g, Double_t x, Double_t y) const;
+    void DrawGraph(TGraph &g, const char *y=0) const;
+    void UpdateRightAxis(TGraph &g) const;
+    void DrawRightAxis(const char *title, Int_t col=kBlack) const;
+
+public:
+    MHWeather(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    // If this is needed be aware that it would be called twice in star
+    // Bool_t Finalize()
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHWeather, 2) // Histogram to display weather and pyrometer data
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mhist/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mhist/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhist/Makefile	(revision 17960)
@@ -0,0 +1,46 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Hist
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mraw -I../manalysis      \
+	   -I../mgui -I../mgeom -I../mdata -I../mfilter -I../mimage \
+           -I../mpointing -I../mmc  -I../mastro -I../msignal        \
+           -I../mbadpixels -I../mcalib -I../mreport -I../mtrigger
+
+SRCFILES = MHEvent.cc \
+	   MHCamEvent.cc \
+           MHCamEventRot.cc \
+           MHStarMap.cc \
+           MHHadronness.cc \
+	   MHTriggerLvl0.cc \
+           MHCamera.cc \
+           MHRate.cc \
+           MHWeather.cc
+
+#           MHFadcPix.cc \
+#           MHFadcCam.cc \
+#           MHCompProb.cc \
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mhistmc/HistMcIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/HistMcIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/HistMcIncl.h	(revision 17960)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mhistmc/HistMcLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/HistMcLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/HistMcLinkDef.h	(revision 17960)
@@ -0,0 +1,21 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHMcRate+;
+#pragma link C++ class MHMcDifRate+;
+#pragma link C++ class MHMcIntRate+;
+#pragma link C++ class MHMcEfficiency+;
+#pragma link C++ class MHMcEfficiencyImpact+;
+#pragma link C++ class MHMcEfficiencyEnergy+;
+#pragma link C++ class MHMcEnergy+;
+#pragma link C++ class MHMcEnergyImpact+;
+#pragma link C++ class MHMcCollectionArea+;
+#pragma link C++ class MHMcEnergyMigration+;
+#pragma link C++ class MHMcCT1CollectionArea+;
+#pragma link C++ class MHMcTriggerLvl2+;
+#pragma link C++ class MHMcUnfoldCoeff+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mhistmc/MHMcCT1CollectionArea.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcCT1CollectionArea.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcCT1CollectionArea.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcCT1CollectionArea.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcCT1CollectionArea.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcCT1CollectionArea.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcCollectionArea.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcCollectionArea.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcCollectionArea.cc	(revision 17960)
@@ -0,0 +1,392 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !   Author(s): Harald Kornmayer 1/2001
+   !   Author(s): Abelardo Moralejo 2/2005 <mailto:moralejo@pd.infn.it>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2005
+   !
+   !
+   \* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHMcCollectionArea                                                      //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHMcCollectionArea.h" 
+
+#include <TH2.h>
+#include <TH3.h>
+#include <TCanvas.h>
+#include <THStack.h>
+#include <TLegend.h>
+#include <TArrayD.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MHMcCollectionArea);
+
+using namespace std;
+
+////////////////////////////////////////////////////////////////////////////////
+//
+//  Constructor. Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHMcCollectionArea::MHMcCollectionArea(const char *name, const char *title):
+  fImpactBins(50), fImpactMax(500.), fMinEvents(10)
+{ 
+  fName  = name  ? name  : "MHMcCollectionArea";
+  fTitle = title ? title : "Collection Area vs. Theta vs. Energy";
+
+  //
+  //   Initialize the histogram for the distribution 
+  //   Theta vs impact parameter vs E (z, y, x)
+  //
+  //   As default we set the energy range from 2 Gev to 20000 GeV (in log 4 
+  //   orders of magnitude) and for each order we take 25 subdivisions --> 
+  //   100 xbins. We set the radius range from 0 m to 500 m with 10 m bin --> 
+  //   50 ybins. We make bins equally spaced in cos(theta)
+  //
+  //   The coarse binning (of fHistColCoarse) is not set by default, the
+  //   PreProcess of mmc/MMcCollectionAreaCalc will do it with the binnings
+  //   found in the parameter list.
+  //
+
+  MBinning binsx;
+  MBinning binsy;
+  MBinning binsz;
+
+  Int_t nbins = 32;
+  TArrayD edges(nbins+1);
+    
+  edges[0] = 0;
+    
+  for(int i = 0; i < nbins; i++)
+    {
+      Double_t x = 1 - i*0.01;  // x = cos(theta) 
+      edges[i+1] = acos(x-0.005)*kRad2Deg;
+    }
+
+  binsx.SetEdgesLog(100, 2., 20000);               // Energy [GeV]
+  binsy.SetEdges   (fImpactBins, 0, fImpactMax);   // Impact parameter [m]
+  binsz.SetEdges   (edges);                        // Theta [deg]
+
+  fHistAll = new TH3D();
+  fHistSel = new TH3D();
+  fHistCol = new TH2D();
+  fHistColCoarse = new TH2D();
+ 
+  MH::SetBinning(fHistAll, &binsx, &binsy, &binsz);
+  MH::SetBinning(fHistSel, &binsx, &binsy, &binsz);
+
+  fHistColCoarse->SetName("CollectionArea");
+  fHistCol->SetName("CollAreaFineBins");
+  fHistAll->SetName("AllEvents");
+  fHistSel->SetName("SelectedEvents");
+
+  fHistAll->Sumw2();
+  fHistSel->Sumw2();
+
+  fHistColCoarse->SetTitle(fTitle);
+  fHistCol->SetTitle(fTitle);
+  fHistAll->SetTitle("All showers - Theta vs Radius vs Energy");
+  fHistSel->SetTitle("Selected showers - Theta vs Radius vs Energy");
+
+  fHistAll->SetDirectory(NULL);
+  fHistSel->SetDirectory(NULL);
+  fHistCol->SetDirectory(NULL);
+  fHistColCoarse->SetDirectory(NULL);
+
+  fHistAll->UseCurrentStyle();
+  fHistSel->UseCurrentStyle();
+  fHistCol->UseCurrentStyle();
+  fHistColCoarse->UseCurrentStyle();
+
+  fHistAll->SetXTitle("E [GeV]");
+  fHistAll->SetYTitle("r [m]"); 
+  fHistAll->SetZTitle("\\theta [\\circ]");
+
+  fHistSel->SetXTitle("E [GeV]");
+  fHistSel->SetYTitle("r [m]");
+  fHistSel->SetZTitle("\\theta [\\circ]");
+
+  fHistCol->SetXTitle("E [GeV]");
+  fHistCol->SetYTitle("\\theta [\\circ]");
+  fHistCol->SetZTitle("A [m^{2}]");
+
+  fHistColCoarse->SetXTitle("E [GeV]");
+  fHistColCoarse->SetYTitle("\\theta [\\circ]");
+  fHistColCoarse->SetZTitle("A [m^{2}]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the three histograms
+//
+MHMcCollectionArea::~MHMcCollectionArea()
+{
+  delete fHistAll;
+  delete fHistSel;
+  delete fHistCol;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the (fine) binnings of histograms fHistAll, fHistSel used in the 
+// calculations. We do not need to change impact parameter binning.
+//
+void MHMcCollectionArea::SetBinnings(const MBinning &binsEnergy, 
+				     const MBinning &binsTheta)
+{
+  MBinning binsImpact;
+  binsImpact.SetEdges(fImpactBins, 0., fImpactMax);
+
+  MH::SetBinning(fHistAll, &binsEnergy, &binsImpact, &binsTheta);
+  MH::SetBinning(fHistSel, &binsEnergy, &binsImpact, &binsTheta);
+
+  fHistAll->Sumw2();
+  fHistSel->Sumw2();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings of the histogram fHistColCoarse, the effective areas
+// in the coarse bins used in the analysis.
+//
+//
+void MHMcCollectionArea::SetCoarseBinnings(const MBinning &binsEnergy, 
+					   const MBinning &binsTheta)
+{
+  MH::SetBinning(fHistColCoarse, &binsEnergy, &binsTheta);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains all showers
+//
+void MHMcCollectionArea::FillAll(Double_t energy, Double_t radius, Double_t theta)
+{
+  fHistAll->Fill(energy, radius, theta);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains the selected showers
+//
+void MHMcCollectionArea::FillSel(Double_t energy, Double_t radius, Double_t theta)
+{
+  fHistSel->Fill(energy, radius, theta);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw
+//
+void MHMcCollectionArea::Draw(Option_t* option)
+{
+  //
+  // Lego plot
+  //
+  TCanvas *c1 = new TCanvas();  
+  c1->SetLogx();
+  c1->SetLogz();
+  c1->SetGridx();
+  c1->SetGridy();
+
+  fHistCol->Draw("lego2");
+    
+  //
+  // Averagye Aeff
+  //
+  TCanvas *c2 = new TCanvas();
+  c2->SetLogx();
+  c2->SetLogy();
+  c2->SetGridx();
+  c2->SetGridy();
+
+  TH1D* harea = fHistCol->ProjectionX();
+  harea->Draw("e1");
+  
+  //
+  // Plot the Aeff for the different theta
+  //
+  TCanvas *c3 = new TCanvas();
+  c3->SetLogx();
+  c3->SetLogy();
+  c3->SetGridx();
+  c3->SetGridy();
+
+  TLegend * leg = new TLegend(0.73,0.65,0.89,0.89);
+   
+  TAxis* yaxis = fHistCol->GetYaxis();
+  const Int_t nbiny = fHistCol->GetYaxis()->GetNbins();
+    
+  THStack* hs = new THStack("aa","aa");
+
+  hs->Add(harea,"e1");
+  leg->AddEntry(harea,"All","l");
+
+  for(Int_t iy=1; iy<=nbiny; iy++)
+    {
+
+      TH1D* h1=  fHistCol->ProjectionX(Form("%d",iy),iy,iy);
+
+      if(h1->GetEntries()==0)
+	continue;
+
+      cout <<h1->GetEntries() << endl;
+
+      leg->AddEntry(h1,Form("\\theta = %.0f",yaxis->GetBinCenter(iy)),"l");
+      h1->SetLineColor(iy);
+      hs->Add(h1,"e1");
+    }
+  hs->SetMinimum(1);
+  
+  hs->Draw("nostack");
+  leg->Draw();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the collection area and set the 'ReadyToSave' flag
+// We first calculate the area in fine energy bins, and then do a
+// weighted mean to obtain the area in coarse bins. The weights in
+// the coarse bins are intended to account for the effect of the 
+// energy spectrum in the effective area itself. The weights 
+// are taken from the tentative differential spectrum dN_gam/dE given 
+// through the function "spectrum". If no such function is supplied, 
+// then no weights are applied (and hence the spectrum will be as a 
+// flat spectrum in dN_gam/dE). Of course we have a "generated" MC
+// spectrum, but within each fine bin the differences in spectrum 
+// should not change the result (if bins are fine enough). With no 
+// supplied tentative spectrum, each fine bin is weighted equally in
+// calculating the area in the coarse bin, and so it is like having a 
+// flat spectrum.
+//
+// You can run this Calc procedure on an already existing 
+// MHMcCollectionArea object, as long as it is filled.
+//
+void MHMcCollectionArea::Calc(TF1 *spectrum)
+{
+  // Search last impact parameter bin containing events
+  // FIXME: this should be done independently for each theta angle.
+  //
+  TH1D &himpact = *(TH1D*)fHistAll->Project3D("y");
+
+  Int_t impbin;
+  for (impbin = himpact.GetNbinsX(); impbin > 0; impbin--)
+    if (himpact.GetBinContent(impbin)>0)
+      break;
+
+  Float_t max_radius = himpact.GetBinLowEdge(impbin);
+
+  Float_t total_area = TMath::Pi()*max_radius*max_radius;
+
+  for (Int_t ix = 1; ix <= fHistAll->GetNbinsX(); ix++)
+    for (Int_t iz = 1; iz <= fHistAll->GetNbinsZ(); iz++)
+      {
+	fHistAll->SetBinContent(ix, impbin, iz, 0.);
+	fHistSel->SetBinContent(ix, impbin, iz, 0.);
+	fHistAll->SetBinError(ix, impbin, iz, 0.);
+	fHistSel->SetBinError(ix, impbin, iz, 0.);
+      }
+
+  TH2D &histsel = *(TH2D*)fHistSel->Project3D("zx,e");
+  TH2D &histall = *(TH2D*)fHistAll->Project3D("zx,e"); 
+  // "e" option means that errors are computed!
+
+
+  TAxis &xaxis = *histsel.GetXaxis();
+  TAxis &yaxis = *histsel.GetYaxis();
+  MH::SetBinning(fHistCol, &xaxis, &yaxis);
+
+  cout << "Total considered MC area = pi * " << max_radius 
+       << "^2 square meters" << endl;
+
+  fHistCol->Sumw2();
+  fHistCol->Divide(&histsel, &histall, total_area, 1., "b");
+
+  //
+  // Now get the effective area in the selected coarse bins. Weight
+  // the values in the small bins according the supplied tentative
+  // spectrum, if it has been supplied as argument of Calc.
+  //
+
+  for (Int_t ibin = 1; ibin <= fHistColCoarse->GetNbinsX(); ibin++)
+    for (Int_t jbin = 1; jbin <= fHistColCoarse->GetNbinsY(); jbin++)
+      {
+	Float_t maxenergy = fHistColCoarse->GetXaxis()->GetBinUpEdge(ibin);
+	Float_t minenergy = fHistColCoarse->GetXaxis()->GetBinLowEdge(ibin);
+
+	Float_t maxtheta = fHistColCoarse->GetYaxis()->GetBinUpEdge(jbin);
+	Float_t mintheta = fHistColCoarse->GetYaxis()->GetBinLowEdge(jbin);
+
+	// Fine bins ranges covered by the coarse bin ibin, jbin:
+	Int_t ibin2max = fHistCol->GetXaxis()->FindBin(maxenergy);
+	Int_t ibin2min = fHistCol->GetXaxis()->FindBin(minenergy);
+
+	Int_t jbin2max = fHistCol->GetYaxis()->FindBin(maxtheta);
+	Int_t jbin2min = fHistCol->GetYaxis()->FindBin(mintheta);
+
+	Float_t area = 0.;
+	Float_t errarea = 0.;
+	Float_t norm = 0;
+
+	for (Int_t ibin2 = ibin2min; ibin2 <= ibin2max; ibin2++)
+	  {
+  	    Float_t weight = spectrum? spectrum->
+  	      Eval(fHistCol->GetXaxis()->GetBinCenter(ibin2)) : 1.;
+
+	    for (Int_t jbin2 = jbin2min; jbin2 <= jbin2max; jbin2++)
+	      {
+		// Skip bins with too few produced MC events
+		if (histall.GetBinContent(ibin2,jbin2) < fMinEvents)
+		  continue;
+
+		area += weight * fHistCol->GetBinContent(ibin2,jbin2);
+		norm += weight;
+		errarea += pow(weight * fHistCol->
+			       GetBinError(ibin2,jbin2), 2.);
+	      }
+	  }
+	if (norm > 0.)
+	  {
+	    area /= norm;
+	    errarea = sqrt(errarea)/norm;
+	  }
+
+	fHistColCoarse->SetBinContent(ibin, jbin, area);
+	fHistColCoarse->SetBinError(ibin, jbin, errarea);
+      }
+
+  SetReadyToSave();
+}
+     
+
Index: branches/Mars_McMismatchStudy/mhistmc/MHMcCollectionArea.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcCollectionArea.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcCollectionArea.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MHMcCollectionArea
+#define MARS_MHMcCollectionArea
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#include "MBinning.h"
+#include "TF1.h"
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+//
+// Version 2:
+//
+// Now all histograms are saved with the object. Added members
+// fImpactMax, fImpactBins, fMinEvents
+//
+
+class MHMcCollectionArea : public MH
+{
+private:
+  TH3D *fHistAll;        // all simulated showers
+  TH3D *fHistSel;        // the selected showers
+  TH2D *fHistCol;        // the collection area in fine bins
+  TH2D *fHistColCoarse;  // the coll. area in coarse bins 
+
+  Int_t   fImpactBins;   // number of bins in i.p. for histograms
+  Float_t fImpactMax;    // [m] Maximum impact parameter for histograms
+
+  Int_t   fMinEvents;    
+  // minimum number of events in each of the "fine bins" of fHistAll 
+  // so that the bin is used in the averaging for the coarse bins. 
+
+  void Calc(TH3D &hsel, TH3D &hall);
+
+public:
+  MHMcCollectionArea(const char *name=NULL, const char *title=NULL);
+  ~MHMcCollectionArea();
+
+  void FillAll(Double_t energy, Double_t radius, Double_t theta);
+  void FillSel(Double_t energy, Double_t radius, Double_t theta);
+
+  const TH2D *GetHist()       const { return fHistCol; }
+  const TH2D *GetHistCoarse() const { return fHistColCoarse; }
+  const TH3D *GetHistAll()    const { return fHistAll; }
+  const TH3D *GetHistSel()    const { return fHistSel; }
+
+  void SetBinnings(const MBinning &binsEnergy, const MBinning &binsTheta);
+  void SetCoarseBinnings(const MBinning &binsEnergy, const MBinning &binsTheta);
+
+  void Draw(Option_t *option="");
+
+  void Calc(TF1 *spectrum);
+
+  ClassDef(MHMcCollectionArea, 2)  // Data Container to store Collection Area
+    };
+
+#endif
Index: branches/Mars_McMismatchStudy/mhistmc/MHMcDifRate.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcDifRate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcDifRate.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcDifRate.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcDifRate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcDifRate.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiency.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiency.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiency.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiency.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiency.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiency.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyEnergy.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyEnergy.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyEnergy.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyEnergy.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyEnergy.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyEnergy.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyImpact.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyImpact.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyImpact.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyImpact.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyImpact.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEfficiencyImpact.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEnergy.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEnergy.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEnergy.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEnergy.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEnergy.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEnergy.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyImpact.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyImpact.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyImpact.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyImpact.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyImpact.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyImpact.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyMigration.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyMigration.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyMigration.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyMigration.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyMigration.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcEnergyMigration.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcIntRate.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcIntRate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcIntRate.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcIntRate.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcIntRate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcIntRate.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcRate.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcRate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcRate.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcRate.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcRate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcRate.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhistmc/MHMcTriggerLvl2.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcTriggerLvl2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcTriggerLvl2.cc	(revision 17960)
@@ -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) const
+{
+  
+    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: branches/Mars_McMismatchStudy/mhistmc/MHMcTriggerLvl2.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcTriggerLvl2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcTriggerLvl2.h	(revision 17960)
@@ -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) const;
+
+    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: branches/Mars_McMismatchStudy/mhistmc/MHMcUnfoldCoeff.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcUnfoldCoeff.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcUnfoldCoeff.cc	(revision 17960)
@@ -0,0 +1,352 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     02/2005 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHMcUnfoldCoeff
+// Container that stores the coefficients to convert from estimated to real
+// (unfolded) energy. 
+// It is filled by MMcUnfoldCoeffCalc
+// Events are weighted from any initial spectrum to a tentative spectrum
+// that must be set through MMcUnfoldCoeffCalc::SetSpectrum method.
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "TH1D.h"
+#include "TH2D.h"
+#include "TF1.h"
+#include "TCanvas.h"
+#include "TArrayD.h"
+
+#include "MHMcUnfoldCoeff.h"
+
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHMcUnfoldCoeff);
+
+using namespace std;
+
+
+// -------------------------------------------------------------------------
+//
+// Constructor: Define and configure the different histograms to be filled
+//
+MHMcUnfoldCoeff::MHMcUnfoldCoeff(const char *name, const char *title) :
+  fNsubbins(20), fEmin(1.), fEmax(100000.), fNumMin(10), fFineBinning(NULL)
+{
+  fName  = name  ? name  : "MHMcUnfoldCoeff";
+  fTitle = title ? title : "Unfolding Coefficients vs. Theta vs. Energy";
+
+  // define histos
+  fHistAll    = new TH1D(); 
+  fHistWeight = new TH1D(); 
+  fHistMcE    = new TH2D();
+  fHistEstE   = new TH2D();
+  fHistCoeff  = new TH2D();
+
+  // set histo names
+  fHistAll->SetName("AllEvents");
+  fHistWeight->SetName("Weights");
+  fHistMcE->SetName("MCEnergy");
+  fHistEstE->SetName("EstimatedEnergy");
+  fHistCoeff->SetName("UnfoldCoeff");
+
+  // set histo titles
+  fHistAll->SetTitle("MC energy for all generated events");
+  fHistWeight->SetTitle("Weights");
+  fHistMcE->SetTitle("MC energy for survivors");
+  fHistEstE->SetTitle("Estimate energy for survivors");
+  fHistCoeff->SetTitle(fTitle);
+
+  // histos directory
+  fHistAll->SetDirectory(NULL);
+  fHistWeight->SetDirectory(NULL);
+  fHistMcE->SetDirectory(NULL);
+  fHistEstE->SetDirectory(NULL);
+  fHistCoeff->SetDirectory(NULL);
+
+  // histos style
+  fHistAll->UseCurrentStyle();
+  fHistWeight->UseCurrentStyle();
+  fHistMcE->UseCurrentStyle();
+  fHistEstE->UseCurrentStyle();
+  fHistCoeff->UseCurrentStyle();
+
+  // labels
+  fHistAll->SetXTitle("E [GeV]");
+  fHistWeight->SetXTitle("E [GeV]");
+  fHistMcE->SetXTitle("E_{MC} [GeV]");
+  fHistEstE->SetXTitle("E_{est} [GeV]");
+  fHistCoeff->SetXTitle("E_{est} [GeV]");
+
+  fHistWeight->SetYTitle("weight");
+  fHistMcE->SetYTitle("\\theta [\\circ]");
+  fHistEstE->SetYTitle("\\theta [\\circ]");
+  fHistCoeff->SetYTitle("\\theta [\\circ]");
+
+  fHistMcE->SetZTitle("weighted entries");
+  fHistEstE->SetZTitle("weighted entries");
+  fHistCoeff->SetZTitle("Coefficient");
+}
+
+// -------------------------------------------------------------------------
+//
+// Destructor: Delete all the histograms
+//
+MHMcUnfoldCoeff::~MHMcUnfoldCoeff()
+{
+  delete fHistAll;
+  delete fHistWeight;
+  delete fHistMcE;
+  delete fHistEstE;
+  delete fHistCoeff;
+
+  if(fFineBinning) 
+    delete fFineBinning;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the histograms binning. The coarse binning has to be provided
+// from outside (in the parameter list) whereas the fine binning for
+// energy is computed from the former.
+// The subbinning is set logarithmicaly (linearly) for a logarithmic
+// (linear) coarse binning. 
+// It is extended down to fEmin and up to fEmax
+// The number of subbins per coarse bins may be changed using
+// SetNsubbins() method
+// The maximum and minimum energies of the fine binning histograms
+// may be changed with the SetEmin() and SetEmax() methods
+//
+void MHMcUnfoldCoeff::SetCoarseBinnings(const MBinning &binsEnergy, 
+					const MBinning &binsTheta)
+{
+  // set histo binning (for coarse bin histos)
+  MH::SetBinning(fHistMcE,&binsEnergy,&binsTheta);
+  MH::SetBinning(fHistEstE,&binsEnergy,&binsTheta);
+  MH::SetBinning(fHistCoeff,&binsEnergy,&binsTheta);
+
+  // good errors
+  fHistMcE->Sumw2();
+  fHistEstE->Sumw2();
+
+  // define fine binning from coarse one
+  const Int_t nbins = binsEnergy.GetNumBins();
+  const TArrayD edges = binsEnergy.GetEdgesD();
+  const Bool_t isLinear = binsEnergy.IsLinear();
+
+  // compute bins needed to extend down to fEmin and up to fEmax
+  Double_t dedown, deup;
+  Int_t binsdown,binsup;
+  MBinning dbin;
+  MBinning ubin;
+  if(isLinear)
+    {
+      dedown   = (edges[1]-edges[0])/fNsubbins;
+      deup     = (edges[nbins]-edges[nbins-1])/fNsubbins;      
+      binsdown = (fEmin<edges[0])     ? Int_t((edges[0]-fEmin)/dedown) : 0;
+      binsup   = (fEmax>edges[nbins]) ? Int_t((fEmax-edges[nbins])/deup) : 0;
+      if(binsdown) dbin.SetEdges(binsdown,fEmin,edges[0]);
+      if(binsup)   ubin.SetEdges(binsup,edges[nbins],fEmax);
+    }
+  else
+    {
+      dedown   = (TMath::Log10(edges[1])-TMath::Log10(edges[0]))/fNsubbins;
+      deup     = (TMath::Log10(edges[nbins])-TMath::Log10(edges[nbins-1]))/fNsubbins;
+      binsdown = (fEmin<edges[0])    ? Int_t((TMath::Log10(edges[0])-TMath::Log10(fEmin))/dedown) : 0;
+      binsup   = (fEmax>edges[nbins])? Int_t((TMath::Log10(fEmax)-TMath::Log10(edges[nbins]))/deup) : 0;
+      if(binsdown) dbin.SetEdgesLog(binsdown,fEmin,edges[0]);
+      if(binsup)   ubin.SetEdgesLog(binsup,edges[nbins],fEmax);
+    }
+  
+  // fill the subins' edges
+  TArrayD fineedges(binsdown+nbins*fNsubbins+binsup+1);
+
+  for(Int_t i=0;i<binsdown;i++)
+    fineedges[i] = dbin.GetEdgesD().At(i);
+
+  for(Int_t i=0;i<nbins;i++)
+    {
+      MBinning coarb;
+      if(isLinear)
+	coarb.SetEdges(fNsubbins,edges[i],edges[i+1]);
+      else
+	coarb.SetEdgesLog(fNsubbins,edges[i],edges[i+1]);
+      
+      for(Int_t j=0;j<fNsubbins;j++)
+	fineedges[binsdown+i*fNsubbins+j] = coarb.GetEdgesD().At(j);
+    }  
+
+  for(Int_t i=0;i<binsup;i++)
+    fineedges[binsdown+nbins*fNsubbins+i] = ubin.GetEdgesD().At(i);
+  
+  fineedges[binsdown+nbins*fNsubbins+binsup] = binsup ? ubin.GetEdgesD().At(binsup): edges[nbins];
+
+  // define fine binning object
+  fFineBinning = new MBinning;
+  fFineBinning->SetEdges(fineedges);
+
+  // apply fine binning to histograms that need it
+  fFineBinning->Apply(*fHistAll);
+  fFineBinning->Apply(*fHistWeight);  
+}
+
+// -------------------------------------------------------------------------
+//
+// Compute the weights for a particular tentative spectrum.
+// For each energy (fine) bin we compute it as the value of the input function
+// divided by the number of entries in the actual energy histogram.
+// First and last bin are not filled since they could be biased
+//
+void MHMcUnfoldCoeff::ComputeWeights(TF1* spectrum)
+{  
+  Bool_t first=kTRUE;
+  Int_t  lastb=0;
+  for(Int_t i=0;i<fHistAll->GetNbinsX();i++)
+    {
+      const Float_t denom = fHistAll->GetBinContent(i+1); // number of events in initial spectrum
+      const Float_t ew    = fHistAll->GetBinCenter(i+1);  // energy associated to the bin
+      const Float_t numer = spectrum->Eval(ew);           // number of events for the required spectrum
+
+      if(denom>fNumMin)
+	{
+	  // do not fill it if it is the first one
+	  if(first)
+	    {
+	      fHistWeight->SetBinContent(i+1,-1);
+	      first=kFALSE;
+	    }
+	  else
+	    {
+	      fHistWeight->SetBinContent(i+1,numer/denom);	
+	      lastb=i+1;
+	    }
+	}
+      else
+	fHistWeight->SetBinContent(i+1,-1);
+    }
+
+  //remove last filled bin
+  if(lastb)
+    fHistWeight->SetBinContent(lastb,-1);
+}
+
+// --------------------------------------------------------------
+//
+// Compute the coefficients used for the (iterative) unfolding
+// The coefficients are the ratio between the contents of the
+// mc energy and estimate energy histograms (filled with weighted
+// events
+// Errors are computed as if estimated and MC energy histos where
+// uncorrelated
+//
+void MHMcUnfoldCoeff::ComputeCoefficients()
+{ 
+  for(Int_t j=0;j<fHistEstE->GetNbinsY();j++)
+    for(Int_t i=0;i<fHistEstE->GetNbinsX();i++)
+      {
+	const Float_t num = fHistMcE->GetBinContent(i+1,j+1);	
+	const Float_t den = fHistEstE->GetBinContent(i+1,j+1);
+		
+	if(den>0)
+	  {	    
+	    const Float_t cf  = num/den;
+	    fHistCoeff->SetBinContent(i+1,j+1,cf);
+
+	    if(num>0)
+	      {
+		const Float_t ernum = fHistMcE->GetBinError(i+1,j+1);
+		const Float_t erden = fHistEstE->GetBinError(i+1,j+1);
+		const Float_t ercf  = cf*(TMath::Sqrt(ernum/num*ernum/num+erden/den*erden/den));
+		fHistCoeff->SetBinError(i+1,j+1,ercf);
+	      }
+	    else
+	      fHistCoeff->SetBinError(i+1,j+1,0);		  
+	  }
+	else
+	  {
+	    *fLog << warn << "MHMcUnfoldCoeff::ComputeCoefficients Warning: energy bin " << i << ", thetabin " << j << " has no survivors, setting coefficient to 0" << endl;
+	    fHistCoeff->SetBinContent(i+1,j+1,0.);
+	    fHistCoeff->SetBinError(i+1,j+1,0.);
+	  }
+      }
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains all showers
+//
+void MHMcUnfoldCoeff::FillAll(Double_t energy)
+{
+  fHistAll->Fill(energy);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histograms which contain survivors
+// each event is introduced with a weight depending on its (MC) energy
+//
+void MHMcUnfoldCoeff::FillSel(Double_t mcenergy,Double_t estenergy,Double_t theta)
+{
+  // bin of the corresponding weight
+  const Int_t wbin = fFineBinning->FindHiEdge(mcenergy);
+
+  if(wbin>0)
+    {
+      // weight
+      const Double_t weight = fHistWeight->GetBinContent(wbin);
+      
+      if(weight>0)
+	{
+	  fHistMcE->Fill(mcenergy,theta,weight);
+	  fHistEstE->Fill(estenergy,theta,weight);
+	}
+      //      else
+	//	*fLog << warn << "MHMcUnfoldCoeff::FillSel Warning: event with energy " << mcenergy << " has no computed weight (lack of MC statistics), skipping" << endl;
+    }
+  // the event has an energy out of the considered range
+  else
+    *fLog << warn << "MHMcUnfoldCoeff::FillSel Warning: event with energy " << mcenergy << " has energy out of bounds, skipping" << endl;   
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw
+//
+void MHMcUnfoldCoeff::Draw(Option_t* option)
+{
+  TCanvas *c1 = new TCanvas();  
+  c1->SetLogx();
+  c1->SetLogy();
+  c1->SetGridx();
+  c1->SetGridy();
+
+  fHistCoeff->Draw("");
+}
+
Index: branches/Mars_McMismatchStudy/mhistmc/MHMcUnfoldCoeff.h
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/MHMcUnfoldCoeff.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/MHMcUnfoldCoeff.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHMcUnfoldCoeff
+#define MARS_MHMcUnfoldCoeff
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TF1;
+class TH1D;
+class TH2D;
+class MBinning;
+
+class MHMcUnfoldCoeff : public MH
+{
+ private:
+
+  TH1D* fHistAll;    // histogram of all events (fine bins)
+  TH1D* fHistWeight; // histogram of weights    (fine bins)
+
+  TH2D* fHistMcE;    // histogram of MC energy for survivors (coarse bins)
+  TH2D* fHistEstE;   // histogram of estimated energy for survivors (coarse bins)
+  TH2D* fHistCoeff;  // histogram of coefficients for iterative unfolding
+
+  Int_t fNsubbins;   // number of subbins per coarse bin
+  Double_t fEmin;    // [GeV] absolute minimum energy where weights are computed
+  Double_t fEmax;    // [GeV] absolute maximum energy where weights are computed
+  Int_t fNumMin;     // minimum number of events in a fine bin required to compute the weight
+
+  MBinning* fFineBinning; // fine binning (used for weights)
+  
+ public:
+
+  MHMcUnfoldCoeff(const char *name=NULL, const char *title=NULL);
+
+  virtual ~MHMcUnfoldCoeff();
+
+  void FillAll(Double_t energy);
+  void FillSel(Double_t mcenergy,Double_t estenergy,Double_t theta);
+  void Draw(Option_t* option="");
+  void ComputeWeights(TF1* spectrum);
+  void ComputeCoefficients();
+
+  void SetCoarseBinnings(const MBinning& binsEnergy,const MBinning& binsTheta);
+  void SetNsubbins(Int_t n)   {fNsubbins=n;}
+  void SetEmax(Double_t emax) {fEmax=emax;}
+  void SetEmin(Double_t emin) {fEmin=emin;}
+  void SetNumMin(Int_t n)     {fNumMin=n;}
+    
+  const TH1D* GetHistAll()    const {return fHistAll;}
+  const TH1D* GetHistWeight() const {return fHistWeight;}
+  const TH2D* GetHistMcE()    const {return fHistMcE;}
+  const TH2D* GetHistEstE()   const {return fHistEstE;}
+  const TH2D* GetHistCoeff()  const {return fHistCoeff;}
+
+  ClassDef(MHMcUnfoldCoeff, 1) // Data Container to store Unfolding Coefficients
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mhistmc/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mhistmc/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhistmc/Makefile	(revision 17960)
@@ -0,0 +1,44 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HistMc
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mhist -I../mmc -I../manalysis \
+    	   -I../mimage -I../mgeom -I../mgui
+
+SRCFILES = MHMcEnergy.cc \
+           MHMcEfficiency.cc \
+           MHMcEfficiencyImpact.cc \
+           MHMcEfficiencyEnergy.cc \
+           MHMcEnergyImpact.cc \
+	   MHMcRate.cc \
+	   MHMcCollectionArea.cc \
+           MHMcIntRate.cc \
+           MHMcDifRate.cc \
+           MHMcEnergyMigration.cc \
+	   MHMcCT1CollectionArea.cc \
+	   MHMcTriggerLvl2.cc \
+	   MHMcUnfoldCoeff.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mhvstime/HVsTimeIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/HVsTimeIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/HVsTimeIncl.h	(revision 17960)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mhvstime/HVsTimeLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/HVsTimeLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/HVsTimeLinkDef.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mhvstime/MHPixVsTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/MHPixVsTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/MHPixVsTime.cc	(revision 17960)
@@ -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): Thomas Bretz, 12/2002 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPixVsTime
+//
+// Display the pixel content versus time or event number
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given the rule for the y-axis is used.
+// 2) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyGraph;;Counts");
+//    The title for the x-axis is ignored and set automatically (MAKE SURE
+//    YOU HAVE TWO SEMICOLON!)
+//
+//
+// Class Version 2:
+// ----------------
+//  + fMaximum
+//  + fMinumum
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPixVsTime.h"
+
+#include <TH1.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+
+#include "MGeomCam.h"
+
+#include "MRawEvtHeader.h"
+#include "MTime.h"
+
+ClassImp(MHPixVsTime);
+
+using namespace std;
+
+const TString MHPixVsTime::gsDefName  = "MHPixVsTime";
+const TString MHPixVsTime::gsDefTitle = "Graph of pixel content vs. time";
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task.
+//
+MHPixVsTime::MHPixVsTime(Int_t idx, const char *name, const char *title)
+    : fIndex(idx), fEvt(NULL), fType(0), fTypeErr(-1), fMinimum(-1111), fMaximum(-1111)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    TString t("Pixel Index #");
+    t += idx;
+    t += " vs Time";
+
+    fGraph = new TGraphErrors;
+    fGraph->SetName("MCamEvent");
+    fGraph->SetTitle(t);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHPixVsTime::~MHPixVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the TGraph and the MHPixVsTime container
+//
+void MHPixVsTime::SetName(const char *name)
+{
+    fGraph->SetName(name);
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the TGraph and the MHPixVsTime container
+//
+void MHPixVsTime::SetTitle(const char *title)
+{
+    fGraph->SetTitle(title);
+    MParContainer::SetTitle(title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MPixVsTime) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+//
+Bool_t MHPixVsTime::SetupFill(const MParList *plist)
+{
+    fEvt = (MCamEvent*)plist->FindObject(fNameEvt, "MCamEvent");
+    if (!fEvt)
+    {
+        if (!fNameEvt.IsNull())
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameEvt <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << warn << GetDescriptor() << ": No MCamEvent available..." << endl;
+    }
+
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fNameTime.IsNull())
+    {
+        fTime = (MTime*)plist->FindObject(fNameTime, "MTime");
+        if (!fTime)
+        {
+            *fLog << err << fNameTime << " [MTime] not found... abort." << endl;
+            return kFALSE;
+        }
+    }
+    else
+    {
+        fHeader = (MRawEvtHeader*)plist->FindObject("MRawEvtHeader");
+        if (!fHeader)
+            *fLog << warn << "MRawEvtHeader not found... using counter." << endl;
+    }
+
+    if (fTitle!=gsDefTitle)
+        fGraph->SetTitle(fTitle);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MPixVsTime-Container.
+//
+Int_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 kERROR;
+    }
+
+    Double_t val = 0;
+    Double_t rms = 0;
+    evt->GetPixelContent(val, fIndex, *fCam, fType);
+    if (!TMath::Finite(val))
+        return kTRUE;  // Use kCONTINUE with extreme care!
+
+    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, fTypeErr);
+        if (!TMath::Finite(rms))
+            return kTRUE;  // Use kCONTINUE with extreme care!
+    }
+
+    fGraph->SetPointError(fGraph->GetN()-1, 0, rms);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return histogram of TGraph
+//
+TH1 *MHPixVsTime::GetHistByName(const TString name) const
+{
+    return fGraph->GetHistogram();
+}
+
+void MHPixVsTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+    pad->SetGrid();
+
+    AppendPad("");
+
+    // This is not done automatically anymore since root 5.12/00
+    // and it is necessary to force a proper update of the axis.
+    TH1 *h = fGraph->GetHistogram();
+
+    h->SetXTitle("Time");
+
+    if (!fNameTime.IsNull())
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+        axe->SetTimeDisplay(1);
+        axe->SetLabelSize(0.033);
+    }
+
+    if (fMinimum!=-1111)
+        fGraph->SetMinimum(fMinimum);
+    if (fMaximum!=-1111)
+        fGraph->SetMaximum(fMaximum);
+
+    TString str(opt);
+    if (!str.Contains("A"))
+        str += "A";
+    if (!str.Contains("P"))
+        str += "P";
+
+    if (str.Contains("same", TString::kIgnoreCase))
+    {
+        str.ReplaceAll("same", "");
+        str.ReplaceAll("A", "");
+    }
+
+    fGraph->Draw(str);
+}
Index: branches/Mars_McMismatchStudy/mhvstime/MHPixVsTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/MHPixVsTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/MHPixVsTime.h	(revision 17960)
@@ -0,0 +1,68 @@
+#ifndef MARS_MHPixVsTime
+#define MARS_MHPixVsTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TGraphErrors
+#include <TGraphErrors.h>
+#endif
+
+class MHCamera;
+class MCamEvent;
+class MGeomCam;
+
+class MRawEvtHeader;
+class MTime;
+
+class MHPixVsTime : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    TGraphErrors *fGraph;
+    Int_t fIndex;
+
+    MCamEvent *fEvt; //! the current event
+    MGeomCam  *fCam; //! the camera geometry
+
+    MRawEvtHeader *fHeader; //!
+    MTime         *fTime;   //!
+
+    TString fNameEvt;
+    TString fNameTime;
+
+    Int_t fType;
+    Int_t fTypeErr;
+
+    Double_t fMinimum;      // User defined minimum
+    Double_t fMaximum;      // User defined maximum
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+public:
+    MHPixVsTime(Int_t idx=0, const char *name=NULL, const char *title=NULL);
+    ~MHPixVsTime();
+
+    void SetNameEvt(const TString name) { fNameEvt = name; }
+    void SetNameTime(const TString name) { fNameTime = name; }
+    void SetType(Int_t type, Int_t e=-1) { fType = type; fTypeErr=e; }
+
+    void SetMinimum(Double_t min=-1111) { fMinimum = min; }
+    void SetMaximum(Double_t max=-1111) { fMaximum = max; }
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    TH1 *GetHistByName(const TString name="") const;
+    TGraph *GetGraph() { return fGraph; }
+
+    void Draw(Option_t *o=NULL);
+
+    ClassDef(MHPixVsTime, 2) // Histogram to sum camera events
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhvstime/MHSectorVsTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/MHSectorVsTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/MHSectorVsTime.cc	(revision 17960)
@@ -0,0 +1,337 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHSectorVsTime
+//
+// Display the mean and its variance vs time of the whole camera or a
+// single sector
+//
+// 1) If no other title is given the rule for the y-axis is used.
+// 2) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyGraph;;Counts");
+//    The title for the x-axis is ignored and set automatically (MAKE SURE
+//    YOU HAVE TWO SEMICOLON!)
+//
+// Example:
+// --------
+//     // Initialize histogram
+//     MHSectorVsTime hist1;
+//     hist1.SetNameTime("MTimeCurrents");
+//     hist1.SetTitle("Title for your Graph;;Q [phe]");
+//
+//     // 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");
+//
+//
+// Class Version 2:
+// ----------------
+//  + Double_t fMinimum;      // User defined minimum
+//  + Double_t fMaximum;      // User defined maximum
+//
+// Class Version 3:
+// ----------------
+//  + Bool_t fUseMedian;     
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHSectorVsTime.h"
+
+#include <TCanvas.h>
+#include <TGraphErrors.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+
+#include "MGeomCam.h"
+
+#include "MRawEvtHeader.h"
+#include "MTime.h"
+
+ClassImp(MHSectorVsTime);
+
+using namespace std;
+
+const TString MHSectorVsTime::gsDefName  = "MHSectorVsTime";
+const TString MHSectorVsTime::gsDefTitle = "Graph of sector mean vs. time";
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task. If fErrType>=0 the variance is
+// taken into account.
+//
+MHSectorVsTime::MHSectorVsTime(const char *name, const char *title)
+    : fGraph(0), fEvt(NULL), fMinimum(-1111), fMaximum(-1111), fUseMedian(kFALSE),
+    fType(0), fTypeErr(-1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the fGraph
+//
+MHSectorVsTime::~MHSectorVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the TGraph and the MHVsTime container
+//
+void MHSectorVsTime::SetName(const char *name)
+{
+    if (fGraph)
+        fGraph->SetName(name);
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the TGraph and the MHVsTime container
+//
+void MHSectorVsTime::SetTitle(const char *title)
+{
+    if (fGraph)
+        fGraph->SetTitle(title);
+    MParContainer::SetTitle(title);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MPixVsTime) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+// Create and/or initialize fGraph
+//
+Bool_t MHSectorVsTime::SetupFill(const MParList *plist)
+{
+    fEvt = dynamic_cast<MCamEvent*>(plist->FindObject(fNameEvt, "MCamEvent"));
+    if (!fEvt)
+    {
+        if (!fNameEvt.IsNull())
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameEvt <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << warn << GetDescriptor() << ": No MCamEvent available..." << endl;
+    }
+
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHCamera.SetGeometry(*fCam);
+
+    if (!fNameTime.IsNull())
+    {
+        fTime = (MTime*)plist->FindObject(fNameTime, "MTime");
+        if (!fTime)
+        {
+            *fLog << err << fNameTime << " [MTime] not found... abort." << endl;
+            return kFALSE;
+        }
+    }
+    else
+    {
+        fHeader = (MRawEvtHeader*)plist->FindObject("MRawEvtHeader");
+        if (!fHeader)
+            *fLog << warn << "MRawEvtHeader not found... using counter." << endl;
+    }
+
+    if (fGraph)
+        delete fGraph;
+
+    fGraph = fTypeErr<0 ? new TGraph : new TGraphErrors;
+    fGraph->SetName(fEvt ? dynamic_cast<TObject*>(fEvt)->GetName() : "MCamEvent");
+    fGraph->SetTitle(fTitle==gsDefTitle?"Camera":fTitle.Data());
+    fGraph->SetMarkerStyle(kFullDotMedium);
+
+    fMin =  FLT_MAX;
+    fMax = -FLT_MAX;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCamEvent
+//
+Int_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 kERROR;
+    }
+
+    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 = fUseMedian ?
+        fHCamera.GetMedianSectors(fSectors, fAreaIndex) :
+        fHCamera.GetMeanSectors(fSectors, fAreaIndex);
+
+    if (!TMath::Finite(val0))
+        return kTRUE;
+
+    fGraph->SetPoint(fGraph->GetN(), t, val0);
+
+    if (fTypeErr>=0)
+    {
+        const Double_t rms0 = fUseMedian ?
+            fHCamera.GetDevSectors(fSectors, fAreaIndex) :
+
+            fHCamera.GetRmsSectors(fSectors, fAreaIndex);
+        if (!TMath::Finite(rms0))
+            return kTRUE;
+
+        ((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;
+
+    if (fMinimum==-1111)
+        fGraph->SetMinimum(fMin-add);
+    if (fMaximum==-1111)
+        fGraph->SetMaximum(fMax+add);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fHistogram from TGraph
+//
+TH1 *MHSectorVsTime::GetHistByName(const TString name) const
+{
+    return fGraph->GetHistogram();
+}
+
+// --------------------------------------------------------------------------
+//
+// This displays the TGraph like you expect it to be (eg. time on the axis)
+// It should also make sure, that the displayed time always is UTC and
+// not local time...
+//
+void MHSectorVsTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(fGraph);
+    pad->SetBorderMode(0);
+    pad->SetGrid();
+
+    AppendPad("");
+
+    // This is not done automatically anymore since root 5.12/00
+    // and it is necessary to force a proper update of the axis.
+    TH1 *h = fGraph->GetHistogram();
+
+    h->SetXTitle("Time");
+
+    if (!fNameTime.IsNull())
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+        axe->SetTimeDisplay(1);
+        axe->SetLabelSize(0.033);
+        h->GetYaxis()->SetTitleOffset(1.15);
+    }
+
+    // If this is set to early the plot remains empty in root 5.12/00
+    if (fMinimum!=-1111)
+        fGraph->SetMinimum(fMinimum);
+    if (fMaximum!=-1111)
+        fGraph->SetMaximum(fMaximum);
+
+    TString str(opt);
+    if (!str.Contains("A"))
+        str += "A";
+    if (!str.Contains("P"))
+        str += "P";
+    if (str.Contains("same", TString::kIgnoreCase))
+    {
+        str.ReplaceAll("same", "");
+        str.ReplaceAll("A", "");
+    }
+
+    fGraph->Draw(str.Data());
+}
+
+void MHSectorVsTime::RecursiveRemove(TObject *obj)
+{
+    if (obj==fGraph)
+        fGraph = 0;
+}
Index: branches/Mars_McMismatchStudy/mhvstime/MHSectorVsTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/MHSectorVsTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/MHSectorVsTime.h	(revision 17960)
@@ -0,0 +1,93 @@
+/* ======================================================================== *\
+!  $Name: not supported by cvs2svn $:$Id: MHSectorVsTime.h,v 1.9 2009-02-07 20:47:52 tbretz Exp $
+\* ======================================================================== */
+#ifndef MARS_MHSectorVsTime
+#define MARS_MHSectorVsTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class MHCamera;
+class MCamEvent;
+class MGeomCam;
+
+class MRawEvtHeader;
+class MTime;
+class TGraph;
+
+class MHSectorVsTime : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+private:
+    TGraph *fGraph;         // The TGraph output to the display
+
+    MCamEvent *fEvt;        //! pointer to the current event
+    MGeomCam  *fCam;        //! pointer the camera geometry
+
+    MRawEvtHeader *fHeader; //! pointer to the event header (DAQ Evt number instead of counter)
+    MTime         *fTime;   //! pointer to event time (time instead of number)
+
+    MHCamera fHCamera;      //! The camera to be used for calculation
+
+    Double_t fMin;          //! Calculation of minimum
+    Double_t fMax;          //! Calculation of maximum
+
+    Double_t fMinimum;      // User defined minimum
+    Double_t fMaximum;      // User defined maximum
+
+    Bool_t fUseMedian;      // Whether to display median/dev instead of mean/rms
+
+    TString fNameEvt;       // Name of MCamEvent to be displayed
+    TString fNameTime;      // Name of MTime container to be used
+
+    Int_t fType;            // Type for mean  used in GetPixelContent
+    Int_t fTypeErr;         // Type for error used in GetPixelContent (-1 = no error)
+
+    TArrayI fSectors;       // Which sectors shell be displayed
+    TArrayI fAreaIndex;     // Which pixel sized should be displayed
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+public:
+    MHSectorVsTime(const char *name=NULL, const char *title=NULL);
+    ~MHSectorVsTime();
+
+    // Setter
+    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; }
+
+    void SetMinimum(Double_t min=-1111) { fMinimum = min; }
+    void SetMaximum(Double_t max=-1111) { fMaximum = max; }
+
+    void SetUseMedian(Bool_t b=kTRUE) { fUseMedian=b; }
+
+    // Getter
+    TH1 *GetHistByName(const TString name="") const;
+    TGraph *GetGraph() { return fGraph; }
+
+    // TObject
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    void Draw(Option_t *o=NULL);
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MHSectorVsTime, 3) // Histogram to sum camera events
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhvstime/MHVsTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/MHVsTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/MHVsTime.cc	(revision 17960)
@@ -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:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHVsTime
+//
+// Use this class if you want to display any rule vs time (or event number)
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given the rule for the y-axis is used.
+// 2) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyGraph;;Counts");
+//    The title for the x-axis is ignored and set automatically (MAKE SURE
+//    YOU HAVE TWO SEMICOLON!)
+//
+// eg.
+//       MHVsTime hist("MHillas.fAlpha");
+//       MHVsTime hist("MPointintPos.GetAbsErr");
+//       MHVsTime hist("MPointintPos.GetAbsErr*kRad2Deg");
+//
+// To set a maximum number of data-points (eg. to display the last 20min
+// only) call SetMaxPts(200)
+//
+// SetMaxPts(-1) disables this feature.
+//
+//
+// Class Version 2:
+// ----------------
+//  + MData      *fData;      // Object from which the data is filled
+//  - MDataChain *fData;      // Object from which the data is filled
+//  + MData      *fError;     // Object from which the error is filled
+//  - MDataChain *fError;     // Object from which the error is filled
+//
+// Class Version 3:
+// ----------------
+//  + Double_t fMinimum;      // User defined minimum
+//  + Double_t fMaximum;      // User defined maximum
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHVsTime.h"
+
+#include <ctype.h>   // tolower
+#include <fstream>
+
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include <TH1.h>
+#include <TGraphErrors.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+#include "MDataPhrase.h"
+#include "MRawEvtHeader.h"
+
+ClassImp(MHVsTime);
+
+using namespace std;
+
+const TString MHVsTime::gsDefName  = "MHVsTime";
+const TString MHVsTime::gsDefTitle = "Container for a graph vs time/evtnumber";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. For more informations about a valid rule
+// see MDataPhrase.
+//
+MHVsTime::MHVsTime(const char *rule, const char *error)
+    : fGraph(NULL), fData(NULL), fError(NULL), fScale(1), fMaxPts(-1),
+    fNumEvents(1), fMinimum(-1111), fMaximum(-1111), fUseEventNumber(0)
+{
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    if (!rule)
+        return;
+
+    fData = new MDataPhrase(rule);
+
+    if (error)
+        fError = new MDataPhrase(error);
+
+    fGraph = error ? new TGraphErrors : new TGraph;
+    fGraph->SetMarkerStyle(kFullDotMedium);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histogram
+//
+MHVsTime::~MHVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+
+    if (fData)
+        delete fData;
+
+    if (fError)
+        delete fError;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members used by the data chain to be used in
+// MTask::AddBranchToList
+//
+TString MHVsTime::GetDataMember() const
+{
+    return fData ? fData->GetDataMember() : (TString)"";
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcess the MDataPhrase. Create a new TGraph. Delete an old one if
+// already allocated.
+//
+Bool_t MHVsTime::SetupFill(const MParList *plist)
+{
+    if (!fGraph || !fData)
+    {
+        *fLog << err << "ERROR - MHVsTime cannot be used with its default constructor!" << endl;
+        return kFALSE;
+    }
+
+    if (!fData->PreProcess(plist))
+        return kFALSE;
+
+    if (fError && !fError->PreProcess(plist))
+        return kFALSE;
+
+    TString title(fData ? GetRule() : (TString)"Graph");
+    title += " vs ";
+    title += fUseEventNumber ? "Event Number" : "Time";
+
+    fGraph->SetNameTitle(fName, fTitle==gsDefTitle?title:fTitle);
+
+    fMean = 0;
+    fN    = 0;
+
+    fMin =  FLT_MAX;
+    fMax = -FLT_MAX;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the TGraph and the MHVsTime container
+//
+void MHVsTime::SetName(const char *name)
+{
+    fGraph->SetName(name);
+    MH::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the TGraph and the MHVsTime container
+//
+void MHVsTime::SetTitle(const char *title)
+{
+    fGraph->SetTitle(title);
+    MH::SetTitle(title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the next data point. If the graph exceeds fMaxPts remove the first
+//
+Int_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 kERROR;
+        }
+        // If the time is not valid skip this entry
+	if (!*tm)
+            return kTRUE;
+
+        // Do not fill events with equal time
+        if (*tm==fLast || *tm==MTime())
+            return kTRUE;
+
+        fLast = *tm;
+
+        t = tm->GetAxisTime();
+    }
+
+    const Double_t v = fData->GetValue();
+    const Double_t e = fError ? fError->GetValue() : 0;
+
+    //*fLog << all << "ADD " << v << " " << e << endl;
+
+    fMean    += v;
+    fMeanErr += e;
+    fN++;
+
+    if (fN==fNumEvents)
+    {
+        /*
+        if ((fMaxPts>0 && fGraph->GetN()>fMaxPts) || fGraph->IsEditable())
+        {
+            fGraph->RemovePoint(0);
+            fGraph->SetEditable(kFALSE);
+        }*/
+
+        const Double_t val = fMean/fN*fScale;
+
+        fGraph->SetPoint(fGraph->GetN(), t, val);
+
+        if (fError)
+            static_cast<TGraphErrors*>(fGraph)->SetPointError(fGraph->GetN()-1, 0, fMeanErr/fN*fScale);
+
+        fMin = TMath::Min(fMin, val);
+        fMax = TMath::Max(fMax, val);
+
+        fMean = 0;
+        fMeanErr = 0;
+        fN = 0;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Minimum and Maximum;
+Bool_t MHVsTime::Finalize()
+{
+    const Double_t add = (fMax-fMin)*0.15;
+
+    if (fMinimum==-1111)
+        fGraph->SetMinimum(fMin-add);
+    if (fMaximum==-1111)
+        fGraph->SetMaximum(fMax+add);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This displays the TGraph like you expect it to be (eg. time on the axis)
+// It should also make sure, that the displayed time always is UTC and
+// not local time...
+//
+void MHVsTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(fGraph);
+    pad->SetBorderMode(0);
+    pad->SetGrid();
+
+    AppendPad("");
+
+    // This is not done automatically anymore since root 5.12/00
+    // and it is necessary to force a proper update of the axis.
+    TH1 *h = fGraph->GetHistogram();
+
+    if (h)
+    {
+        TAxis *axe = h->GetXaxis();
+        // SetPoint deletes the histogram!
+        if (fUseEventNumber)
+            axe->SetTitle("Event Number");
+        else
+        {
+            axe->SetTitle("Time");
+            axe->SetLabelSize(0.033);
+            axe->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+            axe->SetTimeDisplay(1);
+        }
+    }
+
+    if (TestBit(kIsLogy))
+        gPad->SetLogy();
+
+    // If this is set to early the plot remains empty in root 5.12/00
+    if (fMinimum!=-1111)
+        fGraph->SetMinimum(fMinimum);
+    if (fMaximum!=-1111)
+        fGraph->SetMaximum(fMaximum);
+
+    TString str(opt);
+    if (!str.Contains("A"))
+        str += "A";
+    if (!str.Contains("P"))
+        str += "P";
+    if (str.Contains("same", TString::kIgnoreCase))
+    {
+        str.ReplaceAll("same", "");
+        str.ReplaceAll("A", "");
+    }
+
+    fGraph->Draw(str.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Used to rebuild a MHVsTime object of the same type (data members,
+// dimension, ...)
+//
+MParContainer *MHVsTime::New() const
+{
+    MHVsTime *h=new MHVsTime(fData ? (const char*)GetRule() : NULL);
+    h->SetScale(fScale);
+    if (fUseEventNumber)
+        h->SetUseEventNumber();
+    h->SetMaxPts(fMaxPts);
+    return h;
+}
+
+TString MHVsTime::GetRule() const
+{
+    return fData ? fData->GetRule() : (TString)"";
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the total number of bins in a histogram (excluding under- and
+// overflow bins)
+//
+Int_t MHVsTime::GetNbins() const
+{
+    return fGraph->GetN();
+}
+/*
+TH1 *MHVsTime::GetHist()
+{
+    return fGraph ? fGraph->GetHistogram() : 0;
+}
+
+const TH1 *MHVsTime::GetHist() const
+{
+    return fGraph ? fGraph->GetHistogram() : 0;
+}
+
+TH1 *MHVsTime::GetHistByName(const TString name)
+{
+    return GetHist();
+}
+*/
Index: branches/Mars_McMismatchStudy/mhvstime/MHVsTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/MHVsTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/MHVsTime.h	(revision 17960)
@@ -0,0 +1,92 @@
+#ifndef MARS_MHVsTime
+#define MARS_MHVsTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class TGraph;
+class MData;
+
+class MHVsTime : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+protected:
+    // Could be const but root < 3.02/06 doesn't like this...
+    TGraph     *fGraph;     // Histogram to fill
+    MData      *fData;      // Object from which the data is filled
+    MData      *fError;     // Object from which the error is filled
+    Double_t    fScale;     // Scale for axis (eg unit)
+    Int_t       fMaxPts;    // Maximum number of data points
+
+    Int_t       fNumEvents; // Number of events to average
+
+    Double_t    fMean;      //! Mean value
+    Double_t    fMeanErr;   //! Mean error
+    Int_t       fN;         //! Number of entries in fMean
+    MTime       fLast;      //! For checks
+
+    Double_t fMinimum;      // User defined minimum
+    Double_t fMaximum;      // User defined maximum
+
+    Double_t fMin;          //! Calculation of minimum
+    Double_t fMax;          //! Calculation of maximum
+
+    enum {
+        kIsLogy = BIT(18)
+    };
+
+    Bool_t fUseEventNumber;
+
+    Bool_t Finalize();
+
+public:
+    MHVsTime(const char *rule=NULL, const char *ruleerr=NULL);
+    ~MHVsTime();
+
+    void SetScale(Double_t scale) { fScale = scale; }
+
+    void SetMinimum(Double_t min=-1111) { fMinimum = min; }
+    void SetMaximum(Double_t max=-1111) { fMaximum = max; }
+
+    Int_t GetNbins() const;
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    void SetLogy(Bool_t b=kTRUE) { b ? SetBit(kIsLogy) : ResetBit(kIsLogy); }
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    TString GetDataMember() const;
+    TString GetRule() const;
+
+    /*
+     const TH1 *GetHist() const;
+     TH1 *GetHist();
+     TH1 *GetHistByName(const TString name="");
+     */
+    const TGraph *GetGraph() const { return fGraph; }
+    TGraph *GetGraph() { return fGraph; }
+
+    void SetUseEventNumber(Bool_t use = kTRUE) { fUseEventNumber = use; }
+    void SetNumEvents(Int_t n) { fNumEvents=n; }
+
+    void Draw(Option_t *opt=NULL);
+
+    MParContainer *New() const;
+
+    void SetMaxPts(Int_t n) { fMaxPts=n; }
+
+    ClassDef(MHVsTime, 3) // Generalized 1/2/3D-histogram for Mars variables
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mhvstime/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mhvstime/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mhvstime/Makefile	(revision 17960)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HVsTime
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mgeom -I../mhist \
+	   -I../mgui -I../mraw -I../mdata -I../mcalib
+# mhist (MHCamera)
+# mgui  (MCamEvent)
+# mraw  (MRawEvtHeader)
+
+SRCFILES = MHVsTime.cc \
+           MHPixVsTime.cc \
+           MHSectorVsTime.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mimage/ImageIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/ImageIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/ImageIncl.h	(revision 17960)
@@ -0,0 +1,5 @@
+#ifndef __CINT__
+
+#include <TVector2.h>
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mimage/ImageLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/ImageLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/ImageLinkDef.h	(revision 17960)
@@ -0,0 +1,31 @@
+#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 MImgCleanTime+;
+#pragma link C++ class MImgCleanSimple+;
+
+#pragma link C++ class MHillas+;
+#pragma link C++ class MHillasSrc+;
+#pragma link C++ class MHillasExt+;
+#pragma link C++ class MHillasCalc+;
+
+#pragma link C++ class MImagePar+;
+#pragma link C++ class MNewImagePar+;
+#pragma link C++ class MNewImagePar2+;
+#pragma link C++ class MConcentration+;
+
+#pragma link C++ class MHHillas+;
+#pragma link C++ class MHHillasSrc+;
+#pragma link C++ class MHHillasExt+;
+#pragma link C++ class MHImagePar+;
+#pragma link C++ class MHNewImagePar+;
+#pragma link C++ class MHNewImagePar2+;
+#pragma link C++ class MHVsSize+;
+#pragma link C++ class MStereoPar+;
+#pragma link C++ class MStereoCalc+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MCameraSmooth.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MCameraSmooth.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MCameraSmooth.cc	(revision 17960)
@@ -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): Thomas Bretz 08/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MCameraSmooth                                                          //
+//                                                                         //
+//  This task fills each pixel in the camera with the average of the       //
+//  number of cerenkov photons from its surrounding pixels. This can       //
+//  be done using the central pixel or ignoring the central pixel.         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraSmooth.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+ClassImp(MCameraSmooth);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. You can specify the numer of loops how often a
+// smoothing should be done. The default is 1.
+//
+MCameraSmooth::MCameraSmooth(Byte_t n, const char *name, const char *title)
+    : fCounts(n), fUseCentralPixel(kTRUE)
+{
+    fName  = name  ? name  : "MCameraSmooth";
+    fTitle = title ? title : "Task to smooth the camera";
+}
+
+// --------------------------------------------------------------------------
+//
+//  - get the MSignalCam from the parlist (abort if missing)
+//  - get MGeomCam from the parameter list
+//
+Int_t MCameraSmooth::PreProcess (MParList *pList)
+{
+    fEvt = (MSignalCam*)pList->FindObject("MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << dbginf << "MSignalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << warn << dbginf << "No camera geometry available... aborting." << endl;
+
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the smoothing
+//
+Int_t MCameraSmooth::Process()
+{
+    const UShort_t entries = fEvt->GetNumPixels();
+
+    //
+    // remove the pixels in fPixelsID if they are set to be used,
+    // (set them to 'unused' state)
+    //
+
+    Double_t *photons = new Double_t[entries];
+    Double_t *errors  = new Double_t[entries];
+
+    for (int n=0; n<fCounts; n++)
+    {
+        for (UShort_t i=0; i<entries; i++)
+        {
+            MSignalPix &pix = (*fEvt)[i];
+
+            //const Int_t id = pix.GetPixId();
+
+            const MGeomPix &gpix = (*fGeomCam)[i];
+
+            const Int_t nn = 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<nn; j++)
+            {
+                const UShort_t nid = gpix.GetNeighbor(j);
+
+                const MSignalPix &evtpix = (*fEvt)[nid];
+                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: branches/Mars_McMismatchStudy/mimage/MCameraSmooth.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MCameraSmooth.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MCameraSmooth.h	(revision 17960)
@@ -0,0 +1,36 @@
+#ifndef MARS_MCameraSmooth
+#define MARS_MCameraSmooth
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class MGeomCam;
+class MSignalCam;
+
+class MCameraSmooth : public MTask
+{
+private:
+    MSignalCam *fEvt;     //! Pointer to data to smooth
+    MGeomCam   *fGeomCam; //! Camera geometry
+
+    Byte_t fCounts;           // number of smoothing loops
+    Bool_t fUseCentralPixel;  // use also the central pixel
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MCameraSmooth(Byte_t cnt=1, const char *name=NULL, const char *title=NULL);
+
+    void SetUseCentralPixel(Bool_t b=kTRUE) { fUseCentralPixel=kTRUE; }
+
+    ClassDef(MCameraSmooth, 0) // task to smooth the camera contants
+}; 
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mimage/MConcentration.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MConcentration.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MConcentration.cc	(revision 17960)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@atsro.uni-wuerzburg.de>
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!   Author(s): Wolfgang Wittek  6/2002 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Oscar Blanch     3/2004 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MConcentration
+//
+// Storage Container for Concentration parameters
+//
+//
+// Version 1:
+// ----------
+// fConc[i]    [ratio] Number of photons in the i+1 more populated pixels
+//                     over the event size (till i=7).
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MConcentration.h"
+
+
+#include <TArrayF.h>
+#include <TArrayI.h>
+
+#include "MHillas.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MConcentration);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MConcentration::MConcentration(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MConcentration";
+    fTitle = title ? title : "Storage container for concentrations";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes the values with defaults. For the default values see the
+// source code.
+//
+void MConcentration::Reset()
+{
+    for (int i=0; i<9; i++)
+        fConc[i] = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the Concetration Parameters to *fLog
+//
+void MConcentration::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Concentrations (" << GetName() << ")" << endl;
+    for(int i=0;i<9;i++)
+      *fLog << "Conc" << i+1 <<" = "<< fConc[i] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the Concentrations from a Cherenkov photon event
+// assuming Cher.photons/pixel, their standard hillas parameters 
+// and  pixel coordinates are given.
+// In case you don't call Calc from within an eventloop make sure, that
+// you call the Reset member function before.
+//
+// Returns:
+//    Nothing.
+//
+Int_t MConcentration::Calc(const MGeomCam &geom, const MSignalCam &evt, const MHillas &hillas)
+{
+    Float_t maxpix[9] = {0,0,0,0,0,0,0,0,0};             // [#phot]
+
+   const UInt_t npix = evt.GetNumPixels();
+   for (UInt_t j=0; j<npix; j++)
+   {
+       const MSignalPix &pix = evt[j];
+       if (!pix.IsPixelUsed())
+           continue;
+
+        const Double_t nphot = pix.GetNumPhotons()* geom.GetPixRatio(j);
+
+	// 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 k=0;k<i-1;k++)
+                maxpix[7-k]=maxpix[6-k];                 // [#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: branches/Mars_McMismatchStudy/mimage/MConcentration.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MConcentration.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MConcentration.h	(revision 17960)
@@ -0,0 +1,39 @@
+#ifndef MARS_MConcentration
+#define MARS_MConcentration
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MConcentration : public MParContainer
+{
+private:
+    Float_t fConc[9];       // [ratio] Num photons in i+1 pixels over size of event 
+
+public:
+    MConcentration(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MSignalCam &pix, const MHillas &hil);
+
+    void Print(Option_t *opt=NULL) const;
+
+    Float_t GetConc1() const { return fConc[0]; }
+    Float_t GetConc2() const { return fConc[1]; }
+    Float_t GetConc3() const { return fConc[2]; }
+    Float_t GetConc4() const { return fConc[3]; }
+    Float_t GetConc5() const { return fConc[4]; }
+    Float_t GetConc6() const { return fConc[5]; }
+    Float_t GetConc7() const { return fConc[6]; }
+    Float_t GetConc8() const { return fConc[7]; }
+    Float_t GetConc9() const { return fConc[8]; }
+
+    ClassDef(MConcentration, 1) // Storage Container for Concentration Parameter
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHHillas.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHHillas.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHHillas.cc	(revision 17960)
@@ -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  2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek  2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHHillas
+//
+// This class contains histograms for the source independent image parameters
+//
+// ClassVersion 2:
+// ---------------
+//  - fMm2Deg
+//  - fUseMmScale
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHHillas.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MGeomCam.h"
+#include "MBinning.h"
+
+#include "MHCamera.h"
+
+ClassImp(MHHillas);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Width, Length
+//
+MHHillas::MHHillas(const char *name, const char *title)
+    : fGeomCam(0)
+{
+    //
+    //   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, 1.0);
+    fWidth   = new TH1F("Width",  "Width of Ellipse",                100,   0, 1.0);
+    fDistC   = new TH1F("DistC",  "Distance from center of camera",  100,   0, 1.5);
+    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 [\\circ]");
+    fWidth->SetXTitle("Width [\\circ]");
+    fDistC->SetXTitle("Distance [\\circ]");
+    fDelta->SetXTitle("Delta [\\circ]");
+
+    fLength->SetYTitle("Counts");
+    fWidth->SetYTitle("Counts");
+    fDistC->SetYTitle("Counts");
+    fDelta->SetYTitle("Counts");
+
+    fDelta->SetMinimum(0);
+
+    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 gravity", 51, -1.5, 1.5, 51, -1.5, 1.5);
+    fCenter->SetDirectory(NULL);
+    fCenter->SetXTitle("x [mm]");
+    fCenter->SetYTitle("y [mm]");
+    fCenter->SetZTitle("Counts");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHHillas::~MHHillas()
+{
+    delete fLength;
+    delete fWidth;
+
+    delete fDistC;
+    delete fDelta;
+
+    delete fSize;
+    delete fCenter;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning (with the names 'BinningWidth' and 'BinningLength')
+// are found in the parameter list
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plain into the deg-scale
+// used for histogram presentations. The conversion factor is part of
+// the camera geometry. Please create a corresponding MGeomCam container.
+//
+Bool_t MHHillas::SetupFill(const MParList *plist)
+{
+    fGeomCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return 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)
+    {
+        const Float_t r = fGeomCam->GetMaxRadius()*fGeomCam->GetConvMm2Deg();
+
+        const MBinning b(61, -r, r);
+        SetBinning(*fCenter, b, b);
+    }
+    else
+        SetBinning(*fCenter, *bins, *bins);
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Int_t MHHillas::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHHillas::Fill: Pointer (!=NULL) expected." << endl;
+        return kERROR;
+    }
+
+    const MHillas &h = *(MHillas*)par;
+
+    const Double_t scale = fGeomCam->GetConvMm2Deg();
+
+    fLength->Fill(scale*h.GetLength(), w);
+    fWidth ->Fill(scale*h.GetWidth(), w);
+    fDistC ->Fill(scale*h.GetDist0(), w);
+    fCenter->Fill(scale*h.GetMeanX(), scale*h.GetMeanY(), w);
+    fDelta ->Fill(kRad2Deg*h.GetDelta(), w);
+    fSize  ->Fill(h.GetSize(), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the four histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHHillas::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString opt(o);
+    opt.ToLower();
+
+    // FIXME: If same-option given make two independant y-axis!
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(2,3);
+    else
+    {
+        fLength->SetName("LengthSame");
+        fWidth->SetName("WidthSame");
+        fDistC->SetName("DistCSame");
+        fDelta->SetName("DeltaSame");
+        fSize->SetName("SizeSame");
+        fCenter->SetName("CenterSame");
+
+        fLength->SetDirectory(0);
+        fWidth->SetDirectory(0);
+        fDistC->SetDirectory(0);
+        fDelta->SetDirectory(0);
+        fSize->SetDirectory(0);
+        fCenter->SetDirectory(0);
+
+        fDistC->SetLineColor(kBlue);
+        fSize->SetLineColor(kBlue);
+        fDelta->SetLineColor(kBlue);
+        fWidth->SetLineColor(kMagenta);
+        fLength->SetLineColor(kCyan);
+    }
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("WidthSame");
+    RemoveFromPad("LengthSame");
+    MH::DrawSame(*fWidth, *fLength, "Width'n'Length", same);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("DistCSame");
+    fDistC->Draw(same?"same":"");
+
+    pad->cd(3);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    RemoveFromPad("SizeSame");
+    fSize->Draw(same?"same":"");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    gPad->SetPad(0.51, 0.01, 0.99, 0.65);
+    if (same)
+    {
+        TH2 *h=dynamic_cast<TH2*>(gPad->FindObject("Center"));
+        if (h)
+        {
+            // This causes crashes in THistPainter::PaintTable
+            // if the z-axis is not kept. No idea why...
+            h->SetDrawOption("z");
+            h->SetMarkerColor(kBlack);
+        }
+
+        RemoveFromPad("CenterSame");
+        fCenter->SetMarkerColor(kBlue);
+        fCenter->Draw("same");
+    }
+    else
+        fCenter->Draw("colz");
+
+    if (fGeomCam)
+    {
+//        MHCamera *cam = new MHCamera(*fGeomCam);
+//        cam->Draw("same");
+//        cam->SetBit(kCanDelete);
+    }
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("DeltaSame");
+    fDelta->Draw(same?"same":"");
+
+    pad->cd(6);
+    if (gPad && !same)
+        delete gPad;
+}
+
+TH1 *MHHillas::GetHistByName(const TString name) const
+{
+    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)
+{
+    MH::SetPalette("pretty");
+    MH::Paint();
+}
Index: branches/Mars_McMismatchStudy/mimage/MHHillas.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHHillas.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHHillas.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHHillas
+#define MARS_MHHillas
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1F;
+class TH2F;
+class MHillas;
+class MGeomCam;
+
+class MHHillas : public MH
+{
+private:
+    MGeomCam *fGeomCam; //! Camera geometry for plots (for the moment this is a feature for a loop only!)
+
+    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 Paint(Option_t *opt="");
+
+public:
+    MHHillas(const char *name=NULL, const char *title=NULL);
+    ~MHHillas();
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name) const;
+    TObject *FindObject(const TObject *obj) const { return 0; }
+    TObject *FindObject(const char *name) const
+    {
+        return (TObject*)GetHistByName(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, 2) // Container which holds histograms for the source independent image parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHHillasExt.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHHillasExt.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHHillasExt.cc	(revision 17960)
@@ -0,0 +1,370 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHHillasExt
+//
+// This class contains histograms for every Hillas parameter
+//
+// Class Version 2:
+// ----------------
+//  - fHMaxDist
+//  + fHSlopeL
+//
+// ClassVersion 3:
+// ---------------
+//  - fMm2Deg
+//  - fUseMmScale
+//
+// ClassVersion 4:
+// ---------------
+//  + TH1F fHTimeSpread;      // [ns] Spread (rms) of arrival time around mean
+//  + TH1F fHTimeSpreadW;     // [ns] Weighted spread (rms) of arrival time around weighted mean
+//  + TH1F fHSlopeSpread;     // [ns] Spread (rms) of arrival time around slope
+//  + TH1F fHSlopeSpreadW;    // [ns] Weighted spread (rms) of arrival time around slope
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHHillasExt.h"
+
+#include <math.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 "MHillas.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)
+    : fGeom(0), fHillas(0), fHillasExt(0), 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.UseCurrentStyle();
+    fHM3Long.UseCurrentStyle();
+    fHM3Trans.UseCurrentStyle();
+    fHSlopeL.UseCurrentStyle();
+    fHTimeSpread.UseCurrentStyle();
+    fHTimeSpreadW.UseCurrentStyle();
+    fHSlopeSpread.UseCurrentStyle();
+    fHSlopeSpreadW.UseCurrentStyle();
+
+    fHAsym.SetName("Asymmetry");
+    fHM3Long.SetName("M3l");
+    fHM3Trans.SetName("M3t");
+    fHSlopeL.SetName("SlopeL");
+    fHTimeSpread.SetName("TimeSpread");
+    fHTimeSpreadW.SetName("TimeSpreadW");
+    fHSlopeSpread.SetName("SlopeSpread");
+    fHSlopeSpreadW.SetName("SlopeSpreadW");
+
+    fHAsym.SetTitle("Asymmetry");
+    fHM3Long.SetTitle("3^{rd} Moment Longitudinal");
+    fHM3Trans.SetTitle("3^{rd} Moment Transverse");
+    fHSlopeL.SetTitle("Longitudinal time-slope vs. Dist");
+    fHTimeSpread.SetTitle("Time spread around mean");
+    fHTimeSpreadW.SetTitle("Weighted time spread around weighted mean");
+    fHSlopeSpread.SetTitle("Time spread around slope");
+    fHSlopeSpreadW.SetTitle("Weighted time spread around slope");
+
+    fHAsym.SetXTitle("Asym [\\circ]");
+    fHM3Long.SetXTitle("3^{rd} M_{l} [\\circ]");
+    fHM3Trans.SetXTitle("3^{rd} M_{t} [\\circ]");
+    fHSlopeL.SetXTitle("D [\\circ]");
+    fHTimeSpread.SetXTitle("T_{rms} [ns]");
+    fHTimeSpreadW.SetXTitle("T_{rms} [ns]");
+    fHSlopeSpread.SetXTitle("T_{rms} [ns]");
+    fHSlopeSpreadW.SetXTitle("T_{rms} [ns]");
+
+    fHAsym.SetYTitle("Counts");
+    fHM3Long.SetYTitle("Counts");
+    fHM3Trans.SetYTitle("Counts");
+    fHSlopeL.SetYTitle("S_{l} [ns/\\circ]");
+    fHTimeSpread.SetYTitle("Counts");
+    fHTimeSpreadW.SetYTitle("Counts");
+    fHSlopeSpread.SetYTitle("Counts");
+    fHSlopeSpreadW.SetYTitle("Counts");
+
+    fHAsym.SetFillStyle(4000);
+    fHM3Long.SetFillStyle(4000);
+    fHM3Trans.SetFillStyle(4000);
+    //fHSlopeL.SetFillStyle(4000);
+
+    fHAsym.SetDirectory(NULL);
+    fHM3Long.SetDirectory(NULL);
+    fHM3Trans.SetDirectory(NULL);
+    fHSlopeL.SetDirectory(NULL);
+
+    fHTimeSpread.SetDirectory(NULL);
+    fHTimeSpreadW.SetDirectory(NULL);
+    fHSlopeSpread.SetDirectory(NULL);
+    fHSlopeSpreadW.SetDirectory(NULL);
+
+    fHM3Trans.SetLineColor(kBlue);
+
+    fHSlopeSpread.SetLineColor(kBlue);
+    fHSlopeSpreadW.SetLineColor(kBlue);
+
+    fHTimeSpreadW.SetLineStyle(kDashed);
+    fHSlopeSpreadW.SetLineStyle(kDashed);
+
+    MBinning binsx, binsy;
+
+    binsx.SetEdges(51, -1.1, 1.1);
+    binsx.Apply(fHM3Long);
+    binsx.Apply(fHM3Trans);
+
+    binsx.SetEdges(51, -2.0, 2.0);
+    binsx.Apply(fHAsym);
+
+    binsx.SetEdges(100,   0, 1.5);
+    binsy.SetEdges(100,  -9,   9);
+    MH::SetBinning(fHSlopeL, binsx, binsy);
+
+    binsx.SetEdges( 50,   0, 1.5);
+    MH::SetBinning(fHTimeSpread,   binsx);
+    MH::SetBinning(fHSlopeSpread,  binsx);
+    MH::SetBinning(fHTimeSpreadW,  binsx);
+    MH::SetBinning(fHSlopeSpreadW, binsx);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+    }
+
+    fHillas = (MHillas*)plist->FindObject("MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << "MHillas not found in parameter list... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    ApplyBinning(*plist, "Asym",             fHAsym);
+    ApplyBinning(*plist, "M3Long",           fHM3Long);
+    ApplyBinning(*plist, "M3Trans",          fHM3Trans);
+    ApplyBinning(*plist, "Dist",    "Slope", fHSlopeL);
+
+    ApplyBinning(*plist, "TimeSpread",       fHTimeSpread);
+    ApplyBinning(*plist, "TimeSpread",       fHTimeSpreadW);
+    ApplyBinning(*plist, "TimeSpread",       fHSlopeSpread);
+    ApplyBinning(*plist, "TimeSpread",       fHSlopeSpreadW);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the four histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Int_t MHHillasExt::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MHillasSrc *src = (MHillasSrc*)par;
+
+    const Double_t scale = TMath::Sign(fGeom->GetConvMm2Deg(), (src ? src->GetCosDeltaAlpha() : 1));
+    const Double_t dist  = src ? src->GetDist() : fHillas->GetDist0();
+
+    fHAsym.Fill(scale*fHillasExt->GetAsym(), w);
+    fHM3Long.Fill(scale*fHillasExt->GetM3Long(), w);
+    fHM3Trans.Fill(scale*fHillasExt->GetM3Trans(), w);
+    fHSlopeL.Fill(scale*dist, fHillasExt->GetSlopeLong()/scale, w);
+
+    fHTimeSpread.Fill(fHillasExt->GetTimeSpread(), w);
+    fHTimeSpreadW.Fill(fHillasExt->GetTimeSpreadWeighted(), w);
+    fHSlopeSpread.Fill(fHillasExt->GetSlopeSpread(), w);
+    fHSlopeSpreadW.Fill(fHillasExt->GetSlopeSpreadWeighted(), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    // FIXME: If same-option given make two independant y-axis!
+    const TString opt(o);
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(2,2);
+    else
+    {
+        fHAsym.SetName("AsymmetrySame");
+        fHM3Long.SetName("M3lSame");
+        fHM3Trans.SetName("M3tSame");
+        fHSlopeL.SetName("SlopeLSame");
+
+        fHSlopeSpreadW.SetName("SlopeSpreadWSame");
+        fHSlopeSpread.SetName("SlopeSpreadSame");
+        fHTimeSpread.SetName("TimeSpreadSame");
+        fHTimeSpreadW.SetName("TimeSpreadWSame");
+
+        fHAsym.SetDirectory(0);
+        fHM3Long.SetDirectory(0);
+        fHM3Trans.SetDirectory(0);
+        fHSlopeL.SetDirectory(0);
+
+        fHSlopeSpreadW.SetDirectory(0);
+        fHSlopeSpread.SetDirectory(0);
+        fHTimeSpread.SetDirectory(0);
+        fHTimeSpreadW.SetDirectory(0);
+
+        fHM3Long.SetLineColor(kMagenta);
+        fHM3Trans.SetLineColor(kCyan);
+        fHAsym.SetLineColor(kBlue);
+        fHSlopeL.SetMarkerColor(kBlue);
+
+        fHSlopeSpreadW.SetLineColor(kMagenta);
+        fHSlopeSpread.SetLineColor(kMagenta);
+        fHTimeSpread.SetLineColor(kCyan);
+        fHTimeSpreadW.SetLineColor(kCyan);
+    }
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("M3lSame");
+    RemoveFromPad("M3tSame");
+    MH::DrawSame(fHM3Long, fHM3Trans, "3^{rd} Moments", same);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("AsymmetrySame");
+    fHAsym.Draw(same?"same":"");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    //RemoveFromPad("SlopeLSame");
+    //fHSlopeL.Draw(same?"same":"");
+    if (same)
+    {
+        TH2 *h=dynamic_cast<TH2*>(gPad->FindObject("SlopeL"));
+        if (h)
+        {
+            // This causes crashes in THistPainter::PaintTable
+            // if the z-axis is not kept. No idea why...
+            h->SetDrawOption("z");
+            h->SetMarkerColor(kBlack);
+        }
+
+        RemoveFromPad("SlopeLSame");
+        fHSlopeL.SetMarkerColor(kBlue);
+        fHSlopeL.Draw("same");
+    }
+    else
+        fHSlopeL.Draw("colz");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    RemoveFromPad("SlopeSpreadSame");
+    RemoveFromPad("SlopeSpreadWSame");
+    RemoveFromPad("TimeSpreadSame");
+    RemoveFromPad("TimeSpreadWSame");
+
+    fHSlopeSpreadW.Draw(same?"same":"");
+    fHSlopeSpread.Draw("same");
+    fHTimeSpread.Draw("same");
+    fHTimeSpreadW.Draw("same");
+}
+
+TH1 *MHHillasExt::GetHistByName(const TString name) const
+{
+    if (name.Contains("Asym", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHAsym);
+    if (name.Contains("M3L", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHM3Long);
+    if (name.Contains("M3T", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHM3Trans);
+    if (name.Contains("SlopeL", TString::kIgnoreCase))
+        return const_cast<TH2F*>(&fHSlopeL);
+
+    return NULL;
+}
Index: branches/Mars_McMismatchStudy/mimage/MHHillasExt.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHHillasExt.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHHillasExt.h	(revision 17960)
@@ -0,0 +1,54 @@
+#ifndef MARS_MHHillasExt
+#define MARS_MHHillasExt
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MGeomCam;
+class MHillas;
+class MHillasExt;
+
+class MHHillasExt : public MH
+{
+private:
+    MGeomCam   *fGeom;      //! conversion mm to deg
+    MHillas    *fHillas;    //! Pointer to the MHillas container
+    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
+    TH2F fHSlopeL;          //
+
+    TH1F fHTimeSpread;      // [ns] Spread (rms) of arrival time around mean
+    TH1F fHTimeSpreadW;     // [ns] Weighted spread (rms) of arrival time around weighted mean
+    TH1F fHSlopeSpread;     // [ns] Spread (rms) of arrival time around slope
+    TH1F fHSlopeSpreadW;    // [ns] Weighted spread (rms) of arrival time around slope
+
+    TString fHilName;
+
+public:
+    MHHillasExt(const char *name=NULL, const char *title=NULL);
+
+    void SetHillasName(const char *name) { fHilName = name; }
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name) const;
+    TObject *FindObject(const TObject *obj) const { return 0; }
+    TObject *FindObject(const char *name) const
+    {
+        return (TObject*)GetHistByName(name);
+    }
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHHillasExt, 4) // Container which holds histograms for the extended hillas parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHHillasSrc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHHillasSrc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHHillasSrc.cc	(revision 17960)
@@ -0,0 +1,278 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHHillasSrc
+//
+// This class contains histograms for every Hillas parameter
+//
+// ClassVersion 2:
+// ---------------
+//  - fMm2Deg
+//  - fUseMmScale
+//
+///////////////////////////////////////////////////////////////////////
+#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 "MHillasSrc.h"
+
+ClassImp(MHHillasSrc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Alpha, and Dist
+//
+MHHillasSrc::MHHillasSrc(const char *name, const char *title)
+    : fGeom(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHHillasSrc";
+    fTitle = title ? title : "Container for Hillas histograms";
+
+    //
+    // loop over all Pixels and create two histograms
+    // one for the Low and one for the High gain
+    // connect all the histogram with the container fHist
+    //
+    fAlpha    = new TH1F("Alpha",    "Alpha of Ellipse",                 90,   -90,  90);
+    fDist     = new TH1F("Dist",     "Dist of Ellipse",                  70,     0, 2.1);
+    fCosDA    = new TH1F("CosDA",    "cos(Delta,Alpha) of Ellipse",     101,    -1,   1);
+    fDCA      = new TH1F("DCA",      "Distance of closest aproach",     101,  -1.7, 1.7);
+    fDCADelta = new TH1F("DCADelta", "Angle between shower and x-axis",  80,     0, 360);
+
+    fAlpha->SetDirectory(NULL);
+    fDist->SetDirectory(NULL);
+    fCosDA->SetDirectory(NULL);
+    fDCA->SetDirectory(NULL);
+    fDCADelta->SetDirectory(NULL);
+
+    fAlpha->SetXTitle("\\alpha [\\circ]");
+    fDist->SetXTitle("Dist [\\circ]");
+    fCosDA->SetXTitle("cos(\\delta,\\alpha)");
+    fDCA->SetXTitle("DCA [\\circ]");
+    fDCADelta->SetXTitle("DCADelta [0, 2\\pi]");
+
+    fAlpha->SetYTitle("Counts");
+    fDist->SetYTitle("Counts");
+    fCosDA->SetYTitle("Counts");
+    fDCA->SetYTitle("Counts");
+    fDCADelta->SetYTitle("Counts");
+
+    fAlpha->SetMinimum(0);
+    fCosDA->SetMinimum(0);
+    fDCADelta->SetMinimum(0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the four histograms
+//
+MHHillasSrc::~MHHillasSrc()
+{
+    delete fAlpha;
+    delete fDist;
+    delete fCosDA;
+    delete fDCA;
+    delete fDCADelta;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning (with the names 'BinningAlpha' and 'BinningDist')
+// are found in the parameter list
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plain into the deg-scale
+// used for histogram presentations. The conversion factor is part of
+// the camera geometry. Please create a corresponding MGeomCam container.
+//
+Bool_t MHHillasSrc::SetupFill(const MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    ApplyBinning(*plist, "Alpha",    *fAlpha);
+    ApplyBinning(*plist, "Dist",     *fDist);
+    ApplyBinning(*plist, "DCA",      *fDCA);
+    ApplyBinning(*plist, "DCADelta", *fDCADelta);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the four histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Int_t MHHillasSrc::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHHillasSrc::Fill: Pointer (!=NULL) expected." << endl;
+        return kERROR;
+    }
+
+    const MHillasSrc &h = *(MHillasSrc*)par;
+
+    const Double_t scale = fGeom->GetConvMm2Deg();
+
+    fAlpha->Fill(h.GetAlpha(), w);
+    fDist ->Fill(h.GetDist()*scale, w);
+    fCosDA->Fill(h.GetCosDeltaAlpha(), w);
+    fDCA  ->Fill(h.GetDCA()*scale, w);
+    fDCADelta->Fill(h.GetDCADelta(), 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 MHHillasSrc::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    // FIXME: Display Source position
+
+    // FIXME: If same-option given make two independant y-axis!
+    const TString opt(o);
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(2,2);
+    else
+    {
+        fAlpha->SetName("AlphaSame");
+        fDist ->SetName("DistSame");
+        fCosDA->SetName("CosDASame");
+        fDCA  ->SetName("DCASame");
+        fDCADelta->SetName("DCADeltaSame");
+
+        fAlpha->SetDirectory(0);
+        fDist ->SetDirectory(0);
+        fCosDA->SetDirectory(0);
+        fDCA  ->SetDirectory(0);
+        fDCADelta->SetDirectory(0);
+
+        fAlpha->SetLineColor(kBlue);
+        fDist->SetLineColor(kBlue);
+        fDCA->SetLineColor(kBlue);
+        fCosDA->SetLineColor(kBlue);
+        fDCADelta->SetLineColor(kBlue);
+    }
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("AlphaSame");
+    fAlpha->Draw(same?"same":"");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("DistSame");
+    fDist->Draw(same?"same":"");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("DCASame");
+    fDCA->Draw(same?"same":"");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    TVirtualPad *p = gPad;
+    if (!same)
+        p->Divide(1,2);
+    p->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("CosDASame");
+    fCosDA->Draw(same?"same":"");
+
+    p->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("DCADeltaSame");
+    fDCADelta->Draw(same?"same":"");
+}
+
+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) const
+{
+    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: branches/Mars_McMismatchStudy/mimage/MHHillasSrc.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHHillasSrc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHHillasSrc.h	(revision 17960)
@@ -0,0 +1,51 @@
+#ifndef MARS_MHHillasSrc
+#define MARS_MHHillasSrc
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1F;
+class MGeomCam;
+class MHillas;
+
+class MHHillasSrc : public MH
+{
+private:
+    MGeomCam *fGeom;  //! conversion mm to deg
+
+    TH1F *fAlpha;     //->
+    TH1F *fDist;      //->
+    TH1F *fCosDA;     //->
+
+    TH1F *fDCA;       //->
+    TH1F *fDCADelta;  //->
+
+public:
+    MHHillasSrc(const char *name=NULL, const char *title=NULL);
+    ~MHHillasSrc();
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name) const;
+    TObject *FindObject(const TObject *obj) const { return 0; }
+    TObject *FindObject(const char *name) const
+    {
+        return (TObject*)GetHistByName(name);
+    }
+
+    TH1F *GetHistAlpha()         { return fAlpha; }
+    TH1F *GetHistDist()          { return fDist; }
+    TH1F *GetHistCosDeltaAlpha() { return fCosDA; }
+    TH1F *GetHistDCA()           { return fDCA; }
+    TH1F *GetHistDCADelta()      { return fDCADelta; }
+
+    void Draw(Option_t *opt=NULL);
+    void Paint(Option_t *opt);
+
+
+    ClassDef(MHHillasSrc, 2) // Container which holds histograms for the source dependant parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHImagePar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHImagePar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHImagePar.cc	(revision 17960)
@@ -0,0 +1,317 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 03/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHImagePar
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHImagePar.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MImagePar.h"
+
+ClassImp(MHImagePar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHImagePar::MHImagePar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHImagePar";
+    fTitle = title ? title : "Histograms of image parameters";
+
+    fHistSatHi.SetName("SatHi");
+    fHistSatHi.SetTitle("Number of pixels with saturating hi-gains");
+    fHistSatHi.SetXTitle("Pixels");
+    fHistSatHi.SetYTitle("Counts");
+    fHistSatHi.SetDirectory(NULL);
+    fHistSatHi.UseCurrentStyle();
+    fHistSatHi.SetLineColor(kBlue);
+    fHistSatHi.SetFillStyle(4000);
+
+    fHistSatLo.SetName("SatLo");
+    fHistSatLo.SetTitle("Number of pixels with saturating lo-gains");
+    fHistSatLo.SetXTitle("Pixels");
+    fHistSatLo.SetYTitle("Counts");
+    fHistSatLo.SetDirectory(NULL);
+    fHistSatLo.UseCurrentStyle();
+    fHistSatLo.SetFillStyle(4000);
+
+    fHistIslands.SetName("Islands");
+    fHistIslands.SetTitle("Number of Islands");
+    fHistIslands.SetXTitle("N");
+    fHistIslands.SetYTitle("Counts");
+    fHistIslands.SetDirectory(NULL);
+    fHistIslands.UseCurrentStyle();
+    //fHistIslands.SetLineColor(kBlue);
+    fHistIslands.SetFillStyle(4000);
+
+    fHistSizeSubIslands.SetName("SizeSub");
+    fHistSizeSubIslands.SetTitle("Size of Sub Islands");
+    fHistSizeSubIslands.SetXTitle("S [phe]");
+    fHistSizeSubIslands.SetYTitle("Counts");
+    fHistSizeSubIslands.SetDirectory(NULL);
+    fHistSizeSubIslands.UseCurrentStyle();
+    fHistSizeSubIslands.SetLineColor(kBlue);
+    fHistSizeSubIslands.SetFillStyle(4000);
+
+    fHistSizeMainIsland.SetName("SizeMain");
+    fHistSizeMainIsland.SetTitle("Size of Main Island");
+    fHistSizeMainIsland.SetXTitle("S [phe]");
+    fHistSizeMainIsland.SetYTitle("Counts");
+    fHistSizeMainIsland.SetDirectory(NULL);
+    fHistSizeMainIsland.UseCurrentStyle();
+    fHistSizeMainIsland.SetFillStyle(4000);
+
+    fHistNumSP.SetName("NumSP");
+    fHistNumSP.SetTitle("Number of single core pixels");
+    fHistNumSP.SetXTitle("N");
+    fHistNumSP.SetYTitle("Counts");
+    fHistNumSP.SetDirectory(NULL);
+    fHistNumSP.UseCurrentStyle();
+    //fHistNumSP.SetLineColor(kBlue);
+    fHistNumSP.SetFillStyle(4000);
+
+    fHistSizeSP.SetName("SizeSP");
+    fHistSizeSP.SetTitle("Size of single core pixels");
+    fHistSizeSP.SetXTitle("S [phe]");
+    fHistSizeSP.SetYTitle("Counts");
+    fHistSizeSP.SetDirectory(NULL);
+    fHistSizeSP.UseCurrentStyle();
+    //fHistSizeSP.SetLineColor(kBlue);
+    fHistSizeSP.SetFillStyle(4000);
+
+
+    MBinning bins;
+
+    bins.SetEdges(60, -0.5, 59.5);
+    bins.Apply(fHistSatLo);
+    bins.Apply(fHistSatHi);
+    bins.Apply(fHistNumSP);
+
+    bins.SetEdgesLog(50, 1, 1e7);
+    bins.Apply(fHistSizeSubIslands);
+    bins.Apply(fHistSizeMainIsland);
+    bins.Apply(fHistSizeSP);
+
+    bins.SetEdges(15, 0.5, 15.5);
+    bins.Apply(fHistIslands);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHImagePar::SetupFill(const MParList *plist)
+{
+    ApplyBinning(*plist, "Pixels",  fHistSatLo);
+    ApplyBinning(*plist, "Pixels",  fHistSatHi);
+    ApplyBinning(*plist, "Pixels",  fHistNumSP);
+
+    ApplyBinning(*plist, "Islands", fHistIslands);
+
+    ApplyBinning(*plist, "Size",    fHistSizeSubIslands);
+    ApplyBinning(*plist, "Size",    fHistSizeMainIsland);
+    ApplyBinning(*plist, "Size",    fHistSizeSP);
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MNewImagePar container.
+//
+Int_t MHImagePar::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MImagePar::Fill: Pointer (!=NULL) expected." << endl;
+        return kERROR;
+    }
+
+    const MImagePar &h = *(MImagePar*)par;
+
+    fHistSatHi.Fill(h.GetNumSatPixelsHG(),    w);
+    fHistSatLo.Fill(h.GetNumSatPixelsLG(),    w);
+    fHistNumSP.Fill(h.GetNumSinglePixels(),   w);
+    fHistSizeSP.Fill(h.GetSizeSinglePixels(), w);
+    fHistSizeSubIslands.Fill(h.GetSizeSubIslands(), w);
+    fHistSizeMainIsland.Fill(h.GetSizeMainIsland(), w);
+    fHistIslands.Fill(h.GetNumIslands(),      w);
+
+    return kTRUE;
+}
+
+void MHImagePar::Paint(Option_t *o)
+{
+     if (fHistSatHi.GetMaximum()>0 && gPad->GetPad(1))
+         gPad->GetPad(1)->SetLogy();
+     if (fHistIslands.GetMaximum()>0 && gPad->GetPad(3))
+         gPad->GetPad(3)->SetLogy();
+
+     TVirtualPad *pad = gPad->GetPad(2);
+     if (pad)
+     {
+         if (fHistNumSP.GetMaximum()>0 && pad->GetPad(1))
+             pad->GetPad(1)->SetLogy();
+         if (fHistSizeSP.GetMaximum()>0 && pad->GetPad(2))
+         {
+             pad->GetPad(2)->SetLogx();
+             pad->GetPad(2)->SetLogy();
+         }
+     }
+     if (fHistSizeMainIsland.GetMaximum()>0 && gPad->GetPad(4))
+     {
+         gPad->GetPad(4)->SetLogx();
+         gPad->GetPad(4)->SetLogy();
+     }
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHImagePar::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString opt(o);
+    opt.ToLower();
+
+    // FIXME: If same-option given make two independant y-axis!
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(2,2);
+    else
+    {
+        fHistSatHi.SetName("SatHiSame");
+        fHistSatLo.SetName("SatLoSame");
+        fHistIslands.SetName("IslandsSame");
+        fHistSizeSubIslands.SetName("SizeSubSame");
+        fHistSizeMainIsland.SetName("SizeMainSame");
+        fHistNumSP.SetName("NumSPSame");
+        fHistSizeSP.SetName("SizeSPSame");
+
+        fHistSatHi.SetDirectory(0);
+        fHistSatLo.SetDirectory(0);
+        fHistIslands.SetDirectory(0);
+        fHistSizeSubIslands.SetDirectory(0);
+        fHistSizeMainIsland.SetDirectory(0);
+        fHistNumSP.SetDirectory(0);
+        fHistSizeSP.SetDirectory(0);
+
+        fHistSatHi.SetLineColor(kMagenta);
+        fHistSatLo.SetLineColor(kCyan);
+        fHistSizeMainIsland.SetLineColor(kMagenta);
+        fHistSizeSubIslands.SetLineColor(kCyan);
+        fHistIslands.SetLineColor(kBlue);
+        fHistNumSP.SetLineColor(kBlue);
+        fHistSizeSP.SetLineColor(kBlue);
+    }
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("SatHiSame");
+    RemoveFromPad("SatLoSame");
+    MH::DrawSame(fHistSatHi, fHistSatLo, "Saturating Pixels", same);
+    fHistSatHi.SetMinimum();    // switch off to allow log-scale
+    fHistSatLo.SetMinimum();    // switch off to allow log-scale
+    fHistSatLo.SetMaximum(0.1); // dummy value to allow log-scale
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("SizeSubSame");
+    RemoveFromPad("SizeMainSame");
+    MH::DrawSame(fHistSizeMainIsland, fHistSizeSubIslands, "Sizes...", same);
+    fHistSizeMainIsland.SetMinimum();    // switch off to allow log-scale
+    fHistSizeSubIslands.SetMinimum();    // switch off to allow log-scale
+    fHistSizeSubIslands.SetMaximum(0.1); // dummy value to allow log-scale
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    if (!same)
+        pad->GetPad(2)->Divide(1,2,1e-10,1e-10);
+    if (pad->GetPad(2))
+    {
+        pad->GetPad(2)->cd(1);
+        gPad->SetBorderMode(0);
+        RemoveFromPad("NumSPSame");
+        fHistNumSP.Draw(same?"same":"");
+        pad->GetPad(2)->cd(2);
+        gPad->SetBorderMode(0);
+        RemoveFromPad("SizeSPSame");
+        fHistSizeSP.Draw(same?"same":"");
+    }
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("IslandsSame");
+    fHistIslands.Draw(same?"same":"");
+}
+
+TH1 *MHImagePar::GetHistByName(const TString name) const
+{
+    if (name.Contains("SatHi", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistSatHi);
+    if (name.Contains("SatLo", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistSatLo);
+    if (name.Contains("Islands", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistIslands);
+
+    return NULL;
+}
Index: branches/Mars_McMismatchStudy/mimage/MHImagePar.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHImagePar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHImagePar.h	(revision 17960)
@@ -0,0 +1,53 @@
+#ifndef MARS_MHImagePar
+#define MARS_MHImagePar
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MHillas;
+
+class MHImagePar : public MH
+{
+private:
+    TH1F fHistSatHi;          // Number of pixels with sat hi-gain
+    TH1F fHistSatLo;          // Number of pixels with sat lo-gain
+
+    TH1F fHistIslands;        // Number of islands per event
+    TH1F fHistSizeSubIslands; // Size of sub islands
+    TH1F fHistSizeMainIsland; // Size of main island
+
+    TH1F fHistNumSP;          // Number of single core pixels
+    TH1F fHistSizeSP;         // size of single core pixels
+
+    Short_t fNumSatPixelsHG; // number of pixels with saturating hi-gains
+    Short_t fNumSatPixelsLG; // number of pixels with saturating lo-gains
+
+public:
+    MHImagePar(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name) const;
+    TObject *FindObject(const TObject *obj) const { return 0; }
+    TObject *FindObject(const char *name) const
+    {
+        return (TObject*)GetHistByName(name);
+    }
+
+    TH1F &GetHistSatHi()   { return fHistSatHi; }
+    TH1F &GetHistSatLo()   { return fHistSatLo; }
+
+    TH1F &GetHistIslands() { return fHistIslands; }
+
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHImagePar, 1) // Histograms of image parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHNewImagePar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHNewImagePar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHNewImagePar.cc	(revision 17960)
@@ -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): 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-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHNewImagePar
+//
+//
+// ClassVersion 2:
+// ----------
+//  + TH1F fHistConcCOG;   // [ratio] concentration around the center of gravity (all pixels)
+//  + TH1F fHistConcCore;  // [ratio] concentration of signals inside ellipse (used pixels)
+//
+// ClassVersion 3:
+// ---------------
+//  - fMm2Deg
+//  - fUseMmScale
+//
+////////////////////////////////////////////////////////////////////////////
+#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)
+    : fGeom(0)
+{
+    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 [\\circ^{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 [\\circ^{2}]");
+    fHistCoreArea.SetYTitle("Counts");
+    fHistCoreArea.SetDirectory(NULL);
+    fHistCoreArea.UseCurrentStyle();
+    fHistCoreArea.SetLineColor(kBlack);
+    fHistCoreArea.SetFillStyle(4000);
+
+    fHistConc.SetDirectory(NULL);
+    fHistConc1.SetDirectory(NULL);
+    fHistConcCOG.SetDirectory(NULL);
+    fHistConcCore.SetDirectory(NULL);
+    fHistConc.SetName("Conc2");
+    fHistConc1.SetName("Conc1");
+    fHistConcCOG.SetName("ConcCOG");
+    fHistConcCore.SetName("ConcCore");
+    fHistConc.SetTitle("Ratio: Conc");
+    fHistConc1.SetTitle("Ratio: Conc1");
+    fHistConcCOG.SetTitle("Ratio: ConcCOG");
+    fHistConcCore.SetTitle("Ratio: ConcCore");
+    fHistConc.SetXTitle("Ratio");
+    fHistConc1.SetXTitle("Ratio");
+    fHistConcCOG.SetXTitle("Ratio");
+    fHistConcCore.SetXTitle("Ratio");
+    fHistConc.SetYTitle("Counts");
+    fHistConc1.SetYTitle("Counts");
+    fHistConcCOG.SetYTitle("Counts");
+    fHistConcCore.SetYTitle("Counts");
+    fHistConc.UseCurrentStyle();
+    fHistConc1.UseCurrentStyle();
+    fHistConcCOG.UseCurrentStyle();
+    fHistConcCore.UseCurrentStyle();
+    fHistConc.SetFillStyle(4000);
+    fHistConc1.SetFillStyle(4000);
+    fHistConcCOG.SetFillStyle(4000);
+    fHistConcCore.SetFillStyle(4000);
+    fHistConc1.SetLineColor(kBlue);
+    fHistConcCOG.SetLineColor(kBlue);
+
+    MBinning bins;
+
+    bins.SetEdges(100, 0, 1);
+    bins.Apply(fHistLeakage1);
+    bins.Apply(fHistLeakage2);
+    bins.Apply(fHistConc);
+    bins.Apply(fHistConc1);
+    bins.Apply(fHistConcCOG);
+    bins.Apply(fHistConcCore);
+
+    bins.SetEdges(75, 0.5, 150.5);
+    bins.Apply(fHistUsedPix);
+    bins.Apply(fHistCorePix);
+
+    MBinning b;
+    b.SetEdges(50, 0, 1.5);
+    b.Apply(fHistUsedArea);
+    b.Apply(fHistCoreArea);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHNewImagePar::SetupFill(const MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningArea");
+    if (bins)
+    {
+        bins->Apply(fHistUsedArea);
+        bins->Apply(fHistCoreArea);
+    }
+
+    ApplyBinning(*plist, "Leakage", fHistLeakage1);
+    ApplyBinning(*plist, "Leakage", fHistLeakage2);
+
+    ApplyBinning(*plist, "Pixels",  fHistUsedPix);
+    ApplyBinning(*plist, "Pixels",  fHistCorePix);
+
+    //ApplyBinning(*plist, "Area",    fHistUsedArea);
+    //ApplyBinning(*plist, "Area",    fHistCoreArea);
+
+    ApplyBinning(*plist, "Conc",     fHistConc);
+    ApplyBinning(*plist, "Conc1",    fHistConc1);
+    ApplyBinning(*plist, "ConcCOG",  fHistConcCOG);
+    ApplyBinning(*plist, "ConcCore", fHistConcCore);
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MNewImagePar container.
+//
+Int_t MHNewImagePar::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHNewImagePar::Fill: Pointer (!=NULL) expected." << endl;
+        return kERROR;
+    }
+
+    const Double_t scale = fGeom->GetConvMm2Deg()*fGeom->GetConvMm2Deg();
+
+    const MNewImagePar &h = *(MNewImagePar*)par;
+
+    fHistLeakage1.Fill(h.GetLeakage1(), w);
+    fHistLeakage2.Fill(h.GetLeakage2(), w);
+
+    fHistUsedPix.Fill(h.GetNumUsedPixels(), w);
+    fHistCorePix.Fill(h.GetNumCorePixels(), w);
+
+    fHistUsedArea.Fill(h.GetUsedArea()*scale, w);
+    fHistCoreArea.Fill(h.GetCoreArea()*scale, w);
+
+    fHistConc.Fill(h.GetConc(), w);
+    fHistConc1.Fill(h.GetConc1(), w);
+    fHistConcCOG.Fill(h.GetConcCOG(), w);
+    fHistConcCore.Fill(h.GetConcCore(), w);
+
+    return kTRUE;
+}
+
+void MHNewImagePar::Paint(Option_t *o)
+{
+    if (fHistLeakage1.GetMaximum()>0 && gPad->GetPad(1) && gPad->GetPad(1)->GetPad(1))
+        gPad->GetPad(1)->GetPad(1)->SetLogy();
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHNewImagePar::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    // FIXME: If same-option given make two independant y-axis!
+    const TString opt(o);
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(2, 1);
+    else
+    {
+        fHistLeakage1.SetName("Leakage1Same");
+        fHistLeakage2.SetName("Leakage2Same");
+        fHistUsedPix.SetName("UsedPixSame");
+        fHistCorePix.SetName("CorePixSame");
+        fHistUsedArea.SetName("UsedAreaSame");
+        fHistCoreArea.SetName("CoreAreaSame");
+        fHistConcCOG.SetName("ConcCOGSame");
+        fHistConcCore.SetName("ConcCoreSame");
+        fHistConc1.SetName("Conc1Same");
+        fHistConc.SetName("Conc2Same");
+
+        fHistLeakage1.SetDirectory(0);
+        fHistLeakage2.SetDirectory(0);
+        fHistUsedPix.SetDirectory(0);
+        fHistCorePix.SetDirectory(0);
+        fHistUsedArea.SetDirectory(0);
+        fHistCoreArea.SetDirectory(0);
+        fHistConcCOG.SetDirectory(0);
+        fHistConcCore.SetDirectory(0);
+        fHistConc1.SetDirectory(0);
+        fHistConc.SetDirectory(0);
+
+        fHistLeakage1.SetLineColor(kMagenta);
+        fHistLeakage1.SetLineColor(kCyan);
+        fHistCorePix.SetLineColor(kMagenta);
+        fHistUsedPix.SetLineColor(kCyan);
+        fHistConc1.SetLineColor(kMagenta);
+        fHistConc.SetLineColor(kCyan);
+        fHistConcCOG.SetLineColor(kMagenta);
+        fHistConcCore.SetLineColor(kCyan);
+        fHistCoreArea.SetLineColor(kMagenta);
+        fHistUsedArea.SetLineColor(kCyan);
+    }
+
+    pad->cd(1);
+    TVirtualPad *pad1=gPad;
+    pad1->SetBorderMode(0);
+    if (!same)
+        pad1->Divide(1,3, 0.001, 0.001);
+
+    pad1->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    TAxis &x = *fHistLeakage1.GetXaxis();
+    x.SetRangeUser(0.0, x.GetXmax());
+    RemoveFromPad("Leakage1Same");
+    RemoveFromPad("Leakage2Same");
+    MH::DrawSame(fHistLeakage1, fHistLeakage2, "Leakage1 and Leakage2", same);
+    fHistLeakage1.SetMinimum();
+    fHistLeakage2.SetMinimum();
+    fHistLeakage2.SetMaximum(0.1);   // dummy value to allow log-scale
+
+    pad1->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("UsedPixSame");
+    RemoveFromPad("CorePixSame");
+    MH::DrawSame(fHistCorePix, fHistUsedPix, "Number of core/used Pixels", same);
+
+    pad1->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("CoreAreaSame");
+    RemoveFromPad("UsedAreaSame");
+    MH::DrawSame(fHistCoreArea, fHistUsedArea, "Area of core/used Pixels", same);
+
+    pad->cd(2);
+    TVirtualPad *pad2=gPad;
+    pad2->SetBorderMode(0);
+    if (!same)
+        pad2->Divide(1, 2, 0.001, 0.001);
+
+    pad2->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("Conc1Same");
+    RemoveFromPad("Conc2Same");
+    MH::DrawSame(fHistConc1, fHistConc, "Concentrations", same);
+
+    pad2->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    RemoveFromPad("ConcCOGSame");
+    RemoveFromPad("ConcCoreSame");
+    MH::DrawSame(fHistConcCore, fHistConcCOG, "Concentrations", same);
+}
+
+TH1 *MHNewImagePar::GetHistByName(const TString name) const
+{
+    if (name.Contains("Leakage1", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistLeakage1);
+    if (name.Contains("Leakage2", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistLeakage2);
+    if (name.Contains("ConcCOG", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistConcCOG);
+    if (name.Contains("ConcCore", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistConcCore);
+    if (name.Contains("Conc1", TString::kIgnoreCase)) // must be first!
+        return const_cast<TH1F*>(&fHistConc1);
+    if (name.Contains("Conc", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistConc);
+    if (name.Contains("UsedPix", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistUsedPix);
+    if (name.Contains("CorePix", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistCorePix);
+    if (name.Contains("UsedArea", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistUsedArea);
+    if (name.Contains("CoreArea", TString::kIgnoreCase))
+        return const_cast<TH1F*>(&fHistCoreArea);
+
+    return NULL;
+}
Index: branches/Mars_McMismatchStudy/mimage/MHNewImagePar.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHNewImagePar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHNewImagePar.h	(revision 17960)
@@ -0,0 +1,68 @@
+#ifndef MARS_MHNewImagePar
+#define MARS_MHNewImagePar
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MGeomCam;
+class MHillas;
+
+class MHNewImagePar : public MH
+{
+private:
+    MGeomCam *fGeom;     //! Conversion from mm to deg
+
+    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
+    TH1F fHistConcCOG;   // [ratio] concentration of the three pixels next to COG
+    TH1F fHistConcCore;  // [ratio] concentration of signals inside or touching the ellipse
+
+public:
+    MHNewImagePar(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name) const;
+    TObject *FindObject(const TObject *obj) const { return 0; }
+    TObject *FindObject(const char *name) const
+    {
+        return (TObject*)GetHistByName(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; }
+    TH1F &GetHistConcCOG()   { return fHistConcCOG; }
+    TH1F &GetHistConcCore()  { return fHistConcCore; }
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHNewImagePar, 3) // Histograms of new image parameters
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mimage/MHNewImagePar2.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHNewImagePar2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHNewImagePar2.cc	(revision 17960)
@@ -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, 03/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHNewImagePar2
+//
+// ClassVersion 2:
+// ---------------
+//  - fMm2Deg
+//  - fUseMmScale
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHNewImagePar2.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MNewImagePar2.h"
+
+ClassImp(MHNewImagePar2);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHNewImagePar2::MHNewImagePar2(const char *name, const char *title)
+    : fGeom(0)
+{
+    fName  = name  ? name  : "MHNewImagePar2";
+    fTitle = title ? title : "Histograms of new image parameters 2";
+
+    fHistBorder1.SetName("Border1");
+    fHistBorder1.SetTitle("Border Line of border pixels (pixel border)");
+    fHistBorder1.SetXTitle("Border [\\circ]]");
+    fHistBorder1.SetYTitle("Counts");
+    fHistBorder1.SetDirectory(NULL);
+    fHistBorder1.UseCurrentStyle();
+    fHistBorder1.SetFillStyle(4000);
+
+    fHistBorder2.SetName("Border2");
+    fHistBorder2.SetTitle("Border Line of border pixels (pixel center)");
+    fHistBorder2.SetXTitle("Border [\\circ]]");
+    fHistBorder2.SetYTitle("Counts");
+    fHistBorder2.SetDirectory(NULL);
+    fHistBorder2.UseCurrentStyle();
+    fHistBorder2.SetLineColor(kBlue);
+    fHistBorder2.SetFillStyle(4000);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHNewImagePar2::SetupFill(const MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningBorder");
+    if (!bins)
+    {
+        MBinning b;
+        b.SetEdges(87, 0, 10);
+        b.Apply(fHistBorder1);
+        b.Apply(fHistBorder2);
+    }
+    else
+    {
+        bins->Apply(fHistBorder1);
+        bins->Apply(fHistBorder2);
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MNewImagePar2 container.
+//
+Int_t MHNewImagePar2::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MNewImagePar2 *h = dynamic_cast<const MNewImagePar2*>(par);
+    if (!h)
+    {
+        *fLog << err << "MHNewImagePar2::Fill: Pointer (!=NULL) expected." << endl;
+        return kERROR;
+    }
+
+    const Double_t scale = fGeom->GetConvMm2Deg();
+
+    fHistBorder1.Fill(h->GetBorderLinePixel() *scale, w);
+    fHistBorder2.Fill(h->GetBorderLineCenter()*scale, 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 MHNewImagePar2::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    gPad->SetBorderMode(0);
+    MH::DrawSame(fHistBorder1, fHistBorder2, "Border Line");
+}
Index: branches/Mars_McMismatchStudy/mimage/MHNewImagePar2.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHNewImagePar2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHNewImagePar2.h	(revision 17960)
@@ -0,0 +1,35 @@
+#ifndef MARS_MHNewImagePar2
+#define MARS_MHNewImagePar2
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MGeomCam;
+class MHillas;
+
+class MHNewImagePar2 : public MH
+{
+private:
+    MGeomCam *fGeom;    //! conversion mm to deg
+
+    TH1F fHistBorder1;  //
+    TH1F fHistBorder2;  //
+
+public:
+    MHNewImagePar2(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHNewImagePar2, 2) // Histograms of new image parameters
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mimage/MHVsSize.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHVsSize.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHVsSize.cc	(revision 17960)
@@ -0,0 +1,282 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek  2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHVsSize
+//
+// This class contains histograms for the source independent image parameters
+//
+// ClassVersion 2:
+// ---------------
+//  - fMm2Deg
+//  - fUseMmScale
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHVsSize.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 "MHillasSrc.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MGeomCam.h"
+#include "MBinning.h"
+
+ClassImp(MHVsSize);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Width, Length
+//
+MHVsSize::MHVsSize(const char *name, const char *title)
+    : fGeom(0), fHillas(0), fHillasExt(0), fNewImagePar(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHVsSize";
+    fTitle = title ? title : "Source independent image parameters";
+
+    fLength.SetNameTitle("Length", "Length vs. Size");
+    fWidth.SetNameTitle( "Width",  "Width vs. Size");
+    fDist.SetNameTitle(  "Dist",   "Dist vs. Size");
+    fConc1.SetNameTitle( "Conc1",  "Conc1 vs. Size");
+    fArea.SetNameTitle(  "Area",   "Area vs. Size");
+    fM3Long.SetNameTitle("M3Long", "M3Long vs. Size");
+
+    fLength.SetDirectory(NULL);
+    fWidth.SetDirectory(NULL);
+    fDist.SetDirectory(NULL);
+    fConc1.SetDirectory(NULL);
+    fArea.SetDirectory(NULL);
+    fM3Long.SetDirectory(NULL);
+
+    fLength.SetXTitle("Size [phe]");
+    fWidth.SetXTitle("Size [phe]");
+    fDist.SetXTitle("Size [phe]");
+    fConc1.SetXTitle("Size [phe]");
+    fArea.SetXTitle("Size [phe]");
+    fM3Long.SetXTitle("Size [phe]");
+
+    fLength.SetYTitle("Length [\\circ]");
+    fWidth.SetYTitle("Width [\\circ]");
+    fDist.SetYTitle("Distance [\\circ]");
+    fConc1.SetYTitle("Conc1 [ratio]");
+    fArea.SetYTitle("Area [\\circ^{2}]");
+    fM3Long.SetYTitle("M3Long [\\circ]");
+
+    const MBinning binse( 50,   10, 1e5, "", "log");
+    const MBinning binsc(100, 3e-3, 1,   "", "log");
+    const MBinning binsl(100,    0, 0.5);
+    const MBinning binsd(100,    0, 2.0);
+    const MBinning binsa(100,    0, 0.25);
+    const MBinning binsm(100, -1.5, 1.5);
+
+    MH::SetBinning(fLength, binse, binsl);
+    MH::SetBinning(fWidth,  binse, binsl);
+    MH::SetBinning(fDist,   binse, binsd);
+    MH::SetBinning(fConc1,  binse, binsc);
+    MH::SetBinning(fArea,   binse, binsa);
+    MH::SetBinning(fM3Long, binse, binsm);
+
+    fLength.UseCurrentStyle();
+    fWidth.UseCurrentStyle();
+    fDist.UseCurrentStyle();
+    fConc1.UseCurrentStyle();
+    fArea.UseCurrentStyle();
+    fM3Long.UseCurrentStyle();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MHVsSize::SetupFill(const MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fHillas = (MHillas*)plist->FindObject("MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << "MHillas not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fHillasExt = (MHillasExt*)plist->FindObject("MHillasExt");
+    if (!fHillasExt)
+    {
+        *fLog << err << "MHillasExt not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fNewImagePar = (MNewImagePar*)plist->FindObject("MNewImagePar");
+    if (!fNewImagePar)
+    {
+        *fLog << err << "MNewImagePar not found... abort." << endl;
+        return kFALSE;
+    }
+
+    /*
+     ApplyBinning(*plist, "Width",  "Size", fWidth);
+     ApplyBinning(*plist, "Length", "Size", fLength);
+     ApplyBinning(*plist, "Area",   "Size", fArea);
+     ApplyBinning(*plist, "M3Long", "Size", fM3Long);
+     ApplyBinning(*plist, "Conc1",  "Size", fConc1);
+     */
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Int_t MHVsSize::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MHillasSrc *src = dynamic_cast<const MHillasSrc*>(par);
+    if (!src)
+    {
+        *fLog << err << "MHVsSize::Fill: Wrong argument... abort." << endl;
+        return kERROR;
+    }
+
+    const Double_t scale = fGeom->GetConvMm2Deg();
+
+    fLength.Fill(fHillas->GetSize(), scale*fHillas->GetLength(),     w);
+    fWidth.Fill( fHillas->GetSize(), scale*fHillas->GetWidth(),      w);
+    fDist.Fill(  fHillas->GetSize(), scale*src->GetDist(),           w);
+    fConc1.Fill( fHillas->GetSize(), fNewImagePar->GetConc1(),       w);
+    fArea.Fill(  fHillas->GetSize(), scale*scale*fHillas->GetArea(), w);
+    fM3Long.Fill(fHillas->GetSize(), scale*fHillasExt->GetM3Long()*TMath::Sign(1.0f, src->GetCosDeltaAlpha()), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MHVsSize::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString opt(o);
+    opt.ToLower();
+
+    // FIXME: If same-option given make two independant y-axis!
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(3,2);
+    else
+    {
+        fLength.SetName("LengthSame");
+        fWidth.SetName("WidthSame");
+        fDist.SetName("DistSame");
+        fConc1.SetName("Conc1Same");
+        fArea.SetName("AreaSame");
+        fM3Long.SetName("M3LongSame");
+
+        fLength.SetDirectory(0);
+        fWidth.SetDirectory(0);
+        fDist.SetDirectory(0);
+        fConc1.SetDirectory(0);
+        fArea.SetDirectory(0);
+        fM3Long.SetDirectory(0);
+
+        fDist.SetMarkerColor(kBlue);
+        fConc1.SetMarkerColor(kBlue);
+        fWidth.SetMarkerColor(kBlue);
+        fLength.SetMarkerColor(kBlue);
+        fArea.SetMarkerColor(kBlue);
+        fM3Long.SetMarkerColor(kBlue);
+    }
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    RemoveFromPad("LengthSame");
+    fLength.Draw(same?"same":"");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    RemoveFromPad("WidthSame");
+    fWidth.Draw(same?"same":"");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    RemoveFromPad("DistSame");
+    fDist.Draw(same?"same":"");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    RemoveFromPad("AreaSame");
+    fArea.Draw(same?"same":"");
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    RemoveFromPad("M3LongSame");
+    fM3Long.Draw(same?"same":"");
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    RemoveFromPad("Conc1Same");
+    fConc1.Draw(same?"same":"");
+}
Index: branches/Mars_McMismatchStudy/mimage/MHVsSize.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHVsSize.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHVsSize.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MHVsSize
+#define MARS_MHVsSize
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MGeomCam;
+class MHillas;
+class MHillasExt;
+class MNewImagePar;
+
+class MHVsSize : public MH
+{
+private:
+    MGeomCam     *fGeom;        //! Conversion from mm to deg
+    MHillas      *fHillas;      //!
+    MHillasExt   *fHillasExt;   //!
+    MNewImagePar *fNewImagePar; //!
+
+    TH2F fLength;  // Length
+    TH2F fWidth;   // Width
+
+    TH2F fDist;    // Distance to Camera Center
+    TH2F fConc1;   // Angle between Length axis and x-axis
+
+    TH2F fM3Long;  // 
+    TH2F fArea;    // 
+
+public:
+    MHVsSize(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHVsSize, 2) // Container which holds histograms for image parameters vs size
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHillas.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillas.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillas.cc	(revision 17960)
@@ -0,0 +1,426 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHillas
+//
+// Storage Container for image parameters
+//
+//    basic image parameters
+//
+// Version 1:
+// ----------
+// fLength   [mm]       major axis of ellipse
+// fWidth    [mm]       minor axis
+// fDelta    [rad]      angle of major axis with x-axis
+//                      by definition the major axis is pointing into
+//                      the hemisphere x>0, thus -pi/2 < delta < pi/2
+// fSize     [#CerPhot] total sum of pixels
+// fMeanX    [mm]       x of center of ellipse
+// fMeanY    [mm]       y of center of ellipse
+//
+// Version 2:
+// ----------
+// fNumCorePixels  number of pixels called core
+// fNumUsedPixels  number of pixels which survived the cleaning
+//
+// Version 3:
+// ----------
+// fNumCorePixels  moved to MNewImagePar
+// fNumUsedPixels  moved to MNewImagePar
+// fCosDelta       added
+// fSinDelte       added
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillas.h"
+
+#include <TArrayF.h>
+
+#include <TLine.h>
+#include <TEllipse.h>
+#include <TVector2.h>
+
+#include "MGeom.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHillas);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillas::MHillas(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHillas";
+    fTitle = title ? title : "Storage container for image parameters of one event";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes the values with defaults. For the default values see the
+// source code.
+//
+void MHillas::Reset()
+{
+    fLength = -1;
+    fWidth  = -1;
+    fDelta  =  0;
+
+    fSize   = -1;
+    fMeanX  =  0;
+    fMeanY  =  0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  return distance to center (coordinate origin)
+//
+Double_t MHillas::GetDist0() const
+{
+    return TMath::Hypot(fMeanX, fMeanY);
+} 
+
+// --------------------------------------------------------------------------
+//
+//  return the mean position as TVector2(meanx, meany)
+//
+TVector2 MHillas::GetMean() const
+{
+    return TVector2(fMeanX, fMeanY);
+}
+
+// --------------------------------------------------------------------------
+//
+//  return the direction of the main axis (normalized). The main axis
+//  always has the direction  -->  x>0
+//
+TVector2 MHillas::GetNormAxis() const
+{
+    return TVector2(fCosDelta, fSinDelta);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Analytical estimation of length of border line:
+//    U = pi*(a+b - sqrt(a*b))
+//
+//  GetBorderLine() [mm]
+//
+Double_t MHillas::GetBorderLine() const
+{
+    const Double_t a = fWidth+fLength;
+    const Double_t s = fWidth*fLength;
+
+    return TMath::Pi()*(1.5*a - TMath::Sqrt(s));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Analytical estimation of length of border line:
+//    A = pi*a*b
+//
+//  GetArea() [mm^2]
+//
+Double_t MHillas::GetArea() const
+{
+    return TMath::Pi()*fWidth*fLength;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the hillas Parameters to *fLog
+//
+void MHillas::Print(Option_t *) const
+{
+    const Double_t atg = atan2(fMeanX, fMeanY)*kRad2Deg;
+
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Length         [mm]  = " << fLength << endl;
+    *fLog << " - Width          [mm]  = " << fWidth  << endl;
+    *fLog << " - Delta          [deg] = " << fDelta*kRad2Deg << endl;
+    *fLog << " - Size           [phe] = " << fSize   << 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
+{
+    const Double_t atg = atan2(fMeanX, fMeanY)*kRad2Deg;
+
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Length         [deg] = " << fLength*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Width          [deg] = " << fWidth *geom.GetConvMm2Deg() << endl;
+    *fLog << " - Delta          [deg] = " << fDelta*kRad2Deg << endl;
+    *fLog << " - Size           [phe] = " << fSize << endl;
+    *fLog << " - Meanx          [deg] = " << fMeanX *geom.GetConvMm2Deg() << endl;
+    *fLog << " - Meany          [deg] = " << fMeanY *geom.GetConvMm2Deg() << endl;
+    *fLog << " - atg(y/x)       [deg] = " << atg     << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MHillas::Paint(Option_t *opt)
+{
+    static const Float_t sOffsetW=40.0;
+    static const Float_t sOffsetL=266.0;
+
+    if (fLength<0 || fWidth<0)
+        return;
+
+    const Float_t l = fLength+sOffsetL;
+    const Float_t w = fWidth +sOffsetW;
+
+    TLine line;
+    line.SetLineWidth(1);
+    line.SetLineColor(kRed);
+
+    // Length line
+    line.PaintLine(-l*fCosDelta+fMeanX, -l*fSinDelta+fMeanY,
+                   +l*fCosDelta+fMeanX, +l*fSinDelta+fMeanY);
+
+
+    // Width line
+    line.PaintLine(+w*fSinDelta+fMeanX, -w*fCosDelta+fMeanY,
+                   -w*fSinDelta+fMeanX, +w*fCosDelta+fMeanY);
+
+    // Rough estimate for disp
+    const Double_t p = 362*(1-fWidth/fLength);
+
+    // Disp line
+    line.PaintLine( p*fCosDelta+20*fSinDelta+fMeanX,  p*fSinDelta-20*fCosDelta+fMeanY,
+                    p*fCosDelta-20*fSinDelta+fMeanX,  p*fSinDelta+20*fCosDelta+fMeanY);
+    line.PaintLine(-p*fCosDelta+20*fSinDelta+fMeanX, -p*fSinDelta-20*fCosDelta+fMeanY,
+                   -p*fCosDelta-20*fSinDelta+fMeanX, -p*fSinDelta+20*fCosDelta+fMeanY);
+
+    TEllipse e(fMeanX, fMeanY, fLength, fWidth, 0, 360, fDelta*kRad2Deg+180);
+    e.SetLineWidth(2);
+    e.SetLineColor(kGreen);
+    e.Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the image parameters from a Cherenkov photon event
+// assuming Cher.photons/pixel and pixel coordinates are given
+// In case you don't call Calc from within an eventloop make sure, that
+// you call the Reset member function before.
+// Returns:
+//   0  no error
+//   1  number of pixels in event == 0 (special MC events)
+//   2  size==0
+//   3  number of used pixel < 3
+//   4  CorrXY == 0
+//
+Int_t MHillas::Calc(const MGeomCam &geom, const MSignalCam &evt, Int_t island)
+{
+    const UInt_t numpix  = evt.GetNumPixels();
+
+    //
+    // sanity check 1 (special MC events)
+    //
+    if (numpix==0)
+        return 1;
+
+    //
+    // calculate mean value of pixel coordinates and fSize
+    // -----------------------------------------------------
+    //
+    // Because this are only simple sums of roughly 600 values
+    // with an accuracy less than three digits there should not
+    // be any need to use double precision (Double_t) for the
+    // calculation of fMeanX, fMeanY and fSize.
+    //
+    fMeanX = 0;
+    fMeanY = 0;
+    fSize  = 0;
+
+    UInt_t numused = 0;
+
+    for (UInt_t i=0; i<numpix; i++)
+    {
+        MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        const MGeom &gpix = geom[i];
+
+        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]
+
+    for (UInt_t i=0; i<numpix; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        const MGeom &gpix = geom[i];
+
+        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]
+    }
+
+    //
+    // 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    = TMath::Sqrt(d0*d0 + d1*d1) + d0; // [0
+
+    const Double_t tand  = d2==0 ? 0 : d2 / d1; // Force 0 also if d1==0
+    const Double_t tand2 = tand*tand;
+
+    const Double_t s2    = tand2+1;
+    const Double_t s     = TMath::Sqrt(s2);
+
+    // Set default for the case in which the image is symmetric on the y-axis
+    fDelta    = TMath::Pi()/2;
+    fCosDelta = 0;
+    fSinDelta = 1;
+
+    Double_t axis1 = corryy;
+    Double_t axis2 = corrxx;
+
+    // This are all cases in which the image is not symmetric on the y-axis
+    if (d1!=0 || d2==0)
+    {
+        fDelta    = TMath::ATan(tand);
+
+        fCosDelta = 1.0 /s;   // need these in derived classes
+        fSinDelta = tand/s;   // like MHillasExt
+
+        axis1 = (tand2*corryy + d2 + corrxx)/s2;
+        axis2 = (tand2*corrxx - d2 + corryy)/s2;
+    }
+
+    //
+    // fLength^2 is the second moment along the major axis of the distribution
+    // fWidth^2  is the second moment along the minor axis of the distribution
+    //
+    // 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/fSize);  // [mm]
+    fWidth  = axis2<0 ? 0 : TMath::Sqrt(axis2/fSize);  // [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: branches/Mars_McMismatchStudy/mimage/MHillas.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillas.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillas.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MHillas
+#define MARS_MHillas
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayF;
+class TVector2;
+
+class MGeomCam;
+class MSignalCam;
+
+class MHillas : public MParContainer
+{
+private:
+    // for description see MHillas.cc
+    Float_t fLength;        // [mm]        major axis of ellipse
+    Float_t fWidth;         // [mm]        minor axis of ellipse
+    Float_t fDelta;         // [rad]       angle of major axis with x-axis
+    Float_t fSize;          // [#CerPhot]  sum of content of all pixels (number of Cherenkov photons)
+    Float_t fMeanX;         // [mm]        x-coordinate of center of ellipse
+    Float_t fMeanY;         // [mm]        y-coordinate of center of ellipse
+
+    Float_t fSinDelta;      // [1] sin of Delta (to be used in derived classes)
+    Float_t fCosDelta;      // [1] cos of Delta (to be used in derived classes)
+
+public:
+    MHillas(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MSignalCam &pix, Int_t island=-1);
+
+    void Print(const MGeomCam &geom) const;
+    void Print(Option_t *opt=NULL) const;
+    void Paint(Option_t *opt=NULL);
+
+    Float_t  GetLength() const { return fLength; }
+    Float_t  GetWidth() const  { return fWidth; }
+    Float_t  GetDelta() const  { return fDelta; }
+    Float_t  GetSize() const   { return fSize; }
+    Float_t  GetMeanX() const  { return fMeanX; }
+    Float_t  GetMeanY() const  { return fMeanY; }
+    Double_t GetDist0() const;
+
+    TVector2 GetMean() const;
+    TVector2 GetNormAxis() const;
+
+    Double_t GetBorderLine() const;
+    Double_t GetArea() const;
+
+    Float_t GetCosDelta() const { return fCosDelta; }
+    Float_t GetSinDelta() const { return fSinDelta; }
+
+    void Set(const TArrayF &arr);
+
+    ClassDef(MHillas, 3) // Storage Container for Hillas Parameter
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHillasCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillasCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillasCalc.cc	(revision 17960)
@@ -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): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHillasCalc
+//  ===========
+//
+//  This is a task to calculate the Hillas parameters from each event
+//
+//
+//   Flags
+//  --------
+//
+//  By default all flags are set:
+//
+//  To switch of the calculation you may use:
+//   - Disable(MHillasCalc::kCalcHillas)
+//   - Disable(MHillasCalc::kCalcHillasExt)
+//   - Disable(MHillasCalc::kCalcNewImagePar)
+//   - Disable(MHillasCalc::kCalcImagePar)
+//   - Disable(MHillasCalc::kCalcImagePar2)
+//   - Disable(MHillasCalc::kCalcSrcPosCam)
+//   - Disable(MHillasCalc::kCalcConc)
+//
+//  If the calculation of MHillas is switched off a container MHillas
+//  in the parameter list is nevertheless necessary for the calculation
+//  of some other containers, see below.
+//
+//  If kCalcHillasSrc is set and no corresponding MSrcPosCam is found
+//  in the parameter list an empty container (X=0, Y=0) is created.
+//
+//
+//   Container names
+//  -----------------
+//
+//  The names of the containers to be used can be set with:
+//   - SetNameHillas("NewName")
+//   - SetNameHillasExt("NewName")
+//   - SetNameNewImgPar("NewName")
+//   - SetNameImagePar("NewName")
+//   - SetNameImagePar2("NewName")
+//   - SetNameSrcPosCam("NewName")
+//   - SetNameConc("NewName")
+//   - SetNameHillasSrc("NewName")
+//
+//
+//   Islands
+//  ---------
+//
+//  You can change the islands for which the caluclations are done by:
+//   - SetNumIsland()
+//  The default is to use all used pixels (-1)
+//
+//  fIdxIslands effects the calculations:
+//   - kCalcHillas
+//   - kCalcHillasExt
+//   - kCalcNewImgPar
+//   - kCalcNewImgPar2
+//
+//
+//   Example
+//  ---------
+//
+//   MHillasCalc calc0; // calculate all image parameters except source dep.
+//   MHillasCalc calc1; // calculate source dependant image parameters for 'Source'
+//   MHillasCalc calc2; // calculate source dependant image parameters for 'AntiSource'
+//   MHillasCalc calc3; // calculate hillas parameters only for biggest island
+//   MHillasCalc calc4; // calculate hillas parameter for 2nd biggest island
+//   // setup names of input-/output-containers
+//   calc1.SetNameSrcPosCam("Source");
+//   calc2.SetNameSrcPosCam("AntiSource");
+//   calc1.SetNameHillasSrc("MHillasSource");
+//   calc2.SetNameHillasSrc("MHillasAntiSource");
+//   calc3.SetNameHillas("MHillas0");
+//   calc4.SetNameHillas("MHillas1");
+//   // setup calculations to be done
+//   calc0.Disable(MHillasCalc::kCalcHillasSrc);
+//   calc1.SetFlags(MHillasCalc::kCalcHillasSrc);
+//   calc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+//   calc3.SetFlags(MHillasCalc::kCalcHillas);
+//   calc4.SetFlags(MHillasCalc::kCalcHillas);
+//   // choode index of island
+//   calc3.SetNumIsland(0);
+//   calc4.SetNumIsland(1);
+//
+//   // setup tasklist
+//   MTaskList list;
+//   list.Add(&calc0);
+//   list.Add(&calc1);
+//   list.Add(&calc2);
+//   list.Add(&calc3);
+//   list.Add(&calc4);
+//
+//
+//   Input/Output Containers
+//  -------------------------
+//
+//    1) MGeomCam          5) MHillas         8) MImagePar
+//    2) MSignalCam        6) MHillasSrc      9) MNewImagePar
+//    3) MSrcPosCam        7) MHillasExt     10) MNewImagePar2
+//    4) fIdxIslands      11) MConcentration
+//
+//     Flag           | Input Container | Output
+//   -----------------+-----------------+--------
+//    kCalcHillas     |  1  2     4     |    5
+//    kCalcHillasSrc  |        3  4  5  |    6
+//    kCalcHillasExt  |  1  2     4  5  |    7
+//    kCalcImagePar   |     2           |    8
+//    kCalcNewImgPar  |  1  2     4  5  |    9
+//    kCalcNewImgPar2 |  1  2     4     |   10
+//    kCalcConc       |  1  2        5  |   11
+//   -----------------+-----------------+--------
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillasCalc.h"
+
+#include <fstream> // StreamPrimitive
+
+#include "MParList.h"
+
+#include "MSignalCam.h"
+
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MImagePar.h"
+#include "MNewImagePar.h"
+#include "MNewImagePar2.h"
+#include "MConcentration.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHillasCalc);
+
+using namespace std;
+
+const TString MHillasCalc::gsDefName         = "MHillasCalc";
+const TString MHillasCalc::gsDefTitle        = "Calculate Hillas and other image parameters";
+
+const TString MHillasCalc::gsNameHillas      = "MHillas";        // default name of the 'MHillas' container
+const TString MHillasCalc::gsNameHillasExt   = "MHillasExt";     // default name of the 'MHillasExt' container
+const TString MHillasCalc::gsNameNewImagePar = "MNewImagePar";   // default name of the 'MNewImagePar' container
+const TString MHillasCalc::gsNameNewImagePar2= "MNewImagePar2";  // default name of the 'MNewImagePar2' container
+const TString MHillasCalc::gsNameConc        = "MConcentration"; // default name of the 'MConcentration' container
+const TString MHillasCalc::gsNameImagePar    = "MImagePar";      // default name of the 'MImagePar' container
+const TString MHillasCalc::gsNameHillasSrc   = "MHillasSrc";     // default name of the 'MHillasSrc' container
+const TString MHillasCalc::gsNameSrcPosCam   = "MSrcPosCam";     // default name of the 'MSrcPosCam' container
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasCalc::MHillasCalc(const char *name, const char *title)
+        : fNameHillas(gsNameHillas),       fNameHillasExt(gsNameHillasExt),
+          fNameHillasSrc(gsNameHillasSrc), fNameSrcPosCam(gsNameSrcPosCam),
+          fNameConc(gsNameConc),           fNameImagePar(gsNameImagePar),
+          fNameNewImagePar(gsNameNewImagePar),
+          fNameNewImagePar2(gsNameNewImagePar2),
+          fErrors(7), fFlags(0xff), fIdxIsland(-1)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for in-/output containers, see class description
+//
+Int_t MHillasCalc::PreProcess(MParList *pList)
+{
+
+    if (TestFlags(~kCalcHillasSrc))
+    {
+        fCerPhotEvt = (MSignalCam*)pList->FindObject(AddSerialNumber("MSignalCam"));
+        if (!fCerPhotEvt)
+        {
+            *fLog << err << "MSignalCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    if (TestFlags(kCalcHillas|kCalcHillasExt|kCalcNewImagePar|kCalcNewImagePar2|kCalcConc))
+    {
+        fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+        if (!fGeomCam)
+        {
+            *fLog << err << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    // depend on whether MHillas is an in- or output container
+    if (TestFlag(kCalcHillas))
+    {
+        fHillas = (MHillas*)pList->FindCreateObj("MHillas", AddSerialNumber(fNameHillas));
+        if (!fHillas)
+            return kFALSE;
+    }
+
+    if (TestFlags(kCalcHillasExt|kCalcNewImagePar|kCalcConc|kCalcHillasSrc))
+    {
+        fHillas = (MHillas*)pList->FindObject(AddSerialNumber(fNameHillas), "MHillas");
+        if (!fHillas)
+        {
+            *fLog << err << fNameHillas << " [MHillas] not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    // if enabled
+    if (TestFlag(kCalcHillasExt))
+    {
+        fHillasExt = (MHillasExt*)pList->FindCreateObj("MHillasExt", AddSerialNumber(fNameHillasExt));
+        if (!fHillasExt)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcHillasSrc))
+    {
+        const MSrcPosCam *src = (MSrcPosCam*)pList->FindObject(AddSerialNumber(fNameSrcPosCam), "MSrcPosCam");
+        if (!src)
+        {
+            *fLog << warn << AddSerialNumber(fNameSrcPosCam) << " [MSrcPosCam] not found... creating default container." << endl;
+            src = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", AddSerialNumber(fNameSrcPosCam));
+        }
+        if (!src)
+            return kFALSE;
+
+        fHillasSrc = (MHillasSrc*)pList->FindCreateObj("MHillasSrc", AddSerialNumber(fNameHillasSrc));
+        if (!fHillasSrc)
+            return kFALSE;
+
+        fHillasSrc->SetSrcPos(src);
+    }
+
+    // if enabled
+    if (TestFlag(kCalcNewImagePar))
+    {
+        fNewImgPar = (MNewImagePar*)pList->FindCreateObj("MNewImagePar", AddSerialNumber(fNameNewImagePar));
+        if (!fNewImgPar)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcNewImagePar2))
+    {
+        fNewImgPar2 = (MNewImagePar2*)pList->FindCreateObj("MNewImagePar2", AddSerialNumber(fNameNewImagePar2));
+        if (!fNewImgPar2)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcImagePar))
+    {
+        fImagePar = (MImagePar*)pList->FindCreateObj("MImagePar", AddSerialNumber(fNameImagePar));
+        if (!fImagePar)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcConc))
+    {
+        fConc = (MConcentration*)pList->FindCreateObj("MConcentration", fNameConc);
+        if (!fConc)
+            return kFALSE;
+    }
+
+    fErrors.Reset();
+
+    Print();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want do complex descisions inside the calculations
+// we must move the calculation code inside this function
+//
+// If the calculation wasn't sucessfull skip this event
+//
+Int_t MHillasCalc::Process()
+{
+    if (TestFlag(kCalcHillas))
+    {
+        const Int_t rc = fHillas->Calc(*fGeomCam, *fCerPhotEvt, fIdxIsland);
+        if (rc<0 || rc>4)
+        {
+            *fLog << err << dbginf << "MHillas::Calc returned unknown error code!" << endl;
+            return kFALSE;
+        }
+        if (rc>0)
+        {
+            fErrors[rc]++;
+            return kCONTINUE;
+        }
+    }
+
+    if (TestFlag(kCalcHillasSrc))
+    {
+        const Int_t rc = fHillasSrc->Calc(*fHillas);
+        if (rc<0 || rc>2)
+        {
+            *fLog << err << dbginf << "MHillasSrc::Calc returned unknown error code!" << endl;
+            return kFALSE;
+        }
+        if (rc>0)
+        {
+            fErrors[rc+4]++;
+            return kCONTINUE;
+        }
+    }
+    fErrors[0]++;
+
+    if (TestFlag(kCalcHillasExt))
+        fHillasExt->Calc(*fGeomCam, *fCerPhotEvt, *fHillas, fIdxIsland);
+
+    if (TestFlag(kCalcImagePar))
+        fImagePar->Calc(*fCerPhotEvt);
+
+    if (TestFlag(kCalcNewImagePar))
+        fNewImgPar->Calc(*fGeomCam, *fCerPhotEvt, *fHillas, fIdxIsland);
+
+    if (TestFlag(kCalcNewImagePar2))
+        fNewImgPar2->Calc(*fGeomCam, *fCerPhotEvt, fIdxIsland);
+
+    if (TestFlag(kCalcConc))
+        fConc->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the hillas calculation. The percentage
+//  is calculated with respect to the number of executions of this task.
+//
+Int_t MHillasCalc::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    if (!TestFlag(kCalcHillas) && !TestFlag(kCalcHillasSrc))
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    if (TestFlag(kCalcHillas))
+    {
+        PrintSkipped(fErrors[1], "0-Pixel Event (before cleaning, MC event?)");
+        PrintSkipped(fErrors[2], "Calculated Size == 0 (after cleaning)");
+        PrintSkipped(fErrors[3], "Number of used pixels < 3");
+        //PrintSkipped(fErrors[4], "CorrXY==0");
+    }
+    if (TestFlag(kCalcHillasSrc))
+    {
+        PrintSkipped(fErrors[5], "Dist==0");
+        PrintSkipped(fErrors[6], "Arg2==0");
+    }
+    *fLog << " " << (int)fErrors[0] << " (" << Form("%5.1f", 100.*fErrors[0]/GetNumExecutions()) << "%) Evts survived Hillas calculation!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print 'Dataflow'
+//
+void MHillasCalc::Print(Option_t *o) const
+{
+    *fLog << inf << GetDescriptor() << " calculating:" << endl;
+    if (TestFlag(kCalcHillas))
+        *fLog << " - " << fNameHillas << " from MGeomCam, MSignalCam and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcHillasSrc))
+        *fLog << " - " << fNameHillasSrc << " from " << fNameSrcPosCam << ", " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcHillasExt))
+        *fLog << " - " << fNameHillasExt << " from MGeomCam, MSignalCam, " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcImagePar))
+        *fLog << " - " << fNameImagePar << " from MSignalCam" << endl;
+    if (TestFlag(kCalcNewImagePar))
+        *fLog << " - " << fNameNewImagePar << " from MGeomCam, MSignalCam, " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcNewImagePar2))
+        *fLog << " - " << fNameNewImagePar2 << " from MGeomCam, MSignalCam, " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcConc))
+        *fLog << " - " << fNameConc << " from MGeomCam, MSignalCam and " << fNameHillas << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MHillasCalc::StreamPrimitive(ostream &out) const
+{
+    out << "   MHillasCalc " << GetUniqueName() << "(";
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (TestFlags(kCalcHillasExt|kCalcNewImagePar|kCalcConc|kCalcHillasSrc))
+    {
+        if (fNameHillas!=gsNameHillas)
+            out << "   " << GetUniqueName() << ".SetNameHillas(\"" << fNameHillas << "\");" << endl;
+    }
+    if (TestFlag(kCalcHillasSrc) && fNameHillasSrc!=gsNameHillasSrc)
+    {
+        out << "   " << GetUniqueName() << ".SetNameHillasSrc(\"" << fNameHillasSrc << "\");" << endl;
+        out << "   " << GetUniqueName() << ".SetNameSrcPosCam(\"" << fNameSrcPosCam << "\");" << endl;
+    }
+    if (TestFlag(kCalcHillasExt) && fNameHillasExt!=gsNameHillasExt)
+        out << "   " << GetUniqueName() << ".SetNameHillasExt(\"" << fNameHillasExt << "\");" << endl;
+    if (TestFlag(kCalcConc) && fNameConc!=gsNameConc)
+        out << "   " << GetUniqueName() << ".SetNameConc(\"" << fNameConc << "\");" << endl;
+    if (TestFlag(kCalcImagePar) && fNameImagePar!=gsNameImagePar)
+        out << "   " << GetUniqueName() << ".SetNameImagePar(\"" << fNameImagePar << "\");" << endl;
+    if (TestFlag(kCalcNewImagePar) && fNameNewImagePar!=gsNameNewImagePar)
+        out << "   " << GetUniqueName() << ".SetNameNewImagePar(\"" << fNameNewImagePar << "\");" << endl;
+    if (TestFlag(kCalcNewImagePar2) && fNameNewImagePar2!=gsNameNewImagePar2)
+        out << "   " << GetUniqueName() << ".SetNameNewImagePar2(\"" << fNameNewImagePar2 << "\");" << endl;
+
+    if (!TestFlag(kCalcHillas))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcHillas);" << endl;
+    if (!TestFlag(kCalcHillasExt))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcHillasExt);" << endl;
+    if (!TestFlag(kCalcHillasSrc))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcHillasSrc);" << endl;
+    if (!TestFlag(kCalcNewImagePar))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcNewImagePar);" << endl;
+    if (!TestFlag(kCalcNewImagePar2))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcNewImagePar2);" << endl;
+    if (!TestFlag(kCalcConc))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcConc);" << endl;
+    if (!TestFlag(kCalcImagePar))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcImagePar);" << endl;
+
+    if (fIdxIsland>=0)
+        out << "   " << GetUniqueName() << ".SetNumIsland(" << fIdxIsland << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MHillasCalc.IdxIsland: -1
+//
+Int_t MHillasCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "IdxIsland", print))
+    {
+        rc = kTRUE;
+        SetIdxIsland(GetEnvValue(env, prefix, "IdxIsland", fIdxIsland));
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mimage/MHillasCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillasCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillasCalc.h	(revision 17960)
@@ -0,0 +1,121 @@
+#ifndef MARS_MHillasCalc
+#define MARS_MHillasCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MHillasCalkc                                                            //
+//                                                                         //
+// Task to calculate Hillas Parameters                                     //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MGeomCam;
+class MSignalCam;
+class MHillas;
+class MHillasExt;
+class MHillasSrc;
+class MImagePar;
+class MNewImagePar;
+class MNewImagePar2;
+class MConcentration;
+class MSrcPosCam;
+
+class MHillasCalc : public MTask
+{
+    static const TString gsDefName;         // default name
+    static const TString gsDefTitle;        // default title
+
+    static const TString gsNameHillas;      // default name of the 'MHillas' container
+    static const TString gsNameHillasExt;   // default name of the 'MHillasExt' container
+    static const TString gsNameNewImagePar; // default name of the 'MNewImagePar' container
+    static const TString gsNameNewImagePar2; // default name of the 'MNewImagePar' container
+    static const TString gsNameConc;        // default name of the 'MConcentration' container
+    static const TString gsNameImagePar;    // default name of the 'MImagePar' container
+    static const TString gsNameHillasSrc;   // default name of the 'MHillasSrc' container
+    static const TString gsNameSrcPosCam;   // default name of the 'MSrcPosCam' container
+
+    const MGeomCam      *fGeomCam;          //! Camera Geometry used to calculate Hillas
+    const MSignalCam    *fCerPhotEvt;       //! Cerenkov Photon Event used for calculation
+
+    MHillas             *fHillas;           //! output container to store result
+    MHillasExt          *fHillasExt;        //! output container to store result
+    MHillasSrc          *fHillasSrc;        //! output container to store result
+    MImagePar           *fImagePar;         //! output container to store result
+    MNewImagePar        *fNewImgPar;        //! output container to store result
+    MNewImagePar2       *fNewImgPar2;       //! output container to store result
+    MConcentration      *fConc;             //! output container to store result
+
+    TString              fNameHillas;       // name of the 'MHillas' container
+    TString              fNameHillasExt;    // name of the 'MHillasExt' container
+    TString              fNameHillasSrc;    // name of the 'MHillasSrc' container
+    TString              fNameSrcPosCam;    // name of the 'MSrcPosCam' container
+    TString              fNameConc;         // name of the 'MConcentration' container
+    TString              fNameImagePar;     // name of the 'MImagePar' container
+    TString              fNameNewImagePar;  // name of the 'MNewImagePar' container
+    TString              fNameNewImagePar2; // name of the 'MNewImagePar' container
+
+    TArrayL              fErrors;           //! Error counter. Do we have to change to Double?
+
+    Int_t                fFlags;            // Flags defining the behaviour of MHillasCalc
+    Short_t              fIdxIsland;        // Number of island to use for calculation
+
+    // MParContainer
+    void StreamPrimitive(std::ostream &out) const;
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    // Constructor
+    MHillasCalc(const char *name=NULL, const char *title=NULL);
+
+    // Flags
+    enum CalcCont_t {
+        kCalcHillas       = BIT(0),
+        kCalcHillasExt    = BIT(1),
+        kCalcHillasSrc    = BIT(2),
+        kCalcNewImagePar  = BIT(3),
+        kCalcNewImagePar2 = BIT(4),
+        kCalcConc         = BIT(5),
+        kCalcImagePar     = BIT(6)
+    };
+
+    // Setup flags
+    void SetFlags(Int_t f) { fFlags  =  f; }
+    void Enable(Int_t f)   { fFlags |=  f; }
+    void Disable(Int_t f)  { fFlags &= ~f; }
+
+    Bool_t TestFlag(CalcCont_t i) const { return fFlags&i; }
+    Bool_t TestFlags(Int_t i) const     { return fFlags&i; }
+
+    // Setup container names
+    void SetNameHillas(const char *name)      { fNameHillas      = name; }
+    void SetNameHillasExt(const char *name)   { fNameHillasExt   = name; }
+    void SetNameHillasSrc(const char *name)   { fNameHillasSrc   = name; }
+    void SetNameNewImagePar(const char *name) { fNameNewImagePar = name; }
+    void SetNameNewImagePar2(const char *name){ fNameNewImagePar2 = name; }
+    void SetNameConc(const char *name)        { fNameConc        = name; }
+    void SetNameImagePar(const char *name)    { fNameImagePar    = name; }
+    void SetNameSrcPosCam(const char *name)   { fNameSrcPosCam   = name; }
+
+    // Setup island number
+    void SetIdxIsland(Short_t idx) { fIdxIsland = idx; }
+
+    // TObject
+    void Print(Option_t *o="") const;
+
+    ClassDef(MHillasCalc, 0) // Task to calculate Hillas and other image parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHillasExt.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillasExt.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillasExt.cc	(revision 17960)
@@ -0,0 +1,411 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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
+//
+// Version 4:
+// ----------
+// fMaxDist      removed.
+// fSlopeLong    added
+// fSlopeTrans   added
+//
+// Version 5:
+// ----------
+// fTimeSpread           added
+// fTimeSpreadWeighted   added
+//
+// fSlopeSpread          added
+// fSlopeSpreadWeighted  added
+//
+//
+// WARNING: Before you can use fAsym, fSlope* and fM3* you must
+//          multiply by the sign of MHillasSrc::fCosDeltaAlpha
+//
+////////////////////////////////////////////////////////////////////////////
+/*
+ // fAsymna   d/(d na) of ( sum(x*q^na)/sum(q^na), sum(y*q^na)/sum(q^na) )
+ //           projected onto the major axis
+ // fAsym0    (F-B)/(F+B) along the major axis
+ */
+#include "MHillasExt.h"
+
+#include <TArrayF.h>
+#include <TMarker.h>
+#include <TVector2.h>
+#include <TMinuit.h>
+#include <TVirtualPad.h>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+
+ClassImp(MHillasExt);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasExt::MHillasExt(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHillasExt";
+    fTitle = title ? title : "Storage container for extended parameter set of one event";
+
+    Reset();
+}
+
+// -------------------------------------------------------------------------
+//
+// Reset all values to 0
+//
+void MHillasExt::Reset()
+{
+    fAsym       =  0;
+    fM3Long     =  0;
+    fM3Trans    =  0;
+    fSlopeLong  =  0;
+    fSlopeTrans =  0;
+
+    fTimeSpread          = -1;
+    fTimeSpreadWeighted  = -1;
+    fSlopeSpread         = -1;
+    fSlopeSpreadWeighted = -1;
+}
+
+// -------------------------------------------------------------------------
+//
+// calculation of additional parameters based on the camera geometry
+// and the cerenkov photon event
+//
+Int_t MHillasExt::Calc(const MGeomCam &geom, const MSignalCam &evt, const MHillas &hil, Int_t island)
+{
+    //
+    //   calculate the additional image parameters
+    // --------------------------------------------
+    //
+    //  loop to get third moments along ellipse axes and two max pixels
+    //
+    //  For the moments double precision is used to make sure, that
+    //  the complex matrix multiplication and sum is evaluated correctly.
+    //
+    Int_t maxpixid  = 0;
+    Float_t maxpix  = 0;
+
+    // Variables to caluclate time slope
+    // Formula: http://mo.mathematik.uni-stuttgart.de/inhalt/erlaeuterung/erlaeuterung300/
+    UInt_t cnt = 0;
+
+    Double_t sumx      = 0;
+    Double_t sumy      = 0;
+    Double_t sumt      = 0;
+    Double_t sumw      = 0;
+
+    Double_t sumxt     = 0;
+    Double_t sumyt     = 0;
+
+    Double_t sumx2     = 0;
+    Double_t sumy2     = 0;
+    Double_t sumxy     = 0;
+    Double_t sumt2     = 0;
+
+    Double_t sumxw     = 0;
+    Double_t sumyw     = 0;
+    Double_t sumtw     = 0;
+
+    Double_t sumx2w    = 0;
+    Double_t sumy2w    = 0;
+    Double_t sumt2w    = 0;
+    Double_t sumxyw    = 0;
+    Double_t sumxtw    = 0;
+    Double_t sumytw    = 0;
+
+    Double_t sumdx3w   = 0;
+    Double_t sumdy3w   = 0;
+
+    Double_t sumdx2dyw = 0;
+    Double_t sumdxdy2w = 0;
+
+    const UInt_t npix = evt.GetNumPixels();
+    for (UInt_t i=0; i<npix; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        const MGeom &gpix = geom[i];
+
+        const Double_t x = gpix.GetX();
+        const Double_t y = gpix.GetY();
+        const Double_t t = pix.GetArrivalTime();
+
+        Double_t nphot = pix.GetNumPhotons();        // [1]
+
+        // --- time slope ----
+        sumx    += x;
+        sumy    += y;
+        sumt    += t;
+        sumw    += nphot;
+
+        sumxt   += x*t;
+        sumyt   += y*t;
+
+        sumx2   += x*x;
+        sumy2   += y*y;
+        sumxy   += x*y;
+        sumt2   += t*t;
+
+        sumxw   += x*nphot;
+        sumyw   += y*nphot;
+        sumtw   += t*nphot;
+
+        sumx2w  += x*x*nphot;
+        sumy2w  += y*y*nphot;
+        sumt2w  += t*t*nphot;
+
+        sumxyw  += x*y*nphot;
+
+        sumxtw  += x*t*nphot;
+        sumytw  += y*t*nphot;
+
+        // --- 3rd moment ---
+        const Double_t dx = x - hil.GetMeanX();      // [mm]
+        const Double_t dy = y - hil.GetMeanY();      // [mm]
+
+        sumdx3w   += dx*dx*dx*nphot;
+        sumdy3w   += dy*dy*dy*nphot;
+        sumdx2dyw += dx*dx*dy*nphot;
+        sumdxdy2w += dx*dy*dy*nphot;
+
+        cnt++;
+
+        //
+        // Now we are working on absolute values of nphot, which
+        // must take pixel size into account
+        //
+        nphot *= geom.GetPixRatio(i);
+
+        // --- max pixel ---
+        if (nphot>maxpix)
+        {
+            maxpix   = nphot;                        // [1]
+            maxpixid = i;
+        }
+    }
+
+    const Double_t c = hil.GetCosDelta();
+    const Double_t s = hil.GetSinDelta();
+
+    //
+    // Time slope
+    //
+    const Double_t dxt  =  c*sumxt + s*sumyt;
+    const Double_t dyt  = -s*sumxt + c*sumyt;
+
+    const Double_t dx   =  c*sumx  + s*sumy;
+    const Double_t dy   = -s*sumx  + c*sumy;
+
+    const Double_t dx2  =  c*c*sumx2 + 2*c*s*sumxy + s*s*sumy2;
+    const Double_t dy2  =  s*s*sumx2 - 2*c*s*sumxy + c*c*sumy2;
+
+    const Double_t detx =  cnt*dx2 - dx*dx;
+    const Double_t dety =  cnt*dy2 - dy*dy;
+
+    fSlopeLong  = detx==0 ? 0 : (cnt*dxt - sumt*dx)/detx;
+    fSlopeTrans = dety==0 ? 0 : (cnt*dyt - sumt*dy)/dety;
+
+    //
+    // Time spread
+    //
+    const Double_t m = fSlopeLong;
+
+    const Double_t z        = dx; //c*sumx   + s*sumy;
+    const Double_t zw       =       c*sumxw  + s*sumyw;
+
+    const Double_t zt       = dxt; //c*sumxt  + s*sumyt;
+    const Double_t ztw      =        c*sumxtw + s*sumytw;
+
+    const Double_t x2y2     = dx2; //c*c*sumx2  + s*s*sumy2  + 2*c*s*sumxy;
+    const Double_t x2y2w    =        c*c*sumx2w + s*s*sumy2w + 2*c*s*sumxyw;
+
+    const Double_t sumdt    = sumt  - m*z;
+    const Double_t sumdtw   = sumtw - m*zw;
+
+    const Double_t sumdt2   = sumt2  + m*m*x2y2  - 2*m*zt;
+    const Double_t sumdt2w  = sumt2w + m*m*x2y2w - 2*m*ztw;
+
+    const Double_t meant    = sumt  /cnt;
+    const Double_t meandt   = sumdt /cnt;
+    const Double_t meantw   = sumtw /sumw;
+    const Double_t meandtw  = sumdtw/sumw;
+
+    fTimeSpread          = TMath::Sqrt(sumt2 /cnt  - meant *meant);
+    fTimeSpreadWeighted  = TMath::Sqrt(sumt2w/sumw - meantw*meantw);
+
+    fSlopeSpread         = TMath::Sqrt(sumdt2 /cnt  - meandt *meandt);
+    fSlopeSpreadWeighted = TMath::Sqrt(sumdt2w/sumw - meandtw*meandtw);
+
+    //
+    // Third moments along axes get normalized
+    //
+    const Double_t m3l = c*c*c*sumdx3w + s*s*s*sumdy3w + 3*(s*c*c*sumdx2dyw + c*s*s*sumdxdy2w);
+    const Double_t m3t = c*c*c*sumdy3w - s*s*s*sumdx3w + 3*(s*s*c*sumdx2dyw - s*c*c*sumdxdy2w);
+
+    fM3Long  = MMath::Sqrt3(m3l/sumw);      // [mm]
+    fM3Trans = MMath::Sqrt3(m3t/sumw);      // [mm]
+
+    //
+    // Asymmetry
+    //
+    const MGeom &maxp = geom[maxpixid];
+    fAsym = (hil.GetMeanX()-maxp.GetX())*c + (hil.GetMeanY()-maxp.GetY())*s;            // [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() != 9)
+        return;
+
+    fAsym       = arr.At(0);
+    fM3Long     = arr.At(1);
+    fM3Trans    = arr.At(2);
+    fSlopeLong  = arr.At(3);
+    fSlopeTrans = arr.At(4);
+
+    fTimeSpread          = arr.At(5);
+    fTimeSpreadWeighted  = arr.At(6);
+    fSlopeSpread         = arr.At(7);
+    fSlopeSpreadWeighted = arr.At(8);
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MHillasExt to *fLog.
+//
+void MHillasExt::Print(Option_t *o) const
+{
+    const Bool_t showtrans = TString(o).Contains("trans");
+
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Asymmetry      [mm]  = " << fAsym    << endl;
+    *fLog << " - 3.Moment Long  [mm]  = " << fM3Long  << endl;
+    if (showtrans)
+        *fLog << " - 3.Moment Trans [mm]  = " << fM3Trans << endl;
+    *fLog << " - Slope Long     [mm]  = " << fSlopeLong  << endl;
+    if (showtrans)
+        *fLog << " - Slope Trans    [mm]  = " << fSlopeTrans << endl;
+    *fLog << " - Time Spread    [ns]  = " << fTimeSpread << endl;
+    *fLog << " - Slope Spread   [ns]  = " << fSlopeSpread << endl;
+    *fLog << " - Time Spread W  [ns]  = " << fTimeSpreadWeighted << endl;
+    *fLog << " - Slope Spread W [ns]  = " << fSlopeSpreadWeighted << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MHillasExt to *fLog, depending on the geometry in
+// units of deg.
+//
+void MHillasExt::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Asymmetry      [deg] = " << fAsym   *geom.GetConvMm2Deg() << endl;
+    *fLog << " - 3.Moment Long  [deg] = " << fM3Long *geom.GetConvMm2Deg() << endl;
+    *fLog << " - 3.Moment Trans [mm]  = " << fM3Trans*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Slope Long     [mm]  = " << fSlopeLong*geom.GetConvMm2Deg()  << endl;
+    *fLog << " - Slope Trans    [mm]  = " << fSlopeTrans*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Slope Spread   [ns]  = " << fSlopeSpread << endl;
+    *fLog << " - Time Spread W  [ns]  = " << fTimeSpreadWeighted << endl;
+    *fLog << " - Slope Spread W [ns]  = " << fSlopeSpreadWeighted << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+// Paint the 3rd moment on top of the shower. Therefor "MHillas" is needed.
+// it is searched via gPad->FindObject. If opt is not IsNull an object with
+// the name opt is searched.
+//
+void MHillasExt::Paint(Option_t *opt)
+{
+    const TString name(opt);
+
+    const MHillas *hil = dynamic_cast<const MHillas*>(gPad->FindObject(name.IsNull() ? "MHillas" : name.Data()));
+    if (!hil)
+        return;
+
+    TVector2 v(fM3Long, fM3Trans);
+    v  = v.Rotate(hil->GetDelta()+TMath::Pi());
+    v += hil->GetMean();
+
+    TMarker m;
+    m.SetMarkerColor(kRed);
+    m.SetMarkerStyle(kFullDotLarge);
+    m.PaintMarker(v.X(), v.Y());
+}
Index: branches/Mars_McMismatchStudy/mimage/MHillasExt.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillasExt.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillasExt.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHillasExt
+#define MARS_MHillasExt
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayF;
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MHillasExt : public MParContainer
+{
+private:
+    // for description see MExtHillas.cc
+    Float_t fAsym;    // [mm] fDist minus dist: center of ellipse, highest pixel
+    Float_t fM3Long;  // [mm] 3rd moment (e-weighted) along major axis
+    Float_t fM3Trans; // [mm] 3rd moment (e-weighted) along minor axis
+
+    Float_t fSlopeLong;   // [ns/mm] Slope of the arrival time along the major axis
+    Float_t fSlopeTrans;  // [ns/mm] Slope of the arrival time along the minor axis
+
+    // FIXME: We could try to use the Medians!
+    Float_t fTimeSpread;          // [ns] Spread (RMS) of the arrival times around the mean arrival time
+    Float_t fTimeSpreadWeighted;  // [ns] Weighted spread (RMS) of the arrival times around the weighted mean arrival time
+
+    Float_t fSlopeSpread;         // [ns] Spread (RMS) of the arrival time around the slope along the major axis
+    Float_t fSlopeSpreadWeighted; // [ns] Weighted spread (RMS) of the arrival time around the slope along the major axis
+
+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 GetSlopeLong() const           { return fSlopeLong; }
+    Float_t GetSlopeTrans() const          { return fSlopeTrans; }
+    Float_t GetTimeSpread() const          { return fTimeSpread; }
+    Float_t GetTimeSpreadWeighted() const  { return fTimeSpreadWeighted; }
+    Float_t GetSlopeSpread() const         { return fSlopeSpread; }
+    Float_t GetSlopeSpreadWeighted() const { return fSlopeSpreadWeighted; }
+
+    Int_t Calc(const MGeomCam &geom, const MSignalCam &pix,
+               const MHillas &hil, Int_t island=-1);
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    void Paint(Option_t *o="");
+
+    void Set(const TArrayF &arr);
+
+    ClassDef(MHillasExt, 5) // Storage Container for extended Hillas Parameter
+};
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MHillasSrc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillasSrc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillasSrc.cc	(revision 17960)
@@ -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    12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!   Author(s): Wolfgang Wittek 06/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHillasSrc
+//
+// Storage Container for image parameters
+//
+//    source-dependent image parameters
+//
+//
+// Version 1:
+// ----------
+//  fAlpha          angle between major axis and line source-to-center
+//  fDist           distance from source to center of ellipse
+//
+//
+// Version 2:
+// ----------
+//  fHeadTail       added
+//
+//
+// Version 3:
+// ----------
+//  fCosDeltaAlpha  cosine of angle between d and a, where
+//                   - d is the vector from the source position to the
+//                     center of the ellipse
+//                   - a is a vector along the main axis of the ellipse,
+//                     defined with positive x-component
+//
+//
+// Version 4:
+// ----------
+// fHeadTail        removed
+//
+//
+// Version 5:
+// ----------
+//  - added Float_t fDCA;      // [mm]   Distance to closest approach 'DCA'
+//  - added Float_t fDCADelta; // [deg]  Angle of the shower axis with respect
+//                                       to the x-axis [0,2pi]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillasSrc.h"
+
+#include <TArrayF.h>
+
+#include <TLine.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MHillas.h"
+#include "MSrcPosCam.h"
+
+ClassImp(MHillasSrc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasSrc::MHillasSrc(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHillasSrc";
+    fTitle = title ? title : "Parameters depending in source position";
+}
+
+void MHillasSrc::Reset()
+{
+    fDist          = -1;
+    fAlpha         =  0;
+    fCosDeltaAlpha =  0;
+
+    fDCA           = -1;
+    fDCADelta      =  0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of source-dependent parameters
+//  In case you don't call Calc from within an eventloop make sure, that
+//  you call the Reset member function before.
+//
+Int_t MHillasSrc::Calc(const MHillas &hillas)
+{
+     const Double_t mx = hillas.GetMeanX();     // [mm]
+     const Double_t my = hillas.GetMeanY();     // [mm]
+
+     const Double_t sx = mx - fSrcPos->GetX();   // [mm]
+     const Double_t sy = my - fSrcPos->GetY();   // [mm]
+
+     const Double_t sd = hillas.GetSinDelta();  // [1]
+     const Double_t cd = hillas.GetCosDelta();  // [1]
+
+     //
+     // Distance from source position to center of ellipse.
+     // If the distance is 0 distance, Alpha is not specified.
+     // The calculation has failed and returnes kFALSE.
+     //
+     const Double_t dist = TMath::Sqrt(sx*sx + sy*sy);  // [mm]
+     if (dist==0)
+         return 1;
+
+     //
+     // Calculate Alpha and Cosda = cos(d,a)
+     // The sign of Cosda will be used for quantities containing
+     // a head-tail information
+     //
+     // *OLD* const Double_t arg = (sy-tand*sx) / (dist*sqrt(tand*tand+1));
+     // *OLD* fAlpha = asin(arg)*kRad2Deg;
+     //
+     const Double_t arg2 = cd*sx + sd*sy;          // [mm]
+     if (arg2==0)
+         return 2;
+
+     const Double_t arg1 = cd*sy - sd*sx;          // [mm]
+
+     //
+     // Due to numerical uncertanties in the calculation of the
+     // square root (dist) and arg1 it can happen (in less than 1e-5 cases)
+     // that the absolute value of arg exceeds 1. Because this uncertainty
+     // results in an Delta Alpha which is still less than 1e-3 we don't care
+     // about this uncertainty in general and simply set values which exceed
+     // to 1 saving its sign.
+     //
+     const Double_t arg = arg1/dist;
+     fAlpha = TMath::Abs(arg)>1 ? TMath::Sign(90., arg) : TMath::ASin(arg)*TMath::RadToDeg(); // [deg]
+
+     fCosDeltaAlpha = arg2/dist;                 // [1]
+     fDist          = dist;                      // [mm]
+
+     // ----- Calculation of Distance to closest approach 'DCA' -----
+
+     // Components of DCA vector
+     const Double_t fpd1 = sx - arg2*cd;         // [mm]
+     const Double_t fpd2 = sy - arg2*sd;         // [mm]
+
+     // Determine the correct sign of the DCA (cross product of DCA vector and the
+     // vector going from the intersection point of the DCA vector with the shower axis
+     // to the COG)
+     const Double_t sign = arg2*cd*fpd2 - arg2*sd*fpd1;
+     fDCA  = TMath::Sign(TMath::Sqrt(fpd1*fpd1 + fpd2*fpd2), sign); // [mm]
+
+     // Calculate angle of the shower axis with respect to the x-axis
+     fDCADelta = TMath::ACos((sx-fpd1)/TMath::Abs(arg2))*TMath::RadToDeg(); // [deg]
+
+     // Enlarge the interval of fDdca to [0, 2pi]
+     if (sy < fpd2)
+         fDCADelta = 360 - fDCADelta;
+
+     SetReadyToSave();
+
+     return 0;
+}
+
+void MHillasSrc::Paint(Option_t *opt)
+{
+    const Float_t x = fSrcPos ? fSrcPos->GetX() : 0;
+    const Float_t y = fSrcPos ? fSrcPos->GetY() : 0;
+
+    TMarker m;
+    m.SetMarkerColor(kYellow);
+    m.SetMarkerStyle(kStar);
+    m.PaintMarker(x, y);
+/*
+    m.SetMarkerColor(kMagenta);
+    m.PaintMarker(fDist*cos((fDCADelta-fAlpha)*TMath::DegToRad()),
+                  fDist*sin((fDCADelta-fAlpha)*TMath::DegToRad()));
+
+    TLine line;
+    line.SetLineWidth(1);
+    line.SetLineColor(108);
+
+    line.PaintLine(-radius, y, radius, y);
+    line.PaintLine(x, -radius, x, radius);
+  
+    // COG line
+    TLine line(x, y, meanX, meanY);
+    line.SetLineWidth(1);
+    line.SetLineColor(2);
+    line.Paint();*/
+}
+
+// --------------------------------------------------------------------------
+//
+// Print contents of MHillasSrc to *fLog
+//
+void MHillasSrc::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Dist           [mm]  = " << fDist << endl;
+    *fLog << " - Alpha          [deg] = " << fAlpha << endl;
+    *fLog << " - CosDeltaAlpha        = " << fCosDeltaAlpha << endl;
+    *fLog << " - DCA            [mm]  = " << fDCA << endl;
+    *fLog << " - DCA delta      [deg] = " << fDCADelta << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print contents of MHillasSrc to *fLog depending on the geometry in
+// units of deg.
+//
+void MHillasSrc::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Dist           [deg] = " << fDist*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Alpha          [deg] = " << fAlpha << endl;
+    *fLog << " - CosDeltaAlpha        = " << fCosDeltaAlpha << endl;
+    *fLog << " - DCA            [deg] = " << fDCA*geom.GetConvMm2Deg() << endl;
+    *fLog << " - DCA delta      [deg] = " << fDCADelta << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function is ment for special usage, please never try to set
+// values via this function
+//
+void MHillasSrc::Set(const TArrayF &arr)
+{
+    if (arr.GetSize() != 5)
+        return;
+
+    fAlpha = arr.At(0);         // [deg]  angle of major axis with vector to src
+    fDist  = arr.At(1);         // [mm]   distance between src and center of ellipse
+    fCosDeltaAlpha = arr.At(2); // [1]    cosine of angle between d and a
+    fDCA = arr.At(3);           // [mm]
+    fDCADelta = arr.At(4);      // [mm]
+}
Index: branches/Mars_McMismatchStudy/mimage/MHillasSrc.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MHillasSrc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MHillasSrc.h	(revision 17960)
@@ -0,0 +1,63 @@
+#ifndef MARS_MHillasSrc
+#define MARS_MHillasSrc
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayF;
+
+class MHillas;
+class MGeomCam;
+class MSrcPosCam;
+
+class MHillasSrc : public MParContainer
+{
+private:
+    const MSrcPosCam *fSrcPos; //! Source position in the camere
+
+    Float_t fAlpha;         // [deg]  angle of major axis with vector to src
+    Float_t fDist;          // [mm]   distance between src and center of ellipse
+    Float_t fCosDeltaAlpha; // [1]    cosine of angle between d and a
+
+    Float_t fDCA;           // [mm]   Distance to closest approach 'DCA'
+    Float_t fDCADelta;      // [deg]  Angle of the shower axis with respect to the x-axis
+
+public:
+    MHillasSrc(const char *name=NULL, const char *title=NULL);
+    MHillasSrc(const MHillasSrc &h) { h.Copy(*this); }
+
+    void Copy(TObject &o) const
+    {
+        MHillasSrc &src = static_cast<MHillasSrc&>(o);
+        src.fSrcPos = fSrcPos;
+        src.fAlpha  = fAlpha;
+        src.fDist   = fDist;
+        src.fCosDeltaAlpha = fCosDeltaAlpha;
+        src.fDCA = fDCA;
+        src.fDCADelta = fDCADelta;
+    }
+
+    void SetSrcPos(const MSrcPosCam *pos) { fSrcPos = pos; }
+    const MSrcPosCam *GetSrcPos() const   { return fSrcPos; }
+
+    void Reset();
+
+    Float_t GetAlpha()         const { return fAlpha; }
+    Float_t GetDist()          const { return fDist; }
+    Float_t GetCosDeltaAlpha() const { return fCosDeltaAlpha; }
+    Float_t GetDCA()           const { return fDCA; }
+    Float_t GetDCADelta()      const { return fDCADelta; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+    void Paint(Option_t *opt=NULL);
+
+    virtual Int_t Calc(const MHillas &hillas);
+
+    void Set(const TArrayF &arr);
+
+    ClassDef(MHillasSrc, 5) // Container to hold source position dependant parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MImagePar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImagePar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImagePar.cc	(revision 17960)
@@ -0,0 +1,116 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MImagePar
+//
+// Storage Container for new image parameters
+//
+//  Class Version 2:
+//  ----------------
+//    - added Short_t fNumSinglePixels;
+//    - added Float_t fSizeSinglePixels;
+//    - added Float_t fSizeSubIslands;
+//
+//  Class Version 1:
+//  ----------------
+//    Short_t fNumIslands;           // number of islands found
+//
+//    Short_t fNumHGSaturatedPixels; // number of pixels with saturating hi-gains
+//    Short_t fNumSaturatedPixels;   // number of pixels with saturating lo-gains
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImagePar.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MSignalCam.h"
+
+ClassImp(MImagePar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MImagePar::MImagePar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MImagePar";
+    fTitle = title ? title : "New image parameters";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MImagePar::Reset()
+{
+    fNumIslands       = -1;
+    fNumSinglePixels  = -1;
+
+    fNumSatPixelsHG   = -1;
+    fNumSatPixelsLG   = -1;
+
+    fSizeSinglePixels = -1;
+    fSizeSubIslands   = -1;
+    fSizeMainIsland   = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of new image parameters
+//
+void MImagePar::Calc(const MSignalCam &evt)
+{
+    // Get number of saturating pixels
+    fNumSatPixelsHG   = evt.GetNumPixelsSaturatedHiGain();
+    fNumSatPixelsLG   = evt.GetNumPixelsSaturatedLoGain();
+
+    // Get number of islands
+    fNumIslands       = evt.GetNumIslands();
+    fNumSinglePixels  = evt.GetNumSinglePixels();
+    fSizeSinglePixels = evt.GetSizeSinglePixels();
+    fSizeSubIslands   = evt.GetSizeSubIslands();
+    fSizeMainIsland   = evt.GetSizeMainIsland();
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+void MImagePar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Num Islands      [#] = " << fNumIslands       << " Islands" << endl;
+    *fLog << " - Sat.Pixels (HG)  [#] = " << fNumSatPixelsHG   << " Pixels" << endl;
+    *fLog << " - Sat.Pixels (LG)  [#] = " << fNumSatPixelsLG   << " Pixels" << endl;
+    *fLog << " - No rmvd CorePx   [#] = " << fNumSinglePixels  << " Pixels" << endl;
+    *fLog << " - Sz rmvd CorePx [phe] = " << fSizeSinglePixels << endl;
+    *fLog << " - Sz Sub Islands [phe] = " << fSizeSubIslands   << endl;
+    *fLog << " - Sz Main Island [phe] = " << fSizeMainIsland   << endl;
+}
Index: branches/Mars_McMismatchStudy/mimage/MImagePar.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImagePar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImagePar.h	(revision 17960)
@@ -0,0 +1,46 @@
+#ifndef MARS_MImagePar
+#define MARS_MImagePar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MImagePar : public MParContainer
+{
+private:
+    Short_t fNumIslands;     // Number of islands found
+    Short_t fNumSinglePixels;
+
+    Float_t fSizeSinglePixels;
+    Float_t fSizeSubIslands;
+    Float_t fSizeMainIsland;
+
+    Short_t fNumSatPixelsHG; // number of pixels with saturating hi-gains
+    Short_t fNumSatPixelsLG; // number of pixels with saturating lo-gains
+
+public:
+    MImagePar(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Short_t GetNumIslands() const { return fNumIslands; }
+
+    Short_t GetNumSatPixelsHG() const   { return fNumSatPixelsHG; }
+    Short_t GetNumSatPixelsLG() const   { return fNumSatPixelsLG; }
+    Short_t GetNumSinglePixels() const  { return fNumSinglePixels; }
+    Float_t GetSizeSinglePixels() const { return fSizeSinglePixels; }
+    Float_t GetSizeSubIslands() const   { return fSizeSubIslands; }
+    Float_t GetSizeMainIsland() const   { return fSizeMainIsland; }
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Calc(const MSignalCam &evt);
+
+    ClassDef(MImagePar, 2) // Container to hold (geometry and island independant) image parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MImgCleanSimple.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanSimple.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanSimple.cc	(revision 17960)
@@ -0,0 +1,411 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2012 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MImgCleanSimple
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImgCleanSimple.h"
+
+#include <TEnv.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+ClassImp(MImgCleanSimple);
+
+using namespace std;
+
+static const TString gsDefName  = "MImgCleanSimple";
+static const TString gsDefTitle = "Task to perform image cleaning";
+
+const TString MImgCleanSimple::gsNameSignalCam ="MSignalCam";  // default name of the 'MSignalCam' container
+const TString MImgCleanSimple::gsNameGeomCam   ="MGeomCam";    // default name of the 'MGeomCam' container
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Here you can specify the cleaning method and levels. 
+// If you don't specify them the 'common standard' values 3.0 and 2.5 (sigma
+// above mean) are used.
+// Here you can also specify how many rings around the core pixels you want 
+// to analyze (with the fixed lvl2). The default value for "rings" is 1.
+//
+MImgCleanSimple::MImgCleanSimple(const Float_t lvl1, const Float_t lvl2,
+                                 const char *name, const char *title) : fCleaningMethod(kStandard),
+    fCleanLvl1(lvl1), fCleanLvl2(-1), fTimeLvl1(lvl2), fTimeLvl2(-1),
+    fNameGeomCam(gsNameGeomCam), fNameSignalCam(gsNameSignalCam)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+void MImgCleanSimple::ResetCleaning() const
+{
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    //
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        pix.SetPixelUnused();
+        pix.SetPixelCore(kFALSE);
+    }
+}
+
+void MImgCleanSimple::DoCleanStd() const
+{
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // Check if this is above the cleaning level
+        if (pix.GetNumPhotons() <= fCleanLvl1)
+            continue;
+
+        // Ignore unmapped pixels
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        const MGeom &gpix = (*fCam)[idx];
+
+        const Int_t n = gpix.GetNumNeighbors();
+        for (Int_t i=0; i<n; i++)
+        {
+            const MSignalPix &npix = (*fEvt)[gpix.GetNeighbor(i)];
+
+            // Check if one neighbor pixel is also above the cleaning level
+            if (npix.GetNumPhotons() <= fCleanLvl1)
+                continue;
+
+            // Check if both pixels are within the given time window
+            if (TMath::Abs(npix.GetArrivalTime()-pix.GetArrivalTime())>=fTimeLvl1)
+                continue;
+
+            // Ignore unmapped pixels
+            if (npix.IsPixelUnmapped())
+                continue;
+
+            // The pixel is now marked to survive the cleaning. It's neighbor will
+            // be marked later, because the condition is symmetric and the neighbor
+            // will fullfil the condition, too.
+            pix.SetPixelUsed();
+            pix.SetPixelCore();
+
+            break;
+        }
+    }
+}
+
+void MImgCleanSimple::DoCleanSum2() const
+{
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // Ignore unmapped pixels
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        const MGeom &gpix = (*fCam)[idx];
+
+        const Int_t n = gpix.GetNumNeighbors();
+        for (Int_t i=0; i<n; i++)
+        {
+            const MSignalPix &npix = (*fEvt)[gpix.GetNeighbor(i)];
+
+            // Check if the sum (or average) charge of the two neighbors is below threshold
+            if (pix.GetNumPhotons()+npix.GetNumPhotons()<=fCleanLvl1*2)
+                continue;
+
+            // Check if both pixels are within the given time window
+            if (TMath::Abs(npix.GetArrivalTime()-pix.GetArrivalTime())>=fTimeLvl1)
+                continue;
+
+            // Ignore unmapped pixels
+            if (npix.IsPixelUnmapped())
+                continue;
+
+            // The pixel is now marked to survive the cleaning. It's neighbor will
+            // be marked later, because the condition is symmetric and the neighbor
+            // will fullfil the condition, too.
+            pix.SetPixelUsed();
+            pix.SetPixelCore();
+            break;
+        }
+    }
+}
+
+void MImgCleanSimple::DoCleanSum3() const
+{
+    const Double_t clvl = fCleanLvl2>0 ? fCleanLvl2*3 : fCleanLvl1*3;
+    const Double_t tlvl = fTimeLvl2>0  ? fTimeLvl2    : fTimeLvl1;
+
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // Ignore unmapped pixels
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        const MGeom &gpix = (*fCam)[idx];
+
+        const Int_t n = gpix.GetNumNeighbors();
+        for (Int_t i=0; i<n; i++)
+        {
+            const MSignalPix &npix1 = (*fEvt)[gpix.GetNeighbor(i)];
+            const MSignalPix &npix2 = (*fEvt)[gpix.GetNeighbor((i+1)%n)];
+
+            // Check if the sum (or average) charge of the three neighbors (closed package)
+            // is below threshold
+            if (pix.GetNumPhotons()+npix1.GetNumPhotons()+npix2.GetNumPhotons()<=clvl)
+                continue;
+
+            // Check if all thre pixels fullfil the time window condition
+            if (TMath::Abs(pix.GetArrivalTime()-npix1.GetArrivalTime())>=tlvl)
+                continue;
+            if (TMath::Abs(npix1.GetArrivalTime()-npix2.GetArrivalTime())>=tlvl)
+                continue;
+            if (TMath::Abs(npix2.GetArrivalTime()-pix.GetArrivalTime())>=tlvl)
+                continue;
+
+            // Ignore unmapped pixels
+            if (npix1.IsPixelUnmapped() || npix2.IsPixelUnmapped())
+                continue;
+
+            // The pixel is now marked to survive the cleaning. It's neighbors will
+            // be marked later, because the condition is symmetric and the neighbors
+            // will fullfil the condition, too.
+            pix.SetPixelUsed();
+            pix.SetPixelCore();
+            break;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if MEvtHeader exists in the Parameter list already.
+//  if not create one and add them to the list
+//
+Int_t MImgCleanSimple::PreProcess(MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber(fNameGeomCam), "MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << fNameGeomCam << " [MGeomCam] not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+    fEvt = (MSignalCam*)pList->FindObject(AddSerialNumber(fNameSignalCam), "MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << fNameSignalCam << " [MSignalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    Print();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cleans the image.
+//
+Int_t MImgCleanSimple::Process()
+{
+    ResetCleaning();
+
+    switch (fCleaningMethod)
+    {
+    case kStandard:
+        DoCleanStd();   // Check each of the neighbors charge individually
+        break;
+    case kSum2:
+        DoCleanSum2();  // Check the sum of two neighbors
+    case kSum3:
+        DoCleanSum2();  // Check the sum of two   neighbors
+        DoCleanSum3();  // Check the sum of three neighbors
+        break;
+    }
+
+    // Takes roughly 10% of the time
+    fEvt->CalcIslands(*fCam);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print descriptor and cleaning levels.
+//
+void MImgCleanSimple::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << " using ";
+    switch (fCleaningMethod)
+    {
+    case kStandard:
+        *fLog << "standard";
+        break;
+    case kSum2:
+        *fLog << "sum2";
+        break;
+    case kSum3:
+        *fLog << "sum3";
+        break;
+
+    }
+    /*
+    *fLog << " cleaning" << endl;
+    *fLog << "initialized with level " << fCleanLvl1 << " and " << fCleanLvl2;
+    *fLog << " (CleanRings=" << fCleanRings << ")" << endl;
+
+    if (fPostCleanType)
+    {
+        *fLog << "Time post cleaning is switched on with:" << endl;
+        if (fPostCleanType&2)
+            *fLog << " - Two pixel coincidence window: " << fTimeLvl2 << "ns" << endl;
+        if (fPostCleanType&1)
+            *fLog << " - One pixel coincidence window: " << fTimeLvl1 << "ns" << 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 MImgCleanSimple::StreamPrimitive(ostream &out) const
+{
+    out << "   MImgCleanSimple " << GetUniqueName() << "(";
+    out << fCleanLvl1 << ", " << fCleanLvl2;
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (fCleaningMethod!=kStandard)
+    {
+        out << "   " << GetUniqueName() << ".SetMethod(MImgCleanSimple::k";
+        switch (fCleaningMethod)
+        {
+        case kScaled:      out << "Scaled";      break;
+        case kDemocratic:  out << "Democratic";  break;
+        case kProbability: out << "Probability"; break;
+        case kAbsolute:    out << "Absolute";    break;
+        case kTime    :    out << "Time";        break;
+        default:
+            break;
+        }
+        out << ");" << endl;
+    }
+    if (fCleanRings!=1)
+        out << "   " << GetUniqueName() << ".SetCleanRings(" << fCleanRings << ");" << endl;
+
+    if (gsNamePedPhotCam!=fNamePedPhotCam)
+        out << "   " << GetUniqueName() << ".SetNamePedPhotCam(\"" << fNamePedPhotCam << "\");" << endl;
+    if (gsNameGeomCam!=fNameGeomCam)
+        out << "   " << GetUniqueName() << ".SetNameGeomCam(\"" << fNameGeomCam << "\");" << endl;
+    if (gsNameSignalCam!=fNameSignalCam)
+        out << "   " << GetUniqueName() << ".SetNameSignalCam(\"" << fNameSignalCam << "\");" << endl;
+    if (fKeepIsolatedPixels)
+        out << "   " << GetUniqueName() << ".SetKeepIsolatedPixels();" << endl;
+    if (fRecoverIsolatedPixels)
+        out << "   " << GetUniqueName() << ".SetRecoverIsolatedPixels(" << fRecoverIsolatedPixels << ");" << endl;
+
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MImgCleanSimple.CleanLevel1: 3.0
+//   MImgCleanSimple.CleanLevel2: 2.5
+//   MImgCleanSimple.CleanMethod: Standard, Scaled, Democratic, Probability, Absolute
+//   MImgCleanSimple.CleanRings:  1
+//   MImgCleanSimple.KeepIsolatedPixels: yes, no
+//
+Int_t MImgCleanSimple::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "CleanLevel1", print))
+    {
+        rc = kTRUE;
+        fCleanLvl1 = GetEnvValue(env, prefix, "CleanLevel1", fCleanLvl1);
+    }
+    if (IsEnvDefined(env, prefix, "CleanLevel2", print))
+    {
+        rc = kTRUE;
+        fCleanLvl2 = GetEnvValue(env, prefix, "CleanLevel2", fCleanLvl2);
+    }
+    if (IsEnvDefined(env, prefix, "TimeLevel1", print))
+    {
+        rc = kTRUE;
+        fTimeLvl1 = GetEnvValue(env, prefix, "TimeLevel1", fTimeLvl1);
+    }
+    if (IsEnvDefined(env, prefix, "TimeLevel2", print))
+    {
+        rc = kTRUE;
+        fTimeLvl2 = GetEnvValue(env, prefix, "TimeLevel2", fTimeLvl2);
+    }
+
+    if (IsEnvDefined(env, prefix, "CleanMethod", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "CleanMethod", "");
+        s.ToLower();
+        if (s.BeginsWith("standard"))
+            SetMethod(kStandard);
+        if (s.BeginsWith("sum2"))
+            SetMethod(kSum2);
+        if (s.BeginsWith("sum3"))
+            SetMethod(kSum3);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mimage/MImgCleanSimple.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanSimple.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanSimple.h	(revision 17960)
@@ -0,0 +1,77 @@
+#ifndef MARS_MImgCleanSimple
+#define MARS_MImgCleanSimple
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MGeom;
+class MSignalCam;
+class MArrivalTime;
+
+class MImgCleanSimple : public MTask
+{
+public:
+    typedef enum {
+        kStandard,
+        kSum2,
+        kSum3,
+    } CleaningMethod_t;
+
+private:
+    static const TString gsNameGeomCam;    // default name of the 'MGeomCam' container
+    static const TString gsNameSignalCam;  // default name of the 'MSignalCam' container
+
+    const MGeomCam   *fCam;  //!
+          MSignalCam *fEvt;  //!
+
+    CleaningMethod_t fCleaningMethod;
+
+    Float_t  fCleanLvl1;
+    Float_t  fCleanLvl2;
+
+    Float_t  fTimeLvl1;
+    Float_t  fTimeLvl2;
+
+    TString  fNameGeomCam;    // name of the 'MGeomCam' container
+    TString  fNameSignalCam;  // name of the 'MSignalCam' container
+
+    // MImgCleanSimple
+    void ResetCleaning() const;
+    void DoCleanStd() const;
+    void DoCleanSum2() const;
+    void DoCleanSum3() const;
+
+    // MGTask, MTask, MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+    //void  StreamPrimitive(ostream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MImgCleanSimple(const Float_t lvl1=2.0, const Float_t lvl2=1.75,
+                 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; }
+    Float_t GetTimeLvl1() const  { return fTimeLvl1; }
+    Float_t GetTimeLvl2() const  { return fTimeLvl2; }
+
+    void SetCleanLvl1(Float_t lvl) { fCleanLvl1=lvl; }
+    void SetCleanLvl2(Float_t lvl) { fCleanLvl2=lvl; }
+    void SetTimeLvl1(Float_t lvl)  { fTimeLvl1=lvl; }
+    void SetTimeLvl2(Float_t lvl)  { fTimeLvl2=lvl; }
+
+    void SetMethod(CleaningMethod_t m) { fCleaningMethod = m; }
+
+    void SetNameSignalCam(const char *name)   { fNameSignalCam = name; }
+    void SetNameGeomCam(const char *name)     { fNameGeomCam = name; }
+
+    ClassDef(MImgCleanSimple, 1)    // task doing the image cleaning
+}; 
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MImgCleanStd.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanStd.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanStd.cc	(revision 17960)
@@ -0,0 +1,1168 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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>
+!   Author(s): Stefan Ruegamer, 03/2006 <mailto:snruegam@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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 eventually switched off
+// (Unmap: set blind pixels to UNUSED) separately, using the
+// MBlindPixelCalc Class. In the MBlindPixelCalc class there is also the
+// function to replace the value of the noisy pixels with the interpolation
+// of the content of the neighbors (SetUseInterpolation).
+//
+// Example:
+// ...
+// MBlindPixelCalc blind;
+// blind.SetUseInterpolation();
+// blind.SetUseBlindPixels();
+//
+// MImgCleanStd clean;
+// ...
+// tlist.AddToList(&blind);
+// tlist.AddToList(&clean);
+//
+// Look at the MBlindPixelCalc Class for more details.
+//
+// Starting point: default values ----------------------------------------
+//
+// When an event is read, before the image cleaning, all the pixels that
+// are in MSignalCam are set as USED and NOT CORE. All the pixels belong
+// to RING number 1 (like USED pixels).
+// Look at MSignalPix.h to see how these informations of the pixel are
+// stored.
+// The default  cleaning METHOD is the STANDARD one and the number of the
+// rings around the CORE pixel it analyzes is 1. Look at the Constructor
+// of the class in MImgCleanStd.cc to see (or change) the default values.
+//
+// Example: To modify this setting, use the member functions
+// SetMethod(MImgCleanStd::kDemocratic) and SetCleanRings(UShort_t n).
+//
+// MImgCleanStd:CleanStep1 -----------------------------------------------
+//
+// The first step of cleaning defines the CORE pixels. The CORE pixels are
+// the ones which contain the informations about the core of the electro-
+// magnetic shower.
+// The ratio  (A_0/A_i) is calculated from fCam->GetPixRatio(i). A_0 is
+// the area of the central pixel of the camera, A_i is the area of the
+// examined pixel. In this way, if we have a MAGIC-like camera, with the
+// outer pixels bigger than the inner ones, the level of cleaning in the
+// two different regions is weighted.
+// This avoids problems of deformations of the shower images.
+// The signal S_i and the pedestal RMS Prms_i of the pixel are called from
+// the object MSignalPix.
+// If (default method = kStandard)
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f1.png">
+//End_Html
+// the pixel is set as CORE pixel. L_1 (n=1) is called "first level of
+// cleaning" (default: fCleanLvl1 = 3).
+// All the other pixels are set as UNUSED and belong to RING 0.
+// After this point, only the CORE pixels are set as USED, with RING
+// number 1.
+//
+// MImgCleanStd:CleanStep2 ----------------------------------------------
+//
+// The second step of cleaning looks at the isolated CORE pixels and sets
+// them to UNUSED. An isolated pixel is a pixel without CORE neighbors.
+// At the end of this point, we have set as USED only CORE pixels with at
+// least one CORE neighbor.
+//
+// MImgCleanStd:CleanStep3  ----------------------------------------------
+//
+// The third step of cleaning looks at all the pixels (USED or UNUSED) that
+// surround the USED pixels.
+// If the content of the analyzed pixel survives at the second level of
+// cleaning, i.e. if
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f1.png">
+//End_Html
+// the pixel is set as USED. L_2 (n=2) is called "second level of cleaning"
+// (default:fCleanLvl2 = 2.5).
+//
+// When the number of RINGS to analyze is 1 (default value), only the
+// pixels that have a neighbor CORE pixel are analyzed.
+//
+// There is the option to decide the number of times you want to repeat
+// this procedure (number of RINGS analyzed around the core pixels = n).
+// Every time the level of cleaning is the same (fCleanLvl2) and the pixel
+// will belong to ring r+1, 1 < r < n+1. This is described in
+// MImgCleanStd:CleanStep4 .
+//
+// Dictionary and member functions ---------------------------------------
+//
+// Here there is the detailed description of the member functions and of
+// the terms commonly used in the class.
+//
+//
+// STANDARD CLEANING:
+// =================
+// This is the method used for the CT1 data analysis. It is the default
+// method of the class.
+// The number of photo-electrons of a pixel (S_i) is compared to the
+// pedestal RMS of the pixel itself (Prms_i). To have the comparison to
+// the same photon density for all the pixels, taking into account they
+// can have different areas, we have to keep in mind that the number of
+// photons that hit each pixel, goes linearly with the area of the pixel.
+// The fluctuations of the LONS are proportional to sqrt(A_i), so when we
+// compare S_i with Prms_i, only a factor  sqrt(A_0/A_i) is missing to
+// have the same (N.photons/Area) threshold for all the pixels.
+//
+//              !!WARNING: if noise independent from the
+//         pixel size (example: electronic noise) is introduced,
+//         then the noise fluctuations are no longer proportional
+//         to sqrt(A_i), and then the cut value (for a camera with
+//         pixels of different sizes) resulting from the above
+//         procedure  would not be proportional to pixel size as we 
+//         intend. In that case, democratic cleaning is preferred.
+//
+// If
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f1.png">
+//End_Html
+// the pixel survives the cleaning and it is set as CORE (when L_n is the
+// first level of cleaning, fCleanLvl1) or USED (when L_n is the second
+// level of cleaning, fCleanLvl2).
+//
+// Example:
+//
+// MImgCleanStd clean;
+// //creates a default Cleaning object, with default setting
+// ...
+// tlist.AddToList(&clean);
+// // add the image cleaning to the main task list
+//
+//
+// DEMOCRATIC CLEANING:
+// ===================
+// You use this cleaning method when you want to compare the number of
+// photo-electrons of each pixel with the average pedestal RMS of the
+// inner pixels (for the MAGIC camera they are the smaller ones):
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f2.png">
+//End_Html
+// In this case, the simple ratio (A_0/A_i) is used to weight the level of
+// cleaning, because both the inner and the outer pixels (that in MAGIC
+// have a different area) are compared to the same pedestal RMS, coming
+// from the inner pixels.
+//
+// Make sure that you used a class calculating the MPedPhotCam which also
+// updated the contents of the mean values (Recalc) correctly.
+//
+//
+// PROBABILITY CLEANING
+// ====================
+// This method takes signal height (over signal noise) and arrival time
+// into account. Instead of comparing signal/Noise with cleaning level
+// one and two, we calculate
+//  - P_ped: The probability that a signal is a pedestal (using
+//           the signal height and the pedestal) For this probability the
+//           same algorithm like in kScaled is used (which is a standard
+//           cleaning which scales the noise with the mean noise of pixels
+//           with the same size)
+//  - P_sig: The probability that the signal corresponds to the pixel
+//           with the highest signal. For this probability we use the
+//           arrival time only.
+//
+// The cleaning now is done in levels of Probability (eg. 0.2, 0.05)
+// The meaning of the cleaning levels is essentially the same (the same cleaning
+// algorithm is used) but the cleaning is not done in levels of signal/noise
+// but in level of this probability.
+//
+// This probability is calculated as (1-P_ped)*P_sig
+//
+// Example:
+//
+// MImgCleanStd clean(0.2, 0.05);
+// clean.SetMethod(MImgCleanStd::kProbability);
+//
+//
+// ABSOLUTE CLEANING
+// =================
+// This method takes signal height (photons) times area ratio
+// ad the cleaning levels.
+//
+// The cleaning now is done in these levels (eg. 16, 20)
+// The meaning of the cleaning levels is essentially the same (the same cleaning
+// algorithm is used) but the cleaning is not done in different 'units'
+//
+// Example:
+//
+// MImgCleanStd clean(20, 16);
+// clean.SetMethod(MImgCleanStd::kAbsolulte);
+//
+//
+// Member Function:  SetMethod()
+// ============================
+// When you call the MImgCleanStd task, the default method is kStandard.
+//
+// If you want to switch to the kDemocratic method you have to
+// call this member function.
+//
+// Example:
+//
+// MImgCleanStd clean;
+// //creates a default Cleaning object, with default setting
+//
+// clean.SetMethod(MImgCleanStd::kDemocratic);
+// //now the method of cleaning is changed to Democratic
+//
+//
+// FIRST AND SECOND CLEANING LEVEL
+// ===============================
+// When you call the MImgCleanStd task, the default cleaning levels are
+// fCleanLvl1 = 3, fCleanLvl2 = 2.5. You can change them easily when you
+// create the MImgCleanStd object.
+//
+// Example:
+//
+// MImgCleanStd clean(Float_t lvl1,Float_t lvl2);
+// //creates a default cleaning object, but the cleaning levels are now
+// //lvl1 and lvl2.
+//
+// RING NUMBER
+// ===========
+// The standard cleaning procedure is such that it looks for the
+// informations of the boundary part of the shower only on the first
+// neighbors of the CORE pixels.
+// There is the possibility now to look not only at the first 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.
+//
+//
+//  Class Version 4:
+//  ----------------
+//   + Float_t  fTimeLvl2;
+//   - Bool_t   fKeepSinglePixels;
+//   + Bool_t   fKeepIsolatedPixels;
+//   + Int_t    fRecoverIsolatedPixels;
+//
+//
+//  Input Containers:
+//   MGeomCam
+//   MPedPhotCam
+//   MSignalCam
+//
+//  Output Containers:
+//   MSignalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImgCleanStd.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include <TEnv.h>
+
+#include <TGFrame.h>      // TGFrame
+#include <TGLabel.h>      // TGLabel
+#include <TGTextEntry.h>  // TGTextEntry
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayI.h"
+#include "MParList.h"
+#include "MCameraData.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MGGroupFrame.h" // MGGroupFrame
+
+ClassImp(MImgCleanStd);
+
+using namespace std;
+
+enum {
+    kImgCleanLvl1,
+    kImgCleanLvl2
+};
+
+static const TString gsDefName  = "MImgCleanStd";
+static const TString gsDefTitle = "Task to perform image cleaning";
+
+const TString MImgCleanStd::gsNamePedPhotCam="MPedPhotCam"; // default name of the 'MPedPhotCam' container
+const TString MImgCleanStd::gsNameSignalCam ="MSignalCam"; // default name of the 'MSignalCam' container
+const TString MImgCleanStd::gsNameGeomCam   ="MGeomCam";    // default name of the 'MGeomCam' container
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Here you can specify the cleaning method and levels. 
+// If you don't specify them the 'common standard' values 3.0 and 2.5 (sigma
+// above mean) are used.
+// Here you can also specify how many rings around the core pixels you want 
+// to analyze (with the fixed lvl2). The default value for "rings" is 1.
+//
+MImgCleanStd::MImgCleanStd(const Float_t lvl1, const Float_t lvl2,
+                           const char *name, const char *title)
+    : fCleaningMethod(kStandard), fCleanLvl0(lvl1), fCleanLvl1(lvl1),
+    fCleanLvl2(lvl2), fTimeLvl1(1.5), fTimeLvl2(1.5), fCleanRings(1),
+    fKeepIsolatedPixels(kFALSE), fRecoverIsolatedPixels(0),
+    fPostCleanType(0), fNamePedPhotCam(gsNamePedPhotCam),
+    fNameGeomCam(gsNameGeomCam), fNameSignalCam(gsNameSignalCam)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+void MImgCleanStd::ResetCleaning() const
+{
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    //
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        pix.SetPixelUnused();
+        pix.SetPixelCore(kFALSE);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+//
+//
+Bool_t MImgCleanStd::HasCoreNeighbors(const MGeom &gpix) const
+{
+//    if (fKeepIsolatedPixels)
+//        return kTRUE;
+
+#ifdef DEBUG
+    const TArrayD &data = fData->GetData();
+#else
+    const Double_t *data = fData->GetData().GetArray();
+#endif
+
+    //loop on the neighbors to check if they are used
+    const Int_t n = gpix.GetNumNeighbors();
+    for (Int_t i=0; i<n; i++)
+    {
+        const Int_t idx = gpix.GetNeighbor(i);
+
+        // Check if a neighborpixel of our core pixel is
+        // also a core pixel
+        if (data[idx]<=fCleanLvl1)
+            continue;
+
+        // Ignore unmapped pixels
+        MSignalPix &pix = (*fEvt)[idx];
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        return kTRUE;
+    }
+
+    return kFALSE;
+}
+
+Bool_t MImgCleanStd::HasUsedNeighbors(const MGeom &gpix) const
+{
+    //loop on the neighbors to check if they are used
+    const Int_t n = gpix.GetNumNeighbors();
+    for (Int_t i=0; i<n; i++)
+    {
+        const Int_t idx = gpix.GetNeighbor(i);
+
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // Check if a neighborpixel of our core pixel is
+        // also a core pixel
+        if (pix.IsPixelUsed() && !pix.IsPixelUnmapped())
+            return kTRUE;
+    }
+
+    return kFALSE;
+}
+
+
+void MImgCleanStd::SetUsedNeighbors(const MGeom &gpix, Int_t r) const
+{
+    if (r>fCleanRings)
+        return;
+
+#ifdef DEBUG
+    const TArrayD &data = fData->GetData();
+#else
+    const Double_t *data = fData->GetData().GetArray();
+#endif
+
+    // At least one neighbor has been identified as core,
+    // that means we will keep the pixel
+    const Int_t n = gpix.GetNumNeighbors();
+    for (Int_t i=0; i<n; i++)
+    {
+        const Int_t idx = gpix.GetNeighbor(i);
+
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // If the pixel has been assigned to the same or a previous
+        // ring we don't have to proceed. We have to try to set the
+        // ring number of each pixel as low as possible. This means
+        // we are only allowed to increase the ring number.
+        if (pix.IsPixelUsed() && pix.GetRing()<=r)
+            continue;
+
+        // All pixels below the second cleaning level should be ignored
+        if (data[idx] <= fCleanLvl2)
+            continue;
+
+        // Ignore unmapped pixels (remark: used (aka. ring>0)
+        // and unmapped status is exclusive
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        // Set or reset the ring number
+        pix.SetRing(r);
+
+        // Step forward to the surrounding pixels
+        SetUsedNeighbors((*fCam)[idx], r+1);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Here we do the cleaning. We search for all the possible core candidates
+// and from them on we recursively search for used pixels with
+// SetUsedNeighbors. To check the validity of a core pixel
+// either fTimeLvl2 and/or HasCoreNeighbors is used.
+// The size of all removed
+Int_t MImgCleanStd::DoCleaning(Float_t &size) const
+{
+    Int_t n = 0;
+    size = 0;
+
+#ifdef DEBUG
+    const TArrayD &data = fData->GetData();
+#else
+    const Double_t *data = fData->GetData().GetArray();
+#endif
+
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    //
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // Check if this pixel is a possible candidate for a core pixel
+        if (data[idx] <= fCleanLvl1)
+            continue;
+
+        // Ignore unmapped pixels
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        const MGeom &gpix = (*fCam)[idx];
+
+        // Check if the pixel is an isolated core pixel
+        if (!HasCoreNeighbors(gpix))
+        {
+            // Count size and number of isolated core pixels
+            size += pix.GetNumPhotons();
+            n++;
+
+            // If isolated pixels should not be kept or the pixel
+            // is lower than the cleaning level for isolated core
+            // pixels. It is not treated as core pixel.
+            if (!fKeepIsolatedPixels || data[idx]<=fCleanLvl0)
+                continue;
+        }
+
+        // Mark pixel as used and core
+        pix.SetPixelUsed();
+        pix.SetPixelCore();
+
+        // Check if neighbor pixels should be marked as used
+        // This is done recursively depening on fCleanRings
+        SetUsedNeighbors(gpix);
+    }
+
+    return n;
+}
+
+/*
+Float_t MImgCleanStd::GetArrivalTimeNeighbor(const MGeom &gpix) const
+{
+    Float_t min = FLT_MAX;
+
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+    {
+        const Int_t idx = gpix.GetNeighbor(i);
+
+        const MSignalPix &pix = (*fEvt)[idx];
+        // FIXME: Check also used pixels?
+        if (!pix.IsCorePixel())
+            continue;
+
+        const Float_t tm = pix.GetArrivalTime();
+        if (tm<min)
+            min = tm;
+    }
+
+    return tm;
+}
+
+void MImgCleanStd::CheckUsedPixelsForArrivalTime(Float_t timediff) const
+{
+    const MArrayD &data = fData->GetData();
+
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    //
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // If pixel has previously been marked used, ignore
+        if (!pix.IsPixelUsed() || pix.IsPixelCore())
+            continue;
+
+        const MGeom &gpix = (*fCam)[idx];
+
+        // If isolated possible-corepixel doesn't have used
+        // neighbors, ignore it
+        const Float_t tm0 = pix.GetArrivalTime();
+        const Float_t tm1 = GetArrivalTimeCoreNeighbor(gpix);
+
+        if (TMath::Abs(tm0-tm1)<timediff)
+            continue;
+
+        // Mark pixel as used and core
+        pix.SetPixelUnused();
+    }
+}
+*/
+
+Int_t MImgCleanStd::RecoverIsolatedPixels(Float_t &size) const
+{
+#ifdef DEBUG
+    const TArrayD &data = fData->GetData();
+#else
+    const Double_t *data = fData->GetData().GetArray();
+#endif
+
+    Int_t n = 0;
+
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    //
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+
+        // If pixel has previously been marked used, ignore
+        if (pix.IsPixelUsed())
+            continue;
+
+        // If pixel is not a candidate for a core pixel, ignore
+        if (data[idx] <= fCleanLvl1)
+            continue;
+
+        const MGeom &gpix = (*fCam)[idx];
+
+        // If isolated possible-corepixel doesn't have used
+        // neighbors, ignore it
+        if (!HasUsedNeighbors(gpix))
+            continue;
+
+        // Mark pixel as used and core
+        pix.SetPixelUsed();
+        pix.SetPixelCore();
+
+        // Check if neighbor pixels should be marked as used
+        // This is done recursively depening on fCleanRings
+        SetUsedNeighbors(gpix);
+
+        size -= pix.GetNumPhotons();
+        n++;
+    }
+
+    return n;
+}
+
+void MImgCleanStd::CleanTime(Int_t n, Double_t lvl) const
+{
+    MArrayI indices;
+
+    // Add conversion factor for dx here
+    const Double_t dtmax = lvl*fCam->GetConvMm2Deg();
+
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        // check if pixel is used or not
+        const MSignalPix &pix = (*fEvt)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // get arrival time
+        const Double_t tm0 = pix.GetArrivalTime();
+
+        // loop over its neighbpors
+        const MGeom &gpix = (*fCam)[idx];
+
+        Int_t cnt = 0;
+        for (Int_t i=0; i<gpix.GetNumNeighbors(); i++)
+        {
+            // Get index of neighbor
+            const Int_t idx2 = gpix.GetNeighbor(i);
+
+            // check if neighbor is used or not
+            const MSignalPix &npix = (*fEvt)[idx2];
+            if (!npix.IsPixelUsed())
+                continue;
+
+            const Double_t dt = TMath::Abs(npix.GetArrivalTime()-tm0);
+            const Double_t dx = gpix.GetDist((*fCam)[idx2]);
+
+            // If this pixel is to far away (in arrival time) don't count
+            if (dt>dtmax*dx)
+                continue;
+
+            // Now count the pixel. If we did not found n pixels yet
+            // which fullfill the condition, go on searching
+            if (++cnt>=n)
+                break;
+        }
+
+        // If we found at least n neighbors which are
+        // with a time difference of lvl keep the pixel
+        if (cnt>=n)
+            continue;
+
+        indices.Set(indices.GetSize()+1);
+        indices[indices.GetSize()-1] = idx;
+    }
+
+    // Now remove the pixels which didn't fullfill the requirement
+    for (UInt_t i=0; i<indices.GetSize(); i++)
+    {
+        (*fEvt)[indices[i]].SetPixelUnused();
+        (*fEvt)[indices[i]].SetPixelCore(kFALSE);
+    }
+}
+
+void MImgCleanStd::CleanStepTime() const
+{
+    if (fPostCleanType<=0)
+        return;
+
+    if (fPostCleanType&2)
+        CleanTime(2, fTimeLvl2);
+
+    if (fPostCleanType&1)
+        CleanTime(1, fTimeLvl1);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if MEvtHeader exists in the Parameter list already.
+//  if not create one and add them to the list
+//
+Int_t MImgCleanStd::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber(fNameGeomCam), "MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << fNameGeomCam << " [MGeomCam] not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+    fEvt = (MSignalCam*)pList->FindObject(AddSerialNumber(fNameSignalCam), "MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << fNameSignalCam << " [MSignalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed=0;
+    if (fCleaningMethod!=kAbsolute && fCleaningMethod!=kTime)
+    {
+        fPed = (MPedPhotCam*)pList->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+        if (!fPed)
+        {
+            *fLog << err << fNamePedPhotCam << " [MPedPhotCam] not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fData = (MCameraData*)pList->FindCreateObj(AddSerialNumber("MCameraData"));
+    if (!fData)
+        return kFALSE;
+
+    if (fCleanLvl2>fCleanLvl1)
+    {
+        *fLog << warn << "WARNING - fCleanLvl2 (" << fCleanLvl2 << ") > fCleanLvl1 (" << fCleanLvl1 << ")... resetting fCleanLvl2." << endl;
+        fCleanLvl2 = fCleanLvl1;
+    }
+
+    if (fCleanLvl2==fCleanLvl1 && fCleanRings>0)
+    {
+        *fLog << warn << "WARNING - fCleanLvl2 == fCleanLvl1 (" << fCleanLvl1 << ") but fCleanRings>0... resetting fCleanRings to 0." << endl;
+        fCleanRings=0;
+    }
+
+    if (fKeepIsolatedPixels && fCleanLvl0<fCleanLvl1)
+    {
+        *fLog << warn << "WARNING - fKeepIsolatedPixels set but CleanLvl0 (" << fTimeLvl2 << ") < fCleanLvl1 (" << fCleanLvl1 << ")... resetting fTimeLvl2." << endl;
+        fTimeLvl2 = fCleanLvl1;
+    }
+    if (!fKeepIsolatedPixels && fCleanLvl0>fCleanLvl1)
+    {
+        *fLog << warn << "WARNING - fKeepIsolatedPixels not set but CleanLvl0 (" << fTimeLvl2 << ") > fCleanLvl1 (" << fCleanLvl1 << ")... setting fKeepIsolatedCorePixels." << endl;
+        fKeepIsolatedPixels=kTRUE;
+    }
+
+    if (fKeepIsolatedPixels && fTimeLvl2==fCleanLvl1 && fRecoverIsolatedPixels!=0)
+    {
+        *fLog << warn << "WARNING - fTimeLvl2 == fCleanLvl1 (" << fTimeLvl2 << ") and fKeepSinglePixels and fRecoverIsolatedPixels!=0... setting fRecoverIsolatedPixels=0." << endl;
+        fRecoverIsolatedPixels = 0;
+    }
+
+    Print();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cleans the image.
+//
+Int_t MImgCleanStd::Process()
+{
+    switch (fCleaningMethod)
+    {
+    case kStandard:
+        fData->CalcCleaningLevel(*fEvt, *fPed, *fCam);
+        break;
+    case kScaled:
+        fData->CalcCleaningLevel2(*fEvt, *fPed, *fCam);
+        break;
+    case kDemocratic:
+        fData->CalcCleaningLevelDemocratic(*fEvt, *fPed, *fCam);
+        break;
+    case kProbability:
+        fData->CalcCleaningProbability(*fEvt, *fPed, *fCam);
+        break;
+    case kAbsolute:
+        fData->CalcCleaningAbsolute(*fEvt, *fCam);
+        break;
+    case kTime:
+        fData->CalcCleaningArrivalTime(*fEvt, *fCam);
+        break;
+    default:
+        break;
+    }
+
+#ifdef DEBUG
+    *fLog << all << "ResetCleaning" << endl;
+#endif
+    ResetCleaning();
+
+#ifdef DEBUG
+    *fLog << all << "DoCleaning" << endl;
+#endif
+    Float_t size;
+    Short_t n = DoCleaning(size);
+
+#ifdef DEBUG
+    *fLog << all << "RecoverIsolatedPixels" << endl;
+#endif
+    for (UInt_t i=0; i<(UInt_t)fRecoverIsolatedPixels; i++)
+    {
+        const Int_t rc=RecoverIsolatedPixels(size);
+        if (rc==0)
+            break;
+
+        n -= rc;
+    }
+
+#ifdef DEBUG
+    *fLog << all << "Time Cleaning" << endl;
+#endif
+    // FIXME: Remove removed core piselx?
+    CleanStepTime();
+
+    fEvt->SetSinglePixels(n, size);
+
+#ifdef DEBUG
+    *fLog << all << "CalcIslands" << endl;
+#endif
+    // Takes roughly 10% of the time
+    fEvt->CalcIslands(*fCam);
+
+#ifdef DEBUG
+    *fLog << all << "Done." << endl;
+#endif
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print descriptor and cleaning levels.
+//
+void MImgCleanStd::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << " using ";
+    switch (fCleaningMethod)
+    {
+    case kDemocratic:
+        *fLog << "democratic";
+        break;
+    case kStandard:
+        *fLog << "standard";
+        break;
+    case kScaled:
+        *fLog << "scaled";
+        break;
+    case kProbability:
+        *fLog << "probability";
+        break;
+    case kAbsolute:
+        *fLog << "absolute";
+        break;
+    case kTime:
+        *fLog << "time";
+        break;
+
+    }
+    *fLog << " cleaning" << endl;
+    *fLog << "initialized with level " << fCleanLvl1 << " and " << fCleanLvl2;
+    *fLog << " (CleanRings=" << fCleanRings << ")" << endl;
+
+    if (fPostCleanType)
+    {
+        *fLog << "Time post cleaning is switched on with:" << endl;
+        if (fPostCleanType&2)
+            *fLog << " - Two pixel coincidence window: " << fTimeLvl2 << "ns" << endl;
+        if (fPostCleanType&1)
+            *fLog << " - One pixel coincidence window: " << fTimeLvl1 << "ns" << endl;
+    }
+
+    if (fKeepIsolatedPixels)
+        *fLog << "isolated core pixels will be kept above " << fCleanLvl0 << endl;
+
+    if (fRecoverIsolatedPixels)
+    {
+        if (fRecoverIsolatedPixels<0)
+            *fLog << "all ";
+        *fLog << "isolated core pixels with used pixels as neighbors will be recovered";
+        if (fRecoverIsolatedPixels>0)
+            *fLog << " " << fRecoverIsolatedPixels << " times";
+        *fLog << "." << endl;;
+    }
+
+    if (fCleaningMethod!=kAbsolute && fCleaningMethod!=kTime)
+    {
+        *fLog << "Name of MPedPhotCam container used: ";
+        *fLog << (fPed?((MParContainer*)fPed)->GetName():(const char*)fNamePedPhotCam) << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Create two text entry fields, one for each cleaning level and a
+//  describing text line.
+//
+void MImgCleanStd::CreateGuiElements(MGGroupFrame *f)
+{
+    //
+    // Create a frame for line 3 and 4 to be able
+    // to align entry field and label in one line
+    //
+    TGHorizontalFrame *f1 = new TGHorizontalFrame(f, 0, 0);
+    TGHorizontalFrame *f2 = new TGHorizontalFrame(f, 0, 0);
+    
+    /*
+     * --> use with root >=3.02 <--
+     *
+     
+     TGNumberEntry *fNumEntry1 = new TGNumberEntry(frame, 3.0, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+     TGNumberEntry *fNumEntry2 = new TGNumberEntry(frame, 2.5, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+  
+    */
+    TGTextEntry *entry1 = new TGTextEntry(f1, "****", kImgCleanLvl1);
+    TGTextEntry *entry2 = new TGTextEntry(f2, "****", kImgCleanLvl2);
+    
+    // --- doesn't work like expected (until root 3.02?) --- fNumEntry1->SetAlignment(kTextRight);
+    // --- doesn't work like expected (until root 3.02?) --- fNumEntry2->SetAlignment(kTextRight);
+    
+    entry1->SetText("3.0");
+    entry2->SetText("2.5");
+    
+    entry1->Associate(f);
+    entry2->Associate(f);
+    
+    TGLabel *l1 = new TGLabel(f1, "Cleaning Level 1");
+    TGLabel *l2 = new TGLabel(f2, "Cleaning Level 2");
+    
+    l1->SetTextJustify(kTextLeft);
+    l2->SetTextJustify(kTextLeft);
+    
+    //
+    // Align the text of the label centered, left in the row
+    // with a left padding of 10
+    //
+    TGLayoutHints *laylabel = new TGLayoutHints(kLHintsCenterY|kLHintsLeft, 10);
+    TGLayoutHints *layframe = new TGLayoutHints(kLHintsCenterY|kLHintsLeft,  5, 0, 10);
+    
+    //
+    // Add one entry field and the corresponding label to each line
+    //
+    f1->AddFrame(entry1);
+    f2->AddFrame(entry2);
+    
+    f1->AddFrame(l1, laylabel);
+    f2->AddFrame(l2, laylabel);
+    
+    f->AddFrame(f1, layframe);
+    f->AddFrame(f2, layframe);
+    
+    f->AddToList(entry1);
+    f->AddToList(entry2);
+    f->AddToList(l1);
+    f->AddToList(l2);
+    f->AddToList(laylabel);
+    f->AddToList(layframe);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process the GUI Events coming from the two text entry fields.
+//
+Bool_t MImgCleanStd::ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2)
+{
+    if (msg!=kC_TEXTENTRY || submsg!=kTE_ENTER)
+        return kTRUE;
+
+    TGTextEntry *txt = (TGTextEntry*)FindWidget(param1);
+
+    if (!txt)
+        return kTRUE;
+
+    Float_t lvl = atof(txt->GetText());
+
+    switch (param1)
+    {
+    case kImgCleanLvl1:
+        fCleanLvl1 = lvl;
+        *fLog << "Cleaning level 1 set to " << lvl << endl;
+        return kTRUE;
+
+    case kImgCleanLvl2:
+        fCleanLvl2 = lvl;
+        *fLog << "Cleaning level 2 set to " << lvl << endl;
+        return kTRUE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MImgCleanStd::StreamPrimitive(ostream &out) const
+{
+    out << "   MImgCleanStd " << GetUniqueName() << "(";
+    out << fCleanLvl1 << ", " << fCleanLvl2;
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (fCleaningMethod!=kStandard)
+    {
+        out << "   " << GetUniqueName() << ".SetMethod(MImgCleanStd::k";
+        switch (fCleaningMethod)
+        {
+        case kScaled:      out << "Scaled";      break;
+        case kDemocratic:  out << "Democratic";  break;
+        case kProbability: out << "Probability"; break;
+        case kAbsolute:    out << "Absolute";    break;
+        case kTime    :    out << "Time";        break;
+        default:
+            break;
+        }
+        out << ");" << endl;
+    }
+    if (fCleanRings!=1)
+        out << "   " << GetUniqueName() << ".SetCleanRings(" << fCleanRings << ");" << endl;
+
+    if (gsNamePedPhotCam!=fNamePedPhotCam)
+        out << "   " << GetUniqueName() << ".SetNamePedPhotCam(\"" << fNamePedPhotCam << "\");" << endl;
+    if (gsNameGeomCam!=fNameGeomCam)
+        out << "   " << GetUniqueName() << ".SetNameGeomCam(\"" << fNameGeomCam << "\");" << endl;
+    if (gsNameSignalCam!=fNameSignalCam)
+        out << "   " << GetUniqueName() << ".SetNameSignalCam(\"" << fNameSignalCam << "\");" << endl;
+    if (fKeepIsolatedPixels)
+        out << "   " << GetUniqueName() << ".SetKeepIsolatedPixels();" << endl;
+    if (fRecoverIsolatedPixels)
+        out << "   " << GetUniqueName() << ".SetRecoverIsolatedPixels(" << fRecoverIsolatedPixels << ");" << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MImgCleanStd.CleanLevel1: 3.0
+//   MImgCleanStd.CleanLevel2: 2.5
+//   MImgCleanStd.CleanMethod: Standard, Scaled, Democratic, Probability, Absolute
+//   MImgCleanStd.CleanRings:  1
+//   MImgCleanStd.KeepIsolatedPixels: yes, no
+//
+Int_t MImgCleanStd::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "CleanRings", print))
+    {
+        rc = kTRUE;
+        SetCleanRings(GetEnvValue(env, prefix, "CleanRings", fCleanRings));
+    }
+    if (IsEnvDefined(env, prefix, "CleanLevel0", print))
+    {
+        rc = kTRUE;
+        fCleanLvl0 = GetEnvValue(env, prefix, "CleanLevel0", fCleanLvl0);
+    }
+    if (IsEnvDefined(env, prefix, "CleanLevel1", print))
+    {
+        rc = kTRUE;
+        fCleanLvl1 = GetEnvValue(env, prefix, "CleanLevel1", fCleanLvl1);
+    }
+    if (IsEnvDefined(env, prefix, "CleanLevel2", print))
+    {
+        rc = kTRUE;
+        fCleanLvl2 = GetEnvValue(env, prefix, "CleanLevel2", fCleanLvl2);
+    }
+    if (IsEnvDefined(env, prefix, "TimeLevel1", print))
+    {
+        rc = kTRUE;
+        fTimeLvl1 = GetEnvValue(env, prefix, "TimeLevel1", fTimeLvl1);
+    }
+    if (IsEnvDefined(env, prefix, "TimeLevel2", print))
+    {
+        rc = kTRUE;
+        fTimeLvl2 = GetEnvValue(env, prefix, "TimeLevel2", fTimeLvl2);
+    }
+    if (IsEnvDefined(env, prefix, "KeepIsolatedPixels", print))
+    {
+        rc = kTRUE;
+        fKeepIsolatedPixels = GetEnvValue(env, prefix, "KeepIsolatedPixels", fKeepIsolatedPixels);
+    }
+    if (IsEnvDefined(env, prefix, "RecoverIsolatedPixels", print))
+    {
+        rc = kTRUE;
+        fRecoverIsolatedPixels = GetEnvValue(env, prefix, "RecoverIsolatedPixels", fKeepIsolatedPixels);
+    }
+    if (IsEnvDefined(env, prefix, "PostCleanType", print))
+    {
+        rc = kTRUE;
+        fPostCleanType = GetEnvValue(env, prefix, "PostCleanType", fPostCleanType);
+    }
+
+    if (IsEnvDefined(env, prefix, "CleanMethod", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "CleanMethod", "");
+        s.ToLower();
+        if (s.BeginsWith("standard"))
+            SetMethod(kStandard);
+        if (s.BeginsWith("scaled"))
+            SetMethod(kScaled);
+        if (s.BeginsWith("democratic"))
+            SetMethod(kDemocratic);
+        if (s.BeginsWith("probability"))
+            SetMethod(kProbability);
+        if (s.BeginsWith("absolute"))
+            SetMethod(kAbsolute);
+        if (s.BeginsWith("time"))
+            SetMethod(kTime);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mimage/MImgCleanStd.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanStd.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanStd.h	(revision 17960)
@@ -0,0 +1,116 @@
+#ifndef MARS_MImgCleanStd
+#define MARS_MImgCleanStd
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+class MGeomCam;
+class MGeom;
+class MSignalCam;
+class MPedPhotCam;
+class MArrivalTime;
+class MCameraData;
+//class MRawRunHeader;
+
+class MGGroupFrame;
+
+class MImgCleanStd : public MGTask
+{
+public:
+    typedef enum {
+        kStandard,
+        kScaled,
+        kDemocratic,
+        kProbability,
+        kAbsolute,
+        kTime,
+    } CleaningMethod_t;
+
+private:
+    static const TString gsNamePedPhotCam; // default name of the 'MPedPhotCam' container
+    static const TString gsNameGeomCam;    // default name of the 'MGeomCam' container
+    static const TString gsNameSignalCam;  // default name of the 'MSignalCam' container
+
+    const MGeomCam      *fCam;  //!
+          MSignalCam    *fEvt;  //!
+          MPedPhotCam   *fPed;  //!
+          MCameraData   *fData; //!
+//          MRawRunHeader *fHeader; //!
+
+    CleaningMethod_t fCleaningMethod;
+
+    Float_t  fCleanLvl0;
+    Float_t  fCleanLvl1;
+    Float_t  fCleanLvl2;
+
+    Float_t  fTimeLvl1;
+    Float_t  fTimeLvl2;
+
+    UShort_t fCleanRings;
+    Bool_t   fKeepIsolatedPixels;
+    Int_t    fRecoverIsolatedPixels;
+    Int_t    fPostCleanType;
+
+    TString  fNamePedPhotCam; // name of the 'MPedPhotCam' container
+    TString  fNameGeomCam;    // name of the 'MGeomCam' container
+    TString  fNameSignalCam;  // name of the 'MSignalCam' container
+
+    // MImgCleanStd
+    Bool_t HasCoreNeighbors(const MGeom &gpix) const;
+    Bool_t HasUsedNeighbors(const MGeom &gpix) const;
+    void   SetUsedNeighbors(const MGeom &gpix, Int_t r=1) const;
+    Int_t  DoCleaning(Float_t &size) const;
+    void   ResetCleaning() const;
+    Int_t  RecoverIsolatedPixels(Float_t &size) const;
+    void   CleanTime(Int_t n, Double_t lvl) const;
+
+    void CleanStepTime() const;
+
+    // MGTask, MTask, MParContainer
+    void    CreateGuiElements(MGGroupFrame *f);
+    Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    void    StreamPrimitive(std::ostream &out) const;
+
+    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 GetCleanLvl0() const { return fCleanLvl0; }
+    Float_t GetCleanLvl1() const { return fCleanLvl1; }
+    Float_t GetCleanLvl2() const { return fCleanLvl2; }
+
+    Float_t GetTimeLvl1() const { return fTimeLvl1; }
+    Float_t GetTimeLvl2() const { return fTimeLvl2; }
+
+    void SetCleanLvl0(Float_t lvl) { fCleanLvl0=lvl; }
+    void SetCleanLvl1(Float_t lvl) { fCleanLvl1=lvl; }
+    void SetCleanLvl2(Float_t lvl) { fCleanLvl2=lvl; }
+
+    void SetTimeLvl1(Float_t lvl) { fTimeLvl1=lvl; }
+    void SetTimeLvl2(Float_t lvl) { fTimeLvl2=lvl; }
+
+    void SetCleanRings(UShort_t r) { fCleanRings=r; }
+    UShort_t GetCleanRings() const { return fCleanRings;}
+
+    void SetPostCleanType(Int_t t) { fPostCleanType=t; }
+
+    void SetMethod(CleaningMethod_t m) { fCleaningMethod = m; }
+    void SetKeepIsolatedPixels(Bool_t b=kTRUE) { fKeepIsolatedPixels=b; }
+    void SetRecoverIsolatedPixels(Int_t n=-1) { fRecoverIsolatedPixels=n; }
+
+    Bool_t ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2);
+
+    void SetNamePedPhotCam(const char *name)  { fNamePedPhotCam = name; }
+    void SetNameSignalCam(const char *name)   { fNameSignalCam = name; }
+    void SetNameGeomCam(const char *name)     { fNameGeomCam = name; }
+
+    ClassDef(MImgCleanStd, 4)    // task doing the image cleaning
+}; 
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MImgCleanTGB.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanTGB.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanTGB.cc	(revision 17960)
@@ -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(ostream &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: branches/Mars_McMismatchStudy/mimage/MImgCleanTGB.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanTGB.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanTGB.h	(revision 17960)
@@ -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(ostream &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: branches/Mars_McMismatchStudy/mimage/MImgCleanTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanTime.cc	(revision 17960)
@@ -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, 4/2014 <mailto:tbretz@phys.ethz.ch>
+!
+!   Copyright: MAGIC Software Development, 2014
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MImgCleanTime
+//
+//  Input Containers:
+//   MGeomCam
+//   MSignalCam
+//
+//  Output Containers:
+//   MSignalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImgCleanTime.h"
+
+#include <TEnv.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+ClassImp(MImgCleanTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// 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.
+//
+MImgCleanTime::MImgCleanTime(const char *name, const char *title)
+    : fCam(0), fEvt(0), fMinCount(0), fMinSize(25), fDeltaT(2.5*17.5*0.1111),
+    fNameSignalCam("MSignalCam")
+{
+    fName  = name  ? name  : "MImgCleanTime";
+    fTitle = title ? title : "Task to perform image cleaning";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if MEvtHeader exists in the Parameter list already.
+//  if not create one and add them to the list
+//
+Int_t MImgCleanTime::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+    fEvt = (MSignalCam*)pList->FindObject(fNameSignalCam, "MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << fNameSignalCam << " [MSignalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Island MImgCleanTime::CalcIsland(MSignalPix &pix1, const MGeom &gpix1, const uint16_t &island1)
+{
+    pix1.SetIdxIsland(island1);
+
+    const Float_t time1 = pix1.GetArrivalTime();
+
+    Island island(pix1.GetNumPhotons(), time1);
+
+    for (UInt_t i=0; i<gpix1.GetNumNeighbors(); i++)
+    {
+        const Int_t idx2 = gpix1.GetNeighbor(i);
+
+        MSignalPix &pix2 = (*fEvt)[idx2];
+
+        const Int_t island2 = pix2.GetIdxIsland();
+        if (island2>=0)
+        {
+            if (island1==island2)
+                continue;
+
+            // The entries are sorted naturally, therefore
+            // there is no need to check the whole array
+            const auto it = fContacts.rbegin();
+            if (it==fContacts.rend() ||
+                (it->first!=island1 && it->second!=island2))
+                fContacts.emplace_back(island1, island2);
+
+            continue;
+        }
+
+        const Float_t time2 = pix2.GetArrivalTime();
+        if (fabs(time2-time1)<fDeltaT) // FIXME: Scale with distance?
+            island += CalcIsland(pix2, (*fCam)[idx2], island1);
+    }
+
+    return island;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cleans the image.
+//
+Int_t MImgCleanTime::Process()
+{
+    // The assumption is that all pixels contain valid data
+    const UInt_t npix = fEvt->GetNumPixels();
+    for (UInt_t i=0; i<npix; i++)
+    {
+        MSignalPix &pix = (*fEvt)[i];
+        pix.SetPixelUnused();
+        pix.SetPixelCore(kFALSE);
+        pix.SetIdxIsland(-1);
+    }
+
+    // Contains the id of the island for each pixel
+    fIslands.clear();
+    fContacts.clear();
+
+    // Start with island idx==0
+    UShort_t idx = 0;
+    for (UInt_t i=0; i<npix; i++)
+    {
+        MSignalPix &spix = (*fEvt)[i];
+
+        // The following might be much more efficient and faster
+        // if we omit small counted and sized islands already,
+        // but what is the disadvantage?
+        if (spix.GetIdxIsland()<0)
+            fIslands.emplace_back(CalcIsland(spix, (*fCam)[i], idx++));
+    }
+
+    fLut.resize(fIslands.size());
+    for (UInt_t i=0; i<fLut.size(); i++)
+        fLut[i] = i;
+
+    // Unify touching islands if their arrival time ranges overlap
+    for (auto it=fContacts.begin(); it!=fContacts.end(); it++)
+    {
+        const uint16_t &idx1 = fLut[it->first];
+        const uint16_t &idx2 = fLut[it->second];
+        if (idx1==idx2)
+            continue;
+
+              Island &I1 = fIslands[idx1];
+        const Island &I2 = fIslands[idx2];
+
+        // FIXME: Put a limit on count? Put a limit on size?
+        // The ideal cut would be to allow that a single
+        // pixel still can connect two clusters
+        if (I1.count==1 || I1.count==1)
+            continue;
+
+        if (I1.max<I2.min || I2.max<I1.min)
+            continue;
+
+        // Combine both islands
+        I1 += I2;
+
+        // Remove idx2 from the list
+        for (auto is=fLut.begin(); is!=fLut.end(); is++)
+            if (*is==idx2)
+                *is=idx1;
+
+        // Erase entry form contact list
+        fContacts.erase(it);
+
+        // Start over again
+        it = fContacts.begin();
+    }
+
+    uint16_t num_islands = 0;
+    double   size_main   = 0;
+    double   size_tot    = 0;
+
+    vector<bool> used(fIslands.size());
+    for (UInt_t i=0; i<npix; i++)
+    {
+        MSignalPix &pix = (*fEvt)[i];
+
+        // At the end every pixel has an island assigned
+        const Short_t ii = fLut[pix.GetIdxIsland()];
+
+        const Island &island = fIslands[ii];
+
+        if (island.count<=fMinCount || island.size<=fMinSize)
+            continue;
+
+        if (!used[ii])
+        {
+            used[ii] = true;
+            num_islands++;
+
+            size_tot += island.size;
+            if (island.size>size_main)
+                size_main = island.size;
+        }
+
+        pix.SetPixelUsed();
+        pix.SetPixelCore();
+    }
+
+    fEvt->SetIslandInfo(num_islands, size_main, size_tot-size_main);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MImgCleanTime::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "MinSize", print))
+    {
+        rc = kTRUE;
+        SetMinSize(GetEnvValue(env, prefix, "MinSize", fMinSize));
+    }
+    if (IsEnvDefined(env, prefix, "MinCount", print))
+    {
+        rc = kTRUE;
+        SetMinSize(GetEnvValue(env, prefix, "MinCount", (Int_t)fMinCount));
+    }
+    if (IsEnvDefined(env, prefix, "DeltaT", print))
+    {
+        rc = kTRUE;
+        SetMinSize(GetEnvValue(env, prefix, "DeltaT", fDeltaT));
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mimage/MImgCleanTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MImgCleanTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MImgCleanTime.h	(revision 17960)
@@ -0,0 +1,76 @@
+#ifndef MARS_MImgCleanTime
+#define MARS_MImgCleanTime
+
+#include <stdint.h>
+#include <list>
+#include <vector>
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeom;
+class MGeomCam;
+class MSignalPix;
+class MSignalCam;
+
+struct Island
+{
+    uint16_t count;
+    float size;
+    float min;
+    float max;
+
+    Island() : count(0) { }
+    Island(float sz, float tm) : count(1), size(sz), min(tm), max(tm) { }
+
+    void operator+=(const Island &i)
+    {
+        count += i.count;
+        size += i.size;
+        if (i.min<min)
+            min = i.min;
+        if (i.max>max)
+            max = i.max;
+    }
+};
+
+class MImgCleanTime : public MTask
+{
+public:
+    const MGeomCam   *fCam;  //!
+          MSignalCam *fEvt;  //!
+
+    UInt_t  fMinCount;
+    Float_t fMinSize;
+    Float_t fDeltaT;
+
+    TString fNameSignalCam;  // name of the 'MSignalCam' container
+
+    std::vector<Island> fIslands;
+    std::list<std::pair<uint16_t, uint16_t>> fContacts;
+    std::vector<uint16_t> fLut;
+
+    Island CalcIsland(MSignalPix &, const MGeom &, const uint16_t &);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MImgCleanTime(const char *name=NULL, const char *title=NULL);
+
+    //void Print(Option_t *o="") const;
+
+    void SetMinCount(UInt_t sz)  { fMinCount=sz; }
+    void SetMinSize(Float_t lvl) { fMinSize=lvl; }
+    void SetDeltaT(Float_t dt)   { fDeltaT=dt; }
+
+    void SetNameSignalCam(const char *name) { fNameSignalCam = name; }
+
+    ClassDef(MImgCleanTime, 0) // task doing the image cleaning
+}; 
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MNewImagePar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MNewImagePar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MNewImagePar.cc	(revision 17960)
@@ -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): 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 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 fConcCOG;              // [ratio] concentration of the three pixels next to COG
+//    Float_t fConcCore;             // [ratio] concentration of signals inside or touching the ellipse
+//
+//    Float_t fUsedArea;             // Area of pixels which survived the image cleaning
+//    Float_t fCoreArea;             // Area of core pixels
+//    Short_t fNumUsedPixels;        // Number of pixels which survived the image cleaning
+//    Short_t fNumCorePixels;        // number of core pixels
+//    Short_t fNumHGSaturatedPixels; // number of pixels with saturating hi-gains
+//    Short_t fNumSaturatedPixels;   // number of pixels with saturating lo-gains
+//
+// Version 2:
+// ----------
+//  - added fNumSaturatedPixels
+// 
+// Version 3:
+// ----------
+//  - added fNumHGSaturatedPixels
+//  - added fInnerLeakage1
+//  - added fInnerLeakage2
+//  - added fInnerSize
+//  - added fUsedArea
+//  - added fCoreArea
+//
+// Version 4:
+// ----------
+//  - moved cleaning/island independant parameters to MImagePar:
+//    + removed fNumHGSaturatedPixels
+//    + removed fNumSaturatedPixels
+//
+// Version 5:
+// ----------
+//  - added fConcCOG
+//  - added fConcCore
+//
+// Version 6:
+// ----------
+//  - removed fInnerLeakage1
+//  - removed fInnerLeakage2
+//  - removed fInnerSize
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MNewImagePar.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+ClassImp(MNewImagePar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MNewImagePar::MNewImagePar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MNewImagePar";
+    fTitle = title ? title : "New image parameters";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar::Reset()
+{
+    fLeakage1 = -1;
+    fLeakage2 = -1;
+
+    fConc     = -1;
+    fConc1    = -1;
+    fConcCOG  = -1;
+    fConcCore = -1;
+
+    fNumUsedPixels = -1;
+    fNumCorePixels = -1;
+
+    fUsedArea = -1;
+    fCoreArea = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of new image parameters
+//
+void MNewImagePar::Calc(const MGeomCam &geom, const MSignalCam &evt,
+                        const MHillas &hillas, Int_t island)
+{
+    fNumUsedPixels = 0;
+    fNumCorePixels = 0;
+
+    fUsedArea = 0;
+    fCoreArea = 0;
+
+    fConcCore  = 0;
+
+    Double_t edgepix1 = 0;
+    Double_t edgepix2 = 0;
+
+    Float_t maxpix1 = 0;                                 // [#phot]
+    Float_t maxpix2 = 0;                                 // [#phot]
+
+    const Double_t d = FLT_MAX; //geom.GetMaxRadius()*geom.GetMaxRadius();
+    Double_t dist[3] = { d, d, d };
+    Int_t    idx[3]  = { -1, -1, -1};
+
+    const Double_t rl = 1./(hillas.GetLength()*hillas.GetLength());
+    const Double_t rw = 1./(hillas.GetWidth() *hillas.GetWidth());
+
+    UInt_t npix = evt.GetNumPixels();
+    for (UInt_t i=0; i<npix; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (pix.IsPixelUnmapped())
+            continue;
+
+        // Get geometry of pixel
+        const MGeom &gpix = geom[i];
+
+        // Find the three pixels which are next to the COG
+        const Double_t dx = gpix.GetX() - hillas.GetMeanX();      // [mm]
+        const Double_t dy = gpix.GetY() - hillas.GetMeanY();      // [mm]
+
+        const Double_t dist0 = dx*dx+dy*dy;
+
+        if (dist0<dist[0])
+        {
+            dist[2] = dist[1];
+            dist[1] = dist[0];
+            dist[0] = dist0;
+
+            idx[2]  = idx[1];
+            idx[1]  = idx[0];
+            idx[0]  = i;
+        }
+        else
+            if (dist0<dist[1])
+            {
+                dist[2] = dist[1];
+                dist[1] = dist0;
+
+                idx[2]  = idx[1];
+                idx[1]  = i;
+            }
+            else
+                if (dist0<dist[2])
+                {
+                    dist[2] = dist0;
+                    idx[2]  = i;
+                }
+
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // Check for requested islands
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        // count used and core pixels
+        if (pix.IsPixelCore())
+        {
+            fNumCorePixels++;
+            fCoreArea += gpix.GetA();
+        }
+
+        // count used pixels
+        fNumUsedPixels++;
+        fUsedArea += gpix.GetA();
+
+        // signal in pixel
+        Double_t nphot = pix.GetNumPhotons();
+
+        //
+        // Calculate signal contained inside ellipse
+        //
+        const Double_t dzx   =  hillas.GetCosDelta()*dx + hillas.GetSinDelta()*dy; // [mm]
+        const Double_t dzy   = -hillas.GetSinDelta()*dx + hillas.GetCosDelta()*dy; // [mm]
+        const Double_t dz    =  gpix.GetT()*gpix.GetT()/4;
+        const Double_t tana  =  dzy*dzy/(dzx*dzx);
+        const Double_t distr =  (1+tana)/(rl + tana*rw);
+        if (distr>dist0-dz || dzx==0)
+            fConcCore += nphot;
+
+        //
+        // count photons in outer rings of camera
+        //
+        if (gpix.IsInOutermostRing())
+           edgepix1 += nphot;
+        if (gpix.IsInOuterRing())
+           edgepix2 += nphot;
+
+        //
+        // Now convert nphot from absolute number of photons or phe to signal
+        // density (divide by pixel area), to find the pixel with highest signal
+        // density:
+        //
+        nphot *= geom.GetPixRatio(i);
+
+ 	// Look for signal density in two highest pixels:
+        if (nphot>maxpix1)
+        {
+            maxpix2  = maxpix1;
+            maxpix1  = nphot;                            // [1]
+        }
+        else
+            if (nphot>maxpix2)
+                maxpix2 = nphot;                         // [1]
+    }
+
+    fLeakage1 = edgepix1 / hillas.GetSize();
+    fLeakage2 = edgepix2 / hillas.GetSize();
+
+    // FIXME?: in case the pixel with highest signal density is an outer
+    // pixel, the value of fConc (ratio of signal in two highest pixels
+    // to SIZE) should rather be 2*fConc1, under the simplest assumption
+    // that the light density inside the outer (large) pixel is uniform.
+    fConc  = (maxpix1+maxpix2)/hillas.GetSize();         // [ratio]
+    fConc1 = maxpix1/hillas.GetSize();                   // [ratio]
+
+    //
+    // Concentration around COG (it is calculated here, because the
+    // distance of the pixel to COG is calculated anyhow)
+    //
+    fConcCOG = 0;
+    for (UInt_t i=0; i<TMath::Min(3U, npix); i++)
+        fConcCOG += idx[i]<0 ? 0 : evt[idx[i]].GetNumPhotons()*geom.GetPixRatio(idx[i]);
+    fConcCOG /= hillas.GetSize();                        // [ratio]
+
+    // This can for example happen in case of Muon Rings
+    if (fConcCOG<0)
+        fConcCOG=0;
+
+    // Concentration of signal contained in ellipse
+    fConcCore /= hillas.GetSize();
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Leakage1         [1] = " << fLeakage1      << endl;
+    *fLog << " - Leakage2         [1] = " << fLeakage2      << endl;
+    *fLog << " - Conc             [1] = " << fConc          << endl;
+    *fLog << " - Conc1            [1] = " << fConc1         << endl;
+    *fLog << " - ConcCOG          [1] = " << fConcCOG       << endl;
+    *fLog << " - ConcCore         [1] = " << fConcCore      << endl;
+    *fLog << " - Num Used Pixels  [#] = " << fNumUsedPixels << endl;
+    *fLog << " - Num Core Pixels  [#] = " << fNumCorePixels << endl;
+    *fLog << " - Used Area      [mm" << UTF8::kSquare << "] = " << fUsedArea      << endl;
+    *fLog << " - Core Area      [mm" << UTF8::kSquare << "] = " << fCoreArea      << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MNewImagePar to *fLog, depending on the geometry in
+// units of deg.
+//
+void MNewImagePar::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Leakage1         [1] = " << fLeakage1      << endl;
+    *fLog << " - Leakage2         [1] = " << fLeakage2      << endl;
+    *fLog << " - Conc             [1] = " << fConc          << endl;
+    *fLog << " - Conc1            [1] = " << fConc1         << endl;
+    *fLog << " - ConcCOG          [1] = " << fConcCOG       << endl;
+    *fLog << " - ConcCore         [1] = " << fConcCore      << endl;
+    *fLog << " - Num Used Pixels  [#] = " << fNumUsedPixels << endl;
+    *fLog << " - Num Core Pixels  [#] = " << fNumCorePixels << endl;
+    *fLog << " - Used Area     [deg" << UTF8::kSquare << "] = " << fUsedArea*geom.GetConvMm2Deg()*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Core Area     [deg" << UTF8::kSquare << "] = " << fCoreArea*geom.GetConvMm2Deg()*geom.GetConvMm2Deg() << endl;
+}
Index: branches/Mars_McMismatchStudy/mimage/MNewImagePar.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MNewImagePar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MNewImagePar.h	(revision 17960)
@@ -0,0 +1,58 @@
+#ifndef MARS_MNewImagePar
+#define MARS_MNewImagePar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MNewImagePar : public MParContainer
+{
+private:
+    // FIXME: MOVE ALL PARAMETRS WHICH DOES'T DEPEND ON THE IMAGE
+    //        CLEANING TO A NEW CLASS!
+    Float_t fLeakage1;             // (photons in most outer ring of pixels) over fSize
+    Float_t fLeakage2;             // (photons in the 2 outer rings of pixels) over fSize
+
+    Float_t 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 fConcCOG;              // [ratio] concentration of the three pixels next to COG
+    Float_t fConcCore;             // [ratio] concentration of signals inside or touching the ellipse
+
+    Float_t fUsedArea;             // Area of pixels which survived the image cleaning
+    Float_t fCoreArea;             // Area of core pixels
+    Short_t fNumUsedPixels;        // Number of pixels which survived the image cleaning
+    Short_t fNumCorePixels;        // number of core pixels
+
+public:
+    MNewImagePar(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Float_t GetLeakage1() const { return fLeakage1; }
+    Float_t GetLeakage2() const { return fLeakage2; }
+
+    Float_t GetConc() const     { return fConc;     }
+    Float_t GetConc1() const    { return fConc1;    }
+    Float_t GetConcCOG() const  { return fConcCOG;  }
+    Float_t GetConcCore() const { return fConcCore; }
+
+    Short_t GetNumUsedPixels() const { return fNumUsedPixels; }
+    Short_t GetNumCorePixels() const { return fNumCorePixels; }
+
+    Float_t GetUsedArea() const { return fUsedArea; }
+    Float_t GetCoreArea() const { return fCoreArea; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    void Calc(const MGeomCam &geom, const MSignalCam &evt,
+              const MHillas &hillas, Int_t island=-1);
+
+    ClassDef(MNewImagePar, 6) // Container to hold new image parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MNewImagePar2.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MNewImagePar2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MNewImagePar2.cc	(revision 17960)
@@ -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 03/2005, <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MNewImagePar2
+//
+// Storage Container for new image parameters
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MNewImagePar2.h"
+
+#include <TArrayI.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+ClassImp(MNewImagePar2);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MNewImagePar2::MNewImagePar2(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MNewImagePar2";
+    fTitle = title ? title : "New image parameters 2";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar2::Reset()
+{
+    fBorderLinePixel  = 0;
+    fBorderLineCenter = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of new image parameters
+//
+void MNewImagePar2::Calc(const MGeomCam &geom, const MSignalCam &evt, Int_t island)
+{
+    TArrayI idx(evt.GetNumPixels());
+    idx.Reset(-1);
+    Int_t cnt=0;
+
+    Int_t n = evt.GetNumPixels();
+    for (int i=0; i<n; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        Int_t used=0;
+
+        const MGeom &gpix = geom[i];
+        const Int_t nn = gpix.GetNumNeighbors();
+        for (int j=0; j<nn; j++)
+        {
+            const Int_t k = gpix.GetNeighbor(j);
+            if (evt[k].IsPixelUsed())
+                used++;
+        }
+
+        if (used<nn)
+        {
+            idx[cnt++] = i;
+            evt[i].SetBit(BIT(14));
+        }
+        else
+            evt[i].ResetBit(BIT(14));
+
+        // FIXME: GetT is not the correct value
+        fBorderLinePixel += (nn-used)*gpix.GetL();
+    }
+
+    for (Int_t m=0; idx[m]>=0; m++)
+    {
+        const Int_t l = idx[m];
+
+        const MGeom &gpix = geom[l];
+
+        const Int_t nn = gpix.GetNumNeighbors();
+        for (int j=0; j<nn; j++)
+        {
+            const Int_t k = gpix.GetNeighbor(j);
+            if (k<l)
+                continue;
+
+            if (!evt[k].IsPixelUsed())
+                continue;
+
+            if (!evt[k].TestBit(BIT(14)))
+                continue;
+
+            fBorderLineCenter += TMath::Hypot(gpix.GetX()-geom[k].GetX(),
+                                              gpix.GetY()-geom[k].GetY());
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar2::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Border L.Pixel  [mm] = " << fBorderLinePixel  << endl;
+    *fLog << " - Border L.Center [mm] = " << fBorderLineCenter << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MNewImagePar to *fLog, depending on the geometry in
+// units of deg.
+//
+void MNewImagePar2::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - BorderL.Pixel  [deg] = " << fBorderLinePixel*geom.GetConvMm2Deg()  << endl;
+    *fLog << " - BorderL.Center [deg] = " << fBorderLineCenter*geom.GetConvMm2Deg() << endl;
+}
Index: branches/Mars_McMismatchStudy/mimage/MNewImagePar2.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MNewImagePar2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MNewImagePar2.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MNewImagePar2
+#define MARS_MNewImagePar2
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomCam;
+class MSignalCam;
+
+class MNewImagePar2 : public MParContainer
+{
+private:
+    Float_t fBorderLinePixel;   //
+    Float_t fBorderLineCenter;  //
+
+public:
+    MNewImagePar2(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Float_t GetBorderLinePixel() const  { return fBorderLinePixel; }
+    Float_t GetBorderLineCenter() const { return fBorderLineCenter; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    void Calc(const MGeomCam &geom, const MSignalCam &evt, Int_t island=-1);
+
+    ClassDef(MNewImagePar2, 1) // Container to hold new image parameters 2
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/MNewImageParCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MNewImageParCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MNewImageParCalc.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mimage/MNewImageParCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MNewImageParCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MNewImageParCalc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mimage/MStereoCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MStereoCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MStereoCalc.cc	(revision 17960)
@@ -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): Abelardo Moralejo, 11/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MStereoCalc
+//
+//  This is a task to calculate some shower parameters from the images of
+//  two telescopes in stereo mode. 
+//
+//  Input Containers:
+//   MGeomCam
+//   MHillas
+//   MPointingPos
+//
+//  Output Containers:
+//   MStereoPar
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MStereoCalc.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MStereoPar.h"
+#include "MPointingPos.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)
+{
+    fPointingPos1 = (MPointingPos*)pList->FindObject(AddSerialNumber("MPointingPos",fCT1id));
+    if (!fPointingPos1)
+    {
+        *fLog << err << AddSerialNumber("MPointingPos",fCT1id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointingPos2 = (MPointingPos*)pList->FindObject(AddSerialNumber("MPointingPos",fCT2id));
+    if (!fPointingPos2)
+    {
+        *fLog << err << AddSerialNumber("MPointingPos",fCT2id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam1 = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam", fCT1id));
+    if (!fGeomCam1)
+    {
+        *fLog << err << AddSerialNumber("MGeomCam", fCT1id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam2 = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam", fCT2id));
+    if (!fGeomCam2)
+    {
+        *fLog << err << AddSerialNumber("MGeomCam", fCT2id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHillas1 = (MHillas*)pList->FindObject(AddSerialNumber("MHillas", fCT1id));
+    if (!fHillas1)
+    {
+        *fLog << err << AddSerialNumber("MHillas", fCT1id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHillas2 = (MHillas*)pList->FindObject(AddSerialNumber("MHillas", fCT2id));
+    if (!fHillas2)
+    {
+        *fLog << err << AddSerialNumber("MHillas", fCT2id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fStereoPar = (MStereoPar*)pList->FindCreateObj("MStereoPar", fStereoParName);
+    if (!fStereoPar)
+	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, *fPointingPos1, *fGeomCam1, fCT1x, fCT1y,
+                     *fHillas2, *fPointingPos2, *fGeomCam2, fCT2x, fCT2y);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mimage/MStereoCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MStereoCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MStereoCalc.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MStereoCalc
+#define MARS_MStereoCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MStereoCalc                                                             //
+//                                                                         //
+// Task to calculate some shower parameters in stereo mode                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MHillas;
+class MStereoPar;
+class MPointingPos;
+
+class MStereoCalc : public MTask
+{
+    const MGeomCam     *fGeomCam1;     //! CT1: Camera Geometry
+    const MHillas      *fHillas1;      //! CT1: Hillas parameters
+    const MPointingPos *fPointingPos1; //! CT1: Pointing Direction
+
+    const MGeomCam     *fGeomCam2;     //! CT2: Camera Geometry
+    const MHillas      *fHillas2;      //! CT2: Hillas parameters
+    const MPointingPos *fPointingPos2; //! CT2: pointing direction
+
+    Int_t fCT1id;   // CT1: Identifier number
+    Int_t fCT2id;   // CT2: Identifier number
+
+    Float_t fCT1x;   //! FIXME -> Move to parameter list
+    Float_t fCT1y;   //! Position of first telescope
+    Float_t fCT2x;   //! FIXME -> Move to parameter list
+    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();
+
+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: branches/Mars_McMismatchStudy/mimage/MStereoPar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MStereoPar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MStereoPar.cc	(revision 17960)
@@ -0,0 +1,274 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! * 
+!
+!
+!   Author(s): Abelardo Moralejo 11/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MStereoPar
+//
+// Storage Container for shower parameters estimated using the information
+// from two telescopes (presently for MC studies)
+//
+// 
+/////////////////////////////////////////////////////////////////////////////
+#include "MStereoPar.h"
+
+#include <fstream>
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+#include "MGeomCam.h"
+#include "MPointingPos.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.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Transformation of coordinates, from a point on the camera x, y , to
+// the directon 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!
+//
+TVector3 MStereoPar::CamToDir(const MGeomCam &geom, const MPointingPos &pos, Float_t x, Float_t y) const
+{
+    const Double_t rc      = geom.GetCameraDist()*1e3;
+
+    const Double_t CTphi   = pos.GetAzRad();
+    const Double_t CTtheta = pos.GetZdRad();
+
+    //
+    // We convert phi to the convention defined in TDAS 01-05
+    //
+    const Double_t sinphi   = sin(TMath::TwoPi()-CTphi);
+    const Double_t cosphi   = cos(CTphi);
+
+    const Double_t costheta = cos(CTtheta);
+    const Double_t sintheta = sin(CTtheta);
+
+    const Double_t xc = x/rc;
+    const Double_t yc = y/rc;
+
+    const Double_t norm = 1/sqrt(1+xc*xc+yc*yc);
+
+    const Double_t xref = xc * norm;
+    const Double_t yref = yc * norm;
+    const Double_t zref = -1 * norm;
+
+    const Double_t cosx =  xref * sinphi + yref * costheta*cosphi - zref * sintheta*cosphi;
+    const Double_t cosy = -xref * cosphi + yref * costheta*sinphi - zref * sintheta*sinphi;
+    const Double_t cosz =                  yref * sintheta        + zref * costheta;
+
+    //  Now change from system A of TDAS 01-05 to Corsika system:
+    return TVector3(cosx, -cosy, -cosz);
+}
+
+TVector3 MStereoPar::CamToDir(const MGeomCam &geom, const MPointingPos &pos, const TVector2 &p) const
+{
+    return CamToDir(geom, pos, p.X(), p.Y());
+}
+
+void MStereoPar::CalcCT(const MHillas &h, const MPointingPos &p, const MGeomCam &g, TVector2 &cv1, TVector2 &cv2) const
+{
+    //
+    // Get the direction corresponding to the c.o.g. of the image on 
+    // the camera.
+    //
+    // ct1_a, Direction from ct1 to the shower c.o.g.
+    //
+    const TVector3 a = CamToDir(g, p, h.GetMeanX(), h.GetMeanY());
+
+    //
+    // Now we get another (arbitrary) point along the image long axis,
+    // fMeanX + cosdelta, fMeanY + sindelta, and calculate the direction 
+    // to which it corresponds.
+    //
+    const TVector3 c = CamToDir(g, p, h.GetMeanX()+h.GetCosDelta(), h.GetMeanY()+h.GetSinDelta());
+
+    //
+    // 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).
+    //
+    const Double_t coreVersorX = a.Z()*c.X() - a.X()*c.Z();
+    const Double_t coreVersorY = a.Z()*c.Y() - a.X()*c.Z();
+
+    //
+    // 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)
+
+    const TVector3 b = CamToDir(g, p, 0, 0);
+
+    const Double_t coreVersorX_best = a.Z()*b.X() - a.X()*b.Z();
+    const Double_t coreVersorY_best = a.Z()*b.Y() - a.Y()*b.Z();
+
+    cv1.Set(coreVersorX,      coreVersorY);
+    cv2.Set(coreVersorX_best, coreVersorY_best);
+}
+
+TVector2 MStereoPar::VersorToCore(const TVector2 &v1, const TVector2 &v2, const TVector2 &p1, const TVector2 &p2) const
+{
+    const TVector2 dp = p1 - p2;
+
+    //
+    // Estimate core position:
+    //
+    const Double_t t =
+        (dp.X() - v2.X()/v2.Y()*dp.Y())/(v2.X()/v2.Y()*v1.Y() - v1.X());
+
+    // Core will have the same units as p1/p2
+    return p1 + v1*t;
+}
+
+Double_t MStereoPar::CalcImpact(const TVector2 &w, const TVector2 &v, const TVector2 &p) const
+{
+    const TVector2 d = v-p;
+
+    const Double_t f = d*w;
+
+    return TMath::Sqrt( d.Mod2() - f*f );
+}
+
+Double_t MStereoPar::CalcImpact(const TVector3 &v, const TVector2 &p) const
+{
+    const TVector2 w = v.XYvector();
+    return CalcImpact(w, w, p);
+}
+
+Double_t MStereoPar::CalcImpact(const TVector2 &core, const TVector2 &p, const MPointingPos &point) const
+{
+    const TVector2 pt(-sin(point.GetZdRad()) * cos(point.GetAzRad()),
+                      -sin(point.GetZdRad()) * sin(point.GetAzRad()));
+
+    return CalcImpact(pt, core, p);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of shower parameters
+//
+void MStereoPar::Calc(const MHillas &hillas1, const MPointingPos &pos1, const MGeomCam &geom1, const Float_t ct1_x, const Float_t ct1_y,
+                      const MHillas &hillas2, const MPointingPos &pos2, const MGeomCam &geom2, const Float_t ct2_x, const Float_t ct2_y)
+{
+    TVector2 coreVersor1, coreVersor1_best;
+    CalcCT(hillas1, pos1, geom1, coreVersor1, coreVersor1_best);
+
+    TVector2 coreVersor2, coreVersor2_best;
+    CalcCT(hillas2, pos2, geom2, coreVersor2, coreVersor2_best);
+
+    const TVector2 p1(ct1_x, ct1_y);
+    const TVector2 p2(ct2_x, ct2_y);
+
+    // Estimate core position:
+    const TVector2 core = VersorToCore(coreVersor1, coreVersor2, p1, p2);
+
+    // Now the estimated core position assuming the source is
+    // located in the center of the camera
+    const TVector2 core2 = VersorToCore(coreVersor1_best, coreVersor2_best, p1, p2);
+
+    // Copy results to data members
+    //
+    // 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.
+    //
+    fCoreX  = core.X();
+    fCoreY  = core.Y();
+
+    fCoreX2 = core2.X();
+    fCoreY2 = core2.Y();
+
+    // 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. 
+    //
+    const TVector2 v1(hillas1.GetSinDelta(), hillas1.GetCosDelta());
+    const TVector2 v2(hillas2.GetSinDelta(), hillas2.GetCosDelta());
+
+    const TVector2 h1 = hillas1.GetMean()*geom1.GetConvMm2Deg();
+    const TVector2 h2 = hillas2.GetMean()*geom2.GetConvMm2Deg();
+
+    const TVector2 src = VersorToCore(v1, v2, h1, h2);
+
+    // Reconstructed source positon
+    fSourceX = src.X();
+    fSourceY = src.Y();
+
+    // Squared angular distance from reconstr. src pos to camera center.
+    fTheta2 = src.Mod2();
+
+    // Get the direction corresponding to the intersection of axes
+    const TVector3 srcdir = CamToDir(geom1, pos1, src/geom1.GetConvMm2Deg());
+
+    fCT1Impact = CalcImpact(srcdir, p1);
+    fCT2Impact = CalcImpact(srcdir, p2);
+
+    // Now calculate i.p. assuming source is point-like and placed in
+    // the center of the camera.
+    fCT1Impact2 = CalcImpact(core2, p1, pos1);
+    fCT2Impact2 = CalcImpact(core2, p2, pos2);
+
+    SetReadyToSave();
+} 
Index: branches/Mars_McMismatchStudy/mimage/MStereoPar.h
===================================================================
--- branches/Mars_McMismatchStudy/mimage/MStereoPar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/MStereoPar.h	(revision 17960)
@@ -0,0 +1,74 @@
+#ifndef MARS_MStereoPar
+#define MARS_MStereoPar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+class MHillas;
+class MGeomCam;
+class MPointingPos;
+
+class MStereoPar : public MParContainer
+{
+private:
+
+    Float_t fCoreX;   // Estimated core position on ground x
+    Float_t fCoreY;   // Estimated core position on ground y
+
+    Float_t fCoreX2;  // Estimated core position on ground assuming that
+    Float_t fCoreY2;  // the source direction is paralel to the tel. 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.
+
+    TVector3 CamToDir(const MGeomCam &geom, const MPointingPos &pos, Float_t x, Float_t y) const;
+    TVector3 CamToDir(const MGeomCam &geom, const MPointingPos &pos, const TVector2 &p) const;
+
+    void     CalcCT(const MHillas &h, const MPointingPos &p, const MGeomCam &g, TVector2 &cv1, TVector2 &cv2) const;
+
+    TVector2 VersorToCore(const TVector2 &v1, const TVector2 &v2, const TVector2 &p1, const TVector2 &p2) const;
+
+    Double_t CalcImpact(const TVector2 &w, const TVector2 &v, const TVector2 &p) const;
+    Double_t CalcImpact(const TVector3 &v, const TVector2 &p) const;
+    Double_t CalcImpact(const TVector2 &core, const TVector2 &p, const MPointingPos &point) const;
+
+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 &h1, const MPointingPos &p1, const MGeomCam &g1, const Float_t ct1_x, const Float_t ct1_y,
+              const MHillas &h2, const MPointingPos &p2, const MGeomCam &g2, const Float_t ct2_x, const Float_t ct2_y);
+
+    ClassDef(MStereoPar, 1) // Container to hold new image parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mimage/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mimage/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mimage/Makefile	(revision 17960)
@@ -0,0 +1,55 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Image
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mgeom -I../msignal \
+	   -I../mgui -I../mmc -I../mpointing -I../mpedestal \
+           -I../mhist -I../manalysis
+
+# mhist: MHHillas (MHCamera)
+
+
+SRCFILES = MImgCleanStd.cc \
+           MImgCleanTime.cc \
+           MImgCleanSimple.cc \
+           MHillas.cc \
+           MHillasSrc.cc \
+           MHillasExt.cc \
+           MHillasCalc.cc \
+           MImagePar.cc \
+	   MNewImagePar.cc \
+	   MNewImagePar2.cc \
+	   MConcentration.cc \
+           MHHillas.cc \
+           MHHillasSrc.cc \
+           MHHillasExt.cc \
+           MHImagePar.cc \
+	   MHNewImagePar.cc \
+	   MHNewImagePar2.cc \
+           MHVsSize.cc \
+	   MStereoPar.cc \
+	   MStereoCalc.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mjobs/JobsIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/JobsIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/JobsIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mjobs/JobsLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/JobsLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/JobsLinkDef.h	(revision 17960)
@@ -0,0 +1,25 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MSequence+;
+#pragma link C++ class MSequenceSQL+;
+#pragma link C++ class MDataSet+;
+
+#pragma link C++ class MJob+;
+#pragma link C++ class MJCalib+;
+//#pragma link C++ class MJCalibTest+;
+#pragma link C++ class MJCalibration+;
+#pragma link C++ class MJCalibrateSignal+;
+
+#pragma link C++ class MJSimulation+;
+
+#pragma link C++ class MJPedestal+;
+#pragma link C++ class MJStar+;
+#pragma link C++ class MJCut+;
+#pragma link C++ class MJSpectrum+;
+#pragma link C++ class MJMerpp+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MDataSet.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MDataSet.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MDataSet.cc	(revision 17960)
@@ -0,0 +1,840 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MDataSet
+//
+//  This class describes a collection of sequences.
+//
+//  Such an input file looks like:
+//
+//     crab.txt:
+//     ---------
+//       AnalysisNumber: 1
+//
+//       Name: SecondCrab
+//
+//       SequencesOn:  35222 35229
+//       SequencesOff: 36817
+//
+//       SequencePath: /magic/sequences
+//       DataPath:     /magic/data/star
+//
+//       Sequence00035222.File: sequences/sequence035222.txt
+//       Sequence00036817.File: sequences/sequence036817.txt
+//
+//       Sequence00035222.Dir: /data2/wuerzburg/Crab-Analyse/images/035222
+//       Sequence00036817.Dir: /data2/wuerzburg/Crab-Analyse/images/036817
+//
+//       Sequence00036817.Exclude: 36818 36819
+//
+//       WobbleMode: No
+//       MonteCarlo: No
+//
+//       SourceName: CrabNebula
+//       Catalog: /magic/datacenter/setup/magic_favorites_dc.edb
+//
+//
+// Reading the file is based on TEnv. For more details see also
+// the class reference of TEnv.
+//
+//
+// AnalysisNumber: The analysis number is an artifical number used to name
+//  the output files automatically if the names are not overwritten in the
+//  corresponding programs.
+//
+// SequencePath: In case it is not specified the datacenter default path is
+//  used. If it is given it is the place at which the sequence files
+//  are searched, if not overwritten by either a program command line
+//  option (aka. a argument to the constructor) or a resource for
+//  an individual sequence file. Note, that the four digits high-level
+//  directories to sort the sequences are added to the given path.
+//
+// DataPath: In case it is not specified the datacenter default path is
+//  used. If it is given it is the place at which the data files
+//  are searched, if not overwritten by either a program command line
+//  option (aka. a argument to the constructor) or a resource for
+//  an individual data path.  Note, that the four digits high-level
+//  directories to sort the sequences are added to the given path.
+//
+// SequencesOn/Off: The sequence number are used to concatenate the filenames
+//  of the sequences using the file structure used in the datacenter. Each
+//  sequence can be added to the on and off data at the same time but only
+//  once.
+//
+//  If you have different file names you can overwrite the default file names
+//  using Sequence%08d.File (make sure you have 8 digits!)
+//
+//  If the file name is given as "-", e.g.
+//       Sequence00035222.File: -
+//  the current dataset file is read as sequence file. In this case all
+//  resources defined for a sequence file should be prefixed by
+//  "Sequence%08d."; if not prefixed the default without the prefix
+//  is looked up. Be aware that the "Sequence" resource for sequence-files
+//  (for more details see MSequence) is ignored and the already defined
+//  number is used instead and thus should be identical to the sequence
+//  number - which normally is not necessary.
+//
+//  In standard coditions (datacenter file system) paths are concatenated
+//  by using the information in the sequence files (date, etc). You can
+//  overwrite the directories in which the sequence-files (eg I-files) are
+//  stored using Sequence%08d.Dir (make sure you have 8 digits!)
+//
+//  Using the resource Sequence%08d.Exclude you can exclude a list of
+//  runs from a sequence.
+//
+// WobbleMode: This is just a flag which is passed to the program
+//  end eveluated (or not) by the individual program, which takes this
+//  dataset as an input. For example this is necessary in ganymed to do
+//  some wobble mode special setup. If no resource is given (or it is
+//  set to "auto") wobble mode if set if the datset contains no off-
+//  sequences.
+//
+// MonetCarlo: This is just a flag which is passed to the program
+//  end eveluated (or not) by the individual program, which takes this
+//  dataset as an input. For example this tells ganymed to skip some
+//  parts accessing time stamps which are not available in the MCs.
+//
+// SequencePath/DataPath: This determined were the sequences and data-files
+//  are stored. The priorities are as follows:
+//   0) Build in default path:          /magic/sequences   /magic/data/star
+//   1) Def.path from dataset file:       SequencePath         DataPath
+//   2) Indiv.path from dataset file:  12345.SequencePath   12345.DataPath
+//   3) Path from command line:            Argument in the constructors
+//   4) Path for an indiv. dataset:         Sequences00022555.File/Dir
+//
+// Catalog: This is the xephem-style file from the central control
+//  containing the observed sky positions.
+//
+// SourceName: The source name, as defined in the catalog, of the object
+//  the data corresponds to.
+//
+// Name: A name is stored for your convinience
+//
+// Comment: It is just stored.
+//
+// General Remark: MDataSet doesn't implement any action on the given
+// resources. Whether a resource is used, necessary or ignored, and
+// what will happen if you change the resource is always defined by the
+// executed macro or program.
+//
+// Resource file entries are case sensitive!
+//
+//
+// Collection of datsets
+// ---------------------
+//
+//  You can combine more than one datset in a file (if your program
+//  supports this) Such a dataset file could look like this:
+//
+//       35222.SequencesOn: 35222
+//       35222.SequencesOff: 36817
+//
+//       65778.SequencesOn: 65778
+//
+//       12345.SequencesOn: 12345
+//
+//       12345.SequencePath: /home/nobody/specialsequences
+//       65778.DataPath:     /home/nobody/specialstars
+//
+//       SequencePath: /home/nobody/defaultsequences
+//       DataPath:     /home/nobody/defaultstars
+//
+//       Sequence00035222.File: sequences/sequence035222.txt
+//       Sequence00035222.Dir:  /data2/wuerzburg/Crab-Analyse/images/035222
+//
+//       35222.WobbleMode: Off
+//       WobbleMode: On
+//
+//
+// IMPORTANT:
+//   * Run filenames must begin with a string which allows correct
+//     ordering in time, otherwise synchronization might fail.
+//   * Sequence filenames should also have names allowing to order them
+//     in time, but it is not necessary.
+//
+//
+// ===========================================================================
+//
+// ToDO:
+//   * Default paths could be moved into the global .rootrc
+//
+// ===========================================================================
+//
+//
+// Class Version 3:
+// ----------------
+//  + fFileName
+//  + fDataSet
+//
+// Class Version 2:
+// ----------------
+//  + fMonteCarlo
+//  + fWobbleMode
+//  - fIsWobbleMode
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataSet.h"
+
+#include <string.h>  // necessary for Fedora core 2 with kernel 2.6.9-1.667 #1 and gcc 3.4.2
+#include <errno.h>   // necessary for Fedora core 2 with kernel 2.6.9-1.667 #1 and gcc 3.4.2
+
+#include <stdlib.h>
+#include <fstream>
+
+#include <TEnv.h>
+#include <TChain.h>
+#include <TRegexp.h>
+#include <TSystem.h> // TSystem::ExpandPath
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRead.h"
+#include "MJob.h"
+#include "MEnv.h"
+#include "MAstro.h"
+#include "MString.h"
+#include "MDirIter.h"
+#include "MSequence.h"
+#include "MPointingPos.h"
+
+ClassImp(MDataSet);
+
+using namespace std;
+
+const TString MDataSet::fgCatalog = "/magic/datacenter/setup/magic_favorites.edb";
+
+// --------------------------------------------------------------------------
+//
+// Copy the sequence numbers from the TString runs into the TArrayI data
+// Sequences which are twice in the list are only added once. In this case
+// a warning is emitted.
+//
+void MDataSet::Split(TString &runs, TArrayI &data) const
+{
+    const TRegexp regexp("[0-9]+");
+
+    data.Set(0);
+
+    runs.ReplaceAll("\t", " ");
+    runs = runs.Strip(TString::kBoth);
+
+    while (!runs.IsNull())
+    {
+        const TString num = runs(regexp);
+
+        if (num.IsNull())
+        {
+            *fLog << warn << "WARNING - Sequence is NaN (not a number): '" << runs << "'" << endl;
+            break;
+        }
+
+        const Int_t seq = atoi(num.Data());
+        const Int_t n   = data.GetSize();
+
+        // skip already existing entries
+        int i;
+        for (i=0; i<n; i++)
+            if (data[i] == seq)
+                break;
+
+        if (i<n)
+            *fLog << warn << "WARNING - Sequence #" << seq << " already in list... skipped." << endl;
+        else
+        {
+            // set new entry
+            data.Set(n+1);
+            data[n] = seq;
+        }
+
+        // remove entry from string
+        runs.Remove(0, runs.First(num)+num.Length());
+    }
+
+    MJob::SortArray(data);
+}
+
+// --------------------------------------------------------------------------
+//
+// After resolving the sequence filename and directory either from the
+// default (/magic/data/sequences/0004/sequence00004000.txt) or from
+// the corresponding entries in the dataset file.
+// The entries are sorted by filename.
+//
+void MDataSet::ResolveSequences(const TEnv &env, const TString &prefix, const TArrayI &num, TList &list) const
+{
+    TString sequences = fPathSequences;
+    TString data      = fPathDataFiles;
+
+    for (int i=0; i<num.GetSize(); i++)
+    {
+        TString name = GetEnvValue3(env, prefix, "Sequence%d.File",    num[i]);
+        TString dir  = GetEnvValue3(env, prefix, "Sequence%d.Dir",     num[i]);
+        TString excl = GetEnvValue3(env, prefix, "Sequence%d.Exclude", num[i]);
+
+        // Set default sequence file and dir name
+        if (name.IsNull())
+            name = MString::Format("%s%04d/sequence%08d.txt", sequences.Data(), num[i]/10000, num[i]);
+        if (dir.IsNull())
+            dir = MString::Format("%s%04d/%08d", data.Data(), num[i]/10000, num[i]);
+
+        // Check if sequence information is contained in Dataset file
+        const Bool_t useds = name=="-";
+
+        // FIXME: The sequence number from the sequence file is assigned!!!
+        MSequence *seq = new MSequence(useds?fFileName:name, dir, num[i]);
+        seq->ExcludeRuns(excl);
+
+        if (seq->IsValid() && seq->GetSequence()!=(UInt_t)num[i])
+            *fLog << warn << "WARNING - Sequence number " << num[i] << " in dataset file doesn't match number " << seq->GetSequence() << " in sequence file!" << endl;
+
+        list.Add(seq);
+    }
+
+    // For the synchronization we must make sure, that all sequences are
+    // in the correct order...
+    // list.Sort();
+}
+
+Bool_t MDataSet::GetWobbleMode(const TEnv &env, const TString &prefix) const
+{
+    TString wob = GetEnvValue2(env, prefix, "WobbleMode", "auto");
+
+    wob.ToLower();
+    wob=wob.Strip(TString::kBoth);
+
+    if (wob=="auto")
+        return !HasOffSequences();
+
+    return GetEnvValue2(env, prefix, "WobbleMode", kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a dataset from the file fname. If num is != -1 all resources are
+// prefixed with the number. This allows constrcutions like:
+//
+//   89123.SequencesOn: 1 2 3 4
+//   89130.SequencesOn: 5 6 7 8
+//
+// For one dataset:
+//
+//   89123.DataPath: /magic/data/star
+//
+// For all other datasets:
+//
+//   DataPath: /magic/data/star
+//
+// For one sequence of one datasets:
+//
+//   89123.Sequence00000002.Dir: /magic/data/star
+//
+// and therefore allows storage of several datsets in one file with
+// a defaults for non specific resources.
+//
+// sequences and data are the path to the sequences (/magic/sequences)
+// and the data (/magic/data/star) respectively. Both can be overwritten
+// be a default from the dataset file or a resource for an individual
+// sequence.
+//
+void MDataSet::Init(const char *fname, const UInt_t num, TString sequences, TString &data)
+{
+    fName  = "MDataSet";
+    fTitle = "DataSet file";
+
+    // Store given file name as name
+    fFileName = fname;
+
+    // Delete the stored Sequences automatically at destruction
+    fSequencesOn.SetOwner();
+    fSequencesOff.SetOwner();
+
+    // Expand the file name (eg $MARS or ~ are expanded)
+    gSystem->ExpandPathName(fFileName);
+
+    // Check its accessibility
+    const Bool_t access = !gSystem->AccessPathName(fFileName, kFileExists);
+    if (!access)
+    {
+        gLog << err << "ERROR - Dataset file " << fname << " not accessible!" << endl;
+        fNumAnalysis = (UInt_t)-1;
+        return;
+    }
+
+    // Determin the prefix to access this resource
+    const TString prefix = num==(UInt_t)-1 ? "" : MString::Format("%d", num);
+
+    // Open and read the file
+    MEnv env(fFileName);
+
+    // Get analysis number and name
+    fNumAnalysis = GetEnvValue2(env, prefix, "AnalysisNumber", (Int_t)num);
+    fDataSet     = GetEnvValue2(env, prefix, "Name", GetBaseName());
+
+    // Get sequences from file
+    TString str;
+    str = GetEnvValue2(env, prefix, "SequencesOn",  "");
+    Split(str, fNumSequencesOn);
+    str = GetEnvValue2(env, prefix, "SequencesOff", "");
+    Split(str, fNumSequencesOff);
+
+    // Get other resources
+    fNameSource   = GetEnvValue2(env, prefix, "SourceName", "");
+    fCatalog      = GetEnvValue2(env, prefix, "Catalog",    fgCatalog);
+    fMonteCarlo   = GetEnvValue2(env, prefix, "MonteCarlo", kFALSE);
+    fComment      = GetEnvValue2(env, prefix, "Comment",    "");
+
+    fWobbleMode   = GetWobbleMode(env, prefix); // needs the number of off sequences
+
+    fNameSource = fNameSource.Strip(TString::kBoth);
+    fCatalog    = fCatalog.Strip(TString::kBoth);
+
+    // Check for sequence and data path (GetDefPath needs the monte carlo flag)
+    const TString defpathseq  = GetEnvValue2(env, prefix, "SequencePath", GetDefPathSequences());
+    const TString defpathdata = GetEnvValue2(env, prefix, "DataPath",     GetDefPathDataFiles());
+
+    SetupDefaultPath(sequences, defpathseq);
+    SetupDefaultPath(data,      defpathdata);
+
+    fPathSequences = sequences;
+    fPathDataFiles = data;
+
+    // Resolve sequences
+    ResolveSequences(env, prefix, fNumSequencesOn,  fSequencesOn);
+    ResolveSequences(env, prefix, fNumSequencesOff, fSequencesOff);
+
+    // --- Now "touch" resources which are not yet stored in MDataSet ---
+    env.Touch("RunTime");
+
+    // --- Print "untouch" resources ---
+    if (env.GetNumUntouched()>0)
+    {
+        gLog << warn << "WARNING - At least one resource in the dataset-file has not been touched!" << endl;
+        env.PrintUntouched();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. See Read for more details.
+//
+MDataSet::MDataSet(const char *fname, TString sequences, TString data)
+{
+    Init(fname, (UInt_t)-1, sequences, data);
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. See Read for more details.
+//
+MDataSet::MDataSet(const char *fname, Int_t num, TString sequences, TString data)
+{
+    Init(fname, num, sequences, data);
+}
+
+//---------------------------------------------------------------------------
+//
+// Return the name of the file
+//
+const char *MDataSet::GetBaseName() const
+{
+    return gSystem->BaseName(fFileName);
+}
+
+//---------------------------------------------------------------------------
+//
+// Return the directory of the file
+//
+const char *MDataSet::GetFilePath() const
+{
+    return gSystem->DirName(fFileName);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return '+' if both can be accessed, '-' otherwise.
+//
+void MDataSet::PrintFile(ostream &out, const MSequence &seq)
+{
+    const Char_t access =
+        !gSystem->AccessPathName(seq.GetFileName(), kFileExists) &&
+        !gSystem->AccessPathName(seq.GetDataPath(), kFileExists) ? '+' : '-';
+
+    out << "#  " << access << " " << seq.GetFileName() << " <" << seq.GetDataPath() << ">" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Helper to print a seqeunce in Print()
+//
+void MDataSet::PrintSeq(ostream &out, const MSequence &seq) const
+{
+    const Bool_t useds = seq.GetFileName()==fFileName;
+
+    out << "Sequence" << MString::Format("%08d", seq.GetSequence()) << ".File:   " << (useds?"-":seq.GetFileName()) << endl;
+    out << "Sequence" << MString::Format("%08d", seq.GetSequence()) << ".Dir:    " << seq.GetDataPath() << endl;
+    if (!useds && seq.GetNumExclRuns()>0)
+        out << "Sequence" << MString::Format("%08d", seq.GetSequence()) << ".Exclude: " << seq.GetExcludedRuns() << endl;
+
+    if (useds)
+    {
+        out << endl;
+        seq.Print(out, "prefixed");
+        out << endl << "# ---" << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the dataset to the ostream out
+//
+void MDataSet::Print(ostream &out, Option_t *o) const
+{
+    if (!IsValid())
+    {
+        out << "Dataset: " << fFileName << " <invalid - no analysis number available>" << endl;
+        return;
+    }
+    out << "# Path: " << GetFilePath() << endl;
+    out << "# Name: " << GetBaseName() << endl;
+    out << endl;
+    out << "AnalysisNumber: " << fNumAnalysis << endl << endl;
+
+    if (!fDataSet.IsNull())
+        out << "Name: " << fDataSet << endl << endl;
+
+    out << "SequencesOn:   ";
+    for (int i=0; i<fNumSequencesOn.GetSize(); i++)
+        out << " " << fNumSequencesOn[i];
+    out << endl;
+    if (fNumSequencesOff.GetSize()>0)
+    {
+        out << "SequencesOff:  ";
+        for (int i=0; i<fNumSequencesOff.GetSize(); i++)
+            out << " " << fNumSequencesOff[i];
+        out << endl;
+    }
+
+    out << endl;
+    if (!fNameSource.IsNull())
+        out << "SourceName: " << fNameSource << endl;
+    out << "Catalog: " << fCatalog << endl;
+
+    out << "WobbleMode: " << (fWobbleMode?"Yes":"No") << endl << endl;
+    out << "MonteCarlo: " << (fMonteCarlo?"Yes":"No") << endl << endl;
+
+    if (!fComment.IsNull())
+        out << "Comment: " << fComment << endl;
+
+    if (fSequencesOn.GetEntries()>0)
+        out << endl;
+
+    // FIXME: If file==fName --> print Sequence0000.content
+
+    TIter NextOn(&fSequencesOn);
+    TIter NextOff(&fSequencesOff);
+    MSequence *seq=0;
+    while ((seq=(MSequence*)NextOn()))
+        PrintSeq(out, *seq);
+    if (fSequencesOff.GetEntries()>0)
+        out << endl;
+    while ((seq=(MSequence*)NextOff()))
+        PrintSeq(out, *seq);
+
+    if (TString(o).Contains("files", TString::kIgnoreCase))
+    {
+        out << endl;
+        out << "# On-Data Files:" << endl;
+        NextOn.Reset();
+        while ((seq=(MSequence*)NextOn()))
+            PrintFile(out, *seq);
+
+        out << endl;
+        out << "# Off-Data Files:" << endl;
+        NextOff.Reset();
+        while ((seq=(MSequence*)NextOff()))
+            PrintFile(out, *seq);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the dataset to the gLog stream
+//
+void MDataSet::Print(Option_t *o) const
+{
+    gLog << all;
+    Print(gLog, o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the dataset to the file with name filename
+//
+void MDataSet::WriteFile(const char *name, const Option_t *o) const
+{
+    ofstream fout(name);
+    if (!fout)
+    {
+        gLog << err << "Cannot open file " << name << ": ";
+        gLog << strerror(errno) << endl;
+        return;
+    }
+
+    Print(fout, o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds all sequences contained in list to the MDirIter. After adding
+// everything MDirIter::Sort is called to sort all entries by name.
+//
+Bool_t MDataSet::AddSequencesFromList(const TList &list, MDirIter &files)
+{
+    TIter Next(const_cast<TList*>(&list));
+
+    MSequence *seq=0;
+    while ((seq=(MSequence*)Next()))
+    {
+        if (!seq->IsValid())
+        {
+            gLog << err;
+            gLog << "ERROR - MDataSet::AddSequencesFromList: Sequence invalid!" << endl;
+            gLog << "  + File: " << seq->GetFileName() << endl;
+            gLog << "  + Dir:  " << seq->GetDataPath() << endl;
+            return kFALSE;
+        }
+
+        if (seq->GetRuns(files, MSequence::kImages)<=0)
+            return kFALSE;
+    }
+
+    // This is important in case of synchronisation, because the
+    // files in the sequences can be interleaved (eg W1, W2)
+    // Filenames MUST begin with an appropriate string which allow
+    // to order them correctly in time!
+    // files.Sort();
+
+    if (gLog.GetDebugLevel()>4)
+    {
+        gLog << inf << "Files which are searched:" << endl;
+        files.Print();
+    }
+    return kTRUE;
+}
+
+Bool_t MDataSet::AddFilesOn(MDirIter &iter) const
+{
+    return AddSequencesFromList(fSequencesOn, iter);
+}
+
+Bool_t MDataSet::AddFilesOff(MDirIter &iter) const
+{
+    return AddSequencesFromList(fSequencesOff, iter);
+}
+
+Bool_t MDataSet::AddFiles(MDirIter &iter) const
+{
+    const Bool_t rc1 = AddFilesOff(iter);
+    const Bool_t rc2 = AddFilesOn(iter);
+    return rc1 && rc2;
+}
+
+Bool_t MDataSet::AddFilesOn(MRead &read) const
+{
+    MDirIter files;
+    if (!AddFilesOn(files))
+        return kFALSE;
+    return read.AddFiles(files)>0;
+}
+
+Bool_t MDataSet::AddFilesOff(MRead &read) const
+{
+    MDirIter files;
+    if (!AddFilesOff(files))
+        return kFALSE;
+    return read.AddFiles(files)>0;
+}
+
+Bool_t MDataSet::AddFiles(MRead &read) const
+{
+    const Bool_t rc1 = AddFilesOff(read);
+    const Bool_t rc2 = AddFilesOn(read);
+    return rc1 && rc2;
+}
+
+Int_t MDataSet::AddFilesToChain(MDirIter &files, TChain &chain)
+{
+    Int_t num=0;
+    while (1)
+    {
+        const TString fname = files.Next();
+        if (fname.IsNull())
+            break;
+
+        const Int_t n = chain.Add(fname);
+        if (n<=0)
+            return kFALSE;
+        num += n;
+    }
+    return num;
+}
+
+Bool_t MDataSet::AddFilesOn(TChain &chain) const
+{
+    MDirIter files;
+    if (!AddSequencesFromList(fSequencesOn, files))
+        return kFALSE;
+    return AddFilesToChain(files, chain)>0;
+}
+
+Bool_t MDataSet::AddFilesOff(TChain &chain) const
+{
+    MDirIter files;
+    if (!AddSequencesFromList(fSequencesOff, files))
+        return kFALSE;
+    return AddFilesToChain(files, chain)>0;
+}
+
+Bool_t MDataSet::AddFiles(TChain &read) const
+{
+    const Bool_t rc1 = AddFilesOff(read);
+    const Bool_t rc2 = AddFilesOn(read);
+    return rc1 && rc2;
+}
+
+Bool_t MDataSet::GetSourcePos(MPointingPos &pos) const
+{
+    if (!HasSource())
+    {
+        gLog << err << "ERROR - MDataSet::GetSourcePos called, but no source available." << endl;
+        return kFALSE;
+    }
+
+    TString catalog(fCatalog);
+    gSystem->ExpandPathName(catalog);
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    TString ra, dec, epoch;
+
+    Int_t n = 0;
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+        {
+            gLog << err << "ERROR - Source '" << fNameSource << "' not found in " << catalog << "." << endl;
+            return kFALSE;
+        }
+
+        n++;
+
+        TObjArray *arr = line.Tokenize(",");
+
+        if (arr->GetEntries()<6)
+        {
+            gLog << err << "ERROR - Not enough arguments in line #" << n << " of " << catalog << endl;
+            delete arr;
+            return kFALSE;;
+        }
+
+        const TString name = (*arr)[0]->GetName();
+
+        ra    = (*arr)[2]->GetName();
+        dec   = (*arr)[3]->GetName();
+        epoch = (*arr)[5]->GetName();
+
+        delete arr;
+
+        if (name.Strip(TString::kBoth)==fNameSource)
+            break;
+    }
+
+    if (epoch.Strip(TString::kBoth)!=(TString)"2000")
+    {
+        gLog << err << "ERROR - Epoch not 2000... not supported." << endl;
+        return kFALSE;
+    }
+
+    Double_t r,d;
+    if (!MAstro::Coordinate2Angle(ra, r))
+    {
+        gLog << err << "ERROR - Interpreting right ascension: " << ra << endl;
+        return kFALSE;
+    }
+    if (!MAstro::Coordinate2Angle(dec, d))
+    {
+        gLog << err << "ERROR - Interpreting declination: " << dec << endl;
+        return kFALSE;
+    }
+
+    pos.SetSkyPosition(r, d);
+    pos.SetTitle(fNameSource);
+
+    return kTRUE;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Calls ReplaceAll(old, news) for all Dir-entries
+//
+void MDataSet::ReplaceDir(TList &list, const TString &old, const TString &news) const
+{
+    TIter Next(&list);
+    TNamed *name = 0;
+    while ((name=(TNamed*)Next()))
+    {
+        TString dir = name->GetTitle();
+        dir.ReplaceAll(old, news);
+        name->SetTitle(dir);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls ReplaceAll(old, news) for all File-entries
+//
+void MDataSet::ReplaceFile(TList &list, const TString &old, const TString &news) const
+{
+    TIter Next(&list);
+    TNamed *name = 0;
+    while ((name=(TNamed*)Next()))
+    {
+        TString file = name->GetName();
+        file.ReplaceAll(old, news);
+        name->SetName(file);
+    }
+}
+*/
Index: branches/Mars_McMismatchStudy/mjobs/MDataSet.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MDataSet.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MDataSet.h	(revision 17960)
@@ -0,0 +1,191 @@
+#ifndef MARS_MDataSet
+#define MARS_MDataSet
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class TChain;
+
+class MRead;
+class MDirIter;
+class MSequence;
+class MPointingPos;
+
+class MDataSet : public MParContainer
+{
+private:
+    static const TString fgCatalog; //! Default Catalog path
+
+    TString fFileName;        // File name to original file (MParContainer::fName is not streamed)
+    TString fDataSet;         // Name of the dataset given by the user
+
+    UInt_t  fNumAnalysis;     // Analysis number (artificial)
+
+    TString fPathSequences;   // Default path to the sequence files
+    TString fPathDataFiles;   // Default path to the data files
+
+    TArrayI fNumSequencesOn;  // numbers of on-sequences
+    TArrayI fNumSequencesOff; // numbers of off-sequences
+
+    TList   fSequencesOn;     // list of names and paths of on-sequences
+    TList   fSequencesOff;    // list of names and paths of off-sequences
+
+    TString fNameSource;      // Name of source from catalog
+    TString fCatalog;         // edb catalog (magic_favourites.edb)
+
+    TString fComment;         // Comment from DS file
+
+    Bool_t  fWobbleMode;      // Wobble Mode for this dataset?
+    Bool_t  fMonteCarlo;      // For default paths use MC or data path
+
+    // Helper functions for constrcutors
+    void Split(TString &runs, TArrayI &data) const;
+    void ResolveSequences(const TEnv &env, const TString &prefix, const TArrayI &num, TList &list/*, const TString &sequences, const TString &data*/) const;
+    Bool_t GetWobbleMode(const TEnv &env, const TString &prefix) const;
+    static void PrintFile(std::ostream &out, const MSequence &obj);
+    void PrintSeq(std::ostream &out, const MSequence &seq) const;
+
+    // Directory and file handling
+    //void ReplaceDir(TList &list, const TString &old, const TString &news) const;
+    //void ReplaceFile(TList &list, const TString &old, const TString &news) const;
+
+    void SetupDefaultPath(TString &path, const TString &def) const
+    {
+        if (path.IsNull())
+            path = def;
+        if (!path.EndsWith("/"))
+            path += "/";
+    }
+
+    Bool_t HasSequence(UInt_t num, const TArrayI &seq) const
+    {
+        for (int i=0; i<seq.GetSize(); i++)
+            if ((UInt_t)seq[i]==num)
+                return kTRUE;
+        return kFALSE;
+    }
+
+    // Initialize from constrcutors
+    void Init(const char *fname, const UInt_t num, TString sequences, TString &data);
+
+public:
+    MDataSet() : fNumAnalysis((UInt_t)-1)
+    {
+        fName  = "MDataSet";
+        fTitle = "DataSet file";
+    }
+    MDataSet(const char *fname, TString sequences="", TString data="");
+    MDataSet(const char *fname, Int_t num, TString sequences="", TString data="");
+
+    const char    *GetBaseName() const;
+    const char    *GetFilePath() const;
+    const TString &GetFileName() const { return fFileName; }
+    const TString &GetDataSet()  const { return fDataSet;  }
+
+    void Copy(TObject &obj) const
+    {
+        MDataSet &ds = (MDataSet&)obj;
+        ds.fNumAnalysis = fNumAnalysis;
+        ds.fNumSequencesOn = fNumSequencesOn;
+        ds.fNumSequencesOff = fNumSequencesOff;
+        ds.fNameSource = fNameSource;
+        ds.fCatalog = fCatalog;
+        ds.fComment = fComment;
+        ds.fWobbleMode = fWobbleMode;
+        ds.fMonteCarlo = fMonteCarlo;
+
+        TObject *o=0;
+
+        ds.fSequencesOn.Delete();
+        ds.fSequencesOff.Delete();
+
+        TIter NextOn(&fSequencesOn);
+        while ((o=NextOn()))
+            ds.fSequencesOn.Add(o->Clone());
+
+        TIter NextOff(&fSequencesOff);
+        while ((o=NextOff()))
+            ds.fSequencesOff.Add(o->Clone());
+    }
+
+    // Getter
+    Bool_t IsValid() const { return fNumAnalysis!=(UInt_t)-1 && GetNumSequencesOn()>0; }
+
+    UInt_t GetNumSequencesOn() const  { return fNumSequencesOn.GetSize(); }
+    UInt_t GetNumSequencesOff() const { return fNumSequencesOff.GetSize(); }
+
+    Bool_t HasOffSequences() const { return GetNumSequencesOff()>0; }
+
+    Bool_t HasOffSequence(UInt_t num) const { return HasSequence(num, fNumSequencesOff); }
+    Bool_t HasOnSequence(UInt_t num) const  { return HasSequence(num, fNumSequencesOn); }
+    Bool_t HasSequence(UInt_t num) const    { return HasOnSequence(num) || HasOffSequence(num); }
+
+    UInt_t GetNumAnalysis() const { return fNumAnalysis; }
+    void   SetNumAnalysis(UInt_t num) { fNumAnalysis=num; }
+
+    Bool_t HasSource() const { return !fNameSource.IsNull(); }
+    Bool_t GetSourcePos(MPointingPos &pos) const;
+
+    Bool_t IsWobbleMode() const { return fWobbleMode; }
+    Bool_t IsMonteCarlo() const { return fMonteCarlo; }
+
+    const char *GetDefPathDataFiles() const { return fMonteCarlo ? "/magic/montecarlo/star"      : "/magic/data/star"; }
+    const char *GetDefPathSequences() const { return fMonteCarlo ? "/magic/montecarlo/sequences" : "/magic/sequences"; }
+
+    // Setter
+    void SetMonteCarlo(Bool_t ismc=kTRUE) { fMonteCarlo=ismc; }
+    void SetWobbleMode(Bool_t wobm=kTRUE)  { fWobbleMode=wobm; }
+
+    static Bool_t AddSequencesFromList(const TList &list, MDirIter &files);
+    static Int_t  AddFilesToChain(MDirIter &files, TChain &chain);
+
+    const TList &GetSequencesOn() const  { return fSequencesOn; }
+    const TList &GetSequencesOff() const { return fSequencesOff; }
+
+    const TArrayI &GetSequencesNumOn() const  { return fNumSequencesOn; }
+    const TArrayI &GetSequencesNumOff() const { return fNumSequencesOff; }
+
+    Bool_t AddFiles(MRead &read) const;
+    Bool_t AddFilesOn(MRead &read) const;
+    Bool_t AddFilesOff(MRead &read) const;
+
+    Bool_t AddFiles(TChain &read) const;
+    Bool_t AddFilesOn(TChain &read) const;
+    Bool_t AddFilesOff(TChain &read) const;
+
+    Bool_t AddFiles(MDirIter &iter) const;
+    Bool_t AddFilesOn(MDirIter &iter) const;
+    Bool_t AddFilesOff(MDirIter &iter) const;
+
+    /*
+    void ReplaceDir(const TString &old, const TString &news)
+    {
+        ReplaceDir(fSequencesOn,  old, news);
+        ReplaceDir(fSequencesOff, old, news);
+    }
+
+    void ReplaceFile(const TString &old, const TString &news)
+    {
+        ReplaceFile(fSequencesOn,  old, news);
+        ReplaceFile(fSequencesOff, old, news);
+    }
+    */
+
+    // I/O
+    void WriteFile(const char *filename, const Option_t *o) const;
+    void WriteFile(const char *filename) const { WriteFile(filename,""); } //*MENU *ARGS={filename=>fBaseName}
+
+    // TObject
+    void Print(std::ostream &out, Option_t *o) const;
+    void Print(Option_t *o) const;
+    void Print() const { Print(""); } //*MENU*
+
+    ClassDef(MDataSet, 3)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJCalib.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalib.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalib.cc	(revision 17960)
@@ -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): Markus Gaug, 2/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalib
+//
+// A base class for the calibration jobs
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalib.h"
+
+ClassImp(MJCalib);
+
+using namespace std;
+
+const Int_t MJCalib::fgCheckedPixId = 100;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fDataFlag      to kIsUseRootData
+// - fCheckedPixId  to fgCheckedPixId
+// - fPixelCheck    to kFALSE
+// - fPulsePosCheck to kFALSE
+//
+MJCalib::MJCalib() : fStorage(0), fIsPixelCheck(kFALSE), fIsPulsePosCheck(kFALSE)
+{
+  SetUseBlindPixel(kFALSE);
+  SetUsePINDiode(kFALSE);
+
+  SetCheckedPixId();
+}
+
+Bool_t MJCalib::CheckEnvLocal()
+{
+    SetPixelCheck(GetEnv("PixelCheck", fIsPixelCheck));
+    SetPulsePosCheck(GetEnv("PulsePosCheck", fIsPulsePosCheck));
+    SetCheckedPixId(GetEnv("CheckedPixId",fCheckedPixId));
+
+    if (HasEnv("StorageType"))
+      {
+        TString type = GetEnv("StorageType", "");
+        type = type.Strip(TString::kBoth);
+        type.ToLower();
+
+        if (type == (TString)"hists")
+          SetHistsStorage();
+        
+        if (type == (TString)"no" || type == (TString)"nostorage")
+          SetNoStorage();
+      }
+
+    if (!HasEnv("DataType"))
+        return kTRUE;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJCalib.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalib.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalib.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MJCalib
+#define MARS_MJCalib
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MRunIter;
+
+class MJCalib : public MJob
+{
+public:
+
+private:
+
+    static const Int_t fgCheckedPixId;  //! Default for fCheckedPixId
+
+    enum  Storage_t                     // Possible devices for calibration
+      {
+        kNoStorage,
+        kHistsStorage
+      };                                // Possible flags for the storage of results
+
+    Byte_t fStorage;                    // Bit-field for chosen storage type
+
+    enum  Device_t                                       // Possible devices for calibration
+    {
+        kUseBlindPixel,
+        kUsePINDiode
+    };
+
+    Byte_t fDevices;                                     // Bit-field for used devices for calibration
+
+protected:
+
+    Bool_t fIsPixelCheck;               // Check a test pixel?
+    Int_t  fCheckedPixId;               // ID of checked pixel
+
+    Bool_t fIsPulsePosCheck;            // Check pulse position?
+
+    Bool_t CheckEnvLocal();
+
+    Bool_t IsNoStorage    () const { return TESTBIT(fStorage,kNoStorage);    }
+    Bool_t IsHistsStorage () const { return TESTBIT(fStorage,kHistsStorage); }
+
+public:
+    MJCalib();
+
+    Bool_t IsUseBlindPixel() const { return TESTBIT(fDevices,kUseBlindPixel); }
+    Bool_t IsUsePINDiode  () const { return TESTBIT(fDevices,kUsePINDiode);   }
+
+    void SetCheckedPixId ( const Int_t  i=fgCheckedPixId ) { fCheckedPixId  = i; }
+
+    void SetNoStorage    ( const Bool_t b=kTRUE ) { b ? SETBIT(fStorage,kNoStorage)    : CLRBIT(fStorage,kNoStorage); }
+    void SetHistsStorage ( const Bool_t b=kTRUE ) { b ? SETBIT(fStorage,kHistsStorage) : CLRBIT(fStorage,kHistsStorage); }
+
+    void SetPixelCheck     ( const Bool_t b=kTRUE )  { fIsPixelCheck        = b; }
+    void SetPulsePosCheck  ( const Bool_t b=kTRUE )  { fIsPulsePosCheck     = b; }
+
+    void SetUseBlindPixel(const Bool_t b=kTRUE) { b ? SETBIT(fDevices,kUseBlindPixel) : CLRBIT(fDevices,kUseBlindPixel); }
+    void SetUsePINDiode(const Bool_t b=kTRUE)   { b ? SETBIT(fDevices,kUsePINDiode) : CLRBIT(fDevices,kUsePINDiode); }
+
+    ClassDef(MJCalib, 0) // Base class for calibration jobs
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJCalibTest.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalibTest.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalibTest.cc	(revision 17960)
@@ -0,0 +1,535 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalibTest
+//
+// If the flag SetDataCheckDisplay() is set, only the most important distributions
+//  are displayed. 
+// Otherwise, (default: SetNormalDisplay()), a good selection of plots is given
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibTest.h"
+
+#include <TFile.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MTaskEnv.h"
+#include "MEvtLoop.h"
+
+#include "MHCamera.h"
+
+#include "MSignalCam.h"
+#include "MPedestalCam.h"
+#include "MPedPhotCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsTreat.h"
+#include "MBadPixelsCalc.h"
+#include "MBadPixelsMerge.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationTestCam.h"
+#include "MCalibrationTestCalc.h"
+#include "MHCamEvent.h"
+#include "MHCalibrationTestCam.h"
+#include "MHCalibrationTestTimeCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MReadMarsFile.h"
+#include "MRawFileRead.h"
+#include "MGeomApply.h"
+#include "MGeomCam.h"
+#include "MExtractTimeAndChargeSpline.h"
+#include "MExtractor.h"
+#include "MExtractTime.h"
+//#include "MExtractTimeFastSpline.h"
+#include "MFCosmics.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MCalibrateData.h"
+#include "MCalibrateRelTimes.h"
+
+#include "MTriggerPattern.h"
+#include "MTriggerPatternDecode.h"
+#include "MFTriggerPattern.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MJCalibTest);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fUseCosmicsFilter to kTRUE, fExtractor to NULL, fTimeExtractor to NULL
+// fDisplay to kNormalDisplay
+//
+MJCalibTest::MJCalibTest(const char *name, const char *title) 
+    : fUseCosmicsFilter(kTRUE), fExtractor(NULL), fTimeExtractor(NULL),
+      fDisplayType(kNormalDisplay), fGeometry("MGeomCamMagic")
+{
+    fName  = name  ? name  : "MJCalibTest";
+    fTitle = title ? title : "Tool to extract, calibrate and test signals from a file";
+}
+
+
+void MJCalibTest::DisplayResult(MParList &plist)
+{
+  if (!fDisplay)
+    return;
+  
+  //
+  // Get container from list
+  //
+  MGeomCam  &geomcam = *(MGeomCam*) plist.FindObject("MGeomCam");
+  MHCalibrationTestCam &testcam = *(MHCalibrationTestCam*)plist.FindObject("MHCalibrationTestCam");
+  
+  // Create histograms to display
+  MHCamera disp1 (geomcam, "Test;PhotoElectrons",    "Mean equiv. phes");
+  MHCamera disp2 (geomcam, "Test;SigmaPhes",         "Sigma equiv.phes");
+  MHCamera disp3 (geomcam, "Test;PhesPerArea",       "Equiv. Phes per Area");
+  MHCamera disp4 (geomcam, "Test;SigmaPhotPerArea",  "Sigma equiv. Phes per Area");
+  MHCamera disp5 (geomcam, "Test;Phot",              "Calibrated Phes from Fit");
+  MHCamera disp6 (geomcam, "Test;PhotPerArea",       "Calibrated Phes per Area from Fit");
+  MHCamera disp7 (geomcam, "Test;NotInterpolate",    "Not interpolated pixels");
+  MHCamera disp8 (geomcam, "Test;DeviatingPhots",    "Deviating Number Phes");
+  MHCamera disp9 (geomcam, "Test;Arr.Times",         "Mean of calibrated Arr.Times");
+  MHCamera disp10(geomcam, "Test;SigmaArr.Times",    "Sigma of calibrated Arr.Times");
+
+  // Fitted charge means and sigmas
+  disp1.SetCamContent(testcam,  0);
+  disp1.SetCamError(  testcam,  1);
+  disp2.SetCamContent(testcam,  2);
+  disp2.SetCamError(  testcam,  3);
+  disp3.SetCamContent(testcam,  7);
+  disp3.SetCamError(  testcam,  8);
+  disp4.SetCamContent(testcam,  9);
+  disp4.SetCamError(  testcam,  10);
+
+  disp5.SetCamContent(fTestCam,  0);
+  disp5.SetCamError(  fTestCam,  1);
+  disp6.SetCamContent(fTestCam,  2);
+  disp6.SetCamError(  fTestCam,  3);
+  disp7.SetCamError(  fTestCam,  4);
+
+  disp8.SetCamError(  fBadPixels, 22);
+
+  disp9.SetCamContent(fTestTimeCam,  0);
+  disp9.SetCamError(  fTestTimeCam,  1);
+  disp10.SetCamContent(fTestTimeCam,  2);
+  disp10.SetCamError(  fTestTimeCam,  3);
+
+
+  disp1.SetYTitle("Phes");
+  disp2.SetYTitle("\\sigma_{phe}");
+  disp3.SetYTitle("Phes per area [mm^{-2}]");
+  disp4.SetYTitle("\\sigma_{phe} per area [mm^{-2}]");
+
+  disp5.SetYTitle("Phes");
+  disp6.SetYTitle("Phes per area [mm^{-2}]");
+  disp7.SetYTitle("[1]");
+  disp8.SetYTitle("[1]");
+  
+  disp9.SetYTitle("Mean Arr.Times [FADC units]");
+  disp10.SetYTitle("\\sigma_{t} [FADC units]");
+  
+  TCanvas &c = fDisplay->AddTab("TestPhes");
+  c.Divide(4,4);
+  
+  disp1.CamDraw(c, 1, 4, 2, 1);
+  disp2.CamDraw(c, 2, 4, 2, 1);        
+  disp3.CamDraw(c, 3, 4, 1, 1);        
+  disp4.CamDraw(c, 4, 4, 2, 1);        
+  
+  /*
+
+  TCanvas &c2 = fDisplay->AddTab("TestResult");
+  c2.Divide(2,4);
+
+  disp5.CamDraw(c2, 1, 2, 2, 1);
+  disp6.CamDraw(c2, 2, 2, 2, 1);        
+
+  */
+
+  TCanvas &c3 = fDisplay->AddTab("TestDefects");
+  c3.Divide(2,2);
+
+  disp7.CamDraw(c3, 1, 2, 0);
+  disp8.CamDraw(c3, 2, 2, 0);        
+
+  //
+  // Display times
+  // 
+  TCanvas &c4 = fDisplay->AddTab("TestTimes");
+  c4.Divide(2,4);
+
+  disp9.CamDraw(c4, 1, 2,  5, 1);
+  disp10.CamDraw(c4, 2, 2,  5, 1);        
+
+  return;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieve the output file written by WriteResult()
+// 
+const char* MJCalibTest::GetOutputFile() const
+{
+    return Form("%s/calib%08d.root", fPathOut.Data(), fSequence.GetSequence());
+}
+
+Bool_t MJCalibTest::ReadCalibration(TObjArray &l, MBadPixelsCam &cam, MExtractor* &ext1, MExtractor* &ext2, TString &geom) const
+{
+
+  const TString fname = GetOutputFile();
+  
+  *fLog << inf << "Reading from file: " << fname << endl;
+
+  TFile file(fname, "READ");
+  if (!file.IsOpen())
+    {
+      *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+      return kFALSE;
+    }
+  
+  TObject *o = file.Get("ExtractSignal");
+  if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+      *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+      return kFALSE;
+    }
+  ext1 = o ? (MExtractor*)o->Clone() : NULL;
+  
+  o = file.Get("ExtractTime");
+  if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+      *fLog << err << dbginf << "ERROR - ExtractTime read from " << fname << " doesn't inherit from MExtractor!" << endl;
+      return kFALSE;
+    }
+  ext2 = o ? (MExtractor*)o->Clone() : NULL;
+  if (!ext1 && !ext2)
+    {
+      *fLog << err << dbginf << "ERROR - Neither ExtractSignal nor ExrtractTime found in " << fname << "!" << endl;
+      return kFALSE;
+    }
+  
+  o = file.Get("MGeomCam");
+  if (o && !o->InheritsFrom(MGeomCam::Class()))
+    {
+      *fLog << err << dbginf << "ERROR - MGeomCam read from " << fname << " doesn't inherit from MGeomCam!" << endl;
+      return kFALSE;
+    }
+  geom = o ? o->ClassName() : "";
+  
+  TObjArray cont(l);
+  cont.Add(&cam);
+  return ReadContainer(cont);
+}
+
+Bool_t MJCalibTest::Process(MPedestalCam &pedcam)
+{
+    if (!fSequence.IsValid())
+    {
+	  *fLog << err << "ERROR - Sequence invalid..." << endl;
+	  return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate calibration test from Sequence #";
+    *fLog << fSequence.GetSequence() << endl << endl;
+
+  CheckEnv();
+  
+  *fLog << inf;
+  fLog->Separator(GetDescriptor());
+  
+  *fLog << "Calibrate Calibration data from ";
+  *fLog << "Sequence #" << fSequence.GetSequence() << endl;
+  *fLog << endl;
+  
+  MDirIter iter;
+
+  if (fSequence.IsValid())
+    {
+        if (fSequence.SetupCalRuns(iter, 0, !fSequence.IsMonteCarlo())<=0)
+            return kFALSE;
+    }
+  
+  MCalibrationChargeCam      calcam;
+  MCalibrationQECam          qecam;
+  MCalibrationRelTimeCam     tmcam;
+  MBadPixelsCam              badpix;
+  
+  TObjArray calibcont;
+  calibcont.Add(&calcam);
+  calibcont.Add(&qecam);
+  calibcont.Add(&tmcam);
+    
+  MExtractor *extractor1=0;
+  MExtractor *extractor2=0;
+  TString geom;
+
+  if (!ReadCalibration(calibcont, badpix, extractor1, extractor2, geom))
+    {
+      *fLog << err << "Could not read calibration constants " << endl;
+      return kFALSE;
+    }
+  
+  *fLog << all;
+  if (extractor1)
+    {
+      *fLog << underline << "Signal Extractor found in calibration file" << endl;
+      extractor1->Print();
+      *fLog << endl;
+    }
+  else
+    *fLog << inf << "No Signal Extractor: ExtractSignal in file." << endl;
+  
+  if (extractor2)
+    {
+      *fLog << underline << "Time Extractor found in calibration file" << endl;
+      extractor2->Print();
+      *fLog << endl;
+    }
+  else
+    *fLog << inf << "No Time Extractor: ExtractTime in file." << endl;
+  
+  if (!geom.IsNull())
+    *fLog << inf << "Camera geometry found in file: " << geom << endl;
+  else
+    *fLog << inf << "No Camera geometry found using default <MGeomCamMagic>" << endl;
+
+  if (fExtractor)
+    extractor1 = fExtractor;
+  if (fTimeExtractor)
+    extractor2 = fTimeExtractor;
+
+  // Setup Lists
+  MParList plist;
+  plist.AddToList(this); // take care of fDisplay!
+  plist.AddToList(&fTestCam);
+  plist.AddToList(&fTestTimeCam);
+  plist.AddToList(&badpix);
+  plist.AddToList(&pedcam);
+  plist.AddToList(&calcam);
+  plist.AddToList(&qecam);
+  plist.AddToList(&tmcam);
+
+  MSignalCam           cerphot;
+  MPedPhotCam          pedphot;
+  MHCalibrationTestCam testcam;
+
+  plist.AddToList(&cerphot);
+  plist.AddToList(&pedphot);
+  plist.AddToList(&testcam);
+
+  pedcam.SetName("MPedestalFundamental");
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  // Setup Task-lists
+  MRawFileRead rawread(NULL);
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+
+  if (!fSequence.IsMonteCarlo())
+    rawread.AddFiles(iter);
+  else
+    static_cast<MRead&>(read).AddFiles(iter);
+
+  // Check for interleaved events
+  // This will make that for data with version less than 5, where trigger
+  // patterns were not yet correct, all the events in the file will be
+  // processed. For those data there are no interleaved calibration events,
+  // so it makes no sense to run this test on a _D_ file. So we assume it
+  // will be a _C_ file, and accept all events.
+  MTriggerPatternDecode decode;
+  MFTriggerPattern      fcalib;
+  fcalib.DenyCalibration();
+  fcalib.SetDefault(kFALSE);
+  MContinue conttp(&fcalib, "ContTrigPattern");
+
+  MGeomApply            apply; // Only necessary to craete geometry
+  if (!geom.IsNull())
+    apply.SetGeometry(geom);  
+  MBadPixelsMerge       merge(&badpix);
+
+//  MExtractTimeAndChargeSlidingWindow extrsw;
+//  MExtractTimeFastSpline             extime;
+
+  MExtractTimeAndChargeSpline spline;
+
+  MTaskEnv taskenv1("ExtractSignal");
+  MTaskEnv taskenv2("ExtractTime");
+
+  if (extractor1)
+      taskenv1.SetDefault(extractor1);
+
+  if (extractor2)
+      taskenv2.SetDefault(fTimeExtractor);
+  else if (!(extractor1->InheritsFrom("MExtractTimeAndCharge")))
+    {
+      spline.SetWindowSize(8,8);
+      taskenv2.SetDefault(&spline);
+      *fLog << warn << GetDescriptor() 
+            << ": No extractor has been chosen, take default MExtractTimeAndChargeSlidingWindow " << endl;
+    }
+
+
+  MCalibrateData        photcalc;
+  photcalc.AddPedestal("Fundamental");
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);
+  photcalc.SetPedestalFlag(MCalibrateData::kEvent);
+  photcalc.SetSignalType(MCalibrateData::kPhe);
+
+  MCalibrateRelTimes    caltimes;
+  MBadPixelsCalc        badcalc;
+  MBadPixelsTreat       badtreat;
+  badtreat.SetProcessTimes(kFALSE);
+
+  badcalc.SetNamePedPhotCam("MPedPhotFundamental");
+  badtreat.SetUseInterpolation();
+  badtreat.AddNamePedPhotCam("MPedPhotFundamental");
+
+  MCalibrationTestCalc  testcalc;
+
+  MHCamEvent evt0(0,"Signal", "Un-Calibrated Signal;;S [FADC cnts]" );
+  MHCamEvent evt1(0,"CalSig", "Cal. and Interp. Sig. by Pixel Size Ratio;;S [phe]");
+  MHCamEvent evt2(6,"Times" , "Arrival Time;;T [slice]");
+
+  MFillH fill0(&evt0, "MExtractedSignalCam", "FillUncalibrated");
+  MFillH fill1(&evt1, "MSignalCam", "FillCalibrated");
+  MFillH fill2(&evt2, "MSignalCam", "FillTimes");
+  
+  MFillH fillcam("MHCalibrationTestCam",     "MSignalCam" ,"FillTest");
+  MFillH filltme("MHCalibrationTestTimeCam", "MSignalCam", "FillTestTime");
+  fillcam.SetBit(MFillH::kDoNotDisplay);
+  filltme.SetBit(MFillH::kDoNotDisplay);
+
+  MFCosmics cosmics;
+  cosmics.SetNamePedestalCam("MPedestalFundamental");
+  MContinue contcos(&cosmics,"ContCosmics");
+  
+  tlist.AddToList(&read);
+  tlist.AddToList(&decode);
+  tlist.AddToList(&apply);
+  tlist.AddToList(&merge);
+  //  tlist.AddToList(&conttp);
+  tlist.AddToList(&taskenv1);
+  if (!extractor1->InheritsFrom("MExtractTimeAndCharge"))
+    tlist.AddToList(&taskenv2);
+
+  tlist.AddToList(&contcos);
+  tlist.AddToList(&fill0);
+  tlist.AddToList(&photcalc);
+  tlist.AddToList(&caltimes);
+  tlist.AddToList(&badcalc);
+  tlist.AddToList(&badtreat);
+  tlist.AddToList(&fill1);
+  tlist.AddToList(&fill2);
+  tlist.AddToList(&fillcam);
+  tlist.AddToList(&filltme);
+  tlist.AddToList(&testcalc);
+  
+  // Create and setup the eventloop
+  MEvtLoop evtloop(fName);
+  evtloop.SetParList(&plist);
+  evtloop.SetDisplay(fDisplay);
+  evtloop.SetLogStream(fLog);
+  
+  // Execute first analysis
+  if (!evtloop.Eventloop())
+    {
+      *fLog << err << GetDescriptor() << ": Failed." << endl;
+      return kFALSE;
+    }
+  
+  if (fIsPixelCheck)
+    {
+      MHCalibrationTestCam *hcam = (MHCalibrationTestCam*)plist.FindObject("MHCalibrationTestCam");
+      MHCalibrationPix &pix1 = (*hcam)[fCheckedPixId];
+      pix1.DrawClone("");
+      
+      MHCalibrationTestTimeCam *hccam = (MHCalibrationTestTimeCam*)plist.FindObject("MHCalibrationTestTimeCam");
+      MHCalibrationPix &pix11 = (*hccam)[fCheckedPixId];
+      pix11.DrawClone("");
+    }
+
+  DisplayResult(plist);
+
+  if (!WriteResult())
+    return kFALSE;
+
+  *fLog << inf << GetDescriptor() << ": Done." << endl;
+  
+  return kTRUE;
+}
+
+Bool_t MJCalibTest::WriteResult()
+{
+    
+    if (fPathOut.IsNull())
+        return kTRUE;
+    
+    const TString oname(GetOutputFile());
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+    
+    TFile file(oname, "UPDATE");
+    
+    if (fDisplay && fDisplay->Write()<=0)
+    {
+        *fLog << err << "Unable to write MStatusDisplay to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fTestCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MCalibrationTestCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fTestTimeCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MCalibrationTestCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJCalibTest.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalibTest.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalibTest.h	(revision 17960)
@@ -0,0 +1,81 @@
+#ifndef MARS_MJCalibTest
+#define MARS_MJCalibTest
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+#ifndef MARS_MCalibrationTestCam
+#include "MCalibrationTestCam.h"
+#endif
+#ifndef MARS_MHCalibrationTestTimeCam
+#include "MHCalibrationTestTimeCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class MParList;
+class MPedestalCam;
+class MCalibrationRelTimeCam;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MExtractor;
+class MExtractTime;
+
+class MJCalibTest : public MJCalib
+{
+private:
+
+  Bool_t  fUseCosmicsFilter;
+
+  MExtractor   *fExtractor;                  // Signal extractor
+  MExtractTime *fTimeExtractor;              // Arrival time extractor  
+  
+  MBadPixelsCam            fBadPixels;
+  MCalibrationTestCam      fTestCam;
+  MHCalibrationTestTimeCam fTestTimeCam;
+
+  enum  Display_t                                      // Possible Display types
+    {
+      kDataCheckDisplay,
+      kNormalDisplay
+    };
+  
+  Display_t fDisplayType;                              // Chosen Display type
+
+  TString fGeometry;
+  
+  void   DisplayResult(MParList &plist);
+
+  Bool_t WriteResult();
+  
+  Bool_t ReadCalibration(TObjArray &o, MBadPixelsCam &bpix,
+                         MExtractor* &ext1, MExtractor* &ext2, TString &geom) const;
+
+  const char* GetOutputFileName() const;
+
+public:
+
+  MJCalibTest(const char *name=NULL, const char *title=NULL);
+  
+  const char* GetOutputFile() const;
+  
+  MCalibrationTestCam      &GetTestCam()      { return fTestCam; }
+  MHCalibrationTestTimeCam &GetTestTimeCam()  { return fTestTimeCam; }  
+  const MBadPixelsCam &GetBadPixels()  const { return fBadPixels; }
+  
+  void SetExtractor(MExtractor* ext)              { fExtractor = ext; }
+  void SetTimeExtractor(MExtractTime* ext)         { fTimeExtractor = ext; }
+  void SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+  void SetUseCosmicsFilter( const Bool_t b )    { fUseCosmicsFilter = b;  }
+
+  // Displays
+  void SetDataCheckDisplay() { fDisplayType = kDataCheckDisplay; }
+  void SetNormalDisplay()    { fDisplayType = kNormalDisplay;    }
+  
+  Bool_t Process(MPedestalCam &pedcam);
+  
+  ClassDef(MJCalibTest, 0) // Tool to calibrate and test the calibration run itself
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJCalibrateSignal.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalibrateSignal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalibrateSignal.cc	(revision 17960)
@@ -0,0 +1,1072 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalibrateSignal
+//
+// This class is reading the output written by callisto. It calibrates
+// signal and time.
+//
+// The signal and time extractors are read from the callisto-output. In
+// pricipal you could overwrite these default using the resource file,
+// but this is NOT recommended!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibrateSignal.h"
+
+#include <TEnv.h>
+#include <TFile.h>
+
+// Core
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+// General containers
+#include "MGeomCam.h"
+#include "MBadPixelsCam.h"
+#include "MCalibConstCam.h"
+#include "MPedestalCam.h"
+#include "MArrivalTimeCam.h"
+
+// General histograms
+#include "MH3.h"
+#include "MHCamEvent.h"
+#include "MHVsTime.h"
+
+// Calibration containers
+#include "MCalibrationQECam.h"
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationChargePINDiode.h"
+
+// Calibration histograms
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationChargeBlindCam.h"
+#include "MHCalibrationChargePINDiode.h"
+#include "MHCalibrationRelTimeCam.h"
+
+// Tasks
+#include "MReadMarsFile.h"
+#include "MRawFileRead.h"
+#include "MTaskEnv.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MGeomApply.h"
+#include "MExtractTimeAndCharge.h"
+#include "MTriggerPatternDecode.h"
+#include "MCalibrationPatternDecode.h"
+#include "MCalibrationChargeCalc.h"
+#include "MCalibrationRelTimeCalc.h"
+#include "MCalibCalcFromPast.h"
+#include "MPedestalSubtract.h"
+#include "MPedCalcFromLoGain.h"
+#include "MCalibrateData.h"
+#include "MExtractPINDiode.h"
+#include "MExtractBlindPixel.h"
+#include "MCalibrateRelTimes.h"
+#include "MBadPixelsCalc.h"
+#include "MBadPixelsTreat.h"
+#include "MWriteRootFile.h"
+
+// Filter
+#include "MFTriggerPattern.h"
+#include "MFCosmics.h"
+#include "MFilterList.h"
+#include "MFDataPhrase.h"
+
+// Classes for writing movies
+#include "MFEvtNumber.h"
+#include "MMoviePrepare.h"
+#include "MMovieWrite.h"
+#include "MImgCleanStd.h"
+
+
+ClassImp(MJCalibrateSignal);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fIsInterlaced to kTRUE
+// - fIsRelTimesUpdate to kFALSE
+// - fIsHiLoCalibration to kFALSE
+//
+MJCalibrateSignal::MJCalibrateSignal(const char *name, const char *title)
+    : fExtractor(0), fIsInterlaced(kTRUE), fIsRelTimesUpdate(kTRUE), fIsMovieMode(kFALSE), fIsTestMode(kFALSE)
+{
+    fName  = name  ? name  : "MJCalibrateSignal";
+    fTitle = title ? title : "Tool to calibrate data";
+}
+
+MJCalibrateSignal::~MJCalibrateSignal()
+{
+    if (fExtractor)
+        delete fExtractor;
+}
+
+void MJCalibrateSignal::SetExtractor(const MExtractor *ext)
+{
+    if (fExtractor)
+        delete fExtractor;
+
+    fExtractor = ext ? (MExtractor*)ext->Clone() : NULL;
+}
+
+Bool_t MJCalibrateSignal::WriteResult() const
+{
+    if (IsNoStorage() || fIsMovieMode)
+        return kTRUE;
+
+    // FIXME: This is not nice because it will update the signal
+    // file always. Which might make the usage outside of
+    // callisto difficult.
+    TObjArray cont;
+    cont.Add(const_cast<TEnv*>(GetEnv()));
+    cont.Add(const_cast<MSequence*>(&fSequence));
+
+    TNamed cmdline("CommandLine", fCommandLine.Data());
+    cont.Add(&cmdline);
+
+    if (fDisplay)
+    {
+        TString title = "--  Calibrate Signal: ";
+        title += fSequence.GetSequence();
+        title += "  --";
+        fDisplay->SetTitle(title, kFALSE);
+
+        cont.Add(fDisplay);
+    }
+
+    const TString name(Form("signal%08d.root", fSequence.GetSequence()));
+    return WriteContainer(cont, name, "UPDATE");
+}
+
+Bool_t MJCalibrateSignal::ReadCalibration(TObjArray &l, MBadPixelsCam &cam, MExtractor* &ext2, MExtractor* &ext3, TString &geom) const
+{
+    TString fname = Form("%s/calib%08d.root", fPathIn.Data(), fSequence.GetSequence());
+
+    *fLog << inf << "Reading from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+        return kFALSE;
+    }
+
+    TObject *o = file.Get("ExtractSignal");
+    if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+        return kFALSE;
+    }
+    ext3 = o ? (MExtractor*)o->Clone() : NULL;
+
+    o = file.Get("ExtractTime");
+    if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - ExtractTime read from " << fname << " doesn't inherit from MExtractor!" << endl;
+        return kFALSE;
+    }
+    ext2 = o ? (MExtractor*)o->Clone() : NULL;
+    if (!ext3 && !ext2)
+    {
+        *fLog << err << dbginf << "ERROR - Neither ExtractSignal nor ExrtractTime found in " << fname << "!" << endl;
+        return kFALSE;
+    }
+
+    o = file.Get("MGeomCam");
+    if (o && !o->InheritsFrom(MGeomCam::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - MGeomCam read from " << fname << " doesn't inherit from MGeomCam!" << endl;
+        return kFALSE;
+    }
+    geom = o ? o->ClassName() : "";
+
+    TObjArray cont(l);
+    cont.Add(&cam);
+    return ReadContainer(cont);
+}
+
+// --------------------------------------------------------------------------
+//
+// MJCalibration allows to setup several option by a resource file:
+//   MJCalibrateSignal.RawData: yes,no
+//
+// For more details see the class description and the corresponding Getters
+//
+Bool_t MJCalibrateSignal::CheckEnvLocal()
+{
+    SetInterlaced(GetEnv("Interlaced", fIsInterlaced));
+    SetRelTimesUpdate(GetEnv("RelTimesUpdate", fIsRelTimesUpdate));
+    SetMovieMode(GetEnv("MovieMode", fIsMovieMode));
+
+    return MJCalib::CheckEnvLocal();
+}
+
+Bool_t MJCalibrateSignal::Process(MPedestalCam &pedcamab, MPedestalCam &pedcambias,
+                                  MPedestalCam &pedcamextr)
+{
+    if (!fSequence.IsValid())
+    {
+	  *fLog << err << "ERROR - Sequence invalid..." << endl;
+	  return kFALSE;
+    }
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate calibrated data from Sequence #";
+    *fLog << fSequence.GetSequence() << endl << endl;
+
+
+    if (!CheckEnv())
+        return kFALSE;
+
+    // --------------------------------------------------------------------------------
+
+    MDirIter iter;
+    if (fSequence.IsValid())
+    {
+        if (fSequence.GetRuns(iter, fIsTestMode?MSequence::kRawCal:MSequence::kRawDat)<=0)
+            return kFALSE;
+    }
+
+    // Read File
+    MHCalibrationChargeCam      hchacam;
+    MHCalibrationChargeBlindCam hbndcam;
+    MHCalibrationChargePINDiode hpndiod;
+    MHCalibrationRelTimeCam     hrelcam;
+    //MHCalibrationHiLoCam        hilocam;
+    //MHCalibrationPulseTimeCam   hpulcam;
+
+    hchacam.SetOscillations(kFALSE);
+    hbndcam.SetOscillations(kFALSE);
+    hrelcam.SetOscillations(kFALSE);
+
+    MCalibrationChargeCam      calcam;
+    MCalibrationQECam          qecam;
+    MCalibrationBlindCam       bndcam;
+    MCalibrationChargePINDiode pind;
+    MCalibrationRelTimeCam     tmcam;
+    //MCalibrationHiLoCam        hilcam;
+    //MCalibrationPulseTimeCam   pulcam;
+
+    MBadPixelsCam              badpix;
+
+    TObjArray interlacedcont;
+    if (fIsInterlaced)
+    {
+        interlacedcont.Add(&hchacam);
+	if (IsUseBlindPixel())
+            interlacedcont.Add(&hbndcam);
+        if (IsUsePINDiode())  
+            interlacedcont.Add(&hpndiod);
+        if (fIsRelTimesUpdate)
+            interlacedcont.Add(&hrelcam);
+    }
+
+    MExtractor *extractor1=fExtractor;
+    MExtractor *extractor2=0;
+    MExtractor *extractor3=0;
+    TString geom;
+
+    TObjArray calibcont;
+    calibcont.Add(&calcam);
+    calibcont.Add(&qecam);
+    calibcont.Add(&bndcam);
+    calibcont.Add(&tmcam);
+    if (IsUseBlindPixel())
+        calibcont.Add(&bndcam);
+
+    if (!ReadCalibration(calibcont, badpix, extractor2, extractor3, geom))
+        return kFALSE;
+
+    *fLog << all;
+    if (!geom.IsNull())
+        *fLog << inf << "Camera geometry found in file: " << geom << endl;
+    else
+        *fLog << inf << "No Camera geometry found using default <MGeomCamMagic>" << endl;
+
+    if (extractor3)
+    {
+        *fLog << underline << "Signal Extractor found in calibration file" << endl;
+        extractor3->Print();
+        *fLog << endl;
+    }
+    else
+        *fLog << inf << "No Signal Extractor: ExtractSignal in file." << endl;
+
+
+    if (extractor1)
+    {
+      *fLog << underline << "Modified Signal Extractor set by user." << endl;
+      extractor1->Print();
+      *fLog << endl;
+    }
+    else
+    {
+        *fLog << inf << "No modified Signal Extractor set by user... using ExtractSignal." << endl;
+        extractor1 = extractor3 ? (MExtractor*)extractor3->Clone() : 0;
+    }
+
+    if (extractor2)
+    {
+        *fLog << underline << "Time Extractor found in calibration file" << endl;
+        extractor2->Print();
+        *fLog << endl;
+    }
+    else
+        *fLog << inf << "No Time Extractor: ExtractTime in file." << endl;
+
+    // This is necessary for the case in which it is not in the files
+    MCalibConstCam constcam;
+
+    //MBadPixelsCam badcam;
+    constcam.SetBadPixels(&badpix);
+
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+    plist.AddToList(&badpix);
+    plist.AddToList(&constcam);
+    //plist.AddToList(&hilcam);
+    plist.AddToList(&calibcont);       // Using AddToList(TObjArray *)
+    plist.AddToList(&interlacedcont);  // Using AddToList(TObjArray *)
+    //plist.AddToList(&pulcam);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadMarsFile readmc("Events");
+    readmc.DisableAutoScheme();
+
+    MRawFileRead rawread(NULL);
+    rawread.SetForceMode(); // Ignore broken time-stamps
+
+    MRead *read = fSequence.IsMonteCarlo() ? (MRead*)&readmc : (MRead*)&rawread;
+    read->AddFiles(iter);
+
+    const TString fname(Form("s/(([0-9]+_)?(M[12]_)?[0-9.]+)_[CD]_(.*[.])(raw|raw[.]gz|root)$/%s\\/$1_Y_$4root/",
+                             Esc(fPathOut).Data()));
+
+    // Skips MC which have no contents. This are precisely the
+    // events which fullfilled the MC Lvl1 trigger and an
+    // arbitrary cut (typically at 50phe) to speed up simulation
+    MContinue contmc("MRawEvtData.GetNumPixels<0.5", "ContEmptyMC");
+
+    //MPointingPosInterpolate pextr;
+    //pextr.AddFiles(&iter);
+
+    MGeomApply             apply; // Only necessary to create geometry
+    if (!geom.IsNull())
+        apply.SetGeometry(geom);
+    //MBadPixelsMerge        merge(&badpix);
+
+    // Make sure that pedcamab has the correct name
+    pedcamab.SetName("MPedestalFundamental");
+    pedcamextr.SetName("MPedestalFromExtractorRndm");
+    pedcambias.SetName("MPedestalFromExtractor");
+    plist.AddToList(&pedcamextr);
+    plist.AddToList(&pedcambias);
+    plist.AddToList(&pedcamab);
+
+    MArrivalTimeCam timecam;
+    plist.AddToList(&timecam);
+
+    // Check for interleaved events
+    MCalibrationPatternDecode caldec;
+    MTriggerPatternDecode     decode;
+
+    MH3 hpat("MRawRunHeader.GetFileID", "MTriggerPattern.GetUnprescaled");
+    if (fSequence.IsMonteCarlo())
+        hpat.SetWeight("100./MMcRunHeader.fNumSimulatedShowers");
+    else
+        hpat.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hpat.SetName("TrigPat");
+    hpat.SetTitle("Rate of the trigger pattern [Hz];File Id;Trigger Pattern;Rate [Hz]");
+    hpat.InitLabels(MH3::kLabelsXY);
+    //hpat.DefineLabelsY("1=Lvl1;2=Cal;3=Cal;4=Lvl2;5=Cal;7=Cal;8=Ped;9=Ped+Trig;13=Ped+Trig;16=Pin;32=Sum");
+    hpat.DefaultLabelY("UNKNOWN");
+    hpat.DefineLabelY( 0, "0");        //  0: No pattern
+    hpat.DefineLabelY( 1, "Trig");     //  1: Lvl1
+    hpat.DefineLabelY( 2, "Cal");      //  2: Cal
+    hpat.DefineLabelY( 3, "Cal");      //     Cal+Lvl1
+    hpat.DefineLabelY( 4, "Trig");     //  4: Lvl2
+    hpat.DefineLabelY( 5, "Trig");     //     Lvl2+Lvl1
+    hpat.DefineLabelY( 7, "Cal");      //     Lvl2+Cal+Lvl
+    hpat.DefineLabelY( 8, "Ped");      //  8: Ped
+    hpat.DefineLabelY( 9, "Ped+Trig"); //     Ped+Lvl1
+    hpat.DefineLabelY(10, "Ped+Cal");  //     Ped+Cal
+    hpat.DefineLabelY(12, "Ped+Trig"); //     Ped+Lvl2
+    hpat.DefineLabelY(13, "Ped+Trig"); //     Ped+Lvl2+Lvl1
+    hpat.DefineLabelY(16, "Pin");      // 16: Pin
+    hpat.DefineLabelY(32, "Sum");      // 32: Sum
+    hpat.DefineLabelY(33, "Trig");     //     Sum+Lvl1
+    hpat.DefineLabelY(34, "Cal");      //     Sum+Cal
+    hpat.DefineLabelY(35, "Cal");      //     Sum+Cal+Lvl1
+    hpat.DefineLabelY(36, "Trig");     //     Sum+Lvl2
+    hpat.DefineLabelY(37, "Trig");     //     Sum+Lvl1+Lvl2
+    hpat.DefineLabelY(39, "Cal");      //     Sum+Lvl2+Cal+Lvl1
+
+    MFillH fillpat(&hpat, "", "FillPattern");
+    fillpat.SetDrawOption("box");
+
+    // This will make that for data with version less than 5, where
+    // trigger patterns were not yet correct, all the events in the real
+    // data file will be processed. In any case there are no interleaved
+    // calibration events in such data, so this is fine.
+    // We allow only cosmics triggered events to pass (before prescaling)
+    MFTriggerPattern fcalped("SelectTrigEvts");
+    fcalped.SetInverted();
+    fcalped.SetDefault(kTRUE);
+    fcalped.DenyAll();
+    fcalped.AllowTriggerLvl1();
+    fcalped.AllowTriggerLvl2();
+    fcalped.AllowSumTrigger();
+    if (fIsTestMode)
+        fcalped.AllowCalibration();
+
+    // This will skip interleaved events with a cal- or ped-trigger
+    MContinue contcalped(&fcalped, "ContNonTrigger");
+
+    // Create the pedestal subtracted raw-data
+    MPedestalSubtract pedsub;
+    pedsub.SetPedestalCam(&pedcamab);
+
+    // Do signal and pedestal calculation
+    MPedCalcFromLoGain     pedlo1("MPedCalcFundamental");
+    pedlo1.SetPedestalUpdate(kTRUE);
+    pedlo1.SetNamePedestalCamOut("MPedestalFundamental");
+
+    MPedCalcFromLoGain     pedlo2("MPedCalcWithExtractorRndm");
+    pedlo2.SetPedestalUpdate(kTRUE);
+    pedlo2.SetRandomCalculation(kTRUE);
+    pedlo2.SetNamePedestalCamOut("MPedestalFromExtractorRndm");
+
+    MPedCalcFromLoGain     pedlo3("MPedCalcWithExtractor");
+    pedlo3.SetPedestalUpdate(kTRUE);
+    pedlo3.SetRandomCalculation(kFALSE);
+    pedlo3.SetNamePedestalCamOut("MPedestalFromExtractor");
+
+    if (!extractor1)
+    {
+        *fLog << err << "ERROR - extractor1 == NULL" << endl;
+        return kFALSE;
+    }
+
+    // Setup to use the hi-gain extraction window in the lo-gain
+    // range (the start of the lo-gain range is added automatically
+    // by MPedCalcFromLoGain)
+    //
+    // The window size of the extractor is not yet initialized,
+    // so we have to stick to the extraction range
+    //
+    // Even if we would like to use a range comparable to the
+    // hi-gain extraction we use the lo-gain range to make
+    // sure that exclusions (eg. due to switching noise)
+    // are correctly handled.
+    //
+    pedlo1.SetRangeFromExtractor(*extractor1);
+
+    if (extractor1->InheritsFrom("MExtractTimeAndCharge"))
+    {
+        pedlo2.SetExtractor((MExtractTimeAndCharge*)extractor1);
+        pedlo3.SetExtractor((MExtractTimeAndCharge*)extractor1);
+    }
+    else
+    {
+        pedlo2.SetRangeFromExtractor(*extractor1);
+        pedlo3.SetRangeFromExtractor(*extractor1);
+    }
+
+    //------------------------------
+    //
+    // this is the filter to find pedestal events. For the Siegen FADC
+    // these are all events which are not calibration events because
+    // the pedestal is extracted from the lo-gain signal. For MUX
+    // data this are artifiially triggered events with the pedestal
+    // trigger flag, and for safty without Lvl1 or Lvl2 flag)
+    //
+    // For the time "before" the trigger pattern all events (Siegen FADC)
+    // can be considered to be pedestal, because this was also the time
+    // without artifially calibration events
+    //
+    // Deny or allow is done before prescaling.
+    //
+    MFTriggerPattern fped("SelectPedestals");
+    fped.SetDefault(kTRUE);
+    fped.DenyCalibration();
+    if (!extractor1->HasLoGain())
+    {
+        fped.DenyAll();
+        fped.RequirePedestal();
+    }
+
+    //------------------------------
+    //
+    // Apply a filter against cosmics (this is to make sure that the
+    // trigger system was working properly and no empty events survive)
+    // For every event 5% of the pixel must not be empty. In PostProcess
+    // an error is raised if more than 50% of the events were skipped.
+    //
+    // Since unsuitable pixels are not counted in the ideal case
+    // there is no empty pixel at all.
+    //
+    MFCosmics fcosmicscal;
+    fcosmicscal.SetNamePedestalCam("MPedestalFundamental"); //CORRECT?
+    fcosmicscal.SetMaxEmptyPixels(0.05);
+    fcosmicscal.SetMaxAcceptedFraction(0.5);
+
+    MContinue contcoscal(&fcosmicscal, "ContCosmicsCal");
+
+    //------------------------------
+    //
+    // Remove events which are too bright. These events could either
+    // be calibration events or events which produce many many
+    // saturating low-gains and thus spoil the dead pixel plot.
+    // These events don't seem to be physical events so we can fairly
+    // remove them (they are no analysable gammas anyway)
+    // So we remove all events which have less than 5% empty pixels.
+    //
+    MFCosmics fcosmicsbright;
+    fcosmicsbright.SetNamePedestalCam("MPedestalFundamental");
+    fcosmicsbright.SetMaxEmptyPixels(0.10);
+    fcosmicsbright.SetMinAcceptedFraction(0.9);
+
+    MContinue contbright(&fcosmicsbright, "ContBrightEvts");
+    contbright.SetInverted();
+
+    //------------------------------
+    //
+    // Thie signal extractors
+    //
+    MTaskEnv taskenv1("ExtractSignal");
+    MTaskEnv taskenv2("ExtractTime");
+    MTaskEnv taskenv3("ExtractInterlaced");
+    taskenv1.SetDefault(extractor1);
+    taskenv2.SetDefault(extractor2);
+    taskenv3.SetDefault(extractor3);
+
+    //
+    // This is new calibration to photo-electrons, hard-coded
+    // as decided at the Wuerzburg software meeting 26.01.05
+    //
+    MCalibrateData calib;
+    calib.SetSignalType(MCalibrateData::kPhe);
+    //calib.AddPedestal("Fundamental");
+    calib.AddPedestal("FromExtractor");
+    calib.AddPedestal("FromExtractorRndm");
+    calib.SetPedestalFlag(MCalibrateData::kEvent);
+
+    //----------------------------------------------------------
+
+    MExtractPINDiode        pinext;
+    MExtractBlindPixel      bldext;
+
+    // Execute for all events with the calibration trigger. If no
+    // trigger pattern is available do not execute it
+    // The selection is done before prescaling.
+    MFTriggerPattern        fcalib("SelectCalEvts");
+    fcalib.SetDefault(kFALSE);
+    fcalib.DenyAll();
+    fcalib.RequireCalibration();
+    fcalib.AllowTriggerLvl1();
+    fcalib.AllowTriggerLvl2();
+    fcalib.AllowSumTrigger();
+
+    MCalibrationChargeCalc  chcalc;
+    chcalc.SetContinousCalibration();
+    chcalc.SetExtractor(extractor3);
+
+    MCalibrationRelTimeCalc recalc;
+    MCalibCalcFromPast      pacalc;
+
+    chcalc.SetPedestals(&pedcamextr);
+
+    pacalc.SetChargeCalc(&chcalc);
+    if (fIsRelTimesUpdate)
+      pacalc.SetRelTimeCalc(&recalc);
+    pacalc.SetCalibrate(&calib);
+
+    //
+    // Calibration histogramming
+    //
+    MFillH filpin(&hpndiod, "MExtractedSignalPINDiode",   "FillPINDiode");
+    MFillH filbnd(&hbndcam, "MExtractedSignalBlindPixel", "FillBlindCam");
+    MFillH filcam(&hchacam, "MExtractedSignalCam",        "FillChargeCam");
+    MFillH filtme(&hrelcam, "MArrivalTimeCam",            "FillRelTime");
+    //MFillH filhil(&hilocam, "MExtractedSignalCam",        "FillHiLoRatio");
+    //MFillH filpul(&hpulcam, "MRawEvtData",                "FillPulseTime");
+    filpin.SetBit(MFillH::kDoNotDisplay);
+    filbnd.SetBit(MFillH::kDoNotDisplay);
+    filcam.SetBit(MFillH::kDoNotDisplay);
+    filtme.SetBit(MFillH::kDoNotDisplay);
+    //filhil.SetBit(MFillH::kDoNotDisplay);
+    //filpul.SetBit(MFillH::kDoNotDisplay);
+
+    MCalibrateRelTimes caltm;
+    MBadPixelsCalc     bpcal;
+    MBadPixelsTreat    treat;
+
+    //bpcal.SetNamePedPhotCam("MPedPhotFromExtractor");
+    bpcal.SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+
+    //treat.AddNamePedPhotCam("MPedPhotFundamental");
+    treat.AddNamePedPhotCam("MPedPhotFromExtractor");
+    treat.AddNamePedPhotCam("MPedPhotFromExtractorRndm");
+    if (!extractor2 && !extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        treat.SetProcessTimes(kFALSE);
+
+    MHCamEvent evt0(  0, "PedFLG",     "Fundamental Pedestal from Lo Gain;;P [cnts/sl]");
+    MHCamEvent evt1(  2, "PedRmsFLG",  "RMS from Extractor applied to ped.;;\\sigma_{p} [cnts/sl]");
+    MHCamEvent evt2(  0, "Extra'd",    "Extracted Signal;;S [cnts/sl]");
+    // MHCamEvent evt3(4, "PedPhot",    "Calibrated Pedestal;;P [phe]");
+    MHCamEvent evt4(  5, "PedRMS",     "Calibrated RMS from Extractor applied to ped.;;\\sigma_{p} [phe]");
+    MHCamEvent evt5(  0, "Interp'd",   "Interpolated Signal scaled with A/A_{0};;S [phe]");
+    MHCamEvent evt6(102, "Unsuitable", "Fraction of unsuitable events per Pixel;;[1]");
+    // MHCamEvent evt7(  6, "Times",      "Calibrated Arrival Time;;T [fadc sl]");
+    MHCamEvent evt8(  0, "Conv",       "Calibration Conv. Factors;;[phe/cnts]");
+    MHCamEvent evt9(  7, "PulsePos",   "Pulse Position of cosmics (>50phe);;T [ns]");
+    MHCamEvent evtR(  4, "HiLoCal",    "Hi-/Lo-Gain ratio;;Ratio");
+    MHCamEvent evtO(  7, "HiLoOff",    "Lo-/Hi-Gain Offset;;Offset");
+    MHCamEvent evtC(  4, "CalPos",     "Extracted pulse position of calibration pulses;;T [sl]");
+    //MHCamEvent evt2(0, "Extra'd", "Extracted Calibration Signal;;S [cnts/sl]");
+    evt2.SetErrorSpread(kFALSE);
+    evt5.SetErrorSpread(kFALSE);
+    evt6.SetErrorSpread(kFALSE);
+    evt6.SetThreshold();
+
+    MFillH fill0(&evt0, "MPedestalFundamental",          "FillPedFLG");
+    MFillH fill1(&evt1, "MPedestalFromExtractorRndm",    "FillPedRmsFLG");
+    MFillH fill2(&evt2, "MExtractedSignalCam",           "FillExtracted");
+    // MFillH fill3(&evt3, "MPedPhotFundamental",  "FillPedPhot");
+    MFillH fill4(&evt4, "MPedPhotFromExtractorRndm",     "FillPedRMS");
+    MFillH fill5(&evt5, "MSignalCam",                    "FillInterpolated");
+    MFillH fill6(&evt6, "MBadPixelsCam",                 "FillUnsuitable");
+    // MFillH fill7(&evt7, "MSignalCam",                    "FillTimes");
+    MFillH fill8(&evt8, "MCalibConstCam",                "FillConv");
+    MFillH fill9(&evt9, "MSignalCam",                    "FillPulsePos");
+    MFillH fillR(&evtR, "MExtractedSignalCam",           "FillHiLoCal");
+    MFillH fillO(&evtO, "MArrivalTimeCam",               "FillHiLoOff");
+    MFillH fillC(&evtC, "MArrivalTimeCam",               "FillCalPos");
+    //MFillH fill2(&evt2, "MExtractedSignalCam", "FillExtractedSignal");
+
+    MHVsTime histbp("MBadPixelsCam.GetNumUnsuitable");
+    histbp.SetName("BadPixTm");
+    histbp.SetTitle("Number of unsuitable pixels;;N");
+    histbp.SetMinimum(0);
+
+    MHVsTime histdp("MSignalCam.GetNumPixelsUnmapped");
+    histdp.SetName("DeadPixTm");
+    histdp.SetTitle("Number of dead/unmapped pixels;;N");
+    histdp.SetMinimum(0);
+
+    // Task to fill the histogram
+    MFillH fillB(&histbp, "MTime", "FillBadPixTm");
+    MFillH fillD(&histdp, "MTime", "FillDeadPixTm");
+    fillB.SetNameTab("BadPixTm");
+    fillD.SetNameTab("DeadPixTm");
+
+    /*
+     MFillH fillP("MHPulseShape", "", "FillPulseShape");
+     fillP.SetNameTab("Pulse");
+     */
+
+    /*
+     MHVsTime hbadpix("MBadPixelsCam.GetNumUnsuitable");
+     hbadpix.SetNumEvents(50);
+     MFillH fillB(&hbadpix, "MTime");
+     */
+
+    MTaskEnv fillflorian("FinalFantasy");
+    fillflorian.SetDefault();
+
+    // The second rule is for the case reading raw-files!
+    MWriteRootFile write(2, fname, fOverwrite?"RECREATE":"NEW", "Calibrated Data");
+    // Run Header
+    write.AddContainer("MRawRunHeader",             "RunHeaders");
+//    write.AddContainer("MBadPixelsCam",             "RunHeaders");
+    write.AddContainer("MGeomCam",                  "RunHeaders");
+    // Monte Carlo Headers
+    write.AddContainer("MMcRunHeader",              "RunHeaders", kFALSE);
+    write.AddContainer("MMcFadcHeader",             "RunHeaders", kFALSE);
+    write.AddContainer("MMcTrigHeader",             "RunHeaders", kFALSE);
+    write.AddContainer("MMcConfigRunHeader",        "RunHeaders", kFALSE);
+    write.AddContainer("MMcCorsikaRunHeader",       "RunHeaders", kFALSE);
+    write.AddContainer("MCorsikaRunHeader",         "RunHeaders", kFALSE);
+    // Monte Carlo
+    write.AddContainer("MMcEvt",                    "Events",     kFALSE);
+    write.AddContainer("MMcTrig",                   "Events",     kFALSE);
+    write.AddContainer("MCorsikaEvtHeader",         "Events",     kFALSE);
+    // Data tree
+    write.AddContainer("MSignalCam",                "Events");
+    // write.AddContainer("MPedPhotFundamental",               "Events");
+    write.AddContainer("MPedPhotFromExtractor",     "Events");
+    write.AddContainer("MPedPhotFromExtractorRndm", "Events");
+    write.AddContainer("MTime",                     "Events",     kFALSE);
+    write.AddContainer("MRawEvtHeader",             "Events");
+    write.AddContainer("MTriggerPattern",           "Events");
+
+    // Trees with slow-control information (obsolete
+    //  if we don't read merpped root-files)
+    write.AddTree("Trigger",    kFALSE);
+    write.AddTree("Drive",      kFALSE);
+    write.AddTree("CC",         kFALSE);
+    write.AddTree("Pyrometer",  kFALSE);
+    write.AddTree("Currents",   kFALSE);
+    write.AddTree("Camera",     kFALSE);
+    // Slow-Control: Current-tree
+    write.AddContainer("MCameraDC",          "Currents",   kFALSE);
+    // Slow-Control: Camera-tree
+    write.AddContainer("MCameraAUX",         "Camera",     kFALSE);
+    write.AddContainer("MCameraCalibration", "Camera",     kFALSE);
+    write.AddContainer("MCameraCooling",     "Camera",     kFALSE);
+    write.AddContainer("MCameraHV",          "Camera",     kFALSE);
+    write.AddContainer("MCameraLV",          "Camera",     kFALSE);
+    write.AddContainer("MCameraLids",        "Camera",     kFALSE);
+
+    // Write the special MC tree
+    MWriteRootFile writemc(2, fname, fOverwrite?"RECREATE":"NEW", "Calibrated Data");
+    writemc.SetName("WriteMC");
+    writemc.AddContainer("MMcEvtBasic", "OriginalMC", kFALSE);
+    if (fSequence.IsMonteCarlo())
+        writemc.AddCopySource("OriginalMC", kFALSE);
+
+    // Write the special calib tree
+    /*
+    MWriteRootFile writecal(2, fname, fOverwrite?"RECREATE":"NEW");
+    writecal.SetName("WriteCalib");
+    writecal.AddContainer("MBadPixelsCam",          "Calib");
+    writecal.AddContainer("MCalibrationChargeCam",  "Calib");
+    writecal.AddContainer("MCalibrationRelTimeCam", "Calib");
+    */
+
+    //-----------------------------------------------------------
+    // Build tasklist
+
+    MTaskList tlist2("AllEvents");
+
+    tlist2.AddToList(&caldec);
+    tlist2.AddToList(&decode);
+    tlist2.AddToList(&fillpat);
+    tlist2.AddToList(&apply);
+    //tlist2.AddToList(&merge);
+    tlist2.AddToList(&pedsub);
+
+    //-----------------------------------------------------------
+    // Pedestal extraction
+
+    MTaskList tlist3("PedEvents");
+    tlist3.SetFilter(&fped);         // Deny events with cal-trigger
+
+    tlist2.AddToList(&fped);         // If no lo-gain require ped-trigger
+    tlist2.AddToList(&tlist3);       //  and deny cosmics (lvl1/2) trigger
+
+    tlist3.AddToList(&pedlo1);       // extract pedestal events
+    tlist3.AddToList(&pedlo2);       // extract pedestal events
+    tlist3.AddToList(&pedlo3);       // extract pedestal events
+    tlist3.AddToList(&fill0);        // fill pedestal events
+    tlist3.AddToList(&fill1);        // fill pedestal events
+
+    //-----------------------------------------------------------
+    // Calibration
+
+    MTaskList tlist4("CalEvents");
+    tlist4.SetFilter(&fcalib);       // process only events with cal-trigger
+
+    //MFDataPhrase filcalco("MCalibrationConstCam.IsReadyToSave>0.5", "CalibConstFilter");
+    if (fIsInterlaced && !fIsTestMode)
+    {
+        // The task list is executed for all events with the calibration
+        // trigger
+        tlist2.AddToList(&fcalib);     // MFTriggerPattern
+        tlist2.AddToList(&tlist4);
+
+        tlist4.AddToList(&taskenv3);
+        tlist4.AddToList(&contcoscal); // MContinue/ContCosmicsCal
+        if (IsUsePINDiode())
+            tlist4.AddToList(&pinext); // MExtractPINDiode
+        if (IsUseBlindPixel())
+            tlist4.AddToList(&bldext); // MExtractBlindPixel
+        tlist4.AddToList(&pacalc);     // MCalibCalcFromPast
+        /*
+         tlist3.AddToList(&filcalco);   // CalibConstFilter (IsReadyToSave)
+         fill8.SetFilter(&filcalco);
+         tlist3.AddToList(&fill8);      // FillConvUpd
+         */
+
+        tlist4.AddToList(&filcam);     // FillChargeCam
+	if (fIsRelTimesUpdate)
+	  tlist4.AddToList(&filtme);   // FillRelTime
+        if (IsUseBlindPixel())
+            tlist4.AddToList(&filbnd); // FillBlindCam
+        if (IsUsePINDiode())
+            tlist4.AddToList(&filpin); // FillPINDiode
+        tlist4.AddToList(&chcalc);     // MCalibrationChargeCalc
+	if (fIsRelTimesUpdate)
+            tlist4.AddToList(&recalc); // MCalibrationRelTimeCam
+
+        tlist4.AddToList(&fillC);      // FillCalPos
+
+        //tlist3.AddToList(&writecal);   // MWriteRootFile
+    }
+
+    //-----------------------------------------------------------
+    // Cosmics extraction
+
+    // remove all events with a cal- or ped-trigger (no matter
+    // whether they have lvl1 or lvl2 or any other flag
+    tlist2.AddToList(&contcalped);
+
+    // Extract the signal
+    if (extractor1)
+      tlist2.AddToList(&taskenv1);
+
+    // remove all events which definitly don't have a signal
+    // using MFCosmics (ContCosmicsPed)
+    // tlist2.AddToList(&contcosped);
+
+    // Extract arrival time (if a dedicated extrator given)
+    if (extractor2)
+        tlist2.AddToList(&taskenv2);
+
+    // Check if we have an extremely bright event (remove them,
+    // they are presumably errornous events or calibration events)
+    if (!fIsTestMode)
+        tlist2.AddToList(&contbright);
+
+    /*
+    if (fIsHiLoCalibration)
+    {
+        plist.AddToList(&hilocam);
+        tlist2.AddToList(&filhil);
+        }
+
+    if (fIsPulsePosCheck)
+    {
+        plist.AddToList(&hpulcam);
+        tlist2.AddToList(&filpul);
+    }
+    */
+
+    tlist2.AddToList(&fill2);
+    tlist2.AddToList(&fill8);        // FillConv
+    tlist2.AddToList(&calib);        // MCalibrateData
+    if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        tlist2.AddToList(&caltm);
+
+    tlist2.AddToList(&bpcal);        // MBadPixelsCalc
+    tlist2.AddToList(&treat);        // MBadPixelsTreat
+    tlist2.AddToList(&fill6);
+    //    tlist2.AddToList(&fill3);
+    tlist2.AddToList(&fill4);
+    tlist2.AddToList(&fill5);
+    //if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
+    //    tlist2.AddToList(&fill7);
+    tlist2.AddToList(&fill9);
+    if (!fSequence.IsMonteCarlo())
+    {
+        tlist2.AddToList(&fillB);
+        tlist2.AddToList(&fillD);
+    }
+    if (extractor1->HasLoGain())
+    {
+        tlist2.AddToList(&fillR);
+        tlist2.AddToList(&fillO);
+    }
+
+    /*
+     MFillH fillC("MHCleaning", "", "FillClean");
+     tlist2.AddToList(&fillC);
+
+     //tlist2.AddToList(&fillP);
+     */
+
+    // ----- Start: Code for encoding movies -----
+
+    MMoviePrepare movprep;
+    MMovieWrite   movwrite;
+    movprep.SetRangeFromExtractor(*extractor1);
+
+    //MFDataPhrase movfilt("MMovieData.fMax>150");
+    MFDataPhrase movfilt("MMovieData.fMax>5*MMovieData.fMedianPedestalRms", "MovieFilter");
+
+    MImgCleanStd movclean(8.5, 4.0);
+    movclean.SetMethod(MImgCleanStd::kAbsolute);
+
+    //movprep.SetFilter(&evtnum);
+    movclean.SetFilter(&movfilt);
+    movwrite.SetFilter(&movfilt);
+
+    MTaskList tlistmov("MovieEncoder");
+    tlistmov.AddToList(&movprep);
+    tlistmov.AddToList(&movfilt);
+    tlistmov.AddToList(&movclean);
+    tlistmov.AddToList(&movwrite);
+
+    MFEvtNumber evtnum;
+    //evtnum.SetSelector("ThetaSquared.fVal<0.04");
+    //evtnum.SetFileName("ganymed00000001.root");
+    tlistmov.SetFilter(&evtnum);
+
+    if (fIsMovieMode)
+    {
+        tlist2.AddToList(&evtnum);
+        tlist2.AddToList(&tlistmov);
+    }
+
+    // ----- End: Code for encoding movies -----
+
+    tlist2.AddToList(&fillflorian);
+
+    // Setup List for Drive-tree
+    //MPointingPosCalc pcalc;
+
+    // Now setup main tasklist
+    tlist.AddToList(read);
+
+    if (fSequence.IsMonteCarlo())
+    {
+        if (!fIsMovieMode && !HasNullOut())
+            tlist.AddToList(&writemc);
+        tlist.AddToList(&contmc);
+    }
+
+    //if (IsUseRootData())
+    //  tlist2.AddToList(&pextr);
+    tlist.AddToList(&tlist2, fSequence.IsMonteCarlo() ? "Events" : "All");
+
+    //if (fSequence.IsMonteCarlo())
+    //  tlist.AddToList(&pcalc, "Drive");
+
+    if (!fIsMovieMode && !HasNullOut())
+        tlist.AddToList(&write);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    // Execute first analysis
+    const Bool_t rc = evtloop.Eventloop(fMaxEvents);
+
+    // make sure owned object are deleted
+    if (extractor1 && extractor1!=fExtractor)
+        delete extractor1;
+    if (extractor2)
+        delete extractor2;
+    if (extractor3)
+        delete extractor3;
+
+    // return if job failed
+    if (!rc)
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    // if everything went ok write and display result
+    DisplayResult(plist);
+
+    /*
+    if (fIsPixelCheck)
+      {
+        if (fIsPulsePosCheck)
+            hpulcam[fCheckedPixId].DrawClone("");
+
+	//if (fIsHiLoCalibration)
+	//    hilocam[fCheckedPixId].DrawClone("");
+      }
+    interlacedcont.Add(&pulcam);
+    */
+
+    //if (fIsHiLoCalibration)
+    //  interlacedcont.Add(&hilcam);
+
+    //if (fIsPulsePosCheck)
+    //    interlacedcont.Add(plist.FindObject("MHCalibrationPulseTimeCam"));
+
+    //if (fIsHiLoCalibration)
+    //    interlacedcont.Add(plist.FindObject("MHCalibrationHiLoCam"));
+
+    if (!WriteResult())
+        return kFALSE;
+
+    // return if job went ok
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
+
+
+void MJCalibrateSignal::DisplayResult(MParList &plist)
+{
+    /*
+    if (!fDisplay || !fIsHiLoCalibration)
+        return;
+
+    MCalibrationHiLoCam *hcam = (MCalibrationHiLoCam*)plist.FindObject("MCalibrationHiLoCam");
+    MGeomCam            *geom = (MGeomCam*)plist.FindObject("MGeomCam");
+    if (!hcam || !geom)
+        return;
+
+    // Create histograms to display
+    MHCamera disp1(*geom, "HiLoConv", "Ratio Amplification HiGain vs. LoGain (Charges)");
+    MHCamera disp2(*geom, "HiLoDiff", "Arrival Time Diff. HiGain vs. LoGain (Times)");
+
+    disp1.SetCamContent(*hcam, 0);
+    disp1.SetCamError(  *hcam, 1);
+    disp2.SetCamContent(*hcam, 5);
+    disp2.SetCamError(  *hcam, 6);
+
+    disp1.SetYTitle("R [1]");
+    disp2.SetYTitle("\\Delta T [FADC sl.]");
+
+    TCanvas &c1 = fDisplay->AddTab("HiLoConv");
+    c1.Divide(2,3);
+
+    disp1.CamDraw(c1, 1, 2, 1);
+    disp2.CamDraw(c1, 2, 2, 1);
+*/
+}
+
Index: branches/Mars_McMismatchStudy/mjobs/MJCalibrateSignal.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalibrateSignal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalibrateSignal.h	(revision 17960)
@@ -0,0 +1,56 @@
+#ifndef MARS_MJCalibrateSignal
+#define MARS_MJCalibrateSignal
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+
+class TEnv;
+class TList;
+class MTask;
+class MParList;
+class MGeomCam;
+class MSequence;
+class MExtractor;
+class MPedestalCam;
+class MBadPixelsCam;
+class MRunIter;
+
+class MJCalibrateSignal : public MJCalib
+{
+private:
+    MExtractor *fExtractor;
+
+    Bool_t fIsInterlaced;               // Distinguish interlaced from other calibration
+    Bool_t fIsRelTimesUpdate;           // Choose to update relative times from interlaced
+    Bool_t fIsMovieMode;                // Choose to encode a movie
+    Bool_t fIsTestMode;                 // Testmode to calibrate the cal run
+
+    Bool_t CheckEnvLocal();
+
+    void   DisplayResult(MParList &plist);
+
+    Bool_t WriteResult() const;
+    Bool_t ReadCalibration(TObjArray &o, MBadPixelsCam &bpix,
+                           MExtractor* &ext1, MExtractor* &ext2, TString &geom) const;
+    Bool_t ReadExtractorCosmics(MExtractor* &ext1) const;
+
+    const char* GetInputFile() const;
+    
+public:
+    MJCalibrateSignal(const char *name=NULL, const char *title=NULL);
+    ~MJCalibrateSignal();
+
+    Bool_t Process(MPedestalCam &camab, MPedestalCam &cam1, MPedestalCam &cam2);
+
+    void SetInterlaced    (const Bool_t b=kTRUE) { fIsInterlaced     = b; }
+    void SetRelTimesUpdate(const Bool_t b=kTRUE) { fIsRelTimesUpdate = b; }
+    void SetMovieMode     (const Bool_t b=kTRUE) { fIsMovieMode      = b; }
+    void SetTestMode      (const Bool_t b=kTRUE) { fIsTestMode       = b; }
+
+    void SetExtractor(const MExtractor *ext=NULL);
+
+    ClassDef(MJCalibrateSignal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJCalibration.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalibration.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalibration.cc	(revision 17960)
@@ -0,0 +1,1773 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Markus Gaug, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalibration
+//
+//  Do one calibration loop over serious of runs with the same pulser 
+//  colour and the same intensity. The following containers (rectangular) and 
+//  tasks (ellipses) are called to produce an MCalibrationChargeCam and to 
+//  update the MCalibrationQECam: (MCalibrate is not called from this class)
+//
+//Begin_Html
+/*
+<img src="images/CalibClasses.gif">
+*/
+//End_Html
+//
+// Different signal extractors can be set with the command SetExtractor()
+// Only extractors deriving from MExtractor can be set, default is MExtractSlidingWindow
+//
+// Different arrival time extractors can be set with the command SetTimeExtractor()
+// Only extractors deriving from MExtractTime can be set, default is MExtractTimeHighestIntegral
+//
+// At the end of the eventloop, plots and results are displayed, depending on 
+// the flags set (see DisplayResult()) 
+// 
+// If the flag SetFullDisplay() is set, all MHCameras will be displayed. 
+// if the flag SetDataCheckDisplay() is set, only the most important ones are displayed 
+// Otherwise, (default: SetNormalDisplay()), a good selection of plots is given
+//
+// The absolute light calibration devices Blind Pixel and PIN Diode can be switched on
+// and off with the commands:
+//
+// - SetUseBlindPixel(Bool_t )
+// - SetUsePINDiode(Bool_t )
+//
+// See also: MHCalibrationChargePix, MHCalibrationChargeCam, MHGausEvents
+//           MHCalibrationChargeBlindPix, MHCalibrationChargePINDiode
+//           MCalibrationChargePix, MCalibrationChargeCam, MCalibrationChargeCalc
+//           MCalibrationBlindPix, MCalibrationChargePINDiode,
+//           MCalibrationQECam, MBadPixelsPix, MBadPixelsCam
+//
+// If the flag RelTimeCalibration() is set, a calibration of the relative arrival 
+// times is also performed. The following containers (rectangular) and 
+// tasks (ellipses) are called to produce an MCalibrationRelTimeCam used by  
+// MCalibrateTime to correct timing offset between pixels: (MCalibrateTime is not 
+// called from this class)
+//
+//Begin_Html
+/*
+<img src="images/RelTimeClasses.gif">
+*/
+//End_Html
+//
+// Different arrival time extractors can be set directly with the command
+// SetTimeExtractor(MExtractor *)
+//
+// Resource file entries are case sensitive!
+//
+// See also: MHCalibrationRelTimePix, MHCalibrationRelTimeCam, MHGausEvents
+//           MCalibrationRelTimePix, MCalibrationRelTimeCam
+//           MBadPixelsPix, MBadPixelsCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibration.h"
+
+#include <TFile.h>
+#include <TF1.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TRegexp.h>
+#include <TPaveText.h>
+#include <TPaveStats.h>
+#include <TEnv.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MString.h"
+#include "MDirIter.h"
+#include "MSequence.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MHCamera.h"
+#include "MGeomCam.h"
+
+#include "MCalibrationPatternDecode.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationBlindPix.h"
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationBlindCamOneOldStyle.h"
+#include "MCalibrationBlindCamTwoNewStyle.h"
+#include "MCalibrationBlindCamThreeNewStyle.h"
+#include "MCalibrationChargeCalc.h"
+#include "MCalibColorSet.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimeCalc.h"
+
+#include "MHGausEvents.h"
+#include "MHCalibrationCam.h"
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationChargeBlindCam.h"
+#include "MHCalibrationChargePINDiode.h"
+#include "MHCalibrationRelTimeCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MHCamEvent.h"
+
+#include "MReadMarsFile.h"
+#include "MPedCalcPedRun.h"
+#include "MRawFileRead.h"
+#include "MGeomApply.h"
+#include "MPedestalSubtract.h"
+#include "MTaskEnv.h"
+#include "MBadPixelsMerge.h"
+#include "MBadPixelsCam.h"
+#include "MExtractTime.h"
+#include "MExtractor.h"
+#include "MExtractPINDiode.h"
+#include "MExtractBlindPixel.h"
+#include "MExtractTimeAndChargeSpline.h"
+#include "MFCosmics.h"
+#include "MFTriggerPattern.h"
+#include "MContinue.h"
+#include "MFillH.h"
+
+#include "MTriggerPatternDecode.h"   
+
+#include "MArrivalTimeCam.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MJCalibration);
+
+using namespace std;
+
+const Int_t MJCalibration::gkIFAEBoxInaugurationRun        = 20113;
+const Int_t MJCalibration::gkSecondBlindPixelInstallation  = 31693;
+const Int_t MJCalibration::gkSpecialPixelsContInstallation = 34057;
+const Int_t MJCalibration::gkThirdBlindPixelInstallation   = 43308;
+const TString MJCalibration::fgReferenceFile = "mjobs/calibrationref.rc";
+const TString MJCalibration::fgHiLoCalibFile = "resources/hilocalib.rc";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - fExtractor to NULL, fTimeExtractor to NULL, fColor to kNONE,
+//   fDisplay to kNormalDisplay, kRelTimes to kFALSE, kataCheck to kFALSE, kDebug to kFALSE
+// - SetUseBlindPixel()
+// - SetUsePINDiode()
+//
+MJCalibration::MJCalibration(const char *name, const char *title) 
+    : fExtractor(NULL), fTimeExtractor(NULL), 
+      fColor(MCalibrationCam::kNONE), fDisplayType(kDataCheckDisplay),
+      fMinEvents(1000), fGeometry("MGeomCamMagic")
+{
+
+  fName  = name  ? name  : "MJCalibration";
+  fTitle = title ? title : "Tool to create the calibration constants for one calibration run";
+
+  //SetHiLoCalibration();
+  SetRelTimeCalibration();
+  SetDebug(kFALSE);
+
+  SetReferenceFile();
+  SetHiLoCalibFile();
+
+  fConvFADC2PheMin           = 0.;
+  fConvFADC2PheMax           = 1.5;
+  fConvFADC2PhotMin          = 0.; 
+  fConvFADC2PhotMax          = 10.; 
+  fQEMin                     = 0.;
+  fQEMax                     = 0.3;
+  fArrivalTimeMin            = 1.;
+  fArrivalTimeMax            = 10.;
+  fTimeOffsetMin             = -3.;
+  fTimeOffsetMax             =  3.;
+  fTimeResolutionMin         =  0.;
+  fTimeResolutionMax         =  1.;
+
+  fRefFADC2PheInner          = 0.14;
+  fRefFADC2PheOuter          = 0.4;
+  fRefConvFADC2PheInner      = 0.14;
+  fRefConvFADC2PheOuter      = 0.52;
+  fRefQEInner                = 0.18;
+  fRefQEOuter                = 0.12;
+  fRefArrivalTimeInner       = 4.5;
+  fRefArrivalTimeOuter       = 5.0;
+  fRefArrivalTimeRmsInner    = 0.5;
+  fRefArrivalTimeRmsOuter    = 0.5;
+  fRefTimeOffsetOuter        = 0.62;
+  fRefTimeResolutionInner    = 0.12;
+  fRefTimeResolutionOuter    = 0.09;
+}
+
+void MJCalibration::DrawTab(MParList &plist, const char *cont, const char *name, Option_t *opt)
+{
+    TObject *obj = plist.FindObject(cont);
+    if (!obj)
+        return;
+
+    fDisplay->AddTab(name);
+    obj->DrawClone(opt);
+}
+
+MHCamera *MJCalibration::DrawBadPixelPad(const MHCamera &h, Bool_t unsuit) const
+{
+    MHCamera *obj=(MHCamera*)h.DrawCopy("hist");
+
+    gStyle->SetPalette(1);
+
+    const Int_t numcol = gStyle->GetNumberOfColors();
+
+    const Double_t min = 1;
+    const Double_t max = unsuit ? MBadPixelsPix::GetNumUnsuitable() : MBadPixelsPix::GetNumUnreliable();
+    const Double_t f   = (numcol-1)/(max-min);
+
+    FixDataCheckHist(*obj, min, max);
+
+    TPaveText *pave = new TPaveText(0.05, 0.012, 0.975, 0.999);
+
+    const Double_t height = (pave->GetY2()-pave->GetY1())/(max+1);
+
+    pave->SetBit(kCanDelete);
+    pave->ConvertNDCtoPad();
+    pave->SetFillColor(14);
+    pave->Draw();
+
+    Int_t n=0;
+    while (1)
+    {
+        const TString name = unsuit ? MBadPixelsPix::GetUnsuitableName(++n) : MBadPixelsPix::GetUnreliableName(++n);
+        if (name.IsNull())
+            break;
+
+        Int_t cnt = 0;
+        for (UInt_t pix=0; pix<h.GetNumPixels(); pix++)
+            if (TMath::Nint(h.GetPixContent(pix)) == n)
+                cnt++;
+
+        const TString loc = unsuit?MBadPixelsPix::GetUnsuitableName(n):MBadPixelsPix::GetUnreliableName(n);
+
+        const TString left  = Form("%d) %s", n, loc.Data());
+        const TString right = Form("%3i pixels", cnt);
+
+        const Int_t col = gStyle->GetColorPalette(TMath::FloorNint((n-1)*f));
+
+        TText *p = pave->AddText(0.05, pave->GetY2()-height*(n+0.3), left);
+        p->SetTextColor(col);
+        p->SetTextAlign(12);
+
+        p = pave->AddText(0.95, p->GetY(), right);
+        p->SetTextColor(col);
+        p->SetTextAlign(32);
+    }
+
+    return obj;
+}
+
+// --------------------------------------------------------------------------
+//
+// Display the results in MStatusDisplay: 
+//
+// - Add "Calibration" to the MStatusDisplay title
+// - Retrieve the MGeomCam from MParList
+// - Initialize the following MHCamera's:
+//   1)  MCalibrationPix::GetMean()
+//   2)  MCalibrationPix::Sigma()
+//   3)  MCalibrationChargePix::GetRSigma()
+//   4)  MCalibrationChargePix::GetRSigmaPerCharge()
+//   5)  MCalibrationChargePix::GetPheFFactorMethod()
+//   6)  MCalibrationChargePix::GetMeanConvFADC2Phe()
+//   7)  MCalibrationChargePix::GetMeanFFactorFADC2Phot()
+//   8)  MCalibrationQEPix::GetQECascadesFFactor()
+//   9)  MCalibrationQEPix::GetQECascadesBlindPixel()
+//   10) MCalibrationQEPix::GetQECascadesPINDiode()
+//   11) MCalibrationQEPix::GetQECascadesCombined()
+//   12) MCalibrationQEPix::IsAverageQEFFactorAvailable()
+//   13) MCalibrationQEPix::IsAverageQEBlindPixelAvailable()
+//   14) MCalibrationQEPix::IsAverageQEPINDiodeAvailable()
+//   15) MCalibrationQEPix::IsAverageQECombinedAvailable()
+//   16) MCalibrationChargePix::IsHiGainSaturation()
+//   17) MCalibrationPix::GetHiLoMeansDivided()
+//   18) MCalibrationPix::GetHiLoSigmasDivided()
+//   19) MCalibrationChargePix::GetHiGainPickup()
+//   20) MCalibrationChargePix::GetLoGainPickup()
+//   21) MCalibrationChargePix::GetHiGainBlackout()
+//   22) MCalibrationChargePix::GetLoGainBlackout()
+//   23) MCalibrationPix::IsExcluded()
+//   24) MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun)
+//   25) MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnreliableRun)
+//   26) MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainOscillating)
+//   27) MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainOscillating)
+//   28) MCalibrationChargePix::GetAbsTimeMean()
+//   29) MCalibrationChargePix::GetAbsTimeRms()
+//
+// If the flag SetFullDisplay() is set, all MHCameras will be displayed. 
+// if the flag SetDataCheckDisplay() is set, only the most important ones are displayed 
+// and otherwise, (default: SetNormalDisplay()), a good selection of plots is given
+//
+void MJCalibration::DisplayResult(MParList &plist)
+{
+    if (!fDisplay)
+        return;
+
+    TString drawoption = "nonew ";
+    if (fDisplayType == kDataCheckDisplay)
+        drawoption += "datacheck";
+    if (fDisplayType == kFullDisplay)
+        drawoption += "all";
+
+    if (IsUsePINDiode())
+        DrawTab(plist, "MHCalibrationChargePINDiode", "PINDiode",  drawoption);
+    if (IsUseBlindPixel())
+        DrawTab(plist, "MHCalibrationChargeBlindCam", "BlindPix",  drawoption);
+    if (IsRelTimes())
+        DrawTab(plist, "MHCalibrationRelTimeCam",     "Time",      drawoption);
+    DrawTab(plist, "MHCalibrationChargeCam",          "Charge",    drawoption);
+
+    //
+    // Update display
+    //
+    TString title = "--  Calibration: ";
+    title += fSequence.GetSequence();
+    title += "  --";
+    fDisplay->SetTitle(title, kFALSE);
+
+    //
+    // Get container from list
+    //
+    MGeomCam &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
+
+    // Create histograms to display
+    MHCamera disp1 (geomcam, "Charge",            "Fitted Mean Signal (Charges)");
+    MHCamera disp2 (geomcam, "SigmaCharge",       "Sigma of Fitted Signal");
+    MHCamera disp3 (geomcam, "RSigma",            "Reduced Sigmas");
+    MHCamera disp4 (geomcam, "RSigmaPerCharge",   "Reduced Sigma per Charge");
+    MHCamera disp5 (geomcam, "NumPhes",           "Number Photo-electrons");
+    MHCamera disp6 (geomcam, "ConvFADC2Phes",     "Phes per Charge (Before Flat-Field)");
+    MHCamera disp7 (geomcam, "TotalFFactor",      "Total F-Factor(F-Factor Method)");
+    MHCamera disp8 (geomcam, "CascadesQEFFactor", "Cascades QE (F-Factor Method)");
+    MHCamera disp9 (geomcam, "CascadesQEBlindPix","Cascades QE (Blind Pixel Method)");
+    MHCamera disp10(geomcam, "CascadesQEPINDiode","Cascades QE (PIN Diode Method)");
+    MHCamera disp11(geomcam, "CascadesQECombined","Cascades QE (Combined Method)");
+    MHCamera disp12(geomcam, "FFactorValid",      "Pixels with Valid F-Factor Calibration");
+    MHCamera disp13(geomcam, "BlindPixelValid",   "Pixels with valid BlindPixel Calibration");
+    MHCamera disp14(geomcam, "PINdiodeValid",     "Pixels with Valid PINDiode Calibration");
+    MHCamera disp15(geomcam, "CombinedValid",     "Pixels with Valid Combined Calibration");
+    MHCamera disp16(geomcam, "Saturation",        "Pixels with Saturated Hi Gain");
+    MHCamera disp17(geomcam, "ConversionMeans",   "Conversion HiGain.vs.LoGain Means");
+    MHCamera disp18(geomcam, "ConversionSigmas",  "Conversion HiGain.vs.LoGain Sigmas");
+    MHCamera disp19(geomcam, "HiGainPickup",      "Number Pickup Events Hi Gain");
+    MHCamera disp20(geomcam, "LoGainPickup",      "Number Pickup Events Lo Gain");
+    MHCamera disp21(geomcam, "HiGainBlackout",    "Number Blackout Events Hi Gain");
+    MHCamera disp22(geomcam, "LoGainBlackout",    "Number Blackout Events Lo Gain");
+    MHCamera disp23(geomcam, "Excluded",          "Pixels Previously Excluded");
+    MHCamera disp24(geomcam, "UnSuitable",        "Pixels NOT Suited for Further Analysis");
+    MHCamera disp25(geomcam, "UnReliable",        "Pixels Suitable, but NOT Reliable for Further Analysis");
+    MHCamera disp26(geomcam, "HiGainOscillating", "Oscillating Pixels High Gain");
+    MHCamera disp27(geomcam, "LoGainOscillating", "Oscillating Pixels Low Gain");
+    MHCamera disp28(geomcam, "AbsTimeMean",       "Abs. Arrival Times");
+    MHCamera disp29(geomcam, "AbsTimeRms",        "RMS of Arrival Times");
+    MHCamera disp30(geomcam, "MeanTime",          "Mean Rel. Arrival Times");
+    MHCamera disp31(geomcam, "SigmaTime",         "Sigma Rel. Arrival Times");
+    MHCamera disp32(geomcam, "TimeProb",          "Probability of Time Fit");
+    MHCamera disp33(geomcam, "TimeNotFitValid",   "Pixels with not valid Fit Results");
+    MHCamera disp34(geomcam, "TimeOscillating",   "Oscillating Pixels");
+    MHCamera disp35(geomcam, "TotalConv",         "Conversion Factor to Photons");
+    MHCamera disp36(geomcam, "RMSperMean",        "Charge histogram RMS per Mean");
+    MHCamera disp37(geomcam, "TotalConvPhe",      "Conversion Factor to equiv. Phe's");
+
+    // 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, 6);
+    disp25.SetCamContent(fBadPixels, 7);
+
+    // Oscillations
+    disp26.SetCamContent(fBadPixels, 10);
+    disp27.SetCamContent(fBadPixels, 11);
+
+    // Arrival Times
+    disp28.SetCamContent(fCalibrationCam, 26);
+    disp28.SetCamError(  fCalibrationCam, 27);
+    disp29.SetCamContent(fCalibrationCam, 27);
+
+    // RMS and Mean
+    disp36.SetCamContent(fCalibrationCam,32);
+    disp36.SetCamError(fCalibrationCam,33);
+
+    disp1.SetYTitle("Q [FADC cnts]");
+    disp2.SetYTitle("\\sigma_{Q} [FADC cnts]");
+
+    disp3.SetYTitle("\\sqrt{\\sigma^{2}_{Q} - RMS^{2}_{Ped}} [FADC cnts]");
+    disp4.SetYTitle("Red.Sigma/<Q> [1]");
+
+    disp5.SetYTitle("Photo-electons [1]");
+    disp6.SetYTitle("Phes/<Q> [FADC cnts^{-1}]");
+    disp7.SetYTitle("Total F-Factor [1]");
+
+    disp8.SetYTitle("QE [1]");
+    disp9.SetYTitle("QE [1]");
+    disp10.SetYTitle("QE [1]");
+    disp11.SetYTitle("QE [1]");
+
+    disp12.SetYTitle("[1]");
+    disp13.SetYTitle("[1]");
+    disp14.SetYTitle("[1]");
+    disp15.SetYTitle("[1]");
+    disp16.SetYTitle("[1]");
+
+    disp17.SetYTitle("<Q>(High)/<Q>(Low) [1]");
+    disp18.SetYTitle("\\sigma_{Q}(High)/\\sigma_{Q}(Low) [1]");
+
+    disp19.SetYTitle("[1]");
+    disp20.SetYTitle("[1]");
+    disp21.SetYTitle("[1]");
+    disp22.SetYTitle("[1]");
+    //    disp23.SetYTitle("[1]");
+    //    disp24.SetYTitle("[1]");
+    //    disp25.SetYTitle("[1]");
+    disp26.SetYTitle("[1]");
+    disp27.SetYTitle("[1]");
+
+    disp28.SetYTitle("Mean Abs. Time [FADC sl.]");
+    disp29.SetYTitle("RMS Abs. Time [FADC sl.]");
+    disp35.SetYTitle("Conv.Factor [Ph/FADC cnts]");
+    disp36.SetYTitle("Charge RMS/<Q> [1]");
+    disp37.SetYTitle("Conv.Factor [Phe/FADC cnts]");
+
+    for (UInt_t i=0;i<geomcam.GetNumPixels();i++)
+      {
+
+        MCalibrationChargePix &pix = (MCalibrationChargePix&)fCalibrationCam[i];
+        MCalibrationQEPix     &qe  = (MCalibrationQEPix&)fQECam[i];
+
+        if (!pix.IsFFactorMethodValid())
+          continue;
+
+        const Float_t convphe  = pix.GetMeanConvFADC2Phe();
+        const Float_t quaeff   = qe.GetQECascadesFFactor();
+
+        disp35.Fill(i,convphe/quaeff);
+        disp35.SetUsed(i);
+
+        disp37.Fill(i,convphe/quaeff*MCalibrationQEPix::gkDefaultAverageQE);
+        disp37.SetUsed(i);
+      }
+    
+
+    if (IsRelTimes())
+    {
+        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 [FADC units]");
+        disp31.SetYTitle("Timing resolution [FADC units]");
+        disp32.SetYTitle("P_{Time} [1]");
+        disp33.SetYTitle("[1]");
+        disp34.SetYTitle("[1]");
+    }
+
+    if (fDisplayType == kDataCheckDisplay)
+    {
+      // -------------------- FitCharge -------------------
+
+      TCanvas &c1 = fDisplay->AddTab("FitCharge");
+      c1.Divide(3, 3);
+
+      disp1.CamDraw( c1, 1, 3, 6);   // MEAN CHARGES
+      disp36.CamDraw(c1, 2, 3, 6);   // RMS per Charge
+      disp5.CamDraw( c1, 3, 3, 6);   // PHOTO ELECTRONS
+
+      // -------------------- Conversion -------------------
+
+      TCanvas &c2 = fDisplay->AddTab("Conversion");
+      c2.Divide(3,3);
+
+      disp6.SetMinMax(fConvFADC2PheMin, fConvFADC2PheMax);
+      disp8.SetMinMax(fQEMin, fQEMax);
+      disp37.SetMinMax(fConvFADC2PheMin, fConvFADC2PheMax);
+
+      disp6.CamDraw( c2, 1, 3, 6);   // CONVERSION FACTORS
+      disp8.CamDraw( c2, 2, 3, 6);   // QUANTUM EFFICIENCY
+      disp37.CamDraw(c2, 3, 3, 6);   // CONVERSION FADC TO PHOTONS
+
+      c2.cd(1);
+      DisplayReferenceLines(disp6, 2);
+
+      c2.cd(2);
+      DisplayReferenceLines(disp8, 0);
+
+      c2.cd(3);
+      DisplayReferenceLines(disp37, 1);
+
+      // -------------------- AbsTimes -------------------
+
+      TCanvas &c3 = fDisplay->AddTab("AbsTimes");
+      c3.Divide(2,3);
+
+      disp28.SetMinMax(fArrivalTimeMin, fArrivalTimeMax);
+
+      disp28.CamDraw(c3, 1, 2, 6);  // Arrival times
+      disp29.CamDraw(c3, 2, 2, 6);  // Arrival times rms
+
+      c3.cd(1);
+      DisplayReferenceLines(disp28, 3);
+
+      c3.cd(2);
+      DisplayReferenceLines(disp29, 4);
+
+      if (IsRelTimes())
+      {
+          // -------------------- RelTimes -------------------
+
+          TCanvas &c5 = fDisplay->AddTab("RelTimes");
+          c5.Divide(2,3);
+
+          disp30.SetMinMax(fTimeOffsetMin, fTimeOffsetMax);
+          disp31.SetMinMax(fTimeResolutionMin, fTimeResolutionMax);
+
+          disp30.CamDraw(c5, 1, 2, 6); // MEAN REL. ARR. TIMES
+          disp31.CamDraw(c5, 2, 2, 6); // JITTER Rel. Arr. Times
+
+          c5.cd(1);
+          DisplayReferenceLines(disp30, 5);
+
+          c5.cd(2);
+          DisplayReferenceLines(disp31, 6);
+      }
+
+      // -------------------- Unsuitable -------------------
+
+      //
+      // UNSUITABLE PIXELS
+      //
+      TCanvas &c4 = fDisplay->AddTab("Defect");
+      c4.Divide(2,2, 0.005, 0.005);
+
+      c4.cd(1);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+
+      MHCamera *obj8 = DrawBadPixelPad(disp24, kTRUE);
+
+      c4.cd(3);
+      gPad->SetBorderMode(0);
+      obj8->SetPrettyPalette();
+      obj8->Draw();
+
+      //
+      // UNRELIABLE PIXELS
+      // 
+      c4.cd(2);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+
+      MHCamera *obj9 = DrawBadPixelPad(disp25, kFALSE);
+
+      c4.cd(4);
+      gPad->SetBorderMode(0);
+      obj9->SetPrettyPalette();
+      obj9->Draw();
+      return;
+    }
+
+    if (fDisplayType == kNormalDisplay)
+      {
+
+        // Charges
+        TCanvas &c11 = fDisplay->AddTab("FitCharge");
+        c11.Divide(2, 4);
+
+        disp1.CamDraw(c11, 1, 2, 5, 1);
+        disp2.CamDraw(c11, 2, 2, 5, 1);
+
+        // Reduced Sigmas
+        TCanvas &c12 = fDisplay->AddTab("RedSigma");
+        c12.Divide(2,4);
+
+        disp3.CamDraw(c12, 1, 2, 5, 1);
+        disp4.CamDraw(c12, 2, 2, 5, 1);
+
+        //  F-Factor
+        TCanvas &c13 = fDisplay->AddTab("Phe's");
+        c13.Divide(3,4);
+
+        disp5.CamDraw(c13, 1, 3, 5, 1);
+        disp6.CamDraw(c13, 2, 3, 5, 1);
+        disp7.CamDraw(c13, 3, 3, 5, 1);
+
+        // QE's
+        TCanvas &c14 = fDisplay->AddTab("QE's");
+        c14.Divide(4,4);
+
+        disp8.CamDraw(c14, 1, 4, 5, 1);
+        disp9.CamDraw(c14, 2, 4, 5, 1);
+        disp10.CamDraw(c14, 3, 4, 5, 1);
+        disp11.CamDraw(c14, 4, 4, 5, 1);
+
+        // Defects
+        TCanvas &c15 = fDisplay->AddTab("Defect");
+        //      c15.Divide(5,2);
+        c15.Divide(4,2);
+
+        /*
+        disp23.CamDraw(c15, 1, 5, 0);
+        disp24.CamDraw(c15, 2, 5, 0);
+        disp25.CamDraw(c15, 3, 5, 0);
+        disp26.CamDraw(c15, 4, 5, 0);
+        disp27.CamDraw(c15, 5, 5, 0);
+        */
+        disp24.CamDraw(c15, 1, 4, 0);
+        disp25.CamDraw(c15, 2, 4, 0);
+        disp26.CamDraw(c15, 3, 4, 0);
+        disp27.CamDraw(c15, 4, 4, 0);
+
+        // Abs. Times
+        TCanvas &c16 = fDisplay->AddTab("AbsTimes");
+        c16.Divide(2,3);
+
+        disp28.CamDraw(c16, 1, 2, 5);
+        disp29.CamDraw(c16, 2, 2, 5);
+
+        if (IsRelTimes())
+        {
+            // Rel. Times
+            TCanvas &c17 = fDisplay->AddTab("RelTimes");
+            c17.Divide(2,4);
+
+            disp30.CamDraw(c17, 1, 2, 5, 1);
+            disp31.CamDraw(c17, 2, 2, 5, 1);
+        }
+
+        return;
+    }
+
+    if (fDisplayType == kFullDisplay)
+    {
+        MHCalibrationCam *cam = (MHCalibrationCam*)plist.FindObject("MHCalibrationChargeCam");
+
+        for (Int_t sector=1;sector<cam->GetAverageSectors();sector++)
+        {
+            cam->GetAverageHiGainSector(sector).DrawClone("all");
+            cam->GetAverageLoGainSector(sector).DrawClone("all");
+        }
+
+        // Charges
+        TCanvas &c21 = fDisplay->AddTab("FitCharge");
+        c21.Divide(2, 4);
+
+        disp1.CamDraw(c21, 1, 2, 2, 1);
+        disp2.CamDraw(c21, 2, 2, 2, 1);
+
+        // Reduced Sigmas
+        TCanvas &c23 = fDisplay->AddTab("RedSigma");
+        c23.Divide(2,4);
+
+        disp3.CamDraw(c23, 1, 2, 2, 1);
+        disp4.CamDraw(c23, 2, 2, 2, 1);
+
+        //  F-Factor
+        TCanvas &c24 = fDisplay->AddTab("Phe's");
+        c24.Divide(3,5);
+
+        disp5.CamDraw(c24, 1, 3, 2, 1, 1);
+        disp6.CamDraw(c24, 2, 3, 2, 1, 1);
+        disp7.CamDraw(c24, 3, 3, 2, 1, 1);
+
+        // QE's
+        TCanvas &c25 = fDisplay->AddTab("QE's");
+        c25.Divide(4,5);
+
+        disp8.CamDraw(c25, 1, 4, 2, 1, 1);
+        disp9.CamDraw(c25, 2, 4, 2, 1, 1);
+        disp10.CamDraw(c25, 3, 4, 2, 1, 1);
+        disp11.CamDraw(c25, 4, 4, 2, 1, 1);
+
+        // Validity
+        TCanvas &c26 = fDisplay->AddTab("Valid");
+        c26.Divide(4,2);
+
+        disp12.CamDraw(c26, 1, 4, 0);
+        disp13.CamDraw(c26, 2, 4, 0);
+        disp14.CamDraw(c26, 3, 4, 0);
+        disp15.CamDraw(c26, 4, 4, 0);
+
+        // Other info
+        TCanvas &c27 = fDisplay->AddTab("HiLoGain");
+        c27.Divide(3,3);
+        
+        disp16.CamDraw(c27, 1, 3, 0);
+        disp17.CamDraw(c27, 2, 3, 1);
+        disp18.CamDraw(c27, 3, 3, 1);
+
+        // Pickup
+        TCanvas &c28 = fDisplay->AddTab("Pickup");
+        c28.Divide(4,2);
+
+        disp19.CamDraw(c28, 1, 4, 0);
+        disp20.CamDraw(c28, 2, 4, 0);
+        disp21.CamDraw(c28, 3, 4, 0);
+        disp22.CamDraw(c28, 4, 4, 0);
+
+        // Defects
+        TCanvas &c29 = fDisplay->AddTab("Defect");
+        //      c29.Divide(5,2);
+        c29.Divide(4,2);
+
+        disp24.CamDraw(c29, 1, 4, 0);
+        disp25.CamDraw(c29, 2, 4, 0);
+        disp26.CamDraw(c29, 3, 4, 0);
+        disp27.CamDraw(c29, 4, 4, 0);
+
+        // Abs. Times
+        TCanvas &c30 = fDisplay->AddTab("AbsTimes");
+        c30.Divide(2,3);
+
+        disp28.CamDraw(c30, 1, 2, 2);
+        disp29.CamDraw(c30, 2, 2, 1);
+
+        if (IsRelTimes())
+        {
+            // Rel. Times
+            TCanvas &c31 = fDisplay->AddTab("RelTimes");
+            c31.Divide(3,5);
+
+            disp30.CamDraw(c31, 1, 3, 2, 1, 1);
+            disp31.CamDraw(c31, 2, 3, 2, 1, 1);
+            disp32.CamDraw(c31, 3, 3, 4, 1, 1);
+
+            // Time Defects
+            TCanvas &c32 = fDisplay->AddTab("DefTime");
+            c32.Divide(2,2);
+
+            disp33.CamDraw(c32, 1, 2, 0);
+            disp34.CamDraw(c32, 2, 2, 0);
+
+            MHCalibrationCam *ccam = (MHCalibrationCam*)plist.FindObject("MHCalibrationRelTimeCam");
+
+            for (Int_t sector=1;sector<ccam->GetAverageSectors();sector++)
+            {
+                ccam->GetAverageHiGainSector(sector).DrawClone("fourierevents");
+                ccam->GetAverageLoGainSector(sector).DrawClone("fourierevents");
+            }
+
+        }
+
+        return;
+    }
+}
+
+void  MJCalibration::DisplayReferenceLines(const MHCamera &hist, const Int_t what) const
+{
+    MHCamera *cam = dynamic_cast<MHCamera*>(gPad->FindObject(hist.GetName()));
+    if (!cam)
+        return;
+
+  const MGeomCam *geom = cam->GetGeometry();
+
+  const Double_t x = geom->InheritsFrom("MGeomCamMagic") ? 397 : cam->GetNbinsX() ;
+
+  TLine line;
+  line.SetLineStyle(kDashed);
+  line.SetLineWidth(3);
+  line.SetLineColor(kBlue);
+
+  TLine *l1 = NULL;
+
+  switch (what)
+    {
+    case 0:
+      l1 = line.DrawLine(0, fRefQEInner, x, fRefQEInner);      
+      break;
+    case  1:
+      l1 = line.DrawLine(0, fRefConvFADC2PheInner, x, fRefConvFADC2PheInner);
+      break;
+    case  2:
+      l1 = line.DrawLine(0, fRefFADC2PheInner, x, fRefFADC2PheInner );
+      break;
+    case  3:
+      l1 = line.DrawLine(0, fRefArrivalTimeInner, x, fRefArrivalTimeInner );
+      break;
+    case  4:
+      l1 = line.DrawLine(0, fRefArrivalTimeRmsInner, x, fRefArrivalTimeRmsInner );
+      break;
+    case 5:
+      l1 = line.DrawLine(0, 0, x, 0);
+      break;
+    case 6:
+      l1 = line.DrawLine(0, fRefTimeResolutionInner, x, fRefTimeResolutionInner );
+      break;
+    default:
+      break;
+    }
+
+  if (geom->InheritsFrom("MGeomCamMagic"))
+    {
+      const Double_t x2 = cam->GetNbinsX();
+
+      switch (what)
+        {
+        case 0:
+          line.DrawLine(x2, fRefQEOuter, 398, fRefQEOuter);      
+          break;
+        case 1:
+          line.DrawLine(x2, fRefConvFADC2PheOuter, 398, fRefConvFADC2PheOuter );
+          break;
+        case 2:
+          line.DrawLine(x2, fRefFADC2PheOuter, 398, fRefFADC2PheOuter);
+          break;
+        case 3:
+          line.DrawLine(x2, fRefArrivalTimeOuter, 398, fRefArrivalTimeOuter);
+          break;
+        case 4:
+          line.DrawLine(x2, fRefArrivalTimeRmsOuter, 398, fRefArrivalTimeRmsOuter);
+          break;
+        case 5:
+          line.DrawLine(x2, fRefTimeOffsetOuter, 398, fRefTimeOffsetOuter);
+          break;
+        case 6:
+          line.DrawLine(x2, fRefTimeResolutionOuter, 398, fRefTimeResolutionOuter);
+          break;
+	default:
+	  break;
+        }
+    }
+
+  TLegend *leg = new TLegend(0.6,0.85,0.9 ,0.95);
+  leg->SetBit(kCanDelete);
+  leg->AddEntry(l1, "Reference","l");
+  leg->Draw();
+}
+
+/*
+void  MJCalibration::DisplayOutliers(TH1D *hist, const char* whatsmall, const char* whatbig) const
+{
+
+  const Int_t kNotDraw = 1<<9;
+  TF1 *f = hist->GetFunction("gaus");
+  f->ResetBit(kNotDraw);
+
+  const Float_t mean  = f->GetParameter(1);
+  const Float_t lolim = mean - 4.0*f->GetParameter(2);
+  const Float_t uplim = mean + 4.0*f->GetParameter(2);
+  const Stat_t  dead  = hist->Integral(0,hist->FindBin(lolim)-1);
+  const Stat_t  noisy = hist->Integral(hist->FindBin(uplim)+1,hist->GetNbinsX()+1);
+
+  const Double_t max = hist->GetBinContent(hist->GetMaximumBin());                                           
+  
+  const Double_t minl = hist->GetBinCenter(hist->GetXaxis()->GetFirst());
+  const Double_t maxl = hist->GetBinCenter(hist->GetXaxis()->GetLast());
+
+  TLatex deadtex;
+  deadtex.SetTextSize(0.07);
+  deadtex.DrawLatex(minl+0.015*(maxl-minl),max/1.1,
+                    Form("%3i %s pixels",(Int_t)dead,whatsmall));
+
+  TLatex noisytex;
+  noisytex.SetTextSize(0.07);
+  noisytex.DrawLatex(minl+0.015*(maxl-minl),max/1.2,
+                     Form("%3i %s pixels",(Int_t)noisy,whatbig));
+
+}
+*/
+
+void MJCalibration::FixDataCheckHist(TH1D &h, Double_t min, Double_t max)
+{
+    h.SetDirectory(NULL);
+    h.SetStats(kFALSE);
+    h.SetMinimum(min);
+    h.SetMaximum(max);
+
+    //
+    // set the labels bigger
+    //
+    TAxis *xaxe = h.GetXaxis();
+    TAxis *yaxe = h.GetYaxis();
+
+    xaxe->CenterTitle();
+    yaxe->CenterTitle();    
+    xaxe->SetTitleSize(0.06);
+    yaxe->SetTitleSize(0.06);    
+    xaxe->SetTitleOffset(0.8);
+    yaxe->SetTitleOffset(0.85);    
+    xaxe->SetLabelSize(0.05);
+    yaxe->SetLabelSize(0.05);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieve the output file written by WriteResult()
+// 
+const char* MJCalibration::GetOutputFileName() const
+{
+    return Form("calib%08d.root", fSequence.GetSequence());
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following values from resource file:
+//
+//   ConvFADC2PheMin
+//   ConvFADC2PheMax
+//   ConvFADC2PhotMin
+//   ConvFADC2PhotMax
+//
+//   QEMin
+//   QEMax
+//
+//   ArrivalTimeMin
+//   ArrivalTimeMax
+//
+//   TimeOffsetMin
+//   TimeOffsetMax
+//   TimeResolutionMin
+//   TimeResolutionMax
+//
+//   RefConvFADC2PheInner
+//   RefConvFADC2PheOuter
+//   RefConvFADC2PhotInner
+//   RefConvFADC2PhotOuter
+//
+//   RefQEInner
+//   RefQEOuter
+//
+//   RefArrivalTimeInner
+//   RefArrivalTimeOuter
+//   RefArrivalTimeRmsInner
+//   RefArrivalTimeRmsOuter
+//
+//   RefTimeOffsetOuter
+//   RefTimeResolutionInner
+//   RefTimeResolutionOuter
+//
+void MJCalibration::ReadReferenceFile()
+{
+    TEnv refenv(fReferenceFile);
+
+    fConvFADC2PheMin        = refenv.GetValue("ConvFADC2PheMin",fConvFADC2PheMin);
+    fConvFADC2PheMax        = refenv.GetValue("ConvFADC2PheMax",fConvFADC2PheMax);
+    fConvFADC2PhotMin       = refenv.GetValue("ConvFADC2PhotMin",fConvFADC2PhotMin);
+    fConvFADC2PhotMax       = refenv.GetValue("ConvFADC2PhotMax",fConvFADC2PhotMax);
+    fQEMin                  = refenv.GetValue("QEMin",fQEMin);
+    fQEMax                  = refenv.GetValue("QEMax",fQEMax);
+    fArrivalTimeMin         = refenv.GetValue("ArrivalTimeMin",fArrivalTimeMin);
+    fArrivalTimeMax         = refenv.GetValue("ArrivalTimeMax",fArrivalTimeMax);
+    fTimeOffsetMin          = refenv.GetValue("TimeOffsetMin",fTimeOffsetMin);
+    fTimeOffsetMax          = refenv.GetValue("TimeOffsetMax",fTimeOffsetMax);
+    fTimeResolutionMin      = refenv.GetValue("TimeResolutionMin",fTimeResolutionMin);
+    fTimeResolutionMax      = refenv.GetValue("TimeResolutionMax",fTimeResolutionMax);
+			     		                        
+    fRefFADC2PheInner       = refenv.GetValue("RefFADC2PheInner",fRefFADC2PheInner);
+    fRefFADC2PheOuter       = refenv.GetValue("RefFADC2PheOuter",fRefFADC2PheOuter);
+    fRefConvFADC2PhotInner  = refenv.GetValue("RefConvFADC2PhotInner",fRefConvFADC2PhotInner);
+    fRefConvFADC2PhotOuter  = refenv.GetValue("RefConvFADC2PhotOuter",fRefConvFADC2PhotOuter);
+    fRefConvFADC2PheInner   = refenv.GetValue("RefConvFADC2PheInner",fRefConvFADC2PheInner);
+    fRefConvFADC2PheOuter   = refenv.GetValue("RefConvFADC2PheOuter",fRefConvFADC2PheOuter);
+    fRefQEInner             = refenv.GetValue("RefQEInner",fRefQEInner);
+    fRefQEOuter             = refenv.GetValue("RefQEOuter",fRefQEOuter);
+    fRefArrivalTimeInner    = refenv.GetValue("RefArrivalTimeInner",fRefArrivalTimeInner);
+    fRefArrivalTimeOuter    = refenv.GetValue("RefArrivalTimeOuter",fRefArrivalTimeOuter);
+    fRefArrivalTimeRmsInner = refenv.GetValue("RefArrivalTimeRmsInner",fRefArrivalTimeRmsInner);
+    fRefArrivalTimeRmsOuter = refenv.GetValue("RefArrivalTimeRmsOuter",fRefArrivalTimeRmsOuter);
+    fRefTimeOffsetOuter     = refenv.GetValue("RefTimeOffsetOuter",fRefTimeOffsetOuter);
+    fRefTimeResolutionInner = refenv.GetValue("RefTimeResolutionInner",fRefTimeResolutionInner);
+    fRefTimeResolutionOuter = refenv.GetValue("RefTimeResolutionOuter",fRefTimeResolutionOuter);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following values from resource file.
+//
+Bool_t MJCalibration::ReadHiLoCalibFile()
+{
+    if (fExtractor && !fExtractor->HasLoGain())
+        return kTRUE;
+
+//    if (!fIsHiLoCalibration)
+//        return kTRUE;
+
+    // We use the night time stamp to determine the period
+    // because the night must be in the sequence file
+    const MTime &night = fSequence.GetNight();
+    const Int_t period = night.GetMagicPeriod();
+
+    // Open resource file
+    MEnv env(fHiLoCalibFile);
+    if (!env.IsValid())
+    {
+        *fLog << err << "ERROR - Resource file " << fHiLoCalibFile;
+        *fLog << " could not be opened... abort." << endl;
+        return kFALSE;
+    }
+
+    // Defined resource id
+    const TString id = fSequence.IsMonteCarlo() ? "MC" : Form("%02d", period);
+
+    // Check for a valid entry for the correct period
+    TString fname = env.GetValue(id, "");
+    if (fname.IsNull())
+    {
+        *fLog << err << "ERROR - No entry for resource id '" << id;
+        *fLog << "' found in " << fHiLoCalibFile << "... looking for default." << endl;
+        return kFALSE;
+/*
+        *fLog << warn << "WARNING - No entry for period " << period;
+        *fLog << " found in " << fHiLoCalibFile << "... looking for default." << endl;
+
+        fname = env.GetValue("00", "");
+        if (fname.IsNull())
+        {
+            *fLog << err << "ERROR - No default entry (00) found in ";
+            *fLog << fHiLoCalibFile << "... abort." << endl;
+            return kFALSE;
+        }*/
+    }
+
+    *fLog << inf << "Reading Hi-/Lo-Gain calibration constants from " << fname << endl;
+
+    // Open file with calibration constants
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << "ERROR - Couldn't open file " << fname << " for reading... abort." << endl;
+        return kFALSE;
+    }
+
+    // read calibration constants
+    MHCamEvent hilocam;
+    if (hilocam.Read()<=0)
+    {
+        *fLog << err << "ERROR - Unable to read MHCamEvent from " << fname << "... abort." << endl;
+        return kFALSE;
+    }
+
+    // Get histogram with constants
+    MHCamera *hist = hilocam.GetHist();
+    if (!hist)
+    {
+        *fLog << err << "ERROR - MHCamEvent from " << fname << " empty... abort." << endl;
+        return kFALSE;
+    }
+
+    // Do some sanity stuff
+    if (fCalibrationCam.GetSize() < 1)
+        fCalibrationCam.InitSize(hist->GetNumPixels());
+  
+    if (fBadPixels.GetSize() < 1)
+        fBadPixels.InitSize(hist->GetNumPixels());
+  
+    if ((UInt_t)fCalibrationCam.GetSize() != hist->GetNumPixels())
+    {
+        *fLog << err << "ERROR - Size mismatch MHCamEvent and MCalibrationChargeCam.. abort." << endl;
+        return kFALSE;
+    }
+
+    // Copy the constants to their final location
+    // FIXME: For what the hell do we need to have the constants in
+    //        in MCalibrationChargeCam?
+    for (UInt_t i=0; i<hist->GetNumPixels(); i++)
+    {
+        hist->SetBit(MHCamera::kProfile);
+        Double_t v = hist->GetBinContent(i);
+        hist->SetBit(MHCamera::kErrorMean);
+        Double_t e = hist->GetBinError(i);
+        hist->ResetBit(MHCamera::kErrorMean);
+        Double_t s = hist->GetBinError(i);
+
+        if (!hist->IsUsed(i))
+        {
+            fBadPixels[i].SetUncalibrated(MBadPixelsPix::kConversionHiLoNotValid);
+            v = e = s = -1;
+        }
+
+        MCalibrationChargePix &cpix = (MCalibrationChargePix&)fCalibrationCam[i];
+        cpix.SetConversionHiLo(v);
+        cpix.SetConversionHiLoErr(e);
+        cpix.SetConversionHiLoSigma(s);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// MJCalibration allows to setup several option by a resource file:
+//   MJCalibration.Display: full, datacheck, normal
+//   MJCalibration.RelTimeCalibration: yes,no
+//   MJCalibration.DataCheck: yes,no
+//   MJCalibration.Debug: yes,no
+//   MJCalibration.UseBlindPixel: yes,no
+//   MJCalibration.UsePINDiode: yes,no
+//   MJCalibration.Geometry: MGeomCamMagic, MGeomCamECO1000
+//
+// Name of a file containing reference values (see ReadReferenceFile)
+//   Prefix.ReferenceFile:    filename
+// (see ReadReferenceFile)
+//
+// For more details see the class description and the corresponding Getters
+// 
+Bool_t MJCalibration::CheckEnvLocal()
+{
+    TString dis = GetEnv("Display", "");
+    if (dis.BeginsWith("Full", TString::kIgnoreCase))
+        SetFullDisplay();
+    if (dis.BeginsWith("DataCheck", TString::kIgnoreCase))
+        SetDataCheckDisplay();
+    if (dis.BeginsWith("Normal", TString::kIgnoreCase))
+        SetNormalDisplay();
+
+    if (!MJCalib::CheckEnvLocal())
+        return kFALSE;
+
+    SetRelTimeCalibration(GetEnv("RelTimeCalibration", IsRelTimes()));
+    SetDebug(GetEnv("Debug", IsDebug()));
+
+    SetUseBlindPixel(GetEnv("UseBlindPixel", IsUseBlindPixel()));
+    SetUsePINDiode(GetEnv("UsePINDiode", IsUsePINDiode()));
+    SetGeometry(GetEnv("Geometry", fGeometry));
+
+    fMinEvents = (UInt_t)GetEnv("MinEvents", (Int_t)fMinEvents);
+
+    fReferenceFile = GetEnv("ReferenceFile",fReferenceFile.Data());
+    ReadReferenceFile();
+
+    fHiLoCalibFile = GetEnv("HiLoCalibFile",fHiLoCalibFile.Data());
+
+    /*
+    if (IsUseMC() && !fHiLoCalibFile.EndsWith("_mc.root"))
+    {
+        if (!fHiLoCalibFile.EndsWith(".root"))
+        {
+            *fLog << warn << "WARNING - Hi-/Lo-Gain intercalibration file ";
+            *fLog << fHiLoCalibFile << " has not .root as extension..." << endl;
+        }
+        else
+            fHiLoCalibFile.Insert(fHiLoCalibFile.Length()-5, "_mc");
+    }
+    */
+
+    return ReadHiLoCalibFile();
+}
+
+void MJCalibration::InitBlindPixel(MExtractBlindPixel &blindext,
+                                   MHCalibrationChargeBlindCam &blindcam)
+{
+    const Int_t run = fSequence.GetLastRun();
+
+    //
+    // Initialize the blind pixel. Unfortunately, there is a hardware
+    // difference in the first blind pixel until run
+    // gkSecondBlindPixelInstallation and the later setup. The first
+    // needs to use a filter because of the length of spurious NSB photon
+    // signals. The latter get better along extracting the amplitude
+    // from a small window.
+    //
+    const MCalibrationBlindCamOneOldStyle   one;
+    const MCalibrationBlindCamTwoNewStyle   two;
+    const MCalibrationBlindCamThreeNewStyle three;
+
+    const MCalibrationBlindCam &blindresults =
+        run<gkSecondBlindPixelInstallation ? static_cast<MCalibrationBlindCam>(one) :
+        (run<gkThirdBlindPixelInstallation ? static_cast<MCalibrationBlindCam>(two) : static_cast<MCalibrationBlindCam>(three));
+
+    blindresults.Copy(fCalibrationBlindCam);
+
+    blindext.SetExtractionType(MExtractBlindPixel::kIntegral);
+    blindext.SetExtractionType(MExtractBlindPixel::kFilter);
+
+    if (run<gkSecondBlindPixelInstallation)
+    {
+        blindext.SetRange(10,19,0,6);
+        blindext.SetNSBFilterLimit(70);
+    }
+    else
+    {
+        blindext.SetRange(5,8,0,2);
+        blindext.SetNSBFilterLimit(38);
+    }
+
+    if (run>=gkThirdBlindPixelInstallation)
+        blindext.SetDataType(MExtractBlindPixel::kRawEvt2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Execute the task list and the eventloop:
+//
+// - Check the colour of the files in fRuns (FindColor()), otherwise return
+// - Check for consistency between run numbers and number of files
+// - Add fRuns to MReadMarsFile
+// - Put into MParList:
+//   1) MPedestalCam          (pedcam)
+//   2) MCalibrationQECam     (fQECam)
+//   3) MCalibrationChargeCam (fCalibrationCam)
+//   4) MCalibrationRelTimeCam (fRelTimeCam)   (only if flag IsRelTimes() is chosen)
+//   5) MBadPixelsCam         (fBadPixels)
+//   6) MCalibrationChargePINDiode
+//   7) MCalibrationBlindPix
+// - Put into the MTaskList:
+//   1)  MReadMarsFile
+//   2)  MBadPixelsMerge
+//   3)  MGeomApply
+//   4)  MExtractor
+//   5)  MExtractPINDiode
+//   6)  MExtractBlindPixel
+//   7)  MExtractTime (only if flag IsRelTimes() is chosen)
+//   8)  MContinue(MFCosmics)
+//   9)  MFillH("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode",   "FillPINDiode")
+//   10) MFillH("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel", "FillBlindCam")
+//   11) MFillH("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillChargeCam")
+//   12) MFillH("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillRelTime")
+//   13) MCalibrationChargeCalc
+//   14) MFillH("MHCalibrationRelTimeCam",     "MArrivalTimeCam") (only if flag IsRelTimes() is chosen)
+//   15) MCalibrationRelTimeCalc
+// - Execute MEvtLoop
+// - DisplayResult()
+// - WriteResult()
+//
+Bool_t MJCalibration::Process(MPedestalCam &pedcam)
+{
+    if (!fSequence.IsValid())
+    {
+	  *fLog << err << "ERROR - Sequence invalid..." << endl;
+	  return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate calibration constants from Sequence #";
+    *fLog << fSequence.GetSequence() << endl << endl;
+
+    // --------------------------------------------------------------------------------
+    
+    if (!CheckEnv())
+        return kFALSE;
+
+    // --------------------------------------------------------------------------------
+
+    // Setup Tasklist
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    plist.AddToList(this); // take care of fDisplay!
+
+    MDirIter iter;
+    if (fSequence.GetRuns(iter, MSequence::kRawCal)<=0)
+        return kFALSE;
+
+    //
+    // Input containers
+    //
+    pedcam.SetName("MPedestalCam"); // MPedestalFundamental
+    plist.AddToList(&pedcam);
+    plist.AddToList(&fBadPixels);
+
+    //
+    // Calibration Results containers
+    //
+    plist.AddToList(&fQECam);
+    plist.AddToList(&fCalibrationCam);
+    plist.AddToList(&fRelTimeCam);
+    if (IsUseBlindPixel())
+        plist.AddToList(&fCalibrationBlindCam);
+    if (IsUsePINDiode())
+        plist.AddToList(&fCalibrationPINDiode);
+
+    //
+    // Initialize two histogram containers which could be modified in this class
+    //
+    MHCalibrationRelTimeCam     reltimecam;
+    MHCalibrationChargeCam      chargecam;
+    MHCalibrationChargeBlindCam blindcam;
+    plist.AddToList(&chargecam);
+
+    if (IsUseBlindPixel())
+      plist.AddToList(&blindcam);
+    if (IsRelTimes())
+      plist.AddToList(&reltimecam);
+    //
+    // Data Reading tasks
+    //
+    MReadMarsFile read("Events");
+    MRawFileRead rawread(NULL);
+    rawread.SetForceMode(); // Ignore broken time-stamps
+
+    if (!fSequence.IsMonteCarlo())
+    {
+        rawread.AddFiles(iter);
+        tlist.AddToList(&rawread);
+    }
+    else
+    {
+        read.DisableAutoScheme();
+        read.AddFiles(iter);
+        tlist.AddToList(&read);
+    }
+
+    //
+    // Other Tasks
+    //
+
+    // Set the default for data version earlier than 5, where no valid
+    // trigger pattern exists. There should not be pin diode or other
+    // types of events inside the calibration files which should be skipped,
+    // anyway. So we set the default such that the MContinue ccalib
+    // will never be executed.
+    // We allow to have only calibration events before Prescaling.
+    // We require that the calibration events have not been prescaled (why?)
+    MTriggerPatternDecode     trgpat;
+    MFTriggerPattern          fcalib("CalibFilter");
+    fcalib.SetDefault(kFALSE);
+    fcalib.DenyAll(MFTriggerPattern::kPrescaled);
+    fcalib.DenyAll(MFTriggerPattern::kUnPrescaled);
+    fcalib.AllowTriggerLvl1(MFTriggerPattern::kUnPrescaled);
+    fcalib.AllowTriggerLvl1(MFTriggerPattern::kPrescaled);
+    fcalib.AllowTriggerLvl2(MFTriggerPattern::kUnPrescaled);
+    fcalib.AllowTriggerLvl2(MFTriggerPattern::kPrescaled);
+    fcalib.AllowSumTrigger(MFTriggerPattern::kUnPrescaled);
+    fcalib.AllowSumTrigger(MFTriggerPattern::kPrescaled);
+    fcalib.RequireCalibration(MFTriggerPattern::kPrescaled);
+    fcalib.AllowCalibration(MFTriggerPattern::kUnPrescaled);
+
+    MContinue                 ccalib(&fcalib, "ContTrigPattern");
+    ccalib.SetInverted();
+
+    MCalibrationPatternDecode decode;
+    MGeomApply                apply;
+    apply.SetGeometry(fGeometry);
+
+    MBadPixelsMerge          merge(&fBadPixels);
+    MExtractPINDiode         pinext;
+    MExtractBlindPixel       blindext;
+
+    if (IsUseBlindPixel())
+        InitBlindPixel(blindext, blindcam);
+
+//    MExtractSlidingWindow    extract2;
+//    MExtractTimeHighestIntegral timehigh;
+    MCalibrationChargeCalc   calcalc;
+    MCalibrationRelTimeCalc  timecalc;
+    calcalc.SetExtractor(fExtractor);
+
+    if (IsDebug())
+    {
+        chargecam.SetDebug();
+        calcalc.SetDebug();
+    }
+
+    //
+    // Calibration histogramming
+    //
+    MFillH fillpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode",   "FillPINDiode");
+    MFillH fillbnd("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel", "FillBlindCam");
+    MFillH fillcam("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillChargeCam");
+    MFillH filltme("MHCalibrationRelTimeCam",     "MArrivalTimeCam",            "FillRelTime");
+    fillpin.SetBit(MFillH::kDoNotDisplay);
+    fillbnd.SetBit(MFillH::kDoNotDisplay);
+    fillcam.SetBit(MFillH::kDoNotDisplay);
+    filltme.SetBit(MFillH::kDoNotDisplay);
+
+    //
+    // Set default extractors in case, none has been set...
+    //
+    /*
+    if (!fExtractor)
+      fExtractor = &extract2;
+    if (!fTimeExtractor)
+      fTimeExtractor = &timehigh;
+     */
+    MExtractTimeAndChargeSpline spline;
+    if (!fExtractor)
+      fExtractor = &spline;
+//    if (!fTimeExtractor)
+//      fTimeExtractor = &timehigh;
+
+    const Bool_t istimecharge = fExtractor->InheritsFrom("MExtractTimeAndCharge");
+
+    //
+    // Look if the extractor is a pure charge or also a time extractor
+    //
+    if (istimecharge)
+    {
+        if (fExtractorCam.GetSize() == pedcam.GetSize())
+            calcalc.SetPedestals(&fExtractorCam);
+        else
+        {
+            *fLog << err << GetDescriptor() << "ERROR - ";
+            *fLog << "Used Extractor derives from MExtractTimeAndCharge, " << endl;
+            *fLog << "but MExtractorCam size " << fExtractorCam.GetSize() << " ";
+            *fLog << "mismatch pedcam size " << pedcam.GetSize() << "! " << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // Setup more tasks and tasklist
+    //
+    MTaskEnv taskenv("ExtractSignal");
+    taskenv.SetDefault(fExtractor);
+
+    tlist.AddToList(&trgpat);
+    if (fColor != MCalibrationCam::kCT1)
+        tlist.AddToList(&ccalib);
+    tlist.AddToList(&decode);
+    tlist.AddToList(&merge);
+    tlist.AddToList(&apply);
+
+    // Produce pedestal subtracted raw-data
+    MPedestalSubtract pedsub;
+    pedsub.SetPedestalCam(&pedcam);
+    tlist.AddToList(&pedsub);
+
+    MCalibColorSet colorset;
+    if (fColor != MCalibrationCam::kNONE)
+        colorset.SetExplicitColor(fColor);
+    tlist.AddToList(&colorset);
+
+    tlist.AddToList(&taskenv);
+
+    if (IsUsePINDiode())
+      tlist.AddToList(&pinext);
+    if (IsUseBlindPixel())
+      tlist.AddToList(&blindext);
+
+    MTaskEnv taskenv2("ExtractTime");
+    if (!istimecharge)
+    {
+      taskenv2.SetDefault(fTimeExtractor);
+
+      if (IsRelTimes())
+        tlist.AddToList(&taskenv2);
+    }
+
+    //
+    // Apply a filter against cosmics (this is for the old times in which
+    // the calibration events where triggered by level 1 and for
+    // sanity against empty trigger events)
+    //
+    MFCosmics cosmics;
+    cosmics.SetMaxEmptyPixels(0.05);
+    cosmics.SetMaxAcceptedFraction(0.5); // max=0.5 cosmics
+
+    MContinue cont(&cosmics, "ContCosmics");
+    tlist.AddToList(&cont);
+
+    tlist.AddToList(&fillcam);
+
+    if (IsUseBlindPixel())
+      tlist.AddToList(&fillbnd);
+    if (IsUsePINDiode())
+      tlist.AddToList(&fillpin);
+
+    tlist.AddToList(&calcalc);
+
+    if (IsRelTimes())
+    {
+        tlist.AddToList(&filltme);
+        tlist.AddToList(&timecalc);
+    }
+
+    MHCamEvent evt2(0, "Extra'd", "Extracted Calibration Signal;;S [cnts/sl]");
+    MHCamEvent evt9(4, "ArrTm",   "Extracted ArrivalTime;;T");
+
+    MFillH fill2(&evt2, "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill9(&evt9, "MArrivalTimeCam",     "FillArrivalTime");
+
+    tlist.AddToList(&fill2);
+    tlist.AddToList(&fill9);
+
+    /*
+     MFillH fillP("MHPulseShape", "", "FillPulseShape");
+     fillP.SetNameTab("Pulse");
+     tlist.AddToList(&fillP);
+     */
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    if (!taskenv.GetTask() && !taskenv2.GetTask())
+    {
+        *fLog << err << "ERROR - Neither ExtractSignal nor ExtractTime initialized or both '<dummy>'." << endl;
+        return kFALSE;
+    }
+
+    if (!WriteTasks(taskenv.GetTask(), istimecharge ? 0 : taskenv2.GetTask()))
+        return kFALSE;
+
+    // Execute first analysis
+    const Bool_t rc = evtloop.Eventloop();
+
+    if (!fCalibrationPINDiode.IsValid())
+        SetUsePINDiode(kFALSE);
+
+    // Only display result if PreProcessing was successfull
+    const Int_t numexec = !fSequence.IsMonteCarlo() ? rawread.GetNumExecutions() : read.GetNumExecutions();
+    if (numexec>0)
+    {
+        DisplayResult(plist);
+        if (!WriteResult(plist))
+            return kFALSE;
+    }
+
+    if (!rc)
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    if (calcalc.GetNumExecutions()<fMinEvents)
+    {
+        *fLog << err << GetDescriptor() << ": Failed. Less than the required " << fMinEvents << " evts processed." << endl;
+        return kFALSE;
+    }
+
+    // --------------------------------------------------------------------------------
+
+    if (fIsPixelCheck)
+    {
+        chargecam[fCheckedPixId].DrawClone("datacheck");
+        chargecam(fCheckedPixId).DrawClone("datacheck");
+
+        if (IsRelTimes())
+        {
+            reltimecam[fCheckedPixId].DrawClone("");
+            reltimecam(fCheckedPixId).DrawClone("");
+        }
+    }
+
+    *fLog << all << GetDescriptor() << ": Done." << endl << endl << endl;
+
+    return kTRUE;
+}
+
+/*
+Bool_t MJCalibration::WriteEventloop(MEvtLoop &evtloop) const
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+  if (fPathOut.IsNull())
+    return kTRUE;
+  
+  const TString oname(GetOutputFile());
+  
+  *fLog << inf << "Writing to file: " << oname << endl;
+  
+  TFile file(oname, fOverwrite?"RECREATE":"NEW", "File created by MJCalibration", 9);
+  if (!file.IsOpen())
+  {
+      *fLog << err << "ERROR - Couldn't open file " << oname << " for writing..." << endl;
+      return kFALSE;
+  }
+
+  if (evtloop.Write(fName)<=0)
+  {
+      *fLog << err << "Unable to write MEvtloop to " << oname << endl;
+      return kFALSE;
+  }
+  
+  return kTRUE;
+}
+*/
+
+Bool_t MJCalibration::WriteTasks(MTask *t1, MTask *t2) const
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+    TObjArray cont;
+    if (t1)
+        cont.Add(t1);
+    if (t2)
+        cont.Add(t2);
+
+    return WriteContainer(cont, GetOutputFileName(), fOverwrite?"RECREATE":"NEW");
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the result into the output file GetOutputFile(), if fOutputPath exists.
+// 
+// The following containers are written:
+// - MStatusDisplay
+// - MCalibrationChargeCam
+// - MCalibrationBlindCam
+// - MCalibrationQECam
+// - MCalibrationChargePINDiode
+// - MBadPixelsCam
+//
+// If the flag kRelTimes is set, then also:
+// - MCalibrationRelTimeCam
+//
+Bool_t MJCalibration::WriteResult(MParList &plist)
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+    TObjArray cont;
+    cont.Add(&fBadPixels);
+    cont.Add(&fCalibrationCam);
+    cont.Add(&fQECam);
+    cont.Add(&fCalibrationBlindCam);
+    cont.Add(&fCalibrationPINDiode);
+
+    if (IsRelTimes())
+        cont.Add(&fRelTimeCam);
+
+    if (fExtractorCam.GetSize() != 0)
+    {
+        fExtractorCam.SetName("MPedestalExtracted");
+        cont.Add(&fExtractorCam);
+    }
+
+    TObject *pedcam = plist.FindObject("MPedestalCam");
+    if (!pedcam)
+        *fLog << warn << " - WARNING - MPedestalCam (fundamental)... not found for writing!" << endl;
+    else
+        cont.Add(pedcam);
+
+    TObject *geom = plist.FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << " - WARNING - MGeomCam... not found for writing!" << endl;
+    else
+        cont.Add(geom);
+
+    if (IsHistsStorage())
+    {
+        cont.Add(plist.FindObject("MHCalibrationChargeCam"));
+        cont.Add(plist.FindObject("MHCalibrationChargeBlindCam"));
+        cont.Add(plist.FindObject("MHCalibrationChargePINDiode"));
+        if (IsRelTimes())
+            cont.Add(plist.FindObject("MHCalibrationRelTimeCam"));
+    }
+
+    if (fDisplay)
+        cont.Add(fDisplay);
+
+    cont.Add(const_cast<TEnv*>(GetEnv()));
+    cont.Add(&fSequence);
+
+    TNamed cmdline("CommandLine", fCommandLine.Data());
+    cont.Add(&cmdline);
+
+    return WriteContainer(cont, GetOutputFileName(), "UPDATE");
+}
+
+
+void MJCalibration::DisplayDoubleProject(const MHCamera &cam)
+{
+    const UInt_t n = cam.GetGeometry()->GetNumAreas();
+
+    TVirtualPad *pad = gPad;
+    pad->Divide(n, 1, 1e-5, 1e-5);;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        pad->cd(i+1);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+
+        TH1D &h = *cam.ProjectionS(TArrayI(), TArrayI(1, (Int_t*)&i), MString::Format("%s_%d", cam.GetName(), i));
+        FixDataCheckHist(h);
+        h.SetTitle(MString::Format("%s %d",cam.GetTitle(), i));
+        h.SetDirectory(NULL);
+        h.SetBit(kCanDelete);
+        h.Draw();
+
+        h.Fit("gaus", "Q");
+
+        TF1 *f = h.GetFunction("gaus");
+        if (f)
+        {
+            f->SetLineWidth(2);
+            f->SetLineColor(kBlue);
+        }
+    }
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJCalibration.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCalibration.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCalibration.h	(revision 17960)
@@ -0,0 +1,184 @@
+#ifndef MARS_MJCalibration
+#define MARS_MJCalibration
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+#ifndef MARS_MCalibrationChargeCam
+#include "MCalibrationChargeCam.h"
+#endif
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+#ifndef MARS_MCalibrationRelTimeCam
+#include "MCalibrationRelTimeCam.h"
+#endif
+#ifndef MARS_MCalibrationChargePINDiode
+#include "MCalibrationChargePINDiode.h"
+#endif
+#ifndef MARS_MCalibrationQECam
+#include "MCalibrationQECam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+#ifndef MARS_MPedestalCam
+#include "MPedestalCam.h"
+#endif
+
+class TH1D;
+class TPaveText;
+
+class MTask;
+class MParList;
+class MPedestalCam;
+class MExtractor;
+class MExtractTime;
+class MEvtLoop;
+class MExtractBlindPixel;
+class MHCalibrationChargeBlindCam;
+class MHCamera;
+
+class MJCalibration : public MJCalib
+{
+private:
+
+  static const Int_t gkIFAEBoxInaugurationRun;          //! Run number of first IFAE box calibration
+  static const Int_t gkSecondBlindPixelInstallation;    //! Run number upon which second blind pixel was installed
+  static const Int_t gkSpecialPixelsContInstallation;   //! Run number upon which third blind pixel was installed
+  static const Int_t gkThirdBlindPixelInstallation;     //! Run number upon which third blind pixel was installed  
+
+  static const TString  fgReferenceFile;   //! default for fReferenceFile ("mjobs/calibrationref.rc")
+  static const TString  fgHiLoCalibFile;   //! default for fHiLoCalibFile ("mjobs/hilocalib.root")  
+
+  Double_t fConvFADC2PheMin;               //! Histogram minimum for conversion factor to phes
+  Double_t fConvFADC2PheMax;               //! Histogram maximum for conversion factor to phes
+  Double_t fConvFADC2PhotMin;              //! Histogram minimum for conversion factor to phs
+  Double_t fConvFADC2PhotMax;              //! Histogram maixmum for conversion factor to phs
+  Double_t fQEMin;                         //! Histogram minimum for quantum efficiency
+  Double_t fQEMax;                         //! Histogram maximum for quantum efficiency
+  Double_t fArrivalTimeMin;                //! Histogram minimum for arrival times 
+  Double_t fArrivalTimeMax;                //! Histogram maximum for arrival times
+  Double_t fTimeOffsetMin;                 //! Histogram minimum for time offsets
+  Double_t fTimeOffsetMax;                 //! Histogram maximum for time offsets
+  Double_t fTimeResolutionMin;             //! Histogram minimum for time resolutions
+  Double_t fTimeResolutionMax;             //! Histogram maximum for time resolutions
+  					   
+  Float_t  fRefFADC2PheInner;              //! Reference value for the ratio phes/charge - inner
+  Float_t  fRefFADC2PheOuter;              //! Reference value for the ratio phes/charge - outer
+  Float_t  fRefConvFADC2PhotInner;         //! Reference value for the conversion factor to phs - inner
+  Float_t  fRefConvFADC2PhotOuter;         //! Reference value for the conversion factor to phs - outer
+  Float_t  fRefConvFADC2PheInner;          //! Reference value for the conversion factor to phs - inner
+  Float_t  fRefConvFADC2PheOuter;          //! Reference value for the conversion factor to phs - outer
+  Float_t  fRefQEInner;                    //! Reference value for the quantum eff. cascades - inner
+  Float_t  fRefQEOuter;                    //! Reference value for the quantum eff. cascades - outer
+  Float_t  fRefArrivalTimeInner;           //! Reference value for the arrival time - inner
+  Float_t  fRefArrivalTimeOuter;           //! Reference value for the arrival time - outer
+  Float_t  fRefArrivalTimeRmsInner;        //! Reference value for the arrival time - inner
+  Float_t  fRefArrivalTimeRmsOuter;        //! Reference value for the arrival time - outer
+  Float_t  fRefTimeOffsetOuter;            //! Reference value for the time offset - outer
+  Float_t  fRefTimeResolutionInner;  	   //! Reference value for the time resolution - inner
+  Float_t  fRefTimeResolutionOuter;	   //! Reference value for the time resolution - outer
+
+  TString  fReferenceFile;                 // File name containing the reference values
+  TString  fHiLoCalibFile;                 // File name containing the hi-lo calib. constants
+
+  MExtractor     *fExtractor;                           // Signal extractor
+  MExtractTime   *fTimeExtractor;                       // Arrival Time extractor
+
+  MBadPixelsCam                   fBadPixels;           // Bad Pixels cam, can be set from previous runs  
+  MCalibrationChargeCam           fCalibrationCam;      // Calibration conversion factors FADC2Phe  
+  MCalibrationBlindCam            fCalibrationBlindCam; // Calibration from Blind Pixel(s)  
+  MCalibrationChargePINDiode      fCalibrationPINDiode; // Calibration from PIN Diode
+  MCalibrationQECam               fQECam;               // Quantum efficiency, can be set from previous runs
+  MCalibrationRelTimeCam          fRelTimeCam;          // Calibration constants rel. times
+
+  MPedestalCam                    fExtractorCam;        // Pedestal Cam with extractor resolution
+
+  MCalibrationCam::PulserColor_t fColor;                // Colour of the pulsed LEDs
+
+  enum  Display_t                                       // Possible Display types
+    {
+      kFullDisplay,
+      kDataCheckDisplay,
+      kNormalDisplay
+    };
+
+  Display_t fDisplayType;                              // Chosen Display type
+
+  enum { kRelTimes, kDebug };                          // Possible flags
+
+  Byte_t fFlags;                                       // Bit-field for the flags
+
+  UInt_t fMinEvents;                                   // Minimum number of events
+
+  TString fGeometry;                                   // Class name geometry
+
+  Bool_t IsRelTimes     () const { return TESTBIT(fFlags,kRelTimes);       }
+  Bool_t IsDebug        () const { return TESTBIT(fFlags,kDebug);          }
+
+  MHCamera *DrawBadPixelPad(const MHCamera &h, Bool_t unsuit) const;
+  void DrawTab(MParList &plist, const char *cont, const char *name, Option_t *opt);
+  
+  void DisplayResult(MParList &plist);
+  void DisplayReferenceLines(const MHCamera &hist, const Int_t what) const;
+  //void   DisplayOutliers      ( TH1D     *hist, const char* whatsmall, const char* whatbig ) const;
+
+  Bool_t WriteResult   (MParList &plist);
+  //Bool_t WriteEventloop( MEvtLoop &evtloop   ) const;
+  Bool_t WriteTasks    ( MTask *t1, MTask *t2) const;
+  Bool_t CheckEnvLocal ();
+
+  // WORKAROUNDS!!!
+  void   InitBlindPixel(MExtractBlindPixel &blindext,
+                        MHCalibrationChargeBlindCam &blindcam);
+
+  const char* GetOutputFileName() const;
+
+  void ReadReferenceFile();
+  Bool_t ReadHiLoCalibFile();
+
+public:
+  MJCalibration(const char *name=NULL, const char *title=NULL);
+
+  const MCalibrationChargeCam  &GetCalibrationCam() const { return fCalibrationCam; }
+  const MCalibrationRelTimeCam &GetRelTimeCam()     const { return fRelTimeCam;     }
+  const MCalibrationQECam      &GetQECam()          const { return fQECam;          }
+  const MBadPixelsCam          &GetBadPixels()      const { return fBadPixels;      }
+
+  // Containers and pointers
+  void SetBadPixels    ( const MBadPixelsCam &bad)                   { bad.Copy(fBadPixels); }
+  void SetColor        ( const MCalibrationCam::PulserColor_t color) { fColor = color;       }
+  void SetExtractor    ( MExtractor* ext)                            { fExtractor = ext;     }
+  void SetExtractorCam ( const MPedestalCam  &ped)                   { ped.Copy(fExtractorCam); fExtractorCam.SetName(ped.GetName()); }
+  void SetQECam        ( const MCalibrationQECam &qe)                { qe.Copy(fQECam);      }
+  void SetTimeExtractor( MExtractTime* ext)                          { fTimeExtractor = ext; }
+
+  // Displays
+  void SetFullDisplay()      { fDisplayType = kFullDisplay;      }
+  void SetDataCheckDisplay() { fDisplayType = kDataCheckDisplay; }
+  void SetNormalDisplay()    { fDisplayType = kNormalDisplay;    }
+
+  // Camera Geomtry
+  void SetGeometry(const char *geom) { fGeometry = geom; }
+
+  // Flags
+  void SetRelTimeCalibration( const Bool_t b=kTRUE ) { b ? SETBIT(fFlags,kRelTimes)  : CLRBIT(fFlags,kRelTimes); }
+  void SetDebug             ( const Bool_t b=kTRUE ) { b ? SETBIT(fFlags,kDebug)     : CLRBIT(fFlags,kDebug); }
+  //void SetIntensity         ( const Bool_t b=kTRUE ) { b ? SETBIT(fFlags,kIntensity) : CLRBIT(fFlags,kIntensity); }
+
+  // Files
+  void SetReferenceFile( const TString ref=fgReferenceFile ) { fReferenceFile = ref; }
+  void SetHiLoCalibFile( const TString ref=fgHiLoCalibFile ) { fHiLoCalibFile = ref; }
+
+  // Precessing
+  Bool_t Process(MPedestalCam &pedcam);
+
+  // Public helper functions
+  static void DisplayDoubleProject(const MHCamera &cam);
+  static void FixDataCheckHist(TH1D &hist, Double_t min=-1111, Double_t max=-1111);
+
+  ClassDef(MJCalibration, 0) // Tool to run a calibration per pulser colour and intensity
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJCut.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCut.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCut.cc	(revision 17960)
@@ -0,0 +1,1082 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCut
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCut.h"
+
+// Root
+#include <TEnv.h>
+#include <TFile.h>
+#include <TClass.h>
+
+// Environment
+#include "MLog.h"
+#include "MLogManip.h"
+
+// Eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// Display
+#include "MStatusDisplay.h"
+
+// Tasks
+#include "MReadReports.h"
+#include "MReadMarsFile.h"
+#include "MPrint.h"
+#include "MContinue.h"
+#include "MTaskEnv.h"
+#include "MPointingDevCalc.h"
+#include "MParameterCalc.h"
+#include "MSrcPosRndm.h"
+#include "MSrcPosCalc.h"
+#include "MSrcPosCorrect.h"
+#include "MHillasCalc.h"
+#include "MFillH.h"
+#include "MWriteRootFile.h"
+
+// Filter
+#include "MFDataPhrase.h"
+
+// Fit signal environment
+#include "../mhflux/MAlphaFitter.h"
+#include "../mhflux/MHAlpha.h"
+
+// Containers
+#include "MH3.h"
+#include "MBinning.h"
+#include "MDataSet.h"
+#include "MParameters.h"
+#include "MPointingPos.h"
+#include "MObservatory.h"
+#include "MHSrcPosCam.h"
+
+ClassImp(MJCut);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.  Set defaults for fStoreSummary, fStoreresult,
+// fWriteOnly, fFullDisplay to kFALSE and initialize
+// /*fEstimateEnergy and*/ fCalcHadronness with NULL.
+//
+MJCut::MJCut(const char *name, const char *title)
+    : fStoreSummary(kFALSE), fStoreResult(kTRUE), fWriteOnly(kFALSE),
+    fFullDisplay(kTRUE), fRndmSrcPos(kFALSE), fNumOffSourcePos(3),
+    fNameHist("MHThetaSq"),
+    fCalcHadronness(0), fCalcDisp(0), fEstimateEnergy(0)
+{
+    fName  = name  ? name  : "MJCut";
+    fTitle = title ? title : "Standard program to perform g/h-separation cuts";
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete fEstimateEnergy and fCalcHadronness if != NULL
+//
+MJCut::~MJCut()
+{
+    if (fEstimateEnergy)
+        delete fEstimateEnergy;
+    if (fCalcHadronness)
+        delete fCalcHadronness;
+    if (fCalcDisp)
+        delete fCalcDisp;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the summary file (events after cut0)
+// If you give a name the storage of this file is enabled implicitly.
+// If you give no filename the storage is neither enabled nor disabled,
+// but the storage file name is reset.
+// If no filename is set the default filename is used.
+// You can explicitly enable or disable the storage using EnableStoreOf*()
+// The default argument is no filename.
+//
+void MJCut::SetNameSummaryFile(const char *name)
+{
+    fNameSummary=name;
+    if (!fNameSummary.IsNull())
+        EnableStorageOfSummary();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the summary file (events after cut3)
+// If you give a name the storage of this file is enabled implicitly.
+// If you give no filename the storage is neither enabled nor disabled,
+// but the storage file name is reset.
+// If no filename is set the default filename is used.
+// You can explicitly enable or disable the storage using EnableStoreOf*()
+// The default argument is no filename.
+//
+void MJCut::SetNameResultFile(const char *name)
+{
+    fNameResult=name;
+    if (!fNameResult.IsNull())
+        EnableStorageOfResult();
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a task estimating the energy. The given task is cloned.
+//
+/*
+void MJCut::SetEnergyEstimator(const MTask *task)
+{
+    if (fEstimateEnergy)
+        delete fEstimateEnergy;
+    fEstimateEnergy = task ? (MTask*)task->Clone() : 0;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Setup a task calculating the hadronness. The given task is cloned.
+//
+void MJCut::SetHadronnessCalculator(const MTask *task)
+{
+    if (fCalcHadronness)
+        delete fCalcHadronness;
+    fCalcHadronness = task ? (MTask*)task->Clone() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a task calculating disp. The given task is cloned.
+//
+void MJCut::SetDispCalculator(const MTask *task)
+{
+    if (fCalcDisp)
+        delete fCalcDisp;
+    fCalcDisp = task ? (MTask*)task->Clone() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a task estimating the eneryg. The given task is cloned.
+//
+void MJCut::SetEnergyEstimator(const MTask *task)
+{
+    if (fEstimateEnergy)
+        delete fEstimateEnergy;
+    fEstimateEnergy = task ? (MTask*)task->Clone() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// return fOutputPath+"/ganymed%08d.root", num
+//
+TString MJCut::GetOutputFile(UInt_t num) const
+{
+    TString p(fPathOut);
+    p += "/";
+    p += fNameOutput.IsNull() ? Form("ganymed%08d.root", num) : fNameOutput.Data();
+    gSystem->ExpandPathName(p);
+    return p;
+}
+
+/*
+Bool_t MJCut::ReadTasks(const char *fname, MTask* &env1, MTask* &env2) const
+{
+    //    const TString fname = Form("%s/calib%08d.root", fPathIn.Data(), fSequence.GetSequence());
+
+    *fLog << inf << "Reading from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+        return kFALSE;
+    }
+
+    TObject *o = file.Get("EstimateEnergy");
+    if (o && !o->InheritsFrom(MTask::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - EstimateEnergy read from " << fname << " doesn't inherit from MTask!" << endl;
+        return kFALSE;
+    }
+    env1 = o ? (MTask*)o->Clone() : FNULL;
+
+    o = file.Get("CalcHadronness");
+    if (o && !o->InheritsFrom(MTask::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - CalcHadronness read from " << fname << " doesn't inherit from MTask!" << endl;
+        return kFALSE;
+    }
+    env2 = o ? (MTask*)o->Clone() : NULL;
+
+    return kTRUE;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Write the tasks in cont to the file corresponding to analysis number num,
+// see GetOutputFile()
+//
+Bool_t MJCut::WriteTasks(UInt_t num, TObjArray &cont) const
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    const TString oname(GetOutputFile(num));
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile *file = 0;
+    if (fNameResult.IsNull() && fStoreResult)
+    {
+        // If no special name fNameResult is given but the result should be stored,
+        // search for a file named oname (fNameOutput or ganymed%08d.root)
+        file = (TFile*)gROOT->GetListOfFiles()->FindObject(oname);
+        if (!file)
+        {
+            *fLog << err << "ERROR - File " << oname << " expected to be open, but isn't..." << endl;
+            return kFALSE;
+        }
+
+        file->cd();
+    }
+    else
+    {
+        // If special name fNameResult is given or no storage requested,
+        // open a new file named oname (fNameOutput or ganymed%08d.root)
+        file = TFile::Open(oname, fOverwrite?"RECREATE":"NEW", "File created by MJCut", 9);
+
+        if (!file)
+        {
+            *fLog << err << "ERROR - Couldn't open new file " << oname << " for writing..." << endl;
+            return kFALSE;
+        }
+    }
+
+    // Write container to output file
+    const Bool_t rc = WriteContainer(cont);
+
+    // If file was newly opened, close it
+    if (!(fNameResult.IsNull() && fStoreResult))
+        delete file;
+
+    // Return result of writing
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the result plots and other results to the file corresponding to
+// analysis number num, see GetOutputFile()
+//
+Bool_t MJCut::WriteResult(const MParList &plist, const MDataSet &set) const
+{
+    TObjArray arr;
+
+    // Save all MBinnings
+    TIter Next(plist);
+    TObject *o=0;
+    while ((o=Next()))
+        if (o->InheritsFrom(MBinning::Class()))
+            arr.Add(o);
+
+    // Save also the result, not only the setup
+    const MHAlpha *halpha = (MHAlpha*)plist.FindObject("Hist", "MHAlpha");
+    if (halpha)
+        arr.Add((TObject*)(&halpha->GetAlphaFitter()));
+
+    // Save also the dataset, environment and display
+    arr.Add(const_cast<MDataSet*>(&set));
+    arr.Add(const_cast<TEnv*>(GetEnv()));
+    if (fDisplay)
+        arr.Add(fDisplay);
+
+    TNamed cmdline("CommandLine", fCommandLine.Data());
+    arr.Add(&cmdline);
+
+    const Int_t num = set.GetNumAnalysis();
+    const TString fname(fNameOutput.IsNull() ? Form("ganymed%08d.root", num) : fNameOutput.Data());
+
+    // If requested, write to already open output file
+    if (fNameResult.IsNull() && fStoreResult)
+    {
+        *fLog << inf2 << "Searching for open file " << fname << "... " << flush;
+
+        TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(fname);
+        if (file)
+        {
+            *fLog << "found." << endl;
+            file->cd();
+            return WriteContainer(arr);
+        }
+        *fLog << "not found." << endl;
+    }
+
+    return WriteContainer(arr, fname, "UPDATE");
+}
+
+// --------------------------------------------------------------------------
+//
+// MJCut allows to setup several option by a resource file:
+//   MJCut.WriteSummary: yes, no
+//   MJCut.SummaryFile:  filename
+//   MJCut.WriteResult:  yes, no
+//   MJCut.ResultFile:   filename
+//   MJCut.HistName:     MHAlpha
+//
+Bool_t MJCut::CheckEnvLocal()
+{
+    const TString f0(GetEnv("SummaryFile", ""));
+    const TString f1(GetEnv("ResultFile",  ""));
+    if (!f0.IsNull())
+        SetNameSummaryFile(f0);
+    if (!f1.IsNull())
+        SetNameResultFile(f1);
+
+    EnableStorageOfSummary(GetEnv("SummaryFile", fStoreSummary));
+    EnableStorageOfResult(GetEnv("ResultFile", fStoreResult));
+    EnableFullDisplay(GetEnv("FullDisplay", fFullDisplay));
+    EnableRandomSrcPos(GetEnv("RandomSourcePosition", fRndmSrcPos));
+
+    fNumOffSourcePos = GetEnv("NumOffSourcePositions", (Int_t)fNumOffSourcePos);
+    //EnableSubstraction(GetEnv("HistogramSubstraction", fSubstraction));
+
+    SetNameHist(GetEnv("NameHist", fNameHist));
+    SetNameHistFS(GetEnv("NameHistFS", fNameHistFS));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup write to write:
+//     container         tree       optional?
+//  --------------     ----------  -----------
+//   "MHillas"      to  "Events"
+//   "MHillasSrc"   to  "Events"
+//   "Hadronness"   to  "Events"       yes
+//   "MEnergyEst"   to  "Events"       yes
+//   "DataType"     to  "Events"
+//
+void MJCut::SetupWriter(MWriteRootFile *write, const char *name) const
+{
+    if (!write)
+        return;
+
+    write->SetName(name);
+    write->AddContainer("MHillas",        "Events");
+    write->AddContainer("MHillasSrc",     "Events");
+    write->AddContainer("MHillasExt",     "Events");
+    write->AddContainer("MPointingPos",   "Events");
+    write->AddContainer("MHillasSrcAnti", "Events", kFALSE);
+    write->AddContainer("MImagePar",      "Events", kFALSE);
+    write->AddContainer("MNewImagePar",   "Events", kFALSE);
+    write->AddContainer("MNewImagePar2",  "Events", kFALSE);
+    write->AddContainer("Hadronness",     "Events", kFALSE);
+    write->AddContainer("MSrcPosCam",     "Events", kFALSE);
+    write->AddContainer("MSrcPosAnti",    "Events", kFALSE);
+    write->AddContainer("ThetaSquared",   "Events", kFALSE);
+    write->AddContainer("OpticalAxis",    "Events", kFALSE);
+    write->AddContainer("Disp",           "Events", kFALSE);
+    write->AddContainer("Ghostbuster",    "Events", kFALSE);
+    write->AddContainer("MEnergyEst",     "Events", kFALSE);
+    write->AddContainer("MTime",          "Events", kFALSE);
+    write->AddContainer("MMcEvt",         "Events", kFALSE);
+    write->AddContainer("DataType",       "Events");
+    write->AddContainer("FileId",         "Events");
+    write->AddContainer("EvtNumber",      "Events");
+    //    write->AddContainer("MMuonSearchPar", "Events", kFALSE);
+    //    write->AddContainer("MMuonCalibPar",  "Events", kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Create a new instance of an object with name name of class
+// type fNameHist in parlist. It must derive from MHAlpha.
+// Call ForceUsingSize for it and return its pointer.
+// If something fails NULL is returned.
+//
+MHAlpha *MJCut::CreateNewHist(MParList &plist, const char *name) const
+{
+    TClass *cls = gROOT->GetClass(fNameHist);
+    if (!cls)
+    {
+        *fLog << err << "Class " << fNameHist << " not found in dictionary... abort." << endl;
+        return NULL;
+    }
+    if (!cls->InheritsFrom(MHAlpha::Class()))
+    {
+        *fLog << err << "Class " << fNameHist << " doesn't inherit from MHAlpha... abort." << endl;
+        return NULL;
+    }
+
+    const TString objname(Form("Hist%s", name));
+    MHAlpha *h = (MHAlpha*)plist.FindCreateObj(fNameHist, objname);
+    if (!h)
+        return NULL;
+
+    h->ForceUsingSize();
+
+    return h;
+}
+
+// --------------------------------------------------------------------------
+//
+// Create a new instance of an object with name name of class
+// type fNameHistFS in parlist. It must derive from MHFalseSource
+// If something fails NULL is returned.
+//
+MH *MJCut::CreateNewHistFS(MParList &plist, const char *name) const
+{
+    const TString cname(fNameHistFS.IsNull()?"MHFalseSource":fNameHistFS.Data());
+
+    TClass *cls = gROOT->GetClass(cname);
+    if (!cls)
+    {
+        *fLog << err << "Class " << cname << " not found in dictionary... abort." << endl;
+        return NULL;
+    }
+    if (!cls->InheritsFrom("MHFalseSource"))
+    {
+        *fLog << err << "Class " << cname << " doesn't inherit from MHFalseSource... abort." << endl;
+        return NULL;
+    }
+
+    const TString objname(Form("FS%s", name));
+    return (MH*)plist.FindCreateObj(cname, objname);
+}
+
+Bool_t MJCut::FillSrcPosCam(const MDataSet &set, MPointingPos &source, MHSrcPosCam &hsrcpos)
+{
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Filling MHSrcPosCam " << set.GetBaseName() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // La Palma Magic1, Possible source position
+    MObservatory obs;
+    plist.AddToList(&obs);
+    plist.AddToList(&source);
+
+    // Initialize default binnings
+    // MBinning bins1(18,  0,     90,    "BinningSrcPosCam", "lin");
+    // plist.AddToList(&bins1);
+
+    // ------------- Loop Off Data --------------------
+    MReadReports read;
+
+    read.EnableAutoScheme();
+    read.AddToBranchList("MTimeEffectiveOnTime.*");
+    read.AddToBranchList("MEffectiveOnTime.*");
+
+    read.AddTree("Events", "MTime.", MReadReports::kMaster);
+    read.AddTree("Drive",            MReadReports::kRequired);
+    read.AddTree("Starguider",       MReadReports::kRequired);
+    read.AddTree("EffectiveOnTime");
+
+    if (!set.AddFilesOn(read))
+        return kFALSE;
+
+    MFillH fill(&hsrcpos, "MSrcPosCam", "FillSrcPosCam");
+    fill.SetNameTab("SrcPos");
+
+    // How to get source position from off- and on-data?
+    MSrcPosCorrect scor;
+    MSrcPosCalc    scalc;
+    scalc.SetMode(MSrcPosCalc::kDefault);
+
+    MPointingDevCalc devcalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&devcalc, "Starguider");
+    tlist.AddToList(&scalc,   "Events");
+    tlist.AddToList(&scor,    "Events");
+    tlist.AddToList(&fill,    "Events");
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Processing of on-sequences to fill SrcPosCam failed." << endl;
+        return kFALSE;
+    }
+
+    if (!evtloop.GetDisplay())
+    {
+        *fLog << err << GetDescriptor() << ": Execution stopped by user." << endl;
+        return kFALSE;
+    }
+
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
+
+Int_t MJCut::Process(const MDataSet &set)
+{
+    if (!set.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(GetOutputFile(set.GetNumAnalysis())))
+        return kFALSE;
+
+    if (!CheckEnv())
+        return kFALSE;
+
+    // --------------------------------------------------------------------------------
+
+    if (!set.IsWobbleMode() && fNumOffSourcePos!=1)
+    {
+        *fLog << inf << "No wobble mode, but NumOffSoucePos!=1 (" << fNumOffSourcePos << ")... reset to 1." << endl;
+        fNumOffSourcePos = 1;
+    }
+
+    // Possible source position (eg. Wobble Mode)
+    MPointingPos source("MSourcePos");
+    if (set.HasSource())
+    {
+        if (!set.GetSourcePos(source))
+            return -1;
+        *fLog << all;
+        source.Print("RaDec");
+    }
+    else
+        *fLog << all << "No source position applied..." << endl;
+
+    // ADD A CHECK FOR THE SOURCE POSITION by COMPARISON WITH RA/DEC
+
+    MParList plist;
+
+    MHSrcPosCam hsrcpos(set.IsWobbleMode()?0.4:0);
+    if (!set.IsWobbleMode() && source.IsInitialized() && fRndmSrcPos)
+    {
+        if (!FillSrcPosCam(set, source, hsrcpos))
+            return -2;
+        plist.AddToList(&hsrcpos);
+    }
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Perform cuts for data set " << set.GetBaseName() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    // Setup Parlist
+    plist.AddToList(this); // take care of fDisplay!
+
+    MParameterI par("DataType");
+    plist.AddToList(&par);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // La Palma Magic1
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    if (source.IsInitialized())
+        plist.AddToList(&source);
+
+    // Initialize default binnings
+    MBinning bins1( 18,  0,     90,    "BinningAlpha",  "lin");
+    MBinning bins2( 15, 10,     1e6 ,  "BinningSize",   "log");
+    MBinning bins3( 67, -0.005, 0.665, "BinningTheta",  "asin");
+    //MBinning binsT(150,  0,     150,   "BinningDeltaT", "lin");
+    MBinning bins4("BinningFalseSource");
+    MBinning bins5("BinningWidth");
+    MBinning bins6("BinningLength");
+    MBinning bins7("BinningDist");
+    MBinning bins8("BinningSlope");
+    MBinning bins9("BinningM3Long");
+    MBinning bins0("BinningM3Trans");
+    MBinning binsa("BinningAsym");
+    MBinning binsb("BinningConc1");
+    plist.AddToList(&bins1);
+    plist.AddToList(&bins2);
+    plist.AddToList(&bins3);
+    plist.AddToList(&bins4);
+    plist.AddToList(&bins5);
+    plist.AddToList(&bins6);
+    plist.AddToList(&bins7);
+    plist.AddToList(&bins8);
+    plist.AddToList(&bins9);
+    plist.AddToList(&bins0);
+    plist.AddToList(&binsa);
+    plist.AddToList(&binsb);
+    //plist.AddToList(&binsT);
+
+    // --------------------------------------------------------------------------------
+
+    MParameterD scale;
+    scale.SetVal(1./fNumOffSourcePos);
+
+    // Setup fitter and histograms
+    MAlphaFitter fit;
+    plist.AddToList(&fit);
+    if (set.IsWobbleMode())
+        fit.SetScaleUser(1./fNumOffSourcePos); // includes fit.SetScaleMode(MAlphaFitter::kUserScale);
+
+    MHAlpha *halphaoff = CreateNewHist(plist, "Off");
+    MFillH falpha(halphaoff, "", "FillHist");
+    MH *hfsoff = CreateNewHistFS(plist, "Off");
+    MFillH ffs(hfsoff, "MHillas", "FillFS");
+
+    // FIXME: If fPathIn read cuts and energy estimator from file!
+    MContinue contq("", "CutQ");
+    MContinue cont0("", "Cut0");
+    MContinue cont1("", "Cut1");
+    MContinue cont2("", "Cut2");
+    MContinue cont3("", "Cut3");
+    contq.SetAllowEmpty();
+    cont0.SetAllowEmpty();
+    cont1.SetAllowEmpty();
+    cont2.SetAllowEmpty();
+    cont3.SetAllowEmpty();
+
+    // Filter for VsSize
+    MFDataPhrase ftheta(0, "CutT");
+
+    // ------------- Loop Off Data --------------------
+    MReadReports readoffdata;
+    readoffdata.AddTree("Events", "MTime.", MReadReports::kMaster);
+    readoffdata.AddTree("Drive",            MReadReports::kRequired);
+    readoffdata.AddTree("Starguider",       MReadReports::kRequired);
+    readoffdata.AddTree("EffectiveOnTime");
+
+    MReadMarsFile readoffmc("Events");
+    readoffmc.DisableAutoScheme();
+
+    MRead &readoff = set.IsMonteCarlo() ? (MRead&)readoffmc : (MRead&)readoffdata;
+    const Bool_t setrc = set.IsWobbleMode() ? set.AddFilesOn(readoff) : set.AddFilesOff(readoff);
+    if (!setrc && (set.HasOffSequences() || set.IsWobbleMode()))
+    {
+        *fLog << err << "MDataSet::AddFiles" << (set.IsWobbleMode()?"On":"Off") << " failed." << endl;
+        return kFALSE;
+    }
+
+    const TString path(Form("%s/", fPathOut.Data()));
+    TString fname0(path);
+    TString fname1(path);
+    fname0 += fNameSummary.IsNull() ? (TString) Form("ganymed%08d-summary.root", set.GetNumAnalysis()) : fNameSummary;
+    fname1 += fNameResult.IsNull()  ? (TString) Form("ganymed%08d.root",         set.GetNumAnalysis()) : fNameResult;
+
+    MWriteRootFile dummy0(fPathOut.IsNull()||!CanStoreSummary()?0:fname0.Data(), fOverwrite?"RECREATE":"NEW");
+    MWriteRootFile dummy1(fPathOut.IsNull()||!CanStoreResult() ?0:fname1.Data(), fOverwrite?"RECREATE":"NEW");
+
+    MWriteRootFile *write0 = CanStoreSummary() ? &dummy0 : 0;
+    MWriteRootFile *write1 = CanStoreResult()  ? &dummy1 : 0;
+    SetupWriter(write0, "WriteAfterCut0");
+    SetupWriter(write1, "WriteAfterCut3");
+
+    MTaskEnv taskenv0("CalcDisp");
+    taskenv0.SetDefault(fCalcDisp);
+
+    MTaskEnv taskenv1("CalcHadronness");
+    taskenv1.SetDefault(fCalcHadronness);
+
+    MTaskEnv taskenv2("EstimateEnergy");
+    taskenv2.SetDefault(fEstimateEnergy);
+
+    MParameterCalc setevtnum("MRawEvtHeader.fDAQEvtNumber", "SetEvtNumber");
+    setevtnum.SetNameParameter("EvtNumber");
+
+    MParameterCalc setrunnum("MRawRunHeader.GetFileID", "SetFileId");
+    setrunnum.SetNameParameter("FileId");
+
+    MFillH fill1a("MHHillasOffPre  [MHHillas]",      "MHillas",      "FillHillasPre");
+    MFillH fill2a("MHHillasOffPost [MHHillas]",      "MHillas",      "FillHillasPost");
+    MFillH fill3a("MHVsSizeOffPost [MHVsSize]",      "MHillasSrc",   "FillVsSizePost");
+    MFillH fill3c("MHVsSizeOffTheta [MHVsSize]",     "MHillasSrc",   "FillVsSizeTheta");
+    MFillH fill4a("MHHilExtOffPost [MHHillasExt]",   "MHillasSrc",   "FillHilExtPost");
+    MFillH fill5a("MHHilSrcOffPost [MHHillasSrc]",   "MHillasSrc",   "FillHilSrcPost");
+    MFillH fill6a("MHImgParOffPost [MHImagePar]",    "MImagePar",    "FillImgParPost");
+    MFillH fill7a("MHNewParOffPost [MHNewImagePar]", "MNewImagePar", "FillNewParPost");
+    //MFillH fill9a("MHEffOffTime    [MHEffectiveOnTime]", "MTime",        "FillEffOnTime");
+    fill1a.SetNameTab("PreCut");
+    fill2a.SetNameTab("PostCut");
+    fill3a.SetNameTab("VsSize");
+    fill3c.SetNameTab("CutT");
+    fill4a.SetNameTab("HilExt");
+    fill5a.SetNameTab("HilSrc");
+    fill6a.SetNameTab("ImgPar");
+    fill7a.SetNameTab("NewPar");
+    //fill9a.SetNameTab("EffOffT");
+
+    fill3c.SetFilter(&ftheta);
+
+    //MFDataMember fbin("Bin.fVal", '>', 0);
+    //fill9a.SetFilter(&fbin);
+
+    MPrint print2("MEffectiveOnTime");
+    print2.EnableSkip();
+
+    MTaskList tlist2;
+    if (set.IsWobbleMode())
+    {
+        tlist2.SetNumPasses(fNumOffSourcePos);
+        fill2a.SetWeight(&scale);
+        fill3a.SetWeight(&scale);
+        fill3c.SetWeight(&scale);
+        fill4a.SetWeight(&scale);
+        fill5a.SetWeight(&scale);
+        fill6a.SetWeight(&scale);
+        fill7a.SetWeight(&scale);
+    }
+
+    // How to get source position from off- and on-data?
+    MSrcPosCalc scalc;
+    scalc.SetMode(set.IsWobbleMode()?MSrcPosCalc::kWobble:MSrcPosCalc::kOffData); /********************/
+    scalc.SetCallback(&tlist2);
+
+    MSrcPosCorrect scor;
+
+    MHillasCalc hcalc;
+    MHillasCalc hcalc2("MHillasCalcAnti");
+    hcalc.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetNameHillasSrc("MHillasSrcAnti");
+    hcalc2.SetNameSrcPosCam("MSrcPosAnti");
+
+    MSrcPosRndm srcrndm;
+
+    MH3 hvs("MPointingPos.fZd");
+    hvs.SetName("ThetaOff;Theta");
+    hvs.SetTitle("Effective On-Time vs. Zenith Angle;\\Theta [\\circ];T_{on} [s]");
+
+    MFillH fillvs(&hvs, "", "FillOnTime");
+    if (!set.IsMonteCarlo())
+        fillvs.SetWeight("MEffectiveOnTime");
+    fillvs.SetNameTab("OnTime");
+
+    // It is not really necessary to re-calculate the image parameters
+    // for the the on-source for MCs, but it is done for symmetry reasons
+    if (set.IsMonteCarlo())
+        tlist2.AddToList(&fillvs);
+
+    tlist2.AddToList(&scalc);
+    tlist2.AddToList(&scor);
+    tlist2.AddToList(&srcrndm);
+    tlist2.AddToList(&hcalc);
+    if (set.IsWobbleMode())
+        tlist2.AddToList(&hcalc2);
+    tlist2.AddToList(&cont0);  
+    tlist2.AddToList(&taskenv0);
+    tlist2.AddToList(&taskenv1);
+    tlist2.AddToList(&setrunnum);
+    tlist2.AddToList(&setevtnum);
+    if (write0)
+        tlist2.AddToList(write0);
+    tlist2.AddToList(&cont1);
+    if (!fWriteOnly && (!set.IsWobbleMode() || !fNameHistFS.IsNull()))
+        tlist2.AddToList(&ffs);
+    tlist2.AddToList(&cont2);
+    if (!fWriteOnly)
+    {
+        tlist2.AddToList(&fill2a);
+        if (fFullDisplay)
+        {
+            tlist2.AddToList(&ftheta);
+            tlist2.AddToList(&fill3a);
+            tlist2.AddToList(&fill3c);
+            tlist2.AddToList(&fill4a);
+            tlist2.AddToList(&fill5a);
+            tlist2.AddToList(&fill6a);
+            tlist2.AddToList(&fill7a);
+        }
+    }
+    if (!fWriteOnly)
+    {
+        tlist2.AddToList(&falpha);
+        /* if (!fIsMonteCarlo)
+        {
+            tlist2.AddToList(&fbin);
+            tlist2.AddToList(&fill9a);
+        } */
+    }
+    tlist2.AddToList(&cont3);
+    tlist2.AddToList(&taskenv2);
+
+    if (write1)
+        tlist2.AddToList(write1);
+
+    MPointingDevCalc devcalc;
+
+    tlist.AddToList(&readoff);
+    if (!set.IsMonteCarlo())
+        tlist.AddToList(&fillvs, "EffectiveOnTime");
+    if (gLog.GetDebugLevel()>4)
+        tlist.AddToList(&print2, "EffectiveOnTime");
+    tlist.AddToList(&devcalc, "Starguider");
+    tlist.AddToList(&contq,   "Events");
+    if (!fWriteOnly)
+        tlist.AddToList(&fill1a, "Events");
+    tlist.AddToList(&tlist2,  "Events");
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+ 
+    par.SetVal(0);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    TObjArray cont;
+    cont.Add(&contq);
+    cont.Add(&cont0);
+    cont.Add(&cont1);
+    cont.Add(&cont2);
+    cont.Add(&cont3);
+    //if (taskenv1.GetTask())
+    //    cont.Add(taskenv1.GetTask());
+    if (taskenv0.GetTask())
+        cont.Add(taskenv0.GetTask());
+    if (taskenv1.GetTask())
+        cont.Add(taskenv1.GetTask());
+    if (taskenv2.GetTask())
+        cont.Add(taskenv2.GetTask());
+
+    if (!WriteTasks(set.GetNumAnalysis(), cont))
+        return kFALSE;
+
+    if (set.HasOffSequences() || set.IsWobbleMode())
+    {
+        // Execute first analysis
+        if (!evtloop.Eventloop(fMaxEvents))
+        {
+            *fLog << err << GetDescriptor() << ": Processing of off-sequences failed." << endl;
+            return -3;
+        }
+
+        if (!evtloop.GetDisplay())
+        {
+            *fLog << err << GetDescriptor() << ": Execution stopped by user." << endl;
+            return kFALSE;
+        }
+
+        //plist.FindObject("MTimeEffectiveOnTime")->Clear();
+    }
+    else
+    {
+        // This is the simplest way to remove the two object from the parlist
+        delete halphaoff;
+        delete hfsoff;
+    }
+
+    // ------------- Loop On Data --------------------
+    MReadReports readondata;
+    readondata.AddTree("Events", "MTime.", MReadReports::kMaster);
+    readondata.AddTree("Drive",            MReadReports::kRequired);
+    readondata.AddTree("Starguider",       MReadReports::kRequired);
+    readondata.AddTree("EffectiveOnTime");
+
+    MReadMarsFile readonmc("Events");
+    readonmc.DisableAutoScheme();
+
+    MRead &readon = set.IsMonteCarlo() ? (MRead&)readonmc : (MRead&)readondata;
+    if (!set.AddFilesOn(readon))
+        return kFALSE;
+
+    scalc.SetMode(MSrcPosCalc::kDefault);
+    scalc.SetNumRandomOffPositions(fNumOffSourcePos);
+
+    MFillH fill1b("MHHillasOnPre  [MHHillas]",      "MHillas",      "FillHillasPre");
+    MFillH fill2b("MHHillasOnPost [MHHillas]",      "MHillas",      "FillHillasPost");
+    MFillH fill3b("MHVsSizeOnPost [MHVsSize]",      "MHillasSrc",   "FillVsSizePost");
+    MFillH fill3d("MHVsSizeOnTheta [MHVsSize]",     "MHillasSrc",   "FillVsSizeTheta");
+    MFillH fill4b("MHHilExtOnPost [MHHillasExt]",   "MHillasSrc",   "FillHilExtPost");
+    MFillH fill5b("MHHilSrcOnPost [MHHillasSrc]",   "MHillasSrc",   "FillHilSrcPost");
+    MFillH fill6b("MHImgParOnPost [MHImagePar]",    "MImagePar",    "FillImgParPost");
+    MFillH fill7b("MHNewParOnPost [MHNewImagePar]", "MNewImagePar", "FillNewParPost");
+    //MFillH fill9b("MHEffOnTime    [MHEffectiveOnTime]", "MTime",        "FillEffOnTime");
+    fill1b.SetNameTab("PreCut");
+    fill2b.SetNameTab("PostCut");
+    fill3b.SetNameTab("VsSize");
+    fill3d.SetNameTab("CutT");
+    fill4b.SetNameTab("HilExt");
+    fill5b.SetNameTab("HilSrc");
+    fill6b.SetNameTab("ImgPar");
+    fill7b.SetNameTab("NewPar");
+    //fill9b.SetNameTab("EffOnT");
+    fill1b.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    fill2b.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    fill3b.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    fill3d.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    fill4b.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    fill5b.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    fill6b.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    fill7b.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+    //fill9b.SetFilter(&fbin);
+
+    fill3d.SetFilter(&ftheta);
+
+    /*
+     MHVsTime hvs("MEffectiveOnTime.fVal");
+     hvs.SetTitle("Effective On-Time vs. Time;;T_{on}");
+     MFillH fillvs(&hvs, "MTimeEffectiveOnTime", "FillOnTime");
+     fillvs.SetNameTab("OnTime");
+     */
+
+    /*
+    MParameterD weight;
+    weight.SetVal(-1);
+    fill2a.SetWeight(&weight);
+    fill3a.SetWeight(&weight);
+    fill4a.SetWeight(&weight);
+    fill5a.SetWeight(&weight);
+    fill6a.SetWeight(&weight);
+    fill7a.SetWeight(&weight);
+    if (fSubstraction)
+    {
+        fill2a.SetNameTab("PostCut-");
+        fill3a.SetNameTab("VsSize-");
+        fill4a.SetNameTab("HilExt-");
+        fill5a.SetNameTab("HilSrc-");
+        fill6a.SetNameTab("ImgPar-");
+        fill7a.SetNameTab("NewPar-");
+    }
+    */
+    MHAlpha *halphaon=CreateNewHist(plist);
+    MFillH falpha2(halphaon, "", "FillHist");
+    MH *hfs=CreateNewHistFS(plist);
+    MFillH ffs2(hfs, "MHillas", "FillFS");
+    MFillH fillphi("MHPhi", "", "FillPhi");
+    fillphi.SetDrawOption("anticut");
+
+    tlist2.SetNumPasses();
+
+    tlist.Replace(&readon);
+    if (fRndmSrcPos && !set.IsWobbleMode())
+        tlist2.RemoveFromList(&srcrndm);
+
+    MFillH fillsrc(&hsrcpos, "MSrcPosCam", "FillSrcPosCam");
+    fillsrc.SetNameTab("SrcPos");
+
+    if (set.IsWobbleMode()/* && !set.IsMonteCarlo()*/)
+        tlist2.AddToListBefore(&fillsrc, &hcalc);
+
+    MH3 hvs2("MPointingPos.fZd");
+    hvs2.SetName("Theta");
+    hvs2.SetTitle("Effective On-Time vs. Zenith Angle;\\Theta [\\circ];T_{on} [s]");
+
+    MFillH fillvs2(&hvs2, "", "FillOnTime");
+    if (!set.IsMonteCarlo())
+        fillvs2.SetWeight("MEffectiveOnTime");
+    fillvs2.SetNameTab("OnTime");
+    fillvs2.SetDrawOption(set.HasOffSequences()||set.IsWobbleMode()?"same":"");
+
+    if (!fWriteOnly)
+    {
+        tlist.Replace(&fill1b);
+
+        tlist2.Replace(&fill2b);
+        if (fFullDisplay)
+        {
+            tlist2.Replace(&fill3b);
+            tlist2.Replace(&fill3d);
+            tlist2.Replace(&fill4b);
+            tlist2.Replace(&fill5b);
+            tlist2.Replace(&fill6b);
+            tlist2.Replace(&fill7b);
+        }
+        tlist2.Replace(&falpha2);
+        //if (!fIsMonteCarlo)
+        //    tlist2.Replace(&fill9b);
+        if (!set.IsWobbleMode() || !fNameHist.IsNull())
+            tlist2.Replace(&ffs2);
+        if (set.IsWobbleMode())
+        {
+            tlist2.AddToListAfter(&fillphi, &falpha2);
+            if (!fNameHist.IsNull())
+                tlist2.RemoveFromList(&ffs);
+        }
+
+        if (!set.IsMonteCarlo())
+            tlist.Replace(&fillvs2);
+        else
+            tlist2.Replace(&fillvs2);
+    }
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    par.SetVal(1);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Processing of on-sequences failed." << endl;
+        return -4;
+    }
+
+    // FIXME: Perform fit and plot energy dependant alpha plots
+    // and fit result to new tabs!
+    if (!WriteResult(plist, set))
+        return kFALSE;
+
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJCut.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJCut.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJCut.h	(revision 17960)
@@ -0,0 +1,80 @@
+#ifndef MARS_MJCut
+#define MARS_MJCut
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MTask;
+class MDataSet;
+class MParList;
+class MHAlpha;
+class MH;
+class MWriteRootFile;
+class MPointingPos;
+class MHSrcPosCam;
+
+class MJCut : public MJob
+{
+private:
+    Bool_t  fStoreSummary;
+    Bool_t  fStoreResult;
+    Bool_t  fWriteOnly;
+    Bool_t  fFullDisplay;
+    Bool_t  fRndmSrcPos;
+    //Bool_t  fSubstraction;
+
+    UInt_t fNumOffSourcePos;
+
+    TString fNameSummary;
+    TString fNameResult;
+    TString fNameOutput;
+
+    TString fNameHist;
+    TString fNameHistFS;
+
+    MTask  *fCalcHadronness;
+    MTask  *fCalcDisp;
+    MTask  *fEstimateEnergy;
+
+    TString  GetOutputFile(UInt_t num) const;
+    Bool_t   CheckEnvLocal();
+    void     SetupWriter(MWriteRootFile *write, const char *name) const;
+    Bool_t   WriteTasks(UInt_t num, TObjArray &cont) const;
+    Bool_t   WriteResult(const MParList &plist, const MDataSet &set) const;
+    MHAlpha *CreateNewHist(MParList &plist, const char *name="") const;
+    MH      *CreateNewHistFS(MParList &plist, const char *name="") const;
+
+    Bool_t   CanStoreSummary() const { return !fPathOut.IsNull() && fStoreSummary; }
+    Bool_t   CanStoreResult() const  { return !fPathOut.IsNull() && fStoreResult;  }
+
+    Bool_t   FillSrcPosCam(const MDataSet &set, MPointingPos &source, MHSrcPosCam &srcpos);
+
+public:
+    MJCut(const char *name=NULL, const char *title=NULL);
+    ~MJCut();
+
+    Int_t Process(const MDataSet &set);
+
+    void EnableStorageOfSummary(Bool_t b=kTRUE)  { fStoreSummary = b; } // See SetNameSummary
+    void EnableStorageOfResult(Bool_t b=kTRUE)   { fStoreResult  = b; } // See SetNameResult
+    void EnableWriteOnly(Bool_t b=kTRUE)         { fWriteOnly    = b; }
+    void EnableFullDisplay(Bool_t b=kTRUE)       { fFullDisplay  = b; }
+    void EnableRandomSrcPos(Bool_t b=kTRUE)      { fRndmSrcPos   = b; }
+    //void EnableSubstraction(Bool_t b=kTRUE)      { fSubstraction = b; }
+
+    void SetNameSummaryFile(const char *name="");
+    void SetNameResultFile(const char *name="");
+    void SetNameOutFile(const char *name="")      { fNameOutput=name; }
+
+    void SetNameHist(const char *name) { fNameHist=name; }
+    void SetNameHistFS(const char *name) { fNameHistFS=name; }
+
+    void SetEnergyEstimator(const MTask *task=0);
+    void SetHadronnessCalculator(const MTask *task=0);
+    void SetDispCalculator(const MTask *task=0);
+
+    ClassDef(MJCut, 0) // Standard program to perform g/h-separation cuts
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJExtractSignal.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJExtractSignal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJExtractSignal.cc	(revision 17960)
@@ -0,0 +1,537 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+#include "MPrint.h"
+
+#include "MHCamera.h"
+
+#include "MPedestalCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationQECam.h"
+#include "MHCamEvent.h"
+
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MBadPixelsMerge.h"
+#include "MExtractSignal.h"
+#include "MFillH.h"
+#include "MCalibrateData.h"
+#include "MPedPhotCalc.h"
+#include "MWriteRootFile.h"
+
+#include "MExtractSlidingWindow.h"
+#include "MExtractor.h"
+#include "MExtractTime.h"
+#include "MExtractTimeFastSpline.h"
+
+#include "MJExtractSignal.h"
+#include "MStatusDisplay.h"
+
+
+ClassImp(MJExtractSignal);
+
+using namespace std;
+
+MJExtractSignal::MJExtractSignal(const char *name, const char *title)
+    : fRuns(0), fExtractor(NULL), fTimeExtractor(NULL)
+{
+    fName  = name  ? name  : "MJExtractSignal";
+    fTitle = title ? title : "Tool to create a pedestal file (MPedestalCam)";
+}
+
+Bool_t MJExtractSignal::WriteResult()
+{
+    if (fOutputPath.IsNull())
+        return kTRUE;
+
+    const TString oname = GetOutputFileP();
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile file(oname, "RECREATE");
+
+    if (fDisplay && fDisplay->Write()<=0)
+    {
+        *fLog << err << "Unable to write MStatusDisplay to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fPedPhotCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MPedPhotCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fBadPixels.Write()<=0)
+    {
+        *fLog << err << "Unable to write MBadPixelsCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+
+}
+
+void MJExtractSignal::SetOutputPath(const char *path)
+{
+    fOutputPath = path;
+    if (fOutputPath.EndsWith("/"))
+        fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+TString MJExtractSignal::GetOutputFileD() const
+{
+    if (!fRuns)
+        return "";
+
+    return Form("%s/%s-F3.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
+}
+TString MJExtractSignal::GetOutputFileP() const
+{
+    if (!fRuns)
+        return "";
+
+    return Form("%s/%s-F2.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
+}
+
+Bool_t MJExtractSignal::ProcessD(MPedestalCam &pedcam)
+{
+    const TString fname = GetOutputFileD();
+
+    if (gSystem->AccessPathName(fname, kFileExists))
+        return ProcessFileD(pedcam);
+
+    return kTRUE;
+}
+
+Bool_t MJExtractSignal::ProcessFileD(MPedestalCam &pedcam)
+{
+
+  if (!fRuns)
+    {
+      *fLog << err << "No Runs choosen... abort." << endl;
+      return kFALSE;
+    }
+  if (fRuns->GetNumRuns() != fRuns->GetNumEntries())
+    {
+        *fLog << err << "Number of files found doesn't match number of runs... abort." << endl;
+        return kFALSE;
+    }
+  
+  *fLog << inf;
+  fLog->Separator(GetDescriptor());
+  *fLog << "Calculate MExtractedSignalCam from Runs " << fRuns->GetRunsAsString() << endl;
+  *fLog << endl;
+  
+  // Setup Lists
+  MParList plist;
+  plist.AddToList(&pedcam);
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  // Setup Parameters
+  
+  // Make sure, that at least an empty MBadPixelsCam is available
+  // This is necessary for input which don't contain a MBadPixelsCam
+  MBadPixelsCam badcam;
+  plist.AddToList(&badcam);
+  
+  // Setup Task-lists
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(*fRuns);
+  
+  MGeomApply               apply; // Only necessary to craete geometry
+  MBadPixelsMerge          merge(&fBadPixels);
+  MExtractTimeFastSpline   exttime;
+  MExtractSlidingWindow    extcharge; // Only for the cosmics filter
+  
+  MHCamEvent evt("ExtSignal");
+  evt.SetType(0);
+  MFillH fill(&evt, "MExtractedSignalCam");
+  
+  MWriteRootFile write(GetOutputFileD(), "RECREATE", fRuns->GetRunsAsString(), 2);
+  write.AddContainer("MExtractedSignalCam", "Events");
+  write.AddContainer("MArrivalTimeCam",     "Events");
+  write.AddContainer("MTime",               "Events");
+  write.AddContainer("MRawEvtHeader",       "Events");
+  write.AddContainer("MPedestalCam",        "RunHeaders");
+  write.AddContainer("MRawRunHeader",       "RunHeaders");
+  write.AddContainer("MBadPixelsCam",       "RunHeaders");
+  
+  tlist.AddToList(&read);
+  tlist.AddToList(&apply);
+  tlist.AddToList(&merge);
+  
+  if (fTimeExtractor)
+    tlist.AddToList(fTimeExtractor);
+  else
+  {
+      *fLog << warn << GetDescriptor() 
+            << ": No extractor has been chosen, take default MExtractTimeFastSpline " << endl;
+      tlist.AddToList(&exttime);
+  }
+
+  if (fExtractor)
+    tlist.AddToList(fExtractor);
+  else
+  {
+      *fLog << warn << GetDescriptor() 
+            << ": No extractor has been chosen, take default MExtractSlidingWindow " << endl;
+      tlist.AddToList(&extcharge);
+  }
+
+//  MPrint print("MExtractedSignalCam");
+//  tlist.AddToList(&print);
+  
+  if (TestBit(kEnableGraphicalOutput))
+    tlist.AddToList(&fill);
+  tlist.AddToList(&write);
+  
+  // Create and setup the eventloop
+  MEvtLoop evtloop(fName);
+  evtloop.SetParList(&plist);
+  evtloop.SetDisplay(fDisplay);
+  evtloop.SetLogStream(fLog);
+  
+  // Execute first analysis
+  if (!evtloop.Eventloop())
+    {
+      *fLog << err << GetDescriptor() << ": Failed." << endl;
+      return kFALSE;
+    }
+  
+  tlist.PrintStatistics();
+  
+  //DisplayResult(plist);
+  
+  //if (!WriteResult())
+  //    return kFALSE;
+  
+  *fLog << inf << GetDescriptor() << ": Done." << endl;
+  
+  return kTRUE;
+}
+
+Bool_t MJExtractSignal::ReadPedPhotCam()
+{
+    const TString fname = GetOutputFileP();
+
+    if (gSystem->AccessPathName(fname, kFileExists))
+    {
+        *fLog << err << "Input file " << fname << " doesn't exist." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Reading from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (fPedPhotCam.Read()<=0)
+    {
+        *fLog << "Unable to read MPedPhotCam from " << fname << endl;
+        return kFALSE;
+    }
+
+    if (file.FindKey("MBadPixelsCam"))
+    {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+        {
+            *fLog << "Unable to read MBadPixelsCam from " << fname << endl;
+            return kFALSE;
+        }
+        fBadPixels.Merge(bad);
+    }
+
+    if (fDisplay /*&& !fDisplay->GetCanvas("Pedestals")*/) // FIXME!
+        fDisplay->Read();
+
+    return kTRUE;
+}
+
+Bool_t MJExtractSignal::ProcessP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam)
+{
+    if (!ReadPedPhotCam())
+        return ProcessFileP(pedcam, calcam, qecam);
+
+    return kTRUE;
+}
+
+Bool_t MJExtractSignal::ProcessFileP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam)
+{
+    if (!fRuns)
+    {
+        *fLog << err << "No Runs choosen... abort." << endl;
+        return kFALSE;
+    }
+    if (fRuns->GetNumRuns() != fRuns->GetNumEntries())
+    {
+        *fLog << err << "Number of files found doesn't match number of runs... abort." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate MExtractedSignalCam from Runs " << fRuns->GetRunsAsString() << endl;
+    *fLog << endl;
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    static_cast<MRead&>(read).AddFiles(*fRuns);
+
+    // Setup Tasklist
+    MParList plist;
+    plist.AddToList(&pedcam);
+    plist.AddToList(&calcam);
+    plist.AddToList(&qecam);
+    plist.AddToList(&fPedPhotCam);
+    plist.AddToList(&fBadPixels);
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MGeomApply      apply; // Only necessary to craete geometry
+    MBadPixelsMerge merge(&fBadPixels);
+    MExtractSignal  extract;
+    MCalibrateData  calib;
+    MPedPhotCalc    calc;
+
+    MHCamEvent evt1("ExtOffset");
+    MHCamEvent evt2("CalOffset");
+    evt1.SetType(0);
+    evt2.SetType(0);
+    MFillH fill1(&evt1, "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill2(&evt2, "MCerPhotEvt",         "FillCerPhotEvt");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&merge);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill1);
+    tlist.AddToList(&calib);
+    tlist.AddToList(&calc);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill2);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    //DisplayResult(plist);
+
+    if (!WriteResult())
+        return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+}
+
+/*
+Bool_t MJExtractSignal::ProcessFile(MPedestalCam *pedcam, MCalibrationChargeCam *calcam)
+{
+    if (!fRuns)
+    {
+        *fLog << err << "No Runs choosen... abort." << endl;
+        return kFALSE;
+    }
+    if (fRuns->GetNumRuns() != fRuns->GetNumEntries())
+    {
+        *fLog << err << "Number of files found doesn't match number of runs... abort." << endl;
+        return kFALSE;
+    }
+
+    Int_t type = 0;
+    if (pedcam &&  calcam) type = 2;
+    if (pedcam && !calcam) type = 3;
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculating from Runs " << fRuns->GetRunsAsString() << endl;
+    *fLog << endl;
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    static_cast<MRead&>(read).AddFiles(*fRuns);
+
+    // Setup Tasklist
+    MParList plist;
+    switch (type)
+    {
+    case 2:
+        plist.AddToList(calcam);
+        plist.AddToList(&fPedPhotCam);
+    case 3:
+        plist.AddToList(pedcam);
+    }
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MGeomApply     apply; // Only necessary to craete geometry
+    MExtractSignal extract;
+    MCalibrateData calib;
+    MPedPhotCalc   calc;
+
+
+    MHCamEvent evt1("ExtOffset");
+    MHCamEvent evt2("CalOffset");
+    evt1.SetType(0);
+    evt2.SetType(0);
+    MFillH fill1(&evt1, "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill2(&evt2, "MCerPhotEvt",         "FillCerPhotEvt");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill1);
+    tlist.AddToList(&calib);
+    tlist.AddToList(&calc);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill2);
+
+
+    MHCamEvent evt("ExtSignal");
+    evt.SetType(0);
+    MFillH fill(&evt, "MExtractedSignalCam");
+
+    MWriteRootFile write(GetOutputFileD(), "RECREATE", fRuns->GetRunsAsString(), 2);
+    write.AddContainer("MExtractedSignalCam", "Events");
+    write.AddContainer("MTime",               "Events");
+    write.AddContainer("MRawRunHeader",       "RunHeaders");
+    write.AddContainer("MPedestalCam",        "RunHeaders");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill);
+    tlist.AddToList(&write);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    //DisplayResult(plist);
+
+    //if (!WriteResult())
+    //    return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+
+
+    // ------------------------------------------------------
+
+    MGeomApply     apply; // Only necessary to craete geometry
+    MExtractSignal extract;
+    MCalibrateData  calib;
+    MPedPhotCalc   calc;
+
+    MHCamEvent evt1("ExtOffset");
+    MHCamEvent evt2("CalOffset");
+    evt1.SetType(0);
+    evt2.SetType(0);
+    MFillH fill1(&evt1, "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill2(&evt2, "MCerPhotEvt",         "FillCerPhotEvt");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill1);
+    tlist.AddToList(&calib);
+    tlist.AddToList(&calc);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill2);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    //DisplayResult(plist);
+
+    if (!WriteResult())
+        return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+    }
+    */
Index: branches/Mars_McMismatchStudy/mjobs/MJExtractSignal.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJExtractSignal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJExtractSignal.h	(revision 17960)
@@ -0,0 +1,65 @@
+#ifndef MARS_MJExtractSignal
+#define MARS_MJExtractSignal
+
+#ifndef MARS_MPedPhotCam
+#include "MPedPhotCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class TCanvas;
+class MHCamera;
+class MCamEvent;
+class MRunIter;
+class MParList;
+class MPedestalCam;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MExtractor;
+class MExtractTime;
+
+class MJExtractSignal : public MParContainer
+{
+private:
+    TString fOutputPath;
+
+    MRunIter *fRuns;
+    
+    MExtractor   *fExtractor;                  // Signal extractor
+    MExtractTime *fTimeExtractor;              // Arrival time extractor  
+
+    MPedPhotCam   fPedPhotCam;
+    MBadPixelsCam fBadPixels;
+
+    void   DisplayResult(MParList &plist);
+    Bool_t WriteResult();
+
+    Bool_t ReadPedPhotCam();
+
+    Bool_t ProcessFileD(MPedestalCam &pedcam);
+    Bool_t ProcessFileP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam);
+
+public:
+    MJExtractSignal(const char *name=NULL, const char *title=NULL);
+
+    void SetInput(MRunIter *iter) { fRuns = iter; }
+    void SetOutputPath(const char *path=".");
+
+    TString GetOutputFileP() const;
+    TString GetOutputFileD() const;
+
+    MPedPhotCam &GetPedPhotCam() { return fPedPhotCam; }
+    const MBadPixelsCam &GetBadPixels()  const { return fBadPixels; }
+
+    void SetExtractor(MExtractor* ext)              { fExtractor = ext; }
+    void SetTimeExtractor(MExtractTime* ext)         { fTimeExtractor = ext; }
+    void SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+
+    Bool_t ProcessD(MPedestalCam &pedcam);
+    Bool_t ProcessP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam);
+
+    ClassDef(MJExtractSignal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJMerpp.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJMerpp.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJMerpp.cc	(revision 17960)
@@ -0,0 +1,398 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 7/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJMerpp
+//
+// Merging and preprocessing
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJMerpp.h"
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MFDataPhrase.h"
+
+#include "MRawRunHeader.h"
+
+#include "MRawFileRead.h"
+#include "MRawFitsRead.h"
+#include "MReportFileReadCC.h"
+#include "MWriteRootFile.h"
+
+ClassImp(MJMerpp);
+
+using namespace std;
+
+MJMerpp::MJMerpp(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MJMerpp";
+    fTitle = title ? title : "Standard program for merging subsystem data";
+}
+
+void MJMerpp::AddTree(MReportFileReadCC &read, const TString &rep, const TString &only) const
+{
+    if (!only.IsNull() && rep!=only)
+        return;
+
+    read.AddToList(Form("MReport%s", rep.Data()));
+}
+
+void MJMerpp::SetupCurrents(MReportFileReadCC &read, MWriteRootFile *write) const
+{
+    read.SetHasNoHeader();
+    read.AddToList("MReportCurrents");
+
+    if (!write)
+        return;
+
+    write->AddContainer("MTimeCurrents",      "Currents");
+    write->AddContainer("MCameraDC",          "Currents");
+    write->AddContainer("MReportCurrents",    "Currents");
+}
+
+MFilter *MJMerpp::SetupReports(MReportFileReadCC &read, MWriteRootFile *write) const
+{
+    read.SetTelescope(fTelescope);
+
+    read.SetRunNumber(fHeaderRun);
+    read.SetFileNumber(fHeaderFile);
+
+    AddTree(read, "CC",         fOnly);
+    AddTree(read, "Rec",        fOnly);
+    AddTree(read, "Drive",      fOnly);
+    AddTree(read, "Camera",     fOnly);
+    AddTree(read, "Trigger",    fOnly);
+    AddTree(read, "Starguider", fOnly);
+    AddTree(read, "Pyrometer",  fOnly);
+    // AddTree(read, "DAQ",  fOnly);
+
+    if (fReportRun!=(UInt_t)-1)
+        read.AddToList("MReportRun");
+
+    if (!write)
+        return 0;
+
+    const Bool_t required = fOnly.IsNull();
+    write->AddContainer("MReportCamera",      "Camera",     required);
+    write->AddContainer("MTimeCamera",        "Camera",     required);
+    write->AddContainer("MCameraAUX",         "Camera",     required);
+    write->AddContainer("MCameraCalibration", "Camera",     required);
+    write->AddContainer("MCameraCooling",     "Camera",     required);
+    write->AddContainer("MCameraActiveLoad",  "Camera",     required);
+    write->AddContainer("MCameraHV",          "Camera",     required);
+    write->AddContainer("MCameraDC",          "Camera",     required);
+    write->AddContainer("MCameraLV",          "Camera",     required);
+    write->AddContainer("MCameraLids",        "Camera",     required);
+    write->AddContainer("MReportTrigger",     "Trigger",    required);
+    write->AddContainer("MTimeTrigger",       "Trigger",    required);
+    write->AddContainer("MTriggerBit",        "Trigger",    required);
+    write->AddContainer("MTriggerIPR",        "Trigger",    required);
+    write->AddContainer("MTriggerCell",       "Trigger",    required);
+    write->AddContainer("MTriggerPrescFact",  "Trigger",    required);
+    write->AddContainer("MTriggerLiveTime",   "Trigger",    required);
+    write->AddContainer("MReportDrive",       "Drive",      required);
+    write->AddContainer("MTimeDrive",         "Drive",      required);
+    write->AddContainer("MCameraTH",          "Rec",        required);
+    write->AddContainer("MCameraTD",          "Rec",        required);
+    write->AddContainer("MCameraRecTemp",     "Rec",        required);
+    write->AddContainer("MReportRec",         "Rec",        required);
+    write->AddContainer("MTimeRec",           "Rec",        required);
+    write->AddContainer("MReportCC",          "CC",         required);
+    write->AddContainer("MTimeCC",            "CC",         required);
+    write->AddContainer("MReportStarguider",  "Starguider", required);
+    write->AddContainer("MTimeStarguider",    "Starguider", required);
+    write->AddContainer("MReportPyrometer",   "Pyrometer",  required);
+    write->AddContainer("MTimePyrometer",     "Pyrometer",  required);
+    // write->AddContainer("MReportDAQ",         "DAQ");
+    // write->AddContainer("MTimeDAQ",           "DAQ");
+
+    if (fReportRun==(UInt_t)-1)
+        return 0;
+
+    const TString f1 = fReportRun>0   ? Form("MReportRun.fRunNumber==%ud",  fReportRun)  : "";
+    const TString f2 = fReportFile>=0 ? Form("MReportRun.fFileNumber==%ud", fReportFile) : "";
+
+    const TString f = Form(fReportRun>0 && fReportFile>=0 ? "%s && %s" : "%s%s",
+                           f1.Data(), f2.Data());
+
+    MFilter *filter = new MFDataPhrase(f.Data());
+    write->SetFilter(filter);
+    return filter;
+}
+
+void MJMerpp::SetupRaw(MRawFileRead &read, MWriteRootFile *write) const
+{
+//    read.SetInterleave(fInterleave);
+//    read.SetForceMode(fForceProcessing);
+
+    if (!write)
+        return;
+
+    write->AddContainer("MRawRunHeader",  "RunHeaders");
+    write->AddContainer("MTime",          "Events");
+    write->AddContainer("MRawEvtHeader",  "Events");
+    write->AddContainer("MRawEvtData",    "Events");
+    write->AddContainer("MRawEvtData2",   "Events");
+    write->AddContainer("MRawCrateArray", "Events");
+}
+
+Bool_t MJMerpp::GetTimeFromFile()
+{
+    if (!fAutoStartTime && !fAutoStopTime)
+        return kTRUE;
+
+    TFile f(fPathOut, "READ");
+    if (f.IsZombie())
+    {
+        *fLog << err << "ERROR - File " << fPathOut << " could not be opened." << endl;
+        return kFALSE;
+    }
+
+    TTree *t = (TTree*)f.Get("RunHeaders");
+    if (t->GetEntries()!=1)
+    {
+        *fLog << err << "ERROR - File " << fPathOut << " contains no or more than one entry in RunHeaders... Times unchanged." << endl;
+        return kFALSE;
+    }
+
+    MRawRunHeader *h = 0;
+    t->SetBranchAddress("MRawRunHeader.", &h);
+    t->GetEntry(0);
+    if (!h)
+    {
+        *fLog << err << "ERROR - File " << fPathOut << " did not contain RunHeaders.MRawRunHeader... Times unchanged." << endl;
+        return kFALSE;
+    }
+
+    if (fAutoStartTime)
+        fTimeStart = h->GetRunStart();
+    if (fAutoStopTime)
+        fTimeStop = h->GetRunEnd();
+
+    return kTRUE;
+}
+
+Bool_t MJMerpp::CheckFilePermissions()
+{
+    //
+    // check whether the given files are OK.
+    //
+    if (gSystem->AccessPathName(fPathIn, kFileExists))
+    {
+        *fLog << err << "ERROR - Input file '" << fPathIn << "' not accessible." << endl;
+        return kFALSE;
+    }
+
+    if (HasNullOut())
+        return kTRUE;
+
+    const Bool_t fileexist = !gSystem->AccessPathName(fPathOut, kFileExists);
+    const Bool_t writeperm = !gSystem->AccessPathName(fPathOut, kWritePermission);
+
+    if (fileexist && !writeperm)
+    {
+        *fLog << err << "ERROR - No write permission for '" << fPathOut << "'." << endl;
+        return kFALSE;
+    }
+
+    if (fileexist && !fUpdate && !fOverwrite)
+    {
+        *fLog << err << "ERROR - File '" << fPathOut << "' already existing." << endl;
+        return kFALSE;
+    }
+
+    if (!fileexist && fUpdate)
+    {
+        *fLog << err << "ERROR - File '" << fPathOut << "' doesn't yet exist... no update possible." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Int_t MJMerpp::Process()
+{
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "In:  " << fPathIn << endl;
+    if (!HasNullOut())
+        *fLog << (fUpdate?"Upd":"Out") << ": " << fPathOut << endl;;
+    *fLog << endl;
+
+    if (!CheckFilePermissions())
+        return 1;
+
+    // FIXME: Add a check whether the file has already been merpped!!!
+
+    const Bool_t isreport = fPathIn.EndsWith(".rep");
+    const Bool_t isdc     = fPathIn.EndsWith(".txt");
+
+    //
+    // Evaluate possible start-/stop-time
+    //
+    if (fUpdate && (isreport || isdc))
+        if (!GetTimeFromFile())
+            return 2;
+
+    if (fTimeStart)
+        *fLog << inf << "Start Time: " << fTimeStart << endl;
+    if (fTimeStop)
+        *fLog << inf << "Stop  Time: " << fTimeStop << 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);
+
+    //
+    // 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
+    //
+    const TString option(fUpdate?"UPDATE":(fOverwrite?"RECREATE":"NEW"));
+
+    MTask          *read   = 0;
+    MFilter        *filter = 0;
+    MWriteRootFile *write  = HasNullOut() ? 0 : new MWriteRootFile(fPathOut, option, "Magic root-file", fCompression);
+
+    if (isreport || isdc)
+    {
+        MReportFileReadCC *r = new MReportFileReadCC(fPathIn);
+        r->SetTimeStart(fTimeStart);
+        r->SetTimeStop(fTimeStop);
+
+        if (isdc)
+            SetupCurrents(*r, write);
+        else
+            filter = SetupReports(*r, write);
+
+        read = r;
+    }
+    else
+    {
+        MRawFileRead *r = MRawFitsRead::IsFits(fPathIn) ? new MRawFitsRead(fPathIn) : new MRawFileRead(fPathIn);
+        SetupRaw(*r, write);
+        read = r;
+    }
+
+    tasks.AddToList(read);
+    if (filter)
+        tasks.AddToList(filter);
+
+    if (write)
+        tasks.AddToList(write);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetLogStream(fLog);
+    //evtloop.SetDisplay(fDisplay);
+    //if (!SetupEnv(evtloop))
+    //    return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return 3;
+    }
+
+    *fLog << all << GetDescriptor() << ": Done." << endl << endl << endl;;
+
+    return 0;
+}
+
+Int_t MJMerpp::ProcessSeq(TString fname)
+{
+    if (!MSequence::InflateSeq(fname))
+        return 4;
+
+    MSequence seq(fname);
+    if (!seq.IsValid())
+        return 5;
+
+    const UInt_t num = seq.GetNumEntries(MSequence::kDat);
+
+    const TString reppath = fPathIn;
+    const TString calpath = fPathOut;
+
+    // PreCheck: We don't wantto start merpp if we
+    // know that an error will occur
+    for (UInt_t i=0; i<num; i++)
+    {
+        const TString name1 = fHeaderRun==0 ? reppath : seq.GetFileName(i, MSequence::kReportDat, reppath);
+        const TString name2 = seq.GetFileName(i, MSequence::kCalibrated, calpath);
+
+        // Full qualified name could not be determined or file is not
+        // accessible. For excluded files "0" is returned.
+        if (name1.IsNull() || name2.IsNull())
+            return 6;
+    }
+
+    // Now we can safely start processing
+    TString rc;
+    for (UInt_t i=0; i<num; i++)
+    {
+        UInt_t run, file;
+
+        // Excluded
+        if (seq.GetFile(i, MSequence::kDat, run, file)==0)
+            continue;
+
+        // fHeaderRun==0 means: All day summary file
+        const TString name1 = fHeaderRun==0 ? reppath : seq.GetFileName(i, MSequence::kReportDat, reppath);
+        const TString name2 = seq.GetFileName(i, MSequence::kCalibrated, calpath);
+
+        // FIXME: check runcallisto
+        if (fHeaderRun==0)                 // extract valid range from summary file
+            SetConstrainRunRep(run, file); // (this is not guranteed to work :-( )
+        else                               // check for the correct header
+            SetConstrainHeader(seq.GetTelescope(), run, file);
+
+        SetTime(MTime(), MTime()); // Raise error if set?
+        SetPathIn(name1);
+        SetPathOut(name2);
+
+        const Int_t rc = Process();
+        if (rc==0)
+            continue;
+
+        return rc;
+    }
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJMerpp.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJMerpp.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJMerpp.h	(revision 17960)
@@ -0,0 +1,74 @@
+#ifndef MARS_MJMerpp
+#define MARS_MJMerpp
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MReportFileReadCC;
+class MWriteRootFile;
+class MFilter;
+class MRawFileRead;
+
+class MJMerpp : public MJob
+{
+    // Merpp general
+    Byte_t fCompression;
+    Bool_t fUpdate;
+
+    // Setup Raw
+    Bool_t fInterleave;
+    Bool_t fForceProcessing;
+
+    // Setup Reports
+    Short_t  fTelescope;
+
+    UInt_t   fHeaderRun;
+    UInt_t   fHeaderFile;
+
+    UInt_t   fReportRun;
+     Int_t   fReportFile;
+
+    TString  fOnly;
+
+    // Setup reports, currents
+    MTime fTimeStart;
+    MTime fTimeStop;
+
+    Bool_t fAutoStartTime;
+    Bool_t fAutoStopTime;
+
+private:
+    void AddTree(MReportFileReadCC &read, const TString &rep, const TString &only) const;
+
+    void     SetupCurrents(MReportFileReadCC &read, MWriteRootFile *write) const;
+    MFilter *SetupReports(MReportFileReadCC &read, MWriteRootFile *write) const;
+    void     SetupRaw(MRawFileRead &read, MWriteRootFile *write) const;
+
+    Bool_t GetTimeFromFile();
+    Bool_t CheckFilePermissions();
+
+public:
+    MJMerpp(const char *name=0, const char *title=0);
+
+    void SetCompression(Byte_t comp)   { fCompression=comp;   }
+    void SetUpdate(Bool_t upd)         { fUpdate=upd;         }
+    void SetInterleave(Bool_t il)      { fInterleave=il;      }
+    void SetForceProcessing(Bool_t fp) { fForceProcessing=fp; }
+    void SetOnly(const char *tree)     { fOnly=tree;          }
+    void SetConstrainHeader(Short_t tel, Int_t run, Int_t file)
+    { fTelescope=tel; fHeaderRun=run; fHeaderFile=file; }
+    void SetConstrainRunRep(UInt_t run, Int_t file)
+    { fReportRun=run; fReportFile=file; }
+    void SetTime(const MTime &start, const MTime &stop)
+    { fTimeStart=start; fTimeStop=stop; }
+    void SetAutoTime(Bool_t start, Bool_t stop)
+    { fAutoStartTime=start; fAutoStopTime=stop; }
+
+    Int_t Process();
+    Int_t ProcessSeq(TString fname);
+
+    ClassDef(MJMerpp, 0) // Merging and preprocessing
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJPedestal.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJPedestal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJPedestal.cc	(revision 17960)
@@ -0,0 +1,1201 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Markus Gaug, 4/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJPedestal
+//
+// Resource file entries are case sensitive!
+//
+// We require at least fMinEvents (def=50) to be processed by the
+// ExtractPedestal-task. If not an error is returned.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJPedestal.h"
+
+// C/C++ includes
+#include <fstream>
+
+// root classes
+#include <TF1.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+
+#include <TEnv.h>
+#include <TFile.h>
+
+// mars core
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+#include "MTaskEnv.h"
+#include "MSequence.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+// Other basic classes
+#include "MExtractTimeAndCharge.h"
+
+// parameter containers
+#include "MGeomCam.h"
+#include "MHCamera.h"
+#include "MPedestalPix.h"
+
+//#include "MHPedestalPix.h"
+#include "MCalibrationPix.h"
+#include "MHCalibrationPulseTimeCam.h"
+#include "MCalibrationPulseTimeCam.h"
+
+// tasks
+#include "MReadMarsFile.h"
+#include "MRawFileRead.h"
+#include "MGeomApply.h"
+#include "MContinue.h"
+#include "MPedestalSubtract.h"
+#include "MTriggerPatternDecode.h"
+#include "MBadPixelsMerge.h"
+#include "MFillH.h"
+#include "MPedCalcPedRun.h"
+#include "MPedCalcFromLoGain.h"
+#include "MBadPixelsCalc.h"
+#include "MPedestalSubtract.h"
+
+// filter
+#include "MFilterList.h"
+#include "MFTriggerPattern.h"
+#include "MFDataMember.h"
+
+ClassImp(MJPedestal);
+
+using namespace std;
+
+const TString  MJPedestal::fgReferenceFile   = "mjobs/pedestalref.rc";
+const TString  MJPedestal::fgBadPixelsFile   = "mjobs/badpixels_0_559.rc";
+const Float_t  MJPedestal::fgExtractWinLeft  = 0;
+const Float_t  MJPedestal::fgExtractWinRight = 0;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fExtractor to NULL, 
+// - fExtractType to kUsePedRun
+// - fStorage to Normal Storage
+// - fExtractorResolution to kFALSE
+//
+MJPedestal::MJPedestal(const char *name, const char *title) 
+    : fExtractor(NULL), fDisplayType(kDisplayDataCheck),
+    fExtractType(kUsePedRun), fExtractionType(kFundamental),
+    /*fIsUseHists(kFALSE),*/ fDeadPixelCheck(kFALSE), fMinEvents(50),
+    fMinPedestals(100), fMaxPedestals(0), fMinCosmics(25), fMaxCosmics(100)
+{
+    fName  = name  ? name  : "MJPedestal";
+    fTitle = title ? title : "Tool to create a pedestal file (MPedestalCam)";
+
+    SetUsePedRun();
+    SetPathIn("");
+    SetReferenceFile();
+    SetBadPixelsFile();
+
+    SetExtractWinLeft();
+    SetExtractWinRight();
+    //
+    // Default references for case that no value references file is there
+    // (should not occur)
+    //
+
+    fPedestalMin                 = 4.;
+    fPedestalMax                 = 16.;
+    fPedRmsMin                   = 0.;
+    fPedRmsMax                   = 20.;
+    fRefPedClosedLids            = 9.635;
+    fRefPedExtraGalactic         = 9.93;
+    fRefPedGalactic              = 10.03;
+    fRefPedRmsClosedLidsInner    = 1.7;
+    fRefPedRmsExtraGalacticInner = 5.6;
+    fRefPedRmsGalacticInner      = 6.92;
+    fRefPedRmsClosedLidsOuter    = 1.7;
+    fRefPedRmsExtraGalacticOuter = 3.35;
+    fRefPedRmsGalacticOuter      = 4.2;
+}
+
+MJPedestal::~MJPedestal()
+{
+    if (fExtractor)
+        delete fExtractor;
+}
+
+const char* MJPedestal::GetOutputFileName() const
+{
+    return Form("pedest%08d.root", fSequence.GetSequence());
+}
+
+MExtractor *MJPedestal::ReadCalibration()
+{
+    const TString fname = Form("%s/calib%08d.root", fPathIn.Data(), fSequence.GetSequence());
+
+    *fLog << inf << "Reading extractor from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+        return NULL;
+    }
+
+    if (file.FindKey("MBadPixelsCam"))
+    {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+            *fLog << warn << "Unable to read MBadPixelsCam from " << fname << endl;
+        else
+            fBadPixels.Merge(bad);
+    }
+
+    if (fExtractor)
+        return fExtractor;
+
+    TObject *o=0;
+    o = file.Get("ExtractSignal");
+    if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+        return NULL;
+    }
+    return o ? (MExtractor*)o->Clone("ExtractSignal") : NULL;
+}
+
+//---------------------------------------------------------------------------------
+//
+// Display the results. 
+// If Display type "kDataCheck" was chosen, also the reference lines are displayed.
+//
+void MJPedestal::DisplayResult(const MParList &plist)
+{
+    if (!fDisplay)
+        return;
+
+    //
+    // Update display
+    //
+    TString title = "--  Pedestal: ";
+    title += fSequence.GetSequence();
+    title += "  --";
+    fDisplay->SetTitle(title, kFALSE);
+
+    //
+    // Get container from list
+    //
+    const MGeomCam &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
+    //    MCalibrationPedCam &calpedcam = *(MCalibrationPedCam*)plist.FindObject("MCalibrationPedCam");
+
+    //
+    // Create container to display
+    //
+    MHCamera disp0 (geomcam, "MPedestalCam;ped", "Mean Pedestal");
+    MHCamera disp1 (geomcam, "MPedestalCam;RMS", "Pedestal RMS");
+    MHCamera disp2 (geomcam, "MCalibPedCam;histmean", "Mean Pedestal (Hist.)");
+    MHCamera disp3 (geomcam, "MCalibPedCam;histsigma", "Pedestal RMS (Hist.)");
+    MHCamera disp4 (geomcam, "MCalibPedCam;ped", "Mean Pedestal");
+    MHCamera disp5 (geomcam, "MCalibPedCam;RMS", "Pedestal RMS");
+    MHCamera disp6 (geomcam, "MCalibDiffCam;ped", "Diff. Mean Pedestal (Hist.)");
+    MHCamera disp7 (geomcam, "MCalibDiffCam;RMS", "Diff. Pedestal RMS (Hist.)");
+    MHCamera disp8 (geomcam, "MCalibDiffCam;ped", "Diff. Mean Pedestal");
+    MHCamera disp9 (geomcam, "MCalibDiffCam;AbsRMS", "Diff. Abs. Pedestal RMS");
+    MHCamera disp10(geomcam, "MCalibDiffCam;RelRMS", "Diff. Rel. Pedestal RMS");
+
+    disp0.SetCamContent(fPedestalCamOut, 0);
+    disp0.SetCamError  (fPedestalCamOut, 1);
+
+    disp1.SetCamContent(fPedestalCamOut, 2);
+    disp1.SetCamError  (fPedestalCamOut, 3);
+
+    /*
+    if (fIsUseHists)
+      {
+        disp2.SetCamContent(calpedcam, 0);
+        disp2.SetCamError  (calpedcam, 1);
+
+        disp3.SetCamContent(calpedcam, 2);
+        disp3.SetCamError  (calpedcam, 3);
+
+        disp4.SetCamContent(calpedcam, 5);
+        disp4.SetCamError  (calpedcam, 6);
+
+        disp5.SetCamContent(calpedcam, 7);
+        disp5.SetCamError  (calpedcam, 8);
+
+        for (UInt_t i=0;i<geomcam.GetNumPixels();i++)
+          {
+
+            MPedestalPix    &ped  = fPedestalCamOut[i];
+            MCalibrationPix &hist = calpedcam [i];
+            MBadPixelsPix &bad  = fBadPixels[i];
+
+            if (bad.IsUnsuitable())
+              continue;
+
+            disp6.Fill(i,ped.GetPedestal()-hist.GetHiGainMean());
+            disp6.SetUsed(i);
+
+            disp7.Fill(i,hist.GetHiGainSigma()-ped.GetPedestalRms());
+            if (TMath::Abs(ped.GetPedestalRms()-hist.GetHiGainSigma()) < 4.0)
+              disp7.SetUsed(i);
+
+            disp8.Fill(i,ped.GetPedestal()-hist.GetLoGainMean());
+            disp8.SetUsed(i);
+
+            disp9.Fill(i,hist.GetLoGainSigma()-ped.GetPedestalRms());
+            if (TMath::Abs(hist.GetLoGainSigma() - ped.GetPedestalRms()) < 4.0)
+              disp9.SetUsed(i);
+          }
+      }
+    */
+
+    if (fExtractionType!=kFundamental/*fExtractorResolution*/)
+      {
+        for (UInt_t i=0;i<geomcam.GetNumPixels();i++)
+          {
+
+            MPedestalPix &pedo  = fPedestalCamOut[i];
+            MPedestalPix &pedi  = fPedestalCamIn[i];
+            MBadPixelsPix &bad  = fBadPixels[i];
+
+            if (bad.IsUnsuitable())
+              continue;
+
+            const Float_t diff = pedo.GetPedestalRms()-pedi.GetPedestalRms();
+            const Float_t sum  = 0.5*(pedo.GetPedestalRms()+pedi.GetPedestalRms());
+
+            disp9.Fill(i,pedo.GetPedestalRms()-pedi.GetPedestalRms());
+            if (pedo.IsValid() && pedi.IsValid())
+              disp9.SetUsed(i);
+
+            disp10.Fill(i,sum == 0. ? 0. : diff/sum);
+            if (pedo.IsValid() && pedi.IsValid() && sum != 0.)
+              disp10.SetUsed(i);
+          }
+      }
+
+    disp0.SetYTitle("P [cts/slice]");
+    disp1.SetYTitle("P_{rms} [cts/slice]");
+    disp2.SetYTitle("Hist. Mean  [cts/slice]");
+    disp3.SetYTitle("Hist. Sigma [cts/slice]");
+    disp4.SetYTitle("Calc. Mean  [cts/slice]");
+    disp5.SetYTitle("Calc. RMS   [cts/slice]");
+    disp6.SetYTitle("Diff. Mean  [cts/slice]");
+    disp7.SetYTitle("Diff. RMS   [cts/slice]");
+    disp8.SetYTitle("Diff. Mean  [cts/slice]");
+    disp9.SetYTitle("Abs.Diff.RMS [cts/slice]");
+    disp10.SetYTitle("Rel.Diff.RMS [1]");
+
+    //
+    // Display data
+    //
+    if (fDisplayType != kDisplayDataCheck &&  fExtractionType==kFundamental/*fExtractorResolution*/)
+      {
+        TCanvas &c3 = fDisplay->AddTab("Pedestals");
+        c3.Divide(2,3);
+        
+        disp0.CamDraw(c3, 1, 2, 1);
+        disp1.CamDraw(c3, 2, 2, 6);
+        return;
+      }
+
+/*
+    if (fIsUseHists)
+      {
+        
+        TCanvas &c3 = fDisplay->AddTab("Extractor Hist.");
+        c3.Divide(2,3);
+
+        disp2.CamDraw(c3, 1, 2, 1);
+        disp3.CamDraw(c3, 2, 2, 5);
+
+        TCanvas &c4 = fDisplay->AddTab("Extractor Calc.");
+        c4.Divide(2,3);
+        
+        disp4.CamDraw(c4, 1, 2, 1);
+        disp5.CamDraw(c4, 2, 2, 5);
+
+        //TCanvas &c5 = fDisplay->AddTab("Difference Hist.");
+        //c5.Divide(2,3);
+        //
+        //disp6.CamDraw(c5, 1, 2, 1);
+        //disp7.CamDraw(c5, 2, 2, 5);
+
+        TCanvas &c6 = fDisplay->AddTab("Difference Calc.");
+        c6.Divide(2,3);
+        
+        disp8.CamDraw(c6, 1, 2, 1);
+        disp9.CamDraw(c6, 2, 2, 5);
+        return;
+      }
+*/
+    if (fDisplayType == kDisplayDataCheck)
+    {
+
+        TCanvas &c3 = fDisplay->AddTab(fExtractionType!=kFundamental/*fExtractorResolution*/ ? "PedExtrd" : "Ped");
+        c3.Divide(2,3);
+
+        if (fExtractionType==kFundamental)
+            disp0.SetMinMax(fPedestalMin, fPedestalMax);
+        disp1.SetMinMax(fPedRmsMin, fPedRmsMax);
+
+        disp0.CamDraw(c3, 1, 2, 0);  // Don't devide, don't fit
+        disp1.CamDraw(c3, 2, 2, 6);  // Divide, fit
+
+        c3.cd(1);
+        if (fExtractionType==kFundamental)
+            DisplayReferenceLines(disp0, 0);
+
+        c3.cd(2);
+        DisplayReferenceLines(disp1, 1);
+
+        return;
+    }
+
+    if (fExtractionType!=kFundamental/*fExtractorResolution*/)
+    {
+
+          TCanvas &c3 = fDisplay->AddTab(fExtractionType==kWithExtractor?"PedExtrd":"PedRndm");
+          c3.Divide(2,3);
+
+          disp0.CamDraw(c3, 1, 2, 1);  // Don't divide, fit
+          disp1.CamDraw(c3, 2, 2, 6);  // Divide, fit
+
+          TCanvas &c13 = fDisplay->AddTab(fExtractionType==kWithExtractor?"DiffExtrd":"DiffRndm");
+          c13.Divide(2,3);
+
+          disp9.CamDraw(c13,  1, 2, 1);
+          disp10.CamDraw(c13, 2, 2, 1);
+    }
+}
+
+void  MJPedestal::DisplayReferenceLines(const MHCamera &hist, const Int_t what) const
+{
+    MHCamera *cam = dynamic_cast<MHCamera*>(gPad->FindObject(hist.GetName()));
+    if (!cam)
+        return;
+
+  const MGeomCam *geom = cam->GetGeometry();
+
+  const Double_t x = geom->InheritsFrom("MGeomCamMagic") && what ? 397 : cam->GetNbinsX() ;
+
+  TLine line;
+  line.SetLineStyle(kDashed);
+  line.SetLineWidth(3);
+  line.SetLineColor(kBlue);
+  
+  TLegend *leg = new TLegend(0.75,0.75,0.999,0.99);
+  leg->SetBit(kCanDelete);
+
+  if (fExtractionType==kWithExtractorRndm && !(what))
+    {
+      TLine *l0 = line.DrawLine(0,0.,cam->GetNbinsX(),0.);
+      l0->SetBit(kCanDelete);
+      leg->AddEntry(l0, "Reference","l");
+      leg->Draw();
+      return;
+    }
+
+  line.SetLineColor(kBlue);
+  TLine *l1 = line.DrawLine(0, what ? fRefPedRmsGalacticInner : fRefPedGalactic,
+			    x, what ? fRefPedRmsGalacticInner : fRefPedGalactic);
+  l1->SetBit(kCanDelete);  
+  line.SetLineColor(kYellow);
+  TLine *l2 = line.DrawLine(0, what ? fRefPedRmsExtraGalacticInner : fRefPedExtraGalactic,
+			    x, what ? fRefPedRmsExtraGalacticInner : fRefPedExtraGalactic);
+  l2->SetBit(kCanDelete);  
+  line.SetLineColor(kMagenta);
+  TLine *l3 = line.DrawLine(0, what ? fRefPedRmsClosedLidsInner : fRefPedClosedLids,
+			    x, what ? fRefPedRmsClosedLidsInner : fRefPedClosedLids);
+  l3->SetBit(kCanDelete);
+
+  if (geom->InheritsFrom("MGeomCamMagic"))
+    if (what)
+      {
+        const Double_t x2 = cam->GetNbinsX();
+
+        line.SetLineColor(kBlue);
+        line.DrawLine(398, fRefPedRmsGalacticOuter,
+                      x2,  fRefPedRmsGalacticOuter);
+
+        line.SetLineColor(kYellow);
+        line.DrawLine(398, fRefPedRmsExtraGalacticOuter,
+                      x2,  fRefPedRmsExtraGalacticOuter);
+
+        line.SetLineColor(kMagenta);
+        line.DrawLine(398, fRefPedRmsClosedLidsOuter,
+                      x2,  fRefPedRmsClosedLidsOuter);
+      }
+  
+    
+  leg->AddEntry(l1, "Galactic","l");
+  leg->AddEntry(l2, "Extra-Galactic","l");
+  leg->AddEntry(l3, "Closed Lids","l");
+  leg->Draw();
+}
+
+/*
+void  MJPedestal::DisplayOutliers(TH1D *hist) const
+{
+    const Float_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+    const Float_t lolim = mean - 3.5*hist->GetFunction("gaus")->GetParameter(2);
+    const Float_t uplim = mean + 3.5*hist->GetFunction("gaus")->GetParameter(2);
+    const Stat_t  dead  = hist->Integral(0,hist->FindBin(lolim)-1);
+    const Stat_t  noisy = hist->Integral(hist->FindBin(uplim)+1,hist->GetNbinsX()+1);
+
+    TLatex deadtex;
+    deadtex.SetTextSize(0.06);
+    deadtex.DrawLatex(0.1,hist->GetBinContent(hist->GetMaximumBin())/1.1,Form("%3i dead pixels",(Int_t)dead));
+
+    TLatex noisytex;
+    noisytex.SetTextSize(0.06);
+    noisytex.DrawLatex(0.1,hist->GetBinContent(hist->GetMaximumBin())/1.2,Form("%3i noisy pixels",(Int_t)noisy));
+}
+*/
+
+void MJPedestal::FixDataCheckHist(TH1D *hist) const 
+{
+    hist->SetDirectory(NULL);
+    hist->SetStats(0);
+
+    //
+    // set the labels bigger
+    //
+    TAxis *xaxe = hist->GetXaxis();
+    TAxis *yaxe = hist->GetYaxis();
+    
+    xaxe->CenterTitle();
+    yaxe->CenterTitle();    
+    xaxe->SetTitleSize(0.06);
+    yaxe->SetTitleSize(0.06);    
+    xaxe->SetTitleOffset(0.8);
+    yaxe->SetTitleOffset(0.5);    
+    xaxe->SetLabelSize(0.05);
+    yaxe->SetLabelSize(0.05);    
+}
+
+/*
+Bool_t MJPedestal::WriteEventloop(MEvtLoop &evtloop) const
+{
+    if (fOutputPath.IsNull())
+        return kTRUE;
+
+    const TString oname(GetOutputFile());
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile file(oname, fOverwrite?"RECREATE":"NEW", "File created by MJPedestal", 9);
+    if (!file.IsOpen())
+    {
+        *fLog << err << "ERROR - Couldn't open file " << oname << " for writing..." << endl;
+        return kFALSE;
+    }
+
+    if (evtloop.Write(fName)<=0)
+    {
+        *fLog << err << "Unable to write MEvtloop to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+*/
+
+void MJPedestal::SetExtractor(MExtractor* ext)
+{
+    if (ext)
+    {
+        if (fExtractor)
+            delete fExtractor;
+        fExtractor = ext ? (MExtractor*)ext->Clone(ext->GetName()) : NULL;
+    }
+    else
+        fExtractor = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following values from resource file:
+//
+//   PedestalMin
+//   PedestalMax
+//
+//   PedRmsMin
+//   PedRmsMax
+//
+//   RefPedClosedLids
+//   RefPedExtraGalactic
+//   RefPedGalactic
+//
+//   RefPedRmsClosedLidsInner
+//   RefPedRmsExtraGalacticInner
+//   RefPedRmsGalacticInner
+//   RefPedRmsClosedLidsOuter
+//   RefPedRmsExtraGalacticOuter
+//   RefPedRmsGalacticOuter
+//
+void MJPedestal::ReadReferenceFile()
+{
+    TEnv refenv(fReferenceFile);
+    
+    fPedestalMin                 = refenv.GetValue("PedestalMin",fPedestalMin);
+    fPedestalMax                 = refenv.GetValue("PedestalMax",fPedestalMax);
+    fPedRmsMin                   = refenv.GetValue("PedRmsMin",fPedRmsMin);                   
+    fPedRmsMax                   = refenv.GetValue("PedRmsMax",fPedRmsMax);                   
+    fRefPedClosedLids            = refenv.GetValue("RefPedClosedLids",fRefPedClosedLids);            
+    fRefPedExtraGalactic         = refenv.GetValue("RefPedExtraGalactic",fRefPedExtraGalactic);         
+    fRefPedGalactic              = refenv.GetValue("RefPedGalactic",fRefPedGalactic);              
+    fRefPedRmsClosedLidsInner    = refenv.GetValue("RefPedRmsClosedLidsInner",fRefPedRmsClosedLidsInner);    
+    fRefPedRmsExtraGalacticInner = refenv.GetValue("RefPedRmsExtraGalacticInner",fRefPedRmsExtraGalacticInner); 
+    fRefPedRmsGalacticInner      = refenv.GetValue("RefPedRmsGalacticInner",fRefPedRmsGalacticInner);      
+    fRefPedRmsClosedLidsOuter    = refenv.GetValue("RefPedRmsClosedLidsOuter",fRefPedRmsClosedLidsOuter);    
+    fRefPedRmsExtraGalacticOuter = refenv.GetValue("RefPedRmsExtraGalacticOuter",fRefPedRmsExtraGalacticOuter); 
+    fRefPedRmsGalacticOuter      = refenv.GetValue("RefPedRmsGalacticOuter",fRefPedRmsGalacticOuter);      
+}
+
+// --------------------------------------------------------------------------
+//
+// The following resource options are available:
+//
+// Do a datacheck run (read raw-data and enable display)
+//   Prefix.DataCheck:        Yes, No <default>
+//
+// Setup display type
+//   Prefix.Display:          normal <default>, datacheck, none
+//
+// Use cosmic data instead of pedestal data (DatRuns)
+//   Prefix.UseData:          Yes, No <default>
+//
+// Write an output file with pedestals and status-display
+//   Prefix.DisableOutput:    Yes, No <default>
+//
+// Name of a file containing reference values (see ReadReferenceFile)
+//   Prefix.ReferenceFile:    filename
+// (see ReadReferenceFile)
+//
+Bool_t MJPedestal::CheckEnvLocal()
+{
+    if (HasEnv("Display"))
+    {
+        TString type = GetEnv("Display", "normal");
+        type.ToLower();
+        if (type==(TString)"normal")
+            fDisplayType = kDisplayNormal;
+        if (type==(TString)"datacheck")
+            fDisplayType = kDisplayDataCheck;
+        if (type==(TString)"none")
+            fDisplayType = kDisplayNone;
+    }
+
+
+    SetExtractWinLeft (GetEnv("ExtractWinLeft",  fExtractWinLeft ));
+    SetExtractWinRight(GetEnv("ExtractWinRight", fExtractWinRight));
+
+    fMinEvents = (UInt_t)GetEnv("MinEvents", (Int_t)fMinEvents);
+
+    fMinPedestals = (UInt_t)GetEnv("MinPedestals", (Int_t)fMinPedestals);
+    fMaxPedestals = (UInt_t)GetEnv("MaxPedestals", (Int_t)fMaxPedestals);
+
+    fMinCosmics   = (UInt_t)GetEnv("MinCosmics", (Int_t)fMinCosmics);
+    fMaxCosmics   = (UInt_t)GetEnv("MaxCosmics", (Int_t)fMaxCosmics);
+
+    if (!MJCalib::CheckEnvLocal())
+        return kFALSE;
+    
+    if (HasEnv("UseData"))
+        fExtractType = GetEnv("UseData",kFALSE) ? kUseData : kUsePedRun;
+
+    if (fSequence.IsMonteCarlo() && fExtractType==kUseData)
+    {
+        // The reason is, that the standard data files contains empty
+        // (untriggered) events. If we would loop over the default 500
+        // first events of the data file you would calculate the
+        // pedestal from only some single events...
+        *fLog << inf;
+        *fLog << "Sorry, you cannot extract the starting pedestal from the first" << endl;
+        *fLog << "events in your data files... using pedestal file instead.  The" << endl;
+        *fLog << "result should not differ..." << endl;
+        fExtractType = kUsePedRun;
+    }
+
+//    fIsUseHists = GetEnv("UseHists", fIsUseHists);
+
+    SetNoStorage(GetEnv("DisableOutput", IsNoStorage()));
+
+    fDeadPixelCheck = GetEnv("DeadPixelsCheck", fDeadPixelCheck);
+
+    fBadPixelsFile = GetEnv("BadPixelsFile",fBadPixelsFile.Data());
+    fReferenceFile = GetEnv("ReferenceFile",fReferenceFile.Data());
+    ReadReferenceFile();
+
+    // ------------- Do not put simple resource below --------------
+
+    // Setup an environment task
+    MTaskEnv tenv("ExtractSignal");
+    tenv.SetDefault(fExtractor);
+
+    // check the resource file for it
+    if (!CheckEnv(tenv))
+        return kFALSE;
+
+//    if (tenv.ReadEnv(*GetEnv(), GetEnvPrefix()+".ExtractSignal", GetEnvDebug()>2)==kERROR)
+//        return kFALSE;
+
+    // If the resource file didn't change the default we are done
+    if (fExtractor==tenv.GetTask())
+        return kTRUE;
+
+    // If it changed the default check its inheritance...
+    if (!tenv.GetTask()->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << "ERROR: ExtractSignal from resource file doesn't inherit from MExtractor.... abort." << endl;
+        return kFALSE;
+    }
+
+    // ..and store it
+    SetExtractor((MExtractor*)tenv.GetTask());
+
+    return kTRUE;
+}
+
+//---------------------------------------------------------------------------------
+//
+Bool_t MJPedestal::WritePulsePos(TObject *obj) const
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+    const TString name(Form("signal%08d.root", fSequence.GetSequence()));
+
+    TObjArray arr;
+    arr.Add(obj);
+    return WriteContainer(arr, name, fOverwrite?"RECREATE":"NEW");
+}
+
+Int_t MJPedestal::PulsePosCheck(const MParList &plist) const
+{
+    /*
+    if (fIsPixelCheck)
+    {
+        MHPedestalCam *hcam = (MHPedestalCam*)plist.FindObject("MHPedestalCam");
+        if (hcam)
+        {
+            MHPedestalPix &pix1 = (MHPedestalPix&)(*hcam)[fCheckedPixId];
+            pix1.DrawClone("");
+        }
+    }
+    */
+    if (!fIsPulsePosCheck)
+        return kTRUE;
+
+    // FIXME:
+    // The MC cannot run over the first 2000 pedestal events since almost all
+    // events are empty, therefore a pulse pos. check is not possible, either.
+    // For the moment, have to fix the problem hardcoded...
+    //
+    //            MMcEvt *evt = (MMcEvt*)plist.FindObject("MMcEvt");
+    //            const Float_t meanpulsetime = evt->GetFadcTimeJitter();
+    Float_t meanpulsetime  = 4.5;
+    Float_t rmspulsetime   = 1.0;
+
+    MCalibrationPulseTimeCam *cam = NULL;
+    if (!fSequence.IsMonteCarlo())
+    {  /*
+        if (fIsPixelCheck)
+        {
+            MHCalibrationPulseTimeCam *hcam = (MHCalibrationPulseTimeCam*)plist.FindObject("MHCalibrationPulseTimeCam");
+            if (!hcam)
+            {
+                *fLog << err << "MHCalibrationPulseTimeCam not found... abort." << endl;
+                return kFALSE;
+            }
+            hcam->DrawClone();
+            gPad->SaveAs(Form("%s/PulsePosTest_all.root",fPathOut.Data()));
+
+            MHCalibrationPix &pix = (*hcam)[fCheckedPixId];
+            pix.DrawClone();
+            gPad->SaveAs(Form("%s/PulsePosTest_Pixel%04d.root",fPathOut.Data(),fCheckedPixId));
+        }
+        */
+        cam = (MCalibrationPulseTimeCam*)plist.FindObject("MCalibrationPulseTimeCam");
+        if (!cam)
+        {
+            *fLog << err << "MCalibrationPulseTimeCam not found... abort." << endl;
+            return kFALSE;
+        }
+
+        meanpulsetime = cam->GetAverageArea(0).GetHiGainMean();
+        rmspulsetime  = cam->GetAverageArea(0).GetHiGainRms();
+    }
+
+    if (!WritePulsePos(cam))
+        return kFALSE;
+
+    *fLog << all << "Mean pulse time/Avg pos.of maximum (" << (fSequence.IsMonteCarlo()?"MC":"cosmics") << "): ";
+    *fLog << meanpulsetime << "+-" << rmspulsetime << endl;
+
+    MExtractTimeAndCharge *ext = dynamic_cast<MExtractTimeAndCharge*>(fExtractor);
+    if (!ext)
+    {
+        *fLog << warn << "WARNING - no extractor found inheriting from MExtractTimeAndCharge... no pulse position check." << endl;
+        return kTRUE;
+    }
+
+    const Int_t hi0 = ext->GetHiGainFirst();
+    const Int_t lo1 = ext->GetLoGainLast();
+    Int_t hi1 = ext->GetHiGainLast();
+    Int_t lo0 = ext->GetLoGainFirst();
+
+    //
+    // This is for data without lo-gains
+    //
+    const Bool_t haslo = ext->HasLoGain();
+
+    //
+    // Get the ranges for the new extractor setting. The window
+    // size is always rounded to the next higher integer.
+    //
+    const Int_t wshigain = ext->GetWindowSizeHiGain();
+    const Int_t wslogain = ext->GetWindowSizeLoGain();
+
+    //
+    // Here we calculate the end of the lo-gain range
+    // as it is done in MExtractTimeAndCharge
+    //
+    const Double_t poshi  = meanpulsetime;
+    const Double_t poslo  = poshi + ext->GetOffsetLoGain();
+    const Double_t poslo2 = poslo + ext->GetLoGainStartShift();
+
+    //
+    // Do the right side checks range checks
+    //
+    if (poshi+wshigain+fExtractWinRight > hi1-0.5)
+    {
+        *fLog << err;
+        *fLog << "ERROR - Pulse is too much to the right, out of hi-gain range [";
+        *fLog << hi0 << "," << hi1 << "]" << endl;
+        *fLog << endl;
+        return -2;
+    }
+
+    if (haslo && poslo+wslogain+fExtractWinRight > lo1-0.5)
+    {
+        *fLog << err;
+        *fLog << "ERROR - Pulse is too much to the right, out of lo-gain range [";
+        *fLog << lo0 << "," << lo1 << "]" << endl;
+        return -2;
+    }
+
+    //
+    // Do the left side checks range checks
+    //
+    if (poshi-fExtractWinLeft < hi0+0.5)
+    {
+        *fLog << err;
+        *fLog << "ERROR - Pulse is too much to the left, out of hi-gain range [";
+        *fLog << hi0 << "," << hi1 << "]" << endl;
+        return -3;
+    }
+
+    if (haslo && poslo2-fExtractWinLeft < lo0+0.5)
+    {
+        *fLog << warn;
+        *fLog << "WARNING - Pulse is too much to the left, out of lo-gain range [";
+        *fLog << lo0 << "," << lo1 << "]" << endl;
+        *fLog << "Trying to match extraction window and pulse position..." << endl;
+
+        //
+        // Set and store the new ranges
+        //
+        while (poslo2-fExtractWinLeft < lo0+0.5)
+        {
+            hi1--;
+            lo0--;
+
+            if (poshi+wshigain+fExtractWinRight > hi1-0.5)
+            {
+                *fLog << err << "ERROR - No proper extraction window found.... abort." << endl;
+                return -3;
+            }
+        }
+
+        if (lo0<0)
+            lo0=0;
+
+        *fLog << "Changed extraction to hi-gain [" << hi0 << "," << hi1;
+        *fLog << "] and lo-gain [" << lo0 << "," << lo1 << "]" << endl;
+
+        ext->SetRange(hi0, hi1, lo0, lo1);
+    }
+
+    return kTRUE;
+}
+
+Int_t MJPedestal::Process()
+{
+    if (!fSequence.IsValid())
+    {
+	  *fLog << err << "ERROR - Sequence invalid..." << endl;
+	  return kFALSE;
+    }
+
+    // --------------------------------------------------------------------------------
+
+    const TString type = IsUseData() ? "data" : "pedestal";
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate MPedestalCam from " << type << "-runs ";
+    *fLog << fSequence.GetFileName() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    if (!CheckEnv())
+        return kFALSE;
+
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    plist.AddToList(this); // take care of fDisplay!
+
+    MReadMarsFile read("Events");
+    MRawFileRead rawread(NULL);
+    rawread.SetForceMode(); // Ignore broken time-stamps
+
+    MDirIter iter;
+    if (fSequence.IsValid())
+    {
+        const Int_t n0 = IsUseData()
+            ? fSequence.GetRuns(iter, MSequence::kRawDat)
+            : fSequence.GetRuns(iter, MSequence::kRawPed);
+
+        if (n0<=0)
+            return kFALSE;
+    }
+
+    if (!fSequence.IsMonteCarlo())
+    {
+        rawread.AddFiles(iter);
+        tlist.AddToList(&rawread);
+    }
+    else
+    {
+        read.DisableAutoScheme();
+        read.AddFiles(iter);
+	tlist.AddToList(&read);
+    }
+
+    // Setup Tasklist
+    plist.AddToList(&fPedestalCamOut);
+    plist.AddToList(&fBadPixels);
+
+    MGeomApply geomapl;
+    MBadPixelsMerge merge(&fBadPixels);
+
+    MPedCalcPedRun pedcalc;
+    //pedcalc.SetPedestalUpdate(kFALSE);
+
+    MPedCalcFromLoGain pedlogain;
+    pedlogain.SetPedestalUpdate(kFALSE);
+    
+//    MHPedestalCam hpedcam;
+//    hpedcam.SetPedestalsOut(&fPedestalCamOut);
+//    if (fExtractionType != kFundamental)
+//        hpedcam.SetRenorm(kTRUE);
+
+    // To have it in the parlist for MEnv!
+    MHCalibrationPulseTimeCam pulcam;
+    plist.AddToList(&pulcam);
+    MFillH fillpul(&pulcam, "MPedestalSubtractedEvt", "FillPulseTime");
+    fillpul.SetBit(MFillH::kDoNotDisplay);
+
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&merge);
+
+    if (!fPathIn.IsNull())
+    {
+        fExtractor = ReadCalibration();
+        if (!fExtractor)
+            return kFALSE;
+
+        // The requested setup might have been overwritten
+        if (!CheckEnv(*fExtractor))
+            return kFALSE;
+
+        *fLog << all;
+        *fLog << underline << "Signal Extractor found in calibration file and setup:" << endl;
+        fExtractor->Print();
+        *fLog << endl;
+    }
+
+    //
+    // Read bad pixels from outside
+    // 
+    if (!fBadPixelsFile.IsNull())
+    {
+        *fLog << inf << "Excluding: " << fBadPixelsFile << endl;
+        ifstream fin(fBadPixelsFile);
+        fBadPixels.AsciiRead(fin);
+    }
+
+    MTriggerPatternDecode decode;
+    tlist.AddToList(&decode);
+
+    // produce pedestal subtracted raw-data
+    MPedestalSubtract pedsub;
+    if (fExtractor && fExtractionType!=kFundamental)
+        pedsub.SetPedestalCam(&fPedestalCamIn);
+    else
+        pedsub.SetNamePedestalCam(""); // Only copy hi- and lo-gain together!
+    tlist.AddToList(&pedsub);
+
+    // ----------------------------------------------------------------
+    //  Setup filter for pulse position extraction and its extraction
+
+    // This will make that for data with version less than 5, where
+    // trigger patterns were not yet correct, all the events in the real
+    // data file will be processed. In any case there are no interleaved
+    // calibration events in such data, so this is fine.
+    // The selection is done with the trigger bits before prescaling
+    // Extract pulse position from Lvl1 events.
+    MFTriggerPattern fcos("SelectCosmics");
+    fcos.SetDefault(kTRUE);
+    fcos.DenyAll();
+    fcos.RequireTriggerLvl1();
+    fcos.AllowTriggerLvl2();
+    fcos.AllowSumTrigger();
+
+    // Number of events filled into the histogram presenting the
+    // trigger area
+    MFDataMember filterc("MHCalibrationPulseTimeCam.GetNumEvents", '<', fMaxCosmics, "LimitNumCosmics");
+
+    // Combine both filters
+    MFilterList flistc("&&", "FilterCosmics");
+    flistc.AddToList(&fcos);
+
+    // For the case the pulse positon check is switched on
+    // compile the tasklist accordingly
+    // FIXME: MUX Monte Carlos?!??
+    if (fIsPulsePosCheck)
+    {
+        flistc.AddToList(&filterc);
+        fillpul.SetFilter(&flistc);
+
+	tlist.AddToList(&flistc);
+        tlist.AddToList(&fillpul);
+    }
+
+    //MFillH fillC("MHPedestalCor", "MPedestalSubtractedEvt", "FillAcor");
+    //fillC.SetNameTab("Acor");
+    //if (fExtractor && fExtractionType==kWithExtractorRndm)
+    //    tlist.AddToList(&fillC);
+
+    // ------------------------------------------------------------
+    //  Setup filter for pedestal extraction
+    MFTriggerPattern ftp2("SelectPedestals");
+    ftp2.SetDefault(kTRUE);
+    ftp2.DenyAll();
+    ftp2.RequirePedestal();
+
+    // Limit number of events from which a pedestal is extracted
+    MFDataMember filterp(Form("%s.fNumEvents", fPedestalCamOut.GetName()), '<', fMaxPedestals, "LimitNumPedestal");
+
+    // Combine both filters together
+    MFilterList flistp("&&", "FilterPedestal");
+    // If data is not MC and has no lo-gains select pedestals from trigger pattern
+    if (!fSequence.IsMonteCarlo() && !(fExtractor && fExtractor->HasLoGain()))
+        flistp.AddToList(&ftp2);
+    if (fMaxPedestals>0)
+        flistp.AddToList(&filterp);
+
+    // ------------------------------------------------------------
+    //  Setup pedestal extraction
+    MTaskEnv taskenv("ExtractPedestal");
+
+    taskenv.SetDefault(fExtractType==kUsePedRun ?
+                       static_cast<MTask*>(&pedcalc) :
+                       static_cast<MTask*>(&pedlogain));
+
+    taskenv.SetFilter(&flistp);
+    tlist.AddToList(&flistp);
+    tlist.AddToList(&taskenv);
+
+    // ------------------------------------------------------------
+    //  Setup a filter which defines when the loop is stopped
+    MFilterList flist("||");
+    flist.SetInverted();
+    if (fMaxPedestals>0)
+        flist.AddToList(&filterp);
+    if (fIsPulsePosCheck && fMaxCosmics>0)
+        flist.AddToList(&filterc);
+
+    MContinue stop(&flist, "Stop");
+    stop.SetRc(kFALSE);
+    if (flist.GetNumEntries()>0)
+        tlist.AddToList(&stop);
+
+/*
+    if (fIsUseHists && fExtractor)
+      {
+        if (fExtractor->InheritsFrom("MExtractTimeAndCharge"))
+          {
+              if (fExtractionType!=kFundamental)
+              {
+                  const MExtractTimeAndCharge &e = *static_cast<MExtractTimeAndCharge*>(fExtractor);
+                  hpedcam.SetFitStart(-5*e.GetWindowSizeHiGain());
+              }
+              else
+                  hpedcam.SetFitStart(10.);
+          }
+        
+        plist.AddToList(&hpedcam);
+    }
+ */
+    pedcalc.SetPedestalsOut(&fPedestalCamOut);
+    pedlogain.SetPedestalsOut(&fPedestalCamOut);
+
+    // kFundamental
+    if (fExtractor)
+    {
+        if (fExtractionType!=kFundamental)
+        {
+            pedcalc.SetRandomCalculation(fExtractionType==kWithExtractorRndm);
+            pedlogain.SetRandomCalculation(fExtractionType==kWithExtractorRndm);
+
+            pedcalc.SetExtractor((MExtractTimeAndCharge*)fExtractor);
+            pedlogain.SetExtractor((MExtractTimeAndCharge*)fExtractor);
+        }
+        else
+        {
+            pedcalc.SetRangeFromExtractor(*fExtractor);
+            pedlogain.SetRangeFromExtractor(*fExtractor);
+        }
+
+        if (!fExtractor->InheritsFrom("MExtractTimeAndCharge") && fExtractionType!=kFundamental)
+        {
+            *fLog << inf;
+            *fLog << "Signal extractor doesn't inherit from MExtractTimeAndCharge..." << endl;
+            *fLog << " --> falling back to fundamental pedestal extraction." << endl;
+            fExtractionType=kFundamental;
+        }
+    }
+    else
+    {
+        *fLog << warn << GetDescriptor() << ": WARNING - No extractor has been handed over! " << endl;
+        *fLog << "Taking default window for pedestal extraction. The calculated pedestal  RMS" << endl;
+        *fLog << "will probably not match with future pedestal RMS' from different extraction" << endl;
+        *fLog << "windows." << endl;
+    }
+
+
+    /*
+    MHCamEvent evt0(0, "Ped",    "Pedestal;;P [cnts/sl]");
+    MHCamEvent evt1(2, "PedRms", "Pedestal RMS;;\\sigma_{p} [cnts/sl]");
+
+    MFillH fill0(&evt0, &fPedestalCamOut, "FillPedestal");
+    MFillH fill1(&evt1, &fPedestalCamOut, "FillPedRms");
+
+    tlist.AddToList(&fill0);
+    tlist.AddToList(&fill1);
+    */
+
+    //
+    // Execute the eventloop
+    //
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    //    if (!WriteEventloop(evtloop))
+    //        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    if (taskenv.GetNumExecutions()<fMinEvents)
+    {
+        *fLog << err << GetDescriptor() << ": Failed. Less (" << taskenv.GetNumExecutions() << ") than the required " << fMinEvents << " pedestal events extracted." << endl;
+        return kFALSE;
+    }
+
+    if (fIsPulsePosCheck && pulcam.GetNumEvents()<fMinCosmics)
+    {
+        *fLog << err << GetDescriptor() << ": Failed. Less (" << pulcam.GetNumEvents() << ") than the required " << fMinCosmics << " cosmics evts processed." << endl;
+        return kFALSE;
+    }
+
+    if (fPedestalCamOut.GetNumEvents()<fMinPedestals)
+    {
+        *fLog << err << GetDescriptor() << ": Failed. Less (" << fPedestalCamOut.GetNumEvents() << ") than the required " << fMinPedestals << " pedestal evts processed." << endl;
+        return kFALSE;
+    }
+
+    if (fDeadPixelCheck)
+    {
+        MBadPixelsCalc calc;
+        calc.SetPedestalLevelVarianceLo(4.5);
+        calc.SetPedestalLevelVarianceHi();
+        calc.SetPedestalLevel();
+        if (!CheckEnv(calc))
+            return kFALSE;
+        calc.SetGeomCam(dynamic_cast<MGeomCam*>(plist.FindObject("MGeomCam")));
+        if (!calc.CheckPedestalRms(fBadPixels, fPedestalCamOut))
+        {
+            *fLog << err << "ERROR - MBadPixelsCalc::CheckPedestalRms failed...." << endl;
+            return kFALSE;
+        }
+    }
+
+    if (fDisplayType!=kDisplayNone)
+        DisplayResult(plist);
+
+    //    if (!WriteResult())
+    //        return kFALSE;
+
+    const Int_t rc = PulsePosCheck(plist);
+    if (rc<1)
+        return rc;
+
+    *fLog << all << GetDescriptor() << ": Done." << endl << endl << endl;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJPedestal.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJPedestal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJPedestal.h	(revision 17960)
@@ -0,0 +1,141 @@
+#ifndef MARS_MJPedestal
+#define MARS_MJPedestal
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+#ifndef MARS_MPedestalCam
+#include "MPedestalCam.h"
+#endif
+#ifndef MARS_MHPedestalCam
+#include "MHPedestalCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class TCanvas;
+class MParList;
+class MHCamera;
+class TH1D;
+class MExtractor;
+class MExtractPedestal;
+class MEvtLoop;
+
+class MJPedestal : public MJCalib
+{
+private:
+    static const TString  fgReferenceFile;    //! default for fReferenceFile ("pedestalref.rc")
+    static const TString  fgBadPixelsFile;    //! default for fBadPixelsFile ("badpixels_0_559.rc")
+
+    static const Float_t  fgExtractWinLeft;   //! default for fExtractWinLeft  (now set to: 2.5)
+    static const Float_t  fgExtractWinRight;  //! default for fExtractWinRight (now set to: 6.0)
+
+    Axis_t fPedestalMin;                     //! Minimum Axis value for pedestal datacheck display
+    Axis_t fPedestalMax;                     //! Maximum Axis value for pedestal datacheck display
+    Axis_t fPedRmsMin;                       //! Minimum Axis value for ped. RMS datacheck display
+    Axis_t fPedRmsMax;                       //! Maximum Axis value for ped. RMS datacheck display
+				             
+    Float_t fRefPedClosedLids;               //! Reference line pedestal for closed lids run
+    Float_t fRefPedExtraGalactic;            //! Reference line pedestal for extragalactic source
+    Float_t fRefPedGalactic;                 //! Reference line pedestal for galactic source
+
+    Float_t fRefPedRmsClosedLidsInner;       //! Ref. line ped. RMS for closed lids run - inner pixels
+    Float_t fRefPedRmsExtraGalacticInner;    //! Ref. line ped. RMS for extragalactic source - inner pixels
+    Float_t fRefPedRmsGalacticInner;         //! Ref. line ped. RMS for galactic source - inner pixels
+
+    Float_t fRefPedRmsClosedLidsOuter;       //! Ref. line ped. RMS for closed lids run - outer pixels
+    Float_t fRefPedRmsExtraGalacticOuter;    //! Ref. line ped. RMS for extragalactic source - outer pixels
+    Float_t fRefPedRmsGalacticOuter;         //! Ref. line ped. RMS for galactic source - outer pixels
+
+    Float_t fExtractWinLeft;                 //  Number of FADC slices to extract leftward from mean pulse pos.  
+    Float_t fExtractWinRight;                //  Number of FADC slices to extract rightward from mean pulse pos.
+
+    TString fReferenceFile;                  // File name containing the reference values
+    TString fBadPixelsFile;                  // File name containing the bad pixels excluded beforehand 
+
+    MExtractor *fExtractor;                  // Signal extractor, used to find the nr. of used FADC slices
+
+    MPedestalCam  fPedestalCamIn;            // Handed over pedestal results
+    MPedestalCam  fPedestalCamOut;           // Created pedestal results
+    MBadPixelsCam fBadPixels;                // Bad Pixels
+    //    MHPedestalCam fPedestalHist;             // Histogramming pedestal Camera
+
+    enum Display_t { kDisplayNone, kDisplayNormal, kDisplayDataCheck }; // Possible Display types
+    Display_t fDisplayType;                  // Chosen Display type
+
+    enum Extract_t { kUseData, kUsePedRun }; // Possible flags for the extraction of the pedestal
+    Extract_t fExtractType;                  // Chosen extractor type
+
+    enum Extraction { kFundamental, kWithExtractorRndm, kWithExtractor };
+    Int_t fExtractionType;                   // Flag if the extractor is used to calculate the pedestals
+
+//    Bool_t fIsUseHists;                      // Switch on histogramming or not
+    Bool_t fDeadPixelCheck;                  // Should the dead pixel check be done?
+
+    UInt_t  fMinEvents;                      // Minimum number of events
+    UInt_t  fMinPedestals;                   // Minimum number of events
+    UInt_t  fMaxPedestals;                   // Maximum number of events for pedestal extraction
+    UInt_t  fMinCosmics;                     // Minimum number of events
+    UInt_t  fMaxCosmics;                     // Maximum number of events for pulse    extraction
+
+    MExtractor *ReadCalibration();
+    Bool_t ReadPedestalCam();
+    //Bool_t WriteResult();
+    Bool_t WritePulsePos(TObject *obj) const;
+    //Bool_t WriteEventloop(MEvtLoop &evtloop) const;
+
+    void   DisplayResult(const MParList &plist);
+    void   DisplayReferenceLines(const MHCamera &hist, const Int_t what) const;
+    //void   DisplayOutliers(TH1D *hist) const;
+    void   FixDataCheckHist(TH1D *hist) const;
+    Int_t  PulsePosCheck(const MParList &plist) const;
+
+    Bool_t CheckEnvLocal();
+
+    const char*  GetOutputFileName() const;
+
+    void ReadReferenceFile();
+
+    Bool_t WriteExtractor() const;
+
+public:
+    MJPedestal(const char *name=NULL, const char *title=NULL);
+    ~MJPedestal();
+
+    MPedestalCam &GetPedestalCam()            { return fPedestalCamOut; }
+    const MBadPixelsCam &GetBadPixels() const { return fBadPixels;   }
+
+    //    const MHPedestalCam &GetPedestalHist() const { return fPedestalHist;  }
+
+    const Bool_t IsUseData() const { return fExtractType == kUseData; }
+
+    Int_t Process();
+
+    void SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+    void SetPedestals(const MPedestalCam  &ped) { ped.Copy(fPedestalCamIn); }
+    void SetExtractor(MExtractor* ext);
+    void SetUseData()                           { fExtractType = kUseData;   }
+//    void SetUseHists( const Bool_t b=kTRUE)     { fIsUseHists = b;  }
+    void SetDeadPixelCheck(const Bool_t b=kTRUE) { fDeadPixelCheck = b; }
+    void SetUsePedRun()                         { fExtractType = kUsePedRun; }
+    void SetDataCheckDisplay()                  { fDisplayType = kDisplayDataCheck; }
+    void SetNormalDisplay()                     { fDisplayType = kDisplayNormal;    }
+    void SetNoDisplay()                         { fDisplayType = kDisplayNone; }
+
+    void SetExtractionFundamental()       { fExtractionType=kFundamental;       /*fPedestalCamOut.SetName("MPedestalFundamental");*/   }
+    void SetExtractionWithExtractorRndm() { fExtractionType=kWithExtractorRndm; /*fPedestalCamOut.SetName("MPedestalExtractorRndm");*/ }
+    void SetExtractionWithExtractor()     { fExtractionType=kWithExtractor;     /*fPedestalCamOut.SetName("MPedestalExtractor");*/     }
+
+    void SetReferenceFile( const TString ref=fgReferenceFile ) { fReferenceFile = ref; }
+    void SetBadPixelsFile( const TString ref=fgBadPixelsFile ) { fBadPixelsFile = ref; }
+
+    void SetExtractWinLeft ( const Float_t f=fgExtractWinLeft  ) { fExtractWinLeft  = f; }
+    void SetExtractWinRight( const Float_t f=fgExtractWinRight ) { fExtractWinRight = f; }    
+
+    MExtractor *GetExtractor() const { return fExtractor; }
+
+    ClassDef(MJPedestal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJSimulation.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJSimulation.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJSimulation.cc	(revision 17960)
@@ -0,0 +1,1039 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJSimulation
+//
+//
+// Force reading a corsika file even if the footer (RUNE-section) is missing
+// by setting fForceMode to kTRUE or from the resource file by
+//
+//    ForceMode: Yes
+//
+//
+// To switch off the simulation of the camera electronics, use:
+//
+//    Camera: Off
+//
+// Note, that the border of the camera and the propertied of the cones
+// are still simulated (simply because it is fast). Furthermore, this
+// switches off the trigger for the output, i.e. all data which deposits
+// at least one photon in at least one pixel is written to the output file.
+//
+//
+// In case of a pedestal or calibration run the artificial trigger can
+// be "switched off" and the cosmics trrigger "switched on" by setting
+// fForceTrigger to kTRUE or from the resource file by
+//
+//    ForceTrigger: Yes
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJSimulation.h"
+
+#include <TEnv.h>
+#include <TCanvas.h>
+
+// Core
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+#include "MDirIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+// Tasks
+#include "MCorsikaRead.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MGeomApply.h"
+#include "MParameterCalc.h"
+#include "MHillasCalc.h"
+#include "MImgCleanStd.h"
+#include "MWriteRootFile.h"
+#include "MWriteFitsFile.h"
+
+#include "MSimMMCS.h"
+#include "MSimAbsorption.h"
+#include "MSimAtmosphere.h"
+#include "MSimReflector.h"
+#include "MSimPointingPos.h"
+#include "MSimPSF.h"
+#include "MSimGeomCam.h"
+#include "MSimSignalCam.h"
+#include "MSimAPD.h"
+#include "MSimExcessNoise.h"
+#include "MSimCamera.h"
+#include "MSimTrigger.h"
+#include "MSimReadout.h"
+#include "MSimRandomPhotons.h"
+#include "MSimBundlePhotons.h"
+#include "MSimCalibrationSignal.h"
+
+// Histograms
+#include "MBinning.h"
+
+#include "MHn.h"
+#include "MHCamera.h"
+#include "MHCamEvent.h"
+#include "MHPhotonEvent.h"
+
+// Container
+#include "MRawRunHeader.h"
+#include "MParameters.h"
+#include "MReflector.h"
+#include "MParEnv.h"
+#include "MSpline3.h"
+#include "MParSpline.h"
+#include "MGeomCam.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MJSimulation);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fRuns to 0, fExtractor to NULL, fDataCheck to kFALSE
+//
+MJSimulation::MJSimulation(const char *name, const char *title)
+    : fForceMode(kFALSE), fCamera(kTRUE), fForceTrigger(kFALSE),
+    fWriteFitsFile(kFALSE), fOperationMode(kModeData), fRunNumber(-1)
+{
+    fName  = name  ? name  : "MJSimulation";
+    fTitle = title ? title : "Standard analysis and reconstruction";
+}
+
+Bool_t MJSimulation::CheckEnvLocal()
+{
+    fForceMode    = GetEnv("ForceMode",    fForceMode);
+    fForceTrigger = GetEnv("ForceTrigger", fForceTrigger);
+    fCamera       = GetEnv("Camera",       fCamera);
+
+    return kTRUE;
+}
+/*
+TString MJSimulation::GetOutFile(const MSequence &seq) const
+{
+    return seq.IsValid() ? Form("ceres%08d.root", seq.GetSequence()) : "ceres.root";
+}
+*/
+
+Bool_t MJSimulation::WriteResult(const MParList &plist, const MSequence &seq, Int_t num)
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    TObjArray cont;
+    cont.Add(const_cast<TEnv*>(GetEnv()));
+    if (seq.IsValid())
+        cont.Add(const_cast<MSequence*>(&seq));
+
+    cont.Add(plist.FindObject("PulseShape"));
+    cont.Add(plist.FindObject("Reflector"));
+    cont.Add(plist.FindObject("MGeomCam"));
+    cont.Add(plist.FindObject("GeomCones"));
+
+    TNamed cmdline("CommandLine", fCommandLine.Data());
+    cont.Add(&cmdline);
+
+    if (fDisplay)
+    {
+        TString title = "--  Ceres";
+        if (seq.IsValid())
+        {
+            title += ": ";
+            title += seq.GetSequence();
+        }
+        title += "  --";
+        fDisplay->SetTitle("Ceres", kFALSE);
+
+        cont.Add(fDisplay);
+    }
+
+    const TString name =  Form("ceres%08d.root", num);
+    return WriteContainer(cont, name, "RECREATE");
+}
+
+void MJSimulation::SetupHist(MHn &hist) const
+{
+    hist.AddHist("MCorsikaEvtHeader.fTotalEnergy");
+    hist.InitName("Energy");
+    hist.InitTitle("Energy;E [GeV]");
+    hist.SetLog(kTRUE, kTRUE, kFALSE);
+
+    hist.AddHist("MPhotonEvent.GetNumExternal");
+    hist.InitName("Size");
+    hist.InitTitle("Size;S [#]");
+    hist.SetLog(kTRUE, kTRUE, kFALSE);
+
+    /*
+     hist.AddHist("-MCorsikaEvtHeader.fX/100","-MCorsikaEvtHeader.fY/100");
+     hist.SetDrawOption("colz");
+     hist.InitName("Impact;Impact;Impact");
+     hist.InitTitle("Impact;West <--> East [m];South <--> North [m]");
+     hist.SetAutoRange();
+     */
+
+    hist.AddHist("MCorsikaEvtHeader.GetImpact/100");
+    hist.InitName("Impact");
+    hist.InitTitle("Impact;Impact [m]");
+    hist.SetAutoRange();
+
+    hist.AddHist("MCorsikaEvtHeader.fFirstInteractionHeight/100000");
+    hist.InitName("Height");
+    hist.InitTitle("FirstInteractionHeight;h [km]");
+
+    hist.AddHist("(MCorsikaEvtHeader.fAz+MCorsikaRunHeader.fMagneticFieldAz)*TMath::RadToDeg()", "MCorsikaEvtHeader.fZd*TMath::RadToDeg()");
+    hist.InitName("SkyOrigin;Az;Zd");
+    hist.InitTitle("Sky Origin;Az [\\circ];Zd [\\circ]");
+    hist.SetDrawOption("colz");
+    hist.SetAutoRange();
+
+    hist.AddHist("IncidentAngle.fVal");
+    hist.InitName("ViewCone");
+    hist.InitTitle("Incident Angle;\\alpha [\\circ]");
+}
+
+template<class T>
+void MJSimulation::SetupCommonFileStructure(T &write) const
+{
+    // Common run headers
+    write.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE, 1);
+    write.AddContainer("MCorsikaRunHeader",   "RunHeaders", kFALSE, 1);
+    write.AddContainer("MRawRunHeader",       "RunHeaders", kTRUE,  1);
+    write.AddContainer("MGeomCam",            "RunHeaders", kTRUE,  1);
+    write.AddContainer("MMcRunHeader",        "RunHeaders", kTRUE,  1);
+
+    // Common events
+    write.AddContainer("MCorsikaEvtHeader",   "Events", kFALSE);
+    write.AddContainer("MRawEvtHeader",       "Events");
+    write.AddContainer("MMcEvt",              "Events", kFALSE);
+    write.AddContainer("IncidentAngle",       "Events", kFALSE);
+    write.AddContainer("MPointingPos",        "Events", kFALSE);
+}
+
+void MJSimulation::SetupHeaderKeys(MWriteFitsFile &write,MRawRunHeader &header) const
+{
+    const MTime now(-1);
+    write.SetHeaderKey("ISMC",true,"Bool if File is Montecarlo File");
+    write.SetHeaderKey("TELESCOP", "FACT", "");
+    write.SetHeaderKey("PACKAGE", "MARS Cheobs", "");
+    write.SetHeaderKey("VERSION", "1.0", "");
+    write.SetHeaderKey("CREATOR", "Ceres", "");
+    write.SetHeaderKey("EXTREL", 1., "");
+    write.SetHeaderKey("COMPILED", __DATE__" " __TIME__, "");
+    write.SetHeaderKey("REVISION", "0", "");
+    write.SetHeaderKey("ORIGIN", "FACT", "");
+    write.SetHeaderKey("DATE", now.GetStringFmt("%Y-%m-%dT%H:%M:%S").Data(), "");
+    write.SetHeaderKey("NIGHT", now.GetNightAsInt(), "");
+    write.SetHeaderKey("TIMESYS", "UTC", "");
+    write.SetHeaderKey("TIMEUNIT", "d", "");
+    write.SetHeaderKey("MJDREF", 40587, "");
+    //write.SetHeaderKey("BLDVER", 1, "");
+    write.SetHeaderKey("RUNID", header.GetRunNumber(), "");
+    write.SetHeaderKey("NBOARD", 40, "");
+    write.SetHeaderKey("NPIX", header.GetNumPixel(), "");
+    write.SetHeaderKey("NROI", header.GetNumSamplesHiGain(), "");
+    write.SetHeaderKey("NROITM", 0, "");
+    write.SetHeaderKey("TMSHIFT", 0, "");
+    write.SetHeaderKey("CAMERA", "MGeomCamFACT", "");
+    write.SetHeaderKey("DAQ", "DRS4", "");
+
+    // FTemme: ADCRANGE and ADC have to be calculated, using the values for
+    // the fadctype.
+//    write.SetHeaderKey("ADCRANGE", 2000, "Dynamic range in mV");
+//    write.SetHeaderKey("ADC", 12, "Resolution in bits");
+
+    switch(header.GetRunType())
+    {
+    case MRawRunHeader::kRTData|MRawRunHeader::kRTMonteCarlo:
+        write.SetHeaderKey("RUNTYPE", "data", "");
+        break;
+    case MRawRunHeader::kRTPedestal|MRawRunHeader::kRTMonteCarlo:
+        write.SetHeaderKey("RUNTYPE", "pedestal", "");
+        break;
+    case MRawRunHeader::kRTCalibration|MRawRunHeader::kRTMonteCarlo:
+        write.SetHeaderKey("RUNTYPE", "calibration", "");
+        break;
+    }
+//    write.SetHeaderKey("ID", 777, "Board  0: Board ID");
+//    write.SetHeaderKey("FMVER", 532, "Board  0: Firmware Version");
+//    write.SetHeaderKey("DNA", "0", "");
+//    write.SetHeaderKey("BOARD", 0, "");
+//    write.SetHeaderKey("PRESC", 40, "");
+//    write.SetHeaderKey("PHASE", 0, "");
+//    write.SetHeaderKey("DAC0", 26500, "");
+//    write.SetHeaderKey("DAC1", 0, "");
+//    write.SetHeaderKey("DAC2", 0, "");
+//    write.SetHeaderKey("DAC3", 0, "");
+//    write.SetHeaderKey("DAC4", 28800, "");
+//    write.SetHeaderKey("DAC5", 28800, "");
+//    write.SetHeaderKey("DAC6", 28800, "");
+//    write.SetHeaderKey("DAC7", 28800, "");
+    write.SetHeaderKey("REFCLK", header.GetFreqSampling(), "");
+    write.SetHeaderKey("DRSCALIB", false, "");
+//    write.SetHeaderKey("TSTARTI", 0, "");
+//    write.SetHeaderKey("TSTARTF", 0., "");
+//    write.SetHeaderKey("TSTOPI", 0, "");
+//    write.SetHeaderKey("TSTOPF", 0., "");
+//    write.SetHeaderKey("DATE-OBS", "1970-01-01T00:00:00", "");
+//    write.SetHeaderKey("DATE-END", "1970-01-01T00:00:00", "");
+//    write.SetHeaderKey("NTRG", 0, "");
+//    write.SetHeaderKey("NTRGPED", 0, "");
+//    write.SetHeaderKey("NTRGLPE", 0, "");
+//    write.SetHeaderKey("NTRGTIM", 0, "");
+//    write.SetHeaderKey("NTRGLPI", 0, "");
+//    write.SetHeaderKey("NTRGEXT1", 0, "");
+//    write.SetHeaderKey("NTRGEXT2", 0, "");
+//    write.SetHeaderKey("NTRGMISC", 0, "");
+}
+
+void MJSimulation::SetupVetoColumns(MWriteFitsFile &write) const
+{
+    write.VetoColumn("MParameterD.fVal");
+    write.VetoColumn("MRawEvtData.fLoGainPixId");
+    write.VetoColumn("MRawEvtData.fLoGainFadcSamples");
+    write.VetoColumn("MRawEvtData.fABFlags");
+    write.VetoColumn("MRawEvtHeader.fNumTrigLvl2");
+    //write.VetoColumn("MRawEvtHeader.fTrigPattern");
+    write.VetoColumn("MRawEvtHeader.fNumLoGainOn");
+}
+
+Bool_t MJSimulation::Process(const MArgs &args, const MSequence &seq)
+{
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+
+    if (!CheckEnv())
+        return kFALSE;
+
+    if (seq.IsValid())
+        *fLog << fSequence.GetFileName() << endl;
+    else
+        *fLog << "Input: " << args.GetNumArguments() << "-files" << endl;
+    *fLog << endl;
+
+    MDirIter iter;
+    if (seq.IsValid() && seq.GetRuns(iter, MSequence::kCorsika)<=0)
+    {
+        *fLog << err << "ERROR - Sequence valid but without files." << endl;
+        return kFALSE;
+    }
+
+    // --------------------------------------------------------------------------------
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+    // setup TaskList
+    MTaskList tasks;
+    plist.AddToList(&tasks);
+    // --------------------------------------------------------------------------------
+
+    // FIXME: Allow empty GeomCones!
+    MParEnv env0("Reflector");
+    MParEnv env1("GeomCones");
+    MParEnv env2("MGeomCam");
+    env0.SetClassName("MReflector");
+    env1.SetClassName("MGeomCam");
+    env2.SetClassName("MGeomCam");
+    plist.AddToList(&env0);
+    plist.AddToList(&env1);
+    plist.AddToList(&env2);
+
+    plist.FindCreateObj("MPedPhotCam", "MPedPhotFromExtractorRndm");
+
+    MParSpline shape("PulseShape");
+    plist.AddToList(&shape);
+
+    // *** FIXME *** FIXME *** FIXME ***
+    plist.FindCreateObj("MMcRunHeader");
+
+    MRawRunHeader header;
+    header.SetValidMagicNumber();
+    //header.InitFadcType(3);
+
+    switch (fOperationMode)
+    {
+    case kModeData:
+        header.SetRunType(MRawRunHeader::kRTMonteCarlo|MRawRunHeader::kRTData);
+        header.SetRunInfo(0, fRunNumber<0 ? 3 : fRunNumber);
+        break;
+
+    case kModePed:
+        header.SetRunType(MRawRunHeader::kRTMonteCarlo|MRawRunHeader::kRTPedestal);
+        header.SetSourceInfo("Pedestal");
+        header.SetRunInfo(0, fRunNumber<0 ? 1 : fRunNumber);
+        break;
+
+    case kModeCal:
+        header.SetRunType(MRawRunHeader::kRTMonteCarlo|MRawRunHeader::kRTCalibration);
+        header.SetSourceInfo("Calibration");
+        header.SetRunInfo(0, fRunNumber<0 ? 2 : fRunNumber);
+        break;
+
+    case kModePointRun:
+        header.SetRunType(MRawRunHeader::kRTMonteCarlo|MRawRunHeader::kRTPointRun);
+        header.SetRunInfo(0, fRunNumber<0 ? 0 : fRunNumber);
+        break;
+    }
+
+    // FIXME: Move to MSimPointingPos, MSimCalibrationSignal
+    //        Can we use this as input for MSimPointingPos?
+    header.SetObservation("On", "MonteCarlo");
+    plist.AddToList(&header);
+
+    MCorsikaRead read;
+    read.SetForceMode(fForceMode);
+
+    if (!seq.IsValid())
+    {
+        for (int i=0; i<args.GetNumArguments(); i++)
+            read.AddFile(args.GetArgumentStr(i));
+    }
+    else
+        read.AddFiles(iter);
+
+    MContinue precut("", "PreCut");
+    precut.IsInverted();
+    precut.SetAllowEmpty();
+
+    MSimMMCS simmmcs;
+
+    MParSpline splinepde("PhotonDetectionEfficiency");
+    MParSpline splinemirror("MirrorReflectivity");
+    MParSpline splinecones("ConesAngularAcceptance");
+    MParSpline splinecones2("ConesTransmission");
+    plist.AddToList(&splinepde);
+    plist.AddToList(&splinemirror);
+    plist.AddToList(&splinecones);
+    plist.AddToList(&splinecones2);
+
+    const TString sin2 = "sin(MCorsikaEvtHeader.fZd)*sin(MCorsikaRunHeader.fZdMin*TMath::DegToRad())";
+    const TString cos2 = "cos(MCorsikaEvtHeader.fZd)*cos(MCorsikaRunHeader.fZdMin*TMath::DegToRad())";
+    const TString cos  = "cos(MCorsikaEvtHeader.fAz-MCorsikaRunHeader.fAzMin*TMath::DegToRad())";
+
+    const TString form = "acos("+sin2+"*"+cos+"+"+cos2+")*TMath::RadToDeg()";
+
+    MParameterCalc calcangle(form, "CalcIncidentAngle");
+    calcangle.SetNameParameter("IncidentAngle");
+
+    MSimAtmosphere simatm;
+    MSimAbsorption absapd("SimPhotonDetectionEfficiency");
+    MSimAbsorption absmir("SimMirrorReflectivity");
+    MSimAbsorption cones("SimConesAngularAcceptance");
+    MSimAbsorption cones2("SimConesTransmission");
+    absapd.SetParName("PhotonDetectionEfficiency");
+    absmir.SetParName("MirrorReflectivity");
+    cones.SetParName("ConesAngularAcceptance");
+    cones.SetUseTheta();
+    cones2.SetParName("ConesTransmission");
+ 
+    MSimPointingPos pointing;
+
+    MSimReflector reflect;
+    reflect.SetNameGeomCam("GeomCones");
+    reflect.SetNameReflector("Reflector");
+//  MSimStarField stars;
+
+    MContinue cont1("MPhotonEvent.GetNumPhotons<1", "ContEmpty1");
+    MContinue cont2("MPhotonEvent.GetNumPhotons<1", "ContEmpty2");
+    MContinue cont3("MPhotonEvent.GetNumPhotons<2", "ContEmpty3");
+    cont1.SetAllowEmpty();
+    cont2.SetAllowEmpty();
+    cont3.SetAllowEmpty();
+
+    // -------------------------------------------------------------------
+
+    MBinning binse( 120,     1,  1000000, "BinningEnergy",    "log");
+    MBinning binsth( 60,   0.9,   900000, "BinningThreshold", "log");
+    MBinning binsee( 36,   0.9,   900000, "BinningEnergyEst", "log");
+    MBinning binss( 100,     1, 10000000, "BinningSize",      "log");
+//    MBinning binsi( 100,  -500,      500, "BinningImpact");
+    MBinning binsi(  32,     0,      800, "BinningImpact");
+    MBinning binsh( 150,     0,       50, "BinningHeight");
+    MBinning binsaz(720,  -360,      360, "BinningAz");
+    MBinning binszd( 70,     0,       70, "BinningZd");
+    MBinning binsvc( 35,     0,        7, "BinningViewCone");
+    MBinning binsel(150,     0,       50, "BinningTotLength");
+    MBinning binsew(150,     0,       15, "BinningMedLength");
+    MBinning binsd("BinningDistC");
+    MBinning binsd0("BinningDist");
+    MBinning binstr("BinningTrigPos");
+
+    plist.AddToList(&binsee);
+    plist.AddToList(&binse);
+    plist.AddToList(&binsth);
+    plist.AddToList(&binss);
+    plist.AddToList(&binsi);
+    plist.AddToList(&binsh);
+    plist.AddToList(&binszd);
+    plist.AddToList(&binsaz);
+    plist.AddToList(&binsvc);
+    plist.AddToList(&binsel);
+    plist.AddToList(&binsew);
+    plist.AddToList(&binstr);
+    plist.AddToList(&binsd);
+    plist.AddToList(&binsd0);
+
+    MHn mhn1, mhn2, mhn3, mhn4;
+    SetupHist(mhn1);
+    SetupHist(mhn2);
+    SetupHist(mhn3);
+    SetupHist(mhn4);
+
+    MH3 mhtp("TriggerPos.fVal-IntendedPulsePos.fVal-PulseShape.GetWidth");
+    mhtp.SetName("TrigPos");
+    mhtp.SetTitle("Trigger position w.r.t. the first photon hitting a detector");
+
+    MH3 mhew("MPhotonStatistics.fLength");
+    mhew.SetName("TotLength");
+    mhew.SetTitle("Time between first and last photon hitting a detector;L [ns]");
+
+    MH3 mhed("MPhotonStatistics.fTimeMedDev");
+    mhed.SetName("MedLength");
+    mhed.SetTitle("Median deviation (1\\sigma);L [ns]");
+
+    MFillH fillh1(&mhn1, "", "FillCorsika");
+    MFillH fillh2(&mhn2, "", "FillH2");
+    MFillH fillh3(&mhn3, "", "FillH3");
+    MFillH fillh4(&mhn4, "", "FillH4");
+    MFillH filltp(&mhtp, "", "FillTriggerPos");
+    MFillH fillew(&mhew, "", "FillEvtWidth");
+    MFillH filled(&mhed, "", "FillMedDev");
+    fillh1.SetNameTab("Corsika",    "Distribution as simulated by Corsika");
+    fillh2.SetNameTab("Detectable", "Distribution of events hit the detector");
+    fillh3.SetNameTab("Triggered",  "Distribution of triggered events");
+    fillh4.SetNameTab("Cleaned",    "Distribution after cleaning and cuts");
+    filltp.SetNameTab("TrigPos",    "TriggerPosition w.r.t the first photon");
+    fillew.SetNameTab("EvtWidth",   "Time between first and last photon hitting a detector");
+    filled.SetNameTab("MedDev",     "Median deviation of arrival time of photons hitting a detector");
+
+    MHPhotonEvent planeG(1, "HPhotonEventGround");     // Get from MaxImpact
+    MHPhotonEvent plane0(2, "HMirrorPlane0");     // Get from MReflector
+    //MHPhotonEvent plane1(2, "HMirrorPlane1");
+    MHPhotonEvent plane2(2, "HMirrorPlane2");
+    MHPhotonEvent plane3(2, "HMirrorPlane3");
+    MHPhotonEvent plane4(2, "HMirrorPlane4");
+    MHPhotonEvent planeF1(6, "HPhotonEventCamera");   // Get from MGeomCam
+    MHPhotonEvent planeF2(header.IsPointRun()?4:6, "HPhotonEventCones"); // Get from MGeomCam
+
+    plist.AddToList(&planeG);
+    plist.AddToList(&plane0);
+    plist.AddToList(&plane2);
+    plist.AddToList(&plane3);
+    plist.AddToList(&plane4);
+    plist.AddToList(&planeF1);
+    plist.AddToList(&planeF2);;
+
+    //MHPSF psf;
+
+    MFillH fillG(&planeG,   "MPhotonEvent", "FillGround");
+    MFillH fill0(&plane0,   "MirrorPlane0", "FillReflector");
+    //MFillH fill1(&plane1,   "MirrorPlane1", "FillCamShadow");
+    MFillH fill2(&plane2,   "MirrorPlane2", "FillCandidates");
+    MFillH fill3(&plane3,   "MirrorPlane3", "FillReflected");
+    MFillH fill4(&plane4,   "MirrorPlane4", "FillFocal");
+    MFillH fillF1(&planeF1, "MPhotonEvent", "FillCamera");
+    MFillH fillF2(&planeF2, "MPhotonEvent", "FillCones");
+    //MFillH fillP(&psf,      "MPhotonEvent", "FillPSF");
+
+    fillG.SetNameTab("Ground",     "Photon distribution at ground");
+    fill0.SetNameTab("Reflector",  "Photon distribution at reflector plane w/o camera shadow");
+    //fill1.SetNameTab("CamShadow",  "Photon distribution at reflector plane w/ camera shadow");
+    fill2.SetNameTab("Candidates", "*Can hit* photon distribution at reflector plane w/ camera shadow");
+    fill3.SetNameTab("Reflected",  "Photon distribution after reflector projected to reflector plane");
+    fill4.SetNameTab("Focal",      "Photon distribution at focal plane");
+    fillF1.SetNameTab("Camera",    "Photon distribution which hit the detector");
+    fillF2.SetNameTab("Cones",     "Photon distribution after cones");
+    //fillP.SetNameTab("PSF",        "Photon distribution after cones for all mirrors");
+
+    // -------------------------------------------------------------------
+
+    if (!fFileOut.IsNull())
+    {
+        const Ssiz_t dot   = fFileOut.Last('.');
+        const Ssiz_t slash = fFileOut.Last('/');
+        if (dot>slash)
+            fFileOut = fFileOut.Remove(dot);
+    }
+
+    // -------------------------------------------------------------------
+
+    const char *fmt = fFileOut.IsNull() ?
+        Form("s/cer([0-9]+)([0-9][0-9][0-9])/%s\\/%08d.$2%%s_MonteCarlo$1.root/", Esc(fPathOut).Data(), header.GetRunNumber()) :
+        Form("%s/%s%%s.root", Esc(fPathOut).Data(), Esc(fFileOut).Data());
+
+    const TString rule1(Form(fmt, fFileOut.IsNull()?"_R":""));
+    const TString rule2(Form(fmt, "_Y"));
+    const TString rule4(Form(fmt, "_I"));
+    TString rule3(Form(fmt, Form("_%c", header.GetRunTypeChar())));
+
+    MWriteRootFile write4a( 2, rule4, fOverwrite?"RECREATE":"NEW", "Star file");
+    MWriteRootFile write4b( 2, rule4, fOverwrite?"RECREATE":"NEW", "Star file");
+    MWriteRootFile write3b( 2, rule3, fOverwrite?"RECREATE":"NEW", "Camera file");
+    MWriteRootFile write2a( 2, rule2, fOverwrite?"RECREATE":"NEW", "Signal file");
+    MWriteRootFile write2b( 2, rule2, fOverwrite?"RECREATE":"NEW", "Signal file");
+    MWriteRootFile write1a( 2, rule1, fOverwrite?"RECREATE":"NEW", "Reflector file");
+    MWriteRootFile write1b( 2, rule1, fOverwrite?"RECREATE":"NEW", "Reflector file");
+
+    if (fWriteFitsFile)
+        rule3.ReplaceAll(".root", ".fits");
+
+    MWriteFitsFile write3af( 2, rule3, fOverwrite?"RECREATE":"NEW", "Camera file");
+    MWriteRootFile write3ar( 2, rule3, fOverwrite?"RECREATE":"NEW", "Camera file");
+
+    MTask &write3a = fWriteFitsFile ? static_cast<MTask&>(write3af) : static_cast<MTask&>(write3ar);
+
+    //SetupHeaderKeys(write3af,header);
+    SetupVetoColumns(write3af);
+
+    write3af.SetBytesPerSample("Data", 2);
+
+    write1a.SetName("WriteRefData");
+    write1b.SetName("WriteRefMC");
+    write2a.SetName("WriteSigData");
+    write2b.SetName("WriteSigMC");
+    write3a.SetName("WriteCamData");
+    write3b.SetName("WriteCamMC");
+    write4a.SetName("WriteImgData");
+    write4b.SetName("WriteImgMC");
+
+    SetupCommonFileStructure(write1a);
+    SetupCommonFileStructure(write2a);
+    SetupCommonFileStructure(write3ar);
+    SetupCommonFileStructure(write3af);
+    SetupCommonFileStructure(write4a);
+
+    // R: Dedicated file structure
+    write1a.AddContainer("MPhotonEvent", "Events");
+
+    // Y: Dedicated file structure
+    write2a.AddContainer("MPedPhotFromExtractorRndm", "RunHeaders", kTRUE, 1); // FIXME: Needed for the signal files to be display in MARS
+    write2a.AddContainer("MSignalCam", "Events");
+
+    // D: Dedicated file structure
+    write3af.AddContainer("ElectronicNoise",  "RunHeaders", kTRUE, 1);
+    write3af.AddContainer("IntendedPulsePos", "RunHeaders", kTRUE, 1);
+    write3af.AddContainer("MRawEvtData",      "Events");
+    write3af.AddContainer("MTruePhotonsPerPixelCont", "Events");
+    write3af.AddContainer("MPhotonEvent","Events");
+
+    write3ar.AddContainer("ElectronicNoise",  "RunHeaders", kTRUE, 1);
+    write3ar.AddContainer("IntendedPulsePos", "RunHeaders", kTRUE, 1);
+    write3ar.AddContainer("MRawEvtData",      "Events");
+    // It doesn't make much sene to write this information
+    // to the file because the units are internal units not
+    // related to the output samples
+    //    if (header.IsDataRun() || fForceTrigger)
+    //        write3a.AddContainer("TriggerPos",   "Events");
+
+    // I: Dedicated file structure
+    write4a.AddContainer("MHillas",       "Events");
+    write4a.AddContainer("MHillasSrc",    "Events");
+    write4a.AddContainer("MImagePar",     "Events");
+    write4a.AddContainer("MNewImagePar",  "Events");
+
+    // Basic MC data
+    write1b.AddContainer("MMcEvtBasic", "OriginalMC");
+    write2b.AddContainer("MMcEvtBasic", "OriginalMC");
+    write3b.AddContainer("MMcEvtBasic", "OriginalMC");
+    write4b.AddContainer("MMcEvtBasic", "OriginalMC");
+
+    // -------------------------------------------------------------------
+
+    MGeomApply apply;
+
+    MSimPSF simpsf;
+
+    MSimGeomCam simgeom;
+    simgeom.SetNameGeomCam("GeomCones");
+
+    MSimCalibrationSignal simcal;
+    simcal.SetNameGeomCam("GeomCones");
+
+    // Sky Quality Meter: 21.82M = 2.02e-4cd/m^2
+    // 1cd = 12.566 lm / 4pi sr
+
+    // FIXME: Simulate photons before cones and QE!
+
+    MSimRandomPhotons  simnsb;
+    simnsb.SetFreq(5.8, 0.004);  // ph/m^2/nm/sr/ns NSB, 4MHz dark count rate
+    simnsb.SetNameGeomCam("GeomCones");
+
+    // FIXME: How do we handle star-light? We need the rate but we also
+    //        need to process it through the mirror!
+
+    MSimAPD simapd;
+    simapd.SetNameGeomCam("GeomCones");
+
+    MSimExcessNoise   simexcnoise;
+    MSimBundlePhotons simsum;
+    MSimSignalCam     simsignal;
+    MSimCamera        simcam;
+    MSimTrigger       simtrig;
+    MSimReadout       simdaq;
+
+    MContinue conttrig("TriggerPos.fVal<0", "ContTrigger");
+
+    MParameterD pulpos("IntendedPulsePos");
+    // FIXME: Set a default which could be 1/3 of the digitization window
+    //    pulpos.SetVal(40);  // [ns]
+    plist.AddToList(&pulpos);
+
+    MParameterD trigger("TriggerPos");
+    trigger.SetVal(0);
+    plist.AddToList(&trigger);
+
+    // -------------------------------------------------------------------
+
+    // Remove isolated pixels
+    MImgCleanStd clean(0, 0);
+    //clean.SetCleanLvl0(0); // The level above which isolated pixels are kept
+    clean.SetCleanRings(0);
+    clean.SetMethod(MImgCleanStd::kAbsolute);
+
+    //clean.SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+
+    MHillasCalc hcalc;
+    hcalc.Disable(MHillasCalc::kCalcConc);
+
+    MHCamEvent evt0a(/*10*/3, "Signal",    "Average signal (absolute);;S [ph]");
+    MHCamEvent evt0c(/*10*/3, "MaxSignal", "Maximum signal (absolute);;S [ph]");
+    MHCamEvent evt0d(/*11*/8, "ArrTm",     "Time after first photon;;T [ns]");
+    evt0a.SetErrorSpread(kFALSE);
+    evt0c.SetCollectMax();
+
+    MContinue cut("", "Cut");
+
+    MFillH fillx0a(&evt0a,             "MSignalCam",      "FillAvgSignal");
+    MFillH fillx0c(&evt0c,             "MSignalCam",      "FillMaxSignal");
+    MFillH fillx0d(&evt0d,             "MSignalCam",      "FillArrTm");
+    MFillH fillx1("MHHillas",          "MHillas",         "FillHillas");
+    MFillH fillx3("MHHillasSrc",       "MHillasSrc",      "FillHillasSrc");
+    MFillH fillx4("MHNewImagePar",     "MNewImagePar",    "FillNewImagePar");
+    MFillH fillth("MHThreshold",       "",                "FillThreshold");
+    MFillH fillca("MHCollectionArea",  "",                "FillTrigArea");
+
+    fillth.SetNameTab("Threshold");
+    fillca.SetNameTab("TrigArea");
+
+    // -------------------------------------------------------------------
+
+    if (header.IsDataRun())
+    {
+        tasks.AddToList(&read);
+        tasks.AddToList(&precut);
+        tasks.AddToList(&pointing);
+        tasks.AddToList(&simmmcs);
+        if (!fPathOut.IsNull() && !HasNullOut())
+        {
+            //tasks.AddToList(&write1b);
+            tasks.AddToList(&write2b);
+            if (fCamera)
+                tasks.AddToList(&write3b);
+            if (header.IsDataRun())
+                tasks.AddToList(&write4b);
+        }
+        //    if (header.IsPointRun())
+        //        tasks.AddToList(&stars);
+        if (1)
+            tasks.AddToList(&simatm); // Here because before fillh1
+        tasks.AddToList(&calcangle);
+        tasks.AddToList(&fillh1);
+        tasks.AddToList(&fillG);
+        if (!header.IsPointRun())
+        {
+            tasks.AddToList(&absapd);
+            tasks.AddToList(&absmir);
+            if (0)
+                tasks.AddToList(&simatm); // FASTER?
+        }
+        tasks.AddToList(&reflect);
+        if (!header.IsPointRun())
+        {
+            tasks.AddToList(&fill0);
+            //tasks.AddToList(&fill1);
+            tasks.AddToList(&fill2);
+            tasks.AddToList(&fill3);
+            tasks.AddToList(&fill4);
+            tasks.AddToList(&fillF1);
+        }
+        tasks.AddToList(&cones);
+        tasks.AddToList(&cones2);
+        //if (header.IsPointRun())
+        //    tasks.AddToList(&fillP);
+        tasks.AddToList(&cont1);
+    }
+    // -------------------------------
+    tasks.AddToList(&apply);
+    if (header.IsDataRun())
+    {
+        tasks.AddToList(&simpsf);
+        tasks.AddToList(&simgeom);
+        tasks.AddToList(&cont2);
+        if (!header.IsPointRun())
+        {
+            tasks.AddToList(&fillF2);
+            tasks.AddToList(&fillh2);
+        }
+        tasks.AddToList(&cont3);
+    }
+    if (fCamera)
+    {
+        if (header.IsPedestalRun() || header.IsCalibrationRun())
+            tasks.AddToList(&simcal);
+        tasks.AddToList(&simnsb);
+        tasks.AddToList(&simapd);
+        tasks.AddToList(&simexcnoise);
+    }
+    tasks.AddToList(&simsum);
+    if (fCamera)
+    {
+        tasks.AddToList(&simcam);
+        if (header.IsDataRun() || fForceTrigger)
+            tasks.AddToList(&simtrig);
+        tasks.AddToList(&conttrig);
+        tasks.AddToList(&simdaq);
+    }
+    tasks.AddToList(&simsignal);  // What do we do if signal<0?
+    if (!fPathOut.IsNull() && !HasNullOut())
+    {
+        //tasks.AddToList(&write1a);
+        if (!header.IsPedestalRun())
+            tasks.AddToList(&write2a);
+        if (fCamera)
+            tasks.AddToList(&write3a);
+    }
+    // -------------------------------
+    if (fCamera)
+    {
+        // FIXME: MHCollectionArea Trigger Area!
+        if (header.IsDataRun())
+            tasks.AddToList(&fillh3);
+        tasks.AddToList(&filltp);
+    }
+    if (header.IsDataRun())
+    {
+        tasks.AddToList(&fillew);
+        tasks.AddToList(&filled);
+    }
+    if (!header.IsPedestalRun())
+    {
+        tasks.AddToList(&fillx0a);
+        tasks.AddToList(&fillx0c);
+    }
+    if (header.IsDataRun())
+    {
+        tasks.AddToList(&clean);
+        tasks.AddToList(&hcalc);
+        tasks.AddToList(&cut);
+        tasks.AddToList(&fillx0d);
+        tasks.AddToList(&fillx1);
+        //tasks.AddToList(&fillx2);
+        tasks.AddToList(&fillx3);
+        tasks.AddToList(&fillx4);
+        if (!HasNullOut())
+            tasks.AddToList(&write4a);
+        //tasks.AddToList(&fillx5);
+
+        tasks.AddToList(&fillh4);
+        tasks.AddToList(&fillth);
+        tasks.AddToList(&fillca);
+    }
+    //-------------------------------------------
+
+    tasks.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(&gLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    // FIXME: If pedestal file given use the values from this file
+    //-------------------------------------------
+
+    MGeomCam *cam = static_cast<MGeomCam*>(env2.GetCont());
+
+    if (binstr.IsDefault())
+        binstr.SetEdgesLin(150, -shape.GetWidth(),
+                           header.GetFreqSampling()/1000.*header.GetNumSamples()+shape.GetWidth());
+
+    if (binsd.IsDefault() && cam)
+        binsd.SetEdgesLin(100, 0, cam->GetMaxRadius()*cam->GetConvMm2Deg());
+
+    if (binsd0.IsDefault() && cam)
+        binsd0.SetEdgesLin(100, 0, cam->GetMaxRadius()*cam->GetConvMm2Deg());
+
+
+    header.Print();
+
+    // FIXME: Display acceptance curves!
+
+    if (fDisplay)
+    {
+        TCanvas &c = fDisplay->AddTab("Info");
+        c.Divide(2,2);
+
+        c.cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gROOT->SetSelectedPad(0);
+        shape.DrawClone()->SetBit(kCanDelete);
+
+        if (env0.GetCont() && (header.IsDataRun() || header.IsPointRun()))
+        {
+            c.cd(3);
+            gPad->SetBorderMode(0);
+            gPad->SetFrameBorderMode(0);
+            gPad->SetGridx();
+            gPad->SetGridy();
+            gROOT->SetSelectedPad(0);
+            static_cast<MReflector*>(env0.GetCont())->DrawClone("line")->SetBit(kCanDelete);
+        }
+
+        if (fCamera)
+        {
+            if (env1.GetCont())
+            {
+                c.cd(2);
+                gPad->SetBorderMode(0);
+                gPad->SetFrameBorderMode(0);
+                gPad->SetGridx();
+                gPad->SetGridy();
+                gROOT->SetSelectedPad(0);
+                MHCamera *c = new MHCamera(static_cast<MGeomCam&>(*env1.GetCont()));
+                c->SetStats(kFALSE);
+                c->SetBit(MHCamera::kNoLegend);
+                c->SetBit(kCanDelete);
+                c->Draw();
+            }
+
+            if (cam)
+            {
+                c.cd(4);
+                gPad->SetBorderMode(0);
+                gPad->SetFrameBorderMode(0);
+                gPad->SetGridx();
+                gPad->SetGridy();
+                gROOT->SetSelectedPad(0);
+                MHCamera *c = new MHCamera(*cam);
+                c->SetStats(kFALSE);
+                c->SetBit(MHCamera::kNoLegend);
+                c->SetBit(kCanDelete);
+                c->Draw();
+            }
+        }
+
+        TCanvas &d = fDisplay->AddTab("Info2");
+        d.Divide(2,3);
+
+        d.cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gROOT->SetSelectedPad(0);
+        splinepde.DrawClone()->SetBit(kCanDelete);
+
+        d.cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gROOT->SetSelectedPad(0);
+        splinecones2.DrawClone()->SetBit(kCanDelete);
+
+        d.cd(5);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gROOT->SetSelectedPad(0);
+        splinemirror.DrawClone()->SetBit(kCanDelete);
+
+        d.cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gROOT->SetSelectedPad(0);
+        splinecones.DrawClone()->SetBit(kCanDelete);
+        //splinecones2.DrawClone("same")->SetBit(kCanDelete);
+
+        d.cd(6);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gROOT->SetSelectedPad(0);
+        MParSpline *all = (MParSpline*)splinepde.DrawClone();
+        //all->SetTitle("Combined acceptance");
+        all->SetBit(kCanDelete);
+        if (splinemirror.GetSpline())
+            all->Multiply(*splinemirror.GetSpline());
+        if (splinecones2.GetSpline())
+            all->Multiply(*splinecones2.GetSpline());
+    }
+
+    //-------------------------------------------
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        gLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    //-------------------------------------------
+    // FIXME: Display Spline     in tab
+    // FIXME: Display Reflector  in tab
+    // FIXME: Display Routing(?) in tab
+    // FIXME: Display Camera(s)  in tab
+    //-------------------------------------------
+
+    if (!WriteResult(plist, seq, header.GetRunNumber()))
+        return kFALSE;
+
+    *fLog << all << GetDescriptor() << ": Done." << endl << endl << endl;;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJSimulation.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJSimulation.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJSimulation.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MJSimulation
+#define MARS_MJSimulation
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MHn;
+class MArgs;
+class MParList;
+class MSequence;
+class MWriteRootFile;
+class MWriteFitsFile;
+class MRawRunHeader;
+
+class MJSimulation : public MJob
+{
+public:
+    enum Mode_t { kModeData, kModePed, kModeCal, kModePointRun };
+
+private:
+    Bool_t fForceMode;      // Force execution even if RUNE-section was not foundm
+
+    Bool_t fCamera;         // Switch on/off camera (for fast reflector processing)
+    Bool_t fForceTrigger;   // Force the use of the trigger "electronics"
+    Bool_t fWriteFitsFile;
+
+    Int_t  fOperationMode;  // Operation mode (data, ped, cal, pointrun)
+    Int_t  fRunNumber;      // 8 digits run number to be used for the file names
+
+    TString fFileOut;       // Output file name if all runs should be combines
+
+    Bool_t WriteResult(const MParList &plist, const MSequence &seq, Int_t run);
+    Bool_t CheckEnvLocal();
+
+    template<class T>
+    void SetupCommonFileStructure(T &write) const;
+
+    void SetupHist(MHn &hist) const;
+    void SetupHeaderKeys(MWriteFitsFile& write, MRawRunHeader &header) const;
+    void SetupVetoColumns(MWriteFitsFile& write) const;
+
+public:
+    MJSimulation(const char *name=NULL, const char *title=NULL);
+
+    void SetForceMode(Bool_t force=kTRUE) { fForceMode = force; }
+    void SetMode(Int_t mode) { fOperationMode = mode; }
+    void SetWriteFitsFile(Bool_t fits) { fWriteFitsFile = fits; }
+    void SetFileOut(const char *file="") { fFileOut = file; }
+
+    void SetRunNumber(Int_t n=-1) { fRunNumber = n%100000000; }
+
+    // Process
+    Bool_t Process(const MArgs &args, const MSequence &seq);
+
+    ClassDef(MJSimulation, 0) // Job to run the simulation (ceres)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJSpectrum.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJSpectrum.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJSpectrum.cc	(revision 17960)
@@ -0,0 +1,1993 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJSpectrum
+//
+// Program to calculate spectrum
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJSpectrum.h"
+
+// Root
+#include <TF1.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TLine.h>
+#include <TFile.h>
+#include <TGraph.h>
+#include <TChain.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TObjArray.h>
+
+// Environment
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMath.h"
+#include "MString.h"
+#include "MDirIter.h"
+
+#include "MStatusArray.h"
+#include "MStatusDisplay.h"
+
+// Container
+#include "MH3.h"
+#include "MHn.h"
+#include "MEnv.h"
+#include "MBinning.h"
+#include "MParameters.h"
+#include "MDataSet.h"
+#include "MMcCorsikaRunHeader.h"
+
+// Spectrum
+#include "MAlphaFitter.h"
+#include "MHAlpha.h"
+#include "MHCollectionArea.h"
+#include "MHEnergyEst.h"
+#include "MMcSpectrumWeight.h"
+#include "MHEffectiveOnTime.h"
+
+// Eventloop
+#include "MEvtLoop.h"
+#include "MTaskList.h"
+#include "MParList.h"
+
+// Tasks/Filter
+#include "MReadMarsFile.h"
+#include "MEnergyEstimate.h"
+#include "MTaskEnv.h"
+#include "MFillH.h"
+#include "MFDataPhrase.h"
+#include "MFDataMember.h"
+#include "MContinue.h"
+#include "MWriteRootFile.h"
+
+ClassImp(MJSpectrum);
+
+using namespace std;
+
+MJSpectrum::MJSpectrum(const char *name, const char *title)
+    : fCutQ(0), fCut0(0),fCut1(0), fCut2(0), fCut3(0), fCutS(0),
+    fEstimateEnergy(0), fCalcHadronness(0),  fCalcDisp(0),
+    fForceTheta(kFALSE), fForceRunTime(kFALSE), fForceOnTimeFit(kFALSE)
+{
+    fName  = name  ? name  : "MJSpectrum";
+    fTitle = title ? title : "Standard program to calculate spectrum";
+
+    // Make sure that fDisplay is maintained properly
+    // (i.e. removed via RecursiveRemove if closed)
+    gROOT->GetListOfCleanups()->Add(this);
+    SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete all the fCut* data members and fCalcHadronness/fEstimateEnergy
+//
+MJSpectrum::~MJSpectrum()
+{
+    if (fCutQ)
+        delete fCutQ;
+    if (fCut0)
+        delete fCut0;
+    if (fCut1)
+        delete fCut1;
+    if (fCut2)
+        delete fCut2;
+    if (fCut3)
+        delete fCut3;
+    if (fCutS)
+        delete fCutS;
+    if (fEstimateEnergy)
+        delete fEstimateEnergy;
+    if (fCalcHadronness)
+        delete fCalcHadronness;
+    if (fCalcDisp)
+        delete fCalcDisp;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a task estimating the energy. The given task is cloned.
+//
+void MJSpectrum::SetEnergyEstimator(const MTask *task)
+{
+    if (fEstimateEnergy)
+        delete fEstimateEnergy;
+    fEstimateEnergy = task ? (MTask*)task->Clone() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a MTask named name into task from the open file. If this task is
+// required mustexist can be set. Depending on success kTRUE or kFALSE is
+// returned. If the task is a MContinue SetAllowEmpty is called.
+// The name of the task is set to name.
+//
+Bool_t MJSpectrum::ReadTask(MTask* &task, const char *name, Bool_t mustexist) const
+{
+    // If a task is set delete task
+    if (task)
+    {
+        delete task;
+        task = 0;
+    }
+
+    // Try to get task from file
+    task = (MTask*)gFile->Get(name);
+    if (!task)
+    {
+        if (!mustexist)
+            return kTRUE;
+        *fLog << err << dbginf << "ERROR - " << name << " doen't exist in file!" << endl;
+        return kFALSE;
+    }
+
+    // Check if task inherits from MTask
+    if (!task->InheritsFrom(MTask::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - " << name << " read doesn't inherit from MTask!" << endl;
+        delete task;
+        return kFALSE;
+    }
+
+    // Set name of task
+    task->SetName(name);
+
+    // SetAllowEmpty for MContinue tasks
+    if (dynamic_cast<MContinue*>(task))
+        dynamic_cast<MContinue*>(task)->SetAllowEmpty();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print setup used for the MC processing, namely MAlphaFitter ans all fCut*.
+//
+void MJSpectrum::PrintSetup(const MAlphaFitter &fit) const
+{
+    fLog->Separator("Alpha Fitter");
+    *fLog << all;
+    fit.Print("result");
+
+    fLog->Separator("Used Cuts");
+    fCutQ->Print();
+    fCut0->Print();
+    fCut1->Print();
+    fCutS->Print();
+    fCut2->Print();
+    fCut3->Print();
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the first MMcCorsikaRunHeader from the RunHeaders tree in
+// the dataset.
+// The simulated energy range and spectral slope is initialized from
+// there.
+// In the following eventloops the forced check in MMcSpectrumWeight
+// ensures, that the spectral slope and energy range doesn't change.
+//
+Bool_t  MJSpectrum::InitWeighting(const MDataSet &set, MMcSpectrumWeight &w) const
+{
+    fLog->Separator("Initialize energy weighting");
+
+    // Read Resources
+    if (!CheckEnv(w))
+    {
+        *fLog << err << "ERROR - Reading resources for MMcSpectrumWeight failed." << endl;
+        return kFALSE;
+    }
+
+    w.Print("new");
+
+    return kTRUE;
+}
+
+Float_t MJSpectrum::ReadInput(MParList &plist, TH1D &h1, TH1D &h2)
+{
+    *fLog << inf << "Reading from file: " << fPathIn << endl;
+
+    TFile file(fPathIn, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fPathIn << endl;
+        return -1;
+    }
+
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        *fLog << err << dbginf << "ERROR - MStatusDisplay not found in file... abort." << endl;
+        return -1;
+    }
+
+    //arr.EnableTH1Workaround();
+
+    TH1D *vstime = (TH1D*)arr.FindObjectInCanvas("Theta",  "TH1D", "OnTime");
+    TH1D *size   = (TH1D*)arr.FindObjectInCanvas("Excess", "TH1D", "Hist");
+    if (!vstime)
+    {
+        *fLog << err << dbginf << "ERROR - Theta [TH1D] not found in OnTime-tab... abort." << endl;
+        return -1;
+    }
+    if (!size)
+    {
+        *fLog << err << dbginf << "ERROR - Excess [TH1D] not found in Hist-tab... abort." << endl;
+        return -1;
+    }
+
+    vstime->Copy(h1);
+    size->Copy(h2);
+    h1.SetDirectory(0);
+    h2.SetDirectory(0);
+
+    if (fDisplay)
+        arr.DisplayIn(*fDisplay, "Hist");
+
+    if (!ReadTask(fCutQ, "CutQ"))
+        return -1;
+    if (!ReadTask(fCut0, "Cut0"))
+        return -1;
+    if (!ReadTask(fCut1, "Cut1"))
+        return -1;
+    if (!ReadTask(fCut2, "Cut2"))
+        return -1;
+    if (!ReadTask(fCut3, "Cut3"))
+        return -1;
+    if (!ReadTask(fCalcHadronness, "CalcHadronness", kFALSE))
+        return -1;
+    if (!ReadTask(fCalcDisp,       "CalcDisp",       kFALSE))
+        return -1;
+
+    TObjArray arrread;
+
+    TIter Next(plist);
+    TObject *o=0;
+    while ((o=Next()))
+        if (o->InheritsFrom(MBinning::Class()))
+            arrread.Add(o);
+
+    arrread.Add(plist.FindObject("MAlphaFitter"));
+
+    if (!ReadContainer(arrread))
+        return -1;
+
+    // We don't have to proceed. We later overwrite the result anyway
+    if (fForceOnTimeFit)
+        return 0;
+
+    const Double_t ufl = vstime->GetBinContent(0);
+    const Double_t ofl = vstime->GetBinContent(vstime->GetNbinsX()+1);
+    const Double_t eff = vstime->Integral()+ufl+ofl;
+    if (ufl>0)
+    {
+        if (vstime->GetBinLowEdge(1)<=0)
+        {
+            *fLog << err << "ERROR - Undeflow bin of OnTime histogram not empty as it ought to be." << endl;
+            return -1;
+        }
+        *fLog << warn << "WARNING - " << Form("%.1f%% (%.0fs)", 100*ufl/eff, ufl) << " of the eff. observation time is in the underflow bin." << endl;
+    }
+    if (ofl>0)
+        *fLog << warn << "WARNING - " << Form("%.1f%% (%.0fs)", 100*ofl/eff, ofl) << " of the eff. observation time is in the overflow bin." << endl;
+
+    if (!fForceRunTime)
+        return eff;
+
+    TH1D *time   = (TH1D*)arr.FindObjectInCanvas("ExcessTime", "TH1D", "Hist");
+    if (!time)
+    {
+        *fLog << err;
+        *fLog << "ERROR - ExcessTime [TH1D] not found in Hist-tab... abort." << endl;
+        *fLog << "        Did you try to process Monte Carlos with --force-runtime?" <<endl;
+        return -1;
+    }
+
+    const Double_t obs = time->GetXaxis()->GetXmax()-time->GetXaxis()->GetXmin();
+
+    *fLog << inf;
+    *fLog << "Total run time: " << obs/60 << "min" << endl;
+    *fLog << "Eff. obs. time: " << eff/60 << "min  (" << Form("%.1f%%", 100*eff/obs) << ")" << endl;
+
+    return obs;
+}
+
+// --------------------------------------------------------------------------
+//
+// return maximum value of MMcRunHeader.fImpactMax stored in the RunHeaders
+// of the files from the MC dataset
+//
+Bool_t MJSpectrum::AnalyzeMC(const MDataSet &set, Float_t &impactmax, Float_t &emin/*, Float_t emax*/) const
+{
+    if (fDisplay)
+        fDisplay->SetStatusLine1("Analyzing Monte Carlo headers...");
+
+    // ----- Create chain -----
+    *fLog << inf << "Getting files... " << flush;
+    TChain chain("RunHeaders");
+    if (!set.AddFilesOn(chain))
+        return kFALSE;
+    *fLog << "done. " << endl;
+
+    *fLog << all;
+    *fLog << "Searching for maximum impact... " << flush;
+    impactmax = chain.GetMaximum("MMcRunHeader.fImpactMax");
+    *fLog << "found " << impactmax/100 << "m" << endl;
+
+    *fLog << "Searching for minimum lower energy limit... " << flush;
+    emin = chain.GetMinimum("MMcCorsikaRunHeader.fELowLim");
+    *fLog << "found " << emin << "GeV" << endl;
+
+    *fLog << "Searching for maximum lower energy limit... " << flush;
+    const Float_t emin2 = chain.GetMaximum("MMcCorsikaRunHeader.fELowLim");
+    *fLog << "found " << emin2 << "GeV" << endl;
+
+    // Need a check for the upper energy LIMIT?!?
+
+    if (emin2>emin)
+    {
+        *fLog << warn;
+        *fLog << "WARNING - You are using files with different lower limits for the simulated" << endl;
+        *fLog << "          energy, i.e. that the collection area and your correction" << endl;
+        *fLog << "          coefficients between " << emin << "GeV and ";
+        *fLog << emin2 << "GeV might be wrong." << endl;
+    }
+
+/*
+    *fLog << "Getting maximum energy... " << flush;
+    emax = chain.GetMaximum("MMcCorsikaRunHeader.fEUppLim");
+    *fLog << "found " << emax << "GeV" << endl;
+ */
+    return kTRUE;
+}
+
+Bool_t MJSpectrum::ReadOrigMCDistribution(const MDataSet &set, TH1 &h, MMcSpectrumWeight &weight) const
+{
+    // Some debug output
+    *fLog << all << endl;
+    fLog->Separator("Compiling original MC distribution");
+
+    Float_t impactmax=0, Emin=0;
+    if (!AnalyzeMC(set, impactmax, Emin))
+        return kFALSE;
+
+    *fLog << inf << "Getting files... " << flush;
+    MDirIter iter;
+    if (!set.AddFilesOn(iter))
+        return kFALSE;
+    *fLog << "done. " << endl;
+
+    const Int_t tot = iter.GetNumEntries();
+
+    // Prepare histogram
+    h.Reset();
+    h.Sumw2();
+    if (h.InheritsFrom(TH2::Class()))
+    {
+        h.SetNameTitle("ThetaEMC", "Event-Distribution vs Theta and Energy for MC (produced)");
+        h.SetXTitle("\\Theta [\\circ]");
+        h.SetYTitle("E [GeV]");
+        h.SetZTitle(MString::Format("Counts normalized to r=%.0fm", impactmax/100));
+    }
+    else
+    {
+        h.SetNameTitle("ThetaMC", "Event-Distribution vs Theta for MC (produced)");
+        h.SetXTitle("\\Theta [\\circ]");
+        h.SetYTitle(MString::Format("Counts normalized to r=%.0fm", impactmax/100));
+    }
+    h.SetDirectory(0);
+
+    const TString cont = h.InheritsFrom(TH2::Class()) ?
+        "MMcEvtBasic.fEnergy:MMcEvtBasic.fTelescopeTheta*TMath::RadToDeg()>>ThetaEMC" :
+        "MMcEvtBasic.fTelescopeTheta*TMath::RadToDeg()>>ThetaMC";
+
+    if (fDisplay)
+        fDisplay->SetStatusLine1("Reading OriginalMC distribution...");
+
+    TH1 *hfill = (TH1*)h.Clone(h.InheritsFrom(TH2::Class())?"ThetaEMC":"ThetaMC");
+    hfill->SetDirectory(0);
+
+    *fLog << all << "Compiling simulated source spectrum... please stand by, this may take a while." << endl;
+
+    Double_t evts = 0;
+    Int_t    num  = 0;
+
+    // Reading this with a eventloop is five times slower :(
+    TString fname;
+    while (fDisplay)
+    {
+        if (fDisplay)
+            fDisplay->SetProgressBarPosition(Float_t(num++)/tot);
+
+        // Get next filename
+        fname = iter.Next();
+        if (fname.IsNull())
+            break;
+
+        if (fDisplay)
+            fDisplay->SetStatusLine2(fname);
+
+        // open file
+        TFile file(fname);
+        if (file.IsZombie())
+        {
+            *fLog << err << "ERROR - Couldn't open file " << fname << endl;
+            return kFALSE;
+        }
+
+        // Get tree OriginalMC
+        TTree *t = dynamic_cast<TTree*>(file.Get("OriginalMC"));
+        if (!t)
+        {
+            *fLog << err << "ERROR - File " << fname << " doesn't contain tree OriginalMC." << endl;
+            return kFALSE;
+        }
+        if (t->GetEntries()==0)
+        {
+            *fLog << warn << "WARNING - OriginalMC of " << fname << " empty." << endl;
+            continue;
+        }
+
+        // Get tree RunHeaders
+        TTree *rh = dynamic_cast<TTree*>(file.Get("RunHeaders"));
+        if (!rh)
+        {
+            *fLog << err << "ERROR - File " << fname << " doesn't contain tree RunHeaders." << endl;
+            return kFALSE;
+        }
+        if (rh->GetEntries()!=1)
+        {
+            *fLog << err << "ERROR - RunHeaders of " << fname << " doesn't contain exactly one entry." << endl;
+            return kFALSE;
+        }
+
+        // Get corsika run header
+        MMcCorsikaRunHeader *head=0;
+        rh->SetBranchAddress("MMcCorsikaRunHeader.", &head);
+        rh->GetEntry(0);
+        if (!head)
+        {
+            *fLog << err << "ERROR - Couldn't read MMcCorsikaRunHeader from " << fname << "." << endl;
+            return kFALSE;
+        }
+
+        // Get the maximum impact parameter of this file. Due to different
+        // production areas an additional scale-factor is applied.
+        //
+        // Because it is assumed that the efficiency outside the production
+        // area is nearly zero no additional weight has to be applied to the
+        // events after cuts. For the events before cuts it is fair to use
+        // weights... maybe filling the residual impact with unweighted
+        // events would be better?!? (Not that the weighting might be
+        // less correct with low statistics, because it could pronounce
+        // a fluctuation)
+        const Double_t impact = rh->GetMaximum("MMcRunHeader.fImpactMax");
+        const Double_t scale  = impactmax/impact;
+
+        // Propagate the run header to MMcSpectrumWeight
+        if (!weight.Set(*head))
+        {
+            *fLog << err << "ERROR - Initializing MMcSpectrumWeight from " << fname << " failed." << endl;
+            return kFALSE;
+        }
+
+        // Get the corresponding rule for the weights
+        const TString weights(weight.GetFormulaWeights("MMcEvtBasic"));
+
+        // No we found everything... go on reading contents
+        *fLog << inf2 << "Reading OriginalMC of " << fname << endl;
+
+        // Fill histogram from tree
+        hfill->SetDirectory(&file);
+        if (t->Draw(cont, weights, "goff")<0)
+        {
+            *fLog << err << "ERROR - Reading OriginalMC failed." << endl;
+            return kFALSE;
+        }
+        hfill->SetDirectory(0);
+
+        evts += hfill->GetEntries();
+
+        // ----- Complete incomplete energy ranges -----
+        // ----- and apply production area weights -----
+        weight.CompleteEnergySpectrum(*hfill, Emin, scale*scale);
+
+        // Add weighted data from file to final histogram
+        h.Add(hfill);
+    }
+    delete hfill;
+
+    *fLog << all << "Total number of events from files in Monte Carlo dataset: " << evts << endl;
+    if (fDisplay)
+        fDisplay->SetStatusLine2("done.");
+
+    if (!fDisplay || h.GetEntries()>0)
+        return kTRUE;
+
+    *fLog << err << "ERROR - Histogram with distribution from OriginalMC empty..." << endl;
+    return kFALSE;
+}
+
+void MJSpectrum::GetThetaDistribution(TH1D &temp1, TH2D &hist2) const
+{
+    TH1D &temp2 = *hist2.ProjectionX();
+
+    // Display some stuff
+    if (fDisplay)
+    {
+        TCanvas &c = fDisplay->AddTab("ZdDist");
+        c.Divide(2,2);
+
+        // On-Time vs. Theta
+        c.cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        temp1.DrawCopy();
+
+        // Number of MC events (produced) vs Theta
+        c.cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        temp2.SetName("NVsTheta");
+        temp2.DrawCopy("hist");
+
+        c.cd(4);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+
+        c.cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+    }
+
+    // Calculate the Probability
+    temp1.Divide(&temp2);
+    temp1.Scale(1./temp1.Integral(1, temp1.GetNbinsX()+1));
+
+    // Some cosmetics: Name, Axis, etc.
+    temp1.SetName("ProbVsTheta");
+    temp1.SetTitle("Probability vs. Zenith Angle to choose MC events");
+    temp1.SetYTitle("Probability");
+    if (fDisplay)
+        temp1.DrawCopy("hist");
+
+    delete &temp2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Display the final theta distribution.
+//
+Bool_t MJSpectrum::DisplayResult(const TH2D &h2) const
+{
+    if (!fDisplay || !fDisplay->CdCanvas("ZdDist"))
+    {
+        *fLog << err << "ERROR - Display or tab ZdDist vanished... abort." << endl;
+        return kFALSE;
+    }
+
+    TH1D &proj = *h2.ProjectionX();
+    proj.SetNameTitle("ThetaFinal", "Final Theta Distribution");
+    proj.SetXTitle("\\Theta [\\circ]");
+    proj.SetYTitle("Counts");
+    proj.SetLineColor(kBlue);
+    proj.SetDirectory(0);
+    proj.SetBit(kCanDelete);
+
+    TVirtualPad *pad = gPad;
+
+    pad->cd(4);
+    proj.DrawCopy();
+
+    pad->cd(1);
+    TH1D *theta = (TH1D*)gPad->FindObject("Theta");
+    if (!theta)
+    {
+        *fLog << err << "ERROR - Theta-Histogram vanished... cannot proceed." << endl;
+        return kFALSE;
+    }
+
+    // Check whether histogram is empty
+    if (proj.GetMaximum()==0)
+    {
+        *fLog << err;
+        *fLog << "ERROR - The Zenith Angle distribution of your Monte Carlos doesn't overlap" << endl;
+        *fLog << "        with the Zenith Angle distribution of your observation." << endl;
+        *fLog << "        Maybe the energy binning is undefined or wrong (from ";
+        *fLog << h2.GetYaxis()->GetXmin() << "GeV to " << h2.GetYaxis()->GetXmax() << "GeV)" << endl;
+        theta->SetLineColor(kRed);
+        return kFALSE;;
+    }
+
+    // scale histogram and set new maximum for display
+    proj.Scale(theta->GetMaximum()/proj.GetMaximum());
+    theta->SetMaximum(1.05*TMath::Max(theta->GetMaximum(), proj.GetMaximum()));
+
+    // draw project
+    proj.Draw("same");
+
+    // Compare both histograms
+    *fLog << inf << "Comparing theta distributions for data and MCs." << endl;
+
+    const Double_t prob = proj.Chi2Test(theta, "P");
+    if (prob==1)
+        return kTRUE;
+
+    if (prob>0.99)
+    {
+        *fLog << inf;
+        *fLog << "The Zenith Angle distribution of your Monte Carlos fits well" << endl;
+        *fLog << "with the Zenith Angle distribution of your observation." << endl;
+        *fLog << "The probability for identical Theta distributions is " << prob << endl;
+        return kTRUE;
+    }
+
+    if (prob<0.01)
+    {
+        *fLog << err;
+        *fLog << "ERROR - The Zenith Angle distribution of your Monte Carlos does not fit" << endl;
+        *fLog << "        with the Zenith Angle distribution of your observation." << endl;
+        *fLog << "        The probability for identical Theta distributions is " << prob << endl;
+        if (!fForceTheta)
+            *fLog << "        To force processing use --force-theta (with care!)" << endl;
+        theta->SetLineColor(kRed);
+        return fForceTheta;
+    }
+
+    *fLog << warn;
+    *fLog << "WARNING - The Zenith Angle distribution of your Monte Carlos doesn't fits well" << endl;
+    *fLog << "          with the Zenith Angle distribution of your observation." << endl;
+    *fLog << "          The probability for identical Theta distributions is " << prob << endl;
+    return kTRUE;
+}
+
+TString MJSpectrum::GetHAlpha() const
+{
+    TString cls("MHAlpha");
+    if (!fDisplay)
+        return cls;
+
+    TCanvas *c = fDisplay->GetCanvas("Hist");
+    if (!c)
+        return cls;
+
+    TIter Next(c->GetListOfPrimitives());
+    TObject *obj=0;
+    while ((obj=Next()))
+        if (obj->InheritsFrom(MHAlpha::Class()))
+            break;
+
+    return obj ? TString(obj->ClassName()) : cls;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills the excess histogram (vs E-est) from the events stored in the
+// ganymed result file and therefor estimates the energy.
+//
+// The resulting histogram excess-vs-energy ist copied into h2.
+//
+Bool_t MJSpectrum::Refill(MParList &plist, TH1D &h2)/*const*/
+{
+    // Now fill the histogram
+    *fLog << endl;
+    fLog->Separator("Refill Excess");
+    *fLog << endl;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read("Events");
+    read.DisableAutoScheme();
+    read.AddFile(fPathIn);
+/*
+    MTaskEnv taskenv0("CalcDisp");
+    taskenv0.SetDefault(fCalcDisp);
+
+    MTaskEnv taskenv1("CalcHadronness");
+    taskenv1.SetDefault(fCalcHadronness);
+ */
+    MEnergyEstimate est;
+    MTaskEnv taskenv2("EstimateEnergy");
+    taskenv2.SetDefault(fEstimateEnergy ? fEstimateEnergy : &est);
+
+    MContinue *cont = new MContinue("", "CutS");
+    cont->SetAllowEmpty();
+
+    if (fCutS)
+        delete fCutS;
+    fCutS = cont;
+
+    // Try to find the class used to determine the signal!
+    const TString cls = GetHAlpha();
+
+    // FIXME: Create HistE and HistEOff to be able to modify it from
+    // the resource file.
+    MFillH fill1(Form("HistEOff [%s]", cls.Data()), "", "FillHistEOff");
+    MFillH fill2(Form("HistE    [%s]", cls.Data()), "", "FillHistE");
+
+    // Fill a new MHEffectiveOnTime. It can either be used to
+    // re-calculate the on-time or just for manual cross check
+    MFillH fillT("MHEffectiveOnTime", "MTime", "FillOnTime");
+    fillT.SetNameTab("OnTime");
+
+    MFDataMember f0("DataType.fVal", '<', 0.5, "FilterOffData");
+    MFDataMember f1("DataType.fVal", '>', 0.5, "FilterOnData");
+
+    fill1.SetFilter(&f0);
+    fill2.SetFilter(&f1);
+    fillT.SetFilter(&f1);
+
+    tlist.AddToList(&read);
+    //tlist.AddToList(&taskenv0); // not necessary, stored in file!
+    //tlist.AddToList(&taskenv1); // not necessary, stored in file!
+    tlist.AddToList(&f1);
+    tlist.AddToList(&fillT);
+    tlist.AddToList(fCutS);
+    tlist.AddToList(&taskenv2);
+    tlist.AddToList(&f0);
+    tlist.AddToList(&fill1);
+    tlist.AddToList(&fill2);
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    MEvtLoop loop("RefillExcess"); // ***** fName *****
+    loop.SetParList(&plist);
+    loop.SetDisplay(fDisplay);
+    loop.SetLogStream(fLog);
+
+    if (!SetupEnv(loop))
+        return kFALSE;
+
+    if (!loop.Eventloop())
+    {
+        *fLog << err << GetDescriptor() << ": Refilling of data failed." << endl;
+        return kFALSE;
+    }
+
+    if (!loop.GetDisplay())
+    {
+        *fLog << err << GetDescriptor() << ": Execution stopped by user." << endl;
+        return kFALSE;
+    }
+
+    const MHAlpha *halpha = (MHAlpha *)plist.FindObject("HistE");
+    if (!halpha)
+    {
+        *fLog << err << GetDescriptor() << ": HistE [MHAlpha] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    halpha->GetHEnergy().Copy(h2);
+    h2.SetDirectory(0);
+
+    return kTRUE;
+}
+
+/*
+Bool_t MJSpectrum::IntermediateLoop(MParList &plist, MH3 &mh1, TH1D &temp1, const MDataSet &set, MMcSpectrumWeight &weight) const
+{
+    MTaskList tlist1;
+    plist.Replace(&tlist1);
+
+    MReadMarsFile readmc("OriginalMC");
+    //readmc.DisableAutoScheme();
+    if (!set.AddFilesOn(readmc))
+        return kFALSE;
+
+    readmc.EnableBranch("MMcEvtBasic.fTelescopeTheta");
+    readmc.EnableBranch("MMcEvtBasic.fEnergy");
+
+    mh1.SetLogy();
+    mh1.SetLogz();
+    mh1.SetName("ThetaE");
+
+    MFillH fill0(&mh1);
+    //fill0.SetDrawOption("projx only");
+
+    MBinning *bins2 = (MBinning*)plist.FindObject("BinningEnergyEst");
+    MBinning *bins3 = (MBinning*)plist.FindObject("BinningTheta");
+    if (bins2 && bins3)
+    {
+        bins2->SetName("BinningThetaEY");
+        bins3->SetName("BinningThetaEX");
+    }
+    tlist1.AddToList(&readmc);
+    tlist1.AddToList(&weight);
+
+    temp1.SetXTitle("MMcEvtBasic.fTelescopeTheta*kRad2Deg");
+    MH3 mh3mc(temp1);
+
+    MFEventSelector2 sel1(mh3mc);
+    sel1.SetHistIsProbability();
+
+    fill0.SetFilter(&sel1);
+
+    //if (!fRawMc)
+        tlist1.AddToList(&sel1);
+    tlist1.AddToList(&fill0);
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist1.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    MEvtLoop loop1("IntermediateLoop"); // ***** fName *****
+    loop1.SetParList(&plist);
+    loop1.SetLogStream(fLog);
+    loop1.SetDisplay(fDisplay);
+
+    if (!SetupEnv(loop1))
+        return kFALSE;
+
+    if (!loop1.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Processing of MC-data failed." << endl;
+        return kFALSE;
+    }
+
+    if (!loop1.GetDisplay())
+    {
+        *fLog << err << GetDescriptor() << ": Execution stopped by user." << endl;
+        return kFALSE;
+    }
+
+    if (bins2 && bins3)
+    {
+        bins2->SetName("BinningEnergyEst");
+        bins3->SetName("BinningTheta");
+    }
+
+    return kTRUE;
+}
+*/
+
+TString MJSpectrum::FormFloat(Double_t d)
+{
+    TString s;
+    s += d;
+    return s.Strip(TString::kLeading);
+}
+
+TString MJSpectrum::FormFlux(const TF1 &f, const char *unit)
+{
+    Double_t p0 = -f.GetParameter(0);
+    Double_t p1 =  f.GetParameter(1);
+
+    Double_t e0 =  f.GetParError(0);
+    Double_t e1 =  f.GetParError(1);
+
+    MMath::Format(p0, e0);
+    MMath::Format(p1, e1);
+
+    const Int_t    i   = TMath::FloorNint(TMath::Log10(p1));
+    const Double_t exp = TMath::Power(10, i);
+
+    TString str = MString::Format("(%s #pm %s)·10^{%d} ",
+                                  FormFloat(p1/exp).Data(), FormFloat(e1/exp).Data(), i);
+
+    str += MString::Format("#left(#frac{E}{%s}#right)^{-%s #pm %s}", unit,
+                           FormFloat(p0).Data(), FormFloat(e0).Data());
+
+    str += " TeV^{-1} m^{-2} s^{-1}";
+
+    return str;
+}
+
+TString MJSpectrum::FormString(const TF1 &f, Byte_t type)
+{
+    switch (type)
+    {
+    case 0:
+        return FormFlux(f, "500GeV");
+    case 1:
+        return MString::Format("\\chi^{2}/NDF=%.2f/%d", f.GetChisquare(),f.GetNDF());
+    case 2:
+        return MString::Format("P=%.0f%%", 100*TMath::Prob(f.GetChisquare(),  f.GetNDF()));
+    }
+    return "";
+}
+
+TArrayD MJSpectrum::FitSpectrum(TH1D &spectrum) const
+{
+    Axis_t lo, hi;
+    MH::GetRangeUser(spectrum, lo, hi);
+
+    TF1 f("f", "[1]*(x/500)^[0]", lo, hi);
+    f.SetParameter(0, -3.0);
+    f.SetParameter(1, spectrum.GetMaximum());
+    f.SetLineColor(kBlue);
+    f.SetLineWidth(2);
+    spectrum.Fit(&f, "NIR"); // M skipped
+    f.DrawCopy("same");
+
+    TString str = FormString(f);
+
+    TLatex tex;
+    tex.SetTextSize(0.045);
+    tex.SetBit(TLatex::kTextNDC);
+    tex.SetTextAlign(31);
+    tex.DrawLatex(0.89, 0.935, str);
+
+    str = FormString(f, 1);
+    tex.DrawLatex(0.89, 0.83, str);
+
+    str = FormString(f, 2);
+    tex.DrawLatex(0.89, 0.735, str);
+
+    TArrayD res(2);
+    res[0] = f.GetParameter(0);
+    res[1] = f.GetParameter(1);
+    return res;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the final spectrum from:
+//  - collection area
+//  - excess
+//  - correction coefficients
+//  - ontime
+// and display it
+//
+TArrayD MJSpectrum::DisplaySpectrum(MHCollectionArea &area, TH1D &excess, MHEnergyEst &hest, Double_t ontime) const
+{
+    // Create copies of the histograms
+    TH1D collarea(area.GetHEnergy());
+    TH1D spectrum(excess);
+    TH1D weights;
+
+    // Get spill-over corrections from energy estimation
+    hest.GetWeights(weights);  // E_mc/E_est
+
+    // Print effective on-time
+    cout << "Effective On time: " << ontime << "s" << endl;
+
+    // Setup spectrum plot
+    spectrum.SetNameTitle("Preliminary", "N/sm^{2} versus Energy (before unfolding)");
+    spectrum.SetYTitle("N/sm^{2}");
+    spectrum.SetDirectory(NULL);
+    spectrum.SetBit(kCanDelete);
+
+    // Divide by collection are and on-time
+    spectrum.Scale(1./ontime);
+    spectrum.Divide(&collarea);
+
+    // Draw spectrum before applying spill-over corrections
+    TCanvas &c1 = fDisplay->AddTab("Spectrum");
+    c1.Divide(2,2);
+    c1.cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    collarea.DrawCopy();
+
+    c1.cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    TH1D *spec=(TH1D*)spectrum.DrawCopy();
+    //FitSpectrum(*spec);
+
+    c1.cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    weights.DrawCopy();
+
+    // Apply spill-over correction (done't take the errors into account)
+    // They are supposed to be identical with the errors of the
+    // collection area and cancel out.
+    //spectrum.Multiply(&weights);
+    spectrum.SetNameTitle("Flux", "Spectrum");
+    spectrum.SetBit(TH1::kNoStats);
+
+    // Minimum number of excessevents to get 3sigma in 1h
+    TF1 sensl("SensLZA", "85*(x/200)^(-0.55)", 100, 6000);
+    TF1 sensh("SensHZA", "35*(x/200)^(-0.70)", 100, 1000);
+    //sens.SetLineColor(kBlue);
+    //sens.DrawClone("Csame");
+
+    c1.cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    TGraph gsensl;//("Sensitivity LZA", "");
+    TGraph gsensh;//("Sensitivity HZA", "");
+
+    const Double_t sqrton = TMath::Sqrt(ontime/3600.);
+
+    for (int i=0; i<excess.GetNbinsX(); i++)
+    {
+        spectrum.SetBinContent(i+1, spectrum.GetBinContent(i+1)*weights.GetBinContent(i+1));
+        spectrum.SetBinError(i+1,   spectrum.GetBinError(i+1)  *weights.GetBinContent(i+1));
+
+        spectrum.SetBinContent(i+1, spectrum.GetBinContent(i+1)/spectrum.GetBinWidth(i+1)*1000);
+        spectrum.SetBinError(i+1,   spectrum.GetBinError(i+1)/  spectrum.GetBinWidth(i+1)*1000);
+
+        if (collarea.GetBinContent(i+1)<=0)
+            continue;
+
+        const Double_t cen = spectrum.GetBinCenter(i+1);
+        gsensl.SetPoint(gsensl.GetN(), cen, sensl.Eval(cen)*sqrton/spectrum.GetBinWidth(i+1)*1000/collarea.GetBinContent(i+1)/ontime);
+        gsensh.SetPoint(gsensh.GetN(), cen, sensh.Eval(cen)*sqrton/spectrum.GetBinWidth(i+1)*1000/collarea.GetBinContent(i+1)/ontime);
+
+        cout << cen << "   " << sensl.Eval(cen)*sqrton/spectrum.GetBinWidth(i+1)*1000/collarea.GetBinContent(i+1)/ontime;
+        cout <<  "   " << sensh.Eval(cen)*sqrton/spectrum.GetBinWidth(i+1)*1000/collarea.GetBinContent(i+1)/ontime;
+        cout << endl;
+    }
+
+    spectrum.SetMinimum(1e-12);
+    spectrum.SetXTitle("E [GeV]");
+    spectrum.SetYTitle("dN/dE [N/TeVsm^{2}]");
+    spec = (TH1D*)spectrum.DrawCopy();
+
+    TLatex tex;
+    tex.SetTextColor(13);
+
+    TF1 fc("Crab", "6.0e-6*(x/300)^(-2.31-0.26*log10(x/300))", 100, 6000);
+    fc.SetLineStyle(9);
+    fc.SetLineWidth(2);
+    fc.SetLineColor(14);
+    fc.DrawCopy("same");
+
+    tex.DrawLatex(1250, fc.Eval(1250), "Crab/\\Gamma=-2.3");
+
+    TF1 fa("PG1553", "1.8e-6*(x/200)^-4.21", 90, 600);
+    static_cast<const TAttLine&>(fc).Copy(fa);
+    fa.DrawCopy("same");
+
+    tex.SetTextAlign(23);
+    tex.DrawLatex(600, fa.Eval(600), "PG1553/\\Gamma=-4.2");
+
+    gROOT->SetSelectedPad(0);
+
+    gsensl.SetLineStyle(5);
+    gsensl.SetLineColor(14);
+    gsensl.SetLineWidth(2);
+    gsensl.DrawClone("C")->SetBit(kCanDelete);
+
+    gsensh.SetLineStyle(5);
+    gsensh.SetLineColor(14);
+    gsensh.SetLineWidth(2);
+    gsensh.DrawClone("C")->SetBit(kCanDelete);
+
+    // Display dN/dE*E^2 for conveinience
+    fDisplay->AddTab("Check");
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGrid();
+
+    // Calculate Spectrum * E^2
+    for (int i=0; i<spectrum.GetNbinsX(); i++)
+    {
+        const Double_t e = TMath::Sqrt(spectrum.GetBinLowEdge(i+1)*spectrum.GetBinLowEdge(i+2))*1e-3;
+
+        spectrum.SetBinContent(i+1, spectrum.GetBinContent(i+1)*e*e);
+        spectrum.SetBinError(  i+1, spectrum.GetBinError(i+1)  *e*e);
+    }
+
+    for (int i=0; i<gsensl.GetN(); i++)
+    {
+        const Double_t e = gsensl.GetX()[i]*1e-3;
+
+        gsensl.GetY()[i] *= e*e;
+        gsensh.GetY()[i] *= e*e;
+    }
+
+    spectrum.SetName("FluxStd");
+    spectrum.SetMarkerStyle(kFullDotMedium);
+    spectrum.SetTitle("Differential flux times E^{2}");
+    spectrum.SetYTitle("E^{2}·dN/dE [N·TeV/sm^{2}]");
+    spectrum.SetDirectory(0);
+    spectrum.DrawCopy();
+
+    TF1 fc2("Crab*E^2", "x^2*Crab*1e-6", 100, 6000);
+    static_cast<const TAttLine&>(fc).Copy(fc2);
+    fc2.DrawCopy("same");
+
+    TF1 fa2("PG1553*E^2", "x^2*PG1553*1e-6", 100, 6000);
+    static_cast<const TAttLine&>(fc).Copy(fa2);
+    fa2.DrawCopy("same");
+
+    gsensl.DrawClone("C")->SetBit(kCanDelete);
+    gsensh.DrawClone("C")->SetBit(kCanDelete);
+
+    // Fit Spectrum
+    c1.cd(4);
+    return FitSpectrum(*spec);
+
+/*
+    TF1 f("f", "[1]*(x/1e3)^[0]", 10, 3e4);
+    f.SetParameter(0, -2.87);
+    f.SetParameter(1, 1.9e-6);
+    f.SetLineColor(kGreen);
+    spectrum.Fit(&f, "NIM", "", 100, 5000);
+    f.DrawCopy("same");
+
+    const Double_t p0 = f.GetParameter(0);
+    const Double_t p1 = f.GetParameter(1);
+
+    const Double_t e0 = f.GetParError(0);
+    const Double_t e1 = f.GetParError(1);
+
+    const Int_t    np  = TMath::Nint(TMath::Floor(TMath::Log10(p1)));
+    const Double_t exp = TMath::Power(10, np);
+
+    TString str;
+    str += Form("(%.2f#pm%.2f)10^{%d}", p1/exp, e1/exp, np);
+    str += Form("(\\frac{E}{TeV})^{%.2f#pm%.2f}", p0, e0);
+    str += "\\frac{ph}{TeVm^{2}s}";
+
+    TLatex tex;
+    tex.SetTextSize(0.045);
+    tex.SetBit(TLatex::kTextNDC);
+    tex.DrawLatex(0.45, 0.935, str);
+
+    str = Form("\\chi^{2}/NDF=%.2f", f.GetChisquare()/f.GetNDF());
+    tex.DrawLatex(0.70, 0.83, str);
+
+    TArrayD res(2);
+    res[0] = f.GetParameter(0);
+    res[1] = f.GetParameter(1);
+
+    return res;
+  */
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale some image parameter plots using the scale factor and plot them
+// together with the corresponding MC histograms.
+// Called from DisplaySize
+//
+Bool_t MJSpectrum::PlotSame(MStatusArray &arr, MParList &plist, const char *name, const char *tab, const char *plot, Double_t scale) const
+{
+    TString same(name);
+    same += "Same";
+
+    TH1 *h1  = (TH1*)arr.FindObjectInCanvas(name, "TH1F", tab);
+    TH1 *h2  = (TH1*)arr.FindObjectInCanvas(same, "TH1F", tab);
+    if (!h1 || !h2)
+        return kFALSE;
+
+    TObject *obj = plist.FindObject(plot);
+    if (!obj)
+    {
+        *fLog << warn << plot << " not in parameter list... skipping." << endl;
+        return kFALSE;
+    }
+
+    TH1 *h3  = (TH1*)obj->FindObject(name);
+    if (!h3)
+    {
+        *fLog << warn << name << " not found in " << plot << "... skipping." << endl;
+        return kFALSE;
+    }
+
+
+    const MAlphaFitter *fit = (MAlphaFitter*)plist.FindObject("MAlphaFitter");
+    const Double_t ascale = fit ? fit->GetScaleFactor() : 1;
+
+    gPad->SetBorderMode(0);
+    h2->SetLineColor(kBlack);
+    h3->SetLineColor(kBlue);
+    h2->Add(h1, -ascale);
+
+    //h2->Scale(1./ontime);   //h2->Integral());
+    h3->Scale(scale);         //h3->Integral());
+
+    h2->SetMaximum(1.05*TMath::Max(h2->GetMaximum(), h3->GetMaximum()));
+
+    h2 = h2->DrawCopy();
+    h3 = h3->DrawCopy("same");
+
+    // Don't do this on the original object!
+    h2->SetStats(kFALSE);
+    h3->SetStats(kFALSE);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Take a lot of histograms and plot them together in one plot.
+// Calls PlotSame
+//
+Bool_t MJSpectrum::DisplaySize(MParList &plist, Double_t scale) const
+{
+    *fLog << inf << "Reading from file: " << fPathIn << endl;
+
+    TFile file(fPathIn, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fPathIn << endl;
+        return kFALSE;
+    }
+
+    file.cd();
+    MStatusArray arr;
+    if (arr.Read()<=0)
+    {
+        *fLog << "MStatusDisplay not found in file... abort." << endl;
+        return kFALSE;
+    }
+
+    TH1 *excess = (TH1D*)arr.FindObjectInCanvas("Excess", "TH1D", "Hist");
+    if (!excess)
+        return kFALSE;
+
+    // ------------------- Plot excess versus size ------------------- 
+
+    TCanvas &c = fDisplay->AddTab("Excess");
+    c.Divide(3,2);
+    c.cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    excess->SetTitle("Excess events vs Size (data/black, mc/blue)");
+    excess = excess->DrawCopy("E2");
+    // Don't do this on the original object!
+    excess->SetStats(kFALSE);
+    excess->SetMarkerStyle(kFullDotMedium);
+    excess->SetFillColor(kBlack);
+    excess->SetFillStyle(0);
+    excess->SetName("Excess  ");
+    excess->SetDirectory(0);
+
+    TObject *o=0;
+    if ((o=plist.FindObject("ExcessMC")))
+    {
+        TH1 *histsel = (TH1F*)o->FindObject("");
+        if (histsel)
+        {
+            if (scale<0)
+                scale = excess->Integral()/histsel->Integral();
+
+            histsel->Scale(scale);
+            histsel->SetLineColor(kBlue);
+            histsel->SetBit(kCanDelete);
+            histsel = histsel->DrawCopy("E1 same");
+            // Don't do this on the original object!
+            histsel->SetStats(kFALSE);
+          /*
+            fLog->Separator("Kolmogorov Test");
+            histsel->KolmogorovTest(excess, "DX");
+            fLog->Separator("Chi^2 Test");
+            const Double_t p = histsel->Chi2Test(excess, "P");
+
+            TLatex tex;
+            tex.SetBit(TLatex::kTextNDC);
+            tex.DrawLatex(0.75, 0.93, Form("P(\\chi^{2})=%.0f%%", p*100));
+           */
+        }
+    }
+
+    // -------------- Comparison of Image Parameters --------------
+    c.cd(2);
+    PlotSame(arr, plist, "Dist",   "HilSrc",  "MHHilSrcMCPost", scale);
+
+    c.cd(3);
+    PlotSame(arr, plist, "Length", "PostCut", "MHHillasMCPost", scale);
+
+    c.cd(4);
+    PlotSame(arr, plist, "M3l",    "HilExt",  "MHHilExtMCPost", scale);
+
+    c.cd(5);
+    PlotSame(arr, plist, "Conc1",  "NewPar",  "MHNewParMCPost", scale);
+
+    c.cd(6);
+    PlotSame(arr, plist, "Width",  "PostCut", "MHHillasMCPost", scale);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+void MJSpectrum::DisplayCutEfficiency(const MHCollectionArea &area0, const MHCollectionArea &area1) const
+{
+    if (!fDisplay)
+        return;
+
+    const TH1D &trig = area0.GetHEnergy();
+    TH1D &cut = (TH1D&)*area1.GetHEnergy().Clone();
+
+    fDisplay->AddTab("CutEff");
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    cut.Divide(&trig);
+    cut.Scale(100);
+    cut.SetNameTitle("CutEff", "Background Supression: Cut efficiency (after star)");
+    cut.SetYTitle("\\eta [%]");
+    cut.SetDirectory(0);
+    cut.SetMinimum(0);
+    cut.SetMaximum(100);
+    cut.SetBit(kCanDelete);
+    cut.Draw();
+
+    TLine line;
+    line.SetLineColor(kBlue);
+    line.SetLineWidth(2);
+    line.SetLineStyle(kDashed);
+    line.DrawLine(cut.GetBinLowEdge(1), 50, cut.GetBinLowEdge(cut.GetNbinsX()+1), 50);
+}
+
+void MJSpectrum::SetupHistEvtDist(MHn &hist) const
+{
+    hist.AddHist("MMcEvt.fEnergy");
+    hist.InitName("EnergyDist;EnergyEst");
+    hist.InitTitle("Unweighted event distribution (Real statistics);E [GeV];Counts;");
+
+    hist.AddHist("MPointingPos.fZd");
+    hist.InitName("ZdDist;Theta");
+    hist.InitTitle("Unweighted event distribution (Real statistics);Zd [\\circ];Counts;");
+}
+
+void MJSpectrum::SetupHistEnergyEst(MHn &hist) const
+{
+    const char *res = "log10(MEnergyEst.fVal)-log10(MMcEvt.fEnergy)";
+
+    hist.AddHist("MHillas.fSize", res);
+    hist.InitName("ResSize;Size;EnergyResidual");
+    hist.InitTitle(";S [phe];\\Delta lg E;");
+    hist.SetDrawOption("colz profx");
+
+    hist.AddHist("MPointingPos.fZd", res);
+    hist.InitName("ResTheta;Theta;EnergyResidual");
+    hist.InitTitle(";Zd [\\circ];\\Delta lg E;");
+    hist.SetDrawOption("colz profx");
+
+    hist.AddHist("MNewImagePar.fLeakage1", res);
+    hist.InitName("ResLeak;Leakage;EnergyResidual");
+    hist.InitTitle(";Leak;\\Delta lg E;");
+    hist.SetDrawOption("colz profx");
+
+    hist.AddHist("MHillasSrc.fDist*3.37e-3", res);
+    hist.InitName("ResDist;Dist;EnergyResidual");
+    hist.InitTitle(";D [\\circ];\\Delta lg E;");
+    hist.SetDrawOption("colz profx");
+}
+
+void MJSpectrum::SetupHistDisp(MHn &hist) const
+{
+    const char *res = "-Disp.fVal*sign(MHillasSrc.fCosDeltaAlpha)-MHillasSrc.fDist*3.37e-3";
+
+    hist.AddHist("MHillas.fSize", res);
+    hist.InitName("ResSize;Size;ResidualDist");
+    hist.InitTitle(";S [phe];Disp-Dist [\\circ];");
+    hist.SetDrawOption("colz profx");
+
+    hist.AddHist("MPointingPos.fZd", res);
+    hist.InitName("ResTheta;Theta;ResidualDist");
+    hist.InitTitle(";Zd [\\circ];Disp-Dist [\\circ];");
+    hist.SetDrawOption("colz profx");
+
+    hist.AddHist("MNewImagePar.fLeakage1", res);
+    hist.InitName("ResLeak;Leakage;ResidualDist");
+    hist.InitTitle(";Leak;Disp-Dist [\\circ];");
+    hist.SetDrawOption("colz profx");
+
+    hist.AddHist("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/3.37e-3", res);
+    hist.InitName("ResSlope;Slope;ResidualDist");
+    hist.InitTitle(";Slope;Disp-Dist [\\circ];");
+    hist.SetDrawOption("colz profx");
+}
+
+void MJSpectrum::SetupHistEnergyRes(MHn &hist) const
+{
+    hist.AddHist("MEnergyEst.fVal", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hist.InitName("ResEest;EnergyEst;");
+    hist.InitTitle(";E_{est} [GeV];Resolution (E_{mc}/E_{est}-1)^{2};");
+
+    //hist.AddHist("MMcEvt.fEnergy", "(MEnergyEst.fVal/MMcEvt.fEnergy-1)^2", MH3::kProfile);
+    //hist.InitName("ResEmc;EnergyEst;");
+    //hist.InitTitle(";E_{mc} [GeV];Resolution (E_{est}/E_{mc}-1)^{2};");
+    hist.AddHist("MHillas.fSize", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hist.InitName("ResSize;Size;");
+    hist.InitTitle(";S [phe];Resolution (E_{mc}/E_{est}-1)^{2};");
+
+    hist.AddHist("MPointingPos.fZd", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hist.InitName("ResTheta;Theta;");
+    hist.InitTitle(";\\Theta [\\circ];Resolution (E_{mc}/E_{est}-1)^{2};");
+
+    hist.AddHist("MMcEvt.fImpact/100", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hist.InitName("ResImpact;Impact;");
+    hist.InitTitle(";I [m];Resolution (E_{mc}/E_{est}-1)^{2};");
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup write to write:
+//     container         tree       optional?
+//  --------------     ----------  -----------
+//   "MHillas"      to  "Events"
+//   "MHillasSrc"   to  "Events"
+//   "Hadronness"   to  "Events"       yes
+//   "MEnergyEst"   to  "Events"       yes
+//   "DataType"     to  "Events"
+//
+void MJSpectrum::SetupWriter(MWriteRootFile *write/*, const char *name*/) const
+{
+    if (!write)
+        return;
+
+    //write->SetName(name);
+    write->AddContainer("MHillas",        "Events");
+    write->AddContainer("MHillasSrc",     "Events");
+    write->AddContainer("MHillasExt",     "Events");
+    //write->AddContainer("MPointingPos",   "Events");
+    write->AddContainer("MHillasSrcAnti", "Events", kFALSE);
+    write->AddContainer("MImagePar",      "Events", kFALSE);
+    write->AddContainer("MNewImagePar",   "Events", kFALSE);
+    write->AddContainer("MNewImagePar2",  "Events", kFALSE);
+    write->AddContainer("Hadronness",     "Events", kFALSE);
+    write->AddContainer("MSrcPosCam",     "Events", kFALSE);
+    write->AddContainer("MSrcPosAnti",    "Events", kFALSE);
+    write->AddContainer("ThetaSquared",   "Events", kFALSE);
+    write->AddContainer("OpticalAxis",    "Events", kFALSE);
+    write->AddContainer("Disp",           "Events", kFALSE);
+    write->AddContainer("Ghostbuster",    "Events", kFALSE);
+    write->AddContainer("MEnergyEst",     "Events", kFALSE);
+    write->AddContainer("MTime",          "Events", kFALSE);
+    write->AddContainer("MMcEvt",         "Events", kFALSE);
+    write->AddContainer("MWeight",        "Events");
+    write->AddContainer("DataType",       "Events");
+    write->AddContainer("FileId",         "Events");
+    write->AddContainer("EvtNumber",      "Events");
+}
+
+Bool_t MJSpectrum::Process(const MDataSet &set)
+{
+    if (!set.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(GetPathOut()))
+        return kFALSE;
+
+    if (!CheckEnv())
+        return kFALSE;
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Compile Monte Carlo sample (dataset " << set.GetBaseName() << ")" << endl;
+    *fLog << endl;
+
+    if (fDisplay)
+        fDisplay->SetWindowName(fName);
+
+    // Setup everything which is read from the ganymed file
+    MBinning bins1("BinningAlpha");
+    MBinning bins2("BinningEnergyEst");
+    MBinning bins3("BinningTheta");
+    MBinning bins4("BinningFalseSource");
+    MBinning bins5("BinningWidth");
+    MBinning bins6("BinningLength");
+    MBinning bins7("BinningDist");
+    MBinning bins8("BinningM3Long");
+    MBinning bins9("BinningM3Trans");
+    MBinning bins0("BinningSlope");
+    MBinning binsa("BinningAsym");
+    MBinning binsb("BinningConc1");
+
+    MEnv env("", "ganymed.rc");
+
+    MAlphaFitter fit;
+
+    MParList plist;
+    plist.AddToList(&bins0);
+    plist.AddToList(&bins1);
+    plist.AddToList(&bins3);
+    plist.AddToList(&bins4);
+    plist.AddToList(&bins5);
+    plist.AddToList(&bins6);
+    plist.AddToList(&bins7);
+    plist.AddToList(&bins8);
+    plist.AddToList(&bins9);
+    plist.AddToList(&binsa);
+    plist.AddToList(&binsb);
+    plist.AddToList(&fit);
+
+    // Read from the ganymed file
+    TH1D htheta, size;
+    Float_t ontime = ReadInput(plist, htheta, size);
+    if (ontime<0)
+    {
+        *fLog << err << GetDescriptor() << ": Could not determine effective on time..." << endl;
+        return kFALSE;
+    }
+
+    // Set Zenith angle binning to binning from the ganymed-file
+    bins3.SetEdges(htheta, 'x');
+
+    // Read energy binning from resource file
+    if (!CheckEnv(bins2))
+    {
+        *fLog << err << "ERROR - Reading energy binning from resources failed." << endl;
+        return kFALSE;
+    }
+    plist.AddToList(&bins2); // For later use in MC processing
+
+    // -------------- Fill excess events versus energy ---------------
+
+    TH1D excess;
+
+    if (fForceOnTimeFit)
+    {
+        // Refill excess histogram to determine the excess events
+        // If we use the eff. on-time fit we have to loop over the data first
+        // This is not really desired, because if something is wrong with
+        // the Monte Carlos the program runs quite long before it fails
+        if (!Refill(plist, excess))
+            return kFALSE;
+
+        // Print the setup and result of the MAlphaFitter, print used cuts
+        PrintSetup(fit);
+
+        // ------------ On user request redo eff. on-time fit ------------
+        const MHEffectiveOnTime *htime = (MHEffectiveOnTime*)plist.FindObject("MHEffectiveOnTime");
+        if (!htime)
+        {
+            // This should never happen, bt you never know
+            *fLog << err;
+            *fLog << "ERROR - Use of new effective on-time fit requested for on-time determination," << endl;
+            *fLog << "        but MHEffectiveOnTime not found in parameter list... aborting." << endl;
+            return kFALSE;
+        }
+
+        const TH1D &h = htime->GetHEffOnTheta();
+        /*
+        if (!htime->IsConsistent() || h.GetNbinsX()!=htheta.GetNbinsX())
+        {
+            *fLog << err << "ERROR - Effective on-time from newly filles MHEffectiveOnTime (Tab='OnTime) invalid... aborting." << endl;
+            return kFALSE;
+        }*/
+
+        *fLog << inf;
+        *fLog << "Using eff. on-time from new MHEffectiveOnTime (see also 'OnTime')" << endl;
+        *fLog << "   Orig. value: " << ontime << "s" << endl;
+
+        // Copy ontime from newly filled and fitted eff on-time histogram
+        ontime = htime->GetEffOnTime();
+
+        *fLog << "   New   value: " << ontime << "s" << endl;
+
+        h.Copy(htheta);           // Copy contents of newly filled hist into on-time vs. theta
+        htheta.SetName("Theta");  // Copy overwrites the name needed in DisplayResult
+        htheta.SetDirectory(0);   // Remove from global directory added by SetName
+    }
+
+    // ---------------------------------------------------------------
+
+    // Initialize weighting to a new spectrum as defined in the resource file
+    MMcSpectrumWeight weight;
+    if (!InitWeighting(set, weight))
+        return kFALSE;
+
+    // Print Theta and energy binning for cross-checks
+    *fLog << all << endl;
+    bins2.Print();
+    bins3.Print();
+
+    // Now we read the MC distribution as produced by corsika
+    // vs zenith angle and energy.
+    // Weight for the new energy spectrum defined in MMcSpectumWeight
+    // are applied.
+    // Also correction for different lower energy bounds and
+    // different production areas (impact parameters) are applied.
+    TH2D hist;
+    hist.UseCurrentStyle();
+    MH::SetBinning(hist, bins3, bins2);
+    if (!ReadOrigMCDistribution(set, hist, weight))
+        return kFALSE;
+
+    // Check if user has closed the display
+    if (!fDisplay)
+        return kTRUE;
+
+    // Display histograms and calculate za-weights into htheta
+    GetThetaDistribution(htheta, hist);
+
+    // Give the zenith angle weights to the weighting task
+    weight.SetWeightsZd(&htheta);
+
+    // No we apply the the zenith-angle-weights to the corsika produced
+    // MC distribution. Unfortunately this must be done manually
+    // because we are multiplying column by column
+    for (int y=0; y<=hist.GetNbinsY()+1; y++)
+        for (int x=0; x<=hist.GetNbinsX()+1; x++)
+        {
+            hist.SetBinContent(x, y, hist.GetBinContent(x, y)*htheta.GetBinContent(x));
+            hist.SetBinError(x, y,   hist.GetBinError(x, y)  *htheta.GetBinContent(x));
+        }
+
+    // Display the resulting distribution and check it matches
+    // the observation time distribution (this could be false
+    // for example if you miss MCs of some zenith angles, which you have
+    // data for)
+    if (!DisplayResult(hist))
+        return kFALSE;
+
+    // Refill excess histogram to determine the excess events
+    if (!fForceOnTimeFit)
+    {
+        if (!Refill(plist, excess))
+            return kFALSE;
+
+        // Print the setup and result of the MAlphaFitter, print used cuts
+        PrintSetup(fit);
+    }
+
+    // ------------------------- Final loop --------------------------
+
+    *fLog << endl;
+    fLog->Separator("Calculate efficiencies");
+    *fLog << endl;
+
+    MTaskList tlist2;
+    plist.AddToList(&tlist2);
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    if (!set.AddFilesOn(read))
+        return kFALSE;
+
+    // Selector to get correct (final) theta-distribution
+    //temp1.SetXTitle("MPointingPos.fZd");
+    //
+    //MH3 mh3(temp1);
+    //
+    //MFEventSelector2 sel2(mh3);
+    //sel2.SetHistIsProbability();
+    //
+    //MContinue contsel(&sel2);
+    //contsel.SetInverted();
+
+    // Get correct source position
+    //MSrcPosCalc calc;
+
+    // Calculate corresponding Hillas parameters
+    //MHillasCalc hcalc1;
+    //MHillasCalc hcalc2("MHillasCalcAnti");
+    //hcalc1.SetFlags(MHillasCalc::kCalcHillasSrc);
+    //hcalc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+    //hcalc2.SetNameHillasSrc("MHillasSrcAnti");
+    //hcalc2.SetNameSrcPosCam("MSrcPosAnti");
+
+    // Fill collection area and energy estimator (unfolding)
+    // Make sure to use the same binning for MHCollectionArea and MHEnergyEst
+    MHCollectionArea area0("TriggerArea");
+    MHCollectionArea area1;
+    area0.SetHistAll(hist);
+    area1.SetHistAll(hist);
+
+    MHEnergyEst      hest;
+
+    MFillH fill30(&area0, "", "FillTriggerArea");
+    MFillH fill31(&area1, "", "FillCollectionArea");
+    MFillH fill4(&hest,   "", "FillEnergyEst");
+    MFillH fill5("MHThreshold", "", "FillThreshold");
+    fill30.SetWeight();
+    fill31.SetWeight();
+    fill4.SetWeight();
+    fill5.SetWeight();
+    fill30.SetNameTab("TrigArea");
+    fill31.SetNameTab("ColArea");
+    fill4.SetNameTab("E-Est");
+    fill5.SetNameTab("Threshold");
+
+/*
+    MH3 henergy("MMcEvt.fEnergy");
+    henergy.SetName("EventDist;EnergyEst");
+    henergy.SetTitle("Unweighted event distribution (Real statistics);E [GeV];Counts;");
+    henergy.Sumw2();
+    */
+
+    // ---------------------------------------------------------
+
+    MBinning binsA(50, 10, 100000, "BinningSize",           "log");
+    MBinning binsC(50,  0, 0.3,    "BinningLeakage",        "lin");
+    MBinning binsB(51, -1, 1,      "BinningEnergyResidual", "lin");
+    MBinning binsD(51, -1, 1,      "BinningResidualDist",   "lin");
+    MBinning binsI(16,  0, 800,    "BinningImpact",         "lin");
+
+    plist.AddToList(&binsA);
+    plist.AddToList(&binsB);
+    plist.AddToList(&binsC);
+    plist.AddToList(&binsD);
+    plist.AddToList(&binsI);
+
+    MHn heest("Energy", "Energy Residual (lg E_{est} - lg E_{mc})");
+    SetupHistEnergyEst(heest);
+
+    MHn hdisp("Disp", "Dist residual (Disp-Dist)");
+    SetupHistDisp(hdisp);
+
+    MHn henergy("EvtDist");
+    SetupHistEvtDist(henergy);
+
+    MHn heres("EnergyRes");
+    SetupHistEnergyRes(heres);
+
+    MFillH fill4b(&heest, "", "FillEnergyResidual");
+    fill4b.SetWeight();
+
+    MFillH fill4c(&hdisp, "", "FillDispResidual");
+    fill4c.SetWeight();
+
+    MFillH fill4d(&heres, "", "FillEnergyResolution");
+    fill4d.SetWeight();
+
+    MFDataPhrase fdisp("Disp.fVal*sign(MHillasSrc.fCosDeltaAlpha)<0", "FilterDisp");
+    fill4c.SetFilter(&fdisp);
+
+    // ---------------------------------------------------------
+
+    MH3 hsize("MHillas.fSize");
+    hsize.SetName("ExcessMC");
+    hsize.Sumw2();
+
+    MBinning bins(size, "BinningExcessMC");
+    plist.AddToList(&hsize);
+    plist.AddToList(&bins);
+
+    // ---------------------------------------------------------
+
+    MFillH fillsp("MHSrcPosCam", "MSrcPosCam", "FillSrcPosCam");
+    MFillH fill0a(&henergy, "", "FillEventDist");
+    MFillH fill1a("MHHillasMCPre  [MHHillas]",      "MHillas",      "FillHillasPre");
+    MFillH fill2a("MHHillasMCPost [MHHillas]",      "MHillas",      "FillHillasPost");
+    MFillH fill3a("MHVsSizeMCPost [MHVsSize]",      "MHillasSrc",   "FillVsSizePost");
+    MFillH fill4a("MHHilExtMCPost [MHHillasExt]",   "MHillasSrc",   "FillHilExtPost");
+    MFillH fill5a("MHHilSrcMCPost [MHHillasSrc]",   "MHillasSrc",   "FillHilSrcPost");
+    MFillH fill6a("MHImgParMCPost [MHImagePar]",    "MImagePar",    "FillImgParPost");
+    MFillH fill7a("MHNewParMCPost [MHNewImagePar]", "MNewImagePar", "FillNewParPost");
+    MFillH fill8a("ExcessMC       [MH3]",           "",             "FillExcessMC");
+    fillsp.SetNameTab("SrcPos");
+    fill0a.SetNameTab("EvtDist");
+    fill1a.SetNameTab("PreCut");
+    fill2a.SetNameTab("PostCut");
+    fill3a.SetNameTab("VsSize");
+    fill4a.SetNameTab("HilExt");
+    fill5a.SetNameTab("HilSrc");
+    fill6a.SetNameTab("ImgPar");
+    fill7a.SetNameTab("NewPar");
+    fill8a.SetBit(MFillH::kDoNotDisplay);
+    fill1a.SetWeight();
+    fill2a.SetWeight();
+    fill3a.SetWeight();
+    fill4a.SetWeight();
+    fill5a.SetWeight();
+    fill6a.SetWeight();
+    fill7a.SetWeight();
+    fill8a.SetWeight();
+    fillsp.SetWeight();
+
+    // FIXME: To be done: A task checking the lower 1% after the lower
+    // energy limit!
+
+    MTaskEnv taskenv0("CalcDisp");
+    taskenv0.SetDefault(fCalcDisp);
+
+    MTaskEnv taskenv1("CalcHadronness");
+    taskenv1.SetDefault(fCalcHadronness);
+
+    MEnergyEstimate est;
+    MTaskEnv taskenv2("EstimateEnergy");
+    taskenv2.SetDefault(fEstimateEnergy ? fEstimateEnergy : &est);
+
+    MWriteRootFile write(GetPathOut());
+    SetupWriter(&write);
+
+    MParameterI *par = (MParameterI*)plist.FindCreateObj("MParameterI", "DataType");
+    if (!par)
+        return kFALSE;
+    par->SetVal(2);
+
+    // Not really necessary but for sanity
+    TObject *cam = plist.FindObject("MSrcPosCam");
+    if (cam)
+        cam->Clear();
+
+    tlist2.AddToList(&read);
+    // If no weighting should be applied but the events should
+    // be thrown away according to the theta distribution
+    // it is enabled here
+    //if (!fRawMc && fNoThetaWeights)
+    //    tlist2.AddToList(&contsel);
+    //tlist2.AddToList(&calc);
+    //tlist2.AddToList(&hcalc1);
+    //tlist2.AddToList(&hcalc2);
+    tlist2.AddToList(&weight);
+    tlist2.AddToList(&fillsp);
+    tlist2.AddToList(&fill1a);
+    tlist2.AddToList(&fill30);
+    tlist2.AddToList(fCutQ);
+    tlist2.AddToList(fCut0);
+    tlist2.AddToList(&taskenv0);
+    tlist2.AddToList(&taskenv1);
+    tlist2.AddToList(&fdisp);
+    tlist2.AddToList(&fill4c);
+    tlist2.AddToList(fCut1);
+    tlist2.AddToList(fCutS);
+    tlist2.AddToList(fCut2);
+    tlist2.AddToList(fCut3);
+    tlist2.AddToList(&taskenv2);
+    if (!GetPathOut().IsNull())
+        tlist2.AddToList(&write);
+    tlist2.AddToList(&fill31);
+    tlist2.AddToList(&fill4);
+    tlist2.AddToList(&fill4b);
+    tlist2.AddToList(&fill4d);
+    tlist2.AddToList(&fill5);
+    tlist2.AddToList(&fill0a);
+    tlist2.AddToList(&fill2a);
+    tlist2.AddToList(&fill3a);
+    tlist2.AddToList(&fill4a);
+    tlist2.AddToList(&fill5a);
+    tlist2.AddToList(&fill6a);
+    tlist2.AddToList(&fill7a);
+    tlist2.AddToList(&fill8a);
+    //tlist2.AddToList(&fill9a);
+
+    // by setting it here it is distributed to all consecutive tasks
+    tlist2.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    MEvtLoop loop2(fName); // ***** fName *****
+    loop2.SetParList(&plist);
+    loop2.SetDisplay(fDisplay);
+    loop2.SetLogStream(fLog);
+
+    if (!SetupEnv(loop2))
+        return kFALSE;
+
+    if (!loop2.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Processing of MC-data failed." << endl;
+        return kFALSE;
+    }
+
+    if (!loop2.GetDisplay())
+    {
+        *fLog << err << GetDescriptor() << ": Execution stopped by user." << endl;
+        return kFALSE;
+    }
+
+    fLog->Separator("Energy Estimator");
+    if (plist.FindObject("EstimateEnergy"))
+        plist.FindObject("EstimateEnergy")->Print();
+
+    fLog->Separator("Spectrum");
+
+    // -------------------------- Spectrum ----------------------------
+
+    // Calculate and display spectrum (N/TeVsm^2 at 1TeV)
+    TArrayD res(DisplaySpectrum(area1, excess, hest, ontime));
+
+    // Spectrum fitted (convert res[1] from TeV to GeV)
+    TF1 flx("flx", MString::Format("%e*pow(x/500, %f)", res[1]/500, res[0]).Data());
+
+    // Number of events this spectrum would produce per s and m^2
+    Double_t n = flx.Integral(weight.GetEnergyMin(), weight.GetEnergyMax());
+
+    // scale with effective collection area to get the event rate (N/s)
+    // scale with the effective observation time to absolute observed events
+    n *= area1.GetCollectionAreaAbs()*ontime; // N
+
+    // Now calculate the scale factor from the number of events
+    // produced and the number of events which should have been
+    // observed with our telescope in the time ontime
+    const Double_t scale = n/area1.GetEntries();
+
+    // Print normalization constant
+    cout << "MC normalization factor:  " << scale << endl;
+
+    // Display cut efficiency
+    DisplayCutEfficiency(area0, area1);
+
+    // Overlay normalized plots
+    DisplaySize(plist, scale);
+
+    // check if output should be written
+    if (!fPathOut.IsNull())
+    {
+        TNamed ganame("ganymed.root", fPathIn.Data());
+        TNamed cmdline("CommandLine", fCommandLine.Data());
+
+        // Write the output
+        TObjArray cont;
+        cont.Add(&env);                           // ganymed.rc
+        cont.Add(const_cast<TEnv*>(GetEnv()));    // sponde.rc
+        cont.Add(const_cast<MDataSet*>(&set));    // Dataset
+        cont.Add(plist.FindObject("MAlphaFitter"));
+        cont.Add(&area0);
+        cont.Add(&area1);
+        cont.Add(&hest);
+        cont.Add(&ganame);
+        cont.Add(&cmdline);
+
+        if (fDisplay)
+            cont.Add(fDisplay);
+
+        if (!WriteContainer(cont, "", GetPathOut().IsNull()?"RECREATE":"UPDATE"))
+        {
+            *fLog << err << GetDescriptor() << ": Writing result failed." << endl;
+            return kFALSE;
+        }
+    }
+
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJSpectrum.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJSpectrum.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJSpectrum.h	(revision 17960)
@@ -0,0 +1,90 @@
+#ifndef MARS_MJSpectrum
+#define MARS_MJSpectrum
+
+#ifndef MARS_MJob
+#include <MJob.h>
+#endif
+
+class TF1;
+class TH1;
+class TH1D;
+class TH2D;
+
+class MH3;
+class MHn;
+class MTask;
+class MParList;
+class MDataSet;
+class MHEnergyEst;
+class MAlphaFitter;
+class MStatusArray;
+class MWriteRootFile;
+class MHCollectionArea;
+class MMcSpectrumWeight;
+
+class MJSpectrum : public MJob
+{
+private:
+    MTask *fCutQ;
+    MTask *fCut0;
+    MTask *fCut1;
+    MTask *fCut2;
+    MTask *fCut3;
+    MTask *fCutS;
+    MTask *fEstimateEnergy;
+    MTask *fCalcHadronness;
+    MTask *fCalcDisp;
+
+    Bool_t fForceTheta;
+    Bool_t fForceRunTime;
+    Bool_t fForceOnTimeFit;
+
+    // Setup Histograms
+    void SetupHistEvtDist(MHn &hist) const;
+    void SetupHistEnergyEst(MHn &hist) const;
+    void SetupHistDisp(MHn &hist) const;
+    void SetupHistEnergyRes(MHn &hist) const;
+
+    // Read Input
+    Bool_t   ReadTask(MTask* &task, const char *name, Bool_t mustexist=kTRUE) const;
+    Float_t  ReadInput(MParList &plist, TH1D &h1, TH1D &size);
+    Bool_t   AnalyzeMC(const MDataSet &set, Float_t &impactmax, Float_t &emin/*, Float_t emax*/) const;
+    Bool_t   ReadOrigMCDistribution(const MDataSet &set, TH1 &h, MMcSpectrumWeight &w) const;
+    void     GetThetaDistribution(TH1D &temp1, TH2D &temp2) const;
+    TString  GetHAlpha() const;
+    Bool_t   Refill(MParList &plist, TH1D &h) /*const*/;
+    Bool_t   InitWeighting(const MDataSet &set, MMcSpectrumWeight &w) const;
+
+    // Write output
+    void     SetupWriter(MWriteRootFile *write/*, const char *name*/) const;
+
+    // Display Output
+    void    PrintSetup(const MAlphaFitter &fit) const;
+    Bool_t  DisplayResult(const TH2D &mh1) const;
+    //Bool_t  IntermediateLoop(MParList &plist, MH3 &h1, TH1D &temp1, const MDataSet &set, MMcSpectrumWeight &w) const;
+    TArrayD FitSpectrum(TH1D &spectrum) const;
+    TArrayD DisplaySpectrum(MHCollectionArea &area, TH1D &excess, MHEnergyEst &hest, Double_t ontime) const;
+    Bool_t  DisplaySize(MParList &plist, Double_t scale) const;
+    void    DisplayCutEfficiency(const MHCollectionArea &area0, const MHCollectionArea &area1) const;
+    Bool_t  PlotSame(MStatusArray &arr, MParList &plist, const char *name, const char *tab, const char *plot, Double_t scale) const;
+
+public:
+    MJSpectrum(const char *name=NULL, const char *title=NULL);
+    ~MJSpectrum();
+
+    Bool_t Process(const MDataSet &set);
+
+    void ForceTheta(Bool_t b=kTRUE)   { fForceTheta=b; }
+    void ForceRunTime(Bool_t b=kTRUE) { fForceRunTime=b; }
+    void ForceOnTimeFit(Bool_t b=kTRUE) { fForceOnTimeFit=b; }
+
+    void SetEnergyEstimator(const MTask *task);
+
+    static TString FormFloat(Double_t d);
+    static TString FormFlux(const TF1 &f, const char *unit);
+    static TString FormString(const TF1 &f, Byte_t type=0);
+
+    ClassDef(MJSpectrum, 0) // Proh'gram to calculate spectrum
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJStar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJStar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJStar.cc	(revision 17960)
@@ -0,0 +1,583 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJStar
+//
+// Resource file entries are case sensitive!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJStar.h"
+
+#include <TEnv.h>
+#include <TFile.h>
+
+// Core
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+// Histograms
+#include "MHSectorVsTime.h"
+#include "MHEffectiveOnTime.h"
+#include "MHCamEvent.h"
+#include "MBinning.h"
+
+///NEEWWWW
+#include "MH3.h"
+
+// Tasks
+#include "MReadReports.h"
+#include "MReadMarsFile.h"
+#include "MContinue.h"
+#include "MGeomApply.h"
+#include "MEventRateCalc.h"
+#include "MImgCleanStd.h"
+#include "MSrcPosCalc.h"
+#include "MSrcPosCorrect.h"
+#include "MHillasCalc.h"
+#include "MMuonSearchParCalc.h"
+#include "MMuonCalibParCalc.h"
+#include "MFillH.h"
+#include "MWriteRootFile.h"
+
+// Filter
+#include "MFDataPhrase.h"
+#include "MFTriggerPattern.h"
+#include "MFilterList.h"
+#include "MFDataMember.h"
+#include "MFDeltaT.h"
+#include "MFSoftwareTrigger.h"
+
+// Parameter container
+#include "MMuonSetup.h"
+#include "MObservatory.h"
+//#include "MTriggerPattern.h"
+#include "MPointingPosCalc.h"
+
+ClassImp(MJStar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fRuns to 0, fExtractor to NULL, fDataCheck to kFALSE
+//
+MJStar::MJStar(const char *name, const char *title) : fMuonAnalysis(kTRUE)
+{
+    fName  = name  ? name  : "MJStar";
+    fTitle = title ? title : "Standard analysis and reconstruction";
+}
+
+Bool_t MJStar::CheckEnvLocal()
+{
+    DisableMuonAnalysis(!GetEnv("MuonAnalysis", fMuonAnalysis));
+    return kTRUE;
+}
+
+Bool_t MJStar::WriteResult()
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    TObjArray cont;
+    cont.Add(const_cast<TEnv*>(GetEnv()));
+    cont.Add(const_cast<MSequence*>(&fSequence));
+
+    TNamed cmdline("CommandLine", fCommandLine.Data());
+    cont.Add(&cmdline);
+
+    if (fDisplay)
+    {
+        TString title = "--  Star: ";
+        title += fSequence.GetSequence();
+        title += "  --";
+        fDisplay->SetTitle(title, kFALSE);
+
+        cont.Add(fDisplay);
+    }
+
+    const TString oname = Form("star%08d.root", fSequence.GetSequence());
+    return WriteContainer(cont, oname, "RECREATE");
+}
+
+Bool_t MJStar::Process()
+{
+    if (!fSequence.IsValid())
+    {
+        *fLog << err << "ERROR - Sequence invalid!" << endl;
+        return kFALSE;
+    }
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate image parameters of sequence ";
+    *fLog << fSequence.GetFileName() << endl;
+    *fLog << endl;
+
+    if (!CheckEnv())
+        return kFALSE;
+ 
+    // --------------------------------------------------------------------------------
+
+    MDirIter iter;
+    if (fSequence.GetRuns(iter, MSequence::kCalibrated)<=0)
+    {
+        *fLog << err << "ERROR - Sequence valid but without files." << endl;
+        return kFALSE;
+    }
+
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    MMuonSetup muonsetup;
+    plist.AddToList(&muonsetup);
+
+    // Setup binnings for muon analysis
+    MBinning bins1("BinningRadius");
+    MBinning bins2("BinningArcWidth");
+    MBinning bins3("BinningRingBroadening");
+    MBinning bins4("BinningSizeVsArcRadius");
+    MBinning bins5("BinningMuonWidth");
+    MBinning bins6("BinningArcPhi");
+    MBinning binsd("BinningDist");
+    plist.AddToList(&bins1);
+    plist.AddToList(&bins2);
+    plist.AddToList(&bins3);
+    plist.AddToList(&bins4);
+    plist.AddToList(&bins5);
+    plist.AddToList(&bins6);
+    plist.AddToList(&binsd);
+
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadReports readreal;
+    readreal.AddTree("Events", "MTime.", MReadReports::kMaster);
+    readreal.AddTree("Drive",            MReadReports::kRequired);
+    readreal.AddTree("Starguider",       MReadReports::kRequired);
+    readreal.AddTree("Camera",           MReadReports::kRequired);
+    readreal.AddTree("Currents");
+    readreal.AddTree("CC");
+    readreal.AddTree("Rec");
+    readreal.AddTree("Trigger");
+    readreal.AddTree("Pyrometer");
+    readreal.AddFiles(iter);
+
+    MReadMarsFile readmc("Events");
+    readmc.DisableAutoScheme();
+    readmc.AddFiles(iter);
+
+    // ------------------ Setup general tasks ----------------
+
+    MFDeltaT               fdeltat;
+    MContinue              cont(&fdeltat, "FilterDeltaT", "Filter events with wrong timing");
+    cont.SetInverted();
+
+    MGeomApply             apply; // Only necessary to craete geometry
+    MEventRateCalc         rate;
+    rate.SetNumEvents(1200);
+
+    MFSoftwareTrigger swtrig;
+    MContinue contsw(&swtrig, "FilterSwTrigger", "Software trigger");
+    contsw.SetInverted();
+
+    MImgCleanStd           clean;
+    clean.SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+
+    MSrcPosCalc poscalc;
+    MHillasCalc hcalc;
+    hcalc.Disable(MHillasCalc::kCalcConc);
+
+    // ------------------ Setup histograms and fill tasks ----------------
+    MHCamEvent evt0a(0, "Cleaned",   "Average signal after Cleaning;;S [phe]");
+    MHCamEvent evt0c(0, "Sparkless", "Average signal after Cleaning and Spark cuts;;S [phe]");
+    MHCamEvent evt0d(0, "Sparks",    "Average signal after Cleaning for Spark cuts;;S [phe]");
+    MHCamEvent evt0b(0, "UsedPix",   "Fraction of Events in which Pixels are used;;Fraction");
+    evt0a.SetErrorSpread(kFALSE);
+    evt0b.SetErrorSpread(kFALSE);
+    evt0c.SetErrorSpread(kFALSE);
+    evt0d.SetErrorSpread(kFALSE);
+    evt0b.SetThreshold(0);
+
+    MFillH fillvs("MHRate",           "MTime",           "FillEventRate");
+    MFillH fillp1("MHPointing",       "MTimeDrive",      "FillDrive");
+    MFillH fillp2("MHPointing",       "MTimeStarguider", "FillStarguider");
+    fillp1.SetBit(MFillH::kDoNotDisplay);
+    fillp1.SetBit(MFillH::kCanSkip);
+    fillp2.SetBit(MFillH::kCanSkip);
+
+    // Needed in parameter list for ReadEnv
+    MHEffectiveOnTime hontime;
+    plist.AddToList(&hontime);
+
+    MFillH fill0a(&evt0a,             "MSignalCam",      "FillSignalCam");
+    MFillH fill0b(&evt0b,             "MSignalCam",      "FillCntUsedPixels");
+    MFillH fill0c(&evt0c,             "MSignalCam",      "FillSignalCamSparkless");
+    MFillH fill0d(&evt0d,             "MSignalCam",      "FillSignalCamSparks");
+    MFillH fill1("MHHillas",          "MHillas",         "FillHillas");
+    MFillH fill2("MHHillasExt",       "",                "FillHillasExt");
+    MFillH fill3("MHHillasSrc",       "MHillasSrc",      "FillHillasSrc");
+    MFillH fill4("MHImagePar",        "MImagePar",       "FillImagePar");
+    MFillH fill5("MHNewImagePar",     "MNewImagePar",    "FillNewImagePar");
+    MFillH fill9("MHEffectiveOnTime", "MTime",           "FillEffOnTime");
+
+    //fillvs.SetNameTab("Rate");
+    fill9.SetNameTab("EffOnTime");
+    fill0c.SetNameTab("Sparkless");
+    fill0d.SetNameTab("Sparks");
+
+    // FIXME: This should be replaced by a cut working for all triggers!
+    MTriggerPattern par;   // An empty trigger pattern for older files
+    plist.AddToList(&par); // without MTriggerPattern stored in the file
+
+    // For the effective on-time calculation and the muon statistics
+    // we don't want SUM-only events
+    MFTriggerPattern fsum;
+    fsum.SetDefault(kTRUE);
+    fsum.DenyAll();
+    fsum.RequireTriggerLvl1();
+    fsum.AllowTriggerLvl2();
+    fsum.AllowSumTrigger();
+    fill9.SetFilter(&fsum);
+
+    // Plot the trigger pattern rates vs. run-number
+    MH3 hrate("MRawRunHeader.GetFileID", "MTriggerPattern.GetUnprescaled");
+    if (fSequence.IsMonteCarlo())
+        hrate.SetWeight("100./MMcRunHeader.fNumSimulatedShowers");
+    else
+        hrate.SetWeight("1./TMath::Max(MRawRunHeader.GetRunLength,1)");
+    hrate.SetName("Rate");
+    hrate.SetTitle("Event rate after cleaning [Hz];File Id;Trigger Type;");
+    hrate.InitLabels(MH3::kLabelsX);
+    hrate.DefaultLabelY("ERROR");
+    hrate.DefineLabelY( 0, "0");        //  0: No pattern
+    hrate.DefineLabelY( 1, "Trig");     //  1: Lvl1
+    hrate.DefineLabelY( 4, "Trig");     //  4: Lvl2
+    hrate.DefineLabelY( 5, "Trig");     //     Lvl2+Lvl1
+    hrate.DefineLabelY(32, "Sum");      // 32: Sum
+    hrate.DefineLabelY(33, "Trig");     //     Sum+Lvl1
+    hrate.DefineLabelY(36, "Trig");     //     Sum+Lvl2
+    hrate.DefineLabelY(37, "Trig");     //     Sum+Lvl1+Lvl2
+
+    MFillH frate(&hrate, "", "FillRate");
+    frate.SetDrawOption("box");
+
+    // ------------------ Setup write task ----------------
+
+    // Effective on-time need its own not to be skipped by (eg) image cleaning
+    // Muons needs its own to have a unique SetReadyToSave
+    const TString rule(Form("s/(([0-9]+_)?(M[12]_)?[0-9.]+)_Y_(.*[.]root)$/%s\\/$1_I_$4/", Esc(fPathOut).Data()));
+    MWriteRootFile write( 2, rule, fOverwrite?"RECREATE":"NEW", "Image parameters");
+    MWriteRootFile writet(2, rule, fOverwrite?"RECREATE":"NEW", "Image parameters"); // EffectiveOnTime
+    MWriteRootFile writem(2, rule, fOverwrite?"RECREATE":"NEW", "Image parameters"); // Muons
+    writem.SetName("WriteMuons");
+
+    // Data
+    write.AddContainer("MHillas",                   "Events");
+    write.AddContainer("MHillasExt",                "Events");
+    write.AddContainer("MHillasSrc",                "Events");
+    write.AddContainer("MImagePar",                 "Events");
+    write.AddContainer("MNewImagePar",              "Events");
+    write.AddContainer("MRawEvtHeader",             "Events");
+    write.AddContainer("MPointingPos",              "Events");
+    write.AddContainer("MTriggerPattern",           "Events");
+
+    // Run Header
+    write.AddContainer("MRawRunHeader",             "RunHeaders");
+//    write.AddContainer("MBadPixelsCam",             "RunHeaders");
+    write.AddContainer("MGeomCam",                  "RunHeaders");
+    write.AddContainer("MObservatory",              "RunHeaders");
+
+    // Muon Setup
+    write.AddContainer("BinningRadius",             "RunHeaders");
+    write.AddContainer("BinningArcWidth",           "RunHeaders");
+    write.AddContainer("BinningRingBroadening",     "RunHeaders");
+    write.AddContainer("BinningSizeVsArcRadius",    "RunHeaders");
+    write.AddContainer("MMuonSetup",                "RunHeaders");
+
+    if (fSequence.IsMonteCarlo())
+    {
+        // Monte Carlo Data
+        write.AddContainer("MMcEvt",                "Events");
+        write.AddContainer("MMcTrig",               "Events", kFALSE);
+        write.AddContainer("MCorsikaEvtHeader",     "Events", kFALSE);
+        write.AddContainer("MSrcPosCam",            "Events");
+        // Monte Carlo Run Headers
+        write.AddContainer("MMcRunHeader",          "RunHeaders");
+        write.AddContainer("MMcTrigHeader",         "RunHeaders", kFALSE);
+        write.AddContainer("MMcFadcHeader",         "RunHeaders", kFALSE);
+        write.AddContainer("MMcConfigRunHeader",    "RunHeaders", kFALSE);
+        write.AddContainer("MMcCorsikaRunHeader",   "RunHeaders", kFALSE);
+        write.AddContainer("MCorsikaRunHeader",     "RunHeaders", kFALSE);
+    }
+    else
+    {
+        // Event time
+        write.AddContainer("MTime", "Events");
+
+        // Slow-control trees with time information
+        write.AddTree("Drive");
+        write.AddTree("Starguider", kFALSE);
+        write.AddTree("Pyrometer",  kFALSE);
+        writet.AddContainer("MEffectiveOnTime",     "EffectiveOnTime");
+        writet.AddContainer("MTimeEffectiveOnTime", "EffectiveOnTime");
+    }
+
+    // What to write in muon tree
+    writem.AddContainer("MMuonSearchPar",           "Muons");
+    writem.AddContainer("MMuonCalibPar",            "Muons");
+    writem.AddContainer("MHillas",                  "Muons");
+    writem.AddContainer("MHillasExt",               "Muons");
+    writem.AddContainer("MHillasSrc",               "Muons");
+    writem.AddContainer("MImagePar",                "Muons");
+    writem.AddContainer("MNewImagePar",             "Muons");
+    writem.AddContainer("MRawEvtHeader",            "Muons");
+    writem.AddContainer("MPointingPos",             "Muons");
+    if (fSequence.IsMonteCarlo())
+    {
+        // Monte Carlo Data
+        writem.AddContainer("MMcEvt",               "Muons");
+        writem.AddContainer("MMcTrig",              "Muons", kFALSE);
+    }
+
+    if (fSequence.IsMonteCarlo())
+    {
+        if (fMuonAnalysis)
+            writem.AddCopySource("OriginalMC");
+        else
+            write.AddCopySource("OriginalMC");
+    }
+
+    MTaskList tlist2("Events");
+    tlist2.AddToList(&apply);
+    if (!fSequence.IsMonteCarlo())
+        tlist2.AddToList(&cont);
+    tlist2.AddToList(&contsw);
+    if (!fSequence.IsMonteCarlo())
+    {
+        // Calibration events don't enter star at all.
+        tlist2.AddToList(&rate);
+        tlist2.AddToList(&fillvs);
+        tlist2.AddToList(&fsum);
+        tlist2.AddToList(&fill9);
+        tlist2.AddToList(&writet);
+    }
+
+    // Spark cut:
+    //  This cut is a little bit different from the default cut in the
+    //  ganymed.rc, because the cut in ganymed.rc also suppresses a
+    //  little background, while the cut here only shows sparks
+    MFDataPhrase fsparks("log10(MNewImagePar.fConcCOG)<-0.45*(log10(MHillas.fSize)-2.5)-0.24", "SparkCut");
+    //fill0b.SetFilter(&fsparks);
+    fill0c.SetFilter(&fsparks);
+
+    // Inverted spark cut (need not to be a member of the task list
+    // because it fsparks is
+    MFilterList fnsparks(&fsparks);
+    fill0d.SetFilter(&fnsparks);
+
+    tlist2.AddToList(&clean);
+    tlist2.AddToList(&poscalc);
+
+    MFillH fillsp("MHSrcPosCam", "MSrcPosCam", "FillSrcPosCam");
+    fillsp.SetNameTab("Src");
+    if (fSequence.IsMonteCarlo())
+        tlist2.AddToList(&fillsp);
+
+
+    tlist2.AddToList(&hcalc);
+    tlist2.AddToList(&fsparks);
+    tlist2.AddToList(&fill0a);
+    tlist2.AddToList(&fill0c);
+    tlist2.AddToList(&fill0d);
+    tlist2.AddToList(&fill0b);
+    tlist2.AddToList(&frate);
+    tlist2.AddToList(&fill1);
+    tlist2.AddToList(&fill2);
+    tlist2.AddToList(&fill3);
+    tlist2.AddToList(&fill4);
+    tlist2.AddToList(&fill5);
+
+    // ----------------------- Muon Analysis ----------------------
+    // Filter to start muon analysis
+    MFDataPhrase fmuon1("MHillas.fSize>150 && MNewImagePar.fConcCOG<0.1", "MuonPreCut");
+    // Filter to calculate further muon parameters
+    MFDataPhrase fmuon2("(MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg>0.6) && (MMuonSearchPar.fRadius*MGeomCam.fConvMm2Deg<1.35) &&"
+                        "(MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg<0.152)", "MuonSearchCut");
+    // Filter to fill the MHMuonPar
+    MFDataPhrase fmuon3("(MMuonCalibPar.fArcPhi>190) && (MMuonSearchPar.fDeviation*MGeomCam.fConvMm2Deg<0.118) &&"
+                        "(MMuonCalibPar.fArcWidth<0.20) && (MMuonCalibPar.fArcWidth>0.04) &&"
+                        "MMuonCalibPar.fRelTimeSigma<1.5",
+                        "MuonFinalCut");
+    // Filter to write Muons to Muon tree
+    MFDataMember fmuon4("MMuonCalibPar.fArcPhi", '>', -0.5, "MuonWriteCut");
+    writem.SetFilter(&fmuon4);
+
+    MMuonSearchParCalc muscalc;
+    muscalc.SetFilter(&fmuon1);
+
+    MMuonCalibParCalc mcalc;
+    mcalc.SetFilter(&fmuon2);
+
+    MFillH fillmuon("MHSingleMuon", "", "FillMuon");
+    MFillH fillmpar("MHMuonPar",    "", "FillMuonPar");
+    fillmuon.SetFilter(&fmuon2);
+    fillmpar.SetFilter(&fmuon3);
+    fillmuon.SetBit(MFillH::kDoNotDisplay);
+
+    if (fMuonAnalysis)
+    {
+        tlist2.AddToList(&fmuon1);
+        tlist2.AddToList(&muscalc);
+        tlist2.AddToList(&fmuon2);
+        tlist2.AddToList(&fillmuon);
+        tlist2.AddToList(&mcalc);
+        tlist2.AddToList(&fmuon3);
+        tlist2.AddToList(&fillmpar);
+        tlist2.AddToList(&fmuon4);
+        tlist2.AddToList(&writem);
+    }
+
+    // ------------------------------------------------------------
+
+    // Initialize histogram
+    MHSectorVsTime histdc, histrms;
+    histdc.SetNameTime("MTimeCamera");
+    histdc.SetTitle("Average DC currents of all pixels vs time;;<I> [nA]");
+    histdc.SetMinimum(0);
+    histdc.SetMaximum(10);
+    histrms.SetNameTime("MTimeCamera");
+    histrms.SetTitle("Average pedestal rms of all pixels vs time;;<\\sigma_{p}> [phe]");
+    histrms.SetType(5);
+    histrms.SetMinimum(0);
+    histrms.SetMaximum(10);
+
+    /*
+     // Define area index [0=inner, 1=outer]
+     // TArrayI inner(1); inner[0] = 0; histdc.SetAreaIndex(inner);
+     */
+
+    // Task to fill the histogram
+    MFillH filldc(&histdc,   "MCameraDC",                 "FillDC");
+    MFillH fillrms(&histrms, "MPedPhotFromExtractorRndm", "FillPedRms");
+    //MFillH filltst("MHTest", "MTime", "FillTest");
+    filldc.SetNameTab("Currents");
+    fillrms.SetNameTab("MeanRms");
+    //filltst.SetNameTab("Test");
+
+    MFillH fillw1("MHWeather", "MTimeCC",        "FillWeather");
+    MFillH fillw2("MHWeather", "MTimePyrometer", "FillPyrometer");
+    fillw2.SetBit(MFillH::kDoNotDisplay);
+    fillw2.SetBit(MFillH::kCanSkip);
+
+    // instantiate camera histogram containers
+    MHCamEvent evtdt(0, "Thresholds", "Average Discriminator Thresholds;;DT [au]");
+    plist.AddToList(&evtdt);
+
+    // instantiate fill tasks
+    MFillH filldt1("Thresholds", "MCameraTH", "FillDT-CC");
+    MFillH filldt2("Thresholds", "MCameraTH", "FillDT-Rec");
+    filldt1.SetNameTab("DT");
+    filldt2.SetBit(MFillH::kDoNotDisplay);
+    filldt2.SetBit(MFillH::kCanSkip);
+    filldt1.SetBit(MFillH::kCanSkip);
+
+    MHSectorVsTime histipr;
+
+    histipr.SetNameTime("MTimeTrigger");
+    histipr.SetTitle("Mean of all IPR;;<IPR> [Hz]");
+    histipr.SetMinimum(0);
+    //histipr.SetUseMedian();
+
+    // Task to fill the histogram
+    MFillH fillipr(&histipr, "MTriggerIPR", "FillIPR");
+    fillipr.SetNameTab("IPR");
+
+    MPointingPosCalc pcalc;
+
+    // ------------------------------------------------------------
+
+    tlist.AddToList(fSequence.IsMonteCarlo() ? (MTask*)&readmc : (MTask*)&readreal);
+    tlist.AddToList(&pcalc,  fSequence.IsMonteCarlo() ? "Events" : "Drive");
+    //tlist.AddToList(&filltst, "Events");
+    tlist.AddToList(&tlist2, "Events");
+    if (!fSequence.IsMonteCarlo())
+    {
+        // initiate task list
+        tlist.AddToList(&fillw1,  "CC");
+        tlist.AddToList(&fillw2,  "Pyrometer");
+        tlist.AddToList(&fillp1,  "Drive");
+        tlist.AddToList(&fillp2,  "Starguider");
+        tlist.AddToList(&fillrms, "Camera");
+        tlist.AddToList(&filldc,  "Camera");
+        tlist.AddToList(&fillipr, "Trigger");
+        tlist.AddToList(&filldt1, "CC");   // Old files: Receiver information in CC-Tree  (Mars<=2.0)
+        tlist.AddToList(&filldt2, "Rec");  // New files: Receiver information in Rec-Tree (Mars >2.0)
+    }
+    if (!HasNullOut())
+        tlist.AddToList(&write);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    if (!WriteResult())
+        return kFALSE;
+
+    *fLog << all << GetDescriptor() << ": Done." << endl << endl << endl;;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJStar.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJStar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJStar.h	(revision 17960)
@@ -0,0 +1,28 @@
+#ifndef MARS_MJStar
+#define MARS_MJStar
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MJStar : public MJob
+{
+private:
+    Bool_t fMuonAnalysis;
+
+    Bool_t WriteResult();
+    Bool_t CheckEnvLocal();
+
+public:
+    MJStar(const char *name=NULL, const char *title=NULL);
+
+    // Setup
+    void DisableMuonAnalysis(Bool_t b=kTRUE) { fMuonAnalysis = !b; }
+
+    // Process
+    Bool_t Process();
+
+    ClassDef(MJStar, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MJob.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJob.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJob.cc	(revision 17960)
@@ -0,0 +1,633 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJob
+//
+// A base class for jobs
+//
+// SetDebugEnv(0) // switch off debugging
+// SetDebugEnv(1) // reserved
+// SetDebugEnv(2) // print untouched resources after evtloop resources setup
+// SetDebugEnv(3) // do 2) and debug setting env completely
+//
+// To allow overwriting the output files call SetOverwrite()
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJob.h"
+
+#include "MEnv.h"
+
+#include <TFile.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TRandom.h>
+#include <TObjArray.h>
+
+#include "MIter.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MEvtLoop.h"
+
+ClassImp(MJob);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fDataFlag to 0
+//
+MJob::MJob(const char *name, const char *title) : fEnv(0), fEnvDebug(0), fOverwrite(kFALSE), fMaxEvents(0)
+{
+    fName  = name  ? name  : "MJob";
+    fTitle = title ? title : "Base class for jobs";
+}
+
+//------------------------------------------------------------------------
+//
+// If MJob is the owner of fEnv delete fEnv.
+//
+// Reset the owenership bit.
+//
+// Set fEnv to NULL.
+//
+void MJob::ClearEnv()
+{
+    if (fEnv && TestBit(kIsOwner))
+        delete fEnv;
+    ResetBit(kIsOwner);
+    fEnv=0;
+}
+
+//------------------------------------------------------------------------
+//
+// ClearEnv()
+//
+MJob::~MJob()
+{
+    ClearEnv();
+}
+
+//------------------------------------------------------------------------
+//
+// If prefix==0 the prefix is taken from fName up to the first
+// whitespace.
+//
+// A trailing dot is removed.void MJob::SetPrefix(const char *prefix)
+void MJob::SetPrefix(const char *prefix)
+{
+    fEnvPrefix = prefix;
+
+    if (!prefix)
+        fEnvPrefix = fName.First(' ')>0 ? fName(0, fName.First(' ')) : fName;
+
+    if (fEnvPrefix.EndsWith("."))
+        fEnvPrefix.Remove(fEnvPrefix.Length()-1);
+}
+
+//------------------------------------------------------------------------
+//
+// Create a new MEnv from the file env. MJob takes of course the
+// ownership of the newly created MEnv.
+//
+// SetPrefix(prefix)
+//
+// return kFALSE if MEnv is invalid
+//
+Bool_t MJob::SetEnv(const char *env, const char *prefix)
+{
+    SetEnv(new MEnv(env), prefix);
+
+    // Take the owenership of the MEnv instance
+    SetBit(kIsOwner);
+
+    return fEnv->IsValid();
+}
+
+//------------------------------------------------------------------------
+//
+// Set a new fEnv and a new general prefix.
+//
+// Calls SetPrefix(prefix)
+//
+// MJob does not take the owenership of the MEnv instance.
+//
+void MJob::SetEnv(MEnv *env, const char *prefix)
+{
+    ClearEnv();
+
+    fEnv = env;
+
+    SetPrefix(prefix);
+}
+
+//------------------------------------------------------------------------
+//
+// Removes LF's from the path (necessary if the resource file was written
+// with a different operating system than Linux.
+//
+// Removes a trailing slash if the path is not the root-path.
+//
+// Adds fname to the path if given.
+//
+void MJob::FixPath(TString &path)
+{
+    path.ReplaceAll("\015", "");
+
+    if (path==(TString)"/")
+        return;
+
+    if (path.EndsWith("/"))
+        path.Remove(path.Length()-1);
+}
+
+//------------------------------------------------------------------------
+//
+// Calls FixPath
+//
+// Adds fname to the path if given.
+//
+TString MJob::CombinePath(TString path, TString fname)
+{
+    FixPath(path);
+
+    if (fname.IsNull())
+        return path;
+
+    if (path!=(TString)"/")
+        path += "/";
+
+    path += fname;
+
+    return path;
+}
+
+//------------------------------------------------------------------------
+//
+// Sets the output path. The exact meaning (could also be a file) is
+// deined by the derived class.
+//
+void MJob::SetPathOut(const char *path)
+{
+    fPathOut = path;
+    FixPath(fPathOut);
+}
+
+//------------------------------------------------------------------------
+//
+// Sets the input path. The exact meaning (could also be a file) is
+// deined by the derived class.
+//
+void MJob::SetPathIn(const char *path)
+{
+    fPathIn = path;
+    FixPath(fPathIn);
+}
+
+//------------------------------------------------------------------------
+//
+// Returns the TEnv
+//
+const TEnv *MJob::GetEnv() const
+{
+    return static_cast<const TEnv *const>(fEnv);
+}
+
+//------------------------------------------------------------------------
+//
+// Checks GetEnvValue(*fEnv, fEnvPrefix, name, dftl)
+// For details see MParContainer
+//
+Int_t MJob::GetEnv(const char *name, Int_t dflt) const
+{
+    return GetEnvValue2(*fEnv, fEnvPrefix, name, dflt); //    return fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
+}
+
+//------------------------------------------------------------------------
+//
+// Checks GetEnvValue(*fEnv, fEnvPrefix, name, dftl)
+// For details see MParContainer
+//
+Double_t MJob::GetEnv(const char *name, Double_t dflt) const
+{
+    return GetEnvValue2(*fEnv, fEnvPrefix, name, dflt); //    return fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
+}
+
+//------------------------------------------------------------------------
+//
+// Checks GetEnvValue(*fEnv, fEnvPrefix, name, dftl)
+// For details see MParContainer
+//
+const char *MJob::GetEnv(const char *name, const char *dflt) const
+{
+    return GetEnvValue2(*fEnv, fEnvPrefix, name, dflt); //fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
+}
+
+//------------------------------------------------------------------------
+//
+// Checks IsEnvDefined(*fEnv, fEnvPrefix, name, fEnvDebug>2)
+// For details see MParContainer
+//
+Bool_t MJob::HasEnv(const char *name) const
+{
+    return IsEnvDefined(*fEnv, fEnvPrefix, name, fEnvDebug>2);//fEnv->Lookup(Form("%s%s", fEnvPrefix.Data(), name));
+}
+
+//------------------------------------------------------------------------
+//
+// Check fEnv for RadnomNumberGenerator. If it is empty or the
+// corresponding class does either not exist or not inherit from TRandom,
+// gRandom remains unchanged. Otherwise gRandom is set to a newly created
+// instance of this class.
+//
+// The second resource which is checked is RandomNumberSeedValue. If it
+// is empty (not given) the seed keeps unchanged. If a number is given
+// the seed value of gRandom is set accordingly. (0 means that
+// the seed value is set accoring to the time, see TRandom::SetSeed())
+//
+// If an error occured kFALSE is returned, kTRUE otherwise.
+//
+// For exmaple:
+//    RandomNumberGenerator: TRandom3
+//    RandomNumberSeedValue:  0
+//
+Bool_t MJob::InitRandomNumberGenerator() const
+{
+    const TString rng = GetEnv("RandomNumberGenerator", "");
+    if (!rng.IsNull())
+    {
+        TClass *cls = MParContainer::GetClass(rng, &gLog);
+        if (!cls)
+            return kFALSE;
+
+        if (!cls->InheritsFrom(TRandom::Class()))
+        {
+            *fLog << err << "ERROR - RandomNumberGenerator " << rng << " doesn't inherit from TRandom." <<  endl;
+            return kFALSE;
+        }
+
+        delete gRandom;
+        gRandom = static_cast<TRandom*>(cls->New());
+
+        *fLog << inf << "Random number generator " << rng << " initialized." << endl;
+    }
+
+    // Nothing: Keep seed value, 0 set time as seed value, val set seed
+    const TString seed = GetEnv("RandomNumberSeedValue", "");
+    if (!seed.IsNull())
+    {
+        if (!seed.IsAlnum())
+        {
+            *fLog << err << "ERROR - RandomNumberSeedValue not an integer: " << seed <<  endl;
+            return kFALSE;
+        }
+
+        gRandom->SetSeed(seed.Atoi());
+        *fLog << inf << "Random number seed value set to " << seed.Atoi() << endl;
+    }
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Check the resource file for
+//   PathOut
+//   PathIn
+//   MaxEvents
+//   Overwrite
+//   EnvDebug
+//   RandomNumberGenerator
+//   RandomNumberSeedValue
+//
+// and call the virtual function CheckEnvLocal
+//
+Bool_t MJob::CheckEnv()
+{
+    if (!fEnv)
+        return kTRUE;
+
+    if (!InitRandomNumberGenerator())
+        return kFALSE;
+
+    TString p;
+    p = GetEnv("PathOut", "");
+    if (!p.IsNull())
+        SetPathOut(p);
+
+    p = GetEnv("PathIn", "");
+    if (!p.IsNull())
+        SetPathIn(p);
+
+    SetMaxEvents(GetEnv("MaxEvents", fMaxEvents));
+    SetOverwrite(GetEnv("Overwrite", fOverwrite));
+    SetEnvDebug( GetEnv("EnvDebug",  fEnvDebug));
+
+    return CheckEnvLocal();
+}
+
+//------------------------------------------------------------------------
+//
+// Returns the result of c.ReadEnv(*fEnv, fEnvPrefix, fEnvDebug>2)
+// By adding the container first to a MParList it is ensured that
+// all levels are checked.
+//
+Bool_t MJob::CheckEnv(MParContainer &c) const
+{
+    if (!fEnv)
+        return kTRUE;
+
+    // Make sure that all levels are checked
+    MParList l;
+    l.AddToList(&c);
+    return l.ReadEnv(*fEnv, fEnvPrefix+".", fEnvDebug>2);
+}
+
+//------------------------------------------------------------------------
+//
+// Call the eventsloops ReadEnv and print untouched resources afterwards
+// if fEnvDebug>1
+//
+Bool_t MJob::SetupEnv(MEvtLoop &loop) const
+{
+    if (!fEnv)
+        return kTRUE;
+
+    *fLog << all << "Evaluating resources from: " << fEnv->GetRcName() << endl;
+
+    if (!loop.ReadEnv(*fEnv, fEnvPrefix, fEnvDebug>2))
+        return kFALSE;
+
+    if (fEnvDebug>1)
+        fEnv->PrintUntouched();
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Checks whether write permissions to fname exists including
+// the fOverwrite data member. Empty file names return kTRUE
+//
+Bool_t MJob::HasWritePermission(TString fname) const
+{
+    gSystem->ExpandPathName(fname);
+
+    const Bool_t exists = !gSystem->AccessPathName(fname, kFileExists);
+    if (!exists)
+    {
+        const TString dirname = gSystem->DirName(fname);
+
+        Long_t flags;
+        const Bool_t exists2 = !gSystem->GetPathInfo(dirname, 0, (Long_t*)0, &flags, 0);
+        if (!exists2)
+        {
+            *fLog << err << "ERROR - Directory " << dirname << " doesn't exist." << endl;
+            return kFALSE;
+        }
+
+        if ((flags&2)==0)
+        {
+            *fLog << err << "ERROR - " << dirname << " is not a directory." << endl;
+            return kFALSE;
+        }
+
+        const Bool_t write = !gSystem->AccessPathName(dirname, kWritePermission);
+        if (!write)
+        {
+            *fLog << err << "ERROR - No permission to write to directory " << dirname << endl;
+            return kFALSE;
+        }
+
+        return kTRUE;
+    }
+
+    Long_t flags;
+    gSystem->GetPathInfo(fname, 0, (Long_t*)0, &flags, 0);
+    if (flags&4)
+    {
+        *fLog << err << "ERROR - " << fname << " is not a regular file." << endl;
+        return kFALSE;
+    }
+
+    const Bool_t write = !gSystem->AccessPathName(fname, kWritePermission);
+    if (!write)
+    {
+        *fLog << err << "ERROR - No permission to write to " << fname << endl;
+        return kFALSE;
+    }
+
+    if (fOverwrite)
+        return kTRUE;
+
+    *fLog << err;
+    *fLog << "ERROR - File " << fname << " already exists and overwrite not allowed." << endl;
+
+    return kFALSE;
+}
+
+//------------------------------------------------------------------------
+//
+// Write containers in list to gFile. Returns kFALSE if no gFile or any
+// container couldn't be written. kTRUE otherwise.
+//
+Bool_t MJob::WriteContainer(TCollection &list) const
+{
+    if (!gFile)
+    {
+        *fLog << err << dbginf << "ERROR - No file open (gFile==0)" << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        *fLog << inf << " - Writing " << MParContainer::GetDescriptor(*o) << "..." << flush;
+        if (o->Write(o->GetName())<=0)
+        {
+            *fLog << err << dbginf << "ERROR - Writing " << MParContainer::GetDescriptor(*o) << " to file " << gFile->GetName() << endl;
+            return kFALSE;
+        }
+        *fLog << "ok." << endl;
+    }
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Read containers in list into list from gFile
+// Returns kFALSE if no gFile or any container couldn't be read.
+//
+Bool_t MJob::ReadContainer(TCollection &list) const
+{
+    if (!gFile)
+    {
+        *fLog << err << dbginf << "ERROR - No file open (gFile==0)" << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        *fLog << inf << " - Reading " << MParContainer::GetDescriptor(*o) << "..." << flush;
+        if (o->Read(o->GetName())<=0)
+        {
+            *fLog << err << dbginf << "ERROR - Reading " << MParContainer::GetDescriptor(*o) << " from file " << gFile->GetName() << endl;
+            return kFALSE;
+        }
+        *fLog << "ok." << endl;
+    }
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Write containers in cont to fPathOut+"/"+name, or fPathOut only
+// if name is empty.
+//
+Bool_t MJob::WriteContainer(TCollection &cont, const char *name, const char *option, const int compr) const
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    TString oname = CombinePath(fPathOut, name);
+
+    // In case the update-option is selected check whether
+    // the file is already open
+    if (TString(option).Contains("update", TString::kIgnoreCase))
+    {
+        TFile *file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(oname));
+        if (!file || !file->IsOpen() || file->IsZombie())
+        {
+            gSystem->ExpandPathName(oname);
+            file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(oname));
+        }
+
+        if (file && file->IsOpen() && !file->IsZombie())
+        {
+            *fLog << inf << "Updating open file " << oname << "." << endl;
+            file->cd();
+            return WriteContainer(cont);
+        }
+    }
+
+    *fLog << inf << "Writing to file " << oname << "." << endl;
+
+    TString title("File written by ");
+    title += fName;
+
+    // Open a new file with the defined option for writing
+    TFile file(oname, option, title, compr);
+    if (!file.IsOpen() || file.IsZombie())
+    {
+        *fLog << err << "ERROR - Couldn't open file " << oname << " for writing..." << endl;
+        return kFALSE;
+    }
+
+    return WriteContainer(cont);
+}
+
+//------------------------------------------------------------------------
+//
+// return kTRUE if no display is set.
+//
+// Write the display to the TFile with name name, options option and
+// compression level comp.
+//
+// If name IsNull fPathOut is assumed to contain the name, otherwise
+// name is appended to fPathOut. fPathOut might be null.
+//
+Bool_t MJob::WriteDisplay(const char *name, const char *option, const int compr) const
+{
+    if (!fDisplay)
+        return kTRUE;
+
+    TObjArray arr;
+    arr.Add((TObject*)(fDisplay));
+    return WriteContainer(arr, name, option, compr);
+}
+
+TString MJob::ExpandPath(TString fname)
+{
+    // empty
+    if (fname.IsNull())
+        return "";
+
+    // Expand path using environment
+    gSystem->ExpandPathName(fname);
+
+    // Absolute path
+    if (fname[0]=='/')
+    {
+        gLog << dbg << "MJob::ExpandPath - Path " << fname << " is absolute." << endl;
+        return fname;
+    }
+
+    // relative path to file and file could be found
+    if (!gSystem->AccessPathName(fname, kFileExists))
+    {
+        gLog << dbg << "MJob::ExpandPath - Relative path " << fname << " found..." << endl;
+        return fname;
+    }
+
+    // Now check gEnv and MARSSYS. gEnv can overwrite MARSSYS
+    TString path(gEnv ? gEnv->GetValue("Mars.Path", "$MARSSYS") : "$MARSSYS");
+
+    // Expand path using environment
+    gSystem->ExpandPathName(path);
+
+    // check if path ends with a slash
+    path = CombinePath(path, fname);
+
+    gLog << dbg << "MJob::ExpandPath - Filename expanded to " << path << endl;
+
+    // return new path
+    return path;
+}
+
+//------------------------------------------------------------------------
+//
+// Sorts the array.
+//
+void MJob::SortArray(TArrayI &arr)
+{
+    TArrayI idx(arr.GetSize());
+    TArrayI srt(arr);
+
+    TMath::Sort(arr.GetSize(), srt.GetArray(), idx.GetArray(), kFALSE);
+
+    for (int i=0; i<arr.GetSize(); i++)
+        arr[i] = srt[idx[i]];
+}
Index: branches/Mars_McMismatchStudy/mjobs/MJob.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MJob.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MJob.h	(revision 17960)
@@ -0,0 +1,104 @@
+#ifndef MARS_MJob
+#define MARS_MJob
+
+#ifndef MARS_MSequence
+#include "MSequence.h"
+#endif
+
+class MEnv;
+class MEvtLoop;
+
+class MJob : public MParContainer
+{
+private:
+    enum { kIsOwner = BIT(14) };
+
+    // Helper functions for paths
+    static TString CombinePath(TString path, TString fname);
+    static void FixPath(TString &path);
+
+    // Helper functions to set a new fEnv
+    void SetPrefix(const char *prefix);
+    void ClearEnv();
+
+    // Data members for resource files
+    const MEnv *fEnv;         // Resource file
+    TString     fEnvPrefix;   // Prefix for resources
+    Int_t       fEnvDebug;    // Debug setup of resources
+
+protected:
+    TString   fPathOut;       // Directory to write output file to (eg. calib*.root)
+    TString   fPathIn;        // Directory to read output from (eg. calib*.root)
+
+    Bool_t    fOverwrite;     // Allow overwriting output files
+    Int_t     fMaxEvents;     // Maximum number of events
+
+    Bool_t    fNullOut;       // Suppress output files
+
+    // FIXME: Split into MJobSequence and MJobDataSet
+    MSequence fSequence;      // Sequence
+
+    TString   fCommandLine;   // Command line for possible storage
+
+    const TEnv *GetEnv() const;
+    const MEnv *GetMEnv() const { return fEnv; }
+    const TString &GetEnvPrefix() const { return fEnvPrefix; }
+    Int_t GetEnvDebug() const { return fEnvDebug; }
+
+    Int_t       GetEnv(const char *name, Int_t dflt) const;
+    Double_t    GetEnv(const char *name, Double_t dflt) const;
+    const char *GetEnv(const char *name, const char *dflt) const;
+    Bool_t      HasEnv(const char *name) const;
+
+    Bool_t InitRandomNumberGenerator() const;
+    Bool_t SetupEnv(MEvtLoop &loop) const;
+    Bool_t CheckEnv();
+    Bool_t CheckEnv(MParContainer &c) const;
+    void PrintUntouchedEnv() const;
+    virtual Bool_t CheckEnvLocal() { return kTRUE; }
+
+    Bool_t WriteContainer(TCollection &list) const;
+    Bool_t ReadContainer(TCollection &list) const;
+    Bool_t WriteContainer(TCollection &cont, const char *name, const char *option="RECREATE", const int compr=2) const;
+    Bool_t WriteDisplay(const char *name, const char *option="RECREATE", const int comp=2) const;
+
+public:
+    MJob(const char *name=NULL, const char *title=NULL);
+    ~MJob();
+
+    // Setter
+    void   SetPathOut(const char *path=".");
+    void   SetPathIn(const char *path=".");
+
+    void   SetOverwrite(Bool_t b=kTRUE) { fOverwrite=b; }
+    Bool_t SetEnv(const char *env, const char *prefix=0);
+    void   SetEnv(MEnv *env, const char *prefix=0);
+    void   SetEnvDebug(Int_t d=2) { fEnvDebug=d; }
+
+    void   SetMaxEvents(Int_t max) { fMaxEvents = max; }
+    void   SetSequence(const MSequence &seq) { fSequence = seq; }
+
+    void   SetNullOut(Bool_t b=kTRUE) { fNullOut=b; }
+
+    void   SetCommandLine(const TString &s) { fCommandLine = s; }
+
+    // Getter
+    TString GetPathOut() const  { return fPathOut; }
+    TString GetPathIn() const   { return fPathIn; }
+
+    Bool_t HasWritePermission(TString fname) const;
+
+    Bool_t HasNullOut() const { return fNullOut; }
+
+    // Others
+    MStatusDisplay *GetDisplay() { return fDisplay; }
+
+    static TString ExpandPath(TString fname);
+    static void SortArray(TArrayI &arr);
+
+    static TString Esc(TString esc) { esc.ReplaceAll("/", "\\/"); return esc; }
+
+    ClassDef(MJob, 0) // Bas class for Jobs
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MSequence.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MSequence.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MSequence.cc	(revision 17960)
@@ -0,0 +1,1777 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSequence
+//
+//  This class describes a sequence. For sequences see:
+//    http://db.astro.uni-wuerzburg.de
+//
+//  A sequence is a collection of runs which should be used together.
+//  Any run can be contained only once.
+//
+//  Here is an example how a file describing a sequence could look like.
+//
+//  Reading the file is based on TEnv. For more details see also
+//  the class reference of TEnv.
+//
+// ===========================================================================
+//
+//  sequence.txt
+//  ------------
+//
+//   # Sequence number (identifier) - necessary if the path
+//   # contains the sequence number, e.g. image files
+//   Sequence:     31015
+//
+//   # Telescope number the sequence belongs to (if the resource is omitted
+//   #  the default is 1)
+//   Telescope:    1
+//
+//   # Observation Period (not needed, calculated from Night)
+//   # Period:     18
+//
+//   # Date of sunrise of the observation night - necessary if the path
+//   # contains the date, e.g. raw data
+//   Night:        2004-06-24
+//
+//   # Start time of the sequence (first data run, not needed)
+//   Start:        2004-06-24 03:12:42
+//
+//   # Run number of last data run in sequence (not needed)
+//   LastRun:      31032
+//
+//   # Project name of data-runs of sequence (not needed)
+//   Project:      3EG2033+41
+//
+//   # Source name of all runs of sequence (not needed)
+//   Source:       3EG2033+41
+//
+//   # Trigger table of data-runs of sequence (not needed)
+//   TriggerTable: L1_4NN:L2_DEFAULT
+//
+//   # HV Setting table of data-runs of sequence (not needed)
+//   HvSettings:   HVSettings_FF36q
+//
+//   # Total number of data-events in sequence (not needed)
+//   NumEvents:    250914
+//
+//   # Brightest light condition of the contained runs (not needed)
+//   LightCondition: Twilight
+//
+//   # Whether this is MC data or not (necessary in case of MCs if
+//   # default paths should be used)
+//   MonteCarlo: Yes
+//
+//   # List of all runs of this sequence (not needed)
+//   Runs: 31015:31017 31018 31019.0 31019.3 31019.5:7 31020+ 31021::3
+//
+//   # List of all calibration runs of this sequence (necessary if accessed)
+//   CalRuns: 31015 31016 31017
+//   # List of pedestal runs belonging to the calibration runs of this sequence (necessary if accessed)
+//   PedRuns: 31018
+//   # List of all data runs belonging to this sequence (necessary)
+//   DatRuns: 31019.0 31019.3 31019:5:7 31020+ 31021::3
+//
+//   Run00031020: :3 7:9 15
+//
+//   # Just for fun ;-) (not needed, but helpful)
+//   Comment: This is a template for a sequence file
+//
+// ===========================================================================
+//
+//   Runs are devided into file since run 1000000. These Run-/Filenumbers
+//   are given by a dot. X.Y means Run X, File Y.
+//
+//   In the Runs, CalRuns, PedRuns and DatRuns tag you can use
+//   several abbreviationa:
+//
+//    31015:31017     means      31015.0 31016.0 31017.0
+//    31018           means      31018.0
+//    31019.3         means      31019.3
+//    31019.5:7       means      31019.5 31019.6 31019.7
+//    31020+          means      file list for run 21020 given below
+//    31021::3        means      31021.0 31021.1 31021.2 31021.3
+//
+//   For the run-list defined above (note the number must have 8 digits,
+//   for example 'Run00031020') you can also use abbreviations:
+//
+//    :3              means      0 1 2 3
+//    7:9             means      7 8 9
+//
+// ===========================================================================
+//
+//  For special cases you can also setup a sequence directly from a macro,
+//  for example:
+//
+//    MDirIter pediter, datiter, caliter;
+//
+//    MSequence seq;
+//    seq.SetNight("2004-07-06");
+//    seq.AddRun(31751, 'P');
+//    seq.AddRun(31752, 'C');
+//    seq.AddRuns(31753, 31764, 'D');
+//    seq.SetupPedRuns(pediter);
+//    seq.SetupCalRuns(caliter);
+//    seq.SetupDatRuns(datiter);
+//
+//  or
+//
+//    MDirIter iter;
+//
+//    MSequence seq;
+//    seq.SetNight("2004-07-06");
+//    seq.AddFiles(31753, 0, 120);
+//    seq.GetRuns(iter);
+//    seq.SetupPedRuns(iter, "/mypath", "[DPC]");
+//
+//
+// ===========================================================================
+//
+// ToDO:
+//   * Default paths could be moved into the global .rootrc
+//
+// ===========================================================================
+//
+//
+//  Class Version 2:
+//  ----------------
+//   + fMonteCarlo
+//
+//  Class Version 3:
+//  ----------------
+//   + fComment
+//
+//  Class Version 4:
+//  ----------------
+//   + fExclRuns
+//
+//  Class Version 5:
+//  ----------------
+//   + fRunsSub
+//   + fDatRunsSub
+//   + fPedRunsSub
+//   + fCalRunsSub
+//   + fExclRunsSub
+//
+//  Class Version 6:
+//  ----------------
+//   + fTelescope
+//
+//  Class Version 7:
+//  ----------------
+//   + fDrsRuns
+//   + fDrsRunsSub
+//   + fDrsFiles
+//   + fDrsFilesSub
+//   + fDrsSequence
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSequenceSQL.h"
+
+#include <stdlib.h>
+#include <errno.h>
+
+#include <fstream>
+
+#include <TEnv.h>
+#include <TPRegexp.h>
+#include <TSystem.h> // TSystem::ExpandPath
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MJob.h"
+#include "MAstro.h"
+#include "MString.h"
+#include "MDirIter.h"
+
+ClassImp(MSequence);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// This adds an run/file entry to the data/sub arrays. If it is already
+// contained a waring is printed.
+//
+void MSequence::AddEntry(Int_t run, Int_t file, TArrayI &data, TArrayI &sub) const
+{
+    const Int_t n = data.GetSize();
+
+    // skip already existing entries
+    if (IsContained(data, sub, run, file))
+    {
+        *fLog << warn << "WARNING - File " << run << "." << file << " already in list... skipped." << endl;
+        return;
+    }
+
+    if (!fMonteCarlo && run<1000000 && file>0)
+        *fLog << warn << "WARNING - Run number " << run << "<" << "1,000,000 but file " << file << ">0..." << endl;
+
+    // set new entry
+    data.Set(n+1);
+    sub.Set(n+1);
+
+    data[n] = run;
+    sub[n]  = file;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate a token in thr Run string. Add the coresponding run/files
+// with AddEntry
+//
+void MSequence::EvalEntry(const TEnv *env, const TString &prefix, const TString &num, TArrayI &data, TArrayI &sub) const
+{
+    // Split entry into run and file
+    const Int_t run = num.Atoi();
+
+    // Syntax error forbidden by construction
+    const Ssiz_t p1 = num.First('.');
+    const Ssiz_t p2 = num.Last(':');
+
+    // ---------------------------------------------------------------
+
+    const Int_t n1 = atoi(num.Data()+p1+1);
+    const Int_t n2 = atoi(num.Data()+p2+1);
+
+    // ---------------------------------------------------------------
+    //  p1>=0 && p2<0  (. but no :)    run.n1     run.file1
+    if (p1>=0 && p2<0)
+    {
+        AddEntry(run, n1, data, sub);
+        return;
+    }
+
+    // ---------------------------------------------------------------
+    //  p1>=0 && p2>=0  (. and :)      run:n1:n2  run.file1-run.file2
+    if (p1>=0 && p2>=0)
+    {
+        if (n2<n1)
+        {
+            *fLog << warn << "WARNING - Invalid range '" << num << "'... ignored." << endl;
+            return;
+        }
+
+        for (int i=n1; i<=n2; i++)
+            AddEntry(run, i, data, sub);
+        return;
+    }
+
+    // ---------------------------------------------------------------
+    //  p1<0 && p2>=0  (no . but :)    n1:n2      run1-run2
+    if (p1<0 && p2>=0)
+    {
+        if (n2<run)
+        {
+            *fLog << warn << "WARNING - Invalid range in '" << num << "'... ignored." << endl;
+            return;
+        }
+
+        for (int i=run; i<=n2; i++)
+            AddEntry(i, 0, data, sub);
+        return;
+    }
+
+    // ---------------------------------------------------------------
+    //  p0<0 and p1<0  (no . and no :)   run     run
+
+    if (!num.EndsWith("+"))
+    {
+        AddEntry(run, 0, data, sub);
+        return;
+    }
+
+    if (!env)
+        return;
+
+    TPRegexp regexp("([0-9]*:[0-9]+|[0-9]+(:[0-9]*)?)( +|$)");
+
+    TString files = GetEnvValue3(*env, prefix, "Run%d", run);
+    if (files.IsNull())
+    {
+        AddEntry(run, 0, data, sub);
+        return;
+    }
+
+    while (!files.IsNull())
+    {
+        const TString num = files(regexp);
+        if (num.IsNull())
+        {
+            *fLog << warn << "WARNING - File in run " << run << " is NaN (not a number): '" << files << "'" << endl;
+            break;
+        }
+
+        const Ssiz_t p1 = num.First(':');
+        if (p1>=0)
+        {
+            const Int_t n1 = atoi(num.Data());
+            const Int_t n2 = atoi(num.Data()+p1+1);
+
+            if (n2<n1)
+            {
+                *fLog << warn << "WARNING - Invalid range in '" << num << "'... ignored." << endl;
+                return;
+            }
+
+            // FIXME: n2==0 || n2<n1
+            for (int i=n1; i<=n2; i++)
+                AddEntry(run, i, data, sub);
+        }
+        else
+        {
+            const Int_t file = atoi(num.Data());
+            AddEntry(run, file, data, sub);
+        }
+
+        files.Remove(0, files.First(num)+num.Length());
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the TString and add the run/files to the arrays.
+// Run/files which are twice in the list are only added once. In this case
+// a warning is emitted.
+//
+void MSequence::Split(TString &runs, TArrayI &data, TArrayI &sub, const TEnv *env, const TString prefix) const
+{
+    TPRegexp regexp("^[0-9]+([+]|(:|[.]([0-9]*:)?)[0-9]+)?( +|$)");
+
+    data.Set(0);
+    sub.Set(0);
+
+    runs.ReplaceAll("\t", " ");
+    runs = runs.Strip(TString::kBoth);
+
+    while (!runs.IsNull())
+    {
+        const TString num = runs(regexp);
+        if (num.IsNull())
+        {
+            *fLog << warn << "WARNING - Run syntax error: '" << runs << "'" << endl;
+            break;
+        }
+
+        EvalEntry(env, prefix, num.Strip(TString::kTrailing), data, sub);
+
+        runs.Remove(0, runs.First(num)+num.Length());
+    }
+
+    SortArrays(data, sub);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the String from the TEnv file prefixed by prefix-name.
+// Intepret the string using Split which adds the run/files to the arrays.
+//
+void MSequence::Split(const TEnv &env, const TString &prefix, const char *name, TArrayI &data, TArrayI &sub) const
+{
+    TString str = GetEnvValue2(env, prefix, name, "");
+    Split(str, data, sub, &env, prefix);
+}
+
+TString MSequence::InflateFilePath(const MTime &night, Bool_t mc)
+{
+    TString rc = GetStandardPath(mc);
+    rc += "rawfiles/";
+    rc += night.GetStringFmt("%Y/%m/%d/");
+    return rc;
+}
+
+TString MSequence::InflateFilePath(const MTime &night, UShort_t tel, Int_t run, Int_t file, Int_t type)
+{
+    return InflateFilePath(night)+InflateFileName(night, tel, run, file, type);
+}
+
+// --------------------------------------------------------------------------
+//
+// Compile path from the given path name and expand it. If it IsNull()
+// the path is compiled as standard path from tha datacenter). The
+// returned path will end with a "/".
+//
+TString MSequence::GetPathName(TString d, FileType_t type) const
+{
+    // Setup path
+    if (d.IsNull())
+    {
+        d = GetStandardPath();
+        switch (type&kFilePaths)
+        {
+        case kDrs:
+        case kFits:
+            d += "raw/";
+            d += fNight.GetStringFmt("%Y/%m/%d");
+            break;
+        case kRaw:  // rawdata
+        case kRoot: // mcdata
+            d += "rawfiles/";
+            if (!fNight)
+                *fLog << "WARNING - No Night-resource... path not supported." << endl;
+            d += fNight.GetStringFmt("%Y/%m/%d");
+            break;
+        case kReport:
+            d += "../subsystemdata/cc/";
+            d += fNight.GetStringFmt("%Y/%m/%d");
+            break;
+        case kCalibrated:
+            d += MString::Format("callisto/%04d/%08d", fSequence/10000, fSequence);
+            break;
+        case kImages:
+            d += MString::Format("star/%04d/%08d", fSequence/10000, fSequence);
+            break;
+        }
+    }
+    else
+        gSystem->ExpandPathName(d);
+
+    if (!d.EndsWith("/"))
+        d += '/';
+
+    return d;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compile FileName according to night, tel, run, file and type.
+//
+TString MSequence::InflateFileName(const MTime &night, UShort_t tel, Int_t run, Int_t file, Int_t type)
+{
+    if (!night && type==kCorsika)
+    {
+        // /magic/simulated/ceres/001/000/0001/cer123456
+        return MString::Format("cer%06d", -run);
+    }
+
+    TString n;
+
+    if (type&kDrsFile)
+    {
+        n += night.GetStringFmt("%Y%m%d_");
+        n += MString::Format("%03d", run);
+        n += ".drs.fits.?[fg]?z?";
+        return n;
+    }
+    if (type&(kFits|kFact))
+    {
+        n += night.GetStringFmt("%Y%m%d_");
+        n += MString::Format("%03d", run);
+
+        if (type==kFactCal)
+            n += "_C.root";
+        else if (type==kFactImg)
+            n += "_I.root";
+        else
+            n += ".fits.?[fg]?z?";
+        return n;
+    }
+
+    const char *id="_";
+    switch ((RunType_t)(type&kRunType))
+    {
+    case kDat:
+        id = "D";
+        break;
+    case kPed:
+        id = "P";
+        break;
+    case kCal:
+        id = "C";
+        break;
+    case kAll:
+        id = "[PCD]";
+        break;
+    case kCalib:
+        id = "Y";
+        break;
+    case kImage:
+        id = "I";
+        break;
+    case kExcl:
+        break;
+    }
+
+    // Is report file?
+    const Bool_t isrep = type&kReport;
+
+    // Calculate limit for transition from 5-digit to 8-digit numbers
+    const Int_t limit = isrep ? 39373 : 35487;
+
+    // ------------- Create file name --------------
+    if (night)
+        n += night.GetStringFmt("%Y%m%d_");
+
+    // This is for MCs (FIXME!!!!)
+    if (run<0)
+    {
+        n += MString::Format("%08d", -run);
+        if (file>=0)
+            n += MString::Format(".%03d", file);
+    }
+    else
+    {
+        if (tel>0)
+            n += MString::Format("M%d_", tel);
+
+        // R. DeLosReyes and T. Bretz
+        // Changes to read the DAQ numbering format. Changes takes place
+        // between runs 35487 and 00035488 (2004_08_30)
+        n += MString::Format(run>limit ? "%08d" : "%05d", run);
+
+        if (tel>0)
+            n += MString::Format(".%03d", file);
+    }
+
+
+    n += "_";
+    n += id;
+    n += "_*";
+
+    if (tel==0 && run>=0)
+        n += isrep ? "_S" : "_E";
+
+    switch (type&kFileType)
+    {
+    case kRaw:       // MC     // DATA
+        n += run<0 ? ".root" : ".raw.?[fg]?z?";  // TPRegexp: (\.gz)?
+        break;
+    case kReport:
+        n += ".rep";  // TPRegexp: (\.gz)?
+        break;
+    default:
+        n += ".root";
+        break;
+    }
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the expression describing the file-name for the file defined
+// by i-th entry of the the given arrays. The file type identifier is
+// defined by type. The source name is replaced by a wildcard and
+// the extension is defined by the type as well.
+//
+TString MSequence::GetFileRegexp(UInt_t i, const TArrayI &arr, const TArrayI &sub, FileType_t type) const
+{
+    // Entry doesn't exist
+    if (i>=(UInt_t)arr.GetSize())
+        return "";
+
+    // This is (so far) well defined for MAGIC data
+    if (!fMonteCarlo)
+        return InflateFileName(fNight, arr[i]>999999?fTelescope:0, arr[i], sub.GetSize()>0?sub[i]:0, type);
+
+    // Monte Carlos
+    return InflateFileName(fNight, fTelescope, -arr[i], sub.GetSize()>0?sub[i]:0, type);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the filename from the dirctory and the file-regexp.
+// return "" if file is not accessible or the regular expression is not
+// unambiguous.
+//
+TString MSequence::FindFile(const TString &d, const TString &f) const
+{
+    // Check existance and accessibility of file
+    MDirIter file(d, f, 0);
+
+    TString name = file();
+    gSystem->ExpandPathName(name);
+    if (gSystem->AccessPathName(name, kFileExists))
+    {
+        *fLog << err;
+        *fLog << "ERROR - File " << d << f << " not accessible!" << endl;
+        return "";
+    }
+    if (!file().IsNull())
+    {
+        *fLog << err;
+        *fLog << "ERROR - Searching for file " << d << f << " gave more than one result!" << endl;
+        return "";
+    }
+
+    return name;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the path accoring to type (if fDataPath=path=0), fDataPath
+// (if path=0) or path.
+// Returns accessability of the path.
+//
+Bool_t MSequence::FindPath(TString &path, FileType_t type) const
+{
+    if (path.IsNull())
+        path = fDataPath;
+
+    const Bool_t def = path.IsNull();
+
+    path = GetPathName(path, type);
+
+    return def;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the entries from the arrays to the MDirIter
+//
+UInt_t MSequence::GetRuns(MDirIter &iter, const TArrayI &arr, const TArrayI &sub, FileType_t type, TString path) const
+{
+    const Bool_t def = FindPath(path, type);
+
+    // For this particular case we assume that the files are added one by
+    // one without wildcards.
+    const Int_t n0 = iter.GetNumEntries();
+
+    Int_t excluded = 0;
+    for (int i=0; i<arr.GetSize(); i++)
+    {
+        if (IsExcluded(arr[i], sub[i]))
+        {
+            excluded++;
+            continue;
+        }
+
+        const TString n = GetFileRegexp(i, arr, sub, type);
+
+        if (FindFile(path, n).IsNull())
+            continue;
+
+        // Add Path/File to TIter
+        iter.AddDirectory(path, n, 0);
+    }
+
+    // n0: The previous contents of the iter
+    // n1: The number of files which have been added to the iter
+    // n2: The number of files which should have been added from the array
+    const Int_t n1 = iter.GetNumEntries()-n0;
+    const Int_t n2 = arr.GetSize()-excluded;
+    if (n1==0)
+    {
+        *fLog << err;
+        *fLog << "ERROR - No input files for sequence #" << GetSequence() << endl;
+        *fLog << "        read from " << GetBaseName() << endl;
+        *fLog << "        found in" << (def?" default-path ":" ") << path << endl;
+        return 0;
+    }
+
+    if (n1==n2)
+        return n1;
+
+    *fLog << err;
+    *fLog << "ERROR - " << n1 << " input files for sequence #" << GetSequence() << " found in" << endl;
+    *fLog << "        " << (def?" default-path ":" ") << path << endl;
+    *fLog << "        but " << n2 << " files were defined in sequence file" << endl;
+    *fLog << "        " << GetBaseName() << endl;
+    if (fLog->GetDebugLevel()<=4)
+        return 0;
+
+    *fLog << inf << "Files which are searched for this sequence:" << endl;
+    iter.Print();
+    return 0;
+}
+
+UInt_t MSequence::GetDrsFile() const
+{
+    if (fDrsRuns.GetSize()==0)
+        return fDrsFiles.GetSize()==0 ? 0 : fDrsFiles[0];
+
+    UInt_t rc = 0;
+    for (int i=0; i<fDrsFiles.GetSize(); i++)
+    {
+        for (int j=0; j<fPedRuns.GetSize(); j++)
+        {
+            if (fDrsFiles[i]==fPedRuns[j])
+                rc = fDrsFiles[i];
+        }
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns "0" if file at i-th index is excluded. Get the access-path
+// defined by the default or data-path (if path=0) or path.
+// Get the full file-name by accessing the file.
+//
+TString MSequence::GetFileName(UInt_t i, const TArrayI &arr, const TArrayI &sub, FileType_t type, const char *path) const
+{
+    if (i>=(UInt_t)arr.GetSize())
+        return "";
+
+    if (IsExcluded(arr[i], sub[i]))
+        return "0";
+
+    const TString d = FindPath(type, path);
+    const TString n = GetFileRegexp(i, arr, sub, type);
+
+    return FindFile(d, n);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the pointers to the arrays with the runs/files depending on the
+// given type.
+//
+void MSequence::GetArrays(const TArrayI* &r, const TArrayI* &f, Int_t type) const
+{
+    switch ((RunType_t)(type&(kRunType|kExcl)))
+    {
+    case kDrsRun:
+        r = &fDrsRuns;
+        f = &fDrsRunsSub;
+        break;
+    case kDrsFile:
+        r = &fDrsFiles;
+        f = &fDrsFilesSub;
+        break;
+    case kPed:
+        r = &fPedRuns;
+        f = &fPedRunsSub;
+        break;
+    case kDat:
+    case kImage:
+    case kCalib:
+        r = &fDatRuns;
+        f = &fDatRunsSub;
+        break;
+    case kCal:
+        r = &fCalRuns;
+        f = &fCalRunsSub;
+        break;
+    case kExcl:
+        r = &fExclRuns;
+        f = &fExclRunsSub;
+        break;
+    case kAll:
+        r = &fRuns;
+        f = &fRunsSub;
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add runs from the sequence to MDirIter. If path==0 fDataPath is
+// used instead. If it is also empty the standard path of the
+// data-center is assumed. If you have the runs locally use path="."
+//
+// Returns the number of files added.
+//
+// Runs which are in fExlRuns are ignored.
+//
+UInt_t MSequence::GetRuns(MDirIter &iter, FileType_t type, const char *path) const
+{
+    const TArrayI *r=0, *f=0;
+    GetArrays(r, f, type);
+    return r==0 ? 0 : GetRuns(iter, *r, *f, type, path);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the num-th entry of FileType_t as regular expression.
+// If the file is excluded return "".
+// To get the number of valid entries use GetNumEntries(FileType_t)
+//
+//  e.g.
+//        if (GetNumEntries(MSequence::kDat))<5)
+//            GetFileRegexp(3, MSequence::kRawDat);
+//
+TString MSequence::GetFileRegexp(UInt_t num, FileType_t type) const
+{
+    const TArrayI *r=0, *f=0;
+    GetArrays(r, f, type);
+
+    TString rc = GetFileRegexp(num, *r, *f, type);
+    rc.ReplaceAll(".", "\\.");
+    rc.ReplaceAll("*", ".*");
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the num-th entry of FileType_t as filename. To access the
+// path the default is used if path IsNull, path otherwise.
+// If the file could not be accessed "" is returned, if it is
+// excluded "0".
+// To get the number of valid entries use GetNumEntries(FileType_t)
+//
+//  e.g.
+//        if (GetNumEntries(MSequence::kDat))<5)
+//            GetFileName(3, MSequence::kRawDat);
+//
+TString MSequence::GetFileName(UInt_t num, FileType_t type, const char *path) const
+{
+    const TArrayI *r=0, *f=0;
+    GetArrays(r, f, type);
+    return GetFileName(num, *r, *f, type, path);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the num-th entry of FileType_t as filename.
+// If the file could not be accessed or excluded return "".
+// To get the number of valid entries use GetNumEntries(RunType_t)
+//
+UInt_t MSequence::GetNumEntries(RunType_t type) const
+{
+    const TArrayI *r=0, *f=0;
+    GetArrays(r, f, type);
+    return r->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the num-th entry of RunType_t as run- and file-number.
+// Returns -1 if index is out of range, 0 if file is excluded and
+// 1 in case of success.
+//
+//  e.g.
+//        UInt_t run, file;
+//        GetFile(3, MSequence::kDat, run, file);
+//
+Int_t MSequence::GetFile(UInt_t i, RunType_t type, UInt_t &run, UInt_t &file) const
+{
+    const TArrayI *r=0, *f=0;
+    GetArrays(r, f, type);
+
+    if (i>=(UInt_t)r->GetSize())
+        return -1;
+
+    run  = (*r)[i];
+    file = i<(UInt_t)f->GetSize() ? (*f)[i] : 0;
+
+    if (IsExcluded(run, file))
+        return 0;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a file (run/file) to the arrays defined by RunType_t
+//
+void MSequence::AddFile(UInt_t run, UInt_t file, RunType_t type)
+{
+    const TArrayI *rconst=0, *fconst=0;
+
+    GetArrays(rconst, fconst, type);
+
+    if (!rconst || !fconst)
+    {
+        *fLog << err << "ERROR - Invalid values returned by MSequence::GetArrays... " << run << "." << file << " ignored." << endl;
+        return;
+    }
+
+    TArrayI &r=*const_cast<TArrayI*>(rconst);
+    TArrayI &f=*const_cast<TArrayI*>(fconst);
+
+    AddEntry(run, file, r, f);
+
+    SortArrays(r, f);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get LightCondition from str and convert it to LightCondition_t
+//
+MSequence::LightCondition_t MSequence::GetLightCondition(const TString &str) const
+{
+    if (!str.CompareTo("n/a", TString::kIgnoreCase))
+        return kNA;
+    if (!str.CompareTo("No_Moon", TString::kIgnoreCase))
+        return kNoMoon;
+    if (!str.CompareTo("NoMoon", TString::kIgnoreCase))
+        return kNoMoon;
+    if (!str.CompareTo("Twilight", TString::kIgnoreCase))
+        return kTwilight;
+    if (!str.CompareTo("Moon", TString::kIgnoreCase))
+        return kMoon;
+    if (!str.CompareTo("Day", TString::kIgnoreCase))
+        return kDay;
+
+    gLog << warn;
+    gLog << "WARNING - in " << GetBaseName() << ":" << endl;
+    gLog << "          LightCondition-tag is '" << str << "' but must be n/a, no_moon, twilight, moon or day." << endl;
+    return kNA;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the path to the data. If no path is given the data-center default
+// path is used to access the files.
+//
+// kTRUE is returned if the path is acessible, kFALSE otherwise.
+// (In case of the default path kTRUE is returned in any case)
+//
+Bool_t MSequence::SetDataPath(const char *path)
+{
+    fDataPath = path;
+
+    gSystem->ExpandPathName(fDataPath);
+
+    const Bool_t rc = !fDataPath.IsNull() && gSystem->AccessPathName(fDataPath, kFileExists);
+    if (rc)
+        gLog << err << "ERROR - Directory '" << fDataPath << "' doesn't exist." << endl;
+
+    return !rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a sequence from a file. To set the location of the data (datapath)
+// use SetDataPath. The sequence number given is used if no sequence
+// number is found in the sequence file.
+//
+// If the file could not be found or accesed kFALSE is returned, kTRUE
+// otherwise.
+//
+Bool_t MSequence::ReadFile(const char *filename, UInt_t seq)
+{
+    fFileName = filename;
+
+    gSystem->ExpandPathName(fFileName);
+
+    const Bool_t rc = gSystem->AccessPathName(fFileName, kFileExists);
+    if (rc)
+        gLog << err << "ERROR - Sequence file '" << filename << "' doesn't exist." << endl;
+
+    MEnv env(fFileName);
+
+    fSequence = (UInt_t)env.GetValue("Sequence", (Int_t)seq);
+
+    const TString prefix = MString::Format("Sequence%08d", fSequence);
+
+    fTelescope = GetEnvValue2(env, prefix, "Telescope",  1);
+    fLastRun   = GetEnvValue2(env, prefix, "LastRun",   -1);
+    fNumEvents = GetEnvValue2(env, prefix, "NumEvents", -1);
+    fDrsSequence = GetEnvValue2(env, prefix, "DrsSequence", 0);
+
+    TString str;
+    str = GetEnvValue2(env, prefix, "LightCondition", "n/a");
+    fLightCondition = GetLightCondition(str);
+
+    str = GetEnvValue2(env, prefix, "Start", "");
+    fStart.SetSqlDateTime(str);
+
+    str = GetEnvValue2(env, prefix, "Night", "");
+    SetNight(str);
+
+    fProject      = GetEnvValue2(env, prefix, "Project", "");
+    fSource       = GetEnvValue2(env, prefix, "Source", "");
+    fTriggerTable = GetEnvValue2(env, prefix, "TriggerTable", "");
+    fHvSettings   = GetEnvValue2(env, prefix, "HvSettings", "");
+    fMonteCarlo   = GetEnvValue2(env, prefix, "MonteCarlo", kFALSE);
+    fComment      = GetEnvValue2(env, prefix, "Comment",    "");
+
+    Split(env, prefix, "Runs",    fRuns,     fRunsSub);
+    Split(env, prefix, "CalRuns", fCalRuns,  fCalRunsSub);
+    Split(env, prefix, "PedRuns", fPedRuns,  fPedRunsSub);
+    Split(env, prefix, "DatRuns", fDatRuns,  fDatRunsSub);
+    Split(env, prefix, "DrsRuns", fDrsRuns,  fDrsRunsSub);
+    Split(env, prefix, "DrsFiles",fDrsFiles, fDrsFilesSub);
+    Split(env, prefix, "Exclude", fExclRuns, fExclRunsSub);
+
+    if (fDrsRuns.GetSize()==0 && fDrsFiles.GetSize()>1)
+        gLog << warn << "WARNING - In a data sequence only one DrsFiles entry makes sense." << endl;
+
+    // Dummies:
+    env.Touch("Period");
+    env.Touch("ZdMin");
+    env.Touch("ZdMax");
+    env.Touch("L1TriggerTable");
+    env.Touch("L2TriggerTable");
+
+    if (seq==(UInt_t)-1 && env.GetNumUntouched()>0)
+    {
+        gLog << warn << "WARNING - At least one resource in the sequence-file has not been touched!" << endl;
+        env.PrintUntouched();
+    }
+
+    return !rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Instantiate a file from either a file or the database.
+//
+// If not valid sequence could be created the sequence is invalidated,
+// which can be queried with IsValid.
+//
+//  see ReadFile, ReadDatabase and SetDataPath for more details.
+//
+MSequence::MSequence(const char *fname, const char *path, UInt_t seq)
+   : fTelescope(1), fSequence((UInt_t)-1), fLastRun((UInt_t)-1),
+     fNumEvents((UInt_t)-1), fPeriod((UInt_t)-1), fLightCondition(kNA),
+     fMonteCarlo(kFALSE)
+{
+    fName  = "MSequence";
+    fTitle = "Sequence file";
+
+    if (TString(fname).IsNull() && TString(path).IsNull() && seq==(UInt_t)-1)
+        return;
+
+    // regular expression to distinguish beween a mysql-path and
+    // a filename from where the sequence should be retrieved
+    TPRegexp regexp("mysql://[a-zA-Z0-9]+:.+@[a-zA-Z0-9]+/[a-zA-Z0-9]+/([0-9]+:)?[0-9]+");
+
+    const TString db = TString(fname)(regexp);
+
+    const Bool_t rc1 = db.IsNull() ? ReadFile(fname, seq) : ReadDatabase(fname, seq);
+    const Bool_t rc2 = SetDataPath(path);
+
+    if (!rc1 || !rc2)
+        fSequence = (UInt_t)-1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a sequence from the database. Give the path to the database as:
+//    mysql://user:password@name/database
+// In this case you MUST give a sequence number.
+//
+// You can code the telescope and sequence number into the path and
+// omit the arguments:
+//    mysql://user:password@name/database/[tel:]sequence
+//
+// The third option is to give just the sql.rc as string in the argument.
+// In this case you MUST give a sequence number.
+//
+// If the telecope number is omitted as argument, i.e. ==0, or in the
+// database path, a sequence is read from the database if the sequence
+// number is unambiguous.
+//
+// kFALSE is returned if the final sequence is invalid, kTRUE in case of
+// success.
+//
+Bool_t MSequence::ReadDatabase(TString name, UInt_t seq, UShort_t tel)
+{
+    TPRegexp regexp("([0-9]+:)?[0-9]+$");
+
+    const TString telseq = name(regexp);
+
+    if (!telseq.IsNull())
+    {
+        const Ssiz_t p = telseq.First(':');
+
+        const TString strtel = p<0 ? TString("") : telseq(0, p);
+        const TString strseq = telseq(p+1, telseq.Length());
+
+        tel = strtel.Atoi();
+        seq = strseq.Atoi();
+
+        name = gSystem->DirName(name);
+    }
+
+    *this = MSequenceSQL(name, seq, tel);
+
+    return IsValid();
+}
+
+// --------------------------------------------------------------------------
+//
+// Create a sequence from the database, e.g.
+//
+//    TString mysql     = "mysql://MAGIC:password@vela/MyMagic";
+//    Int_t   sequence  = 100002;
+//    Int_t   telescope = 1;
+//
+//    MSequence seq(mysql, sequence, telescope);
+//
+// Is the telescope number is omitted (==0) the database is checked for
+// an unambiguous sequence.
+//
+// For more details see ReadDatabase and MSequenceSQL.
+//
+MSequence::MSequence(const char *fname, UInt_t seq, UShort_t tel)
+{
+    const Bool_t rc = ReadDatabase(fname, seq, tel);
+
+    fName  = "MSequence";
+    fTitle = "Sequence file";
+
+    if (!rc)
+        fSequence = (UInt_t)-1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Some helper functions for the comparison functions
+//
+static int operator==(const TArrayI &a, const TArrayI &b)
+{
+    return a.GetSize()==b.GetSize() &&
+        memcmp(a.GetArray(), b.GetArray(), a.GetSize()*sizeof(Int_t));
+}
+
+static int IsNull(const TArrayI &a, const TArrayI &b)
+{
+    return a==TArrayI(a.GetSize()) && b==TArrayI(b.GetSize());
+}
+
+static int Check(const TArrayI &a, const TArrayI &b)
+{
+    return a==b || IsNull(a, b);
+}
+
+// --------------------------------------------------------------------------
+//
+// Here we test all things mandatory for a sequence:
+//   fTelescope
+//   fSequence
+//   fNight
+//   fMonteCarlo
+//   fCalRuns
+//   fCalRunsSub
+//   fPedRuns
+//   fPedRunsSub
+//   fDatRuns
+//   fDatRunsSub
+//   fDrsRuns
+//   fDrsRunsSub
+//   fExclRuns
+//   fExclRunsSub
+//
+Bool_t MSequence::IsCompatible(const MSequence &s) const
+{
+    return // Mandatory
+        fTelescope   == s.fTelescope   &&
+        fSequence    == s.fSequence    &&
+        fNight       == s.fNight       &&
+
+        fMonteCarlo  == s.fMonteCarlo  &&
+
+        fCalRuns     == s.fCalRuns     &&
+        fPedRuns     == s.fPedRuns     &&
+        fDatRuns     == s.fDatRuns     &&
+        fDrsRuns     == s.fDrsRuns     &&
+        fExclRuns    == s.fExclRuns    &&
+
+        Check(fCalRunsSub,  s.fCalRunsSub) &&
+        Check(fPedRunsSub,  s.fPedRunsSub) &&
+        Check(fDatRunsSub,  s.fDatRunsSub) &&
+        Check(fDrsRunsSub,  s.fDrsRunsSub) &&
+        Check(fExclRunsSub, s.fExclRunsSub);
+}
+
+// --------------------------------------------------------------------------
+//
+// Here we test whether all values of a sequence are identical
+//   IsCompaticle(s)
+//   fStart
+//   fLastRun
+//   fNumEvents
+//   fPeriod
+//   fProject
+//   fSource
+//   fRuns
+//   fHvSettings
+//   fTriggerTable
+//   fLightCondition
+//   fRuns
+//   fRunsSub
+//
+Bool_t MSequence::operator==(const MSequence &s) const
+{
+    return IsCompatible(s) &&
+        // Unnecessary
+        fStart          == s.fStart          &&
+        fLastRun        == s.fLastRun        &&
+        fNumEvents      == s.fNumEvents      &&
+        fPeriod         == s.fPeriod         &&
+        fProject        == s.fProject        &&
+        fSource         == s.fSource         &&
+        fRuns           == s.fRuns           &&
+        fHvSettings     == s.fHvSettings     &&
+        fTriggerTable   == s.fTriggerTable   &&
+        fLightCondition == s.fLightCondition &&
+        Check(fRunsSub, s.fRunsSub);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the sequence has also identical source, i.e.
+// the sequence filepath and the datapath in addition to operator==
+//
+Bool_t MSequence::IsIdentical(const MSequence &s) const
+{
+    return *this==s &&
+        // Obsolete
+        fDataPath==s.fDataPath && fFileName==s.fFileName;
+}
+
+//---------------------------------------------------------------------------
+//
+// Make sure that the name used for writing doesn't contain a full path
+//
+const char *MSequence::GetBaseName() const
+{
+    return gSystem->BaseName(fFileName);
+}
+
+//---------------------------------------------------------------------------
+//
+// Make sure that the name used for writing doesn't contain a full path
+//
+const char *MSequence::GetFilePath() const
+{
+    return gSystem->DirName(fFileName);
+}
+
+// --------------------------------------------------------------------------
+//
+// Find a sequence of continous numbers in f starting at pos (looking
+// only at n entries). The output is converted into sequences
+// of X (single r) and X:Y (a sequence between x and r). The function
+// returnes when position pos+n is reached
+//
+TString MSequence::GetNumSequence(Int_t pos, Int_t n, const TArrayI &f) const
+{
+    TString str;
+
+    Int_t p=pos;
+    while (p<pos+n)
+    {
+        str += MString::Format(" %d", f[p]);
+
+        if (p==pos+n-1)
+            break;
+
+        int i=0;
+        while (++i<n)
+            if (f[p+i]-f[p]!=i)
+                break;
+
+        if (i>1)
+            str += MString::Format(":%d", f[p+i-1]);
+
+        p += i;
+    }
+
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for a sequence of continous numbers in r with f==0 starting at p.
+// A new starting p is returned. The output is converted into sequences
+// of X (single r) and X:Y (a sequence between x and r). The function
+// returnes with the next f!=0.
+//
+TString MSequence::GetNumSequence(Int_t &p, const TArrayI &r, const TArrayI &f) const
+{
+    TString str;
+
+    while (p<r.GetSize() && f[p]==0)
+    {
+        // serach for the first entry which doesn't fit
+        // or has a file number which is != 0
+        int i=0;
+        while (p+ ++i<r.GetSize())
+            if (r[p+i]-r[p]!=i || f[p+i]!=0)
+                break;
+
+        // None found (i-1==0)
+        if (i-1==0)
+            return str;
+
+        // The last run found in the sequence (e.g. 5.0) is followed
+        // by an identical run number but file != 0 (e.g. 5.1)
+        if (p+i<f.GetSize() && r[p+i]==r[p] && f[p+i]!=0)
+            i--;
+
+        // Now we have to check again whether found no valid entry
+        if (i-1==0)
+            return str;
+
+        str += MString::Format(" %d", r[p]);
+        // p now points to the last entry which fits and
+        // has a file number == 0
+        p += i-1;
+        // Only one      found (i-1==1)
+        // More tahn one found (i-1>1)
+        str += i-1==1 ? " " : ":";
+        str += MString::Format("%d", r[p]);
+
+        // One step forward
+        p++;
+    }
+
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the runs in a compressed wa. Returns the RunXXXXXXX string
+// simplyfing the file setup
+//
+TString MSequence::PrintRuns(ostream &out, const char *pre, const char *name, const TArrayI &r, const TArrayI &f) const
+{
+    if (r.GetSize()==0)
+        return "";
+
+    out << pre << name;
+    if (f.GetSize()==0)
+        const_cast<TArrayI&>(f).Set(r.GetSize());
+
+#ifdef DEBUG
+    for (int i=0; i<r.GetSize(); i++)
+        out << "  " << r[i] << "." << f[i];
+    out << endl;
+    return "";
+#endif
+
+    TString str;
+
+    Int_t pos = 0;
+    while (pos<r.GetSize())
+    {
+        TString rc = GetNumSequence(pos, r, f);
+        if (!rc.IsNull())
+        {
+            out << rc;
+            continue;
+        }
+
+        Int_t n = GetSubArray(pos, r.GetSize(), (Int_t*)r.GetArray());
+        // end reached
+        if (n<0)
+            break;
+
+        // This can happen if it is the last entry
+        if (n==1)
+        {
+            out << " " << r[pos];
+            if (f[pos]>=0)
+                out << "." << f[pos];
+        }
+        else
+        {
+            // Check for sequence
+            Bool_t isseq = kTRUE;
+            for (int i=1; i<n; i++)
+                if (f[pos+i]-f[pos]!=i)
+                    isseq=kFALSE;
+
+            if (isseq)
+            {
+                out << " " << r[pos] << ".";
+                if (f[pos]>=0)
+                    out << f[pos];
+                out << ":" << f[pos+n-1];
+            }
+            else
+            {
+                out << " " << r[pos] << "+";
+
+                str += '\n';
+                str += pre;
+                str += MString::Format("Run%08d:", r[pos]);
+                str += GetNumSequence(pos, n, f);
+            }
+        }
+
+        pos += n;
+    }
+
+    out << endl;
+
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the numbers in the classical way (one run after the other)
+//
+void MSequence::PrintRunsClassic(ostream &out, const char *pre, const char *name, const TArrayI &r) const
+{
+    out << pre << name;
+    for (int i=0; i<r.GetSize(); i++)
+        out << " " << r[i];
+    out << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the sequence
+//
+void MSequence::Print(ostream &out, Option_t *o) const
+{
+    const TString opt(o);
+
+    const TString pre = opt.Contains("prefixed") ? MString::Format("Sequence%08d.", fSequence) : "";
+
+    if (!IsValid())
+    {
+        out << pre << "Sequence: " << fFileName << " <invalid>" << endl;
+        return;
+    }
+    if (!fFileName.IsNull())
+        out << "# FileName: " << fFileName << endl;
+    if (!fDataPath.IsNull())
+        out << "# DataPath: " << fDataPath << endl;
+    out << endl;
+    if (pre.IsNull())
+        out << "Sequence:       " << fSequence << endl;
+    if (fTelescope!=1)
+        out << "Telescope:      " << fTelescope << endl;
+    if (fMonteCarlo)
+        out << pre << "MonteCarlo:     Yes" << endl;
+    if (fPeriod!=(UInt_t)-1)
+        out << pre << "Period:         " << fPeriod << endl;
+    if (fNight!=MTime())
+        out << pre << "Night:          " << fNight.GetStringFmt("%Y-%m-%d") << endl;
+    out << endl;
+    if (fLightCondition!=kNA)
+    {
+        out << pre << "LightCondition: ";
+        switch (fLightCondition)
+        {
+        case kNA:       out << "n/a" << endl;      break;
+        case kNoMoon:   out << "NoMoon" << endl;   break;
+        case kTwilight: out << "Twilight" << endl; break;
+        case kMoon:     out << "Moon" << endl;     break;
+        case kDay:      out << "Day" << endl;      break;
+        }
+    }
+
+    if (fStart!=MTime())
+        out << pre << "Start:          " << fStart.GetSqlDateTime() << endl;
+    if (fLastRun!=(UInt_t)-1)
+        out << pre << "LastRun:        " << fLastRun << endl;
+    if (fDrsSequence)
+        out << pre << "DrsSequence:    " << fDrsSequence << endl;
+    if (fNumEvents!=(UInt_t)-1)
+        out << pre << "NumEvents:      " << fNumEvents << endl;
+    if (!fProject.IsNull())
+        out << pre << "Project:        " << fProject << endl;
+    if (!fSource.IsNull())
+        out << pre << "Source:         " << fSource << endl;
+    if (!fTriggerTable.IsNull())
+        out << pre << "TriggerTable:   " << fTriggerTable << endl;
+    if (!fHvSettings.IsNull())
+        out << pre << "HvSettings:     " << fHvSettings << endl;
+    out << endl;
+
+    TString str;
+    if (!HasSubRuns() && opt.Contains("classic"))
+    {
+        PrintRunsClassic(out, pre, "Runs:     ", fRuns);
+        PrintRunsClassic(out, pre, "CalRuns:  ", fCalRuns);
+        PrintRunsClassic(out, pre, "PedRuns:  ", fPedRuns);
+        PrintRunsClassic(out, pre, "DataRuns: ", fDatRuns);
+        PrintRunsClassic(out, pre, "DrsRuns:  ", fDrsRuns);
+        PrintRunsClassic(out, pre, "DrsFiles: ", fDrsFiles);
+        PrintRunsClassic(out, pre, "Exclude:  ", fExclRuns);
+    }
+    else
+    {
+        // FIXME: This needs more check!
+        // FORBID the + syntax in "Runs"
+        // Could we make "Runs" an automatic summary of all runs?
+        // Should we add a check forbidding the same run in
+        // Cal/Ped/Data? What about the Exclude?
+        /*str +=*/ PrintRuns(out, pre, "Runs:     ", fRuns,     fRunsSub);
+        str += PrintRuns(out, pre, "CalRuns:  ", fCalRuns,  fCalRunsSub);
+        str += PrintRuns(out, pre, "PedRuns:  ", fPedRuns,  fPedRunsSub);
+        str += PrintRuns(out, pre, "DatRuns:  ", fDatRuns,  fDatRunsSub);
+        str += PrintRuns(out, pre, "DrsRuns:  ", fDrsRuns,  fDrsRunsSub);
+        str += PrintRuns(out, pre, "DrsFiles: ", fDrsFiles, fDrsFilesSub);
+        str += PrintRuns(out, pre, "Exclude:  ", fExclRuns, fExclRunsSub);
+    }
+
+//    if (!fDataPath.IsNull())
+//        out << endl << pre << "DataPath: " << fDataPath << endl;
+
+    if (!str.IsNull())
+        out << str << endl;
+
+    out << endl;
+
+    if (!fComment.IsNull())
+        out << pre << "Comment: " << fComment << endl;
+
+    if (GetDrsFile())
+        out << "# DrsFile: " << GetDrsFile() << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the sequence to gLog
+//
+void MSequence::Print(Option_t *o) const
+{
+    gLog << all;
+    Print(gLog, o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the sequence to the file with name filename
+//
+Bool_t MSequence::WriteFile(const char *name, const Option_t *o) const
+{
+    ofstream fout(name);
+    if (!fout)
+    {
+        gLog << err << "ERROR - Cannot open file " << name << ": ";
+        gLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    Print(fout, o);
+
+    if (!fout)
+    {
+        gLog << err << "ERROR - Writing file " << name << ": ";
+        gLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// check if the run/file is contained in the arrays.
+//
+Bool_t MSequence::IsContained(const TArrayI &arr, const TArrayI &sub, UInt_t run, UInt_t file) const
+{
+    // Backward compatibilty
+    if (sub.GetSize()==0)
+    {
+        for (int i=0; i<arr.GetSize(); i++)
+            if (run==(UInt_t)arr[i])
+                return kTRUE;
+    }
+    else
+    {
+        for (int i=0; i<arr.GetSize(); i++)
+            if (run==(UInt_t)arr[i] && file==(UInt_t)sub[i])
+                return kTRUE;
+    }
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Exclude all runs which are found in the list, e.g. "100 102 105"
+//
+void MSequence::ExcludeRuns(TString runs)
+{
+    // FIXME: Decode stream!!!
+
+    TArrayI data, sub;
+    Split(runs, data, sub);
+    for (int i=0; i<data.GetSize(); i++)
+        ExcludeFile(data[i], sub[i]);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the excluded runs (to be more precise:the excluded files)
+// in a string
+//
+const TString MSequence::GetExcludedRuns() const
+{
+    TString rc;
+    for (int i=0; i<fExclRuns.GetSize(); i++)
+    {
+        rc += fExclRuns[i];
+        if (fExclRunsSub.GetSize()>0)
+        {
+            rc += ".";
+            rc += fExclRunsSub[i];
+        }
+        rc += " ";
+    }
+    return rc(0, rc.Length()-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to change or set the night manually.
+// The Format is
+//     SetNight("yyyy-mm-dd");
+//
+void MSequence::SetNight(const char *txt)
+{
+    TString night(txt);
+
+    if (night.IsNull())
+    {
+        fNight  = MTime();
+        fPeriod = UInt_t(-1);
+        return;
+    }
+
+    night += " 00:00:00";
+    fNight.SetSqlDateTime(night);
+
+    fPeriod = fNight.GetMagicPeriod();
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a sequence from gDirectory. If the default is given we try
+// to find a sequence with name GetName. If a key with name name
+// exists in the file read this key. Otherwise loop over all keys
+// and return the first key matching the TPRegex (regular expression)
+// matching defined by the argument.
+//
+Int_t MSequence::Read(const char *name)
+{
+    if (!name || !gDirectory)
+        return MParContainer::Read(name);
+
+    if (gDirectory->GetListOfKeys()->FindObject(name))
+        return MParContainer::Read(name);
+
+    TPRegexp regexp(name);
+
+    TIter NextK(gDirectory->GetListOfKeys());
+    TObject *key = 0;
+    while ((key=NextK()))
+        if (TString(key->GetName())(regexp)==key->GetName())
+            return MParContainer::Read(key->GetName());
+
+    *fLog << warn << "WARNING - No key in " << gDirectory->GetName() << " matching " << name << "." << endl;
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// If the sequence name seq is just a digit it is inflated to a full
+// path following the datacenter standard.
+//
+// Returns if file accessible or not.
+//
+Bool_t MSequence::InflateSeq(TString &seq, Bool_t ismc)
+{
+    TObjArray *arr = seq.Tokenize(':');
+    if (arr->GetEntries()<3)
+    {
+        TString num1 = (*arr)[0]->GetName();
+        TString num2 = arr->GetEntries()==2 ? (*arr)[1]->GetName() : "";
+
+        if (num1.IsDigit() && num2.IsDigit())
+        {
+            gLog << err << "ERROR - InflateSeq 'telescope:sequence' not yet implemented." << endl;
+            delete arr;
+            return kFALSE;
+        }
+
+        if (num1.IsDigit() && num2.IsNull())
+        {
+            const Int_t numseq = seq.Atoi();
+            seq = "/magic/";
+            if (ismc)
+                seq += "montecarlo/";
+            seq += MString::Format("sequences/%04d/sequence%08d.txt", numseq/10000, numseq);
+            gLog << inf << "Inflated sequence file: " << seq << endl;
+        }
+    }
+    delete arr;
+
+    if (!gSystem->AccessPathName(seq, kFileExists))
+        return kTRUE;
+
+    gLog << err << "Sorry, sequence file '" << seq << "' doesn't exist." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search starting at position p in array arr and return the number
+// of elemets which are identical to the starting entry (the starting entry
+// is also counted)
+//
+Int_t MSequence::GetSubArray(Int_t p, Int_t n, Int_t *arr)
+{
+    Int_t *ptr0 = arr+p;
+
+    Int_t *ptr = ptr0;
+    Int_t *end = arr+n;
+
+    while (ptr<end && *ptr==*ptr0)
+        ptr++;
+
+    return ptr-ptr0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sort the array arr2 starting at position p for following entries
+// for which arr1 is equal. If not at least two entries are found which
+// can be sorted return -1.
+//
+// The absolute index of the next entry in arr1 is returned.
+//
+Int_t MSequence::SortArraySub(Int_t p, Int_t n, Int_t *arr1, Int_t *arr2)
+{
+    Int_t *ptr2 = arr2+p;
+
+    Int_t cnt = GetSubArray(p, n, arr1);
+    if (cnt==0)
+        return -1;
+
+    TArrayI srt(cnt, ptr2);
+    MJob::SortArray(srt);
+
+    memcpy(ptr2, srt.GetArray(), srt.GetSize()*sizeof(Int_t));
+
+    return p+srt.GetSize();
+}
+
+void MSequence::SortArrays(TArrayI &arr1, TArrayI &arr2)
+{
+    if (arr1.GetSize()!=arr2.GetSize())
+        return;
+
+    TArrayI idx(arr1.GetSize());
+
+    TArrayI srt1(arr1);
+    TArrayI srt2(arr2);
+
+    TMath::Sort(arr1.GetSize(), srt1.GetArray(), idx.GetArray(), kFALSE);
+
+    for (int i=0; i<arr1.GetSize(); i++)
+    {
+        arr1[i] = srt1[idx[i]];
+        arr2[i] = srt2[idx[i]];
+    }
+
+    Int_t p = 0;
+    while (p>=0)
+        p = SortArraySub(p, arr1.GetSize(), arr1.GetArray(), arr2.GetArray());
+}
Index: branches/Mars_McMismatchStudy/mjobs/MSequence.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MSequence.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MSequence.h	(revision 17960)
@@ -0,0 +1,270 @@
+#ifndef MARS_MSequence
+#define MARS_MSequence
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MDirIter;
+
+class MSequence : public MParContainer
+{
+    friend class MSequenceSQL;
+
+public:
+    enum LightCondition_t { kNA, kNoMoon, kTwilight, kMoon, kDay };
+
+    enum FileExt_t {
+        kRaw    =BIT(0),
+        kRoot   =BIT(1),
+        kReport =BIT(2),
+        kCer    =BIT(3),  // Corsika files
+        kFits   =BIT(4),
+        kDrs    =BIT(5),
+        kFact   =BIT(6),
+    };
+    enum RunType_t {
+        kPed    =BIT(7),  // Don't use overlapping bits!
+        kCal    =BIT(8),
+        kDat    =BIT(9),
+        kExcl   =BIT(10),
+        kAll    =kPed|kDat|kCal,
+        kImage  =BIT(11),
+        kCalib  =BIT(12),
+        kDrsRun =BIT(13),
+        kDrsFile=BIT(14),
+    };
+
+    enum { kRunType   = kPed|kCal|kDat|kImage|kCalib|kDrsRun|kDrsFile };
+    enum { kFileType  = kRaw|kRoot|kReport|kCer|kDrs|kFits|kFact };
+    enum { kFilePaths = kFileType|kImage|kCalib };
+
+    enum FileType_t {
+        kRawDat     = kRaw   |kDat,
+        kRawPed     = kRaw   |kPed,
+        kRawCal     = kRaw   |kCal,
+        kFitsPed    = kFits  |kPed,
+        kFitsCal    = kFits  |kCal,
+        kFitsDat    = kFits  |kDat,
+        kFitsDrs    = kFits  |kDrsFile,
+        kFitsDrsRuns= kFits  |kDrsRun,
+        kFactCal    = kFits  |kCalib,
+        kFactImg    = kFits  |kImage,
+        kRawDrs     = kDrs   |kDrsFile,
+        kRawAll     = kRaw   |kAll,
+        kRootDat    = kRoot  |kDat,
+        kRootPed    = kRoot  |kPed,
+        kRootCal    = kRoot  |kCal,
+        kRootAll    = kRoot  |kAll,
+        kReportPed  = kReport|kPed,
+        kReportCal  = kReport|kCal,
+        kReportDat  = kReport|kDat,
+        kReportAll  = kReport|kAll,
+        kCalibrated = kRoot  |kCalib,
+        kImages     = kRoot  |kImage,
+        kCorsika    = kCer   |kDat,
+    };
+
+private:
+    TString fFileName;         // Expanded file name
+    TString fDataPath;         // Path to data files
+
+    UShort_t fTelescope;       // Telescope number
+    UInt_t   fSequence;        // Sequence number
+
+    MTime  fStart;             // Start time of sequence
+
+    UInt_t fLastRun;           // Last run in sequence (necessary?)
+    UInt_t fNumEvents;         // Number of events in sequence
+
+    UInt_t fPeriod;            // Observation period of the sequence
+    MTime  fNight;             // Night (day of sunrise) of the sequence
+
+    UInt_t fDrsSequence;       // Corresponding DRS sequence
+
+    LightCondition_t fLightCondition;
+
+    TString fProject;
+    TString fSource;
+    TString fTriggerTable;
+    TString fHvSettings;
+    TString fComment;
+
+    TArrayI fRuns;            // Run numbers
+    TArrayI fRunsSub;         // Sub runs (files)
+
+    TArrayI fCalRuns;         // Numbers of calibration runs/files
+    TArrayI fCalRunsSub;      // Sub runs (files) of calibration runs
+
+    TArrayI fPedRuns;         // Numbers of pedestal runs/files
+    TArrayI fPedRunsSub;      // Sub runs (files) of pedestal runs
+
+    TArrayI fDatRuns;         // Numbers of data runs/files
+    TArrayI fDatRunsSub;      // Sub runs (files) of data runs
+
+    TArrayI fDrsRuns;         // Numbers of drs pedestal runs/files
+    TArrayI fDrsRunsSub;      // Sub runs (files) of drs pedestal runs
+
+    TArrayI fDrsFiles;        // Runs for which DRS files exist
+    TArrayI fDrsFilesSub;     // Sub runs (files) of DRS files runs
+
+    TArrayI fExclRuns;        // Numbers of excluded runs/files
+    TArrayI fExclRunsSub;     // Sub runs (files) of excluded runs
+
+    Bool_t fMonteCarlo;       // Flag for Monte Carlo sequences
+
+    // Helper for interpretation
+    void    AddEntry(Int_t run, Int_t file, TArrayI &data, TArrayI &sub) const;
+    void    EvalEntry(const TEnv *env, const TString &prefix, const TString &num, TArrayI &data, TArrayI &sub) const;
+
+    void    Split(TString &runs, TArrayI &data, TArrayI &sub, const TEnv *env=0, const TString prefix="") const;
+    void    Split(const TEnv &env, const TString &prefix, const char *name, TArrayI &data, TArrayI &sub) const;
+
+    LightCondition_t GetLightCondition(const TString &str) const;
+
+    // Helper for file setup
+    void    GetArrays(const TArrayI* &r, const TArrayI* &f, Int_t type) const;
+    Bool_t  FindPath(TString &path, FileType_t type) const;
+    TString FindPath(FileType_t type, TString path="") const { FindPath(path, type); return path; }
+    TString FindFile(const TString &d, const TString &f) const;
+    TString GetPathName(TString d, FileType_t type) const;
+    TString GetFileRegexp(UInt_t num, const TArrayI &arr, const TArrayI &sub, FileType_t type) const;
+    TString GetFileName(UInt_t i, const TArrayI &arr, const TArrayI &sub, FileType_t type, const char *path) const;
+    UInt_t  GetRuns(MDirIter &iter, const TArrayI &arr, const TArrayI &file, FileType_t type, TString path="") const;
+
+    // Helper for Print()
+    TString GetNumSequence(Int_t pos, Int_t n, const TArrayI &f) const;
+    TString GetNumSequence(Int_t &pos, const TArrayI &n, const TArrayI &f) const;
+
+    void    PrintRunsClassic(std::ostream &out, const char *pre, const char *name, const TArrayI &r) const;
+    TString PrintRuns(std::ostream &out, const char *pre, const char *name, const TArrayI &r, const TArrayI &f) const;
+
+    // General helper
+    Bool_t  HasSubRuns() const { return fRunsSub.GetSize()!=0 || fDatRunsSub.GetSize()!=0 || fPedRunsSub.GetSize()!=0 || fCalRunsSub.GetSize()!=0 || fDrsRunsSub.GetSize()!=0 || fDrsFilesSub.GetSize()!=0 || fExclRunsSub.GetSize()!=0; }
+    Bool_t  IsContained(const TArrayI &arr, const TArrayI &sub, UInt_t num, UInt_t file) const;
+
+    // Some helpers to handle the arrays
+    static Int_t SortArraySub(Int_t p, Int_t n, Int_t *arr1, Int_t *arr2);
+    static void  SortArrays(TArrayI &arr1, TArrayI &arr2);
+    static Int_t GetSubArray(Int_t p, Int_t n, Int_t *arr1);
+
+public:
+/*
+    MSequence() : fTelescope(1), fSequence((UInt_t)-1), fLastRun((UInt_t)-1),
+        fNumEvents((UInt_t)-1), fPeriod((UInt_t)-1), fLightCondition(kNA), fMonteCarlo(kFALSE)
+    {
+        fName  = "MSequence";
+        fTitle = "Sequence file";
+    }
+    */
+    MSequence(const char *fname=0, const char *path=0, UInt_t id=(UInt_t)-1);
+    MSequence(const char *fname, UInt_t seq, UShort_t tel=0);
+    MSequence(const MSequence &s) : MParContainer(s),
+        fFileName(s.fFileName), fDataPath(s.fDataPath),
+        fTelescope(s.fTelescope),
+        fSequence(s.fSequence), fStart(s.fStart),
+        fLastRun(s.fLastRun), fNumEvents(s.fNumEvents), fPeriod(s.fPeriod),
+        fNight(s.fNight), fLightCondition(s.fLightCondition),
+        fProject(s.fProject), fSource(s.fSource),
+        fTriggerTable(s.fTriggerTable), fHvSettings(s.fHvSettings),
+        fRuns(s.fRuns), fRunsSub(s.fRunsSub), fCalRuns(s.fCalRuns),
+        fCalRunsSub(s.fCalRunsSub), fPedRuns(s.fPedRuns),
+        fPedRunsSub(s.fPedRunsSub), fDatRuns(s.fDatRuns),
+        fDatRunsSub(s.fDatRunsSub), fDrsRuns(s.fDrsRuns),
+        fDrsRunsSub(s.fDrsRunsSub), fDrsFiles(s.fDrsFiles),
+        fDrsFilesSub(s.fDrsFilesSub), fExclRuns(s.fExclRuns),
+        fExclRunsSub(s.fExclRunsSub), fMonteCarlo(s.fMonteCarlo) { }
+
+    Bool_t IsCompatible(const MSequence &s) const;
+    Bool_t IsIdentical(const MSequence &s) const;
+    Bool_t operator==(const MSequence &s) const;
+
+    // I/O
+    Int_t  Read(const char *name=0);
+    Bool_t ReadDatabase(TString sql, UInt_t seq=0, UShort_t tel=0);
+    Bool_t ReadFile(const char *filename, UInt_t id=(UInt_t)-1);
+    Bool_t WriteFile(const char *filename, const Option_t *o) const;
+    Bool_t WriteFile(const char *filename) const { return WriteFile(filename,""); } //*MENU *ARGS={filename=>fBaseName}
+    Bool_t SetDataPath(const char *path="");
+    void   SetDrsSequence(UInt_t seq=0) { fDrsSequence = seq; }
+
+    // TObject
+    void Print(std::ostream &out, Option_t *o) const;
+    void Print(Option_t *o) const;
+    void Print() const { Print(""); } //*MENU*
+
+    // Genaral interface
+    Bool_t IsValid() const { return fTelescope>0 && fSequence!=(UInt_t)-1; }
+    Bool_t IsMonteCarlo() const { return fMonteCarlo; }
+    Bool_t IsExcluded(UInt_t run, UInt_t file) const { return IsContained(fExclRuns, fExclRunsSub, run, file); }
+    Bool_t IsContained(UInt_t run, UInt_t file) const { return IsContained(fCalRuns, fCalRunsSub, run, file) || IsContained(fPedRuns, fPedRunsSub, run, file) || IsContained(fDatRuns, fDatRunsSub, run, file) || IsContained(fDrsRuns, fDrsRunsSub, run, file); }
+
+    // Setter
+    void SetNight(const char*night);
+
+    void AddRun(UInt_t run, RunType_t type=kAll) { AddFile(run, 0, type); }
+    void AddRuns(UInt_t run1, UInt_t run2, RunType_t type=kAll) { for (UInt_t i=run1; i<=run2; i++) AddFile(i, 0, type); }
+    void AddFile(UInt_t run, UInt_t file, RunType_t type=kAll);
+    void AddFiles(UInt_t run, UInt_t f1, UInt_t f2, RunType_t type=kAll) { for (UInt_t i=f1; i<=f2; i++) AddFile(run, i, type); }
+
+    void ExcludeFile(UInt_t run, UInt_t file=0) { /*if (!force || !IsExcluded(run, file))*/ AddFile(run, file, kExcl); }
+    void ExcludeRuns(TString runs);
+
+    void SetMonteCarlo(Bool_t ismc=kTRUE) { fMonteCarlo=ismc; }
+
+    // Getter
+    UInt_t GetNumExclRuns() const { return fExclRuns.GetSize(); }
+
+    UShort_t GetTelescope() const { return fTelescope; }
+    UInt_t GetSequence() const { return fSequence; }
+    UInt_t GetLastRun() const  { return fLastRun; }
+    UInt_t GetPeriod() const   { return fPeriod; }
+    UInt_t GetDrsSequence() const { return fDrsSequence; }
+    UInt_t GetDrsFile() const;
+    Bool_t HasMoon() const { return fLightCondition==kMoon; }
+
+    Int_t  GetFile(UInt_t i, RunType_t type, UInt_t &run, UInt_t &file) const;
+
+    LightCondition_t GetLightCondition() const { return fLightCondition; }
+
+    const MTime   &GetStart() const { return fStart; }
+    const MTime   &GetNight() const { return fNight; }
+    const TString &GetSource() const { return fSource; } 
+
+    const TString GetExcludedRuns() const;
+
+    // Filesystem interface
+    UInt_t  GetRuns(MDirIter &iter, FileType_t type, const char *path=0) const;
+    TString GetFileRegexp(UInt_t num, FileType_t type) const;
+    TString GetFileName(UInt_t i, FileType_t type, const char *path=0) const;
+    UInt_t  GetNumEntries(RunType_t type=kAll) const;
+
+    // Filesystem getter
+    const char    *GetBaseName() const;
+    const char    *GetFilePath() const;
+    const TString &GetFileName() const { return fFileName; }
+    const TString &GetDataPath() const { return fDataPath; }
+
+    const TString  GetStandardPath() const { return GetStandardPath(fMonteCarlo); }
+
+    // Static function for external access
+    //static TString GetStandardPath(Bool_t mc) { return mc?"/magic/montecarlo/":"/data00/fact-construction/"; }
+    static TString GetStandardPath(Bool_t mc) { return mc?"/magic/montecarlo/":"/fact/"; }
+    static Bool_t  InflateSeq(TString &seq, /*FIXME: TELNUM*/ Bool_t ismc=kFALSE);
+
+    static TString InflateFileName(const MTime &night, UShort_t tel, Int_t run, Int_t file, Int_t type=kRawAll);
+    static TString InflateFileName(const MTime &night, Int_t run, Int_t type=kRawAll) { return InflateFileName(night, 1, run, 0, type); }
+
+    static TString InflateFilePath(const MTime &night, UShort_t tel, Int_t run, Int_t file=0, Int_t type=kRawAll);
+    static TString InflateFilePath(const MTime &night, Int_t run, Int_t type=kRawAll) { return InflateFilePath(night, 1, run, 0, type); }
+
+    static TString InflateFilePath(const MTime &night, Bool_t mc=kFALSE);
+
+    ClassDef(MSequence, 7) // Describes a sequences, reads and writes sequence files
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/MSequenceSQL.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MSequenceSQL.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MSequenceSQL.cc	(revision 17960)
@@ -0,0 +1,370 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 7/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSequenceSQL
+//
+// This is an extension to retrieve a sequence from a database instead
+// of readin it from a file
+//
+// Example 1:
+//    MSQLMagic serv("sql.rc");
+//    MSequenceSQL s(serv, 100002))
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    MSequenceSQL s("sql.rc", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    MSequence s = MSequenceSQL("sql.rc", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Instead of initializing the constructor directly you can
+// also use the function GetFromDatabase.
+//
+// Instead of a resource file sql.rc you can also give the qualified
+// path to the database:
+//
+//    mysql://user:password@url/database
+//
+//
+// A telscope number of -1 means: Take fTelescope as telescope number
+// to request. A telescope number of 0 tries to get the sequence from
+// the db including the telescope number. This will fail if more than
+// one sequence with the same number exist in the db for several
+// telescopes.
+//
+//
+// This tool will work from Period017 (2004_05_17) on...
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSequenceSQL.h"
+
+#include <stdlib.h> // atof (Ubuntu 8.10)
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MLogManip.h"
+
+#include "MSQLMagic.h"
+
+ClassImp(MSequenceSQL);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// get the list of runs according to the query. Add the runs to run-list
+// according to the type. Stop adding runs if the given number of events
+// is exceeded.
+//
+// return kFALSE in case of error or if no events are in the files.
+//
+Bool_t MSequenceSQL::GetRuns(MSQLMagic &serv, TString query, RunType_t type, UInt_t nevts)
+{
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    UInt_t cnt=0;
+    UInt_t evts=0;
+
+    TSQLRow *row=0;
+    while ((row = res->Next()) && evts<nevts)
+    {
+        AddFile(atoi((*row)[0]), atoi((*row)[1]), type);
+        evts += atoi((*row)[2]);
+        cnt++;
+    }
+
+    delete res;
+
+    if (cnt==0)
+    {
+        *fLog << err << "ERROR - No " << type << " belonging to this sequence found." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get start and stop time as requested and return stop time if start
+// time is invalid. Return a null string in case of an error or no valid time.
+//
+TString MSequenceSQL::GetTimeFromDatabase(MSQLMagic &serv, const TString &query)
+{
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return "";
+
+    // FIXME: Check for the right number of results?
+
+    TSQLRow *row=res->Next();
+
+    const TString start = (*row)[0] ? (*row)[0] : "";
+    const TString stop  = (*row)[1] ? (*row)[1] : "";
+
+    delete res;
+
+    if (!start.IsNull())
+        return start;
+
+    *fLog << warn << "WARNING - Requesting start time of first calibration run failed." << endl;
+
+    if (!stop.IsNull())
+        return stop;
+
+    *fLog << err << "ERROR - Neither start nor stop time of first calibration could be requested." << endl;
+    return "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert the result into the MSequence data members
+//
+Bool_t MSequenceSQL::GetFromDatabase(MSQLMagic &serv, TSQLRow &data)
+{
+    // Convert the keys from the sequence table to strings
+    TString str[6];
+    str[0] = serv.QueryNameOfKey("Project",         data[1]);
+    str[1] = serv.QueryNameOfKey("Source",          data[2]);
+    str[2] = serv.QueryNameOfKey("L1TriggerTable",  data[3]);
+    str[3] = serv.QueryNameOfKey("L2TriggerTable",  data[4]);
+    str[4] = serv.QueryNameOfKey("HvSettings",      data[5]);
+    str[5] = serv.QueryNameOfKey("LightConditions", data[6]);
+
+    // check that all strings are valid
+    if (str[0].IsNull() || str[1].IsNull() || str[2].IsNull() || str[3].IsNull() || str[4].IsNull() || str[5].IsNull())
+        return kFALSE;
+
+    // Setup the time and night
+    MTime time;
+    time.SetSqlDateTime(data[7]);
+    MTime night = time.GetDateOfSunrise();
+
+    SetNight(night.GetStringFmt("%Y-%m-%d"));
+
+    // set the other values
+    fStart         = time;
+    fLastRun       = atoi(data[0]);
+    fNumEvents     = atoi(data[8]);
+    fTelescope     = atoi(data[11]);
+    fProject       = str[0];
+    fSource        = str[1];
+    fTriggerTable  = str[2]+":"+str[3];
+    fHvSettings    = str[4];
+    fLightCondition = GetLightCondition(str[5]);
+
+    // FIXME: ZdMin (str[9]) ZdMax(str[10]) --> Comment
+    // FIXME: fMonteCarlo
+    // FIXME: fComment?
+
+    // Now prepare queries to request the runs from the database
+    const TString where(Form(" FROM RunData WHERE"
+                             " fTelescopeNumber=%d AND fSequenceFirst=%d AND"
+                             " fExcludedFDAKEY=1 AND fRunTypeKEY%%s",
+                             fTelescope, fSequence));
+
+    const TString query1(Form("SELECT fRunNumber, fFileNumber, fNumEvents %s", where.Data()));
+    const TString query2(Form("SELECT fRunStart, fRunStop %s", where.Data()));
+
+    const TString queryA(Form(query1.Data(), " BETWEEN 2 AND 4 ORDER BY fRunNumber*1000+fFileNumber"));
+    const TString queryC(Form(query1.Data(), "=4 ORDER BY fRunNumber*1000+fFileNumber"));
+    const TString queryD(Form(query1.Data(), "=2 ORDER BY fRunNumber*1000+fFileNumber"));
+    const TString queryT(Form(query2.Data(), "=4 ORDER BY fRunNumber*1000+fFileNumber LIMIT 1"));
+
+    // Try to get a valid time for the first calibration run
+    const TString timec = GetTimeFromDatabase(serv, queryT);
+    if (timec.IsNull())
+        return kFALSE;
+
+    // Query to get pedestal runs sorted in the order by distance to the cal run
+    const TString query4(Form("=3 ORDER BY ABS(TIME_TO_SEC(TIMEDIFF(fRunStop,'%s'))) ASC", timec.Data()));
+    const TString queryP(Form(query1.Data(), query4.Data()));
+
+    // get and setup runs
+    if (!GetRuns(serv, queryA, kAll))
+        return kFALSE;
+    if (!GetRuns(serv, queryC, kCal))
+        return kFALSE;
+    if (!GetRuns(serv, queryP, kPed, 1000))
+        return kFALSE;
+    if (!GetRuns(serv, queryD, kDat))
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a wrapper to get rid of the deletion of res in case of error.
+// It also checks that exactly one sequence has been found and all
+// requested column were returned.
+//
+Bool_t MSequenceSQL::GetFromDatabase(MSQLMagic &serv, TSQLResult &res)
+{
+    if (res.GetRowCount()==0)
+    {
+        *fLog << err << "ERROR - Requested Sequence not found in database." << endl;
+        return kFALSE;
+    }
+
+    if (res.GetRowCount()>1)
+    {
+        *fLog << err << "ERROR - Database request returned morethan one sequence." << endl;
+        return kFALSE;
+    }
+
+    if (res.GetFieldCount()!=12)
+    {
+        *fLog << err << "ERROR - Database request returned unexpected number of rows." << endl;
+        return kFALSE;
+    }
+
+    TSQLRow *row = res.Next();
+
+    return row ? GetFromDatabase(serv, *row) : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the contents of a sequence from the database.
+// The sequence number is given as argument.
+//
+// Example 1:
+//    // Define the database url
+//    MSQLMagic serv("mysql://user:password@url/Database");
+//    MSequenceSQL s;
+//    s.GetFromDatabase(serv, 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    // Define the database in the resource file
+//    MSQLMagic serv("sql.rc");
+//    MSequenceSQL s;
+//    s.GetFromDatabase(serv, 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+//  In case of error the Sequence is set invalid and kFALSE is returned,
+//  kTrue in case of success.
+//
+Bool_t MSequenceSQL::GetFromDatabase(MSQLMagic &serv, UInt_t sequno, Int_t tel)
+{
+    // Check if we are connected to the sql server
+    if (!serv.IsConnected())
+    {
+        *fLog << err << "ERROR - No connection to database in GetSeqFromDatabase." << endl;
+        return kFALSE;
+    }
+
+    /*
+    // check if any telescope number is valid
+    if (tel<0 && fTelescope==0)
+    {
+        *fLog << err << "ERROR - No telescope number given in GetSeqFromDatabase." << endl;
+        return kFALSE;
+    }
+    */
+
+    // check if any sequence number is valid
+    if (sequno==(UInt_t)-1 && fSequence==(UInt_t)-1)
+    {
+        *fLog << err << "ERROR - No sequence number given in GetSeqFromDatabase." << endl;
+        return kFALSE;
+    }
+
+    // set "filename" and sequence number
+    fFileName  = serv.GetName();
+    if (tel>=0)
+        fTelescope = tel;
+    if (sequno!=(UInt_t)-1)
+        fSequence = sequno;
+
+    // get sequence information from database
+    TString query("SELECT fSequenceLast, fProjectKEY, fSourceKEY,"
+                  " fL1TriggerTableKEY, fL2TriggerTableKEY, fHvSettingsKEY, "
+                  " fLightConditionsKEY, fRunStart, fNumEvents, "
+                  " fZenithDistanceMin, fZenithDistanceMax, fTelescopeNumber "
+                  " FROM Sequences WHERE ");
+    query += Form("fSequenceFirst=%d", fSequence);
+
+    if (tel>0)
+        query += Form(" AND fTelescopeNumber=%d", fTelescope);
+
+    // Request information from database
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    const Bool_t rc = GetFromDatabase(serv, *res);
+    delete res;
+
+    // invalidate sequence if retrieval failed
+    if (!rc)
+    {
+        fTelescope = 0;
+        fSequence  = (UInt_t)-1;
+    }
+
+    // return result
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the contents of a sequence from the database.
+// The sequence number is given as argument.
+//
+// Example 1:
+//    // Define the database url
+//    MSequenceSQL s;
+//    s.GetFromDatabase("mysql://user:password@url/Database", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+// Example 2:
+//    // Define the database in the resource file
+//    MSequenceSQL s;
+//    s.GetFromDatabase("sql.rc", 100002);
+//    if (s.IsValid())
+//        s.Print();
+//
+//  In case of error the Sequence is set invalid and kFALSE is returned,
+//  kTrue in case of success.
+//
+Bool_t MSequenceSQL::GetFromDatabase(const char *rc, UInt_t sequno, Int_t tel)
+{
+    MSQLMagic serv(rc);
+    return GetFromDatabase(serv, sequno, tel);
+}
Index: branches/Mars_McMismatchStudy/mjobs/MSequenceSQL.h
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/MSequenceSQL.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/MSequenceSQL.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MSequenceSQL
+#define MARS_MSequenceSQL
+
+#ifndef MARS_MSequence
+#include "MSequence.h"
+#endif
+
+class TSQLRow;
+class TSQLResult;
+
+class MSQLMagic;
+
+class MSequenceSQL : public MSequence
+{
+private:
+    Bool_t  GetRuns(MSQLMagic &serv, TString query, RunType_t type, UInt_t nevts=(UInt_t)-1);
+    TString GetTimeFromDatabase(MSQLMagic &serv, const TString &query);
+    Bool_t  GetFromDatabase(MSQLMagic &serv, TSQLResult &res);
+    Bool_t  GetFromDatabase(MSQLMagic &serv, TSQLRow &data);
+
+public:
+    MSequenceSQL(MSQLMagic &serv, UInt_t seqno, Int_t tel=0) { GetFromDatabase(serv, seqno, tel); }
+    MSequenceSQL(const char *rc, UInt_t seqno, Int_t tel=0)  { GetFromDatabase(rc, seqno, tel); }
+    MSequenceSQL(UInt_t seqno, Int_t tel=0)                  { GetFromDatabase(seqno, tel); }
+
+    Bool_t GetFromDatabase(MSQLMagic &serv, UInt_t seqno=(UInt_t)-1, Int_t tel=-1);
+    Bool_t GetFromDatabase(const char *rc, UInt_t seqno=(UInt_t)-1, Int_t tel=-1);
+    Bool_t GetFromDatabase(UInt_t seqno=(UInt_t)-1, Int_t tel=-1) { return GetFromDatabase("sql.rc", seqno, tel); }
+
+    ClassDef(MSequenceSQL, 0) // Extension of MSequence to get a sequence from a database
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjobs/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/Makefile	(revision 17960)
@@ -0,0 +1,50 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Jobs
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mdata -I../mhbase \
+	   -I../mhcalib -I../mfileio -I../mfilter -I../manalysis -I../mhist \
+           -I../mcalib -I../mbadpixels -I../msignal -I../mraw -I../mpedestal \
+           -I../mtools -I../mimage -I../mpointing -I../mastro -I../mfbase \
+           -I../mhvstime -I../mtrigger -I../mmuon -I../mmc -I../mmovie \
+           -I../mextralgo -I../mhflux -I../msql -I../mreport -I../mcorsika \
+	   -I../msim -I../msimreflector -I../msimcamera -I../melectronics \
+	   -I../mcore
+
+SRCFILES = MSequence.cc \
+           MSequenceSQL.cc \
+           MDataSet.cc \
+           MJob.cc \
+	   MJSimulation.cc \
+	   MJPedestal.cc \
+           MJCalib.cc \
+           MJCalibration.cc \
+           MJCalibrateSignal.cc \
+	   MJMerpp.cc \
+	   MJStar.cc \
+           MJCut.cc \
+           MJSpectrum.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mjobs/badpixels_0_559.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/badpixels_0_559.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/badpixels_0_559.rc	(revision 17960)
@@ -0,0 +1,2 @@
+0
+559
Index: branches/Mars_McMismatchStudy/mjobs/calibrationref.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/calibrationref.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/calibrationref.rc	(revision 17960)
@@ -0,0 +1,77 @@
+#
+# Reference lines for the data check, valid from for data
+# before Nov. 04:
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+ConvFADC2PheMin:          0.
+ConvFADC2PheMax:          5.
+ConvFADC2PhotMin:         0.
+ConvFADC2PhotMax:         10.
+#
+# Quantum Efficiencies:
+#
+QEMin:                    0.
+QEMax:                    3.
+#
+# Arrival Times from Max. bin:
+#
+ArrivalTimeMin:           1.
+ArrivalTimeMax:           10.
+#
+# Relative Time Calibration:
+#
+TimeOffsetMin:           -3.
+TimeOffsetMax:            3.
+TimeResolutionMin:        0.
+TimeResolutionMax:        1.
+######################################################################
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+RefFADC2PheInner:         0.14
+RefFADC2PheOuter:         0.4
+RefConvFADC2PhotInner:    0.8
+RefConvFADC2PhotOuter:    3.8
+RefConvFADC2PheInner:     0.14
+RefConvFADC2PheOuter:     0.56
+#
+# Quantum Efficiencies:
+#
+RefQEInner:               0.18
+RefQEOuter:               0.12
+#
+# Arrival Times from Max. bin:
+#
+RefArrivalTimeInner:      4.5
+RefArrivalTimeOuter:      5.0
+RefArrivalTimeRmsInner:   0.5.
+RefArrivalTimeRmsOuter:   0.5.
+#
+# Relative Time Calibration:
+#
+RefTimeOffsetOuter:       0.62    
+RefTimeResolutionInner:   0.12
+RefTimeResolutionOuter:   0.09
+#
+# Mean Absolute Time:
+#
+InnerRefTime:             3.4
+OuterRefTime:             4.2
+#
+# Mean Absolute Charge:
+#
+InnerRefCharge:           278.
+OuterRefCharge:           282.
Index: branches/Mars_McMismatchStudy/mjobs/calibrationref_Dec04.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/calibrationref_Dec04.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/calibrationref_Dec04.rc	(revision 17960)
@@ -0,0 +1,77 @@
+#
+# Reference lines for the data check, valid from for data
+# from Nov. 04 on
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+ConvFADC2PheMin:          0.
+ConvFADC2PheMax:          1.8
+ConvFADC2PhotMin:         0.
+ConvFADC2PhotMax:         15.
+#
+# Quantum Efficiencies:
+#
+QEMin:                    -0.05
+QEMax:                    3.
+#
+# Relative Time Calibration:
+#
+TimeOffsetMin:           -3.
+TimeOffsetMax:            3.
+TimeResolutionMin:        0.
+TimeResolutionMax:        1.
+#
+# Arrival Times from Max. bin:
+#
+ArrivalTimeMin:           1.
+ArrivalTimeMax:           10.
+######################################################################
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+RefFADC2PheInner:         0.3
+RefFADC2PheOuter:         0.6
+RefConvFADC2PhotInner:    1.7
+RefConvFADC2PhotOuter:    6.55
+RefConvFADC2PheInner:     0.31
+RefConvFADC2PheOuter:     1.26
+#
+# Quantum Efficiencies:
+#
+RefQEInner:               0.18
+RefQEOuter:               0.12
+#
+# Arrival Times from Max. bin:
+#
+RefArrivalTimeInner:      5.4
+RefArrivalTimeOuter:      6.0
+RefArrivalTimeRmsInner:   0.58.
+RefArrivalTimeRmsOuter:   0.57.
+#
+# Relative Time Calibration:
+#
+RefTimeOffsetOuter:       0.62
+RefTimeResolutionInner:   0.12
+RefTimeResolutionOuter:   0.09
+#
+# Mean Absolute Time:
+#
+InnerRefCharge:           115.
+OuterRefCharge:           110.
+#
+# Mean Absolute Charge:
+#
+InnerRefTime:             4.5
+OuterRefTime:             5.0
Index: branches/Mars_McMismatchStudy/mjobs/calibrationref_Nov04.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/calibrationref_Nov04.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/calibrationref_Nov04.rc	(revision 17960)
@@ -0,0 +1,77 @@
+#
+# Reference lines for the data check, valid from for data
+# from Nov. 04 on
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+ConvFADC2PheMin:          0.
+ConvFADC2PheMax:          4.
+ConvFADC2PhotMin:         0.
+ConvFADC2PhotMax:         8.
+#
+# Quantum Efficiencies:
+#
+QEMin:                    -0.05
+QEMax:                    3.
+#
+# Relative Time Calibration:
+#
+TimeOffsetMin:           -3.
+TimeOffsetMax:            3.
+TimeResolutionMin:        0.
+TimeResolutionMax:        1.
+#
+# Arrival Times from Max. bin:
+#
+ArrivalTimeMin:           1.
+ArrivalTimeMax:           10.
+######################################################################
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+RefFADC2PheInner:         0.13
+RefFADC2PheOuter:         0.33
+RefConvFADC2PhotInner:    0.71.
+RefConvFADC2PhotOuter:    2.8
+RefConvFADC2PheInner:     0.135
+RefConvFADC2PheOuter:     0.53
+#
+# Quantum Efficiencies:
+#
+RefQEInner:               0.18
+RefQEOuter:               0.12
+#
+# Arrival Times from Max. bin:
+#
+RefArrivalTimeInner:      4.4
+RefArrivalTimeOuter:      5.0
+RefArrivalTimeRmsInner:   0.58.
+RefArrivalTimeRmsOuter:   0.57.
+#
+# Relative Time Calibration:
+#
+RefTimeOffsetOuter:       0.62
+RefTimeResolutionInner:   0.12
+RefTimeResolutionOuter:   0.09
+#
+# Mean Absolute Time:
+#
+InnerRefCharge:           295.
+OuterRefCharge:           299.
+#
+# Mean Absolute Charge:
+#
+InnerRefTime:             2.95
+OuterRefTime:             3.6
Index: branches/Mars_McMismatchStudy/mjobs/pedestalref.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/pedestalref.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/pedestalref.rc	(revision 17960)
@@ -0,0 +1,39 @@
+#
+# Reference lines and histogram limits for the data check in pedestal files
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+PedestalMin:                 4.
+PedestalMax:                 20.
+#
+# Pedestal RMS:
+#
+PedRmsMin:                   0.
+PedRmsMax:                   20.
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+RefPedClosedLids:            9.635
+RefPedExtraGalactic:         9.93
+RefPedGalactic:              10.03
+#
+# Pedestal RMS:
+#
+RefPedRmsClosedLidsInner:    1.7
+RefPedRmsExtraGalacticInner: 5.6
+RefPedRmsGalacticInner:      6.92
+RefPedRmsClosedLidsOuter:    1.7
+RefPedRmsExtraGalacticOuter: 3.35
+RefPedRmsGalacticOuter:      4.2
Index: branches/Mars_McMismatchStudy/mjobs/pedestalref_Dec04.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/pedestalref_Dec04.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/pedestalref_Dec04.rc	(revision 17960)
@@ -0,0 +1,39 @@
+#
+# Reference lines and histogram limits for the data check in pedestal files
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+PedestalMin:                 4.
+PedestalMax:                 20.
+#
+# Pedestal RMS:
+#
+PedRmsMin:                   0.
+PedRmsMax:                   16.
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+RefPedClosedLids:            9.635
+RefPedExtraGalactic:         9.93
+RefPedGalactic:              10.03
+#
+# Pedestal RMS:
+#
+RefPedRmsClosedLidsInner:    1.7
+RefPedRmsExtraGalacticInner: 4.6
+RefPedRmsGalacticInner:      5.7
+RefPedRmsClosedLidsOuter:    1.7
+RefPedRmsExtraGalacticOuter: 3.3
+RefPedRmsGalacticOuter:      4.1
Index: branches/Mars_McMismatchStudy/mjobs/pedestalref_Feb05.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/pedestalref_Feb05.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/pedestalref_Feb05.rc	(revision 17960)
@@ -0,0 +1,39 @@
+#
+# Reference lines and histogram limits for the data check in pedestal files
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+PedestalMin:                 9.
+PedestalMax:                 21.
+#
+# Pedestal RMS:
+#
+PedRmsMin:                   0.
+PedRmsMax:                   20.
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+RefPedClosedLids:            14.635
+RefPedExtraGalactic:         14.93
+RefPedGalactic:              15.03
+#
+# Pedestal RMS:
+#
+RefPedRmsClosedLidsInner:    1.7
+RefPedRmsExtraGalacticInner: 5.6
+RefPedRmsGalacticInner:      6.92
+RefPedRmsClosedLidsOuter:    1.7
+RefPedRmsExtraGalacticOuter: 3.35
+RefPedRmsGalacticOuter:      4.2
Index: branches/Mars_McMismatchStudy/mjobs/signalref.rc
===================================================================
--- branches/Mars_McMismatchStudy/mjobs/signalref.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjobs/signalref.rc	(revision 17960)
@@ -0,0 +1,10 @@
+#
+# Reference lines for the data check, valid from for data
+# before Dec. 04:
+#
+######################################################################
+#
+# Mean Absolute Time:
+#
+InnerRefTime:             10.0
+OuterRefTime:             10.0
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimize.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimize.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimize.cc	(revision 17960)
@@ -0,0 +1,788 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 9/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJOptimize
+//
+// Class for otimizing the parameters of the supercuts
+//
+// Minimization Control
+// ====================
+//
+//   To choose the minimization algorithm use:
+//         void SetOptimizer(Optimizer_t o);
+//
+//   Allowed options are:
+//        enum Optimizer_t
+//        {
+//            kMigrad,      // Minimize by the method of Migrad
+//            kSimplex,     // Minimize by the method of Simplex
+//            kMinimize,    // Migrad + Simplex (if Migrad fails)
+//            kMinos,       // Minos error determination
+//            kImprove,     // Local minimum search
+//            kSeek,        // Minimize by the method of Monte Carlo
+//            kNone         // Skip optimization
+//        };
+//
+//   For more details on the methods see TMinuit.
+//
+//
+//   You can change the behaviour of the minimization using
+//
+//        void SetNumMaxCalls(UInt_t num=0);
+//        void SetTolerance(Float_t tol=0);
+//
+//   While NumMaxCalls is the first, Tolerance the second arguement.
+//   For more details start root and type
+//
+//        gMinuit->mnhelp("command")
+//
+//   while command can be
+//        * MIGRAD
+//        * SIMPLEX
+//        * MINIMIZE
+//        * MINOS
+//        * IMPROVE
+//        * SEEK
+//
+//   The default (num==0 and tol==0) should always give you the
+//   corresponding defaults used in Minuit.
+//
+//
+// FIXME: Implement changing cut in hadronness...
+// FIXME: Show MHSignificance on MStatusDisplay during filling...
+// FIXME: Choose step-size percentage as static data membewr
+// FIXME: Choose minimization method
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJOptimize.h"
+
+#include <TMinuit.h>
+#include <TVirtualFitter.h>
+
+#include <TStopwatch.h>
+
+#include <TCanvas.h>
+
+#include <TGraph.h>
+#include <TMultiGraph.h>
+
+#include "MHMatrix.h"
+
+// environment
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// parameters
+#include "MParameters.h"
+
+// tasks
+#include "MReadTree.h"
+#include "MMatrixLoop.h"
+#include "MFillH.h"
+#include "MParameterCalc.h"
+#include "MContinue.h"
+
+// filters
+#include "MFDataPhrase.h"
+#include "MFilterList.h"
+
+using namespace std;
+
+//------------------------------------------------------------------------
+//
+// fcn calculates the function to be minimized (using TMinuit::Migrad)
+//
+void MJOptimize::fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    MJOptimize *optim = (MJOptimize*)gMinuit->GetObjectFit();
+
+    // WORKAROUND --- FOR WHAT?
+    if (gMinuit->fEpsi<1e-2)
+    {
+        *optim->fLog << warn << "WARNING - For unknown reasons: fEspi<1e-100... resetting to 0.01." << endl;
+        gMinuit->fEpsi = 0.01;
+    }
+
+    TMinuit *minuit = gMinuit;
+    f = optim->Fcn(TArrayD(TMath::Min(gMinuit->fMaxpar, optim->fParameters.GetSize()), par), minuit);
+    gMinuit = minuit;
+
+}
+
+Double_t MJOptimize::Fcn(const TArrayD &par, TMinuit *minuit)
+{
+    if (fEvtLoop->GetDisplay()!=fDisplay)
+        return 0;
+    /*
+    switch(iflag)
+    {
+    case 1: // first call
+    case 2: // calc derivative
+        break;
+    case 3:
+        // last call
+        MStatusDisplay *d = new MStatusDisplay;
+        fEvtLoop->SetDisplay(d);
+        break;
+    }
+    */
+    MParList *plist = fEvtLoop->GetParList();
+
+    MParameterD   *eval = (MParameterD*)plist->FindObject(fNameMinimizationValue, "MParameterD");
+    MParContainer *pars = (MParContainer*)plist->FindObject("MParameters", "MParContainer");
+
+    MRead *read = (MRead*)plist->FindObject("MTaskList")->FindObject("MRead");
+    if (read)
+        read->Rewind();
+
+    if (fDebug>=0)
+    {
+        *fLog << inf << "New Set: ";
+        for (Int_t i=0; i<fParameters.GetSize(); i++)
+            *fLog << par[i] << " ";
+        *fLog << endl;
+    }
+
+    pars->SetVariables(par);
+    eval->SetVal(0);
+
+    const Bool_t isnull = gLog.IsNullOutput();
+    if (fDebug<3)
+        gLog.SetNullOutput(kTRUE);
+
+    TStopwatch clock;
+    clock.Start();
+    fEvtLoop->Eventloop(fNumEvents, MEvtLoop::kNoStatistics);
+    clock.Stop();
+
+    if (fDebug<3)
+        gLog.SetNullOutput(isnull);
+
+    const Double_t f = eval->GetVal();
+
+    if (fDebug>=0)
+        *fLog << inf << "Result F=" << f << endl;
+
+    if (fDebug>=1 && minuit)
+    {
+        Double_t fmin, fedm, errdef;
+        Int_t n1, n2, istat;
+        minuit->mnstat(fmin, fedm, errdef, n1, n2, istat);
+        *fLog << inf << underline << "Minimization Status so far:" << endl;
+        *fLog << " Calls:      " << minuit->fNfcn << "  (max=" << gMinuit->fMaxIterations << ")" << endl;
+        *fLog << " Parameters: fixed=" << gMinuit->fNpfix << ", free=" << gMinuit->fNpar << endl;
+        *fLog << " Func min:   " << fmin << "  (Epsi=" << gMinuit->fEpsi << ", Apsi=" << gMinuit->fApsi << ")" << endl;
+        *fLog << " Found edm:  " << fedm << endl;
+        *fLog << " ErrDef:     " << errdef << endl;
+        *fLog << " Status:     ";
+
+        switch (istat)
+        {
+        case 0:  *fLog << "n/a" << endl; break;
+        case 1:  *fLog << "approximation only, not accurate" << endl; break;
+        case 2:  *fLog << "full matrix, but forced positive-definite" << endl; break;
+        case 3:  *fLog << "full accurate covariance matrix" << endl; break;
+        default: *fLog << "undefined" << endl; break;
+        }
+    }
+
+    if (fDebug>=1)
+    {
+        clock.Print();
+        fEvtLoop->GetTaskList()->PrintStatistics();
+    }
+
+    return f;
+}
+
+MJOptimize::MJOptimize() : /*fDebug(-1),*/ fNumEvents(0), fType(kSimplex), fNumMaxCalls(0), fTolerance(0), fTestTrain(0), fNameMinimizationValue("MinimizationValue")
+{
+    fRules.SetOwner();
+    fFilter.SetOwner();
+
+    fNamesOn.SetOwner();
+    fNamesOff.SetOwner();
+}
+
+//------------------------------------------------------------------------
+//
+// Add sequences from list to reader
+//
+Bool_t MJOptimize::AddSequences(MRead &read, TList &list) const
+{
+    MDirIter files;
+
+    TIter Next(&list);
+    MSequence *seq=0;
+    while ((seq=(MSequence*)Next()))
+    {
+        if (!seq->IsValid())
+            return kFALSE;
+        if (seq->GetRuns(files, MSequence::kRootDat)<=0)
+            return kFALSE;
+    }
+
+    return read.AddFiles(files)>0;
+}
+
+//------------------------------------------------------------------------
+//
+// Add on-sequences:
+//  - fname: sequence file name (with path)
+//  - dir:   directory were image files are stored
+//
+void MJOptimize::AddSequenceOn(const char *fname, const char *dir)
+{
+    fNamesOn.Add(new MSequence(fname, dir));
+}
+
+//------------------------------------------------------------------------
+//
+// Add off-sequences:
+//  - fname: sequence file name (with path)
+//  - dir:   directory were image files are stored
+//
+void MJOptimize::AddSequenceOff(const char *fname, const char *dir)
+{
+    fNamesOff.Add(new MSequence(fname, dir));
+}
+
+//------------------------------------------------------------------------
+//
+// Empty list of on- and off-sequences
+//
+void MJOptimize::ResetSequences()
+{
+    fNamesOn.Delete();
+    fNamesOff.Delete();
+}
+
+
+//------------------------------------------------------------------------
+//
+// Add a filter which can be applied in the optimization (for deatils
+// see correspodning Run function) You can use the indices you got by
+// AddParameter, eg
+//
+//   AddFilter("M[0] < 3.2");
+//
+// if used in optimization you can do
+//
+//   AddFilter("M[0] < [0]");
+//
+// for more details, see SetParameter and FixParameter
+//
+void MJOptimize::AddFilter(const char *rule)
+{
+    fFilter.Add(new MFDataPhrase(rule));
+}
+
+//------------------------------------------------------------------------
+//
+// Set the fParameters Array accoring to par.
+//
+void MJOptimize::SetParameters(const TArrayD &par)
+{
+    fParameters = par;
+}
+
+//------------------------------------------------------------------------
+//
+// Set the number of events processed by the eventloop. (Be carfull,
+// if you are doing on-off analysis and you only process the first
+// 1000 events which are on-events only the optimization may not work)
+//
+void MJOptimize::SetNumEvents(UInt_t n)
+{
+    fNumEvents=n;
+}
+
+//------------------------------------------------------------------------
+//
+// Set a debug level, which tells the optimization how much information
+// is displayed about and in the running eventloop.
+//
+void MJOptimize::SetDebug(UInt_t n)
+{
+    fDebug=n;
+}
+
+//------------------------------------------------------------------------
+//
+// Set a optimization algorithm to be used. For more information see
+// TMinuit.
+//
+// Available Algorithms are:
+//    kMigrad,   // Minimize by the method of Migrad
+//    kSimplex,  // Minimize by the method of Simplex
+//    kSeek      // Minimize by the method of Monte Carlo
+//
+void MJOptimize::SetOptimizer(Optimizer_t o)
+{
+    fType = o;
+}
+
+//------------------------------------------------------------------------
+//
+// If a status didplay is set, search for tab "Optimizer".
+// If not found, create it.
+// In the tab search for TMultiGraph "Parameters".
+// If not found create it.
+// If empty create TGraphs.
+// Check number of graphs vs. number of parameters.
+// return TList with graphs.
+//
+TList *MJOptimize::GetPlots() const
+{
+    if (!fDisplay)
+        return NULL;
+
+    TCanvas *c=fDisplay->GetCanvas("Optimizer");
+    if (!c)
+        c = &fDisplay->AddTab("Optimizer");
+
+    TMultiGraph *mg = dynamic_cast<TMultiGraph*>(c->FindObject("Parameters"));
+    if (!mg)
+        mg = new TMultiGraph("Parameters", "Parameters of optimization");
+
+    TList *l = mg->GetListOfGraphs();
+    if (!l)
+    {
+        const Int_t n = fParameters.GetSize();
+        for (int i=0; i<n+1; i++)
+        {
+            TGraph *g = new TGraph;
+            if (i==n)
+                g->SetLineColor(kBlue);
+            mg->Add(g, "");
+            AddPoint(mg->GetListOfGraphs(), i, i==n?1:fParameters[i]);
+        }
+        mg->SetBit(kCanDelete);
+        mg->Draw("al*");
+
+        l = mg->GetListOfGraphs();
+    }
+
+    return l->GetSize() == fParameters.GetSize()+1 ? l : NULL;
+}
+
+//------------------------------------------------------------------------
+//
+// Add a point with y=val as last point in idx-th Tgraph of list l.
+//
+void MJOptimize::AddPoint(TList *l, Int_t idx, Float_t val) const
+{
+    if (!l)
+        return;
+
+    TGraph *gr = (TGraph*)l->At(idx);
+    gr->SetPoint(gr->GetN(), gr->GetN(), val);
+}
+
+Int_t MJOptimize::Minuit(TMinuit &minuit, const char *cmd) const
+{
+    Int_t er;
+    Double_t tmp[2] = { Double_t(fNumMaxCalls), fTolerance };
+    minuit.mnexcm(cmd, tmp, 2, er);
+
+    switch (er)
+    {
+    case 0:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm excuted normally." << endl;
+        break;
+    case 1:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm command is blank... ignored." << endl;
+        break;
+    case 2:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm command-line syntax error... ignored." << endl;
+        break;
+    case 3:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm unknown command... ignored." << endl;
+        break;
+    case 4:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm - Abnormal termination (eg Migrad not converged)" << endl;
+        break;
+        /*
+    case 5:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - Parameters requested." << endl;
+        break;
+    case 6:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET INPUT returned." << endl;
+        break;
+    case 7:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET TITLE returned." << endl;
+        break;
+    case 8:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET COVAR returned." << endl;
+        break;
+    case 9:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - reserved." << endl;
+        break;
+    case 10:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - END returned." << endl;
+        break;
+    case 11:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - EXIT or STOP returned." << endl;
+        break;
+    case 12:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - RETURN returned." << endl;
+        break;*/
+    }
+
+    return er;
+}
+
+Bool_t MJOptimize::Optimize(MEvtLoop &evtloop)
+{
+    if (fParameters.GetSize()==0)
+    {
+        *fLog << err << GetDescriptor() << "::Optimize: ERROR - Sorry, no parameters defined." << endl;
+        return kFALSE;
+    }
+
+    if (fType==kNone)
+        return kTRUE;
+
+    gMinuit = new TMinuit(fParameters.GetSize());
+
+    gMinuit->SetFCN(fcn);
+    gMinuit->SetObjectFit(this);
+    gMinuit->SetPrintLevel(-1); // Don't print when DefineParameter
+
+    //
+    // Set starting values and step sizes for parameters
+    //
+    for (Int_t i=0; i<fParameters.GetSize(); i++)
+    {
+        TString name = "par[";
+        name += i;
+        name += "]";
+        Double_t vinit = fParameters[i];
+        Double_t step  = fStep[i];
+
+        Double_t limlo = fLimLo[i];
+        Double_t limup = fLimUp[i];
+
+        Bool_t rc = gMinuit->DefineParameter(i, name, vinit, step, limlo, limup);
+        if (rc)
+        {
+            *fLog << err << dbginf << "Error in defining parameter #" << i << endl;
+            return kFALSE;
+        }
+
+        if (step==0)
+            gMinuit->FixParameter(i);
+    }
+
+    gMinuit->SetPrintLevel(1); // Switch on pritning again
+    gMinuit->mnprin(1,0);      // Print all parameters
+
+    fEvtLoop = &evtloop;
+
+    TList *g=GetPlots();
+
+    // Now ready for minimization step:
+    TStopwatch clock;
+    clock.Start();
+    switch (fType)
+    {
+    case kSimplex:
+        Simplex(*gMinuit);
+        break;
+    case kMigrad:
+        Migrad(*gMinuit);
+        break;
+    case kMinimize:
+        Minimize(*gMinuit);
+        break;
+    case kMinos:
+        Minos(*gMinuit);
+        break;
+    case kImprove:
+        Improve(*gMinuit);
+        break;
+    case kSeek:
+        Seek(*gMinuit);
+        break;
+    case kNone: // Should never happen
+        return kFALSE;
+    }
+    clock.Stop();
+    clock.Print();
+
+    if (evtloop.GetDisplay()!=fDisplay)
+    {
+        *fLog << inf << "Optimization aborted by user." << endl;
+        fDisplay = 0;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Resulting Chisq: " << gMinuit->fAmin << endl;
+
+    //
+    // Update values of fA, fB:
+    //
+    for (Int_t i=0; i<fParameters.GetSize(); i++)
+    {
+        Double_t x1, x2;
+        gMinuit->GetParameter(i,x1,x2);
+        fParameters[i] = x1;
+        cout << i << ": " << fParameters[i] << endl;
+
+        AddPoint(g, i, x1);
+    }
+    AddPoint(g, fParameters.GetSize(), gMinuit->fAmin);
+
+    delete gMinuit;
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Optimize allows to use the optimizing by an eventloop based on
+// some requirements.
+//
+// 1) The tasklist to be executed must have the name MTaskList and
+//    be an entry in the parameterlist.
+//
+// 2) The reading task (MReadMarsFile, MMatrixLoop) must have the name
+//    "MRead". If it derives from MRead Rewind() must be implemented,
+//    otherwise it must start reading from scratch each time its
+//    PreProcess is called.
+//
+// 3) The parameters to be optimized must be accessed through (currently)
+//    a single parameter container (MParContainer) called MParameters.
+//    The parameters are set through SetVariables.
+//
+// 4) The result of a single function call for minimization (eg. chisquare)
+//    must be available after the eventloop in a container of type
+//    MParameterD with the name "MinimizationResult".
+//
+// 5) The parameters to start with must have been set using
+//    MJOptimize::SetParameter or MJOptimize::SetParameters and
+//    MJOptimize::FixParameter
+//
+// The behaviour of the optimization can be changed using:
+//  void SetNumEvents(UInt_t n);
+//  void SetDebug(UInt_t n);
+//  void SetOptimizer(Optimizer_t o);
+//
+// After optimization the resulting parameters are set and another eventloop
+// with a MStatusDisplay is set is called. The resulting parameters can be
+// accessed using: GetParameters()
+//
+// To be fixed:
+//  - MStatusDisplay should show status while optimization is running
+//  - write result into MStatusDisplay
+//  - save result
+//
+Bool_t MJOptimize::Optimize(MParList &parlist)
+{
+    // Checks to make sure, that fcn doesn't crash
+    if (!parlist.FindCreateObj("MParameterD", fNameMinimizationValue))
+        return kFALSE;
+
+    if (!parlist.FindObject("MParameters", "MParContainer"))
+    {
+        *fLog << err << "MParameters [MParContainer] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    MTaskList *tlist = (MTaskList*)parlist.FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << err << "MTaskList not found... abort." << endl;
+        return kFALSE;
+    }
+    tlist->SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    MMatrixLoop *loop = dynamic_cast<MMatrixLoop*>(parlist.FindTask("MRead"));
+
+    TString txt("Starting ");
+    switch (fType)
+    {
+    case kMigrad:    txt += "Migrad";    break;
+    case kMinimize:  txt += "Minimize";  break;
+    case kMinos:     txt += "Minos";     break;
+    case kImprove:   txt += "Improve";   break;
+    case kSimplex:   txt += "Simplex";   break;
+    case kSeek:      txt += "Seek";      break;
+    case kNone:      txt += "no";        break;
+    }
+    txt += " optimization";
+
+    fLog->Separator(txt);
+
+    // Setup eventloop
+    MEvtLoop evtloop(fTitle);
+    evtloop.SetParList(&parlist);
+    evtloop.SetDisplay(fDisplay); // set display for evtloop and all childs
+    parlist.SetDisplay(0);        // reset display for all contents of parlist and tasklist
+    evtloop.SetPrivateDisplay();  // prevent display from being cascaded again in PreProcess
+
+    *fLog << inf << "Number of Parameters: " << fParameters.GetSize() << endl;
+
+    // In case the reader is the matrix loop and testrain is enabled
+    // switch on even mode...
+    if (loop && TMath::Abs(fTestTrain)>0)
+        loop->SetOperationMode(fTestTrain>0?MMatrixLoop::kEven:MMatrixLoop::kOdd);
+
+    if (!Optimize(evtloop))
+        return kFALSE;
+
+    gMinuit = 0;
+
+    // Test with training data
+    fEvtLoop->SetDisplay(fDisplay);
+    if (!Fcn(fParameters))
+        return kFALSE;
+
+    // In case the reader is the matrix loop and testrain is enabled
+    // switch on odd mode...
+    if (!loop || fTestTrain==0)
+        return kTRUE;
+
+    // Test with test-data
+    loop->SetOperationMode(fTestTrain<0?MMatrixLoop::kEven:MMatrixLoop::kOdd);
+
+    // Done already in Fcn
+    // list.SetVariables(fParameters);
+    return Fcn(fParameters);
+}
+
+void MJOptimize::AddRulesToMatrix(MHMatrix &m) const
+{
+    TIter Next1(&fRules);
+    TObject *o1=0;
+    while ((o1=Next1()))
+        m.AddColumn(o1->GetName());
+}
+
+//------------------------------------------------------------------------
+//
+// Fill matrix m by using read. Use rules as a filter if userules.
+//
+Bool_t MJOptimize::FillMatrix(MReadTree &read, MParList &parlist, Bool_t userules)
+{
+    MHMatrix *m = (MHMatrix*)parlist.FindObject("M", "MHMatrix");
+    if (!m)
+    {
+        *fLog << err << "MJOptimize::FillMatrix - ERROR: M [MHMatrix] not found in parlist... abort." << endl;
+        return kFALSE;
+    }
+
+    m->Print("cols");
+
+    //    MGeomCamMagic cam;
+    //    parlist.AddToList(&cam);
+
+    // Setup filter and apply filter to filling of matrix
+    MFilterList list;
+    if (!list.AddToList(fPreCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
+    if (userules)
+        SetupFilters(list);
+    list.SetName("PreCuts");  // reset Name      set by SetupFilters
+    list.SetInverted(kTRUE);  // reset inversion set by SetupFilters
+
+    MContinue cont(&list);
+
+    // Setup filling of matrix
+    MFillH fillh(m);
+
+    // Setup tasklist
+    MTaskList tlist;
+    parlist.Replace(&tlist);
+
+    // Create task list
+    tlist.AddToList(&read);        // read data
+    tlist.AddToList(fPreTasks);    // execute pre-filter tasks
+    tlist.AddToList(&cont);        // execute filters
+    tlist.AddToList(fPostTasks);   // execute post-filter tasks
+    tlist.AddToList(&fillh);       // Fill matrix
+
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    MEvtLoop fillloop(fTitle);
+    fillloop.SetParList(&parlist);
+    fillloop.SetDisplay(fDisplay);
+    if (!fillloop.Eventloop(fNumEvents))
+    {
+        *fLog << err << "Filling matrix failed..." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Read events from file '" << read.GetFileName() << "'" << endl;
+
+    if (fillloop.GetDisplay()!=fDisplay)
+    {
+        fDisplay = 0;
+        *fLog << inf << "Optimization aborted by user." << endl;
+        return kFALSE;
+    }
+
+    m->Print("size");
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Adds all filters to MFilterList
+//
+void MJOptimize::SetupFilters(MFilterList &list, MFilter *filter) const
+{
+    list.SetName("MParameters");
+    list.SetInverted();
+
+    if (filter)
+    {
+        if (fFilter.GetSize()>0)
+        {
+            *fLog << inf;
+            *fLog << "INFORMATION - You are using an  external filter and internal filters." << endl;
+            *fLog << "              Please make sure that all parameters '[i]' are starting" << endl;
+            *fLog << "              behind the number of parameters of the external filter." << endl;
+        }
+        list.AddToList(filter);
+    }
+
+    if (!list.AddToList(fFilter))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList fFilter failed!" << endl;
+
+    *fLog << inf << "Filter: ";
+    list.Print();
+    *fLog << endl;
+}
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimize.h
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimize.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimize.h	(revision 17960)
@@ -0,0 +1,155 @@
+#ifndef MARS_MJOptimize
+#define MARS_MJOptimize
+
+#ifndef MARS_MJOptimizeBase
+#include "MJOptimizeBase.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TMinuit;
+
+class MAlphaFitter;
+
+class MTask;
+class MEvtLoop;
+class MParList;
+class MFilter;
+class MFilterList;
+class MFitParameters;
+class MFitParametersCalc;
+
+class MHMatrix;
+class MGeomCam;
+class MRead;
+class MReadTree;
+
+class MJOptimize : public MJOptimizeBase
+{
+public:
+    enum Optimizer_t
+    {
+        kMigrad,      // Minimize by the method of Migrad
+        kSimplex,     // Minimize by the method of Simplex
+        kMinimize,    // Migrad + Simplex (if Migrad fails)
+        kMinos,       // Minos error determination
+        kImprove,     // Local minimum search
+        kSeek,        // Minimize by the method of Monte Carlo
+        kNone         // Skip optimization
+    };
+
+private:
+    Int_t fNumEvents;
+
+    TList fFilter;
+
+    void AddPoint(TList *l, Int_t idx, Float_t val) const;
+    TList *GetPlots() const;
+
+    MEvtLoop *fEvtLoop;    //!
+
+    // Minuit Interface
+    static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag);
+    Double_t Fcn(const TArrayD &par, TMinuit *minuit=0);
+
+    Int_t Minuit(TMinuit &minuit, const char *cmd) const;
+    Int_t Migrad(TMinuit &minuit) const   { return Minuit(minuit, "MIGRAD"); }
+    Int_t Simplex(TMinuit &minuit) const  { return Minuit(minuit, "SIMPLEX"); }
+    Int_t Minimize(TMinuit &minuit) const { return Minuit(minuit, "MINIMIZE"); }
+    Int_t Seek(TMinuit &minuit) const     { return Minuit(minuit, "SEEK"); }
+    Int_t Improve(TMinuit &minuit) const  { return Minuit(minuit, "IMPROVE"); }
+    Int_t Minos(TMinuit &minuit) const    { return Minuit(minuit, "MINOS"); }
+
+    TArrayD fParameters;   //!
+    TArrayD fLimLo;        //!
+    TArrayD fLimUp;        //!
+    TArrayD fStep;         //!
+
+    Optimizer_t fType;
+    UInt_t  fNumMaxCalls;
+    Float_t fTolerance;
+    Int_t   fTestTrain;
+    TString fNameMinimizationValue;
+
+    Bool_t Optimize(MEvtLoop &evtloop);
+
+protected:
+    TList   fNamesOn;
+    TList   fNamesOff;
+
+    TString fNameOut;
+
+    void   AddRulesToMatrix(MHMatrix &m) const;
+    void   SetupFilters(MFilterList &list, MFilter *filter=0) const;
+    Bool_t AddSequences(MRead &read, TList &list) const;
+    Bool_t FillMatrix(MReadTree &read, MParList &l, Bool_t userules=kFALSE);
+
+public:
+    MJOptimize();
+
+    // I/O
+    void AddSequenceOn(const char *fname, const char *dir="");
+    void AddSequenceOff(const char *fname, const char *dir="");
+
+    void ResetSequences();
+
+    // Interface for filter cuts
+    void AddFilter(const char *rule);
+
+    // Steering of optimization
+    void SetNumEvents(UInt_t n);
+    void SetDebug(UInt_t n);
+    void SetNameOut(const char *name="") { fNameOut = name; }
+    void SetOptimizer(Optimizer_t o);
+    void SetNumMaxCalls(UInt_t num=0) { fNumMaxCalls=num; }
+    void SetTolerance(Float_t tol=0)  { fTolerance=tol; }
+    void EnableTestTrain(Int_t b=1)   { fTestTrain=b; } // Use 1 and -1
+    void SetNameMinimizationValue(const char *name="MinimizationValue") { fNameMinimizationValue = name; }
+
+    // Parameter access
+    void SetParameters(const TArrayD &par);
+    void SetParameter(Int_t idx, Double_t start, Double_t lo=0, Double_t up=0, Double_t step=-1)
+    {
+        if (fParameters.GetSize()<=idx)
+        {
+            fParameters.Set(idx+1);
+            fLimLo.Set(idx+1);
+            fLimUp.Set(idx+1);
+            fStep.Set(idx+1);
+        }
+
+        fParameters[idx] = start;
+        fLimLo[idx] = lo;
+        fLimUp[idx] = up;
+        if (step<=0)
+            fStep[idx] = start==0 ? 0.1 : TMath::Abs(start*0.15);
+        else
+            fStep[idx] = step;
+    }
+    void FixParameter(Int_t idx, Double_t start, Double_t lo=0, Double_t up=0, Double_t step=-1)
+    {
+        if (fParameters.GetSize()<=idx)
+        {
+            fParameters.Set(idx+1);
+            fLimLo.Set(idx+1);
+            fLimUp.Set(idx+1);
+            fStep.Set(idx+1);
+        }
+
+        fParameters[idx] = start;
+        fLimLo[idx] = 0;
+        fLimUp[idx] = 0;
+        fStep[idx]  = 0;
+    }
+
+    const TArrayD &GetParameters() const { return fParameters; }
+
+    // Generalized optimizing routines
+    Bool_t Optimize(MParList &list);
+
+    ClassDef(MJOptimize, 0) // Class for optimization of the Supercuts
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeBase.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeBase.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeBase.cc	(revision 17960)
@@ -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 11/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2005-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJOptimizeBase
+//
+// Base class for classes training a random forest
+//
+// The order when reading a file is:
+//   1) Execution of PreTasks
+//   2) Execution of PreCuts, TestCuts, TrainCuts
+//   3) Selector               (calculated from number of requested events)
+//   4) Splitter               (if sample is split automatically in test/train)
+//   5) PostTasks              (set by user)
+//
+// The split into Pre- and PostTasks is done for speed reason. So, if
+// you calculate a vlue which is not needed for your PreCuts, you can
+// calculate it afterwards, which will speed up execution.
+//
+// void AddPreTask(MTask *t)
+//    Add a task which is executed just after reading the events from the file
+//    this can be any kind of task or even a task list. You can use dedicated
+//    tasks performing some analysis, but also cuts (e.g. MContinue) or a
+//    general task to evaluate new parameters (e.g. MParameterCalc)
+//
+// void AddPreTask(const char *rule, const char *name="MWeight")
+//    This is a short cut to AddPreTask(MTask*) which will add a
+//    MParameterCalc to the list evaluating the given rule and storing the
+//    result in a MParameterD with the given name. For the default "MWeight",
+//    for example, the value can later be accessed by MWeight.fVal.
+//
+// The same functions are available as
+//    void AddPostTask(MTask *t)
+//    void AddPostTask(const char *rule, const char *name="MWeight")
+//
+// It is advicable to use these function if the task is not needed for your
+// event selection. The event selection (by number and by PreCuts) is done
+// in between PreTasks and PostTasks, i.e. a task which is not needed for the
+// event selection but needed later is only executed as often as necessary.
+//
+// The event selection (apart from the number of target events) can be setup
+// by the user. Therefore two functions are available
+//    void AddPreCut(const char *rule)
+//    void AddPreCut(MFilter *f)
+// Both add cuts which are executed after the PreTasks but before the
+// PostTasks. They are executed in both training and testing. To execute cuts
+// only in training or testing use
+//    void AddTrainCut(const char *rule)
+//    void AddTrainCut(MFilter *f)
+// or
+//    void AddTestCut(const char *rule)
+//    void AddTestCut(MFilter *f)
+//
+// To weight the events of your train- and test sample the following functions
+// can be used
+//    void SetWeights(const char *rule)
+//    void SetWeights(MTask *t)
+// This either adds a MParameterCalc to the list of post tasks or a MTask,
+// which is supposed to fill a MParameterD named "MWeight".
+//
+// Last but not least a function if available to add additional tasks to the
+// end of the task list for testing. This can for example be used to add
+// the filling and display of an addition histogram (e.g. add a MFillH)
+// or to do some calculation and write out the result. Basically everything
+// can be done in this way.
+//    void AddTestTask(MTask *t)
+//    void AddTestTask(const char *rule, const char *name="MWeight")
+//
+//
+// REMARK: Note that the actual behavior might still vary a bit
+//         depeding of the implementation in the derived class.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJOptimizeBase.h"
+
+#include <TFile.h>
+#include <TRandom3.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MFDataPhrase.h"
+#include "MParameterCalc.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MJOptimizeBase);
+
+using namespace std;
+
+//------------------------------------------------------------------------
+//
+MJOptimizeBase::MJOptimizeBase() : fDebug(-1), fEnableWeights(kFALSE)
+{
+    if (gRandom && gRandom->IsA()==TRandom::Class())
+        *fLog << warn << "WARNING - gRandom is a TRandom instance. It is highly adviced to use another random generator!" << endl;
+}
+
+//------------------------------------------------------------------------
+//
+// Add a cut which is used to fill the matrix, eg "MMcEvt.fPartId<1.5"
+// (The rule is applied, not inverted: The matrix is filled with
+// the events fullfilling the condition)
+//
+void MJOptimizeBase::AddCut(TList &l, const char *rule)
+{
+    MFilter *f = new MFDataPhrase(rule);
+    f->SetBit(kCanDelete); //FIXME!!!! Why does not any other list delete it???
+    Add(l, f);
+}
+
+//------------------------------------------------------------------------
+//
+// Add an additional parameter (MParameterCalc), eg "0.5", "MWeight"
+// The default container name is "MWeight"
+//
+void MJOptimizeBase::AddPar(TList &l, const char *rule, const char *pname)
+{
+    TString tname(pname);
+    tname += "Calc";
+
+    MParameterCalc *par = new MParameterCalc(rule, tname);
+    par->SetNameParameter(pname);
+//    par->SetBit(kCanDelete);  //FIXME!!!! MTaskList is deleting it
+    Add(l, par);
+}
+
+//------------------------------------------------------------------------
+//
+// Add a task/cut which is used to fill the matrix. If kCanDelete is set
+// MJOptimize takes the ownership.
+//
+void MJOptimizeBase::Add(TList &l, MTask *f)
+{
+    l.Add(f);
+}
+
+//------------------------------------------------------------------------
+//
+// Add a parameter to the list of parameters. The index in the list is
+// returned.
+//
+//   Int_t idx = AddParameter("log10(MHillas.fSize)");
+//
+// Indices are starting with 0.
+//
+Int_t MJOptimizeBase::AddParameter(const char *rule)
+{
+    fRules.Add(new TNamed(rule, ""));
+    return fRules.GetSize()-1;
+}
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeBase.h
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeBase.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeBase.h	(revision 17960)
@@ -0,0 +1,73 @@
+#ifndef MARS_MJOptimizeBase
+#define MARS_MJOptimizeBase
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MTask;
+class MFilter;
+
+class MJOptimizeBase : public MJob
+{
+protected:
+    Int_t  fDebug;
+    Bool_t fEnableWeights;  // Enable using weights
+
+    TList fRules;           // Contains the parameters which can be accessed by matrix column
+    TList fTrainParameters; // Parameters in the last columns
+
+    TList fPreCuts;         // Cuts executed for training and testing
+    TList fTrainCuts;       // Cuts executed only in training
+    TList fTestCuts;        // Cuts executed only in testing
+    TList fPreTasks;        // Tasks executed before cut execution
+    TList fPostTasks;       // Tasks executed after pre cut execution
+    TList fTestTasks;       // Tasks executed at the end of the testing tasklist
+
+    void AddCut(TList &l, const char *rule);
+    void AddPar(TList &l, const char *rule, const char *name);
+    void Add(TList &l, MTask *f);
+
+public:
+    MJOptimizeBase();
+
+    // MJOptimizeBase
+    void SetDebug(Bool_t b=kTRUE) { fDebug = b; }
+
+    // Add a parameter to the list of parameters
+    Int_t AddParameter(const char *rule);
+
+    // Tasks which are executed after reading (training and testing if available)
+    void AddPreTask(MTask *t)                    { Add(fPreTasks,  t); }
+    void AddPreTask(const char *rule,
+                    const char *name="MWeight")  { AddPar(fPreTasks, rule, name); }
+
+    // Cuts which are executed after the pre-tasks (training and testing if available)
+    void AddPreCut(const char *rule)             { AddCut(fPreCuts, rule); }
+    void AddPreCut(MFilter *f)                   { Add(fPreCuts, (MTask*)(f)); }
+
+    // Same as pre-cuts but only executed in taining or testing
+    void AddTrainCut(const char *rule)           { AddCut(fTrainCuts, rule); }
+    void AddTrainCut(MFilter *f)                 { Add(fTrainCuts, (MTask*)(f)); }
+
+    void AddTestCut(const char *rule)            { AddCut(fTestCuts, rule); }
+    void AddTestCut(MFilter *f)                  { Add(fTestCuts, (MTask*)(f)); }
+
+    // Tasks which are excuted after event selection (training and testing if available)
+    void AddPostTask(MTask *t)                   { Add(fPostTasks, t); }
+    void AddPostTask(const char *rule,
+                     const char *name="MWeight") { AddPar(fPostTasks, rule, name); }
+
+    // Tasks executed at the end of the testing tasklist
+    void AddTestTask(MTask *t)                   { Add(fTestTasks, t); }
+    void AddTestTask(const char *rule,
+                     const char *name="MWeight") { AddPar(fTestTasks, rule, name); }
+
+    // Add calculation of weights to list of post tasks. Set fEnableWeights
+    void SetWeights(const char *rule)  { if (fEnableWeights) return; fEnableWeights=kTRUE; AddPostTask(rule); }
+    void SetWeights(MTask *t)          { if (fEnableWeights) return; fEnableWeights=kTRUE; AddPostTask(t);    }
+
+    ClassDef(MJOptimizeBase, 0)//Base class for all optimizations and trainings
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeCuts.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeCuts.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeCuts.cc	(revision 17960)
@@ -0,0 +1,371 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 9/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJOptimizeCuts
+//
+// Class for otimizing the parameters of the supercuts
+//
+// Minimization Control
+// ====================
+//
+//   To choose the minimization algorithm use:
+//         void SetOptimizer(Optimizer_t o);
+//
+//   Allowed options are:
+//        enum Optimizer_t
+//        {
+//            kMigrad,      // Minimize by the method of Migrad
+//            kSimplex,     // Minimize by the method of Simplex
+//            kMinimize,    // Migrad + Simplex (if Migrad fails)
+//            kMinos,       // Minos error determination
+//            kImprove,     // Local minimum search
+//            kSeek,        // Minimize by the method of Monte Carlo
+//            kNone         // Skip optimization
+//        };
+//
+//   For more details on the methods see TMinuit.
+//
+//
+//   You can change the behaviour of the minimization using
+//
+//        void SetNumMaxCalls(UInt_t num=0);
+//        void SetTolerance(Float_t tol=0);
+//
+//   While NumMaxCalls is the first, Tolerance the second arguement.
+//   For more details start root and type
+//
+//        gMinuit->mnhelp("command")
+//
+//   while command can be
+//        * MIGRAD
+//        * SIMPLEX
+//        * MINIMIZE
+//        * MINOS
+//        * IMPROVE
+//        * SEEK
+//
+//   The default (num==0 and tol==0) should always give you the
+//   corresponding defaults used in Minuit.
+//
+//
+// FIXME: Implement changing cut in hadronness...
+// FIXME: Show MHSignificance on MStatusDisplay during filling...
+// FIXME: Choose step-size percentage as static data membewr
+// FIXME: Choose minimization method
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJOptimizeCuts.h"
+
+#include <TClass.h>
+
+#include "MHMatrix.h"
+
+// Environment
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MStatusDisplay.h"
+
+// Eventloop
+#include "MReadTree.h"
+#include "MParList.h"
+#include "MTaskList.h"
+
+// Parameter container
+#include "MGeomCamMagic.h"
+#include "MParameters.h"
+#include "MFilterList.h"
+
+// histograms
+#include "../mhflux/MHAlpha.h"
+
+// Tasks
+#include "MF.h"
+#include "MFillH.h"
+#include "MContinue.h"
+#include "MMatrixLoop.h"
+
+#include "MFMagicCuts.h"
+
+ClassImp(MJOptimizeCuts);
+
+using namespace std;
+
+//------------------------------------------------------------------------
+//
+MHAlpha *MJOptimizeCuts::CreateNewHist(const char *name) const
+{
+    TClass *cls = gROOT->GetClass(fNameHist);
+    if (!cls)
+    {
+        *fLog << err << "Class " << fNameHist << " not found in dictionary... abort." << endl;
+        return NULL;
+    }
+    if (!cls->InheritsFrom(MHAlpha::Class()))
+    {
+        *fLog << err << "Class " << fNameHist << " doesn't inherit from MHAlpha... abort." << endl;
+        return NULL;
+    }
+
+    MHAlpha *h = (MHAlpha*)cls->New();
+    if (h && name)
+        h->SetName(name);
+
+    return h;
+}
+
+//------------------------------------------------------------------------
+//
+Bool_t MJOptimizeCuts::RunOnOffCore(MHAlpha &histon, MHAlpha &histof, const char *fname, MFilter *filter, MAlphaFitter *fit, const char *tree)
+{
+    SetTitle(Form("OptimizeCuts: %s", fname));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    fLog->Separator("Preparing On/Off-optimization");
+
+    MParList parlist;
+
+    MGeomCamMagic geom; // For GetConvMm2Deg
+    parlist.AddToList(&geom);
+
+    MHMatrix m("M");
+    AddRulesToMatrix(m);
+    parlist.AddToList(&m);
+
+    const Int_t idxdatatype = m.AddColumn("DataType.fVal");
+
+    histon.SkipHistTime();
+    histon.SkipHistTheta();
+    //histon.SkipHistEnergy();
+    histof.SkipHistTime();
+    histof.SkipHistTheta();
+    //histof.SkipHistEnergy();
+    histon.ForceUsingSize();
+    histof.ForceUsingSize();
+    histon.InitMapping(&m, 1);
+    histof.InitMapping(&m, 1);
+
+    if (filter)
+    {
+        if (filter->InheritsFrom(MFMagicCuts::Class()))
+            ((MFMagicCuts*)filter)->InitMapping(&m);
+        else
+        {
+            *fLog << err << "ERROR - Currently only MFMagicCuts is supported." << endl;
+            return kFALSE;
+        }
+    }
+
+    parlist.AddToList(&histon);
+    parlist.AddToList(&histof);
+
+    if (fname)
+    {
+        MReadTree read(tree);
+        read.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+        read.AddFile(fname);
+        if (!FillMatrix(read, parlist))
+            return kFALSE;
+    }
+    else
+    {
+        MParameterI par("DataType");
+        parlist.AddToList(&par);
+
+        gLog.Separator("Reading On-Data");
+        par.SetVal(1);
+        MReadTree readon(tree);
+        readon.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+        AddSequences(readon, fNamesOn);
+        if (!FillMatrix(readon, parlist))
+            return kFALSE;
+
+        gLog.Separator("Reading Off-Data");
+        par.SetVal(0);
+        MReadTree readoff(tree);
+        readoff.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+        AddSequences(readoff, fNamesOff);
+        if (!FillMatrix(readoff, parlist))
+            return kFALSE;
+    }
+
+    MTaskList tasklist;
+    parlist.Replace(&tasklist);
+    if (fit)
+        parlist.AddToList(fit);
+
+    MFilterList list;
+    SetupFilters(list, filter);
+
+    MContinue contin(&list);
+    parlist.AddToList(&list);
+
+    MFillH fillof(&histof, "", "FillHistOff");
+    MFillH fillon(&histon, "", "FillHistOn");
+
+    MF f0(Form("M[%d]<0.5", idxdatatype), "FilterOffData");
+    MF f1(Form("M[%d]>0.5", idxdatatype), "FilterOnData");
+
+    fillof.SetFilter(&f0);
+    fillon.SetFilter(&f1);
+
+    MMatrixLoop loop(&m);
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&list);
+    tasklist.AddToList(&contin);
+    tasklist.AddToList(&f0);
+    tasklist.AddToList(&f1);
+    tasklist.AddToList(&fillof);
+    tasklist.AddToList(&fillon);
+
+    // Optimize with the tasklist in this parameterlist
+    if (!Optimize(parlist))
+        return kFALSE;
+
+    *fLog << inf << "Finished processing of " << fname << endl;
+
+    // Copy the result back to be accessible by the user
+    if (fit)
+        histon.GetAlphaFitter().Copy(*fit);
+
+    // Print the result
+    histon.GetAlphaFitter().Print("result");
+
+    // Store result if requested
+    TObjArray cont;
+    cont.Add(&contin);
+    return WriteContainer(cont, fNameOut);
+}
+
+Bool_t MJOptimizeCuts::RunOnCore(MHAlpha &hist, const char *fname, MFilter *filter, MAlphaFitter *fit)
+{
+    SetTitle(Form("OptimizeCuts: %s", fname));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    fLog->Separator("Preparing On-only-optimization");
+
+    MParList parlist;
+
+    MGeomCamMagic geom; // For GetConvMm2Deg
+    parlist.AddToList(&geom);
+
+    MHMatrix m("M");
+    AddRulesToMatrix(m);
+    parlist.AddToList(&m);
+
+    hist.SkipHistTime();
+    hist.SkipHistTheta();
+    hist.SkipHistEnergy();
+    hist.InitMapping(&m); 
+
+    if (filter && filter->InheritsFrom(MFMagicCuts::Class()))
+        ((MFMagicCuts*)filter)->InitMapping(&m);
+
+    MReadTree read("Events");
+    read.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+    if (fname)
+        read.AddFile(fname);
+    else
+        AddSequences(read, fNamesOn);
+    if (!FillMatrix(read, parlist))
+        return kFALSE;
+
+    MTaskList tasklist;
+    parlist.Replace(&tasklist);
+    if (fit)
+        parlist.AddToList(fit);
+
+    MFilterList list;
+    SetupFilters(list, filter);
+
+    MContinue contin(&list);
+    parlist.AddToList(&list);
+
+    MFillH fill(&hist);
+
+    MMatrixLoop loop(&m);
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&list);
+    tasklist.AddToList(&contin);
+    tasklist.AddToList(&fill);
+
+    // Optimize with the tasklist in this parameterlist
+    if (!Optimize(parlist))
+        return kFALSE;
+
+    *fLog << inf << "Finished processing of " << fname << endl;
+
+    // Copy the result back to be accessible by the user
+    if (fit)
+        hist.GetAlphaFitter().Copy(*fit);
+    // Print the result
+    hist.GetAlphaFitter().Print("result");
+
+    // Store result if requested
+    TObjArray cont;
+    cont.Add(&contin);
+    if (fDisplay)
+        cont.Add(fDisplay);
+    return WriteContainer(cont, fNameOut);
+}
+
+//------------------------------------------------------------------------
+//
+Bool_t MJOptimizeCuts::RunOnOff(const char *fname, MFilter *filter, MAlphaFitter *fit, const char *tree)
+{
+    MHAlpha *histon = CreateNewHist("Hist");
+    MHAlpha *histof = CreateNewHist("HistOff");
+
+    if (!histon || !histof)
+        return kFALSE;
+
+    const Bool_t rc = RunOnOffCore(*histon, *histof, fname, filter, fit, tree);
+
+    delete histon;
+    delete histof;
+
+    return rc;
+}
+
+//------------------------------------------------------------------------
+//
+Bool_t MJOptimizeCuts::RunOn(const char *fname, MFilter *filter, MAlphaFitter *fit)
+{
+    MHAlpha *histon = CreateNewHist();
+
+    if (!histon)
+        return kFALSE;
+
+    const Bool_t rc = RunOnCore(*histon, fname, filter, fit);
+
+    delete histon;
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeCuts.h
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeCuts.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeCuts.h	(revision 17960)
@@ -0,0 +1,57 @@
+#ifndef MARS_MJOptimizeCuts
+#define MARS_MJOptimizeCuts
+
+#ifndef MARS_MJOptimize
+#include "MJOptimize.h"
+#endif
+
+class MHAlpha;
+
+class MJOptimizeCuts : public MJOptimize
+{
+private:
+    TString fNameHist;
+
+    MHAlpha *CreateNewHist(const char *name=0) const;
+
+    Bool_t RunOnCore(MHAlpha &hist, const char *fname, MFilter *filter, MAlphaFitter *fit);
+    Bool_t RunOnOffCore(MHAlpha &histon, MHAlpha &histoff, const char *fname, MFilter *filter, MAlphaFitter *fit, const char *tree);
+
+public:
+    MJOptimizeCuts(const char *name="MHAlpha") : MJOptimize(), fNameHist(name) { }
+
+    // Optimization On-Off/Wobble
+    Bool_t RunOnOff(const char *fname, MFilter *filter, MAlphaFitter *fit=0, const char *tree="Events");
+    Bool_t RunOnOff(const char *fname, MAlphaFitter *fit=0, const char *tree="Events")
+    {
+        return RunOnOff(fname, 0, fit, tree);
+    }
+    Bool_t RunOnOff(MFilter *filter, MAlphaFitter *fit=0, const char *tree="Events")
+    {
+        return RunOnOff(0, filter, fit, tree);
+    }
+    Bool_t RunOnOff(MAlphaFitter *fit=0, const char *tree="Events")
+    {
+        return RunOnOff(fit, tree);
+    }
+
+    // Optimization On-only
+    Bool_t RunOn(const char *fname, MFilter *filter, MAlphaFitter *fit=0);
+    Bool_t RunOn(const char *fname, MAlphaFitter *fit=0)
+    {
+        return RunOn(fname, 0, fit);
+    }
+
+    Bool_t RunOn(MFilter *filter, MAlphaFitter *fit=0)
+    {
+        return RunOn(0, filter, fit);
+    }
+    Bool_t RunOn(MAlphaFitter *fit=0)
+    {
+        return RunOn(0, 0, fit);
+    }
+
+    ClassDef(MJOptimizeCuts, 0) // Class for optimization of the Supercuts
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeDisp.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeDisp.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeDisp.cc	(revision 17960)
@@ -0,0 +1,224 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJOptimizeDisp
+//
+// Class for otimizing the disp parameters. For more details see
+// MJOptimize.
+//
+// MJOptimizeDisp minimzes the width of the Theta^2 distribution by
+// minimizing <Theta^2> (the RMS^2 of Theta^2), while Theta^2 is
+// calculated as:
+//        Theta^2 = d^2 + p^2 - 2*d*p*cos(a)
+// with:
+//        d: MHillasSrc.fDist [deg]
+//        p: Disp as calculated by the given rule, eg: [0] (a constant)
+//        a: MHillasSrc.fAlpha [rad]
+//
+// Example:
+// --------
+//    MJOptimizeDisp opt;
+//    opt.SetDebug(2);
+//    opt.SetOptimizer(MJOptimize::kMigrad);
+//    opt.SetNumEvents(20000);
+//    opt.EnableTestTrain();
+//    opt.AddParameter("1-(MHillas.fWidth/MHillas.fLength)");
+//    opt.SetParameter(0, 1, 0, 2);
+//    char *r = "[0]*M[0]"; //Rule to calculate disp
+//    MStatusDisplay *d = new MStatusDisplay;
+//    opt.SetDisplay(d);
+//    opt.RunDisp("ganymed-summary.root", r);
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJOptimizeDisp.h"
+
+#include "MHMatrix.h"
+
+// environment
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// parameters
+#include "MParameters.h"
+#include "MGeomCamMagic.h"
+
+// histograms
+#include "MH3.h"
+#include "MBinning.h"
+#include "../mhflux/MAlphaFitter.h"
+#include "../mhflux/MHThetaSq.h"
+#include "../mtools/MChisqEval.h"
+
+// tasks
+#include "MReadTree.h"
+#include "MMatrixLoop.h"
+#include "MParameterCalc.h"
+#include "MFillH.h"
+
+// filters
+#include "MFDataMember.h"
+
+using namespace std;
+
+ClassImp(MJOptimizeDisp);
+
+//------------------------------------------------------------------------
+//
+// Read all events from file which do match rules and optimize
+// disp estimator.
+//
+Bool_t MJOptimizeDisp::RunDisp(const char *fname, const char *rule, MTask *weights)
+{
+    SetTitle(Form("OptimizeDisp: %s", fname));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    fLog->Separator("Preparing Disp optimization");
+
+    MParList parlist;
+
+    MParameterI par1("DataType");
+    par1.SetVal(1);
+    parlist.AddToList(&par1);
+
+    MParameterD par2("ThetaSquaredCut");
+    par2.SetVal(0.2);
+    parlist.AddToList(&par2);
+
+    MAlphaFitter fit;
+    fit.SetPolynomOrder(0);
+    fit.SetSignalFitMax(0.8);
+    fit.EnableBackgroundFit(kFALSE);
+    fit.SetSignalFunction(MAlphaFitter::kThetaSq);
+    fit.SetMinimizationStrategy(MAlphaFitter::kGaussSigma);
+    parlist.AddToList(&fit);
+
+    // To avoid this hard-coded we have to switch to MReadMarsFile
+    MGeomCamMagic geom; // For GetConvMm2Deg
+    parlist.AddToList(&geom);
+
+    MHMatrix m("M");
+    AddRulesToMatrix(m);
+    parlist.AddToList(&m);
+
+    const Int_t num1 = m.AddColumn("MHillasSrc.fDist*MGeomCam.fConvMm2Deg");
+    const Int_t num2 = m.AddColumn("MHillasSrc.fAlpha*TMath::DegToRad()");
+    const Int_t num3 = m.AddColumn("MHillas.fSize");
+
+    MHThetaSq hist;
+    hist.SkipHistTime();
+    hist.SkipHistTheta();
+    //hist.SkipHistEnergy();
+    //hist.ForceUsingSize();
+    hist.InitMapping(&m, 1);
+
+    MFDataMember filter("DataType.fVal", '>', 0.5);
+    fPreCuts.Add(&filter);
+
+    MParameterCalc calc1(rule, "MParameters");
+    calc1.SetNameParameter("Disp");
+    parlist.AddToList(&calc1);
+
+    const char *disp = "Disp.fVal";
+    const char *n1   = Form("M[%d]", num1);
+
+    const char *rule2 = Form("(%s*%s) + (%s*%s) - (2*%s*%s*cos(M[%d]))",
+                             n1, n1, disp, disp, n1, disp, num2);
+
+    MParameterCalc calc2(rule2, "MThetaSqCalc");
+    calc2.SetNameParameter("ThetaSquared");
+
+    MReadTree read("Events");
+    // NECESSARY BECAUSE OF MDataFormula GetRules missing
+    read.DisableAutoScheme();
+    if (fname)
+        read.AddFile(fname);
+    else
+        AddSequences(read, fNamesOn);
+    if (!FillMatrix(read, parlist, kTRUE))
+        return kFALSE;
+
+    fPreCuts.Remove(&filter);
+
+    MTaskList tasklist;
+    parlist.Replace(&tasklist);
+
+    MFillH fill(&hist);
+    if (weights)
+        fill.SetWeight();
+
+    MChisqEval eval;
+    eval.SetY1(fUseThetaSq?"ThetaSquared.fVal":"sqrt(ThetaSquared.fVal)");
+    if (weights)
+        eval.SetNameWeight();
+
+    MMatrixLoop loop(&m);
+
+    const char *n3   = Form("M[%d]", num3);
+    MH3 hdisp(n3, "sqrt(ThetaSquared.fVal)");
+    hdisp.SetTitle("\\vartheta^{2} distribution vs. Size:Size [phe]:\\vartheta^{2} [\\circ^{2}]");
+
+    MBinning binsx(100, 10, 100000, "BinningMH3X", "log");
+    MBinning binsy(100, 0,  2,      "BinningMH3Y", "lin");
+
+    parlist.AddToList(&binsx);
+    parlist.AddToList(&binsy);
+
+    MFillH fillh2(&hdisp);
+    fillh2.SetDrawOption("blue profx");
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&calc1);
+    tasklist.AddToList(&calc2);
+    if (weights)
+        tasklist.AddToList(weights);
+    tasklist.AddToList(&fill);
+    tasklist.AddToList(&fillh2);
+    tasklist.AddToList(&eval);
+
+    // Optimize with the tasklist in this parameterlist
+    if (!Optimize(parlist))
+        return kFALSE;
+
+    // Print the result
+    *fLog << inf;
+    *fLog << "Finished processing of " << fname << endl;
+    *fLog << "With Rule: " << rule << endl;
+    hist.GetAlphaFitter().Print("result");
+
+    // Store result if requested
+    TObjArray cont;
+    if (fDisplay)
+        cont.Add(fDisplay);
+    cont.Add(&calc1);
+    return WriteContainer(cont, fNameOut);
+}
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeDisp.h
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeDisp.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeDisp.h	(revision 17960)
@@ -0,0 +1,30 @@
+#ifndef MARS_MJOptimizeDisp
+#define MARS_MJOptimizeDisp
+
+#ifndef MARS_MJOptimize
+#include "MJOptimize.h"
+#endif
+
+class MTask;
+
+class MJOptimizeDisp : public MJOptimize
+{
+private:
+    Bool_t fUseThetaSq;
+
+public:
+    MJOptimizeDisp() : MJOptimize(), fUseThetaSq(kFALSE) { }
+
+    void EnableThetaSq(Bool_t b=kTRUE) { fUseThetaSq=b; }
+
+    // Special optimizing routines
+    Bool_t RunDisp(const char *fname, const char *rule, MTask *weights=0);
+    Bool_t RunDisp(const char *rule, MTask *weights=0)
+    {
+        return RunDisp(0, rule, weights);
+    }
+
+    ClassDef(MJOptimizeDisp, 0) // Class for optimization of the Supercuts
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeEnergy.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeEnergy.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeEnergy.cc	(revision 17960)
@@ -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, 9/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJOptimize
+//
+// Class for otimizing a rule to estimate the energy. For more details see
+// MJOptimize.
+//
+// Example:
+// --------
+//
+//    MJOptimizeEnergy opt;
+//    opt.SetDebug(2);
+//    opt.SetOptimizer(MJOptimize::kMigrad);
+//    opt.SetNumEvents(20000);
+//    opt.EnableTestTrain();
+//    opt.AddParameter("MHillas.fSize");
+//    opt.SetParameter(0, 1, 0, 2);
+//    char *r = "[0]*M[0]"; //Rule to calculate estimated energy
+//    MStatusDisplay *d = new MStatusDisplay;
+//    opt.SetDisplay(d);
+//    opt.RunDisp("ganymed-summary.root", r);
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJOptimizeEnergy.h"
+
+#include "MHMatrix.h"
+
+// environment
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// parameters
+#include "MParameters.h"
+#include "MGeomCamMagic.h"
+
+// histograms
+#include "../mhflux/MHEnergyEst.h"
+#include "../mtools/MChisqEval.h"
+
+// tasks
+#include "MReadTree.h"
+#include "MMatrixLoop.h"
+#include "MEnergyEstimate.h"
+#include "MFillH.h"
+
+// filters
+#include "MFDataMember.h"
+
+using namespace std;
+
+ClassImp(MJOptimizeEnergy);
+
+//------------------------------------------------------------------------
+//
+// Read all events from file which do match rules and optimize
+// energy estimator.
+//
+Bool_t MJOptimizeEnergy::RunEnergy(const char *fname, const char *rule, MTask *weights)
+{
+    SetTitle(Form("OptimizeEnergy: %s", fname));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    fLog->Separator("Preparing Energy optimization");
+
+    MParList parlist;
+
+    MParameterI par("DataType");
+    par.SetVal(1);
+    parlist.AddToList(&par);
+
+    MFDataMember filter("DataType.fVal", '>', 0.5);
+    fPreCuts.Add(&filter);
+
+    MGeomCamMagic geom; // For GetConvMm2Deg
+    parlist.AddToList(&geom);
+
+    MHMatrix m("M");
+    AddRulesToMatrix(m);
+    const Int_t map = m.AddColumn("MMcEvt.fEnergy");
+    parlist.AddToList(&m);
+
+    MHEnergyEst hist;
+    hist.InitMapping(&m); 
+
+    MParameterCalc est(rule, "MParameters");
+    est.SetNameParameter("MEnergyEst");
+    parlist.AddToList(&est);
+
+    MReadTree read("Events");
+    // NECESSARY BECAUSE OF MDataFormula GetRules missing
+    read.DisableAutoScheme();
+    if (fname)
+        read.AddFile(fname);
+    else
+        AddSequences(read, fNamesOn);
+    if (!FillMatrix(read, parlist, kTRUE))
+        return kFALSE;
+
+    fPreCuts.Remove(&filter);
+
+    MTaskList tasklist;
+    parlist.Replace(&tasklist);
+
+    MFillH fill(&hist);
+    if (weights)
+        fill.SetWeight();
+
+    MChisqEval eval;
+    eval.SetY1(fOptimLog?Form("log10(MEnergyEst.fVal/M[%d])", map):Form("MEnergyEst.fVal-M[%d]", map));
+    if (weights)
+        eval.SetNameWeight();
+
+    MMatrixLoop loop(&m);
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&est);
+    if (weights)
+        tasklist.AddToList(weights);
+    tasklist.AddToList(&fill);
+    tasklist.AddToList(&eval);
+
+    // Optimize with the tasklist in this parameterlist
+    if (!Optimize(parlist))
+        return kFALSE;
+
+    // Print the result
+    *fLog << inf << "Finished processing of " << fname << endl;
+    *fLog << inf << "With Rule: " << rule << endl;
+    hist.Print();
+
+    // Store result if requested
+    TObjArray cont;
+    cont.Add(&est);
+    if (fDisplay)
+        cont.Add(fDisplay);
+    return WriteContainer(cont, fNameOut);
+}
Index: branches/Mars_McMismatchStudy/mjoptim/MJOptimizeEnergy.h
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/MJOptimizeEnergy.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/MJOptimizeEnergy.h	(revision 17960)
@@ -0,0 +1,30 @@
+#ifndef MARS_MJOptimizeEnergy
+#define MARS_MJOptimizeEnergy
+
+#ifndef MARS_MJOptimize
+#include "MJOptimize.h"
+#endif
+
+class MTask;
+
+class MJOptimizeEnergy : public MJOptimize
+{
+private:
+    Bool_t fOptimLog;
+
+public:
+    MJOptimizeEnergy() : MJOptimize(), fOptimLog(kFALSE) { }
+
+    void EnableOptimLog(Bool_t b=kTRUE) { fOptimLog=b; }
+
+    // Special optimizing routines
+    Bool_t RunEnergy(const char *fname, const char *rule, MTask *weights=0);
+    Bool_t RunEnergy(const char *rule, MTask *weights=0)
+    {
+        return RunEnergy(0, rule, weights);
+    }
+
+    ClassDef(MJOptimizeEnergy, 0) // Class for optimization of the Supercuts
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjoptim/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/Makefile	(revision 17960)
@@ -0,0 +1,43 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Optim
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mfbase -I../mdata -I../mfileio \
+           -I../manalysis -I../mgeom -I../mfilter -I../mjobs
+# mdata:     MDataMember
+# mfbase:    MF
+# mfilter:   MFMagicCuts
+# mhbase:    MHMatrix
+# manalysis: MMatrixLoop
+# mjobs:     MJob
+# mgeom:     MGeomCam
+
+SRCFILES = MJOptimizeBase.cc \
+           MJOptimize.cc \
+           MJOptimizeCuts.cc \
+           MJOptimizeDisp.cc \
+           MJOptimizeEnergy.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mjoptim/OptimIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/OptimIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/OptimIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mjoptim/OptimLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mjoptim/OptimLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjoptim/OptimLinkDef.h	(revision 17960)
@@ -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 MJOptimize+;
+#pragma link C++ class MJOptimizeBase+;
+#pragma link C++ class MJOptimizeCuts+;
+#pragma link C++ class MJOptimizeDisp+;
+#pragma link C++ class MJOptimizeEnergy+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainCuts.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainCuts.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainCuts.cc	(revision 17960)
@@ -0,0 +1,1063 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2010 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJTrainCuts
+// =========
+//
+// This class is meant as a tool to understand better what a trained
+// random forest is doing in the multi-dimensional phase space.
+// Consequently, it can also be used to deduce good one or two dimensional
+// cuts from the results by mimicing the behaviour of the random forest.
+//
+//
+// Usage
+// -----
+//
+// The instance is created by its default constructor
+//
+//    MJTrainCuts opt;
+//
+// In a first step a random forest must be trained and in a second step its
+// performance can be evaluated with an independent test sample. The used
+// samples are defined by two MDataSet objects, one for the on-data (e.g.
+// gammas) and the other one for the off-data (e.g. protons). SequencesOn
+// and SequencesOff are used for testing and training respectively.
+//
+//    MDataSet seton ("myondata.txt");
+//    MDataSet setoff("myoffdata.txt");
+//
+//    // If you want to use all available events
+//    opt.SetDataSetOn(seton);
+//    opt.SetDataSetOff(setoff);
+//
+//    // Try to select 10000 and 30000 events for training and testing resp.
+//    // opt.SetDataSetOn(seton, 10000, 30000);
+//    // opt.SetDataSetOff(setoff, 10000, 30000);
+//
+// Note that by using several data set in one file (see MDataSet) you can
+// have everything in a single file.
+//
+// The variables which are used for training are now setup as usual
+//
+//    Int_t p1 = opt.AddParameter("MHillas.fSize");
+//    Int_t p2 = opt.AddParameter("MHillas.GetArea*MGeomCam.fConvMm2Deg^2");
+//    Int_t p3 = opt.AddParameter("MHillasSrc.fDist*MGeomCam.fConvMm2Deg");
+//
+// In addition you can now setup a binning for the display of each train
+// parameter as follows (for details see MBinning)
+//
+//    opt.AddBinning(p1, MBinning(40, 10, 10000, "", "log"));
+//    opt.AddBinning(p2, MBinning(50,  0, 0.25));
+//    opt.AddBinning(p3, MBinning(50,  0, 2.5));
+//
+// Since with increasing number of variables the possibly combinations
+// increase to fast you have to define which plots you are interested in,
+// for example:
+//
+//    opt.AddHist(p3);      // A 1D plot dist
+//    opt.AddHist(p1, p2);  // A 2D plot area vs. size
+//    opt.AddHist(p3, p2);  // A 2D plot dist vs. size
+//
+// Also 3D plots are avaiable but they are most probably difficult to
+// interprete.
+//
+// In addition to this you have the usual user interface, i.e. that
+//   - PreCuts
+//   - TrainCuts
+//   - TestCuts
+//   - PreTasks
+//   - PostTasks
+//   - TestTasks
+// are available. For details see MJOptimizeBase
+//
+// void EnableRegression() / void EnableClassification()
+//    Defines whether to use the random forest's regression of
+//    classification method. Classification is the default.
+//
+//
+// The produced plots
+// ------------------
+//
+// The tab with the plots filled will always look like this:
+//
+//    +--------+--------+
+//    |1       |2       |
+//    +--------+--------|
+//    |3       |4       |
+//    +--------+        |
+//    |5       |        |
+//    +--------+--------+
+//
+// Pad1 and Pad2 contain the weighted event distribution of the test-sample.
+//
+// Pad2 and Pad5 conatin a profile of the hadronness distribution of the
+// test-sample.
+//
+// Pad4 contains a profile of the hadronness distribution of on-data and
+// off-data together of the test-data.
+//
+// If the profiles for on-data and off-data are identical the displayed
+// hadronness is obviously independant of the other (non shown) trainings
+// variables. Therefore the difference between the two plots show how much
+// the variables are correlated. The same is true if the prfiles in
+// pad3 and pad5 don't differe from the profile in pad4.
+//
+// In the most simple case - the random forest is only trained with the
+// variables displayed - all three plots should be identical (apart from the
+// difference in the distrubution of the three sets).
+//
+// The plot in pad4 can now be used to deduce a good classical cut in the
+// displayed variables.
+//
+//
+// Example:
+// --------
+//
+//    MJTrainCuts opt;
+//    MDataSet seton ("dataset_on.txt");
+//    MDataSet setoff("dataset_off.txt");
+//    opt.SetDataSetOn(seton);
+//    opt.SetDataSetOff(setmix);
+//    Int_t p00 = opt.AddParameter("MHillas.fSize");
+//    Int_t p01 = opt.AddParameter("MHillas.GetArea*MGeomCam.fConvMm2Deg^2");
+//    opt.AddHist(p00, p01);    // Area vs Size
+//    MStatusDisplay *d = new MStatusDisplay;
+//    opt.SetDisplay(d);
+//    opt.Process("rf-cuts.root");
+//
+//
+// Random Numbers:
+// ---------------
+//   Use:
+//         if(gRandom)
+//             delete gRandom;
+//         gRandom = new TRandom3();
+//   in advance to change the random number generator.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MJTrainCuts.h"
+
+#include <TGraph.h>
+#include <TMarker.h>
+#include <TCanvas.h>
+#include <TPRegexp.h>
+#include <TStopwatch.h>
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+// tools
+#include "MMath.h"
+#include "MBinning.h"
+#include "MTFillMatrix.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// tasks
+#include "MReadMarsFile.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MRanForestCalc.h"
+
+// container
+#include "MParameters.h"
+
+// histograms
+#include "MHn.h"
+#include "MHHadronness.h"
+
+// filter
+#include "MFEventSelector.h"
+#include "MFilterList.h"
+
+using namespace std;
+
+class HistSet1D : public TObject
+{
+protected:
+    UInt_t fNx;
+
+    virtual void AddHist(MHn &h, const char *rx, const char *, const char *) const
+    {
+        h.AddHist(rx);
+    }
+    virtual void AddProf(MHn &h, const char *rx, const char *, const char *) const
+    {
+        h.AddHist(rx, "MHadronness.fVal", MH3::kProfileSpread);
+    }
+    virtual void SetupName(MHn &h, const char *name) const
+    {
+        h.InitName(Form("%s%d;%d", name, fNx, fNx));
+    }
+    virtual void SetupHist(MHn &h, const char *name, const char *title) const
+    {
+        SetupName(h, name);
+
+        h.SetAutoRange(kFALSE, kFALSE, kFALSE);
+        h.InitTitle(title);
+    }
+
+    void CreateHist(MHn &h, const char *rx, const char *ry=0, const char *rz=0) const
+    {
+        h.SetLayout(MHn::kComplex);
+        h.SetBit(MHn::kDoNotReset);
+
+        AddHist(h, rx, ry, rz);
+        SetupHist(h, "DistOn", "Distribution of on-data");
+        h.SetWeight("Type.fVal");
+
+        AddHist(h, rx, ry, rz);
+        SetupHist(h, "DistOff", "Distribution of off-data");
+        h.SetWeight("1-Type.fVal");
+
+        AddProf(h, rx, ry, rz);
+        SetupHist(h, "HadOn", "Hadronness profile for on-data");
+        h.SetWeight("Type.fVal");
+
+        AddProf(h, rx, ry, rz);
+        SetupHist(h, "Had", "Hadronness profile for all events");
+
+        AddProf(h, rx, ry, rz);
+        SetupHist(h, "HadOff", "Hadronness profile for off-data");
+        h.SetWeight("1-Type.fVal");
+    }
+
+
+public:
+    HistSet1D(UInt_t nx) : fNx(nx) { }
+
+    virtual MHn *GetHistN(const TList &rules) const
+    {
+        if (!rules.At(fNx))
+            return 0;
+
+        MHn *h = new MHn(Form("%d", fNx));
+
+        CreateHist(*h, rules.At(fNx)->GetName());
+
+        return h;
+    }
+
+    virtual Bool_t CheckBinning(const TObjArray &binnings) const
+    {
+        return binnings.FindObject(Form("Binning%d", fNx));
+    }
+};
+
+class HistSet2D : public HistSet1D
+{
+protected:
+    UInt_t fNy;
+
+    void AddHist(MHn &h, const char *rx, const char *ry, const char *) const
+    {
+        h.AddHist(rx, ry);
+    }
+    void AddProf(MHn &h, const char *rx, const char *ry, const char *) const
+    {
+        h.AddHist(rx, ry, "MHadronness.fVal", MH3::kProfileSpread);
+    }
+    void SetupName(MHn &h, const char *name) const
+    {
+        h.InitName(Form("%s%d:%d;%d;%d", name, fNx, fNy, fNx, fNy));
+    }
+
+    void SetupHist(MHn &h, const char *name, const char *title) const
+    {
+        HistSet1D::SetupHist(h, name, title);
+        h.SetDrawOption("colz");
+    }
+
+public:
+    HistSet2D(UInt_t nx, UInt_t ny) : HistSet1D(nx), fNy(ny) { }
+
+    MHn *GetHistN(const TList &rules) const
+    {
+        if (!rules.At(fNx) || !rules.At(fNy))
+            return 0;
+
+        MHn *h = new MHn(Form("%d:%d", fNx, fNy));
+
+        CreateHist(*h, rules.At(fNx)->GetName(), rules.At(fNy)->GetName());
+
+        return h;
+    }
+    Bool_t CheckBinning(const TObjArray &binnings) const
+    {
+        return HistSet1D::CheckBinning(binnings) && binnings.FindObject(Form("Binning%d", fNy));
+    }
+};
+
+
+class HistSet3D : public HistSet2D
+{
+private:
+    UInt_t fNz;
+
+    void AddHist(MHn &h, const char *rx, const char *ry, const char *rz) const
+    {
+        h.AddHist(rx, ry, rz);
+    }
+    void AddProf(MHn &h, const char *rx, const char *ry, const char *rz) const
+    {
+        h.AddHist(rx, ry, rz, "MHadronness.fVal");
+    }
+    void SetupName(MHn &h, const char *name) const
+    {
+        h.InitName(Form("%s%d:%d:%d;%d;%d;%d", name, fNx, fNy, fNz, fNx, fNy, fNz));
+    }
+
+public:
+    HistSet3D(UInt_t nx, UInt_t ny, UInt_t nz) : HistSet2D(nx, ny), fNz(nz) { }
+
+    MHn *GetHistN(const TList &rules) const
+    {
+        if (!rules.At(fNx) || !rules.At(fNy) || !rules.At(fNz))
+            return 0;
+
+        MHn *h = new MHn(Form("%d:%d:%d", fNx, fNy, fNz));
+
+        CreateHist(*h,
+                   rules.At(fNx)->GetName(),
+                   rules.At(fNy)->GetName(),
+                   rules.At(fNy)->GetName());
+
+        return h;
+    }
+    Bool_t CheckBinning(const TObjArray &binnings) const
+    {
+        return HistSet2D::CheckBinning(binnings) && binnings.FindObject(Form("Binning%d", fNz));
+    }
+};
+
+// ---------------------------------------------------------------------------------------
+
+void MJTrainCuts::AddHist(UInt_t nx)
+{
+    fHists.Add(new HistSet1D(nx));
+}
+
+void MJTrainCuts::AddHist(UInt_t nx, UInt_t ny)
+{
+    fHists.Add(new HistSet2D(nx, ny));
+}
+
+void MJTrainCuts::AddHist(UInt_t nx, UInt_t ny, UInt_t nz)
+{
+    fHists.Add(new HistSet3D(nx, ny, nz));
+}
+
+void MJTrainCuts::AddBinning(UInt_t n, const MBinning &bins)
+{
+    const char *name = Form("Binning%d", n);
+
+    TObject *o = fBinnings.FindObject(name);
+    if (o)
+    {
+        delete fBinnings.Remove(o);
+        *fLog << warn << "WARNING - Binning for parameter " << n << " (" << name << ") already exists... replaced." << endl;
+    }
+
+    // FIXME: Check for existence
+    fBinnings.Add(new MBinning(bins, name, bins.GetTitle()));
+}
+
+/*
+void MJTrainCuts::AddBinning(const MBinning &bins)
+{
+    // FIXME: Check for existence
+    fBinnings.Add(new MBinning(bins, bins.GetName(), bins.GetTitle()));
+}
+*/
+
+// ---------------------------------------------------------------------------------------
+
+// --------------------------------------------------------------------------
+//
+void MJTrainCuts::DisplayResult(MH3 &h31, MH3 &h32, Float_t ontime)
+{
+    TH2D &g = (TH2D&)h32.GetHist();
+    TH2D &h = (TH2D&)h31.GetHist();
+
+    h.SetMarkerColor(kRed);
+    g.SetMarkerColor(kBlue);
+
+    TH2D res1(g);
+    TH2D res2(g);
+
+    h.SetTitle("Hadronness-Distribution vs. Size");
+    res1.SetTitle("Significance Li/Ma");
+    res1.SetXTitle("Size [phe]");
+    res1.SetYTitle("Hadronness");
+    res2.SetTitle("Significance-Distribution");
+    res2.SetXTitle("Size-Cut [phe]");
+    res2.SetYTitle("Hadronness-Cut");
+    res1.SetContour(50);
+    res2.SetContour(50);
+
+    const Int_t nx = h.GetNbinsX();
+    const Int_t ny = h.GetNbinsY();
+
+    gROOT->SetSelectedPad(NULL);
+
+
+    Double_t Stot = 0;
+    Double_t Btot = 0;
+
+    Double_t max2 = -1;
+
+    TGraph gr1;
+    TGraph gr2;
+    for (int x=nx-1; x>=0; x--)
+    {
+        TH1 *hx = h.ProjectionY("H_py", x+1, x+1);
+        TH1 *gx = g.ProjectionY("G_py", x+1, x+1);
+
+        Double_t S = 0;
+        Double_t B = 0;
+
+        Double_t max1 = -1;
+        Int_t maxy1 = 0;
+        Int_t maxy2 = 0;
+        for (int y=ny-1; y>=0; y--)
+        {
+            const Float_t s = gx->Integral(1, y+1);
+            const Float_t b = hx->Integral(1, y+1);
+            const Float_t sig1 = MMath::SignificanceLiMa(s+b, b);
+            const Float_t sig2 = MMath::SignificanceLiMa(s+Stot+b+Btot, b+Btot)*TMath::Log10(s+Stot+1);
+            if (sig1>max1)
+            {
+                maxy1 = y;
+                max1 = sig1;
+            }
+            if (sig2>max2)
+            {
+                maxy2 = y;
+                max2 = sig2;
+
+                S=s;
+                B=b;
+            }
+
+            res1.SetBinContent(x+1, y+1, sig1);
+        }
+
+        Stot += S;
+        Btot += B;
+
+        gr1.SetPoint(x, h.GetXaxis()->GetBinCenter(x+1), h.GetYaxis()->GetBinCenter(maxy1+1));
+        gr2.SetPoint(x, h.GetXaxis()->GetBinCenter(x+1), h.GetYaxis()->GetBinCenter(maxy2+1));
+
+        delete hx;
+        delete gx;
+    }
+
+    //cout << "--> " << MMath::SignificanceLiMa(Stot+Btot, Btot) << " ";
+    //cout << Stot << " " << Btot << endl;
+
+
+    Int_t mx1=0;
+    Int_t my1=0;
+    Int_t mx2=0;
+    Int_t my2=0;
+    Int_t s1=0;
+    Int_t b1=0;
+    Int_t s2=0;
+    Int_t b2=0;
+    Double_t sig1=-1;
+    Double_t sig2=-1;
+    for (int x=0; x<nx; x++)
+    {
+        TH1 *hx = h.ProjectionY("H_py", x+1);
+        TH1 *gx = g.ProjectionY("G_py", x+1);
+        for (int y=0; y<ny; y++)
+        {
+            const Float_t s = gx->Integral(1, y+1);
+            const Float_t b = hx->Integral(1, y+1);
+            const Float_t sig = MMath::SignificanceLiMa(s+b, b);
+            res2.SetBinContent(x+1, y+1, sig);
+
+            // Search for top-rightmost maximum
+            if (sig>=sig1)
+            {
+                mx1=x+1;
+                my1=y+1;
+                s1 = TMath::Nint(s);
+                b1 = TMath::Nint(b);
+                sig1=sig;
+            }
+            if (TMath::Log10(s)*sig>=sig2)
+            {
+                mx2=x+1;
+                my2=y+1;
+                s2 = TMath::Nint(s);
+                b2 = TMath::Nint(b);
+                sig2=TMath::Log10(s)*sig;
+            }
+        }
+        delete hx;
+        delete gx;
+    }
+
+    TGraph gr3;
+    TGraph gr4;
+    gr4.SetTitle("Significance Li/Ma vs. Hadronness-cut");
+
+    TH1 *hx = h.ProjectionY("H_py");
+    TH1 *gx = g.ProjectionY("G_py");
+    for (int y=0; y<ny; y++)
+    {
+        const Float_t s = gx->Integral(1, y+1);
+        const Float_t b = hx->Integral(1, y+1);
+        const Float_t sg1 = MMath::SignificanceLiMa(s+b, b);
+        const Float_t sg2 = s<1 ? 0 : MMath::SignificanceLiMa(s+b, b)*TMath::Log10(s);
+
+        gr3.SetPoint(y, h.GetYaxis()->GetBinLowEdge(y+2), sg1);
+        gr4.SetPoint(y, h.GetYaxis()->GetBinLowEdge(y+2), sg2);
+    }
+    delete hx;
+    delete gx;
+
+    if (fDisplay)
+    {
+        TCanvas &c = fDisplay->AddTab("OptCut");
+        c.SetBorderMode(0);
+        c.Divide(2,2);
+
+        gROOT->SetSelectedPad(0);
+        c.cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetLogx();
+        gPad->SetGridx();
+        gPad->SetGridy();
+        h.DrawCopy();
+        g.DrawCopy("same");
+        gr1.SetMarkerStyle(kFullDotMedium);
+        gr1.DrawClone("LP")->SetBit(kCanDelete);
+        gr2.SetLineColor(kBlue);
+        gr2.SetMarkerStyle(kFullDotMedium);
+        gr2.DrawClone("LP")->SetBit(kCanDelete);
+
+        gROOT->SetSelectedPad(0);
+        c.cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gr4.SetMinimum(0);
+        gr4.SetMarkerStyle(kFullDotMedium);
+        gr4.DrawClone("ALP")->SetBit(kCanDelete);
+        gr3.SetLineColor(kBlue);
+        gr3.SetMarkerStyle(kFullDotMedium);
+        gr3.DrawClone("LP")->SetBit(kCanDelete);
+
+        c.cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetLogx();
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gPad->AddExec("color", "gStyle->SetPalette(1, 0);");
+        res1.SetMaximum(7);
+        res1.DrawCopy("colz");
+
+        c.cd(4);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetLogx();
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gPad->AddExec("color", "gStyle->SetPalette(1, 0);");
+        res2.SetMaximum(res2.GetMaximum()*1.05);
+        res2.DrawCopy("colz");
+
+        //    Int_t mx, my, mz;
+        //    res2.GetMaximumBin(mx, my, mz);
+
+        TMarker m;
+        m.SetMarkerStyle(kStar);
+        m.DrawMarker(res2.GetXaxis()->GetBinCenter(mx1), res2.GetYaxis()->GetBinCenter(my1));
+        m.SetMarkerStyle(kPlus);
+        m.DrawMarker(res2.GetXaxis()->GetBinCenter(mx2), res2.GetYaxis()->GetBinCenter(my2));
+    }
+
+    if (ontime>0)
+        *fLog << all << "Observation Time:     " << TMath::Nint(ontime/60) << "min" << endl;
+    *fLog << "Maximum Significance: " << Form("%.1f", sig1);
+    if (ontime>0)
+        *fLog << Form(" [%.1f/sqrt(h)]", sig1/TMath::Sqrt(ontime/3600));
+    *fLog << endl;
+
+    *fLog << "Significance:         S=" << Form("%.1f", sig1) << " E=" << s1 << " B=" << b1 << " h<";
+    *fLog << Form("%.2f", res2.GetYaxis()->GetBinCenter(my1)) << " s>";
+    *fLog << Form("%3d", TMath::Nint(res2.GetXaxis()->GetBinCenter(mx1))) << endl;
+    *fLog << "Significance*LogE:    S=" << Form("%.1f", sig2/TMath::Log10(s2)) << " E=" << s2 << " B=" << b2 << " h<";
+    *fLog << Form("%.2f", res2.GetYaxis()->GetBinCenter(my2)) << " s>";
+    *fLog << Form("%3d", TMath::Nint(res2.GetXaxis()->GetBinCenter(mx2))) << endl;
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MJTrainCuts::Process(const char *out)
+{
+    // =========================== Consistency checks ==================================
+    if (!fDataSetOn.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet for on-data invalid!" << endl;
+        return kFALSE;
+    }
+    if (!fDataSetOff.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet for off-data invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (fDataSetOn.IsWobbleMode()!=fDataSetOff.IsWobbleMode())
+    {
+        *fLog << err << "ERROR - On- and Off-DataSet have different observation modes!" << endl;
+        return kFALSE;
+    }
+
+    if (fDataSetOn.IsMonteCarlo()!=fDataSetOff.IsMonteCarlo())
+    {
+        *fLog << err << "ERROR - On- and Off-DataSet have different monte carlo modes!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(out))
+        return kFALSE;
+
+    // Check if needed binning exists
+    TIter NextH(&fHists);
+    TObject *o = 0;
+    while ((o=NextH()))
+    {
+        const HistSet1D *hs = static_cast<HistSet1D*>(o);
+        if (hs->CheckBinning(fBinnings))
+            continue;
+
+        *fLog << err << "ERROR - Not all needed binnning exist." << endl;
+        return kFALSE;
+    }
+
+    // =========================== Preparation ==================================
+
+    if (fDisplay)
+        fDisplay->SetTitle(out);
+
+    TStopwatch clock;
+    clock.Start();
+
+    // ------------------ Setup reading --------------------
+    MReadMarsFile read1("Events");
+    MReadMarsFile read2("Events");
+    MReadMarsFile read3("Events");
+    MReadMarsFile  read4("Events");
+    read1.DisableAutoScheme();
+    read2.DisableAutoScheme();
+    read3.DisableAutoScheme();
+    read4.DisableAutoScheme();
+
+    // Setup four reading tasks with the on- and off-data of the two datasets
+    // Training -- On
+    if (!fDataSetOn.AddFilesOn(read1))
+        return kFALSE;
+    // Testing -- On
+    if (!fDataSetOn.AddFilesOff(read4))
+        return kFALSE;
+    // Training -- Off
+    if (!fDataSetOff.AddFilesOn(read3))
+        return kFALSE;
+    // Testing -- Off
+    if (!fDataSetOff.AddFilesOff(read2))
+        return kFALSE;
+
+    // ===============================================================================
+    // ======================           Training             =========================
+    // ===============================================================================
+
+    // ---------------- Setup RF Matrix ----------------
+    MHMatrix train("Train");
+    train.AddColumns(fRules);
+//    if (fEnableWeights[kTrainOn] || fEnableWeights[kTrainOff])
+//        train.AddColumn("MWeight.fVal");
+    train.AddColumn("MHadronness.fVal");
+
+    // ----------------- Prepare filling Matrix RF ------------------
+
+    // Setup the hadronness container identifying gammas and off-data
+    // and setup a container for the weights
+    MParameterD had("MHadronness");
+    MParameterD wgt("MWeight");
+    MParameterD typ("Type");
+
+    // Add them to the parameter list
+    MParList plistx;
+    plistx.AddToList(this); // take care of fDisplay!
+    plistx.AddToList(&had);
+    plistx.AddToList(&wgt);
+    plistx.AddToList(&typ);
+
+    // Setup the tool class to fill the matrix
+    MTFillMatrix fill;
+    fill.SetLogStream(fLog);
+    fill.SetDisplay(fDisplay);
+    fill.AddPreCuts(fPreCuts);
+    fill.AddPreCuts(fTrainCuts);
+
+    // ----------------- Fill on data into matrix ------------------
+
+    // Setup the tool class to read the gammas and read them
+    fill.SetName("FillOn");
+    fill.SetDestMatrix1(&train, fNum[kTrainOn]);
+    fill.SetReader(&read1);
+//    fill.AddPreTasks(fPreTasksSet[kTrainOn]);
+    fill.AddPreTasks(fPreTasks);
+//    fill.AddPostTasks(fPostTasksSet[kTrainOn]);
+    fill.AddPostTasks(fPostTasks);
+
+    // Set classifier for gammas
+    had.SetVal(0);
+    wgt.SetVal(1);
+    typ.SetVal(0);
+
+    // Fill matrix
+    if (!fill.Process(plistx))
+        return kFALSE;
+
+    // Check the number or read events
+    const Int_t numontrn = train.GetNumRows();
+    if (numontrn==0)
+    {
+        *fLog << err << "ERROR - No on-data events available for training... aborting." << endl;
+        return kFALSE;
+    }
+
+    // Remove possible post tasks
+    fill.ClearPreTasks();
+    fill.ClearPostTasks();
+
+    // ----------------- Fill off data into matrix ------------------
+
+    // In case of wobble mode we have to do something special
+    // Setup the tool class to read the background and read them
+    fill.SetName("FillOff");
+    fill.SetDestMatrix1(&train, fNum[kTrainOff]);
+    fill.SetReader(&read3);
+//    fill.AddPreTasks(fPreTasksSet[kTrainOff]);
+    fill.AddPreTasks(fPreTasks);
+//    fill.AddPostTasks(fPostTasksSet[kTrainOff]);
+    fill.AddPostTasks(fPostTasks);
+
+    // Set classifier for background
+    had.SetVal(1);
+    wgt.SetVal(1);
+    typ.SetVal(1);
+
+    // Fiull matrix
+    if (!fill.Process(plistx))
+        return kFALSE;
+
+    // Check the number or read events
+    const Int_t numofftrn = train.GetNumRows()-numontrn;
+    if (numofftrn==0)
+    {
+        *fLog << err << "ERROR - No off-data available for training... aborting." << endl;
+        return kFALSE;
+    }
+
+    // ------------------------ Train RF --------------------------
+
+    MRanForestCalc rf("TrainSeparation", fTitle);
+    rf.SetNumTrees(fNumTrees);
+    rf.SetNdSize(fNdSize);
+    rf.SetNumTry(fNumTry);
+    rf.SetNumObsoleteVariables(1);
+//    rf.SetLastDataColumnHasWeights(fEnableWeights[kTrainOn] || fEnableWeights[kTrainOff]);
+    rf.SetDebug(fDebug>1);
+    rf.SetDisplay(fDisplay);
+    rf.SetLogStream(fLog);
+    rf.SetFileName(out);
+    rf.SetNameOutput("MHadronness");
+
+    // Train the random forest either by classification or regression
+    if (!rf.Train(train, fUseRegression))
+        return kFALSE;
+
+    // ----------------- Print result of training ------------------
+
+    // Output information about what was going on so far.
+    *fLog << all;
+    fLog->Separator("The forest was trained with...");
+
+    *fLog << "Training method:" << endl;
+    *fLog << " * " << (fUseRegression?"regression":"classification") << endl;
+    /*
+    if (fEnableWeights[kTrainOn])
+        *fLog << " * weights for on-data" << endl;
+    if (fEnableWeights[kTrainOff])
+        *fLog << " * weights for off-data" << endl;
+    */
+    *fLog << endl;
+    *fLog << "Events used for training:"   << endl;
+    *fLog << " * Gammas:     " << numontrn  << endl;
+    *fLog << " * Background: " << numofftrn << endl;
+    *fLog << endl;
+    *fLog << "Gamma/Background ratio:" << endl;
+    *fLog << " * Requested:  " << (float)fNum[kTrainOn]/fNum[kTrainOff] << endl;
+    *fLog << " * Result:     " << (float)numontrn/numofftrn << endl;
+    *fLog << endl;
+    *fLog << "Run-Time: " << Form("%.1f", clock.RealTime()/60) << "min (CPU: ";
+    *fLog << Form("%.1f", clock.CpuTime()/60) << "min)" << endl;
+    *fLog << endl;
+    *fLog << "Output file name: " << out << endl;
+
+    // ===============================================================================
+    // ======================           Testing              =========================
+    // ===============================================================================
+    fLog->Separator("Test");
+
+    clock.Continue();
+
+    // ---------------------- Prepare eventloop off-data ---------------------
+
+    // Setup parlist and tasklist for testing
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(this); // Take care of display
+    plist.AddToList(&tlist);
+
+//    MMcEvt mcevt;
+//    plist.AddToList(&mcevt);
+
+    plist.AddToList(&wgt);
+    plist.AddToList(&typ);
+
+    // ----- Setup histograms -----
+    MBinning binsy(50, 0 , 1,      "BinningMH3Y", "lin");
+    MBinning binsx(40, 10, 100000, "BinningMH3X", "log");
+
+    plist.AddToList(&binsx);
+    plist.AddToList(&binsy);
+
+    MH3 h31("MHillas.fSize",  "MHadronness.fVal");
+    MH3 h32("MHillas.fSize",  "MHadronness.fVal");
+    MH3 h40("MMcEvt.fEnergy", "MHadronness.fVal");
+    h31.SetTitle("Background probability vs. Size:Size [phe]:Hadronness h");
+    h32.SetTitle("Background probability vs. Size:Size [phe]:Hadronness h");
+    h40.SetTitle("Background probability vs. Energy:Energy [GeV]:Hadronness h");
+
+    plist.AddToList(&fBinnings);
+
+    MHHadronness hist;
+
+    // ----- Setup tasks -----
+    MFillH fillh0(&hist, "", "FillHadronness");
+    MFillH fillh1(&h31,  "", "FillHadVsSize");
+    MFillH fillh2(&h32,  "", "FillHadVsSize");
+    MFillH fillh4(&h40,  "", "FillHadVsEnergy");
+    fillh0.SetWeight("MWeight");
+    fillh1.SetWeight("MWeight");
+    fillh2.SetWeight("MWeight");
+    fillh4.SetWeight("MWeight");
+    fillh1.SetDrawOption("colz profy");
+    fillh2.SetDrawOption("colz profy");
+    fillh4.SetDrawOption("colz profy");
+    fillh1.SetNameTab("HadSzOff");
+    fillh2.SetNameTab("HadSzOn");
+    fillh4.SetNameTab("HadEnOn");
+    fillh0.SetBit(MFillH::kDoNotDisplay);
+
+    // ----- Setup filter -----
+    MFilterList precuts;
+    precuts.AddToList(fPreCuts);
+    precuts.AddToList(fTestCuts);
+
+    MContinue cont0(&precuts);
+    cont0.SetName("PreCuts");
+    cont0.SetInverted();
+
+    MFEventSelector sel; // FIXME: USING IT (WITH PROB?) in READ will by much faster!!!
+    sel.SetNumSelectEvts(fNum[kTestOff]);
+
+    MContinue contsel(&sel);
+    contsel.SetInverted();
+
+    // ----- Setup tasklist -----
+    tlist.AddToList(&read2);     // Reading task
+    tlist.AddToList(&contsel);   // event selector
+//    tlist.AddToList(fPreTasksSet[kTestOff]);
+    tlist.AddToList(fPreTasks);  // list of pre tasks
+    tlist.AddToList(&cont0);     // list of pre cuts and test cuts
+    tlist.AddToList(&rf);        // evaluate random forest
+//    tlist.AddToList(fPostTasksSet[kTestOff]);
+    tlist.AddToList(fPostTasks); // list of post tasks
+    tlist.AddToList(&fillh1);    // Fill HadSzOff
+
+    TList autodel;
+    autodel.SetOwner();
+
+    TPRegexp regexp("([0-9]:*)+");
+
+    NextH.Reset();
+    while ((o=NextH()))
+    {
+        HistSet1D *hs = static_cast<HistSet1D*>(o);
+
+        // FIXME: Move to beginning of function
+        // Check if needed binning exists
+        if (!hs->CheckBinning(fBinnings))
+            return kFALSE;
+
+        MHn    *hist = hs->GetHistN(fRules);
+        MFillH *fill = new MFillH(hist, "", Form("Fill%s", hist->GetName()));
+
+        fill->SetWeight("MWeight");
+        fill->SetDrawOption("colz");
+        fill->SetNameTab(hist->GetName());
+        fill->SetBit(MFillH::kDoNotDisplay);
+
+        tlist.AddToList(fill);
+
+        autodel.Add(fill);
+        autodel.Add(hist);
+    }
+    tlist.AddToList(&fillh0);      // Fill MHHadronness (not displayed in first loop)
+    tlist.AddToList(&fTestTasks);  // list of test tasks
+
+    // Enable Acceleration
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    // ---------------------- Run eventloop on background ---------------------
+    MEvtLoop loop;
+    loop.SetDisplay(fDisplay);
+    loop.SetLogStream(fLog);
+    loop.SetParList(&plist);
+    //if (!SetupEnv(loop))
+    //   return kFALSE;
+
+    wgt.SetVal(1);
+    typ.SetVal(0);
+    if (!loop.Eventloop())
+        return kFALSE;
+
+    // ---------------------- Prepare eventloop on-data ---------------------
+
+    sel.SetNumSelectEvts(fNum[kTestOn]);      // set number of target events
+
+    fillh0.ResetBit(MFillH::kDoNotDisplay);   // Switch on display MHHadronness
+
+    TIter NextF(&autodel);
+    while ((o=NextF()))
+    {
+        MFillH *fill = dynamic_cast<MFillH*>(o);
+        if (fill)
+            fill->ResetBit(MFillH::kDoNotDisplay);
+    }
+
+    // Remove PreTasksOff and PostTasksOff from the list
+//    tlist.RemoveFromList(fPreTasksSet[kTestOff]);
+//    tlist.RemoveFromList(fPostTasksSet[kTestOff]);
+
+    tlist.Replace(&read4);                   // replace reading off-data by on-data
+
+    // Add the PreTasksOn directly after the reading task
+//    tlist.AddToListAfter(fPreTasksSet[kTestOn], &c1);
+
+    // Add the PostTasksOn after rf
+//    tlist.AddToListAfter(fPostTasksSet[kTestOn], &rf);
+
+    tlist.Replace(&fillh2);                  // Fill HadSzOn instead of HadSzOff
+    tlist.AddToListAfter(&fillh4, &fillh0);  // Filling of HadEnOn
+
+    // Enable Acceleration
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    // ---------------------- Run eventloop on-data ---------------------
+
+    wgt.SetVal(1);
+    typ.SetVal(1);
+    if (!loop.Eventloop())
+        return kFALSE;
+
+    // ---------------------- Print/Display result ---------------------
+
+    // Show what was going on in the testing
+    const Double_t numontst  = h32.GetHist().GetEntries();
+    const Double_t numofftst = h31.GetHist().GetEntries();
+
+    *fLog << all;
+    fLog->Separator("The forest was tested with...");
+    *fLog << "Test method:" << endl;
+    *fLog << " * Random Forest: " << out << endl;
+    /*
+    if (fEnableWeights[kTestOn])
+        *fLog << " * weights for on-data" << endl;
+    if (fEnableWeights[kTestOff])
+        *fLog << " * weights for off-data" << endl;
+    */
+    *fLog << endl;
+    *fLog << "Events used for test:"   << endl;
+    *fLog << " * Gammas:     " << numontst   << endl;
+    *fLog << " * Background: " << numofftst << endl;
+    *fLog << endl;
+    *fLog << "Gamma/Background ratio:" << endl;
+    *fLog << " * Requested:  " << (float)fNum[kTestOn]/fNum[kTestOff] << endl;
+    *fLog << " * Result:     " << (float)numontst/numofftst << endl;
+    *fLog << endl;
+
+    // Display the result plots
+    DisplayResult(h31, h32, -1);
+    //DisplayResult(h31, h32, ontime);
+
+    *fLog << "Total Run-Time: " << Form("%.1f", clock.RealTime()/60) << "min (CPU: ";
+    *fLog << Form("%.1f", clock.CpuTime()/60) << "min)" << endl;
+    fLog->Separator();
+
+    // ----------------- Write result ------------------
+
+    fDataSetOn.SetName("DataSetOn");
+    fDataSetOff.SetName("DataSetOff");
+
+    // Write the display
+    TObjArray arr;
+    arr.Add(const_cast<MDataSet*>(&fDataSetOn));
+    arr.Add(const_cast<MDataSet*>(&fDataSetOff));
+    if (fDisplay)
+        arr.Add(fDisplay);
+
+    SetPathOut(out);
+    return WriteContainer(arr, 0, "UPDATE");
+}
+
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainCuts.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainCuts.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainCuts.h	(revision 17960)
@@ -0,0 +1,117 @@
+#ifndef MARS_MJTrainCuts
+#define MARS_MJTrainCuts
+
+#ifndef MARS_MJTrainRanForest
+#include "MJTrainRanForest.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef MARS_MDataSet
+#include "MDataSet.h"
+#endif
+
+class MH3;
+class MBinning;
+
+class MJTrainCuts : public MJTrainRanForest
+{
+public:
+    enum Type_t { kTrainOn, kTrainOff, kTestOn, kTestOff };
+
+private:
+    MDataSet fDataSetOn;
+    MDataSet fDataSetOff;
+
+    UInt_t fNum[4];
+/*
+    TList fPreTasksSet[4];
+    TList fPostTasksSet[4];
+
+    Bool_t fEnableWeights[4];
+*/
+    Bool_t fUseRegression;
+
+    TList     fHists;
+    TObjArray fBinnings;
+
+    // Result
+    void DisplayResult(MH3 &h31, MH3 &h32, Float_t ontime);
+
+public:
+    MJTrainCuts() :  fUseRegression(kFALSE)
+    {
+        for (int i=0; i<4; i++)
+        {
+            //fEnableWeights[i]=kFALSE;
+            fNum[i] = (UInt_t)-1;
+        }
+
+        fHists.SetOwner();
+        fBinnings.SetOwner();
+    }
+
+    void SetDataSetOn(const MDataSet &ds, UInt_t ntrain=(UInt_t)-1, UInt_t ntest=(UInt_t)-1)
+    {
+        ds.Copy(fDataSetOn);
+
+        fDataSetOn.SetNumAnalysis(1);
+
+        fNum[kTestOn]  = ntrain;
+        fNum[kTrainOn] = ntest;
+    }
+    void SetDataSetOff(const MDataSet &ds, UInt_t ntrain=(UInt_t)-1, UInt_t ntest=(UInt_t)-1)
+    {
+        ds.Copy(fDataSetOff);
+
+        fDataSetOff.SetNumAnalysis(2);
+
+        fNum[kTestOff]  = ntrain;
+        fNum[kTrainOff] = ntest;
+    }
+
+    // Add Histogram
+    void AddHist(UInt_t nx);
+    void AddHist(UInt_t nx, UInt_t ny);
+    void AddHist(UInt_t nx, UInt_t ny, UInt_t nz);
+
+    void AddBinning(UInt_t n, const MBinning &bins);
+    //void AddBinning(const MBinning &bins);
+
+    // Standard user interface
+/*
+    void SetWeights(Type_t typ, const char *rule)  { if (fEnableWeights[typ]) return; fEnableWeights[typ]=kTRUE; AddPostTask(typ, rule); }
+    void SetWeights(Type_t typ, MTask *t)          { if (fEnableWeights[typ]) return; fEnableWeights[typ]=kTRUE; AddPostTask(typ, t); }
+
+    void AddPreTaskOn(MTask *t)                                       { AddPreTask(kTrainOn, t); AddPreTask(kTestOn, t); }
+    void AddPreTaskOn(const char *rule, const char *name="MWeight")   { AddPreTask(kTrainOn, rule, name); AddPreTask(kTestOn, rule, name); }
+    void AddPreTaskOff(MTask *t)                                      { AddPreTask(kTrainOff, t); AddPreTask(kTestOff, t); }
+    void AddPreTaskOff(const char *rule, const char *name="MWeight")  { AddPreTask(kTrainOff, rule, name); AddPreTask(kTestOff, rule, name); }
+
+    void AddPostTaskOn(MTask *t)                                      { AddPostTask(kTrainOn, t); AddPostTask(kTestOn, t); }
+    void AddPostTaskOn(const char *rule, const char *name="MWeight")  { AddPostTask(kTrainOn, rule, name); AddPostTask(kTestOn, rule, name); }
+    void AddPostTaskOff(MTask *t)                                     { AddPostTask(kTrainOff, t); AddPostTask(kTestOff, t); }
+    void AddPostTaskOff(const char *rule, const char *name="MWeight") { AddPostTask(kTrainOff, rule, name); AddPostTask(kTestOff, rule, name); }
+
+    void AddPreTask(Type_t typ, MTask *t)                                      { Add(fPreTasksSet[typ],  t); }
+    void AddPreTask(Type_t typ, const char *rule, const char *name="MWeight")  { AddPar(fPreTasksSet[typ], rule, name); }
+    void AddPostTask(Type_t typ, MTask *t)                                     { Add(fPostTasksSet[typ],  t); }
+    void AddPostTask(Type_t typ, const char *rule, const char *name="MWeight") { AddPar(fPostTasksSet[typ], rule, name); }
+
+    void SetWeightsOn(const char *rule)  { SetWeights(kTrainOn, rule);  SetWeights(kTestOn, rule); }
+    void SetWeightsOn(MTask *t)          { SetWeights(kTrainOn, t);     SetWeights(kTestOn, t); }
+    void SetWeightsOff(const char *rule) { SetWeights(kTrainOff, rule); SetWeights(kTestOff, rule); }
+    void SetWeightsOff(MTask *t)         { SetWeights(kTrainOff, t);    SetWeights(kTestOff, t); }
+*/
+    void EnableRegression(Bool_t b=kTRUE)     { fUseRegression =  b; }
+    void EnableClassification(Bool_t b=kTRUE) { fUseRegression = !b; }
+
+    // Main function to start processing
+    Bool_t Process(const char *out);
+
+    ClassDef(MJTrainCuts, 0)//Class to help finding cuts using the random forest
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainDisp.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainDisp.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainDisp.cc	(revision 17960)
@@ -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 11/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2005-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJTrainDisp
+//
+//
+// Example:
+// --------
+//
+//    // SequencesOn are used for training, SequencesOff for Testing
+//    MDataSet set("mctesttrain.txt");
+//    set.SetNumAnalysis(1);  // Must have a number
+//    MJTrainDisp opt;
+//    //opt.SetDebug();
+//    opt.AddParameter("MHillas.fLength");
+//    opt.AddParameter("MHillas.fWidth");
+//    MStatusDisplay *d = new MStatusDisplay;
+//    opt.SetDisplay(d);
+//    opt.AddPreCut("MHillasSrc.fDCA*MGeomCam.fConvMm2Deg<0.3");
+//    opt.Train("rf-disp.root", set, 30000); // Number of train events
+//
+//    // Two of the displayed histograms show the cut efficiency for
+//    // a given Theta-Cut. The default is 0.215. It can be overwritten
+//    // by
+//    opt.SetThetaCut(0.165);
+//
+//
+// Random Numbers:
+// ---------------
+//   Use:
+//         if(gRandom)
+//             delete gRandom;
+//         gRandom = new TRandom3();
+//   in advance to change the random number generator.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MJTrainDisp.h"
+
+#include <TH2.h>
+#include <TLine.h>
+#include <TCanvas.h>
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+// tools
+#include "MDataSet.h"
+#include "MTFillMatrix.h"
+#include "MChisqEval.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// tasks
+#include "MReadMarsFile.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MRanForestCalc.h"
+#include "MParameterCalc.h"
+
+// container
+#include "MParameters.h"
+
+// histograms
+#include "MBinning.h"
+#include "MH3.h"
+#include "MHn.h"
+#include "MHThetaSq.h"
+
+// filter
+#include "MFilterList.h"
+
+ClassImp(MJTrainDisp);
+
+using namespace std;
+
+const TString MJTrainDisp::fgTrainParameter = "MHillasSrc.fDist*MGeomCam.fConvMm2Deg";
+
+// --------------------------------------------------------------------------
+//
+// Display a result histogram either vs. size or energy
+// FIXME: Could be moved into a new histogram class.
+//
+void MJTrainDisp::DisplayHist(TCanvas &c, Int_t i, MH3 &mh3) const
+{
+    MH::SetPalette("pretty");
+
+    TH2 &hist = *static_cast<TH2*>(mh3.GetHist().Clone());
+    hist.SetBit(TH1::kNoStats);
+    hist.SetDirectory(0);
+
+    TLine line;
+    line.SetLineStyle(kDashed);
+    line.SetLineWidth(1);
+
+    c.cd(i+4);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    //gPad->SetFillColor(kWhite);
+    gPad->SetLogx();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    //gPad->SetLeftMargin(0.12);
+    //gPad->SetRightMargin(0.12);
+
+    const Int_t bin = 3;
+    const Float_t cutval = hist.GetYaxis()->GetBinUpEdge(bin);
+
+    TH1D heff;
+    heff.SetName(Form("Eff%s", hist.GetName()));
+    heff.SetTitle(Form("Cut efficiency vs. %s for \\vartheta<%.3f", hist.GetName(), TMath::Sqrt(cutval)));
+    heff.SetDirectory(0);
+    heff.SetXTitle(hist.GetXaxis()->GetTitle());
+    heff.SetYTitle("Efficiency");
+
+    MH::SetBinning(heff, hist);
+
+    for (int x=0; x<=hist.GetNbinsX()+1; x++)
+    {
+        const Double_t n0 = hist.Integral(x, x, -1, -1);
+        if (n0>0)
+            heff.SetBinContent(x, hist.Integral(x, x, -1, bin)/n0);
+    }
+
+    heff.SetMinimum(0);
+    heff.SetMaximum(1);
+    heff.DrawCopy();
+
+    line.DrawLine(hist.GetXaxis()->GetXmin(), 0.5,
+                  hist.GetXaxis()->GetXmax(), 0.5);
+
+    c.cd(i+0);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    //gPad->SetFillColor(kWhite);
+    gPad->SetLogx();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    //gPad->SetLeftMargin(0.12);
+    //gPad->SetRightMargin(0.12);
+
+    for (int x=0; x<=hist.GetNbinsX(); x++)
+    {
+        const Float_t n = hist.GetBinContent(1); // + hist.GetBinContent(2)
+        if (n==0)
+            continue;
+
+        for (int y=0; y<=hist.GetNbinsY(); y++)
+            hist.SetBinContent(x, y, 100*hist.GetBinContent(x,y)/n);
+    }
+
+    hist.SetMaximum(100);
+    hist.DrawCopy("colz");
+
+    line.DrawLine(hist.GetXaxis()->GetXmin(), cutval,
+                  hist.GetXaxis()->GetXmax(), cutval);
+
+    c.cd(i+2);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    //gPad->SetFillColor(kWhite);
+    gPad->SetLogx();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    //gPad->SetLeftMargin(0.12);
+    //gPad->SetRightMargin(0.12);
+
+    for (int x=0; x<=hist.GetNbinsX(); x++)
+    {
+        const Float_t n = hist.Integral(x, x, -1, 9999);
+        if (n==0)
+            continue;
+
+        for (int y=0; y<=hist.GetNbinsY(); y++)
+            hist.SetBinContent(x, y, 100*hist.GetBinContent(x,y)/n);
+    }
+
+    hist.SetMaximum(25);
+    hist.DrawCopy("colz");
+
+    line.DrawLine(hist.GetXaxis()->GetXmin(), cutval,
+                  hist.GetXaxis()->GetXmax(), cutval);
+}
+
+// --------------------------------------------------------------------------
+//
+// Display the result histograms in a new tab.
+//
+void MJTrainDisp::DisplayResult(MH3 &hsize, MH3 &henergy)
+{
+    TCanvas &c = fDisplay->AddTab("Disp");
+    c.Divide(2,3);
+
+    DisplayHist(c, 1, hsize);
+    DisplayHist(c, 2, henergy);
+}
+
+// --------------------------------------------------------------------------
+//
+// Run Disp optimization
+//
+Bool_t MJTrainDisp::Train(const char *out, const MDataSet &set, Int_t num)
+{
+    SetTitle(Form("Train%s: %s", fNameOutput.Data(), out));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    if (!set.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(out))
+        return kFALSE;
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+
+    // --------------------- Setup files --------------------
+    MReadMarsFile readtrn("Events");
+    MReadMarsFile readtst("Events");
+    readtrn.DisableAutoScheme();
+    readtst.DisableAutoScheme();
+
+    if (!set.AddFilesOn(readtrn))
+    {
+        *fLog << err << "ERROR - Adding SequencesOn." << endl;
+        return kFALSE;
+    }
+    if (!set.AddFilesOff(readtst))
+    {
+        *fLog << err << "ERROR - Adding SequencesOff." << endl;
+        return kFALSE;
+    }
+
+    // ----------------------- Setup Matrix ------------------
+    MHMatrix train("Train");
+    train.AddColumns(fRules);
+    if (fEnableWeights)
+        train.AddColumn("MWeight.fVal");
+    train.AddColumn(fTrainParameter);
+
+    // ----------------------- Fill Matrix RF ----------------------
+    MTFillMatrix fill(fTitle);
+    fill.SetDisplay(fDisplay);
+    fill.SetLogStream(fLog);
+    fill.SetDestMatrix1(&train, num);
+    fill.SetReader(&readtrn);
+    fill.AddPreCuts(fPreCuts);
+    fill.AddPreCuts(fTrainCuts);
+    fill.AddPreTasks(fPreTasks);
+    fill.AddPostTasks(fPostTasks);
+    if (!fill.Process())
+        return kFALSE;
+
+    // ------------------------ Train RF --------------------------
+    MRanForestCalc rf("Train", fTitle);
+    rf.SetNumTrees(fNumTrees);
+    rf.SetNdSize(fNdSize);
+    rf.SetNumTry(fNumTry);
+    rf.SetNumObsoleteVariables(1);
+    rf.SetLastDataColumnHasWeights(fEnableWeights);
+    rf.SetDisplay(fDisplay);
+    rf.SetLogStream(fLog);
+    rf.SetFileName(out);
+    rf.SetDebug(fDebug>1);
+    rf.SetNameOutput(fNameOutput);
+    rf.SetFunction(fResultFunction);
+
+    /*
+    MBinning b(32, 10, 100000, "BinningEnergyEst", "log");
+
+    if (!rf.TrainMultiRF(train, b.GetEdgesD()))    // classification with one tree per bin
+        return;
+
+    if (!rf.TrainSingleRF(train, b.GetEdgesD()))   // classification into different bins
+        return;
+    */
+    if (!rf.TrainRegression(train))                  // regression (best choice)
+        return kFALSE;
+
+    // --------------------- Display result ----------------------
+
+    gLog.Separator("Test");
+
+    MH::SetPalette("pretty");
+
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(this);
+    plist.AddToList(&tlist);
+    //plist.AddToList(&b);
+
+    MParameterD par("ThetaSquaredCut");
+    par.SetVal(fThetaCut*fThetaCut);
+    plist.AddToList(&par);
+
+    MAlphaFitter fit;
+    fit.SetPolynomOrder(0);
+    fit.SetSignalFitMax(0.8);
+    fit.EnableBackgroundFit(kFALSE);
+    fit.SetSignalFunction(MAlphaFitter::kThetaSq);
+    fit.SetMinimizationStrategy(MAlphaFitter::kGaussSigma);
+    plist.AddToList(&fit);
+
+    MFilterList list;
+    if (!list.AddToList(fPreCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
+    if (!list.AddToList(fTestCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fTestCuts failed!" << endl;
+
+    MContinue cont(&list);
+    cont.SetInverted();
+
+    const char *rule = "(MHillasSrc.fDist*MGeomCam.fConvMm2Deg)^2 + (Disp.fVal)^2 - (2*MHillasSrc.fDist*MGeomCam.fConvMm2Deg*Disp.fVal*cos(MHillasSrc.fAlpha*kDeg2Rad))";
+
+    MParameterCalc calcthetasq(rule, "MThetaSqCalc");
+    calcthetasq.SetNameParameter("ThetaSquared");
+
+    MChisqEval eval;
+    eval.SetY1("sqrt(ThetaSquared.fVal)");
+
+    // ----------- Setup binnings ----------------
+    MBinning binsS(50,  10,    100000, "BinningSize",         "log");
+    MBinning binsE(70,  10,    31623,  "BinningEnergy",       "log");
+    MBinning binsG(50, -10,    10,     "BinningSlope",        "lin");
+    MBinning binsX(50, -1,     1,      "BinningResidualDist", "lin");
+    MBinning binsL(50,  0,     0.3,    "BinningLeakage",      "lin");
+    MBinning binsT(51, -0.005, 0.505,  "BinningTheta",        "asin");
+    MBinning binsC(50,  1e-2,  1,      "BinningConc",         "log");
+    MBinning binsW(50,  0,     0.5,    "BinningLength",       "lin");
+    MBinning binsM(50,  0,     0.3,    "BinningWidth",        "lin");
+    MBinning binsV(75,  0, par.GetVal()*25, "BinningThetaSq", "lin");
+
+    plist.AddToList(&binsG);
+    plist.AddToList(&binsS);
+    plist.AddToList(&binsX);
+    plist.AddToList(&binsE);
+    plist.AddToList(&binsL);
+    plist.AddToList(&binsT);
+    plist.AddToList(&binsC);
+    plist.AddToList(&binsV);
+    plist.AddToList(&binsW);
+    plist.AddToList(&binsM);
+
+    // ----------- Setup some histograms ----------------
+
+    MHThetaSq hist;
+    hist.SkipHistTime();
+    hist.SkipHistTheta();
+    hist.SkipHistEnergy();
+
+    // To speed it up we could precalculate it.
+    const char *res = "Disp.fVal-MHillasSrc.fDist*MGeomCam.fConvMm2Deg";
+
+    MHn hres1("Disp1", "Xi Residual (Dist/Disp)");
+    hres1.AddHist("MHillas.fSize", res);
+    hres1.InitName("ResSize;Size;ResidualDist");
+    hres1.InitTitle(";S [phe];Disp-Dist [\\circ];");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg", res);
+    hres1.InitName("ResSlope;Slope;ResidualDist");
+    hres1.InitTitle(";Slope;Disp-Dist [\\circ];");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MNewImagePar.fLeakage1", res);
+    hres1.InitName("ResLeak;Leakage;ResidualDist");
+    hres1.InitTitle(";Leak;Disp-Dist [\\circ];");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MPointingPos.fZd", res);
+    hres1.InitName("ResTheta;Theta;ResidualDist");
+    hres1.InitTitle(";Zd [\\circ];Disp-Dist [\\circ];");
+    hres1.SetDrawOption("colz profx");
+
+    MHn hres2("Disp2", "Dist Residual (Disp-Dist)");
+    hres2.AddHist("MHillas.fLength*MGeomCam.fConvMm2Deg", res);
+    hres2.InitName("ResLength;Length;ResidualDist");
+    hres2.InitTitle(";L [\\circ];Disp-Dist [\\circ];");
+    hres2.SetDrawOption("colz profx");
+    hres2.AddHist("MNewImagePar.fConc1", res);
+    hres2.InitName("ResConc1;Conc;ResidualDist");
+    hres2.InitTitle(";C;Disp-Dist [\\circ];");
+    hres2.SetDrawOption("colz profx");
+    hres2.AddHist("MHillas.fWidth*MGeomCam.fConvMm2Deg", res);
+    hres2.InitName("ResWidth;Width;ResidualDist");
+    hres2.InitTitle(";W [\\circ];Disp-Dist [\\circ];");
+    hres2.SetDrawOption("colz profx");
+    hres2.AddHist("MMcEvt.fEnergy", res);
+    hres2.InitName("ResEmc;Energy;ResidualDist");
+    hres2.InitTitle(";E_{mc} [GeV];Disp-Dist [\\circ];");
+    hres2.SetDrawOption("colz profx");
+
+    MH3 hdisp1("MHillas.fSize",  "ThetaSquared.fVal");
+    MH3 hdisp2("MMcEvt.fEnergy", "ThetaSquared.fVal");
+    hdisp1.SetName("Size;Size;ThetaSq");
+    hdisp2.SetName("Energy;Energy;ThetaSq");
+    hdisp1.SetTitle("\\vartheta distribution vs. Size:Size [phe]:\\vartheta^2 [\\circ]");
+    hdisp2.SetTitle("\\vartheta distribution vs. Energy:Energy [GeV]:\\vartheta^2 [\\circ]");
+
+    // -------------- Setup fill tasks ----------------
+
+    MFillH fillh(&hist, "", "FillThetaSq");
+    MFillH fillh2a(&hres1, "", "FillResiduals1");
+    MFillH fillh2b(&hres2, "", "FillResiduals2");
+    MFillH fillh2c(&hdisp1, "", "FillSize");
+    MFillH fillh2d(&hdisp2, "", "FillEnergy");
+    fillh2c.SetBit(MFillH::kDoNotDisplay);
+    fillh2d.SetBit(MFillH::kDoNotDisplay);
+
+    // --------------- Setup weighting -------------------
+
+    if (fEnableWeights)
+    {
+        fillh.SetWeight();
+        fillh2a.SetWeight();
+        fillh2b.SetWeight();
+        fillh2c.SetWeight();
+        fillh2d.SetWeight();
+        eval.SetNameWeight();
+    }
+
+    // --------------- Setup tasklist -------------------
+
+    tlist.AddToList(&readtst);
+    tlist.AddToList(fPreTasks);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&rf);
+    tlist.AddToList(&calcthetasq);
+    tlist.AddToList(fPostTasks);
+    tlist.AddToList(&fillh);
+    tlist.AddToList(&fillh2a);
+    tlist.AddToList(&fillh2b);
+    tlist.AddToList(&fillh2c);
+    tlist.AddToList(&fillh2d);
+    tlist.AddToList(fTestTasks);
+    tlist.AddToList(&eval);
+
+    // ------------- Setup/run eventloop -----------------
+
+    MEvtLoop loop(fTitle);
+    loop.SetLogStream(fLog);
+    loop.SetDisplay(fDisplay);
+    loop.SetParList(&plist);
+    //if (!SetupEnv(loop))
+    //    return kFALSE;
+
+    if (!loop.Eventloop())
+        return kFALSE;
+
+    // ---------------- Prepare result -------------------
+
+    // Print the result
+    *fLog << inf;
+    *fLog << "Rule: " << rule << endl;
+    *fLog << "Disp: " << fTrainParameter << endl;
+    hist.GetAlphaFitter().Print("result");
+
+    // The user has closed the display
+    if (!fDisplay)
+        return kTRUE;
+
+    DisplayResult(hdisp1, hdisp2);
+
+    TObjArray arr;
+    arr.Add(const_cast<MDataSet*>(&set));
+    if (fDisplay)
+        arr.Add(fDisplay);
+
+    SetPathOut(out);
+    return WriteContainer(arr, 0, "UPDATE");
+}
+
+/*
+#include "MParameterCalc.h"
+#include "MHillasCalc.h"
+#include "../mpointing/MSrcPosRndm.h"
+
+Bool_t MJTrainDisp::TrainGhostbuster(const char *out, const MDataSet &set, Int_t num)
+{
+    SetTitle(Form("TrainGhostbuster: %s", out));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    if (!set.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(out))
+        return kFALSE;
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+
+    // --------------------- Setup files --------------------
+    MReadMarsFile readtrn("Events");
+    MReadMarsFile readtst("Events");
+    readtrn.DisableAutoScheme();
+    readtst.DisableAutoScheme();
+
+    if (!set.AddFilesOn(readtrn))
+        return kFALSE;
+    if (!set.AddFilesOff(readtst))
+        return kFALSE;
+
+    // ----------------------- Setup Matrix ------------------
+    MHMatrix train("Train");
+    train.AddColumns(fRules);
+    if (fEnableWeights)
+        train.AddColumn("MWeight.fVal");
+    train.AddColumn("sign(MHillasSrc.fCosDeltaAlpha)==sign(SignStore.fVal)");
+
+    MParameterCalc calc("MHillasSrc.fCosDeltaAlpha", "SignStore");
+    calc.SetNameParameter("SignStore");
+
+    MSrcPosRndm rndm;
+    rndm.SetRule(fTrainParameter);
+    //rndm.SetDistOfSource(120*3.37e-3);
+
+    MHillasCalc hcalc;
+    hcalc.SetFlags(MHillasCalc::kCalcHillasSrc);
+
+    // ----------------------- Fill Matrix RF ----------------------
+    MTFillMatrix fill(fTitle);
+    fill.SetDisplay(fDisplay);
+    fill.SetLogStream(fLog);
+    fill.SetDestMatrix1(&train, num);
+    fill.SetReader(&readtrn);
+    fill.AddPreCuts(fPreCuts);
+    fill.AddPreCuts(fTrainCuts);
+    fill.AddPreTasks(fPreTasks);
+    fill.AddPostTasks(fPostTasks);
+    fill.AddPostTask(&calc);
+    fill.AddPostTask(&rndm);
+    fill.AddPostTask(&hcalc);
+    if (!fill.Process())
+        return kFALSE;
+
+    // ------------------------ Train RF --------------------------
+    MRanForestCalc rf("TrainGhostbuster", fTitle);
+    rf.SetNumTrees(fNumTrees);
+    rf.SetNdSize(fNdSize);
+    rf.SetNumTry(fNumTry);
+    rf.SetNumObsoleteVariables(1);
+    rf.SetLastDataColumnHasWeights(fEnableWeights);
+    rf.SetDisplay(fDisplay);
+    rf.SetLogStream(fLog);
+    rf.SetFileName(out);
+    rf.SetDebug(fDebug>1);
+    rf.SetNameOutput("Sign");
+
+    if (!rf.TrainRegression(train))                  // regression (best choice)
+        return kFALSE;
+
+    // --------------------- Display result ----------------------
+
+    gLog.Separator("Test");
+
+    MH::SetPalette("pretty");
+
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(this);
+    plist.AddToList(&tlist);
+    //plist.AddToList(&b);
+
+    MFilterList list;
+    if (!list.AddToList(fPreCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
+    if (!list.AddToList(fTestCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fTestCuts failed!" << endl;
+
+    MContinue cont(&list);
+    cont.SetInverted();
+
+    const char *rule = "abs(Sign.fVal-(sign(MHillasSrc.fCosDeltaAlpha)==sign(SignStore.fVal)))";
+
+    //MChisqEval eval;
+    //eval.SetY1("sqrt(ThetaSquared.fVal)");
+
+    MH3 hsign1("MHillas.fSize",  rule);
+    MH3 hsign2("MMcEvt.fEnergy", rule);
+    hsign1.SetTitle("Was ist das? vs. Size:Size [phe]:XXX");
+    hsign2.SetTitle("Was ist das? vs. Energy:Enerhy [GeV]:XXXX");
+
+    MBinning binsx( 70, 10, 31623, "BinningMH3X", "log");
+    MBinning binsy( 51,  0,     1, "BinningMH3Y", "lin");
+
+    plist.AddToList(&binsx);
+    plist.AddToList(&binsy);
+
+    MFillH fillh2a(&hsign1, "", "FillSize");
+    MFillH fillh2b(&hsign2, "", "FillEnergy");
+    fillh2a.SetDrawOption("profx colz");
+    fillh2b.SetDrawOption("profx colz");
+    fillh2a.SetNameTab("Size");
+    fillh2b.SetNameTab("Energy");
+
+    tlist.AddToList(&readtst);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&calc);
+    tlist.AddToList(&rndm);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&rf);
+    tlist.AddToList(&fillh2a);
+    tlist.AddToList(&fillh2b);
+    //tlist.AddToList(&eval);
+
+    MEvtLoop loop(fTitle);
+    loop.SetLogStream(fLog);
+    loop.SetDisplay(fDisplay);
+    loop.SetParList(&plist);
+    //if (!SetupEnv(loop))
+    //    return kFALSE;
+
+    if (!loop.Eventloop())
+        return kFALSE;
+
+    // Print the result
+    *fLog << inf << "Rule: " << rule << endl;
+
+    //DisplayResult(hdisp1, hdisp2);
+
+    SetPathOut(out);
+    if (!WriteDisplay(0, "UPDATE"))
+        return kFALSE;
+
+    return kTRUE;
+}
+*/
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainDisp.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainDisp.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainDisp.h	(revision 17960)
@@ -0,0 +1,46 @@
+#ifndef MARS_MJTrainDisp
+#define MARS_MJTrainDisp
+
+#ifndef MARS_MJTrainRanForest
+#include "MJTrainRanForest.h"
+#endif
+
+class TCanvas;
+
+class MH3;
+class MDataSet;
+
+class MJTrainDisp : public MJTrainRanForest
+{
+private:
+    static const TString fgTrainParameter;
+
+    TString fTrainParameter;
+    TString fResultFunction;
+
+    Float_t fThetaCut;
+
+    // To be moved to a base class
+    TString fNameOutput;
+
+    void DisplayHist(TCanvas &c, Int_t i, MH3 &mh3) const;
+    void DisplayResult(MH3 &hsize, MH3 &henergy);
+
+public:
+    MJTrainDisp() : fTrainParameter(fgTrainParameter), fResultFunction("x"), fThetaCut(0.215), fNameOutput("Disp") { }
+
+    void SetTrainFunc(const char *par, const char *res="x")
+    {
+        fTrainParameter = par;
+        fResultFunction = res;
+    }
+
+    void SetThetaCut(Float_t cut=0.215) { fThetaCut=cut; }
+
+    Bool_t Train(const char *out, const MDataSet &set, Int_t num);
+    //Bool_t TrainGhostbuster(const char *out, const MDataSet &set, Int_t num);
+
+    ClassDef(MJTrainDisp, 0)//Class to train Random Forest disp estimator
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainEnergy.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainEnergy.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainEnergy.cc	(revision 17960)
@@ -0,0 +1,325 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 11/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJTrainEnergy
+//
+//
+// Example:
+// --------
+//
+//    // SequencesOn are used for training, SequencesOff for Testing
+//    MDataSet set("mctesttrain.txt");
+//    set.SetNumAnalysis(1);  // Must have a number
+//    MJTrainEnergy opt;
+//    //opt.SetDebug();
+//    opt.AddParameter("MHillas.fSize");
+//    opt.AddParameter("MHillasSrc.fDist");
+//    MStatusDisplay *d = new MStatusDisplay;
+//    opt.SetDisplay(d);
+//    opt.AddPreCut("MHillasSrc.fDCA*MGeomCam.fConvMm2Deg<0.3");
+//    opt.Train("rf-energy.root", set, 30000); // Number of train events
+//
+// Random Numbers:
+// ---------------
+//   Use:
+//         if(gRandom)
+//             delete gRandom;
+//         gRandom = new TRandom3();
+//   in advance to change the random number generator.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MJTrainEnergy.h"
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+// tools
+#include "MDataSet.h"
+#include "MTFillMatrix.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// tasks
+#include "MReadMarsFile.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MRanForestCalc.h"
+
+// histograms
+#include "MHn.h"
+#include "MBinning.h"
+#include "MHEnergyEst.h"
+
+// filter
+#include "MFilterList.h"
+
+ClassImp(MJTrainEnergy);
+
+using namespace std;
+
+Bool_t MJTrainEnergy::Train(const char *out, const MDataSet &set, Int_t num)
+{
+    SetTitle(Form("Train%s: %s", fNameOutput.Data(), out));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    if (!set.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(out))
+        return kFALSE;
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+
+    // --------------------- Setup files --------------------
+    MReadMarsFile readtrn("Events");
+    MReadMarsFile readtst("Events");
+    readtrn.DisableAutoScheme();
+    readtst.DisableAutoScheme();
+
+    if (!set.AddFilesOn(readtrn))
+    {
+        *fLog << err << "ERROR - Adding SequencesOn." << endl;
+        return kFALSE;
+    }
+    if (!set.AddFilesOff(readtst))
+    {
+        *fLog << err << "ERROR - Adding SequencesOff." << endl;
+        return kFALSE;
+    }
+
+    // ----------------------- Setup Matrix ------------------
+    MHMatrix train("Train");
+    train.AddColumns(fRules);
+    if (fEnableWeights)
+        train.AddColumn("MWeight.fVal");
+    train.AddColumn(fTrainParameter);
+
+    // ----------------------- Fill Matrix RF ----------------------
+    MTFillMatrix fill(fTitle);
+    fill.SetDisplay(fDisplay);
+    fill.SetLogStream(fLog);
+    fill.SetDestMatrix1(&train, num);
+    fill.SetReader(&readtrn);
+    fill.AddPreCuts(fPreCuts);
+    fill.AddPreCuts(fTrainCuts);
+    fill.AddPreTasks(fPreTasks);
+    fill.AddPostTasks(fPostTasks);
+    if (!fill.Process())
+        return kFALSE;
+
+    // ------------------------ Train RF --------------------------
+    MRanForestCalc rf("Train", fTitle);
+    rf.SetNumTrees(fNumTrees);
+    rf.SetNdSize(fNdSize);
+    rf.SetNumTry(fNumTry);
+    rf.SetNumObsoleteVariables(1);
+    rf.SetLastDataColumnHasWeights(fEnableWeights);
+    rf.SetDisplay(fDisplay);
+    rf.SetLogStream(fLog);
+    rf.SetFileName(out);
+    rf.SetDebug(fDebug>1);
+    rf.SetNameOutput(fNameOutput);
+    rf.SetFunction(fResultFunction);
+
+    /*
+    MBinning b(32, 10, 100000, "BinningEnergyEst", "log");
+
+    if (!rf.TrainMultiRF(train, b.GetEdgesD()))    // classification with one tree per bin
+        return;
+
+    if (!rf.TrainSingleRF(train, b.GetEdgesD()))   // classification into different bins
+        return;
+    */
+    if (!rf.TrainRegression(train))                  // regression (best choice)
+        return kFALSE;
+
+    // --------------------- Display result ----------------------
+
+    gLog.Separator("Test");
+
+    MH::SetPalette("pretty");
+
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(this);
+    plist.AddToList(&tlist);
+    //plist.AddToList(&b);
+
+    MFilterList list;
+    if (!list.AddToList(fPreCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
+    if (!list.AddToList(fTestCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fTestCuts failed!" << endl;
+
+    MContinue cont(&list);
+    cont.SetInverted();
+
+    // -------------------------------------------------------------
+    MBinning binsS(40,  10,     100000, "BinningSize",             "log");
+    MBinning binsE(40,  10,     100000, "BinningEnergy",           "log");
+    MBinning binsF(40,  10,     100000, "BinningEnergyEst",        "log");
+    MBinning binsG(90, -14,     14,     "BinningSlope",            "lin");
+    MBinning binsR(50,  -1,     1,      "BinningEnergyResidual",   "lin");
+    MBinning binsL(50,   0,     0.3,    "BinningLeakage",          "lin");
+    MBinning binsT(51,  -0.005, 0.505,  "BinningTheta",            "asin");
+    MBinning binsD(70,   0,     2.4,    "BinningDist",             "lin");
+    MBinning binsC(50,   1e-2,  1,      "BinningConc",             "log");
+    MBinning binsI(32,   0,     800,    "BinningImpact",           "lin");
+
+    plist.AddToList(&binsG);
+    plist.AddToList(&binsS);
+    plist.AddToList(&binsR);
+    plist.AddToList(&binsE);
+    plist.AddToList(&binsF);
+    plist.AddToList(&binsL);
+    plist.AddToList(&binsT);
+    plist.AddToList(&binsD);
+    plist.AddToList(&binsC);
+    plist.AddToList(&binsI);
+
+    MHEnergyEst hist;
+
+    // To speed it up we could precalculate it.
+    const char *res = "log10(MEnergyEst.fVal)-log10(MMcEvt.fEnergy)";
+
+    MHn hres1("Energy1", "Energy Residual (lg E_{est} - lg E_{mc})");
+    hres1.AddHist("MHillas.fSize", res);
+    hres1.InitName("ResSize;Size;EnergyResidual");
+    hres1.InitTitle(";S [phe];\\Delta lg E;");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg", res);
+    hres1.InitName("ResSlope;Slope;EnergyResidual");
+    hres1.InitTitle(";Slope;\\Delta lg E;");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MNewImagePar.fLeakage1", res);
+    hres1.InitName("ResLeak;Leakage;EnergyResidual");
+    hres1.InitTitle(";Leak;\\Delta lg E;");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MHillasSrc.fDist*MGeomCam.fConvMm2Deg", res);
+    hres1.InitName("ResDist;Dist;EnergyResidual");
+    hres1.InitTitle(";D [\\circ];\\Delta lg E;");
+    hres1.SetDrawOption("colz profx");
+
+    MHn hres2("Energy2", "Energy Residual (lg E_{est} - lg E_{mc})");
+    hres2.AddHist("MMcEvt.fEnergy", res);
+    hres2.InitName("ResEmc;Energy;EnergyResidual");
+    hres2.InitTitle(";E_{mc} [GeV];\\Delta lg E;");
+    hres2.SetDrawOption("colz profx");
+    hres2.SetAutoRange(kFALSE, kFALSE, kFALSE);
+    hres2.AddHist("MPointingPos.fZd", res);
+    hres2.InitName("ResTheta;Theta;EnergyResidual");
+    hres2.InitTitle(";Zd [\\circ];\\Delta lg E;");
+    hres2.SetDrawOption("colz profx");
+    hres2.AddHist("MEnergyEst.fVal", res);
+    hres2.InitName("ResEest;Energy;EnergyResidual");
+    hres2.InitTitle(";E_{est} [GeV];\\Delta lg E;");
+    hres2.SetDrawOption("colz profx");
+    hres2.SetAutoRange(kFALSE, kFALSE, kFALSE);
+    hres2.AddHist("MNewImagePar.fConc1", res);
+    hres2.InitName("ResConc1;Conc;EnergyResidual");
+    hres2.InitTitle(";C;\\Delta lg E;");
+    hres2.SetDrawOption("colz profx");
+
+    MHn hres3("Resolution", "Energy Resolution");
+    hres3.AddHist("MEnergyEst.fVal", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResEest;EnergyEst;");
+    hres3.InitTitle(";E_{est} [GeV];Resolution   \\sqrt{<(E_{mc}/E_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+
+    hres3.AddHist("MHillas.fSize", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResSize;Size;");
+    hres3.InitTitle(";S [phe];Resolution   \\sqrt{<(E_{mc}/E_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+/*
+    hres3.AddHist("MMcEvt.fEnergy", "(MEnergyEst.fVal/MMcEvt.fEnergy-1)^2", MH3::kProfile);
+    hres3.InitName("ResEmc;EnergyEst;");
+    hres3.InitTitle(";E_{mc} [GeV];Resolution \\sqrt{<(E_{mc}/E_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+  */
+    hres3.AddHist("MPointingPos.fZd", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResTheta;Theta;");
+    hres3.InitTitle(";\\Theta [\\circ];Resolution   \\sqrt{<(E_{mc}/E_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+
+    hres3.AddHist("MMcEvt.fImpact/100", "(MMcEvt.fEnergy/MEnergyEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResImpact;Impact;");
+    hres3.InitTitle(";I [m];Resolution   \\sqrt{<(E_{mc}/E_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+
+    MFillH fillh0(&hist);
+    MFillH fillh1(&hres1, "", "FillResiduals1");
+    MFillH fillh2(&hres2, "", "FillResiduals2");
+    MFillH fillh3(&hres3, "", "FillResolution");
+
+    if (fEnableWeights)
+    {
+        fillh0.SetWeight();
+        fillh1.SetWeight();
+        fillh2.SetWeight();
+        fillh3.SetWeight();
+    }
+
+    tlist.AddToList(&readtst);
+    tlist.AddToList(fPreTasks);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&rf);
+    tlist.AddToList(fPostTasks);
+    tlist.AddToList(&fillh0);
+    tlist.AddToList(&fillh1);
+    tlist.AddToList(&fillh2);
+    tlist.AddToList(&fillh3);
+    tlist.AddToList(fTestTasks);
+
+    MEvtLoop loop(fTitle);
+    loop.SetLogStream(fLog);
+    loop.SetDisplay(fDisplay);
+    loop.SetParList(&plist);
+    //if (!SetupEnv(loop))
+    //   return kFALSE;
+
+    if (!loop.Eventloop())
+        return kFALSE;
+
+    TObjArray arr;
+    arr.Add(const_cast<MDataSet*>(&set));
+    if (fDisplay)
+        arr.Add(fDisplay);
+
+    SetPathOut(out);
+    return WriteContainer(arr, 0, "UPDATE");
+}
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainEnergy.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainEnergy.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainEnergy.h	(revision 17960)
@@ -0,0 +1,38 @@
+#ifndef MARS_MJTrainEnergy
+#define MARS_MJTrainEnergy
+
+#ifndef MARS_MJTrainRanForest
+#include "MJTrainRanForest.h"
+#endif
+
+class MDataSet;
+
+class MJTrainEnergy : public MJTrainRanForest
+{
+private:
+    TString fTrainParameter;
+    TString fResultFunction;
+
+    // To be moved to a base class
+    TString fNameOutput;
+
+public:
+    MJTrainEnergy() : fNameOutput("MEnergyEst") { SetTrainLin(); }
+
+    void SetTrainLog()     { SetTrainFunc("log(MMcEvt.fEnergy)", "exp(x)"); }
+    void SetTrainLin()     { SetTrainFunc("MMcEvt.fEnergy", "x"); }
+    void SetTrainExpSize() { SetTrainFunc("log(MMcEvt.fEnergy)/log(MHillas.fSize)", "MHillas.fSize^x"); }
+
+    void SetTrainFunc(const char *par, const char *res)
+    {
+        fTrainParameter = par;
+        fResultFunction = res;
+    }
+
+    Bool_t Train(const char *out, const MDataSet &set, Int_t num);
+
+    ClassDef(MJTrainEnergy, 0)//Class to train Random Forest energy estimator
+};
+
+
+#endif
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainImpact.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainImpact.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainImpact.cc	(revision 17960)
@@ -0,0 +1,325 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 8/2010 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJTrainImpact
+//
+//
+// Example:
+// --------
+//
+//    // SequencesOn are used for training, SequencesOff for Testing
+//    MDataSet set("mctesttrain.txt");
+//    set.SetNumAnalysis(1);  // Must have a number
+//    MJTrainImpact opt;
+//    //opt.SetDebug();
+//    opt.AddParameter("MHillas.fSize");
+//    opt.AddParameter("MHillasSrc.fDist");
+//    MStatusDisplay *d = new MStatusDisplay;
+//    opt.SetDisplay(d);
+//    opt.AddPreCut("MHillasSrc.fDCA*MGeomCam.fConvMm2Deg<0.3");
+//    opt.Train("rf-impact.root", set, 30000); // Number of train events
+//
+// Random Numbers:
+// ---------------
+//   Use:
+//         if(gRandom)
+//             delete gRandom;
+//         gRandom = new TRandom3();
+//   in advance to change the random number generator.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MJTrainImpact.h"
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+// tools
+#include "MDataSet.h"
+#include "MTFillMatrix.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// tasks
+#include "MReadMarsFile.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MRanForestCalc.h"
+
+// histograms
+#include "MHn.h"
+#include "MBinning.h"
+#include "MHEnergyEst.h"
+
+// filter
+#include "MFilterList.h"
+
+ClassImp(MJTrainImpact);
+
+using namespace std;
+
+Bool_t MJTrainImpact::Train(const char *out, const MDataSet &set, Int_t num)
+{
+    SetTitle(Form("Train%s: %s", fNameOutput.Data(), out));
+
+    if (fDisplay)
+        fDisplay->SetTitle(fTitle);
+
+    if (!set.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(out))
+        return kFALSE;
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+
+    // --------------------- Setup files --------------------
+    MReadMarsFile readtrn("Events");
+    MReadMarsFile readtst("Events");
+    readtrn.DisableAutoScheme();
+    readtst.DisableAutoScheme();
+
+    if (!set.AddFilesOn(readtrn))
+    {
+        *fLog << err << "ERROR - Adding SequencesOn." << endl;
+        return kFALSE;
+    }
+    if (!set.AddFilesOff(readtst))
+    {
+        *fLog << err << "ERROR - Adding SequencesOff." << endl;
+        return kFALSE;
+    }
+
+    // ----------------------- Setup Matrix ------------------
+    MHMatrix train("Train");
+    train.AddColumns(fRules);
+    if (fEnableWeights)
+        train.AddColumn("MWeight.fVal");
+    train.AddColumn(fTrainParameter);
+
+    // ----------------------- Fill Matrix RF ----------------------
+    MTFillMatrix fill(fTitle);
+    fill.SetDisplay(fDisplay);
+    fill.SetLogStream(fLog);
+    fill.SetDestMatrix1(&train, num);
+    fill.SetReader(&readtrn);
+    fill.AddPreCuts(fPreCuts);
+    fill.AddPreCuts(fTrainCuts);
+    fill.AddPreTasks(fPreTasks);
+    fill.AddPostTasks(fPostTasks);
+    if (!fill.Process())
+        return kFALSE;
+
+    // ------------------------ Train RF --------------------------
+    MRanForestCalc rf("Train", fTitle);
+    rf.SetNumTrees(fNumTrees);
+    rf.SetNdSize(fNdSize);
+    rf.SetNumTry(fNumTry);
+    rf.SetNumObsoleteVariables(1);
+    rf.SetLastDataColumnHasWeights(fEnableWeights);
+    rf.SetDisplay(fDisplay);
+    rf.SetLogStream(fLog);
+    rf.SetFileName(out);
+    rf.SetDebug(fDebug>1);
+    rf.SetNameOutput(fNameOutput);
+    rf.SetFunction(fResultFunction);
+
+    /*
+    MBinning b(32, 10, 100000, "BinningEnergyEst", "log");
+
+    if (!rf.TrainMultiRF(train, b.GetEdgesD()))    // classification with one tree per bin
+        return;
+
+    if (!rf.TrainSingleRF(train, b.GetEdgesD()))   // classification into different bins
+        return;
+    */
+    if (!rf.TrainRegression(train))                  // regression (best choice)
+        return kFALSE;
+
+    // --------------------- Display result ----------------------
+
+    gLog.Separator("Test");
+
+    MH::SetPalette("pretty");
+
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(this);
+    plist.AddToList(&tlist);
+    //plist.AddToList(&b);
+
+    MFilterList list;
+    if (!list.AddToList(fPreCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
+    if (!list.AddToList(fTestCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fTestCuts failed!" << endl;
+
+    MContinue cont(&list);
+    cont.SetInverted();
+
+    // -------------------------------------------------------------
+    MBinning binsS(40,  10,     100000, "BinningSize",             "log");
+    MBinning binsE(40,  10,     100000, "BinningEnergy",           "log");
+//    MBinning binsF(40,  10,     100000, "BinningEnergyEst",        "log");
+    MBinning binsG(90, -14,     14,     "BinningSlope",            "lin");
+    MBinning binsR(50,-100,     100,    "BinningImpactResidual",   "lin");
+    MBinning binsL(50,   0,     0.3,    "BinningLeakage",          "lin");
+    MBinning binsT(51,  -0.005, 0.505,  "BinningTheta",            "asin");
+    MBinning binsD(70,   0,     2.4,    "BinningDist",             "lin");
+    MBinning binsC(50,   1e-2,  1,      "BinningConc",             "log");
+    MBinning binsI(32,   0,     800,    "BinningImpact",           "lin");
+
+    plist.AddToList(&binsG);
+    plist.AddToList(&binsS);
+    plist.AddToList(&binsR);
+    plist.AddToList(&binsE);
+//    plist.AddToList(&binsF);
+    plist.AddToList(&binsL);
+    plist.AddToList(&binsT);
+    plist.AddToList(&binsD);
+    plist.AddToList(&binsC);
+    plist.AddToList(&binsI);
+
+    //MHEnergyEst hist;
+
+    // To speed it up we could precalculate it.
+    const char *res = "(MImpactEst.fVal-MMcEvt.fImpact)/100";
+
+    MHn hres1("Impact1", "Impact Residual (I_{est} - I_{mc})");
+    hres1.AddHist("MHillas.fSize", res);
+    hres1.InitName("ResSize;Size;ImpactResidual");
+    hres1.InitTitle(";S [phe];\\Delta I;");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MHillasExt.fSlopeLong*sign(MHillasSrc.fCosDeltaAlpha)/MGeomCam.fConvMm2Deg", res);
+    hres1.InitName("ResSlope;Slope;ImpactResidual");
+    hres1.InitTitle(";Slope;\\Delta I;");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MNewImagePar.fLeakage1", res);
+    hres1.InitName("ResLeak;Leakage;ImpactResidual");
+    hres1.InitTitle(";Leak;\\Delta I;");
+    hres1.SetDrawOption("colz profx");
+    hres1.AddHist("MHillasSrc.fDist*MGeomCam.fConvMm2Deg", res);
+    hres1.InitName("ResDist;Dist;ImpactResidual");
+    hres1.InitTitle(";D [\\circ];\\Delta I;");
+    hres1.SetDrawOption("colz profx");
+
+    MHn hres2("Impact2", "Impact Residual (I_{est} - I_{mc})");
+    hres2.AddHist("MMcEvt.fEnergy", res);
+    hres2.InitName("ResEmc;Energy;ImpactResidual");
+    hres2.InitTitle(";E_{mc} [m];\\Delta I;");
+    hres2.SetDrawOption("colz profx");
+    hres2.SetAutoRange(kFALSE, kFALSE, kFALSE);
+    hres2.AddHist("MPointingPos.fZd", res);
+    hres2.InitName("ResTheta;Theta;ImpactResidual");
+    hres2.InitTitle(";Zd [\\circ];\\Delta I;");
+    hres2.SetDrawOption("colz profx");
+    hres2.AddHist("MImpactEst.fVal/100", res);
+    hres2.InitName("ResIest;Impact;ImpactResidual");
+    hres2.InitTitle(";I_{est} [m];\\Delta I;");
+    hres2.SetDrawOption("colz profx");
+    hres2.SetAutoRange(kFALSE, kFALSE, kFALSE);
+    hres2.AddHist("MNewImagePar.fConc1", res);
+    hres2.InitName("ResConc1;Conc;ImpactResidual");
+    hres2.InitTitle(";C;\\Delta I;");
+    hres2.SetDrawOption("colz profx");
+
+    MHn hres3("Resolution", "Impact Resolution");
+    hres3.AddHist("MImpactEst.fVal/100", "(MMcEvt.fImpact/MImpactEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResIest;Impact;");
+    hres3.InitTitle(";I_{est} [m];Resolution   \\sqrt{<(I_{mc}/I_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+
+    hres3.AddHist("MHillas.fSize", "(MMcEvt.fImpact/MImpactEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResSize;Size;");
+    hres3.InitTitle(";S [phe];Resolution   \\sqrt{<(I_{mc}/I_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+/*
+    hres3.AddHist("MMcEvt.fEnergy", "(MImpactEst.fVal/MMcEvt.fImpact-1)^2", MH3::kProfile);
+    hres3.InitName("ResEmc;EnergyEst;");
+    hres3.InitTitle(";E_{mc} [GeV];Resolution \\sqrt{<(I_{mc}/I_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+  */
+    hres3.AddHist("MMcEvt.fEnergy", "(MMcEvt.fImpact/MImpactEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResEnergy;Energy;");
+    hres3.InitTitle(";E_{mc} [m];Resolution   \\sqrt{<(I_{mc}/I_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+
+    hres3.AddHist("MPointingPos.fZd", "(MMcEvt.fImpact/MImpactEst.fVal-1)^2", MH3::kProfile);
+    hres3.InitName("ResTheta;Theta;");
+    hres3.InitTitle(";\\Theta [\\circ];Resolution   \\sqrt{<(I_{mc}/I_{est}-1)^{2}>};");
+    hres3.SetConversion("sqrt(x)");
+
+    //MFillH fillh0(&hist);
+    MFillH fillh1(&hres1, "", "FillResiduals1");
+    MFillH fillh2(&hres2, "", "FillResiduals2");
+    MFillH fillh3(&hres3, "", "FillResolution");
+
+    if (fEnableWeights)
+    {
+        //fillh0.SetWeight();
+        fillh1.SetWeight();
+        fillh2.SetWeight();
+        fillh3.SetWeight();
+    }
+
+    tlist.AddToList(&readtst);
+    tlist.AddToList(fPreTasks);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&rf);
+    tlist.AddToList(fPostTasks);
+    //tlist.AddToList(&fillh0);
+    tlist.AddToList(&fillh1);
+    tlist.AddToList(&fillh2);
+    tlist.AddToList(&fillh3);
+    tlist.AddToList(fTestTasks);
+
+    MEvtLoop loop(fTitle);
+    loop.SetLogStream(fLog);
+    loop.SetDisplay(fDisplay);
+    loop.SetParList(&plist);
+    //if (!SetupEnv(loop))
+    //   return kFALSE;
+
+    if (!loop.Eventloop())
+        return kFALSE;
+
+    TObjArray arr;
+    arr.Add(const_cast<MDataSet*>(&set));
+    if (fDisplay)
+        arr.Add(fDisplay);
+
+    SetPathOut(out);
+    return WriteContainer(arr, 0, "UPDATE");
+}
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainImpact.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainImpact.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainImpact.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MJTrainImpact
+#define MARS_MJTrainImpact
+
+#ifndef MARS_MJTrainRanForest
+#include "MJTrainRanForest.h"
+#endif
+
+class MDataSet;
+
+class MJTrainImpact : public MJTrainRanForest
+{
+private:
+    TString fTrainParameter;
+    TString fResultFunction;
+
+    // To be moved to a base class
+    TString fNameOutput;
+
+public:
+    MJTrainImpact() : fNameOutput("MImpactEst") { SetTrainSq(); }
+
+    void SetTrainSq()  { SetTrainFunc("MMcEvt.fImpact^2", "sqrt(x)"); }
+    void SetTrainLin() { SetTrainFunc("MMcEvt.fEnergy", "x"); }
+
+    void SetTrainFunc(const char *par, const char *res)
+    {
+        fTrainParameter = par;
+        fResultFunction = res;
+    }
+
+    Bool_t Train(const char *out, const MDataSet &set, Int_t num);
+
+    ClassDef(MJTrainImpact, 0)//Class to train Random Forest impact estimator
+};
+
+
+#endif
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainRanForest.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainRanForest.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainRanForest.cc	(revision 17960)
@@ -0,0 +1,47 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2005-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJTrainRanForest
+//
+// Base class for classes training a random forest
+//
+// The order when reading a file is:
+//   1) Execution of PreTasks  (set by user)
+//   2) Execution of PreCuts   (set by user)
+//   3) Selector               (calculated from number of requested events)
+//   4) Splitter               (if sample is split automatically in test/train)
+//   5) PostTasks              (set by user)
+//
+// The split into Pre- and PostTasks is done for speed reason. So, if
+// you calculate a vlue which is not needed for your PreCuts, you can
+// calculate it afterwards, which will speed up execution.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJTrainRanForest.h"
+
+ClassImp(MJTrainRanForest);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainRanForest.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainRanForest.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainRanForest.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MJTrainRanForest
+#define MARS_MJTrainRanForest
+
+#ifndef MARS_MJOptimizeBase
+#include "MJOptimizeBase.h"
+#endif
+
+class MTask;
+class MFilter;
+
+class MJTrainRanForest : public MJOptimizeBase
+{
+protected:
+    UShort_t fNumTrees;
+    UShort_t fNdSize;
+    UShort_t fNumTry;
+
+public:
+    MJTrainRanForest()
+    {
+        fNumTrees = 100; //100
+        fNumTry   = 0;   //3   0 means: in MRanForest estimated best value will be calculated
+        fNdSize   = 1;   //1
+    }
+
+    void SetNumTrees(UShort_t n=100)   { fNumTrees = n; }
+    void SetNdSize(UShort_t n=5)       { fNdSize   = n; }
+    void SetNumTry(UShort_t n=0)       { fNumTry   = n; }
+
+    ClassDef(MJTrainRanForest, 0)//Base class for Random Forest training classes
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainSeparation.cc
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainSeparation.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainSeparation.cc	(revision 17960)
@@ -0,0 +1,1060 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJTrainSeparation
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MJTrainSeparation.h"
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TChain.h>
+#include <TGraph.h>
+#include <TMarker.h>
+#include <TCanvas.h>
+#include <TStopwatch.h>
+#include <TVirtualPad.h>
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+// tools
+#include "MMath.h"
+#include "MDataSet.h"
+#include "MTFillMatrix.h"
+#include "MStatusDisplay.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// tasks
+#include "MReadMarsFile.h"
+#include "MReadReports.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MSrcPosRndm.h"
+#include "MHillasCalc.h"
+#include "MRanForestCalc.h"
+#include "MParameterCalc.h"
+
+// container
+#include "MMcEvt.hxx"
+#include "MParameters.h"
+
+// histograms
+#include "MBinning.h"
+#include "MH3.h"
+#include "MHHadronness.h"
+
+// filter
+#include "MF.h"
+#include "MFEventSelector.h"
+#include "MFilterList.h"
+
+// wobble
+#include "MPointingPos.h"
+#include "MPointingDevCalc.h"
+#include "../mastro/MObservatory.h"
+#include "MSrcPosCalc.h"
+#include "MSrcPosCorrect.h"
+#include "../mimage/MHillasCalc.h"
+
+
+ClassImp(MJTrainSeparation);
+
+using namespace std;
+
+void MJTrainSeparation::DisplayResult(MH3 &h31, MH3 &h32, Float_t ontime)
+{
+    TH2D &g = (TH2D&)h32.GetHist();
+    TH2D &h = (TH2D&)h31.GetHist();
+
+    h.SetMarkerColor(kRed);
+    g.SetMarkerColor(kBlue);
+
+    TH2D res1(g);
+    TH2D res2(g);
+
+    h.SetTitle("Hadronness-Distribution vs. Size");
+    res1.SetTitle("Significance Li/Ma");
+    res1.SetXTitle("Size [phe]");
+    res1.SetYTitle("Hadronness");
+    res2.SetTitle("Significance-Distribution");
+    res2.SetXTitle("Size-Cut [phe]");
+    res2.SetYTitle("Hadronness-Cut");
+    res1.SetContour(50);
+    res2.SetContour(50);
+
+    const Int_t nx = h.GetNbinsX();
+    const Int_t ny = h.GetNbinsY();
+
+    gROOT->SetSelectedPad(NULL);
+
+
+    Double_t Stot = 0;
+    Double_t Btot = 0;
+
+    Double_t max2 = -1;
+
+    TGraph gr1;
+    TGraph gr2;
+    for (int x=nx-1; x>=0; x--)
+    {
+        TH1 *hx = h.ProjectionY("H_py", x+1, x+1);
+        TH1 *gx = g.ProjectionY("G_py", x+1, x+1);
+
+        Double_t S = 0;
+        Double_t B = 0;
+
+        Double_t max1 = -1;
+        Int_t maxy1 = 0;
+        Int_t maxy2 = 0;
+        for (int y=ny-1; y>=0; y--)
+        {
+            const Float_t s = gx->Integral(1, y+1);
+            const Float_t b = hx->Integral(1, y+1);
+            const Float_t sig1 = MMath::SignificanceLiMa(s+b, b);
+            const Float_t sig2 = MMath::SignificanceLiMa(s+Stot+b+Btot, b+Btot)*TMath::Log10(s+Stot+1);
+            if (sig1>max1)
+            {
+                maxy1 = y;
+                max1 = sig1;
+            }
+            if (sig2>max2)
+            {
+                maxy2 = y;
+                max2 = sig2;
+
+                S=s;
+                B=b;
+            }
+
+            res1.SetBinContent(x+1, y+1, sig1);
+        }
+
+        Stot += S;
+        Btot += B;
+
+        gr1.SetPoint(x, h.GetXaxis()->GetBinCenter(x+1), h.GetYaxis()->GetBinCenter(maxy1+1));
+        gr2.SetPoint(x, h.GetXaxis()->GetBinCenter(x+1), h.GetYaxis()->GetBinCenter(maxy2+1));
+
+        delete hx;
+        delete gx;
+    }
+
+    //cout << "--> " << MMath::SignificanceLiMa(Stot+Btot, Btot) << " ";
+    //cout << Stot << " " << Btot << endl;
+
+
+    Int_t mx1=0;
+    Int_t my1=0;
+    Int_t mx2=0;
+    Int_t my2=0;
+    Int_t s1=0;
+    Int_t b1=0;
+    Int_t s2=0;
+    Int_t b2=0;
+    Double_t sig1=-1;
+    Double_t sig2=-1;
+    for (int x=0; x<nx; x++)
+    {
+        TH1 *hx = h.ProjectionY("H_py", x+1);
+        TH1 *gx = g.ProjectionY("G_py", x+1);
+        for (int y=0; y<ny; y++)
+        {
+            const Float_t s = gx->Integral(1, y+1);
+            const Float_t b = hx->Integral(1, y+1);
+            const Float_t sig = MMath::SignificanceLiMa(s+b, b);
+            res2.SetBinContent(x+1, y+1, sig);
+
+            // Search for top-rightmost maximum
+            if (sig>=sig1)
+            {
+                mx1=x+1;
+                my1=y+1;
+                s1 = TMath::Nint(s);
+                b1 = TMath::Nint(b);
+                sig1=sig;
+            }
+            if (TMath::Log10(s)*sig>=sig2)
+            {
+                mx2=x+1;
+                my2=y+1;
+                s2 = TMath::Nint(s);
+                b2 = TMath::Nint(b);
+                sig2=TMath::Log10(s)*sig;
+            }
+        }
+        delete hx;
+        delete gx;
+    }
+
+    TGraph gr3;
+    TGraph gr4;
+    gr4.SetTitle("Significance Li/Ma vs. Hadronness-cut");
+
+    TH1 *hx = h.ProjectionY("H_py");
+    TH1 *gx = g.ProjectionY("G_py");
+    for (int y=0; y<ny; y++)
+    {
+        const Float_t s = gx->Integral(1, y+1);
+        const Float_t b = hx->Integral(1, y+1);
+        const Float_t sg1 = MMath::SignificanceLiMa(s+b, b);
+        const Float_t sg2 = s<1 ? 0 : MMath::SignificanceLiMa(s+b, b)*TMath::Log10(s);
+
+        gr3.SetPoint(y, h.GetYaxis()->GetBinLowEdge(y+2), sg1);
+        gr4.SetPoint(y, h.GetYaxis()->GetBinLowEdge(y+2), sg2);
+    }
+    delete hx;
+    delete gx;
+
+    if (fDisplay)
+    {
+        TCanvas &c = fDisplay->AddTab("OptCut");
+        c.SetBorderMode(0);
+        c.Divide(2,2);
+
+        c.cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetLogx();
+        gPad->SetGridx();
+        gPad->SetGridy();
+        h.DrawCopy();
+        g.DrawCopy("same");
+        gr1.SetMarkerStyle(kFullDotMedium);
+        gr1.DrawClone("LP")->SetBit(kCanDelete);
+        gr2.SetLineColor(kBlue);
+        gr2.SetMarkerStyle(kFullDotMedium);
+        gr2.DrawClone("LP")->SetBit(kCanDelete);
+
+        c.cd(3);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gr4.SetMinimum(0);
+        gr4.SetMarkerStyle(kFullDotMedium);
+        gr4.DrawClone("ALP")->SetBit(kCanDelete);
+        gr3.SetLineColor(kBlue);
+        gr3.SetMarkerStyle(kFullDotMedium);
+        gr3.DrawClone("LP")->SetBit(kCanDelete);
+
+        c.cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetLogx();
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gPad->AddExec("color", "gStyle->SetPalette(1, 0);");
+        res1.SetMaximum(7);
+        res1.DrawCopy("colz");
+
+        c.cd(4);
+        gPad->SetBorderMode(0);
+        gPad->SetFrameBorderMode(0);
+        gPad->SetLogx();
+        gPad->SetGridx();
+        gPad->SetGridy();
+        gPad->AddExec("color", "gStyle->SetPalette(1, 0);");
+        res2.SetMaximum(res2.GetMaximum()*1.05);
+        res2.DrawCopy("colz");
+
+        //    Int_t mx, my, mz;
+        //    res2.GetMaximumBin(mx, my, mz);
+
+        TMarker m;
+        m.SetMarkerStyle(kStar);
+        m.DrawMarker(res2.GetXaxis()->GetBinCenter(mx1), res2.GetYaxis()->GetBinCenter(my1));
+        m.SetMarkerStyle(kPlus);
+        m.DrawMarker(res2.GetXaxis()->GetBinCenter(mx2), res2.GetYaxis()->GetBinCenter(my2));
+    }
+
+    if (ontime>0)
+        *fLog << all << "Observation Time:     " << TMath::Nint(ontime/60) << "min" << endl;
+    *fLog << "Maximum Significance: " << Form("%.1f", sig1);
+    if (ontime>0)
+        *fLog << Form(" [%.1f/sqrt(h)]", sig1/TMath::Sqrt(ontime/3600));
+    *fLog << endl;
+
+    *fLog << "Significance:         S=" << Form("%.1f", sig1) << " E=" << s1 << " B=" << b1 << " h<";
+    *fLog << Form("%.2f", res2.GetYaxis()->GetBinCenter(my1)) << " s>";
+    *fLog << Form("%3d", TMath::Nint(res2.GetXaxis()->GetBinCenter(mx1))) << endl;
+    *fLog << "Significance*LogE:    S=" << Form("%.1f", sig2/TMath::Log10(s2)) << " E=" << s2 << " B=" << b2 << " h<";
+    *fLog << Form("%.2f", res2.GetYaxis()->GetBinCenter(my2)) << " s>";
+    *fLog << Form("%3d", TMath::Nint(res2.GetXaxis()->GetBinCenter(mx2))) << endl;
+    *fLog << endl;
+}
+
+/*
+Bool_t  MJSpectrum::InitWeighting(const MDataSet &set, MMcSpectrumWeight &w) const
+{
+    fLog->Separator("Initialize energy weighting");
+
+    if (!CheckEnv(w))
+    {
+        *fLog << err << "ERROR - Reading resources for MMcSpectrumWeight failed." << endl;
+        return kFALSE;
+    }
+
+    TChain chain("RunHeaders");
+    set.AddFilesOn(chain);
+
+    MMcCorsikaRunHeader *h=0;
+    chain.SetBranchAddress("MMcCorsikaRunHeader.", &h);
+    chain.GetEntry(1);
+
+    if (!h)
+    {
+        *fLog << err << "ERROR - Couldn't read MMcCorsikaRunHeader from DataSet." << endl;
+        return kFALSE;
+    }
+
+    if (!w.Set(*h))
+    {
+        *fLog << err << "ERROR - Initializing MMcSpectrumWeight failed." << endl;
+        return kFALSE;
+    }
+
+    w.Print();
+    return kTRUE;
+}
+
+Bool_t MJSpectrum::ReadOrigMCDistribution(const MDataSet &set, TH1 &h, MMcSpectrumWeight &weight) const
+{
+    // Some debug output
+    fLog->Separator("Compiling original MC distribution");
+
+    weight.SetNameMcEvt("MMcEvtBasic");
+    const TString w(weight.GetFormulaWeights());
+    weight.SetNameMcEvt();
+
+    *fLog << inf << "Using weights: " << w << endl;
+    *fLog << "Please stand by, this may take a while..." << flush;
+
+    if (fDisplay)
+        fDisplay->SetStatusLine1("Compiling MC distribution...");
+
+    // Create chain
+    TChain chain("OriginalMC");
+    set.AddFilesOn(chain);
+
+    // Prepare histogram
+    h.Reset();
+
+    // Fill histogram from chain
+    h.SetDirectory(gROOT);
+    if (h.InheritsFrom(TH2::Class()))
+    {
+        h.SetNameTitle("ThetaEMC", "Event-Distribution vs Theta and Energy for MC (produced)");
+        h.SetXTitle("\\Theta [\\circ]");
+        h.SetYTitle("E [GeV]");
+        h.SetZTitle("Counts");
+        chain.Draw("MMcEvtBasic.fEnergy:MMcEvtBasic.fTelescopeTheta*TMath::RadToDeg()>>ThetaEMC", w, "goff");
+    }
+    else
+    {
+        h.SetNameTitle("ThetaMC", "Event-Distribution vs Theta for MC (produced)");
+        h.SetXTitle("\\Theta [\\circ]");
+        h.SetYTitle("Counts");
+        chain.Draw("MMcEvtBasic.fTelescopeTheta*TMath::RadToDeg()>>ThetaMC", w, "goff");
+    }
+    h.SetDirectory(0);
+
+    *fLog << "done." << endl;
+    if (fDisplay)
+        fDisplay->SetStatusLine2("done.");
+
+    if (h.GetEntries()>0)
+        return kTRUE;
+
+    *fLog << err << "ERROR - Histogram with original MC distribution empty..." << endl;
+
+    return h.GetEntries()>0;
+}
+*/
+
+Bool_t MJTrainSeparation::GetEventsProduced(MDataSet &set, Double_t &num, Double_t &min, Double_t &max) const
+{
+    TChain chain("OriginalMC");
+    if (!set.AddFilesOn(chain))
+        return kFALSE;
+
+    min = chain.GetMinimum("MMcEvtBasic.fEnergy");
+    max = chain.GetMaximum("MMcEvtBasic.fEnergy");
+
+    num = chain.GetEntries();
+
+    if (num<100)
+        *fLog << err << "ERROR - Less than 100 entries in OriginalMC-Tree of MC-Train-Data found." << endl;
+
+    return num>=100;
+}
+
+Double_t MJTrainSeparation::GetDataRate(MDataSet &set, Double_t &num) const
+{
+    TChain chain1("Events");
+    if (!set.AddFilesOff(chain1))
+        return kFALSE;
+
+    num = chain1.GetEntries();
+    if (num<100)
+    {
+        *fLog << err << "ERROR - Less than 100 entries in Events-Tree of Train-Data found." << endl;
+        return -1;
+    }
+
+    TChain chain("EffectiveOnTime");
+    if (!set.AddFilesOff(chain))
+        return kFALSE;
+
+    chain.Draw("MEffectiveOnTime.fVal", "MEffectiveOnTime.fVal", "goff");
+
+    TH1 *h = dynamic_cast<TH1*>(gROOT->FindObject("htemp"));
+    if (!h)
+    {
+        *fLog << err << "ERROR - Weird things are happening (htemp not found)!" << endl;
+        return -1;
+    }
+
+    const Double_t ontime = h->Integral();
+    delete h;
+
+    if (ontime<1)
+    {
+        *fLog << err << "ERROR - Less than 1s of effective observation time found in Train-Data." << endl;
+        return -1;
+    }
+
+    return num/ontime;
+}
+
+Double_t MJTrainSeparation::GetNumMC(MDataSet &set) const
+{
+    TChain chain1("Events");
+    if (!set.AddFilesOn(chain1))
+        return kFALSE;
+
+    const Double_t num = chain1.GetEntries();
+    if (num<100)
+    {
+        *fLog << err << "ERROR - Less than 100 entries in Events-Tree of Train-Data found." << endl;
+        return -1;
+    }
+
+    return num;
+}
+
+Float_t MJTrainSeparation::AutoTrain(MDataSet &set, Type_t  typon, Type_t typof, Float_t flux)
+{
+    Double_t num, min, max;
+    if (!GetEventsProduced(set, num, min, max))
+        return -1;
+
+    *fLog << inf << "Using build-in radius of 300m to calculate collection area!" << endl;
+
+    // Target spectrum
+    TF1 flx("Flux", "[0]/1000*(x/1000)^(-2.6)", min, max);
+    flx.SetParameter(0, flux);
+
+    // Number n0 of events this spectrum would produce per s and m^2
+    const Double_t n0 = flx.Integral(min, max);    //[#]
+
+    // Area produced in MC
+    const Double_t A = TMath::Pi()*300*300;        //[m²]
+
+    // Rate R of events this spectrum would produce per s
+    const Double_t R = n0*A;                       //[Hz]
+
+    *fLog << "Source Spectrum: " << flux << " * (E/TeV)^(-2.6) * TeV*m^2*s" << endl;
+
+    *fLog << "Gamma rate from the source inside the MC production area: " << R << "Hz" << endl;
+
+    // Number N of events produced (in trainings sample)
+    const Double_t N = num;                        //[#]
+
+    *fLog << "Events produced by MC inside the production area:         " << TMath::Nint(num) << endl;
+
+    // This correponds to an observation time T [s]
+    const Double_t T = N/R;                        //[s]
+
+    *fLog << "Total time produced by the Monte Carlo:                   " << T << "s" << endl;
+
+    // With an average data rate after star of
+    Double_t data=0;
+    const Double_t r = GetDataRate(set, data); //[Hz]
+    Double_t ontime = data/r;
+
+    *fLog << "Events measured per second effective on time:             " << r << "Hz" << endl;
+    *fLog << "Total effective on time:                                  " << ontime  << "s" << endl;
+
+    const Double_t ratio = T/ontime;
+    *fLog << "Ratio of Monte Carlo to data observation time:            " << ratio << endl;
+
+    // 3570.5/43440.2 = 0.082
+
+
+    // this yields a number of n events to be read for training
+    const Double_t n = r*T;                        //[#]
+
+    *fLog << "Events to be read from the data sample:                   " << TMath::Nint(n) << endl;
+    *fLog << "Events available in data sample:                          " << data << endl;
+
+    if (r<0)
+        return -1;
+
+    Double_t nummc = GetNumMC(set);
+
+    *fLog << "Events available in MC sample:                            " << nummc << endl;
+
+//    *fLog << "MC read probability:                                      " << data/n << endl;
+
+    // more data requested than available => Scale down num MC events
+    Double_t on, off;
+    if (data<n)
+    {
+        on  = TMath::Nint(nummc*data/n);
+        off = TMath::Nint(data);
+        *fLog << warn;
+        *fLog << "Not enough data events available... scaling MC to data by " << data/n << endl;
+        *fLog << inf;
+    }
+    else
+    {
+        on  = TMath::Nint(nummc);
+        off = TMath::Nint(n);
+    }
+
+    if (fNum[typon]>0 && fNum[typon]<on)
+    {
+        fNum[typof] = TMath::Nint(off*fNum[typon]/on);
+        ontime *= fNum[typon]/on;
+        *fLog << warn << "Less MC events requested... scaling data to MC by " << fNum[typon]/on << endl;
+    }
+    else
+    {
+        fNum[typon] = TMath::Nint(on);
+        fNum[typof] = TMath::Nint(off);
+    }
+
+    *fLog << inf;
+    *fLog << "Target number of MC events:   " << fNum[typon] << endl;
+    *fLog << "Target number of data events: " << fNum[typof] << endl;
+
+    /*
+     An event rate dependent selection?
+     ----------------------------------
+     Total average data rate:      R
+     Goal number of events:        N
+     Number of data events:        N0
+     Rate assigned to single evt:  r
+
+     Selection probability: N/N0 * r/R
+
+     f := N/N0 * r
+
+     MF f("f * MEventRate.fRate < rand");
+     */
+
+    return ontime;
+}
+
+Bool_t MJTrainSeparation::Train(const char *out)
+{
+    if (fDisplay)
+        fDisplay->SetTitle(out);
+
+    if (!fDataSetTrain.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet for training invalid!" << endl;
+        return kFALSE;
+    }
+    if (!fDataSetTest.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet for testing invalid!" << endl;
+        return kFALSE;
+    }
+
+    if (fDataSetTrain.IsWobbleMode()!=fDataSetTest.IsWobbleMode())
+    {
+        *fLog << err << "ERROR - Train- and Test-DataSet have different observation modes!" << endl;
+        return kFALSE;
+    }
+
+    if (!HasWritePermission(out))
+        return kFALSE;
+
+        TStopwatch clock;
+    clock.Start();
+
+    // ----------------------- Auto Train? ----------------------
+
+    Float_t ontime = -1;
+    if (fAutoTrain)
+    {
+        fLog->Separator("Auto-Training -- Train-Data");
+        if (AutoTrain(fDataSetTrain, kTrainOn, kTrainOff, fFluxTrain)<0)
+            return kFALSE;
+        fLog->Separator("Auto-Training -- Test-Data");
+        ontime = AutoTrain(fDataSetTest, kTestOn, kTestOff, fFluxTest);
+        if (ontime<0)
+            return kFALSE;
+    }
+
+    // --------------------- Setup files --------------------
+    MReadReports  read1;//("Events");
+    MReadMarsFile read2("Events");
+    MReadMarsFile read3("Events");
+    MReadReports  read4;//("Events");
+    //read1.DisableAutoScheme();
+    read2.DisableAutoScheme();
+    read3.DisableAutoScheme();
+    //read4.DisableAutoScheme();
+
+    read1.AddTree("Events", "MTime.", MReadReports::kMaster);
+    read4.AddTree("Events", "MTime.", MReadReports::kMaster);
+    read1.AddTree("Drive",            MReadReports::kRequired);
+    read4.AddTree("Drive",            MReadReports::kRequired);
+    read1.AddTree("Starguider",       MReadReports::kRequired);
+    read4.AddTree("Starguider",       MReadReports::kRequired);
+
+    // Setup four reading tasks with the on- and off-data of the two datasets
+    if (!fDataSetTrain.AddFilesOn(read1))
+        return kFALSE;
+    const Bool_t setrc1 = fDataSetTrain.IsWobbleMode() ?
+        fDataSetTrain.AddFilesOn(read3) : fDataSetTrain.AddFilesOff(read3);
+    const Bool_t setrc2 = fDataSetTest.IsWobbleMode() ?
+        fDataSetTest.AddFilesOn(read2) : fDataSetTest.AddFilesOff(read2);
+    if (!setrc1  || !setrc2)
+        return kFALSE;
+    if (!fDataSetTest.AddFilesOn(read4))
+        return kFALSE;
+
+    // ----------------------- Setup RF Matrix ----------------------
+    MHMatrix train("Train");
+    train.AddColumns(fRules);
+    if (fEnableWeights[kTrainOn] || fEnableWeights[kTrainOff])
+        train.AddColumn("MWeight.fVal");
+    train.AddColumn("MHadronness.fVal");
+
+    // ----------------------- Fill Matrix RF ----------------------
+
+    // Setup the hadronness container identifying gammas and off-data
+    // and setup a container for the weights
+    MParameterD had("MHadronness");
+    MParameterD wgt("MWeight");
+
+    // Add them to the parameter list
+    MParList plistx;
+    plistx.AddToList(this); // take care of fDisplay!
+    plistx.AddToList(&had);
+    plistx.AddToList(&wgt);
+
+    // Setup the tool class to fill the matrix
+    MTFillMatrix fill;
+    fill.SetLogStream(fLog);
+    fill.SetDisplay(fDisplay);
+    fill.AddPreCuts(fPreCuts);
+    fill.AddPreCuts(fTrainCuts);
+
+    // Set classifier for gammas
+    had.SetVal(0);
+    wgt.SetVal(1);
+
+    // How to get source position from off- and on-data?
+    MPointingPos source("MSourcePos");
+    MObservatory     obs;
+    MSrcPosCalc      scalc;
+    MSrcPosCorrect   scor;
+    MHillasCalc      hcalcw;
+    MHillasCalc      hcalcw2;
+    MPointingDevCalc devcalc;
+    scalc.SetMode(MSrcPosCalc::kDefault); // kWobble for off-source
+    hcalcw.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalcw2.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalcw2.SetNameHillasSrc("MHillasSrcAnti");
+    hcalcw2.SetNameSrcPosCam("MSrcPosAnti");
+    if (fDataSetTrain.IsWobbleMode())
+    {
+        // *******************************************************************
+        // Possible source position (eg. Wobble Mode)
+        if (fDataSetTrain.HasSource())
+        {
+            if (!fDataSetTrain.GetSourcePos(source))
+                return -1;
+            *fLog << all;
+            source.Print("RaDec");
+        }
+        else
+            *fLog << all << "No source position applied..." << endl;
+
+        // La Palma Magic1
+        plistx.AddToList(&obs);
+        plistx.AddToList(&source);
+
+        TList tlist2;
+        tlist2.Add(&scalc);
+        tlist2.Add(&scor);
+        tlist2.Add(&hcalcw);
+        tlist2.Add(&hcalcw2);
+
+        devcalc.SetStreamId("Starguider");
+        tlist2.Add(&devcalc);
+
+        fill.AddPreTasks(tlist2);
+        // *******************************************************************
+    }
+
+    // Setup the tool class to read the gammas and read them
+    fill.SetName("FillGammas");
+    fill.SetDestMatrix1(&train, fNum[kTrainOn]);
+    fill.SetReader(&read1);
+    fill.AddPreTasks(fPreTasksSet[kTrainOn]);
+    fill.AddPreTasks(fPreTasks);
+    fill.AddPostTasks(fPostTasksSet[kTrainOn]);
+    fill.AddPostTasks(fPostTasks);
+    if (!fill.Process(plistx))
+        return kFALSE;
+
+    // Check the number or read events
+    const Int_t numgammastrn = train.GetNumRows();
+    if (numgammastrn==0)
+    {
+        *fLog << err << "ERROR - No gammas available for training... aborting." << endl;
+        return kFALSE;
+    }
+
+    // Remove possible post tasks
+    fill.ClearPreTasks();
+    fill.ClearPostTasks();
+
+    // Set classifier for background
+    had.SetVal(1);
+    wgt.SetVal(1);
+
+    // In case of wobble mode we have to do something special
+    MSrcPosRndm srcrndm;
+    srcrndm.SetDistOfSource(0.4);
+
+    MHillasCalc hcalc;
+    MHillasCalc hcalc2;
+    hcalc.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetNameHillasSrc("MHillasSrcAnti");
+    hcalc2.SetNameSrcPosCam("MSrcPosAnti");
+
+    if (fDataSetTrain.IsWobbleMode())
+    {
+        scalc.SetMode(MSrcPosCalc::kWobble); // kWobble for off-source
+        fPreTasksSet[kTrainOff].AddFirst(&hcalc2);
+        fPreTasksSet[kTrainOff].AddFirst(&hcalc);
+        //fPreTasksSet[kTrainOff].AddFirst(&srcrndm);
+        fPreTasksSet[kTrainOff].AddFirst(&scor);
+        fPreTasksSet[kTrainOff].AddFirst(&scalc);
+    }
+
+    // Setup the tool class to read the background and read them
+    fill.SetName("FillBackground");
+    fill.SetDestMatrix1(&train, fNum[kTrainOff]);
+    fill.SetReader(&read3);
+    fill.AddPreTasks(fPreTasksSet[kTrainOff]);
+    fill.AddPreTasks(fPreTasks);
+    fill.AddPostTasks(fPostTasksSet[kTrainOff]);
+    fill.AddPostTasks(fPostTasks);
+    if (!fill.Process(plistx))
+        return kFALSE;
+
+    // Check the number or read events
+    const Int_t numbackgrndtrn = train.GetNumRows()-numgammastrn;
+    if (numbackgrndtrn==0)
+    {
+        *fLog << err << "ERROR - No background available for training... aborting." << endl;
+        return kFALSE;
+    }
+
+    // ------------------------ Train RF --------------------------
+
+    MRanForestCalc rf("TrainSeparation", fTitle);
+    rf.SetNumTrees(fNumTrees);
+    rf.SetNdSize(fNdSize);
+    rf.SetNumTry(fNumTry);
+    rf.SetNumObsoleteVariables(1);
+    rf.SetLastDataColumnHasWeights(fEnableWeights[kTrainOn] || fEnableWeights[kTrainOff]);
+    rf.SetDebug(fDebug>1);
+    rf.SetDisplay(fDisplay);
+    rf.SetLogStream(fLog);
+    rf.SetFileName(out);
+    rf.SetNameOutput("MHadronness");
+
+    // Train the random forest either by classification or regression
+    if (fUseRegression)
+    {
+        if (!rf.TrainRegression(train)) // regression
+            return kFALSE;
+    }
+    else
+    {
+        if (!rf.TrainSingleRF(train))   // classification
+            return kFALSE;
+    }
+
+    // Output information about what was going on so far.
+    *fLog << all;
+    fLog->Separator("The forest was trained with...");
+
+    *fLog << "Training method:" << endl;
+    *fLog << " * " << (fUseRegression?"regression":"classification") << endl;
+    if (fEnableWeights[kTrainOn])
+        *fLog << " * weights for on-data" << endl;
+    if (fEnableWeights[kTrainOff])
+        *fLog << " * weights for off-data" << endl;
+    if (fDataSetTrain.IsWobbleMode())
+        *fLog << " * random source position in a distance of 0.4°" << endl;
+    *fLog << endl;
+    *fLog << "Events used for training:"   << endl;
+    *fLog << " * Gammas:     " << numgammastrn   << endl;
+    *fLog << " * Background: " << numbackgrndtrn << endl;
+    *fLog << endl;
+    *fLog << "Gamma/Background ratio:" << endl;
+    *fLog << " * Requested:  " << (float)fNum[kTrainOn]/fNum[kTrainOff] << endl;
+    *fLog << " * Result:     " << (float)numgammastrn/numbackgrndtrn << endl;
+    *fLog << endl;
+    *fLog << "Run-Time: " << Form("%.1f", clock.RealTime()/60) << "min (CPU: ";
+    *fLog << Form("%.1f", clock.CpuTime()/60) << "min)" << endl;
+    *fLog << endl;
+    *fLog << "Output file name: " << out << endl;
+
+    // Chekc if testing is requested
+    if (!fDataSetTest.IsValid())
+        return kTRUE;
+
+    // --------------------- Display result ----------------------
+    fLog->Separator("Test");
+
+    clock.Continue();
+
+    // Setup parlist and tasklist for testing
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(this); // Take care of display
+    plist.AddToList(&tlist);
+
+    MMcEvt mcevt;
+    plist.AddToList(&mcevt);
+
+    plist.AddToList(&wgt);
+
+    // ----- Setup histograms -----
+    MBinning binsy(50, 0 , 1,      "BinningMH3Y", "lin");
+    MBinning binsx(40, 10, 100000, "BinningMH3X", "log");
+
+    plist.AddToList(&binsx);
+    plist.AddToList(&binsy);
+
+    MH3 h31("MHillas.fSize",  "MHadronness.fVal");
+    MH3 h32("MHillas.fSize",  "MHadronness.fVal");
+    MH3 h40("MMcEvt.fEnergy", "MHadronness.fVal");
+    h31.SetTitle("Background probability vs. Size:Size [phe]:Hadronness h");
+    h32.SetTitle("Background probability vs. Size:Size [phe]:Hadronness h");
+    h40.SetTitle("Background probability vs. Energy:Energy [GeV]:Hadronness h");
+
+    MHHadronness hist;
+
+    // ----- Setup tasks -----
+    MFillH fillh0(&hist, "", "FillHadronness");
+    MFillH fillh1(&h31);
+    MFillH fillh2(&h32);
+    MFillH fillh4(&h40);
+    fillh0.SetWeight("MWeight");
+    fillh1.SetWeight("MWeight");
+    fillh2.SetWeight("MWeight");
+    fillh4.SetWeight("MWeight");
+    fillh1.SetDrawOption("colz profy");
+    fillh2.SetDrawOption("colz profy");
+    fillh4.SetDrawOption("colz profy");
+    fillh1.SetNameTab("Background");
+    fillh2.SetNameTab("GammasH");
+    fillh4.SetNameTab("GammasE");
+    fillh0.SetBit(MFillH::kDoNotDisplay);
+
+    // ----- Setup filter -----
+    MFilterList precuts;
+    precuts.AddToList(fPreCuts);
+    precuts.AddToList(fTestCuts);
+
+    MContinue c0(&precuts);
+    c0.SetName("PreCuts");
+    c0.SetInverted();
+
+    MFEventSelector sel; // FIXME: USING IT (WITH PROB?) in READ will by much faster!!!
+    sel.SetNumSelectEvts(fNum[kTestOff]);
+
+    MContinue c1(&sel);
+    c1.SetInverted();
+
+    // ----- Setup tasklist -----
+    tlist.AddToList(&read2);
+    if (fDataSetTest.IsWobbleMode())
+    {
+        tlist.AddToList(&srcrndm);
+        tlist.AddToList(&hcalc);
+    }
+    tlist.AddToList(&c1);
+    tlist.AddToList(fPreTasksSet[kTestOff]);
+    tlist.AddToList(fPreTasks);
+    tlist.AddToList(&c0);
+    tlist.AddToList(&rf);
+    tlist.AddToList(fPostTasksSet[kTestOff]);
+    tlist.AddToList(fPostTasks);
+    tlist.AddToList(&fillh0);
+    tlist.AddToList(&fillh1);
+
+    // Enable Acceleration
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    // ----- Run eventloop on background -----
+    MEvtLoop loop;
+    loop.SetDisplay(fDisplay);
+    loop.SetLogStream(fLog);
+    loop.SetParList(&plist);
+    //if (!SetupEnv(loop))
+    //   return kFALSE;
+
+    wgt.SetVal(1);
+    if (!loop.Eventloop())
+        return kFALSE;
+ /*
+    if (!loop.GetDisplay())
+    {
+        gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+        return kFALSE;
+    }
+   */
+    // ----- Setup and run eventloop on gammas -----
+    sel.SetNumSelectEvts(fNum[kTestOn]);
+    fillh0.ResetBit(MFillH::kDoNotDisplay);
+
+    // Remove PreTasksOff and PostTasksOff from the list
+    tlist.RemoveFromList(fPreTasksSet[kTestOff]);
+    tlist.RemoveFromList(fPostTasksSet[kTestOff]);
+
+    // replace the reading task by a new one
+    tlist.Replace(&read4);
+
+    if (fDataSetTest.IsWobbleMode())
+    {
+        // *******************************************************************
+        // Possible source position (eg. Wobble Mode)
+        if (fDataSetTest.HasSource())
+        {
+            if (!fDataSetTest.GetSourcePos(source))
+                return -1;
+            *fLog << all;
+            source.Print("RaDec");
+        }
+        else
+            *fLog << all << "No source position applied..." << endl;
+
+        // La Palma Magic1
+        plist.AddToList(&obs);
+        plist.AddToList(&source);
+
+        // How to get source position from off- and on-data?
+        tlist.AddToListAfter(&scalc,  &read4);
+        tlist.AddToListAfter(&scor,   &scalc);
+        tlist.AddToListAfter(&hcalcw, &scor);
+
+        tlist.AddToList(&devcalc, "Starguider");
+        // *******************************************************************
+    }
+
+    // Add the PreTasksOn directly after the reading task
+    tlist.AddToListAfter(fPreTasksSet[kTestOn], &c1);
+
+    // Add the PostTasksOn after rf
+    tlist.AddToListAfter(fPostTasksSet[kTestOn], &rf);
+
+    // Replace fillh1 by fillh2
+    tlist.Replace(&fillh2);
+
+    // Add fillh4 after the new fillh2
+    tlist.AddToListAfter(&fillh4, &fillh2);
+
+    // Enable Acceleration
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    wgt.SetVal(1);
+    if (!loop.Eventloop())
+        return kFALSE;
+
+    // Show what was going on in the testing
+    const Double_t numgammastst   = h32.GetHist().GetEntries();
+    const Double_t numbackgrndtst = h31.GetHist().GetEntries();
+
+    *fLog << all;
+    fLog->Separator("The forest was tested with...");
+    *fLog << "Test method:" << endl;
+    *fLog << " * Random Forest: " << out << endl;
+    if (fEnableWeights[kTestOn])
+        *fLog << " * weights for on-data" << endl;
+    if (fEnableWeights[kTestOff])
+        *fLog << " * weights for off-data" << endl;
+    if (fDataSetTrain.IsWobbleMode())
+        *fLog << " * random source position in a distance of 0.4°" << endl;
+    *fLog << endl;
+    *fLog << "Events used for test:"   << endl;
+    *fLog << " * Gammas:     " << numgammastst   << endl;
+    *fLog << " * Background: " << numbackgrndtst << endl;
+    *fLog << endl;
+    *fLog << "Gamma/Background ratio:" << endl;
+    *fLog << " * Requested:  " << (float)fNum[kTestOn]/fNum[kTestOff] << endl;
+    *fLog << " * Result:     " << (float)numgammastst/numbackgrndtst << endl;
+    *fLog << endl;
+
+    // Display the result plots
+    DisplayResult(h31, h32, ontime);
+
+    *fLog << "Total Run-Time: " << Form("%.1f", clock.RealTime()/60) << "min (CPU: ";
+    *fLog << Form("%.1f", clock.CpuTime()/60) << "min)" << endl;
+    fLog->Separator();
+
+    fDataSetTrain.SetName("DataSetTrain");
+    fDataSetTest.SetName("DataSetTest");
+
+    // Write the display
+    TObjArray arr;
+    arr.Add(const_cast<MDataSet*>(&fDataSetTrain));
+    arr.Add(const_cast<MDataSet*>(&fDataSetTest));
+    if (fDisplay)
+        arr.Add(fDisplay);
+
+    SetPathOut(out);
+    return WriteContainer(arr, 0, "UPDATE");
+}
Index: branches/Mars_McMismatchStudy/mjtrain/MJTrainSeparation.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/MJTrainSeparation.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/MJTrainSeparation.h	(revision 17960)
@@ -0,0 +1,109 @@
+#ifndef MARS_MJTrainSeparation
+#define MARS_MJTrainSeparation
+
+#ifndef MARS_MJTrainRanForest
+#include "MJTrainRanForest.h"
+#endif
+
+#ifndef MARS_MDataSet
+#include "MDataSet.h"
+#endif
+
+class MH3;
+
+class MJTrainSeparation : public MJTrainRanForest
+{
+public:
+    enum Type_t { kTrainOn, kTrainOff, kTestOn, kTestOff };
+
+private:
+    MDataSet fDataSetTest;
+    MDataSet fDataSetTrain;
+
+    UInt_t fNum[4];
+
+    TList fPreTasksSet[4];
+    TList fPostTasksSet[4];
+
+    Bool_t fAutoTrain;
+    Bool_t fUseRegression;
+
+    Bool_t fEnableWeights[4];
+
+    Float_t fFluxTrain;
+    Float_t fFluxTest;
+
+    // Result
+    void     DisplayResult(MH3 &h31, MH3 &h32, Float_t ontime);
+
+    // Auto training
+    Bool_t   GetEventsProduced(MDataSet &set, Double_t &num, Double_t &min, Double_t &max) const;
+    Double_t GetDataRate(MDataSet &set, Double_t &num) const;
+    Double_t GetNumMC(MDataSet &set) const;
+    Float_t  AutoTrain(MDataSet &set, Type_t typon, Type_t typoff, Float_t flux);
+
+public:
+    MJTrainSeparation() :
+        fAutoTrain(kFALSE), fUseRegression(kFALSE),
+        fFluxTrain(2e-7), fFluxTest(2e-7)
+    { for (int i=0; i<4; i++) { fEnableWeights[i]=kFALSE; fNum[i] = (UInt_t)-1; } }
+
+    void SetDataSetTrain(const MDataSet &ds, UInt_t non=(UInt_t)-1, UInt_t noff=(UInt_t)-1)
+    {
+        ds.Copy(fDataSetTrain);
+
+        fDataSetTrain.SetNumAnalysis(1);
+
+        fNum[kTrainOn]  = non;
+        fNum[kTrainOff] = noff;
+    }
+    void SetDataSetTest(const MDataSet &ds, UInt_t non=(UInt_t)-1, UInt_t noff=(UInt_t)-1)
+    {
+        ds.Copy(fDataSetTest);
+
+        fDataSetTest.SetNumAnalysis(1);
+
+        fNum[kTestOn]  = non;
+        fNum[kTestOff] = noff;
+    }
+
+    // Deprecated, used for test purpose
+    void AddPreTask(Type_t typ, MTask *t)                                      { Add(fPreTasksSet[typ],  t); }
+    void AddPreTask(Type_t typ, const char *rule, const char *name="MWeight")  { AddPar(fPreTasksSet[typ], rule, name); }
+
+    void AddPostTask(Type_t typ, MTask *t)                                     { Add(fPostTasksSet[typ],  t); }
+    void AddPostTask(Type_t typ, const char *rule, const char *name="MWeight") { AddPar(fPostTasksSet[typ], rule, name); }
+
+    void SetWeights(Type_t typ, const char *rule)  { if (fEnableWeights[typ]) return; fEnableWeights[typ]=kTRUE; AddPostTask(typ, rule); }
+    void SetWeights(Type_t typ, MTask *t)          { if (fEnableWeights[typ]) return; fEnableWeights[typ]=kTRUE; AddPostTask(typ, t); }
+
+    // Standard user interface
+    void AddPreTaskOn(MTask *t)                                       { AddPreTask(kTrainOn, t); AddPreTask(kTestOn, t); }
+    void AddPreTaskOn(const char *rule, const char *name="MWeight")   { AddPreTask(kTrainOn, rule, name); AddPreTask(kTestOn, rule, name); }
+    void AddPreTaskOff(MTask *t)                                      { AddPreTask(kTrainOff, t); AddPreTask(kTestOff, t); }
+    void AddPreTaskOff(const char *rule, const char *name="MWeight")  { AddPreTask(kTrainOff, rule, name); AddPreTask(kTestOff, rule, name); }
+
+    void AddPostTaskOn(MTask *t)                                      { AddPostTask(kTrainOn, t); AddPostTask(kTestOn, t); }
+    void AddPostTaskOn(const char *rule, const char *name="MWeight")  { AddPostTask(kTrainOn, rule, name); AddPostTask(kTestOn, rule, name); }
+    void AddPostTaskOff(MTask *t)                                     { AddPostTask(kTrainOff, t); AddPostTask(kTestOff, t); }
+    void AddPostTaskOff(const char *rule, const char *name="MWeight") { AddPostTask(kTrainOff, rule, name); AddPostTask(kTestOff, rule, name); }
+
+    void SetWeightsOn(const char *rule)  { SetWeights(kTrainOn, rule); SetWeights(kTestOn, rule); }
+    void SetWeightsOn(MTask *t)          { SetWeights(kTrainOn, t); SetWeights(kTestOn, t); }
+    void SetWeightsOff(const char *rule) { SetWeights(kTrainOff, rule); SetWeights(kTestOff, rule); }
+    void SetWeightsOff(MTask *t)         { SetWeights(kTrainOff, t); SetWeights(kTestOff, t); }
+
+    void SetFluxTrain(Float_t f) { fFluxTrain = f; }
+    void SetFluxTest(Float_t f)  { fFluxTest  = f; }
+    void SetFlux(Float_t f)      { SetFluxTrain(f); SetFluxTest(f); }
+
+    void EnableAutoTrain(Bool_t b=kTRUE)      { fAutoTrain     =  b; }
+    void EnableRegression(Bool_t b=kTRUE)     { fUseRegression =  b; }
+    void EnableClassification(Bool_t b=kTRUE) { fUseRegression = !b; }
+
+    Bool_t Train(const char *out);
+
+    ClassDef(MJTrainSeparation, 0)//Class to train Random Forest gamma-/background-separation
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mjtrain/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/Makefile	(revision 17960)
@@ -0,0 +1,39 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Train
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mfbase -I../mdata -I../mfileio \
+           -I../manalysis -I../mfilter -I../mjobs -I../mtools \
+           -I../mranforest -I../mhflux -I../mmc -I../mhist -I../mpointing \
+           -I../mimage -I../mjoptim
+
+SRCFILES = MJTrainRanForest.cc \
+	   MJTrainEnergy.cc \
+           MJTrainDisp.cc \
+           MJTrainImpact.cc \
+           MJTrainSeparation.cc \
+           MJTrainCuts.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mjtrain/TrainIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/TrainIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/TrainIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mjtrain/TrainLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mjtrain/TrainLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mjtrain/TrainLinkDef.h	(revision 17960)
@@ -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 MJTrainRanForest+;
+#pragma link C++ class MJTrainEnergy+;
+#pragma link C++ class MJTrainDisp+;
+#pragma link C++ class MJTrainImpact+;
+#pragma link C++ class MJTrainSeparation+;
+#pragma link C++ class MJTrainCuts+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mmain/MAnalysis.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MAnalysis.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MAnalysis.cc	(revision 17960)
@@ -0,0 +1,326 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 9/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MAnalysis.h"
+
+#include <iostream>
+
+#include <TGLabel.h>       // TGlabel
+#include <TGButton.h>      // TGTextButton
+#include <TGTextEntry.h>   // TGNumberEntry
+
+#include "MGList.h"
+#include "MImgCleanStd.h"  // MImgCleanStd
+
+ClassImp(MAnalysis);
+
+using namespace std;
+
+enum {
+    kButHillas = 0x100
+};
+
+void MAnalysis::AddButtons()
+{
+    TGTextButton *hillas = new TGTextButton(fTop2, "Calculate Standard Hillas", kButHillas);
+
+    hillas->Associate(this);
+
+    fList->Add(hillas);
+
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsCenterY|kLHintsLeft, 10, 10, 5, 5);
+    fList->Add(laybut);
+
+    fTop2->AddFrame(hillas, laybut);
+}
+
+void MAnalysis::AddSetupTab()
+{
+    //
+    // Create Setup Tab
+    //
+    TGCompositeFrame *frame = CreateNewTab("Setup");
+ /*
+    TGGroupFrame *grp = new TGGroupFrame(frame, "Setup Display");
+    fList->Add(grp);
+
+    //
+    // Align the lines:
+    //  - top, left
+    //  - padding: top=20, bottom=0, left=20, right=0
+    //
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsNormal, 10, 10, 10);
+    fList->Add(laybut);
+
+    //
+    // Create check buttons for the first two lines
+    //
+    fCheckButton1 = new TGCheckButton(grp, "Display Hillas Histograms when finished");  //, M_CHECK_DISPLHIL);
+    fCheckButton2 = new TGCheckButton(grp, "Display Star Map Histogram when finished"); //, M_CHECK_DISPLHIL);
+
+    fList->AddFirst(fCheckButton1);
+    fList->AddFirst(fCheckButton2);
+
+    //
+    // Create first two lines with the checkbuttons
+    //
+    grp->AddFrame(fCheckButton1, laybut);
+    grp->AddFrame(fCheckButton2, laybut);
+ */
+    TGLayoutHints *laygrp = new TGLayoutHints(kLHintsNormal|kLHintsExpandX, 20, 20, 20);
+    fList->Add(laygrp);
+ /*
+    frame->AddFrame(grp, laygrp);
+  */
+
+    /*
+     * Create GUI for image cleaning
+     */
+    fImgClean = new MImgCleanStd;
+    fImgClean->CreateGui(frame, laygrp);
+    fList->Add(fImgClean);
+}
+
+MAnalysis::MAnalysis(/*const TGWindow *main,*/ const TGWindow *p,
+                     const UInt_t w, const UInt_t h)
+: MBrowser(/*main,*/ p, w, h)
+{
+    AddButtons();
+    AddSetupTab();
+
+    MapSubwindows();
+
+    Layout();
+
+    SetWindowName("Analysis Window");
+    SetIconName("Analysis");
+
+    MapWindow();
+}
+
+// ======================================================================
+
+#include "MStatusDisplay.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamMagic.h"
+#include "MHHillas.h"
+#include "MHStarMap.h"
+#include "MReadMarsFile.h"
+#include "MMcPedestalCopy.h"     // MMcPedestalCopy
+#include "MMcPedestalNSBAdd.h"   // MMcPedestalNSB
+#include "MCerPhotCalc.h"
+#include "MImgCleanStd.h"
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+#include "MSrcPosCam.h"
+#include "MFillH.h"
+#include "MEvtLoop.h"
+#include "MHillas.h"
+#include "MGeomApply.h"
+
+void MAnalysis::CalculateHillas()
+{
+    //
+    // This is a demonstration program which calculates the Hillas
+    // parameter out of a Magic root file.
+
+    const Bool_t displhillas  = kTRUE;//fCheckButton1->GetState();
+    const Bool_t displstarmap = kTRUE;//fCheckButton2->GetState();
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // The geometry container must be created by yourself to make sure
+    // that you don't choos a wrong geometry by chance
+    //
+    MGeomCamMagic geomcam;
+    plist.AddToList(&geomcam);
+
+    MSrcPosCam source;
+    plist.AddToList(&source);
+    /*
+     MSrcPosCam source("Source");
+     source.SetXY(0, 0);
+     plist.AddToList(&source);
+
+     MSrcPosCam antisrc("AntiSrc");
+     antisrc.SetXY(240, 0);
+     plist.AddToList(&antisrc);
+     */
+
+    //
+    // Now setup the tasks and tasklist:
+    //
+    //  1) read in the data from a magic root file   MReadTree
+    //  2) calculate number of cerenkov photons      MCerPhotCalc
+    //  3) clean the image                           MImgCleanStd
+    //  4) calculate hillas                          MHillasCalc
+    //  5) fill the hillas into the histograms       MFillH
+    //
+
+    //
+    // The first argument is the tree you want to read.
+    //   Events:     Cosmic ray events
+    //   PedEvents:  Pedestal Events
+    //   CalEvents:  Calibration Events
+    //
+    MReadMarsFile read("Events", fInputFile);
+    //read.DisableAutoScheme();
+
+    MGeomApply         apply;
+    MMcPedestalCopy    pcopy;
+    MMcPedestalNSBAdd  pdnsb;
+    MCerPhotCalc       ncalc;
+    //MBlindPixelCalc    blind;
+    MHillasCalc        hcalc;
+    MHillasSrcCalc     csrc1;
+    /*
+     MHillasSrcCalc     csrc1("Source",  "HillasSource");
+     MHillasSrcCalc     csrc2("AntiSrc", "HillasAntiSrc");
+     */
+
+    MFillH hfill("MHHillas",       "MHillas");
+    MFillH hfill2("MHHillasExt",   "MHillasSrc");
+    MFillH hfill2s("MHHillasSrc",  "MHillasSrc");
+    MFillH hfill3("MHNewImagePar", "MNewImagePar");
+    MFillH sfill("MHStarMap",      "MHillas");
+    /*
+     MFillH hfill2s("HistSource  [MHHillasSrc]", "HillasSource");
+     MFillH hfill2a("HistAntiSrc [MHHillasSrc]", "HillasAntiSrc");
+     */
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pdnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(fImgClean);
+    //tlist.AddToList(&blind);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&csrc1);
+    //tlist.AddToList(&csrc2);
+
+    if (displhillas)
+    {
+        tlist.AddToList(&hfill);
+        tlist.AddToList(&hfill2);
+        tlist.AddToList(&hfill2s);
+        tlist.AddToList(&hfill3);
+    }
+
+    if (displstarmap)
+        tlist.AddToList(&sfill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Add ProgressBar to window
+    //
+    TGProgressBar *bar = NULL;
+    if (displhillas || displstarmap)
+    {
+        MStatusDisplay *d=new MStatusDisplay;
+        evtloop.SetDisplay(d);
+    }
+    else
+    {
+        bar = CreateProgressBar(fTop2);
+        evtloop.SetProgressBar(bar);
+    }
+
+
+    //
+    // Execute your analysis
+    //
+    /*Bool_t rc =*/ evtloop.Eventloop();
+
+    //
+    // Remove progressbar from window
+    //
+    if (bar)
+        DestroyProgressBar(bar);
+
+ /*
+    if (!rc)
+        return;
+
+    //
+    // After the analysis is finished we can display the histograms
+    //
+    if (displhillas)
+    {
+        plist.FindObject("MHHillas")->DrawClone();
+        plist.FindObject("MHHillasExt")->DrawClone();
+        plist.FindObject("MHHillasSrc")->DrawClone();
+        plist.FindObject("MHNewImagePar")->DrawClone();
+    }
+
+    if (displstarmap)
+        plist.FindObject("MHStarMap")->DrawClone();
+
+    cout << endl;
+    cout << "Calculation of Hillas Parameters finished without error!" << endl;
+ */
+}
+
+// ======================================================================
+
+Bool_t MAnalysis::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+{
+    // Process events generated by the buttons in the frame.
+
+    if (GET_MSG(msg)!=kC_COMMAND || GET_SUBMSG(msg)!=kCM_BUTTON)
+        return MBrowser::ProcessMessage(msg, parm1, parm2);
+
+    switch (parm1)
+    {
+    case kButHillas:
+        if (!InputFileSelected())
+        {
+            DisplError("No Input (root) File selected!");
+            return kTRUE;
+        }
+
+        switch (parm1)
+        {
+        case kButHillas:
+            CalculateHillas();
+            return kTRUE;
+        }
+        return kTRUE;
+    }
+
+    return MBrowser::ProcessMessage(msg, parm1, parm2);
+}
Index: branches/Mars_McMismatchStudy/mmain/MAnalysis.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MAnalysis.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MAnalysis.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MBrowser.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MBrowser.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MBrowser.cc	(revision 17960)
@@ -0,0 +1,604 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+#include "MBrowser.h"
+
+#include <iostream>
+#include <sys/stat.h>       // S_ISDIR
+
+#include <TSystem.h>        // gSystem
+
+#include <TGTab.h>          // TGTab
+#include <TGMenu.h>         // TGPopupMenu
+#include <TG3DLine.h>       // TGHorizontal3DLine
+#include <TGButton.h>       // TGTextButton
+#include <TGMsgBox.h>       // TGMsgBox
+#include <TBrowser.h>       // TBrowser
+#include <TGTextEntry.h>    // TGTextEntry
+#include <TGFSComboBox.h>   // TGFSComboBox, TGFSLboxEntry
+#include <TGProgressBar.h>  // TGHProgressBar
+#include <TGFSContainer.h>  // TGFileContainer
+
+#include "MGList.h"
+
+ClassImp(MBrowser);
+
+using namespace std;
+
+enum {
+    kFileTBrowser,
+    kFileClose,
+    kButDirUp,
+    kButListMode,
+    kButDetailMode,
+    kCBDirectory,
+    kCBFilter,
+    kTEFileName
+};
+
+void MBrowser::CreateMenuBar()
+{
+    //
+    //  crate the menu bar
+    //
+    TGPopupMenu *filemenu = new TGPopupMenu(gClient->GetRoot());
+    filemenu->AddEntry("Open &TBrowser", kFileTBrowser);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("&Close", kFileClose);
+    filemenu->Associate(this);
+    fList->Add(filemenu);
+
+    //
+    //  the button messages are handled by main frame (this)
+    //
+    TGLayoutHints *laymenubar  = new TGLayoutHints(kLHintsTop|kLHintsLeft|kLHintsExpandX, 2, 2, 2, 2);
+    TGLayoutHints *laymenuitem = new TGLayoutHints(kLHintsTop|kLHintsLeft, 0, 4, 0, 0);
+
+    fList->Add(laymenubar);
+    fList->Add(laymenuitem);
+
+    TGMenuBar *menubar = new TGMenuBar(this, 1, 1, kHorizontalFrame);
+    menubar->AddPopup("&File", filemenu, laymenuitem);
+    AddFrame(menubar, laymenubar);
+    fList->Add(menubar);
+}
+
+void MBrowser::CreateUpperFrame(TGCompositeFrame *frametop)
+{
+    TGLayoutHints *lay1 = new TGLayoutHints(kLHintsTop    |kLHintsExpandX, 2, 2, 2, 0);
+    TGLayoutHints *lay2 = new TGLayoutHints(kLHintsCenterY|kLHintsExpandX, 2, 2, 2, 2);
+    TGLayoutHints *lay3 = new TGLayoutHints(kLHintsBottom |kLHintsExpandX, 2, 2, 0, 2);
+    fList->Add(lay1);
+    fList->Add(lay2);
+    fList->Add(lay3);
+
+    //
+    // *********** Create Contents of frame top (upper part) **********
+    //
+    fTop1 = new TGHorizontalFrame(frametop, 500, 50);
+    fTop2 = new TGHorizontalFrame(frametop, 500, 50);
+    fTop3 = new TGHorizontalFrame(frametop, 500, 50);
+
+    // FIXME: If I use TGLayoutHints the Progress Bar doesn't disappear!
+    frametop->AddFrame(fTop1);//, lay1);
+    frametop->AddFrame(fTop2);//, lay2);
+    frametop->AddFrame(fTop3);//, lay3);
+
+    fList->Add(fTop1);
+    fList->Add(fTop2);
+    fList->Add(fTop3);
+}
+
+void MBrowser::CreateDirListMenu(TGCompositeFrame *frame)
+{
+    //
+    // Layout Dir-Listbox and buttons in one row (frame)
+    //
+    //  - layout:
+    //    alignment: top, left
+    //    padding:   5, 5, 5, 5
+    //
+    TGLayoutHints *laydir = new TGLayoutHints(kLHintsExpandX|kLHintsLeft|kLHintsCenterY); //, 5, 5, 5, 5);
+    TGLayoutHints *layout = new TGLayoutHints(kLHintsRight|kLHintsCenterY, 10); //, 5, 5, 5);
+
+    fList->Add(laydir);
+    fList->Add(layout);
+
+    //
+    // Create Dir-Listbox and buttons in first frame
+    //
+    TGFSComboBox *dir = new TGFSComboBox(frame, kCBDirectory);
+    dir->SetHeight(fEntry->GetHeight());
+    dir->Associate(this);
+    fList->Add(dir);
+    frame->AddFrame(dir, laydir);
+
+    const TGPicture *pic0 = fList->GetPicture("magic_t.xpm");
+    if (pic0)
+    {
+        dir->GetListBox()->Resize(100, 150);
+        TGTreeLBEntry *entry = new TGTreeLBEntry(dir->GetListBox()->GetContainer(),
+                                                 new TGString("/magic/data"), pic0, 6000,
+                                                 new TGString("/magic/data"));
+        TGLayoutHints *laylb = new TGLayoutHints(kLHintsLeft|kLHintsTop, 14, 0, 0, 0);
+        dir->AddEntry(entry, laylb);
+        // Not necessary - deleted in ~TGLBContainer: fList->Add(laylb);
+        // fList->Add(laylb);
+    }
+
+    //
+    // Get the three picturs from the system (must be deleted by FreePicture)
+    //
+    const TGPicture *pic1 = fList->GetPicture("tb_list.xpm");
+    if (pic1)
+    {
+        TGPictureButton *list = new TGPictureButton(frame, pic1, kButListMode);
+        list->SetToolTipText("List Mode");
+        list->SetState(kButtonUp);
+        list->AllowStayDown(kTRUE);
+        list->Associate(this);
+        fList->Add(list);
+        frame->AddFrame(list, layout);
+    }
+
+    const TGPicture *pic2 = fList->GetPicture("tb_details.xpm");
+    if (pic2)
+    {
+        TGPictureButton *detail = new TGPictureButton(frame, pic2, kButDetailMode);
+        detail->SetToolTipText("Details Mode");
+        detail->SetState(kButtonEngaged);
+        detail->AllowStayDown(kTRUE);
+        detail->Associate(this);
+        fList->Add(detail);
+        frame->AddFrame(detail, layout);
+    }
+
+    const TGPicture *pic3 = fList->GetPicture("tb_uplevel.xpm");
+    if (pic3)
+    {
+        TGPictureButton *cdup = new TGPictureButton(frame, pic3, kButDirUp);
+        cdup->SetToolTipText("One Level up!");
+        cdup->Associate(this);
+        fList->Add(cdup);
+        frame->AddFrame(cdup, layout);
+    }
+}
+
+void MBrowser::CreateDirListBox(TGCompositeFrame *frame)
+{
+    //
+    // Create file viewer (browser)
+    //
+    fFileView = new TGListView(frame, 540, 380);
+    fList->Add(fFileView);
+
+    TGViewPort *port = fFileView->GetViewPort();
+    port->SetBackgroundColor(fgWhitePixel);
+
+    fFileCont = new TGFileContainer(port, 100, 100, kVerticalFrame, fgWhitePixel);
+    fList->Add(fFileCont);
+
+    fFileView->SetContainer(fFileCont);
+    fFileView->SetViewMode(kLVDetails);
+
+    fFileCont->SetFilter("*.root");
+    fFileCont->Associate(this);
+    fFileCont->Sort(kSortByName);
+
+    TGLayoutHints *layview = new TGLayoutHints(kLHintsTop|kLHintsExpandX|kLHintsExpandY); //, 5, 5, 5, 5);
+    fList->Add(layview);
+
+    frame->AddFrame(fFileView, layview);
+}
+
+void MBrowser::CreateTab1()
+{
+    static const char *filters[] =
+    {
+        "*.root <root-files>",
+        "*      <All Files>",
+        NULL
+    };
+
+    TGCompositeFrame *frame = CreateNewTab("Input File");
+
+    //
+    // Create three frames for the first tab
+    //
+    TGHorizontalFrame *tab1 = new TGHorizontalFrame(frame, 100, 100);
+    TGVerticalFrame   *tab2 = new TGVerticalFrame  (frame, 100, 100);
+
+    TGLayoutHints *laytab1   = new TGLayoutHints(kLHintsNormal|kLHintsExpandX,  10, 10, 10);
+    TGLayoutHints *laytab2   = new TGLayoutHints(kLHintsExpandX|kLHintsExpandY, 10, 10, 10, 10);
+    TGLayoutHints *layfilter = new TGLayoutHints(kLHintsNormal|kLHintsExpandX,  10, 10, 10);
+
+    fEntry = new TGTextEntry(frame, "", kTEFileName);
+    fEntry->Associate(this);
+
+    TGComboBox *filter = new TGComboBox(frame, kCBFilter);
+    filter->SetHeight(fEntry->GetHeight());
+    filter->Associate(this);
+    for (int i=0; filters[i]; i++)
+        filter->AddEntry(filters[i], i);
+    filter->Select(0);
+
+    frame->AddFrame(fEntry, laytab1);
+    frame->AddFrame(tab1,   laytab1);
+    frame->AddFrame(filter, layfilter);
+    frame->AddFrame(tab2,   laytab2);
+
+    CreateDirListMenu(tab1);
+    CreateDirListBox(tab2);
+
+    fList->Add(laytab1);
+    fList->Add(laytab2);
+    fList->Add(tab1);
+    fList->Add(tab2);
+    fList->Add(layfilter);
+    fList->Add(fEntry);
+    fList->Add(filter);
+}
+
+TGCompositeFrame *MBrowser::CreateNewTab(const char *name)
+{
+    return fTabs->AddTab(name);
+}
+
+void MBrowser::CreateLowerFrame(TGCompositeFrame *framelow)
+{
+    //
+    // *********** Create Contents of frame low (downer part) **********
+    //
+
+    //
+    // ----- Create Object holding the Tabs -----
+    //
+    fTabs = new TGTab(framelow, 400, 400);
+    fList->Add(fTabs);
+
+    TGLayoutHints *laytabs = new TGLayoutHints(kLHintsBottom|kLHintsExpandX|kLHintsExpandY, 5, 5, 5, 5);
+    fList->Add(laytabs);
+
+    framelow->AddFrame(fTabs, laytabs);
+
+    //
+    // --- Create the first tab of the tabs ---
+    //
+    CreateTab1();
+}
+
+MBrowser::MBrowser(/*const TGWindow *main,*/ const TGWindow *p,
+                   const UInt_t w, const UInt_t h)
+//: TGTransientFrame(p?p:gClient->GetRoot(),
+//                   main?main:gClient->GetRoot(), w, h)
+: TGMainFrame(p?p:gClient->GetRoot(), w, h)
+{
+    fList = new MGList;
+    fList->SetOwner();
+
+    CreateMenuBar();
+
+    TGLayoutHints *laylinesep  = new TGLayoutHints(kLHintsTop|kLHintsExpandX);
+    fList->Add(laylinesep);
+
+    TGHorizontal3DLine *linesep = new TGHorizontal3DLine(this);
+    fList->Add(linesep);
+    AddFrame(linesep, laylinesep);
+
+    //
+    // ---- Create the top window with a lot of buttons ----
+    //
+    TGLayoutHints *layframetop = new TGLayoutHints(kLHintsExpandX);
+    fList->Add(layframetop);
+
+    TGCompositeFrame *frametop = new TGCompositeFrame(this, 300, 100, kVerticalFrame);
+    fList->Add(frametop);
+    AddFrame(frametop, layframetop);
+
+    linesep = new TGHorizontal3DLine(this);
+    fList->Add(linesep);
+    AddFrame(linesep, laylinesep);
+
+    //
+    // ---- Create the low window with a tabs in it ----
+    //
+    TGLayoutHints *layframelow = new TGLayoutHints(kLHintsExpandX|kLHintsExpandY);
+    fList->Add(layframelow);
+
+    TGCompositeFrame *framelow = new TGCompositeFrame(this, 300, 100, kHorizontalFrame);
+    fList->Add(framelow);
+
+    AddFrame(framelow, layframelow);
+
+    CreateUpperFrame(frametop);
+    CreateLowerFrame(framelow);
+
+    //
+    //   Map the window, set up the layout, etc.
+    //
+    ChangeDir();
+    SetWMSizeHints(400, 350, 1000, 1000, 10, 10); // set the smallest and biggest size of the Main frame
+    Move(rand()%100+50, rand()%100+50);
+}
+
+
+MBrowser::~MBrowser()
+{
+    delete fList;
+} 
+
+TGProgressBar *MBrowser::CreateProgressBar(TGHorizontalFrame *frame)
+{
+    static TGLayoutHints laybar(kLHintsCenterY|kLHintsRight/*|kLHintsExpandX*/,
+                                10, 10);
+
+    TGHProgressBar *bar=new TGHProgressBar(frame);
+
+    bar->SetWidth(150);
+    bar->ShowPosition();
+
+    frame->AddFrame(bar, &laybar);
+
+    Layout();
+    MapSubwindows();
+
+    return bar;
+}
+
+void MBrowser::DestroyProgressBar(TGProgressBar *bar)
+{
+    TGHorizontalFrame *frame = (TGHorizontalFrame*)bar->GetParent();
+
+    frame->RemoveFrame(bar);
+
+    Layout();
+    MapSubwindows();
+
+    delete bar;
+}
+
+void MBrowser::CloseWindow()
+{
+   // Got close message for this MainFrame. Calls parent CloseWindow()
+   // (which destroys the window) and terminate the application.
+   // The close message is generated by the window manager when its close
+   // window menu item is selected.
+
+    delete this;
+}
+
+Bool_t MBrowser::InputFileSelected() 
+{
+    //
+    // Checks if there is a selected input root file
+    //
+    return !fInputFile.IsNull(); //[0]!='\0';
+}
+
+void MBrowser::DisplError(const char *txt)
+{
+    Int_t retval;
+    new TGMsgBox(fClient->GetRoot(), this, "Error!", txt,
+                 kMBIconExclamation, 4, &retval);
+}
+
+void MBrowser::DisplWarning(const char *txt)
+{
+    Int_t retval;
+    new TGMsgBox(fClient->GetRoot(), this, "Warning!", txt,
+                 kMBIconExclamation, 4, &retval);
+}
+
+void MBrowser::DisplInfo(const char *txt)
+{
+    Int_t retval;
+    new TGMsgBox(fClient->GetRoot(), this, "Information!", txt,
+                 kMBIconExclamation, 4, &retval);
+}
+
+void MBrowser::ChangeDir(const char *txt)
+{
+    fFileCont->ChangeDirectory(txt?txt:gSystem->WorkingDirectory());
+
+    const char *dir = fFileCont->GetDirectory();
+
+    TGFSComboBox *cbox = (TGFSComboBox*)fList->FindWidget(kCBDirectory);
+    if (cbox)
+        cbox->Update(dir);
+}
+
+void MBrowser::SetFileName(TString name)
+{
+    if (name[0]!='/')
+    {
+        name.Insert(0, "/");
+        name.Insert(0, fFileCont->GetDirectory());
+    }
+
+    if (gSystem->AccessPathName(name, kFileExists))
+        return;
+
+    if (name.EndsWith(".root", TString::kIgnoreCase))
+        fInputFile = name;
+
+    fEntry->SetText(gSystem->BaseName(name));
+
+    ChangeDir(gSystem->DirName(name));
+}
+
+void MBrowser::SetDir()
+{
+    TGFSComboBox *cbox = (TGFSComboBox*)fList->FindWidget(kCBDirectory);
+    if(!cbox)
+        return;
+
+    const TGTreeLBEntry *entry = (TGTreeLBEntry*)cbox->GetSelectedEntry();
+
+    ChangeDir(entry->GetPath()->GetString());
+}
+
+void MBrowser::SetFilter()
+{
+    //
+    // Try to get widget from list
+    //
+    TGComboBox *filter = (TGComboBox*)fList->FindWidget(kCBFilter);
+    if (!filter)
+        return;
+
+    //
+    // Get the selected text from the list box
+    //
+    const TGTextLBEntry *selected = (TGTextLBEntry*)filter->GetListBox()->GetSelectedEntry();
+
+    //
+    // find filter and remove leading spaces
+    //
+    TString txt = selected->GetText()->GetString();
+    if (txt.First('<') < 0)
+        return;
+
+    //
+    // Set new filter and refresh the file container
+    //
+    txt.Remove(txt.First('<'));
+
+    TString ftxt = txt.Strip();
+    fFileCont->SetFilter(ftxt);
+    fFileCont->DisplayDirectory();
+}
+
+void MBrowser::SetViewMode(const Int_t mode)
+{
+    fFileView->SetViewMode(mode ? kLVList : kLVDetails);
+
+    TGButton *but = (TGButton*)fList->FindWidget(mode);
+    if(!but)
+        return;
+
+    but->SetState(kButtonUp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Process events generated by the gui elements in the frame.
+//
+Bool_t MBrowser::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
+{
+    switch (GET_MSG(msg))
+    {
+    case kC_TEXTENTRY:
+        if (GET_SUBMSG(msg)!=kTE_ENTER)
+            return kTRUE;
+
+        SetFileName(fEntry->GetText());
+        return kTRUE;
+
+    case kC_COMMAND:
+        switch (GET_SUBMSG(msg))
+        {
+        case kCM_MENU:
+            switch (parm1)
+            {
+            case kFileClose:
+                CloseWindow();
+                return kTRUE;
+
+            case kFileTBrowser:
+                new TBrowser();
+                return kTRUE;
+            }
+            return kTRUE;
+
+        case kCM_BUTTON:
+            switch (parm1)
+            {
+            case kButDirUp:
+                //
+                //  goto the parent directory
+                //
+                ChangeDir("..");
+                return kTRUE;
+
+            case kButListMode:
+            case kButDetailMode:
+                SetViewMode(parm1);
+                return kTRUE;
+            }
+            return kTRUE;
+
+        case kCM_COMBOBOX:
+            switch (parm1)
+            {
+            case kCBDirectory:
+                SetDir();
+                return kTRUE;
+            case kCBFilter:
+                SetFilter();
+                return kTRUE;
+            }
+            return kTRUE;
+        }
+        return kTRUE;
+
+    case kC_CONTAINER:
+        switch (GET_SUBMSG(msg))
+        {
+
+            //      case kCT_ITEMCLICK:
+            // 	printf ("itemclick\n");
+            //      break;
+
+        case kCT_ITEMDBLCLICK:
+            //
+            //  process the double click in the file view container
+            //
+            if (parm1 != kButton1 || fFileCont->NumSelected() != 1)
+                return kTRUE;
+
+            //
+            //  one file selected
+            //
+            void *dummy = NULL;
+            const TGFileItem *item = (TGFileItem *)fFileCont->GetNextSelected(&dummy);
+
+            const char *str = item->GetItemName()->GetString();
+
+            //
+            // if the user choose a directory
+            // change to this directory
+            //
+            if (S_ISDIR(item->GetType()))
+            {
+                ChangeDir(str);
+                return kTRUE;
+            }
+
+            SetFileName(str);
+            return kTRUE;
+        }
+    }
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mmain/MBrowser.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MBrowser.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MBrowser.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MCameraDisplay.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MCameraDisplay.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MCameraDisplay.cc	(revision 17960)
@@ -0,0 +1,110 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+#include "MCameraDisplay.h"
+
+#include <TGButton.h>  // TGTextButton
+
+#include "MGList.h"
+#include "MEventDisplay.h"
+
+ClassImp(MCameraDisplay);
+
+enum {
+    kButDisplay = 0x100
+};
+
+// --------------------------------------------------------------------------
+//
+//  Create the 'Data Check' GUI Controls (Window) on the screen. To use it
+//  from within the interpreter you can call a Standard Version with
+//  'new MCameraDisplay()'
+//
+MCameraDisplay::MCameraDisplay(/*const TGWindow *main,*/ const TGWindow *p,
+                               const UInt_t w, const UInt_t h)
+: MBrowser(/*main,*/ p, w, h)
+{
+    TGTextButton *disp = new TGTextButton(fTop2, "Display Events", kButDisplay);
+    fList->Add(disp);
+
+    disp->Associate(this);
+
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsTop|kLHintsLeft, 10, 10, 5, 5);
+    fList->Add(laybut);
+
+    fTop2->AddFrame(disp, laybut);
+
+/*
+    const TGPicture *pic2 = fList->GetPicture("marslogo.xpm");
+    if (pic2)
+    {
+        TGPictureButton *mars  = new TGPictureButton(fTop2, pic2, -1);
+        fList->Add(mars);
+        TGLayoutHints *lay2 = new TGLayoutHints(kLHintsRight, 10, 10, 10, 10);
+        fList->Add(lay2);
+        fTop2->AddFrame(mars,  lay2);
+    }
+  */
+    MapSubwindows();
+
+    Layout();
+
+    SetWindowName("Camera Display Window");
+    SetIconName("Camera Dsiplay");
+
+    MapWindow();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process the GUI control events (here: mainly button clicks)
+//
+Bool_t MCameraDisplay::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+{
+    // Process events generated by the buttons in the frame.
+
+    if (GET_MSG(msg)!=kC_COMMAND || GET_SUBMSG(msg)!=kCM_BUTTON)
+        return MBrowser::ProcessMessage(msg, parm1, parm2);
+
+    switch (parm1)
+    {
+    case kButDisplay:
+        if (!InputFileSelected())
+        {
+            DisplError("No Input (root) File selected!");
+            return kTRUE;
+        }
+
+        switch (parm1)
+        {
+        case kButDisplay:
+            new MEventDisplay(fInputFile);
+            return kTRUE;
+        }
+        return kTRUE;
+    }
+
+    return MBrowser::ProcessMessage(msg, parm1, parm2);
+}
Index: branches/Mars_McMismatchStudy/mmain/MCameraDisplay.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MCameraDisplay.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MCameraDisplay.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MDataCheck.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MDataCheck.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MDataCheck.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MDataCheck.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MDataCheck.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MDataCheck.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MEventDisplay.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MEventDisplay.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MEventDisplay.cc	(revision 17960)
@@ -0,0 +1,904 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+#include "MEventDisplay.h"
+
+//
+// C-lib
+//
+#include <stdlib.h>              // atoi
+
+//
+// root
+//
+#include <TFile.h>               // TFile
+#include <TTree.h>               // TTree
+#include <TList.h>               // TList::Add
+#include <TStyle.h>              // gStyle->SetOptStat
+#include <TCanvas.h>             // TCanvas::cd
+#include <TSystem.h>             // TSystem::BaseName
+
+//
+// root GUI
+//
+#include <TGLabel.h>             // TGLabel
+#include <TGButton.h>            // TGPictureButton
+#include <TG3DLine.h>            // TGHorizontal3DLine
+#include <TGTextEntry.h>         // TGTextEntry
+#include <TGButtonGroup.h>       // TGVButtonGroup
+#include <TRootEmbeddedCanvas.h> // TRootEmbeddedCanvas
+
+//
+// General
+//
+#include "MGList.h"              // MGList
+#include "MString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"                  // MParList::AddToList
+#include "MEvtLoop.h"                  // MEvtLoop::GetParList
+#include "MTaskList.h"                 // MTaskList::AddToList
+
+//
+// Tasks
+//
+#include "MReadMarsFile.h"             // MReadMarsFile
+#include "MGeomApply.h"                // MGeomApply
+#include "MPedestalSubtract.h"         // MPedestalSubtract
+#include "MFDataMember.h"              // MFDataMember
+#include "MFEvtNumber.h"               // MFEvtNumber
+#include "MMcPedestalCopy.h"           // MMcPedestalCopy
+#include "MMcPedestalNSBAdd.h"         // MMcPedestalNSBAdd
+
+#include "MSignalCalc.h"               // MPedestalCalc
+#include "MTaskEnv.h"                  // MTaskEnv
+#include "MExtractTimeAndChargeDigitalFilter.h"
+#include "MImgCleanStd.h"              // MImgCleanStd
+#include "MHillasCalc.h"               // MHillasCalc
+#include "MCalibrationRelTimeCalc.h"   // MCalibrationRelTimeCalc
+#include "MCalibrationPatternDecode.h" // MCalibrationPatternDecode
+#include "MPrint.h"               
+#include "MBadPixelsCalc.h"            // MBadPixelsCalc
+#include "MBadPixelsTreat.h"           // MBadPixelsTreat
+#include "MFillH.h"                    // MFillH
+#include "MMcCalibrationUpdate.h"      // MMcCalibrationUpdate
+#include "MCalibrateData.h"            // MCalibrateData
+#include "MMuonSearchParCalc.h"        // MMuonSearchParCalc
+#include "MMuonCalibParCalc.h"         // MMuonCalibParCalc
+#include "MContinue.h"                 // MContinue
+#include "MTriggerPatternDecode.h"     // MTriggerPatternDecode
+#include "MSimSignalCam.h"             // MSimSignalCam
+#include "MSimGeomCam.h"               // MSimGeomCam
+//#include "MMcTriggerLvl2Calc.h"        // MMcTriggerLvl2Calc
+
+//
+// Container
+//
+#include "MSequence.h"                 // MSequence
+#include "MDirIter.h"                  // MDirIter
+#include "MHillas.h"                   // MHillas::Print(const MGeomCam&)
+#include "MHillasExt.h"                // MHillasExt::Print(const MGeomCam&)
+#include "MHillasSrc.h"                // MHillasSrc::Print(const MGeomCam&)
+#include "MImagePar.h"                 // MImagePar::Print(const MGeomCam&)
+#include "MNewImagePar.h"              // MNewImagePar::Print(const MGeomCam&)
+#include "MHEvent.h"                   // MHEvent
+#include "MHCamera.h"                  // MHCamera
+#include "MRawEvtData.h"               // MRawEvtData
+#include "MArrivalTimeCam.h"           // MArrivalTimeCam
+#include "MBadPixelsCam.h"             // MBadPixelsCam
+#include "MPedPhotCam.h"               // MPedPhotCam
+#include "MCalibrationChargeCam.h"     // MCalibrationChargeCam
+#include "MMuonSearchPar.h"            // MMuonCalibPar
+#include "MHPhotonEvent.h"             // MHPhotonEvent
+//#include "MMcTriggerLvl2.h"            // MMcTriggerLvl2
+
+using namespace std;
+
+ClassImp(MEventDisplay);
+
+// --------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MEventDisplay::MEventDisplay(const char *fname, const char *path) : MStatusDisplay(756), fEvtLoop(0)
+{
+    //
+    // Setup Task list for hillas calculation
+    //
+    SetupTaskList("Events", fname, path);
+
+    //
+    // 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(768, 576 + fUserFrame->GetDefaultHeight());//TMath::Nint(GetWidth()*1.2), TMath::Nint(GetHeight()*1.2 + fUserFrame->GetDefaultHeight()));
+    SetWindowName("Event Display");
+    MapSubwindows();
+
+    //
+    // Readin first event and display it
+    //
+    if (fEvtLoop)
+        ReadFirstEvent();
+
+    SetNoContextMenu(kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor: PostProcess eventloop, delete eventloop with all containers
+//
+MEventDisplay::~MEventDisplay()
+{
+    if (fEvtLoop)
+    {
+        fEvtLoop->PostProcess();
+        delete fEvtLoop;
+    }
+}
+
+Int_t MEventDisplay::GetFileType(const char *tree, const char *fname) const
+{
+    TFile f(fname, "READ");
+    if (f.IsZombie())
+        return 0; // Not a root file
+
+    TTree *t = (TTree*)f.Get(tree);
+    if (!t)
+        return -1;
+
+    if (t->FindBranch("MSignalCam."))
+        return 1;
+
+    if (t->FindBranch("MRawEvtData."))
+        return 2;
+
+    if (t->FindBranch("MPhotonEvent."))
+        return 3;
+
+    return -2;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Setup Task and parameter list for hillas calculation,
+//  preprocess tasks and read in first event (process)
+//
+void MEventDisplay::SetupTaskList(const char *tname, TString fname, const char *path)
+{
+    MBadPixelsCam *badpix = new MBadPixelsCam;
+
+    Int_t type = GetFileType(tname, fname);
+    switch (type)
+    {
+    case  1: gLog << all << "Calibrated Data File detected..." << endl; break;
+    case  2: gLog << all << "Raw Data File detected..." << endl; break;
+    case  3: gLog << all << "Ceres reflector file detected..." << endl; break;
+    case -2: gLog << err << "File type unknown... abort." << endl; return;
+    case -1: gLog << err << "Tree " << tname << " not found... abort." << endl; return;
+    case  0: gLog << inf << "Assuming Sequence file." << endl; break;
+    }
+
+    if (type==0 && !MSequence::InflateSeq(fname))
+        return;
+
+    // Check if file is a sequence...
+    MSequence *seq = type==0 ? new MSequence(fname, path) : new MSequence;
+    if (type==0)
+        type = 1;
+
+    //
+    // 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();
+
+    MParList *plist = new MParList;
+    plist->SetOwner();
+    plist->AddToList(tlist);
+    plist->AddToList(badpix);
+    plist->AddToList(seq);
+
+    MReadMarsFile *read = new MReadMarsFile(tname);
+    read->DisableAutoScheme();
+    if (seq->IsValid())
+    {
+        MDirIter iter;
+        if (seq->GetRuns(iter, MSequence::kCalibrated)<=0)
+            return;
+        read->AddFiles(iter);
+    }
+    else
+        read->AddFile(fname);
+    tlist->AddToList(read);
+
+    MGeomApply *apl = new MGeomApply;
+    tlist->AddToList(apl);
+
+    if (type==3)
+    {
+        MHPhotonEvent *phevt = new MHPhotonEvent;
+        phevt->PermanentReset();
+        plist->AddToList(phevt);
+
+        MFillH *fillh = new MFillH(phevt, "MPhotonEvent");
+        fillh->SetNameTab("Detector");
+        tlist->AddToList(fillh);
+
+        MSimGeomCam *simgeom = new MSimGeomCam;
+        tlist->AddToList(simgeom);
+
+        MSimSignalCam *sim = new MSimSignalCam;
+        tlist->AddToList(sim);
+    }
+
+    MContinue *mcevts = new MContinue("MRawEvtData.GetNumPixels==0", "ContEmpty");
+    if (type==2)
+        tlist->AddToList(mcevts);
+
+    MFEvtNumber *evtnum = new MFEvtNumber;
+    tlist->AddToList(evtnum);
+
+    MContinue *contevt = new MContinue(evtnum);
+    contevt->SetInverted();
+    tlist->AddToList(contevt);
+
+    MTriggerPatternDecode *decode = new MTriggerPatternDecode;
+    tlist->AddToList(decode);
+
+    //MArrivalTime *atime = new MArrivalTime;
+    //plist->AddToList(atime);
+
+    MHEvent *evt01 = new MHEvent(MHEvent::kEvtSignalDensity);
+    MHEvent *evt02 = new MHEvent(MHEvent::kEvtSignalDensity);
+    MHEvent *evt03 = new MHEvent(type==1?MHEvent::kEvtPedPhot:MHEvent::kEvtPedestal);
+    MHEvent *evt04 = new MHEvent(type==1?MHEvent::kEvtPedPhotRMS:MHEvent::kEvtPedestalRMS);
+    MHEvent *evt06a= new MHEvent(MHEvent::kEvtCleaningData);
+    MHEvent *evt06b= new MHEvent(MHEvent::kEvtCleaningLevels);
+    //MHEvent *evt07 = new MHEvent(MHEvent::kEvtIdxMax);
+    MHEvent *evt08 = new MHEvent(MHEvent::kEvtArrTime);
+    MHEvent *evt09 = new MHEvent(MHEvent::kEvtArrTimeCleaned);
+    //MHEvent *evt09 = new MHEvent(MHEvent::kEvtTrigPix);
+    MHEvent *evt10 = new MHEvent(MHEvent::kEvtIslandIndex);
+
+    evt01->SetName("Signal");
+    evt02->SetName("Cleaned");
+    evt03->SetName("Ped");
+    evt04->SetName("PedRMS");
+    evt06a->SetName("CleanData");
+    evt06b->SetName("Levels");
+    //evt07->SetName("MaxSliceIdx");
+    evt08->SetName("ArrTime");
+    evt09->SetName("Time");
+    evt10->SetName("Islands");
+
+    evt01->SetMinimum(0);
+    evt03->SetMinimum(0);
+    evt04->SetMinimum(0);
+    evt06a->SetMinimum(0);
+
+    // This makes sure, that the containers are deleted...
+    plist->AddToList(evt01);
+    plist->AddToList(evt02);
+    plist->AddToList(evt03);
+    plist->AddToList(evt04);
+    plist->AddToList(evt06a);
+    plist->AddToList(evt06b);
+    //plist->AddToList(evt07);
+    plist->AddToList(evt08);
+    plist->AddToList(evt09);
+    plist->AddToList(evt10);
+
+    MFillH          *fill01  = new MFillH(evt01, "MSignalCam", "MFillH01");
+    MImgCleanStd    *clean   = new MImgCleanStd;
+    MFillH          *fill02  = new MFillH(evt02, "MSignalCam", "MFillH02");
+    MFillH          *fill03  = new MFillH(evt03, type==1?"MPedPhotFundamental":"MPedestalCam",       "MFillH03");
+    MFillH          *fill04  = new MFillH(evt04, type==1?"MPedPhotFromExtractorRndm":"MPedestalCam", "MFillH04");
+    MFillH          *fill06a = new MFillH(evt06a, "MCameraData", "MFillH06a");
+    MFillH          *fill06b = new MFillH(evt06b, "MCameraData", "MFillH06b");
+    MHillasCalc     *hcalc   = new MHillasCalc;
+    //MMcTriggerLvl2Calc *trcal  = new MMcTriggerLvl2Calc;
+    //MFillH             *fill09 = new MFillH(evt09, "MMcTriggerLvl2", "MFillH09");
+    MFillH          *fill10  = new MFillH(evt10, "MSignalCam",    "MFillH10");
+
+    MExtractTimeAndChargeDigitalFilter *digf = new MExtractTimeAndChargeDigitalFilter;
+    digf->SetNameWeightsFile("msignal/cosmics_weights46.dat");
+
+    MTaskEnv *taskenv1=new MTaskEnv("ExtractSignal");
+    taskenv1->SetDefault(digf);
+    taskenv1->SetOwner();
+
+    MSignalCalc     *nanal   = new MSignalCalc;
+
+    MBadPixelsCalc  *bcalc   = new MBadPixelsCalc;
+    MBadPixelsTreat *btreat  = new MBadPixelsTreat;
+    btreat->SetProcessTimes(kFALSE);
+    if (type==1)
+    {
+        bcalc->SetNamePedPhotCam("MPedPhotFromExtractor");
+        btreat->AddNamePedPhotCam("MPedPhotFromExtractorRndm");
+        clean->SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+    }
+
+    // If no pedestal or no calibration file is availble
+    if (type==2)
+    {
+        MFilter *f1=new MFDataMember("MRawRunHeader.fRunType", '>', 255.5);
+        f1->SetName("MFMonteCarlo");
+
+        MMcPedestalCopy   *pcopy = new MMcPedestalCopy;
+        MMcPedestalNSBAdd *pdnsb = new MMcPedestalNSBAdd;
+
+        MCalibrationPatternDecode *patdecode = new MCalibrationPatternDecode;
+
+        MPedestalSubtract *pedsub1  = new MPedestalSubtract("PedSubstract1");
+        MPedestalSubtract *pedsub2  = new MPedestalSubtract("PedSubstract2");
+        pedsub2->SetNamePedestalCam();
+
+        MMcCalibrationUpdate* mcupd = new MMcCalibrationUpdate;
+        mcupd->SetOuterPixelsGainScaling(kFALSE);
+
+        MCalibrateData* calib = new MCalibrateData;
+        calib->SetCalibrationMode(MCalibrateData::kFlatCharge);
+        calib->SetPedestalFlag(MCalibrateData::kEvent);
+
+        // MPedestalCam is extracted using the simple MSignalCalc!
+
+        // MC
+        mcupd->SetFilter(f1);
+        //trcal->SetFilter(f1);
+
+        // TaskList
+        tlist->AddToList(f1);
+        tlist->AddToList(pcopy);
+        tlist->AddToList(pdnsb);
+
+        tlist->AddToList(patdecode);
+
+        tlist->AddToList(pedsub1);   // Produce arrays
+        tlist->AddToList(nanal);     // Estimate pedestal!
+        tlist->AddToList(pedsub2);   // subtract pedestal
+
+        tlist->AddToList(taskenv1); // Calculates MExtractedSignalCam, MArrivalTimeCam
+        tlist->AddToList(mcupd);
+        tlist->AddToList(calib);    // MExtractedSignalCam --> MSignalCam
+
+        //tlist->AddToList(bcalc);    // Produce MBadPixelsCam
+        //tlist->AddToList(btreat);   // Treat MBadPixelsCam
+    }
+
+    tlist->AddToList(fill01);
+    tlist->AddToList(clean);
+    tlist->AddToList(fill02);
+    if (type==2)
+        tlist->AddToList(fill03);
+    if (type!=3)
+        tlist->AddToList(fill04);
+    tlist->AddToList(fill06a);
+    tlist->AddToList(fill06b);
+    tlist->AddToList(fill10);
+    if (type==2)
+    {
+        //MFillH *fill07 = new MFillH(evt07, "MRawEvtData",     "MFillH7");
+        MFillH *fill08 = new MFillH(evt08, "MArrivalTimeCam", "MFillH8");
+        //tlist->AddToList(fill07);
+        tlist->AddToList(fill08);
+
+	//tlist->AddToList(trcal);
+	//tlist->AddToList(fill09);
+    }
+    if (type==1 || type==3)
+    {
+        MFillH *fill08 = new MFillH(evt08, "MSignalCam", "MFillH8");
+        MFillH *fill09 = new MFillH(evt09, "MSignalCam", "MFillH9");
+        tlist->AddToList(fill08);
+        tlist->AddToList(fill09);
+    }
+    tlist->AddToList(hcalc);
+
+    // --------------------------------------------------
+    // Muon Analysis
+    MMuonSearchParCalc *muscalc = new MMuonSearchParCalc;
+    MMuonCalibParCalc  *mcalc   = new MMuonCalibParCalc;
+    MFillH *fillmuon = new MFillH("MHSingleMuon", "", "FillMuon");
+    fillmuon->SetNameTab("Muon");
+    tlist->AddToList(muscalc);
+    tlist->AddToList(fillmuon);
+    tlist->AddToList(mcalc);
+
+    // --------------------------------------------------
+    // Cut to steer the display
+    MContinue *cont0=new MContinue("", "Cut");
+    cont0->SetAllowEmpty();
+    tlist->AddToList(cont0);
+
+    //
+    // Now distribute Display to all tasks
+    //
+    fEvtLoop = new MEvtLoop(gSystem->BaseName(fname));
+    fEvtLoop->SetOwner();
+    fEvtLoop->SetParList(plist);
+    fEvtLoop->SetDisplay(this);
+    fEvtLoop->ReadEnv("mars.rc");
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the top part of the frame: This is filename and treename display
+//
+void MEventDisplay::AddTopFramePart1(TGCompositeFrame *frame,
+                                    const char *filename,
+                                    const char *treename)
+{
+    //
+    //  --- the top1 part of the window ---
+    //
+    TGHorizontalFrame *top1 = new TGHorizontalFrame(frame, 1, 1);
+    fList->Add(top1);
+
+    //
+    // create gui elements
+    //
+    TGLabel *file = new TGLabel(top1, new TGString(MString::Format("%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);
+}
+
+void MEventDisplay::AddMiddleFrame(TGCompositeFrame *frame)
+{
+    //
+    // Create the gui elements
+    //
+    TGCheckButton *imgpar = new TGCheckButton(frame, "ImgPar", kShowImgPar);
+    imgpar->SetState(kButtonDown);
+    imgpar->Associate(this);
+    fList->Add(imgpar);
+
+    TGCheckButton *muon = new TGCheckButton(frame, "Muon", kShowMuon);
+    muon->Associate(this);
+    muon->SetState(kButtonDown);
+    fList->Add(muon);
+
+    //
+    // add the gui elements to the frame
+    //
+//    TGLayoutHints *laystd = new TGLayoutHints(kLHintsLeft|kLHintsCenterY, 5, 5);
+//    fList->Add(laystd);
+//    top2->AddFrame(prevevt,    laystd);
+
+    frame->AddFrame(imgpar);
+    frame->AddFrame(muon);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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);
+    TGCompositeFrame *hor = new TGHorizontalFrame(vf1, 1, 1);
+    TGCompositeFrame *ver = new TGVerticalFrame(hor, 1, 1);
+    TGCompositeFrame *vfb = new TGVerticalFrame(hor, 1, 1);
+
+    TGHorizontal3DLine *line = new TGHorizontal3DLine(vf1);
+    TGLayoutHints *expx = new TGLayoutHints(kLHintsExpandX);
+    TGLayoutHints *right = new TGLayoutHints(kLHintsRight|kLHintsTop);
+    fList->Add(line);
+    fList->Add(expx);
+    fList->Add(right);
+
+    hor->AddFrame(ver);
+    hor->AddFrame(vfb, right);
+
+    AddMiddleFrame(vfb);
+
+    //
+    // Add trailing line...
+    //
+    vf1->AddFrame(hor,  expx);
+    vf1->AddFrame(line, expx);
+
+    AddTopFramePart1(ver, filename, "Events");
+    AddTopFramePart2(ver);
+
+    // 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);
+
+    fUserFrame->AddFrame(vf1, expx);
+    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();
+
+    Int_t rc;
+    do
+    {
+        if (dir<0 && !reader->DecEventNum())
+        {
+            reader->SetEventNum(num);
+            return;
+        }
+        if (dir>0 && !reader->IncEventNum())
+        {
+            reader->SetEventNum(num);
+            return;
+        }
+
+        rc = tlist->Process();
+        if (rc==kFALSE || rc==kERROR)
+            return;
+
+        reader->DecEventNum();
+
+        // Define other continue conditions
+        //if (raw && raw->GetNumPixels()<1)
+        //    rc = kCONTINUE;
+
+    } while (rc==kCONTINUE && dir!=0);
+
+    //
+    // Cleare the 'FADC canvas'
+    //
+    fCanvas->Clear();
+    fCanvas->Modified();
+    fCanvas->Update();
+
+    //
+    // Print parameters
+    //
+    *fLog << all;
+    fLog->Separator(MString::Format("Entry %d", reader->GetNumEntry()+1));
+
+    ((MHillas*)     plist->FindObject("MHillas"))->Print(*geom);
+    ((MHillasExt*)  plist->FindObject("MHillasExt"))->Print(*geom);
+    ((MHillasSrc*)  plist->FindObject("MHillasSrc"))->Print(*geom);
+    plist->FindObject("MImagePar")->Print();
+    ((MNewImagePar*)plist->FindObject("MNewImagePar"))->Print(*geom);
+    plist->FindObject("MMuonCalibPar")->Print();
+    ((MMuonSearchPar*)plist->FindObject("MMuonSearchPar"))->Print(*geom);
+
+    //
+    // UpdateDisplay
+    //
+    gStyle->SetOptStat(1101);
+    Update();
+
+    TGTextEntry *entry = (TGTextEntry*)fList->FindWidget(kEvtNumber);
+    entry->SetText(MString::Format("%d", reader->GetNumEntry()+1));
+}
+
+void MEventDisplay::ShowHide()
+{
+    TGCheckButton *but1 = (TGCheckButton*)fList->FindWidget(kShowImgPar);
+    TGCheckButton *but2 = (TGCheckButton*)fList->FindWidget(kShowMuon);
+
+    const Bool_t imgpar = but1 && but1->IsDown();
+    const Bool_t muon   = but2 && but2->IsDown();
+
+    //
+    // Get parlist
+    //
+    MParList *plist = fEvtLoop->GetParList();
+    if (!plist)
+        return;
+
+    //
+    // Draw ellipse on top of all pads
+    //
+    const Int_t n = 5;
+
+    TObject *obj[n] = {
+        plist->FindObject("MHillas"),
+        plist->FindObject("MHillasSrc"),
+        plist->FindObject("MHillasExt"),
+        plist->FindObject("MSrcPosCam"),
+        plist->FindObject("MMuonSearchPar")
+    };
+
+    const Bool_t state[n] = {
+        imgpar,
+        imgpar,
+        imgpar,
+        imgpar,
+        muon,
+    };
+
+    const Int_t ismc = plist->FindObject("MHPhotonEvent") ? 1 : 0;
+
+    for (int i=1; i<7; i++)
+    {
+        TCanvas *c = GetCanvas(i+ismc);
+        if (!c)
+            continue;
+
+        c->cd(1);
+
+        TList *list = gPad->GetListOfPrimitives();
+
+        for (int j=0;j<n; j++)
+            if (obj[j])
+            {
+                if (state[j] && !list->FindObject(obj[j]))
+                    list->Add(obj[j]);
+                if (!state[j] && list->FindObject(obj[j]))
+                    list->Remove(obj[j]);
+            }
+
+        gPad->Modified(kTRUE);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Read first event to get display booted
+//
+void MEventDisplay::ReadFirstEvent()
+{
+    const Int_t rc = fEvtLoop->PreProcess();
+    if (rc==kFALSE || rc==kERROR)
+        return;
+
+    UnLock();
+
+    //
+    // Now read event...
+    //
+    // FIXME: Can we safely replace ReadinEvent() by RedinEvent(1)?
+    ReadinEvent();
+
+    //
+    // After ReInit (MGeomCam might be read from RunHeaders): Add Geometry tab
+    //
+    AddGeometryTabs();
+
+    MReadTree *reader = (MReadTree*)fEvtLoop->FindTask("MRead");
+    TGString *txt = new TGString(MString::Format("of %d", reader->GetEntries()));
+    fNumOfEvts->SetText(txt);
+
+    ShowHide();
+}
+
+// --------------------------------------------------------------------------
+//
+//  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(MString::Format("%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;
+
+        case kCM_CHECKBUTTON:
+            switch (mp1)
+            {
+            case kShowMuon:
+            case kShowImgPar:
+                ShowHide();
+                return kTRUE;
+            }
+            return kTRUE;
+        }
+        break;
+    }
+
+    return MStatusDisplay::ProcessMessage(msg, mp1, mp2);
+}
Index: branches/Mars_McMismatchStudy/mmain/MEventDisplay.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MEventDisplay.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MEventDisplay.h	(revision 17960)
@@ -0,0 +1,62 @@
+#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::kLastElement + 1,
+        kEvtNext,
+        kEvtNumber,
+        kShowMuon,
+        kShowImgPar
+    };
+
+    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 AddMiddleFrame(TGCompositeFrame *frame);
+    void AddGeometryTabs();
+    void AddUserFrame(const char *filename);
+    void ShowHide();
+
+    void UpdateDisplay();
+    void SetupTaskList(const char *tname, TString fname, const char *path);
+
+    void ReadFirstEvent();
+    void ReadinEvent(Int_t dir=0);
+
+    Int_t GetFileType(const char *tree, const char *fname) const;
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+public:
+    MEventDisplay(const char *fname, const char *path="");
+    ~MEventDisplay();
+
+    ClassDef(MEventDisplay, 0) // Display for camera images (cerenkov events)
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mmain/MGDisplayAdc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MGDisplayAdc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MGDisplayAdc.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MGDisplayAdc.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MGDisplayAdc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MGDisplayAdc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MMars.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MMars.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MMars.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MMars.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MMars.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MMars.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MMonteCarlo.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MMonteCarlo.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MMonteCarlo.cc	(revision 17960)
@@ -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.R__FOR_EACH(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: branches/Mars_McMismatchStudy/mmain/MMonteCarlo.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MMonteCarlo.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MMonteCarlo.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MOnlineDisplay.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MOnlineDisplay.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MOnlineDisplay.cc	(revision 17960)
@@ -0,0 +1,225 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MOnlineDisplay.h"
+
+//
+// C-lib
+//
+#include <stdlib.h>              // atoi
+
+//
+// root
+//
+#include <TList.h>               // TList::Add
+#include <TStyle.h>              // gStyle->SetOptStat
+#include <TCanvas.h>             // TCanvas::cd
+
+//
+// root GUI
+//
+#include <TGLabel.h>             // TGLabel
+#include <TGButton.h>            // TGPictureButton
+#include <TGSlider.h>            // TGSlider
+#include <TG3DLine.h>            // TGHorizontal3DLine
+#include <TGTextEntry.h>         // TGTextEntry
+#include <TGButtonGroup.h>       // TGVButtonGroup
+#include <TRootEmbeddedCanvas.h> // TRootEmbeddedCanvas
+
+//
+// General
+//
+#include "MGList.h"              // MGList
+
+#include "MParList.h"            // MParList::AddToList
+#include "MEvtLoop.h"            // MEvtLoop::GetParList
+#include "MTaskList.h"           // MTaskList::AddToList
+
+//
+// Tasks
+//
+#include "MReadMarsFile.h"       // MReadMarsFile
+#include "MGeomApply.h"          // MGeomApply
+#include "MFDataMember.h"        // MFDataMember
+#include "MMcPedestalCopy.h"     // MMcPedestalCopy
+#include "MMcPedestalNSBAdd.h"   // MMcPedestalNSBAdd
+#include "MCerPhotCalc.h"        // MCerPhotCalc
+#include "MCerPhotAnal2.h"       // MCerPhotAnal2
+#include "MImgCleanStd.h"        // MImgCleanStd
+#include "MHillasCalc.h"         // MHillasCalc
+#include "MHillasSrcCalc.h"      // MHillasSrcCalc
+#include "MFillH.h"              // MFillH
+#include "MGTask.h"              // MGTask
+
+//
+// Container
+//
+#include "MHEvent.h"             // MHEvent
+#include "MHCamera.h"            // MHCamera
+#include "MRawEvtData.h"         // MRawEvtData
+
+ClassImp(MOnlineDisplay);
+
+// --------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MOnlineDisplay::MOnlineDisplay() : MStatusDisplay(), fTask(0)
+{
+    //
+    // Add MOnlineDisplay GUI elements to the display
+    //
+    AddUserFrame();
+
+    //
+    // Show new part of the window, resize to correct aspect ratio
+    //
+    // FIXME: This should be done by MStatusDisplay automatically
+    Resize(GetWidth(), GetHeight() + fUserFrame->GetDefaultHeight());
+    SetWindowName("Online Display");
+    MapSubwindows();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the top part of the frame: This is filename and treename display
+//
+void MOnlineDisplay::AddTopFramePart1(TGCompositeFrame *vf1)
+{
+    TGLabel *file = new TGLabel(vf1, new TGString("Magic Online Analysis -- MONA"));
+    TGLayoutHints *laystd = new TGLayoutHints(kLHintsCenterX, 5, 5);
+    fList->Add(file);
+    fList->Add(laystd);
+    vf1->AddFrame(file,  laystd);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the second part of the top frame: This are the event number controls
+//
+void MOnlineDisplay::AddTopFramePart2(TGCompositeFrame *vf1)
+{
+    //
+    // --- the top2 part of the window ---
+    //
+    TGHorizontalFrame *top2 = new TGHorizontalFrame(vf1, 1, 1);
+    fList->Add(top2);
+
+    //
+    // Create the gui elements
+    //
+    TGTextButton *freeze = new TGTextButton(top2, " Freeze ", kFreeze);
+    freeze->SetUserData(freeze);
+    freeze->Associate(this);
+    freeze->SetToolTipText("Freeze the current Event");
+
+    fList->Add(freeze);
+
+    //
+    // add the gui elements to the frame
+    //
+    TGLayoutHints *laystd = new TGLayoutHints(kLHintsLeft|kLHintsCenterY, 5, 5);
+    fList->Add(laystd);
+
+    top2->AddFrame(freeze, laystd);
+
+    TGLayoutHints *laystd2 = new TGLayoutHints(kLHintsCenterX, 5, 5, 5, 5);
+    fList->Add(laystd2);
+    vf1->AddFrame(top2, laystd2);
+
+    //
+    // Add trailing line...
+    //
+    TGHorizontal3DLine *line = new TGHorizontal3DLine(vf1);
+    TGLayoutHints *layline = new TGLayoutHints(kLHintsExpandX);
+    fList->Add(line);
+    fList->Add(layline);
+    vf1->AddFrame(line, layline);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the user frame part of the display
+//
+void MOnlineDisplay::AddUserFrame()
+{
+    fUserFrame->ChangeOptions(kHorizontalFrame);
+
+    // Slider
+    TGVSlider *slider = new TGVSlider(fUserFrame, 1, kSlider1, kSlider);
+    slider->SetRange(10, 300);
+    slider->SetScale(15);
+    slider->SetPosition(10);
+    slider->Associate(this);
+    //slider->SetToolTipText("Change the update frequency of the event display (1-30s)");
+
+    // frame1/2
+    TGCompositeFrame *vf1 = new TGVerticalFrame(fUserFrame, 1, 1);
+    TGCompositeFrame *vf2 = new TGVerticalFrame(fUserFrame, 1, 1);
+
+    AddTopFramePart1(vf1);
+    AddTopFramePart2(vf1);
+
+    // create root embedded canvas and add it to the tab
+    TRootEmbeddedCanvas *ec = new TRootEmbeddedCanvas("Slices", vf2, vf1->GetDefaultHeight()*3/2, vf1->GetDefaultHeight(), 0);
+    vf2->AddFrame(ec);
+    fList->Add(ec);
+
+    // set background and border mode of the canvas
+    fCanvas = ec->GetCanvas();
+    fCanvas->SetBorderMode(0);
+    gROOT->GetListOfCanvases()->Add(fCanvas);
+    //fCanvas->SetBorderSize(1);
+    //fCanvas->SetBit(kNoContextMenu);
+    //fCanvas->SetFillColor(16);
+
+    // layout
+    TGLayoutHints *lays = new TGLayoutHints(kLHintsExpandY);
+    TGLayoutHints *lay = new TGLayoutHints(kLHintsExpandX);
+    fUserFrame->AddFrame(slider, lays);
+    fUserFrame->AddFrame(vf1, lay);
+    fUserFrame->AddFrame(vf2);
+
+    fList->Add(lay);
+    fList->Add(lays);
+    fList->Add(vf1);
+    fList->Add(vf2);
+    fList->Add(slider);
+}
+
+// --------------------------------------------------------------------------
+//
+//  ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+//
+// Processes information from all GUI items.
+// Selecting an item usually generates an event with 4 parameters.
+// The first two are packed into msg (first and second bytes).
+// The other two are parm1 and parm2.
+//
+Bool_t MOnlineDisplay::ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2)
+{
+    if (fTask && fTask->ProcessMessage(GET_MSG(msg), GET_SUBMSG(msg), mp1, mp2))
+        return kTRUE;
+
+    return MStatusDisplay::ProcessMessage(msg, mp1, mp2);
+}
Index: branches/Mars_McMismatchStudy/mmain/MOnlineDisplay.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MOnlineDisplay.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MOnlineDisplay.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MOnlineDump.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MOnlineDump.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MOnlineDump.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MOnlineDump.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MOnlineDump.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MOnlineDump.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmain/MainIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MainIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MainIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mmain/MainLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mmain/MainLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/MainLinkDef.h	(revision 17960)
@@ -0,0 +1,12 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MBrowser+;
+
+#pragma link C++ class MCameraDisplay+;
+#pragma link C++ class MEventDisplay+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mmain/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mmain/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmain/Makefile	(revision 17960)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Main
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../manalysis -I../mdatacheck -I../mraw        \
+	   -I../mgui -I../mgeom -I../mhbase -I../mhist -I../mmontecarlo   \
+           -I../mfileio -I../mimage -I../mhistmc -I../mgbase -I../mfbase  \
+           -I../mdata -I../msignal -I../mcalib -I../mbadpixels            \
+           -I../mpointing -I../mpedestal -I../mmuon -I../mfilter -I../mjobs \
+	   -I../mtrigger -I../mcorsika -I../msimcamera -I../msim
+
+SRCFILES = MBrowser.cc \
+           MEventDisplay.cc \
+           MCameraDisplay.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mmc/MFadcDefine.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MFadcDefine.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MFadcDefine.h	(revision 17960)
@@ -0,0 +1,41 @@
+//
+//  --> Sampling frequency of the FADC, in number of slices
+//  per nsec, for the original 300 MHz FADCs of MAGIC. WARNING:
+//  DO NOT CHANGE this number to set a different sampling frequency
+//  of the signals! USE instead the "fadc_GHz" command in the camera
+//  input card (see instructions)
+//
+#define FADC_SLICES_PER_NSEC 0.3
+//
+//
+//  --> The amount of FADC slice written to the raw format.
+#define FADC_SLICES  15
+//
+//  --> Number of bins per FADC slice that we will use for the analog 
+//      signal simulation. In March 2005, raised this value from 5 to 500 
+//      so that we can properly simulate the time jitter of the PMTs (which is
+//      by default 200 ps)
+#define SUBBINS     500 
+//
+//
+// --> Default values of the single photoelectron response going to the FADC,
+//     in the case the gaussian shape is chosen.
+//
+#define MFADC_RESPONSE_FWHM       5.0
+#define MFADC_RESPONSE_INTEGRAL   4.0
+
+//
+// -->  The maximum number of FADC channels
+//      Most likely it will be always equal to CAMERA_PIXELS 
+#define MFADC_CHANNELS  3800
+//
+//  --> Ratio of high to low gain:
+#define HIGH2LOWGAIN 10.
+//
+//
+//  --> The amount of ns before trigger that would be shown from the ADC
+//      history in order to show also the start of the pulse before the
+//      the trigger time.-> JUST FOR DISPLAY purposes! (see MFadc::Scan)
+#define TIME_BEFORE_TRIGGER    10.  
+// 
+//
Index: branches/Mars_McMismatchStudy/mmc/MMcConfigRunHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcConfigRunHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcConfigRunHeader.cc	(revision 17960)
@@ -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): 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).
+//
+//
+// Class Version 2:
+// ----------------
+// removed obsolete variables which are no longer used by reflector, 
+// nor present in the magic.def file:  fFocalStdev, fPointStdev, fDevAdjust
+//
+// Class Version 3:
+// ----------------
+// Added member fLightCollectionFactorOuter so that we can store
+// the data on the simulatedlight collection efficiency (light
+// guides + plexiglas +...) as a function of incidence angle for
+// outer and inner pixels independently.
+//
+// Class Version 4:
+// ----------------
+// Added member fMirrorFraction, the "active" fraction of the
+// mirror dish, to account for reflectivity losses, missing
+// mirrors, etc.
+//
+// Class Version 5:
+// ----------------
+// Added member fPmtTimeJitter, the time jitter of the PMTs (sigma
+// of gaussian) for each photoelectron.
+//
+// Class Version 6:
+// ----------------
+// Added fParaboloidFocal
+//
+/////////////////////////////////////////////////////////////////////////////////
+
+//
+////////////////////////////////////////////////////////////////////////////
+#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;
+    fParaboloidFocal = -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: branches/Mars_McMismatchStudy/mmc/MMcConfigRunHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcConfigRunHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcConfigRunHeader.h	(revision 17960)
@@ -0,0 +1,117 @@
+#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?
+
+    Float_t fMirrorFraction;    // (adimensional, between 0 and 1) Fraction of mirror dish
+                                //  which is really working.
+
+    // Magic Def Parameters
+    Float_t fFocalDist;         // [cm] Focal distance
+    Float_t fParaboloidFocal;   // [cm] True focal of the paraboloid on which the mirror centers are placed
+    Float_t fPointSpread;       // [cm] Point spread function, sigma in x and y on the camera as simualted in the Reflector
+    Float_t fPointSpreadX;      // [cm] Point spread function, sigma in x on the camera adding gaussian in the Camera
+    Float_t fPointSpreadY;      // [cm] Point spread function, sigma in y on the camera adding gaussian in the Camera
+    Float_t fBlackSpot;         // [cm] Radius of black spot in the mirror center
+    Float_t fCameraWidth;       // [cm] Radius on the camera plain 
+                                // inside which the phe are kept.
+
+    Float_t fMissPointingX;     // [deg] Misspointing in deg added in he Camera 
+    Float_t fMissPointingY;     // [deg] simulation at rho (rotation FoV) = 0. 
+
+    Float_t fPmtTimeJitter;     // [ns] PMT time jitter (sigma of gaussian), per phe-
+
+    // QE Information
+    UInt_t  fNumPMTs;
+    TClonesArray  *fPMTs;
+
+    // Light Collection Information (guides , plexiglas, 1st dynode) 
+
+    TArrayF fIncidentTheta;    // [deg] Angle (0-180 deg) between light 
+                               // direction and camera plane.
+    TArrayF fLightCollectionFactor;//   Inner pixels
+    TArrayF fLightCollectionFactorOuter;//  Outer pixels
+
+public:
+    MMcConfigRunHeader(const char *name=NULL, const char *title=NULL);
+    ~MMcConfigRunHeader() { delete fMirrors; delete fPMTs; }
+
+    void SetMagicDef(Float_t radius, Float_t focal, Float_t point,
+                     Float_t spot, Float_t camwidth);
+    void SetLightCollection(const TArrayF &theta, const TArrayF &factor, 
+			    const TArrayF &factor_outer);
+
+    UInt_t GetNumMirror() const { return fNumMirrors; }
+    void   InitSizeMirror(UInt_t num) { fMirrors->Expand(num); }
+
+    void   SetMirrorFraction(Float_t x) { fMirrorFraction = x; }
+
+    UInt_t GetNumPMTs() const { return fNumPMTs; }
+    void   InitSizePMTs(UInt_t num) { fPMTs->Expand(num); }
+
+    Float_t GetPointSpread() const { return fPointSpread; }
+    void    SetPointSpread(Float_t x) { fPointSpread = x; }
+
+    Float_t GetPointSpreadX() const { return fPointSpreadX; }
+    void    SetPointSpreadX(Float_t x) { fPointSpreadX = x; }
+    Float_t GetPointSpreadY() const { return fPointSpreadY; }
+    void    SetPointSpreadY(Float_t x) { fPointSpreadY = x; }
+
+    Float_t GetMissPointingX() const {return fMissPointingX;}
+    void    SetMissPointingX(Float_t x) {fMissPointingX=x;}
+
+    Float_t GetMissPointingY() const {return fMissPointingY;}
+    void    SetMissPointingY(Float_t x) {fMissPointingY=x;}
+
+    const TArrayF &GetLightCollectionFactor() const {return fLightCollectionFactor; }
+    const TArrayF &GetLightCollectionFactorOuter() const {return fLightCollectionFactorOuter; }
+
+    Float_t GetMirrorFraction() const { return fMirrorFraction; }
+
+    const TArrayF &GetIncidentTheta() const {return fIncidentTheta;}
+
+    void   AddMirror(Int_t id)
+    {
+        new ((*fMirrors)[fNumMirrors++]) MGeomMirror(id);
+    }
+
+    void   AddPMT(Int_t id)
+    {
+        new ((*fPMTs)[fNumPMTs++]) MGeomPMT(id);
+    }
+
+    MGeomMirror &GetMirror(int i)  { return *(MGeomMirror*)(fMirrors->UncheckedAt(i)); }
+    MGeomMirror &GetMirror(int i) const { return *(MGeomMirror*)(fMirrors->UncheckedAt(i)); }
+
+    TClonesArray *GetMirrors() { return fMirrors; }
+
+    MGeomPMT &GetPMT(int i)  { return *(MGeomPMT*)(fPMTs->UncheckedAt(i)); }
+    MGeomPMT &GetPMT(int i) const { return *(MGeomPMT*)(fPMTs->UncheckedAt(i)); }
+    void    SetPmtTimeJitter(Float_t x) { fPmtTimeJitter = x; }
+    Float_t GetPmtTimeJitter() const { return fPmtTimeJitter; }
+
+    ClassDef(MMcConfigRunHeader, 6)  // class for monte carlo configuration information
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mmc/MMcCorsikaRunHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcCorsikaRunHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcCorsikaRunHeader.cc	(revision 17960)
@@ -0,0 +1,212 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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() <<":" << endl;
+    *fLog << " Spectral Slope: " << fSlopeSpec << " from " << fELowLim << "GeV to " << fEUppLim << "GeV" << endl;
+    *fLog << " Number of Telescopes: " << fNumCT << endl;
+    fTelescopes.Print();
+} 
Index: branches/Mars_McMismatchStudy/mmc/MMcCorsikaRunHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcCorsikaRunHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcCorsikaRunHeader.h	(revision 17960)
@@ -0,0 +1,132 @@
+#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; }
+    Float_t GetWobbleMode() const { return fWobbleMode; }
+    Float_t GetCorsikaVersion() const { return fCorsikaVersion; }
+    Float_t GetViewconeAngleInner() const { return fViewconeAngles[0]; }
+    Float_t GetViewconeAngleOuter() const { return fViewconeAngles[1]; }
+    Float_t GetAtmosphericModel() const { return fAtmosphericModel; }
+    Bool_t HasViewCone() const { return fViewconeAngles[1]>0; }
+
+    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);
+
+    void SetSpectrum(Float_t slope, Float_t emin, Float_t emax)
+    {
+        fSlopeSpec=slope; fELowLim=emin; fEUppLim=emax;
+    }
+    void SetViewCone(Float_t inner, Float_t outer)
+    {
+        fViewconeAngles[0] = inner;
+        fViewconeAngles[1] = outer;
+    }
+
+
+    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: branches/Mars_McMismatchStudy/mmc/MMcEvt.cxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcEvt.cxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcEvt.cxx	(revision 17960)
@@ -0,0 +1,255 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s):
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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.
+//
+// Version 4: 
+//   - Added member fFadcTimeJitter
+//
+// Version 5:
+//   - removed fPartId, fEnergy, fImpact, fTelescopeTheta, fTelescopePhi
+//   - derives now from MMcEvtBasic which contains all these values
+//   - moved ParticleId_t to base class MMcEvtBasic
+//
+// Version 6:
+//   - added fEventReuse
+//
+// Version 7:
+//  - moved fPhi   to MMcEvtBasic
+//  - moved fTheta to MmcEvtBasic
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcEvt.hxx"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+ClassImp(MMcEvt);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Calls Clear()
+//
+MMcEvt::MMcEvt()
+{
+    fName  = "MMcEvt";
+    fTitle = "Event info from Monte Carlo";
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Use this to set all data members
+//
+// THIS FUNCTION IS FOR THE SIMULATION OLNY.
+// DON'T USE THIS MEMBERFUNCTION IN THE ANALYSIS.
+//
+MMcEvt::MMcEvt(UInt_t  fEvtNum,    ParticleId_t usPId, Float_t  fEner,
+               Float_t  fThi0,     Float_t  fFirTar,   Float_t  fzFirInt,
+               Float_t  fThet,     Float_t  fPhii,     Float_t  fCorD,
+               Float_t  fCorX,     Float_t  fCorY,     Float_t  fImpa,
+               Float_t  fTPhii,    Float_t  fTThet,    Float_t  fTFirst,
+               Float_t  fTLast,    Float_t  fL_Nmax,   Float_t  fL_t0,
+               Float_t  fL_tmax,   Float_t  fL_a,      Float_t  fL_b,
+               Float_t  fL_c,      Float_t  fL_chi2,   UInt_t   uiPin,
+               UInt_t   uiPat,     UInt_t   uiPre,     UInt_t   uiPco,
+               UInt_t   uiPelS,    UInt_t   uiPelC,    Float_t  elec,
+               Float_t  muon,      Float_t  other,     Float_t  fadc_jitter,
+               Int_t    reuse)
+{
+    fName  = "MMcEvt";
+    fTitle = "Event info from Monte Carlo";
+
+    Fill(fEvtNum, usPId, fEner, fThi0, fFirTar, fzFirInt, fThet,
+	 fPhii, fCorD, fCorX, fCorY, fImpa, fTPhii, fTThet, fTFirst,
+	 fTLast, fL_Nmax, fL_t0, fL_tmax, fL_a, fL_b, fL_c, fL_chi2,
+	 uiPin, uiPat, uiPre, uiPco, uiPelS, uiPelC, elec, muon, other,
+	 fadc_jitter, reuse);
+}
+
+// --------------------------------------------------------------------------
+//
+//  reset all values to values as nonsense as possible
+//
+void MMcEvt::Clear(Option_t *opt)
+{
+    fPartId = kUNDEFINED;
+    fEnergy = -1;
+
+    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;
+
+    fEventReuse = 0;    
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this to set all data members
+//
+// THIS FUNCTION IS FOR THE SIMULATION OLNY.
+// DON'T USE THIS MEMBERFUNCTION IN THE ANALYSIS.
+//
+void MMcEvt::Fill( UInt_t  fEvtNum,    ParticleId_t usPId, Float_t  fEner,
+		   Float_t  fThi0,     Float_t  fFirTar,   Float_t  fzFirInt,
+		   Float_t  fThet,     Float_t  fPhii,     Float_t  fCorD, 
+		   Float_t  fCorX,     Float_t  fCorY,     Float_t  fImpa, 
+		   Float_t  fTPhii,    Float_t  fTThet,    Float_t  fTFirst,
+		   Float_t  fTLast,    Float_t  fL_Nmax,   Float_t  fL_t0,
+		   Float_t  fL_tmax,   Float_t  fL_a,      Float_t  fL_b,
+		   Float_t  fL_c,      Float_t  fL_chi2,   UInt_t   uiPin, 
+		   UInt_t   uiPat,     UInt_t   uiPre,     UInt_t   uiPco,  
+		   UInt_t   uiPelS,    UInt_t   uiPelC,    Float_t  elec,
+                   Float_t  muon,      Float_t  other,     Float_t  fadc_jitter,
+                   Int_t    reuse)
+{
+    //
+    //  All datamembers are filled with the correspondin parameters.
+    //
+    //  Don't use this memberfunction in analysis
+    //
+    fEvtNumber = fEvtNum;
+    fPartId = usPId  ;
+    fEnergy = fEner  ;
+    fThick0 = fThi0;
+    fFirstTarget = fFirTar;
+    fZFirstInteraction = fzFirInt;
+
+    fTheta  = fThet ;
+    fPhi    = fPhii ;
+
+    fCoreD  = fCorD ;
+    fCoreX  = fCorX ;
+    fCoreY  = fCorY ;
+    fImpact = fImpa ;
+
+    fTelescopePhi = fTPhii;
+    fTelescopeTheta = fTThet;
+    fTimeFirst = fTFirst;
+    fTimeLast = fTLast;
+    fLongiNmax = fL_Nmax;
+    fLongit0 = fL_t0;
+    fLongitmax = fL_tmax;
+    fLongia = fL_a;
+    fLongib = fL_b;
+    fLongic = fL_c;
+    fLongichi2 = fL_chi2;
+
+    fPhotIni      = uiPin ;
+    fPassPhotAtm  = fPhotIni-uiPat ;
+    fPassPhotRef  = fPassPhotAtm-uiPre ;
+    fPassPhotCone = uiPco ;
+    fPhotElfromShower = uiPelS ;
+    fPhotElinCamera = uiPelC ;
+
+    fElecCphFraction=elec;
+    fMuonCphFraction=muon;
+    fOtherCphFraction=other;
+
+    fFadcTimeJitter = fadc_jitter;
+
+    fEventReuse = reuse;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+{
+    MMcEvtBasic::Print(opt);
+
+    TString str(opt);
+    if (str.IsNull())
+        *fLog << " Photoelectrons: " << fPhotElfromShower << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a proper description of the monte carlo event
+//
+TString MMcEvt::GetDescription(const TString &s) const
+{
+    TString txt("#splitline{");
+
+    txt += GetParticleName();
+    txt += " ";
+    txt += s;
+    txt += "}{  E=";
+    txt += GetEnergyStr();
+    txt += "  r=";
+    txt += TMath::Nint(GetImpact()/100);
+    txt += "m  Zd=";
+    txt += MString::Format("%.1f", GetTelescopeTheta()*TMath::RadToDeg());
+    txt += "\\circ  ";
+    if (GetPhotElfromShower()>=10000)
+        txt += MString::Format("%dk", TMath::Nint(GetPhotElfromShower()/1000.));
+    else
+        if (GetPhotElfromShower()>=1000)
+            txt += MString::Format("%.1fk", GetPhotElfromShower()/1000.);
+        else
+            txt += GetPhotElfromShower();
+    txt += "PhEl}";
+
+    return txt;
+}
Index: branches/Mars_McMismatchStudy/mmc/MMcEvt.hxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcEvt.hxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcEvt.hxx	(revision 17960)
@@ -0,0 +1,122 @@
+#ifndef MARS_MMcEvt
+#define MARS_MMcEvt
+
+#ifndef MARS_MMcEvtBasic
+#include "MMcEvtBasic.h"
+#endif
+
+
+class MMcEvt : public MMcEvtBasic
+{
+private:
+    UInt_t  fEvtNumber;          // [fits: name=EventNum ; unit=uint32]
+    Float_t fThick0;             // [g/cm2]
+    Float_t fFirstTarget;        // []
+    Float_t fZFirstInteraction;  // [cm]
+
+    Float_t fCoreD;              // [cm] Core d pos
+    Float_t fCoreX;              // [cm] Core x pos
+    Float_t fCoreY;              // [cm] Core y pos
+
+    // Up to here, the info from the CORSIKA event header.
+
+    // Time of first and last photon:
+    Float_t fTimeFirst;          // [ns]
+    Float_t fTimeLast;           // [ns]
+
+    // 6 parameters and chi2 of the NKG fit to the longitudinal
+    // particle distribution. See CORSIKA manual for explanation,
+    // section 4.42 "Longitudinal shower development":
+    //
+    Float_t fLongiNmax;          // [particles]
+    Float_t fLongit0;            // [g/cm2]
+    Float_t fLongitmax;          // [g/cm2]
+    Float_t fLongia;             // [g/cm2]
+    Float_t fLongib;             // []
+    Float_t fLongic;             // [cm2/g]
+    Float_t fLongichi2;
+
+    UInt_t fPhotIni;             // [ph] Initial number of photons
+    UInt_t fPassPhotAtm;         // [ph] Passed atmosphere
+    UInt_t fPassPhotRef;         // [ph] Passed reflector(reflectivity + effective area)
+    UInt_t fPassPhotCone;        // [ph]  Within any valid pixel, before plexiglas
+    UInt_t fPhotElfromShower;    // [phe] Passed qe, coming from the shower
+    UInt_t fPhotElinCamera;      // [phe] usPhotElfromShower + mean of phe from NSB
+
+    // Now follow the fraction of photons reaching the camera produced by
+    // electrons, muons and other particles respectively:
+
+    Float_t  fElecCphFraction;
+    Float_t  fMuonCphFraction;
+    Float_t  fOtherCphFraction;
+
+    Float_t  fFadcTimeJitter;
+    
+    Int_t    fEventReuse; // Number running from 0 to N-1, being N the number
+                          // of times a Corsika event has been reused, by
+                          // orienting the telescope in different ways or by
+                          // setting it at a different location on the ground.
+
+public:
+    MMcEvt();
+    MMcEvt(UInt_t, ParticleId_t, Float_t, Float_t, Float_t,
+           Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+           Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+           Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+           UInt_t, UInt_t, UInt_t, UInt_t, UInt_t, UInt_t,
+           Float_t, Float_t, Float_t, Float_t, Int_t ireuse=0) ;
+
+    // Getter
+    UInt_t  GetEvtNumber() const { return fEvtNumber; }  //Get Event Number
+
+    Float_t GetCoreX() const { return fCoreX; }          //Get Core x pos
+    Float_t GetCoreY() const { return fCoreY; }          //Get Core y pos
+
+    UInt_t  GetPhotIni() const { return fPhotIni; }           //Get Initial photons
+    UInt_t  GetPassPhotAtm() const { return fPassPhotAtm;}    //Get Passed atmosphere
+    UInt_t  GetPassPhotRef() const { return fPassPhotRef; }   //Get Passed reflector
+    UInt_t  GetPassPhotCone() const { return fPassPhotCone; } //Get Passed glas
+    UInt_t  GetPhotElfromShower() const { return fPhotElfromShower; }   //Get Passed qe from shower
+    UInt_t  GetPhotElinCamera() const { return fPhotElinCamera; }       //Get Passed qe total
+    Float_t GetZFirstInteraction() const { return fZFirstInteraction; }
+
+    Float_t GetOtherCphFraction() const { return fOtherCphFraction; }
+
+    Float_t GetLongiNmax() const { return fLongiNmax; }
+    Float_t GetLongia()    const { return fLongia; }
+    Float_t GetLongib()    const { return fLongib; }
+    Float_t GetLongic()    const { return fLongic; }
+    Float_t GetLongichi2() const { return fLongichi2; }
+    Float_t GetLongit0()   const { return fLongit0; }
+    Float_t GetLongitmax() const { return fLongitmax; }
+
+    Float_t GetFadcTimeJitter() const { return fFadcTimeJitter; }
+
+    Float_t GetMuonCphFraction() const { return fMuonCphFraction; }
+
+    TString GetDescription(const TString &s="") const;
+
+    // Setter
+    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 SetEvtNumber(UInt_t n) { fEvtNumber=n; }
+    void SetEventReuse(UInt_t n) { fEventReuse=n; }
+    void SetPhotElfromShower(UInt_t n) { fPhotElfromShower=n; }
+
+    void Fill( UInt_t, ParticleId_t, Float_t, Float_t, Float_t,
+               Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+               Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+               Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+               UInt_t, UInt_t, UInt_t, UInt_t, UInt_t, UInt_t,
+               Float_t, Float_t, Float_t, Float_t, Int_t ireuse=0);
+
+    // TObject
+    void Print(Option_t *opt=NULL) const;
+    void Clear(Option_t *opt=NULL);
+
+    ClassDef(MMcEvt, 7)  //Stores Montecarlo Information of one event (eg. the energy)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/MMcEvtBasic.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcEvtBasic.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcEvtBasic.cc	(revision 17960)
@@ -0,0 +1,233 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 02/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMcEvtBasic
+//
+// This class contains the most basic MonteCarlo information
+// with which an event has been generated
+//
+// Note: The azimuth fTelescopePhi angle in this and other MC classes 
+// follow the convention in the Corsika program (see Corsika manual and
+// TDAS 02-11). There, phi is the azimuth of the momentum vector of 
+// particles, and is measured from the north direction, anticlockwise 
+// (i.e, west is phi=90 degrees). When it refers to the telescope 
+// orientation, it is the azimuth of a vector along the telescope axis, 
+// going from the camera to the mirror. So, fTelescopeTheta=90, 
+// fTelescopePhi = 0 means the telescope is pointing horizontally towards 
+// South. 
+//
+//
+// Version 1: 
+//  New container to keep the very basic informations on the
+//  original MC events produced by Corsika
+//
+// Version 2:
+//  - added typedef for ParticleId_t from MMcEvt
+//  - replaced MMcEvt::ParticleId_t by ParticleId_t
+//
+// Version 3:
+//  - moved fPhi   from MMcEvt
+//  - moved fTheta from MmcEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcEvtBasic.h"
+
+#include "MString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MMcEvtBasic);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Calls Clear()
+//
+MMcEvtBasic::MMcEvtBasic()
+{
+    fName  = "MMcEvtBasic";
+    fTitle = "Basic event info from Monte Carlo";
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Use this to set all data members
+//
+// THIS FUNCTION IS FOR THE SIMULATION OLNY.
+// DON'T USE THIS MEMBERFUNCTION IN THE ANALYSIS.
+//
+MMcEvtBasic::MMcEvtBasic(ParticleId_t usPId, Float_t fEner,
+                         Float_t fImpa, Float_t fTPhii, Float_t fTThet)
+   : fPartId(usPId), fEnergy(fEner), fImpact(fImpa),
+     fTelescopePhi(fTPhii), fTelescopeTheta(fTThet), fTheta(0), fPhi(0)
+{
+    fName  = "MMcEvtBasic";
+    fTitle = "Basic event info from Monte Carlo";
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy operator. Copy all data members
+//
+void MMcEvtBasic::operator=(const MMcEvtBasic &evt)
+{
+    fPartId         = evt.fPartId;
+    fEnergy         = evt.fEnergy;
+    fImpact         = evt.fImpact;
+    fTelescopePhi   = evt.fTelescopePhi;
+    fTelescopeTheta = evt.fTelescopeTheta;
+    fPhi            = evt.fPhi;
+    fTheta          = evt.fTheta;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Reset all values.
+//
+void MMcEvtBasic::Clear(Option_t *opt)
+{
+    fPartId         = kUNDEFINED;
+
+    fEnergy         = -1;
+    fImpact         = -1;
+
+    fTelescopePhi   = 0;
+    fTelescopeTheta = 0;
+
+    fTheta          = 0;
+    fPhi            = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill all data members
+//
+void MMcEvtBasic::Fill(ParticleId_t usPId, Float_t fEner,
+		       Float_t fImpa, Float_t fTPhii, Float_t fTThet)
+{
+    fPartId         = usPId;
+
+    fEnergy         = fEner;
+    fImpact         = fImpa;
+
+    fTelescopePhi   = fTPhii;
+    fTelescopeTheta = fTThet;
+}
+
+TString MMcEvtBasic::GetParticleName(Int_t id)
+{
+    switch (id)
+    {
+    case kUNDEFINED:  return "Undefined";
+    case kGAMMA:      return "Gamma";
+    case kPOSITRON:   return "Positron";
+    case kELECTRON:   return "Electron";
+    case kANTIMUON:   return "Anti-Muon";
+    case kMUON:       return "Muon";
+    case kPI0:        return "Pi-0";
+    case kNEUTRON:    return "Neutron";
+    case kPROTON:     return "Proton";
+    case kHELIUM:     return "Helium";
+    case kOXYGEN:     return "Oxygen";
+    case kIRON:       return "Iron";
+    case kArtificial: return "Artificial";
+    case kNightSky:   return "NightSky";
+    }
+
+    return MString::Format("Id:%d", id);
+}
+
+TString MMcEvtBasic::GetParticleSymbol(Int_t id)
+{
+    switch (id)
+    {
+    case kUNDEFINED:return "N/A";
+    case kGAMMA:    return "\\gamma";
+    case kPOSITRON: return "e^{+}";
+    case kELECTRON: return "e^{-}";
+    case kANTIMUON: return "\\mu^{+}";
+    case kMUON:     return "\\mu^{-}";
+    case kPI0:      return "\\pi^{0}";
+    case kNEUTRON:  return "n";
+    case kPROTON:   return "p";
+    case kHELIUM:   return "He";
+    case kOXYGEN:   return "O";
+    case kIRON:     return "Fe";
+    case kNightSky: return "\\gamma_{NSB}";
+    }
+
+    return MString::Format("Id:%d", id);
+}
+
+TString MMcEvtBasic::GetEnergyStr(Float_t e)
+{
+    if (e>=1000)
+        return MString::Format("%.1fTeV", e/1000);
+
+    if (e>=10)
+        return MString::Format("%dGeV", (Int_t)(e+.5));
+
+    if (e>=1)
+        return MString::Format("%.1fGeV", e);
+
+    return MString::Format("%dMeV", (Int_t)(e*1000+.5));
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the container.
+//
+//  if you specify an option only the requested data members are printed:
+//  allowed options are: id, energy, impact
+//
+void MMcEvtBasic::Print(Option_t *opt) const
+{
+    //
+    //  print out the data member on screen
+    //
+    TString str(opt);
+    if (str.IsNull())
+    {
+        *fLog << all << endl;
+        *fLog << "Monte Carlo output:" << endl;
+        *fLog << " Particle Id:    " << GetParticleName() << endl;
+        *fLog << " Energy:         " << fEnergy << "GeV" << endl;
+        *fLog << " Impactparam.:   " << fImpact/100 << "m" << endl;
+        *fLog << endl;
+        return;
+    }
+    if (str.Contains("id", TString::kIgnoreCase))
+        *fLog << "Particle: " << GetParticleName() << endl;
+    if (str.Contains("energy", TString::kIgnoreCase))
+        *fLog << "Energy: " << fEnergy << "GeV" << endl;
+    if (str.Contains("impact", TString::kIgnoreCase))
+        *fLog << "Impact: " << fImpact << "cm" << endl;
+}
Index: branches/Mars_McMismatchStudy/mmc/MMcEvtBasic.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcEvtBasic.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcEvtBasic.h	(revision 17960)
@@ -0,0 +1,105 @@
+#ifndef MARS_MMcEvtBasic
+#define MARS_MMcEvtBasic
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MMcEvtBasic : public MParContainer
+{
+public:
+    enum ParticleId_t
+    {
+        kUNDEFINED  =   -1,
+        kGAMMA      =    1,
+        kPOSITRON   =    2,
+        kELECTRON   =    3,
+        kANTIMUON   =    5,
+        kMUON       =    6,
+        kPI0        =    7,
+        kNEUTRON    =   13,
+        kPROTON     =   14,
+        kHELIUM     =  402,
+        kOXYGEN     = 1608,
+        kIRON       = 5626,
+        kArtificial = 9998,
+        kNightSky   = 9999
+    };
+
+protected:
+  ParticleId_t fPartId;  // Type of particle
+  Float_t      fEnergy;  // [GeV] Energy
+  Float_t      fImpact;  // [cm] impact parameter
+
+  // Telescope orientation (see TDAS 02-11 regarding the 
+  // precise meaning of these angles):
+  Float_t      fTelescopePhi;    // [rad]
+  Float_t      fTelescopeTheta;  // [rad]
+
+  Float_t      fTheta;           // [rad] Theta angle of event
+  Float_t      fPhi;             // [rad] Phi angle of event (see class description)
+
+public:
+  MMcEvtBasic();
+  MMcEvtBasic(ParticleId_t, Float_t, Float_t, Float_t, Float_t);
+  void operator=(const MMcEvtBasic &evt);
+
+  // Getter
+  ParticleId_t GetPartId() const { return fPartId; }
+
+  Float_t GetEnergy()  const { return fEnergy; }
+  Float_t GetImpact()  const { return fImpact; }
+
+  Float_t GetTelescopePhi() const { return fTelescopePhi; }
+  Float_t GetTelescopeTheta() const { return fTelescopeTheta; }
+
+  Float_t GetParticlePhi() const { return fPhi; }
+  Float_t GetParticleTheta() const { return fTheta; }
+
+  //Float_t GetTheta() const { return fTheta; }
+  //Float_t GetPhi() const { return fPhi ;  }
+
+  static TString GetParticleName(Int_t id);
+  static TString GetParticleSymbol(Int_t id);
+  static TString GetEnergyStr(Float_t e);
+
+  TString GetParticleSymbol() const
+  {
+      return GetParticleSymbol(fPartId);
+  }
+
+  TString GetParticleName() const
+  {
+      return GetParticleName(fPartId);
+  }
+
+  TString GetEnergyStr() const
+  {
+      return GetEnergyStr(fEnergy);
+  }
+
+  // Setter
+  void SetPartId(ParticleId_t id) { fPartId = id; }
+  void SetEnergy(Float_t Energy)  { fEnergy=Energy; }              //Set Energy
+  void SetImpact(Float_t Impact)  { fImpact=Impact;}               //Set impact parameter
+
+  void SetTelescopeTheta(Float_t Theta) { fTelescopeTheta=Theta; }
+  void SetTelescopePhi  (Float_t Phi)   { fTelescopePhi=Phi; }
+
+  void SetParticleTheta(Float_t Theta)  { fTheta=Theta; }
+  void SetParticlePhi  (Float_t Phi)    { fPhi=Phi; }
+
+  //void SetTheta(Float_t Theta) { fTheta=Theta; }                //Set Theta angle
+  //void SetPhi(Float_t Phi)     { fPhi=Phi;  }                   //Set Phi angle
+
+  void Fill(ParticleId_t, Float_t, Float_t, Float_t, Float_t);
+
+  // TObject
+  void Clear(Option_t *opt=NULL);
+  void Print(Option_t *opt=NULL) const;
+
+  ClassDef(MMcEvtBasic, 3) //Stores Basic Montecarlo Information of one event
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/MMcFadcHeader.cxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcFadcHeader.cxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcFadcHeader.cxx	(revision 17960)
@@ -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): Unknown
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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
+//
+// 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).
+//
+// 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).
+//
+// Version 5:
+//   Added member fGainFluctuations
+//
+// Version 6:
+//   Added member fNoiseGainFluctuations
+//
+// Version 7:
+//   Derived class from MCamEvent
+//
+// Version 9:
+//   Added member fElecNoiseFileName
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMcFadcHeader.hxx"
+
+#include <iostream>
+
+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   ;
+  }
+}
+
+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 ; 
+}
+
+Bool_t MMcFadcHeader::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if ((UInt_t)idx>=GetNumPixel())
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+        val = fPedesMean[idx];
+        break;
+    case 1:
+        val = fPedesSigmaHigh[idx];
+        break;
+    case 2:
+        val = fPedesSigmaLow[idx];
+        break;
+    case 3:
+        val = fElecNoise[idx];
+        break;
+    case 4:
+        val = fDigitalNoise[idx];
+        break;
+    default:
+        return kFALSE;
+    }
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mmc/MMcFadcHeader.hxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcFadcHeader.hxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcFadcHeader.hxx	(revision 17960)
@@ -0,0 +1,138 @@
+#ifndef MARS_MMcFadcHeader
+#define MARS_MMcFadcHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#include "MFadcDefine.h"
+
+class MMcFadcHeader : public MParContainer, public MCamEvent {
+ 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 
+
+  TString fElecNoiseFileName; 
+  // Name of the file from which the electronic noise used in the 
+  // simulation has been read in, if the input card option "fadc_noise_from_file"
+  // of the camera simulation has been chosen.
+
+  Bool_t  fGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the signal 
+  // (=> default in camera simulation)
+
+  Bool_t  fNoiseGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the NSB noise 
+  // (=> default in StarResponse program)
+
+
+ public:
+  MMcFadcHeader(const char *name=NULL, const char *title=NULL);
+
+  void Print(Option_t *opt=NULL) const;
+  
+  void SetShape(Float_t shape){
+    fFadcShape=shape;
+  }
+
+  void SetShapeOuter(Float_t shape){
+    fFadcShapeOuter=shape;
+  }
+
+  void SetLow2High(Float_t l2h){
+    fLow2HighGain=l2h;
+  }
+
+  void SetAmplitud(Float_t amp, Float_t ampout=0.0){
+    fAmplFadc=amp;
+    fAmplFadcOuter=ampout;
+ }
+
+  void SetFwhm(Float_t fwhm, Float_t fwhmout=0.0){
+    fFwhmFadc=fwhm;
+    fFwhmFadcOuter=fwhmout;
+  }
+
+  void SetPedestal(Float_t *mean, Int_t dim){
+    for (Int_t i=0;i<dim;i++)
+      fPedesMean[i]=mean[i];
+  }
+
+  void SetPedestalSigma(Float_t *sigmalo, Float_t *sigmahi, Int_t dim){
+    for (Int_t i=0;i<dim;i++){
+      fPedesSigmaLow[i]=sigmalo[i];
+      fPedesSigmaHigh[i]=sigmahi[i];
+    }
+  }
+
+  void SetElecNoise(Float_t *sigmae, Float_t *sigmad, Int_t dim){
+    for (Int_t i=0;i<dim;i++){
+      fElecNoise[i]=sigmae[i];
+      fDigitalNoise[i]=sigmad[i];
+    }
+  }
+  
+  void SetGainFluctuations(Bool_t x) { fGainFluctuations = x; }
+  void SetNoiseGainFluctuations(Bool_t x) { fNoiseGainFluctuations = x; }
+
+  Float_t GetPedestal(UInt_t i) const    { return fPedesMean[i]; }
+  Float_t GetPedestalRmsHigh(UInt_t i) const { return fPedesSigmaHigh[i]; }
+  Float_t GetPedestalRmsLow(UInt_t i) const { return fPedesSigmaLow[i]; }
+  Float_t GetElecNoise(UInt_t i) const { return fElecNoise[i]; }
+  Float_t GetDigitalNoise(UInt_t i) const { return fElecNoise[i]; }
+  Float_t GetAmplitud() const { return fAmplFadc; }
+  Float_t GetAmplitudOuter() const { return fAmplFadcOuter; }
+  Float_t GetLow2HighGain() const { return fLow2HighGain; }
+
+  UInt_t GetNumPixel() const { return MFADC_CHANNELS; }
+
+  // MCamEvent
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void   DrawPixelContent(Int_t num) const { }
+
+  ClassDef(MMcFadcHeader, 10)  //Stores Montecarlo Information describing the FADC behaviour
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/MMcRunHeader.cxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcRunHeader.cxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcRunHeader.cxx	(revision 17960)
@@ -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  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).
+//
+//                                                     
+// Class Version 5: 
+// ----------------
+// removed members fSourceOffsetTheta, fSourceOffsetPhi (were no longer used)                                  //
+//                   
+// Class Version 6: 
+// ----------------
+// removed members fTelesTheta, fTelesPhi (were no longer used)                                  //
+//
+// Class Version 7:
+// ----------------
+// + Float_t fRandomPointingConeSemiAngle;
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MMcRunHeader.hxx"
+
+#include <fstream>
+#include <iomanip>
+
+#include "MLog.h"
+
+ClassImp(MMcRunHeader);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+//
+MMcRunHeader::MMcRunHeader(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcRunHeader";
+    fTitle = title ? title : "Raw Run Header Information";
+
+    fMcRunNumber =0;
+    fProductionSite = 0;
+    fDateRunMMCs = 0;
+    fDateRunCamera = 0;
+    fNumTrigCond = 0;
+    fAllEvtsTriggered = 0 ;
+    fMcEvt = 0;
+    fMcTrig = 0;
+    fMcFadc = 0;
+    fRawEvt = 0;
+    fElecNoise = 0;
+    fStarFieldRotate = 0;
+    fNumAnalisedPixels = 0;
+    fNumSimulatedShowers = 0;
+    fNumStoredShowers = 0;
+    fNumEvents = 0;
+
+    fStarFieldRaH = 0;
+    fStarFieldRaM = 0;
+    fStarFieldRaS = 0;
+    fStarFieldDeD = 0;
+    fStarFieldDeM = 0;
+    fStarFieldDeS = 0;
+
+    fNumPheFromDNSB = 0.0;
+    fShowerThetaMax = 0.0;
+    fShowerThetaMin = 0.0;
+    fShowerPhiMax = 0.0;
+    fShowerPhiMin = 0.0;
+
+    fImpactMax = -1;
+
+    fCWaveLower = 0.0;
+    fCWaveUpper = 0.0;
+
+    fNumObsLev = 0;
+    for (int i=0; i<10; i++){
+      fHeightLev[i]=0.0;
+    }
+    fSlopeSpec = 0.0;
+
+    fCorsikaVersion = UShort_t(-1);
+    fReflVersion    = UShort_t(-1);
+    fCamVersion     = UShort_t(-1);
+
+    fOpticLinksNoise= 0;
+
+    fRandomPointingConeSemiAngle=0;
+}
+
+// -------------------------------------------------------------------------
+//
+// Fill. Put data in the container
+//
+void MMcRunHeader::Fill(const Float_t  runnumber,
+			const UInt_t   productionsite,
+			const Float_t  daterunMMCs,
+			const Float_t   daterunCamera,
+			const UInt_t   numtrigcond,
+			const Byte_t   allevts,
+			const Byte_t   mcevt,
+			const Byte_t   mctrig,
+			const Byte_t   mcfadc,
+			const Byte_t   rawevt,
+			const Byte_t   elecnoise, 
+			const Int_t    numanalpixels,
+			const UInt_t   numsim,
+			const UInt_t   numsto,
+			const Byte_t   starfieldrotate,
+			const Int_t    sfRaH,
+			const Int_t    sfRaM,
+			const Int_t    sfRaS,
+			const Int_t    sfDeD,
+			const Int_t    sfDeM,
+			const Int_t    sfDeS,
+			const Float_t  numdnsb,
+			const Float_t  shthetamax,
+			const Float_t  shthetamin,
+			const Float_t  shphimax,
+			const Float_t  shphimin,
+			const Float_t  impactmax,
+			const Float_t  cwavelower,
+			const Float_t  cwaveupper,
+			const Float_t  slopespec,
+			const UInt_t   numObslev,
+			const Float_t  heightlev[10],
+			const UInt_t   corsika,
+			const UInt_t   refl,
+			const UInt_t   cam,
+                        const Byte_t   opticnoise,
+                        const Float_t  conesmiangle)
+{
+    fMcRunNumber =runnumber;
+    fProductionSite = productionsite;
+    fDateRunMMCs = daterunMMCs;
+    fDateRunCamera = daterunCamera;
+    fNumTrigCond = numtrigcond;
+    fAllEvtsTriggered = allevts;
+    fMcEvt = mcevt;
+    fMcTrig = mctrig;
+    fMcFadc = mcfadc;
+    fRawEvt = rawevt;
+    fElecNoise = elecnoise;
+    fStarFieldRotate = starfieldrotate;
+    fNumAnalisedPixels = numanalpixels;
+    fNumSimulatedShowers = numsim;
+    fNumStoredShowers = numsto;
+    fNumEvents = numsto;
+
+    fStarFieldRaH = sfRaH;
+    fStarFieldRaM = sfRaM;
+    fStarFieldRaS = sfRaS;
+    fStarFieldDeD = sfDeD;
+    fStarFieldDeM = sfDeM;
+    fStarFieldDeS = sfDeS;
+
+    fNumPheFromDNSB = numdnsb;
+    fShowerThetaMax = shthetamax;
+    fShowerThetaMin = shthetamin;
+    fShowerPhiMax = shphimax;
+    fShowerPhiMin = shphimin;
+
+    fImpactMax=impactmax;
+
+    fCWaveLower = cwavelower;
+    fCWaveUpper = cwaveupper;
+
+    fNumObsLev = numObslev;
+    for (UInt_t i=0; i<numObslev; i++){
+      fHeightLev[i]=heightlev[i];
+    }
+    fSlopeSpec = slopespec;
+
+    fCorsikaVersion = corsika;
+    fReflVersion = refl;
+    fCamVersion = cam;
+    fOpticLinksNoise= opticnoise;
+
+    fRandomPointingConeSemiAngle=conesmiangle;
+}
+
+// -------------------------------------------------------------------------
+//
+// 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: branches/Mars_McMismatchStudy/mmc/MMcRunHeader.hxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcRunHeader.hxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcRunHeader.hxx	(revision 17960)
@@ -0,0 +1,172 @@
+#ifndef MARS_MMcRunHeader
+#define MARS_MMcRunHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+// -------------------------------------------------------------
+//
+//  The following data member are in use:
+//
+//    fCorsikaVersion        MHCollectionArea
+//    fReflVersion           MSrcPosCalc
+//    fCamVersion            MMcCalibrationUpdate, MReadMarsFile,
+//                           MMcPedestalCopy, MMcPedestalNSBAdd
+//    fStarField*            MMcBadPixelSet
+//    fImpactMax             MHCollectionArea
+//    fNumSimulatedShowers   MHCollectionArea
+//    [fAllEvtsTriggered]    MHCollectionArea
+//    fNumPheFromDNSB        MMcPedestalNSBAdd
+//
+// -------------------------------------------------------------
+
+class MMcRunHeader : public MParContainer
+{
+private:
+  UInt_t  fNumTrigCond;     // Number of trigger conditions in this file,
+  // zero means single condition mode
+  
+  //-- 0 means: MMcTrig
+  //-- 1 means: MMcTrig;1
+  //-- 2 means: MMcTrig;1 MMcTrig;2
+  
+  Byte_t  fAllEvtsTriggered;  // boolean that indicates is all images are 
+                              // saved or only the ones that trigger
+
+  Byte_t  fMcEvt;           // McEvt stored or not
+  Byte_t  fMcTrig;          // McTrig stored or not
+  Byte_t  fMcFadc;          // McFadc stored or not
+
+  Int_t   fNumAnalisedPixels;  // Number of analised pixels
+  
+  UInt_t  fNumSimulatedShowers; // Number of showers that were simualted
+  UInt_t  fNumStoredShowers;    // Number of store showers in this run
+  UInt_t  fNumEvents;           // Number of events in this root file
+  
+  //  Coordinates of the Starfield
+  
+  Int_t fStarFieldRaH;
+  Int_t fStarFieldRaM;
+  Int_t fStarFieldRaS;
+  Int_t fStarFieldDeD;
+  Int_t fStarFieldDeM;
+  Int_t fStarFieldDeS;
+
+  Float_t fNumPheFromDNSB;  // Number of phe/ns from diffuse NSB
+  
+  //  Angular range used in the Corsika showers generation (degrees)
+  Float_t fShowerThetaMax; // [deg]
+  Float_t fShowerThetaMin; // [deg]
+  Float_t fShowerPhiMax; // [deg] See note in class description.
+  Float_t fShowerPhiMin; // [deg] See note in class description.
+
+  //  Maximum impact parameter in the input rfl file
+  Float_t fImpactMax; // [cm] 
+
+  UShort_t fCorsikaVersion;
+  UShort_t fReflVersion;
+  UShort_t fCamVersion;
+
+  // ---- Run Header Informations ----
+  Float_t fMcRunNumber;     // Run Number
+  UInt_t  fProductionSite;  // code to know where the run was generated
+  Float_t fDateRunMMCs;     // Date of the MMCs production
+  Float_t fDateRunCamera;   // Date, when the Camera program is run.
+
+  Byte_t  fRawEvt;          // RawEvt[Data,Hedaer] stored or not
+
+  Byte_t  fElecNoise;       // Electronic Noise simulated or not
+  Byte_t  fStarFieldRotate; // Is the starfield rotation 
+                            // switched on (1) or off (0)
+
+  //  Wavelength limits for the Cerenkov photons
+  Float_t fCWaveLower;
+  Float_t fCWaveUpper;
+
+  //  Observation levels  
+  UInt_t    fNumObsLev;
+  Float_t   fHeightLev[10]; 
+
+  //  Spectral index
+  Float_t   fSlopeSpec;
+
+  // Noise from Optic Links
+  Byte_t  fOpticLinksNoise;  // Noise from Optic Links simualted or not.
+
+  // Semiaperture of the cone around the direction of the primary within which the
+  // orientation of the telescope axis is scattered (deg). This is used in reflector
+  // simulation to re-use each Corsika event more than once.
+  Float_t fRandomPointingConeSemiAngle;
+
+
+public:
+  MMcRunHeader(const char *name=NULL, const char *title=NULL);
+
+  void Fill(const Float_t  runnumber,
+	    const UInt_t   productionsite,
+	    const Float_t  daterunMMCs,
+	    const Float_t   daterunCamera,
+	    const UInt_t   numtrigcond,
+	    const Byte_t   allevts,
+	    const Byte_t   mcevt,
+	    const Byte_t   mctrig,
+	    const Byte_t   mcfadc,
+	    const Byte_t   rawevt,
+	    const Byte_t   elecnoise, 
+	    const Int_t    numanalpixels,
+	    const UInt_t   numsim,
+	    const UInt_t   numsto,
+	    const Byte_t   starfieldrotate,
+	    const Int_t    sfRaH,
+	    const Int_t    sfRaM,
+	    const Int_t    sfRaS,
+	    const Int_t    sfDeD,
+	    const Int_t    sfDeM,
+	    const Int_t    sfDeS,
+	    const Float_t  numdnsb,
+	    const Float_t  shthetamax,
+	    const Float_t  shthetamin,
+	    const Float_t  shphimax,
+	    const Float_t  shphimin,
+	    const Float_t  impactmax,
+	    const Float_t  cwavelower,
+	    const Float_t  cwaveupper,
+	    const Float_t  slopespec,
+	    const UInt_t   num0bslev,
+	    const Float_t  heightlev[10],
+	    const UInt_t   corsika,                
+	    const UInt_t   refl,
+	    const UInt_t   cam,
+            const Byte_t   opticnoise,
+            const Float_t  conesmiangle=0
+	    );
+  
+  void     GetStarFieldRa(Int_t *hour, Int_t *minute, Int_t *second) const;
+  void     GetStarFieldDec(Int_t *degree, Int_t *minute, Int_t *second) const;
+
+  Float_t  GetNumPheFromDNSB() const      { return fNumPheFromDNSB; }
+  UShort_t GetCamVersion() const          { return fCamVersion; }
+  UShort_t GetReflVersion() const         { return fReflVersion; }
+  UInt_t   GetNumSimulatedShowers() const { return fNumSimulatedShowers; }
+  UInt_t   GetCorsikaVersion() const      { return fCorsikaVersion; }
+  Bool_t   GetAllEvtsTriggered() const    { return fAllEvtsTriggered ? kTRUE : kFALSE; }
+
+  Float_t  GetShowerThetaMin() const { return fShowerThetaMin; } 
+  Float_t  GetShowerThetaMax() const { return fShowerThetaMax; } 
+
+  Float_t  GetShowerPhiMin() const { return fShowerPhiMin; }
+  Float_t  GetShowerPhiMax() const { return fShowerPhiMax; }
+
+  Float_t GetImpactMax() const            {return fImpactMax;}
+
+  Bool_t IsCeres() const { return fCamVersion==UShort_t(-1); }
+
+  void SetNumSimulatedShowers(UInt_t n) { fNumSimulatedShowers=n; }
+  void SetImpactMax(Float_t im) { fImpactMax=im; }
+  void SetCorsikaVersion(UInt_t v) { fCorsikaVersion=v; }
+
+  ClassDef(MMcRunHeader, 7)	// storage container for general run info
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/MMcTrig.cxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcTrig.cxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcTrig.cxx	(revision 17960)
@@ -0,0 +1,141 @@
+#include "MMcTrig.hxx"
+
+#include <iostream>
+
+
+//==========
+// MMcTrig
+//    
+// This class handles and contains the MonteCarlo information
+// with which the events have been generated
+// This information exists for each event.
+//
+// This the second version of this output class. Old root files, which have
+// a previous version of this class, are still compatibles and can be used.
+// But of course, you can no try to get infromatino in these old files about
+// the new data members.
+//
+// The fPixelsFirst array has been increased from 273 (which was the trigger 
+// zone) to 577 (which is the full Camera)
+//
+////////////////////////////////////////////////////////////// 
+
+
+ClassImp(MMcTrig);
+
+using namespace std;
+
+
+MMcTrig::MMcTrig(const char *name, const char *title) {
+  //
+  //  default constructor
+  //  set all values to zero
+
+  
+  fName  = name  ? name  : "MMcTrig";
+  fTitle = title ? title : "Trigger info from Monte Carlo";
+
+    
+  Int_t i,j;
+
+  fNumFirstLevel  = 0 ;
+
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME+1;i++){
+    fTimeFirst[i]    = -99.9;
+    for(j=0;j<CAMERA_PIXELS/8+1;j++){
+      fPixelsFirst[j][i]   = 0;
+    }
+  }
+
+  fNumSecondLevel = 0 ; 
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL2_DEAD_TIME+1;i++){
+    fFirstToSecond[i]=0;
+  }
+}
+
+MMcTrig::~MMcTrig() {
+  //
+  //  default destructor
+  //
+}
+
+void MMcTrig::SetTime(Float_t t, Int_t i)
+{
+    if (i>TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME+1  || i<1)
+    {
+        cout << "fNumFirstLevel out of range. Time will be -99" << endl;
+        return;
+    }
+
+    fTimeFirst[i-1]=t;
+}
+
+void MMcTrig::Clear(Option_t *opt) {
+  //
+  //  
+  //  reset all values to zero
+  Int_t i,j;
+
+  fNumFirstLevel  = 0 ;
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME+1;i++){
+    fTimeFirst[i]    = -99.9;
+    for(j=0;j<CAMERA_PIXELS/8+1;j++){
+      fPixelsFirst[j][i]   = 0;
+    }
+  }
+
+  fNumSecondLevel = 0 ; 
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL2_DEAD_TIME+1;i++){
+    fFirstToSecond[i]=0;
+  }
+
+  //  cout << "MMcTrig::Clear() " << endl ; 
+}
+
+void MMcTrig::Print(Option_t *option) const
+{
+    //
+    //  print out the data member on screen
+    //
+    cout << "Monte Carlo Trigger output:" << endl;
+    cout << " First Level Trigger in this Event: " << fNumFirstLevel << endl;
+    if (!TString(option).Contains("short"))
+    {
+        cout << " Times of first Level Trigger in this Event: ";
+        for (int i=0; i<fNumFirstLevel; i++)
+            cout << fTimeFirst[i] << " ";
+        cout << endl;
+
+        cout << " Pixels of first  Level Trigger in this Event: ";
+        for (int i=0; i<fNumFirstLevel; i++)
+            for(int j=0; j<CAMERA_PIXELS/8+1; j++)
+                cout << (int)fPixelsFirst[j][i] << " ";
+        cout << endl;
+    }
+
+    cout << " Second Level Trigger in this Event: " << fNumSecondLevel << endl;
+    cout << endl;
+}
+
+Byte_t MMcTrig::IsPixelFired(Int_t npix, Int_t nfirstlevel){
+  //======================================================================
+  //
+  //  It returns >1 if the pixel npix was fired when the nfirstlevel
+  //  first level trigger happened, 0 if not.
+  //
+  
+  const Int_t  body=npix/8;
+  const Byte_t reminder= 1<<(npix%8);
+
+  return reminder&fPixelsFirst[body][nfirstlevel];
+  /*
+  Byte_t ret=0;
+  Byte_t reminder;
+  Int_t body;
+
+  body=npix/8;
+  reminder=(Byte_t)(pow(2,npix%8));
+  ret=reminder&fPixelsFirst[body][nfirstlevel];
+  return(ret);
+  */
+}
Index: branches/Mars_McMismatchStudy/mmc/MMcTrig.hxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcTrig.hxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcTrig.hxx	(revision 17960)
@@ -0,0 +1,70 @@
+#ifndef MARS_MMcTrig
+#define MARS_MMcTrig
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MTriggerDefine
+#include "MTriggerDefine.h"
+#endif
+#ifndef MARS_Mdefine
+#include "Mdefine.h"
+#endif
+
+class MMcTrig : public MParContainer {
+ private:
+
+  Short_t fNumFirstLevel  ;    // Number of First Level Trigger in this Event
+  Short_t fNumSecondLevel ;    // Number of Second Level Trigger in this Event
+
+  Float_t fTimeFirst[((Int_t)(TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME))+1];
+                            // Time when it triggers
+  Byte_t fPixelsFirst[((Int_t)(CAMERA_PIXELS/8))+1][((Int_t)(TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME))+1];
+                            // Pixel which are above threshold when trigger happens
+  Short_t fFirstToSecond[((Int_t)(TOTAL_TRIGGER_TIME/LEVEL2_DEAD_TIME))+1];
+
+ public:
+  MMcTrig(const char *name=NULL, const char *title=NULL);
+
+  ~MMcTrig(); 
+
+  void Clear(Option_t *opt=NULL);
+  
+  void Print(Option_t *opt=NULL) const;
+
+  void SetFirstLevel  ( Short_t nTr ) {
+    fNumFirstLevel = nTr ; 
+  } 
+  void SetSecondLevel ( Short_t nTr ) {
+    fNumSecondLevel = nTr ; 
+  } 
+
+  void SetTime( Float_t t, Int_t i);
+
+  void SetMapPixels(Byte_t *map,Int_t nfirst){
+    //  
+    //  It sets the map of pixel that are above the trheshold
+    //
+
+    int i;
+
+    for(i=0;i<((Int_t)(CAMERA_PIXELS/8))+1;i++){
+      fPixelsFirst[i][nfirst]=map[i];
+    }
+  }
+
+  Int_t GetFirstLevel() const {
+    return ( fNumFirstLevel );  
+  }
+
+  Int_t GetNumFirstLevel() const {
+    return ( fNumFirstLevel );  
+  }
+
+  Byte_t IsPixelFired(Int_t npix, Int_t nfirstlevel);
+
+  ClassDef(MMcTrig, 4)  //Stores Montecarlo Information (number of 1st, 2nd level triggers)
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/MMcTrigHeader.cxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcTrigHeader.cxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcTrigHeader.cxx	(revision 17960)
@@ -0,0 +1,71 @@
+#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 
+//
+// Version 4
+//   Added data members fGainFluctuations and fNoiseGainFluctuations
+//
+//
+/////////////////////////
+
+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 ;
+}
+
+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: branches/Mars_McMismatchStudy/mmc/MMcTrigHeader.hxx
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MMcTrigHeader.hxx	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MMcTrigHeader.hxx	(revision 17960)
@@ -0,0 +1,128 @@
+#ifndef MARS_MMcTrigHeader
+#define MARS_MMcTrigHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MTriggerDefine
+#include "MTriggerDefine.h"
+#endif
+#ifndef MARS_Mdefine
+#include "Mdefine.h"
+#endif
+
+class MMcTrigHeader : public MParContainer{
+ private:
+
+  Short_t fTopology     ;      // Topology of the trigger
+                                   // 0 = N-1 neighbours of one pixel
+                                   // 1 = N neighbours
+                                   // 2 = N closed pack
+  Short_t fMultiplicity ;      // Pixel multiplicity of trigger configuration
+  Float_t fThreshold[CAMERA_PIXELS] ; // Threshold for trigger
+  UInt_t fTrigPattern[2];     // Used to inddentify with 
+                              // RawEvt::Trigger Pattern identification  
+  Float_t  fTrigShape   ;   // a number that indicate the shape type of 
+                            // the signal   
+                            // = 0 --> a gaussian  
+  Float_t  fAmplTrig    ;   // the amplitude of the trigger in mV
+  Float_t  fFwhmTrig    ;   // the width of the signal in nsec
+  Float_t  fOverlapingTime;// Minimum coincidence time
+  Float_t  fGateLeng;       // the length of the digital signal if analog 
+                            // signal is above threshold
+  Float_t  fElecNoiseTrig;  // The width of the gaussian noise is that times
+                            // the amplitude of the single phe response 
+                            // for the trigger
+
+  Bool_t  fGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the signal 
+  // (=> default in camera simulation)
+
+  Bool_t  fNoiseGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the NSB noise 
+  // (=> default in StarResponse program)
+
+
+ public:
+  MMcTrigHeader() ;
+
+  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==0 && loi==0) {
+      fTrigPattern[0]= (UInt_t) fThreshold[0];
+      fTrigPattern[1]= (UInt_t) (100*fMultiplicity+fTopology);
+    }
+    else {
+      fTrigPattern[0]=upi;
+      fTrigPattern[1]=loi;
+    }
+  }
+
+  void SetShape(Float_t shape){
+    fTrigShape=shape;
+  }
+
+  void SetAmplitud(Float_t amp){
+    fAmplTrig=amp;
+ }
+
+  void SetFwhm(Float_t fwhm){
+    fFwhmTrig=fwhm;
+  }
+
+  void SetOverlap(Float_t overlap){
+    fOverlapingTime=overlap;
+  }
+
+  void SetGate(Float_t gate){
+    fGateLeng=gate;
+  }
+
+  void SetElecNoise( Float_t elecnoise){
+    fElecNoiseTrig = elecnoise;
+  }
+
+  void SetGainFluctuations(Bool_t x) { fGainFluctuations = x; }
+  void SetNoiseGainFluctuations(Bool_t x) { fNoiseGainFluctuations = x; }
+
+  Short_t GetMultiplicity() { return fMultiplicity; }
+
+  Float_t GetMeanThreshold()
+  {
+    int i;
+    Float_t sum = 0., trigpix = 0.;
+    for(i=0;i<CAMERA_PIXELS;i++)
+    {
+      if (fThreshold[i] < 1.e6 && fThreshold[i] > 0.)
+      {
+        sum += fThreshold[i];
+        trigpix += 1.;
+      }
+    }
+
+    return (sum / trigpix);
+  }
+
+
+  ClassDef(MMcTrigHeader, 5)  //Stores Montecarlo Information which describes the used trigger
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/MTriggerDefine.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/MTriggerDefine.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/MTriggerDefine.h	(revision 17960)
@@ -0,0 +1,114 @@
+#ifndef MARS_MTriggerDefine
+#define MARS_MTriggerDefine
+//
+//
+//      In this file are the fundamental definitions for the class MCTrigger
+//
+// Number of pixels in the trigger region (used by camera simulation,
+// see camera.cxx.
+//
+#define TRIGGER_PIXELS_1      397
+#define TRIGGER_PIXELS_2      397
+#define TRIGGER_PIXELS_3      1657
+#define TRIGGER_PIXELS_4      547  // For MGeomCamMagic1183, PRELIMINARY!
+#define TRIGGER_PIXELS_5      397
+#define TRIGGER_PIXELS_6      1657
+#define TRIGGER_PIXELS_8      126
+#define TRIGGER_PIXELS_9      126
+//
+//      This is the number of Pixels contributing to the TRIGGER logic
+//      for each of the already implemented geometries.
+//      All Pixels-Id above that value don't do an trigger stuff. 
+//      Actually, not all of them are involved in TRIGGER logic, only the
+//      ones of them that are also in some TRIGGER_CELL 
+//   (MagicSoft/Simulation/Detector/include-MTrigger/TABLE_PIXELS_IN_CELLS)
+//
+#define TOTAL_TRIGGER_TIME    160 
+//
+//      This values defines the total range in that we try to find
+//      a trigger. 
+//
+#define LEVEL1_DEAD_TIME    50
+//
+//      Dead time of the detector after one first level trigger happens.
+//
+#define LEVEL2_DEAD_TIME    300
+//
+//      Dead time of the detector after second level trigger fires
+//
+#define TRIG_SLICES_PER_NSEC         4
+//      
+//      Each nano second is divided into the number of this values slices. 
+//      So you can get the total number of timeslices for one Pixel by 
+//      ( TOTAL_TRIGGER_TIME * SLICES_PER_NSEC ). 
+//      In the current settings this are 1000 slices
+//
+#define TRIGGER_TIME_SLICES     (TOTAL_TRIGGER_TIME*TRIG_SLICES_PER_NSEC) 
+//
+//
+//
+//
+//       ------>>>   SETTINGS for the RESPONSE FUNCTION
+// 
+#define RESPONSE_SLICES_TRIG        40
+//
+//       This is the dimension of the array containing the standard response Signal 
+//       for 1 Photoelectron, as seen at the input of the discriminators (for the 
+//       trigger simulation). Each bin corresponds to 1./TRIG_SLICES_PER_NSEC nanoseconds,
+//       so by default it is 0.25 ns and hence the total range is 10 ns. This should be 
+//       enough for any reasonable single photoelectron response (should be much narrower 
+//       than 10 ns!)
+//
+
+//       The Response function
+//       These values are discussed with Eckart. We start from this point. 
+//
+#define RESPONSE_FWHM          2. 
+
+#define RESPONSE_AMPLITUDE     1. 
+//
+//       This are the Standard values of the response function for
+//       1 photo electron. ( 1 means 1 mV per photoelectron ) 
+//
+//
+//       -------->>> SETTINGS for the DISKRIMINATORS
+//
+//
+#define CHANNEL_THRESHOLD      2.5 
+//
+//       This is the diskriminator threshold for each individual channel
+//       First we set the value to 2 unit of the RESPONSE_AMPLITUDE 
+//
+#define TRIGGER_GATE           3. 
+// 
+//       Here we set the width of the digital signal we get if the signal
+//       passes the diskriminator
+//
+//
+#define TRIGGER_OVERLAPING           0.25 
+// 
+//       Here we set the required overlaping time among pixels
+//       to be in coincidence.
+//
+//
+//      --------->>>> SETTINGS for the TRIGGER logic
+//
+//
+#define TRIGGER_CELLS          19  
+//
+//       Number of trigger cells that cover the trigger zone
+//
+#define TRIGGER_MULTI          4.  
+//
+//       We get a Level Zero Trigger, if we have a least TRIGGER_MULTI
+//       channels with a diskrimiator signal at the same time 
+//
+#define TRIGGER_GEOM           0
+//
+//      This defines the geometry required for a trigger. There exists 
+//      different meaning for this behaviour: 
+//         0 means a pixel with trigger_multi-1 neighbours
+//         1 means trigger_multi neighbours
+//         2 means trigger_multi closed neighbours
+//
+#endif
Index: branches/Mars_McMismatchStudy/mmc/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mmc/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/Makefile	(revision 17960)
@@ -0,0 +1,32 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I.  -I../mbase -I../MBase -I../mgeom -I../mgui
+
+CINT     = Mc
+
+SRCFILES = MMcTrigHeader.cxx \
+	   MMcFadcHeader.cxx \
+	   MMcRunHeader.cxx \
+	   MMcEvt.cxx \
+           MMcTrig.cxx \
+	   MMcConfigRunHeader.cc \
+	   MMcCorsikaRunHeader.cc \
+	   MMcEvtBasic.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules 
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mmc/McIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/McIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/McIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mmc/McLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/McLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/McLinkDef.h	(revision 17960)
@@ -0,0 +1,16 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+ 
+#pragma link C++ class MMcEvt+;
+#pragma link C++ class MMcEvtBasic+;
+#pragma link C++ class MMcTrig+;
+#pragma link C++ class MMcRunHeader+;
+#pragma link C++ class MMcTrigHeader+;
+#pragma link C++ class MMcFadcHeader+;
+#pragma link C++ class MMcConfigRunHeader+;
+#pragma link C++ class MMcCorsikaRunHeader+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/Mdefine.h
===================================================================
--- branches/Mars_McMismatchStudy/mmc/Mdefine.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/Mdefine.h	(revision 17960)
@@ -0,0 +1,41 @@
+#ifndef MARS_Mdefine
+#define MARS_Mdefine
+//
+//     Mdefine.h
+//
+//     defines some Values for the MAGIC telecope
+//
+
+//     Number of the Pixels in the Camera
+
+#define     CAMERA_PIXELS         3800
+
+//     Number of the Slices of one Fadc. Be carefull this is the number of 
+//     slices for one gain branch. We sample two times this number. 
+
+//     ParticleId for Monte Carlo simulation
+
+#define  GAMMA 0
+#define  PROTON 14
+#define  HELIUM 402
+#define  OXIGEN 1608
+#define  IRON 5626
+
+
+//---------------------------------------------------------
+// definition of constants
+
+#define TRUE 1
+#define FALSE 0
+
+//camera dimensions and definitions
+#define PIXEL_SIZE  0.00175  // radians
+#define PIXEL_DIST  10.0  //cm
+#define CAMERA_COLOR 13   //Background light grey
+#define DEFAULT_COLOR 1 //black
+//#define TRACK_WALL_COLOR 7   //light blue
+#define PIXEL_LINE_COLOR 15 //dark grey
+#define COLORTABLE_START 18 //Begin of colortable
+#define MAX_PH_EL 500 //upper limit for colortable
+
+#endif
Index: branches/Mars_McMismatchStudy/mmc/readme.txt
===================================================================
--- branches/Mars_McMismatchStudy/mmc/readme.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmc/readme.txt	(revision 17960)
@@ -0,0 +1,6 @@
+
+ Please be aware of that this subdirectory is used in two CVS modules.
+ 
+ If you change something it can affect the Mars and/or Monte Carlo
+ code!
+ 
Index: branches/Mars_McMismatchStudy/mmontecarlo/MMcCollectionAreaCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcCollectionAreaCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcCollectionAreaCalc.cc	(revision 17960)
@@ -0,0 +1,170 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer  1/2001
+!   Author(s): Abelardo Moralejo 2/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMcCollectionAreaCalc
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MMcCollectionAreaCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcEvtBasic.h"
+
+#include "MMcRunHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+#include "MHMcCollectionArea.h"
+
+ClassImp(MMcCollectionAreaCalc);
+
+using namespace std;
+
+////////////////////////////////////////////////////////////////////////////////
+//
+//  Constructor
+//
+MMcCollectionAreaCalc::MMcCollectionAreaCalc(const char *name, const char *title): 
+  fBinsTheta(0), fBinsEnergy(0), fSpectrum(0)
+{
+    fName  = name  ? name  : "MMcCollectionAreaCalc";
+    fTitle = title ? title : "Task to calculate the collection area";
+} 
+
+////////////////////////////////////////////////////////////////////////////////
+//
+// PreProcess. 
+// Create MHMcCollectionArea object if necessary. 
+// Search in parameter list for MBinning objects with binning in theta and E.
+// These contain the coarse binning to be used in the analysis. Then search 
+// for other necessary input containers: 
+// if MMcEvt is found, it means we are in the loop over the Events tree, 
+// and so we must fill the histogram MHMcCollectionArea::fHistSel (using 
+// MHMcCollectionArea::FillSel). If MMcEvt is not found, it means that we are in 
+// the loop over the "OriginalMC" tree, containing all the original Corsika events 
+// produced, and hence we must fill the histogram  fHistAll through 
+// MHMcCollectionArea::FillAll.
+//
+Int_t MMcCollectionAreaCalc::PreProcess (MParList *pList)
+{
+  fCollArea = (MHMcCollectionArea*)pList->FindCreateObj("MHMcCollectionArea");
+
+  // Look for the binnings of the histograms if they have not been already
+  // found in a previous loop.
+
+  if (!fBinsTheta)
+    {
+      fBinsTheta = (MBinning*) pList->FindObject("binsTheta");
+      if (!fBinsTheta)
+	{
+	  *fLog << err << "Coarse Theta binning not found... Aborting." 
+	    << endl;
+	  return kFALSE;
+	}
+    }
+
+  if (!fBinsEnergy)
+    {
+      fBinsEnergy = (MBinning*) pList->FindObject("binsEnergy");
+      if (!fBinsEnergy)
+	{
+	  *fLog << err << "Coarse Energy binning not found... Aborting." 
+		<< endl;
+	  return kFALSE;
+	}
+    }
+
+  fCollArea->SetCoarseBinnings(*fBinsEnergy, *fBinsTheta);
+
+
+  // Look for the input containers
+
+  fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+  if (fMcEvt)
+    {
+        *fLog << inf << "MMcEvt found... I will fill MHMcCollectionArea.fHistSel..." << endl;
+	return kTRUE;
+    }
+
+  *fLog << inf << "MMcEvt not found... looking for MMcEvtBasic..." << endl;
+
+
+  fMcEvtBasic = (MMcEvtBasic*) pList->FindObject("MMcEvtBasic");
+    
+  if (fMcEvtBasic)
+    {
+      *fLog << inf << "MMcEvtBasic found... I will fill MHMcCollectionArea.fHistAll..." << endl;
+      return kTRUE;
+    }
+
+  *fLog << err << "MMcEvtBasic not found. Aborting..." << endl;
+
+  return kFALSE;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+//
+// Process. Depending on whether fMcEvt or fMcEvtBasic are available, fill 
+// MHMcCollectionArea::fHistAll, else, if fMcEvt is available, fill 
+// MHMcCollectionArea::fHistSel
+//
+Int_t MMcCollectionAreaCalc::Process()
+{
+    Double_t energy = fMcEvt? fMcEvt->GetEnergy() : fMcEvtBasic->GetEnergy();
+    Double_t impact = fMcEvt? fMcEvt->GetImpact()/100. : fMcEvtBasic->GetImpact()/100.; // in m
+    Double_t theta  = fMcEvt? fMcEvt->GetTelescopeTheta()*TMath::RadToDeg() : 
+      fMcEvtBasic->GetTelescopeTheta()*TMath::RadToDeg(); // in deg
+
+    if (fMcEvt)
+      fCollArea->FillSel(energy, impact, theta);
+    else
+      fCollArea->FillAll(energy, impact, theta);
+
+    return kTRUE;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+//
+// Postprocess. If both fHistAll and fHistSel are already filled, calculate
+// effective areas. Else it means we still have to run one more loop.
+//
+Int_t MMcCollectionAreaCalc::PostProcess()
+{
+  if ( ((TH2D*)fCollArea->GetHistAll())->GetEntries() > 0 &&
+       ((TH2D*)fCollArea->GetHistSel())->GetEntries() > 0)
+    {
+      *fLog << inf << "Calculation Collection Area..." << endl;
+      fCollArea->Calc(fSpectrum);
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mmontecarlo/MMcCollectionAreaCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcCollectionAreaCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcCollectionAreaCalc.h	(revision 17960)
@@ -0,0 +1,51 @@
+#ifndef MARS_MMcCollectionAreaCalc
+#define MARS_MMcCollectionAreaCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#include <TH2.h>
+#include <TF1.h>
+
+class MParList;
+class MMcEvt;
+class MMcEvtBasic;
+class MMcTrig;
+class MHMcCollectionArea;
+class MBinning;
+
+class MMcCollectionAreaCalc : public MTask
+{
+private:
+    const MMcEvt       *fMcEvt;
+    const MMcEvtBasic  *fMcEvtBasic;
+    const MMcTrig      *fMcTrig;
+
+    MBinning           *fBinsTheta;
+    MBinning           *fBinsEnergy;
+    // Coarse zenith angle and energy bins used in the analysis
+
+    TF1                *fSpectrum; 
+    // Tentative energy spectrum. This modifies slightly the calculation
+    // of the effective area (see MHMcCollectionArea::Calc)
+
+
+    MHMcCollectionArea *fCollArea;
+
+    TString fObjName;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MMcCollectionAreaCalc(const char *name = NULL, const char *title = NULL);
+
+    void SetSpectrum(TF1 *f) { fSpectrum = f; }
+
+    ClassDef(MMcCollectionAreaCalc, 0) // Task to calculate the collection area histogram
+};
+
+#endif 
+
Index: branches/Mars_McMismatchStudy/mmontecarlo/MMcThresholdCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcThresholdCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcThresholdCalc.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmontecarlo/MMcThresholdCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcThresholdCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcThresholdCalc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmontecarlo/MMcTriggerRateCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcTriggerRateCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcTriggerRateCalc.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmontecarlo/MMcTriggerRateCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcTriggerRateCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcTriggerRateCalc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mmontecarlo/MMcUnfoldCoeffCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcUnfoldCoeffCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcUnfoldCoeffCalc.cc	(revision 17960)
@@ -0,0 +1,206 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico 2/2005 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMcUnfoldCoeffCalc
+//  Task to compute the coefficients for energy unfolding (to be used 
+//  typically in an iterative process).
+//
+//  Input containers:
+//   MMcEvt
+//   MMcEvtBasic
+//   MEnergyEst
+//   binsTheta  [MBinning]
+//   binsEnergy [MBinning]
+//
+//  Output containers:
+//   MHMcUnfoldCoeff
+//
+//  The binning for energy and theta are looked in the parameter list
+//  The tentative spectrum MUST be provided using SetSpectrum, otherwise
+//  it is used for default pow(energy,-1.6) [~Crab at 1 TeV]
+//
+//  This task is supposed to be in a two-looped macro/program: 
+//  In the first one MMcEvtBasic is read in order to compute the 
+//  weights to convert from original to tentative spectrum.
+//  In the second one MMcEvt and MEnergyEst are read and fill the 
+//  MC and estimated energy that are divided in the postprocess to
+//  compute the coefficients
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "TF1.h"
+
+#include "MMcUnfoldCoeffCalc.h"
+#include "MHMcUnfoldCoeff.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcEvtBasic.h"
+#include "MEnergyEst.h"
+
+ClassImp(MMcUnfoldCoeffCalc);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+//  Constructor
+//
+MMcUnfoldCoeffCalc::MMcUnfoldCoeffCalc(const char* name, const char* title) :
+  fSpectrum(NULL)
+{
+  fName  = name  ? name  : "MMcUnfoldCoeffCalc";
+  fTitle = title ? title : "Task to calculate the unfolding coefficients";
+} 
+
+// -------------------------------------------------------------------------
+//
+// PreProcess. 
+// Create MHMcUnfoldCoeff object if necessary. Search for other necessary 
+// containers: if MMcEvt is found, it means we are in the loop over the Events 
+// tree, and so we must fill the histogram MHMcUnfoldCoeff::fHistMcE and 
+// MHMcUnfoldCoeff::fHistEstE (using MHMcUnfoldCoeff::FillSel()). 
+// If MMcEvt is not found, it means that we are in the loop over the 
+// "OriginalMC" tree, containing all the original Corsika events 
+// produced, and hence we must fill the histogram  fHistAll through 
+// MHMcUnfoldCoeff::FillAll()
+//
+Int_t MMcUnfoldCoeffCalc::PreProcess (MParList *pList)
+{
+  fUnfoldCoeff = (MHMcUnfoldCoeff*)pList->FindCreateObj("MHMcUnfoldCoeff");
+  
+  if (!fBinsTheta)
+    {
+      fBinsTheta = (MBinning*) pList->FindObject("binsTheta");
+      if (!fBinsTheta)
+	{
+	  *fLog << err << "Coarse Theta binning not found... Aborting." 
+		<< endl;
+	  return kFALSE;
+	}
+    }
+
+  if (!fBinsEnergy)
+    {
+      fBinsEnergy = (MBinning*) pList->FindObject("binsEnergy");
+      if (!fBinsEnergy)
+	{
+	  *fLog << err << "Coarse Energy binning not found... Aborting." 
+		<< endl;
+	  return kFALSE;
+	}
+    }
+  
+  fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+  if (fMcEvt)
+    {      
+      *fLog << inf << "MMcEvt found... Filling MHMcUnfoldCoeff.fHistSel..." << endl;
+
+      fEnergyEst =  (MEnergyEst*)pList->FindObject("MEnergyEst");
+      if(!fEnergyEst)
+	{
+	  *fLog << err << "MEnergyEst not found... aborting..." << endl;
+	  return kFALSE;
+	}
+
+      return kTRUE;
+    }
+
+  *fLog << inf << "MMcEvt not found... looking for MMcEvtBasic..." << endl;
+
+  fMcEvtBasic = (MMcEvtBasic*) pList->FindObject("MMcEvtBasic");
+    
+  if (fMcEvtBasic)
+    {
+      fUnfoldCoeff->SetCoarseBinnings(*fBinsEnergy,*fBinsTheta);
+
+      *fLog << inf << "MMcEvtBasic found... Filling MHMcUnfoldCoeff.fHistAll..." << endl;
+      return kTRUE;
+    }
+
+  *fLog << err << "MMcEvtBasic not found. Aborting..." << endl;
+
+  return kFALSE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Depending on whether fMcEvt or fMcEvtBasic are available, fill 
+// MHMcUnfoldCoeff::fHistAll, else, if fMcEvt is available, fill 
+// MHMcUnfoldCoeff::fHistMcE and MHMcUnfoldCoeff::fHistEstE
+//
+Int_t MMcUnfoldCoeffCalc::Process()
+{
+  Double_t mcenergy  = fMcEvt ? fMcEvt->GetEnergy() : fMcEvtBasic->GetEnergy();
+  Double_t estenergy = fEnergyEst ? fEnergyEst->GetEnergy() : 0;
+  Double_t theta  = fMcEvt? fMcEvt->GetTelescopeTheta()*TMath::RadToDeg() : 0; // in deg
+  
+  if (fMcEvt)
+    fUnfoldCoeff->FillSel(mcenergy, estenergy, theta);
+  else
+    fUnfoldCoeff->FillAll(mcenergy);
+  
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Postprocess. 
+// If both fHistMcE and fHistEstE are already filled, calculate
+// the coefficients. 
+// Else it means we still have to run one more loop, and then the
+// weights are computed
+//
+Int_t MMcUnfoldCoeffCalc::PostProcess()
+{
+  if(((TH2D*)fUnfoldCoeff->GetHistMcE())->GetEntries() > 0  &&
+     ((TH2D*)fUnfoldCoeff->GetHistEstE())->GetEntries() > 0)
+    {
+      fUnfoldCoeff->ComputeCoefficients();
+      return kTRUE;
+    }
+ 
+  if(((TH1D*)fUnfoldCoeff->GetHistAll())->GetEntries() <= 0)
+    {
+      *fLog << err << "Postprocess reached with no histogram computed. Aborting" << endl;
+      return kFALSE;
+    }
+  
+
+  if(fSpectrum)
+    fUnfoldCoeff->ComputeWeights(fSpectrum);
+  else
+    {
+      // default spectrum in case no other one is provided
+      TF1 spectrum("func","pow(x,-1.6)",2.,20000.);
+      fUnfoldCoeff->ComputeWeights(&spectrum);
+    }
+  
+  return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mmontecarlo/MMcUnfoldCoeffCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MMcUnfoldCoeffCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MMcUnfoldCoeffCalc.h	(revision 17960)
@@ -0,0 +1,46 @@
+#ifndef MARS_MMcUnfoldCoeffCalc
+#define MARS_MMcUnfoldCoeffCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#include <TH2.h>
+
+class MParList;
+class MMcEvt;
+class MMcEvtBasic;
+class MEnergyEst;
+class MBinning;
+class MHMcUnfoldCoeff;
+
+class MMcUnfoldCoeffCalc : public MTask
+{
+ private:
+  const MMcEvt*       fMcEvt;
+  const MMcEvtBasic*  fMcEvtBasic;
+  const MEnergyEst*   fEnergyEst;
+
+  MBinning*           fBinsTheta;  // coarse zenith angle binning
+  MBinning*           fBinsEnergy; // coarse energy binning
+  
+  TF1*                fSpectrum;   // Tentative energy spectrum. 
+  
+  MHMcUnfoldCoeff*    fUnfoldCoeff; // container holding coefficients histogram
+  
+  TString fObjName;
+
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();
+  
+ public:
+  MMcUnfoldCoeffCalc(const char *name = NULL, const char *title = NULL);
+
+  void SetSpectrum(TF1 *f) { fSpectrum = f; }
+
+  ClassDef(MMcUnfoldCoeffCalc, 0) // Task to calculate the coefficients for unfolding
+};
+
+#endif 
+
Index: branches/Mars_McMismatchStudy/mmontecarlo/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/Makefile	(revision 17960)
@@ -0,0 +1,33 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = MonteCarlo
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mmc -I../mhbase -I../mhist -I../mhistmc \
+	   -I../mgeom -I../manalysis -I../mtools -I../mfileio          \
+           -I../mfilter -I../mdata -I../mfbase 
+
+SRCFILES = MMcWeightEnergySpecCalc.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mmontecarlo/MonteCarloIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MonteCarloIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MonteCarloIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mmontecarlo/MonteCarloLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mmontecarlo/MonteCarloLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmontecarlo/MonteCarloLinkDef.h	(revision 17960)
@@ -0,0 +1,9 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MMcWeightEnergySpecCalc+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mmovie/MMovieData.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MMovieData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MMovieData.cc	(revision 17960)
@@ -0,0 +1,101 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMovieData
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMovieData.h"
+
+#include <TSpline.h>
+
+ClassImp(MMovieData);
+
+using namespace std;
+
+class MSpline3 : public TSpline3
+{
+public:
+   MSpline3(const char *title,
+            const TGraph *g, const char *opt=0,
+            Double_t valbeg=0, Double_t valend=0)
+        : TSpline3(title, g, opt, valbeg, valend)
+   {
+   }
+
+   Double_t GetXmin() const { return fXmin; }     // Minimum value of abscissa
+   Double_t GetXmax() const { return fXmax; }     // Maximum value of abscissa
+};
+
+// --------------------------------------------------------------------------
+//
+// Creates a MSignalPix object for each pixel in the event
+//
+MMovieData::MMovieData(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMovieData";
+    fTitle = title ? title : "Storage container for movie data";
+
+    fSplines.SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset, deletes all stored splines
+//
+void MMovieData::Reset()
+{
+    fSplines.Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new TSpline3 from a TGraph
+//
+void MMovieData::Add(const TGraph &g)
+{
+    TSpline *sp = new MSpline3(g.GetName(), &g, "b2 e2");
+    fSplines.Add(sp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether tm would extra- or interpolate. kTRUE means tm will
+// be interpolated.
+//
+Bool_t MMovieData::CheckRange(Int_t idx, Double_t tm) const
+{
+    const MSpline3 &sp = (*this)[idx];
+    return tm>=sp.GetXmin() && tm<=sp.GetXmax();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the value of the idx-th spline at x=tm
+//
+Double_t MMovieData::Eval(Int_t idx, Double_t tm) const
+{
+    return (*this)[idx].Eval(tm);
+}
Index: branches/Mars_McMismatchStudy/mmovie/MMovieData.h
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MMovieData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MMovieData.h	(revision 17960)
@@ -0,0 +1,57 @@
+#ifndef MARS_MMovieData
+#define MARS_MMovieData
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class TGraph;
+class MSpline3;
+
+class MMovieData : public MParContainer, public MCamEvent
+{
+private:
+    TObjArray fSplines;
+
+    Float_t fMax;
+    Float_t fMedianPedestalRms;
+    UInt_t  fNumSlices;
+
+    //TSpline *operator[](int i) { return (TSpline*)fSplines[i]; }
+    MSpline3 &operator[](int i) const { return *(MSpline3*)fSplines[i]; }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const { return kFALSE; }
+    void   DrawPixelContent(Int_t num) const { }
+
+public:
+    MMovieData(const char *name=NULL, const char *title=NULL);
+    ~MMovieData() { }
+
+    void Reset();
+    void Add(const TGraph &g);
+
+    void SetMax(Float_t mx) { fMax = mx; }
+    Float_t GetMax() const { return fMax; }
+
+    void SetMedianPedestalRms(Float_t m) { fMedianPedestalRms = m; }
+    Float_t GetMedianPedestalRms() const { return fMedianPedestalRms; }
+
+    void SetNumSlices(UInt_t n) { fNumSlices=n; }
+    UInt_t GetNumSlices() const { return fNumSlices; }
+
+    Bool_t CheckRange(Int_t idx, Double_t tm) const;
+    Double_t Eval(Int_t idx, Double_t tm) const;
+    Double_t CheckedEval(Int_t idx, Double_t tm) const { return CheckRange(idx, tm) ? Eval(idx, tm) : 0; }
+
+    ClassDef(MMovieData, 1) // Storage container for movie data
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmovie/MMoviePrepare.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MMoviePrepare.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MMoviePrepare.cc	(revision 17960)
@@ -0,0 +1,308 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMoviePrepare
+//
+// Prepare the splines for displaying of a movie. The data is shifted by
+// the calculated time offset from MCalibrationRelTimeCam. It is
+// flat-fielded by multiplication with the calibration factor from
+// MCalibrateData divided by the median of the calibration factors of the
+// pixels with area index 0 (for MAGIC: inner pixels).
+//
+// The splines are initialized for the first slice given to the last
+// slice given (included).
+//
+// By default (MJCalibrateSignal.cc) the same slices than for the hi-gain
+// extraction range are used. To overwrite this behaviour use
+//
+//    MMoviewPrepare.FirstSlice: 10
+//    MMoviewPrepare.LastSlice:  50
+//
+// The maximum y-value set as knot is stored together with the splines
+// in MMovieData
+//
+// Input:
+//   MGeomCam
+//   MPedestalSubtractedEvt
+//   MPedestalFundamental [MPedestalCam]
+//   MCalibConstCam
+//   MCalibrationRelTimeCam
+//   MRawRunHeader
+//
+// Output:
+//   MMovieData
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMoviePrepare.h"
+
+#include <TGraph.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibConstCam.h"
+#include "MCalibConstPix.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimePix.h"
+
+#include "MExtractor.h"
+#include "MMovieData.h"
+#include "MRawRunHeader.h"
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MMoviePrepare);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Initialize fData with default rule "MMcEvt.fEnergy"
+//
+MMoviePrepare::MMoviePrepare(const char *name, const char *title)
+    : fFirstSlice(2), fLastSlice(12)
+{
+    fName  = name  ? name  : "MMoviePrepare";
+    fTitle = title ? title : "Task to calculate a MParameterD";
+}
+
+// --------------------------------------------------------------------------
+//
+// Set moview range from extractor
+//
+void MMoviePrepare::SetRangeFromExtractor(const MExtractor &ext)
+{
+    fFirstSlice = ext.GetHiGainFirst();
+    fLastSlice  = ext.GetHiGainLast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Input:
+//   MGeomCam
+//   MPedestalSubtractedEvt
+//   MPedestalFundamental [MPedestalCam]
+//   MCalibrateData
+//   MCalibrationRelTimeCam
+//   MRawRunHeader
+//
+// Output:
+//   MMovieData
+//
+Int_t MMoviePrepare::PreProcess(MParList *plist)
+{
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fEvt = (MPedestalSubtractedEvt*)plist->FindObject("MPedestalSubtractedEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MPedestalSubtractedEvt not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fPed = (MPedestalCam*)plist->FindObject("MPedestalFundamental", "MPedestalCam");
+    if (!fPed)
+    {
+        *fLog << err << "MPedestalFundamental [MPedestalCam] not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fCal = (MCalibConstCam*)plist->FindObject("MCalibConstCam");
+    if (!fCal)
+    {
+        *fLog << err << "MCalibConstCam not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fRel = (MCalibrationRelTimeCam*)plist->FindObject("MCalibrationRelTimeCam");
+    if (!fRel)
+    {
+        *fLog << err << "MCalibrationRelTimeCam not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fRun = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found ... aborting." << endl;
+        return kFALSE;
+    }
+
+    fOut = (MMovieData*)plist->FindCreateObj("MMovieData");
+    if (!fOut)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+/*
+Bool_t MMoviePrepare::ReInit(MParList *plist)
+{
+    MExtractedSignalCam *cam = (MExtractedSignalCam*)plist->FindObject("MExtractedSignalCam");
+    if (!cam)
+    {
+        *fLog << err << "MExtractedSignalCam not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fSlope = cam->GetNumUsedHiGainFADCSlices();
+
+    cout << "---> " << fSlope << " <---" << endl;
+
+    return kTRUE;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Return the median of the calibration constants of all pixels
+// with area index 0
+//
+Double_t MMoviePrepare::GetMedianCalibConst() const
+{
+    Int_t n = fCam->GetNumPixWithAidx(0);
+
+    MArrayF arr(n);
+
+    for (UInt_t i=0; i<fCam->GetNumPixels(); i++)
+        if ((*fCam)[i].GetAidx()==0)
+            arr[--n] = (*fCal)[i].GetCalibConst();
+
+    return TMath::Median(arr.GetSize(), arr.GetArray());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the median of the pedestal rms of all pixels with area index 0
+//
+Double_t MMoviePrepare::GetMedianPedestalRms() const
+{
+    Int_t n = fCam->GetNumPixWithAidx(0);
+
+    MArrayF rms(n);
+
+    for (UInt_t i=0; i<fCam->GetNumPixels(); i++)
+        if ((*fCam)[i].GetAidx()==0)
+            rms[--n] = (*fPed)[i].GetPedestalRms();
+
+    return TMath::Median(rms.GetSize(), rms.GetArray());
+}
+
+// --------------------------------------------------------------------------
+//
+// Get value from fData and set it to fEnergy. SetReadyToSave for fEnergy.
+// Return kCONTINUE if value is NaN (Not a Number)
+//
+Int_t MMoviePrepare::Process()
+{
+    if (fLastSlice>=fEvt->GetNumSamples())
+    {
+        fLastSlice = fEvt->GetNumSamples()-1;
+        *fLog << inf << "Cannot go beyond last slice... set last=" << fLastSlice << "." << endl;
+    }
+
+    // ---------------- Setup ------------------
+    const UInt_t  width = fLastSlice-fFirstSlice+1;     // [slices] width of window shown
+    const Float_t freq = fRun->GetFreqSampling()/1000.; // [GHz] Sampling frequency
+    const Float_t len  = width/freq;                    // [ns]  length of data stream in data-time
+
+    // ---------------- Prepare data ------------------
+
+    fOut->Reset();
+
+    // For invalid calib constants we can use the sector average
+    const UShort_t npix  = fEvt->GetNumPixels();
+    const Double_t slope = 1./GetMedianCalibConst();
+
+    TGraph g(width);
+
+    Float_t max = 0;
+    for (UShort_t p=0; p<npix; p++)
+    {
+        const MCalibrationRelTimePix &tpix = (MCalibrationRelTimePix&)(*fRel)[p];
+
+        const Float_t  offset = tpix.GetTimeOffset();
+        const Float_t  cal    = (*fCal)[p].GetCalibConst();
+        const Float_t *ptr    = fEvt->GetSamples(p)+fFirstSlice;
+        const Float_t  scale  = cal*slope*fCam->GetPixRatio(p);
+
+        for (UInt_t s=0; s<width; s++)
+        {
+            const Double_t x = (s-offset)/freq;
+            const Double_t y = ptr[s]*scale;
+
+            g.SetPoint(s, x, y);
+
+            // Check for maximum in the visible time range only
+            if (x>0 && x<len && y>max)
+                max=y;
+        }
+
+        g.SetName(MString::Format("%d", p));
+        fOut->Add(g);
+    }
+
+    fOut->SetMax(max);
+    fOut->SetNumSlices(width);
+    fOut->SetMedianPedestalRms(GetMedianPedestalRms());
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup
+//
+// Example:
+//   MMoviePrepare.FirstSlice: 10
+//   MMoviePrepare.LastSlice:  50
+//
+Int_t MMoviePrepare::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FirstSlice", print))
+    {
+        rc = kTRUE;
+        fFirstSlice = GetEnvValue(env, prefix, "FirstSlice", (Int_t)fFirstSlice);
+    }
+    if (IsEnvDefined(env, prefix, "LastSlice", print))
+    {
+        rc = kTRUE;
+        fLastSlice = GetEnvValue(env, prefix, "LastSlice", (Int_t)fLastSlice);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mmovie/MMoviePrepare.h
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MMoviePrepare.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MMoviePrepare.h	(revision 17960)
@@ -0,0 +1,51 @@
+#ifndef MARS_MMoviePrepare
+#define MARS_MMoviePrepare
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MExtractor;
+class MMovieData;
+class MPedestalCam;
+class MRawRunHeader;
+class MCalibConstCam;
+class MCalibrationRelTimeCam;
+class MPedestalSubtractedEvt;
+
+class MMoviePrepare : public MTask
+{
+private:
+    MPedestalSubtractedEvt *fEvt;    //! Slices with pedestal subtracted
+    MCalibConstCam         *fCal;    //! Calibration constants signal
+    MCalibrationRelTimeCam *fRel;    //! Calibration constants time
+    MRawRunHeader          *fRun;    //! Run Header (sampling frequency)
+    MGeomCam               *fCam;    //! Pixel size
+    MPedestalCam           *fPed;    //! Fundamental pedestal (slice by slice)
+
+    MMovieData             *fOut;    //! Prepared output container
+
+    UInt_t fFirstSlice;
+    UInt_t fLastSlice;
+
+    // MTask
+    Int_t  PreProcess(MParList *plist);
+    Int_t  Process();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MMoviePrepare
+    Double_t GetMedianCalibConst() const;
+    Double_t GetMedianPedestalRms() const;
+
+public:
+    MMoviePrepare(const char *name=NULL, const char *title=NULL);
+
+    void SetRangeFromExtractor(const MExtractor &ext);
+
+    ClassDef(MMoviePrepare, 0) // Task to prepare a movie
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmovie/MMovieWrite.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MMovieWrite.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MMovieWrite.cc	(revision 17960)
@@ -0,0 +1,887 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMovieWrite
+//
+// The intention of this class is to encode movies prepard by the
+// MMoviePrepare task.
+//
+// For writing the movies the images are converted to ppm and piped through
+// ppm2y4m to mpeg2enc. The output format is a mpeg2 movie and should
+// be within the specifications of mpeg2 for DVD. Its size is 720x480,
+// which is a good compromise between resolution and file size. The frame
+// rate is fixed to 24fps.
+//
+// By changing the setup you can control the output:
+//
+//    NumEvents: To make sure the file size doesn't get too large
+//     (300 evts are roughly 80MB with the default seetings) you can set
+//     a maximum number of events. If this number of events has been encoded
+//     the eventloop is stopped.
+//
+//    TargetLength: The length (in seconds) each even will be encoded to.
+//     For example with the default Target Length of 5s and the fixed frame
+//     rate of 24fps each event will be encoded into 24f/s*5s +1f = 121frames
+//     equally distributed between the beginning of the first and the end of
+//     the last frame.
+//
+//    Threshold: The default threshold is 2. At 2 times median pedestal rms
+//     of the pixles with area index 0 (for MAGIC: inner pixels) the color
+//     palette will change from yellow to red and isolated pixels between
+//     the median rms and 2 times the median of the rms will be removed from
+//     the image. To switch off this behaviour you can set a threshold
+//     below one.
+//
+//    Filename: The output filename of the movie. If it doesn't end with ".mpg"
+//     the suffix is added.
+//
+//  The interpolation of the frames is done using a TSpline3. If the spline
+//  would extrapolate due to the shift by the relative time calibration the
+//  contents is set to zero. Unsuitable pixels are interpolated frame by
+//  frame using the surrounding suitable pixels.
+//
+//  A few words about file size: MPEG is a motion compensation compression,
+//  which means that if a region of a past frame is shown again at the same
+//  place or somewhere else this region is referenced instead of encoded again.
+//  This means that in our case (almost all frames are identical!) the
+//  increase of file size is far from linear with the number of encoded events!
+//
+//
+//  Input:
+//   MGeomCam
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MSignalCam
+//   MBadPixelsCam
+//   MMovieData
+//   [MMcEvt]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMovieWrite.h"
+
+#include <errno.h>
+
+#include <TF1.h>
+#include <TStyle.h>
+#include <TColor.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+#include <TASImage.h>
+#include <TStopwatch.h>
+
+#include "MString.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MMcEvt.hxx"
+
+#include "MH.h"
+#include "MHCamera.h"
+#include "MMovieData.h"
+#include "MSignalCam.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+#include "MCalibrateData.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MMovieWrite);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMovieWrite::MMovieWrite(const char *name, const char *title)
+    : fPipe(0), fTargetLength(5), fThreshold(2), fNumEvents(25000), fFilename("movie.mpg")
+{
+    fName  = name  ? name  : "MMovieWrite";
+    fTitle = title ? title : "Task to encode a movie";
+}
+
+// --------------------------------------------------------------------------
+//
+// Close pipe if still open
+//
+MMovieWrite::~MMovieWrite()
+{
+    if (fPipe)
+        gSystem->ClosePipe(fPipe);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check the pipe for errors. In case of error print an error message.
+// return kFALSE in case of error, kTRUE in case of success.
+//
+Bool_t MMovieWrite::CheckPipe()
+{
+    if (!ferror(fPipe))
+        return kTRUE;
+
+    *fLog << err << "Error in pipe: " << strerror(errno) << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open pipe for encoding the movie
+//
+Bool_t MMovieWrite::OpenPipe()
+{
+    //    name = "ppmtoy4m -B -S 420mpeg2 -v 0 | yuvplay";
+    //    name = Form("ppmtoy4m -B -S 420jpeg -v 0 -F %d:%d | yuv2lav -v 0 -o output%03d.avi", TMath::Nint()  TMath::Nint(fTargetLength*1000))
+    //    name = "ppmtoy4m -B -F 3:1 -S 420jpeg -v 0 | yuv2lav -v 0 -o output.avi";
+
+    TString name;
+    name  = "ppmtoy4m -B -F 24:1 -S 420jpeg -v 0 | ";
+    name += "mpeg2enc -v 0 -F 2 -I 0 -M 2 -o ";
+    name += fFilename;
+    if (!fFilename.EndsWith(".mpg"))
+        name += ".mpg";
+
+    const Int_t n = TMath::Nint(fTargetLength*24)+1;
+
+    name += " -f 9 -E 40 -r 0 -K kvcd ";
+    name += MString::Format("-g %d -G %d", n, n);
+
+    // For higher resolution add "--no-constraints"
+
+    fPipe = gSystem->OpenPipe(name, "w");
+    if (!fPipe)
+    {
+        *fLog << err;
+        *fLog << "Pipe: " << name << endl;
+        *fLog << "Couldn't open pipe... aborting." << endl;
+        CheckPipe();
+        return kFALSE;
+    }
+
+    *fLog << inf << "Setup pipe to ppmtoy4m and mpeg2enc to encode " << fFilename << "." << endl;
+
+    return kTRUE;
+
+    //  1: 37M name += "-f 9 -E 40 -H -4 1 -2 1 --dualprime-mpeg2";
+    //  2: 42M name += "-f 9";
+    //  3: 37M name += "-f 9 -E 40 -4 1 -2 1 --dualprime-mpeg2";
+    //  4: 37M name += "-f 9 -E 40 -4 1 -2 1";
+    //  5: 37M name += "-f 9 -E 40 -4 4 -2 4";           // 640x400   3 frames/slice
+    //  6: 11M name += "-f 3 -E 40 -b 750";              // 640x400   3 frames/slice
+
+    //  7: 28M name += "-f 9 -E 40 -G 50";               // 640x400   3 frames/slice
+    //  8: 24M name += "-f 9 -E 40 -G 500";              // 640x400   3 frames/slice
+
+    //  9: 17M name += "-f 9 -E 40 -G 2400";             // 640x400  24 frames/slice
+    // 10: 19M name += "-f 9 -E 40 -G 1120";             // 720x480   3 frames/slice
+    // 20: 33M name += "-f 9 -E 40 -g 28 -G 28";         // 720x480   3 frames/slice
+    //     57M name += "-f 9 -E 40 -g 28 -G 28 -q 4";    // 720x480   3 frames/slice
+
+    //     30M name += "-f 9 -E  40 -g 84 -G 84 -r  0";          // 720x480   3 frames/slice
+    //     31M name += "-f 9 -E  40 -g 56 -G 56 -r  0";          // 720x480   3 frames/slice
+    //     34M name += "-f 9 -E  40 -g 28 -G 28 -r  0";          // 720x480   3 frames/slice
+    // 24: 24M name += "-f 9 -E  40 -g 28 -G 28 -r  0 -K kvcd";  // 720x480   3 frames/slice
+    // 25: 24M name += "-f 9 -E -40 -g 28 -G 28 -r  0 -K kvcd";  // 720x480   3 frames/slice
+    // 26: 26M name += "-f 9 -E   0 -g 28 -G 28 -r  0 -K kvcd";  // 720x480   3 frames/slice
+    //     34M name += "-f 9 -E  40 -g 28 -G 28 -r  2";          // 720x480   3 frames/slice
+    //     33M name += "-f 9 -E  40 -g 28 -G 28 -r 32";          // 720x480   3 frames/slice
+
+    // name += "-f 9 -E 40 -g 121 -G 121 -r 0 -K kvcd";  // 720x480 5s  24 frames/slice
+
+    // 11: 56M name += "-f 9 -E 40 -g 217 -G 217";       // 720x480  24 frames/slice
+    // 18: 59M name += "-f 9 -E 40 -G 250";              // 720x480  24 frames/slice
+    //     62M name += "-f 9 -E 40 -G 184";              // 720x480  24 frames/slice
+
+    // 12: --- name += "-f 9 -E 40 -G 500 -q 31";        // 720x480  3frames/slice
+    // 13: 49M name += "-f 9 -E 40 -G 500 -q 4";         // 720x480  3frames/slice
+    // 14: 21M name += "-f 9 -E 40 -G 500 -q 4 -b 1500"; // 720x480  3frames/slice
+
+    // 15: 57M name += "-f 9 -E 40 -G 500 --no-constraints"; // 1280 864  3frames/slice
+
+    // 16: >80 name += "-f 9 -E 40 -G 217 --no-constraints -b 3000"; // 1280 864  24frames/slice
+    // 17: >50 name += "-f 9 -E 40 -G 682 -b 3000 --no-constraints"; // 1280 864  24frames/slice
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for:
+//   - MGeomCam
+//   - MRawRunHeader
+//   - MRawEvtHeader
+//   - MSignalCam
+//   - MBadPixelsCam
+//   - MMovieData
+//
+// Open a pipe to write the images to. Can be either a player or
+// an encoder.
+//
+Int_t MMovieWrite::PreProcess(MParList *plist)
+{
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fRun = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fHead = (MRawEvtHeader*)plist->FindObject("MRawEvtHeader");
+    if (!fHead)
+    {
+        *fLog << err << "MRawEvtHeader not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fSig = (MSignalCam*)plist->FindObject("MSignalCam");
+    if (!fSig)
+    {
+        *fLog << err << "MSignalCam not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fBad = (MBadPixelsCam*)plist->FindObject("MBadPixelsCam");
+    if (!fBad)
+    {
+        *fLog << err << "MBadPixelsCam not found ... aborting." << endl;
+        return kFALSE;
+    }
+    fIn = (MMovieData*)plist->FindObject("MMovieData");
+    if (!fIn)
+    {
+        *fLog << err << "MMovieData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMC = (MMcEvt*)plist->FindObject("MMcEvt");
+
+    return OpenPipe();
+}
+
+#ifdef USE_TIMING
+TStopwatch clockT, clock1, clock2, clock3;
+#endif
+
+// --------------------------------------------------------------------------
+//
+// Close pipe if still open
+//
+Int_t MMovieWrite::PostProcess()
+{
+    if (fPipe)
+    {
+        gSystem->ClosePipe(fPipe);
+        fPipe=0;
+    }
+
+#ifdef USE_TIMING
+    *fLog << all << endl;
+    *fLog << "Snap: " << flush;
+    clock1.Print();
+    *fLog << "Writ: " << flush;
+    clock2.Print();
+    *fLog << "Prep: " << flush;
+    clock3.Print();
+    *fLog << "Totl: " << flush;
+    clockT.Print();
+    *fLog << endl;
+#endif
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Produce a 99 color palette made such, that everything below one
+// pedestal rms is white, everything up to two pedestal rms is yellow
+// and everything above gets colors.
+//
+Int_t MMovieWrite::SetPalette(Double_t rms, const TH1 &h) const
+{
+    const Double_t min = h.GetMinimum();
+    const Double_t max = h.GetMaximum();
+
+    const Double_t f = (fThreshold*rms-min)/(max-min);
+    const Double_t w = 1-f;
+
+    // --- Produce the nice colored palette ---
+
+    //             min      th*rms                 max
+    double s[6] = {0.0, f/2,  f,   f+w/4, f+3*w/5, 1.0 };
+
+    double r[6] = {1.0, 1.0,  1.0, 0.85,  0.1,     0.0 };
+    double g[6] = {1.0, 1.0,  1.0, 0.15,  0.1,     0.0 };
+    double b[6] = {0.9, 0.55, 0.4, 0.15,  0.7,     0.1 };
+
+    TArrayI col(99);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,18,00)
+    const Int_t rc = gStyle->CreateGradientColorTable(6, s, r, g, b, col.GetSize());
+#else
+    const Int_t rc = TColor::CreateGradientColorTable(6, s, r, g, b, col.GetSize());
+#endif
+
+    // --- Overwrite the 'underflow' bin with white ---
+
+    for (int i=0; i<col.GetSize(); i++)
+        col[i] = gStyle->GetColorPalette(i);
+
+    col[0] = TColor::GetColor(0xff, 0xff, 0xff);
+
+    // --- Set Plette ---
+
+    gStyle->SetPalette(col.GetSize(), col.GetArray());
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// The created colors are not overwritten and must be deleted manually
+// because having more than 32768 color in a palette will crash
+// gPad->PaintBox
+//
+void MMovieWrite::DeletePalette(Int_t colidx) const
+{
+    for (int i=0; i<99; i++)
+    {
+        TColor *col = gROOT->GetColor(colidx+i);
+        if (col)
+            delete col;
+    }
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Do a snapshot from the pad via TASImage::FromPad and write the
+// image to the pipe.
+// return kFALSE in case of error, kTRUE in case of success.
+//
+Bool_t MMovieWrite::WriteImage(TVirtualPad &pad)
+{
+    clock1.Start(kFALSE);
+    TASImage img;
+    img.FromPad(&pad);
+    clock1.Stop();
+
+    clock2.Start(kFALSE);
+    const Bool_t rc = WriteImage(img);
+    clock2.Stop();
+
+    return rc;
+}
+
+#include <TVirtualPS.h>
+Bool_t MMovieWrite::WriteImage(TVirtualPad &pad)
+{
+    TVirtualPS *psave = gVirtualPS;
+
+    clock1.Start(kFALSE);
+    TImage dump("", 114);
+    dump.SetBit(BIT(11));
+    pad.Paint();
+    TASImage *itmp = (TASImage*)dump.GetStream();
+    clock1.Stop();
+
+    clock2.Start(kFALSE);
+    const Bool_t rc = WriteImage(*itmp);
+    clock2.Stop();
+
+    gVirtualPS = psave;
+
+    return rc;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Update the part of the idst image with the contents of the pad.
+//
+// It is a lot faster not to rerender the parts of the image which don't
+// change anyhow, because rerendering the camera is by far the slowest.
+//
+void MMovieWrite::UpdateImage(TASImage &idst, TVirtualPad &pad)
+{
+    // Get image from pad
+    TASImage isrc;
+    isrc.FromPad(&pad);
+
+    // Get position and width of destination- and source-image
+    const UInt_t wsrc = isrc.GetWidth();    // width  of image
+    const UInt_t hsrc = isrc.GetHeight();   // height of image
+
+    const UInt_t usrc = pad.UtoPixel(1)*4;  // width  of pad (argb)
+    //const UInt_t vsrc = pad.VtoPixel(0);    // height of pad
+
+    const UInt_t xsrc = pad.UtoAbsPixel(0); // offset of pad in canvas
+    const UInt_t ysrc = pad.VtoAbsPixel(1); // offset of pad in canvas
+
+    const UInt_t wdst = idst.GetWidth();
+    //const UInt_t hdst = idst.GetHeight();
+
+    // Update destination image with source image
+    const UInt_t size = wsrc*hsrc;
+
+    UInt_t *psrc = isrc.GetArgbArray();
+    UInt_t *pdst = idst.GetArgbArray();
+
+    UInt_t *src = psrc + ysrc*wsrc+xsrc;
+    UInt_t *dst = pdst + ysrc*wdst+xsrc;
+
+    while (src<psrc+size)
+    {
+        memcpy(dst, src, usrc);
+
+        src += wsrc;
+        dst += wdst;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the image as ppm (raw/P6) to the pipe.
+// return kFALSE in case of error, kTRUE in case of success.
+//
+Bool_t MMovieWrite::WriteImage(TASImage &img)
+{
+    // Write image header
+    fprintf(fPipe, "P6 %d %d 255\n", img.GetWidth(), img.GetHeight());
+    if (!CheckPipe())
+        return kFALSE;
+
+    // Write image data (remove alpha channel from argb data)
+    UInt_t *argb = img.GetArgbArray();
+    for (UInt_t *ptr=argb; ptr<argb+img.GetWidth()*img.GetHeight(); ptr++)
+        if (fwrite(ptr, 3, 1, fPipe)!=1)
+            break;
+
+    return CheckPipe();
+}
+
+// --------------------------------------------------------------------------
+//
+// Update TASImage with changing parts of the image and write image to pipe.
+// return kFALSE in case of error, kTRUE in case of success.
+//
+Bool_t MMovieWrite::WriteImage(TASImage &img, TVirtualPad &pad)
+{
+#ifdef USE_TIMING
+    clock1.Start(kFALSE);
+    UpdateImage(img, pad);
+    clock1.Stop();
+
+    clock2.Start(kFALSE);
+    const Bool_t rc = WriteImage(img);
+    clock2.Stop();
+
+    return rc;
+#else
+    UpdateImage(img, pad);
+    return WriteImage(img);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Do a simple interpolation of the surrounding suitable pixels for all
+// unsuitable pixels.
+//
+void MMovieWrite::TreatBadPixels(TH1 &h) const
+{
+    const UShort_t entries = fCam->GetNumPixels();
+
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (!(*fBad)[i].IsUnsuitable())
+            continue;
+
+        const MGeom &gpix = (*fCam)[i];
+
+        Int_t    num = 0;
+        Double_t sum = 0;
+
+        //
+        // Loop over all its neighbors
+        //
+        Int_t n = gpix.GetNumNeighbors();
+        while (n--)
+        {
+            const UShort_t nidx = gpix.GetNeighbor(n);
+
+            //
+            // Do not use blind neighbors
+            //
+            if ((*fBad)[nidx].IsUnsuitable())
+                continue;
+
+            sum += h.GetBinContent(nidx+1);
+            num++;
+        }
+
+        h.SetBinContent(i+1, sum/num);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Do a simple interpolation of the surrounding suitable pixels for all
+// unsuitable pixels.
+//
+void MMovieWrite::Clean(TH1 &h, Double_t rms) const
+{
+    if (fThreshold<1)
+        return;
+
+    const UShort_t entries = fCam->GetNumPixels();
+
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        Double_t val = h.GetBinContent(i+1);
+        if (val<rms || val>fThreshold*rms)
+            continue;
+
+        const MGeom &gpix = (*fCam)[i];
+
+        //
+        // Loop over all its neighbors
+        //
+        Int_t n = gpix.GetNumNeighbors();
+        while (n)
+        {
+            const UShort_t nidx = gpix.GetNeighbor(n-1);
+            if (h.GetBinContent(nidx+1)>=rms)
+                break;
+            n--;
+        }
+
+        if (n==0)
+            h.SetBinContent(i+1, 0);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MMovieWrite::Process(TH1 &h, TVirtualPad &c)
+{
+    // ---------------- Setup ------------------
+
+    const Float_t freq   = fRun->GetFreqSampling()/1000.; // [GHz] Sampling frequency
+    const UInt_t  slices = fIn->GetNumSlices();
+    const Float_t len    = slices/freq;                   // [ns]  length of data stream in data-time
+    //const Float_t len    = (slices-2)/freq;               // [ns]  length of data stream in data-time
+
+    const Double_t rms = fIn->GetMedianPedestalRms();
+    const Double_t max = fIn->GetMax();    // scale the lover limit such
+    const Double_t dif = (max-rms)*99/98;  // that everything below rms is
+    const Double_t min = max-dif;          // displayed as white
+
+    // If the maximum is equal or less the
+    // pedestal rms something must be wrong
+    if (dif<=0)
+        return kFALSE;
+
+    h.SetMinimum(min);
+    h.SetMaximum(max);
+
+    // -----------------------------------------
+
+    // Produce starting image from canvas
+    TASImage img;
+    img.FromPad(&c);
+
+    // Set new adapted palette for further rendering
+    const Int_t colidx = SetPalette(rms, h);
+
+    // Get the pad containing the camera with the movie
+    TVirtualPad &pad = *c.GetPad(1)->GetPad(1);
+
+    // Calculate number of frames
+    const Int_t numframes = TMath::Nint(fTargetLength*24);
+
+    // Get number of pixels in camera
+    const Int_t npix = fCam->GetNumPixels();
+
+    // Loop over all frames+1 (upper edge)
+    for (Int_t i=0; i<=numframes; i++)
+    {
+        // Calculate corresponding time
+        const Float_t t = len*i/numframes;// + 0.5/freq;  // Process from slice beg+0.5 to end-1.5
+
+        // Calculate histogram contents by spline interpolation
+        for (UShort_t p=0; p<npix; p++)
+        {
+            const Double_t y = (*fBad)[p].IsUnsuitable() ? 0 : fIn->CheckedEval(p, t);
+            h.SetBinContent(p+1, y);
+        }
+
+        // Interpolate unsuitable pixels
+        TreatBadPixels(h);
+
+        // Clean single pixels
+        Clean(h, rms);
+
+        // Set new name to be displayed
+        h.SetName(MString::Format("%d: %.2f/%.1fns", i+1, t*freq, t));
+
+        // Update existing image with new data and encode into pipe
+        if (!WriteImage(img, pad))
+            return kFALSE;
+    }
+
+    DeletePalette(colidx);
+
+    cout << setw(3) << GetNumExecutions() << ": " << MString::Format("%6.2f", (float)numframes/(slices-2)) << " f/sl " << slices << " " << numframes+1 << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MMovieWrite::Process()
+{
+#ifdef USE_TIMING
+    clockT.Start(kFALSE);
+
+    clock3.Start(kFALSE);
+#endif
+    // ---------------- Prepare display ------------------
+
+    Bool_t batch = gROOT->IsBatch();
+    gROOT->SetBatch();
+
+    TCanvas c;
+    //c.Iconify();
+    c.SetBorderMode(0);
+    c.SetFrameBorderMode(0);
+    c.SetFillColor(kWhite);
+    //c.SetCanvasSize(640, 400);
+    c.SetCanvasSize(720, 480);
+    //c.SetCanvasSize(960, 640);
+    //c.SetCanvasSize(1024, 688);
+    //c.SetCanvasSize(1152, 768);
+    //c.SetCanvasSize(1280, 864);
+
+    MH::SetPalette("pretty");
+
+    c.cd();
+    TPad p1("Pad2", "", 0.7, 0.66, 0.99, 0.99);
+    p1.SetNumber(2);
+    p1.SetBorderMode(0);
+    p1.SetFrameBorderMode(0);
+    p1.SetFillColor(kWhite);
+    p1.Draw();
+    p1.cd();
+
+    MHCamera hsig(*fCam, "Signal", "Calibrated Signal");
+    hsig.SetYTitle("S [phe]");
+    hsig.SetCamContent(*fSig, 99);
+    hsig.SetMinimum(0);
+    //hsig.SetContour(99);
+    hsig.Draw("nopal");
+
+    c.cd();
+    TPad p2("Pad3", "", 0.7, 0.33, 0.99, 0.65);
+    p2.SetNumber(3);
+    p2.SetBorderMode(0);
+    p2.SetFrameBorderMode(0);
+    p2.SetFillColor(kWhite);
+    p2.Draw();
+    p2.cd();
+
+    MHCamera htime(*fCam, "ArrivalTime", "Calibrated Arrival Time");
+    htime.SetYTitle("T [au]");
+    htime.SetCamContent(*fSig, 8);
+    htime.Draw("nopal");
+
+    c.cd();
+    TPad p3("Pad4", "", 0.7, 0.00, 0.99, 0.32);
+    p3.SetNumber(4);
+    p3.SetBorderMode(0);
+    p3.SetFrameBorderMode(0);
+    p3.SetFillColor(kWhite);
+    p3.Draw();
+    p3.cd();
+/*
+    TH1F htpro("TimeProj", "", slices, 0, len);
+    for (UInt_t i=0; i<htime.GetNumPixels(); i++)
+        if(htime.IsUsed(i))
+            htpro.Fill((htime.GetBinContent(i+1)-first)/freq, hsig.GetBinContent(i+1));
+    htpro.SetMinimum(0);
+    htpro.SetMaximum(100);
+    htpro.SetLineColor(kBlue);
+    htpro.Draw();
+
+    TF1 fgaus("f1", "gaus");
+    const Double_t m = (htpro.GetMaximumBin()-0.5)*len/slices;
+    fgaus.SetParameter(0, htpro.GetMaximum());
+    fgaus.SetParameter(1, m);
+    fgaus.SetParameter(2, 1.0);
+    fgaus.SetParLimits(1, m-3, m+3);
+    fgaus.SetParLimits(2, 0, 3);
+    fgaus.SetLineWidth(1);
+    fgaus.SetLineColor(kMagenta);
+    htpro.Fit(&fgaus, "NI", "", m-3, m+3);
+    fgaus.Draw("same");
+
+    g.SetMarkerStyle(kFullDotMedium);
+    g.Draw("PL");
+    //g.SetMinimum(0);
+    //g.SetMaximum(100);
+    //g.Draw("APL");
+
+    p3.Update();
+    p3.cd(1);
+    gPad->Update();
+  */
+    c.cd();
+    TPad p0("MainPad", "", 0.01, 0.01, 0.69, 0.99);
+    p0.SetNumber(1);
+    p0.SetBorderMode(0);
+    p0.SetFrameBorderMode(0);
+    p0.SetFillColor(kWhite);
+    p0.Draw();
+    p0.cd();
+ /*
+    cout << "Max=" << hsig.GetMaximum() << "/" << fIn->GetMax() << "   ";
+    cout << hsig.GetMaximum()/fIn->GetMax() << endl;
+    Float_t rms0 = fPed->GetAveragedRmsPerArea(*fCam, 0, fBad)[0];
+    Float_t rms1 = fPed->GetAveragedRmsPerArea(*fCam, 1, fBad)[0];
+    cout << "RMS="<<rms0<<"/"<<rms1<<endl;
+
+    rms0 = GetMedianPedestalRms();
+
+    cout << "MED=" << rms0 << endl;
+    */
+
+    TString s = MString::Format("%d:  Evt #", GetNumExecutions()+1);
+    s += fHead->GetDAQEvtNumber();
+    s += " of ";
+    s += "Run #";
+    s += fRun->GetRunNumber();
+    if (fMC)
+        s = fMC->GetDescription(s);
+
+    MHCamera h(*fCam);
+    h.SetTitle(s);
+    h.SetAllUsed();
+    h.SetYTitle("V [au]");
+    h.SetContour(99);
+
+    h.Draw("nopal");
+
+    // ---------------- Show data ------------------
+    gStyle->SetOptStat(1000000001);
+/*
+    p0.Modified();
+    p1.Modified();
+    p2.Modified();
+
+    p0.GetPad(1)->Modified();
+    p1.GetPad(1)->Modified();
+    p2.GetPad(1)->Modified();
+
+    c.Update();
+ */
+
+    // ---------------- Show data ------------------
+#ifdef USE_TIMING
+    clock3.Stop();
+#endif
+
+    // Switch off automatical adding to directory (SetName would do)
+    const Bool_t add = TH1::AddDirectoryStatus();
+    TH1::AddDirectory(kFALSE);
+
+    const Bool_t rc = Process(h, c);
+
+    // restore previous state
+    TH1::AddDirectory(add);
+
+#ifdef USE_TIMING
+    clockT.Stop();
+#endif
+
+    gROOT->SetBatch(batch);
+
+    if (!rc)
+        return kERROR;
+
+    return fNumEvents<=0 || GetNumExecutions()<fNumEvents;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup
+//
+// Example:
+//   MMovieWrite.TargetLength: 5 <seconds>
+//   MMovieWrite.NumEvents: 500
+//   MMovieWrite.Threshold: 2 <rms>
+//   MMovieWrite.FileName: movie.mpg
+//
+Int_t MMovieWrite::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumEvents", print))
+    {
+        fNumEvents = GetEnvValue(env, prefix, "NumEvents", (Int_t)fNumEvents);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "TargetLength", print))
+    {
+        fTargetLength = GetEnvValue(env, prefix, "TargetLength", fTargetLength);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Threshold", print))
+    {
+        fThreshold = GetEnvValue(env, prefix, "Threshold", fThreshold);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "FileName", print))
+    {
+        fFilename = GetEnvValue(env, prefix, "FileName", fFilename);
+        rc = kTRUE;
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mmovie/MMovieWrite.h
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MMovieWrite.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MMovieWrite.h	(revision 17960)
@@ -0,0 +1,81 @@
+#ifndef MARS_MMovieWrite
+#define MARS_MMovieWrite
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH1;
+class TASImage;
+
+class MMcEvt;
+class MGeomCam;
+class MMovieData;
+class MSignalCam;
+class MPedestalCam;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MBadPixelsCam;
+
+class MMovieWrite : public MTask
+{
+private:
+    MRawRunHeader *fRun;   //! Header with run number and sampling frequency
+    MRawEvtHeader *fHead;  //! Header with event number
+    MGeomCam      *fCam;   //! Camera geometry necessary for the histograms
+    MSignalCam    *fSig;   //! Input signal to display cleaned and uncleaned event
+    MBadPixelsCam *fBad;   //! Information about bad pixels
+    MPedestalCam  *fPed;   //! Fundamental pedestal for palette and cleaning
+    MMcEvt        *fMC;    //! Informatio about MC events
+
+    MMovieData    *fIn;    //! Input data with splines for all pixels
+
+    FILE          *fPipe;  //! Ouput pipe to player or encoder
+
+    Float_t fTargetLength; // [s] Target length for stream of one event (+1 frame)
+    Float_t fThreshold;    // Threshold for cleaning
+    UInt_t  fNumEvents;    // Maximum number of events to encode
+
+    TString fFilename;     // name of output file
+
+    // MTask
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MMovieWrite
+    Bool_t OpenPipe();
+    Bool_t CheckPipe();
+
+    Double_t GetMedianPedestalRms() const;
+
+    void Clean(TH1 &h, Double_t rms) const;
+    void TreatBadPixels(TH1 &h) const;
+
+    Int_t SetPalette(Double_t rms, const TH1 &h) const;
+    void DeletePalette(Int_t colidx) const;
+
+    void UpdateImage(TASImage &img, TVirtualPad &pad);
+
+    Bool_t WriteImage(TASImage &img);
+    Bool_t WriteImage(TASImage &img, TVirtualPad &pad);
+    //Bool_t WriteImage(TVirtualPad &pad);
+
+    Bool_t Process(TH1 &h, TVirtualPad &c);
+
+public:
+    MMovieWrite(const char *name=NULL, const char *title=NULL);
+    ~MMovieWrite();
+
+    void SetFilename(const char *f) { fFilename = f; }
+    void SetNumEvents(Int_t n) { fNumEvents = n; }
+    void SetThreshold(Float_t f) { fThreshold = f; }
+    void SetTargetLength(Float_t l) { fTargetLength = l; }
+
+    ClassDef(MMovieWrite, 0) // Task to encode a movie
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmovie/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/Makefile	(revision 17960)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Movie
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw -I../mgeom -I../mhbase -I../mgui \
+           -I../mcalib -I../msignal -I../mbadpixels -I../mpedestal   \
+           -I../mhist -I../mmc
+
+SRCFILES = MMoviePrepare.cc \
+           MMovieData.cc \
+           MMovieWrite.cc
+
+############################################################
+
+all:  $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
Index: branches/Mars_McMismatchStudy/mmovie/MovieIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MovieIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MovieIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mmovie/MovieLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mmovie/MovieLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmovie/MovieLinkDef.h	(revision 17960)
@@ -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 MMovieWrite+;
+#pragma link C++ class MMoviePrepare+;
+#pragma link C++ class MMovieData+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mmuon/MHMuonPar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MHMuonPar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MHMuonPar.cc	(revision 17960)
@@ -0,0 +1,304 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Meyer, 02/2005 <mailto:meyer@astro.uni-wuerzburg.de>
+!   Author(s): Thomas Bretz, 04/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHMuonPar
+//
+// This class is a histogram class for displaying muonparameters.
+// The folowing histgrams will be plotted:
+// - Radius (TH1F)
+// - ArcWidth (TH1F)
+// - ArcWidth/Radius vs Radius (TProfile) (it is the energy dependent
+//   relative broadening of the muon ring)
+// - Size Vs Radius
+//
+//
+// Inputcontainer:
+//   - MGeomCam
+//   - MMuonSearchPar
+//   - MMuonCalibPar
+//
+//
+// Class Version 2:
+// ----------------
+//  - fMm2Deg
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMuonPar.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TPad.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TProfile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MString.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MMuonSearchPar.h"
+#include "MMuonCalibPar.h"
+
+ClassImp(MHMuonPar);
+
+using namespace std;
+
+const Float_t MHMuonPar::fgIntegralLoLim = 0.751;
+const Float_t MHMuonPar::fgIntegralUpLim = 1.199;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHMuonPar::MHMuonPar(const char *name, const char *title) :
+    fMuonSearchPar(NULL), fMuonCalibPar(NULL), fGeom(NULL)
+{
+    fName  = name  ? name  : "MHMuonPar";
+    fTitle = title ? title : "Histograms of muon parameters";
+
+    fHistRadius.SetName("Radius");
+    fHistRadius.SetTitle("Distribution of Radius'");
+    fHistRadius.SetXTitle("R [\\circ]");
+    fHistRadius.SetYTitle("Counts");
+    fHistRadius.GetXaxis()->SetTitleOffset(1.2);
+    fHistRadius.SetDirectory(NULL);
+    fHistRadius.UseCurrentStyle();
+    fHistRadius.SetFillStyle(4000);
+
+    fHistArcWidth.SetName("ArcWidth");
+    fHistArcWidth.SetTitle("Distribution of ArcWidth");
+    fHistArcWidth.SetXTitle("W [\\circ]");
+    fHistArcWidth.GetXaxis()->SetTitleOffset(1.2);
+    fHistArcWidth.SetYTitle("Counts");
+    fHistArcWidth.SetDirectory(NULL);
+    fHistArcWidth.UseCurrentStyle();
+    fHistArcWidth.SetFillStyle(4000);
+
+    fHistBroad.SetName("RingBroadening");
+    fHistBroad.SetTitle("Profile ArcWidth vs Radius");
+    fHistBroad.SetXTitle("R [\\circ]");
+    fHistBroad.SetYTitle("W/R [1]");
+    fHistBroad.GetXaxis()->SetTitleOffset(1.2);
+    fHistBroad.SetDirectory(NULL);
+    fHistBroad.UseCurrentStyle();
+    fHistBroad.SetFillStyle(4000);
+
+    fHistSize.SetName("SizeVsRadius");
+    fHistSize.SetTitle("Profile MuonSize vs Radius");
+    fHistSize.SetXTitle("R [\\circ]");
+    fHistSize.SetYTitle("S [phe]");
+    fHistSize.GetXaxis()->SetTitleOffset(1.2);
+    fHistSize.SetDirectory(NULL);
+    fHistSize.UseCurrentStyle();
+    fHistSize.SetFillStyle(4000);
+
+    MBinning bins;
+
+    bins.SetEdges(20, 0.5, 1.5);
+    bins.Apply(fHistRadius);
+
+    bins.SetEdges(60, 0., 0.3);
+    bins.Apply(fHistArcWidth);
+
+    bins.SetEdges(20, 0.5, 1.5);
+    bins.Apply(fHistBroad);
+
+    bins.SetEdges(20, 0.5, 1.5);
+    bins.Apply(fHistSize);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHMuonPar::SetupFill(const MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << warn << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fMuonSearchPar = (MMuonSearchPar*)plist->FindObject("MMuonSearchPar");
+    if (!fMuonSearchPar)
+    {
+        *fLog << warn << "MMuonSearchPar not found... abort." << endl;
+        return kFALSE;
+    }
+    fMuonCalibPar = (MMuonCalibPar*)plist->FindObject("MMuonCalibPar");
+    if (!fMuonCalibPar)
+    {
+        *fLog << warn << "MMuonCalibPar not found... abort." << endl;
+        return kFALSE;
+    }
+
+    ApplyBinning(*plist, "Radius",          fHistRadius);
+    ApplyBinning(*plist, "ArcWidth",        fHistArcWidth);
+    ApplyBinning(*plist, "RingBroadening",  fHistBroad);
+    ApplyBinning(*plist, "SizeVsRadius",    fHistSize);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MMuonCalibPar and
+// MMuonSearchPar container.
+//
+Int_t MHMuonPar::Fill(const MParContainer *par, const Stat_t w)
+{
+    const Double_t fMm2Deg = fGeom->GetConvMm2Deg();
+
+    fHistRadius.Fill(fMm2Deg*fMuonSearchPar->GetRadius(), w);
+
+    fHistArcWidth.Fill(fMuonCalibPar->GetArcWidth(), w);
+
+    fHistBroad.Fill(fMm2Deg*fMuonSearchPar->GetRadius(),
+                    fMuonCalibPar->GetArcWidth(), w);
+
+    fHistSize.Fill(fMm2Deg*fMuonSearchPar->GetRadius(),
+                   fMuonCalibPar->GetMuonSize(), 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 MHMuonPar::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHistRadius.Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHistArcWidth.Draw();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHistSize.Draw();
+
+    TText txt;
+    txt.SetTextColor(kBlue);
+
+    TF1 ref("RefShape100%", "-77.07+1249.3*x-351.2*x*x", fgIntegralLoLim, fgIntegralUpLim);
+    // old: 573*x + 430
+    ref.SetLineColor(kBlue);
+    ref.SetLineWidth(1);
+    ref.SetLineStyle(kDashed);
+    gROOT->GetListOfFunctions()->Remove(ref.DrawCopy("same"));
+
+    txt.SetTextAlign(31);
+    txt.DrawText(fgIntegralLoLim, ref.Eval(fgIntegralLoLim+0.05), "100%");
+
+    AppendPad("pad3");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHistBroad.Draw();
+
+    ref.SetName("RefShape12mm");
+    ref.Compile("- 0.02711*x + 0.09359");
+    gROOT->GetListOfFunctions()->Remove(ref.DrawCopy("same"));
+
+    txt.SetTextAlign(11);
+    txt.DrawText(fgIntegralLoLim, ref.Eval(fgIntegralLoLim-0.05), "12mm");
+
+    AppendPad("pad4");
+}
+/*
+Double_t MHMuonPar::Integral(const TProfile &p, Int_t a, Int_t b) const
+{
+    Float_t numerator   = 0;
+    Float_t denominator = 0;
+
+    for (Int_t i=a; i<b; i++)
+    {
+        numerator   += p.GetBinContent(i)*p.GetBinEntries(i);
+        denominator += p.GetBinEntries(i);
+    }
+
+    return denominator==0 ? 0 : numerator/denominator;
+}
+*/
+Double_t MHMuonPar::Integral(const TProfile &p, Float_t a, Float_t b) const
+{
+    const Int_t bin1 = p.GetXaxis()->FindFixBin(a);
+    const Int_t bin2 = p.GetXaxis()->FindFixBin(b);
+
+    return p.Integral(bin1, bin2);
+}
+
+void MHMuonPar::Paint(Option_t *opt)
+{
+    if (TString(opt)==TString("pad4"))
+    {
+        const TString txt = MString::Format("\\Sigma_{%.2f\\circ}^{%.2f\\circ} = %.3f",
+                                            fgIntegralLoLim, fgIntegralUpLim, Integral(fHistBroad));
+
+        TLatex text(0.55, 0.93, txt);
+        text.SetBit(TLatex::kTextNDC);
+        text.SetTextSize(0.055);
+        text.Paint();
+    }
+
+    if (TString(opt)==TString("pad3"))
+    {
+        const TString txt = MString::Format("\\Sigma_{%.2f\\circ}^{%.2f\\circ} = %.f",
+                                            fgIntegralLoLim, fgIntegralUpLim, Integral(fHistSize));
+
+        TLatex text(0.47, 0.93, txt);
+        text.SetBit(TLatex::kTextNDC);
+        text.SetTextSize(0.055);
+        text.Paint();
+    }
+}
Index: branches/Mars_McMismatchStudy/mmuon/MHMuonPar.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MHMuonPar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MHMuonPar.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MHMuonPar
+#define MARS_MHMuonPar
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+
+class MMuonSearchPar;
+class MMuonCalibPar;
+class MGeomCam;
+
+class MHMuonPar : public MH
+{
+private:
+    static const Float_t  fgIntegralLoLim; // lower limit of integral
+    static const Float_t  fgIntegralUpLim; // upper limit of integral
+
+    MMuonSearchPar *fMuonSearchPar; //!
+    MMuonCalibPar  *fMuonCalibPar;  //!
+    MGeomCam       *fGeom;          //! Conversion mm to deg
+
+    TH1F     fHistRadius;     // Radius
+    TH1F     fHistArcWidth;   // ArcWidth
+
+    TProfile fHistBroad;      // ArcWidth/Radius Vs Radius
+    TProfile fHistSize;       // MuonSize Vs Radius
+
+    //Double_t Integral(const TProfile &p, Int_t a, Int_t b) const;
+    Double_t Integral(const TProfile &p, Float_t a=fgIntegralLoLim, Float_t b=fgIntegralUpLim) const;
+
+public:
+    MHMuonPar(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TH1F&     GetHistRadius() const    { return fHistRadius; }
+    const TH1F&     GetHistArcWidth() const  { return fHistArcWidth; }
+    const TProfile& GetHistBroad() const     { return fHistBroad; }
+    const TProfile& GetHistSize() const      { return fHistSize; }
+
+    Double_t GetMeanSize() const  { return Integral(fHistSize);     }
+    Double_t GetMeanWidth() const { return Integral(fHistBroad);    }
+    Stat_t   GetEntries() const   { return fHistBroad.GetEntries(); }
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHMuonPar, 2)
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mmuon/MHSingleMuon.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MHSingleMuon.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MHSingleMuon.cc	(revision 17960)
@@ -0,0 +1,558 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase, 10/2004
+!   Author(s): Markus Meyer, 02/2005 <mailto:meyer@astro.uni-wuerzburg.de>
+!   Author(s): Thomas Bretz, 04/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHSingleMuon
+//
+// This class is a histogram class for displaying the radial (fHistWidth)
+// and the azimuthal (fHistPhi) intensity distribution for one muon.
+// You can retrieve the histogram (TH1F) using the function GetHistPhi()
+// or GetHistWidth().
+// From these histograms the fraction of the ring segment (ArcPhi) and the
+// Width of the muon ring (ArcWidth) is calculated.
+//
+// First, the radius and center of the ring has to be calculted by
+// MMuonSearchParCalc
+// After that the histograms has to be filled in the following way:
+//
+// MFillH fillmuon("MHSingleMuon", "", "FillMuon");
+//
+// The allowed region to estimate ArcPhi is a certain margin around the
+// radius. The default value is 0.2 deg (60mm). If the estimated radius
+// of the arc is 1.0 deg, the pixel contents in the radius range from
+// 0.8 deg to 1.2 deg are fill in the histogram.
+//
+// For ArcPhi only bins over a certain threshold are supposed to be part
+// of the ring.
+// For ArcWidth, the same algorithm is used to determine the fit region
+// for a gaussian fit to the radial intensity distribution. The ArcWidth
+// is defined as the sigma value of the gaussian fit.
+//
+// The binning of the histograms can be changed in the following way:
+//
+// MBinning bins1("BinningMuonWidth");
+// MBinning bins2("BinningArcPhi");
+// bins1.SetEdges(28, 0.3, 1.7);
+// bins2.SetEdges(20, -180,180);
+// plist.AddToList(&bins1);
+// plist.AddToList(&bins2);
+//
+// The values for the thresholds and the margin are saved in MMuonSetup.
+// They can be easily changed in star.rc.
+//
+// Please have in mind, that changes in this basic parameters will change
+// your results!!
+//
+// InputContainer:
+//   - MGeomCam
+//   - MMuonSearchPar
+//
+//
+// Class Version 2:
+// ----------------
+//   + Double_t fRelTimeMean;   // Result of the gaus fit to the arrival time
+//   + Double_t fRelTimeSigma;  // Result of the gaus fit to the arrival time
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHSingleMuon.h"
+
+#include <TF1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MMuonSetup.h"
+#include "MMuonCalibPar.h"
+#include "MMuonSearchPar.h"
+
+ClassImp(MHSingleMuon);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHSingleMuon::MHSingleMuon(const char *name, const char *title) :
+    fSignalCam(0), fMuonSearchPar(0), fGeomCam(0), fMargin(0)
+{
+    fName  = name  ? name  : "MHSingleMuon";
+    fTitle = title ? title : "Histograms of muon parameters";
+
+    fHistPhi.SetName("HistPhi");
+    fHistPhi.SetTitle("HistPhi");
+    fHistPhi.SetXTitle("\\phi [\\circ]");
+    fHistPhi.SetYTitle("sum of ADC");
+    fHistPhi.SetDirectory(NULL);
+    fHistPhi.SetFillStyle(4000);
+    fHistPhi.UseCurrentStyle();
+
+    fHistWidth.SetName("HistWidth");
+    fHistWidth.SetTitle("HistWidth");
+    fHistWidth.SetXTitle("distance from the ring center [\\circ]");
+    fHistWidth.SetYTitle("sum of ADC");
+    fHistWidth.SetDirectory(NULL);
+    fHistWidth.SetFillStyle(4000);
+    fHistWidth.UseCurrentStyle();
+
+    fHistTime.SetName("HistTime");
+    fHistTime.SetTitle("HistTime");
+    fHistTime.SetXTitle("timing difference");
+    fHistTime.SetYTitle("Counts");
+    fHistTime.SetDirectory(NULL);
+    fHistTime.SetFillStyle(4000);
+    fHistTime.UseCurrentStyle();
+
+    MBinning bins;
+    bins.SetEdges(20, -180, 180);
+    bins.Apply(fHistPhi);
+
+    bins.SetEdges(28, 0.3, 1.7);
+    bins.Apply(fHistWidth);
+
+    bins.SetEdges(101, -33, 33);   // +/- 33ns
+    bins.Apply(fHistTime);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHSingleMuon::SetupFill(const MParList *plist)
+{
+    fGeomCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << warn << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+    fMuonSearchPar = (MMuonSearchPar*)plist->FindObject("MMuonSearchPar");
+    if (!fMuonSearchPar)
+    {
+        *fLog << warn << "MMuonSearchPar not found... abort." << endl;
+        return kFALSE;
+    }
+    fSignalCam = (MSignalCam*)plist->FindObject("MSignalCam");
+    if (!fSignalCam)
+    {
+        *fLog << warn << "MSignalCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    MMuonSetup *setup = (MMuonSetup*)const_cast<MParList*>(plist)->FindCreateObj("MMuonSetup");
+    if (!setup)
+        return kFALSE;
+
+    fMargin = setup->GetMargin()/fGeomCam->GetConvMm2Deg();
+
+    ApplyBinning(*plist, "ArcPhi",    fHistPhi);
+    ApplyBinning(*plist, "MuonWidth", fHistWidth);
+    ApplyBinning(*plist, "MuonTime",  fHistTime);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MMuonCalibPar and
+// MMuonSearchPar container.
+//
+Int_t MHSingleMuon::Fill(const MParContainer *par, const Stat_t w)
+{
+    fRelTimeMean  =  0;
+    fRelTimeSigma = -1;
+
+    fHistPhi.Reset();
+    fHistWidth.Reset();
+    fHistTime.Reset();
+
+    const Int_t entries = fSignalCam->GetNumPixels();
+
+    // the position of the center of a muon ring
+    const Float_t cenx = fMuonSearchPar->GetCenterX();
+    const Float_t ceny = fMuonSearchPar->GetCenterY();
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MSignalPix &pix  = (*fSignalCam)[i];
+        const MGeom      &gpix = (*fGeomCam)[i];
+
+        const Float_t dx = gpix.GetX() - cenx;
+        const Float_t dy = gpix.GetY() - ceny;
+
+        const Float_t dist = TMath::Hypot(dx, dy);
+
+        // if the signal is not near the estimated circle, it is ignored.
+        if (TMath::Abs(dist-fMuonSearchPar->GetRadius())<fMargin)
+        {
+            // The arrival time is aligned around 0 for smaller
+            // and more stable histogram range
+            fHistTime.Fill(pix.GetArrivalTime()-fMuonSearchPar->GetTime());
+        }
+
+        // use only the inner pixles. FIXME: This is geometry dependent
+        if (gpix.GetAidx()>0)
+            continue;
+
+        fHistWidth.Fill(dist*fGeomCam->GetConvMm2Deg(), pix.GetNumPhotons());
+    }
+
+    // Setup the function and perform the fit
+    TF1 g1("g1", "gaus");//, -fHistTime.GetXmin(), fHistTime.GetXmax());
+
+    // Choose starting values as accurate as possible
+    g1.SetParameter(0, fHistTime.GetMaximum());
+    g1.SetParameter(1, 0);
+    g1.SetParameter(2, 0.7); // FIXME! GetRMS instead???
+
+    // According to fMuonSearchPar->GetTimeRMS() identified muons
+    // do not have an arrival time rms>3
+    g1.SetParLimits(1, -1.7, 1.7);
+    g1.SetParLimits(2,  0,   3.4);
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    if (fHistTime.Fit(&g1, "QNB"))
+        return kTRUE;
+
+    fRelTimeMean  = g1.GetParameter(1);
+    fRelTimeSigma = g1.GetParameter(2);
+
+    // The mean arrival time which was subtracted before will
+    // be added again, now
+    const Double_t tm0 = fMuonSearchPar->GetTime()+fRelTimeMean;
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MSignalPix &pix  = (*fSignalCam)[i];
+        const MGeom      &gpix = (*fGeomCam)[i];
+
+        const Float_t dx = gpix.GetX() - cenx;
+        const Float_t dy = gpix.GetY() - ceny;
+
+        const Float_t dist = TMath::Hypot(dx, dy);
+
+        // if the signal is not near the estimated circle, it is ignored.
+        if (TMath::Abs(dist-fMuonSearchPar->GetRadius())<fMargin &&
+            TMath::Abs(pix.GetArrivalTime()-tm0) < 2*fRelTimeSigma)
+        {
+            fHistPhi.Fill(TMath::ATan2(dx, dy)*TMath::RadToDeg(), pix.GetNumPhotons());
+        }
+    }
+
+    return kTRUE;
+
+/*
+    // Because the errors (sqrt(content)) are only scaled by a fixed
+    // factor, and the absolute value of the error is nowhere
+    // needed we skip this step
+
+    // error estimation (temporarily)
+    //  The error is estimated from the signal. In order to do so, we have to
+    // once convert the signal from ADC to photo-electron. Then we can get
+    // the fluctuation such as F-factor*sqrt(phe).
+    //  Up to now, the error of pedestal is not taken into accout. This is not
+    // of course correct. We will include this soon.
+    const Double_t Ffactor  = 1.4;
+    for (Int_t i=0; i<fHistPhi.GetNbinsX()+1; i++)
+        fHistPhi.SetBinError(i, fHistPhi.GetBinError(i)*Ffactor);
+
+    for (Int_t i=0; i<fHistWidth.GetNbinsX()+1; i++)
+        fHistWidth.SetBinError(i, fHistWidth.GetBinError(i)*Ffactor);
+
+    return kTRUE;
+ */
+}
+
+// --------------------------------------------------------------------------
+//
+// Find the first bins starting at the bin with maximum content in both
+// directions which are below threshold.
+// If in a range of half the histogram size in both directions no bin
+// below the threshold is found, kFALSE is returned.
+//
+Bool_t MHSingleMuon::FindRangeAboveThreshold(const TProfile &h, Float_t thres, Int_t &first, Int_t &last) const
+{
+    const Int_t n      = h.GetNbinsX();
+    const Int_t maxbin = h.GetMaximumBin();
+    const Int_t edge   = maxbin+n/2;
+
+    // Search from the peak to the right
+    last = -1;
+    for (Int_t i=maxbin; i<edge; i++)
+    {
+        const Float_t val = h.GetBinContent(i%n + 1);
+        if (val<thres)
+        {
+            last = i%n+1;
+            break;
+        }
+    }
+
+    // Search from the peak to the left
+    first = -1;
+    for (Int_t i=maxbin+n-1; i>=edge; i--)
+    {
+        const Float_t val = h.GetBinContent(i%n + 1);
+        if (val<thres)
+        {
+            first = i%n+1;
+            break;
+        }
+    }
+
+    return first>=0 && last>=0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Photon distribution along the estimated circle is fitted with theoritical
+// function in order to get some more information such as Arc Phi and Arc 
+// Length.
+//
+Bool_t MHSingleMuon::CalcPhi(Double_t thres, Double_t &peakphi, Double_t &arcphi) const
+{
+    if (fHistPhi.GetMaximum()<thres)
+        return kFALSE;
+
+    peakphi = 180.-fHistPhi.GetBinCenter(fHistPhi.GetMaximumBin());
+
+    // Now find the position at which the peak edges crosses the threshold
+    Int_t first, last;
+
+    FindRangeAboveThreshold(fHistPhi, thres, first, last);
+
+    const Int_t n    = fHistPhi.GetNbinsX();
+    const Int_t edge = fHistPhi.GetMaximumBin()+n/2;
+    if (first<0)
+        first = (edge-1)%n+1;
+    if (last<0)
+        last  = edge%n+1;;
+
+    const Float_t startfitval = fHistPhi.GetBinLowEdge(first+1);
+    const Float_t endfitval   = fHistPhi.GetBinLowEdge(last);
+
+    arcphi = last-1<first ? 360+(endfitval-startfitval) : endfitval-startfitval;
+
+    //if (fEnableImpactCalc)
+    //    CalcImpact(effbinnum, startfitval, endfitval);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Photon distribution of distance from the center of estimated ring is
+// fitted in order to get some more information such as ARC WIDTH which 
+// can represent to the PSF of our reflector.
+//
+// thres: Threshold above zero to determin the edges of the peak which
+//        is used as fit range
+// width: ArcWidth returned in deg
+// chi:   Chi^2/NDF of the fit
+//
+Bool_t MHSingleMuon::CalcWidth(Double_t thres, Double_t &width, Double_t &chi)
+{
+    Int_t first, last;
+
+    if (!FindRangeAboveThreshold(fHistWidth, thres, first, last))
+        return kFALSE;
+
+    // This happens in some cases
+    const Int_t n = fHistWidth.GetNbinsX()/2;
+    const Int_t m = fHistWidth.GetMaximumBin();
+    if (first>last)
+    {
+        if (m>n)       // If maximum is on the right side of histogram
+            last = n;
+        else
+            first = 0; // If maximum is on the left side of histogram
+    }
+
+    if (last-first<=3)
+        return kFALSE;
+
+    // Now get the fit range
+    const Float_t startfitval = fHistWidth.GetBinLowEdge(first+1);
+    const Float_t endfitval   = fHistWidth.GetBinLowEdge(last);
+
+    // Setup the function and perform the fit
+    TF1 f1("f1", "gaus + [3]", startfitval, endfitval);
+    f1.SetLineColor(kBlue);
+
+    // Choose starting values as accurate as possible
+    f1.SetParameter(0, fHistWidth.GetMaximum());
+    f1.SetParameter(1, fHistWidth.GetBinCenter(m));
+//    f1.SetParameter(2, (endfitval-startfitval)/2);
+    f1.SetParameter(2, 0.1);
+    f1.SetParameter(3, 1.8);
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+//    fHistWidth.Fit(&f1, "QRO");
+    if (fHistWidth.Fit(&f1, "QRN"))
+        return kFALSE;
+
+    chi   = f1.GetChisquare()/f1.GetNDF();
+    width = f1.GetParameter(2);
+
+    return kTRUE;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// An impact parameter is calculated by fitting the histogram of photon
+// distribution along the circle with a theoritical model. 
+// (See G. Vacanti et. al., Astroparticle Physics 2, 1994, 1-11. 
+// The function (6) is used here.) 
+//
+// By default this calculation is suppressed because this calculation is
+// very time consuming. If you want to calculate an impact parameter,
+// you can call the function of EnableImpactCalc().
+//
+void MMuonCalibParCalc::CalcImpact(Int_t effbinnum, Float_t startfitval, Float_t endfitval)
+{
+  // Fit the distribution with Vacanti function. The function is different
+  // for the impact parameter of inside or outside of our reflector. 
+  // Then two different functions are applied to the photon distribution,
+  // and the one which give us smaller chisquare value is taken as a 
+  // proper one.
+
+    Double_t val1,err1,val2,err2;
+    // impact parameter inside mirror radius (8.5m)
+    TString func1;
+    Float_t tmpval = (*fMuonSearchPar).GetRadius()*(*fGeomCam).GetConvMm2Deg()*TMath::DegToRad();
+    tmpval = sin(2.*tmpval)*8.5;
+    func1 += "[0]*";
+    func1 += tmpval;
+    func1 += "*(sqrt(1.-([1]/8.5)**2*sin((x-[2])*3.1415926/180.)**2)+([1]/8.5)*cos((x-[2])*3.1415926/180.))";
+
+    TF1 f1("f1",func1,startfitval,endfitval);
+    f1.SetParameters(2000,3,0);
+    f1.SetParLimits(1,0,8.5);
+    f1.SetParLimits(2,-180.,180.);
+
+    fMuonCalibPar->fHistPhi->Fit("f1","RQEM");
+
+    Float_t chi1 = -1;
+    Float_t chi2 = -1;
+    if(effbinnum>3)
+        chi1 = f1.GetChisquare()/((Float_t)(effbinnum-3));
+
+    gMinuit->GetParameter(1,val1,err1);  // get the estimated IP
+    Float_t estip1 = val1;
+
+    // impact parameter beyond mirror area (8.5m)
+    TString func2;
+    Float_t tmpval2 = (*fMuonSearchPar).GetRadius()*(*fGeomCam).GetConvMm2Deg()*TMath::DegToRad();
+    tmpval2 = sin(2.*tmpval2)*8.5*2.;
+    func2 += "[0]*";
+    func2 += tmpval2;
+    func2 += "*sqrt(1.-(([1]/8.5)*sin((x-[2])*3.1415926/180.))**2)";
+
+    TF1 f2("f2",func2,startfitval,endfitval);
+    f2.SetParameters(2000,20,0);
+    f2.SetParLimits(1,8.5,300.);
+    f2.SetParLimits(2,-180.,180.);
+
+    fMuonCalibPar->fHistPhi->Fit("f2","RQEM+");
+
+    if(effbinnum>3)
+        chi2 = f2.GetChisquare()/((Float_t)(effbinnum-3));
+
+    gMinuit->GetParameter(1,val2,err2);  // get the estimated IP
+    Float_t estip2 = val2;
+
+    if(effbinnum<=3)
+    {
+        fMuonCalibPar->SetEstImpact(-1.);
+    }
+    if(chi2 > chi1)
+    {
+        fMuonCalibPar->SetEstImpact(estip1);
+        fMuonCalibPar->SetChiArcPhi(chi1);
+    }
+    else
+    {
+        fMuonCalibPar->SetEstImpact(estip2);
+        fMuonCalibPar->SetChiArcPhi(chi2);
+    }
+}
+*/
+
+Float_t MHSingleMuon::CalcSize() const
+{
+    const Int_t n = fHistPhi.GetNbinsX();
+
+    Double_t sz=0;
+    for (Int_t i=1; i<=n; i++)
+        sz += fHistPhi.GetBinContent(i)*fHistPhi.GetBinEntries(i);
+
+    return sz;
+}
+
+void MHSingleMuon::Paint(Option_t *o)
+{
+    TF1 *f = fHistWidth.GetFunction("f1");
+    if (f)
+        f->ResetBit(1<<9);
+}
+
+void MHSingleMuon::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(1,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fHistPhi.Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fHistWidth.Draw();
+}
Index: branches/Mars_McMismatchStudy/mmuon/MHSingleMuon.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MHSingleMuon.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MHSingleMuon.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHSingleMuon
+#define MARS_MHSingleMuon
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+
+class MSignalCam;
+class MMuonSearchPar;
+class MMuonCalibPar;
+class MMuonSetup;
+class MGeomCam;
+
+class MHSingleMuon : public MH
+{
+private:
+    MSignalCam     *fSignalCam;     //!
+    MMuonSearchPar *fMuonSearchPar; //!
+    MGeomCam       *fGeomCam;       //!
+
+    Double_t fMargin;               //!
+
+    TProfile fHistPhi;    // Histogram of photon distribution along the arc.
+    TProfile fHistWidth;  // Histogram of radial photon distribution of the arc.
+    TH1F     fHistTime;   // Histogram of arrival time distribution along the arc.
+
+    Double_t fRelTimeMean;   // Result of the gaus fit to the arrival time
+    Double_t fRelTimeSigma;  // Result of the gaus fit to the arrival time
+
+    Bool_t FindRangeAboveThreshold(const TProfile &h, Float_t thres, Int_t &first, Int_t &last) const;
+
+public:
+    MHSingleMuon(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    Bool_t CalcPhi(Double_t, Double_t &, Double_t &) const;
+    Bool_t CalcWidth(Double_t, Double_t &, Double_t &);
+
+    const TProfile &GetHistPhi() const { return fHistPhi; }
+    const TH1F     &GetHistTime() const { return fHistTime; }
+    const TProfile &GetHistWidth() const { return fHistWidth; }
+
+    Double_t GetRelTimeMean() const  { return fRelTimeMean; }
+    Double_t GetRelTimeSigma() const { return fRelTimeSigma; }
+
+    Float_t CalcSize() const;
+
+    void Draw(Option_t *o="");
+    void Paint(Option_t *o="");
+
+    ClassDef(MHSingleMuon, 2)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmuon/MMuonCalibPar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonCalibPar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonCalibPar.cc	(revision 17960)
@@ -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): Keiichi Mase 10/2004 <mailto:mase@mppmu.mpg.de>
+!   Author(s): Markus Meyer 10/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMuonCalibPar
+//
+// Storage Container for muon
+//
+//  This class holds some information for a calibration using muons. Muons
+// are identified by using the class of the MMuonSearchParCalc. You can fill 
+// these information by using the MMuonCalibParCalc. See also these class
+// manuals.
+//
+// Class Version 2:
+// ----------------
+//   + Float_t fRelTimeMean;   // Result of the gaus fit to the arrival time
+//   + Float_t fRelTimeSigma;  // Result of the gaus fit to the arrival time
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMuonCalibPar.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+using namespace std;
+
+ClassImp(MMuonCalibPar);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMuonCalibPar::MMuonCalibPar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMuonCalibPar";
+    fTitle = title ? title : "Parameters to calculate Muon calibration";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MMuonCalibPar::Reset()
+{
+//    fArcLength   = -1.;
+    fArcPhi      = -1.;
+    fArcWidth    = -1.;
+    fChiArcPhi   = -1.;
+    fChiArcWidth = -1.;
+    fMuonSize    =  0.;
+//    fEstImpact   = -1.;
+    fPeakPhi     =  0.;
+
+    fRelTimeMean    =  0;
+    fRelTimeSigma   = -1;
+}
+
+void MMuonCalibPar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Arc Phi        [deg] = " << fArcPhi      << endl;
+    *fLog << " - Arc Width      [deg] = " << fArcWidth    << endl;
+    *fLog << " - Red ChiSq Arc Phi    = " << fChiArcPhi   << endl;
+    *fLog << " - Red ChiSq Arc Width  = " << fChiArcWidth << endl;
+    *fLog << " - Size of muon   [phe] = " << fMuonSize    << endl;
+    *fLog << " - Peak Phi       [deg] = " << fPeakPhi     << endl;
+    *fLog << " - Rel.Time Mean   [ns] = " << fRelTimeMean  << endl;
+    *fLog << " - Rel.Time Sigma  [ns] = " << fRelTimeSigma << endl;
+}
+
Index: branches/Mars_McMismatchStudy/mmuon/MMuonCalibPar.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonCalibPar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonCalibPar.h	(revision 17960)
@@ -0,0 +1,65 @@
+#ifndef MARS_MMuonCalibPar
+#define MARS_MMuonCalibPar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MSignalCam;
+class MMuonSearchPar;
+
+class MMuonCalibPar : public MParContainer
+{
+private:
+//    Float_t fArcLength;     // An arc length of a muon along the arc [deg.]
+    Float_t fArcPhi;        // A opening angle of a muon arc [deg.]
+    Float_t fArcWidth;      // A width of a muon [deg.] (1 sigma of gaussian fit)
+    Float_t fChiArcPhi;     // A chisquare value of the cosine fit for arc phi
+    Float_t fChiArcWidth;   // A chisquare value of the cosine fit for arc wid
+    Float_t fMuonSize;      // A SIZE of muon which is defined as a SIZE around the estimated circle
+//    Float_t fEstImpact;     // An estimated impact parameter from the photon distribution along the arc image
+    //Bool_t  fUseUnmap;      // This is a flag to know the Unmapped pixels are used. Refer to the class of MImgCleanStd
+    Float_t fPeakPhi;       // The angle which indicates the peak position in the estimated circle
+
+    Float_t fRelTimeMean;      // [ns] Result of the gaus fit to the arrival time
+    Float_t fRelTimeSigma;     // [ns] Result of the gaus fit to the arrival time
+
+public:
+    MMuonCalibPar(const char *name=NULL, const char *title=NULL);
+    //~MMuonCalibPar();
+
+    void Reset();
+
+//    Float_t GetArcLength()      const { return fArcLength; }
+    Float_t GetArcPhi()         const { return fArcPhi; }
+    Float_t GetArcWidth()       const { return fArcWidth; }
+    Float_t GetChiArcPhi()      const { return fChiArcPhi; }
+    Float_t GetChiArcWidth()    const { return fChiArcWidth; }
+    Float_t GetMuonSize()       const { return fMuonSize; }
+//    Float_t GetEstImpact()      const { return fEstImpact; }
+    //Bool_t  IsUseUnmap()        const { return fUseUnmap; }
+    Float_t GetPeakPhi()        const { return fPeakPhi; }
+    Float_t GetRelTimeMean()    const { return fRelTimeMean; }
+    Float_t GetRelTimeSigma()   const { return fRelTimeSigma; }
+
+//    void    SetArcLength(Float_t len)       { fArcLength = len; }
+    void    SetArcPhi(Float_t phi)          { fArcPhi = phi; }
+    void    SetArcWidth(Float_t wid)        { fArcWidth = wid; }
+    void    SetChiArcPhi(Float_t chi)       { fChiArcPhi = chi; }
+    void    SetChiArcWidth(Float_t chi)     { fChiArcWidth = chi; }
+    void    SetMuonSize(Float_t size)       { fMuonSize = size; }
+//    void    SetEstImpact(Float_t impact)    { fEstImpact = impact; }
+    //void    SetUseUnmap()                   { fUseUnmap = kTRUE; }
+    void    SetPeakPhi(Float_t phi)         { fPeakPhi = phi; }
+    void    SetTime(Float_t mean, Float_t sigma) { fRelTimeMean=mean; fRelTimeSigma=sigma; }
+
+    void    Print(Option_t *opt=NULL) const;
+
+    ClassDef(MMuonCalibPar, 2) // Container to hold muon calibration parameters
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mmuon/MMuonCalibParCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonCalibParCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonCalibParCalc.cc	(revision 17960)
@@ -0,0 +1,195 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase 10/2004 <mailto:mase@mppmu.mpg.de>
+!              Markus Meyer 10/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MMuonCalibParCalc
+//
+// Task to calculate the muon parameters
+//
+// This class allows you to get more muon information especially useful for
+// the calibration of our telescope. This class store the information into the
+// container of MMuonCalibPar. 
+//
+// In order to make this class work, we need the information of the arc
+// center and the radius. Therefore, we need to use the task of 
+// MMuonSearchParCalc.
+// In the second step two histograms has to be filled for every muon.
+// This is made by MHSingleMuon (look there for more information).
+//
+// The calculation of Muon parameters works as the followings;
+//
+//   MTaskList tlist;
+//   MMuonSearchParCalc musearchcalc;
+//   MFillH fillmuon("MHSingleMuon", "", "FillMuon");
+//   MMuonCalibParCalc mucalibcalc;
+//   tlist.AddToList(&musearchcalc);
+//   tlist.AddToList(&fillmuon);
+//   tlist.AddToList(&mucalibcalc);.
+//
+//
+// For a faster coputation, pre cuts to select the candidates
+// of muons for the calibration should be done. It is already implemented
+// in star. You can set the values in star.rc.
+//
+// ### TODO ###
+//  Up to now, in the histogram the error of the signal is estimated from
+// the signal using a rough conversion factor and a F-factor and this values
+// are global for all pixels. This is not the case for the real data. This
+// value should be taken from some containers. In addition, the error of 
+// the pedestal is not taken into accout. The error treatment should be
+// done correctly.
+//
+//
+//  Input Containers:
+//   MGeomCam
+//   MSignalCam
+//   MMuonSearchPar
+//
+//  Output Containers:
+//   MMuonCalibPar
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MMuonCalibParCalc.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TMinuit.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MSignalCam.h"
+
+#include "MMuonCalibPar.h"
+#include "MMuonSetup.h"
+#include "MMuonSearchPar.h"
+#include "MHSingleMuon.h"
+
+using namespace std;
+
+ClassImp(MMuonCalibParCalc);
+
+static const TString gsDefName  = "MMuonCalibParCalc";
+static const TString gsDefTitle = "Calculate new image parameters";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MMuonCalibParCalc::MMuonCalibParCalc(const char *name, const char *title)
+//    : fEnableImpactCalc(kFALSE)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonCalibParCalc::PreProcess(MParList *pList)
+{
+    fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fHist = (MHSingleMuon*)pList->FindObject("MHSingleMuon");
+    if (!fHist)
+    {
+        *fLog << err << "MHSingleMuon not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fMuonSetup = (MMuonSetup*)pList->FindObject("MMuonSetup");
+    if (!fMuonSetup)
+    {
+        *fLog << err << "MMuonSetup not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fMuonCalibPar = (MMuonCalibPar*)pList->FindCreateObj("MMuonCalibPar");
+    if (!fMuonCalibPar)
+        return kFALSE;
+
+    fMuonSearchPar = (MMuonSearchPar*)pList->FindCreateObj("MMuonSearchPar");
+    if (!fMuonSearchPar)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonCalibParCalc::Process()
+{
+    // Calculation of ArcPhi, ArcWidth and MuonSize.
+    const Float_t thresphi   = fMuonSetup->GetThresholdArcPhi();
+    const Float_t threswidth = fMuonSetup->GetThresholdArcWidth();
+
+    Double_t peakphi, arcphi;
+    Double_t width, chi;
+
+    if (!fHist->CalcPhi(thresphi, peakphi, arcphi))
+        return kTRUE;
+
+    if (!fHist->CalcWidth(threswidth, width, chi))
+        return kTRUE;
+
+    // Get Muon Size
+    //fMuonCalibPar->SetMuonSize(fHist->GetHistPhi().Integral());
+
+    fMuonCalibPar->SetMuonSize(fHist->CalcSize());
+
+    // Calculate ArcPhi
+    fMuonCalibPar->SetPeakPhi(peakphi);
+    fMuonCalibPar->SetArcPhi(arcphi);
+
+    fMuonCalibPar->SetTime(fHist->GetRelTimeMean(), fHist->GetRelTimeSigma());
+
+//    const Float_t conv = TMath::RadToDeg()*fGeomCam->GetConvMm2Deg();
+//    fMuonCalibPar->SetArcLength(fMuonCalibPar->GetArcPhi()
+//                                *fMuonSearchPar->GetRadius()*conv);
+
+    // Calculation of ArcWidth etc...
+    fMuonCalibPar->SetChiArcWidth(chi);
+    fMuonCalibPar->SetArcWidth(width);
+
+    const Double_t rad = fMuonSearchPar->GetRadius()*fGeomCam->GetConvMm2Deg();
+    const Double_t dev = fMuonSearchPar->GetDeviation()*fGeomCam->GetConvMm2Deg();
+
+    // Check if this is a 'Write-Out' candidate
+    if (arcphi>160 && rad>0.573  && rad<1.35 && dev<0.169)
+        fMuonCalibPar->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mmuon/MMuonCalibParCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonCalibParCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonCalibParCalc.h	(revision 17960)
@@ -0,0 +1,41 @@
+#ifndef MARS_MMuonCalibParCalc
+#define MARS_MMuonCalibParCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMuonSearchPar;
+class MMuonCalibPar;
+class MGeomCam;
+class MMuonSetup;
+class MHSingleMuon;
+
+class MMuonCalibParCalc : public MTask
+{
+private:
+    MGeomCam       *fGeomCam;         //!
+    MMuonCalibPar  *fMuonCalibPar;    //!
+    MMuonSearchPar *fMuonSearchPar;   //!
+    MMuonSetup     *fMuonSetup;       //!
+    MHSingleMuon   *fHist;            //!
+
+    //Bool_t fEnableImpactCalc; // If true, the impact calculation will be done, which consumes a lot of time.
+
+    Int_t   PreProcess(MParList *plist);
+    Int_t   Process();
+
+    void    FillHist();
+    void    CalcPhi();
+    void    CalcImpact(Int_t effbinnum, Float_t startfitval, Float_t endfitval);
+    Float_t CalcWidth();
+
+public:
+    MMuonCalibParCalc(const char *name=NULL, const char *title=NULL);
+
+    //void EnableImpactCalc(Bool_t b=kTRUE) { fEnableImpactCalc = b; }
+
+    ClassDef(MMuonCalibParCalc, 0) // task to calculate muon parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmuon/MMuonSearchPar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonSearchPar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonSearchPar.cc	(revision 17960)
@@ -0,0 +1,336 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase 10/2004 <mailto:mase@mppmu.mpg.de>
+!   Author(s): Markus Meyer 10/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMuonSearchPar
+//
+// Storage Container for muon
+//
+// This class is the container for muon parameters. The calculation
+// of Radius and center of the ring is done here.
+// Muons are searched by fitting the image with a circle.
+//
+//  In order to use further information of muons such as the width of arcs,
+// the size of the fraction of the ring and the muons size, use the
+// infomation stored in
+//
+//   MMuonCalibPar.
+//
+// The information will be available by using the task of
+//
+//   MMuonCalibParCalc.
+//
+// Version 2:
+// ----------
+//   + Float_t fTime;      // Mean arrival time of core pixels
+//   + Float_t fTimeRms;   // Rms of arrival time of core pixels
+//
+//  Input Containers:
+//   MGeomCam
+//   MHillas
+//   MSignalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMuonSearchPar.h"
+
+#include <TMinuit.h>
+#include <TEllipse.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+using namespace std;
+
+ClassImp(MMuonSearchPar);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMuonSearchPar::MMuonSearchPar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMuonSearchPar";
+    fTitle = title ? title : "Parameters to find Muons";
+}
+
+// --------------------------------------------------------------------------
+//
+void MMuonSearchPar::Reset()
+{
+    fRadius    = -1;
+    fDeviation = -1;
+    fCenterX   =  0;
+    fCenterY   =  0;
+    fTime      =  0;
+    fTimeRms   = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  return TMath::Hypot(fCenterX, fCenterY);
+//
+Float_t MMuonSearchPar::GetDist() const
+{
+    return TMath::Hypot(fCenterX, fCenterY);
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a wrapper function to have direct access to the data members
+// in the function calculating the minimization value.
+//
+void MMuonSearchPar::fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    const MMuonSearchPar *optim = (MMuonSearchPar*)gMinuit->GetObjectFit();
+    f = optim->Fcn(par);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function gives you the ring radius fitted best to the camera image
+//  and its RMS for the input position.
+//
+Double_t MMuonSearchPar::Fcn(Double_t *par) const
+{
+    const Int_t entries = fSignal.GetSize();
+
+    Double_t meanr=0;
+    Double_t devr =0;
+    Double_t sums =0;
+
+    // It seems that the loop is easy enough for a compiler optimization.
+    // Using pointer arithmetics doesn't improve the speed of the fit.
+    for (Int_t i=0; i<entries; i++ )
+    {
+        const Double_t dx = fX[i]-par[0];
+        const Double_t dy = fY[i]-par[1];
+
+        const Double_t sq = dx*dx + dy*dy;
+
+        sums  += fSignal[i];
+        meanr += fSignal[i] * TMath::Sqrt(sq);
+        devr  += fSignal[i] * sq;
+    }
+
+    par[2] = meanr/sums;
+    par[3] = devr/sums - par[2]*par[2];
+
+    return par[3];
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function finds the center position of the circle which gives minimum 
+// RMS of the fit, changing the center position of the circle.
+//
+void MMuonSearchPar::CalcMinimumDeviation(const MGeomCam &geom,
+                                          const MSignalCam &evt,
+                                          Double_t &x, Double_t &y,
+                                          Double_t &sigma, Double_t &radius)
+{
+    // ------- Make a temporaray copy of the signal ---------
+    // ------- and calculate arrival time parameters --------
+    const Int_t n = geom.GetNumPixels();
+
+    fSignal.Set(n);
+    fX.Set(n);
+    fY.Set(n);
+
+    Int_t p=0;
+    Int_t q=0;
+
+    Double_t mean=0;
+    Double_t sq  =0;
+
+    for (int i=0; i<n; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        fSignal[p] = pix.GetNumPhotons();
+
+        fX[p] = geom[i].GetX();
+        fY[p] = geom[i].GetY();
+        p++;
+
+        //timing
+        if (!pix.IsPixelCore())
+            continue;
+
+        mean += pix.GetArrivalTime();
+        sq   += pix.GetArrivalTime()*pix.GetArrivalTime();
+        q++;
+    }
+
+    mean /= q;
+    sq   /= q;
+
+    fTime    = mean;
+    fTimeRms = TMath::Sqrt(sq-mean*mean);
+
+    fSignal.Set(p);
+
+
+    // ----------------- Setup and call minuit -------------------
+    const Float_t  delta = 30.;  // 3 mm (1/10 of an inner pixel size) Step to move.
+    //const Double_t r     = geom.GetMaxRadius()*2;
+
+    // Save gMinuit
+    TMinuit *minsave = gMinuit;
+
+    // Initialize TMinuit with 4 parameters
+    TMinuit minuit;
+    minuit.SetPrintLevel(-1);     // Switch off printing
+    minuit.Command("set nowarn"); // Switch off warning
+    // Define Parameters
+    minuit.DefineParameter(0, "x",     x, delta,  0, 0);//-r, r);
+    minuit.DefineParameter(1, "y",     y, delta,  0, 0);//-r, r);
+    minuit.DefineParameter(2, "r",     0, 1,      0, 0);
+    minuit.DefineParameter(3, "sigma", 0, 1,      0, 0);
+    // Fix return parameters
+    minuit.FixParameter(2);
+    minuit.FixParameter(3);
+    // Setup Minuit for 'this' and use fit function fcn
+    minuit.SetObjectFit(this);
+    minuit.SetFCN(fcn);
+
+    // Perform Simplex minimization
+    Int_t er;
+    Double_t tmp[2] = { 0, 0 };
+    minuit.mnexcm("simplex", tmp, 2, er);
+
+    // Get resulting parameters
+    Double_t error;
+    minuit.GetParameter(0, x,      error);
+    minuit.GetParameter(1, y,      error);
+    minuit.GetParameter(2, radius, error);
+    minuit.GetParameter(3, sigma,  error);
+
+    sigma = sigma>0 ? TMath::Sqrt(sigma) : 0;
+
+    gMinuit = minsave;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of muon parameters
+//
+void MMuonSearchPar::Calc(const MGeomCam &geom, const MSignalCam &evt,
+                          const MHillas &hillas)
+{
+    Double_t x = hillas.GetMeanX();
+    Double_t y = hillas.GetMeanY();
+
+    // -------------------------------------------------
+    // Keiichi suggested trying to precalculate the Muon
+    // center a bit better, but it neither improves the
+    // fit result nor the speed
+    //
+    // const Float_t tmpr = 300.;  // assume that the temporal cherenkov angle is 1 deg. (300 mm).
+    //
+    // const Double_t a = TMath::Tan(hillas.GetDelta());
+    //
+    // const Double_t dx =     a/TMath::Sqrt(tmpr+a*a)/3.;
+    // const Double_t dy = -tmpr/TMath::Sqrt(1+a*a)/3.;
+    //
+    // Double_t par1[] = { x+dx, y+dy, 0, 0 };
+    // Double_t par2[] = { x-dx, y-dy, 0, 0 };
+    //
+    // const Double_t dev1 = MMuonSearchPar::Fcn(par1);
+    // const Double_t dev2 = MMuonSearchPar::Fcn(par2);
+    //
+    // if (dev1<dev2)
+    // {
+    //     x += dx;
+    //     y += dy;
+    // }
+    // else
+    // {
+    //     x -= dx;
+    //     y -= dy;
+    // }
+    // -------------------------------------------------
+
+    Double_t sigma, rad;
+
+    // find the best fit.
+    CalcMinimumDeviation(geom, evt, x, y, sigma, rad);
+
+    fCenterX   = x;
+    fCenterY   = y;
+    fRadius    = rad;
+    fDeviation = sigma;
+
+    //SetReadyToSave();
+} 
+
+void MMuonSearchPar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Est. Radius     [mm] = " << fRadius  << endl;
+    *fLog << " - Deviation       [mm] = " << fDeviation  << endl;
+    *fLog << " - Center Pos. X   [mm] = " << fCenterX << endl;
+    *fLog << " - Center Pos. Y   [mm] = " << fCenterY << endl;
+}
+
+void MMuonSearchPar::Print(const MGeomCam &geom, Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Est. Radius    [deg] = " << fRadius*geom.GetConvMm2Deg()   << endl;
+    *fLog << " - Deviation      [deg] = " << fDeviation*geom.GetConvMm2Deg()   << endl;
+    *fLog << " - Center Pos. X  [deg] = " << fCenterX*geom.GetConvMm2Deg()  << endl;
+    *fLog << " - Center Pos. Y  [deg] = " << fCenterY*geom.GetConvMm2Deg()  << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MMuonSearchPar::Paint(Option_t *opt)
+{
+    //if (fRadius<180 || fRadius>400 || fDeviation>45)
+    //    return;
+
+    TEllipse e1(fCenterX, fCenterY, fRadius-fDeviation, fRadius-fDeviation);
+    TEllipse e2(fCenterX, fCenterY, fRadius+fDeviation, fRadius+fDeviation);
+    e1.SetLineWidth(1);
+    e2.SetLineWidth(1);
+    e1.SetLineColor(kYellow);
+    e2.SetLineColor(kYellow);
+    e1.Paint();
+    e2.Paint();
+}
Index: branches/Mars_McMismatchStudy/mmuon/MMuonSearchPar.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonSearchPar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonSearchPar.h	(revision 17960)
@@ -0,0 +1,63 @@
+#ifndef MARS_MMuonSearchPar
+#define MARS_MMuonSearchPar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MMuonSearchPar : public MParContainer
+{
+private:
+    Float_t fRadius;    // An estimated radius of the muon ring [mm]
+    Float_t fDeviation; // The standard deviation from the estimated ring [mm]
+    Float_t fCenterX;   // An estimated center position in X of the muon ring [mm]
+    Float_t fCenterY;   // An estimated center position in Y of the muon ring [mm]
+    Float_t fTime;      // Mean arrival time of core pixels
+    Float_t fTimeRms;   // Rms of arrival time of core pixels
+
+    MArrayF fSignal;    //! Temporary storage for signal
+    MArrayF fX;         //! Temporary storage for pixels X-position
+    MArrayF fY;         //! Temporary storage for pixels Y-position
+
+    static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag);
+    Double_t Fcn(Double_t *par) const;
+
+public:
+    MMuonSearchPar(const char *name=NULL, const char *title=NULL);
+
+    // MParContainer
+    void Reset();
+
+    // Getter
+    Float_t GetRadius()    const { return fRadius; }
+    Float_t GetDeviation() const { return fDeviation; }
+    Float_t GetCenterX()   const { return fCenterX; }
+    Float_t GetCenterY()   const { return fCenterY; }
+    Float_t GetDist() const;
+    Float_t GetTime()      const { return fTime; }
+    Float_t GetTimeRms()   const { return fTimeRms; }
+
+    // MMuonSearchPar
+    void   CalcMinimumDeviation(const MGeomCam &geom, const MSignalCam &evt,
+                                Double_t &x, Double_t &y, Double_t &sigma, Double_t &rad);
+
+    void   Calc(const MGeomCam &geom, const MSignalCam &evt,
+		const MHillas &hillas);
+
+    // TObject
+    void   Paint(Option_t *opt="");
+    void   Print(Option_t *opt=NULL) const;
+    void   Print(const MGeomCam &geom, Option_t *opt=NULL) const;
+
+    ClassDef(MMuonSearchPar, 2) // Container to hold muon search parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mmuon/MMuonSearchParCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonSearchParCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonSearchParCalc.cc	(revision 17960)
@@ -0,0 +1,112 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase 09/2004 <mailto:mase@mppmu.mpg.de>
+!   Author(s): Markus Meyer 09/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MMuonSearchParCalc
+//
+// Task to calculate the muon parameters
+//
+// This class search for muons and store the information into the container
+// of MMuonSearchPar. Please see the manual for more information.
+//
+//
+//  Input Containers:
+//   MGeomCam
+//   MHillas
+//   MSignalCam
+//
+//  Output Containers:
+//   MMuonSearchPar
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMuonSearchParCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MSignalCam.h"
+#include "MMuonSearchPar.h"
+
+using namespace std;
+
+ClassImp(MMuonSearchParCalc);
+
+static const TString gsDefName  = "MMuonSearchParCalc";
+static const TString gsDefTitle = "Calculate muon parameters";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MMuonSearchParCalc::MMuonSearchParCalc(const char *name, const char *title)
+  : fHillas(NULL), fMuonPar(NULL)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonSearchParCalc::PreProcess(MParList *pList)
+{
+    fHillas = (MHillas*)pList->FindObject("MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSignalCam = (MSignalCam*)pList->FindObject("MSignalCam");
+    if (!fSignalCam)
+    {
+        *fLog << err << "MSignalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMuonPar = (MMuonSearchPar*)pList->FindCreateObj("MMuonSearchPar");
+    if (!fMuonPar)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonSearchParCalc::Process()
+{
+    fMuonPar->Calc(*fGeomCam, *fSignalCam, *fHillas);
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mmuon/MMuonSearchParCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonSearchParCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonSearchParCalc.h	(revision 17960)
@@ -0,0 +1,31 @@
+#ifndef MARS_MMuonSearchParCalc
+#define MARS_MMuonSearchParCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MHillas;
+class MMuonSearchPar;
+class MGeomCam;
+class MSignalCam;
+
+class MMuonSearchParCalc : public MTask
+{
+private:
+    MGeomCam       *fGeomCam;     //!
+    MSignalCam     *fSignalCam;   //!
+    MHillas        *fHillas;      //! Pointer to the source independent hillas parameters
+    MMuonSearchPar *fMuonPar;     //! Pointer to the output container for the new image parameters
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MMuonSearchParCalc(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MMuonSearchParCalc, 0) // task to calculate muon parameters
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mmuon/MMuonSetup.cc
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonSetup.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonSetup.cc	(revision 17960)
@@ -0,0 +1,84 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 Meyer 04/2005 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMuonSetup
+//
+// Storage Container for setup parameter for the muon analysis
+//
+// - margin
+// - ThresholdArcWidth
+// - ThresholdArcPhi
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMuonSetup.h"
+
+#include <fstream>
+
+#include "MLog.h"
+
+using namespace std;
+
+ClassImp(MMuonSetup);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMuonSetup::MMuonSetup(const char *name, const char *title)
+    : fMargin(0.2), fThresholdArcPhi(5), fThresholdArcWidth(2)
+{
+    fName  = name  ? name  : "MMuonSetup";
+    fTitle = title ? title : "Muon calibration setup parameters";
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MMuonSetup.Margin:            0.2
+//   MMuonSetup.ThresholdArcPhi:   30
+//   MMuonSetup.ThresholdArcWidth: 2
+//
+Int_t MMuonSetup::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Margin", print))
+    {
+        rc = kTRUE;
+        fMargin = GetEnvValue(env, prefix, "Margin", fMargin);
+    }
+    if (IsEnvDefined(env, prefix, "ThresholdArcPhi", print))
+    {
+        rc = kTRUE;
+        fThresholdArcPhi = GetEnvValue(env, prefix, "ThresholdArcPhi", fThresholdArcPhi);
+    }
+    if (IsEnvDefined(env, prefix, "ThresholdArcWidth", print))
+    {
+        rc = kTRUE;
+        fThresholdArcWidth = GetEnvValue(env, prefix, "ThresholdArcWidth", fThresholdArcWidth);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mmuon/MMuonSetup.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MMuonSetup.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MMuonSetup.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MMuonSetup
+#define MARS_MMuonSetup
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MMuonSetup : public MParContainer
+{
+private:
+    Float_t fMargin;            // [deg] margin to evaluate muons. The defaut value is 0.2 deg (60mm)
+    Float_t fThresholdArcPhi;   // [phe] The threshold value to define ArcPhi
+    Float_t fThresholdArcWidth; // [phe] The threshold value to define ArcWidth
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MMuonSetup(const char *name=NULL, const char *title=NULL);
+
+    // Getter
+    Float_t GetMargin() const { return fMargin; }
+    Float_t GetThresholdArcPhi() const { return fThresholdArcPhi; }
+    Float_t GetThresholdArcWidth() const { return fThresholdArcWidth; }
+
+    // Setter
+    void SetMargin(Float_t margin)           { fMargin = margin; }
+    void SetThresholdArcPhi(Float_t thres)   { fThresholdArcPhi = thres; }
+    void SetThresholdArcWidth(Float_t thres) { fThresholdArcWidth = thres; }
+
+    ClassDef(MMuonSetup, 1) // Container to hold setup for muon analysis
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mmuon/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/Makefile	(revision 17960)
@@ -0,0 +1,50 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Muon
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mmc -I../mraw -I../mgeom -I../mfilter \
+	   -I../mdata -I../mhbase -I../mhist -I../mgui -I../mimage   \
+           -I../mhistmc -I../mfileio -I../mmain -I../mhcalib -I../mcalib \
+           -I../msignal -I../mpointing -I../mtools -I../mfbase       \
+           -I../mbadpixels -I../mastro -I../mpedestal -I../manalysis
+
+SRCFILES = MMuonSearchPar.cc \
+           MMuonSearchParCalc.cc \
+           MMuonCalibPar.cc \
+           MMuonCalibParCalc.cc \
+           MHMuonPar.cc \
+           MHSingleMuon.cc \
+           MMuonSetup.cc
+
+############################################################
+
+all:  $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mmuon/MuonIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MuonIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MuonIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mmuon/MuonLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mmuon/MuonLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mmuon/MuonLinkDef.h	(revision 17960)
@@ -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 MMuonSearchPar+;
+#pragma link C++ class MMuonCalibPar+;
+#pragma link C++ class MMuonSetup+;
+
+#pragma link C++ class MMuonSearchParCalc+;
+#pragma link C++ class MMuonCalibParCalc+;
+
+#pragma link C++ class MHMuonPar+;
+#pragma link C++ class MHSingleMuon+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mona.cc
===================================================================
--- branches/Mars_McMismatchStudy/mona.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mona.cc	(revision 17960)
@@ -0,0 +1,347 @@
+#include <TApplication.h>
+
+#include <TThread.h>
+#include <TCanvas.h>
+#include <TMethod.h>          // GetMenuItems
+
+#include <TGButton.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MLogManip.h"
+
+#include "MRawSocketRead.h"
+#include "MGeomApply.h"
+#include "MCerPhotAnal2.h"
+#include "MFillH.h"
+#include "MFRealTimePeriod.h"
+#include "MHTriggerLvl0.h"
+#include "MHCamera.h"         // ::Class(), SetFreezed
+#include "MHCamEvent.h"       // MHCamEvent
+#include "MHEvent.h"          // MHEvent::GetHist()
+
+#include "MOnlineDump.h"
+#include "MOnlineDisplay.h"
+
+#include "MImgCleanStd.h"
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+#include "MEventRateCalc.h"
+
+#include "MArgs.h"
+
+// --------------------------------------------------------------------
+
+#include "MTime.h"
+#include "MRawEvtHeader.h"       // MRawEvtHeader
+#include "MRawRunHeader.h"       // MRawRunHeader
+
+using namespace std;
+
+void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "                    MONA V" << MARSVER << "                      " << endl;
+    gLog << "              Magic Online Analysis               " << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+void Remove(TMethod *m, const char *name)
+{
+    if (TString(m->GetName()).BeginsWith(name))
+        m->SetMenuItem(kMenuNoMenu);
+}
+
+void ChangeContextMenus()
+{
+    TList l;
+    MHCamera::Class()->GetMenuItems(&l);
+    TIter Next(&l);
+    TMethod *m=NULL;
+    while ((m=(TMethod*)Next()))
+    {
+        Remove(m, "DrawClone");
+        Remove(m, "SetName");
+        Remove(m, "Delete");
+        Remove(m, "DrawClass");
+        Remove(m, "Dump");
+        Remove(m, "Inspect");
+        Remove(m, "Smooth");
+        Remove(m, "Fit");
+        Remove(m, "Divide");
+        Remove(m, "Add");
+        Remove(m, "Multiply");
+        Remove(m, "Delete");
+        Remove(m, "SetLineAttributes");
+        Remove(m, "SetFillAttributes");
+        Remove(m, "SetMarkerAttributes");
+        Remove(m, "SetDrawOption");
+    }
+}
+
+#include "MPedPhotCam.h"
+Bool_t Loop(MOnlineDisplay *display, Int_t port)
+{
+    display->Reset();
+
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    MRawSocketRead reader;
+    reader.SetPort(port);
+
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MParList plist;
+
+    MTaskList tasks;
+    plist.AddToList(&tasks);
+    tasks.AddToList(&reader);
+
+    MPedPhotCam pcam;
+    plist.AddToList(&pcam);
+
+    MGeomApply geomapl;
+    MCerPhotAnal2 ncalc;
+    tasks.AddToList(&geomapl);
+    tasks.AddToList(&ncalc);
+
+    MEventRateCalc tcalc;
+    tcalc.SetNumEvents(100);
+    tasks.AddToList(&tcalc);
+
+    MFillH fill1("MHEvent",    "MCerPhotEvt", "MFillEvent");
+    MFillH fill2("MHCamEvent", "MCerPhotEvt", "MFillCamEvent");
+
+    MFRealTimePeriod filter;
+    fill1.SetFilter(&filter);
+
+    MHTriggerLvl0 trigmap(128, "Above 128");
+    MFillH fill3(&trigmap, "MRawEvtData", "MFillTriggerLvl0");
+
+    tasks.AddToList(&filter);
+
+    tasks.AddToList(&fill1);
+    tasks.AddToList(&fill2);
+    tasks.AddToList(&fill3);
+
+    MHCamEvent hist("PedestalRms");
+    hist.SetType(1);
+    plist.AddToList(&hist);
+
+    // -------------------------------------------
+
+    MHCamEvent maxhi("MaxIdxHi", "Index of slice with maximum content (hi-gain)");
+    MHCamEvent maxlo("MaxIdxLo", "Index of slice with maximum content (lo-gain)");
+    maxhi.SetType(3);
+    maxlo.SetType(4);
+    plist.AddToList(&maxhi);
+    plist.AddToList(&maxlo);
+
+    // -------------------------------------------
+
+    MFillH hfilla("MaxIdxHi", "MRawEvtData", "FillMaxIdxHi");
+    MFillH hfillb("MaxIdxLo", "MRawEvtData", "FillMaxIdxLo");
+    MFillH hfillc("Pedestals [MHCamEvent]", "MPedPhotCam", "FillPedestal");
+    MFillH hfilld("PedestalRms", "MPedPhotCam", "FillPedestalRms");
+    tasks.AddToList(&hfilla);
+    tasks.AddToList(&hfillb);
+    tasks.AddToList(&hfillc);
+    tasks.AddToList(&hfilld);
+
+    MOnlineDump dump;
+    dump.SetFilter(&filter);
+    display->SetTask(&dump);
+    tasks.AddToList(&dump);
+
+
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+    MFillH hfill3("MHHillas",   "MHillas",    "MFillHillas");
+    MFillH hfill4("MHHillasSrc","MHillasSrc", "MFillHillasSrc");
+    tasks.AddToList(&clean);
+    tasks.AddToList(&hcalc);
+    tasks.AddToList(&scalc);
+    tasks.AddToList(&hfill3);
+    tasks.AddToList(&hfill4);
+
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    magic.SetDisplay(display);
+    magic.SetProgressBar((TGProgressBar*)NULL);
+
+    if (!magic.Eventloop())
+    {
+        gLog << err << "Mona Eventloop error..." << endl;
+        return kFALSE;
+    }
+
+    tasks.PrintStatistics();
+    return kTRUE;
+}
+
+//
+// By defining the function return type 'void' instead of
+// 'void*' we tell TThread to create a detached thread,
+// but calling Exit() in a detached thread results in a crash
+// when the TGApplication is terminated.
+//
+void *thread(void *ptr)
+{
+    const Int_t port = *((Int_t**)ptr)[0];
+    MOnlineDisplay &d = *((MOnlineDisplay**)ptr)[1];
+
+    //
+    // If a loop is stopped reinitialize a new loop until the
+    // user requested to exit the program.
+    //
+    while (d.CheckStatus()!=MStatusDisplay::kFileExit)
+        Loop(&d, port);
+
+
+    gLog << dbg << "Loop stopped... exit thread()" << endl;
+
+    return 0;
+}
+
+/*
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+#include <TRootGuiFactory.h>
+#include <TPluginManager.h>
+void InitGuiFactory()
+{
+   if (gROOT->IsBatch())
+       gROOT->SetBatch(kFALSE);
+
+    //
+    // Must be loaded by hand, because it is not loaded by TGApplication.
+    // We could also use TApplication instead, but TApplication doesn't
+    // deal with the DISPLAY variable in a convient way.
+    //
+    TPluginHandler *h;
+    if ((h = gROOT->GetPluginManager()->FindHandler("TGuiFactory", "root")))
+    {
+        if (h->LoadPlugin() == -1)
+            return;
+        gGuiFactory = (TGuiFactory*)h->ExecPlugin(0);
+    }
+}
+#endif
+*/
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   mona [-?] [-h] [-a0] [-h] [-pn] [-vn]" << endl << endl;
+    gLog << "     -a0: Do not use Ansii codes." << endl;
+    gLog << "     -pn: TCP/IP port n [default=7000]" << endl;
+    gLog << "     -vn: Verbosity level n [default=2]" << endl << endl;
+    gLog << "     -?/-h: This help" << endl << endl;
+}
+
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    if (arg.HasOption("-?") || arg.HasOption("-h"))
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Set verbosity to highest level.
+    //
+    gLog.SetDebugLevel(arg.HasOption("-v") ? arg.GetIntAndRemove("-v") : 2);
+
+    if (arg.HasOption("-a") && arg.GetIntAndRemove("-a")==0)
+        gLog.SetNoColors();
+
+    const Int_t port = arg.HasOption("-p") ? arg.GetIntAndRemove("-p") : 7000;
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()>0)
+    {
+        Usage();
+        return -1;
+    }
+
+    TApplication app("Mona", &argc, argv);
+    if (gROOT->IsBatch() || !gClient)
+    {
+        gLog << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    /*
+    TGApplication app("Mona", &argc, argv);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+    InitGuiFactory();
+#endif
+    */
+
+    ChangeContextMenus();
+
+    //
+    // Starting MStatusDisplay in the thread results in hangs
+    // if the thread is terminated (by return)
+    //
+    gLog << dbg << "Starting Display..." << flush;
+    MOnlineDisplay d;
+    d.SetWindowName("Magic ONline Analysis");
+    d.SetIconName("Mona");
+
+    d.SetBit(MStatusDisplay::kExitLoopOnExit);
+    gLog << "done." << endl;
+
+    // gDebug=1;
+
+    gLog << dbg << "Starting Thread..." << flush;
+    const void *ptr[2] = { &port, &d };
+    TThread t(thread, ptr);
+    t.Run();
+    gLog << "done." << endl;
+
+    gLog << dbg << "Starting System loop... " << endl;
+    app.Run(kTRUE);
+    gLog << dbg << "System loop stopped." << endl;
+
+    d.UnmapWindow();
+
+    gLog << dbg << "Waiting for termination of thread... (be patient)" << endl;
+    while (t.GetState()!=TThread::kCanceledState)
+        gSystem->ProcessEvents();
+
+    gLog << dbg << "Thread terminated... joining." << endl;
+
+    TThread::Join(t.GetId()); //- seems that it is implicitly done... why?
+
+    gLog << dbg << "Exit MONA." << endl;
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MExtractPedestal.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MExtractPedestal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MExtractPedestal.cc	(revision 17960)
@@ -0,0 +1,1088 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!   Author(s): Thomas Bretz 01/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+// 
+//   MExtractPedestal
+//
+//  Pedestal Extractor base class
+//
+//  Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MGeomCam
+//   MPedestalCam
+//
+//  Output Containers:
+//   MPedestalCam
+//
+//  This class should be used for pedestal extractors with the following facilities:
+//  a) Standardized calculation of AB-noise, mean pedestals and RMS
+//  b) Standardized treatment of area- and sector averaged pedestals values
+//  c) Possibility to use a signal extractor to be applied on the pedestals
+//  d) Possibility to handle two MPedestalCams: one for the signal extractor and 
+//     a second to be filled during the pedestal calculating process.  
+//
+//  ad a): Every calculated value is referred to one FADC slice (e.g. Mean pedestal per slice),
+//         RMS per slice. 
+//         MExtractPedestal applies the following formula (1):
+// 
+//         Pedestal per slice = sum(x_i) / n / slices
+//         PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices )
+//         AB-Offset per slice = (sumAB0 - sumAB1) / n / slices 
+//
+//         where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//         events. "n" is the number of events, "slices" is the number of summed FADC samples.
+// 
+//         Note that the slice-to-slice fluctuations are not Gaussian, but Poissonian, thus 
+//         asymmetric and they are correlated.
+// 
+//         It is important to know that the Pedestal per slice and PedRMS per slice depend 
+//         on the number of used FADC slices, as seen in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyInner.gif">
+*/
+//End_Html
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyOuter.gif">
+*/
+//End_Html
+//
+//        The plots show the inner and outer pixels, respectivly and have the following meaning:
+// 
+//        1) The calculated mean pedestal per slice (from MPedCalcPedRun)
+//        2) The fitted mean pedestal per slice     (from MHPedestalCam)
+//        3) The calculated pedestal RMS per slice  (from MPedCalcPedRun)
+//        4) The fitted sigma of the pedestal distribution per slice
+//                                                  (from MHPedestalCam)
+//        5) The relative difference between calculation and histogram fit
+//           for the mean
+//        6) The relative difference between calculation and histogram fit
+//           for the sigma or RMS, respectively.
+// 
+//        The calculated means do not change significantly except for the case of 2 slices, 
+//        however the RMS changes from 5.7 per slice in the case of 2 extracted slices 
+//        to 8.3 per slice in the case of 26 extracted slices. This change is very significant.
+// 
+// ad b)  Every calculated value is referred to one FADC slice and one (averaged) pixel,
+//        (e.g. Mean Pedestal per area index per slice per pixel, etc. )
+//
+//         MExtractPedestal applies the following formula (2):
+// 
+//         Averaged Pedestal per slice = sum(x_i) / n / slices / n_pix
+//         PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices / n_pix )
+//         AB-Offset per slice = (sumAB0 - sumAB1) / n / slices / n_pix
+//
+//         where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//         events and all concerned pixels. 
+//         "n" is the number of events, "slices" is the number of summed FADC samples and
+//         "n_pix" is the number of pixels belonging to the specific area index or camera sector. 
+// 
+//         Calculating these averaged event-by-event values is very important to trace coherent
+//         fluctuations. An example is given in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalOscillations.gif">
+*/
+//End_Html
+//
+//        The plots show the extracted pedestals of the inner pixels (obtained
+//        with MHPedestalCam), averaged on an event-by-event basis from 
+//        run 13428 with switched off camera LV. 
+//        The meaning of the four plots is:
+// 
+//        1) The distribution of the averaged pedestals
+//        2) The averaged pedestals vs. time. 
+//           One can see clearly the oscillation pattern
+//        3) The fourier transform of the averaged pedestals vs. time. 
+//           One can see clearly a peak at a certain frequency
+//        4) The projection of the fourier components with the non-exponential
+//           (and therefore significant) outlier.
+//
+//    ad c) Many signal extractors, especially those using a sliding window
+//          have biases and their resolutions for zero-signals do not agree 
+//          with the pedestal RMS. For the F-Factor method in the calibration
+//          and the image cleaning, however, both have to be known and measured. 
+//          
+//          For this reason, a signal extractor can be handed over to the 
+//          pedestal extractor and applied on the pedestal events with the 
+//          function SetExtractor(). 
+//          The results will get stored in an MPedestalCam. 
+//        
+//          Note that only extractors deriving from MExtractTimeAndCharge
+//          can be used.
+//
+//   ad d)  The signal extractors themselves need a pedestal to be subtracted 
+//          from the FADC slices. 
+//          If the user wishes that the pededestals do not get overwritten by 
+//          the results from the signal extractor, a different named MPedestalCam
+//          can be created with the function: SetNamePedestalOut(). 
+//
+//  See also: MPedestalCam, MPedestalPix, MPedCalcPedRun, MPedCalcFromLoGain
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractPedestal.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"  
+#include "MRawEvtHeader.h"  
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MGeom.h"
+#include "MGeomCam.h"
+
+#include "MExtractTimeAndCharge.h"
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MExtractPedestal);
+
+using namespace std;
+
+const TString  MExtractPedestal::fgNamePedestalCam = "MPedestalCam";
+const TString  MExtractPedestal::fgNameRawEvtData  = "MRawEvtData";
+
+const UShort_t MExtractPedestal::fgCheckWinFirst   =   0;
+const UShort_t MExtractPedestal::fgCheckWinLast    =  29;
+const UShort_t MExtractPedestal::fgMaxSignalVar    =  40;
+const UShort_t MExtractPedestal::fgMaxSignalAbs    = 250;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor: 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Calls: 
+// - Clear()
+//
+MExtractPedestal::MExtractPedestal(const char *name, const char *title)
+    : fGeom(NULL), fPedestalsInter(NULL),
+    fPedestalsOut(NULL), fExtractor(NULL), fSignal(0),
+    fExtractWinFirst(0), fExtractWinSize(0), fUseSpecialPixels(kFALSE),
+    fCounter(0)
+{
+    fName  = name  ? name  : "MExtractPedestal";
+    fTitle = title ? title : "Base class to calculate pedestals";
+
+    SetIntermediateStorage( kFALSE );
+    SetRandomCalculation  ( kTRUE  );
+
+    SetNamePedestalCamOut();
+    SetNamePedestalCamInter();
+    SetNameRawEvtData();
+
+    SetCheckRange(fgCheckWinFirst, fgCheckWinLast);
+    SetMaxSignalVar(fgMaxSignalVar);
+    SetMaxSignalAbs(fgMaxSignalAbs);
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Call reset() of all Arays
+//
+void MExtractPedestal::ResetArrays()
+{
+    // Reset contents of arrays.
+    fSumx.Reset();
+    fSumx2.Reset();
+    fSumAB0.Reset();
+    fSumAB1.Reset();
+    fAreaSumx.Reset();
+    fAreaSumx2.Reset();
+    fAreaSumAB0.Reset();
+    fAreaSumAB1.Reset();
+    fAreaFilled.Reset();
+    fAreaValid.Reset();
+    fSectorSumx.Reset();
+    fSectorSumx2.Reset();
+    fSectorSumAB0.Reset();
+    fSectorSumAB1.Reset();
+    fSectorFilled.Reset();
+    fSectorValid.Reset();
+    fNumEventsUsed.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Resets Arrays:
+//
+// Sets:
+// - fRawEvt to NULL
+// - fRunHeader to NULL
+//
+void MExtractPedestal::Clear(const Option_t *o)
+{
+ 
+  fRawEvt       = NULL;
+  fRunHeader    = NULL;
+
+  // If the size is yet set, set the size
+  if (fSumx.GetSize()>0)
+    ResetArrays();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd
+// 
+Bool_t MExtractPedestal::SetExtractWindow(UShort_t windowf, UShort_t windows)
+{
+    Bool_t rc = kTRUE;
+
+    if (windows==0)
+    {
+        *fLog << warn << GetDescriptor();
+        *fLog << " - WARNING: Window size in SetExtractWindow has to be > 0... adjusting to 2!" << endl;
+        windows = 2;
+        rc = kFALSE;
+    }
+
+    fExtractWinSize  = windows;
+    fExtractWinFirst = windowf;
+    fExtractWinLast  = fExtractWinFirst+fExtractWinSize-1;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetCheckRange: 
+// 
+// Exits, if the first argument is smaller than 0
+// Exits, if the the last argument is smaller than the first
+//
+Bool_t MExtractPedestal::SetCheckRange(UShort_t chfirst, UShort_t chlast)
+{
+
+  Bool_t rc = kTRUE;
+  
+  if (chlast<=chfirst)
+    {
+      *fLog << warn << GetDescriptor();
+      *fLog << " - WARNING: Last slice in SetCheckRange smaller than first slice... set to first+2" << endl;
+      chlast = chfirst+1;
+      rc = kFALSE;
+    }
+
+  fCheckWinFirst = chfirst;
+  fCheckWinLast  = chlast;
+
+  return rc;
+}
+
+Bool_t MExtractPedestal::SetRangeFromExtractor(const MExtractor &ext, Bool_t logain)
+{
+    const Bool_t haslogains = ext.GetLoGainFirst()!=0 && ext.GetLoGainLast()!=0;
+
+    Bool_t rc1 = kTRUE;
+    if (!haslogains)
+    {
+        // We assume that in case without lo-gains we
+        // deal with pedestal events only
+        rc1 = SetCheckRange(ext.GetHiGainFirst(), ext.GetHiGainLast());
+    }
+
+    const Int_t f = logain && haslogains ? ext.GetLoGainFirst() : ext.GetHiGainFirst();
+    const Int_t l = logain && haslogains ? ext.GetLoGainLast()  : ext.GetHiGainLast();
+
+    const Int_t w = (l-f+1);
+
+    // Setup to use the hi-gain extraction window in the lo-gain
+    // range (the start of the lo-gain range is added automatically
+    // by MPedCalcFromLoGain)
+    const Bool_t rc2 = SetExtractWindow(f, w);
+
+    return rc1 && rc2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check (and if neccesary: correct) the extraction and check ranges.
+//
+void MExtractPedestal::CheckExtractionWindow(UInt_t offset)
+{
+    *fLog << inf;
+    *fLog << "Requested CheckWindow is [" << fCheckWinFirst << "," << fCheckWinLast << "]." <<endl;
+    *fLog << "Requested ExtractWindow is [" << fExtractWinFirst+offset << "," << fExtractWinLast+offset << "]." <<endl;
+
+    // fSignal->GetNumSamples() not yet initialized!!!
+    const UInt_t num = fRunHeader->GetNumSamplesHiGain()+fRunHeader->GetNumSamplesLoGain();
+
+    // Check upper bound for check window
+    if (fCheckWinLast >= num)
+    {
+        *fLog << inf << "CheckWindow [" << fCheckWinFirst << "," << fCheckWinLast;
+        *fLog << "] out of range [0," << num-1 << "]... ";
+        *fLog << "reset upper edge to " << num-1 << "." << endl;
+
+        fCheckWinLast = num-1;
+    }
+
+    // Now check lower bound for check window
+    if (fCheckWinFirst>fCheckWinLast)
+    {
+        *fLog << err << "CheckWindow first slice " << fCheckWinFirst;
+        *fLog << " greater than last slice " << fCheckWinLast;
+        *fLog << "... reset to 0." << endl;
+
+        fCheckWinFirst = 0;
+    }
+
+    // check upper bound for extaction window
+    if (fExtractWinLast+offset >= num)
+    {
+        *fLog << inf << "ExtractWindow [" << fExtractWinFirst+offset << "," << fExtractWinLast+offset;
+        *fLog << "] out of range [0," << num-1 << "]... ";
+        *fLog << "reset upper edge to " << num-1 << "." << endl;
+
+        fExtractWinLast = num-offset-1;
+    }
+
+    // Now check lower bound for check window
+    if (fExtractWinFirst>fExtractWinLast)
+    {
+        *fLog << err << "ExtractWindow first slice " << fExtractWinFirst+offset;
+        *fLog << " greater than last slice " << fExtractWinLast+offset;
+        *fLog << "... reset to 0." << endl;
+
+        fExtractWinFirst = 0;
+    }
+
+    // Calculate window size for extraction window
+    fExtractWinSize = fExtractWinLast-fExtractWinFirst+1;
+
+    // Check if use tries to do a fundamental pedestal extraction
+    // with an odd number of slices
+    if (fExtractor || TMath::Even(fExtractWinSize))
+        return;
+
+    // Make sure the number of extracted slices is even
+    fExtractWinLast += offset+fExtractWinLast==num-1 ? -1 : +1;
+
+    *fLog << inf << "ExtractionWindow odd... set to [";
+    *fLog << fExtractWinFirst+offset << "," << fExtractWinLast+offset << "]" << endl;
+
+    fExtractWinSize = fExtractWinLast-fExtractWinFirst+1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Look for the following input containers:
+//
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MRawEvtHeader
+//  - MGeomCam
+// 
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedestalCam with the name fPedContainerName
+//
+Int_t MExtractPedestal::PreProcess(MParList *pList)
+{
+
+  Clear();
+
+  fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber(fNameRawEvtData));
+  if (!fRawEvt)
+  {
+      *fLog << err << AddSerialNumber(fNameRawEvtData) << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+  if (!fRunHeader)
+  {
+      *fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+  
+  fGeom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+  if (!fGeom)
+  {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fSignal = (MPedestalSubtractedEvt*)pList->FindObject(AddSerialNumber("MPedestalSubtractedEvt"));
+  if (!fSignal)
+  {
+      *fLog << err << AddSerialNumber("MPedestalSubtractedEvt") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  if (!fPedestalsInter && fIntermediateStorage)
+  {
+      fPedestalsInter = (MPedestalCam*)pList->FindCreateObj("MPedestalCam", AddSerialNumber(fNamePedestalCamInter));
+      if (!fPedestalsInter)
+          return kFALSE;
+  }
+
+  if (!fPedestalsOut)
+  {
+      fPedestalsOut = (MPedestalCam*)pList->FindCreateObj("MPedestalCam", AddSerialNumber(fNamePedestalCamOut));
+      if (!fPedestalsOut)
+          return kFALSE;
+  }
+
+  fCounter = 0;
+
+  return fExtractor ? fExtractor->CallPreProcess(pList) : kTRUE;
+}
+
+//-----------------------------------------------------------------------
+//
+// Call Calc(). If fExtractor!=NULL enclose the call in setting the
+// NoiseCalculation to fRandomCalculation
+//
+Int_t MExtractPedestal::Process()
+{
+    //
+    // Necessary check for extraction of special pixels
+    // together with data which does not yet have them
+    //
+    if (fSumx.GetSize()==0)
+        return kTRUE;
+
+    if (fExtractor)
+        fExtractor->SetNoiseCalculation(fRandomCalculation);
+
+    Calc();
+
+    if (fExtractor)
+        fExtractor->SetNoiseCalculation(kFALSE);
+
+    fPedestalsOut->SetNumEvents(fCounter);
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Sets the size (from MPedestalCam::GetSize() ) and resets the following arrays:
+//  - fSumx
+//  - fSumx2
+//  - fSumAB0
+//  - fSumAB1
+//  - fAreaSumx
+//  - fAreaSumx2
+//  - fAreaSumAB0
+//  - fAreaSumAB1
+//  - fAreaFilled
+//  - fAreaValid 
+//  - fSectorSumx 
+//  - fSectorSumx2
+//  - fSectorSumAB0
+//  - fSectorSumAB1
+//  - fSectorFilled
+//  - fSectorValid
+//
+Bool_t MExtractPedestal::ReInit(MParList *pList)
+{
+    // Necessary check for special pixels which might not yet have existed
+    if (!fRawEvt)
+    {
+        if (fRunHeader->GetFormatVersion() > 3)
+            return kTRUE;
+
+        *fLog << err << "ERROR - " << fNameRawEvtData << " [MRawEvtData] has not ";
+        *fLog << "been found and format version > 3... abort." << endl;
+        return kFALSE;
+    }
+
+    // If the size is not yet set, set the size
+    if (fSumx.GetSize()==0)
+    {
+        // Initialize the normal pixels (size of MPedestalCam already set by MGeomApply)
+        const Int_t npixels  = fPedestalsOut->GetSize();
+
+        fSumx.  Set(npixels);
+        fSumx2. Set(npixels);
+        fSumAB0.Set(npixels);
+        fSumAB1.Set(npixels);
+
+        fNumEventsUsed.Set(npixels);
+
+        if (fUseSpecialPixels)
+        {
+            // Initialize size of MPedestalCam in case of special pixels (not done by MGeomApply)
+            const UShort_t nspecial = fRunHeader->GetNumSpecialPixels();
+            if (nspecial == 0)
+            {
+                *fLog << warn << "WARNING - Number of special pixels is 0." << endl;
+                return kTRUE;
+            }
+
+            fPedestalsOut->InitSize((UInt_t)nspecial);
+        }
+        else
+        {
+            // Initialize the averaged areas and sectors (do not exist for special pixels)
+            const Int_t areas    = fPedestalsOut->GetNumAverageArea();
+            const Int_t sectors  = fPedestalsOut->GetNumAverageSector();
+
+            fAreaSumx.  Set(areas);
+            fAreaSumx2. Set(areas);
+            fAreaSumAB0.Set(areas);
+            fAreaSumAB1.Set(areas);
+            fAreaFilled.Set(areas);
+            fAreaValid .Set(areas);
+
+            fSectorSumx.  Set(sectors);
+            fSectorSumx2. Set(sectors);
+            fSectorSumAB0.Set(sectors);
+            fSectorSumAB1.Set(sectors);
+            fSectorFilled.Set(sectors);
+            fSectorValid .Set(sectors);
+
+            for (Int_t i=0; i<npixels; i++)
+            {
+                const UInt_t aidx   = (*fGeom)[i].GetAidx();
+                const UInt_t sector = (*fGeom)[i].GetSector();
+
+                fAreaValid  [aidx]  ++;
+                fSectorValid[sector]++;
+            }
+        }
+    }
+
+    if (fExtractor)
+    {
+        *fLog << all << fExtractor->ClassName() << "... " << flush;
+        if (!fExtractor->ReInit(pList))
+            return kFALSE;
+
+        SetRangeFromExtractor(*fExtractor);
+
+        // fSignal->GetNumSamples() not yet initialized!!!
+        const UInt_t num = fRunHeader->GetNumSamples();
+        if (fExtractWinLast >= num)
+        {
+            *fLog << err;
+            *fLog << "ERROR - Selected fExtractWinLast " << fExtractWinLast;
+            *fLog << " out of range (>=" << num<< ")." << endl;
+            return kFALSE;
+        }
+    }
+    else
+        if (fRunHeader->GetNumSamplesLoGain()==0 && (fCheckWinFirst!=0 || fCheckWinLast!=0))
+        {
+            *fLog << inf << "Data has no lo-gains... resetting check window to extraction window." << endl;
+            SetCheckRange(fExtractWinFirst, fExtractWinLast);
+        }
+
+    //CheckExtractionWindow();
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// PostProcess the extractor if available
+//
+Int_t MExtractPedestal::PostProcess()
+{
+    return fExtractor ? fExtractor->CallPostProcess() : kTRUE;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Check whether the signal variation between fCheckWinFirst and fCheckWinLast
+// exceeds fMaxSignalVar or the signal is greater than fMaxSignalAbs
+//
+Bool_t MExtractPedestal::CheckVariation(UInt_t idx) const
+{
+    // This is the fast workaround to put hi- and lo-gains together
+    USample_t *slices = fSignal->GetSamplesRaw(idx);
+
+    // Start 'real' work
+    USample_t max = 0;
+    USample_t min = (USample_t)-1;
+
+    // Find the maximum and minimum signal per slice in the high gain window
+    for (USample_t *slice=slices+fCheckWinFirst; slice<=slices+fCheckWinLast; slice++)
+    {
+        if (*slice > max)
+            max = *slice;
+        if (*slice < min)
+            min = *slice;
+    }
+
+    max /= fRunHeader->GetScale();
+    min /= fRunHeader->GetScale();
+
+    // If the maximum in the high gain window is smaller than
+    return max-min<fMaxSignalVar && max<fMaxSignalAbs;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Invoke the hi-gain extraction starting at fExtractWinFirst+offset
+// for fExtractWinLast-fExtractWinFirst+1 slices. If Noise calculation
+// is set it is up to the signal extractor to do the right thing.
+//
+// Returns the extracted signal.
+//
+Float_t MExtractPedestal::CalcExtractor(const MRawEvtPixelIter &pixel, Int_t offset) const
+{
+    // Use the same extraction window as for signal extraction
+    const Int_t first = fExtractWinFirst;
+    const Int_t last  = fExtractWinLast;
+
+    const Int_t start = first+offset;
+
+    const Int_t range = last-first+1;
+
+    // This check is already done in CheckExtractionWindow
+    //    if (range>pixel.GetNumSamples()-start)
+    //        range = pixel.GetNumSamples()-start;
+
+    const Int_t idx = pixel.GetPixelId();
+
+    // Do some handling if maxpos is last slice?
+    const Int_t maxposhi = fRandomCalculation ? 0 : fSignal->GetMaxPos(idx, start, start+range-1);
+
+    const Float_t *sig = fSignal->GetSamples(idx);
+
+    // The pedestal is extracted with the hi-gain extractor (eg. digital
+    // filter weights) but from the lo-gains
+    Float_t dummy[3];
+    Float_t sum = 0;
+    fExtractor->FindTimeAndChargeHiGain2(sig+start, range, sum,
+                                         dummy[0], dummy[1], dummy[2],
+                                         0, maxposhi);
+
+    return sum;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Sum slices from fExtractWinFirst to fExtractWinLast. The total sum is
+// returned. ab0 and ab1 will contain the total sum splitted by the
+// AB-flag. If the AB-flag is invalid ab0=ab1=0 is returned.
+//
+UInt_t MExtractPedestal::CalcSums(const MRawEvtPixelIter &pixel, Int_t offset, UInt_t &ab0, UInt_t &ab1) const
+{
+    const Int_t first = fExtractWinFirst+offset;
+
+    USample_t *ptr = fSignal->GetSamplesRaw(pixel.GetPixelId())+first;
+    USample_t *end = ptr + fExtractWinSize;
+
+    Int_t abflag = pixel.HasABFlag() + first;
+
+    UInt_t ab[2] = { 0, 0 };
+    while (ptr<end)
+        ab[abflag++ & 0x1] += *ptr++;
+
+    // This check if for old data without AB-Flag in the data
+    const Bool_t valid = pixel.IsABFlagValid();
+
+    ab0 = valid ? ab[0] : 0;
+    ab1 = valid ? ab[1] : 0;
+
+    return ab[0]+ab[1];
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Check for the variation of the pixel. Return kFALSE if this pixel
+// should not be used.
+// Calculate the pedestal either with the extractor or by summing slices.
+// And update all arrays.
+//
+Bool_t MExtractPedestal::CalcPixel(const MRawEvtPixelIter &pixel, Int_t offset, UInt_t usespecialpixels)
+{
+    const UInt_t idx = pixel.GetPixelId();
+    if (!CheckVariation(idx))
+        return kFALSE;
+
+    //extract pedestal
+    UInt_t ab[2];
+    const Float_t sum = fExtractor ?
+        CalcExtractor(pixel, offset) :
+        CalcSums(pixel, offset, ab[0], ab[1]);
+
+    if (fIntermediateStorage)
+        (*fPedestalsInter)[idx].Set(sum, 0, 0, fNumEventsUsed[idx]);
+
+    const Double_t sqrsum = sum*sum;
+
+    fSumx[idx]  += sum;
+    fSumx2[idx] += sqrsum;
+
+    fNumEventsUsed[idx]++;
+
+    if (!fExtractor && pixel.IsABFlagValid())
+    {
+        fSumAB0[idx] += ab[0];
+        fSumAB1[idx] += ab[1];
+    }
+
+    if (usespecialpixels)
+        return kTRUE;
+
+    const UInt_t aidx   = (*fGeom)[idx].GetAidx();
+    const UInt_t sector = (*fGeom)[idx].GetSector();
+
+    fAreaFilled[aidx]++;
+    fSectorFilled[sector]++;
+
+    fAreaSumx[aidx]      += sum;
+    fAreaSumx2[aidx]     += sqrsum;
+    fSectorSumx[sector]  += sum;
+    fSectorSumx2[sector] += sqrsum;
+
+    if (!fExtractor && pixel.IsABFlagValid())
+    {
+        fAreaSumAB0[aidx]   += ab[0];
+        fAreaSumAB1[aidx]   += ab[1];
+        fSectorSumAB0[aidx] += ab[0];
+        fSectorSumAB1[aidx] += ab[1];
+    }
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Calculates for pixel "idx":
+//
+// Ped per slice      = sum / n / fExtractWinSize;
+// RMS per slice      = sqrt { (sum2 -  sum*sum/n) / (n-1) / fExtractWinSize }
+// ABOffset per slice = (fSumAB0[idx] - fSumAB1[idx]) / n / fExtractWinSize;
+//
+// Stores the results in MPedestalCam[pixid]
+//
+void MExtractPedestal::CalcPixResults(const UInt_t pixid)
+{
+    const UInt_t  nevts = fNumEventsUsed[pixid];
+    if (nevts<2)
+        return;
+
+    const Double_t sum  = fSumx[pixid];
+    const Double_t sum2 = fSumx2[pixid];
+
+    // 1. Calculate the mean of the sums:
+    Double_t ped = sum/nevts;
+
+    // 2. Calculate the Variance of the sums:
+    Double_t var = (sum2-sum*sum/nevts)/(nevts-1.);
+
+    // 3. Calculate the amplitude of the 150MHz "AB" noise
+    Double_t abOffs = (fSumAB0[pixid] - fSumAB1[pixid]) / nevts;
+
+    // 4. Scale the mean, variance and AB-noise to the number of slices:
+    ped    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    // The pedestal extracted with the extractor is divided by
+    // the number of hi-gain samples because the calibration
+    // multiplies by this number
+
+    // scale to 256
+    const UInt_t scale = fExtractor ? 1 : fRunHeader->GetScale();
+
+    ped    /= scale;
+    abOffs /= scale;
+
+    // 5. Calculate the RMS from the Variance:
+    const Double_t rms = var<0 ? 0 : TMath::Sqrt(var)/scale;
+
+    // abOffs contains only half of the signal as ped.
+    // Therefor abOffs is not the full, but the half amplitude
+    (*fPedestalsOut)[pixid].Set(ped, rms, abOffs, nevts);
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Calculates for area idx "aidx" with "napix" valid pixels:
+//
+// Ped per slice      = sum / nevts / fExtractWinSize / napix;
+// RMS per slice      = sqrt { (sum2 -  sum*sum/nevts) / (nevts-1) / fExtractWinSize / napix }
+// ABOffset per slice = (fSumAB0[idx] - fSumAB1[idx]) / nevts / fExtractWinSize / napix;
+//
+// Stores the results in MPedestalCam::GetAverageArea(aidx)
+//
+void MExtractPedestal::CalcAreaResults(const UInt_t aidx)
+{
+    const UInt_t nevts = fAreaFilled[aidx];
+    if (nevts<2)
+        return;
+
+    const UInt_t napix = fAreaValid[aidx];
+    if (napix<1)
+        return;
+
+    const Double_t sum  = fAreaSumx[aidx];
+    const Double_t sum2 = fAreaSumx2[aidx];
+
+    // 1. Calculate the mean of the sums:
+    Double_t ped = sum/nevts;
+
+    // 2. Calculate the Variance of the sums:
+    Double_t var = (sum2/napix-sum*sum/nevts)/(nevts-1.);
+
+    // 3. Calculate the amplitude of the 150MHz "AB" noise
+    Double_t abOffs = (fAreaSumAB0[aidx] - fAreaSumAB1[aidx]) / nevts;
+
+    // 4. Scale the mean, variance and AB-noise to the number of slices:
+    ped    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    // The pedestal extracted with the extractor is divided by
+    // the number of hi-gain samples because the calibration
+    // multiplies by this number
+
+    // scale to 256
+    const UInt_t scale = fExtractor ? 1 : fRunHeader->GetScale();
+
+    // 5. Scale the mean, variance and AB-noise to the number of pixels:
+    ped    /= napix*scale;
+    abOffs /= napix*scale;
+
+    // 6. Calculate the RMS from the Variance:
+    const Double_t rms = var<0 ? 0 : TMath::Sqrt(var)/scale;
+
+    // abOffs contains only half of the signal as ped.
+    // Therefor abOffs is not the full, but the half amplitude
+    fPedestalsOut->GetAverageArea(aidx).Set(ped, rms, abOffs, nevts);
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Calculates for sector idx "sector" with "nspix" valid pixels:
+//
+// Ped per slice      = sum / nevts / fExtractWinSize / nspix;
+// RMS per slice      = sqrt { (sum2 -  sum*sum/nevts) / (nevts-1) / fExtractWinSize / nspix }
+// ABOffset per slice = (fSumAB0[idx] - fSumAB1[idx]) / nevts / fExtractWinSize / nspix;
+//
+// Stores the results in MPedestalCam::GetAverageSector(sector)
+//
+void MExtractPedestal::CalcSectorResults(const UInt_t sector)
+{
+    const UInt_t nevts = fSectorFilled[sector];
+    if (nevts<2)
+        return;
+
+    const UInt_t nspix = fSectorValid[sector];
+    if (nspix<1)
+        return;
+
+    const Double_t sum  = fSectorSumx[sector];
+    const Double_t sum2 = fSectorSumx2[sector];
+
+    // 1. Calculate the mean of the sums:
+    Double_t ped        = sum/nevts;
+
+    // 2. Calculate the Variance of the sums:
+    Double_t var = (sum2/nspix-sum*sum/nevts)/(nevts-1.);
+
+    // 3. Calculate the amplitude of the 150MHz "AB" noise
+    Double_t abOffs = (fSectorSumAB0[sector] - fSectorSumAB1[sector]) / nevts;
+
+    // 4. Scale the mean, variance and AB-noise to the number of slices:
+    ped    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    // The pedestal extracted with the extractor is divided by
+    // the number of hi-gain samples because the calibration
+    // multiplies by this number
+
+    // scale to 256
+    const UInt_t scale = fExtractor ? 1 : fRunHeader->GetScale();
+
+    // 5. Scale the mean, variance and AB-noise to the number of pixels:
+    ped    /= nspix*scale;
+    abOffs /= nspix*scale;
+
+    // 6. Calculate the RMS from the Variance:
+    const Double_t rms = var<0 ? 0 : TMath::Sqrt(var)/scale;
+
+    // abOffs contains only half of the signal as ped.
+    // Therefor abOffs is not the full, but the half amplitude
+    fPedestalsOut->GetAverageSector(sector).Set(ped, rms, abOffs, nevts);
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over the pixels to get the averaged pedestal
+//
+void MExtractPedestal::CalcPixResult()
+{
+    for (UInt_t idx=0; idx<fNumEventsUsed.GetSize(); idx++)
+        CalcPixResults(idx);
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over the sector indices to get the averaged pedestal per sector
+//
+void MExtractPedestal::CalcSectorResult()
+{
+    for (UInt_t sector=0; sector<fSectorFilled.GetSize(); sector++)
+        CalcSectorResults(sector);
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over the (two) area indices to get the averaged pedestal per aidx
+//
+void MExtractPedestal::CalcAreaResult()
+{
+    for (UInt_t aidx=0; aidx<fAreaFilled.GetSize(); aidx++)
+        CalcAreaResults(aidx);
+}
+
+//-----------------------------------------------------------------------
+//
+void MExtractPedestal::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << "Name of interm. MPedestalCam: " << (fPedestalsInter?fPedestalsInter->GetName():fNamePedestalCamInter.Data()) << " (" << fPedestalsInter << ")" << endl;
+    *fLog << "Name of output MPedestalCam:  " << (fPedestalsOut?fPedestalsOut->GetName():fNamePedestalCamOut.Data()) << " (" << fPedestalsOut << ")" << endl;
+    *fLog << "Intermediate Storage is       " << (fIntermediateStorage?"on":"off") << endl;
+    *fLog << "Special pixel mode            " << (fUseSpecialPixels?"on":"off") << endl;
+    if (fExtractor)
+    {
+        *fLog << "Extractor used:               " << fExtractor->ClassName() << " (";
+        *fLog << (fRandomCalculation?"":"non-") << "random)" << endl;
+    }
+    *fLog << "ExtractWindow from slice " << fExtractWinFirst << " to " << fExtractWinLast << " incl." << endl;
+    *fLog << "CheckWindow from slice " << fCheckWinFirst   << " to " << fCheckWinLast << " incl." << endl;
+    *fLog << "Max.allowed signal variation: " << fMaxSignalVar << endl;
+    *fLog << "Max.allowed signal absolute:  " << fMaxSignalAbs << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The following resources are available:
+//    ExtractWindowFirst:    15
+//    ExtractWindowSize:      6
+//    PedestalUpdate:       yes
+//    RandomCalculation:    yes
+//
+Int_t MExtractPedestal::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc=kFALSE;
+
+    // find resource for fUseSpecialPixels
+    if (IsEnvDefined(env, prefix, "UseSpecialPixels", print))
+    {
+        SetUseSpecialPixels(GetEnvValue(env, prefix, "UseSpecialPixels", fUseSpecialPixels));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "IntermediateStorage", print))
+    {
+        SetIntermediateStorage(GetEnvValue(env, prefix, "IntermediateStorage", fIntermediateStorage));
+        rc = kTRUE;
+    }
+
+    // find resource for random calculation
+    if (IsEnvDefined(env, prefix, "RandomCalculation", print))
+    {
+        SetRandomCalculation(GetEnvValue(env, prefix, "RandomCalculation", fRandomCalculation));
+        rc = kTRUE;
+    }
+
+    // Find resources for ExtractWindow
+    Int_t ef = fExtractWinFirst;
+    Int_t es = fExtractWinSize;
+    if (IsEnvDefined(env, prefix, "ExtractWinFirst", print))
+    {
+        ef = GetEnvValue(env, prefix, "ExtractWinFirst", ef);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ExtractWinSize", print))
+    {
+        es = GetEnvValue(env, prefix, "ExtractWinSize", es);
+        rc = kTRUE;
+    }
+
+    SetExtractWindow(ef,es);
+
+    // Find resources for CheckWindow
+    Int_t cfs = fCheckWinFirst;
+    Int_t cls = fCheckWinLast;
+    if (IsEnvDefined(env, prefix, "CheckWinFirst", print))
+    {
+        cfs = GetEnvValue(env, prefix, "CheckWinFirst", cfs);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "CheckWinLast", print))
+    {
+        cls = GetEnvValue(env, prefix, "CheckWinLast", cls);
+        rc = kTRUE;
+    }
+
+    SetCheckRange(cfs,cls);
+
+    // find resource for maximum signal variation
+    if (IsEnvDefined(env, prefix, "MaxSignalVar", print))
+    {
+        SetMaxSignalVar(GetEnvValue(env, prefix, "MaxSignalVar", fMaxSignalVar));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "MaxSignalAbs", print))
+    {
+        SetMaxSignalAbs(GetEnvValue(env, prefix, "MaxSignalAbs", fMaxSignalAbs));
+        rc = kTRUE;
+    }
+
+    // find resource for MPedestalCam
+    if (IsEnvDefined(env, prefix, "NamePedestalCamInter", print))
+    {
+        SetNamePedestalCamInter(GetEnvValue(env, prefix, "NamePedestalCamInter", fNamePedestalCamInter));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "NamePedestalCamOut", print))
+    {
+        SetNamePedestalCamOut(GetEnvValue(env, prefix, "NamePedestalCamOut", fNamePedestalCamOut));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MExtractPedestal.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MExtractPedestal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MExtractPedestal.h	(revision 17960)
@@ -0,0 +1,154 @@
+#ifndef MARS_MExtractPedestal
+#define MARS_MExtractPedestal
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include <MArrayD.h>
+#endif
+
+#ifndef MARS_MArrayI
+#include <MArrayI.h>
+#endif
+
+class MGeomCam;
+class MExtractor;
+class MPedestalCam;
+class MRawEvtData;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MExtractTimeAndCharge;
+class MPedestalSubtractedEvt;
+class MRawEvtPixelIter;
+
+typedef UShort_t USample_t;
+
+class MExtractPedestal : public MTask
+{
+private:
+  static const TString  fgNamePedestalCam;  //! "MPedestalCam"
+  static const TString  fgNameRawEvtData;   //! "MRawEvtData"
+
+  static const UShort_t fgCheckWinFirst;    //! First FADC slice to check for signal (currently set to: 0)
+  static const UShort_t fgCheckWinLast;     //! Last FADC slice to check for signal  (currently set to: 29)
+  static const UShort_t fgMaxSignalVar;     //! The maximum difference between the highest and lowest slice
+  static const UShort_t fgMaxSignalAbs;     //! The maximum absolte slice
+
+  TString fNamePedestalCamOut;       // Name of the outgoing 'MPedestalCam' container
+  TString fNamePedestalCamInter;     // Name of the intermediate 'MPedestalCam' container
+  TString fNameRawEvtData;           // Name of MRawEvtData
+
+  Bool_t  fRandomCalculation;        // Is pedestalextraction by extractor random?
+
+  // Helper functions
+  void CalcAreaResults(const UInt_t aidx);
+  void CalcSectorResults(const UInt_t sector);
+
+protected:
+
+  Bool_t  fIntermediateStorage;      // Is pedestal stored every event?
+
+  MGeomCam      *fGeom;              //! Camera geometry
+  MPedestalCam  *fPedestalsInter;    //! Pedestals of all pixels in the camera (intermediate)
+  MPedestalCam  *fPedestalsOut;      //! Pedestals of all pixels in the camera (outgoing)
+  MRawEvtData   *fRawEvt;            //! Raw event data (time slices)
+  MRawRunHeader *fRunHeader;         //! RunHeader information
+  MExtractTimeAndCharge *fExtractor; //  Possible Extractor
+  MPedestalSubtractedEvt *fSignal;   //!
+
+  UShort_t fExtractWinFirst;         // First FADC slice to extract pedestal from
+  UShort_t fExtractWinSize;          // Number of slices to calculate the pedestal from
+  UShort_t fExtractWinLast;          // Last FADC slice to extract pedestal from 
+
+  UShort_t fCheckWinFirst;
+  UShort_t fCheckWinLast;
+
+  UShort_t fMaxSignalVar;
+  UShort_t fMaxSignalAbs;
+
+  Bool_t  fUseSpecialPixels;         // Flag if the special pixels shall be treated
+
+  MArrayD fSumx;                     // sum of values
+  MArrayD fSumx2;                    // sum of squared values
+  MArrayD fSumAB0;                   // sum of ABFlag=0 slices
+  MArrayD fSumAB1;                   // sum of ABFlag=1 slices
+  MArrayD fAreaSumx;                 // averaged sum of values per area idx
+  MArrayD fAreaSumx2;                // averaged sum of squared values per area idx
+  MArrayD fAreaSumAB0;               // averaged sum of ABFlag=0 slices per area idx
+  MArrayD fAreaSumAB1;               // averaged sum of ABFlag=1 slices per area idx
+  MArrayI fAreaFilled;               // number of valid entries with area idx
+  MArrayI fAreaValid;                // number of valid pixels  within area idx
+  MArrayD fSectorSumx;               // averaged sum of values per sector
+  MArrayD fSectorSumx2;              // averaged sum of squared values per sector
+  MArrayD fSectorSumAB0;             // averaged sum of ABFlag=0 slices per sector
+  MArrayD fSectorSumAB1;             // averaged sum of ABFlag=1 slices per sector 
+  MArrayI fSectorFilled;             // number of valid entries with sector idx
+  MArrayI fSectorValid;              // number of valid pixels within sector idx
+
+  MArrayI fNumEventsUsed;            // Number of events used for pedestal calc for each pixel
+
+  UInt_t  fCounter;                  // Counter for events processed
+
+  // MTask virtual functions
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();
+  Bool_t ReInit(MParList *pList);
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+  // Interface to be overwritten by a new class
+  virtual void ResetArrays();
+  virtual void Calc() = 0;
+
+  // Helper functions
+  void CalcPixResults(const UInt_t pixid);
+
+  void CalcPixResult();
+  void CalcSectorResult();
+  void CalcAreaResult();
+
+  Bool_t  CalcPixel(const MRawEvtPixelIter &pixel, Int_t offset, UInt_t usespecialpixels=kFALSE);
+  Float_t CalcExtractor(const MRawEvtPixelIter &pixel, Int_t offset) const;
+  UInt_t  CalcSums(const MRawEvtPixelIter &pixel, Int_t offset, UInt_t &ab0, UInt_t &ab1) const;
+  Bool_t  CheckVariation(UInt_t idx) const;
+
+  void CheckExtractionWindow(UInt_t offset=0);
+
+  Bool_t SetRangeFromExtractor(const MExtractor &ext, Bool_t logain);
+
+public:
+  MExtractPedestal(const char *name=NULL, const char *title=NULL);
+
+  void Clear(const Option_t *o="");
+  void Print(const Option_t *o="") const;
+
+  // Setters
+  Bool_t SetExtractWindow(UShort_t first, UShort_t size);
+  Bool_t SetCheckRange(UShort_t checkfirst=fgCheckWinFirst, UShort_t checklast=fgCheckWinLast);
+
+  virtual Bool_t SetRangeFromExtractor(const MExtractor &ext) = 0;
+
+  void SetMaxSignalVar(UShort_t maxvar=40)   { fMaxSignalVar = maxvar; }
+  void SetMaxSignalAbs(UShort_t maxabs=250)  { fMaxSignalAbs = maxabs; }
+
+  // names
+  void SetNamePedestalCamInter(const char *name=fgNamePedestalCam) { fNamePedestalCamInter = name; }
+  void SetNamePedestalCamOut  (const char *name=fgNamePedestalCam) { fNamePedestalCamOut   = name; }
+  void SetNameRawEvtData      (const char *name=fgNameRawEvtData)  { fNameRawEvtData       = name; }
+
+  // pointers
+  void SetExtractor     ( MExtractTimeAndCharge *e) { fExtractor      = e; }
+  void SetPedestalsInter( MPedestalCam *pedcam    ) { fPedestalsInter = pedcam; }
+  void SetPedestalsOut  ( MPedestalCam *pedcam    ) { fPedestalsOut   = pedcam; }
+
+  // flags
+  void SetIntermediateStorage (Bool_t b=kTRUE) { fIntermediateStorage = b; }
+  void SetUseSpecialPixels    (Bool_t b=kTRUE) { fUseSpecialPixels    = b; }
+  void SetRandomCalculation   (Bool_t b=kTRUE) { fRandomCalculation   = b; }
+
+  ClassDef(MExtractPedestal, 0)   // Base class for pedestal extractors
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MHPedestalCor.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MHPedestalCor.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MHPedestalCor.cc	(revision 17960)
@@ -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): Thomas Bretz, 10/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPedestalCor
+//
+// A histogram to get the pedestal autocorrelation matrix. Tests have shown
+// the the autocorrelation does not depend on the actual slice so a profile
+// with the autocorrelation depeding on the distance between two slices
+// is filled.
+//
+// Functions to provide the autocorrelation as a TH2D or a TMatrix are
+// provided.
+//
+// Input:
+//  - MPedestalSubtractedEvt (from MFillH)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalCor.h"
+
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+
+#include "MGeomCam.h"
+
+#include "MBinning.h"
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MHPedestalCor);
+
+using namespace std;
+
+const TString MHPedestalCor::gsDefName  = "MHPedestalCor";
+const TString MHPedestalCor::gsDefTitle = "Histogram for autocorrelation";
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task. Set fType to 0
+//
+MHPedestalCor::MHPedestalCor(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+    /*
+    fHist.SetNameTitle("AutoCor", "Autocorrelation of slices");
+    fHist.SetDirectory(0);
+
+    fHist2.SetNameTitle("AutoCorProf", "Autocorrelation from Profile");
+    fHist2.SetDirectory(0);
+
+    fHist3.SetNameTitle("Dev", "Deviation of Profile from plain correlation");
+    fHist3.SetDirectory(0);
+
+    MBinning binsx(61, -30.5, 30.5);
+    MBinning binsy(30, -0.5, 29.5);
+
+    MH::SetBinning(&fHist,  &binsy, &binsy);
+    MH::SetBinning(&fHist2, &binsy, &binsy);
+    MH::SetBinning(&fHist3, &binsy, &binsy);
+    */
+    fProf.SetNameTitle("AutoCorP", "Profile of auto correlation");
+    fProf.SetDirectory(0);
+
+    const MBinning binsx(15, -0.5, 14.5);
+    MH::SetBinning(fProf, binsx);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCamEvent-Container.
+//
+Int_t MHPedestalCor::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MPedestalSubtractedEvt *evt = dynamic_cast<const MPedestalSubtractedEvt*>(par);
+    if (!evt)
+    {
+        *fLog << err << dbginf << "Got no MCamEvent as argument of Fill()..." << endl;
+        return kERROR;
+    }
+
+    // Implement an extraction range
+    // Implement a check as in PedCalcFromLoGain
+
+    const Int_t np = evt->GetNumPixels();
+    const Int_t ns = evt->GetNumSamples();
+
+    Int_t fCheckWinFirst = 0;
+    Int_t fCheckWinLast  = ns;
+
+    Int_t fExtractWinFirst = 17;
+    Int_t fExtractWinLast  = ns;
+
+    Float_t fMaxSignalVar =  40;
+    Float_t fMaxSignalAbs = 250;
+
+    for (int k=0; k<np; k++)
+    {
+        // This is the fast workaround to put hi- and lo-gains together
+        USample_t *slices = evt->GetSamplesRaw(k);//pixel.GetSamples();
+
+        USample_t max = 0;
+        USample_t min = (USample_t)-1;
+
+        // Find the maximum and minimum signal per slice in the high gain window
+        for (USample_t *slice=slices+fCheckWinFirst; slice<slices+fCheckWinLast; slice++)
+        {
+            if (*slice > max)
+                max = *slice;
+            if (*slice < min)
+                min = *slice;
+        }
+
+        // If the maximum in the high gain window is smaller than
+        if (max-min>=fMaxSignalVar || max>=fMaxSignalAbs)
+            continue;
+
+        const Float_t *sig = evt->GetSamples(k);
+
+        for (int i=fExtractWinFirst; i<fExtractWinLast; i++)
+        {
+            const Double_t s2 = sig[i]*sig[i];
+            //            fHist.Fill(i, i, s2);
+            fProf.Fill(0., s2);
+
+            for (int j=fExtractWinFirst; j<fExtractWinLast; j++)
+            {
+                const Double_t sij = sig[i]*sig[j];
+
+//                fHist.Fill(i, j, sij);
+//                fHist.Fill(j, i, sij);
+
+                fProf.Fill(i-j,  sij);
+//                fProf.Fill(j-i,  sij);
+            }
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the autocorrelation matrix as a TH2D
+//
+void MHPedestalCor::GetAutoCorrelation(TH2 &h) const
+{
+    const Int_t n = fProf.GetNbinsX()*2+1;
+
+    const Axis_t xmax = fProf.GetXaxis()->GetXmax();
+
+    const MBinning bins(n, -xmax, xmax);
+    MH::SetBinning(h, bins, bins);
+
+    for (int x=0; x<n; x++)
+        for (int y=0; y<n; y++)
+            h.SetBinContent(x+1, y+1, fProf.GetBinContent(TMath::Abs(x-y)));
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the autocorrelation into the TMatrix
+//
+void MHPedestalCor::GetAutoCorrelation(TMatrix &m) const
+{
+    const Int_t n = fProf.GetNbinsX()*2+1;
+    m.ResizeTo(n, n);
+
+    for (int x=0; x<n; x++)
+        for (int y=0; y<n; y++)
+            m[x][y] = fProf.GetBinContent(TMath::Abs(x-y));
+}
+
+/*
+void MHPedestalCor::Paint(Option_t *)
+{
+    MH::SetPalette("pretty");
+
+    for (int x=0; x<fHist.GetNbinsX(); x++)
+        for (int y=0; y<fHist.GetNbinsX(); y++)
+            fHist2.SetBinContent(x+1, y+1, fProf.GetBinContent(fProf.GetXaxis()->FindFixBin(x-y)));
+
+    fHist.Copy(fHist3);
+    fHist3.Add(&fHist2, -(fHist.GetEntries()/30/30));
+    fHist3.Divide(&fHist);
+    fHist3.Scale(100);
+    fHist3.SetMaximum();
+}
+*/
+
+void MHPedestalCor::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+    pad->SetFrameBorderMode(0);
+
+    //pad->Divide(2, 2, 0.001, 0.001);
+
+    AppendPad();
+/*
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHist.Draw("colz");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHist2.Draw("colz");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fHist3.Draw("colz");
+
+    pad->cd(4);*/
+
+    gPad->SetBorderMode(0);
+    gPad->SetFrameBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fProf.Draw();
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MHPedestalCor.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MHPedestalCor.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MHPedestalCor.h	(revision 17960)
@@ -0,0 +1,40 @@
+#ifndef MARS_MHPedestalCor
+#define MARS_MHPedestalCor
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+
+class MHPedestalCor : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    TProfile fProf;
+
+    Int_t Fill(const MParContainer *par, const Stat_t w=1);
+
+public:
+    MHPedestalCor(const char *name=NULL, const char *title=NULL);
+
+    void GetAutoCorrelation(TH2 &h) const;
+    void GetAutoCorrelation(TMatrix &m) const;
+    TMatrix GetAutoCorrelation() const
+    {
+        TMatrix m; GetAutoCorrelation(m); return m;
+    }
+
+    //void Paint(Option_t *o="");
+    void Draw(Option_t *o="");
+
+    ClassDef(MHPedestalCor, 1) // Histogram to get signal auto correlation
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MMcPedestalCopy.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MMcPedestalCopy.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MMcPedestalCopy.cc	(revision 17960)
@@ -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, 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");
+}
+
+// --------------------------------------------------------------------------
+//
+// Make sure that there is a MPedestalCam object in the parameter list.
+//
+Int_t  MMcPedestalCopy::PreProcess(MParList *pList)
+{
+    return pList->FindCreateObj(AddSerialNumber("MPedestalCam")) ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the runtype.
+// Search for MPedestalCam and MMcFadcHeader.
+//
+Bool_t MMcPedestalCopy::ReInit(MParList *pList)
+{
+    const MRawRunHeader *run = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!run)
+    {
+        *fLog << warn << dbginf << "Warning - cannot check file type, " << AddSerialNumber("MRawRunHeader") << " not found." << endl;
+        return kTRUE;
+    }
+
+    //
+    // If it is no MC file skip this function...
+    //
+    if (!run->IsMonteCarloRun())
+    {
+        *fLog << inf << "This is no MC file... skipping." << endl;
+        return kTRUE;
+    }
+
+    MPedestalCam *pedcam = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!pedcam)
+    {
+        *fLog << err << "MPedestalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // Get MMcRunHeader to check camera version
+    MMcRunHeader *mcrun = (MMcRunHeader*)pList->FindObject(AddSerialNumber("MMcRunHeader"));
+
+    // Check if it is a ceres file
+    if (mcrun && mcrun->IsCeres())
+    {
+        *fLog << inf << "This is a ceres file... subtracting Baseline from ElectronicNoise [MPedestalCam]." << endl;
+
+        MPedestalCam *noise = (MPedestalCam*)pList->FindObject(AddSerialNumber("ElectronicNoise"), "MPedestalCam");
+        if (!noise)
+        {
+            *fLog << err << "ElectronicNoise [MPedestalCam] not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        const int num = pedcam->GetSize();
+        for (int i=0; i<num; i++)
+        {
+            const MPedestalPix &n = (*noise)[i];
+
+            (*pedcam)[i].Set(n.GetPedestal()/run->GetScale(),
+                             n.GetPedestalRms()/run->GetScale());
+        }
+
+        pedcam->SetReadyToSave();
+
+        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 << "MMcFadcHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!mcrun)
+        *fLog << warn << dbginf << AddSerialNumber("MMcRunHeader") << " not found... assuming camera<0.7" << endl;
+
+    const Bool_t camver70 = mcrun && mcrun->GetCamVersion()>=70;
+
+    const int num = pedcam->GetSize();
+    for (int i=0; i<num; 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);
+
+        (*pedcam)[i].Set(pedest/run->GetScale(), sigma/run->GetScale());
+    }
+
+    if (camver70)
+        pedcam->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MMcPedestalCopy.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MMcPedestalCopy.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MMcPedestalCopy.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mpedestal/MMcPedestalNSBAdd.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MMcPedestalNSBAdd.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MMcPedestalNSBAdd.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mpedestal/MMcPedestalNSBAdd.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MMcPedestalNSBAdd.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MMcPedestalNSBAdd.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mpedestal/MPedCalcFromLoGain.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedCalcFromLoGain.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedCalcFromLoGain.cc	(revision 17960)
@@ -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): Josep Flix 04/2001 <mailto:jflix@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Sebastian Commichau 12/2003 
+!   Author(s): Javier Rico 01/2004 <mailto:jrico@ifae.es> 
+!   Author(s): Markus Gaug 01/2004 <mailto:markus@ifae.es>
+!   Author(s): Florian Goebel 06/2004 <mailto:fgoebel@mppmu.mpg.de>
+!   Author(s): Nepomuk Otte 10/2004 <mailto:otte@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+// 
+//   MPedCalcLoGain
+//
+//  This task derives from MExtractPedestal. 
+//  It calculates the pedestals using the low gain slices, whenever the difference 
+//  between the highest and the lowest slice in the high gain
+//  slices is below a given threshold (SetMaxHiGainVar). In this case the receiver
+//  boards do not switch to lo gain and the so called lo gain slices are actually
+//  high gain slices. 
+//
+//  MPedCalcLoGain also fills the ABoffset in MPedestalPix which allows to correct 
+//  the 150 MHz clock noise.
+//
+//  This task takes a pedestal run file and fills MPedestalCam during
+//  the Process() with the pedestal and rms computed in an event basis.
+//  In the PostProcess() MPedestalCam is finally filled with the pedestal
+//  mean and rms computed in a run basis.
+//  More than one run (file) can be merged
+//
+//  MPedCalcPedRun applies the following formula (1):
+// 
+//  Pedestal per slice = sum(x_i) / n / slices
+//  PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices )
+// 
+//  where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//  events. "n" is the number of events, "slices" is the number of summed FADC samples.
+// 
+//  Note that the slice-to-slice fluctuations are not Gaussian, but Poissonian, thus 
+//  asymmetric and they are correlated.
+// 
+//  It is important to know that the Pedestal per slice and PedRMS per slice depend 
+//  on the number of used FADC slices, as seen in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyInner.gif">
+*/
+//End_Html
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyOuter.gif">
+*/
+//End_Html
+//
+// The plots show the inner and outer pixels, respectivly and have the following meaning:
+// 
+// 1) The calculated mean pedestal per slice (from MPedCalcFromLoGain)
+// 2) The fitted mean pedestal per slice     (from MHPedestalCam)
+// 3) The calculated pedestal RMS per slice  (from MPedCalcFromLoGain)
+// 4) The fitted sigma of the pedestal distribution per slice
+//                                           (from MHPedestalCam)
+// 5) The relative difference between calculation and histogram fit
+//    for the mean
+// 6) The relative difference between calculation and histogram fit
+//    for the sigma or RMS, respectively.
+// 
+// The calculated means do not change significantly except for the case of 2 slices, 
+// however the RMS changes from 5.7 per slice in the case of 2 extracted slices 
+// to 8.3 per slice in the case of 26 extracted slices. This change is very significant.
+// 
+// The plots have been produced on run 20123. You can reproduce them using
+// the macro pedestalstudies.C
+// 
+//  Usage of this class: 
+//  ====================
+//  
+// 
+//   fCheckWinFirst   =  fgCheckWinFirst   =  0 
+//   fCheckWinLast    =  fgCheckWinLast    =  29
+//   fExtractWinFirst =  fgExtractWinFirst =  17
+//   fExtractWinSize  =  fgExtractWinSize  =  6
+//   fMaxSignalVar    =  fgMaxSignalVar    = 40;
+//
+//  Call: 
+//  SetCheckRange(fCheckWinFirst,fCheckWinLast); 
+//  to set the Window in which a signal is searched
+//
+//  SetExtractWindow(fExtractWinFirst,fExtractWinSize);
+//  to set the Window from which a signal is extracted
+//
+//  SetMaxSignalVar(fMaxSignalVar);
+//  set the maximum allowed difference between maximum and minimal signal in CheckWindow  
+//
+//   Variables:
+//   fgCheckWinFirst;      First FADC slice to check for signal (currently set to: 0)
+//   fgCheckWinLast:       Last FADC slice to check for signal (currently set to: 29)
+//   fgExtractWinFirst:    First FADC slice to be used for pedestal extraction (currently set to: 15)
+//   fgExtractWinSize:     Window size in slices used for pedestal extraction (currently set to: 6)
+//   fgMaxSignalVar:       The maximum difference between the highest and lowest slice
+//                         in the check window allowed in order to use event
+//
+//  Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MGeomCam
+//
+//  Output Containers:
+//   MPedestalCam
+//
+//  See also: MPedestalCam, MPedestalPix, MHPedestalCam, MExtractor
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedCalcFromLoGain.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"  
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+
+ClassImp(MPedCalcFromLoGain);
+
+using namespace std;
+
+const UShort_t MPedCalcFromLoGain::fgExtractWinFirst =  17;
+const UShort_t MPedCalcFromLoGain::fgExtractWinSize  =   6;
+const UInt_t   MPedCalcFromLoGain::fgNumDump         = 500;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor: 
+//
+// Calls: 
+// - SetExtractWindow(fgExtractWinFirst, fgExtractWinSize)
+//
+MPedCalcFromLoGain::MPedCalcFromLoGain(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPedCalcFromLoGain";
+    fTitle = title ? title : "Task to calculate pedestals from lo-gains";
+
+    SetExtractWindow(fgExtractWinFirst, fgExtractWinSize);
+    SetPedestalUpdate(kTRUE);
+    SetNumDump();
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Checks:
+// - if the number of available slices 
+//   (fRunHeader->GetNumSamplesHiGain()+(Int_t)fRunHeader->GetNumSamplesLoGain()-1)
+//   is smaller than the number of used slices
+//   (fExtractWinSize+ fExtractWinFirst-1) or 
+//    fCheckWinLast
+//
+Bool_t MPedCalcFromLoGain::ReInit(MParList *pList)
+{
+    if (!MExtractPedestal::ReInit(pList))
+        return kFALSE;
+
+    const Int_t nhi = fRunHeader->GetNumSamplesHiGain();
+    const Int_t nlo = fRunHeader->GetNumSamplesLoGain();
+    CheckExtractionWindow(nlo>0?nhi:0);
+
+    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()
+//
+void MPedCalcFromLoGain::Calc()
+{
+    const Int_t nhi = fRunHeader->GetNumSamplesHiGain();
+    const Int_t nlo = fRunHeader->GetNumSamplesLoGain();
+
+    const Int_t offset = nlo>0?nhi:0;
+
+    // Real Process
+    MRawEvtPixelIter pixel(fRawEvt);
+    while (pixel.Next())
+    {
+        if (!CalcPixel(pixel, offset))
+            continue;
+
+        const UInt_t idx = pixel.GetPixelId();
+        if (!fPedestalUpdate || (UInt_t)fNumEventsUsed[idx]<fNumEventsDump)
+            continue;
+
+        CalcPixResults(idx);
+
+        fNumEventsUsed[idx]=0;
+        fSumx[idx]=0;
+        fSumx2[idx]=0;
+        fSumAB0[idx]=0;
+        fSumAB1[idx]=0;
+    }
+
+    if (fNumAreasDump>0 && !(GetNumExecutions() % fNumAreasDump))
+    {
+        CalcAreaResult();
+        fAreaFilled.Reset();
+    }
+
+    if (fNumSectorsDump>0 && !(GetNumExecutions() % fNumSectorsDump))
+    {
+        CalcSectorResult();
+        fSectorFilled.Reset();
+    }
+
+    fCounter++;
+
+    if (fPedestalUpdate)
+        fPedestalsOut->SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+// Compute signal mean and rms in the whole run and store it in MPedestalCam
+//
+Int_t MPedCalcFromLoGain::PostProcess()
+{
+    // Compute pedestals and rms from the whole run
+    if (fPedestalUpdate)
+        return kTRUE;
+
+    *fLog << flush << inf << "Calculating Pedestals..." << flush;
+
+    CalcPixResult();
+    CalcAreaResult();
+    CalcSectorResult();
+
+    fPedestalsOut->SetReadyToSave();
+
+    return MExtractPedestal::PostProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+//  The following resources are available:
+//
+Int_t MPedCalcFromLoGain::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Int_t rc=MExtractPedestal::ReadEnv(env, prefix, print);
+    if (rc==kERROR)
+        return kERROR;
+
+    // find resource for pedestal update
+    if (IsEnvDefined(env, prefix, "PedestalUpdate", print))
+    {
+        SetPedestalUpdate(GetEnvValue(env, prefix, "PedestalUpdate", fPedestalUpdate));
+        rc = kTRUE;
+    }
+
+    // find resource for numdump
+    if (IsEnvDefined(env, prefix, "NumDump", print))
+    {
+        const Int_t num = GetEnvValue(env, prefix, "NumDump", -1);
+        if (num<=0)
+        {
+            *fLog << err << GetDescriptor() << ": ERROR - NumDump invalid!" << endl;
+            return kERROR;
+        }
+
+        SetNumDump(num);
+        rc = kTRUE;
+    }
+
+    // find resource for numeventsdump
+    if (IsEnvDefined(env, prefix, "NumEventsDump", print))
+    {
+        SetNumEventsDump(GetEnvValue(env, prefix, "NumEventsDump", (Int_t)fNumEventsDump));
+        rc = kTRUE;
+    }
+
+    // find resource for numeventsdump
+    if (IsEnvDefined(env, prefix, "NumAreasDump", print))
+    {
+        SetNumAreasDump(GetEnvValue(env, prefix, "NumAreasDump", (Int_t)fNumAreasDump));
+        rc = kTRUE;
+    }
+
+    // find resource for numeventsdump
+    if (IsEnvDefined(env, prefix, "NumSectorsDump", print))
+    {
+        SetNumSectorsDump(GetEnvValue(env, prefix, "NumSectorsDump", (Int_t)fNumSectorsDump));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
+
+void MPedCalcFromLoGain::Print(Option_t *o) const
+{
+    MExtractPedestal::Print(o);
+
+    *fLog << "Pedestal Update is            " << (fPedestalUpdate?"on":"off") << endl;
+    if (fPedestalUpdate)
+    {
+        *fLog << "Num evts for pedestal   calc: " << fNumEventsDump << endl;
+        *fLog << "Num evts for avg.areas  calc: " << fNumAreasDump << endl;
+        *fLog << "Num evts for avg.sector calc: " << fNumSectorsDump << endl;
+    }
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedCalcFromLoGain.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedCalcFromLoGain.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedCalcFromLoGain.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MPedCalcFromLoGain
+#define MARS_MPedCalcFromLoGain
+
+#ifndef MARS_MExtractPedestal
+#include "MExtractPedestal.h"
+#endif
+
+#ifndef ROOT_MArrayB
+#include "MArrayB.h"
+#endif
+
+//class MRawEvtPixelIter;
+class MPedestalPix;
+
+class MPedCalcFromLoGain : public MExtractPedestal
+{
+private:
+    static const UShort_t fgExtractWinFirst;  // First FADC slice to use for pedestal calculation (currently set to: 15)
+    static const UShort_t fgExtractWinSize;   // number of successive slices used to calculate pedestal (currently set to: 6)
+    static const UInt_t   fgNumDump;          //!
+
+    UInt_t  fNumEventsDump;            // Number of event after which MPedestalCam gets updated
+    UInt_t  fNumAreasDump;             // Number of events after which averaged areas gets updated
+    UInt_t  fNumSectorsDump;           // Number of events after which averaged sectors gets updated
+
+    Bool_t  fPedestalUpdate;           // Flag if the pedestal shall be updated after every fNumEventsDump
+
+    // MParContainer
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Bool_t ReInit(MParList *pList);
+    Int_t  PostProcess();
+
+    // MExtractPedestal
+    void   Calc();
+
+public:
+    MPedCalcFromLoGain(const char *name=NULL, const char *title=NULL);
+
+    // Getters
+    void SetNumEventsDump (UInt_t dumpevents=fgNumDump)  { fNumEventsDump  = dumpevents; }
+    void SetNumAreasDump  (UInt_t dumpevents=fgNumDump)  { fNumAreasDump   = dumpevents; }
+    void SetNumSectorsDump(UInt_t dumpevents=fgNumDump)  { fNumSectorsDump = dumpevents; }
+    void SetNumDump       (UInt_t n=fgNumDump) { fNumEventsDump=n; fNumAreasDump=n; fNumSectorsDump=n; }
+
+    void SetPedestalUpdate(Bool_t b=kTRUE) { fPedestalUpdate      = b; }
+
+    Bool_t SetRangeFromExtractor(const MExtractor &ext)
+    {
+        return MExtractPedestal::SetRangeFromExtractor(ext, kTRUE);
+    }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MPedCalcFromLoGain, 1)   // Task to calculate pedestals from data runs
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MPedCalcPedRun.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedCalcPedRun.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedCalcPedRun.cc	(revision 17960)
@@ -0,0 +1,337 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): 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-2007
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MPedCalcPedRun
+//
+//  This task takes a pedestal run file and fills MPedestalCam during
+//  the Process() with the pedestal and rms computed in an event basis.
+//  In the PostProcess() MPedestalCam is finally filled with the pedestal
+//  mean and rms computed in a run basis.
+//  More than one run (file) can be merged
+//
+//  MPedCalcPedRun applies the following formula (1):
+// 
+//  Pedestal per slice = sum(x_i) / n / slices
+//  PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices )
+// 
+//  where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//  events. "n" is the number of events, "slices" is the number of summed FADC samples.
+// 
+//  Note that the slice-to-slice fluctuations are not Gaussian, but Poissonian, thus 
+//  asymmetric and they are correlated.
+// 
+//  It is important to know that the Pedestal per slice and PedRMS per slice depend 
+//  on the number of used FADC slices, as seen in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyInner.gif">
+*/
+//End_Html
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyOuter.gif">
+*/
+//
+// The plots show the inner and outer pixels, respectivly and have the following meaning:
+// 
+// 1) The calculated mean pedestal per slice (from MPedCalcPedRun)
+// 2) The fitted mean pedestal per slice     (from MHPedestalCam)
+// 3) The calculated pedestal RMS per slice  (from MPedCalcPedRun)
+// 4) The fitted sigma of the pedestal distribution per slice
+//                                           (from MHPedestalCam)
+// 5) The relative difference between calculation and histogram fit
+//    for the mean
+// 6) The relative difference between calculation and histogram fit
+//    for the sigma or RMS, respectively.
+// 
+// The calculated means do not change significantly except for the case of 2 slices, 
+// however the RMS changes from 5.7 per slice in the case of 2 extracted slices 
+// to 8.3 per slice in the case of 26 extracted slices. This change is very significant.
+// 
+// The plots have been produced on run 20123. You can reproduce them using
+// the macro pedestalstudies.C
+// 
+//  Usage of this class: 
+//  ====================
+// 
+//  Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//  to modify the ranges in which the window is allowed to move. 
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  29
+//   fLoGainFirst =  fgLoGainFirst =  0 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindowSize(windowhigain, windowlogain) 
+//  to modify the sliding window widths. Windows have to be an even number. 
+//  In case of odd numbers, the window will be modified.
+//
+//  Defaults are:
+//
+//   fHiGainWindowSize = fgHiGainWindowSize = 14
+//   fLoGainWindowSize = fgLoGainWindowSize = 0
+//
+//
+// ToDo:
+//   - Take a setup file (ReadEnv-implementation) as input
+//
+//
+//  Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MGeomCam
+//
+//  Output Containers:
+//   MPedestalCam
+//
+//  See also: MPedestalCam, MPedestalPix, MHPedestalCam, MExtractor
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedCalcPedRun.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+
+#include "MTriggerPattern.h"
+
+ClassImp(MPedCalcPedRun);
+
+using namespace std;
+
+const UShort_t MPedCalcPedRun::fgExtractWinFirst       = 0;
+const UShort_t MPedCalcPedRun::fgExtractWinSize        = 6;
+
+const UInt_t   MPedCalcPedRun::gkFirstRunWithFinalBits = 45605;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor: 
+//
+// Calls: 
+// - SetExtractWindow(fgExtractWinFirst, fgExtractWinSize)
+//
+MPedCalcPedRun::MPedCalcPedRun(const char *name, const char *title)
+    : fIsFirstPedRun(kFALSE), fTrigPattern(NULL)
+{
+    fName  = name  ? name  : "MPedCalcPedRun";
+    fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
+
+    SetExtractWindow(fgExtractWinFirst, fgExtractWinSize);
+}
+
+// --------------------------------------------------------------------------
+//
+// Call MExtractPedestal::ResetArrays
+//
+void MPedCalcPedRun::Reset()
+{
+    MExtractPedestal::ResetArrays();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set fIsFirstPedRun=kTRUE
+//
+Int_t MPedCalcPedRun::PreProcess(MParList *pList)
+{
+    fIsFirstPedRun = kTRUE;
+    fIsNotPedRun   = kFALSE;
+
+    fTrigPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
+    if (!fTrigPattern)
+        *fLog << inf << "MTriggerPattern not found... Cannot use interlaced pedestal events." << endl;
+
+    return MExtractPedestal::PreProcess(pList);
+}
+
+// --------------------------------------------------------------------------
+//
+// The run type is checked for "kRTPedestal"
+// and the variable fIsNotPedRun is set in that case
+//
+Bool_t MPedCalcPedRun::ReInit(MParList *pList)
+{
+    if (!MExtractPedestal::ReInit(pList))
+        return kFALSE;
+
+    CheckExtractionWindow();
+
+    //
+    // If this is the first ped run, the next run (call to ReInit)
+    // is not the first anymore
+    //
+    switch (fRunHeader->GetRunType())
+    {
+    case MRawRunHeader::kRTPedestal:
+    case MRawRunHeader::kRTMonteCarlo:
+        fIsFirstPedRun = kFALSE;
+        fIsNotPedRun   = kFALSE;
+        return kTRUE;
+
+    case MRawRunHeader::kRTCalibration:
+        {
+            TString proj(fRunHeader->GetProjectName());
+            proj.ToLower();
+
+            // test if a continuous light run has been declared as calibration...
+            if (proj.Contains("cl"))
+            {
+                fIsFirstPedRun = kFALSE;
+                fIsNotPedRun   = kFALSE;
+                return kTRUE;
+            }
+        }
+    }
+
+    fIsNotPedRun = kTRUE;
+
+    //
+    // If this is the first call to ReInit (before reading the first file)
+    // nothing should be done. It occurs for the case that the first treated
+    // file is not of pedestal type.
+    //
+    if (fIsFirstPedRun)
+        return kTRUE;
+
+    //
+    // In the other case, produce the MPedestalCam to be use the subsequent
+    // (non-pedestal) events
+    //
+    *fLog << inf << "Finalizing pedestal calculations..." << flush;
+
+    if (!Finalize())
+        return kFALSE;
+
+    Reset();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return kTRUE (without doing anything) in case that the run type is not 
+// equal to 1 (pedestal run)
+//
+// Fill the MPedestalCam container with the signal mean and rms for the event.
+// Store the measured signal in arrays fSumx and fSumx2 so that we can 
+// calculate the overall mean and rms in the PostProcess()
+//
+void MPedCalcPedRun::Calc()
+{
+    if (fIsNotPedRun && !IsPedBitSet())
+        return;
+
+    MRawEvtPixelIter pixel(fRawEvt);
+    while (pixel.Next())
+        CalcPixel(pixel, 0, fUseSpecialPixels);
+
+    fCounter++;
+
+    fPedestalsOut->SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+// Compute signal mean and rms in the whole run and store it in MPedestalCam
+//
+Int_t MPedCalcPedRun::Finalize()
+{
+    //
+    // Necessary check for extraction of special pixels
+    // together with data which does not yet have them
+    //
+    if (fSumx.GetSize()==0)
+        return kTRUE;
+
+    CalcPixResult();
+
+    if (!fUseSpecialPixels)
+    {
+        CalcAreaResult();
+        CalcSectorResult();
+    }
+
+    fPedestalsOut->SetNumSlices(fExtractWinSize);
+    fPedestalsOut->SetReadyToSave();
+
+    return kTRUE;
+}
+
+//-----------------------------------------------------------------------
+//
+// PostProcess MExtractPedestal and call Finalize
+//
+Int_t MPedCalcPedRun::PostProcess()
+{
+    if (!fRawEvt)
+        return kTRUE;
+
+    if (!Finalize())
+        return kFALSE;
+
+    return MExtractPedestal::PostProcess();
+}
+
+//-----------------------------------------------------------------------
+// 
+// Return if the pedestal bit was set from the calibration trigger box.
+// The last but one bit is used for the "pedestal-bit".
+//
+// This bit is set since run gkFirstRunWithFinalBits
+//
+Bool_t MPedCalcPedRun::IsPedBitSet()
+{     
+    if (!fRunHeader->IsMonteCarloRun() && fRunHeader->GetTelescopeNumber()==1 && fRunHeader->GetRunNumber()<gkFirstRunWithFinalBits)
+        return kFALSE;
+
+    if (!fTrigPattern)
+        return kFALSE;
+
+    return (fTrigPattern->GetPrescaled() & MTriggerPattern::kPedestal) ? kTRUE : kFALSE;
+}
+
+//-----------------------------------------------------------------------
+//
+void MPedCalcPedRun::Print(Option_t *o) const
+{
+    MExtractPedestal::Print(o);
+
+    *fLog << "First pedrun out of sequence: " << (fIsFirstPedRun?"yes":"no") << endl;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedCalcPedRun.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedCalcPedRun.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedCalcPedRun.h	(revision 17960)
@@ -0,0 +1,50 @@
+#ifndef MARS_MPedCalcPedRun
+#define MARS_MPedCalcPedRun
+
+#ifndef MARS_MExtractPedestal
+#include "MExtractPedestal.h"
+#endif
+
+class MTriggerPattern;
+class MPedestalPix;
+
+class MPedCalcPedRun : public MExtractPedestal
+{
+private:
+    static const UShort_t fgExtractWinFirst;  // First FADC slice Hi-Gain (currently set to: 3)
+    static const UShort_t fgExtractWinSize;   // Extraction Size Hi-Gain (currently set to: 14)
+    static const UInt_t   gkFirstRunWithFinalBits; // First Run with pedestal trigger bit at place 3
+
+    Bool_t  fIsFirstPedRun;    //! Flag to tell if the first run out of many is used
+    Bool_t  fIsNotPedRun;      //! Flag to tell if the current run is a pedestal run
+
+    MTriggerPattern *fTrigPattern;  //! Trigger pattern decoded
+
+    Bool_t IsPedBitSet();
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    void   Calc();
+    Int_t  PostProcess();
+
+    //void CheckExtractionWindow();
+    //UInt_t CalcSums(const MRawEvtPixelIter &pixel, UInt_t &ab0, UInt_t &ab1);
+    //void CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped);
+
+public:
+    MPedCalcPedRun(const char *name=NULL, const char *title=NULL);
+
+    void Print(Option_t *o="") const;
+    void Reset();
+
+    Bool_t SetRangeFromExtractor(const MExtractor &ext)
+    {
+        return MExtractPedestal::SetRangeFromExtractor(ext, kFALSE);
+    }
+    
+    Int_t Finalize();
+
+    ClassDef(MPedCalcPedRun, 2)   // Task to calculate pedestals from pedestal runs
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MPedPhotCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedPhotCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedPhotCalc.cc	(revision 17960)
@@ -0,0 +1,187 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix 1/2004 <mailto:jflix@ifae.es>
+!   Author(s): Javier Rico 1/2004 <mailto:jrico@ifae.es>
+!   Author(s): Markus Gaug 4/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MPedPhotCalc
+//
+//  This is a Task class to compute, for each pixel, the signal mean and
+//  rms from a pedestal run file that has undergone the standard signal
+//  extration  and calibration procedure. The signal rms can be used as
+//  reference to compute the significance of the measured signals in the
+//  following data runs (e.g. during the image cleaning).
+//
+//  Input Containers:
+//   MSignalCam
+//
+//  Output Containers:
+//   MPedPhotCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+#include "MBadPixelsPix.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MPedPhotCalc);
+
+using namespace std;
+
+//
+// Default constructor
+//
+MPedPhotCalc::MPedPhotCalc(const char *name, const char *title)
+    : fPedestals(NULL), fCerPhot(NULL), fBadPixels(NULL)
+{
+  fName  = name  ? name  : "MPedPhotCalc";
+  fTitle = title ? title : "Task to calculate pedestals in units of photons";
+}
+
+// --------------------------------------------------------------------------
+//
+// Look for the following input containers:
+//
+//  - MSignalCam
+//  - MBadPixelsCam
+// 
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedPhotCam
+//
+Int_t MPedPhotCalc::PreProcess( MParList *pList )
+{      
+  // Look for input container
+  fCerPhot = (MSignalCam*)pList->FindObject("MSignalCam");
+  if (!fCerPhot)
+    {
+      *fLog << err << "MSignalCam not found... aborting." << endl;
+      return kFALSE;
+    }
+
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+      *fLog << warn << "WARNING - MBadPixelsCam not found... ignored." << endl;
+
+  // Create output container
+  fPedestals = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+  if (!fPedestals)
+    return kFALSE;
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit searches for the following input containers:
+//  - MRawRunHeader
+//
+// It also initializes the data arrays fSumx and fSumx2 
+// (only for the first read file)
+// 
+Bool_t MPedPhotCalc::ReInit(MParList *pList)
+{
+  // Initialize arrays
+  if(fSumx.GetSize()==0)
+  {
+      const UShort_t num = fPedestals->GetSize();
+
+      fSumx.Set(num);
+      fSumx2.Set(num);
+
+      memset(fSumx.GetArray(),  0, sizeof(Float_t)*num);
+      memset(fSumx2.GetArray(), 0, sizeof(Float_t)*num);
+  }
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Store the measured number of photons in arrays fSumx and fSumx2
+// so that we can calculate the mean and rms in the PostProcess()
+//
+Int_t MPedPhotCalc::Process()
+{
+    const UInt_t n = fCerPhot->GetNumPixels();
+    for(UInt_t idx=0; idx<n; idx++)
+    {
+       const Float_t nphot = (*fCerPhot)[idx].GetNumPhotons();
+       
+       fSumx[idx]  += nphot;
+       fSumx2[idx] += nphot*nphot;
+    }
+
+    fPedestals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compute mean and rms of the measured charge distribution (in photons)
+//
+Int_t MPedPhotCalc::PostProcess()
+{
+    // Compute pedestals and rms from fSumx and fSumx2 arrays
+    const Int_t n    = GetNumExecutions();
+    const Int_t npix = fSumx.GetSize();
+
+    for(Int_t i=0; i<npix; i++)
+    {
+
+      if (fBadPixels)
+        {
+          const MBadPixelsPix &bad = (*fBadPixels)[i];
+          if (bad.IsBad())
+            continue;
+        }
+
+      const Float_t sum  = fSumx[i];
+      const Float_t sum2 = fSumx2[i];
+      
+      const Float_t photped = sum/n;
+      const Float_t photrms = TMath::Sqrt((sum2-sum*sum/n)/(n-1.));
+      
+      (*fPedestals)[i].Set(photped,photrms);
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedPhotCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedPhotCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedPhotCalc.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MPedPhotCalc
+#define MARS_MPedPhotCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MPedPhotCam;
+class MSignalCam;
+class MBadPixelsCam;
+class MPedPhotCalc : public MTask
+{
+
+  MPedPhotCam   *fPedestals;  // Pedestals of all pixels in the camera
+  MSignalCam    *fCerPhot;    // Calibrated Cherenkov events
+  MBadPixelsCam *fBadPixels;  // Bad Pixels
+  
+  TArrayF fSumx;   // sum of values
+  TArrayF fSumx2;  // sum of squared values
+
+  Bool_t ReInit(MParList *pList);
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess();
+  
+public:
+  MPedPhotCalc(const char *name=NULL, const char *title=NULL);
+
+  ClassDef(MPedPhotCalc, 0) //Task to calculate pedestals in units of photons
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MPedPhotCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedPhotCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedPhotCam.cc	(revision 17960)
@@ -0,0 +1,370 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 07/2003 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedPhotCam
+//
+// Hold the Pedestal information for all pixels in the camera (in usints
+// of photons)
+//
+// Version 2:
+// ----------
+//   - added fAreas
+//   - added fSectors
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotCam.h"
+
+#include <TClonesArray.h>
+
+#include "MArrayI.h"
+#include "MArrayD.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MPedPhotPix.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MPedPhotCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Contains the default constructor. Creates a MPedPhotPix object
+// for each pixel
+//
+void MPedPhotCam::InitArrays(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPedPhotCam";
+    fTitle = title ? title : "Storage container for all Pedestal Information in the camera (in units of photons)";
+
+    fArray   = new TClonesArray("MPedPhotPix", 1);
+    fAreas   = new TClonesArray("MPedPhotPix", 1);
+    fSectors = new TClonesArray("MPedPhotPix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates a MPedPhotPix object for each pixel
+//
+MPedPhotCam::MPedPhotCam(const char *name, const char *title)
+{
+    InitArrays(name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the mean, rms and number of events with the values from
+// the MPedestalCam converted 1:1
+//
+MPedPhotCam::MPedPhotCam(const MPedestalCam &p)
+{
+    const Int_t n = p.GetSize();
+
+    InitArrays();
+    InitSize(n);
+
+    for (int i=0; i<n; i++)
+        (*this)[i].Set(p[i].GetPedestal(), p[i].GetPedestalRms(), p[i].GetNumEvents());
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the array conatining the pixel pedest information
+//
+MPedPhotCam::~MPedPhotCam()
+{
+    delete fArray;
+    delete fAreas;
+    delete fSectors;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MPedPhotCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageAreas
+//
+void MPedPhotCam::InitAreas(const UInt_t i)
+{
+    fAreas->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageSectors
+//
+void MPedPhotCam::InitSectors(const UInt_t i)
+{
+    fSectors->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MPedPhotCam::Init(const MGeomCam &geom)
+{
+    InitSize(geom.GetNumPixels());
+    InitAreas(geom.GetNumAreas());
+    InitSectors(geom.GetNumSectors());
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MPedPhotCam
+//
+Int_t MPedPhotCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MPedPhotCam
+//
+Int_t MPedPhotCam::GetNumSectors() const
+{
+    return fSectors->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MPedPhotCam
+//
+Int_t MPedPhotCam::GetNumAreas() const
+{
+    return fAreas->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MPedPhotPix &MPedPhotCam::operator[](Int_t i)
+{
+    return *static_cast<MPedPhotPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MPedPhotPix &MPedPhotCam::operator[](Int_t i) const
+{
+    return *static_cast<MPedPhotPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MPedPhotPix &MPedPhotCam::GetArea(UInt_t i)
+{
+    return *static_cast<MPedPhotPix*>(fAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MPedPhotPix &MPedPhotCam::GetSector(UInt_t i)
+{
+    return *static_cast<MPedPhotPix*>(fSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MPedPhotPix &MPedPhotCam::GetArea(UInt_t i)const
+{
+    return *static_cast<MPedPhotPix*>(fAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MPedPhotPix &MPedPhotCam::GetSector(UInt_t i) const
+{
+    return *static_cast<MPedPhotPix*>(fSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Call clear of all three TClonesArray
+//
+void MPedPhotCam::Clear(Option_t *o)
+{
+    { fArray->R__FOR_EACH(TObject, Clear)(); }
+    { fAreas->R__FOR_EACH(TObject, Clear)(); }
+    { fSectors->R__FOR_EACH(TObject, Clear)(); }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the avarage pedestal and pedestal rms for all sectors
+// and pixel sizes. The geometry container is used to get the necessary
+// geometry information (sector number, size index) If the bad pixel
+// container is given all pixels which have the flag 'bad' are ignored
+// in the calculation of the sector and size average.
+//
+void MPedPhotCam::ReCalc(const MGeomCam &geom, MBadPixelsCam *bad)
+{
+    const Int_t np = GetSize();
+    const Int_t ns = GetNumSectors();
+    const Int_t na = GetNumAreas();
+
+    // Using MArray instead of TArray because they don't do range checks
+    MArrayI acnt(na);
+    MArrayI scnt(ns);
+    MArrayD asumx(na);
+    MArrayD ssumx(ns);
+    MArrayD asumr(na);
+    MArrayD ssumr(ns);
+
+    for (int i=0; i<np; i++)
+    {
+        if (bad && (*bad)[i].IsUnsuitable())
+            continue;
+
+        // Create sums for areas and sectors
+        const MPedPhotPix &pix = (*this)[i];
+
+        const UInt_t  ne   = pix.GetNumEvents();
+        const Float_t mean = ne*pix.GetMean();
+	const Float_t rms  = ne*pix.GetRms();
+
+        const UInt_t aidx = geom[i].GetAidx();
+        asumx[aidx] += mean;
+	asumr[aidx] += rms;
+        acnt[aidx]  += ne;
+
+        const UInt_t sect = geom[i].GetSector();
+        ssumx[sect] += mean;
+	ssumr[sect] += rms;
+        scnt[sect]  += ne;
+    }
+
+    for (int i=0; i<ns; i++)
+        if (scnt[i]>0)
+            GetSector(i).Set(ssumx[i]/scnt[i], ssumr[i]/scnt[i], scnt[i]);
+        else
+            GetSector(i).Clear();
+
+    for (int i=0; i<na; i++)
+        if (acnt[i]>0)
+            GetArea(i).Set(asumx[i]/acnt[i], asumr[i]/acnt[i], acnt[i]);
+        else
+            GetArea(i).Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// print contents
+//
+void MPedPhotCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    int id = 0;
+
+    TIter Next(fArray);
+    MPedPhotPix *pix;
+    while ((pix=(MPedPhotPix*)Next()))
+    {
+        id++;
+
+        if (!pix->IsValid())
+            continue;
+
+        *fLog << id-1 << ": ";
+        *fLog << pix->GetMean() << " " << pix->GetRms() << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// See MCamEvent
+//
+Bool_t MPedPhotCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx>=GetSize())
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+        val = (*this)[idx].GetMean();
+        break;
+    case 1:
+        val = (*this)[idx].GetRms();
+        break;
+    case 2:
+        val = (*this)[idx].GetNumEvents()>0 ? (*this)[idx].GetRms()/TMath::Sqrt((Float_t)(*this)[idx].GetNumEvents()) : -1;
+        break;
+    case 3:
+        val = (*this)[idx].GetNumEvents()>0 ? (*this)[idx].GetRms()/TMath::Sqrt((Float_t)(*this)[idx].GetNumEvents())/2. : -1;
+        break;
+    case 4:
+        val = (*this)[idx].GetMean()*cam.GetPixRatio(idx);
+        break;
+    case 5:
+        val = (*this)[idx].GetRms()*cam.GetPixRatioSqrt(idx);
+        break;
+    default:
+	return kFALSE;
+    }
+    return val>=0;
+}
+
+void MPedPhotCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MPedPhotCam::DrawPixelContent - not available." << endl;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedPhotCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedPhotCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedPhotCam.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MPedPhotCam
+#define MARS_MPedPhotCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+
+class MGeomCam;
+class MPedPhotPix;
+class MBadPixelsCam;
+class MPedestalCam;
+
+class MPedPhotCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray;    // FIXME: Change TClonesArray away from a pointer?
+    TClonesArray *fAreas;    //-> Array of MPedPhotPix, one per pixel area
+    TClonesArray *fSectors;  //-> Array of MPedPhotPix, one per camera sector
+
+    void InitArrays(const char *name=NULL, const char *title=NULL);
+
+    //  void InitSize(const UInt_t i);
+    void InitAreas(const UInt_t i);
+    void InitSectors(const UInt_t i);
+
+public:
+    MPedPhotCam(const char *name=NULL, const char *title=NULL);
+    MPedPhotCam(const MPedestalCam &pcam);
+    ~MPedPhotCam();
+
+    void Clear(Option_t *o="");
+
+    void Init(const MGeomCam &geom);
+    void InitSize(const UInt_t i); // HB
+    Int_t GetSize() const;
+
+    MPedPhotPix &operator[](Int_t i);
+    const MPedPhotPix &operator[](Int_t i) const;
+
+          MPedPhotPix &GetArea(UInt_t i);
+    const MPedPhotPix &GetArea(UInt_t i) const;
+
+    Int_t GetNumAreas() const;
+
+          MPedPhotPix &GetSector(UInt_t i);
+    const MPedPhotPix &GetSector(UInt_t i) const;
+
+    Int_t GetNumSectors() const;
+
+    void Print(Option_t *o="") const;
+
+    void ReCalc(const MGeomCam &geom, MBadPixelsCam *bad=NULL);
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MPedPhotCam, 2)	// Storage Container for all pedestal information of the camera (in units of photons)
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mpedestal/MPedPhotPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedPhotPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedPhotPix.cc	(revision 17960)
@@ -0,0 +1,57 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedPhotPix
+//
+// This is the storage container to hold informations about the pedestal
+// (offset) value of one Pixel (PMT) in units of photons.
+//
+// Version 2:
+// ----------
+//   - added fNumEvents
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotPix.h"
+
+#include "MLog.h"
+
+ClassImp(MPedPhotPix);
+
+MPedPhotPix::MPedPhotPix()
+{
+    Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MPedPhotPix::Clear(Option_t *o)
+{
+    fMean = -1;
+    fRms  = -1;
+    fNumEvents = 0;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedPhotPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedPhotPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedPhotPix.h	(revision 17960)
@@ -0,0 +1,38 @@
+#ifndef MARS_MPedPhotPix
+#define MARS_MPedPhotPix
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef MARS_MMath
+#include "MMath.h"
+#endif
+
+class MPedPhotPix : public TObject
+{
+private:
+    Float_t fMean;      // [phot] mean value of pedestal (should be 0)
+    Float_t fRms;       // [phot] rms of mean
+
+    UInt_t  fNumEvents; // [n] number of events used to calculate mean (0=n/a)
+
+public:
+    MPedPhotPix();
+
+    void Clear(Option_t *o="");
+
+    Float_t GetMean() const      { return fMean; }
+    Float_t GetRms() const       { return fRms; }
+    UInt_t  GetNumEvents() const { return fNumEvents; }
+
+    //void SetMean(Float_t f) { fMean = f; }
+    void SetRms(Float_t f)  { MMath::ReducePrecision(f);  fRms  = f; }
+    void Set(Float_t m, Float_t r, UInt_t n=1) { MMath::ReducePrecision(r); MMath::ReducePrecision(m); fMean = m; fRms = r; fNumEvents=n; }
+
+    Bool_t IsValid() const { return fRms>=0; }
+
+    ClassDef(MPedPhotPix, 2) // Storage Container for Pedestal information of one pixel in units of photons
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalCalc.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mpedestal/MPedestalCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalCalc.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mpedestal/MPedestalCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalCam.cc	(revision 17960)
@@ -0,0 +1,591 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 Gaug    02/2004 <mailto:markus@ifae.es>
+!   Author(s): Florian Goebel 06/2004 <mailto:fgoebel@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedestalCam
+//
+// Hold the Pedestal information for all pixels in the camera
+//
+// Class Version 2:
+// ----------------
+//  + fNumSlices
+//  - fTotalEntries
+//
+// Class Version 3:
+// ----------------
+//  + fNumEvents
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include <TMath.h>
+
+#include <TArrayI.h>
+#include <TArrayF.h>
+#include <TArrayD.h>
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MPedestalCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MPedestalPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MPedestalCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MPedestalPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MPedestalCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MPedestalPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MPedestalCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+MPedestalCam::MPedestalCam(const char *name, const char *title) 
+    : fNumSlices(0), fNumEvents(0)
+{
+  fName  = name  ? name  : "MPedestalCam";
+  fTitle = title ? title : "Storage container for all Pedestal Information in the camera";
+
+  fArray            = new TClonesArray("MPedestalPix", 1);
+  fAverageAreas     = new TClonesArray("MPedestalPix", 1);
+  fAverageSectors   = new TClonesArray("MPedestalPix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the following TClonesArray's of MPedestalPix containers (if exist):
+// - fArray
+// - fAverageAreas
+// - fAverageSectors
+//  
+MPedestalCam::~MPedestalCam()
+{
+  delete fArray;
+  delete fAverageAreas;
+  delete fAverageSectors;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MPedestalCam::Copy(TObject &obj) const
+{
+
+  MParContainer::Copy(obj);
+
+  MPedestalCam &cam = (MPedestalCam&)obj;
+
+  Int_t n = GetSize();
+
+  if (n==0)
+    return;
+
+  cam.InitSize(n);
+  for (int i=0; i<n; i++)
+    (*this)[i].Copy(cam[i]);
+
+  cam.fNumEvents = fNumEvents;
+  cam.fNumSlices = fNumSlices;
+
+  n = GetNumAverageArea();
+  cam.InitAverageAreas(n);
+  for (int i=0; i<n; i++)
+    GetAverageArea(i).Copy(cam.GetAverageArea(i));
+
+  n = GetNumAverageSector();
+  cam.InitAverageSectors(n);
+  for (int i=0; i<n; i++)
+    GetAverageSector(i).Copy(cam.GetAverageSector(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MPedestalCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageAreas
+//
+void MPedestalCam::InitAverageAreas(const UInt_t i)
+{
+  fAverageAreas->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageSectors
+//
+void MPedestalCam::InitAverageSectors(const UInt_t i)
+{
+  fAverageSectors->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MPedestalCam::Init(const MGeomCam &geom)
+{
+  InitSize          (geom.GetNumPixels() );
+  InitAverageAreas  (geom.GetNumAreas()  );
+  InitAverageSectors(geom.GetNumSectors());
+}
+
+// --------------------------------------------------------------------------
+//
+// This function returns the current size of the TClonesArray 
+// independently if the MPedestalPix is filled with values or not.
+//
+// Get the size of the MPedestalCam
+//
+Int_t MPedestalCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageAreas
+// independently if the MPedestalPix is filled with values or not.
+//
+Int_t MPedestalCam::GetNumAverageArea() const
+{
+  return fAverageAreas->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageSectors
+// independently if the MPedestalPix is filled with values or not.
+//
+Int_t MPedestalCam::GetNumAverageSector() const
+{
+  return fAverageSectors->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MPedestalPix &MPedestalCam::operator[](Int_t i)
+{
+    return *static_cast<MPedestalPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MPedestalPix &MPedestalCam::operator[](Int_t i) const
+{
+    return *static_cast<MPedestalPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MPedestalPix &MPedestalCam::GetAverageArea(UInt_t i)
+{
+  return *static_cast<MPedestalPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MPedestalPix &MPedestalCam::GetAverageArea(UInt_t i) const 
+{
+  return *static_cast<MPedestalPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MPedestalPix &MPedestalCam::GetAverageSector(UInt_t i)
+{
+  return *static_cast<MPedestalPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MPedestalPix &MPedestalCam::GetAverageSector(UInt_t i) const 
+{
+  return *static_cast<MPedestalPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------
+//
+// Calls the ForEach macro for the TClonesArray fArray with the argument Clear()
+// 
+// Loops over the fAverageAreas, calling the function Clear() for 
+// every entry in fAverageAreas
+//
+// Loops over the fAverageSectors, calling the function Clear() for 
+// every entry in fAverageSectors
+// 
+void MPedestalCam::Clear(Option_t *o)
+{
+    { fArray->R__FOR_EACH(TObject, Clear)(); }
+    { fAverageAreas->R__FOR_EACH(TObject, Clear)(); }
+    { fAverageSectors->R__FOR_EACH(TObject, Clear)(); }
+
+    fNumSlices = 0;
+}
+
+void MPedestalCam::PrintArr(const TCollection &list) const
+{
+    Int_t id = 0;
+
+    TIter Next(&list);
+    MPedestalPix *pix = 0;
+
+    while ((pix=(MPedestalPix*)Next()))
+        *fLog << Form("Nr.: %4i  Pedestal: %5.2f    RMS: %5.2f    ABOffset: %5.2f ",
+                      id++, pix->GetPedestal(), pix->GetPedestalRms(), pix->GetPedestalABoffset()) << endl;
+}
+
+void MPedestalCam::Print(Option_t *option) const
+{
+    *fLog << all << GetDescriptor();
+    *fLog << " - Events=" << fNumEvents << ", Slices=" << fNumSlices << ":" << endl;
+
+    *fLog << endl;
+    *fLog << "Event-by-event averaged areas:" << endl;
+    PrintArr(*fAverageAreas);
+
+    *fLog << endl;
+    *fLog << "Event-by-event averaged sectors:" << endl;
+    PrintArr(*fAverageSectors);
+
+    if (TString(option).Contains("all", TString::kIgnoreCase))
+    {
+        *fLog << endl;
+        *fLog << "Pixels:" << endl;
+        PrintArr(*fArray);
+    }
+}
+
+/*
+Float_t MPedestalCam::GetPedestalMin(const MGeomCam *geom) const
+{
+    if (fArray->GetEntries() <= 0)
+        return 50.;
+
+    Float_t minval = (*this)[0].GetPedestalRms();
+
+    for (Int_t i=1; i<fArray->GetEntries(); i++)
+    {
+        const MPedestalPix &pix = (*this)[i];
+
+        Float_t testval = pix.GetPedestalRms();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval < minval)
+            minval = testval;
+    }
+    return minval;
+}
+
+Float_t MPedestalCam::GetPedestalMax(const MGeomCam *geom) const
+{
+    if (fArray->GetEntries() <= 0)
+        return 50.;
+
+    Float_t maxval = (*this)[0].GetPedestalRms();
+
+    for (Int_t i=1; i<fArray->GetEntries(); i++)
+    {
+        const MPedestalPix &pix = (*this)[i];
+
+        Float_t testval = pix.GetPedestalRms();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedPedPerArea(const MGeomCam &geom, const UInt_t ai, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+      
+      mean  += pix.GetPedestal();
+      mean2 += pix.GetPedestal()*pix.GetPedestal();
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1.;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal rms for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal RMS (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal RMS (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedRmsPerArea(const MGeomCam &geom, const UInt_t ai, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t rms  = 0.;
+  Double_t rms2 = 0.;
+  Int_t    nr   = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+      
+      rms  += pix.GetPedestalRms();
+      rms2 += pix.GetPedestalRms()*pix.GetPedestalRms();
+      nr   ++;
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? rms/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((rms2 - rms*rms/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedPedPerSector(const MGeomCam &geom, const UInt_t sec, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr   = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sec != sector)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+      
+      mean  += pix.GetPedestal();
+      mean2 += pix.GetPedestal()*pix.GetPedestal();
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal rms for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal RMS (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal RMS (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedRmsPerSector(const MGeomCam &geom, const UInt_t sec, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t rms  = 0.;
+  Double_t rms2 = 0.;
+  Int_t    nr   = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+
+      const UInt_t sector = geom[i].GetSector();
+
+      if (sec != sector)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+
+      rms  += pix.GetPedestalRms();
+      rms2 += pix.GetPedestalRms()*pix.GetPedestalRms();
+      nr   ++;
+
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? rms/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((rms2 - rms*rms/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+
+Bool_t MPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (GetSize() <= idx)
+        return kFALSE;
+
+    if (!(*this)[idx].IsValid())
+        return kFALSE;
+
+    const Float_t ped = (*this)[idx].GetPedestal();
+    const Float_t rms = (*this)[idx].GetPedestalRms();
+    const UInt_t  num = (*this)[idx].GetNumEvents()*fNumSlices;
+
+    switch (type)
+    {
+    case 0:
+        val = ped;
+        break;
+    case 1:
+        val = fNumSlices>0 ? rms/TMath::Sqrt((Float_t)num)
+            : (*this)[idx].GetPedestalError();
+        break;
+    case 2:
+        val = rms;
+        break;
+    case 3:
+        val = fNumSlices>0 ? rms/TMath::Sqrt((Float_t)num*2.)
+            : (*this)[idx].GetPedestalRmsError();
+        break;
+    case 4:
+        val = rms;
+        break;
+    default:
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+void MPedestalCam::DrawPixelContent(Int_t idx) const
+{
+    *fLog << warn << "MPedestalCam::DrawPixelContent - not available." << endl;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalCam.h	(revision 17960)
@@ -0,0 +1,77 @@
+#ifndef MARS_MPedestalCam
+#define MARS_MPedestalCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+
+class MGeomCam;
+class MPedestalPix;
+class MBadPixelsCam;
+class TArrayF;
+class MPedestalCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TClonesArray *fArray;           //-> FIXME: Change TClonesArray away from a pointer?
+  TClonesArray *fAverageAreas;    //-> Array of MPedestalPix, one per pixel area
+  TClonesArray *fAverageSectors;  //-> Array of MPedestalPix, one per camera sector
+
+  UInt_t fNumSlices;  // Total number of slices
+  UInt_t fNumEvents;  // Number of events used for pedestal calculation (be careful, it has no predefined meaning!)
+
+  void PrintArr(const TCollection &list) const;
+
+public:
+
+  MPedestalCam(const char *name=NULL, const char *title=NULL);
+  ~MPedestalCam();
+
+  // TObject
+  void Clear(Option_t *o="");
+  void Copy(TObject &object) const;
+  void Print(Option_t *o="") const; //*MENU*
+
+  // Getters 
+        MPedestalPix &GetAverageArea   ( UInt_t i );
+  const MPedestalPix &GetAverageArea   ( UInt_t i )            const;
+        Int_t         GetNumAverageArea()                      const;
+        MPedestalPix &GetAverageSector ( UInt_t i );
+  const MPedestalPix &GetAverageSector ( UInt_t i )            const;
+        Int_t         GetNumAverageSector()                    const;
+  //Float_t             GetPedestalMin   ( const MGeomCam *cam ) const;
+  //Float_t             GetPedestalMax   ( const MGeomCam *cam ) const;
+  Int_t               GetSize          ()                      const;
+  ULong_t             GetNumSlices() const { return fNumSlices; }
+  UInt_t              GetNumEvents() const { return fNumEvents; }
+
+  TArrayF GetAveragedPedPerArea  ( const MGeomCam &geom, const UInt_t ai=0,  MBadPixelsCam *bad=NULL );
+  TArrayF GetAveragedPedPerSector( const MGeomCam &geom, const UInt_t sec=0, MBadPixelsCam *bad=NULL );
+  TArrayF GetAveragedRmsPerArea  ( const MGeomCam &geom, const UInt_t ai=0,  MBadPixelsCam *bad=NULL );
+  TArrayF GetAveragedRmsPerSector( const MGeomCam &geom, const UInt_t sec=0, MBadPixelsCam *bad=NULL );
+
+        MPedestalPix &operator[]       ( Int_t i             );
+  const MPedestalPix &operator[]       ( Int_t i             ) const;
+
+  void  Init                           ( const MGeomCam &geom);
+  void  InitSize                       ( const UInt_t i      );
+  void  InitAverageAreas               ( const UInt_t i      );
+  void  InitAverageSectors             ( const UInt_t i      );
+
+  // Setters
+  void SetNumSlices(const ULong_t n) { fNumSlices = n; }
+  void SetNumEvents(const UInt_t n)  { fNumEvents = n; }
+
+  // MCamEvent
+  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, 3)	// Storage Container for all pedestal information of the camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalPix.cc	(revision 17960)
@@ -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@uni-sw.gwdg.de>
+!   Author(s): Markus Gaug    04/2004 <mailto:markus@ifae.es>
+!   Author(s): Florian Goebel 06/2004 <mailto:fgoebel@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedestalPix
+//
+// This is the storage container to hold informations about the pedestal
+// (offset) value of one Pixel (PMT).
+//
+//  Float_t fPedestal:
+//   - mean value of pedestal (PMT offset)
+//  Float_t fPedestalRms:
+//   - root mean square / sigma  / standard deviation of pedestal
+//  Float_t fPedestalABoffset:
+//   - the difference between odd slice pedestal mean and the
+//     total pedestal mean (fPedestal). For even slices pedestal
+//     use -fPedestalABoffset.
+//  UInt_t  fNumEvents:
+//   - number of times, the Process was executed (to estimate the error
+//     of pedestal)
+//
+// version 2:
+// ----------
+// added:
+//  fPedestalABoffset   difference between pedestal mean of odd slices and
+//                      the total pedestal mean (fPedestal)
+//  fNumEvents          number of times, the Process was executed
+//                      (to estimate the error of pedestal)
+//
+// version 3:
+// ----------
+// - fValid removed
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalPix.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MPedestalPix);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Default constructor. Calls Clear()
+//
+MPedestalPix::MPedestalPix()
+{
+    Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+//  return fNumEvents>0 ? fPedestalRms/TMath::Sqrt((Float_t)fNumEvents)   : 0;
+//
+Float_t MPedestalPix::GetPedestalError() const
+{
+    return fNumEvents>0 ? fPedestalRms/TMath::Sqrt((Float_t)fNumEvents)   : 0;
+}
+
+// ------------------------------------------------------------------------
+//
+// return fNumEvents>0 ? fPedestalRms/TMath::Sqrt((Float_t)fNumEvents*2) : 0;
+//
+Float_t MPedestalPix::GetPedestalRmsError() const
+{
+    return fNumEvents>0 ? fPedestalRms/TMath::Sqrt((Float_t)fNumEvents*2) : 0;
+}
+
+void MPedestalPix::Print(Option_t *) const
+{
+    *fLog << all << "P=" << fPedestal;
+    if (fPedestalRms>=0)
+        *fLog << " RMS=" << fPedestalRms;
+    if (fPedestalABoffset>=0)
+        *fLog << " AB=" << fPedestalABoffset;
+    if (fNumEvents>0)
+        *fLog << " (N=" << fNumEvents << ")";
+    *fLog << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MPedestalPix::Clear(Option_t *o)
+{
+    fPedestal         = -1;
+    fPedestalRms      = -1;
+    fPedestalABoffset = -1;
+    fNumEvents        =  0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MPedestalPix::Copy(TObject &object) const
+{
+
+  MPedestalPix &pix =  (MPedestalPix&)object;
+
+  pix.fPedestal         = fPedestal         ;
+  pix.fPedestalRms      = fPedestalRms      ;
+  pix.fPedestalABoffset = fPedestalABoffset ;
+  pix.fNumEvents        = fNumEvents;
+}
+
+// ------------------------------------------------------------------------
+//
+// Set all values to 0
+//
+void MPedestalPix::InitUseHists()
+{
+    fPedestal         = 0;
+    fPedestalRms      = 0;
+    fPedestalABoffset = 0;
+    fNumEvents        = 0;
+}
+
+// ------------------------------------------------------------------------
+//
+// Set fPedestal=m, fPedestalRms=r, fPedestalABoffset=offs, fNumEvents=n
+//
+void MPedestalPix::Set(Float_t m, Float_t r, Float_t offs, UInt_t n)
+{
+    fPedestal         = m;
+    fPedestalRms      = r;
+    fPedestalABoffset = offs;
+    fNumEvents        = n;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return kTRUE if pedestal rms is valid (>=0)
+//
+Bool_t MPedestalPix::IsValid() const
+{
+    return fPedestalRms>=0;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalPix.h	(revision 17960)
@@ -0,0 +1,49 @@
+#ifndef MARS_MPedestalPix
+#define MARS_MPedestalPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MPedestalPix : public MParContainer
+{
+private:
+    Float_t fPedestal;         // mean value of pedestal (PMT offset)
+    Float_t fPedestalRms;      // root mean square / sigma  / standard deviation of pedestal
+    Float_t fPedestalABoffset; // the difference between odd slice pedestal mean and total mean
+    UInt_t  fNumEvents;        // number of times, the Process was executed (to estimate the error of pedestal)
+
+public:
+    MPedestalPix();
+
+    void Clear(Option_t *o="");
+    void Copy(TObject &object) const;
+    void Print(Option_t *o="") const;
+    
+    // Using histograms
+    void InitUseHists();
+
+    // Setters
+    void SetPedestal(const Float_t f)         { fPedestal = f; }
+    void SetPedestalRms(const Float_t f)      { fPedestalRms = f; }
+    void SetPedestalABoffset(const Float_t f) { fPedestalABoffset = f; }
+    void SetNumEvents(const UInt_t n)         { fNumEvents = n; }
+
+    void Set(const Float_t m, const Float_t r, const Float_t offs=0, const UInt_t n=0);
+
+    // Getters
+    Float_t GetPedestal()    const { return fPedestal; }
+    Float_t GetPedestalRms() const { return fPedestalRms; }
+    Float_t GetPedestalABoffset() const { return fPedestalABoffset; }
+
+    Float_t GetPedestalError() const;
+    Float_t GetPedestalRmsError() const;
+
+    UInt_t  GetNumEvents() const { return fNumEvents; }
+
+    Bool_t IsValid() const;
+
+    ClassDef(MPedestalPix, 3) // Storage Container for Pedestal information of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtract.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtract.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtract.cc	(revision 17960)
@@ -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, 10/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MPedestalSubtract
+//
+//  This class merges hi- and lo-gain samples into one array and
+//  subtracts the pedestal (including the AB-offset) from the
+//  data and stores the result in MPedestalSubtractedEvt.
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MPedestalSubtractedEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MPedestalSubtract.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MArrayB.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MPedestalSubtractedEvt.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MPedestalSubtract);
+
+using namespace std;
+
+const char *MPedestalSubtract::fgNamePedestalCam           = "MPedestalCam";
+const char *MPedestalSubtract::fgNamePedestalSubtractedEvt = "MPedestalSubtractedEvt";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MPedestalSubtract::MPedestalSubtract(const char *name, const char *title)
+    : fRawEvt(NULL), fPedestals(NULL), fSignal(NULL)
+{
+    fName  = name  ? name  : "MPedestalSubtract";
+    fTitle = title ? title : "Class to subtract pedestal";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedestalSubtractedEvt
+//
+Int_t MPedestalSubtract::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSignal = (MPedestalSubtractedEvt*)pList->FindCreateObj("MPedestalSubtractedEvt");//, AddSerialNumber(fNamePedestalSubtractedEvt));
+    if (!fSignal)
+        return kFALSE;
+
+    if (fPedestals)
+    {
+        *fLog << inf << "Pedestals given by pointer will be subtracted." << endl;
+        return kTRUE;
+    }
+
+    if (fNamePedestalCam.IsNull())
+    {
+        *fLog << inf << "No name for MPedestalCam given, pedestal subtraction will be skipped." << endl;
+        return kTRUE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber(fNamePedestalCam), "MPedestalCam");
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber(fNamePedestalCam) << " [MPedestalCam] not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Pedestals " << fNamePedestalCam << " will be subtracted." << endl;
+
+    return kTRUE;
+}
+
+void MPedestalSubtract::Memcpy(void *dest, void *src, Int_t cnt) const
+{
+    if (fRawEvt->GetNumBytesPerSample()==2)
+        memcpy(dest, src, cnt*2);
+    else
+    {
+        const Byte_t *b = (Byte_t*)src;
+        for (USample_t *ptr=(USample_t*)dest; ptr<(USample_t*)dest+cnt; ptr++)
+            *ptr = *b++;
+    }
+}
+
+Bool_t MPedestalSubtract::ReInit(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MPedestalSubtract::Process()
+{
+    // Please note:
+    //   - for data with only hi-gain samples numl is 0
+    //   - for data with hi- and lo-gain samples
+    //     numl is 0 if read from a raw-data file or a new MC root-file(?)
+    //     numl is not 0 if read from an old MC root-file
+
+    // Total number of samples
+    const Int_t numh = fRawEvt->GetNumHiGainSamples();
+    const Int_t numl = fRawEvt->GetNumLoGainSamples();
+
+    // Check if event is empty (presumably MC event -- sanity check)
+    if (numh+numl==0)
+        return kCONTINUE;
+
+    // Check for consistency (our simulation can do weird things!)
+    if (numh+numl!=fRunHeader->GetNumSamplesHiGain()+fRunHeader->GetNumSamplesLoGain())
+    {
+        *fLog << err << "MPedestalSubtract::Process: ERROR - Number of samples in event ";
+        *fLog << "(hi+lo=" << numh+numl << ")" << endl << " doesn't match number in run-header ";
+        *fLog << "(" << fRunHeader->GetNumSamplesHiGain()+fRunHeader->GetNumSamplesLoGain() << ")" << endl;
+        *fLog << " In case you are processing real data you have just found a bug." << endl;
+        *fLog << " If you process Monte Carlo data, it means probably that the length" << endl;
+        *fLog << " of the arrays in MRawEvtData are inconsistent with the run-header." << endl;
+        return kERROR;
+    }
+
+    // Get scale between FADC units and 256 ;-)
+    const UInt_t scale = fRawEvt->GetScale();
+
+    // initialize fSignal
+    fSignal->InitSamples(numh+numl);//, fRawEvt->GetNumPixels(), numh+numl);
+
+    // iterate over all pixels
+    MRawEvtPixelIter pixel(fRawEvt);
+    while (pixel.Next())
+    {
+        // Get index ofthis pixel
+        const Int_t pixidx = pixel.GetPixelId();
+
+        if (pixidx>=fSignal->GetNumPixels())
+        {
+            *fLog << err << "ERROR - Pixel index " << pixidx << " out of bounds... abort." << endl;
+            *fLog <<        "        Index from MRawEvtPixelIter is " << pixidx << ", max in MPedestalSubtractedEvt is " << fSignal->GetNumPixels() << endl;
+            return kERROR;
+        }
+        // Get pointer were to store merged raw data
+        USample_t *sample = fSignal->GetSamplesRaw(pixidx);
+
+        // copy hi- and lo-gains samples together
+        Memcpy(sample,      pixel.GetHiGainSamples(), numh);
+        Memcpy(sample+numh, pixel.GetLoGainSamples(), numl);
+
+        // start of destination array, end of hi-gain destination array
+        // and start of hi-gain samples
+        Float_t *beg = fSignal->GetSamples(pixidx);
+        Float_t *end = beg + fSignal->GetNumSamples();
+
+        const USample_t *src = sample;
+
+        // if no pedestals are given just convert the data into
+        // floats and we are finished
+        if (!fPedestals)
+        {
+            while (beg<end)
+                *beg++ = *src++;//Float_t(*src++)/scale;
+            continue;
+        }
+
+        // get pedestal information for this pixel
+        const MPedestalPix &pedpix = (*fPedestals)[pixidx];
+
+        // pedestal information
+        const Int_t   ab  = pixel.HasABFlag() ? 1 : 0;
+        const Float_t ped = pedpix.GetPedestal();
+
+        // determine with which pedestal (+/- AB offset) to start
+        const Bool_t  swap    = (ab&1)==1;
+        const Float_t offh    = swap ? -pedpix.GetPedestalABoffset() : pedpix.GetPedestalABoffset();
+        const Float_t mean[2] = { ped + offh, ped - offh };
+
+        // Copy hi-gains into array and substract pedestal
+        // FIXME: Shell we really subtract the pedestal from saturating slices???
+        for (Float_t *ptr=beg; ptr<end; ptr++)
+            *ptr = Float_t(*src++)/scale - mean[(ptr-beg)&1];
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtract.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtract.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtract.h	(revision 17960)
@@ -0,0 +1,44 @@
+#ifndef MARS_MPedestalSubtract
+#define MARS_MPedestalSubtract
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawRunHeader;
+class MRawEvtData;
+class MPedestalCam;
+class MPedestalSubtractedEvt;
+
+class MPedestalSubtract : public MTask
+{
+private:
+    static const char *fgNamePedestalCam;            //! "MPedestalCam"
+    static const char *fgNamePedestalSubtractedEvt;  //! "MPedestalSubtractedEvt"
+
+    MRawRunHeader          *fRunHeader;      //! Run Header
+    MRawEvtData            *fRawEvt;         //! Input Raw data
+    MPedestalCam           *fPedestals;      //! Pedestals of all pixels in the camera
+    MPedestalSubtractedEvt *fSignal;         //! Output container
+
+    TString  fNamePedestalCam;               // Name of the 'MPedestalCam' container
+    TString  fNamePedestalSubtractedEvt;     // Name of the 'MPedestalSubtractedEvt' container
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+    void Memcpy(void *sample, void *ptr, Int_t cnt) const;
+
+public:
+    MPedestalSubtract(const char *name=NULL, const char *title=NULL);
+
+    void SetPedestalCam(MPedestalCam *pedcam) { fPedestals = pedcam; }
+    void SetNamePedestalCam(const char *name=fgNamePedestalCam) { fNamePedestalCam  = name; }
+
+    void SetNamePedestalSubtractedEvt(const char *name=fgNamePedestalSubtractedEvt) { fNamePedestalSubtractedEvt = name; }
+
+    ClassDef(MPedestalSubtract, 0)   // Class to subtract pedestal including AB-noise
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtractedEvt.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtractedEvt.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtractedEvt.cc	(revision 17960)
@@ -0,0 +1,289 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPedestalSubtractedEvt
+//
+//  Storage container to store the raw FADC values.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalSubtractedEvt.h"
+
+#include <TMath.h>
+
+#include "MLogManip.h"
+
+ClassImp(MPedestalSubtractedEvt);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize number of samples (per pixel) and number of pixels.
+//
+// Initialize the correct length of fSamples and fSamplesRaw
+//
+// And reset its contents to 0.
+//
+void MPedestalSubtractedEvt::InitSamples(UInt_t samples, UInt_t pixels)
+{
+    fNumSamples = samples;
+
+    if (pixels>0)
+        fNumPixels = pixels;
+
+    fSamples.Set(fNumPixels*fNumSamples);
+    fSamplesRaw.Set(fNumPixels*fNumSamples);
+
+    fSamples.Reset();
+    fSamplesRaw.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the first slice with subtracted pedestal of
+// the samples of the pixel with given pixel-index. If the number
+// exceeds the number of pixels NULL is returned.
+//
+// The user is responsible not to exceed the slices for one pixel!
+//
+Float_t *MPedestalSubtractedEvt::GetSamples(UInt_t pixel) const
+{
+    return pixel>=fNumPixels ? NULL : fSamples.GetArray()+pixel*fNumSamples;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the first slice of the raw-data samples of the pixel
+// with given pixel-index. If the number exceeds the number of
+// pixels NULL is returned.
+//
+// The user is responsible not to exceed the slices for one pixel!
+//
+USample_t *MPedestalSubtractedEvt::GetSamplesRaw(UInt_t pixel) const
+{
+    return pixel>=fNumPixels ? NULL : fSamplesRaw.GetArray()+pixel*fNumSamples;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return some information about saturation in the raw-data of pixel idx.
+//
+// The search range is defined by [first,last]. Saturation is considered if
+// contents is >= limit.
+//
+// The number of saturating slices are returned and first/last are filled
+// with the first and last saturating slice index w.r.t. the beginning of
+// the raw-data of this pixel not first.
+//
+// Warning: No range checks and no sanity checks are done!
+//
+Int_t MPedestalSubtractedEvt::GetSaturation(const Int_t idx, Int_t limit, Int_t &first, Int_t &last) const
+{
+    // Determin saturation of hi-gains
+    USample_t *p0 = GetSamplesRaw(idx);
+
+    USample_t *sat0 = 0; // first saturating slice
+    USample_t *sat1 = 0; // last  saturating slice
+
+    Int_t num = 0;
+
+    const USample_t *end = p0+last;
+    for (USample_t *ptr=p0+first; ptr<=end; ptr++)
+    {
+        if (*ptr>=limit)
+        {
+            sat1 = ptr;
+            if (!sat0)
+                sat0 = ptr;
+            num++;
+        }
+    }
+
+    last  = sat1 ? sat1-p0 : -1;
+    first = sat0 ? sat0-p0 : -1;
+
+    return num;
+}
+
+void MPedestalSubtractedEvt::GetStat(const Int_t idx, Float_t &mean, Float_t &rms) const
+{
+    if (fNumSamples<20)
+        return;
+
+    // Get pointer to first slice to be considered
+    Float_t const *sam = GetSamples(idx);
+    Float_t const *beg = sam;
+
+    Double_t sum  = 0;
+    Double_t sum2 = 0;
+
+    for (const Float_t *ptr=beg+10; ptr<sam+fNumSamples-10; ptr++)
+    {
+        sum  += *ptr;
+        sum2 += *ptr * *ptr;
+    }
+
+    sum  /= fNumSamples-20;
+    sum2 /= fNumSamples-20;
+
+    mean = sum;
+    rms  = TMath::Sqrt(sum2 - sum * sum);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the maximum of the pedestal subtracted slices [first,last] of
+// pixel with index idx.
+//
+// The position returned is the index of the position of the pedestal
+// subtracted maximum w.r.t. to first.
+// The value returned is the maximum corresponding to this index.
+//
+// Warning: No range checks and no sanity checks are done!
+//
+Int_t MPedestalSubtractedEvt::GetMax(const Int_t idx, const Int_t first, const Int_t last, Float_t &val) const
+{
+    // Get pointer to first slice to be considered
+    Float_t const *sam = GetSamples(idx);
+
+    Float_t const *beg = sam+first;
+
+    // The best information so far: the first slice is the maximum
+    const Float_t *max = beg;
+
+    for (const Float_t *ptr=beg+1; ptr<=sam+last; ptr++)
+        if (*ptr>*max)
+            max = ptr;
+
+    val = *max;
+    return max-beg;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the maximum of the raw slices [first,last] of pixel with index idx.
+//
+// The position returned is the index of the position of the raw-data
+// w.r.t. to first.
+// The value returned is the maximum corresponding to this index.
+//
+// Warning: No range checks and no sanity checks are done!
+//
+Int_t MPedestalSubtractedEvt::GetRawMax(const Int_t idx, const Int_t first, const Int_t last, UInt_t &val) const
+{
+    // Get pointer to first slice to be considered
+    USample_t const *sam = GetSamplesRaw(idx);
+
+    USample_t const *beg = sam+first;
+
+    // The best information so far: the first slice is the maximum
+    const USample_t *max = beg;
+
+    for (const USample_t *ptr=beg+1; ptr<=sam+last; ptr++)
+        if (*ptr>*max)
+            max = ptr;
+
+    val = *max;
+    return max-beg;
+}
+
+void MPedestalSubtractedEvt::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << endl;
+    *fLog << " Num Pixels:  " << fNumPixels << " (" << fNumSamples << " samples)" << endl;
+    *fLog << " Samples raw:" << hex << endl;;
+    for (UInt_t idx=0; idx<fNumPixels; idx++)
+    {
+        *fLog << setw(4) << dec << idx << hex << ":";
+        for (UInt_t i=0; i<fNumSamples; i++)
+            *fLog << " " << fSamplesRaw[idx*fNumSamples+i];
+        *fLog << endl;
+    }
+    *fLog << dec << endl;
+    *fLog << " Samples:" << endl;;
+    for (UInt_t idx=0; idx<fNumPixels; idx++)
+    {
+        *fLog << setw(4) << idx << ":";
+        for (UInt_t i=0; i<fNumSamples; i++)
+            *fLog << " " << fSamples[idx*fNumSamples+i];
+        *fLog << endl;
+    }
+    *fLog << endl;
+}
+
+Bool_t MPedestalSubtractedEvt::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    switch (type)
+    {
+    case 0:
+    case 1:
+        {
+            Float_t mean, rms;
+            GetStat(idx, mean, rms);
+            val = type==0 ? mean : rms;
+        }
+        break;
+    case 2:
+        {
+            Float_t flt;
+            GetMaxPos(idx, flt);
+            val = flt;
+        }
+        break;
+    }
+
+    return kTRUE;
+}
+
+/*
+#include <TSpline.h>
+#include "MArrayD.h"
+void  MPedestalSubtractedEvt::InterpolateSaturation(const Int_t idx, Int_t limit, Int_t first, Int_t last) const
+{
+    MArrayD x(GetNumSamples());
+    MArrayD y(GetNumSamples());
+
+    Float_t *s = GetSamples(idx);
+
+    Int_t n = 0;
+    for (unsigned int i=0; i<GetNumSamples(); i++)
+    {
+        if (s[i]>limit)
+            continue;
+        x[n] = i;
+        y[n] = s[i];
+        n++;
+    }
+
+    TSpline5 sp("", x.GetArray(), y.GetArray(), n);
+
+    for (unsigned int i=0; i<GetNumSamples(); i++)
+    {
+        if (s[i]>limit)
+            s[i] = sp.Eval(i);
+    }
+}
+*/
Index: branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtractedEvt.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtractedEvt.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/MPedestalSubtractedEvt.h	(revision 17960)
@@ -0,0 +1,127 @@
+#ifndef MARS_MPedestalSubtractedEvt
+#define MARS_MPedestalSubtractedEvt
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef MARS_MArrayS
+#include "MArrayS.h"
+#endif
+
+typedef UShort_t USample_t;
+
+class MPedestalSubtractedEvt : public MParContainer, public MCamEvent
+{
+private:
+    MArrayF fSamples;         // list of all samples with pedestal subtracted
+    MArrayS fSamplesRaw;      // list of all samples (raw)
+
+    UInt_t fNumSamples;       // number of samples per pixel
+    UInt_t fNumPixels;        // number of pixels
+
+public:
+    MPedestalSubtractedEvt(const char *name=NULL, const char *title=NULL)
+        : fNumSamples(0), fNumPixels(0)
+    {
+        fName = name ? name : "MPedestalSubtractedEvt";
+        fTitle = title ? title : "";
+    }
+
+    void InitSize(const UInt_t i) { fNumPixels=i; }
+    void InitSamples(UInt_t samples, UInt_t pixels=0);
+
+    Float_t   *GetSamples(UInt_t pixel=0) const;
+    USample_t *GetSamplesRaw(UInt_t pixel=0) const;
+
+    UInt_t   GetNumSamples() const { return fNumSamples; }
+    UShort_t GetNumPixels() const  { return fNumPixels; }
+
+    Int_t GetSaturation(const Int_t idx, Int_t limit, Int_t &first, Int_t &last) const;
+    //void  InterpolateSaturation(const Int_t idx, Int_t limit, Int_t first, Int_t last) const;
+
+    Int_t GetMax(const Int_t pixidx, const Int_t first, const Int_t last, Float_t &val) const;
+    Int_t GetMax(const Int_t pixidx, Float_t &val) const
+    {
+        return GetMax(pixidx, 0, fNumSamples-1, val);
+    }
+    Int_t GetMaxPos(const Int_t pixidx, const Int_t first, const Int_t last) const
+    {
+        Float_t val;
+        return GetMax(pixidx, first, last, val);
+    }
+    Int_t GetMaxPos(const Int_t pixidx, Float_t &val) const
+    {
+        return GetMax(pixidx, 0, fNumSamples-1, val);
+    }
+
+    Int_t GetMaxPos(const Int_t pixidx) const
+    {
+        Float_t val;
+        return GetMax(pixidx, 0, fNumSamples-1, val);
+    }
+
+    Int_t GetRawMax(const Int_t idx, const Int_t first, const Int_t last, UInt_t &val) const;
+    Int_t GetRawMax(const Int_t pixidx, UInt_t &val) const
+    {
+        return GetRawMax(pixidx, 0, fNumSamples-1, val);
+    }
+    Int_t GetRawMaxPos(const Int_t pixidx, const Int_t first, const Int_t last) const
+    {
+        UInt_t val;
+        return GetRawMax(pixidx, first, last, val);
+    }
+    Int_t GetRawMaxPos(const Int_t pixidx, UInt_t &val) const
+    {
+        return GetRawMax(pixidx, 0, fNumSamples-1, val);
+    }
+
+    Int_t GetRawMaxPos(const Int_t pixidx) const
+    {
+        UInt_t val;
+        return GetRawMax(pixidx, 0, fNumSamples-1, val);
+    }
+
+    UInt_t GetRawMaxVal(const Int_t idx, const Int_t first, const Int_t last) const
+    {
+        UInt_t val;
+        GetRawMax(idx, first, last, val);
+        return val;
+    }
+
+    void GetStat(const Int_t idx, Float_t &mean, Float_t &rms) const;
+
+    Int_t GetSaturation(const Int_t pixidx, Int_t limit) const
+    {
+        Int_t first=0;
+        Int_t last=fNumSamples-1;
+        return GetSaturation(pixidx, limit, first, last);
+    }
+
+    Int_t GetIntegralRaw(Int_t idx, Int_t first, Int_t last) const
+    {
+        USample_t *ptr = GetSamplesRaw(idx);
+
+        const USample_t *end = ptr + last - first + 1;
+
+        Int_t sum = 0;
+        while (ptr<end)
+            sum += *ptr++;
+
+        return sum;
+    }
+
+    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) const { }
+
+    ClassDef(MPedestalSubtractedEvt, 6) //Container to store the raw Event Data
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpedestal/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/Makefile	(revision 17960)
@@ -0,0 +1,54 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Pedestal
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mraw -I../mmc -I../mgeom \
+           -I../msignal -I../manalysis -I../mbadpixels -I../mhcalib \
+           -I../mhbase -I../mcalib -I../mtrigger -I../mcore
+# MCamEvent
+# MMcPedestalCopy   (MRawRunHeader)
+# MMcPedestalCopy   (MMcRunHeader)
+# MMcPedestalNSBAdd (MGeomCam)
+# MPedCalcPedRun    (MExtractedSignal)
+# MPedPhotCalc      (MCerPhotEvt)
+# MPedPhotCalc      (MBadPixelsCam)
+
+SRCFILES = MMcPedestalCopy.cc \
+           MMcPedestalNSBAdd.cc \
+	   MExtractPedestal.cc \
+           MPedCalcPedRun.cc \
+	   MPedCalcFromLoGain.cc \
+           MPedPhotCalc.cc \
+           MPedPhotCam.cc \
+           MPedPhotPix.cc \
+           MPedestalCam.cc \
+	   MPedestalPix.cc \
+           MHPedestalCor.cc \
+           MPedestalSubtract.cc \
+           MPedestalSubtractedEvt.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mpedestal/PedestalIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/PedestalIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/PedestalIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mpedestal/PedestalLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mpedestal/PedestalLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpedestal/PedestalLinkDef.h	(revision 17960)
@@ -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 MMcPedestalCopy+;
+#pragma link C++ class MMcPedestalNSBAdd+;
+
+#pragma link C++ class MPedPhotCalc+;
+#pragma link C++ class MPedPhotCam+;
+#pragma link C++ class MPedPhotPix+;
+
+#pragma link C++ class MExtractPedestal+;
+#pragma link C++ class MPedCalcPedRun+;
+#pragma link C++ class MPedCalcFromLoGain+;
+#pragma link C++ class MPedestalCam+;
+#pragma link C++ class MPedestalPix+;
+#pragma link C++ class MPedestalSubtract+;
+#pragma link C++ class MPedestalSubtractedEvt+;
+
+#pragma link C++ class MHPedestalCor+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MHPointing.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MHPointing.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MHPointing.cc	(revision 17960)
@@ -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, 05/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPointing
+//
+// Display drive information
+//
+// Class Version 2:
+// ----------------
+//
+//  + TGraph fNumStarsCor; // Number of correlated stars identified by starguider
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHPointing.h"
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+#include <TGaxis.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MTime.h"
+#include "MAstro.h"
+
+#include "MReportDrive.h"
+#include "MReportStarguider.h"
+
+ClassImp(MHPointing);
+
+using namespace std;
+
+void MHPointing::ResetGraph(TGraph &g) const
+{
+    g.Set(1);
+    g.SetPoint(0, 0, 0); // Dummy Point
+    g.SetEditable();     // Used as flag: First point? yes/no
+}
+
+void MHPointing::InitGraph(TGraph &g) const
+{
+    ResetGraph(g);
+    g.SetMarkerStyle(kFullDotMedium);
+}
+
+void MHPointing::AddPoint(TGraph &g, Double_t x, Double_t y) const
+{
+    if (g.IsEditable())
+    {
+        g.RemovePoint(0);
+        g.SetEditable(kFALSE);
+    }
+
+    g.SetPoint(g.GetN(), x, y);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHPointing::MHPointing(const char *name, const char *title)
+: /*fTime(0),*/ fReportCosy(0), fReportSG(0)
+{
+    fName  = name  ? name  : "MHPointing";
+    fTitle = title ? title : "Graphs for rate data";
+
+    // Init Graphs
+    fDevTimeSG.SetNameTitle("DevSG",         "Absolute deviation of drive (black) and starguider (blue)");
+    fDevTimeCosy.SetNameTitle("DevCosy",     "Cosy deviation");
+    fBrightness.SetNameTitle("Brightness",   "Arbitrary Sky Brightness (black), No. of stars identified by starguider (blue)");
+    fNumStars.SetNameTitle("NumStars",       "Number of stars identified by starguider");
+    fNumStarsCor.SetNameTitle("NumStarsCor", "Number of stars correlated by starguider");
+    fDevZd.SetNameTitle("DevZd",             "Starguider deviation Zd (blue), Az (black)");
+    fDevAz.SetNameTitle("DevAz",             "Starguider Deviation Az");
+    fPosZd.SetNameTitle("PosZd",             "Nominal position Zd");
+    //fPosAz.SetNameTitle("PosZd",          "Position Az");
+
+    InitGraph(fDevTimeSG);
+    InitGraph(fDevTimeCosy);
+    InitGraph(fBrightness);
+    InitGraph(fNumStars);
+    InitGraph(fNumStarsCor);
+    InitGraph(fDevZd);
+    InitGraph(fDevAz);
+    InitGraph(fPosZd);
+    //InitGraph(fPosAz);
+
+    fDevTimeSG.SetMarkerColor(kBlue);
+    fDevZd.SetMarkerColor(kBlue);
+    fNumStars.SetMarkerColor(kBlue);
+    fNumStarsCor.SetMarkerColor(kMagenta);
+    //fPosAz.SetMarkerColor(kBlue);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHPointing::SetupFill(const MParList *plist)
+{
+    //fTime = (MTime*)plist->FindObject("MTime");
+    //if (!fTime)
+    //{
+    //    *fLog << warn << "MTime not found... abort." << endl;
+    //    return kFALSE;
+    //}
+    fReportSG = (MReportStarguider*)plist->FindObject("MReportStarguider");
+    if (!fReportSG)
+        *fLog << warn << "MReportStarguider not found..." << endl;
+
+    fReportCosy = (MReportDrive*)plist->FindObject("MReportDrive");
+    if (!fReportCosy)
+        *fLog << warn << "MReportDrive not found..." << endl;
+
+    // Reset Graphs
+    ResetGraph(fDevTimeSG);
+    ResetGraph(fDevTimeCosy);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MMuonCalibPar and
+// MMuonSearchPar container.
+//
+Int_t MHPointing::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MTime *t = dynamic_cast<const MTime*>(par);
+    if (!t)
+    {
+        *fLog << err <<"MHPointing::Fill - ERROR: MTime not given as argument... abort." << endl;
+        return kERROR;
+    }
+
+    const Double_t tm = t->GetAxisTime();
+
+    if (t->GetName()==(TString)"MTimeStarguider")
+    {
+        if (!fReportSG)
+        {
+            *fLog << err << "ERROR: fReportSG==NULL... abort." << endl;
+            return kERROR;
+        }
+
+        // Check for old files
+        if (fReportSG->GetSkyBrightness()>0)
+        {
+            AddPoint(fBrightness,  tm, fReportSG->GetSkyBrightness());
+            AddPoint(fNumStars,    tm, fReportSG->GetNumIdentifiedStars());
+            AddPoint(fNumStarsCor, tm, fReportSG->GetNumCorrelatedStars());
+        }
+
+        const Bool_t zdok     = TMath::Abs(fReportSG->GetDevZd())<30;
+        const Bool_t azok     = TMath::Abs(fReportSG->GetDevAz())<90;
+
+        const Double_t devzd  = fReportSG->GetDevZd();
+        const Double_t devaz  = fReportSG->GetDevAz();
+
+        if (zdok && azok)
+            AddPoint(fDevTimeSG, tm, fReportSG->GetDevAbs());
+        if (zdok)
+            AddPoint(fDevZd, tm, devzd);
+        if (azok)
+            AddPoint(fDevAz, tm, devaz);
+        return kTRUE;
+    }
+
+    if (fReportCosy && t->GetName()==(TString)"MTimeDrive")
+    {
+        if (!fReportCosy)
+        {
+            *fLog << err << "ERROR: fReportCosy==NULL... abort." << endl;
+            return kERROR;
+        }
+
+        AddPoint(fDevTimeCosy, tm, fReportCosy->GetAbsError()*60);
+        if (fPosZd.GetY()[fPosZd.GetN()-1] != fReportCosy->GetNominalZd())
+            AddPoint(fPosZd, tm, fReportCosy->GetNominalZd());
+        //if (fPosAz.GetY()[fPosAz.GetN()-1] != fReportCosy->GetNominalAz())
+        //    AddPoint(fPosAz, tm, fReportCosy->GetNominalAz());
+        return kTRUE;
+    }
+
+    return kTRUE;
+}
+
+void MHPointing::DrawGraph(TGraph &g, const char *y) const
+{
+    // This is not done automatically anymore since root 5.12/00
+    // and it is necessary to force a proper update of the axis.
+    TH1 *h = g.GetHistogram();
+    if (h)
+    {
+        delete h;
+        g.SetHistogram(0);
+        h = g.GetHistogram();
+    }
+    if (h)
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetLabelSize(0.033);
+        axe->SetTimeFormat("%H:%M %F1995-01-01 00:00:00 GMT");
+        axe->SetTimeDisplay(1);
+        axe->SetTitle("Time");
+        if (y)
+            h->SetYTitle(y);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Update position of an axis on the right side of the histogram
+//
+void MHPointing::UpdateRightAxis(TGraph &g1, TGraph &g2) const
+{
+    TH1 &h1 = *g1.GetHistogram();
+    TH1 &h2 = *g2.GetHistogram();
+
+    const Double_t max = TMath::Max(h1.GetMaximum(), h2.GetMaximum());
+    if (max==0)
+        return;
+
+    TGaxis *axis = (TGaxis*)gPad->FindObject("RightAxis");
+    if (!axis)
+        return;
+
+    axis->SetX1(g1.GetXaxis()->GetXmax());
+    axis->SetX2(g1.GetXaxis()->GetXmax());
+    axis->SetY1(gPad->GetUymin());
+    axis->SetY2(gPad->GetUymax());
+    axis->SetWmax(max);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw an axis on the right side of the histogram
+//
+
+void MHPointing::DrawRightAxis(const char *title) const
+{
+    TGaxis *axis = new TGaxis(gPad->GetUxmax(), gPad->GetUymin(),
+                              gPad->GetUxmax(), gPad->GetUymax(),
+                              0, 1, 510, "+L");
+    axis->SetName("RightAxis");
+    axis->SetTitle(title);
+    axis->SetTitleOffset(0.9);
+    axis->SetTextColor(kBlue);
+    axis->SetBit(kCanDelete);
+    axis->Draw();
+}
+
+// --------------------------------------------------------------------------
+//
+// This displays the TGraph like you expect it to be (eg. time on the axis)
+// It should also make sure, that the displayed time always is UTC and
+// not local time...
+//
+void MHPointing::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fDevTimeSG.Draw("AP");
+    fDevTimeCosy.Draw("P");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fBrightness.Draw("AP");
+    fNumStars.Draw("P");
+    fNumStarsCor.Draw("P");
+    DrawRightAxis("N");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fDevZd.Draw("AP");
+    fDevAz.Draw("P");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fPosZd.Draw("AP");
+    //fPosAz.Draw("P");
+    //DrawRightAxis("Az [\\circ]");
+}
+
+void MHPointing::Paint(Option_t *o)
+{
+    // If this is set to early the plot remains empty in root 5.12/00
+    if (fDevTimeSG.GetN()>0)
+        fDevTimeSG.SetMinimum(0);
+    if (fDevTimeCosy.GetN()>0)
+        fDevTimeCosy.SetMinimum(0);
+
+
+    if (fBrightness.GetN()>0)
+    {
+        fBrightness.SetMinimum(0);
+        fBrightness.SetMaximum(95);
+    }
+    if (fNumStars.GetN()>0)
+    {
+        fNumStars.SetMinimum(0);
+        fNumStars.SetMaximum(95);
+    }
+    if (fNumStarsCor.GetN()>0)
+    {
+        fNumStarsCor.SetMinimum(0);
+        fNumStarsCor.SetMaximum(95);
+    }
+
+    DrawGraph(fDevTimeSG,   "\\Delta [arcmin]");
+    DrawGraph(fDevTimeCosy, "\\Delta [arcmin]");
+    DrawGraph(fBrightness,  "Brightness [au]");
+    DrawGraph(fNumStars,    "N");
+    DrawGraph(fDevZd,       "\\Delta [arcmin]");
+    DrawGraph(fDevAz,       "\\Delta [arcmin]");
+    DrawGraph(fPosZd,       "Zd [\\circ]");
+    //DrawGraph(fPosAz,       "Az [\\circ]");
+
+    TVirtualPad *pad = gPad;
+
+    pad->cd(2);
+    if (gPad)
+    {
+        fNumStars.GetHistogram()->GetYaxis()->SetTitleColor(kBlue);
+        UpdateRightAxis(fNumStars, fNumStarsCor);
+    }
+/*
+    pad->cd(4);
+    if (gPad)
+    {
+        fPosAz.GetHistogram()->GetYaxis()->SetTitleColor(kBlue);
+        UpdateRightAxis(fPosAz);
+    }*/
+}
Index: branches/Mars_McMismatchStudy/mpointing/MHPointing.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MHPointing.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MHPointing.h	(revision 17960)
@@ -0,0 +1,56 @@
+#ifndef MARS_MHPointing
+#define MARS_MHPointing
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TGraph
+#include <TGraph.h>
+#endif
+
+class MTime;
+class MReportDrive;
+class MReportStarguider;
+
+class MHPointing : public MH
+{
+private:
+    MReportDrive      *fReportCosy;  //!
+    MReportStarguider *fReportSG;    //!
+
+    TGraph             fDevTimeSG;   // Starguider deviation versus time
+    TGraph             fDevTimeCosy; // Drive deviation versus time
+
+    TGraph             fBrightness;  // Arbitrary sky brightness
+
+    TGraph             fNumStars;    // Number of stars identified by starguider
+    TGraph             fNumStarsCor; // Number of correlated stars identified by starguider
+
+    TGraph             fDevZd;       // Starguider deviation Zd
+    TGraph             fDevAz;       // Starguider deviation Az
+
+    TGraph             fPosZd;       // Position Zd
+    //TGraph             fPosAz;       // Position Az
+
+    void ResetGraph(TGraph &g) const;
+    void InitGraph(TGraph &g) const;
+    void AddPoint(TGraph &g, Double_t x, Double_t y) const;
+    void DrawGraph(TGraph &g, const char *y=0) const;
+    void UpdateRightAxis(TGraph &g1, TGraph &g2) const;
+    void DrawRightAxis(const char *title) const;
+
+public:
+    MHPointing(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHPointing, 2) // Histogram to display tracking/pointing information
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mpointing/MHSrcPosCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MHSrcPosCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MHSrcPosCam.cc	(revision 17960)
@@ -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, 2/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHSrcPosCam
+//
+//
+// FIXME: Use ReInit...
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHSrcPosCam.h"
+
+#include <TVector2.h>
+#include <TCanvas.h>
+#include <TEllipse.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MParameters.h"
+#include "MPointingPos.h"
+
+#include "MString.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHSrcPosCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHSrcPosCam::MHSrcPosCam(Float_t offset, const char *name, const char *title)
+    : fTimeEffOn(NULL), fEffOnTime(NULL), fSourcePos(NULL), fGeom(NULL),
+    fPositions("TVector2", 50000), fWobbleOffset(offset)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHSrcPosCam";
+    fTitle = title ? title : "Histogram for source position distribution";
+
+    fHist.SetName("SourcePos");
+    fHist.SetTitle("Source position distribution in camera coordinates");
+    fHist.SetXTitle("dx [\\circ]");
+    fHist.SetYTitle("dy [\\circ]");
+    fHist.SetZTitle("T_{eff} [s]");
+    fHist.SetDirectory(NULL);
+    fHist.UseCurrentStyle();
+    fHist.GetXaxis()->CenterTitle();
+    fHist.GetYaxis()->CenterTitle();
+    fHist.SetContour(99);
+
+    const Float_t x = offset>0 ? offset+0.0499 : offset/2+0.0499;
+    const Int_t   n = offset>0 ? 101           : 51;
+
+    const MBinning bins(n, -x, x); // bin=0.01ø  ~0.5SE
+
+    MH::SetBinning(fHist, bins, bins);
+}
+
+Bool_t MHSrcPosCam::SetupFill(const MParList *pl)
+{
+    fGeom = (MGeomCam*)pl->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "ERROR - MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTimeEffOn = (MTime*)      pl->FindObject("MTimeEffectiveOnTime");
+    fEffOnTime = (MParameterD*)pl->FindObject("MEffectiveOnTime");
+
+    if (!fTimeEffOn && fEffOnTime)
+    {
+        *fLog << err << "ERROR - MTimeEffOnTime not found... aborting." << endl;
+        return kFALSE;
+    }
+    if (!fEffOnTime && fTimeEffOn)
+    {
+        *fLog << err << "ERROR - MEffectiveOnTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fEffOnTime && !fTimeEffOn)
+        *fLog << inf << "Neither MTimeEffOnTime nor MEffectiveOnTime found... assuming MC." << endl;
+    else
+        fTimeLastEffOn = MTime();
+
+    const MPointingPos *pos = (MPointingPos*)pl->FindObject("MSourcePos", "MPointingPos");
+
+    const TString src = pos ? pos->GetString("radec") : "MonteCarlo";
+    fHist.SetTitle(MString::Format("SrcPos distribution in camera: %s", src.Data()));
+
+    fHist.Reset();
+    fNum = 0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// All source positions are buffered until the time of the effective on
+// time time stamp changes. Then the observation time is split into
+// identical parts and the histogram is filled by these events. The
+// effective on time time stamp is reset and the buffered source positions
+// deleted.
+//
+Int_t MHSrcPosCam::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MSrcPosCam *cam = dynamic_cast<const MSrcPosCam*>(par);
+    if (!cam)
+    {
+        *fLog << err << dbginf << "Got no MSrcPosCam as argument of Fill()..." << endl;
+        return kERROR;
+    }
+
+    if (!fEffOnTime)
+    {
+        const TVector2 v(cam->GetXY()*fGeom->GetConvMm2Deg());
+        fHist.Fill(v.X(), v.Y(), w);
+        return kTRUE;
+    }
+
+    // Increase array size if necessary
+    if (fNum==fPositions.GetSize())
+        fPositions.Expand(fNum*2);
+
+    // buffer position into array (could be speed up a little bit more
+    // by using ExpandCreate and memcpy)
+    new (fPositions[fNum++]) TVector2(cam->GetXY()*fGeom->GetConvMm2Deg());
+
+    // Check if there is a new effective on time
+    if (fTimeLastEffOn==MTime())
+        fTimeLastEffOn=*fTimeEffOn;
+
+    if (fTimeLastEffOn == *fTimeEffOn)
+        return kTRUE;
+
+    // Split the observation time to all buffered events
+    const Double_t scale = fEffOnTime->GetVal()/fNum;
+
+    // Fill histogram from array
+    for (int i=0; i<fNum; i++)
+    {
+        const TVector2 &v = (TVector2&)*fPositions[i];
+        fHist.Fill(v.X(), v.Y(), scale*w);
+    }
+
+    // reset time stamp and remove all buffered positions
+    fTimeLastEffOn = *fTimeEffOn;
+    fNum = 0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+void MHSrcPosCam::Paint(Option_t *)
+{
+    MH::SetPalette("pretty", 99);
+}
+
+// --------------------------------------------------------------------------
+//
+void MHSrcPosCam::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    //pad->Divide(2,2);
+
+    gPad->SetLeftMargin(0.25);
+    gPad->SetRightMargin(0.25);
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    AppendPad();
+
+    fHist.Draw("colz");
+
+    if (fHist.GetXaxis()->GetXmax()>0.5)
+    {
+        // Typical wobble distance +/- 1 shaftencoder step
+        TEllipse el;
+        el.SetFillStyle(0);
+        el.SetLineColor(kBlack);
+        el.SetLineStyle(kDashed);
+        el.DrawEllipse(0, 0, fWobbleOffset, 0, 0, 360, 0);
+        el.SetLineColor(17);
+        el.DrawEllipse(0, 0, fWobbleOffset-0.022, 0, 0, 360, 0);
+        el.DrawEllipse(0, 0, fWobbleOffset+0.022, 0, 0, 360, 0);
+    }
+}
+
Index: branches/Mars_McMismatchStudy/mpointing/MHSrcPosCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MHSrcPosCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MHSrcPosCam.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHSrcPosCam
+#define MARS_MHSrcPosCam
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class MGeomCam;
+class MParList;
+class MParameterD;
+class MPointingPos;
+
+class MHSrcPosCam : public MH
+{
+private:
+    TH2D          fHist;           // Histogram of observation time vs source position
+
+    MTime         fTimeLastEffOn;  //! Last time stamp of effective on time
+    MTime        *fTimeEffOn;      //! Current effective on time
+    MParameterD  *fEffOnTime;      //! Effective on time
+    MPointingPos *fSourcePos;      //! Pointing position of the telescope
+    MGeomCam     *fGeom;           //! Conversion from mm to deg
+
+    TClonesArray  fPositions;      //! Buffer to store source positions
+    Int_t         fNum;            //! Position in array
+
+    Float_t       fWobbleOffset;
+
+public:
+    MHSrcPosCam(Float_t wobble=0.4, const char *name=NULL, const char *title=NULL);
+
+    // MH
+    Bool_t SetupFill(const MParList *pl);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+
+    // MHSrcPosCam
+    const TH2D &GetHist() const { return fHist; }
+          TH2D &GetHist()       { return fHist; }
+
+    // TObject
+    void Paint(Option_t *option="");
+    void Draw(Option_t *option="");
+
+    ClassDef(MHSrcPosCam, 1) // Histogram for source position distribution
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MPointing.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointing.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointing.cc	(revision 17960)
@@ -0,0 +1,840 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointing
+// =========
+//
+// This is the class used for the pointing correction done in the MAGIC
+// drive software cosy. NEVER CHANGE IT WITHOUT CONTACTING THE AUTHOR FIRST!
+//
+// Variables/Coefficients
+// ----------------------
+//
+//    Double_t fIe   ; // [rad] Index Error in Elevation
+//    Double_t fIa   ; // [rad] Index Error in Azimuth
+//
+//    Double_t fFlop ; // [rad] Vertical Sag
+//     * do not use if not data: Zd<0
+//
+//    Double_t fNpae ; // [rad] Az-El Nonperpendicularity
+//
+//    Double_t fCa   ; // [rad] Left-Right Collimation Error
+//
+//    Double_t fAn   ; // [rad] Azimuth Axis Misalignment (N-S)
+//    Double_t fAw   ; // [rad] Azimuth Axis Misalignment (E-W)
+//
+//    Double_t fTf   ; // [rad] Tube fluxture (sin)
+//     * same as ecec if no data: Zd<0
+//    Double_t fTx   ; // [rad] Tube fluxture (tan)
+//     * do not use with NPAE if no data: Zd<0
+//
+//    Double_t fNrx  ; // [rad] Nasmyth rotator displacement, horizontan
+//    Double_t fNry  ; // [rad] Nasmyth rotator displacement, vertical
+//
+//    Double_t fCrx  ; // [rad] Alt/Az Coude Displacement (N-S)
+//    Double_t fCry  ; // [rad] Alt/Az Coude Displacement (E-W)
+//
+//    Double_t fEces ; // [rad] Elevation Centering Error (sin)
+//    Double_t fAces ; // [rad] Azimuth Centering Error (sin)
+//    Double_t fEcec ; // [rad] Elevation Centering Error (cos)
+//    Double_t fAcec ; // [rad] Azimuth Centering Error (cos)
+//
+//    Double_t fMagic1;// [rad] MAGIC culmination hysteresis
+//    Double_t fMagic2;// [rad] undefined
+//
+//    Double_t fDx;    // [rad] X-offset in camera (for starguider calibration)
+//    Double_t fDy;    // [rad] Y-offset in camera (for starguider calibration)
+//
+//
+//  Class Version 2:
+//  ----------------
+//    + fPx
+//    + fPy
+//    + fDx
+//    + fDy
+//
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MPointing.h"
+
+#include <fstream>
+
+#include <TMinuit.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+
+ClassImp(AltAz);
+ClassImp(ZdAz);
+ClassImp(RaDec);
+ClassImp(MPointing);
+
+using namespace std;
+
+#undef DEBUG
+//#define DEBUG(txt) txt
+#define DEBUG(txt)
+
+void ZdAz::Round()
+{
+    fX = TMath::Nint(fX);
+    fY = TMath::Nint(fY);
+}
+
+void ZdAz::Abs()
+{
+    fX = TMath::Abs(fX);
+    fY = TMath::Abs(fY);
+}
+
+void MPointing::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPointing";
+    fTitle = title ? title : "Pointing correction model for the MAGIC telescope";
+
+    fCoeff = new Double_t*[kNumPar];
+    fNames = new TString[kNumPar];
+    fDescr = new TString[kNumPar];
+
+    fCoeff[kIA]     = &fIa;      fNames[kIA]     = "IA";
+    fCoeff[kIE]     = &fIe;      fNames[kIE]     = "IE";
+    fCoeff[kFLOP]   = &fFlop;    fNames[kFLOP]   = "FLOP";
+    fCoeff[kAN]     = &fAn;      fNames[kAN]     = "AN";
+    fCoeff[kAW]     = &fAw;      fNames[kAW]     = "AW";
+    fCoeff[kNPAE]   = &fNpae;    fNames[kNPAE]   = "NPAE";
+    fCoeff[kCA]     = &fCa;      fNames[kCA]     = "CA";
+    fCoeff[kTF]     = &fTf;      fNames[kTF]     = "TF";
+    fCoeff[kTX]     = &fTx;      fNames[kTX]     = "TX";
+    fCoeff[kECES]   = &fEces;    fNames[kECES]   = "ECES";
+    fCoeff[kACES]   = &fAces;    fNames[kACES]   = "ACES";
+    fCoeff[kECEC]   = &fEcec;    fNames[kECEC]   = "ECEC";
+    fCoeff[kACEC]   = &fAcec;    fNames[kACEC]   = "ACEC";
+    fCoeff[kNRX]    = &fNrx;     fNames[kNRX]    = "NRX";
+    fCoeff[kNRY]    = &fNry;     fNames[kNRY]    = "NRY";
+    fCoeff[kCRX]    = &fCrx;     fNames[kCRX]    = "CRX";
+    fCoeff[kCRY]    = &fCry;     fNames[kCRY]    = "CRY";
+    fCoeff[kMAGIC1] = &fMagic1;  fNames[kMAGIC1] = "MAGIC1";
+    fCoeff[kMAGIC2] = &fMagic2;  fNames[kMAGIC2] = "MAGIC2";
+    fCoeff[kPX]     = &fPx;      fNames[kPX]     = "PX";
+    fCoeff[kPY]     = &fPy;      fNames[kPY]     = "PY";
+    fCoeff[kDX]     = &fDx;      fNames[kDX]     = "DX";
+    fCoeff[kDY]     = &fDy;      fNames[kDY]     = "DY";
+
+    fDescr[kIA]     =  "Index Error Azimuth";
+    fDescr[kIE]     =  "Index Error Zenith Distance";
+    fDescr[kFLOP]   =  "Vertical Sag";
+    fDescr[kAN]     =  "Azimuth Axis Misalignment (N-S)";
+    fDescr[kAW]     =  "Azimuth Axis Misalignment (E-W)";
+    fDescr[kNPAE]   =  "Az-El Nonperpendicularity";
+    fDescr[kCA]     =  "Left-Right Collimation Error";
+    fDescr[kTF]     =  "Tube fluxture (sin)";
+    fDescr[kTX]     =  "Tube fluxture (tan)";
+    fDescr[kECES]   =  "Elevation Centering Error (sin)";
+    fDescr[kACES]   =  "Azimuth Centering Error (sin)";
+    fDescr[kECEC]   =  "Elevation Centering Error (cos)";
+    fDescr[kACEC]   =  "Azimuth Centering Error (cos)";
+    fDescr[kNRX]    =  "Nasmyth rotator displacement (horizontal)";
+    fDescr[kNRY]    =  "Nasmyth rotator displacement (vertical)";
+    fDescr[kCRX]    =  "Alt/Az Coude Displacement (N-S)";
+    fDescr[kCRY]    =  "Alt/Az Coude Displacement (E-W)";
+    fDescr[kMAGIC1] =  "MAGIC culmination hysteresis";
+    fDescr[kMAGIC2] =  "n/a";
+    fDescr[kPX]     =  "Starguider calibration fixed offset x";
+    fDescr[kPY]     =  "Starguider calibration fixed offset y";
+    fDescr[kDX]     =  "Starguider calibration additional offset dx";
+    fDescr[kDY]     =  "Starguider calibration additional offset dy";
+}
+
+void MPointing::Reset()
+{
+    Clear();
+}
+
+Bool_t MPointing::Load(const char *name)
+{
+    /*
+     ! MMT 1987 July 8
+     ! T   36   7.3622   41.448  -0.0481
+     !   IA        -37.5465    20.80602
+     !   IE        -13.9180     1.25217
+     !   NPAE       +7.0751    26.44763
+     !   CA         -6.9149    32.05358
+     !   AN         +0.5053     1.40956
+     !   AW         -2.2016     1.37480
+     ! END
+     */
+
+    ifstream fin(name);
+    if (!fin)
+    {
+        *fLog << err << "ERROR - Cannot open file '" << name << "'" << endl;
+        return kFALSE;
+    }
+
+    char c;
+    while (fin && fin.get()!='\n');
+    fin >> c;
+
+    if (c!='S' && c!='s')
+    {
+        *fLog << err << "Error: This in not a model correcting the star position (" << c << ")" << endl;
+        return kFALSE;
+    }
+
+    Clear();
+
+    cout << endl;
+
+    Double_t val;
+    fin >> val;
+    *fLog << inf;
+    //*fLog << "Number of observed stars: " << val << endl;
+    fin >> val;
+    //*fLog << "Sky RMS: " << val << "\"" << endl;
+    fin >> val;
+    //*fLog << "Refraction Constant A: " << val << "\"" << endl;
+    fin >> val;
+    //*fLog << "Refraction Constant B: " << val << "\"" << endl;
+
+    *fLog << endl;
+
+    *fLog << "  & = Name            Value                 Sigma " << endl;
+    *fLog << "--------------------------------------------------" << endl;
+
+    while (fin)
+    {
+        TString str;
+        fin >> str;
+        if (!fin)
+        {
+            *fLog << err << "ERROR - Reading file " << name << endl;
+            return kFALSE;
+        }
+
+        str = str.Strip(TString::kBoth);
+
+        if (str=="END")
+            break;
+
+        TString sout;
+
+        if (str[0]=='#')
+            continue;
+
+        if (str[0]=='&')
+        {
+            sout += " & ";
+            str.Remove(0);
+        }
+        else
+            sout += "   ";
+
+        if (str[1]=='=')
+        {
+            sout += "=  ";
+            str.Remove(0);
+        }
+        else
+            sout += "   ";
+
+        fin >> val;
+
+        sout += str;
+        sout += '\t';
+        sout += Form("%11f", val);
+        sout += UTF8::kDeg;
+        sout += "     \t";
+        val *= TMath::DegToRad();
+
+        // Find parameter
+        Int_t n = -1;
+        for (int i=0; i<kNumPar; i++)
+            if (str==fNames[i])
+            {
+                n = i;
+                *fCoeff[i] = val;
+                break;
+            }
+
+        fin >> val;
+        sout += Form("%9f%s", val, UTF8::kDeg);
+
+        if (*fCoeff[n]!=0 || val>0)
+            *fLog << sout << endl;
+
+        if (!fin)
+        {
+            *fLog << err << "ERROR - Reading line " << str << endl;
+            return kFALSE;
+        }
+
+        if (n<0)
+        {
+            *fLog << warn << "WARNING - Parameter " << str << " unknown." << endl;
+            continue;
+        }
+
+        // corresponding error
+        fError[n] = val*TMath::DegToRad();
+    }
+    *fLog << endl;
+
+    fName = name;
+
+    return kTRUE;
+}
+
+Bool_t MPointing::Save(const char *name)
+{
+    /*
+     ! MMT 1987 July 8
+     ! T   36   7.3622   41.448  -0.0481
+     !   IA        -37.5465    20.80602
+     !   IE        -13.9180     1.25217
+     !   NPAE       +7.0751    26.44763
+     !   CA         -6.9149    32.05358
+     !   AN         +0.5053     1.40956
+     !   AW         -2.2016     1.37480
+     ! END
+     */
+
+    ofstream fout(name);
+    if (!fout)
+    {
+        cout << "Error: Cannot open file '" << name << "'" << endl;
+        return kFALSE;
+    }
+
+    MTime t;
+    t.Now();
+
+    fout << "MAGIC1 " << t << endl;
+    fout << "S   00   000000   000000  0000000" << endl;
+    fout << setprecision(8);
+    for (int i=0; i<kNumPar; i++)
+    {
+        fout << " " << setw(6) << GetVarName(i) << " ";
+        fout << setw(13) << *fCoeff[i]*kRad2Deg << "   ";
+        fout << setw(11) << fError[i]*kRad2Deg << endl;
+    }
+    fout << "END" << endl;
+
+    fName = name;
+
+    return kTRUE;
+}
+
+Double_t MPointing::Sign(Double_t val, Double_t alt)
+{
+    // Some pointing corrections are defined as Delta ZA, which
+    // is (P. Wallace) defined [0,90]deg while Alt is defined
+    // [0,180]deg
+    return (TMath::Pi()/2-alt < 0 ? -val : val);
+}
+
+AltAz MPointing::AddOffsets(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    const AltAz I(fIe, fIa);
+    p += I;
+
+    return p;
+}
+
+ZdAz MPointing::AddOffsets(const ZdAz &zdaz) const
+{
+    AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+
+    AltAz c = AddOffsets(p);
+
+    return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+}
+
+TVector3 MPointing::AddOffsets(const TVector3 &v) const
+{
+    AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+    AltAz c = AddOffsets(p);
+
+    TVector3 rc;
+    rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+    return rc;
+}
+
+AltAz MPointing::SubtractOffsets(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    const AltAz I(fIe, fIa);
+    p -= I;
+
+    return p;
+}
+
+ZdAz MPointing::SubtractOffsets(const ZdAz &zdaz) const
+{
+    AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+
+    AltAz c = SubtractOffsets(p);
+
+    return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+}
+
+TVector3 MPointing::SubtractOffsets(const TVector3 &v) const
+{
+    AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+    AltAz c = SubtractOffsets(p);
+
+    TVector3 rc;
+    rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+    return rc;
+}
+
+AltAz MPointing::CalcAnAw(const AltAz &p, Int_t sign) const
+{
+    // Corrections for AN and AW without approximations
+    // as done by Patrick Wallace. The approximation cannot
+    // be used for MAGIC because the correctioon angle
+    // AW (~1.5deg) is not small enough.
+
+    // Vector in cartesian coordinates
+    TVector3 v1;
+
+    // Set Azimuth and Elevation
+    v1.SetMagThetaPhi(1, TMath::Pi()/2-p.Alt(), p.Az());
+
+
+    TVector3 v2(v1);
+//    cout << sign << endl;
+
+//    cout << "v1: " << v1.Theta()*TMath::RadToDeg() << " " << v1.Phi()*TMath::RadToDeg() << endl;
+
+    // Rotate around the x- and y-axis
+    v1.RotateY(sign*fAn);
+    v1.RotateX(sign*fAw);
+
+//    cout << "v1: " << v1.Theta()*TMath::RadToDeg() << " " << v1.Phi()*TMath::RadToDeg() << endl;
+//    cout << "v2: " << v2.Theta()*TMath::RadToDeg() << " " << v2.Theta()*TMath::RadToDeg() << endl;
+
+   // cout << "dv: " << (v2.Theta()-v1.Theta())*TMath::RadToDeg() << " " << (v2.Phi()-v1.Phi())*TMath::RadToDeg() << endl;
+
+    Double_t dalt = v1.Theta()-v2.Theta();
+    Double_t daz  = v1.Phi()  -v2.Phi();
+
+    //cout << dalt*TMath::RadToDeg() << " " << daz*TMath::RadToDeg() << endl;
+
+    if (daz>TMath::Pi())
+        daz -= TMath::TwoPi();
+    if (daz<-TMath::Pi())
+        daz += TMath::TwoPi();
+
+//    if (daz>TMath::Pi()/2)
+//    {
+//    }
+
+    AltAz d(dalt, daz);
+    return d;
+
+    // Calculate Delta Azimuth and Delta Elevation
+    /*
+    AltAz d(TMath::Pi()/2-v1.Theta(), v1.Phi());
+
+    cout << "p :  " << p.Alt()*TMath::RadToDeg() << " " << p.Az()*TMath::RadToDeg() << endl;
+    cout << "d :  " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+    d -= p;
+    cout << "d-p: " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+    d *= sign;
+    cout << "d* : " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+
+
+    cout << "p2:  " << 90-p.Alt()*TMath::RadToDeg() << " " << p.Az()*TMath::RadToDeg() << endl;
+    cout << "d2:  " << 90-d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+
+    Int_t s1 = 90-d.Alt()*TMath::RadToDeg() < 0 ? -1 : 1;
+    Int_t s2 = 90-p.Alt()*TMath::RadToDeg() < 0 ? -1 : 1;
+
+
+    if (s1 != s2)
+    {
+        //90-d.Alt() <-- -90+d.Alt()
+
+        d.Alt(d.Alt()-TMath::Pi());
+        cout << "Alt-" << endl;
+    }
+    cout << "d': " << 90-d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;*/
+ /*
+    // Fix 'direction' of output depending on input vector
+    if (TMath::Pi()/2-sign*p.Alt()<0)
+    {
+        d.Alt(d.Alt()-TMath::Pi());
+        cout << "Alt-" << endl;
+    }
+    //if (TMath::Pi()/2-sign*p.Alt()>TMath::Pi())
+    //{
+    //    d.Alt(TMath::Pi()-d.Alt());
+    //    cout << "Alt+" << endl;
+    //}
+
+    // Align correction into [-180,180]
+    while (d.Az()>TMath::Pi())
+    {
+        d.Az(d.Az()-TMath::Pi()*2);
+        cout << "Az-" << endl;
+    }
+    while (d.Az()<-TMath::Pi())
+    {
+        d.Az(d.Az()+TMath::Pi()*2);
+        cout << "Az+" << endl;
+    }
+   */
+    return d;
+}
+
+
+AltAz MPointing::Correct(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    DEBUG(cout << setprecision(16));
+    DEBUG(cout << "Bend7: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CRX(-fCrx*sin(p.Az()-p.Alt()),  fCrx*cos(p.Az()-p.Alt())/cos(p.Alt()));
+    const AltAz CRY(-fCry*cos(p.Az()-p.Alt()), -fCry*sin(p.Az()-p.Alt())/cos(p.Alt()));
+    p += CRX;
+    p += CRY;
+
+    DEBUG(cout << "Bend6: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz NRX(fNrx*sin(p.Alt()), -fNrx);
+    const AltAz NRY(fNry*cos(p.Alt()), -fNry*tan(p.Alt()));
+    p += NRX;
+    p += NRY;
+
+    DEBUG(cout << "Bend5: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CES(-fEces*sin(p.Alt()), -fAces*sin(p.Az()));
+    const AltAz CEC(-fEcec*cos(p.Alt()), -fAcec*cos(p.Az()));
+    p += CES;
+    p += CEC;
+
+    DEBUG(cout << "Bend4: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz TX(Sign(fTx/tan(p.Alt()), p.Alt()), 0);
+    const AltAz TF(Sign(fTf*cos(p.Alt()), p.Alt()), 0);
+    //p += TX;
+    p += TF;
+
+
+    DEBUG(cout << "Bend3: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    /*
+     //New Corrections for NPAE and CA:
+     TVector3 v(1.,1.,1.); // Vector in cartesian coordinates
+
+     //Set Azimuth and Elevation
+     v.SetPhi(p.Az());
+     v.SetTheta(TMath::Pi()/2-p.Alt());
+     //Rotation Vectors:
+     TVector3 vNpae(             cos(p.Az()),              sin(p.Az()),             0);
+     TVector3   vCa( -cos(p.Az())*cos(p.Alt()), -sin(p.Az())*cos(p.Alt()), sin(p.Alt()));
+     //Rotate around the vectors vNpae and vCa
+     v.Rotate(fNpae, vNpae);
+     v.Rotate(fCa,     vCa);
+
+     p.Az(v.Phi());
+     p.Alt(TMath::Pi()/2-v.Theta());
+     */
+
+    //Old correction terms for Npae and Ca:
+    const AltAz CA(0, -fCa/cos(p.Alt()));
+    p += CA;
+
+    const AltAz NPAE(0, -fNpae*tan(p.Alt()));
+    p += NPAE;
+
+    DEBUG(cout << "Bend2: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz ANAW(CalcAnAw(p, -1));
+    p += ANAW;
+
+    /* Old correction terms for An and Aw:
+     const AltAz AW( fAw*sin(p.Az()), -fAw*cos(p.Az())*tan(p.Alt()));
+     const AltAz AN(-fAn*cos(p.Az()), -fAn*sin(p.Az())*tan(p.Alt()));
+     p += AW;
+     p += AN;
+    */
+
+    DEBUG(cout << "Bend1: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz FLOP(Sign(fFlop, p.Alt()), 0);
+    p += FLOP;
+
+    const AltAz MAGIC1(fMagic1*TMath::Sign(1., sin(p.Az())), 0);
+    p += MAGIC1;
+
+    const AltAz I(fIe, fIa);
+    p += I;
+
+    DEBUG(cout << "Bend0: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    return p;
+}
+
+AltAz MPointing::CorrectBack(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    DEBUG(cout << setprecision(16));
+    DEBUG(cout << "Back0: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz I(fIe, fIa);
+    p -= I;
+
+    const AltAz MAGIC1(fMagic1*TMath::Sign(1., sin(p.Az())), 0);
+    p -= MAGIC1;
+
+    //const AltAz MAGIC1(fMagic1*sin(p.Az()), 0);
+    //p -= MAGIC1;
+
+    const AltAz FLOP(Sign(fFlop, p.Alt()), 0);
+    p -= FLOP;
+
+    DEBUG(cout << "Back1: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    /* Old correction terms for An and Aw:
+     const AltAz AN(-fAn*cos(p.Az()), -fAn*sin(p.Az())*tan(p.Alt()));
+     const AltAz AW( fAw*sin(p.Az()), -fAw*cos(p.Az())*tan(p.Alt()));
+     p -= AN;
+     p -= AW;
+     */
+
+    const AltAz ANAW(CalcAnAw(p, -1));
+    p -= ANAW;
+
+    DEBUG(cout << "Back2: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    //Old Correction terms for Npae and Ca:
+    const AltAz NPAE(0, -fNpae*tan(p.Alt()));
+    p -= NPAE;
+
+    const AltAz CA(0, -fCa/cos(p.Alt()));
+    p -= CA;
+
+    /*
+     //New Correction term for Npae and Ca:
+     TVector3 v2(1.,1.,1.); // Vector in cartesian coordinates
+     //Set Azimuth and Elevation
+     v2.SetPhi(p.Az());
+     v2.SetTheta(TMath::Pi()/2-p.Alt());
+     //Rotation Vectors:
+     TVector3 vNpae(             cos(p.Az()),              sin(p.Az()),             0);
+     TVector3   vCa( -cos(p.Az())*cos(p.Alt()), -sin(p.Az())*cos(p.Alt()), sin(p.Alt()));
+     //Rotate around the vectors vCa and vNpae
+     v2.Rotate(-fCa,     vCa);
+     v2.Rotate(-fNpae, vNpae);
+
+     p.Az(v2.Phi());
+     p.Alt(TMath::Pi()/2-v2.Theta());
+    */
+
+    DEBUG(cout << "Back3: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz TF(Sign(fTf*cos(p.Alt()), p.Alt()), 0);
+    const AltAz TX(Sign(fTx/tan(p.Alt()), p.Alt()), 0);
+    p -= TF;
+    //p -= TX;
+
+    DEBUG(cout << "Back4: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CEC(-fEcec*cos(p.Alt()), -fAcec*cos(p.Az()));
+    const AltAz CES(-fEces*sin(p.Alt()), -fAces*sin(p.Az()));
+    p -= CEC;
+    p -= CES;
+
+    DEBUG(cout << "Back5: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz NRY(fNry*cos(p.Alt()), -fNry*tan(p.Alt()));
+    const AltAz NRX(fNrx*sin(p.Alt()), -fNrx);
+    p -= NRY;
+    p -= NRX;
+
+    DEBUG(cout << "Back6: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CRY(-fCry*cos(p.Az()-p.Alt()), -fCry*sin(p.Az()-p.Alt())/cos(p.Alt()));
+    const AltAz CRX(-fCrx*sin(p.Az()-p.Alt()),  fCrx*cos(p.Az()-p.Alt())/cos(p.Alt()));
+    p -= CRY;
+    p -= CRX;
+
+    DEBUG(cout << "Back7: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    return p;
+}
+
+ZdAz MPointing::Correct(const ZdAz &zdaz) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+    AltAz c = Correct(p);
+    return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+}
+
+TVector3 MPointing::Correct(const TVector3 &v) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+    AltAz c = Correct(p);
+    TVector3 rc;
+    rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+    return rc;
+}
+
+ZdAz MPointing::CorrectBack(const ZdAz &zdaz) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+    AltAz c = CorrectBack(p);
+    return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+}
+
+TVector3 MPointing::CorrectBack(const TVector3 &v) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+    AltAz c = CorrectBack(p);
+    TVector3 rc;
+    rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+    return rc;
+}
+
+void MPointing::SetParameters(const Double_t *par, Int_t n)
+{
+    Clear();
+
+    while (n--)
+        *fCoeff[n] = par[n]/kRad2Deg;
+}
+
+void MPointing::GetParameters(Double_t *par, Int_t n) const
+{
+    while (n--)
+        par[n] = *fCoeff[n]*kRad2Deg;
+}
+
+void MPointing::GetError(TArrayD &par) const
+{
+    par = fError;
+    for (int i=0; i<kNumPar; i++)
+        par[i] *= TMath::RadToDeg();
+}
+
+TVector2 MPointing::GetDxy() const
+{
+    return TVector2(fDx, fDy)*TMath::RadToDeg();
+}
+
+Double_t MPointing::GetPx() const
+{
+    return fPx*TMath::RadToDeg();
+}
+
+Double_t MPointing::GetPy() const
+{
+    return fPy*TMath::RadToDeg();
+}
+
+void MPointing::SetMinuitParameters(TMinuit &m, Int_t n) const
+{
+    if (n<0)
+        n = kNumPar;
+
+    Int_t ierflg = 0;
+
+    while (n--)
+        m.mnparm(n, fNames[n], *fCoeff[n]*kRad2Deg,  1, -360, 360, ierflg);
+}
+
+void MPointing::GetMinuitParameters(TMinuit &m, Int_t n)
+{
+    if (n<0 || n>m.GetNumPars())
+        n = m.GetNumPars();
+
+    while (n--)
+    {
+        m.GetParameter(n, *fCoeff[n], fError[n]);
+        *fCoeff[n] /= kRad2Deg;
+        fError[n]  /= kRad2Deg;
+    }
+}
+/*
+void FormatPar(TMinuit &m, Int_t n)
+{
+    Double_t par, err;
+    m.GetParameter(n, par, err);
+
+    int expp = (int)log10(par);
+    int expe = (int)log10(err);
+
+    if (err<2*pow(10, expe))
+        expe--;
+
+    Int_t exp = expe>expp ? expp : expe;
+
+    par = (int)(par/pow(10, exp)) * pow(10, exp);
+    err = (int)(err/pow(10, exp)) * pow(10, exp);
+
+    cout << par << " +- " << err << flush;
+}
+*/
+void MPointing::PrintMinuitParameters(TMinuit &m, Int_t n) const
+{
+    if (n<0)
+        n = m.GetNumPars();
+
+    cout << setprecision(3);
+
+    Double_t par, er;
+
+    while (n--)
+    {
+        m.GetParameter(n, par, er);
+        cout << Form(" %2d %6s: ", n, (const char*)fNames[n]);
+        cout << setw(8) << par << " \xb1 " << setw(6) <<  er << endl;
+    }
+}
Index: branches/Mars_McMismatchStudy/mpointing/MPointing.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointing.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointing.h	(revision 17960)
@@ -0,0 +1,313 @@
+#ifndef MARS_MPointing
+#define MARS_MPointing
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+// ---------------------------------------------------
+
+#define XY TVector2
+
+inline TVector2 Div(const TVector2 &v1, const TVector2 &v2)
+{
+    return TVector2(v1.X()/v2.X(), v1.Y()/v2.Y());
+}
+inline TVector2 Mul(const TVector2 &v1, const TVector2 &v2)
+{
+    return TVector2(v1.X()*v2.X(), v1.Y()*v2.Y());
+}
+
+inline TVector2 operator-(const TVector2 &v) { return TVector2(-v.X(), -v.Y()); }
+
+class AltAz : public XY
+{
+public:
+    AltAz(double alt=0, double az=0) : XY(alt, az) {}
+
+    double Alt() const { return fX; }
+    double Az()  const { return fY; }
+
+    void operator*=(double c) { fX*=c; fY*=c; }
+    void operator/=(double c) { fX*=c; fY*=c; }
+
+    void Alt(double d) { fX=d; }
+    void Az(double d)  { fY=d; }
+    void operator*=(const XY &c)    { fX*=c.X(); fY*=c.Y(); }
+    void operator/=(const XY &c)    { fX/=c.X(); fY/=c.Y(); }
+    void operator-=(const AltAz &c) { fX-=c.fX; fY-=c.fY; }
+    void operator+=(const AltAz &c) { fX+=c.fX; fY+=c.fY; }
+
+    AltAz operator/(double c) const { return AltAz(fX/c, fY/c); }
+    AltAz operator*(double c) const { return AltAz(fX*c, fY*c); }
+    AltAz operator*(const XY &c) const { return AltAz(fX*c.X(), fY*c.Y()); }
+    AltAz operator/(const XY &c) const { return AltAz(fX/c.X(), fY/c.Y()); }
+    AltAz operator+(const AltAz &c) const { return AltAz(fX+c.fX, fY+c.fY); }
+    AltAz operator-(const AltAz &c) const { return AltAz(fX-c.fX, fY-c.fY); }
+    AltAz operator-() const { return AltAz(-fX, -fY); }
+
+    ClassDef(AltAz, 0)
+};
+
+class ZdAz : public XY
+{
+public:
+    ZdAz(double zd=0, double az=0) : XY(zd, az) {}
+    ZdAz(const ZdAz &c) : XY(c) {}
+
+    void operator*=(double c) { fX*=c; fY*=c; }
+    void operator/=(double c) { fX*=c; fY*=c; }
+
+    double Zd() const { return fX; }
+    double Az() const { return fY; }
+
+    void Zd(double d) { fX=d; }
+    void Az(double d) { fY=d; }
+    void operator*=(const XY &c)   { fX*=c.X(); fY*=c.Y(); }
+    void operator/=(const XY &c)   { fX/=c.X(); fY/=c.Y(); }
+    void operator-=(const ZdAz &c) { fX-=c.fX; fY-=c.fY; }
+    void operator+=(const ZdAz &c) { fX+=c.fX; fY+=c.fY; }
+
+    ZdAz operator/(double c) const { return ZdAz(fX/c, fY/c); }
+    ZdAz operator*(double c) const { return ZdAz(fX*c, fY*c); }
+    ZdAz operator*(const XY &c) const { return ZdAz(fX*c.X(), fY*c.Y()); }
+    ZdAz operator/(const XY &c) const { return ZdAz(fX/c.X(), fY/c.Y()); }
+    ZdAz operator+(const ZdAz &c) const { return ZdAz(fX+c.fX, fY+c.fY); }
+    ZdAz operator-(const ZdAz &c) const { return ZdAz(fX-c.fX, fY-c.fY); }
+    ZdAz operator-() const { return ZdAz(-fX, -fY); }
+
+    // MSlewing only?!?
+    double Ratio() const { return fX/fY; }
+    void Round();
+    void Abs();
+
+    ClassDef(ZdAz, 0)
+};
+
+class RaDec : public XY
+{
+public:
+    RaDec(double ra=0, double dec=0) : XY(ra, dec) {}
+
+    double Ra()  const { return fX; }
+    double Dec() const { return fY; }
+
+    void operator*=(double c) { fX*=c; fY*=c; }
+    void operator/=(double c) { fX*=c; fY*=c; }
+
+    void Ra(double x)  { fX = x; }
+    void Dec(double y) { fY = y; }
+
+    RaDec operator/(double c) const { return RaDec(fX/c, fY/c); }
+    RaDec operator*(double c) const { return RaDec(fX*c, fY*c); }
+    RaDec operator*(const XY &c) const { return RaDec(fX*c.X(), fY*c.Y()); }
+    RaDec operator+(const RaDec &c) const { return RaDec(fX+c.fX, fY+c.fY); }
+    RaDec operator-(const RaDec &c) const { return RaDec(fX-c.fX, fY-c.fY); }
+    RaDec operator-() const { return RaDec(-fX, -fY); }
+
+    ClassDef(RaDec, 0)
+};
+
+// ---------------------------------------------------
+
+class TMinuit;
+
+class MPointing : public MParContainer
+{
+private:
+    enum {
+        kIA,           // [rad] Index Error in Elevation
+        kIE,           // [rad] Index Error in Azimuth
+        kFLOP,         // [rad] Vertical Sag
+        kAN,           // [rad] Az-El Nonperpendicularity
+        kAW,           // [rad] Left-Right Collimation Error
+        kNPAE,         // [rad] Azimuth Axis Misalignment (N-S)
+        kCA,           // [rad] Azimuth Axis Misalignment (E-W)
+        kTF,           // [rad] Tube fluxture (sin)
+        kTX,           // [rad] Tube fluxture (tan)
+        kECES,         // [rad] Nasmyth rotator displacement, horizontal
+        kACES,         // [rad] Nasmyth rotator displacement, vertical
+        kECEC,         // [rad] Alt/Az Coude Displacement (N-S)
+        kACEC,         // [rad] Alt/Az Coude Displacement (E-W)
+        kNRX,          // [rad] Elevation Centering Error (sin)
+        kNRY,          // [rad] Azimuth Centering Error (sin)
+        kCRX,          // [rad] Elevation Centering Error (cos)
+        kCRY,          // [rad] Azimuth Centering Error (cos)
+        kMAGIC1,       // [rad] Magic Term (what is it?)
+        kMAGIC2,       // [rad] Magic Term (what is it?)
+        kPX,           // [rad] Starguider calibration fixed offset x
+        kPY,           // [rad] Starguider calibration fixed offset y
+        kDX,           // [rad] Starguider calibration additional offset dx
+        kDY,           // [rad] Starguider calibration additional offset dy
+        kNumPar   // Number of elements
+    };
+
+
+    Double_t fIe   ; // [rad] Index Error in Elevation
+    Double_t fIa   ; // [rad] Index Error in Azimuth
+    Double_t fFlop ; // [rad] Vertical Sag
+    Double_t fNpae ; // [rad] Az-El Nonperpendicularity
+    Double_t fCa   ; // [rad] Left-Right Collimation Error
+    Double_t fAn   ; // [rad] Azimuth Axis Misalignment (N-S)
+    Double_t fAw   ; // [rad] Azimuth Axis Misalignment (E-W)
+    Double_t fTf   ; // [rad] Tube fluxture (sin)
+    Double_t fTx   ; // [rad] Tube fluxture (tan)
+    Double_t fNrx  ; // [rad] Nasmyth rotator displacement, horizontal
+    Double_t fNry  ; // [rad] Nasmyth rotator displacement, vertical
+    Double_t fCrx  ; // [rad] Alt/Az Coude Displacement (N-S)
+    Double_t fCry  ; // [rad] Alt/Az Coude Displacement (E-W)
+    Double_t fEces ; // [rad] Elevation Centering Error (sin)
+    Double_t fAces ; // [rad] Azimuth Centering Error (sin)
+    Double_t fEcec ; // [rad] Elevation Centering Error (cos)
+    Double_t fAcec ; // [rad] Azimuth Centering Error (cos)
+    Double_t fMagic1; // [rad] Magic Term (what is it?)
+    Double_t fMagic2; // [rad] Magic Term (what is it?)
+
+    Double_t fPx;    // [rad] Starguider calibration fixed offset x
+    Double_t fPy;    // [rad] Starguider calibration fixed offset y
+    Double_t fDx;    // [rad] Starguider calibration additional offset dx
+    Double_t fDy;    // [rad] Starguider calibration additional offset dy
+
+    Double_t **fCoeff; //!
+    TString   *fNames; //!
+    TString   *fDescr; //!
+
+    TArrayD   fError;
+
+    void Init(const char *name=0, const char *title=0);
+
+    void Clear(Option_t *o="")
+    {
+        for (int i=0; i<kNumPar; i++)
+        {
+            *fCoeff[i] = 0;
+            fError[i] = -1;
+        }
+    }
+
+    static Double_t Sign(Double_t val, Double_t alt);
+    AltAz CalcAnAw(const AltAz &p, Int_t sign) const;
+
+public:
+    MPointing() : fError(kNumPar) { Init(); Clear(); }
+    MPointing(const char *name) : fError(kNumPar) { Init(); Clear(); Load(name); }
+    virtual ~MPointing() { delete [] fNames; delete [] fCoeff; delete [] fDescr; }
+
+    Bool_t Load(const char *name);
+    Bool_t Save(const char *name);
+
+    void Reset();
+
+    ZdAz     Correct(const ZdAz &zdaz) const;
+    AltAz    Correct(const AltAz &aaz) const;
+    TVector3 Correct(const TVector3 &v) const;
+
+    ZdAz     CorrectBack(const ZdAz &zdaz) const;
+    AltAz    CorrectBack(const AltAz &aaz) const;
+    TVector3 CorrectBack(const TVector3 &v) const;
+
+    ZdAz     operator()(const ZdAz &zdaz)  const { return Correct(zdaz); }
+    AltAz    operator()(const AltAz &aaz)  const { return Correct(aaz); }
+    TVector3 operator()(const TVector3 &v) const { return Correct(v); }
+
+    ZdAz operator()(const ZdAz &zdaz, void (*fcn)(ZdAz &zdaz, Double_t *par)) const
+    {
+        Double_t par[kNumPar];
+        GetParameters(par);
+        ZdAz za = zdaz;
+        fcn(za, par);
+        return za;
+    }
+
+    AltAz operator()(const AltAz &aaz, void (*fcn)(AltAz &aaz, Double_t *par)) const
+    {
+        Double_t par[kNumPar];
+        GetParameters(par);
+        AltAz aa = aaz;
+        fcn(aa, par);
+        return aa;
+    }
+
+    TVector3 operator()(const TVector3 &aaz, void (*fcn)(TVector3 &aaz, Double_t *par)) const
+    {
+        Double_t par[kNumPar];
+        GetParameters(par);
+        TVector3 v = aaz;
+        fcn(v, par);
+        return v;
+    }
+
+    AltAz    AddOffsets(const AltAz &aa) const;
+    ZdAz     AddOffsets(const ZdAz &zdaz) const;
+    TVector3 AddOffsets(const TVector3 &v) const;
+
+    AltAz    SubtractOffsets(const AltAz &aa) const;
+    ZdAz     SubtractOffsets(const ZdAz &zdaz) const;
+    TVector3 SubtractOffsets(const TVector3 &v) const;
+
+    void SetParameters(const Double_t *par, Int_t n=kNumPar);
+    void GetParameters(Double_t *par, Int_t n=kNumPar) const;
+
+    void SetParameters(const TArrayD &par)
+    {
+        SetParameters(par.GetArray(), par.GetSize());
+    }
+    void GetParameters(TArrayD &par) const
+    {
+        par.Set(kNumPar);
+        GetParameters(par.GetArray());
+    }
+    void GetError(TArrayD &par) const;
+
+    Double_t &operator[](UInt_t i) { return *fCoeff[i]; }
+
+    void SetMinuitParameters(TMinuit &m, Int_t n=-1) const;
+    void GetMinuitParameters(TMinuit &m, Int_t n=-1);
+    void PrintMinuitParameters(TMinuit &m, Int_t n=-1) const;
+
+    const TString &GetVarName(int i) const { return fNames[i]; }
+    const TString &GetDescription(int i) const { return fDescr[i]; }
+
+    /*
+     Double_t GetIe() const { return fIe; }
+     Double_t GetIa() const { return fIa; }
+     Double_t GetCa() const { return fCa; }
+     Double_t GetAn() const { return fAn; }
+     Double_t GetAw() const { return fAw; }
+     Double_t GetNrx() const { return fNrx; }
+     Double_t GetNry() const { return fNry; }
+     Double_t GetCrx() const { return fNrx; }
+     Double_t GetCry() const { return fNry; }
+     Double_t GetEces() const { return fEces; }
+     Double_t GetEcec() const { return fEcec; }
+     Double_t GetAces() const { return fAces; }
+     Double_t GetAcec() const { return fAcec; }
+     Double_t GetNpae() const { return fNpae; }
+     */
+
+    TVector2 GetDxy() const;// { return TVector2(fDx, fDy)*TMath::RadToDeg(); }
+
+    Double_t GetPx() const;// { return fPx*TMath::RadToDeg(); }
+    Double_t GetPy() const;// { return fPy*TMath::RadToDeg(); }
+
+    Bool_t IsPxValid() const { return fError[kPX]>0; }
+    Bool_t IsPyValid() const { return fError[kPY]>0; }
+
+    static const Int_t GetNumPar() { return kNumPar; }
+
+    ClassDef(MPointing, 2) // Pointing Model for MAGIC
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MPointingDev.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingDev.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingDev.cc	(revision 17960)
@@ -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, 07/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointingDev
+//
+// Container stroing the telescope mispointing
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPointingDev.h"
+
+#include <TMath.h>
+
+ClassImp(MPointingDev);
+
+using namespace std;
+
+Double_t MPointingDev::GetDevZdRad() const
+{
+    return fDevZd*TMath::DegToRad();
+}
+
+Double_t MPointingDev::GetDevAzRad() const
+{
+    return fDevAz*TMath::DegToRad();
+}
Index: branches/Mars_McMismatchStudy/mpointing/MPointingDev.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingDev.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingDev.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MPointingDev
+#define MARS_MPointingDev
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+class MPointingDev : public MParContainer
+{
+private:
+    Double_t fDevZd;  // [deg] Pointing offset zenith distance as calculated from starguider data
+    Double_t fDevAz;  // [deg] Pointing offset azimuth as calculated from starguider dat
+
+    Double_t fDevX;   // [deg] Pointing offset in x
+    Double_t fDevY;   // [deg] Pointing offset in y
+
+public:
+    MPointingDev(const char *name=0, const char *title=0) : fDevZd(0), fDevAz(0), fDevX(0), fDevY(0)
+    {
+        fName  = name ? name   : "MPointingDev";
+        fTitle = title ? title : "Container storing the telescope mispointing";
+    }
+
+    void SetDevZdAz(Double_t devzd, Double_t devaz) { fDevZd=devzd; fDevAz=devaz; }
+    void SetDevXY(Double_t dx, Double_t dy) { fDevX=dx; fDevY=dy; }
+    void SetDevXY(const TVector2 &d) { fDevX=d.X(); fDevY=d.Y(); }
+
+    Double_t GetDevZd() const  { return fDevZd; }
+    Double_t GetDevAz() const  { return fDevAz; }
+
+    Double_t GetDevX() const  { return fDevX; }
+    Double_t GetDevY() const  { return fDevY; }
+
+    TVector2 GetDevXY() const { return TVector2(fDevX, fDevY); }
+
+    Double_t GetDevZdRad() const;//  { return fDevZd*TMath::DegToRad(); }
+    Double_t GetDevAzRad() const;//  { return fDevAz*TMath::DegToRad(); }
+
+    ClassDef(MPointingDev, 1) //Container storing the telescope mispointing
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MPointingDevCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingDevCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingDevCalc.cc	(revision 17960)
@@ -0,0 +1,874 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 07/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointingDevCalc
+//
+// Calculates the pointing deviation from the starguider information.
+//
+// There are some quality parameters to steer which are the valid
+// starguider data points:
+//
+//  * MPointingDevCalc.NumMinStars: 8
+//    Minimum number of identified stars required to accep the data
+//
+//  * MPointingDevCalc.NsbLevel:    3.0
+//    Minimum deviation (in rms) from the the mean allowed for the
+//    measured NSB (noise in the ccd camera)
+//
+//  * MPointingDevCalc.NsbMin:      30
+//    - minimum NSB to be used in mean/rms calculation
+//
+//  * MPointingDevCalc.NsbMax:      60
+//    - maximum NSB to be used in mean/rms calculation
+//
+//  * MPointingDevCalc.MaxAbsDev:   15
+//    - Maximum absolute deviation which is consideres as valid (arcmin)
+//
+// Starguider data which doens't fullfill this requirements is ignored.
+// If the measures NSB==0 (file too old, starguider didn't write down
+// these values) the checks based on NSB and NumMinStar are skipped.
+//
+// The calculation of NSB mean and rms is reset for each file (ReInit)
+//
+// If your starguider data doesn't fullfill this requirement the latest
+// value which could be correctly calculated is used instead. If the time
+// for which no valid value can be calculated exceeds one minute
+// the return value is reset to 0/0. The maximum time allowed without
+// a valid value can be setup using:
+//
+//  * MPointingDevCalc.MaxAge:   1
+//    Maximum time before the starguider is reset to 0/0 in minutes
+//
+// Note, that the starguider itself is not well calibrated. Therefore
+// it is necessary to do a starguider calibration in our software.
+//
+// There are two options:
+//
+//  * Simple starguider calibration using offsets in the camera plane
+//
+//    The starguider is calibrated by taking its values (dZd/dAz)
+//    adding them to the source position, calculating the source position
+//    in the camera plane and adding the offsets. To switch off the
+//    full starguider calibration do:
+//
+//      * MPointingDevCalc.PointingModels:
+//
+//    To set the offsets (in units of degree) use
+//
+//      * MPointingDevCalc.Dx: -0.001
+//      * MPointingDevCalc.Dy: -0.004
+//
+//   * A starguider calibration using a pointing model calculated
+//     from calibration data, so called TPoints
+//
+//     Because the pointing model can change from time to time
+//     you can give the run-number from which on a new pointing
+//     model is valid. The run itself is included, e.g.:
+//
+//      * MPointingDevCalc.PointingModels: 85240 89180
+//      * MPointingDevCalc.FilePrefix:     resources/starguider
+//
+//     mean that for all runs<85240 the simple offset correction is used.
+//     For runs >=85240 and <89180 the file resources/starguider0085240.txt
+//     and for runs >=89180 the file resources/starguider0089180.txt is
+//     used. To setup a default file for all runs before 85240 setup
+//     a low number (eg. 0 or 1)
+//
+//     In the case a pointing model is used additional offsets in
+//     the x/y-camera plane (in units of deg) can be set using the DX
+//     and DY parameters of the pointing model. The fDx and fDy data
+//     members of this class are ignored. To overwrite the starguider
+//     calibrated offset in either Az or Zd with a constant, you
+//     can use the PX/PY directive in the pointing model. (To enable
+//     the overwrite set the third column, the error, to a value
+//     greater than zero)
+//
+//
+// At the PostProcessing step a table with statistics is print if the
+// debug level is greater or equal 3 (in most applications it is switched
+// on by -v3)
+//
+//
+// Pointing Models:
+// ----------------
+//
+//  What we know so far about (maybe) important changes in cosy or to the
+//  hardware:
+//
+//   25.01.2010: Changed scaling factors for TPoint camera (M1)
+//
+//   11.01.2010: New TPoint camera (M1)
+//
+//   18.03.2006: The camera holding has been repaired and the camera got
+//               shifted a little bit.
+//
+//   16.04.2006: Around this date a roque lamp focussing has been done
+//
+//   25.04.2006: A missalignment introduced with the roque adjust has been
+//               corrected
+//
+//   The starguider pointing model for the time before 18.3.2006 and after
+//   April 2006 (in fact there are no TPoints until 07/2006 to check it)
+//   and for the period 07/2006 to (at least) 06/2007 are very similar.
+//
+//   The pointing model for the time between 18.3.2006 and 04/2006 is
+//   clearly different, mainly giving different Azimuth values between
+//   Zenith and roughly ~25deg, and a slight offset on both axes.
+//
+//   10.5.2006:  pos1 -= pos0 commented  (What was the mentioned fix?)
+//   29.6.2006:  repaired
+//
+//   23.3.2006:  new starguider algorithm
+//
+//   17.3.2005:  Fixed units of "nompos" in MDriveCom
+//
+//
+// New pointing models have been installed (if the pointing model
+// is different, than the previous one it might mean, that also
+// the starguider calibration is different.) The date only means
+// day-time (noon) at which the model has been changed.
+//
+//   29. Apr. 2004    ~25800
+//    5. Aug. 2004    ~32000
+//   19. Aug. 2004    ~33530
+//    7. Jun. 2005    ~57650
+//    8. Jun. 2005
+//    9. Jun. 2005    ~57860
+//   12. Sep. 2005    ~68338
+//   24. Nov. 2005    ~75562
+//   17. Oct. 2006   ~103130
+//   17. Jun. 2007   ~248193
+//   18. Oct. 2007    291104      // Correction for the offsets introduced by AMC
+//   14. Jan. 2008    328198      // Complete new pointing model
+//   11. Jun. 2008   1000534    (ca. 23:00) // Before new TPoints
+//   19. Jun. 2008              (ca. 15:00) // From   new TPoints
+//    7. Mar. 2009              (ca. 14:00) // From   new TPoints (0808-0902)
+//   14. May  2009                // M1/M2 after upgrade (from TPoints taken in the days before)
+//   17. Aug. 2009              New pointing models for both telescopes
+//   01. Feb. 2010              New pointing models for both telescopes
+//   26. Feb. 2010              New pointing models for both telescopes
+//   31. Mar. 2010              New pointing models for both telescopes
+//   29. Sep. 2010              New pointing model MAGIC I
+//   01. Dec. 2010              New pointing models for both telescopes
+//   06. Jan. 2011              New pointing models for both telescopes
+//
+// From 2.2.2006 beginnig of the night (21:05h, run >=81855) to 24.2.2006
+// beginning of the the night (20:34h, run<83722) the LEDs did not work.
+// In the time after this incident the shift crew often forgot to switch on
+// the LEDs at the beginning of the night!
+//
+// [2006-03-07 00:10:58] In the daytime, we raised the position of the
+// 9 o'clock LED by one screw hole to make it visible when the TPoint
+// Lid is closed. (< run 84980)
+//
+// Mirror refocussing around 23.Apr.2006, from the Runbook.
+//
+// 25./26.4.2006: Run 89180
+//
+// (Note: The year here is not a typo!)
+// [2007-04-25 23:50:39]
+// Markus is performing AMC focussing.
+//
+// Mirror refocussing around 4.Aug.2007, from the Runbook:
+//
+// [2007-08-04 04:46:47]
+// We finished with the focussing with Polaris. The images need to be
+// analysed and new LUTs generated.
+//
+// [2007-08-04 23:47:30]
+// Actually we see that the mispointing is always large; probably since
+// the LUT tables have not yet been adjusted to the new focussing.
+//
+// [2007-08-03 23:07:58]
+// Data taking stopped. Mirror focussing.
+//
+// [2007-08-05 00:09:16]
+// We take some pictures on stars nearby Cyg X3 with the sbig camera;
+// actually the spot doesn't look very nice... The pictures have been
+// saved with name Deneb- and Sadr- Polaris seems a bit better. Should we
+// have new LUT tables after the focussing?
+//
+// [2007-08-10 20:18:48]
+// Tonight we take first images of Polaris with a new LUT file generated
+// based on the recent focussing. The image will be analysed tomorrow and
+// than new LUTs will be generated. For tonight the focussing is still not
+// changed.
+//
+// [2007-08-14 20:57:59]
+// The weather is fine. There is a group of hobby astronomers at the
+// helicopter parking. Before data taking, we tried to check the new LUTs.
+// However, because of technical problems with the new LUTs we had to
+// postpone the measurements. We lost some 10 min of data taking because
+// of this.
+//
+// [2007-08-14 22:29:37]  Run 267253
+// Before continuing the observation we perform a focussing test with the
+// new LUTs from recent Polaris focussing. Note: Data on Her X-1 was taken
+// with old focussing. We performed PSF measurements on Kornephorus (Zd
+// 31.77, Az 264,67) first with old LUTs and then with new LUTs. We took
+// T-points with both focussing. The first T-Point corresponds to the
+// previous focussing and the second with the improved. Please check both
+// T-points for eventual misspointing. We found big improvement of the PSF
+// with the new LUTs and will therefore continue from now on with the new
+// focussing. Having a first look at the SBIG pictures we see a slightly
+// misspointing of ~0.1 deg with the new LUTs.
+//
+// [2007-08-14 22:46:10]
+// Comparing the trigger rate with yesterday night we do not see an
+// improvement with the new focussing.
+//
+// [2007-10-27 email]
+// [...]
+// When removing the cover of the motor all 4 nuts which fix the gear of
+// the motor to the structure fell out. The motor was completely loose.
+// [...]
+// We checked also the second azimuth motor and .. the same situation.
+// [...]
+// Peter Sawallisch opened and fixed all 3 motors of MAGIC-I. We checked
+// all critical screws that came to our minds and fixed them as much as
+// possible with loctite and counter nuts. No damage whatsoever has been
+// found.
+//
+// [2009-08-05 Mail from Markus Garcz. about M1]
+// [...]
+// On the 23.07.2009 we tested the new LUTs using the star Etamin. The
+// PSF (sigma) improved from 11.0 mm to 9.5 mm and the total light content
+// in one PMT from 54% to 62%.
+// Furthermore I saw a small movement of the spot after the new focussing:
+//   dX = 3 CCD pixel = 7 mm
+//   dY = 2 CCD pixel = 4.7 mm
+// The new LUTs are now installed since the 23.07.2009 and are used as
+// default during the observation.
+// [...]
+//
+//
+// [2009-10-16 Email Adrian]
+//
+// I checked the AMC2 log files to check which LUTs had been used in which nights
+//   until    09/09/12  the old version from March had always been used
+//   09/09/13-09/09/16  LUT_090913 (test) was used (by mistake)
+//   09/09/17-09/09/20  switched back to the version from March
+//   since    09/09/21  using actual version LUT_090918
+//                      (PSF at ~10deg still rather poor, but I see strange
+//                      effects I do not yet understand and therefore cannot
+//                      correct)
+//  Especially: nothing has changed in the AMC on 09/09/09,
+//  except that around that date the SBIG camera was readjusted (but this
+//  has no direct affect on the AMC)
+//
+//
+// [2010-02-03 M. Garcz.]
+//
+// New LUTs for M2
+//
+// [2010-06-14 M. Garcz.]
+//
+// New LUTs for M1
+//
+// [2010-07-02 M. Garcz.]
+//
+// New LUTs for M1
+//
+// [2010-10-24]
+//
+// Since about this date we see a higher spread in the TPoints. The reason we
+// found is that SA sends the coordinates of the orginal position and not the
+// target position to the AMC thus the mirrors are not well focussed.
+// This should mainly effect the quality of the TPoints but not the pointing
+// model. However, M2 shows a slight offset.
+//
+// [2010-11-11 M. Garcz.]
+//
+// Last night, TPoints for M2 taken without target
+//
+// [2010-11-18 M. Garcz.]
+//
+// New LUTs for M1
+//
+//
+// Others
+// ------
+//
+// The pointing of both(!) telescopes changed >2009/06/11 2:36h
+// In both cases the reason is unknown.
+//
+// The pointing has changed for M2 after    2009/09/09 noon
+// It recovered to the previous pointing at 2009/10/08 noon
+// Resons unknown (there were LUT changes but at different dates)
+//
+//
+// ToDo:
+// -----
+//
+//   * Is 0/0 the best assumption if the starguider partly fails?
+//
+//
+// Input Container:
+//   MRawRunHeader
+//   MReportStarguider
+//
+// Output Container:
+//   MPointingDev
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPointingDevCalc.h"
+
+#include <stdlib.h> // atoi (Ubuntu 8.10)
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MAstro.h"
+#include "MPointing.h"
+#include "MPointingDev.h"
+#include "MRawRunHeader.h"
+#include "MReportStarguider.h"
+
+ClassImp(MPointingDevCalc);
+
+using namespace std;
+
+const TString MPointingDevCalc::fgFilePrefix="resources/starguider";
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Call Clear() and delete fPointingModels if any.
+//
+MPointingDevCalc::~MPointingDevCalc()
+{
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fPointing and set pointing to NULL
+//
+void MPointingDevCalc::Clear(Option_t *o)
+{
+    if (fPointing)
+        delete fPointing;
+
+    fPointing = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sort the entries in fPoinitngModels
+//
+void MPointingDevCalc::SortPointingModels()
+{
+    const int n = fPointingModels.GetSize();
+
+    TArrayI idx(n);
+
+    TMath::Sort(n, fPointingModels.GetArray(), idx.GetArray(), kFALSE);
+
+    const TArrayI arr(fPointingModels);
+
+    for (int i=0; i<n; i++)
+        fPointingModels[i] = arr[idx[i]];
+}
+
+// --------------------------------------------------------------------------
+//
+// Set new pointing models
+//
+void MPointingDevCalc::SetPointingModels(const TString &models)
+{
+    fPointingModels.Set(0);
+
+    if (models.IsNull())
+        return;
+
+    TObjArray *arr = models.Tokenize(" ");
+
+    const int n = arr->GetEntries();
+    fPointingModels.Set(n);
+
+    for (int i=0; i<n; i++)
+        fPointingModels[i] = atoi((*arr)[i]->GetName());
+
+    delete arr;
+
+    SortPointingModels();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a string with the pointing models, seperated by a space.
+//
+TString MPointingDevCalc::GetPointingModels() const
+{
+    TString rc;
+    for (int i=0; i<fPointingModels.GetSize(); i++)
+        rc += Form ("%d ", fPointingModels[i]);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a number to the pointing models
+//
+void MPointingDevCalc::AddPointingModel(UInt_t runnum)
+{
+    const int n = fPointingModels.GetSize();
+    for (int i=0; i<n; i++)
+        if ((UInt_t)fPointingModels[i]==runnum)
+        {
+            *fLog << warn << "WARNING - Pointing model " << runnum << " already in list... ignored." << endl;
+            return;
+        }
+
+    fPointingModels.Set(n+1);
+    fPointingModels[n] = runnum;
+
+    SortPointingModels();
+}
+
+// --------------------------------------------------------------------------
+//
+// Find the highest number in the array which is lower or equal num.
+//
+UInt_t MPointingDevCalc::FindPointingModel(UInt_t num)
+{
+    const int n = fPointingModels.GetSize();
+    if (n==0)
+        return (UInt_t)-1;
+
+    // Loop over all pointing models
+    for (int i=0; i<n; i++)
+    {
+        // The number stored in the array did not yet overtake the runnumber
+        if ((UInt_t)fPointingModels[i]<num)
+            continue;
+
+        // The first pointing model is later than this run: use a default
+        if (i==0)
+            return (UInt_t)-1;
+
+        // The last entry in the array is the right one.
+        return fPointingModels[i-1];
+    }
+
+    // Runnumber is after last entry of pointing models. Use the last one.
+    return fPointingModels[n-1];
+}
+
+// --------------------------------------------------------------------------
+//
+// Clear the pointing model. If run-number >= 87751 read the new
+// pointing model with fFilePrefix
+//
+Bool_t MPointingDevCalc::ReadPointingModel(const MRawRunHeader &run)
+{
+    const UInt_t num = FindPointingModel(run.GetRunNumber());
+
+    // No poinitng models are defined. Use simple dx/dy-calibration
+    if (num==(UInt_t)-1)
+    {
+        Clear();
+        return kTRUE;
+    }
+
+    // compile the name for the starguider files
+    // The file with the number 00000000 is the default file
+    TString fname = Form("%s%08d.txt", fFilePrefix.Data(), num);
+
+    if (!fPointing)
+        fPointing = new MPointing;
+
+    if (fname==fPointing->GetName())
+    {
+        *fLog << inf << fname << " already loaded." << endl;
+        return kTRUE;
+    }
+
+    return fPointing->Load(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check the file/run type from the run-header and if it is a data file
+// load starguider calibration.
+//
+Bool_t MPointingDevCalc::ReInit(MParList *plist)
+{
+    MRawRunHeader *run = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!run)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNsbSum   =  0;
+    fNsbSq    =  0;
+    fNsbCount =  0;
+
+    fRunType = run->GetRunType();
+
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+        if (!fReport)
+            *fLog << warn << "MReportStarguider not found... skipped." << endl;
+        return ReadPointingModel(*run);
+
+    case MRawRunHeader::kRTMonteCarlo:
+        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 MPointingDevCalc::PreProcess(MParList *plist)
+{
+    fDeviation = (MPointingDev*)plist->FindCreateObj("MPointingDev");
+    fReport    = (MReportStarguider*)plist->FindObject("MReportStarguider");
+
+    // We use kRTNone here as a placeholder for data runs.
+    fRunType  = MRawRunHeader::kRTNone;
+    fLastMjd  = -1;
+
+    fSkip.Reset();
+
+    // In cases in which ReInit isn't called right in time (e.g. if
+    // the first starguider event comes before the first data event)
+    fNsbSum   =  0;
+    fNsbSq    =  0;
+    fNsbCount =  0;
+
+    return fDeviation ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Increase fSkip[i] by one. If the data in fDeviation is outdated (older
+// than fMaxAge) and the current report should be skipped reset DevZdAz and
+// DevXY and fSkip[6] is increased by one.
+//
+void MPointingDevCalc::Skip(Int_t i)
+{
+    fSkip[i]++;
+
+    const Double_t diff = (fReport->GetMjd()-fLastMjd)*1440; // [min] 1440=24*60
+    if (diff<fMaxAge && fLastMjd>0)
+        return;
+
+    fDeviation->SetDevZdAz(0, 0);
+    fDeviation->SetDevXY(0, 0);
+    fSkip[6]++;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do a full starguider calibration using a pointing model for the starguider.
+//
+void MPointingDevCalc::DoCalibration(Double_t devzd, Double_t devaz) const
+{
+    if (!fPointing)
+    {
+        // Do a simple starguider calibration using a simple offset in x and y
+        fDeviation->SetDevZdAz(devzd, devaz);
+
+        // Linear starguider calibration taken from April/May data
+        // For calibration add MDriveReport::GetErrorZd/Az !
+        fDeviation->SetDevXY(fDx, fDy); // 1arcmin ~ 5mm
+
+        return;
+    }
+
+    // Get the nominal position the star is at the sky
+    // Unit: deg
+    ZdAz nom(fReport->GetNominalZd(), fReport->GetNominalAz());
+    nom *= TMath::DegToRad();
+
+    // Get the mispointing measured by the telescope. It is
+    // calculate as follows:
+    //
+    // The mispointing measured by the starguider:
+    //    ZdAz mis(devzd, devaz);
+    //    mis *= TMath::DegToRad();
+
+    // The pointing model is the conversion from the real pointing
+    // position of the telescope into the pointing position measured
+    // by the starguider.
+    //
+    // To keep as close to the fitted model we use the forward correction.
+
+    // Position at which the starguider camera is pointing in real:
+    //       pointing position = nominal position - dev
+    //
+    // The position measured as the starguider's pointing position
+    ZdAz pos(nom);        // cpos = sao - dev
+    pos -= ZdAz(devzd, devaz)*TMath::DegToRad();
+
+    // Now we convert the starguider's pointing position into the
+    // telescope pointing position (the pointing model converts
+    // the telescope pointing position into the starguider pointing
+    // position)
+    ZdAz point = fPointing->CorrectBack(pos);  //FWD!!!
+
+    // MSrcPosCalc uses the following condition to calculate the
+    // source position in the camera:
+    //    real pointing pos = nominal pointing pos - dev
+    //      --> dev = nominal - real
+    // Therefor we calculate dev as follows:
+    ZdAz dev(nom);
+    dev -= point;
+    dev *= TMath::RadToDeg();
+
+    /*
+     // We chose the other way. It is less accurate because is is the
+     // other was than the poinitng model was fittet, but it is more
+     // accurate because the nominal (i.e. real) pointing position
+     // is less accurately known than the position returned by the
+     // starguider.
+     //
+     // Calculate the deviation which would be measured by the starguider
+     // if applied to a perfectly pointing telescope.
+     ZdAz dev = fPointing->Correct(nom);
+     dev -= nom;
+
+     // Now add these offsets and the starguider measured offsets to
+     // the real pointing deviation of the telescope (note, that
+     // signs here are just conventions)
+     dev += ZdAz(devzd, devaz)*TMath::DegToRad(); // --> nom-mis
+     dev *= TMath::RadToDeg();
+     */
+
+    // Check if the starguider pointing model requests overwriting
+    // of the values with constants (e.g. 0)
+    devaz = fPointing->IsPxValid() ? fPointing->GetPx() : dev.Az();
+    devzd = fPointing->IsPyValid() ? fPointing->GetPy() : dev.Zd();
+
+    fDeviation->SetDevZdAz(devzd, devaz);
+    fDeviation->SetDevXY(fPointing->GetDxy());
+}
+
+Int_t MPointingDevCalc::ProcessStarguiderReport()
+{
+    Double_t devzd = fReport->GetDevZd(); // [arcmin]
+    Double_t devaz = fReport->GetDevAz(); // [arcmin]
+    if (devzd==0 && devaz==0)
+    {
+        Skip(1);
+        return kTRUE;
+    }
+
+    if (!fReport->IsMonitoring())
+    {
+        Skip(2);
+        return kTRUE;
+    }
+
+    devzd /= 60; // Convert from arcmin to deg
+    devaz /= 60; // Convert from arcmin to deg
+
+    const Double_t nsb = fReport->GetSkyBrightness();
+    if (nsb>0)
+    {
+        if (nsb>fNsbMin && nsb<fNsbMax)
+        {
+            fNsbSum += nsb;
+            fNsbSq  += nsb*nsb;
+            fNsbCount++;
+        }
+
+        if (fNsbCount>0)
+        {
+            const Double_t sum = fNsbSum/fNsbCount;
+            const Double_t sq  = fNsbSq /fNsbCount;
+
+            const Double_t rms = fNsbLevel*TMath::Sqrt(sq - sum*sum);
+
+            if (nsb<sum-rms || nsb>sum+rms)
+            {
+                Skip(3);
+                return kTRUE;
+            }
+        }
+
+        if (fReport->GetNumIdentifiedStars()<fNumMinStars)
+        {
+            Skip(4);
+            return kTRUE;
+        }
+    }
+
+    // >= 87751 (31.3.06 12:00)
+
+    // Calculate absolute deviation
+    const Double_t dev = MAstro::GetDevAbs(fReport->GetNominalZd(),
+                                           fReport->GetNominalZd()-fReport->GetDevZd()/60,
+                                           devaz);
+
+    // Sanity check... larger deviation are strange and ignored
+    if (dev*60>fMaxAbsDev)
+    {
+        Skip(5);
+        return kTRUE;
+    }
+
+    DoCalibration(devzd, devaz);
+
+    fSkip[0]++;
+    fLastMjd = fReport->GetMjd();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  See class description.
+//
+Int_t MPointingDevCalc::Process()
+{
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTNone:
+    case MRawRunHeader::kRTData:
+        return fReport ? ProcessStarguiderReport() : kTRUE;
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fSkip[0]++;
+        fDeviation->SetDevZdAz(0, 0);
+        fDeviation->SetDevXY(0, 0);
+        return kTRUE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print execution statistics
+//
+Int_t MPointingDevCalc::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    PrintSkipped(fSkip[1], "Starguider deviation not set, is exactly 0/0");
+    PrintSkipped(fSkip[2], "Starguider was not monitoring (eg. LEDs off)");
+    PrintSkipped(fSkip[3], Form("NSB out of %.1f sigma range", fNsbLevel));
+    PrintSkipped(fSkip[4], Form("Number of identified stars < %d", fNumMinStars));
+    PrintSkipped(fSkip[5], Form("Absolute deviation > %.1farcmin", fMaxAbsDev));
+    PrintSkipped(fSkip[6], Form("Events set to 0 because older than %.1fmin", fMaxAge));
+    *fLog << " " << (int)fSkip[0] << " (" << Form("%5.1f", 100.*fSkip[0]/GetNumExecutions()) << "%) Evts survived calculation!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// MPointingDevCalc.NumMinStars: 8
+// MPointingDevCalc.NsbLevel:    3.0
+// MPointingDevCalc.NsbMin:      30
+// MPointingDevCalc.NsbMax:      60
+// MPointingDevCalc.MaxAbsDev:   15
+// MPointingDevCalc.MaxAge:      1.0
+// MPointingDevCalc.Dx:         -0.001
+// MPointingDevCalc.Dy:         -0.004
+//
+// For a detailed description see the class reference.
+//
+Int_t MPointingDevCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumMinStars", print))
+    {
+        SetNumMinStars(GetEnvValue(env, prefix, "NumMinStars", (Int_t)fNumMinStars));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "NsbLevel", print))
+    {
+        SetNsbLevel(GetEnvValue(env, prefix, "NsbLevel", fNsbLevel));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "NsbMin", print))
+    {
+        SetNsbMin(GetEnvValue(env, prefix, "NsbMin", fNsbMin));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "NsbMax", print))
+    {
+        SetNsbMax(GetEnvValue(env, prefix, "NsbMax", fNsbMax));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "MaxAbsDev", print))
+    {
+        SetMaxAbsDev(GetEnvValue(env, prefix, "MaxAbsDev", fMaxAbsDev));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Dx", print))
+    {
+        fDx = GetEnvValue(env, prefix, "Dx", fDx);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Dy", print))
+    {
+        fDy = GetEnvValue(env, prefix, "Dy", fDy);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "MaxAge", print))
+    {
+        fMaxAge = GetEnvValue(env, prefix, "MaxAge", fMaxAge);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "FilePrefix", print))
+    {
+        fFilePrefix = GetEnvValue(env, prefix, "FilePrefix", fFilePrefix);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "PointingModels", print))
+    {
+        SetPointingModels(GetEnvValue(env, prefix, "PointingModels", GetPointingModels()));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mpointing/MPointingDevCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingDevCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingDevCalc.h	(revision 17960)
@@ -0,0 +1,103 @@
+#ifndef MARS_MPointingPositionCalc
+#define MARS_MPointingPositionCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MPointing;
+class MPointingDev;
+class MRawRunHeader;
+class MReportStarguider;
+
+class MPointingDevCalc : public MTask
+{
+private:
+    static const TString fgFilePrefix; //! default file name of pointing model
+
+    MReportStarguider *fReport;    //! MReportStarguider to get mispointing
+    MPointingDev      *fDeviation; //! Output container to store pointing deviation
+    MPointing         *fPointing;  //! MPointing, pointing model for the calibration
+
+    UShort_t fRunType;             //! Run Type to decide where to get pointing position from
+
+    Double_t fNsbSum;              //! Sum of Nsb from Starguider
+    Double_t fNsbSq;               //! Sum of Sq of Nsb from Starguider
+    Int_t    fNsbCount;            //! Counter of Nsb entries from Starguider
+
+    TArrayI  fSkip;                //! Counter for execution statistics
+    Double_t fLastMjd;             //! Time of last processed report
+
+    TString fFilePrefix;           // File name of pointing model
+    TArrayI fPointingModels;       // List with pointing models
+
+    UInt_t  fNumMinStars;          // [num] Minimum number of identified stars
+    Float_t fNsbLevel;             // Minimum deviation from mean in sigma
+    Float_t fNsbMin;               // [au] Minimum NSB to calc mean and rms
+    Float_t fNsbMax;               // [au] Maximum NSB to calc mean and rms
+    Float_t fMaxAbsDev;            // [arcmin] Maximum considered absolute deviation
+    Float_t fMaxAge;               // [min] Maximum age of reports to be used without an update
+
+    Float_t fDx;                   // [deg] Starguider calibration dx
+    Float_t fDy;                   // [deg] Starguider calibration dy
+
+    // MPointingDevCalc
+    void DoCalibration(Double_t devzd, Double_t devaz) const;
+
+    Bool_t ReadPointingModel(const MRawRunHeader &run);
+    UInt_t FindPointingModel(UInt_t num);
+    void   SortPointingModels();
+
+    Int_t ProcessStarguiderReport();
+    void  Skip(Int_t i);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Bool_t ReInit(MParList *plist);
+    Int_t  PreProcess(MParList *plist);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MPointingDevCalc() : fReport(0), fDeviation(0), fPointing(0),
+        fSkip(7), fFilePrefix(fgFilePrefix), fNumMinStars(8),
+        fNsbLevel(3), fNsbMin(30), fNsbMax(60), fMaxAbsDev(15),
+        fMaxAge(1), fDx(0), fDy(0)
+    {
+        fName  = "MPointingDevCalc";
+        fTitle = "Task calculating the starguider correction";
+
+        AddToBranchList("MReportStarguider.*");
+    }
+    ~MPointingDevCalc();
+
+    // Tobject
+    void Clear(Option_t *o="");
+
+    // Setter
+    void SetNumMinStars(UInt_t n)  { fNumMinStars=n; }
+    void SetNsbLevel(Float_t lvl)  { fNsbLevel=lvl;  }
+    void SetNsbMin(Float_t nsb)    { fNsbMin=nsb;    }
+    void SetNsbMax(Float_t nsb)    { fNsbMax=nsb;    }
+    void SetMaxAbsDev(Float_t max) { fMaxAbsDev=max; }
+    void SetDx(Float_t dx)         { fDx=dx; }
+    void SetDy(Float_t dy)         { fDy=dy; }
+    void SetMaxAge(Float_t age)    { fMaxAge=age; }
+
+    void SetFilePrefix(const char *n) { fFilePrefix=n; }
+
+    // Handle pointing models
+    void    SetPointingModels(const TString &models);
+    void    AddPointingModel(UInt_t runnum);
+    TString GetPointingModels() const;
+
+    ClassDef(MPointingDevCalc, 0) //Task calculating the starguider correction
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MPointingPos.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingPos.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingPos.cc	(revision 17960)
@@ -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, 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 "MLog.h"
+
+#include "MTime.h"
+#include "MAstro.h"
+#include "MString.h"
+#include "MObservatory.h"
+#include "MPointingDev.h"
+#include "MAstroSky2Local.h"
+
+ClassImp(MPointingPos);
+
+using namespace std;
+
+const TString MPointingPos::gsDefName  = "MPointingPos";
+const TString MPointingPos::gsDefTitle = "Container storing the (corrected) telescope pointing position";
+
+Double_t MPointingPos::GetZdRad() const
+{
+    return fZd*TMath::DegToRad();
+}
+
+Double_t MPointingPos::GetAzRad() const
+{
+    return fAz*TMath::DegToRad();
+}
+
+Double_t MPointingPos::GetRaRad() const
+{
+    return fRa*TMath::DegToRad()*15;
+}
+
+Double_t MPointingPos::GetDecRad() const
+{
+    return fDec*TMath::DegToRad();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the corresponding rotation angle of the sky coordinate system
+// seen with an Alt/Az telescope calculated from the stored local
+// (Zd/Az) coordinates.
+//
+// Return angle [rad] in the range -pi, pi
+//
+// 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.
+//
+// Return angle [rad] in the range -pi, pi
+//
+// For more information see MAstro::RotationAngle
+//
+Double_t MPointingPos::RotationAngle(const MObservatory &o, const MTime &t, const MPointingDev *dev) const
+{
+    return dev ?
+        MAstroSky2Local(t, o).RotationAngle(GetRaRad(), GetDecRad(), dev->GetDevZdRad(), dev->GetDevAzRad()):
+        MAstroSky2Local(t, o).RotationAngle(GetRaRad(), GetDecRad());
+}
+
+TString MPointingPos::GetString(Option_t *o) const
+{
+    TString opt(o);
+
+    if (opt.IsNull())
+        opt = "radeczdaz";
+
+    TString rc;
+
+    if (opt.Contains("ra", TString::kIgnoreCase))
+        rc += MString::Format(" Ra=%s", MAstro::GetStringHor(fRa).Data());
+
+    if (opt.Contains("ha", TString::kIgnoreCase))
+        rc += MString::Format(" Ha=%s", MAstro::GetStringHor(fHa).Data());
+
+    if (opt.Contains("dec", TString::kIgnoreCase))
+        rc += MString::Format(" Dec=%s", MAstro::GetStringDeg(fDec).Data());
+
+    if (opt.Contains("zd", TString::kIgnoreCase))
+        rc += MString::Format(" Zd=%s", MAstro::GetStringDeg(fZd).Data());
+
+    if (opt.Contains("az", TString::kIgnoreCase))
+        rc += MString::Format(" Az=%s", MAstro::GetStringDeg(fAz).Data());
+
+    if (fTitle!=gsDefTitle)
+        rc += MString::Format(" <%s>", fTitle.Data());
+
+    return rc.Strip(TString::kBoth);
+}
+
+void MPointingPos::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": " << GetString(o) << endl;
+}
Index: branches/Mars_McMismatchStudy/mpointing/MPointingPos.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingPos.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingPos.h	(revision 17960)
@@ -0,0 +1,78 @@
+#ifndef MARS_MPointingPos
+#define MARS_MPointingPos
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+// FIXME: Should not be here... (ZdAz)
+#ifndef MARS_MPointing
+#include "MPointing.h"
+#endif
+
+class MTime;
+class MObservatory;
+class MPointingDev;
+
+class MPointingPos : public MParContainer
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    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
+
+    // Hour angle!
+    // Angle to magnetic field!
+
+public:
+    MPointingPos(const char *name=0, const char *title=0) : fZd(0), fAz(0), fRa(0), fHa(0), fDec(0)
+    {
+        fName  = name  ? (TString)name  : gsDefName;
+        fTitle = title ? (TString)title : gsDefTitle;
+    }
+    MPointingPos(const MPointingPos &p) : MParContainer(p),
+        fZd(p.fZd), fAz(p.fAz), fRa(p.fRa), fHa(p.fHa), fDec(p.fDec)
+    {
+    }
+
+    Bool_t IsInitialized() const { return !(fZd==0 && fAz==0 && fRa==0 && fHa==0 && fDec==0); }
+
+    void Print(Option_t *o="") const;
+
+    TString GetString(Option_t *o="") const;
+
+    void SetLocalPosition(Double_t zd, Double_t az) { fZd=zd; fAz=az; }
+    void SetSkyPosition(Double_t ra, Double_t dec, Double_t ha=0) { fRa=ra; fDec=dec; fHa=ha; }
+
+    Double_t GetZd() const  { return fZd; }
+    Double_t GetAz() const  { return fAz; }
+
+    Double_t GetZdRad() const;//  { return fZd*TMath::DegToRad(); }
+    Double_t GetAzRad() const;//  { return fAz*TMath::DegToRad(); }
+
+    ZdAz GetZdAz() const { return ZdAz(fZd, fAz); }
+
+    Double_t GetRa() const  { return fRa; }
+    Double_t GetHa() const  { return fHa; }
+    Double_t GetDec() const { return fDec; }
+
+    Double_t GetRaRad() const;//  { return fRa*TMath::DegToRad()*15; }
+    Double_t GetDecRad() const;// { return fDec*TMath::DegToRad(); }
+
+    Double_t RotationAngle(const MObservatory &o) const;
+    Double_t RotationAngle(const MObservatory &o, const MTime &t, const MPointingDev *dev=0) 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: branches/Mars_McMismatchStudy/mpointing/MPointingPosCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingPosCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingPosCalc.cc	(revision 17960)
@@ -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/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
+//
+// We do a trick: Because it is not guranteed, that MReadReports calls
+//  ReInit before the first event from the drive-tree is read (because
+//  the first data event may have a time-stamp later than the first
+//  drive event) we always assume that the current run is a data run.
+//  If the assumption is true fReport should be initialized correctly.
+//  For MC runs this should never happen, Because they are read though
+//  MReadMarsFile which gurantees, that ReInit is always called before
+//  Process. If we encounter such a case we stop execution.
+//
+// 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:
+        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");
+    fReport   = (MReportDrive*)plist->FindObject("MReportDrive");
+
+    // We use kRTNone here as a placeholder for data runs.
+    fRunType  = MRawRunHeader::kRTNone;
+
+    return fPosition ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  See class description.
+//
+Int_t MPointingPosCalc::Process()
+{
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTNone:
+    case MRawRunHeader::kRTData:
+        if (!fReport)
+        {
+            *fLog << warn;
+            *fLog << "MPointingPosCalc::Process: fReport==NULL && fRunType!=kRTMonteCarlo... abort!" << endl;
+            return kERROR;
+        }
+        fPosition->SetLocalPosition(fReport->GetNominalZd(), fReport->GetNominalAz());
+        fPosition->SetSkyPosition(fReport->GetRa(), fReport->GetDec());
+        return kTRUE;
+
+    case MRawRunHeader::kRTMonteCarlo:
+        if (!fMcEvt)
+        {
+            *fLog << warn;
+            *fLog << "MPointingPosCalc::Process: fMcEvt==NULL && fRunType==kRTMonteCarlo... abort!" << endl;
+            return kERROR;
+        }
+        fPosition->SetLocalPosition(fMcEvt->GetTelescopeTheta()*TMath::RadToDeg(), fMcEvt->GetTelescopePhi()*TMath::RadToDeg());
+        return kTRUE;
+    }
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mpointing/MPointingPosCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingPosCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingPosCalc.h	(revision 17960)
@@ -0,0 +1,38 @@
+#ifndef MARS_MPointingPosCalc
+#define MARS_MPointingPosCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MReportDrive;
+class MPointingPos;
+
+class MPointingPosCalc : public MTask
+{
+private:
+    MMcEvt       *fMcEvt;    //! MMcEvt to get simulated poiting position from
+    MReportDrive *fReport;   //! MReportDrive to get real poiting position from
+    MPointingPos *fPosition; //! Output container to store pointing position
+
+    UShort_t fRunType;       //! Run Type to decide where to get pointing position from
+
+    Bool_t ReInit(MParList *plist);
+    Int_t  PreProcess(MParList *plist);
+    Int_t  Process();
+
+public:
+    MPointingPosCalc() : fMcEvt(0), fReport(0), fPosition(0)
+    {
+        fName  = "MPointingPosCalc";
+        fTitle = "Task calculating the pointing position";
+
+        AddToBranchList("MReportDrive.*");
+        AddToBranchList("MMcEvt.*");
+    }
+
+    ClassDef(MPointingPosCalc, 0) //Task calculating the pointing position
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MPointingPosInterpolate.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingPosInterpolate.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingPosInterpolate.cc	(revision 17960)
@@ -0,0 +1,412 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez 03/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MExtrapolatePointingPos
+//
+//   In the PreProcess, read the drive report and store it in an TSpline.
+//   In the Process, use the TSpline to calculate the PointingPos for the 
+//   time of the current event.
+// 
+//  Input Containers:
+//    MRawEvtData
+//    MReportDrive
+//    MTimeDrive
+//    MTime
+//
+//  Output Containers:
+//    MPointingPos
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MPointingPosInterpolate.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include <TSpline.h>
+
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MEvtLoop.h"
+#include "MReadReports.h"
+#include "MReportDrive.h"
+#include "MPointingPos.h"
+#include "MTime.h"
+#include "MRawRunHeader.h"
+#include "MDirIter.h"
+
+#include <TCanvas.h>
+
+ClassImp(MPointingPosInterpolate);
+
+using namespace std;
+
+const Int_t MPointingPosInterpolate::fgNumStartEvents = 1;
+// --------------------------------------------------------------------------
+//
+//  Constructor
+//
+MPointingPosInterpolate::MPointingPosInterpolate(const char *name, const char *title)
+  : fEvtTime(NULL), fPointingPos(NULL), fRunHeader(NULL), fDirIter(NULL), 
+    fSplineZd(NULL), fSplineAz(NULL), fRa(0.), fDec(0.),
+    fTimeMode(MPointingPosInterpolate::kEventTime)
+
+{
+    fName  = name  ? name  : "MPointingPosInterpolate";
+    fTitle = title ? title : "Task to interpolate the pointing positons from drive reports";
+
+    fFilename = "";
+    fDebug = kFALSE;
+
+    SetNumStartEvents();
+}
+
+
+MPointingPosInterpolate::~MPointingPosInterpolate()
+{
+  Clear();
+}
+
+void MPointingPosInterpolate::Clear(Option_t *o)
+{
+  if(fSplineZd)
+    delete fSplineZd;
+  if(fSplineAz)
+    delete fSplineAz;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Read the drive report file for the whole night, a build from it the splines
+//
+Bool_t MPointingPosInterpolate::ReadDriveReport()
+{
+
+    *fLog << inf << "Loading report file \"" << fFilename << "\" into TSpline..." << endl;
+
+    if (!fDebug)
+        gLog.SetNullOutput();
+
+    //
+    // ParList
+    //
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+
+    //
+    // TaskList
+    //
+    MReadReports read;
+    read.AddTree("Drive");
+    if (fDirIter)
+      read.AddFiles(*fDirIter);
+    else 
+      read.AddFile(fFilename);     // after the reading of the trees!!!
+
+    read.AddToBranchList("MReportDrive.*");
+    
+    tlist.AddToList(&read);
+    
+    //
+    // EventLoop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.PreProcess())
+    {
+        gLog.SetNullOutput(kFALSE);
+        return kFALSE;
+    }
+
+    TArrayD reportTime(fNumStartEvents);
+    TArrayD currentZd(fNumStartEvents);
+    TArrayD currentAz(fNumStartEvents); 
+    TArrayD nominalZd(fNumStartEvents);
+    TArrayD nominalAz(fNumStartEvents);
+    
+    Int_t n=1;
+    while (tlist.Process())
+    { 
+	MReportDrive* report = (MReportDrive*)plist.FindObject("MReportDrive");
+	MTime* reporttime = (MTime*)plist.FindObject("MTimeDrive");
+	
+	if(n==1)
+	  fFirstDriveTime = *reporttime;
+	else 
+	  fLastDriveTime = *reporttime;
+
+	//
+	// Update the number of entries
+	//
+	if (n>fNumStartEvents)
+	  {
+	    reportTime.Set(n);
+	    currentZd.Set(n);
+	    currentAz.Set(n); 
+	    nominalZd.Set(n);
+	    nominalAz.Set(n);
+	  }
+	//
+	// Sometimes there are two reports with the same time
+	//
+	if (n>1)
+	  if (reporttime->GetTime() == reportTime[n-2])
+	    { 
+	      *fLog << warn <<"["<< GetName() 
+		    << "]: Warning: this report has the same time that the previous one...skipping it " << endl;
+	      continue;
+	    }
+
+	reportTime[n-1] = reporttime->GetTime();
+	currentZd [n-1] = report->GetCurrentZd();
+	currentAz [n-1] = report->GetCurrentAz();
+	nominalZd [n-1] = report->GetNominalZd();
+	nominalAz [n-1] = report->GetNominalAz();
+	fRa             = report->GetRa();
+	fDec            = report->GetDec();
+
+	if (fDebug)
+	  {
+	    *fLog << " GetTime(): " << reporttime->GetTime() << endl;
+	    *fLog << " GetCurrentZd(): " << report->GetCurrentZd() << endl;
+	  }
+	n++;
+    }
+
+    tlist.PrintStatistics();
+
+    gLog.SetNullOutput(kFALSE);
+
+    *fLog << inf << GetDescriptor() << ": loaded " << n-1 << " ReportDrive from "
+	  << fFirstDriveTime << " to " << fLastDriveTime << endl;
+
+    if (fDebug)
+      {
+     	for (int i=0;i<reportTime.GetSize();i++)
+	  *fLog << i            << " " << reportTime[i] << " " 
+ 	      	<< currentZd[i] << " " << currentAz[i]  << " " 
+		<< nominalZd[i] << " " << nominalAz[i]  << endl;
+      }
+
+    fSplineZd = new TSpline3("zenith",
+			     reportTime.GetArray(), nominalZd.GetArray(), n-1);
+    fSplineAz = new TSpline3("azimuth",
+			     reportTime.GetArray(), nominalAz.GetArray(), n-1);
+
+    
+    if (fDebug)
+    {
+        *fLog << n-1 << " " << reportTime.GetSize() << endl;
+        *fLog << n-1 << " " << nominalZd.GetSize() << endl;
+        *fLog << fFirstDriveTime.GetTime() << " " << fSplineZd->Eval((fFirstDriveTime.GetTime()+fLastDriveTime.GetTime())/2.) << endl;
+	TCanvas* c = new TCanvas();
+      	c->Divide(2,1);
+      	c->cd(1);
+   	fSplineZd->Draw();
+   	c->cd(2);
+   	fSplineAz->Draw();
+   	c->Modified();
+   	c->Update();
+        c->SaveAs("pointing.root");
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Input:
+//  - MTime
+// 
+//  Output:
+//  - MPointingPos
+//
+Int_t MPointingPosInterpolate::PreProcess( MParList *pList )
+{
+
+    Clear();
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fEvtTime = (MTime*)pList->FindObject("MTime");
+    if (!fEvtTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointingPos = (MPointingPos*)pList->FindCreateObj("MPointingPos");
+    if (!fPointingPos)
+      return kFALSE;
+
+    if (fFilename.IsNull() && !fDirIter)
+      {
+	*fLog << err << "File name is empty or no MDirIter has been handed over... aborting" << endl;
+	return kFALSE;
+      }
+
+    if( !ReadDriveReport() )
+	return kFALSE;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Get the run start time, and get the pointing position for that time
+//
+Int_t MPointingPosInterpolate::Process()
+{
+
+    //const Int_t run = fRunHeader->GetRunNumber();
+  const MTime &StartRunTime = fRunHeader->GetRunStart();
+  const MTime &EndRunTime   = fRunHeader->GetRunEnd();
+  Int_t time = StartRunTime.GetTime();
+
+   switch(fTimeMode)
+    {
+     case kRunTime:
+         //
+         // Check that we have drive report for this time
+         //
+
+         time = (EndRunTime.GetTime() + StartRunTime.GetTime())/2;
+
+         if( StartRunTime<fFirstDriveTime || StartRunTime>fLastDriveTime)
+         {
+             *fLog << err << GetDescriptor() << ": Run time " << StartRunTime
+                   << " outside range of drive reports  (" << fFirstDriveTime
+                   << ", " << fLastDriveTime << ")" << endl;
+
+            if ( *fEvtTime<fFirstDriveTime )  time = fFirstDriveTime.GetTime();
+            if ( *fEvtTime>fLastDriveTime )   time = fLastDriveTime.GetTime();
+
+             *fLog << " PointingPos: time = " << time << " (" << *fEvtTime << ")  (zd, az) = (" 
+		   << fSplineZd->Eval( time )<< ", "  <<fSplineAz->Eval( time )<< ")" << endl;
+         }
+         break;
+
+    case kEventTime:
+      
+        time = fEvtTime->GetTime();       
+
+        //
+        // Check that we have drive report for this time
+        //
+        if( *fEvtTime<fFirstDriveTime || *fEvtTime>fLastDriveTime)
+        {
+	    if (fDebug)
+	      {
+		*fLog << err << GetDescriptor() << ": Run time = "
+		      << *fEvtTime << " outside range of drive reports  ("
+    	              << fFirstDriveTime << ", "<< fLastDriveTime << ")" << endl;
+               }		
+
+	    if ( *fEvtTime < (fFirstDriveTime) )   time = fFirstDriveTime.GetTime();
+	    else                                   time = fLastDriveTime.GetTime();
+		
+        }
+        break;
+    }
+
+   if (fDebug)
+     {
+       *fLog << " real time : " << time 
+	     << " first time: " << fFirstDriveTime.GetTime()
+	     << " last time: " << fLastDriveTime.GetTime() << endl;
+       *fLog << " PointingPos: time = " << time << " (" << *fEvtTime << ")  (zd, az) = (" 
+	     << fSplineZd->Eval( time )<< ", "  <<fSplineAz->Eval( time )<< ")" << endl;
+     }
+    //
+    // Check that we have drive report for this time
+    //
+    //if( *StartRunTime<fFirstDriveTime || *StartRunTime>fLastDriveTime)
+    if( StartRunTime>fLastDriveTime)
+    {
+	*fLog << err << GetDescriptor() << ": Run time " << StartRunTime
+	      << " outside range of drive reports  (" << fFirstDriveTime 
+	      << ", " << fLastDriveTime << ")" << endl;
+	return kERROR;
+    }
+
+    const Double_t zd = fSplineZd->Eval( time );
+    const Double_t az = fSplineAz->Eval( time );
+
+    if(TMath::Abs(zd)>90 || TMath::Abs(az)>360)
+      {
+        *fLog << warn << GetDescriptor() << ": Wrong Interpolated Pointing Position." << endl;
+	*fLog << " PointingPos: time = " << time << " (" << *fEvtTime << ")  (zd, az, ra, dec) = (" 
+	      << zd << ", "  << az << "," << fRa << "," << fDec << ")" << endl;
+      }
+
+    fPointingPos->SetLocalPosition( zd, az );
+    //fPointingPos->SetSkyPosition( fRa*TMath::DegToRad()/15, fDec*TMath::DegToRad());
+    fPointingPos->SetSkyPosition( fRa, fDec);
+
+    return kTRUE;
+}
+
+
+
+Int_t MPointingPosInterpolate::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "NumStartEvents", print))
+      {
+	SetNumStartEvents(GetEnvValue(env, prefix, "NumStartEvents", fNumStartEvents));
+	rc = kTRUE;
+      }
+
+    if (IsEnvDefined(env, prefix, "TimeMode", print))
+      {
+
+	TString dat(GetEnvValue(env, prefix, "TimeMode", ""));
+	dat.ToLower();
+
+	rc = kTRUE;
+
+	if (dat.Contains("eventtime"))
+	  SetTimeMode(kEventTime);
+	else if (dat.Contains("runtime"))
+	  SetTimeMode(kRunTime);
+	else
+	  rc = kFALSE;
+      }
+    return rc;
+}
+
Index: branches/Mars_McMismatchStudy/mpointing/MPointingPosInterpolate.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MPointingPosInterpolate.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MPointingPosInterpolate.h	(revision 17960)
@@ -0,0 +1,81 @@
+#ifndef MARS_MPointingPosInterpolate
+#define MARS_MPointingPosInterpolate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TSpline
+#include <TSpline.h>
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MTime;
+class MPointingPos;
+class MRawRunHeader;
+class MDirIter;
+
+class MPointingPosInterpolate : public MTask
+{
+public:
+
+    enum TimeMode_t {
+        kRunTime,
+        kEventTime
+    };
+
+private:
+
+  static const Int_t fgNumStartEvents; //! Default for fNumStartEvents (now set to: 10000)
+
+  Int_t fNumStartEvents;               //  Start number of allowed events
+
+  Bool_t fDebug;
+
+  TString fFilename;
+  MTime   fFirstDriveTime;
+  MTime   fLastDriveTime;
+  
+  MTime         *fEvtTime;             //! Raw event time
+  MPointingPos  *fPointingPos;         //! Telescope pointing postion
+  MRawRunHeader *fRunHeader;           //! Run Header
+  MDirIter      *fDirIter;             //! Dir Iter
+  
+  TSpline3* fSplineZd;                 //! Zd vs. time
+  TSpline3* fSplineAz;                 //! Az vs. time
+
+  Double_t  fRa;                       // RA of source
+  Double_t  fDec;                      // Dec of source
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Bool_t ReadDriveReport();    
+
+  TimeMode_t fTimeMode;
+
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    
+  MPointingPosInterpolate(const char *name=NULL, const char *title=NULL);
+
+  ~MPointingPosInterpolate();
+
+  void AddFiles(MDirIter *dir) { fDirIter = dir; }
+  void AddFile(const char *name) { fFilename = name; }
+
+  void SetTimeMode( TimeMode_t mode) { fTimeMode = mode; }
+  void SetDebug( const Bool_t b=kTRUE) { fDebug = b; }
+
+  void Clear(Option_t *o="");
+  
+  Int_t GetNumStartEvents() const { return fNumStartEvents; }
+  void  SetNumStartEvents ( const Int_t i=fgNumStartEvents ) { fNumStartEvents = i; }
+
+  ClassDef(MPointingPosInterpolate, 1)  // Interpolate the drive pointing positions
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosCalc.cc	(revision 17960)
@@ -0,0 +1,620 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosCalc
+//
+// Calculate the current source position in the camera from the (possibly
+// already corrected, by starguider) J2000 sky coordinates of the camera
+// center (contained in MPointingPos), and the source J2000 sky
+// coordinates contained in MSourcePos (of type MPointingPos as well). If
+// no MSourcePos is found in the parameter list,  source position is
+// assumed to be the same for all events, that specified in  MSrcPosCam
+// (if it already existed in the parameter list), or (0,0), the center  of
+// the camera, if no MSrcPosCam was present in the parameter list. In both
+// cases, no calculation is necessary and then the PreProcess returns
+// kSKIP so that the task is removed from the task list.
+// 
+// The conversion factor between the camera plain (mm) and the sky (deg)
+// is taken from MGeomCam. The time is taken from MTime, and the
+// coordinates of the observatory from MObservatory.
+//
+// If a reflector version >= 700 is detected the source position for
+// Gammas (and _only_ gammas) is dynamically calculated from the
+// telescope (e.g. MMcEvt::fTelescopePhi) and the shower (e.g. MMcEvt::fPhi)
+// orientation. In off-mode it is fixed at the camera center.
+//
+// FIXME: Add here some information about the more-cycle calculation
+//
+// Input Container:
+//   MPointingPos
+//   MObservatory
+//   MGeomCam
+//   MTime
+//   [MMcRunHeader]
+//   [MMcCorsikaRunHeader]
+//   [MSourcePos] (of type MPointingPos)
+//
+// Output Container:
+//   MSrcPosCam
+//
+// To be done:
+//   - a switch between using sky-coordinates and time or local-coordinates
+//     from MPointingPos for determine the rotation angle. (Therefor a conversion
+//     needs to be implemented inlcuding asrometric corrections)
+//
+//   - the center of rotation need not to be the camera center
+/////  NOTE, A. Moralejo: I don't see the need for special code either.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosCalc.h"
+
+#include <TRandom.h>
+#include <TVector2.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MPointingDev.h"
+#include "MSrcPosCam.h"
+#include "MRawRunHeader.h"
+
+#include "MMcEvt.hxx"
+#include "MMcRunHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+#include "MAstro.h"
+#include "MVector3.h"
+#include "MAstroSky2Local.h"
+
+ClassImp(MSrcPosCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize fY and fY with 0
+//
+MSrcPosCalc::MSrcPosCalc(const char *name, const char *title)
+    : fObservatory(NULL), fPointPos(NULL), fDeviation(NULL), fMcEvt(NULL),
+    fMcHeader(NULL), fMcCorsika(NULL), fGeom(NULL), fTime(NULL), fCallback(NULL),
+    fSourcePos(NULL), fSrcPosCam(NULL), fSrcPosAnti(NULL), fMode(kDefault),
+    fNumRandomOffPositions(0)
+{
+    fName  = name  ? name  : "MSrcPosCalc";
+    fTitle = title ? title : "Calculates the source position in the camera";
+
+    AddToBranchList("MTime.*");
+    AddToBranchList("MMcEvt.*");
+    AddToBranchList("MPointingPos.*");
+}
+
+// --------------------------------------------------------------------------
+//
+//  delete fSourcePos if kIsOwner
+//  set fSourcePos to NULL
+//
+void MSrcPosCalc::FreeSourcePos()
+{
+    if (fSourcePos && TestBit(kIsOwner))
+        delete fSourcePos;
+
+    fSourcePos = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  ra  [h]
+//  dec [deg]
+//
+void MSrcPosCalc::SetSourcePos(Double_t ra, Double_t dec)
+{
+    FreeSourcePos();
+
+    fSourcePos = new MPointingPos("MSourcePos");
+    fSourcePos->SetSkyPosition(ra, dec);
+
+    SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return ra/dec as string
+//
+TString MSrcPosCalc::GetRaDec(const MPointingPos &pos) const
+{
+    const TString rstr = MAstro::Angle2Coordinate(pos.GetRa());
+    const TString dstr = MAstro::Angle2Coordinate(pos.GetDec());
+
+    return Form("Ra=%sh Dec=%sdeg", rstr.Data(), dstr.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Search and if necessary create MSrcPosCam in the parameter list. Search
+// MSourcePos. If not found, do nothing else, and skip the task. If MSrcPosCam
+// did not exist before and has been created here, it will contain as source
+// position the camera center (0,0).
+// In the case that MSourcePos is found, go ahead in searching the rest of
+// necessary containers. The source position will be calculated for each
+// event in Process.
+//
+Int_t MSrcPosCalc::PreProcess(MParList *pList)
+{
+    // Reset fixed position
+    fFixedPos = TVector2();
+
+    fSrcPosCam = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPosCam)
+        return kFALSE;
+
+    fSrcPosAnti = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", "MSrcPosAnti");
+    if (!fSrcPosAnti)
+        return kFALSE;
+
+    fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointPos = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fSourcePos)
+    {
+        fSourcePos = (MPointingPos*)pList->FindObject("MSourcePos", "MPointingPos");
+        if (!fSourcePos)
+        {
+            *fLog << inf;
+            *fLog << "MSourcePos [MPointPos] not found... The source position" << endl;
+            *fLog << "set in MSrcPosCam will be set to  (0/0)  or in the case" << endl;
+            *fLog << "of  Monte Carlo set to the appropriate wobble position." << endl;
+            return kTRUE;
+        }
+    }
+    // FIXME: Maybe we have to call FreeSourcePos in PostProcess()?
+
+    fDeviation = (MPointingDev*)pList->FindObject("MPointingDev");
+
+    *fLog << inf;
+    //*fLog << "Pointing Position: " << GetRaDec(*fPointPos)  << endl;
+    *fLog << "Source Position: " << GetRaDec(*fSourcePos) << endl;
+    if (fCallback)
+        *fLog << "Calculating " << fCallback->GetNumPasses() << " off-regions." << endl;
+    if (fNumRandomOffPositions)
+        *fLog << "Calculating " << fNumRandomOffPositions << " random off-regions." << endl;
+
+    // For the case ReInit is never called we try:
+    fObservatory = (MObservatory*)pList->FindObject("MObservatory");
+    fTime        = (MTime*)       pList->FindObject("MTime");
+    fRunType     = MRawRunHeader::kRTNone;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Divide the 360deg into num+1 positions. Rotate the given vector
+// by pass+1 steps and return the result.
+//
+TVector2 MSrcPosCalc::Rotate(TVector2 v, Int_t pass, Int_t num) const
+{
+    const Double_t step = TMath::TwoPi()/(num+1);
+    return v.Rotate(step*(pass+1));
+}
+
+// --------------------------------------------------------------------------
+//
+// If fIsWobbleMode==kFALSE set source position to v and anto-source
+// position to -v, if fIsWobbleMode==kTRUE vice versa.
+//
+void MSrcPosCalc::SetSrcPos(TVector2 v) const
+{
+    if (fMode==kWobble)
+    {
+        // The trick here is that the anti-source position in case
+        // of the off-source regions is always the on-source positon
+        // thus a proper anti-source cut is possible.
+        fSrcPosAnti->SetXY(v);
+        if (fCallback)
+            v = Rotate(v, fCallback->GetNumPass(), fCallback->GetNumPasses());
+        else
+            v *= -1;
+        fSrcPosCam->SetXY(v);
+    }
+    else
+    {
+        // Because we don't process this three times like in the
+        // wobble case we have to find another way to determine which
+        // off-source region is the right anti-source position
+        // We do it randomly.
+        fSrcPosCam->SetXY(v);
+        if (fNumRandomOffPositions>1)
+            v = Rotate(v, gRandom->Integer(fNumRandomOffPositions), fNumRandomOffPositions);
+        else
+            v *= -1;
+        fSrcPosAnti->SetXY(v);
+    }
+}
+
+void MSrcPosCalc::InitFixedPos() const
+{
+    // It is set here for the cases in which Process is not called at all
+    fSrcPosCam->SetXY(fFixedPos/fGeom->GetConvMm2Deg());
+
+    // Informal message output
+    *fLog << inf;
+    *fLog << "Source position set to x=" << fFixedPos.X() << "deg ";
+    *fLog << "y=" << fFixedPos.Y() << "deg" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checking for file type. If the file type is Monte Carlo the
+// source position is arbitrarily determined from the MC headers.
+//
+Bool_t MSrcPosCalc::ReInit(MParList *plist)
+{
+    // In OffMode set fixed position to camera center
+    if (fMode==kOffData)
+        fFixedPos = TVector2();
+
+    if (fMode==kOffData || fMode==kFixed)
+    {
+        // It is set here for the cases in which Process is not called at all
+        InitFixedPos();
+        return kTRUE;
+    }
+
+    MRawRunHeader *run = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!run)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunType = run->GetRunType();
+
+    if (fRunType!=MRawRunHeader::kRTMonteCarlo)
+    {
+        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;
+        }
+
+        return kTRUE;
+    }
+
+    fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcHeader = (const MMcRunHeader*)plist->FindObject("MMcRunHeader");
+    if (!fMcHeader)
+    {
+        *fLog << err << "MMcRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcCorsika = 0;
+    if (fMcHeader->IsCeres())
+        return kTRUE;
+
+    fMcCorsika = (MMcCorsikaRunHeader*)plist->FindObject("MMcCorsikaRunHeader");
+    if (!fMcCorsika)
+    {
+        *fLog << err << "MMcCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // We don't know here if these are gammas
+    //if (fMcHeader->GetReflVersion()>600)
+    //    *fLog << inf << "Source position will be calculated from shower and telescope orientation." << endl;
+
+    // Determine Monte Carlo position from Monte Carlo header
+    TVector2 v(0, 0);
+    if (fMcCorsika->GetWobbleMode()>0.5)
+        v.Set(120.*fGeom->GetConvMm2Deg(), 0.);
+    if (fMcCorsika->GetWobbleMode()<-0.5)
+        v.Set(-120.*fGeom->GetConvMm2Deg(), 0.);
+
+    // Set fixed position
+    fFixedPos = v;
+
+    InitFixedPos();
+
+    return kTRUE;
+}
+
+void MSrcPosCalc::CalcResult(const MVector3 &pos0, const MVector3 &pos)
+{
+    // Calculate source position in camera, and convert to mm:
+    TVector2 v = MAstro::GetDistOnPlain(pos0, pos, -fGeom->GetCameraDist()*1000);
+
+    if (fDeviation)
+        v -= fDeviation->GetDevXY()/fGeom->GetConvMm2Deg();
+
+    SetSrcPos(v);
+}
+
+// --------------------------------------------------------------------------
+//
+// Derotate fX/fY by the current rotation angle, set MSrcPosCam
+//
+Int_t MSrcPosCalc::Process()
+{
+    // In off-data mode the position is set to a fixed value
+    // independent of the run type. In fixed-data mode the position
+    // is set to the predefined position converted to mm.
+    if (fMode==kOffData || fMode==kFixed)
+    {
+        SetSrcPos(fFixedPos/fGeom->GetConvMm2Deg());
+        return kTRUE;
+    }
+
+    // If it is a monte carlo run calculate source position from
+    // Monte Carlo headers
+    if (fRunType==MRawRunHeader::kRTMonteCarlo)
+    {
+        // If the reflector version is too old take source position
+        // from the WobbleMode in the header
+        if (fMcHeader->GetReflVersion()<=600)
+        {
+            SetSrcPos(fFixedPos/fGeom->GetConvMm2Deg());
+            return kTRUE;
+        }
+
+        // If this is ceres data and we have a view cone keep
+        // the source position fixed to the center of the camera
+        if (fMcCorsika && fMcCorsika->HasViewCone())
+        {
+            SetSrcPos();
+            return kTRUE;
+        }
+
+        // If the reflector version was new enough calculate the
+        // source position from shower and telescope orientation
+        // FIXME: Copy fMcEvt to fSourcePos!
+        MVector3 pos0, pos;
+        pos0.SetZdAz(fPointPos->GetZdRad(), fPointPos->GetAzRad());
+        pos.SetZdAz(fMcEvt->GetParticleTheta(), fMcEvt->GetParticlePhi());
+
+        CalcResult(pos0, pos);
+
+        // If it was not ceres due to a bug in the MAGIC MCs
+        // we have to fix the sign of X
+        if (!fMcHeader->IsCeres())
+            SetSrcPos(TVector2(-fSrcPosCam->GetX(), fSrcPosCam->GetY()));
+
+        return kTRUE;
+    }
+
+    // If the user requested a fixed source position use this position
+    if (!fSourcePos || !fTime || !fObservatory)
+    {
+        SetSrcPos(fFixedPos/fGeom->GetConvMm2Deg());
+        return kTRUE;
+    }
+
+    // Set Sky coordinates of source, taken from container "MSourcePos"
+    // of type MPointingPos. The sky coordinates must be J2000, as the
+    // sky coordinates of the camera center that we get from the container
+    // "MPointingPos" filled by the Drive.
+    MVector3 pos;  // pos: source position
+    pos.SetRaDec(fSourcePos->GetRaRad(), fSourcePos->GetDecRad());
+
+    // Set sky coordinates of camera center in pos0 (for details see below)
+    MVector3 pos0;  // pos0: camera center
+    pos0.SetRaDec(fPointPos->GetRaRad(), fPointPos->GetDecRad());
+
+    // Here we check that the source position which was given
+    // by the drive system is not off by more than 1deg from the
+    // source position given by the user. (Checking every individual
+    // event is not the fastest, but the safest)
+    if (pos.Angle(pos0)*TMath::RadToDeg()>1)
+    {
+        *fLog << err << "ERROR - Defined source position deviates from pointing-ra/dec by more than 1deg (";
+        *fLog << pos.Angle(pos0) << ")!" << endl;
+        *fLog << "User defined source pos:  ";
+        fSourcePos->Print();
+        *fLog << "Pointing position of tel: ";
+        fPointPos->Print();
+
+        return kERROR;
+    }
+
+    // Convert sky coordinates of source to local coordinates. Warning! These are not the "true" local
+    // coordinates, since this transformation ignores precession and nutation effects.
+    const MAstroSky2Local conv(*fTime, *fObservatory);
+    pos *= conv;
+
+    // Convert sky coordinates of camera center convert to local.
+    // Same comment as above. These coordinates differ from the true
+    // local coordinates of the camera center that one could get from
+    // "MPointingPos", calculated by the Drive: the reason is that the Drive
+    // takes into account precession and nutation corrections, while
+    // MAstroSky2Local (as of Jan 27 2005 at least) does not. Since we just
+    // want to get the source position on the camera from the local
+    // coordinates of the center and the source, it does not matter that
+    // the coordinates contained in pos and pos0 ignore precession and
+    // nutation... since the shift would be the same in both cases. What
+    // would be wrong is to set in pos0 directly the local coordinates
+    // found in MPointingPos!
+    pos0 *= conv;
+
+    //TVector2 vx;
+    if (fDeviation)
+    {
+        // Position at which the starguider camera is pointing in real:
+        //       pointing position = nominal position - dev
+        //
+        //vx = CalcXYinCamera(pos0, pos)*fGeom->GetCameraDist()*1000;
+        pos0.SetZdAz(pos0.Theta()-fDeviation->GetDevZdRad(),
+                     pos0.Phi()  -fDeviation->GetDevAzRad());
+    }
+
+    CalcResult(pos0, pos);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert a coordinate stored in str into a double, stored in ret.
+// Returns kTRUE on success, otherwise kFALSE
+//
+// Allowed formats are:
+//     12.5
+//    -12.5
+//    +12.5
+//  -12:30:00.0
+//   12:30:00.0
+//  +12:30:00.0
+//
+Bool_t MSrcPosCalc::GetCoordinate(TString str, Double_t &ret) const
+{
+    str = str.Strip(TString::kBoth);
+
+    if (str.First(':')<0)
+    {
+        ret = str.Atof();
+        return kTRUE;
+    }
+
+    if (MAstro::Coordinate2Angle(str, ret))
+        return kTRUE;
+
+    *fLog << err << GetDescriptor() << endl;
+    *fLog << "Interpretation of Coordinate '" << str << "' not successfull... abort." << endl;
+    *fLog << "Corrdinate must have the format: '-12:30:00.0', '12:30:00.0' or '+12:30:00.0'" << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MSrcPosCalc.SourceRa:  ra
+//   MSrcPosCalc.SourceDec: dec
+//   MSrcPosCalc.SourcePos: ra dec
+//
+// For format of 'ra' and 'dec' see GetCoordinate()
+//
+// Coordinates are J2000.0
+//
+Int_t MSrcPosCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "FixedPos", print))
+    {
+        TString str = GetEnvValue(env, prefix, "FixedPos", "");
+        str = str.Strip(TString::kBoth);
+
+        Double_t x, y;
+        const Int_t n=sscanf(str.Data(), "%lf %lf", &x, &y);
+        if (n!=2)
+        {
+            *fLog << warn << "WARNING - FixedPos requires two numbers." << endl;
+            return kERROR;
+        }
+
+        fFixedPos = TVector2(x, y);
+        fMode = kFixed;
+
+        rc = kTRUE;
+    }
+
+    Double_t ra=0;
+    Double_t dec=0;
+
+    if (IsEnvDefined(env, prefix, "SourceRaDec", print))
+    {
+        TString str = GetEnvValue(env, prefix, "SourceRaDec", "");
+        str = str.Strip(TString::kBoth);
+
+        const Ssiz_t pos = str.First(' ');
+        if (pos<0)
+        {
+            *fLog << err << GetDescriptor() << "SourceRaDec empty... abort." << endl;
+            return kERROR;
+        }
+
+        if (!GetCoordinate(str(0, pos), ra))
+            return kERROR;
+        if (!GetCoordinate(str(pos+1, str.Length()), dec))
+            return kERROR;
+
+        SetSourcePos(ra, dec);
+        return rc;
+    }
+
+    Bool_t rcsrc = kFALSE;
+    if (IsEnvDefined(env, prefix, "SourceRa", print))
+    {
+        TString str = GetEnvValue(env, prefix, "SourceRa", "");
+
+        if (!GetCoordinate(str, ra))
+            return kERROR;
+
+        rcsrc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "SourceDec", print))
+    {
+        TString str = GetEnvValue(env, prefix, "SourceDec", "");
+
+        if (!GetCoordinate(str, dec))
+            return kERROR;
+
+        rcsrc = kTRUE;
+    }
+
+    if (rcsrc)
+        SetSourcePos(ra, dec);
+
+    return rcsrc || rc;
+}
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosCalc.h	(revision 17960)
@@ -0,0 +1,91 @@
+#ifndef MARS_MSrcPosCalc
+#define MARS_MSrcPosCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+class MObservatory;
+class MPointingPos;
+class MPointingDev;
+class MSrcPosCam;
+class MGeomCam;
+class MTime;
+class MVector3;
+class MTaskList;
+class MMcEvt;
+class MMcRunHeader;
+class MMcCorsikaRunHeader;
+
+class MSrcPosCalc : public MTask
+{
+public:
+    enum Mode_t {
+        kDefault = 0,   // Set source position to on-position
+        kOffData = 1,   // The source position is fixed to (0/0)
+        kWobble  = 2,   // The source position is set to the wobble aka. anti-source position depending on the cycle number
+        kFixed   = 3    // Set source position to predefined fFixedPos
+    };
+private:
+    enum {
+        kIsOwner = BIT(14)
+    };
+
+    const MObservatory        *fObservatory;   //! Observatory location
+    const MPointingPos        *fPointPos;      //! Present pointing position of the telescope in Zd/Az
+    const MPointingDev        *fDeviation;     //! Deviation calculated from starguider data
+    const MMcEvt              *fMcEvt;         //! Possible input of shower position from MC
+    const MMcRunHeader        *fMcHeader;      //! Monte Carlo run header needed for correct wobble position
+    const MMcCorsikaRunHeader *fMcCorsika;     //! Monte Carlo run header needed to determine view cone option
+    const MGeomCam            *fGeom;          //! Camera geomety
+    const MTime               *fTime;          //! Time of the current event
+    const MTaskList           *fCallback;      //! Callback function to get the number of the cycle
+    MPointingPos *fSourcePos;     //! Source Postion in sky coordinates
+    MSrcPosCam   *fSrcPosCam;     //! Output: Source position in the camera
+    MSrcPosCam   *fSrcPosAnti;    //! Output: Anti Source position in the camera
+
+    UShort_t fRunType;            //! Run Type to decide where to get pointing position from
+
+    TVector2 fFixedPos;           //! [deg] Fixed source position
+
+    Int_t fMode;                  // Mode how the source position is calculated
+
+    Int_t fNumRandomOffPositions; // Number of possible random off-sourcr position
+
+    // MSrcPosCalc
+    void     SetSrcPos(TVector2 v=TVector2()) const;
+    TVector2 Rotate(TVector2 v, Int_t pass, Int_t num) const;
+    TString  GetRaDec(const MPointingPos &pos) const;
+    Bool_t   GetCoordinate(TString str, Double_t &ret) const;
+    void     FreeSourcePos();
+    void     CalcResult(const MVector3 &pos0, const MVector3 &pos);
+    void     InitFixedPos() const;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSrcPosCalc(const char *name=NULL, const char *title=NULL);
+    ~MSrcPosCalc() { FreeSourcePos(); }
+
+    // MSrcPosCalc
+    void SetSourcePos(MPointingPos *pos) { FreeSourcePos(); fSourcePos = pos; }
+    void SetSourcePos(Double_t ra, Double_t dec);
+    void SetOwner(Bool_t b=kTRUE) { b ? SetBit(kIsOwner) : ResetBit(kIsOwner); } // Make MSrcPosCalc owner of fSourcePos
+    void SetMode(Mode_t m=kDefault) { fMode = m; }
+    void SetCallback(MTaskList *list) { fCallback=list; }
+    void SetNumRandomOffPositions(Int_t num=0) { fNumRandomOffPositions=num; }
+
+    ClassDef(MSrcPosCalc, 0) // Calculates the source position in the camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosCam.cc	(revision 17960)
@@ -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    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 <TMarker.h>
+#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();
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy constructor, set default name and title
+//
+MSrcPosCam::MSrcPosCam(const MSrcPosCam &p) : fX(p.fX), fY(p.fY)
+{
+    fName  = gsDefName.Data();
+    fTitle = gsDefTitle.Data();
+}
+
+// -----------------------------------------------------------------------
+//
+// Print contents
+//
+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;
+}
+
+// -----------------------------------------------------------------------
+//
+// Paint contents
+//
+void MSrcPosCam::Paint(Option_t *)
+{
+    TMarker m;
+    m.SetMarkerStyle(kStar);
+    m.SetMarkerColor(kBlack);
+    m.DrawMarker(fX, fY);
+}
+
+// -----------------------------------------------------------------------
+//
+// Set fX to v.X() and fY to v.Y()
+//
+void MSrcPosCam::SetXY(const TVector2 &v)
+{
+    fX = v.X();
+    fY = v.Y();
+}
+
+// -----------------------------------------------------------------------
+//
+// Add v.X() to fX and v.Y() to fY
+//
+void MSrcPosCam::Add(const TVector2 &v)
+{
+    fX+=v.X();
+    fY+=v.Y();
+}
+
+// -----------------------------------------------------------------------
+//
+//    return TMath::Hypot(fX, fY);
+//
+Float_t MSrcPosCam::GetDist() const
+{
+    return TMath::Hypot(fX, fY);
+}
+
+// -----------------------------------------------------------------------
+//
+// Get TVector2(fX, fY)
+//
+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(ostream &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: branches/Mars_McMismatchStudy/mpointing/MSrcPosCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosCam.h	(revision 17960)
@@ -0,0 +1,48 @@
+#ifndef MARS_MSrcPosCam
+#define MARS_MSrcPosCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include <TMath.h>
+
+class TVector2;
+
+class MSrcPosCam : public MParContainer
+{
+private:
+    Float_t fX; // [mm] x position of source in camera
+    Float_t fY; // [mm] y position of source in camera
+
+public:
+    MSrcPosCam(const char *name=NULL, const char *title=NULL);
+    MSrcPosCam(const MSrcPosCam &p);
+
+    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);
+
+    void Add(const TVector2 &v);
+
+    Float_t GetDist() const;
+
+    Float_t GetX() const             { return fX; }
+    Float_t GetY() const             { return fY; }
+    TVector2 GetXY() const;
+
+    void Paint(Option_t *opt);
+    void Print(Option_t *opt=NULL) const;
+
+    void StreamPrimitive(std::ostream &out) const;
+
+    //void AsciiRead(ifstream &fin);
+    //void AsciiWrite(ofstream &fout) const;
+
+    ClassDef(MSrcPosCam, 1) // container to store source position in the camera plain
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosCorrect.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosCorrect.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosCorrect.cc	(revision 17960)
@@ -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 6/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosCorrect
+//
+// Performs a misfocussing correction for source and anti-source position
+// in the camera, i.e. it is assumed that the telscope is pointing well
+// (all starguider and other corrections are already applied to the
+// source positon) but the mirror is not focussing to the center of
+// the camera.
+//
+// Due to missfocussing a shift of
+//    dx=0.048deg and dy=0.034deg
+//  or
+//    dx=14.24mm and dy=9.495mm
+// is added between run 53832 (excl) and 56161 (excl)
+//
+//
+// See also: Runbook
+//
+//    2005-05-23 03:33:51:
+//    We start again to make tests on AMC with Roque lamp and PinDiode Tests.
+//    At park position, we do a Laser initial isation and a Laser adjustment.
+//    We discovered that the procedure we used yester day for Roque Lamp
+//    light source was producing a very non-uniform light
+//    We did some studies to produce an uniformly illuminated light from
+//    the Roque Lamp Then we moved the telescope to the Roque Lamp position
+//    and did a Laser adjust for the Roque position. We put the telescope to
+//    the same shaftencoder values as were used in August to adjust the
+//    mirrors
+//    ( 29691 for SE-Az and SE-Zd1 1301 and SE-Zd2 9912 ( sometimes
+//    oscillating to 9913 ) ) When we looked at the image of the spot on the
+//    camer a, we saw a clear offset from the centre. Then we calculated this
+//    offset and put the correct numbers in the AMC code. Then we redid the
+//    laser adjustment and found the spot to be nicely centered.  Our
+//    calculations showed that the offset was 0.048 deg in X direction and
+//    0.032 deg in Y direction.
+//    Good night
+//
+// Believing the Database the following data is affected:
+//   1ES1426+428           Off1ES1426-1
+//   1ES1959+650           Off1ES1959-1
+//   2E-1415+2557          Off2E1415-1
+//   Arp-220               OffArp-220-1
+//   GC-W1                 OffHB1553-1
+//   HB89-1553+11          OffM87-1
+//   M87                   OffW-Comae-1
+//   W-Comae
+//
+//
+// For more details see Process()
+//
+// Input:
+//   MSrcPosCam
+//   MSrcPosAnti [MSrcPosCam]
+//
+// Output:
+//   OpticalAxis [MSrcPosCam]
+//   MSrcPosCam
+//   MSrcPosAnti [MSrcPosCam]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosCorrect.h"
+
+#include <TVector2.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MRawRunHeader.h"
+#include "MReportStarguider.h"
+
+ClassImp(MSrcPosCorrect);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MSrcPosCorrect::MSrcPosCorrect(const char *name, const char *title)
+    : fSrcPosCam(NULL), fSrcPosAnti(NULL), fAxis(NULL), fGeom(NULL)
+     , fDx(-14.24) , fDy(-9.495)
+
+{
+    fName  = name  ? name  : "MSrcPosCorrect";
+    fTitle = title ? title : "Calculates the source position in the camera";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search and if necessary create MSrcPosCam in the parameter list. Search
+// MSourcePos. If not found, do nothing else, and skip the task. If MSrcPosCam
+// did not exist before and has been created here, it will contain as source
+// position the camera center (0,0).
+// In the case that MSourcePos is found, go ahead in searching the rest of
+// necessary containers. The source position will be calculated for each
+// event in Process.
+//
+Int_t MSrcPosCorrect::PreProcess(MParList *pList)
+{
+    fSrcPosCam = (MSrcPosCam*)pList->FindObject("MSrcPosCam");
+    if (!fSrcPosCam)
+    {
+        *fLog << err << "MSrcPosCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSrcPosAnti = (MSrcPosCam*)pList->FindObject("MSrcPosAnti", "MSrcPosCam");
+
+    fAxis = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", "OpticalAxis");
+    if (!fAxis)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checking for file type. If the file type is Monte Carlo the
+// source position is arbitrarily determined from the MC headers.
+//
+Bool_t MSrcPosCorrect::ReInit(MParList *plist)
+{
+    MRawRunHeader *run = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!run)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunType   = run->GetRunType();
+    fRunNumber = run->GetRunNumber();
+
+    if (fRunNumber<56161 && fRunNumber>53832)
+    {
+        *fLog << inf << "Run Number " << fRunNumber << " between 53832 and 56161." << endl;
+        *fLog << "A misfocussing correction (" << fDx << "mm/" << fDy << "mm) will be applied." << endl;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The offset fDx/fDy is subtracted from the source position. The anti-
+// source position is shifted away from the camera-center and rotated
+// around the camera center according to this correction, because it
+// should always be symmetric w.r.t. the camera-center, but it is not
+// necessary on the other side of the camera (e.g. three off-regions).
+//
+Int_t MSrcPosCorrect::Process()
+{
+    if (fRunType==MRawRunHeader::kRTMonteCarlo)
+        return kTRUE;
+
+    if (fRunNumber<=53832 || fRunNumber>=56161)
+        return kTRUE;
+
+    // dx=-0.048deg, dy=0.034deg, d=0.059deg
+    const TVector2 dxy(-fDx, -fDy);
+
+    const TVector2 s1(fSrcPosCam->GetXY());
+    const TVector2 a1(fSrcPosAnti->GetXY());
+    const TVector2 s2 = s1 + dxy;
+
+
+    // Anti-Source position should always be symetric w.r.t. camera center
+    TVector2 a2;
+    a2.SetMagPhi(a1.Mod()+s2.Mod()-s1.Mod(), a1.Phi()+s2.DeltaPhi(s1));
+
+    fAxis->SetXY(dxy);
+    fSrcPosCam->SetXY(s2);
+    fSrcPosAnti->SetXY(s2);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// MSrcPosCorrect.Dx: -14.24
+// MSrcPosCorrect.Dy: -9.495
+//
+// For a detailed description see the class reference.
+//
+Int_t MSrcPosCorrect::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Dx", print))
+    {
+        fDx = GetEnvValue(env, prefix, "Dx", fDx);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Dy", print))
+    {
+        fDy = GetEnvValue(env, prefix, "Dy", fDy);
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosCorrect.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosCorrect.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosCorrect.h	(revision 17960)
@@ -0,0 +1,41 @@
+#ifndef MARS_MSrcPosCorrect
+#define MARS_MSrcPosCorrect
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class TVector2;
+class MSrcPosCam;
+class MReportStarguider;
+
+class MSrcPosCorrect : public MTask
+{
+private:
+    MSrcPosCam *fSrcPosCam;   //! Source position
+    MSrcPosCam *fSrcPosAnti;  //! Anti source position
+    MSrcPosCam *fAxis;        //! New "center of camera"
+
+    MGeomCam   *fGeom;        //! Camera geometry
+
+    UShort_t fRunType;        //! Run Type to decide where to get pointing position from
+    UInt_t   fRunNumber;      //! Current run number
+
+    Float_t fDx;              // [mm] Correction in x
+    Float_t fDy;              // [mm] Correction in y
+
+    // MTask
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MSrcPosCorrect(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSrcPosCorrect, 0) // Corrects MSrcPosCam for missfocussing
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosFromModel.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosFromModel.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosFromModel.cc	(revision 17960)
@@ -0,0 +1,152 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosFromModel
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosFromModel.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MPointing.h"
+#include "MSrcPosCam.h"
+#include "MAstro.h"
+#include "MAstroCatalog.h" // MVector3
+#include "MAstroSky2Local.h"
+#include "MPointingPos.h"
+#include "MGeomCam.h"
+#include "MReportDrive.h"
+
+ClassImp(MSrcPosFromModel);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize fY and fY with 0
+//
+MSrcPosFromModel::MSrcPosFromModel(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MSrcPosFromModel";
+    fTitle = title ? title : "";
+
+    fPoint0401 = new MPointing("bending-fit.txt");
+    fPoint0405 = new MPointing("bending0405.txt");
+}
+
+MSrcPosFromModel::~MSrcPosFromModel()
+{
+    delete fPoint0401;
+    delete fPoint0405;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search and if necessary create MSrcPosCam in the parameter list
+//
+Int_t MSrcPosFromModel::PreProcess(MParList *pList)
+{
+    fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointPos = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fObservatory = (MObservatory*)pList->FindObject("MObservatory");
+    if (!fObservatory)
+    {
+        *fLog << err << "MObservatory not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTime = (MTime*)pList->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPos)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Derotate fX/fY by the current rotation angle, set MSrcPosCam
+//
+Int_t MSrcPosFromModel::Process()
+{
+    MPointing *conv = 0;
+
+    if (!conv && fRun->GetRunNumber()<26237)
+        conv = fPoint0401;
+    if (!conv && fRun->GetRunNumber()<31684)
+        conv = fPoint0405;
+
+    TVector2 d;
+
+    if (conv)
+    {
+        MVector3 sky;
+        sky.SetRaDec(fPointPos->GetRaRad(), fPointPos->GetDecRad());
+
+        // Get current star position (off center)
+        MVector3 vl2 = MAstroSky2Local(*fTime, *fObservatory)*sky;
+        // Get corrected position camera center)
+        TVector3 vl1 = conv->Correct(vl2);
+
+        // Calculate x,y of za2
+        d = MAstro::GetDistOnPlain(vl1, vl2, fGeom->GetCameraDist()*1000);
+    }
+
+    // Set Source position
+    fSrcPos->SetXY(d);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosFromModel.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosFromModel.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosFromModel.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MSrcPosFromModel
+#define MARS_MSrcPosFromModel
+
+//#ifndef ROOT_TVector2
+//#include <TVector2.h>
+//#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MPointingPos;
+class MSrcPosCam;
+class MGeomCam;
+class MPointing;
+class MRawRunHeader;
+class MTime;
+class MObservatory;
+
+class MSrcPosFromModel : public MTask
+{
+private:
+    MPointingPos  *fPointPos;   //! Poiting position as recorded by the drive system
+    MSrcPosCam    *fSrcPos;     //! Source position in the camera
+    MGeomCam      *fGeom;       //! Camera geometry
+    MRawRunHeader *fRun;        //! Run Header storing the run-number
+    MTime         *fTime;
+    MObservatory  *fObservatory;
+
+    MPointing    *fPoint0401;   //! Pointing Model used since 1/2004
+    MPointing    *fPoint0405;   //! Pointing Model used since 5/2004
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+/*
+    TVector2 CalcXYinCamera(const ZdAz &pos0, const ZdAz &pos) const;
+    TVector2 CalcXYinCamera(const MVector3 &pos0, const MVector3 &pos) const;
+    */
+
+public:
+    MSrcPosFromModel(const char *name=NULL, const char *title=NULL);
+    ~MSrcPosFromModel();
+
+    ClassDef(MSrcPosFromModel, 0) // Calculates the source position from a corrected pointing model
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosRndm.cc
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosRndm.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosRndm.cc	(revision 17960)
@@ -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 Bretz, 3/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosRndm
+//
+// Input Container:
+//   MHSrcPosCam
+//
+// Output Container:
+//   MSrcPosCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosRndm.h"
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHSrcPosCam.h"
+
+ClassImp(MSrcPosRndm);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Search for 'MPointingPos'. Create if not found.
+//
+Int_t MSrcPosRndm::PreProcess(MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "ERROR - MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSrcPos = (MSrcPosCam*)plist->FindCreateObj("MSrcPosCam");
+    if (!fSrcPos)
+        return kFALSE;
+
+    fSrcPosAnti = (MSrcPosCam*)plist->FindCreateObj("MSrcPosCam", "MSrcPosAnti");
+    if (!fSrcPosAnti)
+        return kFALSE;
+
+    if (fDistOfSource<0)
+    {
+        fHist = (MHSrcPosCam*)plist->FindObject("MHSrcPosCam");
+        if (!fHist)
+        {
+            *fLog << inf << "MHSrcPosCam not found... skipping." << endl;
+            return kSKIP;
+        }
+
+        *fLog << inf << "MHSrcPosCam found... taken to produce a random distribution." << endl;
+    }
+    else
+        *fLog << inf << "Source position will be produced randomly in a distance of " << fDistOfSource << "° from the camera center!" << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  See class description.
+//
+Int_t MSrcPosRndm::Process()
+{
+    Axis_t x, y;
+    if (fDistOfSource<0)
+        fHist->GetHist().GetRandom2(x, y);
+    else
+    {
+        const Double_t phi = gRandom->Uniform(TMath::TwoPi());
+        x = TMath::Cos(phi)*fDistOfSource;
+        y = TMath::Sin(phi)*fDistOfSource;
+    }
+
+    const Double_t f = fGeom->GetConvMm2Deg();
+
+    fSrcPos->SetXY(x/f, y/f);
+    if (fDistOfSource>=0)
+        fSrcPosAnti->SetXY(-x/f, -y/f);
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mpointing/MSrcPosRndm.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/MSrcPosRndm.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/MSrcPosRndm.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MSrcPosRndm
+#define MARS_MSrcPosRndm
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MSrcPosCam;
+class MHSrcPosCam;
+
+class MSrcPosRndm : public MTask
+{
+private:
+    MSrcPosCam   *fSrcPos;     //!
+    MSrcPosCam   *fSrcPosAnti; //!
+    MHSrcPosCam  *fHist;       //!
+    MGeomCam     *fGeom;       //! Conversion factor from mm to deg
+
+    Double_t fDistOfSource; // [deg] Distance of the source from the camera center
+
+    Int_t  PreProcess(MParList *plist);
+    Int_t  Process();
+
+public:
+    MSrcPosRndm() : fSrcPos(0), fSrcPosAnti(0), fHist(0), fGeom(0), fDistOfSource(-1)
+    {
+        fName  = "MSrcPosRndm";
+        fTitle = "Overwrite the source position with a random one from MHSrcPosCam";
+    }
+
+    void SetDistOfSource(Double_t dist=-1) { fDistOfSource=dist; }
+
+    ClassDef(MSrcPosRndm, 0) //Overwrite the source position with a random one from MHSrcPosCam
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mpointing/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/Makefile	(revision 17960)
@@ -0,0 +1,44 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT = Pointing
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw -I../mreport -I../mmc \
+           -I../mastro -I../mgeom -I../mfileio -I../mhbase
+
+SRCFILES = MPointing.cc \
+	   MPointingDev.cc \
+	   MPointingDevCalc.cc \
+	   MPointingPos.cc \
+	   MPointingPosCalc.cc \
+	   MPointingPosInterpolate.cc \
+           MHPointing.cc \
+	   MHSrcPosCam.cc \
+           MSrcPosCam.cc \
+           MSrcPosCalc.cc \
+           MSrcPosRndm.cc \
+           MSrcPosCorrect.cc \
+           MSrcPosFromModel.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mpointing/PointingIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/PointingIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/PointingIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mpointing/PointingLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mpointing/PointingLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mpointing/PointingLinkDef.h	(revision 17960)
@@ -0,0 +1,29 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MPointing+;
+
+#pragma link C++ class MPointingDev+;
+#pragma link C++ class MPointingDevCalc+;
+
+#pragma link C++ class MPointingPos+;
+#pragma link C++ class MPointingPosCalc+;
+#pragma link C++ class MPointingPosInterpolate+;
+
+#pragma link C++ class MHPointing+;
+#pragma link C++ class MHSrcPosCam+;
+
+#pragma link C++ class MSrcPosCam+;
+#pragma link C++ class MSrcPosCalc+;
+#pragma link C++ class MSrcPosRndm+;
+#pragma link C++ class MSrcPosCorrect+;
+#pragma link C++ class MSrcPosFromModel+;
+
+#pragma link C++ class AltAz+;
+#pragma link C++ class ZdAz+;
+#pragma link C++ class RaDec+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mranforest/MHRanForest.cc
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MHRanForest.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MHRanForest.cc	(revision 17960)
@@ -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 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 <TH1.h>
+#include <TPad.h>
+#include <TMath.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;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_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: branches/Mars_McMismatchStudy/mranforest/MHRanForest.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MHRanForest.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MHRanForest.h	(revision 17960)
@@ -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);
+    Int_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: branches/Mars_McMismatchStudy/mranforest/MHRanForestGini.cc
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MHRanForestGini.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MHRanForestGini.cc	(revision 17960)
@@ -0,0 +1,215 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both 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>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHRanForest
+//
+// This histogram shows a measure of variable importance (mean decrease in
+// Gini-index)
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHRanForestGini.h"
+
+#include <TH1.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 "MDataArray.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)
+    : fRules(0.01, 0.01, 0.99, 0.99)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHRanForestGini";
+    fTitle = title ? title : "Measure of importance of Random Forest-input parameters";
+
+    fGraphGini.SetNameTitle("Gini", "Importance of RF-input parameters measured by mean Gini decrease");
+    fGraphGini.SetMarkerStyle(28);
+    fGraphGini.SetFillColor(38);
+
+    fGraphError.SetNameTitle("ResErr", "Resolution/Error versus train step");
+    fGraphError.SetMarkerStyle(kFullDotMedium);
+
+    fGraphNodes.SetNameTitle("Nodes", "Number of nodes versus train step");
+    fGraphNodes.SetMarkerStyle(kFullDotMedium);
+
+    fRules.SetTextAlign(13);
+    fRules.SetTextSize(0.05);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 kERROR;
+    }
+
+    fGini.Set(fRanForest->GetNumDim());
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the RanForest from a MRanForest container into the corresponding
+// histogram dependant on the particle id.
+//
+//
+Int_t MHRanForestGini::Fill(const MParContainer *par, const Stat_t w)
+{
+    MRanTree *t = fRanForest->GetCurTree();
+
+    for (Int_t i=0;i<fRanForest->GetNumDim();i++)
+        fGini[i] += t->GetGiniDec(i);
+
+    fGraphError.SetPoint(fGraphError.GetN(), GetNumExecutions(), t->GetError());
+    fGraphNodes.SetPoint(fGraphError.GetN(), GetNumExecutions(), t->GetNumEndNodes());
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MHRanForestGini::Finalize()
+{
+    // --- Calculate mean decrease of gini index ---
+    const Int_t n = fGini.GetSize();
+
+    fGraphGini.Set(n);
+
+    for (Int_t i=0; i<n; i++)
+    {
+        fGini[i] /= fRanForest->GetNumTrees()*fRanForest->GetNumData();
+        fGraphGini.SetPoint(i, i+1, fGini[i]);
+    }
+
+    // --- Produce some text information ---
+    fRules.AddText("");
+    fRules.AddText(Form("%s w/ %d trees of node size %d trained by %d evts",
+                        fRanForest->IsClassify()?"Classification":"Regression",
+                        fRanForest->GetNumTrees(),
+                        fRanForest->GetNdSize(),
+                        fRanForest->GetNumData()));
+    fRules.AddText("---");//Form("---> %s", fRanForest->GetTargetRule().Data()));
+
+    const MDataArray &arr = *fRanForest->GetRules();
+
+    int i;
+    for (i=0; i<arr.GetNumEntries(); i++)
+        fRules.AddText(Form("%d) %s", i+1, arr.GetRule(i).Data()));
+
+    for (; i<20; i++)
+        fRules.AddText("");
+
+    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("");
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGrid();
+    fGraphGini.Draw("AB");
+
+    TH1 *h = fGraphGini.GetHistogram();
+    if (h)
+    {
+        h->SetXTitle("No.of RF-input parameter");
+        h->SetYTitle("Mean decrease in Gini-index [au]");
+        h->GetXaxis()->SetNdivisions(10);
+        h->SetMinimum(0);
+    }
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridy();
+    fGraphError.Draw("ALP");
+    h = fGraphError.GetHistogram();
+    if (h)
+    {
+        h->SetXTitle("Train step/Tree number");
+        h->SetYTitle("Error/Resolution");
+        h->SetMinimum(0);
+    }
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridy();
+    fGraphNodes.Draw("ALP");
+    h = fGraphNodes.GetHistogram();
+    if (h)
+    {
+        h->SetXTitle("Train step/Tree number");
+        h->SetYTitle("Number of end nodes");
+        h->SetMinimum(0);
+    }
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fRules.Draw();
+}
Index: branches/Mars_McMismatchStudy/mranforest/MHRanForestGini.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MHRanForestGini.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MHRanForestGini.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MHRanForestGini
+#define MARS_MHRanForestGini
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+#ifndef ROOT_TGraph
+#include <TGraph.h>
+#endif
+#ifndef ROOT_TPaveText
+#include <TPaveText.h>
+#endif
+
+class MParList;
+class MRanForest;
+class MRanTree;
+
+class MHRanForestGini : public MH
+{
+private:
+    MRanForest *fRanForest;  //!
+
+    TArrayF fGini;           //!
+
+    TGraph  fGraphGini;
+    TGraph  fGraphError;
+    TGraph  fGraphNodes;
+
+    TPaveText fRules;
+
+public:
+    MHRanForestGini(Int_t nbins=100, const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Int_t  Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHRanForestGini, 1)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mranforest/MRanForest.cc
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForest.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForest.cc	(revision 17960)
@@ -0,0 +1,703 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both 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@physik.hu-berlin.de>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 <TMath.h>
+#include <TRandom.h>
+
+#include "MHMatrix.h"
+#include "MRanTree.h"
+#include "MData.h"
+#include "MDataArray.h"
+#include "MParList.h"
+
+#include "MArrayI.h"
+#include "MArrayF.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRanForest);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MRanForest::MRanForest(const char *name, const char *title)
+    : fClassify(kTRUE), fNumTrees(100), fNumTry(0), fNdSize(1),
+    fRanTree(NULL), fRules(NULL), fMatrix(NULL), fUserVal(-1)
+{
+    fName  = name  ? name  : "MRanForest";
+    fTitle = title ? title : "Storage container for Random Forest";
+
+    fForest=new TObjArray();
+    fForest->SetOwner(kTRUE);
+}
+
+MRanForest::MRanForest(const MRanForest &rf)
+{
+    // Copy constructor
+    fName  = rf.fName;
+    fTitle = rf.fTitle;
+
+    fClassify = rf.fClassify;
+    fNumTrees = rf.fNumTrees;
+    fNumTry   = rf.fNumTry;
+    fNdSize   = rf.fNdSize;
+    fTreeNo   = rf.fTreeNo;
+    fRanTree  = NULL;
+
+    fRules=new MDataArray();
+    fRules->Reset();
+
+    MDataArray *newrules=rf.fRules;
+
+    for(Int_t i=0;i<newrules->GetNumEntries();i++)
+    {
+        MData &data=(*newrules)[i];
+        fRules->AddEntry(data.GetRule());
+    }
+
+    // trees
+    fForest=new TObjArray();
+    fForest->SetOwner(kTRUE);
+
+    TObjArray *newforest=rf.fForest;
+    for(Int_t i=0;i<newforest->GetEntries();i++)
+    {
+        MRanTree *rantree=(MRanTree*)newforest->At(i);
+
+        MRanTree *newtree=new MRanTree(*rantree);
+        fForest->Add(newtree);
+    }
+
+    fHadTrue  = rf.fHadTrue;
+    fHadEst   = rf.fHadEst;
+    fDataSort = rf.fDataSort;
+    fDataRang = rf.fDataRang;
+    fClassPop = rf.fClassPop;
+    fWeight   = rf.fWeight;
+    fTreeHad  = rf.fTreeHad;
+
+    fNTimesOutBag = rf.fNTimesOutBag;
+}
+
+// --------------------------------------------------------------------------
+// Destructor. 
+MRanForest::~MRanForest()
+{
+    delete fForest;
+    if (fMatrix)
+        delete fMatrix;
+    if (fRules)
+        delete fRules;
+}
+
+void MRanForest::Print(Option_t *o) const
+{
+    *fLog << inf << GetDescriptor() << ": " << endl;
+    MRanTree *t = GetTree(0);
+    if (t)
+    {
+        *fLog << "Setting up RF for training on target:" << endl;
+        *fLog << " " << t->GetTitle() << endl;
+    }
+    if (fRules)
+    {
+        *fLog << "Following rules are used as input to RF:" << endl;
+        for (Int_t i=0;i<fRules->GetNumEntries();i++)
+            *fLog << " " << i << ") " << (*fRules)[i].GetRule() << endl;
+    }
+    *fLog << "Random forest parameters:" << endl;
+    if (t)
+    {
+        *fLog << " - " << (t->IsClassify()?"classification":"regression") << " tree" << endl;
+        *fLog << " - Number of trys: " << t->GetNumTry() << endl;
+        *fLog << " - Node size: " << t->GetNdSize() << endl;
+    }
+    *fLog << " - Number of trees: " << fNumTrees << endl;
+    *fLog << " - User value: " << fUserVal << endl;
+    *fLog << endl;
+}
+
+void MRanForest::SetNumTrees(Int_t n)
+{
+    //at least 1 tree
+    fNumTrees=TMath::Max(n,1);
+}
+
+void MRanForest::SetNumTry(Int_t n)
+{
+    fNumTry=TMath::Max(n,0);
+}
+
+void MRanForest::SetNdSize(Int_t n)
+{
+    fNdSize=TMath::Max(n,1);
+}
+
+void MRanForest::SetWeights(const TArrayF &weights)
+{
+    fWeight=weights;
+}
+
+void MRanForest::SetGrid(const TArrayD &grid)
+{
+    const int n=grid.GetSize();
+
+    for(int i=0;i<n-1;i++)
+        if(grid[i]>=grid[i+1])
+        {
+            *fLog<<warn<<"Grid points must be in increasing order! Ignoring grid."<<endl;
+            return;
+        }
+
+    fGrid=grid;
+
+    //*fLog<<inf<<"Following "<<n<<" grid points are used:"<<endl;
+    //for(int i=0;i<n;i++)
+    //    *fLog<<inf<<" "<<i<<") "<<fGrid[i]<<endl;
+}
+
+MRanTree *MRanForest::GetTree(Int_t i) const
+{
+    return static_cast<MRanTree*>(fForest->UncheckedAt(i));
+}
+
+Int_t MRanForest::GetNumDim() const
+{
+    return fMatrix ? fMatrix->GetNcols() : 0;
+}
+
+Int_t MRanForest::GetNumData() const
+{
+    return fMatrix ? fMatrix->GetNrows() : 0;
+}
+
+Int_t MRanForest::GetNclass() const
+{
+    int maxidx = TMath::LocMax(fClass.GetSize(),fClass.GetArray());
+
+    return int(fClass[maxidx])+1;
+}
+
+void MRanForest::PrepareClasses()
+{
+    const int numdata=fHadTrue.GetSize();
+
+    if(fGrid.GetSize()>0)
+    {
+        // classes given by grid
+        const int ngrid=fGrid.GetSize();
+
+        for(int j=0;j<numdata;j++)
+        {
+            // Array is supposed  to be sorted prior to this call.
+            // If match is found, function returns position of element.
+            // If no match found, function gives nearest element smaller
+            // than value.
+            int k=TMath::BinarySearch(ngrid, fGrid.GetArray(), (Double_t)fHadTrue[j]);
+
+            fClass[j]   = k;
+        }
+
+        int minidx = TMath::LocMin(fClass.GetSize(),fClass.GetArray());
+        int min = fClass[minidx];
+        if(min!=0) for(int j=0;j<numdata;j++)fClass[j]-=min;
+
+    }else{
+        // classes directly given
+        for (Int_t j=0;j<numdata;j++)
+            fClass[j] = TMath::Nint(fHadTrue[j]);
+    }
+}
+
+Double_t MRanForest::CalcHadroness()
+{
+    TVector event;
+    *fRules >> event;
+
+    return CalcHadroness(event);
+}
+
+Double_t MRanForest::CalcHadroness(const TVector &event)
+{
+    fTreeHad.Set(fNumTrees);
+
+    Double_t hadroness=0;
+    Int_t    ntree    =0;
+
+    TIter Next(fForest);
+
+    MRanTree *tree;
+    while ((tree=(MRanTree*)Next()))
+        hadroness += (fTreeHad[ntree++]=tree->TreeHad(event));
+
+    return hadroness/ntree;
+}
+
+Bool_t MRanForest::AddTree(MRanTree *rantree=NULL)
+{
+    fRanTree = rantree ? rantree : fRanTree;
+
+    if (!fRanTree) return kFALSE;
+
+    MRanTree *newtree=new MRanTree(*fRanTree);
+    fForest->Add(newtree);
+
+    return kTRUE;
+}
+
+Bool_t MRanForest::SetupGrow(MHMatrix *mat,MParList *plist)
+{
+    //-------------------------------------------------------------------
+    // access matrix, copy last column (target) preliminarily
+    // into fHadTrue
+    if (fMatrix)
+        delete fMatrix;
+    fMatrix = new TMatrix(mat->GetM());
+
+    int dim     = fMatrix->GetNcols()-1;
+    int numdata = fMatrix->GetNrows();
+
+    fHadTrue.Set(numdata);
+    fHadTrue.Reset();
+
+    for (Int_t j=0;j<numdata;j++)
+        fHadTrue[j] = (*fMatrix)(j,dim);
+
+    // remove last col
+    fMatrix->ResizeTo(numdata,dim);
+
+    //-------------------------------------------------------------------
+    // setup labels for classification/regression
+    fClass.Set(numdata);
+    fClass.Reset();
+
+    if (fClassify)
+        PrepareClasses();
+
+    //-------------------------------------------------------------------
+    // allocating and initializing arrays
+    fHadEst.Set(numdata);
+    fHadEst.Reset();
+
+    fNTimesOutBag.Set(numdata);
+    fNTimesOutBag.Reset();
+
+    fDataSort.Set(dim*numdata);
+    fDataSort.Reset();
+
+    fDataRang.Set(dim*numdata);
+    fDataRang.Reset();
+
+    Bool_t useweights = fWeight.GetSize()==numdata;
+    if (!useweights)
+    {
+        fWeight.Set(numdata);
+        fWeight.Reset(1.);
+        *fLog << inf <<"Setting weights to 1 (no weighting)"<< endl;
+    }
+
+    //-------------------------------------------------------------------
+    // setup rules to be used for classification/regression
+    const MDataArray *allrules=(MDataArray*)mat->GetColumns();
+    if (allrules==NULL)
+    {
+        *fLog << err <<"Rules of matrix == null, exiting"<< endl;
+        return kFALSE;
+    }
+
+    if (allrules->GetNumEntries()!=dim+1)
+    {
+        *fLog << err <<"Rules of matrix " << allrules->GetNumEntries() << " mismatch dimension+1 " << dim+1 << "...exiting."<< endl;
+        return kFALSE;
+    }
+
+    if (fRules)
+        delete fRules;
+
+    fRules = new MDataArray();
+    fRules->Reset();
+
+    const TString target_rule = (*allrules)[dim].GetRule();
+    for (Int_t i=0;i<dim;i++)
+        fRules->AddEntry((*allrules)[i].GetRule());
+
+    *fLog << inf << endl;
+    *fLog << "Setting up RF for training on target:" << endl;
+    *fLog << " " << target_rule.Data() << endl;
+    *fLog << "Following rules are used as input to RF:" << endl;
+    for (Int_t i=0;i<dim;i++)
+        *fLog << " " << i << ") " << (*fRules)[i].GetRule() << endl;
+    *fLog << endl;
+
+    //-------------------------------------------------------------------
+    // prepare (sort) data for fast optimization algorithm
+    if (!CreateDataSort())
+        return kFALSE;
+
+    //-------------------------------------------------------------------
+    // access and init tree container
+    fRanTree = (MRanTree*)plist->FindCreateObj("MRanTree");
+    if(!fRanTree)
+    {
+        *fLog << err << dbginf << "MRanForest, fRanTree not initialized... aborting." << endl;
+        return kFALSE;
+    }
+    //fRanTree->SetName(target_rule); // Is not stored anyhow
+
+    const Int_t tryest = TMath::Nint(TMath::Sqrt(dim));
+
+    *fLog << inf << endl;
+    *fLog << "Following input for the tree growing are used:"<<endl;
+    *fLog << " Forest type     : "<<(fClassify?"classification":"regression")<<endl;
+    *fLog << " Number of Trees : "<<fNumTrees<<endl;
+    *fLog << " Number of Trials: "<<(fNumTry==0?tryest:fNumTry)<<(fNumTry==0?" (auto)":"")<<endl;
+    *fLog << " Final Node size : "<<fNdSize<<endl;
+    *fLog << " Using Grid      : "<<(fGrid.GetSize()>0?"Yes":"No")<<endl;
+    *fLog << " Using Weights   : "<<(useweights?"Yes":"No")<<endl;
+    *fLog << " Number of Events: "<<numdata<<endl;
+    *fLog << " Number of Params: "<<dim<<endl;
+
+    if(fNumTry==0)
+    {
+        fNumTry=tryest;
+        *fLog << inf << endl;
+        *fLog << "Set no. of trials to the recommended value of round(";
+        *fLog << TMath::Sqrt(dim) << ") = " << fNumTry << endl;
+    }
+
+    fRanTree->SetNumTry(fNumTry);
+    fRanTree->SetClassify(fClassify);
+    fRanTree->SetNdSize(fNdSize);
+
+    fTreeNo=0;
+
+    return kTRUE;
+}
+
+Bool_t MRanForest::GrowForest()
+{
+    if(!gRandom)
+    {
+        *fLog << err << dbginf << "gRandom not initialized... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTreeNo++;
+
+    //-------------------------------------------------------------------
+    // initialize running output
+
+    float minfloat=TMath::MinElement(fHadTrue.GetSize(),fHadTrue.GetArray());
+    Bool_t calcResolution=(minfloat>FLT_MIN);
+
+    if (fTreeNo==1)
+    {
+        *fLog << inf << endl << underline;
+
+        if(calcResolution)
+            *fLog << "TreeNum BagSize NumNodes TestSize  Bias/%   var/%   res/% (from oob-data)" << endl;
+        else
+            *fLog << "TreeNum BagSize NumNodes TestSize  Bias/au  var/au  rms/au (from oob-data)" << endl;
+                     //        12345678901234567890123456789012345678901234567890
+    }
+
+    const Int_t numdata = GetNumData();
+    const Int_t nclass  = GetNclass();
+
+    //-------------------------------------------------------------------
+    // bootstrap aggregating (bagging) -> sampling with replacement:
+
+    MArrayF classpopw(nclass);
+    MArrayI jinbag(numdata); // Initialization includes filling with 0
+    MArrayF winbag(numdata); // Initialization includes filling with 0
+
+    float square=0;
+    float mean=0;
+
+    for (Int_t n=0; n<numdata; n++)
+    {
+        // The integer k is randomly (uniformly) chosen from the set
+        // {0,1,...,numdata-1}, which is the set of the index numbers of
+        // all events in the training sample
+  
+        const Int_t k = gRandom->Integer(numdata);
+
+        if(fClassify)
+            classpopw[fClass[k]]+=fWeight[k];
+        else
+            classpopw[0]+=fWeight[k];
+
+        mean  +=fHadTrue[k]*fWeight[k];
+        square+=fHadTrue[k]*fHadTrue[k]*fWeight[k];
+
+        winbag[k]+=fWeight[k]; // Increase weight if chosen more than once
+        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
+    const MArrayF hadtrue(fHadTrue.GetSize(), fHadTrue.GetArray());
+    const MArrayI fclass(fClass.GetSize(), fClass.GetArray());
+    const MArrayI datarang(fDataRang.GetSize(), fDataRang.GetArray());
+
+    MArrayI datsortinbag(fDataSort.GetSize(), fDataSort.GetArray());
+
+    ModifyDataSort(datsortinbag, jinbag);
+
+    fRanTree->GrowTree(fMatrix,hadtrue,fclass,datsortinbag,datarang,classpopw,mean,square,
+                       jinbag,winbag,nclass);
+
+    const Double_t ferr = EstimateError(jinbag, calcResolution);
+
+    fRanTree->SetError(ferr);
+
+    // adding tree to forest
+    AddTree();
+
+    return fTreeNo<fNumTrees;
+}
+
+//-------------------------------------------------------------------
+// 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.
+//
+Double_t MRanForest::EstimateError(const MArrayI &jinbag, Bool_t calcResolution)
+{
+    const Int_t numdata = GetNumData();
+
+    Int_t ninbag = 0;
+    for (Int_t ievt=0;ievt<numdata;ievt++)
+    {
+        if (jinbag[ievt]>0)
+        {
+            ninbag++;
+            continue;
+        }
+
+        fHadEst[ievt] +=fRanTree->TreeHad((*fMatrix), ievt);
+        fNTimesOutBag[ievt]++;
+    }
+
+    Int_t n=0;
+
+    Double_t sum=0;
+    Double_t sq =0;
+    for (Int_t i=0; i<numdata; i++)
+    {
+        if (fNTimesOutBag[i]==0)
+            continue;
+
+        const Float_t hadest = fHadEst[i]/fNTimesOutBag[i];
+
+        const Float_t val = calcResolution ?
+            hadest/fHadTrue[i] - 1 : hadest - fHadTrue[i];
+
+        sum += val;
+        sq  += val*val;
+        n++;
+    }
+
+    if (calcResolution)
+    {
+        sum *= 100;
+        sq  *= 10000;
+    }
+
+    sum /= n;
+    sq  /= n;
+
+    const Double_t var  = TMath::Sqrt(sq-sum*sum);
+    const Double_t ferr = TMath::Sqrt(sq);
+
+    //-------------------------------------------------------------------
+    // give running output
+    *fLog << setw(4) << fTreeNo;
+    *fLog << Form(" %8.1f", 100.*ninbag/numdata);
+    *fLog << setw(9) << fRanTree->GetNumEndNodes();
+    *fLog << Form("  %9.1f", 100.*n/numdata);
+    *fLog << Form(" %7.2f", sum);
+    *fLog << Form(" %7.2f", var);
+    *fLog << Form(" %7.2f", ferr);
+    *fLog << endl;
+
+    return ferr;
+}
+
+Bool_t MRanForest::CreateDataSort()
+{
+    // fDataSort(m,n) is the event number in which fMatrix(m,n) occurs.
+    // fDataRang(m,n) is the rang of fMatrix(m,n), i.e. if rang = r:
+    //   fMatrix(m,n) is the r-th highest value of all fMatrix(m,.).
+    //
+    // There may be more then 1 event with rang r (due to bagging).
+
+    const Int_t numdata = GetNumData();
+    const Int_t dim = GetNumDim();
+
+    TArrayF v(numdata);
+    TArrayI isort(numdata);
+
+
+    for (Int_t mvar=0;mvar<dim;mvar++)
+    {
+
+        for(Int_t n=0;n<numdata;n++)
+        {
+            v[n]=(*fMatrix)(n,mvar);
+            //isort[n]=n;
+
+            if (!TMath::Finite(v[n]))
+            {
+                *fLog << err <<"Event no. "<<n<<", matrix column no. "<<mvar;
+                *fLog << err <<" has a non finite value (eg. NaN)."<<endl;
+                return kFALSE;
+            }
+        }
+
+        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,...).
+
+        // control sorting
+        /*
+        for(int n=0;n<numdata-1;n++)
+            if(v[isort[n]]>v[isort[n+1]])
+            {
+                *fLog << err <<"Event no. "<<n<<", matrix column no. "<<mvar;
+                *fLog << err <<" not at correct sorting position."<<endl;
+                return kFALSE;
+            }
+            */
+
+        // DataRang is similar to the isort index starting from 0 it is
+        // increased by one for each event which is greater, but stays
+        // the same for the same value. (So to say it counts how many
+        // different values we have)
+        for(Int_t n=0;n<numdata-1;n++)
+        {
+            const Int_t n1=isort[n];
+            const Int_t n2=isort[n+1];
+
+            // FIXME: Copying isort[n] to fDataSort[mvar*numdata]
+            // can be accelerated!
+            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];
+    }
+    return kTRUE;
+}
+
+// Reoves all indices which are not in the bag from the datsortinbag
+void MRanForest::ModifyDataSort(MArrayI &datsortinbag, const MArrayI &jinbag)
+{
+    const Int_t numdim=GetNumDim();
+    const Int_t numdata=GetNumData();
+
+    Int_t 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 *subsort = &datsortinbag[m*numdata];
+
+        Int_t k=0;
+        for(Int_t n=0;n<ninbag;n++)
+        {
+            if(jinbag[subsort[k]]==1)
+            {
+                subsort[n] = subsort[k];
+                k++;
+            }else{
+                for(Int_t j=k+1;j<numdata;j++)
+                {
+                    if(jinbag[subsort[j]]==1)
+                    {
+                        subsort[n] = subsort[j];
+                        k = j+1;
+                        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: branches/Mars_McMismatchStudy/mranforest/MRanForest.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForest.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForest.h	(revision 17960)
@@ -0,0 +1,132 @@
+#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_TMatrix
+#include <TMatrix.h>
+#endif
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+class TObjArray;
+
+class MArrayI;
+class MArrayF;
+
+class MRanTree;
+class MDataArray;
+class MHMatrix;
+class MParList;
+
+class MRanForest : public MParContainer
+{
+private:
+    Bool_t fClassify;
+
+    Int_t fNumTrees;       // Number of trees
+    Int_t fNumTry;         // Number of tries
+    Int_t fNdSize;         // Size of node
+
+    Int_t fTreeNo;         //! Number of tree
+
+    MRanTree   *fRanTree;  //! Pointer to some tree
+    MDataArray *fRules;    //! Pointer to corresponding rules
+    TObjArray  *fForest;   //  Array containing forest
+
+    // training data
+    TMatrix *fMatrix;      //!
+
+    // true  and estimated hadronness
+    TArrayI fClass;        //!
+    TArrayD fGrid;         //!
+    TArrayF fHadTrue;      //!
+    TArrayF fHadEst;       //!
+
+    // data sorted according to parameters
+    TArrayI fDataSort;     //!
+    TArrayI fDataRang;     //!
+    TArrayI fClassPop;     //!
+
+    // weights
+    TArrayF fWeight;       //!
+    TArrayI fNTimesOutBag; //!
+
+    // estimates for classification error of growing forest
+    TArrayD fTreeHad;      //! Hadronness values (buffer for MHRanForest)
+
+    Double_t fUserVal;     // A user value describing this tree (eg E-mc)
+
+    Double_t EstimateError(const MArrayI &jinbag, Bool_t calcResolution);
+
+protected:
+    // create and modify (->due to bagging) fDataSort
+    Bool_t CreateDataSort();
+    void ModifyDataSort(MArrayI &datsortinbag, const MArrayI &jinbag);
+
+public:
+    MRanForest(const char *name=NULL, const char *title=NULL);
+    MRanForest(const MRanForest &rf);
+    ~MRanForest();
+
+    void Print(Option_t *o="") const; //*MENU*
+
+    void SetGrid(const TArrayD &grid);
+    void SetWeights(const TArrayF &weights);
+    void SetNumTrees(Int_t n);
+
+    void SetNumTry(Int_t n);
+    void SetNdSize(Int_t n);
+
+    void SetClassify(Bool_t n){ fClassify=n; }
+    void PrepareClasses();
+
+        // tree growing
+    Bool_t SetupGrow(MHMatrix *mat,MParList *plist);
+    Bool_t GrowForest();
+    void   SetCurTree(MRanTree *rantree) { fRanTree=rantree; }
+    Bool_t AddTree(MRanTree *rantree);
+    void   SetUserVal(Double_t d) { fUserVal = d; }
+
+    // getter methods
+    TObjArray  *GetForest() const      { return fForest; }
+    MRanTree   *GetCurTree() const     { return fRanTree; }
+    MRanTree   *GetTree(Int_t i) const;
+    MDataArray *GetRules() const       { return fRules; }
+
+
+    Int_t      GetNumTrees() const { return fNumTrees; }
+    Int_t      GetNumData()  const;
+    Int_t      GetNumDim()   const;
+    Int_t      GetNdSize() const { return fNdSize; }
+    Int_t      GetNclass()   const;
+    Double_t   GetTreeHad(Int_t i) const { return fTreeHad.At(i); }
+    Double_t   GetUserVal() const { return fUserVal; }
+    Bool_t     IsClassify() const { return fClassify; }
+
+    // use forest to calculate hadronness of event
+    Double_t CalcHadroness(const TVector &event);
+    Double_t CalcHadroness();
+
+    Bool_t AsciiWrite(std::ostream &out) const;
+
+    ClassDef(MRanForest, 1) // Storage container for tree structure
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mranforest/MRanForestCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForestCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForestCalc.cc	(revision 17960)
@@ -0,0 +1,498 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 2/2005 <mailto:hengsteb@physik.hu-berlin.de>
+!   Author(s): Thomas Bretz 8/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRanForestCalc
+//
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MRanForestCalc.h"
+
+#include <stdlib.h> // Needed for atof in some cases
+
+#include <TMath.h>
+
+#include <TF1.h>
+#include <TFile.h>
+#include <TGraph.h>
+#include <TVector.h>
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MData.h"
+#include "MDataArray.h"
+
+#include "MRanForest.h"
+#include "MParameters.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+#include "MRanForestGrow.h"
+#include "MFillH.h"
+
+ClassImp(MRanForestCalc);
+
+using namespace std;
+
+const TString MRanForestCalc::gsDefName    = "MRanForestCalc";
+const TString MRanForestCalc::gsDefTitle   = "RF for energy estimation";
+
+const TString MRanForestCalc::gsNameOutput   = "RanForestOut";
+const TString MRanForestCalc::gsNameEvalFunc = "EvalFunction";
+
+MRanForestCalc::MRanForestCalc(const char *name, const char *title)
+    : fData(0), fRFOut(0), fTestMatrix(0), fFunc("x"),
+    fNumTrees(-1), fNumTry(-1), fNdSize(-1), fNumObsoleteVariables(1),
+    fLastDataColumnHasWeights(kFALSE),
+    fNameOutput(gsNameOutput), fDebug(kFALSE), fEstimationMode(kMean)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    // FIXME:
+    fNumTrees = 100; //100
+    fNumTry   = 0;   //3   0 means: in MRanForest estimated best value will be calculated
+    fNdSize   = 1;   //1   
+}
+
+MRanForestCalc::~MRanForestCalc()
+{
+    fEForests.Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a function which is applied to the output of the random forest
+//
+Bool_t MRanForestCalc::SetFunction(const char *func)
+{
+    return !fFunc.SetRule(func);
+}
+
+// --------------------------------------------------------------------------
+//
+// ver=0: One yes/no-classification forest is trained for each bin.
+//        the yes/no classification is done using the grid
+// ver=1: One classification forest is trained. The last column contains a
+//        value which is turned into a classifier by rf itself using the grid
+// ver=2: One classification forest is trained. The last column already contains
+//        the classifier
+// ver=3: A regression forest is trained. The last column contains the
+//        classifier
+//
+Int_t MRanForestCalc::Train(const MHMatrix &matrixtrain, const TArrayD &grid, Int_t ver)
+{
+    gLog.Separator("MRanForestCalc - Train");
+
+    if (!matrixtrain.GetColumns())
+    {
+        *fLog << err << "ERROR - MHMatrix does not contain rules... abort." << endl;
+        return kFALSE;
+    }
+
+    const Int_t ncols = matrixtrain.GetM().GetNcols();
+    const Int_t nrows = matrixtrain.GetM().GetNrows();
+    if (ncols<=0 || nrows <=0)
+    {
+        *fLog << err << "ERROR - No. of columns or no. of rows of matrixtrain equal 0 ... abort." << endl;
+        return kFALSE;
+    }
+
+    // rules (= combination of image par) to be used for energy estimation
+    TFile fileRF(fFileName, "recreate");
+    if (!fileRF.IsOpen())
+    {
+        *fLog << err << "ERROR - File to store RFs could not be opened... abort." << endl;
+        return kFALSE;
+    }
+
+    // The number of columns which have to be removed for the training
+    // The last data column may contain weight which also have to be removed
+    const Int_t nobs = fNumObsoleteVariables + (fLastDataColumnHasWeights?1:0); // Number of obsolete columns
+
+    const MDataArray &dcol = *matrixtrain.GetColumns();
+
+    // Make a copy of the rules for accessing the train-data
+    MDataArray usedrules;
+    for (Int_t i=0; i<ncols; i++)
+        if (i<ncols-nobs)  // -3 is important!!!
+            usedrules.AddEntry(dcol[i].GetRule());
+        else
+            *fLog << inf << "Skipping " << dcol[i].GetRule() << " for training" << endl;
+
+    // In the case of regression store the rule to be regessed in the
+    // last entry of your rules
+    MDataArray rules(usedrules);
+    rules.AddEntry(ver<3?"Classification.fVal":dcol[ncols-1].GetRule().Data());
+
+    // prepare train-matrix finally used
+    TMatrix mat(matrixtrain.GetM());
+
+    // Resize it such that the obsolete columns are removed
+    mat.ResizeTo(nrows, ncols-nobs+1);
+
+    if (fDebug)
+        gLog.SetNullOutput(kTRUE);
+
+    // In the case one independant RF is trained for each bin (e.g.
+    // energy-bin) train all of them
+    const Int_t nbins = ver>0 ? 1 : grid.GetSize()-1;
+    for (Int_t ie=0; ie<nbins; ie++)
+    {
+        // In the case weights should be used initialize the
+        // corresponding array
+        Double_t sum = 0;
+
+        TArrayF weights(nrows);
+        if (fLastDataColumnHasWeights)
+        {
+            for (Int_t j=0; j<nrows; j++)
+            {
+                weights[j] = matrixtrain.GetM()(j, ncols-nobs);
+                sum += weights[j];
+            }
+        }
+
+        *fLog << inf << "MRanForestCalc::Train: Sum of weights " << sum << endl;
+
+        // Setup the matrix such that the last comlumn contains
+        // the classifier or the regeression target value
+        switch (ver)
+        {
+        case 0: // Replace last column by a classification which is 1 in
+                // the case the event belongs to this bin, 0 otherwise
+            {
+                Int_t irows=0;
+                for (Int_t j=0; j<nrows; j++)
+                {
+                    const Double_t value  = matrixtrain.GetM()(j,ncols-1);
+                    const Bool_t   inside = value>grid[ie] && value<=grid[ie+1];
+
+                    mat(j, ncols-nobs) = inside ? 1 : 0;
+
+                    if (inside)
+                        irows++;
+                }
+                if (irows==0)
+                    *fLog << warn << "WARNING - Skipping";
+                else
+                    *fLog << inf << "Training RF for";
+
+                *fLog << " bin " << ie << " (" << grid[ie] << ", " << grid[ie+1] << ") " << irows << "/" << nrows << endl;
+
+                if (irows==0)
+                    continue;
+            }
+            break;
+
+        case 1: // Use last column as classifier or for regression
+        case 2:
+        case 3:
+            for (Int_t j=0; j<nrows; j++)
+                mat(j, ncols-nobs) = matrixtrain.GetM()(j,ncols-1);
+            break;
+        }
+
+        MHMatrix matrix(mat, &rules, "MatrixTrain");
+
+        MParList plist;
+        MTaskList tlist;
+        plist.AddToList(&tlist);
+        plist.AddToList(&matrix);
+
+        MRanForest rf;
+        rf.SetNumTrees(fNumTrees);
+        rf.SetNumTry(fNumTry);
+        rf.SetNdSize(fNdSize);
+        rf.SetClassify(ver<3 ? kTRUE : kFALSE);
+        if (ver==1)
+            rf.SetGrid(grid);
+        if (fLastDataColumnHasWeights)
+            rf.SetWeights(weights);
+
+        plist.AddToList(&rf);
+
+        MRanForestGrow rfgrow;
+        tlist.AddToList(&rfgrow);
+
+        MFillH fillh("MHRanForestGini");
+        tlist.AddToList(&fillh);
+
+        MEvtLoop evtloop(fTitle);
+        evtloop.SetParList(&plist);
+        evtloop.SetDisplay(fDisplay);
+        evtloop.SetLogStream(fLog);
+
+        if (!evtloop.Eventloop())
+            return kFALSE;
+
+        if (fDebug)
+            gLog.SetNullOutput(kFALSE);
+
+        if (ver==0)
+        {
+            // Calculate bin center
+            const Double_t E = (TMath::Log10(grid[ie])+TMath::Log10(grid[ie+1]))/2;
+
+            // save whole forest
+            rf.SetUserVal(E);
+            rf.SetName(Form("%.10f", E));
+        }
+
+        rf.Write();
+    }
+
+    // save rules
+    usedrules.Write("rules");
+
+    fFunc.Write(gsNameEvalFunc);
+
+    return kTRUE;
+}
+
+Int_t MRanForestCalc::ReadForests(MParList &plist)
+{
+    TFile fileRF(fFileName, "read");
+    if (!fileRF.IsOpen())
+    {
+        *fLog << err << dbginf << "File containing RFs could not be opened... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEForests.Delete();
+
+    TIter Next(fileRF.GetListOfKeys());
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        MRanForest *forest=0;
+        fileRF.GetObject(o->GetName(), forest);
+        if (!forest)
+            continue;
+
+        forest->SetUserVal(atof(o->GetName()));
+
+        fEForests.Add(forest);
+    }
+
+    // Maybe fEForests[0].fRules could be used instead?
+    if (fData->Read("rules")<=0)
+    {
+        *fLog << err << "ERROR - Reading 'rules' from file " << fFileName << endl;
+        return kFALSE;
+    }
+
+    if (fileRF.GetListOfKeys()->FindObject(gsNameEvalFunc))
+    {
+        if (fFunc.Read(gsNameEvalFunc)<=0)
+        {
+            *fLog << err << "ERROR - Reading '" << gsNameEvalFunc << "' from file " << fFileName << endl;
+            return kFALSE;
+        }
+
+        *fLog << inf << "Evaluation function found in file: " << fFunc.GetRule() << endl;
+    }
+
+    return kTRUE;
+}
+
+Int_t MRanForestCalc::PreProcess(MParList *plist)
+{
+    fRFOut = (MParameterD*)plist->FindCreateObj("MParameterD", fNameOutput);
+    if (!fRFOut)
+        return kFALSE;
+
+    fData = (MDataArray*)plist->FindCreateObj("MDataArray");
+    if (!fData)
+        return kFALSE;
+
+    if (!ReadForests(*plist))
+    {
+        *fLog << err << "Reading RFs failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "RF read from " << fFileName << endl;
+
+    if (!fFunc.PreProcess(plist))
+    {
+        *fLog << err << "PreProcessing of evaluation function failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fTestMatrix)
+        return kTRUE;
+
+    fData->Print();
+
+    if (!fData->PreProcess(plist))
+    {
+        *fLog << err << "PreProcessing of the MDataArray failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Double_t MRanForestCalc::Eval() const
+{
+    TVector event;
+    if (fTestMatrix)
+        *fTestMatrix >> event;
+    else
+        *fData >> event;
+
+    // --------------- Single Tree RF -------------------
+    if (fEForests.GetEntriesFast()==1)
+    {
+        MRanForest *rf = static_cast<MRanForest*>(fEForests.UncheckedAt(0));
+        return rf->CalcHadroness(event);
+    }
+
+    // --------------- Multi Tree RF -------------------
+    static TF1 f1("f1", "gaus");
+
+    Double_t sume = 0;
+    Double_t sumh = 0;
+    Double_t maxh = 0;
+    Double_t maxe = 0;
+
+    Double_t max  = -1e10;
+    Double_t min  =  1e10;
+
+    TIter Next(&fEForests);
+    MRanForest *rf = 0;
+
+    TGraph g;
+    while ((rf=(MRanForest*)Next()))
+    {
+        const Double_t h = rf->CalcHadroness(event);
+        const Double_t e = rf->GetUserVal();
+
+        g.SetPoint(g.GetN(), e, h);
+
+        sume += e*h;
+        sumh += h;
+
+        if (h>maxh)
+        {
+            maxh = h;
+            maxe = e;
+        }
+        if (e>max)
+            max = e;
+        if (e<min)
+            min = e;
+    }
+
+    switch (fEstimationMode)
+    {
+    case kMean:
+        return sume/sumh;
+    case kMaximum:
+        return maxe;
+    case kFit:
+        f1.SetParameter(0, maxh);
+        f1.SetParameter(1, maxe);
+        f1.SetParameter(2, 0.125);
+        g.Fit(&f1, "Q0N");
+        return f1.GetParameter(1);
+    }
+
+    return 0;
+}
+
+Int_t MRanForestCalc::Process()
+{
+    const Double_t val = Eval();
+
+    fRFOut->SetVal(fFunc.Eval(val));
+    fRFOut->SetReadyToSave();
+
+    return kTRUE;
+}
+
+void MRanForestCalc::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " - Forest ";
+    switch (fEForests.GetEntries())
+    {
+    case 0:  *fLog << "not yet initialized." << endl;     break;
+    case 1:  *fLog << "is a single tree forest." << endl; break;
+    default: *fLog << "is a multi tree forest." << endl;  break;
+    }
+    /*
+     *fLog << " - Trees: " << fNumTrees << endl;
+     *fLog << " - Trys: " << fNumTry << endl;
+     *fLog << " - Node Size: " << fNdSize << endl;
+     *fLog << " - Node Size: " << fNdSize << endl;
+     */
+    *fLog << " - FileName: " << fFileName << endl;
+    *fLog << " - NameOutput: " << fNameOutput << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MRanForestCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FileName", print))
+    {
+        rc = kTRUE;
+        SetFileName(GetEnvValue(env, prefix, "FileName", fFileName));
+    }
+    if (IsEnvDefined(env, prefix, "Debug", print))
+    {
+        rc = kTRUE;
+        SetDebug(GetEnvValue(env, prefix, "Debug", fDebug));
+    }
+    if (IsEnvDefined(env, prefix, "NameOutput", print))
+    {
+        rc = kTRUE;
+        SetNameOutput(GetEnvValue(env, prefix, "NameOutput", fNameOutput));
+    }
+    if (IsEnvDefined(env, prefix, "EstimationMode", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "EstimationMode", "");
+        txt = txt.Strip(TString::kBoth);
+        txt.ToLower();
+        if (txt==(TString)"mean")
+            fEstimationMode = kMean;
+        if (txt==(TString)"maximum")
+            fEstimationMode = kMaximum;
+        if (txt==(TString)"fit")
+            fEstimationMode = kFit;
+        rc = kTRUE;
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mranforest/MRanForestCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForestCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForestCalc.h	(revision 17960)
@@ -0,0 +1,129 @@
+#ifndef MARS_MRanForestCalc
+#define MARS_MRanForestCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_MDataPhrase
+#include "MDataPhrase.h"
+#endif
+
+class MDataArray;
+class MParameterD;
+class MHMatrix;
+
+class MRanForestCalc : public MTask
+{
+public:
+    enum EstimationMode_t
+    {
+        kMean,
+        kMaximum,
+        kFit
+    };
+
+private:
+    static const TString gsDefName;      //! Default Name
+    static const TString gsDefTitle;     //! Default Title
+    static const TString gsNameOutput;   //! Default Output name
+    static const TString gsNameEvalFunc; //! Evaluation function name
+
+    MDataArray  *fData;                 //! Used to store the MDataChains to get the event values
+    MParameterD *fRFOut;                //! Used to store result
+    MHMatrix    *fTestMatrix;           //! Test Matrix used in Process (together with MMatrixLoop)
+    MDataPhrase  fFunc;                 //! Function to apply to the result
+
+    TObjArray    fEForests;             //! List of forests read or to be written
+
+    Int_t        fNumTrees;             //! Training parameters
+    Int_t        fNumTry;               //! Training parameters
+    Int_t        fNdSize;               //! Training parameters
+
+    Int_t        fNumObsoleteVariables; //! Training parameters
+    Bool_t       fLastDataColumnHasWeights; //! Training parameters
+
+    TString      fFileName;             // File name to forest
+    TString      fNameOutput;           // Name of output container
+
+    Bool_t       fDebug;                // Debugging of eventloop while training on/off
+
+    EstimationMode_t fEstimationMode;   // Mode of estimation in case of multi random forest regression
+
+private:
+    // MTask
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+    // MRanForestCalc
+    Int_t ReadForests(MParList &plist);
+    Double_t Eval() const;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // Train Interface
+    Int_t Train(const MHMatrix &n, const TArrayD &grid, Int_t ver);
+
+public:
+    MRanForestCalc(const char *name=NULL, const char *title=NULL);
+    ~MRanForestCalc();
+
+    // TObject
+    void Print(Option_t *o="") const; //*MENU*
+
+    // Setter for estimation
+    void SetFileName(TString filename)            { fFileName = filename; }
+    void SetEstimationMode(EstimationMode_t op)   { fEstimationMode = op; }
+    void SetNameOutput(TString name=gsNameOutput) { fNameOutput = name; }
+
+    // Setter for training
+    void SetNumTrees(UShort_t n=100) { fNumTrees = n; }
+    void SetNdSize(UShort_t n=5)     { fNdSize   = n; }
+    void SetNumTry(UShort_t n=0)     { fNumTry   = n; }
+    void SetDebug(Bool_t b=kTRUE)    { fDebug    = b; }
+
+    Bool_t SetFunction(const char *name="x");
+
+    void SetNumObsoleteVariables(Int_t n=1)          { fNumObsoleteVariables = n; }
+    void SetLastDataColumnHasWeights(Bool_t b=kTRUE) { fLastDataColumnHasWeights = b; }
+
+    // Train Interface
+    Int_t TrainMultiRF(const MHMatrix &n, const TArrayD &grid)
+    {
+        // One yes/no-classification forest is trained for each bin
+        return Train(n, grid, 0);
+    }
+    Int_t TrainSingleRF(const MHMatrix &n, const TArrayD &grid=TArrayD())
+    {
+        // w/o Grid: Last Column contains classifier
+        // w/  Grid: Last Column will be converted by grid into classifier
+        return Train(n, grid, grid.GetSize()==0 ? 2 : 1);
+    }
+    Int_t TrainRegression(const MHMatrix &n)
+    {
+        // Use last column for regression
+        return Train(n, TArrayD(), 3);
+    }
+
+    Int_t Train(const MHMatrix &m, Bool_t regression)
+    {
+        return regression ? TrainRegression(m) : TrainSingleRF(m);
+    }
+
+    // Test Interface
+    void  SetTestMatrix(MHMatrix *m=0) { fTestMatrix=m; }
+    void  InitMapping(MHMatrix *m=0)   { fTestMatrix=m; }
+
+    ClassDef(MRanForestCalc, 1) // Task to calculate RF output and for RF training
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mranforest/MRanForestFill.cc
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForestFill.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForestFill.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mranforest/MRanForestFill.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForestFill.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForestFill.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mranforest/MRanForestGrow.cc
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForestGrow.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForestGrow.cc	(revision 17960)
@@ -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 Hengstebeck 3/2003 <mailto:hengsteb@physik.hu-berlin.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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 "MRanForest.h"
+
+ClassImp(MRanForestGrow);
+
+using namespace std;
+
+const TString MRanForestGrow::gsDefName  = "MRead";
+const TString MRanForestGrow::gsDefTitle = "Task to train a random forst";
+
+MRanForestGrow::MRanForestGrow(const char *name, const char *title)
+{
+    //   set the name and title of this object
+
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    //     SetNumTrees();
+    //     SetNumTry();
+    //     SetNdSize();
+}
+
+Int_t MRanForestGrow::PreProcess(MParList *plist)
+{
+    fMatrix = (MHMatrix*)plist->FindObject("MatrixTrain", "MHMatrix");
+    if (!fMatrix)
+    {
+        *fLog << err << dbginf << "MatrixTrain [MHMatrix] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanForest = (MRanForest*)plist->FindCreateObj("MRanForest");
+    if (!fRanForest)
+    {
+        *fLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    //     fRanForest->SetNumTry(fNumTry);
+    //     fRanForest->SetNdSize(fNdSize);
+    //     fRanForest->SetNumTrees(fNumTrees);
+
+    return fRanForest->SetupGrow(fMatrix,plist);
+}
+
+Int_t MRanForestGrow::Process()
+{
+    return fRanForest->GrowForest();
+}
+
+Int_t MRanForestGrow::PostProcess()
+{
+    fRanForest->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mranforest/MRanForestGrow.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanForestGrow.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanForestGrow.h	(revision 17960)
@@ -0,0 +1,46 @@
+#ifndef MARS_MRanForestGrow
+#define MARS_MRanForestGrow
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MHMatrix;
+class MParList;
+class MRanForest;
+
+class MRanForestGrow : public MRead
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    //     Int_t fNumTrees;
+    //     Int_t fNumTry;
+    //     Int_t fNdSize;
+
+    MRanForest *fRanForest;
+    MHMatrix   *fMatrix;   //! matrix with events
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    UInt_t  GetEntries()            { return 100; }//fNumTrees; }
+    TString GetFileName() const     { return "MRanForestGrow"; }
+    TString GetFullFileName() const { return "MRanForestGrow"; }
+
+public:
+    MRanForestGrow(const char *name=NULL, const char *title=NULL);
+
+    MRanForest *GetForest() const { return fRanForest; }
+
+    //     void SetNumTrees(Int_t n=-1) { fNumTrees=n>0?n:100; }
+    //     void SetNumTry(Int_t   n=-1) { fNumTry  =n>0?n:  3; }
+    //     void SetNdSize(Int_t   n=-1) { fNdSize  =n>0?n:  1; }
+
+    ClassDef(MRanForestGrow, 0) // Task to grow a random forest
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mranforest/MRanTree.cc
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanTree.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanTree.cc	(revision 17960)
@@ -0,0 +1,732 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@physik.hu-berlin.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRanTree
+//
+// ParameterContainer for Tree structure
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRanTree.h"
+
+#include <iostream>
+
+#include <TRandom.h>
+
+#include "MArrayI.h"
+#include "MArrayF.h"
+
+#include "MMath.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRanTree);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+// Default constructor.
+//
+MRanTree::MRanTree(const char *name, const char *title):fClassify(kTRUE),fNdSize(0), fNumTry(3)
+{
+
+    fName  = name  ? name  : "MRanTree";
+    fTitle = title ? title : "Storage container for structure of a single tree";
+}
+
+// --------------------------------------------------------------------------
+// Copy constructor
+//
+MRanTree::MRanTree(const MRanTree &tree)
+{
+    fName  = tree.fName;
+    fTitle = tree.fTitle;
+
+    fClassify = tree.fClassify;
+    fNdSize   = tree.fNdSize;
+    fNumTry   = tree.fNumTry;
+
+    fNumNodes    = tree.fNumNodes;
+    fNumEndNodes = tree.fNumEndNodes;
+
+    fBestVar   = tree.fBestVar;
+    fTreeMap1  = tree.fTreeMap1;
+    fTreeMap2  = tree.fTreeMap2;
+    fBestSplit = tree.fBestSplit;
+    fGiniDec   = tree.fGiniDec;
+}
+
+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(TMatrix *mat, const MArrayF &hadtrue, const MArrayI &idclass,
+                        MArrayI &datasort, const MArrayI &datarang, const MArrayF &tclasspop,
+                        const Float_t &mean, const Float_t &square, const MArrayI &jinbag, const MArrayF &winbag,
+                        const int nclass)
+{
+    // arrays have to be initialized with generous size, so number of total nodes (nrnodes)
+    // is estimated for worst case
+    const Int_t numdim =mat->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++;
+
+    MArrayI bestsplit(nrnodes);
+    MArrayI bestsplitnext(nrnodes);
+
+    fBestVar.Set(nrnodes);    fBestVar.Reset();
+    fTreeMap1.Set(nrnodes);   fTreeMap1.Reset();
+    fTreeMap2.Set(nrnodes);   fTreeMap2.Reset();
+    fBestSplit.Set(nrnodes);  fBestSplit.Reset();
+    fGiniDec.Set(numdim);     fGiniDec.Reset();
+
+
+    if(fClassify)
+        FindBestSplit=&MRanTree::FindBestSplitGini;
+    else
+        FindBestSplit=&MRanTree::FindBestSplitSigma;
+
+    // tree growing
+    BuildTree(datasort,datarang,hadtrue,idclass,bestsplit, bestsplitnext,
+              tclasspop,mean,square,winbag,ninbag,nclass);
+
+    // post processing, determine cut (or split) values fBestSplit
+    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] = ((*mat)(bsp, msp)+(*mat)(bspn,msp))/2;
+    }
+
+    // resizing arrays to save memory
+    fBestVar.Set(fNumNodes);
+    fTreeMap1.Set(fNumNodes);
+    fTreeMap2.Set(fNumNodes);
+    fBestSplit.Set(fNumNodes);
+}
+
+int MRanTree::FindBestSplitGini(const MArrayI &datasort,const MArrayI &datarang,
+                                const MArrayF &hadtrue,const MArrayI &idclass,
+                                Int_t ndstart,Int_t ndend, const MArrayF &tclasspop,
+                                const Float_t &mean, const Float_t &square, Int_t &msplit,
+                                Float_t &decsplit,Int_t &nbest, const MArrayF &winbag,
+                                const int nclass)
+{
+    const Int_t nrnodes = fBestSplit.GetSize();
+    const Int_t numdata = (nrnodes-1)/2;
+    const Int_t mdim = fGiniDec.GetSize();
+
+    // 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;
+
+    // tclasspop: sum of weights for events in class
+    for (Int_t j=0; j<nclass; j++) // loop over number of classes to classifiy
+    {
+        pno+=tclasspop[j]*tclasspop[j];
+        pdo+=tclasspop[j];
+    }
+
+    const Double_t crit0=pno/pdo;  // weighted mean of weights
+
+    // 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++) // we could try ALL variables???
+    {
+        const Int_t mvar= gRandom->Integer(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;
+
+        MArrayF wl(nclass);     // left node //nclass
+        MArrayF wr(tclasspop);  // right node//nclass
+
+        Double_t critvar=-FLT_MAX;
+        for(Int_t nsp=ndstart;nsp<=ndend-1;nsp++)
+        {
+            const Int_t  &nc = datasort[mn+nsp];
+            const Int_t   &k = idclass[nc];
+            const Float_t &u = winbag[nc];
+
+            // do classification, Gini index as split rule
+            rln   +=u*(2*wl[k]+u);  // += u*(wl[k]{i-1} + wl[k]{i-1}+u{i})
+            rld   +=u;   // sum of weights left  from cut total
+            wl[k] +=u;   // sum of weights left  from cut for class k
+
+            rrn   -=u*(2*wr[k]-u);  // -= u*(wr[k]{i-1} + wr[k]{i-1}-u{i})
+            //  rr0=0; rr0+=u*2*tclasspop[k]
+            //  rrn = pno - rr0 + rln
+            rrd   -=u;   // sum of weights right from cut total
+            wr[k] -=u;   // sum of weights right from cut for class k
+
+            // REPLACE BY?
+            // rr0   = 0
+            // rr0  += u*2*tclasspop[k]
+            // rrn   = pno - rr0 + rln
+            // rrd   = pdo - rld
+            // wr[k] = tclasspop[k] - wl[k]
+
+            // crit = (rln*(pdo - rld + 1) + pno - rr0) / rld*(pdo - rld)
+
+            /*
+             if (k==background)
+                continue;
+             crit = TMath::Max(MMath::SignificanceLiMa(rld, rld-wl[k]),
+                               MMath::SignificanceLiMa(rrd, rrd-wr[k]))
+             */
+
+            // This condition is in fact a == (> cannot happen at all)
+            // This is because we cannot set the cut between two identical values
+            //if (datarang[mn+datasort[mn+nsp]]>=datarang[mn+datasort[mn+nsp+1]])
+            if (datarang[mn+nc]>=datarang[mn+datasort[mn+nsp+1]])
+                continue;
+
+            // If crit starts to become pretty large do WHAT???
+            //if (TMath::Min(rrd,rld)<=1.0e-5) // FIXME: CHECKIT FOR WEIGHTS!
+            //    continue;
+
+            const Double_t crit=(rln/rld)+(rrn/rrd);
+            if (!TMath::Finite(crit))
+                continue;
+
+            // Search for the highest value of crit
+            if (crit<=critvar) continue;
+
+            // store the highest crit value and the corresponding event to cut at
+            nbestvar=nsp;
+            critvar=crit;
+        }
+
+        if (critvar<=critmax) continue;
+
+        msplit=mvar;      // Variable in which to split
+        nbest=nbestvar;   // event at which the best split was found
+        critmax=critvar;
+    }
+
+    // crit0 = MMath::SignificanceLiMa(pdo, pdo-tclasspop[0])
+    // mean increase of sensitivity
+    // decsplit = sqrt(critmax/crit0)
+    decsplit=critmax-crit0;
+
+    return critmax<-1.0e10 ? 1 : 0;
+}
+
+int MRanTree::FindBestSplitSigma(const MArrayI &datasort,const MArrayI &datarang,
+                                 const MArrayF &hadtrue, const MArrayI &idclass,
+                                 Int_t ndstart,Int_t ndend, const MArrayF &tclasspop,
+                                 const Float_t &mean, const Float_t &square, Int_t &msplit,
+                                 Float_t &decsplit,Int_t &nbest, const MArrayF &winbag,
+                                 const int nclass)
+{
+    const Int_t nrnodes = fBestSplit.GetSize();
+    const Int_t numdata = (nrnodes-1)/2;
+    const Int_t mdim = fGiniDec.GetSize();
+
+    // 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 split-index,
+
+    // resolution
+    //Double_t pno=-(tclasspop[0]*square-mean*mean)*tclasspop[0];
+    //Double_t pdo= (tclasspop[0]-1.)*mean*mean;
+
+    // n*resolution
+    //Double_t pno=-(tclasspop[0]*square-mean*mean)*tclasspop[0];
+    //Double_t pdo= mean*mean;
+
+    // variance
+    //Double_t pno=-(square-mean*mean/tclasspop[0]);
+    //Double_t pdo= (tclasspop[0]-1.);
+
+    // n*variance
+    Double_t pno= (square-mean*mean/tclasspop[0]);
+    Double_t pdo= 1.;
+
+    // 1./(n*variance)
+    //Double_t pno= 1.;
+    //Double_t pdo= (square-mean*mean/tclasspop[0]);
+
+    const Double_t crit0=pno/pdo;
+
+    // start main loop through variables to find best split,
+
+    Double_t critmin=FLT_MAX;
+
+    // random split selection, number of trials = fNumTry
+    for (Int_t mt=0; mt<fNumTry; mt++)
+    {
+        const Int_t mvar= gRandom->Integer(mdim);
+        const Int_t mn  = mvar*numdata;
+
+        Double_t esumr =mean;
+        Double_t e2sumr=square;
+        Double_t esuml =0;
+        Double_t e2suml=0;
+
+        float wl=0.;// left node
+        float wr=tclasspop[0]; // right node
+
+        Double_t critvar=critmin;
+        for(Int_t nsp=ndstart;nsp<=ndend-1;nsp++)
+        {
+            const Int_t &nc=datasort[mn+nsp];
+            const Float_t &f=hadtrue[nc];;
+            const Float_t &u=winbag[nc];
+
+            e2suml+=u*f*f;
+            esuml +=u*f;
+            wl    +=u;
+
+            //-------------------------------------------
+            // resolution
+            //const Double_t rln=(wl*e2suml-esuml*esuml)*wl;
+            //const Double_t rld=(wl-1.)*esuml*esuml;
+
+            // resolution times n
+            //const Double_t rln=(wl*e2suml-esuml*esuml)*wl;
+            //const Double_t rld=esuml*esuml;
+
+            // sigma
+            //const Double_t rln=(e2suml-esuml*esuml/wl);
+            //const Double_t rld=(wl-1.);
+
+            // sigma times n
+            Double_t rln=(e2suml-esuml*esuml/wl);
+            Double_t rld=1.;
+
+            // 1./(n*variance)
+            //const Double_t rln=1.;
+            //const Double_t rld=(e2suml-esuml*esuml/wl);
+            //-------------------------------------------
+
+            // REPLACE BY??? 
+            e2sumr-=u*f*f;   // e2sumr = square       - e2suml
+            esumr -=u*f;     // esumr  = mean         - esuml
+            wr    -=u;       // wr     = tclasspop[0] - wl
+
+            //-------------------------------------------
+            // resolution
+            //const Double_t rrn=(wr*e2sumr-esumr*esumr)*wr;
+            //const Double_t rrd=(wr-1.)*esumr*esumr;
+
+            // resolution times n
+            //const Double_t rrn=(wr*e2sumr-esumr*esumr)*wr;
+            //const Double_t rrd=esumr*esumr;
+
+            // sigma
+            //const Double_t rrn=(e2sumr-esumr*esumr/wr);
+            //const Double_t rrd=(wr-1.);
+
+            // sigma times n
+            const Double_t rrn=(e2sumr-esumr*esumr/wr);
+            const Double_t rrd=1.;
+
+            // 1./(n*variance)
+            //const Double_t rrn=1.;
+            //const Double_t rrd=(e2sumr-esumr*esumr/wr);
+            //-------------------------------------------
+
+            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 (!TMath::Finite(crit))
+                continue;
+
+            if (crit>=critvar) continue;
+
+            nbestvar=nsp;
+            critvar=crit;
+        }
+
+        if (critvar>=critmin) continue;
+
+        msplit=mvar;
+        nbest=nbestvar;
+        critmin=critvar;
+    }
+
+    decsplit=crit0-critmin;
+
+    //return critmin>1.0e20 ? 1 : 0;
+    return decsplit<0 ? 1 : 0;
+}
+
+void MRanTree::MoveData(MArrayI &datasort,Int_t ndstart, Int_t ndend,
+                        MArrayI &idmove,MArrayI &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();
+
+    MArrayI 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(MArrayI &datasort,const MArrayI &datarang, const MArrayF &hadtrue,
+                         const MArrayI &idclass, MArrayI &bestsplit, MArrayI &bestsplitnext,
+                         const MArrayF &tclasspop, const Float_t &tmean, const Float_t &tsquare, const MArrayF &winbag,
+                         Int_t ninbag, const int nclass)
+{
+    // 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;
+
+    MArrayI nodepop(nrnodes);
+    MArrayI nodestart(nrnodes);
+    MArrayI parent(nrnodes);
+
+    MArrayI ncase(numdata);
+    MArrayI idmove(numdata);
+    MArrayI iv(mdim);
+
+    MArrayF classpop(nrnodes*nclass);//nclass
+    MArrayI nodestatus(nrnodes);
+
+    for (Int_t j=0;j<nclass;j++)
+        classpop[j*nrnodes+0]=tclasspop[j];
+
+    MArrayF mean(nrnodes);
+    MArrayF square(nrnodes);
+    MArrayF lclasspop(tclasspop);
+
+    mean[0]=tmean;
+    square[0]=tsquare;
+
+
+    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<nclass;j++)
+              lclasspop[j]=classpop[j*nrnodes+kbuild];
+
+          Int_t msplit, nbest;
+          Float_t decsplit=0;
+
+          if ((this->*FindBestSplit)(datasort,datarang,hadtrue,idclass,ndstart,
+                                     ndend, lclasspop,mean[kbuild],square[kbuild],msplit,decsplit,
+                                     nbest,winbag,nclass))
+          {
+              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 j=idclass[nc];
+                   
+              // statistics left from cut
+              mean[ncur+1]+=hadtrue[nc]*winbag[nc];
+              square[ncur+1]+=hadtrue[nc]*hadtrue[nc]*winbag[nc];
+
+              // sum of weights left from cut
+              classpop[j*nrnodes+ncur+1]+=winbag[nc];
+          }
+
+          for (Int_t n=ndendl+1;n<=ndend;n++)
+          {
+              const Int_t &nc=ncase[n];
+              const int j=idclass[nc];
+
+              // statistics right from cut
+              mean[ncur+2]  +=hadtrue[nc]*winbag[nc];
+              square[ncur+2]+=hadtrue[nc]*hadtrue[nc]*winbag[nc];
+
+              // sum of weights right from cut
+              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<nclass;j++)
+          {
+              popt1+=classpop[j*nrnodes+ncur+1];
+              popt2+=classpop[j*nrnodes+ncur+2];
+          }
+
+          if(fClassify)
+          {
+              // check if only members of one class in node
+              for (Int_t j=0;j<nclass;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<nclass;j++)
+            {
+                if(classpop[j*nrnodes+kn]>pp)
+                {
+                    // class + status of node kn coded into fBestVar[kn]
+                    fBestVar[kn]=j-nclass;
+                    pp=classpop[j*nrnodes+kn];
+                }
+            }
+
+                float sum=0;
+                for(int i=0;i<nclass;i++) sum+=classpop[i*nrnodes+kn];
+
+                fBestSplit[kn]=mean[kn]/sum;
+        }
+}
+
+Double_t MRanTree::TreeHad(const Float_t *evt)
+{
+    // 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]
+
+    // To get rid of the range check of the root classes
+    const Float_t *split = fBestSplit.GetArray();
+    const Int_t   *map1  = fTreeMap1.GetArray();
+    const Int_t   *map2  = fTreeMap2.GetArray();
+    const Int_t   *best  = fBestVar.GetArray();
+
+    Int_t kt=0;
+    for (Int_t k=0; k<fNumNodes; k++)
+    {
+        if (best[kt]<0)
+            break;
+
+        const Int_t m=best[kt];
+        kt = evt[m]<=split[kt] ? map1[kt] : map2[kt];
+    }
+
+    return split[kt];
+}
+
+Double_t MRanTree::TreeHad(const TVector &event)
+{
+    return TreeHad(event.GetMatrixArray());
+}
+
+Double_t MRanTree::TreeHad(const TMatrixFRow_const &event)
+{
+    return TreeHad(event.GetPtr());
+}
+
+Double_t MRanTree::TreeHad(const TMatrix &m, Int_t ievt)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    return TreeHad(TMatrixRow(m, ievt));
+#else
+    return TreeHad(TMatrixFRow_const(m, ievt));
+#endif
+}
+
+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: branches/Mars_McMismatchStudy/mranforest/MRanTree.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/MRanTree.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/MRanTree.h	(revision 17960)
@@ -0,0 +1,119 @@
+#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
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+
+class TMatrixRow;
+class TRandom;
+
+class MArrayI;
+class MArrayF;
+
+class MRanTree : public MParContainer
+{
+private:
+    Bool_t fClassify;
+
+    Int_t fNdSize;
+    Int_t fNumTry;
+
+    Int_t fNumNodes;
+    Int_t fNumEndNodes;
+    Float_t fError;
+
+    TArrayI fBestVar;
+    TArrayI fTreeMap1;
+    TArrayI fTreeMap2;
+    TArrayF fBestSplit;
+    TArrayF fGiniDec;
+
+    int (MRanTree::*FindBestSplit)
+        (const MArrayI &, const MArrayI &, const MArrayF &, const MArrayI &,
+         Int_t, Int_t , const MArrayF &, const Float_t &, const Float_t &, Int_t &, Float_t &,
+         Int_t &, const MArrayF &, const int); //!
+
+    Double_t TreeHad(const Float_t *evt);
+
+    int FindBestSplitGini(const MArrayI &datasort, const MArrayI &datarang,
+                          const MArrayF &hadtrue, const MArrayI &idclass,
+                          Int_t ndstart, Int_t ndend, const MArrayF &tclasspop,
+                          const Float_t &mean, const Float_t &square, Int_t &msplit,
+                          Float_t &decsplit, Int_t &nbest, const MArrayF &winbag,
+                          const int nclass);
+
+    int FindBestSplitSigma(const MArrayI &datasort, const MArrayI &datarang,
+                           const MArrayF &hadtrue, const MArrayI &idclass,
+                           Int_t ndstart, Int_t ndend, const MArrayF &tclasspop,
+                           const Float_t &mean, const Float_t &square, Int_t &msplit,
+                           Float_t &decsplit, Int_t &nbest, const MArrayF &winbag,
+                           const int nclass);
+
+    void MoveData(MArrayI &datasort, Int_t ndstart, Int_t ndend,
+                  MArrayI &idmove, MArrayI &ncase, Int_t msplit,
+                  Int_t nbest, Int_t &ndendl);
+
+    void BuildTree(MArrayI &datasort, const MArrayI &datarang, const MArrayF &hadtrue,
+                   const MArrayI &idclass,MArrayI &bestsplit,MArrayI &bestsplitnext,
+                   const MArrayF &tclasspop, const Float_t &tmean, const Float_t &tsquare, const MArrayF &winbag,
+                   Int_t ninbag, const int nclass);
+
+public:
+    MRanTree(const char *name=NULL, const char *title=NULL);
+    MRanTree(const MRanTree &tree);
+
+    void SetNdSize(Int_t n);
+    void SetNumTry(Int_t n);
+    void SetError(Float_t f) { fError = f; }
+
+    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 IsClassify() const { return fClassify; }
+    Float_t GetError() const { return fError; }
+
+    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); }
+
+    void SetClassify(Bool_t n){ fClassify=n; }
+
+    // functions used in tree growing process
+    void GrowTree(TMatrix *mat, const MArrayF &hadtrue, const MArrayI &idclass,
+                  MArrayI &datasort, const MArrayI &datarang,const MArrayF &tclasspop,
+                  const Float_t &mean, const Float_t &square, const MArrayI &jinbag, const MArrayF &winbag,
+                  const int nclass);
+
+    Double_t TreeHad(const TVector &event);
+    Double_t TreeHad(const TMatrixFRow_const &event);
+    Double_t TreeHad(const TMatrix &m, Int_t ievt);
+
+    Bool_t AsciiWrite(std::ostream &out) const;
+
+    ClassDef(MRanTree, 1) // Storage container for tree structure
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mranforest/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/Makefile	(revision 17960)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = RanForest
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mdata -I../manalysis -I../mmc -I../mfileio
+#               MParContainer MH     MDataArray MHadronness    MMcEvt
+
+SRCFILES = MRanTree.cc \
+           MRanForest.cc \
+           MRanForestGrow.cc \
+           MRanForestCalc.cc \
+	   MHRanForest.cc \
+	   MHRanForestGini.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mranforest/RanForestIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/RanForestIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/RanForestIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mranforest/RanForestLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mranforest/RanForestLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mranforest/RanForestLinkDef.h	(revision 17960)
@@ -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 MRanTree+;  
+#pragma link C++ class MRanForest+;
+#pragma link C++ class MRanForestGrow+;
+#pragma link C++ class MRanForestCalc+;
+
+#pragma link C++ class MHRanForest+;
+#pragma link C++ class MHRanForestGini+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawBoardsFACT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawBoardsFACT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawBoardsFACT.cc	(revision 17960)
@@ -0,0 +1,55 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRawBoardsFACT
+//
+//  This container stores the information about one crate. A list of this
+//  informations can be find at MRawCrateArray
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRawBoardsFACT.h"
+
+//#include "MLog.h"
+//#include "MLogManip.h"
+
+ClassImp(MRawBoardsFACT);
+
+using namespace std;
+
+MRawBoardsFACT::MRawBoardsFACT()
+{
+    fName = "MRawBoardsFACT";
+
+    memset(fFadTime, 0, 160);
+}
+
+// --------------------------------------------------------------------------
+//
+//  print all stored information to gLog
+//
+void MRawBoardsFACT::Print(Option_t *t) const
+{
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawBoardsFACT.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawBoardsFACT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawBoardsFACT.h	(revision 17960)
@@ -0,0 +1,29 @@
+#ifndef MARS_MRawBoardsFACT
+#define MARS_MRawBoardsFACT
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+//gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MRawBoardsFACT : public MParContainer
+{
+    friend class MRawFitsRead;
+
+private:
+    UInt_t fFadTime[40];  // Crate number the information corresponds to
+
+public:
+    MRawBoardsFACT();
+
+    UInt_t GetFadTime(UInt_t i) const { return fFadTime[i]; }
+
+    void Print(Option_t *t=NULL) const;
+
+    ClassDef(MRawBoardsFACT, 1) //Container to store the Raw CRATE DATA
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawCrateArray.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawCrateArray.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawCrateArray.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mraw/MRawCrateArray.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawCrateArray.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawCrateArray.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mraw/MRawCrateData.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawCrateData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawCrateData.cc	(revision 17960)
@@ -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 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRawCrateData
+//
+//  This container stores the information about one crate. A list of this
+//  informations can be find at MRawCrateArray
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRawCrateData.h"
+
+#include <fstream>
+
+#include <TArrayC.h>
+
+#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
+//
+Bool_t MRawCrateData::ReadEvtOld(istream& fin, UShort_t ver)
+{
+    if (ver<7)
+    {
+        fin.read((char*)&fDAQCrateNumber, 2);
+        fin.read((char*)&fFADCEvtNumber,  4);
+        fin.read((char*)&fFADCClockTick,  4);
+        if (ver>1)
+            fin.read((char*)&fABFlags, 1);
+    }
+    else
+    {
+        //  U8  CrateNumber;    // 0-4
+        //  U8  BoardNumber;    // 0-1
+        //  U8  ChannelNumber;  // 0-3
+        fDAQCrateNumber = 0;
+        fin.read((char*)&fDAQCrateNumber, 1); // U8: CrateNumber 0-4
+
+        Byte_t dummyb;
+        fin.read((char*)&dummyb, 1); // U8 Board   number 0-1
+        fin.read((char*)&dummyb, 1); // U8 Channel number 0-3
+
+        fin.read((char*)&fFADCEvtNumber, 4); // U32 CrateEvtNumber
+
+        // Clock count. The Clock is synchronized with the 10 MHz external clock,
+        //  which is feed to for all FADC channels.
+        // The units are [psec], which is obviously much smaller than the real accuracy.
+        // The ClockTick should be identical for all channels of the same board.
+        //  Still keep it for debugging purposes.
+        // Like in the 300MHz system this number is extremely useful to check the
+        //  integrity of the data.
+        UInt_t dummyi;
+        fin.read((char*)&dummyi, 4); //  U32 FadcClockTickHi;  // high significant bits
+        fin.read((char*)&dummyi, 4); //  U32 FadcClockTickLo;  // low significant bits
+
+        // Trigger Time Interpolation in [psec] (originally it is a double
+        // in Acqiris software). Again this number should be identical for
+        // all channels in the same board. It is not clear at the moment
+        // if this number will be useful in the end, but I propose to keep
+        // it. The data volume is increase by <0.1%
+        UInt_t dummys;
+        fin.read((char*)&dummys, 2); //   U16 TrigTimeInterpol;
+    }
+
+    return fin.eof() ? kFALSE : kTRUE;
+}
+
+Bool_t MRawCrateData::ReadEvt(istream& fin, UShort_t ver, UInt_t size)
+{
+    if (ver<11)
+        return ReadEvtOld(fin, ver);
+
+    if (size==0)
+    {
+        *fLog << err << "ERROR - Event header size unknown." << endl;
+        return kFALSE;
+    }
+
+    if (size<28)
+    {
+        *fLog << err << "ERROR - Event header too small (<28b)." << endl;
+        return kFALSE;
+    }
+
+    TArrayC h(size);
+    fin.read(h.GetArray(), h.GetSize());
+    if (!fin)
+        return kFALSE;
+
+    // ----- convert -----
+    //const Byte_t  *Char  = reinterpret_cast<Byte_t* >(h.GetArray());
+    const UInt_t  *Int   = reinterpret_cast<UInt_t* >(h.GetArray());
+    //const Float_t *Float = reinterpret_cast<Float_t*>(h.GetArray());
+
+    fDAQCrateNumber = Int[0];
+    fFADCEvtNumber  = Int[3];
+
+    return kTRUE;
+}
+
+void MRawCrateData::SkipEvt(istream &fin, UShort_t ver)
+{
+    fin.seekg(ver>1?11:10);
+}
+
+// --------------------------------------------------------------------------
+//
+//  print all stored information to gLog
+//
+void MRawCrateData::Print(Option_t *t) const
+{
+    *fLog << all;
+    *fLog << "Crate #" << dec << fDAQCrateNumber << ":  ";
+    *fLog << "FADCEventNr = " << fFADCEvtNumber << "  ";
+    *fLog << "FADCClockTick = " << fFADCClockTick << " (20MHz)  ";
+    *fLog << "ABFlags = 0x" << Form("%02x", fABFlags) << endl;
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawCrateData.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawCrateData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawCrateData.h	(revision 17960)
@@ -0,0 +1,38 @@
+#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
+
+    Bool_t ReadEvtOld(std::istream& fin, UShort_t ver);
+
+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;
+
+    Bool_t ReadEvt(std::istream& fin, UShort_t ver, UInt_t size);
+    void   SkipEvt(std::istream& fin, UShort_t ver);
+
+    ClassDef(MRawCrateData, 2) //Container to store the Raw CRATE DATA
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawEvtData.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawEvtData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawEvtData.cc	(revision 17960)
@@ -0,0 +1,742 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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 8
+//   ------------------
+//    + MArrayS *fStartCell
+//    + Bool_t   fIsSigned
+//
+//   Version 7
+//   ------------------
+//    + UShort_t fNumBytesPerSample;
+//
+//   Version 6
+//   ------------------
+//    - The data can now be stoe in a single array keeping he full
+//      compatibility
+//
+//   Version 5 (0.8.5):
+//   ------------------
+//    - Changed type of ABFlags from TArrayC to MArrayB
+//
+//   Version 4 (0.8.4):
+//   ------------------
+//    - Changed derivement from MCamEvent to MParContainer and MCamEvent
+//
+//   Version 3 (0.8.4):
+//   ------------------
+//    - Added fABFlags
+//
+//   Version 2:
+//   ----------
+//    - Derives from MCamEvent now
+//
+//   Version 1:
+//   ----------
+//    - First implementation
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRawEvtData.h"
+
+#include <fstream>
+
+#include <TH1.h>
+#include <TGraph.h>
+#include <TArrayC.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayS.h"
+#include "MArrayB.h"
+#include "MArrayI.h"
+#include "MGeomCam.h"
+
+#include "MRawCrateArray.h"
+#include "MRawCrateData.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MRawEvtData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It initializes all arrays with zero size.
+//
+MRawEvtData::MRawEvtData(const char *name, const char *title)
+    : fRunHeader(0), fTriggerType(0), fNumBytesPerSample(1), fIsSigned(false)
+{
+    fName  = name  ? name  : "MRawEvtData";
+    fTitle = title ? title : "Raw Event Data Information";
+
+    InitArrays();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes all the arrays.
+//
+MRawEvtData::~MRawEvtData()
+{
+    DeleteArrays();
+}
+
+// --------------------------------------------------------------------------
+//
+// reset all arrays
+//
+void MRawEvtData::Clear(Option_t *)
+{
+    /*
+     FIXME:
+     Is Reset (set all entries to zero) what you want to do
+     or Set(0) (delete the array)
+     */
+    fHiGainPixId->Reset();
+    fLoGainPixId->Reset();
+    fHiGainFadcSamples->Reset();
+    fLoGainFadcSamples->Reset();
+    fABFlags->Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of hi gain samples per pixel
+//
+UShort_t MRawEvtData::GetNumHiGainSamples() const
+{
+    // If value<0 we are reading old MC files which don't have the
+    // value set so far. So we use the old methid to determin the
+    // numbers and calculate them from the length of the arrays.
+    return fHiGainPixId->GetSize() ? fHiGainFadcSamples->GetSize()/(fHiGainPixId->GetSize()*fNumBytesPerSample) : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of lo gain samples per pixel
+//
+UShort_t MRawEvtData::GetNumLoGainSamples() const
+{
+    // If value<0 we are reading old MC files which don't have the
+    // value set so far. So we use the old methid to determin the
+    // numbers and calculate them from the length of the arrays.
+    return fLoGainPixId->GetSize() ? fLoGainFadcSamples->GetSize()/(fLoGainPixId->GetSize()*fNumBytesPerSample) : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of stored pixel
+//
+UShort_t MRawEvtData::GetNumPixels() const
+{
+    return fHiGainPixId ? fHiGainPixId->GetSize() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print out the onformation to *fLog.
+//  Options:
+//     "hex"      Prints the time slices hexadecimal (default)
+//     "dec"      Prints the time slices decimal
+//
+void MRawEvtData::Print(Option_t *opt) const
+{
+    //
+    // print fadc inforation to screen
+    // Possible Options:
+    // - DEC: Print values decimal instead of hexadecimal (default)
+    //
+    const UShort_t nHiSamp = GetNumHiGainSamples();
+    const UShort_t nLoSamp = GetNumLoGainSamples();
+
+    const UShort_t bps     = GetNumBytesPerSample();
+
+    fLog->unsetf(ios::showbase);
+
+    *fLog << dec << all;
+    *fLog << GetDescriptor() << ": " << endl;
+    *fLog << GetNumPixels() << " Pixels with " << (Int_t)nHiSamp << "/" << (Int_t)nLoSamp << " samples" << endl;
+
+    TString str(opt);
+    Int_t manip = str.Contains("dec", TString::kIgnoreCase);
+
+    MRawEvtPixelIter pixel(const_cast<MRawEvtData*>(this));
+    Int_t i = 0;
+    while (pixel.Next())
+    {
+        const UShort_t idx = pixel.GetPixelId();
+
+        *fLog << endl << dec << setfill(' ');
+        *fLog << " " << setw(3) << i++ << " - " << setw(3) << idx << " ";
+
+        if (pixel.IsABFlagValid())
+            *fLog << "<" << (pixel.HasABFlag()?"B":"A") << "> ";
+
+        *fLog << (manip?dec:hex) << setfill(manip?' ':'0');
+
+        const Byte_t *hi = (Byte_t*)pixel.GetHiGainSamples();
+        const Byte_t *lo = (Byte_t*)pixel.GetLoGainSamples();
+
+        for (int j=0; j<nHiSamp*bps; j++)
+        {
+            *fLog << setw(manip?3:2);
+            *fLog << (hi[j]&0xff);
+            if (manip)
+                *fLog << ' ';
+        }
+
+        for (int j=0; j<nLoSamp*bps; j++)
+        {
+            *fLog << setw(manip?3:2);
+            *fLog << ((UShort_t)lo[j]&0xff);
+            if (manip)
+                *fLog << ' ';
+        }
+    }
+    *fLog << dec << 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"))
+        sscanf(str.Data()+5, "%d", &id);
+    if (str.BeginsWith("hist"))
+        sscanf(str.Data()+4, "%d", &id);
+
+    MRawEvtPixelIter pix(this);
+    if (!pix.Jump(id))
+    {
+        *fLog << warn << dec << "Pixel Idx #" << id << " doesn't exist!" << endl;
+        return;
+    }
+
+    const void *higains = pix.GetHiGainSamples();
+    const void *logains = pix.GetLoGainSamples();
+
+    const Int_t nh = GetNumHiGainSamples();
+    const Int_t nl = GetNumLoGainSamples();
+
+    TString name = "Pixel Idx.";
+    name += pix.GetPixelId();
+
+    fIsSigned = kTRUE;
+
+    Bool_t same = str.Contains("same");
+
+    cout << "MIN/MAX=" << fNumBytesPerSample << " " << GetMin() << " " << GetMax() << endl;
+
+    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, GetSample(higains, i));
+        for (int i=0; i<nl; i++)
+            graphhi->SetPoint(graphhi->GetN(), i+nh, GetSample(logains, i));
+
+        graphhi->SetMaximum(GetMax()+0.5);
+        graphhi->SetMinimum(GetMin());
+
+        graphhi->SetBit(kCanDelete);
+        graphhi->Draw(same ? "C*" : "AC*");
+
+        TH1F *histhi = graphhi->GetHistogram();
+        histhi->SetMinimum(GetMin());
+        histhi->SetMaximum(GetMax()+0.5);
+ 
+        histhi->SetXTitle("Time/FADC Slices");
+        histhi->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+nl, -0.5, nh+nl-.5);
+        histh->SetMinimum(GetMin());
+        histh->SetMaximum(GetMax()+0.5);
+        histh->SetXTitle("Time [FADC Slices]");
+        histh->SetYTitle("Signal [FADC Units]");
+        histh->SetDirectory(NULL);
+        for (int i=0; i<nh; i++)
+            histh->Fill(i, GetSample(higains, i));
+        for (int i=0; i<nl; i++)
+            histh->Fill(i+nl, GetSample(logains, i));
+        histh->SetBit(kCanDelete);
+        histh->Draw(same ? "same" : "");
+
+        return;
+    }
+
+    *fLog << warn << dbginf << "WARNING - You must specify either 'GRAPH' or 'HIST'" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all the arrays
+//  The flag is for future usage.
+//
+void MRawEvtData::InitArrays(UShort_t numconnected, UShort_t maxid)
+{
+    // fRunHeader should not be set only in the constructor!
+    const Int_t numhi  = fRunHeader ? fRunHeader->GetNumSamplesHiGain()  : 0;
+    const Int_t numlo  = fRunHeader ? fRunHeader->GetNumSamplesLoGain()  : 0;
+
+    fNumBytesPerSample = fRunHeader ? fRunHeader->GetNumBytesPerSample() : 1;
+
+
+    if (fRunHeader == 0)
+    {
+        fTriggerType = 0x0000;
+    }
+    else
+    {
+        switch(fRunHeader->GetRunType())
+        {
+        case MRawRunHeader::kRTMonteCarlo|MRawRunHeader::kRTData:
+            fTriggerType = 0x0004; break;
+        case MRawRunHeader::kRTMonteCarlo|MRawRunHeader::kRTPedestal:
+            fTriggerType = 0x0400; break;
+        case MRawRunHeader::kRTMonteCarlo|MRawRunHeader::kRTCalibration:
+            fTriggerType = 0x0164; break;
+        default:
+            fTriggerType = 0x0000; break;
+        }
+    }
+
+    fHiGainPixId       = new MArrayS(numconnected);
+    fLoGainPixId       = new MArrayS(0);
+    fHiGainFadcSamples = new MArrayB(numconnected*(numhi+numlo)*fNumBytesPerSample);
+    fLoGainFadcSamples = new MArrayB(0);
+
+    fABFlags           = new MArrayB(maxid==0 ? 0 : maxid/8+1);
+    fStartCells        = new MArrayS(0);
+
+    fConnectedPixels   = 0;
+}
+
+void MRawEvtData::InitStartCells()
+{
+    delete fStartCells;
+    fStartCells = new MArrayS(fHiGainPixId->GetSize());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all the arrays
+//
+void MRawEvtData::DeleteArrays()
+{
+    delete fHiGainPixId;
+    delete fLoGainPixId;
+    delete fHiGainFadcSamples;
+    delete fLoGainFadcSamples;
+    delete fABFlags;
+    delete fStartCells;
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes all arrays describing the pixel Id and Samples in pixels.
+// The flag is for future usage.
+//
+void MRawEvtData::ResetPixels(UShort_t numconnected, UShort_t maxid)
+{
+    //const int npix = fRunHeader->GetNumCrates()*fRunHeader->GetNumPixInCrate();
+    if (fHiGainPixId && fHiGainPixId->GetSize()==numconnected && (UShort_t)fABFlags->GetSize()==(maxid/8+1))
+    {
+        fConnectedPixels = 0;
+        return;
+    }
+
+    DeleteArrays();
+    InitArrays(numconnected, maxid);
+}
+
+void MRawEvtData::ResetPixels()
+{
+    if (!fRunHeader)
+        return;
+
+    // FIXME: Better give NumNormalPixels if numconnected==0 ?
+
+    ResetPixels(fRunHeader->GetNumNormalPixels(), fRunHeader->GetNumNormalPixels()-1);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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
+//
+void MRawEvtData::AddPixel(UShort_t nOfPixel, const TArrayC &data)
+{
+    const Int_t n = fRunHeader->GetNumSamples();
+    if (data.GetSize()!=n)
+    {
+        *fLog << err << "RawEvtData::AddPixel: Error, number of samples in ";
+        *fLog << "TArrayC " << data.GetSize() << " doesn't match current number " << n << endl;
+        return;
+    }
+
+    //
+    // enhance pixel array by one
+    //
+    fHiGainPixId->Set(fHiGainPixId->GetSize()+1);
+
+    //
+    // add the number of the new pixel to the array as last entry
+    //
+    fHiGainPixId->AddAt(nOfPixel, fHiGainPixId->GetSize()-1);
+
+    //
+    // enhance the array by the number of new samples
+    //
+    fHiGainFadcSamples->Set(fHiGainFadcSamples->GetSize()+n);
+
+    //
+    // add the new slices as last entries to array
+    //
+    fHiGainFadcSamples->AddAt((Byte_t*)data.GetArray(), fHiGainFadcSamples->GetSize()-n, n);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the contents of the MArrayI to the fHiGainFadcSamples
+// One Integer is added to one sample in the array.
+//
+void MRawEvtData::Set(const MArrayI &data)
+{
+    fConnectedPixels = fHiGainPixId->GetSize();
+
+    UInt_t n = fConnectedPixels*fRunHeader->GetNumSamplesHiGain();
+    if (n!=data.GetSize())
+    {
+        *fLog << err << "MRawEvtData::Set: Size mismatch." << endl;
+        *fLog << " fConnectedPixels="   << fConnectedPixels << endl;
+        *fLog << " NumHiGainSamples="   << fRunHeader->GetNumSamplesHiGain() << endl;
+        *fLog << " data.GetSize()="     << data.GetSize() << endl;
+        return;
+    }
+
+    Byte_t *dest = fHiGainFadcSamples->GetArray();
+
+    UInt_t *src  = reinterpret_cast<UInt_t*>(data.GetArray());
+    UInt_t *end  = reinterpret_cast<UInt_t*>(data.GetArray()) + n;
+
+    switch (fNumBytesPerSample)
+    {
+    case 1:
+        {
+            Byte_t *ptr = reinterpret_cast<Byte_t*>(dest);
+            while (src<end)
+                *ptr++ = Byte_t(*src++);
+        }
+        return;
+
+    case 2:
+        {
+            UShort_t *ptr = reinterpret_cast<UShort_t*>(dest);
+            while (src<end)
+                *ptr++ = UShort_t(*src++);
+        }
+        return;
+
+    case 4:
+        memcpy(dest, data.GetArray(), n*4);
+        return;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set indices according to the given array. The array must have the same
+// size as fHiGainPixId
+//
+void MRawEvtData::SetIndices(const MArrayS &idx)
+{
+    if (idx.GetSize()!=fHiGainPixId->GetSize())
+        return;
+
+    for (UInt_t i=0; i<fHiGainPixId->GetSize(); i++)
+        (*fHiGainPixId)[i] = idx[i]-1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set indices according to the length of the array fHiGainPixId
+// from 0 to n-1
+//
+void MRawEvtData::SetIndices()
+{
+    for (UInt_t i=0; i<fHiGainPixId->GetSize(); i++)
+        (*fHiGainPixId)[i] = i;
+}
+
+Byte_t   *MRawEvtData::GetSamples() const    { return fHiGainFadcSamples->GetArray(); }
+UShort_t *MRawEvtData::GetStartCells() const { return fStartCells->GetArray(); }
+UShort_t *MRawEvtData::GetPixelIds() const   { return fHiGainPixId->GetArray(); }
+Bool_t    MRawEvtData::HasStartCells() const { return fStartCells->GetSize()==fHiGainPixId->GetSize(); }
+
+/*
+void MRawEvtData::AddPixel(UShort_t nOfPixel, TArrayC *data, Bool_t lflag)
+{
+    MArrayS *arrpix = lflag ? fLoGainPixId       : fHiGainPixId;
+    MArrayB *arrsam = lflag ? fLoGainFadcSamples : fHiGainFadcSamples;
+
+    //
+    // check whether we got the right number of new samples
+    // if there are no samples already stored: this is the new number of samples
+    //
+    const UShort_t ns    = data->GetSize();
+    const UShort_t nSamp = lflag ? GetNumLoGainSamples() : GetNumHiGainSamples();
+    if (nSamp && ns!=nSamp)
+    {
+        *fLog << err << "RawEvtData::AddPixel: Error, number of samples in ";
+        *fLog << "TArrayC " << ns << " doesn't match current number " << nSamp << endl;
+        return;
+    }
+
+    //
+    // enhance pixel array by one
+    //
+    arrpix->Set(arrpix->GetSize()+1);
+
+    //
+    // add the number of the new pixel to the array as last entry
+    //
+    arrpix->AddAt(nOfPixel, arrpix->GetSize()-1);
+
+    //
+    // enhance the array by the number of new samples
+    //
+    arrsam->Set(arrsam->GetSize()+ns);
+
+    //
+    // add the new slices as last entries to array
+    //
+    arrsam->AddAt((Byte_t*)data->GetArray(), arrsam->GetSize()-ns, ns);
+}
+*/
+
+void MRawEvtData::ReadPixel(istream &fin, Int_t npix)
+{
+    // number of samples
+    const UInt_t ns = fRunHeader->GetNumSamples();
+
+    // bytes per sample
+    const Int_t bps = fRunHeader->GetNumBytesPerSample();
+
+    // Number of bytes
+    const Int_t nb = ns*bps;
+
+    // position in higain array
+    Byte_t *pos = fHiGainFadcSamples->GetArray() + fConnectedPixels*nb;
+
+    // Set pixel index
+    fHiGainPixId->AddAt(npix, fConnectedPixels++);
+
+    // Read data for one pixel
+    fin.read((char*)pos, nb);
+}
+
+void MRawEvtData::SetABFlag(Int_t npix, Bool_t ab)
+{
+    if (ab)
+        SETBIT((*fABFlags)[npix/8], npix%8);
+    else
+        CLRBIT((*fABFlags)[npix/8], npix%8);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills members with information from a magic binary file.
+//   WARNING: you have to use Init() before you can do this
+//
+/*
+void MRawEvtData::ReadEvt(istream &fin, Int_t posinarray)
+{
+
+    const UShort_t npic = fRunHeader->GetNumPixInCrate();
+
+    const UShort_t npos = npic*posinarray;
+
+    //const Byte_t ab = fCrateArray->GetEntry(posinarray)->GetABFlags();
+
+    for (int i=npos; i<npic+npos; i++)
+    {
+        // calc the spiral hardware pixel number
+        const UShort_t ipos = i;
+
+        // Get Hardware Id
+        const Short_t hwid = fRunHeader->GetPixAssignment(ipos);
+
+        // Check whether the pixel is connected or not
+        if (hwid==0)
+        {
+            const UShort_t n = fRunHeader->GetNumSamplesLoGain()+fRunHeader->GetNumSamplesHiGain();
+            fin.seekg(n, ios::cur);
+            return;
+        }
+
+        // -1 converts the hardware pixel Id into the software pixel index
+        const Int_t npix = (Int_t)hwid-1;
+
+        const Byte_t ab = fCrateArray->GetEntry(posinarray)->GetABFlags();
+        AddPixel(fin, npix, TESTBIT(ab, i-npos));
+    }
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Return the size in bytes of one event data block
+//
+Int_t MRawEvtData::GetNumBytes() const
+{
+    const UShort_t nlo  = fRunHeader->GetNumSamplesLoGain();
+    const UShort_t nhi  = fRunHeader->GetNumSamplesHiGain();
+    const UShort_t npic = fRunHeader->GetNumPixInCrate();
+    const UShort_t nbps = fRunHeader->GetNumBytesPerSample();
+
+    return (nhi+nlo)*npic*nbps;
+}
+
+// --------------------------------------------------------------------------
+//
+// Make sure, that you skip the whole event. This function only skips a part
+// of the event - see MRawRead::SkipEvent
+//
+void MRawEvtData::SkipEvt(istream &fin)
+{
+    fin.seekg(GetNumBytes(), ios::cur);
+}
+
+Bool_t MRawEvtData::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    *fLog << warn << "WARNING - The use of MRawEvtData::GetPixelContent is deprecated!" << endl;
+
+    /*
+    MRawEvtPixelIter Next(const_cast<MRawEvtData*>(this));
+    if (!Next.Jump(idx))
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+        val = Next.GetSumHiGainSamples()-(float)GetNumHiGainSamples()*fHiGainFadcSamples->GetArray()[0];
+        val*= cam.GetPixRatio(idx);
+        break;
+    case 1:
+        val = Next.GetMaxHiGainSample();
+        break;
+    case 2:
+        val = Next.GetMaxLoGainSample();
+        break;
+    case 3:
+        val = Next.GetIdxMaxHiGainSample();
+        break;
+    case 4:
+        val = Next.GetIdxMaxLoGainSample();
+        break;
+    case 5:
+        val = Next.GetIdxMaxHiLoGainSample();
+        return val >= 0;
+    }
+*/
+    return kTRUE;
+}
+
+void MRawEvtData::Copy(TObject &named)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+{
+    MRawEvtData &evt = (MRawEvtData &)named;
+
+    *evt.fHiGainPixId = *fHiGainPixId;
+    *evt.fLoGainPixId = *fLoGainPixId;
+
+    *evt.fHiGainFadcSamples = *fHiGainFadcSamples;
+    *evt.fLoGainFadcSamples = *fLoGainFadcSamples;
+
+    *evt.fABFlags = *fABFlags;
+
+    evt.fConnectedPixels = fConnectedPixels;
+
+    evt.fNumBytesPerSample = fNumBytesPerSample;
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawEvtData.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawEvtData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawEvtData.h	(revision 17960)
@@ -0,0 +1,136 @@
+#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>
+#include <stdint.h>
+
+class MRawRunHeader;
+class MRawCrateArray;
+
+class TArrayC;
+class MArrayS;
+class MArrayB;
+class MArrayI;
+
+class MRawEvtData : public MParContainer, public MCamEvent
+{
+    friend class MRawEvtPixelIter;
+private:
+    MRawRunHeader  *fRunHeader;   //! provides information about numbers
+
+    // FIXME: COMMENT ABOUT ORDERING
+
+    MArrayS *fHiGainPixId;        //-> list of pixel IDs of hi gain channel
+    MArrayB *fHiGainFadcSamples;  //-> list of hi gain samples of all pixels (ordering: see fHiGainPixId) {fits: unit=mV ; name=Data }
+
+    MArrayS *fLoGainPixId;        //-> list of pixel IDs of lo gain channel
+    MArrayB *fLoGainFadcSamples;  //-> list of lo gain samples of all pixels (ordering: see fLoGainPixId)
+
+    MArrayB *fABFlags;            //-> A information about the exact trigger position
+    MArrayS *fStartCells;         // {fits: unit=uint16 ; name=StartCellData }
+
+    UShort_t fTriggerType;       // {fits: unit=uint16 ; name=TriggerType }
+
+    UShort_t fNumBytesPerSample;
+
+    Bool_t fIsSigned;
+
+    Int_t fConnectedPixels;       //!
+
+    void InitArrays(UShort_t numconnected=0, UShort_t maxid=0);
+    void DeleteArrays();
+
+    Int_t GetNumBytes() const;
+
+    Long_t GetSample(const void *ptr, Int_t n) // Helper for Draw
+    {
+        fIsSigned = kTRUE;
+        switch (fNumBytesPerSample)
+        {
+        case 1: return fIsSigned ? (Long_t)reinterpret_cast<const Char_t*>(ptr)[n]  : (Long_t)reinterpret_cast<const Byte_t*>(ptr)[n];
+        case 2: return fIsSigned ? (Long_t)reinterpret_cast<const Short_t*>(ptr)[n] : (Long_t)reinterpret_cast<const UShort_t*>(ptr)[n];
+        case 4: return fIsSigned ? (Long_t)reinterpret_cast<const Int_t*>(ptr)[n]   : (Long_t)reinterpret_cast<const UInt_t*>(ptr)[n];
+        }
+        return 0;
+    }
+
+
+public:
+    MRawEvtData(const char *name=NULL, const char *title=NULL);
+    ~MRawEvtData();
+
+    void InitRead(MRawRunHeader *rh)
+    {
+        //
+        // you have to set this before you can read information
+        // from a magic binary file
+        //
+        fRunHeader  = rh;
+    }
+
+    void Clear(Option_t * = NULL);
+    void Print(Option_t * = NULL) const;
+    void Draw (Option_t * = NULL);
+
+    void ResetPixels();
+    void ResetPixels(UShort_t npix, UShort_t maxid);
+    void InitStartCells();
+    void AddPixel(UShort_t nOfPixel, const TArrayC &data);
+    void Set(const MArrayI &data);
+    void SetIndices(const MArrayS &idx);
+    void SetIndices();
+
+    UShort_t GetNumHiGainSamples() const;
+    UShort_t GetNumLoGainSamples() const;
+    UInt_t   GetNumSamples() const { return GetNumHiGainSamples()+GetNumLoGainSamples(); }
+    UShort_t GetNumPixels() const;
+
+    UShort_t GetNumBytesPerSample() const { return fNumBytesPerSample; }
+    UInt_t   GetScale() const { return 1<<((fNumBytesPerSample-1)*8); }
+    Long_t   GetMin() const   { return fIsSigned ? -GetMax()-1 : 0; }
+    Long_t   GetMax() const   {
+        switch (fNumBytesPerSample)
+        {
+        case 1: return fIsSigned ?       0x7f :       0xff;
+        case 2: return fIsSigned ?     0x7fff :     0xffff;
+        case 4: return fIsSigned ? 0x7fffffff : 0xffffffff;
+        }
+    return 0;
+    }
+    Byte_t   *GetSamples() const;
+    UShort_t *GetStartCells() const;
+    UShort_t *GetPixelIds() const;
+
+    Bool_t HasStartCells() const;
+
+    void ReadPixel(std::istream &fin, Int_t npix);
+    void SetABFlag(Int_t npix, Bool_t ab);
+    void SkipEvt(std::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, 8) //Container to store the raw Event Data
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawEvtHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawEvtHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawEvtHeader.cc	(revision 17960)
@@ -0,0 +1,471 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRawEvtHeader 
+//    
+// One Event is a sample of FADC measurements of different Pixels 
+// (Photomultipliers) from the Camera of MAGIC. So all data (FADC) of the 
+// interesting pixels are the modules of an event. To describe pixels the 
+// class MRawPixel is used and the class MRawCrate to describe Crates.
+// To define a single events some other data members are needed 
+// (Time of the events, tirgger pattern of event..)
+// 
+// To describe one event on the level of FADC values the Class MRawEvtHeader is
+// created. It has the following data members: 
+//
+// UInt_t    fDAQEvtNumber
+// -----------------------
+// This it the number of the Event in one 
+// data run. The first event in this run get
+// the number zero. The next one is one bigger.
+//
+// Assuming that one run takes 1 hour and a
+// triggerrate of 1kHz the number must be able
+// to reach 3.6e6 Events. To reach this number
+// you need at least 22 bits. This is the reason
+// why we use an integer (of root type UInt_t)
+// with a range to 4.2e9. 
+//
+// MTime   fRawEvtTime
+// -------------------
+// Time of the event. 
+// The start point of the time determination can be
+// the millenium. From that start point the time is
+// measured in 200ns-count. One day for example
+// contains 432.e9 counts. An array of two unsigned Int is able to 
+// contain 1.8e19 200ns-counts. This corresponds to 41.e6
+// days. This should be more than the livetime of MAGIC.
+// Private member of MTime.h
+//
+// UInt_t  fNumTrigLvl1
+// --------------------
+//
+// Number of first level trigger
+// This member counts the number of First Level Trigger
+// between the last and this event. May be that due to 
+// dead time of the DAQ this number is different from 1.
+// If the DAQ is fast enough, this value should be 1. 
+// This may be usefull in GammaRayBursts and if we 
+// apply a data reduction in the DAQ-chain, which selects
+// only good events. 
+//
+// UInt_t  fNumTrigLvl2
+// --------------------
+//
+// Number of second level trigger
+// This member counts the number of Second Level Trigger
+// between the last and this event. 
+//
+// UInt_t  fTrigPattern[0]
+// -----------------------
+// Trigger Pattern used for this event
+// Each event triggers for a particular configuration and each  
+// configuration should have an ID (which is not fixed yet).
+//
+// UInt_t  fCalibPattern == fTrigPattern[1]  
+// -----------------------
+// Calibration Pattern used for this event
+// Each (calibration) event uses a particular LEDs configuration and 
+// particular strength and colour of the continunous light.
+// Bits 1-16: Pulser slot pattern: 16 LEDs slots.
+// Bits 17: CT1 Pulser
+// Bits 21-24: Colour of Continous light source:
+// Bits 25-32: Strength of continuous light source: 256 level
+//
+// UShort_t fAllLowGainOn
+// ----------------------
+// Type of Trigger. 
+// This is a Byte (8 bit) to indicated if any of the pixels 
+// have a non-negligible low gain (1) or not (0)
+//
+// Class Version 2:
+// ---------------
+//  - added fCalibPattern
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRawEvtHeader.h"
+
+#include <fstream>
+
+#include <TArrayC.h>
+
+#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)
+    : fTime(0), fNumTrigLvl1(0), fNumTrigLvl2(0), fNumLoGainOn(0), fPixLoGainOn(0)
+{
+    fName  = name  ? name  : "MRawEvtHeader";
+    fTitle = title ? title : "Raw Event Header Information";
+
+    //
+    //   set all member to zero, init the pointer to ClonesArray,
+    //
+    fPixLoGainOn = new MArrayB;
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes the array to store pixlogainon
+//
+MRawEvtHeader::~MRawEvtHeader()
+{
+    delete fPixLoGainOn;
+}
+
+// --------------------------------------------------------------------------
+//
+// you have to init the conatainer before you can read from
+// a raw binary file
+//
+void MRawEvtHeader::InitRead(MRawRunHeader *rh, MTime *t)
+{
+    //
+    // this is the number of entries in the array like specification
+    //
+    UInt_t fN = (rh->GetNumCrates() * rh->GetNumPixInCrate() + 7) / 8;
+
+    //
+    // initialize the array
+    //
+    fPixLoGainOn->Set(fN);
+
+    //
+    // this is the conatiner where we have to store the time of the event we
+    // read from the input stream
+    //
+    fTime = t;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Implementation of the Clear function
+//
+//   Resets all members to zero, clear the list of Pixels
+//
+void MRawEvtHeader::Clear(Option_t *)
+{
+    fDAQEvtNumber   = 0;
+    fNumTrigLvl1    = 0;
+    fNumTrigLvl2    = 0;
+    fTrigPattern[0] = 0;
+    fTrigPattern[1] = 0;
+    fTrigType       = 0;
+    fNumLoGainOn    = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This member function prints all Data of one Event to *fLog.
+//
+void MRawEvtHeader::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << "DAQEvtNr: " << dec << fDAQEvtNumber << "  (";
+    *fLog << "Trigger: ";
+    *fLog << "NumLvl1=" << fNumTrigLvl1 << " ";
+    *fLog << "NumLvl2=" << fNumTrigLvl2 << " ";
+    *fLog << "Pattern=" << hex << setfill('0');
+    *fLog << setw(8) << fTrigPattern[0];
+    *fLog << setw(8) << fTrigPattern[1] << " " << dec;
+
+    *fLog << "Type=";
+    switch (fTrigType)
+    {
+    case 0:
+        *fLog << "Trigger";
+        break;
+    case 1:
+        *fLog << "Pedestal";
+        break;
+    case 2:
+        *fLog << "Calibration";
+        break;
+    case 3:
+        *fLog << "PinDiode";
+        break;
+    }
+    *fLog << ")" << endl;
+    *fLog << "Number of Lo Gains On: " << fNumLoGainOn << endl;
+
+    TString str(o);
+    str.ToLower();
+
+    if (str.Contains("nogains"))
+        return;
+
+    for (unsigned int i=0; i<fPixLoGainOn->GetSize(); i++)
+    {
+        for (int j=0; j<8; j++)
+        {
+            const UInt_t on = (*fPixLoGainOn)[i]&(1<<j) ? 1 : 0;
+            *fLog << on;
+        }
+    }
+    if (fPixLoGainOn->GetSize())
+        *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the size in bytes of the event header.
+//
+Int_t MRawEvtHeader::GetNumBytes() const
+{
+    return 36+fPixLoGainOn->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Used to set the header information. This is for MC only. NEVER, NEVER
+// use this somewhere else!
+//
+void MRawEvtHeader::FillHeader(UInt_t uiN, Float_t ulTP)
+{
+    fDAQEvtNumber = uiN;
+    fTrigPattern[0] = (UInt_t)(ulTP/4294967296.0) ;
+    fTrigPattern[1] = (UInt_t)(ulTP-fTrigPattern[0]*4294967296.0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Decode the binary Time Stamp. For more detailed information see the
+// source code.
+//
+Bool_t MRawEvtHeader::DecodeTime(const UInt_t tm[2], UShort_t ver) const
+{
+    //
+    // SuperSecond (20 bits giving hh:mm:ss)
+    // ------------
+    // 
+    // Reading the hours:
+    // Swap bits: 23->16, 22->17, 21->16, 20->19
+    //
+    UInt_t abstime[2] = { tm[0], tm[1] };
+
+    abstime[0] =
+        (abstime[0]>>7 & 0x00010000) |
+        (abstime[0]>>5 & 0x00020000) |
+        (abstime[0]>>3 & 0x00040000) |
+        (abstime[0]>>1 & 0x00080000) |
+        (abstime[0]    & 0xff00ffff);
+
+    // 
+    // SubSecond (24 bits giving number of clock ticks of a 5Mhz signal since 
+    // the beginning of last second, i.e., number of ns with a precision of to
+    // 200 ns) 
+    // ----------
+    //
+    // The last 8 bits must be flipped.
+    //
+    abstime[1] ^= 0x000000ff;
+
+    //
+    // Due to a problem with one Digital Module, three of the less significant
+    // eight bits of the subsecond are corrupted. So, until new DM's arrive to
+    // La Palma, we won't use the eight first bits of the subsecond. 
+    // This reduces the precision from 200 ns to of 51.2 us. (ver<5)
+    //
+    if (ver<5)
+        abstime[1] &= 0xffffff00;
+
+    //
+    // Decode Time Stamp
+    //
+    const Byte_t h  = (abstime[0]>>18 & 0x3)*10 + (abstime[0]>>14 & 0xf);
+    const Byte_t m  = (abstime[0]>>11 & 0x7)*10 + (abstime[0]>> 7 & 0xf);
+    const Byte_t s  = (abstime[0]>> 4 & 0x7)*10 + (abstime[0]>> 0 & 0xf);
+    const UInt_t ns =  abstime[1]*200;
+
+    //
+    // Update the time stamp with the current event time.
+    // Make sure, that the time stamp was initialized correctly
+    // with the start-date/time of the run (after reading the run header)
+    //
+    if (fTime->UpdMagicTime(h, m, s, ns))
+        return kTRUE;
+
+    *fLog << warn << "WARNING - Time (" << Form("%2d:%02d:%02d,%09d", h, m, s, ns);
+    *fLog << ") in header of event #" << dec << fDAQEvtNumber << " invalid..." << endl;
+ 
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// read the EVENT HEADER information from the input stream
+// return FALSE if there is now header anymore, else TRUE
+//
+// For version>2 we expect to have a valid time-stamp in the files.
+//
+// Updates the time stamp with the current event time.
+// Make sure, that the time stamp was initialized correctly
+// with the start-date/time of the run (after reading the run header)
+//
+// Remark: This 'feature' disallows single runs of more than 11h!
+//
+Int_t MRawEvtHeader::ReadEvtOld(istream &fin, UShort_t ver)
+{
+    Int_t rc = kTRUE;
+
+    fin.read((char*)&fDAQEvtNumber, 4);  // Total=4
+    if (!fin)
+        return kFALSE;
+
+    UInt_t abstime[2];
+    fin.read((char*)abstime,        8);  // Total=12
+
+    if (ver>2)
+        if (!DecodeTime(abstime, ver))
+            rc = kCONTINUE;
+
+    Byte_t dummy[4];
+    fin.read((char*)&fNumTrigLvl1,  4);  // Total=16
+    fin.read((char*)&fNumTrigLvl2,  4);  // Total=20
+    fin.read((char*)fTrigPattern,   8);  // Total=28
+    fin.read((char*)&fTrigType,     2);  // Total=30
+    if (ver<=6)
+    {
+        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);
+    }
+    else
+    {
+        // No LoGains for version 7 data
+        fPixLoGainOn->Reset();
+        fNumLoGainOn = 0;
+    }
+
+    return fin.eof() ? kFALSE : rc;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MRawEvtHeader::ReadEvt(istream &fin, UShort_t ver, UInt_t size)
+{
+    if (ver<11)
+        return ReadEvtOld(fin, ver);
+
+    if (size==0)
+    {
+        *fLog << err << "ERROR - Event header size unknown." << endl;
+        return kFALSE;
+    }
+
+    if (size<32)
+    {
+        *fLog << err << "ERROR - Event header too small (<32b)." << endl;
+        return kFALSE;
+    }
+
+    TArrayC h(size);
+    fin.read(h.GetArray(), h.GetSize());
+    if (!fin)
+        return kFALSE;
+
+    // ----- convert -----
+    //const Byte_t  *Char  = reinterpret_cast<Byte_t* >(h.GetArray());
+    const UInt_t  *Int   = reinterpret_cast<UInt_t* >(h.GetArray());
+    //const Float_t *Float = reinterpret_cast<Float_t*>(h.GetArray());
+
+    fDAQEvtNumber   = Int[0];
+    // Decode Time
+    fNumTrigLvl1    = Int[3];
+    fNumTrigLvl2    = Int[4];
+    fTrigPattern[0] = Int[5];
+    fTrigPattern[1] = Int[6];
+    fTrigType       = Int[7];
+
+    // No LoGains for version 7 data
+    fPixLoGainOn->Reset();
+    fNumLoGainOn = 0;
+
+    return DecodeTime(Int+1, ver) ? kTRUE : kCONTINUE;
+}
+
+void MRawEvtHeader::SkipEvt(istream &fin, UShort_t ver)
+{
+    fin.seekg(GetNumBytes(), ios::cur);
+}
+
+// --------------------------------------------------------------------------
+//
+//   Low level decoding of the trigger pattern.
+//   The trigger pattern consists of 16 bits (8+8 bits) generated by the 
+//   trigger system.
+//   The first 8 bits correspond to the trigger configuration before the
+//   prescaling, the others after prescaling.
+//   The meaning of the configuration depends on the chosen trigger table
+//   (that is how the trigger has been programmed) and must be interpreted 
+//    at higher level by the analysis. 
+//   Bit structure:
+//          not prscd | prscaled
+//           xxxx xxxx xxxx xxxx    <-- pattern (x=0,1)
+//     bit   7654 3210 7654 3210
+//          H                   L
+//
+//    e.g.   1000 0000 1000 1000 (hex: 8080) is the pattern when no
+//         L2 trigger selection and no prescaling is applied. 
+//       
+//    Up to now only fTrigPattern[0] is used.
+//
+UInt_t MRawEvtHeader::GetTriggerID() const
+{
+    return fTrigPattern[0];
+}
+
+UInt_t MRawEvtHeader::GetCalibrationPattern() const
+{
+    return fTrigPattern[1];
+}
+
+UInt_t MRawEvtHeader::GetPulserSlotPattern() const
+{
+    return (fTrigPattern[1] >> 16) & 0x1ffff;
+}
+
Index: branches/Mars_McMismatchStudy/mraw/MRawEvtHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawEvtHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawEvtHeader.h	(revision 17960)
@@ -0,0 +1,114 @@
+#ifndef MARS_MRawEvtHeader
+#define MARS_MRawEvtHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MTime;
+class MArrayB;
+class MRawRunHeader;
+
+class MRawEvtHeader : public MParContainer
+{
+public:
+    //
+    // Trigger Type (TT)
+    /*
+    enum {
+        kTTEvent       = 0,
+        kTTPedestal    = 1,
+        kTTCalibration = 2,
+        kTTPinDiode    = 3
+    };
+    */
+    enum CLColor_t 
+      {
+        kCLUV       = BIT(0),
+        kCLGreen    = BIT(1),
+        kCLAmber    = BIT(2),
+        kCLRed      = BIT(3),
+        kCLRedAmber   = kCLRed & kCLAmber,
+        kCLRedGreen   = kCLRed & kCLGreen,
+        kCLRedUV      = kCLRed & kCLUV   ,
+        kCLAmberGreen = kCLAmber & kCLGreen,
+        kCLAmberUV    = kCLAmber & kCLUV   ,
+        kCLGreenUV    = kCLGreen & kCLUV   ,
+        kCLRedAmberGreen = kCLRedAmber & kCLGreen,
+        kCLRedGreenUV    = kCLRedGreen & kCLUV,
+        kCLAmberGreenUV  = kCLAmberGreen & kCLUV,
+        kCLAll           = kCLRedAmberGreen & kCLUV
+      };
+    
+
+private:
+    MTime   *fTime;            //! object to store the time in (ReadEvt)
+
+    UInt_t   fDAQEvtNumber;    // Number of Event {fits: name=EventNum ; unit=uint32}
+
+    UInt_t   fNumTrigLvl1;     // Number of 1st level tiggers between 2 events
+                               // Used in MSimTrigger for the index of the trigger channel
+    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(const UInt_t abstime[2], UShort_t ver) const;
+
+    Int_t GetNumBytes() const;
+
+    Int_t ReadEvtOld(std::istream& fin, UShort_t ver);
+
+public:
+    MRawEvtHeader(const char *name=NULL, const char *title=NULL);
+    ~MRawEvtHeader();
+
+    // MRawEvtHeader
+    void InitRead(MRawRunHeader *rh, MTime *t);
+
+    // Getter
+    UShort_t GetTrigType() const     { return fTrigType; }
+    UInt_t   GetNumTrigLvl1() const  { return fNumTrigLvl1; }
+    UInt_t   GetNumTrigLvl2() const  { return fNumTrigLvl2; }
+    UInt_t   GetDAQEvtNumber() const { return fDAQEvtNumber; }
+    
+    UInt_t   GetTriggerID() const;
+    UInt_t   GetCalibrationPattern() const;
+    UInt_t   GetPulserSlotPattern()  const;
+
+    // Setter (ONLY for Monte Carlo purpose)
+    void FillHeader(UInt_t, Float_t=0);
+
+    void  SetTriggerPattern( const UInt_t pattern )  {  fTrigPattern[0] = pattern; }
+    void  SetCalibrationPattern( const UInt_t pattern )  {  fTrigPattern[1] = pattern; }
+    void  SetDAQEvtNumber(const UInt_t n) { fDAQEvtNumber = n; }
+    void  SetNumTrigLvl1(UInt_t num) { fNumTrigLvl1 = num; }
+
+    // TObject
+    void Clear(Option_t * = NULL);
+    void Print(Option_t * = NULL) const;
+
+    // I/O
+    Int_t ReadEvt(std::istream& fin, UShort_t ver, UInt_t size);
+    void  SkipEvt(std::istream& fin, UShort_t ver);
+
+    ClassDef(MRawEvtHeader, 1) // Parameter Conatiner for raw EVENT HEADER
+}; 
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawEvtPixelIter.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawEvtPixelIter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawEvtPixelIter.cc	(revision 17960)
@@ -0,0 +1,170 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Markus Gaus 10/2002 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////////
+//
+//  MRawEvtPixelIter
+//
+//  class to iterate over all pixels of one event.
+//  The calling is similar to a root iterator:
+//  
+//  MRawEvtData *evtdata;            // must be filled with data from somewhere
+//  MRawEvtPixelIter pixel(evtdata); // evtdata: ptr to event you want to iterate
+//
+//  while (pixel.Next())
+//  {
+//     // here you can access the actual time slices by using
+//     //   pixel.GetPixelId();
+//     //   pixel.GetHiGainFadcSamples()[i]; // i is the number of the slice
+//     //   pixel.HasLoGain();               // check if pixel has
+//     //   pixel.GetLoGainFadcSamples()[i]; // i is the number of the slice
+//
+//     // WARNING: Don't acces more time slices than available.
+//     //   Get the numbers by calling: evtdata->GetNum[Lo,Hi]GainSamples()
+//     //   This number is constant for one event
+//  }
+//
+///////////////////////////////////////////////////////////////////////////////
+#include "MRawEvtPixelIter.h"
+
+#include <TArrayC.h>
+
+#include "MRawEvtData.h"
+
+#include "MArrayS.h"
+#include "MArrayB.h"
+
+ClassImp(MRawEvtPixelIter);
+
+using namespace std;
+
+MRawEvtPixelIter::MRawEvtPixelIter(MRawEvtData *dat) :
+    fABFlags(0), fStartCell(0), fData(dat)
+{
+    fNumBytesHiGain  = dat->GetNumHiGainSamples()*dat->GetNumBytesPerSample();
+    fNumBytesLoGain  = dat->GetNumLoGainSamples()*dat->GetNumBytesPerSample();
+
+    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;
+
+    //
+    // For old MC data which stores hi- and lo-gain in two arrays
+    // we have to use the old algorithm
+    //
+    if (fData->fLoGainPixId->GetSize())
+    {
+        fNumHiGainEntry++;
+        fHiGainId++;
+        fHiGainPos += fNumBytesHiGain;
+
+        fNumLoGainEntry++;
+        fLoGainId++;
+        fLoGainPos += fNumBytesLoGain;
+    }
+    else
+    {
+        fNumLoGainEntry = ++fNumHiGainEntry;
+        fLoGainId       = ++fHiGainId;
+
+        fHiGainPos     += fNumBytesHiGain+fNumBytesLoGain;
+        fLoGainPos      = fHiGainPos + fNumBytesHiGain;
+
+        fStartCell++;
+    }
+
+
+    //
+    // 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;
+    fABFlags  = fData->fABFlags->GetSize()==0 ? 0 : fData->fABFlags->GetArray();
+
+    //
+    // For old MC data which stores hi- and lo-gain in two arrays
+    // we have to use the old algorithm
+    //
+    if (fData->fLoGainPixId->GetSize())
+    {
+        fLoGainId  = fData->fLoGainPixId->GetArray();
+        fHiGainPos = fData->fHiGainFadcSamples->GetArray()-fNumBytesHiGain;
+        fLoGainPos = fData->fLoGainFadcSamples->GetArray()-fNumBytesLoGain;
+    }
+    else
+    {
+        fLoGainId  = fHiGainId;
+        fLoGainPos = fHiGainPos+fNumBytesHiGain;
+        fHiGainPos = fData->fHiGainFadcSamples->GetArray()-(fNumBytesHiGain+fNumBytesLoGain);
+    }
+
+    fStartCell = fData->fStartCells->GetSize() ? fData->GetStartCells()-1 : 0;
+
+    //
+    // 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));
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawEvtPixelIter.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawEvtPixelIter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawEvtPixelIter.h	(revision 17960)
@@ -0,0 +1,122 @@
+#ifndef MARS_MRawEvtPixelIter
+#define MARS_MRawEvtPixelIter
+///////////////////////////////////////////////////////////////////////////////
+//
+//  MRawEvtPixelIter
+//
+//  class to iterate over all pixels of one event.
+//
+///////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class MRawEvtData;
+
+class MRawEvtPixelIter : public TObject
+{
+private:
+    UShort_t  fNumHiGainEntry;  //! actual number of entry in fHiGainPixId
+    UShort_t  fNumLoGainEntry;  //! actual number of entry in fLoGainPixId
+
+    UShort_t *fHiGainId;        //! actual entry of fHiGainPixId
+    UShort_t *fLoGainId;        //! actual entry of fLoGainPixId
+
+    Byte_t   *fHiGainPos;       //! pointer to hi-gain samples of actual pixel
+    Byte_t   *fLoGainPos;       //! pointer to lo-gain samples of actual pixel
+
+    Byte_t   *fABFlags;         //! pointer to AB flags
+    UShort_t *fStartCell;      //! pointer to AB flags
+
+    UShort_t  fNumEntry;
+
+    UInt_t fNumBytesHiGain;   //!
+    UInt_t fNumBytesLoGain;   //!
+
+    UShort_t fNumBytesPerSample; //!
+
+    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;
+    }
+
+    void *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;
+    }
+
+    UInt_t GetNumBytes() const { return fNumBytesHiGain+fNumBytesLoGain; }
+
+    Bool_t HasLoGain() const { return fNumBytesLoGain>0; }
+    Bool_t IsABFlagValid() const { return fABFlags ? kTRUE : kFALSE; }
+    Bool_t HasABFlag() const
+    {
+        //
+        // return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+        //
+        return TESTBIT(GetABFlag(), GetPixelId()%8);
+    }
+    Byte_t GetABFlag() const
+    {
+        //
+        // return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+        //
+        return fABFlags ? fABFlags[GetPixelId()/8] : 0;
+    }
+
+    void *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;
+    }
+
+    UShort_t GetStartCell() const
+    {
+        return fStartCell ? *fStartCell : 0;
+    }
+
+    void Reset();
+
+    void Draw(Option_t *t="GRAPH");
+
+    ClassDef(MRawEvtPixelIter, 0) // iterates over all pixels of one MRawEvtData object
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawFileRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawFileRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawFileRead.cc	(revision 17960)
@@ -0,0 +1,446 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRawFileRead
+//
+//  This tasks reads the raw binary file like specified in the TDAS???
+//  and writes the data in the corresponding containers which are
+//  either retrieved from the parameter list or created and added.
+//
+//  Use SetInterleave() if you don't want to read all events, eg
+//    SetInterleave(5) reads only each 5th event.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MRawRunHeader, MRawEvtHeader, MRawEvtData, MRawCrateArray, MRawEvtTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawFileRead.h"
+
+#include <errno.h>
+
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "izstream.h"
+#include "MTime.h"
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateData.h"
+#include "MRawCrateArray.h"
+
+ClassImp(MRawFileRead);
+
+using namespace std;
+
+/*  ----------- please don't delete and don't care about (Thomas) ------------
+#define kBUFSZ 64 //1024*1024*64
+#include <iomanip.h>
+class bifstream : public istream, public streambuf
+{
+private:
+    char fBuffer[kBUFSZ]; //!
+    FILE *fd;
+
+    int sync()
+    {
+        memset(fBuffer, 0, kBUFSZ);
+        return 0; 
+    }
+    int underflow()
+    {
+        int sz=fread(fBuffer, kBUFSZ, 1, fd);
+        //int sz=fread(fBuffer, 1, kBUFSZ, fd);
+        setg(fBuffer, fBuffer, fBuffer+kBUFSZ);
+
+        return sz==1 ? *(unsigned char*)fBuffer : EOF;//EOF;
+        //return sz==kBUFSZ ? *(unsigned char*)fBuffer : EOF;//EOF;
+    }
+public:
+    bifstream(const char *name) : istream(this)
+    {
+        fd = fopen(name, "rb");
+        setbuf(fBuffer, kBUFSZ);
+    }
+};
+*/
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawFileRead::MRawFileRead(const char *fname, const char *name, const char *title)
+    : fFileNames(NULL), fNumFile(0), fNumTotalEvents(0), fIn(NULL), fParList(NULL), fInterleave(1), fForce(kFALSE), fIsMc(kFALSE)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Read task to read DAQ binary files";
+
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname!=NULL)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream.
+//
+MRawFileRead::~MRawFileRead()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+Byte_t MRawFileRead::IsFileValid(const char *name)
+{
+    izstream fin(name);
+    if (!fin)
+        return 0;
+
+    Byte_t c[4];
+    fin.read((char*)c, 4);
+    if (!fin)
+        return 0;
+
+    if (c[0]!=0xc0)
+        return 0;
+
+    if (c[1]==0xc0)
+        return 1;
+
+    if (c[1]==0xc1)
+        return 2;
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new file to a list of files to be processed, Returns the number
+// of files added. (We can enhance this with a existance chack and
+// wildcard support)
+//
+Int_t MRawFileRead::AddFile(const char *fname, Int_t entries)
+{
+    TNamed *name = new TNamed(fname, "");
+    fFileNames->AddLast(name);
+    return 1;
+
+}
+
+istream *MRawFileRead::OpenFile(const char *filename)
+{
+    return new izstream(filename);
+}
+
+Bool_t MRawFileRead::ReadRunHeader(istream &fin)
+{
+    //
+    // Read RUN HEADER (see specification) from input stream
+    //
+    if (!fRawRunHeader->ReadEvt(fin))
+        if (!fForce)
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Int_t MRawFileRead::OpenNextFile(Bool_t print)
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existance of a next file to read
+    //
+    TObject *file = fFileNames->At(fNumFile);
+    if (!file)
+        return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const char *name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    fIn = OpenFile(expname);
+
+    const Bool_t noexist = !(*fIn);
+    if (noexist)
+    {
+        *fLog << err << "Cannot open file " << expname << ": ";
+        *fLog << (errno!=0?strerror(errno):"Insufficient memory for decompression") << endl;
+    }
+    else
+    {
+        *fLog << inf << "Open file: '" << name << "'" << endl;
+
+        if (fDisplay)
+        {
+            // Show the new file name and the event number after which
+            // the new file has been opened
+            TString txt = GetFileName();
+            txt += " @ ";
+            txt += GetNumExecutions()-1;
+            fDisplay->SetStatusLine2(txt);
+        }
+    }
+
+    delete [] expname;
+
+    if (noexist)
+        return kERROR;
+
+    fNumFile++;
+
+    MRawRunHeader h(*fRawRunHeader);
+
+    if (!ReadRunHeader(*fIn))
+        return kERROR;
+
+    if (!(*fIn))
+    {
+        *fLog << err << "Error: Accessing file '" << name << "'" << endl;
+        return kFALSE;
+    }
+
+    if (h.IsValidRun() && !fRawRunHeader->IsConsistent(h))
+    {
+        *fLog << err << "Error: Inconsistency between previous header and '" << name << "' found." << endl;
+        fRawRunHeader->Print();
+        return kERROR;
+    }
+
+    if (!print)
+        return kTRUE;
+
+    //
+    // Print Run Header
+    //
+    fRawRunHeader->Print("header");
+    *fRawEvtTime = fRawRunHeader->GetRunStart();
+
+    fNumEvents += fRawRunHeader->GetNumEvents();
+
+    fRawRunHeader->SetReadyToSave();
+
+    //
+    // Give the run header information to the 'sub-classes'
+    // Run header must be valid!
+    //
+    fRawEvtHeader->InitRead(fRawRunHeader, fRawEvtTime);
+    fRawEvtData1 ->InitRead(fRawRunHeader);
+    fRawEvtData2 ->InitRead(fRawRunHeader);
+
+    if (!InitReadData(*fIn))
+        return kERROR;
+
+    //
+    // Search for MTaskList
+    //
+    MTask *tlist = (MTask*)fParList->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << err << dbginf << "MTaskList not found... abort." << endl;
+        return kERROR;
+    }
+
+    //
+    // A new file has been opened and new headers have been read.
+    //  --> ReInit tasklist
+    //
+    return tlist->ReInit(fParList) ? kTRUE : kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return file name of current file.
+//
+TString MRawFileRead::GetFullFileName() const
+{
+    const TObject *file = fFileNames->At(fNumFile-1);
+    return file ? file->GetName() : "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Restart with the first file
+//
+Bool_t MRawFileRead::Rewind()
+{
+    fNumFile=0;
+    fNumEvents=0;
+    return OpenNextFile()==kTRUE;
+}
+
+Bool_t MRawFileRead::CalcNumTotalEvents()
+{
+    fNumTotalEvents = 0;
+
+    Bool_t rc = kTRUE;
+
+    while (1)
+    {
+        switch (OpenNextFile(kFALSE))
+        {
+        case kFALSE:
+            break;
+        case kERROR:
+            rc = kFALSE;
+            break;
+        case kTRUE:
+            fNumTotalEvents += fRawRunHeader->GetNumEvents();
+            continue;
+        }
+        break;
+    }
+
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MRawRunHeader <output>   if not found it is created
+//   MRawEvtHeader <output>   if not found it is created
+//   MRawEvtData <output>     if not found it is created
+//   MRawCrateArray <output>  if not found it is created
+//   MRawEvtTime <output>     if not found it is created (MTime)
+//
+// If all containers are found or created the run header is read from the
+// binary file and printed.  If the Magic-Number (file identification)
+// doesn't match we stop the eventloop.
+//
+// Now the EvtHeader and EvtData containers are initialized.
+//
+Int_t MRawFileRead::PreProcess(MParList *pList)
+{
+    fParList = pList;
+
+    //
+    // open the input stream
+    // first of all check if opening the file in the constructor was
+    // successfull
+    //
+    if (!MRawRead::PreProcess(pList))
+        return kFALSE;
+
+    *fLog << inf << "Calculating number of total events..." << flush;
+    if (!CalcNumTotalEvents())
+        return kFALSE;
+    *fLog << inf << " " << fNumTotalEvents << " found." << endl;
+
+    fNumFile=0;
+    fNumEvents=0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The Process reads one event from the binary file:
+//  - The event header is read
+//  - the run header is read
+//  - all crate information is read
+//  - the raw data information of one event is read
+//
+Int_t MRawFileRead::Process()
+{
+    while (1)
+    {
+        if (fIn)
+        {
+            //
+            // skip events if requested
+            //
+            if (fInterleave>1 && GetNumExecutions()%fInterleave>0 && fIn->peek()!=EOF)
+            {
+                SkipEvent(*fIn);
+                return kCONTINUE;
+            }
+
+            //
+            // Read a single event from file
+            //
+            const Bool_t rc = ReadEvent(*fIn);
+            if (rc!=kFALSE)
+                return rc;
+        }
+
+        //
+        // If an event could not be read from file try to open new file
+        //
+        const Int_t rc = OpenNextFile();
+        if (rc!=kTRUE)
+            return rc;
+    }
+    return kTRUE; 
+}
+
+// --------------------------------------------------------------------------
+//
+//  Close the file. Check whether the number of read events differs from
+//  the number the file should containe (MRawRunHeader). Prints a warning
+//  if it doesn't match.
+//
+Int_t MRawFileRead::PostProcess()
+{
+    //
+    // Sanity check for the number of events
+    //
+    if (fNumEvents==GetNumExecutions()-1 || GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << warn << dec;
+    *fLog << "Warning - number of read events (" << GetNumExecutions()-1;
+    *fLog << ") doesn't match number in run header(s) (";
+    *fLog << fNumEvents << ")." << endl;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawFileRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawFileRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawFileRead.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MRawFileRead
+#define MARS_MRawFileRead
+
+#ifndef MARS_MRawRead
+#include "MRawRead.h"
+#endif
+
+class TList;
+class MTaskList;
+
+class MRawFileRead : public MRawRead
+{
+private:
+    TList    *fFileNames;      // list of file names
+    UInt_t    fNumFile;        //! number of next file
+    UInt_t    fNumEvents;      //! input stream (file to read from)
+    UInt_t    fNumTotalEvents; //! total number of events in all files
+
+    std::istream *fIn;         //! input stream (file to read from)
+
+    MParList *fParList;        //! tasklist to call ReInit from
+
+    UInt_t    fInterleave;
+
+    Bool_t    fForce;
+
+    virtual std::istream *OpenFile(const char *filename);
+    virtual Bool_t        ReadRunHeader(std::istream &fin);
+    virtual Bool_t        InitReadData(std::istream &/*fin*/) { return kTRUE; }
+
+    Int_t  OpenNextFile(Bool_t print=kTRUE);
+    Bool_t CalcNumTotalEvents();
+
+protected:
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t    fIsMc;
+
+public:
+    MRawFileRead(const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MRawFileRead();
+
+    static Byte_t IsFileValid(const char *name);
+
+    void SetInterleave(UInt_t i) { fInterleave = i; }
+    void SetForce(Bool_t b=kTRUE) { fForce=b; }
+
+    TString GetFullFileName() const;
+
+    Int_t  AddFile(const char *fname, Int_t entries=-1);
+    Bool_t Rewind();
+    UInt_t GetEntries() { return fNumTotalEvents/fInterleave; }
+
+    const std::istream *GetStream() const { return fIn; }
+
+    ClassDef(MRawFileRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawFileWrite.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawFileWrite.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawFileWrite.cc	(revision 17960)
@@ -0,0 +1,300 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+////////////////////////////////////////////////////////////////////////
+//
+//  MRawFileWrite
+//
+//  Here we write the root containers which contains the data from a
+//  root binary file to a root file. See also MRawFileRead
+//
+//  Input Containers:
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MRawEvtData
+//   MRawEvtData2 [MRawEvtData]
+//   MRawCrateArray
+//   MTime
+//
+//  Output Containers:
+//   -/-
+//
+////////////////////////////////////////////////////////////////////////
+
+#include "MRawFileWrite.h"
+
+#include <TFile.h>
+#include <TTree.h>
+#include <TBranch.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateArray.h"
+
+ClassImp(MRawFileWrite);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It opens the output file (root-file)
+//
+MRawFileWrite::MRawFileWrite(const char *fname,  const Option_t *opt,
+                             const char *ftitle, const Int_t comp,
+                             const char *name, const char *title)
+    : fTData(0), fSplit(kFALSE)
+{
+    fName  = name  ? name  : "MRawFileWrite";
+    fTitle = title ? title : "Write task to write DAQ root files";
+
+    //
+    // Open a rootfile
+    //
+    TString str(fname);
+    if (!str.EndsWith(".root", TString::kIgnoreCase))
+        str += ".root";
+
+    fOut = new TFile(str, opt, ftitle, comp);
+}
+
+MRawFileWrite::~MRawFileWrite()
+{
+    if (fTData)
+    {
+        if (fOut != fTData->GetCurrentFile())
+        {
+            *fLog << warn << endl;
+            *fLog << "WARNING - MWriteRootFile:   Root's  TTree/TFile   has  opened   a  new  file" << endl;
+            *fLog << "  automatically.  You can change this behaviour using TTree::SetMaxTreeSize." << endl;
+            *fLog << "  You won't be able to read splitted  files  correctly with MReadMarsFile if" << endl;
+            *fLog << "  they have more than one entry in 'RunHeaders' or you try to read more than" << endl;
+            *fLog << "  one of such sequences at once." << endl;
+            *fLog << endl;
+        }
+
+        //
+        // For more information see TTree:ChangeFile()
+        //
+        fOut = fTData->GetCurrentFile();
+    }
+
+    //
+    // delete instance, this also does a fOut->Close()
+    //
+    if (fOut->IsOpen())
+        fOut->Write();
+
+    delete fOut;
+
+    //
+    // Remark:
+    // - Trees are automatically deleted by the the file
+    //   (unless file.SetDirectory(0) was called)
+    // - Branches are automatically deleted by the tree destructor
+    //
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess function checks for the following input containers:
+//  - MRawEvtHeader
+//  - MRawEvtData
+//  - MRawCrateArray
+//  - MTime
+//  - MRawRunHeader
+// if a container isn't found the eventloop is stopped.
+//
+// The tree which should containe the run header is created. <RunHeaders>
+// The trees which contains the Events <Events>, <PedEvents>, <CalEvents>
+// are created.
+//
+Int_t MRawFileWrite::PreProcess (MParList *pList)
+{
+    //
+    // test whether file is now open or not
+    //
+    if (!fOut->IsOpen())
+    {
+        *fLog << dbginf << "Error: Cannot open file '" << fOut->GetName() << "'" << endl;
+        return kFALSE;
+    }
+
+    //
+    //  check if MEvtHeader exists in the Parameter list already.
+    //  if not create one and add them to the list
+    //
+    fRawEvtHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+    if (!fRawEvtHeader)
+    {
+        *fLog << err << "MRawEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawEvtData1 = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvtData1)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+    fRawEvtData2 = (MRawEvtData*)pList->FindObject("MRawEvtData2", "MRawEvtData");
+    if (!fRawEvtData2)
+    {
+        *fLog << err << "MRawEvtData2 [MRawEvtData] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawCrateArray = (MRawCrateArray*)pList->FindObject("MRawCrateArray");
+    if (!fRawCrateArray)
+    {
+        *fLog << err << "MRawCrateArray not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTime = (MTime*)pList->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRawRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Remark:
+    // - Trees are automatically deleted by the the file
+    //   (unless file.SetDirectory(0) was called)
+    // - Branches are automatically deleted by the tree destructor
+    //
+    fTRunHeader = new TTree("RunHeaders", "Run headers of all runs in this file");
+    fTRunHeader->Branch("MRawRunHeader.", "MRawRunHeader", &fRawRunHeader, 32000);
+
+    //
+    // create data trees for the three types of data
+    //
+    fTData        =          new TTree("Events",      "Normal Triggered Events");
+    fTPedestal    = fSplit ? new TTree("Pedestals",   "Pedestal Triggered Events")    : fTData;
+    fTCalibration = fSplit ? new TTree("Calibration", "Calibration Triggered Events") : fTData;
+
+    //
+    // From the root dicumentation:
+    //
+    // Note that calling TTree::AutoSave too frequently (or similarly calling
+    // TTree::SetAutoSave with a small value) is an expensive operation.
+    // You should make tests for your own application to find a compromize
+    // between speed and the quantity of information you may loose in case of
+    // a job crash.
+    //
+    // In case your program crashes before closing the file holding this tree,
+    // the file will be automatically recovered when you will connect the file
+    // in UPDATE mode.
+    // The Tree will be recovered at the status corresponding to the last AutoSave.
+    //
+    fTData       ->SetAutoSave(2000000000); // 2GB
+    fTPedestal   ->SetAutoSave(2000000000); // 2GB
+    fTCalibration->SetAutoSave(2000000000); // 2GB
+
+    //
+    // create all branches which are necessary
+    //
+    // FIXME: Can we calculate a good buffer size out of the event size?
+    //        using splitlevel=0 sppeds up writing by a factor of 5-10%
+    fTData->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTData->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTData->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData1,   320000);
+    fTData->Branch("MRawEvtData2.",   "MRawEvtData",    &fRawEvtData2,   320000);
+    fTData->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+    if (!fSplit)
+        return kTRUE;
+
+    fTPedestal   ->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTCalibration->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTPedestal   ->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTCalibration->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTPedestal   ->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData1,   320000);
+    fTCalibration->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData1,   320000);
+    fTPedestal   ->Branch("MRawEvtData2.",   "MRawEvtData",    &fRawEvtData2,   320000);
+    fTCalibration->Branch("MRawEvtData2.",   "MRawEvtData",    &fRawEvtData2,   320000);
+    fTPedestal   ->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+    fTCalibration->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the run header information to the file
+//
+Bool_t MRawFileWrite::ReInit(MParList *pList)
+{
+    fTRunHeader->Fill();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the trigger type from the run header to decide into which tree the
+// event should be filled in and fills  it into this tree.
+//
+Int_t MRawFileWrite::Process()
+{
+    //
+    // get the trigger type of the actual event
+    //
+    const UShort_t type = fRawEvtHeader->GetTrigType();
+
+    //
+    // writa data to the tree. the tree is choosen by the type of the event
+    //
+    switch (type)
+    {
+    case MRawEvtHeader::kTTEvent:
+        fTData->Fill();
+        return kTRUE;
+
+    case MRawEvtHeader::kTTPedestal:
+        fTPedestal->Fill();
+        return kTRUE;
+
+    case MRawEvtHeader::kTTCalibration:
+        fTCalibration->Fill();
+        return kTRUE;
+    }
+
+    *fLog << warn << dbginf << "Got wrong number for the trigger type: " << type;
+    *fLog << " - skipped" << endl;
+
+    return kCONTINUE;
+}
+
Index: branches/Mars_McMismatchStudy/mraw/MRawFileWrite.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawFileWrite.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawFileWrite.h	(revision 17960)
@@ -0,0 +1,53 @@
+#ifndef MARS_MRawFileWrite
+#define MARS_MRawFileWrite
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TFile;
+class TTree;
+
+class MTime;
+class MParList;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MRawCrateArray;
+class MRawEvtData;
+
+class MRawFileWrite : public MTask
+{
+private:
+    MTime          *fTime;
+    MRawRunHeader  *fRawRunHeader;
+    MRawEvtHeader  *fRawEvtHeader;
+    MRawEvtData    *fRawEvtData1;
+    MRawEvtData    *fRawEvtData2;
+    MRawCrateArray *fRawCrateArray;
+
+    TTree *fTData;                  //!
+    TTree *fTPedestal;              //!
+    TTree *fTCalibration;           //!
+
+    TTree *fTRunHeader;             //!
+
+    TFile *fOut;                    //!
+
+    Bool_t fSplit;
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MRawFileWrite(const char *fname, const Option_t *opt="RECREATE",
+                  const char *ftitle="Untitled", const Int_t comp=2,
+                  const char *name=NULL, const char *title=NULL);
+    ~MRawFileWrite();
+
+    void EnableSplit(Bool_t b=kTRUE) { fSplit=b; }
+
+    ClassDef(MRawFileWrite, 0)	// Task to write the raw data containers to a root file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawFitsRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawFitsRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawFitsRead.cc	(revision 17960)
@@ -0,0 +1,266 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2011 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2011
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRawFitsRead
+//
+//  This tasks reads the fits data file in the form used by FACT.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MRawRunHeader, MRawEvtHeader, MRawEvtData, MRawEvtTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawFitsRead.h"
+
+#include <fstream>
+
+#include <TClass.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "factfits.h"
+#include "MTime.h"
+
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawBoardsFACT.h"
+
+ClassImp(MRawFitsRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawFitsRead::MRawFitsRead(const char *fname, const char *name, const char *title)
+    : MRawFileRead(fname, name, title), fRawBoards(0)
+{
+}
+
+const fits *MRawFitsRead::GetFitsFile() const
+{
+    return static_cast<const fits*>(GetStream());
+}
+
+Int_t MRawFitsRead::PreProcess(MParList *pList)
+{
+    fRawBoards = (MRawBoardsFACT*)pList->FindCreateObj("MRawBoardsFACT");
+    if (!fRawBoards)
+        return kFALSE;
+
+    return MRawFileRead::PreProcess(pList);
+}
+
+Bool_t MRawFitsRead::LoadMap(const char *name)
+{
+    fPixelMap.resize(1440);
+
+    if (!name)
+        return kTRUE;
+
+    ifstream fin(name);
+
+    int l = 0;
+
+    string buf;
+    while (getline(fin, buf, '\n'))
+    {
+        if (l>1439)
+            break;
+
+        const TString bf = TString(buf.c_str()).Strip(TString::kBoth);
+        if (bf[0]=='#')
+            continue;
+
+        stringstream str(bf.Data());
+
+        int index, cbpx;
+
+        str >> index;
+        str >> cbpx;
+
+        const int c =  cbpx/1000;
+        const int b = (cbpx/100)%10;
+        const int p = (cbpx/10)%10;
+        const int x =  cbpx%10;
+
+        const int hw = x+p*9+b*36+c*360;
+        if (hw>1439)
+            break;
+
+        fPixelMap[hw] = index;
+        l++;
+    }
+
+    if (l!=1440)
+    {
+        gLog << err << "ERROR - Problems reading " << name << endl;
+        fPixelMap.resize(0);
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Bool_t MRawFitsRead::IsFits(const char *name)
+{
+    return factfits(name).good();
+}
+
+istream *MRawFitsRead::OpenFile(const char *filename)
+{
+    return new factfits(filename);
+}
+
+Bool_t MRawFitsRead::ReadRunHeader(istream &stream)
+{
+    factfits &fin = static_cast<factfits&>(stream);
+
+    if (fin.GetStr("TELESCOP")!="FACT")
+    {
+        gLog << err << "Not a valid FACT FITS file (key TELESCOP not 'FACT')." << endl;
+        return kFALSE;
+    }
+
+    const string type = fin.GetStr("RUNTYPE");
+
+    fRawRunHeader->SetValidMagicNumber();
+    fRawRunHeader->SetNumEvents(fin.GetNumRows());//GetUInt("NAXIS2"));
+    fRawRunHeader->InitPixels(fin.GetUInt("NPIX"));
+    fRawRunHeader->SetObservation(type=="4294967295"?"":fin.GetStr("RUNTYPE"), "FACT");
+    fRawRunHeader->SetRunInfo(0, fin.GetUInt("NIGHT"), fin.GetUInt("RUNID"));
+    fRawRunHeader->InitFact(fin.GetUInt("NPIX")/9, 9, fin.GetUInt("NROI"), fPixelMap.size()==0?0:fPixelMap.data());
+    if (!fin.HasKey("ISMC")){
+        fRawRunHeader->SetFormat(0xf172, fin.GetUInt("BLDVER"));
+    }
+    fRawRunHeader->SetRunType(0/*data*/);
+
+    if (!fin.HasKey("ISMC")){
+        const string runstart = fin.GetStr("DATE-OBS");
+        const string runstop  = fin.GetStr("DATE-END");
+
+        fRawRunHeader->SetRunTime(MTime(runstart.c_str()), MTime(runstop.c_str()));
+    }
+
+    if (!fin.HasKey("ISMC"))
+        return
+            fin.HasKey("NPIX") && fin.HasKey("RUNID")  &&
+            fin.HasKey("NROI") && fin.HasKey("BLDVER") &&
+            fin.HasKey("NIGHT");
+    else
+        return
+            fin.HasKey("NPIX") && fin.HasKey("RUNID")  &&
+            fin.HasKey("NROI") && fin.HasKey("NIGHT");
+}
+
+Bool_t  MRawFitsRead::InitReadData(istream &stream)
+{
+    factfits &fin = static_cast<factfits&>(stream);
+
+    MArrayB **data   = reinterpret_cast<MArrayB**>(fRawEvtData1->DataMember("fHiGainFadcSamples"));
+    MArrayS **cell   = reinterpret_cast<MArrayS**>(fRawEvtData1->DataMember("fStartCells"));
+    UInt_t   *evtnum = reinterpret_cast<UInt_t*>  (fRawEvtHeader->DataMember("fDAQEvtNumber"));
+
+    // The 'wrong' cast is intentional because we read only two bytes from the file
+    UShort_t *trg    = reinterpret_cast<UShort_t*>(fRawEvtHeader->DataMember("fTrigPattern"));
+
+    if (!data || !cell || !evtnum || !trg)
+        return kFALSE;
+
+    fRawEvtData1->ResetPixels();
+    fRawEvtData2->ResetPixels(0, 0);
+    fRawEvtData1->InitStartCells();
+
+    if (!fin.SetRefAddress("EventNum", *evtnum))
+        return kFALSE;
+
+    if (!fin.SetRefAddress("TriggerType", *trg))
+        return kFALSE;
+
+    if (!fin.HasKey("ISMC")){
+        if (!fin.SetRefAddress("NumBoards", fNumBoards))
+            return kFALSE;
+
+        fPCTime.resize(2);
+        if (!fin.SetVecAddress("UnixTimeUTC", fPCTime))
+            if (!fin.SetVecAddress("PCTime", fPCTime))
+                return kFALSE;
+
+
+        if (!fin.SetPtrAddress("BoardTime", fRawBoards->fFadTime, 40))
+            return kFALSE;
+    }
+    else
+        fIsMc = kTRUE;
+
+
+    if (!fin.SetPtrAddress("Data", (int16_t*)(*data)->GetArray(), (*data)->GetSize()/2))
+        return kFALSE;
+
+    if (!fin.SetPtrAddress("StartCellData", (uint16_t*)(*cell)->GetArray(), (*cell)->GetSize()))
+        return kFALSE;
+
+    fRawEvtData1->SetIndices(fRawRunHeader->GetPixAssignment());
+
+    return kTRUE;
+}
+
+Bool_t MRawFitsRead::ReadEvent(istream &stream)
+{
+    if (!static_cast<factfits&>(stream).GetNextRow())
+        return kFALSE;
+
+    if (!fIsMc)
+    {
+        // Skip incomplete events
+        if (fNumBoards!=40)
+            return kCONTINUE;
+
+        fRawEvtTime->SetUnixTime(fPCTime[0], fPCTime[1]);
+
+    }    
+    // FIXME: Correctly sort the pixels here!
+
+    fRawEvtData1->SetReadyToSave();
+    fRawEvtData2->SetReadyToSave();
+
+    return kTRUE;
+}
+
+void MRawFitsRead::SkipEvent(istream &fin)
+{
+    static_cast<factfits&>(fin).SkipNextRow();
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawFitsRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawFitsRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawFitsRead.h	(revision 17960)
@@ -0,0 +1,43 @@
+#ifndef MARS_MRawFitsRead
+#define MARS_MRawFitsRead
+
+#ifndef MARS_MRawFileRead
+#include "MRawFileRead.h"
+#endif
+
+#include <vector>
+
+class fits;
+class MRawBoardsFACT;
+
+class MRawFitsRead : public MRawFileRead
+{
+private:
+    std::vector<UInt_t>   fPCTime;   //! Buffer
+    std::vector<UShort_t> fPixelMap; //! 
+    UInt_t fNumBoards;               //!
+
+    MRawBoardsFACT *fRawBoards;
+
+    Int_t         PreProcess(MParList *pList);
+    std::istream *OpenFile(const char *filename);
+    Bool_t        ReadRunHeader(std::istream &fin);
+    Bool_t        InitReadData(std::istream &fin);
+    Bool_t        ReadEvent(std::istream &fin);
+    void          SkipEvent(std::istream &fin);
+
+public:
+    MRawFitsRead(const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+
+    static Bool_t IsFits(const char *name);
+
+    Bool_t LoadMap(const char *name);
+
+    const fits *GetFitsFile() const;
+
+    const std::vector<UInt_t> &GetPCTime() const { return fPCTime; }
+
+    ClassDef(MRawFitsRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawRead.cc	(revision 17960)
@@ -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 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRawRead
+//
+//  This tasks reads the raw binary file like specified in the TDAS???
+//  and writes the data in the corresponding containers which are
+//  either retrieved from the parameter list or created and added.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:                                                      
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MRawEvtData
+//   MRawEvtData2 [MRawEvtData]
+//   MRawCrateArray
+//   MTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawRead.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateData.h"
+#include "MRawCrateArray.h"
+
+ClassImp(MRawRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawRead::MRawRead(const char *name, const char *title)
+    : fForceMode(kFALSE)
+{
+    fName  = name  ? name  : "MRawRead";
+    fTitle = title ? title : "Bas class for reading DAQ files";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MRawRunHeader <output>   if not found it is created
+//   MRawEvtHeader <output>   if not found it is created
+//   MRawEvtData <output>     if not found it is created
+//   MRawCrateArray <output>  if not found it is created
+//   MRawEvtTime <output>     if not found it is created (MTime)
+//
+// If all containers are found or created the run header is read from the
+// binary file and printed.  If the Magic-Number (file identification)
+// doesn't match we stop the eventloop.
+//
+// Now the EvtHeader and EvtData containers are initialized.
+//
+Int_t MRawRead::PreProcess(MParList *pList)
+{
+    if (!OpenStream())
+        return kFALSE;
+
+    //
+    //  check if all necessary containers exist in the Parameter list.
+    //  if not create one and add them to the list
+    //
+    fRawRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+    if (!fRawRunHeader)
+        return kFALSE;
+
+    fRawEvtHeader = (MRawEvtHeader*)pList->FindCreateObj("MRawEvtHeader");
+    if (!fRawEvtHeader)
+        return kFALSE;
+
+    fRawEvtData1 = (MRawEvtData*)pList->FindCreateObj("MRawEvtData");
+    if (!fRawEvtData1)
+        return kFALSE;
+
+    fRawEvtData2 = (MRawEvtData*)pList->FindCreateObj("MRawEvtData", "MRawEvtData2");
+    if (!fRawEvtData2)
+        return kFALSE;
+
+    fRawCrateArray = (MRawCrateArray*)pList->FindCreateObj("MRawCrateArray");
+    if (!fRawCrateArray)
+        return kFALSE;
+
+    fRawEvtTime = (MTime*)pList->FindCreateObj("MTime");
+    if (!fRawEvtTime)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a workaround for the oldest runs (file version<3)
+// for which no time stamp was available.
+// For this runs a fake time stamp is created
+//
+// Be carefull: This is NOT thread safe!
+//
+void MRawRead::CreateFakeTime() const
+{
+    static Double_t tm = 0; // Range of roughly 8min
+    const UInt_t ct = (*fRawCrateArray)[0]->GetFADCClockTick();
+
+    tm = ct<tm ? fmod(tm, (UInt_t)(-1))+(UInt_t)(-1)+ct : ct;
+
+    const Double_t mhz = 9.375;                        // [1e6 ticks/s]
+    const Double_t t   = tm/mhz;                       // [us]
+    const UInt_t ns    = (UInt_t)fmod(t*1e3, 1e6);
+    //const UShort_t ms  = (UShort_t)fmod(t/1e3, 1e3);
+    const Byte_t s     = (Byte_t)fmod(t/1e6, 60);
+
+    // Create an artificial time stamp!
+    UInt_t m = (Byte_t)fmod(t/60e6, 60);
+    //const Byte_t h     = (Byte_t)(t/3600e6);
+    m += fRawRunHeader->GetRunNumber()*10;
+    m %= 360; // 6h
+
+    fRawEvtTime->UpdMagicTime(m/60, m%60, s, ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a single event from the stream
+//
+Bool_t MRawRead::ReadEvent(istream &fin)
+{
+    //
+    //  Get file format version
+    //
+    const UShort_t ver = fRawRunHeader->GetFormatVersion();
+
+    //
+    // Read in the next EVENT HEADER (see specification),
+    // if there is no next event anymore stop eventloop
+    //
+    const Int_t rc = fRawEvtHeader->ReadEvt(fin, ver, fRawRunHeader->GetHeaderSizeEvt());
+    if (rc==kCONTINUE && fForceMode==kFALSE)
+    {
+        *fLog << err << "Problem found reading the event header... abort." << endl;
+        return kFALSE;
+    }
+    if (rc==kFALSE)
+        return kFALSE;
+
+    //
+    //  Get number of crates from the run header
+    //
+    const UShort_t nc = fRawRunHeader->GetNumCrates();
+
+    //
+    // Delete arrays which stores the pixel information (time slices)
+    //
+    fRawEvtData1->ResetPixels(fRawRunHeader->GetNumNormalPixels(),  fRawRunHeader->GetMaxPixId());
+    fRawEvtData2->ResetPixels(fRawRunHeader->GetNumSpecialPixels(), fRawRunHeader->GetMinPixId());
+
+    //
+    // clear the TClonesArray which stores the Crate Information
+    // and create a new array of the correct size
+    //
+    fRawCrateArray->SetSize(nc);
+
+    //
+    // Calculate the number of byte to be skipped in a file if a pixel is not connected
+    //
+    const UShort_t nskip = fRawRunHeader->GetNumSamples()*fRawRunHeader->GetNumBytesPerSample();
+
+    //
+    // read the CRATE DATA (see specification) from file
+    //
+    Int_t posinarray=0;
+    for (int i=0; i<nc; i++)
+    {
+        if (!fRawCrateArray->GetEntry(i)->ReadEvt(fin, ver, fRawRunHeader->GetHeaderSizeCrate()))
+            return kFALSE;
+
+        //fRawEvtData1->ReadEvt(fin, posinarray++);
+
+        const UShort_t npic = fRawRunHeader->GetNumPixInCrate();
+        const Byte_t   ab   = fRawCrateArray->GetEntry(posinarray)->GetABFlags();
+        for (int j=0; j<npic; j++)
+        {
+            // calc the spiral hardware pixel number
+            const UShort_t ipos = posinarray*npic+j;
+
+            // Get Hardware Id
+            const Short_t hwid = fRawRunHeader->GetPixAssignment(ipos);
+
+            // Check whether the pixel is connected or not
+            if (hwid==0)
+            {
+                fin.seekg(nskip, ios::cur);
+                continue;
+            }
+
+            // -1 converts the hardware pixel Id into the software pixel index
+            if (hwid>0)
+                fRawEvtData1->ReadPixel(fin,   hwid-1);
+            else
+                fRawEvtData2->ReadPixel(fin, -(hwid+1));
+
+            if (ver>=7)
+                continue;
+
+            if (hwid>0)
+                fRawEvtData1->SetABFlag(  hwid-1,  TESTBIT(ab, j));
+            else
+                fRawEvtData1->SetABFlag(-(hwid+1), TESTBIT(ab, j));
+        }
+        if (!fin)
+            return kFALSE;
+
+        posinarray++;
+    }
+
+    // This is a workaround for the oldest runs (version<3)
+    // for which no time stamp was available.
+    // For this runs a fake time stamp is created
+    if (ver<3)
+        CreateFakeTime();
+
+    if (rc==kCONTINUE && fForceMode==kTRUE)
+        return kCONTINUE;
+
+    fRawEvtData1->SetReadyToSave();
+    fRawEvtData2->SetReadyToSave();
+
+    return kTRUE;
+}
+
+void MRawRead::SkipEvent(istream &fin)
+{
+    //
+    //  Get file format version
+    //
+    const UShort_t ver = fRawRunHeader->GetFormatVersion();
+    fRawEvtHeader->SkipEvt(fin, ver);
+
+    const UShort_t nc = fRawRunHeader->GetNumCrates();
+    for (int i=0; i<nc; i++)
+    {
+        fRawCrateArray->GetEntry(i)->SkipEvt(fin, ver);
+        fRawEvtData1->SkipEvt(fin);
+    }
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawRead.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MRawRead
+#define MARS_MRawRead
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MTime;
+class MParList;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MRawEvtData;
+class MRawCrateArray;
+
+class MRawRead : public MRead
+{
+protected:
+    MRawRunHeader  *fRawRunHeader;  // run header information container to fill from file
+    MRawEvtHeader  *fRawEvtHeader;  // event header information container to fill from file
+    MRawEvtData    *fRawEvtData1;   // raw evt data infomation container to fill from file
+    MRawEvtData    *fRawEvtData2;   // raw evt data for pixels with negative indices
+    MRawCrateArray *fRawCrateArray; // crate information array container to fill from file
+    MTime          *fRawEvtTime;    // raw evt time information container to fill from file
+
+    Bool_t          fForceMode;     // Force mode skipping defect events
+
+    void CreateFakeTime() const;
+
+    virtual Bool_t ReadEvent(std::istream &fin);
+    virtual void   SkipEvent(std::istream &fin);
+    Int_t  PreProcess(MParList *pList);
+
+private:
+    virtual Bool_t OpenStream() { return kTRUE; }
+
+public:
+    MRawRead(const char *name=NULL, const char *title=NULL);
+
+    UInt_t GetEntries() { return 0; }
+    Bool_t Rewind() {return kTRUE; }
+
+    void SetForceMode(Bool_t b=kTRUE) { fForceMode = b; }
+
+    ClassDef(MRawRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawRunHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawRunHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawRunHeader.cc	(revision 17960)
@@ -0,0 +1,1440 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRawRunHeader
+//
+// Root storage container for the RUN HEADER information
+//
+//
+//  RAW DATA FORMAT VERSION
+//  =======================
+//
+//  Format Version 12:
+//  -----------------
+//   * fIsSigned
+//
+//  Format Version 11:
+//  -----------------
+//   * all variables got four bytes
+//   * header sizes allow to make the format backward compatible
+//   + fHeaderSizeRun
+//   + fHeaderSizeEvt
+//   + fHeaderSizeCrate
+//   + fFileNumber
+//   + fNumSamplesRemovedHead
+//   + fNumSamplesRemovedTail
+//
+//  Format Version 10:
+//  -----------------
+//    ?
+//
+//  Format Version 9:
+//  -----------------
+//   + fNumEventsRead;
+//   + fSamplingFrequency
+//   - fFreqSampling
+//   + fFadcResolution;
+//   - fNumSignificantBits
+//
+//  Format Version 8:
+//  -----------------
+//   + fNumBytesPerSample;
+//   + fFreqSampling;
+//   + fNumSignificantBits
+//   * changes in MRawCrateHeader
+//
+//  Format Version 7:
+//  -----------------
+//   - unused
+//
+//  Format Version 6:
+//  -----------------
+//   + added CameraVersion
+//   + added TelescopeNumber
+//   + added ObservationMode
+//   + added dummies for TelescopeRa/Dec
+//
+//  Format Version 5:
+//  -----------------
+//   - now the sub millisecond information of the time is valid and decoded
+//     which enhances the precision from 51.2us to 200ns
+//
+//  Format Version 4:
+//  -----------------
+//   - added support for pixels with negative IDs
+//
+//  Format Version 3:
+//  -----------------
+//   - ???
+//
+//  Format Version 2:
+//  -----------------
+//   - removed mjd from data
+//   - added start time
+//   - added stop  time
+//
+//
+//  MRawRunHeader CLASS VERSION
+//  ===========================
+//
+//  Format Version 10:
+//  -----------------
+//   - added fHeaderSizeRun
+//   - added fHeaderSizeEvt
+//   - added fHeaderSizeCrate
+//   - added fFileNumber
+//   - increased fSourceEpochChar
+//
+//  Format Version 7:
+//  -----------------
+//   - added fNumEventsRead;
+//   * renamed fFreqSampling to fSamplingFrequency
+//   * renamed fNumSignificantBits to fFadcResolution
+//
+//  Format Version 6:
+//  -----------------
+//   - added fNumBytesPerSample;
+//   - added fSamplingFrequency;
+//   - added fFadcResolution;
+//
+//  Class Version 5:
+//  -----------------
+//   - for compatibility with newer camera versions
+//
+//  Class Version 4:
+//  -----------------
+//   - added fCameraVersion
+//   - added fTelescopeNumber
+//   - changed length of fProjectName to 101
+//   - changed length of fSourceName  to 81
+//
+//  Class Version 3:
+//  ----------------
+//   - enhanced SourceName and ProjectName by one character, because
+//     without telling us the guranteed trailing \0-character has
+//     skipped
+//
+//  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 <TArrayC.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayS.h"
+#include "MString.h"
+
+ClassImp(MRawRunHeader);
+
+using namespace std;
+
+const UShort_t MRawRunHeader::kMagicNumber      = 0xc0c0;
+const Byte_t   MRawRunHeader::kMaxFormatVersion =     11;
+
+// --------------------------------------------------------------------------
+//
+// 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);
+
+    // Remark: If we read old MC data from a root file which do not
+    // yet contain one of these variable, the value given here is
+    // the default. Do not mix files with and without a value if the
+    // files with the value do not match the default!
+    fFormatVersion=11;
+    fSoftVersion=0;
+    fTelescopeNumber=1;
+    fCameraVersion=1;
+    fFadcType=1;
+    fRunType=kRTNone;  // use 0xffff for invalidation, 0 means: Data run
+    fRunNumber=0;
+    fFileNumber=0;
+    memset(fProjectName,     0, 101);
+    memset(fSourceName,      0,  81);
+    memset(fObservationMode, 0,  61);
+    fSourceEpochChar[0]=0;
+    fSourceEpochChar[1]=0;
+    fSourceEpochDate=0;
+    fNumCrates=0;
+    fNumPixInCrate=0;
+    fNumSamplesLoGain=0;
+    fNumSamplesHiGain=0;
+    fNumEvents=0;
+    fNumEventsRead=0;
+    fNumBytesPerSample=1;
+    fIsSigned = kFALSE;
+    fSamplingFrequency=300;
+    fFadcResolution=8;
+
+    fHeaderSizeRun=0;
+    fHeaderSizeEvt=0;
+    fHeaderSizeCrate=0;
+}
+
+MRawRunHeader::MRawRunHeader(const MRawRunHeader &h)
+{
+    fMagicNumber=h.fMagicNumber;                       // File type identifier
+
+    fHeaderSizeRun=h.fHeaderSizeRun;                   // Size of run header
+    fHeaderSizeEvt=h.fHeaderSizeEvt;                   // Size of evt header
+    fHeaderSizeCrate=h.fHeaderSizeCrate;               // Size of crate header
+
+    fFormatVersion=h.fFormatVersion;                   // File format version
+    fSoftVersion=h.fSoftVersion;                       // DAQ software version
+    fFadcType=h.fFadcType;                             // FADC type (1=Siegen, 2=MUX)
+    fCameraVersion=h.fCameraVersion;                   // Camera Version (1=MAGIC I)
+    fTelescopeNumber=h.fTelescopeNumber;               // Telescope number (1=Magic I)
+    fRunType=h.fRunType;                               // Run Type
+    fRunNumber=h.fRunNumber;                           // Run number
+    fFileNumber=h.fFileNumber;                         // File number
+    memcpy(fProjectName, h.fProjectName, 101);         // Project name
+    memcpy(fSourceName, h.fSourceName, 81);            // Source name
+    memcpy(fObservationMode, h.fObservationMode, 61);  // observation mode
+    memcpy(fSourceEpochChar, h.fSourceEpochChar, 4);   // epoch char of the source
+    fSourceEpochDate=h.fSourceEpochDate;               // epoch date of the source
+    fNumCrates=h.fNumCrates;                           // number of electronic boards
+    fNumPixInCrate=h.fNumPixInCrate;                   // number of pixels in crate
+    fNumSamplesLoGain=h.fNumSamplesLoGain;             // number of logain samples stored
+    fNumSamplesHiGain=h.fNumSamplesHiGain;             // number of higain samples stored
+    fNumBytesPerSample=h.fNumBytesPerSample;           // number of bytes per sample
+    fNumEvents=h.fNumEvents;                           // number of events stored
+    fNumEventsRead=h.fNumEventsRead;                   // number of events read by the electronics
+    fSamplingFrequency=h.fSamplingFrequency;           // Sampling Frequency [MHz]
+    fFadcResolution=h.fFadcResolution;                 // number of significant bits
+    fRunStart=h.fRunStart;                             // time of run start
+    fRunStop=h.fRunStop;                               // time of run stop
+    fPixAssignment = new MArrayS(*h.fPixAssignment);   //-> pixel assignment table
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes the 'pixel-assignment-array'
+//
+MRawRunHeader::~MRawRunHeader()
+{
+    delete fPixAssignment;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks for consistency between two run headers. Checks:
+//    fNumCrates
+//    fNumPixInCrate
+//    fNumSamplesLoGain
+//    fNumSamplesHiGain
+//    fNumBytesPerSample
+//
+Bool_t MRawRunHeader::IsConsistent(const MRawRunHeader &h) const
+{
+    return fNumCrates==h.fNumCrates &&
+        fNumPixInCrate==h.fNumPixInCrate &&
+        fNumSamplesLoGain==h.fNumSamplesLoGain &&
+        fNumSamplesHiGain==h.fNumSamplesHiGain &&
+        fNumBytesPerSample==h.fNumBytesPerSample;
+}
+
+// --------------------------------------------------------------------------
+//
+// Swap the assignment of the pixels with hardware id id0 and id1
+//
+Bool_t MRawRunHeader::SwapAssignment(Short_t id0, Short_t id1)
+{
+    const Int_t n = fPixAssignment->GetSize();
+
+    // Look-up-table
+    UShort_t *lut = fPixAssignment->GetArray();
+
+    // Search for one of the hardware indices to get exchanged
+    int i;
+    for (i=0; i<n; i++)
+        if (lut[i]==id0 || lut[i]==id1)
+            break;
+
+    // Check if one of the two pixels were found
+    if (i==n)
+    {
+        *fLog << warn << "WARNING - Assignment of pixels with hardware ID " << id0 << " and " << id1;
+        *fLog << " should be exchanged, but none were found." << endl;
+        return kTRUE;
+    }
+
+    // Store first index
+    const Int_t idx0 = i;
+
+    // Search for the other hardware indices to get exchanged
+    for (i++; i<n; i++)
+        if (lut[i]==id0 || lut[i]==id1)
+            break;
+
+    // Check if the second pixel was found
+    if (i==n)
+    {
+        *fLog << err << "ERROR - Assignment of pixels with hardware ID " << id0 << " and " << id1;
+        *fLog << " should be exchanged, but only one was found." << endl;
+        return kFALSE;
+    }
+
+    const Int_t idx1 = i;
+
+    const Short_t p0 = lut[idx0];
+    const Short_t p1 = lut[idx1];
+
+    lut[idx0] = p1;
+    lut[idx1] = p0;
+
+    *fLog << inf << "Assignment of pixels with hardware ID " << id0 << " and " << id1 << " exchanged." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return Telescope number, runnumber and filenumber on the form:
+//      run
+// as string for runnumber<1000000 and
+//      telescope:run/file
+// otherwise.
+//
+TString  MRawRunHeader::GetStringID() const
+{
+    return fRunNumber<1000000?MString::Format("%d", fRunNumber):MString::Format("%d:%d/%d", fTelescopeNumber, fRunNumber, fFileNumber);
+}
+
+// --------------------------------------------------------------------------
+//
+// Consistency checks. See code for detils.
+//
+Bool_t MRawRunHeader::IsConsistent() const
+{
+    // FIXME: Match first digits of run-number with telescope number
+
+    if (fFormatVersion>10)
+    {
+        if (GetTypeID()!=fTelescopeNumber     &&
+            GetTypeID()!=fTelescopeNumber*10U &&
+            GetTypeID()!=5U)
+        {
+            *fLog << err << "ERROR - Telescope number " << fTelescopeNumber << " doesn't match the first two digits of the run number " << fRunNumber << " and run number doesn't start with 5." << endl;
+            return kFALSE;
+        }
+
+        // Old formats can not contain a run number larger 999999
+        if (fRunNumber<1000000)
+        {
+            *fLog << err << "ERROR - Run number " << fRunNumber << " smaller than 1000000." << endl;
+            return kFALSE;
+        }
+    }
+
+    // Check for correct number of bytes in data stream
+    if (fFormatVersion>7 && fNumBytesPerSample!=2)
+    {
+        *fLog << err << "ERROR - " << fNumBytesPerSample << " bytes per sample are not supported!" << endl;
+        return kFALSE;
+    }
+
+    // If we have a vlid stop time check its consistency with the start time
+    if (fRunStop!=MTime() && fRunStop<fRunStart)
+    {
+        *fLog << err << "ERROR - Stop time smaller than start time." << endl;
+        return kFALSE;
+    }
+
+    // No file numbers larger than 999 allowed in general
+    if (fFileNumber>999)
+    {
+        *fLog << err << "ERROR - File number " << fFileNumber << " larger than 999." << endl;
+        return kFALSE;
+    }
+
+    // Old formats can not contain a run number larger 0
+    if (fFormatVersion<11 && fFileNumber>0)
+    {
+        *fLog << err << "ERROR - File number " << fFileNumber << " larger than 0." << endl;
+        return kFALSE;
+    }
+
+    if (fFormatVersion>1)
+    {
+        // For most of the formats the start time must be valid
+        if (fRunStart==MTime())
+        {
+            *fLog << err << "ERROR - Start time invalid." << endl;
+            return kFALSE;
+        }
+
+        // For most of the formats an invalid stop time cannot happen if file closed
+        if (fMagicNumber==kMagicNumber && fRunStop==MTime())
+        {
+            *fLog << err << "ERROR - File closed but stop time invalid." << endl;
+            return kFALSE;
+        }
+    }
+    return kTRUE;
+}
+
+void MRawRunHeader::FixRunNumbers()
+{
+    if (fFormatVersion<11 || fTelescopeNumber!=1)
+        return;
+
+    // Map 1:1001349 to 47:1001395
+    if (fRunNumber<48 &&
+        fRunStart.GetMjd()>54674.5 && fRunStart.GetMjd()<56476.5)
+    {
+        fRunNumber += 1001348;
+        *fLog << warn << "Format >V10: Wrong run number increased by 1001348 to " << fRunNumber << "." << endl;
+    }
+
+    // Map 1001916:1001922 to 1002349:1002355
+    if (fRunNumber>1001915 && fRunNumber<1001923 &&
+        fRunStart.GetMjd()>54710.5 && fRunStart.GetMjd()<54711.5)
+    {
+        fRunNumber += 433;
+        *fLog << warn << "Format >V10: Wrong run number increased by 434 to " << fRunNumber << "." << endl;
+    }
+
+    // Map 10000342:1000343 to 10000351:1000351
+    if (fRunNumber>10000342 && fRunNumber<10000352 &&
+        fRunStart.GetMjd()>54254.5 && fRunStart.GetMjd()<54255.5)
+    {
+        fRunNumber -= 9000000;
+        *fLog << warn << "Format >V10: Wrong run number decreased by 9000000 to " << fRunNumber << "." << endl;
+    }
+
+    if (fRunNumber==1000382 &&
+        fRunStart.GetMjd()>54256.5 && fRunStart.GetMjd()<54257.5 &&
+        !strcmp(fSourceName, "GRB080605-2347"))
+    {
+        fFileNumber += 99;
+        *fLog << warn << "Format >V10: Ambiguous file number increased by 99 to " << fFileNumber << "." << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// This implements a fix of the pixel assignment before 25.9.2005
+//
+// From magic_online (the pixel numbers are hardware indices):
+// --------------------------------------------------------------------------
+//   From: Florian Goebel <fgoebel@mppmu.mpg.de>
+//   Date: Sun Sep 25 2005 - 05:13:19 CEST
+//   
+//   [...]
+//   - problem 2: pixels were swaped
+//   - cause: opical fibers were wrongly connected to receiver board
+//      554 <-> 559
+//      555 <-> 558
+//      556 <-> 557
+//   - action: reconnect correctly
+//   - result: ok now
+//   - comment: I don't know when this error was introduced, so backward
+//      correction of the data is difficult.
+//      Fortunately the effect is not too large since the affected 6 pixels are
+//      on the outermost edge of the camera
+//      Since this board has special pixels the optical fibers have been
+//      unplugged several times.
+//   !!!!! Whenever you unplug and reconnect optical fibers make really !!!!!
+//   !!!!! sure you connect them back correctly. !!!!!
+//   !!!!! Always contact me before you do so and if you have any doubts !!!!!
+//   !!!!! how to reconnect the fibers ask me. !!!!!
+//      These swapped pixels have only been found by chance when doing the
+//      flatfielding.
+//   [...]
+//
+// --------------------------------------------------------------------------
+//
+// MAGIC runbook CC_2006_04_22_22_28_52.rbk
+//
+// [2006-04-22 23:14:13]
+//
+// [...]
+// Found 2 pairs of swapped pixels.
+// We corrected swapped pixels 54<->55 in the receiver boards. We probably
+// swapped today in the camera.
+// We did not correct 92<-<93 which are likely swapped. Will check and correct
+// tomorrow.
+//
+// ---
+//
+// comments:
+// - 54<->55 were corrected but have not been swapped, hence they are swapped
+//   since then (run 88560 ok, run 88669 swapped; between them mostly dummy and
+//   test runs)
+// - 92<->93 are never swapped, always ok.
+//
+// --------------------------------------------------------------------------
+//
+// MAGIC runbook CC_2006_08_28_19_40_18.rbk
+//
+// [2006-08-28 23:09:07]
+// While doing a flatfielding we have found out that the signals for pixels
+// 119 and 120 were swapped. We have fixed it by exchanging the corresponding
+// fibers at the input of the receivers (not before the splitters!).
+//
+// ---
+//
+// MAGIC runbook CC_2006_08_29_15_19_14.rbk
+//
+// [2006-08-29 16:43:09]
+// In the last hours we have found out and fixed a good number of pixels which
+// were swapped: 119-120, 160-161-162 and 210-263. According to Florian,
+// 160-161-162 and 210-263 were swapped since November 2005.
+//
+// ---
+//
+// mail Florian Goebel (08/30/2006 03:13 PM):
+//
+// As far as I can tell pixels 161 and 162 as well as 263 and 210 were
+// swapped in the trigger. This leads to some inefficiency of the trigger.
+// However, they were not swapped in the readout. So, you don't have to
+// correct anything in the data for these pixels.
+//
+// ---
+//
+// comments:
+// - 119-120 swapped between run 93251 (not swapped) and 93283 (swapped)
+//   (only testruns between these runs)
+//   corrected since run 99354 (== runbook [2006-08-28 23:09:07])
+// - 160 never swapped
+// - 161-162 were only swapped in the trigger, but nevertheless were
+//   "corrected" also in the signal. Hence signal swapped since 99354
+//
+Bool_t MRawRunHeader::FixAssignment()
+{
+    if (!fTelescopeNumber==1)
+        return kTRUE;
+
+    if (fRunNumber>=53300 && fRunNumber<=68754)
+    {
+        if (!SwapAssignment(554, 559))
+            return kFALSE;
+        if (!SwapAssignment(555, 558))
+            return kFALSE;
+        if (!SwapAssignment(556, 557))
+            return kFALSE;
+    }
+
+    if (fRunNumber>=93283 && fRunNumber<99354)
+    {
+        if (!SwapAssignment(119, 120))
+            return kFALSE;
+    }
+
+    if (fRunNumber>=99354 && fRunNumber<=101789)
+    {
+        if (!SwapAssignment(161, 162))
+            return kFALSE;
+        if (!SwapAssignment(210, 263))
+            return kFALSE;
+    }
+
+    if (fRunNumber>=88669)
+    {
+        if (!SwapAssignment(54, 55))
+            return kFALSE;
+    }
+
+    if (fRunNumber>=200000)
+    {
+        if (!SwapAssignment(428, 429))
+            return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fixes to fix bugs in the run header
+//
+Bool_t MRawRunHeader::Fixes()
+{
+    FixRunNumbers();
+
+    if (fFormatVersion>8 && fRunNumber>326152 && fTelescopeNumber==1)
+    {
+        fNumEvents--;
+        fNumEventsRead--;
+        *fLog << inf << "Format >V8 and Run>M1:326152: Stored number of events decreased by 1." << endl;
+    }
+
+    return FixAssignment();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Reading function to read/interpret the file formats 1-10
+//
+Bool_t MRawRunHeader::ReadEvtOld(istream& fin)
+{
+    if (fFormatVersion==7)
+    {
+        *fLog << err << "ERROR - File format V7 was for testing only and is not correctly implemented!" << endl;
+        return kFALSE;
+    }
+
+    // ----- DAQ software format version -----
+    fin.read((char*)&fSoftVersion, 2);     // Total=6
+
+
+    fFadcType = 1;
+    if (fFormatVersion>7)
+        fin.read((char*)&fFadcType, 2);
+
+    // ----- Camera geometry and telescope number -----
+    fCameraVersion   = 1;
+    fTelescopeNumber = 1;
+    if (fFormatVersion>5)
+    {
+        fin.read((char*)&fCameraVersion,   2); // (+2)
+        fin.read((char*)&fTelescopeNumber, 2); // (+2)
+    }
+
+    // ----- Run information -----
+    fin.read((char*)&fRunType,     2); // Total=8
+
+    fin.read((char*)&fRunNumber,   4); // Total=12
+    fin.read((char*)&fProjectName, fFormatVersion>5?100:22); // Total=34  (+78)
+    fin.read((char*)&fSourceName,  fFormatVersion>5? 80:12); // Total=46  (+58)
+
+    if (fFormatVersion>5)
+        fin.read((char*)fObservationMode, 60); // (+60)
+    // Maybe we should set fObservationMode to something
+    // in case of fFormatVersion<6
+
+    // ----- Source position -----
+    fin.seekg(fFormatVersion>5 ? 16 : 8, ios::cur);
+    /*
+    if (fFormatVersion>5)
+    {
+        fin.read((char*)&fSourceRa,  4);  // F32 SourceRA;  Total=48
+        fin.read((char*)&fSourceDec, 4);  // F32 SourceDEC; Total=52
+    }
+    fin.read((char*)&fTelescopeRa,  4);   // F32 TelescopeRA;  (+4)
+    fin.read((char*)&fTelescopeDec, 4);   // F32 TelescopeDEC; (+4)
+    */
+
+    // Maybe we should set these to something
+    // in case of fFormatVersion<6
+    fin.read((char*)&fSourceEpochChar,  2);     // Total=56
+    fin.read((char*)&fSourceEpochDate,  2);     // Total=58
+
+    // ----- Old Start time -----
+    if (fFormatVersion<2)                       // Total += 10
+    {
+        UShort_t y, m, d;
+        fin.seekg(4, ios::cur);    // 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);
+    }
+
+    // ----- Data Geometry -----
+
+    fin.read((char*)&fNumCrates,        2); // MUX: number of channels
+    fin.read((char*)&fNumPixInCrate,    2); // MUX: number of pix in channel
+    fin.read((char*)&fNumSamplesLoGain, 2); // MUX: dummy (must be 0 for MUX data)
+    fin.read((char*)&fNumSamplesHiGain, 2); // MUX: Number of samples per pixel
+
+    char dummy[16];
+    if (fFormatVersion>8)
+        fin.read(dummy, 4); // 2xU16 (NumSamplesRemovedHead and NumSamplesRemovedTail)
+
+    // ----- Number of events -----
+    fin.read((char*)&fNumEvents, 4);     // Total=70
+
+    if (fFormatVersion>8)
+        fin.read((char*)&fNumEventsRead, 4);
+
+    // New in general features: (should they be included in new MAGIC1 formats, too?)
+    fNumBytesPerSample  = 1;      // 2 for MUX DATA
+    fSamplingFrequency  = 300;
+    fFadcResolution     = 8;
+
+    if (fFormatVersion>7)
+    {
+        fin.read((char*)&fNumBytesPerSample,  2);
+        fin.read((char*)&fSamplingFrequency,  2); // [MHz], 2000 for MuxFadc
+        fin.read((char*)&fFadcResolution,     1); // nominal resolution [# Bits], 10 for MuxFadc
+    }
+
+    // ----- Start/Stop time -----
+    if (fFormatVersion>1)
+    {
+        fRunStart.ReadBinary(fin);              // Total += 7
+        fRunStop.ReadBinary(fin);               // Total += 7
+    }
+
+    //
+    // calculate size of array, create it and fill it
+    //
+    const Int_t nPixel = fNumCrates*fNumPixInCrate;
+    fPixAssignment->Set(nPixel);
+
+    // ----- Pixel Assignement -----
+    fin.read((char*)fPixAssignment->GetArray(), nPixel*2);
+
+    if (fFormatVersion<7)
+        fin.read(dummy, 16);
+
+    // ----- Fixes for broken files or contents -----
+    if (!Fixes())
+        return kFALSE;
+
+    // ----- Consistency checks -----
+    return IsConsistent();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+    // ----- File format version -----
+    fin.read((char*)&fFormatVersion, 2);     // Total=4
+    if (fFormatVersion==10 || fFormatVersion>kMaxFormatVersion)
+    {
+        *fLog << err << "ERROR - File format V" << fFormatVersion << " not implemented!" << endl;
+        return kFALSE;
+    }
+
+    // ----- Process old file formats -----
+    if (fFormatVersion<10)
+        return ReadEvtOld(fin);
+
+    // ----- Overwrite format version for format 11 -----
+    fin.read((char*)&fFormatVersion, 4);
+    if (fFormatVersion<11)
+    {
+        *fLog << err << "ERROR - Format Version <11." << endl;
+        return kFALSE;
+    }
+
+    // ----- Read Header by size as written in the header -----
+    fin.read((char*)&fHeaderSizeRun, 4);
+    if (fHeaderSizeRun<346)
+    {
+        *fLog << err << "ERROR - Event header too small (<388b)." << endl;
+        return kFALSE;
+    }
+
+    TArrayC h(fHeaderSizeRun-12);
+    fin.read(h.GetArray(), h.GetSize());
+    if (!fin)
+        return kFALSE;
+
+    // ----- convert -----
+    const Byte_t  *Char  = reinterpret_cast<Byte_t* >(h.GetArray());
+    const UInt_t  *Int   = reinterpret_cast<UInt_t* >(h.GetArray());
+    //const Float_t *Float = reinterpret_cast<Float_t*>(h.GetArray());
+
+    // ----- Start interpretation -----
+
+    fHeaderSizeEvt   = Int[0];
+    fHeaderSizeCrate = Int[1];
+    fSoftVersion     = Int[2];
+    fFadcType        = Int[3];
+    fCameraVersion   = Int[4];
+    fTelescopeNumber = Int[5];
+    fRunType         = Int[6];
+    fRunNumber       = Int[7];
+    fFileNumber      = Int[8];
+
+    memcpy(fProjectName,     Char+ 36, 100);  // 25
+    memcpy(fSourceName,      Char+136,  80);  // 20
+    memcpy(fObservationMode, Char+216,  60);  // 15
+
+    //F32       fSourceRA     = Float[69];
+    //F32       fSourceDEC    = Float[70];
+    //F32       fTelescopeRA  = Float[71];
+    //F32       fTelescopeDEC = Float[72];
+
+    memcpy(fSourceEpochChar, Char+232, 4);
+
+    fSourceEpochDate    = Int[74];
+    fNumCrates          = Int[75];
+    fNumPixInCrate      = Int[76];
+    fNumSamplesHiGain   = Int[77];
+    fNumSamplesLoGain   = 0;
+
+    //fNumSamplesRemovedHead = Int[78];
+    //fNumSamplesRemovedTail = Int[79];
+
+    fNumEvents          = Int[80];
+    fNumEventsRead      = Int[81];
+    fNumBytesPerSample  = Int[82];
+    fSamplingFrequency  = Int[83];
+    fFadcResolution     = Int[84];
+
+    fRunStart.SetBinary(Int+85);
+    fRunStop.SetBinary(Int+91);
+
+    // ----- 388 bytes so far -----
+
+    const UInt_t n = fNumCrates*fNumPixInCrate;
+    if (fHeaderSizeRun<388+n*4)
+    {
+        *fLog << err << "ERROR - Event header too small to contain pix assignment." << endl;
+        return kFALSE;
+    }
+
+    // ----- Pixel Assignment -----
+    fPixAssignment->Set(n);
+
+    for (UInt_t i=0; i<n; i++)
+        (*fPixAssignment)[i] = Int[97+i];
+
+    // ----- Fixes for broken files or contents -----
+    if (!Fixes())
+        return kFALSE;
+
+    // ----- Consistency checks -----
+    return IsConsistent();
+}
+/*
+Bool_t MRawRunHeader::WriteEvt(ostream& out) const
+{
+    //
+    // write one RUN HEADER from the input stream
+    //
+    const UInt_t n = fNumCrates*fNumPixInCrate;
+
+    const UShort_t magicnumber     = kMagicNumber;
+    const UInt_t   formatversion   = 11;
+    const UInt_t   headersizerun   = (97+n)*4; //???
+
+    // FIXME: Write fixed number (c0c0)
+    out.write((char*)&magicnumber,   2);     // Total=2
+    out.write((char*)&formatversion, 2);     // Total=4
+    out.write((char*)&formatversion, 4);
+    out.write((char*)&headersizerun, 4);
+
+    TArrayC h(headersizerun-12);
+
+    // ----- convert -----
+    Byte_t  *Char  = reinterpret_cast<Byte_t* >(h.GetArray());
+    UInt_t  *Int   = reinterpret_cast<UInt_t* >(h.GetArray());
+    //const Float_t *Float = reinterpret_cast<Float_t*>(h.GetArray());
+
+    // ----- Start interpretation -----
+
+    Int[0] = 0; // fHeaderSizeEvt;
+    Int[1] = 0; // fHeaderSizeCrate;
+    Int[2] = 0; // fSoftVersion;
+    Int[3] = fFadcType;
+    Int[4] = fCameraVersion;
+    Int[5] = fTelescopeNumber;
+    Int[5] = fRunType;
+    Int[6] = fRunNumber;
+    Int[7] = fFileNumber;
+
+    memcpy(Char+ 36, fProjectName,    100);  // 25
+    memcpy(Char+136, fSourceName,      80);  // 20
+    memcpy(Char+216, fObservationMode, 60);  // 15
+
+    //F32       fSourceRA     = Float[69];
+    //F32       fSourceDEC    = Float[70];
+    //F32       fTelescopeRA  = Float[71];
+    //F32       fTelescopeDEC = Float[72];
+
+    memcpy(Char+232, fSourceEpochChar, 4);
+
+    Int[74] = fSourceEpochDate;
+    Int[75] = fNumCrates;
+    Int[76] = fNumPixInCrate;
+    Int[77] = fNumSamplesHiGain;
+
+    //fNumSamplesRemovedHead = Int[78];
+    //fNumSamplesRemovedTail = Int[79];
+
+    Int[80] = fNumEvents;
+    Int[81] = fNumEvents; //fNumEventsRead;
+    Int[82] = fNumBytesPerSample;
+    Int[83] = fSamplingFrequency;
+    Int[84] = fFadcResolution;
+
+    fRunStart.GetBinary(Int+85);
+    fRunStop.GetBinary(Int+91);
+
+    // ----- 388 bytes so far -----
+
+    //const UInt_t n = fNumCrates*fNumPixInCrate;
+    //if (fHeaderSizeRun<(97+n)*4)
+    //{
+    //    *fLog << err << "ERROR - Event header too small to contain pix assignment." << endl;
+    //    return kFALSE;
+    //}
+
+    // ----- Pixel Assignment -----
+    for (UInt_t i=0; i<n; i++)
+        Int[97+i] = (*fPixAssignment)[i];
+
+    out.write(h.GetArray(), h.GetSize());
+
+    return out;
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Return the run type as string ("Data", "Pedestal", ...), for example
+// to print it as readable text.
+//
+const Char_t *MRawRunHeader::GetRunTypeStr() const
+{
+    switch (fRunType)
+    {
+    case kRTData:
+        return "Data";
+    case kRTPedestal:
+        return "Pedestal";
+    case kRTCalibration:
+        return "Calibration";
+    case kRTDominoCal:
+        return "DominoCal";
+    case kRTLinearity:
+        return "Linearity";
+    case kRTPointRun:
+        return "Point-Run";
+    case kRTMonteCarlo:
+        return "Monte Carlo";
+    case kRTNone:
+        return "<none>";
+    default:
+        return "<unknown>";
+    }
+}
+
+Char_t MRawRunHeader::GetRunTypeChar() const
+{
+    switch (fRunType&0xff)
+    {
+    case kRTData:
+    case kRTPointRun:
+        return 'D';
+    case kRTPedestal:
+        return 'P';
+    case kRTCalibration:
+        return 'C';
+    case kRTDominoCal:
+        return 'L';
+    case kRTLinearity:
+        return 'N';
+    default:
+        return ' ';
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// print run header information on *fLog. The option 'header' supresses
+// the pixel index translation table.
+//
+void MRawRunHeader::Print(Option_t *t) const
+{
+    *fLog << all << endl;
+    *fLog << "MagicNumber:  0x" << hex << fMagicNumber << " - ";
+    switch (fMagicNumber)
+    {
+    case kMagicNumber:   *fLog << "OK";               break;
+    case kMagicNumber+1: *fLog << "File not closed!"; break;
+    default:             *fLog << "Wrong!";           break;
+    }
+    *fLog << endl;
+    *fLog << "Versions:     " << dec << "Format=";
+    if (fFormatVersion==0xf172)
+        *fLog << "FITS[f172]";
+    else
+        *fLog << fFormatVersion;
+    *fLog << "  Software=" << fSoftVersion << "  ";
+    if (fFormatVersion>5)
+    {
+        *fLog << "Camera=";
+        if (fCameraVersion==0xfac7)
+            *fLog << "FACT[fac7]";
+        else
+            *fLog << fCameraVersion;
+    }
+    *fLog << endl;
+    if (fFormatVersion>10 && fHeaderSizeRun>0 && fHeaderSizeEvt>0 && fHeaderSizeCrate>0)
+        *fLog << "Header sizes: " << fHeaderSizeRun << "b (run), " << fHeaderSizeEvt << "b (evt), " << fHeaderSizeCrate << "b (crate)" << endl;
+    if (fRunNumber>0)
+    {
+        if (fFormatVersion>5 && fTelescopeNumber>0)
+            *fLog << "Telescope:    " << fTelescopeNumber << endl;
+        *fLog << "RunNumber:    " << fRunNumber;
+        if (fFormatVersion>10)
+            *fLog << "/" << fFileNumber << " (id=" << GetFileID() << ")";
+        *fLog << " (Type=" << GetRunTypeStr() << ")" << endl;
+    }
+    if (fFormatVersion>7)
+    {
+        *fLog << "FadcType:     " << fFadcType << " (";
+        switch (fFadcType)
+        {
+        case 1:      *fLog << "Siegen"; break;
+        case 2:      *fLog << "MUX"; break;
+        case 0xfac7: *fLog << "FACT DRS4"; break;
+        case 0xffff: *fLog << "artificial"; break;
+        default: *fLog << "unknown";
+        }
+        *fLog << ")" << endl;
+    }
+    *fLog << "ProjectName: '" << fProjectName << "'" << endl;
+    if (fFormatVersion>5)
+        *fLog << "Observation: '" << fObservationMode << "'" << endl;
+    if (fSourceName[0]!=0 || fSourceEpochChar[0]!=0 || fSourceEpochDate!=0)
+    {
+        *fLog << "Source:      '" << fSourceName << "' " << "  ";
+        *fLog << fSourceEpochChar << dec << fSourceEpochDate << endl;
+    }
+    if (fRunStart)
+        *fLog << "Run Start:    " << fRunStart << endl;
+    if (fRunStop)
+        *fLog << "Run Stop:     " << fRunStop << endl;
+    if (fNumCrates>0 || fNumPixInCrate>0)
+        *fLog << "Crates:       " << fNumCrates << " x " << fNumPixInCrate << " Pixel/Crate = " << fNumCrates*fNumPixInCrate << " Pixel/Evt" << endl;
+    if (GetNumConnectedPixels()>0)
+        *fLog << "Num Pixels:   " << GetNumNormalPixels() << " (normal) + " << GetNumSpecialPixels() << " (special) = " << GetNumConnectedPixels() << " (total)" << endl;
+    if (fFormatVersion>6)
+        *fLog << "Sampling:     " << fSamplingFrequency << "MHz with " << (int)fFadcResolution << " significant bits" << endl;
+    *fLog << "Samples:      " << fNumSamplesHiGain << "/" << fNumSamplesLoGain << " (hi/lo) * " << fNumBytesPerSample << "B/sample = ";
+    if (fNumCrates>0)
+        *fLog << (fNumSamplesLoGain+fNumSamplesHiGain) * fNumCrates * fNumPixInCrate * fNumBytesPerSample/1000 << "kB/Evt" << endl;
+    else
+        *fLog << (fNumSamplesLoGain+fNumSamplesHiGain) * fNumBytesPerSample << "B/pix" << endl;
+    if (fNumEvents>0 || fNumEventsRead>0)
+    {
+        *fLog << "Evt Counter:  " << fNumEvents;
+        if (fFormatVersion>8)
+            *fLog << " (read=" << fNumEventsRead << ")";
+        *fLog << endl;
+    }
+
+    if (TString(t).Contains("header", TString::kIgnoreCase))
+        return;
+
+    *fLog << inf3 << "Assignment:" << hex << endl;
+    for (int i=0; i<GetNumPixel(); i++)
+        *fLog << setfill('0') << setw(3) << (*fPixAssignment)[i] << " ";
+
+    *fLog << dec << setfill(' ') << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the assigned pixel number for the given FADC channel
+//
+Short_t MRawRunHeader::GetPixAssignment(UShort_t i) const
+{
+    // FIXME: Do we need a range check here?
+    return (Short_t)(*fPixAssignment)[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel which are markes as connected in the
+// pix assignment (!=0)
+//
+UShort_t MRawRunHeader::GetNumConnectedPixels() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    UShort_t rc = 0;
+    for (int i=0; i<num; i++)
+    {
+        if (GetPixAssignment(i)!=0)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel which are markes as connected and so-called
+// 'normal' pixels in the pix assignment (>0)
+//
+UShort_t MRawRunHeader::GetNumNormalPixels() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    UShort_t rc = 0;
+    for (int i=0; i<num; i++)
+    {
+        if (GetPixAssignment(i)>0)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel which are markes as connected and so-called
+// 'special' pixels in the pix assignment (<0)
+//
+UShort_t MRawRunHeader::GetNumSpecialPixels() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    UShort_t rc = 0;
+    for (int i=0; i<num; i++)
+    {
+        if (GetPixAssignment(i)<0)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the maximum id which exists in the pix assignment
+//
+UShort_t MRawRunHeader::GetMaxPixId() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    Short_t rc = 0;
+    for (int i=0; i<num; i++)
+        rc = TMath::Max(GetPixAssignment(i), rc);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return minus th minimum id which exists in the pix assignment
+//
+UShort_t MRawRunHeader::GetMinPixId() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    Short_t rc = 0;
+    for (int i=0; i<num; i++)
+        rc = TMath::Min(GetPixAssignment(i), rc);
+
+    return (UShort_t)-rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel in this event.
+//
+// WARNING: This is the number of pixels stored in this file which is
+//          a multiple of the number of pixels per crate and in general
+//          a number which is larger than the camera size!
+//
+//          To know the range of the pixel indices please use the geometry
+//          container!
+//
+UShort_t MRawRunHeader::GetNumPixel() const
+{
+    return fPixAssignment->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns absolute size in bytes of the run header as read from a raw file.
+// This must be done _after_ the header is read, because the header doesn't
+// have a fixed size (used in MRawSocketRead)
+//
+Int_t MRawRunHeader::GetNumTotalBytes() const
+{
+    switch (fFormatVersion)
+    {
+    case 1:
+        return 80+fNumCrates*fNumPixInCrate*2+16;
+    case 2:
+    case 3:
+    case 4:
+    case 5:
+        return 84+fNumCrates*fNumPixInCrate*2+16;
+    case 6:
+        return 84+fNumCrates*fNumPixInCrate*2+16 +4+78+58+60+8;
+    case 7:
+        return 84+fNumCrates*fNumPixInCrate*2+16 +4+78+58+60+8 +3-16;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Monte Carlo Interface
+//
+// This is a (prelimiary) way to setup an existing FADC system.
+//
+//  1: Siegen FADCs
+//  2: MUX FADCs
+//
+void MRawRunHeader::InitFadcType(UShort_t type)
+{
+    switch (type)
+    {
+    case 1:
+        fNumSamplesHiGain  =   15;
+        fNumSamplesLoGain  =   15;
+        fNumBytesPerSample =    1;    // number of bytes per sample
+        fSamplingFrequency =  300;    // Sampling Frequency [MHz]
+        fFadcResolution    =    8;    // number of significant bits
+        break;
+    case 2:
+        fNumSamplesHiGain  =   50;
+        fNumSamplesLoGain  =    0;
+        fNumBytesPerSample =    2;    // number of bytes per sample
+        fSamplingFrequency = 2000;    // Sampling Frequency [MHz]
+        fFadcResolution    =   12;    // number of significant bits
+        break;
+    case 3:
+        fNumSamplesHiGain  =  150;
+        fNumSamplesLoGain  =    0;
+        fNumBytesPerSample =    2;    // number of bytes per sample
+        fSamplingFrequency = 1000;    // Sampling Frequency [MHz]
+        fFadcResolution    =   12;    // number of significant bits
+        break;
+    }
+
+    fFadcType = type;
+}
+
+// --------------------------------------------------------------------------
+//
+// Monte Carlo Interface
+//
+//  Init a camera
+//
+void MRawRunHeader::InitCamera(UShort_t type, UShort_t pix)
+{
+    switch (type)
+    {
+    case 1:
+        fNumCrates     =   1;
+        fNumPixInCrate = 577;
+        break;
+    case 2:
+        fNumCrates     =   1;
+        fNumPixInCrate = 703;
+        break;
+    case (UShort_t)-1:
+        fNumCrates     =   1;
+        fNumPixInCrate = pix;
+        break;
+    }
+
+    fCameraVersion = type;
+
+    const Int_t n = fNumCrates*fNumPixInCrate;
+
+    fPixAssignment->Set(n);
+
+    for (int i=0; i<n; i++)
+        (*fPixAssignment)[i] = i+1;
+}
+
+void MRawRunHeader::InitFact(UShort_t num, UShort_t pix, UShort_t samples, UShort_t *map)
+{
+    fNumCrates     = num;
+    fNumPixInCrate = pix;
+    fCameraVersion = 0xfac7;
+    fFadcType      = 0xfac7;
+
+    fPixAssignment->Set(num*pix);
+
+    if (map)
+        for (int i=0; i<num*pix; i++)
+            (*fPixAssignment)[i] = map[i]+1;
+    else
+    {
+        for (int i=0; i<num*pix; i++)
+            (*fPixAssignment)[i] = i+1;
+    }
+
+    fNumSamplesHiGain  = samples;
+    fNumSamplesLoGain  = 0;
+    fNumBytesPerSample = 2;      // number of bytes per sample
+    fIsSigned          = kTRUE;
+    fSamplingFrequency = 2000;   // Sampling Frequency [MHz]
+    fFadcResolution    = 12;     // number of significant bits
+}
+
+// --------------------------------------------------------------------------
+//
+// Monte Carlo Interface
+//
+//  Set telescope number, run-number and file-number
+//
+void MRawRunHeader::SetRunInfo(UShort_t tel, UInt_t run, UInt_t file)
+{
+    fTelescopeNumber = tel;
+    fRunNumber       = run;
+    fFileNumber      = file;
+}
+
+// --------------------------------------------------------------------------
+//
+// Monte Carlo Interface
+//
+//  Set source-name, epoch (default J) and date (default 2000)
+//
+void MRawRunHeader::SetSourceInfo(const TString src, char epoch, UShort_t date)
+{
+    strncpy(fSourceName, src.Data(), 80);
+
+    fSourceEpochChar[0] = epoch;     // epoch char of the source
+    fSourceEpochDate    = date;      // epoch date of the source
+}
+
+// --------------------------------------------------------------------------
+//
+// Monte Carlo Interface
+//
+//  Set run-start and -stop time
+//
+void MRawRunHeader::SetRunTime(const MTime &start, const MTime &end)
+{
+    fRunStart = start;
+    fRunStop  = end;
+}
+
+// --------------------------------------------------------------------------
+//
+// Monte Carlo Interface
+//
+//  Set project name and observation mode
+//
+void MRawRunHeader::SetObservation(const TString mode, const TString proj)
+{
+    strncpy(fProjectName,     proj.Data(), 100);
+    strncpy(fObservationMode, mode.Data(),  60);
+}
+
+// --------------------------------------------------------------------------
+//
+// Monte Carlo Interface
+//
+//  Set number of events in file.
+//
+void MRawRunHeader::SetNumEvents(UInt_t num)
+{
+    fNumEvents     = num;
+    fNumEventsRead = num;
+}
+
+// --------------------------------------------------------------------------
+//
+//  NumSamples: 50
+//  NumBytePerSample: 2
+//  SamplingFrequency: 2000
+//  FadcResolution: 12
+//  FadcType: XXXX
+//
+Int_t MRawRunHeader::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "NumSamples", print))
+    {
+        rc = kTRUE;
+        fNumSamplesHiGain = GetEnvValue(env, prefix, "NumSamples", fNumSamplesHiGain);
+        fNumSamplesLoGain = 0;
+    }
+
+    if (IsEnvDefined(env, prefix, "NumBytesPerSample", print))
+    {
+        rc = kTRUE;
+        fNumBytesPerSample = GetEnvValue(env, prefix, "NumBytesPerSample", fNumBytesPerSample);
+    }
+
+    if (IsEnvDefined(env, prefix, "SamplingFrequency", print))
+    {
+        rc = kTRUE;
+        fSamplingFrequency = GetEnvValue(env, prefix, "SamplingFrequency", fSamplingFrequency);
+    }
+    
+    if (IsEnvDefined(env, prefix, "IsSigned", print))
+    {
+        rc = kTRUE;
+        fIsSigned = GetEnvValue(env, prefix, "IsSigned", fIsSigned);
+    }
+
+    if (IsEnvDefined(env, prefix, "FadcResolution", print))
+    {
+        rc = kTRUE;
+        fFadcResolution = GetEnvValue(env, prefix, "FadcResolution", fFadcResolution);
+    }
+    // Saturation behaviour etc.
+    if (IsEnvDefined(env, prefix, "FadcType", print))
+    {
+        //rc = kTRUE;
+        //TString type = GetEnvValue(env, prefix, "FadcType", "");
+        // Eval "Siegen", "MUX", Dwarf"
+    }
+    else
+        if (rc)
+            fFadcType = 0xffff; // "Artificial"
+
+    return rc;
+}
+
Index: branches/Mars_McMismatchStudy/mraw/MRawRunHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawRunHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawRunHeader.h	(revision 17960)
@@ -0,0 +1,194 @@
+#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,
+        kRTDominoCal   = 0x0003,
+        kRTLinearity   = 0x0004,
+        kRTPointRun    = 0x0007,
+        kRTMonteCarlo  = 0x0100,
+        kRTFact        = 0xfac7,
+        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;          // File type identifier
+
+    UInt_t    fHeaderSizeRun;        // Size of run header
+    UInt_t    fHeaderSizeEvt;        // Size of evt header
+    UInt_t    fHeaderSizeCrate;      // Size of crate header
+
+    UShort_t  fFormatVersion;        // File format version
+    UShort_t  fSoftVersion;          // DAQ software version
+    UShort_t  fFadcType;             // FADC type (1=Siegen, 2=MUX)
+    UShort_t  fCameraVersion;        // Camera Version (1=MAGIC I)
+    UShort_t  fTelescopeNumber;      // Telescope number (1=Magic I)
+    UShort_t  fRunType;              // Run Type
+    UInt_t    fRunNumber;            // Run number
+    UInt_t    fFileNumber;           // File number
+    Char_t    fProjectName[101];     // Project name
+    Char_t    fSourceName[81];       // Source name
+    Char_t    fObservationMode[61];  // observation mode
+    Char_t    fSourceEpochChar[4];   // epoch char of the source
+    UShort_t  fSourceEpochDate;      // epoch date of the source
+    UShort_t  fNumCrates;            // number of electronic boards
+    UShort_t  fNumPixInCrate;        // number of pixels in crate
+    UShort_t  fNumSamplesLoGain;     // number of logain samples stored
+    UShort_t  fNumSamplesHiGain;     // number of higain samples stored
+    UShort_t  fNumBytesPerSample;    // number of bytes per sample
+    Bool_t    fIsSigned;
+    UInt_t    fNumEvents;            // number of events stored
+    UInt_t    fNumEventsRead;        // number of events read by the electronics
+    UShort_t  fSamplingFrequency;    // Sampling Frequency [MHz]
+    Byte_t    fFadcResolution;       // number of significant bits
+    MTime     fRunStart;             // time of run start
+    MTime     fRunStop;              // time of run stop
+    MArrayS  *fPixAssignment;        //-> pixel assignment table
+
+    Bool_t SwapAssignment(Short_t id0, Short_t id1);
+    void   FixRunNumbers();
+    Bool_t FixAssignment();
+    Bool_t Fixes();
+    Bool_t IsConsistent() const;
+
+    Bool_t ReadEvtOld(std::istream& fin);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MRawRunHeader(const char *name=NULL, const char *title=NULL);
+    MRawRunHeader(const MRawRunHeader &h);
+    ~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 InitFadcType(UShort_t type);
+    void InitCamera(UShort_t type, UShort_t pix=0);
+    void InitPixels(UShort_t pix) { InitCamera((UShort_t)-1, pix); }
+    void InitFact(UShort_t num, UShort_t pix, UShort_t samples, UShort_t *map=0);
+    void SetRunType(UShort_t type) { fRunType=type; }
+    void SetRunInfo(UShort_t tel, UInt_t run, UInt_t file=0);
+    void SetFileNumber(UInt_t file) { fFileNumber=file; }
+    void SetSourceInfo(const TString src, char epoch='J', UShort_t date=2000);
+    void SetRunTime(const MTime &start, const MTime &end);
+    void SetRunTimeMjd(Float_t start, Float_t stop) { fRunStart.SetMjd(start); fRunStop.SetMjd(stop); }
+    void SetObservation(const TString mode, const TString proj);
+    void SetNumEvents(UInt_t num);
+    void SetValidMagicNumber() { fMagicNumber=kMagicNumber; }
+    void SetFormat(UShort_t file, UShort_t soft) { fFormatVersion=file; fSoftVersion=soft; }
+
+    // This is to get the numbers...
+    UShort_t GetMagicNumber() const       { return fMagicNumber; }
+    UInt_t   GetHeaderSizeEvt() const     { return fHeaderSizeEvt; }
+    UInt_t   GetHeaderSizeCrate() const   { return fHeaderSizeCrate; }
+    UShort_t GetFormatVersion() const     { return fFormatVersion; }
+    UShort_t GetSoftVersion() const       { return fSoftVersion; }
+    UShort_t GetCameraVersion() const     { return fCameraVersion; }
+    UInt_t   GetRunNumber() const         { return fRunNumber; }
+    UInt_t   GetFileNumber() const        { return fFileNumber; }
+    UInt_t   GetTypeID() const            { return (fRunNumber/1000000)%100; }
+    UInt_t   GetFileID() const            { return fRunNumber>1000000?(fRunNumber%1000000)*1000+(fFileNumber%1000):fRunNumber; }
+    TString  GetStringID() const;
+    UShort_t GetTelescopeNumber() const   { return fTelescopeNumber; }
+    UShort_t GetRunType() const           { return fRunType; }
+    const Char_t *GetRunTypeStr() const;
+          Char_t  GetRunTypeChar() const;
+    const Char_t *GetProjectName() const  { return fProjectName; }
+    const Char_t *GetSourceName() const   { return fSourceName; }
+    const Char_t *GetSourceEpocheChar() const { return fSourceEpochChar; }
+    const Char_t *GetObservationMode() const  { return fObservationMode; }
+    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   GetNumSamples() const        { return fNumSamplesHiGain+fNumSamplesLoGain; }
+    UShort_t GetNumBytesPerSample() const { return fNumBytesPerSample; }
+    Bool_t   IsSigned() const             { return fIsSigned; }
+    UInt_t   GetNumEvents() const         { return fNumEvents; }
+    UInt_t   GetNumEventsRead() const     { return fNumEventsRead; }
+    UShort_t GetFreqSampling() const      { return fSamplingFrequency; }
+    const MTime &GetRunStart() const      { return fRunStart; }
+    const MTime &GetRunEnd() const        { return fRunStop; }
+    Double_t GetRunLength() const         { return !fRunStart || !fRunStop ? 0 : fRunStop-fRunStart; }
+    Short_t GetPixAssignment(UShort_t i) const;
+    UShort_t GetMaxPixId() const;
+    UShort_t GetMinPixId() const;
+    UShort_t GetNumConnectedPixels() const;
+    UShort_t GetNumNormalPixels() const;
+    UShort_t GetNumSpecialPixels() const;
+    UInt_t   GetScale() const { switch (fNumBytesPerSample) { case 1: return 0x1; case 2: return 0x100; case 4: return 0x1000000; } return 0; }
+    UInt_t   GetMax() const { switch (fNumBytesPerSample) { case 1: return 0xff; case 2: return 0xffff; case 4: return 0xffffffff; } return 0; }
+
+    const MArrayS &GetPixAssignment() const { return *fPixAssignment; }
+
+    UInt_t GetNumSamplesPerCrate() const
+    {
+        return fNumPixInCrate*(fNumSamplesLoGain+fNumSamplesHiGain);
+    }
+
+    UShort_t GetNumPixel() const;
+    Int_t GetNumTotalBytes() const;
+
+    Bool_t IsValid() const { return fMagicNumber==0xc0c0 || fMagicNumber==0xc0c1; }
+    Bool_t IsMonteCarloRun() const { return fRunType>0x00ff; }
+    Bool_t IsDataRun() const        { return (fRunType&0xff)==kRTData; }
+    Bool_t IsPedestalRun() const    { return (fRunType&0xff)==kRTPedestal; }
+    Bool_t IsCalibrationRun() const { return (fRunType&0xff)==kRTCalibration; }
+    Bool_t IsPointRun() const       { return (fRunType&0xff)==kRTPointRun; }
+
+    Bool_t IsValidRun() const { return fRunType!=kRTNone; }
+
+    Bool_t IsConsistent(const MRawRunHeader &h) const;
+
+    void Print(Option_t *t=NULL) const;
+
+    Bool_t ReadEvt(std::istream& fin);
+    //Bool_t WriteEvt(ostream& fout) const;
+
+    ClassDef(MRawRunHeader, 12)	// storage container for general info
+};
+#endif
Index: branches/Mars_McMismatchStudy/mraw/MRawSocketRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawSocketRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawSocketRead.cc	(revision 17960)
@@ -0,0 +1,293 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRawSocketRead
+//
+//  This tasks reads the raw binary file like specified in the TDAS???
+//  and writes the data in the corresponding containers which are
+//  either retrieved from the parameter list or created and added.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MRawEvtData
+//   MRawCrateArray
+//   MTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawSocketRead.h"
+
+#include <stdlib.h>  // atoi
+
+#include <TArrayC.h> // TAraayC
+
+#include "MReadSocket.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MTime.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateData.h"
+#include "MRawCrateArray.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MRawSocketRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawSocketRead::MRawSocketRead(const char *name, const char *title)
+    : fIn(NULL), fPort(-1)
+{
+    fName  = name  ? name  : "MRawSocketRead";
+    fTitle = title ? title : "Task to read DAQ binary data from tcp/ip socket";
+
+    fIn = new MReadSocket;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream.
+//
+MRawSocketRead::~MRawSocketRead()
+{
+    delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the socket. This blocks until the connection has been established,
+// an error occured opening the connection or the user requested to
+// quit the application.
+//
+Bool_t MRawSocketRead::OpenSocket()
+{
+    if (fDisplay)
+        fDisplay->SetStatusLine2(Form("Waiting for connection on port #%d...", fPort));
+
+    //
+    // Open socket connection
+    //
+    while (1)
+    {
+        //
+        // If port could be opened eveything is ok
+        //
+        if (fIn->Open(fPort))
+            return kTRUE;
+
+        //
+        // If a MStatusDisplay is attached the user might have
+        // requested to quit the application
+        //
+        if (fDisplay)
+            switch (fDisplay->CheckStatus())
+            {
+            case MStatusDisplay::kFileClose:
+            case MStatusDisplay::kFileExit:
+                *fLog << inf << "MRawSocketRead::PreProcess - MStatusDisplay triggered exit." << endl;
+                return kFALSE;
+            default:
+                break;
+            }
+
+        //
+        // If an error occured during opening the socket stop
+        //
+        if (fIn->fail())
+            break;
+    }
+
+    *fLog << err << "ERROR - Cannot open port #" << fPort << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MRawRunHeader <output>   if not found it is created
+//   MRawEvtHeader <output>   if not found it is created
+//   MRawEvtData <output>     if not found it is created
+//   MRawCrateArray <output>  if not found it is created
+//   MTime <output>           if not found it is created
+//
+// If all containers are found or created the run header is read from the
+// binary file and printed.  If the Magic-Number (file identification)
+// doesn't match we stop the eventloop.
+//
+// Now the EvtHeader and EvtData containers are initialized.
+//
+Int_t MRawSocketRead::PreProcess(MParList *pList)
+{
+    if (!OpenSocket())
+        return kFALSE;
+
+    if (!MRawRead::PreProcess(pList))
+        return kFALSE;
+
+    fParList = pList;
+    fRunNumber = (UInt_t)-1;
+    fEvtNumber = (UInt_t)-1;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The Process reads one event from the binary file:
+//  - The event header is read
+//  - the run header is read
+//  - all crate information is read
+//  - the raw data information of one event is read
+//
+Int_t MRawSocketRead::Process()
+{
+    //
+    // Tag which could possibly be used for synchronizing the
+    // data stream. At the moment we check only its correctness.
+    // Synchronisation seems to work well - Why?
+    //
+    char dummy[4];
+    fIn->read(dummy, 4);   // \nEVT
+
+    if (!(dummy[0]=='\n' && dummy[1]=='E' && dummy[2]=='V' &&dummy[3]=='T'))
+    {
+        *fLog << warn << "EVT tag not found. Stream out of sync. Please try to restart..." << endl;
+        // FIXME: Synchronization missing...
+        return kFALSE;
+    }
+
+    //
+    // No we get some size information (each 5 bytes ascii)
+    //
+    char sizecc[6] = {0,0,0,0,0,0}; // 5 bytes plus trailing 0-byte
+    char sizerh[6] = {0,0,0,0,0,0}; // 5 bytes plus trailing 0-byte
+    char sizeev[6] = {0,0,0,0,0,0}; // 5 bytes plus trailing 0-byte
+    fIn->read(sizecc, 5); // Size CC info string
+    fIn->read(sizerh, 5); // Size run header
+    fIn->read(sizeev, 5); // Size Event (+ event header)
+
+    //
+    // Currently we skip the CC info string. We may decode this string
+    // in the future to get additional information
+    //
+    TArrayC dummy2(atoi(sizecc));
+    fIn->read(dummy2.GetArray(), dummy2.GetSize());
+
+    //
+    // Read RUN HEADER (see specification) from input stream
+    //
+    fLog->SetNullOutput();
+    const Bool_t rc = fRawRunHeader->ReadEvt(*fIn);
+    fLog->SetNullOutput(kFALSE);
+
+    if (!rc)
+    {
+        *fLog << err << "Reading MRawRunHeader failed." << endl;
+        return kFALSE;
+    }
+
+    if (fRunNumber!=fRawRunHeader->GetRunNumber())
+    {
+        fRawRunHeader->Print();
+
+        MTaskList *tlist = (MTaskList*)fParList->FindObject("MTaskList");
+        if (!tlist)
+        {
+            *fLog << err << dbginf << "ERROR - Task List not found in Parameter List." << endl;
+            return kFALSE;
+        }
+
+        if (!tlist->ReInit())
+            return kFALSE;
+
+        fRunNumber = fRawRunHeader->GetRunNumber();
+    }
+
+    if (atoi(sizerh)==fRawRunHeader->GetNumTotalBytes())
+    {
+        *fLog << err << "Retrieved size of run header mismatch... stopped." << endl;
+        return kFALSE;
+    }
+
+    if (atoi(sizeev)==0)
+    {
+        *fLog << dbg << "Event contains only run header information... skipped." << endl;
+        return kCONTINUE;
+    }
+
+    *fRawEvtTime = fRawRunHeader->GetRunStart();
+
+    //
+    // Give the run header information to the 'sub-classes'
+    // Run header must be valid!
+    //
+    fRawEvtHeader->InitRead(fRawRunHeader, fRawEvtTime);
+    fRawEvtData1 ->InitRead(fRawRunHeader);
+    fRawEvtData2 ->InitRead(fRawRunHeader);
+
+    if (!ReadEvent(*fIn))
+        return kFALSE;
+
+    //
+    // If no new event was recorded the DAQ resends an old event
+    //
+    if (fEvtNumber==fRawEvtHeader->GetDAQEvtNumber())
+    {
+        *fLog << dbg << "Event number #" << dec << fEvtNumber << " didn't change... skipped." << endl;
+        return kCONTINUE;
+    }
+
+    fEvtNumber=fRawEvtHeader->GetDAQEvtNumber();
+
+    return kTRUE;
+}
+
+Int_t MRawSocketRead::PostProcess()
+{
+    //
+    // Close Socket connection
+    //
+    fIn->Close();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mraw/MRawSocketRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/MRawSocketRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/MRawSocketRead.h	(revision 17960)
@@ -0,0 +1,38 @@
+#ifndef MARS_MRawSocketRead
+#define MARS_MRawSocketRead
+
+#ifndef MARS_MRawRead
+#include "MRawRead.h"
+#endif
+
+class MReadSocket;
+
+class MRawSocketRead : public MRawRead
+{
+private:
+    MReadSocket *fIn;         //! buffered input stream (file to read from)
+    MParList    *fParList;    //!
+
+    UInt_t       fRunNumber;  //!
+    UInt_t       fEvtNumber;  //!
+
+    Int_t        fPort;       // Port on which we wait for the connection
+
+    Bool_t OpenSocket();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MRawSocketRead(const char *name=NULL, const char *title=NULL);
+    ~MRawSocketRead();
+
+    void SetPort(int port) { fPort = port; }
+
+    TString GetFullFileName() const { return "<socket>"; }
+
+    ClassDef(MRawSocketRead, 0)	//Task to read DAQ binary data from tcp/ip socket
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mraw/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mraw/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/Makefile	(revision 17960)
@@ -0,0 +1,41 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Raw
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mfileio -I../mcalib -I../mcore
+# mgui (MCamEvent), mgeom(MGeomCam)
+
+SRCFILES = MRawRunHeader.cc \
+	   MRawEvtHeader.cc \
+	   MRawEvtData.cc \
+	   MRawEvtPixelIter.cc \
+	   MRawCrateArray.cc \
+	   MRawCrateData.cc \
+	   MRawBoardsFACT.cc \
+           MRawRead.cc \
+           MRawFileRead.cc \
+           MRawFitsRead.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mraw/RawIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/RawIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/RawIncl.h	(revision 17960)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mraw/RawLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mraw/RawLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mraw/RawLinkDef.h	(revision 17960)
@@ -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 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 MRawBoardsFACT+;
+
+#pragma link C++ class MRawRead+;
+#pragma link C++ class MRawFileRead+;
+#pragma link C++ class MRawFitsRead+;
+//#pragma link C++ class MRawSocketRead+;
+//#pragma link C++ class MRawFileWrite+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mreflector/MHReflector.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MHReflector.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MHReflector.cc	(revision 17960)
@@ -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): Thomas Bretz, 2/2007 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHReflector
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHReflector.h"
+
+#include <TMath.h>
+#include <TLegend.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MString.h"
+
+#include "MGeomCam.h"
+
+#include "MRflEvtData.h"
+#include "MRflEvtHeader.h"
+
+
+ClassImp(MHReflector);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates and initializes the histograms
+//
+MHReflector::MHReflector(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHReflector";
+    fTitle = title ? title : "Histogram for the reflected photons";
+
+    fHistXY.SetName("ReflXY");
+    fHistXY.SetTitle("Histogram vs X/Y and Energy");
+    fHistXY.SetXTitle("X [\\circ]");
+    fHistXY.SetYTitle("Y [\\circ]");
+    fHistXY.SetZTitle("E [GeV]");
+    fHistXY.SetDirectory(NULL);
+    fHistXY.Sumw2();
+
+    fHistRad.SetName("ReflRad");
+    fHistRad.SetTitle("Histogram vs Radius and Energy");
+    fHistRad.SetXTitle("E [GeV]");
+    fHistRad.SetYTitle("R [\\circ]");
+    fHistRad.SetZTitle("Cnts/deg^{2}");
+    fHistRad.SetDirectory(NULL);
+    fHistRad.Sumw2();
+
+    fHistSize.SetName("ReflSize");
+    fHistSize.SetTitle("Histogram vs Size and Energy");
+    fHistSize.SetXTitle("E [GeV]");
+    fHistSize.SetYTitle("N\\gamma");
+    fHistSize.SetZTitle("Cnts");
+    fHistSize.SetDirectory(NULL);
+    fHistSize.Sumw2();
+
+    MBinning binse, binsd, binsr;
+    binse.SetEdgesLog(2*5, 10, 1000000);
+    binsd.SetEdges(50, -2.5, 2.5);
+    binsr.SetEdges(15, 0, 2.5);
+
+    SetBinning(&fHistXY,   &binsd, &binsd, &binse);
+    SetBinning(&fHistRad,  &binse, &binsr);
+    SetBinning(&fHistSize, &binse, &binse);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for MRflEvtData, MRflEvtHeader and MGeomCam
+//
+Bool_t MHReflector::SetupFill(const MParList *pList)
+{
+    fHeader = (MRflEvtHeader*)pList->FindObject("MRflEvtHeader");
+    if (!fHeader)
+    {
+        *fLog << err << "MRflEvtHeader not found... abort." << endl;
+        return kFALSE;
+    }
+    fData = (MRflEvtData*)pList->FindObject("MRflEvtData");
+    if (!fData)
+    {
+        *fLog << err << "MRflEvtData not found... abort." << endl;
+        return kFALSE;
+    }
+
+    MGeomCam *geom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = geom->GetConvMm2Deg();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill position and radius versus energy
+//
+#include "MRflSinglePhoton.h"
+Int_t MHReflector::Fill(const MParContainer *par, const Stat_t weight)
+{
+    const Double_t energy = fHeader->GetEnergy();
+
+    const Int_t n = fData->GetNumPhotons();
+
+    fHistSize.Fill(energy, n);
+
+    for (int i=0; i<n; i++)
+    {
+        const MRflSinglePhoton &ph = fData->GetPhoton(i);
+
+        const Double_t x = ph.GetX()*fMm2Deg;
+        const Double_t y = ph.GetY()*fMm2Deg;
+        const Double_t r = TMath::Hypot(x, y);
+        const Double_t U = r*TMath::TwoPi();
+
+        if (U==0)
+            continue;
+
+        fHistRad.Fill(energy, r, weight/U);
+        //fHistXY.Fill(x, y, energy);
+    }
+
+    //fData->FillRad(fHistRad, energy/*x*/, fMm2Deg);
+    //fData->Fill(fHistXY,     energy/*z*/, fMm2Deg);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale radial histogram with area
+//
+Bool_t MHReflector::Finalize()
+{
+    /*
+    const TAxis &axey = *fHistRad.GetYaxis();
+    for (int y=1; y<=fHistRad.GetNbinsY(); y++)
+    {
+        const Double_t lo = axey.GetBinLowEdge(y);
+        const Double_t hi = axey.GetBinLowEdge(y+1);
+
+        const Double_t A = (hi*hi-lo*lo)*TMath::Pi()*TMath::Pi();
+
+        for (int x=1; x<=fHistRad.GetNbinsX(); x++)
+            fHistRad.SetBinContent(x, y, fHistRad.GetBinContent(x, y)/A);
+    }
+    */
+    return kTRUE;
+}
+
+#include "../mmc/MMcEvt.hxx"
+void MHReflector::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    pad->Divide(3,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    fHistRad.Draw("colz");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    TH1 *h = fHistRad.ProjectionY("ProfRad", -1, -1, "e");
+    h->SetTitle("RadialProfile");
+    h->SetDirectory(NULL);
+    h->SetBit(kCanDelete);
+    h->SetLineWidth(2);
+    h->SetLineColor(kBlue);
+    h->SetStats(kFALSE);
+    h->Draw("");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    h = fHistSize.ProjectionY("ProfSize", -1, -1, "e");
+    h->SetTitle("Size distribution");
+    h->SetDirectory(NULL);
+    h->SetBit(kCanDelete);
+    h->SetLineColor(kBlue);
+    h->SetLineWidth(2);
+    h->SetStats(kFALSE);
+    h->Draw("");
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+
+    TLegend *leg = new TLegend(0.01, 0.01, 0.99, 0.99, "Energy Range");
+    for (int i=1; i<=fHistRad.GetNbinsX(); i++)
+    {
+        h = fHistRad.ProjectionY(MString::Format("ProjRad%d", i), i, i, "e");
+        h->SetDirectory(NULL);
+        h->SetBit(kCanDelete);
+        h->SetLineWidth(2);
+        h->SetStats(kFALSE);
+        h->Draw(i==1?"":"same");
+        if (i==1)
+            h->SetTitle("Radial Profile");
+
+        const Float_t xlo = fHistRad.GetXaxis()->GetBinLowEdge(i);
+        const Float_t xhi = fHistRad.GetXaxis()->GetBinUpEdge(i);
+
+        const TString lo = MMcEvt::GetEnergyStr(xlo);
+        const TString hi = MMcEvt::GetEnergyStr(xhi);
+
+        leg->AddEntry(h, MString::Format("%s - %s", lo.Data(), hi.Data()));
+    }
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    leg->SetBit(kCanDelete);
+    leg->Draw();
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+
+    gPad->SetLogx();
+    gPad->SetLogy();
+
+    for (int i=1; i<=fHistSize.GetNbinsX(); i++)
+    {
+        h = fHistSize.ProjectionY(MString::Format("ProjSize%d", i), i, i, "e");
+        h->SetDirectory(NULL);
+        h->SetBit(kCanDelete);
+        h->SetLineWidth(2);
+        h->SetStats(kFALSE);
+        h->Draw(i==1?"":"same");
+        if (i==1)
+            h->SetTitle("Size distribution");
+    }
+}
+
+void MHReflector::Paint(Option_t *opt)
+{
+    TVirtualPad *pad = gPad;
+
+    pad->cd(1);
+    SetPalette("pretty");
+
+    TH1 *h=0;
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    if (gPad->FindObject("ProfRad"))
+    {
+        h = fHistRad.ProjectionY("ProfRad", -1, -1, "e");
+        h->Scale(1./h->Integral());
+    }
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    if (gPad->FindObject("ProfSize"))
+    {
+        h = fHistSize.ProjectionY("ProfSize", -1, -1, "e");
+        h->Scale(1./h->Integral());
+    }
+
+    pad->cd(5);
+
+    for (int i=1; i<=fHistRad.GetNbinsX(); i++)
+    {
+        const TString name = MString::Format("ProjRad%d", i);
+        if (!gPad->FindObject(name))
+            continue;
+
+        h = fHistRad.ProjectionY(name, i, i, "e");
+        h->SetLineColor(i);
+        h->Scale(1./fHistRad.Integral());
+        if (i==1)
+            h->SetMaximum(fHistRad.GetMaximum()/fHistRad.Integral()*1.05);
+    }
+
+    pad->cd(6);
+
+    for (int i=1; i<=fHistRad.GetNbinsX(); i++)
+    {
+        const TString name = MString::Format("ProjSize%d", i);
+        if (!gPad->FindObject(name))
+            continue;
+
+        h = fHistSize.ProjectionY(name, i, i, "e");
+        h->SetLineColor(i);
+        h->Scale(1./fHistSize.Integral());
+        if (i==1)
+        {
+            h->SetMaximum(TMath::Power(fHistSize.GetMaximum()/fHistSize.Integral(), 1.05));
+            h->SetMinimum(TMath::Power(fHistSize.GetMinimum(0)/fHistSize.Integral(), 0.95));
+        }
+    }
+
+}
Index: branches/Mars_McMismatchStudy/mreflector/MHReflector.h
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MHReflector.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MHReflector.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MHReflector
+#define MARS_MHReflector
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+class MRflEvtData;
+class MRflEvtHeader;
+
+class MHReflector : public MH
+{
+private:
+    MRflEvtData   *fData;   //!
+    MRflEvtHeader *fHeader; //!
+
+    Double_t fMm2Deg;
+
+    TH3D fHistXY;
+    TH2D fHistRad;
+    TH2D fHistSize;
+
+    Bool_t SetupFill(const MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t weight=1);
+    Bool_t Finalize();
+
+public:
+    MHReflector(const char *name=0, const char *title=0);
+
+    TH2D *GetHistRad() { return &fHistRad; }
+    TH3D *GetHistXY()  { return &fHistXY; }
+
+    void Draw(Option_t *o="");
+    void Paint(Option_t *o="");
+
+    ClassDef(MHReflector, 1)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreflector/MRflEvtData.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflEvtData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflEvtData.cc	(revision 17960)
@@ -0,0 +1,239 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 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 "MGeomCam.h"
+#include "MGeomPix.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";
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy constructor which copies the contents of dat into the new object
+//
+MRflEvtData::MRflEvtData(const MRflEvtData &dat)
+   : fList("MRflSinglePhoton", 0), fPos(0)
+{
+    MRflSinglePhoton *ph=NULL;
+
+    TIter Next(&dat.fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+        new (fList[fPos++]) MRflSinglePhoton(*ph);
+}
+
+// --------------------------------------------------------------------------
+//
+// Clone function producing a clone of this. A pointer to the clone is
+// returned.
+//
+TObject *MRflEvtData::Clone(Option_t *) const
+{
+    return new MRflEvtData(*this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the i-th MRflSinglePhoton. Be carefull the result is not
+// range checked!
+//
+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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills all photon distances scaled with scale (default=1) into a TH1
+//
+void MRflEvtData::FillRad(TH1 &hist, Float_t scale) const
+{
+    MRflSinglePhoton *ph=NULL;
+
+    TIter Next(&fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+        ph->FillRad(hist, scale);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills all photon distances scaled with scale (default=1) versus x
+// into a TH2
+//
+void MRflEvtData::FillRad(TH2 &hist, Double_t x, Float_t scale) const
+{
+    MRflSinglePhoton *ph=NULL;
+
+    TIter Next(&fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+        ph->FillRad(hist, x, scale);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills all photons (x,y) scaled with scale (default=1) into a TH2.
+//
+void MRflEvtData::Fill(TH2 &hist, Float_t scale) const
+{
+    MRflSinglePhoton *ph=NULL;
+
+    TIter Next(&fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+        ph->Fill(hist, scale);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills all photons (x,y) scaled with scale (default=1) versus z into a TH3
+//
+void MRflEvtData::Fill(TH3 &hist, Double_t z, Float_t scale) const
+{
+    MRflSinglePhoton *ph=NULL;
+
+    TIter Next(&fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+        ph->Fill(hist, z, scale);
+}
+
+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;
+
+    MRflSinglePhoton *ph=NULL;
+
+    TIter Next(&fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+        if (cam[idx].IsInside(ph->GetX(), ph->GetY()))
+            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: branches/Mars_McMismatchStudy/mreflector/MRflEvtData.h
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflEvtData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflEvtData.h	(revision 17960)
@@ -0,0 +1,56 @@
+#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 TH1;
+class TH2;
+class TH3;
+
+class MRflSinglePhoton;
+
+class MRflEvtData : public MParContainer, public MCamEvent
+{
+    TClonesArray fList;
+    Int_t fPos;
+
+public:
+    MRflEvtData(const char *name=NULL, const char *title=NULL);
+    MRflEvtData(const MRflEvtData &dat);
+
+    TObject *Clone(Option_t *) const;
+
+    void Reset() { fPos = 0; }
+
+    Int_t GetNumPhotons() const { return fList.GetEntriesFast(); }
+
+    MRflSinglePhoton &GetNewPhoton();
+    void FixSize();
+
+    const MRflSinglePhoton &GetPhoton(Int_t i) const;
+
+    void FillRad(TH1 &hist, Float_t scale=1) const;
+    void FillRad(TH2 &hist, Double_t x, Float_t scale=1) const;
+    void Fill(TH2 &hist, Float_t scale=1) const;
+    void Fill(TH3 &hist, Double_t z, Float_t scale=1) 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: branches/Mars_McMismatchStudy/mreflector/MRflEvtHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflEvtHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflEvtHeader.cc	(revision 17960)
@@ -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): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRflEvtHeader
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRflEvtHeader.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRflEvtHeader);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MRflEvtHeader::MRflEvtHeader(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MRflEvtHeader";
+    fTitle = title ? title : "Event header information from a reflector event";
+}
+
+void MRflEvtHeader::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Event Number:                " << fEvtNumber << endl;
+    *fLog << "Energy:                      " << fEnergy << "GeV" << endl;
+    *fLog << "Height of first intercation: " << fHeightFirstInt << "cm" << endl;
+    *fLog << "Momentum X/Y/Z:              " << fMomentum.X() << "/" << fMomentum.Y() << "/" << fMomentum.Z() << endl;
+    *fLog << "Zenith/Azimuth angle:        " << fTheta*TMath::RadToDeg() << "/" << fPhi*TMath::RadToDeg() << endl;
+    *fLog << endl;
+}
Index: branches/Mars_McMismatchStudy/mreflector/MRflEvtHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflEvtHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflEvtHeader.h	(revision 17960)
@@ -0,0 +1,90 @@
+#ifndef MARS_MRflEvtHeader
+#define MARS_MRflEvtHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+class MRflEvtHeader : public MParContainer
+{
+    Int_t fEvtNumber;
+
+    Float_t fEnergy;         // [GeV] of primary
+
+    TVector3 fMomentum;      // versor of momentum of primary
+    TVector2 fCorePosition;  // shower core position on ground
+
+    Float_t fHeightFirstInt; // [cm] z coordinate (height) of first interaction
+
+    Float_t fPhi;            // Phi of the telescope
+    Float_t fTheta;          // Theta of the telescope [rad]
+
+    Float_t fNmax;           // number of particles in shower maximum fitted by CORSIKA
+    Float_t fT0;             // depth of first interaction point fitted by CORSIKA
+    Float_t fTmax;           // depth of the shower maximum fitted by CORSIKA
+    Float_t fChi2;           // quality of the fit to longit shower development
+
+    /* Now follow the fraction of photons reaching the camera produced by  *
+     * electrons, muons and other particles respectively:                  */
+    Float_t fEFraction;      // elec_cph_fraction
+    Float_t fMFraction;      // muon_cph_fraction
+    Float_t fOFraction;      // other_cph_fraction
+
+public:
+    MRflEvtHeader(const char *name=NULL, const char *title=NULL);
+
+    // Getter
+    Int_t GetEvtNumber() const { return fEvtNumber; }
+
+    Float_t GetEnergy() const { return fEnergy; }
+
+    const TVector3 &GetMomentum() const { return fMomentum; }
+    const TVector2 &GetCorePosition() const { return fCorePosition; }
+
+    Float_t GetHeightFirstInt() const { return fHeightFirstInt; }
+
+    Float_t GetPhi() const   { return fPhi; }
+    Float_t GetTheta() const { return fTheta; }
+
+    Float_t GetNmax() const  { return fNmax; }
+    Float_t GetT0() const    { return fT0; }
+    Float_t GetTmax() const  { return fTmax; }
+    Float_t GetChi2() const  { return fChi2; }
+
+    Float_t GetEFraction() const { return fEFraction; }
+    Float_t GetMFraction() const { return fMFraction; }
+    Float_t GetOFraction() const { return fOFraction; }
+
+    // Setter
+    void SetEvtNumber(Int_t n) { fEvtNumber = n; }
+    void SetEnergy(Float_t x) { fEnergy = x; }
+    void SetMomentum(const TVector3 &v) { fMomentum = v; }
+    void SetCorePosition(const TVector2 &v) { fCorePosition = v; }
+
+    void SetMomentum(Float_t px, Float_t py, Float_t pz) { fMomentum = TVector3(px, py, pz); }
+    void SetCorePosition(Float_t cx, Float_t cy) { fCorePosition = TVector2(cx, cy); }
+    void SetHeightFirstInt(Float_t x) { fHeightFirstInt = x; }
+
+    void SetPhi(Float_t x)   { fPhi = x; }
+    void SetTheta(Float_t x) { fTheta = x; }
+
+    void SetNmax(Float_t x)  { fNmax = x ; }
+    void SetT0(Float_t x)    { fT0 = x; }
+    void SetTmax(Float_t x)  { fTmax = x ; }
+    void SetChi2(Float_t x)  { fChi2 = x ; }
+
+    void SetEFraction(Float_t x) { fEFraction = x ; }
+    void SetMFraction(Float_t x) { fMFraction = x ; }
+    void SetOFraction(Float_t x) { fOFraction = x ; }
+
+    // TObject
+    void Print(Option_t *o="") const;
+
+    ClassDef(MRflEvtHeader, 1) // Header of an event from the reflector program
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreflector/MRflRunHeader.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflRunHeader.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflRunHeader.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mreflector/MRflRunHeader.h
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflRunHeader.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflRunHeader.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mreflector/MRflSinglePhoton.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflSinglePhoton.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflSinglePhoton.cc	(revision 17960)
@@ -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, 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 <TMath.h>
+
+#include <TH2.h>
+#include <TH3.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRflSinglePhoton);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Fill radial photon distance scaled by scale into 1D histogram.
+//
+void MRflSinglePhoton::FillRad(TH1 &hist, Float_t scale) const
+{
+    hist.Fill(TMath::Hypot(fX, fY)*scale);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill radial photon distance scaled by scale versus x into 2D histogram.
+//
+void MRflSinglePhoton::FillRad(TH2 &hist, Double_t x, Float_t scale) const
+{
+    hist.Fill(x, TMath::Hypot(fX, fY)*scale);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill photon position (x,y) scaled by scale into 2D histogram.
+//
+void MRflSinglePhoton::Fill(TH2 &hist, Float_t scale) const
+{
+    hist.Fill(fX*scale, fY*scale);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill photon position (x,y) scaled by scale versus z into 3D histogram.
+//
+void MRflSinglePhoton::Fill(TH3 &hist, Double_t z, Float_t scale) const
+{
+    hist.Fill(fX*scale, fY*scale);
+}
+
+// --------------------------------------------------------------------------
+//
+// Dump all photon information
+//
+void MRflSinglePhoton::Print(Option_t *o) const
+{
+    *fLog << all << "x=" << fX << " y=" << fY << endl;
+}
Index: branches/Mars_McMismatchStudy/mreflector/MRflSinglePhoton.h
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/MRflSinglePhoton.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/MRflSinglePhoton.h	(revision 17960)
@@ -0,0 +1,51 @@
+#ifndef MARS_MRflSinglePhoton
+#define MARS_MRflSinglePhoton
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TH1;
+class TH2;
+class TH3;
+
+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:
+    MRflSinglePhoton() { }
+    MRflSinglePhoton(const MRflSinglePhoton &ph)
+        : fX(ph.fX), fY(ph.fY), fCosU(ph.fCosU), fCosV(ph.fCosV),
+        fTime(ph.fTime), fHeight(ph.fHeight), fPhi(ph.fPhi)
+    {
+    }
+
+    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 FillRad(TH1 &hist, Float_t scale=1) const;
+    void FillRad(TH2 &hist, Double_t x, Float_t scale=1) const;
+    void Fill(TH2 &hist, Float_t scale=1) const;
+    void Fill(TH3 &hist, Double_t z, Float_t scale=1) const;
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MRflSinglePhoton, 0) // Single Photon of a event from the reflector program
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreflector/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/Makefile	(revision 17960)
@@ -0,0 +1,35 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Reflector
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mhbase
+
+SRCFILES = MRflEvtData.cc \
+	   MRflEvtHeader.cc \
+	   MRflRunHeader.cc \
+	   MRflSinglePhoton.cc \
+	   MHReflector.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mreflector/ReflectorIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/ReflectorIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/ReflectorIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mreflector/ReflectorLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mreflector/ReflectorLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreflector/ReflectorLinkDef.h	(revision 17960)
@@ -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 MRflEvtData+;
+#pragma link C++ class MRflEvtHeader+;
+#pragma link C++ class MRflRunHeader+;
+#pragma link C++ class MRflSinglePhoton+;
+
+#pragma link C++ class MHReflector+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReport.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReport.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReport.cc	(revision 17960)
@@ -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, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReport
+//
+//  This is a base class for all reports comming from subsystems stored in
+//  a report file.
+//
+//
+// Due to wrong assignment by arehucas the veriosn number for some
+// cases is replaced.
+//
+//   Old Version | MjdMin  | MjdMax  | New Version
+//  -------------+---------+---------+-------------
+//    see MReport::Interprete()
+//
+//  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;
+
+// --------------------------------------------------------------------------
+//
+// Copy fState and fTime
+//
+void MReport::Copy(TObject &obj) const
+{
+    MReport &rep = static_cast<MReport&>(obj);
+
+    rep.fState = fState;
+
+    if (rep.fTime && fTime)
+        *rep.fTime = *fTime;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the given TString begins with the given tag. Remove
+// the tag from the string.
+//
+Bool_t MReport::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 Tag
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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_t ver)
+{
+    int len, state;
+    int yea, mon, day, hor, min, sec, ms;
+
+    TString fmt(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");
+
+    // M1/M2 telescope number (FIXME: Readout, check?)
+    if (ver>=200805190)
+        fmt.Prepend(" %*c%*d");
+
+    int n = sscanf(str.Data(), fmt.Data(),
+                   &state, &yea, &mon, &day, &hor, &min, &sec, &ms, &len);
+    if (n!=8)
+    {
+        *fLog << err << "ERROR - Cannot interprete header of " << fIdentifier << " (n=" << n << ")" << endl;
+        return kFALSE;
+    }
+
+    if (ms==1000)
+    {
+        *fLog << warn << "WARNING - Milliseconds in timestamp of " << fIdentifier;
+        *fLog << Form(" %d.%d.%d %02d:%02d:%02d.%03d", day, mon, yea, hor, min, sec, ms);
+        *fLog << " reset to 999." << endl;
+        ms = 999;
+    }
+
+    fState=state;
+    if (!fTime->Set(yea, mon, day, hor, min, sec, ms))
+    {
+        *fLog << err << "ERROR - Event " << fIdentifier << " has invalid time ";
+        *fLog << Form("%d.%d.%d %02d:%02d:%02d.%03d", day, mon, yea, hor, min, sec, ms);
+        *fLog << "... abort." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, len);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Report Body must be overwritten. It will get the line idetified to belong
+// to fIdentifier without the leading status and time infomration as an
+// argument.
+//
+Int_t MReport::InterpreteBody(TString &str, Int_t ver)
+{
+    *fLog << warn << "No interpreter existing for: " << fIdentifier << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprets Header and Body of a report file line. Calls SetReadyToSave()
+// in case the interpretation was successfull. And fTime->SetReadyToSave()
+// when a corresponding time container exists.
+//
+// SetupReading must be called successfully before.
+//
+// Due to wrong assignment by arehucas the veriosn number for some
+// cases is replaced.
+//
+//   Old Version | MjdMin  | MjdMax  | New Version
+//  -------------+---------+---------+-------------
+//    200504130  | 53548.0 | 53567.0 |  200506300
+//    200503170  | 53446.5 | 53447.5 |  200502240
+//    200508290  | 53643.5 |         |  200509300
+//    200510250  | 53801.5 | 53813.5 |  200603080
+//    200510250  | 53813.5 |         |  200603190
+//    200604010  | 53863.5 |         |  200605080
+//    200805190  | 54711.5 |         |  200809030
+//    200812040  | 54814.5 |         |  200812140
+//    200902210  | 54968.5 |         |  200905170
+//
+Int_t MReport::Interprete(TString &str, const MTime &start, const MTime &stop, Int_t ver)
+{
+    // Interprete header (time, status, etc) of report
+    if (!InterpreteHeader(str, ver))
+        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;
+
+    // Due to wrong assignment by arehucas the veriosn number for some
+    // cases is replaced.
+    if (ver==200504130 && GetMjd()>53548 && GetMjd()<53567)
+        ver=200506300;
+
+    if (ver==200503170 && GetMjd()>53446.5 && GetMjd()<53447.5)
+        ver=200502240;
+
+    if (ver==200508290 && GetMjd()>53643.5)
+        ver=200509300;
+
+    if (ver==200510250 && GetMjd()>53801.5 && GetMjd()<53813.5)
+        ver=200603080;
+
+    if (ver==200510250 && GetMjd()>53813.5)
+        ver=200603190;
+
+    if (ver==200604010 && GetMjd()>53864.5)
+        ver=200605080;
+
+    if (ver==200805190 && GetMjd()>54711.5)
+        ver=200809030;
+
+    if (ver==200812040 && GetMjd()>54814.5)
+        ver=200812140;
+
+    if (ver==200902210 && GetMjd()>54968.5)
+        ver=200905170;
+
+    // Interprete body (contents) of report
+    const Int_t rc = InterpreteBody(str, ver);
+    if (rc != kTRUE)
+        return rc;
+
+    SetReadyToSave();
+    fTime->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the existance of a corresponding MTime in the given parameter
+// list. If it is not found a new one will be created. The name of the
+// MTime object is created by taking the ClassName() of the derived MReport
+// class and stripping the leading MReport
+//
+Bool_t MReport::SetupReading(MParList &plist)
+{
+    fTime = NULL;
+
+    TString id(ClassName());
+    if (!id.BeginsWith("MReport"))
+    {
+        *fLog << warn << " WARNING - Class name '" << id << "' ";
+        *fLog << " doesn't begin with 'MReport'... no MTime assigned." << endl;
+        return kFALSE;
+    }
+
+    id.Remove(0, 7);
+    if (id.IsNull())
+    {
+        *fLog << warn << " WARNING - No postfix existing... no MTime assigned." << endl;
+        return kFALSE;
+    }
+
+    id.Prepend("MTime");
+
+    fTime = (MTime*)plist.FindCreateObj("MTime", id);
+    if (!fTime)
+        return kFALSE;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReport.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReport.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReport.h	(revision 17960)
@@ -0,0 +1,63 @@
+#ifndef MARS_MReport
+#define MARS_MReport
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class fits;
+
+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, Int_t ver);
+
+protected:
+    Bool_t CheckTag(TString &str, const char *tag) const;
+
+    void Copy(TObject &obj) const;
+
+public:
+    MReport(const char *id, Bool_t time=kTRUE) : fIdentifier(id), fHasReportTime(time), fState(0xff), fTime(0) { }
+
+    virtual Bool_t SetupReading(MParList &plist);
+    virtual Bool_t SetupReadingFits(fits &) { return kTRUE; }
+    virtual Int_t  InterpreteBody(TString &str, Int_t ver);
+
+    Int_t  Interprete(TString &str, const MTime &start, const MTime &stop, const Int_t ver);
+    virtual Int_t  InterpreteFits(const fits &) { return kTRUE; }
+    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; }
+    Double_t GetMjd() const { return fTime ? fTime->GetMjd() : -1; }
+
+    MTime *GetTime() { return fTime; }
+
+    ClassDef(MReport, 1) // Base class for control reports
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportCC.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportCC.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportCC.cc	(revision 17960)
@@ -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, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  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
+//
+// Class Version 2:
+// ----------------
+//  +  Float_t fUPSStatus; // arbitrary units (still not properly defined)
+//  +  Float_t fDifRubGPS; // [us] Difference between the Rubidium clock time and the time provided by the GPS receiver
+//
+// Class Version 3:
+// ----------------
+//  * Moved weather data to new base class
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportCC.h"
+
+#include "fits.h"
+
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MReportRec.h"
+
+#include "MCameraTH.h"
+#include "MCameraTD.h"
+#include "MCameraRecTemp.h"
+
+ClassImp(MReportWeather);
+ClassImp(MReportCC);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "CC-REPORT" Report
+// is expected to have no 'subsystem' time.
+//
+MReportCC::MReportCC() : MReportWeather("CC-REPORT")
+{
+    fName  = "MReportCC";
+    fTitle = "Class for CC-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MCameraTH
+//
+Bool_t MReportCC::SetupReading(MParList &plist)
+{
+    fRecRep = (MReportRec*)plist.FindCreateObj("MReportRec");
+    if (!fRecRep)
+        return kFALSE;
+
+
+    fTH = (MCameraTH*)plist.FindCreateObj("MCameraTH");
+    if (!fTH)
+        return kFALSE;
+
+    fTD = (MCameraTD*)plist.FindCreateObj("MCameraTD");
+    if (!fTD)
+        return kFALSE;
+
+    fRecTemp = (MCameraRecTemp*)plist.FindCreateObj("MCameraRecTemp");
+    if (!fRecTemp)
+        return kFALSE;
+
+
+    return MReport::SetupReading(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the CC-REPORT string
+//
+Bool_t MReportCC::InterpreteCC(TString &str, Int_t ver)
+{
+    const Int_t skip = ver<200407270 ? 30 : 31;
+
+    // Remove the 30/31 tokens of the subsystem status
+    //  table 12.1 p59
+    for (int i=0; i<skip; 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, &fUPSStatus, &fDifRubGPS, &len);
+    if (n!=6)
+    {
+        *fLog << warn << "WARNING - Wrong number of arguments (should be 6)." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, len);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete SCHEDULE section of the CC-REPORT string
+//
+Bool_t MReportCC::InterpreteSchedule(TString &str)
+{
+    if (!CheckTag(str, "SCHEDULE "))
+        return kFALSE;
+
+    str = str.Strip(TString::kBoth);
+
+    // [Sourcename] sourcecategory
+    const Ssiz_t pos1 = str.First(' ');
+    if (pos1<0)
+    {
+        *fLog << warn << "WARNING - Wrong number of arguments (should be 1 or 2)." << endl;
+        return kFALSE;
+    }
+
+    const TString str1 = str(0, pos1);
+
+    str.Remove(0, pos1);
+    str = str.Strip(TString::kBoth);
+
+    if (!str1.IsDigit())
+    {
+        const Ssiz_t pos2 = str.First(' ');
+        if (pos2<0)
+        {
+            *fLog << warn << "WARNING - Wrong number of arguments (should be 1 or 2)." << endl;
+            return kFALSE;
+        }
+
+        TString str2 = str(0, pos2);
+
+        str.Remove(0, pos2);
+
+        // Remove a leading minus. The negative numbers are error codes introduced
+        // by Arehucas. It's only meant for the GRB monitor to change the priority
+        // of its alerts.
+        if (str2[0]=='-')
+            str2.Remove(0, 1);
+
+        if (!str2.IsDigit())
+        {
+            *fLog << warn << "WARNING - Wrong type of second argument (obs. category): " << str2 << endl;
+            return kFALSE;
+        }
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the part of the CC-Report with the MII Subsystem status'
+//
+Bool_t MReportCC::InterpreteStatusM2(TString &str)
+{
+    // Status of: DAQ, DominoCalibration, Drive, Starguider, CaCo,
+    //            CaCo2 LID, CaCo sentinel, CaCo LV, CaCo2 HV, AMC, L2T,
+    //            Domino, Readout, REC, DT, Readout cooling, calib
+    //            %05.2f %05.2f Zd [deg], Az [deg]
+
+    // Remove the 18 tokens of the MAGIC II subsystem status
+    for (int i=0; i<19; i++)
+        str.Remove(0, str.First(' ')+1);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the CC-REPORT string
+//
+Int_t MReportCC::InterpreteBody(TString &str, Int_t ver)
+{
+    if (ver<200404070)
+    {
+        *fLog << err << "ERROR - MReportCC::InterpreteBody not prepared for ";
+        *fLog << " report-files with version<200404070" << endl;
+        return kFALSE;
+    }
+
+    if (!InterpreteCC(str, ver))
+        return kCONTINUE;
+
+    if (ver>=200809030)
+        if (!InterpreteSchedule(str))
+            return kCONTINUE;
+
+    if (ver>=200902030)
+        if (!InterpreteStatusM2(str))
+            return kCONTINUE;
+
+    if (ver<200805190)
+    {
+        fRecRep->InterpreteRec(str, ver, *fTH, *fTD, *fRecTemp);
+        Copy(*fRecRep);
+        fRecRep->SetReadyToSave();
+    }
+
+    if (str.Strip(TString::kBoth)!=(TString)"OVER")
+    {
+        *fLog << warn << "WARNING - 'OVER' tag not found." << endl;
+        return kCONTINUE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print contents of report
+//
+void MReportWeather::Print(Option_t *opt) const
+{
+    *fLog << all << GetDescriptor() << ":  Status=" << (int)GetState();
+    *fLog << "   Hum=" << Form("%3.0f", fHumidity);
+    *fLog << "%  Temp=" << Form("%+3.0f", fTemperature);
+    *fLog << "°C  Wind=" << Form("%3.0f", fWindSpeed);
+    *fLog << "km/h  SolarRad=" << Form("%4.0f", fSolarRadiation) << "W/m^2" << endl;
+}
+
+Bool_t MReportWeather::SetupReadingFits(fits &file)
+{
+    return
+        file.SetRefAddress("T", fTemperature) &&
+        file.SetRefAddress("H", fHumidity)    &&
+        file.SetRefAddress("v", fWindSpeed);
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportCC.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportCC.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportCC.h	(revision 17960)
@@ -0,0 +1,67 @@
+#ifndef MARS_MReportCC
+#define MARS_MReportCC
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportRec;
+class MCameraTH;
+class MCameraTD;
+class MCameraRecTemp;
+
+class MReportWeather : public MReport
+{
+protected:
+    Float_t fHumidity;        // [%]
+    Float_t fTemperature;     // [deg] celsius
+    Float_t fWindSpeed;       // [km/h]
+    Float_t fSolarRadiation;  // [W/m^2] IR-Radiation
+
+    Bool_t SetupReadingFits(fits &fits);
+
+public:
+    MReportWeather(const char *rep="WEATHER-REPORT")  : MReport(rep, kFALSE)
+    {
+        fName  = "MReportWeather";
+        fTitle = "Class for Weather data";
+    }
+
+    void Print(Option_t *opt) const;
+
+    ClassDef(MReportWeather, 1) // Class for Weather information
+};
+
+class MReportCC : public MReportWeather
+{
+private:
+    Float_t fUPSStatus;       // arbitrary units (still not properly defined)
+    Float_t fDifRubGPS;       // [us] Difference between the Rubidium clock time and the time provided by the GPS receiver
+
+    MCameraTH      *fTH;      //! Discriminator thresholds
+    MCameraTD      *fTD;      //! Discriminator delays
+    MCameraRecTemp *fRecTemp; //! Receiver Board temperatures
+
+    MReportRec     *fRecRep;  //! Pipe interpretation to MReportRec if necessary
+
+    // Internal
+    Bool_t SetupReading(MParList &plist);
+    Bool_t InterpreteCC(TString &str, Int_t ver);
+    Bool_t InterpreteSchedule(TString &str);
+    Bool_t InterpreteStatusM2(TString &str);
+
+    // MReport
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportCC();
+
+    Float_t GetHumidity() const       { return fHumidity; }
+    Float_t GetTemperature() const    { return fTemperature; }
+    Float_t GetWindSpeed() const      { return fWindSpeed; }
+    Float_t GetSolarRadiation() const { return fSolarRadiation; }
+
+    ClassDef(MReportCC, 3) // Class for CC-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportCamera.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportCamera.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportCamera.cc	(revision 17960)
@@ -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, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniel Mazin, 04/2005 <mailto:mazin@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  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.
+//
+// Version 2:
+// ----------
+//   - fStstusDC
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportCamera.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+#include "MParList.h"
+
+#include "MCameraCalibration.h"
+#include "MCameraCooling.h"
+#include "MCameraDC.h"
+#include "MCameraHV.h"
+#include "MCameraLV.h"
+#include "MCameraAUX.h"
+#include "MCameraActiveLoad.h"
+#include "MCameraCentralPix.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;
+
+    fDC = (MCameraDC*)plist.FindCreateObj("MCameraDC");
+    if (!fDC)
+        return kFALSE;
+
+    fLV = (MCameraLV*)plist.FindCreateObj("MCameraLV");
+    if (!fLV)
+        return kFALSE;
+
+    fCalibration = (MCameraCalibration*)plist.FindCreateObj("MCameraCalibration");
+    if (!fCalibration)
+        return kFALSE;
+
+    fActiveLoad = (MCameraActiveLoad*)plist.FindCreateObj("MCameraActiveLoad");
+    if (!fActiveLoad)
+        return kFALSE;
+
+    fCentralPix = (MCameraCentralPix*)plist.FindCreateObj("MCameraCentralPix");
+    if (!fCentralPix)
+        return kFALSE;
+
+    return MReport::SetupReading(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the DC* part of the report
+//
+Bool_t MReportCamera::InterpreteDC(TString &str)
+{
+    if (!CheckTag(str, "DC "))
+        return kFALSE;
+
+    return fDC->Interprete(str);
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the HV* part of the report
+//
+Bool_t MReportCamera::InterpreteHV(TString &str)
+{
+    if (!CheckTag(str, "HV "))
+        return kFALSE;
+
+    const char *pos = str.Data();
+    const char *end = str.Data()+577*3;
+
+    Int_t i=0;
+    while (pos<end)
+    {
+        const Char_t hex[4] = { pos[0], pos[1], pos[2], 0 };
+        pos += 3;
+
+        const Int_t n=sscanf(hex, "%3hx", &fHV->fHV[i++]);
+        if (n==1)
+            continue;
+
+        *fLog << warn << "WARNING - Reading hexadecimal HV information." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, end-str.Data()); // Remove DC currents
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the COOL* part of the report
+//
+Bool_t MReportCamera::InterpreteCOOL(TString &str)
+{
+    if (!CheckTag(str, "COOL "))
+        return kFALSE;
+
+    Int_t len;
+
+    Int_t wall, opt, center, water;
+    Short_t hwall, hcenter, hip, lop, pump, ref, valv, res, fans;
+    const Int_t n=sscanf(str.Data(), "%d %d %d %d %hu %hu %hu %hu %hu %hu %hu %hu %hu %n",
+                         &wall, &opt, &center, &water, &hwall, &hcenter,
+                         &hip,  &lop, &pump, &ref, &valv, &res, &fans, &len);
+    if (n!=13)
+    {
+        *fLog << warn << "WARNING - Reading information of 'COOL' section." << endl;
+        return kFALSE;
+    }
+
+    fCooling->fTempWall            = 0.1*wall;
+    fCooling->fTempOptLink         = 0.1*opt;
+    fCooling->fTempCenter          = 0.1*center;
+    fCooling->fTempWater           = 0.1*water;
+    fCooling->fHumWall             = (Byte_t)hwall;
+    fCooling->fHumCenter           = (Byte_t)hcenter;
+    fCooling->fStatusPressureHi    = (Bool_t)hip;
+    fCooling->fStatusPressureLo    = (Bool_t)lop;
+    fCooling->fStatusPump          = (Bool_t)pump;
+    fCooling->fStatusRefrigrerator = (Bool_t)ref;
+    fCooling->fStatusValve         = (Bool_t)valv;
+    fCooling->fStatusResistor      = (Bool_t)res;
+    fCooling->fStatusFans          = (Bool_t)fans;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the LID* part of the report
+//
+Bool_t MReportCamera::InterpreteLID(TString &str)
+{
+    if (!CheckTag(str, "LID "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t limao, limac, limbo, limbc;
+    Short_t slimao, slimac, slimbo, slimbc;
+    Short_t slida, slidb, mlida, mlidb;
+    const Int_t n=sscanf(str.Data(), "%hu %hu %hu %hu %hu %hu %hu %hu %hu %hu %hu %hu %n",
+                         &limao, &limac, &limbo, &limbc,
+                         &slimao, &slimac, &slimbo, &slimbc,
+                         &slida, &slidb, &mlida, &mlidb,
+                         &len);
+    if (n!=12)
+    {
+        *fLog << warn << "WARNING - Reading information of 'LID' section." << endl;
+        return kFALSE;
+    }
+
+    fLids->fLidA.fLimitOpen       = (Bool_t)limao;
+    fLids->fLidA.fLimitClose      = (Bool_t)limac;
+    fLids->fLidA.fSafetyLimitOpen = (Bool_t)slimao;
+    fLids->fLidA.fSafetyLimitClose= (Bool_t)slimac;
+    fLids->fLidA.fStatusLid       = (Byte_t)slida;
+    fLids->fLidA.fStatusMotor     = (Byte_t)mlida;
+
+    fLids->fLidB.fLimitOpen       = (Bool_t)limbo;
+    fLids->fLidB.fLimitClose      = (Bool_t)limbc;
+    fLids->fLidB.fSafetyLimitOpen = (Bool_t)slimbo;
+    fLids->fLidB.fSafetyLimitClose= (Bool_t)slimbc;
+    fLids->fLidB.fStatusLid       = (Byte_t)slidb;
+    fLids->fLidB.fStatusMotor     = (Byte_t)mlidb;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the HVPS* part of the report
+//
+Bool_t MReportCamera::InterpreteHVPS(TString &str)
+{
+    if (!CheckTag(str, "HVPS "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t c1, c2;
+    const Int_t n=sscanf(str.Data(), "%hd %hd %hd %hd %n",
+                         &fHV->fVoltageA, &fHV->fVoltageB, &c1, &c2, &len);
+    if (n!=4)
+    {
+        *fLog << warn << "WARNING - Reading information of 'HVPS' section." << endl;
+        return kFALSE;
+    }
+
+    fHV->fCurrentA = (Byte_t)c1;
+    fHV->fCurrentB = (Byte_t)c2;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the LV* part of the report
+//
+Bool_t MReportCamera::InterpreteLV(TString &str)
+{
+    if (!CheckTag(str, "LV "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t vap5, vap12, van12, vbp5, vbp12, vbn12;
+    Short_t valp12, vblp12, cap5, cap12, can12, cbp5, cbp12;
+    Short_t cbn12, calp12, cblp12, lvps, temp, hum;
+    const Int_t n=sscanf(str.Data(), "%hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %n",
+                         &vap5, &vap12, &van12, &vbp5, &vbp12, &vbn12,
+                         &valp12, &vblp12, &cap5, &cap12, &can12, &cbp5, &cbp12,
+                         &cbn12, &calp12, &cblp12, &lvps, &temp, &hum, &len);
+    if (n!=19)
+    {
+        *fLog << warn << "WARNING - Reading information of 'LV' section." << endl;
+        return kFALSE;
+    }
+
+    fLV->fRequestPowerSupply = (Bool_t)lvps;
+    fLV->fTemp = 0.1*temp;
+    fLV->fHumidity = (Byte_t)hum;
+
+    fLV->fPowerSupplyA.fVoltagePos5V         = 0.01*vap5;
+    fLV->fPowerSupplyA.fVoltagePos12V        = 0.01*vap12;
+    fLV->fPowerSupplyA.fVoltageNeg12V        = 0.01*van12;
+    fLV->fPowerSupplyA.fVoltageOptLinkPos12V = 0.01*valp12;
+    fLV->fPowerSupplyA.fCurrentPos5V         = 0.001*cap5;
+    fLV->fPowerSupplyA.fCurrentPos12V        = 0.001*cap12;
+    fLV->fPowerSupplyA.fCurrentNeg12V        = 0.001*can12;
+    fLV->fPowerSupplyA.fCurrentOptLinkPos12V = 0.001*calp12;
+
+    fLV->fPowerSupplyB.fVoltagePos5V         = 0.01*vbp5;
+    fLV->fPowerSupplyB.fVoltagePos12V        = 0.01*vbp12;
+    fLV->fPowerSupplyB.fVoltageNeg12V        = 0.01*vbn12;
+    fLV->fPowerSupplyB.fVoltageOptLinkPos12V = 0.01*vblp12;
+    fLV->fPowerSupplyB.fCurrentPos5V         = 0.001*cbp5;
+    fLV->fPowerSupplyB.fCurrentPos12V        = 0.001*cbp12;
+    fLV->fPowerSupplyB.fCurrentNeg12V        = 0.001*cbn12;
+    fLV->fPowerSupplyB.fCurrentOptLinkPos12V = 0.001*cblp12;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the AUX* part of the report
+//
+Bool_t MReportCamera::InterpreteAUX(TString &str)
+{
+    if (!CheckTag(str, "AUX "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t led, fan;
+    const Int_t n=sscanf(str.Data(), "%hd %hd %n", &led, &fan, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Reading information of 'AUX' section." << endl;
+        return kFALSE;
+    }
+
+    fAUX->fRequestCaosLEDs=(Bool_t)led;
+    fAUX->fRequestFansFADC=(Bool_t)fan;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the CAL* part of the report
+//
+Bool_t MReportCamera::InterpreteCAL(TString &str)
+{
+    if (!CheckTag(str, "CAL "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t hv, lv, cont, pin;
+
+    const Int_t n=sscanf(str.Data(), "%hd %hd %hd %hd %n", &hv, &lv, &cont, &pin, &len);
+    if (n!=4)
+    {
+        *fLog << warn << "WARNING - Reading information of 'CAL' section." << endl;
+        return kFALSE;
+    }
+
+    fCalibration->fRequestHiVoltage = (Bool_t)hv;
+    fCalibration->fRequestLoVoltage = (Bool_t)lv;
+    fCalibration->fRequestContLight = (Bool_t)cont;
+    fCalibration->fRequestPinDiode  = (Bool_t)pin;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the HOT* part of the report
+//
+Bool_t MReportCamera::InterpreteHOT(TString &str)
+{
+    if (!CheckTag(str, "HOT "))
+        return kFALSE;
+
+    Int_t len;
+    Int_t hot;
+
+    const Int_t n=sscanf(str.Data(), "%d %n", &hot, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Reading information of 'HOT' section." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Active Load REPORT part
+//
+Bool_t MReportCamera::InterpreteActiveLoad(TString &str)
+{
+    if (!CheckTag(str, "ACTLOAD "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t v360a, i360a, v360b, i360b, v175a, i175a, v175b, i175b;
+    Int_t n=sscanf(str.Data(), " %hd %hd %hd %hd %hd %hd %hd %hd %n",
+                   &v360a, &i360a, &v360b, &i360b, &v175a, &i175a, &v175b, &i175b, &len);
+    if (n!=8)
+    {
+        *fLog << warn << "WARNING - Reading information of 'ACTLOAD' section." << endl;
+        return kFALSE;
+    }
+
+    fActiveLoad->fVoltage360A = (float)v360a*0.1;
+    fActiveLoad->fIntens360A  = (float)i360a*0.01;
+    fActiveLoad->fVoltage360B = (float)v360b*0.1;
+    fActiveLoad->fIntens360B  = (float)i360b*0.01;
+    fActiveLoad->fVoltage175A = (float)v175a*0.1;
+    fActiveLoad->fIntens175A  = (float)i175a*0.01;
+    fActiveLoad->fVoltage175B = (float)v175b*0.1;
+    fActiveLoad->fIntens175B  = (float)i175b*0.01;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Central Pixel part
+//
+Bool_t MReportCamera::InterpreteCentralPix(TString &str, Int_t ver)
+{
+    if (!CheckTag(str, "CPIX "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t status;
+
+    Int_t n=sscanf(str.Data(), " %hd %n", &status, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Reading information of 'CPIX' section." << endl;
+            return kFALSE;
+    }
+
+    if (ver>=200812140)
+    {
+        Int_t len2;
+        Int_t dc;
+        n=sscanf(str.Data()+len, " %d %n", &dc, &len2);
+        if (n!=1)
+        {
+            *fLog << warn << "WARNING - Reading information of 'CPIX' section." << endl;
+            return kFALSE;
+        }
+
+        fCentralPix->fDC = dc;
+
+        len += len2;
+    }
+
+    fCentralPix->fStatus = (Bool_t)status;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the CHTEMP part
+//
+Bool_t MReportCamera::InterpreteCHTEMP(TString &str)
+{
+    if (!CheckTag(str, "CHTEMP "))
+        return kFALSE;
+
+    Int_t len, temp1, temp2, temp3;
+    Int_t n=sscanf(str.Data(), " %d %d %d %n", &temp1, &temp2, &temp3, &len);
+    if (n!=3)
+    {
+        *fLog << warn << "WARNING - Reading information of 'CHTEMP' section." << endl;
+        return kFALSE;
+    }
+
+    fAUX->fTempCountingHouse1 = temp1*0.01;
+    fAUX->fTempCountingHouse2 = temp2*0.01;
+    fAUX->fTempCountingHouse3 = temp3*0.01;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the HVFIL part
+//
+Bool_t MReportCamera::InterpreteHVFIL(TString &str)
+{
+    if (!CheckTag(str, "HVFIL "))
+        return kFALSE;
+
+    str=str.Strip(TString::kBoth);
+
+    if (str.BeginsWith("PSSEN "))
+    {
+        fHV->fFileName = "";
+        return kTRUE;
+    }
+
+    const Ssiz_t pos = str.First(' ');
+    /*
+    if (pos<0)
+    {
+        *fLog << warn << "WARNING - Reading information of 'HVFIL' section." << endl;
+        return kFALSE;
+    }
+    */
+
+    fHV->fFileName = pos<0 ? (TString)"" : str(0, pos);
+    if (pos<0)
+        return kTRUE;
+
+    str.Remove(0, pos);
+    str=str.Strip(TString::kBoth);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ps: Camera cabinet power supply
+// v1: PS sensor v1
+// v2: PS sensor v2
+//
+Bool_t MReportCamera::InterpretePSSEN(TString &str)
+{
+    if (!CheckTag(str, "PSSEN "))
+        return kCONTINUE;
+
+    Int_t len;
+    Int_t ps, v1, v2;
+
+    const Int_t n=sscanf(str.Data(), "%d %d %d %n", &ps, &v1, &v2, &len);
+    if (n!=3)
+    {
+        *fLog << warn << "WARNING - Reading information of 'PSSEN' section." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// liq: Liquid inside camera
+//
+Bool_t MReportCamera::InterpreteLIQ(TString &str)
+{
+    if (!CheckTag(str, "LIQ "))
+        return kFALSE;
+
+    Int_t len;
+    Int_t liq;
+
+    const Int_t n=sscanf(str.Data(), "%d %n", &liq, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Reading information of 'LIQ' section." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the CAMERA-REPORT part
+//
+Bool_t MReportCamera::InterpreteCamera(TString &str, Int_t ver)
+{
+    //
+    // 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 len1=0;
+    Short_t cal, stat, hvps, lid, lv, cool, hv, dc, led, fan, can, io, clv;
+    Int_t n;
+
+    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, &len1);
+    if (n!=13)
+    {
+        *fLog << warn << "WARNING - Cannot interprete status' of subsystems." << endl;
+        return kFALSE;
+    }
+
+    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;
+    fDC->fStatus                   = (Byte_t)dc;
+    fActiveLoad->fStatus           = 0xff;
+
+    Int_t len2=0;
+    if (ver > 200504130)
+    {
+        Short_t actl;
+        n=sscanf(str.Data()+len1, " %hd %n", &actl, &len2);
+        if (n!=1)
+        {
+            *fLog << warn << "WARNING - Cannot interprete status of active load." << endl;
+            return kFALSE;
+        }
+        fActiveLoad->fStatus = (Byte_t)actl;
+    }
+    str.Remove(0, len1+len2);
+    str=str.Strip(TString::kLeading);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the CAMERA-REPORT string
+//
+Int_t MReportCamera::InterpreteBody(TString &str, Int_t ver)
+{
+    if (!InterpreteCamera(str, ver))
+        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 (ver >= 200407070)
+    {
+        if (!InterpreteHOT(str))
+            return kCONTINUE;
+    }
+
+    if (ver > 200504130)
+    {
+         if (!InterpreteActiveLoad(str))
+            return kCONTINUE;
+         if (!InterpreteCentralPix(str, ver))
+            return kCONTINUE;
+    }
+
+    if (ver >= 200507190)
+    {
+        if (!InterpreteCHTEMP(str))
+            return kCONTINUE;
+        if (!InterpreteHVFIL(str))
+            return kCONTINUE;
+    }
+
+    if (ver >= 200812140)
+    {
+        if (!InterpretePSSEN(str))
+            return kCONTINUE;
+        if (!InterpreteLIQ(str))
+            return kCONTINUE;
+    }
+
+    if (str!="OVER")
+    {
+        *fLog << warn << "WARNING - 'OVER' tag not found... remaining: " << str << endl;
+        return kCONTINUE;
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportCamera.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportCamera.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportCamera.h	(revision 17960)
@@ -0,0 +1,62 @@
+#ifndef MARS_MReportCamera
+#define MARS_MReportCamera
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MCameraCooling;
+class MCameraLids;
+class MCameraHV;
+class MCameraDC;
+class MCameraLV;
+class MCameraAUX;
+class MCameraCalibration;
+class MCameraActiveLoad;
+class MCameraCentralPix;
+
+class MReportCamera : public MReport
+{
+private:
+    Byte_t fStatus;   // CaCo monitored status of the sentinel (0-9), Sentinel_state
+
+    MCameraCooling     *fCooling;     //!
+    MCameraLids        *fLids;        //!
+    MCameraAUX         *fAUX;         //!
+    MCameraHV          *fHV;          //!
+    MCameraDC          *fDC;          //!
+    MCameraLV          *fLV;          //!
+    MCameraActiveLoad  *fActiveLoad;  //!
+    MCameraCalibration *fCalibration; //!
+    MCameraCentralPix  *fCentralPix;  //!
+
+    Bool_t SetupReading(MParList &plist);
+
+    Bool_t InterpreteCamera(TString &str, Int_t ver);
+    Bool_t InterpreteDC(TString &str);
+    Bool_t InterpreteHV(TString &str);
+    Bool_t InterpreteCOOL(TString &str);
+    Bool_t InterpreteLID(TString &str);
+    Bool_t InterpreteHVPS(TString &str);
+    Bool_t InterpreteLV(TString &str);
+    Bool_t InterpreteAUX(TString &str);
+    Bool_t InterpreteCAL(TString &str);
+    Bool_t InterpreteHOT(TString &str);
+    Bool_t InterpreteActiveLoad(TString &str);
+    Bool_t InterpreteCentralPix(TString &str, Int_t ver);
+    Bool_t InterpreteCHTEMP(TString &str);
+    Bool_t InterpreteHVFIL(TString &str);
+    Bool_t InterpretePSSEN(TString &str);
+    Bool_t InterpreteLIQ(TString &str);
+
+    Int_t  InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportCamera();
+
+    Byte_t GetStatus() const { return  fStatus; }
+
+    ClassDef(MReportCamera, 2) // Class for CAMERA-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportCurrents.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportCurrents.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportCurrents.cc	(revision 17960)
@@ -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, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportCurrents
+//
+// This is the class interpreting and storing the DC-REPORT information.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportCurrents.h"
+
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCameraDC.h"
+
+ClassImp(MReportCurrents);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "DC-REPORT" Reports
+// are expected to have no 'subsystem' time.
+//
+MReportCurrents::MReportCurrents() : MReport("DC-REPORT", kFALSE)
+{
+    fName  = "MReportCurrents";
+    fTitle = "Class for DC-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MCameraDC
+//
+Bool_t MReportCurrents::SetupReading(MParList &plist)
+{
+    fDC = (MCameraDC*)plist.FindCreateObj("MCameraDC");
+    if (!fDC)
+        return kFALSE;
+
+    return MReport::SetupReading(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the DC-REPORT string
+//
+Int_t MReportCurrents::InterpreteBody(TString &str, Int_t ver)
+{
+    Int_t len;
+    Short_t err1, err2;
+    const Int_t n=sscanf(str.Data(), " %hd %hd %n", &err1, &err2, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Reading status information." << endl;
+        return kCONTINUE;
+    }
+
+    fStatus1 = (Byte_t)err1;
+    fStatus2 = (Byte_t)err2;
+
+    // FIXME: Set fDC->fStatus ???
+
+    return fDC->Interprete(str, len);
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportCurrents.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportCurrents.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportCurrents.h	(revision 17960)
@@ -0,0 +1,27 @@
+#ifndef MARS_MReportCurrents
+#define MARS_MReportCurrents
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MCameraDC;
+
+class MReportCurrents : public MReport
+{
+private:
+    Byte_t fStatus1;
+    Byte_t fStatus2;
+
+    MCameraDC *fDC; //!
+
+    Bool_t SetupReading(MParList &plist);
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportCurrents();
+
+    ClassDef(MReportCurrents, 1) // Class for DC-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportDAQ.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportDAQ.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportDAQ.cc	(revision 17960)
@@ -0,0 +1,54 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportDAQ
+//
+// This is the class interpreting and storing the DAQ-REPORT information.
+//
+// --> Currently unused
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportDAQ.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MReportDAQ);
+
+using namespace std;
+
+MReportDAQ::MReportDAQ() : MReport("DAQ-REPORT")
+{
+    fName = "MReportDAQ";
+    fTitle = "Class for DAQ-REPORT information";
+}
+
+Int_t MReportDAQ::InterpreteBody(TString &str, Int_t ver)
+{
+    *fLog << dbg << "D" << flush;
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportDAQ.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportDAQ.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportDAQ.h	(revision 17960)
@@ -0,0 +1,19 @@
+#ifndef MARS_MReportDAQ
+#define MARS_MReportDAQ
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportDAQ : public MReport
+{
+private:
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportDAQ();
+
+    ClassDef(MReportDAQ, 1) // Class for DAQ-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportDrive.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportDrive.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportDrive.cc	(revision 17960)
@@ -0,0 +1,193 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 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 describes 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 "fits.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MReportDrive);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "DRIVE-REPORT"
+//
+MReportDrive::MReportDrive() : MReport("DRIVE-REPORT"),
+    fMjd(0), fRa(0), fDec(0), fHa(0), fNominalZd(0), fNominalAz(0),
+    fCurrentZd(0), fCurrentAz(0), fErrorZd(0), fErrorAz(0)
+{
+    fName  = "MReportDrive";
+    fTitle = "Class for DRIVE-REPORT information (raw telescope position)";
+}
+
+Bool_t MReportDrive::SetupReadingFits(fits &file)
+{
+    return
+        file.SetRefAddress("Ra",  fRa)  &&
+        file.SetRefAddress("Dec", fDec) &&
+        file.SetRefAddress("Ha",  fHa)  &&
+        file.SetRefAddress("Az",  fNominalAz) &&
+        file.SetRefAddress("Zd",  fNominalZd) &&
+        file.SetRefAddress("dAz", fErrorAz)   &&
+        file.SetRefAddress("dZd", fErrorZd);
+}
+
+Int_t MReportDrive::InterpreteFits(const fits &fits)
+{
+    fCurrentZd = fNominalZd - fErrorZd;
+    fCurrentAz = fNominalAz - fErrorAz;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the DRIVE-REPORT string
+//
+Int_t MReportDrive::InterpreteBody(TString &str, Int_t ver)
+{
+    MAstro::String2Angle(str, fRa);
+    MAstro::String2Angle(str, fDec);
+    MAstro::String2Angle(str, fHa);
+
+    Int_t len;
+    Int_t n=sscanf(str.Data(), "%lf %n", &fMjd, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+
+    str.Remove(0, len);
+
+    MAstro::String2Angle(str, fNominalZd);
+    MAstro::String2Angle(str, fNominalAz);
+    MAstro::String2Angle(str, fCurrentZd);
+    MAstro::String2Angle(str, fCurrentAz);
+
+    n=sscanf(str.Data(), "%lf %lf %n", &fErrorZd, &fErrorAz, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    if (ver>=200802200)
+    {
+        Int_t dummy; // Cosy armed or not
+        n=sscanf(str.Data(), "%d %n", &dummy, &len);
+        if (n!=1)
+        {
+            *fLog << warn << "WARNING - Not enough arguments." << endl;
+            return kCONTINUE;
+        }
+
+        str.Remove(0, len);
+        str = str.Strip(TString::kBoth);
+    }
+
+    if (ver>=200905170)
+    {
+        Int_t dummy; // Starguider switched on or not
+        n=sscanf(str.Data(), "%d %n", &dummy, &len);
+        if (n!=1)
+        {
+            *fLog << warn << "WARNING - Not enough arguments." << endl;
+            return kCONTINUE;
+        }
+
+        str.Remove(0, len);
+        str = str.Strip(TString::kBoth);
+    }
+
+    return str.IsNull() ? kTRUE : kCONTINUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// GetAbsError [deg]
+//
+// Returns the absolute deviation from the nominal position calculated
+// from the system error.
+//
+//
+Double_t MReportDrive::GetAbsError() const
+{
+    return MAstro::GetDevAbs(fNominalZd, fCurrentZd, fErrorAz);
+}
+
+void MReportDrive::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": Mjd=" << fMjd << " Ra=" << fRa << " Dec=" << fDec;
+    *fLog << " dZd=" << fErrorZd << " dAz=" << fErrorAz << " D=" << GetAbsError() << endl;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportDrive.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportDrive.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportDrive.h	(revision 17960)
@@ -0,0 +1,53 @@
+#ifndef MARS_MReportDrive
+#define MARS_MReportDrive
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportDrive : public MReport
+{
+private:
+    Double_t fMjd;        // Modified Julian Date send by the drive system
+
+    Double_t fRa;         // [h]   Right ascension
+    Double_t fDec;        // [deg] Declination
+    Double_t fHa;         // [h]   Hour angle
+
+    Double_t fNominalZd;  // [deg] Nominal zenith distance
+    Double_t fNominalAz;  // [deg] Nominal azimuth
+    Double_t fCurrentZd;  // [deg] current zenith distance
+    Double_t fCurrentAz;  // [deg] current azimuth
+
+    Double_t fErrorZd;    // [deg] system error in the zenith angle axis
+    Double_t fErrorAz;    // [deg] sistem error in the azimuth angle axis
+
+    Bool_t SetupReadingFits(fits &fits);
+    Int_t  InterpreteFits(const fits &fits);
+    Int_t  InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportDrive();
+
+    Double_t GetMjd() const       { return fMjd;       }
+
+    Double_t GetRa() const        { return fRa;        }
+    Double_t GetDec() const       { return fDec;       }
+    Double_t GetHa() const        { return fHa;        }
+
+    Double_t GetNominalZd() const { return fNominalZd; }
+    Double_t GetNominalAz() const { return fNominalAz; }
+    Double_t GetCurrentZd() const { return fCurrentZd; }
+    Double_t GetCurrentAz() const { return fCurrentAz; }
+
+    Double_t GetErrorZd() const   { return fErrorZd;   }
+    Double_t GetErrorAz() const   { return fErrorAz;   }
+
+    Double_t GetAbsError() const;
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MReportDrive, 1) // Class for DRIVE-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportFileRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportFileRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportFileRead.cc	(revision 17960)
@@ -0,0 +1,268 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportFileRead
+//
+// Task to read the central control report file. For more information see
+// the base class of all reports MReport.
+//
+// To add a report which should be read use AddToList.
+//
+// eg. AddToList("Drive") will assume the existance of a class called
+//     MReportDrive. It will create such an object automatically. It will
+//     send all lines starting with 'MReportDrive::fIndetifier-REPORT'
+//     to this class.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportFileRead.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TRegexp.h>
+#include <THashTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MReportHelp.h"
+
+ClassImp(MReportFileRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file and creates a
+// THashTable which allows faster access to the MReport* objects.
+//
+MReportFileRead::MReportFileRead(const char *fname, const char *name, const char *title)
+    : fFileName(fname), fVersion(-1), fIn(NULL)
+{
+    fName  = name  ? name  : "MReportFileRead";
+    fTitle = title ? title : "Read task to read general report files";
+
+    fIn = new ifstream;
+
+    fList = new THashTable(1,1);
+    fList->SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream and hash table.
+//
+MReportFileRead::~MReportFileRead()
+{
+    delete fIn;
+    delete fList;
+}
+
+// --------------------------------------------------------------------------
+//
+// Wrapper. Returns the MReportHelp with the given identifier from the
+// hash table.
+//
+MReportHelp *MReportFileRead::GetReportHelp(const TString &str) const
+{
+    return static_cast<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. The name is the class name (eg 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())
+    {
+        delete help;
+        return kFALSE;
+    }
+
+    if (GetReport(help->GetName()))
+    {
+        *fLog << warn << "WARNING - Report with Identifier '";
+        *fLog << help->GetName() << "' already added to the list... ";
+        *fLog << "ignored." << endl;
+        delete help;
+        return kFALSE;
+    }
+
+    fList->Add(help);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call SetupReading for all MReportHelp objects scheduled.
+// Try to open the file and check the file header.
+//
+Int_t MReportFileRead::PreProcess(MParList *pList)
+{
+    fNumLine = 0;
+
+    // Add the MReport instances first to the paramter list
+    // so that SetupReading can find them if needed
+    fList->R__FOR_EACH(MReportHelp, AddToList)(*pList);
+
+    // Setup reading
+    TIter Next(fList);
+    MReportHelp *help=0;
+    while ((help=(MReportHelp*)Next()))
+        if (!help->SetupReading(*pList))
+            return kFALSE;
+
+    //
+    // 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;
+
+    fNumLine = CheckFileHeader();
+    return fNumLine>0;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+        // Check for MReport{str(0,pos)}
+        rep = GetReportHelp(str(0,pos));
+
+        // Remove this part from the string
+        if (GetReport(rep))
+            str.Remove(0, pos);
+    }
+
+    const Int_t rc = rep->Interprete(str, fStart, fStop, fVersion);
+
+    switch (rc)
+    {
+    case kFALSE:
+        *fLog << err << "ERROR - Interpreting '" << rep->GetName() << "' failed (l." << fNumLine << ", V" << fVersion << ")... abort." << endl;
+        break;
+    case kCONTINUE:
+        *fLog << warn << "WARNING - Interpreting '" << rep->GetName() << "' failed (l." << fNumLine << ", V" << fVersion << ")... 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: branches/Mars_McMismatchStudy/mreport/MReportFileRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportFileRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportFileRead.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MReportFileRead
+#define MARS_MReportFileRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class THashTable;
+
+class MTime;
+class MReport;
+class MReportHelp;
+
+class MReportFileRead : public MTask
+{
+private:
+    TString     fFileName;  // Name of the input file
+
+    THashTable *fList;      // List of possible reports to be interpreted
+
+    MTime   fStart;         // Time range which should be read from file
+    MTime   fStop;          // Time range which should be read from file
+
+    Long_t  fNumLine;       // line counter
+
+    Int_t   fVersion;       // File format version
+
+    enum { kHasNoHeader = BIT(14) };
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    virtual Int_t CheckFileHeader() { return 0; }
+    MReport *GetReport(const TString &str) const;
+    MReport *GetReport(MReportHelp *help) const;
+    MReportHelp *GetReportHelp(const TString &str) const;
+
+protected:
+    std::ifstream *fIn;         //! buffered input stream (file to read from)
+    void SetVersion(Int_t v) { fVersion = v; }
+
+public:
+    MReportFileRead(const char *filename, const char *name=NULL, const char *title=NULL);
+    ~MReportFileRead();
+
+    void SetHasNoHeader() { SetBit(kHasNoHeader); }
+    void SetTimeStart(const MTime &tm) { fStart = tm; }
+    void SetTimeStop(const MTime &tm)  { fStop = tm; }
+
+    Bool_t AddToList(const char *name) const;
+
+    ClassDef(MReportFileRead, 0)// Task to read general report file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportFileReadCC.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportFileReadCC.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportFileReadCC.cc	(revision 17960)
@@ -0,0 +1,240 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MReportFileReadCC
+//
+// This is a report file reader which implements the CC header checking.
+// Because diffrent subsystem are writing different headers it is not
+// easily possible to have one Reader for all files. Because of this
+// you must know to which subsystem the file belongs before you can
+// instantiate your reader if you need the header or want to check the
+// header.
+//
+// If you want to restrict reading to 'single run report files' you can
+// call SetRunNumber(12345). In this case Checking the Header will fail
+// if no run information is available or the runnumber in the header
+// doesn't match. To request a 'all run' file use SetRunNumber(0).
+// To allow both file types to be read use SetRunNumber(-1) <default>
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportFileReadCC.h"
+
+#include <fstream>
+#include <stdlib.h> // atoi on gcc 2.95.3
+
+#include <TRegexp.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MReportFileReadCC);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file and creates a
+// THashTable which allows faster access to the MReport* objects.
+//
+MReportFileReadCC::MReportFileReadCC(const char *fname, const char *name, const char *title)
+    : MReportFileRead(fname, name, title), fTelescope(-1), fRunNumber(-1), fFileNumber(-1)
+{
+    fName  = name  ? name  : "MReportFileReadCC";
+    fTitle = title ? title : "Read task to read Central Control report files";
+}
+
+Int_t MReportFileReadCC::GetRunNumber(const TString &str) const
+{
+    Int_t run = -1;
+
+    // whole night report file
+    if (str==TString("[CC Report File]"))
+        run = 0;
+
+    // report file matching a single run
+    if (!str(TRegexp("^[CC Run [0-9]+ Control File]$")).IsNull())
+        run = atoi(str(TRegexp(" [0-9]+")).Data());
+
+    if (run<0)
+    {
+        *fLog << err << "ERROR - First line doesn't match '[CC Report File]' ";
+        *fLog << "nor '^[CC Run [0-9]+ Control File]$'" << endl;
+        return -1;
+    }
+
+    if (fRunNumber!=-1 && fRunNumber!=run)
+    {
+        *fLog << err << "ERROR - Requested run #" << fRunNumber << " doesn't ";
+        *fLog << "match, found run #" << run << endl;
+        return -1;
+    }
+
+    return run;
+}
+
+Int_t MReportFileReadCC::GetVersion(const TString &str) const
+{
+    if (str(TRegexp("^Arehucas Version Number [0-9]+-[0-9]$")).IsNull())
+    {
+        *fLog << err << "ERROR - Version '^Arehucas Version Number [0-9]+-[0-9]$' ";
+        *fLog << "not found in second line." << endl;
+        return -1;
+    }
+
+    TString num = str(TRegexp("[0-9]+-[0-9]"));
+    num.Prepend("20");
+    num.ReplaceAll("-", "");
+
+    return atoi(num.Data());
+}
+
+Int_t MReportFileReadCC::GetTelescope(const TString &str) const
+{
+    if (str(TRegexp("^Telescope M[0-9]$")).IsNull())
+    {
+        *fLog << err << "ERROR - '^Telescope M[0-9]$' not found in third line." << endl;
+        return -1;
+    }
+
+    const Int_t num = atoi(str.Data()+11);
+
+    if (fTelescope != 1 && fTelescope !=2)
+    {
+        *fLog << err << "ERROR - Telsope number M" << num << " in third line unknown." << endl;
+        return -1;
+    }
+
+    if (fTelescope!=-1 && fTelescope!=num)
+    {
+        *fLog << err << "ERROR - Requested telescope M" << fTelescope << " doesn't ";
+        *fLog << "match, found M" << num << endl;
+        return -1;
+    }
+
+    return num;
+}
+
+Int_t MReportFileReadCC::GetFileNumber(const TString &str) const
+{
+    if (str(TRegexp("^Subrun [0-9]+$")).IsNull())
+    {
+        *fLog << err << "ERROR - '^Subrun [0-9]+$' not found in fourth line." << endl;
+        return -1;
+    }
+
+    const Int_t num = atoi(str.Data()+7);
+
+    if (fFileNumber!=-1 && fFileNumber!=num)
+    {
+        *fLog << err << "ERROR - Requested file number (subrun) " << fFileNumber << " doesn't ";
+        *fLog << "match, found " << num << endl;
+        return -1;
+    }
+
+    return num;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the file header corresponds to a central control file
+// header and check for the existance of a correct version number.
+// The version number may later be used to be able to read different
+// file versions
+//
+Int_t MReportFileReadCC::CheckFileHeader()
+{
+    TString str;
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (!*fIn)
+    {
+        *fLog << "ERROR - Unexpected end of file (file empty)" << endl;
+        return -1;
+    }
+
+    const Int_t run = GetRunNumber(str);
+    if (run<0)
+        return -1;
+
+    fRunNumber = run;
+
+    // -----------------------------------------------------------
+
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (!*fIn)
+    {
+        *fLog << "ERROR - Unexpected end of file after line 1." << endl;
+        return -1;
+    }
+
+    const Int_t ver = GetVersion(str);
+    if (ver<0)
+        return -1;
+
+    *fLog << all << "Report File version: <" << ver << ">" << endl;
+    SetVersion(ver);
+
+    // -----------------------------------------------------------
+
+    fTelescope = 1;
+
+    if (ver<200805190)
+        return 3;
+
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (!*fIn)
+    {
+        *fLog << "ERROR - Unexpected end of file after line 2." << endl;
+        return -1;
+    }
+
+    const Int_t tel = GetTelescope(str);
+    if (tel<0)
+        return -1;
+
+    fTelescope = tel;
+
+    // -----------------------------------------------------------
+
+    if (fRunNumber==0)
+        return kTRUE;
+
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (!*fIn)
+    {
+        *fLog << "ERROR - Unexpected end of file after line 3." << endl;
+        return -1;
+    }
+
+    const Int_t num = GetFileNumber(str);
+    if (num<0)
+        return -1;
+
+    fFileNumber = num;
+
+    // -----------------------------------------------------------
+
+    return 4;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportFileReadCC.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportFileReadCC.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportFileReadCC.h	(revision 17960)
@@ -0,0 +1,32 @@
+#ifndef MARS_MReportFileReadCC
+#define MARS_MReportFileReadCC
+
+#ifndef MARS_MReportFileRead
+#include "MReportFileRead.h"
+#endif
+
+class MReportFileReadCC : public MReportFileRead
+{
+private:
+    Int_t fTelescope;
+    Int_t fRunNumber;
+    Int_t fFileNumber;
+
+    Int_t GetRunNumber(const TString &str) const;
+    Int_t GetVersion(const TString &str) const;
+    Int_t GetTelescope(const TString &str) const;
+    Int_t GetFileNumber(const TString &str) const;
+
+    Int_t CheckFileHeader();
+
+public:
+    MReportFileReadCC(const char *filename, const char *name=NULL, const char *title=NULL);
+
+    void SetTelescope(Int_t num)  { fTelescope  = num; }
+    void SetRunNumber(Int_t run)  { fRunNumber  = run; }
+    void SetFileNumber(Int_t run) { fFileNumber = run; }
+
+    ClassDef(MReportFileReadCC, 0)// Task to read the central control report file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportFitsRead.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportFitsRead.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportFitsRead.cc	(revision 17960)
@@ -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/2011 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2011
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportFitsRead
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportFitsRead.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TClass.h>
+#include <TRegexp.h>
+#include <THashTable.h>
+
+#include "fits.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MReport.h"
+
+ClassImp(MReportFitsRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file and creates a
+// THashTable which allows faster access to the MReport* objects.
+//
+MReportFitsRead::MReportFitsRead(const char *fname, const char *name, const char *title)
+    : fFileName(fname), fReport(NULL), fIn(NULL)
+{
+    fName  = name  ? name  : "MReportFitsRead";
+    fTitle = title ? title : "Read task to read general report files";
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream and hash table.
+//
+MReportFitsRead::~MReportFitsRead()
+{
+    delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call SetupReading for all MReportHelp objects scheduled.
+// Try to open the file and check the file header.
+//
+Int_t MReportFitsRead::PreProcess(MParList *pList)
+{
+    // Add the MReport instances first to the paramter list
+    // so that SetupReading can find them if needed
+    //fList->R__FOR_EACH(MReportHelp, AddToList)(*pList);
+
+    fReport = (MReport*)pList->FindCreateObj(fReportName);
+    if (!fReport)
+        return kFALSE;
+
+    if (!fReport->InheritsFrom(MReport::Class()))
+    {
+        *fLog << err << fReportName << " does not derive from MReport." << endl;
+        return kFALSE;
+    }
+
+
+    //
+    // open the input stream
+    // first of all check if opening the file in the constructor was
+    // successfull
+    //
+    if (fIn)
+        delete fIn;
+    fIn = new fits(fFileName.Data());
+    if (!(*fIn))
+    {
+        *fLog << err << "Cannot open file " << fFileName << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    if (fIn->GetStr("TELESCOP")!="FACT")
+    {
+        *fLog << err << "Not a valid FACT FITS file (key TELESCOP not 'FACT')." << endl;
+        return kFALSE;
+    }
+
+    fMjdRef = fIn->HasKey("MJDREF") ? fIn->GetUInt("MJDREF") : 0;
+
+    if (!fIn->HasKey("MJDREF"))
+        *fLog << warn << "MJDREF header key missing... assuming MJDREF==0" << endl;
+
+    return
+        fIn->SetRefAddress("QoS",  fBufQos)  &&
+        fIn->SetRefAddress("Time", fBufTime) &&
+        fReport->SetupReading(*pList) &&
+        fReport->SetupReadingFits(*fIn);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MReportFitsRead::Process()
+{
+    if (!fIn->GetNextRow())
+    {
+        *fLog << inf << "End-of-file detected." << endl;
+        return kFALSE;
+    }
+
+    if (fBufTime==0)
+        return kCONTINUE;
+
+    MTime &time = *fReport->GetTime();
+
+    time.SetMjd(fBufTime+fMjdRef);
+    time.SetReadyToSave();
+
+    // return -1: This is the special case: out of time limit
+    if (fStart && time<fStart)
+        return kCONTINUE;
+    if (fStop  && time>fStop)
+        return kCONTINUE;
+
+    const Int_t rc = fReport->InterpreteFits(*fIn);
+
+
+    /*
+    switch (rc)
+    {
+    case kTRUE:     fNumReports++; break;
+    case kCONTINUE: fNumSkipped++; break;
+    }*/
+
+    switch (rc)
+    {
+    case kFALSE:
+        *fLog << err << "ERROR - Interpreting '" << fReport->GetName() << "' failed (l." << fIn->GetRow() << ")... abort." << endl;
+        break;
+    case kCONTINUE:
+        *fLog << warn << "WARNING - Interpreting '" << fReport->GetName() << "' failed (l." << fIn->GetRow() << ")... 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 MReportFitsRead::PostProcess()
+{
+    fIn->close();
+
+    if (!GetNumExecutions())
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " statistics:" << endl;
+    *fLog << dec << setfill(' ');
+  /*
+    *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: branches/Mars_McMismatchStudy/mreport/MReportFitsRead.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportFitsRead.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportFitsRead.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MReportFitsRead
+#define MARS_MReportFitsRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+#ifdef __CINT__
+#define int32_t  Int_t
+#else
+#include <stdint.h>
+#endif
+
+#include <map>
+
+class fits;
+class THashTable;
+
+class MTime;
+class MReport;
+class MReportHelp;
+
+class MReportFitsRead : public MTask
+{
+private:
+    TString  fFileName;   // Name of the input file
+    TString  fReportName; // Name of the report class
+
+    MReport *fReport;     // List of possible reports to be interpreted
+
+    MTime   fStart;       // Time range which should be read from file
+    MTime   fStop;        // Time range which should be read from file
+
+    int32_t  fBufQos;  //! Buffer for Quality of Service
+    Double_t fBufTime; //! Buffer for Time
+
+    UInt_t fMjdRef;
+
+    enum { kHasNoHeader = BIT(14) };
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    virtual Int_t CheckFileHeader() { return 0; }
+
+protected:
+    fits *fIn;         //! buffered input stream (file to read from)
+
+public:
+    MReportFitsRead(const char *filename, const char *name=NULL, const char *title=NULL);
+    ~MReportFitsRead();
+
+    void SetHasNoHeader() { SetBit(kHasNoHeader); }
+    void SetTimeStart(const MTime &tm) { fStart = tm; }
+    void SetTimeStop(const MTime &tm)  { fStop = tm; }
+
+    void SetReportName(const char *name) { fReportName = name; }
+
+    ClassDef(MReportFitsRead, 0)// Task to read general report file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportHelp.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportHelp.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportHelp.cc	(revision 17960)
@@ -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, 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)
+{
+    //
+    // create the parameter container of the the given class type
+    //
+    *fLog << err;
+    TClass *cls = MParList::GetClass(name, fLog);
+
+    if (cls && cls->InheritsFrom(MReport::Class()))
+        fReport = static_cast<MReport*>(cls->New());
+}
+
+// --------------------------------------------------------------------------
+//
+// The instance of the MReport-class is deleted
+//
+MReportHelp::~MReportHelp()
+{
+    if (fReport)
+        delete fReport;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Identifier ("DRIVE-REPORT") as name. This allows
+// calling FindObject("[identifier]") in lists.
+//
+const char *MReportHelp::GetName() const
+{
+    return fReport->GetIdentifier();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Identifier ("DRIVE-REPORT") hash value as hash value. This
+// allows faster access b usage of a THashTable
+//
+ULong_t MReportHelp::Hash() const
+{
+    return fReport->GetIdentifier().Hash();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the Interprete function of the report and counts the number of
+// successfull interpretations.
+//
+Int_t MReportHelp::Interprete(TString &str, const MTime &start, const MTime &stop, Int_t ver)
+{
+    const Int_t rc = fReport->Interprete(str, start, stop, ver);
+
+    switch (rc)
+    {
+    case kTRUE:     fNumReports++; break;
+    case kCONTINUE: fNumSkipped++; break;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the Setip function for reading of the report
+//
+Bool_t MReportHelp::SetupReading(MParList &plist)
+{
+    return fReport->SetupReading(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the report to the given parameter list.
+//
+void MReportHelp::AddToList(MParList &plist)
+{
+    plist.AddToList(fReport);
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportHelp.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportHelp.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportHelp.h	(revision 17960)
@@ -0,0 +1,41 @@
+#ifndef MARS_MReportHelp
+#define MARS_MReportHelp
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+
+class TString;
+
+class MLog;
+class MTime;
+class MReport;
+class MParList;
+
+class MReportHelp : public TObject
+{
+private:
+    MReport *fReport;
+    ULong_t  fNumReports;
+    ULong_t  fNumSkipped;
+
+public:
+    MReportHelp(const char *name, MLog *fLog);
+    ~MReportHelp();
+
+    const char *GetName() const;
+    ULong_t GetNumReports() const { return fNumReports; }
+    ULong_t GetNumSkipped() const { return fNumSkipped; }
+    ULong_t Hash() const;
+    MReport *GetReport() { return fReport; }
+
+    Int_t Interprete(TString &str, const MTime &start, const MTime &stop, Int_t ver);
+
+    Bool_t SetupReading(MParList &plist);
+    
+    void AddToList(MParList &plist);
+
+    ClassDef(MReportHelp, 0) // Wrapper class for MReport to speed up finding the correct MReport-class
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportHumidity.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportHumidity.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportHumidity.cc	(revision 17960)
@@ -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, 02/2012 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportHumidity
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportHumidity.h"
+
+#include "fits.h"
+
+#include "MLogManip.h"
+
+ClassImp(MReportHumidity);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "DRIVE-REPORT"
+//
+MReportHumidity::MReportHumidity() : MReport("TEMPERATURES-REPORT"),
+    fTimeStamp(0)
+{
+    fName  = "MReportHumidity";
+    fTitle = "Class for DRIVE-REPORT information (raw telescope position)";
+
+    memset(fHumidity, 0, sizeof(Float_t)*4);
+}
+
+Bool_t MReportHumidity::SetupReadingFits(fits &file)
+{
+    return
+        file.SetRefAddress("t",  fTimeStamp)   &&
+        file.SetPtrAddress("H",  fHumidity, 4);
+}
+
+Int_t MReportHumidity::InterpreteFits(const fits &fits)
+{
+    return kTRUE;
+}
+
+Float_t MReportHumidity::GetMean() const
+{
+    Double_t avg = 0;
+    for (int i=0; i<4; i++)
+        avg += fHumidity[i];
+
+    return avg/4;
+}
+
+void MReportHumidity::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": Time=" << fTimeStamp << " Hum=" << GetMean() << "%" << endl;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportHumidity.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportHumidity.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportHumidity.h	(revision 17960)
@@ -0,0 +1,28 @@
+#ifndef MARS_MReportHumidity
+#define MARS_MReportHumidity
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportHumidity : public MReport
+{
+private:
+    Float_t fTimeStamp;   // [s] FSC uptime
+    Float_t fHumidity[4]; // H[%] Humidity sensors readout
+
+    Bool_t SetupReadingFits(fits &fits);
+    Int_t  InterpreteFits(const fits &fits);
+
+public:
+    MReportHumidity();
+
+    Float_t GetTimeStamp() const { return fTimeStamp; }
+    Float_t GetMean() const;
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MReportHumidity, 1) // Class for FTM_CONTROL/TRIGGER_RATES
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportPyrometer.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportPyrometer.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportPyrometer.cc	(revision 17960)
@@ -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, 6/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportPyrometer
+//
+// This is the class interpreting and storing the PYRO-REPORT information.
+//
+// These reports exist since 2007/05/15
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportPyrometer.h"
+
+#include "MLogManip.h"
+
+ClassImp(MReportPyrometer);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "RUN-REPORT" No subsystem
+// is expected.
+//
+MReportPyrometer::MReportPyrometer() : MReport("PYRO-REPORT"),
+    fTempSky(-1), fTempAir(-1), fCloudiness(-1), fLidOpen(kFALSE)
+
+{
+    fName  = "MReportPyrometer";
+    fTitle = "Class for PYRO-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the PYRO-REPORT string
+//
+Int_t MReportPyrometer::InterpreteBody(TString &str, Int_t ver)
+{
+    str = str.Strip(TString::kBoth);
+
+    Int_t status, len;
+
+    const Int_t n=sscanf(str.Data(), "%f %f %d %f %n",
+                         &fTempSky, &fCloudiness, &status, &fTempAir, &len);
+    if (n!=4)
+    {
+        *fLog << warn << "WARNING - Wrong number of arguments." << endl;
+        return kCONTINUE;
+    }
+
+    fLidOpen = status>0;
+
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    return str=="OVER" ? kTRUE : kCONTINUE;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportPyrometer.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportPyrometer.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportPyrometer.h	(revision 17960)
@@ -0,0 +1,32 @@
+#ifndef MARS_MReportPyrometer
+#define MARS_MReportPyrometer
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportPyrometer : public MReport
+{
+private:
+    Float_t fTempSky;     // [K] Temperature Sky
+    Float_t fTempAir;     // [K] Tempareture Air
+    Float_t fCloudiness;  // [%] Cloudiness
+
+    Bool_t  fLidOpen;     //     Lid Status
+
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportPyrometer();
+
+    Float_t GetTempSky() const { return fTempSky; }
+    Float_t GetTempAir() const { return fTempAir; }
+
+    Float_t GetCloudiness() const { return fCloudiness; }
+
+    Bool_t IsLidOpen() const { return fLidOpen; }
+
+    ClassDef(MReportPyrometer, 1) // Class for PYRO-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportRates.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportRates.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportRates.cc	(revision 17960)
@@ -0,0 +1,83 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2012 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportRates
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportRates.h"
+
+#include "fits.h"
+
+#include "MLogManip.h"
+
+ClassImp(MReportRates);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "DRIVE-REPORT"
+//
+MReportRates::MReportRates() : MReport("RATES-REPORT"),
+    fTimeStamp(0), fOnTimeCounter(0), fTriggerCounter(0), fTriggerRate(0),
+    fElapsedTime(0), fElapsedOnTime(0)
+{
+    fName  = "MReportRates";
+    fTitle = "Class for DRIVE-REPORT information (raw telescope position)";
+
+    memset(fBoardRate, 0, sizeof(Float_t)*40);
+    memset(fPatchRate, 0, sizeof(Float_t)*160);
+}
+
+Bool_t MReportRates::SetupReadingFits(fits &file)
+{
+    return
+        file.SetRefAddress("FTMtimeStamp",   fTimeStamp)       &&
+        file.SetRefAddress("OnTimeCounter",  fOnTimeCounter)   &&
+        file.SetRefAddress("TriggerCounter", fTriggerCounter)  &&
+        file.SetRefAddress("TriggerRate",    fTriggerRate)     &&
+        file.SetPtrAddress("BoardRate",      fBoardRate,  40)  &&
+        file.SetPtrAddress("PatchRate",      fPatchRate, 160)  &&
+        file.SetRefAddress("ElapsedTime",    fElapsedTime)     &&
+        file.SetRefAddress("OnTime",         fElapsedOnTime);
+}
+
+Int_t MReportRates::InterpreteFits(const fits &fits)
+{
+    if (fElapsedTime>0 || fElapsedOnTime>0)
+        return kTRUE;
+
+    fElapsedTime   = fTimeStamp*1e-6;
+    fElapsedOnTime = fOnTimeCounter*1e-6;
+    fTriggerRate   = fTriggerCounter*1e6/fTimeStamp;
+
+    return kTRUE;
+}
+
+void MReportRates::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": Time=" << fTimeStamp << "/" << fElapsedTime << " OnTime=" << fOnTimeCounter << "/" << fElapsedOnTime << endl;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportRates.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportRates.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportRates.h	(revision 17960)
@@ -0,0 +1,38 @@
+#ifndef MARS_MReportRates
+#define MARS_MReportRates
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportRates : public MReport
+{
+private:
+    ULong64_t fTimeStamp;       // [us] Time in microseconds, since trigger enabled or disabled
+    ULong64_t fOnTimeCounter;   // [us] Effective on-time, i.e. FTM processes triggers (e.g. No FAD busy)
+    UInt_t    fTriggerCounter;  //      Counter of camera trigers (events) since trigger enabled or disabled"
+    Float_t   fTriggerRate;     // [Hz] Trigger rate"
+    Float_t   fBoardRate[40];   // [Hz] Board rates
+    Float_t   fPatchRate[160];  // [Hz] Patch rates
+    Float_t   fElapsedTime;     // [s]  Time elapsed since previous report
+    Float_t   fElapsedOnTime;   // [s]  On-time elapsed since previous report
+
+    Bool_t SetupReadingFits(fits &fits);
+    Int_t  InterpreteFits(const fits &fits);
+
+public:
+    MReportRates();
+
+    ULong64_t GetTimeStamp() const      { return fTimeStamp;      }
+    ULong64_t GetOnTimeCounter() const  { return fOnTimeCounter;  }
+    UInt_t    GetTriggerCounter() const { return fTriggerCounter; }
+    Float_t   GetTriggerRate() const    { return fTriggerRate;    }
+    Float_t   GetElapsedTime() const    { return fElapsedTime;    }
+    Float_t   GetElapsedOnTime() const  { return fElapsedOnTime;  }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MReportRates, 1) // Class for FTM_CONTROL/TRIGGER_RATES
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportRec.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportRec.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportRec.cc	(revision 17960)
@@ -0,0 +1,131 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2008 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2008
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportRec
+//
+// This is the class interpreting and storing the REC-REPORT information.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportRec.h"
+
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCameraTH.h"
+#include "MCameraTD.h"
+#include "MCameraRecTemp.h"
+
+ClassImp(MReportRec);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "CC-REPORT" Report
+// is expected to have no 'subsystem' time.
+//
+MReportRec::MReportRec() : MReport("REC-REPORT", kFALSE)
+{
+    fName  = "MReportRec";
+    fTitle = "Class for REC-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MCameraTH
+//
+Bool_t MReportRec::SetupReading(MParList &plist)
+{
+    fTH = (MCameraTH*)plist.FindCreateObj("MCameraTH");
+    if (!fTH)
+        return kFALSE;
+
+    fTD = (MCameraTD*)plist.FindCreateObj("MCameraTD");
+    if (!fTD)
+        return kFALSE;
+
+    fRecTemp = (MCameraRecTemp*)plist.FindCreateObj("MCameraRecTemp");
+    if (!fRecTemp)
+        return kFALSE;
+
+    return MReport::SetupReading(plist);
+}
+
+Int_t MReportRec::InterpreteRec(TString &str, Int_t ver, MCameraTH &th, MCameraTD &td, MCameraRecTemp &temp)
+{
+    if (str.BeginsWith("RECEIVERS-COM-ERROR"))
+    {
+        *fLog << inf << "Receiver Com-error... threshold setting and receiver board temp. invalid." << endl;
+        td.Invalidate();
+        th.Invalidate();
+        temp.Invalidate();
+        str.Remove(0, 19);
+
+        return kTRUE;
+    }
+
+    if (!CheckTag(str, "TH "))
+        return kFALSE;
+
+    if (!th.InterpreteTH(str, ver, td))
+        return kCONTINUE;
+
+    if (!CheckTag(str, "TD "))
+        return kFALSE;
+
+    if (!td.InterpreteTD(str, ver))
+        return kCONTINUE;
+
+    if (ver<200510250)
+        return kTRUE;
+
+    if (!CheckTag(str, "RECTEMP "))
+        return kFALSE;
+
+    if (!temp.InterpreteRecTemp(str))
+        return kCONTINUE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the CC-REPORT string
+//
+Int_t MReportRec::InterpreteBody(TString &str, Int_t ver)
+{
+    InterpreteRec(str, ver, *fTH, *fTD, *fRecTemp);
+
+    if (str.Strip(TString::kBoth)!=(TString)"OVER")
+    {
+        *fLog << warn << "WARNING - 'OVER' tag not found." << endl;
+        return kCONTINUE;
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportRec.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportRec.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportRec.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MReportRec
+#define MARS_MReportRec
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MCameraTH;
+class MCameraTD;
+class MCameraRecTemp;
+
+class MReportRec : public MReport
+{
+    friend class MReportCC;
+private:
+    MCameraTH      *fTH;      //! Discriminator thresholds
+    MCameraTD      *fTD;      //! Discriminator delays
+    MCameraRecTemp *fRecTemp; //! Receiver Board temperatures
+
+    // Internal
+    Bool_t SetupReading(MParList &plist);
+
+    Bool_t InterpreteTH(TString &str, Int_t ver);
+    Bool_t InterpreteTD(TString &str, Int_t ver);
+    Bool_t InterpreteRecTemp(TString &str);
+
+    // MReport
+    Int_t InterpreteRec(TString &str, Int_t ver, MCameraTH &th, MCameraTD &td, MCameraRecTemp &temp);
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportRec();
+
+    ClassDef(MReportRec, 1) // Class for REC-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportRun.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportRun.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportRun.cc	(revision 17960)
@@ -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, 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"
+
+ClassImp(MReportRun);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "RUN-REPORT" No subsystem
+// is expected.
+//
+MReportRun::MReportRun() : MReport("RUN-REPORT", kFALSE), fRunNumber(-1)
+{
+    fName  = "MReportRun";
+    fTitle = "Class for RUN-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the RUN-REPORT string
+//
+Int_t MReportRun::InterpreteBody(TString &str, Int_t ver)
+{
+    // --------- Get Token (START/STOP) ---------
+
+    const Int_t ws = str.First(' ');
+    if (ws<0)
+    {
+        *fLog << warn << "WARNING - Token not found." << endl;
+        return kCONTINUE;
+    }
+    const TString tok=str(0, ws);
+
+    str.Remove(0, ws);
+    str = str.Strip(TString::kBoth);
+
+    // --------- Get Run Number ---------
+
+    Int_t len, run;
+    const Int_t n=sscanf(str.Data(), "%d %n", &run, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Wrong number of arguments." << endl;
+        return kCONTINUE;
+    }
+    str.Remove(0, len);
+
+    // --------- Get File Number ---------
+    Int_t file = 0;
+    if (ver>=200805190)
+    {
+        const Int_t nn=sscanf(str.Data(), "%d %n", &file, &len);
+        if (nn!=1)
+        {
+            *fLog << warn << "WARNING - Wrong number of arguments." << endl;
+            return kCONTINUE;
+        }
+        str.Remove(0, len);
+    }
+
+    // --------- Invalidate Run/File Number if run was stopped ---------
+    if (tok=="START")
+    {
+        if (fRunNumber!=-1)
+            *fLog << warn << "WARNING - RUN-REPORT STOP missing for run #" << dec << fRunNumber <<  endl;
+
+        fRunNumber  = run;
+        fFileNumber = file;
+    }
+
+    if (tok=="STOP")
+    {
+        if (fRunNumber==-1)
+            *fLog << warn << "WARNING - RUN-REPORT START missing for run #" << dec << fRunNumber << endl;
+        else
+        {
+            if (fRunNumber!=run)
+                *fLog << warn << "WARNING - RUN-REPORT STOP run number #" << dec << run << " doesn't match started run #" << fRunNumber << "." << endl;
+
+            if (fFileNumber!=file)
+                *fLog << warn << "WARNING - RUN-REPORT STOP file number #" << dec << run << " doesn't match started file #" << fFileNumber << "." << endl;
+        }
+
+        fRunNumber  = -1;
+        fFileNumber = -1;
+    }
+
+    // --------- Get source name ---------
+    Ssiz_t pos = str.First(' ');
+    if (pos<0)
+        pos = str.Length();
+    fSourceName = TString(str(0, pos+1)).Strip(TString::kBoth);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportRun.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportRun.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportRun.h	(revision 17960)
@@ -0,0 +1,29 @@
+#ifndef MARS_MReportRun
+#define MARS_MReportRun
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportRun : public MReport
+{
+private:
+    Int_t   fRunNumber;
+    Int_t   fFileNumber;
+    TString fSourceName;
+
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportRun();
+
+    const TString &GetSourceName() const { return fSourceName; }
+    TString GetSourceName() { return fSourceName; }
+
+    Int_t GetRunNumber() const  { return fRunNumber; }
+    Int_t GetFileNumber() const { return fFileNumber; }
+
+    ClassDef(MReportRun, 0) // Class for RUN-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportStarguider.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportStarguider.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportStarguider.cc	(revision 17960)
@@ -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): Benjamin Riegel, 01/2005 <mailto:riegel@astro.uni-wuerzburg.de>
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportStarguider
+//
+// This is the class interpreting and storing the STARG-REPORT information.
+//
+// This is the place to get the azimuth-/zenith mispointing of the telescope
+// given by the starguider-camera.
+//
+//
+// Starguider reports are available since 2004/11/17.
+// The nomnial pointing position is available since 2005/03/22
+// The sky brightness and the number of identified stars since 2005/03/17
+//
+// Position at which the starguider camera is pointing in real:
+//       pointing position = nominal position - dev
+//
+// Class Version 1:
+// ----------------
+//  + Double_t fDevAz;          // [arcmin]   azimuth mispointing
+//  + Double_t fDevZd;          // [arcmin]   zenith  mispointing
+//
+//
+// Class Version 2:
+// ----------------
+//  + Double_t fNominalZd;          // [deg] Nominal zenith distance
+//  + Double_t fNominalAz;          // [deg] Nominal azimuth
+//
+//  + Float_t  fCameraCenterX;      // [CCD pix] PMT Camera center found
+//  + Float_t  fCameraCenterY;      // [CCD pix] PMT Camera center found
+//
+//  + UInt_t   fNumIdentifiedStars; // Number of stars identified by starguider algorithm
+//
+//  + Double_t fSkyBrightness;      // [au] Sky Brightness as calcualted from the CCD image
+//  + Double_t fMjd;                // Modified Julian Date matching the nominal position
+//
+//
+// Class Version 3:
+// ----------------
+//  + UInt_t   fNumCorrelatedStars; // Number of correlated stars identified by starguider algorithm
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportStarguider.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MReportStarguider);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Initialize identifier to "STARG-REPORT"
+//
+MReportStarguider::MReportStarguider() : MReport("STARG-REPORT")/*,
+    fDevAz(0), fDevZd(0), fNominalZd(0), fNominalAz(0),
+    fCameraCenterX(0), fCameraCenterY(0), fNumIdentifiedStars(0),
+    fNumCorrelatedStars(0), fSkyBrightness(0)*/
+{
+    fName  = "MReportStarguider";
+    fTitle = "Class for STARG-REPORT information (telescope mispointing)";
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the STARG-REPORT string
+//
+void MReportStarguider::Clear(Option_t *o)
+{
+    fDevAz              = 0;
+    fDevZd              = 0;
+
+    fNominalZd          = 0;
+    fNominalAz          = 0;
+
+    fCameraCenterX      = 0;
+    fCameraCenterY      = 0;
+
+    fNumIdentifiedStars = 0;
+    fNumCorrelatedStars = 0;
+
+    fSkyBrightness      = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the STARG-REPORT string
+//
+Int_t MReportStarguider::InterpreteBody(TString &str, Int_t ver)
+{
+    Int_t len;
+    Int_t n=sscanf(str.Data(), "%lf %lf %n", &fDevZd, &fDevAz, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    if (ver<200503170)
+    {
+        // Fix a problem with the units
+        fDevAz *= 60./TMath::RadToDeg();
+        fDevZd *= 60./TMath::RadToDeg();
+        return str.IsNull() ? kTRUE : kCONTINUE;
+    }
+
+    MAstro::String2Angle(str, fNominalZd);   // Nom Zd
+    MAstro::String2Angle(str, fNominalAz);   // Nom Az
+
+    if (ver<200503220)
+    {
+        // Until a fix in the software the written position was nonsense
+        fNominalZd = 0;
+        fNominalAz = 0;
+    }
+
+    n=sscanf(str.Data(), "%f %f %d %lf %lf %n",
+             &fCameraCenterX, &fCameraCenterY, &fNumIdentifiedStars,
+             &fSkyBrightness, &fMjd, &len);
+    if (n!=5)
+    {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    // Seems that hasn't yet been implemented
+    if ((ver>=200508290 && ver<200509300) ||
+        (ver>=200603080))
+    {          
+        // For the moment this are only placeholders....
+        Float_t dx, dy;
+        n=sscanf(str.Data(), "%f %f %n", &dx, &dy, &len);
+        if (n!=2 && ((n!=0&&n!=EOF) || ver!=200603080))
+        {
+            *fLog << warn << "WARNING - Not enough arguments." << endl;
+            return kCONTINUE;
+        }
+
+        str.Remove(0, len);
+        str = str.Strip(TString::kBoth);
+    }
+
+    if (ver>=200605080)
+    {
+        fNumCorrelatedStars = fNumIdentifiedStars;
+        n=sscanf(str.Data(), "%df %n", &fNumIdentifiedStars, &len);
+        if (n!=1)
+        {
+            *fLog << warn << "WARNING - Not enough arguments." << endl;
+            *fLog << str << endl;
+            return kCONTINUE;
+        }
+
+        str.Remove(0, len);
+        str = str.Strip(TString::kBoth);
+    }
+
+    return str.IsNull() ? kTRUE : kCONTINUE;
+}
+
+Double_t MReportStarguider::GetDevAbs() const
+{
+    // Crosscheck SIGN!!!!
+    return MAstro::GetDevAbs(fNominalZd, fNominalZd-fDevZd/60, fDevAz/60)*60;
+}
+
+void MReportStarguider::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " DevZd=" << fDevZd << " DevAz=" << fDevAz << endl;
+    *fLog << " NominalZd=" << fNominalZd << " NominalAz=" << fDevAz << " MJD=" << fMjd << endl;
+    *fLog << " CameraCenterX=" << fCameraCenterX << " CameraCenterY=" << fCameraCenterY << endl;
+    *fLog << " NumIdentifiedStars=" << fNumIdentifiedStars << endl;
+    *fLog << " NumIdentifiedStars=" << fNumIdentifiedStars << " SkyBrightness=" << fSkyBrightness << endl;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportStarguider.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportStarguider.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportStarguider.h	(revision 17960)
@@ -0,0 +1,66 @@
+#ifndef MARS_MReportStarguider
+#define MARS_MReportStarguider
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+class MReportStarguider : public MReport
+{
+public:
+    enum { kError=0, kStandby=2, kMonitoring=4 };
+
+private:
+    Double_t fDevAz;              // [arcmin] azimuth mispointing
+    Double_t fDevZd;              // [arcmin] zenith  mispointing
+
+    Double_t fNominalZd;          // [deg] Nominal zenith distance
+    Double_t fNominalAz;          // [deg] Nominal azimuth
+
+    Float_t  fCameraCenterX;      // [CCD pix] PMT Camera center found
+    Float_t  fCameraCenterY;      // [CCD pix] PMT Camera center found
+
+    UInt_t   fNumIdentifiedStars; // Number of stars identified by starguider algorithm
+    UInt_t   fNumCorrelatedStars; // Number of correlated stars identified by starguider algorithm
+
+    Double_t fSkyBrightness;      // [au] Sky Brightness as calcualted from the CCD image
+    Double_t fMjd;                // Modified Julian Date matching the nominal position
+
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportStarguider();
+
+    void Clear(Option_t *o="");
+
+    Double_t GetDevAz() const { return fDevAz; }
+    Double_t GetDevZd() const { return fDevZd; }
+    Double_t GetDevAbs() const;
+    TVector2 GetDev() const { return TVector2(fDevZd, fDevAz); }
+
+    Double_t GetNominalZd() const { return fNominalZd; }
+    Double_t GetNominalAz() const { return fNominalAz; }
+    TVector2 GetNominalPos() const { return TVector2(fNominalZd, fNominalAz); }
+
+    Float_t  GetCameraCenterX() const { return fCameraCenterX; }
+    Float_t  GetCameraCenterY() const { return fCameraCenterY; }
+    TVector2 GetCameraCenter() const { return TVector2(fCameraCenterX, fCameraCenterY); }
+
+    UInt_t   GetNumIdentifiedStars() const { return fNumIdentifiedStars; }
+    UInt_t   GetNumCorrelatedStars() const { return fNumCorrelatedStars; }
+
+    Double_t GetSkyBrightness() const { return fSkyBrightness; }
+    Double_t GetMjd() const { return fMjd; }
+
+    Bool_t IsMonitoring() const { return GetState()==kMonitoring; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MReportStarguider, 3) // Class for STARG-REPORT information
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportTemperatures.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportTemperatures.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportTemperatures.cc	(revision 17960)
@@ -0,0 +1,109 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2012 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2012
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportTemperatures
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportTemperatures.h"
+
+#include "fits.h"
+
+#include "MLogManip.h"
+
+ClassImp(MReportTemperatures);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "DRIVE-REPORT"
+//
+MReportTemperatures::MReportTemperatures() : MReport("TEMPERATURES-REPORT"),
+    fTimeStamp(0)
+{
+    fName  = "MReportTemperatures";
+    fTitle = "Class for DRIVE-REPORT information (raw telescope position)";
+
+    memset(fTempSensors,  0, sizeof(Float_t)*31);
+    memset(fTempCrate,    0, sizeof(Float_t)*8);
+    memset(fTempPS,       0, sizeof(Float_t)*8);
+    memset(fTempAux,      0, sizeof(Float_t)*4);
+    memset(fTempBack,     0, sizeof(Float_t)*4);
+    memset(fTempEthernet, 0, sizeof(Float_t)*4);
+}
+
+Bool_t MReportTemperatures::SetupReadingFits(fits &file)
+{
+    return
+        file.SetRefAddress("t",       fTimeStamp)       &&
+        file.SetPtrAddress("T_sens",  fTempSensors, 31) &&
+        file.SetPtrAddress("T_crate", fTempCrate,    8) &&
+        file.SetPtrAddress("T_ps",    fTempPS,       8) &&
+        file.SetPtrAddress("T_aux",   fTempAux,      4) &&
+        file.SetPtrAddress("T_back",  fTempBack,     4) &&
+        file.SetPtrAddress("T_eth",   fTempEthernet, 4);
+}
+
+Int_t MReportTemperatures::InterpreteFits(const fits &fits)
+{
+    return kTRUE;
+}
+
+Float_t MReportTemperatures::GetTempMean() const
+{
+    Double_t avg = 0;
+    UInt_t   num = 0;
+
+    for (int i=0; i<31; i++)
+    {
+        if (fTempSensors[i]==0)
+            continue;
+
+        avg += fTempSensors[i];
+        num++;
+    }
+
+    return avg/num;
+}
+
+Float_t MReportTemperatures::GetTempMedian() const
+{
+    Float_t dat[31];
+    UInt_t  num = 0;
+
+    for (int i=0; i<31; i++)
+    {
+        if (fTempSensors[i]!=0)
+            dat[num++] = fTempSensors[i];
+    }
+
+    return TMath::Median(num, dat);
+}
+
+void MReportTemperatures::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": Time=" << fTimeStamp << endl;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportTemperatures.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportTemperatures.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportTemperatures.h	(revision 17960)
@@ -0,0 +1,34 @@
+#ifndef MARS_MReportTemperatures
+#define MARS_MReportTemperatures
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportTemperatures : public MReport
+{
+private:
+    Float_t fTimeStamp;        // [s] FSC uptime
+    Float_t fTempSensors[31];  // [deg C] Sensor compartment temperatures
+    Float_t fTempCrate[8];     // [deg C] Temperatures crate 0 (back/front), 1 (back/front), 2 (back/front), 3 (back/front)"
+    Float_t fTempPS[8];        // [deg C] Temperatures power supplies crate 0 (back/front), 1 (back/front), 2 (back/front), 3 (back/front)
+    Float_t fTempAux[4];       // [deg C] Auxiliary power supply temperatures FTM (top/bottom), FSC (top/bottom)
+    Float_t fTempBack[4];      // [deg C] FTM backpanel temperatures FTM (top/bottom), FSC (top/bottom)
+    Float_t fTempEthernet[4];  // [deg C] Ethernet switches temperatures top (front/back), bottom (front/back)
+
+    Bool_t SetupReadingFits(fits &fits);
+    Int_t  InterpreteFits(const fits &fits);
+
+public:
+    MReportTemperatures();
+
+    Float_t GetTimeStamp() const { return fTimeStamp; }
+    Float_t GetTempMean() const;
+    Float_t GetTempMedian() const;
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MReportTemperatures, 1) // Class for FTM_CONTROL/TRIGGER_RATES
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/MReportTrigger.cc
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportTrigger.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportTrigger.cc	(revision 17960)
@@ -0,0 +1,493 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+! 
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportTrigger
+//
+// This is the class interpreting and storing the TRIGGER-REPORT information.
+//  Updated to add IPR; data format follows TDAS 00-07 ver.6.3 jul-04
+//  http://hegra1.mppmu.mpg.de/MAGIC/private/software/doc/control/tdas0007_v6.3.ps.gz
+//  
+//  *Input:
+//
+//  The report is divided into 9 sections: 
+//  - the name of the Table                 (1 field)
+//  - the cell rates                       (32 fields)
+//  - L1 and L2 table name                 ( 2 fields)
+//  - prescaling factors                  (2x8 fields)
+//  - livetime and deadtime               (5x4 fields)
+//  - L2 output bit rates                (20 integers)
+//  - global rates (before/after presc.)    (2 floats)
+//  - 18 dummy fields                      (18 fields)
+//  - IPR                    (325 hexs + 397 integers) 
+//
+//  *Output:
+//
+//  The values read from the report string are used to fill the following 
+//  containers:
+//  - MTriggerIPR        (Individual Pixel Rates)
+//  - MTriggerCell       (Rate of trigger cells)
+//  - MTriggerBit        (Output Bits from prescaler (before and after presc.)
+//  - MTriggerPrescFact  (Prescaling factors for each bit)
+//  - MTriggerLiveTime   (Values of counters for dead/livetime)
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportTrigger.h"
+
+#include "MParList.h"
+
+#include "MLogManip.h"
+
+#include "MTriggerIPR.h"
+#include "MTriggerCell.h"
+#include "MTriggerBit.h"
+#include "MTriggerPrescFact.h"
+#include "MTriggerLiveTime.h"
+
+#include "MReportFileRead.h"
+
+ClassImp(MReportTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "TRIGGER-REPORT"
+//
+MReportTrigger::MReportTrigger() : MReport("TRIGGER-REPORT")
+{
+    fName  = "MReportTrigger";
+    fTitle = "Class for TRIGGER-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MTriggerIPR
+//  - MTriggerCell
+//  - MTriggerBit
+//  - MTriggerPrescFact
+//  - MTriggerLiveTime
+//
+Bool_t MReportTrigger::SetupReading(MParList &plist)
+{
+  fIPR = (MTriggerIPR*)plist.FindCreateObj("MTriggerIPR");
+  if (!fIPR)
+    return kFALSE;
+
+  fCell = (MTriggerCell*)plist.FindCreateObj("MTriggerCell");
+  if (!fCell)
+    return kFALSE;
+
+  fBit = (MTriggerBit*)plist.FindCreateObj("MTriggerBit");
+  if (!fBit)
+    return kFALSE;
+
+  fPrescFactor = (MTriggerPrescFact*)plist.FindCreateObj("MTriggerPrescFact");
+  if (!fPrescFactor)
+    return kFALSE;
+
+  fLiveTime = (MTriggerLiveTime*)plist.FindCreateObj("MTriggerLiveTime");
+  if (!fLiveTime)
+    return kFALSE;
+  
+  return MReport::SetupReading(plist);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Cell rates section of the report
+//  Read 32 floats separated with a blank
+//
+Bool_t MReportTrigger::InterpreteCell(TString &str)
+{
+  Int_t len=0, n, i=0;
+  Int_t gsNCells=32;
+
+  for (i=0;i<gsNCells;i++)
+    {
+      n = sscanf(str.Data(), " %f %n", &fCell->fCellRate[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Cell Scaler Value #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove cell rates from report string
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Prescaling factors section of the report
+//
+Bool_t MReportTrigger::InterpretePrescFact(TString &str)
+{
+  Int_t len=0, n, i=0;
+  Int_t gsNPrescFacts=8;
+  
+  str.Remove(0, 1);
+
+  for (i=0;i<gsNPrescFacts;i++)
+    {
+    const Int_t ws = str.First(' ');
+    if (ws<=0)
+       {
+	 *fLog << warn << "WARNING - Cannot determine Prescaling factor #" << i << " descriptor" << endl;
+        return kCONTINUE;
+       }
+    TString descriptor = str(0, ws);
+    str.Remove(0, ws);
+      
+      n = sscanf(str.Data(), " %li %n", &fPrescFactor->fPrescFact[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - prescaler factor " << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove Prescal. factors from report string
+    }
+  str=str.Strip(TString::kLeading);  
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Scalers with Live-Deadtime section of the report
+//  Read 4x5 integers separated with a blank
+//  There are 5 scalers,each one with the live and deadtime.
+//  Live and deadtimes have two fields, with the most significant
+//  and less significant bits.
+//
+Bool_t MReportTrigger::InterpreteLiveTime(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNScalers=5;
+  Int_t  dLSB, dMSB,lLSB, lMSB;
+
+  for (i=0;i<gsNScalers;i++)
+    {
+      n = sscanf(str.Data(), " %d %d %d %d %n", &lLSB, &lMSB,&dLSB, &dMSB, &len);
+      if (n!=4)
+	{
+	  *fLog << warn << "WARNING - Live-Deadtime Scaler Value #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+
+      str.Remove(0, len); // Remove Live-Deadtimes from string
+
+      //convert to seconds and fill container
+      // (FIXME! only the MSB (seconds is now considered)
+      (fLiveTime->fLiveTime)[i] = lMSB;
+      (fLiveTime->fDeadTime)[i] = dMSB;      
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Bit rates section of the report
+// 20 integers. First and last two are not used
+//
+Bool_t MReportTrigger::InterpreteBit(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNBits=20;
+  
+  for (i=0;i<gsNBits;i++)
+    {
+      n = sscanf(str.Data(), " %f %n", &fBit->fBit[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Bit rate #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove output bit rates from string
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the L1 and L2 table names
+// 1String + 1Int +1 String
+//
+Bool_t MReportTrigger::InterpreteL1L2Table(TString &str)
+{
+    const Int_t wsL1 = str.First(' ');
+ 
+    if (wsL1<=0)
+       {
+        *fLog << warn << "WARNING - Cannot determine name of L1 trigger table." << endl;
+        return kCONTINUE;
+       }
+    
+    fL1Tablename = str(0, wsL1);
+    str.Remove(0, wsL1);
+
+    // remove an integer between names
+    Int_t len;
+    Int_t mi;
+    Int_t n=sscanf(str.Data(), "%d %n", &mi, &len);
+    if (n!=1)
+      {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+    str.Remove(0, len);
+
+    // L2 tablename
+    const Int_t wsL2 = str.First(' ');
+ 
+    if (wsL2<=0)
+      {
+        *fLog << warn << "WARNING - Cannot determine name of L2 trigger table." << endl;
+        return kCONTINUE;
+      }    
+    fL2Tablename = str(0, wsL2);
+    str.Remove(0,wsL2);
+    str.Strip(TString::kBoth);
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete an unused section of the report 
+// 18 integers
+//
+Bool_t MReportTrigger::InterpreteDummy(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNDummies=18;
+  Int_t dummy;  
+
+  for (i=0;i<gsNDummies;i++)
+    {
+      n = sscanf(str.Data(), " %d %n", &dummy, &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Dummy #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove dummies from report string
+
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the IPR section of the report
+//   sep-04
+//   The IPR are saved as 340 (=number of pixs in trigger area) hex numbers 
+//   and as 397 (= #pixs in inner region) dec numbers.
+//   Only the dec numbers are now saved in the MTriggerIPR container.
+//  
+
+Bool_t MReportTrigger::InterpreteIPR(TString &str)
+{
+
+  Int_t gsNhexIPR=340; //number of IPR saved in hex format
+  Int_t gsNdecIPR=397; //number of IPR saved in dec format
+  
+  // Read Individual pixel rates in hex format
+  const char *pos = str.Data();
+  const char *end = str.Data() + gsNhexIPR*8;
+  
+  Int_t i=0,n,len;
+  short dummy;
+  while (pos < end)
+    {
+      const Char_t hex[9] = { pos[0], pos[1], pos[2], pos[3],pos[4],pos[5],pos[6],pos[7],0 };
+      n = sscanf(hex, "%hx", &dummy);
+      pos+=8;
+      if (n!=1)
+        {
+	  *fLog << warn << "WARNING - Rate #" << i << " missing." << endl;
+	  return kFALSE;
+        }
+    }
+    
+  str.Remove(0, end-str.Data()); // Remove IPR hex  from report string
+  str.Strip(TString::kBoth);
+  
+  // ------  
+  // Read Individual pixel rates in dec format 
+  // and save them in the MTriggerIPR container
+  
+  for (i=0;i<gsNdecIPR;i++)
+    {
+      n = sscanf(str.Data(), " %ld %n", &fIPR->fIPR[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - IPR dec #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove IPR dec from report string      
+    }
+  
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the TRIGGER-REPORT string
+//  Read comments for details
+//
+Int_t MReportTrigger::InterpreteBody(TString &str, Int_t ver )
+{
+
+    str = str.Strip(TString::kLeading);
+ 
+    // Extract trigger table name
+    const Int_t ws = str.First(' ');
+ 
+   if (ws<=0)
+    {
+        *fLog << warn << "WARNING - Cannot determine name of trigger table." << endl;
+        return kCONTINUE;
+    }
+
+    fTablename = str(0, ws);
+    str.Remove(0, ws);
+
+    // Check the Version of CC file, and takes care of the differences
+    // introduced in the format of the report (on May 2004).
+
+    if (ver < 200405050)	
+      {
+	*fLog << warn << " WARNING - This is  an old TRIGGER-REPORT without IPRs" <<endl;
+        return InterpreteOldBody(str);
+      }
+
+    // Read the cell rates (32 fields)
+    if (!InterpreteCell(str))
+      return kCONTINUE;
+
+    // Read L1 and L2 table name (2 fields)
+    if (!InterpreteL1L2Table(str))
+      return kCONTINUE;    
+
+    // Read prescaling factors  (2x8 fields)
+    if (!InterpretePrescFact(str))
+      return kCONTINUE;
+    
+    // Read livetime and deadtime (5x4 fields)
+    if (!InterpreteLiveTime(str))
+      return kCONTINUE;
+
+    // Read L2 outout bit rates
+    if (!InterpreteBit(str))
+      return kCONTINUE;
+
+    // Read global rates (before and after prescaling)
+    Int_t len, n;
+    n = sscanf(str.Data(), " %f %f %n", &fL2BeforePrescaler, &fL2AfterPrescaler, &len);
+    if (n!=2)
+    {
+         *fLog << warn << "WARNING - Couldn't read Trigger rates." << endl;
+        return kFALSE;
+    }
+    str.Remove(0,len);
+    str.Strip(TString::kBoth);
+
+    // Read 18 dummy fields
+    if (!InterpreteDummy(str))
+      return kCONTINUE;
+
+    // Read IPR
+    if (!InterpreteIPR(str))
+      return kCONTINUE;
+
+    return str==(TString)"OVER" ? kTRUE : kCONTINUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the TRIGGER-REPORT string
+//  for OLD runs (older than may-04)
+//
+Bool_t MReportTrigger::InterpreteOldBody(TString &str)
+{
+
+  Int_t len, n;
+  Float_t fPrescalerRates[100]; 
+
+    const char *pos = str.Data();
+    for (int i=0; i<19; i++)
+      {
+        n = sscanf(pos, " %f %n", &fPrescalerRates[i], &len);
+        if (n!=1)
+	  {
+            *fLog << warn << "WARNING - Scaler Value #" << i << " missing." << endl;
+            return kCONTINUE;
+	  }
+        pos += len;
+      }
+
+    n = sscanf(pos, " %f %f %n", &fL2BeforePrescaler, &fL2AfterPrescaler, &len);
+    if (n!=2)
+      {
+        *fLog << warn << "WARNING - Couldn't read Trigger rates." << endl;
+        return kFALSE;
+      }
+    pos += len;
+    for (int i=0; i<11; i++)
+      {
+        Float_t dummy;
+        n = sscanf(pos, " %f %n", &dummy/*fRates[i]*/, &len);
+        if (n!=1)
+	  {
+            *fLog << warn << "WARNING - Rate #" << i << " missing." << endl;
+            return kFALSE;
+	  }
+        pos += len;
+      }
+    str.Remove(0, pos-str.Data());
+    str.Strip(TString::kBoth);
+    
+    return str==(TString)"OVER" ? kTRUE : kCONTINUE;
+}
Index: branches/Mars_McMismatchStudy/mreport/MReportTrigger.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/MReportTrigger.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/MReportTrigger.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MReportTrigger
+#define MARS_MReportTrigger
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerIPR;
+class MTriggerCell;
+class MTriggerBit;
+class MTriggerPrescFact;
+class MTriggerLiveTime;
+
+class MReportTrigger : public MReport
+{
+private:
+  
+  Float_t fL2BeforePrescaler;       // L2 trigger rate before prescaler
+  Float_t fL2AfterPrescaler;        // L2 trigger rate after prescaler
+  TString fTablename;               // Name of the trigger table
+  TString fL1Tablename;             // Name of the L1 trigger table
+  TString fL2Tablename;             // Name of the L2 trigger table
+  
+  MTriggerBit *fBit;                //! container of the L2 prescaler rates
+  MTriggerIPR *fIPR;                //! container of the IPR
+  MTriggerCell *fCell;              //! container of the L1 cell trigger rates
+  MTriggerPrescFact *fPrescFactor;  //! container of the L2 prescaling factors
+  MTriggerLiveTime *fLiveTime;      //! container of the scaler live-deadtime
+  
+  Bool_t SetupReading(MParList &plist);
+
+  Bool_t InterpreteIPR(TString &str);
+  Bool_t InterpreteCell(TString &str);
+  Bool_t InterpreteBit(TString &str);
+  Bool_t InterpretePrescFact(TString &str);
+  Bool_t InterpreteLiveTime(TString &str);
+  Bool_t InterpreteDummy(TString &str);
+  Bool_t InterpreteL1L2Table(TString &str);
+
+  Int_t InterpreteBody(TString &str, Int_t ver);
+  
+  Bool_t InterpreteOldBody(TString &str);
+
+public:
+    MReportTrigger();
+
+    Float_t GetL2BeforePrescaler() const { return fL2BeforePrescaler; }
+    Float_t GetL2AfterPrescaler() const { return fL2AfterPrescaler; }
+    TString GetTablename() const { return fTablename; } 
+    TString GetL1Tablename() const { return fL1Tablename; } 
+    TString GetL2Tablename() const { return fL2Tablename; } 
+
+    ClassDef(MReportTrigger, 2) // Class for TRIGGER-REPORT information
+ };
+
+#endif
Index: branches/Mars_McMismatchStudy/mreport/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mreport/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/Makefile	(revision 17960)
@@ -0,0 +1,51 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Report
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mastro -I../mcamera -I../mgui -I../mtrigger \
+	-I../mcore
+# mgui - MCameraDC <MCamEvent>
+
+SRCFILES = MReport.cc \
+           MReportCC.cc \
+           MReportRec.cc \
+           MReportRun.cc \
+           MReportDAQ.cc \
+           MReportHelp.cc \
+           MReportDrive.cc \
+           MReportCamera.cc \
+           MReportTrigger.cc \
+           MReportCurrents.cc \
+           MReportFitsRead.cc \
+           MReportFileRead.cc \
+           MReportFileReadCC.cc \
+           MReportStarguider.cc \
+           MReportPyrometer.cc \
+           MReportRates.cc \
+           MReportTemperatures.cc \
+           MReportHumidity.cc
+
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mreport/ReportIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/ReportIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/ReportIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mreport/ReportLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mreport/ReportLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mreport/ReportLinkDef.h	(revision 17960)
@@ -0,0 +1,30 @@
+#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 MReportRec+;
+#pragma link C++ class MReportRun+;
+#pragma link C++ class MReportDAQ+;
+#pragma link C++ class MReportDrive+;
+#pragma link C++ class MReportStarguider+;
+#pragma link C++ class MReportWeather+;
+#pragma link C++ class MReportCamera+;
+#pragma link C++ class MReportTrigger+;
+#pragma link C++ class MReportCurrents+;
+#pragma link C++ class MReportPyrometer+;
+
+#pragma link C++ class MReportRates+;
+#pragma link C++ class MReportHumidity+;
+#pragma link C++ class MReportTemperatures+;
+
+#pragma link C++ class MReportHelp+;
+#pragma link C++ class MReportFitsRead+;
+#pragma link C++ class MReportFileRead+;
+#pragma link C++ class MReportFileReadCC+;
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc.cc	(revision 17960)
@@ -0,0 +1,191 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Sebastian Raducci 12/2003 <mailto:raducci@fisica.uniud.it>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MArrivalTimeCalc
+//
+//   This is a task that calculates the arrival times of photons. 
+//   It returns the absolute maximum of the spline that interpolates
+//   the FADC slices 
+//
+// Input Containers:
+//   MRawEvtData
+//
+// Output Containers:
+//   MArrivalTime
+//   MRawEvtData
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTimeCalc.h"
+
+#include "MCubicSpline.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MRawEvtData.h"      
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MArrivalTimeCalc);
+
+using namespace std;
+
+const Byte_t MArrivalTimeCalc::fgSaturationLimit = 254;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// 
+MArrivalTimeCalc::MArrivalTimeCalc(const char *name, const char *title) 
+{
+
+    fName  = name  ? name  : "MArrivalTimeCalc";
+    fTitle = title ? title : "Calculate photons arrival time";
+    
+    SetSaturationLimit();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//  - MArrivalTimeCam
+//
+
+Int_t MArrivalTimeCalc::PreProcess(MParList *pList)
+{
+
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+
+    fArrTime = (MArrivalTimeCam*)pList->FindCreateObj(AddSerialNumber("MArrivalTimeCam"));
+    if (!fArrTime)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluation of the mean arrival times (spline interpolation)
+// per pixel and store them in the MArrivalTime container.
+//
+Int_t MArrivalTimeCalc::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  
+  while (pixel.Next())
+    {
+      
+      const UInt_t idx = pixel.GetPixelId();
+      Float_t time = 0.;
+
+
+      //
+      // If pixel is saturated we use LoGains
+      //
+      if ((pixel.GetMaxHiGainSample() >= fSaturationLimit) && pixel.HasLoGain())
+        {
+          
+          const Short_t nslices = fRawEvt->GetNumLoGainSamples();
+          time = Calc(pixel.GetLoGainSamples(),nslices,idx);
+        }
+      
+
+      //
+      // Use HiGains
+      //
+      else if (pixel.HasLoGain())
+        {
+          
+          const Short_t nslices = fRawEvt->GetNumHiGainSamples();
+          time = Calc(pixel.GetHiGainSamples(),nslices,idx);
+        }
+      
+      //
+      // If pixel is saturated and hasn't lo gains we do nothing, it's value remains -1
+      //
+      MArrivalTimePix &pix = (*fArrTime)[idx];
+      pix.SetArrivalTime(time,0.);
+    }
+    
+  fArrTime->SetReadyToSave();
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+// Possible Methods 
+// Case 1: MCubicSpline (3rd order spline)
+//
+Float_t MArrivalTimeCalc::Calc(const Byte_t *fadcSamples, const Short_t nslices, const UInt_t idx)
+{
+
+  //
+  // Initialize the spline
+  //
+  MCubicSpline *spline = new MCubicSpline(fadcSamples);  
+
+  //
+  // Now find the maximum  
+  //
+  Double_t abMaximum = spline->EvalAbMax();
+  Double_t maximum = spline->EvalMax();
+  const MPedestalPix &ped = (*fPedestals)[idx];
+  const Double_t pedestal = ped.GetPedestal();
+  const Double_t halfMax = (maximum + pedestal)/2.;
+  Float_t time = (halfMax > pedestal) ? (Float_t ) spline->FindVal(halfMax,abMaximum,'l'): 0.0;
+  delete spline;
+  return time;
+    
+}
+
Index: branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MArrivalTimeCalc
+#define MARS_MArrivalTimeCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+class MArrivalTimeCam;
+class MPedestalCam;
+class MArrivalTimeCalc : public MTask
+{
+
+  static const Byte_t fgSaturationLimit; // Default for fSaturationLimit
+  Byte_t              fSaturationLimit; // Maximum FADC counts before being considered as saturated
+  
+  MRawEvtData    *fRawEvt;     // raw event data (time slices)
+  MRawRunHeader  *fRunHeader;  // RunHeader information
+  MPedestalCam   *fPedestals;  // pedestal information
+  
+  MArrivalTimeCam *fArrTime;   // Container with the photons arrival times
+  
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess() {return kTRUE;}
+  
+  Float_t Calc(const Byte_t *fadcSamples, const Short_t nslices, const UInt_t idx);
+  
+public:
+    MArrivalTimeCalc(const char *name=NULL, const char *title=NULL);
+    ~MArrivalTimeCalc(){}
+ 
+    void SetSaturationLimit(const Byte_t lim=fgSaturationLimit) { fSaturationLimit = lim; }
+    
+    ClassDef(MArrivalTimeCalc, 0)   // Task to calculate Arrival Times from raw data
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc2.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc2.cc	(revision 17960)
@@ -0,0 +1,259 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Hendrik Bartko, 02/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MArrivalTimeCalc2
+//
+//  Calculates the arrival time as the mean time of the fWindowSize time slices
+//  which have the highest integral content.
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTimeCalc2.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+
+ClassImp(MArrivalTimeCalc2);
+
+using namespace std;
+
+const Byte_t MArrivalTimeCalc2::fgSaturationLimit = 254;
+const Byte_t MArrivalTimeCalc2::fgFirst  =  0;
+const Byte_t MArrivalTimeCalc2::fgLast   = 14;
+const Byte_t MArrivalTimeCalc2::fgWindowSize = 6;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MArrivalTimeCalc2::MArrivalTimeCalc2(const char *name, const char *title)
+  : fSaturationLimit(fgSaturationLimit)
+{
+
+    fName  = name  ? name  : "MArrivalTimeCalc2";
+    fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+    AddToBranchList("MRawEvtData.*");
+
+    SetRange();
+}
+
+void MArrivalTimeCalc2::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast, Byte_t windowsize)
+{
+    fNumHiGainSamples = hilast-hifirst+1;
+    fNumLoGainSamples = lolast-lofirst+1;
+
+    fHiGainFirst = hifirst;
+    fLoGainFirst = lofirst;
+
+    fWindowSize = windowsize & ~1;
+
+    if (fWindowSize != windowsize)
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size has to be even, set to: " << int(fWindowSize) << " samples " << endl;
+
+    if (fWindowSize<2) 
+    {
+      fWindowSize = 2;
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size set to two samples" << endl;
+    }
+
+    if (fWindowSize > fNumHiGainSamples)
+    {
+      fWindowSize = fNumLoGainSamples & ~1;
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size set to " << int(fWindowSize) << " samples " << endl;
+    }
+
+    if (fWindowSize > fNumLoGainSamples)
+    {
+      fWindowSize = fNumLoGainSamples & ~1;
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size set to " << int(fWindowSize) << " samples " << endl;
+    }
+
+    fWindowSizeSqrt = TMath::Sqrt((Float_t)fWindowSize);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MArrivalTimeCalc2::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    fArrivalTime = (MArrivalTimeCam*)pList->FindCreateObj(AddSerialNumber("MArrivalTimeCam"));
+    if (!fArrivalTime)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+void MArrivalTimeCalc2::FindSignalTime(Byte_t *ptr, Byte_t size, Float_t &time, Float_t &deltatime, Int_t &sat, Float_t pedes, Float_t pedrms) const
+{
+    const Byte_t *end = ptr + size;
+
+    Int_t sum=0;    // integral content of the actual window
+    Int_t max = 0;  // highest integral content of all windows
+
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    sat = 0;
+    Byte_t *p = ptr;
+
+    while (p<ptr+fWindowSize)
+    {
+        sum += *p;
+        if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+    //
+    // Check for saturation in all other slices
+    //
+    while (p<end)
+        if (*p++ >= fSaturationLimit)
+            sat++;
+
+    //
+    // Calculate the i-th sum as
+    //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+    // This is fast and accurate (because we are using int's)
+    //
+    max=sum;
+    Byte_t *ptrmax=ptr;  // pointer to the first slice of the maximum window
+
+    for (p=ptr; p+fWindowSize<end; p++)
+    {
+        sum += *(p+fWindowSize) - *p;
+		
+	if (sum>max)
+	{
+	  max = sum;
+	  ptrmax = p+1;
+	}
+    }
+
+    // now calculate the time for the maximum window
+    Int_t timesignalsum = 0;
+    Int_t timesquaredsum =0;
+    Int_t timesum =0;
+
+    for (p=ptrmax; p < ptrmax + fWindowSize; p++)
+    {
+        timesignalsum += *p*(p-ptr);
+        timesum += p-ptr;
+        timesquaredsum  += (p-ptr)*(p-ptr);
+    }
+
+    const Float_t pedsubsum = max - fWindowSize*pedes;
+    const Float_t pedsubtimesignalsum = timesignalsum - timesum*pedes;
+
+    time      = pedsubsum != 0 ? pedsubtimesignalsum / pedsubsum : 1;
+    deltatime = pedsubsum != 0 ? pedrms / pedsubsum * sqrt(timesquaredsum - fWindowSize*time) : 1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculates the arrival time as the mean time of the fWindowSize time slices
+//  which have the highest integral content.
+//
+Int_t MArrivalTimeCalc2::Process()
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    Int_t sat=0;
+    while (pixel.Next())
+    {
+        //
+        // Find signal in hi- and lo-gain
+        //
+        Float_t timehi, timelo, deltatimehi, deltatimelo;
+        Int_t sathi, satlo;
+
+	//
+        // Take correspodning pedestal
+        //
+        const Int_t pixid = pixel.GetPixelId();
+
+	const MPedestalPix  &ped = (*fPedestals)[pixid];
+
+	MArrivalTimePix &pix = (*fArrivalTime)[pixid];
+
+	const Float_t pedes  = ped.GetPedestal();
+	const Float_t pedrms = ped.GetPedestalRms();
+
+	FindSignalTime(pixel.GetHiGainSamples()+fHiGainFirst, fNumHiGainSamples, timehi, deltatimehi, sathi, pedes, pedrms);
+        FindSignalTime(pixel.GetLoGainSamples()+fLoGainFirst, fNumLoGainSamples, timelo, deltatimelo, satlo, pedes, pedrms);
+
+        if (satlo)
+            sat++;
+
+        pix.SetArrivalTime(timehi+ Float_t(fHiGainFirst), deltatimehi, timelo + Float_t(fLoGainFirst), deltatimelo); 
+	pix.SetGainSaturation(sathi, 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: branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc2.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimeCalc2.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/msignal/MArrivalTimeCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimeCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimeCam.cc	(revision 17960)
@@ -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): 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-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MArrivalTimeCam
+//
+// Hold the ArrivalTime information for all pixels in the camera
+//
+//
+// Class Version 2:
+// ----------------
+//  - Byte_t fFirstUsedSliceHiGain;
+//  - Byte_t fFirstUsedSliceLoGain;
+//  - Byte_t fLastUsedSliceHiGain;
+//  - Byte_t fLastUsedSliceLoGain;
+//
+/////////////////////////////////////////////////////////////////////////////
+#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->R__FOR_EACH(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->R__FOR_EACH(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->IsArrivalTimeValid())
+            continue;
+
+        *fLog << idx << ": ";
+	pix->Print();
+    }
+}
+
+Bool_t MArrivalTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx>=GetSize())
+        return kFALSE;
+
+    const MArrivalTimePix &pix = (*this)[idx];
+
+    switch (type)
+    {
+    case 0:
+        val = pix.GetArrivalTimeHiGain();
+        return pix.IsHiGainValid() && !pix.IsHiGainSaturated();
+
+    case 1:
+        val = pix.GetArrivalTimeHiGainError();
+        return val>0;
+
+    case 2:
+        val = pix.GetArrivalTimeLoGain();
+        return pix.IsLoGainValid() && !pix.IsLoGainSaturated();
+
+    case 3:
+        val = pix.GetArrivalTimeLoGainError();
+        return val>0;
+
+    case 4:
+    case 6:
+        val = pix.GetArrivalTime();
+        return pix.IsArrivalTimeValid();
+
+        // This is for the case the signal has been
+        // extracted from lo- and hi-gain
+    case 7:
+        // Lo- and hi-gain must be successfully extracted
+        if (!pix.IsLoGainValid() || !pix.IsHiGainValid())
+            return kFALSE;
+
+        // Lo- and hi-gain must not be saturated
+        if (pix.IsLoGainSaturated() || pix.IsHiGainSaturated())
+            return kFALSE;
+
+//        if (pix.GetArrivalTimeHiGain()<3 || pix.GetArrivalTimeHiGain()>12 ||
+//            pix.GetArrivalTimeLoGain()<3 || pix.GetArrivalTimeLoGain()>12)
+//            return kFALSE;
+
+        val = pix.GetArrivalTimeLoGain()-pix.GetArrivalTimeHiGain();
+        return TMath::Abs(val)<2; // FIXME: Is this a good value?
+
+    default:
+	return kFALSE;
+    }
+
+    return kFALSE;
+}
+
+void MArrivalTimeCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MArrivalTimeCam::DrawPixelContent - not available." << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MArrivalTimeCam.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimeCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimeCam.h	(revision 17960)
@@ -0,0 +1,68 @@
+#ifndef MARS_MArrivalTimeCam
+#define MARS_MArrivalTimeCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+class MArrivalTimePix;
+
+class MArrivalTimeCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray; //-> FIXME: Change TClonesArray away from a pointer?
+
+//    Byte_t fFirstUsedSliceHiGain;
+//    Byte_t fFirstUsedSliceLoGain;
+
+//    Byte_t fLastUsedSliceHiGain;
+//    Byte_t fLastUsedSliceLoGain;
+
+public:
+
+    MArrivalTimeCam(const char *name=NULL, const char *title=NULL);
+    ~MArrivalTimeCam();
+
+    void Print(Option_t *o="") const;
+    void Clear(Option_t *o="");
+    void SetLogStream(MLog *lg);
+    void Reset() { Clear(); }
+
+    void InitSize(const UInt_t i);
+    Int_t GetSize() const;
+
+//    Byte_t GetNumUsedFADCSlices() const       { return fLastUsedSliceHiGain-fFirstUsedSliceHiGain+1; }
+//    Byte_t GetNumUsedHiGainFADCSlices() const { return fLastUsedSliceHiGain-fFirstUsedSliceHiGain+1; }
+//    Byte_t GetNumUsedLoGainFADCSlices() const { return fLastUsedSliceLoGain-fFirstUsedSliceLoGain+1; }
+
+//    Byte_t GetFirstUsedSliceHiGain() const    { return fFirstUsedSliceHiGain; }
+//    Byte_t GetLastUsedSliceHiGain() const     { return fLastUsedSliceHiGain; }
+
+//    Byte_t GetFirstUsedSliceLoGain() const    { return fFirstUsedSliceLoGain; }
+//    Byte_t GetLastUsedSliceLoGain() const     { return fLastUsedSliceLoGain; }
+/*
+    void   SetUsedFADCSlices(Byte_t firsth, Byte_t lasth, 
+                             Byte_t firstl, Byte_t lastl)
+    {
+      fFirstUsedSliceHiGain    = firsth;
+      fLastUsedSliceHiGain     = lasth;
+      fFirstUsedSliceLoGain    = firstl;
+      fLastUsedSliceLoGain     = lastl;
+    }
+  */
+    MArrivalTimePix &operator[](Int_t i);
+    const MArrivalTimePix &operator[](Int_t i) const;
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MArrivalTimeCam, 2)	// Storage Container for the ArrivalTime in the camera
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/msignal/MArrivalTimePix.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimePix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimePix.cc	(revision 17960)
@@ -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): Markus Gaug  12/2003 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko 02/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MArrivalTimePix
+//
+// This is the storage container to hold informations about the ArrivalTime
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTimePix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MArrivalTimePix);
+
+using namespace std;
+
+static const Float_t gkSignalInitializer = 99999.9;
+
+// ------------------------------------------------------------------------
+//
+// MArrivalTimePix holds the ArrivalTime (HiGain and LoGain) 
+// of the FADC slices and its error. 
+//
+// Additionally, the number of saturated HiGain and LoGain Slices are stored. 
+// 
+// Default values for the ArrivalTime are: 99999.9 
+//
+MArrivalTimePix::MArrivalTimePix(const char* name, const char* title)
+{
+  fName  = name  ? name  : "MArrivalTimePix";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MArrivalTimePix::Clear(Option_t *o)
+{
+  fArrivalTimeHiGain      = gkSignalInitializer;
+  fArrivalTimeHiGainError = -1;
+  fArrivalTimeLoGain      = gkSignalInitializer;
+  fArrivalTimeLoGainError = -1;
+  
+  fNumHiGainSaturated = 0;
+  fNumLoGainSaturated = 0;
+}
+
+void MArrivalTimePix::SetArrivalTime(Float_t sig, Float_t sigerr)   
+{
+  fArrivalTimeHiGain      = sig; 
+  fArrivalTimeHiGainError = sigerr;
+}
+
+void MArrivalTimePix::SetArrivalTime(Float_t sighi, Float_t sighierr,
+                                     Float_t siglo, Float_t sigloerr)   
+{
+  fArrivalTimeHiGain = sighi;
+  fArrivalTimeHiGainError = sighierr;
+  fArrivalTimeLoGain = siglo;
+  fArrivalTimeLoGainError = sigloerr;
+}
+
+Float_t MArrivalTimePix::GetArrivalTime() const
+{
+    // If hi-gain is not saturated and has successfully been
+    // extracted use the hi-gain arrival time
+    if (!IsHiGainSaturated() && IsHiGainValid())
+        return GetArrivalTimeHiGain();
+
+    // If hi-gain could not be used ans the lo-gain could
+    // not be extracted return
+    if (!IsLoGainValid())
+        return 0;
+
+    // in all other cases use the lo-gain arrival time
+    return GetArrivalTimeLoGain();
+}
+
+Bool_t MArrivalTimePix::IsArrivalTimeValid() const
+{
+    // If hi-gain is not saturated and has successfully been
+    // extracted use the hi-gain arrival time
+    if (!IsHiGainSaturated() && IsHiGainValid())
+        return kTRUE;
+
+    // If hi-gain could not be used ans the lo-gain could
+    // not be extracted return kFALSE (no valid arrival time)
+    if (!IsLoGainValid())
+        return kFALSE;
+
+    // in all other cases use the lo-gain arrival time
+    return kTRUE;
+}
+
+void MArrivalTimePix::SetGainSaturation(Byte_t higain, Byte_t logain)
+{
+    fNumHiGainSaturated = higain;
+    fNumLoGainSaturated = logain;
+}
+
+void MArrivalTimePix::Print(Option_t *o) const
+{
+    *fLog << " Signal: " << fArrivalTimeHiGain
+        << " +- " << fArrivalTimeHiGainError
+        << " Nr. Sat. Hi Gain: " <<  fNumHiGainSaturated
+        << " Nr. Sat. Lo Gain: " <<  fNumLoGainSaturated
+        << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MArrivalTimePix.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MArrivalTimePix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MArrivalTimePix.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MArrivalTimePix
+#define MARS_MArrivalTimePix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MArrivalTimePix : public MParContainer
+{
+private:
+  Float_t fArrivalTimeHiGain;      // mean value of the ArrivalTime
+  Float_t fArrivalTimeHiGainError; // error of the mean value of the ArrivalTime
+  Float_t fArrivalTimeLoGain;      // mean value of the ArrivalTime
+  Float_t fArrivalTimeLoGainError; // error of the mean value of the ArrivalTime
+
+  Byte_t fNumHiGainSaturated;      // Number of first hi-gain slice which has saturated (could be negative if already the first slice saturates)
+  Byte_t fNumLoGainSaturated;      // Number of first lo-gain slices which have saturated
+
+public:
+    MArrivalTimePix(const char* name=NULL, const char* title=NULL);
+
+    void Clear(Option_t *o="");
+    void Print(Option_t *o="") const;
+    void Copy(TObject &obj) const
+    {
+        MArrivalTimePix &pix = static_cast<MArrivalTimePix&>(obj);
+
+        pix.fArrivalTimeHiGain      = fArrivalTimeHiGain;
+        pix.fArrivalTimeHiGainError = fArrivalTimeHiGainError;
+        pix.fArrivalTimeLoGain      = fArrivalTimeLoGain;
+        pix.fArrivalTimeLoGainError = fArrivalTimeLoGainError;
+
+        pix.fNumHiGainSaturated     = fNumHiGainSaturated;
+        pix.fNumLoGainSaturated     = fNumLoGainSaturated;
+    }
+
+    // Setter
+    void SetArrivalTime(Float_t sig, Float_t sigerr=0);
+    void SetArrivalTime(Float_t sighi, Float_t sighierr,Float_t siglo, Float_t sigloerr);
+    void SetGainSaturation(Byte_t higain, Byte_t logain=0);
+
+    // 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; }
+
+    Float_t GetArrivalTime()            const;
+    Bool_t  IsArrivalTimeValid()        const;
+
+    Byte_t GetNumHiGainSaturated()      const { return fNumHiGainSaturated; }
+    Byte_t GetNumLoGainSaturated()      const { return fNumLoGainSaturated; }
+
+    Bool_t IsHiGainSaturated()          const { return fNumHiGainSaturated>0; }
+    Bool_t IsLoGainSaturated()          const { return fNumLoGainSaturated>0; }
+
+    Bool_t IsLoGainValid()              const { return fArrivalTimeLoGainError>=0; }
+    Bool_t IsHiGainValid()              const { return fArrivalTimeHiGainError>=0; }
+
+    ClassDef(MArrivalTimePix, 1)	// Storage Container for ArrivalTime information of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MC_calibration_weights_UV46.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MC_calibration_weights_UV46.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MC_calibration_weights_UV46.dat	(revision 17960)
@@ -0,0 +1,124 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.118587 -0.759939               0
+-0.263645 -0.75009                0
+-0.310214 -0.780472               0
+-0.463437 -0.711066               0
+-0.512875 -0.632303               0
+-0.540826 -0.498066               0
+-0.619144 -0.330405               0
+-0.677085 -0.119447               0
+-0.716893 0.216855                0
+-0.659267 0.801966                0
+-0.364716 1.56853                 0
+-0.0164067 1.77302                0
+0.0977922 1.94953                 0
+0.53287 2.07799                   0
+0.703428 1.98081                  0
+0.780245 1.66725                  0
+1.02748 1.54473                   0
+1.27718 1.39987                   0
+1.58343 1.35047                   0
+1.83609 1.33001                   0
+2.04624 0.540095                  0
+2.07248 0.0345484                 0
+2.04722 -0.284436                 0
+1.90993 -0.748188                 0
+1.83718 -0.983809                 0
+1.78393 -1.0628                   0
+1.60923 -1.28475                  0
+1.38147 -1.42858                  0
+1.03132 -1.76524                  0
+0.697112 -2.15254                 0
+0.219843 -1.40928                 0
+0.0677385 -1.03865                0
+0.0163863 -0.920451               0
+-0.0953869 -0.530027              0
+-0.0884961 -0.345785              0
+-0.118639 -0.213164               0
+-0.141397 -0.0617509              0
+-0.158478 0.0285188               0
+-0.151498 0.140743                0
+-0.120191 0.23417                 0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+0 0                               0
+# Low Gain Weights: 6 10          
+# (Amplitude)  (Time)             
+0.0446612 -0.385273               0
+0.038191 -0.00418687              0
+0.0386966 0.0212324               0
+0.0402881 0.0744799               0
+0.0415794 0.229615                0
+0.0598731 0.44332                 0
+0.0758477 0.661518                0
+0.101509 1.10641                  0
+0.159323 1.64997                  0
+0.497256 2.83685                  0
+0.245087 3.27499                  0
+0.140546 2.46177                  0
+0.58086 2.2849                    0
+0.632721 2.45587                  0
+0.72819 2.52835                   0
+0.889583 2.48099                  0
+0.980812 2.50031                  0
+1.09885 2.55892                   0
+1.21374 2.78769                   0
+1.61928 3.08069                   0
+1.38544 1.95583                   0
+1.31998 1.1792                    0
+1.50633 0.591226                  0
+1.50916 0.0793899                 0
+1.5008 -0.33188                   0
+1.47339 -0.575386                 0
+1.45362 -0.915309                 0
+1.40214 -1.31593                  0
+1.34175 -1.77904                  0
+1.0661 -2.05471                   0
+1.31087 -1.49798                  0
+1.33793 -1.34758                  0
+1.10172 -1.21719                  0
+1.08133 -1.09356                  0
+1.04007 -0.981455                 0
+0.976745 -1.08299                 0
+0.930979 -1.14774                 0
+0.874203 -1.18348                 0
+0.816708 -1.20126                 0
+0.587354 -1.92869                 0
+0.783078 -1.89621                 0
+0.792771 -1.03439                 0
+0.622278 -0.781807                0
+0.61184 -0.745831                 0
+0.578792 -0.683741                0
+0.537336 -0.596328                0
+0.51443 -0.592858                 0
+0.482294 -0.560586                0
+0.462351 -0.827587                0
+0.317989 -1.05649                 0
+0.459672 -0.775035                0
+0.468287 -0.619961                0
+0.374182 -0.31635                 0
+0.376946 -0.225242                0
+0.367075 -0.347444                0
+0.340737 -0.393231                0
+0.321054 -0.187384                0
+0.320654 -0.225558                0
+0.302148 -0.399499                0
+0.232954 -0.607578                0
Index: branches/Mars_McMismatchStudy/msignal/MC_cosmics_weights46.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MC_cosmics_weights46.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MC_cosmics_weights46.dat	(revision 17960)
@@ -0,0 +1,104 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.483688 -0.498619     0
+-0.52105 -0.409251      0
+-0.551668 -0.347732     0
+-0.588621 -0.297486     0
+-0.661896 -0.2371       0
+-0.754507 -0.0572828    0
+-0.809786 0.380243      0
+-0.569956 1.15886       0
+-0.0188177 1.56188      0
+0.366116 1.43988        0
+0.560145 1.24361        0
+0.659133 1.09171        0
+0.743506 1.01359        0
+0.842199 0.994443       0
+1.03659 1.08537         0
+1.27803 1.17221         0
+1.52592 1.11221         0
+1.87086 0.786182        0
+1.9451 0.195753         0
+1.84721 -0.202808       0
+1.74892 -0.438476       0
+1.6951 -0.598997        0
+1.63854 -0.777709       0
+1.55247 -1.00352        0
+1.32498 -1.37711        0
+1.00846 -1.77543        0
+0.590272 -2.03408       0
+-0.111902 -1.86442      0
+-0.42886 -1.06692       0
+-0.383767 -0.46555      0
+-0.258546 -0.122314     0
+-0.237253 -0.0243087    0
+-0.234402 0.036867      0
+-0.236007 0.0905807     0
+-0.22029 0.156137       0
+-0.191449 0.235519      0
+-0.139186 0.309597      0
+-0.0270788 0.320152     0
+0.0388423 0.213534      0
+0.0424905 0.116622      0
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273     0
+0.038191 -0.00418687    0
+0.0386966 0.0212324     0
+0.0402881 0.0744799     0
+0.0415794 0.229615      0
+0.0598731 0.44332       0
+0.0758477 0.661518      0
+0.101509 1.10641        0
+0.159323 1.64997        0
+0.497256 2.83685        0
+0.245087 3.27499        0
+0.140546 2.46177        0
+0.58086 2.2849          0
+0.632721 2.45587        0
+0.72819 2.52835         0
+0.889583 2.48099        0
+0.980812 2.50031        0
+1.09885 2.55892         0
+1.21374 2.78769         0
+1.61928 3.08069         0
+1.38544 1.95583         0
+1.31998 1.1792          0
+1.50633 0.591226        0
+1.50916 0.0793899       0
+1.5008 -0.33188         0
+1.47339 -0.575386       0
+1.45362 -0.915309       0
+1.40214 -1.31593        0
+1.34175 -1.77904        0
+1.0661 -2.05471         0
+1.31087 -1.49798        0
+1.33793 -1.34758        0
+1.10172 -1.21719        0
+1.08133 -1.09356        0
+1.04007 -0.981455       0
+0.976745 -1.08299       0
+0.930979 -1.14774       0
+0.874203 -1.18348       0
+0.816708 -1.20126       0
+0.587354 -1.92869       0
+0.783078 -1.89621       0
+0.792771 -1.03439       0
+0.622278 -0.781807      0
+0.61184 -0.745831       0
+0.578792 -0.683741      0
+0.537336 -0.596328      0
+0.51443 -0.592858       0
+0.482294 -0.560586      0
+0.462351 -0.827587      0
+0.317989 -1.05649       0
+0.459672 -0.775035      0
+0.468287 -0.619961      0
+0.374182 -0.31635       0
+0.376946 -0.225242      0
+0.367075 -0.347444      0
+0.340737 -0.393231      0
+0.321054 -0.187384      0
+0.320654 -0.225558      0
+0.302148 -0.399499      0
+0.232954 -0.607578      0
Index: branches/Mars_McMismatchStudy/msignal/MC_weights.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MC_weights.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MC_weights.dat	(revision 17960)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.192984 -0.132188             0
+0.187675 -0.364451             0
+0.00639783 -0.707397           0
+-0.271769 -0.782098            0
+-0.433992 -0.65188             0
+-0.506172 -0.520614            0
+-0.545446 -0.427854            0
+-0.577498 -0.363785            0
+-0.616145 -0.311347            0
+-0.692899 -0.24808             0
+-0.876771 -0.000954896         0
+-0.928628 0.555715             0
+-0.599175 1.43251              0
+0.0173513 1.74512              0
+0.405197 1.54212               0
+0.587034 1.30229               0
+0.690943 1.14398               0
+0.779392 1.06243               0
+0.882825 1.0425                0
+1.08657 1.13784                0
+1.35004 1.22203                0
+1.61967 1.12679                0
+1.96215 0.718709               0
+2.009 0.117553                 0
+1.91269 -0.249042              0
+1.83371 -0.456316              0
+1.77704 -0.626166              0
+1.71784 -0.814262              0
+1.62782 -1.0514                0
+1.38952 -1.44307               0
+1.04176 -1.85012               0
+0.586193 -2.06507              0
+-0.116844 -1.75114             0
+-0.378321 -0.918193            0
+-0.329607 -0.381089            0
+-0.269525 -0.145645            0
+-0.245833 -0.035611            0
+-0.243367 0.0319466            0
+-0.246348 0.0900604            0
+-0.230933 0.158395             0
+-0.200143 0.237071             0
+-0.142623 0.29298              0
+-0.0413303 0.255565            0
+-0.00517261 0.132402           0
+-0.0159254 0.0535915           0
+-0.0269696 0.0219578           0
+-0.0310746 0.0102674           0
+-0.030882 0.00589682           0
+-0.028929 0.0044246            0
+-0.0274387 0.00685789          0
+0.0088518 0.0211059            0
+0.011564 0.0345383             0
+0.0276757 0.0606363            0
+0.051436 0.065177              0
+0.0652995 0.0526172            0
+0.0713662 0.0397629            0
+0.0744256 0.0299231            0
+0.0765017 0.0223275            0
+0.0782008 0.0160109            0
+0.0799735 0.0112381            0
+# Low Gain Weights: 6 10       
+# (Amplitude)  (Time)          
+0.0446612 -0.385273            0
+0.038191 -0.00418687           0
+0.0386966 0.0212324            0
+0.0402881 0.0744799            0
+0.0415794 0.229615             0
+0.0598731 0.44332              0
+0.0758477 0.661518             0
+0.101509 1.10641               0
+0.159323 1.64997               0
+0.497256 2.83685               0
+0.245087 3.27499               0
+0.140546 2.46177               0
+0.58086 2.2849                 0
+0.632721 2.45587               0
+0.72819 2.52835                0
+0.889583 2.48099               0
+0.980812 2.50031               0
+1.09885 2.55892                0
+1.21374 2.78769                0
+1.61928 3.08069                0
+1.38544 1.95583                0
+1.31998 1.1792                 0
+1.50633 0.591226               0
+1.50916 0.0793899              0
+1.5008 -0.33188                0
+1.47339 -0.575386              0
+1.45362 -0.915309              0
+1.40214 -1.31593               0
+1.34175 -1.77904               0
+1.0661 -2.05471                0
+1.31087 -1.49798               0
+1.33793 -1.34758               0
+1.10172 -1.21719               0
+1.08133 -1.09356               0
+1.04007 -0.981455              0
+0.976745 -1.08299              0
+0.930979 -1.14774              0
+0.874203 -1.18348              0
+0.816708 -1.20126              0
+0.587354 -1.92869              0
+0.783078 -1.89621              0
+0.792771 -1.03439              0
+0.622278 -0.781807             0
+0.61184 -0.745831              0
+0.578792 -0.683741             0
+0.537336 -0.596328             0
+0.51443 -0.592858              0
+0.482294 -0.560586             0
+0.462351 -0.827587             0
+0.317989 -1.05649              0
+0.459672 -0.775035             0
+0.468287 -0.619961             0
+0.374182 -0.31635              0
+0.376946 -0.225242             0
+0.367075 -0.347444             0
+0.340737 -0.393231             0
+0.321054 -0.187384             0
+0.320654 -0.225558             0
+0.302148 -0.399499             0
+0.232954 -0.607578             0
Index: branches/Mars_McMismatchStudy/msignal/MC_weights4.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MC_weights4.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MC_weights4.dat	(revision 17960)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.483688 -0.498619         0
+-0.52105 -0.409251          0
+-0.551668 -0.347732         0
+-0.588621 -0.297486         0
+-0.661896 -0.2371           0
+-0.754507 -0.0572828        0
+-0.809786 0.380243          0
+-0.569956 1.15886           0
+-0.0188177 1.56188          0
+0.366116 1.43988            0
+0.560145 1.24361            0
+0.659133 1.09171            0
+0.743506 1.01359            0
+0.842199 0.994443           0
+1.03659 1.08537             0
+1.27803 1.17221             0
+1.52592 1.11221             0
+1.87086 0.786182            0
+1.9451 0.195753             0
+1.84721 -0.202808           0
+1.74892 -0.438476           0
+1.6951 -0.598997            0
+1.63854 -0.777709           0
+1.55247 -1.00352            0
+1.32498 -1.37711            0
+1.00846 -1.77543            0
+0.590272 -2.03408           0
+-0.111902 -1.86442          0
+-0.42886 -1.06692           0
+-0.383767 -0.46555          0
+-0.258546 -0.122314         0
+-0.237253 -0.0243087        0
+-0.234402 0.036867          0
+-0.236007 0.0905807         0
+-0.22029 0.156137           0
+-0.191449 0.235519          0
+-0.139186 0.309597          0
+-0.0270788 0.320152         0
+0.0388423 0.213534          0
+0.0424905 0.116622          0
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+0.178287 2.98244            0
+0.0799794 2.25048           0
+0.501997 2.04566            0
+0.559993 2.18952            0
+0.636334 2.28558            0
+0.784832 2.29757            0
+0.894393 2.36602            0
+1.01571 2.62578             0
+1.14191 3.14701             0
+1.70405 4.27635             0
+1.25503 1.69442             0
+1.19843 1.00804             0
+1.36974 0.493838            0
+1.37759 0.0452029           0
+1.37174 -0.336051           0
+1.34423 -0.563321           0
+1.31669 -0.852661           0
+1.26602 -1.28826            0
+1.20062 -1.85625            0
+0.874127 -2.44773           0
+1.2433 -1.47361             0
+1.27171 -1.3052             0
+1.03025 -1.1211             0
+1.00417 -0.992811           0
+0.968251 -0.911359          0
+0.907626 -1.02038           0
+0.852293 -1.06813           0
+0.797164 -1.16276           0
+0.739386 -1.25445           0
+0.447754 -2.34757           0
+0.777349 -1.83155           0
+0.779564 -1.01577           0
+0.600426 -0.733238          0
+0.5863 -0.688006            0
+0.557156 -0.650488          0
+0.514926 -0.584649          0
+0.485323 -0.569089          0
+0.454047 -0.573249          0
+0.429026 -0.907077          0
+0.245526 -1.35434           0
Index: branches/Mars_McMismatchStudy/msignal/MC_weights46.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MC_weights46.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MC_weights46.dat	(revision 17960)
@@ -0,0 +1,104 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.483688 -0.498619           0
+-0.52105 -0.409251            0
+-0.551668 -0.347732           0
+-0.588621 -0.297486           0
+-0.661896 -0.2371             0
+-0.754507 -0.0572828          0
+-0.809786 0.380243            0
+-0.569956 1.15886             0
+-0.0188177 1.56188            0
+0.366116 1.43988              0
+0.560145 1.24361              0
+0.659133 1.09171              0
+0.743506 1.01359              0
+0.842199 0.994443             0
+1.03659 1.08537               0
+1.27803 1.17221               0
+1.52592 1.11221               0
+1.87086 0.786182              0
+1.9451 0.195753               0
+1.84721 -0.202808             0
+1.74892 -0.438476             0
+1.6951 -0.598997              0
+1.63854 -0.777709             0
+1.55247 -1.00352              0
+1.32498 -1.37711              0
+1.00846 -1.77543              0
+0.590272 -2.03408             0
+-0.111902 -1.86442            0
+-0.42886 -1.06692             0
+-0.383767 -0.46555            0
+-0.258546 -0.122314           0
+-0.237253 -0.0243087          0
+-0.234402 0.036867            0
+-0.236007 0.0905807           0
+-0.22029 0.156137             0
+-0.191449 0.235519            0
+-0.139186 0.309597            0
+-0.0270788 0.320152           0
+0.0388423 0.213534            0
+0.0424905 0.116622            0
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273           0
+0.038191 -0.00418687          0
+0.0386966 0.0212324           0
+0.0402881 0.0744799           0
+0.0415794 0.229615            0
+0.0598731 0.44332             0
+0.0758477 0.661518            0
+0.101509 1.10641              0
+0.159323 1.64997              0
+0.497256 2.83685              0
+0.245087 3.27499              0
+0.140546 2.46177              0
+0.58086 2.2849                0
+0.632721 2.45587              0
+0.72819 2.52835               0
+0.889583 2.48099              0
+0.980812 2.50031              0
+1.09885 2.55892               0
+1.21374 2.78769               0
+1.61928 3.08069               0
+1.38544 1.95583               0
+1.31998 1.1792                0
+1.50633 0.591226              0
+1.50916 0.0793899             0
+1.5008 -0.33188               0
+1.47339 -0.575386             0
+1.45362 -0.915309             0
+1.40214 -1.31593              0
+1.34175 -1.77904              0
+1.0661 -2.05471               0
+1.31087 -1.49798              0
+1.33793 -1.34758              0
+1.10172 -1.21719              0
+1.08133 -1.09356              0
+1.04007 -0.981455             0
+0.976745 -1.08299             0
+0.930979 -1.14774             0
+0.874203 -1.18348             0
+0.816708 -1.20126             0
+0.587354 -1.92869             0
+0.783078 -1.89621             0
+0.792771 -1.03439             0
+0.622278 -0.781807            0
+0.61184 -0.745831             0
+0.578792 -0.683741            0
+0.537336 -0.596328            0
+0.51443 -0.592858             0
+0.482294 -0.560586            0
+0.462351 -0.827587            0
+0.317989 -1.05649             0
+0.459672 -0.775035            0
+0.468287 -0.619961            0
+0.374182 -0.31635             0
+0.376946 -0.225242            0
+0.367075 -0.347444            0
+0.340737 -0.393231            0
+0.321054 -0.187384            0
+0.320654 -0.225558            0
+0.302148 -0.399499            0
+0.232954 -0.607578            0
Index: branches/Mars_McMismatchStudy/msignal/MC_weights_2GSamples.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MC_weights_2GSamples.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MC_weights_2GSamples.dat	(revision 17960)
@@ -0,0 +1,206 @@
+# High Gain Weights: 10 10
+# (Amplitude)  (Time) 
+-0.58121 -5.87941         0
+-0.6795 -5.93277          0
+-0.778453 -5.94334        0
+-0.877262 -5.90919        0
+-0.975084 -5.82862        0
+-1.07106 -5.70014         0
+-1.16428 -5.52262         0
+-1.25386 -5.29528         0
+-1.33889 -5.01745         0
+-1.41845 -4.68897         0
+-1.10123 -0.503345        0
+-1.1055 0.00732161        0
+-1.10071 0.538021         0
+-1.08651 1.08556          0
+-1.06265 1.6465           0
+-1.0289 2.21712           0
+-0.985169 2.79381         0
+-0.931382 3.3729          0
+-0.867577 3.95017         0
+-0.793869 4.52156         0
+-0.732148 6.94018         0
+-0.61223 7.48841          0
+-0.482946 8.00584         0
+-0.344906 8.48814         0
+-0.198799 8.93154         0
+-0.0453747 9.33193        0
+0.114514 9.68562          0
+0.27998 9.98929           0
+0.450051 10.2395          0
+0.623709 10.4337          0
+1.27929 9.89078           0
+1.44405 9.91358           0
+1.60887 9.87489           0
+1.7726 9.77404            0
+1.9341 9.61064            0
+2.09222 9.38519           0
+2.24585 9.09791           0
+2.39386 8.74972           0
+2.5352 8.34248            0
+2.6688 7.87747            0
+2.20159 7.6767            0
+2.32457 7.09547           0
+2.43719 6.46977           0
+2.53867 5.80405           0
+2.62833 5.10291           0
+2.70558 4.37122           0
+2.76995 3.6143            0
+2.82107 2.83714           0
+2.85865 2.04486           0
+2.88252 1.24321           0
+2.73623 -0.842288         0
+2.71582 -1.62074          0
+2.68205 -2.38851          0
+2.63517 -3.14004          0
+2.57555 -3.87047          0
+2.50362 -4.57514          0
+2.41992 -5.24919          0
+2.32509 -5.88822          0
+2.21982 -6.48816          0
+2.10491 -7.04516          0
+2.41839 -8.75222          0
+2.269 -9.20297            0
+2.1124 -9.59137           0
+1.94975 -9.91647          0
+1.78221 -10.1768          0
+1.61098 -10.372           0
+1.43725 -10.5021          0
+1.26219 -10.5673          0
+1.08697 -10.5684          0
+0.912718 -10.5064         0
+0.894181 -10.3883         0
+0.722625 -10.2278         0
+0.554397 -10.0119         0
+0.390485 -9.74353         0
+0.231815 -9.42622         0
+0.0792163 -9.0635         0
+-0.0665269 -8.65917       0
+-0.204746 -8.21739        0
+-0.334828 -7.74192        0
+-0.456247 -7.237          0
+-0.939311 -4.14822        0
+-1.00319 -3.52754         0
+-1.05625 -2.90491         0
+-1.0985 -2.28475          0
+-1.13004 -1.67152         0
+-1.15106 -1.06907         0
+-1.16181 -0.481082        0
+-1.16263 0.0887083        0
+-1.15391 0.636921         0
+-1.13612 1.16048          0
+-1.28655 4.74683          0
+-1.20495 5.05336          0
+-1.11851 5.30847          0
+-1.02818 5.5127           0
+-0.934869 5.66709         0
+-0.839486 5.77285         0
+-0.742903 5.83146         0
+-0.645946 5.84479         0
+-0.549406 5.81487         0
+-0.454032 5.74392         0
+# Low Gain Weights: 10 10 
+# (Amplitude)  (Time)     
+-0.58121 -5.87941         0
+-0.6795 -5.93277          0
+-0.778453 -5.94334        0
+-0.877262 -5.90919        0
+-0.975084 -5.82862        0
+-1.07106 -5.70014         0
+-1.16428 -5.52262         0
+-1.25386 -5.29528         0
+-1.33889 -5.01745         0
+-1.41845 -4.68897         0
+-1.10123 -0.503345        0
+-1.1055 0.00732161        0
+-1.10071 0.538021         0
+-1.08651 1.08556          0
+-1.06265 1.6465           0
+-1.0289 2.21712           0
+-0.985169 2.79381         0
+-0.931382 3.3729          0
+-0.867577 3.95017         0
+-0.793869 4.52156         0
+-0.732148 6.94018         0
+-0.61223 7.48841          0
+-0.482946 8.00584         0
+-0.344906 8.48814         0
+-0.198799 8.93154         0
+-0.0453747 9.33193        0
+0.114514 9.68562          0
+0.27998 9.98929           0
+0.450051 10.2395          0
+0.623709 10.4337          0
+1.27929 9.89078           0
+1.44405 9.91358           0
+1.60887 9.87489           0
+1.7726 9.77404            0
+1.9341 9.61064            0
+2.09222 9.38519           0
+2.24585 9.09791           0
+2.39386 8.74972           0
+2.5352 8.34248            0
+2.6688 7.87747            0
+2.20159 7.6767            0
+2.32457 7.09547           0
+2.43719 6.46977           0
+2.53867 5.80405           0
+2.62833 5.10291           0
+2.70558 4.37122           0
+2.76995 3.6143            0
+2.82107 2.83714           0
+2.85865 2.04486           0
+2.88252 1.24321           0
+2.73623 -0.842288         0
+2.71582 -1.62074          0
+2.68205 -2.38851          0
+2.63517 -3.14004          0
+2.57555 -3.87047          0
+2.50362 -4.57514          0
+2.41992 -5.24919          0
+2.32509 -5.88822          0
+2.21982 -6.48816          0
+2.10491 -7.04516          0
+2.41839 -8.75222          0
+2.269 -9.20297            0
+2.1124 -9.59137           0
+1.94975 -9.91647          0
+1.78221 -10.1768          0
+1.61098 -10.372           0
+1.43725 -10.5021          0
+1.26219 -10.5673          0
+1.08697 -10.5684          0
+0.912718 -10.5064         0
+0.894181 -10.3883         0
+0.722625 -10.2278         0
+0.554397 -10.0119         0
+0.390485 -9.74353         0
+0.231815 -9.42622         0
+0.0792163 -9.0635         0
+-0.0665269 -8.65917       0
+-0.204746 -8.21739        0
+-0.334828 -7.74192        0
+-0.456247 -7.237          0
+-0.939311 -4.14822        0
+-1.00319 -3.52754         0
+-1.05625 -2.90491         0
+-1.0985 -2.28475          0
+-1.13004 -1.67152         0
+-1.15106 -1.06907         0
+-1.16181 -0.481082        0
+-1.16263 0.0887083        0
+-1.15391 0.636921         0
+-1.13612 1.16048          0
+-1.28655 4.74683          0
+-1.20495 5.05336          0
+-1.11851 5.30847          0
+-1.02818 5.5127           0
+-0.934869 5.66709         0
+-0.839486 5.77285         0
+-0.742903 5.83146         0
+-0.645946 5.84479         0
+-0.549406 5.81487         0
+-0.454032 5.74392         0
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractAmplitudeSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractAmplitudeSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractAmplitudeSpline.cc	(revision 17960)
@@ -0,0 +1,644 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug       05/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeSpline
+//
+//   Fast Spline extractor using a cubic spline algorithm of Numerical Recipes. 
+//   It returns the integral below the interpolating spline. 
+// 
+//   Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//         to modify the ranges. Ranges have to be an even number. In case of odd 
+//         ranges, the last slice will be reduced by one.
+//
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  3 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractAmplitudeSpline.h"
+
+#include "MExtractedSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractAmplitudeSpline);
+
+using namespace std;
+
+const Byte_t  MExtractAmplitudeSpline::fgHiGainFirst  = 2;
+const Byte_t  MExtractAmplitudeSpline::fgHiGainLast   = 14;
+const Byte_t  MExtractAmplitudeSpline::fgLoGainFirst  = 3;
+const Byte_t  MExtractAmplitudeSpline::fgLoGainLast   = 14;
+const Float_t MExtractAmplitudeSpline::fgResolution   = 0.003;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+MExtractAmplitudeSpline::MExtractAmplitudeSpline(const char *name, const char *title) 
+    : fHiGainSignal(NULL), fLoGainSignal(NULL),
+      fHiGainFirstDeriv(NULL), fLoGainFirstDeriv(NULL),
+      fHiGainSecondDeriv(NULL), fLoGainSecondDeriv(NULL)
+{
+
+  fName  = name  ? name  : "MExtractAmplitudeSpline";
+  fTitle = title ? title : "Signal Extractor for a fixed FADC window using a fast spline";
+
+  SetResolution();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+MExtractAmplitudeSpline::~MExtractAmplitudeSpline()
+{
+  
+  if (fHiGainSignal)
+    delete [] fHiGainSignal;
+  if (fLoGainSignal)
+    delete [] fLoGainSignal;
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the window defined by (fHiGainLast-fHiGainFirst-1) are odd, subtract one
+// - if the window defined by (fLoGainLast-fLoGainFirst-1) are odd, subtract one
+// - if the Hi Gain window is smaller than 2, set fHiGainLast to fHiGainFirst+1
+// - if the Lo Gain window is smaller than 2, set fLoGainLast to fLoGainFirst+1
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: (Float_t)(fLoGainLast-fLoGainFirst+1)
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractAmplitudeSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = 2.;
+  fNumLoGainSamples = lolast == 0 ? 0. : 2.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+  fHiLoLast  = 0;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit
+//
+// Calls:
+// - MExtractor::ReInit(pList);
+// - fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+// 
+// Deletes all arrays, if not NULL
+// Creates new arrays according to the extraction range
+//
+Bool_t MExtractAmplitudeSpline::ReInit(MParList *pList)
+{
+
+  if (!MExtractor::ReInit(pList))
+    return kFALSE;
+
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+  if (fHiGainSignal)
+    delete [] fHiGainSignal;
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSignal)
+    delete [] fLoGainSignal;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1 + fHiLoLast;
+
+  fHiGainSignal      = new Float_t[range];
+  memset(fHiGainSignal,0,range*sizeof(Float_t));
+  fHiGainFirstDeriv  = new Float_t[range];
+  memset(fHiGainFirstDeriv,0,range*sizeof(Float_t));
+  fHiGainSecondDeriv = new Float_t[range];
+  memset(fHiGainSecondDeriv,0,range*sizeof(Float_t));
+
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() << ": Using for High-Gain Extraction " << range
+        << " FADC samples from " 
+        << Form("%s%2i%s"," High Gain slice ",(Int_t)fHiGainFirst," to (including) ")
+        << Form("%s%2i",fHiLoLast ? "Low Gain slice " : " High Gain slice ",
+                fHiLoLast ?  (Int_t)fHiLoLast : (Int_t)fHiGainLast ) 
+        << endl;
+
+  range = fLoGainLast ? fLoGainLast - fLoGainFirst + 1 : 0;
+
+  fLoGainSignal = new Float_t[range];
+  memset(fLoGainSignal,0,range*sizeof(Float_t));
+  fLoGainFirstDeriv  = new Float_t[range];
+  memset(fLoGainFirstDeriv,0,range*sizeof(Float_t));
+  fLoGainSecondDeriv = new Float_t[range];
+  memset(fLoGainSecondDeriv,0,range*sizeof(Float_t));
+  
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() << ": Using for Low-Gain Extraction " << range
+        << " FADC samples from " 
+        << Form("%s%2i%s%2i"," Low Gain slice ",(Int_t)fLoGainFirst,
+                " to (including) ",(Int_t)fLoGainLast) << endl;
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+// - If fHiLoLast is not 0, loop also from logain to (logain+fHiLoLast)
+// - Sum up contents of logain
+// - If *logain is greater than fSaturationLimit, raise sat by 1
+//
+void MExtractAmplitudeSpline::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+  
+  Int_t count   = 0;
+  Float_t abmaxpos = 0.;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  Byte_t *end = ptr + range;
+  Byte_t *p     = ptr;
+  //
+  // Check for saturation in all other slices
+  //
+  while (++p<end)
+    {
+      
+      fHiGainSignal[count] = (Float_t)*p;
+      
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  count;
+        }
+      
+      count++;
+      
+      if (*p >= fSaturationLimit)
+        {
+          sat++;
+              break;
+        }
+    }
+  
+  if (fHiLoLast != 0)
+    {
+      
+      p    = logain;
+      end  = logain + fHiLoLast + 1;
+      
+      while (p<end)
+        {
+          
+          fHiGainSignal[count] = (Float_t)*p;
+
+          if (*p > max)
+            {
+              max    = *p;
+              maxpos =  count;
+            }
+          
+          range++;
+          count++;
+
+          if (*p++ >= fSaturationLimit)
+            {
+              sat++;
+              break;
+            }
+        }
+    }
+
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+    return;
+
+  //
+  // Don't start if the maxpos is too close to the left limit.
+  //
+  if (maxpos < 2)
+    return;
+
+  Float_t pp;
+  fHiGainSecondDeriv[0] = 0.;
+  fHiGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fHiGainSecondDeriv[i-1] + 4.;
+      fHiGainSecondDeriv[i] = -1.0/pp;
+      fHiGainFirstDeriv [i] = fHiGainSignal[i+1] - fHiGainSignal[i] - fHiGainSignal[i] + fHiGainSignal[i-1];
+      fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+      p++;
+    }
+
+  fHiGainSecondDeriv[range-1] = 0.;
+  for (Int_t k=range-2;k>=0;k--)
+    fHiGainSecondDeriv[k] = (fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k])/6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = fHiGainSignal[klo];
+  Float_t khicont = fHiGainSignal[khi];
+  sum       = khicont;
+  abmaxpos  = lower;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+      if (y > sum)
+        {
+          sum      = y;
+          abmaxpos = x;
+        }
+    }
+
+  if (abmaxpos > upper-0.1)
+    {
+      
+      upper = (Float_t)maxpos+1;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+            + (b*b*b-b)*fHiGainSecondDeriv[khi];
+          
+          if (y > sum)
+            {
+              sum    = y;
+              abmaxpos = x;
+            }
+        }
+    }
+
+ const Float_t up = abmaxpos+step-0.055;
+ const Float_t lo = abmaxpos-step+0.055;
+ const Float_t maxpossave = abmaxpos;
+ 
+ x     = abmaxpos;
+ a     = upper - x;
+ b     = x - lower;
+
+  step  = 0.04; // step size of 83 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+
+ if (abmaxpos < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+      upper--;
+      lower--;
+    }
+ 
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        sum      = y;
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractAmplitudeSpline::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+  
+  Int_t count   = 0;
+  Float_t abmaxpos = 0.;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+  
+  Int_t range = fLoGainLast - fLoGainFirst + 1;
+  Byte_t *end = ptr + range;
+  Byte_t *p   = ptr;
+  //
+  // Check for saturation in all other slices
+  //
+  while (++p<end)
+    {
+      
+      fLoGainSignal[count] = (Float_t)*p;
+      
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  count;
+        }
+      
+      range++;
+      count++;
+      
+      if (*p >= fSaturationLimit)
+        {
+          sat++;
+              break;
+        }
+    }
+  
+
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+    return;
+
+  //
+  // Don't start if the maxpos is too close to the left limit.
+  //
+  if (maxpos < 2)
+    return;
+
+  Float_t pp;
+  fLoGainSecondDeriv[0] = 0.;
+  fLoGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fLoGainSecondDeriv[i-1] + 4.;
+      fLoGainSecondDeriv[i] = -1.0/pp;
+      fLoGainFirstDeriv [i] = fLoGainSignal[i+1] - fLoGainSignal[i] - fLoGainSignal[i] + fLoGainSignal[i-1];
+      fLoGainFirstDeriv [i] = (6.0*fLoGainFirstDeriv[i]-fLoGainFirstDeriv[i-1])/pp;
+      p++;
+    }
+
+  fLoGainSecondDeriv[range-1] = 0.;
+  for (Int_t k=range-2;k>=0;k--)
+    fLoGainSecondDeriv[k] = (fLoGainSecondDeriv[k]*fLoGainSecondDeriv[k+1] + fLoGainFirstDeriv[k])/6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = fLoGainSignal[klo];
+  Float_t khicont = fLoGainSignal[khi];
+  sum       = khicont;
+  abmaxpos  = lower;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+      if (y > sum)
+        {
+          sum      = y;
+          abmaxpos = x;
+        }
+    }
+
+  if (abmaxpos > upper-0.1)
+    {
+      
+      upper = (Float_t)maxpos+1;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = fLoGainSignal[klo];
+      khicont = fLoGainSignal[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+            + (b*b*b-b)*fLoGainSecondDeriv[khi];
+          
+          if (y > sum)
+            {
+              sum    = y;
+              abmaxpos = x;
+            }
+        }
+    }
+
+ const Float_t up = abmaxpos+step-0.055;
+ const Float_t lo = abmaxpos-step+0.055;
+ const Float_t maxpossave = abmaxpos;
+ 
+ x     = abmaxpos;
+ a     = upper - x;
+ b     = x - lower;
+
+  step  = 0.04; // step size of 83 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+
+ if (abmaxpos < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = fLoGainSignal[klo];
+      khicont = fLoGainSignal[khi];
+      upper--;
+      lower--;
+    }
+ 
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > sum)
+        sum      = y;
+    }
+}
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractAmplitudeSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractAmplitudeSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractAmplitudeSpline.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MExtractAmplitudeSpline
+#define MARS_MExtractAmplitudeSpline
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractAmplitudeSpline : public MExtractor
+{
+
+private:
+  
+  static const Byte_t  fgHiGainFirst;    // Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t  fgHiGainLast;     // Default for fHiGainLast   (now set to: 14)
+  static const Byte_t  fgLoGainFirst;    // Default for fLOGainFirst  (now set to: 3)
+  static const Byte_t  fgLoGainLast;     // Default for fLoGainLast   (now set to: 14)
+  static const Float_t fgResolution;     // Default for fResolution   (now set to: 0.003)
+
+  Float_t *fHiGainSignal;                     // Need fast access to the signals in a float way
+  Float_t *fLoGainSignal;                     // Need fast access to the signals in a float way  
+  Float_t *fHiGainFirstDeriv;
+  Float_t *fLoGainFirstDeriv;  
+  Float_t *fHiGainSecondDeriv;
+  Float_t *fLoGainSecondDeriv;  
+
+  Float_t fResolution;                        // The time resolution in FADC units
+  
+  Bool_t ReInit    (MParList *pList);
+  
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;
+
+public:
+
+  MExtractAmplitudeSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractAmplitudeSpline();
+  
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+  void SetResolution(Float_t f=fgResolution)     { fResolution = f;  }
+  
+  ClassDef(MExtractAmplitudeSpline, 0)   // Task to Extract the Amplitude using a Fast Spline
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractBlindPixel.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractBlindPixel.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractBlindPixel.cc	(revision 17960)
@@ -0,0 +1,739 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractBlindPixel
+//
+//  Extracts the signal from a fixed window in a given range.
+//
+//    Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//    to modify the ranges. The "low-gain" ranges are used for the NSB rejection 
+//    whereas the high-gain ranges for blind pixel signal extraction. "High-gain" 
+//    ranges can extend to the slices stored as "low-gain" in MRawEvtPixelIter
+//
+//    Defaults are: 
+// 
+//     fHiGainFirst =  fgHiGainFirst =  10 
+//     fHiGainLast  =  fgHiGainLast  =  29
+//     fLoGainFirst =  fgLoGainFirst =  0 
+//     fLoGainLast  =  fgLoGainLast  =  7
+//
+//  The switches: 
+//  - SetExtractionType ( kAmplitude ) and  SetExtractionType ( kIntegral ) 
+//    can be used to choose between amplitude extraction (using a spline) and
+//    summed integral. 
+//  - SetExtractionType ( kFilter    ) 
+//    can be used to apply a filter discarding events passing over a threshold 
+//    defined in fNSBFilterLimit
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractBlindPixel.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalSubtractedEvt.h"
+#include "MExtractedSignalBlindPixel.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationBlindPix.h"
+
+#include "MExtralgoSpline.h"
+
+ClassImp(MExtractBlindPixel);
+
+using namespace std;
+
+const UInt_t  MExtractBlindPixel::fgBlindPixelIdx    = 559;
+const Byte_t  MExtractBlindPixel::fgHiGainFirst      =  10;
+const Byte_t  MExtractBlindPixel::fgHiGainLast       =  19;
+const Byte_t  MExtractBlindPixel::fgLoGainFirst      =   0;
+const Byte_t  MExtractBlindPixel::fgLoGainLast       =   7;
+const Int_t   MExtractBlindPixel::fgNSBFilterLimit   =  70;
+const Float_t MExtractBlindPixel::fgResolution       = 0.003;
+const Float_t MExtractBlindPixel::gkOverflow         = 300.;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes:
+// - fBlindPixelIdx to fgBlindPixelIdx
+// - fNSBFilterLimit to fgNSBFilterLimit
+// - fResolution to fgResolution
+// - fExtractionType to 0.
+//
+// Calls:
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+//
+MExtractBlindPixel::MExtractBlindPixel(const char *name, const char *title)
+    : fBlindPixel(0), /*fHiLoLast(0),*/ fDataType(0)
+{
+  
+  fName  = name  ? name  : "MExtractBlindPixel";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  SetResolution();
+  SetNSBFilterLimit();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+  
+//  SetNumBlindPixels();
+  fBlindPixelIdx.Set(1);
+  fBlindPixelIdx[0] = fgBlindPixelIdx;
+
+  Clear();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Clear
+//
+// Initializes:
+// - fBlindPixelIdx to 0
+// - fExtractionType to 0
+// 
+// Calls:
+// - SetBlindPixelIdx()
+// 
+// Deletes and sets to NULL (if exists):
+// - fHiGainSignal
+// - fHiGainFirstDeriv
+// - fHiGainSecondDeriv
+//
+void MExtractBlindPixel::Clear( const Option_t *o)
+{
+    fExtractionType = 0;
+
+    fBlindPixelIdx.Set(1);
+    fBlindPixelIdx[0] = fgBlindPixelIdx;
+}
+
+void MExtractBlindPixel::SetBlindPixels(const MCalibrationBlindCam &cam)
+{
+    const Int_t n = cam.GetSize();
+
+    fBlindPixelIdx.Set(n);
+    for (Int_t i=0; i<n; i++)
+        fBlindPixelIdx[i] = cam[i].GetPixId();
+}
+
+void MExtractBlindPixel::SetRange(UShort_t hifirst, UShort_t hilast, Int_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst+1);
+//  if (lolast)
+//    fNumLoGainSamples = (Float_t)(fLoGainLast-fLoGainFirst+1);
+//  else
+    fNumLoGainSamples = 0.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);  
+  
+  //fHiLoFirst = 0;
+  //fHiLoLast  = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls: 
+// - MExtractor::PreProcess(pList)
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedBlindPixel
+//
+Int_t MExtractBlindPixel::PreProcess(MParList *pList)
+{
+
+  if (!MExtractor::PreProcess(pList))
+    return kFALSE;
+
+  fBlindPixel = (MExtractedSignalBlindPixel*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalBlindPixel"));
+  if (!fBlindPixel)
+    return kFALSE;
+
+  const TString raw = IsDataType(kRawEvt2) ? "MRawEvtData2" : "MRawEvtData";
+  const TString sig = IsDataType(kRawEvt2) ? "MPedestalSubtractedEvt2" : "MPedestalSubtractedEvt";
+
+  fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber(raw), "MRawEvtData");
+  if (!fRawEvt)
+    {
+      *fLog << err << raw << " [MRawEvtData] not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  fSignal = (MPedestalSubtractedEvt*)pList->FindObject(AddSerialNumber(sig), "MPedestalSubtractedEvt");
+  if (!fSignal)
+    {
+      *fLog << err << sig << " [MPedestalSubtractedEvt] not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------- //
+//
+// The ReInit searches for:
+// -  MRawRunHeader::GetNumSamplesHiGain()
+// -  MRawRunHeader::GetNumSamplesLoGain()
+//
+// In case that the variables fHiGainLast and fLoGainLast are smaller than 
+// the even part of the number of samples obtained from the run header, a
+// warning is given an the range is set back accordingly. A call to:  
+// - SetRange(fHiGainFirst, fHiGainLast-diff, fLoGainFirst, fLoGainLast) or 
+// - SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast-diff) 
+// is performed in that case. The variable diff means here the difference 
+// between the requested range (fHiGainLast) and the available one. Note that 
+// the functions SetRange() are mostly overloaded and perform more checks, 
+// modifying the ranges again, if necessary.
+//
+Bool_t MExtractBlindPixel::ReInit(MParList *pList)
+{
+  
+  for (UInt_t i=0;i<fBlindPixelIdx.GetSize();i++)
+      fBlindPixel->SetBlindPixelIdx(fBlindPixelIdx[i], i);
+
+  fBlindPixel->SetExtractionType(fExtractionType);
+/*
+  for (UInt_t i=0;i<fBlindPixelIdx.GetSize();i++)
+  {
+
+      MPedestalPix &pedpix  = (*fPedestals)[fBlindPixelIdx.At(i)];    
+      
+      if (&pedpix)
+      {
+	  fBlindPixel->SetPed      ( pedpix.GetPedestal()   * fNumLoGainSamples, i );
+	  fBlindPixel->SetPedErr   ( pedpix.GetPedestalRms()* fNumLoGainSamples 
+                                 / TMath::Sqrt((Float_t)fPedestals->GetNumSlices()*pedpix.GetNumEvents()), i );
+	  fBlindPixel->SetPedRms   ( pedpix.GetPedestalRms()* TMath::Sqrt((Float_t)fNumLoGainSamples), i );
+	  fBlindPixel->SetPedRmsErr( fBlindPixel->GetPedErr()/2., i );
+      }
+  }
+
+  const Int_t higainsamples = fRunHeader->GetNumSamplesHiGain();
+  const Int_t logainsamples = fRunHeader->GetNumSamplesLoGain();
+  Int_t lastavailable       =  higainsamples-1;
+
+  if (logainsamples)
+    {
+      //
+      // If the signal is searched entirely in the low-gain range, have 
+      // to skip the higain completely. This is steered by the variable fHiLoFirst
+      // 
+      const Int_t firstdesired   = (Int_t)fHiGainFirst;
+  
+      if (firstdesired > lastavailable)
+        {
+          const Int_t diff = firstdesired - lastavailable;
+          *fLog << endl;
+          *fLog << warn << "First Hi Gain slice " << (int)fHiGainFirst << " out of range [0,";
+          *fLog << lastavailable << "]... start at slice " << diff << " of the Lo Gain " << endl;
+          
+          fHiLoFirst   = diff;
+        }
+    }
+  
+  const Int_t lastdesired = (Int_t)fHiGainLast;
+
+  if (lastdesired > lastavailable)
+    {
+      Int_t diff     = lastdesired - lastavailable;
+      lastavailable += logainsamples ? logainsamples-1 : 0;
+      
+      if (lastdesired > lastavailable)
+        {
+          *fLog << endl;
+          *fLog << "Last Hi Gain slice " << (int)fHiGainLast << " out of range [0,";
+          *fLog << lastavailable << "]... reduce upper limit by " << diff << endl;
+          diff = logainsamples;
+        }
+
+      fHiGainLast = higainsamples - 1;
+      fHiLoLast   = logainsamples ? diff : 0;
+    }
+ */
+  const Int_t range = fHiGainLast-fHiGainFirst+1; //fHiLoFirst ? fHiLoLast - fHiLoFirst + 1 : fHiGainLast - fHiGainFirst + fHiLoLast + 1;
+
+//  fHiGainSignal.Set(range);
+//  fHiGainSignal.Reset();
+
+  fHiGainFirstDeriv.Set(range);
+  fHiGainFirstDeriv.Reset();
+
+  fHiGainSecondDeriv.Set(range);
+  fHiGainSecondDeriv.Reset();
+
+  *fLog << endl;
+  *fLog << inf << "Extracting "
+      << (IsExtractionType(kAmplitude) ? "Amplitude" : " Integral")
+      << " using " << range << " FADC samples from slice "
+      << (Int_t)fHiGainFirst << " to " << (Int_t)fHiGainLast << " (incl)" << endl;
+
+  if (IsExtractionType(kFilter))
+    *fLog << inf << "Will use Filter using "
+	  << (Int_t)(fLoGainLast-fLoGainFirst+1) << " FADC slices"
+	  << " from slice " << (Int_t)fLoGainFirst
+	  << " to " << (Int_t)fLoGainLast << endl;
+
+  fBlindPixel->SetUsedFADCSlices(fHiGainFirst, range);
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - If fHiLoLast is set, loop from logain to (logain+fHiLoLast)
+// - Add contents of *logain to sum
+//
+/*
+void MExtractBlindPixel::FindIntegral(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat)
+{
+    const Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+    Int_t summ = 0;
+    while (p<end)
+    {
+        summ += *ptr;
+
+        if (*ptr++ >= fSaturationLimit)
+            sat++;
+    }
+
+    sum = (Float_t)summ;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// FindSignalPhe:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - If fHiLoLast is set, loop from logain to (logain+fHiLoLast)
+// - Add contents of *logain to sum
+// 
+//void MExtractBlindPixel::FindAmplitude(Float_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat)
+Float_t MExtractBlindPixel::FindAmplitude(Int_t idx, Int_t numsat) const
+{
+    Int_t sat0 = fHiGainFirst; // First slice to extract and first saturating slice
+    Int_t sat1 = fHiGainLast;  // Last  slice to extract and last saturating slice
+
+    Int_t maxpos = fSignal->GetMaxPos(idx, sat0, sat1);
+
+//    numsat = fSignal->GetSaturation(idx, fSaturationLimit, sat0, sat1);
+
+    const Float_t *ptr = fSignal->GetSamples(idx);
+    const Int_t    num = fHiGainLast-fHiGainFirst+1;
+
+    MExtralgoSpline s(ptr, num, fHiGainFirstDeriv.GetArray(), fHiGainSecondDeriv.GetArray());
+
+    s.SetExtractionType(MExtralgoSpline::kAmplitude);
+
+    s.Extract(numsat, maxpos);
+
+    return s.GetSignal();
+/*
+  Int_t range   = 0;
+  Int_t count   = 0;
+  Float_t abmaxpos = 0.;
+  Byte_t *p     = ptr;
+  Byte_t *end;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+  Int_t summ   = 0;
+
+  if (fHiLoFirst == 0)
+    {
+
+      range = fHiGainLast - fHiGainFirst + 1;
+
+      end   = ptr + range;
+      //
+      // Check for saturation in all other slices
+      //
+      while (p++<end)
+        {
+          
+          fHiGainSignal[count] = (Float_t)*p;
+          summ += *p;
+
+          if (*p > max)
+            {
+              max    = *p;
+              maxpos =  count;
+            }
+          
+          count++;
+
+          if (*p >= fSaturationLimit)
+              sat++;
+        }
+    }
+  
+  if (fHiLoLast != 0)
+    {
+      
+      p    = logain + fHiLoFirst;
+      end  = logain + fHiLoLast;
+      
+      while (p<end)
+        {
+          
+          fHiGainSignal[count] = (Float_t)*p;
+          summ += *p;
+
+          if (*p > max)
+            {
+              max    = *p;
+              maxpos =  count;
+            }
+          
+          range++;
+          count++;
+
+          if (*p++ >= fSaturationLimit)
+              sat++;
+        }
+    }
+
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+  {
+    sum = gkOverflow;
+    return;
+  }
+
+  //
+  // Don't start if the maxpos is too close to the left limit.
+  //
+  if (maxpos < 2)
+  {
+    sum = (Float_t)max;
+    return;
+  }
+
+  Float_t pp;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fHiGainSecondDeriv[i-1] + 4.;
+      fHiGainSecondDeriv[i] = -1.0/pp;
+      fHiGainFirstDeriv [i] = fHiGainSignal[i+1] - fHiGainSignal[i] - fHiGainSignal[i] + fHiGainSignal[i-1];
+      fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+      p++;
+    }
+
+  fHiGainSecondDeriv[range-1] = 0.;
+  for (Int_t k=range-2;k>=0;k--)
+    fHiGainSecondDeriv[k] = (fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k])/6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = fHiGainSignal[klo];
+  Float_t khicont = fHiGainSignal[khi];
+  sum       = (Float_t)khicont;
+  abmaxpos  = lower;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+      if (y > sum)
+        {
+          sum      = y;
+          abmaxpos = x;
+        }
+    }
+
+  if (abmaxpos > upper-0.1)
+    {
+      
+      upper = (Float_t)maxpos+1;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+            + (b*b*b-b)*fHiGainSecondDeriv[khi];
+          
+          if (y > sum)
+            {
+              sum    = y;
+              abmaxpos = x;
+            }
+        }
+    }
+
+ const Float_t up = abmaxpos+step-0.055;
+ const Float_t lo = abmaxpos-step+0.055;
+ const Float_t maxpossave = abmaxpos;
+ 
+ x     = abmaxpos;
+ a     = upper - x;
+ b     = x - lower;
+
+  step  = 0.04; // step size of 83 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+
+ if (abmaxpos < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+      upper--;
+      lower--;
+    }
+ 
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+  */
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalFilter:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+//
+/*
+void MExtractBlindPixel::FindSignalFilter(Byte_t *ptr, Int_t range, Int_t &sum, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + range;
+  
+  while (ptr<end)
+    {
+      sum += *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedBlindPixel container.
+//
+Int_t MExtractBlindPixel::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  
+  fBlindPixel->Clear();
+  
+  for (UInt_t id=0;id<fBlindPixelIdx.GetSize();id++)
+  {
+      // Be carefull: GetSaturation changed sat0 and sat1
+      Int_t sat0 = fHiGainFirst; // First slice to extract and first saturating slice
+      Int_t sat1 = fHiGainLast;  // Last  slice to extract and last saturating slice
+
+      const Int_t sat = fSignal->GetSaturation(fBlindPixelIdx[id], fSaturationLimit, sat0, sat1);
+      
+      if (IsExtractionType(kFilter))
+      {
+          // FIXME: fLoGain* is used to determine the FILTER/CHECK range
+          const Int_t numh = fRunHeader->GetNumSamplesHiGain();
+
+          const Int_t sum = fSignal->GetIntegralRaw(fBlindPixelIdx[id], fLoGainFirst+numh, fLoGainLast+numh);
+	  if (sum > fNSBFilterLimit)
+	  {
+	      fBlindPixel->SetExtractedSignal(-1.,id);
+	      fBlindPixel->SetNumSaturated(sat,id);
+	      fBlindPixel->SetReadyToSave();
+	      continue;
+	  }
+
+          /*
+          sum = 0;
+          if (pixel.HasLoGain())
+            FindSignalFilter(sl+pixel.GetNumLoGainSamples()+fLoGainFirst, fLoGainLast - fLoGainFirst + 1, sum, sat);
+
+          if (fModified)
+            {
+              if (sum > fNSBFilterLimit)
+                {
+                  fBlindPixel->SetExtractedSignal(-1.,id);
+                  fBlindPixel->SetNumSaturated(sat,id);
+                  fBlindPixel->SetReadyToSave();
+                  continue;
+                }
+            }
+          */
+      }
+
+
+      Float_t newsum = 0.;
+      if (IsExtractionType(kAmplitude))
+          newsum = FindAmplitude(fBlindPixelIdx[id], sat);
+      else
+          newsum = fSignal->GetIntegralRaw(fBlindPixelIdx[id], fHiGainFirst, fHiGainLast);
+  
+      fBlindPixel->SetExtractedSignal(newsum, id);
+      fBlindPixel->SetNumSaturated(sat, id);
+  }
+
+  fBlindPixel->SetReadyToSave();
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------------------
+//
+// Returns true if the Data type. Available are: kAmplitude, kIntegral and kFilter
+// The flags kIntegral and kFilter may be set both. 
+//
+Bool_t MExtractBlindPixel::IsDataType( const DataType_t typ )
+{
+  return TESTBIT( fDataType, typ );
+}
+
+// ------------------------------------------------------------------------------------
+//
+// Returns true if the extraction type. Available are: kAmplitude, kIntegral and kFilter
+// The flags kIntegral and kFilter may be set both. 
+//
+Bool_t MExtractBlindPixel::IsExtractionType( const ExtractionType_t typ )
+{
+  return TESTBIT( fExtractionType, typ );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the Data type. Available are: kAmplitude and kIntegral
+//
+void MExtractBlindPixel::SetDataType( const DataType_t typ )
+{
+  SETBIT( fDataType, typ );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the extraction type. Available are: kAmplitude and kIntegral
+//
+void MExtractBlindPixel::SetExtractionType( const ExtractionType_t typ )
+{
+  SETBIT( fExtractionType, typ );
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractBlindPixel.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractBlindPixel.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractBlindPixel.h	(revision 17960)
@@ -0,0 +1,97 @@
+#ifndef MARS_MExtractBlindPixel
+#define MARS_MExtractBlindPixel
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MCalibrationBlindCam;
+class MExtractedSignalBlindPixel;
+
+class MExtractBlindPixel : public MExtractor
+{
+private:
+
+  static const UInt_t  fgBlindPixelIdx;    //! Default blind pixels index before modification run
+  static const Byte_t  fgHiGainFirst;      //! Default First FADC slice Hi-Gain Signal (currently set to: 10   ) 
+  static const Byte_t  fgHiGainLast;       //! Default Last  FADC slice Hi-Gain Signal (currently set to: 29   ) 
+  static const Byte_t  fgLoGainFirst;      //! Default First FADC slice Filter         (currently set to: 0    ) 
+  static const Byte_t  fgLoGainLast;       //! Default Last  FADC slice Filter         (currently set to: 6    ) 
+  static const Int_t   fgNSBFilterLimit;   //! Default for fNSBFilterLimit
+  static const Float_t fgResolution;       //! Default for fResolution         (currently set to: 0.003)
+  static const Float_t gkOverflow;         //! Default sum to assign overflow in case of saturation
+
+  MExtractedSignalBlindPixel *fBlindPixel; // Extracted signal of the Blind Pixel
+
+//  Byte_t   fHiLoFirst;                     // If not zero, start extraction from fHiLoFirst slice of Low-Gain
+//  Byte_t   fHiLoLast;
+
+//  MArrayF  fHiGainSignal;                  //! Need fast access to the signals in a float way
+  MArrayF  fHiGainFirstDeriv;              //! First derivative at intersection
+  MArrayF  fHiGainSecondDeriv;             //! Second derivative at intersection
+
+  Float_t fResolution;                     // The time resolution in FADC units
+  MArrayI fBlindPixelIdx;                  // Array holding the IDs of the blind pixel(s)
+  Int_t   fNSBFilterLimit;                 // Limit of sum of FADC slices for filter part
+
+  Byte_t  fExtractionType;                 // What extraction type has been chosen?
+  Byte_t  fDataType;                       // What data container type is needed?  
+//  Int_t   fNumBlindPixels;                 // Current number of blind pixels
+
+public:
+  enum ExtractionType_t { kAmplitude, kIntegral, kFilter };
+  enum DataType_t       { kRawEvt, kRawEvt2 };
+
+private:
+  Float_t FindAmplitude(Int_t idx, Int_t numsat) const;
+//  void FindIntegral    (Byte_t *firstused, Byte_t *lowgain, Float_t &sum, Byte_t &sat);
+//  void FindSignalFilter(Byte_t *ptr, Int_t range,             Int_t &sum, Byte_t &sat) const;
+  
+  Int_t  PreProcess(MParList *pList);
+  Bool_t ReInit(MParList *pList);
+  Int_t  Process();
+
+public:
+
+  MExtractBlindPixel(const char *name=NULL, const char *title=NULL);
+
+  void Clear( const Option_t *o ="");
+  
+  // Getters
+  Bool_t IsExtractionType ( const ExtractionType_t typ );
+  Bool_t IsDataType       ( const DataType_t       typ );
+
+  // Setters
+  /*
+  void SetBlindPixelIdx(  const Int_t  idx=fgBlindPixelIdx, const UInt_t nr=0 )
+  {
+      if (nr>=fBlindPixelIdx.GetSize())
+          fBlindPixelIdx.Set(nr+1);
+      fBlindPixelIdx[nr] = idx;
+      }
+      */
+
+  void SetBlindPixels(const MCalibrationBlindCam &cam);
+
+  void SetExtractionType( const ExtractionType_t typ=kAmplitude );
+  void SetDataType    ( const DataType_t       typ=kRawEvt    );  
+  void SetNSBFilterLimit( const Int_t   lim=fgNSBFilterLimit )  { fNSBFilterLimit = lim;   }     
+  
+//  void SetNumBlindPixels( const Int_t   num=1 )  { fNumBlindPixels = num;   }
+  
+  void SetRange         ( const UShort_t hifirst=0, const UShort_t hilast=0,
+   		          const Int_t    lofirst=0, const Byte_t   lolast=0 );
+  void SetResolution    ( const Float_t f=fgResolution       )  { fResolution     = f;     }
+  
+  ClassDef(MExtractBlindPixel, 0) // Signal Extractor for the Blind Pixel
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractFACT.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFACT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFACT.cc	(revision 17960)
@@ -0,0 +1,268 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 2014 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2014
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractFACT
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractFACT.h"
+
+#include <algorithm>
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MExtractFACT);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets: 
+// - fWindowSizeHiGain and fWindowSizeLoGain to 0
+// - fLoGainStartShift to fgLoGainStartShift
+// - fLoGainSwitch     to fgLoGainSwitch
+//
+MExtractFACT::MExtractFACT(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MExtractFACT";
+    fTitle = title ? title : "Base class for signal and time extractors";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//  - MArrivalTimeCam    
+//
+Int_t MExtractFACT::PreProcess(MParList *pList)
+{
+    if (!MExtractTime::PreProcess(pList))
+        return kFALSE;
+
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj("MExtractedSignalCam",AddSerialNumber(fNameSignalCam));
+    if (!fSignals)
+        return kFALSE;
+
+    *fLog << flush << inf;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+//
+// Call: 
+// - MArrivalTimeCam::SetUsedFADCSlices(fHiGainFirst, fHiGainLast, fNumHiGainSamples,
+//                                      fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+// - InitArrays();
+//
+Bool_t MExtractFACT::ReInit(MParList *pList)
+{
+    if (!MExtractTime::ReInit(pList))
+        return kFALSE;
+
+    //if (fSignals)
+    //    fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast, fNumHiGainSamples,
+    //                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MArrivalTimeCam container.
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container. 
+// The functions FindTimeAndChargeHiGain() and FindTimeAndChargeLoGain() are 
+// supposed to extract the signal themselves.
+//
+Int_t MExtractFACT::Process()
+{
+    // FIXME: Check ranges
+    //const UInt_t nroi = fSignal->GetNumSamples();
+    const UInt_t npix = fSignal->GetNumPixels();
+
+    const UInt_t rangehi = fHiGainLast - fHiGainFirst - 1;
+
+    for (UInt_t ch=0; ch<npix; ch++)
+    {
+        const Float_t *ptr = fSignal->GetSamples(ch);
+
+        const Float_t *pbeg = ptr+fHiGainFirst+1;
+        const Float_t *pend = ptr+fHiGainLast-1;
+
+        // Find maximum
+        const Float_t *pmax = pbeg;
+
+        if (!IsNoiseCalculation())
+        {
+            for (const Float_t *p=pbeg; p<pend; p++)
+                if (*p>*pmax)
+                    pmax = p;
+        }
+
+        //Float_t max = *pmax;
+
+        // -------------------------------------------------------------------------
+        // Calculate a parabola through this and the surrounding points
+        // on logarithmic values (that's a gaussian)
+        //
+        // Quadratic interpolation
+        //
+        // calculate the parameters of a parabula such that
+        //    y(i)  = a + b*x(i) +   c*x(i)^2
+        //    y'(i) =     b      + 2*c*x(i)
+        //
+        // y = exp( - (x-k)^2 / s^2 / 2 )
+        //
+        // -2*s^2 * log(y) = x^2 - 2*k*x + k^2
+        //
+        // a = (k/s0)^2/2
+        // b = k/s^2
+        // c = -1/(2s^2)      -->    s = sqrt(-1/2c)
+        //
+        Float_t max  = -1;
+        if (pmax>pbeg && pmax<pend-1)
+        {
+            const Float_t &v1 = pmax[-1];
+            const Float_t &v2 = pmax[ 0];
+            const Float_t &v3 = pmax[+1];
+            if (v1>0 && v2>0 && v3>0)
+            {
+                const double y1 = log(v1);
+                const double y2 = log(v2);
+                const double y3 = log(v3);
+
+                const double a = y2;
+                const double b = (y3-y1)/2;
+                const double c = (y1+y3)/2 - y2;
+                if (c<0)
+                {
+                    const double w  = -1./(2*c);
+                    const double dx =  b*w;
+
+                    if (dx>=-1 && dx<=1)
+                    {
+                        max = exp(a + b*dx + c*dx*dx);
+
+                        // Time is position of maximum
+                        //time = dx;
+                        //time += Int_t(pmax-ptr);
+                    }
+                }
+            }
+        }
+
+        Float_t time = -1;
+        if (max>=0)
+        {
+            // -10: maximum search window
+
+            // Time is position of half hight leading edge
+            pend = std::max(pbeg, pmax-10);
+            for (;pmax>=pend; pmax--)
+                if (*pmax<max/2)
+                    break;
+
+            if (pmax>pend && pmax[0]!=pmax[1])
+            {
+                time = (max/2-pmax[0])/(pmax[1]-pmax[0]);
+                time += Int_t(pmax-ptr);
+            }
+        }
+
+        if (time<0)
+        {
+            time = gRandom->Uniform(rangehi)+fHiGainFirst+1;
+            max  = pbeg[uint16_t(time)];
+        }
+
+        // Now store the result in the corresponding containers
+        MExtractedSignalPix &pix = (*fSignals)[ch];
+        MArrivalTimePix     &tix = (*fArrTime)[ch];
+        pix.SetExtractedSignal(max);
+        pix.SetGainSaturation(0);
+
+        tix.SetArrivalTime(time);
+        tix.SetGainSaturation(0);
+    }
+
+    fArrTime->SetReadyToSave();
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.LoGainStartShift: -2.8
+//
+Int_t MExtractFACT::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = MExtractTime::ReadEnv(env, prefix, print);
+    /*
+    if (IsEnvDefined(env, prefix, "LoGainStartShift", print))
+    {
+        fLoGainStartShift = GetEnvValue(env, prefix, "LoGainStartShift", fgLoGainStartShift);
+	SetLoGainStartShift(fLoGainStartShift);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "LoGainSwitch", print))
+    {
+        fLoGainSwitch = GetEnvValue(env, prefix, "LoGainSwitch", (Int_t)fLoGainSwitch);
+        rc = kTRUE;
+    }
+    */
+    return rc;
+}
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractFACT.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFACT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFACT.h	(revision 17960)
@@ -0,0 +1,24 @@
+#ifndef MARS_MExtractFACT
+#define MARS_MExtractFACT
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MExtractFACT : public MExtractTime
+{
+private:
+  Int_t  PreProcess(MParList *pList);
+  Bool_t ReInit(MParList *pList);
+  Int_t  Process();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+  MExtractFACT(const char *name=NULL, const char *title=NULL);
+  
+  virtual Bool_t InitArrays(Int_t) { return kTRUE; }
+
+  ClassDef(MExtractFACT, 0)   // Time And Charge Extractor Base Class
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractFixedWindow.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFixedWindow.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFixedWindow.cc	(revision 17960)
@@ -0,0 +1,332 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!              Thomas Bretz, 01/2004 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MExtractFixedWindow
+//
+//  Extracts the signal from a fixed window in a given range by summing up the 
+//  slice contents.
+//
+//  Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//  to modify the ranges. Ranges have to be an even number. In case of odd 
+//  ranges, the last slice will be reduced by one.
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  3 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractFixedWindow.h"
+#include "MExtractor.h"
+
+#include <fstream>
+
+#include "MExtractedSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractFixedWindow);
+
+using namespace std;
+
+const Byte_t MExtractFixedWindow::fgHiGainFirst =  3;
+const Byte_t MExtractFixedWindow::fgHiGainLast  =  14;
+const Byte_t MExtractFixedWindow::fgLoGainFirst =  3;
+const Byte_t MExtractFixedWindow::fgLoGainLast  =  14;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls:
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractFixedWindow::MExtractFixedWindow(const char *name, const char *title)
+{
+  fName  = name  ? name  : "MExtractFixedWindow";
+  fTitle = title ? title : "Signal Extractor for a fixed FADC window";
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the window defined by (fHiGainLast-fHiGainFirst-1) are odd, subtract one
+// - if the window defined by (fLoGainLast-fLoGainFirst-1) are odd, subtract one
+// - if the Hi Gain window is smaller than 2, set fHiGainLast to fHiGainFirst+1
+// - if the Lo Gain window is smaller than 2, set fLoGainLast to fLoGainFirst+1
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: (Float_t)(fLoGainLast-fLoGainFirst+1)
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractFixedWindow::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  const Byte_t windowhi = hilast-hifirst+1;
+  const Byte_t whieven = windowhi & ~1;
+
+  if (whieven != windowhi)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window size has to be even, set last slice from "
+                    ,(int)hilast," to ",(int)(hilast-1)) << endl;
+      hilast -= 1;
+    }
+  
+  if (whieven<2) 
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window is smaller than 2 FADC sampes, set last slice from" 
+                    ,(int)hilast," to ",(int)(hifirst+1)) << endl;
+      hilast = hifirst+1;
+    }
+  
+
+  if (lolast != 0)
+    {
+      const Byte_t windowlo = lolast-lofirst+1;
+      const Byte_t wloeven = windowlo & ~1;
+
+      if (wloeven != windowlo)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i",": Lo Gain window size has to be even, set last slice from "
+                        ,(int)lolast," to ",(int)(lolast-1)) << endl;
+          lolast -= 1;
+        }
+      
+      if (wloeven<2) 
+        {
+          *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Lo Gain window is smaller than 2 FADC sampes, set last slice from" 
+                    ,(int)lolast," to ",(int)(lofirst+1)) << endl;
+          lolast = lofirst+1;        
+        }
+    }
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst+1);
+  if (fLoGainLast != 0)
+    fNumLoGainSamples = (Float_t)(fLoGainLast-fLoGainFirst+1);  
+  else
+    fNumLoGainSamples = 0.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);  
+
+  const Int_t wshigain = fHiGainLast-fHiGainFirst+1;
+  const Int_t wslogain = fLoGainLast-fLoGainFirst+1;
+
+  switch (wshigain)
+    {
+    case 2:
+      SetResolutionPerPheHiGain(0.021);
+      break;
+    case 4:
+    case 6:
+    case 8:
+    case 10:
+    case 12:
+    case 14:
+      SetResolutionPerPheHiGain(0.011);      
+      break;
+    default:
+        *fLog << warn << GetDescriptor() << ": Could not set the hi-gain extractor resolution/phe for window size " << wshigain << endl;
+    }
+  
+  switch (wslogain)
+    {
+    case 4:
+      SetResolutionPerPheLoGain(0.063);
+      break;
+    case 6:
+      SetResolutionPerPheLoGain(0.017);
+      break;
+    case 8:
+    case 10:
+      SetResolutionPerPheLoGain(0.011);      
+      break;
+    default:
+      *fLog << warn << GetDescriptor() << ": Could not set the lo-gain extractor resolution/phe for window size " << wslogain << endl;
+      SetResolutionPerPheLoGain(0.011);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+//
+Bool_t MExtractFixedWindow::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+
+  *fLog << endl;
+  *fLog << inf << "Taking " << fNumHiGainSamples
+        << " HiGain samples from slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast+fHiLoLast) << " incl" << endl;
+  *fLog << inf << "Taking " << fNumLoGainSamples
+        << " LoGain samples from slice " << (Int_t)fLoGainFirst
+        << " to " << (Int_t)fLoGainLast << " incl" << endl;
+  return kTRUE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+// - If fHiLoLast is not 0, loop also from logain to (logain+fHiLoLast)
+// - Sum up contents of logain
+// - If *logain is greater than fSaturationLimit, raise sat by 1
+//
+void MExtractFixedWindow::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+
+  Int_t summ = 0;
+
+  Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  while (ptr<end)
+    {
+      summ += *ptr;
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+
+  Byte_t *p = logain;
+  end = logain + fHiLoLast;
+  while (p<end)
+    {
+      summ += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+
+  sum = (Float_t)summ;
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - If fHiLoLast is set, loop from logain to (logain+fHiLoLast)
+// - Add contents of *logain to sum
+// 
+void MExtractFixedWindow::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+
+  Int_t summ = 0;
+
+  Byte_t *end = ptr + fLoGainLast - fLoGainFirst + 1;
+  
+  while (ptr<end)
+    {
+      summ += *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+
+  sum = (Float_t)summ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MExtractFixedWindow::StreamPrimitive(ostream &out) const
+{
+
+  out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+  out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+  
+  if (fSaturationLimit!=fgSaturationLimit)
+    {
+      out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+      out << (int)fSaturationLimit << ");" << endl;
+    }
+  
+  const Bool_t arg4 = fNumLoGainSamples+fLoGainFirst-1 != fgLoGainLast;
+  const Bool_t arg3 = arg4 || fLoGainFirst != fgLoGainFirst;
+  const Bool_t arg2 = arg3 || fNumHiGainSamples+fHiGainFirst-1 != fgHiGainLast;
+  const Bool_t arg1 = arg2 || fHiGainFirst != fgHiGainFirst;
+  
+  if (!arg1)
+    return;
+  
+  out << "   " << GetUniqueName() << ".SetRange(";
+  out << (int)fLoGainFirst;
+  if (arg2)
+    {
+      out << ", " << (int)(fNumHiGainSamples+fHiGainFirst-1);
+      if (arg3)
+        {
+          out << ", " << (int)fLoGainFirst;
+          if (arg4)
+            out << ", " << (int)(fNumLoGainSamples+fLoGainFirst-1);
+        }
+    }
+  out << ");" << endl;
+}
+
+void MExtractFixedWindow::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    MExtractor::Print(o);
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractFixedWindow.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFixedWindow.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFixedWindow.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MExtractFixedWindow
+#define MARS_MExtractFixedWindow
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractFixedWindow                                                          //
+//                                                                         //
+// Integrates the time slices of the all pixels in a fixed window          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractFixedWindow : public MExtractor
+{
+private:
+  static const Byte_t fgHiGainFirst;     // First FADC slice Hi-Gain (currently set to: 3) 
+  static const Byte_t fgHiGainLast;      // Last FADC slice Hi-Gain (currently set to: 14) 
+  static const Byte_t fgLoGainFirst;     // First FADC slice Lo-Gain (currently set to: 3) 
+  static const Byte_t fgLoGainLast;      // Last FADC slice Lo-Gain (currently set to: 14) 
+
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;
+
+  void   StreamPrimitive(ostream &out) const;
+
+  Bool_t ReInit(MParList *pList);
+  
+public:
+
+  MExtractFixedWindow(const char *name=NULL, const char *title=NULL);
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+
+  void Print(Option_t *o="") const;
+  
+  ClassDef(MExtractFixedWindow, 1) // Signal Extractor for a fixed extraction window
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowPeakSearch.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowPeakSearch.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowPeakSearch.cc	(revision 17960)
@@ -0,0 +1,564 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 04/2004 <mailto:moralejo@pd.infn.it>
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractFixedWindowPeakSearch
+//
+//  Calculate the signal integrating fWindowSize time slices, the same for 
+//  all pixels. The integrated slices change from event to event, since the
+//  pulse positions in the FADC jump between events, but apparently in a 
+//  "coherent" fashion. We first loop over all pixels and find the one 
+//  which has the highest sum of fPeakSearchWindowSize (default: 4) consecutive 
+//  non-saturated high gain slices. The position of the peak in this pixel 
+//  determines the integration window position for all pixels of this event. 
+//  For the moment we neglect time delays between pixels (which are in most 
+//  cases small). The class is based on MExtractSlidingWindow.
+//
+//  Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//  to modify the ranges in which the window is allowed to move. 
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindows(windowhigain, windowlogain,peaksearchwindow) 
+//  to modify the sliding window widths. Windows have to be an even number. 
+//  In case of odd numbers, the window will be modified.
+//
+//  Call: SetOffsetFromWindow() to adjust the positionning of the extraction
+//  window w.r.t. the peak search window. An fOffsetFromWindow of 0 means that
+//  the starting slice of the extraction window is equal to the starting slice
+//  of the maximizing peak search window. fOffsetFromWindow equal to 1 (default)
+//  means that the extraction window starts one slice earlier than the peak 
+//  search window result. It is recommanded to always use a smaller peak search
+//  window than the extraction window.
+//
+//  Defaults are:
+//
+//   fHiGainWindowSize     = fgHiGainWindowSize     = 6
+//   fLoGainWindowSize     = fgLoGainWindowSize     = 6
+//   fPeakSearchWindowSize = fgPeakSearchWindowSize = 4
+//   fLoGainPeakShift      = fgLoGainPeakShift      = 0
+//   fOffsetFromWindow     = fgOffsetFromWindow     = 1
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractFixedWindowPeakSearch.h"
+#include "MExtractor.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MExtractFixedWindowPeakSearch);
+
+using namespace std;
+
+const Byte_t MExtractFixedWindowPeakSearch::fgHiGainFirst          = 0;
+const Byte_t MExtractFixedWindowPeakSearch::fgHiGainLast           = 16;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainFirst          = 3;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainLast           = 14;
+const Byte_t MExtractFixedWindowPeakSearch::fgHiGainWindowSize     = 6;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainWindowSize     = 6;
+const Byte_t MExtractFixedWindowPeakSearch::fgPeakSearchWindowSize = 4;
+const Byte_t MExtractFixedWindowPeakSearch::fgOffsetFromWindow     = 1;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainPeakShift      = 1;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fHiGainWindowSize to fgHiGainWindowSize
+// - fLoGainWindowSize to fgLoGainWindowSize
+// - fPeakSearchWindowSize to fgPeakSearchWindowSize
+// - fLoGainPeakShift to fgLoGainPeakShift
+//
+// Calls: 
+// - SetOffsetFromWindow()
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractFixedWindowPeakSearch::MExtractFixedWindowPeakSearch(const char *name, const char *title)
+    : fHiGainWindowSize(fgHiGainWindowSize), 
+      fLoGainWindowSize(fgLoGainWindowSize),
+      fPeakSearchWindowSize(fgPeakSearchWindowSize),
+      fLoGainPeakShift(fgLoGainPeakShift)
+{
+
+  fName  = name  ? name  : "MExtractFixedWindowPeakSearch";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+  SetOffsetFromWindow();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - SetWindows(fHiGainWindowSize,fLoGainWindowSize,fPeakSearchWindowSize);
+//
+void MExtractFixedWindowPeakSearch::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  //
+  // Redo the checks if the window is still inside the ranges
+  //
+  SetWindows(fHiGainWindowSize,fLoGainWindowSize,fPeakSearchWindowSize);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd, subtract one
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fHiGainWindowSize
+// - fNumLoGainSamples to: (Float_t)fLoGainWindowSize
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractFixedWindowPeakSearch::SetWindows(Byte_t windowh, Byte_t windowl, Byte_t peaksearchwindow)
+{
+
+  fHiGainWindowSize     = windowh & ~1;
+  fLoGainWindowSize     = windowl & ~1;
+  fPeakSearchWindowSize = peaksearchwindow & ~1;
+
+  if (fHiGainWindowSize != windowh)
+    *fLog << warn << GetDescriptor() << ": Hi Gain window size has to be even, set to: " 
+          << int(fHiGainWindowSize) << " samples " << endl;
+  
+  if (fLoGainWindowSize != windowl)
+    *fLog << warn << GetDescriptor() << ": Lo Gain window size has to be even, set to: " 
+          << int(fLoGainWindowSize) << " samples " << endl;
+    
+  if (fPeakSearchWindowSize != peaksearchwindow)
+    *fLog << warn << GetDescriptor() << ": Peak Search window size has to be even, set to: " 
+          << int(fPeakSearchWindowSize) << " samples " << endl;
+
+  const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
+  const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
+
+  if (fHiGainWindowSize > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fHiGainWindowSize,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fHiGainWindowSize = availhirange;
+    }
+  
+  
+  if (fLoGainWindowSize > availlorange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fLoGainWindowSize,
+                    " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availlorange << endl;
+      fLoGainWindowSize = availlorange;
+    }
+  
+  if (fHiGainWindowSize<2) 
+    {
+      fHiGainWindowSize = 2;
+      *fLog << warn << GetDescriptor() << ": Hi Gain window size set to two samples" << endl;
+    }
+  
+  if (fLoGainWindowSize<2) 
+    {
+      fLoGainWindowSize = 2;
+      *fLog << warn << GetDescriptor() << ": Lo Gain window size set to two samples" << endl;
+    }
+
+  if (fPeakSearchWindowSize<2) 
+    {
+      fPeakSearchWindowSize = 2;
+      *fLog << warn << GetDescriptor() 
+            << ": Peak Search window size set to two samples" << endl;
+    }
+
+  fNumHiGainSamples = (Float_t)fHiGainWindowSize;
+  fNumLoGainSamples = (Float_t)fLoGainWindowSize;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+//
+Bool_t MExtractFixedWindowPeakSearch::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+  *fLog << dec << endl;
+  *fLog << inf << "Taking " << fNumHiGainSamples
+        << " HiGain samples starting with slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast+fHiLoLast) << " incl" << endl;
+  *fLog << inf << "Taking " << fNumLoGainSamples
+        << " LoGain samples starting with slice " << (Int_t)fLoGainFirst
+        << " to " << (Int_t)fLoGainLast << " incl" << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindPeak
+// Finds highest sum of "window" consecutive FADC slices in a pixel, and store
+// in "startslice" the first slice of the group which yields the maximum sum.
+// In "max" the value of the maximum sum is stored, in "sat" the number of 
+// saturated slices.
+//
+void MExtractFixedWindowPeakSearch::FindPeak(Byte_t *ptr, Byte_t window, Byte_t &startslice, Int_t &max, 
+                                             Int_t &sat, Byte_t &satpos) const
+{
+
+  const Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  sat = 0;
+  satpos = 0;
+  
+  startslice = 0;
+  Int_t sum=0;
+
+  //
+  // Calculate the sum of the first "window" slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+
+  while (p<ptr+window)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+              satpos = p-ptr;
+          sat++;
+        }
+    }
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      {
+        if (sat == 0)
+          satpos = p-ptr;
+        sat++;
+      }
+  
+  //
+  // Calculate the i-th sum of n as
+  //    sum_i+1 = sum_i + slice[i+window] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  for (p=ptr; p+window<end; p++)
+    {
+      sum += *(p+window) - *p;
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = p-ptr+1;
+	}
+    }
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainWindowSize)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractFixedWindowPeakSearch::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + fHiGainWindowSize-fHiLoLast;
+
+  Int_t summ = 0;
+  //
+  // Calculate the sum of the "window" slices starting in ptr
+  //
+  while (ptr<end)
+    {
+      summ += *ptr;
+      if (*ptr++ >= fSaturationLimit)
+	sat++;
+    }
+
+  //
+  // If part of the "lo-Gain" slices are used,
+  // repeat steps one and two for the logain part until fHiLoLast
+  //
+  Byte_t *p = logain;
+  end = logain + fHiLoLast;
+  while (p<end)
+    {
+  
+      summ += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+
+  sum = (Float_t)summ;
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainWindowSize)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractFixedWindowPeakSearch::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+  //
+  // Calculate the sum of the "window" slices starting in ptr
+  //
+  Byte_t *p = ptr;
+  Int_t summ = 0;
+
+  while (p<ptr+fLoGainWindowSize)
+    {
+      summ += *p;
+      if (*p++ >= fSaturationLimit)
+	sat++;
+    }
+
+  sum = (Float_t)summ;
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process
+// First find the pixel with highest sum of fPeakSearchWindowSize slices (default:4)
+// "startslice" will mark the slice at which the highest sum begins for that pixel.
+// Then define the beginning of the integration window for ALL pixels as the slice
+// before that: startslice-fOffsetFromWindow, unless of course startslice-fOffsetFromWindow<=0,
+// in which case we start at 0. We will also check that the integration window does not 
+// go beyond the FADC limits.
+//
+Int_t MExtractFixedWindowPeakSearch::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  Int_t sat;
+  Byte_t  satpos;
+  ULong_t gsatpos = 0;
+
+  Int_t maxsumhi = -1000000;
+  Int_t numsat   = 0;
+  Byte_t startslice;
+  Byte_t hiGainFirst = 0;
+  Byte_t loGainFirst = 0;
+  fHiLoLast = 0;
+
+  while (pixel.Next())
+    {
+      Int_t sumhi;
+      sat = 0;
+
+      FindPeak(pixel.GetHiGainSamples()+fHiGainFirst, fPeakSearchWindowSize, startslice, sumhi, sat, satpos);
+
+      if (sumhi > maxsumhi && sat == 0)
+	{
+	  maxsumhi = sumhi;
+	  if (startslice > fOffsetFromWindow)
+            hiGainFirst = fHiGainFirst + startslice - fOffsetFromWindow;
+	  else
+	    hiGainFirst = fHiGainFirst;
+	}
+      else if (sat)
+        {
+          numsat++;
+          gsatpos += satpos;
+        }
+    }
+
+  // Check necessary for calibration events
+  if (numsat > fSignals->GetSize()*0.9)
+    hiGainFirst = gsatpos/numsat - 1;
+
+  loGainFirst = ( hiGainFirst+fLoGainPeakShift > fLoGainFirst ) 
+    ? hiGainFirst+fLoGainPeakShift 
+    : fLoGainFirst;
+
+  // Make sure we will not integrate beyond the hi gain limit:
+  if (hiGainFirst+fHiGainWindowSize > pixel.GetNumHiGainSamples())
+    fHiLoLast = hiGainFirst+fHiGainWindowSize - pixel.GetNumHiGainSamples();
+  //    hiGainFirst = pixel.GetNumHiGainSamples()-fHiGainWindowSize;
+
+  // Make sure we will not integrate beyond the lo gain limit:
+  if (loGainFirst+fLoGainWindowSize > pixel.GetNumLoGainSamples())
+    loGainFirst = pixel.GetNumLoGainSamples()-fLoGainWindowSize;
+
+  pixel.Reset();
+
+  while (pixel.Next())
+    {
+      //
+      // Find signal in hi- and lo-gain
+      //
+      Float_t sumhi=0.;
+      Byte_t sathi=0;
+
+      FindSignalHiGain(pixel.GetHiGainSamples()+hiGainFirst, pixel.GetLoGainSamples(), sumhi, sathi);
+
+      Float_t sumlo=0.;
+      Byte_t satlo=0;
+      if (pixel.HasLoGain())
+        FindSignalLoGain(pixel.GetLoGainSamples()+loGainFirst, sumlo, satlo);
+
+      //
+      // Take corresponding pedestal
+      //
+      const Int_t pixid = pixel.GetPixelId();
+
+      const MPedestalPix  &ped = (*fPedestals)[pixid];
+      MExtractedSignalPix &pix = (*fSignals)[pixid];
+
+      const Float_t pedes  = ped.GetPedestal();
+      const Float_t pedrms = ped.GetPedestalRms();
+      //
+      // Set extracted signal with pedestal substracted
+      //
+      pix.SetExtractedSignal(sumhi - pedes*fNumHiGainSamples, pedrms*fSqrtHiGainSamples,
+                             sumlo - pedes*fNumLoGainSamples, pedrms*fSqrtLoGainSamples);
+
+      pix.SetGainSaturation(sathi, satlo);
+
+      //      pix.SetNumHiGainSlices(fNumHiGainSamples);
+      //      pix.SetNumLoGainSlices(fNumLoGainSamples);      
+      
+    } /* while (pixel.Next()) */
+
+
+  fSignals->SetReadyToSave();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//   MJPedestal.MExtractor.PeakSearchWindow: 4
+//   MJPedestal.MExtractor.OffsetFromWindow: 1
+//   MJPedestal.MExtractor.LoGainPeakShift:  1
+//
+Int_t MExtractFixedWindowPeakSearch::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Byte_t hw = fHiGainWindowSize;
+    Byte_t lw = fLoGainWindowSize;
+    Byte_t pw = fPeakSearchWindowSize;
+
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "PeakSearchWindow", print))
+    {
+        pw = GetEnvValue(env, prefix, "PeakSearchWindow", pw);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+        hw = GetEnvValue(env, prefix, "HiGainWindowSize", hw);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+        lw = GetEnvValue(env, prefix, "LoGainWindowSize", lw);
+        rc = kTRUE;
+    }
+
+    if (rc)
+        SetWindows(hw, lw, pw);
+
+
+    if (IsEnvDefined(env, prefix, "OffsetFromWindow", print))
+    {
+        SetOffsetFromWindow(GetEnvValue(env, prefix, "OffsetFromWindow", fOffsetFromWindow));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "LoGainPeakShift", print))
+    {
+        SetLoGainPeakShift(GetEnvValue(env, prefix, "LoGainPeakShift", fLoGainPeakShift));
+        rc = kTRUE;
+    }
+
+    rc = MExtractor::ReadEnv(env, prefix, print) ? kTRUE : rc;
+
+    return rc;
+}
+
+void MExtractFixedWindowPeakSearch::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " Windows: Hi-Gain=" << (int)fHiGainWindowSize << "  Lo-Gain=" << (int)fLoGainWindowSize;
+    *fLog << "  Peak-Search=" << (int)fPeakSearchWindowSize << endl;
+    *fLog << " Offset From Window: " << (int)fOffsetFromWindow << endl;
+    *fLog << " Lo-Gain peak Shift: " << (int)fLoGainPeakShift << endl;
+    MExtractor::Print(o);
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowPeakSearch.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowPeakSearch.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowPeakSearch.h	(revision 17960)
@@ -0,0 +1,56 @@
+#ifndef MARS_MExtractFixedWindowPeakSearch
+#define MARS_MExtractFixedWindowPeakSearch
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractFixedWindowPeakSearch : public MExtractor
+{
+private:
+
+  static const Byte_t fgHiGainFirst;          //! Default for fHiGainFirst          (now set to:  0)
+  static const Byte_t fgHiGainLast;           //! Default for fHiGainLast 	    (now set to: 16)
+  static const Byte_t fgLoGainFirst;          //! Default for fLoGainFirst	    (now set to:  3)
+  static const Byte_t fgLoGainLast;           //! Default for fLoGainLast 	    (now set to: 14)
+  static const Byte_t fgHiGainWindowSize;     //! Default for fWindowSizeHiGain     (now set to:  6)
+  static const Byte_t fgLoGainWindowSize;     //! Default for fWindowSizeLoGain     (now set to:  6)
+  static const Byte_t fgPeakSearchWindowSize; //! Default for fPeakSearchWindowSize (now set to:  4)
+  static const Byte_t fgOffsetFromWindow;     //! Default for fOffsetFromWindow     (now set to:  1)
+  static const Byte_t fgLoGainPeakShift;      //! Default for fLowGainPeakShift     (now set to:  1)
+
+  Byte_t  fHiGainWindowSize;     // Number of Hi Gain slices in window
+  Byte_t  fLoGainWindowSize;     // Number of Lo Gain slices in window
+  Byte_t  fPeakSearchWindowSize; // Size of FADC window in the search for the highest peak of all pixels.
+  Byte_t  fOffsetFromWindow;     // Number of slices to start extraction before search window
+  Byte_t  fLoGainPeakShift;      // Shift of the low gain pulse with respect to the high gain pulse, in slices: it is 0 if the low gain is delayed with respect to HG by 15 slices.
+
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;  
+
+  void   FindPeak(Byte_t *ptr, Byte_t window, Byte_t &startslice, Int_t &signal, Int_t &sat, Byte_t &satpos) const;
+
+  Bool_t ReInit(MParList *pList);
+  Int_t  Process();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MExtractFixedWindowPeakSearch(const char *name=NULL, const char *title=NULL);
+  
+  Byte_t GetHiGainWindowSize() const { return fHiGainWindowSize; }
+  Byte_t GetLoGainWindowSize() const { return fLoGainWindowSize; }
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);    
+  void SetWindows(Byte_t windowh=fgHiGainWindowSize, Byte_t windowl=fgLoGainWindowSize, 
+                  Byte_t peaksearchwindow=fgPeakSearchWindowSize);
+  void SetOffsetFromWindow(Byte_t offset=fgOffsetFromWindow)  {  fOffsetFromWindow = offset; }
+  
+  void SetLoGainPeakShift(Byte_t shift=fgLoGainPeakShift) { fLoGainPeakShift = shift; }
+  
+  void Print(Option_t *o="") const;
+
+  ClassDef(MExtractFixedWindowPeakSearch, 1) // Signal Extractor for fixed size trigger-corrected extraction window
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowSpline.cc	(revision 17960)
@@ -0,0 +1,440 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug       05/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeSpline
+//
+//   Fast Spline extractor using a cubic spline algorithm of Numerical Recipes. 
+//   It returns the integral below the interpolating spline. 
+// 
+//   Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//         to modify the ranges. 
+//
+//         The spline will then be integrated from fHiGainFirst to fHiGainLast, 
+//         including half of the outer edges. The effective number of intergrated
+//         slices ("range") is thus: 
+// 
+//         range = fHiGainLast - fHiGainFirst
+//
+//         Ranges have to be an even number. In case of odd ranges, the last slice 
+//         will be reduced by one.
+//
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  2 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  13
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractFixedWindowSpline.h"
+
+#include "MExtractedSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractFixedWindowSpline);
+
+using namespace std;
+
+const Byte_t  MExtractFixedWindowSpline::fgHiGainFirst  = 2;
+const Byte_t  MExtractFixedWindowSpline::fgHiGainLast   = 14;
+const Byte_t  MExtractFixedWindowSpline::fgLoGainFirst  = 3;
+const Byte_t  MExtractFixedWindowSpline::fgLoGainLast   = 13;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+MExtractFixedWindowSpline::MExtractFixedWindowSpline(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MExtractFixedWindowSpline";
+  fTitle = title ? title : "Signal Extractor for a fixed FADC window using a fast spline";
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the window defined by (fHiGainLast-fHiGainFirst-1) are odd, subtract one
+// - if the window defined by (fLoGainLast-fLoGainFirst-1) are odd, subtract one
+// - if the Hi Gain window is smaller than 2, set fHiGainLast to fHiGainFirst+1
+// - if the Lo Gain window is smaller than 2, set fLoGainLast to fLoGainFirst+1
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: (Float_t)(fLoGainLast-fLoGainFirst+1)
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractFixedWindowSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  const Byte_t windowhi = hilast-hifirst;
+  const Byte_t whieven  = windowhi & ~1;
+
+  if (whieven != windowhi)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window size has to be uneven, set last slice from "
+                    ,(int)hilast," to ",(int)(hilast-1)) << endl;
+      hilast -= 1;
+    }
+  
+  if (whieven<2) 
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window is smaller than 2 FADC sampes, set last slice from" 
+                    ,(int)hilast," to ",(int)(hifirst+2)) << endl;
+      hilast = hifirst+2;
+    }
+
+  const Byte_t windowlo = lolast-lofirst;
+  const Byte_t wloeven  = windowlo & ~1;
+
+  if (lolast != 0)
+    {
+      if (wloeven != windowlo)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i",": Lo Gain window size has to be uneven, set last slice from "
+                        ,(int)lolast," to ",(int)(lolast-1)) << endl;
+          lolast -= 1;
+        }
+      
+      
+      if (wloeven<2) 
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i",": Lo Gain window is smaller than 2 FADC sampes, set last slice from" 
+                        ,(int)lolast," to ",(int)(lofirst+2)) << endl;
+          lolast = lofirst+2;        
+        }
+    }
+  
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  //
+  // Very important: Because the spline interpolates between the slices, 
+  //                 the number of samples for the pedestal subtraction 
+  //                 is now 1 less than with e.g. MExtractFixedWindow
+  //
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst);
+  if (fLoGainLast != 0)
+    fNumLoGainSamples = (Float_t)(fLoGainLast-fLoGainFirst);  
+  else
+    fNumLoGainSamples = 0.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);  
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit
+//
+// Calls:
+// - MExtractor::ReInit(pList);
+// - fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+// 
+// Deletes all arrays, if not NULL
+// Creates new arrays according to the extraction range
+//
+Bool_t MExtractFixedWindowSpline::ReInit(MParList *pList)
+{
+
+  if (!MExtractor::ReInit(pList))
+    return kFALSE;
+
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+  Int_t range = fHiGainLast - fHiGainFirst + 1 + fHiLoLast;
+
+  fHiGainFirstDeriv.Set(range);
+  fHiGainSecondDeriv.Set(range);
+
+  range = fLoGainLast - fLoGainFirst + 1;
+
+  fLoGainFirstDeriv.Set(range);
+  fLoGainSecondDeriv.Set(range);
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+// - If fHiLoLast is not 0, loop also from logain to (logain+fHiLoLast)
+// - Sum up contents of logain
+// - If *logain is greater than fSaturationLimit, raise sat by 1
+//
+void MExtractFixedWindowSpline::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+  
+  const Byte_t *end = ptr + fHiGainLast - fHiGainFirst;
+  Int_t range = fHiGainLast - fHiGainFirst + fHiLoLast + 1;
+  
+  Float_t pp;
+  //  Int_t   i = 0;
+
+  Int_t summ = 0;
+  // 
+  // Take half of the first slice content
+  // 
+  Float_t *firstderiv = fHiGainFirstDeriv.GetArray();
+  Float_t *secondderiv = fHiGainSecondDeriv.GetArray();
+  sum = (Float_t)*ptr/2.;
+  // 
+  // The first slice has already been treated now!
+  // 
+  ptr++; // i++;
+  firstderiv++; 
+  secondderiv++;
+  //
+  // Check for saturation in all other slices
+  //
+  while (ptr<end)
+    {
+
+      summ += *ptr;
+
+      // pp = fHiGainSecondDeriv[i-1] + 4.;
+      // fHiGainSecondDeriv[i] = -1.0/pp;
+      // fHiGainFirstDeriv [i] = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      // fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+
+      pp = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+
+      secondderiv++;
+      firstderiv++;
+
+      //      i++;
+    }
+  
+  switch (fHiLoLast)
+    {
+    case 0:
+      // Treat the last slice of the high-gain as half slice:
+      sum += (Float_t)*ptr/2.;
+      break;
+    case 1:
+      // Treat the last slice of the high-gain as full slice:
+      summ += *ptr;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      if (*logain >= fSaturationLimit)
+        sat++;
+      // Treat the first slice of the low-gain as half slice:
+      sum  += (Float_t)*logain/2;
+      break;
+    case 2:
+      // Treat the last slice of the high-gain as full slice:
+      summ += *ptr;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      // Treat the last first slice of the low-gain as full slice:
+      summ += *logain;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain+1) - 2.* *(logain) + *(ptr);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      if (*logain++ >= fSaturationLimit)
+        sat++;
+      // Treat the second slice of the low-gain as half slice:
+      sum  += (Float_t)*logain/2;
+      if (*logain >= fSaturationLimit)
+        sat++;
+      break;
+    default:
+      // Treat the last slice of the high-gain as full slice:
+      summ += *ptr;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      // Treat the last first slice of the low-gain as full slice:
+      summ += *logain;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain+1) - 2.* *(logain) + *(ptr);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      if (*logain++ >= fSaturationLimit)
+        sat++;
+      // Treat the rest of the slices:
+      const Byte_t *end = logain+fHiLoLast;
+      while (logain<end)
+	{
+	  summ += *logain;
+	  pp    = *(secondderiv-1) + 4.;
+	  *secondderiv = -1.0/pp;
+	  *firstderiv  = *(logain+1) - 2.* *(logain) + *(logain-1);
+	  *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+	  //	  pp = fHiGainSecondDeriv[i-1] + 4.;
+	  //	  fHiGainSecondDeriv[i] = -1.0/pp;
+	  //	  fHiGainFirstDeriv [i] = *(logain+1) - 2.* *(logain) + *(logain-1);
+	  //	  fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+	  secondderiv++;
+	  firstderiv++;
+	  if (*logain++ >= fSaturationLimit)
+	    sat++;
+	}
+      break;
+    }
+  
+  //
+  // Go back to last but one element:
+  //
+  secondderiv--;
+  firstderiv--;
+
+  for (Int_t k=range-2;k>0;k--)
+    {
+      *secondderiv = *secondderiv * *(secondderiv+1) + *firstderiv;
+      sum += 0.25* *secondderiv;
+      firstderiv--;
+      secondderiv--;
+      //      fHiGainSecondDeriv[k] = fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k];
+      //      sum += 0.25*fHiGainSecondDeriv[k];
+    }
+
+  sum += (Float_t)summ;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractFixedWindowSpline::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+  
+  const Byte_t *end = ptr + fLoGainLast - fLoGainFirst;
+  Int_t range = fLoGainLast - fLoGainFirst + 1;
+  
+  Float_t pp;
+  //  Int_t   i = 0;
+
+  Int_t summ = 0;
+  // 
+  // Take half of the first slice content
+  // 
+  Float_t *firstderiv = fLoGainFirstDeriv.GetArray();
+  Float_t *secondderiv = fLoGainSecondDeriv.GetArray();
+  sum = (Float_t)*ptr/2.;
+  // 
+  // The first slice has already been treated now!
+  // 
+  ptr++; // i++;
+  secondderiv++;
+  firstderiv++;
+  //
+  // Check for saturation in all other slices
+  //
+  while (ptr<end)
+    {
+
+      summ += *ptr;
+      //      i++;
+
+      // pp = fLoGainSecondDeriv[i-1] + 4.;
+      // fLoGainSecondDeriv[i] = -1.0/pp;
+      // fLoGainFirstDeriv [i] = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      // fLoGainFirstDeriv [i] = (6.0*fLoGainFirstDeriv[i]-fLoGainFirstDeriv[i-1])/pp;
+
+      pp = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+
+      secondderiv++;
+      firstderiv++;
+    }
+  
+  sum += (Float_t)*ptr/2.;
+  
+  //
+  // Go back to last but one element:
+  //
+  secondderiv--;
+  firstderiv--;
+
+  for (Int_t k=range-2;k>0;k--)
+    {
+      *secondderiv = *secondderiv * *(secondderiv+1) + *firstderiv;
+      sum += 0.25* *secondderiv;
+      firstderiv--;
+      secondderiv--;
+      //      fLoGainSecondDeriv[k] = fLoGainSecondDeriv[k]*fLoGainSecondDeriv[k+1] + fLoGainFirstDeriv[k];
+      //      sum += 0.25*fLoGainSecondDeriv[k];
+    }
+  
+  sum += (Float_t)summ;
+}
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractFixedWindowSpline.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MExtractFixedWindowSpline
+#define MARS_MExtractFixedWindowSpline
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+#ifndef MARS_MArrayF   
+#include "MArrayF.h"
+#endif
+
+class MExtractFixedWindowSpline : public MExtractor
+{
+
+private:
+  
+  static const Byte_t  fgHiGainFirst;    // Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t  fgHiGainLast;     // Default for fHiGainLast   (now set to: 14)
+  static const Byte_t  fgLoGainFirst;    // Default for fLOGainFirst  (now set to: 3)
+  static const Byte_t  fgLoGainLast;     // Default for fLoGainLast   (now set to: 14)
+
+  MArrayF fHiGainFirstDeriv;             //! Temporary storage
+  MArrayF fLoGainFirstDeriv;             //! Temporary storage
+  MArrayF fHiGainSecondDeriv;            //! Temporary storage
+  MArrayF fLoGainSecondDeriv;            //! Temporary storage
+
+  Bool_t ReInit    (MParList *pList);
+  
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;
+
+public:
+
+  MExtractFixedWindowSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractFixedWindowSpline() {}
+  
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+  
+  ClassDef(MExtractFixedWindowSpline, 0)   // Task to Extract the Arrival Times using a Fast Spline
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractPINDiode.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractPINDiode.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractPINDiode.cc	(revision 17960)
@@ -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): Markus Gaug, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MExtractPINDiode
+//
+//  Extracts the signal from a fixed window in a given range.
+//
+//  Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//  to modify the ranges.
+//
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  29
+//   fLoGainFirst =  fgLoGainFirst =  0
+//   fLoGainLast  =  fgLoGainLast  =  0
+//
+//  The FADC slices are fit by a Gaussian around the pulse maximum. 
+//  The following figures show two typical (high-intensity and low-intensity) 
+//  pulses together with the applied fit:
+//
+//Begin_Html
+/*
+<img src="images/PINDiode_pulse_high.gif">
+<img src="images/PINDiode_pulse_low.gif">
+*/
+//End_Html
+//
+// The fit ranges can be modified with the functions:
+// - SetLowerFitLimit() 
+// - SetUpperFitLimit()
+//
+// Defaults are:
+//   - fLowerFitLimit: 2
+//   - fUpperFitLimit: 5
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractPINDiode.h"
+
+#include <fstream>
+
+#include <TF1.h>
+#include <TH1.h>
+#include <TPad.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalPINDiode.h"
+
+ClassImp(MExtractPINDiode);
+
+using namespace std;
+
+const UInt_t MExtractPINDiode::fgPINDiodeIdx   =  3;
+const Byte_t MExtractPINDiode::fgHiGainFirst   =  0;
+const Byte_t MExtractPINDiode::fgHiGainLast    = 29;
+const Byte_t MExtractPINDiode::fgLoGainFirst   =  0;
+const Byte_t MExtractPINDiode::fgLoGainLast    =  0;
+const Byte_t MExtractPINDiode::fgLowerFitLimit =  2;
+const Byte_t MExtractPINDiode::fgUpperFitLimit =  5;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+// - Set fPINDiodeIdx   to fgPINDiodeIdx
+// - Set fLowerFitLimit to fgLowerFitLimit
+// - Set fUpperFitLimit to fgUpperFitLimit
+//
+MExtractPINDiode::MExtractPINDiode(const char *name, const char *title)
+    : fSlices(NULL)
+{
+
+  fName  = name  ? name  : "MExtractPINDiode";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+  SetPINDiodeIdx();
+
+  SetLowerFitLimit();
+  SetUpperFitLimit();  
+
+  fPedMean.Set(2);
+}
+
+// --------------------------------------------------------------------------
+//
+// - delete the histogram fSlices, if it exists
+//
+MExtractPINDiode::~MExtractPINDiode()
+{
+  if (fSlices)
+    delete fSlices;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the Hi Gain window is smaller than 4, set fHiGainLast to fHiGainFirst+3
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: 0.
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: 0.
+//  
+void MExtractPINDiode::SetRange(UShort_t hifirst, UShort_t hilast, Int_t lofirst, Byte_t lolast)
+{
+
+  lofirst = 0;
+  lolast  = 0;
+
+  const Byte_t window = hilast-hifirst+1;
+
+  if (window<4) 
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Total window is smaller than 4 FADC sampes, set last slice from" 
+                    ,(int)lolast," to ",(int)(lofirst+3)) << endl;
+      hilast = hifirst+3;
+    }
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst+1);
+  fNumLoGainSamples = 0.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = 0.;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls: 
+// - MExtractor::PreProcess
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MRawEvtData2
+//  - MExtractedPINDiode
+//
+// Initializes fPedMean to:
+// - fPedMean[0]: pedestal + AB-offset
+// - fPedMean[1]: pedestal - AB-offset
+//
+// Initializes TH1F fSlices to [fHiGainFirst-0.5,fHiGainLast+0.5]
+//
+Int_t MExtractPINDiode::PreProcess(MParList *pList)
+{
+
+  if (!MExtractor::PreProcess(pList))
+    return kFALSE;
+  
+  fRawEvt = NULL;
+  fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData2"));
+  if (!fRawEvt)
+    {
+      *fLog << err << AddSerialNumber("MRawEvtData2") << " not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  fPINDiode = (MExtractedSignalPINDiode*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalPINDiode"));
+  if (!fPINDiode)
+    return kFALSE;
+
+  fPedMean.Reset();
+/*
+  const MPedestalPix &ped   = (*fPedestals)[fPINDiodeIdx]; 
+
+  if (&ped)
+    {
+      fPedMean[0] = ped.GetPedestal() + ped.GetPedestalABoffset();
+      fPedMean[1] = ped.GetPedestal() - ped.GetPedestalABoffset();      
+    }
+  else
+    {
+      *fLog << err << " Cannot find MPedestalPix of the PIN Diode (idx=" 
+            << fPINDiodeIdx << ")" << endl;
+        return kFALSE;
+    }
+  */
+  if (fSlices)
+    delete fSlices;
+
+  fSlices = new TH1F("PINDiode","PIN Diode fitted slices",(Int_t)(fHiGainLast-fHiGainFirst+1),
+                     fHiGainFirst-0.5,fHiGainLast+0.5);
+  fSlices->SetDirectory(NULL);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fPINDiode->SetUsedFADCSlices(fHiGainFirst, fLoGainLast);
+//
+Bool_t MExtractPINDiode::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fPINDiode->SetUsedFADCSlices(fHiGainFirst, fLoGainLast);
+
+  *fLog << endl;
+  *fLog << inf << "Taking " << fNumHiGainSamples
+        << " HiGain samples from slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast/*+fHiLoLast*/) << " incl" << endl;
+
+  return kTRUE;
+}
+
+
+
+
+// ----------------------------------------------------------------------------------
+//
+// Extracts the (pedestal-subtracted) FADC slices between fHiGainFirst and fHiGainLast 
+// and fills them into the histogram fSlices. Memorizes the position of maximum at 
+// maxpos.
+//
+// Checks for saturation
+// 
+// Fits fSlices to a Gaussian in the ranges: maxpos-fLowerFitLimit, maxpos+fUpperFitLimit
+//
+// Writes fit results into MExtractedSignalPINDiode
+//
+Int_t MExtractPINDiode::Process()
+{
+
+/*
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  fPINDiode->Clear();
+  fSlices->Reset();
+
+  pixel.Jump(fPINDiodeIdx);
+
+  Byte_t sat  = 0;
+
+  const Int_t higainsamples = fRunHeader->GetNumSamplesHiGain();
+  const Int_t logainsamples = fRunHeader->GetNumSamplesLoGain();
+
+  const Bool_t higainabflag = pixel.HasABFlag();
+  Byte_t *ptr = pixel.GetHiGainSamples()+fHiGainFirst;
+  Byte_t *end = ptr+higainsamples;
+
+  Int_t cnt=0;
+
+  Float_t max = 0.;
+  Int_t maxpos = 0;
+
+  while (ptr<end)
+    {
+
+      if (*ptr >= fSaturationLimit)
+        {
+          sat++;
+          break;
+        }
+
+      const Float_t cont = (Float_t)*ptr - fPedMean[(cnt + higainabflag) & 0x1];
+      fSlices->Fill(cnt,cont);
+
+      if (cont > max)
+      {
+        max = cont;
+        maxpos = cnt;
+      }
+
+      ptr++;
+      cnt++;
+    }
+  
+  cnt = 0;
+  
+  if (logainsamples>0 && !sat)
+    {
+      
+      ptr = pixel.GetLoGainSamples();
+      end = ptr+logainsamples;
+      
+      const Bool_t logainabflag = (higainabflag + higainsamples) & 0x1;
+      
+      while (ptr<end)
+        {
+          
+          if (*ptr >= fSaturationLimit)
+            {
+              sat++;
+              break;
+            }
+
+          const Float_t cont = (Float_t)*ptr - fPedMean[(cnt + logainabflag) & 0x1];
+          
+          fSlices->Fill(cnt+ higainsamples,cont);
+          
+          if (cont > max) 
+            {
+              max    = cont;
+              maxpos = cnt+higainsamples;
+            }
+          ptr++;
+          cnt++;
+        }
+    }
+          
+  if (sat)
+    {
+      fPINDiode->SetSaturation(1);
+      return kTRUE;
+    }
+
+  fSlices->Fit("gaus", "Q0", "", maxpos-fLowerFitLimit,maxpos+fUpperFitLimit);
+
+  TF1 &gaus = *fSlices->GetFunction("gaus");
+
+  fPINDiode->SetExtractedSignal(gaus.GetParameter(0), gaus.GetParError(0));
+  fPINDiode->SetExtractedTime  (gaus.GetParameter(1), gaus.GetParError(1));
+  fPINDiode->SetExtractedSigma (gaus.GetParameter(2), gaus.GetParError(2));
+  fPINDiode->SetExtractedChi2  (gaus.GetChisquare());
+  fPINDiode->SetReadyToSave();
+  */
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//
+// deletes fSlices and sets pointer to NULL
+//
+Int_t MExtractPINDiode::PostProcess()
+{
+  
+  delete fSlices;
+  fSlices = NULL;
+  
+  return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractPINDiode.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractPINDiode.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractPINDiode.h	(revision 17960)
@@ -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_MExtractor
+#include "MExtractor.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class TH1F;
+class MExtractedSignalPINDiode;
+
+class MExtractPINDiode : public MExtractor
+{
+private:
+
+  static const UInt_t fgPINDiodeIdx;  
+  static const Byte_t fgHiGainFirst;     // First FADC slice Hi-Gain (now set to: 3) 
+  static const Byte_t fgHiGainLast;      // Last  FADC slice Hi-Gain (now set to: 14) 
+  static const Byte_t fgLoGainFirst;     // First FADC slice Lo-Gain (now set to: 3) 
+  static const Byte_t fgLoGainLast;      // Last  FADC slice Lo-Gain (now set to: 14) 
+
+  static const Byte_t fgLowerFitLimit;   // Default for fLowerFitLimit (now set to: 2)
+  static const Byte_t fgUpperFitLimit;   // Default for fUpperFitLimit (now set to: 5)
+
+  Byte_t fLowerFitLimit;                 // Number of FADC slices before maximum to start fit
+  Byte_t fUpperFitLimit;                 // Number of FADC slices after maximum to end fit
+  
+  MExtractedSignalPINDiode  *fPINDiode;  // Extracted signal of the PIN Diode
+  TH1F                      *fSlices;    // Histogram to fit the slices
+  
+  UInt_t  fPINDiodeIdx;                  // PIN Diode pixel ID
+  
+  MArrayF fPedMean;                      // The used pedestals (0: ped+AB, 1: ped-AB)
+  
+  Int_t  PreProcess( MParList *pList );
+  Bool_t ReInit    ( MParList *pList );  
+  Int_t  Process    ();
+  Int_t  PostProcess();
+  
+public:
+
+  MExtractPINDiode(const char *name=NULL, const char *title=NULL);
+  ~MExtractPINDiode();  
+
+  // Setters
+  void SetRange(UShort_t hifirst=0, UShort_t hilast=0, Int_t lofirst=0, Byte_t lolast=0);
+  void SetPINDiodeIdx  ( const UInt_t idx=fgPINDiodeIdx    ) { fPINDiodeIdx   = idx; }
+  void SetLowerFitLimit( const Byte_t lim=fgLowerFitLimit  ) { fLowerFitLimit = lim; }
+  void SetUpperFitLimit( const Byte_t lim=fgUpperFitLimit  ) { fUpperFitLimit = lim; }     
+
+  ClassDef(MExtractPINDiode, 1) // Signal Extractor for the PIN Diode
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractSignal.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignal.cc	(revision 17960)
@@ -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, 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(ostream &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: branches/Mars_McMismatchStudy/msignal/MExtractSignal.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignal.h	(revision 17960)
@@ -0,0 +1,63 @@
+#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(ostream &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: branches/Mars_McMismatchStudy/msignal/MExtractSignal2.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignal2.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignal2.cc	(revision 17960)
@@ -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, satlo);
+    } /* while (pixel.Next()) */
+
+
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractSignal2.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignal2.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignal2.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/msignal/MExtractSignal3.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignal3.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignal3.cc	(revision 17960)
@@ -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, 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: branches/Mars_McMismatchStudy/msignal/MExtractSignal3.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignal3.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignal3.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/msignal/MExtractSignalABcorr.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignalABcorr.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignalABcorr.cc	(revision 17960)
@@ -0,0 +1,248 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 09/2003 <mailto:markus@ifae.es>
+!              Thomas Bretz, 01/2004 
+!              Florian Goebel, 06/2004
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSignalABcorr
+//
+//   this class is basically a copy of MExtractSignal and is mainly ment as 
+//   an example of how to use the "AB pedestal offset" to correct for the 
+//   150 MHz clock noise. It allows to extract a signal using an odd number 
+//   of slices 
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractSignalABcorr.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractSignalABcorr);
+
+using namespace std;
+
+const Byte_t MExtractSignalABcorr::fgSaturationLimit = 254;
+const Byte_t MExtractSignalABcorr::fgFirst =  3;
+const Byte_t MExtractSignalABcorr::fgLast  = 14;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MExtractSignalABcorr::MExtractSignalABcorr(const char *name, const char *title)
+    : fSaturationLimit(fgSaturationLimit)
+{
+
+    fName  = name  ? name  : "MExtractSignalABcorr";
+    fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+    AddToBranchList("MRawEvtData.*");
+
+    SetRange();
+}
+
+void MExtractSignalABcorr::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+    fNumHiGainSamples = hilast-hifirst+1;
+    fNumLoGainSamples = lolast-lofirst+1;
+
+    fHiGainFirst = hifirst;
+    fLoGainFirst = lofirst;
+
+    fSqrtHiGainSamples = TMath::Sqrt((Float_t)fNumHiGainSamples);
+    fSqrtLoGainSamples = TMath::Sqrt((Float_t)fNumLoGainSamples);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MExtractSignalABcorr::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalCam"));
+    if (!fSignals)
+        return kFALSE;
+
+    fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainFirst+fNumHiGainSamples-1, (Float_t)fNumHiGainSamples,
+                                fLoGainFirst, fLoGainFirst+fNumLoGainSamples-1, (Float_t)fNumLoGainSamples);
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void MExtractSignalABcorr::FindSignal(Byte_t *ptr, Int_t size, Int_t &sum, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + size;
+  
+  sum = 0;
+  sat = 0;
+  
+  while (ptr<end)
+    {
+      sum += *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container.
+//
+Int_t MExtractSignalABcorr::Process()
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+    fSignals->Clear();
+
+    UInt_t  sat=0;
+
+    const Bool_t ApplyABcorrHi = fNumHiGainSamples&0x1;
+    const Bool_t ApplyABcorrLo = fNumLoGainSamples&0x1;
+
+    while (pixel.Next())
+    {
+        Int_t sumhi;
+        Byte_t sathi;
+
+        FindSignal(pixel.GetHiGainSamples()+fHiGainFirst, fNumHiGainSamples, sumhi, sathi);
+
+        Int_t  sumlo = 0;
+        Byte_t satlo = 0;
+        if (pixel.HasLoGain())
+        {
+            FindSignal(pixel.GetLoGainSamples()+fLoGainFirst, fNumLoGainSamples, sumlo, satlo);
+
+            if (satlo)
+              sat++;
+        }
+
+        const Int_t pixid   = pixel.GetPixelId();
+	const Bool_t ABFlag = pixel.HasABFlag();
+
+        const MPedestalPix  &ped = (*fPedestals)[pixid]; 
+	MExtractedSignalPix &pix = (*fSignals)[pixid];
+
+        const Float_t pedes  = ped.GetPedestal();
+        const Float_t pedrms = ped.GetPedestalRms();
+	const Float_t ABoffs = ped.GetPedestalABoffset();
+
+	Float_t pedtothi = pedes*fNumHiGainSamples;
+	Float_t pedtotlo = pedes*fNumLoGainSamples;
+
+	if (ApplyABcorrHi) {
+	  pedtothi += ABoffs*(1-2*((fHiGainFirst+ABFlag)&0x1));
+	}
+	if (ApplyABcorrLo) {
+	  pedtotlo += ABoffs*(1-2*((fLoGainFirst+ABFlag)&0x1));
+	}
+
+        pix.SetExtractedSignal(sumhi - pedtothi, pedrms*fSqrtHiGainSamples,
+                               sumlo - pedtotlo, pedrms*fSqrtLoGainSamples);
+
+	pix.SetGainSaturation(sathi, satlo);
+
+    } /* while (pixel.Next()) */
+
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MExtractSignalABcorr::StreamPrimitive(ostream &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: branches/Mars_McMismatchStudy/msignal/MExtractSignalABcorr.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSignalABcorr.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSignalABcorr.h	(revision 17960)
@@ -0,0 +1,63 @@
+#ifndef MARS_MExtractSignalABcorr
+#define MARS_MExtractSignalABcorr
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractSignalABcorr                                                          //
+//                                                                         //
+// Integrates the time slices of the all pixels of a calibration event     //
+// and substract the pedestal value                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+
+class MExtractSignalABcorr : public MTask
+{
+private:
+    static const Byte_t fgSaturationLimit;
+    static const Byte_t fgFirst;
+    static const Byte_t fgLast;
+
+    MPedestalCam        *fPedestals;    // Pedestals of all pixels in the camera
+    MExtractedSignalCam *fSignals;      // Extracted signal of all pixels in the camera
+
+    MRawEvtData         *fRawEvt;       // raw event data (time slices)
+    MRawRunHeader       *fRunHeader;    // RunHeader information
+
+    Byte_t  fHiGainFirst;
+    Byte_t  fLoGainFirst;
+
+    Byte_t  fNumHiGainSamples;
+    Byte_t  fNumLoGainSamples;
+
+    Float_t fSqrtHiGainSamples;
+    Float_t fSqrtLoGainSamples;
+
+    Byte_t  fSaturationLimit;
+
+    void   FindSignal(Byte_t *ptr, Int_t size, Int_t &sum, Byte_t &sat) const;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+    void   StreamPrimitive(ostream &out) const;
+
+public:
+    MExtractSignalABcorr(const char *name=NULL, const char *title=NULL);
+
+    void SetRange(Byte_t hifirst=fgFirst, Byte_t hilast=fgLast, Byte_t lofirst=fgFirst, Byte_t lolast=fgLast);
+    void SetSaturationLimit(Byte_t lim) { fSaturationLimit = lim; }
+
+    ClassDef(MExtractSignalABcorr, 0) // Task to fill the Extracted Signal Containers from raw data
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractSlidingWindow.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSlidingWindow.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSlidingWindow.cc	(revision 17960)
@@ -0,0 +1,344 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 01/2004 <mailto:hbartko@mppmu.mpg.de>
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSlidingWindow
+//
+//  Extracts the signal from a sliding window of size fHiGainWindowSize and 
+//  fLoGainWindowSize. The signal is the one which maximizes the integral 
+//  contents. 
+//
+//  Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//  to modify the ranges in which the window is allowed to move. 
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindowSize(windowhigain, windowlogain) 
+//  to modify the sliding window widths. Windows have to be an even number. 
+//  In case of odd numbers, the window will be modified.
+//
+//  Defaults are:
+//
+//   fHiGainWindowSize = fgHiGainWindowSize = 6
+//   fLoGainWindowSize = fgLoGainWindowSize = 6
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractSlidingWindow.h"
+#include "MExtractor.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MExtractedSignalCam.h"
+
+ClassImp(MExtractSlidingWindow);
+
+using namespace std;
+
+const Byte_t MExtractSlidingWindow::fgHiGainFirst      = 0;
+const Byte_t MExtractSlidingWindow::fgHiGainLast       = 14;
+const Byte_t MExtractSlidingWindow::fgLoGainFirst      = 3;
+const Byte_t MExtractSlidingWindow::fgLoGainLast       = 14;
+const Byte_t MExtractSlidingWindow::fgHiGainWindowSize = 6;
+const Byte_t MExtractSlidingWindow::fgLoGainWindowSize = 6;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fWindowSizeHiGain to fgHiGainWindowSize
+// - fWindowSizeLoGain to fgLoGainWindowSize
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractSlidingWindow::MExtractSlidingWindow(const char *name, const char *title)
+    : fWindowSizeHiGain(fgHiGainWindowSize), 
+      fWindowSizeLoGain(fgLoGainWindowSize)
+{
+
+  fName  = name  ? name  : "MExtractSlidingWindow";
+  fTitle = title ? title : "Signal Extractor for a sliding FADC window";
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
+//
+void MExtractSlidingWindow::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  //
+  // Redo the checks if the window is still inside the ranges
+  //
+
+  SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+//
+Bool_t MExtractSlidingWindow::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+
+  *fLog << dec << endl;
+  *fLog << inf << "Taking " << fNumHiGainSamples
+        << " HiGain samples starting with slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast+fHiLoLast) << " incl" << endl;
+  *fLog << inf << "Taking " << fNumLoGainSamples
+        << " LoGain samples starting with slice " << (Int_t)fLoGainFirst
+        << " to " << (Int_t)fLoGainLast << " incl" << endl;
+
+  return kTRUE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd, subtract one
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fWindowSizeHiGain
+// - fNumLoGainSamples to: (Float_t)fWindowSizeLoGain
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractSlidingWindow::SetWindowSize(Byte_t windowh, Byte_t windowl)
+{
+  
+  fWindowSizeHiGain = windowh & ~1;
+  fWindowSizeLoGain = windowl & ~1;
+
+  if (fWindowSizeHiGain != windowh)
+    *fLog << warn << GetDescriptor() << ": Hi Gain window size has to be even, set to: " 
+          << int(fWindowSizeHiGain) << " samples " << endl;
+  
+  if (fWindowSizeLoGain != windowl)
+    *fLog << warn << GetDescriptor() << ": Lo Gain window size has to be even, set to: " 
+          << int(fWindowSizeLoGain) << " samples " << endl;
+    
+  const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
+
+  if (fWindowSizeHiGain > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fWindowSizeHiGain,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fWindowSizeHiGain = availhirange;
+    }
+  
+  if (fWindowSizeHiGain<2) 
+    {
+      fWindowSizeHiGain = 2;
+      *fLog << warn << GetDescriptor() << ": Hi Gain window size set to two samples" << endl;
+    }
+  
+  if (fLoGainLast != 0 && fWindowSizeLoGain != 0)
+    {
+      const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
+      
+      if (fWindowSizeLoGain > availlorange)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fWindowSizeLoGain,
+                        " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+          *fLog << warn << GetDescriptor() 
+                << ": Will set window size to: " << (int)availlorange << endl;
+          fWindowSizeLoGain = availlorange;
+        }
+      
+      if (fWindowSizeLoGain<2) 
+        {
+          fWindowSizeLoGain = 2;
+          *fLog << warn << GetDescriptor() << ": Lo Gain window size set to two samples" << endl;
+        }
+    }
+  
+  fNumHiGainSamples = (Float_t)fWindowSizeHiGain;
+  fNumLoGainSamples = (Float_t)fWindowSizeLoGain;
+  
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fWindowSizeHiGain)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - Loop from (ptr+fWindowSizeHiGain) to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum the content of *(ptr+fWindowSizeHiGain) and subtract *ptr
+// - Check if the sum has become bigger and store it in case yes.
+// 
+void MExtractSlidingWindow::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &max, Byte_t &sat) const
+{
+    const Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+    Int_t sum=0;
+    Int_t sumtot =0;
+
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    sat = 0;
+    Byte_t *p = ptr;
+    
+    while (p<ptr+fWindowSizeHiGain-fHiLoLast)
+    {
+        sum += *p;
+        if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+    //
+    // Check for saturation in all other slices
+    //
+    while (p<end)
+        if (*p++ >= fSaturationLimit)
+            sat++;
+
+    //
+    // If part of the "low-Gain" slices are used, 
+    // repeat steps one and two for the logain part until fHiLoLast
+    //
+    Byte_t *l = logain;
+    while (l<logain+fHiLoLast)
+      {
+        sum += *l;
+        if (*l++ >= fSaturationLimit)
+            sat++;
+      }
+
+
+    //
+    // Calculate the i-th sum as
+    //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+    // This is fast and accurate (because we are using int's)
+    //
+    sumtot=sum;
+    for (p=ptr; p+fWindowSizeHiGain-fHiLoLast<end; p++)
+    {
+        sum += *(p+fWindowSizeHiGain-fHiLoLast) - *p;
+        if (sum>sumtot)
+            sumtot = sum;
+    }
+
+    for (l=logain; l<logain+fHiLoLast; l++)
+    {
+        sum += *l - *p++;
+        if (sum>sumtot)
+            sumtot = sum;
+    }
+    max = (Float_t)sumtot;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fWindowSizeLoGain)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - Loop from (ptr+fWindowSizeLoGain) to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum the content of *(ptr+fWindowSizeLoGain) and subtract *ptr
+// - Check if the sum has become bigger and store it in case yes.
+// 
+void MExtractSlidingWindow::FindSignalLoGain(Byte_t *ptr, Float_t &max, Byte_t &sat) const
+{
+    const Byte_t *end = ptr + fLoGainLast - fLoGainFirst + 1;
+
+    Int_t sum=0;
+    Int_t sumtot=0;
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    sat = 0;
+    Byte_t *p = ptr;
+    while (p<ptr+fWindowSizeLoGain)
+    {
+        sum += *p;
+        if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+    //
+    // Check for saturation in all other slices
+    //
+    while (p<end)
+        if (*p++ >= fSaturationLimit)
+            sat++;
+
+    //
+    // Calculate the i-th sum as
+    //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+    // This is fast and accurate (because we are using int's)
+    //
+    sumtot=sum;
+    for (p=ptr; p+fWindowSizeLoGain<end; p++)
+    {
+        sum += *(p+fWindowSizeLoGain) - *p;
+        if (sum>sumtot)
+            sumtot = sum;
+    }
+    max = (Float_t)sumtot;
+}
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractSlidingWindow.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractSlidingWindow.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractSlidingWindow.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MExtractSlidingWindow
+#define MARS_MExtractSlidingWindow
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractSlidingWindow : public MExtractor
+{
+private:
+  
+  static const Byte_t fgHiGainFirst;      // First FADC slice Hi-Gain (currently set to: 3) 
+  static const Byte_t fgHiGainLast;       // Last FADC slice Hi-Gain (currently set to: 14) 
+  static const Byte_t fgLoGainFirst;      // First FADC slice Lo-Gain (currently set to: 3) 
+  static const Byte_t fgLoGainLast;       // Last FADC slice Lo-Gain (currently set to: 14) 
+  static const Byte_t fgHiGainWindowSize; // The extraction window Hi-Gain
+  static const Byte_t fgLoGainWindowSize; // The extraction window Lo-Gain
+
+  Byte_t  fWindowSizeHiGain;             // Number of Hi Gain slices in window
+  Byte_t  fWindowSizeLoGain;             // Number of Lo Gain slices in window  
+  
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &max, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &max, Byte_t &sat) const;  
+
+  Bool_t  ReInit(MParList *pList);
+  
+public:
+  MExtractSlidingWindow(const char *name=NULL, const char *title=NULL);
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+  void SetWindowSize(Byte_t windowh=fgHiGainWindowSize,
+                     Byte_t windowl=fgLoGainWindowSize);
+
+  ClassDef(MExtractSlidingWindow, 1) // Signal Extractor for sliding extraction window
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTime.cc	(revision 17960)
@@ -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): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz, 04/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTime
+//
+//   Base class for the signal extractors, used the functions 
+//   FindTimeHiGain() and FindTimeLoGain() to extract the signal and 
+//   substract the pedestal value    
+//
+//   The following figure gives and example of possible inheritance trees. 
+//   An extractor class can inherit from each of the following base classes:
+//    - MExtractor
+//    - MExtractTime
+//    - MExtractTimeAndCharge
+//
+//Begin_Html
+/*
+<img src="images/ExtractorClasses.gif">
+*/
+//End_Html
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MArrivalTimeCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTime.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MRawRunHeader.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+ClassImp(MExtractTime);
+
+using namespace std;
+
+const char *MExtractTime::fgNameTimeCam = "MArrivalTimeCam";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set: 
+// - all pointers to NULL
+// - all variables to 0
+// - fSaturationLimit to fgSaturationLimit
+// - fNameTimeCam to fgNameTimeCam
+//
+// Call:
+// -  AddToBranchList("MRawEvtData.*")
+//
+MExtractTime::MExtractTime(const char *name, const char *title)
+  : fArrTime(NULL)
+{
+
+  fName  = name  ? name  : "MExtractTime";
+  fTitle = title ? title : "Base class for signal extractors";
+  
+  SetNameTimeCam();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MArrivalTimeCam
+//
+Int_t MExtractTime::PreProcess(MParList *pList)
+{
+  fArrTime = (MArrivalTimeCam*)pList->FindCreateObj("MArrivalTimeCam",AddSerialNumber(fNameTimeCam));
+  if (!fArrTime)
+      return kFALSE;
+
+  return PreProcessStd(pList);
+}
+
+
+void MExtractTime::Print(Option_t *o) const
+{
+    MExtractor::Print(o);
+    if (HasLoGain())
+        *fLog << " Offset Lo-Gain:     " << fOffsetLoGain << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractTime.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTime.h	(revision 17960)
@@ -0,0 +1,40 @@
+#ifndef MARS_MExtractTime
+#define MARS_MExtractTime
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MPedestalPix;
+class MArrivalTimeCam;
+
+class MExtractTime : public MExtractor
+{
+protected:
+  
+  static const char *fgNameTimeCam;   //! "MArrivalTimeCam"
+  TString  fNameTimeCam;              // Name of the 'MArrivalTimeCam' container
+  
+  MArrivalTimeCam *fArrTime;          //! Container with the photons arrival times
+/*
+  virtual void FindTimeHiGain(Byte_t *firstused, Float_t &time, Float_t &dtime,
+                              Byte_t &sat, const MPedestalPix &ped) const {}
+  virtual void FindTimeLoGain(Byte_t *firstused, Float_t &time, Float_t &dtime,
+                              Byte_t &sat, const MPedestalPix &ped) const {}
+  */
+  Int_t  PreProcess( MParList *pList );
+//  Bool_t ReInit    ( MParList *pList );
+//  Int_t  Process   ();
+
+public:
+
+  MExtractTime(const char *name=NULL, const char *title=NULL);
+
+  void Print(Option_t *o) const; //*MENU*
+
+  void SetNameTimeCam(const char *name=fgNameTimeCam) { fNameTimeCam = name; }
+  
+  ClassDef(MExtractTime, 3)   // Arrival Time Extractor Base Class
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndCharge.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndCharge.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndCharge.cc	(revision 17960)
@@ -0,0 +1,461 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 05/2004 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz, 05/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndCharge
+//
+//   Base class for the signal extractors which extract the arrival time 
+//   and the signal at the same time. Uses the functions 
+//   FindTimeAndChargeHiGain() and FindTimeAndChargeLoGain() to extract
+//   the signal.
+//
+//   The following figure gives and example of possible inheritance trees. 
+//   An extractor class can inherit from each of the following base classes:
+//    - MExtractor
+//    - MExtractTime
+//    - MExtractTimeAndCharge
+//
+//Begin_Html
+/*
+<img src="images/ExtractorClasses.gif">
+*/
+//End_Html
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+//
+// Class Version 3:
+// ----------------
+//   - Byte_t fMaxBinContent;
+//
+// Class Version 4:
+// ----------------
+//   - Byte_t fLoGainSwitch
+//   + UInt_t fLoGainSwitch
+//
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MArrivalTimeCam
+//   MExtractedSignalCam
+//
+// For weired events check: Run 94127 Event 672, 1028
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndCharge.h"
+
+#include <TRandom.h>
+#include <TVector3.h>
+
+#include "MMath.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MExtractTimeAndCharge);
+
+using namespace std;
+
+const Float_t MExtractTimeAndCharge::fgLoGainStartShift = -1.0;  // was -2.5
+const UInt_t  MExtractTimeAndCharge::fgLoGainSwitch     =  120;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets: 
+// - fWindowSizeHiGain and fWindowSizeLoGain to 0
+// - fLoGainStartShift to fgLoGainStartShift
+// - fLoGainSwitch     to fgLoGainSwitch
+//
+MExtractTimeAndCharge::MExtractTimeAndCharge(const char *name, const char *title)
+    : fWindowSizeHiGain(0), fWindowSizeLoGain(0)
+{
+    fName  = name  ? name  : "MExtractTimeAndCharge";
+    fTitle = title ? title : "Base class for signal and time extractors";
+
+    SetLoGainStartShift();
+    SetLoGainSwitch();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//  - MArrivalTimeCam    
+//
+Int_t MExtractTimeAndCharge::PreProcess(MParList *pList)
+{
+    if (!MExtractTime::PreProcess(pList))
+        return kFALSE;
+
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj("MExtractedSignalCam",AddSerialNumber(fNameSignalCam));
+    if (!fSignals)
+        return kFALSE;
+
+    *fLog << flush << inf;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+//
+// Call: 
+// - MArrivalTimeCam::SetUsedFADCSlices(fHiGainFirst, fHiGainLast, fNumHiGainSamples,
+//                                      fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+// - InitArrays();
+//
+Bool_t MExtractTimeAndCharge::ReInit(MParList *pList)
+{
+    if (!MExtractTime::ReInit(pList))
+        return kFALSE;
+
+    if (!InitArrays(fRunHeader->GetNumSamplesHiGain()+fRunHeader->GetNumSamplesLoGain()))
+        return kFALSE;
+
+    if (fSignals)
+        fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast, fNumHiGainSamples,
+                                    fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+    if (!HasLoGain())
+    {
+        *fLog << inf << "No lo-gains... resetting lo-gain switch." << endl;
+        fLoGainSwitch=0xff;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the x-value lower than sat0 at which the signal has been
+// fallen bwlow maxcont/2. This time is determined using a simple second
+// order polynomial interpolation.
+//
+Double_t MExtractTimeAndCharge::GetSaturationTime(Int_t sat0, const Float_t *sig, Int_t maxconthalf) const
+{
+    const Int_t p = sat0>1 ? sat0-2 : sat0-1;
+    if (sat0<=0)
+        return 0;
+
+    if (sat0==1)
+        return sig[0]>maxconthalf ? 0 : 0.5;
+
+    if (sig[p]>sig[p+1] || sig[p+1]>sig[p+2])
+        return sig[p+1]>maxconthalf ? sat0-1 : sat0-0.5;
+
+    // Find the place at which the signal is maxcont/2
+    const TVector3 vx(sig[p], sig[p+1], sig[p+2]);
+    const TVector3 vy(p, p+1, p+2);
+
+    return MMath::InterpolParabLin(vx, vy, maxconthalf);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MArrivalTimeCam container.
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container. 
+// The functions FindTimeAndChargeHiGain() and FindTimeAndChargeLoGain() are 
+// supposed to extract the signal themselves.
+//
+Int_t MExtractTimeAndCharge::Process()
+{
+    const Int_t nums = fSignal->GetNumSamples();
+
+    const Int_t numh = fRunHeader->GetNumSamplesHiGain();
+    const Int_t numl = fRunHeader->GetNumSamplesLoGain();
+
+    // Some sanity checks to get rid of some weird behaviour of the simulation
+    if (nums!=numh+numl)
+    {
+        *fLog << err << "MExtractTimeAndCharge::Process: ERROR - Number of samples in event ";
+        *fLog << "(" << nums << ")" << endl << " doesn't match number in run-header ";
+        *fLog << "(" << numh+numl << ")" << endl;
+        *fLog << " In case you are processing real data you have just found a bug." << endl;
+        *fLog << " If you process Monte Carlo data, it means probably that the length" << endl;
+        *fLog << " of the arrays in MRawEvtData are inconsistent with the run-header." << endl;
+        return kERROR;
+    }
+
+    // Start extraction
+    const UInt_t satlim = fSaturationLimit*fRunHeader->GetScale();
+
+    // Do not even try to extract the hi-gain if we have
+    // more than one saturating slice
+    const Int_t rangehi = fHiGainLast - fHiGainFirst + 1;
+
+    MRawEvtPixelIter pixel(fRawEvt);
+    while (pixel.Next())
+    {
+        const Int_t pixidx = pixel.GetPixelId();
+
+        const Float_t *sig = fSignal->GetSamples(pixidx);
+
+        // Would it be better to take lastsat-firstsat?
+        Int_t sathi0   = fHiGainFirst;  // First slice to extract and first saturating slice
+        Int_t sathi1   = fHiGainLast;   // Last  slice to extract and last saturating slice
+        Int_t numsathi = fSignal->GetSaturation(pixidx, satlim, sathi0, sathi1);
+
+        Float_t sumhi =0., deltasumhi =-1; // Set hi-gain of MExtractedSignalPix valid
+        Float_t timehi=0., deltatimehi=-1; // Set hi-gain of MArrivalTimePix valid
+
+        if (numsathi<2)
+        {
+            const Int_t maxposhi = fSignal->GetMaxPos(pixidx, fHiGainFirst, fHiGainLast);
+            FindTimeAndChargeHiGain2(sig+fHiGainFirst, rangehi,
+                                     sumhi, deltasumhi, timehi, deltatimehi,
+                                     numsathi, maxposhi);
+        }
+
+        // If we have saturating slices try to get a better estimate
+        // of the arrival time than timehi or sathi0. This is
+        // usefull to know where to start lo-gain extraction.
+        const UInt_t maxcont = fSignal->GetRawMaxVal(pixidx, fHiGainFirst, fHiGainLast);
+        if (numsathi>1)
+        {
+            timehi = GetSaturationTime(sathi0, sig, maxcont/2)-fHiGainFirst;
+            deltatimehi = 0;
+        }
+
+        // Make sure that in cases the time couldn't be correctly determined
+        // more meaningfull default values are assigned.
+        // For extractors like the digital filter and the spline
+        // we allow extracpolation by one slice.
+        // FIXME: Defined Out-Of-Range better so that the extractors
+        //        know what to return!
+        // e.g. timehi=-2 in sline extractor means: leading edge not found not found
+        if (deltatimehi>-0.5 && (timehi<-1 || timehi>=rangehi))
+        {
+            // Flag this as unreliable!
+            timehi = gRandom->Uniform(rangehi);
+            // deltatimehi=-1; // Set PIXEL to UNRELIABLE?
+        }
+
+        timehi += fHiGainFirst;
+
+        Float_t sumlo =0, deltasumlo =-1;  // invalidate logain of MExtractedSignalPix
+        Float_t timelo=0, deltatimelo=-1;  // invalidate logain of MArrivalTimePix
+        Int_t numsatlo=0;
+
+        //
+        // Adapt the low-gain extraction range from the obtained high-gain time
+        //
+
+        // IN THIS CASE THE PIXEL SHOULD BE MARKED BAD!!!!
+        // MEANS: Hi gain has saturated, but the signal is to dim
+        // to extract the lo-gain properly
+        // This could happen because the maxcont was not extracted from
+        // all slices!
+        // THIS produces pulse positions ~= -1
+        // The signal might be handled in MCalibrateData, but hwat's about
+        // the arrival times in MCalibrateRelTime
+        if (numsathi>0 && maxcont<=fLoGainSwitch)
+            deltasumlo=deltasumhi=deltatimelo=deltatimehi=-1;
+
+        // If more than 8 hi-gain slices have saturated this is
+        // no physical event. We just assume that something with
+        // the extraction is wrong
+        if (numsathi>8) // FIXME: Should be something like 2?
+            deltasumhi=deltatimehi=-1;
+
+        // FIXME: What to do with the pixel if it saturates too early???
+        if (numl>0 && maxcont>fLoGainSwitch)
+        {
+            Int_t first = numh+fLoGainFirst;
+            Int_t last  = numh+fLoGainLast;
+
+            // To determin the window in which the lo-gain is extracted
+            // clearly more information about the relation between the
+            // extraction window and the reslting time is necessary.
+            //
+            // numh + fLoGainStartShift == 14 / fLoGainStartShift=-1
+            //
+            // The lo-gain is expected to have its raising edge
+            // at timehi+numh+fOffsetLoGain. We start to search for the
+            // lo-gain fLoGainStartShift slices earlier.
+            //
+            // Instead of fLoGainStartShift the extractor should now how many
+            // slices before the expected raising edge the start of the
+            // search must be placed and from there we can step 1.5 slices
+            // back to be on the safe side.
+            //
+            // The jitter in the hi-/lo-gain offset ssems to be around +/-0.5
+            const Float_t tm = deltatimehi<0 ? -1.+fHiGainFirst : timehi;
+            first = TMath::FloorNint(tm+numh+fOffsetLoGain+fLoGainStartShift);
+
+            if (first<0)
+                first = 0;
+            if (first>last)
+                first=last;
+
+            /*
+            // Currently we have to stick to this check because at least
+            // the spline has arrays of this size...
+            if (first>last)
+                first = last;
+            if (first<numh+fLoGainFirst)
+                first = numh+fLoGainFirst;
+             */
+            // Would it be better to take lastsat-firstsat?
+            Int_t satlo0 = first;   // First slice to extract and first saturating slice
+            Int_t satlo1 = last;    // Last  slice to extract and last saturating slice
+            numsatlo = fSignal->GetSaturation(pixidx, satlim, satlo0, satlo1);
+
+            //if (satlo0>first && satlo1<last && numsatlo>2)
+            //{
+            //    fSignal->InterpolateSaturation(pixidx, fSaturationLimit, satlo0, satlo1);
+            //    numsatlo = 0;
+            //}
+
+            const Int_t rangelo  = last-first+1;
+            const Int_t maxposlo = fSignal->GetMaxPos(pixidx, first, last);
+            FindTimeAndChargeLoGain2(sig+first, rangelo,
+                                     sumlo, deltasumlo, timelo, deltatimelo,
+                                     numsatlo, maxposlo);
+
+            // If we have saturating slices try to get a better estimate
+            // of the arrival time than timehi or sathi0. This is
+            // usefull to know where to start lo-gain extraction.
+            if (numsatlo>1)
+            {
+                const UInt_t maxcontlo = fSignal->GetRawMaxVal(pixidx, fHiGainFirst, fHiGainLast);
+                timelo = GetSaturationTime(satlo0, sig, maxcontlo/2)-numh-first;
+                deltatimelo = 0;
+            }
+
+            // Make sure that in cases the time couldn't be correctly determined
+            // more meaningfull default values are assigned
+            // For extractors like the digital filter and the spline
+            // we allow extracpolation by one slice.
+            if (deltatimelo>-0.5 && (timelo<-1 || timelo>=rangelo))
+            {
+                // Flag this as unreliable!
+                timelo = gRandom->Uniform(rangelo);
+                //deltatimelo=-1; // Set PIXEL to UNRELIABLE?
+            }
+
+            timelo += first-numh;
+
+            // If more than 6 lo-gain slices have saturated this is
+            // no physical event. We just assume that something with
+            // the extraction is wrong
+            if (numsatlo>6)
+                deltasumlo=deltatimelo=-1;
+
+            // The extracted lo-gain signal cannot be zero or
+            // negative at all, so it must be wrong
+            if (sumlo<=0)
+                deltasumlo=-1;
+
+            //if (TMath::Abs(timelo-fOffsetLoGain - timehi)>1.0)
+            //    deltatimelo = -1;
+        }
+
+        // Now store the result in the corresponding containers
+        MExtractedSignalPix &pix = (*fSignals)[pixidx];
+        MArrivalTimePix     &tix = (*fArrTime)[pixidx];
+        pix.SetExtractedSignal(sumhi, deltasumhi, sumlo, deltasumlo);
+        pix.SetGainSaturation(numsathi, numsatlo);
+
+        tix.SetArrivalTime(timehi, deltatimehi, timelo-fOffsetLoGain, deltatimelo);
+        tix.SetGainSaturation(numsathi, numsatlo);
+    } /* while (pixel.Next()) */
+
+    fArrTime->SetReadyToSave();
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.LoGainStartShift: -2.8
+//
+Int_t MExtractTimeAndCharge::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = MExtractTime::ReadEnv(env, prefix, print);
+
+    if (IsEnvDefined(env, prefix, "LoGainStartShift", print))
+    {
+        fLoGainStartShift = GetEnvValue(env, prefix, "LoGainStartShift", fgLoGainStartShift);
+	SetLoGainStartShift(fLoGainStartShift);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "LoGainSwitch", print))
+    {
+        fLoGainSwitch = GetEnvValue(env, prefix, "LoGainSwitch", (Int_t)fLoGainSwitch);
+        rc = kTRUE;
+    }
+
+    return rc;
+}
+
+void MExtractTimeAndCharge::Print(Option_t *o) const
+{
+    MExtractTime::Print(o);
+
+    if (HasLoGain())
+    {
+        *fLog << dec;
+        *fLog << " LoGainStartShift:   " << fLoGainStartShift << endl;
+        *fLog << " LoGainSwitch:       " << fLoGainSwitch << endl;
+    }
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndCharge.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndCharge.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndCharge.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MExtractTimeAndCharge
+#define MARS_MExtractTimeAndCharge
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MPedestalPix;
+
+class MExtractTimeAndCharge : public MExtractTime
+{
+private:
+  static const Float_t fgLoGainStartShift; //! Default for fLoGainStartShift (now set to: -2.8)
+  static const UInt_t  fgLoGainSwitch;     //! Default for fLoGainSwitch     (now set to: 100)
+  
+  Float_t fLoGainStartShift;      // Shift to start searching the low-gain signal obtained from the high-gain times.
+  UInt_t  fLoGainSwitch;          // Limit for max. bin content before the low-gain gets extracted
+
+protected:
+  Int_t  fWindowSizeHiGain;       //  Window Size High-Gain
+  Int_t  fWindowSizeLoGain;       //  Window Size Low-Gain
+
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+  Double_t GetSaturationTime(Int_t sat0, const Float_t *sig, Int_t maxcont) const;
+
+public:
+  MExtractTimeAndCharge(const char *name=NULL, const char *title=NULL);
+  
+  Int_t   GetWindowSizeHiGain  () const { return fWindowSizeHiGain; }
+  Int_t   GetWindowSizeLoGain  () const { return fWindowSizeLoGain; }
+  Float_t GetLoGainStartShift  () const { return fLoGainStartShift; }
+  UInt_t  GetLoGainSwitch      () const { return fLoGainSwitch;     }
+
+  void SetLoGainStartShift( const Float_t f=fgLoGainStartShift ) { fLoGainStartShift = f;  }
+  void SetLoGainSwitch    ( const UInt_t  i=fgLoGainSwitch     ) { fLoGainSwitch     = i; }
+
+  virtual void SetWindowSize(Int_t windowh, Int_t windowl) { fWindowSizeHiGain = windowh; fWindowSizeLoGain = windowl;  }
+
+  virtual Bool_t InitArrays(Int_t) { return kTRUE; }
+
+  virtual void FindTimeAndChargeHiGain2(const Float_t */*firstused*/, Int_t /*num*/, Float_t &/*sum*/, Float_t &/*dsum*/,
+                                       Float_t &/*time*/, Float_t &/*dtime*/,
+                                       Byte_t /*sat*/, Int_t /*maxpos*/) const { }
+
+  virtual void FindTimeAndChargeLoGain2(const Float_t */*firstused*/, Int_t /*num*/, Float_t &/*sum*/, Float_t &/*dsum*/,
+                                       Float_t &/*time*/, Float_t &/*dtime*/,
+                                       Byte_t /*sat*/, Int_t /*maxpos*/) const { }
+  
+  // For MExtractPedestal
+  Bool_t ReInit(MParList *pList);
+
+  // TObject
+  void Print(Option_t *o="") const; //*MENU*
+
+  ClassDef(MExtractTimeAndCharge, 4)   // Time And Charge Extractor Base Class
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilter.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilter.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilter.cc	(revision 17960)
@@ -0,0 +1,721 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko, 09/2004 <mailto:hbartko@mppmu.mpg.de> 
+!   Author(s): Markus Gaug, 05/2004 <mailto:markus@ifae.es>
+!   Author(s): Diego Tescaro, 05/2004 <mailto:tescaro@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeDigitalFilter
+//
+//   Hendrik has promised to write more documentation
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+// The reading of automatic weights files (color, type) can be switched
+// off using EnableAutomaticWeights(kFALSE).
+//
+// An empty name or "-" as the weights file name is a synonym for
+// setting all weights to 1
+//
+// The digital filter can even do a little extrapolation around the
+// extraction window. For real Pulses having their maximum around
+// slice 0 the extracted time is similar to a gaussian around 0 with
+// sigma 0.4.
+//
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//   [MCalibrationPattern]
+//
+// Output Containers:
+//   MArrivalTimeCam
+//   MExtractedSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeDigitalFilter.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+#include "MCalibrationPattern.h"
+#include "MExtractedSignalCam.h"
+#include "MExtralgoDigitalFilter.h"
+
+ClassImp(MExtractTimeAndChargeDigitalFilter);
+
+using namespace std;
+
+const Byte_t  MExtractTimeAndChargeDigitalFilter::fgHiGainFirst             =  0;
+const Byte_t  MExtractTimeAndChargeDigitalFilter::fgHiGainLast              = 16;
+const Int_t   MExtractTimeAndChargeDigitalFilter::fgLoGainFirst             =  1;
+const Byte_t  MExtractTimeAndChargeDigitalFilter::fgLoGainLast              = 14;
+const Int_t   MExtractTimeAndChargeDigitalFilter::fgBinningResolutionHiGain = 10;
+const Int_t   MExtractTimeAndChargeDigitalFilter::fgBinningResolutionLoGain = 10;
+const Float_t MExtractTimeAndChargeDigitalFilter::fgOffsetLoGain            =  0.95;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls: 
+// - SetWindowSize();
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// - SetBinningResolution();
+//
+// Sets all weights to 1.
+//
+MExtractTimeAndChargeDigitalFilter::MExtractTimeAndChargeDigitalFilter(const char *name, const char *title) 
+    : fBinningResolutionHiGain(fgBinningResolutionHiGain),
+    fBinningResolutionLoGain(fgBinningResolutionLoGain),
+    fAutomaticWeights(kTRUE)
+{
+    fName  = name  ? name  : "MExtractTimeAndChargeDigitalFilter";
+    fTitle = title ? title : "Digital Filter";
+
+    SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+    SetWindowSize(3, 5);
+    SetOffsetLoGain(fgOffsetLoGain); 
+}
+
+// ---------------------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is bigger than the one defined by the ranges, set it
+// to the available range
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fWindowSizeHiGain
+// - fNumLoGainSamples to: (Float_t)fWindowSizeLoGain
+//
+// This function might be used to turn the digital filter into a
+// sliding window extractor by setting the filename to NULL
+//
+void MExtractTimeAndChargeDigitalFilter::SetWindowSize(Int_t windowh, Int_t windowl)
+{
+    if (windowh > fHiGainLast-fHiGainFirst+1)
+    {
+        *fLog << err << "ERROR - The new hi-gain window size exceeds the extraction range." << endl;
+        return;
+    }
+
+    if (windowl > (int)fLoGainLast-fLoGainFirst+1)
+    {
+        *fLog << err << "ERROR - The new hi-gain window size exceeds the extraction range." << endl;
+        return;
+    }
+
+    fWindowSizeHiGain = windowh;
+    fWindowSizeLoGain = windowl;
+
+  /*
+  const Int_t availhirange = (Int_t)();
+
+  if (fWindowSizeHiGain > availhirange)
+  {
+      *fLog << warn << GetDescriptor() << ": Hi Gain window size: " << Form("%2i",fWindowSizeHiGain);
+      *fLog << " is bigger than available range: [" << Form("%2i", (int)fHiGainFirst);
+      *fLog << "," << Form("%21", (int)fHiGainLast) << "]" << endl;
+
+      fHiGainLast = fHiGainFirst + fWindowSizeHiGain;
+
+      *fLog << warn << GetDescriptor() << ": Will set the upper range to: " << (int)fHiGainLast << endl;
+    }
+  
+  if (fWindowSizeHiGain < 2) 
+    {
+      fWindowSizeHiGain = 2;
+      *fLog << warn << GetDescriptor() << ": High Gain window size set to two samples" << endl;
+    }
+  
+  if (fLoGainLast != 0 && fWindowSizeLoGain != 0)
+    {
+      const Int_t availlorange = (Int_t)(fLoGainLast-fLoGainFirst+1);
+      
+      if (fWindowSizeLoGain > availlorange)
+        {
+            *fLog << warn << GetDescriptor() << ": Lo Gain window size: " << Form("%2i",fWindowSizeLoGain);
+            *fLog << " is bigger than available range: [" << Form("%2i", (int)fLoGainFirst);
+            *fLog << "," << Form("%21", (int)fLoGainLast) << "]" << endl;
+
+            fLoGainLast = fLoGainFirst + fWindowSizeLoGain;
+
+            *fLog << warn << GetDescriptor() << ": Will set the upper range to: " << (int)fLoGainLast << endl;
+        }
+      
+      if (fWindowSizeLoGain<2) 
+        {
+          fWindowSizeLoGain = 2;
+          *fLog << warn << GetDescriptor() << ": Low Gain window size set to two samples" << endl;
+        }
+    }*/
+  // 
+  // We need here the effective number of samples which is about 2.5 in the case of a window
+  // size of 6. The exact numbers have to be found still.
+  //
+  fNumHiGainSamples  = fWindowSizeHiGain;
+  fNumLoGainSamples  = fWindowSizeLoGain;
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Executing MExtractTimeAndCharge::PreProcess and searching for
+// MCalibrationPattern
+//
+Int_t MExtractTimeAndChargeDigitalFilter::PreProcess(MParList *pList)
+{
+    if (!MExtractTimeAndCharge::PreProcess(pList))
+        return kFALSE;
+
+    fCalibPattern = (MCalibrationPattern*)pList->FindObject("MCalibrationPattern");
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The weights are determined using GetAutimaticWeights().
+//
+// kFALSE is returned if it returned an error.
+// kTRUE  is returned if no new weights were set.
+//
+// If new weights are set
+//  fNumHiGainSamples
+//  fNumLoGainSamples
+//  fSqrtHiGainSamples
+//  fSqrtLoGainSamples
+// and
+//  fSignals->SetUsedFADCSlices(...)
+// is updated accordingly.
+//
+Bool_t MExtractTimeAndChargeDigitalFilter::GetWeights()
+{
+    switch (GetAutomaticWeights())
+    {
+    case kERROR: // An error occured
+        return kFALSE;
+    case kFALSE: // No new weights set
+        return kTRUE;
+    }
+
+    //
+    // We need here the effective number of samples. In pricipal the number
+    // is different depending on the weights used and must be set
+    // event by event.
+    //
+    fNumHiGainSamples  = fAmpWeightsHiGain.GetSum()/fBinningResolutionHiGain;
+    fNumLoGainSamples  = fAmpWeightsLoGain.GetSum()/fBinningResolutionLoGain;
+    fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+    fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+    // From MExtractTimeAndCharge::ReInit
+    if (fSignals)
+        fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast/*+fHiLoLast*/, fNumHiGainSamples,
+                                    fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// InitArrays
+//
+// Gets called in the ReInit() and initialized the arrays
+//
+Bool_t MExtractTimeAndChargeDigitalFilter::InitArrays(Int_t n)
+{
+    if (!fRunHeader)
+        return kFALSE;
+
+    return GetWeights();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if reading a new weights file is necessary because the calibration
+// pattern has changed. (Cannot be done in ReInit, because at this time
+// the calibration pattern is not available.
+// Then process the event.
+//
+Int_t MExtractTimeAndChargeDigitalFilter::Process()
+{
+    // Change Weights if the calibration patter changes
+    if (!GetWeights())
+        return kERROR;
+
+    // Process event
+    return MExtractTimeAndCharge::Process();
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the digital filter algorithm to the high-gain slices.
+//
+void MExtractTimeAndChargeDigitalFilter::FindTimeAndChargeHiGain2(const Float_t *ptr, Int_t num,
+                                                                  Float_t &sum, Float_t &dsum,
+                                                                  Float_t &time, Float_t &dtime,
+                                                                  Byte_t sat, Int_t maxpos) const
+{
+    // Do some handling if maxpos is last slice!
+
+    MExtralgoDigitalFilter df(fBinningResolutionHiGain, fWindowSizeHiGain,
+                              fAmpWeightsHiGain.GetArray(),
+                              fTimeWeightsHiGain.GetArray(),
+                              fPulseHiGain.GetArray());
+    df.SetData(num, ptr);
+
+    if (IsNoiseCalculation())
+    {
+        sum = df.ExtractNoise();
+        return;
+    }
+
+    df.Extract(/*maxpos*/);
+    df.GetSignal(sum, dsum);
+    df.GetTime(time, dtime);
+}
+
+void MExtractTimeAndChargeDigitalFilter::FindTimeAndChargeLoGain2(const Float_t *ptr, Int_t num,
+                                                                  Float_t &sum, Float_t &dsum,
+                                                                  Float_t &time, Float_t &dtime,
+                                                                  Byte_t sat, Int_t maxpos) const
+{
+    MExtralgoDigitalFilter df(fBinningResolutionLoGain, fWindowSizeLoGain,
+                              fAmpWeightsLoGain.GetArray(),
+                              fTimeWeightsLoGain.GetArray(),
+                              fPulseLoGain.GetArray());
+
+    df.SetData(num, ptr);
+
+    if (IsNoiseCalculation())
+    {
+        sum = df.ExtractNoise();
+        return;
+    }
+
+    df.Extract(/*maxpos*/);
+    df.GetSignal(sum, dsum);
+    df.GetTime(time, dtime);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MExtractor.WeightsFile: filename
+//   MJPedestal.MExtractor.AutomaticWeights: off
+//
+Int_t MExtractTimeAndChargeDigitalFilter::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (IsEnvDefined(env, prefix, "AutomaticWeights", print))
+  {
+      EnableAutomaticWeights(GetEnvValue(env, prefix, "AutomaticWeights", fAutomaticWeights));
+      rc = kTRUE;
+  }
+
+  if (IsEnvDefined(env, prefix, "WeightsFile", print))
+    {
+        SetNameWeightsFile(GetEnvValue(env, prefix, "WeightsFile", ""));
+        rc = kTRUE;
+    }
+  
+  return MExtractTimeAndCharge::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+//----------------------------------------------------------------------------
+//
+// If automatic weights are requested, no default weights (name.IsNull())
+// are requested, fRunHeader is available and fRunHeader->IsMonteCarloRun()
+// is true prepend "MC_" in from of the name.
+//
+// return poth+name;
+//
+TString MExtractTimeAndChargeDigitalFilter::CompileWeightFileName(TString path, const TString &name) const
+{
+    if (fAutomaticWeights && !name.IsNull() && fRunHeader && fRunHeader->IsMonteCarloRun())
+        path += "MC_";
+
+    path += name;
+
+    return path;
+}
+
+//----------------------------------------------------------------------------
+//
+// Read a pre-defined weights file into the class. 
+// This is mandatory for the extraction
+//
+// If filenname is empty, then all weights will be set to 1.
+//
+// Returns:
+//  kTRUE:  new weights set
+//  kFALSE: no  weights set
+//  kERROR: error
+//
+Int_t MExtractTimeAndChargeDigitalFilter::ReadWeightsFile(TString filename, TString path)
+{
+    if (filename.IsNull())
+    {
+        fAmpWeightsHiGain .Set(fBinningResolutionHiGain*fWindowSizeHiGain);
+        fAmpWeightsLoGain .Set(fBinningResolutionLoGain*fWindowSizeLoGain);
+        fTimeWeightsHiGain.Set(fBinningResolutionHiGain*fWindowSizeHiGain);
+        fTimeWeightsLoGain.Set(fBinningResolutionLoGain*fWindowSizeLoGain);
+
+        fAmpWeightsHiGain.Reset(1);
+        fTimeWeightsHiGain.Reset(1);
+        fAmpWeightsLoGain.Reset(1);
+        fTimeWeightsLoGain.Reset(1);
+        return kTRUE;
+    }
+
+    // Add "MC_" in front of the filename if necessary
+    filename = CompileWeightFileName(path, filename);
+
+    //filename = MJob::ExpandPath(filename);
+
+    if (fNameWeightsFileSet==filename)
+        return kFALSE; // No file read
+
+    ifstream fin(filename.Data());
+    if (!fin)
+    {
+        *fLog << err << GetDescriptor() << ": ERROR - Cannot open file " << filename << ": ";
+        *fLog << strerror(errno) << endl;
+        return kERROR;
+    }
+
+    *fLog << all << GetDescriptor() << ": Reading weights in " << filename << "..." << flush;
+
+    Int_t len = 0;
+    Int_t cnt = 0;
+    Int_t line = 0;
+    Bool_t hi = kFALSE;
+    Bool_t lo = kFALSE;
+
+    TString str;
+
+    while (1)
+    {
+        str.ReadLine(fin);
+        if (!fin)
+            break;
+
+        line++;
+
+        if (str.Contains("# High Gain Weights:"))
+        {
+            if (hi)
+            {
+                *fLog << err << "ERROR - 'High Gain Weights' found twice in line #" << line << "." << endl;
+                return kERROR;
+            }
+
+            if (2!=sscanf(str.Data(), "# High Gain Weights: %2i %2i", &fWindowSizeHiGain, &fBinningResolutionHiGain))
+            {
+                *fLog << err << "ERROR - Wrong number of arguments in line #" << line << ":" << endl;
+                *fLog << str << endl;
+                return kERROR;
+            }
+
+            len = fBinningResolutionHiGain*fWindowSizeHiGain;
+            fAmpWeightsHiGain .Set(len);
+            fTimeWeightsHiGain.Set(len);
+            fPulseHiGain.Set(len);
+            hi = kTRUE;
+            continue;
+        }
+
+        if (str.Contains("# Low Gain Weights:"))
+        {
+            if (lo)
+            {
+                *fLog << err << "ERROR - 'Lo Gain Weights' found twice in line #" << line << "." << endl;
+                return kERROR;
+            }
+
+            if (2!=sscanf(str.Data(),"# Low Gain Weights: %2i %2i", &fWindowSizeLoGain, &fBinningResolutionLoGain))
+            {
+                *fLog << err << "ERROR - Wrong number of arguments in line #" << line << ":" << endl;
+                *fLog << str << endl;
+                return kERROR;
+            }
+
+            len = fBinningResolutionLoGain*fWindowSizeLoGain;
+            fAmpWeightsLoGain .Set(len);
+            fTimeWeightsLoGain.Set(len);
+            fPulseLoGain.Set(len);
+            lo = kTRUE;
+            continue;
+        }
+
+        // Handle lines with comments
+        if (str.Contains("#"))
+            continue;
+
+        // Nothing found so far
+        if (len == 0)
+            continue;
+
+        if (3!=sscanf(str.Data(), "%f %f %f",
+                      lo ? &fAmpWeightsLoGain [cnt] : &fAmpWeightsHiGain [cnt],
+                      lo ? &fTimeWeightsLoGain[cnt] : &fTimeWeightsHiGain[cnt],
+                      lo ? &fPulseLoGain[cnt] : &fPulseHiGain[cnt]))
+        {
+            *fLog << err << "ERROR - Wrong number of arguments in line #" << line << ":" << endl;
+            *fLog << str << endl;
+            return kERROR;
+        }
+
+        if (++cnt == len)
+        {
+            len = 0;
+            cnt = 0;
+        }
+    }
+
+    if (cnt != len)
+    {
+        *fLog << err << "ERROR - Size mismatch in weights file " << filename << endl;
+        return kERROR;
+    }
+
+    if (!hi)
+    {
+        *fLog << err << "ERROR - No correct header found in weights file " << filename << endl;
+        return kERROR;
+    }
+
+    *fLog << "done." << endl;
+
+    *fLog << inf << " File contains " << fWindowSizeHiGain << " hi-gain slices ";
+    *fLog << "with a resolution of " << fBinningResolutionHiGain << endl;
+
+    *fLog << inf << " File contains " << fWindowSizeLoGain << " lo-gain slices ";
+    *fLog << "with a resolution of " << fBinningResolutionLoGain << endl;
+
+    //CalcBinningResArrays();
+
+    switch (fWindowSizeHiGain)
+      {
+      case 4:
+	SetResolutionPerPheHiGain(0.036);
+	break;
+      case 6:
+	SetResolutionPerPheHiGain(0.021);
+	break;
+      default:
+	*fLog << warn << "Could not set the high-gain extractor resolution per phe for window size " 
+	      << fWindowSizeHiGain << endl;
+      }
+
+    switch (fWindowSizeLoGain)
+      {
+      case 4:
+	SetResolutionPerPheLoGain(0.005);
+	break;
+      case 6:
+	SetResolutionPerPheLoGain(0.004);
+	break;
+      default:
+	*fLog << warn << "Could not set the low-gain extractor resolution per phe for window size " 
+	      << fWindowSizeLoGain << endl;
+      }
+
+    fNameWeightsFileSet = filename;
+
+    return kTRUE;
+}
+
+
+//----------------------------------------------------------------------------
+//
+// The default (+ prepending possible "MC_") is read for:
+//
+//   - RunType: Pedestal (independant of fAutomaticWeights)
+//   - fAutomaticWeights disabled
+//
+//  if fAutomaticWeights enabled:
+//   - fNameWeightsFile.IsNull()
+//   - !fCalibPattern
+//   - fCalibPattern->GetPulserColor()==MCalibrationCam::kNONE
+//
+// If automatic weights are enabled, the case above didn't take place and
+// fNameWeightsFile starts with "calibration_weights_"
+//   - the color (blue, UV) is replaced by the appropriate one
+//     taken from the calibration pattern
+//
+// In most cases a debug output is printed. Further output about the color
+// determination can be switched on with debug level > 5;
+//
+// Returns:
+//  kFALSE: No new weights set
+//  kTRUE:  New weights set
+//  kERROR: Error
+//
+Int_t MExtractTimeAndChargeDigitalFilter::GetAutomaticWeights()
+{
+    const Ssiz_t pos = fNameWeightsFile.Last('/')+1;
+    const Ssiz_t len = fNameWeightsFile.Length();
+
+    // Split file name in path and name
+    TString path = fNameWeightsFile(0, pos>=0?pos:len);
+    TString name = fNameWeightsFile(pos>=0?pos:0, len);
+
+    // Remove trailing "MC_" for automatic weights
+    if (fAutomaticWeights && name.BeginsWith("MC_"))
+        name.Remove(0, 3);
+
+    // In case of a pedetsal run no calibration pattern can be available
+    // the default weights are always used.
+    if (fRunHeader->GetRunType()==MRawRunHeader::kRTPedestal)
+    {
+        *fLog << dbg << "Pedestal file... using default weights: " << fNameWeightsFile << endl;
+        return ReadWeightsFile(name, path);
+    }
+
+    // If automatic weights are switched off use default weights
+    if (!fAutomaticWeights)
+    {
+        *fLog << dbg << "Automatic weights switched off... using default weights: " << fNameWeightsFile << endl;
+        return ReadWeightsFile(name, path);
+    }
+
+    // If automatic weights are switched on but no filename is given raise error
+    if (fNameWeightsFile.IsNull())
+    {
+        *fLog << err << "ERROR - Cannot get automatic weights without default filename." << endl;
+        return kERROR;
+    }
+
+    // If this is no pedestal run, automatic weights are requested and a
+    // filename for the weights file is given pedestal-extraction from
+    // cosmics data is assumed.
+    if (!fCalibPattern)
+    {
+        *fLog << dbg << "No decoded calibration pattern available... using default weights: " << fNameWeightsFile << endl;
+        return ReadWeightsFile(name, path);
+    }
+
+    const Bool_t debug = gLog.GetDebugLevel()>5;
+
+    // If no calibration pattern is available do not change the
+    // current weighs or current weights file name.
+    if (fCalibPattern->GetPulserColor()==MCalibrationCam::kNONE)
+    {
+        // If we are extracting data and the calibration pattern is kNONE
+        // we assume that it is a data file without interleaved events
+        // and calibration pattern information available.
+        if ((fRunHeader->GetRunType()!=MRawRunHeader::kRTData && !fRunHeader->IsMonteCarloRun()) || debug)
+            *fLog << dbg << "No calibration color set so far... guessing default: " << fNameWeightsFile << endl;
+
+        return ReadWeightsFile(name, path);
+    }
+
+    if (debug)
+    {
+        *fLog << dbg << endl;
+        *fLog << underline << GetDescriptor() << endl;
+        *fLog << " Trying to get automatic weight for " << fNameWeightsFile << endl;
+        *fLog << " Run type: ";
+    }
+
+    if (name.BeginsWith("calibration_weights_") && fCalibPattern)
+    {
+        if (debug)
+            *fLog << " Calibration with color " << fCalibPattern->GetPulserColorStr() << ", setting ";
+        switch (fCalibPattern->GetPulserColor())
+        {
+        case MCalibrationCam::kBLUE:  // 2
+        case MCalibrationCam::kGREEN: // 1
+            if (debug)
+                *fLog << "blue/green, ";
+            name.ReplaceAll("UV", "blue");
+            break;
+
+        case MCalibrationCam::kUV:    // 3
+        case MCalibrationCam::kCT1:   // 0
+            if (debug)
+                *fLog << "UV/CT1, ";
+            name.ReplaceAll("blue", "UV");
+            break;
+        case MCalibrationCam::kNONE:
+            break;
+        default: // kNone + etc
+            *fLog << err << "ERROR - Cannot get automatic weights for " << fCalibPattern->GetPulserColorStr() << endl;
+            return kERROR;
+        }
+    }
+
+    return ReadWeightsFile(name, path);
+}
+
+//----------------------------------------------------------------------------
+//
+// Print the setup of the digital filter extraction used. Use
+//  the option "weights" if you want to print also all weights.
+//
+void MExtractTimeAndChargeDigitalFilter::Print(Option_t *o) const
+{
+    if (IsA()==Class())
+        *fLog << GetDescriptor() << ":" << endl;
+
+    MExtractTimeAndCharge::Print(o);
+    *fLog << " Window Size HiGain: " << setw(2) << fWindowSizeHiGain        << "  LoGain: " << setw(2) << fWindowSizeLoGain << endl;
+    *fLog << " Binning Res HiGain: " << setw(2) << fBinningResolutionHiGain << "  LoGain: " << setw(2) << fBinningResolutionHiGain << endl;
+    *fLog << " Weights File desired: " << (fNameWeightsFile.IsNull()?"-":fNameWeightsFile.Data()) << endl;
+    if (!fNameWeightsFileSet.IsNull())
+        *fLog << " Weights File set:     " << fNameWeightsFileSet << endl;
+
+    TString opt(o);
+    if (!opt.Contains("weights"))
+        return;
+
+    *fLog << endl;
+    *fLog << inf << "Using the following weights: " << endl;
+    *fLog << "Hi-Gain:" << endl;
+    for (Int_t i=0; i<fBinningResolutionHiGain*fWindowSizeHiGain; i++)
+        *fLog << " " << fAmpWeightsHiGain[i] << " \t " << fTimeWeightsHiGain[i] << endl;
+
+    *fLog << "Lo-Gain:" << endl;
+    for (Int_t i=0; i<fBinningResolutionLoGain*fWindowSizeLoGain; i++)
+        *fLog << " " << fAmpWeightsLoGain[i] << " \t " << fTimeWeightsLoGain[i] << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilter.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilter.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilter.h	(revision 17960)
@@ -0,0 +1,97 @@
+#ifndef MARS_MExtractTimeAndChargeDigitalFilter
+#define MARS_MExtractTimeAndChargeDigitalFilter
+
+#ifndef MARS_MExtractTimeAndCharge
+#include "MExtractTimeAndCharge.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MCalibrationPattern;
+
+class MExtractTimeAndChargeDigitalFilter : public MExtractTimeAndCharge
+{
+private:
+    static const Byte_t  fgHiGainFirst;             //! Default for fHiGainFirst       (now set to: 0)
+    static const Byte_t  fgHiGainLast;              //! Default for fHiGainLast        (now set to:14)
+    static const Int_t   fgLoGainFirst;             //! Default for fLoGainFirst       (now set to: 3)
+    static const Byte_t  fgLoGainLast;              //! Default for fLoGainLast        (now set to:14)
+    static const Int_t   fgBinningResolutionHiGain; //! Default for fBinningResolutionHiGain (now set to: 10)
+    static const Int_t   fgBinningResolutionLoGain; //! Default for fBinningResolutionLoGain (now set to: 10)
+    static const TString fgNameWeightsFile;         //! "cosmics_weights.dat"
+    static const Float_t fgOffsetLoGain;            //! Default for fOffsetLoGain (now set to 1.7)
+
+    MCalibrationPattern  *fCalibPattern;            //! Calibration DM pattern
+
+    Int_t   fBinningResolutionHiGain;               //  Number of weights per bin High-Gain
+    Int_t   fBinningResolutionLoGain;               //  Number of weights per bin Low-Gain
+
+    MArrayF fAmpWeightsHiGain;                      //! Amplitude weights High-Gain (from weights file)
+    MArrayF fTimeWeightsHiGain;                     //! Time weights High-Gain (from weights file)
+    MArrayF fAmpWeightsLoGain;                      //! Amplitude weights Low-Gain (from weights file)
+    MArrayF fTimeWeightsLoGain;                     //! Time weights Low-Gain (from weights file)
+
+    MArrayF fPulseHiGain;                           //! Pulse Shape Hi-Gain (for chisq)
+    MArrayF fPulseLoGain;                           //! Pulse Shape Lo-Gain (for chisq)
+
+    TString fNameWeightsFile;                       // Name of the weights file
+    Bool_t  fAutomaticWeights;                      // Flag whether weight should be determined automatically
+    TString fNameWeightsFileSet;                    //! Flag if weights have alreayd been set
+
+    // MExtractTimeAndChargeDigitalFilter
+    void    CalcBinningResArrays();
+    Int_t   GetAutomaticWeights();
+    Bool_t  GetWeights();
+    Int_t   ReadWeightsFile(TString filename, TString path="");
+    TString CompileWeightFileName(TString path, const TString &name) const;
+
+
+    // MExtractTimeAndCharge
+    Bool_t InitArrays(Int_t n);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+protected:
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MExtractTimeAndChargeDigitalFilter(const char *name=NULL, const char *title=NULL);
+    ~MExtractTimeAndChargeDigitalFilter() { }
+
+    void SetNameWeightsFile(TString s="")
+    {
+        s.ReplaceAll("\015", ""); // This is a fix for TEnv files edited with windows editors
+        fNameWeightsFile = s;
+        fNameWeightsFileSet="";
+    }
+
+    void EnableAutomaticWeights(Bool_t b=kTRUE) { fAutomaticWeights = b; }
+
+    void SetBinningResolution(const Int_t rh=fgBinningResolutionHiGain, const Int_t rl=fgBinningResolutionLoGain)
+    {
+        fBinningResolutionHiGain = rh;
+        fBinningResolutionLoGain = rl;
+    }
+
+    void SetWindowSize( Int_t windowh, Int_t windowl);
+    const char* GetNameWeightsFile() const  { return fNameWeightsFile.Data(); }
+
+    void Print(Option_t *o="") const; //*MENU*
+
+    void FindTimeAndChargeHiGain2(const Float_t *firstused, Int_t num, Float_t &sum, Float_t &dsum,
+                                  Float_t &time, Float_t &dtime,
+                                  Byte_t sat, Int_t maxpos) const;
+
+    void FindTimeAndChargeLoGain2(const Float_t *firstused, Int_t num, Float_t &sum,  Float_t &dsum,
+                                  Float_t &time, Float_t &dtime,
+                                  Byte_t sat, Int_t maxpos) const;
+
+    ClassDef(MExtractTimeAndChargeDigitalFilter, 3)   // Hendrik's digital filter
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc	(revision 17960)
@@ -0,0 +1,573 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 02/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeDigitalFilterPeakSearch
+//
+//   An extractor using the digital filter in combination with a global
+//   peak search, analogue to the class MExtractFixedWindowPeakSearch.
+//
+//   The extractor returns kFALSE if too many events lie outside the 
+//   range: (peak - fOffsetLeftFromPeak, peak - fOffsetRightFromPeak)
+//
+//   Input Containers:
+//    MRawEvtData
+//    MRawRunHeader
+//    MPedestalCam
+//
+//   Output Containers:
+//    MArrivalTimeCam
+//    MExtractedSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeDigitalFilterPeakSearch.h"
+
+#include <fstream>
+
+#include <TFile.h>
+#include <TH1F.h>
+#include <TH2F.h>
+#include <TString.h>
+#include <TMatrix.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MExtractTimeAndChargeDigitalFilterPeakSearch);
+
+using namespace std;
+
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgHiGainFirst             =  0;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgHiGainLast              = 20;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgLoGainFirst             =  0;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgLoGainLast              = 14;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgOffsetLeftFromPeak      =  3;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgOffsetRightFromPeak     =  3;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgPeakSearchWindowSize    =  2;
+const Int_t  MExtractTimeAndChargeDigitalFilterPeakSearch::fgHiGainFailureLimit      = 10;
+const Int_t  MExtractTimeAndChargeDigitalFilterPeakSearch::fgLoGainFailureLimit      = 25;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fOffsetLeftFromPeak    to fgOffsetLeftFromPeak
+// - fOffsetRightFromPeak   to fgOffsetRightFromPeak
+// - fPeakSearchWindowSize  to fgPeakSearchWindowSize
+// - fHiGainFailureLimit to fgHiGainFailureLimit
+// - fLoGainFailureLimit to fgLoGainFailureLimit
+//
+MExtractTimeAndChargeDigitalFilterPeakSearch::MExtractTimeAndChargeDigitalFilterPeakSearch(const char *name, const char *title) 
+    :   fHiGainOutOfRangeLeft(0), fHiGainOutOfRangeRight(0),
+        fLoGainOutOfRangeLeft(0), fLoGainOutOfRangeRight(0),
+        fBadPixels(NULL)
+{
+    fName  = name  ? name  : "MExtractTimeAndChargeDigitalFilterPeakSearch";
+    fTitle = title ? title : "Digital Filter";
+
+    SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+    SetOffsetLeftFromPeak();
+    SetOffsetRightFromPeak();
+    SetPeakSearchWindowSize();
+    SetHiGainFailureLimit();
+    SetLoGainFailureLimit();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//  - MArrivalTimeCam    
+//
+// The following variables are set to 0:
+//
+//  - fHiGainOutOfRangeLeft
+//  - fHiGainOutOfRangeRight
+//  - fLoGainOutOfRangeLeft
+//  - fLoGainOutOfRangeRight
+//
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::PreProcess(MParList *pList)
+{
+
+  if (!MExtractTimeAndCharge::PreProcess(pList))
+    return kFALSE;
+  
+  fHiGainOutOfRangeLeft  = 0;
+  fHiGainOutOfRangeRight = 0;
+  fLoGainOutOfRangeLeft  = 0;
+  fLoGainOutOfRangeRight = 0;
+  
+  fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+  if (!fBadPixels)
+    {
+      *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindPeak
+//
+// Finds highest sum of "window" consecutive FADC slices in a pixel, and store
+// in "startslice" the first slice of the group which yields the maximum sum.
+// In "max" the value of the maximum sum is stored, in "sat" the number of 
+// saturated slices.
+//
+void MExtractTimeAndChargeDigitalFilterPeakSearch::FindPeak(Byte_t *ptr, Byte_t *logain, Byte_t &startslice, Int_t &max, 
+							    Int_t &sat, Byte_t &satpos) const
+{
+
+  Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  sat = 0;
+  satpos = 0;
+  
+  startslice = 0;
+  Int_t sum=0;
+
+  //
+  // Calculate the sum of the first "fPeakSearchWindowSize" slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+
+  while (p<ptr+fPeakSearchWindowSize)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+              satpos = p-ptr;
+          sat++;
+        }
+    }
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      {
+        if (sat == 0)
+          satpos = p-ptr;
+        sat++;
+      }
+  
+  //
+  // Calculate the i-th sum of n as
+  //    sum_i+1 = sum_i + slice[i+fPeakSearchWindowSize] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  for (p=ptr; p+fPeakSearchWindowSize<end; p++)
+    {
+      sum += *(p+fPeakSearchWindowSize) - *p;
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = p-ptr+1;
+	}
+    }
+
+  if (!fHiLoLast)
+    return;
+
+  Byte_t *l = logain;
+
+  while (++p < end && l < logain+fHiLoLast)
+    {
+      sum += *l - *p;
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = p-ptr+1;
+	}
+
+      if (*l++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+            satpos = l-logain + fHiGainLast - fHiGainFirst;
+          sat++;
+        }
+    }
+  
+  if (fHiLoLast <= fPeakSearchWindowSize)
+    return;
+
+  while (l < logain+fHiLoLast)
+    {
+      if (*l++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+            satpos = l-logain+fHiGainLast-fHiGainFirst;
+          sat++;
+        }
+
+      sum += *l - *(l-fPeakSearchWindowSize);
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = l-logain + fHiGainLast - fHiGainFirst - fPeakSearchWindowSize + 1;
+	}
+    }
+
+  return;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Process
+//
+// First find the pixel with highest sum of fPeakSearchWindowSize slices (default:2)
+// "startslice" will mark the slice at which the highest sum begins for that pixel.
+//
+// Then define the beginning of the digital filter search window for ALL pixels as the slice
+// before that: startslice-fOffsetLeftFromPeak until: startslice+fOffsetRightFromPeak
+//
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  Int_t   sat        = 0;
+  Byte_t  satpos     = 0;
+  ULong_t gsatpos    = 0;
+
+  Int_t   maxsumhi   = -1000000;
+  Int_t   numsat     = 0;
+  Byte_t  startslice = 0;
+
+  Byte_t hiGainFirstsave = fHiGainFirst;
+  Byte_t hiGainLastsave  = fHiGainLast;
+  Byte_t loGainFirstsave = fLoGainFirst;
+  Byte_t loGainLastsave  = fLoGainLast; 
+  Byte_t hiLoLastsave    = fHiLoLast;
+
+  Byte_t higainfirst     = fHiGainFirst;
+  UInt_t peakpixel       = 0;
+
+  while (pixel.Next())
+    {
+
+      Int_t sumhi;
+      sat = 0;
+
+      MBadPixelsPix &bad = (*fBadPixels)[pixel.GetPixelId()];
+      
+      if (!bad.IsUnsuitable())
+        FindPeak(pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), startslice, sumhi, sat, satpos);
+
+      if (sumhi > maxsumhi && sat == 0)
+	{
+	  maxsumhi     = sumhi;
+	  higainfirst  = fHiGainFirst + startslice;
+          peakpixel    = pixel.GetPixelId();
+	}
+      else if (sat)
+        {
+          numsat++;
+          gsatpos += satpos;
+        }
+    }
+
+  //
+  // Check necessary for calibration events
+  //
+  if (numsat > fSignals->GetSize()*0.9)
+    higainfirst = gsatpos/numsat - 1;
+
+  //
+  // Shift the start slice to the left:
+  //
+  if (higainfirst >= fHiGainFirst + fOffsetLeftFromPeak)
+    fHiGainFirst = higainfirst - fOffsetLeftFromPeak;
+  else
+    {
+      //      *fLog << err << (Int_t)higainfirst << "   " << peakpixel << endl;      
+      fHiGainOutOfRangeLeft++;
+    }
+  
+  //
+  // Shift the last slice to the right:
+  //
+  const Byte_t rlim = higainfirst + fOffsetRightFromPeak + fWindowSizeHiGain - 1;
+  if (rlim <= fHiGainLast+fHiLoLast)
+    if (rlim > fHiGainLast)
+      {
+        fHiLoLast   = rlim - fHiGainLast;
+        fHiGainLast = pixel.GetNumHiGainSamples() - 1;
+      }
+    else
+      {
+        fHiLoLast   = 0;
+        fHiGainLast = rlim;
+      }
+  else 
+    {
+      fHiGainOutOfRangeRight++;
+      //      *fLog << err << (Int_t)higainfirst << "   " << peakpixel << endl;      
+    }
+  
+  const Byte_t llim = higainfirst + (Int_t)fOffsetLoGain;
+  if ( llim  >= fLoGainFirst + fOffsetLeftFromPeak) 
+    fLoGainFirst = llim - fOffsetLeftFromPeak;
+  else
+    fLoGainOutOfRangeLeft++;
+  
+  //
+  // Make sure we will not integrate beyond the lo gain limit:
+  //
+  const Byte_t lolast = fLoGainFirst+fWindowSizeLoGain+fOffsetRightFromPeak-1;  
+  if (lolast < pixel.GetNumLoGainSamples())
+    fLoGainLast = lolast;
+  else
+    {
+      fLoGainOutOfRangeRight++;
+      //      *fLog << err << (Int_t)higainfirst << "   " << peakpixel << "  " << (int)fLoGainFirst << endl;      
+    }
+  
+  //  *fLog << inf << (int)fHiGainFirst << "  " << (int)higainfirst << "  " << (int)fHiGainLast 
+  //        << "  " << (int)fLoGainFirst << "  " << (int)fLoGainLast << endl;
+
+  pixel.Reset();
+
+  while (pixel.Next())
+    {
+
+      //
+      // Find signal in hi- and lo-gain
+      //
+      Float_t sumhi =0., deltasumhi =0; // Set hi-gain of MExtractedSignalPix valid
+      Float_t timehi=0., deltatimehi=0; // Set hi-gain of MArrivalTimePix valid
+      Byte_t sathi=0;
+
+      // Initialize fMaxBinContent for the case, it gets not set by the derived class
+      fMaxBinContent = fLoGainSwitch + 1; 
+
+      const Int_t pixidx = pixel.GetPixelId();
+      const MPedestalPix  &ped = (*fPedestals)[pixidx];
+      const Bool_t higainabflag = pixel.HasABFlag();
+
+      FindTimeAndChargeHiGain(pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), 
+                              sumhi, deltasumhi, 
+                              timehi, deltatimehi, 
+                              sathi, ped, higainabflag);
+
+      //
+      // Make sure that in cases the time couldn't be correctly determined
+      // more meaningfull default values are assigned
+      //
+      if (timehi<0)
+          timehi = -1;
+      if (timehi>pixel.GetNumHiGainSamples())
+          timehi = pixel.GetNumHiGainSamples();
+      
+      Float_t sumlo =0., deltasumlo =-1.; // invalidate logain of MExtractedSignalPix
+      Float_t timelo=0., deltatimelo=-1;  // invalidate logain of MArrivalTimePix
+      Byte_t satlo=0;
+      
+      //
+      // Adapt the low-gain extraction range from the obtained high-gain time
+      //
+      if (pixel.HasLoGain() && (fMaxBinContent > fLoGainSwitch) )
+      {
+          deltasumlo  = 0; // make logain of MExtractedSignalPix valid
+          deltatimelo = 0; // make logain of MArrivalTimePix valid
+
+          fLoGainFirstSave = fLoGainFirst;
+          const Byte_t logainstart = sathi 
+            ? sathi + (Int_t)fLoGainStartShift
+            : (Byte_t)(timehi + fLoGainStartShift);
+        
+	  fLoGainFirst = logainstart > fLoGainFirstSave ? logainstart : fLoGainFirstSave;
+
+          if ( fLoGainFirst < fLoGainLast )
+            {
+              const Bool_t logainabflag = (higainabflag + pixel.GetNumHiGainSamples()) & 0x1;
+              FindTimeAndChargeLoGain(pixel.GetLoGainSamples()+fLoGainFirst,
+                                      sumlo, deltasumlo,
+                                      timelo, deltatimelo,
+                                      satlo, ped, logainabflag);
+          }
+          fLoGainFirst = fLoGainFirstSave;
+
+          // Make sure that in cases the time couldn't be correctly determined
+          // more meaningfull default values are assigned
+          if (timelo<0)
+              timelo = -1;
+          if (timelo>pixel.GetNumLoGainSamples())
+              timelo = pixel.GetNumLoGainSamples();
+      }
+
+      MExtractedSignalPix &pix = (*fSignals)[pixidx];
+      MArrivalTimePix     &tix = (*fArrTime)[pixidx];
+      pix.SetExtractedSignal(sumhi, deltasumhi,sumlo, deltasumlo);
+      pix.SetGainSaturation(sathi, satlo);
+
+      tix.SetArrivalTime(timehi, deltatimehi, timelo-fOffsetLoGain, deltatimelo);
+      tix.SetGainSaturation(sathi, satlo);
+ 
+    } /* while (pixel.Next()) */
+
+  fArrTime->SetReadyToSave();
+  fSignals->SetReadyToSave();
+
+  fHiGainFirst  = hiGainFirstsave;
+  fHiGainLast   = hiGainLastsave ; 
+  fLoGainFirst  = loGainFirstsave;
+  fLoGainLast   = loGainLastsave ; 
+  fHiLoLast     = hiLoLastsave;
+
+  return kTRUE;
+}
+
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::PostProcess()
+{
+
+  if (GetNumExecutions() < 1)
+    return kTRUE;
+
+  *fLog << warn << endl;
+
+  const Int_t higainfailure = ((fHiGainOutOfRangeLeft+fHiGainOutOfRangeRight)*100)/GetNumExecutions();
+  const Int_t logainfailure = ((fLoGainOutOfRangeLeft+fLoGainOutOfRangeRight)*100)/GetNumExecutions();
+
+  if (fHiGainOutOfRangeLeft > 0)
+    *fLog << Form("%5.1f",((Float_t)fHiGainOutOfRangeLeft*100)/GetNumExecutions())
+          << "% ranging out of hi-gain window to the left!" << endl;
+  if (fHiGainOutOfRangeRight > 0)
+    *fLog << Form("%5.1f",((Float_t)fHiGainOutOfRangeRight*100)/GetNumExecutions())
+	  << "% ranging out of hi-gain window to the right!" << endl;
+  if (fLoGainOutOfRangeLeft > 0)
+    *fLog << Form("%5.1f",((Float_t)fLoGainOutOfRangeLeft*100)/GetNumExecutions())
+          << "% ranging out of lo-gain window to the left!" << endl;
+  if (fLoGainOutOfRangeRight > 0)
+    *fLog << Form("%5.1f",((Float_t)fLoGainOutOfRangeRight*100)/GetNumExecutions())
+	  << "% ranging out of lo-gain window to the right!" << endl;
+
+  
+  if (higainfailure > fHiGainFailureLimit)
+    {
+      *fLog << err << higainfailure << "% range failures in high gain above limit of: " << fHiGainFailureLimit << "%." << endl;
+      return kFALSE;
+    }
+  
+  if (logainfailure > fLoGainFailureLimit)
+    {
+      *fLog << err << logainfailure << "% range failures in low gain above limit of: " << fLoGainFailureLimit << "%." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//   MJPedestal.MExtractor.BinningResolutionHiGain: 10
+//   MJPedestal.MExtractor.BinningResolutionLoGain: 10
+//   MJPedestal.MExtractor.WeightsFile: filename
+//
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (IsEnvDefined(env, prefix, "OffsetLeftFromPeak", print))
+    {
+      fOffsetLeftFromPeak = GetEnvValue(env, prefix, "OffsetLeftFromPeak", fOffsetLeftFromPeak);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "OffsetRightFromPeak", print))
+    {
+      fOffsetRightFromPeak = GetEnvValue(env, prefix, "OffsetRightFromPeak", fOffsetRightFromPeak);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "PeakSearchWindowSize", print))
+    {
+      fPeakSearchWindowSize = GetEnvValue(env, prefix, "PeakSearchWindowSize", fPeakSearchWindowSize);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "HiGainFailureLimit", print))
+    {
+      fHiGainFailureLimit = GetEnvValue(env, prefix, "HiGainFailureLimit", fHiGainFailureLimit);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "LoGainFailureLimit", print))
+    {
+      fLoGainFailureLimit = GetEnvValue(env, prefix, "LoGainFailureLimit", fLoGainFailureLimit);
+      rc = kTRUE;
+    }
+  
+  return MExtractTimeAndChargeDigitalFilter::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+
+void MExtractTimeAndChargeDigitalFilterPeakSearch::Print(Option_t *o) const
+{
+    if (IsA()==Class())
+        *fLog << GetDescriptor() << ":" << endl;
+
+    MExtractTimeAndChargeDigitalFilter::Print(o);
+    *fLog << " Offset from Peak left:   " << (int)fOffsetLeftFromPeak   << endl;
+    *fLog << " Offset from Peak right:  " << (int)fOffsetRightFromPeak  << endl;
+    *fLog << " Peak search window size: " << (int)fPeakSearchWindowSize << endl;
+    *fLog << " High Gain Failure limit: " << fHiGainFailureLimit << endl;
+    *fLog << " Low Gain Failure limit:  " << fLoGainFailureLimit << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.h	(revision 17960)
@@ -0,0 +1,73 @@
+#ifndef MARS_MExtractTimeAndChargeDigitalFilterPeakSearch
+#define MARS_MExtractTimeAndChargeDigitalFilterPeakSearch
+
+#ifndef MARS_MExtractTimeAndChargeDigitalFilter
+#include "MExtractTimeAndChargeDigitalFilter.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+class TH1F;
+class TH2F;
+class MPedestalPix;
+class MBadPixelsCam;
+
+class MExtractTimeAndChargeDigitalFilterPeakSearch : public MExtractTimeAndChargeDigitalFilter
+{
+private:
+
+  static const Byte_t fgHiGainFirst;           //! Default for fHiGainFirst           (now set to: 0)
+  static const Byte_t fgHiGainLast;            //! Default for fHiGainLast            (now set to:18)
+  static const Byte_t fgLoGainFirst;           //! Default for fLoGainFirst           (now set to: 2)
+  static const Byte_t fgLoGainLast;            //! Default for fLoGainLast            (now set to:14)
+  static const Byte_t fgOffsetLeftFromPeak;    //! Default for fOffsetLeftFromPeak    (now set to: 1)  
+  static const Byte_t fgOffsetRightFromPeak;   //! Default for fOffsetRightFromPeak   (now set to: 2)  
+  static const Byte_t fgPeakSearchWindowSize;  //! Default for fPeakSearchWindowSize  (now set to: 2)
+  static const Int_t  fgHiGainFailureLimit;    //! Default for fHiGainMaxFailureLimit (now set to: 5)
+  static const Int_t  fgLoGainFailureLimit;    //! Default for fHiGainMaxFailureLimit (now set to: 10)
+
+  Byte_t  fOffsetLeftFromPeak;                 // Number of slices to start extraction before peak slice
+  Byte_t  fOffsetRightFromPeak;                // Number of slices to stop  extraction after  peak slice
+  Byte_t  fPeakSearchWindowSize;               // Size of FADC window in the search for the highest peak of all pixels.
+  Int_t   fHiGainFailureLimit;                 // Limit for percentage of events ranging out of limits in high gain
+  Int_t   fLoGainFailureLimit;                 // Limit for percentage of events ranging out of limits in low gain
+
+  ULong_t fHiGainOutOfRangeLeft;               // Number of events out of range to the left side in high gain
+  ULong_t fHiGainOutOfRangeRight;              // Number of events out of range to the right side in high gain
+  ULong_t fLoGainOutOfRangeLeft;               // Number of events out of range to the left side in low gain
+  ULong_t fLoGainOutOfRangeRight;              // Number of events out of range to the right side in low gain
+
+  MBadPixelsCam *fBadPixels;                   // Bad Pixels Camera
+  
+  void    FindPeak(Byte_t *ptr, Byte_t *logain,
+                   Byte_t &startslice, Int_t &max, Int_t &sat, Byte_t &satpos) const;
+
+  Int_t   PreProcess(MParList *pList);
+  Int_t   Process();
+  Int_t   PostProcess();
+
+  Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+
+  MExtractTimeAndChargeDigitalFilterPeakSearch(const char *name=NULL, const char *title=NULL);  
+  ~MExtractTimeAndChargeDigitalFilterPeakSearch() { }
+  
+  void SetOffsetLeftFromPeak  ( Byte_t offset=fgOffsetLeftFromPeak   )  { fOffsetLeftFromPeak   = offset; }
+  void SetOffsetRightFromPeak ( Byte_t offset=fgOffsetRightFromPeak  )  { fOffsetRightFromPeak  = offset; }
+  void SetPeakSearchWindowSize( Byte_t size  =fgPeakSearchWindowSize )  { fPeakSearchWindowSize = size;   }
+  void SetHiGainFailureLimit  ( Int_t  lim   =fgHiGainFailureLimit   )  { fHiGainFailureLimit   = lim;    }     
+  void SetLoGainFailureLimit  ( Int_t  lim   =fgLoGainFailureLimit   )  { fLoGainFailureLimit   = lim;    }
+
+  void Print(Option_t *o="") const;
+
+  ClassDef(MExtractTimeAndChargeDigitalFilterPeakSearch, 1)   // Digital filter with global Peak Search
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSlidingWindow.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSlidingWindow.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSlidingWindow.cc	(revision 17960)
@@ -0,0 +1,486 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug,    09/2004 <mailto:markus@ifae.es> 
+!   Author(s): Hendrik Bartko, 01/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2005
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSlidingWindow
+//
+//   Extracts the signal from a sliding window of size fHiGainWindowSize and 
+//   fLoGainWindowSize, respectively. The signal is the one which maximizes 
+//   the clock-noise and pedestal-corrected integral contents.
+//
+//   The amplitude-weighted arrival time is calculated from the window with 
+//   the highest integral using the following formula:
+//
+//   t = sum(s(i) * i) / sum(i) 
+// 
+//   where i denotes the FADC slice index and s(i) the clock-noise and 
+///  pedestal-corrected FADC value at slice index i. The sum runs over the 
+//   extraction window size.
+//
+//   Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//         to modify the ranges in which the window is allowed to move. 
+//
+//   Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  2 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindowSize(windowhigain, windowlogain) 
+//        to modify the sliding window widths. Windows have to be an even number. 
+//        Odd numbers are possible since the clock-noise is corrected for.
+//
+//  Defaults are:
+//
+//  fHiGainWindowSize = 6
+//  fLoGainWindowSize = 6
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeSlidingWindow.h"
+
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractTimeAndChargeSlidingWindow);
+
+using namespace std;
+
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgHiGainFirst  = 0;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgHiGainLast   = 16;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgLoGainFirst  = 2;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgLoGainLast   = 14;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgHiGainWindowSize = 6;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgLoGainWindowSize = 8;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+// Initializes:
+// - fWindowSizeHiGain to fgHiGainWindowSize
+// - fWindowSizeLoGain to fgLoGainWindowSize
+//
+MExtractTimeAndChargeSlidingWindow::MExtractTimeAndChargeSlidingWindow(const char *name, const char *title) 
+{
+  
+  fName  = name  ? name  : "MExtractTimeAndChargeSlidingWindow";
+  fTitle = title ? title : "Calculate arrival times and charges using a sliding window";
+
+  fWindowSizeHiGain = fgHiGainWindowSize;
+  fWindowSizeLoGain = fgLoGainWindowSize;
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+//-------------------------------------------------------------------
+//
+// Set the ranges
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
+//
+void MExtractTimeAndChargeSlidingWindow::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst, hilast, lofirst, lolast);
+
+  //
+  // Redo the checks if the window is still inside the ranges
+  //
+  SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
+  
+}
+
+// -----------------------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fWindowSizeHiGain
+// - fNumLoGainSamples to: (Float_t)fWindowSizeLoGain
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractTimeAndChargeSlidingWindow::SetWindowSize(Int_t windowh, Int_t windowl)
+{
+  
+  fWindowSizeHiGain = windowh;
+  fWindowSizeLoGain = windowl;
+
+  const Int_t availhirange = (Int_t)(fHiGainLast-fHiGainFirst+1);
+
+  if (fWindowSizeHiGain > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fWindowSizeHiGain,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fWindowSizeHiGain = availhirange;
+    }
+  
+  if (fWindowSizeHiGain<1) 
+    {
+      fWindowSizeHiGain = 1;
+      *fLog << warn << GetDescriptor() << ": High Gain window size too small, set to one sample" << endl;
+    }
+  
+  if (fLoGainLast != 0 && fWindowSizeLoGain != 0)
+    {
+      const Int_t availlorange = (Int_t)(fLoGainLast-fLoGainFirst+1);
+      
+      if (fWindowSizeLoGain > availlorange)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fWindowSizeLoGain,
+                        " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+          *fLog << warn << GetDescriptor() 
+                << ": Will set window size to: " << (int)availlorange << endl;
+          fWindowSizeLoGain = availlorange;
+        }
+    }
+  
+  fNumHiGainSamples = (Float_t)fWindowSizeHiGain;
+  fNumLoGainSamples = fLoGainLast ? (Float_t)fWindowSizeLoGain : 0.;
+  
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+  switch (fWindowSizeHiGain)
+    {
+    case 2:
+      SetResolutionPerPheHiGain(0.050);
+      break;
+    case 4:
+      SetResolutionPerPheHiGain(0.039);
+      break;
+    case 6:
+    case 8:
+      SetResolutionPerPheHiGain(0.011);
+      break;
+    case 14:
+      SetResolutionPerPheHiGain(0.009);
+      break;
+    default:
+      *fLog << warn << GetDescriptor() << ": Could not set the high-gain extractor resolution per phe for window size " 
+            << fWindowSizeHiGain << endl;
+    }
+  
+  switch (fWindowSizeLoGain)
+    {
+    case 2:
+      SetResolutionPerPheLoGain(0.028);
+      break;
+    case 4:
+      SetResolutionPerPheLoGain(0.013);
+      break;
+    case 6:
+      SetResolutionPerPheLoGain(0.008);
+      break;
+    case 8:
+    case 10:
+      SetResolutionPerPheLoGain(0.005);
+      break;
+    default:
+      *fLog << warn << GetDescriptor() << ": Could not set the low-gain extractor resolution per phe for window size " 
+            << fWindowSizeLoGain << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// InitArrays
+//
+// Gets called in the ReInit() and initialized the arrays
+//
+Bool_t MExtractTimeAndChargeSlidingWindow::InitArrays()
+{
+  Int_t range = (Int_t)(fHiGainLast - fHiGainFirst + 1 + fHiLoLast);
+  fHiGainSignal.Set(range);
+  range = (Int_t)(fLoGainLast - fLoGainFirst + 1);
+  fLoGainSignal.Set(range);
+
+  return kTRUE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeAndChargeSlidingWindow::FindTimeAndChargeHiGain(Byte_t *first, Byte_t *logain, Float_t &sum, Float_t &dsum, 
+                                                          Float_t &time, Float_t &dtime, 
+                                                          Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag)
+{
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p  = first;
+  
+  Float_t max = 0;  // highest integral content of all windows
+  sat         = 0;
+
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+
+  const Float_t PedMean[2] = { pedes + ABoffs, pedes - ABoffs };
+
+  fMaxBinContent = 0;
+  //
+  // Check for saturation in all other slices
+  //
+  Int_t ids = fHiGainFirst;
+  Float_t *sample = fHiGainSignal.GetArray();
+
+  while (p<first+fWindowSizeHiGain)
+    {
+
+      const Float_t signal = (Float_t)*p - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal;
+      *sample++            = signal;
+      
+      if (*p > fMaxBinContent)
+	fMaxBinContent = *p;
+
+      if (*p++ >= fSaturationLimit)
+        if (!sat)
+            sat = ids-2;
+    }
+
+  if (IsNoiseCalculation())
+    return;
+   
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    {
+      if (*p > fMaxBinContent)
+	fMaxBinContent = *p;
+      
+      if (*p++ >= fSaturationLimit)
+	if (!sat)
+	  sat = ids-2;
+    }
+
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  Int_t count    = 0;
+  max            = sum;
+  Int_t idx      =  0;  // idx of the first slice of the maximum window
+  
+  for (p=first; p+fWindowSizeHiGain<end; p++)
+    {
+      
+      const Float_t signal = (Float_t)*(p+fWindowSizeHiGain) - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal - *(sample-fWindowSizeHiGain);
+      *sample++            = signal;
+      
+      if (sum>max)
+        {
+          max   = sum;
+          idx   = count+1;
+        }
+      count++;
+    }
+  
+  // 
+  // overlap bins
+  // 
+  Byte_t *l = logain;
+  while (l < logain+fHiLoLast)
+    {
+      
+      const Float_t signal = (Float_t)*l - PedMean[(ids++ + abflag) & 0x1];          
+      sum                 += signal - *(sample-fWindowSizeHiGain);
+      *sample++            = signal;
+
+      if (*l > fMaxBinContent)
+        fMaxBinContent = *logain;
+      
+      if (*l++ >= fSaturationLimit)
+        if (!sat)
+          sat = ids-2;
+      
+      if (sum>max)
+        {
+          max   = sum;
+          idx   = count+1;
+        }
+      count++;
+    } /* while (l<logain+fHiLoLast) */
+
+  //
+  // now calculate the time for the maximum window
+  //
+  Float_t timesignalsum  = 0.;
+  Int_t   timesquaredsum = 0;
+  
+  for (Int_t i=idx; i<idx+fWindowSizeHiGain; i++)
+    {
+      timesignalsum   += fHiGainSignal[i]*i;
+      timesquaredsum  += i*i;
+    }
+  
+  sum   = max;
+
+  time  = max > 0.1 ? timesignalsum / max  + Float_t(fHiGainFirst) : 1.;
+  dtime = max > 0.1 ? ped.GetPedestalRms() / max * sqrt(timesquaredsum - fWindowSizeHiGain*time) : 1.;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeAndChargeSlidingWindow::FindTimeAndChargeLoGain(Byte_t *first, Float_t &sum, Float_t &dsum, 
+                                                          Float_t &time, Float_t &dtime, 
+                                                          Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag) 
+{
+  
+  Int_t range = fLoGainLast - fLoGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p  = first;
+  
+  Float_t max = 0;  // highest integral content of all windows
+  Int_t count = 0;  // counter to recognize the AB-flag
+
+  Float_t pedes        = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+
+  Float_t PedMean[2] = { pedes + ABoffs, pedes - ABoffs };
+  //
+  // Check for saturation in all other slices
+  //
+  Int_t ids = fLoGainFirst;
+
+  while (p<first+fWindowSizeLoGain)
+    {
+      const Float_t signal = (Float_t)*p - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal;
+      fLoGainSignal[count] = signal;
+      
+      if (*p++ >= fSaturationLimit)
+        sat++;
+
+      count++;
+    }
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+  
+  if (IsNoiseCalculation())
+    return;
+
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  count          = 0;
+  max            = sum;
+  Int_t idx      =  0;  // idx of the first slice of the maximum window
+  
+  for (p=first; p+fWindowSizeLoGain<end; p++)
+    {
+
+      const Float_t signal = (Float_t)*(p+fWindowSizeLoGain) - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal - fLoGainSignal[count];
+      fLoGainSignal[count + fWindowSizeLoGain] = signal;
+
+      if (sum>max)
+	{
+	  max   = sum;
+          idx   = count+1;
+	}
+      count++;
+    }
+  
+  //
+  // now calculate the time for the maximum window
+  //
+  Float_t timesignalsum  = 0;
+  Int_t   timesquaredsum = 0;
+  
+  for (Int_t i=idx; i<idx+fWindowSizeLoGain; i++)
+    {
+      timesignalsum   += fLoGainSignal[i]*i;
+      timesquaredsum  += i*i;
+    }
+  
+  sum   = max;
+
+  time  = max > 0.1 ? timesignalsum / max  + Float_t(fLoGainFirst) : 1.;
+  dtime = max > 0.1 ? ped.GetPedestalRms() / max * sqrt(timesquaredsum - fWindowSizeLoGain*time) : 1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//
+Int_t MExtractTimeAndChargeSlidingWindow::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+  
+  Byte_t hw = fWindowSizeHiGain;
+  Byte_t lw = fWindowSizeLoGain;
+  
+  Bool_t rc = kFALSE;
+  
+  if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+      hw = GetEnvValue(env, prefix, "HiGainWindowSize", hw);
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+      lw = GetEnvValue(env, prefix, "LoGainWindowSize", lw);
+      rc = kTRUE;
+    }
+  
+  if (rc)
+    SetWindowSize(hw, lw);
+  
+  return MExtractTimeAndCharge::ReadEnv(env, prefix, print) ? kTRUE : rc;
+
+}
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSlidingWindow.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSlidingWindow.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSlidingWindow.h	(revision 17960)
@@ -0,0 +1,56 @@
+#ifndef MARS_MExtractTimeAndChargeSlidingWindow
+#define MARS_MExtractTimeAndChargeSlidingWindow
+
+#ifndef MARS_MExtractTimeAndCharge
+#include "MExtractTimeAndCharge.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MPedestalPix;
+
+class MExtractTimeAndChargeSlidingWindow : public MExtractTimeAndCharge
+{
+private:
+  static const Byte_t fgHiGainFirst;      //! Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t fgHiGainLast;       //! Default for fHiGainLast   (now set to: 14)
+  static const Byte_t fgLoGainFirst;      //! Default for fLOGainFirst  (now set to: 2)
+  static const Byte_t fgLoGainLast;       //! Default for fLoGainLast   (now set to: 14)
+  static const Byte_t fgHiGainWindowSize; //! The extraction window Hi-Gain
+  static const Byte_t fgLoGainWindowSize; //! The extraction window Lo-Gain
+
+  Float_t fHiGainWindowSizeSqrt;         // Square root of number of gains in window
+  Float_t fLoGainWindowSizeSqrt;         // Square root of number of gains in window
+  
+  MArrayF fHiGainSignal;                 //! Need fast access to the signals in a float way
+  MArrayF fLoGainSignal;                 //! Store them in separate arrays
+
+  Bool_t  InitArrays();
+  
+  Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MExtractTimeAndChargeSlidingWindow(const char *name=NULL, const char *title=NULL);
+  ~MExtractTimeAndChargeSlidingWindow() {}
+
+  void SetRange    ( Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0 );  
+  void SetWindowSize(Int_t windowh=fgHiGainWindowSize,
+                     Int_t windowl=fgLoGainWindowSize);
+
+  void FindTimeAndChargeHiGain(Byte_t *first, Byte_t *logain, Float_t &sum, Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+  void FindTimeAndChargeLoGain(Byte_t *first, Float_t &sum,  Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+
+  ClassDef(MExtractTimeAndChargeSlidingWindow, 1)   // Task to Extract Times and Charges using a Sliding Window
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSpline.cc	(revision 17960)
@@ -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 analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzbrug.de>
+!   Author(s): Markus Gaug 09/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2002-2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeSpline
+//
+//   Fast Spline extractor using a cubic spline algorithm, adapted from 
+//   Numerical Recipes in C++, 2nd edition, pp. 116-119.
+//   
+//   The coefficients "ya" are here denoted as "fHiGainSignal" and "fLoGainSignal"
+//   which means the FADC value subtracted by the clock-noise corrected pedestal.
+//
+//   The coefficients "y2a" get immediately divided 6. and are called here 
+//   "fHiGainSecondDeriv" and "fLoGainSecondDeriv" although they are now not exactly 
+//   the second derivative coefficients any more. 
+// 
+//   The calculation of the cubic-spline interpolated value "y" on a point 
+//   "x" along the FADC-slices axis becomes:
+// 
+//   y =    a*fHiGainSignal[klo] + b*fHiGainSignal[khi] 
+//       + (a*a*a-a)*fHiGainSecondDeriv[klo] + (b*b*b-b)*fHiGainSecondDeriv[khi]
+//
+//   with:
+//   a = (khi - x)
+//   b = (x - klo)
+//
+//   and "klo" being the lower bin edge FADC index and "khi" the upper bin edge FADC index.
+//   fHiGainSignal[klo] and fHiGainSignal[khi] are the FADC values at "klo" and "khi".
+//
+//   An analogues formula is used for the low-gain values.
+//
+//   The coefficients fHiGainSecondDeriv and fLoGainSecondDeriv are calculated with the 
+//   following simplified algorithm:
+//
+//   for (Int_t i=1;i<range-1;i++) {
+//       pp                   = fHiGainSecondDeriv[i-1] + 4.;
+//       fHiGainFirstDeriv[i] = fHiGainSignal[i+1] - 2.*fHiGainSignal[i] + fHiGainSignal[i-1]
+//       fHiGainFirstDeriv[i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+//   }
+// 
+//   for (Int_t k=range-2;k>=0;k--)
+//       fHiGainSecondDeriv[k] = (fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k])/6.;
+// 
+//
+//   This algorithm takes advantage of the fact that the x-values are all separated by exactly 1
+//   which simplifies the Numerical Recipes algorithm.
+//   (Note that the variables "fHiGainFirstDeriv" are not real first derivative coefficients.)
+//
+//   The algorithm to search the time proceeds as follows:
+//
+//   1) Calculate all fHiGainSignal from fHiGainFirst to fHiGainLast 
+//      (note that an "overlap" to the low-gain arrays is possible: i.e. fHiGainLast>14 in the case of 
+//      the MAGIC FADCs).
+//   2) Remember the position of the slice with the highest content "fAbMax" at "fAbMaxPos".
+//   3) If one or more slices are saturated or fAbMaxPos is less than 2 slices from fHiGainFirst, 
+//      return fAbMaxPos as time and fAbMax as charge (note that the pedestal is subtracted here).
+//   4) Calculate all fHiGainSecondDeriv from the fHiGainSignal array
+//   5) Search for the maximum, starting in interval fAbMaxPos-1 in steps of 0.2 till fAbMaxPos-0.2.
+//      If no maximum is found, go to interval fAbMaxPos+1. 
+//      --> 4 function evaluations
+//   6) Search for the absolute maximum from fAbMaxPos to fAbMaxPos+1 in steps of 0.2 
+//      --> 4 function  evaluations
+//   7) Try a better precision searching from new max. position fAbMaxPos-0.2 to fAbMaxPos+0.2
+//      in steps of 0.025 (83 psec. in the case of the MAGIC FADCs).
+//      --> 14 function evaluations
+//   8) If Time Extraction Type kMaximum has been chosen, the position of the found maximum is 
+//      returned, else:
+//   9) The Half Maximum is calculated. 
+//  10) fHiGainSignal is called beginning from fAbMaxPos-1 backwards until a value smaller than fHalfMax
+//      is found at "klo". 
+//  11) Then, the spline value between "klo" and "klo"+1 is halfed by means of bisection as long as 
+//      the difference between fHalfMax and spline evaluation is less than fResolution (default: 0.01).
+//      --> maximum 12 interations.
+//   
+//  The algorithm to search the charge proceeds as follows:
+//
+//  1) If Charge Type: kAmplitude was chosen, return the Maximum of the spline, found during the 
+//     time search.
+//  2) If Charge Type: kIntegral was chosen, sum the fHiGainSignal between:
+//     (Int_t)(fAbMaxPos - fRiseTimeHiGain) and 
+//     (Int_t)(fAbMaxPos + fFallTimeHiGain)
+//     (default: fRiseTime: 1.5, fFallTime: 4.5)
+//                                           sum the fLoGainSignal between:
+//     (Int_t)(fAbMaxPos - fRiseTimeHiGain*fLoGainStretch) and 
+//     (Int_t)(fAbMaxPos + fFallTimeHiGain*fLoGainStretch)
+//     (default: fLoGainStretch: 1.5)
+//       
+//  The values: fNumHiGainSamples and fNumLoGainSamples are set to:
+//  1) If Charge Type: kAmplitude was chosen: 1.
+//  2) If Charge Type: kIntegral was chosen: fRiseTimeHiGain + fFallTimeHiGain
+//                 or: fNumHiGainSamples*fLoGainStretch in the case of the low-gain
+//
+//  Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//        to modify the ranges.
+// 
+//        Defaults: 
+//        fHiGainFirst =  2 
+//        fHiGainLast  =  14
+//        fLoGainFirst =  2 
+//        fLoGainLast  =  14
+//
+//  Call: SetResolution() to define the resolution of the half-maximum search.
+//        Default: 0.01
+//
+//  Call: SetRiseTime() and SetFallTime() to define the integration ranges 
+//        for the case, the extraction type kIntegral has been chosen.
+//
+//  Call: - SetChargeType(MExtractTimeAndChargeSpline::kAmplitude) for the 
+//          computation of the amplitude at the maximum (default) and extraction 
+//          the position of the maximum (default)
+//          --> no further function evaluation needed
+//        - SetChargeType(MExtractTimeAndChargeSpline::kIntegral) for the 
+//          computation of the integral beneith the spline between fRiseTimeHiGain
+//          from the position of the maximum to fFallTimeHiGain after the position of 
+//          the maximum. The Low Gain is computed with half a slice more at the rising
+//          edge and half a slice more at the falling edge.
+//          The time of the half maximum is returned.
+//          --> needs one function evaluations but is more precise
+//        
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeSpline.h"
+
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractTimeAndChargeSpline);
+
+using namespace std;
+
+const Byte_t  MExtractTimeAndChargeSpline::fgHiGainFirst      = 0;
+const Byte_t  MExtractTimeAndChargeSpline::fgHiGainLast       = 14;
+const Int_t   MExtractTimeAndChargeSpline::fgLoGainFirst      = 1;
+const Byte_t  MExtractTimeAndChargeSpline::fgLoGainLast       = 14;
+const Float_t MExtractTimeAndChargeSpline::fgResolution       = 0.05;
+const Float_t MExtractTimeAndChargeSpline::fgRiseTimeHiGain   = 0.64;
+const Float_t MExtractTimeAndChargeSpline::fgFallTimeHiGain   = 0.76;
+const Float_t MExtractTimeAndChargeSpline::fgLoGainStretch    = 1.5;
+const Float_t MExtractTimeAndChargeSpline::fgOffsetLoGain     = 1.3;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+// Initializes:
+// - fResolution     to fgResolution
+// - fRiseTimeHiGain to fgRiseTimeHiGain
+// - fFallTimeHiGain to fgFallTimeHiGain
+// - Charge Extraction Type to kAmplitude
+// - fLoGainStretch  to fgLoGainStretch
+//
+MExtractTimeAndChargeSpline::MExtractTimeAndChargeSpline(const char *name, const char *title) 
+    : fRiseTimeHiGain(0), fFallTimeHiGain(0), fHeightTm(0.5), fExtractionType(MExtralgoSpline::kIntegralRel)
+{
+
+  fName  = name  ? name  : "MExtractTimeAndChargeSpline";
+  fTitle = title ? title : "Calculate photons arrival time using a fast spline";
+
+  SetResolution();
+  SetLoGainStretch();
+  SetOffsetLoGain(fgOffsetLoGain);
+
+  SetRiseTimeHiGain();
+  SetFallTimeHiGain();
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+
+//-------------------------------------------------------------------
+//
+// Set the ranges
+// In order to set the fNum...Samples variables correctly for the case, 
+// the integral is computed, have to overwrite this function and make an 
+// explicit call to SetChargeType().
+//
+void MExtractTimeAndChargeSpline::SetRange(UShort_t hifirst, UShort_t hilast, Int_t lofirst, Byte_t lolast)
+{
+  MExtractor::SetRange(hifirst, hilast, lofirst, lolast);
+
+  SetChargeType(fExtractionType);
+}
+
+//-------------------------------------------------------------------
+//
+// Set the Charge Extraction type. Possible are:
+// - kAmplitude: Search the value of the spline at the maximum
+// - kIntegral:  Integral the spline from fHiGainFirst to fHiGainLast,   
+//               by counting the edge bins only half and setting the 
+//               second derivative to zero, there.
+//
+void MExtractTimeAndChargeSpline::SetChargeType(MExtralgoSpline::ExtractionType_t typ)
+{
+  fExtractionType = typ;
+
+  InitArrays(fHiGainFirstDeriv.GetSize());
+
+  switch (fExtractionType)
+  {
+  case MExtralgoSpline::kAmplitude:
+  case MExtralgoSpline::kAmplitudeRel:
+  case MExtralgoSpline::kAmplitudeAbs:
+      SetResolutionPerPheHiGain(0.053);
+      SetResolutionPerPheLoGain(0.016);
+      return;
+
+  case MExtralgoSpline::kIntegralRel:
+  case MExtralgoSpline::kIntegralAbs:
+      switch (fWindowSizeHiGain)
+      {
+      case 1:
+          SetResolutionPerPheHiGain(0.041);
+          break;
+      case 2:
+          SetResolutionPerPheHiGain(0.064);
+          break;
+      case 3:
+      case 4:
+          SetResolutionPerPheHiGain(0.050);
+          break;
+      case 5:
+      case 6:
+          SetResolutionPerPheHiGain(0.030);
+          break;
+      default:
+          *fLog << warn << GetDescriptor() << ": Could not set the high-gain extractor resolution per phe for window size "
+              << fWindowSizeHiGain << "... using default!" << endl;
+          SetResolutionPerPheHiGain(0.050);
+          break;
+      }
+
+      switch (fWindowSizeLoGain)
+      {
+      case 1:
+      case 2:
+          SetResolutionPerPheLoGain(0.005);
+          break;
+      case 3:
+      case 4:
+          SetResolutionPerPheLoGain(0.017);
+          break;
+      case 5:
+      case 6:
+      case 7:
+          SetResolutionPerPheLoGain(0.005);
+          break;
+      case 8:
+      case 9:
+          SetResolutionPerPheLoGain(0.005);
+          break;
+      default:
+          *fLog << warn << "Could not set the low-gain extractor resolution per phe for window size "
+              << fWindowSizeLoGain << "... using default!" << endl;
+          SetResolutionPerPheLoGain(0.005);
+          break;
+      }
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// InitArrays
+//
+// Gets called in the ReInit() and initialized the arrays
+//
+Bool_t MExtractTimeAndChargeSpline::InitArrays(Int_t n)
+{
+    // Initialize arrays to the maximum number of entries necessary
+    fHiGainFirstDeriv .Set(n);
+    fHiGainSecondDeriv.Set(n);
+
+    fLoGainFirstDeriv .Set(n);
+    fLoGainSecondDeriv.Set(n);
+
+    fRiseTimeLoGain = fRiseTimeHiGain * fLoGainStretch;
+    fFallTimeLoGain = fFallTimeHiGain * fLoGainStretch;
+
+    switch (fExtractionType)
+    {
+    case MExtralgoSpline::kAmplitude:
+    case MExtralgoSpline::kAmplitudeRel:
+    case MExtralgoSpline::kAmplitudeAbs:
+        fNumHiGainSamples  = 1.;
+        fNumLoGainSamples  = fLoGainLast ? 1. : 0.;
+        fSqrtHiGainSamples = 1.;
+        fSqrtLoGainSamples = 1.;
+        fWindowSizeHiGain  = 1;
+        fWindowSizeLoGain  = 1;
+        fRiseTimeHiGain    = 0.5;
+        break;
+
+    case MExtralgoSpline::kIntegralAbs:
+    case MExtralgoSpline::kIntegralRel:
+        fNumHiGainSamples  = fRiseTimeHiGain + fFallTimeHiGain;
+        fNumLoGainSamples  = fLoGainLast ? fRiseTimeLoGain + fFallTimeLoGain : 0.;
+        fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+        fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+        fWindowSizeHiGain  = TMath::CeilNint(fRiseTimeHiGain + fFallTimeHiGain);
+        fWindowSizeLoGain  = TMath::CeilNint(fRiseTimeLoGain + fFallTimeLoGain);
+        break;
+    }
+
+    return kTRUE;
+}
+
+void MExtractTimeAndChargeSpline::FindTimeAndChargeHiGain2(const Float_t *ptr, Int_t num,
+                                                           Float_t &sum, Float_t &dsum,
+                                                           Float_t &time, Float_t &dtime,
+                                                           Byte_t sat, Int_t maxpos) const
+{
+    // Do some handling if maxpos is last slice!
+    MExtralgoSpline s(ptr, num, fHiGainFirstDeriv.GetArray(), fHiGainSecondDeriv.GetArray());
+
+    s.SetExtractionType(fExtractionType);
+    s.SetHeightTm(fHeightTm);
+    s.SetRiseFallTime(fRiseTimeHiGain, fFallTimeHiGain);
+
+    if (IsNoiseCalculation())
+    {
+        sum  = s.ExtractNoise();
+        dsum = 1;
+        return;
+    }
+
+    s.Extract(maxpos);
+    s.GetTime(time, dtime);
+    s.GetSignal(sum, dsum);
+}
+
+void MExtractTimeAndChargeSpline::FindTimeAndChargeLoGain2(const Float_t *ptr, Int_t num,
+                                                           Float_t &sum,  Float_t &dsum,
+                                                           Float_t &time, Float_t &dtime,
+                                                           Byte_t sat, Int_t maxpos) const
+{
+    MExtralgoSpline s(ptr, num, fLoGainFirstDeriv.GetArray(), fLoGainSecondDeriv.GetArray());
+
+    s.SetExtractionType(fExtractionType);
+    s.SetHeightTm(fHeightTm);
+    s.SetRiseFallTime(fRiseTimeLoGain, fFallTimeLoGain);
+
+    if (IsNoiseCalculation())
+    {
+        sum = s.ExtractNoise();
+        return;
+    }
+
+    s.Extract(maxpos);
+    s.GetTime(time, dtime);
+    s.GetSignal(sum, dsum);
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   Resolution
+//   RiseTimeHiGain
+//   FallTimeHiGain
+//   LoGainStretch
+//   ExtractionType: amplitude, integral
+//
+Int_t MExtractTimeAndChargeSpline::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+  
+  if (IsEnvDefined(env, prefix, "Resolution", print))
+    {
+      SetResolution(GetEnvValue(env, prefix, "Resolution",fResolution));
+      rc  = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "RiseTimeHiGain", print))
+    {
+      SetRiseTimeHiGain(GetEnvValue(env, prefix, "RiseTimeHiGain", fRiseTimeHiGain));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "FallTimeHiGain", print))
+    {
+      SetFallTimeHiGain(GetEnvValue(env, prefix, "FallTimeHiGain", fFallTimeHiGain));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "LoGainStretch", print))
+    {
+      SetLoGainStretch(GetEnvValue(env, prefix, "LoGainStretch", fLoGainStretch));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "HeightTm", print))
+    {
+      fHeightTm = GetEnvValue(env, prefix, "HeightTm", fHeightTm);
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "ExtractionType", print))
+  {
+      TString type = GetEnvValue(env, prefix, "ExtractionType", "");
+      type.ToLower();
+      type = type.Strip(TString::kBoth);
+      if (type==(TString)"amplitude")
+          SetChargeType(MExtralgoSpline::kAmplitude);
+      if (type==(TString)"integralabsolute")
+          SetChargeType(MExtralgoSpline::kIntegralAbs);
+      if (type==(TString)"integralrelative")
+          SetChargeType(MExtralgoSpline::kIntegralRel);
+      rc=kTRUE;
+  }
+
+  return MExtractTimeAndCharge::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeAndChargeSpline.h	(revision 17960)
@@ -0,0 +1,108 @@
+#ifndef MARS_MExtractTimeAndChargeSpline
+#define MARS_MExtractTimeAndChargeSpline
+
+#ifndef MARS_MExtractTimeAndCharge
+#include "MExtractTimeAndCharge.h"
+#endif
+
+#ifndef MARS_MExtralgoSpline
+#include "MExtralgoSpline.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MPedestalPix;
+
+class MExtractTimeAndChargeSpline : public MExtractTimeAndCharge
+{
+private:
+    static const Byte_t  fgHiGainFirst;      //! Default for fHiGainFirst  (now set to: 2)
+    static const Byte_t  fgHiGainLast;       //! Default for fHiGainLast   (now set to: 14)
+    static const Int_t   fgLoGainFirst;      //! Default for fLoGainFirst  (now set to: 2)
+    static const Byte_t  fgLoGainLast;       //! Default for fLoGainLast   (now set to: 14)
+    static const Float_t fgResolution;       //! Default for fResolution   (now set to: 0.003)
+    static const Float_t fgRiseTimeHiGain;   //! Default for fRiseTime     (now set to: 1.5)
+    static const Float_t fgFallTimeHiGain;   //! Default for fFallTime     (now set to: 4.5)
+    static const Float_t fgLoGainStretch;    //! Default for fLoGainStretch    (now set to: 1.5)
+    static const Float_t fgOffsetLoGain;     //! Default for fOffsetLoGain     (now set to 1.7)
+//    static const Float_t fgLoGainStartShift; //! Default for fLoGainStartShift (now set to -1.6)
+
+//    MArrayF fHiGainSignal;                   //! Need fast access to the signals in a float way
+//    MArrayF fLoGainSignal;                   //! Store them in separate arrays
+    MArrayF fHiGainFirstDeriv;               //! High-gain discretized first derivatives
+    MArrayF fLoGainFirstDeriv;               //! Low-gain discretized first derivatives
+    MArrayF fHiGainSecondDeriv;              //! High-gain discretized second derivatives
+    MArrayF fLoGainSecondDeriv;              //! Low-gain discretized second derivatives
+
+    Float_t fResolution;                     // The time resolution in FADC units
+
+    Float_t fRiseTimeHiGain;                 // The usual rise time of the pulse in the high-gain
+    Float_t fFallTimeHiGain;                 // The usual fall time of the pulse in the high-gain
+    Float_t fRiseTimeLoGain;                 // The usual rise time of the pulse in the low-gain
+    Float_t fFallTimeLoGain;                 // The usual fall time of the pulse in the low-gain
+
+    Float_t fLoGainStretch;                  // The stretch of the low-gain w.r.t. the high-gain pulse
+    Float_t fHeightTm;
+
+//    Int_t   fRandomIter;                     //! Counter used to randomize weights for noise calculation
+
+    Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+    Bool_t  InitArrays(Int_t n);
+
+private:
+    MExtralgoSpline::ExtractionType_t fExtractionType;
+
+public:
+    MExtractTimeAndChargeSpline(const char *name=NULL, const char *title=NULL);
+
+    Float_t GetRiseTimeHiGain() const { return fRiseTimeHiGain; }
+    Float_t GetFallTimeHiGain() const { return fFallTimeHiGain; }
+
+    void SetRange(UShort_t hifirst=0, UShort_t hilast=0, Int_t lofirst=0, Byte_t lolast=0 );
+
+    void SetResolution(const Float_t f=fgResolution)  { fResolution  = f;  }
+
+    void SetRiseTimeHiGain(const Float_t f=fgRiseTimeHiGain)
+    {
+        fRiseTimeHiGain    = f;
+        fRiseTimeLoGain    = f*fLoGainStretch;
+        fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+        fWindowSizeHiGain  = TMath::Nint(fRiseTimeHiGain + fFallTimeHiGain);
+    }
+    void SetFallTimeHiGain(const Float_t f=fgFallTimeHiGain)
+    {
+        fFallTimeHiGain    = f;
+        fFallTimeLoGain    = f*fLoGainStretch;
+        fNumHiGainSamples  = fRiseTimeHiGain + fFallTimeHiGain;
+        fNumLoGainSamples  = fLoGainLast ? fRiseTimeLoGain + fFallTimeLoGain : 0.;
+        fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+        fWindowSizeLoGain  = TMath::Nint(fRiseTimeLoGain + fFallTimeLoGain);
+    }
+
+    void SetHeightTm(const Double_t h) { fHeightTm = h; }
+
+    void SetLoGainStretch(const Float_t f=fgLoGainStretch) { fLoGainStretch = f;   }
+
+    void SetChargeType(const MExtralgoSpline::ExtractionType_t typ=MExtralgoSpline::kIntegralRel);
+/*
+    void FindTimeAndChargeHiGain(Byte_t *first, Byte_t *logain, Float_t &sum, Float_t &dsum,
+                                 Float_t &time, Float_t &dtime,
+                                 Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+    void FindTimeAndChargeLoGain(Byte_t *first, Float_t &sum,  Float_t &dsum,
+                                 Float_t &time, Float_t &dtime,
+                                 Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+*/
+    void FindTimeAndChargeHiGain2(const Float_t *firstused, Int_t num, Float_t &sum, Float_t &dsum,
+                                  Float_t &time, Float_t &dtime,
+                                  Byte_t sat, Int_t maxpos) const;
+
+    void FindTimeAndChargeLoGain2(const Float_t *firstused, Int_t num, Float_t &sum,  Float_t &dsum,
+                                  Float_t &time, Float_t &dtime,
+                                  Byte_t sat, Int_t maxpos) const;
+
+    ClassDef(MExtractTimeAndChargeSpline, 5)   // Task to Extract Arrival Times and Charges using a Cubic Spline
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeFastSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeFastSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeFastSpline.cc	(revision 17960)
@@ -0,0 +1,744 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug       05/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeFastSpline
+//
+//   Fast arrival Time extractor using a cubic spline algorithm of Numerical Recipes. 
+//   It returns the position of the half maximum between absolute maximum 
+//   and pedestal of the spline that interpolates the FADC slices.
+//
+//   The precision of the half-maximum searches can be chosen by:
+//   SetPrecision().
+//
+//   The precision of the maximum-finder is fixed to 0.025 FADC units.
+// 
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeFastSpline.h"
+
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MExtractTimeFastSpline);
+
+using namespace std;
+
+const Byte_t  MExtractTimeFastSpline::fgHiGainFirst  = 2;
+const Byte_t  MExtractTimeFastSpline::fgHiGainLast   = 14;
+const Byte_t  MExtractTimeFastSpline::fgLoGainFirst  = 3;
+const Byte_t  MExtractTimeFastSpline::fgLoGainLast   = 14;
+const Float_t MExtractTimeFastSpline::fgResolution   = 0.003;
+const Float_t MExtractTimeFastSpline::fgRiseTime     = 2.;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+// Initializes:
+// - fResolution to fgResolution
+//
+MExtractTimeFastSpline::MExtractTimeFastSpline(const char *name, const char *title) 
+    : fHiGainFirstDeriv(NULL), fLoGainFirstDeriv(NULL),
+      fHiGainSecondDeriv(NULL), fLoGainSecondDeriv(NULL)
+{
+
+  fName  = name  ? name  : "MExtractTimeFastSpline";
+  fTitle = title ? title : "Calculate photons arrival time using a fast spline";
+
+  SetResolution();
+  SetRiseTime  ();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+}
+
+MExtractTimeFastSpline::~MExtractTimeFastSpline()
+{
+  
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - Deletes x, if not NULL
+// - Creates x according to the range
+//
+void MExtractTimeFastSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+
+  if (range < 2)
+    {
+      *fLog << warn << GetDescriptor()
+            << Form("%s%2i%s%2i%s",": Hi-Gain Extraction range [",(int)fHiGainFirst,","
+                    ,fHiGainLast,"] too small, ") << endl;
+      *fLog << warn << GetDescriptor()
+            << " will move higher limit to obtain 4 slices " << endl;
+      SetRange(fHiGainFirst, fHiGainLast+4-range,fLoGainFirst,fLoGainLast);
+      range = fHiGainLast - fHiGainFirst + 1;
+    }
+  
+
+  fHiGainFirstDeriv = new Float_t[range];
+  memset(fHiGainFirstDeriv,0,range*sizeof(Float_t));
+  fHiGainSecondDeriv = new Float_t[range];
+  memset(fHiGainSecondDeriv,0,range*sizeof(Float_t));
+
+  range = fLoGainLast - fLoGainFirst + 1;
+
+  if (range >= 2)
+    {
+      
+      fLoGainFirstDeriv = new Float_t[range];
+      memset(fLoGainFirstDeriv,0,range*sizeof(Float_t));
+      fLoGainSecondDeriv = new Float_t[range];
+      memset(fLoGainSecondDeriv,0,range*sizeof(Float_t));
+
+    }
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeFastSpline::FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+
+  const Int_t range = fHiGainLast - fHiGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t *p = first;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    {
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  p-first;
+        }
+
+      if (*p++ >= fSaturationLimit)
+        {
+          sat++;
+          break;
+        }
+    }
+  
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+    return;
+
+  if (maxpos < 1)
+    {
+      time = -999.;
+      return;
+    }
+  
+  Float_t pp;
+
+  p = first;
+  fHiGainSecondDeriv[0] = 0.;
+  fHiGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      p++;
+      pp = fHiGainSecondDeriv[i-1] + 4.;
+      fHiGainSecondDeriv[i] = -1.0/pp;
+      fHiGainFirstDeriv [i] = *(p+1) - 2.* *(p) + *(p-1);
+      fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+    }
+
+  fHiGainSecondDeriv[range-1] = 0.;
+
+  for (Int_t k=range-2;k>0;k--)
+    fHiGainSecondDeriv[k] = fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k];
+  for (Int_t k=range-2;k>0;k--)
+    fHiGainSecondDeriv[k] /= 6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = (Float_t)*(first+klo);
+  Float_t khicont = (Float_t)*(first+khi);
+  time          = upper;
+  Float_t abmax = khicont;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1 in steps of 0.2 till maxpos-0.2.
+  // If no maximum is found, go to interval maxpos+1.
+  //
+  Float_t higainklo = fHiGainSecondDeriv[klo];
+  Float_t higainkhi = fHiGainSecondDeriv[khi];
+
+  while ( x < upper - 0.3 )
+    {
+      
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*higainklo
+        + (b*b*b-b)*higainkhi;
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+    }
+  
+  //
+  // Search for the absolute maximum from maxpos to maxpos+1 in steps of 0.2
+  //
+  if (time > upper-0.1)
+    {
+
+      upper = (Float_t)maxpos+1.;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+
+      higainklo = fHiGainSecondDeriv[klo];
+      higainkhi = fHiGainSecondDeriv[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*higainklo
+            + (b*b*b-b)*higainkhi;
+          
+          if (y > abmax)
+            {
+              abmax  = y;
+              time   = x;
+            }
+        }
+  }
+
+  //
+  // Now, the time, abmax and khicont and klocont are set correctly within the previous precision.
+  // Try a better precision. 
+  //
+  const Float_t up = time+step-0.035;
+  const Float_t lo = time-step+0.035;
+  const Float_t maxpossave = time;
+  
+  x     = time;
+  a     = upper - x;
+  b     = x - lower;
+
+  step  = 0.025; // step size of 83 ps 
+
+  higainklo = fHiGainSecondDeriv[klo];
+  higainkhi = fHiGainSecondDeriv[khi];
+
+  //
+  // First, try from time up to time+0.2 in steps of 83ps.
+  //
+  while ( x < up )
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*higainklo
+        + (b*b*b-b)*higainkhi;
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+      
+    }
+
+
+  //
+  // Second, try from time down to time-0.2 in steps of 0.04.
+  //
+  x     = maxpossave;
+  //
+  // Test the possibility that the absolute maximum has not been found between
+  // maxpos and maxpos+0.02, then we have to look between maxpos-0.02 and maxpos
+  // which requires new setting of klocont and khicont
+  //
+  if (x < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+      upper--;
+      lower--;
+    }
+  
+  a     = upper - x;
+  b     = x - lower;
+
+  higainklo = fHiGainSecondDeriv[klo];
+  higainkhi = fHiGainSecondDeriv[khi];
+
+  while ( x > lo )
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*higainklo
+        + (b*b*b-b)*higainkhi;
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+    }
+
+#if 0
+  const Float_t pedes   = ped.GetPedestal();
+  const Float_t halfmax = pedes + (abmax - pedes)/2.;
+
+  //
+  // Now, loop from the maximum bin leftward down in order to find the position of the half maximum.
+  // First, find the right FADC slice:
+  // 
+  klo   = maxpos;
+  while (klo > maxpos-fStartBeforeMax)
+    {
+      if (*(first+klo) < (Byte_t)halfmax)
+        break;
+      klo--;
+    }
+
+  //
+  // Loop from the beginning of the slice upwards to reach the halfmax:
+  // With means of bisection:
+  // 
+  x     = (Float_t)klo;
+  a     = 1.;
+  b     = 0.;
+  klocont = (Float_t)*(first+klo);
+  khicont = (Float_t)*(first+klo+1);
+
+  step = 0.5;
+  Bool_t back = kFALSE;
+
+  while (step > fResolution)
+    {
+      
+      if (back)
+        {
+          x -= step;
+          a += step;
+          b -= step;
+        }
+      else
+        {
+          x += step;
+          a -= step;
+          b += step;
+        }
+      
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+      if (y >= halfmax)
+        back = kTRUE;
+      else
+        back = kFALSE;
+
+      step /= 2.;
+      
+    }
+  time  = (Float_t)fHiGainFirst + x;
+
+#endif
+  dtime = 0.035;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeFastSpline::FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+  
+  const Int_t range = fLoGainLast - fLoGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p   = first;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    {
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  p-first;
+        }
+
+      if (*p++ >= fSaturationLimit)
+        {
+          sat++;
+          break;
+        }
+    }
+  
+  if (sat)
+    return;
+
+  if (maxpos < 1)
+    return;
+  
+  Float_t pp;
+
+  p = first;
+  fLoGainSecondDeriv[0] = 0.;
+  fLoGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      p++;
+      pp = fLoGainSecondDeriv[i-1] + 4.;
+      fLoGainSecondDeriv[i] = -1.0/pp;
+      fLoGainFirstDeriv [i] = *(p+1) - 2.* *(p) + *(p-1);
+      fLoGainFirstDeriv [i] = (6.0*fLoGainFirstDeriv[i]-fLoGainFirstDeriv[i-1])/pp;
+    }
+
+  fLoGainSecondDeriv[range-1] = 0.;
+
+  for (Int_t k=range-2;k>0;k--)
+    fLoGainSecondDeriv[k] = fLoGainSecondDeriv[k]*fLoGainSecondDeriv[k+1] + fLoGainFirstDeriv[k];
+  for (Int_t k=range-2;k>0;k--)
+    fLoGainSecondDeriv[k] /= 6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = (Float_t)*(first+klo);
+  Float_t khicont = (Float_t)*(first+khi);
+  time          = upper;
+  Float_t abmax = khicont;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+
+    }
+
+ if (time > upper-0.1)
+    {
+
+      upper = (Float_t)maxpos+1.;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+            + (b*b*b-b)*fLoGainSecondDeriv[khi];
+          
+          if (y > abmax)
+            {
+              abmax  = y;
+              time   = x;
+            }
+        }
+  }
+ 
+  const Float_t up = time+step-0.055;
+  const Float_t lo = time-step+0.055;
+  const Float_t maxpossave = time;
+
+  x     = time;
+  a     = upper - x;
+  b     = x - lower;
+
+  step  = 0.025; // step size of 165 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+      
+    }
+
+  if (time < klo + 0.01)
+    {
+      klo--;
+      khi--;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+      upper--;
+      lower--;
+    }
+  
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+      
+    }
+
+  const Float_t pedes   = ped.GetPedestal();
+  const Float_t halfmax = pedes + (abmax - pedes)/2.;
+
+  //
+  // Now, loop from the maximum bin leftward down in order to find the position of the half maximum.
+  // First, find the right FADC slice:
+  // 
+  klo   = maxpos;
+  while (klo > maxpos-4)
+    {
+      if (*(first+klo) < (Byte_t)halfmax)
+        break;
+      klo--;
+    }
+
+  //
+  // Loop from the beginning of the slice upwards to reach the halfmax:
+  // With means of bisection:
+  // 
+  x     = (Float_t)klo;
+  a     = 1.;
+  b     = 0.;
+  klocont = (Float_t)*(first+klo);
+  khicont = (Float_t)*(first+klo+1);
+  time  = x;
+
+  step = 0.5;
+  Bool_t back = kFALSE;
+
+  while (step > fResolution)
+    {
+      
+      if (back)
+        {
+          x -= step;
+          a += step;
+          b -= step;
+        }
+      else
+        {
+          x += step;
+          a -= step;
+          b += step;
+        }
+      
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+      if (y >= halfmax)
+        back = kTRUE;
+      else
+        back = kFALSE;
+
+      step /= 2.;
+
+    }
+
+  time  = (Float_t)fLoGainFirst + x;
+  dtime = fResolution;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.Resolution: 0.003
+//   MJPedestal.MExtractor.RiseTime:   1.5
+//
+Int_t MExtractTimeFastSpline::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+        SetResolution(GetEnvValue(env, prefix, "Resolution", fResolution));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+        SetRiseTime(GetEnvValue(env, prefix, "RiseTime", fRiseTime));
+        rc = kTRUE;
+    }
+
+    return MExtractTime::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+void MExtractTimeFastSpline::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " Resolution:     " << fResolution << endl;
+    *fLog << " RiseTime:       " << fRiseTime << endl;
+    MExtractTime::Print(o);
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeFastSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeFastSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeFastSpline.h	(revision 17960)
@@ -0,0 +1,51 @@
+#ifndef MARS_MExtractTimeFastSpline
+#define MARS_MExtractTimeFastSpline
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MPedestalPix;
+
+class MExtractTimeFastSpline : public MExtractTime
+{
+private:
+  static const Byte_t  fgHiGainFirst;    // Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t  fgHiGainLast;     // Default for fHiGainLast   (now set to: 14)
+  static const Byte_t  fgLoGainFirst;    // Default for fLOGainFirst  (now set to: 3)
+  static const Byte_t  fgLoGainLast;     // Default for fLoGainLast   (now set to: 14)
+  static const Float_t fgResolution;     // Default for fResolution   (now set to: 0.003)
+  static const Float_t fgRiseTime  ;     // Default for fRiseTime     (now set to: 1.5  )  
+
+  Float_t *fHiGainFirstDeriv;            //!
+  Float_t *fLoGainFirstDeriv;            //!
+  Float_t *fHiGainSecondDeriv;           //!
+  Float_t *fLoGainSecondDeriv;           //!
+
+  Float_t fResolution;                   // The time resolution in FADC units
+  Float_t fRiseTime  ;                   // The rise time of the pulse
+  Byte_t  fStartBeforeMax;               // Slices to start searching for the halfmax before max
+  
+  void FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  void FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+
+  Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MExtractTimeFastSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractTimeFastSpline();
+    
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);      
+  void SetResolution(Float_t f=fgResolution)     { fResolution = f;  }
+  void SetRiseTime  (Float_t f=fgRiseTime  )     { fRiseTime   = f; fStartBeforeMax = (Int_t)(1.5*fRiseTime); }  
+
+  void Print(Option_t *o) const;
+  
+  ClassDef(MExtractTimeFastSpline, 1)   // Task to Extract the Arrival Times using a Fast Spline
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeHighestIntegral.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeHighestIntegral.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeHighestIntegral.cc	(revision 17960)
@@ -0,0 +1,336 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 02/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeHighestIntegral
+//
+//  Calculates the arrival time as the mean time of the fWindowSize time slices
+//  which have the highest integral content.
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeHighestIntegral.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MPedestalPix.h"
+
+ClassImp(MExtractTimeHighestIntegral);
+
+using namespace std;
+
+const Byte_t MExtractTimeHighestIntegral::fgHiGainFirst  =  0;
+const Byte_t MExtractTimeHighestIntegral::fgHiGainLast   = 14;
+const Byte_t MExtractTimeHighestIntegral::fgLoGainFirst  =  3;
+const Byte_t MExtractTimeHighestIntegral::fgLoGainLast   = 14;
+const Byte_t MExtractTimeHighestIntegral::fgHiGainWindowSize = 6;
+const Byte_t MExtractTimeHighestIntegral::fgLoGainWindowSize = 6;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractTimeHighestIntegral::MExtractTimeHighestIntegral(const char *name, const char *title)
+    : fHiGainWindowSize(fgHiGainWindowSize), 
+      fLoGainWindowSize(fgLoGainWindowSize)
+{
+
+  fName  = name  ? name  : "MExtractTimeHighestIntegral";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+//
+void MExtractTimeHighestIntegral::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+  
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  
+  if (range < 2)
+    {
+      *fLog << warn << GetDescriptor()
+            << Form("%s%2i%s%2i%s",": Hi-Gain Extraction range [",(int)fHiGainFirst,","
+                    ,fHiGainLast,"] too small, ") << endl;
+      *fLog << warn << GetDescriptor()
+            << " will move higher limit to obtain 4 slices " << endl;
+      SetRange(fHiGainFirst, fHiGainLast+4-range,fLoGainFirst,fLoGainLast);
+    }
+  
+  if (fLoGainLast != 0)
+    {
+      range = fLoGainLast - fLoGainFirst + 1;
+      
+      if (range < 2)
+        {
+          *fLog << warn << GetDescriptor()
+                << Form("%s%2i%s%2i%s",": Lo-Gain Extraction range [",(int)fLoGainFirst,","
+                        ,fLoGainLast,"] too small, ") << endl;
+          *fLog << warn << GetDescriptor()
+                << " will move lower limit to obtain 4 slices " << endl;
+          SetRange(fHiGainFirst, fHiGainLast,fLoGainFirst,fLoGainLast+4-range);
+        }
+    }
+
+  SetWindowSize(fHiGainWindowSize,fLoGainWindowSize);
+
+  fNumHiGainSamples = fHiGainLast-fHiGainFirst+1;
+  fNumLoGainSamples = fLoGainLast ? fLoGainLast-fLoGainFirst+1 : 0;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd, subtract one
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+void MExtractTimeHighestIntegral::SetWindowSize(Byte_t windowh, Byte_t windowl)
+{
+
+  fHiGainWindowSize = windowh & ~1;
+  fLoGainWindowSize = windowl & ~1;
+
+  if (fHiGainWindowSize != windowh)
+    *fLog << warn << GetDescriptor() << ": Hi Gain window size has to be even, set to: " 
+          << int(fHiGainWindowSize) << " samples " << endl;
+  
+  if (fLoGainWindowSize != windowl)
+    *fLog << warn << GetDescriptor() << ": Lo Gain window size has to be even, set to: " 
+          << int(fLoGainWindowSize) << " samples " << endl;
+    
+  const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
+  const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
+
+  if (fHiGainWindowSize > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fHiGainWindowSize,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fHiGainWindowSize = availhirange;
+    }
+  
+  if (fLoGainWindowSize > availlorange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fLoGainWindowSize,
+                    " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availlorange << endl;
+      fLoGainWindowSize= availlorange;
+    }
+
+  fHiGainWindowSizeSqrt = TMath::Sqrt((Float_t)fHiGainWindowSize);
+  fLoGainWindowSizeSqrt = TMath::Sqrt((Float_t)fLoGainWindowSize);
+}
+
+
+void MExtractTimeHighestIntegral::FindTimeHiGain(Byte_t *ptr, Float_t &time, Float_t &deltatime, Byte_t &sat, const MPedestalPix &ped) const
+{
+
+  const Byte_t *end = ptr + fHiGainLast - fHiGainFirst +1 ;
+
+  Int_t sum=0;    // integral content of the actual window
+  Int_t max = 0;  // highest integral content of all windows
+  
+  //
+  // Calculate the sum of the first fWindowSize slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+  
+  while (p<ptr+fHiGainWindowSize)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+  
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+  
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  Byte_t *ptrmax=ptr;  // pointer to the first slice of the maximum window
+  
+  for (p=ptr; p+fHiGainWindowSize<end; p++)
+    {
+      sum += *(p+fHiGainWindowSize) - *p;
+      
+      if (sum>max)
+	{
+	  max = sum;
+	  ptrmax = p+1;
+	}
+    }
+  
+  // now calculate the time for the maximum window
+  Int_t timesignalsum = 0;
+  Int_t timesquaredsum =0;
+  Int_t timesum =0;
+  
+  for (p=ptrmax; p < ptrmax + fHiGainWindowSize; p++)
+    {
+      timesignalsum += *p*(p-ptr);
+      timesum += p-ptr;
+      timesquaredsum  += (p-ptr)*(p-ptr);
+    }
+  
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t pedrms = ped.GetPedestalRms();
+  const Float_t pedsubsum = max - fHiGainWindowSize*pedes;
+  const Float_t pedsubtimesignalsum = timesignalsum - timesum*pedes;
+
+  time      = pedsubsum != 0 ? pedsubtimesignalsum / pedsubsum  + Float_t(fHiGainFirst): 1;
+  deltatime = pedsubsum != 0 ? pedrms / pedsubsum * sqrt(timesquaredsum - fHiGainWindowSize*time) : 1;
+}
+
+void MExtractTimeHighestIntegral::FindTimeLoGain(Byte_t *ptr, Float_t &time, Float_t &deltatime, Byte_t &sat, const MPedestalPix &ped) const
+{
+
+  const Byte_t *end = ptr + fLoGainLast - fLoGainFirst +1 ;
+
+  Int_t sum=0;    // integral content of the actual window
+  Int_t max = 0;  // highest integral content of all windows
+  
+  //
+  // Calculate the sum of the first fWindowSize slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+  
+  while (p<ptr+fLoGainWindowSize)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+  
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+  
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  Byte_t *ptrmax=ptr;  // pointer to the first slice of the maximum window
+  
+  for (p=ptr; p+fLoGainWindowSize<end; p++)
+    {
+      sum += *(p+fLoGainWindowSize) - *p;
+      
+      if (sum>max)
+	{
+	  max = sum;
+	  ptrmax = p+1;
+	}
+    }
+  
+  // now calculate the time for the maximum window
+  Int_t timesignalsum = 0;
+  Int_t timesquaredsum =0;
+  Int_t timesum =0;
+  
+  for (p=ptrmax; p < ptrmax + fLoGainWindowSize; p++)
+    {
+      timesignalsum += *p*(p-ptr);
+      timesum += p-ptr;
+      timesquaredsum  += (p-ptr)*(p-ptr);
+    }
+  
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t pedrms = ped.GetPedestalRms();
+  const Float_t pedsubsum = max - fLoGainWindowSize*pedes;
+  const Float_t pedsubtimesignalsum = timesignalsum - timesum*pedes;
+
+  time      = pedsubsum != 0 ? pedsubtimesignalsum / pedsubsum  + Float_t(fLoGainFirst) : 1;
+  deltatime = pedsubsum != 0 ? pedrms / pedsubsum * sqrt(timesquaredsum - fLoGainWindowSize*time) : 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//
+Int_t MExtractTimeHighestIntegral::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Byte_t hw = fHiGainWindowSize;
+    Byte_t lw = fLoGainWindowSize;
+
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+        hw = GetEnvValue(env, prefix, "HiGainWindowSize", hw);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+        lw = GetEnvValue(env, prefix, "LoGainWindowSize", lw);
+        rc = kTRUE;
+    }
+
+    if (rc)
+        SetWindowSize(hw, lw);
+
+    return MExtractTime::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+void MExtractTimeHighestIntegral::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " Windows: Hi-Gain=" << (int)fHiGainWindowSize << "  Lo-Gain=" << (int)fLoGainWindowSize << endl;
+    MExtractTime::Print(o);
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeHighestIntegral.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeHighestIntegral.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeHighestIntegral.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MExtractTimeHighestIntegral
+#define MARS_MExtractTimeHighestIntegral
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MExtractTimeHighestIntegral : public MExtractTime
+{
+private:
+  static const Byte_t fgHiGainFirst;
+  static const Byte_t fgHiGainLast;
+  static const Byte_t fgLoGainFirst;
+  static const Byte_t fgLoGainLast;
+  static const Byte_t fgHiGainWindowSize;
+  static const Byte_t fgLoGainWindowSize;
+
+  Byte_t  fHiGainWindowSize;            // Number of gains in window
+  Float_t fHiGainWindowSizeSqrt;        // Sqaure root of number of gains in window
+  Byte_t  fLoGainWindowSize;            // Number of gains in window
+  Float_t fLoGainWindowSizeSqrt;        // Sqaure root of number of gains in window
+
+  void FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  void FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+
+  Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+  MExtractTimeHighestIntegral(const char *name=NULL, const char *title=NULL);
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);        
+  void SetWindowSize(Byte_t windowh=fgHiGainWindowSize,
+                     Byte_t windowl=fgLoGainWindowSize);
+
+  void Print(Option_t *o="") const;
+
+  ClassDef(MExtractTimeHighestIntegral, 1) // Task to Extract the Arrival Times As the mean time of the fWindowSize time slices
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeSpline.cc	(revision 17960)
@@ -0,0 +1,203 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Sebastian Raducci 12/2003 <mailto:raducci@fisica.uniud.it>
+!              Markus Gaug       04/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeSpline
+//
+//   This is a task that calculates the arrival times of photons. 
+//   It returns the absolute maximum of the spline that interpolates
+//   the FADC slices 
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeSpline.h"
+#include "MCubicSpline.h"
+
+#include "MGeomCam.h"
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MExtractTimeSpline);
+
+using namespace std;
+
+const Byte_t MExtractTimeSpline::fgHiGainFirst  = 0;
+const Byte_t MExtractTimeSpline::fgHiGainLast   = 14;
+const Byte_t MExtractTimeSpline::fgLoGainFirst  = 3;
+const Byte_t MExtractTimeSpline::fgLoGainLast   = 14;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractTimeSpline::MExtractTimeSpline(const char *name, const char *title) 
+    : fXHiGain(NULL), fXLoGain(NULL)
+{
+
+  fName  = name  ? name  : "MExtractTimeSpline";
+  fTitle = title ? title : "Calculate photons arrival time using a spline";
+    
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+}
+
+MExtractTimeSpline::~MExtractTimeSpline()
+{
+  
+  if (fXHiGain)
+    delete fXHiGain;
+  if (fXLoGain)
+    delete fXLoGain;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - Deletes x, if not NULL
+// - Creates x according to the range
+//
+void MExtractTimeSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  if (fXHiGain)
+    delete fXHiGain;
+
+  if (fXLoGain)
+    delete fXLoGain;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+
+  if (range < 2)
+    {
+      *fLog << warn << GetDescriptor()
+            << Form("%s%2i%s%2i%s",": Hi-Gain Extraction range [",(int)fHiGainFirst,","
+                    ,fHiGainLast,"] too small, ") << endl;
+      *fLog << warn << GetDescriptor()
+            << " will move higher limit to obtain 4 slices " << endl;
+      SetRange(fHiGainFirst, fHiGainLast+4-range,fLoGainFirst,fLoGainLast);
+      range = fHiGainLast - fHiGainFirst + 1;
+    }
+  
+  fXHiGain = new Byte_t[range+1];
+  for (Int_t i=0; i<range+1; i++)
+    fXHiGain[i] = i;
+  
+  range = fLoGainLast - fLoGainFirst + 1;
+
+  if (range >= 2)
+    {
+      
+      fXLoGain = new Byte_t[range+1];
+      for (Int_t i=0; i<range+1; i++)
+        fXLoGain[i] = i;
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeSpline::FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+  
+  const Int_t range = fHiGainLast - fHiGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t *p = first;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+
+  //
+  // Initialize the spline
+  //
+  MCubicSpline spline(first,fXHiGain,kTRUE,range,0.0,0.0);  
+
+  //
+  // Now find the maximum  
+  //
+  Double_t abMaximum = spline.EvalAbMax();
+  Double_t maximum = spline.EvalMax();
+  const Double_t pedestal = ped.GetPedestal();
+  const Double_t halfMax = (maximum + pedestal)/2.;
+  time = (halfMax > pedestal) ? (Float_t ) spline.FindVal(halfMax,abMaximum,'l') + (Float_t)fHiGainFirst : 0.0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeSpline::FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+  
+  const Int_t range = fLoGainLast - fLoGainFirst + 1;
+
+  if (range < 2)
+    return;
+
+  const Byte_t *end = first + range;
+  Byte_t *p = first;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+
+  //
+  // Initialize the spline
+  //
+  MCubicSpline spline(first,fXLoGain,kTRUE,range,0.0,0.0);  
+
+  //
+  // Now find the maximum  
+  //
+  Double_t abMaximum = spline.EvalAbMax();
+  Double_t maximum = spline.EvalMax();
+  const Double_t pedestal = ped.GetPedestal();
+  const Double_t halfMax = (maximum + pedestal)/2.;
+
+  time = (halfMax > pedestal) ? (Float_t )spline.FindVal(halfMax,abMaximum,'l') + (Float_t)fLoGainFirst : 0.0;
+}
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractTimeSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractTimeSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractTimeSpline.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MExtractTimeSpline
+#define MARS_MExtractTimeSpline
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MPedestalPix;
+
+class MExtractTimeSpline : public MExtractTime
+{
+private:
+  static const Byte_t fgHiGainFirst;
+  static const Byte_t fgHiGainLast;
+  static const Byte_t fgLoGainFirst;
+  static const Byte_t fgLoGainLast;
+
+  Byte_t *fXHiGain;
+  Byte_t *fXLoGain;  
+  
+  void FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  void FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  
+public:
+
+  MExtractTimeSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractTimeSpline();
+    
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);      
+  
+  ClassDef(MExtractTimeSpline, 0)   // Task to Extract the Arrival Times using a Spline
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalBlindPixel.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalBlindPixel.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalBlindPixel.cc	(revision 17960)
@@ -0,0 +1,143 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MExtractedSignalBlindPixel
+//
+// The storage container of the extracted signal of the calibration Blind Pixel(s). 
+// Additionally, the number of saturated Slices are stored. 
+// There is place for various blind pixels set into the camera in  July. Default 
+// is one blind pixel.
+//
+// Default values for the extracted signals are: gkSignalInitializer
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractedSignalBlindPixel.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractedSignalBlindPixel);
+
+using namespace std;
+
+const Int_t MExtractedSignalBlindPixel::gkSignalInitializer = 99999;
+// ------------------------------------------------------------------------
+//
+//
+// Sets:
+// - the dimenstion of fBlindPixelIdx to 1
+// - the dimenstion of fExtractedSignal to 1
+// - the dimenstion of fNumSaturated to 1
+// - the dimenstion of fPed. to 1;      
+// - the dimenstion of fPedErr. to 1;
+// - the dimenstion of fPedRms. to 1;   
+// - the dimenstion of fPedRmsErr. to 1;
+//
+// Calls:
+// - Clear()
+//
+MExtractedSignalBlindPixel::MExtractedSignalBlindPixel(const char* name, const char* title)
+{
+
+  fName  = name  ? name  : "MExtractedSignalBlindPixel";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  fBlindPixelIdx.Set(1);
+  fExtractedSignal.Set(1);
+  fNumSaturated.Set(1);
+
+  fPed.Set(1);      
+  fPedErr.Set(1);   
+  fPedRms.Set(1);   
+  fPedRmsErr.Set(1);
+
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Set values of:
+// - fNumSaturated   
+// - fExtractedSignal
+// to gkSignalInitializer
+//
+void MExtractedSignalBlindPixel::Clear(Option_t *o)
+{
+
+  for (Int_t i=0;i<fBlindPixelIdx.GetSize();i++)
+    {
+      fNumSaturated   .AddAt(gkSignalInitializer,i);
+      fExtractedSignal.AddAt(gkSignalInitializer,i);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Set number num of used FADC slices, starting from (including) first 
+//
+void MExtractedSignalBlindPixel::SetUsedFADCSlices(const Byte_t first, const Byte_t num)   
+{
+  fFirst          = first; 
+  fNumFADCSamples = num;
+}
+
+// --------------------------------------------------------------------------------------------
+//
+// Returns true, if fExtractedSignal is greater or equal 0 and smaller than gkSignalInitializer
+//
+Bool_t MExtractedSignalBlindPixel::IsValid( const Int_t i ) const
+{
+    return fExtractedSignal.At(i) >= 0 && fExtractedSignal.At(i) <  gkSignalInitializer;
+}
+
+// --------------------------------------------------------------------------------------------
+//
+// Prints for all stored blind pixels the ID, the signal and the number of saturated slices
+//
+void MExtractedSignalBlindPixel::Print(Option_t *o) const
+{
+
+  for (Int_t i=0;i<fBlindPixelIdx.GetSize();i++)
+    {
+      
+      *fLog << "Blind Pixel ID: " << fBlindPixelIdx.At(i)
+            << ": Signal: " << fExtractedSignal.At(i)
+            << " Saturated Slices: " <<  fNumSaturated.At(i)
+            << endl;
+    }
+}
+
+// ------------------------------------------------------------------------------------
+//
+// Returns true if the extraction type. Available are: kAmplitude, kIntegral and kFilter
+// The flags kIntegral and kFilter may be set both. 
+//
+Bool_t MExtractedSignalBlindPixel::IsExtractionType( const MExtractBlindPixel::ExtractionType_t typ )
+{
+  
+  return TESTBIT( fExtractionType, typ );
+
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalBlindPixel.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalBlindPixel.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalBlindPixel.h	(revision 17960)
@@ -0,0 +1,102 @@
+#ifndef MARS_MExtractedSignalBlindPixel
+#define MARS_MExtractedSignalBlindPixel
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef MARS_MExtractBlindPixel
+#include <MExtractBlindPixel.h>
+#endif
+
+class MExtractedSignalBlindPixel : public MParContainer
+{
+private:
+
+  static const Int_t gkSignalInitializer; //! Initializer for variables
+
+  TArrayI fBlindPixelIdx;                 // Array Blind Pixel IDs
+  TArrayF fExtractedSignal;               // Array Extracted signals per Blind Pixel ID
+  TArrayI fNumSaturated;                  // Array Number of saturated slices per Blind Pixel ID 
+  					  
+  TArrayF fPed;                           // Array Pedestal per Blind Pixel IDs                               
+  TArrayF fPedErr;                        // Array Pedestal Error per Blind Pixel ID          
+  TArrayF fPedRms;                        // Array Pedestal RMS per Blind Pixel ID 
+  TArrayF fPedRmsErr;                     // Array Pedestal RMS Error per Blind Pixel ID 
+					  
+  Byte_t  fFirst;                         // First FADC extraction slice
+  Byte_t  fNumFADCSamples;                // Number of summed FADC slices
+  Byte_t  fExtractionType;                // What extraction type has been chosen?
+  
+public:
+
+  MExtractedSignalBlindPixel(const char* name=NULL, const char* title=NULL);
+
+  void Clear(Option_t *o="");
+  void Print(Option_t *o="") const;
+  
+  // Getters
+  Int_t   GetBlindPixelIdx   ( const Int_t i=0 )  const { return fBlindPixelIdx.At(i)    ; }  
+  Float_t GetExtractedSignal ( const Int_t i=0 )  const { return fExtractedSignal.At(i)  ; }
+  Int_t   GetNumBlindPixels  ()                   const { return fBlindPixelIdx.GetSize(); }
+  Int_t   GetNumSaturated    ( const Int_t i=0 )  const { return fNumSaturated.At(i)     ; }
+  Byte_t  GetNumFADCSamples  ()                   const { return fNumFADCSamples         ; }
+
+  Float_t GetPed             ( const Int_t i=0 )  const { return fPed.At(i)              ; }
+  Float_t GetPedErr          ( const Int_t i=0 )  const { return fPedErr.At(i)           ; }
+  Float_t GetPedRms          ( const Int_t i=0 )  const { return fPedRms.At(i)           ; }
+  Float_t GetPedRmsErr       ( const Int_t i=0 )  const { return fPedRmsErr.At(i)        ; }
+
+  Bool_t  IsExtractionType   ( const MExtractBlindPixel::ExtractionType_t typ );
+  Bool_t  IsValid            ( const Int_t i=0 )  const;   
+
+  // Setter
+  void SetExtractionType( const Byte_t b=0 )            { fExtractionType  = b           ; }
+  void SetNumFADCSamples( const Byte_t num )            { fNumFADCSamples  = num         ; }    
+  void SetUsedFADCSlices( const Byte_t first, const Byte_t num );
+
+  void SetBlindPixelIdx  ( const Int_t i,   const Int_t nr=0)      {
+    if (nr>fBlindPixelIdx.GetSize()-1)
+      {
+	fBlindPixelIdx.Set(nr+1);
+	fExtractedSignal.Set(nr+1);
+	fNumSaturated.Set(nr+1);
+	fPed.Set(nr+1);
+	fPedErr.Set(nr+1);
+	fPedRms.Set(nr+1);
+	fPedRmsErr.Set(nr+1);
+      }
+    fBlindPixelIdx.AddAt(i,nr); }
+  void SetExtractedSignal( const Float_t f, const Int_t nr=0 )     {
+    fExtractedSignal.AddAt(f,nr); }
+  void SetNumSaturated   ( const Int_t i,   const Int_t nr=0 )     {
+    fNumSaturated.AddAt(i,nr); }
+  void SetPed            ( const Float_t f, const Int_t nr=0 )     {
+    fPed.AddAt(f,nr); }
+  void SetPedErr         ( const Float_t f, const Int_t nr=0 )     {
+    fPedErr.AddAt(f,nr); }
+  void SetPedRms         ( const Float_t f, const Int_t nr=0 )     {
+    fPedRms.AddAt(f,nr); }
+  void SetPedRmsErr      ( const Float_t f, const Int_t nr=0 )     {
+    fPedRmsErr.AddAt(f,nr); }
+
+  ClassDef(MExtractedSignalBlindPixel, 3)	// Storage Container for extracted signal of Blind Pixel
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalCam.cc	(revision 17960)
@@ -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): 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-2006
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MExtractedSignalCam
+//
+// Hold the Extracted Signal information for all pixels in the camera
+//
+// Class Version 3:
+// ----------------
+//  - fNdf
+//
+// Class Version 4:
+// ----------------
+//  - Byte_t fFirstUsedSliceLoGain;         // First Low Gain FADC used for extraction (incl.)
+//  + Int_t  fFirstUsedSliceLoGain;         // First Low Gain FADC used for extraction (incl.)
+//
+/////////////////////////////////////////////////////////////////////////////
+#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->R__FOR_EACH(MParContainer, SetLogStream)(lg);
+    MParContainer::SetLogStream(lg);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MExtractedSignalCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MExtractedSignalCam
+//
+Int_t MExtractedSignalCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel index)
+//
+MExtractedSignalPix &MExtractedSignalCam::operator[](Int_t i)
+{
+    return *static_cast<MExtractedSignalPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel index)
+//
+const MExtractedSignalPix &MExtractedSignalCam::operator[](Int_t i) const
+{
+    return *static_cast<MExtractedSignalPix*>(fArray->UncheckedAt(i));
+}
+
+/*
+Float_t MExtractedSignalCam::GetProb( const Int_t pixidx )   const
+{ 
+  if (pixidx > GetSize()-1)
+    return -1.;
+  
+  return TMath::Prob((*this)[pixidx].GetChisquare(),fNdf); 
+}
+*/
+
+void MExtractedSignalCam::Clear(Option_t *o)
+{
+    fArray->R__FOR_EACH(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->IsLoGainValid() && ! pix->IsHiGainValid())
+            continue;
+
+        *fLog << idx << ": ";
+	pix->Print();
+    }
+}
+
+Bool_t MExtractedSignalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx>=GetSize())
+        return kFALSE;
+
+    const MExtractedSignalPix &pix = (*this)[idx];
+
+    switch (type)
+    {
+    case 0:
+        val = pix.GetExtractedSignalHiGain();
+        return pix.IsHiGainValid() && !pix.IsHiGainSaturated();
+
+    case 1:
+        val = pix.GetExtractedSignalHiGainError();
+        return val>0;
+
+    case 2:
+        val = pix.GetExtractedSignalLoGain();
+        return pix.IsLoGainValid() && !pix.IsLoGainSaturated();
+
+    case 3:
+        val = pix.GetExtractedSignalLoGainError();
+        return val>0;
+
+        // This is for the case the signal has been
+        // extracted from lo- and hi-gain
+    case 4:
+        // Lo- and hi-gain must be successfully extracted
+        if (!pix.IsLoGainValid() || !pix.IsHiGainValid())
+            return kFALSE;
+
+        // Lo- and hi-gain must not be saturated
+        if (pix.IsLoGainSaturated() || pix.IsHiGainSaturated())
+            return kFALSE;
+
+        // Both signals must have a positive value
+        if (pix.GetExtractedSignalLoGain()<=0 || pix.GetExtractedSignalHiGain()<=0)
+            return kFALSE;
+
+        //val = log10(pix.GetExtractedSignalHiGain())-log10(pix.GetExtractedSignalLoGain());
+        //return TMath::Abs(val-1)<0.4;
+        val = pix.GetExtractedSignalHiGain()/pix.GetExtractedSignalLoGain();
+        //return val>4 && val<30;
+        return val>4 && val<35;
+
+    case 5:
+        val = pix.GetExtractedSignalHiGain();
+        return pix.IsHiGainValid() && !pix.IsHiGainSaturated() && val>100;
+
+    default:
+	return kFALSE;
+    }
+
+    return kFALSE;
+}
+
+void MExtractedSignalCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MExtractedSignaCam::DrawPixelContent - not available." << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalCam.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalCam.h	(revision 17960)
@@ -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;        // First High Gain FADC used for extraction (incl.)
+  Int_t  fFirstUsedSliceLoGain;        // First Low Gain FADC used for extraction (incl.)
+  
+  Byte_t fLastUsedSliceHiGain;         // Last High Gain FADC used for extraction (incl.)
+  Byte_t fLastUsedSliceLoGain;         // Last Low Gain FADC used for extraction (incl.)
+  
+  Float_t fUsedWindowHiGain;           // High Gain FADC extraction window 
+  Float_t fUsedWindowLoGain;           // Low Gain FADC extraction window 
+
+public:
+    MExtractedSignalCam(const char *name=NULL, const char *title=NULL);
+    ~MExtractedSignalCam();
+
+    void    Print(Option_t *o="") const;
+    void    Clear(Option_t *o="");
+    void    Reset() { Clear(); }
+
+    void    InitSize(const UInt_t i);
+    Int_t   GetSize () const;
+
+    Byte_t  GetFirstUsedSliceHiGain()    const { return fFirstUsedSliceHiGain; }
+    Int_t   GetFirstUsedSliceLoGain()    const { return fFirstUsedSliceLoGain; }
+    Byte_t  GetLastUsedSliceHiGain()     const { return fLastUsedSliceHiGain;  }
+    Byte_t  GetLastUsedSliceLoGain()     const { return fLastUsedSliceLoGain;  }
+
+    Float_t GetNumUsedHiGainFADCSlices() const { return fUsedWindowHiGain;     }
+    Float_t GetNumUsedLoGainFADCSlices() const { return fUsedWindowLoGain;     }
+
+    void    SetLogStream     ( MLog *lg  );
+    void    SetUsedFADCSlices(Byte_t firsth, Byte_t lasth, Float_t winh,
+                              Int_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, 4)	// Storage Container for extracted signals in the camera
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalPINDiode.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalPINDiode.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalPINDiode.cc	(revision 17960)
@@ -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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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;
+// ------------------------------------------------------------------------
+//
+// 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: -1. 
+//
+MExtractedSignalPINDiode::MExtractedSignalPINDiode(const char* name, const char* title)
+{
+
+  fName  = name  ? name  : "MExtractedSignalPINDiode";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values to -1.
+//
+void MExtractedSignalPINDiode::Clear(Option_t *o)
+{
+
+  fExtractedSignal          = -1.;
+  fExtractedSignalErr       = -1.;
+  fExtractedTime            = -1.;
+  fExtractedTimeErr         = -1.; 
+  fExtractedSigma           = -1.; 
+  fExtractedSigmaErr        = -1.; 
+  fExtractedChi2            = -1.; 
+
+  fSaturated  = kFALSE;
+  
+}
+
+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::SetExtractedSigma(const Float_t sig, const Float_t sigerr)   
+{
+  fExtractedSigma    = sig; 
+  fExtractedSigmaErr = sigerr;
+}
+
+void MExtractedSignalPINDiode::SetExtractedTime(const Float_t sig, const Float_t sigerr)   
+{
+  fExtractedTime    = sig; 
+  fExtractedTimeErr = sigerr;
+}
+
+Bool_t MExtractedSignalPINDiode::IsValid() const
+{
+  if (fSaturated)
+    return kFALSE;
+  
+  return fExtractedSignal >= 0. || fExtractedSignalErr >= 0.;
+}
+
+void MExtractedSignalPINDiode::Print(Option_t *o) const
+{
+  *fLog << Form(" Signal: %4.2f+-%4.2f",fExtractedSignal,fExtractedSignalErr) 
+        << Form(" Arr.Time: %4.2f+-%4.2f",fExtractedTime,fExtractedTimeErr) 
+        << Form(" Sigma: %4.2f+-%4.2f",fExtractedSigma,fExtractedSigmaErr) 
+        << Form(" Chi2: %5.2f",fExtractedChi2) 
+        << Form(" Saturation: %s",fSaturated ? "yes" : "no")
+        << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalPINDiode.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalPINDiode.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalPINDiode.h	(revision 17960)
@@ -0,0 +1,57 @@
+#ifndef MARS_MExtractedSignalPINDiode
+#define MARS_MExtractedSignalPINDiode
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MExtractedSignalPINDiode : public MParContainer
+{
+private:
+
+  Float_t fExtractedSignal;    // Extracted signal amplitude
+  Float_t fExtractedSignalErr; // Error extracted signal amplitude
+  Float_t fExtractedTime;      // Position of signal amplitude
+  Float_t fExtractedTimeErr;   // Error position of signal amplitude
+  Float_t fExtractedSigma;     // Width Gauss fit 
+  Float_t fExtractedSigmaErr;  // Error of width
+  Float_t fExtractedChi2;      // Chi2 Gauss fit   
+ 
+  Byte_t fNumFADCSamples;      // Number of used FADC slices
+  Byte_t fFirst;               // First FADC slice to start extraction
+  
+  Bool_t fSaturated;           // FADC saturation occurrance flag
+
+public:
+
+  MExtractedSignalPINDiode(const char* name=NULL, const char* title=NULL);
+  
+  void Clear(Option_t *o="");
+  
+  // 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 GetExtractedSigma()     const { return fExtractedSigma;        }
+  Float_t GetExtractedSigmaErr()  const { return fExtractedSigmaErr;     }
+  Float_t GetExtractedChi2()      const { return fExtractedChi2;         }  
+  Byte_t  GetNumFADCSamples()     const { return fNumFADCSamples;        }
+  
+  Bool_t  IsValid()    const;   
+  
+  // Print
+  void Print(Option_t *o="") const;
+
+  // Setter
+  void SetExtractedSignal(const Float_t sig, const Float_t sigerr);
+  void SetExtractedSigma(  const Float_t sig, const Float_t sigerr);
+  void SetExtractedTime(  const Float_t sig, const Float_t sigerr);
+  void SetExtractedChi2(  const Float_t chi ) { fExtractedChi2 = chi; }
+  void SetSaturation  (   const Bool_t b=kTRUE) { fSaturated = b;  }
+  void SetUsedFADCSlices( const Byte_t first, const Byte_t num);
+
+  ClassDef(MExtractedSignalPINDiode, 2)	// Storage Container for Extracted Signal information of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalPix.cc	(revision 17960)
@@ -0,0 +1,111 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  12/2003 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MExtractedSignalPix
+//
+// This is the storage container to hold informations about the pedestal
+// (offset) value of one Pixel (PMT).
+//
+// Class Version 3:
+// ----------------
+//  - fIsLoGainUsed
+//  - fChisquare
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractedSignalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractedSignalPix);
+
+using namespace std;
+
+static const Float_t gkSignalInitializer = -99999.9;
+
+// ------------------------------------------------------------------------
+//
+// MExtractedSignalPix holds the extracted signal (HiGain and LoGain) 
+// of the FADC slices and its error. 
+//
+// Additionally, the number of saturated HiGain and LoGain Slices are stored. 
+// 
+// Default values for the extracted signals are: 99999.9 
+//
+MExtractedSignalPix::MExtractedSignalPix(const char* name, const char* title)
+{
+  fName  = name  ? name  : "MExtractedSignalPix";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  Clear();
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MExtractedSignalPix::Clear(Option_t *o)
+{
+  fExtractedSignalHiGain      = gkSignalInitializer;
+  fExtractedSignalHiGainError = -1;
+  fExtractedSignalLoGain      = gkSignalInitializer;
+  fExtractedSignalLoGainError = -1;
+  
+  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;
+}
+
+void MExtractedSignalPix::SetGainSaturation(Byte_t higain, Byte_t logain)
+{
+    fNumHiGainSaturated = higain;
+    fNumLoGainSaturated = logain;
+}
+
+void MExtractedSignalPix::Print(Option_t *o) const
+{
+    *fLog << " Signal: " << fExtractedSignalHiGain
+        << " +- " << fExtractedSignalHiGainError
+        << " Nr. Sat. Hi Gain: " <<  fNumHiGainSaturated
+        << " Nr. Sat. Lo Gain: " <<  fNumLoGainSaturated
+        << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractedSignalPix.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractedSignalPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractedSignalPix.h	(revision 17960)
@@ -0,0 +1,50 @@
+#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
+
+  Byte_t fNumHiGainSaturated;          // Number of how many hi-gain slices saturated
+  Byte_t fNumLoGainSaturated;          // Number of how many lo-gain slices saturated
+
+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=0);
+  void SetExtractedSignal( Float_t sighi, Float_t sighierr,Float_t siglo, Float_t sigloerr);
+  void SetGainSaturation ( Byte_t higain, Byte_t logain=0);
+    
+  // 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 IsHiGainSaturated()              const { return fNumHiGainSaturated>0;        }
+  Bool_t IsLoGainSaturated()              const { return fNumLoGainSaturated>0;        }
+
+  Bool_t IsLoGainValid()                  const { return fExtractedSignalLoGainError>=0; }
+  Bool_t IsHiGainValid()                  const { return fExtractedSignalHiGainError>=0; }
+
+  ClassDef(MExtractedSignalPix, 3) // Storage Container for Extracted Signal information of one pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MExtractor.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractor.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractor.cc	(revision 17960)
@@ -0,0 +1,369 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+// MExtractor
+// ==========
+//
+//   Base class for the signal extractors, used the functions 
+//   FindSignalHiGain() and FindSignalLoGain() to extract the signal and 
+//   substract the pedestal value    
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+//   The signal extractor classes can be setup from an environmental
+//   setup file. For more information see ReadEnv and MEvtLoop::ReadEnv
+//
+//
+// IMPORTANT: For all classes you derive from MExtractor make sure that:
+//    - Print() is correctly implemented
+//    - Clone() works
+//    - Class Version number != 0 and the I/O works PERFECTLY
+//    - only data members which are necessary for the setup (not the ones
+//      created in PreProcess and Process) are written
+//    - the version number is maintained!
+//    - If the flag fNoiseCalculation is set, the signal extractor should 
+//      calculate the pure noise contriubtion from a fixed window in time.
+//
+// The following figure gives and example of possible inheritance trees. 
+// An extractor class can inherit from each of the following base classes:
+//    - MExtractor
+//    - MExtractTime
+//    - MExtractTimeAndCharge
+//
+//Begin_Html
+/*
+<img src="images/ExtractorClasses.gif">
+*/
+//End_Html
+//
+//
+// Class Version 6:
+// ----------------
+//  + Float_t fResolutionPerPheHiGain; // Extractor-dependent charge resolution per phe for high-gain (see TDAS-0502).
+//  + Float_t fResolutionPerPheLoGain; // Extractor-dependent charge resolution per phe for low-gain  (see TDAS-0502).
+//
+// Class Version 7:
+// ----------------
+//  - Byte_t fHiLoLast;                // Number of slices in fLoGainSamples counted for the High-Gain signal
+//
+// Class Version 8:
+// ----------------
+//  - Byte_t fSaturationLimit;
+//  + Uint_t fSaturationLimit;
+//
+// Class Version 9:
+// ----------------
+//  - MPedestalCam fPedestals
+//
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MExtractedSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractor.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MRawRunHeader.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+//#include "MPedestalSubtractEvt.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractor);
+
+using namespace std;
+
+const UInt_t  MExtractor::fgSaturationLimit = 245;
+const char   *MExtractor::fgNameSignalCam   = "MExtractedSignalCam";
+const Float_t MExtractor::fgOffsetLoGain    = 1.51;   // 5 ns
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set: 
+// - all pointers to NULL
+// - all variables to 0
+// - fSaturationLimit to fgSaturationLimit
+// - fNameSignalCam to fgNameSignalCam
+// - fNoiseCalculation to kFALSE 
+//
+MExtractor::MExtractor(const char *name, const char *title)
+    : fResolutionPerPheHiGain(0), fResolutionPerPheLoGain(0),
+    fSignals(NULL), fRawEvt(NULL), fRunHeader(NULL), fSignal(NULL),
+    fLoGainLast(0), fNumHiGainSamples(0), fNumLoGainSamples(0)
+{
+    fName  = name  ? name  : "MExtractor";
+    fTitle = title ? title : "Base class for signal extractors";
+
+    SetNameSignalCam();
+    SetOffsetLoGain();
+    SetSaturationLimit();
+    SetNoiseCalculation(kFALSE);
+}
+
+void MExtractor::SetRange(UShort_t hifirst, UShort_t hilast, Int_t lofirst, Byte_t lolast)
+{
+    fHiGainFirst = hifirst;
+    fHiGainLast  = hilast;
+
+    fLoGainFirst = lofirst;
+    fLoGainLast  = lolast;
+}
+
+//-----------------------------------------------------------------------
+//
+// - Set the variable fHiLoLast to 0 (will be initialized later in ReInit()
+// - Get the pointers to: 
+//     MRawEvtData
+//     MRawRunHeader
+//
+Int_t MExtractor::PreProcessStd(MParList *pList)
+{
+
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSignal = (MPedestalSubtractedEvt*)pList->FindObject(AddSerialNumber("MPedestalSubtractedEvt"));
+    if (!fSignal)
+    {
+        *fLog << err << AddSerialNumber("MPedestalSubtractedEvt") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MExtractor::PreProcess(MParList *pList)
+{
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj("MExtractedSignalCam",AddSerialNumber(fNameSignalCam));
+    if (!fSignals)
+        return kFALSE;
+
+    return PreProcessStd(pList);
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit searches for:
+// -  MRawRunHeader::GetNumSamplesHiGain()
+// -  MRawRunHeader::GetNumSamplesLoGain()
+//
+// In case that the variable fLoGainLast is smaller than 
+// the even part of the number of samples obtained from the run header, a
+// warning is given an the range is set back accordingly. A call to:  
+// - SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast-diff) 
+// is performed in that case. The variable diff means here the difference 
+// between the requested range (fLoGainLast) and the available one. Note that 
+// the functions SetRange() are mostly overloaded and perform more checks, 
+// modifying the ranges again, if necessary.
+//
+// In case that the variable fHiGainLast is smaller than the available range 
+// obtained from the run header, a warning is given that a part of the low-gain 
+// samples are used for the extraction of the high-gain signal. 
+//
+Bool_t MExtractor::ReInit(MParList *pList)
+{
+    const Int_t numl = fRunHeader->GetNumSamplesLoGain();
+    const Int_t numh = fRunHeader->GetNumSamplesHiGain();
+    const Int_t num  = numh+numl;
+
+    if (fHiGainLast>=num)
+    {
+        *fLog << err << "MExtractor: ERROR - Last hi-gain slice " << (int)fHiGainLast << " must not exceed " << num-1 << endl;
+        return kFALSE;
+    }
+    if (fLoGainLast>=num)
+    {
+        *fLog << err << "MExtractor: ERROR - Last lo-gain slice " << (int)fLoGainLast << " must not exceed " << num-1 << endl;
+        return kFALSE;
+    }
+
+    if (numl==0)
+    {
+        *fLog << inf << "No lo-gains... resetting lo-gain range";
+        fLoGainFirst=0;
+        fLoGainLast =0;
+        *fLog << "." << endl;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container.
+//
+Int_t MExtractor::Process()
+{
+    return kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MExtractor::StreamPrimitive(ostream &out) const
+{
+  out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+  out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+  
+  if (fSaturationLimit!=fgSaturationLimit)
+  {
+      out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+      out << (int)fSaturationLimit << ");" << endl;
+  }
+  
+  out << "   " << GetUniqueName() << ".SetRange(";
+  out << (int)fHiGainFirst;
+  out << ", " << (int)fHiGainLast;
+  out << ", " << (int)fLoGainFirst;
+  out << ", " << (int)fLoGainLast;
+  out << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MExtractor.HiGainFirst: 5
+//   MJPedestal.MExtractor.LoGainFirst: 5
+//   MJPedestal.MExtractor.HiGainLast:  10
+//   MJPedestal.MExtractor.LoGainLast:  10
+//   MJPedestal.MExtractor.SaturationLimit: 88
+//
+Int_t MExtractor::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    UShort_t hf = fHiGainFirst;
+    UShort_t hl = fHiGainLast;
+    Int_t    lf = fLoGainFirst;
+    Byte_t   ll = fLoGainLast;
+
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "HiGainFirst", print))
+    {
+        hf = GetEnvValue(env, prefix, "HiGainFirst", hf);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainFirst", print))
+    {
+        lf = GetEnvValue(env, prefix, "LoGainFirst", lf);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "HiGainLast", print))
+    {
+        hl = GetEnvValue(env, prefix, "HiGainLast", hl);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainLast", print))
+    {
+        ll = GetEnvValue(env, prefix, "LoGainLast", ll);
+        rc = kTRUE;
+    }
+
+    SetRange(hf, hl, lf, ll);
+
+    if (IsEnvDefined(env, prefix, "OffsetLoGain", print))
+    {
+        SetOffsetLoGain(GetEnvValue(env, prefix, "OffsetLoGain", fOffsetLoGain));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "SaturationLimit", print))
+    {
+        SetSaturationLimit(GetEnvValue(env, prefix, "SaturationLimit", (Int_t)fSaturationLimit));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "NoiseCalculation", print))
+    {
+        SetNoiseCalculation(GetEnvValue(env, prefix, "NoiseCalculation", fNoiseCalculation));
+        rc = kTRUE;
+    }
+
+    // Be carefull: Returning kERROR is not forseen in derived classes
+    return rc;
+}
+
+void MExtractor::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ":" << endl;
+
+    *fLog << " Hi Gain Range:      " << Form("%2d %2d", fHiGainFirst, fHiGainLast) << endl;
+    *fLog << " Saturation Lim:     " << Form("%3d", fSaturationLimit) << endl;
+    if (HasLoGain())
+    {
+        *fLog << " Lo Gain Range:      " << Form("%2d %2d", fLoGainFirst, fLoGainLast) << endl;
+        *fLog << " Num Samples Hi/Lo:  " << Form("%2.1f %2.1f", fNumHiGainSamples, fNumLoGainSamples) << endl;
+    }
+}
Index: branches/Mars_McMismatchStudy/msignal/MExtractor.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MExtractor.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MExtractor.h	(revision 17960)
@@ -0,0 +1,119 @@
+#ifndef MARS_MExtractor
+#define MARS_MExtractor
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractor                                                              //
+//                                                                         //
+// Base class for the signal extractors                                    //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalSubtractedEvt;
+class MExtractedSignalCam;
+
+class MExtractor : public MTask
+{
+private:
+  static const Float_t fgOffsetLoGain;     //! Default for fOffsetLoGain (now set to 1.51 (= 5ns)
+  
+  Bool_t  fNoiseCalculation;               //! Flag if extractor determines noise contribution from pedestal file.
+
+  Float_t fResolutionPerPheHiGain;         // Extractor-dependent charge resolution per phe for high-gain (see TDAS-0502).
+  Float_t fResolutionPerPheLoGain;         // Extractor-dependent charge resolution per phe for low-gain  (see TDAS-0502).
+  
+protected:
+  static const UInt_t  fgSaturationLimit;  //! Default for fSaturationLimit (now set to: 254)
+  static const char   *fgNameSignalCam;    //! "MExtractedSignalCam"
+  
+  Float_t fOffsetLoGain;                   // Offset of the low-gain signal w.r.t. the High-Gain slices
+
+  MExtractedSignalCam *fSignals;           //! Extracted signal of all pixels in the camera
+
+  MRawEvtData         *fRawEvt;            //! Raw event data (time slices)
+  MRawRunHeader       *fRunHeader;         //! RunHeader information
+
+  MPedestalSubtractedEvt *fSignal;         //!
+
+  UShort_t fHiGainFirst;                   // First FADC slice nr. to extract the High Gain signal
+  UShort_t fHiGainLast;                    // Last FADC slice nr. to extract the High Gain signal
+  Int_t    fLoGainFirst;                   // First FADC slice nr. to extract the Low Gain signal
+  Byte_t   fLoGainLast;                    // Last FADC slice nr. to extract the Low Gain signal
+                                           
+//  Byte_t   fHiLoLast;                      // Number of slices in fLoGainSamples counted for the High-Gain signal
+                                           
+  Float_t  fNumHiGainSamples;              // Number High Gain FADC slices used to extract the signal
+  Float_t  fNumLoGainSamples;              // Number Low  Gain FADC slices used to extract the signal
+                                           
+  Float_t  fSqrtHiGainSamples;             // Sqrt. nr. High Gain FADC slices used to extract the signal
+  Float_t  fSqrtLoGainSamples;             // Sqrt. nr. Low  Gain FADC slices used to extract the signal
+
+  UInt_t   fSaturationLimit;               // Highest FADC slice value until being declared saturated
+
+  TString  fNameSignalCam;                 // Name of the 'MExtractedSignalCam' container
+
+  // MExtractor
+  virtual void FindSignalHiGain(Byte_t */*firstused*/, Byte_t */*lowgain*/, Float_t &/*sum*/, Byte_t &/*sat*/) const { }
+  virtual void FindSignalLoGain(Byte_t */*firstused*/, Float_t &/*sum*/, Byte_t &/*sat*/) const { }
+
+  void SetResolutionPerPheHiGain(Float_t f) { fResolutionPerPheHiGain=f; }
+  void SetResolutionPerPheLoGain(Float_t f) { fResolutionPerPheLoGain=f; }
+
+  Int_t   PreProcessStd(MParList *pList);
+
+  // MTask
+  Int_t   PreProcess( MParList *pList );
+  Bool_t  ReInit    ( MParList *pList );
+  Int_t   Process   ();
+  void    StreamPrimitive(std::ostream &out) const;
+  Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+
+public:
+  MExtractor(const char *name=NULL, const char *title=NULL);
+  
+  // getter
+  UShort_t GetHiGainFirst()      const { return fHiGainFirst;      }
+  UShort_t GetHiGainLast ()      const { return fHiGainLast ;      }
+  Int_t    GetLoGainFirst()      const { return fLoGainFirst;      }
+  Byte_t   GetLoGainLast ()      const { return fLoGainLast ;      }
+  Float_t  GetNumHiGainSamples() const { return fNumHiGainSamples; }
+  Float_t  GetNumLoGainSamples() const { return fNumLoGainSamples; }
+  Float_t  GetOffsetLoGain()     const { return fOffsetLoGain;     }
+  Float_t  GetResolutionPerPheHiGain() const { return fResolutionPerPheHiGain; }
+  Float_t  GetResolutionPerPheLoGain() const { return fResolutionPerPheLoGain; }
+  UInt_t   GetSaturationLimit() const { return fSaturationLimit; }
+
+  Bool_t  HasLoGain() const { return fLoGainFirst>0 || fLoGainLast>0; }
+  Bool_t  IsNoiseCalculation () const { return fNoiseCalculation; }
+
+  // Setter
+  Float_t SetResolutionPerPheHiGain() const { return fResolutionPerPheHiGain; }
+  Float_t SetResolutionPerPheLoGain() const { return fResolutionPerPheLoGain; }
+
+  virtual void SetRange(UShort_t hifirst=0, UShort_t hilast=0, Int_t lofirst=0, Byte_t lolast=0);
+
+  void SetOffsetLoGain    ( const Float_t  f=fgOffsetLoGain          ) { fOffsetLoGain     = f;    }
+  void SetSaturationLimit ( const UInt_t lim=fgSaturationLimit       ) { fSaturationLimit  = lim;  }
+  void SetNameSignalCam   ( const char *name=fgNameSignalCam ) { fNameSignalCam    = name; }
+  void SetNoiseCalculation( const Bool_t   b=kTRUE                   ) { fNoiseCalculation = b;    }
+
+  // TObject
+  void Clear(Option_t * = "")
+    {
+      fHiGainFirst = fHiGainLast = fLoGainFirst = fLoGainLast = /*fHiLoLast =*/ 0;
+    }
+
+  void Print(Option_t *o="") const; //*MENU*
+
+  ClassDef(MExtractor, 9) // Signal Extractor Base Class
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MFilterData.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MFilterData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MFilterData.cc	(revision 17960)
@@ -0,0 +1,150 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 2013<mailto:thomas.bretz@phys.ethz.ch>
+!
+!   Copyright: MAGIC Software Development, 2013
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MFilterData
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MFilterData.h"
+
+#include <algorithm>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MFilterData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MFilterData::MFilterData(const char *name, const char *title)
+    : fSignalIn(NULL), fSignalOut(NULL),
+    fNameSignalIn("MPedestalSubtractedEvt"),
+    fNameSignalOut("FilteredEvt")
+{
+    fName  = name  ? name  : "MFilterData";
+    fTitle = title ? title : "Class to filter the data";
+
+    // Default weights
+    fWeights.resize(14);
+    fWeights[ 0] = -0.217305;
+    fWeights[ 1] = -0.213277;
+    fWeights[ 2] = -0.193537;
+    fWeights[ 3] = -0.181686;
+    fWeights[ 4] = -0.15356;
+    fWeights[ 5] = -0.129926;
+    fWeights[ 6] = -0.0792033;
+    fWeights[ 7] = -0.0219311;
+    fWeights[ 8] =  0.0550301;
+    fWeights[ 9] =  0.127364;
+    fWeights[10] =  0.206711;
+    fWeights[11] =  0.246864;
+    fWeights[12] =  0.271012;
+    fWeights[13] =  0.283444;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFilterData::PreProcess(MParList *pList)
+{
+    fSignalIn = (MPedestalSubtractedEvt*)pList->FindObject(fNameSignalIn);
+    if (!fSignalIn)
+    {
+        *fLog << err << fNameSignalIn << " [MPedestalSubtractedEvt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSignalOut = (MPedestalSubtractedEvt*)pList->FindCreateObj("MPedestalSubtractedEvt", fNameSignalOut);
+    if (!fSignalOut)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+void MFilterData::Filter(UShort_t npix, UShort_t nroi, const Float_t *beg, Float_t *out) const
+{
+    const uint16_t nw = fWeights.size();
+
+    const float *begw = fWeights.data();
+    const float *endw = fWeights.data()+nw;
+
+    for (const Float_t *in=beg; in<beg+nroi*npix; )
+    {
+        // Loop from 0 to nroi-nw-1
+        const Float_t *end = in+nroi-nw;
+        for (; in<end; in++, out++)
+        {
+            // This works even if out==in
+            const float *w = begw;
+            const float *p = in;
+
+            // Loop over weights
+            *out = *p++ * *w++;
+            while (w<endw)
+                *out += *p++ * *w++;
+        }
+
+        // skip last nw samples
+        in += nw;
+        out += nw;
+
+        // Loop from nroi-nw to nroi
+        // end = in+nw;
+        // for (; in<end; in++)
+        // {
+        //     Double_t sum = 0;
+        //     for (uint16_t j=0; j<nw; j++)
+        //         sum += in[min(j, last)]*fWeights[j];
+        //     *out++ = sum;
+        // }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MFilterData::Process()
+{
+    // FIXME: Implement an alternative: the simple filter
+    // (p[10]+p[11]+p[12]) - (p[0]+p[1]+p[2])
+    // Store first sum in ring-buffer
+
+    const uint16_t nroi = fSignalIn->GetNumSamples();
+    const uint16_t npix = fSignalIn->GetNumPixels();
+
+    if (fSignalIn!=fSignalOut)
+        fSignalOut->InitSamples(nroi); // contains setting to 0
+
+    Filter(npix, nroi, fSignalIn->GetSamples(), fSignalOut->GetSamples());
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/msignal/MFilterData.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MFilterData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MFilterData.h	(revision 17960)
@@ -0,0 +1,41 @@
+#ifndef MARS_MFilterData
+#define MARS_MFilterData
+
+#include<vector>
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MPedestalSubtractedEvt;
+
+class MFilterData : public MTask
+{
+private:
+    MPedestalSubtractedEvt *fSignalIn;  //! Input container
+    MPedestalSubtractedEvt *fSignalOut; //! Output container
+
+    TString fNameSignalIn;
+    TString fNameSignalOut;
+
+    std::vector<float> fWeights;
+
+    Int_t  PreProcess(MParList *pList);
+    //Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MFilterData(const char *name=NULL, const char *title=NULL);
+
+    void SetNameSignalIn(const char *name="MPedestalSubtractedEvt")  { fNameSignalIn=name; }
+    void SetNameSignalOut(const char *name="MPedestalSubtractedEvt") { fNameSignalOut=name; }
+
+    void SetWeights(const std::vector<float> &w) { fWeights = w; }
+    void SetAverage(const UInt_t n) { fWeights.assign(n, 1./n); }
+
+    void Filter(UShort_t npix, UShort_t nroi, const Float_t *beg, Float_t *out) const;
+
+    ClassDef(MFilterData, 0) // Class to filter the calibrated data
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MSignalCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MSignalCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MSignalCalc.cc	(revision 17960)
@@ -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  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2007
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MSignalCalc
+//
+//   This is a task which calculates the number of photons from the FADC
+//   time slices. At the moment it integrates simply the FADC values.
+//
+//  Input Containers:
+//   MRawEvtData, MPedestalCam
+//
+//  Output Containers:
+//   MSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MSignalCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MSignalCam.h"
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+#include "MRawEvtPixelIter.h"
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MSignalCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. b is the number of slices before the maximum slice,
+// a the number of slices behind the maximum slice which is taken as signal.
+//
+MSignalCalc::MSignalCalc(Byte_t b, Byte_t a, const char *name, const char *title)
+    : fBefore(b), fAfter(a)
+{
+    fName  = name  ? name  : "MSignalCalc";
+    fTitle = title ? title : "Task to calculate Cerenkov photons from raw data";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawRunHeader
+//  - MRawEvtData
+//  - MPestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//  - MSignalCam
+//
+Int_t MSignalCalc::PreProcess(MParList *pList)
+{
+    fSkip = 0;
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << dbginf << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawEvt = (MPedestalSubtractedEvt*)pList->FindObject("MPedestalSubtractedEvt");
+    if (!fRawEvt)
+    {
+        *fLog << dbginf << "MPedestalSubtractedEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MSignalCam*)pList->FindCreateObj("MSignalCam");
+    if (!fCerPhotEvt)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Bool_t MSignalCalc::ReInit(MParList *pList)
+{
+    fPedestals=NULL;
+
+    // This must be done in ReInit because in PreProcess the
+    // headers are not available
+    if (fRunHeader->IsMonteCarloRun())
+        return kTRUE;
+
+    fPedestals = (MPedestalCam*)pList->FindCreateObj("MPedestalCam");
+    if (!fPedestals)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MSignalCam container.
+//
+Int_t MSignalCalc::Process()
+{
+    if (!fPedestals)
+        return kTRUE;
+
+    const Int_t npix = fRawEvt->GetNumPixels();
+    const Int_t nhi  = fRunHeader->GetNumSamplesHiGain();
+    const Int_t nlo  = fRunHeader->GetNumSamplesLoGain();
+
+    for (int i=0; i<npix; i++)
+    {
+        USample_t *raw = fRawEvt->GetSamplesRaw(i);
+
+        USample_t *ptr   = raw;
+        USample_t *max   = ptr+fRawEvt->GetMaxPos(i, 0, nhi-1);
+	USample_t *end   = ptr+nhi;
+        USample_t *first = max-fBefore;
+        USample_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)  // FIXME!!!!
+            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 (nlo>0 && sat==0 && ishi)
+        {
+            // Area: x9
+            ptr = raw+nhi;
+            end = ptr+nlo;
+
+            sumb = 0;   // sum background
+            sqb  = 0;   // sum sqares background
+            nb   = 0;
+
+            while (ptr<end)
+            {
+                // Background already caced from hi-gains!
+                sumb += *ptr;
+                sqb  += *ptr* *ptr;
+                nb++;
+                ptr++;
+            }
+        }
+
+        if (nlo>0 && sat>1 && !ishi)
+        {
+            // Area: x9
+            ptr = raw+nhi;
+            max = ptr+fRawEvt->GetMaxPos(i, nhi, nhi+nlo-1);
+
+            if (*max>250) // FIXME!!!!
+            {
+                fSkip++;
+                return kCONTINUE;
+            }
+
+            end   = ptr+nlo;
+            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  = nb==0 ? 0 : (float)sumb/nb;       // background
+        //Float_t sb = (float)sumsb/nsb;     // signal+background
+
+        Float_t msb  = nb==0 ? 0 : (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 squares signal
+
+        //Float_t mss  = (float)sqs/nsb;     // mean quare signal
+        //Float_t sigs = sqrt(mss-s*s);      // sigma signal
+
+        //if (sat>1)
+        //    s *= 11.3;
+
+        //fCerPhotEvt->AddPixel(idx, s, sigs);
+
+        // Preliminary: Do not overwrite pedestals calculated by
+        // MMcPedestalCopy and MMcPedestalNSBAdd
+        (*fPedestals)[i].Set(b/fRunHeader->GetScale(), sigb/fRunHeader->GetScale());
+    }
+
+    //fCerPhotEvt->FixSize();
+    //fCerPhotEvt->SetReadyToSave();
+
+    fPedestals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+Int_t MSignalCalc::PostProcess()
+{
+    if (GetNumExecutions()==0 || fSkip==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fSkip << " (" << setw(3) << (int)(fSkip*100/GetNumExecutions()) << "%) Evts skipped due to: lo gain saturated." << endl;
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/msignal/MSignalCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MSignalCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MSignalCalc.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MSignalCalc
+#define MARS_MSignalCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MPedestalCam;
+class MSignalCam;
+class MRawRunHeader;
+class MPedestalSubtractedEvt;
+
+class MSignalCalc : public MTask
+{
+private:
+    MRawRunHeader          *fRunHeader;  // RunHeader information
+    MPedestalSubtractedEvt *fRawEvt;     // raw event data (time slices)
+    MSignalCam             *fCerPhotEvt; // Cerenkov Photon Event used for calculation
+    MPedestalCam           *fPedestals;  // Pedestals of all pixels in the camera
+
+    Byte_t fBefore;
+    Byte_t fAfter;
+
+    Int_t fSkip;                //!
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MSignalCalc(Byte_t b=2, Byte_t a=5, const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSignalCalc, 0)   // Task to calculate cerenkov photons from raw data
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MSignalCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MSignalCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MSignalCam.cc	(revision 17960)
@@ -0,0 +1,699 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2010
+!
+! Version 2:
+! ----------
+!
+! Made persistent (the correct contets is not guranteed, because it is
+! calculated from the outside (e.g. in MImgCleanStd))
+!
+!    Short_t       fNumIslands;                  //!
+!    Short_t       fNumSinglePixels;             //!
+!    Float_t       fSizeSinglePixels;            //!
+!    Float_t       fSizeSubIslands;              //!
+!    Float_t       fSizeMainIsland;              //!
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//            
+// MSignalCam
+//
+// Class Version 1:
+// ----------------
+//  - first version
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSignalCam.h"
+
+#include <math.h>
+#include <limits.h>
+#include <fstream>
+
+#include <TArrayI.h>
+#include <TArrayD.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+ClassImp(MSignalCam);
+ClassImp(MSignalCamIter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MSignalPix object for each pixel in the event
+//
+MSignalCam::MSignalCam(const char *name, const char *title) /*: fNumPixels(0)*/
+{
+    fName  = name  ? name  : "MSignalCam";
+    fTitle = title ? title : "(Number of Photon)-Event Information";
+
+    fPixels = new TClonesArray("MSignalPix", 0);
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy contants of obj into this instance.
+//
+void MSignalCam::Copy(TObject &obj) const
+{
+    MSignalCam &cam = static_cast<MSignalCam&>(obj);
+
+    cam.fNumIslands = fNumIslands;
+    cam.fNumSinglePixels = fNumSinglePixels;
+    cam.fSizeSinglePixels = fSizeSinglePixels;
+    cam.fSizeSubIslands = fSizeSubIslands;
+    cam.fSizeMainIsland = fSizeMainIsland;
+
+    cam.fNumPixelsSaturatedHiGain = fNumPixelsSaturatedHiGain;
+    cam.fNumPixelsSaturatedLoGain = fNumPixelsSaturatedLoGain;
+
+    cam.fPixels->Delete();
+
+    const UInt_t n = GetNumPixels();
+
+    cam.InitSize(n);
+
+    for (UInt_t i=0; i<n; i++)
+        new ((*cam.fPixels)[i]) MSignalPix((*this)[i]);
+}
+
+// --------------------------------------------------------------------------
+//
+// reset counter and delete netries in list.
+//
+void MSignalCam::Reset()
+{
+    fNumSinglePixels  =  0;
+    fSizeSinglePixels =  0;
+    fSizeSubIslands   =  0;
+    fSizeMainIsland   =  0;
+    fNumIslands       = -1;
+
+    fNumPixelsSaturatedHiGain = -1;
+    fNumPixelsSaturatedLoGain = -1;
+
+    fPixels->R__FOR_EACH(TObject, Clear)();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Dump the cerenkov photon event to *fLog
+//
+void MSignalCam::Print(Option_t *) const
+{
+    const Int_t entries = fPixels->GetEntries();
+
+    *fLog << GetDescriptor() << dec << endl;
+    *fLog << " Number of Pixels: " << GetNumPixels() << "(" << entries << ")" << endl;
+
+    for (Int_t i=0; i<entries; i++ )
+        (*this)[i].Print();
+}
+
+// --------------------------------------------------------------------------
+//
+//   Count and return the number of unmapped pixels
+//
+Int_t MSignalCam::GetNumPixelsUnmapped() const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n <= 0)
+        return -1;
+
+    Int_t cnt=0;
+    for (UInt_t i=0; i<n; i++)
+    {
+        if ((*this)[i].IsPixelUnmapped())
+            cnt++;
+    }
+
+    return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum number of photons  of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetNumPhotonsMin(const MGeomCam *geom) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n <= 0)
+        return -5.;
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval < minval)
+            minval = testval;
+    }
+
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum number of photons of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetNumPhotonsMax(const MGeomCam *geom) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n <= 0)
+        return 50.;
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons();
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum ratio of photons/error
+//
+Float_t MSignalCam::GetRatioMin(const MGeomCam *geom) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n <= 0)
+        return -5.;
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons()/pix.GetErrorPhot();
+        if (geom)
+            testval *= geom->GetPixRatioSqrt(i);
+
+        if (testval < minval)
+            minval = testval;
+    }
+
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum ratio of photons/error
+//
+Float_t MSignalCam::GetRatioMax(const MGeomCam *geom) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n <= 0)
+        return -5.;
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons()/pix.GetErrorPhot();
+        if (geom)
+            testval *= geom->GetPixRatioSqrt(i);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+
+    return maxval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum of error
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetErrorPhotMin(const MGeomCam *geom) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n <= 0)
+        return 50.;
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetErrorPhot();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval < minval)
+            minval = testval;
+    }
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum ratio of photons/error
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetErrorPhotMax(const MGeomCam *geom) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n <= 0)
+        return 50.;
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetErrorPhot();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+MSignalPix *MSignalCam::AddPixel(Int_t idx, Float_t nph, Float_t er)
+{
+    MSignalPix *pix = static_cast<MSignalPix*>((*fPixels)[idx]);
+    pix->Set(nph, er);
+    return pix;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function recursively finds all pixels of one island and assigns
+// the number num as island number to the pixel.
+//
+//  1) Check whether a pixel with the index idx exists, is unused
+//     and has not yet a island number assigned.
+//  2) Assign the island number num to the pixel
+//  3) Loop over all its neighbors taken from the geometry geom. For all
+//     neighbors recursively call this function (CalcIsland)
+//  4) Sum the size of the pixel and all neighbors newly assigned
+//     (by CalcIsland) to this island
+//
+// Returns the sum of the pixel size.
+//
+Double_t MSignalCam::CalcIsland(const MGeomCam &geom, Int_t idx, Int_t num)
+{
+    // Get the pixel information of a pixel with this index
+    MSignalPix &pix = (*this)[idx];
+
+    // If an island number was already assigned to this pixel... do nothing.
+    if (pix.GetIdxIsland()>=0)
+        return 0;
+
+    // If the pixel is an unused pixel... do nothing.
+    if (!pix.IsPixelUsed())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix.SetIdxIsland(num);
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeom &gpix = geom[idx];
+
+    // Get the size of this pixel
+    Double_t size = pix.GetNumPhotons();
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        size += CalcIsland(geom, gpix.GetNeighbor(i), num);
+
+    // return size of this (sub)cluster
+    return size;
+}
+
+// --------------------------------------------------------------------------
+//
+// Each pixel which is maked as used is assigned an island number
+// (starting from 0). A pixel without an island number assigned
+// has island number -1.
+//
+// The index 0 corresponds to the island with the highest size (sum
+// of GetNumPhotons() in island). The size is decreasing with
+// increasing indices.
+//
+// The information about pixel neighbory is taken from the geometry
+// MGeomCam geom;
+//
+// You can access this island number of a pixel with a call to
+// MSignalPix->GetIdxIsland. The total number of islands available
+// can be accessed with MSignalCam->GetNumIslands.
+//
+// CalcIslands returns the number of islands found. If an error occurs,
+// eg the geometry has less pixels than the highest index stored, -1 is
+// returned.
+//
+Int_t MSignalCam::CalcIslands(const MGeomCam &geom)
+{
+    const UInt_t numpix = GetNumPixels();
+
+    if (/*fMaxIndex<0 ||*/ numpix==0)
+    {
+        *fLog << err << "ERROR - MSignalCam doesn't contain pixels!" << endl;
+        fNumIslands = 0;
+        return -1;
+    }
+/*
+    if ((UInt_t)fMaxIndex>=geom.GetNumPixels())
+    {
+        *fLog << err << "ERROR - MSignalCam::CalcIslands: Size mismatch - geometry too small!" << endl;
+        return -1;
+    }
+  */
+    // Create a list to hold the sizes of the islands (The maximum
+    // number of islands possible is roughly fNumPixels/4)
+    TArrayD size(numpix/3);
+
+    // Calculate Islands
+    Int_t   n=0;
+    Float_t totsize = 0;
+
+    for (UInt_t idx=0; idx<numpix; idx++)
+    {
+        const MSignalPix &pix = (*this)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // This 'if' is necessary (although it is done in GetIsland, too)
+        // because otherwise the counter (n) would be wrong.
+        // So only 'start' a new island for used pixels (selected by
+        // using the Iterator) which do not yet belong to another island.
+        if (pix.GetIdxIsland()<0)
+        {
+            // Don't put this in one line! n is used twice...
+            const Double_t sz = CalcIsland(geom, idx/*pix->GetPixId()*/, n);
+            size[n++] = sz;
+            totsize += sz;
+        }
+    }
+
+    // Create an array holding the indices
+    TArrayI idxarr(n);
+
+    // Sort the sizes descending
+    TMath::Sort(n, size.GetArray(), idxarr.GetArray(), kTRUE);
+
+    // Replace island numbers by size indices -- After this
+    // islands indices are sorted by the island size
+    for (UInt_t idx=0; idx<numpix; idx++)
+    {
+        MSignalPix &pix = (*this)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        const Short_t i = pix.GetIdxIsland();
+
+        // Find new index
+        Short_t j;
+        for (j=0; j<n; j++)
+            if (idxarr[j]==i)
+                break;
+
+        pix.SetIdxIsland(j==n ? -1 : j);
+    }
+
+    // Now assign number of islands found
+    fNumIslands     = n;
+    fSizeSubIslands = n>0 ? totsize-size[idxarr[0]] : 0;
+    fSizeMainIsland = n>0 ? size[idxarr[0]] : 0;
+
+    // return number of island
+    return fNumIslands;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compares the cleaning (fRing and fIsCore) of this object and the
+// argument. Return the result (kFALSE if different).
+//
+// If differences are found the pixels (the pixel from this object first)
+// is printed.
+//
+Bool_t MSignalCam::CompareCleaning(const MSignalCam &cam) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n != cam.GetNumPixels())
+    {
+        *fLog << warn << "MSignalCam::CompareCleaning - Number of pixels mismatch." << endl;
+        return kFALSE;
+    }
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &p = (*this)[i];
+        const MSignalPix &q = cam[i];
+
+        if (p.GetRing()==q.GetRing() && p.IsPixelCore()==q.IsPixelCore())
+            continue;
+
+        *fLog << warn << "MSignalCam::CompareCleaning - Pixel #" << i << " mismatch." << endl;
+        p.Print();
+        q.Print();
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compares the islands (fIdxIsland) of this object and the
+// argument. Return the result (kFALSE if different).
+//
+// If differences are found the pixels (the pixel from this object first)
+// is printed.
+//
+Bool_t MSignalCam::CompareIslands(const MSignalCam &cam) const
+{
+    const UInt_t n = GetNumPixels();
+
+    if (n != cam.GetNumPixels())
+    {
+        *fLog << warn << "MSignalCam::CompareIslands - Number of pixels mismatch." << endl;
+        return kFALSE;
+    }
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &p = (*this)[i];
+        const MSignalPix &q = cam[i];
+
+        if (p.GetIdxIsland()==q.GetIdxIsland())
+            continue;
+
+        *fLog << warn << "MSignalCam::CompareIslands - Pixel #" << i << " mismatch." << endl;
+        p.Print();
+        q.Print();
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns, depending on the type flag:
+//
+//  0: Number of Photons*PixRatio <default>
+//  1: Error*sqrt(PixRatio)
+//  2: Cleaning level = Num Photons*sqrt(PixRatio)/Error
+//  3: Number of Photons
+//  4: Error
+//  5: Island index
+//  6: arrival time of mapped pixels
+//  7: arrival time if signa avove 20phe
+//  8: arrival time
+// 10: as 0, but returns kFALSE if signal <=0
+// 11: as 8, but returns kFALSE if signal <=0
+//
+Bool_t MSignalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx<0 || (UInt_t)idx>GetNumPixels())
+        return kFALSE;
+
+    const MSignalPix &pix = (*this)[idx];
+
+    // Used inlcudes status unampped
+    if (!pix.IsPixelUsed() && (type<6 || type==8))
+        return kFALSE;
+
+    const Double_t ratio = cam.GetPixRatio(idx);
+
+    switch (type)
+    {
+    case 1: // scaled error of phtoons
+        val = pix.GetErrorPhot()*TMath::Sqrt(ratio);
+        return kTRUE;
+
+    case 2: // significance of number of photons
+        if (pix.GetErrorPhot()<=0)
+            return kFALSE;
+        val = pix.GetNumPhotons()*TMath::Sqrt(ratio)/pix.GetErrorPhot();
+        return kTRUE;
+
+    case 3: // number of photo electrons
+        val = pix.GetNumPhotons();
+        break;
+
+    case 4: // error of signal
+        val = pix.GetErrorPhot();
+        break;
+
+    case 5: // index of island
+        val = pix.GetIdxIsland();
+        break;
+
+    case 6: // arrival time of mapped pixels only
+        if (pix.IsPixelUnmapped())
+            return kFALSE;
+        val = pix.GetArrivalTime();
+        break;
+
+    case 7: // pulse position above 50phe
+        // The number of photons is not scaled with the ratio because
+        // otherwise to many large pixels survive (maybe because the
+        // fluctuations scale different than expected)
+        if (pix.IsPixelUnmapped() || pix.GetNumPhotons()<50)
+            return kFALSE;
+        val = pix.GetArrivalTime();
+        break;
+
+    case 8: // arrival time
+        val = pix.GetArrivalTime();
+        break;
+
+        /*
+    case 10: // lo gain time
+        if (pix.IsPixelUnmapped() || !pix.IsLoGainUsed() ||
+            pix.GetNumPhotons()<320)
+            return kFALSE;
+        val = pix.GetArrivalTime();
+        return kTRUE;
+
+    case 11: // hi gain time
+        // The number of photons is not scaled with the ratio because
+        // otherwise to many large pixels survive (maybe because the
+        // fluctuations scale different than expected)
+        if (pix.IsPixelUnmapped() || pix.IsLoGainUsed() ||
+            pix.GetNumPhotons()<50)
+            return kFALSE;
+        val = pix.GetArrivalTime();
+        return kTRUE;
+        */
+
+    case 10:
+        val = pix.GetNumPhotons()*ratio;
+        return val>0;
+
+    case 11:
+        val = pix.GetArrivalTime();
+        return pix.GetNumPhotons()>0;
+
+    case 9:
+    default:
+        val = pix.GetNumPhotons()*ratio;
+        return kTRUE;
+    }
+    return kTRUE;
+}
+
+void MSignalCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MSignalCam::DrawPixelContent - not available." << endl;
+}
+
+TObject *MSignalCamIter::Next()
+{
+    if (!fUsedOnly)
+    {
+        fIdx++;
+        return TObjArrayIter::Next();
+    }
+
+    MSignalPix *pix;
+    while ((pix = (MSignalPix*)TObjArrayIter::Next()))
+    {
+        fIdx++;
+        if (pix->IsPixelUsed())
+            return pix;
+    }
+    return pix;
+}
Index: branches/Mars_McMismatchStudy/msignal/MSignalCam.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MSignalCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MSignalCam.h	(revision 17960)
@@ -0,0 +1,118 @@
+#ifndef MARS_MSignalCam
+#define MARS_MSignalCam
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MSignalPix
+#include "MSignalPix.h"
+#endif
+
+class MGeomCam;
+class MSignalPix;
+class MSignalCamIter;
+
+class MSignalCam : public MParContainer, public MCamEvent
+{
+    friend class MSignalCamIter;
+private:
+    Short_t       fNumIslands;                  //!
+    Short_t       fNumSinglePixels;             //!
+    Float_t       fSizeSinglePixels;            //!
+    Float_t       fSizeSubIslands;              //!
+    Float_t       fSizeMainIsland;              //!
+
+    Int_t         fNumPixelsSaturatedHiGain;
+    Int_t         fNumPixelsSaturatedLoGain;
+    TClonesArray *fPixels;     //-> FIXME: Change TClonesArray away from a pointer?
+
+    Double_t CalcIsland(const MGeomCam &geom, Int_t idx, Int_t num);
+
+public:
+    MSignalCam(const char *name=NULL, const char *title=NULL);
+    ~MSignalCam() { delete fPixels; }
+
+    // Setter function to fill pixels
+    MSignalPix *AddPixel(Int_t idx, Float_t nph=0, Float_t er=0);
+    void InitSize(const UInt_t i)
+    {
+        fPixels->ExpandCreate(i);
+    }
+
+    // Setter functions for use in image cleaning classes only
+    void SetSinglePixels(Short_t num, Float_t size)  { fNumSinglePixels=num; fSizeSinglePixels=size; }
+    void SetNumPixelsSaturated(UInt_t hi, UInt_t lo) { fNumPixelsSaturatedHiGain=hi;fNumPixelsSaturatedLoGain=lo; }
+    void SetIslandInfo(Short_t num, Float_t main, Float_t sub)
+    { fNumIslands = num; fSizeMainIsland=main; fSizeSubIslands=sub; }
+
+    // Getter functions
+    UInt_t  GetNumPixels() const { return fPixels->GetEntriesFast(); }
+    Short_t GetNumIslands() const { return fNumIslands; };
+    Short_t GetNumSinglePixels() const { return fNumSinglePixels; }
+    Float_t GetSizeSinglePixels() const { return fSizeSinglePixels; }
+    Float_t GetSizeSubIslands() const { return fSizeSubIslands; }
+    Float_t GetSizeMainIsland() const { return fSizeMainIsland; }
+    Int_t   GetNumPixelsSaturatedHiGain() const { return fNumPixelsSaturatedHiGain; }
+    Int_t   GetNumPixelsSaturatedLoGain() const { return fNumPixelsSaturatedLoGain; }
+
+    Int_t   GetNumPixelsUnmapped() const;
+
+    Float_t GetNumPhotonsMin(const MGeomCam *geom=NULL) const;
+    Float_t GetNumPhotonsMax(const MGeomCam *geom=NULL) const;
+
+    Float_t GetRatioMin(const MGeomCam *geom=NULL) const;
+    Float_t GetRatioMax(const MGeomCam *geom=NULL) const;
+
+    Float_t GetErrorPhotMin(const MGeomCam *geom=NULL) const;
+    Float_t GetErrorPhotMax(const MGeomCam *geom=NULL) const;
+
+    // Getter functions to access single pixels
+    MSignalPix &operator[](int i)       { return *(MSignalPix*)(fPixels->UncheckedAt(i)); }
+    MSignalPix &operator[](int i) const { return *(MSignalPix*)(fPixels->UncheckedAt(i)); }
+
+    // Functions to change the contained data
+    Int_t CalcIslands(const MGeomCam &geom);
+
+    // Functions for easy comparisons
+    Bool_t CompareCleaning(const MSignalCam &cam) const;
+    Bool_t CompareIslands(const MSignalCam &cam) const;
+
+    // class MParContainer
+    void Reset();
+
+    // class TObject
+    void Copy(TObject &obj) const;
+    void Print(Option_t *opt=NULL) const;
+    void Clear(Option_t *opt=NULL) { Reset(); }
+
+    // class MCamEvent
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    // To build an iterator for this class
+    operator TIterator*() const;
+
+    ClassDef(MSignalCam, 2) // class for an event containing cerenkov photons
+};
+
+class MSignalCamIter : public TObjArrayIter
+{
+private:
+    Bool_t fUsedOnly;
+    Int_t fIdx;
+
+public:
+    MSignalCamIter(const MSignalCam *evt, Bool_t usedonly=kTRUE, Bool_t dir=kIterForward) : TObjArrayIter(evt->fPixels, dir), fUsedOnly(usedonly), fIdx(-1) { }
+    TObject *Next();
+    void Reset() { fIdx=-1; TObjArrayIter::Reset(); }
+    TIterator &operator=(const TIterator &) { return *this; }
+    Int_t GetIdx() const { return fIdx; }
+    ClassDef(MSignalCamIter, 0)
+};
+
+inline MSignalCam::operator TIterator*() const { return new MSignalCamIter(this); }
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MSignalPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MSignalPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MSignalPix.cc	(revision 17960)
@@ -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): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MSignalPix
+//
+// Storage container for the signal in a pixel in number of photons.
+//
+// NOTE: This container is NOT ment for I/O. Write it to a file on your
+//       own risk!
+//
+// fIsSaturated: boolean variable set to kTRUE whenever one or more of
+//               the low gain FADC slices of the pixel is in saturation.
+//
+// Version 2:
+// ----------
+//  - added fIsSaturated
+//
+// Version 4:
+// ----------
+//  - added fIsHGSaturated
+//
+// Version 5:
+// ----------
+//  - added fIdxIsland
+//
+// Version 6:
+// ----------
+//  - put the '!' into the comment line for
+//      Bool_t   fIsCore;        //! the pixel is a Core pixel -> kTRUE
+//      Short_t  fRing;          //! NT: number of analyzed rings around the core pixels, fRing>0 means: used, fRing= 0 means: unused, fRing= -1 means: unmapped (no possible to use in the calculation of the image parameters)
+//      Short_t  fIdxIsland;     //! the pixel is a Core pixel -> kTRUE
+//      Bool_t   fIsHGSaturated; //! the pixel's high gain is saturated
+//    This is a queick hack to gain storage space - the structure of
+//    the container for calibrated data will change soon.
+//
+// Version 7:
+// ----------
+//  - removed '!' from fRing to allow the status 'Unmapped' to be stored
+//    after calibration (bad pixel treatment). This increases the file
+//    size of the calibrated data by roughly 0.5%
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MSignalPix.h"
+
+#include "MLog.h"
+
+ClassImp(MSignalPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. The pixel is assumed as used and not a core pixel.
+// NT 29/04/2003: A pixel is considered used when fRing > 0.
+//
+MSignalPix::MSignalPix(Float_t phot, Float_t errphot) :
+    fIsCore(kFALSE), fRing(1), fIdxIsland(-1),
+    fPhot(phot), fErrPhot(errphot), fArrivalTime(-1)
+{
+    MMath::ReducePrecision(fPhot);
+    MMath::ReducePrecision(fErrPhot);
+} 
+
+void MSignalPix::Clear(Option_t *o)
+{
+    fIsCore      = kFALSE;
+    fRing        =  1;
+    fIdxIsland   = -1;
+    fPhot        =  0;
+    fErrPhot     =  0;
+    fArrivalTime = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print information to gLog.
+//
+void MSignalPix::Print(Option_t *) const
+{ 
+    gLog << GetDescriptor();// << " Pixel: "<< fPixId;
+    switch (fRing)
+    {
+    case -1:
+        gLog << "Unampped";
+        break;
+    case 0:
+        gLog << " Unused ";
+        break;
+    default:
+        gLog << "  Used  ";
+        break;
+    }
+    gLog << (fIsCore?" Core ":"      ");
+    gLog << "Nphot= " << fPhot << " Error(Nphot)=" << fErrPhot << endl;
+}
Index: branches/Mars_McMismatchStudy/msignal/MSignalPix.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MSignalPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MSignalPix.h	(revision 17960)
@@ -0,0 +1,74 @@
+#ifndef MARS_MSignalPix
+#define MARS_MSignalPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MMath
+#include "MMath.h"
+#endif
+
+class MSignalPix : public MParContainer
+{
+private:
+    Bool_t   fIsCore;        //! the pixel is a Core pixel -> kTRUE
+    Short_t  fRing;          //  NT: number of analyzed rings around the core pixels, fRing>0 means: used, fRing= 0 means: unused, fRing= -1 means: unmapped (no possible to use in the calculation of the image parameters)
+    Short_t  fIdxIsland;     //! the pixel is a Core pixel -> kTRUE
+
+    Float_t  fPhot;          // The number of Cerenkov photons
+    Float_t  fErrPhot;       // the error of fPhot
+    Float_t  fArrivalTime;   // Calibrated Arrival Time
+
+public:
+    MSignalPix(Float_t phot=0, Float_t errphot=0);
+    MSignalPix(const MSignalPix &pix)
+        : fIsCore(pix.fIsCore), fRing(pix.fRing), fIdxIsland(pix.fIdxIsland),
+        fPhot(pix.fPhot), fErrPhot(pix.fErrPhot), fArrivalTime(pix.fArrivalTime)
+    {
+    }
+
+    // TObject
+    void Clear(Option_t *o=0);
+    void Copy(TObject &obj) const
+    {
+        MSignalPix &pix = (MSignalPix&)obj;
+        pix.fIsCore      = fIsCore;
+        pix.fRing        = fRing;
+        pix.fIdxIsland   = fIdxIsland;
+        pix.fPhot        = fPhot;
+        pix.fErrPhot     = fErrPhot;
+        pix.fArrivalTime = fArrivalTime;
+    }
+    void    Print(Option_t *opt = NULL) const;
+
+    // MSignalPix
+    Float_t GetNumPhotons() const         { return fPhot;    }
+    Float_t GetErrorPhot() const          { return fErrPhot; }
+    Float_t GetArrivalTime() const        { return fArrivalTime; }
+
+    Bool_t  IsPixelUsed() const           { return fRing>0; }
+    Bool_t  IsPixelUnmapped() const       { return fRing==-1; }
+    void    SetPixelUnused()              { fRing=0;  }
+    void    SetPixelUsed()                { fRing=1;  }
+    void    SetPixelUnmapped()            { fRing=-1; }
+    void    SetIdxIsland(Short_t num)     { fIdxIsland=num; }
+    Short_t GetIdxIsland() const          { return fIdxIsland; }
+
+    void    SetRing(UShort_t r)           { fRing = r;   }
+    Short_t GetRing() const               { return fRing;}
+
+    void    SetPixelCore(Bool_t b=kTRUE)  { fIsCore = b; }
+    Bool_t  IsPixelCore() const           { return fIsCore;  }
+
+    void    SetNumPhotons(Float_t f)      { MMath::ReducePrecision(f); fPhot    = f; }
+    void    SetErrorPhot(Float_t f)       { MMath::ReducePrecision(f); fErrPhot = f; }
+    void    Set(Float_t np, Float_t ep)   { MMath::ReducePrecision(np); MMath::ReducePrecision(ep);  fPhot = np; fErrPhot = ep; }
+    void    SetArrivalTime(Float_t tm)    { fArrivalTime = tm; }
+
+    //void    AddNumPhotons(Float_t f)      { fPhot += f; }
+    //void    Scale(Float_t f)              { fPhot /= f; }
+
+    ClassDef(MSignalPix, 7)  // class containing information about the Cerenkov Photons in a pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/MTreatSaturation.cc
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MTreatSaturation.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MTreatSaturation.cc	(revision 17960)
@@ -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, 2014 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2014
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MTreatSaturation
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MTreatSaturation.h"
+
+#include <algorithm>
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+#include "MExtralgoSpline.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalSubtractedEvt.h"
+
+ClassImp(MTreatSaturation);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MTreatSaturation::MTreatSaturation(const char *name, const char *title)
+    : fRaw(0), fEvt(0)
+{
+    fName  = name  ? name  : "MTreatSaturation";
+    fTitle = title ? title : "Base class for replacing saturation with pulses";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MTreatSaturation::PreProcess(MParList *pList)
+{
+    fRaw = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRaw)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MPedestalSubtractedEvt*)pList->FindObject("MPedestalSubtractedEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MPedestalSubtractedEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MTreatSaturation::Process()
+{
+    const UInt_t fHiGainFirst =  50;
+    const UInt_t fHiGainLast  = 225;
+
+    const UInt_t npix = fEvt->GetNumPixels();
+
+    const UInt_t rangehi = fHiGainLast - fHiGainFirst - 1;
+
+    if (fDev1.GetSize()!=rangehi)
+    {
+        fDev1.Set(rangehi);
+        fDev2.Set(rangehi);
+    }
+
+    for (UInt_t ch=0; ch<npix; ch++)
+    {
+        Float_t *ptr = fEvt->GetSamples(ch);
+
+        const Float_t *pbeg = ptr+fHiGainFirst+1;
+        const Float_t *pend = ptr+fHiGainLast-1;
+
+        // Find maximum
+        const Float_t *pmax = pbeg;
+        for (const Float_t *p=pbeg; p<pend; p++)
+            if (*p>*pmax)
+                pmax = p;
+
+        // Is there any chance for saturation?
+        if (*pmax<1900)
+            continue;
+
+        // Determine a rough estimate for the average baseline
+        double baseline = 0;
+        for (const Float_t *p=ptr+10; p<ptr+50; p++)
+            baseline += *ptr;
+        baseline /= 40;
+
+        // Do a spline interpolation to find the crossing of 1.8V
+        // before and after the maximum (This is a level, I think
+        // there is no saturation effect at all yet)
+        MExtralgoSpline s(pbeg, rangehi, fDev1.GetArray(), fDev2.GetArray());
+        s.SetExtractionType(MExtralgoSpline::kAmplitudeRel);
+
+        const double leading = s.SearchYdn(pmax-pbeg, 1800);
+        const double falling = s.SearchYup(pmax-pbeg, 1800);
+        const double width   = falling-leading;
+
+        // If the width above 1.8V is below 3 samples... go ahead as usual.
+        if (width<3)
+            continue;
+
+        // Estimate the amplitude and the arrival time from the width
+        const double amplitude = (1800-baseline)/(0.898417 - 0.0187633*width + 0.000163919*width*width - 6.87369e-7*width*width*width + 1.13264e-9*width*width*width*width);
+        const double deltat    = -1.41371-0.0525846*width + 93.2763/(width+13.196);
+        const double time0     = leading-deltat-1;
+
+        const Int_t beg = TMath::FloorNint(leading);
+        const Int_t end = TMath::CeilNint(falling);
+
+        ptr += fHiGainFirst+1;
+        for (Int_t i=beg-5; i<end+5; i++)
+        {
+            const double x = i-time0;
+            const double v = amplitude*(1-1/(1+exp(x/2.14)))*exp(-x/38.8)+baseline;
+            if (v>ptr[i])
+                ptr[i] = v;
+        }
+    }
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/msignal/MTreatSaturation.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/MTreatSaturation.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/MTreatSaturation.h	(revision 17960)
@@ -0,0 +1,32 @@
+#ifndef MARS_MTreatSaturation
+#define MARS_MTreatSaturation
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MPedestalSubtractedEvt;
+
+class MTreatSaturation : public MTask
+{
+private:
+    MRawEvtData            *fRaw;
+    MPedestalSubtractedEvt *fEvt;
+
+    MArrayF fDev1;
+    MArrayF fDev2;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+public:
+    MTreatSaturation(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MTreatSaturation, 0)   // Replace saturating samples with pulse
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/msignal/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/Makefile	(revision 17960)
@@ -0,0 +1,73 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Signal
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES =  -I. -I../mbase -I../mgui -I../mraw -I../manalysis \
+            -I../mgeom -I../mtools -I../mpedestal -I../mbadpixels \
+            -I../mcalib -I../mextralgo
+
+# mgui (MCamEvent):         MExtractSignalCam
+# mgeom(MGeomCam):          MArrivalTime
+# mtools(MCubicSpline):     MArrivalTime
+# mraw (MRawEvtData):       MExtractSignal
+# manalysis (MPedestalCam): MExtractSignal
+
+SRCFILES = MExtractedSignalCam.cc \
+           MExtractedSignalPix.cc \
+	   MExtractedSignalPINDiode.cc \
+	   MExtractedSignalBlindPixel.cc \
+           MExtractor.cc \
+	   MExtractPINDiode.cc \
+	   MExtractBlindPixel.cc \
+           MExtractTime.cc \
+           MExtractTimeAndCharge.cc \
+           MExtractTimeAndChargeSpline.cc \
+           MExtractTimeAndChargeDigitalFilter.cc \
+           MExtractFACT.cc \
+           MSignalCam.cc \
+           MSignalPix.cc \
+           MSignalCalc.cc \
+	   MFilterData.cc \
+	   MTreatSaturation.cc \
+           MArrivalTimeCam.cc \
+	   MArrivalTimePix.cc
+
+#           MExtractSignal.cc \
+#           MExtractSignal2.cc \
+#           MExtractSignal3.cc \
+#           MExtractSignalABcorr.cc \
+
+#           MExtractFixedWindow.cc \
+#           MExtractSlidingWindow.cc \
+#           MExtractFixedWindowPeakSearch.cc \
+#           MExtractFixedWindowSpline.cc \
+#           MExtractAmplitudeSpline.cc \
+#           MExtractTimeSpline.cc \
+#           MExtractTimeFastSpline.cc \
+#           MExtractTimeHighestIntegral.cc \
+#           MExtractTimeAndChargeSlidingWindow.cc \
+#           MExtractTimeAndChargeDigitalFilterPeakSearch.cc \
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/msignal/SignalIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/SignalIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/SignalIncl.h	(revision 17960)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+//#include <TArrayC.h>
+//#include "MArrayB.h"
+//#include "MArrayS.h"
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/msignal/SignalLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/msignal/SignalLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/SignalLinkDef.h	(revision 17960)
@@ -0,0 +1,50 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MExtractedSignalCam+;
+#pragma link C++ class MExtractedSignalPix+;
+#pragma link C++ class MExtractedSignalPINDiode+;
+#pragma link C++ class MExtractedSignalBlindPixel+;
+
+//#pragma link C++ class MExtractSignal+;
+//#pragma link C++ class MExtractSignal2+;
+//#pragma link C++ class MExtractSignal3+;
+//#pragma link C++ class MExtractSignalABcorr+;
+
+#pragma link C++ class MExtractor+;
+#pragma link C++ class MExtractPINDiode+;
+#pragma link C++ class MExtractBlindPixel+;
+
+//#pragma link C++ class MExtractFixedWindow+;
+//#pragma link C++ class MExtractSlidingWindow+;
+//#pragma link C++ class MExtractFixedWindowPeakSearch+;
+//#pragma link C++ class MExtractFixedWindowSpline+;
+//#pragma link C++ class MExtractAmplitudeSpline+;
+
+#pragma link C++ class MExtractFACT+;
+#pragma link C++ class MExtractTime+;
+#pragma link C++ class MTreatSaturation+;
+//#pragma link C++ class MExtractTimeSpline+;
+//#pragma link C++ class MExtractTimeFastSpline+;
+//#pragma link C++ class MExtractTimeHighestIntegral+;
+
+#pragma link C++ class MExtractTimeAndCharge+;
+#pragma link C++ class MExtractTimeAndChargeSpline+;
+#pragma link C++ class MExtractTimeAndChargeDigitalFilter+;
+//#pragma link C++ class MExtractTimeAndChargeSlidingWindow+;
+//#pragma link C++ class MExtractTimeAndChargeDigitalFilterPeakSearch+;
+
+#pragma link C++ class MArrivalTimeCam+;
+#pragma link C++ class MArrivalTimePix+;
+
+#pragma link C++ class MSignalPix+;
+#pragma link C++ class MSignalCam+;
+#pragma link C++ class MSignalCamIter+;
+#pragma link C++ class MSignalCalc+;
+
+#pragma link C++ class MFilterData+;
+
+#endif
Index: branches/Mars_McMismatchStudy/msignal/calibration_weights_UV.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/calibration_weights_UV.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/calibration_weights_UV.dat	(revision 17960)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+-0.135294 -0.845262         0
+-0.307049 -0.967471         0
+-0.487632 -0.971773         0
+-0.614716 -0.913206         0
+-0.721512 -0.827152         0
+-0.775976 -0.717254         0
+-0.845087 -0.509839         0
+-0.955046 -0.209035         0
+-1.00224 0.2472             0
+-0.903555 0.817093          0
+-0.556441 1.76312           0
+-0.194211 2.12631           0
+0.219836 2.22675            0
+0.513689 2.28873            0
+0.822468 2.38924            0
+0.971705 2.34813            0
+1.18817 2.07459             0
+1.5515 1.81714              0
+1.97131 1.69619             0
+2.33012 1.28281             0
+2.45352 0.287745            0
+2.4015 -0.339334            0
+2.25982 -0.827606           0
+2.11244 -1.2129             0
+1.92951 -1.54897            0
+1.83142 -1.8268             0
+1.64896 -1.90661            0
+1.28279 -2.00748            0
+0.793985 -2.24883           0
+0.262309 -2.15446           0
+-0.0559972 -1.30597         0
+-0.177972 -0.825199         0
+-0.226058 -0.373441         0
+-0.231339 -0.152992         0
+-0.236687 -0.0444464        0
+-0.247735 0.101245          0
+-0.248764 0.294579          0
+-0.189974 0.354396          0
+-0.109625 0.435904          0
+-0.00029747 0.373219        0
+0.0438014 0.13228           0
+0.049418 0.0464338          0
+0.0405008 -0.0314221        0
+0.0302813 -0.0478527        0
+0.027379 -0.00159103        0
+0.0416632 -0.0947573        0
+0.0300094 -0.200671         0
+-0.0135778 -0.145184        0
+-0.0426915 -0.130517        0
+-0.0753977 -0.0119239       0
+-0.0810973 0.0442347        0
+-0.0835202 0.0186848        0
+-0.074967 0.051449          0
+-0.0655645 0.0449615        0
+-0.0661155 0.0215451        0
+-0.0665032 0.0587461        0
+-0.0606857 0.0855372        0
+-0.0374867 0.0523137        0
+-0.0270469 0.0100236        0
+-0.0249475 -0.0585201       0
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273         0
+0.038191 -0.00418687        0
+0.0386966 0.0212324         0
+0.0402881 0.0744799         0
+0.0415794 0.229615          0
+0.0598731 0.44332           0
+0.0758477 0.661518          0
+0.101509 1.10641            0
+0.159323 1.64997            0
+0.497256 2.83685            0
+0.245087 3.27499            0
+0.140546 2.46177            0
+0.58086 2.2849              0
+0.632721 2.45587            0
+0.72819 2.52835             0
+0.889583 2.48099            0
+0.980812 2.50031            0
+1.09885 2.55892             0
+1.21374 2.78769             0
+1.61928 3.08069             0
+1.38544 1.95583             0
+1.31998 1.1792              0
+1.50633 0.591226            0
+1.50916 0.0793899           0
+1.5008 -0.33188             0
+1.47339 -0.575386           0
+1.45362 -0.915309           0
+1.40214 -1.31593            0
+1.34175 -1.77904            0
+1.0661 -2.05471             0
+1.31087 -1.49798            0
+1.33793 -1.34758            0
+1.10172 -1.21719            0
+1.08133 -1.09356            0
+1.04007 -0.981455           0
+0.976745 -1.08299           0
+0.930979 -1.14774           0
+0.874203 -1.18348           0
+0.816708 -1.20126           0
+0.587354 -1.92869           0
+0.783078 -1.89621           0
+0.792771 -1.03439           0
+0.622278 -0.781807          0
+0.61184 -0.745831           0
+0.578792 -0.683741          0
+0.537336 -0.596328          0
+0.51443 -0.592858           0
+0.482294 -0.560586          0
+0.462351 -0.827587          0
+0.317989 -1.05649           0
+0.459672 -0.775035          0
+0.468287 -0.619961          0
+0.374182 -0.31635           0
+0.376946 -0.225242          0
+0.367075 -0.347444          0
+0.340737 -0.393231          0
+0.321054 -0.187384          0
+0.320654 -0.225558          0
+0.302148 -0.399499          0
+0.232954 -0.607578          0
Index: branches/Mars_McMismatchStudy/msignal/calibration_weights_UV4.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/calibration_weights_UV4.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/calibration_weights_UV4.dat	(revision 17960)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.735581 -0.673266           0
+-0.800386 -0.47606            0
+-0.902801 -0.192719           0
+-0.945945 0.237423            0
+-0.851618 0.770424            0
+-0.598107 1.28444             0
+-0.290663 1.69546             0
+0.0967702 1.89144             0
+0.362204 1.98161              0
+0.610111 2.06506              0
+0.919902 2.20752              0
+1.12282 1.94486               0
+1.46305 1.70309               0
+1.85728 1.58904               0
+2.19155 1.21011               0
+2.37154 0.603168              0
+2.37187 0.000360131           0
+2.25639 -0.535921             0
+2.12495 -0.948388             0
+1.97328 -1.286                0
+1.72155 -1.70358              0
+1.55218 -1.75991              0
+1.21489 -1.86382              0
+0.759117 -2.09403             0
+0.266577 -2.03167             0
+-0.102906 -1.60487            0
+-0.284545 -1.16641            0
+-0.367327 -0.679947           0
+-0.376403 -0.3943             0
+-0.379568 -0.229929           0
+-0.218954 0.0443019           0
+-0.22659 0.163101             0
+-0.195144 0.249649            0
+-0.136182 0.328464            0
+-0.0541723 0.334035           0
+-0.00249719 0.207255          0
+0.00794832 0.102902           0
+0.00785676 0.0396167          0
+0.00459524 0.0111356          0
+0.00887564 0.0405             0
+# Low Gain Weights: 4 10      
+# (Amplitude)  (Time)         
+0.178287 2.98244              0
+0.0799794 2.25048             0
+0.501997 2.04566              0
+0.559993 2.18952              0
+0.636334 2.28558              0
+0.784832 2.29757              0
+0.894393 2.36602              0
+1.01571 2.62578               0
+1.14191 3.14701               0
+1.70405 4.27635               0
+1.25503 1.69442               0
+1.19843 1.00804               0
+1.36974 0.493838              0
+1.37759 0.0452029             0
+1.37174 -0.336051             0
+1.34423 -0.563321             0
+1.31669 -0.852661             0
+1.26602 -1.28826              0
+1.20062 -1.85625              0
+0.874127 -2.44773             0
+1.2433 -1.47361               0
+1.27171 -1.3052               0
+1.03025 -1.1211               0
+1.00417 -0.992811             0
+0.968251 -0.911359            0
+0.907626 -1.02038             0
+0.852293 -1.06813             0
+0.797164 -1.16276             0
+0.739386 -1.25445             0
+0.447754 -2.34757             0
+0.777349 -1.83155             0
+0.779564 -1.01577             0
+0.600426 -0.733238            0
+0.5863 -0.688006              0
+0.557156 -0.650488            0
+0.514926 -0.584649            0
+0.485323 -0.569089            0
+0.454047 -0.573249            0
+0.429026 -0.907077            0
+0.245526 -1.35434             0
Index: branches/Mars_McMismatchStudy/msignal/calibration_weights_UV46.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/calibration_weights_UV46.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/calibration_weights_UV46.dat	(revision 17960)
@@ -0,0 +1,104 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.735581 -0.673266      0
+-0.800386 -0.47606       0
+-0.902801 -0.192719      0
+-0.945945 0.237423       0
+-0.851618 0.770424       0
+-0.598107 1.28444        0
+-0.290663 1.69546        0
+0.0967702 1.89144        0
+0.362204 1.98161         0
+0.610111 2.06506         0
+0.919902 2.20752         0
+1.12282 1.94486          0
+1.46305 1.70309          0
+1.85728 1.58904          0
+2.19155 1.21011          0
+2.37154 0.603168         0
+2.37187 0.000360131      0
+2.25639 -0.535921        0
+2.12495 -0.948388        0
+1.97328 -1.286           0
+1.72155 -1.70358         0
+1.55218 -1.75991         0
+1.21489 -1.86382         0
+0.759117 -2.09403        0
+0.266577 -2.03167        0
+-0.102906 -1.60487       0
+-0.284545 -1.16641       0
+-0.367327 -0.679947      0
+-0.376403 -0.3943        0
+-0.379568 -0.229929      0
+-0.218954 0.0443019      0
+-0.22659 0.163101        0
+-0.195144 0.249649       0
+-0.136182 0.328464       0
+-0.0541723 0.334035      0
+-0.00249719 0.207255     0
+0.00794832 0.102902      0
+0.00785676 0.0396167     0
+0.00459524 0.0111356     0
+0.00887564 0.0405        0
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273      0
+0.038191 -0.00418687     0
+0.0386966 0.0212324      0
+0.0402881 0.0744799      0
+0.0415794 0.229615       0
+0.0598731 0.44332        0
+0.0758477 0.661518       0
+0.101509 1.10641         0
+0.159323 1.64997         0
+0.497256 2.83685         0
+0.245087 3.27499         0
+0.140546 2.46177         0
+0.58086 2.2849           0
+0.632721 2.45587         0
+0.72819 2.52835          0
+0.889583 2.48099         0
+0.980812 2.50031         0
+1.09885 2.55892          0
+1.21374 2.78769          0
+1.61928 3.08069          0
+1.38544 1.95583          0
+1.31998 1.1792           0
+1.50633 0.591226         0
+1.50916 0.0793899        0
+1.5008 -0.33188          0
+1.47339 -0.575386        0
+1.45362 -0.915309        0
+1.40214 -1.31593         0
+1.34175 -1.77904         0
+1.0661 -2.05471          0
+1.31087 -1.49798         0
+1.33793 -1.34758         0
+1.10172 -1.21719         0
+1.08133 -1.09356         0
+1.04007 -0.981455        0
+0.976745 -1.08299        0
+0.930979 -1.14774        0
+0.874203 -1.18348        0
+0.816708 -1.20126        0
+0.587354 -1.92869        0
+0.783078 -1.89621        0
+0.792771 -1.03439        0
+0.622278 -0.781807       0
+0.61184 -0.745831        0
+0.578792 -0.683741       0
+0.537336 -0.596328       0
+0.51443 -0.592858        0
+0.482294 -0.560586       0
+0.462351 -0.827587       0
+0.317989 -1.05649        0
+0.459672 -0.775035       0
+0.468287 -0.619961       0
+0.374182 -0.31635        0
+0.376946 -0.225242       0
+0.367075 -0.347444       0
+0.340737 -0.393231       0
+0.321054 -0.187384       0
+0.320654 -0.225558       0
+0.302148 -0.399499       0
+0.232954 -0.607578       0
Index: branches/Mars_McMismatchStudy/msignal/calibration_weights_UV_logaintest.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/calibration_weights_UV_logaintest.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/calibration_weights_UV_logaintest.dat	(revision 17960)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time) 
+	-0.123301	0.281176              0
+	-0.0989162	0.189014              0
+	-0.0744146	0.109115              0
+	-0.0579067	-0.00970563           0
+	-0.08634	-0.175186             0
+	-0.153627	-0.35012              0
+	-0.248048	-0.509518             0
+	-0.368571	-0.608264             0
+	-0.457643	-0.603256             0
+	-0.514441	-0.531277             0
+	-0.63496	-0.822575             0
+	-0.700206	-0.606683             0
+	-0.779942	-0.340557             0
+	-0.792388	0.0335111             0
+	-0.691357	0.514475              0
+	-0.473932	1.0154                0
+	-0.210221	1.47267               0
+	0.143091	1.75857               0
+	0.413054	1.93247               0
+	0.689521	2.07962               0
+	0.848796	2.39505               0
+	1.08333	2.1765                        0
+	1.43826	1.98218                       0
+	1.81403	1.94894                       0
+	2.1227	1.64159                       0
+	2.30177	1.09338                       0
+	2.33713	0.518179                      0
+	2.27011	-0.077444                     0
+	2.17053	-0.546523                     0
+	2.03214	-0.930314                     0
+	1.99228	-1.61593                      0
+	1.80151	-1.73669                      0
+	1.4472	-1.90893                      0
+	0.979215	-2.22413              0
+	0.476345	-2.27293              0
+	0.0815403	-1.99688              0
+	-0.158713	-1.69048              0
+	-0.332713	-1.22056              0
+	-0.412026	-0.947722             0
+	-0.486163	-0.785726             0
+	-0.559431	0.115011              0
+	-0.524321	0.280475              0
+	-0.453902	0.377856              0
+	-0.352013	0.515131              0
+	-0.221563	0.552559              0
+	-0.128697	0.485583              0
+	-0.0563877	0.46736               0
+	0.00608425	0.387754              0
+	0.0461686	0.367825              0
+	0.0998553	0.408476              0
+	0.0575847	-0.020068             0
+	0.0361577	-0.0950281            0
+	0.021779	-0.0724483            0
+	0.00683997	-0.0950705            0
+	-0.0143629	-0.0588636            0
+	-0.014106	-0.0472336            0
+	-0.0404541	-0.112081             0
+	-0.0567406	-0.0926997            0
+	-0.069889	-0.109181             0
+	-0.0940175	-0.135339             0
+# Low Gain Weights: 6 10                      
+# (Amplitude)  (Time)                         
+	-0.123301	0.281176              0
+	-0.0989162	0.189014              0
+	-0.0744146	0.109115              0
+	-0.0579067	-0.00970563           0
+	-0.08634	-0.175186             0
+	-0.153627	-0.35012              0
+	-0.248048	-0.509518             0
+	-0.368571	-0.608264             0
+	-0.457643	-0.603256             0
+	-0.514441	-0.531277             0
+	-0.63496	-0.822575             0
+	-0.700206	-0.606683             0
+	-0.779942	-0.340557             0
+	-0.792388	0.0335111             0
+	-0.691357	0.514475              0
+	-0.473932	1.0154                0
+	-0.210221	1.47267               0
+	0.143091	1.75857               0
+	0.413054	1.93247               0
+	0.689521	2.07962               0
+	0.848796	2.39505               0
+	1.08333	2.1765                        0
+	1.43826	1.98218                       0
+	1.81403	1.94894                       0
+	2.1227	1.64159                       0
+	2.30177	1.09338                       0
+	2.33713	0.518179                      0
+	2.27011	-0.077444                     0
+	2.17053	-0.546523                     0
+	2.03214	-0.930314                     0
+	1.99228	-1.61593                      0
+	1.80151	-1.73669                      0
+	1.4472	-1.90893                      0
+	0.979215	-2.22413              0
+	0.476345	-2.27293              0
+	0.0815403	-1.99688              0
+	-0.158713	-1.69048              0
+	-0.332713	-1.22056              0
+	-0.412026	-0.947722             0
+	-0.486163	-0.785726             0
+	-0.559431	0.115011              0
+	-0.524321	0.280475              0
+	-0.453902	0.377856              0
+	-0.352013	0.515131              0
+	-0.221563	0.552559              0
+	-0.128697	0.485583              0
+	-0.0563877	0.46736               0
+	0.00608425	0.387754              0
+	0.0461686	0.367825              0
+	0.0998553	0.408476              0
+	0.0575847	-0.020068             0
+	0.0361577	-0.0950281            0
+	0.021779	-0.0724483            0
+	0.00683997	-0.0950705            0
+	-0.0143629	-0.0588636            0
+	-0.014106	-0.0472336            0
+	-0.0404541	-0.112081             0
+	-0.0567406	-0.0926997            0
+	-0.069889	-0.109181             0
+	-0.0940175	-0.135339             0
Index: branches/Mars_McMismatchStudy/msignal/calibration_weights_blue.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/calibration_weights_blue.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/calibration_weights_blue.dat	(revision 17960)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+-0.605623 -1.11881          0
+-0.764793 -1.10531          0
+-0.86103 -1.1367            0
+-0.90412 -1.1014            0
+-0.953294 -0.946356         0
+-1.01994 -0.665753          0
+-1.11013 -0.378876          0
+-1.26403 -0.0260436         0
+-1.22181 0.842651           0
+-0.482293 1.76104           0
+0.284962 2.31134            0
+0.611944 2.38608            0
+0.8414 2.6344               0
+0.951306 2.73879            0
+1.07472 2.52913             0
+1.16903 2.19412             0
+1.3172 1.95371              0
+1.87082 1.59091             0
+2.61481 1.15287             0
+2.86574 0.237112            0
+2.50204 -0.745746           0
+2.30737 -1.23243            0
+2.13806 -1.71705            0
+2.07571 -2.05767            0
+1.9644 -2.17221             0
+1.9001 -2.20019             0
+1.70573 -2.2269             0
+1.03329 -2.16862            0
+-0.1132 -2.07192            0
+-0.746055 -1.21823          0
+-0.489468 -0.0876857        0
+-0.310262 0.331252          0
+-0.227732 0.591827          0
+-0.182658 0.617976          0
+-0.184889 0.639342          0
+-0.153689 0.670494          0
+-0.0841314 0.571983         0
+0.086702 0.514434           0
+0.343918 0.474596           0
+0.470154 0.180966           0
+0.351024 -0.122442          0
+0.303044 -0.230226          0
+0.262699 -0.349064          0
+0.243201 -0.354185          0
+0.238138 -0.351845          0
+0.226132 -0.380497          0
+0.161807 -0.296499          0
+0.0464236 -0.18346          0
+-0.0407385 -0.132386        0
+-0.0350163 0.0786269        0
+0.0827034 0.113955          0
+0.0865831 0.097233          0
+0.103917 0.121197           0
+0.108297 0.106561           0
+0.109348 0.104756           0
+0.128509 0.0501978          0
+0.142551 -0.0127797         0
+0.146076 -0.0501855         0
+0.11112 -0.100616           0
+0.0495201 -0.157116         0
+# Low Gain Weights: 6 10    
+# (Amplitude)  (Time)       
+0.0911607 1.86069           0
+0.134612 2.42822            0
+0.11393 2.54774             0
+0.239782 2.89304            0
+0.38454 3.39314             0
+0.506359 4.46877            0
+0.655883 5.52101            0
+0.73793 6.57492             0
+0.626733 5.91162            0
+0.622878 5.2788             0
+0.875104 5.70684            0
+1.0185 4.05712              0
+1.03351 2.62644             0
+1.17511 1.6677              0
+1.25046 1.13376             0
+1.2901 0.924149             0
+1.31334 0.437335            0
+1.31663 0.507458            0
+1.31277 0.427002            0
+1.32304 -0.0901286          0
+1.38784 -0.706265           0
+1.37487 -0.901873           0
+1.36665 -0.786355           0
+1.32075 -0.6806             0
+1.28396 -0.713758           0
+1.26222 -1.18985            0
+1.21343 -1.68063            0
+1.19453 -2.03872            0
+1.2299 -2.06586             0
+1.22115 -1.76823            0
+1.18887 -2.03884            0
+1.14439 -1.67582            0
+1.13325 -1.30011            0
+1.06283 -1.09575            0
+1.00479 -1.1072             0
+0.966371 -1.32491           0
+0.920684 -1.40639           0
+0.905236 -1.87588           0
+0.933327 -1.81847           0
+0.931535 -1.5951            0
+0.890207 -1.70808           0
+0.853004 -0.945718          0
+0.845928 -0.714034          0
+0.810665 -0.763716          0
+0.766765 -0.886576          0
+0.733744 -0.826087          0
+0.710135 -0.687648          0
+0.701588 -1.26231           0
+0.71366 -1.04794            0
+0.719342 -0.998027          0
+0.732828 -1.5976            0
+0.699252 -1.20079           0
+0.690217 -0.920725          0
+0.639485 -0.679626          0
+0.604624 -0.636375          0
+0.582796 -0.785263          0
+0.555253 -0.706474          0
+0.55048 -0.932222           0
+0.560973 -0.88078           0
+0.567122 -0.86762           0
Index: branches/Mars_McMismatchStudy/msignal/calibration_weights_blue4.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/calibration_weights_blue4.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/calibration_weights_blue4.dat	(revision 17960)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.902168 -0.585312        0
+-0.984524 -0.32831         0
+-1.12036 -0.0157807        0
+-1.08172 0.756907          0
+-0.427114 1.56066          0
+0.186216 1.92954           0
+0.509304 2.06633           0
+0.699549 2.27174           0
+0.776041 2.3434            0
+0.8686 2.15573             0
+1.04178 1.93083            0
+1.17443 1.71284            0
+1.66255 1.38999            0
+2.31293 1.00065            0
+2.53376 0.210701           0
+2.3316 -0.460552           0
+2.11661 -0.992708          0
+1.95813 -1.43769           0
+1.91826 -1.72912           0
+1.83121 -1.83277           0
+1.6757 -1.91204            0
+1.50581 -1.93994           0
+0.91874 -1.89528           0
+-0.086052 -1.81483         0
+-0.651007 -1.09872         0
+-0.615758 -0.392913        0
+-0.393843 0.132625         0
+-0.284098 0.418838         0
+-0.258366 0.437323         0
+-0.262974 0.468126         0
+0.0180038 0.377062         0
+0.0449773 0.327324         0
+0.128299 0.336854          0
+0.297876 0.323257          0
+0.402965 0.18143           0
+0.373367 -0.00201841       0
+0.315525 -0.13922          0
+0.279239 -0.242999         0
+0.275543 -0.242753         0
+0.279876 -0.233989         0
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+0.65753 5.13268            0
+0.809076 4.33176           0
+0.831737 3.71302           0
+1.1134 4.00049             0
+1.43596 5.0645             0
+1.79077 7.81167            0
+2.41467 11.9052            0
+2.51185 13.4427            0
+2.24589 11.6437            0
+2.4845 12.1853             0
+1.22189 -0.852173          0
+1.20546 -1.07064           0
+1.19308 -1.07012           0
+1.1102 -1.13675            0
+1.03029 -1.34782           0
+0.866849 -3.1326           0
+0.41862 -6.79244           0
+0.502624 -6.45882          0
+0.577826 -6.33469          0
+0.49339 -6.35753           0
+1.0849 -2.02333            0
+1.03231 -1.8621            0
+1.01565 -1.75607           0
+0.879394 -2.04283          0
+0.704799 -2.79451          0
+0.524634 -4.2905           0
+0.242824 -6.03388          0
+0.198697 -6.9872           0
+0.323405 -6.28596          0
+0.175753 -6.97616          0
+0.843516 -1.76069          0
+0.790041 -1.14628          0
+0.778283 -1.04629          0
+0.693194 -1.51392          0
+0.537627 -2.42885          0
+0.460845 -2.70401          0
+0.459979 -2.10235          0
+0.239633 -4.66788          0
+0.413692 -3.09085          0
+0.310226 -3.82814          0
Index: branches/Mars_McMismatchStudy/msignal/calibration_weights_blue46.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/calibration_weights_blue46.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/calibration_weights_blue46.dat	(revision 17960)
@@ -0,0 +1,104 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.902168 -0.585312          0
+-0.984524 -0.32831           0
+-1.12036 -0.0157807          0
+-1.08172 0.756907            0
+-0.427114 1.56066            0
+0.186216 1.92954             0
+0.509304 2.06633             0
+0.699549 2.27174             0
+0.776041 2.3434              0
+0.8686 2.15573               0
+1.04178 1.93083              0
+1.17443 1.71284              0
+1.66255 1.38999              0
+2.31293 1.00065              0
+2.53376 0.210701             0
+2.3316 -0.460552             0
+2.11661 -0.992708            0
+1.95813 -1.43769             0
+1.91826 -1.72912             0
+1.83121 -1.83277             0
+1.6757 -1.91204              0
+1.50581 -1.93994             0
+0.91874 -1.89528             0
+-0.086052 -1.81483           0
+-0.651007 -1.09872           0
+-0.615758 -0.392913          0
+-0.393843 0.132625           0
+-0.284098 0.418838           0
+-0.258366 0.437323           0
+-0.262974 0.468126           0
+0.0180038 0.377062           0
+0.0449773 0.327324           0
+0.128299 0.336854            0
+0.297876 0.323257            0
+0.402965 0.18143             0
+0.373367 -0.00201841         0
+0.315525 -0.13922            0
+0.279239 -0.242999           0
+0.275543 -0.242753           0
+0.279876 -0.233989           0
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0911607 1.86069            0
+0.134612 2.42822             0
+0.11393 2.54774              0
+0.239782 2.89304             0
+0.38454 3.39314              0
+0.506359 4.46877             0
+0.655883 5.52101             0
+0.73793 6.57492              0
+0.626733 5.91162             0
+0.622878 5.2788              0
+0.875104 5.70684             0
+1.0185 4.05712               0
+1.03351 2.62644              0
+1.17511 1.6677               0
+1.25046 1.13376              0
+1.2901 0.924149              0
+1.31334 0.437335             0
+1.31663 0.507458             0
+1.31277 0.427002             0
+1.32304 -0.0901286           0
+1.38784 -0.706265            0
+1.37487 -0.901873            0
+1.36665 -0.786355            0
+1.32075 -0.6806              0
+1.28396 -0.713758            0
+1.26222 -1.18985             0
+1.21343 -1.68063             0
+1.19453 -2.03872             0
+1.2299 -2.06586              0
+1.22115 -1.76823             0
+1.18887 -2.03884             0
+1.14439 -1.67582             0
+1.13325 -1.30011             0
+1.06283 -1.09575             0
+1.00479 -1.1072              0
+0.966371 -1.32491            0
+0.920684 -1.40639            0
+0.905236 -1.87588            0
+0.933327 -1.81847            0
+0.931535 -1.5951             0
+0.890207 -1.70808            0
+0.853004 -0.945718           0
+0.845928 -0.714034           0
+0.810665 -0.763716           0
+0.766765 -0.886576           0
+0.733744 -0.826087           0
+0.710135 -0.687648           0
+0.701588 -1.26231            0
+0.71366 -1.04794             0
+0.719342 -0.998027           0
+0.732828 -1.5976             0
+0.699252 -1.20079            0
+0.690217 -0.920725           0
+0.639485 -0.679626           0
+0.604624 -0.636375           0
+0.582796 -0.785263           0
+0.555253 -0.706474           0
+0.55048 -0.932222            0
+0.560973 -0.88078            0
+0.567122 -0.86762            0
Index: branches/Mars_McMismatchStudy/msignal/cosmics_weights.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/cosmics_weights.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/cosmics_weights.dat	(revision 17960)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.296762 -0.632805         0
+0.052669 -1.03525          0
+-0.259279 -0.926851        0
+-0.435774 -0.963835        0
+-0.583858 -0.843637        0
+-0.653866 -0.665019        0
+-0.722997 -0.627056        0
+-0.7894 -0.481322          0
+-0.916398 -0.314016        0
+-1.05471 0.000154063       0
+-1.23631 1.12827           0
+-0.772589 1.98746          0
+-0.166435 1.84358          0
+0.202461 2.02063           0
+0.509947 1.80846           0
+0.669284 1.54607           0
+0.834405 1.63452           0
+0.998756 1.44834           0
+1.28039 1.37314            0
+1.63214 1.43295            0
+2.18222 1.3064             0
+2.41072 0.532674           0
+2.32602 -0.191982          0
+2.17997 -0.682484          0
+2.01379 -0.865313          0
+1.91545 -1.0259            0
+1.79855 -1.3302            0
+1.64895 -1.45366           0
+1.34434 -1.67446           0
+0.873027 -2.09955          0
+0.0473139 -2.34944         0
+-0.451361 -1.53652         0
+-0.523845 -0.485103        0
+-0.431676 -0.0878126       0
+-0.332904 0.169116         0
+-0.297262 0.238137         0
+-0.270423 0.350654         0
+-0.245929 0.419744         0
+-0.173941 0.511192         0
+-0.0119864 0.561345        0
+0.202838 0.416069          0
+0.267667 0.122226          0
+0.200201 -0.132905         0
+0.133702 -0.24494          0
+0.0701731 -0.285589        0
+0.0385833 -0.252528        0
+0.0188702 -0.259152        0
+0.00219847 -0.281877       0
+-0.0460886 -0.324774       0
+-0.155267 -0.309696        0
+-0.257781 -0.0760684       0
+-0.259848 0.0358922        0
+-0.225765 0.0960974        0
+-0.20464 0.128228          0
+-0.176549 0.157698         0
+-0.15318 0.150098          0
+-0.144226 0.132703         0
+-0.133485 0.149325         0
+-0.111339 0.194484         0
+-0.0410094 0.201485        0
+# Low Gain Weights: 6 10   
+# (Amplitude)  (Time)      
+0.0446612 -0.385273        0
+0.038191 -0.00418687       0
+0.0386966 0.0212324        0
+0.0402881 0.0744799        0
+0.0415794 0.229615         0
+0.0598731 0.44332          0
+0.0758477 0.661518         0
+0.101509 1.10641           0
+0.159323 1.64997           0
+0.497256 2.83685           0
+0.245087 3.27499           0
+0.140546 2.46177           0
+0.58086 2.2849             0
+0.632721 2.45587           0
+0.72819 2.52835            0
+0.889583 2.48099           0
+0.980812 2.50031           0
+1.09885 2.55892            0
+1.21374 2.78769            0
+1.61928 3.08069            0
+1.38544 1.95583            0
+1.31998 1.1792             0
+1.50633 0.591226           0
+1.50916 0.0793899          0
+1.5008 -0.33188            0
+1.47339 -0.575386          0
+1.45362 -0.915309          0
+1.40214 -1.31593           0
+1.34175 -1.77904           0
+1.0661 -2.05471            0
+1.31087 -1.49798           0
+1.33793 -1.34758           0
+1.10172 -1.21719           0
+1.08133 -1.09356           0
+1.04007 -0.981455          0
+0.976745 -1.08299          0
+0.930979 -1.14774          0
+0.874203 -1.18348          0
+0.816708 -1.20126          0
+0.587354 -1.92869          0
+0.783078 -1.89621          0
+0.792771 -1.03439          0
+0.622278 -0.781807         0
+0.61184 -0.745831          0
+0.578792 -0.683741         0
+0.537336 -0.596328         0
+0.51443 -0.592858          0
+0.482294 -0.560586         0
+0.462351 -0.827587         0
+0.317989 -1.05649          0
+0.459672 -0.775035         0
+0.468287 -0.619961         0
+0.374182 -0.31635          0
+0.376946 -0.225242         0
+0.367075 -0.347444         0
+0.340737 -0.393231         0
+0.321054 -0.187384         0
+0.320654 -0.225558         0
+0.302148 -0.399499         0
+0.232954 -0.607578         0
Index: branches/Mars_McMismatchStudy/msignal/cosmics_weights4.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/cosmics_weights4.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/cosmics_weights4.dat	(revision 17960)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.637443 -0.648763       0
+-0.707555 -0.610204       0
+-0.772465 -0.469694       0
+-0.896081 -0.305143       0
+-1.02783 0.00696361       0
+-1.03684 0.731979         0
+-0.73698 1.49428          0
+-0.23419 1.57509          0
+0.12767 1.83675           0
+0.441087 1.70526          0
+0.639658 1.50546          0
+0.806192 1.58667          0
+0.966865 1.41151          0
+1.24058 1.34506           0
+1.58293 1.39453           0
+2.02092 1.46038           0
+2.31508 0.8539            0
+2.31705 0.051831          0
+2.18497 -0.493294         0
+2.01129 -0.749924         0
+1.8675 -0.959329          0
+1.75322 -1.25026          0
+1.60962 -1.37231          0
+1.3216 -1.58832           0
+0.880364 -1.9924          0
+0.219661 -2.50675         0
+-0.35077 -1.96955         0
+-0.553454 -0.855454       0
+-0.491715 -0.387673       0
+-0.38701 -0.0297507       0
+-0.293549 0.092153        0
+-0.278646 0.194742        0
+-0.263716 0.25195         0
+-0.221238 0.323789        0
+-0.121941 0.381038        0
+0.00379863 0.393009       0
+0.0805122 0.201843        0
+0.0443888 -0.0531952      0
+-0.0199606 -0.175625      0
+-0.0809393 -0.21419       0
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+0.178287 2.98244          0
+0.0799794 2.25048         0
+0.501997 2.04566          0
+0.559993 2.18952          0
+0.636334 2.28558          0
+0.784832 2.29757          0
+0.894393 2.36602          0
+1.01571 2.62578           0
+1.14191 3.14701           0
+1.70405 4.27635           0
+1.25503 1.69442           0
+1.19843 1.00804           0
+1.36974 0.493838          0
+1.37759 0.0452029         0
+1.37174 -0.336051         0
+1.34423 -0.563321         0
+1.31669 -0.852661         0
+1.26602 -1.28826          0
+1.20062 -1.85625          0
+0.874127 -2.44773         0
+1.2433 -1.47361           0
+1.27171 -1.3052           0
+1.03025 -1.1211           0
+1.00417 -0.992811         0
+0.968251 -0.911359        0
+0.907626 -1.02038         0
+0.852293 -1.06813         0
+0.797164 -1.16276         0
+0.739386 -1.25445         0
+0.447754 -2.34757         0
+0.777349 -1.83155         0
+0.779564 -1.01577         0
+0.600426 -0.733238        0
+0.5863 -0.688006          0
+0.557156 -0.650488        0
+0.514926 -0.584649        0
+0.485323 -0.569089        0
+0.454047 -0.573249        0
+0.429026 -0.907077        0
+0.245526 -1.35434         0
Index: branches/Mars_McMismatchStudy/msignal/cosmics_weights46.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/cosmics_weights46.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/cosmics_weights46.dat	(revision 17960)
@@ -0,0 +1,104 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.637443 -0.648763     0
+-0.707555 -0.610204     0
+-0.772465 -0.469694     0
+-0.896081 -0.305143     0
+-1.02783 0.00696361     0
+-1.03684 0.731979       0
+-0.73698 1.49428        0
+-0.23419 1.57509        0
+0.12767 1.83675         0
+0.441087 1.70526        0
+0.639658 1.50546        0
+0.806192 1.58667        0
+0.966865 1.41151        0
+1.24058 1.34506         0
+1.58293 1.39453         0
+2.02092 1.46038         0
+2.31508 0.8539          0
+2.31705 0.051831        0
+2.18497 -0.493294       0
+2.01129 -0.749924       0
+1.8675 -0.959329        0
+1.75322 -1.25026        0
+1.60962 -1.37231        0
+1.3216 -1.58832         0
+0.880364 -1.9924        0
+0.219661 -2.50675       0
+-0.35077 -1.96955       0
+-0.553454 -0.855454     0
+-0.491715 -0.387673     0
+-0.38701 -0.0297507     0
+-0.293549 0.092153      0
+-0.278646 0.194742      0
+-0.263716 0.25195       0
+-0.221238 0.323789      0
+-0.121941 0.381038      0
+0.00379863 0.393009     0
+0.0805122 0.201843      0
+0.0443888 -0.0531952    0
+-0.0199606 -0.175625    0
+-0.0809393 -0.21419     0
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273     0
+0.038191 -0.00418687    0
+0.0386966 0.0212324     0
+0.0402881 0.0744799     0
+0.0415794 0.229615      0
+0.0598731 0.44332       0
+0.0758477 0.661518      0
+0.101509 1.10641        0
+0.159323 1.64997        0
+0.497256 2.83685        0
+0.245087 3.27499        0
+0.140546 2.46177        0
+0.58086 2.2849          0
+0.632721 2.45587        0
+0.72819 2.52835         0
+0.889583 2.48099        0
+0.980812 2.50031        0
+1.09885 2.55892         0
+1.21374 2.78769         0
+1.61928 3.08069         0
+1.38544 1.95583         0
+1.31998 1.1792          0
+1.50633 0.591226        0
+1.50916 0.0793899       0
+1.5008 -0.33188         0
+1.47339 -0.575386       0
+1.45362 -0.915309       0
+1.40214 -1.31593        0
+1.34175 -1.77904        0
+1.0661 -2.05471         0
+1.31087 -1.49798        0
+1.33793 -1.34758        0
+1.10172 -1.21719        0
+1.08133 -1.09356        0
+1.04007 -0.981455       0
+0.976745 -1.08299       0
+0.930979 -1.14774       0
+0.874203 -1.18348       0
+0.816708 -1.20126       0
+0.587354 -1.92869       0
+0.783078 -1.89621       0
+0.792771 -1.03439       0
+0.622278 -0.781807      0
+0.61184 -0.745831       0
+0.578792 -0.683741      0
+0.537336 -0.596328      0
+0.51443 -0.592858       0
+0.482294 -0.560586      0
+0.462351 -0.827587      0
+0.317989 -1.05649       0
+0.459672 -0.775035      0
+0.468287 -0.619961      0
+0.374182 -0.31635       0
+0.376946 -0.225242      0
+0.367075 -0.347444      0
+0.340737 -0.393231      0
+0.321054 -0.187384      0
+0.320654 -0.225558      0
+0.302148 -0.399499      0
+0.232954 -0.607578      0
Index: branches/Mars_McMismatchStudy/msignal/cosmics_weights4_logaintest.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/cosmics_weights4_logaintest.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/cosmics_weights4_logaintest.dat	(revision 17960)
@@ -0,0 +1,85 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time) 
+-0.990564 0.813232      0
+-0.806484 1.74836       0
+-0.43829 2.4249         0
+0.0451181 2.67058       0
+0.463887 3.01401        0
+0.714 3.23898           0
+0.887111 3.15779        0
+1.05327 3.24712         0
+1.32499 3.86809         0
+1.44213 4.59276         0
+2.06205 4.04486         0
+2.45161 2.90439         0
+2.6494 1.52572          0
+2.66069 0.436417        0
+2.55694 -0.362778       0
+2.43585 -1.04956        0
+2.34313 -1.55472        0
+2.24881 -2.11859        0
+2.03605 -2.86169        0
+1.95231 -3.51744        0
+1.6486 -3.72459         0
+1.2416 -3.07972         0
+0.925084 -2.32165       0
+0.684032 -1.68812       0
+0.589887 -1.32468       0
+0.570156 -1.05064       0
+0.561215 -0.620602      0
+0.551184 -0.200923      0
+0.562483 -0.388106      0
+0.561862 -1.06923       0
+0.511264 -0.720139      0
+0.418279 -0.712441      0
+0.378939 -0.269248      0
+0.425153 0.0483749      0
+0.467989 0.158911       0
+0.512818 0.306459       0
+0.533694 0.107538       0
+0.515955 -0.211784      0
+0.483112 -0.217814      0
+0.463744 0.0214888      0
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time) 
+-0.461712  -0.478171    0
+-0.508663  -0.456735    0
+-0.550858  -0.358047    0
+-0.615084  -0.230953    0
+-0.655615  0.0171828    0
+-0.593359  0.573597     0
+-0.354573  1.15547      0
+-0.0166319  1.26005     0
+0.226452  1.52102       0
+0.451298  1.45511       0
+0.527201  1.27282       0
+0.680384  1.38144       0
+0.826361  1.26079       0
+1.05602  1.22515        0
+1.30687  1.29254        0
+1.59171  1.40908        0
+1.77973  0.952821       0
+1.79484  0.245375       0
+1.7262  -0.21442        0
+1.62411  -0.484694      0
+1.73426  -0.615484      0
+1.64165  -0.907105      0
+1.52898  -1.07112       0
+1.30084  -1.29905       0
+0.983446  -1.68008      0
+0.532795  -2.19838      0
+0.133827  -1.90033      0
+-0.0392906  -1.02741    0
+-0.0357089  -0.721406   0
+-0.0139902  -0.385772   0
+-0.414459  -0.200187    0
+-0.406329  -0.0821537   0
+-0.403955  0.0227461    0
+-0.391219  0.127372     0
+-0.347919  0.206207     0
+-0.29191  0.277449      0
+-0.234367  0.24775      0
+-0.228396  0.104672     0
+-0.238849  0.0733048    0
+-0.245189  0.0500998    0
+
Index: branches/Mars_McMismatchStudy/msignal/cosmics_weights_logaintest.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/cosmics_weights_logaintest.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/cosmics_weights_logaintest.dat	(revision 17960)
@@ -0,0 +1,125 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time) 
+-0.0851354 -0.0818943        0
+-0.121924 -0.584977          0
+-0.269186 -0.874395          0
+-0.470451 -1.00063           0
+-0.662756 -1.12938           0
+-0.770093 -1.10388           0
+-0.835339 -0.995019          0
+-0.899395 -0.884381          0
+-0.983397 -0.628212          0
+-0.997415 -0.00715026        0
+-1.11376 -0.0168757          0
+-1.0091 1.14057              0
+-0.638545 2.07741            0
+-0.107314 2.54285            0
+0.380996 3.02362             0
+0.731444 3.34887             0
+0.959498 3.28988             0
+1.17934 3.38254              0
+1.57619 4.01168              0
+1.8263 4.58323               0
+2.07564 5.08144              0
+2.53926 3.80961              0
+2.86297 2.12543              0
+2.91748 0.749097             0
+2.80503 -0.228309            0
+2.6423 -1.05946              0
+2.50982 -1.64579             0
+2.36653 -2.27444             0
+2.05553 -3.101               0
+1.87853 -3.72935             0
+2.03964 -4.75531             0
+1.43034 -4.09923             0
+0.877873 -2.95319            0
+0.551859 -1.99114            0
+0.451674 -1.45197            0
+0.44424 -1.0055              0
+0.467447 -0.55123            0
+0.471455 -0.160571           0
+0.48432 -0.250935            0
+0.432957 -0.747835           0
+-0.195425 0.688031                            0
+-0.128512 0.426902                            0
+-0.0250589 0.67848                            0
+0.111442 0.594296                             0
+0.137021 0.454404                             0
+0.18465 0.425805                              0
+0.173857 0.191566                             0
+0.166493 -0.088923                            0
+0.129184 -0.103965                            0
+0.150974 0.0291908                            0
+0.43261 -0.441491                             0
+0.385866 -0.245876                            0
+0.281277 -0.66199                             0
+0.148729 -0.538564                            0
+0.153182 -0.382713                            0
+0.106348 -0.355415                            0
+0.123019 -0.263842                            0
+0.0911191 -0.197345                           0
+0.0963107 -0.229423                           0
+0.0550985 -0.187527                           0
+# Low Gain Weights: 6 10                      
+# (Amplitude)  (Time)                         
+	0.190173	-0.352992             0
+	0.155921	-0.475234             0
+	0.111158	-0.510688             0
+	0.0258716	-0.585781             0
+	-0.0846783	-0.752984             0
+	-0.259831	-1.02767              0
+	-0.439926	-1.02041              0
+	-0.585558	-0.734472             0
+	-0.663611	-0.690174             0
+	-0.73984	-0.576795             0
+	-0.672748	-0.173961             0
+	-0.693405	-0.0130429            0
+	-0.699736	0.1524                0
+	-0.698901	0.407909              0
+	-0.638204	0.836755              0
+	-0.44419	1.55279               0
+	-0.142557	1.8777                0
+	0.153996	1.59209               0
+	0.356156	1.7666                0
+	0.564031	1.65896               0
+	0.707804	1.38728               0
+	0.85022	1.45257                       0
+	0.99052	1.2707                        0
+	1.22473	1.15456                       0
+	1.46489	1.05566                       0
+	1.70603	0.973196                      0
+	1.857	0.57388                       0
+	1.8993	0.113422                      0
+	1.88339	-0.2337                       0
+	1.83839	-0.429011                     0
+	1.78206	-0.626315                     0
+	1.71376	-0.903836                     0
+	1.61136	-1.05343                      0
+	1.41208	-1.25025                      0
+	1.14602	-1.52358                      0
+	0.805571	-1.90971              0
+	0.502163	-1.71115              0
+	0.294872	-1.13556              0
+	0.189728	-1.07744              0
+	0.084943	-0.887703             0
+	-0.0316251	-0.719687             0
+	-0.109198	-0.668266             0
+	-0.185341	-0.531971             0
+	-0.300562	-0.397775             0
+	-0.390757	-0.259113             0
+	-0.449349	-0.0664538            0
+	-0.438326	0.189747              0
+	-0.387571	0.299769              0
+	-0.33554	0.456087              0
+	-0.272877	0.508469              0
+	-0.0686699	0.350793              0
+	-0.0289917	0.38007               0
+	0.0150257	0.319358              0
+	0.0807497	0.267639              0
+	0.144026	0.199999              0
+	0.187235	0.0767841             0
+	0.183333	-0.124801             0
+	0.139438	-0.239748             0
+	0.0952476	-0.3751               0
+	0.0410329	-0.38942              0
+
Index: branches/Mars_McMismatchStudy/msignal/pulpo_weights.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/pulpo_weights.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/pulpo_weights.dat	(revision 17960)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+-0.12431 0.185239              0
+-0.0267055 0.0037991           0
+-0.0259801 -0.423405           0
+-0.183327 -0.800635            0
+-0.40724 -0.758845             0
+-0.54078 -0.801479             0
+-0.662083 -0.722269            0
+-0.720992 -0.554825            0
+-0.773543 -0.498706            0
+-0.825219 -0.351983            0
+-0.862103 -0.262895            0
+-1.00393 0.21406               0
+-0.930389 1.22904              0
+-0.520129 1.99452              0
+-0.0150508 1.81237             0
+0.292189 1.98133               0
+0.570068 1.78746               0
+0.719691 1.52423               0
+0.864022 1.60506               0
+1.02168 1.41713                0
+1.26558 1.35391                0
+1.61344 1.34607                0
+2.01336 1.22433                0
+2.20595 0.50917                0
+2.15054 -0.160944              0
+2.04229 -0.623651              0
+1.90462 -0.810952              0
+1.81945 -0.967633              0
+1.72207 -1.25811               0
+1.58263 -1.37678               0
+1.30022 -1.58265               0
+0.85573 -1.91552               0
+0.25147 -2.17209               0
+-0.16104 -1.45872              0
+-0.249172 -0.520003            0
+-0.199678 -0.182078            0
+-0.142631 0.0632378            0
+-0.123823 0.124224             0
+-0.113025 0.213306             0
+-0.102673 0.272495             0
+0.0188075 0.287166             0
+0.108756 0.28294               0
+0.192197 0.181065              0
+0.209837 -0.00954936           0
+0.157036 -0.154499             0
+0.113306 -0.229067             0
+0.0699705 -0.249718            0
+0.0446349 -0.217674            0
+0.0293213 -0.222187            0
+0.0159978 -0.24989             0
+-0.309299 -0.195262            0
+-0.355871 -0.195246            0
+-0.410243 -0.208791            0
+-0.458189 -0.179693            0
+-0.486599 -0.0937612           0
+-0.502873 -0.0553459           0
+-0.50502 0.00789869            0
+-0.494301 0.0521942            0
+-0.492681 0.0475246            0
+-0.486371 0.0990417            0
+# Low Gain Weights: 6 10       
+# (Amplitude)  (Time)          
+-0.508787 -1.8512              0
+-0.482402 -1.06646             0
+-0.764704 -1.0321              0
+-0.89732 -1.08093              0
+-1.00112 -0.949638             0
+-1.08997 -0.731505             0
+-1.15379 -0.55427              0
+-1.23129 -0.208521             0
+-1.24038 0.181441              0
+-1.0946 1.5747                 0
+-0.760548 3.89286              0
+-0.768054 2.78435              0
+-0.0388176 2.74531             0
+0.30468 3.00492                0
+0.607574 3.03692               0
+0.919068 3.02925               0
+1.21051 3.06817                0
+1.56039 3.21235                0
+1.83534 3.54928                0
+2.60839 4.14646                0
+2.29192 1.47429                0
+2.26241 0.98134                0
+2.41491 0.106406               0
+2.32984 -0.768902              0
+2.19051 -1.3234                0
+2.03991 -1.59426               0
+1.88649 -2.01044               0
+1.63313 -2.5487                0
+1.42679 -3.31539               0
+0.649283 -3.91761              0
+0.937235 -1.55157              0
+0.904694 -1.63591              0
+0.549783 -1.06607              0
+0.524229 -0.397922             0
+0.54955 -0.0404911             0
+0.546924 -0.138923             0
+0.506861 -0.00935328           0
+0.519261 0.118637              0
+0.48628 0.51656                0
+0.571592 -0.313517             0
+0.60678 -1.15412               0
+0.601982 -0.153964             0
+0.566105 -0.196816             0
+0.523068 -0.415408             0
+0.464942 -0.445999             0
+0.428435 -0.354879             0
+0.40545 -0.523187              0
+0.321979 -0.606825             0
+0.312933 -1.06197              0
+0.0312496 -1.21027             0
+-0.113826 -0.71054             0
+-0.123841 -0.810667            0
+-0.28705 -0.429981             0
+-0.298861 -0.222333            0
+-0.315921 -0.263296            0
+-0.353192 -0.316989            0
+-0.397503 -0.0799875           0
+-0.375387 -0.0788394           0
+-0.411545 -0.0428121           0
+-0.404853 -0.296136            0
Index: branches/Mars_McMismatchStudy/msignal/pulpo_weights4.dat
===================================================================
--- branches/Mars_McMismatchStudy/msignal/pulpo_weights4.dat	(revision 17960)
+++ branches/Mars_McMismatchStudy/msignal/pulpo_weights4.dat	(revision 17960)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.830773 -0.513332              0
+-0.883684 -0.367084              0
+-0.981636 -0.181162              0
+-1.0654 0.181257                 0
+-0.989822 0.940191               0
+-0.64358 1.59018                 0
+-0.170784 1.55768                0
+0.153406 1.78731                 0
+0.443244 1.66404                 0
+0.589961 1.42946                 0
+0.834668 1.56661                 0
+0.99416 1.38965                  0
+1.26811 1.31138                  0
+1.60335 1.32056                  0
+1.99633 1.31936                  0
+2.23206 0.747258                 0
+2.22358 0.0467182                0
+2.11605 -0.439809                0
+1.97093 -0.678148                0
+1.88466 -0.862697                0
+1.70404 -1.19545                 0
+1.56508 -1.315                   0
+1.28049 -1.51062                 0
+0.853542 -1.84239                0
+0.269082 -2.21694                0
+-0.1855 -1.69602                 0
+-0.332178 -0.756789              0
+-0.286346 -0.395196              0
+-0.215935 -0.0982026             0
+-0.194873 0.00415795             0
+-0.181069 0.0877068              0
+-0.176841 0.139735               0
+-0.149863 0.184439               0
+-0.081151 0.160871               0
+-0.0351086 0.0185016             0
+-0.0674657 -0.19927              0
+-0.184774 -0.322906              0
+-0.280436 -0.407465              0
+-0.362954 -0.392359              0
+-0.393249 -0.299451              0
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.895686 2.74051                0
+-0.894816 2.07478                0
+-0.29184 2.11503                 0
+0.0665281 2.43427                0
+0.35031 2.52029                  0
+0.568335 2.53046                 0
+0.747945 2.56963                 0
+0.943671 2.77718                 0
+1.09444 3.22759                  0
+1.66295 4.63169                  0
+2.24768 1.97632                  0
+2.20569 1.23156                  0
+2.40659 0.413157                 0
+2.29192 -0.421216                0
+2.12793 -1.00932                 0
+2.01982 -1.29659                 0
+1.9169 -1.66267                  0
+1.77059 -2.21215                 0
+1.65931 -3.01017                 0
+1.07882 -4.32181                 0
+0.697307 -1.78007                0
+0.660479 -1.69108                0
+0.291088 -1.17701                0
+0.307283 -0.541925               0
+0.385063 -0.125812               0
+0.379987 -0.167953               0
+0.3629 -0.0595063                0
+0.376758 0.0997659               0
+0.347217 0.48611                 0
+0.4555 -0.0459001                0
+0.386874 -1.7207                 0
+0.414701 -0.700196               0
+0.264508 -0.520446               0
+0.179367 -0.635974               0
+0.0945086 -0.675258              0
+0.0590596 -0.576493              0
+0.0266148 -0.56912               0
+-0.0221451 -0.604525             0
+-0.0287237 -0.951405             0
+-0.225035 -1.19463               0
Index: branches/Mars_McMismatchStudy/msim/MHPhotonEvent.cc
===================================================================
--- branches/Mars_McMismatchStudy/msim/MHPhotonEvent.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MHPhotonEvent.cc	(revision 17960)
@@ -0,0 +1,458 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPhotonEvent
+//
+// This is a histogram class to visualize the contents of a MPhotonEvent.
+//
+// Histograms for the distribution in x/y (z is just ignored), the
+// arrival direction, a profile of the arrival time vs position and
+// a spectrum is filles and displayed.
+//
+// There are several types of histograms (in the sense of binnings)
+// for several purposes:
+//
+// Type 1:
+//   The maximum in x and y is determined from MCorsikaRunHeader
+//   (not yet implemented. Fixed to 25000, 100 bins)
+//
+// Type 2:
+//   The maximum in x and y is determined from MReflector->GetMaxR();
+//   (100 bins)
+//
+// Type 3:
+//   The maximum in x and y is determined from MGeomCam->GetMaxR();
+//   (roughly 10 bins per pixel)
+//
+// Type 4:
+//   Two times the traversal size of pixel #0 ( 4*MGeomCam[0].GetT() )
+//   (101 bins, units cm)
+//
+// Type 5:
+//   As type 3 but in cm instead of mm
+//
+// The binning is optimized using MH::FindGoodLimits.
+//
+// Fill expects a MPhotonEvent (the second argumnet in MFillH).
+//
+//
+// Class Version 2:
+// ----------------
+//  + TH1D fHistH;
+//
+// Class Version 3:
+// ----------------
+//  + replaced TH1D by TH1F
+//  + replaced TH2D by TH2F
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPhotonEvent.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MCorsikaRunHeader.h"
+
+#include "MReflector.h"
+
+ClassImp(MHPhotonEvent);
+
+using namespace std;
+
+void MHPhotonEvent::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHPhotonEvent";
+    fTitle = title ? title : "Histogram to display the information of MPhotonEvents";
+
+    fHistXY.SetName("Position");
+    fHistXY.SetTitle("Histogram of position x/y");
+    fHistXY.SetXTitle("X [cm]");
+    fHistXY.SetYTitle("Y [cm]");
+    fHistXY.SetZTitle("Counts");
+    fHistXY.SetDirectory(NULL);
+    fHistXY.Sumw2();
+
+    fHistUV.SetName("Direction");
+    fHistUV.SetTitle("Histogram of arrival direction CosU/CosV");
+    fHistUV.SetXTitle("CosU");
+    fHistUV.SetYTitle("CosV");
+    fHistUV.SetZTitle("Counts");
+    fHistUV.SetDirectory(NULL);
+    fHistUV.Sumw2();
+
+    fHistT.SetName("Time");
+    fHistT.SetTitle("Time profile in x/y");
+    fHistT.SetXTitle("X [cm]");
+    fHistT.SetYTitle("Y [cm]");
+    fHistT.SetZTitle("T [ns]");
+    fHistT.SetDirectory(NULL);
+
+    fHistWL.SetName("Spectrum");
+    fHistWL.SetTitle("Wavelength distribution");
+    fHistWL.SetXTitle("\\lambda [nm]");
+    fHistWL.SetYTitle("Counts");
+    fHistWL.SetDirectory(NULL);
+
+    fHistH.SetName("Height");
+    fHistH.SetTitle("Production Height");
+    fHistH.SetXTitle("h [km]");
+    fHistH.SetYTitle("Counts");
+    fHistH.SetDirectory(NULL);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates and initializes the histograms.
+//
+MHPhotonEvent::MHPhotonEvent(Double_t max, const char *name, const char *title)
+    : fHistT("", "", 1, 0, 1, 1, 0, 1), fType(-1), fPermanentReset(kFALSE)
+{
+    // pre-initialization of the profile is necessary to get fZmin and fZmax set
+
+    Init(name, title);
+
+    const MBinning binsd(51, -max, max);
+    const MBinning binsa(51, -1,   1);
+
+    SetBinning(fHistXY, binsd, binsd);
+    SetBinning(fHistUV, binsa, binsa);
+    SetBinning(fHistT,  binsd, binsd);
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates and initializes the histograms.
+//
+MHPhotonEvent::MHPhotonEvent(Int_t type, const char *name, const char *title)
+    : fHistT("", "", 1, 0, 1, 1, 0, 1), fType(type), fPermanentReset(kFALSE)
+{
+    // pre-initialization of the profile is necessary to get fZmin and fZmax set
+
+    Init(name, title);
+
+    const MBinning bins(51, -1, 1);
+
+    SetBinning(fHistUV, bins, bins);
+}
+
+// --------------------------------------------------------------------------
+//
+// Find good limits for a binning num x [-max;max]
+// and apply it to fHistXY and fHistT.
+//
+void MHPhotonEvent::SetBinningXY(Int_t num, Double_t max)
+{
+    Double_t min = -max;
+
+    MH::FindGoodLimits(num, num, min, max, kFALSE);
+    MH::FindGoodLimits(num, num, min, max, kFALSE);
+
+    const MBinning binsd(num+1, min, max);
+
+    SetBinning(fHistXY, binsd, binsd);
+    SetBinning(fHistT,  binsd, binsd);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for MRflEvtData, MRflEvtHeader and MGeomCam
+//
+Bool_t MHPhotonEvent::SetupFill(const MParList *pList)
+{
+    Double_t xmax =  -1;
+    Int_t    num  = 100;
+
+    const Int_t f = fPermanentReset ? 2 : 1;
+    MBinning(100/f, 0, 25).Apply(fHistH);
+    MBinning(70, 275, 625).Apply(fHistWL);
+
+    switch (fType)
+    {
+    case -1:
+        return kTRUE;
+        // case0: Take a value defined by the user
+    case 1:
+        xmax = 25000;
+        break;
+    case 2:
+        {
+            MReflector *r = (MReflector*)pList->FindObject("Reflector", "MReflector");
+            if (!r)
+            {
+                *fLog << err << "Reflector [MReflector] not found... aborting." << endl;
+                return kFALSE;
+            }
+            xmax = r->GetMaxR();
+            break;
+        }
+    case 3: // The maximum radius (mm)
+        fHistXY.SetXTitle("X [mm]");
+        fHistXY.SetYTitle("Y [mm]");
+        fHistT.SetXTitle("X [mm]");
+        fHistT.SetYTitle("Y [mm]");
+        // *Fallthrough*
+
+    case 4: // Two times the pixel-0 traversal size
+    case 5: // The maximum radius (cm) -- ~ 10 bins / pix
+    case 6: // The maximum radius (cm) -- ~  5 bins / pix
+    case 7: // The maximum radius (cm) -- ~  3 bins / pix
+    case 8: // The maximum radius (cm) -- ~  2 bins / pix
+        {
+            MGeomCam *c = (MGeomCam*)pList->FindObject("MGeomCam");
+            if (!c)
+            {
+                *fLog << err << "MGeomCam not found... aborting." << endl;
+                return kFALSE;
+            }
+            // Type 3: Define ~10 bins per pixel
+            xmax = fType!=4 ? c->GetMaxRadius() : 4*(*c)[0].GetT()/10;
+
+            switch (fType)
+            {
+            case 3:
+            case 5:
+                // ~10 bins per pixel
+                num = TMath::Nint(10*c->GetMaxRadius()/(*c)[0].GetT());
+                break;
+            case 6:
+                // ~5 bins per pixel
+                num = TMath::Nint(5*c->GetMaxRadius()/(*c)[0].GetT());
+                break;
+            case 7:
+                // ~3 bins per pixel
+                num = TMath::Nint(3*c->GetMaxRadius()/(*c)[0].GetT());
+                break;
+            case 8:
+                // ~2 bins per pixel
+                num = TMath::Nint(2*c->GetMaxRadius()/(*c)[0].GetT());
+                break;
+            case 4:
+                num = 101;
+                break;
+            }
+
+            if (fType==5 || fType==6 || fType==7)
+                xmax /= 10;
+
+            break;
+        }
+    default:
+        *fLog << err << "No valid binning (Type=" << fType << ") given... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinningXY(num, xmax);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit overwrites the binning of the Wavelength histogram
+// by the wavlenegth band from MCorsikaRunHeader.
+// The bin-width is 5nm (fPermanentReset==kTRUE) or 10nm (kFALSE).
+//
+Bool_t MHPhotonEvent::ReInit(MParList *pList)
+{
+    MCorsikaRunHeader *h = (MCorsikaRunHeader*)pList->FindObject("MCorsikaRunHeader");
+    if (!h)
+    {
+        *fLog << err << "MCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    /*
+    // What is the size of the light pool onm the ground?
+    if (fType==1)
+        SetBinningXY(100, h->GetImpactMax());
+    */
+
+    const Int_t f = fPermanentReset ? 10 : 2;
+
+    Double_t xmin = h->GetWavelengthMin()-20;
+    Double_t xmax = h->GetWavelengthMax()+20;
+    Int_t    num  = TMath::CeilNint((xmax-xmin)/f);
+
+    MH::FindGoodLimits(num, num, xmin, xmax, kTRUE);
+
+    MBinning(TMath::Abs(num), xmin-.5, xmax-.5).Apply(fHistWL);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill contents of MPhotonEvent into histograms
+//
+Int_t MHPhotonEvent::Fill(const MParContainer *par, const Stat_t weight)
+{
+    const MPhotonEvent *evt = dynamic_cast<const MPhotonEvent*>(par);
+    if (!evt)
+    {
+        *fLog << err << dbginf << "No MPhotonEvent found..." << endl;
+        return kERROR;
+    }
+
+    // Check if we want to use this class as a single event display
+    if (fPermanentReset && evt->GetNumPhotons()>0)
+        Clear();
+
+    // Get number of photons
+    const Int_t num = evt->GetNumPhotons();
+
+    // Set minimum to maximum possible value
+    Double_t min = FLT_MAX;
+
+    // Loop over all photons and determine the time of the first photon
+    // FIXME: Should we get it from some statistics container?
+    for (Int_t idx=0; idx<num; idx++)
+        min = TMath::Min(min, (*evt)[idx].GetTime());
+
+    // Now fill all histograms
+    for (Int_t idx=0; idx<num; idx++)
+    {
+        const MPhotonData &ph = (*evt)[idx];
+
+        if (ph.GetPrimary()==MMcEvtBasic::kNightSky || ph.GetPrimary()==MMcEvtBasic::kArtificial)
+            continue;
+
+        const Double_t x = ph.GetPosX();
+        const Double_t y = ph.GetPosY();
+        const Double_t u = ph.GetCosU();
+        const Double_t v = ph.GetCosV();
+        const Double_t t = ph.GetTime()-min;
+        const Double_t w = ph.GetWavelength();
+        const Double_t h = ph.GetProductionHeight()/100000;
+
+        //TVector3 dir = dat->GetDir3();
+        //dir *= -1./dir.Z();
+
+        fHistXY.Fill(x, y);
+        fHistUV.Fill(u, v);
+        fHistT.Fill(x, y, t);
+        fHistWL.Fill(w);
+        fHistH.Fill(h);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+/*
+Bool_t MHPhotonEvent::Finalize()
+{
+    const TAxis &axey = *fHistRad.GetYaxis();
+    for (int y=1; y<=fHistRad.GetNbinsY(); y++)
+    {
+        const Double_t lo = axey.GetBinLowEdge(y);
+        const Double_t hi = axey.GetBinLowEdge(y+1);
+
+        const Double_t A = (hi*hi-lo*lo)*TMath::Pi()*TMath::Pi();
+
+        for (int x=1; x<=fHistRad.GetNbinsX(); x++)
+            fHistRad.SetBinContent(x, y, fHistRad.GetBinContent(x, y)/A);
+    }
+    return kTRUE;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Make sure that the TProfile2D doesn't fix it's displayed minimum at 0.
+// Set the pretty-palette.
+//
+void MHPhotonEvent::Paint(Option_t *opt)
+{
+    SetPalette("pretty");
+
+    fHistT.SetMinimum();
+    fHistT.SetMinimum(fHistT.GetMinimum(0));
+}
+
+// --------------------------------------------------------------------------
+//
+void MHPhotonEvent::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    pad->Divide(3,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGrid();
+    fHistXY.Draw("colz");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGrid();
+    fHistT.Draw("colz");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGrid();
+    fHistUV.Draw("colz");
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->SetGrid();
+    fHistWL.Draw();
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->SetGrid();
+    fHistH.Draw();
+}
+
+// --------------------------------------------------------------------------
+//
+// PermanentReset: Off
+//
+Int_t MHPhotonEvent::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "PermanentReset", print))
+    {
+        rc = kTRUE;
+        fPermanentReset = GetEnvValue(env, prefix, "PermanentReset", fPermanentReset);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msim/MHPhotonEvent.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/MHPhotonEvent.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MHPhotonEvent.h	(revision 17960)
@@ -0,0 +1,68 @@
+#ifndef MARS_MHPhotonEvent
+#define MARS_MHPhotonEvent
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TProfile2D
+#include <TProfile2D.h>
+#endif
+
+class MPhotonEvent;
+
+class MHPhotonEvent : public MH
+{
+private:
+    TH2F       fHistXY;
+    TH2F       fHistUV;
+    TProfile2D fHistT;
+    TH1F       fHistWL;
+    TH1F       fHistH;
+
+    Int_t      fType;
+    Bool_t     fPermanentReset;
+
+    // MHPhotonEvent
+    void Init(const char *name, const char *title);
+    void SetBinningXY(Int_t num, Double_t max);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Fill(const MParContainer *par, const Stat_t weight=1);
+    //Bool_t Finalize();
+
+public:
+    MHPhotonEvent(Double_t max, const char *name=0, const char *title=0);
+    MHPhotonEvent(Int_t type=3, const char *name=0, const char *title=0);
+
+    void PermanentReset(Bool_t b=kTRUE) { fPermanentReset=b; }
+
+    // TObject
+    void Draw(Option_t *o="");
+    void Paint(Option_t *o="");
+
+    void Clear(Option_t *o="")
+    {
+        fHistXY.Reset();
+        fHistUV.Reset();
+        fHistT.Reset();
+        fHistWL.Reset();
+        fHistH.Reset();
+    }
+
+    const TH2F &GetHistXY() const { return fHistXY; }
+    const TProfile2D &GetHistT() const  { return fHistT; }
+
+    ClassDef(MHPhotonEvent, 3) // Histogram to display the information of MPhotonEvents
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msim/MPhotonData.cc
===================================================================
--- branches/Mars_McMismatchStudy/msim/MPhotonData.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MPhotonData.cc	(revision 17960)
@@ -0,0 +1,345 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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:thomas.bretz@epfl.ch>
+!   Author(s): Qi Zhe,       06/2007 <mailto:qizhe@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPhotonData
+//
+//  Storage container to store Corsika events
+//
+// For details on the coordinate systems see our Wiki.
+//
+//   Version 1:
+//   ----------
+//    * First implementation
+//
+//   Version 2:
+//   ----------
+//    - fNumPhotons
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPhotonData.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TMath.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MPhotonData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MPhotonData::MPhotonData(/*const char *name, const char *title*/)
+    : fPosX(0), fPosY(0), fCosU(0), fCosV(0), fTime(0), fWavelength(0),
+    /*fNumPhotons(1),*/ fProductionHeight(0), fPrimary(MMcEvtBasic::kUNDEFINED),
+    fTag(-1), fWeight(1)
+{
+   // fName  = name  ? name  : "MPhotonData";
+   // fTitle = title ? title : "Corsika Event Data Information";
+}
+
+/*
+MPhotonData::MPhotonData(const MPhotonData &ph)
+: fPosX(ph.fPosX), fPosY(ph.fPosY), fCosU(ph.fCosU), fCosV(ph.fCosV),
+fTime(ph.fTime), fWavelength(ph.fWavelength), fNumPhotons(ph.fNumPhotons),
+fProductionHeight(ph.fProductionHeight), fPrimary(ph.fPrimary),
+fTag(ph.fTag), fWeight(ph.fWeight)
+{
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Copy function. Copy all data members into obj.
+//
+void MPhotonData::Copy(TObject &obj) const
+{
+    MPhotonData &d = static_cast<MPhotonData&>(obj);
+
+//    d.fNumPhotons       = fNumPhotons;
+    d.fPosX             = fPosX;
+    d.fPosY             = fPosY;
+    d.fCosU             = fCosU;
+    d.fCosV             = fCosV;
+    d.fWavelength       = fWavelength;
+    d.fPrimary          = fPrimary;
+    d.fTime             = fTime;
+    d.fTag              = fTag;
+    d.fWeight           = fWeight;
+    d.fProductionHeight = fProductionHeight;
+
+    TObject::Copy(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the square cosine of the Theta-angle == 1-CosU^2-CosV^2
+//
+Double_t MPhotonData::GetCosW2() const
+{
+    return 1 - GetSinW2();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the square sine of the Theta-angle == CosU^2+CosV^2
+//
+Double_t MPhotonData::GetSinW2() const
+{
+    return fCosU*fCosU + fCosV*fCosV;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the cosine of the Theta-angle == sqrt(1-CosU^2-CosV^2)
+//
+Double_t MPhotonData::GetCosW() const
+{
+    return TMath::Sqrt(GetCosW2());
+}
+
+// --------------------------------------------------------------------------
+//
+// return the sine of the Theta-angle == sqrt(CosU^2+CosV^2)
+//
+Double_t MPhotonData::GetSinW() const
+{
+    return TMath::Sqrt(GetSinW2());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the theta angle in radians
+//
+Double_t MPhotonData::GetTheta() const
+{
+    return TMath::ASin(GetSinW());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a TQuaternion with the first three components x, y, and z
+// and the fourth component the time.
+//
+TQuaternion MPhotonData::GetPosQ() const
+{
+    return TQuaternion(GetPos3(), fTime);
+}
+
+// --------------------------------------------------------------------------
+//
+// return a TQuaternion with the first three components the direction
+// moving in space (GetDir3()) and the fourth component is the
+// one devided by the speed of light (converted to cm/ns)
+//
+// FIXME: v in air!
+//
+TQuaternion MPhotonData::GetDirQ() const
+{
+    return TQuaternion(GetDir3(), 1./(TMath::C()*100/1e9));
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the wavelength to a random lambda^-2 distributed value
+// between wmin and wmax.
+//
+void MPhotonData::SimWavelength(Float_t wmin, Float_t wmax)
+{
+    const Double_t w = gRandom->Uniform(wmin, wmax);
+
+    fWavelength = TMath::Nint(wmin*wmax / w);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the data member according to the 8 floats read from a reflector-file.
+// This function MUST reset all data-members, no matter whether these are
+// contained in the input stream.
+//
+Int_t MPhotonData::FillRfl(Float_t f[8])
+{
+    // Check coordinate system!!!!
+    fWavelength = TMath::Nint(f[0]);
+    fPosX = f[1];  // [cm]
+    fPosY = f[2];  // [cm]
+    fCosU = f[3];  // cos to x
+    fCosV = f[4];  // cos to y
+    fTime = f[5];  // [ns]
+    fProductionHeight = f[6];
+
+    // f[7]: Camera inclination angle
+
+    fPrimary    = MMcEvtBasic::kUNDEFINED;
+//    fNumPhotons =  1;
+    fTag        = -1;
+    fWeight     =  1;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the data member according to the 7 floats read from a corsika-file.
+// This function MUST reset all data-members, no matter whether these are
+// contained in the input stream.
+//
+// Currently we exchange x and y and set y=-y to convert Corsikas coordinate
+// system intpo our own.
+//
+Int_t MPhotonData::FillCorsika(Float_t f[7], Int_t i)
+{
+    const UInt_t n = TMath::Nint(f[0]);
+
+    if (n==0)
+        // FIXME: Do we need to decode the rest anyway?
+        return kCONTINUE;
+
+    // Check reuse
+    if (i >=0)
+      {
+       const Int_t reuse = (n/1000)%100; // Force this to be 1!
+       if (reuse!=i)
+           return kCONTINUE;
+      }
+
+    // This seems to be special to mmcs
+    fWavelength = n%1000;
+    fPrimary    = MMcEvtBasic::ParticleId_t(n/100000);
+
+    // x=north, y=west
+    //fPosX = f[1];  // [cm]
+    //fPosY = f[2];  // [cm]
+    //fCosU = f[3];  // cos to x
+    //fCosV = f[4];  // cos to y
+    // x=west, y=south
+    fPosX =  f[2];  // [cm]
+    fPosY = -f[1];  // [cm]
+
+    fCosU =  f[4];  // cos to x
+    fCosV = -f[3];  // cos to y
+
+    fTime =  f[5];  // [ns]
+
+    fProductionHeight = f[6]; // [cm]
+
+    // Now reset all data members which are not in the stream
+    fTag    = -1;
+    fWeight =  1;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the data member according to the 8 floats read from a eventio-file.
+// This function MUST reset all data-members, no matter whether these are
+// contained in the input stream.
+//
+// Currently we exchange x and y and set y=-y to convert Corsikas coordinate
+// system into our own.
+//
+Int_t MPhotonData::FillEventIO(Float_t f[8])
+{
+    // photons in this bunch
+    const UInt_t n = TMath::Nint(f[6]);
+    if (n==0)
+        return 0;
+
+    f[6] = n-1;
+
+    fPosX             =  f[1];              // xpos relative to telescope [cm]
+    fPosY             = -f[0];              // ypos relative to telescope [cm]
+    fCosU             =  f[3];              // cos to x
+    fCosV             = -f[2];              // cos to y
+    fTime             =  f[4];              // a relative arival time [ns]
+    fProductionHeight =  f[5];              // altitude of emission [cm]
+    fWavelength       =  TMath::Nint(f[7]); // so far always zeor = unspec. [nm]
+
+    // Now reset all data members which are not in the stream
+    fPrimary    = MMcEvtBasic::kUNDEFINED;
+    fTag        = -1;
+    fWeight     =  1;
+
+    return n;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Read seven floats from the stream and call FillCorsika for them.
+//
+Int_t MPhotonData::ReadCorsikaEvt(istream &fin)
+{
+    Float_t f[7];
+    fin.read((char*)&f, 7*4);
+
+    const Int_t rc = FillCorsika(f);
+
+    return rc==kTRUE ? !fin.eof() : rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read eight floats from the stream and call FillRfl for them.
+//
+Int_t MPhotonData::ReadRflEvt(istream &fin)
+{
+    Float_t f[8];
+    fin.read((char*)&f, 8*4);
+
+    const Int_t rc = FillRfl(f);
+
+    return rc==kTRUE ? !fin.eof() : rc;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Print contents. The tag and Weight are only printed if they are different
+// from the default.
+//
+void MPhotonData::Print(Option_t *) const
+{
+    gLog << inf << endl;
+//    gLog << "Num Photons:      " << fNumPhotons << " from " << MMcEvtBasic::GetParticleName(fPrimary) << endl;
+    gLog << "Origin:           " << MMcEvtBasic::GetParticleName(fPrimary) << endl;
+    gLog << "Wavelength:       " << fWavelength << "nm" << endl;
+    gLog << "Pos X/Y  Cos U/V: " << fPosX << "/" << fPosY << "   " << fCosU << "/" << fCosV << endl;
+    gLog << "Time/Prod.Height: " << fTime << "ns/" << fProductionHeight << "cm" << endl;
+    if (fTag>=0)
+        gLog << "Tag:              " << fTag << endl;
+    if (fWeight!=1)
+        gLog << "Weight:           " << fWeight << endl;
+}
Index: branches/Mars_McMismatchStudy/msim/MPhotonData.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/MPhotonData.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MPhotonData.h	(revision 17960)
@@ -0,0 +1,136 @@
+#ifndef MARS_MPhotonData
+#define MARS_MPhotonData
+
+#ifndef MARS_MMcEvtBasic
+#include "MMcEvtBasic.h"
+#endif
+
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+#ifndef ROOT_TQuaternion
+#include <math.h>
+#define sqrt ::sqrt
+#include <TQuaternion.h>
+#undef sqrt
+#endif
+
+// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MCorsikaRunHeader;
+
+class MPhotonData : public TObject
+{
+private:
+    Float_t fPosX;                       // [cm] "+west"    "-east"  (both at observation level)
+    Float_t fPosY;                       // [cm] "+south"   "-north" (north denotes the magnet north which is defined to be in the geografic north!)
+
+    Float_t fCosU;                       // [cos x] U direction cosine to x-axis
+    Float_t fCosV;                       // [cos y] V direction cosine to y-axis
+
+    Float_t fTime;                       // [ns] Time since first interaction or entrance into atmosphere
+    UShort_t fWavelength;                // [nm] Wavelength
+//    UInt_t   fNumPhotons;                // Number of cherenkov photons ins bunch
+    Float_t  fProductionHeight;          // [cm] Height of bunch production
+    MMcEvtBasic::ParticleId_t fPrimary;  // Type of emitting particle
+
+    Int_t   fTag;    //! A tag for external use
+    Float_t fWeight; //! A weight for external use
+
+public:
+    MPhotonData(/*const char *name=NULL, const char *title=NULL*/);
+    //MPhotonData(const MPhotonData &ph);
+
+    // Getter 1D
+    Float_t  GetPosX()  const { return fPosX; }
+    Float_t  GetPosY()  const { return fPosY; }
+
+    Float_t  GetCosU()  const { return fCosU; }
+    Float_t  GetCosV()  const { return fCosV; }
+    Double_t GetCosW()  const;
+    Double_t GetSinW()  const;
+    Double_t GetCosW2()  const;
+    Double_t GetSinW2()  const;
+    Double_t GetTheta() const;
+
+    Double_t GetTime()  const { return fTime; }
+
+    // Getter 2D
+    TVector2 GetPos2()  const { return TVector2(fPosX, fPosY); }
+    TVector2 GetDir2()  const { return TVector2(fCosU, fCosV);}
+//    TVector2 GetDir2() const { return TVector2(fCosU, fCosV)/(1-TMath::Hypot(fCosU, fCosV)); }
+
+    // Getter 3D
+    TVector3 GetPos3()  const { return TVector3(fPosX, fPosY, 0); }
+    TVector3 GetDir3()  const { return TVector3(fCosU, fCosV, -GetCosW()); }
+
+    // Getter 4D
+    TQuaternion GetPosQ() const;
+    TQuaternion GetDirQ() const;
+
+    // Getter Others
+    UShort_t GetWavelength() const { return fWavelength; }
+    Float_t GetProductionHeight() const { return fProductionHeight; }
+    MMcEvtBasic::ParticleId_t GetPrimary() const { return fPrimary; }
+
+    //virtual Float_t GetWeight() const { return 1; }
+    virtual Float_t GetWeight() const { return fWeight; }
+    void SetWeight(Float_t w=1) { fWeight=w; }
+
+    // Setter
+    void SetPosition(Float_t x, Float_t y)  { fPosX=x; fPosY=y; }
+    void SetDirection(Float_t u, Float_t v) { fCosU=u; fCosV=v; }
+
+    void SetPosition(const TVector2 &p)     { fPosX=p.X(); fPosY=p.Y(); }
+    void SetDirection(const TVector2 &d)    { fCosU=d.X(); fCosV=d.Y(); }
+
+    void SetPosition(const TQuaternion &p)  { fPosX=p.fVectorPart.X(); fPosY=p.fVectorPart.Y(); fTime=p.fRealPart; }
+    void SetDirection(const TQuaternion &d) { fCosU=d.fVectorPart.X(); fCosV=d.fVectorPart.Y(); }
+
+    void SetPrimary(MMcEvtBasic::ParticleId_t p) { fPrimary=p; }
+    void SetWavelength(UShort_t wl) { fWavelength=wl; }
+
+    void AddTime(Double_t dt) { fTime += dt; }
+    void SetTime(Double_t t)  { fTime  = t; }
+
+    void SimWavelength(Float_t wmin, Float_t wmax);
+
+    void Copy(TObject &obj) const;
+
+    void SetTag(Int_t tag) { fTag=tag; }
+    Int_t GetTag() const { return fTag; }
+
+    // TObject
+    //void Clear(Option_t * = NULL);
+    void Print(Option_t * = NULL) const;
+    //void Draw (Option_t * = NULL);
+    Bool_t IsSortable() const { return kTRUE; }
+    Int_t  Compare(const TObject *obj) const
+    {
+        const MPhotonData &d = *static_cast<const MPhotonData*>(obj);
+        if (fTime<d.fTime)
+            return -1;
+        if (fTime>d.fTime)
+            return 1;
+        return 0;
+    }
+
+    // I/O
+    //Int_t ReadCorsikaEvt(istream &fin);
+    //Int_t ReadRflEvt(istream &fin);
+
+    Int_t FillCorsika(Float_t f[7], Int_t i);
+    Int_t FillEventIO(Float_t f[7]);
+    Int_t FillRfl(Float_t f[8]);
+
+    ClassDef(MPhotonData, 2) //Container to store a cherenkov photon bunch from a CORSUKA file
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msim/MPhotonEvent.cc
===================================================================
--- branches/Mars_McMismatchStudy/msim/MPhotonEvent.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MPhotonEvent.cc	(revision 17960)
@@ -0,0 +1,598 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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): Qi Zhe,       06/2007 <mailto:qizhe@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPhotonEvent
+//
+// Storage container to store photon collections
+//
+// The class is designed to be extremely fast which is important taking into
+// account the extremely high number of photons. This has some impacts on
+// its handling.
+//
+// The list has to be kept consistent, i.e. without holes.
+//
+// There are two ways to achieve this:
+//
+//   a) Use RemoveAt to remove an entry somewhere
+//   b) Compress() the TClonesArray afterwards
+//
+// Compress is not the fastes, so there is an easier way.
+//
+//   a) When you loop over the list and want to remove an entry copy all
+//      following entry backward in the list, so that the hole will
+//      be created at its end.
+//   b) Call Shrink(n) with n the number of valid entries in your list.
+//
+// To loop over the TClonesArray you can use a TIter which has some
+// unnecessary overhead and therefore is slower than necessary.
+//
+// Since the list is kept consistent you can use a simple loop saving
+// a lot of CPU time taking into account the high number of calls to
+// TObjArrayIter::Next which you would create.
+//
+// Here is an example (how to remove every second entry)
+//
+//  ---------------------------------------------------------------------
+//
+//    Int_t cnt = 0;
+//
+//    const Int_t num = event->GetNumPhotons();
+//    for (Int_t idx=0; idx<num; idx++)
+//    {
+//        if (idx%2==0)
+//           continue;
+//
+//        MPhotonData *dat = (*event)[idx];
+//
+//        (*event)[cnt++] = *dat;
+//     }
+//
+//     event->Shrink(cnt);
+//
+//  ---------------------------------- or -------------------------------
+//
+//    TClonesArray &arr = MPhotonEvent->GetArray();
+//
+//    Int_t cnt = 0;
+//
+//    const Int_t num = arr.GetEntriesFast();
+//    for (Int_t idx=0; idx<num; idx++)
+//    {
+//        if (idx%2==0)
+//           continue;
+//
+//        MPhotonData *dat = static_cast<MPhotonData*>(arr.UncheckedAt(idx));
+//
+//        *static_cast<MPhotonData*>(arr.UncheckedAt(cnt++)) = *dat;
+//     }
+//
+//     MPhotonEvent->Shrink(cnt);
+//
+//  ---------------------------------------------------------------------
+//
+// The flag for a sorted array is for speed reasons not in all conditions
+// maintained automatically. Especially Add() doesn't reset it.
+//
+// So be sure that if you want to sort your array it is really sorted.
+//
+//
+//   Version 1:
+//   ----------
+//    - First implementation
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPhotonEvent.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TMarker.h>
+
+#include <MMath.h>
+
+#include "MArrayF.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MPhotonData.h"
+#include "MCorsikaFormat.h"
+
+ClassImp(MPhotonEvent);
+
+using namespace std;
+
+// ==========================================================================
+
+class MyClonesArray : public TClonesArray
+{
+public:
+    TObject **FirstRef() { return fCont; }
+
+    // --------------------------------------------------------------------------
+    //
+    // This is an extremly optimized version of ExpandCreateFast. It only resets
+    // the marker for the last element (fLast) to n-1 and doen't change anything
+    // else. This implicitly assumes that the stored objects don't allocate
+    // memory. It does not necessarily mean that the slots after fLast
+    // are empty (set to 0). This is what is assumed in the TClonesArray.
+    // We also don't call Changed() because it would reset Sorted. If the
+    // array was sorted before it is also sorted now. You MUST make sure
+    // that you only set n in a range for which valid entries have been
+    // created before (e.g. by ExpandCreateFast).
+    //
+    void FastShrink(Int_t n)
+    {
+        fLast = n - 1;
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    // This is a optimized (faster) version of Delete which deletes consequtive
+    // entries from index idx1 to idx2 (both included) and calls their
+    // destructor. Note that there is no range checking done!
+    //
+    void FastRemove(Int_t idx1, Int_t idx2)
+    {
+        // Remove object at index idx.
+
+        //if (!BoundsOk("RemoveAt", idx1)) return 0;
+        //if (!BoundsOk("RemoveAt", idx2)) return 0;
+
+        Long_t dtoronly = TObject::GetDtorOnly();
+
+        idx1 -= fLowerBound;
+        idx2 -= fLowerBound;
+
+        for (TObject **obj=fCont+idx1; obj<=fCont+idx2; obj++)
+        {
+            if (!*obj)
+                continue;
+
+            if ((*obj)->TestBit(kNotDeleted)) {
+                // Tell custom operator delete() not to delete space when
+                // object fCont[i] is deleted. Only destructors are called
+                // for this object.
+                TObject::SetDtorOnly(*obj);
+                delete *obj;
+            }
+
+            *obj = 0;
+            // recalculate array size
+        }
+        TObject::SetDtorOnly((void*)dtoronly);
+
+        if (idx1<=fLast && fLast<=idx2)
+        {
+            do {
+                fLast--;
+            } while (fLast >= 0 && fCont[fLast] == 0);
+        }
+
+        Changed();
+    }
+
+
+    //void SetSorted() { fSorted = kTRUE; }
+
+    // --------------------------------------------------------------------------
+    //
+    // This is an optimized version of Sort which doesn't check the
+    // IsSortable flag before. It only sorts the entries from 0
+    // to GetEntriesFast().
+    //
+    void UncheckedSort()
+    {
+        if (fSorted)
+            return;
+
+        const Int_t nentries = GetEntriesFast();
+        if (nentries <= 0)
+            return;
+
+        QSort(GetObjectRef(First()), fKeep->GetObjectRef(fKeep->First()),
+              0, TMath::Min(nentries, kMaxInt-fLowerBound));
+
+        fSorted = kTRUE;
+    }
+};
+
+// ==========================================================================
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It initializes all arrays with zero size.
+//
+MPhotonEvent::MPhotonEvent(const char *name, const char *title)
+    : fData("MPhotonData", 1)
+{
+    fName  = name  ? name  : "MPhotonEvent";
+    fTitle = title ? title : "Corsika Event Data Information";
+
+    fData.SetBit(TClonesArray::kForgetBits);
+    fData.BypassStreamer(kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+// This is an extremly optimized version of ExpandCreateFast. It only resets
+// the marker for the last element (fLast) to n-1 and doen't change anything
+// else. This has the advantage that the allocated memory is kept but only
+// valid entries are written to a file.
+//
+// If the array was sorted before it is also sorted now. You MUST make sure
+// that you only set n in a range for which valid entries have been
+// created before (e.g. by ExpandCreateFast).
+//
+Int_t MPhotonEvent::Shrink(Int_t n)
+{
+    /*
+    // The number of object written by the streamer is defined by
+    // GetEntriesFast(), i.e. this number must be shrinked to
+    // the real array size. We use RemoveAt instead of ExpandCreate
+    // because RemoveAt doesn't free memory. Thus in the next
+    // iteration it can be reused and doesn't need to be reallocated.
+    // Do not change this. It is optimized for execution speed
+    //        for (int i=fData.GetSize()-1; i>=n; i--)
+    //          fData.RemoveAt(i);
+    const Bool_t sorted = fData.IsSorted();
+
+    MyClonesArray &loc = static_cast<MyClonesArray&>(fData);
+
+    loc.FastRemove(n, fData.GetSize()-1);
+
+    // If it was sorted before it is also sorted now.
+    if (sorted)
+        loc.SetSorted();
+    */
+
+    // fData.ExpandCreateFast(n);  // Just set fLast = n -1
+
+    // Just set fLast = n -1
+    static_cast<MyClonesArray&>(fData).FastShrink(n);
+    return fData.GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// The resized the array. If it has to be increased in size it is done
+// with ExpandCreateFast. If it should be shrinked it is done with
+// ExpandCreateFast if n>fData.GetSize()/100 or n==0. This keeps the allocated
+// memory and just sets the marker for the last element in the array (fLast).
+//
+// If the allocated memory grew to huge we reset the allocated memory
+// by calling ExpandCreate(n) (frees the allocated storage for the
+// objects) and Expand(n) (frees the allocated memory for the list
+// of pointers to the objects)
+//
+// 100 hundred is an arbitrary number taking into account that todays
+// computers have a lot of memory and we don't want to free and allocate
+// new memory too often.
+//
+// In priciple there might be more clever methods to handle the memory.
+//
+void MPhotonEvent::Resize(Int_t n)
+{
+    if (n==0 || n*100>fData.GetSize())
+        fData.ExpandCreateFast(n);  // Just set fLast = n -1
+    else
+    {
+        fData.ExpandCreate(n);      // Free memory of allocated MPhotonData
+        fData.Expand(n);            // Free memory of allocated pointers
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// If n is smaller than the current allocated array size a reference to
+// the n-th entry is returned, otherwise an entry at n is created
+// calling the default constructor. Note, that there is no range check
+// but it is not recommended to call this function with
+// n>fData.GetSize()
+//
+MPhotonData &MPhotonEvent::Add(Int_t n)
+{
+    // Do not modify this. It is optimized for execution
+    // speed and flexibility!
+    TObject *o = 0;
+    if (n<fData.GetSize() && fData.UncheckedAt(n))
+    {
+        o=fData.UncheckedAt(n);
+        static_cast<MyClonesArray&>(fData).FastShrink(n+1);
+    }
+    else
+    {
+        o=fData.New(n);
+    }
+    return static_cast<MPhotonData&>(*o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new photon (MPhtonData) at the end of the array.
+// In this case the default constructor of MPhotonData is called.
+//
+// A reference to the new object is returned.
+//
+MPhotonData &MPhotonEvent::Add()
+{
+    return Add(GetNumPhotons());
+}
+
+void MPhotonEvent::Sort(Bool_t force)
+{
+    if (force)
+        fData.UnSort();
+
+    static_cast<MyClonesArray&>(fData).UncheckedSort(); /*Sort(GetEntriesFast())*/
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the i-th photon from the array. Not, for speed reasons there is no
+// range check so you are responsible that you do not excess the number
+// of photons (GetNumPhotons)
+//
+MPhotonData &MPhotonEvent::operator[](UInt_t idx)
+{
+    return *static_cast<MPhotonData*>(fData.UncheckedAt(idx));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the i-th photon from the array. Not, for speed reasons there is no
+// range check so you are responsible that you do not excess the number
+// of photons (GetNumPhotons)
+//
+const MPhotonData &MPhotonEvent::operator[](UInt_t idx) const
+{
+    return *static_cast<MPhotonData*>(fData.UncheckedAt(idx));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the first photon if available.
+//
+MPhotonData *MPhotonEvent::GetFirst() const
+{
+    return fData.GetEntriesFast()==0 ? 0 : static_cast<MPhotonData*>(fData.First());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the last photon if available.
+//
+MPhotonData *MPhotonEvent::GetLast() const
+{
+    return fData.GetEntriesFast()==0 ? 0 : static_cast<MPhotonData*>(fData.Last());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of "external" photons, i.e. which are not NightSky
+//
+Int_t MPhotonEvent::GetNumExternal() const
+{
+    const Int_t n=GetNumPhotons();
+
+    Int_t rc = 0;
+    for (int i=0; i<n; i++)
+        if ((*this)[i].GetPrimary()!=MMcEvtBasic::kNightSky && (*this)[i].GetPrimary()!=MMcEvtBasic::kArtificial)
+            rc++;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return time of first photon, 0 if none in array.
+// Note: If you want this to be the earliest make sure that the array
+// is properly sorted.
+//
+Float_t MPhotonEvent::GetTimeFirst() const
+{
+    const MPhotonData *dat=GetFirst();
+    return dat ? dat->GetTime() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return time of first photon, 0 if none in array.
+// Note: If you want this to be the latest make sure that the array
+// is properly sorted.
+//
+Float_t MPhotonEvent::GetTimeLast() const
+{
+    const MPhotonData *dat=GetLast();
+    return dat ? dat->GetTime() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the median devian from the median of all arrival times.
+// The median deviation is calculated using MMath::MedianDev.
+// It is the half width in which one sigma (~68%) of all times are
+// contained around the median.
+//
+Double_t MPhotonEvent::GetTimeMedianDev() const
+{
+    const UInt_t n = GetNumPhotons();
+
+    MArrayF arr(n);
+    for (UInt_t i=0; i<n; i++)
+        arr[i] = operator[](i).GetTime();
+
+    return MMath::MedianDev(n, arr.GetArray()/*, Double_t &med*/);
+}
+
+Double_t MPhotonEvent::GetMeanX() const
+{
+    const UInt_t n = GetNumPhotons();
+    if (n==0)
+        return 0;
+
+    Double_t mean = 0;
+    for (UInt_t i=0; i<n; i++)
+        mean += operator[](i).GetPosX();
+
+    return mean / n;
+}
+
+Double_t MPhotonEvent::GetMeanY() const
+{
+    const UInt_t n = GetNumPhotons();
+    if (n==0)
+        return 0;
+
+    Double_t mean = 0;
+    for (UInt_t i=0; i<n; i++)
+        mean += operator[](i).GetPosY();
+
+    return mean / n;
+}
+
+Double_t MPhotonEvent::GetMeanT() const
+{
+    const UInt_t n = GetNumPhotons();
+    if (n==0)
+        return 0;
+
+    Double_t mean = 0;
+    for (UInt_t i=0; i<n; i++)
+        mean += operator[](i).GetTime();
+
+    return mean / n;
+}
+
+void MPhotonEvent::AddXY(Double_t x, Double_t y)
+{
+    const UInt_t n = GetNumPhotons();
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        MPhotonData &p = operator[](i);
+        p.SetPosition(p.GetPosX()+x, p.GetPosY()+y);
+    }
+}
+
+void MPhotonEvent::SimWavelength(Float_t wmin, Float_t wmax)
+{
+    const UInt_t n = GetNumPhotons();
+
+    for (UInt_t i=0; i<n; i++)
+        operator[](i).SimWavelength(wmin, wmax);
+}
+Int_t MPhotonEvent::ReadEventIoEvt(MCorsikaFormat *fInFormat)
+{
+   Int_t  bunchHeader[3];
+   fInFormat->Read(bunchHeader, 3 * sizeof(Int_t));
+
+   Int_t n = 0;
+
+   for (int bunch = 0; bunch < bunchHeader[2]; bunch++)
+      {
+      Float_t buffer[8];
+      fInFormat->Read(buffer, 8 * sizeof(Float_t));
+
+      if (Add(n).FillEventIO(buffer))
+         n++;
+      }
+
+   Resize(n);
+   fData.UnSort();
+
+   SetReadyToSave();
+
+   //*fLog << all << "Number of photon bunches: " << fData.GetEntriesFast() << endl;
+   return kTRUE;
+
+}
+
+Int_t MPhotonEvent::ReadCorsikaEvt(Float_t * data, Int_t numEvents, Int_t arrayIdx)
+{
+   Int_t n = 0;
+
+   for (Int_t event = 0; event < numEvents; event++)
+      {
+      const Int_t rc = Add(n).FillCorsika(data + 7 * event, arrayIdx);
+
+      switch (rc)
+      {
+      case kCONTINUE:  continue;        // No data in this bunch... skip it.
+      case kERROR:     return kERROR;   // Error occured
+      }
+
+      // This is a photon we would like to keep later.
+      // Increase the counter by one
+      n++;
+      }
+
+   Resize(n);
+   fData.UnSort();
+
+   SetReadyToSave();
+
+   //*fLog << all << "Number of photon bunches: " << fData.GetEntriesFast() << endl;
+   return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the array
+//
+void MPhotonEvent::Print(Option_t *) const
+{
+    // This is much faster than looping over all entries and discarding
+    // the empty ones
+    const UInt_t n = GetNumPhotons();
+    for (UInt_t i=0; i<n; i++)
+        operator[](i).Print();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 MPhotonEvent::Paint(Option_t *)
+{
+    MPhotonData *ph=NULL;
+
+    TMarker m;
+    m.SetMarkerStyle(kFullDotMedium); // Gtypes.h
+
+    TIter Next(&fData);
+    while ((ph=(MPhotonData*)Next()))
+    {
+        m.SetX(ph->GetPosY()*10);  // north
+        m.SetY(ph->GetPosX()*10);  // east
+        m.Paint();
+    }
+}
Index: branches/Mars_McMismatchStudy/msim/MPhotonEvent.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/MPhotonEvent.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MPhotonEvent.h	(revision 17960)
@@ -0,0 +1,115 @@
+#ifndef MARS_MPhotonEvent
+#define MARS_MPhotonEvent
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+#include <iosfwd>
+
+using namespace std;
+
+class MPhotonData;
+class MCorsikaRunHeader;
+class MCorsikaFormat;
+
+class MPhotonEvent : public MParContainer
+{
+private:
+    TClonesArray fData;
+
+public:
+    MPhotonEvent(const char *name=NULL, const char *title=NULL);
+
+    void Sort(Bool_t force=kFALSE);
+    Bool_t IsSorted() const { return fData.IsSorted(); }
+
+    // Getter/Setter
+    Int_t GetNumPhotons() const { return fData.GetEntriesFast(); }
+    Int_t GetNumExternal() const;
+
+    Float_t  GetTimeFirst() const;
+    Float_t  GetTimeLast() const;
+    Double_t GetTimeMedianDev() const;
+
+    Double_t GetMeanX() const;
+    Double_t GetMeanY() const;
+    Double_t GetMeanT() const;
+
+    TClonesArray &GetArray() { return fData; }
+    const TClonesArray &GetArray() const { return fData; }
+
+    MPhotonData &Add(Int_t n);
+    MPhotonData &Add();
+
+    MPhotonData *GetFirst() const;
+    MPhotonData *GetLast() const;
+
+    MPhotonData &operator[](UInt_t idx);
+    const MPhotonData &operator[](UInt_t idx) const;
+
+    Int_t Shrink(Int_t n);
+    void Resize(Int_t n);
+
+    void AddXY(Double_t x, Double_t y);
+    void SimWavelength(Float_t wmin, Float_t wmax);
+
+    // I/O
+    Int_t ReadEventIoEvt(MCorsikaFormat *fInFormat);
+    Int_t ReadCorsikaEvt(Float_t * data, Int_t numEvents, Int_t arrayIdx);
+
+    // TObject
+    void Paint(Option_t *o="");
+    void Print(Option_t * = NULL) const;
+    //void Clear(Option_t * = NULL);
+
+    ClassDef(MPhotonEvent, 1) //Container to store the raw Event Data
+};
+
+// FIXME: Should we merge this into MPhotonEvent?
+class MPhotonStatistics : public MParContainer
+{
+private:
+    Float_t fTimeFirst;  //! Start of (simulated) sampling window
+    Float_t fTimeLast;   //! Start of (simulated) sampling window
+
+    Float_t fLength;     // Time between first and last photon
+    Float_t fTimeMedDev; // Median deviation
+
+//    Float_t fOffset;
+//    Float_t fWindow;
+
+    Int_t fMaxIndex;     //!
+
+public:
+    MPhotonStatistics(const char *name=NULL, const char *title=NULL) : fMaxIndex(-1)
+    {
+        fName  = name  ? name  : "MPhotonStatistics";
+        fTitle = title ? title : "Corsika Event Data Information";
+    }
+
+    void SetTime(Float_t first, Float_t last) { fTimeFirst=first; fTimeLast=last; }
+    void SetLength(Float_t len) { fLength=len; }
+    void SetMaxIndex(UInt_t idx) { fMaxIndex=idx; }
+    void SetTimeMedDev(Float_t dev) { fTimeMedDev=dev; }
+
+//    Float_t GetRawTimeFirst() const { return fTimeFirst; }
+//    Float_t GetRawTimeLast() const { return fTimeLast; }
+
+    Float_t GetTimeFirst() const { return fTimeFirst; }
+    Float_t GetTimeLast() const { return fTimeLast; }
+
+    Float_t GetLength() const { return fLength; }
+    Float_t GetTimeMedDev() const { return fTimeMedDev; }
+
+    Int_t GetMaxIndex() const { return fMaxIndex; }
+
+//    Bool_t IsValid() const { return fTimeLast>=fTimeFirst; }
+
+    ClassDef(MPhotonStatistics, 1)
+};
+#endif
Index: branches/Mars_McMismatchStudy/msim/MSimAbsorption.cc
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimAbsorption.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimAbsorption.cc	(revision 17960)
@@ -0,0 +1,197 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimAbsorption
+//
+//  Task to calculate wavelength or incident angle dependent absorption
+//
+//  Input Containers:
+//   fParName [MParSpline]
+//   MPhotonEvent
+//   MCorsikaEvtHeader
+//   MCorsikaRunHeader
+//
+//  Output Containers:
+//   MPhotonEvent
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimAbsorption.h"
+
+#include <fstream>
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MParSpline.h"
+
+#include "MCorsikaEvtHeader.h"
+#include "MCorsikaRunHeader.h"
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+ClassImp(MSimAbsorption);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimAbsorption::MSimAbsorption(const char* name, const char *title)
+    : fEvt(0), fHeader(0), fSpline(0), fParName("MParSpline"), fUseTheta(kFALSE)
+{
+    fName  = name  ? name  : "MSimAbsorption";
+    fTitle = title ? title : "Task to calculate wavelength dependent absorption";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the needed parameter containers. Read spline from file
+// calling ReadFile();
+//
+Int_t MSimAbsorption::PreProcess(MParList *pList)
+{
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSpline = (MParSpline*)pList->FindObject(fParName, "MParSpline");
+    if (!fSpline)
+    {
+        *fLog << err << fParName << " [MParSpline] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fSpline->IsValid())
+    {
+        *fLog << err << "Spline in " << fParName << " is inavlid... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHeader = (MCorsikaEvtHeader*)pList->FindObject("MCorsikaEvtHeader");
+    if (!fHeader)
+    {
+        *fLog << err << "MCorsikaEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Using " << (fUseTheta?"Theta":"Wavelength") << " for absorption." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MSimAbsorption::ReInit(MParList *pList)
+{
+    if (fUseTheta)
+        return kTRUE;
+
+    MCorsikaRunHeader *h = (MCorsikaRunHeader*)pList->FindObject("MCorsikaRunHeader");
+    if (!h)
+    {
+        *fLog << err << "MCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (h->GetWavelengthMin()<fSpline->GetXmin())
+        *fLog << warn << "WARNING - Lower bound of wavelength bandwidth exceeds lower bound of spline." << endl;
+
+    if (h->GetWavelengthMax()>fSpline->GetXmax())
+        *fLog << warn << "WARNING - Upper bound of wavelength bandwidth exceeds upper bound of spline." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Throw all events out of the MPhotonEvent which don't survive.
+// Depending on fUseTheta either the wavelength or the incident angle
+// is used.
+//
+Int_t MSimAbsorption::Process()
+{
+    // Get the number of photons in the list
+    const Int_t num = fEvt->GetNumPhotons();
+
+    // Counter for number of total and final events
+    Int_t cnt = 0;
+    for (Int_t i=0; i<num; i++)
+    {
+        // Get i-th photon from the list
+        const MPhotonData &ph = (*fEvt)[i];
+
+        // Depending on fUseTheta get the incident angle of the wavelength
+        const Double_t wl = fUseTheta ? ph.GetTheta()*TMath::RadToDeg() : ph.GetWavelength();
+
+        // Get the efficiency (the probability that this photon will survive)
+        // from the spline.
+        const Double_t eff = fSpline->Eval(wl);
+
+        // Get a random value between 0 and 1 to determine whether the photn will survive
+        // gRandom->Rndm() = [0;1[
+        if (gRandom->Rndm()>=eff)
+            continue;
+
+        // Copy the surviving events bakc in the list
+        (*fEvt)[cnt++] = ph;
+    }
+
+    // Now we shrink the array to the number of new entries.
+    fEvt->Shrink(cnt);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FileName: reflectivity.txt
+// UseTheta: No
+//
+Int_t MSimAbsorption::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "ParName", print))
+    {
+        rc = kTRUE;
+        SetParName(GetEnvValue(env, prefix, "ParName", fParName));
+    }
+
+    if (IsEnvDefined(env, prefix, "UseTheta", print))
+    {
+        rc = kTRUE;
+        SetUseTheta(GetEnvValue(env, prefix, "UseTheta", fUseTheta));
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msim/MSimAbsorption.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimAbsorption.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimAbsorption.h	(revision 17960)
@@ -0,0 +1,43 @@
+#ifndef MARS_MSimAbsorption
+#define MARS_MSimAbsorption
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MParSpline;
+class MPhotonEvent;
+class MCorsikaEvtHeader;
+
+class MSimAbsorption : public MTask
+{
+private:
+    MPhotonEvent      *fEvt;     //! Event stroing the photons
+    MCorsikaEvtHeader *fHeader;  //! Header storing event information
+
+    MParSpline        *fSpline;  //! Spline to interpolate wavelength or incident angle
+
+    TString fParName;            // Container name of the spline containing the curve
+    Bool_t  fUseTheta;           // Switches between using wavelength or incident angle
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSimAbsorption(const char *name=NULL, const char *title=NULL);
+
+    // MSimAbsorption
+    void SetParName(const char *name) { fParName=name; }
+
+    void SetUseTheta(Bool_t b=kTRUE) { fUseTheta = b; }
+
+    ClassDef(MSimAbsorption, 0) // Task to calculate wavelength or incident angle dependent absorption
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msim/MSimAtmosphere.cc
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimAtmosphere.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimAtmosphere.cc	(revision 17960)
@@ -0,0 +1,875 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimAtmosphere
+//
+//  Task to calculate wavelength or incident angle dependent absorption
+//
+//  Input Containers:
+//   MPhotonEvent
+//   MCorsikaRunHeader
+//
+//  Output Containers:
+//   MPhotonEvent
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimAtmosphere.h"
+
+#include <fstream>
+
+#include <TGraph.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCorsikaRunHeader.h"
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+ClassImp(MSimAtmosphere);
+
+using namespace std;
+
+// ==========================================================================
+//
+// January 2002, A. Moralejo: We now precalculate the slant paths for the
+// aerosol and Ozone vertical profiles, and then do an interpolation in
+// wavelength for every photon to get the optical depths. The parameters
+// used, defined below, have been taken from "Atmospheric Optics", by
+// L. Elterman and R.B. Toolin, chapter 7 of the "Handbook of geophysics
+// and Space environments". (S.L. Valley, editor). McGraw-Hill, NY 1965.
+// 
+// WARNING: the Mie scattering and the Ozone absorption are implemented
+// to work only with photons produced at a height a.s.l larger than the
+// observation level. So this is not expected to work well for simulating
+// the telescope pointing at theta > 90 deg (for instance for neutrino
+// studies. Rayleigh scattering works even for light coming from below.
+// 
+// Fixed bugs (of small influence) in Mie absorption implementation: there
+// were errors in the optical depths table, as well as a confusion:
+// height a.s.l. was used as if it was height above the telescope level.
+// The latter error was also present in the Ozone aborption implementation.
+// 
+// On the other hand, now we have the tables AE_ABI and OZ_ABI with optical
+// depths between sea level and a height h (before it was between 2km a.s.l
+// and a height h). So that we can simulate also in the future a different
+// observation level.
+// 
+// AM: WARNING: IF VERY LARGE zenith angle simulations are to be done (say
+// above 85 degrees, for neutrino primaries or any other purpose) this code
+// will have to be adapted accordingly and checked, since in principle it has
+// been written and tested to simulate the absorption of Cherenkov photons
+// arriving at the telescope from above.
+// 
+// AM: WARNING 2: not to be used for wavelengths outside the range 250-700 nm
+// 
+// January 2003, Abelardo Moralejo: found error in Ozone absorption treatment.
+// At large zenith angles, the air mass used was the one calculated for
+// Rayleigh scattering, but since the Ozone distribution is rather different
+// from the global distribution of air molecules, this is not a good
+// approximation. Now I have left in this code only the Rayleigh scattering,
+// and moved to atm.c the Mie scattering and Ozone absorption calculated in
+// a better way.
+// 
+// A. Moralejo, January 2003: added some parameters for Mie scattering
+// and Ozone absorption derived from the clear standard atmosphere model
+// in "Atmospheric Optics", by L. Elterman and R.B. Toolin, chapter 7 of
+// the "Handbook of geophysics and Space environments". S.L. Valley,
+// editor. McGraw-Hill, NY 1965.
+// 
+// AM, Jan 2003: Changed the meaning of the argument height: now it is the
+// true height above sea level at which a photon has been emitted, before
+// it was the height given by Corsika, measured in the vertical of the
+// observer and not in the vertical of the emitting particle.
+//
+//
+// MAGIC-Winter and MAGIC-Summer by M. Haffke,
+// parametrizing profiles obtained with MSIS:
+// http://uap-www.nrl.navy.mil/models_web/msis/msis_home.htm
+//
+//
+// The MAGIC-Winter and MAGIC-Summer parametrisations reproduce the MSIS
+// profiles for the 3 atmospheric layers from 0 up to 40 km height. Beyond
+// that height, it was not possible to achieve a good fit, but the amount
+// of residual atmosphere is so small that light absorption would be
+// negligible anyway. Showers develop well below 40 km.
+//
+//
+// The mass overburden is given by T = AATM + BATM * exp(-h/CATM)
+// The last layer of the US standard atmosphere (in which T varies
+// linearly with h) is above 100 km and has not been included here
+// because it should not matter.
+//
+class MAtmRayleigh
+{
+private:
+    static const Double_t fgMeanFreePath; // [g/cm^2] Mean free path for scattering Rayleigh XR
+
+    Double_t fR;         // [cm] Earth radius to be used
+
+    Double_t fHeight[5]; // Layer boundaries (atmospheric layer)
+
+    // Parameters of the different atmospheres. We use the same parametrization
+    // shape as in Corsika atmospheric models (see Corsika manual, appendix D).
+    // The values here can be/are obtained from the Corsika output
+    //Float_t  fAtmA[4];   // The index refers to the atmospheric layer (starting from sea level and going upwards)
+    Float_t  fAtmB[4];   // The index refers to the atmospheric layer (starting from sea level and going upwards)
+    Float_t  fAtmC[4];   // The index refers to the atmospheric layer (starting from sea level and going upwards)
+
+    Double_t fRho[5];    // Precalculated integrals for rayleigh scatterning
+
+    // --------------------------------------------------------------------------
+    //
+    // Precalcalculate the integrals from the observer level to the next
+    // atmpsheric layer below including the lower boundary. Thus a
+    // correct calculation is reduced to the calculation of the upper
+    // boundary.
+    //
+    // fRho[0] = B0;
+    // fRho[1] = B0-A0 + B1;
+    // fRho[2] = B0-A0 + B1-A1 + B2;
+    // fRho[3] = B0-A0 + B1-A1 + B2+A2 + B3;
+    // fRho[4] = B0-A0 + B1-A1 + B2+A2 + B3 - A3;
+    //
+    void PreCalcRho()
+    {
+        // Limits (height in cm) of the four layers in which
+        // atmosphere is parametrized.
+        // This is a stupid trick giving 0 for the integrals below
+        // the observer
+
+        // FIXME: Could be replaced by 0, AtmLay[0]-fAtmLay[3]
+
+        const Double_t h[5] =
+        {
+            fObsLevel,                     // fObsLevel,                   //   0km
+            TMath::Max(fObsLevel, 7.75e5), // TMath::Max(fObsLevel, 4e5),  //   4km
+             16.5e5,                       //  10e5,                       //  10km
+             50.0e5,                       //  40e5,                       //  40km
+            105.0e5,                       // 100e5                        // 100km
+        };
+
+        memcpy(fHeight, h, sizeof(Double_t)*5);
+
+        fRho[0] = 0;
+        for (int i=0; i<4; i++)
+        {
+            const Double_t b = fAtmB[i];
+            const Double_t c = fAtmC[i];
+
+            const Double_t h1 = h[i+1];
+            const Double_t h0 = h[i];
+
+            const Double_t B = b*TMath::Exp(-h0/c);
+            const Double_t A = b*TMath::Exp(-h1/c);
+
+            // Calculate rho for the i-th layer from the lower
+            // to the higher layer boundary.
+            // If height is within the layer only calculate up to height.
+            fRho[i]  += B;
+            fRho[i+1] = fRho[i] - A;
+        }
+    }
+
+protected:
+    Double_t fObsLevel; // [cm] observation level a.s.l.
+
+public:
+    // Init an atmosphere from the data stored in MCorsikaRunHeader
+    MAtmRayleigh(const MCorsikaRunHeader &h)
+    {
+        Init(h);
+    }
+
+    // Defualt constructor
+    MAtmRayleigh() : fObsLevel(-1) { }
+
+    // Check if the ovservation level has been correctly initialized
+    // Used as a marker for correct initialization
+    Bool_t IsValid() const { return fObsLevel>=0; }
+
+    // Get the Earth radius to be used
+    Double_t R() const { return fR; }
+
+    // Init an atmosphere from the data stored in MCorsikaRunHeader
+    // This initialized fObsLevel, fR, fAtmB and fAtmC and
+    // PreCalcRho
+    void Init(const MCorsikaRunHeader &h)
+    {
+        // Observation level above earth radius
+        fObsLevel = h.GetObsLevel();
+
+        // Use earth radius as defined in Corsika
+        fR = h.EarthRadius();
+
+        //memcpy(fAtmA, (Float_t*)h.GetAtmosphericCoeffA(), sizeof(Float_t)*4);
+        memcpy(fAtmB, (Float_t*)h.GetAtmosphericCoeffB(), sizeof(Float_t)*4);
+        memcpy(fAtmC, (Float_t*)h.GetAtmosphericCoeffC(), sizeof(Float_t)*4);
+
+        PreCalcRho();
+    }
+
+    // Return the vertical thickness between the observer and height.
+    // Therefor the integral of the layers below (including the lower
+    // boudary) Have been precalculated by PreCalcRho
+    Double_t GetVerticalThickness(Double_t height) const
+    {
+        // FIXME: We could store the start point above obs-level
+        //        (Does this really gain anything?)
+        Int_t i=0;
+        while (i<4 && height>fHeight[i+1])
+            i++;
+
+        const Double_t b = fAtmB[i];
+        const Double_t c = fAtmC[i];
+
+        return fRho[i] - b*TMath::Exp(-height/c);
+    }
+
+    /*
+     // The "orginal" code for the vertical thickness
+    Double_t GetVerticalThickness(Double_t obslev, Double_t height) const
+    {
+        // This is a C++-version of the original code from attenu.c
+
+        // Limits (height in cm) of the four layers in which atmosphere is parametrized:
+        const double lahg[5] =
+        {
+            obslev,
+            TMath::Max(obslev, 4e5),
+            1.0e6,
+            4.0e6,
+            1.0e7
+        };
+
+        Double_t Rho_Tot = 0.0;
+        for (int i=0; i<4; i++)
+        {
+            const Double_t b = fAtmB[i];
+            const Double_t c = fAtmC[i];
+
+            const Double_t h0 = TMath::Min(height, lahg[i+1]);
+            const Double_t h1 =                    lahg[i];
+
+            // Calculate rho for the i-th layer from the lower
+            // to the higher layer boundary.
+            // If height is within the layer only calculate up to height.
+            Rho_Tot += b*(exp(-h1/c) - exp(-h0/c));
+
+            if (lahg[i+1] > height)
+                break;
+        }
+
+        return Rho_Tot;
+    }
+    */
+    Double_t CalcTransmission(Double_t height, Double_t wavelength, Double_t sin2) const
+    {
+        // sin2: sin(theta)^2
+        // height is the true height a.s.l.
+
+        // LARGE ZENITH ANGLE FACTOR (AIR MASS FACTOR):
+        // Air mass factor "airmass" calculated using a one-exponential
+        // density profile for the atmosphere,
+        //
+        //     rho = rho_0 exp(-height/hscale) with hscale = 7.4 km
+        //
+        // The air mass factor is defined as I(theta)/I(0), the ratio of
+        // the optical paths I (in g/cm2) traversed between two given
+        // heights, at theta and at 0 deg z.a.
+
+        const Double_t H = height-fObsLevel;
+        const Double_t h = 2*H;
+
+        // Scale-height (cm) for Exponential density profile
+        const Double_t hscale = 7.4e5;
+        const Double_t f      = 2*hscale;
+
+        // Precalc R*cos(theta)^2 (FIXME: Is ph.GetCosW2 more precise?)
+        const Double_t Rcos2 = fR * (1-sin2); // cos2 = 1 - sin2
+
+        const Double_t x1 = TMath::Sqrt((Rcos2      ) / f);
+        const Double_t x2 = TMath::Sqrt((Rcos2 + 2*h) / f);
+        const Double_t x3 = TMath::Sqrt((fR         ) / f);
+        const Double_t x4 = TMath::Sqrt((fR    + 2*h) / f);
+
+        // Return a -1 transmittance in the case the photon comes
+        // exactly from the observation level, because in that case the
+        // "air mass factor" would become infinity and the calculation
+        // is not valid!
+        if (fabs(x3-x4) < 1.e-10)
+            return  -1.;
+
+        const Double_t e12 = erfc(x1) - erfc(x2);
+        const Double_t e34 = erfc(x3) - erfc(x4);
+
+        const Double_t airmass = TMath::Exp(-fR*sin2 / f) * e12/e34;
+
+        // Calculate the traversed "vertical thickness" of air using the
+        // US Standard atmosphere:
+        const Double_t Rho_tot = GetVerticalThickness(/*fObsLevel,*/ height);
+
+        // We now convert from "vertical thickness" to "slanted thickness"
+        // traversed by the photon on its way to the telescope, simply
+        // multiplying by the air mass factor m:
+        const Double_t Rho_Fi = airmass * Rho_tot;
+
+        // Finally we calculate the transmission coefficient for the Rayleigh
+        // scattering:
+        // AM Dec 2002, introduced ABS below to account (in the future) for
+        // possible photons coming from below the observation level.
+
+        const Double_t wl = 400./wavelength;
+
+        // Mean free path for scattering Rayleigh XR (g/cm^2)
+        return TMath::Exp(-TMath::Abs(Rho_Fi/fgMeanFreePath)*wl*wl*wl*wl);
+    }
+};
+
+// ==========================================================================
+
+class MAtmosphere : public MAtmRayleigh
+{
+private:
+    static const Double_t STEPTHETA; // aprox. 1 degree
+
+    // Aerosol number density for 31 heights a.s.l., from 0 to 30 km,
+    // in 1 km steps (units: cm^-3)
+    static const Double_t aero_n[31];
+
+    // Ozone concentration for 51 heights a.s.l., from 0 to 50 km,
+    // in 1 km steps (units: cm/km)
+    static const Double_t oz_conc[51];
+
+    // aerosol_path contains the path integrals for the aerosol number
+    // density (relative to the number density at sea level) between the
+    // observation level and a height h for different zenith angles. The
+    // first index indicate height above sea level in units of 100m, the
+    // second is the zenith angle in degrees.
+    float aerosol_path[301][90];
+
+    // ozone_path contains the path integrals for the ozone concentration
+    // between the observation level and a height h for different zenith
+    // angles. The first index indicate height above sea level in units
+    // of 100m, the second is the zenith angle in degrees.
+    float ozone_path[501][90];
+
+    // Interpolate the graph at wavelength
+    Double_t GetBeta(Double_t wavelength, const TGraph &g) const
+    {
+        // FIXME: This might not be the fastest because range
+        // checks are done for each call!
+        return g.GetN()==0 ? 0 : g.Eval(wavelength)*1e-5; // from km^-1 to cm^-1
+/*
+        // Linear interpolation
+        // (FIXME: Is it faster to be replaced with a binary search?)
+        // (       This might be faster because we have more photons
+        //         with smaller wavelengths)
+        //int index;
+        //for (index = 1; index <g.GetN()-1; index++)
+        //    if (wavelength < g.GetX()[index])
+        //        break;
+        const Int_t index = TMath::BinarySearch(g.GetN(), g.GetX(), wavelength)+1;
+
+        const Double_t t0 = g.GetY()[index-1];
+        const Double_t t1 = g.GetY()[index];
+
+        const Double_t w0 = g.GetX()[index-1];
+        const Double_t w1 = g.GetX()[index];
+
+        const Double_t beta0 = t0+(t1-t0)*(wavelength-w0)/(w1-w0);
+
+        return beta0 * 1e-5; // from km^-1 to cm^-1
+        */
+    }
+
+
+    //MSpline3 *fAbsCoeffOzone;
+    //MSpline3 *fAbsCoeffAerosols;
+
+    TGraph *fAbsCoeffOzone;
+    TGraph *fAbsCoeffAerosols;
+
+public:
+    MAtmosphere(const MCorsikaRunHeader &h) : fAbsCoeffOzone(0), fAbsCoeffAerosols(0)
+    {
+        Init(h);//, "ozone.txt", "aerosols.txt");
+    }
+
+    MAtmosphere(const char *name1=0, const char *name2=0) : fAbsCoeffOzone(0), fAbsCoeffAerosols(0)
+    {
+        if (name1)
+            InitOzone(name1);
+        if (name2)
+            InitAerosols(name2);
+    }
+
+    ~MAtmosphere()
+    {
+        if (fAbsCoeffOzone)
+            delete fAbsCoeffOzone;
+        if (fAbsCoeffAerosols)
+            delete fAbsCoeffAerosols;
+    }
+
+    Float_t GetWavelengthMin() const { return fAbsCoeffOzone && fAbsCoeffAerosols ? TMath::Max(fAbsCoeffOzone->GetX()[0], fAbsCoeffAerosols->GetX()[0]) : -1; }
+    Float_t GetWavelengthMax() const { return fAbsCoeffOzone && fAbsCoeffAerosols ? TMath::Min(fAbsCoeffOzone->GetX()[fAbsCoeffOzone->GetN()-1], fAbsCoeffAerosols->GetX()[fAbsCoeffAerosols->GetN()-1]) : -1; }
+
+    Bool_t HasValidOzone() const   { return fAbsCoeffOzone    && fAbsCoeffOzone->GetN()>0; }
+    Bool_t HasValidAerosol() const { return fAbsCoeffAerosols && fAbsCoeffAerosols->GetN()>0; }
+
+    Bool_t IsAllValid() const { return IsValid() && HasValidOzone() && HasValidAerosol(); }
+
+    void PreCalcOzone()
+    {
+        // It follows a precalculation of the slant path integrals we need
+        // for the estimate of the Mie scattering and Ozone absorption:
+        Double_t dh = 1.e3;
+        const Double_t STEPTHETA = 1.74533e-2; // aprox. 1 degree
+
+        // Ozone absorption
+        for (Int_t j = 0; j < 90; j++)
+        {
+            const Double_t theta = j * STEPTHETA;  
+            const Double_t sin2  = sin(theta)*sin(theta);
+            const Double_t H     = R()+fObsLevel;
+
+            Double_t path_slant = 0;
+            for (Double_t h = fObsLevel; h <= 50e5; h += dh)
+            {
+                // h is the true height vertical above ground
+                if (fmod(h,1e4) == 0)
+                    ozone_path[(int)(h/1e4)][j] = path_slant;
+
+                const Double_t km  = h/1e5;
+                const Int_t    i   = TMath::FloorNint(km);
+                const Double_t l   = R()+h;
+
+                const Double_t L   = TMath::Sqrt(l*l - H*H * sin2);
+                const Double_t f   = dh * l / L;
+
+                // Linear interpolation at h/1e5
+                Double_t interpol = oz_conc[i] + fmod(km, 1) * (oz_conc[i+1]-oz_conc[i]);
+
+                path_slant += f * interpol;
+            }
+        }
+    }
+
+    void PreCalcAerosol()
+    {
+        // It follows a precalculation of the slant path integrals we need
+        // for the estimate of the Mie scattering and Ozone absorption:
+        Double_t dh = 1.e3;
+        const Double_t STEPTHETA = 1.74533e-2; // aprox. 1 degree
+
+        /* Mie (aerosol): */
+        for (Int_t j = 0; j < 90; j++)
+        {
+            const Double_t theta = j * STEPTHETA;  
+            const Double_t sin2  = sin(theta)*sin(theta);
+            const Double_t H     = R()+fObsLevel;
+
+            Double_t path_slant = 0;
+            for (Double_t h = fObsLevel; h <= 30e5; h += dh)
+            {
+                // h is the true height vertical above ground
+                if (fmod(h,1e4) == 0)
+                    aerosol_path[(int)(h/1e4)][j] = path_slant;
+
+                const Double_t km  = h/1e5;
+                const Int_t    i   = TMath::FloorNint(km);
+                const Double_t l   = R()+h;
+
+                const Double_t L   = TMath::Sqrt(l*l - H*H * sin2);
+                const Double_t f   = dh * l / L;
+
+                // Linear interpolation at h/1e5
+                Double_t interpol = aero_n[i] + fmod(km, 1)*(aero_n[i+1]-aero_n[i]);
+
+                path_slant += f * interpol/aero_n[0];    // aero_n [km^-1]
+            }
+        }
+    }
+
+    Bool_t InitOzone(const TString name="")
+    {
+        if (!name.IsNull())
+        {
+            if (fAbsCoeffOzone)
+                delete fAbsCoeffOzone;
+
+            fAbsCoeffOzone = new TGraph(name);
+            fAbsCoeffOzone->Sort();
+        }
+
+        if (!HasValidAerosol())
+            return kFALSE;
+
+        if (IsValid())
+            PreCalcOzone();
+
+        return kTRUE;
+    }
+
+    Bool_t InitAerosols(const TString name="")
+    {
+        if (!name.IsNull())
+        {
+            if (fAbsCoeffAerosols)
+                delete fAbsCoeffAerosols;
+
+            fAbsCoeffAerosols = new TGraph(name);
+            fAbsCoeffAerosols->Sort();
+        }
+
+        if (!HasValidAerosol())
+            return kFALSE;
+
+        if (IsValid())
+            PreCalcAerosol();
+
+        return kTRUE;
+    }
+
+    void Init(const MCorsikaRunHeader &h, const char *name1=0, const char *name2=0)
+    {
+        MAtmRayleigh::Init(h);
+
+        InitOzone(name1);
+        InitAerosols(name2);
+    }
+/*
+    Double_t GetOz(Double_t height, Double_t theta) const
+    {
+        // Distance between two points D = 1km /cos(theta)
+        // Density along y within this km:   f =  (x[i+1]-x[i])/1km * dy
+        // Integral of this density  f =  (x[i+1]-x[i])/1km * (y[i+1]-y[i])
+        // f(h) = int [ (c1-c0)/1km*(h-h0)*dh + c0 ] dh
+        //      = (c-co)*(h-h0)
+
+        Double_t rc = 0;
+        int i;
+        for (i=0; i<49; i++)
+            if (i>=2 && i+1<height/1e5)    // cm -> km
+                rc += oz_conc[i] * 1e5/cos(theta);
+
+        rc -= oz_conc[2]*0.2*1e5/cos(theta);
+        rc += oz_conc[i+1]*fmod(height/1e5,1)*1e5/cos(theta);
+
+        return rc;
+    }
+    */
+
+    Double_t CalcOzoneAbsorption(Double_t h, Double_t wavelength, Double_t theta) const
+    {
+        if (!fAbsCoeffOzone)
+            return 1;
+
+        //******* Ozone absorption *******
+        if (h > 50.e5)
+            h = 50.e5;
+
+        // Vigroux Ozone absorption coefficient a.s.l. through interpolation:
+        //const float oz_vigroux[15]= {1.06e2, 1.01e1, 8.98e-1, 6.40e-2, 1.80e-3, 0, 0, 3.50e-3, 3.45e-2, 9.20e-2, 1.32e-1, 6.20e-2, 2.30e-2, 1.00e-2, 0.00};
+        //const Double_t beta0 = getbeta(wavelength, oz_vigroux);
+        const Double_t beta0 = GetBeta(wavelength, *fAbsCoeffOzone);
+
+        // Now use the pre-calculated values of the path integral
+        // for h and theta
+        const UInt_t H = TMath::Nint(h/1e4);
+        const UInt_t T = TMath::Min(89, TMath::Nint(theta/STEPTHETA));
+
+        const Double_t path = ozone_path[H][T];
+
+        return TMath::Exp(-beta0*path);
+    }
+
+    Double_t CalcAerosolAbsorption(Double_t h, Double_t wavelength, Double_t theta) const
+    {
+        if (!fAbsCoeffAerosols)
+            return 1;
+
+        //******* Mie (aerosol) *******
+        if (h > 30.e5)
+            h = 30.e5;
+
+        //const float aero_betap[15] = {0.27, 0.26, 0.25, 0.24, 0.24, 0.23, 0.20, 0.180, 0.167, 0.158, 0.150, 0.142, 0.135, 0.127, 0.120};
+        //const Double_t beta0 = getbeta(wavelength, aero_betap);
+        const Double_t beta0 = GetBeta(wavelength, *fAbsCoeffAerosols);
+
+        // Now use the pre-calculated values of the path integral
+        // for h and theta
+        const UInt_t H = TMath::Nint(h/1e4);
+        const UInt_t T = TMath::Min(89, TMath::Nint(theta/STEPTHETA));
+
+
+        const Double_t path = aerosol_path[H][T];
+
+        return TMath::Exp(-beta0*path);
+    }
+
+    Double_t GetTransmission(const MPhotonData &ph) const
+    {
+        const Double_t wavelength = ph.GetWavelength();
+        const Double_t height     = ph.GetProductionHeight();
+
+        // Reduce the necessary number of floating point operations
+        // by storing the intermediate results
+        const Double_t sin2  = ph.GetSinW2();
+        const Double_t cost  = TMath::Sqrt(1-sin2);
+        const Double_t theta = TMath::ACos(cost);
+
+        // Path from production height to obslevel
+        const Double_t z = height-fObsLevel;
+
+        // Distance of emission point to incident point on ground
+        const Double_t d = z/cost;
+
+        // Avoid problems if photon is very close to telescope:
+        if (TMath::Abs(d)<1)
+            return 1;
+
+        // Earth radius plus observation height (distance of telescope
+        // from earth center)
+        const Double_t H = R() + fObsLevel;
+
+        // We calculate h, the true height a.s.l.
+        // of the photon emission point in cm
+        const Double_t h = TMath::Sqrt(H*H + d*d + 2*H*z) - R();
+
+        //**** Rayleigh scattering: *****
+        const Double_t T_Ray = CalcTransmission(h, wavelength, sin2);
+        if (T_Ray<0)
+            return 0;
+
+        //****** Ozone absorption: ******
+        const Double_t T_Oz  = CalcOzoneAbsorption(h, wavelength, theta);
+
+        //******** Mie (aerosol) ********
+        const Double_t T_Mie = CalcAerosolAbsorption(h, wavelength, theta);
+
+        // FIXME: What if I wanna display these values?
+
+        // Calculate final transmission coefficient
+        return T_Ray * T_Oz * T_Mie;
+    }
+};
+
+const Double_t MAtmosphere::STEPTHETA = 1.74533e-2; // aprox. 1 degree
+
+const Double_t MAtmRayleigh::fgMeanFreePath = 2970;
+
+const Double_t MAtmosphere::aero_n[31] = {200, 87, 38, 16, 7.2, 3.1, 1.1, 0.4, 0.14, 5.0e-2, 2.6e-2, 2.3e-2, 2.1e-2, 2.3e-2, 2.5e-2, 4.1e-2, 6.7e-2, 7.3e-2, 8.0e-2, 9.0e-2, 8.6e-2, 8.2e-2, 8.0e-2, 7.6e-2, 5.2e-2, 3.6e-2, 2.5e-2, 2.4e-2, 2.2e-2, 2.0e-2, 1.9e-2};
+
+const Double_t MAtmosphere::oz_conc[51]={0.3556603E-02, 0.3264150E-02, 0.2933961E-02, 0.2499999E-02, 0.2264150E-02, 0.2207546E-02, 0.2160377E-02, 0.2226414E-02, 0.2283018E-02, 0.2811320E-02, 0.3499999E-02, 0.4603772E-02, 0.6207545E-02, 0.8452828E-02, 0.9528299E-02, 0.9905657E-02, 0.1028302E-01, 0.1113207E-01, 0.1216981E-01, 0.1424528E-01, 0.1641509E-01, 0.1839622E-01, 0.1971697E-01, 0.1981131E-01, 0.1933962E-01, 0.1801886E-01, 0.1632075E-01, 0.1405660E-01, 0.1226415E-01, 0.1066037E-01, 0.9028300E-02, 0.7933960E-02, 0.6830187E-02, 0.5820753E-02, 0.4830188E-02, 0.4311319E-02, 0.3613206E-02, 0.3018867E-02, 0.2528301E-02, 0.2169811E-02, 0.1858490E-02, 0.1518867E-02, 0.1188679E-02, 0.9301884E-03, 0.7443394E-03, 0.5764149E-03, 0.4462263E-03, 0.3528301E-03, 0.2792452E-03, 0.2226415E-03, 0.1858490E-03};
+
+// ==========================================================================
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimAtmosphere::MSimAtmosphere(const char* name, const char *title)
+    : fEvt(0), fAtmosphere(0),
+    fFileAerosols("resmc/atmosphere-aerosols.txt"),
+    fFileOzone("resmc/atmosphere-ozone.txt")
+{
+    fName  = name  ? name  : "MSimAtmosphere";
+    fTitle = title ? title : "Simulate the wavelength and height-dependant atmpsheric absorption";
+
+    fAtmosphere = new MAtmosphere;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calls Clear()
+//
+MSimAtmosphere::~MSimAtmosphere()
+{
+    delete fAtmosphere;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the needed parameter containers. Read spline from file
+// calling ReadFile();
+//
+Int_t MSimAtmosphere::PreProcess(MParList *pList)
+{
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MSimAtmosphere::ReInit(MParList *pList)
+{
+    MCorsikaRunHeader *h = (MCorsikaRunHeader*)pList->FindObject("MCorsikaRunHeader");
+    if (!h)
+    {
+        *fLog << err << "MCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    //if (fRunHeader->Has(MCorsikaRunHeader::kRefraction))
+    //    *fLog << inf << "Atmospheric refraction already applied in Corsika... skipping our own." << endl;
+
+    // FIXME: Check wavelength range
+
+    /*
+    if (h->GetWavelengthMin()<fSpline->GetXmin())
+        *fLog << warn << "WARNING - Lower bound of wavelength bandwidth exceeds lower bound of spline." << endl;
+
+    if (h->GetWavelengthMax()>fSpline->GetXmax())
+        *fLog << warn << "WARNING - Upper bound of wavelength bandwidth exceeds upper bound of spline." << endl;
+    */
+
+    fAtmosphere->Init(*h, fFileOzone, fFileAerosols);
+
+    if (!fAtmosphere->IsAllValid())
+    {
+        *fLog << err << "ERROR - Something with the atmoshere's initialization went wrong!" << endl;
+        return kFALSE;
+    }
+
+    if (h->GetWavelengthMin()<fAtmosphere->GetWavelengthMin())
+        *fLog << warn << "WARNING - Lower bound of wavelength bandwidth exceeds valid range of atmosphere." << endl;
+
+    if (h->GetWavelengthMax()>fAtmosphere->GetWavelengthMax())
+        *fLog << warn << "WARNING - Lower bound of wavelength bandwidth exceeds  valid range of atmosphere." << endl;
+
+    if (!h->Has(MCorsikaRunHeader::kAtmext))
+        *fLog << warn << "WARNING - ATMEXT option not used for Corsika data." << endl;
+
+    if (!h->Has(MCorsikaRunHeader::kRefraction))
+        *fLog << warn << "WARNING - Refraction calculation disabled for Corsika data." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MSimAtmosphere::Process()
+{
+    // Get the number of photons in the list
+    const Int_t num = fEvt->GetNumPhotons();
+
+    // FIMXE: Add checks for
+    //         * upgoing particles
+    //         * Can we take the full length until the camera into account?
+
+    // Counter for number of total and final events
+    Int_t cnt = 0;
+    for (Int_t i=0; i<num; i++)
+    {
+        // Get i-th photon from the list
+        const MPhotonData &ph = (*fEvt)[i];
+
+        // Get atmospheric transmission for this photon
+        const Double_t eff = fAtmosphere->GetTransmission(ph);
+
+        // Get a random value between 0 and 1 to determine whether the photon will survive
+        // gRandom->Rndm() = [0;1[
+        if (gRandom->Rndm()>=eff)
+            continue;
+
+        // Copy the surviving events bakc in the list
+        (*fEvt)[cnt++] = ph;
+    }
+
+    // Now we shrink the array to the number of new entries.
+    fEvt->Shrink(cnt);
+
+    return kTRUE;
+}
+
+/*
+ Int_t MSimWavelength::Process()
+ {
+    // Get the number of photons in the list
+    const Int_t num = fEvt->GetNumPhotons();
+
+    // FIMXE: Add checks for
+    //         * upgoing particles
+    //         * wavelength range
+    //         * check if corsika atmosphere is switched on
+    //         * Can we take the full length until the camera into account?
+
+    // Counter for number of total and final events
+    Int_t cnt = 0;
+    for (Int_t i=0; i<num; i++)
+    {
+        // Get i-th photon from the list
+        MPhotonData &ph = (*fEvt)[i];
+
+        const Double_t min = fRunHeader->GetWavelengthMin(); // WAVLGL
+        const Double_t max = fRunHeader->GetWavelengthMax(); // WAVLGU
+        const Double_t f   = (max-min)/max;
+
+        // WAVELENGTH = 1. / (1/min - RD(1)/(min*max/(max-min)))
+
+
+        ph.SetWavelength(TMath::Nint(min / (1. - gRandom->Rndm()*f)));
+    }
+
+    return kTRUE;
+ }
+ */
+
+// --------------------------------------------------------------------------
+//
+// FileAerosols: resmc/atmosphere-aerosols.txt
+// FileOzone:    resmc/atmosphere-ozone.txt
+//
+Int_t MSimAtmosphere::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "FileAerosols", print))
+    {
+        rc = kTRUE;
+        fFileAerosols = GetEnvValue(env, prefix, "FileAerosols", fFileAerosols);
+    }
+
+    if (IsEnvDefined(env, prefix, "FileOzone", print))
+    {
+        rc = kTRUE;
+        fFileOzone = GetEnvValue(env, prefix, "FileOzone", fFileOzone);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msim/MSimAtmosphere.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimAtmosphere.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimAtmosphere.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MSimAtmosphere
+#define MARS_MSimAtmosphere
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MAtmosphere;
+class MPhotonEvent;
+
+class MSimAtmosphere : public MTask
+{
+private:
+    MPhotonEvent *fEvt;        //! Event stroing the photons
+
+    MAtmosphere  *fAtmosphere; //! Instance of class describing atmosphere
+
+    TString fFileAerosols;     // Name of file with aersole absorption
+    TString fFileOzone;        // Name of file with ozone absorption
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSimAtmosphere(const char *name=NULL, const char *title=NULL);
+    ~MSimAtmosphere();
+
+    ClassDef(MSimAtmosphere, 0) // Simulate the wavelength and height-dependant atmpsheric absorption
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msim/MSimMMCS.cc
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimMMCS.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimMMCS.cc	(revision 17960)
@@ -0,0 +1,221 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimMMCS
+//
+// Task to copy the Mars CheObs MC headers to the old Mars style
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimMMCS.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+#include "MRawRunHeader.h"
+
+#include "MCorsikaRunHeader.h"
+#include "MCorsikaEvtHeader.h"
+
+#include "MMcRunHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+#include "MPointingPos.h"
+
+ClassImp(MSimMMCS);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimMMCS::MSimMMCS(const char* name, const char *title)
+{
+    fName  = name  ? name  : "MSimMMCS";
+    fTitle = title ? title : "Task to copy the Mars CheObs MC headers to the old Mars style";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MSimMMCS::PreProcess(MParList *plist)
+{
+    fMcRunHeader = (MMcRunHeader*)plist->FindCreateObj("MMcRunHeader");
+    if (!fMcRunHeader)
+        return kFALSE;
+
+    if (!plist->FindCreateObj("MMcCorsikaRunHeader"))
+        return kFALSE;
+
+    if (!plist->FindCreateObj("MRawRunHeader"))
+        return kFALSE;
+
+    fMcEvtBasic = (MMcEvtBasic*)plist->FindCreateObj("MMcEvtBasic");
+    if (!fMcEvtBasic)
+        return kFALSE;
+
+    fMcEvt = (MMcEvt*)plist->FindCreateObj("MMcEvt");
+    if (!fMcEvt)
+        return kFALSE;
+
+    fPointingTel = (MPointingPos*)plist->FindObject("MPointingPos");
+    if (!fPointingTel)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvtHeader = (MCorsikaEvtHeader*)plist->FindObject("MCorsikaEvtHeader");
+    if (!fEvtHeader)
+    {
+        *fLog << err << "MCorsikaEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunHeader = (MCorsikaRunHeader*)plist->FindObject("MCorsikaRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MSimMMCS::ReInit(MParList *plist)
+{
+    MMcCorsikaRunHeader *mch = (MMcCorsikaRunHeader*)plist->FindObject("MMcCorsikaRunHeader");
+    if (!mch)
+    {
+        *fLog << err << "MMcCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    mch->SetSpectrum(fRunHeader->GetSlopeSpectrum(),
+                     fRunHeader->GetEnergyMin(), fRunHeader->GetEnergyMax());
+    mch->SetViewCone(fRunHeader->GetViewConeInnerAngle(),
+                     fRunHeader->GetViewConeOuterAngle());
+    mch->SetReadyToSave();
+
+    // ----------------------------------------------------
+
+    //    fNumPheFromDNSB        MMcPedestalNSBAdd   // Number of phe/ns from diffuse NSB
+
+    // FIXME: Is there a way to write them as LAST entry in the file?
+    fMcRunHeader->SetNumSimulatedShowers(fRunHeader->GetNumEvents()*fRunHeader->GetNumReuse());
+    fMcRunHeader->SetCorsikaVersion(TMath::Nint(fRunHeader->GetProgramVersion()*100));
+
+    if (fRunHeader->GetImpactMax()>0)
+        fMcRunHeader->SetImpactMax(fRunHeader->GetImpactMax());
+
+    // ----------------------------------------------------
+
+    MRawRunHeader *rh = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!rh)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const UInt_t id = fRunHeader->GetParticleID();
+
+    // FIXME: Is there a way to write them as LAST entry in the file?
+    rh->SetFileNumber(fRunHeader->GetRunNumber()%1000);
+    rh->SetSourceInfo(MMcEvtBasic::GetParticleName(id));
+    rh->SetReadyToSave();
+
+    // ----------------------------------------------------
+
+    fMcEvtBasic->SetPartId(MMcEvtBasic::ParticleId_t(id));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// We have two scenarios for the ponting:
+//
+//  1) Diffuse flux (view cone option)
+//
+//     Azimuth and Zenith angle are fixed values (min==max).
+//     The diffuse flux is produced in a cone around this angle.
+//
+//     That means that the telescope orientation is aligned and fixed
+//     along the cone axis.
+//
+//     To analyse a diffuse flux the source position should be fixed to
+//     the camera center.
+//     In some cases (e.g. training of RF) the source depending parameters
+//     might be needed w.r.t. the real origin of the primary particle.
+//     In this case the primary shower direction is needed.
+//
+//  2) Directed flux
+//
+//     Particles are produced between a min and max Azimuth and Zenith angle.
+//     The telescope axis is either parallel (on source) or off axis
+//     (wobble) to the primary particle direction.
+//     This is used to "fake" the trajectory of the source.
+//
+//  3) Flux along a trajectory
+//
+//     [...]
+//
+Int_t MSimMMCS::Process()
+{
+    fMcEvtBasic->SetEnergy(fEvtHeader->GetTotalEnergy());
+    fMcEvtBasic->SetImpact(fEvtHeader->GetImpact());
+
+    // Pointing direction of the telescope (telescope axis)
+    fMcEvtBasic->SetTelescopeTheta(fPointingTel->GetZdRad());
+    fMcEvtBasic->SetTelescopePhi(fPointingTel->GetAzRad());
+
+    // Direction of primary particle
+    // Convert from corsika frame to telescope frame, taking
+    // the magnetic field into account: tel = corsika+offset
+    fMcEvtBasic->SetParticleTheta(fEvtHeader->GetZd());
+    fMcEvtBasic->SetParticlePhi(fEvtHeader->GetAz()+fRunHeader->GetMagneticFieldAz());
+
+    fMcEvtBasic->SetReadyToSave();
+
+
+    static_cast<MMcEvtBasic&>(*fMcEvt) = *fMcEvtBasic;
+
+
+    fMcEvt->SetEvtNumber(fEvtHeader->GetEvtNumber());
+    fMcEvt->SetEventReuse(fEvtHeader->GetNumReuse());
+    fMcEvt->SetPhotElfromShower(0);
+
+    if (fRunHeader->GetImpactMax()<0 &&
+        fEvtHeader->GetImpact()>fMcRunHeader->GetImpactMax())
+        fMcRunHeader->SetImpactMax(fEvtHeader->GetImpact());
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/msim/MSimMMCS.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimMMCS.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimMMCS.h	(revision 17960)
@@ -0,0 +1,37 @@
+#ifndef MARS_MSimMMCS
+#define MARS_MSimMMCS
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MMcEvt;
+class MMcEvtBasic;
+class MPointingPos;
+class MCorsikaEvtHeader;
+class MCorsikaRunHeader;
+class MMcRunHeader;
+
+class MSimMMCS : public MTask
+{
+private:
+    MMcEvtBasic       *fMcEvtBasic;   //!
+    MMcEvt            *fMcEvt;        //!
+    MPointingPos      *fPointingTel;  //! telescope poiting position in local (telescope) coordinate system
+    MCorsikaEvtHeader *fEvtHeader;    //!
+    MCorsikaRunHeader *fRunHeader;    //!
+    MMcRunHeader      *fMcRunHeader;  //!
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSimMMCS(const char* name=0, const char *title=0);
+
+    ClassDef(MSimMMCS, 0) // Task to copy the Mars CheObs MC headers to the old Mars style
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msim/MSimPointingPos.cc
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimPointingPos.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimPointingPos.cc	(revision 17960)
@@ -0,0 +1,263 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSimPointingPos
+//
+//
+// This task is meant to simulate the pointing position (mirror orientation).
+// This depends on the direction from which the shower is coming but also
+// on the user request (e.g. Wobble mode).
+//
+//
+// If fOffTargetDistance==0 the telescope is oriented depending on the
+// view cone option. If a view cone was given the orientation is fixed to
+// the main direction around the view cone was produced. If no view
+// cone was given the telescope is oriented parallel to the shower axis.
+//
+// If no view cone option was given and off-target observations are switched
+// on by setting fOffTargetDistance!=0 the poitnting position is calculated:
+//
+//  1) fOffTargetDistance < 0:
+//     The pointing position is randomly distributed in a disk of radius
+//     -fOffTargetDistance. fOffTargetDistance is silently ignored.
+//
+//  2) fOffTargetDistance > 0:
+//     The pointing position is set to a position in the given distance
+//     away from the shower axis. If fOffTargetPhi>=0 it is fixed at
+//     this phi value. For phi<0 it is randomly distributed at distances
+//     fOffTargetDistance. (phi==0 is the direction of positive theta)
+//
+//
+//  Input Containers:
+//   MCorsikaRunHeader
+//   MCorsikaEvtHeader
+//
+//  Output Containers:
+//   MPointingPos
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimPointingPos.h"
+
+#include <TRandom.h>
+#include <TVector3.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCorsikaEvtHeader.h"
+#include "MCorsikaRunHeader.h"
+
+#include "MPointingPos.h"
+
+ClassImp(MSimPointingPos);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimPointingPos::MSimPointingPos(const char* name, const char *title)
+    : fRunHeader(0), fEvtHeader(0), fPointing(0),
+    fOffTargetDistance(0), fOffTargetPhi(-1)
+
+{
+    fName  = name  ? name  : "MSimPointingPos";
+    fTitle = title ? title : "Task to simulate the pointing position (mirror orientation)";
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the distance from the real source to the poitning position.
+//
+Double_t MSimPointingPos::GetOffTargetDistance() const
+{
+    return fOffTargetDistance==0 ? 0 : fOffTargetDistance*TMath::RadToDeg();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the phi angle counted from the upward direction the source position
+// is rotated. distance from the real source to the pointing position.
+// A negative value refers to a random distribution.
+//
+Double_t MSimPointingPos::GetOffTargetPhi() const
+{
+    return fOffTargetPhi<0 ? -1 : fOffTargetPhi*TMath::RadToDeg();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set fOffTargetDistance, see also GetOffTargetDistance
+//
+void MSimPointingPos::SetOffTargetDistance(Double_t d)
+{
+    fOffTargetDistance = d==0 ? 0 : d*TMath::DegToRad();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set fOffTargetPhi, see also GetOffTargetPhi
+//
+void MSimPointingPos::SetOffTargetPhi(Double_t p)
+{
+    fOffTargetPhi = p<0 ? -1 : p*TMath::DegToRad();
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Search for all necessary containers
+//
+Int_t MSimPointingPos::PreProcess(MParList *pList)
+{
+    fPointing = (MPointingPos*)pList->FindCreateObj("MPointingPos");
+    if (!fPointing)
+        return kFALSE;
+
+    fRunHeader = (MCorsikaRunHeader*)pList->FindObject("MCorsikaRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvtHeader = (MCorsikaEvtHeader*)pList->FindObject("MCorsikaEvtHeader");
+    if (!fEvtHeader)
+    {
+        *fLog << err << "MCorsikaEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!IsOffTargetObservation())
+        return kTRUE;
+
+    *fLog << inf;
+    *fLog << "Off target observations switched on with" << endl;
+    if (fOffTargetDistance>0)
+    {
+        *fLog <<"   a pointing distance of " << GetOffTargetDistance() << "deg ";
+        if (fOffTargetPhi<0)
+            *fLog << "randomly distributed in phi." << endl;
+        else
+            *fLog << "and phi=" << GetOffTargetPhi() << "deg." << endl;
+    }
+    else
+        *fLog << "   a homogenous distribution up to a distance of " << -GetOffTargetDistance() << "deg " << endl;
+
+    return kTRUE;
+}
+
+Bool_t MSimPointingPos::ReInit(MParList *pList)
+{
+    if (fRunHeader->HasViewCone() && IsOffTargetObservation())
+    {
+        *fLog << warn;
+        *fLog << "WARNING - Combining the view cone option with off-target observations doesn't make sense." << endl;
+        *fLog << "          Option for off-target observations will be ignored." << endl;
+    }
+    // FIXME: Check also the enlightened region on the ground!
+    return kTRUE;
+}
+
+void MSimPointingPos::GetDelta(Double_t &dtheta, Double_t &dphi) const
+{
+    if (fOffTargetDistance>0)
+    {
+        dtheta = fOffTargetDistance;
+        dphi   = fOffTargetPhi>=0 ? fOffTargetPhi : gRandom->Uniform(TMath::TwoPi());
+    }
+    else
+    {
+        dtheta = TMath::Sqrt(gRandom->Uniform(fOffTargetDistance));
+        dphi   = gRandom->Uniform(TMath::TwoPi());
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MSimPointingPos::Process()
+{
+    // If a view cone is given use the fixed telescope orientation
+    const Bool_t viewcone = fRunHeader->HasViewCone();
+
+    // Local sky coordinates (direction of telescope axis)
+    Double_t zd = viewcone ? fRunHeader->GetZdMin() : fEvtHeader->GetZd()*TMath::RadToDeg();  // x==north
+    Double_t az = viewcone ? fRunHeader->GetAzMin() : fEvtHeader->GetAz()*TMath::RadToDeg();  // y==west
+
+    if (!viewcone)
+    {
+        Double_t dtheta, dphi;
+        GetDelta(dtheta, dphi);
+
+        const Double_t theta = zd*TMath::DegToRad();
+        const Double_t phi   = az*TMath::DegToRad();
+
+        TVector3 src, pnt;
+        src.SetMagThetaPhi(1, theta,        phi);
+        pnt.SetMagThetaPhi(1, theta+dtheta, phi);
+
+        pnt.Rotate(dphi, src);
+
+        zd = pnt.Theta()*TMath::RadToDeg();
+        az = pnt.Phi()  *TMath::RadToDeg();
+    }
+
+    // Transform the corsika coordinate system (north is magnetic north)
+    // into the telescopes local coordinate system. Note, that all vectors
+    // are already correctly oriented.
+    az += fRunHeader->GetMagneticFieldAz()*TMath::RadToDeg();
+
+    // Setup the pointing position
+    fPointing->SetLocalPosition(zd, az);
+
+    // Calculate incident angle between magnetic field direction
+    // and pointing direction ( phi and theta? )
+
+    return kTRUE;
+}
+
+Int_t MSimPointingPos::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "OffTargetDistance", print))
+    {
+        rc = kTRUE;
+        SetOffTargetDistance(GetEnvValue(env, prefix, "OffTargetDistance", GetOffTargetDistance()));
+    }
+
+    if (IsEnvDefined(env, prefix, "OffTargetPhi", print))
+    {
+        rc = kTRUE;
+        SetOffTargetPhi(GetEnvValue(env, prefix, "OffTargetPhi", GetOffTargetPhi()));
+    }
+
+    return rc;
+}
+
Index: branches/Mars_McMismatchStudy/msim/MSimPointingPos.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/MSimPointingPos.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/MSimPointingPos.h	(revision 17960)
@@ -0,0 +1,54 @@
+#ifndef MARS_MSimPointingPos
+#define MARS_MSimPointingPos
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MCorsikaEvtHeader;
+class MCorsikaRunHeader;
+class MPointingPos;
+
+class MSimPointingPos : public MTask
+{
+private:
+    MCorsikaRunHeader *fRunHeader;  //! Header storing event information
+    MCorsikaEvtHeader *fEvtHeader;  //! Header storing event information
+    MPointingPos      *fPointing;   //! Output storing telescope poiting position in local (telescope) coordinate system
+
+    Double_t fOffTargetDistance;    // [rad] Distance of the observed off-target position from the source
+    Double_t fOffTargetPhi;         // [rad] Rotation angle of the off-target position (phi==0 means south, phi=90 west) [0;2pi], phi<0 means random
+
+    // MSimPointingPos
+    void GetDelta(Double_t &dtheta, Double_t &dphi) const;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSimPointingPos(const char *name=NULL, const char *title=NULL);
+
+    // Getter
+    Double_t GetOffTargetDistance() const;
+    Double_t GetOffTargetPhi() const;
+
+    // Setter
+    void SetOffTargetDistance(Double_t d=0);
+    void SetOffTargetPhi(Double_t p=-1);
+
+    // MSimPointingPos
+    Bool_t IsOffTargetObservation() const { return fOffTargetDistance!=0; }
+
+    // TObject
+
+    ClassDef(MSimPointingPos, 0) // Task to simulate the pointing position (mirror orientation)
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/msim/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/msim/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/Makefile	(revision 17960)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Sim
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mmc -I../mgeom -I../mgui -I../mcorsika \
+           -I../mpointing -I../msimreflector -I../mhbase -I../mraw
+
+SRCFILES = MPhotonData.cc \
+	   MPhotonEvent.cc \
+	   MHPhotonEvent.cc \
+	   MSimMMCS.cc \
+	   MSimAtmosphere.cc \
+	   MSimAbsorption.cc \
+	   MSimPointingPos.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/msim/SimIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/SimIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/SimIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/msim/SimLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/msim/SimLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msim/SimLinkDef.h	(revision 17960)
@@ -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 MPhotonEvent+;
+#pragma link C++ class MPhotonData+;
+
+#pragma link C++ class MHPhotonEvent+;
+
+#pragma link C++ class MPhotonStatistics+;
+
+#pragma link C++ class MSimPointingPos+;
+#pragma link C++ class MSimAbsorption+;
+#pragma link C++ class MSimAtmosphere+;
+
+#pragma link C++ class MSimMMCS+;
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimAPD.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimAPD.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimAPD.cc	(revision 17960)
@@ -0,0 +1,441 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimAPD
+//
+// This tasks simulates the individual APDs. Before starting the APD is
+// initialized randomly according to the photon rate hitting the APD. Such
+// it is assumed that the initial condition of the APD is similar to the real
+// one. In this context it is assumed that the events are independent, so
+// that the APD is always in the same condition.
+//
+// For every photon and event the behaviour of the APD is simulated. The
+// output is set as weight to the MPhotonData containers.
+//
+// Remark:
+//   - The photon rate used to initialize the APD must match the one used
+//     to "fill" the random photons. (FIXME: This should be stored somewhere)
+//
+//  Input Containers:
+//   fNameGeomCam [MGeomCam]
+//   MPhotonEvent
+//   MPhotonStatistics
+//
+//  Output Containers:
+//   MPhotonEvent
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimAPD.h"
+
+#include <TH2.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMath.h"
+#include "MParList.h"
+
+#include "MGeomCam.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MAvalanchePhotoDiode.h"
+
+#include "MParameters.h"
+
+ClassImp(MSimAPD);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimAPD::MSimAPD(const char* name, const char *title)
+    : fGeom(0), fEvt(0), fStat(0), fType(1),
+    fNumCells(60), fCrosstalkCoeff(0), fDeadTime(3),
+    fRecoveryTime(8.75), fAfterpulseProb1(0.11), fAfterpulseProb2(0.14)
+
+{
+    fName  = name  ? name  : "MSimAPD";
+    fTitle = title ? title : " Task to simulate the detection behaviour of APDs";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Get the necessary parameter containers
+//
+Int_t MSimAPD::PreProcess(MParList *pList)
+{
+    if (fNameGeomCam.IsNull())
+    {
+        *fLog << inf << "No geometry container... skipping." << endl;
+        return kSKIP;
+    }
+
+    fGeom = (MGeomCam*)pList->FindObject(fNameGeomCam, "MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << inf << fNameGeomCam << " [MGeomCam] not found..." << endl;
+
+        fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+        if (!fGeom)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fStat = (MPhotonStatistics*)pList->FindObject("MPhotonStatistics");
+    if (!fStat)
+    {
+        *fLog << err << "MPhotonStatistics not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCrosstalkCoeffParam = (MParameterD*)pList->FindCreateObj("MParameterD","CrosstalkCoeffParam");
+    if (!fCrosstalkCoeffParam)
+    {
+        *fLog << err << "CrosstalkCoeffParam [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+    fCrosstalkCoeffParam->SetVal(fCrosstalkCoeff);
+
+    fRates = (MPedestalCam*)pList->FindObject("AccidentalPhotonRates", "MPedestalCam");
+    if (!fRates)
+    {
+        *fLog << inf;
+        *fLog << "AccidentalPhotonRates [MPedestalCam] not found..." << endl;
+        *fLog << " using " << fFreq << " as default for all G-APDs." << endl;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize as many APDs as we have pixels in the fGeomCam
+//
+Bool_t MSimAPD::ReInit(MParList *plist)
+{
+    if (UInt_t(fAPDs.GetEntriesFast())==fGeom->GetNumPixels())
+        return kTRUE;
+
+    fAPDs.Delete();
+
+    // FIXME:
+    //   * initialize an empty APD and read the APD setup from a file to
+    //     allow different APDs.
+    //   * Make the arguments a data member of MSimAPD
+
+    Int_t   ncells     = 0;
+    Float_t crosstalk  = 0;
+    Float_t deadtime   = 0;
+    Float_t recovery   = 0;
+    Float_t afterprob1 = 0;
+    Float_t afterprob2 = 0;
+
+    switch (fType)
+    {
+    case 0:
+        ncells     = fNumCells;
+        crosstalk  = fCrosstalkCoeff;
+        deadtime   = fDeadTime;
+        recovery   = fRecoveryTime;
+        afterprob1 = fAfterpulseProb1;
+        afterprob2 = fAfterpulseProb2;
+
+        gLog << inf << "Using custom G-APD parameters:" << endl;
+        gLog << " - Num cells:          " << fNumCells << endl;
+        gLog << " - Crosstalk coeff.:   " << fCrosstalkCoeff << endl;
+        gLog << " - Dead time:          " << fDeadTime << " ns" << endl;
+        gLog << " - Recovery time:      " << fRecoveryTime << " ns" << endl;
+        gLog << " - Afterpulse 1 prob.: " << fAfterpulseProb1 << endl;
+        gLog << " - Afterpulse 2 prob.: " << fAfterpulseProb2 << endl;
+        break;
+
+    case 1:
+        ncells     = 30;
+        crosstalk  = 0.2;
+        deadtime   = 3;
+        recovery   = 8.75*4;
+        afterprob1 = 0;
+        afterprob2 = 0;
+        break;
+
+    case 2:
+        ncells     = 60;
+        crosstalk  = 0.2;
+        deadtime   = 3;
+        recovery   = 8.75;
+        afterprob1 = 0;
+        afterprob2 = 0;
+        break;
+
+    case 3:
+        ncells     = 60;
+        crosstalk  = 0.15;
+        deadtime   = 3;
+        recovery   = 8.75;
+        afterprob1 = 0;
+        afterprob2 = 0;
+        break;
+
+    case 4:
+        ncells     = 60;
+        crosstalk  = 0.15;
+        deadtime   = 3;
+        recovery   = 8.75;
+        afterprob1 = 0.14;
+        afterprob2 = 0.11;
+        break;
+
+    default:
+        *fLog << err << "ERROR - APD type " << fType << " undefined." << endl;
+        return kFALSE;
+    }
+
+    for (UInt_t i=0; i<fGeom->GetNumPixels(); i++)
+    {
+        APD *apd = new APD(ncells, crosstalk, deadtime, recovery);
+        apd->SetAfterpulseProb(afterprob1, afterprob2);
+
+        fAPDs.Add(apd);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process all photons through the corresponding APD and set the output
+// (weight) accordingly.
+//
+Int_t MSimAPD::Process()
+{
+    // Make all APDs look neutral for the first hit by a photon according to the
+    // average hit rate
+    const UInt_t npix = fAPDs.GetEntriesFast();
+
+    // Check if we can safely proceed (this can fail if we either haven't been
+    // ReInit'ed or the max index in MPhotonStatistics is wrong)
+    if ((Int_t)npix<fStat->GetMaxIndex())
+    {
+        *fLog << err << "ERROR - MSimAPD::Process: Only " << npix << " APDs initialized. At least " << fStat->GetMaxIndex() << " needed... abort." << endl;
+        return kERROR;
+    }
+
+    // To ensure that the photons are always sorted when calling
+    // HitRandomCellRelative the array is sorted here. If it is sorted
+    // already nothing will be done since the status is stored.
+    // FIXME: Check that this is true and check that it is really necessary
+    fEvt->Sort();
+
+    // This tries to initialize dead and relaxing cells properly. If
+    // the APD has not been initialized before the chip is randomsly
+    // filled, otherwise a time window of the default relaxing time
+    // is simulated, so that the previous influence is less than a permille.
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        const Double_t freq = fRates ? (*fRates)[idx].GetPedestal() : fFreq;
+
+        // Init creates an empty G-APD, i.e. without external pulses
+        // but the correct history for afterpulses and relaxation.
+        // If it was already initialized once it evolves the G-APD
+        // for a time until the effect of relaxation and afterpulses
+        // is below 0.1%. The also creates the possible afterpulses
+        // of the future and deletes later afterpulses from the list.
+        // After the the time stamp fTime is set to 0.
+        static_cast<APD*>(fAPDs.UncheckedAt(idx))->Init(freq);
+    }
+
+    // Get number of photons
+    const Int_t num = fEvt->GetNumPhotons();
+
+    // Loop over all photons
+    for (Int_t i=0; i<num; i++)
+    {
+        // Get i-th photon
+        MPhotonData &ph = (*fEvt)[i];
+
+        // Get arrival time of photon wrt to left edge of window and its index
+        const Double_t t = ph.GetTime()-fStat->GetTimeFirst();
+        const Int_t  idx = ph.GetTag();
+        if (idx<0)
+        {
+            *fLog << err << "ERROR - MSimAPD: Invalid index -1." << endl;
+            return kERROR;
+        }
+
+        if (ph.GetWeight()!=1)
+        {
+            *fLog << err << "ERROR - MSimAPD: Weight of " << i << "-th photon not 1, but " << ph.GetWeight() << endl;
+            ph.Print();
+            return kERROR;
+        }
+
+        // Simulate hitting the APD at a time t after T0 (APD::fTime).
+        // Crosstalk is taken into account and the resulting signal height
+        // in effective "number of photons" is returned. Afterpulses until
+        // this time "hit" the G-APD and newly created afterpulses
+        // are stored in the list of afterpulses
+        const Double_t hits = static_cast<APD*>(fAPDs.UncheckedAt(idx))->HitRandomCellRelative(t);
+
+        // Set the weight to the input
+        ph.SetWeight(hits);
+    }
+
+    // Now we have to shift the evolved time of all APDs to the end of our
+    // simulated time.
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        APD *a = static_cast<APD*>(fAPDs.UncheckedAt(idx));
+
+        const Double_t end = fStat->GetTimeLast()-fStat->GetTimeFirst();
+
+        // This moves T0 (APD::fTime) at the right edge of our time-
+        // window. For the next event this means that afterpulses of past
+        // noise and afterpulses will be available already.
+        // FIXME: Note, that this might mean that a cosmics-pulse
+        //        might increase the noise above the normal level.
+        a->IncreaseTime(end);
+
+        // Get the afterpulses and add them to the signal
+        TIter Next(&a->GetListOfAfterpulses());
+        Afterpulse *ap = 0;
+        while ((ap=static_cast<Afterpulse*>(Next())))
+        {
+            // Skip afterpulses later than that which have been
+            // already produced
+            if (ap->GetTime()>=end)
+                continue;
+
+            // Add a new photon
+            // FIXME: SLOW!
+            MPhotonData &ph = fEvt->Add();
+
+            // Set source to Artificial (noise), the amplitude produced by the
+            // afterpulse (includes crosstalk), its arrival time
+            // and its amplitude, as well as the index of the channel it
+            // corresponds to.
+            ph.SetPrimary(MMcEvtBasic::kArtificial);
+            ph.SetWeight(ap->GetAmplitude());
+            ph.SetTime(ap->GetTime()+fStat->GetTimeFirst());
+            ph.SetTag(idx);
+        }
+
+        // It seems to make sense to delete the previous afterpulses now
+        // but this is not necessary. We have to loop over them in any
+        // case. So we omit the additional loop for deletion but instead
+        // do the deletion in the next loop at the end of Init()
+        // If needed this could be used to keep the total memory
+        // consumption slighly lower.
+    }
+
+    // Now the newly added afterpulses have to be sorted into the array correctly
+    fEvt->Sort();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// NameGeomCam
+// Type: 1
+//
+// Example for a custom made G-APD:
+//
+//    Type: 0
+//    NumCells: 60
+//    CrosstalkCoefficient: 0.1   // [prob]
+//    DeadTime: 3                 // [ns]
+//    RecoveryTime: 8.75          // [ns]
+//    AfterpulseProb1: 0.14       // [prob]
+//    AfterpulseProb2: 0.11       // [prob]
+//
+Int_t MSimAPD::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NameGeomCam", print))
+    {
+        rc = kTRUE;
+        fNameGeomCam = GetEnvValue(env, prefix, "NameGeomCam", fNameGeomCam);
+    }
+
+    if (IsEnvDefined(env, prefix, "Type", print))
+    {
+        rc = kTRUE;
+        fType = GetEnvValue(env, prefix, "Type", fType);
+    }
+
+    if (fType!=0)
+        return rc;
+
+    if (IsEnvDefined(env, prefix, "NumCells", print))
+    {
+        rc = kTRUE;
+        fNumCells = GetEnvValue(env, prefix, "NumCells", fNumCells);
+    }
+    if (IsEnvDefined(env, prefix, "CrosstalkCoefficient", print))
+    {
+        rc = kTRUE;
+        fCrosstalkCoeff = GetEnvValue(env, prefix, "CrosstalkCoefficient", fCrosstalkCoeff);
+    }
+    if (IsEnvDefined(env, prefix, "DeadTime", print))
+    {
+        rc = kTRUE;
+        fDeadTime = GetEnvValue(env, prefix, "DeadTime", fDeadTime);
+    }
+    if (IsEnvDefined(env, prefix, "RecoveryTime", print))
+    {
+        rc = kTRUE;
+        fRecoveryTime = GetEnvValue(env, prefix, "RecoveryTime", fRecoveryTime);
+    }
+    if (IsEnvDefined(env, prefix, "AfterpulseProb1", print))
+    {
+        rc = kTRUE;
+        fAfterpulseProb1 = GetEnvValue(env, prefix, "AfterpulseProb1", fAfterpulseProb1);
+    }
+    if (IsEnvDefined(env, prefix, "AfterpulseProb2", print))
+    {
+        rc = kTRUE;
+        fAfterpulseProb2 = GetEnvValue(env, prefix, "AfterpulseProb2", fAfterpulseProb2);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimAPD.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimAPD.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimAPD.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MSimAPD
+#define MARS_MSimAPD
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MGeomCam;
+class MParList;
+class MPhotonEvent;
+class MPhotonStatistics;
+class MPedestalCam;
+class MParameterD;
+
+class MSimAPD : public MTask
+{
+private:
+    MGeomCam          *fGeom;    //! APD geometry (used to know how many pixels we have)
+    MPhotonEvent      *fEvt;     //! Event storing the photon information
+    MPhotonStatistics *fStat;    //! Storing event statistics (needed for the start-time)
+    MPedestalCam      *fRates;   //! Accidental Photon Rates for all pixels
+
+    MParameterD       *fCrosstalkCoeffParam;
+
+    TObjArray fAPDs;             //! Array keeping the necessary number of APDs
+
+    TString fNameGeomCam;        // Name of the geometry container storing the APD gemeotry
+
+    Double_t fFreq;              // Frequency of random phtons which hit the APDs
+
+    Int_t fType;
+
+    Int_t   fNumCells;           // Number of cells along one side
+    Float_t fCrosstalkCoeff;     // Crosstalk coefficient (P form the formula)
+    Float_t fDeadTime;           // Single cell dead time in nano-seconds
+    Float_t fRecoveryTime;       // Single cell recovery time in nano-seconds
+    Float_t fAfterpulseProb1;    // Early afterpulse probability
+    Float_t fAfterpulseProb2;    // Late afterpulse probability
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSimAPD(const char *name=NULL, const char *title=NULL);
+
+    void SetNameGeomCam(const char *name="MGeomCam") { fNameGeomCam = name; }
+    void SetFreq(Float_t f) { fFreq=f; }
+
+    ClassDef(MSimAPD, 0) // Task to simulate the detection behaviour of APDs
+};
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimBundlePhotons.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimBundlePhotons.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimBundlePhotons.cc	(revision 17960)
@@ -0,0 +1,212 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimBundlePhotons
+//
+// This task sets a new tag (index) for all photons in a list MPhotonEvent
+// based on a look-up table.
+//
+// Input:
+//  MPhotonEvent
+//  MPhotonStatistics
+//
+// Output
+//  MPhotonEvent
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimBundlePhotons.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayI.h"
+
+#include "MParList.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+ClassImp(MSimBundlePhotons);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimBundlePhotons::MSimBundlePhotons(const char* name, const char *title)
+: fEvt(0), fStat(0)//, fFileName("mreflector/dwarf-apdmap.txt")
+{
+    fName  = name  ? name  : "MSimBundlePhotons";
+    fTitle = title ? title : "Task to bundle (re-index) photons according to a look-up table";
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the needed containers and read the oruting table.
+//
+Int_t MSimBundlePhotons::PreProcess(MParList *pList)
+{
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fStat = (MPhotonStatistics*)pList->FindObject("MPhotonStatistics");
+    if (!fStat)
+    {
+        *fLog << err << "MPhotonStatistics not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fFileName.IsNull())
+        return kSKIP;
+
+    // Read the look-up table
+    fLut.Delete();
+    if (!fFileName.IsNull() && fLut.ReadFile(fFileName)<0)
+        return kFALSE;
+
+    // If the table is empty remove this task from the tasklist
+    if (fLut.IsEmpty())
+    {
+        *fLog << inf << "Look-up table to bundle photons empty... skipping." << endl;
+        return kSKIP;
+    }
+
+    // Now invert the tablee. Otherwise we have to do a lot of
+    // searching for every index.
+    fLut.Invert();
+
+    // Make sure that each line has exactly one row
+    if (!fLut.HasConstantLength() && fLut.GetMaxEntries()!=1)
+    {
+        *fLog << err << fFileName << " wrongly formatted." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Using look-up table from " << fFileName << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Re-index all photons according to the look-up table.
+//
+Int_t MSimBundlePhotons::Process()
+{
+    // Make sure that we don't get a seg-fault
+    /*
+    if (fStat->GetMaxIndex()>=fLut.GetEntriesFast())
+    {
+        *fLog << err;
+        *fLog << "ERROR - MSimBundlePhotons::Process: Maximum pixel index stored" << endl;
+        *fLog << "        in tag of MPhotonData exceeds the look-up table length." << endl;
+        return kERROR;
+    }*/
+
+    // FIXME: Add a range check comparing the min and max tag with
+    // the number of entries in the routing table
+
+    // Get total number of photons
+    const Int_t num = fEvt->GetNumPhotons();
+
+    // If there are no photons we can do nothing
+    if (num==0)
+        return kTRUE;
+
+    // Get maximum index allowed
+    const Int_t max = fLut.GetEntriesFast();
+
+    // Initialize a counter for the final number of photons.
+    Int_t cnt=0;
+
+    // Loop over all photons
+    for (Int_t i=0; i<num; i++)
+    {
+        // Get i-th photon from array
+        MPhotonData &ph = (*fEvt)[i];
+
+        // Get pixel index (tag) from photon
+        const Int_t tag = ph.GetTag();
+
+        // Check if the photon was tagged at all and
+        // whether the corresponding lut entry exists
+        if (tag<0 || tag>=max)
+            continue;
+
+        // Get the routing assigned to this index
+        const MArrayI &row = fLut.GetRow(tag);
+
+        // Sanity check: Check if we were routed to a
+        // valid entry if not throw away this photon.
+        if (row.GetSize()==0)
+            continue;
+
+        // Get corresponding entry from routing table
+        const Int_t &idx = row[0];
+
+        // Check if we were routed to a valid entry ("not connected")
+        // if not throw away this photon.
+        if (idx<0)
+            continue;
+
+        // Set Tag to new index
+        ph.SetTag(idx);
+
+        // Copy photon to its now position in array and increade counter
+        (*fEvt)[cnt++] = ph;
+    }
+
+    // Shrink the list of photons to its new size
+    fEvt->Shrink(cnt);
+
+    // Set new maximum index (Note, that this is the maximum index
+    // available in the LUT, which does not necessarily correspond
+    // to, e.g., the number of pixels although it should)
+    fStat->SetMaxIndex(fLut.GetMaxIndex());
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FileName: lut.txt
+//
+Int_t MSimBundlePhotons::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FileName", print))
+    {
+        rc = kTRUE;
+        fFileName = GetEnvValue(env, prefix, "FileName", fFileName);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimBundlePhotons.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimBundlePhotons.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimBundlePhotons.h	(revision 17960)
@@ -0,0 +1,40 @@
+#ifndef MARS_MSimBundlePhotons
+#define MARS_MSimBundlePhotons
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MLut
+#include "MLut.h"
+#endif
+
+class MParList;
+class MPhotonEvent;
+class MPhotonStatistics;
+
+class MSimBundlePhotons: public MTask
+{
+private:
+    MPhotonEvent      *fEvt;     //! Event storing the photons
+    MPhotonStatistics *fStat;    //! Event statistics needed for crosschecks
+
+    TString fFileName;           // File to from which to read the lut
+    MLut    fLut;                // Look-up table
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MSimBundlePhotons(const char *name=NULL, const char *title=NULL);
+
+    void SetFileName(const char *name) { fFileName = name; }
+
+    ClassDef(MSimBundlePhotons, 0) // Task to bundle (re-index) photons according to a look-up table
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimCalibrationSignal.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimCalibrationSignal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimCalibrationSignal.cc	(revision 17960)
@@ -0,0 +1,287 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimCalibrationSignal
+//
+// This task is a MRead task which produces events instead of reading them
+// from a file. To be more precise, calibration events are produced.
+// (Note, that pedestal events are also a kind of calibration events).
+//
+// Whether pedestal or calibration events are produced is defined by
+// the RunType stored in MRawRunheader. The number of pixels which are
+// "enlightened" are determined from a MGeomCam.
+//
+//
+//  Input Containers:
+//   fNameGeomCam [MGeomCam]
+//   MRawRunHeader
+//   IntendedPulsePos [MParameterD]
+//
+//  Output Containers:
+//   [MPhotonEvent]
+//   [TriggerPos [MParameterD]]
+//   MPhotonStatistics
+//   MRawEvtHeader
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimCalibrationSignal.h"
+
+#include <TRandom.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParameters.h"
+
+#include "MGeomCam.h"
+#include "MTriggerPattern.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MParSpline.h"
+
+ClassImp(MSimCalibrationSignal);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimCalibrationSignal::MSimCalibrationSignal(const char* name, const char *title)
+    : fParList(0), fGeom(0), fPulse(0), fPulsePos(0), fTrigger(0),
+    fRunHeader(0), fEvtHeader(0),  fEvt(0), fStat(0),
+    fNumEvents(1000), fNumPhotons(5), fTimeJitter(1)
+{
+    fName  = name  ? name  : "MRead";//"MSimCalibrationSignal";
+    fTitle = title ? title : "Task to create a fake signal (derives from MRead)";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check for the needed parameter containers.
+//
+Int_t MSimCalibrationSignal::PreProcess(MParList *pList)
+{
+    fGeom = (MGeomCam*)pList->FindObject(fNameGeomCam, "MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << inf << fNameGeomCam << " [MGeomCam] not found..." << endl;
+
+        fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+        if (!fGeom)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent");
+    if (!fEvt)
+        return kFALSE;
+
+    fTrigger = (MParameterD*)pList->FindCreateObj("MParameterD", "TriggerPos");
+    if (!fTrigger)
+        return kFALSE;
+
+    fStat = (MPhotonStatistics*)pList->FindCreateObj("MPhotonStatistics");
+    if (!fStat)
+        return kFALSE;
+
+    fEvtHeader = (MRawEvtHeader*)pList->FindCreateObj("MRawEvtHeader");
+    if (!fEvtHeader)
+        return kFALSE;
+
+    fPulsePos = (MParameterD*)pList->FindObject("IntendedPulsePos", "MParameterD");
+    if (!fPulsePos)
+    {
+        *fLog << err << "IntendedPulsePos [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPulse = (MParSpline*)pList->FindObject("PulseShape", "MParSpline");
+    if (!fPulse)
+    {
+        *fLog << err << "PulsShape [MParSpline] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    *fLog << all << "Number of Events: " << fNumEvents << endl;
+
+    //
+    // Search for MTaskList
+    //
+    fParList = pList;
+
+    //
+    // A new file has been opened and new headers have been read.
+    //  --> ReInit tasklist
+    //
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit the task-list if this is the first "event from this fake file"
+//
+Bool_t MSimCalibrationSignal::CallReInit()
+{
+    if (GetNumExecutions()!=1)
+        return kTRUE;
+
+    MTask *tlist = (MTask*)fParList->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << err << dbginf << "MTaskList not found... abort." << endl;
+        return kFALSE;
+    }
+
+    // FIXME: Is there a way to write them as LAST entry in the file?
+    fRunHeader->SetReadyToSave();
+
+    return tlist->ReInit(fParList);
+}
+
+// --------------------------------------------------------------------------
+//
+// Produce the events.
+//
+Int_t MSimCalibrationSignal::Process()
+{
+    if (GetNumExecutions()>fNumEvents)
+        return kFALSE;
+
+    if (!CallReInit())
+        return kERROR;
+
+    Int_t cnt = 0;
+    if (fRunHeader->IsCalibrationRun())
+    {
+        for (UInt_t idx=0; idx<fGeom->GetNumPixels(); idx++)
+        {
+            // FIXME: Scale number of photons with the pixel size!
+            const Int_t num = gRandom->Poisson(fNumPhotons);
+
+            // FIXME: How does the distribution look like? Poissonian?
+            for (Int_t i=0; i<num; i++)
+            {
+                MPhotonData &ph = fEvt->Add(cnt++);
+
+                // FIMXE: Is this the correct distribution
+                const Float_t tm = gRandom->Gaus(0, fTimeJitter);
+
+                ph.SetPrimary(MMcEvtBasic::kArtificial);
+                ph.SetTag(idx);
+                ph.SetWeight();
+                ph.SetTime(tm);
+            }
+        }
+    }
+
+    fEvt->Shrink(cnt);
+    fEvt->Sort(kTRUE);
+
+    // ------------ FIMXE: Move somewhere else? -------------
+    // -------------------- MSimGeomCam ---------------------
+
+    // =====> Move to MSimReadoutWindow ?
+
+    const Double_t freq = fRunHeader->GetFreqSampling()/1000.;
+
+    // We add an additional sample at the end to support a possible shift
+    // of the start time of the first event by 0 to 1 sample.
+    const Int_t   ns = fRunHeader->GetNumSamplesHiGain()+1;
+
+    // Length (ns), Pulse position (Units ns)
+    const Float_t pp = fPulsePos->GetVal();
+    const Float_t pw = fPulse->GetWidth();
+
+    const Float_t first = cnt>0 ? fEvt->GetFirst()->GetTime() : 0;
+    const Float_t last  = cnt>0 ? fEvt->GetLast()->GetTime()  : ns*freq;
+
+    fStat->SetTime(first-pp-pw, last-pp+pw + ns*freq);
+    fStat->SetMaxIndex(fGeom->GetNumPixels()-1);
+    fStat->SetReadyToSave();
+
+    // FIXME: Jitter! (Own class?)
+    fTrigger->SetVal((pp+pw)*freq);
+    fTrigger->SetReadyToSave();
+
+    // Set trigger pattern according to the trigger type
+    const UInt_t p = fRunHeader->IsCalibrationRun() ? 0x100 : 0x400; 
+    //const UInt_t p = fRunHeader->IsCalibrationRun() ? MTriggerPattern::kCalibration : MTriggerPattern::kPedestal;
+    fEvtHeader->SetTriggerPattern(~(p | (p<<8)));
+    fEvtHeader->SetCalibrationPattern(0/*BIT(16)<<16*/); // CT1 Pulser, see MCalibrationPatternDecode
+    fEvtHeader->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the parameters from the resource file.
+//
+//    NumEvents:   1000
+//    NumPhotons:     5
+//    TimeJitter:     1
+//
+Int_t MSimCalibrationSignal::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumEvents", print))
+    {
+        rc = kTRUE;
+        fNumEvents = GetEnvValue(env, prefix, "NumEvents", (Int_t)fNumEvents);
+    }
+
+    if (IsEnvDefined(env, prefix, "NumPhotons", print))
+    {
+        rc = kTRUE;
+        fNumPhotons = GetEnvValue(env, prefix, "NumPhotons", (Int_t)fNumPhotons);
+    }
+
+    if (IsEnvDefined(env, prefix, "TimeJitter", print))
+    {
+        rc = kTRUE;
+        fTimeJitter = GetEnvValue(env, prefix, "TimeJitter", fTimeJitter);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimCalibrationSignal.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimCalibrationSignal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimCalibrationSignal.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MSimCalibrationSignal
+#define MARS_MSimCalibrationSignal
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MGeomCam;
+class MParList;
+class MParSpline;
+class MPhotonEvent;
+class MPhotonStatistics;
+class MParameterD;
+class MRawRunHeader;
+class MRawEvtHeader;
+
+class MSimCalibrationSignal : public MRead
+{
+private:
+    MParList          *fParList;    //! Store pointer to MParList for initializing ReInit
+    MGeomCam          *fGeom;       //! Camera geometry to know the number of expected pixels
+    MParSpline        *fPulse;      //! Pulse Shape to get pulse width from
+    MParameterD       *fPulsePos;   //! Expected position at which the pulse should be
+    MParameterD       *fTrigger;    //! Position in analog channels at which the triggersignal  is raised
+    MRawRunHeader     *fRunHeader;  //! Digitization window and frequency
+
+    MRawEvtHeader     *fEvtHeader;  //! Event header which is filled by the trigger pattern
+    MPhotonEvent      *fEvt;        //! Photon event into which the new photons are stored
+    MPhotonStatistics *fStat;       //! Photon statistic which is filled
+
+    TString fNameGeomCam;           // Name of the camera geometry
+
+    UInt_t  fNumEvents;             // Number of events to produce
+    UInt_t  fNumPhotons;            // Average number of photons to produce
+    Float_t fTimeJitter;            // Time jitter (sigma)
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+    // MSimCalibrationSignal
+    Bool_t CallReInit();
+
+    //Int_t ReadRouting(const char *fname, TObjArray &arr);
+public:
+    MSimCalibrationSignal(const char *name=NULL, const char *title=NULL);
+
+    void SetNameGeomCam(const char *name="MGeomCam") { fNameGeomCam = name; }
+
+    UInt_t  GetEntries() { return fNumEvents; }
+    TString GetFullFileName() const { return "cer000001"; }
+    //virtual Bool_t  Rewind();
+
+    ClassDef(MSimCalibrationSignal, 0) // Task to create a fake signal (derives from MRead)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimCamera.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimCamera.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimCamera.cc	(revision 17960)
@@ -0,0 +1,460 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@phys.ethz.ch>
+!
+!   Copyright: CheObs Software Development, 2000-2013
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimCamera
+//
+//  This task initializes the analog channels with analog noise and simulated
+//  the analog pulses from the photon signal.
+//
+//  Input Containers:
+//   MPhotonEvent
+//   MPhotonStatistics
+//   MRawRunHeader
+//
+//  Output Containers:
+//   MAnalogChannels
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimCamera.h"
+
+#include <TF1.h>
+#include <TRandom.h>            // Needed for TRandom
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTruePhotonsPerPixelCont.h"
+
+#include "MSpline3.h"
+#include "MParSpline.h"
+
+#include "MParList.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MAnalogSignal.h"
+#include "MAnalogChannels.h"
+
+#include "MParameters.h"
+
+#include "MMcEvt.hxx"            // To be replaced by a CheObs class
+#include "MRawRunHeader.h"
+
+ClassImp(MSimCamera);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimCamera::MSimCamera(const char* name, const char *title)
+    : fEvt(0), fStat(0), fRunHeader(0), fElectronicNoise(0), fGain(0),
+      fCamera(0), fMcEvt(0),fCrosstalkCoeffParam(0), fSpline(0), fBaselineGain(kFALSE),
+      fDefaultOffset(-1), fDefaultNoise(-1), fDefaultGain(-1), fACFudgeFactor(0),
+      fACTimeConstant(0)
+
+{
+    fName  = name  ? name  : "MSimCamera";
+    fTitle = title ? title : "Task to simulate the electronic noise and to convert photons into pulses";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the necessayr parameter containers.
+// Setup spline for pulse shape.
+//
+Int_t MSimCamera::PreProcess(MParList *pList)
+{
+    fMcEvt = (MMcEvt*)pList->FindCreateObj("MMcEvt");
+    if (!fMcEvt)
+        return kFALSE;
+
+    fCamera = (MAnalogChannels*)pList->FindCreateObj("MAnalogChannels");
+    if (!fCamera)
+        return kFALSE;
+
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fStat = (MPhotonStatistics*)pList->FindObject("MPhotonStatistics");
+    if (!fStat)
+    {
+        *fLog << err << "MPhotonStatistics not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunHeader = (MRawRunHeader *)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+/*
+    fPulsePos = (MParameterD*)pList->FindObject("IntendedPulsePos", "MParameterD");
+    if (!fPulsePos)
+    {
+        *fLog << err << "IntendedPulsePos [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+ */
+
+    // Create it here to make sure that MGeomApply will set the correct size
+    fElectronicNoise = (MPedestalCam*)pList->FindCreateObj("MPedestalCam", "ElectronicNoise");
+    if (!fElectronicNoise)
+        return kFALSE;
+
+    fGain = (MPedestalCam*)pList->FindCreateObj("MPedestalCam", "Gain");
+    if (!fGain)
+        return kFALSE;
+
+    fAccidentalPhotons = (MPedestalCam*)pList->FindObject("AccidentalPhotonRates","MPedestalCam");
+    if(!fAccidentalPhotons)
+    {
+        *fLog << err << "AccidentalPhotonRates [MPedestalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCrosstalkCoeffParam = (MParameterD*)pList->FindCreateObj("MParameterD","CrosstalkCoeffParam");
+    if (!fCrosstalkCoeffParam)
+    {
+        *fLog << err << "CrosstalkCoeffParam [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTruePhotons = (MTruePhotonsPerPixelCont*)pList->FindCreateObj("MTruePhotonsPerPixelCont");
+    if (!fTruePhotons)
+    {
+        *fLog << err << "MTruePhotonsPerPixelCont not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    MParSpline *pulse = (MParSpline*)pList->FindObject("PulseShape", "MParSpline");
+    if (!pulse)
+    {
+        *fLog << err << "PulseShape [MParSpline] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+//    if (fRunHeader->GetFreqSampling()!=1000)
+//    {
+//        *fLog << err  << "ERROR - Sampling frequencies others than 1GHz are not yet supported." << endl;
+//        *fLog << warn << "FIXME - SCALE MPulsShape WITH THE SAMPLING FREQUENCY." << endl;
+//        return kFALSE;
+//    }
+
+    fSpline = pulse->GetSpline();
+    if (!fSpline)
+    {
+        *fLog << err << "No spline initialized." << endl;
+        return kFALSE;
+    }
+
+    // ---------------- Information output ----------------------
+
+    if (fBaselineGain)
+        *fLog << inf << "Gain is also applied to the electronic noise." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FIXME: For now this is a workaround to set a baseline and the
+// electronic (guassian noise)
+//
+Bool_t MSimCamera::ReInit(MParList *plist)
+{
+    for (int i=0; i<fElectronicNoise->GetSize(); i++)
+    {
+        MPedestalPix &ped = (*fElectronicNoise)[i];
+        ped.SetPedestal(fDefaultOffset);
+        if (fDefaultNoise>0)
+            ped.SetPedestalRms(fDefaultNoise);
+
+        ped.SetPedestalABoffset(0);
+        ped.SetNumEvents(0);
+
+
+        MPedestalPix &gain = (*fGain)[i];
+        if (fDefaultGain>0)
+            gain.SetPedestal(fDefaultGain);
+
+        gain.SetPedestalRms(0);
+        gain.SetPedestalABoffset(0);
+        gain.SetNumEvents(0);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// fStat->GetMaxIndex must return the maximum index possible
+// (equiv. number of pixels) not just the maximum index stored!
+//
+Int_t MSimCamera::Process()
+{
+    // Calculate start time, end time and corresponding number of samples
+    const Double_t freq = fRunHeader->GetFreqSampling()/1000.;
+
+    // FIXME: Should we use a higher sampling here?
+
+    const Double_t start = fStat->GetTimeFirst()*freq;
+    const Double_t end   = fStat->GetTimeLast() *freq;
+
+    const UInt_t   nlen  = TMath::CeilNint(end-start);
+
+    // Get number of pixels/channels
+    const UInt_t npix = fStat->GetMaxIndex()+1;
+
+    if (npix>(UInt_t)fElectronicNoise->GetSize())
+    {
+        *fLog << err << "ERROR - More indices (" << npix << ") ";
+        *fLog << "assigned than existing in camera (";
+        *fLog << fElectronicNoise->GetSize() << ")!" << endl;
+        return kERROR;
+    }
+
+    const Double_t pl = fSpline->GetXmin()*freq;
+    const Double_t pr = fSpline->GetXmax()*freq;
+
+    // Init the arrays and set the range which will contain valid data
+    fCamera->Init(npix, nlen);
+    fCamera->SetValidRange(TMath::FloorNint(pr), TMath::CeilNint(nlen+pl));
+
+    // Add electronic noise to empty channels
+    for (UInt_t i=0; i<npix; i++)
+    {
+        const MPedestalPix &pix = (*fElectronicNoise)[i];
+
+        const Double_t val = pix.GetPedestal();
+        const Double_t rms = pix.GetPedestalRms();
+
+        // FTemme: Implementation of AC-coupling:
+        // to calculate the value of the accoupling per slice I use the
+        // following equation:
+        // accouplingPerSlice = accidentalPhotonRate * (1 + crossTalkProb)
+        //       * areaOfOnePulse / samplingRate;
+        // Therefore I need the following variables
+        // Double_t accidentalPhotonRate; // [MHz]
+        // Float_t crossTalkProb;         // [1]
+        // Double_t areaOfOnePulse;       // [ADC-Counts * s]
+        // Double_t samplingRate;         // [slices * MHz]
+
+        // The accidental photon rate is stored in GHz, so we have to multiply
+        // with 1E3 to get MHz:
+        const MPedestalPix &accPhoPix = (*fAccidentalPhotons)[i];
+
+        const Double_t accidentalPhotonRate = accPhoPix.GetPedestal() * 1e3; //[MHz]
+
+        Double_t currentAccidentalPhotonRate = accidentalPhotonRate;
+        if (fACTimeConstant!=0)
+        {
+            const Double_t accidentalPhotons      = fACTimeConstant * accidentalPhotonRate;
+            const Double_t sigmaAccidentalPhotons = TMath::Sqrt(accidentalPhotons);
+
+            const Double_t gaus = gRandom->Gaus(accidentalPhotons,sigmaAccidentalPhotons);
+
+            currentAccidentalPhotonRate = gaus / fACTimeConstant;
+        }
+
+        // Get the CrosstalkCoefficient Parameter
+        const Double_t crossTalkProb = fCrosstalkCoeffParam->GetVal();
+
+        // To get the area of one Pulse, I only need to calculate the Integral
+        // of the Pulse Shape, which is stored in fSpline. Because the spline is
+        // normalized to a maximal amplitude of 1.0, I had to multiply it with
+        // the Default gain [ADC-Counts * s]
+        const Double_t areaOfOnePulse = fSpline->Integral() * fDefaultGain;
+
+        // The sampling rate I get from the RunHeader:
+        const Double_t samplingRate = fRunHeader->GetFreqSampling(); // [slices * MHz]
+
+        const Double_t accouplingPerSlice = currentAccidentalPhotonRate
+            * (1 + crossTalkProb + fACFudgeFactor)
+            * areaOfOnePulse / samplingRate;
+
+        // The accoupling is substracted from the timeline by decreasing the
+        // mean of the gaussian noise which is added
+
+        if (!fBaselineGain)
+        {
+            (*fCamera)[i].AddGaussianNoise(rms, val - accouplingPerSlice);
+            continue;
+        }
+        // Sorry, the name "pedestal" is misleading here
+        // FIXME: Simulate gain fluctuations
+        const Double_t gain = (*fGain)[i].GetPedestal();
+
+        // FIXME: We might add the base line here already.
+        // FIXME: How stable is the offset?
+        // FIXME: Should we write a container AppliedGain for MSImTrigger?
+
+        (*fCamera)[i].AddGaussianNoise(rms*gain, (val - accouplingPerSlice)*gain);
+    }
+
+    // FIXME: Simulate correlations with neighboring pixels
+
+    const Int_t num = fEvt->GetNumPhotons();
+
+    // A random shift, uniformely distributed within one slice, to make sure that
+    // the first photon is not always aligned identically with a sample edge.
+    // FIXME: Make it switchable
+    const Float_t rndm = gRandom->Uniform();
+
+    // FIXME: Shell we add a random shift of [0,1] samples per channel?
+    //        Or maybe per channel and run?
+
+    Double_t tot = 0;
+
+    for (int i=0 ; i<1440 ; i++)
+    {
+        (*fTruePhotons->cherenkov_photons_weight)[i] = 0;
+        (*fTruePhotons->cherenkov_photons_number)[i] = 0;
+        (*fTruePhotons->cherenkov_arrival_time_mean)[i] = 0;
+        (*fTruePhotons->cherenkov_arrival_time_variance)[i] = 0;
+        (*fTruePhotons->muon_cherenkov_photons_weight)[i] = 0;
+        (*fTruePhotons->muon_cherenkov_photons_number)[i] = 0;
+        (*fTruePhotons->cherenkov_arrival_time_min)[i] = 10000;
+        (*fTruePhotons->cherenkov_arrival_time_max)[i] = 0;
+        (*fTruePhotons->noise_photons_weight)[i] = 0;
+    }
+
+    // Simulate pulses
+    for (Int_t i=0; i<num; i++)
+    {
+        const MPhotonData &ph = (*fEvt)[i];
+
+        const UInt_t   idx = ph.GetTag();
+        const Double_t t   = (ph.GetTime()-fStat->GetTimeFirst())*freq+rndm;// - fSpline->GetXmin();
+
+        // FIXME: Time jitter?
+        // FIXME: Add additional routing here?
+        // FIMXE: How stable is the gain?
+
+        if (ph.GetPrimary()!=MMcEvt::kNightSky && ph.GetPrimary()!=MMcEvt::kArtificial)
+        {
+            tot += ph.GetWeight();
+            (*fTruePhotons->cherenkov_photons_weight)[idx] += ph.GetWeight();
+            (*fTruePhotons->cherenkov_photons_number)[idx] += 1;
+
+            (*fTruePhotons->cherenkov_arrival_time_mean)[idx] += t;
+            (*fTruePhotons->cherenkov_arrival_time_variance)[idx] += t*t;
+
+            if (ph.GetPrimary()==MMcEvt::kMUON)
+            {
+                (*fTruePhotons->muon_cherenkov_photons_weight)[idx] += ph.GetWeight();
+                (*fTruePhotons->muon_cherenkov_photons_number)[idx] += 1;
+            }
+
+            // find min
+            if (t < (*fTruePhotons->cherenkov_arrival_time_min)[idx] )
+            {
+                (*fTruePhotons->cherenkov_arrival_time_min)[idx] = t;
+            }
+            // find max
+            if (t > (*fTruePhotons->cherenkov_arrival_time_max)[idx] )
+            {
+               (*fTruePhotons->cherenkov_arrival_time_max)[idx] = t;
+            }
+        }
+        else
+        {
+            (*fTruePhotons->noise_photons_weight)[idx] += ph.GetWeight();
+        }
+
+        // Sorry, the name "pedestal" is misleading here
+        // FIXME: Simulate gain fluctuations
+        const Double_t gain = (*fGain)[idx].GetPedestal();
+
+        // === FIXME === FIXME === FIXME === Frequency!!!!
+        (*fCamera)[idx].AddPulse(*fSpline, t, ph.GetWeight()*gain);
+    }
+
+    for (unsigned int i=0 ; i < 1440 ; i++)
+    {
+        float number = (*fTruePhotons->cherenkov_photons_number)[i];
+        (*fTruePhotons->cherenkov_arrival_time_mean)[i] /= number;
+        float mean = (*fTruePhotons->cherenkov_arrival_time_mean)[i];
+        float sum_tt = (*fTruePhotons->cherenkov_arrival_time_variance)[i];
+        (*fTruePhotons->cherenkov_arrival_time_variance)[i] = (sum_tt / number - mean*mean) /(number - 1);
+    }
+
+    fMcEvt->SetPhotElfromShower(TMath::Nint(tot));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// BaselineGain: Off
+//
+Int_t MSimCamera::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "BaselineGain", print))
+    {
+        rc = kTRUE;
+        fBaselineGain = GetEnvValue(env, prefix, "BaselineGain", fBaselineGain);
+    }
+
+    if (IsEnvDefined(env, prefix, "DefaultOffset", print))
+    {
+        rc = kTRUE;
+        fDefaultOffset = GetEnvValue(env, prefix, "DefaultOffset", fDefaultOffset);
+    }
+    if (IsEnvDefined(env, prefix, "DefaultNoise", print))
+    {
+        rc = kTRUE;
+        fDefaultNoise = GetEnvValue(env, prefix, "DefaultNoise", fDefaultNoise);
+    }
+    if (IsEnvDefined(env, prefix, "DefaultGain", print))
+    {
+        rc = kTRUE;
+        fDefaultGain = GetEnvValue(env, prefix, "DefaultGain", fDefaultGain);
+    }
+    if (IsEnvDefined(env, prefix, "ACFudgeFactor", print))
+    {
+        rc = kTRUE;
+        fACFudgeFactor = GetEnvValue(env, prefix, "ACFudgeFactor", fACFudgeFactor);
+    }
+    if (IsEnvDefined(env, prefix, "ACTimeConstant", print))
+    {
+        rc = kTRUE;
+        fACTimeConstant = GetEnvValue(env, prefix, "ACTimeConstant", fACTimeConstant);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimCamera.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimCamera.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimCamera.h	(revision 17960)
@@ -0,0 +1,65 @@
+#ifndef MARS_MSimCamera
+#define MARS_MSimCamera
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#include "MArrayF.h"
+
+class MMcEvt;
+class MParList;
+class MPhotonEvent;
+class MPhotonStatistics;
+class MRawRunHeader;
+class MAnalogChannels;
+class MPedestalCam;
+class MArrayF;
+class MTruePhotonsPerPixelCont;
+
+class MSpline3;
+class MParameterD;
+
+class MSimCamera : public MTask
+{
+private:
+    MPhotonEvent      *fEvt;             //! Event stroing the photons
+    MPhotonStatistics *fStat;            //! Valid time range of the phootn event
+    MRawRunHeader     *fRunHeader;       //! Sampling frequency
+    MPedestalCam      *fElectronicNoise; //! Electronic noise (baseline and rms)
+    MPedestalCam      *fGain;            //! Electronic noise (baseline and rms)
+    MPedestalCam      *fAccidentalPhotons;//! Accidental photon rates
+
+    MAnalogChannels   *fCamera;          //! Output of the analog signals
+    MMcEvt            *fMcEvt;           //! For information stored in MMcEvt
+
+    MParameterD       *fCrosstalkCoeffParam;
+    MTruePhotonsPerPixelCont    *fTruePhotons;  //! Container to store the number of photons per pixel
+
+    const MSpline3    *fSpline;          // Pulse Shape    
+
+    Bool_t fBaselineGain;  // Should the gain be applied to baseline and electronic noise?
+
+    Double_t fDefaultOffset;  // Default offset added to all channels
+    Double_t fDefaultNoise;   // Default noise (RMS) added to all samples
+    Double_t fDefaultGain;    // Default gain (multiplication factor to the given/used pulse shape)
+
+    Double_t fACFudgeFactor;
+
+    Double_t fACTimeConstant;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSimCamera(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSimCamera, 0) // Task to simulate the electronic noise and to convert photons into pulses
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimExcessNoise.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimExcessNoise.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimExcessNoise.cc	(revision 17960)
@@ -0,0 +1,121 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimExcessNoise
+//
+//  This task adds the noise (usually signal height, i.e. excess, dependent)
+//  to the photon signal.
+//
+//  Input Containers:
+//   MCorsikaEvent
+//
+//  Output Containers:
+//   MCorsikaEvent
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimExcessNoise.h"
+
+#include <TMath.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+ClassImp(MSimExcessNoise);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimExcessNoise::MSimExcessNoise(const char* name, const char *title)
+: fEvt(0), fExcessNoise(0.2)
+{
+    fName  = name  ? name  : "MSimExcessNoise";
+    fTitle = title ? title : "Task to simulate the excess dependant noise (conversion photon to signal height)";
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the necessary parameter containers.
+//
+Int_t MSimExcessNoise::PreProcess(MParList *pList)
+{
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Excess Noise Factor in use " << fExcessNoise << "%" << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Change the weight of each signal according to the access noise
+//
+Int_t MSimExcessNoise::Process()
+{
+    const UInt_t num = fEvt->GetNumPhotons();
+    for (UInt_t i=0; i<num; i++)
+    {
+        MPhotonData &ph = (*fEvt)[i];
+
+        const Float_t oldw = ph.GetWeight();
+        if (oldw<0)
+            continue;
+
+        const Float_t neww = gRandom->Gaus(oldw, fExcessNoise*TMath::Sqrt(oldw));
+        ph.SetWeight(neww);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ExcessNoise: 0.2
+//
+Int_t MSimExcessNoise::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "ExcessNoise", print))
+    {
+        rc = kTRUE;
+        fExcessNoise = GetEnvValue(env, prefix, "ExcessNoise", fExcessNoise);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimExcessNoise.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimExcessNoise.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimExcessNoise.h	(revision 17960)
@@ -0,0 +1,31 @@
+#ifndef MARS_MSimExcessNoise
+#define MARS_MSimExcessNoise
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MPhotonEvent;
+
+class MSimExcessNoise : public MTask
+{
+private:
+    MPhotonEvent *fEvt;     //! Event storing the photons
+
+    Double_t fExcessNoise;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MSimExcessNoise(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSimExcessNoise, 0) // Task to simulate the excess dependant noise (conversion photon to signal height)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimGeomCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimGeomCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimGeomCam.cc	(revision 17960)
@@ -0,0 +1,223 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimGeomCam
+//
+//  This task takes a photon list from a MPhotonEvent and checks which pixel
+// from a MGeomCam is hit. The photons are tagged with the corresponding
+// index.
+//
+// Additionally (and provisionally) it also calculates the photon event
+// statistics.
+//
+//  Input Containers:
+//   MPhotonEvent
+//   fNameGeomCam [MGeomCam]
+//   MRawRunHeader
+//   [IntendedPulsePos [MParameterD]]
+//   [MPulseShape]
+//
+//  Output Containers:
+//   MPhotonStatistics
+//   -/-
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimGeomCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MParameters.h"
+#include "MParSpline.h"
+#include "MRawRunHeader.h"
+
+ClassImp(MSimGeomCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimGeomCam::MSimGeomCam(const char* name, const char *title)
+    : fGeom(0), fEvt(0), fStat(0), fPulsePos(0), fHeader(0), fPulse(0),
+    fNameGeomCam("MGeomCam")
+{
+    fName  = name  ? name  : "MSimGeomCam";
+    fTitle = title ? title : "Task to tag each photon in a MPhotonEvent with a pixel index from a MGeomCam";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the needed parameter containers.
+//
+Int_t MSimGeomCam::PreProcess(MParList *pList)
+{
+    fGeom = (MGeomCam*)pList->FindObject(fNameGeomCam, "MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << inf << fNameGeomCam << " [MGeomCam] not found..." << endl;
+
+        fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+        if (!fGeom)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPulse = (MParSpline*)pList->FindObject("PulseShape", "MParSpline");
+/*
+    if (!fPulse)
+    {
+        *fLog << err << "MPulsShape not found... aborting." << endl;
+        return kFALSE;
+    }
+ */
+    fPulsePos = (MParameterD*)pList->FindObject("IntendedPulsePos", "MParameterD");
+/*
+    if (!fPulsePos)
+    {
+        *fLog << err << "IntendedPulsePos [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+*/
+    fHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fStat = (MPhotonStatistics*)pList->FindCreateObj("MPhotonStatistics");
+    if (!fStat)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+Int_t MSimGeomCam::Process()
+{
+    const Int_t num = fEvt->GetNumPhotons();
+
+    Int_t cnt = 0;
+    for (Int_t i=0; i<num; i++)
+    {
+        MPhotonData &ph = (*fEvt)[i];
+
+        //
+        // sum the photons content in each pixel
+        //
+        for (UInt_t idx=0; idx<fGeom->GetNumPixels(); idx++)
+        {
+            // FIXME: Improve search algorithm (2D Binary search?)
+            // Here we convert the photons from the ceres-coordinate
+            // system which is viewed from the camera to the mirror
+            // into the camera coordinates which are viewed from
+            // the mirror to the camera.
+            // (x on the right, y upwards, right-handed)
+            if (!(*fGeom)[idx].IsInside(-ph.GetPosX()*10, ph.GetPosY()*10))
+                continue;
+
+            ph.SetTag(idx);
+
+            (*fEvt)[cnt++] = ph;
+
+            break;
+        }
+    }
+
+    fEvt->Shrink(cnt);
+    //fEvt->Sort();
+
+    // ------ FIXME: Move somewhere else? MSimCalibrationSignal ------
+/*
+    if (!fEvt->IsSorted())
+    {
+        *fLog << err << "ERROR - MSimGeomCam: MPhotonEvent must be sorted!" << endl;
+        return kERROR;
+    }
+ */
+    const Float_t freq = fHeader->GetFreqSampling()/1000.;
+
+    // We add an additional sample at the end to support a possible shift
+    // of the start time of the first event by 0 to 1 sample.
+    const Int_t   ns   = fHeader->GetNumSamplesHiGain()+1;
+
+    const Float_t first = cnt>0 ? fEvt->GetTimeFirst() :  0;
+    const Float_t last  = cnt>0 ? fEvt->GetTimeLast()  : ns*freq;
+
+    // Length (ns), Pulse position (Units ns)
+    const Float_t pp   = fPulsePos ? fPulsePos->GetVal() : 0;
+    const Float_t pw   = fPulse    ? fPulse->GetWidth()  : 0;
+
+    fStat->SetTimeMedDev(fEvt->GetTimeMedianDev());
+    fStat->SetTime(first-pp-pw, last-pp+pw + ns*freq);
+    fStat->SetLength(last-first);
+    fStat->SetMaxIndex(fGeom->GetNumPixels()-1);
+    fStat->SetReadyToSave();
+
+    // ----------------------------------------------------------------------
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the parameters from the resource file.
+//
+//    NameGeometry: MGeomCamDwarf
+//
+Int_t MSimGeomCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NameGeometry", print))
+    {
+        rc = kTRUE;
+        SetNameGeomCam(GetEnvValue(env, prefix, "NameGeometry", fNameGeomCam));
+        // FIXME: What about setup of this container?
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimGeomCam.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimGeomCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimGeomCam.h	(revision 17960)
@@ -0,0 +1,44 @@
+#ifndef MARS_MSimGeomCam
+#define MARS_MSimGeomCam
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MParList;
+class MPhotonEvent;
+class MPhotonStatistics;
+class MSignalCam;
+class MParameterD;
+class MRawRunHeader;
+class MParSpline;
+
+class MSimGeomCam : public MTask
+{
+private:
+    MGeomCam          *fGeom;     //!
+    MPhotonEvent      *fEvt;      //! Event stroing the photons
+    MPhotonStatistics *fStat;     //!
+    MParameterD       *fPulsePos; //! Intended pulse position in digitization window [ns]
+    MRawRunHeader     *fHeader;   //! Length of digitization window
+    MParSpline        *fPulse;    //!
+
+    TString fNameGeomCam;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+public:
+    MSimGeomCam(const char *name=NULL, const char *title=NULL);
+
+    void SetNameGeomCam(const char *name="MGeomCam") { fNameGeomCam=name; }
+
+    ClassDef(MSimGeomCam, 0) // Task to tag each photon in a MPhotonEvent with a pixel index from a MGeomCam
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimPSF.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimPSF.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimPSF.cc	(revision 17960)
@@ -0,0 +1,124 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimPSF
+//
+//  This task makes a naiv simulation of the psf by smearing out the photons
+//  in a plane (camera plane) by a 2D-Gaussian with fSigma
+//
+//  Input Containers:
+//   MPhotonEvent
+//
+//  Output Containers:
+//   MPhotonEvent
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimPSF.h"
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+ClassImp(MSimPSF);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimPSF::MSimPSF(const char* name, const char *title)
+    : fEvt(0), fSigma(-1)
+{
+    fName  = name  ? name  : "MSimPSF";
+    fTitle = title ? title : "Task to do a naiv simulation of the psf by smearout in the camera plane";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for MPhotonEvent
+//
+Int_t MSimPSF::PreProcess(MParList *pList)
+{
+    if (fSigma<=0)
+        return kSKIP;
+
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Smear out all photons by a gaussian with fSigma
+//
+Int_t MSimPSF::Process()
+{
+    const UInt_t num = fEvt->GetNumPhotons();
+
+    // Loop over all mirrors
+    for (UInt_t i=0; i<num; i++)
+    {
+        // Get i-th photon
+        MPhotonData &ph = (*fEvt)[i];
+
+        // Get random gaussian shift
+        const TVector2 v(gRandom->Gaus(0, fSigma), gRandom->Gaus(0, fSigma));
+
+        // Add random smear out
+        ph.SetPosition(ph.GetPos2()+v);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sigma: 10
+//
+Int_t MSimPSF::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "Sigma", print))
+    {
+        rc = kTRUE;
+        fSigma = GetEnvValue(env, prefix, "Sigma", fSigma);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimPSF.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimPSF.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimPSF.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MSimPSF
+#define MARS_MSimPSF
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MPhotonEvent;
+
+class MSimPSF : public MTask
+{
+private:
+    MPhotonEvent *fEvt;   //! Event stroing the photons
+
+    Double_t      fSigma; //  Gaussian sigma of the smearout
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+
+public:
+    MSimPSF(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSimPSF, 0) // Task to do a naiv simulation of the psf by smearout in the camera plane
+};
+    
+#endif
+
Index: branches/Mars_McMismatchStudy/msimcamera/MSimRandomPhotons.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimRandomPhotons.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimRandomPhotons.cc	(revision 17960)
@@ -0,0 +1,553 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimRandomPhotons
+//
+//  Simulate poissonian photons. Since the distribution of the arrival time
+// differences of these photons is an exonential we can simulate them
+// using exponentially distributed time differences between two consecutive
+// photons.
+//
+// FIXME: We should add the wavelength distribution.
+//
+// The artificial night sky background rate is calculated as follows:
+//
+//  * The photon detection efficiency vs. wavelength of the detector is obtained
+//    from "PhotonDetectionEfficiency" of type "MParSpline"
+//
+//  * The angular acceptance of the light collectors is obtained
+//    from "ConesAngularAcceptance" of type "MParSpline"
+//
+//  * The spectral acceptance of the light collectors is obtained
+//    from "ConesTransmission" of type "MParSpline"
+//
+//  * The reflectivity of the mirrors vs wavelength is obtained
+//    from "MirrorReflectivity" of type "MParSpline"
+//
+// The rate is then calculated as
+//
+//   R = R0 * Ai * f
+//
+// R0 is the night sky background rate as given in Eckart's paper (divided
+// by the wavelength window). Ai the area of the cones acceptance window,
+// f is given as:
+//
+//   f = nm * Min(Ar, sr*d^2)
+//
+// with
+//
+//   nm being the integral of the product of the mirror reflectivity, the cone
+//   transmission and the photon detection efficiency.
+//
+//   d the distance of the focal plane to the mirror
+//
+//   Ar is the total reflective area of the reflector
+//
+//   sr is the effective solid angle corresponding to the integral of the
+//   cones angular acceptance
+//
+// Alternatively, the night-sky background rate can be calculated from
+// a spectrum as given in Fig. 1 (but versus Nanometers) in
+//
+//   Chris R. Benn & Sara L. Ellison La Palma Night-Sky Brightness
+//
+// After proper conversion of the units, the rate of the pixel 0
+// is then calculated by
+//
+//     rate = f * nsb
+//
+// With nsb
+//
+//   nsb = Integral(nsb spectrum * combines efficiencies)
+//
+// and f can be either
+//
+//   Eff. angular acceptance Cones (e.g. 20deg) * Cone-Area (mm^2)
+//   f = sr * A0
+//
+// or
+//
+//   Mirror-Area * Field of view of cones (deg^2)
+//   f = Ar * A0;
+//
+//
+//  Input Containers:
+//   fNameGeomCam [MGeomCam]
+//   MPhotonEvent
+//   MPhotonStatistics
+//   MCorsikaEvtHeader
+//   [MCorsikaRunHeader]
+//
+//  Output Containers:
+//   MPhotonEvent
+//   AccidentalPhotonRate [MPedestalCam]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimRandomPhotons.h"
+
+#include <TRandom.h>
+
+#include "MMath.h"        // RndmExp
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeom.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCorsikaRunHeader.h"
+
+#include "MSpline3.h"
+#include "MParSpline.h"
+#include "MReflector.h"
+
+ClassImp(MSimRandomPhotons);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimRandomPhotons::MSimRandomPhotons(const char* name, const char *title)
+    : fGeom(0), fEvt(0), fStat(0), /*fEvtHeader(0),*/ fRunHeader(0),
+    fRates(0), fSimulateWavelength(kFALSE), fNameGeomCam("MGeomCam"),
+    fFileNameNSB("resmc/night-sky-la-palma.txt")
+{
+    fName  = name  ? name  : "MSimRandomPhotons";
+    fTitle = title ? title : "Simulate possonian photons (like NSB or dark current)";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check for the necessary containers
+//
+Int_t MSimRandomPhotons::PreProcess(MParList *pList)
+{
+    fGeom = (MGeomCam*)pList->FindObject(fNameGeomCam, "MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << inf << fNameGeomCam << " [MGeomCam] not found..." << endl;
+
+        fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+        if (!fGeom)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fStat = (MPhotonStatistics*)pList->FindObject("MPhotonStatistics");
+    if (!fStat)
+    {
+        *fLog << err << "MPhotonStatistics not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRates = (MPedestalCam*)pList->FindCreateObj("MPedestalCam", "AccidentalPhotonRates");
+    if (!fRates)
+        return kFALSE;
+
+    /*
+    fEvtHeader = (MCorsikaEvtHeader*)pList->FindObject("MCorsikaEvtHeader");
+    if (!fEvtHeader)
+    {
+        *fLog << err << "MCorsikaEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }*/
+
+    fRunHeader = (MCorsikaRunHeader*)pList->FindObject("MCorsikaRunHeader");
+    if (fSimulateWavelength && !fRunHeader)
+    {
+        *fLog << err << "MCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    MReflector *r = (MReflector*)pList->FindObject("Reflector", "MReflector");
+    if (!r)
+    {
+        *fLog << err << "Reflector [MReflector] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MParSpline *s1 = (MParSpline*)pList->FindObject("PhotonDetectionEfficiency", "MParSpline");
+    const MParSpline *s2 = (MParSpline*)pList->FindObject("ConesTransmission",         "MParSpline");
+    const MParSpline *s3 = (MParSpline*)pList->FindObject("MirrorReflectivity",        "MParSpline");
+    const MParSpline *s4 = (MParSpline*)pList->FindObject("ConesAngularAcceptance",    "MParSpline");
+
+    // Ensure that all efficiencies are at least defined in the raneg of the
+    // photon detection efficiency. We assume that this is the limiting factor
+    // and has to be zero at both ends.
+    if (s2->GetXmin()>s1->GetXmin())
+    {
+        *fLog << err << "ERROR - ConeTransmission range must be defined down to " << s1->GetXmin() << "nm (PhotonDetectionEffciency)." << endl;
+        return kFALSE;
+    }
+    if (s2->GetXmax()<s1->GetXmax())
+    {
+        *fLog << err << "ERROR - ConeTransmission range must be defined up to " << s1->GetXmax() << "nm (PhotonDetectionEffciency)." << endl;
+        return kFALSE;
+    }
+    if (s3->GetXmin()>s1->GetXmin())
+    {
+        *fLog << err << "ERROR - MirrorReflectivity range must be defined down to " << s1->GetXmin() << "nm (PhotonDetectionEffciency)." << endl;
+        return kFALSE;
+    }
+    if (s3->GetXmax()<s1->GetXmax())
+    {
+        *fLog << err << "ERROR - MirrorReflectivity range must be defined up to " << s1->GetXmax() << "nm (PhotonDetectionEffciency)." << endl;
+        return kFALSE;
+    }
+
+    // If the simulated wavelength range exists and is smaller, reduce the
+    // range to it. Later it is checked that at both edges the transmission
+    // is 0. This must be true in both cases: The simulated wavelength range
+    // exceed the PDE or the PDE range exceeds the simulated waveband.
+    const Float_t wmin = fRunHeader && fRunHeader->GetWavelengthMin()>s1->GetXmin() ? fRunHeader->GetWavelengthMin() : s1->GetXmin();
+    const Float_t wmax = fRunHeader && fRunHeader->GetWavelengthMax()<s1->GetXmax() ? fRunHeader->GetWavelengthMax() : s1->GetXmax();
+
+    const Int_t min = TMath::FloorNint(wmin);
+    const Int_t max = TMath::CeilNint(wmax);
+
+    // Multiply all relevant efficiencies to get the total transmission
+    MParSpline eff;
+    eff.SetFunction("1", max-min, min, max);
+
+    eff.Multiply(*s1->GetSpline());
+    eff.Multiply(*s2->GetSpline());
+    eff.Multiply(*s3->GetSpline());
+
+    // Effectively transmitted wavelength band in the simulated range
+    const Double_t nm = eff.GetSpline()->Integral();
+
+    // Angular acceptance of the cones
+    const Double_t sr = s4 && s4->GetSpline() ? s4->GetSpline()->IntegralSolidAngle() : 1;
+
+    {
+        const Double_t d2   = fGeom->GetCameraDist()*fGeom->GetCameraDist();
+        const Double_t conv = fGeom->GetConvMm2Deg()*TMath::DegToRad();
+        const Double_t f1   = TMath::Min(r->GetA()/1e4, sr*d2) * conv*conv;
+
+        // Rate in GHz / mm^2
+        fScale = fFreqNSB * nm * f1; // [GHz/mm^2] efficiency * m^2 *rad^2 *mm^2
+
+        const Double_t freq0 = fScale*(*fGeom)[0].GetA()*1000;
+
+        *fLog << inf << "Resulting Freq. in " << fNameGeomCam << "[0]: " << Form("%.2f", freq0) << "MHz" << endl;
+
+        // FIXME: Scale with the number of pixels
+        if (freq0>1000)
+        {
+            *fLog << err << "ERROR - Frequency exceeds 1GHz, this might leed to too much memory consumption." << endl;
+            return kFALSE;
+        }
+    }
+
+    if (fFileNameNSB.IsNull())
+        return kTRUE;
+
+    // const MMcRunHeader *mcrunheader = (MMcRunHeader*)pList->FindObject("MMcRunHeader");
+    // Set NumPheFromDNSB
+
+    // # Number of photons from the diffuse NSB (nphe / ns 0.1*0.1 deg^2 239 m^2) and
+    // nsb_mean 0.20
+    // Magic pixel: 0.00885361 deg
+    // dnsbpix = 0.2*50/15
+    // ampl = MMcFadcHeader->GetAmplitud()
+    // sqrt(pedrms*pedrms + dnsbpix*ampl*ampl/ratio)
+
+    // Conversion of the y-axis
+    // ------------------------
+    // Double_t ff = 1;                               // myJy / arcsec^2 per nm
+    // ff *= 1e-6;                                    // Jy   / arcsec^2 per nm
+    // ff *= 3600*3600;                               // Jy   / deg^2
+    // ff *= 1./TMath::DegToRad()/TMath::DegToRad();  // Jy/sr = 1e-26J/s/m^2/Hz/sr
+    // ff *= 1e-26;                                   // J/s/m^2/Hz/sr   per nm
+
+    const Double_t arcsec2rad = TMath::DegToRad()/3600.;
+    const Double_t f = 1e-32 / (arcsec2rad*arcsec2rad);
+
+    // Read night sky background flux from file
+    MParSpline flux;
+    if (!flux.ReadFile(fFileNameNSB))
+        return kFALSE;
+
+    if (flux.GetXmin()>wmin)
+    {
+        *fLog << err << "ERROR - NSB flux from " << fFileNameNSB << " must be defined down to " << wmin << "nm." << endl;
+        return kFALSE;
+    }
+    if (flux.GetXmax()<wmax)
+    {
+        *fLog << err << "ERROR - NSB flux from " << fFileNameNSB << " must be defined up to " << wmax << "nm." << endl;
+        return kFALSE;
+    }
+
+    MParSpline nsb;
+
+    // Normalization to our units,
+    // conversion from energy flux to photon flux
+    nsb.SetFunction(Form("%.12e/(x*TMath::H())", f), max-min, min, max);
+
+    // multiply night sky background flux with normalization
+    nsb.Multiply(*flux.GetSpline());
+
+    // Multiply with the total transmission
+    nsb.Multiply(*eff.GetSpline());
+
+    // Check if the photon flux is zero at both ends of the NSB
+    if (eff.GetSpline()->Eval(min)>1e-5)
+    {
+        *fLog << warn << "WARNING - Total transmission efficiency at ";
+        *fLog << min << "nm is not zero, but " << eff.GetSpline()->Eval(min) << "... abort." << endl;
+    }
+    if (eff.GetSpline()->Eval(max)>1e-5)
+    {
+        *fLog << warn << "WARNING - Total transmission efficiency at ";
+        *fLog << max << "nm is not zero, but " << eff.GetSpline()->Eval(max) << "... abort." << endl;
+    }
+
+    // Check if the photon flux is zero at both ends of the simulated region
+    if (eff.GetSpline()->Eval(wmin)>1e-5)
+    {
+        *fLog << err << "ERROR - Total transmission efficiency at ";
+        *fLog << wmin << "nm is not zero... abort." << endl;
+        *fLog << "        PhotonDetectionEfficency: " << s1->GetSpline()->Eval(wmin) << endl;
+        *fLog << "        ConeTransmission:         " << s2->GetSpline()->Eval(wmin) << endl;
+        *fLog << "        MirrorReflectivity:       " << s3->GetSpline()->Eval(wmin) << endl;
+        *fLog << "        TotalEfficiency:          " << eff.GetSpline()->Eval(wmin) << endl;
+        return kFALSE;
+    }
+    if (eff.GetSpline()->Eval(wmax)>1e-5)
+    {
+        *fLog << err << "ERROR - Total transmission efficiency at ";
+        *fLog << wmax << "nm is not zero... abort." << endl;
+        *fLog << "        PhotonDetectionEfficency: " << s1->GetSpline()->Eval(wmax) << endl;
+        *fLog << "        ConeTransmission:         " << s2->GetSpline()->Eval(wmax) << endl;
+        *fLog << "        MirrorReflectivity:       " << s3->GetSpline()->Eval(wmax) << endl;
+        *fLog << "        TotalEfficiency:          " << eff.GetSpline()->Eval(wmax) << endl;
+        return kFALSE;
+    }
+
+    // Conversion from m to radians
+    const Double_t conv = fGeom->GetConvMm2Deg()*TMath::DegToRad()*1e3;
+
+    // Angular acceptance of the cones
+    //const Double_t sr = s5.GetSpline()->IntegralSolidAngle(); // sr
+    // Absolute reflector area
+    const Double_t Ar = r->GetA()/1e4;                          // m^2
+    // Size of the cone's entrance window
+    const Double_t A0 = (*fGeom)[0].GetA()*1e-6;                // m^2
+
+    // Rate * m^2 * Solid Angle
+    // -------------------------
+
+    // Angular acceptance Cones (e.g. 20deg) * Cone-Area
+    const Double_t f1 = A0 * sr;                // m^2 sr
+
+    // Mirror-Area * Field of view of cones (e.g. 0.1deg)
+    const Double_t f2 = Ar * A0*conv*conv;      // m^2 sr
+
+    // FIXME: Calculate the reflectivity of the bottom by replacing
+    // MirrorReflectivity by bottom reflectivity and reflect
+    // and use it to reflect the difference between f1 and f2
+    // if any.
+
+    // Total NSB rate in MHz per m^2 and sr
+    const Double_t rate = nsb.GetSpline()->Integral() * 1e-6;
+
+    *fLog << inf;
+
+    // Resulting rates as if Razmick's constant had been used
+    // *fLog << 1.75e6/(600-300) * f1 * eff.GetSpline()->Integral() << " MHz" << endl;
+    // *fLog << 1.75e6/(600-300) * f2 * eff.GetSpline()->Integral() << " MHz" << endl;
+
+    *fLog << "Conversion factor Fnu:         " << f  << endl;
+    *fLog << "Total reflective area:         " << Form("%.2f", Ar) << " m" << UTF8::kSquare << endl;
+    *fLog << "Acceptance area of cone 0:     " << Form("%.2f", A0*1e6) << " mm" << UTF8::kSquare << " = ";
+    *fLog << A0*conv*conv << " sr" << endl;
+    *fLog << "Cones angular acceptance:      " << sr << " sr" << endl;
+    *fLog << "ConeArea*ConeSolidAngle (f1):  " << f1 << " m^2 sr" << endl;
+    *fLog << "MirrorArea*ConeSkyAngle (f2):  " << f2 << " m^2 sr" << endl;
+    *fLog << "Effective. transmission:       " << Form("%.1f", nm) << " nm" << endl;
+    *fLog << "NSB freq. in " << fNameGeomCam << "[0] (f1): " << Form("%.2f", rate * f1) << " MHz" << endl;
+    *fLog << "NSB freq. in " << fNameGeomCam << "[0] (f2): " << Form("%.2f", rate * f2) << " MHz" << endl;
+    *fLog << "Using f2." << endl;
+
+    // Scale the rate per mm^2 and to GHz
+    fScale = rate * f2 / (*fGeom)[0].GetA() / 1000;
+
+    // FIXME: Scale with the number of pixels
+    if (rate*f2>1000)
+    {
+        *fLog << err << "ERROR - Frequency exceeds 1GHz, this might leed to too much memory consumption." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Bool_t MSimRandomPhotons::ReInit(MParList *pList)
+{
+    // Overwrite the default set by MGeomApply
+    fRates->Init(*fGeom);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check for the necessary containers
+//
+Int_t MSimRandomPhotons::Process()
+{
+    // Get array from event container
+    // const Int_t num = fEvt->GetNumPhotons();
+    //
+    // Do not produce pure pedestal events!
+    // if (num==0)
+    //    return kTRUE;
+
+    // Get array from event container
+    // FIXME: Use statistics container instead
+    const UInt_t npix = fGeom->GetNumPixels();
+
+    // This is the possible window in which the triggered digitization
+    // may take place.
+    const Double_t start = fStat->GetTimeFirst();
+    const Double_t end   = fStat->GetTimeLast();
+
+    // Loop over all pixels
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        // Scale the rate with the pixel size.
+        const Double_t rate = fFreqFixed + fScale*(*fGeom)[idx].GetA();
+
+        (*fRates)[idx].SetPedestal(rate);
+
+        // Calculate the average distance between two consequtive photons
+        const Double_t avglen = 1./rate;
+
+        // Start producing photons at time "start"
+        Double_t t = start;
+        while (1)
+        {
+            // Get a random time for the photon.
+            // The differences are exponentially distributed.
+            t += MMath::RndmExp(avglen);
+
+            // Check if we reached the end of the useful time window
+            if (t>end)
+                break;
+
+            // Add a new photon
+            // FIXME: SLOW!
+            MPhotonData &ph = fEvt->Add();
+
+            // Set source to NightSky, time to t and tag to pixel index
+            ph.SetPrimary(MMcEvtBasic::kNightSky);
+            ph.SetWeight();
+            ph.SetTime(t);
+            ph.SetTag(idx);
+
+            // fProductionHeight, fPosX, fPosY, fCosU, fCosV (irrelevant)  FIXME: Reset?
+
+            if (fSimulateWavelength)
+            {
+                const Float_t wmin = fRunHeader->GetWavelengthMin();
+                const Float_t wmax = fRunHeader->GetWavelengthMax();
+
+                ph.SetWavelength(TMath::Nint(gRandom->Uniform(wmin, wmax)));
+            }
+        }
+    }
+
+    // Re-sort the photons by time!
+    fEvt->Sort(kTRUE);
+
+    // Update maximum index
+    fStat->SetMaxIndex(npix-1);
+
+    // Shrink
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the parameters from the resource file.
+//
+//    FrequencyFixed: 0.040
+//    FrequencyNSB:   5.8
+//
+// The fixed frequency is given in units fitting the units of the time.
+// Usually the time is given in nanoseconds thus, e.g., 0.040 means 40MHz.
+//
+// The FrequencyNSB is scaled by the area of the pixel in cm^2. Therefore
+// 0.040 would mean 40MHz/cm^2
+//
+Int_t MSimRandomPhotons::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FrequencyFixed", print))
+    {
+        rc = kTRUE;
+        fFreqFixed = GetEnvValue(env, prefix, "FrequencyFixed", fFreqFixed);
+    }
+
+    if (IsEnvDefined(env, prefix, "FrequencyNSB", print))
+    {
+        rc = kTRUE;
+        fFreqNSB = GetEnvValue(env, prefix, "FrequencyNSB", fFreqNSB);
+    }
+
+    if (IsEnvDefined(env, prefix, "FileNameNSB", print))
+    {
+        rc = kTRUE;
+        fFileNameNSB = GetEnvValue(env, prefix, "FileNameNSB", fFileNameNSB);
+    }
+
+    if (IsEnvDefined(env, prefix, "SimulateCherenkovSpectrum", print))
+    {
+        rc = kTRUE;
+        fSimulateWavelength = GetEnvValue(env, prefix, "SimulateCherenkovSpectrum", fSimulateWavelength);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimRandomPhotons.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimRandomPhotons.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimRandomPhotons.h	(revision 17960)
@@ -0,0 +1,55 @@
+#ifndef MARS_MSimRandomPhotons
+#define MARS_MSimRandomPhotons
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MParList;
+class MParSpline;
+class MPhotonEvent;
+class MPhotonStatistics;
+class MCorsikaRunHeader;
+class MPedestalCam;
+
+class MSimRandomPhotons : public MTask
+{
+private:
+    MGeomCam          *fGeom;    //! container with the geometry
+    MPhotonEvent      *fEvt;     //! Event storing the photons
+    MPhotonStatistics *fStat;    //! Container storing evenet statistics
+//    MCorsikaEvtHeader *fEvtHeader;  //! Header storing event information
+    MCorsikaRunHeader *fRunHeader;  //! Header storing run information
+    MPedestalCam      *fRates;   // Random count rate per pixel
+
+    // FIXME: Make this a single number per Pixel/APD
+    Double_t fFreqFixed; // [1/ns]      A fixed frequency per pixel
+    Double_t fFreqNSB;   // [1/ns/cm^2] A frequency depending on area
+
+    Double_t fScale;
+
+    Bool_t fSimulateWavelength;
+
+    TString fNameGeomCam;
+    TString fFileNameNSB;
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+public:
+    MSimRandomPhotons(const char *name=NULL, const char *title=NULL);
+
+    void SetFreq(Float_t fnsb, Float_t fdc) { fFreqNSB=fnsb; fFreqFixed=fdc; }
+
+    void SetNameGeomCam(const char *name="MGeomCam") { fNameGeomCam = name; }
+
+    ClassDef(MSimRandomPhotons, 0) // Simulate possonian photons (like NSB or dark current)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimReadout.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimReadout.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimReadout.cc	(revision 17960)
@@ -0,0 +1,348 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimReadout
+//
+// Task to convert the analog channels into a digital signal. This should
+// simulate the conversion and saturation bahaviour of the FADC/readout
+// system.
+//
+// You can give a conversion factor from the unitx of your analog signal
+// to the units of your adc. This is a fixed factor because it is just
+// a matter of what the meaning of an adc count is, nothing which could
+// jitter or is a real part of the electronics. Such effects should
+// be simulated somewhere else.
+//
+//
+//  Input Containers:
+//   MGeomCam
+//   MAnalogChannels
+//   TriggerPos [MParameterD]
+//   IntendedPulsePos [MParameterD]
+//   MRawRunHeader
+//
+//  Output Containers:
+//   MRawEvtData
+//   MRawEvtHeader
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimReadout.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayI.h"
+
+#include "MParList.h"
+#include "MParameters.h"
+
+#include "MGeomCam.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+
+#include "MAnalogSignal.h"
+#include "MAnalogChannels.h"
+
+ClassImp(MSimReadout);
+
+using namespace std;
+
+
+// ------------------------------------------------------------------------
+//
+// Default constructor
+//
+MSimReadout::MSimReadout(const char* name, const char *title)
+    : fRunHeader(0), fEvtHeader(0), fCamera(0), fPulsePos(0), fTrigger(0), fData(0),
+    fConversionFactor(1)
+{
+    fName  = name  ? name  : "MSimReadout";
+    fTitle = title ? title : "Task to simulate the analog readout (FADCs)";
+}
+
+// ------------------------------------------------------------------------
+//
+// Look for the needed parameter containers.
+// Initialize MRawEvtData from MRawEvtRunHeader.
+//
+Int_t MSimReadout::PreProcess(MParList *pList)
+{
+    fCamera = (MAnalogChannels*)pList->FindObject("MAnalogChannels");
+    if (!fCamera)
+    {
+        *fLog << err << "MAnalogChannels not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTrigger = (MParameterD*)pList->FindObject("TriggerPos", "MParameterD");
+    if (!fTrigger)
+    {
+        *fLog << err << "TriggerPos [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPulsePos = (MParameterD*)pList->FindObject("IntendedPulsePos", "MParameterD");
+    if (!fPulsePos)
+    {
+        *fLog << err << "IntendedPulsePos [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvtHeader = (MRawEvtHeader*)pList->FindCreateObj("MRawEvtHeader");
+    if (!fEvtHeader)
+        return kFALSE;
+
+    fData = (MRawEvtData*)pList->FindCreateObj("MRawEvtData");
+    if (!fData)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Bool_t MSimReadout::ReInit(MParList *plist)
+{
+    MGeomCam *cam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunHeader->InitPixels(cam->GetNumPixels());
+
+    fData->InitRead(fRunHeader);
+    fData->ResetPixels();
+    fData->InitStartCells();
+    fData->SetIndices();
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Convert (digitize) the analog channels into digital (FADC) data.
+//
+Int_t MSimReadout::Process()
+{
+    // Sanity checks
+    if (fData->GetNumLoGainSamples()>0)
+    {
+        *fLog << err << "ERROR - MSimReadout: Lo-gains not implemented yet." << endl;
+        return kERROR;
+    }
+
+    // Make sure that we have not more analog channels than pixels
+    // FIXME: Is this really necessary?
+    if (fCamera->GetNumChannels()>fData->GetNumPixels())
+    {
+        *fLog << err;
+        *fLog << "ERROR - Number of analog channels " << fCamera->GetNumChannels();
+        *fLog << " exceeds number of pixels " << fData->GetNumPixels() << endl;
+        return kERROR;
+    }
+
+    if (fTrigger->GetVal()<0)
+    {
+        *fLog << err << "ERROR - MSimReadout: MSimReadout executed for an event which has no trigger." << endl;
+        return kERROR;
+    }
+
+    // Get the intended pulse position and convert it to slices
+    const Float_t pulpos = fPulsePos->GetVal()*fRunHeader->GetFreqSampling()/1000.;
+
+    // Get trigger position and correct for intended pulse position
+    const Int_t trig = TMath::CeilNint(fTrigger->GetVal()-pulpos);
+
+    // Check if the position is valid
+    if (trig<0)
+    {
+        *fLog << err;
+        *fLog << "ERROR - Trigger position before analog signal." << endl;
+        *fLog << "        Trigger:  " << fTrigger->GetVal() << endl;
+        *fLog << "        PulsePos: " << pulpos << endl;
+        return kERROR;
+    }
+
+    // Get Number of samples in analog channels
+    const Int_t nsamp = fCamera->GetNumSamples();
+
+    // Get number of samples to be digitized
+    const Int_t nslices = fData->GetNumSamples();
+
+    // Check if the whole requested signal can be digitized
+    if (trig+nslices>nsamp)
+    {
+        *fLog << err << "ERROR - Trigger position beyond valid analog signal range." << endl;
+        *fLog << "        Trigger:    " << fTrigger->GetVal() << endl;
+        *fLog << "        PulsePos:   " << pulpos << endl;
+        *fLog << "        SamplesIn:  " << nsamp << endl;
+        *fLog << "        SamplesOut: " << nslices << endl;
+        return kERROR;
+    }
+
+    const Float_t offset    = 0;//128;
+    // FTemme: Don't need this anymore:
+//    const UInt_t  max       = fData->GetMax();
+//    const UInt_t  min       = fData->GetMin();
+
+
+    // FIXME: Take this into account
+//    const UInt_t scale      = 16;
+//    const UInt_t resolution = 12;
+
+    // Digitize into a buffer
+    MArrayI buffer(nslices*fData->GetNumPixels());
+
+    // Loop over all channels/pixels
+    for (UInt_t i=0; i<fCamera->GetNumChannels(); i++)
+    {
+        // Get i-th canalog hannel
+        const MAnalogSignal &sig = (*fCamera)[i];
+
+        // Digitize all slices
+        for (Int_t j=0; j<nslices; j++)
+        {
+
+            Float_t slice = 0;
+            if (j+trig >= (Int_t)sig.GetSize())
+            {
+                // DN: This, IMHO can never happen, since the check in line 205
+                // already took care for this.
+                // DN: But I don't understand why Thomas did this?
+                //      We need to add noise at least ?!
+                slice = offset;
+            }
+            else
+            {
+                // normal case
+
+                // Why do we add 'offset' when it is a hardcoded zero?
+                // And why do we multiply, while this value *may* be changed
+                // by a user, but it should not? Why do we care?
+                // Because we can?
+                slice = sig[j+trig] * fConversionFactor + offset;
+            }
+
+
+            // Saturation in FACT is done as follows:
+            // If the digitized signal is larger than an upper limit 'max'
+            // the ADC does set a special bit! The overflow bit ...
+            // So while we say we have a 12bit ADC ... in fact we sometimes
+            // also use a 13th bit ...
+            // but this does not increase our resolution by a factor of 2!
+
+            // There are different binary formats for signed integers,
+            // however the 'Two's complement' format
+            // http://en.wikipedia.org/wiki/Two%27s_complement
+            // is increadibly common, and this is also what is used by FACTs ADCs.
+
+            // A normal 12bit (two's complement formatted) signed integer
+            // goes from -2048 to +2047 and is coded like this:
+            // from -2048 = 0x800 = 1000.0000.0000
+            // to   +2047 = 0x7FF = 0111.1111.1111
+            //
+            // But on a normal PC we store these 12 bit numbers in a space, that
+            // was designed for 16bit numbers. This is no problem for the positive numbers
+            // 12bit: 0x7FF = 0111.1111.1111 --> 16bit: 0x07FF = 0000.0111.1111.1111
+            // This bit combination is always understood as +2047 .. no problem!
+            // But the negative numbers:
+            // 12bit: 0x800 = 1000.0000.0000 --> 16bit: 0x0800 = 0000.1000.0000.0000
+            // This *would* normally be understood as +2048, because we need to
+            // 'enlarge' the 'sign bit'
+            // so our largest negative number written into a 16bit storage space
+            // should look like this:
+            // 0xF800 = 1111.1000.0000.0000  --> -2048
+
+            // The enlargement of the sign bit is autotically done on the FACT FAD
+            // board already before the data is send to any PC, because we can do it
+            // damn fast on that board, and a PC would need to touch every incoming
+            // data word again....
+            // But now since we have enlarged the 12th bit ... the sign bit into
+            // the space of bits 13,14,15 and 16 ... where did the overflow-bit go?
+            //
+            //  Well .. we still have plenty of bit-combinations, which are normally
+            // forbidden for a 12bit ADC, and these we can use to encode both,
+            // the positive and negative overflow.
+            // we decided to do this:
+            // positive overflow
+            // 0000.1000.0000.0000 --> interpreted by a PC as +2048 and thus out of 12 bit range!
+            // negative underflow
+            // 1111.0111.1111.1111 --> interpreted by a PC as -2049 and thus out of 12 bit range!
+
+            // we will simulate exactly the same behaviour here!
+
+            // max and min can be set, by the user currently ..
+            // but I don't see why this should be possible.
+            Int_t digitized_value = TMath::Nint(slice);
+            if (digitized_value > 2047) // positive overflow
+                buffer[nslices*i + j] = 0x0800; // <-- +2048
+            else if (digitized_value < -2048)
+                buffer[nslices*i + j] = 0xF7FF; // <-- -2049
+            else
+                buffer[nslices*i + j] = digitized_value;
+        }
+    }
+
+    // Set samples as raw-data
+    fData->Set(buffer);
+    fData->SetReadyToSave();
+
+    // Set the trigger/daq event number
+    fEvtHeader->SetDAQEvtNumber(GetNumExecutions());
+    fEvtHeader->SetReadyToSave();
+
+    // FIMXE: This will never be stored correctly :(
+    fRunHeader->SetNumEvents(fRunHeader->GetNumEvents()+1);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the parameters from the resource file.
+//
+//  ConversionFactor: 1
+//
+Int_t MSimReadout::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "ConversionFactor", print))
+    {
+        rc = kTRUE;
+        fConversionFactor = GetEnvValue(env, prefix, "ConversionFactor", fConversionFactor);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimReadout.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimReadout.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimReadout.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MSimReadout
+#define MARS_MSimReadout
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MParameterD;
+class MRawEvtData;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MAnalogChannels;
+
+class MSimReadout : public MTask
+{
+private:
+    MRawRunHeader    *fRunHeader;  //! Digitization window and frequency
+    MRawEvtHeader    *fEvtHeader;  //! Event header which is filled with the event number
+    MAnalogChannels  *fCamera;     //! Analog channes to be read out
+    MParameterD      *fPulsePos;   //! Intended pulse position
+    MParameterD      *fTrigger;    //! Position of trigger in the analog signal
+
+    MRawEvtData      *fData;       //! Digitized FADC signal
+
+    Double_t fConversionFactor;    // Conversion factor (arbitrary) from analog signal to FADC counts
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Bool_t ReInit(MParList *pList);
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+public:
+    MSimReadout(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSimReadout, 0) // Task to simulate the analog readout (FADCs)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimSignalCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimSignalCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimSignalCam.cc	(revision 17960)
@@ -0,0 +1,190 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimSignalCam
+//
+//  This task takes a photon list (MPhotonEvent) and converts it into
+//  a MSignalCam container. Photons with kNightSky as source are not
+//  considered. The arrival time is just the average arrival time
+//  of the photons minus the one of the first.
+//
+//  Input Containers:
+//   MPhotonEvent
+//   MPhotonStatistics
+//   [TriggerPos [MParameterD]]
+//
+//  Output Containers:
+//   MSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MParameters.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+ClassImp(MSimSignalCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimSignalCam::MSimSignalCam(const char* name, const char *title)
+    : fEvt(0), fStat(0), fSignal(0), fTrigger(0)
+{
+    fName  = name  ? name  : "MSimSignalCam";
+    fTitle = title ? title : "Task to convert a tagged MPhotonEvent list into MSignalCam";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the necessary parameter containers
+//
+Int_t MSimSignalCam::PreProcess(MParList *pList)
+{
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fStat = (MPhotonStatistics*)pList->FindObject("MPhotonStatistics");
+    if (!fStat)
+    {
+        *fLog << err << "MPhotonStatistics not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTrigger = (MParameterD*)pList->FindObject("TriggerPos", "MParameterD");
+/*
+    if (!fTrigger)
+    {
+        *fLog << err << "TriggerPos [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+*/
+    fSignal = (MSignalCam*)pList->FindCreateObj("MSignalCam");
+    if (!fSignal)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size, i.e. the number of pixels, from MSignalCam. It has to be
+// preset e.g. by MGeomApply in a preceeding ReInit.
+//
+Bool_t MSimSignalCam::ReInit(MParList *plist)
+{
+    const UInt_t npix = fSignal->GetNumPixels();
+
+    if (npix==0)
+    {
+        *fLog << err << "ERROR - MSignalCam has 0 entries. Presumably MGeomApply::ReInit not done." << endl;
+        return kFALSE;
+    }
+
+    if (fCont.GetSize()!=npix)
+    {
+        fCont.Set(npix);
+        fTime.Set(npix);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over all photons to sum the photons and determine the average
+// arrival time. Write the result into the MSignalCam.
+//
+// Photons from the NSB are ignored.
+//
+Int_t MSimSignalCam::Process()
+{
+    // FIXME: Check the maximum index in GetTag from the statistics container
+    fCont.Reset();
+    fTime.Reset();
+
+    // Loop over all photons in the event
+    const UInt_t num = fEvt->GetNumPhotons();
+    for (UInt_t i=0; i<num; i++)
+    {
+        // Get i-th photon
+        const MPhotonData &ph = (*fEvt)[i];
+
+        // Reject photons from the night sky
+        if (ph.GetPrimary()==MMcEvtBasic::kNightSky || ph.GetPrimary()==MMcEvtBasic::kArtificial)
+            continue;
+
+        // Get tag (must be the index tag!)
+        const Int_t idx = ph.GetTag();
+
+        // Reject untagged photons
+        if (idx<0)
+            continue;
+
+        // Calculate sum of time and photons
+        fCont[idx] += ph.GetWeight();
+        fTime[idx] += ph.GetTime()*ph.GetWeight();
+    }
+
+    // Get time of start point from the statistics container
+    //   FIXME: Should be the real time of the first photon
+
+    // ====> Distance to trigger position! (if TrigPos found!)
+    // What about events with trigger<0?
+    const Float_t trig  = fTrigger && fTrigger->GetVal()>=0 ? fTrigger->GetVal()  : 0;
+    const Float_t first = fStat->GetTimeFirst()+trig;
+
+    // Loop over all pixels and set signal and arrival time.
+    // Set the pixels valid.
+    const UInt_t npix = fSignal->GetNumPixels();
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        MSignalPix &pix = (*fSignal)[idx];
+
+        pix.SetNumPhotons(fCont[idx]); 
+        pix.SetArrivalTime(fCont[idx]<=0 ? -1 : fTime[idx]/fCont[idx]-first);
+        pix.SetRing(fCont[idx]>0); // Used==1, Unused==0
+        pix.SetPixelCore(kFALSE);
+    }
+    fSignal->SetReadyToSave();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimSignalCam.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimSignalCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimSignalCam.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MSimSignalCam
+#define MARS_MSimSignalCam
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MParList;
+class MPhotonEvent;
+class MPhotonStatistics;
+class MSignalCam;
+class MParameterD;
+
+class MSimSignalCam : public MTask
+{
+private:
+    MPhotonEvent      *fEvt;      //! Event containing the photons
+    MPhotonStatistics *fStat;     //! Statistics about the event
+    MSignalCam        *fSignal;   //! Output container
+    MParameterD       *fTrigger;  //! Trigger position w.r.t. analog channels
+
+    MArrayD fCont;   //! Local buffer for contents
+    MArrayD fTime;   //! local buffer for time
+
+    // MParContainer
+    // Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MTask
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *plist);
+    Int_t  Process();
+
+public:
+    MSimSignalCam(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSimSignalCam, 0) // Task to convert a tagged MPhotonEvent list into MSignalCam
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MSimTrigger.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimTrigger.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimTrigger.cc	(revision 17960)
@@ -0,0 +1,844 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimTrigger
+//
+// This task takes the pure analog channels and simulates a trigger
+// electronics.
+//
+// In a first step several channels can be summed together by a look-up table
+// fRouteAC.
+//
+// In a second step from these analog channels the output of a discriminator
+// is calculated using a threshold and optional a fixed digital signal length.
+//
+// The signal length of the digital signal emitted by the discriminator
+// can either be bound to the time the signal is above the threshold
+// defined by fDiscriminatorThreshold if fDigitalSignalLength<0 or set to a
+// fixed length (fDigitalSignalLength>0).
+//
+// With a second look-up table fCoincidenceMap the analog channels are
+// checked for coincidences. The coincidence must at least be of the length
+// defined by fCoincidenceTime. The earliest coincide is then stored as
+// trigger position.
+//
+// If a minimum multiplicity m is given, m signals above threshold
+// in the coincidence patterns are enough to emit a trigger signal.
+//
+//
+// For MAGIC1:
+//  - fDigitalSignalLength between 6ns and 12ns
+//  - fCoincidenceTime between 0.25ns to 1ns
+//
+//
+//  Input Containers:
+//   IntendedPulsePos [MParameterD]
+//   MAnalogChannels
+//   MRawRunHeader
+//
+//  Output Containers:
+//   TriggerPos [MParameterD]
+//   MRawEvtHeader
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimTrigger.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MParameters.h"
+
+#include "MLut.h"
+#include "MArrayI.h"
+
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+
+#include "MAnalogSignal.h"
+#include "MAnalogChannels.h"
+#include "MDigitalSignal.h"
+
+#include "MTriggerPattern.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MSimTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimTrigger::MSimTrigger(const char *name, const char *title)
+    : fCamera(0),
+      fPulsePos(0),
+      fTrigger(0),
+      fRunHeader(0),
+      fEvtHeader(0),
+      fElectronicNoise(0),
+      fGain(0),
+      fDiscriminatorThreshold(-1),
+      fDigitalSignalLength(8),
+      fCoincidenceTime(0.5),
+      fShiftBaseline(kTRUE),
+      fUngainSignal(kTRUE),
+      fSimulateElectronics(kTRUE),
+      fMinMultiplicity(-1),
+      fCableDelay(21),
+      fCableDamping(0.)     // default Damping Set to zero, so users, who do not set
+                            // the CableDamoing in the ceres.rc do not see a difference.
+
+{
+    fName  = name  ? name  : "MSimTrigger";
+    fTitle = title ? title : "Task to simulate trigger electronics";
+}
+
+// --------------------------------------------------------------------------
+//
+// Take two TObjArrays with a collection of digital signals.
+// Every signal from one array is compared with any from the other array.
+// For all signals which overlap and which have an overlap time >gate
+// a new digital signal is created storing start time and length of overlap.
+// They are collected in a newly allocated TObjArray. A pointer to this array
+// is returned.
+//
+// The user gains owenership of the object, i.e., the user is responsible of
+// deleting the memory.
+//
+TObjArray *MSimTrigger::CalcCoincidence(const TObjArray &arr1, const TObjArray &arr2/*, Float_t gate*/) const
+{
+    TObjArray *res = new TObjArray;
+
+    if (arr1.GetEntriesFast()==0 || arr2.GetEntriesFast()==0)
+        return res;
+
+    TIter Next1(&arr1);
+    MDigitalSignal *ttl1 = 0;
+    while ((ttl1=static_cast<MDigitalSignal*>(Next1())))
+    {
+        TIter Next2(&arr2);
+        MDigitalSignal *ttl2 = 0;
+        while ((ttl2=static_cast<MDigitalSignal*>(Next2())))
+        {
+            MDigitalSignal *ttl = new MDigitalSignal(*ttl1, *ttl2);
+            /*
+            if (ttl->GetLength()<=gate)
+            {
+                delete ttl;
+                continue;
+            }
+            */
+            res->Add(ttl);
+        }
+    }
+
+    res->SetOwner();
+
+    return res;
+}
+
+class Edge : public TObject
+{
+private:
+    Double_t fEdge;
+    Int_t    fRising;
+
+public:
+    Edge(Double_t t, Int_t rising) : fEdge(t), fRising(rising) { }
+    Bool_t IsSortable() const { return kTRUE; }
+    Int_t Compare(const TObject *o) const { const Edge *e = static_cast<const Edge*>(o); if (e->fEdge<fEdge) return 1; if (e->fEdge>fEdge) return -1; return 0; }
+
+    Int_t IsRising() const { return fRising; }
+    Double_t GetEdge() const { return fEdge; }
+};
+
+// --------------------------------------------------------------------------
+//
+// Calculate a multiplicity trigger on the given array(s). The idx-array
+// conatins all channels which should be checked for coincidences
+// and the ttls array conatins the arrays with the digital signals.
+//
+// For the windows in which more or euqal than threshold channels have
+// a high signal a new MDigitalSignal is created.  newly allocated
+// array with a collection of these trigger signals is returned.
+//
+TObjArray *MSimTrigger::CalcMinMultiplicity(const MArrayI &idx, const TObjArray &ttls, Int_t threshold) const
+{
+    // Create a new array for the rising and falling edges of the signals
+    TObjArray times;
+    times.SetOwner();
+
+    // Fill the array with edges from all digital signals of all our channels
+    for (UInt_t k=0; k<idx.GetSize(); k++)
+    {
+        TObjArray *arr = static_cast<TObjArray*>(ttls[idx[k]]);
+
+        TIter Next(arr);
+        MDigitalSignal *ttl = 0;
+        while ((ttl=static_cast<MDigitalSignal*>(Next())))
+        {
+            times.Add(new Edge(ttl->GetStart(),  1));
+            times.Add(new Edge(ttl->GetEnd(),   -1));
+        }
+    }
+
+    // Sort them in time
+    times.Sort();
+
+    // Start with no channel active
+    Int_t lvl = 0;
+
+    TObjArray *res = new TObjArray;
+    res->SetOwner();
+
+    // First remove all edges which do not change the status
+    // "below threshold" or "above threshold"
+    for (int i=0; i<times.GetEntriesFast(); i++)
+    {
+        // Get i-th edge
+        const Edge &e = *static_cast<Edge*>(times.UncheckedAt(i));
+
+        // Claculate what the number of active channels after the edge is
+        const Int_t lvl1 = lvl + e.IsRising();
+
+        // Remove edge if number of active channels before and after the
+        // edge lower is lower than the threshold or higher than
+        // the threshold
+        if (lvl+1<threshold || lvl-1>=threshold)
+            delete times.RemoveAt(i);
+
+        // keep the (now) "previous" level
+        lvl = lvl1<0 ? 0 : lvl1;
+    }
+
+    // Remove the empty slots from the array
+    times.Compress();
+
+    //
+    for (int i=0; i<times.GetEntriesFast()-1; i++)
+    {
+        // get the current edge
+        const Edge &e0 = *static_cast<Edge*>(times.UncheckedAt(i));
+
+        // go ahead if this is a falling edge
+        if (e0.IsRising()!=1)
+            continue;
+
+        // get the following edge (must be a falling edge now)
+        const Edge &e1 = *static_cast<Edge*>(times.UncheckedAt(i+1));
+
+        // calculate the length of the digital signal
+        const Double_t len = e1.GetEdge()-e0.GetEdge();
+
+        // Create a digital trigger signal
+        MDigitalSignal *ds = new MDigitalSignal(e0.GetEdge(), len);
+        //ds->SetIndex(lvl);
+        res->Add(ds);
+    }
+
+    return res;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the necessary parameter containers. Read the luts.
+//
+Int_t MSimTrigger::PreProcess(MParList *pList)
+{
+    fTrigger = (MParameterD*)pList->FindCreateObj("MParameterD", "TriggerPos");
+    if (!fTrigger)
+        return kFALSE;
+
+    fPulsePos = (MParameterD*)pList->FindObject("IntendedPulsePos", "MParameterD");
+    if (!fPulsePos)
+    {
+        *fLog << err << "IntendedPulsePos [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCamera = (MAnalogChannels*)pList->FindObject("MAnalogChannels");
+    if (!fCamera)
+    {
+        *fLog << err << "MAnalogChannels not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvtHeader = (MRawEvtHeader*)pList->FindCreateObj("MRawEvtHeader");
+    if (!fEvtHeader)
+        return kFALSE;
+
+    if (!fSimulateElectronics)
+    {
+        *fLog << inf << "Simulation of electronics switched off... first photon will trigger." << endl;
+        return kTRUE;
+    }
+
+    fElectronicNoise = 0;
+    if (fShiftBaseline)
+    {
+        fElectronicNoise = (MPedestalCam*)pList->FindObject("ElectronicNoise", "MPedestalCam");
+        if (!fElectronicNoise)
+        {
+            *fLog << err << "ElectronicNoise [MPedestalCam] not found... aborting." << endl;
+            return kFALSE;
+        }
+        *fLog << inf << "Baseline will be shifted back to 0 for discriminator." << endl;
+    }
+
+    fGain = 0;
+    if (fUngainSignal)
+    {
+        fGain = (MPedestalCam*)pList->FindObject("Gain", "MPedestalCam");
+        if (!fGain)
+        {
+            *fLog << err << "Gain [MPedestalCam] not found... aborting." << endl;
+            return kFALSE;
+        }
+        *fLog << inf << "Discriminator will be multiplied by applied gain." << endl;
+    }
+
+    fRouteAC.Delete();
+    if (!fNameRouteAC.IsNull() && fRouteAC.ReadFile(fNameRouteAC)<0)
+        return kFALSE;
+
+    fCoincidenceMap.Delete();
+    if (!fNameCoincidenceMap.IsNull() && fCoincidenceMap.ReadFile(fNameCoincidenceMap)<0)
+        return kFALSE;
+
+    // ---------------- Consistency checks ----------------------
+
+    if (!fRouteAC.IsEmpty() && !fCoincidenceMap.IsEmpty() &&
+        fCoincidenceMap.GetMaxIndex()>fRouteAC.GetNumRows()-1)
+    {
+        *fLog << err;
+        *fLog << "ERROR - AC routing produces " << fRouteAC.GetNumRows() << " analog channels," << endl;
+        *fLog << "        but the coincidence map expects at least " << fCoincidenceMap.GetMaxIndex()+1 << " channels." << endl;
+        return kERROR;
+    }
+
+//    if (fDiscriminatorThreshold<=0)
+//    {
+//        *fLog << err << "ERROR - Discriminator threshold " << fDiscriminatorThreshold << " invalid." << endl;
+//        return kFALSE;
+//    }
+
+    if (fElectronicNoise && !fRouteAC.IsEmpty() && !fRouteAC.IsDefaultCol())
+    {
+        // FIXME: Apply to analog channels when summing
+        *fLog << warn << "WARNING - A baseline shift doesn't make sense for sum-channels... reset." << endl;
+        fElectronicNoise = 0;
+    }
+
+    if (fGain && !fRouteAC.IsEmpty() && !fRouteAC.IsDefaultCol())
+    {
+        // FIXME: Apply to analog channels when summing
+        *fLog << warn << "WARNING - Ungain doesn't make sense for sum-channels... reset." << endl;
+        fGain = 0;
+    }
+
+
+    // ---------------- Information output ----------------------
+
+    *fLog << inf;
+
+    if (fRouteAC.IsEmpty())
+        *fLog << "Re-routing/summing of analog channels before discriminator switched off." << endl;
+    else
+        *fLog << "Using " << fNameRouteAC << " for re-routing/summing of analog channels before discriminator." << endl;
+
+    if (fCoincidenceMap.IsEmpty() && fMinMultiplicity<=0)
+        *fLog << "No coincidences of digital channels will be checked. Signal-above-threshold trigger applied." << endl;
+    else
+    {
+        *fLog << "Using ";
+        if (fCoincidenceMap.IsEmpty())
+            *fLog << "the whole camera";
+        else
+            *fLog << "patterns from " << fNameCoincidenceMap;
+        *fLog << " to check for ";
+        if (fMinMultiplicity>0)
+            *fLog << fMinMultiplicity << " multiplicity." << endl;
+        else
+            *fLog << "coincidences of the digital channels." << endl;
+        }
+
+    *fLog << "Using discriminator threshold of " << fDiscriminatorThreshold << endl;
+
+    *fLog << "Using fCableDelay " << fCableDelay << endl;
+    *fLog << "Using fCableDamping " << fCableDamping << endl;
+
+    ////////////////////////////////
+    // open some output files for debugging
+//    patch_file.open("/home/fact_opr/patch_file.csv", ios_base::out);
+//    clipped_file.open("/home/fact_opr/clipped_file.csv", ios_base::out);
+//    digital_file.open("/home/fact_opr/digital_file.csv", ios_base::out);
+//    ratescan_file.open("/home/fact_opr/ratescan_file.csv", ios_base::out);
+
+
+
+    return kTRUE;
+}
+
+/*
+class MDigitalChannel : public TObjArray
+{
+private:
+    TObjArray fArray;
+
+public:
+    MDigitalSignal *GetSignal(UInt_t i) { return static_cast<MDigitalSignal*>(fArray[i]); }
+
+};
+*/
+
+#include "MCamEvent.h"
+class MTriggerSignal : public MParContainer, public MCamEvent
+{
+private:
+    TObjArray fSignals;
+
+public:
+    MTriggerSignal() { fSignals.SetOwner(); }
+
+    void Add(MDigitalSignal *signal) { fSignals.Add(signal); }
+
+    MDigitalSignal *GetSignal(UInt_t i) { return static_cast<MDigitalSignal*>(fSignals[i]); }
+
+    void Sort() { fSignals.Sort(); }
+
+    Int_t GetNumSignals() const { return fSignals.GetEntriesFast(); }
+
+    Float_t GetFirstTrigger() const
+    {
+        MDigitalSignal *sig = static_cast<MDigitalSignal*>(fSignals[0]);
+        return sig ? sig->GetStart() : -1;
+    }
+    Int_t GetFirstIndex() const
+    {
+        MDigitalSignal *sig = static_cast<MDigitalSignal*>(fSignals[0]);
+        return sig ? sig->GetIndex() : -1;
+    }
+    Bool_t GetPixelContent(Double_t&, Int_t, const MGeomCam&, Int_t) const
+    {
+        switch (1)
+        {
+        case 1: // yes/no
+        case 2: // first time
+        case 3: // length
+        case 4: // n
+            break;
+        }
+
+        return kTRUE;
+    }
+    void DrawPixelContent(Int_t) const
+    {
+    }
+};
+
+
+void MSimTrigger::SetTrigger(Double_t pos, Int_t idx)
+{
+    // FIXME: Jitter! (Own class?)
+    fTrigger->SetVal(pos);
+    fTrigger->SetReadyToSave();
+
+    // Flag this event as triggered by the lvl1 trigger (FIXME?)
+    fEvtHeader->SetTriggerPattern(pos<0 ? 0 : 4);
+    fEvtHeader->SetNumTrigLvl1((UInt_t)idx);
+    fEvtHeader->SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MSimTrigger::Process()
+{
+    // Invalidate trigger
+    //fTrigger->SetVal(-1);
+    // Calculate the minimum and maximum time for a valid trigger
+    const Double_t freq    = fRunHeader->GetFreqSampling()/1000.;
+    const Float_t  nsamp   = fRunHeader->GetNumSamplesHiGain();
+    const Float_t  pulspos = fPulsePos->GetVal()/freq;
+
+    // Valid range in units of bins
+    const Float_t min = fCamera->GetValidRangeMin()+pulspos;
+    const Float_t max = fCamera->GetValidRangeMax()-(nsamp-pulspos);
+
+    if (!fSimulateElectronics)
+    {
+        SetTrigger(min, -1);
+        return kTRUE;
+    }
+
+    // ================== Simulate channel bundling ====================
+
+    // FIXME: Before we can bundle the channels we have to make a copy
+    //        and simulate clipping
+
+    // Check if routing should be done
+    const Bool_t empty = fRouteAC.IsEmpty();
+
+    // If no channels are summed the number of patches stays the same
+    const UInt_t npatch = empty ? fCamera->GetNumChannels() : fRouteAC.GetEntriesFast();
+
+    // Use the given analog channels as default out. If channels are
+    // summed overwrite with a newly allocated set of analog channels
+    MAnalogChannels *patches = fCamera;
+    MAnalogChannels *raw_patches = fCamera;
+    if (!empty)
+    {
+        // FIXME: Can we add gain and offset here into a new container?
+
+        patches = new MAnalogChannels(npatch, fCamera->GetNumSamples());
+        raw_patches = new MAnalogChannels(npatch, fCamera->GetNumSamples());
+        for (UInt_t patch_id=0; patch_id<npatch; patch_id++)
+        {
+            const MArrayI &row = fRouteAC.GetRow(patch_id);
+            for (UInt_t pxl_in_patch=0; pxl_in_patch<row.GetSize(); pxl_in_patch++)
+            {
+                const UInt_t pixel_id = row[pxl_in_patch];
+
+                // FIXME: Shrinking the mapping table earlier (e.g.
+                //        ReInit) would avoid a lot of if's
+                if (pixel_id<fCamera->GetNumChannels())
+                {
+                    (*raw_patches)[patch_id].AddSignal((*fCamera)[pixel_id]);
+                    (*patches)[patch_id].AddSignal((*fCamera)[pixel_id]);
+                    (*patches)[patch_id].AddSignal((*fCamera)[pixel_id], fCableDelay, fCableDamping);
+                }
+            }
+        }
+    }
+
+    // DN: 20140219 Ratescan:
+    //
+    //
+//    for (UInt_t patch_id=0; patch_id<npatch; patch_id++)
+//    {
+//        MAnalogSignal current_patch = (*raw_patches)[patch_id];
+//        float max = current_patch[0];
+//        for (UInt_t i=1; i<current_patch.GetSize(); i++)
+//        {
+//            if (current_patch[i] > max)
+//            {
+//                max = current_patch[i];
+//            }
+//        }
+//        ratescan_file << max << " ";
+//    }
+//    ratescan_file << endl;
+
+//    // DN 20131108: DEBUGGING:
+//    for (UInt_t patch_id=0; patch_id<npatch; patch_id++)
+//    {
+//        for (UInt_t slice=0; slice<fCamera->GetNumSamples(); slice++)
+//        {
+//            patch_file << (*raw_patches)[patch_id][slice] << "\t";
+//            clipped_file << (*patches)[patch_id][slice] << "\t";
+//        }
+//        patch_file << endl;
+//        clipped_file << endl;
+//    }
+
+
+
+    // FIXME: Write patches
+
+    // ================== Simulate discriminators ====================
+
+    TObjArray ttls(npatch);
+    ttls.SetOwner();
+
+    for (UInt_t i=0; i<npatch; i++)
+    {
+        // FIXME: What if the gain was also allpied to the baseline?
+        const Double_t offset = fElectronicNoise ? (*fElectronicNoise)[i].GetPedestal() : 0;
+        const Double_t gain   = fGain            ? (*fGain)[i].GetPedestal()            : 1;
+        ttls.AddAt(
+                    (*patches)[i].Discriminate(
+                        fDiscriminatorThreshold*gain+offset,                // treshold
+                        Double_t(fCableDelay),                              // start
+                        Double_t(fCamera->GetNumSamples() - fCableDelay),   // end
+                        //fDigitalSignalLength                              // time-over-threshold, or fixed-length?
+                        -1                                                  // -1 = time-over-threshold
+                        ),
+                    i
+                    );
+    }
+
+    // FIXME: Write TTLs!
+
+    // If analog channels had been newly allocated free memmory
+    if (patches!=fCamera)
+        delete patches;
+    if (raw_patches!=fCamera)
+        delete raw_patches;
+
+    // =================== Simulate coincidences ======================
+
+    // If the map is empty we create a one-pixel-coincidence map
+    // FIMXE: This could maybe be accelerated if the Clone can be
+    //        omitted in the loop
+    if (fCoincidenceMap.IsEmpty())
+    {
+        if (fMinMultiplicity>0)
+            fCoincidenceMap.SetDefaultRow(npatch);
+        else
+            fCoincidenceMap.SetDefaultCol(npatch);
+    }
+
+    // Create an array for the individual triggers
+    MTriggerSignal triggers;
+
+    Int_t cnt  = 0;
+    Int_t rmlo = 0;
+    Int_t rmhi = 0;
+
+//    cout << "MSimTrigger::fMinMultiplicity = " << fMinMultiplicity << endl;
+//    cout << "MSimTrigger::fCoincidenceTime = " << fCoincidenceTime << endl;
+//    cout << "fCoincidenceMap.GetEntries() = " << fCoincidenceMap.GetEntries() << endl;
+//    cout << "MSimTrigger::fCableDelay = " << fCableDelay << endl;
+//    cout << "MSimTrigger::fCableDamping = " << fCableDamping << endl;
+//    cout << "min:" << min << endl;
+//    cout << "max:" << max << endl;
+
+    for (int j=0; j<fCoincidenceMap.GetEntries(); j++)
+    {
+        const MArrayI &idx = fCoincidenceMap.GetRow(j);
+
+        TObjArray *arr = 0;
+
+        if (fMinMultiplicity>0)
+        {
+            arr = CalcMinMultiplicity(idx, ttls, fMinMultiplicity);
+        }
+        else
+        {
+            arr = CalcMinMultiplicity(idx, ttls, idx.GetSize());
+            /*
+            // Start with a copy of the first coincidence channel
+            arr = static_cast<TObjArray*>(ttls[idx[0]]->Clone());
+            arr->SetOwner();
+
+            // compare to all other channels in this coincidence patch, one by one
+            for (UInt_t k=1; k<idx.GetSize() && arr->GetEntriesFast()>0; k++)
+            {
+                TObjArray *res = CalcCoincidence(*arr, *static_cast<TObjArray*>(ttls[idx[k]]));//, fCoincidenceTime);
+
+                // Delete the original array and keep the new one
+                delete arr;
+                arr = res;
+            }*/
+        }
+
+        // Count the number of totally emitted coincidence signals
+        cnt += arr->GetEntriesFast();
+
+        // Remove all signals which are not in the valid digitization range
+        // (This is not the digitization window, but the region in which
+        //  the analog channels contain usefull data)
+        // and which are shorter than the defined coincidence gate.
+        TIter Next(arr);
+        MDigitalSignal *ttl = 0;
+        while ((ttl=static_cast<MDigitalSignal*>(Next())))
+        {
+            if (ttl->GetLength()<fCoincidenceTime)
+            {
+                delete arr->Remove(ttl);
+                continue;
+            }
+
+            if (ttl->GetStart()<min)
+            {
+                delete arr->Remove(ttl);
+                rmlo++;
+                continue;
+            }
+            if (ttl->GetStart()>max)
+            {
+                delete arr->Remove(ttl);
+                rmhi++;
+                continue;
+            }
+
+            // Set trigger-channel index to keep this information
+            //ttl->SetIndex(j);
+        }
+
+        // Remove the empty slots
+        arr->Compress();
+
+//        cout << "ttls(j=" << j << "):";
+//        TObjArray *arr2 = static_cast<TObjArray*>(ttls[j]);
+//        TIter Nexty(arr);
+//        MDigitalSignal *ttly = 0;
+//        while ((ttly=static_cast<MDigitalSignal*>(Nexty())))
+//        {
+//            cout << "|"<< ttly->GetStart() << ", " << ttly->GetLength();
+//        }
+//        cout << endl;
+
+
+        // If we have at least one trigger keep the earliest one.
+        // FIXME: The triggers might be ordered in time automatically:
+        //        To be checked!
+        // FIXME: Simulate trigger dead-time!
+        if (arr->GetEntriesFast()>0)
+        {
+            ttl = static_cast<MDigitalSignal*>(arr->RemoveAt(0));
+            // Set trigger-channel index to keep this information
+            ttl->SetIndex(j);
+            triggers.Add(ttl);
+        }
+
+        // delete the allocated space
+        delete arr;
+    }
+
+    // There are usually not enough entries that it is worth to search
+    // for the earliest instead of just sorting and taking the first one
+    //  FIXME: This could be improved if checking for IsSortable
+    //         is omitted
+    triggers.Sort();
+    // FIXME: Store triggers! (+ Reversed pixels?)
+
+    SetTrigger(triggers.GetFirstTrigger(), triggers.GetFirstIndex());
+
+    // No trigger issued. Go on.
+    if (triggers.GetNumSignals()==0)
+    {
+        if (rmlo>0 || rmhi>0)
+            *fLog << inf2 << GetNumExecutions() << ": " << rmlo << "/" << rmhi << " trigger out of valid range. No trigger raised." << endl;
+        return kTRUE;
+    }
+
+    // Number of patches which have triggered out of the total number of
+    // Coincidence signals emitted. (If the total number is higher than
+    // the number of triggers either some triggers had to be removed or
+    // or a patch has emitted more than one trigger signal)
+    // FIXME: inf2?
+    *fLog << inf << GetNumExecutions() << ": ";
+    *fLog << setw(3) << triggers.GetNumSignals() << " triggers left out of ";
+    *fLog << setw(3) << cnt << " (" << rmlo << "/" << rmhi << " trigger out of valid range), T=" << fTrigger->GetVal();
+    *fLog << endl;
+
+    //# Trigger characteristics: gate length (ns), min. overlapping time (ns),
+    //# amplitude and FWHM of (gaussian) single phe response for trigger:
+    //trigger_prop 3.0 0.25 1.0 2.0
+
+    return kTRUE;
+}
+
+Int_t MSimTrigger::PostProcess()
+{
+//    patch_file.close();
+//    clipped_file.close();
+//    digital_file.close();
+//    ratescan_file.close();
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FileNameRouteac:         routeac.txt
+// FileNameCoincidenceMap:  coincidence.txt
+// DiscriminatorTheshold:   3.5
+// DigitalSignalLength:     8
+// CoincidenceTime:         0.5
+// SimulateElectronics:     Yes
+//
+Int_t MSimTrigger::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "FileNameRouteAC", print))
+    {
+        rc = kTRUE;
+        fNameRouteAC = GetEnvValue(env, prefix, "FileNameRouteAC", fNameRouteAC);
+    }
+
+    if (IsEnvDefined(env, prefix, "FileNameCoincidenceMap", print))
+    {
+        rc = kTRUE;
+        fNameCoincidenceMap = GetEnvValue(env, prefix, "FileNameCoincidenceMap", fNameCoincidenceMap);
+    }
+
+    if (IsEnvDefined(env, prefix, "DiscriminatorThreshold", print))
+    {
+        rc = kTRUE;
+        fDiscriminatorThreshold = GetEnvValue(env, prefix, "DiscriminatorThreshold", fDiscriminatorThreshold);
+    }
+
+    if (IsEnvDefined(env, prefix, "DigitalSignalLength", print))
+    {
+        rc = kTRUE;
+        fDigitalSignalLength = GetEnvValue(env, prefix, "DigitalSignalLength", fDigitalSignalLength);
+    }
+
+    if (IsEnvDefined(env, prefix, "CoincidenceTime", print))
+    {
+        rc = kTRUE;
+        fCoincidenceTime = GetEnvValue(env, prefix, "CoincidenceTime", fCoincidenceTime);
+    }
+
+    if (IsEnvDefined(env, prefix, "SimulateElectronics", print))
+    {
+        rc = kTRUE;
+        fSimulateElectronics = GetEnvValue(env, prefix, "SimulateElectronics", fSimulateElectronics);
+    }
+
+    if (IsEnvDefined(env, prefix, "MinMultiplicity", print))
+    {
+        rc = kTRUE;
+        fMinMultiplicity = GetEnvValue(env, prefix, "MinMultiplicity", fMinMultiplicity);
+    }
+
+    if (IsEnvDefined(env, prefix, "CableDelay", print))
+    {
+        rc = kTRUE;
+        fCableDelay = GetEnvValue(env, prefix, "CableDelay", fCableDelay);
+    }
+
+    if (IsEnvDefined(env, prefix, "CableDamping", print))
+    {
+        rc = kTRUE;
+        fCableDamping = GetEnvValue(env, prefix, "CableDamping", fCableDamping);
+    }
+
+
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MSimTrigger.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MSimTrigger.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MSimTrigger.h	(revision 17960)
@@ -0,0 +1,88 @@
+#ifndef MARS_MSimTrigger
+#define MARS_MSimTrigger
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MLut
+#include "MLut.h"
+#endif
+
+#include <fstream>
+
+class MParList;
+class MParameterD;
+class MAnalogChannels;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MPedestalCam;
+
+class MSimTrigger : public MTask
+{
+private:
+    MAnalogChannels *fCamera;           //! The analog input channels
+    MParameterD     *fPulsePos;         //! The intended pulse positon
+    MParameterD     *fTrigger;          //! The trigger position w.r.t. the analog channels
+    MRawRunHeader   *fRunHeader;        //! The run header storing infos about the digitization
+    MRawEvtHeader   *fEvtHeader;        //! The event header storing the trigger information
+    MPedestalCam    *fElectronicNoise;  //! Electronic noise (for baseline correction)
+    MPedestalCam    *fGain;             //! Gain of the pulses
+
+    MLut fRouteAC;                      // Combinination map for the AC channels
+    MLut fCoincidenceMap;               // channels for which digital coincidence is checked
+
+    TString fNameRouteAC;               // Name for the AC routing
+    TString fNameCoincidenceMap;        // Name for the coincidence mape
+
+    Float_t fDiscriminatorThreshold;    // Discriminator threshold
+    Float_t fDigitalSignalLength;       // Length of the output of the discriminator
+    Float_t fCoincidenceTime;           // Minimum coincidence time (gate) [slices]
+
+    Bool_t  fShiftBaseline;             // Shift the baseline back to 0 for the threshold (needs ElectronicNoise [MPedestalCam])
+    Bool_t  fUngainSignal;              // "Remove" the gain from the signal (needs Gain [MPedestalCam])
+    Bool_t  fSimulateElectronics;       // If the electronics is not simulated the trigger is set artificially to the first photon arrived
+
+    Int_t   fMinMultiplicity;           // N out of M
+
+    Int_t   fCableDelay;                // signal runtime on the clipping cable in slices, e.g. 105cm cable = 2*105cm
+                                        // (20cm/ns) = 10.5ns = 21slices @ 2GHz [slices]
+
+    Float_t fCableDamping;              // the signal is damped a bit when reflecting at the end of the cable and is inverted as well.
+                                        // Damping factor in [-1..0]. In short tests by Kai Schennetten it looked like -0.96.
+
+    // debugging
+    std::ofstream patch_file;
+    std::ofstream clipped_file;
+    std::ofstream digital_file;
+    std::ofstream ratescan_file;
+
+
+    // MSimTrigger
+    TObjArray *CalcCoincidence(const TObjArray &arr1, const TObjArray &arr2/*, Float_t gate=0*/) const;
+    TObjArray *CalcMinMultiplicity(const MArrayI &idx, const TObjArray &ttls, Int_t threshold) const;
+    TObjArray *CalcCoincidences(const MArrayI &idx, const TObjArray &ttls) const;
+    void SetTrigger(Double_t pos, Int_t idx);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MSimTrigger(const char *name=NULL, const char *title=NULL);
+
+    void SetNameRouteAC(const char *name) { fNameRouteAC=name; }
+    void SetNameCoincidenceMap(const char *name) { fNameCoincidenceMap=name; }
+
+    void SetDiscriminatorThreshold(Float_t th) { fDiscriminatorThreshold=th; }
+    void SetDigitalSignalLength(Float_t ln) { fDigitalSignalLength=ln; }
+    void SetCoincidenceTime(Float_t tm) { fCoincidenceTime=tm; }
+
+    ClassDef(MSimTrigger, 0) // Task to simulate trigger electronics
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/MTruePhotonsPerPixelCont.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MTruePhotonsPerPixelCont.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MTruePhotonsPerPixelCont.cc	(revision 17960)
@@ -0,0 +1,27 @@
+#include "MTruePhotonsPerPixelCont.h"
+ClassImp(MTruePhotonsPerPixelCont);
+
+MTruePhotonsPerPixelCont::MTruePhotonsPerPixelCont(const char *name, const char *title)
+{
+    cherenkov_photons_weight = new MArrayF(1440);
+    cherenkov_photons_number = new MArrayF(1440);
+    muon_cherenkov_photons_weight = new MArrayF(1440);
+    muon_cherenkov_photons_number = new MArrayF(1440);
+    noise_photons_weight = new MArrayF(1440);
+    cherenkov_arrival_time_mean = new MArrayF(1440);
+    cherenkov_arrival_time_variance = new MArrayF(1440);
+    cherenkov_arrival_time_min = new MArrayF(1440);
+    cherenkov_arrival_time_max = new MArrayF(1440);
+}
+
+MTruePhotonsPerPixelCont::~MTruePhotonsPerPixelCont(){
+    delete cherenkov_photons_weight;
+    delete cherenkov_photons_number;
+    delete muon_cherenkov_photons_weight;
+    delete muon_cherenkov_photons_number;
+    delete noise_photons_weight;
+    delete cherenkov_arrival_time_mean;
+    delete cherenkov_arrival_time_variance;
+    delete cherenkov_arrival_time_min;
+    delete cherenkov_arrival_time_max;
+}
Index: branches/Mars_McMismatchStudy/msimcamera/MTruePhotonsPerPixelCont.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/MTruePhotonsPerPixelCont.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/MTruePhotonsPerPixelCont.h	(revision 17960)
@@ -0,0 +1,41 @@
+#ifndef STUFF_H
+#define STUFF_H
+
+#include "MParContainer.h"
+#include "MArrayF.h"
+
+/*
+ * 
+- sum of heights of all cherenkov photons and their crosstalk pulses
+- number of all cherenkov photons and their crosstalk pulses
+- sum of heights of all cherenkov photons and their crosstalk pulses caused by muons
+- number of all cherenkov photons and their crosstalk pulses caused by muons
+- sum of heights of all other pulses (NSB, DC,Afterpulses) and their crosstalk pulses
+- Mean of the arrivaltimes of the cherenkov photons
+- Rms of the arrivaltimes of the cherenkov photons
+- Median of the arrivaltimes of the cherenkov photons
+- Min of the arrivaltimes of the cherenkov photons
+- Max of the arrivaltimes of the cherenkov photons 
+* */
+
+class MTruePhotonsPerPixelCont : public MParContainer
+{
+public:
+    MArrayF *cherenkov_photons_weight;          // {fits: name=McCherPhotWeight}
+    MArrayF *cherenkov_photons_number;          // {fits: name=McCherPhotNumber}
+    MArrayF *muon_cherenkov_photons_weight;     // {fits: name=McMuonCherPhotWeight}
+    MArrayF *muon_cherenkov_photons_number;     // {fits: name=McMuonCherPhotNumber}
+    MArrayF *noise_photons_weight;              // {fits: name=McNoisePhotWeight}
+    MArrayF *cherenkov_arrival_time_mean;       // {fits: name=McCherArrTimeMean}
+    MArrayF *cherenkov_arrival_time_variance;   // {fits: name=McCherArrTimeVar}
+    MArrayF *cherenkov_arrival_time_min;        // {fits: name=McCherArrTimeMin}
+    MArrayF *cherenkov_arrival_time_max;        // {fits: name=McCherArrTimeMax}
+
+    
+    MTruePhotonsPerPixelCont(const char *name="MTruePhotonsPerPixelCont", const char *title="MTruePhotonsPerPixelCont");
+    ~MTruePhotonsPerPixelCont();
+    
+    ClassDef(MTruePhotonsPerPixelCont, 1) // MTruePhotonsPerPixelCont
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimcamera/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/Makefile	(revision 17960)
@@ -0,0 +1,44 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = SimCamera
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgeom -I../msim -I../msignal -I../mcorsika \
+	   -I../mmc -I../mgui -I../mcalib -I../mraw -I../mfileio -I../melectronics \
+	   -I../mtrigger -I../mpedestal -I../msimreflector
+
+SRCFILES = MSimPSF.cc \
+	   MSimGeomCam.cc \
+	   MSimRandomPhotons.cc \
+	   MSimAPD.cc \
+	   MSimBundlePhotons.cc \
+	   MSimCalibrationSignal.cc \
+	   MSimExcessNoise.cc \
+	   MSimCamera.cc \
+	   MSimTrigger.cc \
+	   MSimReadout.cc \
+           MSimSignalCam.cc \
+           MTruePhotonsPerPixelCont.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/msimcamera/SimCameraIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/SimCameraIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/SimCameraIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/msimcamera/SimCameraLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/msimcamera/SimCameraLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimcamera/SimCameraLinkDef.h	(revision 17960)
@@ -0,0 +1,22 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MSimPSF+;
+#pragma link C++ class MSimGeomCam+;
+#pragma link C++ class MSimRandomPhotons+;
+#pragma link C++ class MSimAPD+;
+#pragma link C++ class MSimExcessNoise+;
+#pragma link C++ class MSimBundlePhotons+;
+#pragma link C++ class MSimSignalCam+;
+
+#pragma link C++ class MSimCamera+;
+#pragma link C++ class MSimTrigger+;
+#pragma link C++ class MSimReadout+;
+#pragma link C++ class MSimCalibrationSignal+;
+
+#pragma link C++ class MTruePhotonsPerPixelCont+;
+
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/MMirror.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirror.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirror.cc	(revision 17960)
@@ -0,0 +1,181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMirror
+//
+// Note, that we could use basic geometry classes instead, but especially
+// CanHit is time critical. So this class is (should be) optimized for
+// execution speed.
+//
+// This base class provides the code to calculate a spherical mirror
+// (ExecuteMirror) and to scatter in a way to get a proper PSF.
+// Furthermore it stored the geometry of a mirror.
+//
+// ------------------------------------------------------------------------
+//
+// Bool_t CanHit(const MQuaternion &p) const;
+//
+//    This is a very rough estimate of whether a photon at a position p
+//    can hit a mirror. The position might be off in z and the photon
+//    still has to follow its trajectory. Nevertheless we can fairly assume
+//    the the way to travel in x/y is pretty small so we can give a rather
+//    good estimate of whether the photon can hit.
+//
+//    Never throw away a photon whihc can hit the mirror!
+//
+// ------------------------------------------------------------------------
+//
+// Bool_t HasHit(const MQuaternion &p) const;
+//
+//    Check if the given position coincides with the mirror. The position
+//    is assumed to be the incident point on the mirror's surface.
+//
+//    The coordinates are in the mirrors coordinate frame.
+//
+//    The action should coincide with what is painted in Paint()
+//
+// ------------------------------------------------------------------------
+//
+// Double_t GetA() const
+//
+//     Return the reflective area of the mirror
+//
+// ------------------------------------------------------------------------
+//
+// Double_t GetMaxR() const
+//
+//     Return the maximum distance of a reflective point from the
+//     mirror center
+//
+// ------------------------------------------------------------------------
+//
+// void Paint(Option_t *opt)
+//
+//    Paint the mirror in x/y.
+//
+//    The graphic should coincide with the action in HasHit
+//
+// ------------------------------------------------------------------------
+//
+// Int_t ReadM(const TObjArray &tok);
+//
+//    Read the mirror's setup from a file. The first eight tokens should be
+//    ignored. (This could be fixed!)
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMirror.h"
+
+#include <TRandom.h>
+
+#include "MLog.h"
+
+#include "MQuaternion.h"
+
+ClassImp(MMirror);
+
+using namespace std;
+
+void MMirror::SetShape(Char_t c)
+{
+    switch (toupper(c))
+    {
+    case 'S':
+        fShape = 0;
+        break;
+
+    case 'P':
+        fShape = 1;
+        break;
+
+    default:
+        fShape = 0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the TVector2 which is the x/y position of the mirror minus
+// q.XYvector/(;
+//
+TVector2 MMirror::operator-(const MQuaternion &q) const
+{
+    return TVector2(X()-q.X(), Y()-q.Y());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the TVector2 which is the difference of this mirror and the
+// given mirror
+//
+TVector2 MMirror::operator-(const MMirror &m) const
+{
+    return TVector2(X()-m.X(), Y()-m.Y());
+}
+
+// --------------------------------------------------------------------------
+//
+// Simulate the PSF. Therefor we smear out the given normal vector
+// with a gaussian.
+//
+// Returns a vector which can be added to the normal vector.
+//
+// FIXME: What is the correct focal distance to be given here?
+//        Can the smearing be imporved?
+//
+TVector3 MMirror::SimPSF(const TVector3 &n, Double_t F, Double_t psf) const
+{
+    //const TVector3 n( x, y, -d)         // Normal vector of the mirror
+    const TVector3 xy(-n.Y(), n.X(), 0);  // Normal vector in x/y plane
+
+    Double_t gx, gy;
+    gRandom->Rannor(gx, gy);         // 2D random Gauss distribution
+
+    psf /= 2;                        // The factor two because of the doubleing of the angle in the reflection
+    psf /= F;                        // Scale the Gauss to the size of the PSF
+    //psf *= n.Z();                  // 
+    psf *= n.Mag();                  // This means that the PSF is measured in the focal distance
+
+    TVector3 dn(gx*psf, gy*psf, 0);  // Instead of psf/F also atan(psf/F) might make sense
+
+    dn.Rotate(-n.Theta(), xy);       // Tilt the gauss-vector to the normal vector
+
+    return dn;  // Return the vector to be added to the normal vector
+}
+
+// --------------------------------------------------------------------------
+//
+void MMirror::Print(Option_t *o) const
+{
+    gLog << fPos.X()  << " " << fPos.Y()  << " " << fPos.Z() << " ";
+    gLog << fNorm.X() << " " << fNorm.Y() << " " << fNorm.Z() << " ";
+    gLog << fFocalLength << " ";
+    if (fSigmaPSF>0)
+        gLog << fSigmaPSF << " ";
+
+    const TString n = ClassName();
+
+    gLog << n(7, n.Length());
+}
Index: branches/Mars_McMismatchStudy/msimreflector/MMirror.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirror.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirror.h	(revision 17960)
@@ -0,0 +1,110 @@
+#ifndef MARS_MMirror
+#define MARS_MMirror
+
+#ifndef ROOT_TRotation
+#include <TRotation.h>
+#endif
+
+class MQuaternion;
+
+class MMirror : public TObject
+{
+    friend void operator/=(MQuaternion &, const MMirror &);
+    friend void operator*=(MQuaternion &, const MMirror &);
+    friend void operator-=(MQuaternion &, const MMirror &);
+    friend void operator+=(MQuaternion &, const MMirror &);
+
+private:
+    TVector3  fPos;
+    TVector3  fNorm;  // faster without
+
+    TRotation fTilt;
+
+    // ----- Spherical mirror data members -----
+    Double_t  fFocalLength;
+    Double_t  fSigmaPSF;
+
+    Int_t fShape; // Spherical=0, Parabolic=1
+
+    //    MMirror *fNeighbors[964];
+
+public:
+    MMirror() : fSigmaPSF(-1), fShape(0)
+    {
+    }
+
+    // ----- Mirror basic functions -----
+    TVector2 operator-(const MQuaternion &q) const;// { return TVector2(X()-q.X(), Y()-q.Y()); }
+    TVector2 operator-(const MMirror &m) const;// { return TVector2(X()-m.X(), Y()-m.Y()); }
+
+    void SetSigmaPSF(Double_t psf) { fSigmaPSF = psf; }
+    void SetFocalLength(Double_t f) { fFocalLength = f; }
+    void SetPosition(const TVector3 &v) { fPos = v; }
+    void SetNorm(const TVector3 &n) {
+        fNorm = n;
+
+        fTilt = TRotation();
+        // Can be simplified??  rotate the mirror along
+        // perpendicular to its normal projected to x/y and z
+        // by its "zenith angle"
+        fTilt.Rotate(-n.Theta(), TVector3(-n.Y(), n.X(), 0));
+    }
+    void SetShape(Char_t c);
+
+    void SetZ(Double_t z) { fPos.SetZ(z); }
+
+    Double_t X() const { return fPos.X(); }
+    Double_t Y() const { return fPos.Y(); }
+    Double_t Z() const { return fPos.Z(); }
+
+    Double_t Nx() const { return fNorm.X(); }
+    Double_t Ny() const { return fNorm.Y(); }
+    Double_t Nz() const { return fNorm.Z(); }
+
+    TVector2 GetPosXY() const { return fPos.XYvector(); }
+    const TVector3 &GetPos() const { return fPos; }
+    const TVector3 &GetNorm() const { return fNorm; }
+
+    Double_t GetFocalLength() const { return fFocalLength; }
+    Double_t GetSigmaPSF() const { return fSigmaPSF; }
+
+    Double_t GetDist() const { return fPos.Perp(); }
+    Int_t GetShape() const { return fShape; }
+
+    virtual Double_t GetMaxR() const=0;// { return TMath::Max(fMaxRX, fMaxRY); }
+    virtual Double_t GetA() const=0;// { return TMath::Max(fMaxRX, fMaxRY); }
+
+    TVector3 SimPSF(const TVector3 &n, Double_t F, Double_t psf) const;
+    TVector3 SimPSF(const TVector3 &n) const
+    {
+        return SimPSF(n, fFocalLength, fSigmaPSF/10); // Convert from mm to cm
+    }
+
+    Bool_t ExecuteMirror(MQuaternion &p, MQuaternion &u) const;
+
+    // ----- Basic function for parabolic mirror -----
+    Bool_t ExecuteReflection(MQuaternion &p, MQuaternion &u) const;
+
+    // ----- Mirror specialized functions -----
+
+    virtual Bool_t HasHit(const MQuaternion &p) const=0;
+    virtual Bool_t CanHit(const MQuaternion &p) const=0;
+
+    virtual Int_t ReadM(const TObjArray &tok)=0;
+    virtual void  WriteM(std::ostream &out) const=0;
+
+    // TObject
+    void Print(Option_t *o) const;
+
+    /*
+    Bool_t IsSortable() const { return kTRUE; }
+    Int_t Compare(const TObject *obj) const
+    {
+        MMirror &m = (MMirror&)*obj;
+        return m.fPos.Mag2()<fPos.Mag2();
+    }
+    */
+    ClassDef(MMirror, 2) // Base class to describe a mirror
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/MMirrorDisk.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirrorDisk.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirrorDisk.cc	(revision 17960)
@@ -0,0 +1,174 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMirrorDisk
+//
+// A disk like spherical mirror.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMirrorDisk.h"
+
+#include <stdlib.h> // atof (Ubuntu 8.10)
+
+#include <TMath.h>
+#include <TObjArray.h>
+
+#include <TEllipse.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+
+#include "MQuaternion.h"
+
+ClassImp(MMirrorDisk);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Return the aread of the disk: Pi*r^2
+//
+Double_t MMirrorDisk::GetA() const
+{
+    return TMath::Pi()*fR*fR;
+}
+
+// ------------------------------------------------------------------------
+//
+// This is a very rough estimate of whether a photon at a position p
+// can hit a mirror. The position might be off in z and the photon
+// still has to follow its trajectory. Nevertheless we can fairly assume
+// the the way to travel in x/y is pretty small so we can give a rather
+// good estimate of whether the photon can hit.
+//
+// never throw away a photon whihc can hit the mirror!
+//
+Bool_t MMirrorDisk::CanHit(const MQuaternion &p) const
+{
+    // p is given in the reflectors coordinate frame. This is meant
+    // to be a fast check to sort out all mirrors which we can omit
+    // without time consuming calculations.
+
+    // Check if this mirror can be hit at all
+    const Double_t dx = TMath::Abs(p.X()-X());
+    if (dx>fR*1.05)
+        return kFALSE;
+
+    const Double_t dy = TMath::Abs(p.Y()-Y());
+    if (dy>fR*1.05)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Check if the given position coincides with the mirror. The position
+// is assumed to be the incident point on the mirror's surface.
+//
+// The coordinates are in the mirrors coordinate frame.
+//
+// The action should coincide with what is painted in Paint()
+//
+Bool_t MMirrorDisk::HasHit(const MQuaternion &p) const
+{
+    // p is the incident point in the mirror in the mirror's
+    // coordinate frame
+
+    // Black spot in the mirror center (here we can fairly ignore
+    // the distance from the plane to the mirror surface, as long
+    // as the black spot does not become too large)
+    if (p.R2()<0.5*0.5)
+        return kFALSE;
+
+    // Check if the photon has really hit the square mirror
+    return p.R()<fR;
+}
+
+// ------------------------------------------------------------------------
+//
+// Print the contents of the mirror
+//
+void MMirrorDisk::Print(Option_t *o) const
+{
+    MMirror::Print(o);
+    gLog << " " << fR << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint the mirror in x/y.
+//
+// The graphic should coincide with the action in HasHit
+//
+void MMirrorDisk::Paint(Option_t *opt)
+{
+    TEllipse e;
+    e.SetFillColor(18);
+    if (!TString(opt).Contains("line", TString::kIgnoreCase))
+    {
+        e.SetFillColor(17);
+        e.SetLineStyle(0);
+    }
+    if (TString(opt).Contains("same", TString::kIgnoreCase))
+        e.SetFillStyle(0);
+    e.PaintEllipse(X(), Y(), fR, fR, 0, 360, 0);
+
+    if (!TString(opt).Contains("line", TString::kIgnoreCase))
+        e.SetFillColor(gPad->GetFillColor());
+
+    if (!TString(opt).Contains("border", TString::kIgnoreCase))
+        e.PaintEllipse(X(), Y(), 0.5, 0.5, 0, 360, 0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Read the mirror's setup from a file. The first eight tokens should be
+// ignored. (This could be fixed!)
+//
+// Here we read: fR
+//
+Int_t MMirrorDisk::ReadM(const TObjArray &tok)
+{
+    if (tok.GetEntries()!=1)
+        return -1;
+
+    const Double_t d = atof(tok[0]->GetName());
+
+    if (d<=0)
+        return -1;
+
+    fR = d/2;
+
+    return 1;
+}
+
+// ------------------------------------------------------------------------
+//
+void MMirrorDisk::WriteM(ostream &out) const
+{
+    out << fR*2;
+}
Index: branches/Mars_McMismatchStudy/msimreflector/MMirrorDisk.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirrorDisk.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirrorDisk.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MMirrorDisk
+#define MARS_MMirrorDisk
+
+#ifndef MARS_MMirror
+#include "MMirror.h"
+#endif
+
+class MMirrorDisk : public MMirror
+{
+private:
+    Double_t fR; // Radius of the disk
+
+public:
+    MMirrorDisk() : fR(24.75) { }
+
+    // MMirror
+    Double_t GetMaxR() const { return fR; }
+    Double_t GetA() const;
+
+    Bool_t CanHit(const MQuaternion &p) const;
+    Bool_t HasHit(const MQuaternion &p) const;
+
+    Int_t ReadM(const TObjArray &tok);
+    void  WriteM(std::ostream &out) const;
+
+    //TObject
+    void Paint(Option_t *);
+    void Print(Option_t *) const;
+
+    ClassDef(MMirrorDisk, 1)  // A spherical disk type mirror
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/MMirrorHex.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirrorHex.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirrorHex.cc	(revision 17960)
@@ -0,0 +1,344 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMirrorHex
+//
+// A hexagonal spherical mirror
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMirrorHex.h"
+
+#include <stdlib.h> // atof (Ubuntu 8.10)
+
+#include <TMath.h>
+#include <TObjArray.h>
+
+#include <TEllipse.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+
+#include "MHexagon.h"
+#include "MQuaternion.h"
+
+ClassImp(MMirrorHex);
+
+using namespace std;
+
+const Double_t MMirrorHex::fgCos30 = TMath::Cos(30*TMath::DegToRad());
+const Double_t MMirrorHex::fgCos60 = TMath::Cos(60*TMath::DegToRad());
+const Double_t MMirrorHex::fgSin60 = TMath::Sin(60*TMath::DegToRad());
+
+// --------------------------------------------------------------------------
+//
+// Return the aread of the hexagon: d^2*sin(60)
+//
+Double_t MMirrorHex::GetA() const
+{
+    return fD*fD*fgSin60*4;
+}
+
+// ------------------------------------------------------------------------
+//
+// This is a very rough estimate of whether a photon at a position p
+// can hit a mirror. The position might be off in z and the photon
+// still has to follow its trajectory. Nevertheless we can fairly assume
+// the the way to travel in x/y is pretty small so we can give a rather
+// good estimate of whether the photon can hit.
+//
+// never throw away a photon whihc can hit the mirror!
+//
+Bool_t MMirrorHex::CanHit(const MQuaternion &p) const
+{
+    // p is given in the reflectors coordinate frame. This is meant
+    // to be a fast check to sort out all mirrors which we can omit
+    // without time consuming calculations.
+
+    return TMath::Hypot(p.X()-X(), p.Y()-Y())<1.05*fMaxR;
+}
+
+// ------------------------------------------------------------------------
+//
+// Check if the given position coincides with the mirror. The position
+// is assumed to be the incident point on the mirror's surface.
+//
+// The coordinates are in the mirrors coordinate frame.
+//
+// The action should coincide with what is painted in Paint()
+//
+Bool_t MMirrorHex::HasHit(const MQuaternion &p) const
+{
+    // p is the incident point in the mirror in the mirror's
+    // coordinate frame
+
+    // Black spot in the mirror center (here we can fairly ignore
+    // the distance from the plane to the mirror surface, as long
+    // as the black spot does not become too large)
+    if (p.R2()<0.5*0.5)
+        return kFALSE;
+
+    //
+    // 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(p.X())>fD)
+        return kFALSE;
+
+    const Double_t dxc = p.X()*fgCos60;
+    const Double_t dys = p.Y()*fgSin60;
+
+    if (TMath::Abs(dxc+dys)>fD)
+        return kFALSE;
+
+    if (TMath::Abs(dxc-dys)>fD)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint the mirror in x/y.
+//
+// The graphic should coincide with the action in HasHit
+//
+void MMirrorHex::Paint(Option_t *opt)
+{
+    MHexagon h;
+    TEllipse e;
+    h.SetFillColor(18);
+    if (!TString(opt).Contains("line", TString::kIgnoreCase))
+    {
+        h.SetFillColor(17);
+        h.SetLineStyle(0);
+        e.SetLineStyle(0);
+        e.SetFillColor(gPad->GetFillColor());
+    }
+
+    if (TString(opt).Contains("same", TString::kIgnoreCase))
+    {
+        h.SetFillStyle(0);
+        e.SetFillStyle(0);
+    }
+
+    h.PaintHexagon(X(), Y(), fD*2);
+
+    if (!TString(opt).Contains("border", TString::kIgnoreCase))
+        e.PaintEllipse(X(), Y(), 0.5, 0.5, 0, 360, 0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Print the contents of the mirror
+//
+void MMirrorHex::Print(Option_t *o) const
+{
+    MMirror::Print(o);
+    gLog << " " << fD*2 << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// Read the mirror's setup from a file. The first eight tokens should be
+// ignored. (This could be fixed!)
+//
+// Here we read: D
+//
+Int_t MMirrorHex::ReadM(const TObjArray &tok)
+{
+    if (tok.GetEntries()!=1)
+        return -1;
+
+    const Double_t d = atof(tok[0]->GetName());
+
+    if (d<=0)
+        return -1;
+
+    SetD(d);
+
+    return 1;
+}
+
+// ------------------------------------------------------------------------
+//
+void MMirrorHex::WriteM(ostream &out) const
+{
+    out << fD*2;
+}
+
+// ------------------------------------------------------------------------
+//
+// Check if the given position coincides with the mirror. The position
+// is assumed to be the incident point on the mirror's surface.
+//
+// The coordinates are in the mirrors coordinate frame.
+//
+// The action should coincide with what is painted in Paint()
+//
+Bool_t MMirrorHex15::HasHit(const MQuaternion &p) const
+{
+    // p is the incident point in the mirror in the mirror's
+    // coordinate frame
+
+    // Black spot in the mirror center (here we can fairly ignore
+    // the distance from the plane to the mirror surface, as long
+    // as the black spot does not become too large)
+//    if (p.R2()<0.5*0.5)
+//        return kFALSE;
+
+    static const TVector2 rot(cos(-15*TMath::DegToRad()), sin(-15*TMath::DegToRad()));
+
+    const TVector2 &v = p.XYvector();
+
+    const Double_t x = v^rot;
+    const Double_t y = v*rot;
+
+    //
+    // 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(x)>fD)
+        return kFALSE;
+
+    const Double_t dxc = x*fgCos60;
+    const Double_t dys = y*fgSin60;
+
+    if (TMath::Abs(dxc+dys)>fD)
+        return kFALSE;
+
+    if (TMath::Abs(dxc-dys)>fD)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint the mirror in x/y.
+//
+// The graphic should coincide with the action in HasHit
+//
+void MMirrorHex15::Paint(Option_t *opt)
+{
+    MHexagon h;
+    TEllipse e;
+    h.SetFillColor(18);
+    if (!TString(opt).Contains("line", TString::kIgnoreCase))
+    {
+        h.SetFillColor(17);
+        h.SetLineStyle(0);
+        e.SetLineStyle(0);
+        e.SetFillColor(gPad->GetFillColor());
+    }
+
+    if (TString(opt).Contains("same", TString::kIgnoreCase))
+    {
+        h.SetFillStyle(0);
+        e.SetFillStyle(0);
+    }
+
+    h.PaintHexagon(X(), Y(), fD*2, 15*TMath::DegToRad());
+
+    if (!TString(opt).Contains("border", TString::kIgnoreCase))
+        e.PaintEllipse(X(), Y(), 0.5, 0.5, 0, 360, 0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Check if the given position coincides with the mirror. The position
+// is assumed to be the incident point on the mirror's surface.
+//
+// The coordinates are in the mirrors coordinate frame.
+//
+// The action should coincide with what is painted in Paint()
+//
+Bool_t MMirrorHex90::HasHit(const MQuaternion &p) const
+{
+    // p is the incident point in the mirror in the mirror's
+    // coordinate frame
+
+    // Black spot in the mirror center (here we can fairly ignore
+    // the distance from the plane to the mirror surface, as long
+    // as the black spot does not become too large)
+    if (p.R2()<0.5*0.5)
+        return kFALSE;
+
+    //
+    // 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 parallel to the y axis (see camera displays) and two
+    // more, rotated with respect to that one by +- 60 degrees.
+    //
+    if (TMath::Abs(p.Y())>fD)
+        return kFALSE;
+
+    const Double_t dxs = p.X()*fgSin60;
+    const Double_t dyc = p.Y()*fgCos60;
+
+    if (TMath::Abs(dxs+dyc)>fD)
+        return kFALSE;
+
+    if (TMath::Abs(dxs-dyc)>fD)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint the mirror in x/y.
+//
+// The graphic should coincide with the action in HasHit
+//
+void MMirrorHex90::Paint(Option_t *opt)
+{
+    MHexagon h;
+    TEllipse e;
+    h.SetFillColor(18);
+    if (!TString(opt).Contains("line", TString::kIgnoreCase))
+    {
+        h.SetFillColor(17);
+        h.SetLineStyle(0);
+        e.SetLineStyle(0);
+        e.SetFillColor(gPad->GetFillColor());
+    }
+
+    if (TString(opt).Contains("same", TString::kIgnoreCase))
+    {
+        h.SetFillStyle(0);
+        e.SetFillStyle(0);
+    }
+
+    h.PaintHexagon(X(), Y(), fD*2, TMath::Pi()/2);
+
+    if (!TString(opt).Contains("border", TString::kIgnoreCase))
+        e.PaintEllipse(X(), Y(), 0.5, 0.5, 0, 360, 0);
+}
+
Index: branches/Mars_McMismatchStudy/msimreflector/MMirrorHex.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirrorHex.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirrorHex.h	(revision 17960)
@@ -0,0 +1,69 @@
+#ifndef MARS_MMirrorHex
+#define MARS_MMirrorHex
+
+#ifndef MARS_MMirror
+#include "MMirror.h"
+#endif
+
+class MMirrorHex : public MMirror
+{
+protected:
+    const static Double_t fgCos30;
+    const static Double_t fgCos60;
+    const static Double_t fgSin60;
+
+    Double_t fD;  // half diameter D or better distance between opposite sides
+    Double_t fMaxR;
+
+    void SetD(Double_t d) { fD=d/2; fMaxR=fD/fgCos30; }
+
+public:
+    MMirrorHex() { SetD(24.75); }
+
+    // MMirror
+    Double_t GetMaxR() const { return fMaxR; }
+    Double_t GetA() const;
+    Double_t GetD() const { return fD; }
+
+    Bool_t CanHit(const MQuaternion &p) const;
+    Bool_t HasHit(const MQuaternion &p) const;
+
+    Int_t ReadM(const TObjArray &tok);
+    void  WriteM(std::ostream &out) const;
+
+    // TObject
+    void Paint(Option_t *);
+    void Print(Option_t *) const;
+
+    ClassDef(MMirrorHex, 1) // A spherical hexagon type mirror
+};
+
+class MMirrorHex90 : public MMirrorHex
+{
+public:
+    MMirrorHex90() : MMirrorHex() { }
+
+    // MMirror
+    Bool_t HasHit(const MQuaternion &p) const;
+
+    // TObject
+    void Paint(Option_t *);
+
+    ClassDef(MMirrorHex90, 1) // A spherical hexagon type mirror (MMirrorHex rotated by 90deg)
+};
+
+class MMirrorHex15 : public MMirrorHex
+{
+public:
+    MMirrorHex15() : MMirrorHex() { }
+
+    // MMirror
+    Bool_t HasHit(const MQuaternion &p) const;
+
+    // TObject
+    void Paint(Option_t *);
+
+    ClassDef(MMirrorHex15, 1) // A spherical hexagon type mirror (MMirrorHex rotated by 15deg)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/MMirrorSquare.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirrorSquare.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirrorSquare.cc	(revision 17960)
@@ -0,0 +1,193 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMirror
+//
+// A square type spherical mirror
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMirrorSquare.h"
+
+#include <stdlib.h> // atof (Ubuntu 8.10)
+
+#include <TMath.h>
+#include <TObjArray.h>
+
+#include <TBox.h>
+#include <TEllipse.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+
+#include "MQuaternion.h"
+
+ClassImp(MMirrorSquare);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Return the max radius, i.e. the distance of the edges to zje center
+//
+Double_t MMirrorSquare::GetMaxR() const
+{
+    return TMath::Sqrt(2.)*fSideLength;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the aread of the square: l^2
+//
+Double_t MMirrorSquare::GetA() const
+{
+    return fSideLength*fSideLength*4;
+}
+
+// ------------------------------------------------------------------------
+//
+// This is a very rough estimate of whether a photon at a position p
+// can hit a mirror. The position might be off in z and the photon
+// still has to follow its trajectory. Nevertheless we can fairly assume
+// the the way to travel in x/y is pretty small so we can give a rather
+// good estimate of whether the photon can hit.
+//
+// never throw away a photon whihc can hit the mirror!
+//
+Bool_t MMirrorSquare::CanHit(const MQuaternion &p) const
+{
+    // p is given in the reflectors coordinate frame. This is meant
+    // to be a fast check to sort out all mirrors which we can omit
+    // without time consuming calculations.
+
+    // Check if this mirror can be hit at all
+    const Double_t dx = TMath::Abs(p.X()-X());
+    if (dx>fSideLength*1.05)
+        return kFALSE;
+
+    const Double_t dy = TMath::Abs(p.Y()-Y());
+    if (dy>fSideLength*1.05)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Check if the given position coincides with the mirror. The position
+// is assumed to be the incident point on the mirror's surface.
+//
+// The coordinates are in the mirrors coordinate frame.
+//
+// The action should coincide with what is painted in Paint()
+//
+Bool_t MMirrorSquare::HasHit(const MQuaternion &p) const
+{
+    // p is the incident point in the mirror in the mirror's
+    // coordinate frame
+
+    // Black spot in the mirror center (here we can fairly ignore
+    // the distance from the plane to the mirror surface, as long
+    // as the black spot does not become too large)
+    if (p.R2()<0.5*0.5)
+        return kFALSE;
+
+    // Check if the photon has really hit the square mirror
+    if (TMath::Max(fabs(p.X()), fabs(p.Y()))>fSideLength)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint the mirror in x/y.
+//
+// The graphic should coincide with the action in HasHit
+//
+void MMirrorSquare::Paint(Option_t *opt)
+{
+    TBox b;
+    TEllipse e;
+    b.SetFillColor(18);
+
+    if (!TString(opt).Contains("line", TString::kIgnoreCase))
+    {
+        b.SetFillColor(17);
+        b.SetLineStyle(0);
+        e.SetLineStyle(0);
+        e.SetFillColor(gPad->GetFillColor());
+    }
+
+    if (TString(opt).Contains("same", TString::kIgnoreCase))
+    {
+        b.SetFillStyle(0);
+        e.SetFillStyle(0);
+    }
+
+    b.PaintBox(X()-fSideLength, Y()-fSideLength, X()+fSideLength, Y()+fSideLength);
+
+    if (!TString(opt).Contains("border", TString::kIgnoreCase))
+        e.PaintEllipse(X(), Y(), 0.5, 0.5, 0, 360, 0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Print the contents of the mirror
+//
+void MMirrorSquare::Print(Option_t *o) const
+{
+    MMirror::Print(o);
+    gLog << " " << fSideLength << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// Read the mirror's setup from a file. The first eight tokens should be
+// ignored. (This could be fixed!)
+//
+// Here we read: L
+//
+Int_t MMirrorSquare::ReadM(const TObjArray &tok)
+{
+    if (tok.GetEntries()!=1)
+        return -1;
+
+    Double_t l = atof(tok[0]->GetName());
+
+    if (l<=0)
+        return -1;
+
+    fSideLength = l/2;
+
+    return 1;
+}
+
+// ------------------------------------------------------------------------
+//
+void MMirrorSquare::WriteM(ostream &out) const
+{
+    out << fSideLength*2;
+}
Index: branches/Mars_McMismatchStudy/msimreflector/MMirrorSquare.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MMirrorSquare.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MMirrorSquare.h	(revision 17960)
@@ -0,0 +1,33 @@
+#ifndef MARS_MMirrorSquare
+#define MARS_MMirrorSquare
+
+#ifndef MARS_MMirror
+#include "MMirror.h"
+#endif
+
+class MMirrorSquare : public MMirror
+{
+private:
+    Double_t fSideLength; // HALF of the side length!
+
+public:
+    MMirrorSquare() : fSideLength(24.75) { }
+
+    // MMirror
+    Double_t GetMaxR() const;
+    Double_t GetA() const;
+
+    Bool_t HasHit(const MQuaternion &p) const;
+    Bool_t CanHit(const MQuaternion &p) const;
+
+    Int_t ReadM(const TObjArray &tok);
+    void  WriteM(std::ostream &out) const;
+
+    // TObject
+    void Paint(Option_t *);
+    void Print(Option_t *) const;
+
+    ClassDef(MMirrorSquare, 1) // A spherical square type mirror
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/MReflector.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MReflector.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MReflector.cc	(revision 17960)
@@ -0,0 +1,462 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReflector
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReflector.h"
+
+#include <fstream>
+#include <errno.h>
+
+#include <stdlib.h> // atof (Ubuntu 8.10)
+
+#include <TClass.h>
+#include <TSystem.h>
+#include <TEllipse.h>
+
+#include "MQuaternion.h"
+#include "MMirror.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MH.h"
+
+ClassImp(MReflector);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MReflector::MReflector(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MReflector";
+    fTitle = title ? title : "Parameter container storing a collection of several mirrors (reflector)";
+
+    fMirrors.SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the SigmaPSF of all mirrors currently stored.
+//
+void MReflector::SetSigmaPSF(Double_t psf)
+{
+    fMirrors.R__FOR_EACH(MMirror, SetSigmaPSF)(psf);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the maximum radius of th ereflector. This is not meant as
+// a precise number but as a rough estimate e.g. to bin a histogram.
+//
+void MReflector::InitMaxR()
+{
+    fMaxR = 0;
+
+    TIter Next(&fMirrors);
+    MMirror *m = 0;
+    while ((m=static_cast<MMirror*>(Next())))
+    {
+        // Take into account the maximum incident angle 8eg 10deg) and
+        // the theta-angle of the mirror and the z-distance.
+        const Double_t r = m->GetDist()+1.5*m->GetMaxR();
+        if (r > fMaxR)
+            fMaxR = r;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the total Area of all mirrors. Note, that it is recalculated
+// with any call.
+//
+Double_t MReflector::GetA() const
+{
+    Double_t A = 0;
+
+    TIter Next(&fMirrors);
+    MMirror *m = 0;
+    while ((m=static_cast<MMirror*>(Next())))
+        A += m->GetA();
+
+    return A;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the pointer to the first mirror. This is a very dangerous way of
+// access, but the fastest possible. because it is the most often called
+// function in ExecuteReflector we have to have a very fast access.
+//
+const MMirror **MReflector::GetFirstPtr() const
+{
+    return (const MMirror**)fMirrors.GetObjectRef(0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get number of mirrors. There should be no holes in the array!
+//
+const UInt_t MReflector::GetNumMirrors() const
+{
+    return fMirrors.GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check with a rough estimate whether a photon can hit the reflector.
+//
+Bool_t MReflector::CanHit(const MQuaternion &p) const
+{
+    // p is given in the reflectory coordinate frame. This is meant as a
+    // fast check without lengthy calculations to omit all photons which
+    // cannot hit the reflector at all
+    return p.R2()<fMaxR*fMaxR;
+}
+
+// --------------------------------------------------------------------------
+//
+// I/O helper for ReadFile to avoid calling "delete arr" before every return
+//
+MMirror *MReflector::EvalTokens(TObjArray &arr, Double_t defpsf) const
+{
+    if (arr.GetEntries()<9)
+    {
+        *fLog << err << "ERROR - Not enough arguments..." << endl;
+        return 0;
+    }
+
+    const TVector3 pos(atof(arr[0]->GetName()),
+                       atof(arr[1]->GetName()),
+                       atof(arr[2]->GetName()));
+
+    const TVector3 norm(atof(arr[3]->GetName()),
+                        atof(arr[4]->GetName()),
+                        atof(arr[5]->GetName()));
+
+    UInt_t n = 6;
+
+    TString six = arr[n]->GetName();
+
+    Char_t shape = 'S';
+    if (!six.IsFloat())
+    {
+        shape = six[0];
+        n++;
+    }
+
+    const Double_t F = atof(arr[n++]->GetName());
+
+    const TString val = arr[n++]->GetName();
+
+    const Double_t psf = val.IsFloat() ? val.Atof() : -1;
+
+    n += val.IsFloat() ? 1 : 0;
+
+    TString type = arr[n-1]->GetName();
+    type.Prepend("MMirror");
+
+    for (UInt_t i=0; i<n; i++)
+        delete arr.RemoveAt(i);
+    arr.Compress();
+
+    TString msg;
+    TClass *cls = MParContainer::GetClass(type);
+    if (!cls)
+    {
+        *fLog << err << "ERROR - Class " << type << " not in dictionary." << endl;
+        return 0;
+    }
+
+    if (!cls->InheritsFrom(MMirror::Class()))
+    {
+        *fLog << err << "ERROR - Cannot create new instance of class " << type << ": " << endl;
+        *fLog << "Class doesn't inherit from MMirror." << endl;
+        return 0;
+    }
+
+    MMirror *m = static_cast<MMirror*>(cls->New());
+    if (!m)
+    {
+        *fLog << err << "ERROR - Cannot create new instance of class " << type << ": " << endl;
+        *fLog << " - Class has no default constructor." << endl;
+        *fLog << " - An abstract member functions of a base class is not overwritten." << endl;
+        return 0;
+    }
+
+    m->SetPosition(pos);
+    m->SetNorm(norm);
+    m->SetShape(shape);
+    m->SetFocalLength(F);
+    m->SetSigmaPSF(psf>=0 ? psf : defpsf);
+
+    if (m->ReadM(arr)>=0)
+        return m;
+
+    *fLog << err << "ERROR - " << type << "::ReadM failed." << endl;
+
+    delete m;
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a reflector setup from a file. This needs improvemtn.
+//
+// The file structur is like:
+//
+//     x y z nx ny nz F [psf] Type ...
+//
+//  x:         x-coordinate of the mirror's center
+//  y:         y-coordinate of the mirror's center
+//  z:         z-coordinate of the mirror's center
+//  nx:        x-component of the normal vecor in the mirror center
+//  ny:        y-component of the normal vecor in the mirror center
+//  nz:        z-component of the normal vecor in the mirror center
+//  [shape]:   S for spherical <default>, P for parabolic
+//  F:         Focal distance of a spherical mirror
+//  [psf]:     This number is the psf given in the units of x,y,z and
+//             defined at the focal distance F. It can be used to overwrite
+//             the second argument given in ReadFile for individual mirrors.
+//  Type:      A instance of a mirrot of the class Type MMirrorType is created
+//             (Type can be, for example, Hex for for MMirrorHex).
+//  ...:       Additional arguments as defined in MMirrorType::ReadM
+//
+//
+// Coordinate System:
+//  The coordinate system is local in the reflectors frame.
+//  It is defined viewing from the back side of the reflector
+//  towards the camera. (x "right", y "up", z from reflector to camera)
+//  Note, that it is left-handed!
+//
+Bool_t MReflector::ReadFile(TString fname, Double_t defpsf)
+{
+    SetTitle(fname);
+    fMirrors.Delete();
+
+    gSystem->ExpandPathName(fname);
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << (errno!=0?strerror(errno):"Insufficient memory for decompression") << endl;
+        return kFALSE;
+    }
+
+/*
+    Int_t idx[964];
+    Int_t srt[964];
+    for (int i=0; i<964; i++)
+        srt[i] = gRandom->Integer(964);
+
+    TMath::Sort(964, srt, idx);
+    */
+
+    Int_t cnt = 0;
+
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        // Count lines
+        cnt++;
+
+        // Skip comments
+        if (line.BeginsWith("#"))
+            continue;
+
+        // Remove leading and trailing whitespaces
+        line=line.Strip(TString::kBoth);
+
+        // Skip empty lines
+        if (line.IsNull())
+            continue;
+
+        // Tokenize line
+        TObjArray *arr = line.Tokenize(' ');
+
+        // Evaluate tokens
+        MMirror *m = EvalTokens(*arr, defpsf);
+
+        // Delete now obsolete array
+        delete arr;
+
+        // Check if a new mirror could be created successfully
+        if (!m)
+        {
+            *fLog << err << "Error in line " << cnt << ": " << line << endl;
+            return kFALSE;
+        }
+
+        // Add new mirror to array
+        fMirrors.Add(m);
+    }
+
+    InitMaxR();
+
+    return kTRUE;
+
+//    fMirrors.Sort();
+/*
+    for (int i=0; i<964; i++)
+    {
+        MMirror &ref = (MMirror&)*fMirrors[i];
+
+        TArrayD dist(964);
+        for (int j=0; j<964; j++)
+        {
+            const MMirror &mir = (MMirror&)*fMirrors[j];
+            dist[j] = (ref-mir).Mod();
+        }
+
+        TArrayI idx(964);
+        TMath::Sort(964, dist.GetArray(), idx.GetArray(), kFALSE);
+
+        for (int j=0; j<964; j++)
+        {
+            ref.fNeighbors.Add(fMirrors[idx[j]]);
+        }
+    }*/
+}
+
+// ------------------------------------------------------------------------
+//
+Bool_t MReflector::WriteFile(TString fname) const
+{
+    gSystem->ExpandPathName(fname);
+
+    ofstream fout(fname);
+    if (!fout)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << (errno!=0?strerror(errno):"Insufficient memory for decompression") << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&fMirrors);
+    MMirror *m = 0;
+    while ((m=static_cast<MMirror*>(Next())))
+    {
+        //  x:         x-coordinate of the mirror's center
+        //  y:         y-coordinate of the mirror's center
+        //  z:         z-coordinate of the mirror's center
+        //  nx:        x-component of the normal vecor in the mirror center
+        //  ny:        y-component of the normal vecor in the mirror center
+        //  nz:        z-component of the normal vecor in the mirror center
+        //  [shape]:   S for spherical <default>, P for parabolic
+        //  F:         Focal distance of a spherical mirror
+        //  [psf]:     This number is the psf given in the units of x,y,z and
+        //             defined at the focal distance F. It can be used to overwrite
+        //             the second argument given in ReadFile for individual mirrors.
+        //  Type:      A instance of a mirrot of the class Type MMirrorType is created
+        //             (Type can be, for example, Hex for for MMirrorHex).
+        //  ...:       Additional arguments as defined in MMirrorType::ReadM
+
+        fout << setw(12) << m->X() << " ";
+        fout << setw(12) << m->Y() << " ";
+        fout << setw(12) << m->Z() << "  ";
+        fout << setw(12) << m->Nx() << " ";
+        fout << setw(12) << m->Ny() << " ";
+        fout << setw(12) << m->Nz() << " ";
+        if (m->GetShape()==1)
+            fout << "P ";
+        fout << m->GetFocalLength() << " ";
+        // cout << m->GetSigmaPSF() << " ";
+        fout << m->ClassName()+7 << " ";
+        m->WriteM(fout);
+        fout << endl;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the collection of mirrors
+//
+void MReflector::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << " (" << GetNumMirrors() << "): " << endl;
+
+    fMirrors.Print(o);
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint the collection of mirrors
+//
+void MReflector::Paint(Option_t *o)
+{
+    if (!TString(o).Contains("same", TString::kIgnoreCase))
+        MH::SetPadRange(-fMaxR*1.01, -fMaxR*1.01, fMaxR*1.01, fMaxR*1.01);
+
+    fMirrors.Paint(o);
+
+    TEllipse e;
+    e.SetFillStyle(0);
+    e.SetLineColor(17);
+    e.PaintEllipse(0, 0, fMaxR, fMaxR, 0, 360, 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// SigmaPSF: -1
+// FileName: reflector.txt
+//
+// SigmaPSF can be used to set a default for the psf of the mirrors
+// read from the file. Note, that this can be overwritten for individual
+// mirrors in the file. The SigmaPSF is the sigma of a 1D-Gauss fitted
+// to the radial profile of the light distribution.
+//
+// For details on the file structure see MReflector::ReadFile
+//
+Int_t MReflector::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    Double_t psf = -1;
+    if (IsEnvDefined(env, prefix, "SetSigmaPSF", print))
+    {
+        rc = kTRUE;
+        psf = GetEnvValue(env, prefix, "SetSigmaPSF", -1);
+    }
+
+    if (IsEnvDefined(env, prefix, "FileName", print))
+    {
+        rc = kTRUE;
+        if (!ReadFile(GetEnvValue(env, prefix, "FileName", ""), psf))
+            return kERROR;
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimreflector/MReflector.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MReflector.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MReflector.h	(revision 17960)
@@ -0,0 +1,63 @@
+#ifndef MARS_MReflector
+#define MARS_MReflector
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MQuaternion;
+class MMirror;
+
+class MReflector : public MParContainer
+{
+private:
+    //Simple Array               // 5.1s
+    TObjArray fMirrors;          // 6.1s   (Pointer)
+    //TObjArray fMirrors;        // 6.1s   (GetObjectRef)
+    //TObjArray fMirrors;        // 8.3s   (Next)
+    //TObjArray fMirrors;        // 10.1s  (UncheckedAt)
+    //TList fMirrors;            // 10.7s
+    //TOrdCollection fMirrors;   // 23.4s
+
+    Double_t fMaxR;
+
+    void InitMaxR();
+
+    // Helper for I/O
+    MMirror *EvalTokens(TObjArray &arr, Double_t defpsf) const;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MReflector(const char *name=NULL, const char *title=NULL);
+
+    const MMirror **GetFirstPtr() const;
+    const UInt_t GetNumMirrors() const;
+
+    const MMirror *GetMirror(UInt_t idx) const { return idx>=GetNumMirrors()?0:*(GetFirstPtr()+idx); }
+
+    Bool_t ReadFile(TString fname, Double_t defpsf=-1);
+    Bool_t WriteFile(TString fname) const;
+
+    Double_t GetMaxR() const { return fMaxR; }
+    Double_t GetA() const;
+
+    virtual Bool_t CanHit(const MQuaternion &p) const;
+
+    Int_t ExecuteReflector(MQuaternion &p, MQuaternion &u) const;
+
+    void SetSigmaPSF(Double_t psf);
+
+    // TObject
+    void Paint(Option_t *o);
+    void Print(Option_t *o) const;
+
+    ClassDef(MReflector, 1) // Parameter container storing a collection of several mirrors (reflector)
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/MSimRays.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MSimRays.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MSimRays.cc	(revision 17960)
@@ -0,0 +1,241 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:thomas.bretz@epfl.ch>
+!
+!   Copyright: CheObs Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimRays
+//
+// Task to produce rays from a light source at either infinity or a given
+// height from a given local sky position.
+//
+// The sky position is defined by an MPointingPos object in the parameter
+// list (if none exists, the source is at the reflector axis). Its
+// default name is "MPointingPos".
+//
+// The height of the light/point source is set by SetHeight in units of km.
+// A value <= 0 means infinity.
+//
+// The number of rays produced per event is defined by SetNumPhotons(n).
+// The default is 1000.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimRays.h"
+
+#include <TMath.h>       // root >=5.20
+#include <TRandom.h>
+#include <TRotation.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MQuaternion.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MReflector.h"
+#include "MPointingPos.h"
+
+ClassImp(MSimRays);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimRays::MSimRays(const char* name, const char *title)
+    : fEvt(0), fReflector(0), fPointPos(0), fSource(0),
+    fNumPhotons(1000), fHeight(-1),
+    fNameReflector("MReflector"), fNamePointPos("MPointingPos"),
+    fNameSource("Source")
+{
+    fName  = name  ? name  : "MSimRays";
+    fTitle = title ? title : "Task to calculate reflection os a mirror";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the necessary parameter containers.
+//
+Int_t MSimRays::PreProcess(MParList *pList)
+{
+    fEvt = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent");
+    if (!fEvt)
+        return kFALSE;
+
+    if (!pList->FindCreateObj("MCorsikaEvtHeader"))
+        return kFALSE;
+
+    fReflector = (MReflector*)pList->FindObject(fNameReflector, "MReflector");
+    if (!fReflector)
+    {
+        *fLog << inf << fNameReflector << " [MReflector] not found..." << endl;
+        return kFALSE;
+    }
+
+    fSource = (MPointingPos*)pList->FindObject(fNameSource, "MPointingPos");
+    if (!fSource)
+    {
+//        *fLog << inf << fNameSource << " [MPointingPos] not found..." << endl;
+//        return kFALSE;
+    }
+
+    fPointPos = (MPointingPos*)pList->FindObject(fNamePointPos, "MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << inf << fNamePointPos << " [MPointingPos] not found..." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Converts the photons into the telscope coordinate frame using the
+// pointing position from MPointingPos.
+//
+// Reflects all photons on all mirrors and stores the final photons on
+// the focal plane. Also intermediate photons are stored for debugging.
+//
+Int_t MSimRays::Process()
+{
+    // Get arrays from event container
+    fEvt->Resize(fNumPhotons);
+
+    TClonesArray &arr  = fEvt->GetArray();
+
+    const Int_t num = arr.GetEntriesFast();
+
+    const Double_t maxr = fReflector->GetMaxR();
+
+    const Double_t deltazd = fSource ? fSource->GetZdRad() : 0;
+    const Double_t deltaaz = fSource ? fSource->GetAzRad() : 0;
+
+    const Double_t zd = fPointPos->GetZdRad() + deltazd;
+    const Double_t az = fPointPos->GetAzRad() + deltaaz;
+
+
+    // cm     -> m
+    // s      -> ns
+    // length -> time
+    const Double_t conv = 1./(TMath::C()*100/1e9);
+
+    // Local sky coordinates (direction of telescope axis)
+    //const Double_t zd = fPointing->GetZdRad();  // x==north
+    //const Double_t az = fPointing->GetAzRad();
+
+    // Height of point source [cm] (0 means infinity)
+    const Double_t h = fHeight * 100000;
+
+    // Rotation matrix to derotate sky
+    // For the new coordinate system see the Wiki
+    TRotation rot;    // The signs are positive because we align the incident point on ground to the telescope axis
+    rot.RotateX( zd); // Rotate point on ground to align it with the telescope axis
+    rot.RotateZ(-az); // tilt the point from ground to make it parallel to the mirror plane
+
+    Int_t idx = 0;
+    while (idx<num)
+    {
+        MPhotonData &dat = *static_cast<MPhotonData*>(arr.UncheckedAt(idx));
+
+        Double_t x, y;
+        const Double_t r = gRandom->Uniform();
+        gRandom->Circle(x, y, maxr*TMath::Sqrt(r));
+/*
+        Double_t ra = gRandom->Uniform(maxr);
+        Double_t ph = gRandom->Uniform(TMath::TwoPi());
+
+
+        // Get radom incident point on the mirror plane.
+        //const Double_t x = gRandom->Uniform(-maxr, maxr);
+        //const Double_t y = gRandom->Uniform(-maxr, maxr);
+
+        Double_t x = ra*sin(ph);
+        Double_t y = ra*cos(ph);
+
+//        if (x*x + y*y > maxr*maxr)
+//            continue;
+  */
+        // The is the incident direction of the photon
+        // h==0 means infinitiy
+        const TVector3 u = fHeight>0 ? TVector3(x, y, -h).Unit() :  TVector3(0, 0, -1);
+
+        // w is pointing away from the direction the photon comes from
+        // CORSIKA-orig: x(north), y(west),  z(up), t(time)
+        // NOW:          x(east),  y(north), z(up), t(time)
+        MQuaternion p(TVector3(x, y, 0), fHeight>0 ? TMath::Sqrt(x*x + y*y + h*h): 0);
+        MQuaternion w(u, conv);
+
+        // Rotate the coordinates into the reflector's coordinate system.
+        // It is assumed that the z-plane is parallel to the focal plane.
+        // (The reflector coordinate system is defined by the telescope orientation)
+        p *= rot;
+        w *= rot;
+
+        // Now propagate the photon to the z-plane in the new coordinate system
+        p.PropagateZ0(w);
+
+        // Shift the coordinate system to the telescope. Corsika's
+        // coordinate system is always w.r.t. to the particle axis
+        //p += impact;
+
+        // Store new position and direction in the reflector's coordinate frame
+        dat.SetPosition(p);
+        dat.SetDirection(w);
+
+        idx++;
+    }
+
+    // Doesn't seem to be too time consuming. But we could also sort later!
+    //  (after cones, inside the camera)
+    // fEvt->Sort(kTRUE);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Height: -1
+// NumPhotons: 1000
+//
+Int_t MSimRays::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Height", print))
+    {
+        rc = kTRUE;
+        fHeight = GetEnvValue(env, prefix, "Height", fHeight);
+    }
+    if (IsEnvDefined(env, prefix, "NumPhotons", print))
+    {
+        rc = kTRUE;
+        fNumPhotons = GetEnvValue(env, prefix, "NumPhotons", (Int_t)fNumPhotons);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimreflector/MSimRays.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MSimRays.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MSimRays.h	(revision 17960)
@@ -0,0 +1,52 @@
+#ifndef MARS_MSimRays
+#define MARS_MSimRays
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MGeomCam;
+class MPointingPos;
+class MPhotonEvent;
+class MCorsikaEvtHeader;
+
+class MReflector;
+
+class MSimRays : public MTask
+{
+private:
+    MPhotonEvent  *fEvt;        //! Event storing the photons
+    MReflector    *fReflector;  //! Geometry of the reflector
+    MPointingPos  *fPointPos;   //! Direction the telescope is pointing to
+    MPointingPos  *fSource;     //! Direction the rays are coming from relative to the telescope
+
+    UInt_t   fNumPhotons;       // Number of photons to be produced
+    Double_t fHeight;           //[km] Height of point source (<=0 means infinity)
+
+    TString fNameReflector;
+    TString fNamePointPos;
+    TString fNameSource;
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MSimRays(const char *name=NULL, const char *title=NULL);
+
+    void SetNameReflector(const char *name="MReflector")  { fNameReflector = name; }
+    void SetNamePointPos(const char *name="MPointingPos") { fNamePointPos  = name; }
+    void SetNameSource(const char *name="Source")         { fNameSource    = name; }
+
+    void SetHeight(Double_t h=-1) { fHeight=h; }
+    void SetNumPhotons(UInt_t n)  { fNumPhotons=n; }
+
+    // MSimRays
+    ClassDef(MSimRays, 0) // Task to simulate a source for rays
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/MSimReflector.cc
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MSimReflector.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MSimReflector.cc	(revision 17960)
@@ -0,0 +1,598 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2009 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2010
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MSimReflector
+//
+//  fDetectorFrame is a radius in centimeter, defining a disk in the focal
+//  plane around the focal point, in which photons are absorbed. If
+//  fDetectorFrame<=0 the virtual HitFrame function of the camera
+//  geometry container is used instead.
+//
+//  fDetectorMargin is a margin (in mm) which is given to the
+//  MGeomCam::HitDetector. It should define a margin around the area
+//  defined in HitDetector on the focal plane in which photons are kept.
+//  Usually this can be 0 because photons not hitting the detector are
+//  obsolete except they can later be "moved" inside the detector, e.g.
+//  if you use MSimPSF to emulate a PSF by moving photons randomly
+//  on the focal plane. To switch off this check set detector margin to -1.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimReflector.h"
+
+#include <TMath.h>
+#include <TRandom.h>
+
+#include "MGeomCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MQuaternion.h"
+#include "MMirror.h"
+#include "MReflector.h"
+#include "MReflection.h"
+
+#include "MCorsikaEvtHeader.h"
+//#include "MCorsikaRunHeader.h"
+
+#include "MPhotonEvent.h"
+#include "MPhotonData.h"
+
+#include "MPointingPos.h"
+
+ClassImp(MSimReflector);
+
+using namespace std;
+
+// USEFUL CORSIKA OPTIONS:
+//  NOCLONG
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MSimReflector::MSimReflector(const char* name, const char *title)
+    : fEvt(0), fMirror0(0), fMirror1(0), fMirror2(0), fMirror3(0),
+    fMirror4(0), /*fRunHeader(0),*/ fEvtHeader(0), fReflector(0),
+    fGeomCam(0), fPointing(0), fNameReflector("MReflector"),
+    fDetectorFrame(0), fDetectorMargin(0)
+{
+    fName  = name  ? name  : "MSimReflector";
+    fTitle = title ? title : "Task to calculate reflection os a mirror";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the necessary parameter containers.
+//
+Int_t MSimReflector::PreProcess(MParList *pList)
+{
+    fMirror0 = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent", "MirrorPlane0");
+    if (!fMirror0)
+        return kFALSE;
+    fMirror1 = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent", "MirrorPlane1");
+    if (!fMirror1)
+        return kFALSE;
+    fMirror2 = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent", "MirrorPlane2");
+    if (!fMirror2)
+        return kFALSE;
+    fMirror3 = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent", "MirrorPlane3");
+    if (!fMirror3)
+        return kFALSE;
+    fMirror4 = (MPhotonEvent*)pList->FindCreateObj("MPhotonEvent", "MirrorPlane4");
+    if (!fMirror4)
+        return kFALSE;
+
+    fReflector = (MReflector*)pList->FindObject(fNameReflector, "MReflector");
+    if (!fReflector)
+    {
+        *fLog << err << fNameReflector << " [MReflector] not found..." << endl;
+        return kFALSE;
+    }
+
+    if (fReflector->GetNumMirrors()==0)
+    {
+        *fLog << err << "ERROR - Reflector '" << fNameReflector << "' doesn't contain a single mirror." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject(fNameGeomCam, "MGeomCam");
+    if (!fGeomCam)
+    {
+        if (!fNameGeomCam.IsNull())
+            *fLog << inf << fNameGeomCam << " [MGeomCam] not found..." << endl;
+
+        fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+        if (!fGeomCam)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fEvt = (MPhotonEvent*)pList->FindObject("MPhotonEvent");
+    if (!fEvt)
+    {
+        *fLog << err << "MPhotonEvent not found... aborting." << endl;
+        return kFALSE;
+    }
+    /*
+    fRunHeader = (MCorsikaRunHeader*)pList->FindObject("MCorsikaRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MCorsikaRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+    */
+    fEvtHeader = (MCorsikaEvtHeader*)pList->FindObject("MCorsikaEvtHeader");
+    if (!fEvtHeader)
+    {
+        *fLog << err << "MCorsikaEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointing = (MPointingPos*)pList->FindObject(/*"PointingCorsika",*/ "MPointingPos");
+    if (!fPointing)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The main point of calculating the reflection is to determine the
+// coincidence point of the particle trajectory on the mirror surface.
+//
+// If the position and the trajectory of a particle is known it is enough
+// to calculate the z-value of coincidence. x and y are then well defined.
+//
+//  Since the problem (mirror) has a rotational symmetry we only have to care
+//  about the distance from the z-axis.
+//
+// Given:
+//
+//    p:  position  vector of particle (z=0)
+//    u:  direction vector of particle
+//    F:  Focal distance of the mirror
+//
+//  We define:
+//
+//    q   :=   (px,    py   )
+//    v   :=   (ux/uz, uy/uz)
+//    r^2 := x^2 + y^2
+//
+//
+// Distance from z-axis:
+// ---------------------
+//
+//          q'        =  q - z*v        (z>0)
+//
+//    Calculate distance r (|q|)
+//
+//          r^2       = (px-z*ux)^2 + (py-z*uy)^2
+//          r^2       = px^2+py^2 + z^2*(ux^2+uy^2) - 2*z*(px*ux+py*uy)
+//          r^2       =   |q|^2   + z^2*|v|^2       - 2*z* q*v
+//
+//
+// Spherical Mirror Surface:  (distance of surface point from 0/0/0)
+// -------------------------
+//
+//   Sphere:  r^2 +   z^2    = R^2               | Parabola: z = p*r^2
+//   Mirror:  r^2 +  (z-R)^2 = R^2               | Mirror:   z = p*r^2
+//                                               |
+//    Focal length: F=R/2                        |  Focal length: F = 1/4p
+//                                               |
+//   r^2 + (z-2*F)^2 = (2*F)^2                   |           z = r^2/4F
+//                                               |
+//          z        = -sqrt(4*F*F - r*r) + 2*F  |
+//          z-2*F    = -sqrt(4*F*F - r*r)        |
+//         (z-2*F)^2 = 4*F*F - r*r               |
+//   z^2-4*F*z+4*F^2 = 4*F*F - r*r  (4F^2-r^2>0) |  z - r^2/4F = 0
+//   z^2-4*F*z+r^2   = 0
+//
+//    Find the z for which our particle has the same distance from the z-axis
+//    as the mirror surface.
+//
+//    substitute r^2
+//
+//
+// Equation to solve:
+// ------------------
+//
+//   z^2*(1+|v|^2) - 2*z*(2*F+q*v) + |q|^2 =  0  |  z^2*|v|^2 - 2*z*(2*F+q*v) + |q|^2 = 0
+//
+//                                   z = (-b +- sqrt(b*b - 4ac))/(2*a)
+//
+//              a =   1+|v|^2                    |             a = |v|^2
+//              b = - 2*b'  with  b' = 2*F+q*v   |             b = - 2*b'  with  b' = 2*F+q*v
+//              c =   |q|^2                      |             c = |q|^2
+//                                               |
+//
+//                                        substitute b := 2*b'
+//
+//                            z = (2*b' +- 2*sqrt(b'*b' - ac))/(2*a)
+//                            z = (  b' +-   sqrt(b'*b' - ac))/a
+//                            z = (b'/a +-   sqrt(b'*b' - ac))/a
+//
+//                                        substitute f := b'/a
+//
+//                                      z = f +- sqrt(f^2 - c/a)
+//
+// =======================================================================================
+//
+// After z of the incident point has been determined the position p is
+// propagated along u to the plane with z=z. Now it is checked if the
+// mirror was really hit (this is implemented in HasHit).
+// From the position on the surface and the mirrors curvature we can
+// now calculate the normal vector at the incident point.
+// This normal vector is smeared out with MMirror::PSF (basically a
+// random gaussian) and then the trajectory is reflected on the
+// resulting normal vector.
+//
+Bool_t MMirror::ExecuteReflection(MQuaternion &p, MQuaternion &u) const
+{
+    // If the z-componenet of the direction vector is normalized to 1
+    // the calculation of the incident points becomes very simple and
+    // the resulting z is just the z-coordinate of the incident point.
+    const TVector2 v(u.XYvector()/u.Z());
+    const TVector2 q(p.XYvector());
+
+    // Radius of curvature
+    const Double_t G = 2*fFocalLength;
+
+    // Find the incident point of the vector to the mirror
+    // u corresponds to downward going particles, thus we use -u here
+    const Double_t b = G - q*v;
+    const Double_t a = v.Mod2();
+    const Double_t c = q.Mod2();
+
+    // Solution for q spherical (a+1) (parabolic mirror (a) instead of (a+1))
+    const Double_t A = fShape ? a : a+1;
+
+    const Double_t f = b/A;
+    const Double_t g = c/A;
+
+    // Solution of second order polynomial (transformed: a>0)
+    // (The second solution can be omitted, it is the intersection
+    //  with the upper part of the sphere)
+    const Double_t z = a==0 ? c/(2*b) : f - TMath::Sqrt(f*f - g);
+
+    // Move the photon along its trajectory to the x/y plane of the
+    // mirror's coordinate frame. Therefor stretch the vector
+    // until its z-component is the distance from the vector origin
+    // until the vector hits the mirror surface.
+    // p += z/u.Z()*u;
+    // p is at the mirror plane and we want to propagate back to the mirror surface
+    p.PropagateZ(u, z);
+
+    // MirrorShape: Now check if the photon really hit the mirror or just missed it
+    if (!HasHit(p))
+        return kFALSE;
+
+    // Get normal vector for reflection by calculating the derivatives
+    // of a the mirror's surface along x and y
+    const Double_t d = fShape ? G : TMath::Sqrt(G*G - p.R2());
+
+    // The solution for the normal vector is
+    //    TVector3 n(-p.X()/d, -p.Y()/d, 1));
+    // Since the normal vector doesn't need to be of normal
+    // length we can avoid an obsolete division
+    TVector3 n(p.X(), p.Y(), -d);
+
+    if (fSigmaPSF>0)
+        n += SimPSF(n);
+
+    // Changes also the sign of the z-direction of flight
+    // This is faster giving identical results
+    u *= MReflection(n);
+    //u *= MReflection(p.X(), p.Y(), -d);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Converts the coordinates into the coordinate frame of the mirror.
+// Executes the reflection calling ExecuteReflection and converts
+// the coordinates back.
+// Depending on whether the mirror was hit kTRUE or kFALSE is returned.
+// It the mirror was not hit the result coordinates are wrong.
+//
+Bool_t MMirror::ExecuteMirror(MQuaternion &p, MQuaternion &u) const
+{
+    // Move the mirror to the point of origin and rotate the position into
+    // the individual mirrors coordinate frame.
+    // Rotate the direction vector into the mirror's coordinate frame
+    p -= fPos;
+    p *= fTilt;
+    u *= fTilt;
+
+    // Move the photon along its trajectory to the x/y plane of the
+    // mirror's coordinate frame. Therefor stretch the vector
+    // until its z-component vanishes.
+    //p -= p.Z()/u.Z()*u;
+
+    // p is at the reflector plane and we want to propagate back to the mirror plane
+    p.PropagateZ0(u);
+
+    // Now try to  propagate the photon from the plane to the mirror
+    // and reflect its direction vector on the mirror.
+    if (!ExecuteReflection(p, u))
+        return kFALSE;
+
+    // Derotate from mirror coordinates and shift the photon back to
+    // reflector coordinates.
+    // Derotate the direction vector
+    u *= fTilt.Inverse();
+    p *= fTilt.Inverse();
+    p += fPos;
+
+    return kTRUE;
+}
+
+// Jeder Spiegel sollte eine Liste aller andern Spiegel in der
+// reihenfolge Ihrer Entfernung enthalten. Wir starten mit der Suche
+// immer beim zuletzt getroffenen Spiegel!
+//
+// --------------------------------------------------------------------------
+//
+// Loops over all mirrors of the reflector. After doing a rough check
+// whether the mirror can be hit at all the reflection is executed
+// calling the ExecuteMirror function of the mirrors.
+//
+// If a mirror was hit its index is retuened, -1 otherwise.
+//
+// FIXME: Do to lopping over all mirrors for all photons this is the
+// most time consuming function in teh reflector simulation. By a more
+// intelligent way of finding the right mirror then just testing all
+// this could be accelerated a lot.
+//
+Int_t MReflector::ExecuteReflector(MQuaternion &p, MQuaternion &u) const
+{
+    //static const TObjArray *arr = &((MMirror*)fMirrors[0])->fNeighbors;
+
+    // This way of access is somuch faster than the program is
+    // a few percent slower if accessed by UncheckedAt
+    const MMirror **s = GetFirstPtr();
+    const MMirror **e = s+GetNumMirrors();
+    //const MMirror **s = (const MMirror**)fMirrors.GetObjectRef(0);
+    //const MMirror **e = s+fMirrors.GetEntriesFast();
+    //const MMirror **s = (const MMirror**)arr->GetObjectRef(0);
+    //const MMirror **e = s+arr->GetEntriesFast();
+
+    // Loop over all mirrors
+    for (const MMirror **m=s; m<e; m++)
+    {
+        const MMirror &mirror = **m;
+
+        // FIXME: Can we speed up using lookup tables or
+        //        indexed tables?
+
+        // MirrorShape: Check if this mirror can be hit at all
+        // This is to avoid time consuming calculation if there is no
+        // chance of a coincidence.
+        // FIXME: Inmprove search algorithm (2D Binary search?)
+        if (!mirror.CanHit(p))
+            continue;
+
+        // Make a local copy of position and direction which can be
+        // changed by ExecuteMirror.
+        MQuaternion q(p);
+        MQuaternion v(u);
+
+        // Check if this mirror is hit, and if it is hit return
+        // the reflected position and direction vector.
+        // If the mirror is missed we go on with the next mirror.
+        if (!mirror.ExecuteMirror(q, v))
+            continue;
+
+        // We hit a mirror. Restore the local copy of position and
+        // direction back into p und u.
+        p = q;
+        u = v;
+
+        //arr = &mirror->fNeighbors;
+
+        return m-s;
+    }
+
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Converts the photons into the telscope coordinate frame using the
+// pointing position from MPointingPos.
+//
+// Reflects all photons on all mirrors and stores the final photons on
+// the focal plane. Also intermediate photons are stored for debugging.
+//
+Int_t MSimReflector::Process()
+{
+    // Get arrays from event container
+    TClonesArray &arr  = fEvt->GetArray();
+
+    // Because we knwo in advance what the maximum storage space could
+    // be we allocated it in advance (or shrink it if it was extremely
+    // huge before)
+    // Note, that the drawback is that an extremly large event
+    //       will take about five times its storage space
+    //       for a moment even if a lot from it is unused.
+    //       It will be freed in the next step.
+    fMirror0->Resize(arr.GetEntriesFast()); // Free memory of allocated MPhotonData
+    fMirror2->Resize(arr.GetEntriesFast()); // Free memory of allocated MPhotonData
+    fMirror3->Resize(arr.GetEntriesFast()); // Free memory of allocated MPhotonData
+    fMirror4->Resize(arr.GetEntriesFast()); // Free memory of allocated MPhotonData
+
+    // Initialize mirror properties
+    const Double_t F = fGeomCam->GetCameraDist()*100; // Focal length [cm]
+
+    // Local sky coordinates (direction of telescope axis)
+    const Double_t zd = fPointing->GetZdRad();  // x==north
+    const Double_t az = fPointing->GetAzRad();
+
+    // Rotation matrix to derotate sky
+    // For the new coordinate system see the Wiki
+    TRotation rot;    // The signs are positive because we align the incident point on ground to the telescope axis
+    rot.RotateZ( az); // Rotate point on ground to align it with the telescope axis
+    rot.RotateX(-zd); // tilt the point from ground to make it parallel to the mirror plane
+
+    // Now get the impact point from Corsikas output
+    const TVector3 impact(fEvtHeader->GetX(), fEvtHeader->GetY(), 0);
+
+    // Counter for number of total and final events
+    UInt_t cnt[6] = { 0, 0, 0, 0, 0, 0 };
+
+    const Int_t num = arr.GetEntriesFast();
+    for (Int_t idx=0; idx<num; idx++)
+    {
+        MPhotonData *dat = static_cast<MPhotonData*>(arr.UncheckedAt(idx));
+
+        // w is pointing away from the direction the photon comes from
+        // CORSIKA-orig: x(north), y(west),  z(up), t(time)
+        // NOW:          x(east),  y(north), z(up), t(time)
+        MQuaternion p(dat->GetPosQ());  // z=0
+        MQuaternion w(dat->GetDirQ());  // z<0
+
+        // Shift the coordinate system to the telescope. Corsika's
+        // coordinate system is always w.r.t. to the particle axis
+        p -= impact;
+
+        // Rotate the coordinates into the reflector's coordinate system.
+        // It is assumed that the z-plane is parallel to the focal plane.
+        // (The reflector coordinate system is defined by the telescope orientation)
+        p *= rot;
+        w *= rot;
+
+        // ---> Simulate star-light!
+        // w.fVectorPart.SetXYZ(0.2/17, 0.2/17, -(1-TMath::Hypot(0.3, 0.2)/17));
+
+        // Now propagate the photon to the z-plane in the new coordinate system
+        p.PropagateZ0(w);
+
+        // Store new position and direction in the reflector's coordinate frame
+        dat->SetPosition(p); 
+        dat->SetDirection(w);
+
+        (*fMirror0)[cnt[0]++] = *dat;
+        //*static_cast<MPhotonData*>(cpy0.UncheckedAt(cnt[0]++)) = *dat;
+
+        // Check if the photon has hit the camera housing and holding
+        if (fGeomCam->HitFrame(p, w, fDetectorFrame))
+            continue;
+
+        // FIXME: Do we really need this one??
+        //(*fMirror1)[cnt[1]++] = *dat;
+        //*static_cast<MPhotonData*>(cpy1.UncheckedAt(cnt[1]++)) = *dat;
+
+        // Check if the reflector can be hit at all
+        if (!fReflector->CanHit(p))
+            continue;
+
+        (*fMirror2)[cnt[2]++] = *dat;
+        //*static_cast<MPhotonData*>(cpy2.UncheckedAt(cnt[2]++)) = *dat;
+
+        // Now execute the reflection of the photon on the mirrors' surfaces
+        const Int_t num = fReflector->ExecuteReflector(p, w);
+        if (num<0)
+            continue;
+
+        // Set new position and direction (w.r.t. to the reflector's coordinate system)
+        // Set also the index of the mirror which was hit as tag.
+        dat->SetTag(num);
+        dat->SetPosition(p);
+        dat->SetDirection(w);
+
+        (*fMirror3)[cnt[3]++] = *dat;
+        //*static_cast<MPhotonData*>(cpy3.UncheckedAt(cnt[3]++)) = *dat;
+
+        // Propagate the photon along its trajectory to the focal plane z=F
+        p.PropagateZ(w, F);
+
+        // Store new position
+        dat->SetPosition(p);
+
+        (*fMirror4)[cnt[4]++] = *dat;
+        //*static_cast<MPhotonData*>(cpy4.UncheckedAt(cnt[4]++)) = *dat;
+
+        // FIXME: It make make sense to move this out of this class
+        // It is detector specific not reflector specific
+        // Discard all photons which definitly can not hit the detector surface
+        if (fDetectorMargin>=0 && !fGeomCam->HitDetector(p, fDetectorMargin))
+            continue;
+
+        // Copy this event to the next 'new' in the list
+        *static_cast<MPhotonData*>(arr.UncheckedAt(cnt[5]++)) = *dat;
+    }
+
+    // Now we shrink the array to a storable size (for details see
+    // MPhotonEvent::Shrink).
+    fMirror0->Shrink(cnt[0]);
+    //fMirror1->Shrink(cnt[1]);
+    fMirror2->Shrink(cnt[2]);
+    fMirror3->Shrink(cnt[3]);
+    fMirror4->Shrink(cnt[4]);
+    fEvt->Shrink(cnt[5]);
+
+    // Doesn't seem to be too time consuming. But we could also sort later!
+    //  (after cones, inside the camera)
+    fEvt->Sort(kTRUE);
+
+    // FIXME FIXME FIXME: Set maxindex, first and last time.
+    // SetMaxIndex(fReflector->GetNumMirrors()-1)
+    // if (fEvt->GetNumPhotons())
+    // {
+    //    SetTime(fEvt->GetFirst()->GetTime(), fEvt->GetLast()->GetTime());
+    // }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// DetectorMargin: 0
+//
+Int_t MSimReflector::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "DetectorFrame", print))
+    {
+        rc = kTRUE;
+        fDetectorFrame = GetEnvValue(env, prefix, "DetectorFrame", 0);
+    }
+    if (IsEnvDefined(env, prefix, "DetectorMargin", print))
+    {
+        rc = kTRUE;
+        fDetectorMargin = GetEnvValue(env, prefix, "DetectorMargin", 0);
+    }
+
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/msimreflector/MSimReflector.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/MSimReflector.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/MSimReflector.h	(revision 17960)
@@ -0,0 +1,58 @@
+#ifndef MARS_MSimReflector
+#define MARS_MSimReflector
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MGeomCam;
+class MPointingPos;
+class MPhotonEvent;
+class MCorsikaEvtHeader;
+
+class MReflector;
+
+class MSimReflector : public MTask
+{
+private:
+    MPhotonEvent     *fEvt;        //! Event  storing the photons
+    MPhotonEvent     *fMirror0;    //! Event  storing the photons in the mirror plane (w/o camera shadow)
+    MPhotonEvent     *fMirror1;    //! Event  storing the photons in the mirror plane (w/  camera shadow)
+    MPhotonEvent     *fMirror2;    //! Event  storing the photons in the mirror plane (w/  camera shadow)
+    MPhotonEvent     *fMirror3;    //! Event  storing the photons in the mirror plane (w/  camera shadow)
+    MPhotonEvent     *fMirror4;    //! Event  storing the photons in the mirror plane (w/  camera shadow)
+    //MCorsikaRunHeader *fRunHeader;     //! Header storing event information
+    MCorsikaEvtHeader *fEvtHeader;     //! Header storing event information
+
+    MReflector        *fReflector;  //!
+    MGeomCam          *fGeomCam;    //!
+    MPointingPos      *fPointing;   //!
+
+    TString fNameGeomCam;        // Name of the geometry container storing the APD gemeotry
+    TString fNameReflector;      // Name of the container storing the reflector geometry 
+
+    Double_t fDetectorFrame;     // A disk of radius DetectorFrame around the focal point absorbing photons
+    Double_t fDetectorMargin;    // A margin around the detector (MGeomCam::HitCamera) in which photons are also stored
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MSimReflector(const char *name=NULL, const char *title=NULL);
+
+    // MSimReflector
+    void SetNameGeomCam(const char *name="MGeomCam")     { fNameGeomCam   = name; }
+    void SetNameReflector(const char *name="MReflector") { fNameReflector = name; }
+
+    void SetDetectorFrame(Double_t cm=0)  { fDetectorFrame  = cm; }
+    void SetDetectorMargin(Double_t mm=0) { fDetectorMargin = mm; }
+
+    ClassDef(MSimReflector, 0) // Task to calculate reflection on a mirror
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msimreflector/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/Makefile	(revision 17960)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = SimReflector
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mcorsika -I../msim -I../mpointing \
+	   -I../mmc -I../mgui -I../mgeom
+
+SRCFILES = MSimReflector.cc \
+           MSimRays.cc \
+	   MReflector.cc \
+	   MMirror.cc \
+	   MMirrorSquare.cc \
+	   MMirrorHex.cc \
+	   MMirrorDisk.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/msimreflector/SimReflectorIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/SimReflectorIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/SimReflectorIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/msimreflector/SimReflectorLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/msimreflector/SimReflectorLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msimreflector/SimReflectorLinkDef.h	(revision 17960)
@@ -0,0 +1,18 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MSimReflector+;
+#pragma link C++ class MSimRays+;
+
+#pragma link C++ class MReflector+;
+#pragma link C++ class MMirror+;
+#pragma link C++ class MMirrorSquare+;
+#pragma link C++ class MMirrorDisk+;
+#pragma link C++ class MMirrorHex+;
+#pragma link C++ class MMirrorHex15+;
+#pragma link C++ class MMirrorHex90+;
+
+#endif
Index: branches/Mars_McMismatchStudy/msql/MBasketSQL.cc
===================================================================
--- branches/Mars_McMismatchStudy/msql/MBasketSQL.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MBasketSQL.cc	(revision 17960)
@@ -0,0 +1,85 @@
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MBasketSQL                                                           //
+//                                                                      //
+// Implement TBasket for a SQL backend                                  //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MBasketSQL
+#define MARS_MBasketSQL
+
+#include "MBasketSQL.h"
+
+#include "TBasket.h"
+#include "TTree.h"
+#include "TBranch.h"
+#include "MBufferSQL.h"
+
+ClassImp(MBasketSQL)
+
+namespace std {} using namespace std;
+
+//_________________________________________________________________________
+MBasketSQL::MBasketSQL() : TBasket(), fRowPtr(0)
+{
+   // Default constructor.
+}
+
+//_________________________________________________________________________
+MBasketSQL::MBasketSQL(TBranch *branch, TSQLRow **sqlrow, Int_t index, TString type)
+{
+    // Create a TSQLBuffer for this basket.
+    SetName(branch->GetName());
+    SetTitle(branch->GetName());
+
+    fClassName   = "MBasketSQL";
+
+    fBufferSize  = branch->GetBasketSize();
+    fNevBufSize  = branch->GetEntryOffsetLen();
+    fNevBuf      = 0;
+    fEntryOffset = 0;  //Must be set to 0 before calling Sizeof
+    fDisplacement= 0;  //Must be set to 0 before calling Sizeof
+    fBuffer      = 0;  //Must be set to 0 before calling Sizeof
+    fBufferRef   = 0;
+
+    fBufferRef = new MBufferSQL(sqlrow, index, type);
+
+    fHeaderOnly  = kTRUE;
+    fLast        = 0;
+    //Streamer(*fBufferRef);
+    fBuffer      = 0;
+    fBranch      = branch;
+    fHeaderOnly  = kFALSE;
+    branch->GetTree()->IncrementTotalBuffers(fBufferSize);
+}
+
+//_________________________________________________________________________
+void MBasketSQL::PrepareBasket(Long64_t entry)
+{
+    // Prepare the basket for the next entry.
+    fBranch->GetTree()->LoadTree(entry);
+}
+
+//_________________________________________________________________________
+Int_t MBasketSQL::ReadBasketBytes(Long64_t , TFile *)
+{
+    Error("ReadBasketBytes","This member function should not be called!");
+    return 0;
+}
+
+//_________________________________________________________________________
+Int_t MBasketSQL::ReadBasketBuffers(Long64_t , Int_t, TFile *)
+{
+    Error("ReadBasketBuffers","This member function should not be called!");
+    return 0;
+}
+
+//_________________________________________________________________________
+void MBasketSQL::Update(Int_t, Int_t) 
+{
+    // See TBasket::Update.
+    fNevBuf++;
+}
+
+#endif
Index: branches/Mars_McMismatchStudy/msql/MBasketSQL.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/MBasketSQL.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MBasketSQL.h	(revision 17960)
@@ -0,0 +1,40 @@
+#ifndef ROOT_MBasketSQL
+#define ROOT_MBasketSQL
+
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MBasketSQL                                                           //
+//                                                                      //
+// Implement TBasket for a SQL backend                                  //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+
+#include "TBasket.h"
+
+class TSQLRow;
+
+class MBasketSQL : public TBasket
+{
+private:
+   MBasketSQL(const MBasketSQL&);            // MBasketSQL objects are not copiable.
+   MBasketSQL& operator=(const MBasketSQL&); // MBasketSQL objects are not copiable.
+
+protected:
+   TSQLRow **fRowPtr; //!
+
+public:
+   MBasketSQL();
+   MBasketSQL(TBranch *b, TSQLRow **r, Int_t index, TString type);
+
+   void PrepareBasket(Long64_t entry);
+
+   virtual Int_t ReadBasketBuffers(Long64_t pos, Int_t len, TFile *file);
+   virtual Int_t ReadBasketBytes(Long64_t pos, TFile *file);
+
+   void Update(Int_t offset, Int_t skipped);
+
+   ClassDef(MBasketSQL,1)  //the TBranch buffers
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msql/MBufferSQL.cc
===================================================================
--- branches/Mars_McMismatchStudy/msql/MBufferSQL.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MBufferSQL.cc	(revision 17960)
@@ -0,0 +1,71 @@
+// @(#)root/tree:$Id: MBufferSQL.cxx 43518 2012-03-28 01:04:07Z pcanal $
+// Author: Philippe Canal and al. 08/2004
+
+/*************************************************************************
+ * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
+
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MBufferSQL                                                           //
+//                                                                      //
+// Implement TBuffer for a SQL backend                                  //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+#include "MBufferSQL.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "TError.h"
+
+#include "TSQLResult.h"
+#include "TSQLRow.h"
+
+#include "MTime.h"
+
+using namespace std;
+
+ClassImp(MBufferSQL);
+
+//________________________________________________________________________
+MBufferSQL::MBufferSQL() : TBufferFile(), fRowPtr(0)
+{
+   // Constructor.
+}
+
+//________________________________________________________________________
+MBufferSQL::MBufferSQL(TSQLRow **r, Int_t index, TString type) :
+TBufferFile(TBufferFile::kRead), fRowPtr(r), fIndex(index), fIsDate(kFALSE)
+{
+    // Constructor.
+    if (type.BeginsWith("date", TString::kIgnoreCase) ||
+        type.BeginsWith("time", TString::kIgnoreCase))
+        fIsDate = kTRUE;
+}
+
+//________________________________________________________________________
+void MBufferSQL::ReadDouble(Double_t &d)
+{
+   // Operator>>
+   const char *ptr = (*fRowPtr)->GetField(fIndex);
+
+   if (ptr==0)
+   {
+       d = 0;
+       Error("operator>>(Double_t&)","NULL value found in cell");
+       return;
+   }
+
+   if (!fIsDate)
+   {
+       d = atof(ptr);
+       return;
+   }
+
+   d = MTime(ptr).GetAxisTime();
+}
Index: branches/Mars_McMismatchStudy/msql/MBufferSQL.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/MBufferSQL.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MBufferSQL.h	(revision 17960)
@@ -0,0 +1,56 @@
+// @(#)root/tree:$Id: MBufferSQL.h 25450 2008-09-18 21:13:42Z pcanal $
+// Author: Philippe Canal 2005
+
+/*************************************************************************
+ * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
+
+#ifndef ROOT_MBufferSQL
+#define ROOT_MBufferSQL
+
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MBufferSQL                                                           //
+//                                                                      //
+// Implement TBuffer for a SQL backend                                  //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+
+#ifndef ROOT_TBufferFile
+#include "TBufferFile.h"
+#endif
+#ifndef ROOT_TString
+#include "TString.h"
+#endif
+
+
+class TSQLResult;
+class TSQLRow;
+
+class MBufferSQL : public TBufferFile
+{
+private:
+    TSQLRow **fRowPtr;      //!
+    Int_t     fIndex;
+    Bool_t    fIsDate;
+
+   // TBuffer objects cannot be copied or assigned
+    MBufferSQL(const MBufferSQL &);        // not implemented
+    void operator=(const MBufferSQL &);    // not implemented
+
+public:
+    MBufferSQL();
+    MBufferSQL(TSQLRow **row, Int_t index, TString type);
+
+    void ReadDouble(Double_t &d);
+
+    ClassDef(MBufferSQL, 1); // Implementation of TBuffer to load and write to a SQL database
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/msql/MSQLMagic.cc
===================================================================
--- branches/Mars_McMismatchStudy/msql/MSQLMagic.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MSQLMagic.cc	(revision 17960)
@@ -0,0 +1,367 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2006
+!
+!
+\* ======================================================================== */
+
+////////////////////////////////////////////////////////////////////////
+//
+//  MSQLMagic
+//
+// This is an enhancement of MSQLServer especially made the feature
+// the interfaction with our database.
+//
+////////////////////////////////////////////////////////////////////////
+#include "MSQLMagic.h"
+
+#include <stdlib.h> // atoi (Ubuntu 8.10)
+
+#include <iostream>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+ClassImp(MSQLMagic);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Return the name corresponding to a key. If col starts with f or
+// end with KEY it is stripped.
+//
+//  If the query fails an empty string is returned.
+//
+//  On success the name of the key is returned.
+//
+TString MSQLMagic::QueryValOf(TString col, const char *ext, const char *key)
+{
+    if (col.EndsWith("KEY"))
+        col.Remove(col.Length()-3);
+    if (col.BeginsWith("f"))
+        col.Remove(0, 1);
+
+    const TString query=Form("SELECT f%s%s FROM %s WHERE f%sKEY=%s",
+                             col.Data(), ext, col.Data(), col.Data(), key);
+
+    TSQLResult *res = Query(query);
+    if (!res)
+        return "";
+
+    TSQLRow *row=res->Next();
+
+    const TString rc = row ? (*row)[0] : "";
+
+    if (row)
+        delete row;
+
+    delete res;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the name corresponding to a key. If col starts with f or
+// end with KEY it is stripped.
+//
+//  If the query fails an empty string is returned.
+//
+//  On success the name of the key is returned.
+//
+TString MSQLMagic::QueryNameOfKey(TString col, const char *key)
+{
+    return QueryValOf(col, "Name", key);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the value corresponding to a key. If col starts with f or
+// end with KEY it is stripped.
+//
+//  If the query fails an empty string is returned.
+//
+//  On success the value of the key is returned.
+//
+TString MSQLMagic::QueryValOfKey(TString col, const char *key)
+{
+    return QueryValOf(col, "", key);
+}
+
+// --------------------------------------------------------------------------
+//
+//  return the key of f[col]KEY where f[col][ext]=[val]
+//
+//  return -1 if the query failed or the KEY was not found
+//  return  0 if the KEY could not be determined after inserting
+//  return the KEY in case of success
+//
+Int_t MSQLMagic::QueryKeyOf(const char *col, const char *ext, const char *val)
+{
+    const TString query1 = Form("SELECT f%sKEY FROM %s WHERE f%s%s='%s'",
+                                col, col, col, ext, val);
+
+    TSQLResult *res1 = Query(query1);
+    if (!res1)
+    {
+        cout << "ERROR - Query has failed: " << query1 << endl;
+        return -1;
+    }
+
+    TSQLRow *row=res1->Next();
+
+    const Int_t rc1 = row && (*row)[0] ? atoi((*row)[0]) : -1;
+
+    if (row)
+        delete row;
+
+    delete res1;
+
+    return rc1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  return the key of f[col]KEY where f[col]=[val]
+//
+//  return -1 if the query failed or the KEY was not found
+//  return  0 if the KEY could not be determined after inserting
+//  return the KEY in case of success
+//
+Int_t MSQLMagic::QueryKeyOfVal(const char *col, const char *val)
+{
+    return QueryKeyOf(col, "", val);
+}
+
+// --------------------------------------------------------------------------
+//
+//  return the key of f[col]KEY where f[col]Name=[name]
+//
+//  if value [name] is not existing, insert value (creates anew key)
+//  and return the new key
+//
+//  return -1 if the query failed or the KEY was not found (insert=kFALSE)
+//  return  0 if the KEY could not be determined after inserting
+//  return the KEY in case of success
+//
+Int_t MSQLMagic::QueryKeyOfName(const char *col, const char *name, Bool_t insert)
+{
+    const Int_t rc1 = QueryKeyOf(col, "Name", name);
+
+    if (rc1>=0)
+        return rc1;
+
+    if (!insert)
+        return -1;
+
+    //insert new value
+    const Int_t rc2 = Insert(col, Form("f%sName=\"%s\"", col, name));
+    if (rc2<0)       // Dummy mode
+        return 0;
+    if (rc2==kFALSE) // Query failed
+        return -1;
+
+    const Int_t key = QueryKeyOfName(col, name, kFALSE);
+    if (key>0)
+    {
+        cout << " - New " << col << ": " << name << endl;
+        return key;
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the column of an entry in a table is existing and not null.
+// The entry is defined by column=test (column name) and a optional
+// WHERE statement.
+//
+Bool_t MSQLMagic::ExistStr(const char *column, const char *table, const char *test, const char *where)
+{
+    TString query = test ?
+        Form("SELECT %s FROM %s WHERE %s='%s' %s %s", column, table, column, test, where?"AND":"", where?where:"") :
+        Form("SELECT %s FROM %s WHERE %s", column, table, where);
+
+    TSQLResult *res = Query(query);
+    if (!res)
+        return kFALSE;
+
+    Bool_t rc = kFALSE;
+
+    TSQLRow *row=res->Next();
+    if (row && (*row)[0])
+        rc=kTRUE;
+
+    if (row)
+        delete row;
+
+    delete res;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if at least one row with one field exists in table
+// defined by where
+//
+Bool_t MSQLMagic::ExistRow(const char *table, const char *where)
+{
+    return ExistStr("*", table, 0, where);
+}
+
+// --------------------------------------------------------------------------
+//
+// An abbreviation for an Insert-Query.
+//
+// It builds "INSERT table SET vars"
+// The whitespaces are already conatined.
+//
+// On success kTRUE is returned, kFALSE otherwise.
+// In Dummy mode no query is send an -1 is returned.
+//
+Int_t MSQLMagic::Insert(const char *table, const char *vars, const char *where)
+{
+    // Build query
+    TString query("INSERT ");
+    query += table;
+    query += " SET ";
+    query += vars;
+    if (!TString(where).IsNull())
+    {
+        query += ", ";
+        query += where;
+    }
+
+    // Check for dummy mode
+    if (fIsDummy)
+    {
+        cout << "MSQLMagic - DUMMY: " << query << endl;
+        return -1;
+    }
+
+    // Execute query
+    if (Exec(query))
+        return kTRUE;
+
+    // Return error on failure
+    cout << "Error - Insert failed: " << query << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// An abbreviation for an Update-Query.
+//
+// It builds "UPDATE table SET vars WHERE where"
+// The whitespaces are already conatined.
+//
+// On success kTRUE is returned, kFALSE otherwise.
+// In Dummy mode no query is send an -1 is returned.
+//
+Int_t MSQLMagic::Update(const char *table, const char *vars, const char *where)
+{
+    // Build query
+    TString query("UPDATE ");
+    query += table;
+    query += " SET ";
+    query += vars;
+
+    if (!TString(where).IsNull())
+    {
+        query += " WHERE ";
+        query += where;
+    }
+
+    // Check for dummy mode
+    if (fIsDummy)
+    {
+        cout << "MSQLMagic - DUMMY: " << query << endl;
+        return -1;
+    }
+
+    // Execute Query
+    if (Exec(query))
+        return kTRUE;
+
+    // return kFALSE on failure
+    cout << "Error - Update failed: " << query << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// An abbreviation for checking the existance with ExistStr and
+// calling insert or update respectively.
+//
+Int_t MSQLMagic::InsertUpdate(const char *table, const char *col, const char *val, const char *vars)
+{
+    return ExistStr(col, table, val) ?
+        Update(table, vars, Form("%s='%s'", col, val)) :
+        Insert(table, vars, Form("%s='%s'", col, val));
+}
+
+// --------------------------------------------------------------------------
+//
+// An abbreviation for checking whether a row with the condition where
+// exists. If no such row exist Insert vars into table, otherwise update
+// vars in table at row(s) defined by where.
+//
+Int_t MSQLMagic::InsertUpdate(const char *table, const char *vars, const char *where)
+{
+    return ExistRow(table, where) ?
+        Update(table, vars, where) :
+        Insert(table, vars);
+}
+
+// --------------------------------------------------------------------------
+//
+// An abbreviation for a Dalete-Query.
+//
+// It builds "DELETE FROM table WHERE where"
+// The whitespaces are already conatined.
+//
+// On success kTRUE is returned, kFALSE otherwise.
+// In Dummy mode no query is send an -1 is returned.
+//
+Int_t MSQLMagic::Delete(const char *table, const char *where)
+{
+    // Build query
+    TString query("DELETE FROM ");
+    query += table;
+    query += " WHERE ";
+    query += where;
+
+    // Check for dummy mode
+    if (fIsDummy)
+    {
+        cout << "MSQLMagic - DUMMY: " << query << endl;
+        return -1;
+    }
+
+    // Execute query
+    if (Exec(query))
+        return kTRUE;
+
+    // return kFALSE on failure
+    cout << "Error - Delete failed: " << query << endl;
+    return kFALSE;
+}
+
Index: branches/Mars_McMismatchStudy/msql/MSQLMagic.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/MSQLMagic.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MSQLMagic.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MSQLMagic
+#define MARS_MSQLMagic
+
+#ifndef MARS_MSQLServer
+#include "MSQLServer.h"
+#endif
+
+class MSQLMagic : public MSQLServer
+{
+    Bool_t fIsDummy;
+
+public:
+    MSQLMagic(TSQLServer *serv, const char *dbname=0, const char *tname=0, const char *col=0) :
+        MSQLServer(serv, dbname, tname, col), fIsDummy(kFALSE)
+    {
+    }
+
+    MSQLMagic(const char *connection, const char *user, const char *password) :
+        MSQLServer(connection, user, password), fIsDummy(kFALSE)
+    {
+    }
+
+    MSQLMagic(const char *link) : MSQLServer(link), fIsDummy(kFALSE)
+    {
+    }
+
+    MSQLMagic(TEnv &env, const char *prefix=0) :
+        MSQLServer(env, prefix), fIsDummy(kFALSE)
+    {
+    }
+
+    MSQLMagic() : MSQLServer(), fIsDummy(kFALSE)
+    {
+    }
+
+
+    void SetIsDummy(Bool_t dummy=kTRUE) { fIsDummy=dummy; }
+    Bool_t IsDummy() const { return fIsDummy; }
+
+    TString QueryValOf(TString col, const char *ext, const char *key);
+    TString QueryValOfKey(TString col, const char *key);
+    TString QueryNameOfKey(TString col, const char *key);
+    Int_t   QueryKeyOfName(const char *col, const char *name, Bool_t insert=kTRUE);
+    Int_t   QueryKeyOfVal(const char *col, const char *val);
+    Int_t   QueryKeyOf(const char *col, const char *ext, const char *val);
+    Bool_t  ExistStr(const char *column, const char *table, const char *test, const char *where=0);
+    Bool_t  ExistRow(const char *table, const char *where);
+
+    Int_t Insert(const char *table, const char *vars, const char *where=0);
+    Int_t Update(const char *table, const char *vars, const char *where=0);
+    Int_t Delete(const char *table, const char *where);
+    Int_t InsertUpdate(const char *table, const char *col, const char *val, const char *vars);
+    Int_t InsertUpdate(const char *table, const char *vars, const char *where);
+
+    void Delete(const Option_t *o) { TObject::Delete(o); }
+
+    ClassDef(MSQLMagic, 0) // An enhancement of MSQLServer featuring our database
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/msql/MSQLServer.cc
===================================================================
--- branches/Mars_McMismatchStudy/msql/MSQLServer.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MSQLServer.cc	(revision 17960)
@@ -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): Thomas Bretz 2/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+
+////////////////////////////////////////////////////////////////////////
+//
+//  MSQLServer
+//
+//  Using this instead of a TSQLServer gives the possibility to
+//  browse a database server through the TBrowser and it will offer
+//  many features usefull working with relational tables.
+//
+//  Use it like TSQlServer:
+//    new MSQLServer("mysql://localhost:3306?compress", "hercules", "stdmagicpassword");
+//    // now start your TBrowser
+//    new TBrowser;
+//
+////////////////////////////////////////////////////////////////////////
+#include "MSQLServer.h"
+
+#include <iostream>
+#include <iomanip>
+#include <stdlib.h>
+
+#include <TROOT.h>
+#include <TMath.h>
+
+#include <TH1.h>
+#include <TEnv.h>
+#include <TPRegexp.h>
+
+#include <TSQLResult.h>
+#include <TSQLServer.h>
+#include <TSQLRow.h>
+
+#include <TBrowser.h>
+
+#include <TObjString.h>
+#include <TObjArray.h>
+
+#include "MTreeSQL.h"
+
+ClassImp(MSQLServer);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Used in virtual function TObject::Browse() to create the
+//
+void MSQLServer::BrowseColumn(TBrowser *b) /*FOLD00*/
+{
+    if (!fServ)
+        return;
+
+    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 ? (*row)[1] : "");
+
+    if (row)
+        delete row;
+
+    delete res;
+
+    const Bool_t isnum =
+        !desc.Contains("char", TString::kIgnoreCase) &&
+        !desc.Contains("text", TString::kIgnoreCase);
+
+    cout << query1 << endl;
+    res = fServ->Query(query1);
+    if (!res)
+    {
+        cout << "query - failed: " << query1 << endl;
+        return;
+    }
+
+    TArrayD arr(2);
+    Int_t num=0;
+    Double_t max=0;
+    Double_t min=0;
+    Double_t sum=0;
+    Double_t sqr=0;
+
+    while ((row=res->Next()))
+    {
+        const TString row0((*row)[0]);
+
+        if (!isnum)
+        {
+            cout << row0 << endl;
+            continue;
+        }
+
+        if (num==arr.GetSize())
+            arr.Set(arr.GetSize()*2);
+
+        arr[num] = atof(row0.Data());
+
+        if (num==0)
+            min=max=arr[0];
+
+        if (arr[num]>max) max = arr[num];
+        if (arr[num]<min) min = arr[num];
+
+        sum += arr[num];
+        sqr += arr[num]*arr[num];
+
+        num++;
+    }
+
+    delete res;
+
+    if (!isnum)
+        return;
+
+    if (max==min) max += 1;
+
+    Int_t num0 = 1;
+
+    if (num>0)
+    {
+        /*
+         cout << "Num:   " << num << endl;
+         cout << "Mean:  " << sum/num << endl;
+         cout << "Range: " << max-min << endl;
+         cout << "RMS:   " << TMath::Sqrt(sqr/num-sum*sum/num/num) << endl;
+         */
+
+        num0 = (Int_t)((max-min)*40/TMath::Sqrt(sqr/num-sum*sum/num/num));
+    }
+
+    const TString title(Form("#splitline{%s}{<%s>}", (const char*)query1, (const char*)desc));
+
+    TH1F *hist=new TH1F(fColumn, title, num0, min, max);
+    for (int i=0; i<num; i++)
+        hist->Fill(arr[i]);
+
+    //cout << "Done." << endl;
+
+    hist->Draw();
+    hist->SetBit(kCanDelete);
+}
+
+void MSQLServer::BrowseTable(TBrowser *b) /*FOLD00*/
+{
+    if (!fServ)
+        return;
+
+    TSQLResult *res = fServ->GetColumns(fDataBase, fTable);
+    if (!res)
+        return;
+
+    TSQLRow *row;
+    while ((row=res->Next()))
+    {
+        TString row0((*row)[0]);
+        delete row;
+
+        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*/
+{
+    if (!fServ)
+        return;
+
+    TSQLResult *res = fServ->GetTables(fDataBase);
+    if (!res)
+        return;
+
+    TSQLRow *row;
+    while ((row=res->Next()))
+    {
+        TString row0((*row)[0]);
+        delete row;
+
+        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*/
+{
+    if (!fServ)
+        return;
+
+    TSQLResult *res = fServ->GetDataBases();
+    if (!res)
+        return;
+
+    TSQLRow *row;
+    while ((row=res->Next()))
+    {
+        const TString row0((*row)[0]);
+        delete row;
+
+        MSQLServer *sql = (MSQLServer*)fList.FindObject(row0);
+        if (!sql)
+        {
+            sql = new MSQLServer(fServ, row0);
+            fList.Add(sql);
+        }
+        b->Add(sql, row0);
+    }
+}
+
+void MSQLServer::PrintLine(const TArrayI &max) /*FOLD00*/
+{
+    cout << "+" << setfill('-');
+    for (int i=0; i<max.GetSize(); i++)
+        cout << setw(max[i]+1) << "-" << "-+";
+    cout << endl;
+}
+
+void MSQLServer::PrintTable(TSQLResult &res) /*FOLD00*/
+{
+    Int_t n = res.GetFieldCount();
+
+    TArrayI max(n);
+
+    for (int i=0; i<n; i++)
+        max[i] = strlen(res.GetFieldName(i));
+
+    TSQLRow *row;
+
+    TList rows;
+    rows.SetOwner();
+
+    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*/
+{
+    if (!fServ)
+        return "";
+
+    TSQLResult *res = fServ->GetColumns(fDataBase, fTable);
+    if (!res)
+        return "";
+
+    TString fields;
+
+    TSQLRow *row;
+
+    TList rows;
+    rows.SetOwner();
+
+    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*/
+{
+    if (!fServ)
+        return;
+
+    TSQLResult *res = fServ->Query(query);
+    if (res)
+    {
+        PrintTable(*res);
+        delete res;
+    }
+    else
+        cout << "Query failed: " << query << endl;
+}
+
+void MSQLServer::Print(Option_t *o) const /*FOLD00*/
+{
+    const TString opt(o);
+    if (!opt.IsNull())
+    {
+        PrintQuery(o);
+        return;
+    }
+
+    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)
+    {
+        fServ->Close(option);
+        if (TestBit(kIsOwner))
+        {
+            fTrees.Delete();
+
+            delete fServ;
+            fServ=0;
+            ResetBit(kIsOwner);
+            fType=kIsZombie;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Send a SQL query to the SQL server.
+//
+// If MSQLServer is no server (column, row, ...) NULL is returned and an
+//  error message is send to stdout.
+//
+// If the query failed for some reason an error message is send to stdout
+//  and NULL is returned.
+//
+// If everything works fine a TSQLResult is returned. Make sure that you
+// delete it!
+//
+TSQLResult *MSQLServer::Query(const char *sql) /*FOLD00*/
+{
+    if (!fServ)
+        return NULL;
+
+    if (fType!=kIsServer)
+    {
+        cout << "ERROR: MSQLServer::Query - this is not a server!" << endl;
+        return NULL;
+    }
+
+    TSQLResult *res = fServ->Query(sql);
+    if (!res)
+    {
+        cout << /*"ERROR: MSQLServer::Query - Query failed: " <<*/ sql << endl;
+        return NULL;
+    }
+
+    return res;
+}
+
+// --------------------------------------------------------------------------
+//
+// Send a SQL query to the SQL server.
+//
+// If MSQLServer is no server (column, row, ...) NULL is returned and an
+//  error message is send to stdout.
+//
+// If the query failed kFALSE is returned.
+//
+// On success kTRUE is returned.
+//
+Bool_t MSQLServer::Exec(const char* sql)
+{
+    if (!fServ)
+        return kFALSE;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(5,12,00)
+    TSQLResult *res = fServ->Query(sql);
+    if (!res)
+    {
+        cout << "ERROR: MSQLServer::Exec - Query failed: " << sql << endl;
+        return kFALSE;
+    }
+    delete res;
+    return kTRUE;
+#else
+    if (fType!=kIsServer)
+    {
+        cout << "ERROR: MSQLServer::Exec - this is not a server!" << endl;
+        return kFALSE;
+    }
+
+    return fServ->Exec(sql);
+#endif
+}
+
+Int_t MSQLServer::SelectDataBase(const char *dbname) /*FOLD00*/
+{
+    fDataBase = dbname;
+    return fType==kIsServer && fServ ? fServ->SelectDataBase(dbname) : 0;
+}
+
+TSQLResult *MSQLServer::GetDataBases(const char *wild) /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->GetDataBases(wild) : NULL;
+}
+
+TSQLResult *MSQLServer::GetTables(const char *wild, const char *dbname) /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->GetTables(dbname?dbname:fDataBase.Data(), wild) : NULL;
+}
+
+TSQLResult *MSQLServer::GetColumns(const char *table, const char *wild, const char *dbname) /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->GetColumns(dbname?dbname:fDataBase.Data(), table, wild) : NULL;
+}
+
+Int_t MSQLServer::CreateDataBase(const char *dbname) /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->CreateDataBase(dbname) : 0;
+}
+
+Int_t MSQLServer::DropDataBase(const char *dbname) /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->DropDataBase(dbname) : 0;
+}
+
+Int_t MSQLServer::Reload() /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->Reload() : 0;
+}
+
+Int_t MSQLServer::Shutdown() /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->Shutdown() : 0;
+}
+
+const char *MSQLServer::ServerInfo() /*FOLD00*/
+{
+    return fType==kIsServer && fServ ? fServ->ServerInfo() : "";
+}
+
+Bool_t MSQLServer::IsConnected() const
+{
+    return fType==kIsServer && fServ ? fServ->IsConnected() : kFALSE;
+}
+
+const char *MSQLServer::GetName() const
+{
+    if (!fServ)
+        return "Unconnected!";
+
+    switch (fType)
+    {
+    case kIsServer:   return Form("%s://%s:%d/%s", fServ->GetDBMS(), fServ->GetHost(), fServ->GetPort(), fDataBase.Data());
+    case kIsDataBase: return GetNameDataBase();
+    case kIsTable:    return GetNameTable();
+    case kIsColumn:   return GetNameColumn();
+    default:          return "n/a";
+    }
+}
+
+Bool_t MSQLServer::Split(TString &url, TString &user, TString &pasw) const
+{
+    const Ssiz_t pos1 = url.First("://")+3;
+    const Ssiz_t pos2 = url.Last(':')   +1;
+    const Ssiz_t pos3 = url.First('@');
+
+    if (pos1<0 || pos2<0 || pos3<0 || pos1>pos2 || pos2>pos3)
+        return kFALSE;
+
+    user = url(pos1, pos2-pos1-1);
+    pasw = url(pos2, pos3-pos2);
+
+    url.Remove(pos1, pos3+1-pos1);
+
+    return kTRUE;
+}
+
+void MSQLServer::Init(const char *connection, const char *user, const char *password) /*FOLD00*/
+{
+    fType = kIsZombie;
+
+    fServ = TSQLServer::Connect(connection, user, password);
+    if (fServ)
+    {
+        gROOT->GetListOfBrowsables()->Add(this, connection);
+        fType = kIsServer;
+        SetBit(kIsOwner);
+        SetBit(kMustCleanup);
+    }
+    else
+        fType = kIsZombie;
+
+    fList.SetOwner();
+}
+
+void MSQLServer::InitEnv(TEnv &env, const char *prefix)
+{
+    TString url  = env.GetValue("URL",      "");
+    TString db   = env.GetValue("Database", "");
+    TString user = env.GetValue("User",     "");
+    TString pass = env.GetValue("Password", "");
+
+    user = env.GetValue(Form("%s.User", db.Data()), user);
+
+    pass = env.GetValue(Form("%s.Password", user.Data()), pass);
+    pass = env.GetValue(Form("%s.%s.Password", db.Data(), user.Data()), pass);
+
+    if (prefix)
+    {
+        url = env.GetValue(Form("%s.URL", prefix), url);
+        db  = env.GetValue(Form("%s.Database", prefix), db);
+
+        user = env.GetValue(Form("%s.User", prefix), user);
+        user = env.GetValue(Form("%s.%s.User", prefix, db.Data()), user);
+
+        pass = env.GetValue(Form("%s.Password", prefix), pass);
+        pass = env.GetValue(Form("%s.%s.Password", prefix, user.Data()), pass);
+        pass = env.GetValue(Form("%s.%s.%s.Password", prefix, db.Data(), user.Data()), pass);
+    }
+
+    user = user.Strip(TString::kBoth);
+    pass = pass.Strip(TString::kBoth);
+    url  = url.Strip(TString::kBoth);
+
+    if (user.IsNull() && pass.IsNull())
+    {
+        if (!Split(url, user, pass))
+        {
+            fType = kIsZombie;
+            return;
+        }
+    }
+
+    Init(url, user, pass);
+
+    if (IsConnected() && !db.IsNull())
+        SelectDataBase(db);
+}
+
+MSQLServer::MSQLServer(const char *connection, const char *user, const char *password) /*FOLD00*/
+{
+    Init(connection, user, password);
+}
+
+// --------------------------------------------------------------------------
+//
+// Instantiate a dabase connection either by
+//   mysql://user:password@url/database
+// or by a resource file (in teh given string doesn't contain mysql://)
+//
+MSQLServer::MSQLServer(const char *u) : fType(kIsZombie) /*FOLD00*/
+{
+    if (TString(u).Contains("mysql://", TString::kIgnoreCase))
+    {
+        TString url(u);
+        TString user, pasw;
+
+        if (!Split(url, user, pasw))
+        {
+            fType = kIsZombie;
+            return;
+        }
+        Init(url, user, pasw);
+    }
+    else
+    {
+        TEnv env(u);
+        InitEnv(env);
+    }
+}
+
+MSQLServer::MSQLServer(TEnv &env, const char *prefix)
+{
+    InitEnv(env, prefix);
+}
+
+MSQLServer::MSQLServer()
+{
+    if (gEnv)
+        InitEnv(*gEnv);
+}
+
+MSQLServer::MSQLServer(MSQLServer &serv)
+{
+    fServ = serv.fServ;
+
+    fDataBase = serv.fDataBase;
+    fTable = serv.fTable;
+    fColumn = serv.fColumn;
+
+    fType = serv.fType;
+}
+
+MSQLServer::~MSQLServer() /*FOLD00*/
+{
+    if (gDebug>0)
+        cout << "Delete: " << GetName() << endl;
+
+    Close();
+}
+
+Bool_t MSQLServer::PrintError(const char *txt, const char *q) const /*FOLD00*/
+{
+    cout << "Fatal error acessing database: " << txt << endl;
+    cout << "Query: " << q << endl;
+    return kFALSE;
+}
+
+TString MSQLServer::GetEntry(const char *where, const char *col, const char *table) const /*FOLD00*/
+{
+    if (!fServ)
+        return "";
+
+    if (table==0)
+        table = Form("%s.%s", (const char *)fDataBase, (const char*)fTable);
+    if (col==0)
+        col = (const char *)fColumn;
+
+    const TString query(Form("SELECT %s FROM %s WHERE %s", col, table, where));
+
+    TSQLResult *res = fServ->Query(query);
+    if (!res)
+        return (PrintError("GetEntry - TSQLResult==NULL", query), "");
+
+    if (res->GetFieldCount()!=1)
+    {
+        delete res;
+        return (PrintError("GetEntry - Number of columns != 1", query), "");
+    }
+
+    if (res->GetRowCount()>1)
+    {
+        delete res;
+        return (PrintError("GetEntry - Number of rows > 1", query), "");
+    }
+
+    if (res->GetRowCount()==0)
+    {
+        delete res;
+        return "";
+    }
+
+    const char *fld = res->Next()->GetField(0);
+    if (!fld)
+    {
+        delete res;
+        return (PrintError("GetEntry - Entry is empty", query), "");
+    }
+
+    const TString rc(fld);
+    delete res;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the name of the (first) column with a primary key
+//
+TString MSQLServer::GetPrimaryKeys(const char *table)
+{
+    TSQLResult *res = GetColumns(table);
+    if (!res)
+        return "";
+
+    TObjArray arr;
+    arr.SetOwner();
+
+    TSQLRow *row = 0;
+    while ((row=res->Next()))
+    {
+        const TString key = (*row)[3];
+        if (key=="PRI")
+            arr.Add(new TObjString((*row)[0]));
+        delete row;
+    }
+    delete res;
+
+    arr.Sort();
+
+    TString rc;
+    for (int i=0; i<arr.GetEntries(); i++)
+    {
+        if (i>0)
+            rc += ", ";
+        rc += arr[i]->GetName();
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches in the text for patterns like "Table.Column". If such a pettern
+// is found the primary key of the table is requested a "LEFT JOIN"
+// with this Table is added ON the identity of the primary key of Table
+// with the given table.
+//
+TString MSQLServer::GetJoins(const char *table, const TString text)
+{
+    Int_t p=0;
+
+    TString mods;
+    TArrayI pos;
+
+    // Find all Table.Column expression. Because also floating point
+    // numbers can contain a dot the result has to be checked carefully
+    TString joins;
+    TPRegexp reg = TPRegexp("\\w+[.]\\w+");
+    while (1)
+    {
+        // Check whether expression is found
+        if (reg.Match(text, mods, p, 130, &pos)==0)
+            break;
+
+        // Get expression from text
+        const TString expr = text(pos[0], pos[1]-pos[0]);
+        p = pos[1];
+
+        if (expr.IsFloat())
+            continue;
+
+        const TString tab = expr(0, expr.First('.'));
+        //const TString var = expr(expr.First('.')+1, expr.Length());
+
+        // If the table found is the primary table itself skip it.
+        if (tab==table)
+            continue;
+
+        // If this join has already be set, skip it.
+        if (joins.Contains(Form(" %s ", tab.Data())))
+            continue;
+
+        // Now get the primary key of the table to be joined
+        const TString prim = GetPrimaryKeys(tab);
+        if (prim.IsNull())
+            continue;
+
+        joins += Form("LEFT JOIN %s USING (%s) ", tab.Data(), prim.Data());
+    }
+
+    if (!joins.IsNull())
+        joins += " ";
+
+    return joins;
+}
+
+MTreeSQL *MSQLServer::GetTree(TString table, TString addon)
+{
+    if (fType!=kIsServer || !fServ || !TestBit(kIsOwner))
+        return 0;
+
+    TIter Next(&fTrees);
+    TObject *o = 0;
+    while ((o=Next()))
+    {
+        if (o->GetName()==table && o->GetName()==addon)
+            return (MTreeSQL*)o;
+    }
+
+    MTreeSQL *t = new MTreeSQL(this, table, addon);
+    fTrees.Add(t);
+
+    return t;
+}
+
+void MSQLServer::RecursiveRemove(TObject *obj)
+{
+    if (fServ==obj)
+    {
+        fServ=NULL;
+        fType = kIsZombie;
+        ResetBit(kIsOwner);
+    }
+}
Index: branches/Mars_McMismatchStudy/msql/MSQLServer.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/MSQLServer.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MSQLServer.h	(revision 17960)
@@ -0,0 +1,151 @@
+#ifndef MARS_MSQLServer
+#define MARS_MSQLServer
+
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+
+class TEnv;
+class TArrayI;
+
+class TSQLServer;
+class TSQLResult;
+
+class MTreeSQL;
+
+class MSQLServer : public TObject
+{
+private:
+    TSQLServer *fServ;
+    TList fTrees;
+
+    TString fDataBase;
+    TString fTable;
+    TString fColumn;
+
+    TList   fList;
+
+    enum Type_t { kIsZombie, kIsServer, kIsDataBase, kIsTable, kIsColumn };
+
+    Type_t  fType;
+
+    enum { kIsOwner=BIT(14) };
+
+    Bool_t IsFolder() const { return kTRUE; }
+
+    Bool_t PrintError(const char *txt, const char *q) const;
+
+    TString GetFields() const;
+
+    void BrowseDataBase(TBrowser *b);
+    void BrowseTable(TBrowser *b);
+    void BrowseColumn(TBrowser *b);
+    void BrowseServer(TBrowser *b);
+
+    void Browse(TBrowser *b)
+    {
+        if (!b)
+            return;
+
+        switch (fType)
+        {
+        case kIsServer:   BrowseServer(b);   break;
+        case kIsDataBase: BrowseDataBase(b); break;
+        case kIsTable:    BrowseTable(b);    break;
+        case kIsColumn:   BrowseColumn(b);   break;
+        default:
+            break;
+        }
+    }
+
+    const char *GetNameTable()    const { return Form("%s/%s",    (const char*)fDataBase, (const char*)fTable); }
+    const char *GetNameColumn()   const { return Form("%s/%s/%s", (const char*)fDataBase, (const char*)fTable, (const char*)fColumn); }
+
+    Bool_t Split(TString &url, TString &user, TString &pasw) const;
+
+    void Init(const char *connection, const char *user, const char *password);
+    void InitEnv(TEnv &env, const char *prefix=0);
+
+public:
+    MSQLServer(TSQLServer *serv, const char *dbname=0, const char *tname=0, const char *col=0)
+        : fServ(serv), fDataBase(dbname), fTable(tname), fColumn(col), fType(kIsZombie)
+    {
+        fList.SetOwner();
+
+        fType = kIsColumn;
+
+        if (fColumn.IsNull())
+            fType = kIsTable;
+
+        if (fTable.IsNull() && fColumn.IsNull())
+            fType = kIsDataBase;
+
+        if (fDataBase.IsNull() && fTable.IsNull() && fColumn.IsNull())
+            fType = kIsZombie;
+
+        if (!serv)
+            fType = kIsZombie;
+    }
+
+    MSQLServer(const char *connection, const char *user, const char *password);
+    MSQLServer(const char *link);
+    MSQLServer(TEnv &env, const char *prefix=0);
+    MSQLServer(MSQLServer &serv);
+    MSQLServer();
+    ~MSQLServer();
+
+    static void PrintLine(const TArrayI &max);
+    static void PrintTable(TSQLResult &res);
+
+    const char *GetName() const;
+    const char *GetNameDataBase() const { return fDataBase; }
+
+    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);
+    Bool_t      Exec(const char* sql);
+    Int_t       SelectDataBase(const char *dbname);
+    TSQLResult *GetDataBases(const char *wild = 0);
+    TSQLResult *GetTables(const char *wild = 0, const char *dbname = 0);
+    TSQLResult *GetColumns(const char *table, const char *wild = 0, const char *dbname = 0);
+    Int_t       CreateDataBase(const char *dbname);
+    Int_t       DropDataBase(const char *dbname);
+    Int_t       Reload();
+    Int_t       Shutdown();
+    const char *ServerInfo();
+    Bool_t      IsConnected() const;
+
+    TString     GetEntry(const char *where, const char *col=0, const char *table=0) const;
+    TString     GetPrimaryKeys(const char *table);
+    TString     GetJoins(const char *table, const TString text);
+
+    void RecursiveRemove(TObject *obj);
+
+    MTreeSQL   *GetTree(TString table, TString addon="");
+
+    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: branches/Mars_McMismatchStudy/msql/MSqlInsertRun.cc
===================================================================
--- branches/Mars_McMismatchStudy/msql/MSqlInsertRun.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MSqlInsertRun.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/msql/MSqlInsertRun.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/MSqlInsertRun.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MSqlInsertRun.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/msql/MTreeSQL.cc
===================================================================
--- branches/Mars_McMismatchStudy/msql/MTreeSQL.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MTreeSQL.cc	(revision 17960)
@@ -0,0 +1,361 @@
+// @(#)root/tree:$Id: MTreeSQL.cxx 43270 2012-03-06 22:46:11Z pcanal $
+// Author: Philippe Canal and al. 08/2004
+
+/*************************************************************************
+ * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
+
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MTreeSQL                                                             //
+//                                                                      //
+// Implement TTree for a SQL backend                                    //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+
+#include <Riostream.h>
+#include <map>
+#include <stdlib.h>
+
+#include "TString.h"
+#include "TROOT.h"
+#include "TSystem.h"
+#include "TError.h"
+#include "TFile.h"
+#include "TTree.h"
+#include "TLeaf.h"
+#include "TBranch.h"
+#include "TPRegexp.h"
+
+#include "TSQLRow.h"
+#include "TSQLResult.h"
+
+#include "MSQLServer.h"
+
+#include "MTreeSQL.h"
+#include "MBasketSQL.h"
+
+ClassImp(MTreeSQL);
+
+using namespace std;
+
+//______________________________________________________________________________
+MTreeSQL::MTreeSQL(MSQLServer *server, const TString& table, const TString &addon) :
+    TTree(table, addon, 0), fServer(server), fQuery(table+" "+addon), fResult(0), fRow(0)
+{
+    fEntries = 0;
+
+    if (fServer==0)
+    {
+        Error("MTreeSQL","No TSQLServer specified");
+        return;
+    }
+
+    fTables.push_back(table);
+
+    // Constructor with an explicit TSQLServer
+    TPRegexp reg(" +JOIN +([a-zA-Z0-9_.]+)");
+
+    Int_t p = -1;
+    while (p<addon.Length())
+    {
+        TArrayI pos;
+        if (reg.Match(addon, "ig", ++p, 100, &pos)!=2)
+            continue;
+
+        if (pos[2] >= 0 && pos[3] >= 0)
+        {
+            const TString subStr = addon(pos[2], pos[3]-pos[2]);
+            fTables.push_back(subStr);
+        }
+
+        p = pos[3];
+    }
+
+    for (auto it=fTables.begin(); it!=fTables.end(); it++)
+        if (!CheckTable(*it))
+            return;
+
+    Init();
+}
+
+MTreeSQL::~MTreeSQL()
+{
+    for (auto it=fRows.begin(); it!=fRows.end(); it++)
+        delete *it;
+
+    delete fResult;
+}
+
+//______________________________________________________________________________
+Bool_t MTreeSQL::CheckTable(const TString &table) const
+{
+    // Check the table exist in the database
+    if (fServer==0)
+        return kFALSE;
+
+    TSQLResult *tables = fServer->GetTables(table);
+    if (!tables)
+        return kFALSE;
+
+    TSQLRow * row = 0;
+    while ((row = tables->Next()))
+    {
+        if (table.CompareTo(row->GetField(0),TString::kIgnoreCase)==0)
+            return kTRUE;
+
+        delete row;
+    }
+    delete tables;
+
+    // The table is a not a permanent table, let's see if it is a 'temporary' table
+    const Int_t before = gErrorIgnoreLevel;
+    gErrorIgnoreLevel = kFatal;
+
+    TSQLResult *res = fServer->GetColumns(table);
+    if (res)
+        delete res;
+
+    gErrorIgnoreLevel = before;
+
+    if (!res)
+        Error("CheckTable", "%s", ("Table "+table+" not found.").Data());
+
+    return res ? kTRUE : kFALSE;
+}
+
+//______________________________________________________________________________
+void MTreeSQL::Init()
+{
+   // Initializeation routine
+   // Number of entries needed to create the branches
+   //GetEntries();
+
+   vector<pair<TString,TString>> cols;
+
+   for (auto it=fTables.begin(); it!=fTables.end(); it++)
+   {
+       TSQLResult *res = fServer->GetColumns(*it);
+
+       TSQLRow *row = 0;
+       while ((row=res->Next()))
+       {
+           TString f1 = row->GetField(1);
+
+           Int_t p0 = f1.First('(');
+           if (p0<0)
+               p0 = f1.First(' ');
+           if (p0<0)
+               p0 = f1.Length();
+
+           const TString type = f1(0, p0);
+
+           if (type.CompareTo("int",       TString::kIgnoreCase) &&
+               type.CompareTo("date",      TString::kIgnoreCase) &&
+               type.CompareTo("time",      TString::kIgnoreCase) &&
+               type.CompareTo("datetime",  TString::kIgnoreCase) &&
+               type.CompareTo("year",      TString::kIgnoreCase) &&
+               type.CompareTo("timestamp", TString::kIgnoreCase) &&
+               type.CompareTo("bit",       TString::kIgnoreCase) &&
+               type.CompareTo("tinyint",   TString::kIgnoreCase) &&
+               type.CompareTo("smallint",  TString::kIgnoreCase) &&
+               type.CompareTo("mediumint", TString::kIgnoreCase) &&
+               type.CompareTo("integer",   TString::kIgnoreCase) &&
+               type.CompareTo("bigint",    TString::kIgnoreCase) &&
+               type.CompareTo("decimal",   TString::kIgnoreCase) &&
+               type.CompareTo("int",       TString::kIgnoreCase) &&
+               type.CompareTo("real",      TString::kIgnoreCase) &&
+               type.CompareTo("float",     TString::kIgnoreCase) &&
+               type.CompareTo("double",    TString::kIgnoreCase))
+           {
+               Info("Init", "%s", ("Skipping "+*it+"."+TString(row->GetField(0))+" ["+type+"]").Data());
+               continue;
+           }
+
+           const TString name = *it+"."+row->GetField(0);
+           cols.push_back(make_pair(name, type));
+
+           delete row;
+       }
+       delete res;
+   }
+
+   TString list;
+   for (auto it=cols.begin(); it!=cols.end(); it++)
+       list += ","+it->first;
+
+   list.Remove(0, 1);
+
+   fResult = fServer->Query(("SELECT "+list+" FROM "+fQuery).Data());
+   if (!fResult)
+       return;
+
+   TSQLRow *row = 0;
+   while ((row=(TSQLRow*)fResult->Next()))
+       fRows.push_back(row);
+
+   fEntries = fRows.size();
+
+   // ==============================================================
+
+   // determine leaf description string
+   Int_t idx = 0;
+   for (auto it=cols.begin(); it!=cols.end(); it++, idx++)
+   {
+       const TString name = it->first;
+
+       TBranch *br = TTree::Branch(name, 0, name+"/D");
+
+       br->ResetAddress();
+       br->SetEntries(fEntries);
+
+       auto entry = br->GetBasketEntry();
+       entry[0] = 0;
+       entry[1] = fEntries;
+
+       TBasket *bsk = new MBasketSQL(br, &fRow, idx, it->second);
+
+       br->GetListOfBaskets()->AddAtAndExpand(bsk, 0);
+   }
+}
+
+//______________________________________________________________________________
+Long64_t  MTreeSQL::GetEntries() const
+{
+   // Get the number of rows in the database
+    return GetEntriesFast();
+}
+
+//______________________________________________________________________________
+Long64_t  MTreeSQL::GetEntriesFast()    const
+{
+   // Return the number of entries as of the last check.
+   // Use GetEntries for a more accurate count.
+
+   return fEntries;
+}
+
+//______________________________________________________________________________
+Long64_t MTreeSQL::LoadTree(Long64_t entry)
+{
+    // Setup the tree to the load the specified entry.
+    // Make sure the server and result set are setup for the requested entry
+    if (entry<0 || entry>=fEntries)
+        return -1;
+
+    fReadEntry = entry;
+    fRow = fRows[entry];
+
+    return entry;
+}
+
+//______________________________________________________________________________
+void MTreeSQL::Refresh()
+{
+    if (!fServer)
+        return;
+
+    //  Refresh contents of this Tree and his branches from the current
+    //  Tree status in the database
+    //  One can call this function in case the Tree on its file is being
+    //  updated by another process
+    for (auto it=fRows.begin(); it!=fRows.end(); it++)
+        delete *it;
+
+    fRows.clear();
+
+    delete fResult;
+
+    Init();
+}
+
+//______________________________________________________________________________
+TBranch* MTreeSQL::BranchImp(const char *, const char *,
+                             TClass *, void *, Int_t ,
+                             Int_t )
+{
+   // Not implemented yet
+
+   Fatal("BranchImp","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+TBranch* MTreeSQL::BranchImp(const char *, TClass *,
+                             void *, Int_t , Int_t )
+{
+   // Not implemented yet
+
+   Fatal("BranchImp","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+Int_t MTreeSQL::Branch(TCollection *, Int_t,
+                       Int_t, const char *)
+{
+   // Not implemented yet
+
+   Fatal("Branch","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+Int_t MTreeSQL::Branch(TList *, Int_t, Int_t)
+{
+   // Not implemented yet
+
+   Fatal("Branch","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+Int_t MTreeSQL::Branch(const char *, Int_t ,
+                       Int_t)
+{
+   // Not implemented yet
+
+   Fatal("Branch","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+TBranch* MTreeSQL::Bronch(const char *, const char *, void *,
+                          Int_t, Int_t)
+{
+   // Not implemented yet
+
+   Fatal("Bronc","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+TBranch* MTreeSQL::BranchOld(const char *, const char *,
+                             void *, Int_t, Int_t)
+{
+   // Not implemented yet
+
+   Fatal("BranchOld","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+TBranch *MTreeSQL::Branch(const char *, const char *, void *,
+                          Int_t, Int_t)
+{
+   // Not implemented yet
+
+   Fatal("Branch","Not implemented yet");
+   return 0;
+}
+
+//______________________________________________________________________________
+Int_t MTreeSQL::Fill()
+{
+   Fatal("Fill","Not implemented yet");
+   return -1;
+}
Index: branches/Mars_McMismatchStudy/msql/MTreeSQL.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/MTreeSQL.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/MTreeSQL.h	(revision 17960)
@@ -0,0 +1,87 @@
+// @(#)root/tree:$Id: MTreeSQL.h 30663 2009-10-11 22:11:51Z pcanal $
+// Author: Rene Brun   12/01/96
+
+/*************************************************************************
+ * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
+
+#ifndef ROOT_MTreeSQL
+#define ROOT_MTreeSQL
+
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MTreeSQL                                                             //
+//                                                                      //
+// A TTree object is a list of TBranch.                                 //
+//   To Create a TTree object one must:                                 //
+//    - Create the TTree header via the TTree constructor               //
+//    - Call the TBranch constructor for every branch.                  //
+//                                                                      //
+//   To Fill this object, use member function Fill with no parameters.  //
+//     The Fill function loops on all defined TBranch.                  //
+//                                                                      //
+// MTreeSQL is the TTree implementation interfacing with an SQL         //
+// database                                                             //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+
+
+#ifndef ROOT_TTree
+#include "TTree.h"
+#endif
+
+#include <vector>
+
+class MSQLServer;
+class TSQLRow;
+
+class MTreeSQL : public TTree
+{
+protected:
+   MSQLServer *fServer;
+
+   TString     fQuery;
+
+   TSQLResult *fResult;
+   TSQLRow    *fRow;
+
+   std::vector<TString>  fTables;
+   std::vector<TSQLRow*> fRows;
+
+   Bool_t CheckTable(const TString &table) const;
+   void   Init();
+
+   virtual TBranch *BranchImp(const char *branchname, const char *classname, TClass *ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel);
+   virtual TBranch *BranchImp(const char *branchname, TClass *ptrClass, void *addobj, Int_t bufsize, Int_t splitlevel);
+
+public:
+   MTreeSQL(MSQLServer *server, const TString& table, const TString &addon="");
+   ~MTreeSQL();
+
+   Int_t    Branch(TCollection *list, Int_t bufsize=32000, Int_t splitlevel=99, const char *name="");
+   Int_t    Branch(TList *list, Int_t bufsize=32000, Int_t splitlevel=99);
+   Int_t    Branch(const char *folder, Int_t bufsize=32000, Int_t splitlevel=99);
+   TBranch *Bronch(const char *name, const char *classname, void *addobj, Int_t bufsize=32000, Int_t splitlevel=99);
+   TBranch *BranchOld(const char *name, const char *classname, void *addobj, Int_t bufsize=32000, Int_t splitlevel=1);
+   TBranch *Branch(const char *name, void *address, const char *leaflist, Int_t bufsize) { return TTree::Branch(name, address, leaflist, bufsize); }
+#if !defined(__CINT__)
+   TBranch *Branch(const char *name, const char *classname, void *addobj, Int_t bufsize=32000, Int_t splitlevel=99);
+#endif
+
+   Int_t    Fill();
+   Long64_t GetEntries()    const;
+   Long64_t GetEntries(const char *sel) { return TTree::GetEntries(sel); }
+   Long64_t GetEntriesFast()const;
+   Long64_t LoadTree(Long64_t entry);
+
+   void     Refresh();
+
+   ClassDef(MTreeSQL,1);  // TTree Implementation read and write to a SQL database.
+};
+
+
+#endif
Index: branches/Mars_McMismatchStudy/msql/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/msql/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/Makefile	(revision 17960)
@@ -0,0 +1,36 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+############################################################
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Sql
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw -I../mfileio
+
+SRCFILES = \
+	MSQLServer.cc \
+        MSQLMagic.cc \
+	MTreeSQL.cc \
+	MBasketSQL.cc \
+	MBufferSQL.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/msql/SqlIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/SqlIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/SqlIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/msql/SqlLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/msql/SqlLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/msql/SqlLinkDef.h	(revision 17960)
@@ -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 MSQLColumn+;
+#pragma link C++ class MSQLServer+;
+
+#pragma link C++ class MSQLMagic+;
+
+#pragma link C++ class MTreeSQL+;
+#pragma link C++ class MBasketSQL+;
+#pragma link C++ class MBufferSQL+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mstarcam/MStarCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/MStarCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/MStarCam.cc	(revision 17960)
@@ -0,0 +1,113 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 04/2004 <mailto:jlopez@ifae.es>
+!   Author(s): Jordi Albert 04/2004 <mailto:albert@astro.uni-wuerzburg.de>
+!   Author(s): Robert Wagner 08/2004 <mailto:rwagner@mppmu.mpg.de>
+!                 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MStarCam                                                                //
+//                                                                         //
+// A Container to hold star positions in the camera                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MStarCam.h"
+
+#include <TList.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStarPos.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+// Default constructor. 
+//
+//
+MStarCam::MStarCam(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MStarCam";
+  fTitle = title ? title : "";
+  
+  fStars = new TList;
+
+  fInnerPedestalDC = 0.;
+  fOuterPedestalDC = 0.;
+  fInnerPedestalRMSDC = 0.;
+  fOuterPedestalRMSDC = 0.;
+  
+}
+
+MStarCam::~MStarCam()
+{
+    fStars->SetOwner();
+    fStars->Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+MStarPos &MStarCam::operator[] (Int_t i)
+{
+  MStarPos& star = *static_cast<MStarPos*>(fStars->At(i));
+  return star;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+const MStarPos &MStarCam::operator[] (Int_t i) const
+{
+    return *static_cast<MStarPos*>(fStars->At(i));
+}
+
+void MStarCam::Paint(Option_t *o)
+{
+	TIter Next(fStars);
+	MStarPos* star;
+	while ((star=(MStarPos*)Next())) 
+	    star->Paint(o);
+}
+
+void MStarCam::Print(Option_t *o) const
+{
+      *fLog << inf << "DCs baseline:" << endl;
+      *fLog << inf << " Inner Pixels Mean pedestal \t" << setw(4) << fInnerPedestalDC << " uA  and RMS " << setw(4) << fInnerPedestalRMSDC << " uA for DCs" << endl;
+      *fLog << inf << " Outer Pixels Mean pedestal \t" << setw(4) << fOuterPedestalDC << " uA  and RMS " << setw(4) << fOuterPedestalRMSDC << " uA for DCs" << endl;
+      
+      TIter Next(fStars);
+      MStarPos* star;
+      UInt_t starnum = 0;
+      while ((star=(MStarPos*)Next())) 
+        {
+          *fLog << inf << "Star[" << starnum << "] info:" << endl;
+          star->Print(o);
+          starnum++;
+        }
+}
Index: branches/Mars_McMismatchStudy/mstarcam/MStarCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/MStarCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/MStarCam.h	(revision 17960)
@@ -0,0 +1,64 @@
+#ifndef MARS_MStarCam
+#define MARS_MStarCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class TList;
+
+class MGeomCam;
+class MStarPos;
+
+class MStarCam : public MParContainer
+{
+private:
+
+  TList  *fStars;  //-> FIXME: Change TClonesArray away from a pointer?
+
+  // BaseLine DCs info
+  Float_t fInnerPedestalDC;         //[ua]
+  Float_t fOuterPedestalDC;         //[ua]
+
+  Float_t fInnerPedestalRMSDC;      //[ua]
+  Float_t fOuterPedestalRMSDC;      //[ua]
+
+  MHCamera fDisplay;
+
+ public:
+
+  MStarCam(const char *name=NULL, const char *title=NULL);
+  ~MStarCam();
+
+  MStarPos &operator[] (Int_t i);
+  const MStarPos &operator[] (Int_t i) const;
+
+  TList *GetList() const { return fStars; }
+  UInt_t GetNumStars() const { return fStars->GetSize(); }
+
+  //Getters
+
+  Float_t GetInnerPedestalDC() {return fInnerPedestalDC;}
+  Float_t GetOuterPedestalDC() {return fOuterPedestalDC;}
+  Float_t GetInnerPedestalRMSDC() { return fInnerPedestalRMSDC;}
+  Float_t GetOuterPedestalRMSDC() { return fOuterPedestalRMSDC;}
+
+  MHCamera& GetDisplay() { return fDisplay; }
+
+    //Setters
+  void SetInnerPedestalDC(Float_t ped) {fInnerPedestalDC = ped;}
+  void SetOuterPedestalDC(Float_t ped) {fOuterPedestalDC = ped;}
+  void SetInnerPedestalRMSDC(Float_t rms){fInnerPedestalRMSDC = rms;}
+  void SetOuterPedestalRMSDC(Float_t rms){fOuterPedestalRMSDC = rms;}
+
+  void Paint(Option_t *o=NULL);
+  void Print(Option_t *o=NULL) const;
+
+  ClassDef(MStarCam, 1)	// Storage Container for star positions in the camera
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mstarcam/MStarCamTrans.cc
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/MStarCamTrans.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/MStarCamTrans.cc	(revision 17960)
@@ -0,0 +1,1233 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 08/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MStarCamTrans
+// ---------------
+//
+// this is a collection of transformations between
+//
+// a) celestial (declination, hourangle)      = (  dec,   h); units (deg,hour)
+// b) local     (zenith angle, azimuth angle) = (theta, phi); units (deg, deg)
+// c) camera    (x-coordinate, y-coordinate)  = (    X,   Y); units ( mm,  mm)
+//
+// coordinates. As to the definition of the coordinates, the conventions
+// of TDAS 00-11 are used. 
+//
+// The transformations use 
+//   - cos(Lat) and sin(Lat) from an MObservatory container, 
+//     where 'Lat' is the geographical latitude of the telescope.
+//   - fDistCam from an MGeomCam container,
+//     which is the distance of the camera from the reflector center
+//   
+//   in order to apply one of the transformations the  
+//      'MGeomCam' and 'MObservatory' containers have to be present;
+//      the corresponding objects 'mgeom' and 'mobserv' have to be used as 
+//      arguments of the constructor
+//
+//               MStarCamTrans(mgeom, mobserv);
+//
+// The tranformations ignore effects like nutation, precession, refraction, ...
+// This is not a real problem as long as relative positions are considered, as
+// in all the transformations, except in CelToLoc and LocToCel.
+//
+// The camera coordinates (X, Y) are assumed to be the coordinates for an ideal
+// imaging, without imaging errors. The x-axis is assumed to be horizonthal,
+// the y-axis is pointing upwards.
+//
+// the azimuthal angle is defined as :   0 degrees  = north
+//                                      90 degrees  = east
+//                                     180 degrees  = south
+//                                     270 degrees  = west  
+// 
+// Examples for the use of the transformations :
+//
+// - if the local coordinates (theta1, phi1) of a point (X1, Y1) in the camera
+//   are known one may caculate the local coordinates (theta2, phi2) of any 
+//   other point (X2, Y2) in the camera :
+//
+//         LocCamCamToLoc(theta1, phi1, X1, Y1, X2, Y2, theta2, phi2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Loc0CamToLoc(theta1, phi1, X2, Y2, theta2, phi2);
+//
+
+// - if the local coordinates (theta1, phi1) of a point (X1, Y1) in the camera
+//   are known one may caculate the position (X2, Y2) for another direction
+//   (theta2, phi2) :
+//
+//         LocCamLocToCam(theta1, phi1, X1, Y1, theta2, phi2, X2, Y2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Loc0LocToCam(theta1, phi1, X2, Y2, theta2, phi2);
+//
+// - if the celestial coordinates (dec1, h1) of a point (X1, Y1) in the camera
+//   are known one may caculate the celestial coordinates (dec2, h2) of any 
+//   other point (X2, Y2) in the camera :
+//
+//         CelCamCamToCel(dec1, h1, X1, Y1, X2, Y2, dec2, h2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Cel0CamToCel(dec1, h1, X2, Y2, dec2, h2);
+//
+//
+// - if the celestial coordinates (dec1, h1) of a point (X1, Y1) in the camera
+//   are known one may caculate the position (X2, Y2) for any other direction :
+//
+//         CelCamCelToCam(dec1, h1, X1, Y1, dec2, h2, X2, Y2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Cel0CelToCam(dec1, h1, dec2, h2, X2, Y2);
+//
+//
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MStarCamTrans.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TStyle.h>
+#include <TGraph.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+
+//#include "MH.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MGeomCam.h"
+#include "MObservatory.h"
+
+using namespace std;
+
+ClassImp(MStarCamTrans);
+
+
+// --------------------------------------------------------------------------
+//
+// Constructor
+// 
+//    get distance between camera and reflector from an MGeomCam     container
+//    get cos(Lat) and sin(Lat) from                 an MObservatory container
+//
+MStarCamTrans::MStarCamTrans(const MGeomCam &cam, const MObservatory &obs) 
+{
+  if (&cam == NULL)
+  {
+    gLog << err << "MStarCamTrans::MStarCamTrans;  MGeomCam container is not available"
+          << endl;
+    return;
+  }
+
+  if (&obs == NULL)
+  {
+    gLog << err << "MStarCamTrans::MStarCamTrans;  MObservatory container is not available"
+          << endl;
+    return;
+  }
+
+  fDistCam = cam.GetCameraDist() * 1000.0;     //  [mm]
+  fCLat    = obs.GetCosPhi();
+  fSLat    = obs.GetSinPhi();
+
+  if (fDistCam*fCLat*fSLat == 0.0)
+  {
+    gLog << "MStarCamTrans::TransCelLocCam; one of 'fDistCam, fCLat, fSLat' is zero !!!$$$$$$$$$$$$$$$$$ : "
+        << fDistCam << ",  " << fCLat << ",  " << fSLat << endl;
+  }
+
+
+  fGridBinning = 0.50;   // degrees
+  fGridFineBin = 0.01;   // degrees
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Loc0CamToLoc
+//
+// Input :   (theta0, phi0)    direction for the position (0,0) in the camera  
+//           (     X,    Y)    a position in the camera
+// 
+// Output :  ( theta,  phi)    direction for the position (X,Y) in the camera
+//
+Bool_t MStarCamTrans::Loc0CamToLoc(Double_t theta0deg, Double_t phi0deg,
+                                     Double_t X,         Double_t Y,
+                                     Double_t &thetadeg, Double_t &phideg) 
+{
+  Double_t theta0 = theta0deg / kRad2Deg;
+  Double_t phi0   = phi0deg   / kRad2Deg;
+
+  Double_t XC = X / fDistCam;
+  Double_t YC = Y / fDistCam;
+
+  Double_t theta;
+  Double_t phiminphi0;
+
+  //--------------------------------------------
+  Double_t sip = -XC;
+  Double_t cop = sin(theta0) + YC*cos(theta0);
+
+  Double_t sit = sqrt(cop*cop + XC*XC);
+  Double_t cot = cos(theta0) - YC*sin(theta0);
+
+  // there is an ambiguity in the sign of cos(theta)
+  // - if theta0 is close to 0 or Pi 
+  //   choose that theta which is closer to theta0,
+  //   i.e. require the same sign for cos(theta) and cos(theta0)
+  // - otherwise choose that theta which is compatible with a small
+  //   difference |phi-phi0|, i.e. cos(phi-phi0) > 0
+
+  if( fabs(theta0deg - 90.0) > 45.0 )
+    theta = TMath::ATan2( sit, TMath::Sign(cot, cos(theta0)) );
+  else
+    theta = TMath::ATan2( sit, TMath::Sign(cot, cop/cot) );
+
+  Double_t sig = TMath::Sign(1.0, cot*tan(theta));
+  phiminphi0 = TMath::ATan2(sig*sip, sig*cop);
+
+  //--------------------------------------------
+  phideg   = (phi0 + phiminphi0) * kRad2Deg;
+  thetadeg =               theta * kRad2Deg;
+
+  //gLog << "MStarCamTrans::Loc0Cam2Log; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Loc0LocToCam
+//
+// Input :   (theta0, phi0)   direction for the position (0,0) in the camera  
+//           ( theta,  phi)   some other direction
+// 
+// Output :  (X, Y)      position in the camera corresponding to (theta, phi)
+//
+//  (see also MAstro::GetDistOnPlain())
+//
+Bool_t MStarCamTrans::Loc0LocToCam(Double_t theta0deg, Double_t phi0deg,
+                                     Double_t thetadeg,  Double_t phideg,
+                                     Double_t &X,        Double_t &Y)
+{
+  Double_t theta0 = theta0deg / kRad2Deg;
+  Double_t phi0   = phi0deg   / kRad2Deg;
+
+  Double_t theta = thetadeg / kRad2Deg;
+  Double_t phi   = phideg   / kRad2Deg;
+
+  //--------------------------------------------
+  Double_t YC =   (cos(theta0)*tan(theta)*cos(phi-phi0) - sin(theta0))
+                / (cos(theta0) + sin(theta0)*tan(theta)); 
+  Double_t XC = -sin(phi-phi0) * (cos(theta0) - YC*sin(theta0)) * tan(theta);
+
+  //--------------------------------------------
+  X = XC * fDistCam;
+  Y = YC * fDistCam;
+
+
+  //gLog << "MStarCamTrans::Loc0LocToCam; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocCamToLoc0
+//
+// Input :   ( X, Y)         a position in the camera
+//           (theta, phi)    direction for the position (X,Y) in the camera
+// 
+// Output :  ( theta0,  phi0)    direction for the position (0,0) in the camera
+//
+Bool_t MStarCamTrans::LocCamToLoc0(Double_t thetadeg,   Double_t phideg,
+                                     Double_t X,          Double_t Y,
+                                     Double_t &theta0deg, Double_t &phi0deg) 
+{
+  Double_t theta = thetadeg / kRad2Deg;
+  Double_t phi   = phideg   / kRad2Deg;
+
+  Double_t XC = X / fDistCam;
+  Double_t YC = Y / fDistCam;
+
+  //--------------------------------------------
+
+  Double_t theta0;
+  Double_t phiminphi0;
+
+  Double_t tant1 = 0.0;
+  Double_t tant2 = 0.0;
+
+  Double_t ip;
+
+  // calculate tan(theta0)
+  // dummy loop to avoid a 'go to'
+  for (Int_t i=0; i<1; i++)
+  {
+    if ( tan(theta) == 0.0 )
+    {
+      if (XC != 0.0)
+      {
+        // this can never occur
+        gLog << "MStarCamTrans::LocCam2Loc0; thetadeg, XC = " << thetadeg
+              << ",  " << XC << endl;
+         return kFALSE;
+      }
+      tant1 = -YC;
+
+      theta0 = TMath::Pi() *
+               modf( (atan(tant1)+TMath::Pi()) / TMath::Pi(), &ip );
+      phiminphi0 = 0.0;
+
+      break;
+    }
+
+    Double_t a = 1.0   + XC*XC -  YC*YC*tan(theta)*tan(theta);
+    Double_t b = 2.0   * YC    * (1.0 + tan(theta)*tan(theta));
+    Double_t c = XC*XC + YC*YC -        tan(theta)*tan(theta);
+
+    if (a == 0.0)
+    {
+      if (b == 0.0)
+      {
+        // this can never occur
+        gLog << "MStarCamTrans::LocCam2Loc0; a, b = " << a << ",  "
+              << b << endl;
+         return kFALSE;
+      }
+      tant1 = -c/b;  
+    }
+    else
+    {
+      Double_t discr = b*b - 4.0*a*c;
+      if (discr < 0.0)
+      {
+        gLog << "MStarCamTrans::LocCam2Loc0; discr = " << discr << endl;
+        return kFALSE;
+      }
+
+      // two solutions for tan(theta0)
+      tant1 = (-b + sqrt(discr)) / (2.0*a);
+      tant2 = (-b - sqrt(discr)) / (2.0*a);
+
+      if (fabs(tant1-tant2) < 1.e-5)
+        tant2 = 0.0;
+    }
+
+    // define the sign of tan(theta0) and 
+    // reject the solution with the wrong sign
+
+    if ( fabs(thetadeg - 90.0) > 45.0 )
+    {
+      Double_t sig = TMath::Sign(1.0, cos(theta));
+      if ( tant1 != 0.0  &&  TMath::Sign(1.0, tant1) != sig )
+	   tant1 = 0.0; 
+
+      if ( tant2 != 0.0  &&  TMath::Sign(1.0, tant2) != sig )
+	   tant2 = 0.0; 
+    }
+    else
+    {
+      // require sign of cos(phi-phi0) to be > 0
+      if ( tant1 != 0.0  &&
+           TMath::Sign( 1.0, (tant1+YC)/ ((1.0-YC*tant1)*tan(theta)) ) != 1.0 )
+        tant1 = 0.0;
+
+      if ( tant2 != 0.0  &&
+           TMath::Sign( 1.0, (tant2+YC)/ ((1.0-YC*tant2)*tan(theta)) ) != 1.0 )
+        tant2 = 0.0;
+    }
+
+    if (tant1 != 0.0  &&  tant2 != 0.0)
+    {
+      gLog << "MStarCamTrans::LocCam2Loc0; there are 2 solutions for tan(theta0),  tant1, tant2 = " 
+            << tant1 << ",  " << tant2 << endl;
+    }
+
+    if (tant1 != 0.0)
+      theta0 = TMath::Pi() *
+               modf( (atan(tant1)+TMath::Pi()) / TMath::Pi(), &ip );
+    else if (tant2 != 0.0)
+      theta0 = TMath::Pi() *
+               modf( (atan(tant2)+TMath::Pi()) / TMath::Pi(), &ip );
+    else
+    {
+      theta0 = theta;
+      gLog << "MStarCamTrans::LocCam2Loc0; there is no solution for tan(theta0)"
+            << endl;
+    }
+
+    Double_t sip = -XC;
+    Double_t cop = sin(theta0) + YC*cos(theta0);
+    Double_t cot = cos(theta0) - YC*sin(theta0);
+    Double_t sig = TMath::Sign(1.0, cot*tan(theta));
+
+    phiminphi0 = TMath::ATan2(sig*sip, sig*cop);
+  } // end of dummy loop
+
+  //--------------------------------------------
+  phi0deg   = (phi - phiminphi0) * kRad2Deg;
+  theta0deg =             theta0 * kRad2Deg;
+
+  //gLog << "MStarCamTrans::LocCamToLoc0; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cel0CamToCel
+//
+// Input :   (dec0, h0)    direction for the position (0,0) in the camera  
+//           (   X,  Y)    a position in the camera
+// 
+// Output :  (dec,   h)    direction for the position (X,Y) in the camera
+//
+Bool_t MStarCamTrans::Cel0CamToCel(Double_t dec0deg, Double_t h0hour,
+                                     Double_t X,       Double_t Y,
+                                     Double_t &decdeg, Double_t &hhour) 
+{
+  //--------------------------------------------
+
+  // transform celestial coordinates (  dec0,   h0) 
+  //      into local coordinates     (theta0, phi0)
+  Double_t theta0deg;
+  Double_t phi0deg;
+  CelToLoc(dec0deg, h0hour, theta0deg, phi0deg);
+
+  // get the local coordinates (theta, phi) 
+  //         for the position (X, Y) in the camera
+  Double_t thetadeg;
+  Double_t phideg;
+  Loc0CamToLoc(theta0deg, phi0deg, X, Y, thetadeg, phideg);
+
+  // transform local coordinates     (theta, phi)
+  //      into celestial coordinates (  dec,   h) 
+  LocToCel(thetadeg, phideg, decdeg, hhour);
+
+  //--------------------------------------------
+
+
+  //gLog << "MStarCamTrans::Cel0CamToCel; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cel0CelToCam
+//
+// Input :   (dec0, h0)   direction for the position (0,0) in the camera  
+//           (dec,   h)   some other direction
+// 
+// Output :  (X, Y)      position in the camera corresponding to (dec, h)
+//
+Bool_t MStarCamTrans::Cel0CelToCam(Double_t dec0deg, Double_t h0hour,
+                                     Double_t decdeg,  Double_t hhour,
+                                     Double_t &X,        Double_t &Y)
+{
+  //--------------------------------------------
+
+  // transform celestial coordinates (  dec0,   h0) 
+  //      into local coordinates     (theta0, phi0)
+  Double_t theta0deg;
+  Double_t phi0deg;
+  CelToLoc(dec0deg, h0hour, theta0deg, phi0deg);
+
+  // transform celestial coordinates (  dec,   h) 
+  //      into local coordinates     (theta, phi)
+  Double_t thetadeg;
+  Double_t phideg;
+  CelToLoc(decdeg, hhour, thetadeg, phideg);
+
+  // get the position (X, Y) in the camera
+  // from the local coordinates (theta, phi) 
+  Loc0LocToCam(theta0deg, phi0deg, thetadeg, phideg, X, Y);
+
+  //--------------------------------------------
+
+  //gLog << "MStarCamTrans::Cel0CelToCam; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelCamToCel0
+//
+// Input :   ( X,    Y)    a position in the camera
+//           (dec,   h)    direction for the position (X,Y) in the camera
+// 
+// Output :  (dec0, h0)    direction for the position (0,0) in the camera
+//
+
+Bool_t MStarCamTrans::CelCamToCel0(Double_t decdeg,   Double_t hhour, 
+                                     Double_t X,        Double_t Y,
+                                     Double_t &dec0deg, Double_t &h0hour) 
+{
+  //--------------------------------------------
+
+  // transform celestial coordinates (  dec,   h) 
+  //      into local coordinates     (theta, phi)
+  Double_t thetadeg;
+  Double_t phideg;
+  CelToLoc(decdeg, hhour, thetadeg, phideg);
+
+  // get the local coordinates (theta, phi) 
+  //         for the position (0, 0) in the camera
+  Double_t theta0deg;
+  Double_t phi0deg;
+  LocCamToLoc0(thetadeg, phideg, X, Y, theta0deg, phi0deg);
+
+  // transform local coordinates     (theta0, phi0)
+  //      into celestial coordinates (  dec0,   h0) 
+  LocToCel(theta0deg, phi0deg, dec0deg, h0hour);
+
+  //--------------------------------------------
+
+
+  //gLog << "MStarCamTrans::CelCamToCel0; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocCamCamToLoc
+//
+// Input :   (theta1, phi1)  direction for the position (X1,Y1) in the camera  
+//           (    X1,   Y1)  a position in the camera
+//           (    X2,   Y2)  another position in the camera 
+// 
+// Output :  (theta2, phi2)  direction for the position (X2,Y2) in the camera
+//
+Bool_t MStarCamTrans::LocCamCamToLoc(Double_t theta1deg, Double_t phi1deg,
+                                      Double_t X1,         Double_t Y1,
+                                      Double_t X2,         Double_t Y2,
+                                      Double_t &theta2deg, Double_t &phi2deg)
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Loc0CamToLoc(theta1deg, phi1deg, X2, Y2, theta2deg, phi2deg); 
+    return kTRUE;
+  }
+
+  if (X2 == 0.0  && Y2 == 0.0)
+  {
+    LocCamToLoc0(theta1deg, phi1deg, X1, Y1, theta2deg, phi2deg); 
+    return kTRUE;
+  }
+
+  Double_t theta0deg;
+  Double_t phi0deg;
+  LocCamToLoc0(theta1deg, phi1deg, X1, Y1, theta0deg, phi0deg); 
+
+  Loc0CamToLoc(theta0deg, phi0deg, X2, Y2, theta2deg, phi2deg); 
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocCamLocToCam
+//
+// Input :   (theta1, phi1)  direction for the position (X1,Y1) in the camera  
+//           (    X1,   Y1)  a position in the camera
+//           (theta2, phi2)  another direction
+// 
+// Output :  (    X2,   Y2)  position corresponding to (theta2, phi2)
+//
+Bool_t MStarCamTrans::LocCamLocToCam(Double_t theta1deg, Double_t phi1deg,
+                                       Double_t X1,        Double_t Y1,
+				       Double_t theta2deg, Double_t phi2deg,
+				       Double_t &X2,       Double_t &Y2)
+
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Loc0LocToCam(theta1deg, phi1deg, theta2deg, phi2deg, X2, Y2);
+
+    return kTRUE;
+  }
+
+
+  Double_t theta0deg;
+  Double_t phi0deg;
+  LocCamToLoc0(theta1deg, phi1deg, X1, Y1, theta0deg, phi0deg); 
+
+  Loc0LocToCam(theta0deg, phi0deg, theta2deg, phi2deg, X2, Y2);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelCamCamToCel
+//
+// Input :   (dec1, h1)  direction for the position (X1,Y1) in the camera  
+//           (  X1, Y1)  a position in the camera
+//           (  X2, Y2)  another position in the camera 
+// 
+// Output :  (dec2, h2)  direction for the position (X2,Y2) in the camera
+//
+Bool_t MStarCamTrans::CelCamCamToCel(Double_t dec1deg, Double_t h1deg,
+                                      Double_t X1,       Double_t Y1,
+                                      Double_t X2,       Double_t Y2,
+                                      Double_t &dec2deg, Double_t &h2deg) 
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Cel0CamToCel(dec1deg, h1deg, X2, Y2, dec2deg, h2deg); 
+    return kTRUE;
+  }
+
+  if (X2 == 0.0  && Y2 == 0.0)
+  {
+    CelCamToCel0(dec1deg, h1deg, X1, Y1, dec2deg, h2deg); 
+    return kTRUE;
+  }
+
+  Double_t dec0deg;
+  Double_t h0deg;
+  CelCamToCel0(dec1deg, h1deg, X1, Y1, dec0deg, h0deg); 
+
+  Cel0CamToCel(dec0deg, h0deg, X2, Y2, dec2deg, h2deg); 
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelCamCelToCam
+//
+// Input :   (dec1, h1)  direction for the position (X1,Y1) in the camera  
+//           (  X1, Y1)  a position in the camera
+//           (dec2, h2)  another direction
+// 
+// Output :  (  X2, Y2)  position corresponding to (dec2, h2)
+//
+Bool_t MStarCamTrans::CelCamCelToCam(Double_t dec1deg, Double_t h1deg,
+                                       Double_t X1,      Double_t Y1,
+				       Double_t dec2deg, Double_t h2deg,
+				       Double_t &X2,     Double_t &Y2)
+
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Cel0CelToCam(dec1deg, h1deg, dec2deg, h2deg, X2, Y2);
+
+    return kTRUE;
+  }
+
+
+  Double_t dec0deg;
+  Double_t h0deg;
+  CelCamToCel0(dec1deg, h1deg, X1, Y1, dec0deg, h0deg); 
+
+  Cel0CelToCam(dec0deg, h0deg, dec2deg, h2deg, X2, Y2);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelToLoc
+//
+// Input :   (dec,     h)    celestial coordinates
+// 
+// Output :  (theta, phi)    corresponding local coordinates
+//
+// (see also MAstroCatalog and MAstroSky2Local)
+//
+Bool_t MStarCamTrans::CelToLoc(Double_t decdeg,    Double_t hhour,
+                                 Double_t &thetadeg, Double_t &phideg) 
+{
+  Double_t a1 =  fCLat;
+  Double_t a3 = -fSLat;
+
+  Double_t dec = decdeg / kRad2Deg;
+  Double_t h   =  hhour / 24.0 * TMath::TwoPi();
+
+  // transform celestial coordinates (  dec,   h) 
+  //      into local coordinates     (theta, phi)
+  Double_t xB =   cos(dec) * cos(h);
+  Double_t yB =   cos(dec) * sin(h);
+  Double_t zB = - sin(dec);
+
+  Double_t xA =  a3*xB        - a1*zB;
+  Double_t yA =         - yB;
+  Double_t zA = -a1*xB        - a3*zB;
+
+  thetadeg = acos(-zA)             * kRad2Deg;
+  phideg   = TMath::ATan2(yA, xA)  * kRad2Deg;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocToCel
+// 
+// Input :   (theta, phi)    local coordinates
+//
+// Output :  (dec,     h)    corresponding celestial coordinates
+//
+// (see also MAstroCatalog and MAstroSky2Local)
+//
+Bool_t MStarCamTrans::LocToCel(Double_t thetadeg, Double_t phideg,
+                                 Double_t &decdeg,  Double_t &hhour) 
+{
+  Double_t a1 =  fCLat;
+  Double_t a3 = -fSLat;
+
+  Double_t theta = thetadeg / kRad2Deg;
+  Double_t phi   =   phideg / kRad2Deg;
+
+  //--------------------------------------------
+
+  // transform local coordinates     (theta, phi)
+  //      into celestial coordinates (  dec,   h) 
+  Double_t xA =   sin(theta) * cos(phi);
+  Double_t yA =   sin(theta) * sin(phi);
+  Double_t zA = - cos(theta);
+
+  Double_t xB =  a3*xA        - a1*zA;
+  Double_t yB =         - yA;
+  Double_t zB = -a1*xA        - a3*zA;
+  
+  Double_t dec = asin(-zB);
+  Double_t h   = TMath::ATan2(yB, xB);
+
+  //--------------------------------------------
+  decdeg = dec * kRad2Deg;
+  hhour  = h * 24.0 / TMath::TwoPi();
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PlotGridAtDec0H0
+// 
+//     set the celestial coordinates of the camera center     
+//     and plot the lines of constant (Theta, Phi)
+//          and the lines of constant (Dec,   H  )
+//
+// (see also MAstroCatalog::Draw and MAstroCamera::Draw)
+//
+// Warning: Leaks Memory!
+//
+Bool_t MStarCamTrans::PlotGridAtDec0H0(TString name,
+                                         Double_t dec0deg, Double_t h0hour) 
+{
+  Double_t theta0deg;
+  Double_t phi0deg;
+  CelToLoc(dec0deg, h0hour, theta0deg, phi0deg);
+
+  PlotGrid(name, theta0deg, phi0deg, dec0deg, h0hour);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PlotGridAtTheta0Phi0
+// 
+//     set the local coordinates of the camera center     
+//     and plot the lines of constant (Theta, Phi)
+//          and the lines of constant (Dec,   H  )
+//
+// (see also MAstroCatalog::Draw and MAstroCamera::Draw)
+//
+// Warning: Leaks Memory!
+//
+Bool_t MStarCamTrans::PlotGridAtTheta0Phi0(TString name,
+                                    Double_t theta0deg, Double_t phi0deg) 
+{
+  Double_t dec0deg;
+  Double_t h0hour;
+  LocToCel(theta0deg, phi0deg, dec0deg, h0hour);
+
+  PlotGrid(name, theta0deg, phi0deg, dec0deg, h0hour);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetGridParameters
+// 
+//     set the binning for the grid    (fGridBinning)
+//     set the binning along the lines (fGridFineBin)
+//
+Bool_t MStarCamTrans::SetGridParameters(
+             Double_t gridbinning, Double_t gridfinebin) 
+{
+  fGridBinning = gridbinning;
+  fGridFineBin = gridfinebin;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PlotGrid
+// 
+// - plot the lines of constant (Theta, Phi) 
+//                              with the camera center at (Theta0, Phi0)
+// -  and the lines of constant (Dec,   H  ) 
+//                              with the camera center at (Dec0,   H0  )
+//
+// (see also MAstroCatalog::Draw and MAstroCamera::Draw)
+//
+// Warning: Leaks Memory! 
+//
+Bool_t MStarCamTrans::PlotGrid(TString name,
+                                 Double_t theta0deg, Double_t phi0deg,
+                                 Double_t dec0deg,   Double_t h0hour) 
+{
+    Double_t mmtodeg = 180.0 / TMath::Pi() / fDistCam ;
+    //gLog << "mmtodeg = " << mmtodeg << endl;
+
+    // aberr   is the ratio r_optaberr/r_ideal between 
+    //         the distance from the camera center with optical aberration and
+    //         the distance from the camera center with an ideal imaging
+    // the value 1.07 is valid if the expected position (with aberration)
+    // in the camera is calculated as the average of the positions obtained
+    // from the reflections at the individual mirrors
+    Double_t aberr = 1.07;
+
+    //--------------------------------------------------------------------
+
+    TCanvas *c1 = new TCanvas(name, name, 0, 0, 300, 600);
+
+    //gROOT->Reset();
+    gStyle->SetCanvasColor(0);
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetFrameBorderMode(0);
+    gStyle->SetOptStat(0000000);
+    gStyle->SetPalette(1);
+
+    c1->Divide(1,2);
+    c1->SetBorderMode(0);
+
+    Double_t xlo = -534.0 * mmtodeg;
+    Double_t xup =  534.0 * mmtodeg;
+
+    Double_t ylo = -534.0 * mmtodeg;
+    Double_t yup =  534.0 * mmtodeg;
+
+    TString nam1 = name;
+    nam1 += "_:_Theta-Phi";
+    TString tit1 = name;
+    tit1 += "_:_Theta-Phi-lines";
+    TH2D *plot1 = new TH2D(nam1, tit1, 1, xlo, xup, 1, ylo, yup);
+    plot1->GetXaxis()->SetTitle("x [deg]");
+    plot1->GetYaxis()->SetTitle("y [deg]");
+
+
+    TString nam2 = name;
+    nam2 += "_:_Dec-Hour";
+    TString tit2 = name;
+    tit2 += "_:_Dec-Hour-lines";
+    TH2D *plot2 = new TH2D(nam2, tit2, 1, xlo, xup, 1, ylo, yup);
+    plot2->GetXaxis()->SetTitle("x [deg]");
+    plot2->GetYaxis()->SetTitle("y [deg]");
+
+
+    c1->cd(1);
+    plot1->Draw();
+    //delete plot1;
+
+    c1->cd(2);
+    plot2->Draw();
+    //delete plot2;
+
+    TGraph *graph1;
+    TLatex *pix;
+
+    Char_t tit[100];
+    Double_t xtxt;
+    Double_t ytxt;
+
+    Double_t xx;
+    Double_t yy;
+
+    Double_t gridbinning = fGridBinning;
+    Double_t gridfinebin = fGridFineBin;
+    Int_t    numgridlines = (Int_t)(4.0/gridbinning);
+
+
+    //--------------------------------------------------------------------
+    // Theta-Phi lines
+
+    // direction for the center of the camera
+    Double_t theta0 = theta0deg;
+    Double_t phi0   = phi0deg;
+    
+
+    //-----   lines for fixed theta   ------------------------------------
+
+    const Int_t Ntheta = numgridlines;
+    Double_t theta[Ntheta];
+    Double_t dtheta = gridbinning;
+
+    Int_t nphi = (Int_t)(4.0/gridfinebin);
+    const Int_t Nphi   = nphi+1;
+    Double_t phi[Nphi];
+    Double_t dphi = gridfinebin/sin(theta0/180.0*3.1415926);
+    if ( dphi > 360.0/((Double_t)(Nphi-1)) )
+      dphi = 360.0/((Double_t)(Nphi-1));
+
+    for (Int_t j=0; j<Ntheta; j++)
+    {
+      theta[j] = theta0 + ((Double_t)j)*dtheta 
+                        - ((Double_t)(Ntheta/2)-1.0)*dtheta;
+    }
+
+    for (Int_t k=0; k<Nphi; k++)
+    {
+      phi[k] = phi0 + ((Double_t)k)*dphi - ((Double_t)(Nphi/2)-1.0)*dphi;
+    }
+
+
+    Double_t x[Nphi];
+    Double_t y[Nphi];
+	
+    
+
+    for (Int_t j=0; j<Ntheta; j++)
+    {
+      if (theta[j] < 0.0) continue;
+
+      for (Int_t k=0; k<Nphi; k++)
+      {
+        Loc0LocToCam(theta0, phi0, theta[j], phi[k],
+                           xx, yy);
+        x[k] = xx * mmtodeg * aberr;
+        y[k] = yy * mmtodeg * aberr;
+
+        //gLog << "theta0, phi0 = " << theta0 << ",  " << phi0 
+        //     << " : theta, phi, x, y = " << theta[j] << ",  "
+        //     << phi[k] << ";   " << x[k] << ",  " << y[k] << endl;  
+      }
+
+      c1->cd(1);
+      graph1 = new TGraph(Nphi,x,y);
+      graph1->SetLineColor(j+1);
+      graph1->SetLineStyle(1);
+      graph1->SetMarkerColor(j+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"Theta = %6.2f", theta[j]);
+      xtxt = xlo + (xup-xlo)*0.1;
+      ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)j) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(j+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    //-----   lines for fixed phi   ------------------------------------
+
+    Int_t ntheta1 = (Int_t)(4.0/gridfinebin);
+    const Int_t Ntheta1 = ntheta1;
+    Double_t theta1[Ntheta1];
+    Double_t dtheta1 = gridfinebin;
+
+    const Int_t Nphi1   = numgridlines;
+    Double_t phi1[Nphi1];
+    Double_t dphi1 = gridbinning/sin(theta0/180.0*3.1415926);
+    if ( dphi1 > 360.0/((Double_t)Nphi1) )
+      dphi1 = 360.0/((Double_t)Nphi1);
+
+    for (Int_t j=0; j<Ntheta1; j++)
+    {
+      theta1[j] = theta0 + ((Double_t)j)*dtheta1 
+                        - ((Double_t)(Ntheta1/2)-1.0)*dtheta1;
+    }
+
+    for (Int_t k=0; k<Nphi1; k++)
+    {
+      phi1[k] = phi0 + ((Double_t)k)*dphi1 - ((Double_t)(Nphi1/2)-1.0)*dphi1;
+    }
+
+
+    Double_t x1[Ntheta1];
+    Double_t y1[Ntheta1];
+	
+    for (Int_t k=0; k<Nphi1; k++)
+    {
+      Int_t count = 0;
+      for (Int_t j=0; j<Ntheta1; j++)
+      {
+        if (theta1[j] < 0.0) continue;
+                 
+        Loc0LocToCam(theta0, phi0, theta1[j], phi1[k],
+                           xx, yy);
+        x1[count] = xx * mmtodeg * aberr;
+        y1[count] = yy * mmtodeg * aberr;
+
+        //gLog << "theta0, phi0 = " << theta0 << ",  " << phi0 
+        //     << " : theta1, phi1, x1, y1 = " << theta1[j] << ",  "
+        //     << phi1[k] << ";   " << x1[count] << ",  " << y1[count] << endl;  
+        count++;
+      }
+
+      c1->cd(1);
+      graph1 = new TGraph(count,x1,y1);
+      graph1->SetLineColor(k+1);
+      graph1->SetLineStyle(2);
+      graph1->SetMarkerColor(k+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"Phi = %6.2f", phi1[k]);
+      Double_t xtxt = xlo + (xup-xlo)*0.75;
+      Double_t ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)k) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(k+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    c1->cd(1);
+    sprintf(tit,"Theta0 = %6.2f    Phi0 = %6.2f", theta0, phi0);
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.92;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+
+    sprintf(tit,"                 [deg]                [deg]");
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.86;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+
+
+    //--------------------------------------------------------------------
+    // Dec-Hour lines 
+
+    // direction for the center of the camera
+    Double_t dec0 = dec0deg;
+    Double_t h0   = h0hour;
+    //trans.LocToCel(theta0, phi0, dec0, h0);
+    
+
+    //-----   lines for fixed dec   ------------------------------------
+
+    const Int_t Ndec = numgridlines;
+    Double_t dec[Ndec];
+    Double_t ddec = gridbinning;
+
+    Int_t nh = (Int_t)(4.0/gridfinebin);
+    const Int_t Nh   = nh+1;
+    Double_t h[Nh];
+    Double_t dh = gridfinebin/cos(dec0/180.0*3.1415926);
+    if ( dh > 360.0/((Double_t)(Nh-1)) )
+      dh = 360.0/((Double_t)(Nh-1));
+
+
+    for (Int_t j=0; j<Ndec; j++)
+    {
+      dec[j] = dec0 + ((Double_t)j)*ddec 
+                        - ((Double_t)(Ndec/2)-1.0)*ddec;
+    }
+
+    for (Int_t k=0; k<Nh; k++)
+    {
+      h[k] = h0 + ((Double_t)k)*dh - ((Double_t)(Nh/2)-1.0)*dh;
+    }
+
+
+    Double_t xh[Nh];
+    Double_t yh[Nh];
+	
+    
+
+    for (Int_t j=0; j<Ndec; j++)
+    {
+      if (fabs(dec[j]) > 90.0) continue;
+
+      for (Int_t k=0; k<Nh; k++)
+      {
+        Double_t hh0 = h0   *24.0/360.0;                 
+        Double_t hx = h[k]*24.0/360.0;
+        Cel0CelToCam(dec0, hh0, dec[j], hx,
+                           xx, yy);
+        xh[k] = xx * mmtodeg * aberr;
+        yh[k] = yy * mmtodeg * aberr;
+
+        //gLog << "dec0, h0 = " << dec0 << ",  " << h0 
+        //     << " : dec, h, xh, yh = " << dec[j] << ",  "
+        //     << h[k] << ";   " << xh[k] << ",  " << yh[k] << endl;  
+      }
+
+      c1->cd(2);
+      graph1 = new TGraph(Nh,xh,yh);
+      graph1->SetLineColor(j+1);
+      graph1->SetLineStyle(1);
+      graph1->SetMarkerColor(j+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"Dec = %6.2f", dec[j]);
+      xtxt = xlo + (xup-xlo)*0.1;
+      ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)j) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(j+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    //-----   lines for fixed hour angle   ------------------------------------
+
+    Int_t ndec1 = (Int_t)(4.0/gridfinebin);
+    const Int_t Ndec1 = ndec1;
+    Double_t dec1[Ndec1];
+    Double_t ddec1 = gridfinebin;
+
+    const Int_t Nh1   = numgridlines;
+    Double_t h1[Nh1];
+    Double_t dh1 = gridbinning/cos(dec0/180.0*3.1415926);
+    if ( dh1 > 360.0/((Double_t)Nh1) )
+      dh1 = 360.0/((Double_t)Nh1);
+
+
+    for (Int_t j=0; j<Ndec1; j++)
+    {
+      dec1[j] = dec0 + ((Double_t)j)*ddec1 
+                        - ((Double_t)(Ndec1/2)-1.0)*ddec1;
+    }
+
+    for (Int_t k=0; k<Nh1; k++)
+    {
+      h1[k] = h0 + ((Double_t)k)*dh1 - ((Double_t)(Nh1/2)-1.0)*dh1;
+    }
+
+
+    Double_t xd[Ndec1];
+    Double_t yd[Ndec1];
+	
+    for (Int_t k=0; k<Nh1; k++)
+    {
+      Int_t count = 0;
+      for (Int_t j=0; j<Ndec1; j++)
+      {
+        if (fabs(dec1[j]) > 90.0) continue;
+
+        Double_t hh0 = h0   *24.0/360.0;                 
+        Double_t hhx = h1[k]*24.0/360.0;   
+        Cel0CelToCam(dec0, hh0, dec1[j], hhx,
+                           xx, yy);
+        xd[count] = xx * mmtodeg * aberr;
+        yd[count] = yy * mmtodeg * aberr;
+
+        //gLog << "dec0, h0 = " << dec0 << ",  " << h0 
+        //     << " : dec1, h1, xd, yd = " << dec1[j] << ",  "
+        //     << h1[k] << ";   " << xd[count] << ",  " << yd[count] << endl;  
+
+        count++;
+      }
+
+      c1->cd(2);
+      graph1 = new TGraph(count,xd,yd);
+      graph1->SetLineColor(k+1);
+      graph1->SetLineStyle(2);
+      graph1->SetMarkerColor(k+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"H = %6.2f", h1[k]);
+      Double_t xtxt = xlo + (xup-xlo)*0.75;
+      Double_t ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)k) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(k+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    c1->cd(2);
+    sprintf(tit,"Dec0 = %6.2f    H0 = %6.2f", dec0, h0);
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.92;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+
+    sprintf(tit,"              [deg]             [deg]");
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.86;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+ 
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mstarcam/MStarCamTrans.h
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/MStarCamTrans.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/MStarCamTrans.h	(revision 17960)
@@ -0,0 +1,103 @@
+#ifndef MARS_MStarCamTrans
+#define MARS_MStarCamTrans
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class MGeomCam;
+class MObservatory;
+
+class MStarCamTrans
+{
+private:
+  Double_t  fDistCam;   // distance camera reflector [mm]
+  Double_t  fCLat;      // cos(Lat)
+  Double_t  fSLat;      // sin(Lat)
+
+  Double_t fGridBinning;   // degrees
+  Double_t fGridFineBin;   // degrees
+
+public:
+  MStarCamTrans(const MGeomCam &cam, const MObservatory &obs);
+
+  Bool_t Loc0CamToLoc(Double_t theta0deg, Double_t phi0deg, 
+                      Double_t X,         Double_t Y,
+                      Double_t &thetadeg, Double_t &phideg); 
+
+  Bool_t Loc0LocToCam(Double_t theta0deg, Double_t phi0deg,
+                      Double_t thetadeg,  Double_t phideg,
+                      Double_t &X,        Double_t &Y);
+
+  Bool_t LocCamToLoc0(Double_t thetadeg,   Double_t phideg, 
+                      Double_t X,          Double_t Y,
+                      Double_t &theta0deg, Double_t &phi0deg); 
+
+  Bool_t Cel0CamToCel(Double_t dec0deg, Double_t h0hour, 
+                      Double_t X,       Double_t Y,
+                      Double_t &decdeg, Double_t &hhour); 
+
+  Bool_t Cel0CelToCam(Double_t dec0deg, Double_t h0hour,
+                      Double_t decdeg,  Double_t hhour,
+                      Double_t &X,      Double_t &Y);
+
+  Bool_t CelCamToCel0(Double_t decdeg,   Double_t hhour, 
+                      Double_t X,        Double_t Y,
+                      Double_t &dec0deg, Double_t &h0hour); 
+
+  Bool_t LocCamCamToLoc(Double_t theta1deg,  Double_t phi1deg, 
+                        Double_t X1,         Double_t Y1,
+                        Double_t X2,         Double_t Y2,
+                        Double_t &theta2deg, Double_t &phi2deg); 
+
+  Bool_t LocCamLocToCam(Double_t theta1deg, Double_t phi1deg,
+                        Double_t X1,        Double_t Y1,
+                        Double_t theta2deg, Double_t phi2deg,
+                        Double_t &X2,       Double_t &Y2);
+
+  Bool_t CelCamCamToCel(Double_t dec1deg,  Double_t h1hour, 
+                        Double_t X1,       Double_t Y1,
+                        Double_t X2,       Double_t Y2,
+                        Double_t &dec2deg, Double_t &h2hour); 
+
+  Bool_t CelCamCelToCam(Double_t dec1deg, Double_t h1hour, 
+                        Double_t X1,      Double_t Y1,
+                        Double_t dec2deg, Double_t h2hour,
+                        Double_t &X2,     Double_t &Y2);
+
+  Bool_t CelToLoc(Double_t decdeg,    Double_t hhour, 
+                  Double_t &thetadeg, Double_t &phideg); 
+
+  Bool_t LocToCel(Double_t thetadeg, Double_t phideg, 
+                  Double_t &decdeg,  Double_t &hhour);
+
+  Bool_t PlotGridAtDec0H0(TString name, 
+                          Double_t dec0deg,   Double_t h0hour);
+  Bool_t PlotGridAtTheta0Phi0(TString name,
+                              Double_t theta0deg, Double_t phi0deg);
+
+  Bool_t SetGridParameters(Double_t gridbinning,  Double_t gridfinebin);
+
+  Bool_t PlotGrid(TString name,
+                  Double_t theta0deg, Double_t phi0deg,
+	          Double_t dec0deg,   Double_t h0hour);
+
+  ClassDef(MStarCamTrans, 0) // Class for transformations between Celestial, Local and Camera coordinates 
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mstarcam/MStarPos.cc
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/MStarPos.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/MStarPos.cc	(revision 17960)
@@ -0,0 +1,279 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López ,   4/2004 <mailto:jlopez@ifae.es>
+!              Robert Wagner,   7/2004 <mailto:rwagner@mppmu.mpg.de>
+!              Wolfgang Wittek, 8/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MStarPos.h"
+
+#include <TEllipse.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MStarPos);
+
+using namespace std;
+
+MStarPos::MStarPos(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MStarPos";
+    fTitle = title ? title : "";
+    
+    Reset();
+}
+
+void MStarPos::Reset()
+{
+
+    //Expected position on camera
+     fMagExp = 0.;
+     fXExp   = 0.;
+     fYExp   = 0.;
+
+    //Ideal position on camera
+     fMagIdeal = 0.;
+     fXIdeal   = 0.;
+     fYIdeal   = 0.;
+
+    //Info from calculation
+     fMagCalc    = 0.;
+     fMaxCalc    = 0.;
+     fMeanXCalc  = 0.;
+     fMeanYCalc  = 0.;
+     fSigmaXCalc = 0.;
+     fSigmaYCalc = 0.;
+     fCorrXYCalc = 0.;
+     fXXErrCalc  = 0.;
+     fXYErrCalc  = 0.;
+     fYYErrCalc  = 0.;
+
+    //Info from Gauss fit
+     fMagFit    = 0.;
+     fMaxFit    = 0.;
+     fMeanXFit  = 0.;
+     fMeanYFit  = 0.;
+     fSigmaXFit = 0.;
+     fSigmaYFit = 0.;
+     fCorrXYFit = 0.;
+     fXXErrFit  = 0.;
+     fXYErrFit  = 0.;
+     fYYErrFit  = 0.;
+
+     fChiSquareFit = 0.;
+     fNdofFit      = 1;
+
+}
+
+void MStarPos::SetExpValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagExp = mag;
+     fXExp = x;
+     fYExp = y;
+}
+
+void MStarPos::SetIdealValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagIdeal = mag;
+     fXIdeal = x;
+     fYIdeal = y;
+}
+
+void MStarPos::SetCalcValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+               Float_t sigmaX,    Float_t sigmaY, Float_t correlation, 
+	       Float_t xx,        Float_t xy,     Float_t yy)
+{
+     fMagCalc    = mag;
+     fMaxCalc    = max;
+     fMeanXCalc  = x;
+     fMeanYCalc  = y;
+     fSigmaXCalc = sigmaX;
+     fSigmaYCalc = sigmaY;
+     fCorrXYCalc = correlation;
+     fXXErrCalc  = xx;
+     fXYErrCalc  = xy;
+     fYYErrCalc  = yy;
+}
+
+
+void MStarPos::SetFitValues(
+               Float_t mag,       Float_t max,    Float_t x,    Float_t y, 
+               Float_t sigmaX,    Float_t sigmaY, Float_t correlation, 
+               Float_t xx,        Float_t xy,     Float_t yy,
+               Float_t chiSquare, Int_t ndof)
+{
+     fMagFit    = mag;
+     fMaxFit    = max;
+     fMeanXFit  = x;
+     fMeanYFit  = y;
+     fSigmaXFit = sigmaX;
+     fSigmaYFit = sigmaY;
+     fCorrXYFit = correlation;
+     fXXErrFit  = xx;
+     fXYErrFit  = xy;
+     fYYErrFit  = yy;
+
+     fChiSquareFit = chiSquare;
+     fNdofFit      = ndof;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MStarPos::Paint(Option_t *opt)
+{
+  //Print a cross in the expected position
+  TMarker mexp(fXExp, fYExp, 29);
+  mexp.SetMarkerSize(3);
+  mexp.SetMarkerColor(94);
+  mexp.Paint(); 
+
+  if (fSigmaXCalc>0. && fSigmaYCalc>0.)
+    {
+      TEllipse ecalc(fMeanXCalc, fMeanYCalc, fSigmaXCalc, fSigmaYCalc, 
+                     0, 360, 0);
+      ecalc.SetLineWidth(3);
+      //ecalc.SetLineColor(kBlue);
+      ecalc.SetLineColor(kMagenta);
+      ecalc.Paint();
+    }
+
+  if (fSigmaXFit>0. && fSigmaYFit>0.)
+    {
+      //Print a cross in the fitted position
+      //TMarker mFit(fMeanXFit, fMeanYFit, 3);
+      //mFit.SetMarkerSize(3);
+      //mFit.SetMarkerColor(1);
+      //mFit.Paint(); 
+
+      Double_t cxx = fSigmaXFit*fSigmaXFit;
+      Double_t cyy = fSigmaYFit*fSigmaYFit;
+      Double_t d   = cyy - cxx;
+      Double_t cxy = fCorrXYFit * fSigmaXFit * fSigmaYFit;
+      Double_t tandel;
+      if (cxy != 0.0)
+        tandel = ( d + sqrt(d*d + 4.0*cxy*cxy) ) / (2.0*cxy); 
+      else
+        tandel = 0.0;
+
+      Double_t sindel = tandel / sqrt(1.0 + tandel*tandel);
+      Double_t delta = TMath::ASin(sindel);
+
+      Double_t major =   (cxx + 2.0*tandel*cxy + tandel*tandel*cyy)
+	                / (1.0 + tandel*tandel);  
+
+      Double_t minor =   (tandel*tandel*cxx - 2.0*tandel*cxy + cyy)
+	                / (1.0 + tandel*tandel);  
+
+      TEllipse efit(fMeanXFit, fMeanYFit, sqrt(major), sqrt(minor), 
+                    0, 360,      delta*kRad2Deg);
+      efit.SetLineWidth(3);
+      //efit.SetLineColor(kMagenta);
+      //efit.SetLineColor(kBlack);
+      efit.Paint();
+    }
+}
+  
+void MStarPos::Print(Option_t *opt) const
+{
+  TString o = opt;
+
+  if (o.Contains("name", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Name: \"" << this->GetName() << "\"" << endl;
+    }
+      
+  if (o.Contains("mag", TString::kIgnoreCase) || opt == NULL)
+    {
+  
+      *fLog << inf << "Star magnitude:" << endl;
+      *fLog << inf << " Ideal \t" << setw(4) << fMagIdeal << endl;
+      *fLog << inf << " Expected \t" << setw(4) << fMagExp << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMagCalc << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMagFit << endl;
+    }
+  
+  if (o.Contains("max", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Maximum:" << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMaxCalc << " uA" 
+            << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMaxFit << " uA" << endl;
+    }
+  
+  if (o.Contains("pos", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star position:" << endl;
+      *fLog << inf << " Ideal \t X " << setw(4) << fXIdeal 
+            << " mm \tY " << setw(4) << fYIdeal << " mm" << endl;
+      *fLog << inf << " Expected \t X " << setw(4) << fXExp 
+            << " mm \tY " << setw(4) << fYExp << " mm" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fMeanXCalc 
+            << " mm \tY " << setw(4) << fMeanYCalc << " mm" << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fMeanXFit 
+            << " mm \tY " << setw(4) << fMeanYFit << " mm" << endl;
+    }
+
+  if (o.Contains("siz", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star size:" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fSigmaXCalc 
+            << " mm \tY " << setw(4) << fSigmaYCalc << " mm \t correlation " 
+            << setw(4) << fCorrXYCalc << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fSigmaXFit 
+            << " mm \tY " << setw(4) << fSigmaYFit << " mm \t correlation " 
+            << setw(4) << fCorrXYFit << endl;
+    }
+
+  if (o.Contains("chi", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Fit Quality:" << endl;
+      *fLog << inf << " ChiSquareFit/NdofFit \t " << setw(3) 
+            << fChiSquareFit << "/" << fNdofFit << endl;
+    }
+
+  if (o.Contains("err", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Error Matrix of (fMeanX,fMeanY) :" 
+            << endl;
+      *fLog << inf << " xxCalc,xyCalc,yyCalc \t " << setw(3) << fXXErrCalc 
+            << ", " << fXYErrCalc << ", " << fYYErrCalc << endl;
+      *fLog << inf << " xxFit,xyFit,yyFit \t " << setw(3) << fXXErrFit << ", " 
+            << fXYErrFit << ", " << fYYErrFit << endl;
+    }
+
+
+}
+//--------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mstarcam/MStarPos.h
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/MStarPos.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/MStarPos.h	(revision 17960)
@@ -0,0 +1,121 @@
+#ifndef MARS_MStarPos
+#define MARS_MStarPos
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MStarPos : public MParContainer
+{
+private:
+
+    //Expected position on camera
+    Float_t fMagExp;
+    Float_t fXExp;    //[mm]
+    Float_t fYExp;    //[mm]
+
+    //Ideal position on camera
+    Float_t fMagIdeal;
+    Float_t fXIdeal;    //[mm]
+    Float_t fYIdeal;    //[mm]
+
+    //Info from calculation
+    Float_t fMagCalc;
+    Float_t fMaxCalc;            //[uA]
+    Float_t fMeanXCalc;          //[mm]
+    Float_t fMeanYCalc;          //[mm]
+    Float_t fSigmaXCalc;         //[mm]
+    Float_t fSigmaYCalc;         //[mm]
+    Float_t fCorrXYCalc;          // correlation coefficient
+    Float_t fXXErrCalc;           // error matrix of (fMeanXCalc,fMeanYCalc)
+    Float_t fXYErrCalc;
+    Float_t fYYErrCalc;
+
+    //Info from Gauss fit
+    Float_t fMagFit;
+    Float_t fMaxFit;             //[uA]
+    Float_t fMeanXFit;           //[mm]
+    Float_t fMeanYFit;           //[mm]
+    Float_t fSigmaXFit;          //[mm]
+    Float_t fSigmaYFit;          //[mm]
+    Float_t fCorrXYFit;          // correlation coefficient
+    Float_t fXXErrFit;           // error matrix of (fMeanXFit,fMeanYFit)
+    Float_t fXYErrFit;
+    Float_t fYYErrFit;
+
+    Float_t fChiSquareFit;
+    Int_t   fNdofFit;
+
+
+public:
+
+    MStarPos(const char *name=NULL, const char *title=NULL);
+    //~MStarPos();
+
+    Float_t GetMagExp() {return fMagExp;}
+    Float_t GetXExp() {return fXExp;}
+    Float_t GetYExp() {return fYExp;}
+
+    Float_t GetMagIdeal() {return fMagIdeal;}
+    Float_t GetXIdeal() {return fXIdeal;}
+    Float_t GetYIdeal() {return fYIdeal;}
+
+    Float_t GetMagCalc() {return fMagCalc;}
+    Float_t GetMaxCalc() {return fMaxCalc;}
+    Float_t GetMeanXCalc() {return fMeanXCalc;}
+    Float_t GetMeanYCalc() {return fMeanYCalc;}
+    Float_t GetSigmaXCalc() {return fSigmaXCalc;}
+    Float_t GetSigmaYCalc() {return fSigmaYCalc;}
+    Float_t GetCorrXYCalc()        {return fCorrXYCalc;}
+    Float_t GetXXErrCalc()         {return fXXErrCalc;}
+    Float_t GetXYErrCalc()         {return fXYErrCalc;}
+    Float_t GetYYErrCalc()         {return fYYErrCalc;}
+
+    
+    // getters for the Gauss fit
+    Float_t GetMagFit()           {return fMagFit;}
+    Float_t GetMaxFit()           {return fMaxFit;}
+    Float_t GetMeanXFit()         {return fMeanXFit;}
+    Float_t GetMeanYFit()         {return fMeanYFit;}
+    Float_t GetSigmaXFit()        {return fSigmaXFit;}
+    Float_t GetSigmaYFit()        {return fSigmaYFit;}
+    Float_t GetCorrXYFit()        {return fCorrXYFit;}
+    Float_t GetXXErrFit()         {return fXXErrFit;}
+    Float_t GetXYErrFit()         {return fXYErrFit;}
+    Float_t GetYYErrFit()         {return fYYErrFit;}
+    Float_t GetChiSquareFit()     {return fChiSquareFit;}
+    UInt_t  GetNdofFit()          {return fNdofFit;}
+    Float_t GetChiSquareNdofFit() {return fChiSquareFit/fNdofFit;}
+
+    // -----
+    Float_t GetMeanX() {return fMeanXFit!=0?fMeanXFit:fMeanXCalc;}
+    Float_t GetMeanY() {return fMeanYFit!=0?fMeanYFit:fMeanYCalc;}
+
+    Float_t GetSigmaX() {return fSigmaXFit!=0?fSigmaXFit:fSigmaXCalc;}
+    Float_t GetSigmaY() {return fSigmaYFit!=0?fSigmaYFit:fSigmaYCalc;}
+
+
+    void Reset();
+
+    void SetExpValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetIdealValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetCalcValues(Float_t mag,    Float_t max,    Float_t x, Float_t y, 
+                       Float_t sigmaX, Float_t sigmaY, Float_t correlation, 
+		       Float_t xx,     Float_t xy,     Float_t yy);
+
+    void SetFitValues(Float_t mag,    Float_t max,    Float_t x, Float_t y, 
+                      Float_t sigmaX, Float_t sigmaY, Float_t correlation, 
+                      Float_t xx,     Float_t xy,     Float_t yy,
+                      Float_t chi,   Int_t ndof);
+
+    void Paint(Option_t *opt=NULL);
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MStarPos, 1) // Container that holds the star information in the PMT camera
+};
+
+#endif
+
+
Index: branches/Mars_McMismatchStudy/mstarcam/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/Makefile	(revision 17960)
@@ -0,0 +1,27 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mhbase -I../mhist -I../mgeom -I../mastro
+
+CINT = Starcam
+
+SRCFILES = MStarCam.cc \
+	   MStarPos.cc \
+           MStarCamTrans.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mstarcam/StarcamIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/StarcamIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/StarcamIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mstarcam/StarcamLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mstarcam/StarcamLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mstarcam/StarcamLinkDef.h	(revision 17960)
@@ -0,0 +1,13 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MStarPos+;
+#pragma link C++ class MStarCam+;
+
+#pragma link C++ class MStarCamTrans+;
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mtemp/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/Makefile	(revision 17960)
@@ -0,0 +1,55 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+CINT     = Temp
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../mbase \
+	   -I../mjobs \
+	   -I../mpedestal \
+	   -I../mbadpixels \
+	   -I../mfileio \
+           -I../mraw \
+           -I../manalysis \
+	   -I../mgui \
+	   -I../mgeom \
+	   -I../msignal \
+	   -I../mcalib \
+	   -I../mfilter \
+	   -I../mhbase \
+	   -I../mimage \
+	   -I../mpointing \
+	   -I../mcamera \
+	   -I../mhist \
+	   -I../mmc \
+	   -I../mreport \
+	   -I../mastro \
+           -I../mstarcam
+
+SRCFILES = \
+        MFindStars.cc \
+        MTelAxisFromStars.cc \
+        MHTelAxisFromStars.cc \
+        MSkyCamTrans.cc \
+	MStarLocalCam.cc \
+        MSourceDirections.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mtemp/PaddingExample.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/PaddingExample.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/PaddingExample.C	(revision 17960)
@@ -0,0 +1,673 @@
+
+void InitBinnings(MParList *plist)
+{
+        gLog << "InitBinnings" << endl;
+
+        //--------------------------------------------
+        MBinning *binse = new MBinning("BinningE");
+        //binse->SetEdgesLog(30, 1.0e2, 1.0e5);
+
+	//This is Daniel's binning in energy:
+        binse->SetEdgesLog(14, 296.296, 86497.6);
+        plist->AddToList(binse);
+
+        //--------------------------------------------
+
+        MBinning *binssize = new MBinning("BinningSize");
+        binssize->SetEdgesLog(50, 10, 1.0e5);
+        plist->AddToList(binssize);
+
+        MBinning *binsdistc = new MBinning("BinningDist");
+        binsdistc->SetEdges(50, 0, 1.4);
+        plist->AddToList(binsdistc);
+
+        MBinning *binswidth = new MBinning("BinningWidth");
+        binswidth->SetEdges(50, 0, 1.0);
+        plist->AddToList(binswidth);
+
+        MBinning *binslength = new MBinning("BinningLength");
+        binslength->SetEdges(50, 0, 1.0);
+        plist->AddToList(binslength);
+
+        MBinning *binsalpha = new MBinning("BinningAlpha");
+        binsalpha->SetEdges(100, -100, 100);
+        plist->AddToList(binsalpha);
+
+        MBinning *binsasym = new MBinning("BinningAsym");
+        binsasym->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsasym);
+
+        MBinning *binsm3l = new MBinning("BinningM3Long");
+        binsm3l->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3l);
+
+        MBinning *binsm3t = new MBinning("BinningM3Trans");
+        binsm3t->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3t);
+
+   
+        //.....
+        MBinning *binsb = new MBinning("BinningSigmabar");
+        binsb->SetEdges( 100,  0.0,  50.0);
+        plist->AddToList(binsb);
+
+        MBinning *binssig = new MBinning("BinningSigma");
+        binssig->SetEdges( 100,  0.0, 120.0);
+        plist->AddToList(binssig);
+
+        MBinning *binth = new MBinning("BinningTheta");
+        // this is Daniel's binning in theta
+        //Double_t yedge[8] = 
+        //  {9.41, 16.22, 22.68, 28.64, 34.03, 38.84, 43.08, 44.99};
+        // this is our binning
+        //Double_t yedge[9] = 
+        //               {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        //TArrayD yed;
+        //yed.Set(9,yedge);
+        //binth->SetEdges(yed);
+        
+        //binth->SetEdges(     1, 0.0, 90.0);
+        binth->SetEdgesCos( 10, 0.0, 90.0);
+        plist->AddToList(binth);
+
+        //MBinning *bincosth = new MBinning("BinningCosTheta");
+        //Double_t yedge[9] = 
+        //               {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        //Double_t zedge[9]; 
+        //for (Int_t i=0; i<9; i++)
+	//{
+	//zedge[8-i] = cos(yedge[i]/kRad2Deg);
+	//}
+        //TArrayD zed;
+        //zed.Set(9,zedge);
+        //bincosth->SetEdges(zed);
+        //plist->AddToList(bincosth);
+
+        MBinning *binsdiff = new MBinning("BinningDiffsigma2");
+        binsdiff->SetEdges(100, -500.0, 1500.0);
+        plist->AddToList(binsdiff);
+
+        // robert ----------------------------------------------
+        MBinning *binsalphaf = new MBinning("BinningAlphaFlux");
+        binsalphaf->SetEdges(100, -100, 100);
+        plist->AddToList(binsalphaf);
+
+	MBinning *binsdifftime = new MBinning("BinningTimeDiff");
+	binsdifftime->SetEdges(50, 0, 10);
+	plist->AddToList(binsdifftime);
+
+	MBinning *binstime = new MBinning("BinningTime");
+	binstime->SetEdges(50, 44500, 61000);
+	plist->AddToList(binstime);
+}
+
+
+void DeleteBinnings(MParList *plist)
+{
+        gLog << "DeleteBinnings" << endl;
+
+        TObject *bin;
+
+        //--------------------------------------------
+        bin = plist->FindObject("BinningE");
+        if (bin) delete bin;
+
+        //--------------------------------------------
+
+        bin = plist->FindObject("BinningSize");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDist");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningWidth");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningLength");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAlpha");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAsym");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Long");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Trans");
+        if (bin) delete bin;
+
+        //.....
+        bin = plist->FindObject("BinningSigmabar");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningSigma");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningCosTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDiffsigma2");
+        if (bin) delete bin;
+
+
+        // robert ----------------------------------------------
+        bin = plist->FindObject("BinningAlphaFlux");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTimeDiff");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTime");
+        if (bin) delete bin;
+}
+
+
+
+//************************************************************************
+void PaddingExample()
+{
+      gLog.SetNoColors();
+
+      if (gRandom)
+        delete gRandom;
+      gRandom = new TRandom3(0);
+
+      //-----------------------------------------------
+      TString tag = "080000";
+
+      const char *offfile  = "*OffCrab11*";
+
+      const char *onfile  = "*CrabNebula*";
+
+      const char *mcfile = "calibrated_MCdata2";
+
+      //-----------------------------------------------
+
+      // path for input for Mars
+
+     if (tag == "080000")  
+     { 
+       TString inPathON  = "/.magic/magicserv01/MAGIC/calibrateddata/2004_09_21/";
+       TString inPathOFF = "/.magic/magicserv01/MAGIC/calibrateddata/2004_09_21/";
+       TString inPathMC  = "/.magic/data21a/mase/Mars/Mars041103/DataCalibUV/";
+
+     }
+
+      // path for output from Mars
+     TString outPath = "/.magic/data21a/wittek/PaddedData/";
+//     outPath += tag;
+//     outPath += "/";
+
+      //-----------------------------------------------
+
+
+    //************************************************************************
+
+    // Job A : 
+    //  - produce MHSigmaTheta plots for ON, OFF and MC data
+    //  - write out (or read in) these MHSigmaTheta plots
+    //  - read ON (or OFF or MC) data
+    //  - pad the events; 
+    //  - write root file for ON (or OFF or MC) data (ON1.root, ...);
+
+    Bool_t JobA    = kTRUE;  
+    Bool_t GPadON  = kTRUE;    // \  generate Pad histograms 
+    Bool_t GPadOFF = kFALSE;    //  | and write them onto disk
+    Bool_t GPadMC  = kFALSE;    // /
+    Bool_t Merge   = kFALSE;   // read the Pad histograms, merge them
+                               // and write them onto disk
+    Bool_t Wout    = kFALSE;   // \  read in merged padding histograms and
+                               //  | write out root file of padded data
+                               // /  (ON1.root, OFF1.root or MC1.root) 
+    TString typeInput("ON");
+    //TString typeInput("OFF");
+    //TString typeInput("MC");
+
+
+
+
+    //************************************************************************
+
+    
+  //---------------------------------------------------------------------
+  // Job A
+  //=========
+
+    //  - produce the histograms "sigmabar versus Theta", etc. 
+    //    for ON, OFF and MC data (to be used for the padding)
+    //
+    //  - write root file of padded ON (OFF, MC) events (ON1.root, ...) 
+    //    (after the standard cuts, before the g/h separation)
+
+
+ if (JobA)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job A" << endl;
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobA, GPadON, GPadOFF, GPadMC, Merge, Wout = " 
+         << (JobA    ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadON  ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadOFF ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadMC  ? "kTRUE" : "kFALSE")  << ",  " 
+         << (Merge   ? "kTRUE" : "kFALSE")  << ",  " 
+         << (Wout    ? "kTRUE" : "kFALSE")  << endl;
+    
+    //--------------------------------------------------
+
+
+    // name of MPedPhotCam container
+    TString fNamePedPhotCam("MPedPhotCam");
+
+
+    //************************************************************
+    // generate histograms to be used in the padding
+    // 
+    // read ON, OFF and MC data files
+    // generate (or read in) the padding histograms for ON, OFF and MC data
+    //
+
+    MPad pad;
+    pad.SetName("MPad");
+
+    //--------------------------------------------------
+    // names of ON and OFF files to be read
+    // for generating the histograms to be used in the padding 
+    TString fileON  = inPathON;
+    fileON += onfile;
+    fileON += ".root";
+
+    TString fileOFF = inPathOFF;
+    fileOFF += offfile;
+    fileOFF += ".root";
+
+    TString fileMC = inPathMC;
+    fileMC += mcfile;
+    fileMC += ".root";
+
+    //--------------------------------------------------
+    // name of files to contain the paddding histograms of ON, OFF and MC data
+      TString NamePadON(outPath);
+      NamePadON += "PadON";
+      NamePadON += ".root";
+
+      TString NamePadOFF(outPath);
+      NamePadOFF += "PadOFF";
+      NamePadOFF += ".root";
+
+      TString NamePadMC(outPath);
+      NamePadMC += "PadMC";
+      NamePadMC += ".root";
+
+    // name of file to conatin the merged histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta";
+    outNameSigTh += ".root";
+
+    //--------------------------------------------------
+
+    if (GPadON || GPadOFF || GPadMC)
+    {
+      // generate the padding histograms
+      gLog << "=====================================================" << endl;
+      gLog << "Start generating the padding histograms" << endl;
+
+
+    gLog << "fileON, fileOFF, fileMC = " << fileON << ",  " 
+         << fileOFF << ",  " << fileMC   << endl;
+
+
+
+    //--------------------------------------------------
+      MMakePadHistograms makepad;
+      makepad.SetMaxEvents(-1);
+      makepad.SetNamePedPhotCam(fNamePedPhotCam);
+      makepad.SetPedestalLevel(2.0);
+      makepad.SetUseInterpolation(kTRUE);
+      makepad.SetProcessPedestal(kTRUE);
+      makepad.SetProcessTime(kFALSE);
+
+      //-----------------------------------------
+      // ON events
+
+      if (GPadON)
+      {
+        makepad.SetDataType("ON");
+        makepad.SetNameInputFile(fileON);
+        makepad.SetNameOutputFile(NamePadON);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+      // OFF events
+
+      if (GPadOFF)
+      {
+        makepad.SetDataType("OFF");
+        makepad.SetNameInputFile(fileOFF);
+        makepad.SetNameOutputFile(NamePadOFF);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+      // MC events
+
+      if (GPadMC)
+      {
+        makepad.SetDataType("MC");
+        makepad.SetNameInputFile(fileMC);
+        makepad.SetNameOutputFile(NamePadMC);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+
+
+      gLog << "" << endl;
+      gLog << "End of generating the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+    }
+
+    //************************************************************
+
+    if (Merge)
+    {
+      gLog << "=====================================================" << endl;
+      gLog << "Start of merging the padding histograms" << endl;
+      gLog << "" << endl;
+
+      //pad.MergeONOFFMC(NamePadON, NamePadOFF, NamePadMC, outNameSigTh);
+      //pad.MergeONOFFMC(NamePadON, "", NamePadMC, outNameSigTh);
+      pad.MergeONOFFMC(NamePadON, NamePadOFF, "", outNameSigTh);
+      //pad.MergeONOFFMC("", NamePadOFF, NamePadMC, outNameSigTh);
+
+      gLog << "" << endl;
+      gLog << "End of merging the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+    }
+    // end of Merge
+
+
+
+    //************************************************************
+
+  if (Wout)
+  {
+    // read the target padding histograms ---------------------------
+    pad.ReadPaddingDist(outNameSigTh);
+
+
+    gLog << "=====================================================" << endl;
+    gLog << "Start the padding" << endl;
+
+    //--------------------------------------------------
+    // type of data to be padded 
+    gLog << "typeInput = " << typeInput << endl;
+
+    //-------------------------------------------
+    // name of input root file
+    if (typeInput == "ON")
+      TString filenamein(fileON);
+    else if (typeInput == "OFF")
+      TString filenamein(fileOFF);
+    else if (typeInput == "MC")
+      TString filenamein(fileMC);
+    gLog << "data to be padded : " << filenamein << endl;
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += "Hillas";
+    outNameImage += typeInput;
+    outNameImage += "1.root";
+    gLog << "padded data to be written onto : " << outNameImage << endl;
+
+    //-----------------------------------------------------------
+    pad.SetDataType(typeInput);
+    pad.SetNamePedPhotCam(fNamePedPhotCam);
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadReports read;
+    read.AddTree("Drive");
+    read.AddTree("Events","MTime.",kTRUE);
+    static_cast<MRead&>(read).AddFile(filenamein);
+
+    read.AddToBranchList("MReportDrive.*");
+    read.AddToBranchList("MRawEvtHeader.*");
+
+
+//    MReadMarsFile read("Events", filenamein);
+//    read.DisableAutoScheme();
+
+    MGeomApply        apply;
+
+    // a way to find out whether one is dealing with MC :
+    //MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);  // MC
+    //f1.SetName("Select MC");
+    //MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);  // data
+    //f2.SetName("Select Data");
+
+
+
+      MBadPixelsCalc badcalc;
+      badcalc.SetNamePedPhotContainer(fNamePedPhotCam);
+      badcalc.SetPedestalLevel(2.0);
+      badcalc.SetName("BadCalc");
+
+      MBadPixelsTreat badtreat;
+      badtreat.SetNamePedPhotCam(fNamePedPhotCam);
+      badtreat.SetUseInterpolation(kTRUE);
+      badtreat.SetProcessPedestal(kTRUE);
+      badtreat.SetProcessTimes(kFALSE);
+      badtreat.SetName("BadTreat");
+
+      MPointingPosCalc mpointcalc;
+
+      MFSelBasic selbasic;
+      selbasic.SetCuts(20.0, 0.0, 25.8419, 90.0, 126.0);
+
+      MContinue contbasic(&selbasic);
+      contbasic.SetName("SelBasic");
+
+      MHBadPixels bad("BadPixels");
+      bad.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillbad("BadPixels[MHBadPixels]", "MBadPixelsCam");
+      fillbad.SetName("FillBad");
+
+      MHSigmaTheta sigth("SigmaTheta");
+      sigth.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "");
+      fillsigtheta.SetName("FillSigTheta");    
+
+
+    MImgCleanStd    clean(3.0, 2.5);
+    clean.SetMethod(MImgCleanStd::kScaled);
+    clean.SetCleanRings(1); 
+    clean.SetName("Clean");
+    clean.SetNamePedPhotCam(fNamePedPhotCam);
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImagePar(fImgParName);
+
+    MHillasSrcCalc hsrccalc("MSrcPosCam", fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFSelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(500, 2, 20, 0.0, 5.0, 0.001, 0.001);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+      
+    /*
+      MWriteRootFile write(outNameImage);
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      //write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+      //write.AddContainer("MTime",         "Events");
+      write.AddContainer("MPointingPos", "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MImagePar",     "Events");
+
+      write.AddContainer("MReportDrive",  "Drive", kFALSE);
+      write.AddContainer("MTimeDrive",    "Drive", kFALSE);  //new
+    */
+
+    //*****************************
+    // entries in MParList
+    
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+    pliston.AddToList(&bad);
+    pliston.AddToList(&sigth);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+    //tliston.AddToList(&f1);
+    //tliston.AddToList(&f2);
+    tliston.AddToList(&apply);
+    tliston.AddToList(&mpointcalc, "Events");
+
+//    tliston.AddToList(&badcalc); done in callisto
+//    tliston.AddToList(&badtreat); done in callisto
+
+    tliston.AddToList(&contbasic, "Events");
+    //tliston.AddToList(&pad, "Events"); 
+
+    
+    tliston.AddToList(&fillbad, "Events");
+    tliston.AddToList(&fillsigtheta, "Events");
+    tliston.AddToList(&clean, "Events");
+
+    tliston.AddToList(&hcalc, "Events");
+    tliston.AddToList(&hsrccalc, "Events");
+
+    tliston.AddToList(&hfill1, "Events");
+    tliston.AddToList(&hfill2, "Events");
+    tliston.AddToList(&hfill3, "Events");
+    tliston.AddToList(&hfill4, "Events");
+    tliston.AddToList(&hfill5, "Events");
+
+    tliston.AddToList(&contstandard, "Events");
+    //tliston.AddToList(&write);
+    
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 2000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+
+    pliston.FindObject("SigmaTheta", "MHSigmaTheta")->DrawClone();
+    pliston.FindObject("BadPixels",  "MHBadPixels")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    //DeleteBinnings(&pliston);
+
+      gLog << "End of padding" << endl;
+      gLog << "=====================================================" << endl;
+  }  
+
+
+    gLog << "Macro ONOFFAnalysis : End of Job A" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+}
+
+
+
+
+
+
+
+   
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/TempIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/TempIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/TempIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mtemp/TempLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/TempLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/TempLinkDef.h	(revision 17960)
@@ -0,0 +1,14 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MFindStars+;
+#pragma link C++ class MTelAxisFromStars+;
+#pragma link C++ class MHTelAxisFromStars+;
+#pragma link C++ class MSkyCamTrans+;
+#pragma link C++ class MStarLocalCam+;
+#pragma link C++ class MSourceDirections+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/.rootrc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/.rootrc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/.rootrc	(revision 17960)
@@ -0,0 +1,45 @@
+#############################################################################
+#                                                                           #
+# This is the path where root seraches for macros                           #
+# to execute (eg. .x merpp.C)                                               #
+#                                                                           #
+#############################################################################
+
+Unix.*.Root.MacroPath:       .:./macros:../../macros
+
+#############################################################################
+#                                                                           #
+# This is the path where the dynamic loader (eg. gSystem->Load("mars.so")   #
+# is searching for the shared objects                                       #
+#                                                                           #
+#############################################################################
+
+Unix.*.Root.DynamicPath:     .:./lib
+
+#############################################################################
+#                                                                           #
+# This is the name of the logon macro (executed at root startup) and the    #
+# logoff macro (executed when quiting root)                                 #
+#                                                                           #
+#############################################################################
+
+Rint.Logon:                  rootlogon.C
+Rint.Logoff:                 rootlogoff.C
+
+#############################################################################
+#                                                                           #
+# This is used if you want to use the root documentation facility to        #
+# create the documentation of the code out of the code                      #
+#                                                                           #
+#############################################################################
+
+Root.Html.DescriptionStyle:  Doc++
+
+Root.Html.Author:            !   Author(s):
+Root.Html.Copyright:         !   Copyright
+Root.Html.Modified:          !   Modified:
+Root.Html.Description        // ----
+
+Root.Html.Root:              http://root.cern.ch/root/htmldoc/
+Root.Html.HomePage:          http://magic.astro.uni-wuerzburg.de/mars/
+Root.Html.SearchEngine:      http://magic.astro.uni-wuerzburg.de/mars/search.html
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/IFAEIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/IFAEIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/IFAEIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/IFAELinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/IFAELinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/IFAELinkDef.h	(revision 17960)
@@ -0,0 +1,40 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MDisplay+;
+#pragma link C++ class MHillasDisplay+;
+#pragma link C++ class MPSFFit+;
+#pragma link C++ class MPSFFitCalc+;
+#pragma link C++ class MSrcPlace+;
+#pragma link C++ class MSrcPosFromFile+;
+#pragma link C++ class MSrcRotate+;
+#pragma link C++ class MSrcTranslate+;
+#pragma link C++ class MIslands+;
+#pragma link C++ class MImgIsland+;
+#pragma link C++ class MIslandsCalc+;
+#pragma link C++ class MIslandsClean+;
+#pragma link C++ class MFHVNotNominal+;
+#pragma link C++ class MCalibrateDC+;
+#pragma link C++ class MHPSFFromStars+;
+#pragma link C++ class MControlPlots+;
+#pragma link C++ class MSrcPosFromStars+;
+#pragma link C++ class MLiveTime+;
+#pragma link C++ class MLiveTimeCalc+;
+#pragma link C++ class MTopology+;
+#pragma link C++ class MTopologyCalc+;
+#pragma link C++ class MImageParDisp+;
+#pragma link C++ class MDispParameters+;
+#pragma link C++ class MDispCalc+;
+#pragma link C++ class MHDisp+;
+#pragma link C++ class MFDisp+;
+#pragma link C++ class MFindDisp+;
+#pragma link C++ class MEffAreaAndCoeffCalc+;
+#pragma link C++ class MGainFluctuationPix+;
+#pragma link C++ class MGainFluctuationCam+;
+#pragma link C++ class MGainFluctuationCamIter+;
+#pragma link C++ class MAddGainFluctuation+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MAddGainFluctuation.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MAddGainFluctuation.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MAddGainFluctuation.cc	(revision 17960)
@@ -0,0 +1,219 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch Bigas 01/2005  <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2002-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MAddGainFluctuation
+//
+//   This is a task which add gain fluctuatins
+//
+//  Input Containers:
+//   MCerPhotEvt
+//   MGainFluctuationCam
+//   MGeomCam
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAddGainFluctuation.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+#include "MGainFluctuationCam.h"
+
+#include "TRandom.h"
+
+ClassImp(MAddGainFluctuation);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MAddGainFluctuation::MAddGainFluctuation(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MAddGainFluctuation";
+    fTitle = title ? title : "Add gain fluctuation";
+
+    FillHist(1,0.1);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MCerPhotEvt
+//  - MGeomCam
+//
+// The following containers are also searched and created if
+// they were not found:
+// - MGainFluctuationCam
+//
+//
+Int_t MAddGainFluctuation::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fCerPhotEvt)
+        return kFALSE;
+
+    fGainFlucCam = (MGainFluctuationCam*)pList->FindCreateObj(AddSerialNumber("MGainFluctuationCam"));
+    if (!fGainFlucCam)
+        return kFALSE;
+
+
+    Fill();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MAddGainFluctuation::ReInit(MParList *pList)
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale the content of MCerPhotPix by Gain fluctuaion
+//
+Int_t MAddGainFluctuation::Process()
+{
+    //fCerPhotEvt->InitSize(fRawEvt->GetNumPixels());
+
+//    if (fIsMcFile)
+//        ScalePedestals();
+
+    if(!fAddFluctuations)
+      return kTRUE;
+
+    Double_t gain;
+
+    MCerPhotPix *pix = 0;
+
+    TIter Next(*fCerPhotEvt);
+
+    while ((pix=(MCerPhotPix*)Next()))
+    {
+        const UInt_t idx = pix->GetPixId();
+
+	fGainFlucCam->GetPixelContent(gain,idx,*fGeomCam,1);
+	pix->Scale(1.0/gain);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill Histogram with Gain Fluctuations distribution in the Camera
+//
+//  flag:
+//
+//     0 : All to one
+//     1 : Gaussian centered at one with sigma "sigma"
+//     2 : Uniform distribution from 1/sigma to 1*sigma
+void MAddGainFluctuation::FillHist(int flag, float sigma){
+
+  TRandom rnd;
+  Float_t val;
+
+  fGainsDistribution = new TH1F("Gain","Gain Fluctuatins",1000,0.0,2.0);
+
+  switch(flag){
+  case 0:
+    fAddFluctuations=0;
+    break;
+  case 1:
+    fAddFluctuations=1;
+    for(int i=0;i<10000;i++){
+      val=rnd.Gaus(1.0,sigma);
+      fGainsDistribution->Fill(val);
+    }
+    break;
+  case 2:
+    fAddFluctuations=1;
+    for(int i=0;i<10000;i++){
+      val=rnd.Uniform(1.0/sigma,1.0*sigma);
+      fGainsDistribution->Fill(val);
+    }
+    break;
+  default:
+    fAddFluctuations=0;
+    for(int i=0;i<10000;i++){
+      val=rnd.Gaus(1.0,sigma);
+      fGainsDistribution->Fill(val);
+    }
+    break;
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set and Fill Histogram with Gain Fluctuations distribution in the Camera
+//
+void MAddGainFluctuation::SetHist(int bins, float fb, float lb, float *values){
+
+  fGainsDistribution = new TH1F("Gain","Gain Fluctuatins",bins,fb,lb);
+  
+  for(int i=0;i<bins;i++){
+    fGainsDistribution->SetBinContent(i,values[i]);
+  }
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill MGainFluctuatinCam 
+//
+void MAddGainFluctuation::Fill(){
+
+  const Int_t pixels=fGeomCam->GetNumPixels();
+  
+  if(fAddFluctuations)
+    for (int idx=0;idx<pixels;idx++)
+      fGainFlucCam->AddPixel(idx,fGainsDistribution->GetRandom());
+  else
+    for (int idx=0;idx<pixels;idx++)
+      fGainFlucCam->AddPixel(idx,1.0);
+
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MAddGainFluctuation.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MAddGainFluctuation.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MAddGainFluctuation.h	(revision 17960)
@@ -0,0 +1,54 @@
+#ifndef MARS_MAddGainFluctuation
+#define MARS_MAddGainFluctuation
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCerPhotCalc                                                            //
+//                                                                         //
+// Integrates the desired ADC time slices of one pixel and substracts the  //
+// pedestal (offset) value                                                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TH1F
+#include <TH1F.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MCerPhotEvt;
+class MGainFluctuationCam;
+class MGeomCam;
+class TH1F;
+
+class MAddGainFluctuation : public MTask
+{
+    const MGeomCam     *fGeomCam;
+    MCerPhotEvt    *fCerPhotEvt; // Cerenkov Photon Event used for calculation
+    MGainFluctuationCam    *fGainFlucCam; // Gain Fluctuation
+    TH1F *fGainsDistribution;   // Distribution of Gain fluctuatins in the Camera
+    Int_t fAddFluctuations;     // If 0 skip Process
+
+    void Fill();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MAddGainFluctuation(const char *name=NULL, const char *title=NULL);
+
+    void SetHist(int bins, float fb, float lb, float *values);
+    void FillHist(int flag, float sigma);
+
+    ClassDef(MAddGainFluctuation, 0)   // Task to add Gain fluctuations
+};
+ 
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MCalibrateDC.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MCalibrateDC.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MCalibrateDC.cc	(revision 17960)
@@ -0,0 +1,272 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier López , 5/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibrateDC
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateDC.h"
+
+#include <TString.h>
+#include <TH1F.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MReadReports.h"
+#include "MGeomApply.h"
+
+ClassImp(MCalibrateDC);
+using namespace std;
+
+MCalibrateDC::MCalibrateDC(TString filename, const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MCalibrateDC";
+  fTitle = title ? title : "Taks to intercalibrate the DC of all pmts from a continuos light run";
+
+  fFileName = filename;
+  
+  fStartingMissCalibration.Set(2004,3,8);
+  fEndingMissCalibration.Set(2004,4,15);
+  
+  Int_t   nbins = 120;
+  Float_t min = 0;
+  Float_t max = 30.;
+  fCalHist = new TH1F("calhist","",nbins,min,max);
+
+  fDCCalibration = 1.;
+  fDCCalibrationRMS = 0.;
+
+  fDCMissCalibrationFactor = 30./40.95;
+}
+MCalibrateDC::~MCalibrateDC()
+{
+  delete  fCalHist;
+}
+
+Int_t MCalibrateDC::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Initialization of objects that need the information from MGeomCam
+    fDisplay.SetGeometry(*fGeomCam);
+    fNumPixels = fGeomCam->GetNumPixels();
+
+    fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+
+    if (!fTimeCurr)
+    {
+      *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Run over the continuos light run to get the DC intercalibration factors
+    fDCCalibrationFactor.Set(fNumPixels);
+    fDCCalibrationFactor.Reset(1.);
+
+    if ( fFileName != "" )
+      {
+        ProcessFile();
+        DCCalibrationCalc();
+ 
+        UInt_t numPixelsSetUnsuedForDC = 0;
+        
+        for (UInt_t pix=1; pix<fNumPixels; pix++)
+          {
+            if (fDisplay.GetBinContent(pix+1) > fMinDCAllowed)
+              fDCCalibrationFactor[pix] = fDCCalibration/fDisplay.GetBinContent(pix+1);
+            else
+              {
+                numPixelsSetUnsuedForDC++;
+                fDCCalibrationFactor[pix] = 0.; //FIXME: Maybe to introduce a setunused in MCameraDC ?
+              }
+          }
+
+        *fLog << inf << GetName() << " set unused " << numPixelsSetUnsuedForDC << " because too low dc." << endl;
+        
+      }
+
+    return kTRUE;
+}
+
+Int_t MCalibrateDC::Process()
+{
+
+  if (*fTimeCurr >= fStartingMissCalibration && *fTimeCurr <= fEndingMissCalibration)
+    {
+      for (UInt_t pix=1; pix<fNumPixels; pix++)
+        {
+          MGeomPix& pixel = (*fGeomCam)[pix];
+          if (pixel.GetSector() >=3 && pixel.GetSector() <=5)
+            (*fCurr)[pix] *= fDCCalibrationFactor[pix]*fDCMissCalibrationFactor;
+          else
+            (*fCurr)[pix] *= fDCCalibrationFactor[pix];
+
+        }
+    }
+  else
+    for (UInt_t pix=1; pix<fNumPixels; pix++)
+      (*fCurr)[pix] *= fDCCalibrationFactor[pix];
+	  
+  return kTRUE;
+}
+
+Bool_t MCalibrateDC::ProcessFile()
+{
+
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MCameraDC     dccam;
+    plist.AddToList(&dccam);
+
+    // Reads the trees of the root file and the analysed branches
+    MReadReports read;
+    read.AddTree("Currents"); 
+    read.AddFile(fFileName);     // after the reading of the trees!!!
+    read.AddToBranchList("MReportCurrents.*");
+    
+    MGeomApply geomapl;
+
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&read);
+
+    // Enable logging to file
+    //*fLog.SetOutputFile(lname, kTRUE);
+
+    //
+    // Execute the eventloop
+    //
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetLogStream(fLog);
+
+    // Execute first analysis
+      if (!evtloop.PreProcess())
+        {
+          *fLog << err << GetDescriptor() << ": Failed." << endl;
+	  return kFALSE;
+        }
+        
+      while (tlist.Process())
+        fDisplay.AddCamContent(dccam);
+        
+      evtloop.PostProcess();
+
+    tlist.PrintStatistics();
+
+    UInt_t numexecutions = read.GetNumExecutions();
+    UInt_t numPixels = fDisplay.GetNumPixels();
+    for (UInt_t pix = 1; pix <= numPixels; pix++)
+      fDisplay[pix] /= numexecutions;
+    
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+}
+
+Bool_t MCalibrateDC::DCCalibrationCalc()
+{
+
+   for (UInt_t pix=1; pix<fNumPixels; pix++)
+       fCalHist->Fill(fDisplay.GetBinContent(pix+1));
+
+   Float_t nummaxprobdc = fCalHist->GetBinContent(fCalHist->GetMaximumBin());
+   Float_t maxprobdc = fCalHist->GetBinCenter(fCalHist->GetMaximumBin());
+   UInt_t bin = fCalHist->GetMaximumBin();
+   do
+   {
+       bin++;
+   }
+   while(fCalHist->GetBinContent(bin)/nummaxprobdc > 0.5);
+   Float_t halfmaxprobdc = fCalHist->GetBinCenter(bin);
+
+   *fLog << dbg << " maxprobdc[high] " << maxprobdc << "[" << nummaxprobdc << "] ";
+   *fLog << dbg << " halfmaxprobdc[high] " << halfmaxprobdc << "[" << fCalHist->GetBinContent(bin) << "]" << endl;
+
+   Float_t rmsguess = TMath::Abs(maxprobdc-halfmaxprobdc);
+   Float_t min = maxprobdc-3*rmsguess;
+   min = (min<0.?0.:min);
+   Float_t max = maxprobdc+3*rmsguess;
+
+   *fLog << dbg << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+
+   TF1 func("func","gaus",min,max);
+   func.SetParameters(nummaxprobdc, maxprobdc, rmsguess);
+   
+   fCalHist->Fit("func","QR0");
+
+   UInt_t aproxnumdegrees = 6*(bin-fCalHist->GetMaximumBin());
+   Float_t chiq = func.GetChisquare();
+   fDCCalibration = func.GetParameter(1);
+   fDCCalibrationRMS = func.GetParameter(2);
+
+   *fLog << dbg << " fDCCalibration " << fDCCalibration << " fDCCalibrationRMS " << fDCCalibrationRMS << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+
+   Int_t numsigmas = 5;
+   Axis_t minbin = fDCCalibration-numsigmas*fDCCalibrationRMS/fCalHist->GetBinWidth(1);
+   minbin=minbin<1?1:minbin;
+   Axis_t maxbin = fDCCalibration+numsigmas*fDCCalibrationRMS/fCalHist->GetBinWidth(1);
+   *fLog << dbg << " Number of pixels with dc under " << numsigmas << " sigmas = " << fCalHist->Integral((int)minbin,(int)maxbin) << endl;
+
+    //Check results from the fit are consistent
+    if (TMath::Abs(fDCCalibration-maxprobdc) > rmsguess || fDCCalibrationRMS > rmsguess)
+      {
+        *fLog << warn << GetName() << " Calibration DC fit give non consistent results." << endl;
+        *fLog << warn << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+        *fLog << warn << " fDCCalibration " << fDCCalibration << " fDCCalibrationRMS " << fDCCalibrationRMS << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+        fDCCalibration = maxprobdc;
+        fDCCalibrationRMS = rmsguess/1.175; // FWHM=2.35*rms
+      }
+
+   return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MCalibrateDC.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MCalibrateDC.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MCalibrateDC.h	(revision 17960)
@@ -0,0 +1,76 @@
+#ifndef MARS_MCalibrateDC
+#define MARS_MCalibrateDC
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH1F;
+class MGeomCam;
+class MCameraDC;
+
+class MCalibrateDC : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MCameraDC     *fCurr;
+    MTime         *fTimeCurr;
+
+    MTime fStartingMissCalibration;
+    MTime fEndingMissCalibration;
+    
+    TString fFileName;
+    
+    TH1F *fCalHist;
+    MHCamera fDisplay;
+
+    Double_t fMinDCAllowed; //[uA]
+    
+    UInt_t fNumPixels ;
+    TArrayD  fDCCalibrationFactor;
+    Double_t fDCMissCalibrationFactor;
+    
+    Double_t fDCCalibration; //[uA]
+    Double_t fDCCalibrationRMS; //[uA]
+    
+    Bool_t ProcessFile();
+    Bool_t DCCalibrationCalc();
+    
+  public:
+    
+    MCalibrateDC(TString filename="", const char *name=NULL, const char *title=NULL);
+    ~MCalibrateDC();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    //Setters
+    void SetFileName(TString filename="") {fFileName=filename;}
+    void SetMinDCAllowed(Double_t mindc=0.5) {fMinDCAllowed=mindc;}
+    
+    //Getters
+    MHCamera& GetDisplay() { return fDisplay; }
+    TArrayD&  GetDCCalibrationFactor() { return fDCCalibrationFactor; }
+
+    ClassDef(MCalibrateDC, 0) // Taks to intercalibrate the DC of all pmts from a continuos light run
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MControlPlots.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MControlPlots.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MControlPlots.cc	(revision 17960)
@@ -0,0 +1,262 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     04/2004 <mailto:jrico@ifae.es>
+!              Ester Aliu      10/2004 <mailto:aliu@ifae.es> (update according
+!                                        the new classes of the islands)
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MControlPlots
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+
+#include "TStyle.h"
+
+#include "MParList.h"
+#include "MControlPlots.h"
+#include "MIslands.h"
+#include "MImgIsland.h"
+#include "MHCamera.h"
+#include "MGeomCamMagic.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MControlPlots);
+
+using namespace std;
+
+static const TString gsDefName  = "MControlPlots";
+static const TString gsDefTitle = "Produce some control plots";
+
+// -------------------------------------------------------------------------
+//
+// Constructor
+//
+MControlPlots::MControlPlots(TString filename,const char* name, const char* title)
+  : fMode(kOn), fFileName(filename), fGeomCam(NULL), fIslands(NULL), fProduceFile(kTRUE)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fCameraHisto[kOn] = NULL;
+    fCameraHisto[kOff] = NULL;
+
+}
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MControlPlots::~MControlPlots()
+{
+  Clear();
+
+  if(fCameraHisto[kOn])
+    delete fCameraHisto[kOn];
+  if(fCameraHisto[kOff])
+    delete fCameraHisto[kOff];
+}
+
+void MControlPlots::Clear(const Option_t *o)
+{
+
+  if(fGeomCam)
+    delete fGeomCam;
+
+  fGeomCam = NULL;
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Look for needed containers.
+//
+Int_t MControlPlots::PreProcess(MParList* pList)
+{ 
+
+  Reset();
+
+  // FIXME! only valid for Magic geometry for the time being!
+  fGeomCam = new MGeomCamMagic;
+
+  // look for MIslands object
+  fIslands = (MIslands*)pList->FindObject("MIslands");
+  if (!fIslands)
+    *fLog << warn << AddSerialNumber("MIslands") << " [MIslands] not found... Some control plots will not be produced" << endl;
+  else
+    {  
+      if (fCameraHisto[fMode])
+	{
+	  *fLog << err << GetDescriptor() 
+		<< "Camera with mode " << fMode << " already existing " << endl;
+	  return kFALSE;
+	}
+      TString name = "";
+      switch (fMode)
+	{
+	case kOn:
+	  name += "On";
+	  break;
+	case kOff:
+	  name += "Off";
+	  break;
+	}
+      fCameraHisto[fMode] = new MHCamera(*fGeomCam,
+					 name.Data(),
+					 "Pixels surviving Image Cleaning");
+    }
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+//
+Int_t MControlPlots::Process()
+{ 
+  if(!fIslands) return kTRUE;
+
+  MImgIsland *imgIsl = NULL;
+  TIter Next(fIslands->GetList());
+  
+  Int_t pixNum = 0;  
+  Int_t idPix = -1;
+  
+  while ((imgIsl=(MImgIsland*)Next())) 
+    {
+      pixNum = imgIsl->GetPixNum();
+      
+      for(Int_t k = 0; k<pixNum; k++)
+	{
+	  idPix = imgIsl->GetPixList(k);
+	  fCameraHisto[fMode]->Fill(idPix,1.);
+	  fCameraHisto[fMode]->SetUsed(idPix);
+	}
+    }
+
+  /*  for (UInt_t i=0;i<fGeomCam->GetNumPixels();i++)
+    {
+      //      cout << fIslands->GetIslId(i) << " ";
+      if (fIslands->GetIslId(i)>=0)
+	{
+	  fCameraHisto[fMode]->Fill(i,1);
+	  fCameraHisto[fMode]->SetUsed(i);
+	}
+	}*/
+
+  //  cout << endl;
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+//
+Int_t MControlPlots::PostProcess()
+{
+  if(!fProduceFile) return kTRUE;
+  if(fProduceFile && !fFileName.Length())
+    {
+      *fLog << warn <<  "MControlPlots::PostProcess Warning: output file requested but no name for it" << endl;
+      return kTRUE;
+    }
+
+  // Canvas style
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetStatColor(0);
+  gStyle->SetTitleFillColor(0);
+
+  TCanvas* c = new TCanvas("survivals","Pixels surviving Image Cleaning",800,800);
+  MHCamera* diff=NULL;
+
+  // in case both on and off histos are present, print both and the difference between them
+  if(fCameraHisto[kOn] && fCameraHisto[kOff])
+    {      
+      diff = new MHCamera(*fGeomCam,"Diff","Difference of pixels surviving Image Cleaning");
+
+      // Normalize Off to On
+      Float_t NormOn=0;
+      Float_t NormOff=0;
+      for(Int_t i=1;i<diff->GetSize()-2;i++)
+	{
+	  NormOff+=fCameraHisto[kOff]->GetBinContent(i);
+	  NormOn+=fCameraHisto[kOn]->GetBinContent(i);
+	}      
+
+      fCameraHisto[kOff]->Scale(NormOn/NormOff);
+
+      for(Int_t i=1;i<diff->GetSize()-2;i++)
+	{
+	  diff->SetBinContent(i,(Double_t)fCameraHisto[kOn]->GetBinContent(i)-fCameraHisto[kOff]->GetBinContent(i));
+	  diff->SetUsed(i);
+	}      
+      fCameraHisto[kOn]->SetPrettyPalette();
+      fCameraHisto[kOff]->SetPrettyPalette();
+      diff->SetPrettyPalette();
+
+      c->Divide(2,2);
+
+      Float_t max = TMath::Max(fCameraHisto[kOn]->GetMaximum(),fCameraHisto[kOff]->GetMaximum());
+      Float_t min = TMath::Min(fCameraHisto[kOn]->GetMinimum(),fCameraHisto[kOff]->GetMinimum());
+      fCameraHisto[kOn]->SetMaximum(max);
+      fCameraHisto[kOn]->SetMinimum(min); 
+      fCameraHisto[kOff]->SetMaximum(max);
+      fCameraHisto[kOff]->SetMinimum(min); 
+      
+      c->cd(1);
+      fCameraHisto[kOn]->Draw();
+      gPad->Modified();
+      gPad->Update();
+
+      c->cd(2);
+      fCameraHisto[kOff]->Draw();
+      gPad->Modified();
+      gPad->Update();
+
+      c->cd(3);
+      diff->Draw();
+      gPad->Modified();
+      gPad->Update();      
+
+      c->cd(4);
+      diff->DrawProjection();
+      gPad->Modified();
+      gPad->Update();
+    }
+  // plot the existing histo
+  else
+    {
+      c->cd(1);
+      fCameraHisto[fMode]->Draw();
+      gPad->Modified();
+      gPad->Update();
+    }
+  
+  c->SaveAs(fFileName);
+  delete c;  
+  if(diff)
+    delete diff;
+  return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MControlPlots.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MControlPlots.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MControlPlots.h	(revision 17960)
@@ -0,0 +1,47 @@
+#ifndef MARS_MControlPlots
+#define MARS_MControlPlots
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TString;
+class MIslands;
+class MImgIsland;
+class MGeomCam;
+class MHCamera;
+
+class MControlPlots : public MTask
+{
+ public:
+  enum OnOffMode_t {kOn=0,kOff=1};
+  
+ private:
+  OnOffMode_t  fMode;           // On/Off data mode 
+  TString      fFileName;       // name of the ps file
+  MGeomCam*    fGeomCam;        // pointer to camera geometry object
+  MIslands*    fIslands;        // pointer to the island object
+  MHCamera*    fCameraHisto[2]; // pointer to camera histos
+  Bool_t       fProduceFile;    // flag to produce the ouput (ps) file
+  
+  Int_t PreProcess(MParList *plist);
+  Int_t Process();
+  Int_t PostProcess();
+
+ public:
+  MControlPlots(TString filename="",const char* name=NULL, const char* title=NULL);
+
+  virtual ~MControlPlots();
+
+  void Reset() { Clear(); }
+  void Clear(const Option_t *o="");
+
+  void SetFilename(TString fname)           {fFileName=fname;}
+  void SetMode(OnOffMode_t mode)            {fMode=mode;}
+  void SetProduceFile(Bool_t mod=kTRUE)     {fProduceFile=mod;}  
+
+  ClassDef(MControlPlots, 0) // task to produce some control plots
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MDispCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MDispCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MDispCalc.cc	(revision 17960)
@@ -0,0 +1,345 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Eva Domingo    , 12/2004 <mailto:domingo@ifae.es>
+!              Wolfgang Wittek, 12/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MDispCalc                                                             //
+//                                                                         //
+//   This task calculates Disp with a given parameterization               //
+//   (parameters are stored in the MDispParameters container)              //
+//   Also the matrix of variables to be used in the Disp                   //
+//   parameterization is defined                                           //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MDispCalc.h"
+
+#include <math.h>
+#include <TArray.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MMcEvt.hxx"
+#include "MPointingPos.h"
+#include "MImageParDisp.h"
+#include "MDispParameters.h"
+
+#include "MHMatrix.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MDispCalc);
+
+using namespace std;
+
+static const Int_t nPars=5;   // number of parameters used in the Disp expression
+
+enum dispVar_t {kSize,kWidth,kLength,kConc,kLeakage1,kLeakage2,kTotVar};  // enum variables for the
+                                                                          // matrix columns mapping
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+MDispCalc::MDispCalc(const char *imagepardispname, 
+		     const char *dispparametersname, 
+                     const char *name, const char *title)
+  :     fImageParDispName(imagepardispname), 
+	fDispParametersName(dispparametersname),
+	fLogSize0(3.), fLength0(0.1), fWidth0(0.05), 
+	fConc0(0.35), fLeakage10(0.05), fLeakage20(0.1)
+{
+    fName  = name  ? name  : "MDispCalc";
+    fTitle = title ? title : "Class to calculate Disp";
+
+    // object of MDispParamteres that will hold the Disp parameters
+    fDispParameters = new MDispParameters(fDispParametersName);
+    // initialize the size of the Disp parameters and parameters stepsizes arrays
+    fDispParameters->GetParameters().Set(nPars);
+    fDispParameters->GetStepsizes().Set(nPars);
+    // set Disp parameters to their default values
+    fDispParameters->InitParameters();
+
+    fMatrix = NULL;
+
+    // initialize mapping array dimension to the number of columns of fMatrix
+    fMap.Set(kTotVar);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MDispCalc::~MDispCalc()
+{
+    delete fDispParameters;
+}
+
+
+// --------------------------------------------------------------------------
+//
+Int_t MDispCalc::PreProcess(MParList *pList)
+{
+    // look for the defined camera geometry to get mm to deg conversion factor
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." 
+              << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+
+    // look for Disp related containers
+    fImageParDisp = (MImageParDisp*)pList->FindCreateObj("MImageParDisp", 
+                                                         fImageParDispName);
+    if (!fImageParDisp)
+    {
+        *fLog << err << fImageParDispName 
+              << " [MImageParDisp] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    //-----------------------------------------------------------
+    // if fMatrix exists, skip preprocessing and just read events from matrix;
+    // if doesn't exist, read variables values from containers, so look for them
+    if (fMatrix)
+        return kTRUE;
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject("MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << "MSrcPosCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHil = (MHillas*)pList->FindObject("MHillas");
+    if (!fHil)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject("MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << "MHillasExt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << "MNewImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... This is not a MC file,"
+	      << " you are not trying to optimize Disp, just calculating it."
+	      << endl;
+	//        return kFALSE;
+    }
+
+    fPointing = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointing)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+	return kFALSE;
+    }
+
+    //------------------------------------------
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers for the Disp parameterization. This function adds all 
+// necessary columns to the given matrix. Afterwards, you should fill 
+// the matrix with the corresponding data (eg from a file by using 
+// MHMatrix::Fill). Then, if you loop through the matrix (eg using 
+// MMatrixLoop), MDispCalc::Calc will take the values from the matrix 
+// instead of the containers.
+//
+void MDispCalc::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    fMap[kSize]      = fMatrix->AddColumn("MHillas.fSize");
+    fMap[kWidth]     = fMatrix->AddColumn("MHillas.fWidth");
+    fMap[kLength]    = fMatrix->AddColumn("MHillas.fLength");
+
+    fMap[kConc]      = fMatrix->AddColumn("MNewImagePar.fConc");
+    fMap[kLeakage1]  = fMatrix->AddColumn("MNewImagePar.fLeakage1");
+    fMap[kLeakage2]  = fMatrix->AddColumn("MNewImagePar.fLeakage2");
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns a mapped value from the Matrix
+//
+Double_t MDispCalc::GetVal(Int_t i) const
+{
+    Double_t val = (*fMatrix)[fMap[i]];
+
+    //    *fLog << "MDispCalc::GetVal; i, fMatrix, fMap, val = "
+    //          << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+    return val;
+}
+
+
+// ---------------------------------------------------------------------------
+//
+// Calculate Disp 
+// 
+//
+Int_t MDispCalc::Process()
+{
+    // get variables needed to compute disp from the matrix or the containers
+    const Double_t size     = fMatrix ? GetVal(kSize)     : fHil->GetSize();
+    const Double_t width0   = fMatrix ? GetVal(kWidth)    : fHil->GetWidth();
+    const Double_t length0  = fMatrix ? GetVal(kLength)   : fHil->GetLength();
+    const Double_t conc     = fMatrix ? GetVal(kConc)     : fNewPar->GetConc();
+    const Double_t leakage1 = fMatrix ? GetVal(kLeakage1) : fNewPar->GetLeakage1();
+    const Double_t leakage2 = fMatrix ? GetVal(kLeakage2) : fNewPar->GetLeakage2();
+
+    // convert to deg
+    const Double_t width   = width0  * fMm2Deg;
+    const Double_t length  = length0 * fMm2Deg;
+
+    // create an array to pass the variables to MDispCalc::Calc
+    TArrayD imagevars(kTotVar);
+    imagevars[kSize]      = log10(size);
+    imagevars[kWidth]     = width;
+    imagevars[kLength]    = length;
+    imagevars[kConc]      = conc;
+    imagevars[kLeakage1]  = leakage1;
+    imagevars[kLeakage2]  = leakage2;
+
+    // compute Disp
+    Double_t disp = Calc(imagevars); 
+
+    // save value into MImageParDisp container
+    fImageParDisp->SetDisp(disp);
+    fImageParDisp->SetReadyToSave();
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the Disp parameterization and Calculate Disp
+//
+//
+Double_t MDispCalc::Calc(TArrayD &imagevar)
+{
+    // get parameters
+    const TArrayD& p = fDispParameters->GetParameters();
+
+    // get image variables to be used in the Disp parameterization
+    Double_t logsize  = imagevar[0];
+    Double_t width    = imagevar[1];
+    Double_t length   = imagevar[2];
+    //    Double_t conc     = imagevar[3];
+    //    Double_t leakage1 = imagevar[4];
+    //    Double_t leakage2 = imagevar[5];
+    
+    // Disp parameterization to be optimized
+    //  Note: fLogSize0, fLength0... variables are introduced to uncorrelate as much
+    //        as possible the parameters in the Disp expression, with the purpose of
+    //        helping the minimization algorithm to converge. They are set approx.
+    //        to their distribution mean value in the MDisp constructor, but can be 
+    //        changed using the corresponding set function.
+    //
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;
+
+//    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(length-fLength0) 
+//      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(length-fLength0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*length/width;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(length-fLength0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0) + p[5]*(length-fLength0))*width/length;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(width-fWidth0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;   // + p[5]*(width-fWidth0))*width/length;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(conc-fConc0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;   // + p[5]*(conc-fConc0))*width/length;
+
+    //    Double_t disp = ( p[0] + p[1]*(logsize-fLogSize0) 
+    //		      + p[2]*pow(logsize-fLogSize0,2)
+    //		      + p[3]*pow(logsize-fLogSize0,3) 
+    //		      + p[4]*pow(logsize-fLogSize0,4) )
+    //                    *(1-width/length);
+
+    
+    Double_t disp = ( p[0] + p[1]*(logsize-fLogSize0) 
+    		    + p[2]*pow(logsize-fLogSize0,2)
+    		    + p[3]*pow(logsize-fLogSize0,3) 
+    		    + p[4]*pow(logsize-fLogSize0,4) )
+                        *( 1./(1.+width/length) );
+
+    /*
+    Double_t disp = ( p[0] + p[1]*(logsize) 
+		    + p[2]*pow(logsize,2)
+    		    + p[3]*pow(logsize,3) 
+		    + p[4]*pow(logsize,4) )
+                        *( 1./(1.+width/length) );
+    */
+
+    return disp;
+}
+
+//===========================================================================
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MDispCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MDispCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MDispCalc.h	(revision 17960)
@@ -0,0 +1,107 @@
+#ifndef MARS_MDispCalc
+#define MARS_MDispCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MSrcPosCam;
+class MHillas;
+class MHillasExt;
+class MNewImagePar;
+class MMcEvt;
+class MPointingPos;
+class MImageParDisp;
+class MDispParameters;
+class MHMatrix;
+class MParList;
+
+class MDispCalc : public MTask
+{
+private:
+
+    MSrcPosCam      *fSrcPos;
+    MHillas         *fHil;
+    MHillasExt      *fHilExt;
+    MNewImagePar    *fNewPar;
+    MMcEvt          *fMcEvt;
+    MPointingPos    *fPointing;        
+    
+    MImageParDisp   *fImageParDisp;    //! output container for Disp value
+    MDispParameters *fDispParameters;  //!  container for Disp parameters
+
+    TString  fImageParDispName;    // name of container to store Disp
+    TString  fDispParametersName;  // name of container for Disp parameters
+
+    Double_t fLogSize0;            // Variables introduced in the Disp expression
+    Double_t fLength0;             // to shift the minimization around the mean
+    Double_t fWidth0;              // values of the variables, so it makes easier
+    Double_t fConc0;               // to MINUIT to converge. Default values are set
+    Double_t fLeakage10;           // in the constructor (to their standard mean 
+    Double_t fLeakage20;           // distribution values) but can be changed with
+                                   // the corresponding set function.
+
+    Double_t fMm2Deg;              // conversion factor from mm to deg
+
+    MHMatrix *fMatrix;             // matrix defined to have as much columns as 
+                                   // variables wanted to parameterize Disp,
+                                   // and as much rows as events used for the 
+                                   // optimization (filled at MFindDisp)
+
+    TArrayI  fMap;                 // array storing the matrix mapping column
+                                   // numbers corresponding to each variable
+                                   // added to fMatrix
+
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Double_t GetVal(Int_t i) const;        // get value of variable entered in the
+                                           // matrix at column fMap[i]
+
+
+public:
+
+    MDispCalc(const char *imagepardispname = "MImageParDisp",
+	      const char *dispname         = "MDisp",
+              const char *name=NULL, const char *title=NULL);
+    ~MDispCalc();
+
+    void InitMapping(MHMatrix *mat);       // define the matrix of variables
+                                           // needed for the Disp parameterization 
+
+    Double_t Calc(TArrayD &imagevar);      // calculate Disp with a given expression
+
+    void SetLogSize0(Double_t newmeanval)  { fLogSize0  = newmeanval; }
+    void SetWidth0(Double_t newmeanval)    { fWidth0    = newmeanval; }
+    void SetLength0(Double_t newmeanval)   { fLength0   = newmeanval; }
+    void SetConc0(Double_t newmeanval)     { fConc0     = newmeanval; }
+    void SetLeakage10(Double_t newmeanval) { fLeakage10 = newmeanval; }
+    void SetLeakage20(Double_t newmeanval) { fLeakage20 = newmeanval; }
+
+    MDispParameters *GetDispParameters()   { return fDispParameters; }
+
+    ClassDef(MDispCalc, 0) // Task to evaluate Disp
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MEffAreaAndCoeffCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MEffAreaAndCoeffCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MEffAreaAndCoeffCalc.cc	(revision 17960)
@@ -0,0 +1,420 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     02/2005 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Computes the Effective areas and coefficients for unfolding for a given
+// spectrum that can be parametrized by a function
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "MEffAreaAndCoeffCalc.h"
+
+#include "TF1.h"
+#include "MHillas.h"
+#include "MMcEvt.hxx"
+#include "TH2F.h"
+#include "TFile.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEffAreaAndCoeffCalc);
+
+using namespace std;
+
+const Int_t ntbins=1;                      // default number of theta bins
+const Double_t tbin[ntbins+1] = {0,90};    // default theta bins bounds
+const Int_t nebins = 10;                   // default number of energy bins
+const Float_t emin = 10.;                  // default minimum energy value
+const Float_t emax = 10000.;               // default maximum energy value
+const Int_t nsubbins = 20;                 // default number of subbins per bin
+const Char_t* deff = "4.e9*pow(x,-2.6+1)"; // default spectrum function
+
+// -------------------------------------------------------------------------
+//
+// Constructor
+//
+MEffAreaAndCoeffCalc::MEffAreaAndCoeffCalc()
+  : fSpec(NULL),  fEmin(emin), fEmax(emax), fEbins(nebins), fEsubbins(nsubbins), 
+    fWeight(NULL), fCoeff(NULL), fEffA(NULL)//, fFile(NULL)
+{
+  // set the default function
+  SetFunction(deff);  
+
+  // create the TChains 
+  fCini = new TChain("OriginalMC");
+  fCcut = new TChain("Events");
+
+  // define some useful aliases
+  fCini->SetAlias("logenergy","log10(MMcEvtBasic.fEnergy)");
+  fCini->SetAlias("theta","MMcEvtBasic.fTelescopeTheta*180./3.14159");
+
+  fCcut->SetAlias("logenergy","log10(MMcEvt.fEnergy)");
+  fCcut->SetAlias("theta","MMcEvt.fTelescopeTheta*180./3.14159");
+
+  fCcut->SetBranchAddress("MHillas.",&fHillas);
+  fCcut->SetBranchAddress("MMcEvt.",&fMcEvt);
+
+  // initial value of the zenith angle binning
+  SetThetaBinning(ntbins,tbin);
+  
+  // borra
+  //  fFile = new TFile("coeftest.root","RECREATE");
+}
+
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MEffAreaAndCoeffCalc::~MEffAreaAndCoeffCalc()
+{
+  if(fSpec)
+    delete fSpec;
+
+  if(fTbin)
+    delete [] fTbin;
+
+  if(fWeight)
+    delete [] fWeight;
+
+  if(fCoeff)
+    delete fCoeff;
+
+  if(fEffA)
+    delete fEffA;
+
+
+  delete fCini;
+  delete fCcut;
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the binning in zenith angle
+//
+void MEffAreaAndCoeffCalc::SetThetaBinning(Int_t n, const Double_t* binlist)
+{
+  fNTbins=n;
+  if(fTbin) delete [] fTbin;
+  fTbin = new Double_t[n+1];
+  for(Int_t i=0;i<n+1;i++)
+    fTbin[i] = binlist[i];
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the function by expression and minimum and maximum energies
+//
+void MEffAreaAndCoeffCalc::SetFunction(const Char_t* chfunc, Float_t emin, Float_t emax)
+{
+  if(fSpec)
+    delete fSpec;
+  if(emin<=0 || emax<=0 || emax<emin)
+    {
+      emin = fEmin;
+      emax = fEmax;
+    }
+  else
+    {
+      fEmin = emin;
+      fEmax = emax;
+    }
+  fSpec = new TF1("fspec",chfunc,emin,emax);
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the function by function pointer
+//
+void MEffAreaAndCoeffCalc::SetFunction(TF1* newf)
+{
+  if(fSpec)
+    delete fSpec;
+  fSpec = newf;
+}
+
+// -------------------------------------------------------------------------
+//
+// fill the histogram containing the original sample energy spectrum
+//
+void MEffAreaAndCoeffCalc::FillOriginalSpectrum()
+{  
+}
+
+// -------------------------------------------------------------------------
+//
+// compute the weights for a particular input spectrum
+//
+void MEffAreaAndCoeffCalc::ComputeWeights()
+{  
+  // OJO!! maybe this should be hard-coded somewhere else
+  const Float_t abslogmin=0.;
+  const Float_t abslogmax=5.;
+
+  const Float_t logemin = TMath::Log10(fEmin);
+  const Float_t logemax = TMath::Log10(fEmax);
+  const Float_t de    = (logemax-logemin)/fEbins; // bin size (in log)
+  const Float_t desub = de/fEsubbins; // subbin size (in log)
+  const Int_t esbins   = fEbins*fEsubbins; // total number of subbins
+
+  // compute the binning for weights histogram
+  const Int_t nmindist = (logemin>abslogmin)? Int_t((logemin-abslogmin)/desub) : 0;
+  const Int_t nmaxdist = (logemax<abslogmax)? Int_t((abslogmax-logemax)/desub) : 0;
+
+  fLogEWmin = logemin-desub*nmindist;
+  fLogEWmax = logemax+desub*nmaxdist;
+  fEWbins   = nmindist+esbins+nmaxdist;
+  
+  // reset the weights array
+  if(fWeight)
+    delete [] fWeight;
+  fWeight = new Double_t[fEWbins];
+    
+
+  TH1F* horigs = new TH1F("horigs","Original energy spectrum",fEWbins,fLogEWmin,fLogEWmax);
+  fCini->Draw("logenergy>>horigs","","goff");
+  // borra
+  //  horigs->Write();
+
+  // borra
+  //  TH1F hw("hw","hw",fEWbins,fLogEWmin,fLogEWmax);
+  for(Int_t i=0;i<fEWbins;i++)
+    {
+      const Float_t denom = horigs->GetBinContent(i+1);               // number of events in initial spectrum
+      const Float_t ew    = TMath::Power(10,fLogEWmin+(i+0.5)*desub); // real energy
+      const Float_t numer = fSpec->Eval(ew);                          // number of events for the required spectrum
+      if(denom>10)
+	fWeight[i]=numer/denom;
+      else
+	{
+	  //	  cout << "MEffAreaAndCoeffCalc::ComputeWeights Warning: no statistic to compute weight for energy " << ew << ", setting it to -1 "  << endl;
+	  fWeight[i]=-1;
+	}
+      // borra
+      //      hw.SetBinContent(i+1,fWeight[i]);
+    }
+  // borra
+  //  hw.Write();
+
+  delete horigs;
+}
+
+// --------------------------------------------------------------
+//
+// compute the coefficients used for the (iterative) unfolding 
+//
+void MEffAreaAndCoeffCalc::ComputeCoefficients()
+{ 
+  if(!fWeight)
+    {
+      cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: No weights computed! nothing done" << endl;
+      return;
+    }
+
+  const Float_t logemin = TMath::Log10(fEmin);
+  const Float_t logemax = TMath::Log10(fEmax);
+  const Float_t de = (logemax-logemin)/fEbins; // bin size (in log)
+  const Float_t desub = de/fEsubbins; // subbin size (in log)
+  const Int_t nentries = Int_t(fCcut->GetEntries());
+ 
+  // declare needed histos
+  TH2F* hest = new TH2F("hest","Estimated energy",fEbins,logemin,logemax,fNTbins,fTbin);
+  TH2F* hmc  = new TH2F("hmc","MC energy",fEbins,logemin,logemax,fNTbins,fTbin);
+
+  // borra
+  //  TH1F* hest1  = new TH1F("hest1","Estimated energy",fEbins,logemin,logemax);
+  //  TH1F* hmc1   = new TH1F("hmc1","MC energy",fEbins,logemin,logemax);
+  //  TH1F* coef1  = new TH1F("coef1","coefficients",fEbins,logemin,logemax);
+
+  // reset the coefficients
+  if(fCoeff)
+    delete fCoeff;
+  fCoeff = new TH2F("fcoeff","Coefficients for unfolding",fEbins,logemin,logemax,fNTbins,fTbin);
+
+  // fill the histograms of estimated and measured energy for weighted events
+  for(Int_t i=0;i<nentries;i++)
+    {
+      fCcut->GetEntry(i);  
+
+      // mc and estimated energy
+      // OJO!! Estimated energy will be taken directly from some input container
+      Float_t emc   = fMcEvt->GetEnergy();
+      Float_t estim = fHillas->GetSize()/0.18/15.;
+
+      if((emc<fEmin && estim<fEmin) || (emc>fEmax && estim>fEmax) ||
+	 (emc<fEmin && estim>fEmax) || (emc>fEmax && estim<fEmin))
+	continue;
+
+      Float_t theta = fMcEvt->GetTheta()*180./3.14159; // zenith angle (in degrees)
+
+      // compute the bin where the weight is taken from
+      Int_t wbin = Int_t((TMath::Log10(emc)-fLogEWmin)/desub);
+
+      // fill the histograms
+      if(wbin<fEWbins)
+	{
+	  if(fWeight[wbin]>0)
+	    {
+	      hest->Fill(TMath::Log10(estim),theta,fWeight[wbin]); 
+	      hmc->Fill(TMath::Log10(emc),theta,fWeight[wbin]);
+	      // borra
+// 	      if(theta<fTbin[1])
+// 		{
+// 		  hest1->Fill(TMath::Log10(estim),fWeight[wbin]); 
+// 		  hmc1->Fill(TMath::Log10(emc),fWeight[wbin]);
+// 		}
+	    }
+	  else
+	    cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: event " << i << " with energy " << emc << " has no computed weight (lack of MC statistics), skipping" << endl;
+	}
+      else
+      	cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: event " << i << " with energy " << emc << " has energy out of bounds, skipping" << endl;
+    }
+
+  // divide the previous histos to get the coefficients for unfolding
+  for(Int_t j=0;j<fNTbins;j++)
+    for(Int_t i=0;i<fEbins;i++)
+      {
+	const Float_t num = hmc->GetBinContent(i+1,j+1);
+	const Float_t den = hest->GetBinContent(i+1,j+1);
+	//borra
+// 	const Float_t num1 = hmc1->GetBinContent(i+1);
+// 	const Float_t den1 = hest1->GetBinContent(i+1);
+	if(den)
+	  {
+	    fCoeff->SetBinContent(i+1,j+1,num/den);
+	    //borra
+// 	    if(j==0 && den1)
+// 	      coef1->SetBinContent(i+1,num1/den1);
+	  }
+	else
+	  {
+	    cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: energy bin " << i << ", thetabin " << j << " has no survivors, setting coefficient to 0" << endl;
+	    fCoeff->SetBinContent(i+1,j+1,0.);
+	  }
+      }
+
+
+  //borra
+//   hmc1->Write();
+//   hest1->Write();
+//   coef1->Write();
+
+  delete hmc;
+  delete hest;
+}
+
+// --------------------------------------------------------------
+//
+// compute the coefficients used for the (iterative) unfolding 
+//
+void MEffAreaAndCoeffCalc::ComputeEffectiveAreas()
+{
+  if(!fWeight)
+    {
+      cout << "MEffAreaAndCoeffCalc::ComputeEffectiveAreas Warning: No weights computed! nothing done" << endl;
+      return;
+    }
+
+  //OJO!! radius should be read from somewhere!
+  const Float_t radius = 30000.; // generation radius (in cm)
+  const Float_t Atot = 3.14159*radius*radius; //total area (in cm^2)
+  const Float_t logemin = TMath::Log10(fEmin);
+  const Float_t logemax = TMath::Log10(fEmax);
+  const Int_t esbins = fEbins*fEsubbins; // total number of subbins
+  const Float_t de = (logemax-logemin)/fEbins; // bin size (in log)
+  const Float_t desub = de/fEsubbins; // subbin size (in log)
+
+  // reset the effective areas
+  if(fEffA)
+    delete fEffA;
+  fEffA = new TH2F("feffa","Effective area",fEbins,logemin,logemax,fNTbins,fTbin);
+  //borra
+//   TH1F eff("eff","Effective area",fEbins,logemin,logemax);
+  
+  // fill the spectrum of the survivors
+  TH2F* hpass= new TH2F("hpass","Survivors",esbins,logemin,logemax,fNTbins,fTbin);
+  TH2F* horig= new TH2F("horig","Original events",esbins,logemin,logemax,fNTbins,fTbin);
+
+  fCcut->Draw("theta:logenergy>>hpass","","goff");
+  fCini->Draw("theta:logenergy>>horig","","goff");
+  
+  // compute the effective areas
+  for(Int_t j=0;j<fNTbins;j++)
+    for(Int_t i=0;i<fEbins;i++)
+      {
+	Float_t effarea =0;
+	Float_t wtot = 0;
+	for(Int_t k=0;k<fEsubbins;k++)
+	  {
+	    Float_t numerator = hpass->GetBinContent(i*fEsubbins+k+1,j+1);
+	    Float_t denominator = horig->GetBinContent(i*fEsubbins+k+1,j+1);
+	    
+	    if(denominator<=0)
+	      cout << "MEffAreaAndCoeffCalc::ComputeEffectiveAreas Warning: energy subbin " << i*fEsubbins+k <<", theta bin " << j << " contains no events" << endl;
+	    else
+	      {
+		const Float_t ew = TMath::Power(10,logemin+(i*fEsubbins+k+0.5)*desub);
+		const Float_t ww = fSpec->Eval(ew);
+		effarea+=Atot*numerator/denominator*ww;
+		wtot   += ww;
+	      }
+	  }
+	if(!wtot)
+	  {
+	    cout << "MEffAreaAndCoeffCalc::ComputeEffectiveAreas Warning: energy bin " << i <<", theta bin " << j << " contains no events setting effective area to 0" << endl;
+	    fEffA->SetBinContent(i+1,j+1,0);
+	  }	    
+	else
+	  {
+	    fEffA->SetBinContent(i+1,j+1,effarea/wtot);	
+	    // borra
+// 	    if(j==0)
+// 	      {
+// 		//		cout << "*****" << i << ": " << effarea/wtot << endl;
+// 		eff.SetBinContent(i+1,effarea/wtot);
+// 	      }
+	  }
+      }
+
+  // borra
+//   eff.Write();
+  
+  delete hpass;
+  delete horig;
+}
+
+// --------------------------------------------------------------
+//
+// Call the internal functions to compute all the factors
+//
+void MEffAreaAndCoeffCalc::ComputeAllFactors()
+{
+  ComputeWeights();
+  ComputeCoefficients();
+  ComputeEffectiveAreas();
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MEffAreaAndCoeffCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MEffAreaAndCoeffCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MEffAreaAndCoeffCalc.h	(revision 17960)
@@ -0,0 +1,79 @@
+#ifndef MARS_MEffAreaAndCoeffCalc
+#define MARS_MEffAreaAndCoeffCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TF1;
+class TH1F;
+class TH2F;
+class MHillas;
+class MMcEvt;
+
+#include "TChain.h"
+
+class MEffAreaAndCoeffCalc
+{
+ private:
+
+  TF1* fSpec;        // function used to parametrize the spectrum
+
+  Float_t fEmin;    // Minimum energy in GeV
+  Float_t fEmax;    // Maximum energy in GeV
+  Int_t fEbins;      // number of bins to build spectrum
+  Int_t fEsubbins;   // number of subbins per big bin (to compute weights, eff areas...)
+
+  Float_t fLogEWmin; // Log Minimum energy for weights (in GeV)
+  Float_t fLogEWmax; // Log Maximum energy for weights (in GeV)
+  Int_t    fEWbins;   // Number of bins for weights
+
+  Int_t fNTbins;      // Number of bins in zenith angle
+  Double_t* fTbin;     // array containing bin boundaries (size must be fNTbins+)
+
+  Double_t* fWeight; // array containing weights
+  TH2F* fCoeff;      // histogram containing unfolding coefficients
+  TH2F* fEffA;       // histogram containing effective areas
+
+  TChain* fCini;     // chain for initial MC files (before trigger)
+  TChain* fCcut;     // chain for surviving MC events (after cuts)
+
+  MHillas* fHillas;  // pointer to the MHillas Branch
+  MMcEvt*  fMcEvt;   // pointer to the MMcEvt Branch
+
+  //  TFile* fFile; // output file (for debugging only)
+
+ protected:
+
+  void FillOriginalSpectrum();
+  void ComputeCoefficients();
+  void ComputeWeights();
+  void ComputeEffectiveAreas();
+
+ public:
+
+  MEffAreaAndCoeffCalc();
+
+  virtual ~MEffAreaAndCoeffCalc();
+
+  void SetFunction(const Char_t* chfunc, Float_t emin=0., Float_t emax=0.);
+  void SetFunction(TF1*);
+  void SetEbins(Int_t i)    {fEbins=i;}
+  void SetEsubbins(Int_t i) {fEsubbins=i;}
+  void SetEmin(Float_t x)   {fEmin=x;}
+  void SetEmax(Float_t x)   {fEmax=x;}
+
+  void SetThetaBinning(Int_t n, const Double_t* binlist);
+
+  void AddFile(const Char_t* name) {fCini->Add(name); fCcut->Add(name);}
+
+  TH2F* GetEffectiveAreaHisto() {return fEffA;}
+  TH2F* GetCoefficientHisto()   {return fCoeff;}
+
+  void ComputeAllFactors();
+
+  ClassDef(MEffAreaAndCoeffCalc, 0) // task to compute the Effective areas and Coefficients for the unfolding 
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MFHVNotNominal.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MFHVNotNominal.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MFHVNotNominal.cc	(revision 17960)
@@ -0,0 +1,250 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 5/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MFHVNotNominal
+//
+//   Filter to look if the HV monitored value is in agreement with the
+//   expected nominal value. If this is not true it sets a flag in MBadPixelsCam
+//   to not use this pixel in the analysis.
+//   Moreover if more than a certain number of pixels (set by defauld to 230) is
+//   deviated from the nominal value the event is rejected.
+//
+//  Input Containers:
+//   MCameraHV
+//
+//  Output Containers:
+//   MBadPixelsCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MFHVNotNominal.h"
+
+#include <fstream>
+#include <stdlib.h>
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCameraHV.h"
+
+#include "MBadPixelsPix.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MFHVNotNominal);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MFHVNotNominal::MFHVNotNominal(const char *name, const char *title)
+  : fHV(NULL), fBadPixels(NULL), fHVConfFile("NULL"), fMaxHVDeviation(0.03), fMaxNumPixelsDeviated(230)
+{
+    fName  = name  ? name  : "MFHVNotNominal";
+    fTitle = title ? title : "Filter to reject events with too many pixels out of nominal HV";
+
+    fCut[0] = 0;
+    fCut[1] = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MCameraHV
+//
+// The following containers are searched and created if they were not found:
+//  - MBadPixelsCam
+//
+Int_t MFHVNotNominal::PreProcess(MParList *pList)
+{
+  // 
+  // Containers that have to be there.
+  //
+    fHV = (MCameraHV*)pList->FindObject("MCameraHV");
+    if (!fHV)
+    {
+      *fLog << err << "MCameraHV not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    // 
+    // Containers that are created in case that they are not there.
+    //
+    fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+    if (!fBadPixels)
+      {
+	*fLog << err << "Cannot find nor create MBadPixelsCam... aborting" << endl;
+	return kFALSE;
+      }
+
+    if (fHVConfFile != "NULL")
+      {
+        
+	const UInt_t npix = 577;
+	fHVNominal.Set(npix);
+
+	// Here we get the nominal HV values directitly from a CC 
+	// HV configuration file.
+	// Those files have the following structure:
+	//  [HV]
+	//  pixel_'hwnumber'='hvvalue'
+    
+	ifstream fin(fHVConfFile);
+    
+	TString str;
+	
+	if(!fin)
+	  {
+	    *fLog << err << "Imposible to open CC HV configuration file " << fHVConfFile << endl;
+	    return kFALSE;
+	  }
+	else
+	    *fLog << dbg << "Opened CC HV configuration file " << fHVConfFile << endl;
+
+	
+	fin >> str;
+	if(str != "[HV]")
+	  {
+	    *fLog << err << fHVConfFile << " file is not a CC HV configuration file" << endl;
+	    return kFALSE;
+	  }
+        else
+	    *fLog << dbg << fHVConfFile << " file is a good CC HV configuration file" << endl;
+
+	UInt_t npixinfile=0;
+	while(1)
+	  {
+	    fin >> str;
+	    if (fin.eof())
+	      break;
+
+	    UInt_t equalpos = str.Index("=");
+	    UInt_t underpos = str.Index("_");
+	    UInt_t length   = str.Length();
+
+	    TString tmp = str(underpos+1,equalpos-(underpos+1));
+	    UInt_t   hwpix = atoi((const char*)tmp);
+	    tmp = str(equalpos+1,length-(equalpos+1));
+	    Double_t value = atof((const char*)tmp);
+				  
+	    fHVNominal[hwpix-1]=value;
+	    npixinfile++;
+	  }
+	
+	fin.close();
+
+	if (npixinfile!=npix)
+	  {
+	    *fLog << err << fHVConfFile << " CC HV configuration file contain " << npixinfile << " pixels while the camera have " << npix << " pixels." << endl;
+	    return kFALSE;
+	  }	    
+      }
+
+    return kTRUE;
+}
+
+
+// ---------------------------------------------------------
+//
+// HVNotNominal rejection: 
+// 
+// Requiring less than fMaxHVDeviation deviation of HV monitored values
+// from nominal ones.
+// 
+// fMaxNumPixelsDeviated is set to 230 by default which is slightly higher 
+// than the number of outer pixels in MAGIC (for the case that 
+// the outer pixels have some defect).
+//
+Bool_t MFHVNotNominal::HVNotNominalRejection()
+{
+  UInt_t npix = fHVNominal.GetSize();
+
+  UInt_t notnominalpix = 0;
+
+  for (UInt_t idx=1; idx<npix; idx++)
+    {
+      Double_t hv = (*fHV)[idx];
+      Double_t nominal = fHVNominal[idx];
+      Double_t dev = 2.*TMath::Abs(nominal-hv)/(nominal+hv);
+      
+      if (dev > fMaxHVDeviation)
+	{
+	  MBadPixelsPix &bad = (*fBadPixels)[idx];
+	  bad.SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+	  bad.SetHardware(MBadPixelsPix::kHVNotNominal);
+	  notnominalpix++;
+	}
+    }
+
+    if (notnominalpix!=0)
+      fCut[0]++;
+
+    //
+    // If the camera contains more than fMaxNumPixelsDeviated
+    // pixels with deviated HV, then the event is discarted.
+    //
+
+    return notnominalpix > fMaxNumPixelsDeviated;
+}
+
+// -----------------------------------------------------------
+//
+//  Compare the HV monitored valued with the HV nominal ones.
+//
+Int_t MFHVNotNominal::Process()
+{
+    fResult = HVNotNominalRejection();
+
+    if (fResult)
+      fCut[1]++;
+
+    return kTRUE;
+}
+
+Int_t MFHVNotNominal::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << " " << setw(7) << fCut[0] << " (" << setw(3) ;
+    *fLog << (Int_t)(fCut[0]*100/GetNumExecutions()) ;
+    *fLog << "%) 'some not nominal pixel' events" << endl;
+
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (Int_t)(fCut[1]*100/GetNumExecutions()) ;
+    *fLog << "%) rejected events" ;
+    *fLog << " (with fMaxNumPixelsDeviated = " << fMaxNumPixelsDeviated << ")" << endl;
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MFHVNotNominal.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MFHVNotNominal.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MFHVNotNominal.h	(revision 17960)
@@ -0,0 +1,61 @@
+#ifndef MARS_MFHVNotNominal
+#define MARS_MFHVNotNominal
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MCameraHV;
+class MBadPixelsCam;
+
+class MFHVNotNominal : public MFilter
+{
+private:
+    MCameraHV      *fHV;          // HV monitored values of all pixels in the camera
+    MBadPixelsCam  *fBadPixels;   // Bad Pixels storage container
+
+    TString fHVConfFile;
+    TArrayD fHVNominal;
+    Bool_t  fResult;
+
+    Float_t fMaxHVDeviation;         // Maximum HV deviation from nominal values in %.
+    Float_t fMaxNumPixelsDeviated;   // Maximum number of pixels with HV deviated from nominal values.
+
+    UInt_t fCut[2];
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    Bool_t HVNotNominalRejection();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+  
+public:
+    MFHVNotNominal(const char *name=NULL, const char *title=NULL);
+
+    void    SetHVNominalValues(const TString hvconf)    { fHVConfFile = hvconf; }
+    void    SetHVNominalValues(const TArrayD hvnominal) { fHVNominal  = hvnominal; }
+
+    void    SetMaxHVDeviation(const Float_t d)       { fMaxHVDeviation = d; }
+    void    SetMaxNumPixelsDeviated(const Float_t n) { fMaxNumPixelsDeviated = n; }
+
+    Float_t GetfMaxHVDeviation() const          { return fMaxHVDeviation; }
+    Float_t GetfMaxNumPixelsDeviated() const    { return fMaxNumPixelsDeviated; }
+    TArrayD GetHVNominal() const { return fHVNominal; }
+    
+    ClassDef(MFHVNotNominal, 0)   // Filter to filter the events with HV out of nominal values 
+};
+
+#endif
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationCam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationCam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationCam.cc	(revision 17960)
@@ -0,0 +1,259 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 1/2005 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//            
+// MGainFluctuationCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MGainFluctuationCam.h"
+
+#include <math.h>
+#include <limits.h>
+#include <fstream>
+
+#include <TArrayD.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MGainFluctuationCam);
+ClassImp(MGainFluctuationCamIter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MGainFluctuationPix object for each pixel in the event
+//
+MGainFluctuationCam::MGainFluctuationCam(const char *name, const char *title) : fNumPixels(0)
+{
+    fName  = name  ? name  : "MGainFluctuationCam";
+    fTitle = title ? title : "(Gain Fluctuation)-Event Information";
+
+    fPixels = new TClonesArray("MGainFluctuationPix", 0);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// reset counter and delete netries in list.
+//
+void MGainFluctuationCam::Reset()
+{
+    fNumPixels  =  0;
+    fMaxIndex   = -1;
+    fLut.Set(0);
+    // fPixels->Delete();
+}
+
+void MGainFluctuationCam::FixSize()
+{
+    fLut.Set(fMaxIndex+1);
+
+    if (fPixels->GetEntriesFast() == (Int_t)fNumPixels)
+        return;
+
+    fPixels->ExpandCreateFast(fNumPixels);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Dump the gain fluctuation event to *fLog
+//
+void MGainFluctuationCam::Print(Option_t *) const
+{
+    const Int_t entries = fPixels->GetEntries();
+
+    *fLog << GetDescriptor() << dec << endl;
+    *fLog << " Number of Pixels: " << fNumPixels << "(" << entries << ")" << endl;
+
+    for (Int_t i=0; i<entries; i++ )
+        (*this)[i].Print();
+}
+
+Float_t MGainFluctuationCam::GetGain(int i) const
+{
+  const MGainFluctuationPix &pix = (*this)[i];
+  
+  return pix.GetGain();
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum number of photons  of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MGainFluctuationCam::GetGainMin(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return -5.;
+
+    const UInt_t n = geom->GetNumPixels();
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGainFluctuationPix &pix = (*this)[i];
+
+        const UInt_t id = pix.GetPixId();
+        if (id<0 || id>=n)
+            continue;
+
+        Float_t testval = pix.GetGain();
+
+        if (testval < minval)
+            minval = testval;
+    }
+
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum number of photons of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MGainFluctuationCam::GetGainMax(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return 50.;
+
+    const UInt_t n = geom->GetNumPixels();
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGainFluctuationPix &pix = (*this)[i];
+
+        const UInt_t id = pix.GetPixId();
+        if (id<0 || id>=n)
+            continue;
+
+        Float_t testval = pix.GetGain();
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the pixel with the requested idx. NULL if it doesn't
+// exist. The Look-up-table fLut is used. If its size is zero (according
+// to Rene this will happen if an old class object is loaded) we still
+// try to search in the array.
+//
+MGainFluctuationPix *MGainFluctuationCam::GetPixById(Int_t idx) const
+{
+    if (idx<0)
+        return 0;
+
+    if (fLut.GetSize()>0)
+    {
+        if (idx>=fLut.GetSize())
+            return 0;
+        return fLut[idx]<0 ? 0 : (MGainFluctuationPix*)(fPixels->UncheckedAt(fLut[idx]));
+    }
+
+    TIter Next(fPixels);
+    MGainFluctuationPix *pix = NULL;
+
+    while ((pix=(MGainFluctuationPix*)Next()))
+        if (pix->GetPixId()==idx)
+            return pix;
+
+    return NULL;
+}
+
+MGainFluctuationPix *MGainFluctuationCam::AddPixel(Int_t idx, Float_t gain)
+    {
+        //
+        // If this is too slow or takes to much space we might use
+        // MGeomApply and an InitSize member function instead.
+        //
+        if (idx>=fLut.GetSize())
+        {
+            const Int_t n = fLut.GetSize();
+            fLut.Set(idx*2+1); //idx+1 is slower than idx*2+1
+            for (int i=n; i<idx*2+1; i++)
+                fLut[i] = -1;
+        }
+
+        fLut[idx] = fNumPixels;
+        if (idx>fMaxIndex)
+            fMaxIndex=idx;
+
+        return new ((*fPixels)[fNumPixels++]) MGainFluctuationPix(idx, gain);
+    }
+
+// --------------------------------------------------------------------------
+//
+// Returns, depending on the type flag:
+//
+//  0: Number of Photons*PixRatio
+//  1: Error*sqrt(PixRatio)
+//  2: Cleaning level = Num Photons*sqrt(PixRatio)/Error
+//  3: Number of Photons
+//  4: Error
+//  5: Island index
+//
+Bool_t MGainFluctuationCam::GetPixelContent(Double_t &val, Int_t idx,const MGeomCam&, Int_t type) const
+{
+    MGainFluctuationPix *pix = GetPixById(idx);
+
+    switch (type)
+    {
+    case 1:
+        val = pix->GetGain();
+        return kTRUE;
+    }
+    return kTRUE;
+}
+
+void MGainFluctuationCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MGainFluctuationCam::DrawPixelContent - not available." << endl;
+}
+
+TObject *MGainFluctuationCamIter::Next()
+{
+    if (!fUsedOnly)
+        return TObjArrayIter::Next();
+
+    MGainFluctuationPix *pix;
+    while ((pix = (MGainFluctuationPix*)TObjArrayIter::Next()))
+            return pix;
+    return pix;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationCam.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationCam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationCam.h	(revision 17960)
@@ -0,0 +1,104 @@
+#ifndef MARS_MGainFluctuationCam
+#define MARS_MGainFluctuationCam
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MGainFluctuationPix
+#include "MGainFluctuationPix.h"
+#endif
+
+class MGeomCam;
+class MGainFluctuationPix;
+class MGainFluctuationCamIter;
+
+class MGainFluctuationCam : public MParContainer, public MCamEvent
+{
+    friend class MGainFluctuationCamIter;
+private:
+    UInt_t        fNumPixels;
+     Int_t        fMaxIndex;
+    TArrayI       fLut;        // Lookup tabel to lookup pixel by index
+    TClonesArray *fPixels;     //-> FIXME: Change TClonesArray away from a pointer?
+
+    void RebuildLut()
+    {
+        // Resize Lut
+        fLut.Set(fMaxIndex+1);
+
+        // Reset Lut
+        fLut.Reset(-1);
+
+        // Rebuild Lut
+        for (UInt_t i=0; i<GetNumPixels(); i++)
+        {
+            const MGainFluctuationPix &pix = (*this)[i];
+            fLut[pix.GetPixId()] = i;
+        }
+    }
+
+public:
+    MGainFluctuationCam(const char *name=NULL, const char *title=NULL);
+    ~MGainFluctuationCam() { delete fPixels; }
+
+    // Setter function to fill pixels
+    MGainFluctuationPix *AddPixel(Int_t idx, Float_t gain);
+    void FixSize();
+
+    // Getter functions
+    UInt_t  GetNumPixels() const { return fNumPixels; }
+    Float_t GetGain(int i) const;
+
+    Float_t GetGainMin(const MGeomCam *geom=NULL) const;
+    Float_t GetGainMax(const MGeomCam *geom=NULL) const;
+
+    // Getter functions to access single pixels
+    MGainFluctuationPix &operator[](int i)       { return *(MGainFluctuationPix*)(fPixels->UncheckedAt(i)); }
+    MGainFluctuationPix &operator[](int i) const { return *(MGainFluctuationPix*)(fPixels->UncheckedAt(i)); }
+
+    MGainFluctuationPix *GetPixById(Int_t idx) const;
+
+    void Sort(Int_t upto = kMaxInt)
+    {
+        // Sort pixels by index
+        fPixels->Sort(upto);
+        RebuildLut();
+    } // For convinience: Sort pixels by index
+
+    // class MParContainer
+    void Reset();
+
+    // class TObject
+    void Print(Option_t *opt=NULL) const;
+    void Clear(Option_t *opt=NULL) { Reset(); }
+
+    // class MCamEvent
+    Bool_t GetPixelContent(Double_t &val, Int_t idx,const MGeomCam&, Int_t type=1) const;
+    void DrawPixelContent(Int_t num) const;
+
+    // To build an iterator for this class
+    operator TIterator*() const;
+
+    ClassDef(MGainFluctuationCam, 1)    // class for an event containing cerenkov photons
+};
+
+class MGainFluctuationCamIter : public TObjArrayIter
+{
+private:
+    Bool_t fUsedOnly;
+public:
+    MGainFluctuationCamIter(const MGainFluctuationCam *evt, Bool_t usedonly=kTRUE, Bool_t dir=kIterForward) : TObjArrayIter(evt->fPixels, dir), fUsedOnly(usedonly) { }
+    TObject *Next();
+    TIterator &operator=(const TIterator &) { return *this; }
+    ClassDef(MGainFluctuationCamIter, 0)
+};
+
+inline MGainFluctuationCam::operator TIterator*() const { return new MGainFluctuationCamIter(this); }
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationPix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationPix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationPix.cc	(revision 17960)
@@ -0,0 +1,59 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 1/2005 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGainFluctuationPix
+//
+// Storage container for the gain fluctuation in a pixel in relative value.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGainFluctuationPix.h"
+
+#include "MLog.h"
+
+ClassImp(MGainFluctuationPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MGainFluctuationPix::MGainFluctuationPix(Int_t pix, Float_t gain):
+  fPixId(pix), fGain(gain)
+{
+} 
+
+
+// --------------------------------------------------------------------------
+//
+//  Print information to gLog.
+//
+void MGainFluctuationPix::Print(Option_t *) const
+{ 
+    gLog << GetDescriptor() <<" Pixel: "<< fPixId;
+    gLog << "Relative gain " << fGain << endl;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationPix.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationPix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MGainFluctuationPix.h	(revision 17960)
@@ -0,0 +1,28 @@
+#ifndef MARS_MGainFluctuationPix_H
+#define MARS_MGainFluctuationPix_H
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGainFluctuationPix : public MParContainer
+{
+private:
+
+    Int_t    fPixId;     // the pixel Id
+
+    Float_t  fGain;      // The relative gain repect to nominal one
+
+public:
+    MGainFluctuationPix(Int_t pix=-1, Float_t gain=0);
+
+    Int_t   GetPixId() const            { return fPixId;   }
+    Float_t GetGain() const             { return fGain;    }
+    void    SetGain(Float_t g)          { fGain    = g; }
+
+    void    Print(Option_t *opt = NULL) const;
+
+    ClassDef(MGainFluctuationPix, 1)  // class containing information about the Cerenkov Photons in a pixel
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MHPSFFromStars.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MHPSFFromStars.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MHPSFFromStars.cc	(revision 17960)
@@ -0,0 +1,476 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López 05/2004 <mailto:jlopezs@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHPSFFromStars                                               
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPSFFromStars.h"
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TText.h>
+#include <TPaveText.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+
+#include "MStarLocalCam.h"
+#include "MStarLocalPos.h"
+
+#include "MParList.h"
+
+ClassImp(MHPSFFromStars);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+MHPSFFromStars::MHPSFFromStars(Int_t starpos, const char *name, const char *title)
+    : fGeom(NULL), fCurr(NULL), fSelectedStarPos(starpos)
+{
+    fName  = name  ? name  : "MHPSFFromStars";
+    fTitle = title ? title : "Class to fill the Point Spread Function histograms";
+
+    fNumEvents=0;
+
+    fHistMeanX.SetName("MeanX");
+    fHistMeanX.SetTitle("Mean X of the Fit");
+    fHistMeanX.SetDirectory(NULL);
+    fHistMeanX.UseCurrentStyle();
+    fHistMeanX.SetXTitle("Mean X [\\circ]");
+    fHistMeanX.SetYTitle("Counts [#]");
+    fHistMeanX.SetBins(800,-2.0,2.0);
+
+    fHistMeanY.SetName("MeanY");
+    fHistMeanY.SetTitle("Mean Y of the Fit");
+    fHistMeanY.SetDirectory(NULL);
+    fHistMeanY.UseCurrentStyle();
+    fHistMeanY.SetXTitle("Mean Y [\\circ]");
+    fHistMeanY.SetYTitle("Counts [#]");
+    fHistMeanY.SetBins(800,-2.0,2.0);
+
+    fHistSigmaMinor.SetName("SigmaMinor");
+    fHistSigmaMinor.SetTitle("Sigma X of the Fit");
+    fHistSigmaMinor.SetDirectory(NULL);
+    fHistSigmaMinor.UseCurrentStyle();
+    fHistSigmaMinor.SetXTitle("Sigma X [\\circ]");
+    fHistSigmaMinor.SetYTitle("Counts [#]");
+    fHistSigmaMinor.SetBins(160,0,0.8);
+    
+    fHistSigmaMajor.SetName("SigmaMajor");
+    fHistSigmaMajor.SetTitle("Sigma Y of the Fit");
+    fHistSigmaMajor.SetDirectory(NULL);
+    fHistSigmaMajor.UseCurrentStyle();
+    fHistSigmaMajor.SetXTitle("Sigma Y [\\circ]");
+    fHistSigmaMajor.SetYTitle("Counts [#]");
+    fHistSigmaMajor.SetBins(160,0,0.8);
+
+    fProjectionX.SetName("ProjetionX");
+    fProjectionX.SetTitle("Star projection in X axis");
+    fProjectionX.SetDirectory(NULL);
+    fProjectionX.UseCurrentStyle();
+    fProjectionX.SetXTitle("X [\\circ]");
+    fProjectionX.SetYTitle("DC [uA]");
+    fProjectionX.SetBins(16,-0.8,0.8);
+
+    fProjectionY.SetName("ProjetionY");
+    fProjectionY.SetTitle("Star projection in Y axis");
+    fProjectionY.SetDirectory(NULL);
+    fProjectionY.UseCurrentStyle();
+    fProjectionY.SetXTitle("Y [\\circ]");
+    fProjectionY.SetYTitle("DC [uA]");
+    fProjectionY.SetBins(16,-0.8,0.8);
+
+    fProfile.SetName("Profile");
+    fProfile.SetTitle("Star profile");
+    fProfile.SetDirectory(NULL);
+    fProfile.UseCurrentStyle();
+    fProfile.SetXTitle("X [\\circ]");
+    fProfile.SetYTitle("X [\\circ]");
+    fProfile.SetZTitle("DC [uA]");
+    fProfile.SetBins(16,-0.8,0.8,16,-0.8,0.8);
+
+    fvsTimeMeanX.Set(0);
+    fvsTimeMeanY.Set(0);
+    fvsTimeSigmaMinor.Set(0);
+    fvsTimeSigmaMajor.Set(0);
+
+    //  fTime.Set(0);
+    fEvent.Set(0);
+
+}
+
+MHPSFFromStars::~MHPSFFromStars()
+{
+  delete fGraphMeanX;
+  delete fGraphMeanY;
+  delete fGraphSigmaMinor;
+  delete fGraphSigmaMajor;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// TObject *MHPSFFromStars::lone(const char *) const
+// {
+//   MHPSFFromStars *hpsf = new MHPSFFromStars();
+  
+//   return hpsf;
+// }
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+//
+Bool_t MHPSFFromStars::SetupFill(const MParList *pList)
+{
+  
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+  {
+      *fLog << err << GetDescriptor() 
+            << ": MGeomCam not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  TArrayC PixelsUsed;
+  PixelsUsed.Set(577);
+  PixelsUsed.Reset((Char_t)kTRUE);
+  fCamera.SetGeometry(*fGeom,"StarsDisplay","StarsDisplay");
+  fCamera.SetUsed(PixelsUsed);
+
+  fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+  
+  if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+//--------------------------------------------------------------------------------
+//
+//
+Bool_t MHPSFFromStars::Fill(const MParContainer *par, const Stat_t w)
+{
+  const UInt_t numPixels = fGeom->GetNumPixels();
+
+  MStarLocalCam* stars = (MStarLocalCam*)par;
+  if (!stars)
+    {
+      *fLog << err << "No argument in " << GetName() << "::Fill... abort." << endl;
+      return kFALSE;
+    }
+
+  //
+  MStarLocalPos* star = SelectStar(stars);
+  if (star == NULL)
+    return kCONTINUE;
+  
+
+  //Check good conditions of the fitting procedure
+  Float_t expectedStarXPos = star->GetMeanX();
+  Float_t expectedStarYPos = star->GetMeanY();
+
+  if ( star->GetChiSquareNdof() == 0 
+       || star->GetChiSquareNdof()>5.)
+//       || TMath::Sqrt(expectedStarXPos*expectedStarXPos+expectedStarYPos*expectedStarYPos)>150.)
+    {
+      *fLog << warn << "Star selected were bad reconstructed" << endl;
+      return kCONTINUE;
+    }
+  
+
+
+  //Fill Histograms
+  fHistMeanX.Fill(star->GetMeanX()*fGeom->GetConvMm2Deg());
+  fHistMeanY.Fill(star->GetMeanY()*fGeom->GetConvMm2Deg());
+  if (star->GetSigmaMinorAxis() < 0)
+    *fLog << err << GetName() << " Sigma of the fit " << star->GetSigmaMinorAxis() << " negative" << endl;
+  if (star->GetSigmaMajorAxis() < 0)
+    *fLog << err << GetName() << " Sigma of the fit " << star->GetSigmaMajorAxis() << " negative" << endl;
+  fHistSigmaMinor.Fill(star->GetSigmaMinorAxis()*fGeom->GetConvMm2Deg());
+  fHistSigmaMajor.Fill(star->GetSigmaMajorAxis()*fGeom->GetConvMm2Deg());
+  
+  fCamera.AddCamContent(*fCurr);
+  
+  //Selected star X(andY) projections
+  Float_t ringofinterest = 4*(star->GetSigmaMajorAxis()>star->GetSigmaMinorAxis()?star->GetSigmaMajorAxis():star->GetSigmaMinorAxis());
+
+  // First define a area of interest around the expected position of the star
+  for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+      Float_t pixelXCenter = (*fGeom)[pix].GetX();
+      Float_t pixelYCenter = (*fGeom)[pix].GetY();
+      Float_t dist = TMath::Sqrt((pixelXCenter-expectedStarXPos)*(pixelXCenter-expectedStarXPos)+
+                          (pixelYCenter-expectedStarYPos)*(pixelYCenter-expectedStarYPos));
+      
+      if ((dist < ringofinterest))
+        {
+          fProjectionX.Fill((pixelXCenter-expectedStarXPos)*fGeom->GetConvMm2Deg(), (*fCurr)[pix]);
+          fProjectionY.Fill((pixelYCenter-expectedStarYPos)*fGeom->GetConvMm2Deg(), (*fCurr)[pix]);
+          //FIXME          fProfile.Fill((pixelXCenter-expectedStarXPos)*fGeom->GetConvMm2Deg(),(pixelYCenter-expectedStarYPos)*fGeom->GetConvMm2Deg(), (*fCurr)[pix]);
+        }
+    }
+  
+  
+  //
+  fvsTimeMeanX.Set(fNumEvents+1);
+  fvsTimeMeanY.Set(fNumEvents+1);
+  fvsTimeSigmaMinor.Set(fNumEvents+1);
+  fvsTimeSigmaMajor.Set(fNumEvents+1);
+  
+  //  fTime.Set(fNumEvents+1);
+  fEvent.Set(fNumEvents+1);
+
+  fvsTimeMeanX[fNumEvents] = star->GetMeanX()*fGeom->GetConvMm2Deg();
+  fvsTimeMeanY[fNumEvents] = star->GetMeanY()*fGeom->GetConvMm2Deg();
+  fvsTimeSigmaMinor[fNumEvents] = star->GetSigmaMinorAxis()*fGeom->GetConvMm2Deg();
+  fvsTimeSigmaMajor[fNumEvents] = star->GetSigmaMajorAxis()*fGeom->GetConvMm2Deg();
+
+  //  fTime[fNumEvents] = ?;
+  fEvent[fNumEvents] = fNumEvents;
+
+  fNumEvents++;
+  
+//   fGraphMeanX.SetPoint(fNumEvents,fNumEvents,star->GetMeanX()*fGeom->GetConvMm2Deg());
+//   fGraphMeanY.SetPoint(fNumEvents,fNumEvents,star->GetMeanY()*fGeom->GetConvMm2Deg());
+//   fGraphSigmaMinor.SetPoint(fNumEvents,fNumEvents,star->GetSigmaMinorAxis()*fGeom->GetConvMm2Deg());
+//   fGraphSigmaMajor.SetPoint(fNumEvents,fNumEvents,star->GetSigmaMajorAxis()*fGeom->GetConvMm2Deg());
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MHPSFFromStars::Finalize()
+{
+  *fLog << inf << GetName() << " Statistics: " << fNumEvents << " events" << endl;
+  //Fit  the profile plot with a gaussian(+baseline)
+
+  return kTRUE;
+}
+
+MStarLocalPos* MHPSFFromStars::SelectStar(MStarLocalCam* stars)
+{
+  TIter Next(stars->GetList());
+  MStarLocalPos* star = NULL;
+  MStarLocalPos* selectedStar = NULL;
+  
+  Float_t dist;
+  
+  if (fSelectedStarPos >= 0)
+    for (Int_t i=0; i<=fSelectedStarPos; i++)
+        star = (MStarLocalPos*)Next();
+  else //Look for the closer star to the center
+    {
+      Float_t mindist = 600; //mm
+      while ((star=(MStarLocalPos*)Next())) 
+        {
+          dist = TMath::Sqrt(star->GetMeanX()*star->GetMeanX() +
+                             star->GetMeanY()*star->GetMeanY());
+          if (dist < mindist)
+            {
+              selectedStar = star;
+              mindist = dist;
+            }
+        }
+      
+      star = selectedStar;
+      if (star == NULL)
+          *fLog << warn << "Not found star closer to center" << endl;
+      
+    }
+      
+  return star;
+}
+
+static Double_t fitfunc(Double_t *x, Double_t *par)
+{
+   Double_t fitval = 
+     par[0] + par[1]*TMath::Exp(-0.5*(x[0]-par[2])*(x[0]-par[2])/(par[3]*par[3]));
+
+   return fitval;
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+//
+void MHPSFFromStars::Draw(const Option_t *opt)
+{
+
+  TString option(opt);
+  option.ToLower();
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  if (fNumEvents==0)
+    {
+      *fLog << err << GetName() << " no entries to be drawn" << endl;
+      return;
+    }
+  
+    
+
+  if (option.Contains("mean"))
+    {
+      fGraphMeanX = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeMeanX.GetArray());
+      fGraphMeanX->SetName("GraphMeanX");
+      fGraphMeanX->SetTitle("Star X position v.s. event ");
+      fGraphMeanX->UseCurrentStyle();
+      fGraphMeanX->GetXaxis()->SetTitle("Event [#]");
+      fGraphMeanX->GetYaxis()->SetTitle("X [\\circ]");
+
+      fGraphMeanY = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeMeanY.GetArray());
+      fGraphMeanY->SetName("GraphMeanY");
+      fGraphMeanY->SetTitle("Star Y position v.s. event ");
+      fGraphMeanY->UseCurrentStyle();
+      fGraphMeanY->GetXaxis()->SetTitle("Event [#]");
+      fGraphMeanY->GetYaxis()->SetTitle("Y [\\circ]");
+
+      pad->Divide(2,2);
+
+      pad->cd(1);
+      fHistMeanX.DrawClone();
+      pad->cd(2);
+      fHistMeanY.DrawClone();
+      pad->cd(3);
+      fGraphMeanX->SetMarkerStyle(20);
+      fGraphMeanX->SetMarkerSize(0.4);
+      fGraphMeanX->Draw("AP");
+      pad->cd(4);
+      fGraphMeanY->SetMarkerStyle(20);
+      fGraphMeanY->SetMarkerSize(0.4);
+      fGraphMeanY->Draw("AP");
+    }
+  else if (option.Contains("sig"))
+    {
+
+      fGraphSigmaMinor = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeSigmaMinor.GetArray());
+      fGraphSigmaMinor->SetName("GraphSigmaMinor");
+      fGraphSigmaMinor->SetTitle("Star X sigma v.s. event ");
+      fGraphSigmaMinor->UseCurrentStyle();
+      fGraphSigmaMinor->GetXaxis()->SetTitle("Event [#]");
+      fGraphSigmaMinor->GetYaxis()->SetTitle("Sigma X [\\circ]");
+
+      fGraphSigmaMajor = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeSigmaMajor.GetArray());
+      fGraphSigmaMajor->SetName("GraphSigmaMajor");
+      fGraphSigmaMajor->SetTitle("Star Y sigma v.s. event ");
+      fGraphSigmaMajor->UseCurrentStyle();
+      fGraphSigmaMajor->GetXaxis()->SetTitle("Event [#]");
+      fGraphSigmaMajor->GetYaxis()->SetTitle("Sigma Y [\\circ]");
+
+      pad->Divide(2,2);
+
+      pad->cd(1);
+      fHistSigmaMinor.DrawClone();
+      pad->cd(2);
+      fHistSigmaMajor.DrawClone();
+      pad->cd(3);
+      fGraphSigmaMinor->SetMarkerStyle(21);
+      fGraphSigmaMinor->SetMarkerSize(0.4);
+//       fGraphSigmaMinor->SetMarkerColor(kBlue);
+      fGraphSigmaMinor->Draw("AP");
+      fGraphSigmaMajor->SetMarkerStyle(21);
+      fGraphSigmaMajor->SetMarkerSize(0.4);
+      pad->cd(4);
+      fGraphSigmaMajor->Draw("AP");
+    }
+  else if (option.Contains("proj"))
+  {
+      pad->Divide(2,1);
+
+      pad->cd(1);
+// Creates a Root function based on function fitf above
+      TF1 *funcX = new TF1("fitfuncX",fitfunc,-0.4,0.4,4);
+
+      Float_t sigguess = fHistSigmaMinor.GetMean();
+      Float_t max = fProjectionX.GetMaximum();
+// Sets initial values and parameter names
+      funcX->SetParNames("base","Max","Mean","Sigma");
+      funcX->SetParameters(1.,max,0.,sigguess);
+
+// Fit histogram in range defined by function
+      fProjectionX.Fit("fitfuncX","QR");
+      //      fProjectionX.DrawClone();
+
+      pad->cd(2);
+      TF1 *funcY = new TF1("fitfuncY",fitfunc,-0.4,0.4,4);
+
+      sigguess = fHistSigmaMajor.GetMean();
+      max = fProjectionY.GetMaximum();
+// Sets initial values and parameter names
+      funcY->SetParNames("base","Max","Mean","Sigma");
+      funcY->SetParameters(1.,max,0.,sigguess);
+
+// Fit histogram in range defined by function
+      fProjectionY.Fit("fitfuncX","QR");
+      fProjectionY.DrawClone();
+  }
+//   else if (option.Contains("prof"))
+//   {
+//       fProfile.DrawClone();
+//   }
+  else if (option.Contains("cam"))
+    {
+      pad->cd(1);
+
+      TArrayF x(fNumEvents);
+      TArrayF y(fNumEvents);
+      for (UInt_t i=0; i<fNumEvents; i++)
+        {
+          x[i] = fvsTimeMeanX[i]/fGeom->GetConvMm2Deg();
+          y[i] = fvsTimeMeanY[i]/fGeom->GetConvMm2Deg();
+        }
+      
+      fGraphPath = new TGraph((Int_t)fNumEvents,x.GetArray(),y.GetArray());
+      fGraphPath->SetName("GraphPath");
+      fGraphPath->UseCurrentStyle();
+
+      fCamera.DrawClone();
+      fCamera.SetPrettyPalette();
+      fGraphPath->Draw("P");
+      fGraphPath->SetMarkerStyle(21);
+      fGraphPath->SetMarkerSize(0.4);
+    }
+  else
+    *fLog << err << GetName() << "::Draw Uknown option " << option << endl;
+  
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MHPSFFromStars.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MHPSFFromStars.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MHPSFFromStars.h	(revision 17960)
@@ -0,0 +1,101 @@
+#ifndef MARS_MHPSFFromStars
+#define MARS_MHPSFFromStars
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef ROOT_TH1F
+#include <TH1F.h>
+#endif
+
+#ifndef ROOT_TGraph
+#include <TGraph.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+
+#ifndef ROOT_TProfile2D
+#include <TProfile2D.h>
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TObject;
+class MCameraDC;
+class MStarLocalPos;
+class MStarLocalCam;
+
+class MHPSFFromStars : public MH
+{
+ private:
+
+  MGeomCam* fGeom;
+  MCameraDC* fCurr;
+  
+  TH1F fHistMeanX;
+  TH1F fHistMeanY;
+  TH1F fHistSigmaMinor;
+  TH1F fHistSigmaMajor;
+
+  TGraph *fGraphMeanX;
+  TGraph *fGraphMeanY;
+  TGraph *fGraphPath;
+  TGraph *fGraphSigmaMinor;
+  TGraph *fGraphSigmaMajor;
+
+  TArrayF fvsTimeMeanX;
+  TArrayF fvsTimeMeanY;
+  TArrayF fvsTimeSigmaMinor;
+  TArrayF fvsTimeSigmaMajor;
+
+  TArrayF fTime;
+  TArrayF fEvent;
+
+  ULong_t fNumEvents;
+
+  MHCamera fCamera;
+  TProfile fProjectionX;
+  TProfile fProjectionY;
+  TProfile2D fProfile;
+
+  Int_t fSelectedStarPos;
+  MStarLocalPos* SelectStar(MStarLocalCam* stars);
+
+  public:
+
+  MHPSFFromStars(Int_t starpos=-1, const char *name=NULL, const char *title=NULL);
+  ~MHPSFFromStars();
+
+  Bool_t SetupFill(const MParList *pList);
+  Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+  Bool_t Finalize();
+
+  void Draw(const Option_t*);
+/*   TObject* Clone(const char *) const; */
+
+  //Getter
+  TProfile& GetProjectionX() { return fProjectionX; }
+  TProfile& GetProjectionY() { return fProjectionY; }
+  
+  ClassDef(MHPSFFromStars, 1) // A list of histograms storing star information from PMT DCs
+};
+
+#endif
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MImgIsland.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MImgIsland.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MImgIsland.cc	(revision 17960)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Ester Aliu ,  9/2004 <mailto:aliu@ifae.es>
+!             
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MImgIsland.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MImgIsland);
+
+using namespace std;
+
+MImgIsland::MImgIsland(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MImgIsland";
+    fTitle = title ? title : "Storage container for one island information";
+    //    cout << "Creo 1 isla" << endl;      
+    Reset();
+}
+MImgIsland::~MImgIsland()
+{
+  //  cout << "Destruyo 1 isla" << endl;
+}
+
+void MImgIsland::Reset()
+{
+  fPixNum = 0;
+  fSigToNoise = -1;
+  fTimeSpread = -1;
+  fMeanX = -1000;
+  fMeanY = -1000;
+  fDist = -1;
+  fDistW = -1;
+  fDistL = -1;
+  fDistS = -1;
+ 
+  fWidth = -1;
+  fLength = -1;
+  fSizeIsl = -1;
+  fAlpha = -1000;
+  
+  fPixList.Reset(-1);
+  fPeakPulse.Reset(-1);
+   
+}
+
+// -------------------------------------------------------------------------
+// 
+// Initialize
+// 
+void MImgIsland::InitSize(Int_t i)
+{
+  fPixList.Set(i);
+  fPeakPulse.Set(i);
+}
+
+
+// -------------------------------------------------------------------------
+// 
+// Set the pixels id in the island
+//
+void MImgIsland::SetPixList(const Int_t i, const Int_t idx)
+{
+    fPixList[i] = idx;   
+}
+
+
+
+
+// -------------------------------------------------------------------------
+// 
+// Set the arrival time in one pixel of the island
+//
+void MImgIsland::SetPeakPulse(const Int_t i, const Float_t t)
+{
+    fPeakPulse[i] = t;
+}
+
+
+// -------------------------------------------------------------------------
+// 
+// Print the island information
+//
+void MImgIsland::Print(Option_t *opt) const
+{
+
+  // TString o = opt;
+
+  *fLog << inf << "  Number of pixels = " << fPixNum << endl;
+  *fLog << inf << "  Signal-To-Noise ="  << fSigToNoise << endl;
+  *fLog << inf << "  Time Spread (Core pixels) = " << fTimeSpread << endl;
+  *fLog << inf << "  DistL = " << fDistL << endl;
+  *fLog << inf << "  DistW = " << fDistW << endl;
+  *fLog << inf << "  DistS = " << fDistS << endl;
+  *fLog << inf << "  Alpha = " << fAlpha << endl;
+
+}
+      
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MImgIsland.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MImgIsland.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MImgIsland.h	(revision 17960)
@@ -0,0 +1,100 @@
+#ifndef MARS_MImgIsland
+#define MARS_MImgIsland
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+
+class MImgIsland : public MParContainer
+{
+ private:
+
+  Int_t   fPixNum;
+  Float_t fSigToNoise;
+  Float_t fTimeSpread;
+  Float_t fDist;
+  Float_t fDistL;
+  Float_t fDistW;
+  Float_t fDistS;
+  
+  Float_t fWidth;
+  Float_t fLength;
+  Float_t fSizeIsl;
+  Float_t fMeanX;
+  Float_t fMeanY;
+ 
+  Float_t fAlpha;
+
+
+  TArrayI fPixList;
+  TArrayF fPeakPulse;
+  
+public:
+
+  MImgIsland(const char *name=NULL, const char *title=NULL);
+  ~MImgIsland();
+
+  Int_t   GetPixNum()      { return fPixNum; }
+  Float_t GetSigToNoise()  { return fSigToNoise; }
+  Float_t GetTimeSpread()  { return fTimeSpread; }
+  Float_t GetDist()        { return fDist; }  
+  Float_t GetDistL()       { return fDistL; }
+  Float_t GetDistW()       { return fDistW; }
+  Float_t GetDistS()       { return fDistS; }
+
+  //hillas parameters
+  Float_t GetSizeIsl()     { return fSizeIsl; }
+  Float_t GetMeanX()       { return fMeanX; }
+  Float_t GetMeanY()       { return fMeanY; }
+  Float_t GetWidth()       { return fWidth; }
+  Float_t GetLength()      { return fLength; }
+
+  // hillas src parameters
+  Float_t GetAlpha()       { return fAlpha; }
+  
+  void    InitSize(Int_t i);
+  UInt_t  GetSize() const { return fPixList.GetSize(); }
+
+  Int_t    GetPixList(const Int_t i = 0)   const { return fPixList.At(i); };
+  Float_t   GetPeakPulse(const Int_t i = 0) const { return fPeakPulse.At(i); };
+ 
+  void Reset();
+
+  void SetPixNum    (Int_t   i)   { fPixNum = i; }
+  void SetSigToNoise(Float_t val) { fSigToNoise = val; }
+  void SetTimeSpread(Float_t val) { fTimeSpread = val; }
+  void SetDist      (Float_t val) { fDist = val; } 
+  void SetDistL     (Float_t val) { fDistL = val; }
+  void SetDistW     (Float_t val) { fDistW = val; }
+  void SetDistS     (Float_t val) { fDistS = val; } 
+
+  //hillas parameters
+  void SetSizeIsl   (Float_t val) { fSizeIsl = val; }
+  void SetMeanX     (Float_t val) { fMeanX = val; }
+  void SetMeanY     (Float_t val) { fMeanY = val; }
+  void SetWidth     (Float_t val) { fWidth = val; }
+  void SetLength    (Float_t val) { fLength = val; }
+  
+  // hillas src parameters
+  void SetAlpha     (Float_t val) { fAlpha = val; }
+ 
+  void SetPixList( const Int_t i, const Int_t id);
+  void SetPeakPulse( const Int_t i, const Float_t time);
+
+  //  void Paint(Option_t *opt=NULL);
+  void Print(Option_t *opt=NULL) const;  
+
+  ClassDef(MImgIsland, 2) // Container that holds the island information
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslands.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslands.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslands.cc	(revision 17960)
@@ -0,0 +1,83 @@
+#include "MIslands.h"
+
+#include <TList.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MImgIsland.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MIslands::MIslands(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MIslands";
+    fTitle = title ? title : "Storage container for the island information of one event";
+
+    fIslands = new TList;
+    fIslands->SetOwner();    
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor.
+//
+MIslands::~MIslands()
+{
+   fIslands->Delete();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+
+MImgIsland &MIslands::operator[] (Int_t i)
+{
+  MImgIsland& isl = *static_cast<MImgIsland*>(fIslands->At(i));
+  return isl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+
+const MImgIsland &MIslands::operator[] (Int_t i) const
+{
+    return *static_cast<MImgIsland*>(fIslands->At(i));
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Print the island parameters to *fLog
+//
+ 
+void MIslands::Print(Option_t *opt) const
+{
+  *fLog << all;
+  *fLog << "Island Parameters (" << GetName() << ")"  << endl;
+
+  TIter Next(fIslands);
+  MImgIsland* isl;
+  UInt_t islnum = 0;
+  while ((isl=(MImgIsland*)Next())) 
+    {
+      *fLog << inf << "*** Island #" << islnum << " parameters ***" << endl;
+      isl->Print();
+      islnum++;
+    }  
+  
+}
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslands.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslands.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslands.h	(revision 17960)
@@ -0,0 +1,49 @@
+#ifndef MARS_MIslands
+#define MARS_MIslands
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class TList;
+
+class MImgIsland;
+
+class MIslands : public MParContainer
+{
+ private:
+
+  TList*  fIslands;  //-> FIXME: Change TClonesArray away from a pointer?
+
+  //MHCamera fDisplay;
+  
+  Int_t fIslNum; 
+  Float_t fAlphaW;
+
+ public:
+
+  MIslands(const char *name=NULL, const char *title=NULL);
+  ~MIslands();
+
+  MImgIsland &operator[] (Int_t i);
+  const MImgIsland &operator[] (Int_t i) const;
+
+  TList* GetList() const { return fIslands; }
+  UInt_t GetIslNum() const { return fIslands->GetSize(); } //number of islands
+  Float_t GetAlphaW() const { return fAlphaW; }     //alpha weighted
+
+  void SetIslNum       (Int_t   i)   { fIslNum = i; }
+  void SetAlphaW(Float_t val) { fAlphaW = val; }
+  //  MHCamera& GetDisplay() { return fDisplay; }
+
+  //  void Paint(Option_t *o=NULL);
+  void Print(Option_t *o=NULL) const;
+
+  ClassDef(MIslands, 2)	// Storage Container for islands
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsCalc.cc	(revision 17960)
@@ -0,0 +1,826 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Ester Aliu, 2/2004 <aliu@ifae.es>
+|
+!   Last Update: 7/2004
+!
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MIslandsCalc
+//
+// The Island Calc task calculates some islands parameters for each 
+// of the events such as:
+// 
+//   - fPixNum                 //  number of pixels in the island
+//   - fSigToNoise             //  signal to noise of the island
+//   - fTimeSpread             //  "time" of the island
+//   - fMeanX                  //  mean X position of the island
+//   - fMeanY                  //  mean Y position of the island
+//   - fDist                   //  dist between an island and the continent
+//   - fLength                 //  major axis of the island ellipse
+//   - fWidth                  //  minor axis of the island ellipse
+//   - fDistL                  //  dist divided by lenght of the larger island
+//   - fDistW                  //  dist divided by width of the larger island
+//   - fDistS                  //  dist divided by size of the larger island
+//
+//   - fPixList                //  list of pixels in the island (TArrayI)
+//   - fPeakPulse              //  mean arrival time of the pixels in the island (TArrayF)
+//
+// Input Containers:
+//   MGeomCam
+//   MCerPhotEvt
+//   MPedestalCam
+//   MArrivalTimeCam
+//
+// Output Containers:
+//   MIslands
+//   MImgIsland
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MIslandsCalc.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIslands.h"
+#include "MImgIsland.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+ClassImp(MIslandsCalc);
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MIslandsCalc::MIslandsCalc(const char* name, const char* title)    
+  : fIsl(NULL)
+{
+    fName  = name  ? name  : "MIslandsCalc";
+    fTitle = title ? title : "Calculate island parameters";
+}
+
+
+// --------------------------------------------------------------------------
+Int_t MIslandsCalc::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPed)
+      {
+        *fLog << dbginf << "MPedestalCam not found... aborting." << endl;
+        return kFALSE;
+      }
+
+    fTime = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber("MArrivalTimeCam"));
+    if (!fTime)
+      {
+        *fLog << dbginf << "MArrivalTimeCam not found... aborting." << endl;
+        return kFALSE;
+      }
+   
+    if (strlen(fIslName) > 0)
+      {
+	fIsl = (MIslands*)pList->FindCreateObj("MIslands", AddSerialNumber(fIslName));
+      }
+    else
+      {
+      fIsl = (MIslands*)pList->FindCreateObj(AddSerialNumber("MIslands"));
+      }
+    if (!fIsl)
+      return kFALSE;
+    
+    return kTRUE;
+}
+
+
+Int_t MIslandsCalc::Process(){
+ 
+  fIsl->GetList()->Delete();
+  IslandPar();
+  
+  return kTRUE;     
+}
+
+
+Int_t MIslandsCalc::IslandPar(){
+
+  //calculates all the island parameters 
+
+  const Int_t nPix=fCam->GetNumPixels();
+  const Int_t nVect=50;
+  Int_t numisl;
+
+  Int_t** vect;
+  vect = new Int_t*[nVect];
+  for(Int_t i=0;i<nVect;i++)
+    vect[i]= new Int_t[nPix];
+  
+  Int_t* num;
+  num = new Int_t[nVect];
+  
+  if (fIslandAlgorithm == 1)
+    Calc1(numisl,nVect,nPix,vect,num);
+  if (fIslandAlgorithm == 2)
+    Calc2(numisl,nVect,nPix,vect,num);
+  
+  //set the number of islands in one event
+  fIsl->SetIslNum(numisl);
+
+  //cout << "code numisl " << numisl << endl;
+  //examine each island...
+
+  Float_t  noise;
+  Float_t  signal;
+ 
+  Int_t PixelNumIsl[numisl];
+  Float_t SigToNoise[numisl];
+  Float_t time[nPix];
+  Float_t timeVariance[numisl];
+  Float_t meanX[numisl];
+  Float_t meanY[numisl];
+  Float_t length[numisl];
+  Float_t width[numisl];
+  Float_t dist[numisl];
+  Float_t distL[numisl];
+  Float_t distW[numisl];
+  Float_t distS[numisl];
+
+
+  Float_t size[numisl], sizeLargeIsl, distance, alpha, alphaW, sizetot;
+
+  sizeLargeIsl = 0;
+  alphaW = 0;
+  sizetot = 0;
+
+  for(Int_t i = 1; i<=numisl ; i++)
+    {
+     
+      MImgIsland *imgIsl = new MImgIsland;
+      
+      imgIsl->InitSize(num[i]);
+      
+      Int_t n = 0;
+      
+      Float_t minTime = 10000.;
+      Float_t maxTime = 0.;
+
+      Float_t minX = 10000.;
+      Float_t maxX = 0.;
+
+      Float_t minY = 10000.;
+      Float_t maxY = 0.;
+
+      signal = 0;
+      noise = 0;
+      
+      size[i-1] = 0;
+      meanX[i-1] = 0;
+      meanY[i-1] = 0;
+      dist[i-1] = 0;
+      
+      PixelNumIsl[i-1] = 0;
+      timeVariance[i-1] = 0;
+           
+      for(Int_t idx=0 ; idx<nPix ; idx++)
+	{
+	  MCerPhotPix *pix = fEvt->GetPixById(idx);
+	  if(!pix) continue;
+	  const MGeomPix &gpix2 = (*fCam)[pix->GetPixId()];
+	  const MPedestalPix &ped  = (*fPed)[idx];
+	  const MArrivalTimePix &timepix = (*fTime)[idx];
+	  const Float_t nphot = pix->GetNumPhotons();
+
+	  if (vect[i][idx]==1){
+	    
+	    PixelNumIsl[i-1]++;
+	    signal += nphot * (fCam->GetPixRatio(idx));
+	    noise += pow(ped.GetPedestalRms(),2);
+	    
+	    size[i-1] += nphot;
+	    if (i == 1)
+	      sizeLargeIsl += nphot;
+	    
+	    meanX[i-1] += nphot * gpix2.GetX();
+	    meanY[i-1] += nphot * gpix2.GetY();
+	    
+	    time[i-1] = timepix.IsLoGainUsed() ? timepix.GetArrivalTimeLoGain() : timepix.GetArrivalTimeHiGain();
+	    
+	    imgIsl->SetPixList(PixelNumIsl[i-1]-1,pix->GetPixId());
+	    imgIsl->SetPeakPulse(PixelNumIsl[i-1]-1,time[i-1]);     	  	
+	    
+	    //calculates the time spread only for core pixels  
+	    if (fEvt->IsPixelCore(idx)){ 
+	      
+	      if (time[i-1] > maxTime){
+		maxTime = time[i-1];
+		maxX = gpix2.GetX();
+		maxY = gpix2.GetY();
+	      }
+	      if (time[i-1] < minTime){
+		minTime = time[i-1];
+		minX = gpix2.GetX();
+		minY = gpix2.GetY();
+	      }
+	      
+	    }
+	    n++;
+	  }	  
+	}  
+      
+      meanX[i-1] /= size[i-1];
+      meanY[i-1] /= size[i-1];
+
+      dist[i-1] = TMath::Power(meanX[i-1]-meanX[0],2) + TMath::Power(meanY[i-1]-meanY[i-1],2);
+      dist[i-1] = TMath::Sqrt(dist[i-1]);
+      
+      //timeVariance[i-1] = (maxTime-minTime);
+      
+      if (maxX!=minX && maxY!=minY)
+	timeVariance[i-1] = (maxTime-minTime)/sqrt(TMath::Power(maxX-minX,2) + TMath::Power(maxY-minY,2)); 
+      else
+	timeVariance[i-1] = -1;
+      
+      //noise = 0, in the case of MC w/o noise
+      if (noise == 0) noise = 1;
+      
+      SigToNoise[i-1]= (Float_t)signal/(Float_t)sqrt(noise);
+      
+      imgIsl->SetPixNum(PixelNumIsl[i-1]);
+      imgIsl->SetSigToNoise(SigToNoise[i-1]);
+      imgIsl->SetTimeSpread(timeVariance[i-1]);
+      imgIsl->SetMeanX(meanX[i-1]);
+      imgIsl->SetMeanY(meanY[i-1]);
+      imgIsl->SetDist(dist[i-1]);
+      imgIsl->SetSizeIsl(size[i-1]);
+      
+
+      // sanity check: if one island has 2 or less pixels
+      if (num[i]>2){
+      
+
+      // calculate width and lenght of each island
+
+      Double_t corrxx=0;              // [m^2]
+      Double_t corrxy=0;              // [m^2]
+      Double_t corryy=0;              // [m^2]
+      
+      for(Int_t idx=0 ; idx<nPix ; idx++){
+	
+	MCerPhotPix *pix = fEvt->GetPixById(idx);
+	if(!pix) continue;
+	const MGeomPix &gpix3 = (*fCam)[pix->GetPixId()];
+	const Float_t nphot = pix->GetNumPhotons();
+	
+	if (vect[i][idx]==1){
+	  
+	  const Float_t dx = gpix3.GetX() - meanX[i-1];     // [mm]
+	  const Float_t dy = gpix3.GetY() - meanY[i-1];     // [mm]
+	  
+	  corrxx += nphot * dx*dx;                     // [mm^2]
+	  corrxy += nphot * dx*dy;                     // [mm^2]
+	  corryy += nphot * dy*dy;                     // [mm^2]	       
+	  
+	}
+      }
+   
+      const Double_t d0    = corryy - corrxx;
+      const Double_t d1    = corrxy*2;
+      const Double_t d2    = d0 + TMath::Sqrt(d0*d0 + d1*d1);
+      const Double_t tand  = d2 / d1;
+      const Double_t tand2 = tand*tand;
+      
+      const Double_t s2 = tand2+1;
+      const Double_t s  = TMath::Sqrt(s2);
+      
+      const Double_t CosDelta =  1.0/s;   // need these in derived classes
+      const Double_t SinDelta = tand/s;   // like MHillasExt
+      
+      const Double_t axis1 = (tand2*corryy + d2 + corrxx)/s2/size[i-1];
+      const Double_t axis2 = (tand2*corrxx - d2 + corryy)/s2/size[i-1];
+      
+      //
+      // fLength^2 is the second moment along the major axis of the ellipse
+      // fWidth^2  is the second moment along the minor axis of the ellipse
+      //
+      // From the algorithm we get: fWidth <= fLength is always true
+      //
+      // very small numbers can get negative by rounding
+      //
+      length[i-1] = axis1<0 ? 0 : TMath::Sqrt(axis1);  // [mm]
+      width[i-1]  = axis2<0 ? 0 : TMath::Sqrt(axis2);  // [mm]
+      
+      
+      // alpha calculation
+      
+      const Double_t mx = meanX[i-1];     // [mm]
+      const Double_t my = meanY[i-1];     // [mm]
+      
+      //FIXME: xpos, ypos from MSrcPos
+      const Double_t xpos = 0.;
+      const Double_t ypos = 0.;
+      
+      const Double_t sx = mx - xpos;   // [mm]
+      const Double_t sy = my - ypos;   // [mm]
+      
+      const Double_t sd = SinDelta;  // [1]
+      const Double_t cd = CosDelta;  // [1]
+      
+      //
+      // Distance from source position to center of ellipse.
+      // If the distance is 0 distance, Alpha is not specified.
+      // The calculation has failed and returnes kFALSE.
+      //
+      distance = TMath::Sqrt(sx*sx + sy*sy);  // [mm]
+      if (distance==0){
+	
+	for (Int_t l = 0; l< nVect; l++)
+	  delete [] vect[l]; 
+	
+	delete [] vect;
+	delete [] num;
+	
+	return 1;
+      }
+      
+      //
+      // Calculate Alpha and Cosda = cos(d,a)
+      // The sign of Cosda will be used for quantities containing
+      // a head-tail information
+      //
+      // *OLD* const Double_t arg = (sy-tand*sx) / (dist*sqrt(tand*tand+1));
+      // *OLD* fAlpha = asin(arg)*kRad2Deg;
+      //
+      const Double_t arg2 = cd*sx + sd*sy;          // [mm]
+      if (arg2==0){
+	
+	for (Int_t l = 0; l< nVect; l++)
+	  delete [] vect[l]; 
+	
+	delete [] vect;
+	delete [] num;
+	
+	return 2;
+      }
+
+      const Double_t arg1 = cd*sy - sd*sx;          // [mm]
+      
+      //
+      // Due to numerical uncertanties in the calculation of the
+      // square root (dist) and arg1 it can happen (in less than 1e-5 cases)
+      // that the absolute value of arg exceeds 1. Because this uncertainty
+      // results in an Delta Alpha which is still less than 1e-3 we don't care
+      // about this uncertainty in general and simply set values which exceed
+      // to 1 saving its sign.
+      //
+      const Double_t arg = arg1/distance;
+      alpha = TMath::Abs(arg)>1 ? TMath::Sign(90., arg) : TMath::ASin(arg)*TMath::RadToDeg(); // [deg]
+      
+      alphaW += alpha*size[i-1];
+      sizetot += size[i-1];
+      
+      ////////////////////////////////////////
+      
+      distL[i-1]=dist[i-1]/length[0];
+      distW[i-1]=dist[i-1]/width[0];
+      distS[i-1]= dist[i-1]/size[0];
+      
+      imgIsl->SetLength(length[i-1]);
+      imgIsl->SetWidth(width[i-1]);
+      
+      imgIsl->SetDistL(distL[i-1]);
+      imgIsl->SetDistW(distW[i-1]);
+      imgIsl->SetDistS(distS[i-1]);
+      
+      imgIsl->SetAlpha(alpha);
+
+      }
+
+      fIsl->GetList()->Add(imgIsl);
+      
+    }
+  
+  fIsl->SetAlphaW(alphaW/sizetot);   
+  //fIsl->SetReadyToSave();
+  
+  for (Int_t l = 0; l< nVect; l++)
+    delete [] vect[l]; 
+
+ delete [] vect;
+ delete [] num;
+
+  return kTRUE;  
+}
+
+//------------------------------------------------------------------------------------------
+void MIslandsCalc::Calc1(Int_t& numisl, const Int_t nv, const Int_t npix, Int_t** vect, Int_t* num){
+  
+  
+  /////////////////////////////
+  //
+  //        ALGORITHM # 1
+  // counts the number of islands as you can see in 
+  // the event display after doing the std image cleaning
+  //
+  /////////////////////////////
+  
+  Int_t    sflag;
+  Int_t    control = 0;
+  
+  Int_t    nvect = 0;
+  
+  numisl = 0;
+
+  Int_t    zeros[nv];
+  
+  for(Int_t m = 0; m < nv ; m++)
+    for(Int_t n = 0; n < npix ; n++)
+	vect[m][n] = 0;
+    
+  for(Int_t n = 0; n < nv ; n++)
+    zeros[n] = 0;
+  
+  //cout << "new event" <<endl;
+  MCerPhotPix *pix;
+
+  // Loop over used pixels only
+  TIter Next(*fEvt);
+  
+  //after the interpolation of the pixels, these can be disordered by index. This is important for this algorithm of calculating islands
+  fEvt->Sort();
+
+  while ((pix=static_cast<MCerPhotPix*>(Next())))
+    {
+      const Int_t idx = pix->GetPixId();
+
+      const MGeomPix &gpix  = (*fCam)[idx];
+      const Int_t    nnmax  = gpix.GetNumNeighbors();
+
+      if( fEvt->IsPixelUsed(idx)) 
+     	{
+	  //cout <<idx <<endl;
+	  sflag = 0;
+	  
+	  for(Int_t j=0; j < nnmax ; j++)
+	    {
+	      const Int_t idx2 = gpix.GetNeighbor(j);
+	      
+	      if (idx2 < idx)
+		{
+		  for(Int_t k = 1; k <= nvect; k++)
+		    {
+		      if (vect[k][idx2] == 1)
+			{
+			  sflag = 1;
+			  vect[k][idx] = 1;
+			}
+		    }
+		}
+	    }
+	  
+	  if (sflag == 0)
+	    {
+	      nvect++;
+	      vect[nvect][idx] = 1;	     
+	    }
+	  
+	}
+    }
+  
+  numisl = nvect;
+  
+    
+  // Repeated Chain Corrections
+
+  Int_t jmin = 0;
+  
+  for(Int_t i = 1; i <= nvect; i++){
+    control=0;
+    for(Int_t j = i+1; j <= nvect; j++){
+      control = 0;
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 1;
+	  k=npix;
+	}
+      }
+      if (control == 1){
+	for(Int_t k = 0; k < npix; k++){
+	  if(vect[j][k] == 1) vect[i][k] = 1;
+	  vect[j][k] = 0;
+	  zeros[j] = 1;
+	}	
+	numisl = numisl-1;	    
+      }
+    }
+    
+    for(Int_t j = 1; j <= i-1; j++){
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 2; 
+	  jmin=j;
+	  k=npix;
+	  j=i;
+	}
+      }
+      
+      if (control == 2){
+	for (Int_t k = 0; k < npix; k++){
+	  if(vect[i][k]==1) vect[jmin][k]=1;
+	  vect[i][k] = 0;
+	  zeros[i] = 1;
+	}
+	numisl = numisl-1;	    
+      }	   
+    } 
+  }
+  
+  Int_t pixMAX = 0;
+  Int_t idMAX = 1;
+  Int_t l = 1;
+  Int_t numpixels;
+  
+  for(Int_t i = 1;  i<= nvect ; i++)
+    {
+      numpixels = 0;
+
+      if (zeros[i] == 0)
+	{
+	  for(Int_t k=0; k<npix; k++)
+	    {
+	      vect[l][k] = vect[i][k];
+	      if (vect[l][k] == 1)
+		numpixels++;      		
+	    }
+
+	  num[l] = numpixels;      	
+
+	  if (numpixels>pixMAX)
+	    {
+	      pixMAX = numpixels;
+	      idMAX = l;
+	    }
+	  l++;
+	}
+    }
+
+
+  //the larger island will correspond to the 1st component of the vector
+  
+  num[nvect+1] = num[1];
+  num[1] = num[idMAX];
+  num[idMAX] = num[nvect+1];
+
+  
+  for(Int_t k = 0; k<npix; k++) 
+    {
+      vect[nvect+1][k] = vect[1][k];
+      vect[1][k] = vect[idMAX][k];
+      vect[idMAX][k] = vect[nvect+1][k];
+    }
+}
+
+//------------------------------------------------------------------------------------------
+
+void MIslandsCalc::Calc2(Int_t& numisl, const Int_t nv, const Int_t npix, Int_t** vect, Int_t* num){  
+
+  
+  /////////////////////////////
+  //
+  //        ALGORITHM # 2
+  // counts the number of islands considering as the same 
+  // islands the ones separated for 2 or less pixels
+  //
+  /////////////////////////////
+  
+  Int_t    sflag;
+  Int_t    control;
+  
+  Int_t    nvect = 0;
+  numisl = 0;
+ 
+  Int_t    zeros[nv];
+  
+  Int_t kk[npix];
+
+  for(Int_t m = 0; m < nv ; m++)
+    for(Int_t n = 0; n < npix ; n++)
+	vect[m][n] = 0;
+    
+  for(Int_t n = 0; n < nv ; n++)
+    zeros[n] = 0;
+  
+  for(Int_t n = 0; n < npix ; n++)
+    kk[n] = 0;
+  
+  MCerPhotPix *pix;
+
+  //after the interpolation of the pixels, these can be disordered by index. This is important for this algorithm of calculating islands
+  fEvt->Sort();
+
+  // 1st loop over used pixels only
+  TIter Next0(*fEvt);
+ 
+  while ((pix=static_cast<MCerPhotPix*>(Next0())))
+    {
+      const Int_t idx = pix->GetPixId();
+      
+      const MGeomPix &gpix  = (*fCam)[idx]; 
+      const Int_t    nnmax  = gpix.GetNumNeighbors();
+
+      if( fEvt->IsPixelUsed(idx))
+	{
+	  kk[idx] = 1 ;
+	  for(Int_t j=0; j< nnmax; j++)
+	    {
+	      kk[gpix.GetNeighbor(j)] = 1;
+	    }
+	} 
+      
+    }
+      
+ 
+  //2nd loop over all pixels
+  TIter Next(*fEvt);
+   
+  while ((pix=static_cast<MCerPhotPix*>(Next())))
+    {
+      const Int_t idx = pix->GetPixId();
+      
+      const MGeomPix &gpix  = (*fCam)[idx];
+      const Int_t    nnmax  = gpix.GetNumNeighbors();
+      
+      if ( kk[idx] > 0)
+     	{
+	  sflag = 0;
+	  
+	  for(Int_t j=0; j < nnmax ; j++)
+	    {
+	      const Int_t idx2 = gpix.GetNeighbor(j);
+	      
+	      if (idx2 < idx)
+		{
+		  for(Int_t k = 1; k <= nvect; k++)
+		    {
+		      if (vect[k][idx2] == 1)
+			{
+			  sflag = 1;
+			  vect[k][idx] = 1;
+			}
+		    }
+		}
+	    }
+	  
+	  if (sflag == 0)
+	    {
+	      nvect++;
+	      vect[nvect][idx] = 1;	     
+	    }
+	  
+	}
+    }
+  
+  numisl = nvect;
+  
+ // Repeated Chain Corrections
+
+  Int_t jmin = 0;
+  
+  for(Int_t i = 1; i <= nvect; i++){
+    control=0;
+    for(Int_t j = i+1; j <= nvect; j++){
+      control = 0;
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 1;
+	  k=npix;
+	}
+      }
+      if (control == 1){
+	for(Int_t k = 0; k < npix; k++){
+	  if(vect[j][k] == 1) vect[i][k] = 1;
+	  vect[j][k] = 0;
+	  zeros[j] = 1;
+	}	
+	numisl = numisl-1;	    
+      }
+    }
+    
+    for(Int_t j = 1; j <= i-1; j++){
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 2; 
+	  jmin=j;
+	  k=npix;
+	  j=i;
+	}
+      }
+      
+      if (control == 2){
+	for (Int_t k = 0; k < npix; k++){
+	  if(vect[i][k]==1) vect[jmin][k]=1;
+	  vect[i][k] = 0;
+	  zeros[i] = 1;
+	}
+	numisl = numisl-1;	    
+      }	   
+    } 
+  } 
+  
+  Int_t l = 1;
+  Int_t numpixels;
+  Int_t pixMAX = 0;
+  Int_t idMAX = 1;
+
+  for(Int_t i = 1;  i<= nvect ; i++)
+    {
+      numpixels = 0;
+
+      if (zeros[i] == 0)
+	{
+	  for(Int_t k = 0; k<npix; k++)
+	    {
+	      vect[l][k] = vect[i][k];
+	      if (vect[l][k] == 1)
+		numpixels++;
+	    }
+
+	  num[l] = numpixels;
+	  
+	  if (numpixels>pixMAX)
+	    {
+	      pixMAX = numpixels;
+	      idMAX = l;
+	    }
+	  l++;
+	}
+    }
+  
+  
+  //the larger island will correspond to the 1st component of the vector
+
+  num[nvect +1] = num[1];
+  num[1] = num[idMAX];
+  num[idMAX]=num[nvect+1];
+
+  for(Int_t k = 0; k<npix; k++) 
+    {
+      vect[nvect+1][k] = vect[1][k];
+      vect[1][k] = vect[idMAX][k];
+      vect[idMAX][k] = vect[nvect+1][k];
+    }
+
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsCalc.h	(revision 17960)
@@ -0,0 +1,55 @@
+#ifndef MARS_MIslandsCalc
+#define MARS_MIslandsCalc
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MCerPhotPix;
+class MCerPhotEvt;
+class MPedestalCam;
+class MArrivalTimeCam;
+class MArrivalTimePix;
+class MGeomCam;
+class MIslands;
+class MImgIsland;
+
+class MIslandsCalc : public MGTask
+{
+ private:
+    const MGeomCam    *fCam;        //!
+    MCerPhotEvt       *fEvt;        //!
+    MSigmabar         *fSgb;        //!
+    MPedestalCam      *fPed;        //!
+    MArrivalTimeCam   *fTime;       //!
+    MGeomCam          *fGeomCam;
+
+    MIslands          *fIsl;        //!   output container to store result
+  
+    TString           fIslName;     //    name of the 'MIslands' container
+  
+    Int_t  fIslandAlgorithm;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t IslandPar();               //
+    void  Calc1(Int_t&,const Int_t,const Int_t,Int_t**,Int_t*);    // algorithm of counting islands #1
+    void  Calc2(Int_t&,const Int_t,const Int_t,Int_t**,Int_t*);    // algorithm of counting islands #2
+    
+           
+ public:
+    MIslandsCalc(const char* name=NULL, const char* title=NULL);
+    void SetOutputName(TString outname)   { fIslName = outname; }
+    
+    void SetAlgorithm(Int_t m)   {fIslandAlgorithm = m;}
+    
+    ClassDef(MIslandsCalc, 0)        // task doing the image cleaning
+}; 
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsClean.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsClean.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsClean.cc	(revision 17960)
@@ -0,0 +1,373 @@
+/* ======================================================================== *\
+!
+!
+!   Author(s): Ester Aliu, 3/2004
+!  
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MIslandClean
+//
+// The Island Cleaning task selects the islands you use for the Hillas
+// parameters calculation, after the normal image cleaning.
+//
+// There are two methods to make the selection: 
+//
+//    - No time method, as used is Whipple. It calculates an island parameter 
+//   called "signal to noise" and adds a new threshold that eliminates some   
+//   of the islands. The way the island is eliminated is seeting the pixels 
+//   of the islands as UNUSED 
+//
+//    - Time method, taking profit of the time information in MAGIC.
+//   Calculates the maximum time difference (in time slices) for each island 
+//   and corrects for the island size. With an other new threshold "noise" 
+//   islands are supposed to be eliminated.     
+//
+// Other cleanings that are allowed in this code are:
+// 
+//    - Resting only with the continent, i.e. the larger island
+//    
+//  Example:
+//
+//  MIslands   isl;
+//  isl.SetName("MIslands1");
+
+//  MImgCleanStd clean;
+//  MIslandClean islclean(0.2);
+//  islclean.SetInputName("MIslands1");  
+//  islclean.SetMethod(0); // for timing method 
+//
+//  tlist.AddToList(&clean);
+//  tlist.AddToList(&islclean);
+//
+//
+//  Input Containers:
+//    MGeomCam
+//    MCerPhotEvt
+//    MPedestalCam
+//    MArrivalTime
+//    MIslands
+//
+//  Output Containers:
+//    MCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MIslandsClean.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIslands.h"
+#include "MImgIsland.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+ClassImp(MIslandsClean);
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MIslandsClean::MIslandsClean(const Float_t newThres, const char *name, const char *title)    
+  : fIsl(NULL), fIslandCleaningMethod(kNoTiming), fIslCleanThres(newThres)
+{
+    fName  = name  ? name  : "MIslandsClean";
+    fTitle = title ? title : "Clean islands";
+}
+
+
+Int_t MIslandsClean::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPed)
+      {
+        *fLog << dbginf << "MPedestalCam not found... aborting." << endl;
+        return kFALSE;
+      }
+
+    fTime = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber("MArrivalTimeCam"));
+    if (!fTime)
+      {
+        *fLog << dbginf << "MArrivalTimeCam not found... aborting." << endl;
+        return kFALSE;
+      }
+
+    if (strlen(fIslName) > 0)
+      fIsl = (MIslands*)pList->FindObject(AddSerialNumber(fIslName));
+    else
+      fIsl = (MIslands*)pList->FindObject(AddSerialNumber("MIslands"));
+    if (!fIsl)
+      {
+        *fLog << dbginf << "MIslands not found... aborting." << endl;
+        return kFALSE;
+      }
+    
+    return kTRUE;
+}
+
+
+
+Int_t MIslandsClean::Process()
+{
+  
+  MImgIsland *imgIsl = new MImgIsland;
+  TIter Next(fIsl->GetList());
+
+  Int_t pixNum = 0;  
+  Int_t idPix = -1;
+
+  ////////////////////////////////////////////////////
+  //
+  //       TIME SPREAD ISLAND CLEANING
+  //  eliminates the island with a time spread 
+  //         higher than a given limit 
+  /////////////////////////////////////////////////// 
+  if( fIslandCleaningMethod == 0 ){
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      //fIslCleanThreshold has different values, FIXME, put two variables
+      if(imgIsl->GetTimeSpread() > fIslCleanThres)
+	{
+	  pixNum = imgIsl->GetPixNum();
+	  
+	  for(Int_t k = 0; k<pixNum; k++)
+	    {
+	      idPix = imgIsl->GetPixList(k);
+	      MCerPhotPix &pix  = (*fEvt)[idPix];
+	      pix.SetPixelUnused();
+	    }
+	}
+    }
+    
+  }
+  
+
+  ////////////////////////////////////////////////////
+  //
+  //      SIGNAL TO NOISE ISLAND CLEANING
+  //  eliminates the island with a signal-to-noise 
+  //         lower than a given limit 
+  /////////////////////////////////////////////////// 
+  else if ( fIslandCleaningMethod == 1 ) {
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      if(imgIsl->GetSigToNoise() < fIslCleanThres)
+	{
+	  pixNum = imgIsl->GetPixNum();
+	  
+	  for(Int_t k = 0; k<pixNum; k++)
+	    {
+	      idPix = imgIsl->GetPixList(k);
+	      MCerPhotPix &pix  = (*fEvt)[idPix];
+	      pix.SetPixelUnused();
+	    }
+	}
+    }	
+  }  
+  
+
+  ////////////////////////////////////////////////////
+  //
+  //      ISLAND SIZE OVER EVENT SIZE ISLAND CLEANING
+  //  eliminates the island with an island size over event size  
+  //         lower than a given limit 
+  /////////////////////////////////////////////////// 
+  else if ( fIslandCleaningMethod == 2 ) {
+    Float_t size = 0;
+    while ((imgIsl=(MImgIsland*)Next())) {
+      size += imgIsl->GetSizeIsl();
+    }
+    
+    Next.Reset();
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      if(imgIsl->GetSizeIsl()/size < fIslCleanThres)
+	{
+	  pixNum = imgIsl->GetPixNum();
+	  
+	  for(Int_t k = 0; k<pixNum; k++)
+	    {
+	      idPix = imgIsl->GetPixList(k);
+	      MCerPhotPix &pix  = (*fEvt)[idPix];
+	      pix.SetPixelUnused();
+	    }
+	}
+    }	
+  }  
+  
+  
+  ////////////////////////////////////////////////////
+  //
+  //       CONTINENT ISLAND CLEANING
+  //  eliminates all the islands except the continent 
+  //      i.e. the larger island in the event
+  //     according the number of pixels
+  /////////////////////////////////////////////////// 
+  else if( fIslandCleaningMethod == 3 ){
+    Int_t i = 0;
+    while ((imgIsl=(MImgIsland*)Next())) {
+      if (i != 0){
+	
+	pixNum = imgIsl->GetPixNum();
+	
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      i++;   
+    }
+  }
+  
+
+  ////////////////////////////////////////////////////
+  //
+  //       LARGER and SECOND LARGER ISLAND CLEANING
+  // eliminates all the islands except the two biggest 
+  //               ones according size
+  //                
+  /////////////////////////////////////////////////// 
+  else if( fIslandCleaningMethod == 4 ){
+
+    Int_t i = 0;
+    Int_t islnum = fIsl->GetIslNum();
+    Float_t islSize[islnum]; 
+    Int_t islIdx[islnum]; 
+
+    for (Int_t j = 0; j<islnum ; j++){
+      islSize[j] = -1;
+      islIdx[j] = -1;
+    }
+    
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      islSize[i] = imgIsl->GetSizeIsl();
+      i++;
+    }
+ 
+    
+    TMath::Sort(islnum, islSize, islIdx, kTRUE);
+    
+    i = 0;
+    Next.Reset();
+    while ((imgIsl=(MImgIsland*)Next())) {
+      if (islnum > 1 && islIdx[0]!=i && islIdx[1]!=i){
+	
+	//cout <<  "removed " << i << " isl 0" << islIdx[0] << " isl 1" << islIdx[1] << endl;
+	  
+	pixNum = imgIsl->GetPixNum();
+	
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      i++;   
+    }  
+  }
+
+
+
+  ///////////////////////////////////////////////////////
+  //
+  //       LARGER and SECOND LARGER ISLAND CLEANING II
+  // eliminates all the islands except the two biggest 
+  // ones according size, if the second one almost has 
+  // the 80% of the size of the biggest one
+  //
+  //                
+  ////////////////////////////////////////////////////// 
+  else if( fIslandCleaningMethod == 5 ){
+
+    Int_t i = 0;
+    Int_t islnum = fIsl->GetIslNum();
+    Float_t islSize[islnum]; 
+    Int_t islIdx[islnum]; 
+
+    for (Int_t j = 0; j<islnum ; j++){
+      islSize[j] = -1;
+      islIdx[j] = -1;
+    }
+    
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      islSize[i] = imgIsl->GetSizeIsl();
+      i++;
+    }
+    
+    TMath::Sort(islnum, islSize, islIdx, kTRUE);
+    
+    i = 0;
+    Next.Reset();
+
+    while ((imgIsl=(MImgIsland*)Next())) {
+
+      if (i!=0 && islIdx[0]!=i && islIdx[1]!=i){
+	  
+	pixNum = imgIsl->GetPixNum();
+	
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      else if(i!=0 && islSize[islIdx[i]]<0.6*islSize[islIdx[0]]){
+	
+	pixNum = imgIsl->GetPixNum();
+      
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      i++;   
+    }  
+  }
+  
+  fEvt->SetReadyToSave();
+  
+  return kTRUE;
+  
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsClean.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsClean.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MIslandsClean.h	(revision 17960)
@@ -0,0 +1,60 @@
+#ifndef MARS_MIslandsClean
+#define MARS_MIslandsClean
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MCerPhotPix;
+class MCerPhotEvt;
+class MPedestalCam;
+class MArrivalTimeCam;
+class MArrivalTimePix;
+class MIslands;
+class MImgIsland;
+
+class MIslandsClean : public MGTask
+{
+ public: 
+
+  typedef enum {
+    kTiming,
+    kNoTiming
+  } IslandCleaningMethod_t;
+  
+ private:
+    const MGeomCam    *fCam;        //!
+    MCerPhotEvt       *fEvt;        //!
+    MSigmabar         *fSgb;        //!
+    MPedestalCam      *fPed;        //!
+    MArrivalTimeCam   *fTime;       //!
+    MIslands          *fIsl;        //!   
+   
+    TString           fIslName;
+
+    // IslandCleaningMethod_t fIslandCleaningMethod;
+    Int_t fIslandCleaningMethod;
+   
+    Float_t fIslCleanThres;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+           
+ public:
+    MIslandsClean(const Float_t newThres=50, const char *name=NULL, const char *title=NULL);
+    
+    void SetInputName(TString inname)    {fIslName = inname;}
+    
+    //void SetMethod(IslandCleaningMethod_t m)   {fIslandCleaningMethod = m;}
+    void SetMethod(Int_t m)   {fIslandCleaningMethod = m;}
+    
+    ClassDef(MIslandsClean, 0)        // task doing the island cleaning
+}; 
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFit.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFit.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFit.cc	(revision 17960)
@@ -0,0 +1,86 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López , 4/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MPSFFit.h"
+
+#include <TEllipse.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MPSFFit);
+
+using namespace std;
+
+MPSFFit::MPSFFit(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MPSFFit";
+    fTitle = title ? title : "Container that holds the values of the PSF fit.";
+
+    fMaximun = -666.; 
+    fMeanMinorAxis = -666.; 
+    fMeanMajorAxis = -666.; 
+    fSigmaMinorAxis = -666.; 
+    fSigmaMajorAxis = -666.; 
+    fChisquare = -666.; 
+}
+
+void MPSFFit::Print(Option_t *opt) const
+{
+
+    *fLog << all << GetDescriptor() << " " << GetTitle() << endl;
+
+    *fLog << all << " Maximun \t " << fMaximun << " uA" << endl;
+    *fLog << all << " Mean Minor Axis \t " << fMeanMinorAxis << " mm \t";
+    *fLog << all << " Sigma Minor Axis \t " << fSigmaMinorAxis << " mm" << endl;
+    *fLog << all << " Mean Major Axis \t " << fMeanMajorAxis << " mm \t";
+    *fLog << all << " Sigma Major Axis \t " << fSigmaMajorAxis << " mm" << endl;
+    *fLog << all << " Chi Square \t " << fChisquare;
+    *fLog << all << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MPSFFit::Paint(Option_t *opt)
+{
+    if (fSigmaMinorAxis<0 || fSigmaMajorAxis<0)
+        return;
+
+    TEllipse e(fMeanMinorAxis, fMeanMajorAxis, fSigmaMinorAxis, fSigmaMajorAxis, 0, 360, 0);
+    e.SetLineWidth(2);
+    e.Paint();
+}
+
+void MPSFFit::Reset()
+{
+     SetMaximun(0.0);
+     SetMeanMinorAxis(0.0);
+     SetMeanMajorAxis(0.0);
+     SetSigmaMinorAxis(0.0);
+     SetSigmaMajorAxis(0.0);
+     SetChisquare(0.0);
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFit.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFit.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFit.h	(revision 17960)
@@ -0,0 +1,45 @@
+#ifndef MARS_MPSFFit
+#define MARS_MPSFFit
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MPSFFit : public MParContainer
+{
+private:
+
+    Float_t fMaximun;
+    Float_t fMeanMinorAxis;
+    Float_t fMeanMajorAxis;
+    Float_t fSigmaMinorAxis;
+    Float_t fSigmaMajorAxis;
+    Float_t fChisquare;
+
+public:
+    MPSFFit(const char *name=NULL, const char *title=NULL);
+    //~MPSFFit();
+
+    void SetMaximun(Float_t Maximun_) {fMaximun=Maximun_;}
+    void SetMeanMinorAxis(Float_t MeanMinorAxis_) {fMeanMinorAxis=MeanMinorAxis_;}
+    void SetMeanMajorAxis(Float_t MeanMajorAxis_) {fMeanMajorAxis=MeanMajorAxis_;}
+    void SetSigmaMinorAxis(Float_t SigmaMinorAxis_) {fSigmaMinorAxis=SigmaMinorAxis_;}
+    void SetSigmaMajorAxis(Float_t SigmaMajorAxis_) {fSigmaMajorAxis=SigmaMajorAxis_;}
+    void SetChisquare(Float_t Chisquare_) {fChisquare=Chisquare_;}
+
+    Float_t GetMaximun() {return fMaximun;}
+    Float_t GetMeanMinorAxis() {return fMeanMinorAxis;}
+    Float_t GetMeanMajorAxis() {return fMeanMajorAxis;}
+    Float_t GetSigmaMinorAxis() {return fSigmaMinorAxis;}
+    Float_t GetSigmaMajorAxis() {return fSigmaMajorAxis;}
+    Float_t GetChisquare() {return fChisquare;}
+
+    void Reset();
+
+    void Paint(Option_t *opt=NULL);
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MPSFFit, 1) // Container that holds the values of the PSF fit.
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFitCalc.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFitCalc.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFitCalc.cc	(revision 17960)
@@ -0,0 +1,569 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López , 4/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MPSFFitCalc.h"
+
+#include <iostream>
+
+
+#include <TH1D.h>
+#include <TString.h>
+#include <TArrayS.h>
+#include <TArrayI.h>
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TStopwatch.h>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MMinuitInterface.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MPSFFitCalc);
+
+using namespace std;
+
+
+const Int_t numVar = 5;
+const Float_t pixelSize = 31.5; //[mm]
+const Float_t sqrt2 = sqrt(2.);
+const Float_t sqrt3 = sqrt(3.);
+const Bool_t usePrintOut = kTRUE;
+const Int_t minuitPrintOut = 0;
+
+UInt_t  numPixels;
+Bool_t  isPixelUsed[577];
+UInt_t  numPixelsUsed;
+Float_t pixelPosX[577];
+Float_t pixelPosY[577];
+Float_t pixelValue[577];
+Float_t ChiSquare;
+
+MPSFFitCalc::MPSFFitCalc(ImgCleanMode_t imgmode, const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPSFFitCalc";
+    fTitle = title ? title : "Task that fits the PSF using the dc readout of the camera.";
+
+    fImgCleanMode = imgmode;
+    fNumRings     = 6;
+    fPedLevel     = 3.0; 
+
+
+// Initialization of the camera dc mask 'fIsPixelused[]'
+    numPixels = 577;
+    for (UInt_t pixid=0; pixid<numPixels; pixid++)
+	isPixelUsed[pixid] = kTRUE;
+
+    fTotalMeanFit.Reset();
+    fNumTotalMeanFits = 0;
+
+    fMaxDC = 30.;
+
+    fPedestalDCHist = new TH1D("ped","",(Int_t)fMaxDC*10,0.,fMaxDC);
+
+    fVname = new TString[numVar];
+    fVinit.Set(numVar); 
+    fStep.Set(numVar); 
+    fLimlo.Set(numVar); 
+    fLimup.Set(numVar); 
+    fFix.Set(numVar);
+
+
+    fVname[0] = "max";
+    fVinit[0] = fMaxDC;
+    fStep[0]  = fVinit[0]/sqrt2;
+    fLimlo[0] = 1.;
+    fLimup[0] = 40.;
+    fFix[0]   = 0;
+
+    fVname[1] = "meanminor";
+    fVinit[1] = 0.;
+    fStep[1]  = fVinit[0]/sqrt2;
+    fLimlo[1] = -600.;
+    fLimup[1] = 600.;
+    fFix[1]   = 0;
+
+    fVname[2] = "sigmaminor";
+    fVinit[2] = pixelSize;
+    fStep[2]  = fVinit[0]/sqrt2;
+    fLimlo[2] = pixelSize/(2*sqrt3);
+    fLimup[2] = 500.;
+    fFix[2]   = 0;
+
+    fVname[3] = "meanmajor";
+    fVinit[3] = 0.;
+    fStep[3]  = fVinit[0]/sqrt2;
+    fLimlo[3] = -600.;
+    fLimup[3] = 600.;
+    fFix[3]   = 0;
+
+    fVname[4] = "sigmamajor";
+    fVinit[4] = pixelSize;
+    fStep[4]  = fVinit[0]/sqrt2;
+    fLimlo[4] = pixelSize/(2*sqrt3);
+    fLimup[4] = 500.;
+    fFix[4]   = 0;
+
+    fObjectFit  = NULL;
+    //    fMethod     = "SIMPLEX";
+    fMethod     = "MIGRAD";
+    fNulloutput = kFALSE;
+}
+
+MPSFFitCalc::~MPSFFitCalc()
+{
+  delete fPedestalDCHist;
+}
+
+//______________________________________________________________________________
+//
+// The 2D gaussian fucntion used to fit the spot of the star
+//
+static Double_t func(float x,float y,Double_t *par)
+{
+    Double_t value=par[0]*exp(-(x-par[1])*(x-par[1])/(2*par[2]*par[2]))*exp(-(y-par[3])*(y-par[3])/(2*par[4]*par[4]));
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// Function used by Minuit to do the fit
+//
+static void fcnPSF(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+
+//calculate chisquare
+    Double_t chisq = 0;
+    Double_t delta;
+    Double_t x,y,z;
+    Double_t errorz = 0.2; //[uA]
+
+
+    for (UInt_t pixid=1; pixid<numPixels; pixid++) 
+    {
+
+	if (isPixelUsed[pixid] && pixelValue[pixid]>0.)
+	{
+	    x = pixelPosX[pixid];
+	    y = pixelPosY[pixid];
+	    z = pixelValue[pixid];
+
+	    if (errorz > 0.0)
+	    {
+		delta  = (z-func(x,y,par))/errorz;
+		chisq += delta*delta;
+	    }
+	    else
+		cerr << "ERROR fcnPSF: This should never happen errorz[" << pixid << "] " << errorz << endl;
+	}
+    }
+    f = chisq;
+    ChiSquare = chisq;
+
+}
+
+
+void MPSFFitCalc::InitFitVariables()
+{
+
+  for (UInt_t pixid=1; pixid<577; pixid++) 
+    pixelValue[pixid]=(Float_t)((*fCamera)[pixid]);
+
+  numPixelsUsed = 0;
+  Float_t totalDC = 0.0;
+  
+    fVinit[0] = fMaxDC;
+
+    if(usePrintOut)
+      *fLog << dbg << "Pixels used in the fit \t";
+
+    for (UInt_t idx=0; idx<numPixels; idx++)
+    {
+	if (isPixelUsed[idx])
+	{
+	    fVinit[1] += pixelPosX[idx]*pixelValue[idx];
+	    fVinit[3] += pixelPosY[idx]*pixelValue[idx];
+	    totalDC += pixelValue[idx];
+	    numPixelsUsed++;
+
+	    if(usePrintOut)
+	      *fLog << dbg << ' ' << idx; 
+	}
+    }
+    if(usePrintOut)
+      *fLog << dbg << endl;
+
+     
+    fVinit[1] /= totalDC;
+    fVinit[3] /= totalDC;
+    
+
+    fVinit[2] = pixelSize*sqrt((Float_t)numPixelsUsed)/2;
+    fVinit[4] = pixelSize*sqrt((Float_t)numPixelsUsed)/3;
+
+    //Init steps
+
+    for(Int_t i=0; i<numVar; i++)
+	if (fVinit[i] != 0)
+	  fStep[i] = TMath::Abs(fVinit[i]/sqrt2);
+
+    
+    for (UInt_t pixidx=0; pixidx<numPixels; pixidx++)
+      if ( (*fGeomCam)[pixidx].GetSector() == 6)
+	fPedestalDCHist->Fill(pixelValue[pixidx]);
+    
+    fPedestalDC = fPedestalDCHist->GetBinCenter(fPedestalDCHist->GetMaximumBin());
+
+    for (UInt_t pixid=1; pixid<577; pixid++) 
+      pixelValue[pixid]-=fPedestalDC;
+
+    if(usePrintOut)
+      {
+	*fLog << dbg << "numPixelsUsed \t" << numPixelsUsed << endl;
+	*fLog << dbg << "fPedestalDC \t" << fPedestalDC << endl;
+	*fLog << dbg << "Maximun DC Init. value \t" << fVinit[0] << endl;
+	*fLog << dbg << "Mean Minor Axis Init. value \t" << fVinit[1] << " mm\t";
+	*fLog << dbg << "Sigma Minor Axis Init. value \t" << fVinit[2] << endl;
+	*fLog << dbg << "Mean Major Axis Init. value \t" << fVinit[3] << " mm\t";
+	*fLog << dbg << "Sigma Major Axis Init. value \t" << fVinit[4] << endl;
+      }
+}
+
+void MPSFFitCalc::RingImgClean()
+{
+
+  Bool_t  isPixelUsedTmp[577];
+
+  fMaxDC=0;
+  UInt_t maxDCpix[2];
+
+
+// Look for the two neighbor pixels with the maximun signal and set all pixels as unused
+    Float_t dc[2];
+    Float_t dcsum;
+
+// Find the two close pixels with the maximun dc
+    for(UInt_t pixidx=0; pixidx<numPixels; pixidx++)
+    {
+
+      if(isPixelUsed[pixidx])
+	{
+	  dc[0] = (Float_t)(*fCamera)[pixidx];
+	  isPixelUsedTmp[pixidx] = kFALSE;
+	  
+	  MGeomPix g = (*fGeomCam)[pixidx];
+	  Int_t numNextNeighbors = g.GetNumNeighbors();
+	  
+	  for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+	    {
+	      if(isPixelUsed[pixidx])
+		{
+		  UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+		  dc[1] = (Float_t)(*fCamera)[swneighbor];
+		  
+		  dcsum = dc[0] + dc[1];
+		  
+		  if(dcsum > fMaxDC*2)
+		    {
+		      maxDCpix[0] = pixidx;
+		      maxDCpix[1] = swneighbor;
+		      fMaxDC = dcsum/2;
+		    }	
+		}
+	    }
+	}
+    }
+
+// Those variables are:
+// 1. an array of 2 dimensions
+//    1.1 the first dimension store the ring around the 'maxiun signal pixel'
+//    1.2 the sw numbers of the pixels in this ring
+// 2. an array with the number of pixels in each ring
+    UInt_t isPixelUesdInRing[fNumRings][577];
+    UInt_t numPixelsUsedInRing[fNumRings];
+
+// Store the 'maximun signal pixel in the [0] ring and set it as used 
+
+    for (Int_t core=0; core<2; core++)
+    {
+	isPixelUesdInRing[0][0] = maxDCpix[core];
+	numPixelsUsedInRing[0] = 1;
+	isPixelUsedTmp[isPixelUesdInRing[0][0]] = kTRUE;
+	
+	UInt_t count;
+	
+// Loop over the neighbors of the previus ring and store the sw numbers in the 2D array to be 
+// use in the next loop/ring 
+	for (UShort_t ring=0; ring<fNumRings-1; ring++)
+	{
+	    count = 0;  // In this variable we count the pixels we are in each ring
+	    for(UInt_t nextPixelUsed=0; nextPixelUsed<numPixelsUsedInRing[ring]; nextPixelUsed++)
+	    {
+		MGeomPix g = (*fGeomCam)[isPixelUesdInRing[ring][nextPixelUsed]];
+		Int_t numNextNeighbors = g.GetNumNeighbors();
+		for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+		{
+		    UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+		    if (!isPixelUsedTmp[swneighbor])
+		    {
+			isPixelUsedTmp[swneighbor] = kTRUE;
+			isPixelUesdInRing[ring+1][count] = swneighbor;
+			count++;
+		    }
+		}
+		numPixelsUsedInRing[ring+1] = count;
+	    }
+	}
+
+
+    if(usePrintOut)
+      {
+	for (UInt_t row=0; row<fNumRings; row++)
+	  {
+	    
+	    *fLog << dbg  << "fIsPixeUsed[" << row << "][" << numPixelsUsedInRing[row] << "] ";
+	    for (UInt_t column=0; column<numPixelsUsedInRing[row]; column++)
+	      *fLog << dbg << isPixelUesdInRing[row][column] << ' ';
+	    *fLog << dbg << endl;
+	  }	
+      }
+    }
+
+
+    for(UInt_t pixidx=0; pixidx<numPixels; pixidx++)
+      {
+      if(isPixelUsed[pixidx] && isPixelUsedTmp[pixidx])
+	  isPixelUsed[pixidx] = kTRUE;
+      else
+	  isPixelUsed[pixidx] = kFALSE;
+      }
+
+}
+
+void MPSFFitCalc::RmsImgClean(Float_t pedestal)
+{}
+
+void MPSFFitCalc::MaskImgClean(TArrayS blindpixels)
+{
+    
+    Int_t npix = blindpixels.GetSize();
+
+    for (Int_t idx=0; idx<npix; idx++)
+	isPixelUsed[blindpixels[idx]] = kFALSE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MCameraDC
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPSFFit
+//
+Int_t MPSFFitCalc::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+// Initialize positions of the pixels to be used in the minuit minimizations
+
+    for (UInt_t pixid=1; pixid<577; pixid++) 
+    {
+	MGeomPix &pix=(*fGeomCam)[pixid];
+	pixelPosX[pixid] = pix.GetX();
+	pixelPosY[pixid] = pix.GetY();
+    }
+   
+    fCamera = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCamera)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fFit = (MPSFFit*)pList->FindCreateObj(AddSerialNumber("MPSFFit"));
+    if (!fFit)
+    {
+      *fLog << err << AddSerialNumber("MPSFFit") << " cannot be created ... aborting" << endl;
+      return kFALSE;
+    }
+    
+    // Minuit initialization
+
+    TMinuit *gMinuit = new TMinuit(6);  //initialize TMinuit with a maximum of 5 params
+    gMinuit->SetFCN(fcnPSF);
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+    arglist[0] = minuitPrintOut;
+    gMinuit->mnexcm("SET PRI", arglist ,1,ierflg);
+
+    return kTRUE;
+
+}
+
+Int_t MPSFFitCalc::Process()
+{
+
+    // ------------------------------------------
+    // image cleaning
+
+    switch(fImgCleanMode)
+    {
+	case kRing:
+	{
+	    RingImgClean();
+	    break;
+	}
+	case kRms:
+	{
+	    RmsImgClean(fPedLevel);
+	    break;
+	}
+	case kMask:
+	{
+	    MaskImgClean(fBlindPixels);
+	    break;
+	}
+	case kCombined:
+	{
+	    MaskImgClean(fBlindPixels);
+	    RingImgClean();
+	    MaskImgClean(fBlindPixels);
+	    break;
+	}
+	default:
+	{
+	    *fLog << err << "Image Cleaning mode " << fImgCleanMode << " not defined" << endl;
+	    return kFALSE;
+	}
+    }
+
+    InitFitVariables();
+
+    // -------------------------------------------
+    // call MINUIT
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    for (Int_t i=0; i<numVar; i++)
+      gMinuit->mnparm(i, fVname[i], fVinit[i], fStep[i], fLimlo[i], fLimup[i], ierflg);
+
+    TStopwatch clock;
+    clock.Start();
+
+// Now ready for minimization step
+    arglist[0] = 500;
+    arglist[1] = 1.;
+    gMinuit->mnexcm(fMethod, arglist ,2,ierflg);
+
+    clock.Stop();
+
+    if(usePrintOut)
+      {
+	*fLog << dbg << "Time spent for the minimization in MINUIT :   " << endl;;
+	clock.Print();
+      }
+
+    if (ierflg)
+    {
+	*fLog << err << "MMinuitInterface::CallMinuit error " << ierflg << endl;
+	return kCONTINUE;
+    }
+    
+    fNumTotalMeanFits++;
+
+    Double_t parm,parmerr;
+    
+    gMinuit->GetParameter(0,parm,parmerr);
+    fFit->SetMaximun(parm);
+    fTotalMeanFit.SetMaximun(fTotalMeanFit.GetMaximun()+parm);
+
+    gMinuit->GetParameter(1,parm,parmerr);
+    fFit->SetMeanMinorAxis(parm);
+    fTotalMeanFit.SetMeanMinorAxis(fTotalMeanFit.GetMeanMinorAxis()+parm);
+
+    gMinuit->GetParameter(2,parm,parmerr);
+    fFit->SetSigmaMinorAxis(parm);
+    fTotalMeanFit.SetSigmaMinorAxis(fTotalMeanFit.GetSigmaMinorAxis()+parm);
+
+    gMinuit->GetParameter(3,parm,parmerr);
+    fFit->SetMeanMajorAxis(parm);
+    fTotalMeanFit.SetMeanMajorAxis(fTotalMeanFit.GetMeanMajorAxis()+parm);
+
+    gMinuit->GetParameter(4,parm,parmerr);
+    fFit->SetSigmaMajorAxis(parm);
+    fTotalMeanFit.SetSigmaMajorAxis(fTotalMeanFit.GetSigmaMajorAxis()+parm);
+
+    fFit->SetChisquare(ChiSquare/(numPixelsUsed-numVar));
+    fTotalMeanFit.SetChisquare(fTotalMeanFit.GetChisquare()+ChiSquare/(numPixelsUsed-numVar));
+
+    if(usePrintOut)
+      {
+	fFit->Print();
+	fTotalMeanFit.Print();
+      }
+
+    return kTRUE;
+}
+
+Int_t MPSFFitCalc::PostProcess()
+{
+  
+  fTotalMeanFit.SetMaximun(fTotalMeanFit.GetMaximun()/fNumTotalMeanFits);
+  fTotalMeanFit.SetMeanMinorAxis(fTotalMeanFit.GetMeanMinorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetSigmaMinorAxis(fTotalMeanFit.GetSigmaMinorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetMeanMajorAxis(fTotalMeanFit.GetMeanMajorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetSigmaMajorAxis(fTotalMeanFit.GetSigmaMajorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetChisquare(fTotalMeanFit.GetChisquare()/fNumTotalMeanFits);
+
+  fFit->SetMaximun(fTotalMeanFit.GetMaximun());
+  fFit->SetMeanMinorAxis(fTotalMeanFit.GetMeanMinorAxis());
+  fFit->SetSigmaMinorAxis(fTotalMeanFit.GetSigmaMinorAxis());
+  fFit->SetMeanMajorAxis(fTotalMeanFit.GetMeanMajorAxis());
+  fFit->SetSigmaMajorAxis(fTotalMeanFit.GetSigmaMajorAxis());
+  fFit->SetChisquare(fTotalMeanFit.GetChisquare());
+
+    if(usePrintOut)
+      fTotalMeanFit.Print();
+    
+  return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFitCalc.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFitCalc.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MPSFFitCalc.h	(revision 17960)
@@ -0,0 +1,93 @@
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPSFFitCalc                                                             //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MPSFFitCalc
+#define MARS_MPSFFitCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class TSring;
+class TH1D;
+
+class MGeomCam;
+#ifndef MARS_MCameraDC
+#include "MCameraDC.h"
+#endif
+#ifndef MARS_MPSFFit
+#include "MPSFFit.h"
+#endif
+
+class MPSFFitCalc : public MTask
+{
+
+private:
+ 
+    MGeomCam  *fGeomCam;
+    MCameraDC *fCamera; 
+    MPSFFit   *fFit;
+
+    MPSFFit   fTotalMeanFit;
+    UInt_t    fNumTotalMeanFits;
+    
+    TH1D *fPedestalDCHist;
+    Float_t fPedestalDC;
+
+    TString *fVname;
+    TArrayD fVinit; 
+    TArrayD fStep; 
+    TArrayD fLimlo; 
+    TArrayD fLimup; 
+    TArrayI fFix;
+    TObject *fObjectFit;
+    TString fMethod;
+    Bool_t fNulloutput;
+
+    Float_t fMaxDC;
+    UShort_t fImgCleanMode;
+    UShort_t fNumRings;
+    Float_t fPedLevel;
+    TArrayS fBlindPixels;
+
+    void RingImgClean();
+    void RmsImgClean(Float_t pedestal);
+    void MaskImgClean(TArrayS blindpixels);
+
+    void InitFitVariables();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+
+    enum ImgCleanMode_t{kNone=0,kRing,kRms,kMask,kCombined};
+    static const ImgCleanMode_t kDefault = kRing;
+
+    MPSFFitCalc(ImgCleanMode_t imgmode=kDefault, const char *name=NULL, const char *title=NULL);
+    ~MPSFFitCalc();
+    
+    void SetImgCleanMode(ImgCleanMode_t imgmode=kDefault){ fImgCleanMode=imgmode;};
+    void SetNumRings(UShort_t numRings) {fNumRings=numRings;}
+    void SetPedLevel(Float_t pedestal) {fPedLevel=pedestal;}
+    void SetBlindPixels(TArrayS blindpixels) {fBlindPixels=blindpixels;}
+    
+
+    ClassDef(MPSFFitCalc, 0)   // Task that fits the PSF using the dc readout of the camera.
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromFile.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromFile.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromFile.cc	(revision 17960)
@@ -0,0 +1,227 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López  04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosFromFile
+//
+// Task to set the position of the source as a function of run number according
+// to the positions read from an input file
+//
+//  Output Containers:
+//    MSrcPosCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+
+#include "MParList.h"
+#include "MSrcPosFromFile.h"
+
+#include "MRawRunHeader.h"
+#include "MSrcPosCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MSrcPosFromFile);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcPosFromFile";
+static const TString gsDefTitle = "Set the position of the (off axis) source according to input file";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. cardpath is the name of the input file (.pos) where the
+// source positions are stored in the format Run# x y (in mm). mode indicates whether
+// to read or to save the positions of the source in/from the internal histogram
+//
+MSrcPosFromFile::MSrcPosFromFile(TString cardpath, OnOffMode_t mode, const char *name, const char *title)
+  : fRawRunHeader(NULL), fSourcePositionFilePath(cardpath)
+{
+  fName  = name  ? name  : gsDefName.Data();
+  fTitle = title ? title : gsDefTitle.Data();
+  SetMode(mode);
+
+  fRunList=0x0;
+  fRunSrcPos=0x0;
+  fRunMap=0x0;
+
+  fLastRun  = 0;
+  fFirstRun = 0;
+  fLastValidSrcPosCam=0x0;
+
+  SetInternalHistoName(TString(fName)+"Hist");
+}
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MSrcPosFromFile::~MSrcPosFromFile()
+{
+  if(fRunList)
+    delete [] fRunList;
+  if(fRunSrcPos)
+    delete [] fRunSrcPos;
+  if(fRunMap)
+    delete fRunMap;
+}
+
+// -------------------------------------------------------------------------
+//
+// Open and read the input file.
+Int_t MSrcPosFromFile::PreProcess(MParList *pList)
+{
+  if(GetMode()==MSrcPlace::kOn)
+    {
+      // Count the number of runs in the card with the source poistions
+      ReadSourcePositionsFile(kCount);
+      
+      if(!fRunList)
+	fRunList = new Int_t[fNumRuns];
+      if(!fRunSrcPos)
+	fRunSrcPos = new MSrcPosCam[fNumRuns];
+      if(!fRunMap)
+	fRunMap = new TExMap(fNumRuns);
+      
+      // Read card with the source poistions
+      ReadSourcePositionsFile(kRead);
+    }
+
+  if(!MSrcPlace::PreProcess(pList))
+    return kFALSE;
+  
+  fRawRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+  if (!fRawRunHeader)
+    {
+      *fLog << err << AddSerialNumber("MRawRunHeader") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// In case we enter a new run, look for the position in the read list
+// If there is no value for that run, take the previous one
+// 
+Int_t MSrcPosFromFile::ComputeNewSrcPosition()
+{
+  const UInt_t run = fRawRunHeader->GetRunNumber();
+  if(run!=fLastRun)
+    {      
+      fLastRun=run;
+      MSrcPosCam* srcpos = (MSrcPosCam*)fRunMap->GetValue(run);
+
+      *fLog << inf << "Source position for run " << run;
+
+      if(srcpos)
+	fLastValidSrcPosCam = srcpos;
+      else if(run>fFirstRun)
+	for(UInt_t irun=run-1; irun>=fFirstRun;irun--)
+	  if((srcpos=(MSrcPosCam*)fRunMap->GetValue(irun)))
+	    {
+	      *fLog << inf << " not found in file. Taking position for run "<< irun;
+	      fLastValidSrcPosCam = srcpos;
+	      break;
+	    }
+      else if(fLastValidSrcPosCam)
+	*fLog << inf << " not found in file. Taking previous position: ";
+	
+      if(!fLastValidSrcPosCam)
+	{
+	  *fLog << warn << "MSrcPosFromFile::ComputeNewSrcPosition warning: no value for the first run. Taking first found run in file, run number " << fFirstRun;
+	  fLastValidSrcPosCam = (MSrcPosCam*)fRunMap->GetValue(fFirstRun);
+	}
+
+      *fLog << inf << "\tX\t" << setprecision(3) << fLastValidSrcPosCam->GetX();
+      *fLog << inf << "\tY\t" << setprecision(3) << fLastValidSrcPosCam->GetY() << endl;      
+    }
+
+  GetOutputSrcPosCam()->SetXY(fLastValidSrcPosCam->GetX(),fLastValidSrcPosCam->GetY());
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read file with table of source positions as function of run
+// 
+Int_t MSrcPosFromFile::ReadSourcePositionsFile(UShort_t readmode)
+{
+  
+  ifstream fin(fSourcePositionFilePath);
+  if(!fin)
+    {
+      *fLog << err << "MSrcPosFromFile::ReadSourcePositionsFile. Cannot open file " << fSourcePositionFilePath << endl;
+      return kFALSE;
+    }
+  
+  UInt_t run;
+  Float_t x,y;
+  
+  fNumRuns=0;
+  
+  *fLog << dbg << "MSrcPosFromFile::ReadSourcePositionsFile(" << readmode << ')' << endl;
+  while(1)
+    {
+      fin >> run >> x >> y;
+      if(!fFirstRun) fFirstRun=run;
+      if(fin.eof())
+	break;
+      
+      switch(readmode)
+	{
+	case kCount:
+	  {
+	    
+	    *fLog << dbg << "Source position for run " << run;
+	    *fLog << dbg << "\tX\t" << x << " mm";
+	    *fLog << dbg << "\tY\t" << y << " mm" << endl;
+	    
+	    fNumRuns++;
+	    break;
+	  }
+	case kRead:
+	  {
+	    fRunList[fNumRuns] = run;
+	    fRunSrcPos[fNumRuns].SetXY(x,y);
+	    fRunMap->Add(fRunList[fNumRuns],(Long_t)&(fRunSrcPos[fNumRuns]));
+	    fNumRuns++;
+	    break;
+	  }
+	default:
+	  *fLog << err << "Read mode " << readmode << " node defined" << endl;
+	  return kFALSE;
+	}
+    }
+  
+  fin.close();
+  
+  
+  return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromFile.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromFile.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromFile.h	(revision 17960)
@@ -0,0 +1,48 @@
+#ifndef MARS_MSrcPosFromFile
+#define MARS_MSrcPosFromFile
+
+#ifndef MARS_MSrcPlace
+#include "MSrcPlace.h"
+#endif
+
+#ifndef ROOT_TMap
+#include <TExMap.h>
+#endif
+
+class MRawRunHeader;
+class MSrcPosCam;
+
+class MSrcPosFromFile : public MSrcPlace
+{
+ private:
+
+    MRawRunHeader *fRawRunHeader;
+
+    Int_t  fNumRuns;
+    UInt_t  fFirstRun;
+    UInt_t  fLastRun;
+
+    Int_t      *fRunList;
+    MSrcPosCam *fRunSrcPos;
+    MSrcPosCam *fLastValidSrcPosCam;
+    TExMap     *fRunMap;   // list of run numbers positions
+
+    TString fSourcePositionFilePath;
+
+    virtual Int_t ReadSourcePositionsFile(UShort_t readmode);
+    virtual Int_t ComputeNewSrcPosition();
+    
+    virtual Int_t PreProcess(MParList *plist);
+    
+public:    
+    enum ReadMode_t {kCount=0,kRead};
+
+    MSrcPosFromFile(TString cardpath=0, OnOffMode_t mode=kOn, const char *name=NULL, const char *title=NULL);
+    ~MSrcPosFromFile();
+
+    void SetInputFileName(TString fname) {fSourcePositionFilePath=fname;}
+
+    ClassDef(MSrcPosFromFile, 0) // task to calculate the position of the source as a function of the run number 
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromStars.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromStars.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromStars.cc	(revision 17960)
@@ -0,0 +1,335 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Roger Firpo   04/2004 <mailto:jlopez@ifae.es>
+!   Author(s): Javier López  05/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosFromStars
+//
+// Task to set the position of the source using the positions of the stars
+// in the field of view of the source
+//
+//  Output Containers:
+//    MSrcPosCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+#include "MSrcPosFromStars.h"
+
+#include <TList.h>
+#include <TH2F.h>
+#include <TF2.h>
+#include <TTimer.h>
+#include <TString.h>
+#include <TCanvas.h>
+
+#include "MSrcPosCam.h"
+#include "MStarLocalCam.h"
+#include "MStarLocalPos.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MSrcPosFromStars);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcPosFromStars";
+static const TString gsDefTitle = "task to calculate the position of the source using the position of stars";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MSrcPosFromStars::MSrcPosFromStars(const char *name, const char *title)
+    : fStars(NULL)
+{
+  fName  = name  ? name  : gsDefName.Data();
+  fTitle = title ? title : gsDefTitle.Data();
+  
+  fDistances.Set(0);
+
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MSrcPosFromStars::PreProcess(MParList *pList)
+{
+
+  if(!MSrcPlace::PreProcess(pList))
+    return kFALSE;
+  
+  fStars = (MStarLocalCam*)pList->FindObject(AddSerialNumber("MStarLocalCam"));
+  if (!fStars)
+    {
+      *fLog << err << AddSerialNumber("MStarLocalCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  fNumStars = fDistances.GetSize();
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+static Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        cout << "Type 'q' to exit, <return> to go on: " << endl;
+        TString input;
+        input = getchar();
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+Int_t MSrcPosFromStars::ComputeNewSrcPosition()
+{
+
+  if (fNumStars == 0)
+    {
+      if (fStars->GetNumStars() > 0)
+        {
+
+          //Look for the star closer to the center of the camera
+          TIter Next(fStars->GetList());
+          MStarLocalPos* star;
+          Float_t mindist = 600; //mm
+          UInt_t starnum = 0;
+          Int_t select = -1;
+          while ((star=(MStarLocalPos*)Next())) 
+            {
+              Float_t dist = TMath::Sqrt(star->GetMeanX()*star->GetMeanX() +
+                                         star->GetMeanY()*star->GetMeanY());
+              if (dist < mindist)
+                {
+                  mindist = dist;
+                  select = starnum;
+                }
+              
+              starnum++;
+            }
+
+          if (select < 0)
+            {
+              *fLog << err << "Not found star closer to center" << endl;
+              return kFALSE;
+            }
+          
+          MStarLocalPos& selecStar = (*fStars)[select];
+
+          if (selecStar.GetChiSquareNdof() > 0. && selecStar.GetChiSquareNdof() < 10.)
+            {
+              
+              Float_t selecStarPosX = selecStar.GetMeanX();
+              Float_t selecStarPosY = selecStar.GetMeanY();
+        
+              GetOutputSrcPosCam()->SetXY(selecStarPosX,selecStarPosY);
+            }
+        }
+    }
+  else if (fStars->GetNumStars() >= fNumStars)
+    {
+      
+      Float_t diameterInnerPixel = 30; //[mm]
+      Float_t diameterOuterPixel = 60; //[mm]
+      
+      Double_t probability = 1.;
+
+      // Resolution and computing time are proportional to bins^2
+      const Int_t bins  = 200;
+      Double_t max_x_mm = 600;
+      Double_t min_x_mm = -max_x_mm;
+      Double_t max_y_mm = max_x_mm;
+      Double_t min_y_mm = -max_x_mm;
+      
+      // bins to mmrees
+      const Double_t bin2mm = 2 * max_x_mm / bins;
+      
+      // First run, to find the maximum peak and define the area
+      TH2F *hgrid = new TH2F("hgrid", "", bins, min_x_mm, max_x_mm, bins, min_y_mm, max_y_mm);
+      
+      for (Int_t ny = 1; ny <= bins; ny++)
+        for (Int_t nx = 1; nx <= bins; nx++)
+          hgrid->SetBinContent(nx, ny, 1.);
+
+      for (UInt_t numstar = 0; numstar < fNumStars; numstar++)
+        {
+          probability = 1;
+          
+          MStarLocalPos& star  = (*fStars)[numstar];
+          
+          if (star.GetChiSquareNdof() > 0. && star.GetChiSquareNdof() < 10.)
+            {
+              
+              Float_t starPosX  = star.GetMeanX();
+              Float_t starPosY  = star.GetMeanY();
+              Float_t starDist  = Dist(0.,0.,starPosX,starPosY);
+              Float_t starSigma = (starDist<350.?diameterInnerPixel:diameterOuterPixel);
+              
+//               *fLog << dbg << "Star[" << numstar << "] pos (" << starPosX << "," << starPosY << ") dist " << starDist << " size " << starSigma << endl;
+              
+              if (starSigma != 0)
+                {
+                  for (Int_t ny = 1; ny < bins + 1; ny++)
+                    {
+                      for (Int_t nx = 0; nx < bins + 1; nx++)
+                        {
+                          Float_t dist = Dist(min_x_mm + nx * bin2mm, starPosX, min_y_mm + ny * bin2mm, starPosY);
+                          Float_t prob = Prob(dist, fDistances[numstar], starSigma);
+                          
+//                           if ( prob > 0.8)
+//                             *fLog << dbg << " x " << min_x_mm + nx * bin2mm << " y " << min_y_mm + ny * bin2mm << " dist " << dist << " stardist " << fDistances[numstar] << " prob " << prob << endl;
+
+                          probability = hgrid->GetBinContent(nx, ny)*prob;
+                          hgrid->SetBinContent(nx, ny, probability);
+
+                        }
+                    }
+                }
+              else probability *= 1;
+              
+            }
+        }
+      
+      // Finding the peak
+      Double_t peak[2] = {0,0};
+      Double_t peak_value = 0;
+      
+      for (Int_t ny = 0; ny < bins + 1; ny++)
+        {
+          for (Int_t nx = 0; nx < bins + 1; nx++)
+            {
+              if (hgrid->GetBinContent(nx, ny) > peak_value)
+                {
+                  peak_value = hgrid->GetBinContent(nx, ny);
+                  peak[0] = min_x_mm + nx * bin2mm;
+                  peak[1] = min_y_mm + ny * bin2mm;
+                }
+            }
+        }
+      
+      *fLog << dbg << "The peak is at (x, y) = (" << peak[0] << ", " << peak[1] << ") mm" << endl;
+      
+      
+//       TCanvas c1;
+//       hgrid->Draw("lego");
+//       if(!HandleInput())
+//         exit(1);
+      
+      
+      // Here we define a small area surrounding the peak to avoid wasting time and resolution anywhere else
+      
+      min_x_mm = peak[0] - diameterInnerPixel;
+      max_x_mm = peak[0] + diameterInnerPixel;
+      min_y_mm = peak[1] - diameterInnerPixel;
+      max_y_mm = peak[1] + diameterInnerPixel;
+      
+      const Double_t xbin2mm = (max_x_mm - min_x_mm) / bins;
+      const Double_t ybin2mm = (max_y_mm - min_y_mm) / bins;
+      
+      // Other run centered in the peak for more precision
+      TH2F *hagrid = new TH2F("hagrid", "", bins, min_x_mm, max_x_mm, bins, min_y_mm, max_y_mm);
+
+      for (Int_t ny = 1; ny <= bins; ny++)
+        for (Int_t nx = 1; nx <= bins; nx++)
+          hagrid->SetBinContent(nx, ny, 1.);
+          
+      
+      for (UInt_t numstar = 0; numstar < fNumStars; numstar++)
+        {
+          probability = 1;
+          
+          MStarLocalPos& star  = (*fStars)[numstar];
+          
+          if (star.GetChiSquareNdof() > 0. && star.GetChiSquareNdof() < 10.)
+            {
+              
+              Float_t starPosX  = star.GetMeanX();
+              Float_t starPosY  = star.GetMeanY();
+              Float_t starDist  = Dist(0.,0.,starPosX,starPosY);
+              Float_t starSigma = (starDist<350.?diameterInnerPixel:diameterOuterPixel);
+              
+              if (starSigma != 0)
+                {
+                  for (Int_t ny = 0; ny < bins; ny++)
+                    {
+                      for (Int_t nx = 0; nx < bins; nx++)
+                        {
+                          Float_t prob = Prob(Dist(min_x_mm + nx * xbin2mm, starPosX, min_y_mm + ny * ybin2mm, starPosY), fDistances[numstar], starSigma);
+                          
+                          probability = hagrid->GetBinContent(nx, ny)*prob;
+                          hagrid->SetBinContent(nx, ny, probability);
+                        }
+                    }
+                }
+              else probability *= 1;                          
+              
+            }
+        }
+      
+      // This time we fit the histogram with a 2D gaussian
+      // Although we don't expect our function to be gaussian...
+      TF2 *gauss2d = new TF2("gauss2d","[0]*exp(-(x-[1])*(x-[1])/(2*[2]*[2]))*exp(-(y-[3])*(y-[3])/(2*[4]*[4]))", min_x_mm, max_x_mm, min_y_mm, max_y_mm);
+      
+      gauss2d->SetParName(0,"f0");
+      gauss2d->SetParName(1,"meanx");
+      gauss2d->SetParName(2,"sigmax");
+      gauss2d->SetParName(3,"meany");
+      gauss2d->SetParName(4,"sigmay");
+      
+      gauss2d->SetParameter(0,10);
+      gauss2d->SetParameter(1,peak[0]);
+      gauss2d->SetParameter(2,0.002);
+      gauss2d->SetParameter(3,peak[1]);
+      gauss2d->SetParameter(4,0.002);
+      
+      GetOutputSrcPosCam()->SetXY(gauss2d->GetParameter(1), gauss2d->GetParameter(3));
+      
+      delete hgrid;
+      delete hagrid;
+    }
+  
+
+  return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromStars.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromStars.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MSrcPosFromStars.h	(revision 17960)
@@ -0,0 +1,52 @@
+#ifndef MARS_MSrcPosFromStars
+#define MARS_MSrcPosFromStars
+
+#ifndef ROOT_TArrayF
+#include "TArrayF.h"
+#endif
+
+#ifndef ROOT_TMath
+#include "TMath.h"
+#endif
+
+#ifndef MARS_MSrcPlace
+#include "MSrcPlace.h"
+#endif
+
+class MStarLocalCam;
+class MSrcPosCam;
+
+class MSrcPosFromStars : public MSrcPlace
+{
+ private:
+
+  MStarLocalCam *fStars;
+
+  UInt_t fNumStars;
+  TArrayF fDistances;
+
+  virtual Int_t ComputeNewSrcPosition();
+  virtual Int_t PreProcess(MParList *plist);
+    
+public:    
+
+  MSrcPosFromStars(const char *name=NULL, const char *title=NULL);
+
+
+// This fuction is to compute the probability using a ring distribution
+  Double_t Prob(Double_t d, Double_t dist, Double_t sigma)
+    {
+      return TMath::Exp(-(d-dist)*(d-dist)/(2*sigma*sigma));///(sigma*TMath::Sqrt(2*3.141592654));
+    }
+ 
+  Double_t Dist(Double_t x1, Double_t x2, Double_t y1, Double_t y2)
+    {
+      return TMath::Sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
+    }
+  
+  void SetDistances(TArrayF dist) { fDistances = dist; }
+  
+  ClassDef(MSrcPosFromStars, 0) // task to calculate the position of the source using the position of stars
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MTopology.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MTopology.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MTopology.cc	(revision 17960)
@@ -0,0 +1,129 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix   09/2004 <mailto:jflix@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTopology
+//
+// Storage Container for topology parameters:
+//
+// fDistance = SUM_(i,j) D_ij , where i,j<UsedPixels and d_ij are distances
+//                              between pixels. This characterizes topology.
+//
+// fUsed = Used Pixels after image cleaning.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MTopology.h"
+
+#include <iostream>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+using namespace std;
+ClassImp(MTopology);
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+
+MTopology::MTopology(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MTopology";
+    fTitle = title ? title : "Parameters related to Topology of images after image cleaning";
+
+    Reset();
+}
+
+void MTopology::Reset()
+{
+    fDistance = -1;
+    fUsed = -1;
+}
+
+void MTopology::Print(Option_t *opt) const
+{
+      *fLog << all << GetDescriptor() << ":" << endl;
+      *fLog << "Topology Distance [mm] = " << fDistance << ": ";
+      *fLog << "Used Pixels = " << fUsed << ": " << endl;
+
+}
+
+Int_t MTopology::Calc(const MGeomCam &geom, const MCerPhotEvt &evt)
+{
+    const Int_t Pixels = evt.GetNumPixels();
+   
+    Double_t X[Pixels];
+    Double_t Y[Pixels];
+    Int_t NPixels[Pixels];
+ 
+    if (Pixels < 3)
+    {
+	Reset();
+	return 1;
+    };
+
+    MCerPhotPix *pix = 0;
+    
+    TIter Next(evt);
+    
+    fN_Pixels = 0;
+
+    Double_t fDist = 0.;
+    
+    while ((pix=(MCerPhotPix*)Next()))
+    {
+	const MGeomPix &gpix = geom[pix->GetPixId()];
+	
+	NPixels[fN_Pixels] = pix->GetPixId();
+	X[fN_Pixels] = gpix.GetX();
+	Y[fN_Pixels] = gpix.GetY();
+	
+	fN_Pixels++;
+    };
+
+    for (int i = 0; i < fN_Pixels ; i++){
+	for (int j = 0; j < fN_Pixels ; j++){
+	    fDist += sqrt(pow(X[j]-X[i],2) + pow(Y[j]-Y[i],2));
+	};		
+    };
+
+    fDistance = (Int_t)(fDist+.5);
+
+    SetDistance(fDistance);
+    SetUsedPixels(fN_Pixels);
+
+    SetReadyToSave();
+
+    return 0;
+	    
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/MTopology.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/MTopology.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/MTopology.h	(revision 17960)
@@ -0,0 +1,39 @@
+#ifndef MARS_MTopology
+#define MARS_MTopology
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomCam;
+class MCerPhotEvt;
+
+class MTopology : public MParContainer
+{
+private:
+
+    Int_t fDistance; // Evaluated sum of distances between 'used' pixels after image cleaning [mm]
+    Int_t fUsed;     // Number of pixels contained in an image
+
+    Int_t fN_Pixels;
+
+public:
+
+    MTopology(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MCerPhotEvt &evt);
+    
+    void Print(Option_t *opt=NULL) const;
+    
+    Int_t GetDistance()             { return fDistance; } 
+    Int_t GetUsedPixels()           { return fUsed; }
+
+    void SetDistance(Int_t Dist)    { fDistance=Dist; } 
+    void SetUsedPixels(Int_t Used)  { fUsed=Used; }
+
+    ClassDef(MTopology, 1) // Container to hold Topology related parameters
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mifae/library/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/library/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/library/Makefile	(revision 17960)
@@ -0,0 +1,96 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS IFAE library
+#
+##################################################################
+# @maintitle
+
+# @code
+
+#
+#  please change all system depend values in the 
+#  config.mk.${OSTYPE} file 
+#
+#
+include ../../../Makefile.conf.$(OSTYPE)
+include ../../../Makefile.conf.general
+
+#
+CINT     = IFAE
+#
+
+SOLIB    = ../../../libmars.so
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../../../mbase \
+	   -I../../../mjobs \
+	   -I../../../mpedestal \
+	   -I../../../mbadpixels \
+	   -I../../../mfileio \
+           -I../../../mraw \
+           -I../../../manalysis \
+	   -I../../../mgui \
+	   -I../../../mgeom \
+	   -I../../../msignal \
+	   -I../../../mcalib \
+	   -I../../../mfilter \
+	   -I../../../mhbase \
+	   -I../../../mimage \
+	   -I../../../mpointing \
+	   -I../../../mcamera \
+	   -I../../../mastro \
+	   -I../../../mhist \
+	   -I../../../mfbase \
+	   -I../../../mmc \
+	   -I../../../mdata \
+	   -I../../
+
+
+SRCFILES = \
+	MDisplay.cc \
+	MHillasDisplay.cc \
+        MPSFFit.cc \
+        MPSFFitCalc.cc \
+	MSrcPlace.cc \
+        MSrcPosFromFile.cc \
+	MSrcRotate.cc \
+	MSrcTranslate.cc \
+        MIslands.cc \
+	MImgIsland.cc \
+        MIslandsCalc.cc \
+        MIslandsClean.cc \
+        MFHVNotNominal.cc \
+        MCalibrateDC.cc \
+        MHPSFFromStars.cc \
+	MControlPlots.cc \
+        MSrcPosFromStars.cc \
+        MLiveTime.cc \
+        MLiveTimeCalc.cc \
+	MTopology.cc \
+	MTopologyCalc.cc \
+	MImageParDisp.cc \
+	MDispParameters.cc \
+	MDispCalc.cc \
+	MHDisp.cc \
+	MFDisp.cc \
+	MFindDisp.cc \
+	MEffAreaAndCoeffCalc.cc \
+	MGainFluctuationPix.cc \
+	MGainFluctuationCam.cc \
+	MAddGainFluctuation.cc
+
+
+############################################################
+
+all: $(OBJS)
+
+include ../../../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper: clean rmbak
+
+# @endcode
Index: branches/Mars_McMismatchStudy/mtemp/mifae/macros/OptimizeDisp.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/macros/OptimizeDisp.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/macros/OptimizeDisp.C	(revision 17960)
@@ -0,0 +1,555 @@
+//************************************************************************
+//
+// Authors : Eva Domingo,     12/2004 <mailto:domingo@ifae.es>
+//           Wolfgang Wittek, 12/2004 <mailto:wittek@mpppmu.mpg.de>
+//
+//
+// Macro for estimating the DISP parameter
+// ---------------------------------------
+//
+// DISP is the distance between the center of gravity of the shower image
+//      and the estimated source position, assumed to lie on the major 
+//      axis of the shower
+//
+// In order to get an estimate of DISP 
+// - one assumes a parametrization DISP = f(p[0],p[1],p[2],... ; s1,s2,s3,...)
+//           where s1,s2,s3,... are measurable quantities like
+//                              image parameters, (theta, phi), etc.
+//           and p[0],p[1],p[2], ... are free parameters
+//
+// - and determines the free parameters p[0],p[1],p[2]... from MC gamma data 
+//   by minimizing a parameter which measures the deviation of the estimated
+//   source position (using DISP) and the true source position
+//
+// The following classes are used :
+//
+// MDispParameters  container holding the parameters p[0],p[1],p[2],...
+//
+// MDispCalc        task calculating DISP with the parameters stored in 
+//                  MDispParameters
+//
+//   ::Calc         member function where the DISP parameterization is 
+//                  defined. It calculates DISP for a given event;
+//                  it is called by MDispCalc::Process()      
+//
+// MFindDisp        class with several functions :
+//
+//  ::DefineTrainMatrix     \  member functions which generate the training
+//  ::DefineTestMatrix       | and test samples (in the form of matrices)
+//  ::DefineTrainTestMatrix /  from the MC gamma data
+//
+//  ::FindParams    member function steering the minimization
+//                  (definition of the fcn function for Minuit, setting up the 
+//                  event loop to be executed in each minimization step,
+//                  call to Minuit);
+//                  for the minimization the training matrices are used
+//
+//  ::TestParams    member function testing the quality of the DISP estimate;
+//                  for the test the test matrices are used
+//
+// MHDisp           container for histograms which are useful for judging
+//                  the quality of the DISP estimate
+//                  Also task calculating the Minimization parameter
+//                  contribution of an event (in Fill()) 
+//                  and computing the final Minimization parameter of the 
+//                  whole event sample (in Finalize())
+//
+// MFDisp           filter to select sample for the optimization     
+//
+// 
+// The classes are stored in the CVS directory Mars/mtemp/mifae/library
+//                                   and       Mars/mtemp/mifae/macros
+//
+//
+//************************************************************************
+
+void OptimizeDisp()
+{
+    //************************************************************************
+
+    Bool_t CMatrix     = kFALSE;  // Create training and test matrices 
+    Bool_t WOptimize   = kFALSE;  // Do optimization using the training sample
+                                  // and write Disp parameter values 
+                                  // onto the file parDispfile
+                                  // Optimize Disp with :
+                        //TString typeOpt = "Data";
+                        TString typeOpt = "MC";
+    Bool_t RTest       = kFALSE;  // Test the quality of the Disp estimate
+                                  // using the test matrix
+    Bool_t WDisp       = kTRUE;  // Make Disp plots for the data of type :
+                        //TString typeInput = "ON";
+                        //TString typeInput = "OFF";
+                        TString typeInput = "MC";
+
+    //************************************************************************
+
+    gLog.SetNoColors();
+
+    if (gRandom)
+      delete gRandom;
+    gRandom = new TRandom3(0);
+    
+    //-----------------------------------------------
+    //names of files to be read for generating the training and test matrices
+    const char *filetrain  = "...";
+    const char *filetest   = "...";
+    
+    //-----------------------------------------------
+    // path for input for Mars
+    TString inPathON  = 
+      "/home/pcmagic14/wittek/CalibData/CrabLow42/2004_10_16/";
+    TString inPathOFF = 
+      "/home/pcmagic14/wittek/CalibData/CrabLow42/2004_10_17/";
+    TString inPathMC  = 
+    //"/discpepe/root_0.73mirror/wuerzburg/";
+    "~domingo/MAGIC/Disp05/";
+    
+    // path for output from Mars
+    TString outPath = "~domingo/MAGIC/Disp05/DispOptimization/";
+    
+    //-----------------------------------------------
+    // names of files for which Disp plots should be made
+    const char *offfile  = "*OffCrabLow42*";
+    const char *onfile   = "*CrabLowEn42*";
+    const char *mcfile   = "All_gammas0.73wuerzburg_zbin0to12_cleaned_3020_PeakSearch6_RunHeaders";
+    //-----------------------------------------------
+    
+    
+    //---------------------------------------------------------------------
+    gLog << "=====================================================" << endl;
+    gLog << "Macro OptimizeDisp : Start " << endl;
+    
+    gLog << "" << endl;
+    gLog << "Macro OptimizeDisp : CMatrix, WOptimize, RTest, WDisp = "
+         << (CMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (WOptimize  ? "kTRUE" : "kFALSE")  << ",  "
+         << (RTest      ? "kTRUE" : "kFALSE")  << ",  "
+         << (WDisp      ? "kTRUE" : "kFALSE")  << endl;
+    
+
+    //--------------------------------------------
+    // files to contain the matrices (generated from filenameTrain and
+    //                                               filenameTest)
+    // 
+    // for the training
+    TString fileMatrixTrain = outPath;
+    fileMatrixTrain += "MatrixTrainDisp";
+    fileMatrixTrain += ".root";
+    gLog << "" << endl;
+    gLog << "Files containing the Training and Test matrices :" << endl;
+    gLog << "      fileMatrixTrain = " << fileMatrixTrain << endl; 
+    
+    // for testing
+    TString fileMatrixTest = outPath;
+    fileMatrixTest += "MatrixTestDisp";
+    fileMatrixTest += ".root";
+    gLog << "      fileMatrixTest = " << fileMatrixTest << endl; 
+    gLog << "" << endl;
+    
+
+    //---------------
+    // file to contain the optimum Disp parameter values  
+    TString parDispFile = outPath;
+    //    parDispFile += "parDispMC.root";
+    parDispFile += "parDispMC_withcuts.root";
+
+    gLog << "" << endl;
+    gLog << "File containing the optimum Disp parameter values : parDispFile = " 
+         << parDispFile << endl;
+
+
+    // Set the filter cuts to select a sample of events for the Disp optimization
+    //    (islandsmin,islandsmax,usedpixelsmin,usedpixelsmax,corepixelsmin,
+    //     corepixelsmax,sizemin,sizemax,leakage1min,leakage1max,leakage2min,
+    //     leakage2max,lengthmin,widthmin);
+    MFDisp *fdisp = NULL;
+    fdisp = new MFDisp;
+    fdisp->SetCuts(0,2,7,600,0,600,0.,3000.,0.,0.,0.,0.,0.,0.);
+    fdisp->SetName("FilterSelector2");
+
+
+    // Create the MFindDisp object and set the file to store optimium Disp parameters
+    MFindDisp finddisp(fdisp);
+    finddisp.SetFilenameParam(parDispFile);
+
+
+    
+    //======================================================================
+    // Create matrices and write them onto files 
+    //======================================================================
+    
+    if (CMatrix)
+    {
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Generate the training and test samples" << endl;
+      
+      //--------------------------------------------
+      // files to be read for optimizing the Disp parameters
+      // 
+      // for the training
+      TString filenameTrain = inPathMC;
+      filenameTrain += mcfile;
+      filenameTrain += ".root";
+      Int_t howManyTrain = 30000;
+      gLog << "filenameTrain = " << filenameTrain << ",   howManyTrain = "
+	   << howManyTrain  << endl; 
+      
+      // for testing
+      TString filenameTest = inPathMC;
+      filenameTest += mcfile;
+      filenameTest += ".root";
+      Int_t howManyTest = 30000;
+      gLog << "filenameTest = " << filenameTest << ",   howManyTest = "
+	   << howManyTest  << endl; 
+      
+      
+      //--------------------------------------------      
+      // For the events in the matrices define requested distribution
+      // in some quantities; this may be a 1-dim, 2-dim or 3-dim distribution
+      
+      /*
+      // Define the cos(theta) distribution
+      TString mname("costheta");
+      MBinning bincost("Binning"+mname);
+      bincost.SetEdges(10, 0., 1.0);
+      
+      //MH3 mh3("cos((MPointingPos.fZd)/kRad2Deg)");
+      MH3 mh3("cos(MMcEvt.fTelescopeTheta)");
+      mh3.SetName(mname);
+      MH::SetBinning(&mh3.GetHist(), &bincost);
+      
+      for (Int_t i=1; i<=mh3.GetNbins(); i++)
+	mh3.GetHist().SetBinContent(i, 1.0);
+      */
+
+      // Define the log10(Etrue) distribution
+      TString mh3name("log10Etrue");
+      MBinning binslogE("Binning"+mh3name);
+      binslogE.SetEdges(50, 1., 3.);
+      
+      MH3 mh3("log10(MMcEvt.fEnergy)");
+      mh3.SetName(mh3name);
+      MH::SetBinning(&mh3.GetHist(), &binslogE);
+      
+      // Flat energy distribution 
+      //      for (Int_t i=1; i<=mh3.GetNbins(); i++)
+      //      	mh3.GetHist().SetBinContent(i, 1.0);
+      
+      // Power law energy distribution
+      //      for (Int_t i=1; i<=mh3.GetNbins(); i++)
+      //      {
+      //        Double_t weight = pow((Double_t)i, -1.7);
+      //        mh3.GetHist().SetBinContent(i, weight);
+      //      }      
+
+      /* 
+      // define the 'cos(Theta) vs. log10(Etrue)' distribution
+      TString mh3name("cosThetaVslog10Etrue");
+      MBinning binslogE("Binning"+mh3name+"X");
+      binslogE.SetEdges(18, 1.5, 2.2);
+      MBinning binscost("Binning"+mh3name+"Y");
+      binscost.SetEdges(10, 0., 1.0);
+      
+      //    MH3 mh3("log10(MMcEvt.fEnergy)", "cos((MPointingPos.fZd)/kRad2Deg)");
+      MH3 mh3("log10(MMcEvt.fEnergy)", "cos(MMcEvt.fTelescopeTheta)");
+      mh3.SetName(mh3name);
+      MH::SetBinning((TH2*)&mh3.GetHist(), &binslogE, &binscost);
+      
+      for (Int_t i=1; i<=((TH2*)mh3.GetHist()).GetNbinsX(); i++)
+      {
+	//	Double_t weight = pow((Double_t)i, -1.7);
+	for (Int_t j=1; j<=((TH2*)mh3.GetHist()).GetNbinsY(); j++)
+	{
+	  //	  mh3.GetHist().SetBinContent(i, j, weight);
+	  mh3.GetHist().SetBinContent(i, j, 1.);
+	}
+      }
+      */
+      
+      //--------------------------
+      // Training and test samples are generated from the same input files
+      if (filenameTrain == filenameTest)
+      {
+        if ( !finddisp.DefineTrainTestMatrix(
+                              filenameTrain,   mh3, 
+                              howManyTrain,    howManyTest,  
+                              fileMatrixTrain, fileMatrixTest, 0)     )
+	{
+	  *fLog << "OptimizeDisp.C : DefineTrainTestMatrix failed" << endl;
+          return;
+        }	
+      }
+      
+      //--------------------------
+      // Training and test samples are generated from different input files
+      else
+      {
+        if ( !finddisp.DefineTrainMatrix(filenameTrain, mh3,
+					 howManyTrain,  fileMatrixTrain, 0) )
+        {
+          *fLog << "OptimizeDisp.C : DefineTrainMatrix failed" << endl;
+          return;
+        }
+
+	if ( !finddisp.DefineTestMatrix( filenameTest, mh3, 
+					 howManyTest,  fileMatrixTest, 0)  )
+	{
+          *fLog << "OptimizeDisp.C : DefineTestMatrix failed" << endl;
+          return;
+        }
+      }
+
+      gLog << "Generation of training and test samples finished" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+    
+    
+
+    //======================================================================
+    // Optimize Disp parameters using the training sample
+    // 
+    // the initial values of the parameters are taken 
+    //     - from the file parDispInit (if != "")
+    //     - or from the arrays params and steps (if their sizes are != 0)
+    //     - or from the MDispParameters constructor
+    //======================================================================
+    
+    if (WOptimize)
+    {
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Optimize the Disp parameters over a " 
+	   << typeOpt << " sample, using the training matrices" << endl;
+      
+      // Read training matrices from file
+      finddisp.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+
+      //--------------------------------------------
+      // file which contains the initial values for the Disp parameters; 
+      // if parDispInit ="" 
+      //    - the initial values are taken from the arrays params and steps
+      //      if their sizes are different from 0
+      //    - otherwise they are taken from the MDispParameters constructor
+      
+      TString parDispInit = outPath;
+      //parDispInit += "parDispInit.root";
+      parDispInit = "";
+      
+      //--------------------------------------------
+      
+      TArrayD params(0);
+      TArrayD steps(0);
+      
+      if (parDispInit == "")
+      {
+	Double_t vparams[5] = {
+	// p[0],     p[1],     p[2],     p[3],     p[4],     p[5]
+	   1.0,      0.6,     -0.8,     -0.8,     -1.2/*,      0.5*/};
+	// 0.5,      0.,       0.03,     0.,       0./*,       0.5*/};
+	// 0.8,      0.,       0.,       0.,       0./*,       0.5*/};
+	
+	Double_t vsteps[5] = {
+	// dp[0],    dp[1],    dp[2],    dp[3],    dp[4],    dp[5]
+	   0.01,     0.005,    0.005,    0.005,    0.01/*,    0.001*/};
+	// 0.01,     0.01,     0.01,     0.01,     0.01/*,     0.001*/};
+	// 0.01,     0.01,     0.01,     0.01,     0.01/*,     0.001*/};
+
+	params.Set(5, vparams);
+	steps.Set (5, vsteps );
+      }
+
+      
+      Bool_t rf;
+      rf = finddisp.FindParams(parDispInit, params, steps);
+      
+      if (!rf) 
+      {
+	gLog << "OptimizeDisp.C : optimization of the Disp parameters failed" << endl;
+	return;
+      }
+      
+      gLog << "Optimization of Disp parameters finished" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+
+
+
+    //======================================================================
+    // Test the Disp parameters on the test sample
+    //======================================================================
+    
+    if (RTest)
+    {
+      // Read test matrices from file
+      finddisp.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+      
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Test the Disp parameters using the test matrices" << endl;
+      Bool_t rt = finddisp.TestParams();
+      if (!rt) 
+      {
+	gLog << "Test of the Disp parameters on the test matrices failed" 
+	     << endl;
+      }
+      gLog << "Test of the Disp parameters finished" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+    
+    
+
+
+    //======================================================================
+    // Make Disp plots
+    //======================================================================
+
+    if (WDisp)
+    {
+      gLog << "" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Make plots for Disp for data of the type " << typeInput << endl;
+      
+      //--------------------------------------------
+      // type of data to be read (ON, OFF or MC)
+      if (typeInput == "ON")
+	TString file(onfile);
+      else if (typeInput == "OFF")
+	TString file(offfile);
+      else if (typeInput == "MC")
+	TString file(mcfile);
+      
+      // name of input root file
+      TString filenameData = inPathMC;
+      filenameData += mcfile;
+      filenameData += ".root";
+      gLog << "Input file '" <<  filenameData << endl;
+      
+      //----------------------------------------------------
+      // read in optimum Disp parameter values 
+      
+      TFile inparam(parDispFile);
+      MDispParameters dispin;
+      dispin.Read("MDispParameters");
+      inparam.Close();
+      
+      gLog << "Disp parameter values were read in from file '"
+	   << parDispFile << "'" << endl;
+      
+      TArrayD dispPar;
+      dispPar =  dispin.GetParameters();
+      
+      TArrayD dispStep;
+      dispStep =  dispin.GetStepsizes();
+      
+      gLog << "optimum parameter values for calculating Disp : " << endl;
+      for (Int_t i=0; i<dispPar.GetSize(); i++)
+      {
+	gLog << dispPar[i] << ",  ";
+      }
+      gLog << endl;
+      
+      
+      //----------------------------------------------------
+      MTaskList tliston;
+      MParList  pliston;
+      
+      MReadMarsFile read("Events", filenameData);
+      read.DisableAutoScheme();
+      
+      // set cuts to select an event sample to apply Disp
+      MContinue contdisp(fdisp);
+      
+      // calculate Disp
+      MDispCalc dispcalc;
+      
+      // make Disp plots
+      // SelectedPos = 1  means choose the right source position
+      //               2                   wrong
+      //               3               the position according to M3Long
+      //               4               the position according to Asym
+      MHDisp hdisp1;
+      hdisp1.SetName("MHDispCorr");
+      hdisp1.SetSelectedPos(1);
+      MFillH filldisp1("MHDispCorr[MHDisp]", "");
+      
+      MHDisp hdisp2;
+      hdisp2.SetName("MHDispWrong");
+      hdisp2.SetSelectedPos(2);
+      MFillH filldisp2("MHDispWrong[MHDisp]", "");
+      
+      MHDisp hdisp3;
+      hdisp3.SetName("MHDispM3Long");
+      hdisp3.SetSelectedPos(3);
+      MFillH filldisp3("MHDispM3Long[MHDisp]", "");
+      
+      MHDisp hdisp4;
+      hdisp4.SetName("MHDispAsym");
+      hdisp4.SetSelectedPos(4);
+      MFillH filldisp4("MHDispAsym[MHDisp]", "");
+      
+      
+      //*****************************
+      // entries in MParList
+
+      pliston.AddToList(&tliston);
+      pliston.AddToList(&dispin);
+      pliston.AddToList(&hdisp1);
+      pliston.AddToList(&hdisp2);
+      pliston.AddToList(&hdisp3);
+      pliston.AddToList(&hdisp4);
+      
+      //*****************************
+      // entries in MTaskList
+    
+      tliston.AddToList(&read);
+      if (fdisp != NULL)
+	tliston.AddToList(&contdisp);
+      tliston.AddToList(&dispcalc);
+      tliston.AddToList(&filldisp1);
+      tliston.AddToList(&filldisp2);
+      tliston.AddToList(&filldisp3);
+      tliston.AddToList(&filldisp4);
+      
+      //*****************************
+      
+      //-------------------------------------------
+      // Execute event loop
+      //
+      MProgressBar bar;
+      MEvtLoop evtloop;
+      evtloop.SetParList(&pliston);
+      evtloop.SetProgressBar(&bar);
+      
+      Int_t maxevents = -1;
+      if ( !evtloop.Eventloop(maxevents) )
+        return;
+      
+      tliston.PrintStatistics(0, kTRUE);
+      
+      //-------------------------------------------
+      // Display the histograms
+      //
+      hdisp1.Draw();
+      hdisp2.Draw();
+      hdisp3.Draw();
+      hdisp4.Draw();
+      
+      //-------------------------------------------
+      
+      gLog << "Disp plots were made for file '" << filenameData << endl; 
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+    
+    delete fdisp;
+    
+    gLog << "Macro OptimizeDisp.C : End " << endl;
+    gLog << "=======================================================" << endl;
+    
+}
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/macros/lightcurve.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/macros/lightcurve.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/macros/lightcurve.C	(revision 17960)
@@ -0,0 +1,1178 @@
+
+Double_t ChiSquareNDof(TH1D *h1, TH1D *h2);
+Int_t GetBin(Double_t size, Int_t numberSizeBins, Double_t sizeBins[]);
+
+void lightcurve(TString f_on_name = "../HillasFiles/Mrk421/*_H.root", 
+                TString f_off_name = "../HillasFiles/OffMrk421/*_H.root")
+{
+
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetTimeOffset(-3600);
+
+  // Configuration
+  const Bool_t debug = kFALSE;
+  const Double_t timebin = 1380.; //[sec]
+  TString psname = "./20040421_Mrk421.1380s.ps";
+
+  //Constanst
+  const Double_t kConvDegToRad = TMath::Pi()/180.;
+  const Double_t kSec = 1e3;  //[sec/milisec]
+  const Double_t kDay = 24.*60.*60.;  //[Day/sec]
+
+  UInt_t numberTimeBins = 1;
+  TArrayI numberOnEvents(1);
+  TArrayD numberOnEventsAfterCleaning(1);
+  TArrayD numberBkgEventsToNormOn(1);
+  TArrayD timeOn(1);
+  
+  TArrayD meanTimeBinOn(1);
+  TArrayD widthTimeBinOn(1);
+
+  TArrayD zenithMinimumOn(1);
+  TArrayD zenithMaximumOn(1);
+
+  TArrayD deadFractionOn(1);
+  
+  TObjArray coszenithHistoOn;
+  TObjArray alphaHistoOn;
+  TObjArray srcposHistoOn;
+  TObjArray timediffHistoOn;
+  
+  const Int_t numberSizeBins = 3;
+  Double_t sizeBins[numberSizeBins] = {1897., 2785., 4087.}; //[Photons]
+
+  //cuts
+
+  Double_t widthmin[numberSizeBins]  = { 0.06, 0.06, 0.06 }; 
+  Double_t widthmax[numberSizeBins]  = { 0.10, 0.12, 0.12 };
+  Double_t lengthmin[numberSizeBins] = { 0.10, 0.10, 0.10 }; 
+  Double_t lengthmax[numberSizeBins] = { 0.25, 0.26, 0.36 };
+  Double_t distmin[numberSizeBins]   = { 0.30, 0.30, 0.30 }; 
+  Double_t distmax[numberSizeBins]   = { 1.20, 1.20, 1.20 };
+
+//   const Int_t numberSizeBins = 4;
+//   Double_t sizeBins[numberSizeBins] = {1292., 1897., 2785., 4087.}; //[Photons]
+
+//   //cuts
+
+//   Double_t widthmin[numberSizeBins]  = { 0.06, 0.06, 0.06, 0.06 }; 
+//   Double_t widthmax[numberSizeBins]  = { 0.10, 0.10, 0.12, 0.12 };
+//   Double_t lengthmin[numberSizeBins] = { 0.10, 0.10, 0.10, 0.10 }; 
+//   Double_t lengthmax[numberSizeBins] = { 0.20, 0.25, 0.26, 0.36 };
+//   Double_t distmin[numberSizeBins]   = { 0.30, 0.30, 0.30, 0.30 }; 
+//   Double_t distmax[numberSizeBins]   = { 1.20, 1.20, 1.20, 1.20 };
+
+  //alpha plot integration for gammas
+  Double_t sigexccmin = 0.;
+  Double_t sigexccmax = 15.;
+  Double_t bkgnormmin = 40.;
+  Double_t bkgnormmax = 80.;
+  
+  gStyle->SetOptStat(111111);
+  gStyle->SetOptFit();
+  
+  //
+  // Make a loop only for the ON data:
+  //
+  
+  MParList plist_on;
+  MTaskList tlist_on;
+  plist_on.AddToList(&tlist_on);
+  
+  // ON containers
+  MGeomCamMagic geomcam;
+  MRawRunHeader runheader_on;
+  MRawEvtHeader evtheader_on;
+  MTime              time_on;
+  MLiveTime      livetime_on;
+  MHillas          hillas_on;
+  MHillasSrc    hillassrc_on;
+  MSrcPosCam       srcpos_on;
+  MReportDrive      drive_on;
+
+  plist_on.AddToList(&geomcam);
+  plist_on.AddToList(&runheader_on);
+  plist_on.AddToList(&evtheader_on);
+  plist_on.AddToList(&time_on);
+  plist_on.AddToList(&livetime_on);
+  plist_on.AddToList(&hillas_on);
+  plist_on.AddToList(&hillassrc_on);
+  plist_on.AddToList(&srcpos_on);
+  plist_on.AddToList(&drive_on);
+
+  Int_t nbins_Size = 60;
+  Double_t min_Size = log10(sizeBins[0])*0.8;
+  Double_t max_Size = log10(1000000)*1.2;
+  TH1F *hSize_on = new TH1F ("hSizeOn","",nbins_Size,min_Size,max_Size);
+
+  Int_t nbins_Width = 20;
+  Double_t min_Width = 0.;
+  Double_t max_Width = widthmax[numberSizeBins-1]*1.2;
+  TH1F *hWidth_on = new TH1F ("hWidthOn","",nbins_Width,min_Width,max_Width);
+
+  Int_t nbins_Length = 20;
+  Double_t min_Length = 0.;
+  Double_t max_Length =  lengthmax[numberSizeBins-1]*1.2;
+  TH1F *hLength_on = new TH1F ("hLengthOn","",nbins_Length,min_Length,max_Length);
+
+  Int_t nbins_Dist = 20;
+  Double_t min_Dist = 0.;
+  Double_t max_Dist = distmax[numberSizeBins-1]*1.2;
+  TH1F *hDist_on = new TH1F ("hDistOn","",nbins_Dist,min_Dist,max_Dist);
+
+  Int_t nbins_abs = 18;
+  Double_t minalpha_abs = 0.;
+  Double_t maxalpha_abs =90.;
+  TH1F *hAlpha_on_abs = new TH1F ("hAbsAlphaOn","",nbins_abs,minalpha_abs,maxalpha_abs);
+
+  Int_t nbins = nbins_abs*2;
+  Double_t minalpha = -90.;
+  Double_t maxalpha =  90.;
+  TH1F *hAlpha_on = new TH1F ("hAlphaOn","",nbins,minalpha,maxalpha);
+
+  Int_t nbins_srcpos = 200;
+  Double_t minsrcpos = -200.;
+  Double_t maxsrcpos =  200.;  //[mm]  //!!! position precition 3mm ~ 0.01 deg
+  TH2F *hSrcPos_on = new TH2F ("hSrcPosOn","",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+
+  //
+  //tasks
+  //
+  
+  MReadTree read_on("Parameters", f_on_name);
+  read_on.DisableAutoScheme();
+ 
+  MSrcPlace srcplace;
+  MHillasSrcCalc csrc_on;
+
+  MLiveTimeCalc livetimecalc_on;
+  livetimecalc_on.SetRealTimeBinSize(timebin);
+
+//   // prints
+//   MPrint pevent("MRawEvtHeader");
+//   MPrint phillas("MHillas");
+//   MPrint phillassrc("MHillasSrc");
+//   MPrint psrcpos("MSrcPosCam");
+  
+  //tasklist
+  tlist_on.AddToList(&read_on);
+  tlist_on.AddToList(&livetimecalc_on);
+  tlist_on.AddToList(&srcplace);
+  tlist_on.AddToList(&csrc_on);
+  
+  // Create and setup the eventloop
+  MEvtLoop loop_on;
+  loop_on.SetParList(&plist_on);
+  //loop_on.SetDisplay(display);
+  
+//   MProgressBar bar;
+//   loop_on.SetProgressBar(&bar);
+  
+//   if (!loop_on.Eventloop())
+//     return;
+
+  if (!loop_on.PreProcess())
+    return;
+  
+  numberOnEventsAfterCleaning[numberTimeBins-1] = 0;
+  zenithMinimumOn[numberTimeBins-1] = 100.;
+  zenithMaximumOn[numberTimeBins-1] = 0.;
+  timeOn[numberTimeBins-1] = 0;
+
+  //create histos needed in the time bins
+
+  TString alphaTitle = Form("%s%02i","hAlphaOn",numberTimeBins-1);
+  TH1F *hAlpha_on_abs_timebin = new TH1F (alphaTitle,"",nbins_abs,minalpha_abs,maxalpha_abs);
+
+  TString srcposTitle =  Form("%s%02i","hSrcPosOn",numberTimeBins-1);
+  TH2F *hSrcPos_on_timebin = new TH2F (srcposTitle,"",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+
+  Int_t nbins_coszenith = 200;
+  Double_t mincoszenith = 0.;  
+  Double_t maxcoszenith = 1.;  
+  TString coszenithTitle =  Form("%s%02i","hCosZenithOn",numberTimeBins-1);
+  TH1F *hCosZenith_on_timebin = new TH1F (coszenithTitle,"",nbins_coszenith,mincoszenith,maxcoszenith);
+
+  Int_t nbins_timediff = 2000;
+  Double_t mintimediff = 0.;  
+  Double_t maxtimediff = 40.;  
+  TString timediffTitle =  Form("%s%02i","hTimeDiffOn",numberTimeBins-1);
+  TH1F *hTimeDiff_on_timebin = new TH1F (timediffTitle,"",nbins_timediff,mintimediff,maxtimediff);
+  TF1 *f1 = new TF1("exp","expo",mintimediff,maxtimediff);	      
+
+  Double_t lastSrcPosX = 0;
+  Double_t lastSrcPosY = 0;
+
+  while(tlist_on.Process())
+    {
+      numberOnEventsAfterCleaning[numberTimeBins-1]++;
+      
+      if (srcpos_on.GetX() == 0. && srcpos_on.GetY() == 0.)
+	srcpos_on.SetXY(lastSrcPosX,lastSrcPosY);
+      else
+	{
+	  lastSrcPosX = srcpos_on.GetX();
+	  lastSrcPosY = srcpos_on.GetY();
+	}
+      srcplace.CallProcess();
+      csrc_on.CallProcess();
+
+      
+      Double_t size = hillas_on.GetSize();
+      Double_t width = hillas_on.GetWidth()*geomcam.GetConvMm2Deg();
+      Double_t length = hillas_on.GetLength()*geomcam.GetConvMm2Deg();
+      Double_t meanx = hillas_on.GetMeanX()*geomcam.GetConvMm2Deg();
+      Double_t meany = hillas_on.GetMeanY()*geomcam.GetConvMm2Deg();
+      Double_t centerdist = TMath::Sqrt(meanx*meanx + meany*meany);
+      Double_t dist = hillassrc_on.GetDist()*geomcam.GetConvMm2Deg();
+      Double_t alpha = hillassrc_on.GetAlpha();
+      Double_t srcposx = srcpos_on.GetX();
+      Double_t srcposy = srcpos_on.GetY();
+      Double_t zenith = drive_on.GetNominalZd();
+	  
+
+      Int_t sizebin = GetBin(size,numberSizeBins,sizeBins);
+	  
+      if (sizebin >= 0)
+	{
+	  if (width > widthmin[sizebin] && width < widthmax[sizebin])
+	    {
+	      if (length > lengthmin[sizebin] && length < lengthmax[sizebin])
+		{
+		  if (dist > distmin[sizebin] && centerdist < distmax[sizebin])
+		    {      
+		      
+		      //General histos
+		      hSize_on->Fill(log10(size));
+		      hWidth_on->Fill(width);
+		      hLength_on->Fill(length);
+		      hDist_on->Fill(dist);
+		      hAlpha_on_abs->Fill(TMath::Abs(alpha));
+		      hAlpha_on->Fill(alpha);
+		      hSrcPos_on->Fill(srcposx,srcposy);
+		      
+		      // Time bin histos
+		      hAlpha_on_abs_timebin->Fill(TMath::Abs(alpha));
+		      hSrcPos_on_timebin->Fill(srcposx,srcposy);
+		      hCosZenith_on_timebin->Fill(TMath::Cos(zenith*kConvDegToRad));
+		      
+		      if (zenith != 0 && zenith < zenithMinimumOn[numberTimeBins-1])
+			zenithMinimumOn[numberTimeBins-1] = zenith;
+		      if (zenith>zenithMaximumOn[numberTimeBins-1])
+			zenithMaximumOn[numberTimeBins-1] = zenith;
+		      
+		    }
+		}
+	    }
+	}
+      
+      
+      // Check if you are overload the maxim time bin
+      if (numberTimeBins != livetime_on.GetNumberTimeBins())
+	{
+	  timeOn[numberTimeBins-1] = livetime_on.GetLiveTimeTArray().At(numberTimeBins-1);
+	  meanTimeBinOn[numberTimeBins-1] = livetime_on.GetMeanRealTimeTArray().At(numberTimeBins-1);
+	  widthTimeBinOn[numberTimeBins-1] = livetime_on.GetWidthRealTimeTArray().At(numberTimeBins-1);
+
+	  //Compute the number of on events
+	  numberOnEvents[numberTimeBins-1] = (Double_t) hAlpha_on_abs_timebin->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+	  numberBkgEventsToNormOn[numberTimeBins-1] =  (Double_t)  hAlpha_on_abs_timebin->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);	      
+	  
+// 	  hTimeDiff_on_timebin->Fit("exp","RQ0");
+// 	  deadFractionOn[numberTimeBins-1] = (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/(TMath::Abs(f1->GetParameter(1))*hTimeDiff_on_timebin->GetEntries());
+// 	  cout << "1-> Exp(" << f1->GetParameter(0) << " + " << f1->GetParameter(1) << "*x) +- [" <<  f1->GetParError(0) << ' ' << f1->GetParError(1) << "]" << endl;
+// 	  cout << "Calc entries " << (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/(TMath::Abs(f1->GetParameter(1))) << " +- Nt*(" << TMath::Sqrt( f1->GetParameter(0)*f1->GetParError(0)*f1->GetParameter(0)*f1->GetParError(0) + (f1->GetParError(1)*f1->GetParError(1))/(f1->GetParameter(1)*f1->GetParameter(1)))  << ") meas entries " << hTimeDiff_on_timebin->GetEntries() << " dead fraction " << deadFractionOn[numberTimeBins-1] << endl;
+	  deadFractionOn[numberTimeBins-1] = 1.;
+	  
+	  alphaHistoOn.AddLast(hAlpha_on_abs_timebin);
+	  srcposHistoOn.AddLast(hSrcPos_on_timebin);
+	  coszenithHistoOn.AddLast(hCosZenith_on_timebin);
+	  timediffHistoOn.AddLast(hTimeDiff_on_timebin);
+	  
+	  numberTimeBins = livetime_on.GetNumberTimeBins();
+	  
+	  timeOn.Set(numberTimeBins);
+	  numberOnEvents.Set(numberTimeBins);
+	  numberBkgEventsToNormOn.Set(numberTimeBins);
+	  widthTimeBinOn.Set(numberTimeBins);
+	  meanTimeBinOn.Set(numberTimeBins);
+	  zenithMinimumOn.Set(numberTimeBins);
+	  zenithMaximumOn.Set(numberTimeBins);
+	  deadFractionOn.Set(numberTimeBins);
+	  numberOnEventsAfterCleaning.Set(numberTimeBins);
+	  
+	  timeOn[numberTimeBins-1] = 0.;
+	  zenithMinimumOn[numberTimeBins-1] = 100.;
+	  zenithMaximumOn[numberTimeBins-1] = 0.;
+	  numberOnEventsAfterCleaning[numberTimeBins-1] = 0;
+	  
+	  alphaTitle =  Form("%s%02i","hAlphaOn",numberTimeBins-1);         
+	  hAlpha_on_abs_timebin = new TH1F (alphaTitle,"",nbins_abs,minalpha_abs,maxalpha_abs);
+	  
+	  srcposTitle =  Form("%s%02i","hSrcPosOn",numberTimeBins-1);
+	  hSrcPos_on_timebin = new TH2F (srcposTitle,"",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+	  
+	  coszenithTitle =  Form("%s%02i","hCosZenithOn",numberTimeBins-1);
+	  hCosZenith_on_timebin = new TH1F (coszenithTitle,"",nbins_coszenith,mincoszenith,maxcoszenith);
+	  
+	  timediffTitle =  Form("%s%02i","hTimeDiffOn",numberTimeBins-1);
+	  hTimeDiff_on_timebin = new TH1F (timediffTitle,"",nbins_timediff,mintimediff,maxtimediff);
+	  
+	}
+      
+    }
+	
+  loop_on.PostProcess();
+  
+  tlist_on.PrintStatistics();
+  
+  timeOn[numberTimeBins-1] = livetime_on.GetLiveTimeTArray().At(numberTimeBins-1);
+  meanTimeBinOn[numberTimeBins-1] = livetime_on.GetMeanRealTimeTArray().At(numberTimeBins-1);
+  widthTimeBinOn[numberTimeBins-1] = livetime_on.GetWidthRealTimeTArray().At(numberTimeBins-1);
+  
+  //Compute the number of on events for the last time bin
+  numberOnEvents[numberTimeBins-1] = (Double_t) hAlpha_on_abs_timebin->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+  numberBkgEventsToNormOn[numberTimeBins-1] =  (Double_t)  hAlpha_on_abs_timebin->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);	      
+
+//   hTimeDiff_on_timebin->Fit("exp","RQ0");
+//   deadFractionOn[numberTimeBins-1] = (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/(TMath::Abs(f1->GetParameter(1))*hTimeDiff_on_timebin->GetEntries());
+
+//   cout.precision(5);
+//   cout << "2-> Exp(" << f1->GetParameter(0) << " + 
+//   cout << "Calc entries " << (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/TMath::Abs(f1->GetParameter(1)) << " +- Nt*(" << TMath::Sqrt( f1->GetParameter(0)*f1->GetParError(0)*f1->GetParameter(0)*f1->GetParError(0) + (f1->GetParError(1)*f1->GetParError(1))/(f1->GetParameter(1)*f1->GetParameter(1)))  << ") meas entries " << hTimeDiff_on_timebin->GetEntries() << " dead fraction " << deadFractionOn[numberTimeBins-1] << endl;
+  deadFractionOn[numberTimeBins-1] = 1.;
+
+  alphaHistoOn.AddLast(hAlpha_on_abs_timebin);
+  srcposHistoOn.AddLast(hSrcPos_on_timebin);
+  coszenithHistoOn.AddLast(hCosZenith_on_timebin);
+  timediffHistoOn.AddLast(hTimeDiff_on_timebin);
+
+  //-----------------------OFF------------------------
+
+  TObjArray alphaHistoOff;
+  TObjArray srcposHistoOff;
+
+  TArrayD timeOff(numberTimeBins);
+
+  TArrayI numberOffEvents(numberTimeBins);
+
+  TArrayD numberBkgEventsToNormOff(numberTimeBins);
+  TArrayD onOffNormFactor(numberTimeBins);
+  TArrayD onOffNormFactorWithEvents(numberTimeBins);
+  TArrayD onOffNormFactorWithLiveTime(numberTimeBins);
+
+  TArrayD numberExcessEvents(numberTimeBins);
+  TArrayD errorNumberExcessEvents(numberTimeBins);
+
+  TArrayD numberExcessEventsPerSec(numberTimeBins);
+  TArrayD errorNumberExcessEventsPerSec(numberTimeBins);
+
+  TArrayD numberExcessEventsPerMin(numberTimeBins);
+  TArrayD errorNumberExcessEventsPerMin(numberTimeBins);
+
+  timeOff.Set(numberTimeBins);
+  
+  TH1F* hAlpha_off_abs_timebin;
+  TH2F* hSrcPos_off_timebin;
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      alphaTitle =  Form("%s%02i","hAlphaOff",bin);
+      hAlpha_off_abs_timebin = new TH1F (alphaTitle,"",nbins_abs,minalpha_abs,maxalpha_abs);;
+      alphaHistoOff.AddLast(hAlpha_off_abs_timebin);
+      //      cout << "hAlpha_off_abs_timebin " << hAlpha_off_abs_timebin <<  " alphaHistoOff [" << bin << "] " << alphaHistoOff[bin] << endl;
+
+      srcposTitle =  Form("%s%02i","hSrcPosOff",bin);
+      hSrcPos_off_timebin = new TH2F (srcposTitle,"",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+      srcposHistoOff.AddLast(hSrcPos_off_timebin);
+      //      cout << "hSrcPos_off_timebin " << hSrcPos_off_timebin <<  " srcposHistoOff [" << bin << "] " << srcposHistoOff[bin] << endl;
+    }
+
+  // 
+  // Make a loop only for the OFF data:
+  //
+  
+  MParList plist_off;
+  MTaskList tlist_off;
+  plist_off.AddToList(&tlist_off);
+  
+  MRawRunHeader runheader_off;
+  MRawEvtHeader evtheader_off;
+  MTime              time_off;
+  MLiveTime      livetime_off;
+  MHillas          hillas_off;
+  MHillasSrc    hillassrc_off;
+  MSrcPosCam       srcpos_off;
+  MReportDrive      drive_off;
+  
+  plist_off.AddToList(&geomcam);
+  plist_off.AddToList(&runheader_off);
+  plist_off.AddToList(&evtheader_off);
+  plist_off.AddToList(&time_off);
+  plist_off.AddToList(&livetime_off);
+  plist_off.AddToList(&hillas_off);
+  plist_off.AddToList(&hillassrc_off);
+  plist_off.AddToList(&srcpos_off);
+  plist_off.AddToList(&drive_off);
+
+  TH1F *hSize_off      = new TH1F ("hSizeOff","",nbins_Size,min_Size,max_Size);
+  TH1F *hWidth_off     = new TH1F ("hWidthOff","",nbins_Width,min_Width,max_Width);
+  TH1F *hLength_off    = new TH1F ("hLengthOff","",nbins_Length,min_Length,max_Length);
+  TH1F *hDist_off      = new TH1F ("hDistOff","",nbins_Dist,min_Dist,max_Dist);
+  TH1F *hAlpha_off_abs = new TH1F ("hAbsAlphaOff","",nbins_abs,minalpha_abs,maxalpha_abs);
+  TH1F *hAlpha_off     = new TH1F ("hAlphaOff","",nbins,minalpha,maxalpha);
+  TH2F *hSrcPos_off    = new TH2F ("hSrcPosOff","",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+
+  //tasks
+  MReadTree read_off("Parameters", f_off_name);
+  read_off.DisableAutoScheme();
+
+  // taks to set the src position in the off data for the time bins
+  // --------------------------------------------------------------
+  MSrcPlace srcplace_timebin;
+  srcplace_timebin.SetCreateHisto(kFALSE);
+  srcplace_timebin.SetMode(MSrcPlace::kOff);
+  // --------------------------------------------------------------
+
+  //  srcplace.SetMode(MSrcPlace::kOff);
+  
+  MHillasSrcCalc csrc_off;
+  
+  MLiveTimeCalc livetimecalc_off;
+
+ //tasklist
+  tlist_off.AddToList(&read_off);
+  tlist_off.AddToList(&livetimecalc_off);
+  tlist_off.AddToList(&srcplace_timebin); // This is just to run the preprocess correctely
+  tlist_off.AddToList(&csrc_off); // This is just to run the preprocess correctely
+  
+  // Create and setup the eventloop
+  MEvtLoop loop_off;
+  loop_off.SetParList(&plist_off);
+  //loop_off.SetDisplay(display);
+  
+//   MProgressBar bar_off;
+//   loop_off.SetProgressBar(&bar_off);
+  
+//   if (!loop_off.Eventloop(numEntries))
+//     return;
+  
+  if (!loop_off.PreProcess())
+    return;
+
+  while(tlist_off.Process())
+    {
+
+      //First read the variables source(i.e. time bin) independent
+      Double_t zenith = drive_off.GetNominalZd();
+
+      Double_t size = hillas_off.GetSize();
+      Double_t width = hillas_off.GetWidth()*geomcam.GetConvMm2Deg();
+      Double_t length = hillas_off.GetLength()*geomcam.GetConvMm2Deg();
+      Double_t meanx = hillas_off.GetMeanX()*geomcam.GetConvMm2Deg();
+      Double_t meany = hillas_off.GetMeanY()*geomcam.GetConvMm2Deg();
+      Double_t centerdist = TMath::Sqrt(meanx*meanx + meany*meany);
+      
+      Int_t sizebin = GetBin(size,numberSizeBins,sizeBins);
+      
+      if (sizebin >= 0)
+	{
+	  if (width > widthmin[sizebin] && width < widthmax[sizebin])
+	    {
+	      if (length > lengthmin[sizebin] && length < lengthmax[sizebin])
+		{
+		  if (centerdist < distmax[sizebin])
+		    {
+		      //General histos
+
+		      srcplace_timebin.SetPositionHisto(hSrcPos_on);
+		      srcplace_timebin.CallProcess();
+		      csrc_off.CallProcess();
+		      
+		      Double_t dist = hillassrc_off.GetDist()*geomcam.GetConvMm2Deg();
+		      Double_t alpha = hillassrc_off.GetAlpha();
+		      Double_t srcposx = srcpos_off.GetX();
+		      Double_t srcposy = srcpos_off.GetY();
+		      
+		      if (dist > distmin[sizebin] )
+			{
+			  hSize_off->Fill(log10(size));
+			  hWidth_off->Fill(width);
+			  hLength_off->Fill(length);
+			  
+			  hDist_off->Fill(dist);
+			  hAlpha_off_abs->Fill(TMath::Abs(alpha));
+			  hAlpha_off->Fill(alpha);
+			  hSrcPos_off->Fill(srcposx,srcposy);
+			}
+		      
+		      // Time bin histos
+		      for (UInt_t bin=0; bin<numberTimeBins; bin++)
+			{
+			  srcplace_timebin.SetPositionHisto((TH2F*)srcposHistoOn[bin]);
+			  srcplace_timebin.CallProcess();
+			  csrc_off.CallProcess();
+			  
+			  dist = hillassrc_off.GetDist()*geomcam.GetConvMm2Deg();
+			  alpha = hillassrc_off.GetAlpha();
+			  srcposx = srcpos_off.GetX();
+			  srcposy = srcpos_off.GetY();
+			  
+			  if (dist > distmin[sizebin])
+			    {
+			      ((TH1F*)alphaHistoOff[bin])->Fill(TMath::Abs(alpha));
+			      ((TH2F*)srcposHistoOff[bin])->Fill(srcposx,srcposy);
+			    }
+			}
+		    }
+		}
+	    }
+	}
+    }
+  
+  loop_off.PostProcess();
+
+  tlist_off.PrintStatistics();
+
+  TArrayD meanTimeBinOnInSec(numberTimeBins);
+  TArrayD widthTimeBinOnInSec(numberTimeBins);
+  
+  TArrayD meanTriggerRateOn(numberTimeBins);
+  TArrayD errorMeanTriggerRateOn(numberTimeBins);
+
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      cout.precision(5);
+      cout << bin << " timeOn " << timeOn[bin] << " mean-width time " << meanTimeBinOn[bin] << "-" << widthTimeBinOn[bin] << endl;
+    }
+  livetime_off.Print("last");
+  livetime_off.Print("all");
+  cout << "livetime_off.GetLiveTime() " << livetime_off.GetLiveTime() << endl;
+
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      timeOff[bin] = livetime_off.GetLiveTime();
+
+      //
+      meanTriggerRateOn[bin] = numberOnEventsAfterCleaning[bin]/timeOn[bin];
+      errorMeanTriggerRateOn[bin] = TMath::Sqrt(numberOnEventsAfterCleaning[bin])/timeOn[bin];
+
+      meanTimeBinOnInSec[bin]  = (meanTimeBinOn[bin]-(Int_t)meanTimeBinOn[bin]);
+      if (meanTimeBinOnInSec[bin] > 0.5)
+	meanTimeBinOnInSec[bin] = meanTimeBinOnInSec[bin] - 1 ;
+      meanTimeBinOnInSec[bin] *= kDay;
+
+      widthTimeBinOnInSec[bin] = widthTimeBinOn[bin]*kDay;
+
+      numberOffEvents[bin] = (Double_t) ((TH1F*)alphaHistoOff[bin])->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+      numberBkgEventsToNormOff[bin] =  (Double_t) ((TH1F*)alphaHistoOff[bin])->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);
+      if (numberOffEvents[bin] != 0 && numberBkgEventsToNormOff[bin] != 0)
+	{
+	  onOffNormFactorWithEvents[bin] = numberBkgEventsToNormOn[bin]/numberBkgEventsToNormOff[bin];
+	  onOffNormFactorWithLiveTime[bin] = timeOn[bin]/timeOff[bin];
+	  onOffNormFactor[bin] = onOffNormFactorWithEvents[bin];
+	  numberExcessEvents[bin] = numberOnEvents[bin] - onOffNormFactor[bin]*numberOffEvents[bin];
+	  errorNumberExcessEvents[bin] = TMath::Sqrt(numberOnEvents[bin] + onOffNormFactor[bin]*onOffNormFactor[bin]*numberOffEvents[bin]);
+	  numberExcessEventsPerSec[bin] = numberExcessEvents[bin]/timeOn[bin]*(deadFractionOn[bin]>1.?deadFractionOn[bin]:1.);
+	  errorNumberExcessEventsPerSec[bin] = errorNumberExcessEvents[bin]/timeOn[bin];
+	  numberExcessEventsPerMin[bin] = 60.*numberExcessEvents[bin]/timeOn[bin]*(deadFractionOn[bin]>1.?deadFractionOn[bin]:1.);
+	  errorNumberExcessEventsPerMin[bin] = 60.*errorNumberExcessEvents[bin]/timeOn[bin];
+
+	}
+    }
+  
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      cout.precision(5);
+      cout << bin << " timeOn " << timeOn[bin] << " mean-width time " << meanTimeBinOnInSec[bin] << "-" << widthTimeBinOnInSec[bin] << endl;
+      cout << " numberOnEvents\t " << numberOnEvents[bin] << endl;
+      cout << " numberOffEvents\t " << numberOffEvents[bin] << endl;
+      cout << " numberBkgEventsToNormOn\t " << numberBkgEventsToNormOn[bin] << endl;
+      cout << " numberBkgEventsToNormOff\t " << numberBkgEventsToNormOff[bin] << endl;
+      cout << " onOffNormFactorWithEvents\t " << onOffNormFactorWithEvents[bin] << endl;
+      cout << " onOffNormFactorWithLiveTime\t " << onOffNormFactorWithLiveTime[bin] << endl;
+      cout << " numberExcessEvents\t " <<  numberExcessEvents[bin] <<  " +- " << errorNumberExcessEvents[bin] << endl;
+      cout << " deadFraction\t" << deadFractionOn[bin] << endl;
+      cout << " Excess/Sec\t " << numberExcessEventsPerSec[bin] << " +- " << errorNumberExcessEventsPerSec[bin] << endl;
+      cout << " Trigger Rate\t " << meanTriggerRateOn[bin] << " +- " << errorMeanTriggerRateOn[bin] << endl;
+    }
+
+  
+
+  TString openpsname = psname + "(";
+  TString closepsname = psname + ")";
+
+  TCanvas *c0 = new TCanvas;
+  c0->cd(1);
+  TGraphErrors* lightcurvegraph = new TGraphErrors(numberTimeBins,meanTimeBinOnInSec.GetArray(),numberExcessEventsPerMin.GetArray(),widthTimeBinOnInSec.GetArray(),errorNumberExcessEventsPerMin.GetArray());
+  lightcurvegraph->SetTitle("LightCurve");
+  lightcurvegraph->SetMinimum(0.);
+  lightcurvegraph->SetMarkerStyle(21);
+  lightcurvegraph->SetMarkerSize(0.03);
+  lightcurvegraph->Draw("AP");
+  lightcurvegraph->GetYaxis()->SetTitle("Excess/min");
+  lightcurvegraph->GetXaxis()->SetTitle("UTC Time");
+  lightcurvegraph->GetXaxis()->SetTimeDisplay(1);
+  c0->Print(openpsname);
+      
+  TCanvas *c00 = new TCanvas;
+  c00->cd(1);
+  TGraphErrors* cosmicrategraph = new TGraphErrors(numberTimeBins,meanTimeBinOnInSec.GetArray(),meanTriggerRateOn.GetArray(),widthTimeBinOnInSec.GetArray(),errorMeanTriggerRateOn.GetArray());
+  cosmicrategraph->SetTitle("Cosmic Rate");
+  cosmicrategraph->SetMarkerStyle(21);
+  cosmicrategraph->SetMarkerSize(0.03);
+  cosmicrategraph->Draw("AP");
+  cosmicrategraph->GetYaxis()->SetTitle("[Hz]");
+  cosmicrategraph->GetXaxis()->SetTitle("UTC Time");
+  cosmicrategraph->GetXaxis()->SetTimeDisplay(1);
+  c00->Print(psname);
+
+  TCanvas** c = new TCanvas*[numberTimeBins];
+  
+  //Compute the maximum of all hAlphaOn histograms
+  Float_t maxAlphaHistoHeight = 0;
+  
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      for (UInt_t i=1; i<=nbins_abs; i++)
+	if (((TH1F*)alphaHistoOn[bin])->GetBinContent(i) > maxAlphaHistoHeight)
+	  maxAlphaHistoHeight = ((TH1F*)alphaHistoOn[bin])->GetBinContent(i);
+    }      
+  
+  cout << "maxAlphaHistoHeight " << maxAlphaHistoHeight << endl;
+
+  for (UInt_t bin=0; bin<numberTimeBins-1; bin++)
+    {
+      c[bin] = new TCanvas;
+      c[bin]->cd(1);
+      
+      ((TH1F*)alphaHistoOn[bin])->Sumw2();
+      ((TH1F*)alphaHistoOff[bin])->SetStats(0);
+      ((TH1F*)alphaHistoOff[bin])->Sumw2();
+      ((TH1F*)alphaHistoOff[bin])->Scale(onOffNormFactor[bin]); 
+      ((TH1F*)alphaHistoOn[bin])->SetStats(0); //-> Do NOT show the legend with statistics
+      ((TH1F*)alphaHistoOn[bin])->SetLineColor(kBlack);
+      ((TH1F*)alphaHistoOn[bin])->SetMarkerStyle(21);
+      ((TH1F*)alphaHistoOn[bin])->SetMarkerColor(kBlack);
+      ((TH1F*)alphaHistoOn[bin])->SetMarkerSize(0.7);
+      ((TH1F*)alphaHistoOff[bin])->SetFillColor(46);
+      ((TH1F*)alphaHistoOff[bin])->SetLineColor(46);
+      ((TH1F*)alphaHistoOff[bin])->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+      ((TH1F*)alphaHistoOn[bin])->SetMaximum(maxAlphaHistoHeight*1.2);
+      ((TH1F*)alphaHistoOff[bin])->SetMinimum(0.);
+      alphaTitle =  Form("%s%02i","hAlphaOnOff",bin);
+      ((TH1F*)alphaHistoOn[bin])->SetTitle(alphaTitle);
+      
+      
+      ((TH1F*)alphaHistoOn[bin])->DrawCopy("E1P");
+      ((TH1F*)alphaHistoOff[bin])->DrawCopy("HISTSAME");
+      ((TH1F*)alphaHistoOff[bin])->DrawCopy("ESAME");
+      ((TH1F*)alphaHistoOn[bin])->DrawCopy("E1PSAME");
+
+      c[bin]->Print(psname);
+    }
+
+  c[numberTimeBins-1] = new TCanvas;
+  c[numberTimeBins-1]->cd(1);
+  
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->Sumw2();
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetStats(0);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->Sumw2();
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->Scale(onOffNormFactor[numberTimeBins-1]); 
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetStats(0); //-> Do NOT show the legend with statistics
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetLineColor(kBlack);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMarkerStyle(21);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMarkerColor(kBlack);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMarkerSize(0.7);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetFillColor(46);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetLineColor(46);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMaximum(maxAlphaHistoHeight*1.2);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetMinimum(0.);
+  alphaTitle =  Form("%s%02i","hAlphaOnOff",numberTimeBins-1);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetTitle(alphaTitle);
+  
+  
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->DrawCopy("E1P");
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->DrawCopy("HISTSAME");
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->DrawCopy("ESAME");
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->DrawCopy("E1PSAME");
+  
+  c[numberTimeBins-1]->Print(psname);
+
+  //  TString rootname = psname.ReplaceAll(".ps",".root");
+  TString rootname = "./prueba.root";
+  TFile input(rootname, "RECREATE");
+
+   for (UInt_t bin=0; bin<numberTimeBins; bin++)
+     {
+       ((TH1F*)alphaHistoOn[bin])->Write();
+       ((TH2F*)srcposHistoOn[bin])->Write();
+       ((TH1F*)coszenithHistoOn[bin])->Write();
+       ((TH1F*)timediffHistoOn[bin])->Write();
+       ((TH1F*)alphaHistoOff[bin])->Write();
+       ((TH2F*)srcposHistoOff[bin])->Write();
+    }
+  
+  input.Close();
+
+  // ############################################################################
+  // Calculate significance and excess: 
+  // ############################################################################
+
+  Double_t norm_on_abs  = (Double_t) hAlpha_on_abs->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);
+  Double_t exces_on_abs = (Double_t) hAlpha_on_abs->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+  Double_t norm_off_abs  = (Double_t) hAlpha_off_abs->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);
+  Double_t exces_off_abs = (Double_t) hAlpha_off_abs->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+  Double_t norm = norm_on_abs/norm_off_abs;
+
+  char text_tit_alpha[256];
+  sprintf(text_tit_alpha, " Alpha Plot On and Off ");
+  hAlpha_off_abs->SetTitle(text_tit_alpha);
+  hAlpha_on_abs->SetTitle(text_tit_alpha);
+
+  Double_t excess  = exces_on_abs - exces_off_abs*norm;
+  Double_t sign    = excess / sqrt( exces_on_abs + norm*norm*exces_off_abs );
+  Double_t int_off = (Double_t) hAlpha_off_abs->Integral(1, 18);
+  int hAlpha_on_entries  = (int) hAlpha_on_abs->GetEntries();
+  int hAlpha_off_entries = (int) hAlpha_off_abs->GetEntries();
+    
+  cout << "---> Normalization F factor =\t" << norm <<endl;
+  cout << "---> Excess =\t\t\t" << excess <<endl;
+  cout << "---> Significancia =\t\t" << sign <<endl;    
+  cout << "---> entries on   =\t\t" << hAlpha_on_entries  <<endl;
+  cout << "---> entries off  =\t\t" << hAlpha_off_entries <<endl;
+  cout << "---> integral off =\t\t" << int_off <<endl;
+
+  Double_t shiftx;
+
+  // ############################################################################
+  // Draw SIZE
+  // ############################################################################
+  TCanvas *c1 = new TCanvas;
+
+  gPad->cd();
+
+  gPad->SetLogy();
+  hSize_on->Sumw2();
+  hSize_off->Sumw2();
+  hSize_off->Scale(norm); 
+  hSize_on->SetLineColor(kBlack);
+  hSize_on->SetMarkerStyle(21);
+  hSize_on->SetMarkerSize(0.7);
+  hSize_on->SetMarkerColor(kBlack);
+  hSize_off->SetFillColor(46);
+  hSize_off->SetLineColor(46);
+  hSize_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hSize_off->SetMinimum(0.1);
+  hSize_on->SetMinimum(0.1);
+  hSize_on->SetTitle("SIZE distribution");
+  hSize_off->SetTitle("SIZE distribution");
+
+  hSize_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_size = (TPaveStats*) hSize_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_size){
+    shiftx = pavs_on_size->GetX2NDC() - pavs_on_size->GetX1NDC();
+    pavs_on_size->SetX1NDC(pavs_on_size->GetX1NDC() - shiftx);
+    pavs_on_size->SetX2NDC(pavs_on_size->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hSize_off->DrawCopy("HISTSAME");
+  hSize_off->DrawCopy("ESAME");
+
+  gPad->Modified();
+  gPad->Update();
+
+  Double_t chisize = ChiSquareNDof((TH1D*)hSize_on,(TH1D*)hSize_off);
+
+  Double_t x_label_pos  = log10(1000000)*0.7;
+  Double_t y_label_pos  = log10((hSize_on->GetBinContent(hSize_on->GetMaximumBin()))/2.);
+  Double_t textsize = 0.03;
+
+  char text_size[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chisize);
+
+  TLatex *tsize = new TLatex(x_label_pos, y_label_pos, text_size);
+  tsize->SetTextSize(textsize);
+//  tsize->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c1->Print(psname);
+
+  // ############################################################################
+  // DrawCopy DIST
+  // ############################################################################
+  TCanvas *c2 = new TCanvas;
+
+  gPad->cd();
+
+  hDist_on->Sumw2();
+  hDist_off->Sumw2();
+  hDist_off->Scale(norm); 
+  hDist_on->SetLineColor(kBlack);
+  hDist_on->SetMarkerStyle(21);
+  hDist_on->SetMarkerSize(0.7);
+  hDist_on->SetMarkerColor(kBlack);
+  hDist_off->SetFillColor(46);
+  hDist_off->SetLineColor(46);
+  hDist_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hDist_off->SetMinimum(0.);
+  hDist_on->SetTitle("DIST distribution");
+  hDist_off->SetTitle("DIST distribution");
+
+  hDist_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_dist = (TPaveStats*) hDist_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_dist){
+    shiftx = pavs_on_dist->GetX2NDC() - pavs_on_dist->GetX1NDC();
+    pavs_on_dist->SetX1NDC(pavs_on_dist->GetX1NDC() - shiftx);
+    pavs_on_dist->SetX2NDC(pavs_on_dist->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hDist_off->DrawCopy("HISTSAME");
+  hDist_off->DrawCopy("ESAME");
+  hDist_on->DrawCopy("E1PSAME");
+
+  Double_t chidist = ChiSquareNDof((TH1D*)hDist_on,(TH1D*)hDist_off);
+
+  x_label_pos  = distmax[numberSizeBins-1]*0.7;
+  y_label_pos  = hDist_on->GetBinContent(hDist_on->GetMaximumBin())/2.;
+
+  char text_dist[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chidist);
+
+  TLatex *tdist = new TLatex(x_label_pos, y_label_pos, text_dist);
+  tdist->SetTextSize(textsize);
+//  tdist->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c2->Print(psname);
+
+   // ############################################################################
+  // DrawCopy WIDTH
+  // ############################################################################
+  TCanvas *c3 = new TCanvas;
+
+  gPad->cd();
+
+  hWidth_off->Sumw2();
+  hWidth_off->Scale(norm); 
+  hWidth_on->SetLineColor(kBlack);
+  hWidth_on->SetMarkerStyle(21);
+  hWidth_on->SetMarkerSize(0.7);
+  hWidth_on->SetMarkerColor(kBlack);
+  hWidth_off->SetFillColor(46);
+  hWidth_off->SetLineColor(46);
+  hWidth_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hWidth_off->SetMinimum(0.);
+  hWidth_on->SetTitle("WIDTH distribution");
+  hWidth_off->SetTitle("WIDTH distribution");
+
+  hWidth_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_width = (TPaveStats*) hWidth_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_width){
+    shiftx = pavs_on_width->GetX2NDC() - pavs_on_width->GetX1NDC();
+    pavs_on_width->SetX1NDC(pavs_on_width->GetX1NDC() - shiftx);
+    pavs_on_width->SetX2NDC(pavs_on_width->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hWidth_off->DrawCopy("HISTSAME");
+  hWidth_off->DrawCopy("ESAME");
+  hWidth_on->DrawCopy("E1PSAME");
+
+  Double_t chiwidth = ChiSquareNDof((TH1D*)hWidth_on,(TH1D*)hWidth_off);
+
+  x_label_pos  = widthmax[numberSizeBins-1]*0.7;
+  y_label_pos  = hWidth_on->GetBinContent(hWidth_on->GetMaximumBin())/2.;
+
+  char text_width[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chiwidth);
+
+  TLatex *twidth = new TLatex(x_label_pos, y_label_pos, text_width);
+  twidth->SetTextSize(textsize);
+//  twidth->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+ 
+  c3->Print(psname);
+
+  // ############################################################################
+  // DrawCopy LENGTH
+  // ############################################################################
+  TCanvas *c4 = new TCanvas;
+ 
+  gPad->cd();
+
+  hLength_on->Sumw2();
+  hLength_off->Sumw2();
+  hLength_off->Scale(norm); 
+  hLength_on->SetLineColor(kBlack);
+  hLength_on->SetMarkerStyle(21);
+  hLength_on->SetMarkerSize(0.7);
+  hLength_on->SetMarkerColor(kBlack);
+  hLength_off->SetFillColor(46);
+  hLength_off->SetLineColor(46);
+  hLength_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hLength_off->SetMinimum(0.);
+  hLength_on->SetTitle("LENGTH distribution");
+  hLength_off->SetTitle("LENGTH distribution");
+
+  hLength_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_length = (TPaveStats*) hLength_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_length){
+    shiftx = pavs_on_length->GetX2NDC() - pavs_on_length->GetX1NDC();
+    pavs_on_length->SetX1NDC(pavs_on_length->GetX1NDC() - shiftx);
+    pavs_on_length->SetX2NDC(pavs_on_length->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hLength_off->DrawCopy("HISTSAME");
+  hLength_off->DrawCopy("ESAME");
+  hLength_on->DrawCopy("E1PSAME");
+
+  Double_t chilength = ChiSquareNDof((TH1D*)hLength_on,(TH1D*)hLength_off);
+
+  x_label_pos  = lengthmax[numberSizeBins-1]*0.7;
+  y_label_pos  = hLength_on->GetBinContent(hLength_on->GetMaximumBin())/2.;
+
+  char text_length[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chilength);
+
+  TLatex *tlength = new TLatex(x_label_pos, y_label_pos, text_length);
+  tlength->SetTextSize(textsize);
+//  tlength->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c4->Print(psname);
+
+ // ############################################################################
+  // DrawCopy normalized ALPHA plot
+  // ############################################################################
+  TCanvas *c5 = new TCanvas;
+  
+  gPad->cd();
+
+  hAlpha_on_abs->Sumw2();
+  hAlpha_off_abs->SetStats(0);
+  hAlpha_off_abs->Sumw2();
+  hAlpha_off_abs->Scale(norm); 
+  hAlpha_on_abs->SetStats(0); //-> Do NOT show the legend with statistics
+  hAlpha_on_abs->SetLineColor(kBlack);
+  hAlpha_on_abs->SetMarkerStyle(21);
+  //hAlpha_on_abs->SetMarkerSize();
+  hAlpha_on_abs->SetMarkerColor(kBlack);
+  hAlpha_on_abs->SetMarkerSize(0.7);
+  hAlpha_off_abs->SetFillColor(46);
+  hAlpha_off_abs->SetLineColor(46);
+  hAlpha_off_abs->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hAlpha_off_abs->SetMinimum(0.);
+  hAlpha_on_abs->SetTitle("Alpha plot");
+  hAlpha_off_abs->SetTitle("Alpha plot");
+
+  
+  hAlpha_on_abs->DrawCopy("E1P");
+  hAlpha_off_abs->DrawCopy("HISTSAME");
+  hAlpha_off_abs->DrawCopy("ESAME");
+  hAlpha_on_abs->DrawCopy("E1PSAME");
+
+
+   //draw the LEGEND with excess and significance values in the alpha plot:
+  char text_Fnorm[256], text_excess[256], text_sign[256];
+  char text_entries_on[256], text_entries_off[256], text_integral_off[256];
+  int hAlpha_on_entries  = (int) hAlpha_on_abs->GetEntries();
+  int hAlpha_off_entries = (int) hAlpha_off_abs->GetEntries();
+  sprintf(text_Fnorm,       " F norm =       %.3f", norm);
+  sprintf(text_excess,      " Excess =       %.3f", excess);
+  sprintf(text_sign,        " Significance = %.3f", sign);
+  sprintf(text_entries_on,  " Entries ON   = %d",  hAlpha_on_entries);
+  sprintf(text_entries_off, " Entries OFF  = %d",  hAlpha_off_entries);
+  sprintf(text_integral_off," Integral OFF = %d",  int_off);
+  
+  x_label_pos  = 90.*0.7;
+  y_label_pos  = (hAlpha_on_abs->GetBinContent(hAlpha_on_abs->GetMaximumBin())); //2.;
+  Double_t y_label_step = y_label_pos / 8.;
+
+  TLatex *t0 = new TLatex(x_label_pos, y_label_pos - y_label_step*0, text_Fnorm);
+  t0->SetTextSize(textsize);
+  t0->Draw();
+  TLatex *t1 = new TLatex(x_label_pos, y_label_pos - y_label_step*1, text_excess);
+  t1->SetTextSize(textsize);
+  t1->Draw();
+  TLatex *t2 = new TLatex(x_label_pos, y_label_pos - y_label_step*2, text_sign);
+  t2->SetTextSize(textsize);
+  t2->Draw();
+  TLatex *t3 = new TLatex(x_label_pos, y_label_pos - y_label_step*3, text_entries_on);
+  t3->SetTextSize(textsize);
+  t3->Draw();
+  TLatex *t4 = new TLatex(x_label_pos, y_label_pos - y_label_step*4, text_entries_off);
+  t4->SetTextSize(textsize);
+  t4->Draw();
+  TLatex *t5 = new TLatex(x_label_pos, y_label_pos - y_label_step*5, text_integral_off);
+  t5->SetTextSize(textsize);
+  t5->Draw();
+  
+
+  Double_t chialpha = ChiSquareNDof((TH1D*)hAlpha_on_abs,(TH1D*)hAlpha_off_abs);
+
+  y_label_pos  = (hAlpha_on_abs->GetBinContent(hAlpha_on_abs->GetMaximumBin()))/2.;
+
+  char text_alpha[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chialpha);
+
+  TLatex *talpha = new TLatex(x_label_pos, y_label_pos, text_alpha);
+  talpha->SetTextSize(textsize);
+//  talpha->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c5->Print(psname);
+
+  // ############################################################################
+  // DrawCopy normalized alpha histos for alpha form -90 to 90 deg.
+  // ############################################################################
+  TCanvas *c6 = new TCanvas;
+
+  gPad->cd();
+
+  hAlpha_on->Sumw2();
+  hAlpha_off->SetStats(0);
+  hAlpha_off->Sumw2();
+  hAlpha_off->Scale(norm); 
+  hAlpha_off->SetFillColor(46);
+  hAlpha_off->SetLineColor(46);
+  hAlpha_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hAlpha_off->SetMinimum(0.); 
+  hAlpha_on->SetStats(0); //-> Do NOT show the legend with statistics
+  hAlpha_on->SetLineColor(kBlack);
+  hAlpha_on->SetMarkerStyle(21);
+  hAlpha_on->SetMarkerSize(0.7);
+  hAlpha_on->SetMarkerColor(kBlack);
+  hAlpha_on->SetTitle("Alpha plot form -90 to 90 deg");
+  hAlpha_off->SetTitle("Alpha plot form -90 to 90 deg");
+
+  hAlpha_on->DrawCopy("E1P");
+  hAlpha_off->DrawCopy("HISTSAME");
+  hAlpha_off->DrawCopy("ESAME");
+  hAlpha_on->DrawCopy("E1PSAME");
+
+  Double_t chialpha90 = ChiSquareNDof((TH1D*)hAlpha_on,(TH1D*)hAlpha_off);
+
+  x_label_pos  = 90.*0.5;
+  y_label_pos  = hAlpha_on->GetBinContent(hAlpha_on->GetMaximumBin())/2.;
+
+  char text_alpha90[256];
+  sprintf(text_alpha90,"ChiSquare/NDof = %4.2f",chialpha90);
+
+  TLatex *talpha90 = new TLatex(x_label_pos, y_label_pos, text_alpha90);
+  talpha90->SetTextSize(textsize);
+//  talpha90->Draw();
+
+  gPad->Update();
+  gPad->Modified();
+
+  c6->Print(psname);
+
+  cout << "---> ChiSquare/NDof [Size] =\t\t" << chisize << endl;
+  cout << "---> ChiSquare/NDof [Dist] =\t\t" << chidist << endl;
+  cout << "---> ChiSquare/NDof [Width] =\t\t" << chiwidth << endl;
+  cout << "---> ChiSquare/NDof [Length] =\t\t" << chilength << endl;
+  cout << "---> ChiSquare/NDof [Abs(Alpha)] =\t" << chialpha << endl;
+  cout << "---> ChiSquare/NDof [Alpha] =\t\t" << chialpha90 << endl;
+
+
+  TCanvas *c7 = new TCanvas;
+  hSrcPos_on->DrawCopy("BOX");
+  c7->Print(psname);
+
+  TCanvas *c8 = new TCanvas;
+  hSrcPos_off->DrawCopy("BOX");
+  c8->Print(closepsname);
+
+  cout << "Done!!" <<endl;
+  
+}
+
+
+Double_t ChiSquareNDof(TH1D *h1, TH1D *h2)
+{
+    Double_t chiq = 0.;
+    Double_t chi;
+    Double_t error;
+    Int_t nbinsnozero = 0;
+
+    Int_t nbins = h1->GetNbinsX();
+    if (nbins != h2->GetNbinsX() || nbins == 0)
+	return -1;
+
+    for (UInt_t bin=1; bin<=nbins; bin++)
+    {
+	error = sqrt(h1->GetBinError(bin)*h1->GetBinError(bin) +
+			   h2->GetBinError(bin)*h2->GetBinError(bin));
+	if (error != 0)
+	{
+	    chi = (h1->GetBinContent(bin)-h2->GetBinContent(bin))/error;
+	    chiq += chi*chi;
+	    nbinsnozero++;
+	}
+    }
+
+    return (nbinsnozero>0?chiq/nbinsnozero:0);
+}
+
+Int_t GetBin(Double_t size, Int_t numberSizeBins, Double_t sizeBins[])
+{
+
+  Int_t result = -1;
+
+  Int_t lowerbin = 0;
+  Int_t upperbin = numberSizeBins;
+  Int_t bin;
+
+  Int_t count = 0;
+
+  if (size >= sizeBins[0])
+    {
+      while (upperbin - lowerbin > 1 && count++<=numberSizeBins)
+	{
+	  bin = (upperbin+lowerbin)/2;
+	  if (size >= sizeBins[bin])
+	    lowerbin = bin;
+	  else
+	    upperbin = bin;
+	}
+      result = count<=numberSizeBins?lowerbin:-1;
+    }
+
+  return result;
+
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/macros/psffit.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/macros/psffit.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/macros/psffit.C	(revision 17960)
@@ -0,0 +1,149 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+
+void psffit(const TString filename="dc_2004_03_19_00_36_50_20781_Mrk421.root", const TString directory="/nfs/magic/CaCodata/rootdata/Mrk421/Period015/2004_03_19/", const UInt_t numEvents = 0)
+{
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MPSFFit       psffit;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&psffit);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+
+  const Int_t numrings = 3;
+  const Int_t numblind = 23;
+  const Short_t x[numblind] = {  8,  27, 224, 279, 339,
+			       507, 508, 509, 510, 511, 512, 513, 514,
+			       543,
+			       559, 560, 561, 562, 563, 564, 565, 566, 567};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  MPSFFitCalc psfcalc;
+  //psfcalc.SetImgCleanMode(MPSFFitCalc::kRing);
+  psfcalc.SetImgCleanMode(MPSFFitCalc::kCombined);
+  psfcalc.SetNumRings(numrings);
+  psfcalc.SetBlindPixels(blindpixels);
+
+
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&psfcalc, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  //
+  // Execute your analysis
+  //
+
+  if (numEvents > 0)
+  {
+      if (!evtloop.Eventloop(numEvents))
+	  return;
+  }
+  else
+  {
+      if (!evtloop.PreProcess())
+	  return;
+      
+      MHCamera display(geomcam);
+      display.SetPrettyPalette();
+      display.Draw();
+      gPad->cd(1);
+      psffit.Draw();
+      
+      while (tlist.Process())
+      {
+	  display.SetCamContent(dccam);
+	  gPad->Modified();
+	  gPad->Update();
+          psffit.Print();
+	  // Remove the comments if you want to go through the file
+	  // event-by-event:
+	  if (!HandleInput())
+	      break;
+      } 
+
+      evtloop.PostProcess();
+  }
+
+  tlist.PrintStatistics();
+
+  psffit.Print();
+  cout << "RUN " << psffit.GetMeanMinorAxis() << ' ' << psffit.GetSigmaMinorAxis() << ' ' <<  psffit.GetMeanMajorAxis()  << ' ' <<  psffit.GetSigmaMajorAxis() << ' ' << psffit.GetChisquare() << endl;
+  
+}
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/macros/psffromstars.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/macros/psffromstars.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/macros/psffromstars.C	(revision 17960)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 05/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+Double_t fitfunc(Double_t *x, Double_t *par);
+
+
+void psffromstars(const TString filename="dc_*.root", const TString directory="/nfs/magic/CaCodata/online_data/Period015/cacadata/2004_03_21/", const UInt_t numEvents = 100000000)
+{
+
+  gStyle->SetOptFit(1);
+  
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarLocalCam starcam;
+  MHPSFFromStars mhpsf;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+  plist.AddToList(&mhpsf);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+  TString continuoslightfile = 
+    //    "/home/Javi/mnt_magic_data/CaCo/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+    "/nfs/magic/CaCodata/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+
+  Float_t mindc = 0.7; //[uA]
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 1;
+  const Short_t x[numblind] = { 124};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 3.5;
+  UInt_t integratedevents = 10;
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+
+  MFillH fpsf("MHPSFFromStars","MStarLocalCam");
+  
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  tlist.AddToList(&findstars, "Currents");
+  tlist.AddToList(&fpsf, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+//   MProgressBar bar;
+//   evtloop.SetProgressBar(&bar);
+  
+  //
+  // Execute your analysis
+  //
+  
+  if (!evtloop.Eventloop(numEvents))
+    return;
+
+  tlist.PrintStatistics();
+
+  //Draw results
+
+  MStatusDisplay *d = new MStatusDisplay;
+  d->SetTitle(Form("- %s -",filename));
+  d->SetLogStream(&gLog, kTRUE);            // Disables output to stdout
+
+  // Create a default canvas
+  TCanvas &c1 = d.AddTab("Star spot Position");
+  mhpsf.Draw("mean");
+  TCanvas &c2 = d.AddTab("Star's Path");
+  mhpsf.Draw("camera");
+  TCanvas &c3 = d.AddTab("Star spot Size");
+  mhpsf.Draw("sigma");
+  TCanvas &c4 = d.AddTab("Star XY Projection");
+  mhpsf.Draw("projection");
+  
+  d->Print("./psf.ps");
+  
+  //  if (!HandleInput()) {}
+
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mifae/macros/runlivetime.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/macros/runlivetime.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/macros/runlivetime.C	(revision 17960)
@@ -0,0 +1,96 @@
+void runlivetime(TString filename)
+{
+
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+
+  //
+  // Make a loop only for the ON data:
+  //
+  
+  MParList plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  //Containers
+  
+  MLiveTime livetime;
+
+  plist.AddToList(&livetime);
+  
+  //
+  //tasks
+  //
+  
+  MReadTree read("Parameters");
+  read.DisableAutoScheme();
+
+  TString tmpfile = "./runlivetime.ls.tmp";
+  TString cmd = "ls " + filename + " > " + tmpfile;
+  gSystem->Exec(cmd);
+  TString tmpline;
+  ifstream in(tmpfile);
+  while(1)
+  {
+      in >> tmpline;
+      if(in.eof())
+	  break;
+      read.AddFile(tmpline);
+  }
+  TString cmd = "rm " + tmpfile;
+  gSystem->Exec(cmd);
+
+  Double_t timebin = 500.; //[sec]
+  MLiveTimeCalc livetimecalc;
+  livetimecalc.SetRealTimeBinSize(timebin);
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&livetimecalc);
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop loop;
+  loop.SetParList(&plist);
+     
+
+  if (!loop.Eventloop())
+      return;
+
+//   if (!loop.PreProcess())
+//     return;
+
+//   while(loop.Process())
+//     {}
+  
+//   loop.PostProcess();
+
+  tlist.PrintStatistics();
+
+  UInt_t numbertimebins = livetime.GetNumberTimeBins();
+  TArrayD y(numbertimebins);
+  TArrayD erry(numbertimebins);
+
+  for (UInt_t bin=0; bin<numbertimebins; bin++)
+    {
+      y[bin] = bin+1.;
+      erry[bin] = 0.;
+    }
+
+  TCanvas *c0 = new TCanvas;
+  c0->cd(1);
+  TGraphErrors *graph = new TGraphErrors(numbertimebins,livetime.GetMeanRealTimeArray(),y.GetArray(),livetime.GetWidthRealTimeArray(),erry.GetArray());
+  graph->SetTitle("");
+  graph->SetMinimum(0.);
+  graph->SetMarkerStyle(21);
+  graph->SetMarkerSize(0.03);
+  graph->Draw("AP");
+  graph->GetXaxis()->SetLabelSize(0.03);
+  graph->GetXaxis()->SetTitle("Time [MJD]");
+  //  lightcurvegraph->GetXaxis()->SetTimeDisplay(1);
+
+  
+}
Index: branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/20040510_Mrk421.pos
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/20040510_Mrk421.pos	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/20040510_Mrk421.pos	(revision 17960)
@@ -0,0 +1,40 @@
+25791 -31.8904 -22.2868
+25793 -31.204 -25.1259
+25794 -30.8582 -26.1056
+25796 -30.8433 -27.315
+25800 -30.9893 -26.5873
+25801 -30.129 -28.5482
+25802 -30.0869 -29.0446
+25803 -29.6106 -29.6053
+25806 -29.5739 -30.2493
+25807 -29.1453 -30.803
+25811 -29.2426 -30.7231
+25812 -29.1423 -31.5773
+25813 -29.4705 -31.4197
+25814 -29.1459 -32.4534
+25816 -28.9612 -33.5763
+25817 -28.9655 -33.0914
+25819 -29.2206 -33.2739
+25820 -29.013 -33.6073
+25837 -23.6607 -37.5356
+25839 -23.2204 -38.3438
+25840 -23.2022 -38.145
+25842 -23.2352 -38.8685
+25843 -22.9597 -38.2165
+25845 -22.7618 -39.4373
+25846 -22.4334 -38.3265
+25848 -22.1283 -38.5474
+25850 -22.0476 -39.362
+25851 -21.3159 -38.6381
+25852 -20.51 -39.3704
+25854 -20.0418 -39.6989
+25855 -20.0536 -39.2094
+25858 -20.3918 -42.9825
+25860 -20.5511 -43.2302
+25861 -22.9288 -40.9434
+25862 -21.534 -43.0463
+25863 -23.9955 -41.2485
+25864 -23.6695 -42.2856
+25874 -23.8745 -43.3409
+25876 -20.2687 -43.5657
+25883 -24.6953 -42.6541
Index: branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_220404_pos.txt
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_220404_pos.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_220404_pos.txt	(revision 17960)
@@ -0,0 +1,65 @@
+23203 49.2726 61.8901
+23204 41.693 83.1926
+23209 33.6331 88.5239
+23210 28.2513 92.6265
+23212 21.4295 96.1593
+23213 16.432 97.7467
+23216 0.550093 102.076
+23217 -8.98307 101.311
+23219 -19.9699 101.232
+23220 -48.3997 97.7073
+23222 -35.553 94.5315
+23223 -42.1249 90.7072
+23225 -49.72 87.585
+23226 -48.378 70.4774
+23229 -55.2906 60.7539
+23230 -56.1453 60.0578
+23232 -57.1738 52.706
+23233 -57.0943 47.5582
+23235 -63.7419 43.9618
+23236 -62.0881 37.9026
+23238 -73.589 36.2268
+23239 -70.8132 31.9569
+23241 -70.478 28.262
+23242 -69.6348 24.0415
+23244 -68.4586 20.6795
+23245 -67.2766 19.0235
+23250 -55.8484 0.194891
+23253 -53.7881 -3.28016
+23255 -52.8007 -4.84312
+23256 -51.2311 -6.88246
+23259 -48.3625 -9.56292
+23262 -45.6057 -11.7548
+23265 -43.3533 -13.5378
+23268 -44.4973 -14.4726
+23271 -43.343 -15.6643
+23273 -42.2395 -16.4098
+23275 -41.4118 -16.7661
+23278 -40.2932 -17.6661
+23279 -39.9929 -17.671
+23280 -39.711 -17.442
+23281 -39.0344 -18.3018
+23282 -38.4745 -18.2764
+23283 -35.0204 -18.1458
+23289 -34.7234 -20.9747
+23291 -34.1059 -22.5775
+23292 -34.7917 -21.5298
+23293 -33.2113 -22.229
+23294 -33.4358 -21.962
+23297 -32.7803 -21.0645
+23299 -31.8816 -21.61
+23300 -30.4907 -23.1672
+23301 -31.7465 -21.3046
+23302 -30.2575 -21.4706
+23303 -29.7285 -21.6212
+23304 -29.5768 -21.3276
+23305 -29.2646 -23.2172
+23306 -29.0006 -21.7169
+23307 -28.9752 -21.71
+23308 -29.1528 -21.6656
+23309 -28.5402 -21.0133
+23310 -28.6243 -21.7256
+23311 -29.0955 -21.5047
+23312 -29.5512 -22.1346
+23314 -29.679 -22.068
+23317 -30.901 -21.6827
Index: branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_april.pos
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_april.pos	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_april.pos	(revision 17960)
@@ -0,0 +1,326 @@
+20780 -61.6944 67.059
+20781 -64.6926 47.4227
+20783 -65.8374 43.1406
+20784 -66.6132 39.1829
+20786 -67.4031 35.7154
+20787 -66.244 32.1211
+20790 -65.9027 29.6755
+20791 -62.6377 59.1079
+20794 -65.6662 25.6452
+20795 -64.9428 22.9849
+20797 -64.1151 20.8169
+20798 -63.723 18.4919
+20800 -63.3643 16.6103
+20801 -63.1704 14.2815
+20804 -62.7876 13.6825
+20805 -62.4634 11.3297
+20806 -62.1662 9.6296
+20807 -60.0303 8.64362
+20808 -60.2703 0.509429
+20809 -59.386 -0.938021
+20811 -58.1121 -4.42333
+20812 -56.5063 -5.16089
+20813 -54.9194 -6.98546
+20814 -53.7668 -8.03962
+20818 -46.0907 -16.6877
+20819 -45.8623 -14.8199
+20820 -45.7539 -14.3919
+20821 -44.929 -16.358
+22245 10.2468 23.1621
+22249 25.85 25.9106
+22250 25.6546 29.1566
+22251 29.1613 25.4159
+22254 58.316 33.7302
+22255 37.5861 29.4664
+22257 57.9896 34.7069
+22258 61.9726 25.5081
+22260 81.5392 37.5373
+22261 70.6807 16.5722
+22264 58.1712 25.6161
+22266 66.3476 40.3227 
+22384 33.7108 44.2858
+22388 31.4939 45.9244
+22394 36.3619 47.3819
+22395 38.3426 48.5743
+22400 39.6094 48.8239
+22401 41.1102 50.745
+22406 42.1073 51.6704
+22407 43.8524 54.075
+22411 45.2629 54.7259
+22412 45.3289 58.2773
+22413 45.9415 58.2507
+22414 69.3919 87.317
+22429 52.0164 66.3798
+22439 45.8513 71.0317
+22440 45.5684 71.4425
+22450 43.789 74.1573
+22451 41.3883 76.8225
+22461 410.064 168.151
+22462 407.911 169.206
+22466 394.568 183.316
+22467 393.798 194.727
+22477 380.467 220.11
+22478 373.801 240.848
+22483 20.3671 101.709
+22484 14.4039 101.842
+22489 8.03032 103.608
+22490 0.0405639 104.229
+22495 289.384 348.55
+22496 255.487 359.161
+22503 -15.7097 106.418
+22504 -22.6365 102.47
+22511 -30.7607 100.265
+22512 -33.8572 100.537
+22516 -41.9986 100.456
+22517 -48.2052 90.4964
+22522 -65.668 42.6643
+22526 -65.0008 41.6949
+22527 -65.629 38.2615
+22531 -66.3627 35.6813
+22532 -67.0988 32.6288
+22534 -67.5101 30.7526
+22535 -66.7941 28.2758
+22538 -66.0013 26.5091
+22539 -65.0212 23.9648
+22541 -64.507 22.077
+22544 -63.4069 19.9872
+22558 276.466 -110.216
+22559 -263.554 -391.457
+22560 -284.903 -390.722
+22711 244.229 32.1922
+22717 587.4 109.335
+22718 53.802 53.875
+22719 44.9718 46.5444
+22720 48.771 45.2452
+22722 46.5953 51.4958
+22723 47.1241 57.9021
+22725 46.6285 59.6458
+22726 48.0192 62.5682
+22728 46.6808 63.3769
+22729 81.7319 131.281
+22731 41.5407 73.4151
+22732 38.9125 74.97
+22735 394.369 184.289
+22736 391.167 187.667
+22738 375.638 224.6
+22739 368.822 243.244
+22743 16.1032 94.8722
+22744 11.2596 95.7668
+22746 4.11151 98.6553
+22747 -5.51529 98.7573
+22749 258.705 353.641
+22750 228.989 359.292
+22752 -22.5239 97.8863
+22754 -25.7971 97.6711
+22755 -31.3562 96.3472
+22756 -35.3656 94.8347
+22757 -43.9467 89.2152
+22758 -54.7801 64.0827
+22763 -63.5534 45.2586
+22765 -64.7755 40.1216
+22766 -65.8142 38.821
+22768 -66.4905 35.2643
+22769 -67.0298 32.6377
+22810 -117.508 -441.851
+22811 -200.855 -401.565
+22962 40.604 36.4264
+22964 599.401 46.4693
+22965 63.519 44.8682
+22967 365.741 -0.122339
+22969 369.93 20.0097
+00000 300.355 -52.2264
+22970 280.213 -149.609
+22971 234.378 -216.905
+22973 254.659 189.151
+22974 101.128 -67.7792
+22976 47.8854 59.8481
+22977 47.2984 63.6432
+22979 46.9635 66.0826
+22980 44.1839 70.2999
+22982 43.3303 73.4819
+22983 37.8974 77.0181
+22985 395.191 176.371
+22986 393.522 190.227
+22988 390.085 162.713
+22989 375.7 224.23
+22995 259.366 357.751
+22996 223.73 362.435
+22998 -21.9336 102.655
+22999 -28.3336 97.6638
+23001 -44.8834 89.8799
+23002 -50.7141 85.5837
+23005 -60.7778 56.2697
+23008 -65.9688 42.2415
+23010 -66.5424 40.1167
+23011 -67.0799 36.9962
+23013 -67.3001 33.4055
+23014 -67.4957 32.6484
+23016 -67.5712 30.9981
+23017 -67.2629 28.5432
+23019 -66.3983 26.7778
+23020 -65.4753 24.7367
+23022 -64.1789 22.3838
+23023 -63.4728 20.7786
+23025 -60.7328 12.414
+23030 -57.9515 10.0549
+23031 -57.1479 7.4803
+23033 -53.4069 3.53683
+23035 -53.9728 -4.72199
+23036 -52.1748 -5.9891
+23037 -50.7731 -6.82306
+23038 -48.9648 -8.49934
+23041 -47.7019 -9.17361
+23042 -46.4665 -10.6739
+23044 -45.0935 -10.5075
+23045 -44.107 -12.1032
+23047 -43.4158 -11.1391
+23048 -43.0353 -13.1539
+23051 -42.7699 -12.5803
+23052 -42.1787 -13.5728
+23054 -41.6294 -13.8375
+23055 -41.2568 -14.0938
+23057 -290.439 250.263
+23062 -297.09 263.923
+23063 -298.562 260.606
+23065 -299.633 250.574
+23066 -300.793 248.678
+23069 -301.577 248.353
+23070 -305.353 240.577
+23072 -305.971 240.208
+23073 -308.467 237.252
+23076 -309.522 235.973
+23077 -308.17 235.072
+23081 -309.601 234.154
+23082 -307.69 232.974
+23084 -310.036 231.466
+23085 -310.173 229.806
+23086 -311.19 228.58
+23087 -311.67 226.48
+23088 -312.337 224.47
+23089 -313.102 222.753
+23091 -314.491 219.638
+23092 -315.423 219.455
+23093 -316.648 211.099
+23094 -317.449 216.1
+23096 -318.305 213.36
+23097 -319.057 212.771
+23098 -319.745 212.283
+00000 -319.947 211.413
+23099 -320.291 209.397
+23100 -320.67 210.915
+23101 -321.542 211.145
+23102 -322.189 209.441
+23104 -322.937 209.212
+23105 -323.247 207.812
+23107 -323.708 206.321
+23108 -323.338 200.837
+23203 45.1872 61.2712
+23204 394.129 182.738
+23209 376.848 222.488
+23210 91.4164 230.426
+23212 15.2987 98.4375
+23213 9.83596 100.328
+23216 -2.32038 104.881
+23217 -9.40899 104.143
+23219 245.469 359.594
+23220 219.868 376.786
+23223 143.542 397
+23225 130.714 401.776
+23226 125.609 404.129
+23229 -62.92 55.0264
+23230 -66.0427 47.7518
+23232 -67.3102 44.9688
+23233 -67.9107 41.3038
+23235 -68.3111 38.6037
+23236 -68.415 35.9021
+23238 -68.563 33.0559
+23239 -68.2589 29.757
+23241 -67.9479 28.7807
+23242 -67.3735 26.8282
+23244 -66.6344 25.2004
+23245 -66.0266 24.3683
+23278 -38.4621 -15.8849
+23279 -38.1683 -15.9046
+23280 -291.557 248.291
+23281 -295.06 263.191
+23282 -296.571 269.995
+23283 -297.366 266.598
+23286 -310.404 237.349
+23288 -311.872 235.932
+23289 -311.352 235.505
+23291 -305.265 238.91
+23292 -308.408 234.851
+23293 -310.426 224.93
+23294 -311.411 232.103
+23296 -312.035 231.051
+23297 -312.038 229.156
+23298 -312.824 228.12
+23299 -313.127 225.547
+23300 -313.222 222.556
+23301 -314.431 222.262
+23302 -315.148 220.916
+23303 -315.74 219.728
+23304 -316.556 218.823
+00000 -316.638 217.144
+23305 -316.76 217.022
+23306 -317.965 221.19
+23307 -318.97 214.2
+23308 -319.403 208.621
+23309 -320.184 206.064
+23310 -320.648 208.893
+23311 -322.682 215.685
+23312 -318.403 206.408
+23313 -599.997 13.1938
+23314 -59.0671 -27.9948
+23316 -234.741 196.301
+23317 -240.554 192.296
+23425 -66.5951 18.1945
+23426 -63.939 8.33197
+23427 -56.5394 -0.631792
+23428 -54.9475 -2.29846
+23442 -53.4959 -4.3676
+23443 -53.2873 -2.89022
+23449 -50.1898 -6.25351
+23450 -49.0202 -6.93665
+23464 -48.5527 -6.68196
+23465 -47.1345 -8.4623
+23479 -46.0659 -9.21844
+23480 -44.326 -9.73134
+23495 -43.4018 -9.54128
+23496 -41.9692 -10.3322
+23511 -286.402 284.23
+23512 -286.98 278.243
+23527 -290.011 278.777
+23528 -291.986 277.958
+23544 -293.79 277.126
+23545 -295.22 275.579
+23561 -307.265 242.111
+23562 -308.875 240.952
+23573 -309.08 237.911
+23574 -311.794 238.41
+23586 -311.922 233.851
+23588 -313.525 236.201
+23599 -313.652 233.38
+23600 -314.257 233.529
+23611 -310.519 233.267
+23612 -313.229 230.611
+23622 -315.964 226.994
+23623 -315.815 226.584
+23634 -317.842 222.603
+23636 -318.592 222.275
+23647 -319.315 221.166
+23648 -320.237 219.248
+23663 -320.955 218.693
+23664 -321.558 216.198
+23675 -322.119 214.459
+23676 -322.734 212.887
+23686 -323.392 211.242
+23687 -324.446 207.76
+23698 -325.499 205.158
+23699 -331.149 201.771
+23709 -333.366 199.833
+23710 -332.384 197
+23720 -315.361 196.689
+23721 92.2192 241.811
+23732 -332.349 193.469
+23733 90.7276 242.28
Index: branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_may.pos
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_may.pos	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mifae/srcpositions/Mrk421_may.pos	(revision 17960)
@@ -0,0 +1,41 @@
+25791 -84.8946 47.6763
+25794 -122.125 48.4988
+25796 -122.461 49.1271
+25797 -158.079 50.8216
+25801 -84.0898 46.3166
+25802 -84.5659 47.6243
+25803 -83.9559 46.2252
+25806 -85.946 51.5223
+25807 -94.0789 51.5786
+25811 -84.4276 47.8788
+25812 -84.3594 47.8559
+25813 -84.5057 48.0659
+25814 -84.3513 47.8463
+25817 -94.3231 52.0249
+25820 -93.7396 50.8518
+25837 -100.304 51.9021
+25839 -100.155 51.9117
+25840 -133.041 50.619
+25842 -153.155 51.9754
+25843 -164.676 50.8785
+25845 -167.419 52.1466
+25846 -152.706 51.8807
+25847 -156.14 52.1006
+25848 -155.703 52.0932
+25850 -153.024 52.1258
+00000 -150.056 51.9723
+25851 -157.841 51.8809
+25852 -155.837 51.886
+25854 -158.421 51.9508
+25855 -156.322 51.9079
+25858 -103.452 52.2983
+25861 -103.909 52.3202
+25862 -98.145 52.5624
+25863 -99.9381 52.4628
+25865 -101.62 52.8831
+25874 -104.375 52.2092
+25875 -109.995 51.9257
+25876 -83.6544 48.1068
+25877 -108.161 52.0623
+25883 -83.6796 48.0056
+25884 -119.101 66.3904
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/FluxCalcAndUnfold.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/FluxCalcAndUnfold.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/FluxCalcAndUnfold.C	(revision 17960)
@@ -0,0 +1,59 @@
+void Flux6c() 
+{
+
+  TString datafile = "files/AlphaEnergyTheta.LastKeichiRF.27MC.root";
+  TString areafile = "files/area.root";
+
+  TFile* file = new TFile(datafile);
+
+  MHAlphaEnergyTheta hAlpha;
+  hAlpha.Read("MHAlphaEnergyTheta");
+  hAlpha.DrawClone();
+
+  MHEffectiveOnTime hEffTime;
+  hEffTime.Read("MHEffectiveOnTime");
+  hEffTime.DrawClone();
+
+  TFile* file3 = new TFile(areafile);
+  MHMcCollectionArea area;
+  area.Read("MHMcCollectionArea");
+  area.DrawClone();
+
+  //
+  // Read Migration Matrix
+  //
+  TFile* file4 = new TFile("files/EnergyParams.Keichi.Resized.root");
+  MHMcEnergyMigration migm;
+  migm.Read("MHMcEnergyMigration");
+  
+  // ----------------------------------------------------------------------- 
+  //
+  // Calculate # Excess events vs. Energy and Theta
+  //
+  MHExcessEnergyTheta *hex = new MHExcessEnergyTheta;
+  hex->Calc(&hAlpha);
+  hex->Draw();
+  
+  MHFlux* hFluxNUnf = new MHFlux;
+  hFluxNUnf->Calc(hex, &area, &hEffTime);
+  TH1D* fluxNUnf = hFluxNUnf->GetAverageFlux();
+
+  // ----------------------------------------------------------------------- 
+  //
+  // Unfold # Excess events vs. Energy and Theta
+  //
+  
+  TH2D* tobeunfolded = hex->GetHist();
+  TH2D* unfolded = new TH2D(*tobeunfolded);    
+  
+  MUnfoldSpectrum munfs;
+  munfs.SetDistToUnfold(tobeunfolded);
+  munfs.SetMigrationMatrix(migm->GetHist());
+  munfs.SetPriorConstant();
+  //munfs.SetPriorInput(hpr);
+  munfs.SetUnfoldingMethod(2);
+  munfs.Calc();
+  unfolded=munfs.GetUnfDist();
+
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MFindStars.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MFindStars.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MFindStars.cc	(revision 17960)
@@ -0,0 +1,946 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Robert Wagner, 2/2004 <mailto:rwagner@mppmu.mpg.de>
+!   Author(s): Javier López , 4/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFindStars
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFindStars.h"
+
+#include <TMinuit.h>
+#include <TStopwatch.h>
+#include <TTimer.h>
+#include <TString.h>
+#include <TFile.h>
+#include <TTree.h>
+#include <TCanvas.h>
+#include <TH1F.h>
+#include <TF1.h>
+#include <TEllipse.h>
+
+
+#include "MObservatory.h"
+#include "MAstroCamera.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+#include "MReportDrive.h"
+#include "MStarLocalCam.h"
+#include "MStarLocalPos.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MFindStars);
+using namespace std;
+
+const Float_t sqrt2 = sqrt(2.);
+const Float_t sqrt3 = sqrt(3.);
+const UInt_t  lastInnerPixel = 396;
+    
+
+//______________________________________________________________________________
+//
+// The 2D gaussian fucntion used to fit the spot of the star
+//
+static Double_t func(float x,float y,Double_t *par)
+{
+    Double_t value=par[0]*exp(-(x-par[1])*(x-par[1])/(2*par[2]*par[2]))*exp(-(y-par[3])*(y-par[3])/(2*par[4]*par[4]));
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// Function used by Minuit to do the fit
+//
+static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+
+  MParList*      plist = (MParList*)gMinuit->GetObjectFit();
+  MTaskList*     tlist = (MTaskList*)plist->FindObject("MTaskList");
+  MFindStars*    find = (MFindStars*)tlist->FindObject("MFindStars");
+  MStarLocalCam* stars = (MStarLocalCam*)plist->FindObject("MStarLocalCam");
+  MGeomCam*      geom = (MGeomCam*)plist->FindObject("MGeomCam");
+
+  MHCamera& display = (MHCamera&)find->GetDisplay();
+  
+  Float_t innerped = stars->GetInnerPedestalDC();
+  Float_t innerrms = stars->GetInnerPedestalRMSDC();
+  Float_t outerped = stars->GetOuterPedestalDC();
+  Float_t outerrms = stars->GetOuterPedestalRMSDC();
+
+  UInt_t numPixels = geom->GetNumPixels();
+  
+//calculate chisquare
+    Double_t chisq = 0;
+    Double_t delta;
+    Double_t x,y,z;
+    Double_t errorz=0;
+
+    UInt_t usedPx=0;
+    for (UInt_t pixid=1; pixid<numPixels; pixid++) 
+    {
+	if (display.IsUsed(pixid))
+	{
+	    x = (*geom)[pixid].GetX();
+	    y = (*geom)[pixid].GetY();
+            z = display.GetBinContent(pixid+1)-(pixid>lastInnerPixel?outerped:innerped);
+            errorz=(pixid>lastInnerPixel?outerrms:innerrms);
+
+	    if (errorz > 0.0)
+	    {
+              usedPx++;
+              delta  = (z-func(x,y,par))/errorz;
+              chisq += delta*delta;
+	    }
+	    else
+		cerr << " TMinuit::fcn errorz[" << pixid << "] " << errorz << endl;
+	}
+    }
+    f = chisq;
+
+    find->SetChisquare(chisq);
+    find->SetDegreesofFreedom(usedPx);
+}
+
+MFindStars::MFindStars(const char *name, const char *title): 
+  fGeomCam(NULL), fCurr(NULL), fTimeCurr(NULL), fDrive(NULL), fStars(NULL), fNumVar(5)
+{
+  fName  = name  ? name  : "MFindStars";
+  fTitle = title ? title : "Tool to find stars from DC Currents";
+
+  fNumIntegratedEvents=0;
+  fMaxNumIntegratedEvents = 10;
+  fRingInterest = 125.; //[mm] ~ 0.4 deg
+  fDCTailCut = 4;
+  
+  fPixelsUsed.Set(577);
+  fPixelsUsed.Reset((Char_t)kTRUE);
+  
+  //Fitting(Minuit) initialitation
+  const Float_t pixelSize = 31.5; //[mm]
+  fMinuitPrintOutLevel = -1;
+  
+  fVname = new TString[fNumVar];
+  fVinit.Set(fNumVar); 
+  fStep.Set(fNumVar); 
+  fLimlo.Set(fNumVar); 
+  fLimup.Set(fNumVar); 
+  fFix.Set(fNumVar);
+
+  fVname[0] = "max";
+  fVinit[0] = 10.*fMaxNumIntegratedEvents;
+  fStep[0]  = fVinit[0]/sqrt2;
+  fLimlo[0] = fMinDCForStars;
+  fLimup[0] = 30.*fMaxNumIntegratedEvents;
+  fFix[0]   = 0;
+
+  fVname[1] = "meanx";
+  fVinit[1] = 0.;
+  fStep[1]  = fVinit[1]/sqrt2;
+  fLimlo[1] = -600.;
+  fLimup[1] = 600.;
+  fFix[1]   = 0;
+
+  fVname[2] = "sigmaminor";
+  fVinit[2] = pixelSize;
+  fStep[2]  = fVinit[2]/sqrt2;
+  fLimlo[2] = pixelSize/(2*sqrt3);
+  fLimup[2] = 500.;
+  fFix[2]   = 0;
+
+  fVname[3] = "meany";
+  fVinit[3] = 0.;
+  fStep[3]  = fVinit[3]/sqrt2;
+  fLimlo[3] = -600.;
+  fLimup[3] = 600.;
+  fFix[3]   = 0;
+
+  fVname[4] = "sigmamajor";
+  fVinit[4] = pixelSize;
+  fStep[4]  = fVinit[4]/sqrt2;
+  fLimlo[4] = pixelSize/(2*sqrt3);
+  fLimup[4] = 500.;
+  fFix[4]   = 0;
+
+  fObjectFit  = NULL;
+  //  fMethod     = "SIMPLEX";
+  fMethod     = "MIGRAD";
+  //  fMethod     = "MINIMIZE";
+  fNulloutput = kFALSE;
+
+  // Set output level
+  //  fLog->SetOutputLevel(3); // No dbg messages
+
+  fGeometryFile="";
+  fBSCFile="";
+}
+
+Int_t MFindStars::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Initialize camera display with the MGeomCam information
+    fDisplay.SetGeometry(*fGeomCam,"FindStarsDisplay","FindStarsDisplay");
+    fDisplay.SetUsed(fPixelsUsed);
+
+    fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+
+    if (!fTimeCurr)
+    {
+      *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+
+    if (!fDrive)
+      {
+
+        *fLog << warn << AddSerialNumber("MReportDrive") << " not found ... ignored." << endl;
+
+      }
+    else
+      {
+	
+	MObservatory magic1;
+
+	MMcConfigRunHeader *config=0;
+	MGeomCam           *geom=0;
+
+	TFile file(fGeometryFile);
+	TTree *tree = (TTree*)file.Get("RunHeaders");
+	tree->SetBranchAddress("MMcConfigRunHeader", &config);
+	if (tree->GetBranch("MGeomCam")) tree->SetBranchAddress("MGeomCam", &geom);
+	tree->GetEntry(0);
+	
+	fAstro.SetMirrors(*config->GetMirrors());
+	fAstro.SetGeom(*geom);	
+	fAstro.ReadBSC(fBSCFile);
+	
+	fAstro.SetObservatory(magic1);
+	
+      }
+    
+
+    fStars = (MStarLocalCam*)pList->FindCreateObj(AddSerialNumber("MStarLocalCam"));
+    if (!fStars)
+    {
+      *fLog << err << AddSerialNumber("MStarLocalCam") << " cannot be created ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fMinDCForStars = 1.*fMaxNumIntegratedEvents; //[uA]
+
+    // Initialize the TMinuit object
+
+    TMinuit *gMinuit = new TMinuit(fNumVar);  //initialize TMinuit with a maximum of params
+    gMinuit->SetFCN(fcn);
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+    arglist[0] = fMinuitPrintOutLevel;
+    gMinuit->mnexcm("SET PRI", arglist ,1,ierflg);
+
+    // Set MParList object pointer to allow mimuit to access internally
+    gMinuit->SetObjectFit(pList);
+
+    return kTRUE;
+}
+
+Int_t MFindStars::Process()
+{
+
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+
+  if (fNumIntegratedEvents >= fMaxNumIntegratedEvents) {
+
+    //Fist delete the previous stars in the list
+    fStars->GetList()->Delete();
+
+    if (fDrive) {
+
+      //If drive information is provided we take RaDec info
+      //from the drive and let the star list fill by the astrocamera.
+
+      //FIXME: rwagner: Doesn't work as expected
+      //FIXME: rwagner: For the time being set manually.
+      //fAstro.SetRaDec(fDrive->GetRa(), fDrive->GetDec());              
+
+      fAstro.SetTime(*fTimeCurr);
+      fAstro.SetGuiActive();
+      fAstro.FillStarList(fStars->GetList());      
+
+      cout << "Number of Stars added by astrocamera is " <<fStars->GetList()->GetSize() << endl;
+      
+      MStarLocalPos* starpos;
+      TIter Next(fStars->GetList());
+      while ((starpos=(MStarLocalPos*)Next())) {
+	starpos->SetCalcValues(40,40,starpos->GetXExp(),starpos->GetYExp(),fRingInterest/2,fRingInterest/2);
+	starpos->SetFitValues (40,40,starpos->GetXExp(),starpos->GetYExp(),fRingInterest/2,fRingInterest/2,0.,1);
+      }
+
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+          
+      DCPedestalCalc();
+
+    } 
+    else 
+    {
+      
+      cout << "No drive information available: Will not use a star catalog to identify stars."<< endl;
+      
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+          
+      if (DCPedestalCalc()) {
+
+	Float_t innermin = fStars->GetInnerPedestalDC()+fDCTailCut*fStars->GetInnerPedestalRMSDC();
+	Float_t outermin = fStars->GetOuterPedestalDC()+fDCTailCut*fStars->GetOuterPedestalRMSDC();
+	fMinDCForStars = innermin>outermin?innermin:outermin;
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars = " << fMinDCForStars << endl;
+              
+	// Find the star candidates searching the most brights pairs of pixels
+	Float_t maxPixelDC;
+	MGeomPix maxPixel;
+	
+	while(FindPixelWithMaxDC(maxPixelDC, maxPixel)) {
+	  
+	  MStarLocalPos *starpos = new MStarLocalPos;
+	  starpos->SetExpValues(maxPixelDC,maxPixel.GetX(),maxPixel.GetY());
+	  starpos->SetCalcValues(maxPixelDC,maxPixelDC,maxPixel.GetX(),maxPixel.GetY(),fRingInterest/2,fRingInterest/2);
+	  starpos->SetFitValues(maxPixelDC,maxPixelDC,maxPixel.GetX(),maxPixel.GetY(),fRingInterest/2,fRingInterest/2,0.,1);
+	  fStars->GetList()->Add(starpos);
+	  
+	  ShadowStar(starpos);
+	}	
+	fDisplay.SetUsed(origPixelsUsed);
+      }      
+    }
+
+    //Show the stars found
+    //fStars->Print("namepos");
+   
+    //loop to extract position of stars on the camera
+    if (fStars->GetList()->GetSize() == 0) {
+      *fLog << err << GetName() << "No stars candidates in the camera." << endl;
+      return kCONTINUE;
+    } else
+      *fLog << inf << GetName() << " found " << fStars->GetList()->GetSize() 
+	    << " stars candidates in the camera." << endl;
+    
+    for (UInt_t pix=1; pix<numPixels; pix++) {
+      if (fDisplay.IsUsed(pix))
+	origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+	origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+
+    TIter Next(fStars->GetList());
+    MStarLocalPos* star;
+    while ((star=(MStarLocalPos*)Next())) {
+       FindStar(star);
+       ShadowStar(star);
+    }
+
+    //Show the stars found: Here it is interesting to see what FindStars
+    //made out of the positions we gave to it.
+    fStars->Print("namepos");
+
+    
+    //After finding stars reset all variables
+    fDisplay.Reset();
+    fStars->GetDisplay().Reset(); //FIXME: Put this display just in the container
+    fDisplay.SetUsed(origPixelsUsed);
+    fNumIntegratedEvents=0;
+  }
+
+  for (UInt_t pix=1; pix<numPixels; pix++) {
+    if (fDisplay.IsUsed(pix))
+      origPixelsUsed[pix]=(Char_t)kTRUE;
+    else
+      origPixelsUsed[pix]=(Char_t)kFALSE;
+    
+  }
+  
+  fDisplay.AddCamContent(*fCurr);
+  fNumIntegratedEvents++;
+  fDisplay.SetUsed(origPixelsUsed);
+  
+  return kTRUE;
+}
+
+Int_t MFindStars::PostProcess()
+{
+  return kTRUE;
+}
+
+void MFindStars::SetBlindPixels(TArrayS blindpixels)
+{
+    Int_t npix = blindpixels.GetSize();
+
+    for (Int_t idx=0; idx<npix; idx++)
+      {
+	fPixelsUsed[blindpixels[idx]]=(Char_t)kFALSE;
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "MFindStars::SetBlindPixels fDisplay.IsUsed(" <<blindpixels[idx]  << ") kFALSE" << endl;
+      }
+    
+    fDisplay.SetUsed(fPixelsUsed);
+}
+
+Bool_t MFindStars::DCPedestalCalc()
+{
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+   UInt_t numPixels = fGeomCam->GetNumPixels();
+   Float_t ped;
+   Float_t rms;
+
+   TH1F **dchist = new TH1F*[2];
+   for (UInt_t i=0; i<2; i++)
+      dchist[i] = new TH1F("","",26,0.4*fMaxNumIntegratedEvents,3.*fMaxNumIntegratedEvents);
+   
+   for (UInt_t pix=1; pix<=lastInnerPixel; pix++)
+       dchist[0]->Fill(fDisplay.GetBinContent(pix+1));
+   for (UInt_t pix=lastInnerPixel+1; pix<numPixels; pix++)
+       dchist[1]->Fill(fDisplay.GetBinContent(pix+1));
+
+   // inner/outer pixels
+   for (UInt_t i=0; i<2; i++)
+    {
+      Float_t nummaxprobdc = dchist[i]->GetBinContent(dchist[i]->GetMaximumBin());
+      Float_t maxprobdc = dchist[i]->GetBinCenter(dchist[i]->GetMaximumBin());
+      UInt_t bin = dchist[i]->GetMaximumBin();
+      do
+        {
+          bin++;
+        }
+      while(dchist[i]->GetBinContent(bin)/nummaxprobdc > 0.5);
+      Float_t halfmaxprobdc = dchist[i]->GetBinCenter(bin);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc[high] " << maxprobdc << "[" << nummaxprobdc << "] ";
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " halfmaxprobdc[high] " << halfmaxprobdc << "[" << dchist[i]->GetBinContent(bin) << "]" << endl;
+      
+      Float_t rmsguess = TMath::Abs(maxprobdc-halfmaxprobdc);
+      Float_t min = maxprobdc-3*rmsguess;
+      min = (min<0.?0.:min);
+      Float_t max = maxprobdc+3*rmsguess;
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+      
+      TF1 func("func","gaus",min,max);
+      func.SetParameters(nummaxprobdc, maxprobdc, rmsguess);
+      
+      dchist[i]->Fit("func","QR0");
+      
+      UInt_t aproxnumdegrees = 6*(bin-dchist[i]->GetMaximumBin());
+      Float_t chiq = func.GetChisquare();
+      ped = func.GetParameter(1);
+      rms = func.GetParameter(2);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+      
+      Int_t numsigmas = 5;
+      Axis_t minbin = ped-numsigmas*rms/dchist[i]->GetBinWidth(1);
+      minbin=minbin<1?1:minbin;
+      Axis_t maxbin = ped+numsigmas*rms/dchist[i]->GetBinWidth(1);
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " Number of pixels with dc under " << numsigmas << " sigmas = " << dchist[i]->Integral((int)minbin,(int)maxbin) << endl;
+      
+      //Check results from the fit are consistent
+      if (ped < 0. || rms < 0.)
+        {
+          *fLog << dbg << "dchist[i]->GetEntries()" << dchist[i]->GetEntries();
+//            TCanvas *c1 = new TCanvas("c2","c2",500,800);
+//            dchist[i]->Draw();
+//            c1->Print("dchist.ps");
+//            delete c1;
+//            exit(1);
+        }
+      else if (TMath::Abs(ped-maxprobdc) > rmsguess || rms > rmsguess)
+        {
+          *fLog << warn << GetName() << " Pedestal DC fit give non consistent results for " << (i==0?"Inner":"Outer") << "pixels." << endl;
+          *fLog << warn << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+          *fLog << warn << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+          ped = maxprobdc;
+          rms = rmsguess/1.175; // FWHM=2.35*rms
+        }
+   
+      if (i == 0)
+        {
+          fStars->SetInnerPedestalDC(ped);
+          fStars->SetInnerPedestalRMSDC(rms);
+        }
+      else
+        {
+          fStars->SetOuterPedestalDC(ped);
+          fStars->SetOuterPedestalRMSDC(rms);
+        }
+
+      
+
+    }
+   
+
+   for (UInt_t i=0; i<2; i++)
+      delete dchist[i];
+   delete [] dchist;
+
+   //=================================================================
+
+   // reset gMinuit to the MINUIT object for optimizing the supercuts 
+   gMinuit = savePointer;
+   //-------------------------------------------
+   
+   if (fStars->GetInnerPedestalDC() < 0. ||  fStars->GetInnerPedestalRMSDC() < 0. || fStars->GetOuterPedestalDC() < 0. ||  fStars->GetOuterPedestalRMSDC() < 0.)
+     return kFALSE;
+  
+   return kTRUE;
+}
+    
+Bool_t MFindStars::FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Find the two close pixels with the maximun dc
+    UInt_t maxPixIdx[2];
+
+    maxDC = 0;
+
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	if(fDisplay.IsUsed(pix))
+	{
+	    Float_t dc[2];
+	    dc[0] = fDisplay.GetBinContent(pix+1);
+	    if (dc[0] < fMinDCForStars)
+		continue;
+
+	    MGeomPix &g = (*fGeomCam)[pix];
+	    Int_t numNextNeighbors = g.GetNumNeighbors();
+	    
+	    Float_t dcsum;
+	    for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+	    {
+              UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+              if(fDisplay.IsUsed(swneighbor))
+                {
+                  dc[1] = fDisplay.GetBinContent(swneighbor+1);
+                  if (dc[1] < fMinDCForStars)
+                    continue;
+                  
+                  dcsum = dc[0] + dc[1];
+                  
+                  if(dcsum > maxDC*2)
+                    {
+                      if(dc[0]>=dc[1])
+                        {
+                          maxPixIdx[0] = pix;
+                          maxPixIdx[1] = swneighbor;
+                          maxDC = dc[0];
+                        }
+                      else
+                        {
+                          maxPixIdx[1] = pix;
+                          maxPixIdx[0] = swneighbor;
+                          maxDC = dc[1];
+                        }
+                    }	
+                }
+            }
+        }
+    }
+
+    if (maxDC == 0)
+      {
+        *fLog << warn << " No found pixels with maximum dc" << endl;
+	return kFALSE;
+      }
+    
+    maxPix = (*fGeomCam)[maxPixIdx[0]];
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Star candidate maxDC(" << setw(3) << maxDC << " uA) x position(" << setw(3) << maxPix.GetX() <<  " mm) x position(" << setw(3) << maxPix.GetY() << " mm) swnumber(" << maxPixIdx[0] << ")" << endl;
+
+    return kTRUE;
+}
+
+Bool_t MFindStars::FindStar(MStarLocalPos* star)
+{    
+ 
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  Float_t innerped = fStars->GetInnerPedestalDC();
+  Float_t outerped = fStars->GetOuterPedestalDC();
+
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+  
+  for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+      if (fDisplay.IsUsed(pix))
+        origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+        origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+  
+  Float_t expX = star->GetXExp();
+  Float_t expY = star->GetYExp();
+  
+  Float_t max=0;
+  UInt_t  pixmax=0;
+  Float_t meanX=0;
+  Float_t meanY=0;
+  Float_t meanSqX=0;
+  Float_t meanSqY=0;
+  Float_t sumCharge=0;
+  UInt_t usedInnerPx=0;	
+  UInt_t usedOuterPx=0;	
+
+  const Float_t meanPresition = 3.; //[mm]
+  const UInt_t maxNumIterations = 10;
+  UInt_t numIterations = 0;
+
+  do
+    {
+
+      //rwagner: Need to find px with highest dc and need to assume it is
+      // somewhere near the center of the star
+      //after that we need to REDEFINE our roi! because expected pos could be
+      // quite off that px!
+      
+      // 1.) Initial roi around expected position
+
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // 2.) Find px with highest dc in that region
+
+      for(UInt_t pix=0; pix<numPixels; pix++)	
+	if(fDisplay.IsUsed(pix))
+	  {
+	    Float_t charge  = fDisplay.GetBinContent(pix+1);	      
+	    if (charge>max)
+	      {
+		max=charge;
+		pixmax=pix;
+	      }
+	    
+	  }         
+
+      // 3.) make it new center
+
+      expX = (*fGeomCam)[pixmax].GetX();
+      expY = (*fGeomCam)[pixmax].GetY();
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	fPixelsUsed[pix]=(Char_t)kTRUE;       
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // First define a area of interest around the expected position of the star
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+  
+      fDisplay.SetUsed(fPixelsUsed);
+    
+      // determine mean x and mean y
+      usedInnerPx=0;	
+      usedOuterPx=0;	
+      for(UInt_t pix=0; pix<numPixels; pix++)
+	{
+	  if(fDisplay.IsUsed(pix))
+	    {
+	      pix>lastInnerPixel?usedOuterPx++:usedInnerPx++;
+	      
+	      Float_t charge  = fDisplay.GetBinContent(pix+1);
+	      Float_t pixXpos = (*fGeomCam)[pix].GetX();
+	      Float_t pixYpos = (*fGeomCam)[pix].GetY();
+	      
+	      if (charge>max)
+		{
+		  max=charge;
+		  pixmax=pix;
+		}
+	      
+	      meanX     += charge*pixXpos;
+	      meanY     += charge*pixYpos;
+	      meanSqX   += charge*pixXpos*pixXpos;
+	      meanSqY   += charge*pixYpos*pixYpos;
+	      sumCharge += charge;
+	    }
+	} 
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " usedInnerPx " << usedInnerPx << " usedOuterPx " << usedOuterPx << endl;
+      
+      meanX   /= sumCharge;
+      meanY   /= sumCharge;
+      meanSqX /= sumCharge;
+      meanSqY /= sumCharge;
+      
+      expX = meanX;
+      expY = meanY;
+      
+      if (++numIterations >  maxNumIterations)
+	{
+	  *fLog << warn << GetName() << "Mean calculation not converge after " << maxNumIterations << " iterations" << endl;
+	  break;
+	}
+        
+    } while(TMath::Abs(meanX-expX) > meanPresition || TMath::Abs(meanY-expY) > meanPresition);
+  
+  Float_t rmsX = (meanSqX - meanX*meanX) - fRingInterest*fRingInterest/12;
+  Float_t rmsY = (meanSqY - meanY*meanY) - fRingInterest*fRingInterest/12;
+  
+  if ( rmsX > 0)
+    rmsX =  TMath::Sqrt(rmsX);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsX² " << rmsX << endl;
+      *fLog << warn << " meanSqX " << meanSqX << " meanX " << meanX << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge << endl;
+      rmsX = 0.;
+    }
+  
+  if ( rmsY > 0)
+    rmsY =  TMath::Sqrt(rmsY);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsY² " << rmsY << endl;
+      *fLog << warn << " meanSqY " << meanSqY << " meanY " << meanY << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge<< endl;
+      rmsY = 0.;
+    }
+  
+  // Substrack pedestal DC
+  sumCharge-= (usedInnerPx*innerped+usedOuterPx*outerped)/(usedInnerPx+usedOuterPx);
+  max-=pixmax>lastInnerPixel?outerped:innerped;
+  
+  
+  star->SetCalcValues(sumCharge,max,meanX,meanY,rmsX,rmsY);
+  
+  if (rmsX <= 0. || rmsY <= 0.)
+    return kFALSE;
+    
+    
+// fit the star spot using TMinuit
+
+    
+    for (UInt_t pix=1; pix<numPixels; pix++)
+      if (fDisplay.IsUsed(pix))
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "[fit the star spot] fDisplay.IsUsed(" << pix << ") kTRUE" << endl;
+  
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars " << fMinDCForStars << " pixmax>lastInnerPixel?outerped:innerped " << (pixmax>lastInnerPixel?outerped:innerped) << " fMaxNumIntegratedEvents " << fMaxNumIntegratedEvents << endl;
+
+  //Initialate variables for fit
+    fVinit[0] = max;
+    fLimlo[0] = fMinDCForStars-(pixmax>lastInnerPixel?outerped:innerped);
+    fLimup[0] = 30*fMaxNumIntegratedEvents-(pixmax>lastInnerPixel?outerped:innerped);
+    fVinit[1] = meanX;
+    fVinit[2] = rmsX;
+    fVinit[3] = meanY;
+    fVinit[4] = rmsY;
+    //Init steps
+    for(Int_t i=0; i<fNumVar; i++)
+      {
+	if (fVinit[i] != 0)
+	  fStep[i] = TMath::Abs(fVinit[i]/sqrt2);
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fVinit[" << i << "] " << fVinit[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fStep[" << i << "] " << fStep[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimlo[" << i << "] " << fLimlo[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimup[" << i << "] " << fLimup[i] << endl;
+      }
+    //
+
+    // -------------------------------------------
+    // call MINUIT
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    for (Int_t i=0; i<fNumVar; i++)
+      gMinuit->mnparm(i, fVname[i], fVinit[i], fStep[i], fLimlo[i], fLimup[i], ierflg);
+
+    TStopwatch clock;
+    clock.Start();
+
+// Now ready for minimization step
+    arglist[0] = 500;
+    arglist[1] = 1.;
+    gMinuit->mnexcm(fMethod, arglist ,2,ierflg);
+
+    clock.Stop();
+
+    if(fMinuitPrintOutLevel>=0)
+      {
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Time spent for the minimization in MINUIT :   " << endl;;
+	clock.Print();
+      }
+
+    Double_t integratedCharge;
+    Double_t maxFit, maxFitError;
+    Double_t meanXFit, meanXFitError;
+    Double_t sigmaMinorAxis, sigmaMinorAxisError;
+    Double_t meanYFit, meanYFitError;
+    Double_t sigmaMajorAxis, sigmaMajorAxisError;
+    Float_t chisquare = GetChisquare();
+    Int_t   dregrees  = GetDegreesofFreedom()-fNumVar;
+
+    if (!ierflg)
+      {
+        gMinuit->GetParameter(0,maxFit, maxFitError);
+        gMinuit->GetParameter(1,meanXFit,meanXFitError);
+        gMinuit->GetParameter(2,sigmaMinorAxis,sigmaMinorAxisError);
+        gMinuit->GetParameter(3,meanYFit,meanYFitError);
+        gMinuit->GetParameter(4,sigmaMajorAxis,sigmaMajorAxisError);
+        
+        //FIXME: Do the integral properlly
+        integratedCharge = 0.;
+
+        
+      }
+    else
+      {
+        maxFit = 0.;
+        meanXFit = 0.;
+        sigmaMinorAxis = 0.;
+        meanYFit = 0.;
+        sigmaMajorAxis = 0.;
+        integratedCharge = 0.;
+
+	*fLog << err << "TMinuit::Call error " << ierflg << endl;
+      }
+
+    //rwagner: get error matrix
+    Double_t matrix[2][2];
+    gMinuit->mnemat(&matrix[0][0],2);
+
+    star->SetFitValues(integratedCharge,maxFit,meanXFit,meanYFit,sigmaMinorAxis,sigmaMajorAxis,chisquare,dregrees,
+  		       matrix[0][0],matrix[1][0],matrix[1][1]);
+    
+    // reset the display to the starting values
+    fDisplay.SetUsed(origPixelsUsed);
+
+    if (ierflg)
+      return kCONTINUE;
+    return kTRUE;
+}
+
+Bool_t MFindStars::ShadowStar(MStarLocalPos* star)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Define an area around the star which will be set unused.
+    UInt_t shadowPx=0;	
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	Float_t pixXpos  = (*fGeomCam)[pix].GetX();
+	Float_t pixYpos  = (*fGeomCam)[pix].GetY();
+        Float_t starXpos = star->GetMeanX();
+        Float_t starYpos = star->GetMeanY();
+        
+	Float_t starSize = 3*star->GetSigmaMajorAxis();
+        
+	Float_t dist = sqrt((pixXpos-starXpos)*(pixXpos-starXpos)+
+			    (pixYpos-starYpos)*(pixYpos-starYpos));
+
+        if (dist > starSize && fDisplay.IsUsed(pix))
+	  fPixelsUsed[pix]=(Char_t)kTRUE;
+        else
+          {
+            fPixelsUsed[pix]=(Char_t)kFALSE;
+            shadowPx++;
+          }
+    }
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << " shadowPx " << shadowPx << endl;
+
+    fDisplay.SetUsed(fPixelsUsed);
+
+    return kTRUE;
+}
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MFindStars.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MFindStars.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MFindStars.h	(revision 17960)
@@ -0,0 +1,116 @@
+#ifndef MARS_MFindStars
+#define MARS_MFindStars
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MAstroCamera
+#include "MAstroCamera.h"
+#endif
+
+class MGeomCam;
+class MGeomPix;
+class MCameraDC;
+class MTime;
+class MReportDrive;
+class MStarLocalCam;
+class MStarLocalPos;
+
+class MFindStars : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MCameraDC     *fCurr;
+    MTime         *fTimeCurr;
+    MReportDrive  *fDrive;
+    MStarLocalCam *fStars;
+
+    MAstroCamera fAstro;
+    TArrayC      fPixelsUsed;
+    MHCamera     fDisplay;
+
+    UInt_t fMaxNumIntegratedEvents;
+    UInt_t fNumIntegratedEvents;
+
+    Float_t fRingInterest; //[mm]
+    Float_t fMinDCForStars; //[uA]
+
+    Float_t fDCTailCut;
+
+    //Fitting(Minuit) variables
+    const Int_t fNumVar;
+    Float_t fTempChisquare;
+    Int_t fTempDegreesofFreedom;
+    Int_t fMinuitPrintOutLevel;
+    
+    TString *fVname;
+    TArrayD fVinit; 
+    TArrayD fStep; 
+    TArrayD fLimlo; 
+    TArrayD fLimup; 
+    TArrayI fFix;
+    TObject *fObjectFit;
+    TString fMethod;
+    Bool_t fNulloutput;
+    
+    Bool_t DCPedestalCalc();
+    Bool_t FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix);
+    Bool_t FindStar(MStarLocalPos* star);
+    Bool_t ShadowStar(MStarLocalPos* star);
+
+    TString fGeometryFile;
+    TString fBSCFile;
+
+  public:
+    
+    MFindStars(const char *name=NULL, const char *title=NULL);
+    
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // setters
+    void SetNumIntegratedEvents(UInt_t max) {fMaxNumIntegratedEvents=max;}
+    void SetRingInterest(Float_t ring) {fRingInterest=ring;}
+    void SetBlindPixels(TArrayS blindpixels);
+    void SetMinuitPrintOutLevel(Int_t level) {fMinuitPrintOutLevel=level;}
+    void SetDCTailCut(Float_t cut) {fDCTailCut=cut;}
+
+    void SetChisquare(Float_t chi) {fTempChisquare=chi;}
+    void SetDegreesofFreedom(Int_t free) {fTempDegreesofFreedom=free;}
+
+    void SetGeometryFile(TString f) {fGeometryFile=f;}
+    void SetBSCFile(TString f) {fBSCFile=f;}
+    void SetRaDec(Double_t ra, Double_t dec) {fAstro.SetRaDec(ra,dec);}
+    void SetRaDec(TVector3 &v) { fAstro.SetRaDec(v); }
+    void SetLimMag(Double_t mag) { fAstro.SetLimMag(mag); } 
+    void SetRadiusFOV(Double_t deg) { fAstro.SetRadiusFOV(deg); }
+
+
+    //Getters
+    MHCamera& GetDisplay() { return fDisplay; }
+    
+    Float_t GetChisquare() {return fTempChisquare;}
+    Int_t GetDegreesofFreedom() {return fTempDegreesofFreedom;}
+    UInt_t GetNumIntegratedEvents() {return fMaxNumIntegratedEvents;}
+    Float_t GetRingInterest() {return fRingInterest;}
+    
+  ClassDef(MFindStars, 0) // Tool to find stars from DC Currents
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MPointingPosCalcWA.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MPointingPosCalcWA.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MPointingPosCalcWA.cc	(revision 17960)
@@ -0,0 +1,181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointingPosCalc
+//
+// Currently:
+//
+//  * MC files:  Copy the simulated telescope position (Telescope Theta,
+//               Telescope Phi in MMcEvt) to MPointingPosition
+//
+//  * Real Data: Copy the nominal poiting position (Nominal Zd, Nominal Az
+//               in MReportDrive) to MPointingPosition
+//
+// Future: Interpolate the pointing position for each event between two
+//         consecutive drive reports.
+//
+// Input Container:
+//   MRawRunHeader
+//   [MMcEvt, MReportDrive]
+//
+// Output Container:
+//   MPointingPosition
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPointingPosCalcWA.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MVector3.h"
+
+#include "MPointingPos.h"
+#include "MAstro.h"
+#include "MObservatory.h"
+#include "MAstroSky2Local.h"
+#include "MRawRunHeader.h"
+#include "MReportDrive.h"
+#include "MMcEvt.hxx"
+
+ClassImp(MPointingPosCalcWA);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Search for MRawRunHeader. Get the run type from there. Depending on
+// the run type search either for MMcEvt or MReportDrive.
+//
+Bool_t MPointingPosCalcWA::ReInit(MParList *plist)
+{
+    fObs = (MObservatory*)plist->FindCreateObj("MObservatory");
+    if (!fObs)
+    {
+       *fLog << err << "MObservatory not found... aborting." << endl;
+        return kFALSE; 
+    }
+
+    fRunHeader = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunType = fRunHeader->GetRunType();
+
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+        fReport = (MReportDrive*)plist->FindObject("MReportDrive");
+        if (!fReport)
+        {
+            *fLog << err << "MReportDrive not found... will set Az and Zd to a fixed value." << endl;
+            return kTRUE;
+        }
+        return kTRUE;
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+        if (!fMcEvt)
+        {
+            *fLog << err << "MMcEvt not found... aborting." << endl;
+            return kFALSE;
+        }
+        return kTRUE;
+
+    case MRawRunHeader::kRTPedestal:
+        *fLog << err << "Cannot work in a pedestal Run!... aborting." << endl;
+        return kFALSE;
+
+    case MRawRunHeader::kRTCalibration:
+        *fLog << err << "Cannot work in a calibration Run!... aborting." << endl;
+        return kFALSE;
+
+    default:
+        *fLog << err << "Run Type " << fRunType << " unknown!... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Search for 'MPointingPos'. Create if not found.
+//
+Int_t MPointingPosCalcWA::PreProcess(MParList *plist)
+{
+    fPosition = (MPointingPos*)plist->FindCreateObj("MPointingPos");
+    return fPosition ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  See class description.
+//
+Int_t MPointingPosCalcWA::Process()
+{
+
+    const char plus = '+';
+    Char_t Rsgn;
+    UShort_t Rhour, Rmin, Rsec;
+    Double_t ra;
+
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+     if(!fReport)
+     {
+        MTime start = fRunHeader->GetRunStart();
+
+        MVector3 v;
+        v.SetRaDec(fRa,fDec);
+        v *= MAstroSky2Local(start,*fObs);
+        Double_t ZA = v.Theta()*180./acos(-1.);
+        Double_t Az = v.Phi()*180./acos(-1.);
+//        cout << " Za = " << ZA << " v.Theta() " << v.Theta() << " Az " << Az << " v.Phi " << v.Phi() << endl;
+        fPosition->SetLocalPosition(ZA, Az);
+        MAstro::Rad2Hms(fRa, Rsgn, Rhour, Rmin, Rsec);
+        if (Rsgn==plus) ra = Rhour + Rmin/60. + Rsec/3600.;
+        else ra = - (Rhour + Rmin/60. + Rsec/3600.);
+        fPosition->SetSkyPosition(ra, TMath::RadToDeg()*fDec);
+        return kTRUE;
+     }
+     else 
+     {
+        fPosition->SetLocalPosition(fReport->GetNominalZd(), fReport->GetNominalAz());
+        fPosition->SetSkyPosition(fReport->GetRa(), fReport->GetDec());
+        return kTRUE;
+     }
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fPosition->SetLocalPosition(fMcEvt->GetTelescopeTheta()*TMath::RadToDeg(), fMcEvt->GetTelescopePhi()*TMath::RadToDeg());
+        return kTRUE;
+    }
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MPointingPosCalcWA.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MPointingPosCalcWA.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MPointingPosCalcWA.h	(revision 17960)
@@ -0,0 +1,44 @@
+#ifndef MARS_MPointingPositionCalcWA
+#define MARS_MPointingPositionCalcWA
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MReportDrive;
+class MPointingPos;
+class MRawRunHeader;
+class MObservatory;
+
+class MPointingPosCalcWA : public MTask
+{
+private:
+    MMcEvt        *fMcEvt;    //! MMcEvt to get simulated poiting position from
+    MReportDrive  *fReport;   //! MReportDrive to get real poiting position from
+    MPointingPos  *fPosition; //! Output container to store pointing position
+    MObservatory  *fObs;
+    MRawRunHeader *fRunHeader;
+    Double_t fRa;
+    Double_t fDec;
+    
+
+    UShort_t fRunType;            //! Run Type to decide where to get pointing position from
+
+    Bool_t ReInit(MParList *plist);
+    Int_t  PreProcess(MParList *plist);
+    Int_t  Process();
+
+public:
+    MPointingPosCalcWA()
+    {
+        fName  = "MPointingPosCalcWA";
+        fTitle = "Task calculating the pointing position";
+    }
+
+    void SetRaDec(Double_t ra, Double_t dec)  {fRa = ra; fDec = dec;}
+
+    ClassDef(MPointingPosCalcWA, 0) //Task calculating the pointing position
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MSkyPlot.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MSkyPlot.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MSkyPlot.cc	(revision 17960)
@@ -0,0 +1,1346 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniel Mazin, 8/2004 <mailto:mazin@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSkyPlot
+//
+// Create a false source plot. For the Binning in x,y the object MBinning
+// "BinningFalseSource" is taken from the paremeter list.
+//
+// The binning in alpha is currently fixed as 18bins from 0 to 90deg.
+//
+// If MTime, MObservatory and MPointingPos is available in the paremeter
+// list each image is derotated.
+//
+// MSkyPlot fills a 3D histogram with alpha distribution for
+// each (derotated) x and y position.
+//
+// Only a radius of 1.2deg around the camera center is taken into account.
+//
+// The displayed histogram is the projection of alpha<fAlphaCut into
+// the x,y plain and the projection of alpha>90-fAlphaCut
+//
+// By using the context menu (find it in a small region between the single
+// pads) you can change the AlphaCut 'online'
+//
+// Each Z-Projection (Alpha-histogram) is scaled such, that the number
+// of entries fits the maximum number of entries in all Z-Projections.
+// This should correct for the different acceptance in the center
+// and at the border of the camera. This, however, produces more noise
+// at the border.
+//
+// Here is a slightly simplified version of the algorithm:
+// ------------------------------------------------------
+//    MHillas hil; // Taken as second argument in MFillH
+//
+//    MSrcPosCam src;
+//    MHillasSrc hsrc;
+//    hsrc.SetSrcPos(&src);
+//
+//    for (int ix=0; ix<nx; ix++)
+//        for (int iy=0; iy<ny; iy++)
+//        {
+//            TVector2 v(cx[ix], cy[iy]); //cx center of x-bin ix
+//            if (rho!=0)                 //cy center of y-bin iy
+//                v=v.Rotate(rho);         //image rotation angle
+//
+//            src.SetXY(v);               //source position in the camera
+//
+//            if (!hsrc.Calc(hil))        //calc source dependant hillas
+//                return;
+//
+//            //fill absolute alpha into histogram
+//            const Double_t alpha = hsrc.GetAlpha();
+//            fHist.Fill(cx[ix], cy[iy], TMath::Abs(alpha), w);
+//        }
+//    }
+//
+// Use MHFalse Source like this:
+// -----------------------------
+//    MFillH fill("MSkyPlot", "MHillas");
+// or
+//    MSkyPlot hist;
+//    hist.SetAlphaCut(12.5);  // The default value
+//    hist.SetBgmean(55);      // The default value
+//    MFillH fill(&hist, "MHillas");
+//
+// To be implemented:
+// ------------------
+//  - a switch to use alpha or |alpha|
+//  - taking the binning for alpha from the parlist (binning is
+//    currently fixed)
+//  - a possibility to change the fit-function (eg using a different TF1)
+//  - a possibility to change the fit algorithm (eg which paremeters
+//    are fixed at which time)
+//  - use a different varaible than alpha
+//  - a possiblity to change the algorithm which is used to calculate
+//    alpha (or another parameter) is missing (this could be done using
+//    a tasklist somewhere...)
+//  - a more clever (and faster) algorithm to fill the histogram, eg by
+//    calculating alpha once and fill the two coils around the mean
+//  - more drawing options...
+//  - Move Significance() to a more 'general' place and implement
+//    also different algorithms like (Li/Ma)
+//  - implement fit for best alpha distribution -- online (Paint)
+//  - currently a constant pointing position is assumed in Fill()
+//  - the center of rotation need not to be the camera center
+//  - ERRORS on each alpha bin to estimate the chi^2 correctly!
+//    (sqrt(N)/binwidth) needed for WOlfgangs proposed caluclation
+//    of alpha(Li/Ma)
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSkyPlot.h"
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TH1.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TPaveLabel.h>
+#include <TPaveText.h>
+#include <TStopwatch.h>
+#include <TFile.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MReportDrive.h"
+#include "MHillasSrc.h"
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MHadronness.h"
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MAstroCatalog.h"
+#include "MAstroSky2Local.h"
+#include "MStarCamTrans.h"
+#include "MStatusDisplay.h"
+#include "MMath.h"
+#include "MSupercuts.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MSkyPlot);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MSkyPlot::MSkyPlot(const char *name, const char *title)
+  : fGeomCam(NULL),   
+    fTime(NULL),      
+    fPointPos(NULL),  
+    fRepDrive(NULL),  
+    fSrcPosCam(NULL), 
+    fPntPosCam(NULL), 
+    fObservatory(NULL),
+    fHillas(NULL),    
+    fHillasExt(NULL), 
+    fHillasSrc(NULL), 
+    fNewImagePar(NULL),
+    fMm2Deg(-1)
+{
+
+  *fLog << warn << "entering default constructor in MSkyPlot" << endl; 
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MSkyPlot";
+    fTitle = title ? title : "sky plot vs x, y";
+
+    fSetCenter=kTRUE;
+
+    fHistSignif.SetDirectory(NULL);
+    fHistNexcess.SetDirectory(NULL);
+    fHistOn.SetDirectory(NULL);
+    fHistSignifGaus.SetDirectory(NULL);
+
+    fHistSignif.UseCurrentStyle();
+    fHistNexcess.UseCurrentStyle();
+    fHistOn.UseCurrentStyle();
+    fHistSignifGaus.UseCurrentStyle();
+
+    fHistSignif.SetName("SkyPlotSignif");
+    fHistSignif.SetTitle("Sky Plot of significance vs x, y");
+    fHistSignif.SetXTitle("x [\\circ]");
+    fHistSignif.SetYTitle("y [\\circ]");
+
+    fHistNexcess.SetName("SkyPlotNexcess");
+    fHistNexcess.SetTitle("Sky Plot of number of excess vs x, y");
+    fHistNexcess.SetXTitle("x [\\circ]");
+    fHistNexcess.SetYTitle("y [\\circ]");
+
+    fHistOn.SetName("SkyPlotOn");
+    fHistOn.SetTitle("Sky Plot of number of On events vs x, y");
+    fHistOn.SetXTitle("x [\\circ]");
+    fHistOn.SetYTitle("y [\\circ]");
+
+    fHistSignifGaus.SetName("SignifDistrib");
+    fHistSignifGaus.SetTitle("Distribution of the significances from the sky plot");
+    fHistSignifGaus.SetXTitle("significance");
+    fHistSignifGaus.SetYTitle("counts");
+
+    // set some values for the sky plot geometry:
+    fMinXGrid    =-1.;  		// [deg] 
+    fMaxXGrid    = 1.;             //  [deg] , right edge of the skyplot
+    fMinYGrid    =-1.;            //  [deg] , upper edge of the skyplot
+    fMaxYGrid    = 1.;             //  [deg] , lower edge of the skyplot
+    fBinStepGrid = 0.05;         //  [deg], 
+    fAlphaONMax  = 5.;           //  [deg] , upper cut for alpha ON region in the alpha plot
+                      // [deg], ON region in the alpha plot, maybe 5 deg is better
+                      // NOTE: up to now only values of 5, 10, 15, 20 degrees are possible
+// ra,dec lines from wolfgang:
+    fGridBinning = 0.50;   // degrees
+    fGridFineBin = 0.01;   // degrees
+
+// elapsed time:
+    fElaTime = 0.;
+
+    // some filter cuts:
+    fSizeMin    = 2000.;             // min size in photons
+    fSizeMax    = 100000.;             // max size in photons
+    fLeakMax    = 0.25;             // leakmax  in per cent
+    fMaxDist = 1.4;          // dist max cut (ever possible)
+    fMinDist = 0.1;          // dist max cut (ever possible)
+    fHadrCut = 0.2;          // hadronness cut
+
+    fNumBinsAlpha   = 36; 	 // number of bins for alpha histograms
+    fAlphaLeftEdge  = 0.;        // [deg] left edge
+    fAlphaRightEdge = 90.;       // [deg] left edge
+
+    fAlphaBgLow     = 30.;
+    fAlphaBgUp      = 90.;
+
+    {
+// SET DEFAULT VALUES HERE	
+    fLengthUp[0] =  0.2;
+    fLengthUp[1] =  0.0;
+    fLengthUp[2] =  0.0;
+    fLengthUp[3] =  0.0;
+    fLengthUp[4] =  0.0;
+    fLengthUp[5] =  0.0;
+    fLengthUp[6] =  0.0;
+    fLengthUp[7] =  0.0;
+
+    fLengthLo[0] =  0.;
+    fLengthLo[1] =  0.;
+    fLengthLo[2] =  0.;
+    fLengthLo[3] =  0.;
+    fLengthLo[4] =  0.;
+    fLengthLo[5] =  0.;
+    fLengthLo[6] =  0.;
+    fLengthLo[7] =  0.;
+
+    fWidthUp[0] =  0.1;
+    fWidthUp[1] =  0.0;
+    fWidthUp[2] =  0.0;
+    fWidthUp[3] =  0.0;
+    fWidthUp[4] =  0.0;
+    fWidthUp[5] =  0.0;
+    fWidthUp[6] =  0.0;
+    fWidthUp[7] =  0.0;
+
+    fWidthLo[0] =  0.;
+    fWidthLo[1] =  0.;
+    fWidthLo[2] =  0.;
+    fWidthLo[3] =  0.;
+    fWidthLo[4] =  0.;
+    fWidthLo[5] =  0.;
+    fWidthLo[6] =  0.;
+    fWidthLo[7] =  0.;
+
+    fDistUp[0] =  1.e10;
+    fDistUp[1] =  0.0;
+    fDistUp[2] =  0.0;
+    fDistUp[3] =  0.0;
+    fDistUp[4] =  0.0;
+    fDistUp[5] =  0.0;
+    fDistUp[6] =  0.0;
+    fDistUp[7] =  0.0;
+
+    fDistLo[0] =  0.0;
+    fDistLo[1] =  0.0;
+    fDistLo[2] =  0.0;
+    fDistLo[3] =  0.0;
+    fDistLo[4] =  0.0;
+    fDistLo[5] =  0.0;
+    fDistLo[6] =  0.0;
+    fDistLo[7] =  0.0;
+    }
+
+    fSaveAlphaPlots=kTRUE;
+    fSaveSkyPlots=kTRUE;
+    fSaveNexPlot=kTRUE;
+    fUseRF=kFALSE;
+    fAlphaHName = "alphaplot.root";
+    fSkyHName   = "skyplot.root";
+    fNexHName   = "Nexcess.gif";
+
+    fHistAlpha = new TOrdCollection();
+    fHistAlpha->SetOwner();    
+
+}
+
+MSkyPlot::~MSkyPlot()
+{
+
+  if (fHistAlpha)
+    delete fHistAlpha;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th hist 
+//
+TH1D *MSkyPlot::GetAlphaPlot(Int_t i)
+{
+  if (GetSize() == 0)
+    return NULL;
+
+  return static_cast<TH1D*>(i==-1 ? fHistAlpha->At(GetSize()/2+1) : fHistAlpha->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th hist 
+//
+const TH1D *MSkyPlot::GetAlphaPlot(Int_t i) const 
+{
+  if (GetSize() == 0)
+    return NULL;
+
+  return static_cast<TH1D*>(i==-1 ? fHistAlpha->At(GetSize()/2+1) : fHistAlpha->At(i));
+}
+
+
+void MSkyPlot::ReadCuts(const TString parSCinit="OptSCParametersONOFFThetaRange0_1570mRad.root")
+{
+
+cout << " parameters read from file: " << parSCinit << endl;
+    //--------------------------------
+    // create container for the supercut parameters
+    // and set them to their initial values
+    MSupercuts super;
+
+  // read the cuts coefficients
+    TFile inparam(parSCinit);
+    super.Read("MSupercuts");
+    inparam.Close();
+    *fLog << "MFindSupercutsONOFF::FindParams; initial values of parameters are taken from file "
+          << parSCinit << endl;
+
+    TArrayD params = super.GetParameters();
+    TArrayD steps  = super.GetStepsizes();
+ // TMP2
+    if (params.GetSize() == steps.GetSize())
+    {
+            *fLog << "SC parameters and Setps are: " << endl;
+            for (Int_t z = 0; z < params.GetSize(); z++)
+            {
+                cout << params[z] << setw(20) << steps[z] << endl;
+            }
+    }
+ // ENDTMP2
+    for (Int_t i=0; i<8; i++)
+    {
+	fLengthUp[i]  = params[i];
+        fLengthLo[i] = params[i+8];
+	fWidthUp[i]   = params[i+16];
+	fWidthLo[i]  = params[i+24];
+        fDistUp[i]    = params[i+32];
+        fDistLo[i]   = params[i+40];
+    }
+}
+
+void MSkyPlot::SetSkyPlot(Float_t xmin, Float_t xmax, Float_t ymin, Float_t ymax, Float_t step)
+{
+    Float_t temp;
+
+    if (xmax<xmin)
+    {
+        *fLog << warn << "SetSkyPlot: xmax is smaller xmin ... exchanging them." << endl;
+	temp = xmax;
+	xmax = xmin;
+	xmin = temp;
+    }	
+
+    if (ymax<ymin)
+    {
+        *fLog << warn << "SetSkyPlot: ymax is smaller ymin ... exchanging them." << endl;
+	temp = ymax;
+	ymax = ymin;
+	ymin = temp;
+    }	
+    
+    if (step<0)
+        *fLog << warn << "SetSkyPlot: step<0... taking absolute value." << endl;
+
+    fBinStepGrid = TMath::Abs(step);
+    fMinXGrid    = xmin;
+    fMaxXGrid    = xmax;
+    fMinYGrid    = ymin;
+    fMaxYGrid    = ymax;
+    
+    *fLog << endl <<  inf << " SetSkyPlot: fMinXGrid, fMaxXGrid, fMinYGrid, fMaxYGrid, fBinStepGrid: " << endl;
+    *fLog << inf << "           " << fMinXGrid << ", " << fMaxXGrid << ", " << fMinYGrid << ", " 
+                 << fMaxYGrid<< ", " << fBinStepGrid << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the alpha cut (|alpha|<fAlphaCut) which is use to estimate the
+// number of excess events
+//
+void MSkyPlot::SetAlphaCut(Float_t alpha)
+{
+    if (alpha<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    fAlphaONMax = TMath::Abs(alpha);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the upper and lower limit for the background region in the alpha plot
+// to estimate the number of background events
+//
+void MSkyPlot::SetAlphaBGLimits(Float_t alphalow, Float_t alphaup)
+{
+    Float_t alphatemp;
+    if (alphalow<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    if (alphaup<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    if (TMath::Abs(alphaup)<TMath::Abs(alphalow)) {
+        *fLog << warn << "AlphaLow > AlphaUp... exchanging limits." << endl;
+	alphatemp = alphaup;
+	alphaup = alphalow;
+	alphalow = alphatemp;
+    }
+
+    fAlphaBgLow = TMath::Abs(alphalow);
+    fAlphaBgUp  = TMath::Abs(alphaup);
+}
+
+// calculate the values for the cuts:
+Double_t MSkyPlot::CalcLimit(Double_t *a, Double_t ls, Double_t ls2, Double_t dd2)
+{
+
+    Double_t  limit = a[0] + a[1] * dd2 +
+                      ls  * (a[3] + a[4] * dd2) +
+                      ls2 * (a[6] + a[7] * dd2);
+
+     return limit;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningFalseSource) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+// 
+Int_t MSkyPlot::PreProcess(MParList *plist)
+{
+
+  *fLog << warn << "entering PreProcess in MSkyPlot::PreProcess" << endl; 
+  
+    fGeomCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = fGeomCam->GetConvMm2Deg();
+
+    fRepDrive = (MReportDrive*)plist->FindObject(AddSerialNumber("MReportDrive"));
+    if (!fRepDrive)
+        *fLog << warn << "MReportDrive not found... could be problem for sky map." << endl;
+
+
+    fSrcPosCam = (MSrcPosCam*)plist->FindCreateObj(AddSerialNumber("MSrcPosCam"));
+    if (!fSrcPosCam)
+        *fLog << warn << "MSrcPosCam not found... no sky map." << endl;
+
+/*
+    fPntPosCam = (MSrcPosCam*)plist->FindObject(AddSerialNumber("MPntPosCam"));
+    if (!fPntPosCam)
+        *fLog << warn << "MPntPosCam not found... no sky map." << endl;
+*/
+
+    fPointPos = (MPointingPos*)plist->FindObject(AddSerialNumber("MPointingPos"));
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... no sky map." << endl;
+
+    fTime = (MTime*)plist->FindObject(AddSerialNumber("MTime"));
+    if (!fTime)
+        *fLog << warn << "MTime not found... could be problem for sky map." << endl;
+
+    fObservatory = (MObservatory*)plist->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+        *fLog << warn << "MObservatory not found... no sky map." << endl;
+
+
+    fHillas = (MHillas*)plist->FindObject(AddSerialNumber("MHillas"));
+    if (!fHillas)
+        *fLog << err << "MHillas not found... no sky map." << endl;
+
+    fHillasExt = (MHillasExt*)plist->FindObject(AddSerialNumber("MHillasExt"));
+    if (!fHillasExt)
+        *fLog << err << "MHillasExt not found... no sky map." << endl;
+
+    fHillasSrc = (MHillasSrc*)plist->FindObject(AddSerialNumber("MHillasSrc"));
+    if (!fHillasSrc)
+        *fLog << err << "MHillasSrc not found... no sky map." << endl;
+
+    fNewImagePar = (MNewImagePar*)plist->FindObject(AddSerialNumber("MNewImagePar"));
+    if (!fNewImagePar)
+        *fLog << err << "MNewImagePar not found... no sky map." << endl;
+
+    if(fUseRF)
+    {
+       fHadron = (MHadronness*)plist->FindObject(AddSerialNumber("MHadronness"));
+       if (!fHadron)
+           *fLog << err << "MHadronness not found although specified... no sky map." << endl;
+
+       *fLog << inf << "Hadronness cut set to : " << fHadrCut << endl;
+    }
+
+    // FIXME: Because the pointing position could change we must check
+    // for the current pointing position and add a offset in the
+    // Fill function!
+
+   // prepare skyplot
+    fNumStepsX     =  (int) ((fMaxXGrid - fMinXGrid) / fBinStepGrid + 1.5);
+    fNumStepsY     =  (int) ((fMaxYGrid - fMinYGrid) / fBinStepGrid + 1.5);
+    fNumalphahist  =  (int) (fNumStepsX * fNumStepsY  + 0.5);
+
+    *fLog << inf << "SetSkyPlot: fNumStepsX, fNumStepsY, fNumalphahist: "
+                 << fNumStepsX << ", " << fNumStepsY << ", " << fNumalphahist << endl;
+
+   // fHistSignif.SetName("SPSignif2ndOrder");
+   // fHistSignif.SetTitle("Sky Plot of significance (2nd order fit)");
+    fHistSignif.SetBins(fNumStepsX, fMinXGrid-0.5*fBinStepGrid, fMaxXGrid+0.5*fBinStepGrid, 
+			fNumStepsY, fMinYGrid-0.5*fBinStepGrid, fMaxYGrid+0.5*fBinStepGrid);
+    fHistSignif.SetFillStyle(4000);
+
+   // fHistNexcess.SetName("SPNex2ndOrder");
+   // fHistNexcess.SetTitle("Sky Plot of Number of excess events (2nd order fit)");
+    fHistNexcess.SetBins(fNumStepsX, fMinXGrid-0.5*fBinStepGrid, fMaxXGrid+0.5*fBinStepGrid, 
+			fNumStepsY, fMinYGrid-0.5*fBinStepGrid, fMaxYGrid+0.5*fBinStepGrid);
+    fHistNexcess.SetFillStyle(4000);
+
+   // fHistOn.SetName("SPOnCounted");
+   // fHistOn.SetTitle("Sky Plot of ON events (counted)");
+    fHistOn.SetBins(fNumStepsX, fMinXGrid-0.5*fBinStepGrid, fMaxXGrid+0.5*fBinStepGrid, 
+			fNumStepsY, fMinYGrid-0.5*fBinStepGrid, fMaxYGrid+0.5*fBinStepGrid);
+    fHistOn.SetFillStyle(4000);
+
+    //fHistSignifGaus.SetName("SignifDistrib");
+    fHistSignifGaus.SetTitle("Distribution of the significances from the sky plot");
+    fHistSignifGaus.SetBins(100, -10., 10.); 
+
+    // create alpha histograms
+    for (Int_t i=0; i< fNumalphahist; i++)
+      {
+    	// temp histogram for an alpha plot
+	TH1D *temp = new TH1D("alphaplot","alphaplot",fNumBinsAlpha,fAlphaLeftEdge,fAlphaRightEdge);
+	temp->SetDirectory(NULL);
+	fHistAlpha->AddAt(temp,i);
+      }
+
+    fHistAlphaBinWidth = GetAlphaPlot()->GetBinWidth(1);
+//cout  << " (*fHistAlpha)[10].GetBinContent(5) " << (*fHistAlpha)[10].GetBinContent(5) << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Int_t MSkyPlot::Process()
+{
+
+//      *fLog << err << "MPointingPos ENTERING the process" << endl;
+//      *fLog << err << "MPointingPos:: fUseRF " << (int)fUseRF << endl;
+  // check whether MPointingPos comtains something:
+  if (TMath::Abs(fPointPos->GetRa())<1e-3 && TMath::Abs(fPointPos->GetDec())<1e-3) 
+    {
+      *fLog << warn << "MPointingPos is not filled ... event skipped" << endl;
+      return kTRUE;
+    }
+  
+  // Get RA_0, DEC_0 for the camera center (Tracking MDrive?, can be set from outside)
+  if (fSetCenter==kTRUE)
+    {
+      if (fRepDrive)
+	{
+	  fRa0  = fRepDrive->GetRa();  // [h]
+	  fDec0 = fRepDrive->GetDec(); // [deg]
+	  if (fRa0 < 0. || fRa0 > 24. || fDec0 < -90. || fDec0 > 90. || (fRa0==0 && fDec0==0)) return kTRUE;  // temp!, should be changed
+	}
+      else
+	{
+	  fRa0 = fPointPos->GetRa(); 
+	  fDec0 = fPointPos->GetDec();
+	} 
+      *fLog << inf << "Ra (center) = " << fRa0 << ", Dec = " << fDec0 << endl;
+      fSetCenter=kFALSE;
+    }
+
+  // some filter cuts:
+  if ( fHillas->GetSize() > fSizeMin && fHillas->GetSize() < fSizeMax && fNewImagePar->GetLeakage1() < fLeakMax)
+    {
+      
+      Double_t xsource, ysource, cosgam, singam, x_0, y_0, xsourcam, ysourcam;
+      Double_t dx, dy, beta, tanbeta, alphapar, distpar;
+      Double_t logsize, lgsize, lgsize2, dist2, hadr; 
+      const Double_t log3000n = log(3000.*0.18);  // now in phe, thus must shift the offset
+      const Float_t fDistOffset = 0.9;
+      
+      //Get Hadronness if available:
+      if(fUseRF) 
+	{
+		hadr=fHadron->GetHadronness();
+//		cout << " will use RF " << hadr << endl;
+	}
+      // Get camera rotation angle
+      Double_t rho = 0;
+      if (fTime && fObservatory && fPointPos)
+	{
+	  rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+	  //*fLog << inf << " rho = " << rho*180./TMath::Pi() << ", Zd = " << fPointPos->GetZd() << 
+	  //                ", Az = " << fPointPos->GetAz() << ", Ra = " << fPointPos->GetRa() << ", Dec = " << fPointPos->GetDec() << endl;
+	  
+	  // => coord. system: xtilde, ytilde with center in RA_0, DEC_0 
+	  
+	  // Get Rot. Angle:
+	  cosgam = TMath::Cos(rho);
+	  singam = TMath::Sin(rho);
+	  // Get x_0, y_0 for RA_0,DEC_0 of the current event
+	}
+      else 
+	{
+	  //	rho = fPointPos->RotationAngle(*fObservatory);
+	  Double_t theta, phi, sing, cosg;
+	  theta = fPointPos->GetZd()*TMath::Pi()/180.;
+	  phi = fPointPos->GetAz()*TMath::Pi()/180.;
+	  printf("theta: %5.3f, phi: %5.3f\n", theta*180./4.1415, phi*180./4.1415);
+	  fObservatory->RotationAngle(theta, phi, sing, cosg);        
+	  cosgam = cosg;
+	  singam = sing;
+	}
+      // if (fPointPos)
+      //    rho = fPointPos->RotationAngle(*fObservatory);
+      
+      /*
+	//TEMP
+	//        theta = mcevt->GetTelescopeTheta();
+	Double_t theta, phi, sing, cosg;
+	theta = fPointPos->GetZd()*TMath::Pi()/180.;
+	phi = fPointPos->GetAz()*TMath::Pi()/180.;
+	//   printf("theta: %5.3f, phi: %5.3f\n", theta*180./4.1415, phi*180./4.1415);
+	fObservatory->RotationAngle(theta, phi, sing, cosg);
+	
+	// conclusion: diffference in rho = 7 deg
+	//  *fLog << "new thetaTel, phiTel, cosal, sinal, rho = " << theta << ",  "
+	//        << phi << ",  " << cosg << ",  " << sing << ", " << TMath::ATan2(sing,cosg)*180./TMath::Pi() << endl;
+	
+	Double_t a1 =  0.876627;
+	Double_t a3 = -0.481171;
+	Double_t thetaTel=theta, phiTel=phi;
+	
+	Double_t denom =  1./ sqrt( sin(thetaTel)*sin(phiTel) * sin(thetaTel)*sin(phiTel) +
+	( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) ) *
+	( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) )   );
+	Double_t cosal = - (a3 * sin(thetaTel) + a1 * cos(thetaTel) * cos(phiTel)) * denom;
+	Double_t sinal =    a1 * sin(phiTel) * denom;
+	
+	//  *fLog << "old thetaTel, phiTel, cosal, sinal, rho = " << thetaTel << ",  "
+	//        << phiTel << ",  " << cosal << ",  " << sinal << ", " << TMath::ATan2(sinal,cosal)*180./TMath::Pi() << endl;
+	
+	// END TEMP
+      */
+	    
+      // make the center of the plot different from the center of the camera
+      /*
+	x_0 = fPntPosCam->GetX()*fMm2Deg; 
+	y_0 = fPntPosCam->GetY()*fMm2Deg; 
+      */      
+      x_0 = 0.;  
+      y_0 = 0.;
+      
+      Int_t index = 0;  // index for alpha histograms
+      // loop over xtilde
+      for (Int_t gridy = 0; gridy < fNumStepsY; gridy++)   
+	{
+	  ysource = fMinYGrid + gridy * fBinStepGrid;
+	  // loop over ytilde
+	  for (Int_t gridx = 0; gridx < fNumStepsX; gridx++)
+	    {
+	      
+	      xsource = fMinXGrid + gridx * fBinStepGrid;
+	      
+	      /*     derotation    : rotate  into camera coordinates */
+	      /*     formel: (x_cam)      (cos(gam)  -sin(gam))   (xtilde)   (x_0)
+		     (     )  = - (                   ) * (      ) + (   ) 
+	        (y_cam)      (sin(gam)   cos(gam))   (ytilde)   (y_0)
+	      */
+	      xsourcam = - (cosgam * xsource - singam * ysource) + x_0;
+	      ysourcam = - (singam * xsource + cosgam * ysource) + y_0;
+	      
+	      
+	      /*    end derotatiom    */
+	      //           xsourcam = xsource;
+	      //           ysourcam = ysource;
+
+	      /* calculate ALPHA und DIST according to the source position */
+	      dx = fHillas->GetMeanX()*fMm2Deg - xsourcam;
+	      dy = fHillas->GetMeanY()*fMm2Deg - ysourcam;
+	      tanbeta = dy / dx ;
+	      beta = TMath::ATan(tanbeta);
+	      alphapar = (fHillas->GetDelta() - beta) * 180./ TMath::Pi();
+	      distpar = sqrt( dy*dy + dx*dx );
+	      if(alphapar >  90.) alphapar -= 180.;
+	      if(alphapar < -90.) alphapar += 180.;
+	      alphapar = TMath::Abs(alphapar);
+	      
+	      if(fUseRF)
+	      {
+		
+//		cout << " will use RF " << hadr << endl;
+		if(hadr<fHadrCut  &&  distpar < fMaxDist && distpar > fMinDist)
+		{
+		    TH1D *hist = GetAlphaPlot(index);
+                    hist->Fill(alphapar);
+		}
+	      }
+	      else
+	      {
+	      	// apply cuts
+	      	logsize = log(fHillas->GetSize());
+	      	lgsize = logsize-log3000n;
+	      	lgsize2 = lgsize*lgsize;
+	      	dist2 = distpar*distpar - fDistOffset*fDistOffset;
+	      
+	      	if ( (fHillas->GetLength()*fMm2Deg) < CalcLimit(fLengthUp, lgsize, lgsize2, dist2) &&
+		   (fHillas->GetLength()*fMm2Deg) > CalcLimit(fLengthLo, lgsize, lgsize2, dist2))
+			if ( (fHillas->GetWidth()*fMm2Deg) < CalcLimit(fWidthUp, lgsize, lgsize2, dist2) &&
+		     	(fHillas->GetWidth()*fMm2Deg) > CalcLimit(fWidthLo, lgsize, lgsize2, dist2))
+			  if ( distpar < CalcLimit(fDistUp, lgsize, lgsize2, dist2) &&
+		      	  distpar > CalcLimit(fDistLo, lgsize, lgsize2, dist2) &&
+		      	  distpar < fMaxDist && distpar > fMinDist)
+		    	{
+		      // gamma candidates!
+		      //*fLog <<  "Length : " << fHillas->GetLength()*fMm2Deg << ", Width : " << fHillas->GetWidth()*fMm2Deg << endl;
+		      //*fLog <<  "distpar: " << distpar << ", Size : " << fHillas->GetSize() << endl;
+		      	TH1D *hist = GetAlphaPlot(index);
+		      	hist->Fill(alphapar);
+		    	}
+		}
+	      	index++;
+	    }
+	}
+    }
+    return kTRUE;
+}
+
+// calculate number of events below alphacut, number of excess events, significance
+
+Int_t MSkyPlot::PostProcess()
+{
+
+    Int_t nrow, ncolumn;
+    Double_t Non, chisquarefit, numdegfreed, Noff_fit, Nex, Sign; 
+    const Int_t onbinsalpha = TMath::Nint(fAlphaONMax/fHistAlphaBinWidth);
+
+
+// fit function for the background
+    TF1 * fitbgpar = new TF1("fbgpar", "[0]*x*x + [1]", fAlphaBgLow, fAlphaBgUp);
+    fitbgpar->SetLineColor(2);
+
+// number degrees of freedom:
+    numdegfreed = (fAlphaBgUp - fAlphaBgLow) / fHistAlphaBinWidth - 2.; 
+
+    int index2 = 0;  // index of the TH2F histograms
+
+    TOrdCollectionIter Next(fHistAlpha);
+    TH1D *alpha_iterator = NULL;
+
+    fHistNexcess.Reset();
+    fHistOn.Reset();
+    fHistSignif.Reset();   
+    fHistSignifGaus.Reset();
+    
+    while ( (alpha_iterator = (TH1D*)Next())) {
+	 // find the bin in the 2dim histogram
+         nrow    = index2/fHistOn.GetNbinsX() + 1;              // row of the histogram (y)
+         ncolumn = index2%fHistOn.GetNbinsX()+1;   		// column of the histogram (x)
+         //ncolumn = TMath::Nint(fmod(index2,fHistOn.GetNbinsX()))+1;   // column of the histogram (x)
+
+         // number of ON events below fAlphaONMax
+         Non = 0.;
+         for(Int_t i=1; i<=onbinsalpha;i++) Non += (*alpha_iterator).GetBinContent(i);
+
+         fHistOn.SetBinContent(ncolumn, nrow, Non);		// fill in the fHistOn
+
+         // fit parabola to a background region
+         alpha_iterator->Fit(fitbgpar,"EQRN");  // NWR OK?????????????????????????
+         // get Chi2
+         chisquarefit = fitbgpar->GetChisquare();
+         if (chisquarefit/numdegfreed<2. && chisquarefit/numdegfreed>0.01);
+         else  *fLog << warn << "Fit is bad, chi2/ndf = " << chisquarefit/numdegfreed << endl;
+	 
+         // estimate Noff from the fit:
+       	 Noff_fit = (1./3. * (fitbgpar->GetParameter(0)) * TMath::Power(fAlphaONMax,3.) +
+		     (fitbgpar->GetParameter(1)) * fAlphaONMax) /  fHistAlphaBinWidth;
+	 
+	 Nex = Non - Noff_fit;
+
+         fHistNexcess.SetBinContent(ncolumn, nrow, Nex);	// fill in the fHistNexcess
+	 
+         if (Noff_fit<0.) Sign = 0.;
+	 //         else Sign = LiMa17(Non,Noff_fit,1.);
+         else Sign = MMath::SignificanceLiMaSigned(Non, Noff_fit, 1.);
+	 
+         fHistSignif.SetBinContent(ncolumn, nrow, Sign);	// fill in the fHistSignif
+         fHistSignifGaus.Fill(Sign);
+	 
+         index2++;
+    }
+    
+    // fit with gaus 
+    fHistSignifGaus.Fit("gaus","N");
+    
+    
+    //temp
+    /*
+      Double_t decl, hang;
+      MStarCamTrans mstarc(*fGeomCam, *fObservatory);
+      mstarc.LocToCel(fRepDrive->GetNominalZd(),fRepDrive->GetNominalAz(),decl, hang);
+      
+      *fLog << warn << "MDrive, RA, DEC = " << fRepDrive->GetRa() << ", " << fRepDrive->GetDec() << endl;
+      *fLog << warn << "MStarCamTrans, H angle , DEC = " << hang << ", " << decl << endl;
+      */
+    //endtemp
+    
+    
+    // save alpha plots:
+    //  TString stri1 = "alphaplots.root";
+    if(fSaveAlphaPlots==kTRUE) SaveAlphaPlots(fAlphaHName);
+    
+    // save sky plots:
+    //  TString stri2 = "skyplots.root";
+    if(fSaveSkyPlots==kTRUE) SaveSkyPlots(fSkyHName);
+    
+    // save nex plot:
+    if(fSaveNexPlot==kTRUE) SaveNexPlot(fNexHName);
+    
+    fHistAlpha->Clear();
+
+    delete fitbgpar;
+    
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the MAstroCatalog corresponding to fRa, fDec. The limiting magnitude
+// is set to 9, while the fov is equal to the current fov of the false
+// source plot.
+//
+TObject *MSkyPlot::GetCatalog()
+{
+    const Double_t maxr = 0.98*TMath::Abs(fHistSignif.GetBinCenter(1));
+
+    // Create catalog...
+    MAstroCatalog stars;
+    stars.SetLimMag(9);
+    stars.SetGuiActive(kFALSE);
+    stars.SetRadiusFOV(maxr);
+    stars.SetRaDec(fRa*TMath::DegToRad()*15, fDec*TMath::DegToRad());
+    stars.ReadBSC("bsc5.dat");
+
+    TObject *o = (MAstroCatalog*)stars.Clone();
+    o->SetBit(kCanDelete);
+
+    return o;
+}
+
+void MSkyPlot::SaveNexPlot(TString nexplotname)
+{
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetCanvasBorderSize(0);
+    gStyle->SetCanvasColor(10);
+//    gStyle->SetPadBorderMode(0);
+//    gStyle->SetPadBorderSize(0);
+    gStyle->SetPadColor(10);
+    gStyle->SetOptFit(0);
+    gStyle->SetOptStat(0);
+    gStyle->SetStatColor(10);
+    gStyle->SetPalette(1);
+    gStyle->SetPadRightMargin(0.16);
+    gStyle->SetPadLeftMargin(0.13);
+
+    Char_t timet[100];
+
+    TH2D tmp = fHistNexcess;
+    tmp.SetMaximum(470); 
+    tmp.SetMinimum(-90); 
+    TCanvas can("SkyPlot","SkyPlot", 0, 0, 800, 400);
+    can.Divide(2,1);
+    can.cd(1);
+    tmp.GetYaxis()->SetTitleOffset(1.3);
+    tmp.Draw("colz"); 
+    TPaveLabel myname(fMinXGrid-0.5,fMinYGrid-0.4,fMinXGrid+0.3,fMinYGrid-0.2,"by D. Mazin");
+    myname.Draw();
+
+    can.cd(2);
+    fHistNexcess.SetMaximum(470);    
+    fHistNexcess.SetMinimum(-40);    
+    fHistNexcess.GetXaxis()->SetTitleOffset(1.3);
+    fHistNexcess.GetYaxis()->SetTitleOffset(1.6);
+    gPad->SetTheta(20);
+    fHistNexcess.Draw("lego2");
+    TLatex tu(0.5,0.8,"elapsed time:");
+    tu.Draw();
+    sprintf(timet,"%.1f min",fElaTime);
+    TLatex tut(0.5,0.7,timet);
+    tut.Draw();
+
+    can.Print(nexplotname);  
+//    can.Print("test.root");
+}
+
+void MSkyPlot::SaveSkyPlots(TString skyplotfilename)
+{
+
+  TFile rootfile(skyplotfilename, "RECREATE",
+		 "sky plots in some variations");
+  fHistSignif.Write();
+  fHistNexcess.Write();
+  fHistOn.Write();
+  fHistSignif.Write();
+     
+  // from Wolfgang: 
+  //--------------------------------------------------------------------
+  // Dec-Hour lines
+  Double_t rho, sinrho, cosrho;
+  Double_t theta, phi, sing, cosg;
+  // do I need it?
+  if (fTime && fObservatory && fPointPos)
+    {
+      rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+      sinrho=TMath::Sin(rho);
+      cosrho=TMath::Cos(rho);
+    }
+  
+  theta = fPointPos->GetZd()*TMath::Pi()/180.;
+  phi = fPointPos->GetAz()*TMath::Pi()/180.;
+  //   printf("theta: %5.3f, phi: %5.3f\n", theta*180./4.1415, phi*180./4.1415);
+  fObservatory->RotationAngle(theta, phi, sing, cosg);
+  
+  *fLog << "1: sinrho, cosrho = " << sinrho << ", " << cosrho << endl;
+  *fLog << "2: sinrho, cosrho = " << sing << ", " << cosg << endl;
+  sinrho=sing;
+  cosrho=cosg;
+
+  Double_t fDistCam = fGeomCam->GetCameraDist() * 1000.0;     //  [mm]
+  Double_t gridbinning = fGridBinning;
+  Double_t gridfinebin = fGridFineBin;
+  Int_t    numgridlines = (Int_t)(4.0/gridbinning);
+  Double_t aberr = 1.07;
+  Double_t mmtodeg = 180.0 / TMath::Pi() / fDistCam ;
+  
+  Double_t declin, hangle;  // [deg], [h]
+  MStarCamTrans mstarc(*fGeomCam, *fObservatory);
+  if (fRepDrive) mstarc.LocToCel(fRepDrive->GetNominalZd(),fRepDrive->GetNominalAz(),declin, hangle);
+  else mstarc.LocToCel(theta*180./TMath::Pi(),phi*180./TMath::Pi(),declin, hangle); // NOT GOOD!
+  
+  TLatex *pix;
+  
+  Char_t tit[100];
+  Double_t xtxt;
+  Double_t ytxt;
+  
+  Double_t xlo = -534.0 * mmtodeg;
+  Double_t xup =  534.0 * mmtodeg;
+  
+  Double_t ylo = -534.0 * mmtodeg;
+  Double_t yup =  534.0 * mmtodeg;
+  
+  Double_t xx, yy;
+  
+  
+  // direction for the center of the camera
+  Double_t dec0 = declin;
+  Double_t h0   = hangle*360./24.; //deg
+  //    Double_t RaHOffset = fRepDrive->GetRa() - h0;
+    //trans.LocToCel(theta0, phi0, dec0, h0);
+  
+  gStyle->SetOptFit(0);
+  gStyle->SetOptStat(0);
+  gStyle->SetPalette(1);
+  TCanvas *c1 = new TCanvas("SPlotsRaDecLines","SPlotsRaDecLines", 400, 0, 700, 600);
+  c1->Divide(2,2);
+  c1->cd(1);
+  fHistSignif.Draw("colz");
+  c1->cd(2);
+  fHistNexcess.Draw("colz");
+  c1->cd(3);
+  fHistOn.Draw("colz");
+  c1->cd(4);
+  gPad->SetLogy();
+  fHistSignifGaus.Draw(); 
+  
+  //-----   lines for fixed dec   ------------------------------------
+  
+  const Int_t Ndec = numgridlines;
+  Double_t dec[Ndec];
+  Double_t ddec = gridbinning;
+  
+  Int_t nh = (Int_t)(4.0/gridfinebin);
+  const Int_t Nh   = nh+1;
+  Double_t h[Nh];
+  Double_t dh = gridfinebin/cos(dec0/180.0*3.1415926);
+  if ( dh > 360.0/((Double_t)(Nh-1)) )
+    dh = 360.0/((Double_t)(Nh-1));
+  
+  // start to copy
+  for (Int_t j=0; j<Ndec; j++)
+    {
+      dec[j] = dec0 + ((Double_t)j)*ddec
+	- ((Double_t)(Ndec/2)-1.0)*ddec;
+    }
+  
+  for (Int_t k=0; k<Nh; k++)
+    {
+      h[k] = h0 + ((Double_t)k)*dh - ((Double_t)(Nh/2)-1.0)*dh;
+    }
+  
+  Double_t xh[Nh];
+  Double_t yh[Nh];
+  
+  for (Int_t j=0; j<Ndec; j++)
+    {
+      if (fabs(dec[j]) > 90.0) continue;
+      
+      for (Int_t k=0; k<Nh; k++)
+	{
+	  Double_t hh0 = h0   *24.0/360.0;
+	  Double_t hx = h[k]*24.0/360.0;
+	  mstarc.Cel0CelToCam(dec0, hh0, dec[j], hx,
+			      xx, yy);
+	  xx = xx * mmtodeg * aberr;
+	  yy = yy * mmtodeg * aberr;
+	  //        xh[k] = xx * mmtodeg * aberr;
+	  //        yh[k] = yy * mmtodeg * aberr;
+	  xh[k] = cosg * xx + sing * yy;
+	  yh[k] =-sing * xx + cosg * yy;
+	  //        xh[k] = cosrho * xx + sinrho * yy;
+	  //        yh[k] =-sinrho * xx + cosrho * yy;
+	  
+	  
+	  //gLog << "dec0, h0 = " << dec0 << ",  " << h0
+	  //     << " : dec, h, xh, yh = " << dec[j] << ",  "
+	  //     << h[k] << ";   " << xh[k] << ",  " << yh[k] << endl;
+	}
+      
+      //      c1->cd(2);
+      TGraph * graph1 = new TGraph(Nh,xh,yh);
+      //graph1->SetLineColor(j+1);
+      graph1->SetLineColor(36);
+      graph1->SetLineStyle(1);
+      graph1->SetLineWidth(1);
+      //graph1->SetMarkerColor(j+1);
+      graph1->SetMarkerColor(1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      
+      c1->cd(1);
+      graph1->Draw("L");
+      c1->cd(2);
+      graph1->Draw("L");
+      c1->cd(3);
+      graph1->Draw("L");
+      //delete graph1;
+      //      graphvec.push_back(*graph1);
+      //      graphvec[j].Draw("L");
+      
+      sprintf(tit,"Dec = %6.2f", dec[j]);
+      xtxt = xlo + (xup-xlo)*0.1;
+      ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)j) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(36);
+      pix->SetTextSize(.03);
+      //pix->Draw("");
+      //delete pix;
+      
+    }
+  //stop copy
+  //-----   lines for fixed hour angle   ------------------------------------
+  
+  Int_t ndec1 = (Int_t)(4.0/gridfinebin);
+  const Int_t Ndec1 = ndec1;
+  Double_t dec1[Ndec1];
+  Double_t ddec1 = gridfinebin;
+  
+  const Int_t Nh1   = numgridlines;
+  Double_t h1[Nh1];
+  Double_t dh1 = gridbinning/cos(dec0/180.0*3.1415926);
+  if ( dh1 > 360.0/((Double_t)Nh1) )
+    dh1 = 360.0/((Double_t)Nh1);
+  
+  // start copy
+  for (Int_t j=0; j<Ndec1; j++)
+    {
+      dec1[j] = dec0 + ((Double_t)j)*ddec1
+	- ((Double_t)(Ndec1/2)-1.0)*ddec1;
+    }
+  
+  for (Int_t k=0; k<Nh1; k++)
+    {
+      h1[k] = h0 + ((Double_t)k)*dh1 - ((Double_t)(Nh1/2)-1.0)*dh1;
+    }
+  
+  Double_t xd[Ndec1];
+  Double_t yd[Ndec1];
+  
+  for (Int_t k=0; k<Nh1; k++)
+    {
+      Int_t count = 0;
+      for (Int_t j=0; j<Ndec1; j++)
+	{
+	  if (fabs(dec1[j]) > 90.0) continue;
+	  
+	  Double_t hh0 = h0   *24.0/360.0;
+	  Double_t hhx = h1[k]*24.0/360.0;
+	  mstarc.Cel0CelToCam(dec0, hh0, dec1[j], hhx,
+                           xx, yy);
+	  //        xd[count] = xx * mmtodeg * aberr;
+	  //        yd[count] = yy * mmtodeg * aberr;
+	  
+	  xx = xx * mmtodeg * aberr;
+	  yy = yy * mmtodeg * aberr;
+	  xd[count] = cosg * xx + sing * yy;
+	  yd[count] =-sing * xx + cosg * yy;
+
+	  //gLog << "dec0, h0 = " << dec0 << ",  " << h0
+	  //     << " : dec1, h1, xd, yd = " << dec1[j] << ",  "
+	  //     << h1[k] << ";   " << xd[count] << ",  " << yd[count] << endl;
+	  
+	  count++;
+	}
+      
+      //      c1->cd(2);
+      TGraph * graph1 = new TGraph(count,xd,yd);
+      //graph1->SetLineColor(k+1);
+      graph1->SetLineColor(36);
+      graph1->SetLineWidth(2);
+      graph1->SetLineStyle(1);
+      //graph1->SetMarkerColor(k+1);
+      graph1->SetMarkerColor(1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      c1->cd(1);
+      graph1->Draw("L");
+      c1->cd(2);
+      graph1->Draw("L");
+      c1->cd(3);
+      graph1->Draw("L");
+
+      sprintf(tit,"RA = %6.2f", fRa0 + (h0 - h1[k]));
+      Double_t xtxt = xlo + (xup-xlo)*0.75;
+      Double_t ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)k) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(36);
+      pix->SetTextSize(.03);
+      //pix->Draw("");
+      //delete pix;
+      
+    }
+  
+  //    c1->cd(2);
+  sprintf(tit,"Dec0 = %6.2f [deg]   Ra0 = %6.2f [h]", dec0, fRa0);
+  xtxt = xlo + (xup-xlo)*0.05 + 0.80;
+  ytxt = ylo + (yup-ylo)*0.75;
+  pix = new TLatex(xtxt, ytxt, tit);
+  pix->SetTextColor(1);
+  pix->SetTextSize(.05);
+  c1->cd(1);
+  pix->Draw("");
+  c1->cd(2);
+  pix->Draw("");
+  c1->cd(3);
+  pix->Draw("");
+  //delete pix;
+  
+  c1->Write();
+  // we suppose that the {skyplotfilename} ends with .root
+  Int_t sizeofout = skyplotfilename.Sizeof();
+  TString outps = skyplotfilename.Remove(sizeofout-5,5) + "ps";
+  c1->Print(outps);  // temporary!!!!!
+
+  TCanvas *c2 = new TCanvas("SkyPlotsWithRaDecLines","SkyPlotsWithRaDecLines", 0, 0, 300, 600);
+  c2->Divide(1,2);
+  c2->SetBorderMode(0);
+  c2->cd(1);
+  fHistSignif.Draw("colz");
+  c2->cd(2);
+  fHistNexcess.Draw("colz");
+  c2->Write();
+  
+  rootfile.Close();
+  delete c1;
+  delete c2;
+  delete pix;
+
+}
+
+void MSkyPlot::SaveAlphaPlots(const TString alphaplotfilename)
+{
+   TFile rootfile(alphaplotfilename, "RECREATE",
+                   "all the alpha plots");
+
+    int index = 0;  // index of the TH2F histograms
+    Char_t strtitle[100];
+    Char_t strname[100];
+    Float_t xpos, ypos, signif, nex;
+    Int_t nrow, ncolumn, non;
+
+    TH1D *alpha_iterator = NULL;
+    TOrdCollectionIter Next(fHistAlpha);
+
+    while( (alpha_iterator = (TH1D*)Next())) {
+
+          nrow    = index/fHistOn.GetNbinsX() + 1;                    // row of the histogram (y)
+          //ncolumn = TMath::Nint(fmod(index,fHistOn.GetNbinsX()))+1;   // column of the histogram (x)
+          ncolumn = index%fHistOn.GetNbinsX()+1;   // column of the histogram (x)
+          xpos    = fMinXGrid + fBinStepGrid*(ncolumn-1);
+          ypos    = fMinYGrid + fBinStepGrid*(nrow-1);
+          non     = TMath::Nint(fHistOn.GetBinContent(ncolumn,nrow));
+          nex     = fHistNexcess.GetBinContent(ncolumn,nrow);
+          signif  = fHistSignif.GetBinContent(ncolumn,nrow);
+
+          sprintf(strname,"AlphaPlotX%.2fY%.2f", xpos, ypos); 
+          sprintf(strtitle,"for x= %.2f deg, y= %.2f deg: S= %.2f sigma, Nex= %.2f, Non= %d", 
+			xpos, ypos, signif, nex, non);
+           
+	  alpha_iterator->SetName(strname);
+	  alpha_iterator->SetTitle(strtitle);
+          alpha_iterator->Write();
+          index++;
+    }
+
+   rootfile.Close();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// This is a preliminary implementation of a alpha-fit procedure for
+// all possible source positions. It will be moved into its own
+// more powerfull class soon.
+//
+// The fit function is "gaus(0)+pol2(3)" which is equivalent to:
+//   [0]*exp(-0.5*((x-[1])/[2])^2) + [3] + [4]*x + [5]*x^2
+// or
+//   A*exp(-0.5*((x-mu)/sigma)^2) + a + b*x + c*x^2
+//
+// Parameter [1] is fixed to 0 while the alpha peak should be
+// symmetric around alpha=0.
+//
+// Parameter [4] is fixed to 0 because the first derivative at
+// alpha=0 should be 0, too.
+//
+// In a first step the background is fitted between bgmin and bgmax,
+// while the parameters [0]=0 and [2]=1 are fixed.
+//
+// In a second step the signal region (alpha<sigmax) is fittet using
+// the whole function with parameters [1], [3], [4] and [5] fixed.
+//
+// The number of excess and background events are calculated as
+//   s = int(0, sigint, gaus(0)+pol2(3))
+//   b = int(0, sigint,         pol2(3))
+//
+// The Significance is calculated using the Significance() member
+// function.
+//
+
+// I might need this
+/*
+    TCanvas *c=new TCanvas;
+
+    gStyle->SetPalette(1, 0);
+
+    c->Divide(3,2, 0, 0);
+    c->cd(1);
+    gPad->SetBorderMode(0);
+    hists->Draw("colz");
+    hists->SetBit(kCanDelete);
+    catalog->Draw("mirror same");
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    hist->Draw("colz");
+    hist->SetBit(kCanDelete);
+    catalog->Draw("mirror same");
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    histb->Draw("colz");
+    histb->SetBit(kCanDelete);
+    catalog->Draw("mirror same");
+    c->cd(4);
+    gPad->Divide(1,3, 0, 0);
+    TVirtualPad *p=gPad;
+    p->SetBorderMode(0);
+    p->cd(1);
+    gPad->SetBorderMode(0);
+    h0b.DrawCopy();
+    h0a.DrawCopy("same");
+    p->cd(2);
+    gPad->SetBorderMode(0);
+    h3.DrawCopy();
+    p->cd(3);
+    gPad->SetBorderMode(0);
+    h2.DrawCopy();
+
+*/
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MSkyPlot.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MSkyPlot.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MSkyPlot.h	(revision 17960)
@@ -0,0 +1,171 @@
+#ifndef MARS_MSkyPlot
+#define MARS_MSkyPlot
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+class TH2D;
+class TH1D;
+
+class MParList;
+class MTime;
+class MPointingPos;
+class MSrcPosCam;
+class MReportDrive;
+class MObservatory;
+class MHillas;
+class MHillasExt;
+class MHillasSrc;
+class MNewImagePar;
+class MHadronness;
+class MGeomCam;
+class TOrdCollection;
+class MSkyPlot : public MTask
+{
+private:
+
+    MGeomCam      *fGeomCam;     //! container to take the event time from
+    MTime         *fTime;        //! container to take the event time from
+    MPointingPos  *fPointPos;    //! container to take pointing position from
+    MReportDrive  *fRepDrive;    //!      
+    MSrcPosCam    *fSrcPosCam;   //! container with x and y of the source
+    MSrcPosCam    *fPntPosCam;   //! container with x and y of the position MReportDrive.GetRa, MReportDrive.GetDec
+    MObservatory  *fObservatory; //! container to take observatory location from
+    MHillas       *fHillas;      //!
+    MHillasExt    *fHillasExt;   //!
+    MHillasSrc    *fHillasSrc;   //!
+    MNewImagePar  *fNewImagePar; //!
+    MHadronness   *fHadron;      //!
+
+    TOrdCollection *fHistAlpha;  // vector of histograms for alpha
+
+    Float_t        fMm2Deg;      // conversion factor for display in degrees
+    Double_t       fGridBinning; // degrees
+    Double_t       fGridFineBin; // degrees
+
+//    Float_t fAlphaCut;           // Alpha cut
+//    Float_t fBgMean;             // Background mean
+
+//    Float_t fMinDist;            // Min dist
+//    Float_t fMaxDist;            // Max dist
+
+//    Float_t fMinLD;              // Minimum distance in percent of dist
+//    Float_t fMaxLD;              // Maximum distance in percent of dist
+
+    Int_t fNumalphahist;		// number of histograms for alpha
+    Int_t fNumBinsAlpha;
+    Float_t fHistAlphaBinWidth;
+    Float_t fAlphaLeftEdge;
+    Float_t fAlphaRightEdge;
+    Float_t fAlphaONMax;	//  [deg] , upper cut for alpha ON region in the alpha plot, [deg], ON region in the alpha plot, maybe 5 deg is better,  NOTE: up to now only values of 5, 10, 15, 20 degrees are possible
+    Float_t fAlphaBgLow;	   // lower limit for bg region in the ON alpha plot 
+    Float_t fAlphaBgUp;		   // upper limit for bg region in the ON alpha plot
+    
+    TH2D     fHistSignif;          // sky plot of significance vs. x and y
+    TH2D     fHistNexcess;         // sky plot of number of excess events vs. x and y
+    TH2D     fHistOn;              // sky plot of events below fAlphaONMax vs. x and y
+    TH1D     fHistSignifGaus;      // distribution of significance
+    Bool_t   fSetCenter;           // used to set the center of these histograms once
+    Bool_t   fUseRF;               // use RF hadronness cut instead of supercuts
+    Double_t fRa0;		   //    
+    Double_t fDec0;		   //
+    Bool_t   fSaveAlphaPlots;	   //
+    Bool_t   fSaveSkyPlots;	   //
+    Bool_t   fSaveNexPlot;	   //
+				   
+    Float_t fMinXGrid;		   //  [deg] , left edge of the skyplot
+    Float_t fMaxXGrid;		   //  [deg] , right edge of the skyplot
+    Float_t fMinYGrid;		   //  [deg] , upper edge of the skyplot
+    Float_t fMaxYGrid;		   //  [deg] , lower edge of the skyplot
+    Float_t fBinStepGrid;	   //  [deg] , grid size
+    Int_t fNumStepsX;		   // number of bins in x 
+    Int_t fNumStepsY;		   // number of bins in y
+
+
+    // some filter cuts:
+    Float_t fSizeMin;		// min size in photons
+    Float_t fSizeMax;		// max size in photons
+    Float_t fLeakMax;		// leakmax  in per cent
+    Float_t fMaxDist;          // dist max cut (ever possible)
+    Float_t fMinDist;          // dist min cut (ever possible)
+    Float_t fHadrCut;          // hadronness cut 
+
+    // coefficients for the cuts:
+    Double_t fLengthUp[8], fLengthLo[8], fWidthUp[8], fWidthLo[8], fDistUp[8], fDistLo[8];
+
+    Double_t fRa;
+    Double_t fDec;
+
+    TString fAlphaHName;          // name for histogram with alpha plots
+    TString fSkyHName;            // name for histogram with sky plots
+    TString fNexHName;            // name for canvas with Nex plot
+    Float_t fElaTime;             // elapsed time [min]
+
+    TObject *GetCatalog();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+
+public:
+    MSkyPlot(const char *name=NULL, const char *title=NULL);
+    ~MSkyPlot();
+
+    Double_t CalcLimit(Double_t *a, Double_t ls, Double_t ls2, Double_t dd2);
+
+    TH2D *GetHistSignif    () { return &fHistSignif;  }
+    TH2D *GetHistNexcess   () { return &fHistNexcess; }
+    TH2D *GetHistOn        () { return &fHistOn;      }
+    TH1D *GetHistSignifGaus() { return &fHistSignifGaus; }
+
+    Int_t GetSize()  const { return fHistAlpha->GetSize(); }
+
+    TH1D *GetAlphaPlot( const Int_t i=-1);
+    const TH1D *GetAlphaPlot( const Int_t=-1) const;
+
+    void ReadCuts(const TString parSCinit);
+
+    void SaveAlphaPlots(const TString stri2);
+    void SaveNexPlot(const TString stri3);
+    void SaveSkyPlots(TString stri);
+
+    void SetAlphaCut(Float_t alpha); 
+    void SetAlphaBGLimits(Float_t alphalow, Float_t alphalup); 
+
+    void SetMinDist(Float_t dist) { fMinDist = dist; } // Absolute minimum distance
+    void SetMaxDist(Float_t dist) { fMaxDist = dist; } // Absolute maximum distance
+    void SetSizeMin(Float_t size) { fSizeMin = size; } // Absolute minimum Size
+    void SetSizeMax(Float_t size) { fSizeMax = size; } // Absolute maximum Size
+    void SetSkyPlot(Float_t xmin, Float_t xmax, Float_t ymin, Float_t ymax, Float_t step);
+    void SetHadrCut(Float_t b)    { fHadrCut = b;    }  // hadronness cut
+
+    void SetOutputSkyName(TString outname2)     { fSkyHName = outname2; }
+    void SetNotSaveSkyPlots()                   { fSaveSkyPlots = kFALSE; }
+
+    void SetOutputAlphaName(TString outname1)   { fAlphaHName = outname1; }
+    void SetNotSaveAlphaPlots()                 { fSaveAlphaPlots = kFALSE; }
+
+    void SetOutputNexName(TString outname3)     { fNexHName = outname3; }
+    void SetElapsedTime(Float_t g)              { fElaTime = g; }
+    void SetNotSaveNexPlot()                    { fSaveNexPlot = kFALSE; }
+
+    void SetUseRF()                             { fUseRF = kTRUE; }
+
+    ClassDef(MSkyPlot, 1) //2D-histogram in alpha, x and y
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfold.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfold.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfold.cc	(revision 17960)
@@ -0,0 +1,3079 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s) : T. Bretz  02/2002 <mailto:tbretz@astro.uni-wuerzburg.de>   
+!               W. Wittek 09/2002 <mailto:wittek@mppmu.mpg.de>             
+!               R. Wagner, 11/2004 <mailto:rwagner@mppmu.mpg.de>           
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MUnfold
+//
+/////////////////////////////////////////////////////////////////////////////   
+#include "MUnfold.h"
+
+#include <TMath.h>
+#include <TRandom3.h>
+#include <TVector.h>
+#include <TMatrixD.h>
+#include <TMatrix.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TProfile.h>
+#include <TF1.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MUnfold);
+using namespace std;
+
+// -----------------------------------------------------------------------
+//
+// fcnSmooth     (used by SmoothMigrationMatrix)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function 
+//                                               to be minimized
+//
+static void fcnSmooth(Int_t &npar, Double_t *gin, Double_t &f, 
+               Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    Double_t a0 = par[0];
+    Double_t a1 = par[1];
+    Double_t a2 = par[2];
+
+    Double_t b0 = par[3];
+    Double_t b1 = par[4];
+    Double_t b2 = par[5];
+
+    // loop over bins of log10(E-true)
+    Double_t chi2 = 0.0;
+    Int_t npoints = 0;
+    Double_t func[20];
+
+    for (UInt_t j=0; j<gUnfold.fNb; j++)
+    {
+        Double_t yj   = ((double)j) + 0.5;
+        Double_t mean = a0 + a1*yj + a2*yj*yj + yj;
+        Double_t RMS  = b0 + b1*yj + b2*yj*yj;
+
+        if (RMS <= 0.0)
+        {
+            chi2 = 1.e20;
+            break;
+        }
+
+        // loop over bins of log10(E-est)
+
+        //.......................................
+        Double_t function;
+        Double_t sum=0.0;
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            Double_t xlow = (double)i;
+            Double_t xup  = xlow + 1.0;
+            Double_t xl  = (xlow- mean) / RMS;
+            Double_t xu  = (xup - mean) / RMS;
+            function = (TMath::Freq(xu) - TMath::Freq(xl));
+
+            //*fLog << "i, xl, xu, function = " <<  i <<  ",  "  << xl << ",  "
+            //     << xu  << ",  " << function << endl;
+
+            if (function < 1.e-10)
+                function = 0.0;
+
+            func[i] = function;
+            sum += function;
+        }
+
+        //      *fLog << "mean, RMS = "  << mean << ",  " << RMS
+        //     << ",   j , sum of function = " << j << ",  " << sum << endl;
+
+        //.......................................
+
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            if (sum != 0.0)
+                func[i] /= sum;
+
+            gUnfold.fMigSmoo(i,j) = func[i];
+            gUnfold.fMigChi2(i,j) = 0.0;
+
+            // if relative error is greater than 30 % ignore the point
+
+            if (gUnfold.fMigOrig(i,j)     != 0 &&
+                gUnfold.fMigOrigerr2(i,j) != 0 &&
+                func[i] != 0  )
+            {
+                if (gUnfold.fMigOrigerr2(i,j)/
+                    (gUnfold.fMigOrig(i,j)*gUnfold.fMigOrig(i,j)) <= 0.09)
+                {
+                    gUnfold.fMigChi2(i,j) =   ( gUnfold.fMigOrig(i,j) - func[i] )
+                        * ( gUnfold.fMigOrig(i,j) - func[i] )
+                        /   gUnfold.fMigOrigerr2(i,j);
+                    chi2 += gUnfold.fMigChi2(i,j);
+                    npoints += 1;
+                }
+            }
+        }
+        //.......................................
+
+    }
+    f = chi2;
+
+    //*fLog << "fcnSmooth : f = " << f << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        Int_t     NDF = npoints - npar;
+        Double_t prob = TMath::Prob(chi2, NDF);
+
+        gLog << "fcnSmooth : npoints, chi2, NDF, prob = " << npoints << ",  ";
+        gLog << chi2 << ",  " << NDF << ",  " << prob << endl;
+        gLog << "=======================================" << endl;
+    }
+}
+
+
+// -----------------------------------------------------------------------
+//
+// fcnTikhonov2     (used by Tikhonov2)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function F
+// the free parameters are the first (fNb-1) elements
+//                     of the normalized unfolded distribution
+//
+static void fcnTikhonov2(Int_t &npar, Double_t *gin, Double_t &f,
+                  Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    // (npar+1) is the number of bins of the unfolded distribuition (fNb)
+    //  npar    is the number of free parameters                    (fNb-1)
+
+    UInt_t npar1 = npar + 1;
+
+    UInt_t fNa = gUnfold.fNa;
+    UInt_t fNb = gUnfold.fNb;
+    if (npar1 != fNb)
+    {
+        gLog << "fcnTikhonov2 : inconsistency in number of parameters; npar, fNb = ";
+        gLog << npar << ",  " << fNb << endl;
+        //return;
+    }
+    npar1 = fNb;
+
+    TMatrixD p(npar1, 1);
+    TMatrixD &fVb = gUnfold.fVb;
+
+    // p is the normalized unfolded distribution
+    // sum(p(i,0)) from i=0 to npar is equal to 1
+    Double_t sum = 0.0;
+    for (Int_t i=0; i<npar; i++)
+    {
+        p(i,0) = par[i];
+        sum += par[i];
+    }
+    p(npar,0) = 1.0 - sum;
+
+
+    // all p(i,0) have to be greater than zero
+    for (UInt_t i=0; i<npar1; i++)
+        if (p(i,0) <= 0.0)
+        {
+            f = 1.e20;
+            return;
+        }
+
+    //.......................
+    // take least squares result for the normaliztion
+    TMatrixD alpha(gUnfold.fMigrat, TMatrixD::kMult, p);
+
+    //TMatrixD v4   (gUnfold.fVa, TMatrixD::kTransposeMult,
+    //                                 gUnfold.fVacovInv);
+    //TMatrixD norma(v4,  TMatrixD::kMult, gUnfold.fVa);
+
+    TMatrixD v5   (alpha, TMatrixD::kTransposeMult, gUnfold.fVacovInv);
+    TMatrixD normb(v5,    TMatrixD::kMult, alpha);
+
+    TMatrixD normc(v5,    TMatrixD::kMult, gUnfold.fVa);
+
+    Double_t norm  = normc(0,0)/normb(0,0);
+
+    //.......................
+
+    // b is the unnormalized unfolded distribution
+    // sum(b(i,0)) from i=0 to npar is equal to norm
+    //                       (the total number of events)
+    for (UInt_t i=0; i<npar1; i++)
+        fVb(i,0) = p(i,0) * norm;
+
+    TMatrixD Gb(gUnfold.fMigrat, TMatrixD::kMult, fVb);
+    TMatrixD v3(fNa, 1);
+    v3 = gUnfold.fVa;
+    v3 -= Gb;
+
+    TMatrixD v1(1,fNa);
+    for (UInt_t i=0; i<fNa; i++)
+    {
+        v1(0,i) = 0;
+        for (UInt_t j=0; j<fNa; j++)
+            v1(0,i) += v3(j,0) * gUnfold.fVacovInv(j,i) ;
+    }
+
+    for (UInt_t i = 0; i<fNa; i++)
+        gUnfold.Chi2(i,0) = v1(0,i) * v3(i,0);
+
+    Double_t chisqsum = 0;
+    for (Int_t i=0; i<gUnfold.Chi2.GetNrows(); i++)
+      chisqsum += gUnfold.Chi2(i, 0);
+    gUnfold.Chisq = chisqsum;
+    
+    //-----------------------------------------------------
+    // calculate 2nd derivative squared
+    // regularization term (second derivative squared)
+    gUnfold.SecDeriv = 0;
+    for (UInt_t j=1; j<(fNb-1); j++)
+     {
+         const Double_t temp =
+             + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+             - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+
+         gUnfold.SecDeriv += temp*temp;
+     }
+
+    gUnfold.ZerDeriv = 0;
+    for (UInt_t j=0; j<fNb; j++)
+        gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+    f = gUnfold.Chisq/2 * gUnfold.fW + gUnfold.SecDeriv;
+
+    //*fLog << "F=" << f      << " \tSecDeriv=" << gUnfold.SecDeriv
+    //     << " \tchi2="
+    //	  << gUnfold.Chisq << " \tfW=" << gUnfold.fW << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        //..............................................
+        // calculate external error matrix of the fitted parameters 'val'
+        // extend it with the covariances for y=1-sum(val)
+        Double_t emat[20][20];
+        Int_t    ndim = 20;
+        gMinuit->mnemat(&emat[0][0], ndim);
+
+        Double_t covv = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t cov = 0;
+            for (UInt_t k=0; k<(gUnfold.fNb-1); k++)
+                cov += emat[i][k];
+
+            emat[i][gUnfold.fNb-1] = -cov;
+            emat[gUnfold.fNb-1][i] = -cov;
+
+            covv += cov;
+        }
+        emat[gUnfold.fNb-1][gUnfold.fNb-1] = covv;
+
+        for (UInt_t i=0; i<gUnfold.fNb; i++)
+            for (UInt_t k=0; k<gUnfold.fNb; k++)
+                gUnfold.fVbcov(i,k) = emat[i][k] *norm*norm;
+
+        //-----------------------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        gUnfold.fResult.ResizeTo(gUnfold.fNb, 5);
+
+        Double_t sum = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t val;
+            Double_t err;
+            if (!gMinuit->GetParameter(i, val, err))
+            {
+                gLog << "Error getting parameter #" << i << endl;
+                return;
+            }
+
+            Double_t eplus;
+            Double_t eminus;
+            Double_t eparab;
+            Double_t gcc;
+            gMinuit->mnerrs(i, eplus, eminus, eparab, gcc);
+
+            gUnfold.fVb(i, 0)     = val    * norm;
+
+            gUnfold.fResult(i, 0) = val    * norm;
+            gUnfold.fResult(i, 1) = eparab * norm;
+            gUnfold.fResult(i, 2) = eplus  * norm;
+            gUnfold.fResult(i, 3) = eminus * norm;
+            gUnfold.fResult(i, 4) = gcc;
+            sum += val;
+        }
+        gUnfold.fVb(gUnfold.fNb-1, 0)     = (1.0-sum) * norm;
+
+        gUnfold.fResult(gUnfold.fNb-1, 0) = (1.0-sum) * norm;
+        gUnfold.fResult(gUnfold.fNb-1, 1) =
+            sqrt(gUnfold.fVbcov(gUnfold.fNb-1,gUnfold.fNb-1));
+        gUnfold.fResult(gUnfold.fNb-1, 2) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 3) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 4) = 1;
+        //..............................................
+
+        //-----------------------------------------------------
+        // calculate 0th derivative squared
+        gUnfold.ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        gUnfold.Entropy = 0;
+        for (UInt_t j=0; j<gUnfold.fNb; j++)
+            if (p(j,0) > 0)
+                gUnfold.Entropy += p(j,0) * log( p(j,0) );
+
+
+        //-----------------------------------------------------
+        // calculate SpurSigma
+        gUnfold.SpurSigma = 0.0;
+        for (UInt_t m=0; m<fNb; m++)
+            gUnfold.SpurSigma += gUnfold.fVbcov(m,m);
+        // *fLog << "SpurSigma =" << SpurSigma << endl;
+
+        //-----------------------------------------------------
+        gUnfold.SpurAR  = 0;
+        gUnfold.DiffAR2 = 0;
+
+        //-----------------------------------------------------
+        gUnfold.fNdf   = gUnfold.fNa;
+        gUnfold.fChisq   = gUnfold.Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          gUnfold.fChi2(i,0) = gUnfold.Chi2(i,0);
+	}
+
+
+        UInt_t iNdf = (UInt_t) (gUnfold.fNdf+0.5);
+
+        //*fLog << "fcnTikhonov2 : fW, chisq (from fcnF) = "
+        //     << gUnfold.fW << ",  " << gUnfold.fChisq << endl;
+
+        gUnfold.fProb = iNdf>0 ? TMath::Prob(gUnfold.fChisq, iNdf) : 0;
+    }
+}
+
+
+TH1 *MUnfold::DrawMatrixClone(const TMatrixD &m, Option_t *opt="")
+{
+    const Int_t nrows = m.GetNrows();
+    const Int_t ncols = m.GetNcols();
+
+    TMatrix m2(nrows, ncols);
+    for (int i=0; i<nrows; i++)
+        for (int j=0; j<ncols; j++)
+            m2(i, j) = m(i, j);
+
+    TH2F *hist = new TH2F(m2);
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+
+}
+
+
+TH1 *MUnfold::DrawMatrixColClone(const TMatrixD &m, Option_t *opt="", Int_t col=0)
+{
+    const Int_t nrows = m.GetNrows();
+
+    TVector vec(nrows);
+    for (int i=0; i<nrows; i++)
+        vec(i) = m(i, col);
+
+    TH1F *hist = new TH1F("TVector","",nrows,0,nrows);
+    for (int i=0; i<nrows; i++)
+      hist->SetBinContent(i+1, vec(i));
+    
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+}
+
+
+void MUnfold::PrintTH3Content(const TH3 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            *fLog << hist.GetBinContent(i,j,k) << " \t";
+      *fLog << endl << endl;
+    }
+}
+
+void MUnfold::PrintTH3Error(const TH3 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            *fLog << hist.GetBinError(i, j, k) << " \t";
+      *fLog << endl << endl;
+    }
+}
+
+void MUnfold::PrintTH2Content(const TH2 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            *fLog << hist.GetBinContent(i,j) << " \t";
+        *fLog << endl << endl;
+}
+
+void MUnfold::PrintTH2Error(const TH2 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            *fLog << hist.GetBinError(i, j) << " \t";
+        *fLog << endl << endl;
+}
+
+void MUnfold::PrintTH1Content(const TH1 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        *fLog << hist.GetBinContent(i) << " \t";
+    *fLog << endl << endl;
+}
+
+void MUnfold::PrintTH1Error(const TH1 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        *fLog << hist.GetBinError(i) << " \t";
+    *fLog << endl << endl;
+}
+
+void MUnfold::CopyCol(TMatrixD &m, const TH1 &h, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        m(i, col) = h.GetBinContent(i+1);
+}
+
+void MUnfold::CopyCol(TH1 &h, const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        h.SetBinContent(i+1, m(i, col));
+}
+
+void MUnfold::CopyH2M(TMatrixD &m, const TH2 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+            m(i, j) = h.GetBinContent(i+1, j+1);
+}
+
+void MUnfold::CopySqr(TMatrixD &m, const TH1 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+        {
+            const Double_t bin =  h.GetBinContent(i+1, j+1);
+            m(i, j) = bin*bin;
+        }
+}
+
+Double_t MUnfold::GetMatrixSumRow(const TMatrixD &m, Int_t row)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(row, i);
+
+    return sum;
+}
+
+Double_t MUnfold::GetMatrixSumDiag(const TMatrixD &m)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, i);
+
+    return sum;
+}
+
+Double_t MUnfold::GetMatrixSumCol(const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, col);
+
+    return sum;
+}
+
+Double_t MUnfold::GetMatrixSum(const TMatrixD &m)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += GetMatrixSumRow(m, i);
+
+    return sum;
+}
+
+
+Double_t MUnfold::CalcSpurSigma(TMatrixD &T, Double_t norm)
+{
+  Double_t spursigma = 0;
+  
+  for (UInt_t a=0; a<fNb; a++)
+    {
+      for (UInt_t b=0; b<fNb; b++)
+	{
+	  fVbcov(a,b) = 0;
+	  
+	  for (UInt_t c=0; c<fNa; c++)
+	    for (UInt_t d=0; d<fNa; d++)
+	      fVbcov(a,b) += T(a,d)*fVacov(d,c)*T(b,c);
+	  
+	  fVbcov(a,b) *= norm*norm;
+	}
+      spursigma += fVbcov(a,a);
+    }
+  
+  return spursigma;
+}
+
+
+MUnfold::MUnfold(TH1D &ha, TH2D &hacov, TH2D &hmig)
+        : fVEps(hmig.GetYaxis()->GetNbins(),1), fVEps0(fVEps, 0)
+    {
+        // ha      is the distribution to be unfolded
+        // hacov   is the covariance matrix of ha
+        // hmig    is the migration matrix;
+        //         this matrix will be used in the unfolding
+        //         unless SmoothMigrationMatrix(*hmigrat) is called;
+        //         in the latter case hmigrat is smoothed
+        //         and the smoothed matrix is used in the unfolding
+
+        // Eigen values of the matrix G, which are smaller than EpsLambda
+        // will be considered as being zero
+        EpsLambda = 1.e-10;
+        fW = 0.0;
+
+        fNa  = hmig.GetXaxis()->GetNbins();
+        const Double_t alow = hmig.GetXaxis()->GetXmin();
+        const Double_t aup  = hmig.GetXaxis()->GetXmax();
+
+        fNb  = hmig.GetYaxis()->GetNbins();
+        const Double_t blow = hmig.GetYaxis()->GetXmin();
+        const Double_t bup  = hmig.GetYaxis()->GetXmax();
+
+
+        UInt_t Na = ha.GetNbinsX();
+        if (fNa != Na)
+        {
+            *fLog << "MUnfold::MUnfold : dimensions do not match,  fNa = ";
+            *fLog << fNa << ",   Na = " << Na << endl;
+        }
+
+        *fLog << "MUnfold::MUnfold :" << endl;
+        *fLog << "==================" << endl;
+        *fLog << "   fNa = " << fNa << ",   fNb = " << fNb << endl;
+
+        // ------------------------
+
+        fVa.ResizeTo(fNa, 1);
+        CopyCol(fVa, ha, 0);
+
+        *fLog << "   fVa = ";
+
+        for (UInt_t i=0; i<fNa; i++)
+            *fLog << fVa(i,0) << " \t";
+        *fLog << endl;
+
+        Double_t vaevents = GetMatrixSumCol(fVa, 0);
+        *fLog << "   Total number of events in fVa = " << vaevents << endl;
+
+        // ------------------------
+
+        fChi2.ResizeTo(fNa,1);
+        Chi2.ResizeTo(fNa,1);
+
+        // ------------------------
+
+        fVacov.ResizeTo(fNa, fNa);
+        fSpurVacov = 0;
+
+        CopyH2M(fVacov, hacov);
+
+        fVapoints = 0;
+        for (UInt_t i=0; i<fNa; i++)
+            if (fVa(i,0)>0 && fVacov(i,i)<fVa(i,0)*fVa(i,0))
+                fVapoints++;
+
+        fSpurVacov = GetMatrixSumDiag(fVacov);
+
+        //*fLog << "MUnfold::MUnfold :   fVacov = " << endl;
+        //*fLog << "==============================" << endl;
+        //fVacov.Print();
+
+        *fLog << "   Number of significant points in fVa = ";
+        *fLog << fVapoints << endl;
+
+        *fLog << "   Spur of fVacov = ";
+        *fLog << fSpurVacov << endl;
+
+        // ------------------------
+
+        fVacovInv.ResizeTo(fNa, fNa);
+        fVacovInv = fVacov;
+        fVacovInv.InvertPosDef();
+
+        //*fLog << "MUnfold::MUnfold :   fVacovInv = " << endl;
+        //*fLog << "==================================" << endl;
+        //fVacovInv.Print();
+
+        // ------------------------
+        // fMigrat is the migration matrix to be used in the unfolding;
+        // fMigrat may be overwritten by SmoothMigrationMatrix
+
+        fMigrat.ResizeTo(fNa, fNb); // row, col
+
+        CopyH2M(fMigrat, hmig);
+
+
+        // ------------------------
+
+        fMigraterr2.ResizeTo(fNa, fNb); // row, col
+        CopySqr(fMigraterr2, hmig);
+
+        // normaxlize
+
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            const Double_t sum = GetMatrixSumCol(fMigrat, j);
+
+            if (sum==0)
+                continue;
+
+            TMatrixDColumn col1(fMigrat, j);
+            col1 *= 1./sum;
+
+            TMatrixDColumn col2(fMigraterr2, j);
+            col2 *= 1./(sum*sum);
+        }
+
+        //*fLog << "MUnfold::MUnfold :   fMigrat = " << endl;
+        //*fLog << "===============================" << endl;
+        //fMigrat.Print();
+
+        //*fLog << "MUnfold::MUnfold :   fMigraterr2 = " << endl;
+        //*fLog << "===================================" << endl;
+        //fMigraterr2.Print();
+
+        // ------------------------
+        G.ResizeTo(fNa, fNa);
+        EigenValue.ResizeTo(fNa);
+        Eigen.ResizeTo(fNa, fNa);
+
+        fMigOrig.ResizeTo(fNa, fNb); 
+        fMigOrigerr2.ResizeTo(fNa, fNb); 
+
+        fMigSmoo.ResizeTo    (fNa, fNb); 
+        fMigSmooerr2.ResizeTo(fNa, fNb); 
+        fMigChi2.ResizeTo    (fNa, fNb); 
+
+        // ------------------------
+
+        fVEps0 = 1./fNb;
+
+        //*fLog << "MUnfold::MUnfold :   Default prior distribution fVEps = " << endl;
+        //*fLog << "========================================================" << endl;
+        //fVEps.Print();
+
+        // ------------------------
+
+        fVb.ResizeTo(fNb,1);
+        fVbcov.ResizeTo(fNb,fNb);
+
+        // ----------------------------------------------------
+        // number and range of weights to be scanned
+        Nix  = 30;
+        xmin = 1.e-5;
+        xmax = 1.e5;
+        dlogx = (log10(xmax)-log10(xmin)) / Nix;
+
+        SpSig.ResizeTo (Nix);
+        SpAR.ResizeTo  (Nix);
+        chisq.ResizeTo (Nix);
+        SecDer.ResizeTo(Nix);
+        ZerDer.ResizeTo(Nix);
+        Entrop.ResizeTo(Nix);
+        DAR2.ResizeTo  (Nix);
+        Dsqbar.ResizeTo(Nix);
+
+        //------------------------------------
+        // plots as a function of the iteration  number
+
+        hBchisq = new TH1D("Bchisq", "chisq",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpAR  = new TH1D("BSpAR", "SpurAR",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpAR  = new TH1D("BDSpAR", "Delta(SpurAR)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpSig = new TH1D("BSpSig", "SpurSigma/SpurC",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpSig = new TH1D("BDSpSig", "Delta(SpurSigma/SpurC)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSecDeriv = new TH1D("BSecDeriv", "Second Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSecDeriv = new TH1D("BDSecDeriv", "Delta(Second Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBZerDeriv = new TH1D("BZerDeriv", "Zero Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDZerDeriv = new TH1D("BDZerDeriv", "Delta(Zero Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBEntropy = new TH1D("BEntrop", "Entropy",
+                             Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDEntropy = new TH1D("BDEntrop", "Delta(Entropy)",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDAR2 = new TH1D("BDAR2", "norm(AR-AR+)",
+                          Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBD2bar = new TH1D("BD2bar", "(b_unfolded-b_ideal)**2",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        //-------------------------------------
+        // original migration matrix
+        fhmig = new TH2D("fMigrat", "Migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        fhmig->Sumw2();
+
+        //-------------------------------------
+        // smoothed migration matrix
+        shmig = new TH2D("sMigrat", "Smoothed migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        shmig->Sumw2();
+
+        //-------------------------------------
+        // chi2 contributions for smoothing of migration matrix
+        shmigChi2 = new TH2D("sMigratChi2", "Chi2 contr. for smoothing",
+                             fNa, alow, aup, fNb, blow, bup);
+
+        //-------------------------------------
+        // eigen values of matrix G = M * M(transposed)
+        hEigen = new TH1D("Eigen", "Eigen values of M*MT",
+                          fNa, 0.5, fNa+0.5);
+
+        //------------------------------------
+        // Ideal distribution
+        
+        fhb0 = new TH1D("fhb0", "Ideal distribution", fNb, blow, bup);
+        fhb0->Sumw2();
+        
+
+        //------------------------------------
+        // Distribution to be unfolded
+        fha = new TH1D("fha", "Distribution to be unfolded", fNa, alow, aup);
+        fha->Sumw2();
+
+        //------------------------------------
+        // Prior distribution
+        hprior = new TH1D("Prior", "Prior distribution", fNb, blow, bup);
+
+        //-----------------------------S-------
+        // Unfolded distribution
+        hb = new TH1D("DataSp", "Unfolded distribution", fNb, blow, bup);
+        hb->Sumw2();
+
+    }
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+    MUnfold::~MUnfold()
+    {
+//       if (hBchisq) delete hBchisq;
+//       if (hBSpAR) delete hBSpAR;
+//       if (hBDSpAR) delete hBDSpAR;
+//       if (hBSpSig) delete hBSpSig;
+//       if (hBDSpSig) delete hBDSpSig;
+//       if (hBSecDeriv) delete hBSecDeriv;
+//       if (hBSecDeriv) delete hBDSecDeriv;
+//       if (hBZerDeriv) delete hBZerDeriv;
+//       if (hBDZerDeriv) delete hBDZerDeriv;
+//       if (hBEntropy) delete hBEntropy;
+//       if (hBDEntropy) delete hBDEntropy;
+//       if (hBDAR2) delete hBDAR2;
+//       if (hBD2bar) delete hBD2bar;
+//       if (fhmig) delete fhmig;
+//       if (shmig) delete shmig;
+//       if (shmigChi2) delete shmigChi2;
+//       if (hEigen) delete hEigen;
+//       if (fhb0) delete fhb0;
+//       if (fha) delete fha;
+//       if (hprior) delete hprior;
+//       if (hb) delete hb;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a constant
+    //
+    void MUnfold::SetPriorConstant()
+    {
+        fVEps0 = 1./fNb;
+
+        CopyCol(*hprior, fVEps);
+
+        //*fLog << "SetPriorConstant : Prior distribution fVEps = " << endl;
+        //*fLog << "==============================================" << endl;
+        //fVEps.Print();
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Take prior distribution from the histogram 'ha'
+    // which may have a different binning than 'hprior'
+    //
+    Bool_t MUnfold::SetPriorRebin(TH1D &ha)
+    {
+
+        // ------------------------------------------------------------------
+        //
+        // fill the contents of histogram 'ha' into the histogram 'hprior';
+        // the histograms need not have the same binning;
+        // if the binnings are different, the bin contents of histogram 'ha'
+        //    are distributed properly (linearly) over the bins of 'hprior'
+        //
+
+        const Int_t    na   = ha.GetNbinsX();
+        const Double_t alow = ha.GetBinLowEdge(1);
+        const Double_t aup  = ha.GetBinLowEdge(na+1);
+
+        const Int_t    nb   = hprior->GetNbinsX();
+        const Double_t blow = hprior->GetBinLowEdge(1);
+        const Double_t bup  = hprior->GetBinLowEdge(nb+1);
+
+        // check whether there is an overlap
+        //       between the x ranges of the 2 histograms
+        if (alow>bup || aup<blow)
+        {
+            *fLog << "Rebinning not possible because there is no overlap of the x ranges of the two histograms" << endl;
+            return kFALSE;
+        }
+
+        // there is an overlap
+        //********************
+        Double_t sum = 0;
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t yl = hprior->GetBinLowEdge(j);
+            const Double_t yh = hprior->GetBinLowEdge(j+1);
+
+            // search bins of histogram ha which contribute
+            // to bin j of histogram hb
+            //----------------
+            Int_t il=0;
+            Int_t ih=0;
+            for (Int_t i=2; i<=na+1; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                if (xl>yl)
+                {
+                    il = i-1;
+
+                    //.................................
+                    ih = 0;
+                    for (Int_t k=(il+1); k<=(na+1); k++)
+                    {
+                        const Double_t xh = ha.GetBinLowEdge(k);
+                        if (xh >= yh)
+                        {
+                            ih = k-1;
+                            break;
+                        }
+                    }
+                    //.................................
+                    if (ih == 0)
+                        ih = na;
+                    break;
+                }
+            }
+            //----------------
+            if (il == 0)
+            {
+                *fLog << "Something is wrong " << endl;
+                *fLog << "          na, alow, aup = " << na << ",  " << alow
+                    << ",  " << aup << endl;
+                *fLog << "          nb, blow, bup = " << nb << ",  " << blow
+                    << ",  " << bup << endl;
+                return kFALSE;
+            }
+
+            Double_t content=0;
+            // sum up the contribution to bin j
+            for (Int_t i=il; i<=ih; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                const Double_t xh = ha.GetBinLowEdge(i+1);
+                const Double_t bina = xh-xl;
+
+                if (xl<yl  &&  xh<yh)
+                    content += ha.GetBinContent(i) * (xh-yl) / bina;
+                else
+                    if (xl<yl  &&  xh>=yh)
+                        content += ha.GetBinContent(i) * (yh-yl) / bina;
+                    else
+                        if (xl>=yl  &&  xh<yh)
+                            content += ha.GetBinContent(i);
+                        else if (xl>=yl  &&  xh>=yh)
+                            content += ha.GetBinContent(i) * (yh-xl) / bina;
+            }
+            hprior->SetBinContent(j, content);
+            sum += content;
+        }
+
+        // normalize histogram hb
+        if (sum==0)
+        {
+            *fLog << "histogram hb is empty; sum of weights in ha = ";
+            *fLog << ha.GetSumOfWeights() << endl;
+            return kFALSE;
+        }
+
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t content = hprior->GetBinContent(j)/sum;
+            hprior->SetBinContent(j, content);
+            fVEps0(j-1) = content;
+        }
+
+        //*fLog << "SetPriorRebin : Prior distribution fVEps = " << endl;
+        //*fLog << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set prior distribution to a given distribution 'hpr'
+    //
+    Bool_t MUnfold::SetPriorInput(TH1D &hpr)
+    {
+        CopyCol(fVEps, hpr);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+
+        if (sum<=0)
+        {
+            *fLog << "MUnfold::SetPriorInput: invalid prior distribution" << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+
+        CopyCol(*hprior, fVEps);
+
+        //*fLog << "SetPriorInput : Prior distribution fVEps = " << endl;
+        //*fLog << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a power law
+    // use input distribution 'hprior' only
+    //           for defining the histogram parameters
+    //
+    Bool_t MUnfold::SetPriorPower(Double_t gamma)
+    {
+        // generate distribution according to a power law
+        //                        dN/dE = E^{-gamma}
+        //  or with y = lo10(E),  E = 10^y :
+        //                        dN/dy = ln10 * 10^{y*(1-gamma)}
+        TH1D hpower(*hprior);
+
+        const UInt_t   nbin = hprior->GetNbinsX();
+        const Double_t xmin = hprior->GetBinLowEdge(1);
+        const Double_t xmax = hprior->GetBinLowEdge(nbin+1);
+
+        *fLog << "nbin, xmin, xmax = " << nbin << ",  ";
+        *fLog << xmin << ",  " << xmax << endl;
+
+        TF1* fpow = new TF1("fpow", "pow(10.0, x*(1.0-[0]))", xmin,xmax);
+        fpow->SetParName  (0,"gamma");
+        fpow->SetParameter(0, gamma );
+
+        hpower.FillRandom("fpow", 100000);
+
+        // fill prior distribution
+        CopyCol(fVEps, hpower);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+        if (sum <= 0)
+        {
+            *fLog << "MUnfold::SetPriorPower : invalid prior distribution"  << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+        CopyCol(*hprior, fVEps);
+
+        //*fLog << "SetPriorPower : Prior distribution fVEps = " << endl;
+        //*fLog << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set the initial weight
+    //
+    Bool_t MUnfold::SetInitialWeight(Double_t &weight)
+    {
+        if (weight == 0.0)
+        {
+            TMatrixD v1(fVa, TMatrixD::kTransposeMult, fVacovInv);
+            TMatrixD v2(v1, TMatrixD::kMult, fVa);
+            weight = 1./sqrt(v2(0,0));
+        }
+
+        *fLog << "MUnfold::SetInitialWeight : Initial Weight = "
+            << weight << endl;
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Print the unfolded distribution
+    //
+    void MUnfold::PrintResults()
+    {
+        *fLog << bintitle << endl;
+        *fLog << "PrintResults : Unfolded distribution fResult " << endl;
+        *fLog << "=============================================" << endl;
+        //*fLog << "val, eparab, eplus, eminus, gcc = "  << endl;
+
+        for (UInt_t i=0; i<fNb; i++)
+        {
+	  //    *fLog << fResult(i, 0) << " \t";
+          //  *fLog << fResult(i, 1) << " \t";
+          //  *fLog << fResult(i, 2) << " \t";
+          //  *fLog << fResult(i, 3) << " \t";
+          //  *fLog << fResult(i, 4) <<  endl;
+        }
+        *fLog << "Chisquared, NDF, chi2 probability, ixbest = "
+            << fChisq << ",  "
+            << fNdf << ",  " << fProb << ",  " << ixbest << endl;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Schmelling  : unfolding by minimizing the function Z
+    //               by Gauss-Newton iteration
+    //
+    //               the weights are scanned between
+    //               1.e-5*fWinitial and 1.e5*fWinitial
+    //
+    Bool_t MUnfold::Schmelling(TH1D &hb0)
+    {
+    
+        //======================================================================
+        // copy ideal distribution
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+    
+        //-----------------------------------------------------------------------
+        // Initialization
+        // ==============
+
+        Int_t numGiteration;
+        Int_t MaxGiteration = 1000;
+
+        TMatrixD alpha;
+        alpha.ResizeTo(fNa, 1);
+
+
+        //-----------------------------------------------------------------------
+        // Newton iteration
+        // ================
+
+        Double_t dga2;
+        Double_t dga2old;
+        Double_t EpsG = 1.e-12;
+
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        TMatrixD gamma (fNa, 1);
+        TMatrixD dgamma(fNa, 1);
+
+        Double_t fWinitial;
+        fWinitial = 0.0;
+        SetInitialWeight(fWinitial);
+        // for my example this fWinitial was not good; therefore :
+        fWinitial = 1.0;
+
+        Int_t ix;
+        Double_t xiter;
+
+        //--------   start  scanning weights   --------------------------
+        // if full == kFALSE   only quantities necessary for the Gauss-Newton
+        //                     iteration are calculated in SchmellCore
+        // if full == kTRUE    in addition the unfolded distribution,
+        //                     its covariance matrix and quantities like
+        //                     Chisq, SpurAR, etc. are computed in SchmellCore
+        //Bool_t full;
+        //full = kFALSE;
+        Int_t full;
+
+        *fLog << "Schmelling : start loop over weights" << endl;
+
+        dga2 = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            xiter = pow(10.0,log10(xmin)+ix*dlogx) * fWinitial;
+
+            //----------   start Gauss-Newton iteration   ----------------------
+            numGiteration = 0;
+
+            // if there was no convergence and the starting gamma was != 0
+            // redo unfolding for the same weight starting with gamma = 0
+            //
+            Int_t gamma0 = 0;
+            while (1)
+	    {
+              if (dga2 > EpsG)
+	      {
+                gamma0 = 1;
+                gamma.Zero();
+	      }
+
+              dga2 = 1.e20;
+
+              while (1)
+              {
+                dga2old = dga2;
+
+                full = 0;
+                SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+                gamma += dgamma;
+
+                //*fLog << "Schmelling : ix, numGiteration, dga2, dga2old = "
+                //     << ix << ",  " << numGiteration << ",  "
+                //     << dga2 << ",  " << dga2old << endl;
+
+                numGiteration += 1;
+
+                // convergence
+                if (dga2 < EpsG)
+                    break;
+
+                // no convergence
+                if (numGiteration > MaxGiteration)
+                    break;
+
+                // gamma doesn't seem to change any more
+                if (fabs(dga2-dga2old) < EpsG/100.)
+                    break;
+              }
+              //----------   end Gauss-Newton iteration   ------------------------
+              if (dga2<EpsG || gamma0 != 0) break;
+	    }
+
+            // if Gauss-Newton iteration has not converged
+            // go to next weight
+            if (dga2 > EpsG)
+            {
+                *fLog << "Schmelling : Gauss-Newton iteration has not converged;"
+                    << "   numGiteration = " << numGiteration << endl;
+                *fLog << "             ix, dga2, dga2old = " << ix << ",  "
+                    << dga2 << ",  " << dga2old << endl;
+                continue;
+            }
+
+            //*fLog << "Schmelling : Gauss-Newton iteration has converged;" << endl;
+            //*fLog << "==================================================" << endl;
+            //*fLog << "             numGiteration = " << numGiteration << endl;
+            //*fLog << "             ix, dga2 = " << ix << ",  " << dga2 << endl;
+
+            // calculated quantities which will be useful for determining
+            // the best weight (Chisq, SpurAR, ...)
+            //full = kTRUE;
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)  = SpurAR;
+            SpSig(ix) = SpurSigma;
+            chisq(ix) = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+        }
+        //----------   end of scanning weights   -------------------------------
+        *fLog << "Schmelling : end of loop over weights" << endl;
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xbin = log10(xmin)+ix*dlogx;
+            xiter = pow(10.0,xbin) * fWinitial;
+
+            Int_t bin;
+            bin = hBchisq->FindBin( xbin );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+
+        // Select best weight
+        SelectBestWeight();
+
+        if (ixbest < 0.0)
+        {
+            *fLog << "Schmelling : no solution found; " << endl;
+            return kFALSE;
+        }
+
+        // do the unfolding using the best weight
+        //full = kTRUE;
+
+
+        xiter = pow(10.0,log10(xmin)+ixbest*dlogx) * fWinitial;
+
+        //----------   start Gauss-Newton iteration   ----------------------
+        numGiteration = 0;
+        gamma.Zero();
+        dga2 = 1.e20;
+
+        while (1)
+        {
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+            gamma += dgamma;
+
+            //*fLog << "Schmelling : sum(dgamma^2) = " << dga2 << endl;
+
+            numGiteration += 1;
+
+            if (numGiteration > MaxGiteration)
+                break;
+
+            if (dga2 < EpsG)
+                break;
+        }
+        //----------   end Gauss-Newton iteration   ------------------------
+
+
+        //-----------------------------------------------------------------------
+        // termination stage
+        // =================
+
+        *fLog << "Schmelling : best solution found; " << endl;
+        *fLog << "==================================" << endl;
+        *fLog << "             xiter, ixbest, numGiteration, Chisq = "
+            << xiter << ",  " << ixbest << ",  "
+            << numGiteration << ",  " << Chisq << endl;
+
+        //------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        fNdf = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0; 
+	}
+
+        //--------------------------------------------------------
+
+        *fLog << "Schmelling : gamma = " << endl;
+        for (UInt_t i=0; i<fNa; i++)
+            *fLog << gamma(i,0) << " \t";
+        *fLog << endl;
+
+        return kTRUE;
+    }
+
+
+
+
+    // -----------------------------------------------------------------------
+    //
+    // SchmellCore     main part of Schmellings calculations
+    //
+    void MUnfold::SchmellCore(Int_t full, Double_t &xiter, TMatrixD &gamma,
+                     TMatrixD &dgamma, Double_t &dga2)
+    {
+        Double_t norm;
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        //--------------------------------------------------------
+        //--      determine the probability vector p
+
+
+        TMatrixD v3(gamma, TMatrixD::kTransposeMult, fMigrat);
+        TMatrixD v4(TMatrixD::kTransposed, v3);
+        d = v4;
+        Double_t dmax  = -1.e10;
+        for (UInt_t j=0; j<fNb; j++)
+            if (d(j,0)>dmax)
+                dmax = d(j,0);
+
+        Double_t psum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            d(j,0) -= dmax;
+            p(j,0)  = fVEps0(j)*exp(xiter*d(j,0));
+            psum += p(j,0);
+        }
+
+        p *= 1.0/psum;
+
+        //--      get the vector alpha
+
+        TMatrixD alpha(fMigrat, TMatrixD::kMult, p);
+
+        //--      determine the current normalization
+
+        TMatrixD v2   (alpha, TMatrixD::kTransposeMult, fVacovInv);
+        TMatrixD normb(v2,    TMatrixD::kMult, alpha);
+
+        TMatrixD normc(v2,    TMatrixD::kMult, fVa);
+
+        norm  = normc(0,0)/normb(0,0);
+
+        //--------------------------------------------------------
+        //--      determine the scaled slope vector s and Hessian H
+
+        TMatrixD Zp(fNa,1);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Zp(i,0) = norm*alpha(i,0) - fVa(i,0);
+            for (UInt_t k=0; k<fNa; k++)
+                Zp(i,0) += gamma(k,0)*fVacov(k,i);
+        }
+
+
+        TMatrixD Q  (fNa, fNa);
+        TMatrixD wZdp(fNa, fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Q(i,j) = - alpha(i,0)*alpha(j,0);
+                for (UInt_t k=0; k<fNb; k++)
+                    Q(i,j) += fMigrat(i,k)*fMigrat(j,k)*p(k,0);
+                wZdp(i,j) = xiter*norm*Q(i,j) + fVacov(i,j);
+            }
+        }
+
+        //--      invert H and calculate the next Newton step
+
+        Double_t determ = 1.0;
+        wZdp_inv = wZdp;
+        wZdp_inv.Invert(&determ);
+
+        if(determ == 0.0)
+        {
+            *fLog << "SchmellCore: matrix inversion for H failed" << endl;
+            return;
+        }
+
+
+        dga2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            dgamma(i,0) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                dgamma(i,0) -= wZdp_inv(i,j)*Zp(j,0);
+            dga2 += dgamma(i,0)*dgamma(i,0);
+        }
+
+        if (full == 0)
+            return;
+
+        //--------------------------------------------------------
+        //--      determine chi2 and dNdf (#measurements ignored)
+        Double_t dNdf = 0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Chi2(i,0) = 0;
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Chi2(i,0) += fVacov(i,j) * gamma(i,0) * gamma(j,0);
+                dNdf       += fVacov(i,j) * wZdp_inv(j,i);
+            }
+        }
+        Chisq = GetMatrixSumCol(Chi2, 0);
+        SpurAR = fNa - dNdf;
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        TMatrixD AR(fNa, fNa);
+        DiffAR2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                AR(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    AR(i,j) +=  fVacov(i,k) * wZdp_inv(k,j);
+                DiffAR2 += AR(i,j) * AR(i,j);
+            }
+        }
+
+        //--------------------------------------------------------
+        //--      fill distribution b(*)
+        fVb = p;
+        fVb *= norm;
+
+        //--      determine the covariance matrix of b (very expensive)
+
+        TMatrixD T(fNb,fNa);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                T(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    T(i,j) += xiter*wZdp_inv(k,j)*(fMigrat(k,i)-alpha(k,0))*p(i,0);
+            }
+        }
+
+        SpurSigma = CalcSpurSigma(T, norm);
+
+        //--------------------------------------------------------
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            Double_t temp =
+                + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //--------------------------------------------------------
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Smooth migration matrix
+    //              by fitting a function to the migration matrix
+    //
+    Bool_t MUnfold::SmoothMigrationMatrix(TH2D &hmigorig)
+    {
+        // copy histograms into matrices; the matrices will be used in fcnSmooth
+        // ------------------------
+
+      
+      //*fLog << "MUnfold::SmoothMigrationMatrix : fNa, fNb = " << fNa << ",  " << fNb << endl;
+
+      //*fLog << "MUnfold::SmoothMigrationMatrix:   fMigOrig = "  << endl;
+      //*fLog << "========================================"  << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrig(i, j)     = hmigorig.GetBinContent(i+1, j+1);
+	        //*fLog << fMigOrig(i, j) << " \t";
+            }
+            //*fLog << endl;
+        }
+      
+
+        // ------------------------
+
+      
+        //*fLog << "MUnfold::SmoothMigrationMatrix :   fMigOrigerr2 = " << endl;
+        //*fLog << "=============================================" << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrigerr2(i, j) =   hmigorig.GetBinError(i+1, j+1)
+                    * hmigorig.GetBinError(i+1, j+1);
+
+                //*fLog << fMigOrigerr2(i, j) << " \t";
+            }
+            //*fLog << endl;
+        }
+      
+
+        // ------------------------
+        // the number of free parameters (npar) is equal to 6:
+        //     a0mean, a1mean, a2mean     
+        //     <log10(Eest)>    = a0 + a1*log10(Etrue) + a2*SQR(log10(Etrue))
+        //                                                     + log10(Etrue)  
+        //     b0RMS,  b1RMS, b2RMS      
+        //     RMS(log10(Eest)) = b0 + b1*log10(Etrue) + b2*SQR(log10(Etrue))
+        // 
+        UInt_t npar = 6;
+
+        if (npar > 20)
+        {
+            *fLog << "MUnfold::SmoothMigrationMatrix : too many parameters,  npar = "
+                << npar << endl;
+            return kFALSE;
+        }
+
+
+        //..............................................
+        // Find reasonable starting values for a0, a1 and b0, b1
+
+        Double_t xbar   = 0.0;
+        Double_t xxbar  = 0.0;
+
+        Double_t ybarm  = 0.0;
+        Double_t xybarm = 0.0;
+
+        Double_t ybarR  = 0.0;
+        Double_t xybarR = 0.0;
+
+        Double_t Sum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            Double_t x = (double)j + 0.5;
+
+            Double_t meany = 0.0;
+            Double_t RMSy  = 0.0;
+            Double_t sum   = 0.0;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                Double_t y = (double)i + 0.5;
+                meany +=   y * fMigOrig(i, j);
+                RMSy  += y*y * fMigOrig(i, j);
+                sum   +=       fMigOrig(i, j);
+            }
+            if (sum > 0.0)
+            {
+                meany  = meany / sum;
+                RMSy   =  RMSy / sum  - meany*meany;
+                RMSy = sqrt(RMSy);
+
+                Sum += sum;
+                xbar  +=   x * sum;
+                xxbar += x*x * sum;
+
+                ybarm  +=   meany * sum;
+                xybarm += x*meany * sum;
+
+                ybarR  +=   RMSy  * sum;
+                xybarR += x*RMSy  * sum;
+            }
+        }
+
+        if (Sum > 0.0)
+        {
+            xbar   /= Sum;
+            xxbar  /= Sum;
+
+            ybarm  /= Sum;
+            xybarm /= Sum;
+
+            ybarR  /= Sum;
+            xybarR /= Sum;
+        }
+
+        Double_t a1start = (xybarm - xbar*ybarm) / (xxbar - xbar*xbar);
+        Double_t a0start = ybarm - a1start*xbar;
+        a1start = a1start - 1.0;
+
+        Double_t b1start = (xybarR - xbar*ybarR) / (xxbar - xbar*xbar);
+        Double_t b0start = ybarR - b1start*xbar;
+
+        *fLog << "MUnfold::SmoothMigrationMatrix : " << endl;
+        *fLog << "============================" << endl;
+        *fLog << "a0start, a1start = " << a0start << ",  " << a1start << endl;
+        *fLog << "b0start, b1start = " << b0start << ",  " << b1start << endl;
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        sprintf(&name[0][0], "a0mean");
+        vinit[0] = a0start;
+        //vinit[0] = 1.0;
+        step[0]  = 0.1;
+        limlo[0] = 0.0;
+        limup[0] = 0.0;
+        fix[0]   = 0;
+
+        sprintf(&name[1][0], "a1mean");
+        vinit[1] = a1start;
+        //vinit[1] = 0.0;
+        step[1]  = 0.1;
+        limlo[1] = 0.0;
+        limup[1] = 0.0;
+        fix[1]   = 0;
+
+        sprintf(&name[2][0], "a2mean");
+        vinit[2] = 0.0;
+        step[2]  = 0.1;
+        limlo[2] = 0.0;
+        limup[2] = 0.0;
+        fix[2]   = 0;
+
+        sprintf(&name[3][0], "b0RMS");
+        vinit[3] = b0start;
+          //vinit[3] = 0.8;
+        step[3]  = 0.1;
+        limlo[3] = 1.e-20;
+        limup[3] = 10.0;
+        fix[3]   = 0;
+
+        sprintf(&name[4][0], "b1RMS");
+        vinit[4] = b1start;
+        //vinit[4] = 0.0;
+        step[4]  = 0.1;
+        limlo[4] = 0.0;
+        limup[4] = 0.0;
+        fix[4]   = 0;
+
+        sprintf(&name[5][0], "b2RMS");
+        vinit[5] = 0.0;
+        step[5]  = 0.1;
+        limlo[5] = 0.0;
+        limup[5] = 0.0;
+        fix[5]   = 0;
+
+
+        if ( CallMinuit(fcnSmooth, npar, name, vinit,
+                        step, limlo, limup, fix) )
+        {
+
+            // ------------------------
+            // fMigrat is the migration matrix to be used in the unfolding;
+            // fMigrat, as set by the constructor, is overwritten
+            //          by the smoothed migration matrix
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigrat(i, j) = fMigSmoo(i, j);
+
+            // ------------------------
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigraterr2(i, j) = fMigSmooerr2(i, j);
+
+
+            // normalize
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                Double_t sum = 0.0;
+                for (UInt_t i=0; i<fNa; i++)
+                    sum += fMigrat(i, j);
+
+                //*fLog << "SmoothMigrationMatrix : normalization fMigrat; j, sum + "
+                //     << j << ",  " << sum << endl;
+
+                if (sum == 0.0)
+                    continue;
+
+                for (UInt_t i=0; i<fNa; i++)
+                {
+                    fMigrat(i, j)     /= sum;
+                    fMigraterr2(i, j) /= (sum*sum);
+                }
+            }
+
+            *fLog << "MUnfold::SmoothMigrationMatrix :   fMigrat = "  << endl;
+            *fLog << "========================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    *fLog << fMigrat(i, j) << " \t";
+                *fLog << endl;
+            }
+
+	    /*
+            *fLog << "MUnfold::SmoothMigrationMatrix :   fMigraterr2 = "  << endl;
+            *fLog << "============================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    *fLog << fMigraterr2(i, j) << " \t";
+                *fLog << endl;
+            }
+	    */
+
+            // ------------------------
+
+            return kTRUE;
+        }
+
+        return kFALSE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Prepare the call to MINUIT for the minimization of the function
+    //         f = chi2*w/2 + reg, where reg is the regularization term
+    //         reg is the sum the squared 2nd derivatives
+    //                        of the unfolded distribution
+    //
+    // the corresponding fcn routine is 'fcnTikhonov2'
+    //
+    Bool_t MUnfold::Tikhonov2(TH1D &hb0)
+    {
+        // the number of free parameters (npar) is equal to
+        // the number of bins (fNb) of the unfolded distribution minus 1,
+        // because of the constraint that the total number of events
+        // is fixed
+        UInt_t npar = fNb-1;
+
+        if (npar > 20)
+        {
+            *fLog << "MUnfold::Tikhonov2 : too many parameters,  npar = "
+                << npar << ",  fNb = " << fNb << endl;
+            return kFALSE;
+        }
+
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        //---   start w loop -----------------------------------
+
+        *fLog << "Tikhonov2 : start loop over weights" << endl;
+
+        Int_t ix;
+        Double_t xiter;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            fW = pow(10.0,log10(xmin)+ix*dlogx);
+
+            //..............................................
+            // Set starting values and step sizes for parameters
+
+            char name[20][100];
+            Double_t vinit[20];
+            Double_t  step[20];
+            Double_t limlo[20];
+            Double_t limup[20];
+            Int_t    fix[20];
+
+            for (UInt_t i=0; i<npar; i++)
+            {
+                sprintf(&name[i][0], "p%d", i+1);
+                vinit[i] = fVEps0(i);
+                step[i]  = fVEps0(i)/10;
+
+                // lower and upper limits  (limlo=limup=0: no limits)
+                //limlo[i] = 1.e-20;
+                limlo[i] = -1.0;
+                limup[i] = 1.0;
+                fix[i]   = 0;
+            }
+
+            // calculate solution for the weight fW
+            // flag non-convergence by chisq(ix) = 0.0
+            chisq(ix) = 0.0;
+            if ( CallMinuit(fcnTikhonov2, npar, name, vinit,
+                            step, limlo, limup, fix) )
+            {
+                // calculate difference between ideal and unfolded distribution
+                Double_t D2bar = 0.0;
+                for (UInt_t i = 0; i<fNb; i++)
+                {
+                    Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                    D2bar += temp*temp;
+                }
+
+                SpAR(ix)   = SpurAR;
+                SpSig(ix)  = SpurSigma;
+                chisq(ix)  = Chisq;
+                SecDer(ix) = SecDeriv;
+                ZerDer(ix) = ZerDeriv;
+                Entrop(ix) = Entropy;
+                DAR2(ix)   = DiffAR2;
+                Dsqbar(ix) = D2bar;
+            }
+        }
+        *fLog << "Tikhonov2 : end of loop over weights" << endl;
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            // test whether minimization has converged
+            if (chisq(ix) != 0.0)
+            {
+                xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+                Int_t bin;
+                bin = hBchisq->FindBin( log10(xiter) );
+                hBchisq->SetBinContent(bin,chisq(ix));
+
+                //hBSpAR->SetBinContent(bin,SpAR(ix));
+                hBSpAR->SetBinContent(bin,0.0);
+
+                hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+                hBSecDeriv->SetBinContent(bin,SecDer(ix));
+                hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+                hBEntropy->SetBinContent(bin,Entrop(ix));
+
+                //hBDAR2->SetBinContent(bin,DAR2(ix));
+                hBDAR2->SetBinContent(bin,0.0);
+
+                hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+                if (ix > 0)
+                {
+                    //Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                    //hBDSpAR->SetBinContent(bin,DSpAR);
+
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    Double_t DSpSig = diff;
+                    hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                    Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                    hBDEntropy->SetBinContent(bin,DEntrop);
+
+                    Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                    hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                    Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                    hBDZerDeriv->SetBinContent(bin,DZerDer);
+                }
+            }
+        }
+
+
+        //---   end w loop -----------------------------------
+
+        // Select best weight
+        SelectBestWeight();
+
+        *fLog << " Tikhonov2 : after SelectBestWeight" << endl;
+
+        if (ixbest < 0.0)
+        {
+            *fLog << "Tikhonov2 : no result found; " << endl;
+            return kFALSE;
+        }
+
+        *fLog << "Tikhonov2 : best result found; " << endl;
+        *fLog << "===============================" << endl;
+        *fLog << "           ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        fW = pow(10.0,log10(xmin)+ixbest*dlogx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        for (UInt_t i=0; i<npar; i++)
+        {
+            sprintf(&name[i][0], "p%d", i+1);
+            vinit[i] = fVEps0(i);
+            step[i]  = fVEps0(i)/10;
+
+            // lower and upper limits  (limlo=limup=0: no limits)
+            //limlo[i] = 1.e-20;
+            limlo[i] = -1.0;
+            limup[i] = 1.0;
+            fix[i]   = 0;
+        }
+
+        // calculate solution for the best weight
+        CallMinuit(fcnTikhonov2, npar, name, vinit,
+                   step, limlo, limup, fix);
+
+
+        *fLog << "Tikhonov : Values for best weight " << endl;
+        *fLog << "==================================" << endl;
+        *fLog << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        *fLog << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        return kTRUE;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Bertero :
+    //
+    // the unfolded distribution is calculated iteratively;
+    // the number of iterations after which the iteration is stopped
+    //            corresponds to the 'weight' in other methods
+    // a small number of iterations corresponds to strong regularization
+    // a high number to no regularization
+    //
+    // see : M.Bertero, INFN/TC-88/2 (1988)
+    //       V.B.Anykeyev et al., NIM A303 (1991) 350
+    //
+    Bool_t MUnfold::Bertero(TH1D &hb0)
+    {
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        TMatrixD bold(fNb, 1);
+        bold.Zero();
+
+        //----------------------------------------------------------
+
+        Double_t db2 = 1.e20;
+
+
+        TMatrixD aminusaest(fNa, 1);
+
+        //-------   scan number of iterations   -----------------
+
+        *fLog << "Bertero : start loop over number of iterations" << endl;
+
+        Int_t ix;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            // calculate solution for the iteration number xiter
+            BertCore(xiter);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)   = SpurAR;
+            SpSig(ix)  = SpurSigma;
+            chisq(ix)  = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+            db2 = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-bold(i,0);
+                db2 += temp*temp;
+            }
+            bold = fVb;
+
+            //if (db2 < Epsdb2) break;
+
+        }
+
+        *fLog << "Bertero : end of loop over number of iterations" << endl;
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            Int_t bin;
+            bin = hBchisq->FindBin( log10(xiter) );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+        //-------   end of scan of number of iterations   -----------------
+
+        // Select best weight
+        SelectBestWeight();
+
+
+        if (ixbest < 0.0)
+        {
+            *fLog << "Bertero : weight iteration has NOT converged; " << endl;
+            return kFALSE;
+        }
+
+        *fLog << "Bertero : weight iteration has converged; " << endl;
+        *fLog << "            ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        // calculate solution for the iteration number xiter
+        Double_t xiter = pow(10.0,log10(xmin)+ixbest*dlogx);
+        BertCore(xiter);
+
+        *fLog << "Bertero : Values for best weight " << endl;
+        *fLog << "=================================" << endl;
+        *fLog << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        *fLog << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        //----------------
+
+        fNdf   = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0;
+        }
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // main part of Bertero's calculations
+    //
+    Bool_t MUnfold::BertCore(Double_t &xiter)
+    {
+        // ignore eigen values which are smaller than EpsLambda
+        TMatrixD G_inv(fNa, fNa);
+        TMatrixD Gtil_inv(fNa, fNa);
+        TMatrixD atil(fNb, fNa);
+        TMatrixD aminusaest(fNa, 1);
+
+        G_inv.Zero();
+        Gtil_inv.Zero();
+        SpurAR = 0.0;
+
+        // -----   loop over eigen values   ------------------
+        // calculate the approximate inverse of the matrix G
+        //*fLog << "flaml = " << endl;
+
+        UInt_t flagstart = 2;
+        Double_t flaml=0;
+
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda)
+                continue;
+
+            switch (flagstart)
+            {
+            case 1 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be zero
+                flaml = 1.0 - pow(1.0-tau*EigenValue(l),xiter);
+                break;
+
+            case 2 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be equal to the measured distribution
+                flaml =           1.0 - pow(1.0-tau*EigenValue(l),xiter)
+                    + EigenValue(l) * pow(1.0-tau*EigenValue(l),xiter);
+                break;
+            }
+
+            //  *fLog << flaml << ",  ";
+
+            for (UInt_t m=0; m<fNa; m++)
+            {
+                for (UInt_t n=0; n<fNa; n++)
+                {
+                    G_inv(m,n)    += 1.0  /EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                    Gtil_inv(m,n) += flaml/EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                }
+            }
+            SpurAR += flaml;
+        }
+        //*fLog << endl;
+
+
+        //*fLog << "Gtil_inv =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    *fLog << Gtil_inv(m,n) << ",  ";
+        //  }
+        //  *fLog << endl;
+        //}
+
+        //-----------------------------------------------------
+        // calculate the unfolded distribution b
+        TMatrixD v2(fMigrat, TMatrixD::kTransposeMult, Gtil_inv);
+        atil = v2;
+        TMatrixD v4(atil, TMatrixD::kMult, fVa);
+        fVb = v4;
+
+        //-----------------------------------------------------
+        // calculate AR and AR+
+        TMatrixD AR(v2, TMatrixD::kMult, fMigrat);
+
+        TMatrixD v3(fMigrat, TMatrixD::kTransposeMult, G_inv);
+        TMatrixD ARplus(v3, TMatrixD::kMult, fMigrat);
+
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        DiffAR2 = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            for (UInt_t k=0; k<fNb; k++)
+            {
+                Double_t tempo = AR(j,k) - ARplus(j,k);
+                DiffAR2       += tempo*tempo;
+            }
+        }
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            // temp = ( 2.0*fVb(j,0)-fVb(j-1,0)-fVb(j+1,0) ) / ( 2.0*fVb(j,0) );
+            Double_t temp =    2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        Double_t sumb = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+            sumb += fVb(j,0);
+
+        TMatrixD p(fNb,1);
+        p = fVb;
+        if (sumb > 0.0)
+            p *= 1.0/sumb;
+
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //-----------------------------------------------------
+
+        TMatrixD Gb(fMigrat, TMatrixD::kMult, fVb);
+        aminusaest = fVa;
+        aminusaest -= Gb;
+    
+        TMatrixD v1(1,fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            v1(0,i) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                v1(0,i) += aminusaest(j,0) * fVacovInv(j,i) ;
+        }
+
+        //-----------------------------------------------------
+        // calculate error matrix fVbcov of unfolded distribution
+        SpurSigma = CalcSpurSigma(atil);
+
+        //-----------------------------------------------------
+        // calculate the chi squared
+        for (UInt_t i = 0; i<fNa; i++)
+            Chi2(i,0) = v1(0,i) * aminusaest(i,0);
+
+        Chisq = GetMatrixSumCol(Chi2,0);
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Calculate the matrix G = M * M(transposed)
+    //           and its eigen values and eigen vectors
+    //
+    Bool_t MUnfold::CalculateG()
+    {
+        // Calculate matrix G = M*M(transposed)     (M = migration matrix)
+        //           the matrix Eigen of the eigen vectors of G
+        //           the vector EigenValues of the eigen values of G
+        //           the parameter tau = 1/lambda_max
+        //
+        TMatrixD v5(TMatrixD::kTransposed, fMigrat);
+        //TMatrixD G(fMigrat, TMatrixD::kMult, v5);
+        G.Mult(fMigrat, v5);
+
+        Eigen = G.EigenVectors(EigenValue);
+
+        RankG = 0.0;
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda) continue;
+            RankG += 1.0;
+        }
+
+        tau = 1.0 / EigenValue(0);
+
+        //  *fLog << "eigen values : " << endl;
+        //  for (Int_t i=0; i<fNa; i++)
+        //  {
+        //    *fLog << EigenValue(i) << ",  ";
+        //  }
+        //  *fLog << endl;
+
+        //*fLog << "eigen vectors : " << endl;
+        //for (Int_t i=0; i<fNa; i++)
+        //{
+        //  *fLog << "               vector " << i << endl;
+        //  for (Int_t j=0; j<fNa; j++)
+        //  {
+        //    *fLog << Eigen(j,i) << ",  ";
+        //  }
+        //  *fLog << endl;
+        //}
+        //*fLog << endl;
+
+        //*fLog << "G =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    *fLog << G(m,n) << ",  ";
+        //  }
+        //  *fLog << endl;
+        //}
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Select the best weight
+    //
+    Bool_t MUnfold::SelectBestWeight()
+    {
+        //-------------------------------
+        // select 'best' weight according to some criterion
+
+        Int_t ix;
+
+        Double_t DiffSpSigmax = -1.e10;
+        Int_t    ixDiffSpSigmax = -1;
+
+        Double_t DiffSigpointsmin = 1.e10;
+        Int_t    ixDiffSigpointsmin = -1;
+
+        Double_t DiffRankGmin = 1.e10;
+        Int_t    ixDiffRankGmin = -1;
+
+        Double_t D2barmin = 1.e10;
+        Int_t    ixD2barmin = -1;
+
+        Double_t DiffSpSig1min = 1.e10;
+        Int_t    ixDiffSpSig1min = -1;
+
+
+        Int_t ixmax = -1;
+
+        // first loop over all weights :
+        //       find smallest chi2
+        Double_t chisqmin = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            // consider only weights for which
+            //  - unfolding was successful
+            if (chisq(ix) != 0.0)
+            {
+                if (chisq(ix) < chisqmin)
+                    chisqmin = chisq(ix);
+            }
+        }
+        Double_t chisq0 = chisqmin > fVapoints ? chisqmin : fVapoints/2.0;
+
+        // second loop over all weights :
+        //        consider only weights for which chisq(ix) < chisq0
+        ixbest = -1;
+        for (ix=0; ix<Nix; ix++)
+        {
+            if (chisq(ix) != 0.0 && chisq(ix) < 2.0*chisq0)
+            {
+                // ixmax = highest weight with successful unfolding
+                //         (Least squares solution)
+                ixmax = ix;
+
+                SpurSigma = SpSig(ix);
+                SpurAR    = SpAR(ix);
+                Chisq    = chisq(ix);
+                D2bar     = Dsqbar(ix);
+
+                //----------------------------------
+                // search weight where SpurSigma changes most
+                //                               (as a function of the weight)
+                if (ix > 0  &&  chisq(ix-1) != 0.0)
+                {
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    if (diff > DiffSpSigmax)
+                    {
+                        DiffSpSigmax   = diff;
+                        ixDiffSpSigmax = ix;
+                    }
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the number of significant measurements
+                Double_t DiffSigpoints = fabs(Chisq-fVapoints);
+
+                if (DiffSigpoints < DiffSigpointsmin)
+                {
+                    DiffSigpointsmin   = DiffSigpoints;
+                    ixDiffSigpointsmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the rank of matrix G
+                Double_t DiffRankG = fabs(Chisq-RankG);
+
+                if (DiffRankG < DiffRankGmin)
+                {
+                    DiffRankGmin   = DiffRankG;
+                    ixDiffRankGmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where SpurSigma is close to 1.0
+                Double_t DiffSpSig1 = fabs(SpurSigma/fSpurVacov-1.0);
+
+                if (DiffSpSig1 < DiffSpSig1min)
+                {
+                    DiffSpSig1min   = DiffSpSig1;
+                    ixDiffSpSig1min = ix;
+                }
+
+                //----------------------------------
+                // search weight where D2bar is minimal
+
+                if (D2bar < D2barmin)
+                {
+                    D2barmin   = D2bar;
+                    ixD2barmin = ix;
+                }
+
+                //----------------------------------
+            }
+        }
+
+
+        // choose solution where increase of SpurSigma is biggest
+        //if ( DiffSpSigmax > 0.0)
+        //  ixbest = ixDiffSpSigmax;
+        //else
+        //  ixbest = ixDiffSigpointsmin;
+
+        // choose Least Squares Solution
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+        // ixbest = ixmax;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        // choose weight where chi2 is close to the number of significant
+        // measurements
+        // ixbest = ixDiffSigpointsmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+        // ixbest = ixDiffRankGmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+           ixbest = ixDiffSpSig1min;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        *fLog << "SelectBestWeight : ixDiffSpSigmax, DiffSpSigmax = "
+            << ixDiffSpSigmax << ",  " << DiffSpSigmax << endl;
+        *fLog << "================== ixDiffSigpointsmin, DiffSigpointsmin = "
+            << ixDiffSigpointsmin << ",  " << DiffSigpointsmin << endl;
+
+        *fLog << "                   ixDiffRankGmin, DiffRankGmin = "
+            << ixDiffRankGmin << ",  " << DiffRankGmin << endl;
+
+        *fLog << "                   ixDiffSpSig1min, DiffSpSig1min = "
+            << ixDiffSpSig1min << ",  " << DiffSpSig1min << endl;
+
+        *fLog << "                   ixD2barmin, D2barmin = "
+            << ixD2barmin << ",  " << D2barmin << endl;
+        *fLog << "                   ixmax  = " << ixmax  << endl;
+        *fLog << "                   ixbest = " << ixbest << endl;
+
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Draw the plots
+    //
+    Bool_t MUnfold::DrawPlots()
+    {
+
+        // in the plots, mark the weight which has been selected
+        Double_t xbin = log10(xmin)+ixbest*dlogx;
+
+        TMarker *m = new TMarker();
+        m->SetMarkerSize(1);
+        m->SetMarkerStyle(20);
+
+        //-------------------------------------
+        // draw the iteration plots
+        TString ctitle = bintitle;
+        ctitle += "Plots versus weight";
+        TCanvas *c = new TCanvas("iter", ctitle, 900, 600);
+        c->Divide(3,2);
+
+        c->cd(1);
+        hBchisq->Draw();
+        gPad->SetLogy();
+        hBchisq->SetXTitle("log10(iteration number)");
+        hBchisq->SetYTitle("chisq");
+        m->DrawMarker(xbin, log10(chisq(ixbest)));
+
+        c->cd(2);
+        hBD2bar->Draw();
+        gPad->SetLogy();
+        hBD2bar->SetXTitle("log10(iteration number)");
+        hBD2bar->SetYTitle("(b_unfolded-b_ideal)**2");
+        m->DrawMarker(xbin, log10(Dsqbar(ixbest)));
+
+        /*
+         c->cd(3);
+         hBDAR2->Draw();
+         gPad->SetLogy();
+         strgx = "log10(iteration number)";
+         strgy = "norm(AR-AR+)";
+         hBDAR2->SetXTitle(strgx);
+         hBDAR2->SetYTitle(strgy);
+         m->DrawMarker(xbin, log10(DAR2(ixbest)));
+         */
+
+        c->cd(3);
+        hBSecDeriv->Draw();
+        hBSecDeriv->SetXTitle("log10(iteration number)");
+        hBSecDeriv->SetYTitle("Second Derivative squared");
+        m->DrawMarker(xbin, SecDer(ixbest));
+
+        /*
+         c->cd(8);
+         hBDSecDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Second Derivative squared)";
+         hBDSecDeriv->SetXTitle(strgx);
+         hBDSecDeriv->SetYTitle(strgy);
+         */
+
+        /*
+         c->cd(4);
+         hBZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Zero Derivative squared";
+         hBZerDeriv->SetXTitle(strgx);
+         hBZerDeriv->SetYTitle(strgy);
+         m->DrawMarker(xbin, ZerDer(ixbest));
+         */
+
+        /*
+         c->cd(5);
+         hBDZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Zero Derivative squared)";
+         hBDZerDeriv->SetXTitle(strgx);
+         hBDZerDeriv->SetYTitle(strgy);
+         */
+
+        c->cd(4);
+        hBSpAR->Draw();
+        hBSpAR->SetXTitle("log10(iteration number)");
+        hBSpAR->SetYTitle("SpurAR");
+        m->DrawMarker(xbin, SpAR(ixbest));
+
+
+        /*
+         c->cd(11);
+         hBDSpAR->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurAR)";
+         hBDSpAR->SetXTitle(strgx);
+         hBDSpAR->SetYTitle(strgy);
+         */
+
+        c->cd(5);
+        hBSpSig->Draw();
+        hBSpSig->SetXTitle("log10(iteration number)");
+        hBSpSig->SetYTitle("SpurSig/SpurC");
+        m->DrawMarker(xbin, SpSig(ixbest)/fSpurVacov);
+
+        /*
+         c->cd(14);
+         hBDSpSig->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurSig/SpurC)";
+         hBDSpSig->SetXTitle(strgx);
+         hBDSpSig->SetYTitle(strgy);
+         */
+
+        c->cd(6);
+        hBEntropy->Draw();
+        hBEntropy->SetXTitle("log10(iteration number)");
+        hBEntropy->SetYTitle("Entropy");
+        m->DrawMarker(xbin, Entrop(ixbest));
+
+        /*
+         c->cd(17);
+         hBDEntropy->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Entropy)";
+         hBDEntropy->SetXTitle(strgx);
+         hBDEntropy->SetYTitle(strgy);
+         */
+
+        //-------------------------------------
+
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            fha->SetBinContent(i+1, fVa(i, 0)         );
+            fha->SetBinError  (i+1, sqrt(fVacov(i, i)));
+
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fhmig->SetBinContent(i+1, j+1, fMigOrig(i, j)           );
+                fhmig->SetBinError  (i+1, j+1, sqrt(fMigOrigerr2(i, j)) );
+
+                shmig->SetBinContent(i+1, j+1, fMigrat(i, j)           );
+                shmig->SetBinError  (i+1, j+1, sqrt(fMigraterr2(i, j)) );
+                shmigChi2->SetBinContent(i+1, j+1, fMigChi2(i, j)   );
+            }
+        }
+
+        //PrintTH2Content(*shmig);
+        //PrintTH2Content(*shmigChi2);
+
+        //-------------------------------------
+        CopyCol(*hprior, fVEps);
+        CopyCol(*hb,     fVb);
+        for (UInt_t i=0; i<fNb; i++)
+            hb->SetBinError(i+1, sqrt(fVbcov(i, i)));
+
+        PrintTH1Content(*hb);
+        PrintTH1Error(*hb);
+
+        //..............................................
+        for (UInt_t i=0; i<fNa; i++)
+            hEigen->SetBinContent(i+1, EigenValue(i));
+
+        //..............................................
+        // draw the plots
+        TString cctitle = bintitle;
+        cctitle +=  "Unfolding input";
+        TCanvas *cc = new TCanvas("input", cctitle, 900, 600);
+        cc->Divide(3, 2);
+
+        // distribution to be unfolded
+        cc->cd(1);
+        fha->Draw();
+        gPad->SetLogy();
+        fha->SetXTitle("log10(E_{est}/GeV)");
+        fha->SetYTitle("Counts");
+
+        // superimpose unfolded distribution
+        hb->Draw("*HSAME");
+	hb->SetMarkerColor(75);
+	hb->SetLineColor(75);
+
+        // prior distribution
+        cc->cd(2);
+        hprior->Draw();
+        gPad->SetLogy();
+        hprior->SetXTitle("log10(E_{true}/GeV)");
+        hprior->SetYTitle("Counts");
+
+        // migration matrix
+        cc->cd(3);
+        fhmig->Draw("box");
+        fhmig->SetXTitle("log10(E_{est}/GeV)");
+        fhmig->SetYTitle("log10(E_{true}/GeV)");
+
+        // smoothed migration matrix
+        cc->cd(4);
+        shmig->Draw("box");
+        shmig->SetXTitle("log10(E_{est}/GeV)");
+        shmig->SetYTitle("log10(E_{true}/GeV)");
+
+        // chi2 contributions for smoothing
+        cc->cd(5);
+        shmigChi2->Draw("box");
+        shmigChi2->SetXTitle("log10(E_{est}/GeV)");
+        shmigChi2->SetYTitle("log10(E_{true}/GeV)");
+
+        // Eigenvalues of matrix M*M(transposed)
+        cc->cd(6);
+        hEigen->Draw();
+        hEigen->SetXTitle("l");
+        hEigen->SetYTitle("Eigen values Lambda_l of M*M(transposed)");
+
+
+       //..............................................
+        // draw the results
+        TString crtitle = bintitle;
+        crtitle +=  "Unfolding results";
+        TCanvas *cr = new TCanvas("results", crtitle, 600, 600);
+        cr->Divide(2, 2);
+
+        // unfolded distribution
+        cr->cd(1);
+        hb->Draw();
+        gPad->SetLogy();
+        hb->SetXTitle("log10(E-true/GeV)");
+        hb->SetYTitle("Counts");
+
+	
+        // covariance matrix of unfolded distribution
+        cr->cd(2);
+        TH1 *hbcov=DrawMatrixClone(fVbcov, "lego");
+        hbcov->SetBins(fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1),
+                       fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1));
+
+        hbcov->SetName("hbcov");
+        hbcov->SetTitle("Error matrix of distribution hb");
+        hbcov->SetXTitle("log10(E_{true}/GeV)");
+        hbcov->SetYTitle("log10(E_{true}/GeV)");
+       
+	
+        // chi2 contributions
+        cr->cd(3);
+        TH1 *hchi2=DrawMatrixColClone(fChi2);
+        hchi2->SetBins(fNa, fha->GetBinLowEdge(1), fha->GetBinLowEdge(fNa+1));
+
+        hchi2->SetName("Chi2");
+        hchi2->SetTitle("chi2 contributions");
+        hchi2->SetXTitle("log10(E_{est}/GeV)");
+        hchi2->SetYTitle("Chisquared");
+	
+	
+        // ideal distribution
+        
+        cr->cd(4);
+        fhb0->Draw();
+        gPad->SetLogy();
+        fhb0->SetXTitle("log10(E_{true}/GeV)");
+        fhb0->SetYTitle("Counts");
+        
+
+        // superimpose unfolded distribution
+        hb->Draw("*Hsame");
+	
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Interface to MINUIT
+    //
+    //
+    Bool_t MUnfold::CallMinuit(
+                      void (*fcnx)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+                      UInt_t npar, char name[20][100],
+                      Double_t vinit[20], Double_t step[20],
+                      Double_t limlo[20], Double_t limup[20], Int_t fix[20])
+    {
+        //
+        // Be carefull: This is not thread safe
+        //
+        UInt_t maxpar = 100;
+
+        if (npar > maxpar)
+        {
+            *fLog << "MUnfold::CallMinuit : too many parameters,  npar = " << fNb
+                << ",   maxpar = " << maxpar << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Set the maximum number of parameters
+        TMinuit minuit(maxpar);
+
+
+        //..............................................
+        // Set the print level
+        // -1   no output except SHOW comands
+        //  0   minimum output
+        //  1   normal output (default)
+        //  2   additional ouput giving intermediate results
+        //  3   maximum output, showing progress of minimizations
+        //
+        Int_t printLevel = -1;
+        minuit.SetPrintLevel(printLevel);
+
+        //..............................................       
+        // Printout for warnings
+        //    SET WAR      print warnings
+        //    SET NOW      suppress warnings
+        Int_t errWarn;
+        Double_t tmpwar = 0;
+        minuit.mnexcm("SET NOW", &tmpwar, 0, errWarn);
+
+        //..............................................
+        // Set the address of the minimization function
+        minuit.SetFCN(fcnx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (minuit.DefineParameter(i, &name[i][0], vinit[i], step[i],
+                                       limlo[i], limup[i]))
+            {
+                *fLog << "MUnfold::CallMinuit: Error in defining parameter "
+                    << name << endl;
+                return kFALSE;
+            }
+        }
+
+        //..............................................
+        //Int_t NumPars = minuit.GetNumPars();
+        //*fLog << "MUnfold::CallMinuit :  number of free parameters = "
+        //     << NumPars << endl;
+
+        //..............................................
+        // Minimization
+        minuit.SetObjectFit(this);
+
+        //..............................................
+        // Error definition :
+        //
+        //    for2 chisquare function :
+        //      up = 1.0   means calculate 1-standard deviation error
+        //         = 4.0   means calculate 2-standard deviation error
+        //
+        //    for log(likelihood) function :
+        //      up = 0.5   means calculate 1-standard deviation error
+        //         = 2.0   means calculate 2-standard deviation error
+        Double_t up = 1.0;
+        minuit.SetErrorDef(up);
+
+
+
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+
+        //..............................................
+        // fix a parameter
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (fix[i] > 0)
+            {
+                Int_t parNo = i;
+                minuit.FixParameter(parNo);
+            }
+        }
+
+        //..............................................
+        // Set maximum number of iterations (default = 500)
+        Int_t maxiter = 100000;
+        minuit.SetMaxIterations(maxiter);
+
+        //..............................................
+        // minimization by the method of Migrad
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+        //..............................................       
+        // same minimization as by Migrad
+        // but switches to the SIMPLEX method if MIGRAD fails to converge
+        Int_t errMinimize;
+        Double_t tmp = 0;
+        minuit.mnexcm("MINIMIZE", &tmp, 0, errMinimize);
+
+        //..............................................       
+        // check quality of minimization
+        // istat = 0   covariance matrix not calculated
+        //         1   diagonal approximation only (not accurate)
+        //         2   full matrix, but forced positive-definite
+        //         3   full accurate covariance matrix 
+        //             (indication of normal convergence)
+        Double_t fmin, fedm, errdef;
+        Int_t    npari, nparx, istat;
+        minuit.mnstat(fmin, fedm, errdef, npari, nparx, istat);
+
+        if (errMinimize || istat < 3)
+        {
+            *fLog << "MUnfold::CallMinuit : Minimization failed" << endl;
+            *fLog << "       fmin = " << fmin   << ",   fedm = "  << fedm
+                << ",   errdef = "  << errdef << ",   istat = " << istat
+                << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Minos error analysis
+        // minuit.mnmnos();
+
+        //..............................................       
+        // Print current status of minimization
+        // if nkode = 0    only function value
+        //            1    parameter values, errors, limits
+        //            2    values, errors, step sizes, internal values
+        //            3    values, errors, step sizes, 1st derivatives
+        //            4    values, paraboloc errors, MINOS errors
+  
+        //Int_t nkode = 4;
+        //minuit.mnprin(nkode, fmin);
+
+        //..............................................       
+        // call fcn with IFLAG = 3 (final calculation : calculate p(chi2))
+        // iflag = 1   initial calculations only
+        //         2   calculate 1st derivatives and function
+        //         3   calculate function only
+        //         4   calculate function + final calculations
+        const char *command = "CALL";
+        Double_t iflag = 3;
+        Int_t errfcn3;
+        minuit.mnexcm(command, &iflag, 1, errfcn3); 
+
+        return kTRUE;
+    }
+
+
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfold.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfold.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfold.h	(revision 17960)
@@ -0,0 +1,199 @@
+#ifndef MARS_MUnfold
+#define MARS_MUnfold
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOT_TMatrixD
+#include <TMatrixD.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH2;
+class TH3;
+class TString;
+class TVectorD;
+class TH2D;
+class TH3D;
+
+class MUnfold : public MTask
+{
+
+private:
+
+  TH1 *DrawMatrixClone(const TMatrixD &m, Option_t *opt);
+  TH1 *DrawMatrixColClone(const TMatrixD &m, Option_t *opt, Int_t col);
+  void PrintTH3Content(const TH3 &hist);
+  void PrintTH3Error(const TH3 &hist);
+  void PrintTH2Content(const TH2 &hist);
+  void PrintTH2Error(const TH2 &hist);
+  void PrintTH1Content(const TH1 &hist);
+  void PrintTH1Error(const TH1 &hist);
+  void CopyCol(TMatrixD &m, const TH1 &h, Int_t col);
+  void CopyCol(TH1 &h, const TMatrixD &m, Int_t col);
+  void CopyH2M(TMatrixD &m, const TH2 &h);
+  void CopySqr(TMatrixD &m, const TH1 &h);
+  Double_t GetMatrixSumRow(const TMatrixD &m, Int_t row);
+  Double_t GetMatrixSumDiag(const TMatrixD &m);
+  Double_t GetMatrixSumCol(const TMatrixD &m, Int_t col);
+  Double_t GetMatrixSum(const TMatrixD &m);
+
+public:
+    TString   bintitle;
+
+    UInt_t    fNa;        // Number of bins in the distribution to be unfolded
+    UInt_t    fNb;        // Number of bins in the unfolded distribution
+
+    TMatrixD  fMigrat;    // migration matrix                  (fNa, fNb)
+    TMatrixD  fMigraterr2;// error**2 of migration matrix      (fNa, fNb)
+
+    TMatrixD  fMigOrig;    // original migration matrix         (fNa, fNb)
+    TMatrixD  fMigOrigerr2;// error**2 oforiginal migr. matrix  (fNa, fNb)
+
+    TMatrixD  fMigSmoo;    // smoothed migration matrix M       (fNa, fNb)
+    TMatrixD  fMigSmooerr2;// error**2 of smoothed migr. matrix (fNa, fNb)
+    TMatrixD  fMigChi2;    // chi2 contributions for smoothing  (fNa, fNb)
+
+    TMatrixD  fVa;        // distribution to be unfolded       (fNa)
+    TMatrixD  fVacov;     // error matrix of fVa               (fNa, fNa)
+    TMatrixD  fVacovInv; // inverse of fVacov                 (fNa, fNa)
+    Double_t  fSpurVacov; // Spur of fVacov
+
+    //    UInt_t    fVaevents;  // total number of events
+    UInt_t    fVapoints;  // number of significant measurements
+
+    TMatrixD  fVb;        // unfolded distribution             (fNb)
+    TMatrixD  fVbcov;     // error matrix of fVb               (fNb, fNb)
+
+    TMatrixD  fVEps;      // prior distribution                (fNb)
+    TMatrixDColumn fVEps0;
+
+    Double_t  fW;         // weight
+    Double_t  fWbest;     // best weight
+    Int_t     ixbest;
+
+    TMatrixD  fResult;    // unfolded distribution and errors  (fNb, 5)
+    TMatrixD  fChi2;      // chisquared contribution           (fNa, 1)
+
+    Double_t  fChisq;     // total chisquared
+    Double_t  fNdf;       // number of degrees of freedom
+    Double_t  fProb;      // chisquared probability
+
+    TMatrixD  G;          // G = M * M(transposed)             (fNa, fNa)
+    TVectorD  EigenValue; // vector of eigenvalues lambda of G (fNa)
+    TMatrixD  Eigen;      // matrix of eigen vectors of G      (fNa, fNa)
+    Double_t  RankG;      // rank of G
+    Double_t  tau;        // 1 / lambda_max
+    Double_t  EpsLambda;
+
+    // quantities stored for each weight :
+    TVectorD SpSig;       // Spur of covariance matrix of fVbcov
+    TVectorD SpAR;        // effective rank of G^tilde
+    TVectorD chisq;       // chi squared (measures agreement between
+    // fVa and the folded fVb)
+    TVectorD SecDer;      // regularization term = sum of (2nd der.)**2
+    TVectorD ZerDer;      // regularization term = sum of (fVb)**2
+    TVectorD Entrop;      // regularization term = reduced cross-entropy
+    TVectorD DAR2;        //
+    TVectorD Dsqbar;      //
+
+    Double_t SpurAR;
+    Double_t SpurSigma;
+    Double_t SecDeriv;
+    Double_t ZerDeriv;
+    Double_t Entropy;
+    Double_t DiffAR2;
+    Double_t Chisq;
+    Double_t D2bar;
+
+    TMatrixD Chi2;
+
+    //
+
+    // plots versus weight
+    Int_t    Nix;
+    Double_t xmin;
+    Double_t xmax;
+    Double_t dlogx;
+
+    TH1D *hBchisq;
+    TH1D *hBSpAR;
+    TH1D *hBDSpAR;
+    TH1D *hBSpSig;
+    TH1D *hBDSpSig;
+    TH1D *hBSecDeriv;
+    TH1D *hBDSecDeriv;
+    TH1D *hBZerDeriv;
+    TH1D *hBDZerDeriv;
+    TH1D *hBEntropy;
+    TH1D *hBDEntropy;
+    TH1D *hBDAR2;
+    TH1D *hBD2bar;
+
+    //
+    TH1D *hEigen;
+
+    // plots for the best solution
+    TH2D *fhmig;
+    TH2D *shmig;
+    TH2D *shmigChi2;
+
+    TH1D *fhb0;
+
+    TH1D *fha;
+
+    TH1D *hprior;
+
+    TH1D *hb;
+
+    Double_t CalcSpurSigma(TMatrixD &T, Double_t norm=1);
+
+    // -----------------------------------------------------------------------
+    //
+    // Constructor
+    //              copy histograms into matrices
+    //
+    MUnfold(TH1D &ha, TH2D &hacov, TH2D &hmig);
+    ~MUnfold();
+   
+    void SetPriorConstant();
+    Bool_t SetPriorRebin(TH1D &ha);
+    Bool_t SetPriorInput(TH1D &hpr);
+    Bool_t SetPriorPower(Double_t gamma);
+    Bool_t SetInitialWeight(Double_t &weight);
+    void PrintResults();
+    Bool_t Schmelling(TH1D &hb0);
+    void SchmellCore(Int_t full, Double_t &xiter, TMatrixD &gamma,
+			      TMatrixD &dgamma, Double_t &dga2);
+    Bool_t SmoothMigrationMatrix(TH2D &hmigorig);
+    Bool_t Tikhonov2(TH1D &hb0);
+    Bool_t Bertero(TH1D &hb0);
+    Bool_t BertCore(Double_t &xiter);
+    Bool_t CalculateG();
+    Bool_t SelectBestWeight();
+    Bool_t DrawPlots();
+    Bool_t CallMinuit(
+                      void (*fcnx)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+                      UInt_t npar, char name[20][100],
+                      Double_t vinit[20], Double_t step[20],
+                      Double_t limlo[20], Double_t limup[20], Int_t fix[20]);
+    TMatrixD &GetVb() { return fVb; }
+    TMatrixD &GetVbcov() { return fVbcov; }
+    TMatrixD &GetResult() { return fResult; }
+    TMatrixD &GetChi2() { return fChi2; }
+    Double_t &GetChisq() { return fChisq; }
+    Double_t &GetNdf() { return fNdf; }
+    Double_t &GetProb() { return fProb; }
+    TMatrixD &GetMigSmoo() { return fMigSmoo; }
+    TMatrixD &GetMigSmooerr2() { return fMigSmooerr2; }
+    TMatrixD &GetMigChi2() { return fMigChi2; }
+
+    ClassDef(MUnfold, 1)
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfoldSpectrum.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfoldSpectrum.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfoldSpectrum.cc	(revision 17960)
@@ -0,0 +1,313 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!   Author(s) : R. Wagner, 02/2004 <mailto:rwagner@mppmu.mpg.de>           
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MUnfoldSpectrum
+//
+//  Unfolds a gamma spectrum using the algorithms given in the MUnfold class
+//
+/////////////////////////////////////////////////////////////////////////////   
+#include "MUnfoldSpectrum.h"
+
+#include "TH1D.h"
+#include "TH2D.h"
+#include "TH3D.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MUnfold.h"
+
+ClassImp(MUnfoldSpectrum);
+using namespace std;
+
+MUnfoldSpectrum::MUnfoldSpectrum()
+  : fUnfoldingMethod(2), fPrior(0)
+{
+      
+}
+
+void MUnfoldSpectrum::Calc()
+{
+  // Unfold # Excess events vs. Energy and Theta
+  
+  //   TH2D* tobeunfolded = hex->GetHist();
+  //   TH2D* unfolded = new TH2D(*tobeunfolded);  
+  //   TH3D* migration = migm->GetHist();
+  
+  //const Int_t energyBins = fToBeUnfolded->GetXaxis()->GetNbins();
+  //const Int_t thetaBins =  fToBeUnfolded->GetYaxis()->GetNbins();
+  //const TAxis* axisEnergy = fToBeUnfolded->GetXaxis();
+  //const TAxis* axisTheta  = fToBeUnfolded->GetYaxis();
+  //cout << "Distribution to be unfolded has " << energyBins 
+  //     << ", " << thetaBins << " bins" <<endl;
+  
+  TAxis &taxis  = *fToBeUnfolded->GetYaxis();
+  Int_t numybins = taxis.GetNbins();
+  
+  cout << "Processing a total number of  " << numybins << " bins. " <<endl;
+  cout << "-------------------" << endl << endl;
+  
+  for (Int_t m=1; m<=numybins; m++) {
+    TString bintitle = "Bin ";
+    bintitle += m;
+    bintitle += ": ";
+    
+    cout << "Processing " << bintitle << endl;
+    
+    // -----------------------------------------
+    // ha : distribution to be unfolded
+    
+    TH1D &ha = *fToBeUnfolded->ProjectionX("", m, m, "e");
+    TString title = bintitle;
+    title += "E-est distr. to be unfolded";
+    ha.SetNameTitle("ha", title);
+    TAxis &aaxis = *ha.GetXaxis();
+    Int_t na = aaxis.GetNbins();
+    Double_t alow = aaxis.GetBinLowEdge(1);
+    Double_t aup  = aaxis.GetBinLowEdge(na+1);
+	
+    cout << ha.GetName() << ": " << ha.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=ha.GetNbinsX(); i++)
+      cout << ha.GetBinContent(i) << " \t";
+    cout << endl << endl;
+	
+    // -----------------------------------------
+    // covariance matrix of the distribution ha
+      
+    title = bintitle;
+    title +=  "Error matrix of distribution ha";
+    TH2D hacov("hacov", title, na, alow, aup, na, alow, aup);
+          
+    Double_t errmin = 3.0;
+    for (Int_t i=1; i<=na; i++) {
+      for (Int_t j=1; j<=na; j++) 
+	hacov.SetBinContent(i, j, 0.0);	
+      const Double_t content = ha.GetBinContent(i);
+      const Double_t error2  = (ha.GetBinError(i))*(ha.GetBinError(i));
+      if (content <= errmin  &&  error2 < errmin) 
+	hacov.SetBinContent(i, i, errmin);
+      else
+	hacov.SetBinContent(i, i, error2);
+    }
+    
+    //PrintTH2Content(hacov);
+      
+    // -----------------------------------------
+    // migration matrix :
+    //           x corresponds to measured quantity
+    //           y corresponds to true quantity
+    
+    // The projection is made for the selected bins only.
+    // To select a bin range along an axis, use TAxis::SetRange, eg
+    // h3.GetYaxis()->SetRange(23,56);
+    
+    //        taxis->SetRange(m,m);
+    TH2D &hmig = *(TH2D*)fMigrationMatrix->Project3D("yxe");
+    title = bintitle;
+    title += "Migration Matrix";
+    hmig.SetNameTitle("Migrat", title);
+    
+    TAxis &aaxismig = *hmig.GetXaxis();
+    Int_t namig = aaxismig.GetNbins();
+    
+    if (na != namig) {
+      cout << "doUnfolding : binnings are incompatible; na, namig = "
+	   << na << ",  " << namig << endl;
+      return;
+    }
+    
+    TAxis &baxismig = *hmig.GetYaxis();
+    Int_t nbmig = baxismig.GetNbins();
+    Double_t blow = baxismig.GetBinLowEdge(1);
+    Double_t bup  = baxismig.GetBinLowEdge(nbmig+1);
+          
+    // -----------------------------------------
+    // dummy ideal distribution
+    
+    Int_t nb = nbmig;
+      
+    title = bintitle;
+    title += "Dummy Ideal distribution";
+    TH1D hb0("dummyhb0", title, nb, blow, bup);
+    //MH::SetBinning(&hb0, &baxismig); 
+    hb0.Sumw2();
+    
+    for (Int_t k=1; k<=nb; k++) {
+      hb0.SetBinContent(k, 1.0/nb);
+      hb0.SetBinError  (k, 0.1/nb);
+    }
+	
+    //PrintTH1Content(hb0);
+        
+    // -----------------------------------------
+    // unfolded distribution
+	
+    title = bintitle;
+    title += "Unfolded distribution";
+    TH1D hb("hb", title, nb, blow, bup);
+	                    
+    // ha      is the distribution to be unfolded
+    // hacov   is the covariance matrix of the distribution ha
+    // hmig    is the migration matrix;
+    //         it is used in the unfolding unless it is overwritten
+    //         by SmoothMigrationMatrix by the smoothed migration matrix
+    // hmigor  is the migration matrix to be smoothed;
+    //         the smoothed migration matrix will be used in the unfolding
+    // hpr     the prior distribution
+    //         it is only used if SetPriorInput(*hpr) is called   
+    // hb      unfolded distribution
+
+    // create an MUnfold object;
+    MUnfold unfold(ha, hacov, hmig);
+    unfold.bintitle = bintitle;
+
+    // smooth the migration matrix;
+    //        the smoothed migration matrix will be used in the unfolding
+    //        hmig is the original (unsmoothed) migration matrix
+    unfold.SmoothMigrationMatrix(hmig);
+
+    // define prior distribution (has always to be defined) 
+    // the alternatives are 
+    //   SetPriorConstant():   isotropic distribution
+    //   SetPriorPower(gamma): dN/dE = E^{-gamma}
+    //   SetPriorInput(*hpr):  the distribution *hpr is used 
+    //   SetPriorRebin(*ha):   use rebinned histogram ha 
+    Bool_t errorprior=kTRUE;
+    switch (fPrior)
+    {
+    case 1:
+        unfold.SetPriorConstant();
+        break;
+    case 2:
+        errorprior = unfold.SetPriorPower(fPriorPowerGamma);
+        break;
+    case 3:
+        if (!fPriorInputHist)
+        {
+            cout << "Error: No hpr!" << endl;
+            return;
+        }
+        errorprior = unfold.SetPriorInput(*fPriorInputHist);
+        break;
+    case 4:
+        errorprior = unfold.SetPriorRebin(*fPriorRebinHist);
+        break;
+    }
+    if (!errorprior)
+    {
+        cout << "MUnfoldSpectrum::SetPrior... : failed.  fPrior = " ;
+        cout << fPrior << endl;
+        return;
+    }
+
+    // calculate the matrix G = M * M(transposed)
+    //           M being the migration matrix
+    unfold.CalculateG();
+
+    switch (fUnfoldingMethod)
+    {
+    case 1: // Schmelling:
+    // minimize the function Z by Gauss-Newton iteration;
+    // the parameters to be fitted are gamma(i) = lambda(i)/w;
+        cout << "Unfolding algorithm : Schmelling" << endl;
+        if (!unfold.Schmelling(hb0)) cout << "MUnfoldSpectrum::Schmelling : failed." << endl;
+        break;
+
+    case 2: // Tikhonov2 :
+    // regularization term is sum of (2nd deriv.)**2 ;
+    // minimization by using MINUIT;
+    // the parameters to be fitted are
+    // the bin contents of the unfolded distribution
+        cout << "Unfolding algorithm :   Tikhonov" << endl;
+        if (!unfold.Tikhonov2(hb0)) cout << "MUnfoldSpectrum::Tikhonov2 : failed." << endl;
+        break;
+
+    case 3: // Bertero: minimization by iteration
+        cout << "Unfolding algorithm :    Bertero" << endl;
+        if (!unfold.Bertero(hb0)) cout << "MUnfoldSpectrum::Bertero : failed." << endl;
+        break;
+    }    
+    unfold.PrintResults();
+    unfold.DrawPlots();
+
+    // get unfolded distribution
+    TMatrixD &Vb    = unfold.GetVb();
+    TMatrixD &Vbcov = unfold.GetVbcov();
+    UInt_t fNb = unfold.fNb;
+    for (UInt_t a=0; a<fNb; a++)
+    {
+      hb.SetBinContent(a+1, Vb(a,0));
+      hb.SetBinError(a+1, sqrt(Vbcov(a, a)) );
+    }
+    
+    for (Int_t k=1; k<=nb; k++) {
+      Double_t content = hb.GetBinContent(k);
+      Double_t error   = hb.GetBinError(k);
+      
+      fUnfolded->SetBinContent(k, m, content);
+      fUnfolded->SetBinError(k, m, error);
+      
+      //hex->FillBinContent(k, m, content, error);
+    }    	
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MUnfoldSpectrum::~MUnfoldSpectrum()
+{
+}
+
+
+// -----------------------------------------------------------------------
+//
+// Define prior distribution to be a constant
+//
+void MUnfoldSpectrum::SetPriorConstant()
+{
+  fPrior=1;  
+}
+
+void MUnfoldSpectrum::SetPriorRebin(TH1D *ha)
+{
+  fPriorRebinHist=ha;
+  fPrior=2;
+}
+ 
+void MUnfoldSpectrum::SetPriorInput(TH1D *hpr)
+{
+  fPriorInputHist=hpr;
+  fPrior=3;
+}
+
+void MUnfoldSpectrum::SetPriorPower(Double_t gamma)
+{
+  fPriorPowerGamma=gamma;
+  fPrior=4;
+}
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfoldSpectrum.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfoldSpectrum.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/MUnfoldSpectrum.h	(revision 17960)
@@ -0,0 +1,43 @@
+#ifndef MARS_MUnfoldSpectrum
+#define MARS_MUnfoldSpectrum
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+class MUnfoldSpectrum : public MTask
+{
+ public:
+  MUnfoldSpectrum();
+  ~MUnfoldSpectrum();
+
+ private:
+  TH2D *fToBeUnfolded;
+  TH2D *fUnfolded;
+  TH3D *fMigrationMatrix;
+  Short_t fUnfoldingMethod;
+  Short_t fPrior;
+  TH1D *fPriorRebinHist;
+  TH1D *fPriorInputHist;
+  Double_t fPriorPowerGamma;
+
+ public:
+  void Calc();
+  void SetDistToUnfold(TH2D* dist) { fToBeUnfolded = dist; }
+  void SetMigrationMatrix(TH3D* migm) { fMigrationMatrix = migm; }
+  TH2D* GetUnfDist() { return fUnfolded; }
+  void SetPriorConstant();
+  void SetPriorRebin(TH1D *ha);
+  void SetPriorInput(TH1D *hpr);
+  void SetPriorPower(Double_t gamma);
+  void SetUnfoldingMethod(Short_t method) { fUnfoldingMethod = method; }
+  
+  ClassDef(MUnfoldSpectrum, 1)
+
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calculate_of_weights.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calculate_of_weights.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calculate_of_weights.C	(revision 17960)
@@ -0,0 +1,164 @@
+const int no_samples=6;
+
+
+void calculate_of_weights(TH1F *shape, TString noise_file = "/mnt/home/pcmagic17/hbartko/mars/results/04sep12/noise_autocorr_AB_36038.root", Int_t t_offset = -10)
+{
+
+  
+  TH1F * derivative = new TH1F("derivative","derivative",161,-1.05,15.05);
+
+
+  for (int i = 1; i<162;i++){
+    derivative->SetBinContent(i,((shape->GetBinContent(i+1)-shape->GetBinContent(i-1))/0.2));
+    derivative->SetBinError(i,(sqrt(shape->GetBinError(i+1)*shape->GetBinError(i+1)+shape->GetBinError(i-1)*shape->GetBinError(i-1))/0.2));
+  }
+  
+  // normalize the shape, such that the integral for 6 slices is one!
+
+  float sum = 0;
+  for (int i=40; i<101; i++){sum+=shape->GetBinContent(i);}
+  sum /= 10;
+
+  shape->Scale(1./sum);
+  derivative->Scale(1./sum);
+
+
+  TCanvas * c1 = new TCanvas("c1","c1",600,400);
+  //c1= canvas();
+  shape->Draw();
+
+  TCanvas *c2 = new TCanvas("c2","c2",600,400);
+  //c2=canvas();
+  derivative->Draw();
+
+
+  // book the histograms for the weights
+
+  TH1F * hw_amp = new TH1F("hw_amp","hw_amp",no_samples*10,-0.5,no_samples-0.5);
+  TH1F * hw_time = new TH1F("hw_time","hw_time",no_samples*10,-0.5,no_samples-0.5);
+  TH1F * hshape = new TH1F("hshape","hshape",no_samples*10,-0.5,no_samples-0.5);
+  TH1F * hderivative = new TH1F("hderivative","hderivative",no_samples*10,-0.5,no_samples-0.5);
+
+
+  // read in the noise auto-correlation function:
+
+  TMatrix B(no_samples,no_samples);
+
+  f = new TFile(noise_file);
+  TH2F * noise_corr = (TH2F*)c_corr->FindObject("hcorr");
+  for (int i=0; i<no_samples; i++){
+    for (int j=0; j<no_samples; j++){
+      B[i][j]=noise_corr->GetBinContent(i+1,j+1);
+    }
+  }  
+  f->Close();
+
+  B.Invert();
+
+  // now the loop over t_{rel} in [-0.4;0.6[ :
+
+  for (int i=-4; i<6; i++){
+    
+  
+    TMatrix g(no_samples,1);
+    TMatrix gT(1,no_samples);
+    TMatrix d(no_samples,1);
+    TMatrix dT(1,no_samples);
+    
+    
+    for (int count=0; count < no_samples; count++){
+      
+      g[count][0]=shape->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i); 
+      gT[0][count]=shape->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i);
+      d[count][0]=derivative->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i);
+      dT[0][count]=derivative->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i);
+      
+      hshape->SetBinContent(i+5+10*count,shape->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i));
+      hderivative->SetBinContent(i+5+10*count,derivative->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i));
+    }
+    
+    
+    TMatrix m_denom = (gT*(B*g))*(dT*(B*d)) - (dT*(B*g))*(dT*(B*g));
+    float denom = m_denom[0][0];  // m_denom is a real number
+    
+    TMatrix m_first = dT*(B*d);     // m_first is a real number
+    float first = m_first[0][0]/denom;
+    
+    TMatrix m_last = gT*(B*d);      // m_last is a real number 
+    float last = m_last[0][0]/denom;
+    
+    TMatrix m1 = gT*B;
+  
+    m1 *=first;
+    
+    TMatrix m2 = dT*B; 
+    
+    m2 *=last;
+    
+    TMatrix w_amp= m1 - m2;
+    
+    
+    TMatrix m_first1 = gT*(B*g);
+    float first1 = m_first1[0][0]/denom;
+    
+    TMatrix m_last1 = gT*(B*d);
+    float last1 = m_last1[0][0]/denom;
+    
+    TMatrix m11 = dT*B; 
+   
+    m11 *=first1;
+    
+    TMatrix m21 = gT*B;
+    
+    m21 *=last1;
+    
+    
+    TMatrix w_time= m11 - m21; 
+    
+    
+    float amp = 0;
+    float amp_time = 0;
+
+    for (int count=0; count < no_samples; count++){
+      hw_amp->SetBinContent(i+5+10*count,w_amp[0][count]);
+      hw_time->SetBinContent(i+5+10*count,w_time[0][count]);
+    }
+   
+
+    
+    TMatrix m_delta_E = dT*(B*d);      // m_last is a real number 
+    float delta_E = m_delta_E[0][0]/denom;
+
+
+    TMatrix m_delta_Et = gT*(B*g);      // m_last is a real number 
+    float delta_Et = m_delta_Et[0][0]/denom;
+
+    cout << " i " << i << " delta E " << sqrt(delta_E) << " delta Et " << sqrt(delta_Et) << endl;
+
+
+  } // end loop over t_rel
+
+
+  TCanvas * c3 = new TCanvas("c3","c3",600,400);
+  hw_amp->Draw();
+
+  TCanvas * c4 = new TCanvas("c4","c4",600,400);
+  hw_time->Draw();
+
+  TCanvas * c5 = new TCanvas("c5","c5",600,400);
+  hshape->Draw();
+
+  TCanvas * c6 = new TCanvas("c6","c6",600,400);
+  hderivative->Draw();
+
+  /*
+  f_out = new TFile("/home/pcmagic17/hbartko/mars/results/04sep15/calibration_weights_corr_iterated.root","RECREATE");  //"../of_weights_bin4.root"
+  hw_amp->Write();
+  hw_time->Write();
+  hshape->Write();
+  hderivative->Write();
+  shape->Write();
+  derivative->Write();
+  f_out->Close();
+  */
+}
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calibrate_data_ped_standard.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calibrate_data_ped_standard.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calibrate_data_ped_standard.C	(revision 17960)
@@ -0,0 +1,737 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko, 03/2004 <mailto:hbartko@mppmu.mpg.de>
+!              Markus Gaug,    03/2004 <mailto:markus@ifae.es>
+!              Wolfgang Wittek 07/2004 <mailto:wittek@mppmu.mpg.de>
+!              Daniel Mazin    08/2004 <mailto:mazin@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//-------------------------------------
+//
+//  changes by W. Wittek :
+//      - call SetRange() and SetWindows() for 
+//                        MExtractedFixedWindowPeakSearch
+//      - call SetRange() and SetWindowSize() for MPedCalcPedRun
+//      - call MPedCalcFromData in 3rd loop (data calibration)
+//
+//-------------------------------------
+
+
+
+//const TString defpath = "/local/rootdata/2004_08_23/";
+
+//  const TString defpath = "/mnt/data21a/Crab_August/";
+
+   const TString defpath = "/home/pcmagic04/pratik/analysis/2004_08_14/";
+
+//const TString defcontinuoslightfile =   
+//    "/.magic/magicserv01/MAGIC/rootdata2/2004_04_22/20040813_32834_C_3EG1727+04-100CL_E.root";
+const TString defcontinuoslightfile =   
+    "/mnt/data21a/Crab_August/20040820_34060_C_CrabNebula-100CL_E.root";
+
+//  ON data Mkn 421
+
+const TString defrout = "34994_test.root";
+const Int_t defpedr  = 10060; //      {17191,17192};
+const Int_t defcalr  = 10051; //      {17193,17198,17200};
+const Int_t defdatar = 23210; //      {17206,17207,17208};
+
+
+//void calibrate_data_pedestal(const TString inpath=defpath, 
+//               const Int_t pedrun=defpedr, 
+//               const Int_t calrun=defcalr, 
+//               const Int_t datarun=defdatar, 
+//	       const TString continuoslightfile=defcontinuoslightfile,
+//               const TString resname=defrout)
+
+void calibrate_data_ped_standard(const TString inpath = defpath, 
+                                 const Int_t pedrun = defpedr, 
+                                 const Int_t calrun = defcalr, 
+                                 const Int_t datarun = defdatar, 
+	                         const TString continuoslightfile = defcontinuoslightfile,
+                                 const TString resname = defrout)
+
+{
+ cout << " inpath : " << inpath << endl;
+ cout << " pedrun : " << pedrun << endl;
+ cout << " calrun : " << calrun << endl;
+ cout << " datarun : " << datarun << endl;
+ cout << " continuoslightfile : " << continuoslightfile << endl;
+ cout << " FILE to write : " << resname << endl;
+
+  gLog.SetNoColors();
+  // the parameters should be identical to the ones of MPedCalcPedRun
+
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+ 
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+
+
+
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+  
+/*
+  for (Int_t i=0;i<psize;i++) {
+    cout << "Adding pedestal run: " << pedruns[i] << endl;
+    pruns.AddRun(pedruns[i],inpath);
+  }
+  for (Int_t i=0;i<csize;i++) {
+    cout << "Adding calibration run: " << calruns[i] << endl;
+    cruns.AddRun(calruns[i],inpath);
+  }
+  for (Int_t i=0;i<dsize;i++) {
+    cout << "Adding data run: " << dataruns[i] << endl;
+    druns.AddRun(dataruns[i],inpath);
+  }
+*/
+
+    cout << "Adding pedestal run: " << pedrun << endl;
+    pruns.AddRun(pedrun,inpath);
+    cout << "Adding calibration run: " << calrun << endl;
+    cruns.AddRun(calrun,inpath);
+    cruns.AddRun(10001,inpath);
+cruns.AddRun(10002,inpath);
+cruns.AddRun(10003,inpath);
+cruns.AddRun(10004,inpath);
+cruns.AddRun(10005,inpath);
+cruns.AddRun(10006,inpath);
+cruns.AddRun(10007,inpath);
+cruns.AddRun(10008,inpath);
+cruns.AddRun(10009,inpath);
+cruns.AddRun(10010,inpath);
+cruns.AddRun(10011,inpath);
+cruns.AddRun(10012,inpath);
+cruns.AddRun(10013,inpath);
+cruns.AddRun(10014,inpath);
+cruns.AddRun(10015,inpath);
+cruns.AddRun(10016,inpath);
+cruns.AddRun(10017,inpath);
+cruns.AddRun(10018,inpath);
+cruns.AddRun(10019,inpath);
+cruns.AddRun(10020,inpath);
+cruns.AddRun(10021,inpath);
+cruns.AddRun(10022,inpath);
+cruns.AddRun(10023,inpath);
+cruns.AddRun(10024,inpath);
+cruns.AddRun(10025,inpath);
+cruns.AddRun(10026,inpath);
+cruns.AddRun(10027,inpath);
+cruns.AddRun(10028,inpath);
+cruns.AddRun(10029,inpath);
+cruns.AddRun(10030,inpath);
+cruns.AddRun(10031,inpath);
+cruns.AddRun(10032,inpath);
+cruns.AddRun(10033,inpath);
+cruns.AddRun(10034,inpath);
+cruns.AddRun(10035,inpath);
+cruns.AddRun(10036,inpath);
+cruns.AddRun(10037,inpath);
+cruns.AddRun(10038,inpath);
+cruns.AddRun(10039,inpath);
+cruns.AddRun(10040,inpath);
+cruns.AddRun(10041,inpath);
+cruns.AddRun(10042,inpath);
+cruns.AddRun(10043,inpath);
+cruns.AddRun(10044,inpath);
+cruns.AddRun(10045,inpath);
+cruns.AddRun(10046,inpath);
+cruns.AddRun(10047,inpath);
+cruns.AddRun(10048,inpath);
+cruns.AddRun(10049,inpath);
+cruns.AddRun(10050,inpath);
+
+
+   cout << "Adding data run: " << datarun << endl;
+    druns.AddRun(datarun,inpath);
+
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+  //
+  // for excluding pixels from the beginning:
+  //
+  // badcam.AsciiRead("badpixels.dat");
+
+
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+
+  // the parameters should be identical to the ones of the extractor
+  MPedCalcPedRun pedcalc;
+  pedcalc.SetRange(0,14,0,14);
+  pedcalc.SetWindowSize( WindowSize, WindowSize);
+
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+  pedloop.SetDisplay(display);
+
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+  // 
+  // Now the short version: 
+  //
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+
+
+//  const MCalibrationCam::PulserColor_t color=MCalibrationCam::kGREEN;
+//cout << "COLOR = " << color << endl;
+
+
+  //calloop.SetColor(color);  // neu
+  //  calloop.SetFullDisplay();
+  //
+  calloop.SetExtractor(&extractor);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetBadPixels(badcam);
+  //
+  // The next two commands are for the display:
+  //
+  calloop.SetDisplay(display);
+//  calloop.SetFullDisplay(); //new
+  
+  //
+  // Apply rel. time calibration:
+  //
+    //calloop.SetRelTimeCalibration();
+    //calloop.SetTimeExtractor(&timeext);
+  //
+  // Do the event-loop:
+  //
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  if (!calloop.Process(pedcam))
+    return;
+cout << " end of Process " << endl;
+
+  badcam.Print();
+  
+  MBadPixelsCam          &badbad  = calloop.GetBadPixels();
+  MCalibrationChargeCam  &calcam  = calloop.GetCalibrationCam();
+  MCalibrationRelTimeCam &timecam = calloop.GetRelTimeCam();
+  MCalibrationQECam      &qecam   = calloop.GetQECam();
+
+  badbad.Print();
+
+  /************************************************************************/
+  /*                THIRD LOOP: DATA CALIBRATION INTO PHOTONS             */
+  /************************************************************************/
+
+
+  // First: a small loop to calculate the pedestals from the data for the first some events
+
+
+  // Create an empty Parameter List and an empty Task List
+
+
+  MParList plist3a;
+  MTaskList tlist3a;
+  plist3a.AddToList(&tlist3a);
+  
+  MPedestalCam        pedcamdata;
+  pedcamdata.SetName("MPedestalCamFromData");
+ 
+
+  plist3a.AddToList(&pedcamdata);
+ 
+
+  MRawRunHeader       runhead3a;
+  plist3a.AddToList(&geomcam );
+  plist3a.AddToList(&runhead3a);
+
+
+   
+  //tasks
+ 
+  MPedCalcFromLoGain peddatacalc;
+ 
+
+  peddatacalc.SetPedContainerName("MPedestalCamFromData");
+  peddatacalc.SetPedestalUpdate(kFALSE);
+  peddatacalc.SetRange( 0, 11, 1, 14);
+  peddatacalc.SetWindowSize( 12, 14);
+  peddatacalc.SetNumEventsDump(500);
+  peddatacalc.SetMaxHiGainVar(40);
+
+ 
+  MReadMarsFile read3a("Events");
+  read3a.DisableAutoScheme();
+  static_cast<MRead&>(read3a).AddFiles(druns);
+  
+  tlist3a.AddToList(&read3a);
+  tlist3a.AddToList(&geomapl);
+  tlist3a.AddToList(&peddatacalc);
+
+
+  MEvtLoop evtloop3a;
+  evtloop3a.SetParList(&plist3a);
+  
+  cout << " event loop over the first 500 data events for pedestal calculation" << endl;
+
+  if ( !evtloop3a.Eventloop(500) )
+    return;
+
+//   if (!evtloop3a.PreProcess())
+//     return;
+  
+//   for (int i=0; i<500; i++){
+//     if (!tlist3a.Process()) break;
+//   }
+  
+//   evtloop3a.PostProcess();
+
+
+  // Now the main third loop for the cosmics and pedestal calibration
+
+
+  MParList  plist3;  
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+ 
+
+  // containers
+ 
+  MCerPhotEvt         photevt;
+  MPedPhotCam         pedphotcam;
+
+  MPedPhotCam         pedphotcamdata;
+  pedphotcamdata.SetName("MPedPhotCamFromData");
+ 
+  MSrcPosCam          srccam;
+  MRawRunHeader       runhead;
+  MExtractedSignalCam sigcam;
+//  MSrcPosCam          pntcam;  //new!
+//  pntcam.SetName("MPntPosCam");
+
+//  MCameraDC     dccam;
+//  MStarCam      starcam;
+
+// changes by wolfgang:
+  MObservatory  obs;
+//  MStarCam      sourcecam;
+//  sourcecam.SetName("MSourceCam");
+//  MHTelAxisFromStars htelaxis;
+  plist3.AddToList(&obs);
+//  plist3.AddToList(&htelaxis);
+//  plist3.AddToList(&sourcecam);
+//  plist3.AddToList(&pntcam);  //new!
+// end changes
+
+  plist3.AddToList(&geomcam );
+  plist3.AddToList(&pedcam);
+  plist3.AddToList(&pedcamdata);
+  plist3.AddToList(&calcam  );
+  plist3.AddToList(&qecam   );
+  plist3.AddToList(&badbad  );
+  plist3.AddToList(&timecam );
+  plist3.AddToList(&sigcam  );
+  plist3.AddToList(&photevt);
+  plist3.AddToList(&pedphotcam);
+  plist3.AddToList(&pedphotcamdata);
+  plist3.AddToList(&srccam);
+  plist3.AddToList(&runhead);
+//  plist3.AddToList(&dccam);
+//  plist3.AddToList(&starcam);
+
+
+  //tasks
+//  MReadMarsFile read3("Events");
+
+  MReadReports read3;
+  read3.AddTree("Currents"); 
+  read3.AddTree("Drive"); 
+  read3.AddTree("Events","MTime.",kTRUE); 
+
+//  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(druns);
+
+  read3.AddToBranchList("MReportCurrents.*");
+  read3.AddToBranchList("MReportDrive.*");
+  read3.AddToBranchList("MRawCrateArray.*");
+  read3.AddToBranchList("MRawEvtData.*");
+  read3.AddToBranchList("MRawEvtHeader.*");
+
+
+  Float_t mindc = 0.9; //[uA]
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 5;
+  const Short_t x[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 2.5;
+  UInt_t integratedevents = 1;
+
+  // We need the MAGIC mirror geometry from a MC header:
+//  TString geometryfile = "../Mars/Gamma_zbin9_90_7_1480to1489_w0.root";
+  
+    TString geometryfile = "/.magic/magicserv01/MAGIC/mcdata/Period016/spot_1cm/standard/gamma/Gamma_zbin9_90_7_1740to1749_w0.root";
+
+  // We need the Bright Star Catalog:
+
+  // TString catalogfile = "mtemp/mmpi/macros/bsc5.dat";
+  
+  TString catalogfile = "bsc5.dat";
+  
+  MFindStars findstars;
+  // findstars.SetBlindPixels(blindpixels);  ?? WHY?
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+  findstars.SetGeometryFile(geometryfile);
+  findstars.SetBSCFile(catalogfile);
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+//  const Double_t ra  = MAstro::Hms2Rad(20, 0, 0);
+//  const Double_t dec = MAstro::Dms2Rad(20, 48, 0);
+  findstars.SetRaDec(ra,dec);
+  findstars.SetLimMag(8);
+  findstars.SetRadiusFOV(1.5);
+
+
+  //$$$$$$$$$$$$$$$$ ww
+/*
+  MSourceDirections sdirs;
+  sdirs.SetGeometryFile(geometryfile);
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  sdirs.SetRaDec(ra,dec);
+  sdirs.AddDirection(ra,dec,1,"Mkn 421");
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 14, 29);
+  sdirs.AddDirection(ra,dec,1,"My_UMa 51");
+  sdirs.SetRadiusFOV(3);
+
+  Int_t InputType=1;
+  MTelAxisFromStars telaxis;
+  telaxis.SetInputType(InputType);
+  MFillH fillhisto("MHTelAxisFromStars[MHTelAxisFromStars]","");
+  htelaxis.SetInputType(InputType);
+*/
+  //$$$$$$$$$$$$$$$$ ww
+
+
+  peddatacalc.SetPedestalUpdate(kTRUE);
+  MArrivalTimeCalc2   timecalc;
+ 
+
+  MCalibrateData      photcalc;     
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);  
+  photcalc.EnablePedestalType(MCalibrateData::kEvent);
+  photcalc.EnablePedestalType(MCalibrateData::kRun);
+
+
+  MBadPixelsCalc  badcalc;
+ 
+  MPointingPosCalc pntposcalc;
+//  MPointingPosCalc mpntposcalc;  // not necessary, wolfgang calculates by himself
+  
+  // for the interpolation of the bad pixels comment the following lines in
+  // done in the next step (Analysis.C)
+  /*
+  MBadPixelsTreat badtreat;
+  badtreat.SetUseInterpolation();
+  badtreat.SetProcessRMS();
+  badtreat.SetNumMinNeighbors(int);
+  */
+
+
+  // set the names of the pedestal containers to be used:
+//  extractor.SetNamePedContainer("MPedestalCamFromData");
+  extractor.SetNamePedestalCam("MPedestalCamFromData");
+  timeext.SetNamePedestalCam("MPedestalCamFromData");
+//   photcalc.SetNamePedADCRunContainer("MPedestalCam");
+//   photcalc.SetNamePedADCEventContainer("MPedestalCamFromData");
+//   photcalc.SetNamePedPhotRunContainer("MPedPhotCam");
+//   photcalc.SetNamePedPhotEventContainer("MPedPhotCamFromData");
+  photcalc.SetNamePedADCContainer("MPedestalCamFromData");
+  photcalc.SetNamePedPhotContainer("MPedPhotCamFromData");
+
+  badcalc.SetNamePedPhotContainer("MPedPhotCamFromData");
+
+
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+//  tlist3.AddToList(&dccal,     "Currents");
+//  tlist3.AddToList(&findstars, "Currents");
+//  tlist3.AddToList(&sdirs);
+//  tlist3.AddToList(&telaxis);
+//  tlist3.AddToList(&mpntposcalc);
+  tlist3.AddToList(&pntposcalc);
+//  tlist3.AddToList(&fillhisto);  // changed by wolfgang
+  
+  tlist3.AddToList(&peddatacalc, "Events");
+  tlist3.AddToList(&extractor,   "Events");
+  tlist3.AddToList(&timeext,     "Events");
+  tlist3.AddToList(&photcalc,    "Events");
+  tlist3.AddToList(&badcalc,     "Events");
+ 
+
+  MWriteRootFile write(resname);
+  
+  write.AddContainer("MGeomCam"              , "RunHeaders");
+  write.AddContainer("MRawRunHeader"         , "RunHeaders");
+//  write.AddContainer("MSrcPosCam"            , "RunHeaders");
+  write.AddContainer("MCalibrationChargeCam" , "RunHeaders");
+  write.AddContainer("MCalibrationQECam"     , "RunHeaders");
+  write.AddContainer("MCalibrationRelTimeCam", "RunHeaders");
+
+  write.AddContainer("MTime"         ,      "Events");
+  write.AddContainer("MPedestalCam"  ,      "Events");
+  write.AddContainer("MPedestalCamFromData","Events");
+  write.AddContainer("MCerPhotEvt"   ,      "Events");
+  write.AddContainer("MRawEvtHeader" ,      "Events");
+  write.AddContainer("MBadPixelsCam" ,      "Events");
+  write.AddContainer("MPedPhotCamFromData", "Events");
+  write.AddContainer("MArrivalTimeCam",     "Events");
+  
+//  write.AddContainer("MStarCam",            "Events");
+  write.AddContainer("MSrcPosCam",          "Events");
+
+  write.AddContainer("MReportDrive",         "Events");  //new
+//  write.AddContainer("MPntPosCam",           "Events"); 
+  write.AddContainer("MPointingPos",         "Events"); 
+
+  tlist3.AddToList(&write);
+  
+  // Create and execute eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+    
+  cout << "*************************************************************" << endl;
+  cout << "***   COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS)  ***" << endl;
+  cout << "*************************************************************" << endl;
+
+  int maxevents = 3000;
+  
+  if (!evtloop3.Eventloop(maxevents))  
+    return;  
+  tlist3.PrintStatistics();
+
+// changes by wolfgang
+//  TObject *obj = plist3.FindObject("MHTelAxisFromStars");
+//  obj->DrawClone();
+
+}
+
+void CamDraw(TCanvas &c, MHCamera &cam, MCamEvent &evt, Int_t i, Int_t j, Int_t fit)
+{
+
+  c.cd(i);
+  gPad->SetBorderMode(0);
+  MHCamera *obj1=(MHCamera*)cam.DrawCopy("hist");
+  //  obj1->AddNotify(evt);
+  
+  c.cd(i+j);
+  gPad->SetBorderMode(0);
+  obj1->Draw();
+  ((MHCamera*)obj1)->SetPrettyPalette();
+
+  if (fit != 0)
+    {
+      c.cd(i+2*j);
+      gPad->SetBorderMode(0);
+      TH1D *obj2 = (TH1D*)obj1->Projection(obj1.GetName());
+      
+//      obj2->Sumw2();
+      obj2->Draw();
+      obj2->SetBit(kCanDelete);
+
+      const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+      const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+      const Double_t integ = obj2->Integral("width")/2.5066283;
+      const Double_t mean  = obj2->GetMean();
+      const Double_t rms   = obj2->GetRMS();
+      const Double_t width = max-min;
+
+      if (rms == 0. || width == 0. )
+        return;
+      
+      switch (fit)
+        {
+        case 1:
+          TF1 *sgaus = new TF1("sgaus","gaus(0)",min,max);
+          sgaus->SetBit(kCanDelete);
+          sgaus->SetParNames("Area","#mu","#sigma");
+          sgaus->SetParameters(integ/rms,mean,rms);
+          sgaus->SetParLimits(0,0.,integ);
+          sgaus->SetParLimits(1,min,max);
+          sgaus->SetParLimits(2,0,width/1.5);
+          obj2->Fit("sgaus","QLR");
+          obj2->GetFunction("sgaus")->SetLineColor(kYellow);
+          break;
+
+        case 2:
+          TString dgausform = "([0]-[3])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
+          dgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
+          TF1 *dgaus = new TF1("dgaus",dgausform.Data(),min,max);
+          dgaus->SetBit(kCanDelete);
+          dgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}","A_{2}","#mu_{2}","#sigma_{2}");
+          dgaus->SetParameters(integ,(min+mean)/2.,width/4.,
+                               integ/width/2.,(max+mean)/2.,width/4.);
+          // The left-sided Gauss 
+          dgaus->SetParLimits(0,integ-1.5,integ+1.5);
+          dgaus->SetParLimits(1,min+(width/10.),mean);
+          dgaus->SetParLimits(2,0,width/2.);
+          // The right-sided Gauss 
+          dgaus->SetParLimits(3,0,integ);
+          dgaus->SetParLimits(4,mean,max-(width/10.));
+          dgaus->SetParLimits(5,0,width/2.);
+          obj2->Fit("dgaus","QLRM");
+          obj2->GetFunction("dgaus")->SetLineColor(kYellow);
+          break;
+          
+        case 3:
+          TString tgausform = "([0]-[3]-[6])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
+          tgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
+          tgausform += "+[6]/[8]*exp(-0.5*(x-[7])*(x-[7])/[8]/[8])";
+          TF1 *tgaus = new TF1("tgaus",tgausform.Data(),min,max);
+          tgaus->SetBit(kCanDelete);
+          tgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}",
+                             "A_{2}","#mu_{2}","#sigma_{2}",
+                             "A_{3}","#mu_{3}","#sigma_{3}");
+          tgaus->SetParameters(integ,(min+mean)/2,width/4.,
+                               integ/width/3.,(max+mean)/2.,width/4.,
+                               integ/width/3.,mean,width/2.);
+          // The left-sided Gauss 
+          tgaus->SetParLimits(0,integ-1.5,integ+1.5);
+          tgaus->SetParLimits(1,min+(width/10.),mean);
+          tgaus->SetParLimits(2,width/15.,width/2.);
+          // The right-sided Gauss 
+          tgaus->SetParLimits(3,0.,integ);
+          tgaus->SetParLimits(4,mean,max-(width/10.));
+          tgaus->SetParLimits(5,width/15.,width/2.);
+          // The Gauss describing the outliers
+          tgaus->SetParLimits(6,0.,integ);
+          tgaus->SetParLimits(7,min,max);
+          tgaus->SetParLimits(8,width/4.,width/1.5);
+          obj2->Fit("tgaus","QLRM");
+          obj2->GetFunction("tgaus")->SetLineColor(kYellow);
+          break;
+        case 4:
+          obj2->Fit("pol0","Q");
+          obj2->GetFunction("pol0")->SetLineColor(kYellow);
+          break;
+        case 9:
+          break;
+        default:
+          obj2->Fit("gaus","Q");
+          obj2->GetFunction("gaus")->SetLineColor(kYellow);
+          break;
+        }
+      
+        TArrayI s0(3);
+        s0[0] = 6;
+        s0[1] = 1;
+        s0[2] = 2;
+
+        TArrayI s1(3);
+        s1[0] = 3;
+        s1[1] = 4;
+        s1[2] = 5;
+
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TH1D *half[4];
+        half[0] = obj1->ProjectionS(s0, inner, "Sector 6-1-2 Inner");
+        half[1] = obj1->ProjectionS(s1, inner, "Sector 3-4-5 Inner");
+        half[2] = obj1->ProjectionS(s0, outer, "Sector 6-1-2 Outer");
+        half[3] = obj1->ProjectionS(s1, outer, "Sector 3-4-5 Outer");
+
+        for (int i=0; i<4; i++)      
+        {
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->Draw("same");
+        }
+
+      gPad->Modified();
+      gPad->Update();
+      
+    }
+}
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calibration_shape.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calibration_shape.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/macros/calibration_shape.C	(revision 17960)
@@ -0,0 +1,380 @@
+/* ======================================================================== *\
+!  
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MAGIC.h"
+
+
+const TString pedfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12149_P_Cab-On_E.root";
+const TString calfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12526_C_Cab-On_E.root";
+const TString datafile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12517_D_Cab-On_E.root";
+
+Int_t pedr = 36038;
+Int_t calr = 36042;
+//Int_t datar = 12517;
+
+
+
+void calibration_shape(const TString inpath = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_06/", Int_t pedruns = pedr, Int_t calruns = calr, Int_t ipix=316)
+
+{
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  
+  pruns.AddRun(pedruns,inpath);
+ 
+  cruns.AddRun(calruns,inpath);
+  
+ 
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+
+ 
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+  // MPedCalcPedRun pedcalc;
+  MPedCalcFromLoGain pedcalc_ped;
+  pedcalc_ped.SetMaxHiGainVar(20);
+  pedcalc_ped.SetRange(0, 11, 1, 14);
+  pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+ 
+
+
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc_ped);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+ 
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+ 
+
+  //
+  // Create a empty Parameter List and an empty Task List 
+  //
+  MParList  plist2;
+  MTaskList tlist2;
+  plist2.AddToList(&tlist2);
+  plist2.AddToList(&pedcam);
+  plist2.AddToList(&badcam);
+  
+   
+  MReadMarsFile read2("Events");
+  read2.DisableAutoScheme();
+  static_cast<MRead&>(read2).AddFiles(cruns);
+  
+  MGeomCamMagic              geomcam;
+  MExtractedSignalCam        sigcam;
+  MArrivalTimeCam            timecam;
+  MRawEvtData                evtdata;
+  
+  //
+  // Get the previously created MPedestalCam into the new Parameter List 
+  //
+  plist2.AddToList(&geomcam);
+  plist2.AddToList(&sigcam);
+  plist2.AddToList(&timecam);
+  plist2.AddToList(&evtdata);
+  
+  //
+  // We saw that the signal jumps between slices, 
+  // thus take the sliding window
+  //		
+  
+  MGeomApply             geomapl;
+  
+  
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  //timeext.SetWindowSize(10,10);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+  
+  
+  // timecalc->SetRange(8,14,8,14,6);
+  
+  // filter against cosmics
+  MFCosmics            cosmics;
+  MContinue            cont(&cosmics);
+  
+  tlist2.AddToList(&read2);
+  tlist2.AddToList(&geomapl);
+  tlist2.AddToList(&extractor);
+  tlist2.AddToList(&timeext);
+  
+  //
+  // In case, you want to skip the cosmics rejection, 
+  // uncomment the next line
+  //
+  tlist2.AddToList(&cont);
+  //
+  // In case, you want to skip the somewhat lengthy calculation
+  // of the arrival times using a spline, uncomment the next two lines
+  //
+  
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist2);
+  //    evtloop.SetDisplay(display);
+    
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  //
+  // Execute second analysis
+  //
+  
+  
+  if (!evtloop.PreProcess())
+    return;
+  
+  int count = 1; 
+  
+  TH2F * shape = new TH2F("shape","shape",300,0,30,1000,-20,250);
+  TH2F * shape_corr = new TH2F("shape_corr","shape_corr",300,0,30,1000,-20,250);
+  TH2F * shape_corr_all = new TH2F("shape_corr_all","shape_corr_all",300,0,30,1000,-20,250);
+  TH1F * htime = new TH1F("htime","htime",150,0,15);
+  TH1F * hsig = new TH1F("hsig","hsig",300,-50,550);
+  
+  //   cout << " hello " << endl;
+  
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+  
+  while (tlist2.Process()){ //loop over the events  
+    
+    count++;
+    
+    if (count%1000==0)  cout << "Event #" <<  count << endl;  
+    
+    MRawEvtPixelIter pixel(&evtdata);
+    
+
+    double value = 0;
+    pedcam.GetPixelContent(value, ipix, geomcam, 0);
+    
+	
+    double time = 0;
+    timecam.GetPixelContent(time, ipix, geomcam, 0);  // was 0)
+    
+    double sig = 0;
+    sigcam.GetPixelContent(sig, ipix, geomcam, 0);
+    
+    Byte_t sat = (sigcam)[ipix].GetNumHiGainSaturated();
+
+
+    htime->Fill(time);
+    hsig->Fill(sig);
+    
+  
+    pixel.Jump(ipix);
+	
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+    const Int_t nh = evtdata.GetNumHiGainSamples();
+    const Int_t nl = evtdata.GetNumLoGainSamples(); 
+	
+    Bool_t ABFlag = pixel.HasABFlag();
+	
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+    
+    const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+    
+   
+    Float_t PedMean[2];
+    PedMean[0] = ped_mean + ABoffs;
+    PedMean[1] = ped_mean - ABoffs; 
+    
+    
+      
+	  
+    for (int sample=0; sample<nh; sample++){
+      shape->Fill(sample+0.5,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+      shape->Fill(sample+15.5,logains[sample]-PedMean[(sample+ABFlag)&0x1]);
+      shape_corr->Fill(sample+0.5+5.-time,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+      shape_corr->Fill(sample+15.5+5.-time,logains[sample]-PedMean[(sample+nh+ABFlag)&0x1]);
+      if (sat==0){
+	shape_corr_all->Fill(sample+0.5+5.-time,(higains[sample]-PedMean[(sample+ABFlag)&0x1])/sig*250);
+	shape_corr_all->Fill(sample+15.5+5.-time,(logains[sample]-PedMean[(sample+nh+ABFlag)&0x1])/sig*250);
+      }
+    }
+	
+	
+  } // end loop over the entries
+    
+  tlist2.PrintStatistics();
+  
+  
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Raw Calibration Signal Shape, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Calibration Signal Shape, Arrival Time Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_shape_corr_all = new TCanvas("c_shape_corr_all","c_shape_corr_all",600,400);
+  c_shape_corr_all->SetFillColor(0);
+  c_shape_corr_all->SetBorderMode(0);
+  c_shape_corr_all->SetGridx();
+  c_shape_corr_all->SetGridy();
+  shape_corr_all->SetStats(0);
+  TString title3 = "Calibration Signal Shape, Arrival Time + Amplitude Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr_all->SetTitle(title3);
+  shape_corr_all->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all->SetYTitle("signal  [a.u.]");
+  shape_corr_all->SetMarkerStyle(20);
+  shape_corr_all->SetMarkerColor(4);
+  shape_corr_all->SetMarkerSize(0.3);
+  shape_corr_all->Draw();
+ 
+  
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Calibration Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Calibration Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+
+
+  TCanvas * c7 = new TCanvas("c7","c7",600,400);
+  c7->cd();
+  c7->SetGridx();
+  c7->SetGridy();
+  c7->SetFillColor(0);
+  //  c7->SetBordermode(0);
+    
+  TProfile * shape_corr_all_pfx = (TProfile*)shape_corr_all->ProfileX();
+  
+  shape_corr_all_pfx->SetStats(0);
+  TString title6 = "Average Calibration Signal Shape, Amplitude + Arrival Time Corrected, Pixel";
+  title6+=ipix;
+  shape_corr_all_pfx->SetTitle(title6);
+  shape_corr_all_pfx->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all_pfx->SetYTitle("signal [a.u.]");
+  shape_corr_all_pfx->SetMarkerStyle(20);
+  shape_corr_all_pfx->SetMarkerColor(4);
+  shape_corr_all_pfx->SetMarkerSize(0.5);
+  shape_corr_all_pfx->Draw();
+}
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/macros/data_shape.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/macros/data_shape.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/macros/data_shape.C	(revision 17960)
@@ -0,0 +1,377 @@
+/* ======================================================================== *\
+!  
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MAGIC.h"
+
+
+const TString pedfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12149_P_Cab-On_E.root";
+const TString calfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12526_C_Cab-On_E.root";
+const TString datafile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12517_D_Cab-On_E.root";
+
+Int_t pedr = 36058;
+Int_t calr = 36058;
+//Int_t datar = 12517;
+
+
+
+void data_shape(const TString inpath = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_06/", Int_t pedruns = pedr, Int_t calruns = calr, Int_t ipix=316)
+
+{
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  
+  pruns.AddRun(pedruns,inpath);
+ 
+  cruns.AddRun(calruns,inpath);
+  
+ 
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+
+ 
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+  // MPedCalcPedRun pedcalc;
+  MPedCalcFromLoGain pedcalc_ped;
+  pedcalc_ped.SetMaxHiGainVar(20);
+  pedcalc_ped.SetRange(0, 11, 1, 14);
+  pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+ 
+
+
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc_ped);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+ 
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+ 
+
+  //
+  // Create a empty Parameter List and an empty Task List 
+  //
+  MParList  plist2;
+  MTaskList tlist2;
+  plist2.AddToList(&tlist2);
+  plist2.AddToList(&pedcam);
+  plist2.AddToList(&badcam);
+  
+  
+  MReadMarsFile read2("Events");
+  read2.DisableAutoScheme();
+  static_cast<MRead&>(read2).AddFiles(cruns);
+  
+  MGeomCamMagic              geomcam;
+  MExtractedSignalCam        sigcam;
+  MArrivalTimeCam            timecam;
+  MRawEvtData                evtdata;
+  
+  //
+  // Get the previously created MPedestalCam into the new Parameter List 
+  //
+  plist2.AddToList(&geomcam);
+  plist2.AddToList(&sigcam);
+  plist2.AddToList(&timecam);
+  plist2.AddToList(&evtdata);
+  
+  //
+  // We saw that the signal jumps between slices, 
+  // thus take the sliding window
+  //		
+  
+  MGeomApply             geomapl;
+  
+  
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+  
+  
+  // timecalc->SetRange(8,14,8,14,6);
+  
+  // filter against cosmics
+  MFCosmics            cosmics;
+  MContinue            cont(&cosmics);
+  
+  tlist2.AddToList(&read2);
+  tlist2.AddToList(&geomapl);
+  tlist2.AddToList(&extractor);
+  tlist2.AddToList(&timeext);
+  
+  //
+  // In case, you want to skip the cosmics rejection, 
+  // uncomment the next line
+  //
+  tlist2.AddToList(&cont);
+  //
+  // In case, you want to skip the somewhat lengthy calculation
+  // of the arrival times using a spline, uncomment the next two lines
+  //
+  
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist2);
+  //    evtloop.SetDisplay(display);
+    
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  //
+  // Execute second analysis
+  //
+  
+  
+  if (!evtloop.PreProcess())
+    return;
+  
+  int count = 1; 
+  
+  TH2F * shape = new TH2F("shape","shape",30,0,30,1000,-50,250);
+  TH2F * shape_corr = new TH2F("shape_corr","shape_corr",300,0,30,1000,-50,250);
+  TH2F * shape_corr_all = new TH2F("shape_corr_all","shape_corr_all",300,0,30,1000,-50,250);
+  TH1F * htime = new TH1F("htime","htime",150,0,15);
+  TH1F * hsig = new TH1F("hsig","hsig",300,-50,550);
+  
+  //   cout << " hello " << endl;
+  
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+  
+  while (tlist2.Process()){ //loop over the events  
+    
+    count++;
+    
+    if (count%1000==0)  cout << "Event #" <<  count << endl;  
+    
+    MRawEvtPixelIter pixel(&evtdata);
+    
+
+    double value = 0;
+    pedcam.GetPixelContent(value, ipix, geomcam, 0);
+    
+	
+    double time = 0;
+    timecam.GetPixelContent(time, ipix, geomcam, 0);  // was 0)
+    
+    double sig = 0;
+    sigcam.GetPixelContent(sig, ipix, geomcam, 0);
+    
+    Byte_t sat = (sigcam)[ipix].GetNumHiGainSaturated();
+
+    hsig->Fill(sig);
+    
+    if (sig>60 && sat==0){
+
+      htime->Fill(time);
+
+      pixel.Jump(ipix);
+      
+      const Byte_t *higains = pixel.GetHiGainSamples();
+      const Byte_t *logains = pixel.GetLoGainSamples();
+      const Int_t nh = evtdata.GetNumHiGainSamples();
+      const Int_t nl = evtdata.GetNumLoGainSamples(); 
+      
+      Bool_t ABFlag = pixel.HasABFlag();
+      
+      const Byte_t *higains = pixel.GetHiGainSamples();
+      const Byte_t *logains = pixel.GetLoGainSamples();
+      
+      const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+      
+      Float_t PedMean[2];
+      PedMean[0] = ped_mean + ABoffs;
+      PedMean[1] = ped_mean - ABoffs; 
+    
+    
+      
+	  
+      for (int sample=0; sample<nh; sample++){
+	shape->Fill(sample+0.5,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+	shape->Fill(sample+15.5,logains[sample]-PedMean[(sample+ABFlag)&0x1]);
+	shape_corr->Fill(sample+0.5+6.-time,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+	shape_corr->Fill(sample+15.5+6.-time,logains[sample]-PedMean[(sample+nh+ABFlag)&0x1]);
+	shape_corr_all->Fill(sample+0.5+6.-time,(higains[sample]-PedMean[(sample+ABFlag)&0x1])/sig*250);
+	shape_corr_all->Fill(sample+15.5+6.-time,(logains[sample]-PedMean[(sample+nh+ABFlag)&0x1])/sig*250);
+      }
+    }// end if (sig > 50)
+	
+  } // end loop over the entries
+    
+  tlist2.PrintStatistics();
+  
+  
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Raw Data Signal Shape, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Data Signal Shape, Arrival Time Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_shape_corr_all = new TCanvas("c_shape_corr_all","c_shape_corr_all",600,400);
+  c_shape_corr_all->SetFillColor(0);
+  c_shape_corr_all->SetBorderMode(0);
+  c_shape_corr_all->SetGridx();
+  c_shape_corr_all->SetGridy();
+  shape_corr_all->SetStats(0);
+  TString title3 = "Data Signal Shape, Arrival Time + Amplitude Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr_all->SetTitle(title3);
+  shape_corr_all->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all->SetYTitle("signal  [a.u.]");
+  shape_corr_all->SetMarkerStyle(20);
+  shape_corr_all->SetMarkerColor(4);
+  shape_corr_all->SetMarkerSize(0.3);
+  shape_corr_all->Draw();
+ 
+  
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Data Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Data Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+
+  TCanvas * c7 = new TCanvas("c7","c7",600,400);
+  c7->cd();
+  c7->SetGridx();
+  c7->SetGridy();
+  c7->SetFillColor(0);
+  //  c7->SetBordermode(0);
+    
+  TProfile * shape_corr_all_pfx = (TProfile*)shape_corr_all->ProfileX();
+  
+  shape_corr_all_pfx->SetStats(0);
+  TString title6 = "Average Data Signal Shape, Amplitude + Arrival Time Corrected, Pixel";
+  title6+=ipix;
+  shape_corr_all_pfx->SetTitle(title6);
+  shape_corr_all_pfx->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all_pfx->SetYTitle("signal [a.u.]");
+  shape_corr_all_pfx->SetMarkerStyle(20);
+  shape_corr_all_pfx->SetMarkerColor(4);
+  shape_corr_all_pfx->SetMarkerSize(0.5);
+  shape_corr_all_pfx->Draw();
+
+}
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/macros/findstars.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/macros/findstars.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/macros/findstars.C	(revision 17960)
@@ -0,0 +1,184 @@
+void ReadSetup(TString fname, MAstroCamera &cam)
+{
+    MMcConfigRunHeader *config=0;
+    MGeomCam           *geom=0;
+
+    TFile file(fname);
+    TTree *tree = (TTree*)file.Get("RunHeaders");
+    tree->SetBranchAddress("MMcConfigRunHeader", &config);
+    if (tree->GetBranch("MGeomCam"))
+        tree->SetBranchAddress("MGeomCam", &geom);
+    tree->GetEntry(0);
+
+    cam.SetMirrors(*config->GetMirrors());
+    cam.SetGeom(*geom);
+}
+
+void findstars(const TString filename="20040422_23213_D_Mrk421_E.root", const TString directory="/data/MAGIC/Period016/rootdata2/2004_04_22/", const UInt_t numEvents = 0)
+{
+
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarLocalCam starcam;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddTree("Drive"); // If you do not include Drive info, the MFindStars class
+                         // will not use the star catalog method
+  read.AddFile(directory+filename); // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+  read.AddToBranchList("MReportDrive.*");
+
+  MGeomApply geomapl;
+  TString continuoslightfile =   
+     "/data/MAGIC/Period016/rootdata/2004_04_16/20040416_22368_P_Off3c279-2CL100_E.root";
+  Float_t mindc = 0.9; //[uA]
+
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 5;
+  const Short_t x[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 2.5;
+  UInt_t integratedevents = 1;
+
+  // We need the MAGIC mirror geometry from a MC header:
+  TString geometryfile = "/mcdata/standard/camera/NSB_013/Gamma/Gamma_zbin9_90_7_1480to1489_w0.root";
+
+  // We need the Bright Star Catalog:
+  TString catalogfile = "/home/rwagner/bsc5.dat";
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+  findstars.SetGeometryFile(geometryfile);
+  findstars.SetBSCFile(catalogfile);
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  findstars.SetRaDec(ra,dec);
+  findstars.SetLimMag(8);
+  findstars.SetRadiusFOV(1.5);
+
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  tlist.AddToList(&findstars, "Currents");
+  
+  // The following lines you only need if in addition you want to display
+  // independent MAstroCamera output
+  //
+  //  TString fname = "/mcdata/standard/camera/NSB_013/Gamma/Gamma_zbin9_90_7_1480to1489_w0.root";
+  //  MObservatory magic1;      
+  //  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26); //Mkn421
+  //  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  //
+  //  MAstroCamera stars;        
+  //  ReadSetup(fname, stars); 
+  //  stars.SetLimMag(9);
+  //  stars.SetRadiusFOV(3);
+  //  stars.SetRaDec(ra, dec);
+  //  stars.ReadBSC("/home/rwagner/bsc5.dat");
+  //  stars.SetObservatory(magic1);
+
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  if (!evtloop.PreProcess())
+    return;
+  
+  MHCamera display(geomcam);
+  display.SetPrettyPalette();
+  display.Draw();
+  gPad->cd(1);
+  starcam.Draw();
+  
+  UInt_t numevents=0;
+  
+  while (tlist.Process())
+    {
+      numevents++;
+      if (numevents%integratedevents==0)
+	{
+	  display.SetCamContent(findstars.GetDisplay());
+	  gPad->Modified();
+	  gPad->Update();	      
+        // This line prints the results:
+	// 	  starcam.Print();
+	// This is how to access the TList of stars:
+	// 	  TList* starlist = starcam.GetList();
+
+	// This is how to iterate over stars found:
+	// 	  TIter Next(starlist);
+	// 	  MStarLocalPos* star;
+	// 	  UInt_t starnum = 0;
+	// 	  cout << filename << " ";
+	// 	  cout << "Iterating over list" << endl;
+	// 	  while ((star=(MStarLocalPos*)Next())) 
+	// 	    {
+	// 	      cout << "star[" << starnum << "] ";
+	// 	      cout << star->GetMeanX() << " " 
+	// 		   << star->GetMeanY() << " ";
+	// 	      starnum++;
+	// 	    }
+	// 	  cout << endl;
+	
+	}//integratedevents
+
+      MTime time;
+      time.Set(2004, 4, 22, 21, 51, 15);
+      
+      //superimpose star picture
+      //       stars.SetTime(time);
+      //       TObject *o = stars.Clone();
+      //       o->SetBit(kCanDelete);
+      //       o->Draw();
+      
+      if (!HandleInput())
+        break;
+
+    }
+
+  evtloop.PostProcess();
+    
+  tlist.PrintStatistics();
+
+}
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/macros/noise_autocorrelation_AB.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/macros/noise_autocorrelation_AB.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/macros/noise_autocorrelation_AB.C	(revision 17960)
@@ -0,0 +1,343 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko  09/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+const TString defname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+const TString defpedname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+
+// works with one pedestal file to calculate the noise autocorrelation
+
+void noise_autocorrelation_AB(const TString fname = defpedname, const TString pedname = defpedname, Int_t ipix = 67) {
+  
+  MParList plist_ped;
+  
+  MTaskList tlist_ped;
+  plist_ped.AddToList(&tlist_ped);
+  
+  MPedestalCam   pedcam;
+  plist_ped.AddToList(&pedcam);
+  
+  MReadMarsFile read("Events", pedname);
+  read.DisableAutoScheme();
+  tlist_ped.AddToList(&read);
+  
+  MGeomApply     geomapl_ped;
+  MGeomCamMagic  geomcam;
+  tlist_ped.AddToList(&geomapl_ped);
+
+  
+  MPedCalcFromLoGain pedcalc_ped;
+  //pedcalc_ped.SetMaxHiGainVar(20);
+  //pedcalc_ped.SetRange(0, 11, 1, 14);
+  //pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+  tlist_ped.AddToList(&pedcalc_ped);
+  
+  MEvtLoop evtloop_ped;
+  evtloop_ped.SetParList(&plist_ped);
+  
+  if (!evtloop_ped.Eventloop())
+    return;
+  
+  tlist_ped.PrintStatistics();
+  
+  
+  // now the event loop for the signal reconstruction with pedestals subtracted
+  
+  
+  MParList plist;
+  MTaskList     tlist;
+  plist.AddToList(&tlist);
+
+  plist.AddToList(&pedcam);
+  
+  MRawRunHeader runheader;
+  plist.AddToList(&runheader);
+
+  MRawEvtData evtdata; 
+  plist.AddToList(&evtdata);
+ 
+  MExtractedSignalCam sigcam;
+  plist.AddToList(&sigcam);
+  
+  MArrivalTimeCam timecam;
+  plist.AddToList(&timecam);
+
+  
+  MReadMarsFile read("Events", fname);
+  read.DisableAutoScheme();
+  
+  MGeomApply geomapl;
+
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+
+    
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&extractor);
+  tlist.AddToList(&timeext);
+
+  
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+  if (!evtloop.PreProcess())
+    return;
+
+  TString title = "Noise Autocorrelation B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}>, Pixel ";
+  title += ipix;
+ 
+
+  Int_t First = 1;
+
+  TH2F * hcorr = new TH2F("hcorr","hcorr",15,0,15,15,0,15);
+ 
+  TH2F * shape = new TH2F("shape","shape",311,-1.05,30.05,1000,-20,250);
+  TH2F * shape_corr = new TH2F("shape_corr","shape_corr",311,-1.05,30.05,1000,-20,250);
+  TH1F * htime = new TH1F("htime","htime",150,0,15);
+  TH1F * hsig = new TH1F("hsig","hsig",300,-50,550); 
+
+
+  Float_t B[15][15];
+  Float_t bi[15];
+  Float_t bj[15];
+  
+  for (int i=0; i<15; i++){
+    bi[i]=0;
+    bj[i]=0;
+    for (int j=0; j<15; j++){
+      B[i][j]=0;
+    }
+  }
+
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+
+  cout << " ped_mean " << ped_mean << " pedRMS " << pedRMS << endl;
+  int count = 0;
+
+  while (tlist.Process()) {
+
+    if (First) {
+      First = 0;
+
+      const Int_t nh = runheader.GetNumSamplesHiGain();
+      const Int_t nl = runheader.GetNumSamplesLoGain();
+      const Int_t nt = nh+nl;
+      
+    }
+
+    
+    htime->Fill(timecam[ipix].GetArrivalTimeHiGain());
+    hsig->Fill(sigcam[ipix].GetExtractedSignalHiGain());
+
+
+    MRawEvtPixelIter pixel(&evtdata);
+    pixel.Jump(ipix);
+
+    Bool_t ABFlag = pixel.HasABFlag();
+
+   
+    count++; // couter for the number of events
+
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+  
+    const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+
+    Float_t PedMean[2];
+    PedMean[0] = ped_mean + ABoffs;
+    PedMean[1] = ped_mean - ABoffs;
+
+
+    // calculate the noise autocorrelation matrix
+    for (int slice=0; slice<nh; slice++) {     
+      bi[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];
+      bj[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];  
+      for (int ii = 0; ii< nh; ii++){
+	B[slice][ii]+=(higains[slice]-PedMean[(slice+ABFlag)&0x1])*(higains[ii]-PedMean[(ii+ABFlag)&0x1]);
+      }
+    }
+
+
+    // compute the noise signal shape
+    
+    Int_t trigger = 0;
+    Double_t charge = 0;
+    Double_t charge_time = 0;
+
+
+    for (int slice=0; slice<nh; slice++) {
+      shape->Fill(slice,higains[slice]-PedMean[(slice+ABFlag)&0x1]);
+      shape->Fill(slice+nh,logains[slice]-PedMean[(slice+ABFlag)&0x1]);
+      if (trigger==0 && (higains[slice]-PedMean[(slice+ABFlag)&0x1]) >= 4.0) 
+	trigger = slice;
+    }
+
+    for (int slice=0; slice<nh; slice++) 
+      if (trigger>=1 && slice<=trigger+2){
+	 charge += higains[slice]-PedMean[(slice+ABFlag)&0x1];
+	 charge_time += slice*(higains[slice]-PedMean[(slice+ABFlag)&0x1]);
+      }
+  
+    if (charge>0) charge_time /= charge;
+
+    for (int slice=0; slice<nh; slice++)
+      if (trigger>=1)
+	shape_corr->Fill(slice+3-charge_time,(higains[slice]-PedMean[(slice+ABFlag)&0x1]));
+
+
+
+    
+  } // end eventloop.Process()
+  
+  evtloop.PostProcess();
+
+
+  for (int i=0; i<15; i++){
+    for (int j=0; j<15; j++){
+      hcorr->Fill(i,j,B[i][j]/count-bi[i]/count*bj[j]/count);
+      //      cout << "i " << i << " j " << j << " B[i][j] " << B[i][j] << " bi[i] " << bi[i] << " bj[j] " << bj[j] << endl;
+    }
+  }
+
+  cout << " pedmean " << ped_mean << " pedRMS " << pedRMS << endl;
+
+
+  TCanvas * c_corr = new TCanvas("c_corr","c_corr",600,400);
+  c_corr->SetFillColor(0);
+  c_corr->SetBorderMode(0);
+  c_corr->SetGridx();
+  c_corr->SetGridy();
+  gStyle->SetPalette(1);
+
+  hcorr->SetStats(0);
+  hcorr->SetTitle(title);
+  hcorr->SetXTitle("slice i");
+  hcorr->SetYTitle("slice j");
+  hcorr->Draw("colz");
+
+ 
+  TCanvas * c_corr_px = new TCanvas("c_corr_px","c_corr_px",600,400);
+  c_corr_px->SetFillColor(0);
+  c_corr_px->SetBorderMode(0);
+  c_corr_px->SetGridx();
+  c_corr_px->SetGridy();
+  
+  TH1F * hcorr_px = (TH1F*)hcorr->ProjectionX("hcorr_px",6,6);
+  hcorr_px->SetLineColor(4);
+  hcorr_px->SetLineWidth(2);
+  hcorr_px->SetStats(0);
+  TString title1 = "Noise Autocorrelation, FADC sample 6, Pixel";
+  title1+=ipix;
+  hcorr_px->SetTitle(title);
+  hcorr_px->SetXTitle("slice i");
+  hcorr_px->SetYTitle("B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}> [FADC counts]");
+  
+  hcorr_px->Draw();
+
+
+
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Noise Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Noise Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+
+}
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mmpi/macros/noise_autocorrelation_AB_all.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mmpi/macros/noise_autocorrelation_AB_all.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mmpi/macros/noise_autocorrelation_AB_all.C	(revision 17960)
@@ -0,0 +1,358 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko  09/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+const TString defname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+const TString defpedname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+
+// works with one pedestal file to calculate the noise autocorrelation
+
+
+
+
+void noise_autocorrelation_AB_all(const TString fname = defpedname, const TString pedname = defpedname) {
+
+
+  //  for (int i=1; i++; i<397){
+
+  TH2F bla;
+  TH2F * hcorr = new TH2F("hcorr","hcorr",15,0,15,15,0,15);
+
+
+  for (int i=1; i<397; i++){
+    bla = noise_autocorrelation_AB_pix(fname,pedname, i);
+    
+    hcorr->Add(&bla);
+  }
+
+  
+  TCanvas * c_corr = new TCanvas("c_corr","c_corr",600,400);
+  c_corr->SetFillColor(0);
+  c_corr->SetBorderMode(0);
+  c_corr->SetGridx();
+  c_corr->SetGridy();
+  gStyle->SetPalette(1);
+
+  hcorr->Scale(1./396.);
+ 
+  hcorr->Draw("colz");
+      //  }
+
+}  
+
+
+
+
+
+TH2F noise_autocorrelation_AB_pix(const TString fname = defpedname, const TString pedname = defpedname, Int_t ipix = 67) {
+  
+  MParList plist_ped;
+  
+  MTaskList tlist_ped;
+  plist_ped.AddToList(&tlist_ped);
+  
+  MPedestalCam   pedcam;
+  plist_ped.AddToList(&pedcam);
+  
+  MReadMarsFile read("Events", pedname);
+  read.DisableAutoScheme();
+  tlist_ped.AddToList(&read);
+  
+  MGeomApply     geomapl_ped;
+  MGeomCamMagic  geomcam;
+  tlist_ped.AddToList(&geomapl_ped);
+
+  
+  MPedCalcFromLoGain pedcalc_ped;
+  //pedcalc_ped.SetMaxHiGainVar(20);
+  //pedcalc_ped.SetRange(0, 11, 1, 14);
+  //pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+  tlist_ped.AddToList(&pedcalc_ped);
+  
+  MEvtLoop evtloop_ped;
+  evtloop_ped.SetParList(&plist_ped);
+  
+  if (!evtloop_ped.Eventloop())
+    return;
+  
+  tlist_ped.PrintStatistics();
+  
+  
+  // now the event loop for the signal reconstruction with pedestals subtracted
+  
+  
+  MParList plist;
+  MTaskList     tlist;
+  plist.AddToList(&tlist);
+
+  plist.AddToList(&pedcam);
+  
+  MRawRunHeader runheader;
+  plist.AddToList(&runheader);
+
+  MRawEvtData evtdata; 
+  plist.AddToList(&evtdata);
+ 
+  MExtractedSignalCam sigcam;
+  plist.AddToList(&sigcam);
+  
+  MArrivalTimeCam timecam;
+  plist.AddToList(&timecam);
+
+  
+  MReadMarsFile read("Events", fname);
+  read.DisableAutoScheme();
+  
+  MGeomApply geomapl;
+
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+
+    
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&extractor);
+  tlist.AddToList(&timeext);
+
+  
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+  if (!evtloop.PreProcess())
+    return;
+
+  TString title = "Noise Autocorrelation B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}>, Pixel ";
+  title += ipix;
+ 
+
+  Int_t First = 1;
+
+  TH2F hcorr("hcorr","hcorr",15,0,15,15,0,15);
+ 
+ 
+  Float_t B[15][15];
+  Float_t bi[15];
+  Float_t bj[15];
+  
+  for (int i=0; i<15; i++){
+    bi[i]=0;
+    bj[i]=0;
+    for (int j=0; j<15; j++){
+      B[i][j]=0;
+    }
+  }
+
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+
+  cout << " ped_mean " << ped_mean << " pedRMS " << pedRMS << " ABoffs " << pedcam[ipix].GetPedestalABoffset() << endl;
+  int count = 0;
+
+  while (tlist.Process()) {
+
+    if (First) {
+      First = 0;
+
+      const Int_t nh = runheader.GetNumSamplesHiGain();
+      const Int_t nl = runheader.GetNumSamplesLoGain();
+      const Int_t nt = nh+nl;
+      
+    }
+
+ 
+
+    MRawEvtPixelIter pixel(&evtdata);
+    pixel.Jump(ipix);
+
+    Bool_t ABFlag = pixel.HasABFlag();
+
+   
+    count++; // couter for the number of events
+
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+  
+    const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+
+    Float_t PedMean[2];
+    PedMean[0] = ped_mean + ABoffs;
+    PedMean[1] = ped_mean - ABoffs;
+
+
+    // calculate the noise autocorrelation matrix
+    for (int slice=0; slice<nh; slice++) {     
+      bi[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];
+      bj[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];  
+      for (int ii = 0; ii< nh; ii++){
+	B[slice][ii]+=(higains[slice]-PedMean[(slice+ABFlag)&0x1])*(higains[ii]-PedMean[(ii+ABFlag)&0x1]);
+      }
+    }
+
+
+    // compute the noise signal shape
+    
+    Int_t trigger = 0;
+    Double_t charge = 0;
+    Double_t charge_time = 0;
+
+
+   
+
+
+    
+  } // end eventloop.Process()
+  
+  evtloop.PostProcess();
+
+
+  for (int i=0; i<15; i++){
+    for (int j=0; j<15; j++){
+      hcorr->Fill(i,j,B[i][j]/count-bi[i]/count*bj[j]/count);
+      //      cout << "i " << i << " j " << j << " B[i][j] " << B[i][j] << " bi[i] " << bi[i] << " bj[j] " << bj[j] << endl;
+    }
+  }
+
+  cout << " pedmean " << ped_mean << " pedRMS " << pedRMS << endl;
+
+
+  return hcorr;
+
+  /*
+
+  TCanvas * c_corr = new TCanvas("c_corr","c_corr",600,400);
+  c_corr->SetFillColor(0);
+  c_corr->SetBorderMode(0);
+  c_corr->SetGridx();
+  c_corr->SetGridy();
+  gStyle->SetPalette(1);
+
+  hcorr->SetStats(0);
+  hcorr->SetTitle(title);
+  hcorr->SetXTitle("slice i");
+  hcorr->SetYTitle("slice j");
+  hcorr->Draw("colz");
+
+ 
+  TCanvas * c_corr_px = new TCanvas("c_corr_px","c_corr_px",600,400);
+  c_corr_px->SetFillColor(0);
+  c_corr_px->SetBorderMode(0);
+  c_corr_px->SetGridx();
+  c_corr_px->SetGridy();
+  
+  TH1F * hcorr_px = (TH1F*)hcorr->ProjectionX("hcorr_px",6,6);
+  hcorr_px->SetLineColor(4);
+  hcorr_px->SetLineWidth(2);
+  hcorr_px->SetStats(0);
+  TString title1 = "Noise Autocorrelation, FADC sample 6, Pixel";
+  title1+=ipix;
+  hcorr_px->SetTitle(title);
+  hcorr_px->SetXTitle("slice i");
+  hcorr_px->SetYTitle("B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}> [FADC counts]");
+  
+  hcorr_px->Draw();
+
+
+
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Noise Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Noise Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+  */
+}
+
+
+
+
+
+
+
Index: branches/Mars_McMismatchStudy/mtemp/mpisa/macros/AnalCurrents.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mpisa/macros/AnalCurrents.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mpisa/macros/AnalCurrents.C	(revision 17960)
@@ -0,0 +1,257 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/*
+#include <iostream>
+#include <stdlib.h>
+#include <string.h>
+#include <TString.h>
+#include <TArrayS.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamMagic.h"
+#include "MCameraDC.h"
+
+#include "MReadReports.h"
+#include "MGeomApply.h"
+#include "MEvtLoop.h"
+*/
+const Int_t gsNpix = 577;
+MGeomCamMagic geomcam;
+
+using namespace std;
+
+void AnalCurrents(const TString filename)
+{
+    //UInt_t numEvents = 1000000;
+    UInt_t numEvents = 1;
+    
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;  
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    
+    
+    MCameraDC     dccam;
+    
+    plist.AddToList(&geomcam);
+    plist.AddToList(&dccam);
+    
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    // Reads the trees of the root file and the analysed branches
+    MReadReports read;
+    read.AddTree("Currents"); 
+    read.AddFile(filename);     // after the reading of the trees!!!
+    read.AddToBranchList("MReportCurrents.*");
+    
+    MGeomApply geomapl;
+    
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&read);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+     
+    MCerPhotEvt dcevt;
+    
+    const Int_t NSteps = 5;  // Number of steps to average DC over events
+    Int_t count = 0;         // counter for averaging NSteps events
+    Int_t NumAverEvt = 1;    // counter for averaged events stored into dcevt
+    Double_t val[gsNpix];    // array for managing the averaging of gsNpix
+                             // DC values over NSteps events
+
+    // Initialize to 0 array val
+    for(Int_t i=0; i<gsNpix; i++)
+	val[i] = 0.0;
+    //
+    // Execute your analysis
+    //
+    //if (!evtloop.Eventloop(numEvents))
+    //  return kFALSE;
+    if (!evtloop.PreProcess())
+	return;
+    
+    while (tlist.Process())
+    {
+	++count;
+	for(Int_t i=0; i<gsNpix; i++)
+	{
+	    val[i] += dccam.GetCurrent(i);
+
+	    if( (count%NSteps) == 0 )
+	    {
+		dcevt.AddPixel(i,val[i]/(Double_t)NSteps,0);
+		dcevt.GetPixelContent(val[i],i,geomcam,0);
+		val[i] = 0.0;
+	    }
+	}
+
+	// Reset count and call findstar function on this macroevent
+	if( (count%NSteps) == 0 )
+	{
+	    count = 0;
+	    ++NumAverEvt;
+	    cout << "Calling test_findstar function" << endl;
+	    test_findstar(&dcevt);
+	}
+    }
+
+    // Last loop overall pixels to fill with the average 
+    // of last count events
+    if(count!=0)
+    {
+	for(Int_t i=0; i<gsNpix; i++)
+	    dcevt.AddPixel(i,val[i]/(Double_t)count,0);
+
+	cout << "Calling test_findstar function" << endl;
+	test_findstar(&dcevt);
+    }
+
+    cout << "Number of averaged events stored into container = " << NumAverEvt << endl;
+    tlist.PrintStatistics();
+    
+}
+
+
+// This macro creates a fake MCerPhotEvt container (with some clusters
+// that simulate the starfield seen by the DC currents) and then applies
+// the image cleaning and the Hillas algorithm to recognize and classify
+// the clusters.
+//
+void test_findstar(MCerPhotEvt *wDCEvt)
+{
+    //MGeomCamMagic *geom; 
+    MCerPhotEvt *DCEvt = new MCerPhotEvt();
+    Int_t cluster[gsNpix];
+    Float_t startp[gsNpix];
+    
+    memset(cluster,-1,gsNpix);
+    memset(startp,-1,gsNpix);
+    
+    TVectorD *startpixs = new TVectorD();
+    Double_t tempDC;
+    Int_t pixid;
+    // fill a fake MCerPhotEvt 
+    // loop over all pixels
+    for (pixid=0; pixid<gsNpix ; pixid++)
+    {
+	switch (pixid)
+	{
+	    case 9:
+		DCEvt->AddPixel(pixid,1.1,0.0);
+		break;
+	    case 2:
+	    case 8:
+	    case 21:
+	    case 22:
+	    case 23:
+	    case 10:
+		DCEvt->AddPixel(pixid,1.1,0.0);
+		break;
+	    case 39:
+		DCEvt->AddPixel(pixid,1.2,0.0);
+		break;
+	    case 64:
+		DCEvt->AddPixel(pixid,1.71,0.0);
+		break;
+	    case 65:
+		DCEvt->AddPixel(pixid,1.70,0.0);
+		break;
+	    case 40:
+		DCEvt->AddPixel(pixid,1.72,0.0);
+		break;
+	    default:
+		DCEvt->AddPixel(pixid);
+		break;
+	}
+    } // end loop over pixels
+
+    if(!(FindStartPixels(wDCEvt, startpixs)))
+	cout << "ARGH!@!! In function FindStartPixel(): no starting pixel found" << endl;
+    
+}
+
+Int_t FindStartPixels(MCerPhotEvt *evt, TVectorD *startpixs)
+{
+    Double_t currDC;
+    Int_t i = 0;
+    Double_t DCthr = 10.0;
+    
+    MCerPhotPix *dcpix;
+    MGeomPix *pix;
+    
+    // look for all the pixels with a DC higher than the DC of neighbour pixels 
+    // loop over all pixels
+    for (Int_t pixid=0; pixid<gsNpix; pixid++)
+    {
+	Double_t tempDC;
+
+	pix = (MGeomPix *)geomcam[pixid]; // MGeomCamMagic pixel
+	
+	// Get the DC value of the current pixel
+	evt->GetPixelContent(currDC,pixid,geomcam,0);
+	
+	Float_t maxDC = 0.0;
+	// look for the max DC in the neighbors pixels
+	for (Int_t j=0; j < pix->GetNumNeighbors(); j++)
+	{
+	    evt->GetPixelContent(tempDC,pix->GetNeighbor(j),geomcam,0);
+	    if(tempDC > maxDC) 
+		maxDC = tempDC;
+	}
+	
+	// a starting pixel was found: it is added to the array
+	if ((currDC>maxDC) && (currDC>DCthr))
+	{
+	    startpixs->ResizeTo(++i);
+	    startpixs(i-1)=pixid;
+	    cout << "Starting pixel PixID=" << startpixs(i-1) << " curr=" << currDC << endl;
+	}
+    }
+    
+    if(startpixs->GetNrows()>0)
+    {
+	cout << "Number of starting pixels = " << startpixs->GetNrows() << endl;
+	return 1;
+    }
+    else
+	return 0;
+}
+/*
+Int_t FindCluster(Int_t startpix, Int_t cluster, MGeomCam *geom)
+{
+  return 1;
+
+}
+*/
+
Index: branches/Mars_McMismatchStudy/mtemp/mpisa/macros/test_findstar.C
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mpisa/macros/test_findstar.C	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mpisa/macros/test_findstar.C	(revision 17960)
@@ -0,0 +1,98 @@
+// This macro creates a fake MCerPhotEvt container (with some clusters
+// that simulate the starfield seen by the DC currents) and then applies
+// the image cleaning and the Hillas algorithm to recognize and classify
+// the clusters.
+//
+void test_findstar();
+{
+  // Empty container and task lists
+  MParList plist;
+  MTaskList tlist;
+
+  //  cout << "0" <<endl;  
+  plist.AddToList(&tlist);
+
+  MCerPhotEvt *DCEvt;
+
+  MGeomCamMagic *geom; 
+
+  const Int_t gsNpix = 577;
+
+  TArrayF *startpixs(gsNpix);
+  Int_t cluster[gsNpix];
+  memset(cluster,-1,gsNpix*sizeof(Int_t));
+  memset(startpixs,-1,gsNpix*sizeof(Int_t));
+
+  // fill a fake MCerPhotEvt 
+
+// loop over all pixels
+  
+  for (Int_t pixid = 0; pixid <gsNpix ; pixid++)
+    {
+      MCerPhotPix dcpix =  DCEvt[pixid];
+
+      cout << "1" <<endl;  
+      // a fake cluster:
+      dcpix->SetNumPhotons(0.);
+      
+      switch (pixid)
+      {
+      case 10:
+	dcpix->SetNumPhotons(1.5);
+      case 3:
+	dcpix->SetNumPhotons(1.1);
+      case 9:
+	dcpix->SetNumPhotons(1.1);
+      case 22:
+	dcpix->SetNumPhotons(1.1);
+      case 23:
+	dcpix->SetNumPhotons(1.1);
+      case 24:
+	dcpix->SetNumPhotons(1.1);
+      case 11:
+	dcpix->SetNumPhotons(1.1);
+      };
+    }; // end loop over pixels
+
+  
+  if (!(FindStartPixels(DCEvt, startpixs, geom)))
+    cout << "Error calling the FindStartPixels function!!" << endl;
+  
+  return;
+};  
+
+Int_t FindStartPixels(MCerPhotEvt *evt, TArrayF *startpixs, MGeomCam *geom)
+{
+  // look for all the pixels with a DC higher than the DC of neighbour pixels 
+
+  // loop over all pixels
+  MCerPhotEvtIter Next(evt, kFALSE);
+  
+  for (Int_t pixid=0; pixid<gsNPix; pixid++)
+    {
+      MCerPhotPix dcpix =  DCEvt[pixid]; // curren pix with DC
+
+      const MGeomPix &pix = (*geom)[pixid]; // MGeomCam pixel
+      
+      currDC = dcpix->GetNumPhotons();  // DC of current pixel
+
+      // look for the max DC in the neighbors pixels
+      Float_t macDC = 0;
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++) 
+	if ( evt[pix.GetNeighbor(j)]->GetNumPhotons() > maxDC) 
+	  maxDC = evt[pix.GetNeighbor(j)]->GetNumPhotons();
+     
+      // a starting pixel was found: it is added to the array and the pointer
+      // to the array is increased by 1
+      if ( currDC > maxDC)
+	*(startpixs++) = currDC;
+    }
+
+  return 1;
+}
+
+Int_t FindCluster(Int_t startpix, Int_t cluster, MGeomCam *geom)
+{
+  return 1;
+
+} ;
Index: branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.cpp
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.cpp	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.cpp	(revision 17960)
@@ -0,0 +1,83 @@
+// DCCurrentEvent.cpp: Implementiberung der Klasse DCCurrentEvent.
+//
+//////////////////////////////////////////////////////////////////////
+
+#ifndef DCCURRENTEVENT_INCLUDED
+#include "DCCurrentEvent.h"
+#endif
+#ifndef GLOBALS_INCLUDED
+#include "Globals.h"
+#endif
+
+#include <sstream>
+#include <istream>
+#include <ostream>
+#include <iostream>
+#include <iomanip>
+#include <iterator>
+#include <vector>
+
+extern int gYear, gMonth, gDay;
+
+//////////////////////////////////////////////////////////////////////
+// Konstruktion/Destruktion
+//////////////////////////////////////////////////////////////////////
+
+DCCurrentEvent::DCCurrentEvent()
+{
+    m_dcValues.reserve( Globals::CAMERA_PIXELS );
+    
+}
+
+DCCurrentEvent::~DCCurrentEvent()
+{
+}
+
+std::istream& operator >> ( std::istream& in, DCCurrentEvent& event )
+{
+    using std::string;
+    using std::getline;
+
+    // read the starting tag
+    string tag;
+    in >> tag;
+    if ( tag != "DC")
+    {
+        in.clear( std::ios_base::badbit);
+        return in;
+    }
+
+    // read error codes
+    in >> event.m_dcError1 >> event.m_dcError2;
+
+    // read in the timestamp
+    in >> event.m_dcHour >> event.m_dcMin >> event.m_dcSec >> event.m_dcMSec;
+
+    getline( in, event.m_dcCurr );
+
+    return in;
+}
+
+std::ostream& operator << ( std::ostream& out, const DCCurrentEvent& event )
+{
+    using namespace std;
+
+    out << "DC-REPORT ";
+    out << setfill('0') << right << resetiosflags(ios_base::showpos);
+    out << setw(2) << 0 << ' ';
+    out << setw(4) << gYear << ' ';
+    out << setw(2) << gMonth << ' ';
+    out << setw(2) << gDay << ' ';
+    out << setw(2) << event.m_dcHour << ' ';
+    out << setw(2) << event.m_dcMin  << ' ';
+    out << setw(2) << event.m_dcSec  << ' ';
+    out << setw(3) << event.m_dcMSec << ' ';
+
+    out << setfill('0') << internal << setiosflags(ios_base::showpos);
+    out << setw(3) << event.m_dcError1 << " ";
+    out << setw(3) << event.m_dcError2;
+    out << setfill('0') << right << resetiosflags(ios_base::showpos);
+
+    out << event.m_dcCurr;
+    return out;
+}
Index: branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.h	(revision 17960)
@@ -0,0 +1,38 @@
+// DCCurrentEvent.h: Schnittstelle für die Klasse DCCurrentEvent.
+//
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(DCCURRENTEVENT_INCLUDED)
+#define DCCURRENTEVENT_INCLUDED
+
+#include <ctime>
+#include <vector>
+#include <string>
+#include <istream>
+#include <ostream>
+
+class DCCurrentEvent
+{
+    friend std::istream& operator >> ( std::istream& in, DCCurrentEvent& event );
+    friend std::ostream& operator << ( std::ostream& out, const DCCurrentEvent& event );
+
+private:
+    int	       		m_dcError1;
+    int	       		m_dcError2;
+    int	       		m_dcHour;
+    int	       		m_dcMin;
+    int	       		m_dcSec;
+    int	       		m_dcMSec;
+    time_t     		m_dcTime;
+    std::string       m_dcCurr;
+    std::vector<int>	m_dcValues;
+
+public:
+	DCCurrentEvent();
+	virtual ~DCCurrentEvent();
+};
+
+std::istream& operator >> ( std::istream& in, DCCurrentEvent& event );
+std::ostream& operator << ( std::ostream& out, const DCCurrentEvent& event );
+
+#endif // !defined(DCCURRENTEVENT_INCLUDED)
Index: branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/Globals.h
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/Globals.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/Globals.h	(revision 17960)
@@ -0,0 +1,20 @@
+// Globals.h: Global variables
+//            We use a class to hold these global values
+//            in order not to pollute the global namespace
+//
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(GLOBALS_INCLUDED)
+#define GLOBALS_INCLUDED
+
+class Globals  
+{
+public:
+	enum {CAMERA_PIXELS = 577};
+
+private:
+	Globals();				// prevent inadvertent instantiation
+
+};
+
+#endif // !defined(GLOBALS_INCLUDED)
Index: branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/Makefile	(revision 17960)
@@ -0,0 +1,116 @@
+##################################################################
+#
+# makefile
+#
+# @file        makefile
+# @title       Converter of DCCurrent files to new format
+# @author      M Merck
+# @email       merck@astro.uni-wuerzburg.de
+# @date        Wed Dec 17 11:51:11 MET 2003
+#
+#_______________________________________________________________
+#
+# Created: Wed Dec 17 11:51:11 MET 2003
+# Author:  Martin Merck
+# Purpose: Makefile for the compilation of dcconvertor
+# Notes:   
+#    
+##################################################################
+
+# @code
+
+# compilers & tools
+
+CC            = gcc
+CXX           = g++
+F77           = g77
+
+INCLUDES = -I.
+
+OPTIM    =
+DEBUG    = -g
+
+# compilation and linking flags
+
+CXXFLAGS  = ${INCLUDES} ${OPTIM} ${DEBUG}
+CFLAGS    = ${CXXFLAGS}
+FFLAGS    = ${CXXFLAGS}
+LIBS      =
+
+#------------------------------------------------------------------------------
+
+#.SILENT:
+
+.SUFFIXES: .c .cxx .cpp .C .c++ .h .hxx .H .h++ .o .so .f
+
+SRCS = \
+	main.cpp \
+	DCCurrentEvent.cpp
+
+HEADERS = \
+	DCCurrentEvent.h \
+	Globals.h
+
+OBJS = \
+	DCCurrentEvent.o \
+	main.o
+
+PROGRAM=dcconvertor
+
+############################################################
+
+all: ${PROGRAM}
+
+depend:
+	@makedepend $(SRCS) -fMakefile 2> /dev/null
+
+${PROGRAM}: $(OBJS)
+	@echo "Linking..." $@
+	$(CXX) $(CXXFLAGS) $(OBJS) $(LIBS) -o $@
+	@echo "done."
+
+.cxx.o:
+	@echo "Compiling " $<
+	$(CXX) $(CXXFLAGS) -c $< -o $@
+
+.c.o:
+	@echo "Compiling " $<
+	$(CC) $(CFLAGS) -c $< -o $@
+
+.f.o:
+	@echo "Compiling " $<
+	$(F77) $(FFLAGS) -c $< -o $@
+
+lclean:
+	@echo "Cleanning..."
+	@rm -f *.o core
+
+clean:
+	@echo "Cleanning..."
+	@rm -f $(OBJS) core 
+
+mrproper: clean
+	@echo "Mr.Proper in action . . ."
+	@rm -f $(PROGRAM)
+
+ctags:
+	@echo "Creating CTAGS file . . ."
+	@ctags -txw $(SRCS) $(HEADERS) > CTAGS
+
+etags:
+	@echo "Creating TAGS file . . ."
+	@etags -C $(SRCS) $(HEADERS)
+
+listsrc:
+	@ls -m $(SRCS) $(HEADERS) | sed 's/,//g'
+
+redo: clean all
+
+# @endcode
+# DO NOT DELETE
+
+main.o: Globals.h /usr/include/stdlib.h /usr/include/features.h
+main.o: /usr/include/sys/cdefs.h /usr/include/gnu/stubs.h
+main.o: /usr/lib/gcc-lib/i486-suse-linux/3.3/include/stddef.h
+main.o: DCCurrentEvent.h
+DCCurrentEvent.o: DCCurrentEvent.h Globals.h
Index: branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/main.cpp
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/main.cpp	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/main.cpp	(revision 17960)
@@ -0,0 +1,57 @@
+/***************************************************************************
+                          main.cpp  -  description
+                             -------------------
+    begin                : Tue Dec  9 12:05:18 CET 2003
+    copyright            : (C) 2003 by Martin Merck
+    email                : merck@astro.uni-wuerzburg.de
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is part of the MAGIC Software  * ***************************************************************************/
+
+#ifndef GLOBALS_INCLUDED
+#include "Globals.h"
+#endif
+
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <iterator>
+#include <string>
+#include <stdlib.h>
+#include "DCCurrentEvent.h"
+
+using namespace std;
+
+int gYear, gMonth, gDay;
+
+void usage();
+
+int main(int argc, char *argv[])
+{
+  if (argc != 3)
+     usage();
+
+  string dcFileName( argv[1] );
+  string date = dcFileName.substr( dcFileName.rfind( "dc_" ) + 3, 10 );
+  sscanf( date.c_str(), "%d_%d_%d", &gYear, &gMonth, &gDay);
+  cout << gYear << ":" << gMonth << ":" << gDay << endl;
+  
+  
+  std::ifstream input( argv[1] );
+  ofstream output( const_cast<const char *> (argv[2]) );
+
+  copy( istream_iterator<DCCurrentEvent>( input ),
+        istream_iterator<DCCurrentEvent>(),
+        ostream_iterator<DCCurrentEvent>( output, "\n") );
+
+  return EXIT_SUCCESS;
+}
+
+void usage()
+{
+  cerr << "USAGE: dcconvertor <input file> <output file>" << endl;
+  exit( EXIT_FAILURE );
+}
+  
Index: branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/rundcconv
===================================================================
--- branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/rundcconv	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtemp/mwuerzburg/tools/dcconverter/rundcconv	(revision 17960)
@@ -0,0 +1,43 @@
+#!/bin/sh
+# Script to convert DC current files from the old format to the new format
+#
+PS3="Select the Date for which MERPP should run? "
+DATES=`ls -d -1 ./cacodata_old/20* | cut -d/ -f3 '-'`
+select DATE in $DATES "Exit"; do
+	break
+done
+if [ "$DATE" = "Exit" ]
+then
+  exit
+fi
+
+INDIR=./cacodata_old/$DATE
+OUTDIR=./cacodata/$DATE
+if [ -d $OUTDIR ]
+then
+  echo "An output directory for the date $DATE already"
+  echo "exists. Please be sure that you selected the"
+  echo "correct date. If you want to rerun MERPP on this"
+  echo "date please delete the directory and all files it"
+  echo "contains from the rootfiles directory."
+  exit
+fi
+echo $DATE
+mkdir ./cacodata/$DATE
+
+LOGFILE=$OUTDIR/dcconv.log
+CACOFILES=`ls -1 $INDIR/dc_*.txt`
+
+TIME=`date`
+echo "-----------------------------------------------------------------" > $LOGFILE
+echo " dcconvertor run started $TIME" >> $LOGFILE
+echo "-----------------------------------------------------------------" >> $LOGFILE
+
+for i in $CACOFILES
+do
+  IN_FILE=$i
+  OUT_FILE=$OUTDIR/$i
+  dcconvertor $IN_FILE $OUT_FILE
+  echo $IN_FILE >> $LOGFILE
+  echo "Processed file $IN_FILE in $SECONDS secs."
+done
Index: branches/Mars_McMismatchStudy/mtools/MCalendar.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MCalendar.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MCalendar.cc	(revision 17960)
@@ -0,0 +1,1629 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalendar
+//
+//
+// Resource files
+// --------------
+//
+// A calendar sheet is bets setup via a resource file with the
+// following contants:
+//
+//  The day shown in the first column. (Sun=0, Mon=1, ...)
+//     FirstDay: 0
+//
+//  The Number of blocks the calendar sheet is made of:
+//     NumBlocks: 2
+//
+//  Set the position a graphic of the moon. The alignment is
+//  coded as described in TAttText (0=off):
+//     Moon.Graf.Align: 11
+//
+//  Set the position a text describing the moon phase. The alignment is
+//  coded as described in TAttText (0=off):
+//     Moon.Text.Align: 11
+//
+//  Set the text type: 0=MoonPhase, 1=MoonPeriod, 2=MagicPeriod
+//     Moon.Text.Type:  0
+//
+//  Determin whether the text should be continous or only at
+//  new moon (only valid if both alignments identical)
+//     Moon.Text.Continous: Yes
+//
+//  Radius of the moon graphics in units of the pave height:
+//     Moon.Graf.Radius: 0.08
+//
+//  Horizontal and vertical margin in units of the pave height
+//  between the pave border and the text:
+//     MarginX: 0.05
+//
+//  Space between the cells in units of the cell height:
+//     CellSpace: 0.01
+//
+//  Space between the blocks in units of the cell height:
+//     BlockSpace: 0.1
+//
+//  Local to determin the language to be used. For more details see
+//  for example MTime::GetStringFmt or strftime (eg. de_DE, es_ES, it_IT)
+//  The empty default is the system default (eg as if you call "date")
+//     Language:
+//
+//  The file name of a file containing the setup for holidays and birthdays:
+//     HolidayFile:
+//
+//  The setup of the pave in your calendar is done by the style defined
+//  by a pave. For more details see TPave or MEnv::GetEnvPave:
+//     Date.{PaveStyle}
+//
+//  The contents of each pave in your calendar.
+//      Contents: Date Day Week Holiday Birthday
+//
+//  There are NO predefined content-strings. All the names given here
+//  are completely artificial. You could also call them just A and B.
+//  If you setup them correctly they might still behave like Date and Day.
+//  This also means that you can define as many of them as you want.
+//
+//  You can setup the contents by their names individually (eg. Holiday).
+//  The possible Style is defined by a TLatex object. For more details
+//  see TLatex or MEnv::GetAttText.
+//
+//      To setup the position in the pave use:
+//          Holiday.TextAlign: center
+//          Holiday.TextAlign: center top
+//          Holiday.TextAlign: right center
+//          Holiday.TextAlign: right top
+//
+//      The text style can be setup by:
+//          Holiday.TextSize:  0.13
+//          Holiday.TextColor: Blue
+//
+//      To setup a day-dependant string, in addition to the three resources
+//      above, a format string as defined in MTime::GetStringFmt or strftime.
+//          Holiday.Format: %a
+//
+//  Contents for which a format was setup are compiled by using
+//  MTime::GetStringFmt.
+//  Contents without a format set (by eg. Holiday.Format) are searched in
+//  the holiday resource file:
+//
+//      For the 1.1. and 25.12. the setup could be:
+//          Holiday.01/01: New year
+//          Holiday.12/25: Christmas
+//
+//      Holidays with respect to Easter are given as
+//          Holiday.-1: Easter Saturday
+//          Holiday.0: Easter
+//          Holiday.1: Easter Monday
+//
+//  In addition to this you can overwrite the default for the active
+//  and/or inactivedays by:
+//     Date.Active.{PaveStyle}
+//     Holiday.Active.TextColor: Blue
+//     Holiday.Inactive.TextColor: Gray1
+//
+//  To define a special setup for only one day (Sun=0, Mon=1, ...) use:
+//     Date.Active.0.{PaveStyle}
+//     Holiday.Active.0.TextColor: Red
+//     Holiday.Inactive.0.TextColor: White
+//
+//  To get a resource file describing the default layout draw a calendar
+//  sheet and choose "SaveResourceFile" from the context menu. By using
+//  the context menu you can change the layout and also save it to a
+//  resource file. Read such a resource file using ReadResourceFile.
+//
+//
+// Context Menu
+// ------------
+//
+//  void SetDate(UInt_t Month, Int_t Year=-1)
+//    Used to set new year and month. Use Year=-1 to keep the year
+//
+//  void SetLocal(const char *Locale="")
+//    Set new Localization. For more details see MTime::GetStringFmt or
+//    strftime
+//
+//  void SetFirstDay(Int_t FirstDay)
+//    Define the WeekDay in the first column (Son=0, Mon=1, ...)
+//
+//  void SetLayout(Byte_t NumberOfBlocks, Double_t MarginX, Double_t MarginY, Double_t CellSpace, Double_t BlockSpace)
+//    change the Layout. For more details see section "Resource Files"
+//
+//  void ResetLayout(num)
+//    Remove everything from the layout. num is the number of default blocks
+//    (corresponding to NumBlocks). A value smaller or equal 0 will leave
+//    the number of block unchanged (which is the default from the
+//    context menu)
+//
+//  void ResetHolidays()
+//    remove all holidays.
+//
+//  void SetDefaultLayout(num)
+//    set the layout to the default layout. num is the number of displayed
+//    blocks (corresponding to NumBlocks). A value smaller or equal 0 will
+//    leave the number of block unchanged (which is the default from the
+//    context menu)
+//
+//  void SetDefaultHolidays()
+//    set the default holidays
+//
+//  void ReadResourceFile(const char *FileName=0)
+//    read layout from a resource file. (also the holidays are reread)
+//
+//  void ReadHolidayFile(const char *FileName=0)
+//    read holidays from a file
+//
+//  void SaveResourceFile(const char *FileName=0)
+//    save current layout to a file
+//
+//  void SaveHolidayFile(const char *FileName=0)
+//    save current holidays to a file
+//
+//  void Add(const char *Name, Int_t Align, const char *Format, Float_t FontSize=0.3, Int_t FontColor=1); //*MENU
+//    add contents to the pave (for more details see section
+//    "resource files")
+//
+//  void SetDay(const char *Format="%a", Float_t FontSize=0.3, Int_t Color=kBlack)
+//  void SetDate(const char *Format="%e", Float_t FontSize=0.3, Int_t Color=kBlack)  { Remove(GetAlign()); Add("Date", GetAlign(), Format, FontSize, Color); } //*MENU*
+//    set the current position in the pave to a format defined by Format.
+//    with FontSize and FontColor. For more details see MTime::GetStringFmt
+//    or the man-page of strftime. The name of the corrsponding resources
+//    is set to "Day" or "Date".
+//
+//  void SetHoliday(Float_t FontSize=0.13, Int_t Color=kBlue)
+//  void SetBirthday(Float_t FontSize=0.13, Int_t Color=kBlue)
+//  void SetEaster(Float_t FontSize=0.13, Int_t Color=kBlue)
+//    set the current position in the pave to a holiday with name
+//    "Holiday", "Birthday". The holidays are read from the
+//    holiday resource file. For more details see section "Resource files"
+//
+//  void AddHoliday(const char *text)
+//  void AddBirthday(const char *text)
+//  void AddEaster(const char *text)
+//    Add a holiday ("Holiday.mm/dd", "Birthday.mm/dd" or "Holiday.%d")
+//    for the current date (for easter the offset to easter is used instead)
+//    to the holiday resources.
+//
+//  void Remove()
+//    Remove the contents from the edge you are pointing to.
+//
+// void PrintEnv()
+//    Print the current resources.
+//
+// void SetEnv(const char *VariableName, const char *Value)
+//    Set a new resource.
+//
+// void RemoveEnv(const char *VariableName)
+//    Remove a resource and all subsequent resources
+//
+//  void SetMoonGraf(Int_t Align, Float_t Radius)
+//  void SetMoonText(Int_t Align, Int_t Type, Int_t Continous)
+//    change the setup of the moon. For more details see the
+//    section "Resource Files"
+//
+//
+// Format
+// ------
+//
+// For convinience here is a copy from MTime of the most important
+// format string to be used in the "Format" resource, GetStringFmt
+// or DrawDate:
+//
+//  %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.
+//  %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).
+//  %x  The preferred date representation for the current locale w/o time.
+//  %y  The year as a decimal number without a century (range 00 to 99).
+//  %Y  The year as a decimal number including the century.
+
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalendar.h"
+
+#include <TStyle.h>
+#include <TArrow.h>
+#include <TLatex.h>
+#include <TMarker.h>
+#include <TArrayD.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+#include <TEllipse.h>
+#include <TASImage.h>
+#include <TPaveText.h>
+#include <THashList.h>
+#include <TObjArray.h>
+
+#include "MEnv.h"
+#include "MTime.h"
+
+ClassImp(MCalendar);
+
+// ****************+ ROOT Bugs  *****************
+// fCornerRadius not handled in TPave::Copy
+// TEllipse::Paint(values) doesn't work at all
+// TEnv::SetValue crashes if created with default constructor
+// TEnv::Save doesn't take filename as an argument
+// TEnv::fRcName no Getter
+// DrawClone doesn't work for a canvas/pad containing a TASImage
+// TPave::GetCornerRadius not const
+// TPabe::GetBorderRadius not const
+// TEllipse is transparent if FillColor=kWhite
+// TLatex::PaintLatex also sets data members to arguments in
+//  contradiction to all other graf-classes.
+// TEnv cannot be streamed from/to a file (means: cannot be cloned!)
+// Double_t TEnv::GetValue  Typo: dobule
+// Support for TTF fonts in font directory in TText?
+// TASImage::DrawText doesn't search TTFonts in root ttfont-path
+// TTF::SetTextFont ttffont not deleted (see gSystem->Which)
+// TASImage doesn't support transparency?
+
+using namespace std;
+
+//---------------------------------------------------------------------------
+//
+// Convert Umlauts and other exotic characters to TLatex readable characters
+//
+void MCalendar::Convert2Latex(TString &str)
+{
+    str.ReplaceAll("\xe4", "\\ddot{a}");
+    str.ReplaceAll("\xf6", "\\ddot{o}");
+    str.ReplaceAll("\xfc", "\\ddot{u}");
+    str.ReplaceAll("\xc4", "\\ddot{A}");
+    str.ReplaceAll("\xd6", "\\ddot{O}");
+    str.ReplaceAll("\xdc", "\\ddot{U}");
+    str.ReplaceAll("\xdf", "\\beta");
+    str.ReplaceAll("\xe1", "\\acute{a}");
+    str.ReplaceAll("\xe9", "\\acute{e}");
+    str.ReplaceAll("\xec", "\\grave{i}");
+
+    str.ReplaceAll("\xc3\xa4", "\\ddot{a}");
+    str.ReplaceAll("\xc3\xb6", "\\ddot{o}");
+    str.ReplaceAll("\xc3\xbc", "\\ddot{u}");
+    str.ReplaceAll("\xc3\x84", "\\ddot{A}");
+    str.ReplaceAll("\xc3\x96", "\\ddot{O}");
+    str.ReplaceAll("\xc3\x9c", "\\ddot{U}");
+    str.ReplaceAll("\xc3\x9f", "\\beta");
+    str.ReplaceAll("\xc3\xa1", "\\acute{a}");
+    str.ReplaceAll("\xc3\xa9", "\\acute{e}");
+    str.ReplaceAll("\xc3\xac", "\\grave{i}");
+}
+
+void MCalendar::ConvertUTF8(TString &str, Bool_t fwd)
+{
+    if (fwd)
+    {
+        str.ReplaceAll("\xe4", "\xc3\xa4");
+        str.ReplaceAll("\xf6", "\xc3\xb6");
+        str.ReplaceAll("\xfc", "\xc3\xbc");
+        str.ReplaceAll("\xc4", "\xc3\x84");
+        str.ReplaceAll("\xd6", "\xc3\x96");
+        str.ReplaceAll("\xdc", "\xc3\x9c");
+        str.ReplaceAll("\xdf", "\xc3\x9f");
+        str.ReplaceAll("\xe1", "\xc3\xa1");
+        str.ReplaceAll("\xe9", "\xc3\xa9");
+        str.ReplaceAll("\xec", "\xc3\xac");
+    }
+    else
+    {
+        str.ReplaceAll("\xc3\xa4", "\xe4");
+        str.ReplaceAll("\xc3\xb6", "\xf6");
+        str.ReplaceAll("\xc3\xbc", "\xfc");
+        str.ReplaceAll("\xc3\x84", "\xc4");
+        str.ReplaceAll("\xc3\x96", "\xd6");
+        str.ReplaceAll("\xc3\x9c", "\xdc");
+        str.ReplaceAll("\xc3\x9f", "\xdf");
+        str.ReplaceAll("\xc3\xa1", "\xe1");
+        str.ReplaceAll("\xc3\xa9", "\xe9");
+        str.ReplaceAll("\xc3\xac", "\xec");
+    }
+}
+
+
+//---------------------------------------------------------------------------
+//
+// TEnv doesn't have a streamer so we have to make sure that the
+// resources get corretly cloned.
+//
+TObject *MCalendar::Clone(const char *newname) const
+{
+    MCalendar *cal = (MCalendar*)TObject::Clone(newname);
+
+    if (cal->fEnv)
+        delete cal->fEnv;
+    if (cal->fEnvHolidays)
+        delete cal->fEnvHolidays;
+
+    cal->fEnv         = (MEnv*)fEnv->Clone();
+    cal->fEnvHolidays = (MEnv*)fEnvHolidays->Clone();
+
+    return cal;
+}
+
+//---------------------------------------------------------------------------
+//
+// return the StringFmt (see MTime::GetStringFmt or strftime)
+// corresponding to the Format fmt (Default="%B", LongMonthName).
+// For more complicated formatings day, hour, minutes and sec can
+// be given.
+//
+TString MCalendar::GetStringFmt(const char *fmt, Int_t day, Int_t h, Int_t m, Int_t s) const
+{
+    MTime t;
+    t.Set(fYear, fMonth, day, h, m, s);
+    return t.GetStringFmt(fmt, GetLanguage());
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the Pave setup for the given condition from the resources
+//
+void MCalendar::GetPave(TPave &pave, Bool_t active, Int_t n)
+{
+    // ----- Default ----
+    TPave def;
+    def.SetName(pave.GetName());
+    def.SetLineStyle(kSolid);
+    def.SetLineColor(kBlack);
+    def.SetLineWidth(0);
+    def.SetFillColor(18);
+    def.SetFillStyle(1001);
+    def.SetCornerRadius(0);
+    def.SetBorderSize(1);
+
+    fEnv->GetAttPave("", def);
+
+    def.Copy(pave);
+
+    pave.SetCornerRadius(def.GetCornerRadius());
+    pave.SetLineColor(active ? kBlack : 15);
+
+    const char *fmt1 = active ? "Active"    : "Inactive";
+    const char *fmt2 = active ? "Active.%d" : "Inactive.%d";
+
+    fEnv->GetAttributes(     fmt1,     &pave);
+    fEnv->GetAttributes(Form(fmt2, n), &pave);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the Moon setup for the given condition from the resources
+//
+void MCalendar::GetMoon(TAttText &text, TAttFill &fill, Bool_t active, Int_t n)
+{
+    TAttText txt(11, 0, gStyle->GetTextColor(), gStyle->GetTextFont(), 0.13);
+    TAttFill fil(0, 1001);
+
+    fEnv->GetAttText("Moon", txt);
+    fEnv->GetAttFill("Moon", fil);
+
+    txt.Copy(text);
+    fil.Copy(fill);
+
+    text.SetTextColor(active ? kRed   : 15);
+    fill.SetFillColor(active ? kBlack : 15);
+
+    const char *fmt1 = active ? "Moon.Active"    : "Moon.Inactive";
+    const char *fmt2 = active ? "Moon.Active.%d" : "Moon.Inactive.%d";
+
+    fEnv->GetAttText(fmt1, text);
+    fEnv->GetAttFill(fmt1, fill);
+
+    fEnv->GetAttText(Form(fmt2, n), text);
+    fEnv->GetAttFill(Form(fmt2, n), fill);
+}
+
+//---------------------------------------------------------------------------
+//
+// Get the Text setup for the given condition from the resources
+//
+void MCalendar::GetLatex(TLatex &latex, Bool_t active, Int_t n)
+{
+    const TString fmt = fEnv->GetValue(Form("%s.Format", latex.GetName()), "");
+    latex.SetTitle(fmt);
+
+    TAttText(0, 0, kBlack, gStyle->GetTextFont(), 0.3).Copy(latex);
+    fEnv->GetAttText(latex.GetName(), latex);
+
+    if (!active)
+        latex.SetTextColor(15);
+
+    const char *fmt1 = active ? "%s.Active"    : "%s.Inactive";
+    const char *fmt2 = active ? "%s.Active.%d" : "%s.Inactive.%d";
+
+    fEnv->GetAttText(Form(fmt1, latex.GetName()),    latex);
+    fEnv->GetAttText(Form(fmt2, latex.GetName(), n), latex);
+}
+
+//---------------------------------------------------------------------------
+//
+// Add a text. The name determins the identifier for which the resources
+// are searched, align the position in the pave (the convention is the same
+// as in TAttText). If a format fmt is given the date corresponding to the
+// pave is converted to a string using MTime::GetStringFmt. See MTime
+// for more details. If the format is empty the Holiday resources are
+// searched for an entry with the name. size defines the default height
+// of the text in units of the pave-height and color the default color in
+// case of active days.
+//  eg.
+//         Add("Day", 13, "%a", 0.3, kRed);
+// would produce a short WeekDay-name (%a) at the top left edge with
+// with a default height of 0.3*pave-height in Red. You can change
+// the behaviour from the resource file by:
+//         Day.{TextAttribute}
+//         Day.Active.{TextAttribute}
+//         Day.Inctive.{TextAttribute}
+//         Day.Active.i.{TextAttribute}
+//         Day.Inctive.i.{TextAttribute}
+// for more details about TextAttribute see MEnv::GetAttText and TAttText.
+// i is a placeholder for the WeekDay number (starting with sunday=0)
+//
+void MCalendar::Add(const char *name, Int_t align, const char *fmt, Float_t size, Int_t col)
+{
+    TAttText att(align, 0, col, gStyle->GetTextFont(), size);
+    Add(name, fmt, att);
+}
+
+void MCalendar::Add(const char *name, const char *fmt, const TAttText &att)
+{
+    fEnv->SetAttText(name, att);
+    fEnv->SetValue(Form("%s.Format", name), fmt);
+
+    const TString cont = Form(" %s ", fEnv->GetValue("Contents", ""));
+    const TString form = Form(" %s ", name);
+    if (!cont.Contains(form))
+        fEnv->SetValue("Contents", Form("%s %s", cont.Strip(TString::kBoth).Data(), name));
+}
+
+//---------------------------------------------------------------------------
+//
+// Save the current layout to a resource file. If no filename is given
+// the filename of the current open resource file is used.
+//
+void MCalendar::SaveResourceFile(const char *fname)
+{
+    const TString name = fname ? fname : fEnv->GetName();
+
+    gSystem->Unlink(name);
+
+    MEnv env(name);
+
+    env.SetValue("FirstDay",             fFirstDay);
+    env.SetValue("NumBlocks",            fNumBlocks);
+
+    env.SetValue("Orientation",          fOrientation);
+    env.SetValue("Rotation",             fRotation);
+
+    env.SetValue("Moon.Graf.Align",      fMoonAlignGraf);
+    env.SetValue("Moon.Text.Align",      fMoonAlignText);
+    env.SetValue("Moon.Text.Type",       fMoonTextType);
+    env.SetValue("Moon.Text.Continous",  fMoonTextCont);
+    env.SetValue("Moon.Graf.Radius",     fMoonRadius);
+
+    env.SetValue("MarginX",              fMarginX);
+    env.SetValue("MarginY",              fMarginY);
+    env.SetValue("CellSpace",            fCellSpace);
+    env.SetValue("BlockSpace",           fBlockSpace);
+
+    env.SetValue("Language",             GetLanguage());
+
+    env.SetValue("HolidayFile",          fEnvHolidays->GetName());
+
+    env.AddEnv(*fEnv);
+    env.Save();
+}
+
+//---------------------------------------------------------------------------
+//
+// Save the current holidays to a resource file. If no filename is given
+// the filename of the current open holiday file is used.
+//
+void MCalendar::SaveHolidayFile(const char *fname)
+{
+    const TString name = fname ? fname : fEnvHolidays->GetName();
+
+    gSystem->Unlink(name);
+
+    MEnv env(name);
+    env.AddEnv(*fEnvHolidays);
+    env.Save();
+}
+
+//---------------------------------------------------------------------------
+//
+// The Layout will be resetted and than restored from the specified
+// resource file. If no filename is given the filename of the current
+// open resource file is used.
+//
+void MCalendar::ReadResourceFile(const char *fname)
+{
+    const TString name = fname ? fname : fEnv->GetName();
+
+    ResetLayout(2);
+
+    delete fEnv;
+    fEnv = new MEnv(name);
+
+    fFirstDay      = fEnv->GetValue("FirstDay",             fFirstDay);
+    fNumBlocks     = fEnv->GetValue("NumBlocks",            fNumBlocks);
+
+    fOrientation   = fEnv->GetValue("Orientation",          fOrientation);
+    fRotation      = fEnv->GetValue("Rotation",             fOrientation);
+
+    fMoonAlignGraf = fEnv->GetValue("Moon.Graf.Align",      fMoonAlignGraf);
+    fMoonAlignText = fEnv->GetValue("Moon.Text.Align",      fMoonAlignText);
+    fMoonTextType  = fEnv->GetValue("Moon.Text.Type",       fMoonTextType);
+    fMoonTextCont  = fEnv->GetValue("Moon.Text.Continous",  fMoonTextCont);
+    fMoonRadius    = fEnv->GetValue("Moon.Graf.Radius",     fMoonRadius);
+
+    fMarginX       = fEnv->GetValue("MarginX",              fMarginX);
+    fMarginY       = fEnv->GetValue("MarginY",              fMarginY);
+    fCellSpace     = fEnv->GetValue("CellSpace",            fCellSpace);
+    fBlockSpace    = fEnv->GetValue("BlockSpace",           fBlockSpace);
+
+    SetLocal(fEnv->GetValue("Language", ""));
+    ReadHolidayFile();
+}
+
+//---------------------------------------------------------------------------
+//
+// The Holidays will be resetted and than restored from the specified
+// holiday file. If no filename is given the filename of the current
+// open holiday file is used.
+//
+void MCalendar::ReadHolidayFile(const char *fname)
+{
+    const TString name = fname ? fname : fEnvHolidays->GetName();
+
+    if (fEnvHolidays)
+        delete fEnvHolidays;
+    fEnvHolidays = new MEnv(name);
+}
+
+//---------------------------------------------------------------------------
+//
+// Reset the layout (remove everything)
+//
+// num is the number of default blocks (corresponding to NumBlocks).
+// A value smaller or equal 0 will leave the number of block unchanged
+// (which is the default)
+//
+void MCalendar::ResetLayout(Int_t num)
+{
+    fOrientation   = kFALSE;
+    fRotation      = kFALSE;
+
+    fFirstDay      = 1;
+
+    if (num>0)
+        fNumBlocks = num;
+
+    fMoonAlignGraf = 0;
+    fMoonAlignText = 0;
+    fMoonTextType  = 0;
+    fMoonTextCont  = kFALSE;
+    fMoonRadius    = 0.08;
+
+    fMarginX       = 0.05;
+    fMarginY       = 0.05;
+
+    fCellSpace     = 0.01;
+    fBlockSpace    = 0.1;
+
+    if (fEnv)
+        delete fEnv;
+
+    fEnv = new MEnv("/dev/null");
+}
+
+//---------------------------------------------------------------------------
+//
+// Reset the holidays (remove everything)
+//
+void MCalendar::ResetHolidays()
+{
+    if (fEnvHolidays)
+        delete fEnvHolidays;
+
+    fEnvHolidays = new MEnv("/dev/null");
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the holidays to the default holidays
+//
+void MCalendar::SetDefaultHolidays()
+{
+    ResetHolidays();
+
+    fEnvHolidays->SetValue("Holiday.0",     "Easter");
+    fEnvHolidays->SetValue("Holiday.01/01", "New Year");
+    fEnvHolidays->SetValue("Holiday.12/25", "Christmas");
+    fEnvHolidays->SetValue("Holiday.12/26", "Christmas");
+}
+
+//---------------------------------------------------------------------------
+//
+// Set the layout to the default layout
+//
+// num is the number of default blocks (corresponding to NumBlocks).
+// A value smaller or equal 0 will leave the number of block unchanged
+// (which is the default)
+//
+void MCalendar::SetDefaultLayout(Int_t num)
+{
+    ResetLayout(num);
+
+    fMoonAlignGraf = 11;
+    fMoonAlignText = 11;
+
+    fEnv->SetValue("Contents", "Day Date Week Holiday Birthday");
+
+    fEnv->SetValue("Day.TextAlign",           "top left");
+    fEnv->SetValue("Day.Format",              "%e");
+
+    fEnv->SetValue("Date.TextAlign",          "bottom right");
+    fEnv->SetValue("Date.Format",             "%a");
+
+    fEnv->SetValue("Week.TextAlign",          "top right");
+    fEnv->SetValue("Week.Format",             "KW%V");
+    fEnv->SetValue("Week.TextSize",           0.1);
+    fEnv->SetValue("Week.Restriction",        1);
+    fEnv->SetValue("Week.Active.TextColor",   "Grey8");
+
+    fEnv->SetValue("Holiday.TextAlign",       "center");
+    fEnv->SetValue("Holiday.TextSize",        0.13);
+    fEnv->SetValue("Holiday.TextColor",       kBlue);
+
+    fEnv->SetValue("Birthday.TextAlign",      "center");
+    fEnv->SetValue("Birthday.TextSize",       0.13);
+    fEnv->SetValue("Birthday.TextColor",      kBlue);
+
+    //    fEnv->SetValue("Easter.TextAlign",        "center");
+    //    fEnv->SetValue("Easter.TextSize",         0.13);
+    //    fEnv->SetValue("Easter.TextColor",        kBlue);
+
+    fEnv->SetValue("Date.Active.0.TextColor", kRed);
+
+    fEnv->SetValue("Date.Active.TextFont",     22);
+    fEnv->SetValue("Day.Active.TextFont",      22);
+    fEnv->SetValue("Date.Inactive.TextFont",  132);
+    fEnv->SetValue("Day.Inactive.TextFont",   132);
+
+    // fEnv->SetValue("Date.Inactive.LineStyle", kDashed);
+    // fEnv->SetValue("Date.Inactive.FillColor", kWhite);
+}
+
+//---------------------------------------------------------------------------
+//
+// Create a calendar piece for the given year and month. If a filename
+// is given the corresponding resource file is read. If no month and/or
+// no year is given the current date is used instead.
+//
+MCalendar::MCalendar(UShort_t y, Byte_t m, const char *fname)
+   : fYear(y==0?MTime(-1).Year():y), fMonth(m==0?MTime(-1).Month():m)
+{
+    fEnv        =0;
+    fEnvHolidays=0;
+
+    //fUpdate = kFALSE;
+
+    SetDefaultLayout(2);
+    SetDefaultHolidays();
+
+    if (fname)
+        ReadResourceFile(fname);
+}
+
+//---------------------------------------------------------------------------
+//
+// Delete the two resource files
+//
+MCalendar::~MCalendar()
+{
+    delete fEnv;
+    delete fEnvHolidays;
+}
+
+//---------------------------------------------------------------------------
+//
+// Take the pave edges and the margin and calculate the new x and y
+// coordinates from it for the given alignment (as in TAttText),
+//
+TArrayD MCalendar::ConvertAlign(Int_t align, Double_t x[2], Double_t y[2], Double_t m[2]) const
+{
+    align = Rotate(align);
+
+    TArrayD p(2);
+    switch (align/10)
+    {
+    case 1: p[0] = x[0]+m[0];     break;
+    case 2: p[0] = (x[0]+x[1])/2; break;
+    case 3: p[0] = x[1]-m[0];     break;
+    }
+    switch (align%10)
+    {
+    case 1: p[1] = y[0]+m[1];     break;
+    case 2: p[1] = (y[0]+y[1])/2; break;
+    case 3: p[1] = y[1]-m[1];     break;
+    }
+    return p;
+}
+
+//---------------------------------------------------------------------------
+//
+// Rotate the aligment if the orientation is changed.
+//
+Int_t MCalendar::Rotate(Int_t align, Bool_t fwd) const
+{
+    if (fOrientation==fRotation)
+        return align;
+
+    static const Int_t b[4] = { 11, 31, 33, 13 };
+    static const Int_t a[4] = { 11, 13, 33, 31 };
+
+    const Int_t *c = fwd ? a :b;
+
+    for (int i=0; i<4; i++)
+        if (align==c[i])
+            return c[(i+1)%4];
+
+    return align;
+}
+
+//---------------------------------------------------------------------------
+//
+// Paint the text str at the position indirectly given by alignement, x and
+// y (see ConvertAlign for more details) with the attributes from TAttText.
+//
+void MCalendar::PaintLatex(TAttText &att, Int_t align, Double_t x[2], Double_t y[2], Double_t ratio[2], /*Double_t height,*/ TString str)
+{
+    TLatex tex;
+    att.Copy(tex);
+
+    Double_t m[2] = {
+        fMarginX*ratio[0],
+        fMarginY*ratio[1] 
+    };
+
+    const TArrayD p = ConvertAlign(align, x, y, m);
+     /*
+    tex.SetText(p[0], p[1], str);
+    tex.SetTextAngle(0);
+    tex.SetTextSize(att.GetTextSize()*height);
+
+    while (1)
+    {
+        Double_t w = tex.GetXsize();
+        Double_t h = tex.GetYsize();
+        if (w<width-2*m[0] && h<height-2*m[1])
+            break;
+
+        tex.SetTextSize(tex.GetTextSize()*0.99);
+    }
+
+    tex.Paint();
+    */
+
+    const Double_t scale = fOrientation            ? x[1]-x[0] : y[1]-y[0];
+    const Double_t phi   = fOrientation!=fRotation ? -90 : 0;
+
+    Convert2Latex(str);
+
+    tex.SetTextAlign(align);
+    tex.PaintLatex(p[0], p[1], phi, att.GetTextSize()*scale, str);
+}
+
+//---------------------------------------------------------------------------
+//
+// Paint a clock as a symbol for summer-/wintertime
+//
+void MCalendar::PaintClock(Double_t x[2], Double_t y[2], Double_t r[2], Int_t fill, char dir)
+{
+    Double_t k[2] = { (x[0]+x[1])/2, (y[0]+y[1])/2 };
+
+    TEllipse e(k[0], k[1], r[0]*2.5, r[1]*2.5, 30, 360, 0);
+    e.SetLineColor(kBlack);
+    e.SetLineStyle(kSolid);
+    e.SetFillColor(fill);
+    e.Paint();
+
+    TMarker m;
+    m.SetMarkerStyle(kFullDotSmall);
+    for (int i=2; i<12; i++)
+        m.PaintMarker(k[0]+r[0]*2*cos(TMath::TwoPi()*i/12),
+                      k[1]+r[1]*2*sin(TMath::TwoPi()*i/12));
+
+    TArrow a(k[0]+r[0]*3, k[1], k[0]+r[0]*2.7, k[1]+r[1]*1.5, r[1]/2);
+    a.Paint(dir=='-'?"->":"<-");
+}
+
+//---------------------------------------------------------------------------
+//
+// Check the holiday resources for a holiday matching the the resource name:
+//   name.mm/dd
+// while name is the name of the TObject, mm and dd are month and day
+// of the MTime.
+//
+TString MCalendar::GetHoliday(const TObject &o, const MTime &tm)
+{
+    const Int_t easter = (Int_t)MTime::GetEaster(fYear).GetMjd();
+
+    const TString fmt = o.GetTitle();
+
+    if (!fmt.IsNull())
+        return tm.GetStringFmt(fmt, GetLanguage());
+
+    TString env(o.GetName());
+
+    const TString post1 = Form(".%d", (Int_t)tm.GetMjd()-easter);
+    const TString post2 = Form(".%02d/%02d", tm.Month(), tm.Day());
+
+    TString rc;
+    for (int i=0; i<7; i++)
+    {
+        MTime tx(tm.GetMjd()+i);
+        const TString post3 = Form(".%02d/%02d-%d", tx.Month(), tx.Day(), (7-tm.WeekDay())%7);
+        rc = fEnvHolidays->GetValue(env+post3, rc);
+    }
+
+    rc = fEnvHolidays->GetValue(env+post1, rc);
+    rc = fEnvHolidays->GetValue(env+post2, rc);
+/*
+    if (fLanguage=="de_DE")
+    {
+        MTime t;
+        t.Set(fYear, 5, 14);
+        t.SetMjd(t.GetMjd()-t.WeekDay());
+
+        if ((Int_t)t.GetMjd() == easter + 49)
+            t.SetMjd(t.GetMjd()-7);
+
+        if ((Int_t)tm.GetMjd()==(Int_t)t.GetMjd())
+            return "Muttertag";
+    }
+
+  */
+    return rc;
+}
+
+void MCalendar::Paint(Option_t *opt)
+{
+    /*
+    if (fUpdate)
+    {
+        fEnv->SetAttLine(fActive?"Date.Active":"Date.Inactive", *this);
+        fUpdate = kFALSE;
+    }
+    */
+
+    // How should this be done?
+    //fOrientation = gPad->PixeltoX(1)>-gPad->PixeltoY(1);
+
+    MTime t;
+    t.Set(fYear, fMonth, 1);
+
+    Int_t n = t.WeekDay();
+
+    Int_t diff = (7-fFirstDay)%7;
+    n += diff;
+    n %= 7;
+
+    t.SetMjd(t.GetMjd()-n);
+    n = 0;
+
+    for (; n<99; n++)
+    {
+        const MTime tm(t.GetMjd()+n);
+
+        const Bool_t active = tm.Month()==(UInt_t)fMonth;
+
+        Double_t x[2], y[2], ratio[2];
+        const Bool_t rc =  GetBox(n, x, y, ratio);
+
+        if (!active && rc)
+            break;
+
+        // Get part of string for this day
+        const Int_t day = (n+7-diff)%7;
+
+        TPave pave;
+        pave.SetName("Date");
+        GetPave(pave, active, day);
+
+        // ---------- Paint Border and fill area ----------
+        pave.SetX1NDC(x[0]);
+        pave.SetY1NDC(y[0]);
+        pave.SetX2NDC(x[1]);
+        pave.SetY2NDC(y[1]);
+        pave.Paint(pave.GetOption());
+
+        Double_t r[2] = {
+            fMoonRadius*ratio[0],
+            fMoonRadius*ratio[1]
+        };
+
+        // ---------- Paint Text ----------
+        const TString contents = fEnv->GetValue("Contents", "");
+        TObjArray *arr = contents.Tokenize(" ");
+
+        TIter Next(arr);
+        TObject *o=0;
+        while ((o=Next()))
+        {
+            TLatex latex;
+            latex.SetName(o->GetName());
+
+            const TString res = fEnv->GetValue(Form("%s.Restriction", o->GetName()), "0123456");
+            if (res.First('0'+tm.WeekDay())<0)
+                continue;
+
+            GetLatex(latex, active, day);
+
+            const TString text = GetHoliday(latex, tm);
+
+            if (text=="T+" || text=="T-")
+            {
+                PaintClock(x, y, r, pave.GetFillColor(), text[1]);
+                continue;
+            }
+
+            if (!text.IsNull())
+                PaintLatex(latex, latex.GetTextAlign(), x, y, ratio, text);
+        }
+
+        delete arr;
+
+        // ---------- Paint Moon Phase -----------
+        //Double_t r[2] = {
+        //    fMoonRadius*ratio[0],
+        //    fMoonRadius*ratio[1]
+        //};
+        Double_t m[2] = {
+            fMarginX*ratio[0] + r[0],
+            fMarginY*ratio[1] + r[1]
+        };
+
+        TAttText text;
+        TAttFill fill;
+        GetMoon(text, fill, active, day);
+
+        // Shift if grafic and moon should be displayed at the same
+        // location, the text is a discrete number and it is
+        // switched to continous.
+        const Bool_t  rot  = fOrientation!=fRotation;
+        const Float_t phi  = rot ? -90 : 0;
+        const Int_t   dx   = rot;
+        const Int_t   dy   = (rot+1)%2;
+        const Bool_t  cont = fMoonTextType==0 || fMoonTextCont;
+        if (fMoonAlignGraf)
+        {
+            TArrayD p = ConvertAlign(fMoonAlignGraf, x, y, m);
+
+            if (fMoonAlignGraf==fMoonAlignText && cont && fMoonAlignGraf==22)
+                p[dy] += rot ? -m[dy]/2 : m[dy]/2;
+
+            TEllipse e(p[0], p[1], r[0], r[1], -90+phi, 90+phi, 0);
+            fill.Copy(e);
+            e.SetLineStyle(0);
+            e.Paint();
+            if (tm.GetMoonPhase()<0.5)
+            {
+                e.SetLineStyle(kSolid);
+                e.SetLineColor(pave.GetFillColor());
+                e.SetFillColor(pave.GetFillColor());
+            }
+            else
+            {
+                e.SetPhimin(90+phi);  // bug in PaintEllipse!
+                e.SetPhimax(270+phi); // bug in PaintEllipse!
+            }
+            const Double_t R  = tm.GetMoonPhase()<0.5 ? 1-tm.GetMoonPhase() : tm.GetMoonPhase();
+            const Double_t r0 = 1.0-TMath::Sqrt(2.0-2.0*R);
+            if (rot)
+                e.SetR2(r[1]*r0);  // bug in PaintEllipse!
+            else
+                e.SetR1(r[0]*r0);  // bug in PaintEllipse!
+            e.Paint();
+        }
+
+        if (fMoonAlignGraf==fMoonAlignText && !cont && tm.GetMoonPhase()>0.004)
+            continue;
+
+        // ---------- Paint Moon Text -----------
+        if (fMoonAlignText)
+        {
+            if (fMoonAlignGraf!=fMoonAlignText || (fMoonAlignGraf==fMoonAlignText && !cont))
+                m[dx] -= r[dx];
+
+            TArrayD p = ConvertAlign(fMoonAlignText, x, y, m);
+
+            if (fMoonAlignGraf==fMoonAlignText && cont)
+            {
+                if (rot)
+                {
+                    m[dx] = -m[dx];
+                    m[dy] = -m[dy];
+                }
+
+                switch (fMoonAlignGraf/10)
+                {
+                case 1: p[dx] += m[dx];                                          break;
+                case 2: p[dy] += fMoonAlignGraf%10==1 ? m[dy]*1.25 : -m[dy]*1.25; break;
+                case 3: p[dx] -= m[dx];                                          break;
+                }
+            }
+
+            TString num;
+            switch (fMoonTextType)
+            {
+            case 0:// kMoonPhase:
+                num = Form("%d%%", TMath::Nint(tm.GetMoonPhase()*100));
+                break;
+            case 1://kMoonPeriod:
+                num = Form("%d", (Int_t)tm.GetMoonPeriod());
+                break;
+            case 2://kMagicPeriod:
+                num = Form("%d", tm.GetMagicPeriod());
+                break;
+            }
+
+            const Double_t scale = fOrientation ? x[1]-x[0] : y[1]-y[0];
+
+            TLatex tex;
+            text.Copy(tex);
+            tex.SetTextAlign(10*(fMoonAlignText/10)+2);  // 12
+            tex.PaintLatex(p[0], p[1], phi, text.GetTextSize()*scale, num);
+        }
+    }
+
+    /*
+     TASImage img;
+     img.FromPad(gPad);
+     img.Flip(90);
+     img.Paint();
+     */
+}
+
+Bool_t MCalendar::GetBox(Int_t n, Double_t x[2], Double_t y[2], Double_t *ratio)
+{
+    //const Int_t   maxrows = 6; //28/(7*fNumBlocks) + 1;
+    const Float_t addrows = 0;
+
+    Int_t maxrows;
+    switch(fNumBlocks)
+    {
+    case 0:
+    case 1: maxrows=6; break;
+    case 2: maxrows=3; break;
+    case 3: maxrows=2; break;
+    case 4: maxrows=2; break;
+    default: maxrows=1; break;
+    }
+
+    const Float_t ratio0  = -gPad->PixeltoX(1)/gPad->PixeltoY(1);
+
+    // Cellspace
+    const Float_t  celly  = fCellSpace;
+    const Float_t  cellx  = fOrientation ? fCellSpace/ratio0 : fCellSpace*ratio0;
+
+    // Blockspace
+    //Float_t blockspacey = fBlockSpace;
+    const Float_t  blockx = fOrientation ? fBlockSpace/ratio0 : fBlockSpace*ratio0;
+
+    const Float_t  w      = (0.99-cellx*(7*fNumBlocks-1)-(fNumBlocks-1)*blockx)/(fNumBlocks*7);
+    const Float_t  h      = (0.99-celly*(maxrows-1)/*-blockspacey*/)/(maxrows+addrows);
+
+
+    const Int_t    ix     = n%(7*fNumBlocks);
+    const Int_t    iy     = n/(7*fNumBlocks);
+
+    const Int_t    col    = ix/7;
+
+    const Double_t p0     = 0.005 - col*(cellx - blockx);
+
+    TArrayD a(2), b(2);
+
+    a[0] =  p0   + ix*(cellx + w);
+    a[1] =  p0   + ix*(cellx + w) + w;
+
+    b[0] =  0.995 - iy*(celly + h) - h;
+    b[1] =  0.995 - iy*(celly + h);
+
+    if (ratio)
+    {
+        ratio[0] = ratio0>1 ? h : h*ratio0;
+        ratio[1] = ratio0>1 ? h/ratio0 : h;
+    }
+
+    if (fOrientation)
+    {
+        x[0] = b[0];
+        x[1] = b[1];
+        y[0] = a[0];
+        y[1] = a[1];
+    }
+    else
+    {
+        x[0] = a[0];
+        x[1] = a[1];
+        y[0] = b[0];
+        y[1] = b[1];
+    }
+
+    if (fOrientation)
+    {
+        TArrayD d(2,y);
+        y[0] = 1-d[1];
+        y[1] = 1-d[0];
+    }
+
+    if (fRotation)
+    {
+        TArrayD d(2,x);
+        x[0] = 1-d[1];
+        x[1] = 1-d[0];
+    }
+
+    return ix==0 && iy>0;
+}
+
+//---------------------------------------------------------------------------
+//
+// Determine the absolute number of the day from the event (mouse)
+// position.
+//
+Int_t MCalendar::GetN(Double_t x[2], Double_t y[2])
+{
+    if (!gPad)
+        return 0;
+
+    const Double_t px = gPad->AbsPixeltoX(gPad->GetEventX());
+    const Double_t py = gPad->AbsPixeltoY(gPad->GetEventY());
+
+    int n=0;
+    for (n=0; n<99; n++)
+    {
+        GetBox(n, x, y);
+        if (x[0]<px && px<x[1] && y[0]<py && py<y[1])
+           break;
+    }
+
+    return n==99 ? -1 : n;
+}
+
+//---------------------------------------------------------------------------
+//
+// Determine the date of the day from the event (mouse) position.
+//
+MTime MCalendar::GetDate()
+{
+    const Int_t n = GetN();
+    if (n<0)
+        return MTime();
+
+    MTime t;
+    t.Set(fYear, fMonth, 1);
+
+    Int_t k = t.WeekDay();
+
+    k += (7-fFirstDay)%7;
+    k %= 7;
+
+    return MTime(t.GetMjd()-k+n);
+}
+
+//---------------------------------------------------------------------------
+//
+// Determin the alignment of the event (mouse) position.
+//
+Int_t MCalendar::GetAlign()
+{
+    Double_t x[2], y[2];
+    if (GetN(x, y)<0)
+        return 0;
+
+    const Double_t px = gPad->AbsPixeltoX(gPad->GetEventX());
+    const Double_t py = gPad->AbsPixeltoY(gPad->GetEventY());
+
+    const Int_t alignx = (Int_t)(3*(px-x[0])/(x[1]-x[0]))+1;
+    const Int_t aligny = (Int_t)(3*(py-y[0])/(y[1]-y[0]))+1;
+
+    return Derotate(alignx*10+aligny);
+}
+
+//---------------------------------------------------------------------------
+//
+// Remove the text entry at the event (mouse) position.
+//
+void MCalendar::Remove(Int_t align)
+{
+    TObjArray *arr = TString(fEnv->GetValue("Contents", "")).Tokenize(" ");
+
+    TIter Next(arr);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        TAttText att;
+        fEnv->GetAttText(o->GetName(), att);
+
+        if (att.GetTextAlign()!=align)
+            continue;
+
+        TString cont = Form(" %s ", fEnv->GetValue("Contents", ""));
+        cont.ReplaceAll(Form(" %s ", o->GetName()), " ");
+        fEnv->SetValue("Contents", cont.Strip(TString::kBoth).Data());
+
+        RemoveEnv(o->GetName());
+    }
+
+    delete arr;
+}
+
+Int_t MCalendar::DistancetoPrimitive(Int_t x, Int_t y)
+{
+    const Double_t px = gPad->AbsPixeltoX(x);
+    const Double_t py = gPad->AbsPixeltoY(y);
+
+    return px>0.01 && px<0.99 && py>0.01 && py<0.99 ? 0 : 99999;
+}
+
+//---------------------------------------------------------------------------
+//
+// Add a holiday named "text" at the event (mouse) position.
+//
+void MCalendar::AddHoliday(const char *text)
+{
+    MTime t = GetDate();
+    if (!t)
+        return;
+
+    const TString str = Form("Holiday.%02d/%02d", t.Month(), t.Day());
+
+    fEnvHolidays->SetValue(str, text);
+}
+
+//---------------------------------------------------------------------------
+//
+// Add a birthday named "text" at the event (mouse) position.
+//
+void MCalendar::AddBirthday(const char *text)
+{
+    MTime t = GetDate();
+    if (!t)
+        return;
+
+    const TString str = Form("Birthday.%02d/%02d", t.Month(), t.Day());
+
+    fEnvHolidays->SetValue(str, text);
+}
+
+//---------------------------------------------------------------------------
+//
+// Add a easterday named "text" at the event (mouse) position. The special
+// thing is that the holiday is relative to easter and will shift with
+// easter for other years.
+//
+void MCalendar::AddEaster(const char *text)
+{
+    MTime t = GetDate();
+    if (!t)
+        return;
+
+    const Int_t easter = (Int_t)MTime::GetEaster(fYear).GetMjd();
+
+    const TString str = Form("Holiday.%d", (Int_t)t.GetMjd()-easter);
+
+    fEnvHolidays->SetValue(str, text);
+}
+
+//---------------------------------------------------------------------------
+//
+// Print the current resources.
+//
+void MCalendar::PrintEnv() const
+{
+    fEnv->Print();
+}
+
+//---------------------------------------------------------------------------
+//
+// Set a new resource.
+//
+void MCalendar::SetEnv(const char *VariableName, const char *Value) const
+{
+    fEnv->SetValue(VariableName, Value);
+}
+
+//---------------------------------------------------------------------------
+//
+// Remove a resource and all subsequent resources
+//
+void MCalendar::RemoveEnv(const char *name) const
+{
+    const TString n1 = name;
+    const TString n2 = Form("%s.", name);
+
+    TCollection *table = fEnv->GetTable();
+
+    TIter Next(table);
+    TObject *o=0;
+    while ((o=Next()))
+        if (n1==o->GetName() || TString(o->GetName()).BeginsWith(n2))
+            delete table->Remove(o);
+}
+
+//---------------------------------------------------------------------------
+//
+// Create a pad with the given coordinates, Draw a clone of the image
+// into it and resize the pad to the image properties such that it is
+// centered in the original area.
+//
+// DrawImage cd()'s to the new pad.
+//
+TASImage *MCalendar::DrawImage(const TASImage &img, Float_t x1, Float_t y1, Float_t x2, Float_t y2, Bool_t rot)
+{
+    TPad *pad=new TPad("Img", "Image", x1, y1, x2, y2);
+    pad->SetBorderMode(0);
+    pad->SetFillColor(gPad?gPad->GetFillColor():kWhite);
+    pad->SetBit(kCanDelete);
+    pad->SetTopMargin(0);
+    pad->SetRightMargin(0);
+    pad->SetLeftMargin(0);
+    pad->SetBottomMargin(0);
+    pad->Draw();
+
+    gROOT->SetSelectedPad(0);
+
+    pad->cd();
+
+    TASImage *clone = (TASImage*)img.DrawClone();
+    clone->SetBit(kCanDelete);
+
+    pad->Modified();
+    pad->Update();
+
+    const Int_t wi = clone->GetScaledWidth();
+    const Int_t hi = clone->GetScaledHeight();
+
+    TCanvas *c = pad->GetCanvas();
+
+    const Float_t x = (x1+x2)/2;
+    const Float_t y = (y1+y2)/2;
+
+    Float_t w = TMath::Abs(x2-x1)/2;
+    Float_t h = TMath::Abs(y2-y1)/2;
+
+    const Float_t ri = TMath::Abs(c->PixeltoX(wi)/c->PixeltoY(hi));
+    const Float_t rp = TMath::Abs(w/h);
+
+    if (ri>rp)
+        h = w/ri;
+    else
+        w = h*ri;
+
+    pad->SetPad(x-w, y-h, x+w, y+h);
+    pad->SetFixedAspectRatio();
+
+    return clone;
+}
+
+//---------------------------------------------------------------------------
+//
+// Small helper for GetImage: Allocate a new TASImage. If it is valid
+// return the pointer, if not delete the object and return NULL.
+//
+TASImage *MCalendar::ReturnFile(const char *file) const
+{
+    TASImage *img = new TASImage(file);
+    if (img->IsValid())
+        return img;
+
+    delete img;
+    return NULL;
+}
+
+//---------------------------------------------------------------------------
+//
+// Get a TASImage from a TEnv (if no TEnv is given as argument the
+// default resource file os used). The TEnv is searched for the following
+// tags in the following order:
+//
+//   %B:    The month name as defined by the local (try GetStringFmt("%B"))
+//   %b:    The abbreviation of the month name as defined by the local (try GetStringFmt("%b"))
+//   %02d:  The number of the month with leading zeros.
+//
+// If no tag could be found or the image read is invalid NULL is returned.
+// Otherwise a newly allocated TASImage is returned (the used is responsible
+// of deleting it)
+//
+TASImage *MCalendar::GetImage(TEnv *env, const char *pwd)
+{
+    if (!env)
+        env = fEnv;
+
+    TString fStrMonth  = GetStringFmt("%B");
+    TString fStrMonth3 = GetStringFmt("%b");
+
+    ConvertUTF8(fStrMonth3, kFALSE);
+    ConvertUTF8(fStrMonth,  kFALSE);
+
+    const TString path(pwd);
+
+    TString file = env->GetValue(fStrMonth, "");
+    if (!file.Strip(TString::kBoth).IsNull())
+        return ReturnFile(path+file);
+
+    file = env->GetValue(fStrMonth3, "");
+    if (!file.Strip(TString::kBoth).IsNull())
+        return ReturnFile(path+file);
+
+    file = env->GetValue(Form("%02d", fMonth), "");
+    if (!file.Strip(TString::kBoth).IsNull())
+        return ReturnFile(path+file);
+
+    return NULL;
+}
+
+//---------------------------------------------------------------------------
+//
+// Draw a Latex (after conversion with Convert2Latex, to support Umlauts,
+// etc) text text at the coordinates x and y with the attributes att.
+//
+// To use a date format string (see GetStringFmt()) instead of a plain
+// text use DrawDate instead.
+//
+void MCalendar::DrawLatex(Float_t x, Float_t y, const char *text, const TAttText &att)
+{
+    TString str(text);
+    Convert2Latex(str);
+
+    TLatex *latex = new TLatex(x, y, text);
+    att.Copy(*latex);
+    latex->SetBit(kCanDelete);
+    latex->Draw();
+}
+
+const char *MCalendar::GetTTFontPath(const char *file) const
+{
+    const TString p1 = gEnv->GetValue("Root.TTFontPath", "");
+    const TString p2 = "/usr/X11R6/lib/X11/fonts/truetype";
+   // const TString p3 = path;
+
+    TString n(file);
+
+    if (n.First('.')<0 && n.First('/')<0)
+        n.Append(".ttf");
+
+    return gSystem->Which(p1+":"+p2/*+":"+p3*/, n, kReadPermission);
+}
+
+//---------------------------------------------------------------------------
+//
+// Draw a Text text into your image. For more details see TASImage::DrawText.
+//
+// This is a wrapper to simplify access to TrueType Fonts.
+//
+// You can just skip the path and the extension, eg "comic" is enough for
+// the TTF "comic.ttf".
+//
+// The search path is "*.*.Root.TTFontPath" from gEnv (.rootrc),
+// "/usr/X11R6/lib/X11/fonts/truetype" and path.
+//
+// For available fonts see eg. $ROOTSYS/fonts
+//
+void MCalendar::DrawText(TASImage &img, Int_t x, Int_t y, const char *txt,
+                         Int_t size, const char *color, const char *font,
+                         TImage::EText3DType type, const char *path)
+{
+    const char *file = GetTTFontPath(font);
+    if (!file)
+        return;
+
+    img.DrawText(x, y, txt, size, color, file, type);
+
+    delete file;
+}
+
+#define __CINT__
+#include <TTF.h>
+TASImage *MCalendar::DrawTTF(Float_t x1, Float_t x2, Float_t y1, Float_t y2,
+                             const char *text, Float_t sz, const char *font)
+{
+    const char *file = GetTTFontPath(font);
+    if (!file)
+        return NULL;
+
+    const UInt_t size = TMath::Nint(sz*941);
+
+    delete file;
+
+    const Double_t x = (x1+x2)/2;
+    const Double_t y = (y1+y2)/2;
+
+    TASImage img;
+    DrawDate(img, 0, 0, text, size, "#000000", font);
+
+    const Double_t w = gPad->PixeltoX(img.GetWidth())/2;
+    const Double_t h = gPad->PixeltoY(img.GetHeight())/2;
+
+    return DrawImage(img, x-w, y-h, x+w, y+h);
+}
+
+/*
+void MCalendar::Update()
+{
+    cout << "Update" << endl;
+    fUpdate=kTRUE;
+}
+
+void MCalendar::Selected(TVirtualPad *pad,TObject *o,Int_t event)
+{
+    if (event==kButton1Down && pad)
+    {
+        pad->cd();
+        fAlign = GetAlign();
+        fActive = GetDate().Month()==fMonth;
+        fEnv->GetAttLine(fActive?"Date.Active":"Date.Inactive", *this);
+        fEnv->GetAttLine(Form(fActive?"Date.Active.%d":"Date.Inactive.%d", fDay), *this);
+    }
+
+    cout << "SetModel " << gPad << " " << pad << " " << o << " " << event << endl;
+    //Picked(fSelectedPad, fSelected, fEvent);  // emit signal
+
+}
+
+void MCalendar::SetAttributes()
+{
+    if (!gPad)
+        return;
+
+    TAttLine::SetLineAttributes();
+
+    cout << "gPad " << gPad << endl;
+
+    fAlign  = GetAlign();
+    fActive = GetDate().Month()==fMonth;
+    fDay    = GetDate().WeekDay();
+
+    fEnv->GetAttLine(fActive?"Date.Active":"Date.Inactive", *this);
+    fEnv->GetAttLine(Form(fActive?"Date.Active.%d":"Date.Inactive.%d", fDay), *this);
+
+    TQObject::Connect("TCanvas", "Selected(TVirtualPad*,TObject*,Int_t)",
+                      "MCalendar", this, "Selected(TVirtualPad*,TObject*,Int_t)");
+
+    TQObject::Connect("TGedPatternSelect", "PatternSelected(Style_t)", "MCalendar", this, "Update()");
+    TQObject::Connect("TGColorSelect",     "ColorSelected(Pixel_t)",   "MCalendar", this, "Update()");
+    TQObject::Connect("TGListBox",         "Selected(Int_t)",          "MCalendar", this, "Update()");
+}
+*/
+
Index: branches/Mars_McMismatchStudy/mtools/MCalendar.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MCalendar.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MCalendar.h	(revision 17960)
@@ -0,0 +1,224 @@
+#ifndef MARS_MCalendar
+#define MARS_MCalendar
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+#ifndef ROOT_TImage
+#include <TImage.h>
+#endif
+#ifndef ROOT_Gtypes
+#include <Gtypes.h>
+#endif
+
+/*
+#include <TAttLine.h>
+#include <TAttFill.h>
+#include <TAttText.h>
+*/
+
+class TEnv;
+class TPave;
+class TLatex;
+class TAttText;
+class TAttFill;
+class TArrayD;
+class TASImage;
+
+class MEnv;
+class MTime;
+
+class MCalendar : public TObject//, public TAttLine, public TAttText, public TAttFill
+{
+private:
+    /*
+    enum {
+        kMoonPhase,
+        kMoonPeriod,
+        kMagicPeriod
+    };*/
+
+    /*
+    Int_t  fAlign;
+    Bool_t fActive;
+    Bool_t fUpdate;
+    Int_t  fDay;
+    */
+    MEnv    *fEnv;
+    MEnv    *fEnvHolidays;
+
+    Bool_t   fOrientation;
+    Bool_t   fRotation;
+
+    Int_t    fYear;
+    Int_t    fMonth;
+    Int_t    fFirstDay;
+    Int_t    fNumBlocks;
+
+    TString  fLanguage;
+
+    Double_t fMarginX;
+    Double_t fMarginY;
+    Double_t fCellSpace;
+    Double_t fBlockSpace;
+
+    Int_t    fMoonAlignGraf;
+    Int_t    fMoonAlignText;
+    Int_t    fMoonTextType;
+    Int_t    fMoonTextCont;
+    Float_t  fMoonRadius;
+
+    // Resource file evaluation
+    void    GetPave(TPave &pave, Bool_t active, Int_t n);
+    void    GetMoon(TAttText &text, TAttFill &fill, Bool_t active, Int_t n);
+    void    GetLatex(TLatex &latex, Bool_t active, Int_t n);
+    TString GetHoliday(const TObject &o, const MTime &tm);
+
+    // Helper function for Paint
+    TArrayD ConvertAlign(Int_t align, Double_t x[2], Double_t y[2], Double_t m[2]) const;
+    Bool_t  GetBox(Int_t n, Double_t x[2], Double_t y[2], Double_t *ratio=0);
+
+    // Helper function for GetImage
+    TASImage  *ReturnFile(const char *file) const;
+    const char *GetTTFontPath(const char *file) const;
+
+    // Orientation
+    Int_t Rotate(Int_t align, Bool_t fwd=kTRUE) const;
+    Int_t Derotate(Int_t align) const { return Rotate(align, kFALSE); }
+
+    // Menu interaction
+    Int_t   GetN(Double_t x[2], Double_t y[2]);
+    Int_t   GetN() { Double_t x[2], y[2]; return GetN(x,y); }
+    MTime   GetDate();
+    Int_t   GetAlign();
+
+    // Paint text
+    void PaintLatex(TAttText &att, Int_t align, Double_t x[2], Double_t y[2], Double_t ratio[2], /*Double_t height,*/ TString str);
+    void PaintClock(Double_t x[2], Double_t y[2], Double_t r[2], Int_t fill, char dir);
+
+    // GUI interactions
+    Int_t DistancetoPrimitive(Int_t px, Int_t py);
+
+public:
+    MCalendar(UShort_t y=0, Byte_t m=0, const char *fname=0);
+    ~MCalendar();
+
+    TObject    *Clone(const char *newname="") const;
+
+    // Getter
+    const char *GetName() const { return Form("%04d-%02d", fYear, fMonth); }
+    const char *GetLanguage() const { return fLanguage; }
+    Int_t       GetYear() const { return fYear; }
+    Int_t       GetMonth() const { return fMonth; }
+    Int_t       GetFirstDay() const { return fFirstDay; }
+    Int_t       GetNumBlocks() const { return fNumBlocks; }
+    Double_t    GetMarginX() const { return fMarginX; }
+    Double_t    GetMarginY() const { return fMarginY; }
+    Double_t    GetCellSpace() const { return fCellSpace; }
+    Double_t    GetBlockSpace() const { return fBlockSpace; }
+    Int_t       GetMoonAlignGraf() const { return fMoonAlignGraf; }
+    Int_t       GetMoonAlignText() const { return fMoonAlignText; }
+    Int_t       GetMoonTextType() const { return fMoonTextType; }
+    Int_t       GetMoonTextCont() const { return fMoonTextCont; }
+    Float_t     GetMoonRadius() const { return fMoonRadius; }
+    TString     GetStringFmt(const char *fmt="%B", Int_t day=1, Int_t h=12, Int_t m=0, Int_t s=0) const;
+    Bool_t      IsRotated() const { return fRotation; }
+    Bool_t      IsVertical() const { return fOrientation; }
+
+
+    // Setter - Menu
+    void SetDate(UInt_t Month, Int_t Year=-1) { fMonth=Month; if (Year>0) fYear=Year; } // *MENU* *ARGS={Month=>fMonth,Year=>fYear}
+    void SetLocal(const char *Locale="") { fLanguage=Locale; } // *MENU* *ARGS={Locale=>fLanguage}
+    void SetFirstDay(Int_t FirstDay) { fFirstDay=FirstDay%7; } // *MENU* *ARGS={FirstDay=>fFirstDay}
+    void SetLayout(Byte_t NumberOfBlocks, Double_t MarginX, Double_t MarginY, Double_t CellSpace, Double_t BlockSpace) { fNumBlocks=NumberOfBlocks, fMarginX=MarginX; fMarginY=MarginY; fCellSpace=CellSpace; fBlockSpace=BlockSpace; } //*MENU* *ARGS={NumberOfBlocks=>fNumBlocks,MarginX=>fMarginX,MarginY=>fMarginY,CellSpace=>fCellSpace,BlockSpace=>fBlockSpace}
+
+    void ResetLayout(Int_t num);
+    void ResetLayout() { ResetLayout(-1); } //*MENU
+    void ResetHolidays(); //*MENU
+
+    void SetDefaultLayout(Int_t num);
+    void SetDefaultLayout() { SetDefaultLayout(-1); } //*MENU
+    void SetDefaultHolidays(); //*MENU
+
+    void ReadResourceFile(const char *FileName=0); //*MENU
+    void ReadHolidayFile(const char *FileName=0);  //*MENU
+    void SaveResourceFile(const char *FileName=0); //*MENU
+    void SaveHolidayFile(const char *FileName=0);  //*MENU
+
+    void Add(const char *Name, Int_t Align, const char *Format, Float_t FontSize=0.3, Int_t FontColor=1); //*MENU
+    void Add(const char *name, const char *fmt, const TAttText &att);
+
+    void SetDay(const char *Format="%a", Float_t FontSize=0.3, Int_t Color=kBlack)  { Remove(GetAlign()); Add("Day", GetAlign(), Format, FontSize, Color); } //*MENU*
+    void SetDate(const char *Format="%e", Float_t FontSize=0.3, Int_t Color=kBlack)  { Remove(GetAlign()); Add("Date", GetAlign(), Format, FontSize, Color); } //*MENU*
+    void SetHoliday(Float_t FontSize=0.13, Int_t Color=kBlue)   { Remove(GetAlign()); Add("Holiday", GetAlign(), "", FontSize, Color); }  //*MENU*
+    void SetBirthday(Float_t FontSize=0.13, Int_t Color=kBlue)  { Remove(GetAlign()); Add("Birthday", GetAlign(), "", FontSize, Color); } //*MENU*
+    void SetEaster(Float_t FontSize=0.13, Int_t Color=kBlue)    { Remove(GetAlign()); Add("Easter", GetAlign(), "", FontSize, Color); }   //*MENU*
+
+    void AddHoliday(const char *text);    //*MENU
+    void AddBirthday(const char *text);   //*MENU
+    void AddEaster(const char *text);     //*MENU
+
+    void Remove() { Remove(GetAlign()); } //*MENU*
+    void Remove(Int_t align);
+
+    //    void ToggleOrientation() { fOrientation = !fOrientation; } //*MENU
+    void SetRotated(Bool_t b=kTRUE) { fRotation = b; } // *TOGGLE* *GETTER=IsRotated
+    void SetVertical(Bool_t b=kTRUE) { fOrientation = b; } // *TOGGLE* *GETTER=IsVertical
+
+    void PrintEnv() const; //*MENU
+    void SetEnv(const char *VariableName, const char *Value) const;//*MENU
+    void RemoveEnv(const char *VariableName) const;//*MENU
+
+    void SetMoonGraf(Int_t Align, Float_t Radius) { fMoonAlignGraf=Align; fMoonRadius=Radius; } //*MENU* *ARGS={Align=>fMoonAlignGraf,Radius=>fMoonRadius}
+    void SetMoonText(Int_t Align, Int_t Type, Int_t Continous) { fMoonAlignText=Align; fMoonTextType=Type; fMoonTextCont=Continous; } //*MENU* *ARGS={Align=>fMoonAlignText,Type=>fMoonTextType,Continous=>fMoonTextCont}
+
+    // Calendar sheet interface
+    static TASImage *DrawImage(const TASImage &img, Float_t x1, Float_t y1, Float_t x2, Float_t y2, Bool_t rot=kFALSE);
+    TASImage *GetImage(TEnv *env=NULL, const char *path="");
+    void      DrawLatex(Float_t x, Float_t y, const char *text, const TAttText &att);
+    void      DrawDate(Float_t x, Float_t y, const char *text, const TAttText &att)
+    {
+        DrawLatex(x, y, GetStringFmt(text), att);
+    }
+    void DrawText(TASImage &img, Int_t x, Int_t y, const char *txt,
+                  Int_t size=50, const char *color = 0,
+                  const char *font = "fixed", TImage::EText3DType type = TImage::kPlain, const char *path=0);
+    void DrawDate(TASImage &img, Int_t x, Int_t y, const char *txt,
+                  Int_t size=50, const char *color = 0,
+                  const char *font = "fixed", TImage::EText3DType type = TImage::kPlain, const char *path=0)
+    {
+        DrawText(img, x, y, GetStringFmt(txt), size, color, font, type, path);
+    }
+    TASImage *DrawTTF(Float_t x1, Float_t x2, Float_t y1, Float_t y2,
+                      const char *text, Float_t size, const char *font);
+    TASImage *DrawTTFDate(Float_t x1, Float_t x2, Float_t y1, Float_t y2,
+                          const char *text, Float_t size, const char *font)
+    {
+        return DrawTTF(x1, y1, x2, y2, GetStringFmt(text), size, font);
+    }
+    //Bool_t DrawImage(TEnv &env, Float_t x1, Float_t y1, Float_t x2, Float_t y2) const;
+
+    // Convertions
+    static void Convert2Latex(TString &str);
+    static void ConvertUTF8(TString &str, Bool_t fwd=kTRUE);
+
+    // TObject
+    void Paint(Option_t *o="");
+
+    /*
+     void Update();
+     void SetLineAttributes() {}
+     void SetFillAttributes() {}
+     void SetTextAttributes() {}
+     void SetTextAngle(Float_t) {}
+     void Selected(TVirtualPad*,TObject*,Int_t);
+     */
+     //void SetAttributes(); //*MENU
+
+    ClassDef(MCalendar, 1)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/MChisqEval.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MChisqEval.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MChisqEval.cc	(revision 17960)
@@ -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 07/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MChisqEval
+//
+// Evaluates a chisq from one or two MParameterD calculated in an eventloop.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MChisqEval.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDataPhrase.h"
+#include "MParameters.h" // MParameterD
+
+#include "MParList.h"
+
+ClassImp(MChisqEval);
+
+using namespace std;
+
+const TString MChisqEval::gsDefName  = "MChisqEval";
+const TString MChisqEval::gsDefTitle = "Evaluate a chisq";
+
+MChisqEval::MChisqEval(const char *name, const char *title)
+    : fData0(NULL), fData1(NULL), fWeight(NULL), fNameResult("MinimizationValue")
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+MChisqEval::MChisqEval(MData *y1, const char *name, const char *title)
+: fData0(NULL), fData1(NULL), fWeight(NULL), fNameResult("MinimizationValue")
+{
+    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), fWeight(NULL), fNameResult("MinimizationValue")
+{
+    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 MDataPhrase(data));
+}
+
+void MChisqEval::SetY2(const TString data)
+{
+    SetY2(new MDataPhrase(data));
+}
+
+Int_t MChisqEval::PreProcess(MParList *plist)
+{
+    fChisq = 0;
+    fSumW  = 0;
+
+    if (!fData0)
+        return kFALSE;
+
+    if (!fData0->PreProcess(plist))
+        return kFALSE;
+
+    if (fData1)
+        if (!fData1->PreProcess(plist))
+            return kFALSE;
+
+    if (!fNameWeight.IsNull())
+    {
+        fWeight = (MParameterD*)plist->FindObject(fNameWeight, "MParameterD");
+        if (!fWeight)
+            return kFALSE;
+    }
+
+    fResult = (MParameterD*)plist->FindCreateObj("MParameterD", fNameResult);
+    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 er = fData1 ? y1*y2 : 1;
+
+    const Double_t w  = fWeight ? fWeight->GetVal() : 1;
+
+    fChisq += w*dy*dy/er;
+    fSumW  += w;
+
+    return kTRUE;
+}
+
+Int_t MChisqEval::PostProcess()
+{
+    if (GetNumExecutions()>0)
+        fChisq /= fSumW;
+
+    fResult->SetVal(fChisq);
+
+    *fLog << inf << GetDescriptor() << ": Result=" << fChisq << endl;
+
+    return kTRUE;
+}
+
+void MChisqEval::StreamPrimitive(ostream &out) const
+{
+    out << "   MChisqEval " << GetUniqueName() << ";";
+    if (fData0)
+        out << "   " << GetUniqueName() << ".SetY1(\"" << fData0->GetRule() << "\");" << endl;
+    if (fData1)
+        out << "   " << GetUniqueName() << ".SetY1(\"" << fData1->GetRule() << "\");" << endl;
+}
+
Index: branches/Mars_McMismatchStudy/mtools/MChisqEval.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MChisqEval.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MChisqEval.h	(revision 17960)
@@ -0,0 +1,56 @@
+#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;
+
+    MData   *fData0; // Data Member one (monte carlo data or chisq function)
+    MData   *fData1; // Data Member two (measured data)
+
+    MParameterD *fWeight;  //! Storage for weight
+    MParameterD *fResult;  //! Storage for result
+
+    TString fNameResult;
+    TString fNameWeight;
+
+    Double_t     fChisq;   //! Evaluated chi square
+    Double_t     fSumW;    //! Sum of weights
+
+    void StreamPrimitive(std::ostream &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); }
+    void SetNameWeight(TString w="MWeight") { fNameWeight=w; }
+
+    Double_t GetChisq() const { return fChisq; }
+ 
+    ClassDef(MChisqEval, 0)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/MCubicCoeff.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MCubicCoeff.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MCubicCoeff.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mtools/MCubicCoeff.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MCubicCoeff.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MCubicCoeff.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mtools/MCubicSpline.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MCubicSpline.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MCubicSpline.cc	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mtools/MCubicSpline.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MCubicSpline.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MCubicSpline.h	(revision 17960)
@@ -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: branches/Mars_McMismatchStudy/mtools/MFFT.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MFFT.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MFFT.cc	(revision 17960)
@@ -0,0 +1,1181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 01/2004  <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2001-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  Fast Fourier Transforms                                                 //
+//                                                                          //
+//  (Most of the code is adapted from Numerical Recipies in C++, 2nd ed.,   //
+//  pp. 509-563)                                                            //
+//                                                                          //
+//  Usage:                                                                  //
+//                                                                          //
+//  1) Functions RealFunctionFFT:  (FOURIER TRANSFORM)                      //
+//     * Take as argument arrays of real numbers,                           // 
+//       in some cases the dimension of the array has to be given separately//
+//     * Return a COMPLEX array with the following meaning:                 //
+//       array[0]: The value of F(0) (has only real component)              //
+//       array[1]: The value of F(N/2) (has only real component)            //
+//       array[2i]: The real part of F(i)                                   //
+//       array[2i+1]: The imaginary part of F(i)                            //
+//     * Note that F(N-i)* = F(i), therefore only the positive frequency    //
+//       half is stored.                                                    //
+//     * The dimension MUST be an integer power of 2,                       //
+//       otherwise, the array will be shortened!!                           //
+//                                                                          //
+//  2) Functions RealFunctionIFFT:  (INVERSER FOURIER TRANSFORM)            // 
+//     * Take as argument a COMPLEX array                                   //
+//       of Fourier-transformed REAL numbers                                //
+//       with the following meaning:                                        //
+//       array[0]: The value of F(0) (has only real component)              //
+//       array[1]: The value of F(N/2) (has only real component)            //
+//       array[2i]: The real part of F(i)                                   //
+//       array[2i+1]: The imaginary part of F(i)                            //
+//     * Returns the original complex array of dimension 2N-1               //                                
+//                                                                          //
+//  3) Functions PowerSpectrumDensity:                                      //
+//     * Return a histogram with the spectral density, i.e.                 //
+//       P(k) = 1/(N*N) * |F(k)|*|F(k)|                                     //
+//     * The histogram is ranged between 0 and 1./(2*binwidth)              //
+//     * The number of bins equals N/2+1                                    //
+//     * Note that histograms with unequal binwidth can not yet be treated! //
+//     * If the PSD does NOT CONVERGE to 0 at the maximum bin,              //
+//       you HAVE TO sample your data finer!                                //
+//
+// Fourier-Transformation:
+// =======================
+
+// (taken from http://www.parasitaere-kapazitaeten.net/Pd/ft.htm)
+//
+//  The Fourier-Transformation is a mathematical function that breaks
+// down a signal (like sound) into its frequency-spectrum as a set of
+// sinusoidal components, converting it from the Time Domain to the
+// Frequency Domain.
+// 
+//  In the Time Domain the signal x[ ] consists of N samples, labeled
+// from 0 to N-1. In the Frequency Domain the RFFT produces two signals
+// (signalvectors), treated as complex numbers representing the Real Part:
+// Re X[ ] and the Imaginary Part: Im X[ ]. They are seen as the Cosine-
+// und Sine-Components of the base frequencies. Each of these two signals
+// contains one more sample than the half of the original signal: N/2 + 1
+// samples. (this results from the fact, that the sine-components of the
+// first frequency (0) and the last (nyquist, N/2) are always 0). With the
+// complex Fourier-Transformation N complexe values are transformed to N
+// new complex values. For both it applies to: the Frequency Domain
+// contains exactly the same information as the Time-Domain.
+// 
+//  A Real FFT over 64 samples produces values for 33 cosine- and 33
+// sine-wave-amplitudes with the frequencies 0, 1, 2, 3, ..., 30, 31, 32.
+// The first value (frequency 0) is the DC (direct current), the other
+// values have to be seen in practice as factors of a
+// fundamental-frequency which can be calculated by dividing samplerate by
+// windowsize. The highest frequency is the nyquist-frequency
+// (samplerate/2).
+// 
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MFFT.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayD.h"
+#include "MArrayF.h"
+#include "MArrayI.h"
+
+ClassImp(MFFT);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor
+//  Initializes random number generator and default variables
+//
+MFFT::MFFT() : fDim(0)
+{
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. 
+//
+MFFT::~MFFT()
+{
+}
+
+void MFFT::TransformF(const Int_t isign, TArrayF &data)
+{
+  
+  UInt_t   n,mmax,m,j,istep,i;
+  Float_t wtemp,wr,wpr,wpi,wi,theta;
+  Float_t tempr,tempi;
+  
+  Int_t nn = fDim/2;
+  n = nn << 1;
+
+  //
+  // The bit-reversal section of the routine:
+  // Exchange the two complex numbers
+  //
+  j=1;
+  for (i=1;i<n;i+=2) {
+    if (j > i) {
+      Swap(data[j-1],data[i-1]);
+      Swap(data[j],data[i]);
+    }
+    m=nn;
+    while (m >= 2 && j > m) {
+      j -= m;
+      m >>= 1;
+    }
+    j += m;
+  }
+  // 
+  // Here begins the Danielson-Lanczos section of the routine
+  //
+  mmax=2;
+  while (n > mmax) {         // Outer loop executed log_2(nn) times
+
+    istep = mmax << 1;
+    //
+    // Initialize the trigonometric recurrence:
+    //
+    theta = isign*(6.28318530717959/mmax);
+
+    wtemp = TMath::Sin(0.5*theta);
+    wpr   = -2.0*wtemp*wtemp;
+    wpi   = TMath::Sin(theta);
+
+    wr=1.0;
+    wi=0.0;
+
+    for (m=1; m<mmax; m+=2) {
+      for (i=m; i<=n; i+=istep) {
+        // 
+        // The Danielson-Lanczos formula:
+        //
+        j          = i+mmax;
+        tempr      = wr*data[j-1] - wi*data[j];
+        tempi      = wr*data[j]   + wi*data[j-1];
+        data[j-1] = data[i-1]   - tempr;
+        data[j]   = data[i]     - tempi;
+        data[i-1] += tempr;
+        data[i]   += tempi;
+      }
+
+      //
+      // Trigonometric recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi+wr;
+      wi = wi*wpr         + wtemp*wpi+wi;
+
+    }
+    mmax=istep;
+  }
+}
+
+
+void MFFT::TransformD(const Int_t isign, TArrayD &data)
+{
+  
+  UInt_t   n,mmax,m,j,istep,i;
+  Double_t wtemp,wr,wpr,wpi,wi,theta;
+  Double_t tempr,tempi;
+  
+  Int_t nn = fDim/2;
+  n = nn << 1;
+
+  //
+  // The bit-reversal section of the routine:
+  // Exchange the two complex numbers
+  //
+  j=1;
+  for (i=1;i<n;i+=2) {
+    if (j > i) {
+      Swap(data[j-1],data[i-1]);
+      Swap(data[j],data[i]);
+    }
+    m=nn;
+    while (m >= 2 && j > m) {
+      j -= m;
+      m >>= 1;
+    }
+    j += m;
+  }
+  // 
+  // Here begins the Danielson-Lanczos section of the routine
+  //
+  mmax=2;
+  while (n > mmax) {         // Outer loop executed log_2(nn) times
+
+    istep = mmax << 1;
+    //
+    // Initialize the trigonometric recurrence:
+    //
+    theta = isign*(6.28318530717959/mmax);
+
+    wtemp = TMath::Sin(0.5*theta);
+    wpr   = -2.0*wtemp*wtemp;
+    wpi   = TMath::Sin(theta);
+
+    wr=1.0;
+    wi=0.0;
+
+    for (m=1; m<mmax; m+=2) {
+      for (i=m; i<=n; i+=istep) {
+        // 
+        // The Danielson-Lanczos formula:
+        //
+        j          = i+mmax;
+        tempr      = wr*data[j-1] - wi*data[j];
+        tempi      = wr*data[j]   + wi*data[j-1];
+        data[j-1] = data[i-1]   - tempr;
+        data[j]   = data[i]     - tempi;
+        data[i-1] += tempr;
+        data[i]   += tempi;
+      }
+
+      //
+      // Trigonometric recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi+wr;
+      wi = wi*wpr         + wtemp*wpi+wi;
+
+    }
+    mmax=istep;
+  }
+}
+
+//
+// Calculates the Fourier transform of a set of n real-valued data points. 
+// Replaces this data (which is stored in array data[1..n]) by the positive
+// frequency half of its complex Fourier transform. The real-valued first 
+// and last components of the complex transform are returned as elements 
+// data[1] and data[2], respectively. n must be a power of 2. This routine
+// also calculates the inverse transform of a complex data array if it is 
+// the transform of real data. (Result in this case mus be multiplied by 
+// 2/n.). From NUMERICAL RECIPES IN C++.
+//
+void MFFT::RealFTF(const Int_t isign)
+{
+  
+  Int_t    i,i1,i2,i3,i4;
+  Float_t  c1=0.5,c2,h1r,h1i,h2r,h2i;
+  Float_t wr,wi,wpr,wpi,wtemp,theta;
+
+  //
+  // Initialize the recurrence
+  //
+  theta = TMath::Pi() / (Double_t)(fDim>>1);
+
+  if(isign==1) // forward transform
+    {
+      c2    = -0.5;
+      TransformF(1,fDataF);
+    }
+  else         // set up backward transform
+    {
+      c2    = 0.5;
+      theta = -theta;
+    }
+
+  wtemp = TMath::Sin(0.5*theta);
+  wpr   = -2.0*wtemp*wtemp;
+  wpi   = TMath::Sin(theta);
+
+  wr    = 1.0 + wpr;
+  wi    = wpi;
+
+  for(i=1;i<(fDim>>2);i++) // case i=0 done separately below
+    {
+
+      i2 = 1 + (i1 = i+i);
+      i4 = 1 + (i3 = fDim-i1);
+
+      //
+      // The two separate transforms are separated out of the data
+      //
+      h1r  =  c1*(fDataF[i1]+fDataF[i3]);
+      h1i  =  c1*(fDataF[i2]-fDataF[i4]);
+      h2r  = -c2*(fDataF[i2]+fDataF[i4]);
+      h2i  =  c2*(fDataF[i1]-fDataF[i3]);
+
+      //
+      // Here, they are recombined to from the true transform 
+      // of the orginal real data
+      //
+      fDataF[i1] =  h1r + wr*h2r - wi*h2i;
+      fDataF[i2] =  h1i + wr*h2i + wi*h2r;
+      fDataF[i3] =  h1r - wr*h2r + wi*h2i;
+      fDataF[i4] = -h1i + wr*h2i + wi*h2r;
+      
+      //
+      // The recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi + wr;
+      wi =    wi*wpr   + wtemp*wpi + wi;
+    }
+
+  //
+  // Squeeze the first and last data together to get them all 
+  // within the original array
+  //
+  if(isign==1)
+    {
+      fDataF[0] = (h1r=fDataF[0]) + fDataF[1];
+      fDataF[1] =     h1r  -      fDataF[1];
+    }
+  else
+    {
+
+      fDataF[0] = c1*((h1r=fDataF[0]) + fDataF[1]);
+      fDataF[1] = c1*(h1r-fDataF[1]);
+
+      //
+      // The inverse transform for the case isign = -1
+      //
+      TransformF(-1,fDataF);  
+
+      //
+      // normalize correctly (not done in original NR's)
+      //
+      for(i=1;i<=fDim;i++)
+        fDataF[i] *= (2./fDim);
+    }
+}
+void MFFT::RealFTD(const Int_t isign)
+{
+  
+  Int_t    i,i1,i2,i3,i4;
+  Float_t  c1=0.5,c2,h1r,h1i,h2r,h2i;
+  Double_t wr,wi,wpr,wpi,wtemp,theta;
+
+  //
+  // Initialize the recurrence
+  //
+  theta=3.141592653589793/(Double_t) (fDim>>1);
+
+  if(isign==1) // forward transform
+    {
+      c2    = -0.5;
+      TransformD(1,fDataD);
+    }
+  else         // set up backward transform
+    {
+      c2    = 0.5;
+      theta = -theta;
+    }
+
+  wtemp = TMath::Sin(0.5*theta);
+  wpr   = -2.0*wtemp*wtemp;
+  wpi   = TMath::Sin(theta);
+
+  wr    = 1.0 + wpr;
+  wi    = wpi;
+
+  for(i=1;i<(fDim>>2);i++) // case i=0 done separately below
+    {
+
+      i2 = 1 + (i1 = i+i);
+      i4 = 1 + (i3 = fDim-i1);
+
+      //
+      // The two separate transforms are separated out of the data
+      //
+      h1r  =  c1*(fDataD[i1]+fDataD[i3]);
+      h1i  =  c1*(fDataD[i2]-fDataD[i4]);
+      h2r  = -c2*(fDataD[i2]+fDataD[i4]);
+      h2i  =  c2*(fDataD[i1]-fDataD[i3]);
+
+      //
+      // Here, they are recombined to from the true transform 
+      // of the orginal real data
+      //
+      fDataD[i1] =  h1r + wr*h2r - wi*h2i;
+      fDataD[i2] =  h1i + wr*h2i + wi*h2r;
+      fDataD[i3] =  h1r - wr*h2r + wi*h2i;
+      fDataD[i4] = -h1i + wr*h2i + wi*h2r;
+      
+      //
+      // The recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi + wr;
+      wi =    wi*wpr   + wtemp*wpi + wi;
+    }
+
+  //
+  // Squeeze the first and last data together to get them all 
+  // within the original array
+  //
+  if(isign==1)
+    {
+      fDataD[0] = (h1r=fDataD[0]) + fDataD[1];
+      fDataD[1] =     h1r  -      fDataD[1];
+    }
+  else
+    {
+
+      fDataD[0] = c1*((h1r=fDataD[0]) + fDataD[1]);
+      fDataD[1] = c1*(h1r-fDataD[1]);
+
+      //
+      // The inverse transform for the case isign = -1
+      //
+      TransformD(-1,fDataD);  
+      
+      //
+      // normalize correctly (not done in original NR's)
+      //
+      for(i=1;i<=fDim;i++)
+        fDataD[i] *= (2./fDim);
+    }
+}
+
+
+//
+// Fast Fourier Transform for float arrays
+//
+Float_t* MFFT::RealFunctionFFT(const Int_t n, const Float_t *data)
+{
+
+  fDim = n;
+  CheckDim(n);
+
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data[i];
+
+  RealFTF(1);
+  
+  return fDataF.GetArray();
+
+}
+
+//
+// Fast Inverse Fourier Transform for float arrays
+//
+Float_t* MFFT::RealFunctionIFFT(const Int_t n, const Float_t *data)
+{
+
+  fDim = n;
+  CheckDim(fDim);
+  
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data[i];
+
+  RealFTF(-1);
+  
+  return fDataF.GetArray();
+
+}
+
+//
+// Fast Fourier Transform for double arrays
+//
+Double_t* MFFT::RealFunctionFFT(const Int_t n, const Double_t *data)
+{
+
+  fDim = n;
+  CheckDim(n);
+
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data[i];
+
+  RealFTD(1);
+  
+  return fDataD.GetArray();
+
+}
+
+//
+// Fast Inverse Fourier Transform for double arrays
+//
+Double_t* MFFT::RealFunctionIFFT(const Int_t n, const Double_t *data)
+{
+
+  fDim = n;
+  CheckDim(fDim);
+  
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data[i];
+
+  RealFTD(-1);
+  
+  return fDataD.GetArray();
+
+}
+
+//
+// Fast Fourier Transform for TArrayF's
+//
+TArrayF* MFFT::RealFunctionFFT(const TArrayF *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data->At(i);
+
+  RealFTF(1);
+  
+  return new TArrayF(fDim,fDataF.GetArray());
+
+}
+
+//
+// Inverse Fast Fourier Transform for TArrayF's
+//
+TArrayF* MFFT::RealFunctionIFFT(const TArrayF *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+  
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data->At(i);
+
+  RealFTF(-1);
+
+  return new TArrayF(fDim,fDataF.GetArray());
+}
+
+
+//
+// Fast Fourier Transform for TArrayD's
+//
+TArrayD* MFFT::RealFunctionFFT(const TArrayD *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data->At(i);
+
+  RealFTD(1);
+  
+  return new TArrayD(fDim,fDataD.GetArray());
+
+}
+
+//
+// Inverse Fast Fourier Transform for TArrayD's
+//
+TArrayD* MFFT::RealFunctionIFFT(const TArrayD *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+  
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data->At(i);
+
+  RealFTD(-1);
+
+  return new TArrayD(fDim,fDataD.GetArray());
+}
+
+//----------------------------------------------------------
+//
+// Power Spectrum Density Calculation
+//
+TH1D* MFFT::PowerSpectrumDensity(const TH1D *hist)
+{
+
+  TH1D *newhist = (TH1D*)CheckHist(hist,1);
+
+  fDataD.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = hist->GetBinContent(i);
+
+  RealFTD(1);
+
+  Int_t dim2 = fDim*fDim;
+  Double_t c02;
+  Double_t ck2;
+  Double_t cn2;
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //    (stored in fData{0])
+  //
+  c02 = fDataD[0]*fDataD[0];
+  newhist->Fill(c02/dim2);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)| + |C(N-k)|*|C(N-k)|)
+  //
+  for (Int_t k=2;k<fDim-2;k+=2)
+    {
+
+      Int_t ki  = k+1;
+      ck2 = (fDataD[k]*fDataD[k] + fDataD[ki]*fDataD[ki]);
+      newhist->Fill(ck2/dim2);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //    (stored in fData[1])
+  //
+  cn2 = (fDataD[1]*fDataD[1]);
+  newhist->Fill(cn2/dim2);
+
+  return newhist;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for TArrayF
+//
+TArrayF* MFFT::PowerSpectrumDensity(const TArrayF *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  
+  TArrayF *newarray = new TArrayF(dim05);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataF[0]*fDataF[0]);
+  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataF[1]*fDataF[1]);
+  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for TArrayI
+//
+TArrayF* MFFT::PowerSpectrumDensity(const TArrayI *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = (Float_t)array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  
+  TArrayF *newarray = new TArrayF(dim05);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataF[0]*fDataF[0]);
+  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataF[1]*fDataF[1]);
+  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for TArrayD
+//
+TArrayD* MFFT::PowerSpectrumDensity(const TArrayD *array)
+{
+  
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataD.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = array->At(i);
+
+  RealFTD(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  
+  TArrayD *newarray = new TArrayD(dim05);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataD[0]*fDataD[0]);
+  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataD[k2]*fDataD[k2] + fDataD[k2+1]*fDataD[k2+1]);
+      newarray->AddAt(ck2/dim2,k);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataD[1]*fDataD[1]);
+  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for MArrayF
+// The difference to the TArrayF versions is that 
+// the resulting array has two entries less, namely 
+// the first and last one are skipped!
+//
+MArrayF* MFFT::PowerSpectrumDensity(const MArrayF *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t ck2;
+  
+  MArrayF *newarray = new MArrayF(dim05-2);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  //  c02 = (fDataF[0]*fDataF[0]);
+  //  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k-1);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  //  cn2 = (fDataF[1]*fDataF[1]);
+  //  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+//-----------------------------------------------------
+//
+// Power Spectrum Density calculation for MArrayI
+// The difference to the TArrayI versions is that 
+// the resulting array has two entries less, namely 
+// the first and last one are skipped!
+//
+MArrayF* MFFT::PowerSpectrumDensity(const MArrayI *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = (Float_t)array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t ck2;
+  
+  MArrayF *newarray = new MArrayF(dim05-2);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  //  c02 = (fDataF[0]*fDataF[0]);
+  //  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k-1);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  //  cn2 = (fDataF[1]*fDataF[1]);
+  //  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for MArrayD
+// The difference to the TArrayI versions is that 
+// the resulting array has two entries less, namely 
+// the first and last one are skipped!
+//
+MArrayD* MFFT::PowerSpectrumDensity(const MArrayD *array)
+{
+  
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataD.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = array->At(i);
+
+  RealFTD(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t ck2;
+  
+  MArrayD *newarray = new MArrayD(dim05-2);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  //  c02 = (fDataD[0]*fDataD[0]);
+  //  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataD[k2]*fDataD[k2] + fDataD[k2+1]*fDataD[k2+1]);
+      newarray->AddAt(ck2/dim2,k-1);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  //  cn2 = (fDataD[1]*fDataD[1]);
+  //  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -----------------------------------------------
+//
+// Power Spectrum Density calculation for TH1
+//
+TH1F* MFFT::PowerSpectrumDensity(const TH1 *hist)
+{
+
+  TH1F *newhist = (TH1F*)CheckHist(hist,0);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = hist->GetBinContent(i);
+
+  RealFTF(1);
+
+  Int_t dim2 = fDim*fDim;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataF[0]*fDataF[0]);
+  newhist->Fill(0.,c02/dim2);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=2;k<fDim;k+=2)
+    {
+      ck2 = (fDataF[k]*fDataF[k] + fDataF[k+1]*fDataF[k+1]);
+      newhist->Fill(k/2.,ck2/dim2);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataF[1]*fDataF[1]);
+  newhist->Fill(fDim/2.-1.,cn2/dim2);
+  
+  return newhist;
+}
+
+
+//
+// Power Spectrum Density calculation for TH1I
+//
+TH1F* MFFT::PowerSpectrumDensity(const TH1F *hist)
+{
+  return PowerSpectrumDensity((TH1*)hist);
+}
+
+//
+// Power Spectrum Density calculation for TH1I
+//
+TH1F* MFFT::PowerSpectrumDensity(const TH1I *hist)
+{
+  return PowerSpectrumDensity((TH1*)hist);
+}
+
+
+void MFFT::CheckDim(Int_t a)
+{
+
+  // If even number, return 0
+  if (a==2)  return;
+
+  // If odd number, return the closest power of 2
+  if (a & 1) 
+    { 
+      Int_t b = 1; 
+      while (b < fDim/2+1)
+        b <<= 1; 
+
+      fDim = b;
+      //      gLog << warn << "Dimension of Data is not a multiple of 2, will take only first " 
+      //           << fDim << " entries! " << endl;
+      return; 
+    }
+
+  CheckDim(a>>1);
+}
+
+TH1* MFFT::CheckHist(const TH1 *hist, const Int_t flag)
+{
+  
+  // number of entries
+  fDim = hist->GetNbinsX();
+  CheckDim(fDim);
+
+  // Step width
+  Double_t delta = hist->GetBinWidth(1);
+  
+  // Nyquist frequency
+  Axis_t fcrit = 1./(2.*delta);
+  Axis_t low = -0.5;
+  Axis_t up  = fcrit;
+
+  switch (flag)
+    {
+    case 0: 
+      return new TH1F(Form("%s%s",hist->GetName()," PSD"),
+                      Form("%s%s",hist->GetTitle()," - Power Spectrum Density"),
+                      fDim/2,low,up);
+      break;
+    case 1:
+      return new TH1D(Form("%s%s",hist->GetName()," PSD"),
+                      Form("%s%s",hist->GetTitle()," - Power Spectrum Density"),
+                      fDim/2,low,up);
+      break;
+    default:
+      return new TH1F(Form("%s%s",hist->GetName()," PSD"),
+                      Form("%s%s",hist->GetTitle()," - Power Spectrum Density"),
+                      fDim/2,low,up);
+      break;
+    }
+}
+
+//
+// Real function spectrum with data windowing
+//
+TArrayF* MFFT::RealFunctionSpectrum(const TArrayF *data) 
+{
+  
+  fDim = data->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data->At(i);
+
+  fWindowF.Set(fDim);
+
+  Int_t dim2 = fDim/2;
+
+  TArrayF *power = new TArrayF(dim2);
+
+  // 
+  // Start program spctrm from NR's
+  //
+  Float_t w, facp, facm, sumw=0.;
+  
+  facm = dim2;
+  facp = 1./dim2;
+  
+  for (Int_t j=0;j<dim2;j++)
+    {
+      Int_t j2 = j+j;
+      w     = ApplyWindow(j,facm,facp);
+      sumw += w*w;
+      fWindowF[j2]   = fDataF[j]*w;
+      fWindowF[j2+1] = fDataF[dim2+j]*w;
+    }
+  
+  TransformF(1,fWindowF);
+  
+  power->AddAt(fWindowF[0]*fWindowF[0] + fWindowF[1]*fWindowF[1],0);
+
+  //  power->AddAt(fWindowF[0]*fWindowF[0],0);
+  //  power->AddAt(fWindowF[1]*fWindowF[1],dim2-1);  
+
+
+  for (Int_t j=1;j<dim2;j++)
+    //  for (Int_t j=1;j<dim2;j++)
+    {
+      Int_t j2 = j+j;
+      Float_t buf = fWindowF[j2+1]     *fWindowF[j2+1] 
+                  + fWindowF[j2  ]     *fWindowF[j2  ] 
+                  + fWindowF[fDim-j2+1]*fWindowF[fDim-j2+1] 
+                  + fWindowF[fDim-j2  ]*fWindowF[fDim-j2  ] ;
+      power->AddAt(buf/sumw/(fDim+fDim),j);
+    }
+  
+  return power;
+
+}
Index: branches/Mars_McMismatchStudy/mtools/MFFT.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MFFT.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MFFT.h	(revision 17960)
@@ -0,0 +1,92 @@
+#ifndef MARS_MFFT
+#define MARS_MFFT
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include "TArrayF.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include "TArrayD.h"
+#endif
+
+#ifndef ROOT_TH1F
+#include "TH1F.h"
+#endif
+
+#ifndef ROOT_TH1D
+#include "TH1D.h"
+#endif
+
+class MArrayI;
+class MArrayD;
+class MArrayF;
+class MFFT : public TObject
+{
+private:
+
+  void Swap(Float_t &a,  Float_t &b)    { Float_t  c = a;  a = b;  b = c;  }
+  void Swap(Double_t &a, Double_t &b)   { Double_t c = a;  a = b;  b = c;  }
+
+  void TransformF(const Int_t isign, TArrayF &data);
+  void TransformD(const Int_t isign, TArrayD &data);  
+  void RealFTF(const Int_t isign);
+  void RealFTD(const Int_t isign);
+
+  void CheckDim(Int_t a);
+  TH1 *CheckHist(const TH1 *hist, const Int_t flag);
+
+  Float_t ApplyWindow(const Int_t j, const Float_t a, const Float_t b) const 
+    {
+
+      return 1.0-TMath::Abs((j-a)*b);      // Bartlett
+      // return 1.0;                        // Square
+      // return 1.0-(((j-a)*b)*((j-a)*b));   // Welch
+      
+    }
+  
+  Int_t   fDim;
+  TArrayF fDataF;
+  TArrayD fDataD;  
+  TArrayF fWindowF;
+  TArrayD fWindowD;  
+
+public:
+
+  MFFT();
+  ~MFFT();
+
+  TArrayF*  RealFunctionFFT( const TArrayF *data);
+  TArrayF*  RealFunctionIFFT(const TArrayF *data);  
+  
+  TArrayD*  RealFunctionFFT( const TArrayD *data);
+  TArrayD*  RealFunctionIFFT(const TArrayD *data);  
+  
+  Float_t*  RealFunctionFFT( const Int_t n, const Float_t *data);
+  Float_t*  RealFunctionIFFT(const Int_t n, const Float_t *data);  
+  
+  Double_t* RealFunctionFFT( const Int_t n, const Double_t *data);
+  Double_t* RealFunctionIFFT(const Int_t n, const Double_t *data);  
+  
+  TH1F* PowerSpectrumDensity(const TH1 *hist);
+  TH1F* PowerSpectrumDensity(const TH1F *hist);
+  TH1F* PowerSpectrumDensity(const TH1I *hist);  
+  TH1D* PowerSpectrumDensity(const TH1D *hist);
+
+  TArrayF* PowerSpectrumDensity(const TArrayI *array);  
+  TArrayF* PowerSpectrumDensity(const TArrayF *array);
+  TArrayD* PowerSpectrumDensity(const TArrayD *array);
+
+  MArrayF* PowerSpectrumDensity(const MArrayI *array);  
+  MArrayF* PowerSpectrumDensity(const MArrayF *array);
+  MArrayD* PowerSpectrumDensity(const MArrayD *array);
+
+  TArrayF*  RealFunctionSpectrum(const TArrayF *data);
+  
+  ClassDef(MFFT,0)  // Class to perform a Fast Fourier Transform
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mtools/MHSimulatedAnnealing.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MHSimulatedAnnealing.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MHSimulatedAnnealing.cc	(revision 17960)
@@ -0,0 +1,248 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug <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 <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: branches/Mars_McMismatchStudy/mtools/MHSimulatedAnnealing.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MHSimulatedAnnealing.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MHSimulatedAnnealing.h	(revision 17960)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHSimulatedAnnealing
+#define MARS_MHSimulatedAnnealing
+///////////////////////////////////////////////////////////////////////////////
+//
+//  MHSimulatedAnnealing
+//
+///////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+
+#ifndef ROOT_TVector
+#include <TVector.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: branches/Mars_McMismatchStudy/mtools/MRolke.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MRolke.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MRolke.cc	(revision 17960)
@@ -0,0 +1,799 @@
+// @(#)root/physics:$Name: not supported by cvs2svn $:$Id: MRolke.cc,v 1.2 2006-10-17 16:32:52 meyer Exp $
+// Author: Jan Conrad    9/2/2004
+
+/*************************************************************************
+ * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRolke
+//
+//  This class computes confidence intervals for the rate of a Poisson
+//  in the presence of background and efficiency with a fully frequentist
+//  treatment of the uncertainties in the efficiency and background estimate
+//  using the profile likelihood method.
+//
+//  The signal is always assumed to be Poisson.
+//
+//  The method is very similar to the one used in MINUIT (MINOS).
+//
+//  Two options are offered to deal with cases where the maximum likelihood
+//  estimate (MLE) is not in the physical region. Version "bounded likelihood" 
+//  is the one used by MINOS if bounds for the physical region are chosen. Versi//  on "unbounded likelihood (the default) allows the MLE to be in the 
+//  unphysical region. It has however better coverage. 
+//  For more details consult the reference (see below). 
+//
+//
+//   It allows the following Models:
+//
+//       1: Background - Poisson, Efficiency - Binomial  (cl,x,y,z,tau,m)
+//       2: Background - Poisson, Efficiency - Gaussian  (cl,xd,y,em,tau,sde)
+//       3: Background - Gaussian, Efficiency - Gaussian (cl,x,bm,em,sd)
+//       4: Background - Poisson, Efficiency - known     (cl,x,y,tau,e)
+//       5: Background - Gaussian, Efficiency - known    (cl,x,y,z,sdb,e)
+//       6: Background - known, Efficiency - Binomial    (cl,x,z,m,b)
+//       7: Background - known, Efficiency - Gaussian    (cl,x,em,sde,b)
+//
+//  Parameter definition:
+//
+//  cl  =  Confidence level
+//
+//  x = number of observed events
+//
+//  y = number of background events
+//
+//  z = number of simulated signal events
+//
+//  em = measurement of the efficiency.
+//
+//  bm = background estimate
+//
+//  tau = ratio between signal and background region (in case background is
+//  observed) ratio between observed and simulated livetime in case
+//  background is determined from MC.
+//
+//  sd(x) = sigma of the Gaussian
+//
+//  e = true efficiency (in case known)
+//
+//  b = expected background (in case known)
+//
+//  m = number of MC runs
+//
+//  mid = ID number of the model ...
+//
+//  For a description of the method and its properties:
+//
+//  W.Rolke, A. Lopez, J. Conrad and Fred James
+//  "Limits and Confidence Intervals in presence of nuisance parameters"
+//   http://lanl.arxiv.org/abs/physics/0403059
+//   Nucl.Instrum.Meth.A551:493-503,2005
+//
+//  Should I use MRolke, TFeldmanCousins, TLimit?
+//  ============================================
+//  1. I guess MRolke makes TFeldmanCousins obsolete?
+//
+//  Certainly not. TFeldmanCousins is the fully frequentist construction and 
+//  should be used in case of no (or negligible uncertainties). It is however 
+//  not capable of treating uncertainties in nuisance parameters.
+//  MRolke is desined for this case and it is shown in the reference above
+//  that it has good coverage properties for most cases, ie it might be
+//  used where FeldmannCousins can't.
+//
+//  2. What are the advantages of MRolke over TLimit?
+//
+//  MRolke is fully frequentist. TLimit treats nuisance parameters Bayesian. 
+//  For a coverage study of a Bayesian method refer to 
+//  physics/0408039 (Tegenfeldt & J.C). However, this note studies 
+//  the coverage of Feldman&Cousins with Bayesian treatment of nuisance 
+//  parameters. To make a long story short: using the Bayesian method you 
+//  might introduce a small amount of over-coverage (though I haven't shown it 
+//  for TLimit). On the other hand, coverage of course is a not so interesting 
+//  when you consider yourself a Bayesian.
+//
+// Author: Jan Conrad (CERN)
+//
+// see example in tutorial Rolke.C
+//
+// Copyright CERN 2004                Jan.Conrad@cern.ch
+//
+///////////////////////////////////////////////////////////////////////////
+
+
+#include "MRolke.h"
+#include "TMath.h"
+#include "Riostream.h"
+
+ClassImp(MRolke)
+
+//__________________________________________________________________________
+MRolke::MRolke(Double_t CL, Option_t * /*option*/)
+{
+   //constructor
+   fUpperLimit  = 0.0;
+   fLowerLimit  = 0.0;
+   fCL          = CL;
+   fSwitch      = 0; // 0: unbounded likelihood
+                    // 1: bounded likelihood
+}
+
+//___________________________________________________________________________
+MRolke::~MRolke()
+{
+}
+
+
+//___________________________________________________________________________
+Double_t MRolke::CalculateInterval(Int_t x, Int_t y, Int_t z, Double_t bm, Double_t em,Double_t e, Int_t mid, Double_t sde, Double_t sdb, Double_t tau, Double_t b, Int_t m)
+{
+   //calculate interval
+   Int_t done = 0;
+   Double_t limit[2];
+
+   limit[1] = Interval(x,y,z,bm,em,e,mid, sde,sdb,tau,b,m);
+
+   if (limit[1] > 0) {
+      done = 1;
+   }
+
+   if (fSwitch == 0) {
+
+      Int_t trial_x = x;
+
+      while (done == 0) {
+         trial_x++;
+         limit[1] = Interval(trial_x,y,z,bm,em,e,mid, sde,sdb,tau,b,m);
+         if (limit[1] > 0) done = 1;
+      } 
+   }
+
+   return limit[1];
+}
+
+
+
+
+//_____________________________________________________________________
+Double_t MRolke::Interval(Int_t x, Int_t y, Int_t z, Double_t bm, Double_t em,Double_t e, Int_t mid, Double_t sde, Double_t sdb, Double_t tau, Double_t b, Int_t m)
+{
+   // Calculates the Confidence Interval
+
+   //Double_t dchi2 =  Chi2Percentile(1,1-fCL);
+   Double_t dchi2 = TMath::ChisquareQuantile(fCL, 1);
+
+   Double_t tempxy[2],limits[2] = {0,0};
+   Double_t slope,fmid,low,flow,high,fhigh,test,ftest,mu0,maximum,target,l,f0;
+   Double_t med = 0;
+   Double_t maxiter=1000, acc = 0.00001;
+   Int_t i;
+   Int_t bp = 0;
+
+   if ((mid != 3) && (mid != 5)) bm = (Double_t)y;
+
+   if ((mid == 3) || (mid == 5)) {
+      if (bm == 0) bm = 0.00001;
+   } 
+
+   if ((mid <= 2) || (mid == 4)) bp = 1;
+  
+
+   if (bp == 1 && x == 0 && bm > 0 ){
+
+      for(Int_t i = 0; i < 2; i++) {
+         x++;
+         tempxy[i] = Interval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);
+      }
+      slope = tempxy[1] - tempxy[0];
+      limits[1] = tempxy[0] - slope;
+      limits[0] = 0.0;
+      if (limits[1] < 0) limits[1] = 0.0;
+      goto done;
+   }
+
+   if (bp != 1 && x == 0){
+
+      for(Int_t i = 0; i < 2; i++) {
+         x++;
+         tempxy[i] = Interval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);
+      }
+      slope = tempxy[1] - tempxy[0];
+      limits[1] = tempxy[0] - slope;
+      limits[0] = 0.0;
+      if (limits[1] < 0) limits[1] = 0.0;
+      goto done;
+   }
+
+   if (bp != 1  && bm == 0){
+      for(Int_t i = 0; i < 2; i++) {
+         bm++;
+         limits[1] = Interval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);
+         tempxy[i] = limits[1];
+      }
+      slope = tempxy[1] - tempxy[0];
+      limits[1] = tempxy[0] - slope;
+      if (limits[1] < 0) limits[1] = 0;
+      goto done;
+   }
+
+
+   if (x == 0 && bm == 0){
+      x++;
+      bm++;
+
+      limits[1] = Interval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);
+      tempxy[0] = limits[1];
+      x  = 1;
+      bm = 2;
+      limits[1] = Interval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);
+      tempxy[1] = limits[1];
+      x  = 2;
+      bm = 1;
+      limits[1] = Interval(x,y,z,bm,em,e,mid,sde,sdb,tau,b,m);
+      limits[1] = 3*tempxy[0] -tempxy[1] - limits[1];
+      if (limits[1] < 0) limits[1] = 0;
+      goto done;
+   }
+
+   mu0 = Likelihood(0,x,y,z,bm,em,e,mid,sde,sdb,tau,b,m,1);
+
+   maximum = Likelihood(0,x,y,z,bm,em,e,mid,sde,sdb,tau,b,m,2);
+
+   test = 0;
+
+   f0 = Likelihood(test,x,y,z,bm,em,e,mid,sde,sdb,tau,b,m,3);
+
+   if ( fSwitch == 1 ) {  // do this only for the unbounded likelihood case
+      if ( mu0 < 0 ) maximum = f0;
+   }
+
+   target = maximum - dchi2;
+
+   if (f0 > target) {
+      limits[0] = 0;
+   } else {
+      if (mu0 < 0){
+         limits[0] = 0;
+         limits[1] = 0;
+      }
+
+      low   = 0;
+      flow  = f0;
+      high  = mu0;
+      fhigh = maximum;
+
+      for(Int_t i = 0; i < maxiter; i++) {
+         l = (target-fhigh)/(flow-fhigh);
+         if (l < 0.2) l = 0.2;
+         if (l > 0.8) l = 0.8;
+
+         med = l*low + (1-l)*high;
+         if(med < 0.01){
+            limits[1]=0.0;                           
+            goto done;
+         }
+
+         fmid = Likelihood(med,x,y,z,bm,em,e,mid,sde,sdb,tau,b,m,3);
+
+         if (fmid > target) {
+            high  = med;
+            fhigh = fmid;
+         } else {
+            low  = med;
+            flow = fmid;
+         }
+         if ((high-low) < acc*high) break;
+      }
+      limits[0] = med;
+   }
+
+
+   if(mu0 > 0) {
+      low  = mu0;
+      flow = maximum;
+   } else {
+      low  = 0;
+      flow = f0;
+   }
+
+   test = low +1 ;
+
+   ftest = Likelihood(test,x,y,z,bm,em,e,mid,sde,sdb,tau,b,m,3);
+
+   if (ftest < target) {
+      high  = test;
+      fhigh = ftest;
+   } else {
+      slope = (ftest - flow)/(test - low);
+      high  = test + (target -ftest)/slope;
+      fhigh = Likelihood(high,x,y,z,bm,em,e,mid,sde,sdb,tau,b,m,3);
+   }
+
+   for(i = 0; i < maxiter; i++) {
+      l = (target-fhigh)/(flow-fhigh);
+      if (l < 0.2) l = 0.2;
+      if (l > 0.8) l = 0.8;
+      med  = l * low + (1.-l)*high;
+      fmid = Likelihood(med,x,y,z,bm,em,e,mid,sde,sdb,tau,b,m,3);
+
+      if (fmid < target) {
+         high  = med;
+         fhigh = fmid;
+      } else {
+         low  = med;
+         flow = fmid;
+      }
+      if (high-low < acc*high) break;
+   }
+   limits[1] = med;
+
+done:
+
+   if ( (mid == 4) || (mid==5) ) {
+      limits[0] /= e;
+      limits[1] /= e;
+   }
+
+
+   fUpperLimit = limits[1];
+   fLowerLimit = TMath::Max(limits[0],0.0);
+
+  
+   return limits[1];
+}
+
+
+//___________________________________________________________________________
+Double_t MRolke::Likelihood(Double_t mu, Int_t x, Int_t y, Int_t z, Double_t bm,Double_t em, Double_t e, Int_t mid, Double_t sde, Double_t sdb, Double_t tau, Double_t b, Int_t m, Int_t what)
+{
+   // Chooses between the different profile likelihood functions to use for the
+   // different models.
+   // Returns evaluation of the profile likelihood functions.
+
+   switch (mid) {
+      case 1: return EvalLikeMod1(mu,x,y,z,e,tau,b,m,what);
+      case 2: return EvalLikeMod2(mu,x,y,em,e,sde,tau,b,what);
+      case 3: return EvalLikeMod3(mu,x,bm,em,e,sde,sdb,b,what);
+      case 4: return EvalLikeMod4(mu,x,y,tau,b,what);
+      case 5: return EvalLikeMod5(mu,x,bm,sdb,b,what);
+      case 6: return EvalLikeMod6(mu,x,z,e,b,m,what);
+      case 7: return EvalLikeMod7(mu,x,em,e,sde,b,what);
+   }
+
+   return 0;
+}
+
+//_________________________________________________________________________
+Double_t MRolke::EvalLikeMod1(Double_t mu, Int_t x, Int_t y, Int_t z, Double_t e, Double_t tau, Double_t b, Int_t m, Int_t what)
+{
+   // Calculates the Profile Likelihood for MODEL 1:
+   //  Poisson background/ Binomial Efficiency
+   // what = 1: Maximum likelihood estimate is returned
+   // what = 2: Profile Likelihood of Maxmimum Likelihood estimate is returned.
+   // what = 3: Profile Likelihood of Test hypothesis is returned
+   // otherwise parameters as described in the beginning of the class)
+
+   Double_t f  = 0;
+   Double_t zm = Double_t(z)/m;
+
+   if (what == 1) {
+      f = (x-y/tau)/zm;
+   }
+
+   if (what == 2) {
+      mu = (x-y/tau)/zm;
+      b  = y/tau;
+      Double_t e = zm;
+      f = LikeMod1(mu,b,e,x,y,z,tau,m);
+   }
+
+   if (what == 3) {
+      if (mu == 0){
+         b = (x+y)/(1.0+tau);
+         e = zm;
+         f = LikeMod1(mu,b,e,x,y,z,tau,m);
+      } else {
+         MRolke g;
+         g.ProfLikeMod1(mu,b,e,x,y,z,tau,m);
+         f = LikeMod1(mu,b,e,x,y,z,tau,m);
+      }
+   }
+
+   return f;
+}
+
+//________________________________________________________________________
+Double_t MRolke::LikeMod1(Double_t mu,Double_t b, Double_t e, Int_t x, Int_t y, Int_t z, Double_t tau, Int_t m)
+{
+   // Profile Likelihood function for MODEL 1:
+   // Poisson background/ Binomial Efficiency
+
+   return 2*(x*TMath::Log(e*mu+b)-(e*mu +b)-LogFactorial(x)+y*TMath::Log(tau*b)-tau*b-LogFactorial(y) + TMath::Log(TMath::Factorial(m)) - TMath::Log(TMath::Factorial(m-z)) - TMath::Log(TMath::Factorial(z))+ z * TMath::Log(e) + (m-z)*TMath::Log(1-e));
+}
+
+//________________________________________________________________________
+void MRolke::ProfLikeMod1(Double_t mu,Double_t &b,Double_t &e,Int_t x,Int_t y, Int_t z,Double_t tau,Int_t m)
+{
+   // Void needed to calculate estimates of efficiency and background for model 1
+
+   Double_t med = 0.0,fmid;
+   Int_t maxiter =1000;
+   Double_t acc = 0.00001;
+   Double_t emin = ((m+mu*tau)-TMath::Sqrt((m+mu*tau)*(m+mu*tau)-4 * mu* tau * z))/2/mu/tau;
+
+   Double_t low  = TMath::Max(1e-10,emin+1e-10);
+   Double_t high = 1 - 1e-10;
+
+   for(Int_t i = 0; i < maxiter; i++) {
+      med = (low+high)/2.;
+
+      fmid = LikeGradMod1(med,mu,x,y,z,tau,m);
+
+      if(high < 0.5) acc = 0.00001*high;
+      else           acc = 0.00001*(1-high);
+
+      if ((high - low) < acc*high) break;
+
+      if(fmid > 0) low  = med;
+      else         high = med;
+   }
+
+   e = med;
+   Double_t eta = Double_t(z)/e -Double_t(m-z)/(1-e);
+
+   b = Double_t(y)/(tau -eta/mu);
+}
+
+//___________________________________________________________________________
+Double_t MRolke::LikeGradMod1(Double_t e, Double_t mu, Int_t x,Int_t y,Int_t z,Double_t tau,Int_t m)
+{
+   //gradient model
+   Double_t eta, etaprime, bprime,f;
+   eta = static_cast<double>(z)/e - static_cast<double>(m-z)/(1.0 - e);
+   etaprime = (-1) * (static_cast<double>(m-z)/((1.0 - e)*(1.0 - e)) + static_cast<double>(z)/(e*e));
+   Double_t b = y/(tau - eta/mu);
+   bprime = (b*b * etaprime)/mu/y;
+   f =  (mu + bprime) * (x/(e * mu + b) - 1)+(y/b - tau) * bprime + eta;
+   return f;
+}
+
+//___________________________________________________________________________
+Double_t MRolke::EvalLikeMod2(Double_t mu, Int_t x, Int_t y, Double_t em, Double_t e,Double_t sde, Double_t tau, Double_t b, Int_t what)
+{
+   // Calculates the Profile Likelihood for MODEL 2:
+   //  Poisson background/ Gauss Efficiency
+   // what = 1: Maximum likelihood estimate is returned
+   // what = 2: Profile Likelihood of Maxmimum Likelihood estimate is returned.
+   // what = 3: Profile Likelihood of Test hypothesis is returned
+   // otherwise parameters as described in the beginning of the class)
+
+   Double_t v =  sde*sde;
+   Double_t coef[4],roots[3];
+   Double_t f = 0;
+
+   if (what == 1) {
+      f = (x-y/tau)/em;
+   }
+
+   if (what == 2) {
+      mu = (x-y/tau)/em;
+      b = y/tau;
+      e = em;
+      f = LikeMod2(mu,b,e,x,y,em,tau,v);
+   }
+
+   if (what == 3) {
+      if (mu == 0 ) {
+         b = (x+y)/(1+tau);
+         f = LikeMod2(mu,b,e,x,y,em,tau,v);
+      } else {
+         coef[3] = mu;
+         coef[2] = mu*mu*v-2*em*mu-mu*mu*v*tau;
+         coef[1] = ( - x)*mu*v - mu*mu*mu*v*v*tau - mu*mu*v*em + em*mu*mu*v*tau + em*em*mu - y*mu*v;
+         coef[0] = x*mu*mu*v*v*tau + x*em*mu*v - y*mu*mu*v*v + y*em*mu*v;
+
+         TMath::RootsCubic(coef,roots[0],roots[1],roots[2]);
+
+         e = roots[1];
+         b = y/(tau + (em - e)/mu/v);
+         f = LikeMod2(mu,b,e,x,y,em,tau,v);
+      }
+   }
+
+   return f;
+}
+
+//_________________________________________________________________________
+Double_t MRolke::LikeMod2(Double_t mu, Double_t b, Double_t e,Int_t x,Int_t y,Double_t em,Double_t tau, Double_t v)
+{
+   // Profile Likelihood function for MODEL 2:
+   // Poisson background/Gauss Efficiency
+
+   return 2*(x*TMath::Log(e*mu+b)-(e*mu+b)-LogFactorial(x)+y*TMath::Log(tau*b)-tau*b-LogFactorial(y)-0.9189385-TMath::Log(v)/2-(em-e)*(em-e)/v/2);
+}
+
+//_____________________________________________________________________
+
+Double_t MRolke::EvalLikeMod3(Double_t mu, Int_t x, Double_t bm, Double_t em, Double_t e, Double_t sde, Double_t sdb, Double_t b, Int_t what)
+{
+   // Calculates the Profile Likelihood for MODEL 3:
+   // Gauss  background/ Gauss Efficiency
+   // what = 1: Maximum likelihood estimate is returned
+   // what = 2: Profile Likelihood of Maxmimum Likelihood estimate is returned.
+   // what = 3: Profile Likelihood of Test hypothesis is returned
+   // otherwise parameters as described in the beginning of the class)
+
+   Double_t f = 0.;
+   Double_t  v = sde*sde;
+   Double_t  u = sdb*sdb;
+
+   if (what == 1) {
+      f = (x-bm)/em;
+   }
+
+
+   if (what == 2) {
+      mu = (x-bm)/em;
+      b  = bm;
+      e  = em;
+      f  = LikeMod3(mu,b,e,x,bm,em,u,v);
+   }
+
+
+   if(what == 3) {
+      if(mu == 0.0){
+         b = ((bm-u)+TMath::Sqrt((bm-u)*(bm-u)+4*x*u))/2.;
+         e = em;
+         f = LikeMod3(mu,b,e,x,bm,em,u,v);
+      } else {
+         Double_t temp[3];
+         temp[0] = mu*mu*v+u;
+         temp[1] = mu*mu*mu*v*v+mu*v*u-mu*mu*v*em+mu*v*bm-2*u*em;
+         temp[2] = mu*mu*v*v*bm-mu*v*u*em-mu*v*bm*em+u*em*em-mu*mu*v*v*x;
+         e = (-temp[1]+TMath::Sqrt(temp[1]*temp[1]-4*temp[0]*temp[2]))/2/temp[0];
+         b = bm-(u*(em-e))/v/mu;
+         f = LikeMod3(mu,b,e,x,bm,em,u,v);
+      }
+   }
+
+   return f;
+}
+
+//____________________________________________________________________
+Double_t MRolke::LikeMod3(Double_t mu,Double_t b,Double_t e,Int_t x,Double_t bm,Double_t em,Double_t u,Double_t v)
+{
+   // Profile Likelihood function for MODEL 3:
+   // Gauss background/Gauss Efficiency
+
+   return 2*(x * TMath::Log(e*mu+b)-(e*mu+b)-LogFactorial(x)-1.837877-TMath::Log(u)/2-(bm-b)*(bm-b)/u/2-TMath::Log(v)/2-(em-e)*(em-e)/v/2);
+}
+
+//____________________________________________________________________
+Double_t MRolke::EvalLikeMod4(Double_t mu, Int_t x, Int_t y, Double_t tau, Double_t b, Int_t what)
+{
+   // Calculates the Profile Likelihood for MODEL 4:
+   // Poiss  background/Efficiency known
+   // what = 1: Maximum likelihood estimate is returned
+   // what = 2: Profile Likelihood of Maxmimum Likelihood estimate is returned.
+   // what = 3: Profile Likelihood of Test hypothesis is returned
+   // otherwise parameters as described in the beginning of the class)
+
+   Double_t f = 0.0;
+
+   if (what == 1) f = x-y/tau;
+   if (what == 2) {
+      mu = x-y/tau;
+      b  = Double_t(y)/tau;
+      f  = LikeMod4(mu,b,x,y,tau);
+   }
+   if (what == 3) {
+      if (mu == 0.0) {
+         b = Double_t(x+y)/(1+tau);
+         f = LikeMod4(mu,b,x,y,tau);
+      } else {
+         b = (x+y-(1+tau)*mu+sqrt((x+y-(1+tau)*mu)*(x+y-(1+tau)*mu)+4*(1+tau)*y*mu))/2/(1+tau);
+         f = LikeMod4(mu,b,x,y,tau);
+      }
+   }
+   return f;
+}
+
+//___________________________________________________________________
+Double_t MRolke::LikeMod4(Double_t mu,Double_t b,Int_t x,Int_t y,Double_t tau)
+{
+   // Profile Likelihood function for MODEL 4:
+   // Poiss background/Efficiency known
+
+   return 2*(x*TMath::Log(mu+b)-(mu+b)-LogFactorial(x)+y*TMath::Log(tau*b)-tau*b-LogFactorial(y) );
+}
+
+//___________________________________________________________________
+Double_t MRolke::EvalLikeMod5(Double_t mu, Int_t x, Double_t bm, Double_t sdb, Double_t b, Int_t what)
+{
+   // Calculates the Profile Likelihood for MODEL 5:
+   // Gauss  background/Efficiency known
+   // what = 1: Maximum likelihood estimate is returned
+   // what = 2: Profile Likelihood of Maxmimum Likelihood estimate is returned.
+   // what = 3: Profile Likelihood of Test hypothesis is returned
+   // otherwise parameters as described in the beginning of the class)
+
+   Double_t u=sdb*sdb;
+   Double_t f = 0;
+
+   if(what == 1) {
+      f = x - bm;
+   }
+   if(what == 2) {
+      mu = x-bm;
+      b  = bm;
+      f  = LikeMod5(mu,b,x,bm,u);
+   }
+
+   if (what == 3) {
+      b = ((bm-u-mu)+TMath::Sqrt((bm-u-mu)*(bm-u-mu)-4*(mu*u-mu*bm-u*x)))/2;
+      f = LikeMod5(mu,b,x,bm,u);
+   }
+   return f;
+}
+
+//_______________________________________________________________________
+Double_t MRolke::LikeMod5(Double_t mu,Double_t b,Int_t x,Double_t bm,Double_t u)
+{
+   // Profile Likelihood function for MODEL 5:
+   // Gauss background/Efficiency known
+
+   return 2*(x*TMath::Log(mu+b)-(mu + b)-LogFactorial(x)-0.9189385-TMath::Log(u)/2-((bm-b)*(bm-b))/u/2);
+}
+
+//_______________________________________________________________________
+Double_t MRolke::EvalLikeMod6(Double_t mu, Int_t x, Int_t z, Double_t e, Double_t b, Int_t m, Int_t what)
+{
+   // Calculates the Profile Likelihood for MODEL 6:
+   // Gauss  known/Efficiency binomial
+   // what = 1: Maximum likelihood estimate is returned
+   // what = 2: Profile Likelihood of Maxmimum Likelihood estimate is returned.
+   // what = 3: Profile Likelihood of Test hypothesis is returned
+   // otherwise parameters as described in the beginning of the class)
+
+   Double_t coef[4],roots[3];
+   Double_t f = 0.;
+   Double_t zm = Double_t(z)/m;
+
+   if(what==1){
+      f = (x-b)/zm;
+   }
+
+   if(what==2){
+      mu = (x-b)/zm;
+      e  = zm;
+      f  = LikeMod6(mu,b,e,x,z,m);
+   }
+   if(what == 3){
+      if(mu==0){
+         e = zm;
+      } else {
+         coef[3] = mu*mu;
+         coef[2] = mu * b - mu * x - mu*mu - mu * m;
+         coef[1] = mu * x - mu * b + mu * z - m * b;
+         coef[0] = b * z;
+         TMath::RootsCubic(coef,roots[0],roots[1],roots[2]);
+         e = roots[1];
+      }
+      f =LikeMod6(mu,b,e,x,z,m);
+   }
+   return f;
+}
+
+//_______________________________________________________________________
+Double_t MRolke::LikeMod6(Double_t mu,Double_t b,Double_t e,Int_t x,Int_t z,Int_t m)
+{
+   // Profile Likelihood function for MODEL 6:
+   // background known/ Efficiency binomial
+
+   Double_t f = 0.0;
+
+   if (z > 100 || m > 100) {
+      f = 2*(x*TMath::Log(e*mu+b)-(e*mu+b)-LogFactorial(x)+(m*TMath::Log(m)  - m)-(z*TMath::Log(z) - z)  - ((m-z)*TMath::Log(m-z) - m + z)+z*TMath::Log(e)+(m-z)*TMath::Log(1-e));
+   } else {
+      f = 2*(x*TMath::Log(e*mu+b)-(e*mu+b)-LogFactorial(x)+TMath::Log(TMath::Factorial(m))-TMath::Log(TMath::Factorial(z))-TMath::Log(TMath::Factorial(m-z))+z*TMath::Log(e)+(m-z)*TMath::Log(1-e));
+   }
+   return f;
+}
+
+
+//___________________________________________________________________________
+Double_t MRolke::EvalLikeMod7(Double_t mu, Int_t x, Double_t em, Double_t e, Double_t sde, Double_t b, Int_t what)
+{
+   // Calculates the Profile Likelihood for MODEL 7:
+   // background known/Efficiency Gauss
+   // what = 1: Maximum likelihood estimate is returned
+   // what = 2: Profile Likelihood of Maxmimum Likelihood estimate is returned.
+   // what = 3: Profile Likelihood of Test hypothesis is returned
+   // otherwise parameters as described in the beginning of the class)
+
+   Double_t v=sde*sde;
+   Double_t f = 0.;
+
+   if(what ==  1) {
+      f = (x-b)/em;
+   }
+
+   if(what == 2) {
+      mu = (x-b)/em;
+      e  = em;
+      f  = LikeMod7(mu, b, e, x, em, v);
+   }
+
+   if(what == 3) {
+      if(mu==0) {
+         e = em;
+      } else {
+         e = ( -(mu*em-b-mu*mu*v)-TMath::Sqrt((mu*em-b-mu*mu*v)*(mu*em-b-mu*mu*v)+4*mu*(x*mu*v-mu*b*v + b * em)))/( - mu)/2;
+      }
+      f = LikeMod7(mu, b, e, x, em, v);
+   }
+
+   return f;
+}
+
+//___________________________________________________________________________
+Double_t MRolke::LikeMod7(Double_t mu,Double_t b,Double_t e,Int_t x,Double_t em,Double_t v)
+{
+   // Profile Likelihood function for MODEL 6:
+   // background known/ Efficiency binomial
+
+   return 2*(x*TMath::Log(e*mu+b)-(e*mu + b)-LogFactorial(x)-0.9189385-TMath::Log(v)/2-(em-e)*(em-e)/v/2);
+}
+
+//______________________________________________________________________
+Double_t MRolke::EvalPolynomial(Double_t x, const Int_t  coef[], Int_t N)
+{
+  // evaluate polynomial
+
+   const Int_t   *p;
+   p = coef;
+   Double_t ans = *p++;
+   Int_t i = N;
+
+   do
+      ans = ans * x  +  *p++;
+   while( --i );
+
+   return ans;
+}
+
+//______________________________________________________________________
+Double_t MRolke::EvalMonomial(Double_t x, const Int_t coef[], Int_t N)
+{
+   // evaluate mononomial
+
+   Double_t ans;
+   const Int_t   *p;
+
+   p   = coef;
+   ans = x + *p++;
+   Int_t i = N-1;
+
+   do
+      ans = ans * x  + *p++;
+   while( --i );
+
+   return ans;
+}
+//--------------------------------------------------------------------------
+//
+// Uses Stirling-Wells formula: ln(N!) ~ N*ln(N) - N + 0.5*ln(2piN)
+// if N exceeds 70, otherwise use the TMath functions
+//
+//
+Double_t MRolke::LogFactorial(Int_t n)
+{
+   if (n>69)
+       return n*TMath::Log(n)-n + 0.5*TMath::Log(TMath::TwoPi()*n);
+   else
+       return TMath::Log(TMath::Factorial(n));
+}
Index: branches/Mars_McMismatchStudy/mtools/MRolke.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MRolke.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MRolke.h	(revision 17960)
@@ -0,0 +1,91 @@
+// @(#)root/physics:$Name: not supported by cvs2svn $:$Id: MRolke.h,v 1.1 2006-10-17 12:52:15 meyer Exp $
+// Author: Jan Conrad    9/2/2004
+
+/*************************************************************************
+ * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
+ * All rights reserved.                                                  *
+ *                                                                       *
+ * For the licensing terms see $ROOTSYS/LICENSE.                         *
+ * For the list of contributors see $ROOTSYS/README/CREDITS.             *
+ *************************************************************************/
+
+#ifndef MARS_MRolke
+#define MARS_MRolke
+
+#ifndef ROOT_TObject
+#include "TObject.h"
+#endif
+
+class MRolke : public TObject {
+
+protected:
+   Double_t fCL;         // confidence level as a fraction [e.g. 90% = 0.9]
+   Double_t fUpperLimit; // the calculated upper limit
+   Double_t fLowerLimit; // the calculated lower limit
+   Int_t fSwitch;        // 0: for unbounded likelihood
+                         // 1: for bounded likelihood
+
+   // The Calculator
+
+   Double_t Interval(Int_t x, Int_t y, Int_t z, Double_t bm, Double_t em, Double_t e, Int_t mid, Double_t sde, Double_t sdb, Double_t tau, Double_t b,Int_t m);
+
+   // LIKELIHOOD ROUTINE
+
+   Double_t Likelihood(Double_t mu, Int_t x, Int_t y, Int_t z, Double_t bm, Double_t em, Double_t e, Int_t mid, Double_t sde, Double_t sdb, Double_t tau, Double_t b, Int_t m, Int_t what);
+
+   //MODEL 1
+   Double_t EvalLikeMod1(Double_t mu, Int_t x, Int_t y, Int_t z, Double_t e, Double_t tau, Double_t b, Int_t m, Int_t what);
+   Double_t LikeMod1(Double_t mu,Double_t b, Double_t e, Int_t x, Int_t y, Int_t z, Double_t tau, Int_t m);
+   void     ProfLikeMod1(Double_t mu,Double_t &b, Double_t &e,Int_t x,Int_t y, Int_t z,Double_t tau,Int_t m);
+   Double_t LikeGradMod1(Double_t e, Double_t mu, Int_t x,Int_t y,Int_t z,Double_t tau,Int_t m);
+
+   //MODEL 2
+   Double_t EvalLikeMod2(Double_t mu, Int_t x, Int_t y, Double_t em, Double_t e,Double_t sde, Double_t tau, Double_t b, Int_t what);
+
+   Double_t LikeMod2(Double_t mu, Double_t b, Double_t e,Int_t x,Int_t y,Double_t em,Double_t tau, Double_t v);
+
+   //MODEL 3
+   Double_t EvalLikeMod3(Double_t mu, Int_t x, Double_t bm, Double_t em, Double_t e, Double_t sde, Double_t sdb, Double_t b, Int_t what);
+   Double_t LikeMod3(Double_t mu,Double_t b,Double_t e,Int_t x,Double_t bm,Double_t em,Double_t u,Double_t v);
+
+   //MODEL 4
+   Double_t EvalLikeMod4(Double_t mu, Int_t x, Int_t y, Double_t tau, Double_t b, Int_t what);
+   Double_t LikeMod4(Double_t mu,Double_t b,Int_t x,Int_t y,Double_t tau);
+
+   //MODEL 5
+   Double_t EvalLikeMod5(Double_t mu, Int_t x, Double_t bm, Double_t sdb, Double_t b, Int_t what);
+   Double_t LikeMod5(Double_t mu,Double_t b,Int_t x,Double_t bm,Double_t u);
+
+   //MODEL 6
+   Double_t EvalLikeMod6(Double_t mu, Int_t x, Int_t z, Double_t e, Double_t b, Int_t m, Int_t what);
+   Double_t LikeMod6(Double_t mu,Double_t b,Double_t e,Int_t x,Int_t z,Int_t m);
+
+   //MODEL 7
+   Double_t EvalLikeMod7(Double_t mu, Int_t x, Double_t em, Double_t e, Double_t sde, Double_t b, Int_t what);
+   Double_t LikeMod7(Double_t mu,Double_t b,Double_t e,Int_t x,Double_t em,Double_t v);
+
+   //MISC
+   static Double_t EvalPolynomial(Double_t x, const Int_t coef[], Int_t N);
+   static Double_t EvalMonomial  (Double_t x, const Int_t coef[], Int_t N);
+
+   Double_t LogFactorial(Int_t n);
+
+
+public:
+
+   MRolke(Double_t CL=0.9, Option_t *option = "");
+ 
+   virtual ~MRolke();
+
+   Double_t CalculateInterval(Int_t x, Int_t y, Int_t z, Double_t bm, Double_t em, Double_t e, Int_t mid, Double_t sde, Double_t sdb, Double_t tau, Double_t b,Int_t m);
+   Double_t GetUpperLimit(void) const { return fUpperLimit;}
+   Double_t GetLowerLimit(void) const { return fLowerLimit;}
+   Int_t    GetSwitch(void) const     { return fSwitch;}
+   void     SetSwitch(Int_t sw) { fSwitch = sw; } 
+   Double_t GetCL(void) const         { return fCL;}
+   void     SetCL(Double_t CL)  { fCL = CL; }
+
+   ClassDef(MRolke,1) //calculate confidence limits using the Rolke method
+};
+#endif
+
Index: branches/Mars_McMismatchStudy/mtools/MSimulatedAnnealing.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MSimulatedAnnealing.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MSimulatedAnnealing.cc	(revision 17960)
@@ -0,0 +1,630 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 10/2002  <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MSimulatedAnnealing                                                     //
+//                                                                          //
+//  class to perform a Simulated Annealing minimization on an n-dimensional //
+//  simplex of a function 'FunctionToMinimize(TArrayF &)' in multi-         //
+//  dimensional parameter space.                                            //
+//  (The code is adapted from Numerical Recipies in C++, 2nd ed.,           //
+//  pp. 457-459)                                                            //
+//                                                                          //
+//  Classes can inherit from MSimulatedAnnealing                            //
+//  and use the function:                                                   //
+//                                                                          //
+//  RunSimulatedAnnealing();                                                //
+//                                                                          //
+//  They HAVE TO initialize the following input arguments                   //
+//  (with ndim being the parameter dimension (max. 20)):                    //
+//                                                                          //
+//  1) a TMatrix p(ndim+1,ndim)                                             //
+//     holding the start simplex                                            //
+//  2) a TArrayF y(ndim+1)                                                  //
+//     whose components must be pre-initialized to the values of            //
+//      FunctionToMinimize evaluated at the fNdim+1 vertices (rows) of p    //
+//  3) a TArrayF p0(ndim)                                                   //
+//     whose components contain the lower simplex borders                   //
+//  4) a TArrayF p1(ndim)                                                   //
+//     whose components contain the upper simplex borders                   //
+//    (The simplex will not get reflected out of these borders !!!)         //
+//                                                                          //
+//  These arrays have to be initialized with a call to:                     //
+//  Initialize(TMatrix \&, TArrayF \&, TArrayF \&, TArrayF \&)              //
+//                                                                          //
+//  5) a virtual function FunctionToMinimize(TArrayF &)                     //
+//     acting on a TArrayF(ndim) array of parameter values                  //
+//                                                                          //
+//  Additionally, a global start temperature can be chosen with:            //
+//                                                                          //
+//  SetStartTemperature(Float_t temp)                                       //
+//  (default is: 10)                                                        //
+//                                                                          //
+//  A total number of total moves (watch out for the CPU time!!!) with:     //
+//                                                                          //
+//  SetNumberOfMoves(Float_t totalMoves)                                    //
+//  (default is: 200)                                                       //
+//                                                                          //
+//  The temperature is reduced after evaluation step like:                  //
+//      CurrentTemperature = StartTemperature*(1-currentMove/totalMoves)    //
+//  where currentMove is the cumulative number of moves so far              //
+//                                                                          //
+//  WARNING: The start temperature and number of moves has to be optimized  //
+//           for each individual problem.                                   //
+//           It is not straightforward using the defaults!                  //
+//           In case, you omit this important step,                         //
+//           you will get local minima without even noticing it!!           //
+//                                                                          //
+//  You may define the following variables:                                 //
+//                                                                          //
+//  1) A global convergence criterium fTol                                  //
+//     which determines an early return for:                                //
+//                                                                          //
+//     max(FunctionToMinimize(p))-min(FunctionToMinimize(p))                //
+//     -----------------------------------------------------  \< fTol       //
+//     max(FunctionToMinimize(p))+min(FunctionToMinimize(p))                //
+//                                                                          //
+//     ModifyTolerance(Float_t)                                             //
+//                                                                          //
+//  2) A verbose level for prints to *fLog                                  //
+//                                                                          //
+//     SetVerbosityLevel(Verbosity_t)                                       //
+//                                                                          //
+//  3) A bit if you want to have stored                                     //
+//     the full simplex after every call to Amebsa:                         //
+//                                                                          //
+//     SetFullStorage()                                                     //
+//                                                                          //
+//  4) The random number generator                                          //
+//     e.g. if you want to test the stability of the output                 //
+//                                                                          //
+//     SetRandom(TRandom *rand)                                             //
+//                                                                          //
+//                                                                          //
+//  Output containers:                                                      //
+//                                                                          //
+//  MHSimulatedAnnealing                                                    //
+//                                                                          //
+//  Use:                                                                    //
+//    GetResult()->Draw(Option_t *o)                                        //
+//  or                                                                      //
+//    GetResult()->DrawClone(Option_t *o)                                   //
+//                                                                          //
+//  to retrieve the output histograms                                       //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimulatedAnnealing.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TMath.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHSimulatedAnnealing.h"
+
+const Float_t MSimulatedAnnealing::gsYtryStr = 10000000;  
+const Float_t MSimulatedAnnealing::gsYtryCon = 20000000;  
+const Int_t   MSimulatedAnnealing::gsMaxDim  = 20;
+const Int_t   MSimulatedAnnealing::gsMaxStep = 50;
+
+ClassImp(MSimulatedAnnealing);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor
+//  Initializes random number generator and default variables
+//
+MSimulatedAnnealing::MSimulatedAnnealing()
+    : fResult(NULL), fTolerance(0.0001),
+      fNdim(0), fNumberOfMoves(200),
+      fStartTemperature(10), fFullStorage(kFALSE),
+      fInit(kFALSE), 
+      fP(gsMaxDim, gsMaxDim), fP0(gsMaxDim),
+      fP1(gsMaxDim), fY(gsMaxDim), fYb(gsMaxDim), fYconv(gsMaxDim),
+      fPb(gsMaxDim), fPconv(gsMaxDim),
+      fBorder(kEStrictBorder), fVerbose(kEDefault)
+{
+
+    // random number generator
+    fRandom = gRandom;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. 
+//
+MSimulatedAnnealing::~MSimulatedAnnealing()
+{
+  if (fResult) 
+    delete fResult;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Initialization needs the following four members:
+//
+//  1) a TMatrix p(ndim+1,ndim)
+//     holding the start simplex 
+//  2) a TVector y(ndim+1)
+//     whose components must be pre-initialized to the values of 
+//     FunctionToMinimize evaluated at the fNdim+1 vertices (rows) of fP
+//  3) a TVector p0(ndim)
+//     whose components contain the lower simplex borders 
+//  4) a TVector p1(ndim)
+//     whose components contain the upper simplex borders
+//    (The simplex will not get reflected out of these borders !!!)
+//
+//  It is possible to perform an initialization and 
+//  a subsequent RunMinimization several times. 
+//  Each time, a new class MHSimulatedAnnealing will get created
+//  (and destroyed). 
+//
+Bool_t MSimulatedAnnealing::Initialize(const TMatrix &p,  const TVector &y, 
+                                       const TVector &p0, const TVector &p1)
+{
+
+    fNdim = p.GetNcols();
+    fMpts = p.GetNrows();
+
+    //
+    // many necessary checks ...
+    //
+    if (fMpts > gsMaxDim) 
+    {
+       gLog << err << "Dimension of Matrix fP is too big ... aborting." << endl;
+        return kFALSE;
+    }
+    if (fNdim+1 != fMpts) 
+    {
+        gLog << err << "Matrix fP does not have the right dimensions ... aborting." << endl;
+        return kFALSE;
+    }
+    if (y.GetNrows() != fMpts) 
+    {
+        gLog << err << "Array fY has not the right dimension ... aborting." << endl;
+        return kFALSE;
+    }
+    if (p0.GetNrows() != fNdim) 
+    {
+        gLog << err << "Array fP0 has not the right dimension ... aborting." << endl;
+        return kFALSE;
+    }
+    if (p1.GetNrows() != fNdim) 
+    {
+        gLog << err << "Array fP1 has not the right dimension ... aborting." << endl;
+        return kFALSE;
+    }
+
+    //
+    // In order to allow multiple use of the class
+    // without need to construct the class every time new
+    // delete the old fResult and create a new one in RunMinimization
+    //
+    if (fResult)
+       delete fResult;
+
+    fY.ResizeTo(fMpts);
+    
+    fPsum.ResizeTo(fNdim);
+    fPconv.ResizeTo(fNdim);
+    
+    fP0.ResizeTo(fNdim);
+    fP1.ResizeTo(fNdim);
+    fPb.ResizeTo(fNdim);
+    
+    fP.ResizeTo(fMpts,fNdim);
+
+    fY  = y;
+    fP  = p;
+    fP0 = p0;
+    fP1 = p1;
+    fPconv.Zero();
+
+    fInit = kTRUE;
+    fYconv = 0.;
+
+    return kTRUE;
+}
+
+
+// ---------------------------------------------------------------------------
+//
+//  RunMinimization:
+//
+//  Runs only eafter a call to Initialize(const TMatrix \&, const TVector \&,
+//                                        const TVector \&, const TVector \&)
+//  
+//  Temperature and number of moves should have been set
+//  (default: StartTemperature = 10, NumberOfMoves = 200
+//
+//  
+//  It is possible to perform an initialization and 
+//  a subsequent RunMinimization several times. 
+//  Each time, a new class MHSimulatedAnnealing will get created
+//  (and destroyed). 
+Bool_t MSimulatedAnnealing::RunMinimization()
+{
+    if (!fInit)
+    {
+        gLog << err << "No succesful initialization performed yet... aborting." << endl;
+        return kFALSE;
+    }
+
+    Int_t    iter        = 0;
+    UShort_t iret        = 0;
+    UShort_t currentMove = 0;
+    Real_t   currentTemp = fStartTemperature;
+
+    fResult = new MHSimulatedAnnealing(fNumberOfMoves,fNdim);
+    if (fFullStorage) 
+      fResult->InitFullSimplex();
+
+    while(1)
+    {
+        if (iter > 0) 
+        {
+            gLog << "Convergence at move: " << currentMove ;
+            gLog << " and temperature: " << currentTemp << endl;
+            break;
+        }
+        
+        if (currentTemp > 0.) 
+        {
+          //
+          // Reduce the temperature 
+          //
+          // FIXME: Maybe it is necessary to also incorporate other 
+          //        ways to reduce the temperature (T0*(1-k/K)**alpha)
+          // 
+          currentTemp = fStartTemperature*(1.-(float)currentMove++/fNumberOfMoves);
+          iter = 1;
+        } 
+        else 
+        {
+            // Make sure that now, the program will return only on convergence !
+            // The program returns to here only after gsMaxStep moves
+            // If we have not reached convergence until then, we assume that an infinite 
+            // loop has occurred and quit.
+            if (iret != 0) 
+            {
+                gLog << warn << "No Convergence at the end ! " << endl;
+                fY.Zero();
+
+                break;
+            }
+            iter = 150;
+            iret++;
+            currentMove++;
+        }
+        
+        if (fVerbose==2) {
+            gLog << dbginf << " current..." << endl;
+            gLog << " - move:        " << currentMove << endl;
+            gLog << " - temperature: " << currentTemp << endl;
+            gLog << " - best function evaluation: " << fYb << endl;
+        }
+
+        iter = Amebsa(iter, currentTemp);
+
+        // Store the current best values in the histograms
+        fResult->StoreBestValueEver(fPb,fYb,currentMove);
+
+        // Store the complete simplex if we have full storage
+        if (fFullStorage) 
+          fResult->StoreFullSimplex(fP,currentMove);
+    }
+
+    //
+    // Now, the matrizes and vectors have all the same value, 
+    // Need to initialize again to allow a new Minimization
+    //
+    fInit = kFALSE;
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Amebsa
+//
+//  This is the (adjusted) amebsa function from 
+//  Numerical Recipies (pp. 457-458)
+//             
+//  The routine makes iter function evaluations at an annealing
+//  temperature fCurrentTemp, then returns. If iter is returned 
+//  with a poisitive value, then early convergence has occurred. 
+//
+Int_t MSimulatedAnnealing::Amebsa(Int_t iter, const Real_t temp)
+{
+    GetPsum();
+  
+    while (1) 
+    {
+        UShort_t ihi = 0; // Simplex point with highest function evaluation
+        UShort_t ilo = 1; // Simplex point with lowest  function evaluation
+
+        // Function eval. at ilo (with random fluctuations)
+        Real_t ylo = fY(0) + gRandom->Exp(temp); 
+
+        // Function eval. at ihi (with random fluctuations)
+        Real_t yhi = fY(1) + gRandom->Exp(temp); 
+
+        // The function evaluation at next highest point
+        Real_t ynhi = ylo; 
+
+        if (ylo > yhi)
+        {
+            // Determine which point is the highest (worst),
+            // next-highest and lowest (best)
+            ynhi = yhi;
+            yhi  = ylo;
+            ylo  = ynhi;
+        }
+    
+        // By looping over the points in the simplex 
+        for (UShort_t i=2;i<fMpts;i++) 
+        {
+            const Real_t yt = fY(i) + gRandom->Exp(temp);
+      
+            if (yt <= ylo)
+            {
+                ilo = i;
+                ylo = yt;
+            }
+
+            if (yt > yhi)
+            {
+                ynhi = yhi;
+                ihi  = i;
+                yhi  = yt;
+            }
+            else 
+                if (yt > ynhi) 
+                    ynhi = yt;
+        }
+
+        // Now, fY(ilo) is smallest and fY(ihi) is at biggest value 
+        if (iter < 0)
+        {
+            // Enough looping with this temperature, go to decrease it
+            // First put best point and value in slot 0
+            
+            Real_t dum = fY(0);
+            fY(0)      = fY(ilo);
+            fY(ilo)    = dum;
+
+            for (UShort_t n=0;n<fNdim;n++)
+            {
+                dum       = fP(0,n);
+                fP(0,n)   = fP(ilo,n);
+                fP(ilo,n) = dum;
+            }
+          
+            break;
+        }
+        
+        // Compute the fractional range from highest to lowest and
+        // return if satisfactory
+        Real_t tol = fabs(yhi) + fabs(ylo);
+        if (tol != 0)
+            tol = 2.0*fabs(yhi-ylo)/tol;
+    
+        if (tol<fTolerance)
+        {
+            // Put best point and value in fPconv
+            fYconv = fY(ilo);
+            for (UShort_t n=0; n<fNdim; n++)
+                fPconv(n) = fP(ilo, n);  
+
+            break;
+        }
+        iter -= 2;
+
+        // Begin new Iteration. First extrapolate by a factor of -1 through
+        // the face of the simplex across from the high point, i.e. reflect
+        // the simplex from the high point
+        Real_t ytry = Amotsa(-1.0, ihi, yhi,temp);
+    
+        if (ytry <= ylo)
+        {
+            // cout << " !!!!!!!!!!!!!! E X P A N D  !!!!!!!!!!!!!!" << endl;
+            // Gives a result better than the best point, so try an additional
+            // extrapolation by a factor of 2
+            ytry = Amotsa(2.0, ihi, yhi,temp);
+            continue;
+        }
+
+        if (ytry < ynhi)
+        {
+            iter++;
+            continue;
+        }
+
+        // cout << " !!!!!!!!!!!! R E F L E C T  !!!!!!!!!!!!!!!!!!!!" << endl;
+        // The reflected point is worse than the second-highest, so look for an
+        // intermediate lower point, for (a one-dimensional contraction */
+        const Real_t fYsave = yhi;
+        ytry = Amotsa(0.5, ihi, yhi,temp);
+
+        if (ytry < fYsave)
+            continue;
+
+        // cout << " !!!!!!!!!!!! R E F L E C T  !!!!!!!!!!!!!!!!!!!!" << endl;
+        // The reflected point is worse than the second-highest, so look for an
+        // intermediate lower point, for (a one-dimensional contraction */
+        const Real_t ysave = yhi;
+        ytry = Amotsa(0.5, ihi, yhi,temp);
+      
+        if (ytry < ysave)
+            continue;
+
+        // cout << " !!!!!!!!!!!! C O N T R A C T  !!!!!!!!!!!!!!!!!!" << endl;
+        // Cannot seem to get rid of that point, better contract around the
+        // lowest (best) point
+        for (UShort_t i=0; i<fMpts; i++)
+        {
+            if (i != ilo)
+            {
+                for (UShort_t j=0;j<fNdim;j++)
+                {
+                    fPsum(j) = 0.5*(fP(i, j) + fP(ilo, j));
+
+                    // Create new cutvalues
+                    fP(i, j) = fPsum(j);
+                }
+                fY(i) = FunctionToMinimize(fPsum);
+            }
+        }
+
+        iter -= fNdim;
+        GetPsum();
+    }
+    return iter;
+}
+
+void MSimulatedAnnealing::GetPsum()
+{
+    for (Int_t n=0; n<fNdim; n++)
+    {
+        Real_t sum=0.0;
+        for (Int_t m=0;m<fMpts;m++)
+            sum += fP(m,n);
+
+        fPsum(n) = sum;
+    }
+}
+
+
+Real_t MSimulatedAnnealing::Amotsa(const Float_t fac, const UShort_t ihi, 
+                                   Real_t &yhi, const Real_t temp)
+{
+  
+    const Real_t fac1 = (1.-fac)/fNdim;
+    const Real_t fac2 = fac1 - fac;
+
+    Int_t borderflag = 0;
+    TVector ptry(fNdim);
+    TVector cols(fMpts);
+
+    for (Int_t j=0; j<fNdim; j++)
+    {
+        ptry(j) = fPsum(j)*fac1 - fP(ihi, j)*fac2;
+
+        // Check that the simplex does not go to infinite values,
+        // in case of: reflect it
+        const Real_t newcut = ptry(j);
+  
+        if (fP1(j) > fP0(j))
+        {
+            if (newcut > fP1(j))
+            {
+                ptry(j) = fP1(j);
+                borderflag = 1;
+            }
+            else
+                if (newcut < fP0(j))
+                {
+                    ptry(j) = fP0(j);
+                    borderflag = 1;
+                }
+        }
+    
+        else
+        {
+            if (newcut < fP1(j))
+            {
+                ptry(j) = fP1(j);
+                borderflag = 1;
+            }
+            else
+                if (newcut > fP0(j))
+                {
+                    ptry(j) = fP0(j);
+                    borderflag = 1;
+                }
+        }
+    }
+
+    Real_t faccompare = 0.5;
+    Real_t ytry = 0;
+  
+    switch (borderflag)
+    {
+    case kENoBorder:
+        ytry = FunctionToMinimize(fPsum);
+        break;
+
+    case kEStrictBorder:
+        ytry = FunctionToMinimize(fPsum) + gsYtryStr;
+        break;
+
+    case kEContractBorder:
+        ytry = fac == faccompare ? gsYtryCon : gsYtryStr;
+        break;
+    }
+
+    if (ytry < fYb)
+    {
+        fPb = ptry;
+        fYb = ytry;
+    }
+
+    const Real_t yflu = ytry + gRandom->Exp(temp);
+
+    if (yflu >= yhi)
+        return yflu;
+
+    fY(ihi) = ytry;
+    yhi     = yflu;
+    
+    for(Int_t j=0; j<fNdim; j++)
+    {
+        fPsum(j) += ptry(j)-fP(ihi, j);
+        fP(ihi, j) = ptry(j);
+    }
+
+    return yflu;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Dummy FunctionToMinimize
+//
+//  A class inheriting from MSimulatedAnnealing NEEDS to contain a similiar
+//  
+//  virtual Float_t FunctionToMinimize(const TVector \&)
+//  
+//  The TVector contains the n parameters (dimensions) of the function
+//
+Float_t MSimulatedAnnealing::FunctionToMinimize(const TVector &arr) 
+{
+  return 0.0;
+}
Index: branches/Mars_McMismatchStudy/mtools/MSimulatedAnnealing.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MSimulatedAnnealing.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MSimulatedAnnealing.h	(revision 17960)
@@ -0,0 +1,110 @@
+#ifndef MARS_MSimulatedAnnealing
+#define MARS_MSimulatedAnnealing
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+class MHSimulatedAnnealing;
+class TRandom;
+
+class MSimulatedAnnealing : public TObject
+{
+private:
+
+    static const Float_t gsYtryStr;  // Fixed high value to keep the simplex inside the borders
+    static const Float_t gsYtryCon;  // Fixed high value to keep the simplex inside the borders
+    static const Int_t   gsMaxDim;   // Fixed maximum number of dimensions
+    static const Int_t   gsMaxStep;  // Fixed maximum number of loops with temperature=0
+
+    MHSimulatedAnnealing *fResult;   //! The histogram output container
+
+    TRandom *fRandom;                // The random number generator -> random numbers between 0 and 1
+  
+    Real_t   fTolerance;             // The convergence break condition
+  
+    UShort_t fNdim;                  // The number of parameters 
+    UShort_t fMpts;                  // The number of simplex points (=fNdim+1)
+  
+    UShort_t fNumberOfMoves;         // The total number of moves (== CPU time) 
+
+    Real_t   fStartTemperature;      // The start temperature -> will slowly get decreased to 0
+
+    Bool_t   fFullStorage;           // kTRUE -> the whole simplex gets stored in MHSimlutedAnnealing
+    Bool_t   fInit;                  // kTRUE -> initialization was succesful
+
+    TMatrix fP;                      // The (ndim+1,ndim) matrix containing the simplex 
+
+    TVector fPsum;                   // The sum of each point of the simplex
+    
+    TVector fP0;                     // The boundary conditions on the weak side
+    TVector fP1;                     // The boundary conditions on the strong side
+    TVector fY;                      // The array containing the function evaluation results
+
+    Real_t  fYb;                     // The best function evaluation value ever found
+    Real_t  fYconv;                  // The function evaluation value at the convergence point
+    
+    TVector fPb;                     // The parameters belonging to fYb
+    TVector fPconv;                  // The parameters belonging to fYconv
+    
+    Int_t Amebsa(Int_t iter,
+                 const Real_t temp); // The function deciding if the simplex has to get reflected, expanded or contracted
+
+    Real_t   Amotsa(const Float_t  fac,
+                    const UShort_t ihi,
+                    Real_t &yhi,
+                    const Real_t temp); // The function reflecting, expanding and contracting the simplex: fac=-1 -> reflection, fac=0.5 -> contraction, fac=2.0 -> expansion
+
+    void     GetPsum();              
+    
+protected:
+  
+    virtual Float_t FunctionToMinimize(const TVector &arr); // The optimization function  
+
+public:
+    enum BorderFlag_t { kENoBorder, kEStrictBorder, kEContractBorder };
+    enum Verbosity_t  { kEDefault, kEVerbose, kEDebug };
+
+private:
+    BorderFlag_t fBorder;         
+    Verbosity_t  fVerbose;        
+
+public:
+    MSimulatedAnnealing();
+    virtual ~MSimulatedAnnealing();
+
+    void ModifyTolerance(Float_t tol)          { fTolerance = tol;  }
+    void ModifyBorderFlag(BorderFlag_t border) { fBorder    = border; }
+    
+    Bool_t Initialize(const TMatrix &p,  const TVector &y,
+                      const TVector &p0, const TVector &p1);
+  
+    void SetNumberOfMoves(UShort_t moves)      { fNumberOfMoves    = moves;  }
+    void SetStartTemperature(Float_t temp)     { fStartTemperature = temp;   }
+    void SetFullStorage()                      { fFullStorage      = kTRUE;  }  
+    void SetVerbosityLevel(Verbosity_t level)  { fVerbose          = level;  }
+    void SetRandom(TRandom *rand)              { fRandom           = rand;   }
+
+    const TVector &GetPb()    const            { return fPb;    }
+    Float_t GetYb()           const            { return fYb;    }
+
+    const TVector &GetPconv() const            { return fPconv; }    
+    Float_t GetYconv()        const            { return fYconv; }  
+  
+  
+    MHSimulatedAnnealing *GetResult()          { return fResult; }
+  
+    Bool_t RunMinimization();
+  
+    ClassDef(MSimulatedAnnealing,1)  // Class to perform a Simulated Annealing Minimization
+};
+    
+#endif
Index: branches/Mars_McMismatchStudy/mtools/MTFillMatrix.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MTFillMatrix.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MTFillMatrix.cc	(revision 17960)
@@ -0,0 +1,495 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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");
+//
+//
+// Task List execution
+// ----------------------------------------------
+//
+// The tasklist is excuted in the follwowing order:
+//   - fReader      set by SetReader
+//   - fPreTasks    in the order as set with the SetPreTask functions
+//   - fPreCuts     in the order as set with the SetPreCut  functions
+//   - Selection    the event selection
+//   - fPostTasks   in the order as set with the SetPostTask functions
+//   - Fill Matrix
+//   - Write output
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTFillMatrix.h"
+
+#include <TFile.h>
+#include <TMath.h>
+
+// environment
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+// eventloop
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+// tasks
+#include "MRead.h"
+#include "MFillH.h"
+#include "MContinue.h"
+
+// filters
+#include "MFDataPhrase.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 || num==0)
+        return kTRUE;
+
+    m->Print("SizeCols");
+
+    if (num<0)
+        return kTRUE;
+
+    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;
+}
+
+void MTFillMatrix::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFillMatrix";
+    fTitle = title ? title : "Tool to fill MHMatrix from file";
+}
+
+MTFillMatrix::MTFillMatrix(const char *name, const char *title)
+: fReference(0), fReader(0), fDestMatrix1(0), fDestMatrix2(0),
+  fNumDestEvents1(0), fNumDestEvents2(0), fNumMaxEvents(0),
+  fWriteFile1(0), fWriteFile2(0)
+{
+    Init(name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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, const char *name, const char *title)
+: fReference(0), fReader(0), fDestMatrix1(0), fDestMatrix2(0),
+  fNumDestEvents1(0), fNumDestEvents2(0), fNumMaxEvents(0),
+  fWriteFile1(0), fWriteFile2(0)
+{
+    Init(name, title);
+    if (ref)
+        fReference = (MH3*)ref->Clone();
+}
+
+MTFillMatrix::~MTFillMatrix()
+{
+    if (fReference)
+        delete fReference;
+}
+
+//------------------------------------------------------------------------
+//
+// Function serving AddPreCuts, AddPreTasks and AddPostTasks
+//
+void MTFillMatrix::Add(const TList &src, const TClass *cls, TList &dest)
+{
+    TIter Next(&src);
+    TObject *obj=0;
+    while ((obj=Next()))
+        if (obj->InheritsFrom(cls))
+            dest.Add(obj);
+}
+
+//------------------------------------------------------------------------
+//
+// Add a cut which is used to fill the matrix, eg "MMcEvt.fOartId<1.5"
+// (The rule is applied, nit inverted: The matrix is filled with
+// the events fullfilling the condition)
+//
+void MTFillMatrix::AddPreCut(const char *rule)
+{
+    MFilter *f = new MFDataPhrase(rule);
+    f->SetBit(kCanDelete);
+    AddPreCut(f);
+}
+
+//------------------------------------------------------------------------
+//
+// Add a cut which is used to fill the matrix. If kCanDelete is set
+// MJOptimize takes the ownership.
+//
+void MTFillMatrix::AddPreCut(MFilter *f)
+{
+    fPreCuts.Add(f);
+}
+
+//------------------------------------------------------------------------
+//
+// Add all entries deriving from MFilter from list to PreCuts.
+// The ownership is not affected.
+//
+void MTFillMatrix::AddPreCuts(const TList &list)
+{
+    Add(list, MFilter::Class(), fPreCuts);
+}
+
+//------------------------------------------------------------------------
+//
+// Add a task which is executed before the precuts. If kCanDelete is set
+// MJOptimize takes the ownership.
+//
+void MTFillMatrix::AddPreTask(MTask *t)
+{
+    fPreTasks.Add(t);
+}
+
+//------------------------------------------------------------------------
+//
+// Add all entries deriving from MTask from list to PreTasks.
+// The ownership is not affected.
+//
+void MTFillMatrix::AddPreTasks(const TList &list)
+{
+    Add(list, MTask::Class(), fPreTasks);
+}
+
+//------------------------------------------------------------------------
+//
+// Add a task which is executed after the precuts. If kCanDelete is set
+// MJOptimize takes the ownership.
+//
+void MTFillMatrix::AddPostTask(MTask *t)
+{
+    fPostTasks.Add(t);
+}
+
+//------------------------------------------------------------------------
+//
+// Add all entries deriving from MTask from list to PostTasks.
+// The ownership is not affected.
+//
+void MTFillMatrix::AddPostTasks(const TList &list)
+{
+    Add(list, MTask::Class(), fPostTasks);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the matrix (FIXME: Flow diagram missing)
+//
+Bool_t MTFillMatrix::Process(const MParList &parlist)
+{
+    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 ";
+    if (fNumDestEvents1<0)
+        *fLog << "all events";
+    else
+        *fLog << fNumDestEvents1;
+    cout << "." << endl;
+    if (fDestMatrix2)
+    {
+        *fLog << "Fill " << fDestMatrix2->GetDescriptor() << " with ";
+    if (fNumDestEvents2<0)
+        *fLog << "all events";
+    else
+        *fLog << fNumDestEvents2;
+    cout << "." << 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
+    //
+    //parlist.Print();
+    MParList  plist(parlist);
+    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 (fNumDestEvents1>0 || fNumDestEvents2>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 PreCuts
+    //
+    MFilterList list;
+    list.SetName("PreCuts");
+    if (!list.AddToList(fPreCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
+
+    MContinue cont0(&list);
+    cont0.SetInverted();
+
+    //
+    // 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
+    tlist.AddToList(fPreTasks, 0);   // PreTasks
+    if (fPreCuts.GetEntries()>0)
+        tlist.AddToList(&cont0);     // PreCuts
+    if (fReference && selector)
+        tlist.AddToList(&cont);      // select a sample of events
+    tlist.AddToList(&invsplit);      // process invsplit (which implicitly processes split)
+    tlist.AddToList(fPostTasks, 0);  // PostTasks
+    if (fDestMatrix1)
+        tlist.AddToList(&fill1);     // fill matrix 1
+    if (fDestMatrix2)
+        tlist.AddToList(&fill2);     // fill matrix 2
+    if (fWriteFile1)
+    {
+        fWriteFile1->SetFilter(&split);
+        tlist.AddToList(fWriteFile1);
+    }
+    if (fWriteFile2)
+    {
+        fWriteFile2->SetFilter(&invsplit);
+        tlist.AddToList(fWriteFile2);
+    }
+
+    tlist.SetAccelerator(MTask::kAccDontReset|MTask::kAccDontTime);
+
+    //
+    // Execute the eventloop
+    //
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+
+    const Bool_t rc = evtloop.Eventloop(fNumMaxEvents);
+
+    if (selector)
+        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);
+}
+
+Int_t MTFillMatrix::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumDestEvents1", print))
+    {
+        rc = kTRUE;
+        SetNumDestEvents1(GetEnvValue(env, prefix, "NumDestEvents1", fNumDestEvents1));
+    }
+    if (IsEnvDefined(env, prefix, "NumDestEvents2", print))
+    {
+        rc = kTRUE;
+        SetNumDestEvents2(GetEnvValue(env, prefix, "NumDestEvents2", fNumDestEvents2));
+    }
+    return rc;
+}
Index: branches/Mars_McMismatchStudy/mtools/MTFillMatrix.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MTFillMatrix.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MTFillMatrix.h	(revision 17960)
@@ -0,0 +1,105 @@
+#ifndef MARS_MTFillMatrix
+#define MARS_MTFillMatrix
+
+#ifndef MARS_MParList
+#include "MParList.h"
+#endif
+
+#ifndef MARS_MH3
+#include "MH3.h"
+#endif
+
+class MRead;
+class MTask;
+class MHMatrix;
+class MFilter;
+
+class MTFillMatrix : public MParContainer
+{
+private:
+    MH3      *fReference;
+    MRead    *fReader;
+
+    MHMatrix *fDestMatrix1;
+    MHMatrix *fDestMatrix2;
+
+    Int_t     fNumDestEvents1;
+    Int_t     fNumDestEvents2;
+
+    Int_t     fNumMaxEvents;
+
+    MTask    *fWriteFile1;
+    MTask    *fWriteFile2;
+
+    TList     fPreCuts;
+    TList     fPreTasks;
+    TList     fPostTasks;
+
+    void Init(const char *name, const char *title);
+
+    void Add(const TList &src, const TClass *cls, TList &dest);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    Bool_t CheckResult(MHMatrix *m, Int_t num) const;
+    Bool_t WriteMatrix(MHMatrix *m, const TString &fname, Int_t i) const;
+
+public:
+    MTFillMatrix(const char *name=0, const char *title=0);
+    MTFillMatrix(const MH3 *ref, const char *name=0, const char *title=0);
+    ~MTFillMatrix();
+
+    void SetDestMatrix1(MHMatrix *matrix, UInt_t num=0)
+    {
+        fDestMatrix1 = matrix;
+        if (num>0)
+            SetNumDestEvents1(num);
+    }
+    void SetWriteFile1(MTask *write, UInt_t num=0)
+    {
+        fWriteFile1 = write;
+        if (num>0)
+            SetNumDestEvents1(num);
+    }
+    void SetDestMatrix2(MHMatrix *matrix, UInt_t num=0)
+    {
+        fDestMatrix2 = matrix;
+        if (num>0)
+            SetNumDestEvents2(num);
+    }
+    void SetWriteFile2(MTask *write, UInt_t num=0)
+    {
+        fWriteFile2 = write;
+        if (num>0)
+            SetNumDestEvents2(num);
+    }
+    void SetNumDestEvents1(UInt_t num) { fNumDestEvents1 = num; }
+    void SetNumDestEvents2(UInt_t num) { fNumDestEvents2 = num; }
+    void SetMaxEvents(UInt_t num)      { fNumMaxEvents = num; }
+
+    void SetReader(MRead *task) { fReader = task; }
+
+    void AddPreCut(const char *rule);
+    void AddPreCut(MFilter *f);
+    void AddPreCuts(const TList &list);
+
+    void ClearPreCuts()   { fPreCuts.Clear(); }
+    void ClearPreTasks()  { fPreTasks.Clear(); }
+    void ClearPostTasks() { fPostTasks.Clear(); }
+
+    void AddPreTask(MTask *t);
+    void AddPreTasks(const TList &list);
+
+    void AddPostTask(MTask *t);
+    void AddPostTasks(const TList &list);
+
+    Bool_t Process(const MParList &plist=MParList());
+
+    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: branches/Mars_McMismatchStudy/mtools/MagicCivilization.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicCivilization.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicCivilization.cc	(revision 17960)
@@ -0,0 +1,380 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 "MH.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicCivilization);
+
+using namespace std;
+
+void MagicCivilization::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    delete fGeomCam;
+}
+
+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;
+
+    AppendPad();
+}
+
+void MagicCivilization::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    fColors.Set(fNumPixels);
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicCivilization::MagicCivilization(Byte_t lim, UShort_t init)
+    : fTimer(this, 500, kTRUE), fGeomCam(NULL), fNumInit(init), fLimit(lim)
+{
+    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();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 Float_t r = fGeomCam->GetMaxRadius();
+
+    MH::SetPadRange(-r, -r, r, r*1.1);
+
+    TAttLine line;
+    TAttFill fill;
+
+    // FIXME:
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        fill.SetFillColor(fColors[i]);
+        pix.PaintPrimitive(line, fill);
+    }
+ /*
+    for (int i=0; i<6; i++)
+        fText[i]->Paint();
+        */
+}
+
+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;
+
+    fColors.Reset();
+
+    Update();
+
+    gPad->Modified();
+    gPad->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
+    //
+    new TCanvas("MagicCivilization", "Magic Civilization", 0, 0, 800, 800);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFillColor(22);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    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();
+        gPad->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++)
+    {
+        MGeom &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++)
+    {
+        MGeom &pix = (*fGeomCam)[i];
+
+        if (pix.TestBit(kHasCreation))
+        {
+            pix.SetBit(kHasFlag);
+            fColors[i] = kBlack;
+            fNumCivilizations++;
+        }
+        else
+        {
+            pix.ResetBit(kHasFlag);
+            fColors[i] = kBackground;
+        }
+        pix.ResetBit(kHasCreation);
+    }
+
+    if (fNumCivilizations==0 || fNumCivilizations==fNumPixels)
+        fAuto = kFALSE;
+
+    fStep++;
+
+    Update();
+
+    gPad->Update();
+
+    return kTRUE;
+}
+
Index: branches/Mars_McMismatchStudy/mtools/MagicCivilization.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicCivilization.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicCivilization.h	(revision 17960)
@@ -0,0 +1,77 @@
+#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
+#ifndef ROOT_TArrayI
+#include <TArrayI.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
+
+    TArrayI fColors;
+
+    void   Update();
+    void   Free();
+    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: branches/Mars_McMismatchStudy/mtools/MagicDomino.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicDomino.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicDomino.cc	(revision 17960)
@@ -0,0 +1,665 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 <TMath.h>
+#include <TCanvas.h>
+#include <TRandom.h>
+#include <TInterpreter.h>
+
+#include "MH.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;
+
+    delete fGeomCam;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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();
+    AppendPad();
+}
+
+// ------------------------------------------------------------------------
+//
+// Reset/set all veriables needed for a new camera geometry
+//
+void MagicDomino::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    fColors.Set(fNumPixels);
+}
+
+// ------------------------------------------------------------------------
+//
+// remove the pixel numbers in the tile from the pad
+//
+void MagicDomino::RemoveNumbers()
+{
+    for (int i=0; i<6; i++)
+        fText[i]->SetText(0, 0, "");
+}
+
+// ------------------------------------------------------------------------
+//
+// Reset/restart the game
+//
+void MagicDomino::Reset()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        fColors[i] = kBackground;
+        (*fGeomCam)[i].ResetBit(kUserBits);
+    }
+
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    SetBit(kNoContextMenu);
+#endif
+
+    if (fDone)
+    {
+        delete fDone;
+        fDone = NULL;
+    }
+
+
+    gPad->SetFillColor(22);
+
+    fNumPixel = -1;
+    fNumTile  =  0;
+    fPoints   =  0;
+
+    NewTile();
+}
+
+// ------------------------------------------------------------------------
+//
+void MagicDomino::Init()
+{
+    for (int i=0; i<6; i++)
+    {
+        fText[i] = new TText(0, 0, "");
+        fText[i]->SetTextFont(122);
+        fText[i]->SetTextAlign(22);   // centered/centered
+    }
+
+    //
+    // 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();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicDomino::MagicDomino()
+    : fGeomCam(NULL), fDir(kBottom), fDone(NULL)
+{
+    SetNewCamera(new MGeomCamMagic);
+    Init();
+}
+// ------------------------------------------------------------------------
+//
+//
+MagicDomino::MagicDomino(const MGeomCam &geom)
+    : fGeomCam(NULL), fDir(kBottom), fDone(NULL)
+{
+    SetNewCamera(static_cast<MGeomCam*>(geom.Clone()));
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MagicDomino::~MagicDomino()
+{
+    Free();
+
+    RemoveNumbers();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 Float_t r = fGeomCam->GetMaxRadius();
+
+    MH::SetPadRange(-r, -r, r, r*1.1);
+
+    TAttLine line;
+    TAttFill fill;
+
+    // FIXME:
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        fill.SetFillColor(fColors[i]);
+        pix.PaintPrimitive(line, fill);
+    }
+
+    for (int i=0; i<6; i++)
+        fText[i]->Paint();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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
+    //
+    new TCanvas("MagicDomino", "Magic Domino Next Neighbours", 0, 0, 800, 800);
+
+    gPad->SetBorderMode(0);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Reset the game pad
+    //
+    Reset();
+
+    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)
+    {
+        MGeom &pix=(*fGeomCam)[fNumPixel];
+        pix.ResetBit(kIsTile);
+        for (int i=0; i<pix.GetNumNeighbors(); i++)
+            (*fGeomCam)[pix.GetNeighbor(i)].ResetBit(kIsTile);
+
+        fPoints += pix.GetNumNeighbors();
+    }
+
+    RemoveNumbers();
+
+    fNumPixel = -1;
+    fSkipped  =  0;
+    fNumTile++;
+
+    NewColors();
+    Update();
+
+    gPad->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 MGeom &pix1=(*fGeomCam)[fNumPixel];
+    for (int i=0; i<pix1.GetNumNeighbors(); i++)
+    {
+        const Int_t idx1 = pix1.GetNeighbor(i);
+        const MGeom &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 MGeom &hex = (*fGeomCam)[idx2];
+
+            if (hex.TestBit(kIsTile) || fColors[idx2]==kBackground)
+            {
+                ignored++;
+                continue;
+            }
+
+            if (fColors[idx2]==fColors[idx1])
+                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);
+
+    gPad->SetFillColor(kRed);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDone->SetBit(kNoContextMenu|kCannotPick);
+    ResetBit(kNoContextMenu);
+#endif
+
+    gPad->Modified();
+    gPad->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();
+
+    gPad->Modified();
+    gPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Hide the tile from the pad
+//
+void MagicDomino::HideTile()
+{
+    if (fNumPixel<0)
+        return;
+
+    RemoveNumbers();
+
+    MGeom &pix1=(*fGeomCam)[fNumPixel];
+    fColors[fNumPixel] = fOldColors[6];
+    pix1.ResetBit(kIsTile);
+    for (int i=0; i<pix1.GetNumNeighbors(); i++)
+    {
+        Int_t idx = pix1.GetNeighbor(i);
+
+        fColors[idx] = fOldColors[i];
+        (*fGeomCam)[idx].ResetBit(kIsTile);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Show the tile on the pad
+//
+void MagicDomino::ShowTile()
+{
+    if (fNumPixel<0)
+        return;
+
+    Int_t indices[6];
+    GetSortedNeighbors(indices);
+
+    RemoveNumbers();
+
+    MGeom &pix2=(*fGeomCam)[fNumPixel];
+    fOldColors[6] = fColors[fNumPixel];
+    fColors[fNumPixel] = kBlack;
+    pix2.SetBit(kIsTile);
+    for (int i=0; i<pix2.GetNumNeighbors(); i++)
+    {
+        Int_t idx = pix2.GetNeighbor(i);
+
+        fOldColors[i] = fColors[idx];
+
+        int j=0;
+        while (indices[j]!=i)
+            j++;
+
+        MGeom &pix = (*fGeomCam)[idx];
+
+        fColors[idx] = fNewColors[(j+fPosition)%6];
+        pix.SetBit(kIsTile);
+
+        TString num;
+        num += idx;
+
+        fText[i]->SetText(pix.GetX(), pix.GetY(), num);
+        fText[i]->SetTextSize(0.3*pix.GetT()/fGeomCam->GetMaxRadius());
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Hide the tile, change its position, show it again, update status text
+//
+void MagicDomino::ChangePixel(Int_t add)
+{
+    HideTile();
+
+    fNumPixel = add;
+
+    ShowTile();
+
+    Update();
+
+    gPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Analyse the directions of the next neighbors
+//
+Short_t MagicDomino::AnalysePixel(Int_t dir)
+{
+    const MGeom &pix=(*fGeomCam)[fNumPixel<0?0:fNumPixel];
+
+    Double_t fAngle[6] = { -10, -10, -10, -10, -10, -10 };
+
+    for (int i=0; i<pix.GetNumNeighbors(); i++)
+    {
+        MGeom &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 MGeom &pix=(*fGeomCam)[fNumPixel<0?0:fNumPixel];
+
+    Double_t fAngle[6] = { -10, -10, -10, -10, -10, -10 };
+
+    for (int i=0; i<pix.GetNumNeighbors(); i++)
+    {
+        MGeom &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: branches/Mars_McMismatchStudy/mtools/MagicDomino.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicDomino.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicDomino.h	(revision 17960)
@@ -0,0 +1,99 @@
+#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
+#ifndef ROOT_TArrayI
+#include <TArrayI.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
+
+    TArrayI fColors;
+
+    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    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    Init();
+
+    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(const MGeomCam &geom);
+    ~MagicDomino();
+
+    void Reset();        //*MENU*
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MagicDomino, 0) // Magic Camera Games: Some kind of Domino
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/MagicJam.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicJam.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicJam.cc	(revision 17960)
@@ -0,0 +1,1040 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2005-2008
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicJam
+//
+// Jam is a multi player game. It is controlled by its context menu (click
+// with the right mouse button on one of the pixels in the game pad).
+//
+// Start the game with:
+//  MagicJam jam;
+//
+// Rules:
+//  MagicJam is a multiplayer game. The aim is to own the full game pad.
+// Ech pixel in the pad can contain as many entries as it has neighbors.
+// If it has more entries than neighbors it overflows into its neighbors.
+// All pixels into which such an overflow occures will be captured by
+// the current player. Player by player will be able to increase the
+// entry in one pixel by one. Increase the contents of an empty pixel to
+// one or by one in an owned pixel. The player who once will own the
+// all pixels will win.
+//
+// Editor:
+//  To edit or create a new game start the editor from the context menu
+// of MagicJam. The editor is also controlled from its context menu.
+// Use the curso keys to shift your game.
+// Warning: You MUST create a single-island game. Games which have two
+// islands might result in edless loops. (Currently there is no check!)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MagicJam.h"
+
+#include <climits> // INT_MAX (Ubuntu 8.10)
+
+#include <iostream>
+#include <fstream>
+
+#include <errno.h>
+
+#include <KeySymbols.h>
+
+#include <TMath.h>
+#include <TRandom.h>
+
+#include <TBox.h>
+#include <TLine.h>
+#include <TText.h>
+
+#include <TStyle.h>
+#include <TSystem.h>
+
+#include <TNtuple.h>
+#include <TASImage.h>
+#include <TInterpreter.h>
+#include <TGFileDialog.h>
+
+#include "MH.h"
+#include "MHexagon.h"
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MDirIter.h"
+
+ClassImp(MagicJamAbc);
+ClassImp(MagicJamEditor);
+ClassImp(MagicJam);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//                     The editor for MagicJam
+// -------------------------------------------------------------------------
+
+// --------------------------------------------------------------------------
+//
+// Move the contents of the pad
+//
+void MagicJamEditor::Move(int dx, int dy)
+{
+    const TArrayC cpy(fUsed);
+
+    Int_t h = cpy.GetSize()/fWidth;
+
+    for (int i=0; i<cpy.GetSize(); i++)
+    {
+        Int_t x = i%fWidth;
+        Int_t y = i/fWidth;
+
+        x += dx   + fWidth;
+        y += dy*2 + h;
+
+        x %= fWidth;
+        y %= h;
+
+        fUsed[x+y*fWidth] = cpy[i];
+    }
+    gPad->GetPad(1)->Modified();
+    gPad->GetPad(1)->Update();
+    gPad->Modified();
+    gPad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the pad with size wx, hy
+//
+void MagicJamEditor::InitGeom(int wx, int hy)
+{
+    const Float_t dx = 0.5*(wx-1);
+    const Float_t dy = 0.5*(hy-1);
+
+    fWidth = wx;
+
+    MGeomCam cam(wx*hy, 1);
+
+    for (int x=0; x<wx; x++)
+        for (int y=0; y<hy; y++)
+        {
+            Float_t x0 = TMath::Odd(y) ? x-0.25 : x+0.25;
+
+            cam.SetAt(x + y*fWidth, MGeomPix(x0-dx, (y-dy)*0.866, 1));
+        }
+
+
+    cam.InitGeometry();
+
+    SetGeometry(cam);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get index of pixel with position px, py
+//
+Int_t MagicJamEditor::GetPixelIndexFlt(Float_t px, Float_t py) const
+{
+    if (fNcells<=1)
+        return -1;
+
+    Int_t i;
+    for (i=0; i<fNcells-2; i++)
+    {
+        if ((*fGeomCam)[i].IsInside(px, py))
+            return i;
+    }
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the MagicJam editor. Load a game with name name.
+//
+MagicJamEditor::MagicJamEditor(const char *name) : fImage(NULL)
+{
+    InitGeom(20, 20);
+
+    SetBit(kNoLegend);
+    SetBit(kNoScale);
+
+    Draw();
+
+    gPad->SetEditable(kFALSE);
+
+    if (name)
+        LoadGame(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fImage
+//
+MagicJamEditor::~MagicJamEditor()
+{
+    if (fImage)
+        delete fImage;
+}
+
+// --------------------------------------------------------------------------
+//
+// Change width and height of pad. Preserve contents.
+//
+void MagicJamEditor::SetWidthHeight(Int_t dx, Int_t dy)
+{
+    TNtuple tup("", "", "x:y");
+    tup.SetDirectory(0);
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        if (IsUsed(i))
+            tup.Fill((*fGeomCam)[i].GetX(), (*fGeomCam)[i].GetY());
+    }
+    InitGeom(dx, dy);
+
+    fEntries=0;
+    for (int i=0; i<tup.GetEntries(); i++)
+    {
+        tup.GetEntry(i);
+        const Int_t idx = GetPixelIndexFlt(tup.GetArgs()[0], tup.GetArgs()[1]);
+        if (idx>=0)
+        {
+            SetUsed(idx);
+            fEntries++;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Save the current game
+//
+void MagicJamEditor::SaveGame(const char *name)
+{
+    ofstream fout(name);
+    if (!fout)
+    {
+        cout << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return;
+    }
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+        if (IsUsed(i))
+            fout << i%fWidth << " " << i/fWidth << endl;
+
+    SetName(name);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Load a game
+//
+void MagicJamEditor::LoadGame(const char *name)
+{
+    InitGeom(1,1);
+    Reset();
+
+    ifstream fin(name);
+    if (!fin)
+    {
+        cout << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return;
+    }
+
+    Int_t maxx=-INT_MAX;
+    Int_t maxy=-INT_MAX;
+    Int_t minx= INT_MAX;
+    Int_t miny= INT_MAX;
+
+    TNtuple tup("", "", "x:y");
+    tup.SetDirectory(0);
+
+    while (1)
+    {
+        Int_t x,y;
+        fin >> x >> y;
+        if (!fin)
+            break;
+
+        tup.Fill(x, y);
+
+        maxx = TMath::Max(maxx, x);
+        maxy = TMath::Max(maxy, y);
+        minx = TMath::Min(minx, x);
+        miny = TMath::Min(miny, y);
+    }
+
+    if (tup.GetEntries()==0)
+    {
+        cout << "File " << name << " contains no entries!" << endl;
+        return;
+    }
+
+    if (TMath::Odd(miny))
+        miny--;
+
+    InitGeom((maxx-minx)+1, (maxy-miny)+1);
+
+    for (int i=0; i<tup.GetEntries(); i++)
+    {
+        tup.GetEntry(i);
+
+        const Int_t x = TMath::Nint(tup.GetArgs()[0]) - minx;
+        const Int_t y = TMath::Nint(tup.GetArgs()[1]) - miny;
+        SetUsed(x + y*fWidth);
+    }
+
+    fEntries=tup.GetEntries();;
+
+    SetName(name);
+}
+
+void MagicJamEditor::ShowImageAsBackground(const char *name)
+{
+    if (fImage)
+        delete fImage;
+
+    fImage = new TASImage(name);
+    if (!fImage->IsValid())
+    {
+        delete fImage;
+        fImage = NULL;
+        return;
+    }
+
+    fImage->SetEditable(kFALSE);
+
+    SetFillStyle(4000);
+}
+
+void MagicJamEditor::RemoveBackgroundImage()
+{
+    if (fImage)
+    {
+        delete fImage;
+        fImage=NULL;
+    }
+
+    SetFillStyle(1001);
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint the game pad
+//
+void MagicJamEditor::Paint(Option_t *o)
+{
+    TString str = Form("Jam Editor pad %dx%d", fWidth, GetNumPixels()/fWidth);
+    SetTitle(str);
+
+    Float_t maxx = 0;
+    Float_t minx = 0;
+    Float_t maxy = 0;
+    Float_t miny = 0;
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        const Float_t x = (*fGeomCam)[i].GetX();
+        const Float_t y = (*fGeomCam)[i].GetY();
+
+        maxx = TMath::Max(maxx, x);
+        minx = TMath::Min(minx, x);
+        maxy = TMath::Max(maxy, y);
+        miny = TMath::Min(miny, y);
+    }
+
+    if (fImage)
+    {
+        const Float_t r = fGeomCam->GetMaxRadius();
+
+        MH::SetPadRange(-r*1.02, -r*1.02, TestBit(kNoLegend) ? r : 1.15*r, r*1.2);
+
+        Double_t x1, y1, x2, y2;
+        gPad->GetRange(x1, y1, x2, y2);
+
+        gPad->SetLeftMargin  (    (minx-x1)/(x2-x1));
+        gPad->SetBottomMargin(    (miny-y1)/(y2-y1));
+        gPad->SetRightMargin (1 - (maxx-x1)/(x2-x1));
+        gPad->SetTopMargin   (1 - (maxy-y1)/(y2-y1));
+
+        fImage->Paint();
+    }
+
+    gStyle->SetOptStat(11);
+    MHCamera::Paint(o);
+
+    TBox box;
+    box.SetLineColor(kBlack);
+    box.SetFillStyle(0);
+    box.PaintBox(minx-1, miny-1, maxx+1, maxy+1);
+
+    TLine l;
+    //l.SetLineStyle(kDashed);
+    l.SetLineColor(15);
+    l.PaintLine(0, miny, 0, maxy);
+    l.PaintLine(minx, 0, maxx, 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Call MHCamera Draw connect a signal to catch the keynoard events
+//
+void MagicJamEditor::Draw(Option_t *o)
+{
+    MHCamera::Draw();
+
+    // This seems to be necessary due to the pad-in-pad geometry
+    // otherwise I don't get the information about the keys pressed
+    gPad->GetCanvas()->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",
+                               "MagicJamEditor", this,
+                               "EventInfo(Int_t,Int_t,Int_t,TObject*)");
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the keyboard events
+//
+void MagicJamEditor::EventInfo(Int_t event, Int_t px, Int_t py, TObject *o)
+{
+    if (event==kKeyPress)
+    {
+        switch (py)
+        {
+        case kKey_Left:
+            Move(-1, 0);
+            break;
+
+        case kKey_Right:
+            Move(1, 0);
+            break;
+
+        case kKey_Up:
+            Move(0, 1);
+            break;
+
+        case kKey_Down:
+            Move(0, -1);
+            break;
+
+        default:
+            return;
+        }
+
+        TVirtualPad *p = dynamic_cast<TVirtualPad*>(o);
+        if (p)
+        {
+            p->Modified();
+            p->Update();
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Execute mouse events
+//
+void MagicJamEditor::ExecuteEvent(Int_t event, Int_t px, Int_t py)
+{
+    const Int_t idx = GetPixelIndex(px, py);
+    if (idx<0)
+        return;
+
+    switch (event)
+    {
+    case kButton1Down:
+        if (IsUsed(idx))
+        {
+            ResetUsed(idx);
+            fEntries--;
+        }
+        else
+        {
+            SetUsed(idx);
+            fEntries++;
+        }
+        break;
+
+    case kButton1Motion:
+        if (!IsUsed(idx))
+        {
+            SetUsed(idx);
+            fEntries++;
+        }
+        break;
+
+    default:
+        return;
+    }
+
+    gPad->Modified();
+    gPad->Update();
+}
+
+
+// -------------------------------------------------------------------------
+//                        MagicJam -- the Game
+// -------------------------------------------------------------------------
+
+// --------------------------------------------------------------------------
+//
+// Fill 1 in a single pixel. If the pixel has more content than neighbors
+// it overflows into its neighbors. Called recursivly.
+//
+void MagicJam::FillPix(Int_t idx)
+{
+    if (CountPlayers()==1)
+        return;
+
+    const Int_t newval = fBinEntries[idx+1]+1;
+
+    const MGeom &gpix = (*fGeomCam)[idx];
+    const Int_t n = gpix.GetNumNeighbors();
+
+    SetBinContent(idx+1, fNumPlayer);
+    SetUsed(idx);
+
+    if (newval <= n)
+    {
+        fBinEntries[idx+1] = newval;
+        return;
+    }
+
+    fEntries -= n;
+    fBinEntries[idx+1] = 1;
+
+    for (int i=0; i<n; i++)
+        FillPix(gpix.GetNeighbor(i));
+
+    gPad->Modified();
+    gPad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Count tiles of player 
+//
+Int_t MagicJam::CountPlayer(Int_t player) const
+{
+    Int_t sum = 0;
+    for (int i=0; i<GetNbinsX(); i++)
+        if (IsUsed(i) && TMath::Nint(GetBinContent(i+1))==player)
+            sum += fBinEntries[i+1];
+    return sum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Count number of players still able to move
+//
+Int_t MagicJam::CountPlayers() const
+{
+    if (GetEntries()<=fNumPlayers)
+        return 0;
+
+    Int_t cnt=0;
+    for (int i=0; i<fNumPlayers; i++)
+        if (CountPlayer(i)>0)
+            cnt++;
+
+    return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Start MagicJam. Loads the default game jam.txt and initializes a
+// two player game
+//
+MagicJam::MagicJam(const char *jam, MagicJam *game) : fNumPlayers(0), fGame(game)
+{
+    SetTitle("Magic Jam (game)");
+
+    SetBit(kNoLegend);
+    SetBit(kNoScale);
+    SetBit(kMustCleanup);
+
+    LoadGame(jam);
+
+    gInterpreter->DeleteGlobal(this);
+    gROOT->GetListOfCleanups()->Add(this);
+
+    if (fGame!=NULL)
+    {
+        SetBit(kNoContextMenu);
+        SetBit(kNoStats);
+        return;
+    }
+
+    if (!fGeomCam)
+        return;
+
+    SetNumPlayers(2);
+    SetMinMax(-0.5, 9.5);
+
+    Draw();
+    gPad->SetEditable(kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove fGame if it was deleted
+//
+void MagicJam::RecursiveRemove(TObject *obj)
+{
+    if (fGame==obj)
+        fGame=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a new number of players. Restarts the game
+//
+void MagicJam::SetNumPlayers(Byte_t n)
+{
+    if (n<2 || n>9)
+        return;
+
+    fNumPlayers = n;
+    fNumPlayer  = 0;
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Loads a new geometry (game). Restarts the game.
+//
+void MagicJam::LoadGame(const char *name)
+{
+    /*
+    if (gPad)
+    {
+    static const char *gOpenTypes[] =
+    {
+        "Template files",  "*.txt",
+        "All files",    "*",
+        NULL,           NULL
+    };
+
+    static TString dir(".");
+
+    TGFileInfo fi; // fFileName and fIniDir deleted in ~TGFileInfo
+
+    fi.fFileTypes = (const char**)gOpenTypes;
+    fi.fIniDir    = StrDup(dir);
+
+    dlg = new TGFileDialog(0, 0, kFDOpen, &fi);
+
+    // Checks is meanwhile the game has been closed!
+    if (!gPad)
+        return;
+
+    cout << "done" << endl;
+
+    cout << gPad << endl;
+
+    if (!fi.fFilename || gPad==NULL)
+        return;
+
+    cout << "test" << endl;
+
+    dir  = fi.fIniDir;
+    name = fi.fFilename;
+    }
+    //if (!gROOT->GetListOfSpecials()->FindObject(this))
+    //    return;
+
+    cout << "Done." << endl;
+    */
+    //***
+
+
+
+    ifstream fin(name);
+    if (!fin)
+    {
+        cout << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return;
+    }
+
+    Int_t maxx=-INT_MAX;
+    Int_t maxy=-INT_MAX;
+    Int_t minx= INT_MAX;
+    Int_t miny= INT_MAX;
+
+    TNtuple tup("", "", "x:y");
+    tup.SetDirectory(0);
+
+    while (1)
+    {
+        Int_t x,y;
+        fin >> x >> y;
+        if (!fin)
+            break;
+
+        tup.Fill(x, y);
+
+        maxx = TMath::Max(maxx, x);
+        maxy = TMath::Max(maxy, y);
+        minx = TMath::Min(minx, x);
+        miny = TMath::Min(miny, y);
+    }
+
+    if (tup.GetEntries()==0)
+    {
+        cout << "File " << name << " contains no entries!" << endl;
+        return;
+    }
+
+    MGeomCam cam(tup.GetEntries());
+
+    for (int i=0; i<tup.GetEntries(); i++)
+    {
+        tup.GetEntry(i);
+
+        const Int_t x = TMath::Nint(tup.GetArgs()[0]);
+        const Int_t y = TMath::Nint(tup.GetArgs()[1]);
+
+        Float_t dx = -minx-0.5*(maxx-minx+1);
+        Float_t dy = -miny-0.5*(maxy-miny+1);
+
+        dx += TMath::Odd(y) ? x-0.25 : x+0.25;
+        dy += y;
+
+        cam.SetAt(i, MGeomPix(dx, dy*0.866));
+    }
+
+    for (UInt_t i=0; i<cam.GetNumPixels(); i++)
+    {
+        Int_t nn[6] = { -1, -1, -1, -1, -1, -1 };
+        Int_t idx=0;
+
+        for (UInt_t j=0; j<cam.GetNumPixels(); j++)
+            if (i!=j && cam.GetDist(i,j)<1.5)
+                nn[idx++] = j;
+
+        cam[i].SetNeighbors(nn[0], nn[1], nn[2], nn[3], nn[4], nn[5]);
+    }
+
+    cam.InitGeometry();
+
+    SetGeometry(cam);
+
+    SetName(name);
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Restart the game.
+//
+void MagicJam::Reset(Option_t *o)
+{
+    MHCamera::Reset("");
+
+    if (fNumPlayers==0)
+    {
+        SetAllUsed();
+        return;
+    }
+
+    const Int_t max = TMath::Max((Int_t)GetNumPixels()/25, 1);
+    for (Int_t i=0; i<fNumPlayers; i++)
+    {
+        for (Int_t x=0; x<max; x++)
+        {
+            const Int_t idx = gRandom->Integer(GetNumPixels()-1);
+
+            if (IsUsed(idx))
+            {
+                x--;
+                continue;
+            }
+
+            SetUsed(idx);
+            SetBinContent(idx+1, i);
+            fBinEntries[idx+1] = 1;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Star an editor to make your own game.
+//
+void MagicJam::StartEditor() const
+{
+    TCanvas *c=new TCanvas;
+
+    c->SetName("Editor");
+    c->SetTitle("MagicJam Editor");
+
+    MagicJamEditor *build=new MagicJamEditor;
+
+    build->SetBit(kCanDelete);
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the current game in the editor.
+//
+void MagicJam::OpenInEditor() const
+{
+    TCanvas *c=new TCanvas;
+
+    c->SetName("Editor");
+    c->SetTitle("MagicJam Editor");
+
+    MagicJamEditor *build=new MagicJamEditor(GetName());
+
+    build->SetBit(kCanDelete);
+}
+
+// --------------------------------------------------------------------------
+//
+// Show the Jam games of this directory
+//
+void  MagicJam::ShowDirectory(const char *dir)
+{
+    MDirIter Next(dir, "*.jam");
+
+    TList list;
+
+    TString file;
+    while (1)
+    {
+        file=Next();
+        if (file.IsNull())
+            break;
+
+        MagicJam *jam = new MagicJam(file, this);
+        if (jam->GetNumPixels()==0)
+        {
+            delete jam;
+            continue;
+        }
+        list.Add(jam);
+    }
+
+    const Int_t n1 = TMath::Nint(TMath::Ceil(list.GetEntries()/3.));
+    const Int_t n2 = TMath::Nint(TMath::Ceil((float)list.GetEntries()/n1));
+
+    TCanvas *c = new TCanvas;
+    c->SetBorderMode(0);
+    c->SetFillColor(kWhite);
+    c->Divide(n1, n2, 0, 0);
+    c->SetBit(kNoContextMenu);
+    c->SetBit(kCannotPick);
+
+    Int_t i=0;
+
+    TObject *o=0;
+
+    TIter NextObj(&list);
+
+    while ((o=NextObj()))
+    {
+        list.Remove(o);
+
+        c->cd(++i);
+        gPad->SetFillColor(kWhite);
+        o->SetBit(kCanDelete);
+        o->Draw();
+        gPad->SetBit(kCannotPick);
+    }
+
+    // Delete empty pads
+    for (; i<=n1*n2; i++)
+        delete c->GetPad(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Process mouse events
+//
+void MagicJam::ExecuteEvent(Int_t event, Int_t px, Int_t py)
+{
+    if (fNumPlayers==0) // We are in ShowDirectory-Mode
+    {
+        if (event!=kButton1Down)
+            return;
+
+        if (fGame)
+        {
+            // Do a simple search for the pad containing fGame
+            TIter Next(gROOT->GetListOfCanvases());
+            TCanvas *c=0;
+            while((c=(TCanvas*)Next()))
+            {
+                TVirtualPad *pad1 = c->GetPad(1);
+                if (!pad1)
+                    continue;
+
+                if (!pad1->GetListOfPrimitives()->FindObject(fGame))
+                    continue;
+
+                fGame->LoadGame(GetName());
+
+                pad1->Modified();
+                pad1->Update();
+                return;
+            }
+        }
+
+        // No pad found. Open new canvas for it
+        new TCanvas;
+        new MagicJam(GetName());
+
+        return;
+    }
+
+    if (CountPlayers()==1) // We already have a winner
+        return;
+
+    if (event==kButton1Down)
+    {
+        const Int_t idx = GetPixelIndex(px, py);
+        if (idx<0)
+            return;
+
+        if (IsUsed(idx) && TMath::Nint(GetBinContent(idx+1))!=fNumPlayer)
+        {
+            const Int_t col = gPad->GetFillColor();
+
+            gPad->SetFillColor(kRed);
+            gPad->Modified();
+            gPad->Update();
+
+            gSystem->Sleep(250);
+
+            gPad->SetFillColor(col);
+            gPad->Modified();
+            gPad->Update();
+            return;
+        }
+
+        FillPix(idx);
+
+        do
+        {
+            fNumPlayer++;
+            fNumPlayer %= fNumPlayers;
+        }
+        while (CountPlayers()>1 && CountPlayer(fNumPlayer)==0);
+
+        gPad->Modified();
+        gPad->Update();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint game pad
+//
+void MagicJam::Paint(Option_t *o)
+{
+    if (GetNumPixels()==0)
+        return;
+
+    gStyle->SetOptStat(11);
+
+    Int_t palette[50] =
+    {
+        4, 4, 4, 4, 4,  // light blue
+        3, 3, 3, 3, 3,  // light green
+        6, 6, 6, 6, 6,  // magenta
+        5, 5, 5, 5, 5,  // yellow
+        7, 7, 7, 7, 7,  // cyan
+        //8, 8, 8, 8, 8,  // dark green
+        //11, 11, 11, 11,11, // light gray
+        12, 12, 12, 12,12, // dark gray
+        1, 1, 1, 1, 1,  // black
+        46, 46, 46, 46, 46,
+        51, 51, 51, 51, 51,   // brown
+    };
+
+    gStyle->SetPalette(50, palette);
+    MHCamera::Paint(o);
+
+    TText txt;
+    txt.SetTextAlign(13);       // left/bottom
+    txt.SetTextSize(0.03);
+
+    const Double_t range = fGeomCam->GetMaxRadius();
+
+    Int_t max = 0;
+    Int_t num = 0;
+    Int_t pos = 0;
+    for (int i=0; i<fNumPlayers; i++)
+    {
+        const Int_t cnt = CountPlayer(i);
+
+        if (cnt>max)
+        {
+            max = cnt;
+            num = i;
+        }
+        if (cnt==0)
+            continue;
+
+        TString str = Form("Player #%d: %d %s", i+1, cnt, i==fNumPlayer?"<*>":"");
+
+        txt.SetTextColor(GetColor(i, fMinimum, fMaximum, kFALSE));
+        txt.PaintText(-range*0.95, range-pos*range*0.06, str);
+
+        pos++;
+    }
+
+    if (CountPlayers()==1)
+    {
+        TString str = "And the Winner... is... player #";
+        str += Form("%d (Score=%d)", num+1, max);
+        txt.SetTextColor(kRed);  // white
+        txt.SetTextAlign(22);    // centered/centered
+        txt.SetTextSize(0.05);   // white
+        txt.PaintText(0, 0, str);
+    }
+
+    if (fNumPlayers==0)
+    {
+        txt.SetTextSize(0.075);
+        txt.SetTextColor(kBlack);
+
+        txt.SetTextAlign(13); // left/top
+        txt.PaintTextNDC(0.02, 0.99, GetName());
+
+        //txt.SetTextAlign(11); // left/bottom
+        //txt.PaintTextNDC(0.01, 0.01, Form("%d", GetNumPixels()));
+        txt.PaintTextNDC(0.02, 0.91, Form("%d", GetNumPixels()));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls draw of the base class MHCamera with the necessary options
+//
+void MagicJam::Draw(Option_t *o)
+{
+    MHCamera::Draw(fNumPlayers>0 ? "pixelentries nopal" : "nopal");
+    gPad->SetBit(kCannotPick);
+}
Index: branches/Mars_McMismatchStudy/mtools/MagicJam.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicJam.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicJam.h	(revision 17960)
@@ -0,0 +1,128 @@
+#ifndef MARS_MagicJam
+#define MARS_Magicjam
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+// --------------------------------------------------------------------
+
+class MagicJamAbc : public MHCamera
+{
+public:
+    // Remove this items from the context menu
+    void  SetLineAttributes() { }
+    void  SetFillAttributes() { }
+    void  SetMarkerAttributes() { }
+    void  SetName(const char *name) { MHCamera::SetName(name); }
+    void  SetTitle(const char *name) { MHCamera::SetTitle(name); }
+    TH1  *DrawCopy(const Option_t *o="") const { return MHCamera::DrawCopy(o); }
+    void  PrintInfo() const {  }
+    void  SetDrawOption(Option_t *option="") { MHCamera::SetDrawOption(option); }
+    Int_t Fit(const char *formula ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0) { return 0; }
+    Int_t Fit(TF1 *f1 ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0) { return 0; }
+    void  SetMaximum(Double_t maximum=-1111) { MHCamera::SetMaximum(maximum); }
+    void  SetMinimum(Double_t minimum=-1111) { MHCamera::SetMinimum(minimum); }
+    void  Add(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1) { }
+    void  Add(TF1 *h1, Double_t c1, Option_t *) { }
+    void  Add(const TH1 *h1, Double_t c1=1) { }
+    void  Divide(TF1 *f1, Double_t c1=1) { }
+    void  Divide(const TH1 *h1) { }
+    void  Divide(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option="") { }
+    void  Multiply(TF1 *h1, Double_t c1=1) { }
+    void  Multiply(const TH1 *h1) { }
+    void  Multiply(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option="") { }
+    void  Smooth(int, int, int) { }
+    void  Smooth(int, const Option_t *) { }
+    void  SetPrettyPalette() {}
+    void  SetDeepBlueSeaPalette() {}
+    void  SetInvDeepBlueSeaPalette() {}
+    void  SetFreezed(Bool_t f=kTRUE) { }
+    void  SetAbberation(Float_t f=0.0713) { }
+    void  SetAutoScale() { }
+    void  SetMinMax(Double_t min=-1111, Double_t max=-1111) { SetMinimum(min); SetMaximum(max); }
+    TH1  *ShowBackground(Int_t niter=2, Option_t *option="same") { return 0; }
+    Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05) { return 0; }
+    void  SetErrorSpread(Bool_t f=kTRUE) { }
+
+    // Make the full pad sensible for the context menu
+    Int_t DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+    ClassDef(MagicJamAbc, 0) // Helper class for MagicJam
+};
+
+// --------------------------------------------------------------------
+class TASImage;
+
+class MagicJamEditor : public MagicJamAbc
+{
+    Int_t fWidth;
+
+    TASImage *fImage;
+
+    void Move(int dx, int dy);
+    void InitGeom(int wx, int hy);
+    Int_t GetPixelIndexFlt(Float_t px, Float_t py) const;
+
+public:
+    MagicJamEditor(const char *name=0);
+    ~MagicJamEditor();
+
+    // MagicJamEditor
+    void   SetAllUsed() { MHCamera::SetAllUsed(); } //*MENU*
+    void   Reset(Option_t *o="") { MHCamera::Reset(o); } //*MENU*
+    void   Invert() { for (UInt_t i=0; i<GetNumPixels(); i++) if (IsUsed(i)) ResetUsed(i); else SetUsed(i); } //*MENU*
+    void   SetWidthHeight(Int_t dx, Int_t dy); //*MENU*
+    Bool_t ShowUnused() const { return TestBit(kNoUnused); }
+    void   DoNotDisplayUnused(Bool_t b) { b ? SetBit(kNoUnused) : ResetBit(kNoUnused); } //*TOGGLE* *GETTER=ShowUnused
+
+    void   LoadGame(const char *name="default.jam");//*MENU* *ARGS={name=>fName}
+    void   SaveGame(const char *name="default.jam"); //*MENU* *ARGS={name=>fName}
+
+    void   ShowImageAsBackground(const char *name); //*MENU*
+    void   RemoveBackgroundImage(); //*MENU*
+
+    // TObject
+    void Paint(Option_t *o);
+    void Draw(Option_t *o="");
+    void EventInfo(Int_t event, Int_t px, Int_t py, TObject *);
+    void ExecuteEvent(Int_t event, Int_t px, Int_t py);
+
+    ClassDef(MagicJamEditor, 0) // Editor for the MAGIC Jam games
+};
+
+// --------------------------------------------------------------------
+
+class MagicJam : public MagicJamAbc
+{
+private:
+    Int_t fNumPlayers;
+    Int_t fNumPlayer;
+
+    MagicJam *fGame; //!
+
+    void FillPix(Int_t idx);
+    Int_t CountPlayer(Int_t player) const;
+    Int_t CountPlayers() const;
+
+public:
+    MagicJam(const char *jam="mtools/jam/default.jam", MagicJam *game=NULL);
+
+    // MagicJam
+    void  SetNumPlayers(Byte_t n=2); //*MENU*
+    void  LoadGame(const char *name="default.jam"); //*MENU* *ARGS={name=>fName}
+    void  Reset(Option_t *o=""); //*MENU*
+    void  StartEditor() const; //*MENU*
+    void  OpenInEditor() const; //*MENU*
+    void  ShowDirectory(const char *dir="mtools/jam"); //*MENU*
+
+    // TObject
+    void  ExecuteEvent(Int_t event, Int_t px, Int_t py);
+    void  Paint(Option_t *o);
+    void  Draw(Option_t *o=0);
+    void  RecursiveRemove(TObject *obj);
+
+    ClassDef(MagicJam, 0) // MAGIC-Jam (game)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/MagicReversi.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicReversi.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicReversi.cc	(revision 17960)
@@ -0,0 +1,543 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 "MH.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;
+
+    fText->Delete();
+    fFlags->Delete();
+
+    delete fText;
+    delete fFlags;
+
+    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();
+}
+
+void MagicReversi::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  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);
+    fColors.Set(fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        TText &t = *new ((*fText)[i]) TText;
+        t.SetTextFont(122);
+        t.SetTextAlign(22);   // centered/centered
+        t.SetTextSize(0.3*pix.GetT()/fRange);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        t.SetBit(kNoContextMenu|kCannotPick);
+#endif
+
+        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();
+}
+*/
+
+void MagicReversi::Init()
+{
+    //
+    // 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();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicReversi::MagicReversi()
+    : fGeomCam(NULL), fDone(NULL)
+{
+    SetNewCamera(new MGeomCamMagic);
+
+    Init();
+}
+
+MagicReversi::MagicReversi(const MGeomCam &geom)
+    : fGeomCam(NULL), fDone(NULL)
+{
+    SetNewCamera(static_cast<MGeomCam*>(geom.Clone()));
+
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 Float_t r = fGeomCam->GetMaxRadius();
+
+    MH::SetPadRange(-r, -r, r, r*1.1);
+
+    TAttLine line;
+    TAttFill fill;
+
+    // FIXME:
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        fill.SetFillColor(fColors[i]);
+        pix.PaintPrimitive(line, fill);
+
+        //
+        // Adopt absolute sized of markers to relative range
+        //
+        Float_t r = (*fGeomCam)[i].GetT()*gPad->XtoAbsPixel(1)/325;
+        GetFlag(i)->SetMarkerSize(20.0*r/fRange);
+
+        if (pix.TestBit(kHasFlag))
+            GetFlag(i)->Paint();
+
+        GetText(i)->Paint();
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// 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)
+{
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    if (!gPad)
+        new TCanvas("MagicReversi", "Magic Reversi", 0, 0, 800, 800);
+
+    gPad->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();
+}
+
+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++)
+    {
+        fColors[i] = kEmpty;
+        (*fGeomCam)[i].ResetBit(kUserBits);
+
+        GetFlag(i)->SetMarkerColor(kBlack);
+        GetText(i)->SetText(0, 0, "");
+    }
+
+    fNumUser  = 0;
+
+    for (int i=0; i<6; i++)
+        fUsrPts[i]=0;
+
+    for (int i=1; i<5*fNumUsers; i++)
+    {
+        fColors[i-1] = i%fNumUsers+kRed;
+        fUsrPts[i%fNumUsers]++;
+    }
+
+    Update();
+
+    gPad->SetFillColor(22);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    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();
+
+    gPad->SetFillColor(winner+kRed);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    ResetBit(kNoContextMenu);
+#endif
+}
+
+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=MGeomPix::kRightTop; dir<=MGeomPix::kLeftTop; dir++)
+    {
+        Int_t idx = origidx;
+        Int_t length = 0;
+
+        while (1)
+        {
+            idx = fGeomCam->GetNeighbor(idx, dir);
+            if (idx<0 || fColors[idx]==kEmpty)
+                break;
+
+            if (fColors[idx]==col)
+            {
+                if (length!=0)
+                    test[dir] = length;
+                break;
+            }
+
+            length++;
+        }
+    }
+
+    int cnt = 0;
+
+    for (int dir=MGeomPix::kRightTop; dir<=MGeomPix::kLeftTop; dir++)
+    {
+        Int_t idx = origidx;
+
+        if (test[dir])
+            cnt++;
+
+        if (flip)
+            for (int i=0; i<test[dir]; i++)
+            {
+                idx = fGeomCam->GetNeighbor(idx, dir);
+
+                fUsrPts[fColors[idx]-kRed]--;
+                fUsrPts[fNumUser]++;
+
+                fColors[idx] = col;
+            }
+    }
+
+    return cnt ? kTRUE : kFALSE;
+}
+
+Bool_t MagicReversi::CheckMoves()
+{
+    for (unsigned int i=0; i<fNumPixels; i++)
+        if (fColors[i]==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();
+        gPad->Modified();
+        gPad->Update();
+        return;
+    }
+
+    UInt_t idx;
+    for (idx=0; idx<fNumPixels; idx++)
+        if ((*fGeomCam)[idx].DistancetoPrimitive(px, py)<=0)
+            break;
+
+    if (idx==fNumPixels)
+        return;
+
+    if (event==kButton1Down && fColors[idx]==kEmpty)
+    {
+        if (!Flip(idx, kTRUE))
+            return;
+
+        fUsrPts[fNumUser]++;
+
+        fColors[idx] = 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();
+    }
+
+    gPad->Modified();
+}
Index: branches/Mars_McMismatchStudy/mtools/MagicReversi.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicReversi.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicReversi.h	(revision 17960)
@@ -0,0 +1,83 @@
+#ifndef MARS_MagicReversi
+#define MARS_MagicReversi
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class TText;
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class MagicReversi : public TObject
+{
+private:
+    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  *fText;          // array of all texts
+    TClonesArray  *fFlags;         // array of all texts
+
+    TArrayI fColors;
+
+    TText         *fDone;          // TText showing the 'Game over'
+    TText         *fUsrTxt[6];     // TText showing the numbers of pixels and bombs
+
+    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
+    };
+
+    TText   *GetText(Int_t i) { return (TText*)fText->At(i); }
+    TMarker *GetFlag(Int_t i) { return (TMarker*)fFlags->At(i); }
+
+    void  Done();
+    void  Update();
+    void  SetNewCamera(MGeomCam *);
+    void  Free();
+    void  Init();
+
+    Bool_t Flip(Int_t idx, Bool_t flip);
+    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(const MGeomCam &geom);
+    ~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: branches/Mars_McMismatchStudy/mtools/MagicShow.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicShow.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicShow.cc	(revision 17960)
@@ -0,0 +1,380 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): 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 "MH.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;
+
+    delete fGeomCam;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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;
+
+    Update();
+
+    fColors.Reset();
+
+    // FIXME: Reset all texts
+
+    AppendPad();
+}
+
+// ------------------------------------------------------------------------
+//
+// Reset/set all veriables needed for a new camera geometry
+//
+void MagicShow::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    fNumPixel  = 0;//fNumPixels-1;
+
+    fColors.Set(fNumPixels);
+
+    for (int i=0; i<6; i++)
+    {
+        fText[i] = new TText(0, 0, "");
+        fText[i]->SetTextFont(122);
+        fText[i]->SetTextAlign(22);   // centered/centered
+    }
+
+}
+
+void MagicShow::Init()
+{
+    //
+    // 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();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicShow::MagicShow()
+    : fTimer(this, 250, kTRUE), fGeomCam(NULL), fNumPixel(-1), fAuto(kTRUE)
+{
+    SetNewCamera(new MGeomCamMagic);
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicShow::MagicShow(const MGeomCam &geom)
+    : fTimer(this, 250, kTRUE), fGeomCam(NULL), fNumPixel(-1), fAuto(kTRUE)
+{
+    SetNewCamera(static_cast<MGeomCam*>(geom.Clone()));
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MagicShow::~MagicShow()
+{
+    Free();
+
+    for (int i=0; i<6; i++)
+        delete fText[i];
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 Float_t r = fGeomCam->GetMaxRadius();
+
+    MH::SetPadRange(-r, -r, r, r*1.1);
+
+    TAttLine line;
+    TAttFill fill;
+
+    // FIXME:
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        fill.SetFillColor(fColors[i]);
+        pix.PaintPrimitive(line, fill);
+    }
+
+    for (int i=0; i<6; i++)
+        fText[i]->Paint();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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
+    //
+    new TCanvas("MagicShow", "Magic Show Next Neighbours", 0, 0, 800, 800);
+
+    gPad->SetBorderMode(0);
+    gPad->SetFillColor(22);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    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();
+        gPad->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)
+{
+    const MGeom &pix1=(*fGeomCam)[fNumPixel];
+
+    fColors[fNumPixel] = kBackground;
+    for (int i=0; i<pix1.GetNumNeighbors(); i++)
+    {
+        fColors[pix1.GetNeighbor(i)] = kBackground;
+        if (TString(fText[i]->GetTitle()).IsNull())
+            continue;
+
+        fText[i]->SetText(0, 0, "");
+    }
+
+    fNumPixel += add;
+
+    if (fNumPixel>=fNumPixels)
+        fNumPixel = 0;
+    if (fNumPixel<0)
+        fNumPixel = fNumPixels-1;
+
+    const MGeom &pix2=(*fGeomCam)[fNumPixel];
+
+    fColors[fNumPixel] = kBlue;
+
+    for (int i=0; i<pix2.GetNumNeighbors(); i++)
+    {
+        Int_t idx = pix2.GetNeighbor(i);
+
+        fColors[idx] = kMagenta;
+
+        TString num;
+        num += idx;
+
+        const MGeom &pix=(*fGeomCam)[idx];
+
+        fText[i]->SetText(pix.GetX(), pix.GetY(), num);
+        fText[i]->SetTextSize(0.3*pix.GetT()/fGeomCam->GetMaxRadius());
+    }
+
+    Update();
+
+    gPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// If automatic is switched on step one pixel forward
+//
+Bool_t MagicShow::HandleTimer(TTimer *timer)
+{
+    if (fAuto)
+        ChangePixel(+1);
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mtools/MagicShow.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicShow.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicShow.h	(revision 17960)
@@ -0,0 +1,74 @@
+#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
+#ifndef ROOT_TArrayI
+#include <TArrayI.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
+
+    TArrayI fColors;
+
+    void   Update();
+    void   Free();
+    void   SetNewCamera(MGeomCam *);
+    void   ChangePixel(Int_t add);
+    void   Init();
+
+    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(const MGeomCam &geom);
+    ~MagicShow();
+
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MagicShow, 0) // Tool to visualize next neighbours
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/MagicSnake.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicSnake.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicSnake.cc	(revision 17960)
@@ -0,0 +1,582 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 "MH.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicSnake);
+
+using namespace std;
+
+void MagicSnake::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    delete fGeomCam;
+
+    delete fArray;
+}
+
+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();
+    AppendPad();
+}
+
+void MagicSnake::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    fColors.Set(fNumPixels);
+}
+
+void MagicSnake::Init()
+{
+    //
+    // 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();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicSnake::MagicSnake()
+    : fTimer(this, 500, kTRUE), fGeomCam(NULL), fDone(NULL), fPaused(NULL)
+{
+    SetNewCamera(new MGeomCamMagic);
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicSnake::MagicSnake(const MGeomCam &geom)
+    : fTimer(this, 500, kTRUE), fGeomCam(NULL), fDone(NULL), fPaused(NULL)
+{
+    SetNewCamera(static_cast<MGeomCam*>(geom.Clone()));
+    Init();
+}
+
+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);
+        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;
+
+    //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 Float_t r = fGeomCam->GetMaxRadius();
+
+    MH::SetPadRange(-r, -r, r, r*1.1);
+
+    TAttLine line;
+    TAttFill fill;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        fill.SetFillColor(fColors[i]);
+        pix.PaintPrimitive(line, fill);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// 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
+    //
+    new TCanvas("MagicSnake", "Magic Snake", 0, 0, 800, 800);
+
+    //fDrawingPad = gPad;
+    gPad->SetBorderMode(0);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Reset the game pad
+    //
+    Reset();
+
+    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++)
+    {
+        fColors[i] = 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);
+        fColors[idx] = kRed;
+    }
+
+    fNumFood = fNumPixels/6;
+    // FIXME. gROOT->GetColor doesn't allow more than 100 colors!
+    if (fNumFood>46)
+        fNumFood=46;
+
+    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);
+        fColors[idx] = 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);
+        fColors[idx] = kYellow;
+    }
+
+    gPad->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();
+    gPad->SetFillColor(col);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDone->SetBit(kNoContextMenu|kCannotPick);
+    ResetBit(kNoContextMenu);
+#endif
+}
+
+// ------------------------------------------------------------------------
+//
+// 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))
+    {
+        fColors[fArray[0]] = 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))
+    {
+        MGeom &pix = (*fGeomCam)[fArray[0]];
+
+        if (!pix.TestBit(kHasTransport))
+        {
+            if (pix.TestBit(kHasDoor))
+                fColors[fArray[0]] = kMagenta;
+            else
+                fColors[fArray[0]] = 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++)
+            {
+                fColors[i] = kMagenta;
+                (*fGeomCam)[i].SetBit(kHasDoor);
+            }
+    }
+
+    SetWormColor();
+}
+
+void MagicSnake::SetWormColor()
+{
+    for (int i=0; i<fLength; i++)
+    {
+        const Int_t idx = fArray[i];
+
+        MGeom &pix = (*fGeomCam)[idx];
+
+        if (pix.TestBit(kHasTransport))
+            continue;
+
+        pix.SetBit(kHasWorm);
+
+        fColors[idx] = 51+fLength-i;
+    }
+}
+
+Int_t MagicSnake::ScanNeighbours()
+{
+    const Int_t first = fArray[fLength-1];
+
+    const MGeom &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 MGeom &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 MGeom &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();
+
+    gPad->Modified();
+    gPad->Update();
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mtools/MagicSnake.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MagicSnake.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MagicSnake.h	(revision 17960)
@@ -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
+#ifndef ROOT_TArrayI
+#include <TArrayI.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
+
+    TArrayI fColors;
+
+    TText    *fDone;            // TText showing the 'Game over'
+    TText    *fPaused;          // TText showing the 'Game over'
+    TText     fShow;            // TText showing the numbers of pixels and bombs
+
+    TVirtualPad   *fDrawingPad; // pad in which we are drawing
+
+    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);
+    void   Init();
+
+    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(const MGeomCam &geom);
+    ~MagicSnake();
+
+    void Reset();        //*MENU*
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MagicSnake, 0) // Magic Camera Games: Snake
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mtools/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/Makefile	(revision 17960)
@@ -0,0 +1,47 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Tools
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mdata -I../mhbase \
+	   -I../mfileio -I../mfbase -I../manalysis -I../mhist
+
+#manalysis: MChisqEval (MParameters)
+
+SRCFILES = MChisqEval.cc \
+	   MTFillMatrix.cc \
+	   MHSimulatedAnnealing.cc \
+	   MSimulatedAnnealing.cc \
+	   MFFT.cc \
+           MCubicCoeff.cc \
+           MCubicSpline.cc \
+	   MagicReversi.cc \
+	   MagicSnake.cc \
+           MagicShow.cc \
+           MagicDomino.cc \
+           MagicCivilization.cc \
+           MineSweeper.cc \
+	   MRolke.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mtools/MineSweeper.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MineSweeper.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MineSweeper.cc	(revision 17960)
@@ -0,0 +1,463 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of CheObs, the Modular Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appears in all copies and
+! * that both that 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/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: CheObs Software Development, 2000-2009
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 "MH.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;
+
+    fText->Delete();
+    fFlags->Delete();
+
+    delete fText;
+    delete fFlags;
+
+    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();
+    AppendPad();
+}
+
+void MineSweeper::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  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);
+    fColors.Set(fNumPixels);
+    //fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        TText &t = *new ((*fText)[i]) TText;
+        t.SetTextFont(122);
+        t.SetTextAlign(22);   // centered/centered
+        t.SetTextSize(0.3*pix.GetT()/fRange);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        t.SetBit(kNoContextMenu|kCannotPick);
+#endif
+
+        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
+    }
+}
+
+void MineSweeper::Init()
+{
+    //
+    // 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();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MineSweeper::MineSweeper()
+    : fGeomCam(NULL), fDone(NULL), fShow(NULL)
+{
+    SetNewCamera(new MGeomCamMagic);
+    Init();
+}
+
+MineSweeper::MineSweeper(const MGeomCam &geom)
+    : fGeomCam(NULL), fDone(NULL), fShow(NULL)
+{
+    SetNewCamera(static_cast<MGeomCam*>(geom.Clone()));
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MineSweeper::~MineSweeper()
+{
+    Free();
+
+    delete fShow;
+
+    if (fDone)
+        delete fDone;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 Float_t r = fGeomCam->GetMaxRadius();
+
+    MH::SetPadRange(-r, -r, r, r*1.1);
+
+    TAttLine line;
+    TAttFill fill;
+
+    // FIXME:
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeom &pix = (*fGeomCam)[i];
+
+        fill.SetFillColor(fColors[i]);
+        pix.PaintPrimitive(line, fill);
+
+        //
+        // Adopt absolute sized of markers to relative range
+        //
+        Float_t r = (*fGeomCam)[i].GetT()*gPad->XtoAbsPixel(1)/325;
+        GetFlag(i)->SetMarkerSize(20.0*r/fRange);
+
+        if (pix.TestBit(kHasFlag))
+            GetFlag(i)->Paint();
+
+        GetText(i)->Paint();
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 no canvas is yet existing to draw into, create a new one
+    //
+    if (!gPad)
+        new TCanvas("MineSweeper", "Magic Mine Sweeper", 0, 0, 800, 800);
+
+    gPad->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();
+}
+
+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++)
+    {
+        fColors[i] = kHidden;
+        (*fGeomCam)[i].ResetBit(kUserBits);
+
+        GetFlag(i)->SetMarkerColor(kBlack);
+        GetText(i)->SetText(0, 0, "");
+    }
+    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);
+    }
+
+    gPad->SetFillColor(22);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    gPad->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))
+        {
+            fColors[j] = 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();
+
+    gPad->SetFillColor(col);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    gPad->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)
+{
+    MGeom &pix=(*fGeomCam)[idx];
+
+    if (pix.TestBit(kIsVisible))
+        return;
+
+    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++;
+
+    fColors[idx] = fColorBombs[cnt];
+
+    TString str;
+    if (cnt)
+        str += cnt;
+
+    TText *txt = GetText(idx);
+    txt->SetText(pix.GetX(), pix.GetY(), str);
+
+    if (cnt)
+        return;
+
+    for (int j=0; j<pix.GetNumNeighbors(); j++)
+        OpenHexagon(pix.GetNeighbor(j));
+}
+
+// ------------------------------------------------------------------------
+//
+// 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 ((*fGeomCam)[idx].DistancetoPrimitive(px, py)<=0)
+            break;
+
+    if (idx==fNumPixels)
+        return;
+
+    MGeom &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))
+        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);
+
+    gPad->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: branches/Mars_McMismatchStudy/mtools/MineSweeper.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/MineSweeper.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/MineSweeper.h	(revision 17960)
@@ -0,0 +1,77 @@
+#ifndef MARS_MineSweeper
+#define MARS_MineSweeper
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class TText;
+class TMarker;
+class TVirtualPad;
+
+class MGeom;
+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  *fText;          // array of all texts
+    TClonesArray  *fFlags;         // array of all texts
+
+    TArrayI fColors;
+
+    TText         *fDone;          // TText showing the 'Game over'
+    TText         *fShow;          // TText showing the numbers of pixels and bombs
+
+    enum
+    {
+        kHidden    = 50,
+        kIsVisible = BIT(16),
+        kHasBomb   = BIT(17),
+        kHasFlag   = BIT(18),
+        kUserBits  = 0x7fc000 // 14-23 are allowed
+    };
+
+    TText   *GetText(Int_t i) { return (TText*)fText->At(i); }
+    TMarker *GetFlag(Int_t i) { return (TMarker*)fFlags->At(i); }
+
+    void  OpenHexagon(Int_t idx);
+    void  Done(TString, Int_t);
+    void  Update(Int_t);
+    void  SetNewCamera(MGeomCam *);
+    void  PaintPrimitives();
+    void  Free();
+    void  Init();
+
+    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(const MGeomCam &geom);
+    ~MineSweeper();
+
+    void Reset();        //*MENU*
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MineSweeper, 0) // Magic Camera Games: Mine Sweeper
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/ToolsIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/ToolsIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/ToolsIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mtools/ToolsLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mtools/ToolsLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/ToolsLinkDef.h	(revision 17960)
@@ -0,0 +1,28 @@
+#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 MagicJamAbc+;
+//#pragma link C++ class MagicJam+;
+//#pragma link C++ class MagicJamEditor+;
+#pragma link C++ class MagicDomino+;
+#pragma link C++ class MagicCivilization+;
+
+#pragma link C++ class MRolke+;
+
+#endif
Index: branches/Mars_McMismatchStudy/mtools/jam/bike.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/bike.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/bike.jam	(revision 17960)
@@ -0,0 +1,443 @@
+8 14
+9 14
+10 14
+11 14
+12 14
+13 14
+36 14
+37 14
+38 14
+39 14
+40 14
+7 15
+8 15
+9 15
+10 15
+11 15
+12 15
+13 15
+14 15
+15 15
+35 15
+36 15
+37 15
+38 15
+39 15
+40 15
+41 15
+42 15
+5 16
+6 16
+7 16
+11 16
+12 16
+14 16
+15 16
+16 16
+34 16
+35 16
+41 16
+42 16
+43 16
+5 17
+6 17
+11 17
+12 17
+16 17
+17 17
+33 17
+34 17
+35 17
+43 17
+44 17
+45 17
+4 18
+5 18
+11 18
+16 18
+17 18
+23 18
+24 18
+25 18
+32 18
+33 18
+34 18
+35 18
+44 18
+45 18
+4 19
+5 19
+11 19
+12 19
+17 19
+18 19
+25 19
+32 19
+33 19
+35 19
+36 19
+45 19
+46 19
+3 20
+4 20
+10 20
+11 20
+17 20
+18 20
+25 20
+31 20
+32 20
+36 20
+43 20
+44 20
+45 20
+46 20
+3 21
+4 21
+10 21
+11 21
+12 21
+18 21
+19 21
+26 21
+28 21
+29 21
+32 21
+37 21
+38 21
+39 21
+40 21
+42 21
+43 21
+44 21
+45 21
+46 21
+47 21
+3 22
+4 22
+9 22
+10 22
+11 22
+12 22
+18 22
+25 22
+26 22
+28 22
+29 22
+31 22
+32 22
+37 22
+38 22
+39 22
+40 22
+41 22
+42 22
+43 22
+46 22
+3 23
+4 23
+9 23
+10 23
+11 23
+12 23
+13 23
+18 23
+19 23
+25 23
+27 23
+29 23
+32 23
+38 23
+39 23
+40 23
+41 23
+42 23
+46 23
+47 23
+3 24
+4 24
+7 24
+8 24
+9 24
+10 24
+11 24
+12 24
+13 24
+18 24
+24 24
+25 24
+28 24
+31 24
+32 24
+36 24
+37 24
+38 24
+39 24
+40 24
+45 24
+46 24
+4 25
+5 25
+6 25
+7 25
+11 25
+12 25
+14 25
+15 25
+17 25
+18 25
+24 25
+25 25
+26 25
+27 25
+28 25
+32 25
+34 25
+35 25
+36 25
+37 25
+38 25
+39 25
+40 25
+46 25
+3 26
+4 26
+5 26
+11 26
+14 26
+15 26
+16 26
+17 26
+23 26
+24 26
+25 26
+26 26
+27 26
+31 26
+32 26
+33 26
+34 26
+35 26
+38 26
+39 26
+45 26
+46 26
+4 27
+5 27
+12 27
+16 27
+17 27
+22 27
+23 27
+24 27
+25 27
+26 27
+27 27
+28 27
+30 27
+31 27
+32 27
+33 27
+34 27
+35 27
+38 27
+39 27
+45 27
+46 27
+4 28
+5 28
+6 28
+11 28
+12 28
+15 28
+16 28
+21 28
+22 28
+23 28
+24 28
+25 28
+26 28
+27 28
+28 28
+29 28
+30 28
+31 28
+32 28
+33 28
+34 28
+38 28
+39 28
+44 28
+45 28
+6 29
+7 29
+12 29
+13 29
+15 29
+16 29
+21 29
+22 29
+24 29
+25 29
+27 29
+28 29
+29 29
+30 29
+31 29
+32 29
+34 29
+35 29
+38 29
+39 29
+44 29
+45 29
+6 30
+7 30
+8 30
+9 30
+10 30
+11 30
+12 30
+13 30
+14 30
+20 30
+21 30
+24 30
+25 30
+27 30
+28 30
+29 30
+30 30
+34 30
+35 30
+36 30
+37 30
+38 30
+39 30
+42 30
+43 30
+8 31
+9 31
+10 31
+11 31
+12 31
+13 31
+20 31
+21 31
+25 31
+26 31
+36 31
+37 31
+38 31
+39 31
+40 31
+41 31
+42 31
+43 31
+12 32
+13 32
+18 32
+19 32
+20 32
+25 32
+26 32
+27 32
+38 32
+39 32
+40 32
+12 33
+13 33
+14 33
+15 33
+16 33
+18 33
+19 33
+20 33
+23 33
+24 33
+25 33
+26 33
+27 33
+28 33
+12 34
+13 34
+14 34
+15 34
+16 34
+17 34
+18 34
+21 34
+22 34
+23 34
+24 34
+25 34
+26 34
+27 34
+28 34
+29 34
+30 34
+13 35
+16 35
+17 35
+18 35
+19 35
+20 35
+21 35
+22 35
+28 35
+29 35
+30 35
+31 35
+12 36
+13 36
+16 36
+17 36
+18 36
+19 36
+29 36
+30 36
+13 37
+14 37
+17 37
+30 37
+31 37
+13 38
+14 38
+15 38
+16 38
+17 38
+31 38
+13 39
+14 39
+15 39
+16 39
+17 39
+32 39
+16 40
+17 40
+31 40
+16 41
+17 41
+32 41
+13 42
+14 42
+15 42
+30 42
+31 42
+32 42
+33 42
+11 43
+12 43
+13 43
+14 43
+30 43
+31 43
+32 43
+33 43
+34 43
+35 43
+10 44
+11 44
+12 44
+35 44
+11 45
Index: branches/Mars_McMismatchStudy/mtools/jam/car.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/car.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/car.jam	(revision 17960)
@@ -0,0 +1,86 @@
+4 1
+5 1
+15 1
+16 1
+3 2
+4 2
+5 2
+14 2
+15 2
+16 2
+0 3
+1 3
+2 3
+3 3
+6 3
+7 3
+8 3
+9 3
+10 3
+11 3
+12 3
+13 3
+14 3
+17 3
+18 3
+19 3
+0 4
+1 4
+2 4
+3 4
+4 4
+5 4
+6 4
+7 4
+8 4
+9 4
+10 4
+11 4
+12 4
+13 4
+14 4
+15 4
+16 4
+17 4
+18 4
+1 5
+2 5
+3 5
+4 5
+5 5
+9 5
+10 5
+14 5
+15 5
+16 5
+17 5
+18 5
+4 6
+8 6
+9 6
+13 6
+14 6
+15 6
+5 7
+6 7
+9 7
+10 7
+14 7
+15 7
+6 8
+7 8
+8 8
+9 8
+10 8
+11 8
+12 8
+13 8
+14 8
+8 9
+9 9
+10 9
+11 9
+12 9
+13 9
+12 10
+13 11
Index: branches/Mars_McMismatchStudy/mtools/jam/crown.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/crown.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/crown.jam	(revision 17960)
@@ -0,0 +1,180 @@
+9 16
+10 16
+11 16
+12 16
+13 16
+14 16
+15 16
+16 16
+17 16
+18 16
+19 16
+20 16
+21 16
+22 16
+23 16
+24 16
+25 16
+26 16
+27 16
+28 16
+29 16
+10 17
+11 17
+12 17
+13 17
+14 17
+15 17
+16 17
+17 17
+18 17
+19 17
+20 17
+21 17
+22 17
+23 17
+24 17
+25 17
+26 17
+27 17
+28 17
+29 17
+9 18
+10 18
+11 18
+12 18
+14 18
+15 18
+16 18
+17 18
+18 18
+20 18
+21 18
+22 18
+23 18
+24 18
+26 18
+27 18
+28 18
+29 18
+10 19
+11 19
+12 19
+13 19
+14 19
+15 19
+16 19
+17 19
+18 19
+21 19
+22 19
+23 19
+24 19
+25 19
+26 19
+27 19
+28 19
+29 19
+9 20
+10 20
+11 20
+12 20
+14 20
+15 20
+16 20
+17 20
+18 20
+20 20
+21 20
+22 20
+23 20
+24 20
+26 20
+27 20
+28 20
+29 20
+10 21
+12 21
+13 21
+14 21
+15 21
+16 21
+17 21
+18 21
+19 21
+20 21
+21 21
+22 21
+23 21
+24 21
+25 21
+26 21
+27 21
+29 21
+9 22
+10 22
+12 22
+13 22
+14 22
+16 22
+18 22
+19 22
+20 22
+22 22
+24 22
+25 22
+26 22
+28 22
+29 22
+10 23
+13 23
+14 23
+16 23
+17 23
+19 23
+20 23
+22 23
+23 23
+25 23
+26 23
+29 23
+13 24
+16 24
+19 24
+22 24
+25 24
+13 25
+14 25
+19 25
+20 25
+25 25
+26 25
+13 26
+19 26
+25 26
+13 27
+14 27
+19 27
+20 27
+25 27
+26 27
+12 28
+14 28
+18 28
+19 28
+20 28
+24 28
+26 28
+13 29
+14 29
+18 29
+19 29
+20 29
+21 29
+25 29
+26 29
+18 30
+19 30
+20 30
+19 31
+20 31
Index: branches/Mars_McMismatchStudy/mtools/jam/default.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/default.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/default.jam	(revision 17960)
@@ -0,0 +1,105 @@
+2 0
+3 0
+4 0
+2 1
+5 1
+1 2
+5 2
+2 3
+6 3
+0 4
+1 4
+2 4
+3 4
+4 4
+5 4
+6 4
+7 4
+8 4
+9 4
+10 4
+11 4
+12 4
+13 4
+14 4
+15 4
+16 4
+17 4
+18 4
+19 4
+3 5
+6 5
+1 6
+2 6
+3 6
+4 6
+5 6
+6 6
+7 6
+8 6
+9 6
+10 6
+11 6
+12 6
+13 6
+14 6
+15 6
+16 6
+17 6
+18 6
+19 6
+20 6
+4 7
+6 7
+4 8
+5 8
+6 8
+9 8
+10 8
+11 8
+12 8
+13 8
+16 8
+18 8
+5 9
+6 9
+9 9
+12 9
+14 9
+16 9
+17 9
+19 9
+5 10
+6 10
+7 10
+8 10
+12 10
+14 10
+16 10
+18 10
+6 11
+8 11
+9 11
+12 11
+14 11
+16 11
+17 11
+19 11
+6 12
+9 12
+10 12
+11 12
+12 12
+14 12
+15 12
+17 12
+18 12
+1 13
+6 13
+1 14
+2 14
+3 14
+6 14
+4 15
+5 15
+6 15
Index: branches/Mars_McMismatchStudy/mtools/jam/earth.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/earth.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/earth.jam	(revision 17960)
@@ -0,0 +1,498 @@
+16 0
+17 0
+17 1
+18 1
+57 1
+16 2
+17 2
+18 2
+19 2
+55 2
+56 2
+57 2
+17 3
+18 3
+19 3
+20 3
+21 3
+34 3
+35 3
+51 3
+52 3
+53 3
+54 3
+55 3
+56 3
+57 3
+58 3
+17 4
+18 4
+19 4
+20 4
+21 4
+33 4
+34 4
+35 4
+38 4
+51 4
+52 4
+53 4
+54 4
+55 4
+56 4
+57 4
+17 5
+18 5
+19 5
+20 5
+21 5
+22 5
+33 5
+34 5
+35 5
+36 5
+38 5
+39 5
+52 5
+53 5
+54 5
+55 5
+56 5
+57 5
+16 6
+17 6
+18 6
+19 6
+20 6
+21 6
+22 6
+32 6
+33 6
+34 6
+35 6
+36 6
+37 6
+38 6
+52 6
+53 6
+54 6
+55 6
+56 6
+16 7
+17 7
+18 7
+19 7
+20 7
+21 7
+22 7
+23 7
+33 7
+34 7
+35 7
+36 7
+37 7
+54 7
+55 7
+57 7
+58 7
+15 8
+16 8
+17 8
+18 8
+19 8
+20 8
+21 8
+22 8
+23 8
+32 8
+33 8
+34 8
+35 8
+36 8
+49 8
+50 8
+51 8
+52 8
+53 8
+55 8
+56 8
+57 8
+16 9
+17 9
+18 9
+19 9
+20 9
+21 9
+22 9
+32 9
+33 9
+34 9
+35 9
+36 9
+37 9
+49 9
+51 9
+54 9
+55 9
+15 10
+16 10
+17 10
+18 10
+19 10
+20 10
+32 10
+33 10
+34 10
+35 10
+36 10
+37 10
+38 10
+48 10
+50 10
+51 10
+15 11
+16 11
+17 11
+18 11
+19 11
+28 11
+29 11
+30 11
+31 11
+32 11
+33 11
+34 11
+35 11
+36 11
+37 11
+38 11
+39 11
+45 11
+48 11
+51 11
+52 11
+53 11
+14 12
+15 12
+16 12
+17 12
+27 12
+28 12
+29 12
+30 12
+31 12
+32 12
+33 12
+34 12
+35 12
+36 12
+37 12
+38 12
+44 12
+48 12
+49 12
+52 12
+12 13
+13 13
+14 13
+27 13
+28 13
+29 13
+30 13
+31 13
+32 13
+33 13
+34 13
+35 13
+36 13
+37 13
+39 13
+40 13
+44 13
+45 13
+47 13
+48 13
+49 13
+52 13
+10 14
+11 14
+13 14
+15 14
+16 14
+17 14
+27 14
+28 14
+29 14
+30 14
+31 14
+32 14
+33 14
+34 14
+35 14
+36 14
+38 14
+39 14
+40 14
+43 14
+44 14
+45 14
+46 14
+47 14
+48 14
+49 14
+50 14
+9 15
+10 15
+11 15
+12 15
+16 15
+28 15
+29 15
+30 15
+31 15
+32 15
+33 15
+34 15
+35 15
+36 15
+37 15
+38 15
+39 15
+41 15
+42 15
+43 15
+44 15
+45 15
+46 15
+47 15
+48 15
+49 15
+50 15
+51 15
+52 15
+8 16
+9 16
+10 16
+11 16
+12 16
+13 16
+14 16
+15 16
+28 16
+29 16
+30 16
+31 16
+32 16
+33 16
+37 16
+38 16
+39 16
+40 16
+41 16
+42 16
+43 16
+44 16
+45 16
+46 16
+47 16
+48 16
+49 16
+50 16
+51 16
+54 16
+8 17
+9 17
+10 17
+11 17
+12 17
+13 17
+14 17
+15 17
+16 17
+29 17
+36 17
+37 17
+38 17
+39 17
+40 17
+41 17
+42 17
+43 17
+44 17
+45 17
+46 17
+47 17
+48 17
+49 17
+50 17
+51 17
+52 17
+53 17
+54 17
+55 17
+56 17
+7 18
+8 18
+9 18
+10 18
+11 18
+12 18
+13 18
+14 18
+15 18
+16 18
+17 18
+29 18
+30 18
+31 18
+33 18
+34 18
+37 18
+38 18
+39 18
+40 18
+41 18
+42 18
+43 18
+44 18
+45 18
+46 18
+47 18
+48 18
+49 18
+50 18
+51 18
+52 18
+53 18
+55 18
+56 18
+7 19
+8 19
+9 19
+10 19
+11 19
+12 19
+13 19
+14 19
+15 19
+16 19
+17 19
+18 19
+19 19
+29 19
+31 19
+32 19
+33 19
+34 19
+35 19
+36 19
+37 19
+38 19
+39 19
+40 19
+41 19
+42 19
+43 19
+44 19
+45 19
+46 19
+47 19
+48 19
+49 19
+50 19
+51 19
+52 19
+53 19
+54 19
+55 19
+5 20
+6 20
+7 20
+8 20
+9 20
+10 20
+11 20
+12 20
+13 20
+16 20
+17 20
+18 20
+21 20
+32 20
+35 20
+36 20
+37 20
+38 20
+39 20
+40 20
+41 20
+42 20
+43 20
+44 20
+45 20
+46 20
+47 20
+48 20
+49 20
+50 20
+51 20
+52 20
+53 20
+54 20
+55 20
+56 20
+57 20
+5 21
+6 21
+7 21
+8 21
+9 21
+10 21
+11 21
+12 21
+13 21
+14 21
+15 21
+16 21
+17 21
+18 21
+19 21
+20 21
+21 21
+22 21
+23 21
+24 21
+25 21
+26 21
+27 21
+28 21
+29 21
+30 21
+31 21
+32 21
+33 21
+34 21
+35 21
+36 21
+37 21
+38 21
+39 21
+40 21
+41 21
+42 21
+43 21
+44 21
+45 21
+46 21
+47 21
+48 21
+49 21
+50 21
+51 21
+52 21
+53 21
+54 21
+55 21
+56 21
+57 21
+58 21
Index: branches/Mars_McMismatchStudy/mtools/jam/flydog.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/flydog.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/flydog.jam	(revision 17960)
@@ -0,0 +1,266 @@
+19 25
+20 25
+17 26
+18 26
+20 26
+17 27
+20 27
+16 28
+18 28
+19 28
+16 29
+19 29
+20 29
+21 29
+22 29
+23 29
+14 30
+15 30
+21 30
+23 30
+9 31
+10 31
+11 31
+12 31
+13 31
+14 31
+22 31
+23 31
+6 32
+7 32
+8 32
+12 32
+14 32
+15 32
+16 32
+17 32
+18 32
+19 32
+23 32
+24 32
+25 32
+26 32
+9 33
+10 33
+11 33
+12 33
+20 33
+21 33
+27 33
+5 34
+6 34
+7 34
+11 34
+21 34
+22 34
+27 34
+28 34
+29 34
+30 34
+5 35
+8 35
+9 35
+10 35
+11 35
+21 35
+23 35
+31 35
+32 35
+33 35
+34 35
+35 35
+36 35
+37 35
+38 35
+39 35
+40 35
+41 35
+42 35
+43 35
+44 35
+45 35
+46 35
+47 35
+5 36
+6 36
+11 36
+12 36
+13 36
+14 36
+15 36
+21 36
+23 36
+32 36
+47 36
+5 37
+7 37
+8 37
+15 37
+22 37
+24 37
+25 37
+32 37
+34 37
+35 37
+36 37
+37 37
+38 37
+39 37
+40 37
+41 37
+42 37
+43 37
+44 37
+45 37
+46 37
+47 37
+4 38
+8 38
+9 38
+10 38
+11 38
+12 38
+13 38
+14 38
+15 38
+16 38
+17 38
+18 38
+19 38
+20 38
+21 38
+22 38
+23 38
+24 38
+25 38
+26 38
+27 38
+28 38
+29 38
+30 38
+31 38
+33 38
+35 38
+4 39
+21 39
+22 39
+33 39
+36 39
+37 39
+38 39
+39 39
+40 39
+41 39
+42 39
+43 39
+44 39
+2 40
+3 40
+4 40
+5 40
+6 40
+7 40
+8 40
+9 40
+10 40
+19 40
+20 40
+23 40
+24 40
+25 40
+26 40
+27 40
+28 40
+29 40
+30 40
+31 40
+32 40
+39 40
+40 40
+41 40
+42 40
+43 40
+44 40
+45 40
+2 41
+11 41
+12 41
+13 41
+14 41
+15 41
+16 41
+17 41
+18 41
+19 41
+20 41
+21 41
+22 41
+23 41
+25 41
+26 41
+33 41
+45 41
+2 42
+17 42
+18 42
+19 42
+20 42
+21 42
+22 42
+23 42
+24 42
+28 42
+29 42
+30 42
+31 42
+32 42
+33 42
+41 42
+42 42
+43 42
+44 42
+3 43
+4 43
+5 43
+6 43
+7 43
+8 43
+9 43
+10 43
+11 43
+12 43
+13 43
+14 43
+15 43
+16 43
+17 43
+28 43
+34 43
+37 43
+38 43
+39 43
+40 43
+41 43
+27 44
+34 44
+36 44
+39 44
+27 45
+29 45
+30 45
+31 45
+32 45
+33 45
+37 45
+38 45
+39 45
+26 46
+27 46
+28 46
+33 46
+34 46
+38 46
+35 47
+36 47
+37 47
+38 47
Index: branches/Mars_McMismatchStudy/mtools/jam/heart.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/heart.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/heart.jam	(revision 17960)
@@ -0,0 +1,164 @@
+8 1
+7 2
+8 2
+7 3
+8 3
+9 3
+5 4
+6 4
+8 4
+9 4
+10 4
+6 5
+8 5
+9 5
+10 5
+4 6
+5 6
+8 6
+9 6
+10 6
+11 6
+4 7
+5 7
+8 7
+9 7
+10 7
+11 7
+12 7
+3 8
+4 8
+7 8
+8 8
+9 8
+10 8
+11 8
+12 8
+3 9
+4 9
+7 9
+8 9
+9 9
+10 9
+11 9
+12 9
+13 9
+2 10
+3 10
+7 10
+8 10
+9 10
+10 10
+11 10
+12 10
+13 10
+3 11
+7 11
+8 11
+9 11
+10 11
+11 11
+12 11
+13 11
+1 12
+2 12
+6 12
+7 12
+8 12
+9 12
+10 12
+11 12
+12 12
+13 12
+14 12
+2 13
+7 13
+8 13
+9 13
+10 13
+11 13
+12 13
+13 13
+14 13
+0 14
+1 14
+6 14
+7 14
+8 14
+9 14
+10 14
+11 14
+12 14
+13 14
+14 14
+15 14
+1 15
+6 15
+7 15
+8 15
+9 15
+10 15
+11 15
+12 15
+13 15
+14 15
+15 15
+0 16
+1 16
+3 16
+6 16
+7 16
+8 16
+9 16
+10 16
+13 16
+14 16
+15 16
+1 17
+4 17
+5 17
+6 17
+7 17
+8 17
+9 17
+10 17
+14 17
+15 17
+0 18
+1 18
+5 18
+6 18
+7 18
+8 18
+9 18
+14 18
+15 18
+1 19
+2 19
+6 19
+7 19
+8 19
+9 19
+10 19
+11 19
+13 19
+14 19
+15 19
+1 20
+2 20
+3 20
+4 20
+5 20
+6 20
+9 20
+10 20
+11 20
+12 20
+13 20
+14 20
+3 21
+4 21
+5 21
+11 21
+12 21
+13 21
Index: branches/Mars_McMismatchStudy/mtools/jam/magiclogo.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/magiclogo.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/magiclogo.jam	(revision 17960)
@@ -0,0 +1,245 @@
+2 22
+3 22
+4 22
+5 22
+6 22
+7 22
+8 22
+9 22
+10 22
+11 22
+12 22
+13 22
+14 22
+15 22
+16 22
+17 22
+18 22
+2 23
+3 23
+9 23
+10 23
+11 23
+12 23
+13 23
+14 23
+15 23
+16 23
+18 23
+19 23
+1 24
+2 24
+8 24
+9 24
+10 24
+11 24
+12 24
+13 24
+14 24
+15 24
+16 24
+18 24
+19 24
+20 24
+1 25
+2 25
+7 25
+8 25
+9 25
+10 25
+11 25
+12 25
+13 25
+14 25
+15 25
+16 25
+20 25
+21 25
+1 26
+6 26
+7 26
+8 26
+9 26
+10 26
+11 26
+12 26
+13 26
+14 26
+15 26
+20 26
+21 26
+1 27
+2 27
+5 27
+6 27
+7 27
+8 27
+9 27
+10 27
+11 27
+12 27
+13 27
+14 27
+15 27
+16 27
+21 27
+22 27
+0 28
+1 28
+4 28
+5 28
+6 28
+7 28
+8 28
+9 28
+10 28
+11 28
+12 28
+13 28
+14 28
+15 28
+20 28
+21 28
+1 29
+5 29
+6 29
+7 29
+8 29
+9 29
+10 29
+13 29
+14 29
+15 29
+21 29
+22 29
+0 30
+1 30
+4 30
+5 30
+6 30
+7 30
+8 30
+9 30
+11 30
+14 30
+21 30
+22 30
+1 31
+2 31
+4 31
+5 31
+6 31
+7 31
+8 31
+9 31
+11 31
+12 31
+13 31
+14 31
+21 31
+22 31
+1 32
+4 32
+5 32
+6 32
+7 32
+8 32
+9 32
+13 32
+21 32
+22 32
+1 33
+2 33
+4 33
+5 33
+6 33
+7 33
+8 33
+9 33
+10 33
+11 33
+14 33
+22 33
+23 33
+1 34
+2 34
+3 34
+4 34
+5 34
+6 34
+7 34
+8 34
+9 34
+10 34
+13 34
+14 34
+15 34
+16 34
+21 34
+22 34
+2 35
+3 35
+4 35
+5 35
+6 35
+7 35
+16 35
+22 35
+23 35
+2 36
+3 36
+16 36
+21 36
+22 36
+3 37
+4 37
+5 37
+16 37
+21 37
+22 37
+4 38
+5 38
+15 38
+16 38
+17 38
+18 38
+21 38
+22 38
+5 39
+6 39
+7 39
+18 39
+21 39
+22 39
+6 40
+7 40
+8 40
+17 40
+20 40
+21 40
+8 41
+9 41
+10 41
+11 41
+12 41
+18 41
+19 41
+20 41
+21 41
+9 42
+10 42
+11 42
+12 42
+13 42
+14 42
+15 42
+16 42
+17 42
+18 42
+19 42
+12 43
+13 43
+14 43
+15 43
+16 43
+17 43
Index: branches/Mars_McMismatchStudy/mtools/jam/man.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/man.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/man.jam	(revision 17960)
@@ -0,0 +1,201 @@
+23 3
+24 3
+25 3
+26 3
+27 3
+28 3
+29 3
+30 3
+31 3
+32 3
+33 3
+23 4
+32 4
+33 4
+23 5
+33 5
+34 5
+23 6
+25 6
+26 6
+27 6
+28 6
+29 6
+30 6
+31 6
+32 6
+33 6
+23 7
+26 7
+34 7
+35 7
+23 8
+25 8
+34 8
+35 8
+23 9
+26 9
+28 9
+29 9
+30 9
+31 9
+32 9
+33 9
+34 9
+35 9
+23 10
+25 10
+28 10
+23 11
+26 11
+28 11
+23 12
+25 12
+28 12
+23 13
+26 13
+28 13
+23 14
+25 14
+28 14
+23 15
+24 15
+25 15
+26 15
+27 15
+28 15
+29 15
+22 16
+29 16
+23 17
+30 17
+22 18
+30 18
+23 19
+30 19
+22 20
+30 20
+23 21
+30 21
+22 22
+30 22
+23 23
+30 23
+22 24
+29 24
+23 25
+26 25
+27 25
+28 25
+29 25
+30 25
+31 25
+32 25
+33 25
+22 26
+25 26
+33 26
+34 26
+23 27
+26 27
+27 27
+28 27
+29 27
+30 27
+31 27
+32 27
+35 27
+22 28
+27 28
+32 28
+33 28
+34 28
+23 29
+24 29
+25 29
+26 29
+27 29
+33 29
+34 29
+22 30
+27 30
+32 30
+33 30
+34 30
+23 31
+25 31
+26 31
+27 31
+34 31
+22 32
+24 32
+28 32
+29 32
+30 32
+31 32
+32 32
+34 32
+23 33
+25 33
+26 33
+27 33
+28 33
+33 33
+35 33
+22 34
+27 34
+33 34
+23 35
+28 35
+33 35
+22 36
+26 36
+27 36
+28 36
+29 36
+30 36
+31 36
+32 36
+23 37
+26 37
+28 37
+22 38
+26 38
+27 38
+23 39
+27 39
+22 40
+23 40
+24 40
+25 40
+26 40
+27 40
+23 41
+27 41
+22 42
+23 42
+24 42
+25 42
+26 42
+27 42
+23 43
+27 43
+22 44
+27 44
+22 45
+28 45
+21 46
+28 46
+22 47
+28 47
+21 48
+28 48
+22 49
+28 49
+22 50
+23 50
+26 50
+27 50
+24 51
+25 51
+26 51
Index: branches/Mars_McMismatchStudy/mtools/jam/post.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/post.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/post.jam	(revision 17960)
@@ -0,0 +1,192 @@
+7 2
+8 2
+10 2
+11 2
+17 2
+18 2
+20 2
+21 2
+8 3
+9 3
+11 3
+12 3
+17 3
+18 3
+20 3
+21 3
+8 4
+9 4
+11 4
+12 4
+16 4
+17 4
+19 4
+20 4
+10 5
+13 5
+16 5
+19 5
+9 6
+10 6
+11 6
+12 6
+13 6
+14 6
+15 6
+16 6
+17 6
+18 6
+19 6
+9 7
+10 7
+11 7
+12 7
+13 7
+14 7
+15 7
+16 7
+17 7
+18 7
+19 7
+20 7
+7 8
+8 8
+9 8
+10 8
+11 8
+17 8
+18 8
+19 8
+20 8
+21 8
+7 9
+8 9
+9 9
+10 9
+19 9
+20 9
+21 9
+22 9
+6 10
+7 10
+8 10
+9 10
+19 10
+20 10
+21 10
+22 10
+6 11
+7 11
+8 11
+9 11
+20 11
+21 11
+22 11
+23 11
+24 11
+5 12
+6 12
+7 12
+8 12
+20 12
+21 12
+22 12
+23 12
+24 12
+5 13
+6 13
+8 13
+20 13
+21 13
+22 13
+23 13
+24 13
+25 13
+4 14
+5 14
+7 14
+8 14
+20 14
+21 14
+22 14
+23 14
+24 14
+25 14
+4 15
+5 15
+8 15
+9 15
+20 15
+21 15
+23 15
+24 15
+25 15
+26 15
+3 16
+4 16
+5 16
+7 16
+8 16
+20 16
+21 16
+23 16
+24 16
+25 16
+4 17
+5 17
+8 17
+9 17
+20 17
+21 17
+23 17
+24 17
+25 17
+26 17
+3 18
+4 18
+5 18
+8 18
+9 18
+19 18
+20 18
+23 18
+24 18
+25 18
+26 18
+4 19
+5 19
+9 19
+10 19
+11 19
+18 19
+19 19
+20 19
+23 19
+24 19
+25 19
+26 19
+27 19
+9 20
+10 20
+11 20
+12 20
+16 20
+17 20
+18 20
+19 20
+23 20
+24 20
+25 20
+11 21
+12 21
+13 21
+14 21
+15 21
+16 21
+17 21
+18 21
+12 22
+13 22
+14 22
+15 22
+16 22
Index: branches/Mars_McMismatchStudy/mtools/jam/running.jam
===================================================================
--- branches/Mars_McMismatchStudy/mtools/jam/running.jam	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtools/jam/running.jam	(revision 17960)
@@ -0,0 +1,129 @@
+16 1
+17 1
+13 2
+14 2
+15 2
+16 2
+17 2
+14 3
+15 3
+0 4
+14 4
+15 4
+0 5
+1 5
+4 5
+5 5
+6 5
+7 5
+15 5
+0 6
+1 6
+2 6
+3 6
+4 6
+5 6
+6 6
+7 6
+14 6
+15 6
+1 7
+2 7
+3 7
+7 7
+8 7
+15 7
+1 8
+7 8
+8 8
+9 8
+10 8
+11 8
+12 8
+13 8
+14 8
+15 8
+8 9
+9 9
+10 9
+11 9
+12 9
+13 9
+14 9
+15 9
+8 10
+9 10
+9 11
+10 11
+8 12
+9 12
+1 13
+2 13
+9 13
+10 13
+11 13
+12 13
+13 13
+14 13
+15 13
+1 14
+2 14
+8 14
+9 14
+10 14
+11 14
+12 14
+13 14
+14 14
+15 14
+3 15
+4 15
+7 15
+8 15
+9 15
+10 15
+15 15
+16 15
+17 15
+18 15
+3 16
+4 16
+5 16
+6 16
+7 16
+9 16
+10 16
+16 16
+17 16
+5 17
+6 17
+9 17
+10 17
+11 17
+8 18
+9 18
+10 18
+11 18
+8 19
+12 19
+7 20
+12 20
+7 21
+8 21
+9 21
+10 21
+11 21
+12 21
+13 21
+14 21
+15 21
+16 21
+17 21
+7 22
+12 22
+8 23
+12 23
+8 24
+9 24
+10 24
+11 24
Index: branches/Mars_McMismatchStudy/mtrigger/MFTriggerPattern.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MFTriggerPattern.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MFTriggerPattern.cc	(revision 17960)
@@ -0,0 +1,390 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz  12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2008
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFTriggerPattern
+//
+//  A Filter for testing the trigger performance using Trigger Pattern.
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+//
+// To setup the filter you can use Deny, Allow and Require functions.
+// Allow is just resetting a bit set by Deny (mostly used in combination
+// with DenyAl in advance)
+//
+// For more details on the meaning of the bits set by these member
+// functions see Eval()
+//
+// For more details on the meaning of the trigger pattern see:
+//   MTriggerPattern
+//
+// Input Containers:
+//   MTriggerPattern
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFTriggerPattern.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTriggerPattern.h"
+
+ClassImp(MFTriggerPattern);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. The default is to allow passing any trigger pattern.
+//
+MFTriggerPattern::MFTriggerPattern(const char *name, const char *title)
+    : fPattern(0), fMaskRequiredPrescaled(0), fMaskRequiredUnprescaled(0),
+      fMaskDeniedPrescaled(0), fMaskDeniedUnprescaled(0), fDefault(kTRUE)
+{
+    fName  = name  ? name  : "MFTriggerPattern";
+    fTitle = title ? title : "Filter on Trigger Pattern";
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy constructor
+//
+MFTriggerPattern::MFTriggerPattern(MFTriggerPattern &trigpatt)
+: MFilter(trigpatt)
+{
+    fMaskRequiredPrescaled   = trigpatt.fMaskRequiredPrescaled;
+    fMaskRequiredUnprescaled = trigpatt.fMaskRequiredUnprescaled;
+
+    fMaskDeniedPrescaled     = trigpatt.fMaskDeniedPrescaled;
+    fMaskDeniedUnprescaled   = trigpatt.fMaskDeniedUnprescaled;
+
+    fDefault                 = trigpatt.fDefault;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Search for MTriggerPattern in the paremeter list.
+//
+Int_t MFTriggerPattern::PreProcess(MParList *pList)
+{
+    fPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
+    if (!fPattern)
+    {
+	*fLog << err << "MTriggerPattern not found... abort." << endl;
+	return kFALSE;
+    }
+
+    memset(fCounter, 0, sizeof(fCounter));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+// If the prescaled and unprescaled trigger patters is equal 0 fDefault
+// is returned.
+//
+// The returned value is false if any of the require mask bits doesn't
+// match a corresponding bit in the trigger bits. If the trigger mask
+// contains at least the same bits as in the require mask the returned
+// value is true. (Note that this means if the require masks are 0
+// true is returned)
+//
+// This return value can be overwritten by the deny mask. If any of the
+// bits in the deny mask will match a trigger bit false will be returned.
+//
+Int_t MFTriggerPattern::Eval()
+{
+    const Byte_t p = fPattern->GetPrescaled();
+    const Byte_t u = fPattern->GetUnprescaled();
+    if (p==0 && u==0)
+    {
+        fCounter[2]++;
+        return fDefault;
+    }
+
+    Bool_t rc = kFALSE;
+
+    // Check whether all the bits required are ON
+    if ( ((p & fMaskRequiredPrescaled)   == fMaskRequiredPrescaled) &&
+         ((u & fMaskRequiredUnprescaled) == fMaskRequiredUnprescaled))
+      rc = kTRUE;
+
+    // Now overwrite the result if one of the bits is denied
+    if ( (p & fMaskDeniedPrescaled) || (u & fMaskDeniedUnprescaled) )
+    {
+        fCounter[3]++;
+        return kFALSE;
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// See Eval()
+//
+Int_t MFTriggerPattern::Process()
+{
+    fResult = Eval();
+    fCounter[fResult ? 0 : 1]++;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFTriggerPattern::PostProcess()
+{
+    const UInt_t n = GetNumExecutions();
+    if (n==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << "  " << setw(7) << fCounter[2] << " (" << setw(3);
+    *fLog << (int)(fCounter[2]*100/n);
+    *fLog << "%) Default (" << (fDefault?"true":"false") << ") returned." << endl;
+
+    *fLog << "  " << setw(7) << fCounter[3] << " (" << setw(3);
+    *fLog << (int)(fCounter[3]*100/n);
+    *fLog << "%) Trigger denied." << endl;
+
+    *fLog << " " << setw(7) << fCounter[0] << " (" << setw(3);
+    *fLog << (int)(fCounter[0]*100/n);
+    *fLog << "%) Accepted trigger pattern." << endl;
+
+    *fLog << " " << setw(7) << fCounter[1] << " (" << setw(3);
+    *fLog << (int)(fCounter[1]*100/n);
+    *fLog << "%) Rejected trigger pattern!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Require that a prescaled or unprescaled bit in the trigger pattern is
+// passed. The bit is defined by mask, the prescaling by prescaled. The
+// default is unprescaled.
+//
+// Because it doesn't make sense to require a denied bit we reset
+// the deny bit at the same time.
+//
+void MFTriggerPattern::Require(const Byte_t mask, Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled |=  mask) : (fMaskRequiredUnprescaled |=  mask);
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled   &= ~mask) : (fMaskDeniedUnprescaled   &= ~mask);
+}
+
+// -------------------------------------------------------------------------
+//
+// Deny that a prescaled or unprescaled bit in the trigger pattern is
+// passed. The bit is defined by mask, the prescaling by prescaled. The
+// default is unprescaled.
+//
+// Because it doesn't make sense to deny a required bit we reset
+// the require bit at the same time.
+//
+void MFTriggerPattern::Deny(const Byte_t mask, Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled   |=  mask) : (fMaskDeniedUnprescaled   |=  mask);
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled &= ~mask) : (fMaskRequiredUnprescaled &= ~mask);
+}
+
+// -------------------------------------------------------------------------
+//
+// Remove the given bits from the deny-mask. Thus you can first deny
+// all bits to pass and then define which bit you want to allow
+// to pass. The bit is defined by mask, the prescaling by prescaled. The
+// default is unprescaled.
+//
+void MFTriggerPattern::Allow(const Byte_t mask, Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled &= ~mask) : (fMaskDeniedUnprescaled &= ~mask);
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Deny all bits (i.e. also require non bits) for the given prescaling
+// option. The prescaling is defined by prescaled. The default is
+// unprescaled.
+//
+void MFTriggerPattern::DenyAll(Prescale_t prescaled)
+{
+    Deny(0xff, prescaled);
+}
+
+// -------------------------------------------------------------------------
+//
+// Allow all bits. resets the deny mask for the given prescaling option,
+// but keeps the require mask unchanged. The prescaling is defined
+// by prescaled. The default is unprescaled.
+//
+void MFTriggerPattern::AllowAll(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled = 0) : (fMaskDeniedUnprescaled = 0);
+}
+
+// -------------------------------------------------------------------------
+//
+// Low level settings. USE THESE ONLY IF YOU ARE AN EXPERT!
+//
+// You can concatenate bits either by using MTriggerPatter:
+//   eg. MTriggerPattern::kTriggerLvl1 & MTiggerPattern::kTriggerLvl2
+// of by hexadecimal values:
+//   eg. 0xab
+//
+//  while 0xab can be decoded like:
+//
+//                                   8421 8421
+//       0xa=10=8+2 0xb=11=8+2+1 --> 1010 1011
+//
+// or vice versa it is easy to get a hexadecimal number from a bit pattern,
+//   eg.
+//
+//       8421 8421
+//       0101 1101  -->  4+1=5=0x5 8+4+1=13=0xd --> 0x5d
+//
+void MFTriggerPattern::SetMaskRequired(const Byte_t mask, Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled = mask) : (fMaskRequiredUnprescaled = mask);
+}
+
+// -------------------------------------------------------------------------
+//
+// Low level settings. USE THESE ONLY IF YOU ARE AN EXPERT!
+//
+// You can concatenate bits either by using MTriggerPatter:
+//   eg. MTriggerPattern::kTriggerLvl1 & MTiggerPattern::kTriggerLvl2
+// of by hexadecimal values:
+//   eg. 0xab
+//
+//  while 0xab can be decoded like:
+//
+//                                   8421 8421
+//       0xa=10=8+2 0xb=11=8+2+1 --> 1010 1011
+//
+// or vice versa it is easy to get a hexadecimal number from a bit pattern,
+//   eg.
+//
+//       8421 8421
+//       0101 1101  -->  4+1=5=0x5 8+4+1=13=0xd --> 0x5d
+//
+void MFTriggerPattern::SetMaskDenied(const Byte_t mask, Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled  = mask) : (fMaskDeniedUnprescaled  = mask);
+}
+
+// -------------------------------------------------------------------------
+//
+// Create the mask to allow a particular (un)prescaled trigger pattern.
+//
+// Possible arguments are (upper/lower case is ignored):
+//
+//           "LT1"  : Trigger Level 1 flag
+//           "CAL"  : Calibration flag
+//           "LT2"  : Trigger Level 2 flag
+//           "PED"  : Pedestal flag
+//           "PIND" : Pin Diode flag
+//           "SUMT" : Sum Trigger flag
+// 
+// concatenations of these strings are allowed and considered as 
+// a logic "and", while trigger pattern flags not considered are
+// anyway allowed. To deny a particular trigger pattern use
+// the method Deny
+// Example: patt = "lt1 lt2" allows events with trigger pattern flags
+// {LT1,CAL,LT2} but not events with flags {LT1,CAL}.
+//
+void MFTriggerPattern::Require(TString patt, Prescale_t prescaled)
+{
+    if (patt.Contains("LT1", TString::kIgnoreCase))
+        RequireTriggerLvl1(prescaled);
+
+    if (patt.Contains("LT2", TString::kIgnoreCase))
+        RequireTriggerLvl2(prescaled);
+
+    if (patt.Contains("CAL", TString::kIgnoreCase))
+        RequireCalibration(prescaled);
+
+    if (patt.Contains("PED", TString::kIgnoreCase))
+        RequirePedestal(prescaled);
+
+    if (patt.Contains("PIND", TString::kIgnoreCase))
+        RequirePinDiode(prescaled);
+
+    if (patt.Contains("SUMT", TString::kIgnoreCase))
+        RequireSumTrigger(prescaled);
+}
+
+// -------------------------------------------------------------------------
+//
+// Create the mask to deny a particular (un)prescaled trigger pattern.
+//
+// This method is there because is not possible to deny trigger patterns
+// using only the Require pattern. Possible arguments are (upper/lower
+// case is ignored) the flags for:
+//
+//           "LT1"  : Trigger Level 1
+//           "CAL"  : Calibration
+//           "LT2"  : Trigger Level 2
+//           "PED"  : Pedestal
+//           "PIND" : Pin Diode
+//           "SUMT" : Sum Trigger
+// 
+// concatenations of these strings are allowed and considered as 
+// a logic "and", while trigger pattern flags not considered are
+// anyway allowed.
+//
+// Example: patt = "lt1 lt2" deny events with trigger pattern flags
+// {LT1,CAL,LT2} but not events with flags {LT1,CAL}.
+//
+void MFTriggerPattern::Deny(TString patt, Prescale_t prescaled)
+{
+    if (patt.Contains("LT1", TString::kIgnoreCase))
+        DenyTriggerLvl1(prescaled);
+
+    if (patt.Contains("LT2", TString::kIgnoreCase))
+        DenyTriggerLvl2(prescaled);
+
+    if (patt.Contains("CAL", TString::kIgnoreCase))
+        DenyCalibration(prescaled);
+
+    if (patt.Contains("PED", TString::kIgnoreCase))
+        DenyPedestal(prescaled);
+
+    if (patt.Contains("PIND", TString::kIgnoreCase))
+        DenyPinDiode(prescaled);
+
+    if (patt.Contains("SUMT", TString::kIgnoreCase))
+        DenySumTrigger(prescaled);
+}
Index: branches/Mars_McMismatchStudy/mtrigger/MFTriggerPattern.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MFTriggerPattern.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MFTriggerPattern.h	(revision 17960)
@@ -0,0 +1,91 @@
+#ifndef MARS_MFTriggerPattern
+#define MARS_MFTriggerPattern
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef MARS_MTriggerPatter
+#include "MTriggerPattern.h"
+#endif
+
+class MTriggerPattern;
+
+class MFTriggerPattern : public MFilter
+{
+public:
+    enum Prescale_t {
+        kUnPrescaled,
+        kPrescaled
+    };
+
+private:
+  MTriggerPattern *fPattern;        //!
+
+  Byte_t fMaskRequiredPrescaled;    // Mask for filtering Trigger Pattern allowed
+  Byte_t fMaskRequiredUnprescaled;  // Mask for filtering Trigger Pattern allowed
+  Byte_t fMaskDeniedPrescaled;      // Mask for filtering Trigger Pattern denied
+  Byte_t fMaskDeniedUnprescaled;    // Mask for filtering Trigger Pattern denied
+
+  Bool_t fDefault;                  // Default which is used if trigger pattern has default value (p==0&&u==0)
+
+  Bool_t fResult;                   //! Calculated result to be returned by IsExpressionTrue
+  Int_t  fCounter[4];               //! Counter for results
+
+  // MFTriggerPattern
+  void Require(const Byte_t mask, Prescale_t prescaled=kUnPrescaled);
+  void Deny(const Byte_t mask, Prescale_t prescaled=kUnPrescaled);
+  void Allow(const Byte_t mask, Prescale_t prescaled=kUnPrescaled);
+
+  Int_t Eval();
+
+  // MTask
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess();
+
+  // MFilter
+  Bool_t IsExpressionTrue() const { return fResult; }
+
+public:
+  MFTriggerPattern(const char *name=NULL, const char *title=NULL);
+  MFTriggerPattern(MFTriggerPattern &trigpatt);
+
+  // Setter
+  void RequireTriggerLvl1(Prescale_t prescaled=kUnPrescaled) { Require(MTriggerPattern::kTriggerLvl1, prescaled); }
+  void RequireTriggerLvl2(Prescale_t prescaled=kUnPrescaled) { Require(MTriggerPattern::kTriggerLvl2, prescaled); }
+  void RequireCalibration(Prescale_t prescaled=kUnPrescaled) { Require(MTriggerPattern::kCalibration, prescaled); }
+  void RequirePedestal(Prescale_t prescaled=kUnPrescaled)    { Require(MTriggerPattern::kPedestal, prescaled);    }
+  void RequirePinDiode(Prescale_t prescaled=kUnPrescaled)    { Require(MTriggerPattern::kPinDiode, prescaled);    }
+  void RequireSumTrigger(Prescale_t prescaled=kUnPrescaled)  { Require(MTriggerPattern::kSumTrigger, prescaled);  }
+
+  void DenyTriggerLvl1(Prescale_t prescaled=kUnPrescaled)    { Deny(MTriggerPattern::kTriggerLvl1, prescaled); }
+  void DenyTriggerLvl2(Prescale_t prescaled=kUnPrescaled)    { Deny(MTriggerPattern::kTriggerLvl2, prescaled); }
+  void DenyCalibration(Prescale_t prescaled=kUnPrescaled)    { Deny(MTriggerPattern::kCalibration, prescaled); }
+  void DenyPedestal(Prescale_t prescaled=kUnPrescaled)       { Deny(MTriggerPattern::kPedestal, prescaled);    }
+  void DenyPinDiode(Prescale_t prescaled=kUnPrescaled)       { Deny(MTriggerPattern::kPinDiode, prescaled);    }
+  void DenySumTrigger(Prescale_t prescaled=kUnPrescaled)     { Deny(MTriggerPattern::kSumTrigger, prescaled);  }
+
+  void AllowTriggerLvl1(Prescale_t prescaled=kUnPrescaled)   { Allow(MTriggerPattern::kTriggerLvl1, prescaled); }
+  void AllowTriggerLvl2(Prescale_t prescaled=kUnPrescaled)   { Allow(MTriggerPattern::kTriggerLvl2, prescaled); }
+  void AllowCalibration(Prescale_t prescaled=kUnPrescaled)   { Allow(MTriggerPattern::kCalibration, prescaled); }
+  void AllowPedestal(Prescale_t prescaled=kUnPrescaled)      { Allow(MTriggerPattern::kPedestal, prescaled);    }
+  void AllowPinDiode(Prescale_t prescaled=kUnPrescaled)      { Allow(MTriggerPattern::kPinDiode, prescaled);    }
+  void AllowSumTrigger(Prescale_t prescaled=kUnPrescaled)    { Allow(MTriggerPattern::kSumTrigger, prescaled);  }
+
+  void DenyAll(Prescale_t prescaled=kUnPrescaled);
+  void AllowAll(Prescale_t prescaled=kUnPrescaled);
+
+  void Require(TString patt, Prescale_t prescaled=kUnPrescaled);
+  void Deny(TString patt, Prescale_t prescaled=kUnPrescaled);
+
+  void SetDefault(Bool_t b) { fDefault=b; }
+
+  // Low level settings. USE THESE ONLY IF YOU ARE AN EXPERT!
+  void SetMaskRequired(const Byte_t mask, Prescale_t prescaled=kUnPrescaled);
+  void SetMaskDenied(const Byte_t mask, Prescale_t prescaled=kUnPrescaled);
+
+  ClassDef(MFTriggerPattern, 1) // A Filter for the Trigger Pattern
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerBit.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerBit.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerBit.cc	(revision 17960)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerBit
+//
+//   This class stores the information about the L2 output Bit rates
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerBit.h"
+
+ClassImp(MTriggerBit);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerBit.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerBit.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerBit.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MTriggerBit
+#define MARS_MTriggerBit
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MTriggerBit : public MParContainer
+{
+    friend class MReportTrigger;
+
+private:
+    
+    static const Int_t gsNBits=20;        // number of output bits
+
+    TArrayF fBit; // Array with the output bit rates
+
+public:
+    MTriggerBit() : fBit(gsNBits)  
+    {
+        fName  = "MTriggerBit";
+        fTitle = "Container for the L2 output bits rates ";
+    }
+
+    TArrayF GetTriggerBit() const { return fBit; }
+
+    Double_t operator[](const Int_t idx) 
+      {  
+	if (idx > gsNBits)
+	  return kFALSE;
+	
+	return fBit[idx]; 
+      }
+
+    ClassDef(MTriggerBit, 1) // Container for the L2 output bits rates
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerCell.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerCell.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerCell.cc	(revision 17960)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerCell
+//
+//   This class stores the information about the Trigger Cell Rates
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerCell.h"
+
+ClassImp(MTriggerCell);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerCell.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerCell.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerCell.h	(revision 17960)
@@ -0,0 +1,44 @@
+#ifndef MARS_MTriggerCell
+#define MARS_MTriggerCell
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MTriggerCell : public MParContainer
+{
+    friend class MReportTrigger;
+private:
+    static const Int_t gsNCells=32; //Number of fields with cell rates
+                                    // 19 cells and 12 dummy 
+
+    TArrayF fCellRate;       // Array of the measured L1 cell rates
+
+public:
+    MTriggerCell() : fCellRate(gsNCells)
+    {
+        fName  = "MTriggerCell";
+        fTitle = "Container for the measured cell rates";
+    }
+
+    Float_t GetMean() const { return fCellRate.GetSum()/fCellRate.GetSize(); }
+
+    TArrayF GetCellRate() const { return fCellRate; }
+
+    Double_t operator[](const Int_t idx) 
+      { 
+	if (idx > gsNCells)
+	  return kFALSE;
+	
+	return fCellRate[idx]; 
+      }
+
+
+    ClassDef(MTriggerCell, 1) // Container for the trigger cell rates
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerIPR.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerIPR.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerIPR.cc	(revision 17960)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerIPR
+//
+//   This class stores the information about the Individual Pixel Rates
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerIPR.h"
+
+ClassImp(MTriggerIPR);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerIPR.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerIPR.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerIPR.h	(revision 17960)
@@ -0,0 +1,57 @@
+#ifndef MARS_MTriggerIPR
+#define MARS_MTriggerIPR
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerIPR : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    static const Int_t gsNTrigPix=397;  // number of trigger pixels
+
+    TArrayL fIPR;                       // [Hz] IPR (Individual Pixel Rates)
+
+public:
+    MTriggerIPR() : fIPR(gsNTrigPix)
+    {
+        fName  = "MTriggerIPR";
+        fTitle = "Trigger-Container for the Individual Pixel Rate (IPR)";
+    }
+
+    Float_t GetMean() const { return fIPR.GetSum()/fIPR.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx >= gsNTrigPix)
+	return kFALSE;
+
+      val = fIPR[idx];
+      return val>0;
+    }
+
+    Double_t operator[](const Int_t idx) 
+      {
+	if (idx > gsNTrigPix)
+	  return kFALSE;
+
+	return fIPR[idx]; 
+      } 
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerIPR, 1) // Trigger-Container for the Individual Pixel Rate (IPR)
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerLiveTime.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerLiveTime.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerLiveTime.cc	(revision 17960)
@@ -0,0 +1,38 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerLiveTime
+//
+//   This class stores the information about the livetime and deadtime
+//   measured by the scalers 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerLiveTime.h"
+
+ClassImp(MTriggerLiveTime);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerLiveTime.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerLiveTime.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerLiveTime.h	(revision 17960)
@@ -0,0 +1,44 @@
+#ifndef MARS_MTriggerLiveTime
+#define MARS_MTriggerLiveTime
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerLiveTime : public MParContainer
+{
+    friend class MReportTrigger;
+
+private:
+    static const Int_t gsNScalers=5;        // number of scalers
+
+    TArrayL fLiveTime; // Array with the livetime
+    TArrayL fDeadTime; // Array with the deadtime
+
+public:
+    MTriggerLiveTime() : fLiveTime(gsNScalers), fDeadTime(gsNScalers)  
+    {
+        fName  = "MTriggerLiveTime";
+        fTitle = "Container for the Live-deadtime      ";
+    }
+
+    TArrayL GetLiveTime() const { return fLiveTime; }
+    TArrayL GetDeadTime() const { return fDeadTime; }
+
+    // !FIX ME!  Only live time is returned...
+    Double_t operator[](const Int_t idx) 
+      {  	
+	if (idx > gsNScalers)
+	  return -1;
+	
+	return fLiveTime[idx]; 
+      }
+
+    ClassDef(MTriggerLiveTime, 1) // Container for the Live-Deadtime
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerPattern.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerPattern.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerPattern.cc	(revision 17960)
@@ -0,0 +1,190 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz  12/2004 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2004-2007
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MTriggerPattern
+//
+//  A container to store the decoded trigger pattern.
+//
+// The idea is, that this container will never change the meaning of its
+// variables, while the trigger pattern itself could.
+//
+// If new 'features' are necessary the decoding (MTriggerPatternDecode)
+// must be changed to correctly decode the pattern into the existing
+// MTriggerPattern. If new information is decoded you may have to
+// add new variables to this container. Don't forget to increase the
+// class version number (ClassDef) and document your change HERE.
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+//
+// --------------------------------------------------------------------------
+//
+// Here an explanation about the meaning of the Trigger Pattern.
+// The trigger pattern is a 16-BIT number where are stored informations
+// about which thriggers have been shot on each event. Every bit
+// correspond to a prticular kind of trigger (Pedestal, Calibration,
+// LT1, LT2, PIN Diode...) but the whole trigger pattern number
+// is divided into two parts (from left to right):
+// 
+// 1) The first concerns unprescaled triggers.
+// 2) The second concerns prescaled triggers.
+// 
+// The prescaler is a devicee installed AFTER the LT2. It collects
+// all kind of triggers and can prescale each trigger by a different
+// prescaling factor. This means that we can set the prescaler to
+// accept every LT2 trigger but only 1% of calibration triggers.
+// Therefore LT2 prescaling factor will be set to 1, while CAL prescaling
+// factor will be set to 100. If after the prescaler at least one trigger
+// survives, then the event is considered "TRIGGERED" and aquired by the DAQ.
+// 
+// The current BIT meaning is:
+// 
+// BIT(0):  prescaled LT1
+// BIT(1):  prescaled Calibration Trigger
+// BIT(2):  prescaled LT2
+// BIT(3):  prescaled Pedestal Trigger
+// BIT(4):  prescaled Pin Diode
+// BIT(5):  prescaled Sum Trigger
+// BIT(6):  unused
+// BIT(7):  unused
+// BIT(8):  unprescaled LT1
+// BIT(9):  unprescaled Calibration Trigger
+// BIT(10): unprescaled LT2
+// BIT(11): unprescaled Pedestal Trigger
+// BIT(12): unprescaled Pin Diode
+// BIT(13): unprescaled Sum Trigger
+// BIT(14): unused
+// BIT(15): unused
+// 
+// Why are we saving both prescaled and unprescaled triggers?
+// Which should I look at? Let's give an example:
+// 
+//    BIT #      15-14-13-12-11-10- 9- 8- 7- 6- 5- 4- 3- 2- 1- 0
+// 
+//    event #1:   0  0  0  0  0  0  1  1  0  0  0  0  0  0  0  1
+//    event #2:   0  0  0  0  0  0  1  1  0  0  0  0  0  0  1  1
+// 
+// In both cases you have both CAL and LT1 trigger, but in first
+// event calibration trigger is prescaled and in second event no
+// trigger is prescaled. Imagine you are looking for calibration events. 
+// If you look at the prescale bits you are sure that events with CAL
+// flag are calibration events (event #2) but you can miss other
+// real calibration events (event #1). If you are lucky that
+// the related prescaling factor is 1 you won't have this problem,
+// otherway you will have it. 
+// 
+// To select events by the trigger pattern you should use MFTriggerPattern
+// filter. This filter uses Require- and Deny- methods to select your
+// trigger pattern. Require- methods requires that your trigger bit is ON,
+// otherway the event is kicked out. Deny- methods requires that your
+// trigger bit is OFF, otherway your event is kicked out. Other bits not
+// selected by your Require- or Deny- call are ignored. Let's give an
+// example. You want to select all events that have both LT1 and LT2
+// trigger but which are not calibration neither Pin Diode events. You
+// should look at unprescaled bits to be sure about which were the initial
+// triggers. Then you can implement in your macro something like:
+// 
+//      MFTriggerPattern ftrigpatt;
+//      ftrigpatt.RequireTriggerLvl1(MFTriggerPattern::kUnPrescaled);
+//      ftrigpatt.RequireTriggerLvl2(MFTriggerPattern::kUnPrescaled);
+//      ftrigpatt.DenyCalibration(MFTriggerPattern::kUnPrescaled);
+//      ftrigpatt.DenyPinDiode(MFTriggerPattern::kUnPrescaled);
+// 
+// Then you use in your tasklist as a usual MF filter. In this
+// example Pedestal trigger flag is ignored. Consider that by default
+// MFTriggerPattern::kUnPrescaled is set for Require- and Deny- methods.
+// 
+// WARNING: please use MTriggerPatternDecode task to read the trigger pattern
+// of the event and to fill MTriggerPattern container. If you use your
+// private stuff to read MRawEvtHeader.fTriggerPattern[0] (data member
+// where the trigger pattern is stored) you must invert all the bits of
+// your number. Current hardware, infact, writes the trigger pattern bit-inverted.
+// 
+// 
+// For further informations contact:
+// 
+// Nicola Galante        nicola.galante@pi.infn.it
+// Riccardo Paoletti     riccardo.paoletti@pi.infn.it
+// Antonio Stamerra      antonio.stamerra@pi.infn.it
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPattern.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTriggerPattern);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MTriggerPattern::MTriggerPattern(const char *name, const char *title)
+    : fPrescaled(0), fUnprescaled(0)
+{
+    fName  = name  ? name  : "MTriggerPattern";
+    fTitle = title ? title : "Container for decoded trigger pattern";
+}
+
+void MTriggerPattern::Copy(TObject &obj) const
+{
+    static_cast<MTriggerPattern&>(obj).fPrescaled=fPrescaled;
+    static_cast<MTriggerPattern&>(obj).fUnprescaled=fUnprescaled;
+}
+
+void MTriggerPattern::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Trigger Pattern (un/prescaled): ";
+
+    if (fUnprescaled&kPedestal)
+        *fLog << "P";
+    if (fUnprescaled&kCalibration)
+        *fLog << "C";
+    if (fUnprescaled&kTriggerLvl1)
+        *fLog << "1";
+    if (fUnprescaled&kTriggerLvl2)
+        *fLog << "2";
+    if (fUnprescaled&kSumTrigger)
+        *fLog << "S";
+    if (fUnprescaled&kPinDiode)
+        *fLog << "-";
+    *fLog << "/";
+    if (fPrescaled&kPedestal)
+        *fLog << "P";
+    if (fPrescaled&kCalibration)
+        *fLog << "C";
+    if (fPrescaled&kTriggerLvl1)
+        *fLog << "1";
+    if (fPrescaled&kTriggerLvl2)
+        *fLog << "2";
+    if (fPrescaled&kSumTrigger)
+        *fLog << "S";
+    if (fPrescaled&kPinDiode)
+        *fLog << "-";
+    *fLog << endl;
+}
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerPattern.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerPattern.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerPattern.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MTriggerPattern
+#define MARS_MTriggerPattern
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MTriggerPattern : public MParContainer
+{
+    friend class MTriggerPatternDecode;
+
+public:
+    enum Pattern_t {
+        kTriggerLvl1 = BIT(0), //  1   1: Level 1 from L2 board
+        kCalibration = BIT(1), //  2   2: Pulse Trigger
+        kTriggerLvl2 = BIT(2), //  4   4: LUT Pseudo Size selection
+        kPedestal    = BIT(3), //  8   8: Artificial pedestal event
+        kPinDiode    = BIT(4), // 10  16:
+        kSumTrigger  = BIT(5), // 20  32: Flag for an event taken with sum trigger
+        kUndefined1  = BIT(6), // 40  64: Trigger lvl1 directly from L1 without going through L2
+        kUndefined2  = BIT(7)  // 80 128: Undefined? (L3?)
+    };
+
+private:
+    Byte_t fPrescaled;   // Bit Pattern as defined above
+    Byte_t fUnprescaled; // Bit Pattern as defined above
+
+public:
+    MTriggerPattern(const char *name=0, const char *title=0);
+
+    void Print(Option_t *o="") const;
+    void Copy(TObject &obj) const;
+
+    void Reset() { fPrescaled=0; fUnprescaled=0; }
+
+    Byte_t GetPrescaled() const   { return fPrescaled; }
+    Byte_t GetUnprescaled() const { return fUnprescaled; }
+
+    ClassDef(MTriggerPattern, 1) // Container storing the decoded trigger pattern
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerPatternDecode.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerPatternDecode.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerPatternDecode.cc	(revision 17960)
@@ -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): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz 12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MTriggerPatternDecode
+//
+//  Decodes the trigger pattern from MRawEvtData into MTriggerPattern.
+//
+// For files before file version 5 the trigger pattern is set according
+// to the file type
+//
+// For more details see: MTriggerPattern
+//
+// Input:
+//   MRawEvtData
+//
+// Output:
+//   MTriggerPattern
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPatternDecode.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MTriggerPattern.h"
+
+ClassImp(MTriggerPatternDecode);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MTriggerPatternDecode::MTriggerPatternDecode(const char *name, const char *title)
+    : fRunHeader(0), fEvtHeader(0), fPattern(0)
+{
+    fName  = name  ? name  : "MTriggerPatternDecode";
+    fTitle = title ? title : "Task to decode Trigger Pattern";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MTriggerPatternDecode::PreProcess(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+	*fLog << err << "MRawRunHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fEvtHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+    if (!fEvtHeader)
+    {
+	*fLog << err << "MRawEvtHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fPattern = (MTriggerPattern*)pList->FindCreateObj("MTriggerPattern");
+    if (!fPattern)
+	return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MTriggerPatternDecode::Process()
+{
+    if (fRunHeader->GetCameraVersion()==0xfac7)
+    {
+        UInt_t pat = 0;
+
+        if (fEvtHeader->GetTriggerID()&0x4)
+            pat |= MTriggerPattern::kTriggerLvl1;
+
+        if (fEvtHeader->GetTriggerID()&0x400)
+            pat |= MTriggerPattern::kPedestal;
+
+        if (fEvtHeader->GetTriggerID()&0x100)
+            pat |= MTriggerPattern::kCalibration;
+
+        if (fEvtHeader->GetTriggerID()&0x8000)
+            pat |= MTriggerPattern::kSumTrigger;
+
+        fPattern->fPrescaled   = pat;
+        fPattern->fUnprescaled = pat;
+
+        return kTRUE;
+    }
+
+    if (fRunHeader->GetFormatVersion()<5)
+    {
+        switch (fRunHeader->GetRunType()&0xff)
+        {
+        case MRawRunHeader::kRTData:
+            fPattern->fPrescaled   = MTriggerPattern::kTriggerLvl1;
+            fPattern->fUnprescaled = MTriggerPattern::kTriggerLvl1;
+            return kTRUE;
+
+        case MRawRunHeader::kRTPedestal:
+            fPattern->fPrescaled   = MTriggerPattern::kPedestal;
+            fPattern->fUnprescaled = MTriggerPattern::kPedestal;
+            return kTRUE;
+
+        case MRawRunHeader::kRTCalibration:
+            fPattern->fPrescaled   = MTriggerPattern::kCalibration;
+            fPattern->fUnprescaled = MTriggerPattern::kCalibration;
+            return kTRUE;
+        }
+        return kTRUE;
+    }
+
+    const UInt_t pattern = ~fEvtHeader->GetTriggerID();
+
+    // The the trigger pattern is currently written with inverted bits,
+    // but in the future this could be changed. In this case the file version
+    // number of the raw-data format must be checked. It tells you the
+    // file format (meaning of the bits)
+    // If for some reason the file-format has not been correctly changed
+    // use the run-number to decide whether the bits must be inverted or not.
+
+    // Trigger Pattern is a number of 16 bits, but if the machine
+    // is a 64 bits then the bit inversion the first 16 bits are set to 1,
+    // possibly giving problems with the filtering with the masks.
+    // Because UInt_t by definition is a 32 bit number on any
+    // machine (see root manual) no check is needed.
+    // The simplest workaround is:
+    //   pattern &= 0xffffffff;
+
+    // For the moment the meaning of the bits in
+    // MRawEvtHeader::GetTriggerID and in MTriggerPattern::fTriggerPattern
+    // are identical - this may change in the future! In this case
+    // the decoding HERE must be changed - NOT MTriggerPattern.
+    // If an enhancement of the information stored in MTriggerPattern
+    // is necessary ADD new variables! Don't change the meaning of the old
+    // ones!
+    fPattern->fPrescaled   =  pattern     & 0xff;
+    fPattern->fUnprescaled = (pattern>>8) & 0xff;
+
+    // This is a workaround for the new scheme in which L1TPU (the signal
+    // comming directly from the L1 is connected, but the L1 (routed
+    // over L2 is disconnected)
+    if (!fRunHeader->IsMonteCarloRun() && fRunHeader->GetTelescopeNumber()==1 &&
+        fRunHeader->GetRunNumber()>1006246)
+    {
+        fPattern->fPrescaled   |= (pattern>> 6)&1;
+        fPattern->fUnprescaled |= (pattern>>14)&1;
+
+        fPattern->fPrescaled   &= 0xbf;
+        fPattern->fUnprescaled &= 0xbf;
+    }
+
+    return kTRUE;
+}
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerPatternDecode.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerPatternDecode.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerPatternDecode.h	(revision 17960)
@@ -0,0 +1,29 @@
+#ifndef MARS_MTriggerPatternDecode
+#define MARS_MTriggerPatternDecode
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MTriggerPattern;
+
+class MTriggerPatternDecode : public MTask
+{
+private:
+    MRawRunHeader   *fRunHeader;
+    MRawEvtHeader   *fEvtHeader;
+    MTriggerPattern *fPattern;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MTriggerPatternDecode(const char *name=0, const char *title=0);
+
+    ClassDef(MTriggerPatternDecode, 1) // Task to decode the Trigger Pattern
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerPrescFact.cc
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerPrescFact.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerPrescFact.cc	(revision 17960)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerPrescFact
+//
+//   This class stores the information about the L2 prescaling factors
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPrescFact.h"
+
+ClassImp(MTriggerPrescFact);
+
+using namespace std;
Index: branches/Mars_McMismatchStudy/mtrigger/MTriggerPrescFact.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/MTriggerPrescFact.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/MTriggerPrescFact.h	(revision 17960)
@@ -0,0 +1,42 @@
+#ifndef MARS_MTriggerPrescFact
+#define MARS_MTriggerPrescFact
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerPrescFact : public MParContainer
+{
+    friend class MReportTrigger;
+
+private:
+    
+    static const Int_t gsNPrescFacts=8;        // number of factors
+
+    TArrayL fPrescFact; // Array with the prescaling factors
+
+public:
+    MTriggerPrescFact() : fPrescFact(gsNPrescFacts)  
+    {
+        fName  = "MTriggerPrescFact";
+        fTitle = "Container for the L2 Prescaling Factors      ";
+    }
+
+    TArrayL GetPrescFactors() const { return fPrescFact; }
+
+    Double_t operator[](const Int_t idx) 
+      {  
+	if (idx > gsNPrescFacts)
+	  return kFALSE;
+	
+	return fPrescFact[idx]; 
+      }
+
+    ClassDef(MTriggerPrescFact, 1) // Container for the L2 Prescaling Factors
+};
+
+#endif
Index: branches/Mars_McMismatchStudy/mtrigger/Makefile
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/Makefile	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/Makefile	(revision 17960)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.general
+include ../Makefile.conf.$(OSTYPE)
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Trigger
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mraw -I../mcalib
+
+SRCFILES = MTriggerIPR.cc \
+	   MTriggerCell.cc\
+	   MTriggerBit.cc\
+	   MTriggerPrescFact.cc\
+	   MTriggerLiveTime.cc \
+           MTriggerPattern.cc \
+           MTriggerPatternDecode.cc \
+           MFTriggerPattern.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: branches/Mars_McMismatchStudy/mtrigger/TriggerIncl.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/TriggerIncl.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/TriggerIncl.h	(revision 17960)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: branches/Mars_McMismatchStudy/mtrigger/TriggerLinkDef.h
===================================================================
--- branches/Mars_McMismatchStudy/mtrigger/TriggerLinkDef.h	(revision 17960)
+++ branches/Mars_McMismatchStudy/mtrigger/TriggerLinkDef.h	(revision 17960)
@@ -0,0 +1,17 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MTriggerIPR+;
+#pragma link C++ class MTriggerCell+;
+#pragma link C++ class MTriggerBit+;
+#pragma link C++ class MTriggerPrescFact+;
+#pragma link C++ class MTriggerLiveTime+;
+
+#pragma link C++ class MTriggerPattern+;
+#pragma link C++ class MTriggerPatternDecode+;
+#pragma link C++ class MFTriggerPattern+;
+
+#endif
Index: branches/Mars_McMismatchStudy/readcorsika.cc
===================================================================
--- branches/Mars_McMismatchStudy/readcorsika.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/readcorsika.cc	(revision 17960)
@@ -0,0 +1,204 @@
+#include <TClass.h>
+#include <TSystem.h>
+#include <TVector2.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+#include "MPrint.h"
+
+#include "MCorsikaRead.h"
+
+#include "MWriteRootFile.h"
+
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "            ReadCorsika - MARS V" << MARSVER        << endl;
+    gLog << "     MARS - Read and print corsika data files"      << endl;
+    gLog << "   Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   readcorsika [-h] [-?] [-vn] [-dec] [-a0] [-A=arrayNo] [-T=telescopeNo] inputfile[.raw] [outputfile[.root]]" << endl << endl;
+    gLog << "     inputfile:     corsika raw file or eventio file" << endl;
+    gLog << "     outputfile:    root file" << endl;
+    gLog << "   -A=arrayNo:      use data only of array number arrayNo" << endl;
+    gLog << "   -T=telescopeNo:  use data only of telescope number telescopeNo (used only for eventio input file)" << endl;
+    gLog << "   -ff                       Force reading of file even if problems occur" << endl;
+    gLog.Usage();
+//    gLog << "     -f:  force reading of runheader" << endl;
+    gLog << "     -?, -h, --help: This help" << endl << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    arg.RemoveRootArgs();
+
+    const Int_t  kCompLvl = arg.GetIntAndRemove("--comp=", 1);
+    const Int_t  kArrayNo = arg.GetIntAndRemove("-A=", -1);
+    const Int_t  kTelNo   = arg.GetIntAndRemove("-T=", -1);
+    const Bool_t kForce   = arg.HasOnlyAndRemove("-f");
+    const Bool_t kForceRd = arg.HasOnlyAndRemove("-ff");
+
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()<1 || arg.GetNumArguments()>2)
+    {
+        Usage();
+        return 2;
+    }
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    TString kNamein  = arg.GetArgumentStr(0);
+    TString kNameout = arg.GetArgumentStr(1);
+  
+//    if (!kNamein.EndsWith(".raw") && !kNamein.EndsWith(".raw.gz"))
+//        kNamein += ".raw";
+
+    if (!kNameout.IsNull() && !kNameout.EndsWith(".root"))
+        kNameout += ".root";
+
+    //
+    // Initialize Non-GUI (batch) mode
+    //
+    TObject::Class()->IgnoreTObjectStreamer();
+    TVector2::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    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 2;
+    }
+
+    //
+    //  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 ----
+    //
+    /*
+    MCorsikaRunHeader runheader;
+    plist.AddToList(&runheader);
+
+    MCorsikaEvtHeader evtheader;
+    plist.AddToList(&evtheader);
+
+    MCorsikaData evtdata;
+    plist.AddToList(&evtdata);
+    */
+    //
+    // 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 MCorsikaRead::PreProcess
+    //
+    MCorsikaRead read(kNamein);
+    read.SetForceMode(kForceRd);
+    read.SetArrayIdx(kArrayNo);
+    read.SetTelescopeIdx(kTelNo);
+    tasks.AddToList(&read);
+
+    MPrint print0;
+    MPrint print1("MCorsikaEvtHeader", "", "PrintEvtHeader");
+    MPrint print4("MPhotonEvent",      "", "PrintEvent");
+
+    MWriteRootFile write(kNameout, kForce?"RECREATE":"NEW", "Corsika File", kCompLvl);
+    write.AddContainer("MCorsikaRunHeader", "RunHeaders");
+    write.AddContainer("MCorsikaEvtHeader", "Events");
+    write.AddContainer("MPhotonEvent",      "Events");
+
+    if (kNameout.IsNull())
+    {
+        tasks.AddToList(&print0);
+        tasks.AddToList(&print1);
+        if (gLog.GetDebugLevel()>2)
+            tasks.AddToList(&print4);
+    }
+    else
+        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 (MCorsikaRead) and
+    // write all the information into a root file (MCorsikaFileWrite)
+    //
+    // between reading and writing we can do, transformations, checks, etc.
+    // (I'm think of a task like MCorsikaDataCheck)
+    //
+    if (!magic.Eventloop())
+    {
+        gLog << err << "ERROR: Reading Corsika file failed!" << endl;
+        return 2;
+    }
+
+    gLog << all << "Reading Corsika file finished successfull!" << endl;
+
+    // end of small readin program
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/readdaq.cc
===================================================================
--- branches/Mars_McMismatchStudy/readdaq.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/readdaq.cc	(revision 17960)
@@ -0,0 +1,211 @@
+#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 "MRawFitsRead.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 with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << 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|.fits]" << endl << endl;
+    gLog << "     input file:   Magic DAQ binary file." << endl;
+    gLog.Usage();
+    gLog << "     -d1: print data in decimal values" << endl;
+    gLog << "     -c1: print MRawCrateArray data" << endl;
+    gLog << "     -ff: force reading of broken runheader" << endl;
+    gLog << "     -f:  force reading of files with problems" << endl;
+    gLog << "     -?, -h, --help: This help" << endl << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    arg.RemoveRootArgs();
+
+    //
+    // Set verbosity to highest level.
+    //
+    const Bool_t kDecimal    = arg.HasOption("-d") && arg.GetIntAndRemove("-d")==1;
+    const Bool_t kPrintArray = arg.HasOption("-c") && arg.GetIntAndRemove("-c")==1;
+    const Bool_t kForce      = arg.HasOnlyAndRemove("-ff");
+    const Bool_t kForceMode  = arg.HasOnlyAndRemove("-f");
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return 2;
+    }
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    TString kNamein = arg.GetArgumentStr(0);
+  
+    if (!kNamein.EndsWith(".raw")  && !kNamein.EndsWith(".raw.gz") &&
+        !kNamein.EndsWith(".fits") && !kNamein.EndsWith(".fits.gz"))
+        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 2;
+    }
+
+    //
+    //  open the file
+    //
+    gLog << " Open the file '" << kNamein << "'" << endl;
+
+
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MParList plist;
+
+    MTaskList tasks;
+    tasks.SetOwner();
+    plist.AddToList(&tasks);
+
+    //
+    // ---- The following is only necessary to supress some output ----
+    //
+    MRawRunHeader runheader;
+    plist.AddToList(&runheader);
+
+    MRawEvtHeader evtheader;
+    plist.AddToList(&evtheader);
+
+    MRawEvtData evtdata;
+    plist.AddToList(&evtdata);
+
+    MRawEvtData evtdata2("MRawEvtData2");
+    plist.AddToList(&evtdata2);
+
+    MRawCrateArray cratearray;
+    plist.AddToList(&cratearray);
+
+    MTime evttime;
+    plist.AddToList(&evttime);
+
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    MRawFileRead *read = MRawFitsRead::IsFits(kNamein) ? new MRawFitsRead(kNamein) : new MRawFileRead(kNamein);
+    read->SetBit(kCanDelete);
+    read->SetForce(kForce);
+    read->SetForceMode(kForceMode);
+    tasks.AddToList(read);
+
+    MPrint print0;
+    MPrint print1("MRawEvtHeader",  "nogains",            "PrintEvtHeader");
+    MPrint print2("MTime",          "",                   "PrintTime");
+    MPrint print3("MRawCrateArray", "",                   "PrintCrateArray");
+    MPrint print4("MRawEvtData",    kDecimal?"dec":"hex", "PrintEvtData");
+    MPrint print5("MRawEvtData2",   kDecimal?"dec":"hex", "PrintEvtData2");
+
+    tasks.AddToList(&print0);
+    tasks.AddToList(&print1);
+    tasks.AddToList(&print2);
+    if (kPrintArray)
+        tasks.AddToList(&print3);
+    tasks.AddToList(&print4);
+    tasks.AddToList(&print5);
+
+    //
+    // create the looping object and tell it about the parameters to use
+    // and the tasks to execute
+    //
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    //
+    // Start the eventloop which reads the raw file (MRawFileRead) and
+    // write all the information into a root file (MRawFileWrite)
+    //
+    // between reading and writing we can do, transformations, checks, etc.
+    // (I'm think of a task like MRawDataCheck)
+    //
+    if (!magic.Eventloop())
+    {
+        gLog << err << "ERROR: Reading DAQ file failed!" << endl;
+        return 2;
+    }
+
+    gLog << all << "Reading DAQ file finished successfull!" << endl;
+
+    // end of small readin program
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/readraw.cc
===================================================================
--- branches/Mars_McMismatchStudy/readraw.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/readraw.cc	(revision 17960)
@@ -0,0 +1,225 @@
+#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 with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << 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.Usage();
+    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)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    // Evaluate arguments
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    // check for the right usage of the program
+    if (arg.HasOption("-?") || arg.HasOption("-h") || arg.HasOption("--help") ||
+        arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return 2;
+    }
+
+    arg.RemoveRootArgs();
+
+    // 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;
+    }
+
+    //
+    // Initialize Non-GUI (batch) mode
+    //
+    gROOT->SetBatch();
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    TString kNamein = arg.GetArgumentStr(0);
+  
+    //
+    // check whether the given files are OK.
+    //
+    if (gSystem->AccessPathName(kNamein, kFileExists))
+    {
+        if (!kNamein.EndsWith(".root"))
+            kNamein += ".root";
+
+        if (gSystem->AccessPathName(kNamein, kFileExists))
+        {
+            gLog << err << "Sorry, the input file '" << kNamein << "' doesn't exist." << endl;
+            return 2;
+        }
+    }
+
+    //
+    //  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 2;
+    }
+
+    //
+    //  check the branches in the Tree 
+    //
+    gLog << " Check all the Branches in the Tree." << endl;
+    gLog << endl;
+
+    MRawEvtHeader  *evtheader = NULL;
+    MTime          *evttime   = NULL;
+    MRawEvtData    *evtdata   = NULL;
+    MRawEvtData    *evtdata2  = NULL;
+    MRawCrateArray *evtcrate  = NULL;
+    MMcEvt         *evtmc     = NULL;
+    MMcTrig        *trigmc    = NULL;
+
+    EnableBranch(evttree, "MRawEvtHeader",  &evtheader);
+    EnableBranch(evttree, "MTime",          &evttime);
+    EnableBranch(evttree, "MRawEvtData",    &evtdata);
+    EnableBranch(evttree, "MRawEvtData2",   &evtdata2);
+    EnableBranch(evttree, "MRawCrateArray", &evtcrate);
+    EnableBranch(evttree, "MMcEvt",         &evtmc);
+    EnableBranch(evttree, "MMcTrig",        &trigmc);
+
+    //
+    // loop over all entries 
+    //
+    const Int_t nent = (Int_t)evttree->GetEntries();
+
+    gLog << " Entries in Tree Data: " << dec << nent << endl;
+    gLog << endl;
+
+    for (Int_t i = 0; i<nent; i++)
+    {
+        gLog << all << "Entry: " << i << endl;
+
+        //
+        // readin event with the selected branches
+        //
+        evttree->GetEvent(i);
+
+        if (evtmc)
+            evtmc->Print();
+        if (trigmc)
+            trigmc->Print("short");
+        if (evtheader)
+            evtheader->Print();
+        if (evttime)
+            evttime->Print();
+        if (evtcrate)
+            evtcrate->Print();
+        if (evtdata)
+            evtdata->Print(kDecimal?"dec":"hex");
+        if (evtdata2)
+            evtdata2->Print(kDecimal?"dec":"hex");
+
+        gLog << endl;
+    } 
+    
+    // end of small readin program
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/resmc/atmosphere-aerosols.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/atmosphere-aerosols.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/atmosphere-aerosols.txt	(revision 17960)
@@ -0,0 +1,18 @@
+# Wavelength dependant aerosol scattering coefficient at sea level 
+# (units: km^-1)
+
+280  0.27
+300  0.26
+320  0.25
+340  0.24
+360  0.24
+380  0.23
+400  0.20
+450  0.180
+500  0.167
+550  0.158
+600  0.150
+650  0.142
+700  0.135
+800  0.127
+900  0.120
Index: branches/Mars_McMismatchStudy/resmc/atmosphere-ozone.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/atmosphere-ozone.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/atmosphere-ozone.txt	(revision 17960)
@@ -0,0 +1,17 @@
+# Vigroux ozone absorption coefficients (cm-1)
+
+280  1.06e2
+300  1.01e1
+320  8.98e-1
+340  6.40e-2
+360  1.80e-3
+380  0
+400  0
+450  3.50e-3
+500  3.45e-2
+550  9.20e-2
+600  1.32e-1
+650  6.20e-2
+700  2.30e-2
+800  1.00e-2
+900  0
Index: branches/Mars_McMismatchStudy/resmc/ct1-pde.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/ct1-pde.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/ct1-pde.txt	(revision 17960)
@@ -0,0 +1,23 @@
+260 0
+280 0
+300 0.050
+320 0.235
+340 0.260
+360 0.260
+380 0.245
+400 0.230
+420 0.215
+440 0.193
+460 0.160
+480 0.140
+500 0.120
+520 0.080
+540 0.060
+560 0.045
+580 0.030
+600 0.020
+620 0.005
+640 0
+660 0
+680 0
+700 0
Index: branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-apdmap.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-apdmap.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-apdmap.txt	(revision 17960)
@@ -0,0 +1,703 @@
+0 4 5 6 
+1 7 18 36 
+2 8 9 10 
+3 11 12 26 
+13 14 28 29 
+15 30 31 32 
+16 17 33 34 
+19 37 60 90 
+20 21 38 39 
+22 40 41 42 
+23 24 43 44 
+25 45 46 72 
+27 47 48 74 
+49 50 76 77 
+51 52 78 79 
+53 80 81 82 
+54 55 83 84 
+56 57 85 86 
+35 58 59 88 
+61 91 126 168 
+62 63 92 93 
+64 65 94 95 
+66 96 97 98 
+67 68 99 100 
+69 70 101 102 
+71 103 104 142 
+73 105 106 144 
+75 107 108 146 
+109 110 148 149 
+111 112 150 151 
+113 114 152 153 
+115 154 155 156 
+116 117 157 158 
+118 119 159 160 
+120 121 161 162 
+87 122 123 164 
+89 124 125 166 
+127 169 216 270 
+128 129 170 171 
+130 131 172 173 
+132 133 174 175 
+134 176 177 178 
+135 136 179 180 
+137 138 181 182 
+139 140 183 184 
+141 185 186 236 
+143 187 188 238 
+145 189 190 240 
+147 191 192 242 
+193 194 244 245 
+195 196 246 247 
+197 198 248 249 
+199 200 250 251 
+201 252 253 254 
+202 203 255 256 
+204 205 257 258 
+206 207 259 260 
+208 209 261 262 
+163 210 211 264 
+165 212 213 266 
+167 214 215 268 
+217 271 330 396 
+218 219 272 273 
+220 221 274 275 
+222 223 276 277 
+224 225 278 279 
+226 280 281 282 
+227 228 283 284 
+229 230 285 286 
+231 232 287 288 
+233 234 289 290 
+235 291 292 354 
+237 293 294 356 
+239 295 296 358 
+241 297 298 360 
+243 299 300 362 
+301 302 364 365 
+303 304 366 367 
+305 306 368 369 
+307 308 370 371 
+309 310 372 373 
+311 374 375 376 
+312 313 377 378 
+314 315 379 380 
+316 317 381 382 
+318 319 383 384 
+320 321 385 386 
+263 322 323 388 
+265 324 325 390 
+267 326 327 392 
+269 328 329 394 
+331 397 468 546 
+332 333 398 399 
+334 335 400 401 
+336 337 402 403 
+338 339 404 405 
+340 341 406 407 
+342 408 409 410 
+343 344 411 412 
+345 346 413 414 
+347 348 415 416 
+349 350 417 418 
+351 352 419 420 
+353 421 422 496 
+355 423 424 498 
+357 425 426 500 
+359 427 428 502 
+361 429 430 504 
+363 431 432 506 
+433 434 508 509 
+435 436 510 511 
+437 438 512 513 
+439 440 514 515 
+441 442 516 517 
+443 444 518 519 
+445 520 521 522 
+446 447 523 524 
+448 449 525 526 
+450 451 527 528 
+452 453 529 530 
+454 455 531 532 
+456 457 533 534 
+387 458 459 536 
+389 460 461 538 
+391 462 463 540 
+393 464 465 542 
+395 466 467 544 
+469 547 630 720 
+470 471 548 549 
+472 473 550 551 
+474 475 552 553 
+476 477 554 555 
+478 479 556 557 
+480 481 558 559 
+482 560 561 562 
+483 484 563 564 
+485 486 565 566 
+487 488 567 568 
+489 490 569 570 
+491 492 571 572 
+493 494 573 574 
+495 575 576 662 
+497 577 578 664 
+499 579 580 666 
+501 581 582 668 
+503 583 584 670 
+505 585 586 672 
+507 587 588 674 
+589 590 676 677 
+591 592 678 679 
+593 594 680 681 
+595 596 682 683 
+597 598 684 685 
+599 600 686 687 
+601 602 688 689 
+603 690 691 692 
+604 605 693 694 
+606 607 695 696 
+608 609 697 698 
+610 611 699 700 
+612 613 701 702 
+614 615 703 704 
+616 617 705 706 
+535 618 619 708 
+537 620 621 710 
+539 622 623 712 
+541 624 625 714 
+543 626 627 716 
+545 628 629 718 
+631 721 816 918 
+632 633 722 723 
+634 635 724 725 
+636 637 726 727 
+638 639 728 729 
+640 641 730 731 
+642 643 732 733 
+644 645 734 735 
+646 736 737 738 
+647 648 739 740 
+649 650 741 742 
+651 652 743 744 
+653 654 745 746 
+655 656 747 748 
+657 658 749 750 
+659 660 751 752 
+661 753 754 852 
+663 755 756 854 
+665 757 758 856 
+667 759 760 858 
+669 761 762 860 
+671 763 764 862 
+673 765 766 864 
+675 767 768 866 
+769 770 868 869 
+771 772 870 871 
+773 774 872 873 
+775 776 874 875 
+777 778 876 877 
+779 780 878 879 
+781 782 880 881 
+783 784 882 883 
+785 884 885 886 
+786 787 887 888 
+788 789 889 890 
+790 791 891 892 
+792 793 893 894 
+794 795 895 896 
+796 797 897 898 
+798 799 899 900 
+800 801 901 902 
+707 802 803 904 
+709 804 805 906 
+711 806 807 908 
+713 808 809 910 
+715 810 811 912 
+717 812 813 914 
+719 814 815 916 
+817 919 1026 1140 
+818 819 920 921 
+820 821 922 923 
+822 823 924 925 
+824 825 926 927 
+826 827 928 929 
+828 829 930 931 
+830 831 932 933 
+832 833 934 935 
+834 936 937 938 
+835 836 939 940 
+837 838 941 942 
+839 840 943 944 
+841 842 945 946 
+843 844 947 948 
+845 846 949 950 
+847 848 951 952 
+849 850 953 954 
+851 955 956 1066 
+853 957 958 1068 
+855 959 960 1070 
+857 961 962 1072 
+859 963 964 1074 
+861 965 966 1076 
+863 967 968 1078 
+865 969 970 1080 
+867 971 972 1082 
+973 974 1084 1085 
+975 976 1086 1087 
+977 978 1088 1089 
+979 980 1090 1091 
+981 982 1092 1093 
+983 984 1094 1095 
+985 986 1096 1097 
+987 988 1098 1099 
+989 990 1100 1101 
+991 1102 1103 1104 
+992 993 1105 1106 
+994 995 1107 1108 
+996 997 1109 1110 
+998 999 1111 1112 
+1000 1001 1113 1114 
+1002 1003 1115 1116 
+1004 1005 1117 1118 
+1006 1007 1119 1120 
+1008 1009 1121 1122 
+903 1010 1011 1124 
+905 1012 1013 1126 
+907 1014 1015 1128 
+909 1016 1017 1130 
+911 1018 1019 1132 
+913 1020 1021 1134 
+915 1022 1023 1136 
+917 1024 1025 1138 
+1027 1141 1260 1386 
+1028 1029 1142 1143 
+1030 1031 1144 1145 
+1032 1033 1146 1147 
+1034 1035 1148 1149 
+1036 1037 1150 1151 
+1038 1039 1152 1153 
+1040 1041 1154 1155 
+1042 1043 1156 1157 
+1044 1045 1158 1159 
+1046 1160 1161 1162 
+1047 1048 1163 1164 
+1049 1050 1165 1166 
+1051 1052 1167 1168 
+1053 1054 1169 1170 
+1055 1056 1171 1172 
+1057 1058 1173 1174 
+1059 1060 1175 1176 
+1061 1062 1177 1178 
+1063 1064 1179 1180 
+1065 1181 1182 1304 
+1067 1183 1184 1306 
+1069 1185 1186 1308 
+1071 1187 1188 1310 
+1073 1189 1190 1312 
+1075 1191 1192 1314 
+1077 1193 1194 1316 
+1079 1195 1196 1318 
+1081 1197 1198 1320 
+1083 1199 1200 1322 
+1201 1202 1324 1325 
+1203 1204 1326 1327 
+1205 1206 1328 1329 
+1207 1208 1330 1331 
+1209 1210 1332 1333 
+1211 1212 1334 1335 
+1213 1214 1336 1337 
+1215 1216 1338 1339 
+1217 1218 1340 1341 
+1219 1220 1342 1343 
+1221 1344 1345 1346 
+1222 1223 1347 1348 
+1224 1225 1349 1350 
+1226 1227 1351 1352 
+1228 1229 1353 1354 
+1230 1231 1355 1356 
+1232 1233 1357 1358 
+1234 1235 1359 1360 
+1236 1237 1361 1362 
+1238 1239 1363 1364 
+1240 1241 1365 1366 
+1123 1242 1243 1368 
+1125 1244 1245 1370 
+1127 1246 1247 1372 
+1129 1248 1249 1374 
+1131 1250 1251 1376 
+1133 1252 1253 1378 
+1135 1254 1255 1380 
+1137 1256 1257 1382 
+1139 1258 1259 1384 
+1261 1387 1518 1656 
+1262 1263 1388 1389 
+1264 1265 1390 1391 
+1266 1267 1392 1393 
+1268 1269 1394 1395 
+1270 1271 1396 1397 
+1272 1273 1398 1399 
+1274 1275 1400 1401 
+1276 1277 1402 1403 
+1278 1279 1404 1405 
+1280 1281 1406 1407 
+1282 1408 1409 1410 
+1283 1284 1411 1412 
+1285 1286 1413 1414 
+1287 1288 1415 1416 
+1289 1290 1417 1418 
+1291 1292 1419 1420 
+1293 1294 1421 1422 
+1295 1296 1423 1424 
+1297 1298 1425 1426 
+1299 1300 1427 1428 
+1301 1302 1429 1430 
+1303 1431 1432 1566 
+1305 1433 1434 1568 
+1307 1435 1436 1570 
+1309 1437 1438 1572 
+1311 1439 1440 1574 
+1313 1441 1442 1576 
+1315 1443 1444 1578 
+1317 1445 1446 1580 
+1319 1447 1448 1582 
+1321 1449 1450 1584 
+1323 1451 1452 1586 
+1453 1454 1588 1589 
+1455 1456 1590 1591 
+1457 1458 1592 1593 
+1459 1460 1594 1595 
+1461 1462 1596 1597 
+1463 1464 1598 1599 
+1465 1466 1600 1601 
+1467 1468 1602 1603 
+1469 1470 1604 1605 
+1471 1472 1606 1607 
+1473 1474 1608 1609 
+1475 1610 1611 1612 
+1476 1477 1613 1614 
+1478 1479 1615 1616 
+1480 1481 1617 1618 
+1482 1483 1619 1620 
+1484 1485 1621 1622 
+1486 1487 1623 1624 
+1488 1489 1625 1626 
+1490 1491 1627 1628 
+1492 1493 1629 1630 
+1494 1495 1631 1632 
+1496 1497 1633 1634 
+1367 1498 1499 1636 
+1369 1500 1501 1638 
+1371 1502 1503 1640 
+1373 1504 1505 1642 
+1375 1506 1507 1644 
+1377 1508 1509 1646 
+1379 1510 1511 1648 
+1381 1512 1513 1650 
+1383 1514 1515 1652 
+1385 1516 1517 1654 
+1519 1657 1800 1950 
+1520 1521 1658 1659 
+1522 1523 1660 1661 
+1524 1525 1662 1663 
+1526 1527 1664 1665 
+1528 1529 1666 1667 
+1530 1531 1668 1669 
+1532 1533 1670 1671 
+1534 1535 1672 1673 
+1536 1537 1674 1675 
+1538 1539 1676 1677 
+1540 1541 1678 1679 
+1542 1680 1681 1682 
+1543 1544 1683 1684 
+1545 1546 1685 1686 
+1547 1548 1687 1688 
+1549 1550 1689 1690 
+1551 1552 1691 1692 
+1553 1554 1693 1694 
+1555 1556 1695 1696 
+1557 1558 1697 1698 
+1559 1560 1699 1700 
+1561 1562 1701 1702 
+1563 1564 1703 1704 
+1565 1705 1706 1852 
+1567 1707 1708 1854 
+1569 1709 1710 1856 
+1571 1711 1712 1858 
+1573 1713 1714 1860 
+1575 1715 1716 1862 
+1577 1717 1718 1864 
+1579 1719 1720 1866 
+1581 1721 1722 1868 
+1583 1723 1724 1870 
+1585 1725 1726 1872 
+1587 1727 1728 1874 
+1729 1730 1876 1877 
+1731 1732 1878 1879 
+1733 1734 1880 1881 
+1735 1736 1882 1883 
+1737 1738 1884 1885 
+1739 1740 1886 1887 
+1741 1742 1888 1889 
+1743 1744 1890 1891 
+1745 1746 1892 1893 
+1747 1748 1894 1895 
+1749 1750 1896 1897 
+1751 1752 1898 1899 
+1753 1900 1901 1902 
+1754 1755 1903 1904 
+1756 1757 1905 1906 
+1758 1759 1907 1908 
+1760 1761 1909 1910 
+1762 1763 1911 1912 
+1764 1765 1913 1914 
+1766 1767 1915 1916 
+1768 1769 1917 1918 
+1770 1771 1919 1920 
+1772 1773 1921 1922 
+1774 1775 1923 1924 
+1776 1777 1925 1926 
+1635 1778 1779 1928 
+1637 1780 1781 1930 
+1639 1782 1783 1932 
+1641 1784 1785 1934 
+1643 1786 1787 1936 
+1645 1788 1789 1938 
+1647 1790 1791 1940 
+1649 1792 1793 1942 
+1651 1794 1795 1944 
+1653 1796 1797 1946 
+1655 1798 1799 1948 
+1801 1951 2106 2269 
+1802 1803 1952 1953 
+1804 1805 1954 1955 
+1806 1807 1956 1957 
+1808 1809 1958 1959 
+1810 1811 1960 1961 
+1812 1813 1962 1963 
+1814 1815 1964 1965 
+1816 1817 1966 1967 
+1818 1819 1968 1969 
+1820 1821 1970 1971 
+1822 1823 1972 1973 
+1824 1825 1974 1975 
+1826 1976 1977 1978 
+1827 1828 1979 1980 
+1829 1830 1981 1982 
+1831 1832 1983 1984 
+1833 1834 1985 1986 
+1835 1836 1987 1988 
+1837 1838 1989 1990 
+1839 1840 1991 1992 
+1841 1842 1993 1994 
+1843 1844 1995 1996 
+1845 1846 1997 1998 
+1847 1848 1999 2000 
+1849 1850 2001 2002 
+1851 2003 2004 2161 
+1853 2005 2006 2163 
+1855 2007 2008 2165 
+1857 2009 2010 2167 
+1859 2011 2012 2169 
+1861 2013 2014 2171 
+1863 2015 2016 2173 
+1865 2017 2018 2175 
+1867 2019 2020 2177 
+1869 2021 2022 2179 
+1871 2023 2024 2181 
+1873 2025 2026 2183 
+1875 2027 2028 2185 
+2029 2030 2187 2188 
+2031 2032 2189 2190 
+2033 2034 2191 2192 
+2035 2036 2193 2194 
+2037 2038 2195 2196 
+2039 2040 2197 2198 
+2041 2042 2199 2200 
+2043 2044 2201 2202 
+2045 2046 2203 2204 
+2047 2048 2205 2206 
+2049 2050 2207 2208 
+2051 2052 2209 2210 
+2053 2054 2211 2212 
+2055 2213 2215 2216 
+2056 2057 2217 2218 
+2058 2059 2219 2220 
+2060 2061 2221 2222 
+2062 2063 2223 2224 
+2064 2065 2225 2226 
+2066 2067 2227 2228 
+2068 2069 2229 2230 
+2070 2071 2231 2232 
+2072 2073 2233 2234 
+2074 2075 2235 2236 
+2076 2077 2237 2238 
+2078 2079 2239 2240 
+2080 2081 2241 2242 
+1927 2082 2083 2245 
+1929 2084 2085 2247 
+1931 2086 2087 2249 
+1933 2088 2089 2251 
+1935 2090 2091 2253 
+1937 2092 2093 2255 
+1939 2094 2095 2257 
+1941 2096 2097 2259 
+1943 2098 2099 2261 
+1945 2100 2101 2263 
+1947 2102 2103 2265 
+1949 2104 2105 2267 
+2108 2109 2270 2271 
+2110 2111 2272 2273 
+2112 2113 2274 2275 
+2114 2115 2276 2277 
+2116 2117 2278 2279 
+2118 2119 2280 2281 
+2120 2121 2282 2283 
+2122 2123 2284 2285 
+2124 2125 2286 2287 
+2126 2127 2288 2289 
+2128 2129 2290 2291 
+2130 2131 2292 2293 
+2132 2133 2294 2295 
+2135 2136 2296 2297 
+2137 2138 2298 2299 
+2139 2140 2300 2301 
+2141 2142 2302 2303 
+2143 2144 2304 2305 
+2145 2146 2306 2307 
+2147 2148 2308 2309 
+2149 2150 2310 2311 
+2151 2152 2312 2313 
+2153 2154 2314 2315 
+2155 2156 2316 2317 
+2157 2158 2318 2319 
+2159 2160 2320 2321 
+2162 2322 2323 2478 
+2164 2324 2325 2480 
+2166 2326 2327 2482 
+2168 2328 2329 2484 
+2170 2330 2331 2486 
+2172 2332 2333 2488 
+2174 2334 2335 2490 
+2176 2336 2337 2492 
+2178 2338 2339 2494 
+2180 2340 2341 2496 
+2182 2342 2343 2498 
+2184 2344 2345 2500 
+2186 2346 2347 
+2348 2349 2350 2502 
+2351 2352 2503 2504 
+2353 2354 2506 
+2355 2356 2507 2508 
+2357 2358 2509 2510 
+2359 2360 2511 2512 
+2361 2362 2513 2514 
+2363 2364 2515 2516 
+2365 2366 2517 2518 
+2367 2368 2519 2520 
+2369 2370 2521 2522 
+2371 2372 2524 
+2214 2373 2374 2525 
+2375 2376 2377 2526 
+2378 2379 2527 2528 
+2380 2381 2529 2530 
+2382 2383 2531 2532 
+2384 2385 2533 2534 
+2386 2387 2535 2536 
+2388 2389 2537 2538 
+2390 2391 2539 2540 
+2392 2393 2541 2542 
+2394 2395 2543 2544 
+2396 2397 2545 2546 
+2398 2399 2547 2548 
+2400 2401 2402 2549 
+2243 2244 2403 2404 
+2246 2405 2406 2551 
+2248 2407 2408 
+2250 2409 2410 2555 
+2252 2411 2412 2557 
+2254 2413 2414 2559 
+2256 2415 2416 2561 
+2258 2417 2418 2563 
+2260 2419 2420 2565 
+2262 2421 2422 2567 
+2264 2423 2424 2569 
+2266 2425 2426 2571 
+2268 2427 2428 2573 
+2432 2433 2574 2575 
+2434 2435 2576 2577 
+2436 2437 2578 2579 
+2438 2439 2580 2581 
+2440 2441 2582 2583 
+2442 2443 2584 2585 
+2444 2445 2586 2587 
+2446 2447 2588 2589 
+2448 2449 2590 2591 
+2450 2451 2592 2593 
+2456 2457 2596 2597 
+2458 2459 2598 2599 
+2460 2461 2600 2601 
+2462 2463 2602 2603 
+2464 2465 2604 2605 
+2466 2467 2606 2607 
+2468 2469 2608 2609 
+2470 2471 2610 2611 
+2472 2473 2612 2613 
+2474 2475 2614 2615 
+2481 2617 2618 
+2483 2619 2620 2733 
+2485 2621 2622 2735 
+2487 2623 2624 2736 
+2489 2625 2626 
+2491 2627 2628 
+2493 2629 2630 2743 
+2495 2631 2632 2745 
+2497 2633 2634 2747 
+2499 2501 2635 2636 
+2505 2638 2639 
+2640 2641 2748 2749 
+2642 2643 2750 2751 
+2644 2645 2752 2753 
+2646 2647 2755 
+2648 2649 2757 
+2650 2651 2759 
+2652 2653 2760 2761 
+2654 2655 2762 2763 
+2523 2656 2657 
+2658 2659 
+2660 2661 2764 2765 
+2662 2663 2766 2767 
+2664 2665 2768 
+2666 2667 2770 
+2668 2669 2772 
+2670 2671 2774 2775 
+2672 2673 2776 2777 
+2674 2675 2778 
+2676 2677 2678 2779 
+2552 2553 2679 2680 
+2554 2681 2682 2780 
+2556 2683 2684 2782 
+2558 2685 2686 2783 
+2560 2687 2688 2786 
+2562 2689 2690 
+2564 2691 2692 2790 
+2566 2693 2694 2792 
+2568 2695 2696 2794 
+2570 2697 2698 
+2705 2706 2796 2797 
+2707 2708 2798 2799 
+2709 2710 2800 2801 
+2721 2722 2804 2805 
+2723 2724 2806 2807 
+2725 2726 2808 2809 
+2737 2738 2811 2812 
+2739 2740 2813 2814 
+2741 2742 2815 2816 
+2754 2817 2818 
+2756 2819 2820 
+2758 2821 2822 2823 
+2769 2824 2825 
+2771 2826 2827 
+2773 2828 2829 2830 
+2784 2785 2831 2832 
+2787 2788 2833 2834 
+2789 2791 2835 2836 
Index: branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-cones.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-cones.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-cones.txt	(revision 17960)
@@ -0,0 +1,90 @@
+0.5 0.942857
+1.5 0.882078
+2.5 0.893286
+3.5 0.893548
+4.5 0.884714
+5.5 0.877297
+6.5 0.889766
+7.5 0.88427
+8.5 0.867865
+9.5 0.857536
+10.5 0.858007
+11.5 0.838215
+12.5 0.827676
+13.5 0.809332
+14.5 0.775211
+15.5 0.74564
+16.5 0.693656
+17.5 0.63983
+18.5 0.565555
+19.5 0.487428
+20.5 0.418415
+21.5 0.334325
+22.5 0.220308
+23.5 0.14511
+24.5 0.0983764
+25.5 0.079236
+26.5 0.0281795
+27.5 0.00349249
+28.5 0.00335294
+29.5 0
+30.5 0
+31.5 0
+32.5 0.00327273
+33.5 0
+34.5 0
+35.5 0.00169173
+36.5 0
+37.5 0
+38.5 0.0014311
+39.5 0
+40.5 0
+41.5 0
+42.5 0
+43.5 0
+44.5 0
+45.5 0
+46.5 0
+47.5 0
+48.5 0
+49.5 0
+50.5 0
+51.5 0
+52.5 0
+53.5 0
+54.5 0
+55.5 0
+56.5 0
+57.5 0
+58.5 0
+59.5 0
+60.5 0
+61.5 0
+62.5 0
+63.5 0
+64.5 0
+65.5 0
+66.5 0
+67.5 0
+68.5 0
+69.5 0
+70.5 0
+71.5 0
+72.5 0
+73.5 0
+74.5 0
+75.5 0
+76.5 0
+77.5 0
+78.5 0
+79.5 0
+80.5 0
+81.5 0
+82.5 0
+83.5 0
+84.5 0
+85.5 0
+86.5 0
+87.5 0
+88.5 0
+89.5 0
Index: branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-pde-gapd.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-pde-gapd.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-pde-gapd.txt	(revision 17960)
@@ -0,0 +1,48 @@
+280 0
+320 0.14
+360 0.2483
+369.655 0.272855
+380.359 0.30322
+392.682 0.328166
+400 0.3427
+410 0.36
+420 0.3791
+429.652 0.394688
+440 0.4056
+450 0.4111
+460 0.4132
+469.397 0.413991
+480 0.4125
+487.328 0.409247
+500 0.4052
+509.192 0.397064
+520 0.3869
+530 0.3736
+540 0.3634
+550 0.35
+560 0.3368
+570 0.325
+580 0.3114
+590 0.2987
+600 0.2847
+610 0.2726
+616.74 0.261643
+626.822 0.250952
+636.905 0.241449
+646.987 0.22957
+660 0.2192
+670 0.2099
+680 0.2028
+690 0.1933
+700 0.1847
+710 0.1778
+720 0.1699
+730 0.1616
+740 0.1526
+750 0.1464
+760 0.138
+770 0.1308
+780 0.1232
+790 0.1158
+846.399 0.0751422
+950 0
Index: branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-reflectivity.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-reflectivity.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-reflectivity.txt	(revision 17960)
@@ -0,0 +1,14 @@
+280 0.810
+290 0.857
+310 0.893
+330 0.912
+360 0.923
+390 0.924
+430 0.917
+475 0.902
+530 0.873
+620 0.811
+710 0.749
+800 0.687
+890 0.625
+980 0.563
Index: branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-reflector.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-reflector.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/dwarf/dwarf-reflector.txt	(revision 17960)
@@ -0,0 +1,41 @@
+  60    0.0000  1.84098  -0.0612508 -0.0000000 0.998122 490.712  Hex 59.5
+  30   51.9615  1.84098  -0.0306254 -0.0530447 0.998122 490.712  Hex 59.5
+ -30   51.9615  1.84098   0.0306254 -0.0530447 0.998122 490.712  Hex 59.5
+ -60    0.0000  1.84098   0.0612508 -0.0000000 0.998122 490.712  Hex 59.5
+ -30  -51.9615  1.84098   0.0306254  0.0530447 0.998122 490.712  Hex 59.5
+  30  -51.9615  1.84098  -0.0306254  0.0530447 0.998122 490.712  Hex 59.5
+ 120    0.0000  7.36392  -0.1218180 -0.0000000 0.992552 496.248  Hex 59.5
+  90   51.9615  5.52294  -0.0915334 -0.0528468 0.994399 494.401  Hex 59.5
+  60  103.9230  7.36392  -0.0609090 -0.1054970 0.992552 496.248  Hex 59.5
+   0  103.9230  5.52294  -0.0000000 -0.1056940 0.994399 494.401  Hex 59.5
+ -60  103.9230  7.36392   0.0609090 -0.1054970 0.992552 496.248  Hex 59.5
+ -90   51.9615  5.52294   0.0915334 -0.0528468 0.994399 494.401  Hex 59.5
+-120    0.0000  7.36392   0.1218180 -0.0000000 0.992552 496.248  Hex 59.5
+ -90  -51.9615  5.52294   0.0915334  0.0528468 0.994399 494.401  Hex 59.5
+ -60 -103.9230  7.36392   0.0609090  0.1054970 0.992552 496.248  Hex 59.5
+   0 -103.9230  5.52294  -0.0000000  0.1056940 0.994399 494.401  Hex 59.5
+  60 -103.9230  7.36392  -0.0609090  0.1054970 0.992552 496.248  Hex 59.5
+  90  -51.9615  5.52294  -0.0915334  0.0528468 0.994399 494.401  Hex 59.5
+ 150   51.9615 12.88690  -0.1514320 -0.0524576 0.987075 501.799  Hex 59.5
+ 120  103.9230 12.88690  -0.1211460 -0.1049150 0.987075 501.799  Hex 59.5
+  30  155.8850 12.88690  -0.0302864 -0.1573730 0.987075 501.799  Hex 59.5
+ -30  155.8850 12.88690   0.0302864 -0.1573730 0.987075 501.799  Hex 59.5
+-120  103.9230 12.88690   0.1211460 -0.1049150 0.987075 501.799  Hex 59.5
+-150   51.9615 12.88690   0.1514320 -0.0524576 0.987075 501.799  Hex 59.5
+-150  -51.9615 12.88690   0.1514320  0.0524576 0.987075 501.799  Hex 59.5
+-120 -103.9230 12.88690   0.1211460  0.1049150 0.987075 501.799  Hex 59.5
+ -30 -155.8850 12.88690   0.0302864  0.1573730 0.987075 501.799  Hex 59.5
+  30 -155.8850 12.88690  -0.0302864  0.1573730 0.987075 501.799  Hex 59.5
+ 120 -103.9230 12.88690  -0.1211460  0.1049150 0.987075 501.799  Hex 59.5
+ 150  -51.9615 12.88690  -0.1514320  0.0524576 0.987075 501.799  Hex 59.5
+ 210   51.9615 23.93270  -0.2097090 -0.0518896 0.976386 512.949  Hex 59.5
+ 180  103.9230 22.09180  -0.1800740 -0.1039660 0.978143 511.087  Hex 59.5
+ 150  155.8850 23.93270  -0.1497920 -0.1556690 0.976386 512.949  Hex 59.5
+ 120  207.8460 29.45570  -0.1191940 -0.2064490 0.971170 518.547  Hex 59.5
+  60  207.8460 23.93270  -0.0599169 -0.2075580 0.976386 512.949  Hex 59.5
+   0  207.8460 22.09180  -0.0000000 -0.2079320 0.978143 511.087  Hex 59.5
+ -60  207.8460 23.93270   0.0599169 -0.2075580 0.976386 512.949  Hex 59.5
+-120  207.8460 29.45570   0.1191940 -0.2064490 0.971170 518.547  Hex 59.5
+-150  155.8850 23.93270   0.1497920 -0.1556690 0.976386 512.949  Hex 59.5
+-180  103.9230 22.09180   0.1800740 -0.1039660 0.978143 511.087  Hex 59.5
+-210   51.9615 23.93270   0.2097090 -0.0518896 0.976386 512.949  Hex 59.5
Index: branches/Mars_McMismatchStudy/resmc/fact/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt	(revision 17960)
@@ -0,0 +1,603 @@
+ 200 0.5271       
+# 201 0.5420       
+# 202 0.5569       
+# 203 0.5714       
+# 204 0.5852       
+ 205 0.5988       
+# 206 0.6117       
+# 207 0.6240       
+# 208 0.6355       
+# 209 0.6465       
+ 210 0.6569       
+# 211 0.6665       
+# 212 0.6755       
+# 213 0.6840       
+# 214 0.6916       
+ 215 0.6987       
+# 216 0.7053       
+# 217 0.7111       
+# 218 0.7166       
+# 219 0.7216       
+ 220 0.7260       
+# 221 0.7302       
+# 222 0.7336       
+# 223 0.7368       
+# 224 0.7397       
+ 225 0.7423       
+# 226 0.7446       
+# 227 0.7465       
+# 228 0.7484       
+# 229 0.7498       
+ 230 0.7509       
+# 231 0.7518       
+# 232 0.7527       
+# 233 0.7532       
+# 234 0.7534       
+# 235 0.7535       
+# 236 0.7532       
+# 237 0.7529       
+# 238 0.7525       
+ 239 0.7517       
+# 240 0.7509       
+# 241 0.7499       
+# 242 0.7486       
+# 243 0.7472       
+ 244 0.7458       
+# 245 0.7442       
+# 246 0.7424       
+# 247 0.7405       
+# 248 0.7385       
+ 249 0.7365       
+# 250 0.7343       
+# 251 0.7322       
+# 252 0.7297       
+# 253 0.7273       
+ 254 0.7250       
+# 255 0.7226       
+# 256 0.7204       
+# 257 0.7179       
+# 258 0.7156       
+ 259 0.7134       
+# 260 0.7113       
+# 261 0.7093       
+# 262 0.7074       
+# 263 0.7056       
+ 264 0.7039       
+# 265 0.7023       
+# 266 0.7009       
+# 267 0.6995       
+# 268 0.6984       
+# 269 0.6976       
+# 270 0.6968       
+# 271 0.6963       
+# 272 0.6960       
+ 273 0.6961       
+# 274 0.6964       
+# 275 0.6967       
+# 276 0.6972       
+# 277 0.6981       
+ 278 0.6991       
+# 279 0.7003       
+# 280 0.7019       
+# 281 0.7036       
+# 282 0.7055       
+ 283 0.7075       
+# 284 0.7098       
+# 285 0.7123       
+# 286 0.7149       
+# 287 0.7174       
+ 288 0.7202       
+# 289 0.7233       
+# 290 0.7265       
+# 291 0.7295       
+# 292 0.7328       
+ 293 0.7361       
+# 294 0.7395       
+# 295 0.7430       
+# 296 0.7464       
+# 297 0.7500       
+ 298 0.7534       
+# 299 0.7568       
+# 300 0.7605       
+# 301 0.7641       
+# 302 0.7673       
+# 303 0.7707       
+# 304 0.7743       
+# 305 0.7777       
+# 306 0.7812       
+ 307 0.7846       
+# 308 0.7879       
+# 309 0.7912       
+# 310 0.7944       
+# 311 0.7975       
+ 312 0.8007       
+# 313 0.8037       
+# 314 0.8065       
+# 315 0.8095       
+# 316 0.8124       
+ 317 0.8152       
+# 318 0.8161       
+# 319 0.8180       
+# 320 0.8207       
+# 321 0.8232       
+ 322 0.8255       
+# 323 0.8275       
+# 324 0.8302       
+# 325 0.8325       
+# 326 0.8346       
+ 327 0.8368       
+# 328 0.8390       
+# 329 0.8412       
+# 330 0.8429       
+# 331 0.8448       
+ 332 0.8466       
+# 333 0.8484       
+# 334 0.8501       
+# 335 0.8519       
+# 336 0.8535       
+# 337 0.8553       
+# 338 0.8569       
+# 339 0.8583       
+# 340 0.8597       
+ 341 0.8610       
+# 342 0.8626       
+# 343 0.8636       
+# 344 0.8648       
+# 345 0.8662       
+ 346 0.8674       
+# 347 0.8683       
+# 348 0.8695       
+# 349 0.8706       
+# 350 0.8716       
+ 351 0.8726       
+# 352 0.8737       
+# 353 0.8747       
+# 354 0.8755       
+# 355 0.8766       
+ 356 0.8772       
+# 357 0.8782       
+# 358 0.8787       
+# 359 0.8798       
+# 360 0.8804       
+ 361 0.8810       
+# 362 0.8818       
+# 363 0.8823       
+# 364 0.8828       
+# 365 0.8836       
+ 366 0.8842       
+# 367 0.8851       
+# 368 0.8851       
+# 369 0.8857       
+# 370 0.8864       
+# 371 0.8872       
+# 372 0.8876       
+# 373 0.8879       
+# 374 0.8882       
+ 375 0.8886       
+# 376 0.8890       
+# 377 0.8893       
+# 378 0.8897       
+# 379 0.8912       
+ 380 0.8912       
+# 381 0.8916       
+# 382 0.8921       
+# 383 0.8922       
+# 384 0.8927       
+ 385 0.8930       
+# 386 0.8931       
+# 387 0.8935       
+# 388 0.8936       
+# 389 0.8940       
+ 390 0.8938       
+# 391 0.8945       
+# 392 0.8946       
+# 393 0.8948       
+# 394 0.8951       
+ 395 0.8949       
+# 396 0.8952       
+# 397 0.8955       
+# 398 0.8956       
+# 399 0.8958       
+ 400 0.8958       
+# 401 0.8958       
+# 402 0.8960       
+# 403 0.8962       
+# 404 0.8963       
+# 405 0.8963       
+# 406 0.8965       
+# 407 0.8965       
+# 408 0.8966       
+ 409 0.8965       
+# 410 0.8968       
+# 411 0.8967       
+# 412 0.8970       
+# 413 0.8968       
+ 414 0.8966       
+# 415 0.8965       
+# 416 0.8967       
+# 417 0.8967       
+# 418 0.8967       
+ 419 0.8967       
+# 420 0.8967       
+# 421 0.8968       
+# 422 0.8965       
+# 423 0.8966       
+ 424 0.8966       
+# 425 0.8965       
+# 426 0.8965       
+# 427 0.8965       
+# 428 0.8962       
+ 429 0.8962       
+# 430 0.8960       
+# 431 0.8959       
+# 432 0.8957       
+# 433 0.8958       
+ 434 0.8957       
+# 435 0.8957       
+# 436 0.8955       
+# 437 0.8954       
+# 438 0.8951       
+# 439 0.8951       
+# 440 0.8949       
+# 441 0.8947       
+# 442 0.8944       
+ 443 0.8941       
+# 444 0.8941       
+# 445 0.8939       
+# 446 0.8939       
+# 447 0.8939       
+ 448 0.8938       
+# 449 0.8938       
+# 450 0.8938       
+# 451 0.8939       
+# 452 0.8940       
+ 453 0.8940       
+# 454 0.8942       
+# 455 0.8943       
+# 456 0.8943       
+# 457 0.8944       
+ 458 0.8942       
+# 459 0.8943       
+# 460 0.8942       
+# 461 0.8943       
+# 462 0.8943       
+ 463 0.8940       
+# 464 0.8937       
+# 465 0.8934       
+# 466 0.8931       
+# 467 0.8929       
+ 468 0.8927       
+# 469 0.8924       
+# 470 0.8920       
+# 471 0.8917       
+# 472 0.8912       
+# 473 0.8908       
+# 474 0.8903       
+# 475 0.8898       
+# 476 0.8894       
+ 477 0.8890       
+# 478 0.8885       
+# 479 0.8880       
+# 480 0.8875       
+# 481 0.8869       
+ 482 0.8863       
+# 483 0.8857       
+# 484 0.8851       
+# 485 0.8846       
+# 486 0.8843       
+ 487 0.8840       
+# 488 0.8838       
+# 489 0.8837       
+# 490 0.8836       
+# 491 0.8834       
+ 492 0.8834       
+# 493 0.8834       
+# 494 0.8833       
+# 495 0.8833       
+# 496 0.8832       
+ 497 0.8831       
+# 498 0.8830       
+# 499 0.8829       
+# 500 0.8828       
+# 501 0.8828       
+ 502 0.8826       
+# 503 0.8824       
+# 504 0.8821       
+# 505 0.8818       
+# 506 0.8814       
+# 507 0.8810       
+# 508 0.8806       
+# 509 0.8801       
+# 510 0.8796       
+ 511 0.8793       
+# 512 0.8790       
+# 513 0.8787       
+# 514 0.8782       
+# 515 0.8776       
+ 516 0.8771       
+# 517 0.8766       
+# 518 0.8759       
+# 519 0.8754       
+# 520 0.8750       
+ 521 0.8745       
+# 522 0.8742       
+# 523 0.8738       
+# 524 0.8733       
+# 525 0.8729       
+ 526 0.8723       
+# 527 0.8718       
+# 528 0.8711       
+# 529 0.8705       
+# 530 0.8700       
+ 531 0.8696       
+# 532 0.8692       
+# 533 0.8688       
+# 534 0.8685       
+# 535 0.8679       
+ 536 0.8674       
+# 537 0.8668       
+# 538 0.8662       
+# 539 0.8656       
+# 540 0.8650       
+# 541 0.8645       
+# 542 0.8641       
+# 543 0.8638       
+# 544 0.8632       
+ 545 0.8627       
+# 546 0.8620       
+# 547 0.8616       
+# 548 0.8610       
+# 549 0.8603       
+ 550 0.8598       
+# 551 0.8594       
+# 552 0.8587       
+# 553 0.8583       
+# 554 0.8578       
+ 555 0.8574       
+# 556 0.8569       
+# 557 0.8563       
+# 558 0.8557       
+# 559 0.8551       
+ 560 0.8545       
+# 561 0.8541       
+# 562 0.8536       
+# 563 0.8530       
+# 564 0.8524       
+ 565 0.8518       
+# 566 0.8513       
+# 567 0.8508       
+# 568 0.8500       
+# 569 0.8496       
+ 570 0.8490       
+# 571 0.8484       
+# 572 0.8480       
+# 573 0.8475       
+# 574 0.8467       
+# 575 0.8463       
+# 576 0.8459       
+# 577 0.8452       
+# 578 0.8446       
+ 579 0.8441       
+# 580 0.8435       
+# 581 0.8428       
+# 582 0.8422       
+# 583 0.8416       
+ 584 0.8410       
+# 585 0.8407       
+# 586 0.8401       
+# 587 0.8396       
+# 588 0.8392       
+ 589 0.8386       
+# 590 0.8379       
+# 591 0.8375       
+# 592 0.8366       
+# 593 0.8358       
+ 594 0.8354       
+# 595 0.8345       
+# 596 0.8339       
+# 597 0.8334       
+# 598 0.8330       
+ 599 0.8325       
+# 600 0.8322       
+# 601 0.8316       
+# 602 0.8311       
+# 603 0.8305       
+ 604 0.8298       
+# 605 0.8291       
+# 606 0.8283       
+# 607 0.8276       
+# 608 0.8270       
+# 609 0.8262       
+# 610 0.8256       
+# 611 0.8249       
+# 612 0.8246       
+ 613 0.8241       
+# 614 0.8252       
+# 615 0.8367       
+# 616 0.8225       
+# 617 0.8220       
+ 618 0.8216       
+# 619 0.8209       
+# 620 0.8203       
+# 621 0.8195       
+# 622 0.8188       
+ 623 0.8179       
+# 624 0.8171       
+# 625 0.8166       
+# 626 0.8159       
+# 627 0.8156       
+ 628 0.8151       
+# 629 0.8145       
+# 630 0.8140       
+# 631 0.8135       
+# 632 0.8130       
+ 633 0.8125       
+# 634 0.8118       
+# 635 0.8111       
+# 636 0.8104       
+# 637 0.8096       
+ 638 0.8089       
+# 639 0.8082       
+# 640 0.8075       
+# 641 0.8068       
+# 642 0.8064       
+# 643 0.8058       
+# 644 0.8053       
+# 645 0.8047       
+# 646 0.8042       
+ 647 0.8037       
+# 648 0.8031       
+# 649 0.8025       
+# 650 0.8019       
+# 651 0.8011       
+ 652 0.8005       
+# 653 0.7997       
+# 654 0.7992       
+# 655 0.7986       
+# 656 0.7979       
+ 657 0.7972       
+# 658 0.7965       
+# 659 0.7961       
+# 660 0.7956       
+# 661 0.7949       
+ 662 0.7944       
+# 663 0.7937       
+# 664 0.7931       
+# 665 0.7925       
+# 666 0.7918       
+ 667 0.7913       
+# 668 0.7907       
+# 669 0.7901       
+# 670 0.7895       
+# 671 0.7889       
+ 672 0.7883       
+# 673 0.7878       
+# 674 0.7872       
+# 675 0.7866       
+# 676 0.7860       
+# 677 0.7854       
+# 678 0.7848       
+# 679 0.7842       
+# 680 0.7835       
+ 681 0.7827       
+# 682 0.7820       
+# 683 0.7815       
+# 684 0.7809       
+# 685 0.7803       
+ 686 0.7798       
+# 687 0.7792       
+# 688 0.7788       
+# 689 0.7782       
+# 690 0.7777       
+ 691 0.7771       
+# 692 0.7766       
+# 693 0.7759       
+# 694 0.7752       
+# 695 0.7745       
+ 696 0.7740       
+# 697 0.7734       
+# 698 0.7727       
+# 699 0.7720       
+# 700 0.7714       
+ 701 0.7708       
+# 702 0.7702       
+# 703 0.7696       
+# 704 0.7692       
+# 705 0.7689       
+ 706 0.7682       
+# 707 0.7677       
+# 708 0.7673       
+# 709 0.7667       
+# 710 0.7661       
+# 711 0.7655       
+# 712 0.7649       
+# 713 0.7641       
+# 714 0.7634       
+ 715 0.7629       
+# 716 0.7621       
+# 717 0.7614       
+# 718 0.7609       
+# 719 0.7603       
+ 720 0.7599       
+# 721 0.7595       
+# 722 0.7590       
+# 723 0.7586       
+# 724 0.7583       
+ 725 0.7578       
+# 726 0.7572       
+# 727 0.7568       
+# 728 0.7563       
+# 729 0.7558       
+ 730 0.7552       
+# 731 0.7545       
+# 732 0.7538       
+# 733 0.7532       
+# 734 0.7524       
+ 735 0.7518       
+# 736 0.7510       
+# 737 0.7505       
+# 738 0.7501       
+# 739 0.7496       
+ 740 0.7492       
+# 741 0.7488       
+# 742 0.7483       
+# 743 0.7481       
+# 744 0.7478       
+# 745 0.7475       
+# 746 0.7471       
+# 747 0.7467       
+# 748 0.7462       
+ 749 0.7457       
+# 750 0.7453       
+# 751 0.7447       
+# 752 0.7441       
+# 753 0.7435       
+ 754 0.7428       
+# 755 0.7421       
+# 756 0.7416       
+# 757 0.7412       
+# 758 0.7405       
+ 759 0.7399       
+# 760 0.7395       
+# 761 0.7390       
+# 762 0.7387       
+# 763 0.7384       
+ 764 0.7382       
+# 765 0.7380       
+# 766 0.7377       
+# 767 0.7374       
+# 768 0.7371       
+ 769 0.7368       
+# 770 0.7367       
+# 771 0.7362       
+# 772 0.7358       
+# 773 0.7354       
+ 774 0.7351       
+# 775 0.7346       
+# 776 0.7342       
+# 777 0.7337       
+# 778 0.7334       
+# 779 0.7327       
+# 780 0.7324       
+# 781 0.7319       
+# 782 0.7316       
+ 783 0.7312       
+# 784 0.7309       
+# 785 0.7306       
+# 786 0.7304       
+# 787 0.7302       
+ 788 0.7300       
+# 789 0.7298       
+# 790 0.7298       
+# 791 0.7296       
+# 792 0.7295       
+ 793 0.7292       
+# 794 0.7290       
+# 795 0.7290       
+# 796 0.7288       
+# 797 0.7286       
+ 798 0.7286       
+# 799 0.7281       
+ 800 0.7282
+ 900 0.685
+950 0.6634
Index: branches/Mars_McMismatchStudy/resmc/fact/Transmittance_1439Cones_FACT_bearbeitet.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/Transmittance_1439Cones_FACT_bearbeitet.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/Transmittance_1439Cones_FACT_bearbeitet.txt	(revision 17960)
@@ -0,0 +1,44 @@
+# several points are outcomment, for a faster calculation of the spline
+250    0.0005566
+#260    0.00081966
+270    0.00061284
+280    0.0030381
+290    0.020164
+300    0.090906
+310    0.239483
+320    0.422324
+330    0.555866
+340    0.645322
+350    0.709289
+360    0.757315
+370    0.79624
+380    0.824558
+390    0.842468
+400    0.853939
+#410    0.861924
+420    0.866997
+#430    0.871904
+440    0.875743
+#450    0.878966
+460    0.881858
+#470    0.883873
+480    0.88636
+490    0.889237
+500    0.890949
+#510    0.892239
+#520    0.893734
+530    0.895242
+#540    0.896486
+#550    0.89755
+560    0.898537
+#570    0.898963
+#580    0.899302
+590    0.899906
+600    0.900801
+700    0.900
+# artificial points for ceres
+800    0.9
+900    0.9
+950    0.9
+
+
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_20130402.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_20130402.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_20130402.txt	(revision 17960)
@@ -0,0 +1,608 @@
+# this file was taken from the logbook (https://www.fact-project.org/logbook/showthread.php?tid=548, MirrorReflectivity_Lustermann_FACT.txt).
+# The three values for the reflectivity per wavelength in the original document were averaged.
+# For a wavelength of 900 and 950 two values for the reflectivity were estimated.
+# The values are NOT multiplied by 1.035 (or even 1.0375, as Julia Thaele supposed in the logbook thread).
+# about 4 of 5 values are commented out, to accelerate the spline calculation.
+ 200 0.5271       
+# 201 0.5420       
+# 202 0.5569       
+# 203 0.5714       
+# 204 0.5852       
+ 205 0.5988       
+# 206 0.6117       
+# 207 0.6240       
+# 208 0.6355       
+# 209 0.6465       
+ 210 0.6569       
+# 211 0.6665       
+# 212 0.6755       
+# 213 0.6840       
+# 214 0.6916       
+ 215 0.6987       
+# 216 0.7053       
+# 217 0.7111       
+# 218 0.7166       
+# 219 0.7216       
+ 220 0.7260       
+# 221 0.7302       
+# 222 0.7336       
+# 223 0.7368       
+# 224 0.7397       
+ 225 0.7423       
+# 226 0.7446       
+# 227 0.7465       
+# 228 0.7484       
+# 229 0.7498       
+ 230 0.7509       
+# 231 0.7518       
+# 232 0.7527       
+# 233 0.7532       
+# 234 0.7534       
+# 235 0.7535       
+# 236 0.7532       
+# 237 0.7529       
+# 238 0.7525       
+ 239 0.7517       
+# 240 0.7509       
+# 241 0.7499       
+# 242 0.7486       
+# 243 0.7472       
+ 244 0.7458       
+# 245 0.7442       
+# 246 0.7424       
+# 247 0.7405       
+# 248 0.7385       
+ 249 0.7365       
+# 250 0.7343       
+# 251 0.7322       
+# 252 0.7297       
+# 253 0.7273       
+ 254 0.7250       
+# 255 0.7226       
+# 256 0.7204       
+# 257 0.7179       
+# 258 0.7156       
+ 259 0.7134       
+# 260 0.7113       
+# 261 0.7093       
+# 262 0.7074       
+# 263 0.7056       
+ 264 0.7039       
+# 265 0.7023       
+# 266 0.7009       
+# 267 0.6995       
+# 268 0.6984       
+# 269 0.6976       
+# 270 0.6968       
+# 271 0.6963       
+# 272 0.6960       
+ 273 0.6961       
+# 274 0.6964       
+# 275 0.6967       
+# 276 0.6972       
+# 277 0.6981       
+ 278 0.6991       
+# 279 0.7003       
+# 280 0.7019       
+# 281 0.7036       
+# 282 0.7055       
+ 283 0.7075       
+# 284 0.7098       
+# 285 0.7123       
+# 286 0.7149       
+# 287 0.7174       
+ 288 0.7202       
+# 289 0.7233       
+# 290 0.7265       
+# 291 0.7295       
+# 292 0.7328       
+ 293 0.7361       
+# 294 0.7395       
+# 295 0.7430       
+# 296 0.7464       
+# 297 0.7500       
+ 298 0.7534       
+# 299 0.7568       
+# 300 0.7605       
+# 301 0.7641       
+# 302 0.7673       
+# 303 0.7707       
+# 304 0.7743       
+# 305 0.7777       
+# 306 0.7812       
+ 307 0.7846       
+# 308 0.7879       
+# 309 0.7912       
+# 310 0.7944       
+# 311 0.7975       
+ 312 0.8007       
+# 313 0.8037       
+# 314 0.8065       
+# 315 0.8095       
+# 316 0.8124       
+ 317 0.8152       
+# 318 0.8161       
+# 319 0.8180       
+# 320 0.8207       
+# 321 0.8232       
+ 322 0.8255       
+# 323 0.8275       
+# 324 0.8302       
+# 325 0.8325       
+# 326 0.8346       
+ 327 0.8368       
+# 328 0.8390       
+# 329 0.8412       
+# 330 0.8429       
+# 331 0.8448       
+ 332 0.8466       
+# 333 0.8484       
+# 334 0.8501       
+# 335 0.8519       
+# 336 0.8535       
+# 337 0.8553       
+# 338 0.8569       
+# 339 0.8583       
+# 340 0.8597       
+ 341 0.8610       
+# 342 0.8626       
+# 343 0.8636       
+# 344 0.8648       
+# 345 0.8662       
+ 346 0.8674       
+# 347 0.8683       
+# 348 0.8695       
+# 349 0.8706       
+# 350 0.8716       
+ 351 0.8726       
+# 352 0.8737       
+# 353 0.8747       
+# 354 0.8755       
+# 355 0.8766       
+ 356 0.8772       
+# 357 0.8782       
+# 358 0.8787       
+# 359 0.8798       
+# 360 0.8804       
+ 361 0.8810       
+# 362 0.8818       
+# 363 0.8823       
+# 364 0.8828       
+# 365 0.8836       
+ 366 0.8842       
+# 367 0.8851       
+# 368 0.8851       
+# 369 0.8857       
+# 370 0.8864       
+# 371 0.8872       
+# 372 0.8876       
+# 373 0.8879       
+# 374 0.8882       
+ 375 0.8886       
+# 376 0.8890       
+# 377 0.8893       
+# 378 0.8897       
+# 379 0.8912       
+ 380 0.8912       
+# 381 0.8916       
+# 382 0.8921       
+# 383 0.8922       
+# 384 0.8927       
+ 385 0.8930       
+# 386 0.8931       
+# 387 0.8935       
+# 388 0.8936       
+# 389 0.8940       
+ 390 0.8938       
+# 391 0.8945       
+# 392 0.8946       
+# 393 0.8948       
+# 394 0.8951       
+ 395 0.8949       
+# 396 0.8952       
+# 397 0.8955       
+# 398 0.8956       
+# 399 0.8958       
+ 400 0.8958       
+# 401 0.8958       
+# 402 0.8960       
+# 403 0.8962       
+# 404 0.8963       
+# 405 0.8963       
+# 406 0.8965       
+# 407 0.8965       
+# 408 0.8966       
+ 409 0.8965       
+# 410 0.8968       
+# 411 0.8967       
+# 412 0.8970       
+# 413 0.8968       
+ 414 0.8966       
+# 415 0.8965       
+# 416 0.8967       
+# 417 0.8967       
+# 418 0.8967       
+ 419 0.8967       
+# 420 0.8967       
+# 421 0.8968       
+# 422 0.8965       
+# 423 0.8966       
+ 424 0.8966       
+# 425 0.8965       
+# 426 0.8965       
+# 427 0.8965       
+# 428 0.8962       
+ 429 0.8962       
+# 430 0.8960       
+# 431 0.8959       
+# 432 0.8957       
+# 433 0.8958       
+ 434 0.8957       
+# 435 0.8957       
+# 436 0.8955       
+# 437 0.8954       
+# 438 0.8951       
+# 439 0.8951       
+# 440 0.8949       
+# 441 0.8947       
+# 442 0.8944       
+ 443 0.8941       
+# 444 0.8941       
+# 445 0.8939       
+# 446 0.8939       
+# 447 0.8939       
+ 448 0.8938       
+# 449 0.8938       
+# 450 0.8938       
+# 451 0.8939       
+# 452 0.8940       
+ 453 0.8940       
+# 454 0.8942       
+# 455 0.8943       
+# 456 0.8943       
+# 457 0.8944       
+ 458 0.8942       
+# 459 0.8943       
+# 460 0.8942       
+# 461 0.8943       
+# 462 0.8943       
+ 463 0.8940       
+# 464 0.8937       
+# 465 0.8934       
+# 466 0.8931       
+# 467 0.8929       
+ 468 0.8927       
+# 469 0.8924       
+# 470 0.8920       
+# 471 0.8917       
+# 472 0.8912       
+# 473 0.8908       
+# 474 0.8903       
+# 475 0.8898       
+# 476 0.8894       
+ 477 0.8890       
+# 478 0.8885       
+# 479 0.8880       
+# 480 0.8875       
+# 481 0.8869       
+ 482 0.8863       
+# 483 0.8857       
+# 484 0.8851       
+# 485 0.8846       
+# 486 0.8843       
+ 487 0.8840       
+# 488 0.8838       
+# 489 0.8837       
+# 490 0.8836       
+# 491 0.8834       
+ 492 0.8834       
+# 493 0.8834       
+# 494 0.8833       
+# 495 0.8833       
+# 496 0.8832       
+ 497 0.8831       
+# 498 0.8830       
+# 499 0.8829       
+# 500 0.8828       
+# 501 0.8828       
+ 502 0.8826       
+# 503 0.8824       
+# 504 0.8821       
+# 505 0.8818       
+# 506 0.8814       
+# 507 0.8810       
+# 508 0.8806       
+# 509 0.8801       
+# 510 0.8796       
+ 511 0.8793       
+# 512 0.8790       
+# 513 0.8787       
+# 514 0.8782       
+# 515 0.8776       
+ 516 0.8771       
+# 517 0.8766       
+# 518 0.8759       
+# 519 0.8754       
+# 520 0.8750       
+ 521 0.8745       
+# 522 0.8742       
+# 523 0.8738       
+# 524 0.8733       
+# 525 0.8729       
+ 526 0.8723       
+# 527 0.8718       
+# 528 0.8711       
+# 529 0.8705       
+# 530 0.8700       
+ 531 0.8696       
+# 532 0.8692       
+# 533 0.8688       
+# 534 0.8685       
+# 535 0.8679       
+ 536 0.8674       
+# 537 0.8668       
+# 538 0.8662       
+# 539 0.8656       
+# 540 0.8650       
+# 541 0.8645       
+# 542 0.8641       
+# 543 0.8638       
+# 544 0.8632       
+ 545 0.8627       
+# 546 0.8620       
+# 547 0.8616       
+# 548 0.8610       
+# 549 0.8603       
+ 550 0.8598       
+# 551 0.8594       
+# 552 0.8587       
+# 553 0.8583       
+# 554 0.8578       
+ 555 0.8574       
+# 556 0.8569       
+# 557 0.8563       
+# 558 0.8557       
+# 559 0.8551       
+ 560 0.8545       
+# 561 0.8541       
+# 562 0.8536       
+# 563 0.8530       
+# 564 0.8524       
+ 565 0.8518       
+# 566 0.8513       
+# 567 0.8508       
+# 568 0.8500       
+# 569 0.8496       
+ 570 0.8490       
+# 571 0.8484       
+# 572 0.8480       
+# 573 0.8475       
+# 574 0.8467       
+# 575 0.8463       
+# 576 0.8459       
+# 577 0.8452       
+# 578 0.8446       
+ 579 0.8441       
+# 580 0.8435       
+# 581 0.8428       
+# 582 0.8422       
+# 583 0.8416       
+ 584 0.8410       
+# 585 0.8407       
+# 586 0.8401       
+# 587 0.8396       
+# 588 0.8392       
+ 589 0.8386       
+# 590 0.8379       
+# 591 0.8375       
+# 592 0.8366       
+# 593 0.8358       
+ 594 0.8354       
+# 595 0.8345       
+# 596 0.8339       
+# 597 0.8334       
+# 598 0.8330       
+ 599 0.8325       
+# 600 0.8322       
+# 601 0.8316       
+# 602 0.8311       
+# 603 0.8305       
+ 604 0.8298       
+# 605 0.8291       
+# 606 0.8283       
+# 607 0.8276       
+# 608 0.8270       
+# 609 0.8262       
+# 610 0.8256       
+# 611 0.8249       
+# 612 0.8246       
+ 613 0.8241       
+# 614 0.8252       
+# 615 0.8367       
+# 616 0.8225       
+# 617 0.8220       
+ 618 0.8216       
+# 619 0.8209       
+# 620 0.8203       
+# 621 0.8195       
+# 622 0.8188       
+ 623 0.8179       
+# 624 0.8171       
+# 625 0.8166       
+# 626 0.8159       
+# 627 0.8156       
+ 628 0.8151       
+# 629 0.8145       
+# 630 0.8140       
+# 631 0.8135       
+# 632 0.8130       
+ 633 0.8125       
+# 634 0.8118       
+# 635 0.8111       
+# 636 0.8104       
+# 637 0.8096       
+ 638 0.8089       
+# 639 0.8082       
+# 640 0.8075       
+# 641 0.8068       
+# 642 0.8064       
+# 643 0.8058       
+# 644 0.8053       
+# 645 0.8047       
+# 646 0.8042       
+ 647 0.8037       
+# 648 0.8031       
+# 649 0.8025       
+# 650 0.8019       
+# 651 0.8011       
+ 652 0.8005       
+# 653 0.7997       
+# 654 0.7992       
+# 655 0.7986       
+# 656 0.7979       
+ 657 0.7972       
+# 658 0.7965       
+# 659 0.7961       
+# 660 0.7956       
+# 661 0.7949       
+ 662 0.7944       
+# 663 0.7937       
+# 664 0.7931       
+# 665 0.7925       
+# 666 0.7918       
+ 667 0.7913       
+# 668 0.7907       
+# 669 0.7901       
+# 670 0.7895       
+# 671 0.7889       
+ 672 0.7883       
+# 673 0.7878       
+# 674 0.7872       
+# 675 0.7866       
+# 676 0.7860       
+# 677 0.7854       
+# 678 0.7848       
+# 679 0.7842       
+# 680 0.7835       
+ 681 0.7827       
+# 682 0.7820       
+# 683 0.7815       
+# 684 0.7809       
+# 685 0.7803       
+ 686 0.7798       
+# 687 0.7792       
+# 688 0.7788       
+# 689 0.7782       
+# 690 0.7777       
+ 691 0.7771       
+# 692 0.7766       
+# 693 0.7759       
+# 694 0.7752       
+# 695 0.7745       
+ 696 0.7740       
+# 697 0.7734       
+# 698 0.7727       
+# 699 0.7720       
+# 700 0.7714       
+ 701 0.7708       
+# 702 0.7702       
+# 703 0.7696       
+# 704 0.7692       
+# 705 0.7689       
+ 706 0.7682       
+# 707 0.7677       
+# 708 0.7673       
+# 709 0.7667       
+# 710 0.7661       
+# 711 0.7655       
+# 712 0.7649       
+# 713 0.7641       
+# 714 0.7634       
+ 715 0.7629       
+# 716 0.7621       
+# 717 0.7614       
+# 718 0.7609       
+# 719 0.7603       
+ 720 0.7599       
+# 721 0.7595       
+# 722 0.7590       
+# 723 0.7586       
+# 724 0.7583       
+ 725 0.7578       
+# 726 0.7572       
+# 727 0.7568       
+# 728 0.7563       
+# 729 0.7558       
+ 730 0.7552       
+# 731 0.7545       
+# 732 0.7538       
+# 733 0.7532       
+# 734 0.7524       
+ 735 0.7518       
+# 736 0.7510       
+# 737 0.7505       
+# 738 0.7501       
+# 739 0.7496       
+ 740 0.7492       
+# 741 0.7488       
+# 742 0.7483       
+# 743 0.7481       
+# 744 0.7478       
+# 745 0.7475       
+# 746 0.7471       
+# 747 0.7467       
+# 748 0.7462       
+ 749 0.7457       
+# 750 0.7453       
+# 751 0.7447       
+# 752 0.7441       
+# 753 0.7435       
+ 754 0.7428       
+# 755 0.7421       
+# 756 0.7416       
+# 757 0.7412       
+# 758 0.7405       
+ 759 0.7399       
+# 760 0.7395       
+# 761 0.7390       
+# 762 0.7387       
+# 763 0.7384       
+ 764 0.7382       
+# 765 0.7380       
+# 766 0.7377       
+# 767 0.7374       
+# 768 0.7371       
+ 769 0.7368       
+# 770 0.7367       
+# 771 0.7362       
+# 772 0.7358       
+# 773 0.7354       
+ 774 0.7351       
+# 775 0.7346       
+# 776 0.7342       
+# 777 0.7337       
+# 778 0.7334       
+# 779 0.7327       
+# 780 0.7324       
+# 781 0.7319       
+# 782 0.7316       
+ 783 0.7312       
+# 784 0.7309       
+# 785 0.7306       
+# 786 0.7304       
+# 787 0.7302       
+ 788 0.7300       
+# 789 0.7298       
+# 790 0.7298       
+# 791 0.7296       
+# 792 0.7295       
+ 793 0.7292       
+# 794 0.7290       
+# 795 0.7290       
+# 796 0.7288       
+# 797 0.7286       
+ 798 0.7286       
+# 799 0.7281       
+ 800 0.7282
+ 900 0.685
+950 0.6634
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_Lustermann_FACT.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_Lustermann_FACT.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_Lustermann_FACT.txt	(revision 17960)
@@ -0,0 +1,602 @@
+800	73	73	72.45
+799	73.01	72.99	72.44
+798	73.04	73.04	72.49
+797	73.05	73.05	72.48
+796	73.07	73.07	72.49
+795	73.09	73.09	72.51
+794	73.09	73.09	72.51
+793	73.12	73.12	72.53
+792	73.15	73.15	72.55
+791	73.15	73.16	72.57
+790	73.17	73.18	72.59
+789	73.19	73.17	72.59
+788	73.18	73.2	72.62
+787	73.21	73.22	72.64
+786	73.23	73.23	72.66
+785	73.25	73.24	72.7
+784	73.27	73.27	72.74
+783	73.3	73.3	72.75
+782	73.34	73.34	72.79
+781	73.38	73.37	72.83
+780	73.42	73.42	72.87
+779	73.46	73.46	72.9
+778	73.53	73.53	72.95
+777	73.56	73.57	72.99
+776	73.61	73.62	73.04
+775	73.65	73.65	73.08
+774	73.71	73.7	73.13
+773	73.74	73.75	73.14
+772	73.78	73.78	73.17
+771	73.83	73.82	73.21
+770	73.87	73.88	73.25
+769	73.87	73.9	73.26
+768	73.91	73.91	73.3
+767	73.95	73.94	73.33
+766	73.98	73.97	73.35
+765	73.99	74.01	73.39
+764	74.02	74.03	73.41
+763	74.04	74.05	73.44
+762	74.05	74.09	73.48
+761	74.09	74.1	73.52
+760	74.14	74.14	73.56
+759	74.18	74.19	73.6
+758	74.24	74.25	73.67
+757	74.31	74.32	73.72
+756	74.37	74.37	73.75
+755	74.41	74.41	73.82
+754	74.48	74.49	73.88
+753	74.55	74.56	73.95
+752	74.61	74.62	74
+751	74.67	74.69	74.06
+750	74.74	74.73	74.11
+749	74.78	74.78	74.14
+748	74.83	74.82	74.21
+747	74.87	74.88	74.26
+746	74.92	74.92	74.3
+745	74.96	74.94	74.34
+744	74.98	74.99	74.36
+743	75.01	75.01	74.4
+742	75.03	75.04	74.43
+741	75.07	75.09	74.49
+740	75.12	75.11	74.53
+739	75.16	75.16	74.55
+738	75.22	75.22	74.6
+737	75.26	75.26	74.64
+736	75.31	75.31	74.69
+735	75.39	75.39	74.75
+734	75.46	75.46	74.81
+733	75.53	75.52	74.9
+732	75.6	75.6	74.95
+731	75.67	75.66	75.01
+730	75.74	75.74	75.09
+729	75.8	75.8	75.15
+728	75.86	75.84	75.2
+727	75.9	75.89	75.24
+726	75.93	75.94	75.29
+725	76	75.99	75.36
+724	76.05	76.04	75.41
+723	76.07	76.07	75.43
+722	76.12	76.12	75.47
+721	76.16	76.17	75.52
+720	76.21	76.21	75.56
+719	76.26	76.25	75.59
+718	76.31	76.31	75.65
+717	76.36	76.37	75.7
+716	76.43	76.43	75.78
+715	76.51	76.5	75.85
+714	76.57	76.56	75.9
+713	76.63	76.64	75.97
+712	76.7	76.72	76.04
+711	76.77	76.78	76.11
+710	76.83	76.83	76.17
+709	76.88	76.88	76.24
+708	76.94	76.94	76.3
+707	76.98	76.98	76.34
+706	77.04	77.03	76.4
+705	77.11	77.1	76.46
+704	77.14	77.13	76.49
+703	77.18	77.17	76.52
+702	77.24	77.24	76.57
+701	77.3	77.31	76.63
+700	77.36	77.38	76.68
+699	77.43	77.44	76.74
+698	77.51	77.51	76.8
+697	77.58	77.57	76.87
+696	77.63	77.63	76.93
+695	77.68	77.69	76.99
+694	77.75	77.76	77.06
+693	77.82	77.82	77.13
+692	77.88	77.89	77.2
+691	77.93	77.95	77.26
+690	77.99	78	77.32
+689	78.04	78.04	77.38
+688	78.1	78.1	77.43
+687	78.15	78.15	77.47
+686	78.21	78.19	77.54
+685	78.26	78.25	77.59
+684	78.32	78.32	77.63
+683	78.38	78.39	77.68
+682	78.44	78.44	77.73
+681	78.52	78.51	77.79
+680	78.59	78.59	77.88
+679	78.66	78.66	77.94
+678	78.72	78.72	77.99
+677	78.78	78.78	78.06
+676	78.84	78.84	78.13
+675	78.9	78.89	78.19
+674	78.95	78.95	78.26
+673	79.01	79.02	78.32
+672	79.07	79.06	78.37
+671	79.13	79.12	78.43
+670	79.17	79.17	78.5
+669	79.23	79.23	78.56
+668	79.3	79.3	78.6
+667	79.36	79.36	78.66
+666	79.42	79.42	78.71
+665	79.5	79.49	78.77
+664	79.56	79.55	78.82
+663	79.62	79.61	78.88
+662	79.69	79.67	78.95
+661	79.74	79.73	79.01
+660	79.8	79.8	79.08
+659	79.85	79.85	79.13
+658	79.89	79.9	79.16
+657	79.96	79.95	79.24
+656	80.03	80.03	79.32
+655	80.09	80.11	79.39
+654	80.16	80.17	79.44
+653	80.22	80.22	79.48
+652	80.3	80.3	79.56
+651	80.36	80.35	79.63
+650	80.44	80.42	79.7
+649	80.5	80.51	79.75
+648	80.55	80.57	79.82
+647	80.62	80.62	79.88
+646	80.67	80.66	79.93
+645	80.7	80.71	79.99
+644	80.76	80.77	80.07
+643	80.81	80.82	80.12
+642	80.88	80.87	80.17
+641	80.92	80.91	80.22
+640	80.98	80.98	80.28
+639	81.06	81.05	80.34
+638	81.15	81.13	80.4
+637	81.22	81.2	80.47
+636	81.29	81.3	80.54
+635	81.36	81.36	80.61
+634	81.44	81.44	80.66
+633	81.51	81.5	80.73
+632	81.55	81.55	80.8
+631	81.6	81.59	80.85
+630	81.64	81.64	80.91
+629	81.69	81.68	80.97
+628	81.74	81.74	81.04
+627	81.78	81.79	81.11
+626	81.83	81.81	81.13
+625	81.9	81.89	81.18
+624	81.95	81.94	81.24
+623	82.03	82.03	81.3
+622	82.13	82.12	81.38
+621	82.2	82.21	81.44
+620	82.29	82.29	81.5
+619	82.35	82.35	81.56
+618	82.42	82.42	81.63
+617	82.46	82.45	81.68
+616	82.51	82.5	81.75
+615	83.92	83.93	83.15
+614	82.76	82.77	82.04
+613	82.64	82.65	81.93
+612	82.69	82.69	81.99
+611	82.72	82.73	82.02
+610	82.8	82.8	82.08
+609	82.86	82.86	82.14
+608	82.95	82.95	82.21
+607	83.01	83	82.27
+606	83.09	83.08	82.33
+605	83.17	83.16	82.41
+604	83.24	83.23	82.47
+603	83.31	83.3	82.53
+602	83.37	83.37	82.59
+601	83.41	83.42	82.64
+600	83.47	83.48	82.71
+599	83.5	83.5	82.74
+598	83.54	83.55	82.8
+597	83.58	83.58	82.85
+596	83.62	83.65	82.9
+595	83.7	83.7	82.96
+594	83.78	83.77	83.06
+593	83.82	83.83	83.1
+592	83.89	83.9	83.18
+591	83.98	83.99	83.27
+590	84.05	84.02	83.31
+589	84.11	84.1	83.38
+588	84.19	84.17	83.41
+587	84.22	84.21	83.46
+586	84.27	84.25	83.5
+585	84.33	84.32	83.55
+584	84.36	84.36	83.57
+583	84.41	84.43	83.64
+582	84.47	84.48	83.7
+581	84.54	84.53	83.77
+580	84.6	84.6	83.86
+579	84.66	84.66	83.92
+578	84.69	84.7	83.98
+577	84.75	84.76	84.04
+576	84.83	84.82	84.12
+575	84.89	84.87	84.14
+574	84.93	84.91	84.18
+573	85	85	84.26
+572	85.07	85.05	84.29
+571	85.1	85.1	84.32
+570	85.16	85.16	84.38
+569	85.21	85.21	84.45
+568	85.26	85.25	84.5
+567	85.33	85.33	84.59
+566	85.37	85.36	84.65
+565	85.42	85.41	84.7
+564	85.47	85.47	84.79
+563	85.54	85.53	84.84
+562	85.59	85.59	84.89
+561	85.66	85.66	84.91
+560	85.71	85.7	84.94
+559	85.77	85.76	84.99
+558	85.83	85.83	85.05
+557	85.89	85.89	85.12
+556	85.94	85.94	85.19
+555	85.99	86	85.24
+554	86.04	86.02	85.29
+553	86.08	86.06	85.34
+552	86.1	86.12	85.39
+551	86.17	86.18	85.46
+550	86.22	86.23	85.5
+549	86.27	86.28	85.55
+548	86.34	86.34	85.61
+547	86.4	86.41	85.67
+546	86.45	86.45	85.71
+545	86.52	86.52	85.78
+544	86.57	86.56	85.83
+543	86.62	86.62	85.89
+542	86.65	86.65	85.94
+541	86.69	86.69	85.97
+540	86.74	86.74	86.03
+539	86.8	86.8	86.08
+538	86.85	86.87	86.14
+537	86.92	86.92	86.19
+536	86.98	86.98	86.25
+535	87.03	87.03	86.32
+534	87.08	87.08	86.38
+533	87.11	87.11	86.41
+532	87.15	87.14	86.46
+531	87.19	87.18	86.5
+530	87.22	87.23	86.54
+529	87.27	87.28	86.6
+528	87.34	87.34	86.66
+527	87.41	87.4	86.72
+526	87.46	87.45	86.77
+525	87.52	87.52	86.83
+524	87.55	87.56	86.88
+523	87.6	87.61	86.94
+522	87.63	87.64	86.98
+521	87.67	87.67	87.02
+520	87.71	87.72	87.08
+519	87.75	87.75	87.12
+518	87.8	87.8	87.17
+517	87.86	87.87	87.25
+516	87.91	87.92	87.31
+515	87.97	87.96	87.36
+514	88.02	88.02	87.41
+513	88.06	88.07	87.48
+512	88.09	88.09	87.52
+511	88.11	88.11	87.56
+510	88.14	88.14	87.6
+509	88.18	88.19	87.65
+508	88.23	88.24	87.72
+507	88.27	88.27	87.76
+506	88.3	88.31	87.81
+505	88.33	88.34	87.86
+504	88.37	88.36	87.9
+503	88.4	88.39	87.93
+502	88.41	88.42	87.95
+501	88.44	88.45	87.96
+500	88.45	88.45	87.95
+499	88.46	88.48	87.94
+498	88.48	88.48	87.94
+497	88.49	88.49	87.95
+496	88.51	88.5	87.96
+495	88.53	88.52	87.95
+494	88.53	88.53	87.93
+493	88.55	88.55	87.93
+492	88.55	88.56	87.9
+491	88.57	88.57	87.87
+490	88.61	88.6	87.87
+489	88.63	88.62	87.86
+488	88.64	88.64	87.86
+487	88.66	88.67	87.88
+486	88.69	88.7	87.91
+485	88.73	88.73	87.93
+484	88.79	88.78	87.97
+483	88.85	88.84	88.03
+482	88.9	88.9	88.09
+481	88.95	88.95	88.16
+480	89.02	89	88.23
+479	89.07	89.05	88.29
+478	89.11	89.1	88.35
+477	89.14	89.14	88.42
+476	89.18	89.17	88.47
+475	89.21	89.21	88.52
+474	89.26	89.25	88.59
+473	89.31	89.3	88.64
+472	89.34	89.34	88.69
+471	89.37	89.39	88.74
+470	89.4	89.42	88.79
+469	89.44	89.44	88.83
+468	89.47	89.48	88.87
+467	89.49	89.49	88.9
+466	89.51	89.5	88.92
+465	89.54	89.54	88.95
+464	89.56	89.57	88.99
+463	89.59	89.61	89.01
+462	89.6	89.63	89.05
+461	89.61	89.62	89.07
+460	89.6	89.61	89.06
+459	89.62	89.62	89.04
+458	89.63	89.63	89.01
+457	89.65	89.65	89.01
+456	89.65	89.65	89
+455	89.65	89.66	88.99
+454	89.64	89.64	88.97
+453	89.62	89.63	88.96
+452	89.62	89.63	88.95
+451	89.61	89.64	88.93
+450	89.61	89.63	88.9
+449	89.63	89.63	88.88
+448	89.63	89.64	88.87
+447	89.64	89.66	88.88
+446	89.65	89.65	88.86
+445	89.65	89.65	88.87
+444	89.67	89.67	88.89
+443	89.67	89.67	88.89
+442	89.7	89.71	88.92
+441	89.74	89.73	88.95
+440	89.76	89.75	88.97
+439	89.77	89.77	88.99
+438	89.77	89.77	88.99
+437	89.78	89.8	89.03
+436	89.79	89.82	89.04
+435	89.81	89.82	89.08
+434	89.82	89.81	89.08
+433	89.83	89.83	89.08
+432	89.82	89.82	89.06
+431	89.85	89.85	89.08
+430	89.87	89.85	89.09
+429	89.87	89.87	89.11
+428	89.87	89.88	89.12
+427	89.88	89.89	89.17
+426	89.88	89.89	89.18
+425	89.89	89.9	89.17
+424	89.9	89.92	89.17
+423	89.9	89.91	89.16
+422	89.9	89.9	89.16
+421	89.91	89.92	89.2
+420	89.91	89.93	89.18
+419	89.9	89.92	89.19
+418	89.91	89.91	89.19
+417	89.91	89.92	89.17
+416	89.89	89.92	89.19
+415	89.89	89.89	89.18
+414	89.92	89.9	89.17
+413	89.91	89.92	89.21
+412	89.92	89.94	89.23
+411	89.91	89.92	89.19
+410	89.91	89.94	89.19
+409	89.89	89.89	89.18
+408	89.88	89.9	89.2
+407	89.88	89.88	89.18
+406	89.88	89.89	89.17
+405	89.88	89.86	89.15
+404	89.85	89.88	89.15
+403	89.86	89.87	89.14
+402	89.82	89.84	89.14
+401	89.81	89.83	89.11
+400	89.8	89.83	89.1
+399	89.81	89.81	89.12
+398	89.79	89.81	89.09
+397	89.77	89.78	89.09
+396	89.75	89.75	89.05
+395	89.73	89.72	89.01
+394	89.75	89.74	89.04
+393	89.7	89.71	89.02
+392	89.69	89.69	89.01
+391	89.68	89.68	88.98
+390	89.6	89.62	88.93
+389	89.63	89.65	88.92
+388	89.59	89.58	88.9
+387	89.57	89.58	88.89
+386	89.54	89.54	88.85
+385	89.53	89.53	88.83
+384	89.49	89.48	88.84
+383	89.44	89.44	88.79
+382	89.42	89.42	88.79
+381	89.35	89.39	88.75
+380	89.36	89.33	88.68
+379	89.33	89.35	88.67
+378	89.23	89.24	88.45
+377	89.17	89.18	88.43
+376	89.14	89.14	88.41
+375	89.1	89.09	88.38
+374	89.07	89.05	88.35
+373	89.04	89.01	88.33
+372	88.99	88.98	88.3
+371	88.93	88.95	88.28
+370	88.88	88.84	88.2
+369	88.8	88.78	88.12
+368	88.74	88.72	88.08
+367	88.72	88.73	88.07
+366	88.62	88.64	87.99
+365	88.56	88.56	87.95
+364	88.49	88.48	87.88
+363	88.43	88.43	87.82
+362	88.41	88.36	87.78
+361	88.31	88.31	87.69
+360	88.24	88.26	87.63
+359	88.21	88.18	87.55
+358	88.09	88.07	87.46
+357	88.02	88.01	87.43
+356	87.93	87.93	87.3
+355	87.85	87.86	87.27
+354	87.75	87.74	87.17
+353	87.67	87.66	87.07
+352	87.55	87.56	86.99
+351	87.44	87.47	86.88
+350	87.35	87.35	86.78
+349	87.24	87.25	86.69
+348	87.14	87.13	86.59
+347	87.02	87.01	86.47
+346	86.92	86.91	86.38
+345	86.81	86.81	86.25
+344	86.66	86.66	86.12
+343	86.54	86.54	86.01
+342	86.45	86.44	85.9
+341	86.27	86.28	85.74
+340	86.14	86.15	85.62
+339	85.99	86	85.49
+338	85.85	85.86	85.36
+337	85.7	85.7	85.2
+336	85.52	85.52	85.01
+335	85.38	85.35	84.84
+334	85.18	85.18	84.67
+333	84.99	85	84.52
+332	84.81	84.81	84.35
+331	84.63	84.62	84.18
+330	84.46	84.44	83.96
+329	84.26	84.28	83.81
+328	84.05	84.06	83.59
+327	83.83	83.83	83.38
+326	83.6	83.62	83.16
+325	83.39	83.4	82.95
+324	83.16	83.18	82.72
+323	82.89	82.91	82.46
+322	82.69	82.71	82.26
+321	82.49	82.46	82.01
+320	82.22	82.21	81.79
+319	81.94	81.95	81.51
+318	81.7	81.7	81.42
+317	81.49	81.5	81.56
+316	81.22	81.21	81.28
+315	80.92	80.93	80.99
+314	80.63	80.63	80.7
+313	80.34	80.35	80.42
+312	80.04	80.04	80.12
+311	79.73	79.72	79.8
+310	79.41	79.41	79.49
+309	79.09	79.09	79.18
+308	78.76	78.75	78.85
+307	78.43	78.43	78.52
+306	78.1	78.09	78.18
+305	77.73	77.73	77.84
+304	77.39	77.4	77.49
+303	77.05	77.02	77.15
+302	76.7	76.69	76.81
+301	76.38	76.38	76.47
+300	76.02	76.03	76.1
+299	75.66	75.65	75.73
+298	75.33	75.31	75.39
+297	74.98	74.98	75.03
+296	74.62	74.62	74.68
+295	74.28	74.29	74.33
+294	73.93	73.94	73.97
+293	73.61	73.6	73.62
+292	73.29	73.27	73.29
+291	72.96	72.94	72.95
+290	72.66	72.65	72.63
+289	72.34	72.34	72.31
+288	72.03	72.04	71.99
+287	71.77	71.77	71.69
+286	71.52	71.53	71.42
+285	71.27	71.28	71.15
+284	71.02	71.04	70.89
+283	70.8	70.8	70.65
+282	70.62	70.61	70.43
+281	70.42	70.44	70.21
+280	70.25	70.27	70.04
+279	70.11	70.13	69.86
+278	70	70.01	69.72
+277	69.91	69.92	69.6
+276	69.83	69.84	69.49
+275	69.79	69.79	69.43
+274	69.76	69.77	69.38
+273	69.74	69.75	69.33
+272	69.74	69.76	69.31
+271	69.78	69.78	69.33
+270	69.85	69.83	69.37
+269	69.92	69.92	69.43
+268	70.01	70.02	69.5
+267	70.13	70.14	69.59
+266	70.27	70.29	69.72
+265	70.41	70.43	69.86
+264	70.57	70.59	70
+263	70.75	70.77	70.17
+262	70.94	70.94	70.33
+261	71.13	71.13	70.52
+260	71.33	71.34	70.72
+259	71.54	71.56	70.92
+258	71.77	71.78	71.14
+257	72	72.01	71.37
+256	72.24	72.25	71.62
+255	72.47	72.48	71.84
+254	72.71	72.72	72.08
+253	72.94	72.95	72.31
+252	73.18	73.19	72.55
+251	73.42	73.43	72.8
+250	73.63	73.64	73.02
+249	73.85	73.85	73.24
+248	74.05	74.06	73.45
+247	74.25	74.26	73.65
+246	74.44	74.45	73.84
+245	74.62	74.63	74.02
+244	74.78	74.78	74.19
+243	74.91	74.93	74.32
+242	75.05	75.07	74.47
+241	75.17	75.18	74.61
+240	75.27	75.28	74.71
+239	75.35	75.36	74.81
+238	75.41	75.43	74.9
+237	75.44	75.47	74.95
+236	75.48	75.49	74.99
+235	75.49	75.52	75.03
+234	75.49	75.5	75.04
+233	75.46	75.47	75.03
+232	75.39	75.41	75
+231	75.31	75.32	74.92
+230	75.21	75.23	74.84
+229	75.09	75.11	74.75
+228	74.95	74.95	74.62
+227	74.76	74.75	74.45
+226	74.55	74.56	74.27
+225	74.32	74.33	74.05
+224	74.05	74.06	73.81
+223	73.75	73.75	73.54
+222	73.43	73.43	73.23
+221	73.07	73.07	72.91
+220	72.64	72.65	72.51
+219	72.18	72.2	72.09
+218	71.68	71.68	71.61
+217	71.13	71.13	71.07
+216	70.53	70.54	70.51
+215	69.86	69.87	69.89
+214	69.14	69.15	69.2
+213	68.36	68.36	68.47
+212	67.49	67.5	67.67
+211	66.57	66.58	66.79
+210	65.6	65.61	65.86
+209	64.55	64.54	64.87
+208	63.41	63.42	63.82
+207	62.23	62.25	62.71
+206	60.98	60.99	61.54
+205	59.67	59.67	60.29
+204	58.29	58.28	59
+203	56.87	56.88	57.66
+202	55.41	55.41	56.26
+201	53.89	53.9	54.82
+200	52.37	52.39	53.38
+
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt	(revision 17960)
@@ -0,0 +1,603 @@
+ 200 0.5271       
+# 201 0.5420       
+# 202 0.5569       
+# 203 0.5714       
+# 204 0.5852       
+ 205 0.5988       
+# 206 0.6117       
+# 207 0.6240       
+# 208 0.6355       
+# 209 0.6465       
+ 210 0.6569       
+# 211 0.6665       
+# 212 0.6755       
+# 213 0.6840       
+# 214 0.6916       
+ 215 0.6987       
+# 216 0.7053       
+# 217 0.7111       
+# 218 0.7166       
+# 219 0.7216       
+ 220 0.7260       
+# 221 0.7302       
+# 222 0.7336       
+# 223 0.7368       
+# 224 0.7397       
+ 225 0.7423       
+# 226 0.7446       
+# 227 0.7465       
+# 228 0.7484       
+# 229 0.7498       
+ 230 0.7509       
+# 231 0.7518       
+# 232 0.7527       
+# 233 0.7532       
+# 234 0.7534       
+# 235 0.7535       
+# 236 0.7532       
+# 237 0.7529       
+# 238 0.7525       
+ 239 0.7517       
+# 240 0.7509       
+# 241 0.7499       
+# 242 0.7486       
+# 243 0.7472       
+ 244 0.7458       
+# 245 0.7442       
+# 246 0.7424       
+# 247 0.7405       
+# 248 0.7385       
+ 249 0.7365       
+# 250 0.7343       
+# 251 0.7322       
+# 252 0.7297       
+# 253 0.7273       
+ 254 0.7250       
+# 255 0.7226       
+# 256 0.7204       
+# 257 0.7179       
+# 258 0.7156       
+ 259 0.7134       
+# 260 0.7113       
+# 261 0.7093       
+# 262 0.7074       
+# 263 0.7056       
+ 264 0.7039       
+# 265 0.7023       
+# 266 0.7009       
+# 267 0.6995       
+# 268 0.6984       
+# 269 0.6976       
+# 270 0.6968       
+# 271 0.6963       
+# 272 0.6960       
+ 273 0.6961       
+# 274 0.6964       
+# 275 0.6967       
+# 276 0.6972       
+# 277 0.6981       
+ 278 0.6991       
+# 279 0.7003       
+# 280 0.7019       
+# 281 0.7036       
+# 282 0.7055       
+ 283 0.7075       
+# 284 0.7098       
+# 285 0.7123       
+# 286 0.7149       
+# 287 0.7174       
+ 288 0.7202       
+# 289 0.7233       
+# 290 0.7265       
+# 291 0.7295       
+# 292 0.7328       
+ 293 0.7361       
+# 294 0.7395       
+# 295 0.7430       
+# 296 0.7464       
+# 297 0.7500       
+ 298 0.7534       
+# 299 0.7568       
+# 300 0.7605       
+# 301 0.7641       
+# 302 0.7673       
+# 303 0.7707       
+# 304 0.7743       
+# 305 0.7777       
+# 306 0.7812       
+ 307 0.7846       
+# 308 0.7879       
+# 309 0.7912       
+# 310 0.7944       
+# 311 0.7975       
+ 312 0.8007       
+# 313 0.8037       
+# 314 0.8065       
+# 315 0.8095       
+# 316 0.8124       
+ 317 0.8152       
+# 318 0.8161       
+# 319 0.8180       
+# 320 0.8207       
+# 321 0.8232       
+ 322 0.8255       
+# 323 0.8275       
+# 324 0.8302       
+# 325 0.8325       
+# 326 0.8346       
+ 327 0.8368       
+# 328 0.8390       
+# 329 0.8412       
+# 330 0.8429       
+# 331 0.8448       
+ 332 0.8466       
+# 333 0.8484       
+# 334 0.8501       
+# 335 0.8519       
+# 336 0.8535       
+# 337 0.8553       
+# 338 0.8569       
+# 339 0.8583       
+# 340 0.8597       
+ 341 0.8610       
+# 342 0.8626       
+# 343 0.8636       
+# 344 0.8648       
+# 345 0.8662       
+ 346 0.8674       
+# 347 0.8683       
+# 348 0.8695       
+# 349 0.8706       
+# 350 0.8716       
+ 351 0.8726       
+# 352 0.8737       
+# 353 0.8747       
+# 354 0.8755       
+# 355 0.8766       
+ 356 0.8772       
+# 357 0.8782       
+# 358 0.8787       
+# 359 0.8798       
+# 360 0.8804       
+ 361 0.8810       
+# 362 0.8818       
+# 363 0.8823       
+# 364 0.8828       
+# 365 0.8836       
+ 366 0.8842       
+# 367 0.8851       
+# 368 0.8851       
+# 369 0.8857       
+# 370 0.8864       
+# 371 0.8872       
+# 372 0.8876       
+# 373 0.8879       
+# 374 0.8882       
+ 375 0.8886       
+# 376 0.8890       
+# 377 0.8893       
+# 378 0.8897       
+# 379 0.8912       
+ 380 0.8912       
+# 381 0.8916       
+# 382 0.8921       
+# 383 0.8922       
+# 384 0.8927       
+ 385 0.8930       
+# 386 0.8931       
+# 387 0.8935       
+# 388 0.8936       
+# 389 0.8940       
+ 390 0.8938       
+# 391 0.8945       
+# 392 0.8946       
+# 393 0.8948       
+# 394 0.8951       
+ 395 0.8949       
+# 396 0.8952       
+# 397 0.8955       
+# 398 0.8956       
+# 399 0.8958       
+ 400 0.8958       
+# 401 0.8958       
+# 402 0.8960       
+# 403 0.8962       
+# 404 0.8963       
+# 405 0.8963       
+# 406 0.8965       
+# 407 0.8965       
+# 408 0.8966       
+ 409 0.8965       
+# 410 0.8968       
+# 411 0.8967       
+# 412 0.8970       
+# 413 0.8968       
+ 414 0.8966       
+# 415 0.8965       
+# 416 0.8967       
+# 417 0.8967       
+# 418 0.8967       
+ 419 0.8967       
+# 420 0.8967       
+# 421 0.8968       
+# 422 0.8965       
+# 423 0.8966       
+ 424 0.8966       
+# 425 0.8965       
+# 426 0.8965       
+# 427 0.8965       
+# 428 0.8962       
+ 429 0.8962       
+# 430 0.8960       
+# 431 0.8959       
+# 432 0.8957       
+# 433 0.8958       
+ 434 0.8957       
+# 435 0.8957       
+# 436 0.8955       
+# 437 0.8954       
+# 438 0.8951       
+# 439 0.8951       
+# 440 0.8949       
+# 441 0.8947       
+# 442 0.8944       
+ 443 0.8941       
+# 444 0.8941       
+# 445 0.8939       
+# 446 0.8939       
+# 447 0.8939       
+ 448 0.8938       
+# 449 0.8938       
+# 450 0.8938       
+# 451 0.8939       
+# 452 0.8940       
+ 453 0.8940       
+# 454 0.8942       
+# 455 0.8943       
+# 456 0.8943       
+# 457 0.8944       
+ 458 0.8942       
+# 459 0.8943       
+# 460 0.8942       
+# 461 0.8943       
+# 462 0.8943       
+ 463 0.8940       
+# 464 0.8937       
+# 465 0.8934       
+# 466 0.8931       
+# 467 0.8929       
+ 468 0.8927       
+# 469 0.8924       
+# 470 0.8920       
+# 471 0.8917       
+# 472 0.8912       
+# 473 0.8908       
+# 474 0.8903       
+# 475 0.8898       
+# 476 0.8894       
+ 477 0.8890       
+# 478 0.8885       
+# 479 0.8880       
+# 480 0.8875       
+# 481 0.8869       
+ 482 0.8863       
+# 483 0.8857       
+# 484 0.8851       
+# 485 0.8846       
+# 486 0.8843       
+ 487 0.8840       
+# 488 0.8838       
+# 489 0.8837       
+# 490 0.8836       
+# 491 0.8834       
+ 492 0.8834       
+# 493 0.8834       
+# 494 0.8833       
+# 495 0.8833       
+# 496 0.8832       
+ 497 0.8831       
+# 498 0.8830       
+# 499 0.8829       
+# 500 0.8828       
+# 501 0.8828       
+ 502 0.8826       
+# 503 0.8824       
+# 504 0.8821       
+# 505 0.8818       
+# 506 0.8814       
+# 507 0.8810       
+# 508 0.8806       
+# 509 0.8801       
+# 510 0.8796       
+ 511 0.8793       
+# 512 0.8790       
+# 513 0.8787       
+# 514 0.8782       
+# 515 0.8776       
+ 516 0.8771       
+# 517 0.8766       
+# 518 0.8759       
+# 519 0.8754       
+# 520 0.8750       
+ 521 0.8745       
+# 522 0.8742       
+# 523 0.8738       
+# 524 0.8733       
+# 525 0.8729       
+ 526 0.8723       
+# 527 0.8718       
+# 528 0.8711       
+# 529 0.8705       
+# 530 0.8700       
+ 531 0.8696       
+# 532 0.8692       
+# 533 0.8688       
+# 534 0.8685       
+# 535 0.8679       
+ 536 0.8674       
+# 537 0.8668       
+# 538 0.8662       
+# 539 0.8656       
+# 540 0.8650       
+# 541 0.8645       
+# 542 0.8641       
+# 543 0.8638       
+# 544 0.8632       
+ 545 0.8627       
+# 546 0.8620       
+# 547 0.8616       
+# 548 0.8610       
+# 549 0.8603       
+ 550 0.8598       
+# 551 0.8594       
+# 552 0.8587       
+# 553 0.8583       
+# 554 0.8578       
+ 555 0.8574       
+# 556 0.8569       
+# 557 0.8563       
+# 558 0.8557       
+# 559 0.8551       
+ 560 0.8545       
+# 561 0.8541       
+# 562 0.8536       
+# 563 0.8530       
+# 564 0.8524       
+ 565 0.8518       
+# 566 0.8513       
+# 567 0.8508       
+# 568 0.8500       
+# 569 0.8496       
+ 570 0.8490       
+# 571 0.8484       
+# 572 0.8480       
+# 573 0.8475       
+# 574 0.8467       
+# 575 0.8463       
+# 576 0.8459       
+# 577 0.8452       
+# 578 0.8446       
+ 579 0.8441       
+# 580 0.8435       
+# 581 0.8428       
+# 582 0.8422       
+# 583 0.8416       
+ 584 0.8410       
+# 585 0.8407       
+# 586 0.8401       
+# 587 0.8396       
+# 588 0.8392       
+ 589 0.8386       
+# 590 0.8379       
+# 591 0.8375       
+# 592 0.8366       
+# 593 0.8358       
+ 594 0.8354       
+# 595 0.8345       
+# 596 0.8339       
+# 597 0.8334       
+# 598 0.8330       
+ 599 0.8325       
+# 600 0.8322       
+# 601 0.8316       
+# 602 0.8311       
+# 603 0.8305       
+ 604 0.8298       
+# 605 0.8291       
+# 606 0.8283       
+# 607 0.8276       
+# 608 0.8270       
+# 609 0.8262       
+# 610 0.8256       
+# 611 0.8249       
+# 612 0.8246       
+ 613 0.8241       
+# 614 0.8252       
+# 615 0.8367       
+# 616 0.8225       
+# 617 0.8220       
+ 618 0.8216       
+# 619 0.8209       
+# 620 0.8203       
+# 621 0.8195       
+# 622 0.8188       
+ 623 0.8179       
+# 624 0.8171       
+# 625 0.8166       
+# 626 0.8159       
+# 627 0.8156       
+ 628 0.8151       
+# 629 0.8145       
+# 630 0.8140       
+# 631 0.8135       
+# 632 0.8130       
+ 633 0.8125       
+# 634 0.8118       
+# 635 0.8111       
+# 636 0.8104       
+# 637 0.8096       
+ 638 0.8089       
+# 639 0.8082       
+# 640 0.8075       
+# 641 0.8068       
+# 642 0.8064       
+# 643 0.8058       
+# 644 0.8053       
+# 645 0.8047       
+# 646 0.8042       
+ 647 0.8037       
+# 648 0.8031       
+# 649 0.8025       
+# 650 0.8019       
+# 651 0.8011       
+ 652 0.8005       
+# 653 0.7997       
+# 654 0.7992       
+# 655 0.7986       
+# 656 0.7979       
+ 657 0.7972       
+# 658 0.7965       
+# 659 0.7961       
+# 660 0.7956       
+# 661 0.7949       
+ 662 0.7944       
+# 663 0.7937       
+# 664 0.7931       
+# 665 0.7925       
+# 666 0.7918       
+ 667 0.7913       
+# 668 0.7907       
+# 669 0.7901       
+# 670 0.7895       
+# 671 0.7889       
+ 672 0.7883       
+# 673 0.7878       
+# 674 0.7872       
+# 675 0.7866       
+# 676 0.7860       
+# 677 0.7854       
+# 678 0.7848       
+# 679 0.7842       
+# 680 0.7835       
+ 681 0.7827       
+# 682 0.7820       
+# 683 0.7815       
+# 684 0.7809       
+# 685 0.7803       
+ 686 0.7798       
+# 687 0.7792       
+# 688 0.7788       
+# 689 0.7782       
+# 690 0.7777       
+ 691 0.7771       
+# 692 0.7766       
+# 693 0.7759       
+# 694 0.7752       
+# 695 0.7745       
+ 696 0.7740       
+# 697 0.7734       
+# 698 0.7727       
+# 699 0.7720       
+# 700 0.7714       
+ 701 0.7708       
+# 702 0.7702       
+# 703 0.7696       
+# 704 0.7692       
+# 705 0.7689       
+ 706 0.7682       
+# 707 0.7677       
+# 708 0.7673       
+# 709 0.7667       
+# 710 0.7661       
+# 711 0.7655       
+# 712 0.7649       
+# 713 0.7641       
+# 714 0.7634       
+ 715 0.7629       
+# 716 0.7621       
+# 717 0.7614       
+# 718 0.7609       
+# 719 0.7603       
+ 720 0.7599       
+# 721 0.7595       
+# 722 0.7590       
+# 723 0.7586       
+# 724 0.7583       
+ 725 0.7578       
+# 726 0.7572       
+# 727 0.7568       
+# 728 0.7563       
+# 729 0.7558       
+ 730 0.7552       
+# 731 0.7545       
+# 732 0.7538       
+# 733 0.7532       
+# 734 0.7524       
+ 735 0.7518       
+# 736 0.7510       
+# 737 0.7505       
+# 738 0.7501       
+# 739 0.7496       
+ 740 0.7492       
+# 741 0.7488       
+# 742 0.7483       
+# 743 0.7481       
+# 744 0.7478       
+# 745 0.7475       
+# 746 0.7471       
+# 747 0.7467       
+# 748 0.7462       
+ 749 0.7457       
+# 750 0.7453       
+# 751 0.7447       
+# 752 0.7441       
+# 753 0.7435       
+ 754 0.7428       
+# 755 0.7421       
+# 756 0.7416       
+# 757 0.7412       
+# 758 0.7405       
+ 759 0.7399       
+# 760 0.7395       
+# 761 0.7390       
+# 762 0.7387       
+# 763 0.7384       
+ 764 0.7382       
+# 765 0.7380       
+# 766 0.7377       
+# 767 0.7374       
+# 768 0.7371       
+ 769 0.7368       
+# 770 0.7367       
+# 771 0.7362       
+# 772 0.7358       
+# 773 0.7354       
+ 774 0.7351       
+# 775 0.7346       
+# 776 0.7342       
+# 777 0.7337       
+# 778 0.7334       
+# 779 0.7327       
+# 780 0.7324       
+# 781 0.7319       
+# 782 0.7316       
+ 783 0.7312       
+# 784 0.7309       
+# 785 0.7306       
+# 786 0.7304       
+# 787 0.7302       
+ 788 0.7300       
+# 789 0.7298       
+# 790 0.7298       
+# 791 0.7296       
+# 792 0.7295       
+ 793 0.7292       
+# 794 0.7290       
+# 795 0.7290       
+# 796 0.7288       
+# 797 0.7286       
+ 798 0.7286       
+# 799 0.7281       
+ 800 0.7282
+ 900 0.685
+950 0.6634
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/Transmittance_1439Cones_FACT.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/Transmittance_1439Cones_FACT.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/Transmittance_1439Cones_FACT.txt	(revision 17960)
@@ -0,0 +1,37 @@
+250    0.05566
+260    0.081966
+270    0.061284
+280    0.30381
+290    2.0164
+300    9.0906
+310    23.9483
+320    42.2324
+330    55.5866
+340    64.5322
+350    70.9289
+360    75.7315
+370    79.624
+380    82.4558
+390    84.2468
+400    85.3939
+410    86.1924
+420    86.6997
+430    87.1904
+440    87.5743
+450    87.8966
+460    88.1858
+470    88.3873
+480    88.636
+490    88.9237
+500    89.0949
+510    89.2239
+520    89.3734
+530    89.5242
+540    89.6486
+550    89.755
+560    89.8537
+570    89.8963
+580    89.9302
+590    89.9906
+600    90.0801
+700    90.0
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/Transmittance_1439Cones_FACT_bearbeitet.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/Transmittance_1439Cones_FACT_bearbeitet.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/Transmittance_1439Cones_FACT_bearbeitet.txt	(revision 17960)
@@ -0,0 +1,44 @@
+# several points are outcomment, for a faster calculation of the spline
+250    0.0005566
+#260    0.00081966
+270    0.00061284
+280    0.0030381
+290    0.020164
+300    0.090906
+310    0.239483
+320    0.422324
+330    0.555866
+340    0.645322
+350    0.709289
+360    0.757315
+370    0.79624
+380    0.824558
+390    0.842468
+400    0.853939
+#410    0.861924
+420    0.866997
+#430    0.871904
+440    0.875743
+#450    0.878966
+460    0.881858
+#470    0.883873
+480    0.88636
+490    0.889237
+500    0.890949
+#510    0.892239
+#520    0.893734
+530    0.895242
+#540    0.896486
+#550    0.89755
+560    0.898537
+#570    0.898963
+#580    0.899302
+590    0.899906
+600    0.900801
+700    0.900
+# artificial points for ceres
+800    0.9
+900    0.9
+950    0.9
+
+
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres20130911_noComments.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres20130911_noComments.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres20130911_noComments.rc	(revision 17960)
@@ -0,0 +1,55 @@
+MLog.VerbosityLevel: 4
+
+BinningImpact.Raw:       40   0       1000
+BinningTrigPos.Raw:     300    -25       275
+
+RandomNumberGenerator: TRandom3
+
+Reflector.Constructor: MReflector
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+Reflector.SetSigmaPSF: 10.0
+
+MGeomCam.Constructor:   MGeomCamFACT();
+
+MSimAPD.Type: 4
+MSimExcessNoise.ExcessNoise: 0.12
+
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+#MSimRandomPhotons.FrequencyFixed: 0.004
+#MSimRandomPhotons.FrequencyNSB:   0.025
+#MSimRandomPhotons.FileName:
+
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+MSimTrigger.DiscriminatorThreshold: 39738
+
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:         300
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+MSimCamera.DefaultOffset: 3580
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+MSimCamera.fACFudgeFactor: 0.3367
+MSimCamera.fACTimeConstant: 20
+
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+Cut.Inverted: Yes
+
+Cut.Condition: MHillas.fSize>10
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres20130911_noComments_withoutNSB.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres20130911_noComments_withoutNSB.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres20130911_noComments_withoutNSB.rc	(revision 17960)
@@ -0,0 +1,55 @@
+MLog.VerbosityLevel: 4
+
+BinningImpact.Raw:       40   0       1000
+BinningTrigPos.Raw:     300    -25       275
+
+RandomNumberGenerator: TRandom3
+
+Reflector.Constructor: MReflector
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+Reflector.SetSigmaPSF: 10.0
+
+MGeomCam.Constructor:   MGeomCamFACT();
+
+MSimAPD.Type: 4
+MSimExcessNoise.ExcessNoise: 0.12
+
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+#MSimRandomPhotons.FrequencyFixed: 0.004
+MSimRandomPhotons.FrequencyNSB:   0.0
+MSimRandomPhotons.FileNameNSB:
+
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+MSimTrigger.DiscriminatorThreshold: 39738
+
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:         300
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+MSimCamera.DefaultOffset: 3580
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+MSimCamera.fACFudgeFactor: 0.3367
+MSimCamera.fACTimeConstant: 20
+
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+Cut.Inverted: Yes
+
+Cut.Condition: MHillas.fSize>10
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSB.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSB.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSB.rc	(revision 17960)
@@ -0,0 +1,296 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 4
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+MSimRandomPhotons.FileNameNSB:
+MSimRandomPhotons.FrequencyNSB:   0.0
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+#MSimTrigger.DiscriminatorThreshold: 13416
+
+# new Value from 29.01.2013: DiscriminatorThreshold is 9*offset(3280)+21*gain(328)=36408
+MSimTrigger.DiscriminatorThreshold: 36408
+
+# new Value from 28.08.2013: DiscriminatorThreshold is 9*offset(3720)+21*gain(372)=41292
+MSimTrigger.DiscriminatorThreshold: 41292
+
+# HEGRA like single pixel above threshold trigger
+#MSimTrigger.DiscriminatorThreshold:  10.00
+# Is this an option for a single pixel trigger?
+#MSimTrigger.DigitalSignalLength:     -1
+#MSimTrigger.CoincidenceTime:          3
+
+# Magic like 2NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-2NN.txt
+#MSimTrigger.DiscriminatorThreshold:  7.00
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 3NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-3NN.txt
+#MSimTrigger.DiscriminatorThreshold:  6.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 4NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-4NN.txt
+#MSimTrigger.DiscriminatorThreshold:  5.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+#MSimTrigger.FileNameRouteAC:         resmc/fact-7map.txt
+#MSimTrigger.DiscriminatorThreshold:  14040
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:        1024
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+# Old values
+# Baseline at 15 like in MAGIC
+# 1.5 bit noise for a gain of 64
+# This allows a maximum of 200phe/pix
+#MSimCamera.DefaultOffset: 960
+#MSimCamera.DefaultNoise:   96
+#MSimCamera.DefaultGain:   256
+
+# New values
+#MSimCamera.DefaultOffset: 1000
+#MSimCamera.DefaultNoise:    30
+#MSimCamera.DefaultGain:    190
+
+# New values from 7.12.2012
+# gain of one pe is ~10mV, corresponds to 328 DAC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3280 DAC)
+# electronic noise is about 0.15 pe (->50 DAC)
+#MSimCamera.DefaultOffset: 3280
+#MSimCamera.DefaultNoise:    50
+#MSimCamera.DefaultGain:    328
+
+# New values from 28.08.2013
+# Gain (integral over 30 slices) of one pe is 123.5 mV ns in real data.
+# Gain(integral over 30 slices over the PulseShape is 10.8757 1ns.
+# The scaling factor (DefaultGain) should be 123.5 / 10.8757 mV = 11,3556 mV
+# this corresponds to 372 ADC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3720 ADC)
+# electronic noise is about 1.4 mV (->45 ADC)
+MSimCamera.DefaultOffset: 3720
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.fACFudgeFactor: 0.3367
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC1.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC1.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC1.rc	(revision 17960)
@@ -0,0 +1,296 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 1
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+MSimRandomPhotons.FileNameNSB:
+MSimRandomPhotons.FrequencyNSB:   0.0
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+#MSimTrigger.DiscriminatorThreshold: 13416
+
+# new Value from 29.01.2013: DiscriminatorThreshold is 9*offset(3280)+21*gain(328)=36408
+MSimTrigger.DiscriminatorThreshold: 36408
+
+# new Value from 28.08.2013: DiscriminatorThreshold is 9*offset(3720)+21*gain(372)=41292
+MSimTrigger.DiscriminatorThreshold: 41292
+
+# HEGRA like single pixel above threshold trigger
+#MSimTrigger.DiscriminatorThreshold:  10.00
+# Is this an option for a single pixel trigger?
+#MSimTrigger.DigitalSignalLength:     -1
+#MSimTrigger.CoincidenceTime:          3
+
+# Magic like 2NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-2NN.txt
+#MSimTrigger.DiscriminatorThreshold:  7.00
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 3NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-3NN.txt
+#MSimTrigger.DiscriminatorThreshold:  6.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 4NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-4NN.txt
+#MSimTrigger.DiscriminatorThreshold:  5.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+#MSimTrigger.FileNameRouteAC:         resmc/fact-7map.txt
+#MSimTrigger.DiscriminatorThreshold:  14040
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:        1024
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+# Old values
+# Baseline at 15 like in MAGIC
+# 1.5 bit noise for a gain of 64
+# This allows a maximum of 200phe/pix
+#MSimCamera.DefaultOffset: 960
+#MSimCamera.DefaultNoise:   96
+#MSimCamera.DefaultGain:   256
+
+# New values
+#MSimCamera.DefaultOffset: 1000
+#MSimCamera.DefaultNoise:    30
+#MSimCamera.DefaultGain:    190
+
+# New values from 7.12.2012
+# gain of one pe is ~10mV, corresponds to 328 DAC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3280 DAC)
+# electronic noise is about 0.15 pe (->50 DAC)
+#MSimCamera.DefaultOffset: 3280
+#MSimCamera.DefaultNoise:    50
+#MSimCamera.DefaultGain:    328
+
+# New values from 28.08.2013
+# Gain (integral over 30 slices) of one pe is 123.5 mV ns in real data.
+# Gain(integral over 30 slices over the PulseShape is 10.8757 1ns.
+# The scaling factor (DefaultGain) should be 123.5 / 10.8757 mV = 11,3556 mV
+# this corresponds to 372 ADC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3720 ADC)
+# electronic noise is about 1.4 mV (->45 ADC)
+MSimCamera.DefaultOffset: 3720
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.fACFudgeFactor: 0.3367
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC2.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC2.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC2.rc	(revision 17960)
@@ -0,0 +1,296 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 2
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+MSimRandomPhotons.FileNameNSB:
+MSimRandomPhotons.FrequencyNSB:   0.0
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+#MSimTrigger.DiscriminatorThreshold: 13416
+
+# new Value from 29.01.2013: DiscriminatorThreshold is 9*offset(3280)+21*gain(328)=36408
+MSimTrigger.DiscriminatorThreshold: 36408
+
+# new Value from 28.08.2013: DiscriminatorThreshold is 9*offset(3720)+21*gain(372)=41292
+MSimTrigger.DiscriminatorThreshold: 41292
+
+# HEGRA like single pixel above threshold trigger
+#MSimTrigger.DiscriminatorThreshold:  10.00
+# Is this an option for a single pixel trigger?
+#MSimTrigger.DigitalSignalLength:     -1
+#MSimTrigger.CoincidenceTime:          3
+
+# Magic like 2NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-2NN.txt
+#MSimTrigger.DiscriminatorThreshold:  7.00
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 3NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-3NN.txt
+#MSimTrigger.DiscriminatorThreshold:  6.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 4NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-4NN.txt
+#MSimTrigger.DiscriminatorThreshold:  5.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+#MSimTrigger.FileNameRouteAC:         resmc/fact-7map.txt
+#MSimTrigger.DiscriminatorThreshold:  14040
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:        1024
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+# Old values
+# Baseline at 15 like in MAGIC
+# 1.5 bit noise for a gain of 64
+# This allows a maximum of 200phe/pix
+#MSimCamera.DefaultOffset: 960
+#MSimCamera.DefaultNoise:   96
+#MSimCamera.DefaultGain:   256
+
+# New values
+#MSimCamera.DefaultOffset: 1000
+#MSimCamera.DefaultNoise:    30
+#MSimCamera.DefaultGain:    190
+
+# New values from 7.12.2012
+# gain of one pe is ~10mV, corresponds to 328 DAC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3280 DAC)
+# electronic noise is about 0.15 pe (->50 DAC)
+#MSimCamera.DefaultOffset: 3280
+#MSimCamera.DefaultNoise:    50
+#MSimCamera.DefaultGain:    328
+
+# New values from 28.08.2013
+# Gain (integral over 30 slices) of one pe is 123.5 mV ns in real data.
+# Gain(integral over 30 slices over the PulseShape is 10.8757 1ns.
+# The scaling factor (DefaultGain) should be 123.5 / 10.8757 mV = 11,3556 mV
+# this corresponds to 372 ADC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3720 ADC)
+# electronic noise is about 1.4 mV (->45 ADC)
+MSimCamera.DefaultOffset: 3720
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.fACFudgeFactor: 0.3367
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC3.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC3.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC3.rc	(revision 17960)
@@ -0,0 +1,296 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 3
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+MSimRandomPhotons.FileNameNSB:
+MSimRandomPhotons.FrequencyNSB:   0.0
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+#MSimTrigger.DiscriminatorThreshold: 13416
+
+# new Value from 29.01.2013: DiscriminatorThreshold is 9*offset(3280)+21*gain(328)=36408
+MSimTrigger.DiscriminatorThreshold: 36408
+
+# new Value from 28.08.2013: DiscriminatorThreshold is 9*offset(3720)+21*gain(372)=41292
+MSimTrigger.DiscriminatorThreshold: 41292
+
+# HEGRA like single pixel above threshold trigger
+#MSimTrigger.DiscriminatorThreshold:  10.00
+# Is this an option for a single pixel trigger?
+#MSimTrigger.DigitalSignalLength:     -1
+#MSimTrigger.CoincidenceTime:          3
+
+# Magic like 2NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-2NN.txt
+#MSimTrigger.DiscriminatorThreshold:  7.00
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 3NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-3NN.txt
+#MSimTrigger.DiscriminatorThreshold:  6.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 4NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-4NN.txt
+#MSimTrigger.DiscriminatorThreshold:  5.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+#MSimTrigger.FileNameRouteAC:         resmc/fact-7map.txt
+#MSimTrigger.DiscriminatorThreshold:  14040
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:        1024
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+# Old values
+# Baseline at 15 like in MAGIC
+# 1.5 bit noise for a gain of 64
+# This allows a maximum of 200phe/pix
+#MSimCamera.DefaultOffset: 960
+#MSimCamera.DefaultNoise:   96
+#MSimCamera.DefaultGain:   256
+
+# New values
+#MSimCamera.DefaultOffset: 1000
+#MSimCamera.DefaultNoise:    30
+#MSimCamera.DefaultGain:    190
+
+# New values from 7.12.2012
+# gain of one pe is ~10mV, corresponds to 328 DAC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3280 DAC)
+# electronic noise is about 0.15 pe (->50 DAC)
+#MSimCamera.DefaultOffset: 3280
+#MSimCamera.DefaultNoise:    50
+#MSimCamera.DefaultGain:    328
+
+# New values from 28.08.2013
+# Gain (integral over 30 slices) of one pe is 123.5 mV ns in real data.
+# Gain(integral over 30 slices over the PulseShape is 10.8757 1ns.
+# The scaling factor (DefaultGain) should be 123.5 / 10.8757 mV = 11,3556 mV
+# this corresponds to 372 ADC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3720 ADC)
+# electronic noise is about 1.4 mV (->45 ADC)
+MSimCamera.DefaultOffset: 3720
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.fACFudgeFactor: 0.3367
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC4.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC4.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC4.rc	(revision 17960)
@@ -0,0 +1,296 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 4
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+MSimRandomPhotons.FileNameNSB:
+MSimRandomPhotons.FrequencyNSB:   0.0
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+#MSimTrigger.DiscriminatorThreshold: 13416
+
+# new Value from 29.01.2013: DiscriminatorThreshold is 9*offset(3280)+21*gain(328)=36408
+MSimTrigger.DiscriminatorThreshold: 36408
+
+# new Value from 28.08.2013: DiscriminatorThreshold is 9*offset(3720)+21*gain(372)=41292
+MSimTrigger.DiscriminatorThreshold: 41292
+
+# HEGRA like single pixel above threshold trigger
+#MSimTrigger.DiscriminatorThreshold:  10.00
+# Is this an option for a single pixel trigger?
+#MSimTrigger.DigitalSignalLength:     -1
+#MSimTrigger.CoincidenceTime:          3
+
+# Magic like 2NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-2NN.txt
+#MSimTrigger.DiscriminatorThreshold:  7.00
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 3NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-3NN.txt
+#MSimTrigger.DiscriminatorThreshold:  6.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 4NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-4NN.txt
+#MSimTrigger.DiscriminatorThreshold:  5.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+#MSimTrigger.FileNameRouteAC:         resmc/fact-7map.txt
+#MSimTrigger.DiscriminatorThreshold:  14040
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:        1024
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+# Old values
+# Baseline at 15 like in MAGIC
+# 1.5 bit noise for a gain of 64
+# This allows a maximum of 200phe/pix
+#MSimCamera.DefaultOffset: 960
+#MSimCamera.DefaultNoise:   96
+#MSimCamera.DefaultGain:   256
+
+# New values
+#MSimCamera.DefaultOffset: 1000
+#MSimCamera.DefaultNoise:    30
+#MSimCamera.DefaultGain:    190
+
+# New values from 7.12.2012
+# gain of one pe is ~10mV, corresponds to 328 DAC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3280 DAC)
+# electronic noise is about 0.15 pe (->50 DAC)
+#MSimCamera.DefaultOffset: 3280
+#MSimCamera.DefaultNoise:    50
+#MSimCamera.DefaultGain:    328
+
+# New values from 28.08.2013
+# Gain (integral over 30 slices) of one pe is 123.5 mV ns in real data.
+# Gain(integral over 30 slices over the PulseShape is 10.8757 1ns.
+# The scaling factor (DefaultGain) should be 123.5 / 10.8757 mV = 11,3556 mV
+# this corresponds to 372 ADC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3720 ADC)
+# electronic noise is about 1.4 mV (->45 ADC)
+MSimCamera.DefaultOffset: 3720
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.fACFudgeFactor: 0.3367
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC5.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC5.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSBXTC5.rc	(revision 17960)
@@ -0,0 +1,296 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 3
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+MSimRandomPhotons.FileNameNSB:
+MSimRandomPhotons.FrequencyNSB:   0.0
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+#MSimTrigger.DiscriminatorThreshold: 13416
+
+# new Value from 29.01.2013: DiscriminatorThreshold is 9*offset(3280)+21*gain(328)=36408
+MSimTrigger.DiscriminatorThreshold: 36408
+
+# new Value from 28.08.2013: DiscriminatorThreshold is 9*offset(3720)+21*gain(372)=41292
+MSimTrigger.DiscriminatorThreshold: 41292
+
+# HEGRA like single pixel above threshold trigger
+#MSimTrigger.DiscriminatorThreshold:  10.00
+# Is this an option for a single pixel trigger?
+#MSimTrigger.DigitalSignalLength:     -1
+#MSimTrigger.CoincidenceTime:          3
+
+# Magic like 2NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-2NN.txt
+#MSimTrigger.DiscriminatorThreshold:  7.00
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 3NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-3NN.txt
+#MSimTrigger.DiscriminatorThreshold:  6.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 4NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-4NN.txt
+#MSimTrigger.DiscriminatorThreshold:  5.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+#MSimTrigger.FileNameRouteAC:         resmc/fact-7map.txt
+#MSimTrigger.DiscriminatorThreshold:  14040
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:        1024
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+# Old values
+# Baseline at 15 like in MAGIC
+# 1.5 bit noise for a gain of 64
+# This allows a maximum of 200phe/pix
+#MSimCamera.DefaultOffset: 960
+#MSimCamera.DefaultNoise:   96
+#MSimCamera.DefaultGain:   256
+
+# New values
+#MSimCamera.DefaultOffset: 1000
+#MSimCamera.DefaultNoise:    30
+#MSimCamera.DefaultGain:    190
+
+# New values from 7.12.2012
+# gain of one pe is ~10mV, corresponds to 328 DAC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3280 DAC)
+# electronic noise is about 0.15 pe (->50 DAC)
+#MSimCamera.DefaultOffset: 3280
+#MSimCamera.DefaultNoise:    50
+#MSimCamera.DefaultGain:    328
+
+# New values from 28.08.2013
+# Gain (integral over 30 slices) of one pe is 123.5 mV ns in real data.
+# Gain(integral over 30 slices over the PulseShape is 10.8757 1ns.
+# The scaling factor (DefaultGain) should be 123.5 / 10.8757 mV = 11,3556 mV
+# this corresponds to 372 ADC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3720 ADC)
+# electronic noise is about 1.4 mV (->45 ADC)
+MSimCamera.DefaultOffset: 3720
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    358
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.fACFudgeFactor: 0.3367
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSB_Roi300.rc
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSB_Roi300.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/ceres_withoutNSB_Roi300.rc	(revision 17960)
@@ -0,0 +1,296 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+MLog.VerbosityLevel: 4
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Ceres
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#PathOut: .
+#PathIn: .
+
+
+# -------------------------------------------------------------------------
+# Configure Eventloop
+# -------------------------------------------------------------------------
+#MaxEvents: 10000
+#Overwrite: yes,no
+
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+# BinningEnergy.Raw:      100      1    100000  log
+# BinningSize.Raw:        100      1  10000000  log
+BinningImpact.Raw:       40   0       1000
+# BinningHeight.Raw:       50      0        12
+# BinningAz.Raw:          360   -360       360
+# BinningZd.Raw:           70      0        70
+# BinningViewCone.Raw:    155      0        31
+BinningTrigPos.Raw:     300    -25       275
+# BinningEvtWidth.Raw:    150      0        25
+# BinningDist.Raw:        100      0       2.5
+# BinningDistC.Raw:       100      0       2.5
+# BinningThreshold.Raw:    35    0.9     90000  log
+# BinningEnergyEst.Raw:   100    0.9     90000  log
+
+
+# -------------------------------------------------------------------------
+# Initialize random number generator (see MJob::InitRandomNumberGenerator)
+# -------------------------------------------------------------------------
+RandomNumberGenerator: TRandom3
+#RandomNumberSeedValue: 0
+
+
+# -------------------------------------------------------------------------
+# Ceres general setup
+# -------------------------------------------------------------------------
+
+# Switch off the camera "electronics"
+#Camera: Off
+
+# Force the use of the "hardware" trigger for calibration data
+#ForceTrigger: Yes
+
+
+# -------------------------------------------------------------------------
+# Some setup for the atmosphere. The default should be well suited.
+# -------------------------------------------------------------------------
+#MSimAtmosphere.FileAerosols: resmc/atmopshere-aerosols.txt
+#MSimAtmosphere.FileOzone:    resmc/atmopshere-ozone.txt
+
+
+# -------------------------------------------------------------------------
+# Here you can control the poiting of the telescope. To switch on
+# off-target observations set a value for the distance !=0 [deg].
+# For details see MSimPointingPos
+# -------------------------------------------------------------------------
+#MSimPointingPos.OffTargetDistance: 0.4
+#MSimPointingPos.OffTargetPhi: -1
+
+
+# -------------------------------------------------------------------------
+# Setup the reflector and camera geometry
+# -------------------------------------------------------------------------
+Reflector.Constructor: MReflector
+
+# For the file definition see MReflector::ReadFile
+
+Reflector.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-reflector.txt
+# Units mm: ~0.02° 
+#Reflector.SetSigmaPSF: 1.8
+# Units mm: ~0.03°
+#Reflector.SetSigmaPSF: 2.6
+#Reflector.SetSigmaPSF: 1.66
+
+# new Value from 7.12.2012:
+# 0.95 of the reflected light was inside a circle with a radius of 2.25mm. This corresponds to a SigmaPSF of 1.3 mm
+#Reflector.SetSigmaPSF: 1.3
+
+# new Value from 29.05.2013:
+# Set SigmaPSF to pixelsize
+Reflector.SetSigmaPSF: 10.0
+
+# --- DWARF ---
+# distance from mirror to camera [cm]
+#focal_distance     489.73
+# TRUE focal of the paraboloid (must correspond to that of the mirror positions defined below!)
+#paraboloid_focal   488.87
+
+#MGeomCam.Constructor:   MGeomCamDwarf(189.8,  9.5,  4.8887);
+MGeomCam.Constructor:   MGeomCamFACT();
+
+#MSimBundlePhotons.FileName: resmc/dwarf-fact.txt
+
+# Set the APD type (1: 30x30 <default>, 2: 60x60, 3:60x60(ct=15%))
+MSimAPD.Type: 4
+MSimExcessNoise.ExcessNoise: 0.12
+
+# -------------------------------------------------------------------------
+# Setup the absorption, conversion efficiency and angular acceptance
+# -------------------------------------------------------------------------
+MirrorReflectivity.FileName:           /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt
+PhotonDetectionEfficiency.FileName:    /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-pde-1.0V.txt
+ConesAngularAcceptance.FileName:       /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-cones-angular-acceptance.txt
+ConesTransmission.FileName:            /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/Transmittance_1439Cones_FACT_bearbeitet.txt
+
+# -------------------------------------------------------------------------
+# Setup what in MMCS would be called "additional spot size"
+# -------------------------------------------------------------------------
+#MSimPSF.Sigma: -1
+#MSimReflector.DetectorMargin: 0
+
+# -------------------------------------------------------------------------
+# Setup the dark counts (FrequencyFixed) and the NSB noise per cm^2
+# -------------------------------------------------------------------------
+# Dark Counts per APD: ~4MHz
+#MSimRandomPhotons.FrequencyFixed: 0.004
+# NSB photon rate per cm^2 ~40MHz (folded with the cones' angular
+# acceptance and the wavelength acceptance of the camera (window, apd, etc)
+# 0.040 1/ns/cm^2 NSB-rate:
+MSimRandomPhotons.FileNameNSB:
+MSimRandomPhotons.FrequencyNSB:   0.0
+
+# FIXME: With a class describing the cones we could give NSB as
+# per sr and cm^2
+
+# -------------------------------------------------------------------------
+# Setup the trigger
+# -------------------------------------------------------------------------
+# This line could be omitted but then the discriminator would be
+# evaluated for all pixels not just for the pixels which are
+# later "connected" in the trigger (used in the coincidence map)
+# MSimTrigger.FileNameRouteAC:         resmc/magic-trigger-1NN.txt
+
+MSimTrigger.FileNameRouteAC: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/fact-trigger-sum.txt
+#MSimTrigger.DiscriminatorThreshold: 13416
+
+# new Value from 29.01.2013: DiscriminatorThreshold is 9*offset(3280)+21*gain(328)=36408
+MSimTrigger.DiscriminatorThreshold: 36408
+
+# new Value from 28.08.2013: DiscriminatorThreshold is 9*offset(3720)+21*gain(372)=41292
+MSimTrigger.DiscriminatorThreshold: 41292
+
+# HEGRA like single pixel above threshold trigger
+#MSimTrigger.DiscriminatorThreshold:  10.00
+# Is this an option for a single pixel trigger?
+#MSimTrigger.DigitalSignalLength:     -1
+#MSimTrigger.CoincidenceTime:          3
+
+# Magic like 2NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-2NN.txt
+#MSimTrigger.DiscriminatorThreshold:  7.00
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 3NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-3NN.txt
+#MSimTrigger.DiscriminatorThreshold:  6.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Magic like 4NN trigger (inner 396 pixel)
+#MSimTrigger.FileNameCoincidenceMap:  resmc/magic-trigger-4NN.txt
+#MSimTrigger.DiscriminatorThreshold:  5.0
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+#MSimTrigger.FileNameRouteAC:         resmc/fact-7map.txt
+#MSimTrigger.DiscriminatorThreshold:  14040
+#MSimTrigger.DigitalSignalLength:     8
+#MSimTrigger.CoincidenceTime:         0.5
+
+# Every Pixel(!) should see the same signal independant of its size
+MSimCalibrationSignal.NumPhotons: 24
+MSimCalibrationSignal.NumEvents:  1000
+
+IntendedPulsePos.Val: 30
+
+#PulseShape.Function.Name: exp(-(x/2)^2/2)
+#PulseShape.FileName: /fhgfs/groups/app/mc_workshop/datacenter/setup/ceres/030/dwarf-pulse.txt
+
+# -------------------------------------------------------------------------
+# Description how a pedestal/calibration signal is produced
+# -------------------------------------------------------------------------
+
+#MSimCalibrationSignal.NumEvents:  1000
+#MSimCalibrationSignal.NumPhotons;    5
+#MSimCalibrationSignal.TimeJitter;  1.0
+
+
+# -------------------------------------------------------------------------
+# Setup the FADC
+# -------------------------------------------------------------------------
+
+MRawRunHeader.SamplingFrequency: 2000
+MRawRunHeader.NumSamples:        300
+MRawRunHeader.NumBytesPerSample:    2
+MRawRunHeader.FadcResolution:      12
+
+# Old values
+# Baseline at 15 like in MAGIC
+# 1.5 bit noise for a gain of 64
+# This allows a maximum of 200phe/pix
+#MSimCamera.DefaultOffset: 960
+#MSimCamera.DefaultNoise:   96
+#MSimCamera.DefaultGain:   358
+
+# New values
+#MSimCamera.DefaultOffset: 1000
+#MSimCamera.DefaultNoise:    30
+#MSimCamera.DefaultGain:    190
+
+# New values from 7.12.2012
+# gain of one pe is ~10mV, corresponds to 328 DAC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3280 DAC)
+# electronic noise is about 0.15 pe (->50 DAC)
+#MSimCamera.DefaultOffset: 3280
+#MSimCamera.DefaultNoise:    50
+#MSimCamera.DefaultGain:    328
+
+# New values from 28.08.2013
+# Gain (integral over 30 slices) of one pe is 123.5 mV ns in real data.
+# Gain(integral over 30 slices over the PulseShape is 10.8757 1ns.
+# The scaling factor (DefaultGain) should be 123.5 / 10.8757 mV = 11,3556 mV
+# this corresponds to 372 ADC (16 bit with a dynamic range of 2 V)
+# offset is 10 pe (->3720 ADC)
+# electronic noise is about 1.4 mV (->45 ADC)
+MSimCamera.DefaultOffset: 3720
+MSimCamera.DefaultNoise:    45
+MSimCamera.DefaultGain:    372
+
+# Value for the fudgefactor in the calculation of the accoupling:
+MSimCamera.fACFudgeFactor: 0.3367
+
+#MSimReadout.fConversionFactor: 1
+
+# The number of sampling points is almost irrelevant because they
+# are equidistant, i.e. calculated and no search is necessary.
+# Nevertheless, you must make sure that there are enough points
+# to sample the function accuratly enough.
+# Attention: x in the function is given in slices, so if you change the sampling
+# frequency you have to change also this function
+PulseShape.Function.Name:  (1.626*(1-exp(-0.3803*0.5*x))*exp(-0.0649*0.5*x))
+PulseShape.Function.Npx:   300
+PulseShape.Function.Xmin:   0
+PulseShape.Function.Xmax:   300
+
+# -------------------------------------------------------------------------
+# Setup an image cleaning on the pure gamma signal (without noise)
+# -------------------------------------------------------------------------
+
+#MImgCleanStd.CleanLevel1:   6.0
+#MImgCleanStd.CleanLevel2:   6.0
+
+# -------------------------------------------------------------------------
+# This is a cut executed after the calculation of the image parameters
+# -------------------------------------------------------------------------
+Cut.Inverted: Yes
+
+#Cut.Condition: MNewImagePar.fNumUsedPixels>3 && MHillas.fSize>6
+Cut.Condition: MHillas.fSize>10
+#&& MHillas.fSize>30
+#MSimTrigger.SimulateElectronics: Off
+
+# Does not trigger anyway
+ContEmpty3.Condition: MPhotonEvent.GetNumPhotons<10
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-pulse.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-pulse.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-pulse.txt	(revision 17960)
@@ -0,0 +1,25 @@
+-7.5 	  0            
+-6.16 	  0            
+-4.521 	  0.0148871    
+-3.85 	  0.0323368    
+-2.26295  0.377118     
+-1.38 	  0.692495     
+-0.93942  0.860482     
+-0.682 	  0.945699     
+-0.145 	  1            
+0.82529   0.83773      
+1.56058   0.701257     
+2.95764   0.547716     
+6.4871 	  0.320253     
+12.3694   0.132595     
+16.0459   0.0529824    
+22.59 	  -0.0323165   
+28.2755   -0.0843197   
+35.1635   -0.100556    
+54.1895   -0.084316    
+77.6303   -0.0520671   
+96.55 	  -0.0317267   
+116.985   -0.0198186   
+136.34 	  -0.00989597  
+151.34 	  0            
+155  	  0            
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-reflectivity-measured.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-reflectivity-measured.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-reflectivity-measured.txt	(revision 17960)
@@ -0,0 +1,11 @@
+280 0.81
+290 0.83
+320 0.88
+360 0.915
+400 0.93
+450 0.925
+500 0.903
+600 0.851
+700 0.8
+800 0.73
+999 0.64
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-reflector.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-reflector.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/dwarf-reflector.txt	(revision 17960)
@@ -0,0 +1,41 @@
+  60    0.0000  1.84098  -0.0612508 -0.0000000 0.998122 490.712  Hex 59.5
+  30   51.9615  1.84098  -0.0306254 -0.0530447 0.998122 490.712  Hex 59.5
+ -30   51.9615  1.84098   0.0306254 -0.0530447 0.998122 490.712  Hex 59.5
+ -60    0.0000  1.84098   0.0612508 -0.0000000 0.998122 490.712  Hex 59.5
+ -30  -51.9615  1.84098   0.0306254  0.0530447 0.998122 490.712  Hex 59.5
+  30  -51.9615  1.84098  -0.0306254  0.0530447 0.998122 490.712  Hex 59.5
+ 120    0.0000  7.36392  -0.1218180 -0.0000000 0.992552 496.248  Hex 59.5
+  90   51.9615  5.52294  -0.0915334 -0.0528468 0.994399 494.401  Hex 59.5
+  60  103.9230  7.36392  -0.0609090 -0.1054970 0.992552 496.248  Hex 59.5
+   0  103.9230  5.52294  -0.0000000 -0.1056940 0.994399 494.401  Hex 59.5
+ -60  103.9230  7.36392   0.0609090 -0.1054970 0.992552 496.248  Hex 59.5
+ -90   51.9615  5.52294   0.0915334 -0.0528468 0.994399 494.401  Hex 59.5
+-120    0.0000  7.36392   0.1218180 -0.0000000 0.992552 496.248  Hex 59.5
+ -90  -51.9615  5.52294   0.0915334  0.0528468 0.994399 494.401  Hex 59.5
+ -60 -103.9230  7.36392   0.0609090  0.1054970 0.992552 496.248  Hex 59.5
+   0 -103.9230  5.52294  -0.0000000  0.1056940 0.994399 494.401  Hex 59.5
+  60 -103.9230  7.36392  -0.0609090  0.1054970 0.992552 496.248  Hex 59.5
+  90  -51.9615  5.52294  -0.0915334  0.0528468 0.994399 494.401  Hex 59.5
+ 150   51.9615 12.88690  -0.1514320 -0.0524576 0.987075 501.799  Hex 59.5
+ 120  103.9230 12.88690  -0.1211460 -0.1049150 0.987075 501.799  Hex 59.5
+  30  155.8850 12.88690  -0.0302864 -0.1573730 0.987075 501.799  Hex 59.5
+ -30  155.8850 12.88690   0.0302864 -0.1573730 0.987075 501.799  Hex 59.5
+-120  103.9230 12.88690   0.1211460 -0.1049150 0.987075 501.799  Hex 59.5
+-150   51.9615 12.88690   0.1514320 -0.0524576 0.987075 501.799  Hex 59.5
+-150  -51.9615 12.88690   0.1514320  0.0524576 0.987075 501.799  Hex 59.5
+-120 -103.9230 12.88690   0.1211460  0.1049150 0.987075 501.799  Hex 59.5
+ -30 -155.8850 12.88690   0.0302864  0.1573730 0.987075 501.799  Hex 59.5
+  30 -155.8850 12.88690  -0.0302864  0.1573730 0.987075 501.799  Hex 59.5
+ 120 -103.9230 12.88690  -0.1211460  0.1049150 0.987075 501.799  Hex 59.5
+ 150  -51.9615 12.88690  -0.1514320  0.0524576 0.987075 501.799  Hex 59.5
+# 210   51.9615 23.93270  -0.2097090 -0.0518896 0.976386 512.949  Hex 59.5
+# 180  103.9230 22.09180  -0.1800740 -0.1039660 0.978143 511.087  Hex 59.5
+# 150  155.8850 23.93270  -0.1497920 -0.1556690 0.976386 512.949  Hex 59.5
+# 120  207.8460 29.45570  -0.1191940 -0.2064490 0.971170 518.547  Hex 59.5
+#  60  207.8460 23.93270  -0.0599169 -0.2075580 0.976386 512.949  Hex 59.5
+#   0  207.8460 22.09180  -0.0000000 -0.2079320 0.978143 511.087  Hex 59.5
+# -60  207.8460 23.93270   0.0599169 -0.2075580 0.976386 512.949  Hex 59.5
+#-120  207.8460 29.45570   0.1191940 -0.2064490 0.971170 518.547  Hex 59.5
+#-150  155.8850 23.93270   0.1497920 -0.1556690 0.976386 512.949  Hex 59.5
+#-180  103.9230 22.09180   0.1800740 -0.1039660 0.978143 511.087  Hex 59.5
+#-210   51.9615 23.93270   0.2097090 -0.0518896 0.976386 512.949  Hex 59.5
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-cones-angular-acceptance.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-cones-angular-acceptance.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-cones-angular-acceptance.txt	(revision 17960)
@@ -0,0 +1,43 @@
+0.0 0.937746
+#0.5 0.937746
+#1.5 0.937418
+2.5 0.93976
+#3.5 0.936127
+#4.5 0.935089
+5.5 0.936749
+#6.5 0.934326
+#7.5 0.930171
+8.5 0.928966
+#9.5 0.920311
+#10.5 0.922695
+11.5 0.924916
+12.5 0.913469
+13.5 0.908584
+14.5 0.8928
+15.5 0.876443
+#16.5 0.838244
+17.5 0.809582
+#18.5 0.766141
+19.5 0.734286
+#20.5 0.675619
+21.5 0.605115
+#22.5 0.557933
+23.5 0.510183
+#24.5 0.427758
+25.5 0.376363
+#26.5 0.347437
+27.5 0.281052
+28.5 0.220598
+#29.5 0.201032
+30.5 0.134495
+31.5 0.10123
+#32.5 0.0761607
+33.5 0.0491442
+#34.5 0.0322082
+35.5 0.012836
+#36.5 0.00400929
+37.5 0.00129465
+#38.5 0.000650586
+39.5 0
+40.5 0
+88.5 0
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-cones-trans-sample2.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-cones-trans-sample2.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-cones-trans-sample2.txt	(revision 17960)
@@ -0,0 +1,633 @@
+250 0
+260 0
+270 0
+273 0
+274 .000108507
+275 .000108507
+276 .000434028
+277 .000651042
+278 .000868056
+279 .00119358
+280 .0016276
+281 .00217014
+282 .00282118
+283 .00358073
+284 .00444878
+285 .00564236
+286 .00694444
+287 .00868056
+288 .0109592
+289 .0135634
+290 .0164931
+291 .0201823
+292 .0245226
+293 .0294054
+294 .0352648
+295 .0416667
+296 .0489366
+297 .0571832
+298 .0662977
+299 .0760634
+300 .0870226
+301 .0986328
+302 .110894
+303 .124566
+304 .139214
+305 .155056
+306 .172201
+307 .190213
+308 .208767
+309 .228299
+310 .24783
+311 .267361
+312 .286892
+313 .30599
+314 .32487
+315 .343859
+316 .361762
+317 .379015
+318 .396593
+319 .419596
+320 .435655
+321 .45204
+322 .466905
+323 .481337
+324 .496202
+325 .509874
+326 .523112
+327 .535916
+328 .548611
+329 .559896
+330 .57194
+331 .582357
+332 .592556
+333 .602865
+334 .612413
+335 .621528
+336 .630968
+337 .639431
+338 .647569
+339 .655924
+340 .663737
+341 .671007
+342 .678494
+343 .685872
+344 .6926
+345 .700087
+346 .706706
+347 .712674
+348 .719293
+349 .725369
+350 .73112
+351 .737088
+352 .742513
+353 .747179
+354 .753038
+355 .758138
+356 .763455
+357 .76888
+358 .773655
+359 .777995
+360 .78342
+361 .787977
+362 .792209
+363 .797092
+364 .801324
+365 .805556
+366 .810221
+367 .814128
+368 .818251
+369 .822917
+370 .826823
+371 .830404
+372 .834744
+373 .838433
+374 .841905
+375 .845812
+376 .849175
+377 .852865
+378 .853082
+379 .851237
+380 .854058
+381 .857096
+382 .858941
+383 .860786
+384 .863173
+385 .865126
+386 .867839
+387 .870334
+388 .871419
+389 .87283
+390 .874457
+391 .875977
+392 .87793
+393 .879883
+394 .881076
+395 .882378
+396 .883572
+397 .884983
+398 .886285
+399 .887261
+400 .888238
+401 .889431
+402 .890625
+403 .891493
+404 .892904
+405 .893772
+406 .89464
+407 .895508
+408 .896159
+409 .897027
+410 .898112
+411 .898763
+412 .899631
+413 .900391
+414 .901367
+415 .901801
+416 .902452
+417 .903103
+418 .903863
+419 .904731
+420 .905707
+421 .905816
+422 .90625
+423 .907118
+424 .907444
+425 .908529
+426 .909288
+427 .909614
+428 .910048
+429 .910916
+430 .911024
+431 .911784
+432 .912869
+433 .912869
+434 .91352
+435 .913954
+436 .91428
+437 .914931
+438 .915799
+439 .916124
+440 .916992
+441 .917535
+442 .918077
+443 .919054
+444 .919922
+445 .919488
+446 .919054
+447 .919054
+448 .91862
+449 .919162
+450 .919596
+451 .919054
+452 .919379
+453 .919488
+454 .919054
+455 .919596
+456 .919705
+457 .919162
+458 .919922
+459 .920139
+460 .920356
+461 .921332
+462 .922309
+463 .922526
+464 .923503
+465 .924588
+466 .925347
+467 .926758
+468 .927734
+469 .92806
+470 .929036
+471 .930122
+472 .93023
+473 .931641
+474 .932183
+475 .932292
+476 .93316
+477 .934028
+478 .934462
+479 .936089
+480 .939019
+481 .939236
+482 .939453
+483 .937391
+484 .934896
+485 .934679
+486 .934679
+487 .933051
+488 .932834
+489 .931858
+490 .931098
+491 .930122
+492 .929579
+493 .929036
+494 .927951
+495 .927843
+496 .927409
+497 .926432
+498 .926432
+499 .927083
+500 .926215
+501 .927083
+502 .928602
+503 .928168
+504 .930122
+505 .931315
+506 .931749
+507 .933919
+508 .935113
+509 .935872
+510 .937934
+511 .939236
+512 .93967
+513 .941406
+514 .942057
+515 .9426
+516 .943793
+517 .945313
+518 .944987
+519 .946181
+520 .946289
+521 .945964
+522 .94694
+523 .947808
+524 .94694
+525 .948134
+526 .948459
+527 .948134
+528 .948676
+529 .949219
+530 .948351
+531 .948785
+532 .949002
+533 .949219
+534 .950087
+535 .949978
+536 .949544
+537 .950304
+538 .950521
+539 .950412
+540 .950629
+541 .950955
+542 .950521
+543 .950955
+544 .951172
+545 .95128
+546 .951823
+547 .951823
+548 .95128
+549 .951823
+550 .952148
+551 .952474
+552 .952908
+553 .952691
+554 .952365
+555 .952582
+556 .952582
+557 .952799
+558 .953451
+559 .953451
+560 .952908
+561 .952908
+562 .952365
+563 .952474
+564 .952799
+565 .952474
+566 .952691
+567 .953776
+568 .953668
+569 .953559
+570 .953885
+571 .953559
+572 .953668
+573 .95421
+574 .954102
+575 .954102
+576 .954536
+577 .954427
+578 .954536
+579 .955187
+580 .954644
+581 .954536
+582 .95497
+583 .95497
+584 .954861
+585 .95497
+586 .954861
+587 .954753
+588 .955295
+589 .955078
+590 .955187
+591 .955729
+592 .955187
+593 .955404
+594 .955838
+595 .955404
+596 .955404
+597 .956055
+598 .956055
+599 .956163
+600 .95638
+601 .956272
+602 .956163
+603 .956489
+604 .95638
+605 .956597
+606 .956706
+607 .956489
+608 .956814
+609 .95714
+610 .956706
+611 .956597
+612 .956923
+613 .956489
+614 .956489
+615 .956706
+616 .95638
+617 .956163
+618 .956055
+619 .955946
+620 .95638
+621 .95638
+622 .955838
+623 .955729
+624 .956055
+625 .956163
+626 .956489
+627 .957031
+628 .956814
+629 .95714
+630 .957248
+631 .957031
+632 .957248
+633 .957682
+634 .957465
+635 .957791
+636 .957899
+637 .957791
+638 .958442
+639 .959093
+640 .95855
+641 .958876
+642 .958984
+643 .958767
+644 .959201
+645 .959744
+646 .959635
+647 .959744
+648 .960286
+649 .959852
+650 .959961
+651 .960395
+652 .960069
+653 .960395
+654 .960503
+655 .960503
+656 .960612
+657 .960938
+658 .960395
+659 .960612
+660 .961046
+661 .960938
+662 .96148
+663 .961263
+664 .960829
+665 .961155
+666 .961806
+667 .960829
+668 .961697
+669 .962023
+670 .961263
+671 .961589
+672 .961697
+673 .961046
+674 .961806
+675 .962131
+676 .961806
+677 .962348
+678 .962131
+679 .961589
+680 .96224
+681 .962999
+682 .961589
+683 .962457
+684 .961589
+685 .961914
+686 .962782
+687 .963216
+688 .961914
+689 .962131
+690 .962891
+691 .962457
+692 .962674
+693 .962674
+694 .962674
+695 .962999
+696 .963325
+697 .962565
+698 .962891
+699 .963216
+700 .961914
+701 .962782
+702 .962891
+703 .962782
+704 .963325
+705 .963867
+706 .962782
+707 .962999
+708 .962674
+709 .962891
+710 .962782
+711 .962674
+712 .961806
+713 .961806
+714 .961372
+715 .960395
+716 .960178
+717 .960503
+718 .960286
+719 .959635
+720 .958767
+721 .957574
+722 .957899
+723 .957574
+724 .955512
+725 .954753
+726 .954102
+727 .953885
+728 .95421
+729 .954319
+730 .953016
+731 .953668
+732 .953559
+733 .953451
+734 .954644
+735 .954644
+736 .95421
+737 .954861
+738 .955295
+739 .955187
+740 .956706
+741 .95714
+742 .957248
+743 .95855
+744 .95931
+745 .959961
+746 .960938
+747 .961589
+748 .961589
+749 .962674
+750 .963325
+751 .963433
+752 .964627
+753 .965495
+754 .965169
+755 .965603
+756 .965712
+757 .966037
+758 .966905
+759 .967014
+760 .966471
+761 .967122
+762 .967122
+763 .966905
+764 .96799
+765 .968207
+766 .967773
+767 .968207
+768 .967882
+769 .967773
+770 .967882
+771 .967556
+772 .967773
+773 .96799
+774 .967773
+775 .967665
+776 .967665
+777 .967773
+778 .967448
+779 .967339
+780 .967122
+781 .967014
+782 .967448
+783 .967122
+784 .966471
+785 .966688
+786 .966037
+787 .966037
+788 .966363
+789 .965929
+790 .965603
+791 .965278
+792 .964844
+793 .964518
+794 .964627
+795 .963759
+796 .963325
+797 .96365
+798 .963542
+799 .963867
+800 .964084
+801 .963542
+802 .962999
+803 .962891
+804 .963108
+805 .963433
+806 .963216
+807 .962782
+808 .963325
+809 .963759
+810 .962782
+811 .962457
+812 .963433
+813 .963108
+814 .963325
+815 .963759
+816 .962999
+817 .963216
+818 .964193
+819 .964301
+820 .964627
+821 .965495
+822 .965278
+823 .965386
+824 .966146
+825 .966146
+826 .96658
+827 .966905
+828 .96658
+829 .966688
+830 .967448
+831 .967556
+832 .968207
+833 .96875
+834 .968316
+835 .968207
+836 .968424
+837 .967773
+838 .96799
+839 .967882
+840 .967014
+841 .966905
+842 .966797
+843 .966254
+844 .96658
+845 .967014
+846 .965603
+847 .965386
+848 .965061
+849 .962999
+850 .962999
+851 .962457
+852 .960286
+853 .960178
+854 .958876
+855 .956814
+856 .95714
+857 .955078
+858 .952474
+859 .951497
+860 .949219
+861 .947374
+862 .945204
+863 .944119
+864 .941406
+865 .940321
+866 .9375
+867 .937283
+868 .934353
+869 .932509
+870 .928928
+871 .928385
+872 .925239
+873 .924696
+874 .922635
+875 .91862
+876 .91862
+877 .913411
+878 .908854
+879 .904188
+880 .899631
+881 .894965
+882 .890951
+883 .883138
+884 .87576
+885 .868273
+886 .864258
+887 .860135
+888 .85395
+889 .845812
+890 .844944
+891 .84158
+892 .837782
+893 .83941
+894 .839952
+895 .831489
+896 .831055
+897 .826714
+898 .833984
+899 .836155
+900 .834201
+# added point need for ceres
+950 .8
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-pde-1.4V.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-pde-1.4V.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-pde-1.4V.txt	(revision 17960)
@@ -0,0 +1,56 @@
+# several points are outcomment, for a faster calculation of the spline
+# 2 artificial points
+280 0
+290 0
+#
+320 0.121739
+360 0.215913
+369.655 0.237265
+380.359 0.26367
+392.682 0.285362
+400 0.298
+410 0.313043
+420 0.329652
+429.652 0.343207
+440 0.352696
+450 0.357478
+460 0.359304
+469.397 0.359992
+480 0.358696
+487.328 0.355867
+500 0.352348
+#509.192 0.345273
+520 0.336435
+#530 0.32487
+540 0.316
+#550 0.304348
+560 0.29287
+#570 0.282609
+580 0.270783
+#590 0.259739
+600 0.247565
+610 0.237043
+616.74 0.227516
+626.822 0.218219
+636.905 0.209956
+646.987 0.199626
+#660 0.190609
+#670 0.182522
+680 0.176348
+#690 0.168087
+#700 0.160609
+710 0.154609
+#720 0.147739
+#730 0.140522
+740 0.132696
+#750 0.127304
+#760 0.12
+770 0.113739
+#780 0.10713
+790 0.100696
+846.399 0.065341
+# artificial points
+880 0.01
+890 0.001
+900 0
+950 0
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-reflector-real_ceres.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-reflector-real_ceres.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-reflector-real_ceres.txt	(revision 17960)
@@ -0,0 +1,48 @@
+# x, y and z describe the x-, y- and z-coordinate of the center of the mirror (in cm)
+# nx, ny and nz describe the x-, y- and z- component of the normal vector of the mirror
+# which is normed
+# F is the focal distance of the spherical mirror (in cm)
+# Type: Hex is a hexagonal mirror
+# fD = 60.6 is the distance of two parallel sides of the hexagon (in cm)
+# the normalvectors point to (0,0,978.132)
+# Ann-Kristin Overkemping, 03 2012
+#
+# added information about PSF: theta1 is the angle according to the smearing radius
+# of 1 sigma of the PSF area (in rad)
+# Ann-Kristin Overkemping, 06 2013
+#
+# recalculated all values according to real distances of mirrors to camera,
+# real reflection positions and partly tilted mirror mountings
+# Ann-Kristin Overkemping, 07 2013
+#########################################################################################
+# x y z nx ny nz F Type fD
+31 53.694 6.745 -0.032935 -0.055560 0.997912 487.624 Hex 60.6
+62 0 10.374 -0.064847 0.000127 0.997895 488.431 Hex 60.6
+31 -53.694 7.753 -0.031980 0.054888 0.997980 488.286 Hex 60.6
+-31 -53.694 8.055 0.031505 0.055296 0.997973 488.236 Hex 60.6
+-62 0 9.064 0.062825 -0.000215 0.998025 488.218 Hex 60.6
+-31 53.694 5.434 0.031224 -0.056422 0.997919 488.133 Hex 60.6
+93.072 52.915 13.993 -0.096734 -0.054764 0.993803 488.453 Hex 60.6
+92.516 -52.915 17.144 -0.096221 0.054676 0.993857 488.496 Hex 60.6
+0 -107 10.799 0.000122 0.109760 0.993958 488.506 Hex 60.6
+-92.829 -52.915 15.372 0.095753 0.054568 0.993908 488.637 Hex 60.6
+-93.367 52.915 12.319 0.095154 -0.055501 0.993914 488.696 Hex 60.6
+0 107 12.234 -0.000817 -0.111529 0.993761 488.441 Hex 60.6
+62 107.387 16.266 -0.064900 -0.111481 0.991645 488.783 Hex 60.6
+123.448 0 22.728 -0.129106 -0.000044 0.991631 488.938 Hex 60.6
+62 -107.387 14.922 -0.063895 0.110571 0.991812 488.791 Hex 60.6
+-62 -107.387 14.302 0.063484 0.110542 0.991842 489.000 Hex 60.6
+-123.969 0 19.773 0.127436 -0.000885 0.991846 489.075 Hex 60.6
+-62 107.387 16.163 0.063208 -0.111675 0.991733 488.767 Hex 60.6
+-31 161.168 27.391 0.031514 -0.168234 0.985243 490.212 Hex 60.6
+31 161.116 27.687 -0.032460 -0.168136 0.985229 490.199 Hex 60.6
+123.743 107.331 29.558 -0.129328 -0.112322 0.985220 489.448 Hex 60.6
+154.708 53.582 29.755 -0.161510 -0.056332 0.985262 490.166 Hex 60.6
+155.212 -53.582 26.899 -0.161225 0.055293 0.985368 490.109 Hex 60.6
+124.246 -107.331 26.702 -0.128675 0.110978 0.985458 489.448 Hex 60.6
+31 -161.481 25.619 -0.032036 0.167185 0.985405 490.071 Hex 60.6
+-31 -161.481 25.619 0.032047 0.166922 0.985449 489.978 Hex 60.6
+-124.420 -107.331 25.717 0.128309 0.111059 0.985496 489.479 Hex 60.6
+-154.795 -53.582 29.263 0.160523 0.055663 0.985461 489.975 Hex 60.6
+-155.229 53.582 26.801 0.160255 -0.056631 0.985450 489.956 Hex 60.6
+-124.038 107.331 27.884 0.127897 -0.112420 0.985395 489.439 Hex 60.6
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-trigger-all.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-trigger-all.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-trigger-all.txt	(revision 17960)
@@ -0,0 +1,162 @@
+#FACT Trigger-Patches (SoftIDs)
+    1025   917  1138  1024   916  1137  1023   915  1136  
+    1022   914  1135  1021   913  1134  1020   912  1133  
+    1145  1031  1144  1030   922  1029   921   819   920  
+    1148  1034  1147  1033   925  1032   924   822   923  
+     821   725   820   724   634   723   633   549   632  
+     548   470   547   469   397   546   468   396   545  
+     818   722   817   721   631   816   720   630   815  
+     719   629   814   718   628   813   717   627   812  
+     716   626   811   715   625   810   714   624   809  
+     467   395   544   466   394   543   465   393   542  
+    1151  1037  1150  1036   928  1035   927   825   926  
+     824   728   823   727   637   726   636   552   635  
+     551   473   550   472   400   471   399   333   398  
+     332   272   331   271   217   330   270   216   329  
+     269   215   328   268   214   327   267   213   326  
+     464   392   541   463   391   540   462   390   539  
+    1154  1040  1153  1039   931  1038   930   828   929  
+     827   731   826   730   640   729   639   555   638  
+     554   476   553   475   403   474   402   336   401  
+     335   275   334   274   220   273   219   171   218  
+     170   128   169   127    91   168   126    90   167  
+     173   131   172   130    94   129    93    63    92  
+      62    38    61    37    19    60    36    18    59  
+    1157  1043  1156  1042   934  1041   933   831   932  
+     830   734   829   733   643   732   642   558   641  
+     557   479   556   478   406   477   405   339   404  
+     338   278   337   277   223   276   222   174   221  
+     833   834   832   736   737   735   645   646   644  
+     560   561   559   481   482   480   408   409   407  
+     341   342   340   280   281   279   225   226   224  
+     176   177   175   133   134   132    96    97    95  
+      65    66    64    40    41    39    21    22    20  
+      68    69    42    43    44    23    24    45    10  
+       8     9     7     1     2     6     0     3     5  
+     344   345   282   283   284   227   228   229   178  
+     179   180   135   136   137    98    99   100    67  
+     182   183   138   139   140   101   102   141    70  
+     103   142    71   104   143    72   105   144    73  
+    1163  1164  1047  1048  1049   938   939   940   835  
+     836   837   738   739   740   647   648   649   562  
+     563   564   483   484   485   410   411   412   343  
+    1166  1167  1050  1051  1052   941   942   943   838  
+     839   840   741   742   743   650   651   652   565  
+     566   567   486   487   488   413   414   415   346  
+     347   348   285   286   287   230   231   232   181  
+     350   351   288   289   290   233   234   291   184  
+     421   496   353   422   497   354   423   498   355  
+     235   292   185   236   293   186   237   294   187  
+    1169  1170  1053  1054  1055   944   945   946   841  
+     842   843   744   745   746   653   654   655   568  
+     569   570   489   490   491   416   417   418   349  
+     661   754   575   662   755   576   663   756   577  
+     664   757   578   665   758   579   666   759   580  
+     958  1069   854   959  1070   855   960  1071   856  
+     961  1072   857   962  1073   858   963  1074   859  
+    1172  1173  1056  1057  1058   947   948   949   844  
+     845   846   747   748   749   656   657   658   571  
+     572   573   492   493   494   419   420   495   352  
+    1175  1176  1059  1060  1061   950   951   952   847  
+     848   849   750   751   752   659   660   753   574  
+     955  1066   851   956  1067   852   957  1068   853  
+     967  1078   863   968  1079   864   969  1080   865  
+     964  1075   860   965  1076   861   966  1077   862  
+     769   868   770   869   974   870   975  1086   976  
+     772   871   773   872   977   873   978  1089   979  
+     508   589   509   590   677   591   678   771   679  
+     430   505   362   431   506   363   432   507   433  
+     673   766   587   674   767   588   675   768   676  
+     670   763   584   671   764   585   672   765   586  
+     427   502   359   428   503   360   429   504   361  
+     667   760   581   668   761   582   669   762   583  
+     775   874   776   875   980   876   981  1092   982  
+     511   592   512   593   680   594   681   774   682  
+     301   364   302   365   434   366   435   510   436  
+     241   298   191   242   299   192   243   300   244  
+     238   295   188   239   296   189   240   297   190  
+     424   499   356   425   500   357   426   501   358  
+     778   877   779   878   983   879   984  1095   985  
+     514   595   515   596   683   597   684   777   685  
+     304   367   305   368   437   369   438   513   439  
+     148   193   149   194   245   195   246   303   247  
+     106   145    74   107   146    75   108   147   109  
+      49    76    50    77   110    78   111   150   112  
+      25    46    11    26    47    12    27    48    28  
+     781   880   782   881   986   882   987  1098   988  
+     517   598   518   599   686   600   687   780   688  
+     307   370   308   371   440   372   441   516   442  
+     151   196   152   197   248   198   249   306   250  
+     520   601   603   602   689   691   690   783   785  
+     310   373   375   374   443   445   444   519   521  
+     154   199   201   200   251   253   252   309   311  
+      52    79    81    80   113   115   114   153   155  
+       4    13    15    14    29    31    30    51    53  
+      35    17    58    34    16    57    33    32    56  
+     157   156   204   203   202   256   255   254   314  
+      55    54    84    83    82   118   117   116   158  
+     122    86   163   121    85   162   120   119   161  
+     125    89   166   124    88   165   123    87   164  
+     787   786   888   887   886   994   993   992  1106  
+     523   522   606   605   604   694   693   692   788  
+     313   312   378   377   376   448   447   446   524  
+     790   789   891   890   889   997   996   995  1109  
+     526   525   609   608   607   697   696   695   791  
+     316   315   381   380   379   451   450   449   527  
+     160   159   207   206   205   259   258   257   317  
+     263   209   322   262   208   321   261   260   320  
+     461   389   538   460   388   537   459   387   536  
+     266   212   325   265   211   324   264   210   323  
+     793   792   894   893   892  1000   999   998  1112  
+     529   528   612   611   610   700   699   698   794  
+     319   318   384   383   382   454   453   452   530  
+     710   620   805   709   619   804   708   618   803  
+     713   623   808   712   622   807   711   621   806  
+    1016   908  1129  1015   907  1128  1014   906  1127  
+    1019   911  1132  1018   910  1131  1017   909  1130  
+     796   795   897   896   895  1003  1002  1001  1115  
+     532   531   615   614   613   703   702   701   797  
+     458   386   535   457   385   534   456   455   533  
+     799   798   900   899   898  1006  1005  1004  1118  
+     707   617   802   706   616   801   705   704   800  
+    1013   905  1126  1012   904  1125  1011   903  1124  
+#FACT Irregular-Patches (SoftIDs)
+    1348  1419  1249  1349  1420  1250  1350  1421  1251  
+    1345  1416  1246  1346  1417  1247  1347  1418  1248  
+    1256  1142  1141  1255  1028  1027   919  1026   918  
+    1140  1254  1139  1353  1253  1352  1252  1438  1351  
+    1356  1355  1260  1146  1354  1259  1258  1257  1143  
+    1424  1359  1358  1263  1423  1422  1357  1262  1261  
+    1365  1429  1364  1363  1268  1362  1267  1266  1152  
+    1428  1427  1426  1361  1425  1360  1265  1264  1149  
+    1273  1367  1272  1158  1366  1271  1270  1269  1155  
+    1160  1161  1159  1045  1046  1044   936   937   935  
+    1368  1274  1275  1162  1369  1276  1277  1278  1165  
+    1430  1370  1371  1372  1373  1279  1280  1281  1168  
+    1431  1432  1433  1374  1434  1375  1282  1283  1171  
+    1435  1376  1377  1284  1436  1437  1378  1285  1286  
+    1379  1380  1287  1174  1381  1288  1289  1290  1177  
+    1291  1178  1179  1180  1062  1063   953   954   850  
+    1064  1181  1292  1065  1182  1293  1439  1183  1294  
+    1297  1186  1384  1296  1185  1383  1295  1184  1382  
+    1300  1189  1387  1299  1188  1386  1298  1187  1385  
+    1306  1195  1393  1305  1194  1392  1304  1193  1391  
+    1303  1192  1390  1302  1191  1389  1301  1190  1388  
+     970   866   971   867   972   973  1084  1200  1201  
+    1196  1307  1197  1308  1081  1198  1082  1199  1083  
+    1085  1202  1203  1309  1087  1088  1204  1310  1205  
+    1090  1206  1091  1207  1311  1312  1394  1313  1395  
+    1094  1210  1211  1317  1399  1318  1400  1319  1401  
+    1208  1209  1093  1316  1315  1396  1397  1314  1398  
+    1096  1212  1097  1213  1214  1320  1215  1321  1322  
+    1099   989  1100  1216   990  1101  1103  1217  1102  
+     784   883   885   884   991  1105  1104  1219  1218  
+    1108  1107  1223  1222  1221  1220  1325  1324  1323  
+    1110  1225  1224  1328  1327  1404  1326  1403  1402  
+    1111  1227  1226  1329  1331  1330  1407  1406  1405  
+    1114  1113  1229  1228  1334  1333  1332  1409  1408  
+    1119  1233  1232  1336  1117  1116  1231  1230  1335  
+    1010   902  1009   901  1008  1007  1120  1235  1234  
+    1239  1338  1238  1337  1123  1237  1122  1236  1121  
+    1339  1410  1240  1340  1411  1241  1341  1412  1242  
+    1342  1413  1243  1343  1414  1244  1344  1415  1245  
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-trigger-sum.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-trigger-sum.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/fact-trigger-sum.txt	(revision 17960)
@@ -0,0 +1,162 @@
+#FACT Trigger-Patches (SoftIDs)
+    1025   917  1138  1024   916  1137  1023   915  1136  
+    1022   914  1135  1021   913  1134  1020   912  1133  
+    1145  1031  1144  1030   922  1029   921   819   920  
+    1148  1034  1147  1033   925  1032   924   822   923  
+     821   725   820   724   634   723   633   549   632  
+     548   470   547   469   397   546   468   396   545  
+     818   722   817   721   631   816   720   630   815  
+     719   629   814   718   628   813   717   627   812  
+     716   626   811   715   625   810   714   624   809  
+     467   395   544   466   394   543   465   393   542  
+    1151  1037  1150  1036   928  1035   927   825   926  
+     824   728   823   727   637   726   636   552   635  
+     551   473   550   472   400   471   399   333   398  
+     332   272   331   271   217   330   270   216   329  
+     269   215   328   268   214   327   267   213   326  
+     464   392   541   463   391   540   462   390   539  
+    1154  1040  1153  1039   931  1038   930   828   929  
+     827   731   826   730   640   729   639   555   638  
+     554   476   553   475   403   474   402   336   401  
+     335   275   334   274   220   273   219   171   218  
+     170   128   169   127    91   168   126    90   167  
+     173   131   172   130    94   129    93    63    92  
+      62    38    61    37    19    60    36    18    59  
+    1157  1043  1156  1042   934  1041   933   831   932  
+     830   734   829   733   643   732   642   558   641  
+     557   479   556   478   406   477   405   339   404  
+     338   278   337   277   223   276   222   174   221  
+     833   834   832   736   737   735   645   646   644  
+     560   561   559   481   482   480   408   409   407  
+     341   342   340   280   281   279   225   226   224  
+     176   177   175   133   134   132    96    97    95  
+      65    66    64    40    41    39    21    22    20  
+      68    69    42    43    44    23    24    45    10  
+       8     9     7     1     2     6     0     3     5  
+     344   345   282   283   284   227   228   229   178  
+     179   180   135   136   137    98    99   100    67  
+     182   183   138   139   140   101   102   141    70  
+     103   142    71   104   143    72   105   144    73  
+    1163  1164  1047  1048  1049   938   939   940   835  
+     836   837   738   739   740   647   648   649   562  
+     563   564   483   484   485   410   411   412   343  
+    1166  1167  1050  1051  1052   941   942   943   838  
+     839   840   741   742   743   650   651   652   565  
+     566   567   486   487   488   413   414   415   346  
+     347   348   285   286   287   230   231   232   181  
+     350   351   288   289   290   233   234   291   184  
+     421   496   353   422   497   354   423   498   355  
+     235   292   185   236   293   186   237   294   187  
+    1169  1170  1053  1054  1055   944   945   946   841  
+     842   843   744   745   746   653   654   655   568  
+     569   570   489   490   491   416   417   418   349  
+     661   754   575   662   755   576   663   756   577  
+     664   757   578   665   758   579   666   759   580  
+     958  1069   854   959  1070   855   960  1071   856  
+     961  1072   857   962  1073   858   963  1074   859  
+    1172  1173  1056  1057  1058   947   948   949   844  
+     845   846   747   748   749   656   657   658   571  
+     572   573   492   493   494   419   420   495   352  
+    1175  1176  1059  1060  1061   950   951   952   847  
+     848   849   750   751   752   659   660   753   574  
+     955  1066   851   956  1067   852   957  1068   853  
+     967  1078   863   968  1079   864   969  1080   865  
+     964  1075   860   965  1076   861   966  1077   862  
+     769   868   770   869   974   870   975  1086   976  
+     772   871   773   872   977   873   978  1089   979  
+     508   589   509   590   677   591   678   771   679  
+     430   505   362   431   506   363   432   507   433  
+     673   766   587   674   767   588   675   768   676  
+     670   763   584   671   764   585   672   765   586  
+     427   502   359   428   503   360   429   504   361  
+     667   760   581   668   761   582   669   762   583  
+     775   874   776   875   980   876   981  1092   982  
+     511   592   512   593   680   594   681   774   682  
+     301   364   302   365   434   366   435   510   436  
+     241   298   191   242   299   192   243   300   244  
+     238   295   188   239   296   189   240   297   190  
+     424   499   356   425   500   357   426   501   358  
+     778   877   779   878   983   879   984  1095   985  
+     514   595   515   596   683   597   684   777   685  
+     304   367   305   368   437   369   438   513   439  
+     148   193   149   194   245   195   246   303   247  
+     106   145    74   107   146    75   108   147   109  
+      49    76    50    77   110    78   111   150   112  
+      25    46    11    26    47    12    27    48    28  
+     781   880   782   881   986   882   987  1098   988  
+     517   598   518   599   686   600   687   780   688  
+     307   370   308   371   440   372   441   516   442  
+     151   196   152   197   248   198   249   306   250  
+     520   601   603   602   689   691   690   783   785  
+     310   373   375   374   443   445   444   519   521  
+     154   199   201   200   251   253   252   309   311  
+      52    79    81    80   113   115   114   153   155  
+       4    13    15    14    29    31    30    51    53  
+      35    17    58    34    16    57    33    32    56  
+     157   156   204   203   202   256   255   254   314  
+      55    54    84    83    82   118   117   116   158  
+     122    86   163   121    85   162   120   119   161  
+     125    89   166   124    88   165   123    87   164  
+     787   786   888   887   886   994   993   992  1106  
+     523   522   606   605   604   694   693   692   788  
+     313   312   378   377   376   448   447   446   524  
+     790   789   891   890   889   997   996   995  1109  
+     526   525   609   608   607   697   696   695   791  
+     316   315   381   380   379   451   450   449   527  
+     160   159   207   206   205   259   258   257   317  
+     263   209   322   262   208   321   261   260   320  
+     461   389   538   460   388   537   459   387   536  
+     266   212   325   265   211   324   264   210   323  
+     793   792   894   893   892  1000   999   998  1112  
+     529   528   612   611   610   700   699   698   794  
+     319   318   384   383   382   454   453   452   530  
+     710   620   805   709   619   804   708   618   803  
+     713   623   808   712   622   807   711   621   806  
+    1016   908  1129  1015   907  1128  1014   906  1127  
+    1019   911  1132  1018   910  1131  1017   909  1130  
+     796   795   897   896   895  1003  1002  1001  1115  
+     532   531   615   614   613   703   702   701   797  
+     458   386   535   457   385   534   456   455   533  
+     799   798   900   899   898  1006  1005  1004  1118  
+     707   617   802   706   616   801   705   704   800  
+    1013   905  1126  1012   904  1125  1011   903  1124  
+#FACT Irregular-Patches (SoftIDs)
+#    1348  1419  1249  1349  1420  1250  1350  1421  1251  
+#    1345  1416  1246  1346  1417  1247  1347  1418  1248  
+#    1256  1142  1141  1255  1028  1027   919  1026   918  
+#    1140  1254  1139  1353  1253  1352  1252  1438  1351  
+#    1356  1355  1260  1146  1354  1259  1258  1257  1143  
+#    1424  1359  1358  1263  1423  1422  1357  1262  1261  
+#    1365  1429  1364  1363  1268  1362  1267  1266  1152  
+#    1428  1427  1426  1361  1425  1360  1265  1264  1149  
+#    1273  1367  1272  1158  1366  1271  1270  1269  1155  
+#    1160  1161  1159  1045  1046  1044   936   937   935  
+#    1368  1274  1275  1162  1369  1276  1277  1278  1165  
+#    1430  1370  1371  1372  1373  1279  1280  1281  1168  
+#    1431  1432  1433  1374  1434  1375  1282  1283  1171  
+#    1435  1376  1377  1284  1436  1437  1378  1285  1286  
+#    1379  1380  1287  1174  1381  1288  1289  1290  1177  
+#    1291  1178  1179  1180  1062  1063   953   954   850  
+#    1064  1181  1292  1065  1182  1293  1439  1183  1294  
+#    1297  1186  1384  1296  1185  1383  1295  1184  1382  
+#    1300  1189  1387  1299  1188  1386  1298  1187  1385  
+#    1306  1195  1393  1305  1194  1392  1304  1193  1391  
+#    1303  1192  1390  1302  1191  1389  1301  1190  1388  
+#     970   866   971   867   972   973  1084  1200  1201  
+#    1196  1307  1197  1308  1081  1198  1082  1199  1083  
+#    1085  1202  1203  1309  1087  1088  1204  1310  1205  
+#    1090  1206  1091  1207  1311  1312  1394  1313  1395  
+#    1094  1210  1211  1317  1399  1318  1400  1319  1401  
+#    1208  1209  1093  1316  1315  1396  1397  1314  1398  
+#    1096  1212  1097  1213  1214  1320  1215  1321  1322  
+#    1099   989  1100  1216   990  1101  1103  1217  1102  
+#     784   883   885   884   991  1105  1104  1219  1218  
+#    1108  1107  1223  1222  1221  1220  1325  1324  1323  
+#    1110  1225  1224  1328  1327  1404  1326  1403  1402  
+#    1111  1227  1226  1329  1331  1330  1407  1406  1405  
+#    1114  1113  1229  1228  1334  1333  1332  1409  1408  
+#    1119  1233  1232  1336  1117  1116  1231  1230  1335  
+#    1010   902  1009   901  1008  1007  1120  1235  1234  
+#    1239  1338  1238  1337  1123  1237  1122  1236  1121  
+#    1339  1410  1240  1340  1411  1241  1341  1412  1242  
+#    1342  1413  1243  1343  1414  1244  1344  1415  1245  
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/template_rising_edge_maxprob.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/template_rising_edge_maxprob.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/template_rising_edge_maxprob.txt	(revision 17960)
@@ -0,0 +1,300 @@
+1	-1.25
+2	-1.75
+3	-1.75
+4	-0.75
+5	-1.75
+6	-0.25
+7	-0.75
+8	-1.25
+9	-1.25
+10	-0.75
+11	-1.25
+12	-0.75
+13	-1.25
+14	-0.25
+15	-0.25
+16	-0.75
+17	-1.25
+18	-0.25
+19	-0.25
+20	-0.75
+21	-0.75
+22	-1.25
+23	0.25
+24	-1.25
+25	0.25
+26	-1.25
+27	-0.75
+28	-1.25
+29	-0.75
+30	-0.25
+31	-1.25
+32	-0.25
+33	0.25
+34	-0.75
+35	-0.75
+36	-0.25
+37	-0.75
+38	-0.25
+39	-1.25
+40	-1.25
+41	-0.75
+42	-0.25
+43	-0.75
+44	-1.25
+45	-1.25
+46	-1.75
+47	-0.75
+48	-0.75
+49	-0.75
+50	-0.25
+51	-1.25
+52	-0.75
+53	-1.25
+54	-0.75
+55	-1.25
+56	-1.25
+57	-1.25
+58	-1.75
+59	-0.75
+60	-0.75
+61	-0.25
+62	-1.75
+63	-0.75
+64	-0.75
+65	-1.25
+66	-0.25
+67	-0.75
+68	-0.25
+69	0.75
+70	2.25
+71	3.75
+72	6.25
+73	7.25
+74	7.75
+75	9.25
+76	10.25
+77	11.25
+78	10.75
+79	11.25
+80	11.25
+81	10.75
+82	10.75
+83	10.25
+84	10.75
+85	9.25
+86	8.75
+87	9.25
+88	8.75
+89	7.25
+90	7.25
+91	7.75
+92	7.25
+93	7.25
+94	7.25
+95	7.25
+96	6.75
+97	6.75
+98	7.25
+99	5.75
+100	6.25
+101	5.25
+102	5.75
+103	4.75
+104	4.75
+105	4.75
+106	4.75
+107	4.25
+108	3.75
+109	4.75
+110	5.25
+111	4.75
+112	3.75
+113	3.75
+114	3.25
+115	4.25
+116	3.25
+117	2.75
+118	2.75
+119	2.75
+120	2.75
+121	2.75
+122	2.25
+123	2.75
+124	2.25
+125	2.75
+126	2.25
+127	2.25
+128	2.25
+129	2.25
+130	1.75
+131	1.75
+132	1.75
+133	1.75
+134	1.75
+135	0.75
+136	1.25
+137	0.75
+138	2.25
+139	1.25
+140	1.25
+141	1.75
+142	1.25
+143	0.75
+144	1.75
+145	1.25
+146	1.25
+147	1.25
+148	1.25
+149	1.75
+150	1.25
+151	0.75
+152	1.25
+153	0.75
+154	1.25
+155	0.25
+156	1.25
+157	0.25
+158	0.75
+159	0.25
+160	-0.25
+161	0.75
+162	0.25
+163	-0.25
+164	0.75
+165	-0.75
+166	0.25
+167	0.75
+168	-0.25
+169	-0.25
+170	0.25
+171	0.75
+172	-0.75
+173	-0.25
+174	-0.25
+175	-0.25
+176	-0.25
+177	-0.25
+178	0.25
+179	-0.25
+180	-0.25
+181	-0.25
+182	-0.25
+183	0.25
+184	0.25
+185	0.25
+186	0.25
+187	-0.75
+188	-0.75
+189	-0.25
+190	-0.25
+191	-0.75
+192	0.75
+193	0.75
+194	-1.25
+195	-1.25
+196	-1.25
+197	0.25
+198	-1.25
+199	0.25
+200	-0.75
+201	-1.25
+202	-0.25
+203	0.25
+204	0.25
+205	0.25
+206	0.25
+207	-1.25
+208	-0.75
+209	-0.75
+210	-0.25
+211	0.25
+212	-0.75
+213	0.25
+214	-0.25
+215	-0.75
+216	-0.75
+217	-0.25
+218	-0.75
+219	-1.25
+220	-0.75
+221	-0.25
+222	-1.25
+223	0.25
+224	-0.25
+225	-0.25
+226	0.25
+227	-1.25
+228	-0.75
+229	-0.25
+230	-0.75
+231	-0.75
+232	-0.75
+233	-0.25
+234	-1.25
+235	-1.25
+236	-0.25
+237	-0.75
+238	0.25
+239	-1.25
+240	-0.25
+241	-0.75
+242	-0.75
+243	-0.75
+244	-0.25
+245	-0.25
+246	0.75
+247	-1.75
+248	-1.25
+249	-0.75
+250	-1.75
+251	-1.25
+252	-0.75
+253	0.25
+254	-0.25
+255	-0.25
+256	-0.25
+257	-1.75
+258	-1.25
+259	-0.25
+260	0.75
+261	-2.25
+262	-1.25
+263	-0.25
+264	-0.75
+265	-1.75
+266	0.25
+267	-0.75
+268	-0.75
+269	-0.25
+270	-0.75
+271	-0.25
+272	-0.25
+273	-0.25
+274	-0.25
+275	-1.25
+276	-0.75
+277	-0.25
+278	0.25
+279	-1.25
+280	-1.75
+281	-1.25
+282	-0.75
+283	-0.75
+284	-0.25
+285	-0.25
+286	-0.75
+287	0.25
+288	-1.25
+289	-1.25
+290	-0.75
+291	-0.25
+292	-0.75
+293	-1.25
+294	-0.25
+295	-1.25
+296	-0.75
+297	-0.75
+298	-0.25
+299	-1.25
+300	-1.75
Index: branches/Mars_McMismatchStudy/resmc/fact/alternatives/template_rising_edge_maxprob_in_ns.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/alternatives/template_rising_edge_maxprob_in_ns.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/alternatives/template_rising_edge_maxprob_in_ns.txt	(revision 17960)
@@ -0,0 +1,300 @@
+-39.5 -1.25
+-39 -1.75
+-38.5 -1.75
+-38 -0.75
+-37.5 -1.75
+-37 -0.25
+-36.5 -0.75
+-36 -1.25
+-35.5 -1.25
+-35 -0.75
+-34.5 -1.25
+-34 -0.75
+-33.5 -1.25
+-33 -0.25
+-32.5 -0.25
+-32 -0.75
+-31.5 -1.25
+-31 -0.25
+-30.5 -0.25
+-30 -0.75
+-29.5 -0.75
+-29 -1.25
+-28.5 0.25
+-28 -1.25
+-27.5 0.25
+-27 -1.25
+-26.5 -0.75
+-26 -1.25
+-25.5 -0.75
+-25 -0.25
+-24.5 -1.25
+-24 -0.25
+-23.5 0.25
+-23 -0.75
+-22.5 -0.75
+-22 -0.25
+-21.5 -0.75
+-21 -0.25
+-20.5 -1.25
+-20 -1.25
+-19.5 -0.75
+-19 -0.25
+-18.5 -0.75
+-18 -1.25
+-17.5 -1.25
+-17 -1.75
+-16.5 -0.75
+-16 -0.75
+-15.5 -0.75
+-15 -0.25
+-14.5 -1.25
+-14 -0.75
+-13.5 -1.25
+-13 -0.75
+-12.5 -1.25
+-12 -1.25
+-11.5 -1.25
+-11 -1.75
+-10.5 -0.75
+-10 -0.75
+-9.5 -0.25
+-9 -1.75
+-8.5 -0.75
+-8 -0.75
+-7.5 -1.25
+-7 -0.25
+-6.5 -0.75
+-6 -0.25
+-5.5 0.75
+-5 2.25
+-4.5 3.75
+-4 6.25
+-3.5 7.25
+-3 7.75
+-2.5 9.25
+-2 10.25
+-1.5 11.25
+-1 10.75
+-0.5 11.25
+0 11.25
+0.5 10.75
+1 10.75
+1.5 10.25
+2 10.75
+2.5 9.25
+3 8.75
+3.5 9.25
+4 8.75
+4.5 7.25
+5 7.25
+5.5 7.75
+6 7.25
+6.5 7.25
+7 7.25
+7.5 7.25
+8 6.75
+8.5 6.75
+9 7.25
+9.5 5.75
+10 6.25
+10.5 5.25
+11 5.75
+11.5 4.75
+12 4.75
+12.5 4.75
+13 4.75
+13.5 4.25
+14 3.75
+14.5 4.75
+15 5.25
+15.5 4.75
+16 3.75
+16.5 3.75
+17 3.25
+17.5 4.25
+18 3.25
+18.5 2.75
+19 2.75
+19.5 2.75
+20 2.75
+20.5 2.75
+21 2.25
+21.5 2.75
+22 2.25
+22.5 2.75
+23 2.25
+23.5 2.25
+24 2.25
+24.5 2.25
+25 1.75
+25.5 1.75
+26 1.75
+26.5 1.75
+27 1.75
+27.5 0.75
+28 1.25
+28.5 0.75
+29 2.25
+29.5 1.25
+30 1.25
+30.5 1.75
+31 1.25
+31.5 0.75
+32 1.75
+32.5 1.25
+33 1.25
+33.5 1.25
+34 1.25
+34.5 1.75
+35 1.25
+35.5 0.75
+36 1.25
+36.5 0.75
+37 1.25
+37.5 0.25
+38 1.25
+38.5 0.25
+39 0.75
+39.5 0.25
+40 -0.25
+40.5 0.75
+41 0.25
+41.5 -0.25
+42 0.75
+42.5 -0.75
+43 0.25
+43.5 0.75
+44 -0.25
+44.5 -0.25
+45 0.25
+45.5 0.75
+46 -0.75
+46.5 -0.25
+47 -0.25
+47.5 -0.25
+48 -0.25
+48.5 -0.25
+49 0.25
+49.5 -0.25
+50 -0.25
+50.5 -0.25
+51 -0.25
+51.5 0.25
+52 0.25
+52.5 0.25
+53 0.25
+53.5 -0.75
+54 -0.75
+54.5 -0.25
+55 -0.25
+55.5 -0.75
+56 0.75
+56.5 0.75
+57 -1.25
+57.5 -1.25
+58 -1.25
+58.5 0.25
+59 -1.25
+59.5 0.25
+60 -0.75
+60.5 -1.25
+61 -0.25
+61.5 0.25
+62 0.25
+62.5 0.25
+63 0.25
+63.5 -1.25
+64 -0.75
+64.5 -0.75
+65 -0.25
+65.5 0.25
+66 -0.75
+66.5 0.25
+67 -0.25
+67.5 -0.75
+68 -0.75
+68.5 -0.25
+69 -0.75
+69.5 -1.25
+70 -0.75
+70.5 -0.25
+71 -1.25
+71.5 0.25
+72 -0.25
+72.5 -0.25
+73 0.25
+73.5 -1.25
+74 -0.75
+74.5 -0.25
+75 -0.75
+75.5 -0.75
+76 -0.75
+76.5 -0.25
+77 -1.25
+77.5 -1.25
+78 -0.25
+78.5 -0.75
+79 0.25
+79.5 -1.25
+80 -0.25
+80.5 -0.75
+81 -0.75
+81.5 -0.75
+82 -0.25
+82.5 -0.25
+83 0.75
+83.5 -1.75
+84 -1.25
+84.5 -0.75
+85 -1.75
+85.5 -1.25
+86 -0.75
+86.5 0.25
+87 -0.25
+87.5 -0.25
+88 -0.25
+88.5 -1.75
+89 -1.25
+89.5 -0.25
+90 0.75
+90.5 -2.25
+91 -1.25
+91.5 -0.25
+92 -0.75
+92.5 -1.75
+93 0.25
+93.5 -0.75
+94 -0.75
+94.5 -0.25
+95 -0.75
+95.5 -0.25
+96 -0.25
+96.5 -0.25
+97 -0.25
+97.5 -1.25
+98 -0.75
+98.5 -0.25
+99 0.25
+99.5 -1.25
+100 -1.75
+100.5 -1.25
+101 -0.75
+101.5 -0.75
+102 -0.25
+102.5 -0.25
+103 -0.75
+103.5 0.25
+104 -1.25
+104.5 -1.25
+105 -0.75
+105.5 -0.25
+106 -0.75
+106.5 -1.25
+107 -0.25
+107.5 -1.25
+108 -0.75
+108.5 -0.75
+109 -0.25
+109.5 -1.25
+110 -1.75
Index: branches/Mars_McMismatchStudy/resmc/fact/fact-cones-angular-acceptance.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/fact-cones-angular-acceptance.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/fact-cones-angular-acceptance.txt	(revision 17960)
@@ -0,0 +1,43 @@
+0.0 0.937746
+#0.5 0.937746
+#1.5 0.937418
+2.5 0.93976
+#3.5 0.936127
+#4.5 0.935089
+5.5 0.936749
+#6.5 0.934326
+#7.5 0.930171
+8.5 0.928966
+#9.5 0.920311
+#10.5 0.922695
+11.5 0.924916
+12.5 0.913469
+13.5 0.908584
+14.5 0.8928
+15.5 0.876443
+#16.5 0.838244
+17.5 0.809582
+#18.5 0.766141
+19.5 0.734286
+#20.5 0.675619
+21.5 0.605115
+#22.5 0.557933
+23.5 0.510183
+#24.5 0.427758
+25.5 0.376363
+#26.5 0.347437
+27.5 0.281052
+28.5 0.220598
+#29.5 0.201032
+30.5 0.134495
+31.5 0.10123
+#32.5 0.0761607
+33.5 0.0491442
+#34.5 0.0322082
+35.5 0.012836
+#36.5 0.00400929
+37.5 0.00129465
+#38.5 0.000650586
+39.5 0
+40.5 0
+88.5 0
Index: branches/Mars_McMismatchStudy/resmc/fact/fact-pde-1.0V.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/fact-pde-1.0V.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/fact-pde-1.0V.txt	(revision 17960)
@@ -0,0 +1,57 @@
+# several points are outcomment, for a faster calculation of the spline
+# 20120415, 10:45, ftemme: Multiply the pde-values for an overvoltage of 1.4 V (from file fact-pde-1.4V.txt) with k = 0.843306985
+# 2 artificial points        
+280 0          
+290 0          
+#           
+320 0.105098129          
+360 0.1863992011          
+369.655 0.2048325318          
+380.359 0.2276281527          
+392.682 0.2463550079          
+400 0.2572654815          
+410 0.2702522085          
+420 0.2845908742          
+429.652 0.2962930004          
+440 0.3044849204          
+450 0.3086132544          
+460 0.3101896529          
+469.397 0.3107836081          
+480 0.3096647623          
+487.328 0.3072224668          
+500 0.3041844896          
+#509.192 0.2980765926          
+520 0.2904466855          
+#530 0.2804625402          
+540 0.2728050073          
+#550 0.2627457543          
+560 0.2528367167          
+#570 0.2439783237          
+580 0.2337688553          
+#590 0.224234493          
+600 0.2137245937          
+610 0.2046408776          
+616.74 0.196416152          
+626.822 0.188389987          
+636.905 0.1812564813          
+646.987 0.1723385202          
+#660 0.1645540811          
+#670 0.1575725175          
+680 0.1522424602          
+#690 0.1451106812          
+#700 0.1386548716          
+710 0.1334750296          
+#720 0.1275441107          
+#730 0.1213136241          
+740 0.1145573837          
+#750 0.1099024324          
+#760 0.1035968382          
+770 0.0981916732          
+#780 0.0924860773          
+790 0.0869315602          
+846.399 0.0564093417          
+# artificial          
+880 0.0086330699          
+890 0.000863307          
+900 0          
+950 0          
Index: branches/Mars_McMismatchStudy/resmc/fact/fact-reflector.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/fact-reflector.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/fact-reflector.txt	(revision 17960)
@@ -0,0 +1,68 @@
+ 31 53.694 5.400 -0.031804 -0.055087 0.997975 487.624 Hex 60.6
+ 62 0 4.586 -0.063556 0.000000 0.997978 488.431 Hex 60.6
+ 31 -53.694 4.732 -0.031783 0.055049 0.997978 488.286 Hex 60.6
+ -31 -53.694 4.783 0.031784 0.055052 0.997977 488.236 Hex 60.6
+ -62 0 4.801 0.063570 0.000000 0.997977 488.218 Hex 60.6
+ -31 53.694 4.886 0.031788 -0.055058 0.997977 488.133 Hex 60.6
+ 93 52.915 12.477 -0.095722 -0.054464 0.993917 488.453 Hex 60.6
+ 93 -52.915 12.433 -0.095718 0.054461 0.993918 488.496 Hex 60.6
+ 0 -107 12.422 0.000000 0.110125 0.993918 488.506 Hex 60.6
+ -93 -52.915 12.288 0.095703 0.054453 0.993919 488.637 Hex 60.6
+ -93 52.915 12.228 0.095697 -0.054450 0.993920 488.696 Hex 60.6
+ 0 107 12.489 0.000000 -0.110133 0.993917 488.441 Hex 60.6
+ 62 107.387 16.273 -0.063929 -0.110729 0.991792 488.783 Hex 60.6
+ 124 0 16.113 -0.127838 0.000000 0.991795 488.938 Hex 60.6
+ 62 -107.387 16.265 -0.063929 0.110728 0.991792 488.791 Hex 60.6
+ -62 -107.387 16.049 0.063915 0.110704 0.991796 489.000 Hex 60.6
+ -124 0 15.972 0.127820 0.000000 0.991797 489.075 Hex 60.6
+ -62 107.387 16.290 0.063931 -0.110731 0.991792 488.767 Hex 60.6
+ -31 161.043 27.101 0.032122 -0.166873 0.985455 490.212 Hex 60.6
+ 31 161.043 27.115 -0.032123 -0.166875 0.985455 490.199 Hex 60.6
+ 124 107.331 27.912 -0.128595 -0.111308 0.985431 489.448 Hex 60.6
+ 155 53.582 27.150 -0.160618 -0.055524 0.985454 490.166 Hex 60.6
+ 155 -53.582 27.210 -0.160628 0.055527 0.985452 490.109 Hex 60.6
+ 124 -107.331 27.912 -0.128595 0.111308 0.985431 489.448 Hex 60.6
+ 31 -161.043 27.250 -0.032127 0.166898 0.985451 490.071 Hex 60.6
+ -31 -161.043 27.349 0.032130 0.166915 0.985448 489.978 Hex 60.6
+ -124 -107.331 27.879 0.128590 0.111305 0.985432 489.479 Hex 60.6
+ -155 -53.582 27.352 0.160652 0.055535 0.985448 489.975 Hex 60.6
+ -155 53.582 27.373 0.160655 -0.055537 0.985447 489.956 Hex 60.6
+ -124 107.331 27.921 0.128596 -0.111310 0.985430 489.439 Hex 60.6
+
+
+
+#########################################################################################		
+# x y z nx ny nz F Type fD  								#
+
+#											#
+
+#											#
+
+# x, y and z describe the x-, y- and z-coordinate of the center of the mirror		#
+
+#											#
+
+# nx, ny and nz describe the x-, y- and z- component of the normal vector of the mirror #
+
+# which is normed									#
+
+#											#
+
+# F is the focal distance of the spherical mirror					#
+
+#											#
+
+# Type: Hex is a hexagonal mirror							#
+
+#											#
+
+# fD = 60.6 is the distance of two parallel sides of the hexagon in cm			#
+
+#										  	#
+
+# the normalvectors point to (0,0,978.132)						#
+
+#											#
+
+# Ann-Kristin Overkemping, 03 2012							#
+#########################################################################################
Index: branches/Mars_McMismatchStudy/resmc/fact/fact-trigger-sum.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/fact/fact-trigger-sum.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/fact/fact-trigger-sum.txt	(revision 17960)
@@ -0,0 +1,162 @@
+#FACT Trigger-Patches (SoftIDs)
+    1025   917  1138  1024   916  1137  1023   915  1136  
+    1022   914  1135  1021   913  1134  1020   912  1133  
+    1145  1031  1144  1030   922  1029   921   819   920  
+    1148  1034  1147  1033   925  1032   924   822   923  
+     821   725   820   724   634   723   633   549   632  
+     548   470   547   469   397   546   468   396   545  
+     818   722   817   721   631   816   720   630   815  
+     719   629   814   718   628   813   717   627   812  
+     716   626   811   715   625   810   714   624   809  
+     467   395   544   466   394   543   465   393   542  
+    1151  1037  1150  1036   928  1035   927   825   926  
+     824   728   823   727   637   726   636   552   635  
+     551   473   550   472   400   471   399   333   398  
+     332   272   331   271   217   330   270   216   329  
+     269   215   328   268   214   327   267   213   326  
+     464   392   541   463   391   540   462   390   539  
+    1154  1040  1153  1039   931  1038   930   828   929  
+     827   731   826   730   640   729   639   555   638  
+     554   476   553   475   403   474   402   336   401  
+     335   275   334   274   220   273   219   171   218  
+     170   128   169   127    91   168   126    90   167  
+     173   131   172   130    94   129    93    63    92  
+      62    38    61    37    19    60    36    18    59  
+    1157  1043  1156  1042   934  1041   933   831   932  
+     830   734   829   733   643   732   642   558   641  
+     557   479   556   478   406   477   405   339   404  
+     338   278   337   277   223   276   222   174   221  
+     833   834   832   736   737   735   645   646   644  
+     560   561   559   481   482   480   408   409   407  
+     341   342   340   280   281   279   225   226   224  
+     176   177   175   133   134   132    96    97    95  
+      65    66    64    40    41    39    21    22    20  
+      68    69    42    43    44    23    24    45    10  
+       8     9     7     1     2     6     0     3     5  
+     344   345   282   283   284   227   228   229   178  
+     179   180   135   136   137    98    99   100    67  
+     182   183   138   139   140   101   102   141    70  
+     103   142    71   104   143    72   105   144    73  
+    1163  1164  1047  1048  1049   938   939   940   835  
+     836   837   738   739   740   647   648   649   562  
+     563   564   483   484   485   410   411   412   343  
+    1166  1167  1050  1051  1052   941   942   943   838  
+     839   840   741   742   743   650   651   652   565  
+     566   567   486   487   488   413   414   415   346  
+     347   348   285   286   287   230   231   232   181  
+     350   351   288   289   290   233   234   291   184  
+     421   496   353   422   497   354   423   498   355  
+     235   292   185   236   293   186   237   294   187  
+    1169  1170  1053  1054  1055   944   945   946   841  
+     842   843   744   745   746   653   654   655   568  
+     569   570   489   490   491   416   417   418   349  
+     661   754   575   662   755   576   663   756   577  
+     664   757   578   665   758   579   666   759   580  
+     958  1069   854   959  1070   855   960  1071   856  
+     961  1072   857   962  1073   858   963  1074   859  
+    1172  1173  1056  1057  1058   947   948   949   844  
+     845   846   747   748   749   656   657   658   571  
+     572   573   492   493   494   419   420   495   352  
+    1175  1176  1059  1060  1061   950   951   952   847  
+     848   849   750   751   752   659   660   753   574  
+     955  1066   851   956  1067   852   957  1068   853  
+     967  1078   863   968  1079   864   969  1080   865  
+     964  1075   860   965  1076   861   966  1077   862  
+     769   868   770   869   974   870   975  1086   976  
+     772   871   773   872   977   873   978  1089   979  
+     508   589   509   590   677   591   678   771   679  
+     430   505   362   431   506   363   432   507   433  
+     673   766   587   674   767   588   675   768   676  
+     670   763   584   671   764   585   672   765   586  
+     427   502   359   428   503   360   429   504   361  
+     667   760   581   668   761   582   669   762   583  
+     775   874   776   875   980   876   981  1092   982  
+     511   592   512   593   680   594   681   774   682  
+     301   364   302   365   434   366   435   510   436  
+     241   298   191   242   299   192   243   300   244  
+     238   295   188   239   296   189   240   297   190  
+     424   499   356   425   500   357   426   501   358  
+     778   877   779   878   983   879   984  1095   985  
+     514   595   515   596   683   597   684   777   685  
+     304   367   305   368   437   369   438   513   439  
+     148   193   149   194   245   195   246   303   247  
+     106   145    74   107   146    75   108   147   109  
+      49    76    50    77   110    78   111   150   112  
+      25    46    11    26    47    12    27    48    28  
+     781   880   782   881   986   882   987  1098   988  
+     517   598   518   599   686   600   687   780   688  
+     307   370   308   371   440   372   441   516   442  
+     151   196   152   197   248   198   249   306   250  
+     520   601   603   602   689   691   690   783   785  
+     310   373   375   374   443   445   444   519   521  
+     154   199   201   200   251   253   252   309   311  
+      52    79    81    80   113   115   114   153   155  
+       4    13    15    14    29    31    30    51    53  
+      35    17    58    34    16    57    33    32    56  
+     157   156   204   203   202   256   255   254   314  
+      55    54    84    83    82   118   117   116   158  
+     122    86   163   121    85   162   120   119   161  
+     125    89   166   124    88   165   123    87   164  
+     787   786   888   887   886   994   993   992  1106  
+     523   522   606   605   604   694   693   692   788  
+     313   312   378   377   376   448   447   446   524  
+     790   789   891   890   889   997   996   995  1109  
+     526   525   609   608   607   697   696   695   791  
+     316   315   381   380   379   451   450   449   527  
+     160   159   207   206   205   259   258   257   317  
+     263   209   322   262   208   321   261   260   320  
+     461   389   538   460   388   537   459   387   536  
+     266   212   325   265   211   324   264   210   323  
+     793   792   894   893   892  1000   999   998  1112  
+     529   528   612   611   610   700   699   698   794  
+     319   318   384   383   382   454   453   452   530  
+     710   620   805   709   619   804   708   618   803  
+     713   623   808   712   622   807   711   621   806  
+    1016   908  1129  1015   907  1128  1014   906  1127  
+    1019   911  1132  1018   910  1131  1017   909  1130  
+     796   795   897   896   895  1003  1002  1001  1115  
+     532   531   615   614   613   703   702   701   797  
+     458   386   535   457   385   534   456   455   533  
+     799   798   900   899   898  1006  1005  1004  1118  
+     707   617   802   706   616   801   705   704   800  
+    1013   905  1126  1012   904  1125  1011   903  1124  
+#FACT Irregular-Patches (SoftIDs)
+#    1348  1419  1249  1349  1420  1250  1350  1421  1251  
+#    1345  1416  1246  1346  1417  1247  1347  1418  1248  
+#    1256  1142  1141  1255  1028  1027   919  1026   918  
+#    1140  1254  1139  1353  1253  1352  1252  1438  1351  
+#    1356  1355  1260  1146  1354  1259  1258  1257  1143  
+#    1424  1359  1358  1263  1423  1422  1357  1262  1261  
+#    1365  1429  1364  1363  1268  1362  1267  1266  1152  
+#    1428  1427  1426  1361  1425  1360  1265  1264  1149  
+#    1273  1367  1272  1158  1366  1271  1270  1269  1155  
+#    1160  1161  1159  1045  1046  1044   936   937   935  
+#    1368  1274  1275  1162  1369  1276  1277  1278  1165  
+#    1430  1370  1371  1372  1373  1279  1280  1281  1168  
+#    1431  1432  1433  1374  1434  1375  1282  1283  1171  
+#    1435  1376  1377  1284  1436  1437  1378  1285  1286  
+#    1379  1380  1287  1174  1381  1288  1289  1290  1177  
+#    1291  1178  1179  1180  1062  1063   953   954   850  
+#    1064  1181  1292  1065  1182  1293  1439  1183  1294  
+#    1297  1186  1384  1296  1185  1383  1295  1184  1382  
+#    1300  1189  1387  1299  1188  1386  1298  1187  1385  
+#    1306  1195  1393  1305  1194  1392  1304  1193  1391  
+#    1303  1192  1390  1302  1191  1389  1301  1190  1388  
+#     970   866   971   867   972   973  1084  1200  1201  
+#    1196  1307  1197  1308  1081  1198  1082  1199  1083  
+#    1085  1202  1203  1309  1087  1088  1204  1310  1205  
+#    1090  1206  1091  1207  1311  1312  1394  1313  1395  
+#    1094  1210  1211  1317  1399  1318  1400  1319  1401  
+#    1208  1209  1093  1316  1315  1396  1397  1314  1398  
+#    1096  1212  1097  1213  1214  1320  1215  1321  1322  
+#    1099   989  1100  1216   990  1101  1103  1217  1102  
+#     784   883   885   884   991  1105  1104  1219  1218  
+#    1108  1107  1223  1222  1221  1220  1325  1324  1323  
+#    1110  1225  1224  1328  1327  1404  1326  1403  1402  
+#    1111  1227  1226  1329  1331  1330  1407  1406  1405  
+#    1114  1113  1229  1228  1334  1333  1332  1409  1408  
+#    1119  1233  1232  1336  1117  1116  1231  1230  1335  
+#    1010   902  1009   901  1008  1007  1120  1235  1234  
+#    1239  1338  1238  1337  1123  1237  1122  1236  1121  
+#    1339  1410  1240  1340  1411  1241  1341  1412  1242  
+#    1342  1413  1243  1343  1414  1244  1344  1415  1245  
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-cones-inner.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-cones-inner.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-cones-inner.txt	(revision 17960)
@@ -0,0 +1,91 @@
+0 0.76689
+1 0.767188
+2 0.767655
+3 0.768267
+4 0.768986
+5 0.769804
+6 0.770669
+7 0.771571
+8 0.772459
+9 0.7733
+10 0.774058
+11 0.774677
+12 0.775129
+13 0.775351
+14 0.775305
+15 0.774922
+16 0.774165
+17 0.772956
+18 0.77125
+19 0.768978
+20 0.766071
+21 0.762467
+22 0.758089
+23 0.752863
+24 0.746714
+25 0.739565
+26 0.731332
+27 0.721932
+28 0.711278
+29 0.699282
+30 0.685851
+31 0.67089
+32 0.654304
+33 0.635991
+34 0.615851
+35 0.593779
+36 0.569668
+37 0.543407
+38 0.514884
+39 0.483986
+40 0.450593
+41 0.414586
+42 0.375842
+43 0.334236
+44 0.289641
+45 0.241926
+46 0.190959
+47 0.136603
+48 0.0787193
+49 0.01717
+50 0
+51 0
+52 0
+53 0
+54 0
+55 0
+56 0
+57 0
+58 0
+59 0
+60 0
+61 0
+62 0
+63 0
+64 0
+65 0
+66 0
+67 0
+68 0
+69 0
+70 0
+71 0
+72 0
+73 0
+74 0
+75 0
+76 0
+77 0
+78 0
+79 0
+80 0
+81 0
+82 0
+83 0
+84 0
+85 0
+86 0
+87 0
+88 0
+89 0
+90 0
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-pde.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-pde.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-pde.txt	(revision 17960)
@@ -0,0 +1,46 @@
+260  0.168976
+270  0.180823
+280  0.190639
+290  0.19218
+300  0.196431
+310  0.197546
+320  0.212858
+330  0.229798
+340  0.242375
+350  0.250858
+360  0.263936
+370  0.268997
+380  0.273221
+390  0.280902
+400  0.276798
+410  0.278339
+420  0.273486
+430  0.275343
+440  0.267152
+450  0.265158
+460  0.256554
+470  0.246537
+480  0.241916
+490  0.231595
+500  0.214683
+510  0.199858
+520  0.184623
+530  0.168351
+540  0.161342
+550  0.150584
+560  0.13536
+570  0.114933
+580  0.0872733
+590  0.0688758
+600  0.0598879
+610  0.048965
+620  0.0414054
+630  0.0340656
+640  0.0259531
+650  0.019942
+660  0.0143137
+670  0.00931912
+680  0.00660328
+690  0.00494685
+700  0.00310554
+900  0
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-reflectivity.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-reflectivity.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-reflectivity.txt	(revision 17960)
@@ -0,0 +1,49 @@
+# reflectivity file
+# reflectivity for each mirror in the frame
+# J C Gonzalez, 1998
+#
+# Modified Jan 2003, A. Moralejo: data from measurements of real mirror.
+# Modified Dec 2006, A. Moralejo: extended data up to 850 nm.
+#
+# number of datapoints
+# datapoints
+270 0.861
+280 0.864
+290 0.860
+300 0.849
+310 0.835
+320 0.819
+330 0.804
+340 0.799
+350 0.803
+360 0.811
+370 0.823
+380 0.840
+390 0.849
+400 0.860
+410 0.869
+420 0.882
+430 0.883
+440 0.887
+450 0.893
+460 0.893
+470 0.897
+480 0.902
+490 0.898
+500 0.899
+510 0.902
+520 0.897
+530 0.899
+540 0.898
+550 0.894
+560 0.893
+570 0.889
+580 0.885
+590 0.884
+600 0.878
+610 0.877
+650 0.86
+700 0.84
+750 0.81
+800 0.77
+900 0.69
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-reflector-chessboard.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-reflector-chessboard.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-reflector-chessboard.txt	(revision 17960)
@@ -0,0 +1,964 @@
+-825.0000 -375.0000  120.9856 0.23484851 0.10674932 0.96615255  1819.0634 Square 49.5
+-825.0000 -325.0000  115.8294 0.23518226 0.09264756 0.96752557  1813.8174 Square 49.5
+-825.0000 -275.0000  111.4098 0.23546947 0.07848982 0.96870712  1809.3239 Square 49.5
+-825.0000 -225.0000  115.7269 0.23669581 0.06455340 0.96943692  1805.5815 Square 49.5
+-825.0000 -175.0000  112.7805 0.23689252 0.05024993 0.97023548  1802.5890 Square 49.5
+-825.0000 -125.0000  102.5707 0.23604705 0.03576470 0.97108325  1800.3455 Square 49.5
+-825.0000  -25.0000  108.3609 0.23718851 0.00718753 0.97143706  1798.1027 Square 49.5
+-825.0000   25.0000  108.3609 0.23718851 -0.00718753 0.97143706 1798.1027 Square 49.5
+-825.0000  125.0000  102.5707 0.23604705 -0.03576470 0.97108325 1800.3455 Square 49.5
+-825.0000  175.0000  112.7805 0.23689252 -0.05024993 0.97023548 1802.5890 Square 49.5
+-825.0000  225.0000  115.7269 0.23669581 -0.06455340 0.96943692 1805.5815 Square 49.5
+-825.0000  275.0000  111.4098 0.23546947 -0.07848982 0.96870712 1809.3239 Square 49.5
+-825.0000  325.0000  115.8294 0.23518226 -0.09264756 0.96752557 1813.8174 Square 49.5
+-825.0000  375.0000  120.9856 0.23484851 -0.10674932 0.96615255 1819.0634 Square 49.5
+-775.0000 -425.0000  115.0928 0.22097369 0.12117912 0.96772220  1813.0683 Square 49.5
+-775.0000 -375.0000  109.2001 0.22133386 0.10709703 0.96929951  1807.0782 Square 49.5
+-775.0000 -325.0000  104.0439 0.22165046 0.09295019 0.97068601  1801.8411 Square 49.5
+-775.0000 -275.0000   99.6243 0.22192291 0.07874684 0.97187919  1797.3553 Square 49.5
+-775.0000 -225.0000  103.9414 0.22309255 0.06476880 0.97264316  1793.6193 Square 49.5
+-775.0000 -175.0000  100.9950 0.22327921 0.05041789 0.97344976  1790.6319 Square 49.5
+-775.0000 -125.0000   90.7852 0.22247085 0.03588240 0.97427880  1788.3922 Square 49.5
+-775.0000  -75.0000   89.3120 0.22256257 0.02153831 0.97468046  1786.8995 Square 49.5
+-775.0000  -25.0000   96.5754 0.22356009 0.00721162 0.97466347  1786.1532 Square 49.5
+-775.0000   25.0000   96.5754 0.22356009 -0.00721162 0.97466347 1786.1532 Square 49.5
+-775.0000   75.0000   89.3120 0.22256257 -0.02153831 0.97468046 1786.8995 Square 49.5
+-775.0000  125.0000   90.7852 0.22247085 -0.03588240 0.97427880 1788.3922 Square 49.5
+-775.0000  175.0000  100.9950 0.22327921 -0.05041789 0.97344976 1790.6319 Square 49.5
+-775.0000  225.0000  103.9414 0.22309255 -0.06476880 0.97264316 1793.6193 Square 49.5
+-775.0000  275.0000   99.6243 0.22192291 -0.07874684 0.97187919 1797.3553 Square 49.5
+-775.0000  325.0000  104.0439 0.22165046 -0.09295019 0.97068601 1801.8411 Square 49.5
+-775.0000  375.0000  109.2001 0.22133386 -0.10709703 0.96929951 1807.0782 Square 49.5
+-775.0000  425.0000  115.0928 0.22097369 -0.12117912 0.96772220 1813.0683 Square 49.5
+-725.0000 -475.0000  110.6732 0.20696987 0.13560095 0.96890446  1808.5752 Square 49.5
+-725.0000 -425.0000  104.0439 0.20735043 0.12155025 0.97068601  1801.8411 Square 49.5
+-725.0000 -375.0000   98.1511 0.20769047 0.10742611 0.97227789  1795.8606 Square 49.5
+-725.0000 -325.0000  100.9950 0.20887410 0.09363322 0.97344976  1790.6319 Square 49.5
+-725.0000 -275.0000   96.5754 0.20913686 0.07932777 0.97466347  1786.1532 Square 49.5
+-725.0000 -225.0000   84.8925 0.20846173 0.06469502 0.97588845  1782.4232 Square 49.5
+-725.0000 -175.0000   81.9461 0.20863429 0.05036000 0.97669627  1779.4406 Square 49.5
+-725.0000 -125.0000   87.7363 0.20966540 0.03614921 0.97710473  1777.2046 Square 49.5
+-725.0000  -75.0000   86.2631 0.20975389 0.02169868 0.97751341  1775.7142 Square 49.5
+-725.0000  -25.0000   77.5265 0.20889394 0.00720324 0.97791177  1774.9692 Square 49.5
+-725.0000   25.0000   77.5265 0.20889394 -0.00720324 0.97791177 1774.9692 Square 49.5
+-725.0000   75.0000   86.2631 0.20975389 -0.02169868 0.97751341 1775.7142 Square 49.5
+-725.0000  125.0000   87.7363 0.20966540 -0.03614921 0.97710473 1777.2046 Square 49.5
+-725.0000  175.0000   81.9461 0.20863429 -0.05036000 0.97669627 1779.4406 Square 49.5
+-725.0000  225.0000   84.8925 0.20846173 -0.06469502 0.97588845 1782.4232 Square 49.5
+-725.0000  275.0000   96.5754 0.20913686 -0.07932777 0.97466347 1786.1532 Square 49.5
+-725.0000  325.0000  100.9950 0.20887410 -0.09363322 0.97344976 1790.6319 Square 49.5
+-725.0000  375.0000   98.1511 0.20769047 -0.10742611 0.97227789 1795.8606 Square 49.5
+-725.0000  425.0000  104.0439 0.20735043 -0.12155025 0.97068601 1801.8411 Square 49.5
+-725.0000  475.0000  110.6732 0.20696987 -0.13560095 0.96890446 1808.5752 Square 49.5
+-675.0000 -525.0000  107.7269 0.19285332 0.14999702 0.96969505  1805.5815 Square 49.5
+-675.0000 -475.0000  100.3609 0.19324809 0.13598940 0.97168002  1798.1027 Square 49.5
+-675.0000 -425.0000   93.7316 0.19360546 0.12189974 0.97347695  1791.3786 Square 49.5
+-675.0000 -375.0000   87.8388 0.19392480 0.10773600 0.97508263  1785.4071 Square 49.5
+-675.0000 -325.0000   90.6827 0.19504127 0.09390876 0.97628892  1780.1862 Square 49.5
+-675.0000 -275.0000   86.2631 0.19528810 0.07956182 0.97751341  1775.7142 Square 49.5
+-675.0000 -225.0000   74.5801 0.19464912 0.06488304 0.97872463  1771.9898 Square 49.5
+-675.0000 -175.0000   71.6338 0.19481119 0.05050660 0.97953953  1769.0117 Square 49.5
+-675.0000 -125.0000   77.4240 0.19578462 0.03625641 0.97997646  1766.7790 Square 49.5
+-675.0000  -75.0000   75.9508 0.19586775 0.02176308 0.98038880  1765.2909 Square 49.5
+-675.0000  -25.0000   67.2142 0.19505505 0.00722426 0.98076569  1764.5469 Square 49.5
+-675.0000   25.0000   67.2142 0.19505505 -0.00722426 0.98076569 1764.5469 Square 49.5
+-675.0000   75.0000   75.9508 0.19586775 -0.02176308 0.98038880 1765.2909 Square 49.5
+-675.0000  125.0000   77.4240 0.19578462 -0.03625641 0.97997646 1766.7790 Square 49.5
+-675.0000  175.0000   71.6338 0.19481119 -0.05050660 0.97953953 1769.0117 Square 49.5
+-675.0000  225.0000   74.5801 0.19464912 -0.06488304 0.97872463 1771.9898 Square 49.5
+-675.0000  275.0000   86.2631 0.19528810 -0.07956182 0.97751341 1775.7142 Square 49.5
+-675.0000  325.0000   90.6827 0.19504127 -0.09390876 0.97628892 1780.1862 Square 49.5
+-675.0000  375.0000   87.8388 0.19392480 -0.10773600 0.97508263 1785.4071 Square 49.5
+-675.0000  425.0000   93.7316 0.19360546 -0.12189974 0.97347695 1791.3786 Square 49.5
+-675.0000  475.0000  100.3609 0.19324809 -0.13598940 0.97168002 1798.1027 Square 49.5
+-675.0000  525.0000  107.7269 0.19285332 -0.14999702 0.96969505 1805.5815 Square 49.5
+-625.0000 -575.0000  106.2537 0.17864081 0.16434955 0.97009107  1804.0851 Square 49.5
+-625.0000 -525.0000   98.1511 0.17904351 0.15039655 0.97227789  1795.8606 Square 49.5
+-625.0000 -475.0000   90.7852 0.17941198 0.13635310 0.97427880  1788.3922 Square 49.5
+-625.0000 -425.0000   92.1559 0.18051778 0.12275209 0.97588178  1781.6775 Square 49.5
+-625.0000 -375.0000   86.2631 0.18082232 0.10849339 0.97751341  1775.7142 Square 49.5
+-625.0000 -325.0000   73.1070 0.18030565 0.09375894 0.97913183  1770.5006 Square 49.5
+-625.0000 -275.0000   68.6874 0.18053117 0.07943371 0.98035646  1766.0349 Square 49.5
+-625.0000 -225.0000   73.0044 0.18151326 0.06534477 0.98121506  1762.3156 Square 49.5
+-625.0000 -175.0000   70.0580 0.18166790 0.05086701 0.98204344  1759.3417 Square 49.5
+-625.0000 -125.0000   59.8483 0.18098475 0.03619695 0.98281957  1757.1121 Square 49.5
+-625.0000  -75.0000   58.3751 0.18106068 0.02172728 0.98323189  1755.6261 Square 49.5
+-625.0000  -25.0000   65.6385 0.18190060 0.00727602 0.98329000  1754.8832 Square 49.5
+-625.0000   25.0000   65.6385 0.18190060 -0.00727602 0.98329000 1754.8832 Square 49.5
+-625.0000   75.0000   58.3751 0.18106068 -0.02172728 0.98323189 1755.6261 Square 49.5
+-625.0000  125.0000   59.8483 0.18098475 -0.03619695 0.98281957 1757.1121 Square 49.5
+-625.0000  175.0000   70.0580 0.18166790 -0.05086701 0.98204344 1759.3417 Square 49.5
+-625.0000  225.0000   73.0044 0.18151326 -0.06534477 0.98121506 1762.3156 Square 49.5
+-625.0000  275.0000   68.6874 0.18053117 -0.07943371 0.98035646 1766.0349 Square 49.5
+-625.0000  325.0000   73.1070 0.18030565 -0.09375894 0.97913183 1770.5006 Square 49.5
+-625.0000  375.0000   86.2631 0.18082232 -0.10849339 0.97751341 1775.7142 Square 49.5
+-625.0000  425.0000   92.1559 0.18051778 -0.12275209 0.97588178 1781.6775 Square 49.5
+-625.0000  475.0000   90.7852 0.17941198 -0.13635310 0.97427880 1788.3922 Square 49.5
+-625.0000  525.0000   98.1511 0.17904351 -0.15039655 0.97227789 1795.8606 Square 49.5
+-625.0000  575.0000  106.2537 0.17864081 -0.16434955 0.97009107 1804.0851 Square 49.5
+-575.0000 -625.0000  106.2537 0.16434955 0.17864081 0.97009107  1804.0851 Square 49.5
+-575.0000 -575.0000   97.4146 0.16475384 0.16475384 0.97247743  1795.1134 Square 49.5
+-575.0000 -525.0000   89.3120 0.16512707 0.15076819 0.97468046  1786.8995 Square 49.5
+-575.0000 -475.0000   81.9461 0.16546858 0.13669143 0.97669627  1779.4406 Square 49.5
+-575.0000 -425.0000   83.3167 0.16649716 0.12306312 0.97833234  1772.7345 Square 49.5
+-575.0000 -375.0000   77.4240 0.16677949 0.10876923 0.97997646  1766.7790 Square 49.5
+-575.0000 -325.0000   64.2678 0.16629693 0.09399392 0.98158569  1761.5720 Square 49.5
+-575.0000 -275.0000   59.8483 0.16650597 0.07963329 0.98281957  1757.1121 Square 49.5
+-575.0000 -225.0000   64.1653 0.16742010 0.06551221 0.98370659  1753.3976 Square 49.5
+-575.0000 -175.0000   61.2189 0.16756347 0.05099758 0.98454138  1750.4275 Square 49.5
+-575.0000 -125.0000   51.0091 0.16692642 0.03628835 0.98530134  1748.2008 Square 49.5
+-575.0000  -75.0000   49.5359 0.16699681 0.02178219 0.98571680  1746.7167 Square 49.5
+-575.0000  -25.0000   56.7994 0.16777923 0.00729475 0.98579760  1745.9748 Square 49.5
+-575.0000   25.0000   56.7994 0.16777923 -0.00729475 0.98579760 1745.9748 Square 49.5
+-575.0000   75.0000   49.5359 0.16699681 -0.02178219 0.98571680 1746.7167 Square 49.5
+-575.0000  125.0000   51.0091 0.16692642 -0.03628835 0.98530134 1748.2008 Square 49.5
+-575.0000  175.0000   61.2189 0.16756347 -0.05099758 0.98454138 1750.4275 Square 49.5
+-575.0000  225.0000   64.1653 0.16742010 -0.06551221 0.98370659 1753.3976 Square 49.5
+-575.0000  275.0000   59.8483 0.16650597 -0.07963329 0.98281957 1757.1121 Square 49.5
+-575.0000  325.0000   64.2678 0.16629693 -0.09399392 0.98158569 1761.5720 Square 49.5
+-575.0000  375.0000   77.4240 0.16677949 -0.10876923 0.97997646 1766.7790 Square 49.5
+-575.0000  425.0000   83.3167 0.16649716 -0.12306312 0.97833234 1772.7345 Square 49.5
+-575.0000  475.0000   81.9461 0.16546858 -0.13669143 0.97669627 1779.4406 Square 49.5
+-575.0000  525.0000   89.3120 0.16512707 -0.15076819 0.97468046 1786.8995 Square 49.5
+-575.0000  575.0000   97.4146 0.16475384 -0.16475384 0.97247743 1795.1134 Square 49.5
+-575.0000  625.0000  106.2537 0.16434955 -0.17864081 0.97009107 1804.0851 Square 49.5
+-525.0000 -675.0000  107.7269 0.14999702 0.19285332 0.96969505  1805.5815 Square 49.5
+-525.0000 -625.0000   98.1511 0.15039655 0.17904351 0.97227789  1795.8606 Square 49.5
+-525.0000 -575.0000   89.3120 0.15076819 0.16512707 0.97468046  1786.8995 Square 49.5
+-525.0000 -525.0000   89.2095 0.15176268 0.15176268 0.97669656  1778.6952 Square 49.5
+-525.0000 -475.0000   81.8435 0.15208347 0.13759933 0.97874258  1771.2452 Square 49.5
+-525.0000 -425.0000   67.2142 0.15170948 0.12281244 0.98076569  1764.5469 Square 49.5
+-525.0000 -375.0000   61.3214 0.15196349 0.10854535 0.98240776  1758.5984 Square 49.5
+-525.0000 -325.0000   64.1653 0.15286183 0.09462875 0.98370659  1753.3976 Square 49.5
+-525.0000 -275.0000   59.7457 0.15305832 0.08017340 0.98495958  1748.9429 Square 49.5
+-525.0000 -225.0000   48.0628 0.15253969 0.06537415 0.98613278  1745.2329 Square 49.5
+-525.0000 -175.0000   45.1164 0.15266863 0.05088954 0.98696633  1742.2663 Square 49.5
+-525.0000 -125.0000   50.9066 0.15345360 0.03653657 0.98748016  1740.0422 Square 49.5
+-525.0000  -75.0000   49.4334 0.15351978 0.02193140 0.98790217  1738.5599 Square 49.5
+-525.0000  -25.0000   40.6968 0.15286265 0.00727917 0.98822064  1737.8188 Square 49.5
+-525.0000   25.0000   40.6968 0.15286265 -0.00727917 0.98822064 1737.8188 Square 49.5
+-525.0000   75.0000   49.4334 0.15351978 -0.02193140 0.98790217 1738.5599 Square 49.5
+-525.0000  125.0000   50.9066 0.15345360 -0.03653657 0.98748016 1740.0422 Square 49.5
+-525.0000  175.0000   45.1164 0.15266863 -0.05088954 0.98696633 1742.2663 Square 49.5
+-525.0000  225.0000   48.0628 0.15253969 -0.06537415 0.98613278 1745.2329 Square 49.5
+-525.0000  275.0000   59.7457 0.15305832 -0.08017340 0.98495958 1748.9429 Square 49.5
+-525.0000  325.0000   64.1653 0.15286183 -0.09462875 0.98370659 1753.3976 Square 49.5
+-525.0000  375.0000   61.3214 0.15196349 -0.10854535 0.98240776 1758.5984 Square 49.5
+-525.0000  425.0000   67.2142 0.15170948 -0.12281244 0.98076569 1764.5469 Square 49.5
+-525.0000  475.0000   81.8435 0.15208347 -0.13759933 0.97874258 1771.2452 Square 49.5
+-525.0000  525.0000   89.2095 0.15176268 -0.15176268 0.97669656 1778.6952 Square 49.5
+-525.0000  575.0000   89.3120 0.15076819 -0.16512707 0.97468046 1786.8995 Square 49.5
+-525.0000  625.0000   98.1511 0.15039655 -0.17904351 0.97227789 1795.8606 Square 49.5
+-525.0000  675.0000  107.7269 0.14999702 -0.19285332 0.96969505 1805.5815 Square 49.5
+-475.0000 -725.0000  110.6732 0.13560095 0.20696987 0.96890446  1808.5752 Square 49.5
+-475.0000 -675.0000  100.3609 0.13598940 0.19324809 0.97168002  1798.1027 Square 49.5
+-475.0000 -625.0000   90.7852 0.13635310 0.17941198 0.97427880  1788.3922 Square 49.5
+-475.0000 -575.0000   81.9461 0.13669143 0.16546858 0.97669627  1779.4406 Square 49.5
+-475.0000 -525.0000   81.8435 0.13759933 0.15208347 0.97874258  1771.2452 Square 49.5
+-475.0000 -475.0000   74.4776 0.13789143 0.13789143 0.98080166  1763.8031 Square 49.5
+-475.0000 -425.0000   59.8483 0.13754841 0.12306963 0.98281957  1757.1121 Square 49.5
+-475.0000 -375.0000   53.9555 0.13777967 0.10877342 0.98447199  1751.1699 Square 49.5
+-475.0000 -325.0000   56.7994 0.13860024 0.09483174 0.98579760  1745.9748 Square 49.5
+-475.0000 -275.0000   52.3798 0.13877917 0.08034584 0.98705871  1741.5249 Square 49.5
+-475.0000 -225.0000   40.6968 0.13830430 0.06551256 0.98822064  1737.8188 Square 49.5
+-475.0000 -175.0000   37.7504 0.13842170 0.05099747 0.98905950  1734.8554 Square 49.5
+-475.0000 -125.0000   43.5407 0.13913916 0.03661557 0.98959567  1732.6337 Square 49.5
+-475.0000  -75.0000   42.0675 0.13919943 0.02197886 0.99002043  1731.1530 Square 49.5
+-475.0000  -25.0000   33.3309 0.13859837 0.00729465 0.99032181  1730.4127 Square 49.5
+-475.0000   25.0000   33.3309 0.13859837 -0.00729465 0.99032181 1730.4127 Square 49.5
+-475.0000   75.0000   42.0675 0.13919943 -0.02197886 0.99002043 1731.1530 Square 49.5
+-475.0000  125.0000   43.5407 0.13913916 -0.03661557 0.98959567 1732.6337 Square 49.5
+-475.0000  175.0000   37.7504 0.13842170 -0.05099747 0.98905950 1734.8554 Square 49.5
+-475.0000  225.0000   40.6968 0.13830430 -0.06551256 0.98822064 1737.8188 Square 49.5
+-475.0000  275.0000   52.3798 0.13877917 -0.08034584 0.98705871 1741.5249 Square 49.5
+-475.0000  325.0000   56.7994 0.13860024 -0.09483174 0.98579760 1745.9748 Square 49.5
+-475.0000  375.0000   53.9555 0.13777967 -0.10877342 0.98447199 1751.1699 Square 49.5
+-475.0000  425.0000   59.8483 0.13754841 -0.12306963 0.98281957 1757.1121 Square 49.5
+-475.0000  475.0000   74.4776 0.13789143 -0.13789143 0.98080166 1763.8031 Square 49.5
+-475.0000  525.0000   81.8435 0.13759933 -0.15208347 0.97874258 1771.2452 Square 49.5
+-475.0000  575.0000   81.9461 0.13669143 -0.16546858 0.97669627 1779.4406 Square 49.5
+-475.0000  625.0000   90.7852 0.13635310 -0.17941198 0.97427880 1788.3922 Square 49.5
+-475.0000  675.0000  100.3609 0.13598940 -0.19324809 0.97168002 1798.1027 Square 49.5
+-475.0000  725.0000  110.6732 0.13560095 -0.20696987 0.96890446 1808.5752 Square 49.5
+-425.0000 -775.0000  115.0928 0.12117912 0.22097369 0.96772220  1813.0683 Square 49.5
+-425.0000 -725.0000  104.0439 0.12155025 0.20735043 0.97068601  1801.8411 Square 49.5
+-425.0000 -675.0000   93.7316 0.12189974 0.19360546 0.97347695  1791.3786 Square 49.5
+-425.0000 -625.0000   92.1559 0.12275209 0.18051778 0.97588178  1781.6775 Square 49.5
+-425.0000 -575.0000   83.3167 0.12306312 0.16649716 0.97833234  1772.7345 Square 49.5
+-425.0000 -525.0000   67.2142 0.12281244 0.15170948 0.98076569  1764.5469 Square 49.5
+-425.0000 -475.0000   59.8483 0.12306963 0.13754841 0.98281957  1757.1121 Square 49.5
+-425.0000 -425.0000   61.2189 0.12385126 0.12385126 0.98454138  1750.4275 Square 49.5
+-425.0000 -375.0000   55.3262 0.12406403 0.10946827 0.98621743  1744.4911 Square 49.5
+-425.0000 -325.0000   42.1700 0.12369353 0.09458917 0.98780200  1739.3010 Square 49.5
+-425.0000 -275.0000   37.7504 0.12385100 0.08013888 0.98905950  1734.8554 Square 49.5
+-425.0000 -225.0000   42.0675 0.12454686 0.06593657 0.99002043  1731.1530 Square 49.5
+-425.0000 -175.0000   39.1211 0.12465493 0.05132850 0.99087160  1728.1924 Square 49.5
+-425.0000 -125.0000   28.9113 0.12416774 0.03651992 0.99158896  1725.9729 Square 49.5
+-425.0000  -75.0000   27.4381 0.12422077 0.02192131 0.99201243  1724.4936 Square 49.5
+-425.0000  -25.0000   34.7015 0.12481757 0.00734221 0.99215254  1723.7540 Square 49.5
+-425.0000   25.0000   34.7015 0.12481757 -0.00734221 0.99215254 1723.7540 Square 49.5
+-425.0000   75.0000   27.4381 0.12422077 -0.02192131 0.99201243 1724.4936 Square 49.5
+-425.0000  125.0000   28.9113 0.12416774 -0.03651992 0.99158896 1725.9729 Square 49.5
+-425.0000  175.0000   39.1211 0.12465493 -0.05132850 0.99087160 1728.1924 Square 49.5
+-425.0000  225.0000   42.0675 0.12454686 -0.06593657 0.99002043 1731.1530 Square 49.5
+-425.0000  275.0000   37.7504 0.12385100 -0.08013888 0.98905950 1734.8554 Square 49.5
+-425.0000  325.0000   42.1700 0.12369353 -0.09458917 0.98780200 1739.3010 Square 49.5
+-425.0000  375.0000   55.3262 0.12406403 -0.10946827 0.98621743 1744.4911 Square 49.5
+-425.0000  425.0000   61.2189 0.12385126 -0.12385126 0.98454138 1750.4275 Square 49.5
+-425.0000  475.0000   59.8483 0.12306963 -0.13754841 0.98281957 1757.1121 Square 49.5
+-425.0000  525.0000   67.2142 0.12281244 -0.15170948 0.98076569 1764.5469 Square 49.5
+-425.0000  575.0000   83.3167 0.12306312 -0.16649716 0.97833234 1772.7345 Square 49.5
+-425.0000  625.0000   92.1559 0.12275209 -0.18051778 0.97588178 1781.6775 Square 49.5
+-425.0000  675.0000   93.7316 0.12189974 -0.19360546 0.97347695 1791.3786 Square 49.5
+-425.0000  725.0000  104.0439 0.12155025 -0.20735043 0.97068601 1801.8411 Square 49.5
+-425.0000  775.0000  115.0928 0.12117912 -0.22097369 0.96772220 1813.0683 Square 49.5
+-375.0000 -825.0000  120.9856 0.10674932 0.23484851 0.96615255  1819.0634 Square 49.5
+-375.0000 -775.0000  109.2001 0.10709703 0.22133386 0.96929951  1807.0782 Square 49.5
+-375.0000 -725.0000   98.1511 0.10742611 0.20769047 0.97227789  1795.8606 Square 49.5
+-375.0000 -675.0000   87.8388 0.10773600 0.19392480 0.97508263  1785.4071 Square 49.5
+-375.0000 -625.0000   86.2631 0.10849339 0.18082232 0.97751341  1775.7142 Square 49.5
+-375.0000 -575.0000   77.4240 0.10876923 0.16677949 0.97997646  1766.7790 Square 49.5
+-375.0000 -525.0000   61.3214 0.10854535 0.15196349 0.98240776  1758.5984 Square 49.5
+-375.0000 -475.0000   53.9555 0.10877342 0.13777967 0.98447199  1751.1699 Square 49.5
+-375.0000 -425.0000   55.3262 0.10946827 0.12406403 0.98621743  1744.4911 Square 49.5
+-375.0000 -375.0000   49.4334 0.10965699 0.10965699 0.98790217  1738.5599 Square 49.5
+-375.0000 -325.0000   36.2773 0.10932672 0.09474983 0.98947973  1733.3742 Square 49.5
+-375.0000 -275.0000   31.8577 0.10946637 0.08027534 0.99074365  1728.9324 Square 49.5
+-375.0000 -225.0000   36.1747 0.11008525 0.06605115 0.99172500  1725.2332 Square 49.5
+-375.0000 -175.0000   33.2283 0.11018111 0.05141785 0.99258064  1722.2752 Square 49.5
+-375.0000 -125.0000   23.0186 0.10974728 0.03658243 0.99328609  1720.0576 Square 49.5
+-375.0000  -75.0000   21.5454 0.10979431 0.02195886 0.99371174  1718.5796 Square 49.5
+-375.0000  -25.0000   28.8088 0.11032538 0.00735503 0.99386831  1717.8407 Square 49.5
+-375.0000   25.0000   28.8088 0.11032538 -0.00735503 0.99386831 1717.8407 Square 49.5
+-375.0000   75.0000   21.5454 0.10979431 -0.02195886 0.99371174 1718.5796 Square 49.5
+-375.0000  125.0000   23.0186 0.10974728 -0.03658243 0.99328609 1720.0576 Square 49.5
+-375.0000  175.0000   33.2283 0.11018111 -0.05141785 0.99258064 1722.2752 Square 49.5
+-375.0000  225.0000   36.1747 0.11008525 -0.06605115 0.99172500 1725.2332 Square 49.5
+-375.0000  275.0000   31.8577 0.10946637 -0.08027534 0.99074365 1728.9324 Square 49.5
+-375.0000  325.0000   36.2773 0.10932672 -0.09474983 0.98947973 1733.3742 Square 49.5
+-375.0000  375.0000   49.4334 0.10965699 -0.10965699 0.98790217 1738.5599 Square 49.5
+-375.0000  425.0000   55.3262 0.10946827 -0.12406403 0.98621743 1744.4911 Square 49.5
+-375.0000  475.0000   53.9555 0.10877342 -0.13777967 0.98447199 1751.1699 Square 49.5
+-375.0000  525.0000   61.3214 0.10854535 -0.15196349 0.98240776 1758.5984 Square 49.5
+-375.0000  575.0000   77.4240 0.10876923 -0.16677949 0.97997646 1766.7790 Square 49.5
+-375.0000  625.0000   86.2631 0.10849339 -0.18082232 0.97751341 1775.7142 Square 49.5
+-375.0000  675.0000   87.8388 0.10773600 -0.19392480 0.97508263 1785.4071 Square 49.5
+-375.0000  725.0000   98.1511 0.10742611 -0.20769047 0.97227789 1795.8606 Square 49.5
+-375.0000  775.0000  109.2001 0.10709703 -0.22133386 0.96929951 1807.0782 Square 49.5
+-375.0000  825.0000  120.9856 0.10674932 -0.23484851 0.96615255 1819.0634 Square 49.5
+-325.0000 -825.0000  115.8294 0.09264756 0.23518226 0.96752557  1813.8174 Square 49.5
+-325.0000 -775.0000  104.0439 0.09295019 0.22165046 0.97068601  1801.8411 Square 49.5
+-325.0000 -725.0000  100.9950 0.09363322 0.20887410 0.97344976  1790.6319 Square 49.5
+-325.0000 -675.0000   90.6827 0.09390876 0.19504127 0.97628892  1780.1862 Square 49.5
+-325.0000 -625.0000   73.1070 0.09375894 0.18030565 0.97913183  1770.5006 Square 49.5
+-325.0000 -575.0000   64.2678 0.09399392 0.16629693 0.98158569  1761.5720 Square 49.5
+-325.0000 -525.0000   64.1653 0.09462875 0.15286183 0.98370659  1753.3976 Square 49.5
+-325.0000 -475.0000   56.7994 0.09483174 0.13860024 0.98579760  1745.9748 Square 49.5
+-325.0000 -425.0000   42.1700 0.09458917 0.12369353 0.98780200  1739.3010 Square 49.5
+-325.0000 -375.0000   36.2773 0.09474983 0.10932672 0.98947973  1733.3742 Square 49.5
+-325.0000 -325.0000   39.1211 0.09532436 0.09532436 0.99087160  1728.1924 Square 49.5
+-325.0000 -275.0000   34.7015 0.09544873 0.08076431 0.99215254  1723.7540 Square 49.5
+-325.0000 -225.0000   23.0186 0.09511431 0.06584837 0.99328609  1720.0576 Square 49.5
+-325.0000 -175.0000   20.0722 0.09519588 0.05125932 0.99413793  1717.1019 Square 49.5
+-325.0000 -125.0000   25.8624 0.09569896 0.03680729 0.99472958  1714.8859 Square 49.5
+-325.0000  -75.0000   24.3892 0.09574086 0.02209404 0.99516106  1713.4090 Square 49.5
+-325.0000  -25.0000   15.6526 0.09531863 0.00733220 0.99541981  1712.6707 Square 49.5
+-325.0000   25.0000   15.6526 0.09531863 -0.00733220 0.99541981 1712.6707 Square 49.5
+-325.0000   75.0000   24.3892 0.09574086 -0.02209404 0.99516106 1713.4090 Square 49.5
+-325.0000  125.0000   25.8624 0.09569896 -0.03680729 0.99472958 1714.8859 Square 49.5
+-325.0000  175.0000   20.0722 0.09519588 -0.05125932 0.99413793 1717.1019 Square 49.5
+-325.0000  225.0000   23.0186 0.09511431 -0.06584837 0.99328609 1720.0576 Square 49.5
+-325.0000  275.0000   34.7015 0.09544873 -0.08076431 0.99215254 1723.7540 Square 49.5
+-325.0000  325.0000   39.1211 0.09532436 -0.09532436 0.99087160 1728.1924 Square 49.5
+-325.0000  375.0000   36.2773 0.09474983 -0.10932672 0.98947973 1733.3742 Square 49.5
+-325.0000  425.0000   42.1700 0.09458917 -0.12369353 0.98780200 1739.3010 Square 49.5
+-325.0000  475.0000   56.7994 0.09483174 -0.13860024 0.98579760 1745.9748 Square 49.5
+-325.0000  525.0000   64.1653 0.09462875 -0.15286183 0.98370659 1753.3976 Square 49.5
+-325.0000  575.0000   64.2678 0.09399392 -0.16629693 0.98158569 1761.5720 Square 49.5
+-325.0000  625.0000   73.1070 0.09375894 -0.18030565 0.97913183 1770.5006 Square 49.5
+-325.0000  675.0000   90.6827 0.09390876 -0.19504127 0.97628892 1780.1862 Square 49.5
+-325.0000  725.0000  100.9950 0.09363322 -0.20887410 0.97344976 1790.6319 Square 49.5
+-325.0000  775.0000  104.0439 0.09295019 -0.22165046 0.97068601 1801.8411 Square 49.5
+-325.0000  825.0000  115.8294 0.09264756 -0.23518226 0.96752557 1813.8174 Square 49.5
+-275.0000 -825.0000  111.4098 0.07848982 0.23546947 0.96870712  1809.3239 Square 49.5
+-275.0000 -775.0000   99.6243 0.07874684 0.22192291 0.97187919  1797.3553 Square 49.5
+-275.0000 -725.0000   96.5754 0.07932777 0.20913686 0.97466347  1786.1532 Square 49.5
+-275.0000 -675.0000   86.2631 0.07956182 0.19528810 0.97751341  1775.7142 Square 49.5
+-275.0000 -625.0000   68.6874 0.07943371 0.18053117 0.98035646  1766.0349 Square 49.5
+-275.0000 -575.0000   59.8483 0.07963329 0.16650597 0.98281957  1757.1121 Square 49.5
+-275.0000 -525.0000   59.7457 0.08017340 0.15305832 0.98495958  1748.9429 Square 49.5
+-275.0000 -475.0000   52.3798 0.08034584 0.13877917 0.98705871  1741.5249 Square 49.5
+-275.0000 -425.0000   37.7504 0.08013888 0.12385100 0.98905950  1734.8554 Square 49.5
+-275.0000 -375.0000   31.8577 0.08027534 0.10946637 0.99074365  1728.9324 Square 49.5
+-275.0000 -325.0000   34.7015 0.08076431 0.09544873 0.99215254  1723.7540 Square 49.5
+-275.0000 -275.0000   30.2820 0.08086997 0.08086997 0.99343852  1719.3185 Square 49.5
+-275.0000 -225.0000   18.5990 0.08058494 0.06593313 0.99456467  1715.6245 Square 49.5
+-275.0000 -175.0000   15.6526 0.08065423 0.05132542 0.99541981  1712.6707 Square 49.5
+-275.0000 -125.0000   21.4428 0.08108254 0.03685570 0.99602574  1710.4562 Square 49.5
+-275.0000  -75.0000   19.9697 0.08111814 0.02212313 0.99645894  1708.9802 Square 49.5
+-275.0000  -25.0000   11.2331 0.08075849 0.00734168 0.99670666  1708.2424 Square 49.5
+-275.0000   25.0000   11.2331 0.08075849 -0.00734168 0.99670666 1708.2424 Square 49.5
+-275.0000   75.0000   19.9697 0.08111814 -0.02212313 0.99645894 1708.9802 Square 49.5
+-275.0000  125.0000   21.4428 0.08108254 -0.03685570 0.99602574 1710.4562 Square 49.5
+-275.0000  175.0000   15.6526 0.08065423 -0.05132542 0.99541981 1712.6707 Square 49.5
+-275.0000  225.0000   18.5990 0.08058494 -0.06593313 0.99456467 1715.6245 Square 49.5
+-275.0000  275.0000   30.2820 0.08086997 -0.08086997 0.99343852 1719.3185 Square 49.5
+-275.0000  325.0000   34.7015 0.08076431 -0.09544873 0.99215254 1723.7540 Square 49.5
+-275.0000  375.0000   31.8577 0.08027534 -0.10946637 0.99074365 1728.9324 Square 49.5
+-275.0000  425.0000   37.7504 0.08013888 -0.12385100 0.98905950 1734.8554 Square 49.5
+-275.0000  475.0000   52.3798 0.08034584 -0.13877917 0.98705871 1741.5249 Square 49.5
+-275.0000  525.0000   59.7457 0.08017340 -0.15305832 0.98495958 1748.9429 Square 49.5
+-275.0000  575.0000   59.8483 0.07963329 -0.16650597 0.98281957 1757.1121 Square 49.5
+-275.0000  625.0000   68.6874 0.07943371 -0.18053117 0.98035646 1766.0349 Square 49.5
+-275.0000  675.0000   86.2631 0.07956182 -0.19528810 0.97751341 1775.7142 Square 49.5
+-275.0000  725.0000   96.5754 0.07932777 -0.20913686 0.97466347 1786.1532 Square 49.5
+-275.0000  775.0000   99.6243 0.07874684 -0.22192291 0.97187919 1797.3553 Square 49.5
+-275.0000  825.0000  111.4098 0.07848982 -0.23546947 0.96870712 1809.3239 Square 49.5
+-225.0000 -825.0000  115.7269 0.06455340 0.23669581 0.96943692  1805.5815 Square 49.5
+-225.0000 -775.0000  103.9414 0.06476880 0.22309255 0.97264316  1793.6193 Square 49.5
+-225.0000 -725.0000   84.8925 0.06469502 0.20846173 0.97588845  1782.4232 Square 49.5
+-225.0000 -675.0000   74.5801 0.06488304 0.19464912 0.97872463  1771.9898 Square 49.5
+-225.0000 -625.0000   73.0044 0.06534477 0.18151326 0.98121506  1762.3156 Square 49.5
+-225.0000 -575.0000   64.1653 0.06551221 0.16742010 0.98370659  1753.3976 Square 49.5
+-225.0000 -525.0000   48.0628 0.06537415 0.15253969 0.98613278  1745.2329 Square 49.5
+-225.0000 -475.0000   40.6968 0.06551256 0.13830430 0.98822064  1737.8188 Square 49.5
+-225.0000 -425.0000   42.0675 0.06593657 0.12454686 0.99002043  1731.1530 Square 49.5
+-225.0000 -375.0000   36.1747 0.06605115 0.11008525 0.99172500  1725.2332 Square 49.5
+-225.0000 -325.0000   23.0186 0.06584837 0.09511431 0.99328609  1720.0576 Square 49.5
+-225.0000 -275.0000   18.5990 0.06593313 0.08058494 0.99456467  1715.6245 Square 49.5
+-225.0000 -225.0000   22.9160 0.06631118 0.06631118 0.99559312  1711.9324 Square 49.5
+-225.0000 -175.0000   19.9697 0.06636939 0.05162063 0.99645894  1708.9802 Square 49.5
+-225.0000 -125.0000    9.7599 0.06610364 0.03672425 0.99713672  1706.7669 Square 49.5
+-225.0000  -75.0000    8.2867 0.06613219 0.02204406 0.99756734  1705.2917 Square 49.5
+-225.0000  -25.0000   15.5501 0.06645699 0.00738411 0.99776197  1704.5543 Square 49.5
+-225.0000   25.0000   15.5501 0.06645699 -0.00738411 0.99776197 1704.5543 Square 49.5
+-225.0000   75.0000    8.2867 0.06613219 -0.02204406 0.99756734 1705.2917 Square 49.5
+-225.0000  125.0000    9.7599 0.06610364 -0.03672425 0.99713672 1706.7669 Square 49.5
+-225.0000  175.0000   19.9697 0.06636939 -0.05162063 0.99645894 1708.9802 Square 49.5
+-225.0000  225.0000   22.9160 0.06631118 -0.06631118 0.99559312 1711.9324 Square 49.5
+-225.0000  275.0000   18.5990 0.06593313 -0.08058494 0.99456467 1715.6245 Square 49.5
+-225.0000  325.0000   23.0186 0.06584837 -0.09511431 0.99328609 1720.0576 Square 49.5
+-225.0000  375.0000   36.1747 0.06605115 -0.11008525 0.99172500 1725.2332 Square 49.5
+-225.0000  425.0000   42.0675 0.06593657 -0.12454686 0.99002043 1731.1530 Square 49.5
+-225.0000  475.0000   40.6968 0.06551256 -0.13830430 0.98822064 1737.8188 Square 49.5
+-225.0000  525.0000   48.0628 0.06537415 -0.15253969 0.98613278 1745.2329 Square 49.5
+-225.0000  575.0000   64.1653 0.06551221 -0.16742010 0.98370659 1753.3976 Square 49.5
+-225.0000  625.0000   73.0044 0.06534477 -0.18151326 0.98121506 1762.3156 Square 49.5
+-225.0000  675.0000   74.5801 0.06488304 -0.19464912 0.97872463 1771.9898 Square 49.5
+-225.0000  725.0000   84.8925 0.06469502 -0.20846173 0.97588845 1782.4232 Square 49.5
+-225.0000  775.0000  103.9414 0.06476880 -0.22309255 0.97264316 1793.6193 Square 49.5
+-225.0000  825.0000  115.7269 0.06455340 -0.23669581 0.96943692 1805.5815 Square 49.5
+-175.0000 -825.0000  112.7805 0.05024993 0.23689252 0.97023548  1802.5890 Square 49.5
+-175.0000 -775.0000  100.9950 0.05041789 0.22327921 0.97344976  1790.6319 Square 49.5
+-175.0000 -725.0000   81.9461 0.05036000 0.20863429 0.97669627  1779.4406 Square 49.5
+-175.0000 -675.0000   71.6338 0.05050660 0.19481119 0.97953953  1769.0117 Square 49.5
+-175.0000 -625.0000   70.0580 0.05086701 0.18166790 0.98204344  1759.3417 Square 49.5
+-175.0000 -575.0000   61.2189 0.05099758 0.16756347 0.98454138  1750.4275 Square 49.5
+-175.0000 -525.0000   45.1164 0.05088954 0.15266863 0.98696633  1742.2663 Square 49.5
+-175.0000 -475.0000   37.7504 0.05099747 0.13842170 0.98905950  1734.8554 Square 49.5
+-175.0000 -425.0000   39.1211 0.05132850 0.12465493 0.99087160  1728.1924 Square 49.5
+-175.0000 -375.0000   33.2283 0.05141785 0.11018111 0.99258064  1722.2752 Square 49.5
+-175.0000 -325.0000   20.0722 0.05125932 0.09519588 0.99413793  1717.1019 Square 49.5
+-175.0000 -275.0000   15.6526 0.05132542 0.08065423 0.99541981  1712.6707 Square 49.5
+-175.0000 -225.0000   19.9697 0.05162063 0.06636939 0.99645894  1708.9802 Square 49.5
+-175.0000 -175.0000   17.0233 0.05166603 0.05166603 0.99732705  1706.0293 Square 49.5
+-175.0000 -125.0000    6.8135 0.05145838 0.03675599 0.99799851  1703.8169 Square 49.5
+-175.0000  -75.0000    5.3403 0.05148064 0.02206313 0.99843025  1702.3424 Square 49.5
+-175.0000  -25.0000   12.6037 0.05173435 0.00739062 0.99863353  1701.6053 Square 49.5
+-175.0000   25.0000   12.6037 0.05173435 -0.00739062 0.99863353 1701.6053 Square 49.5
+-175.0000   75.0000    5.3403 0.05148064 -0.02206313 0.99843025 1702.3424 Square 49.5
+-175.0000  125.0000    6.8135 0.05145838 -0.03675599 0.99799851 1703.8169 Square 49.5
+-175.0000  175.0000   17.0233 0.05166603 -0.05166603 0.99732705 1706.0293 Square 49.5
+-175.0000  225.0000   19.9697 0.05162063 -0.06636939 0.99645894 1708.9802 Square 49.5
+-175.0000  275.0000   15.6526 0.05132542 -0.08065423 0.99541981 1712.6707 Square 49.5
+-175.0000  325.0000   20.0722 0.05125932 -0.09519588 0.99413793 1717.1019 Square 49.5
+-175.0000  375.0000   33.2283 0.05141785 -0.11018111 0.99258064 1722.2752 Square 49.5
+-175.0000  425.0000   39.1211 0.05132850 -0.12465493 0.99087160 1728.1924 Square 49.5
+-175.0000  475.0000   37.7504 0.05099747 -0.13842170 0.98905950 1734.8554 Square 49.5
+-175.0000  525.0000   45.1164 0.05088954 -0.15266863 0.98696633 1742.2663 Square 49.5
+-175.0000  575.0000   61.2189 0.05099758 -0.16756347 0.98454138 1750.4275 Square 49.5
+-175.0000  625.0000   70.0580 0.05086701 -0.18166790 0.98204344 1759.3417 Square 49.5
+-175.0000  675.0000   71.6338 0.05050660 -0.19481119 0.97953953 1769.0117 Square 49.5
+-175.0000  725.0000   81.9461 0.05036000 -0.20863429 0.97669627 1779.4406 Square 49.5
+-175.0000  775.0000  100.9950 0.05041789 -0.22327921 0.97344976 1790.6319 Square 49.5
+-175.0000  825.0000  112.7805 0.05024993 -0.23689252 0.97023548 1802.5890 Square 49.5
+-125.0000 -825.0000  102.5707 0.03576470 0.23604705 0.97108325  1800.3455 Square 49.5
+-125.0000 -775.0000   90.7852 0.03588240 0.22247085 0.97427880  1788.3922 Square 49.5
+-125.0000 -725.0000   87.7363 0.03614921 0.20966540 0.97710473  1777.2046 Square 49.5
+-125.0000 -675.0000   77.4240 0.03625641 0.19578462 0.97997646  1766.7790 Square 49.5
+-125.0000 -625.0000   59.8483 0.03619695 0.18098475 0.98281957  1757.1121 Square 49.5
+-125.0000 -575.0000   51.0091 0.03628835 0.16692642 0.98530134  1748.2008 Square 49.5
+-125.0000 -525.0000   50.9066 0.03653657 0.15345360 0.98748016  1740.0422 Square 49.5
+-125.0000 -475.0000   43.5407 0.03661557 0.13913916 0.98959567  1732.6337 Square 49.5
+-125.0000 -425.0000   28.9113 0.03651992 0.12416774 0.99158896  1725.9729 Square 49.5
+-125.0000 -375.0000   23.0186 0.03658243 0.10974728 0.99328609  1720.0576 Square 49.5
+-125.0000 -325.0000   25.8624 0.03680729 0.09569896 0.99472958  1714.8859 Square 49.5
+-125.0000 -275.0000   21.4428 0.03685570 0.08108254 0.99602574  1710.4562 Square 49.5
+-125.0000 -225.0000    9.7599 0.03672425 0.06610364 0.99713672  1706.7669 Square 49.5
+-125.0000 -175.0000    6.8135 0.03675599 0.05145838 0.99799851  1703.8169 Square 49.5
+-125.0000 -125.0000   12.6037 0.03695310 0.03695310 0.99863353  1701.6053 Square 49.5
+-125.0000  -75.0000   11.1305 0.03696941 0.02218165 0.99907019  1700.1312 Square 49.5
+-125.0000   75.0000   11.1305 0.03696941 -0.02218165 0.99907019 1700.1312 Square 49.5
+-125.0000  125.0000   12.6037 0.03695310 -0.03695310 0.99863353 1701.6053 Square 49.5
+-125.0000  175.0000    6.8135 0.03675599 -0.05145838 0.99799851 1703.8169 Square 49.5
+-125.0000  225.0000    9.7599 0.03672425 -0.06610364 0.99713672 1706.7669 Square 49.5
+-125.0000  275.0000   21.4428 0.03685570 -0.08108254 0.99602574 1710.4562 Square 49.5
+-125.0000  325.0000   25.8624 0.03680729 -0.09569896 0.99472958 1714.8859 Square 49.5
+-125.0000  375.0000   23.0186 0.03658243 -0.10974728 0.99328609 1720.0576 Square 49.5
+-125.0000  425.0000   28.9113 0.03651992 -0.12416774 0.99158896 1725.9729 Square 49.5
+-125.0000  475.0000   43.5407 0.03661557 -0.13913916 0.98959567 1732.6337 Square 49.5
+-125.0000  525.0000   50.9066 0.03653657 -0.15345360 0.98748016 1740.0422 Square 49.5
+-125.0000  575.0000   51.0091 0.03628835 -0.16692642 0.98530134 1748.2008 Square 49.5
+-125.0000  625.0000   59.8483 0.03619695 -0.18098475 0.98281957 1757.1121 Square 49.5
+-125.0000  675.0000   77.4240 0.03625641 -0.19578462 0.97997646 1766.7790 Square 49.5
+-125.0000  725.0000   87.7363 0.03614921 -0.20966540 0.97710473 1777.2046 Square 49.5
+-125.0000  775.0000   90.7852 0.03588240 -0.22247085 0.97427880 1788.3922 Square 49.5
+-125.0000  825.0000  102.5707 0.03576470 -0.23604705 0.97108325 1800.3455 Square 49.5
+ -75.0000 -825.0000  101.0975 0.02146761 0.23614373 0.97148097  1798.8502 Square 49.5
+ -75.0000 -775.0000   89.3120 0.02153831 0.22256257 0.97468046  1786.8995 Square 49.5
+ -75.0000 -725.0000   86.2631 0.02169868 0.20975389 0.97751341  1775.7142 Square 49.5
+ -75.0000 -675.0000   75.9508 0.02176308 0.19586775 0.98038880  1765.2909 Square 49.5
+ -75.0000 -625.0000   58.3751 0.02172728 0.18106068 0.98323189  1755.6261 Square 49.5
+ -75.0000 -575.0000   49.5359 0.02178219 0.16699681 0.98571680  1746.7167 Square 49.5
+ -75.0000 -525.0000   49.4334 0.02193140 0.15351978 0.98790217  1738.5599 Square 49.5
+ -75.0000 -475.0000   42.0675 0.02197886 0.13919943 0.99002043  1731.1530 Square 49.5
+ -75.0000 -425.0000   27.4381 0.02192131 0.12422077 0.99201243  1724.4936 Square 49.5
+ -75.0000 -375.0000   21.5454 0.02195886 0.10979431 0.99371174  1718.5796 Square 49.5
+ -75.0000 -325.0000   24.3892 0.02209404 0.09574086 0.99516106  1713.4090 Square 49.5
+ -75.0000 -275.0000   19.9697 0.02212313 0.08111814 0.99645894  1708.9802 Square 49.5
+ -75.0000 -225.0000    8.2867 0.02204406 0.06613219 0.99756734  1705.2917 Square 49.5
+ -75.0000 -175.0000    5.3403 0.02206313 0.05148064 0.99843025  1702.3424 Square 49.5
+ -75.0000 -125.0000   11.1305 0.02218165 0.03696941 0.99907019  1700.1312 Square 49.5
+ -75.0000  -75.0000    9.6573 0.02219145 0.02219145 0.99950742  1698.6575 Square 49.5
+ -75.0000   75.0000    9.6573 0.02219145 -0.02219145 0.99950742 1698.6575 Square 49.5
+ -75.0000  125.0000   11.1305 0.02218165 -0.03696941 0.99907019 1700.1312 Square 49.5
+ -75.0000  175.0000    5.3403 0.02206313 -0.05148064 0.99843025 1702.3424 Square 49.5
+ -75.0000  225.0000    8.2867 0.02204406 -0.06613219 0.99756734 1705.2917 Square 49.5
+ -75.0000  275.0000   19.9697 0.02212313 -0.08111814 0.99645894 1708.9802 Square 49.5
+ -75.0000  325.0000   24.3892 0.02209404 -0.09574086 0.99516106 1713.4090 Square 49.5
+ -75.0000  375.0000   21.5454 0.02195886 -0.10979431 0.99371174 1718.5796 Square 49.5
+ -75.0000  425.0000   27.4381 0.02192131 -0.12422077 0.99201243 1724.4936 Square 49.5
+ -75.0000  475.0000   42.0675 0.02197886 -0.13919943 0.99002043 1731.1530 Square 49.5
+ -75.0000  525.0000   49.4334 0.02193140 -0.15351978 0.98790217 1738.5599 Square 49.5
+ -75.0000  575.0000   49.5359 0.02178219 -0.16699681 0.98571680 1746.7167 Square 49.5
+ -75.0000  625.0000   58.3751 0.02172728 -0.18106068 0.98323189 1755.6261 Square 49.5
+ -75.0000  675.0000   75.9508 0.02176308 -0.19586775 0.98038880 1765.2909 Square 49.5
+ -75.0000  725.0000   86.2631 0.02169868 -0.20975389 0.97751341 1775.7142 Square 49.5
+ -75.0000  775.0000   89.3120 0.02153831 -0.22256257 0.97468046 1786.8995 Square 49.5
+ -75.0000  825.0000  101.0975 0.02146761 -0.23614373 0.97148097 1798.8502 Square 49.5
+ -25.0000 -825.0000  108.3609 0.00718753 0.23718851 0.97143706  1798.1027 Square 49.5
+ -25.0000 -775.0000   96.5754 0.00721162 0.22356009 0.97466347  1786.1532 Square 49.5
+ -25.0000 -725.0000   77.5265 0.00720324 0.20889394 0.97791177  1774.9692 Square 49.5
+ -25.0000 -675.0000   67.2142 0.00722426 0.19505505 0.98076569  1764.5469 Square 49.5
+ -25.0000 -625.0000   65.6385 0.00727602 0.18190060 0.98329000  1754.8832 Square 49.5
+ -25.0000 -575.0000   56.7994 0.00729475 0.16777923 0.98579760  1745.9748 Square 49.5
+ -25.0000 -525.0000   40.6968 0.00727917 0.15286265 0.98822064  1737.8188 Square 49.5
+ -25.0000 -475.0000   33.3309 0.00729465 0.13859837 0.99032181  1730.4127 Square 49.5
+ -25.0000 -425.0000   34.7015 0.00734221 0.12481757 0.99215254  1723.7540 Square 49.5
+ -25.0000 -375.0000   28.8088 0.00735503 0.11032538 0.99386831  1717.8407 Square 49.5
+ -25.0000 -325.0000   15.6526 0.00733220 0.09531863 0.99541981  1712.6707 Square 49.5
+ -25.0000 -275.0000   11.2331 0.00734168 0.08075849 0.99670666  1708.2424 Square 49.5
+ -25.0000 -225.0000   15.5501 0.00738411 0.06645699 0.99776197  1704.5543 Square 49.5
+ -25.0000 -175.0000   12.6037 0.00739062 0.05173435 0.99863353  1701.6053 Square 49.5
+ -25.0000 -125.0000    2.3939 0.00736075 0.03680375 0.99929540  1699.3944 Square 49.5
+ -25.0000  -75.0000    0.9207 0.00736394 0.02209183 0.99972882  1697.9208 Square 49.5
+ -25.0000   75.0000    0.9207 0.00736394 -0.02209183 0.99972882 1697.9208 Square 49.5
+ -25.0000  125.0000    2.3939 0.00736075 -0.03680375 0.99929540 1699.3944 Square 49.5
+ -25.0000  175.0000   12.6037 0.00739062 -0.05173435 0.99863353 1701.6053 Square 49.5
+ -25.0000  225.0000   15.5501 0.00738411 -0.06645699 0.99776197 1704.5543 Square 49.5
+ -25.0000  275.0000   11.2331 0.00734168 -0.08075849 0.99670666 1708.2424 Square 49.5
+ -25.0000  325.0000   15.6526 0.00733220 -0.09531863 0.99541981 1712.6707 Square 49.5
+ -25.0000  375.0000   28.8088 0.00735503 -0.11032538 0.99386831 1717.8407 Square 49.5
+ -25.0000  425.0000   34.7015 0.00734221 -0.12481757 0.99215254 1723.7540 Square 49.5
+ -25.0000  475.0000   33.3309 0.00729465 -0.13859837 0.99032181 1730.4127 Square 49.5
+ -25.0000  525.0000   40.6968 0.00727917 -0.15286265 0.98822064 1737.8188 Square 49.5
+ -25.0000  575.0000   56.7994 0.00729475 -0.16777923 0.98579760 1745.9748 Square 49.5
+ -25.0000  625.0000   65.6385 0.00727602 -0.18190060 0.98329000 1754.8832 Square 49.5
+ -25.0000  675.0000   67.2142 0.00722426 -0.19505505 0.98076569 1764.5469 Square 49.5
+ -25.0000  725.0000   77.5265 0.00720324 -0.20889394 0.97791177 1774.9692 Square 49.5
+ -25.0000  775.0000   96.5754 0.00721162 -0.22356009 0.97466347 1786.1532 Square 49.5
+ -25.0000  825.0000  108.3609 0.00718753 -0.23718851 0.97143706 1798.1027 Square 49.5
+  25.0000 -825.0000  108.3609 -0.00718753 0.23718851 0.97143706 1798.1027 Square 49.5
+  25.0000 -775.0000   96.5754 -0.00721162 0.22356009 0.97466347 1786.1532 Square 49.5
+  25.0000 -725.0000   77.5265 -0.00720324 0.20889394 0.97791177 1774.9692 Square 49.5
+  25.0000 -675.0000   67.2142 -0.00722426 0.19505505 0.98076569 1764.5469 Square 49.5
+  25.0000 -625.0000   65.6385 -0.00727602 0.18190060 0.98329000 1754.8832 Square 49.5
+  25.0000 -575.0000   56.7994 -0.00729475 0.16777923 0.98579760 1745.9748 Square 49.5
+  25.0000 -525.0000   40.6968 -0.00727917 0.15286265 0.98822064 1737.8188 Square 49.5
+  25.0000 -475.0000   33.3309 -0.00729465 0.13859837 0.99032181 1730.4127 Square 49.5
+  25.0000 -425.0000   34.7015 -0.00734221 0.12481757 0.99215254 1723.7540 Square 49.5
+  25.0000 -375.0000   28.8088 -0.00735503 0.11032538 0.99386831 1717.8407 Square 49.5
+  25.0000 -325.0000   15.6526 -0.00733220 0.09531863 0.99541981 1712.6707 Square 49.5
+  25.0000 -275.0000   11.2331 -0.00734168 0.08075849 0.99670666 1708.2424 Square 49.5
+  25.0000 -225.0000   15.5501 -0.00738411 0.06645699 0.99776197 1704.5543 Square 49.5
+  25.0000 -175.0000   12.6037 -0.00739062 0.05173435 0.99863353 1701.6053 Square 49.5
+  25.0000 -125.0000    2.3939 -0.00736075 0.03680375 0.99929540 1699.3944 Square 49.5
+  25.0000  -75.0000    0.9207 -0.00736394 0.02209183 0.99972882 1697.9208 Square 49.5
+  25.0000   75.0000    0.9207 -0.00736394 -0.02209183 0.99972882 1697.9208 Square 49.5
+  25.0000  125.0000    2.3939 -0.00736075 -0.03680375 0.99929540 1699.3944 Square 49.5
+  25.0000  175.0000   12.6037 -0.00739062 -0.05173435 0.99863353 1701.6053 Square 49.5
+  25.0000  225.0000   15.5501 -0.00738411 -0.06645699 0.99776197 1704.5543 Square 49.5
+  25.0000  275.0000   11.2331 -0.00734168 -0.08075849 0.99670666 1708.2424 Square 49.5
+  25.0000  325.0000   15.6526 -0.00733220 -0.09531863 0.99541981 1712.6707 Square 49.5
+  25.0000  375.0000   28.8088 -0.00735503 -0.11032538 0.99386831 1717.8407 Square 49.5
+  25.0000  425.0000   34.7015 -0.00734221 -0.12481757 0.99215254 1723.7540 Square 49.5
+  25.0000  475.0000   33.3309 -0.00729465 -0.13859837 0.99032181 1730.4127 Square 49.5
+  25.0000  525.0000   40.6968 -0.00727917 -0.15286265 0.98822064 1737.8188 Square 49.5
+  25.0000  575.0000   56.7994 -0.00729475 -0.16777923 0.98579760 1745.9748 Square 49.5
+  25.0000  625.0000   65.6385 -0.00727602 -0.18190060 0.98329000 1754.8832 Square 49.5
+  25.0000  675.0000   67.2142 -0.00722426 -0.19505505 0.98076569 1764.5469 Square 49.5
+  25.0000  725.0000   77.5265 -0.00720324 -0.20889394 0.97791177 1774.9692 Square 49.5
+  25.0000  775.0000   96.5754 -0.00721162 -0.22356009 0.97466347 1786.1532 Square 49.5
+  25.0000  825.0000  108.3609 -0.00718753 -0.23718851 0.97143706 1798.1027 Square 49.5
+  75.0000 -825.0000  101.0975 -0.02146761 0.23614373 0.97148097 1798.8502 Square 49.5
+  75.0000 -775.0000   89.3120 -0.02153831 0.22256257 0.97468046 1786.8995 Square 49.5
+  75.0000 -725.0000   86.2631 -0.02169868 0.20975389 0.97751341 1775.7142 Square 49.5
+  75.0000 -675.0000   75.9508 -0.02176308 0.19586775 0.98038880 1765.2909 Square 49.5
+  75.0000 -625.0000   58.3751 -0.02172728 0.18106068 0.98323189 1755.6261 Square 49.5
+  75.0000 -575.0000   49.5359 -0.02178219 0.16699681 0.98571680 1746.7167 Square 49.5
+  75.0000 -525.0000   49.4334 -0.02193140 0.15351978 0.98790217 1738.5599 Square 49.5
+  75.0000 -475.0000   42.0675 -0.02197886 0.13919943 0.99002043 1731.1530 Square 49.5
+  75.0000 -425.0000   27.4381 -0.02192131 0.12422077 0.99201243 1724.4936 Square 49.5
+  75.0000 -375.0000   21.5454 -0.02195886 0.10979431 0.99371174 1718.5796 Square 49.5
+  75.0000 -325.0000   24.3892 -0.02209404 0.09574086 0.99516106 1713.4090 Square 49.5
+  75.0000 -275.0000   19.9697 -0.02212313 0.08111814 0.99645894 1708.9802 Square 49.5
+  75.0000 -225.0000    8.2867 -0.02204406 0.06613219 0.99756734 1705.2917 Square 49.5
+  75.0000 -175.0000    5.3403 -0.02206313 0.05148064 0.99843025 1702.3424 Square 49.5
+  75.0000 -125.0000   11.1305 -0.02218165 0.03696941 0.99907019 1700.1312 Square 49.5
+  75.0000  -75.0000    9.6573 -0.02219145 0.02219145 0.99950742 1698.6575 Square 49.5
+  75.0000  -25.0000    0.9207 -0.02209183 0.00736394 0.99972882 1697.9208 Square 49.5
+  75.0000   25.0000    0.9207 -0.02209183 -0.00736394 0.99972882 1697.9208 Square 49.5
+  75.0000   75.0000    9.6573 -0.02219145 -0.02219145 0.99950742 1698.6575 Square 49.5
+  75.0000  125.0000   11.1305 -0.02218165 -0.03696941 0.99907019 1700.1312 Square 49.5
+  75.0000  175.0000    5.3403 -0.02206313 -0.05148064 0.99843025 1702.3424 Square 49.5
+  75.0000  225.0000    8.2867 -0.02204406 -0.06613219 0.99756734 1705.2917 Square 49.5
+  75.0000  275.0000   19.9697 -0.02212313 -0.08111814 0.99645894 1708.9802 Square 49.5
+  75.0000  325.0000   24.3892 -0.02209404 -0.09574086 0.99516106 1713.4090 Square 49.5
+  75.0000  375.0000   21.5454 -0.02195886 -0.10979431 0.99371174 1718.5796 Square 49.5
+  75.0000  425.0000   27.4381 -0.02192131 -0.12422077 0.99201243 1724.4936 Square 49.5
+  75.0000  475.0000   42.0675 -0.02197886 -0.13919943 0.99002043 1731.1530 Square 49.5
+  75.0000  525.0000   49.4334 -0.02193140 -0.15351978 0.98790217 1738.5599 Square 49.5
+  75.0000  575.0000   49.5359 -0.02178219 -0.16699681 0.98571680 1746.7167 Square 49.5
+  75.0000  625.0000   58.3751 -0.02172728 -0.18106068 0.98323189 1755.6261 Square 49.5
+  75.0000  675.0000   75.9508 -0.02176308 -0.19586775 0.98038880 1765.2909 Square 49.5
+  75.0000  725.0000   86.2631 -0.02169868 -0.20975389 0.97751341 1775.7142 Square 49.5
+  75.0000  775.0000   89.3120 -0.02153831 -0.22256257 0.97468046 1786.8995 Square 49.5
+  75.0000  825.0000  101.0975 -0.02146761 -0.23614373 0.97148097 1798.8502 Square 49.5
+ 125.0000 -825.0000  102.5707 -0.03576470 0.23604705 0.97108325 1800.3455 Square 49.5
+ 125.0000 -775.0000   90.7852 -0.03588240 0.22247085 0.97427880 1788.3922 Square 49.5
+ 125.0000 -725.0000   87.7363 -0.03614921 0.20966540 0.97710473 1777.2046 Square 49.5
+ 125.0000 -675.0000   77.4240 -0.03625641 0.19578462 0.97997646 1766.7790 Square 49.5
+ 125.0000 -625.0000   59.8483 -0.03619695 0.18098475 0.98281957 1757.1121 Square 49.5
+ 125.0000 -575.0000   51.0091 -0.03628835 0.16692642 0.98530134 1748.2008 Square 49.5
+ 125.0000 -525.0000   50.9066 -0.03653657 0.15345360 0.98748016 1740.0422 Square 49.5
+ 125.0000 -475.0000   43.5407 -0.03661557 0.13913916 0.98959567 1732.6337 Square 49.5
+ 125.0000 -425.0000   28.9113 -0.03651992 0.12416774 0.99158896 1725.9729 Square 49.5
+ 125.0000 -375.0000   23.0186 -0.03658243 0.10974728 0.99328609 1720.0576 Square 49.5
+ 125.0000 -325.0000   25.8624 -0.03680729 0.09569896 0.99472958 1714.8859 Square 49.5
+ 125.0000 -275.0000   21.4428 -0.03685570 0.08108254 0.99602574 1710.4562 Square 49.5
+ 125.0000 -225.0000    9.7599 -0.03672425 0.06610364 0.99713672 1706.7669 Square 49.5
+ 125.0000 -175.0000    6.8135 -0.03675599 0.05145838 0.99799851 1703.8169 Square 49.5
+ 125.0000 -125.0000   12.6037 -0.03695310 0.03695310 0.99863353 1701.6053 Square 49.5
+ 125.0000  -75.0000   11.1305 -0.03696941 0.02218165 0.99907019 1700.1312 Square 49.5
+ 125.0000  -25.0000    2.3939 -0.03680375 0.00736075 0.99929540 1699.3944 Square 49.5
+ 125.0000   25.0000    2.3939 -0.03680375 -0.00736075 0.99929540 1699.3944 Square 49.5
+ 125.0000   75.0000   11.1305 -0.03696941 -0.02218165 0.99907019 1700.1312 Square 49.5
+ 125.0000  125.0000   12.6037 -0.03695310 -0.03695310 0.99863353 1701.6053 Square 49.5
+ 125.0000  175.0000    6.8135 -0.03675599 -0.05145838 0.99799851 1703.8169 Square 49.5
+ 125.0000  225.0000    9.7599 -0.03672425 -0.06610364 0.99713672 1706.7669 Square 49.5
+ 125.0000  275.0000   21.4428 -0.03685570 -0.08108254 0.99602574 1710.4562 Square 49.5
+ 125.0000  325.0000   25.8624 -0.03680729 -0.09569896 0.99472958 1714.8859 Square 49.5
+ 125.0000  375.0000   23.0186 -0.03658243 -0.10974728 0.99328609 1720.0576 Square 49.5
+ 125.0000  425.0000   28.9113 -0.03651992 -0.12416774 0.99158896 1725.9729 Square 49.5
+ 125.0000  475.0000   43.5407 -0.03661557 -0.13913916 0.98959567 1732.6337  Square 49.5
+ 125.0000  525.0000   50.9066 -0.03653657 -0.15345360 0.98748016 1740.0422  Square 49.5
+ 125.0000  575.0000   51.0091 -0.03628835 -0.16692642 0.98530134 1748.2008  Square 49.5
+ 125.0000  625.0000   59.8483 -0.03619695 -0.18098475 0.98281957 1757.1121  Square 49.5
+ 125.0000  675.0000   77.4240 -0.03625641 -0.19578462 0.97997646 1766.7790  Square 49.5
+ 125.0000  725.0000   87.7363 -0.03614921 -0.20966540 0.97710473 1777.2046  Square 49.5
+ 125.0000  775.0000   90.7852 -0.03588240 -0.22247085 0.97427880 1788.3922  Square 49.5
+ 125.0000  825.0000  102.5707 -0.03576470 -0.23604705 0.97108325 1800.3455  Square 49.5
+ 175.0000 -825.0000  112.7805 -0.05024993 0.23689252 0.97023548 1802.5890   Square 49.5
+ 175.0000 -775.0000  100.9950 -0.05041789 0.22327921 0.97344976 1790.6319   Square 49.5
+ 175.0000 -725.0000   81.9461 -0.05036000 0.20863429 0.97669627 1779.4406   Square 49.5
+ 175.0000 -675.0000   71.6338 -0.05050660 0.19481119 0.97953953 1769.0117   Square 49.5
+ 175.0000 -625.0000   70.0580 -0.05086701 0.18166790 0.98204344 1759.3417   Square 49.5
+ 175.0000 -575.0000   61.2189 -0.05099758 0.16756347 0.98454138 1750.4275   Square 49.5
+ 175.0000 -525.0000   45.1164 -0.05088954 0.15266863 0.98696633 1742.2663   Square 49.5
+ 175.0000 -475.0000   37.7504 -0.05099747 0.13842170 0.98905950 1734.8554   Square 49.5
+ 175.0000 -425.0000   39.1211 -0.05132850 0.12465493 0.99087160 1728.1924   Square 49.5
+ 175.0000 -375.0000   33.2283 -0.05141785 0.11018111 0.99258064 1722.2752   Square 49.5
+ 175.0000 -325.0000   20.0722 -0.05125932 0.09519588 0.99413793 1717.1019   Square 49.5
+ 175.0000 -275.0000   15.6526 -0.05132542 0.08065423 0.99541981 1712.6707   Square 49.5
+ 175.0000 -225.0000   19.9697 -0.05162063 0.06636939 0.99645894 1708.9802   Square 49.5
+ 175.0000 -175.0000   17.0233 -0.05166603 0.05166603 0.99732705 1706.0293   Square 49.5
+ 175.0000 -125.0000    6.8135 -0.05145838 0.03675599 0.99799851 1703.8169   Square 49.5
+ 175.0000  -75.0000    5.3403 -0.05148064 0.02206313 0.99843025 1702.3424   Square 49.5
+ 175.0000  -25.0000   12.6037 -0.05173435 0.00739062 0.99863353 1701.6053   Square 49.5
+ 175.0000   25.0000   12.6037 -0.05173435 -0.00739062 0.99863353 1701.6053   Square 49.5
+ 175.0000   75.0000    5.3403 -0.05148064 -0.02206313 0.99843025 1702.3424   Square 49.5
+ 175.0000  125.0000    6.8135 -0.05145838 -0.03675599 0.99799851 1703.8169   Square 49.5
+ 175.0000  175.0000   17.0233 -0.05166603 -0.05166603 0.99732705 1706.0293   Square 49.5
+ 175.0000  225.0000   19.9697 -0.05162063 -0.06636939 0.99645894 1708.9802   Square 49.5
+ 175.0000  275.0000   15.6526 -0.05132542 -0.08065423 0.99541981 1712.6707   Square 49.5
+ 175.0000  325.0000   20.0722 -0.05125932 -0.09519588 0.99413793 1717.1019   Square 49.5
+ 175.0000  375.0000   33.2283 -0.05141785 -0.11018111 0.99258064 1722.2752   Square 49.5
+ 175.0000  425.0000   39.1211 -0.05132850 -0.12465493 0.99087160 1728.1924   Square 49.5
+ 175.0000  475.0000   37.7504 -0.05099747 -0.13842170 0.98905950 1734.8554   Square 49.5
+ 175.0000  525.0000   45.1164 -0.05088954 -0.15266863 0.98696633 1742.2663   Square 49.5
+ 175.0000  575.0000   61.2189 -0.05099758 -0.16756347 0.98454138 1750.4275   Square 49.5
+ 175.0000  625.0000   70.0580 -0.05086701 -0.18166790 0.98204344 1759.3417   Square 49.5
+ 175.0000  675.0000   71.6338 -0.05050660 -0.19481119 0.97953953 1769.0117   Square 49.5
+ 175.0000  725.0000   81.9461 -0.05036000 -0.20863429 0.97669627 1779.4406   Square 49.5
+ 175.0000  775.0000  100.9950 -0.05041789 -0.22327921 0.97344976 1790.6319   Square 49.5
+ 175.0000  825.0000  112.7805 -0.05024993 -0.23689252 0.97023548 1802.5890   Square 49.5
+ 225.0000 -825.0000  115.7269 -0.06455340 0.23669581 0.96943692 1805.5815   Square 49.5
+ 225.0000 -775.0000  103.9414 -0.06476880 0.22309255 0.97264316 1793.6193   Square 49.5
+ 225.0000 -725.0000   84.8925 -0.06469502 0.20846173 0.97588845 1782.4232   Square 49.5
+ 225.0000 -675.0000   74.5801 -0.06488304 0.19464912 0.97872463 1771.9898   Square 49.5
+ 225.0000 -625.0000   73.0044 -0.06534477 0.18151326 0.98121506 1762.3156   Square 49.5
+ 225.0000 -575.0000   64.1653 -0.06551221 0.16742010 0.98370659 1753.3976   Square 49.5
+ 225.0000 -525.0000   48.0628 -0.06537415 0.15253969 0.98613278 1745.2329   Square 49.5
+ 225.0000 -475.0000   40.6968 -0.06551256 0.13830430 0.98822064 1737.8188   Square 49.5
+ 225.0000 -425.0000   42.0675 -0.06593657 0.12454686 0.99002043 1731.1530   Square 49.5
+ 225.0000 -375.0000   36.1747 -0.06605115 0.11008525 0.99172500 1725.2332   Square 49.5
+ 225.0000 -325.0000   23.0186 -0.06584837 0.09511431 0.99328609 1720.0576   Square 49.5
+ 225.0000 -275.0000   18.5990 -0.06593313 0.08058494 0.99456467 1715.6245   Square 49.5
+ 225.0000 -225.0000   22.9160 -0.06631118 0.06631118 0.99559312 1711.9324   Square 49.5
+ 225.0000 -175.0000   19.9697 -0.06636939 0.05162063 0.99645894 1708.9802   Square 49.5
+ 225.0000 -125.0000    9.7599 -0.06610364 0.03672425 0.99713672 1706.7669   Square 49.5
+ 225.0000  -75.0000    8.2867 -0.06613219 0.02204406 0.99756734 1705.2917   Square 49.5
+ 225.0000  -25.0000   15.5501 -0.06645699 0.00738411 0.99776197 1704.5543   Square 49.5
+ 225.0000   25.0000   15.5501 -0.06645699 -0.00738411 0.99776197 1704.5543   Square 49.5
+ 225.0000   75.0000    8.2867 -0.06613219 -0.02204406 0.99756734 1705.2917   Square 49.5
+ 225.0000  125.0000    9.7599 -0.06610364 -0.03672425 0.99713672 1706.7669   Square 49.5
+ 225.0000  175.0000   19.9697 -0.06636939 -0.05162063 0.99645894 1708.9802   Square 49.5
+ 225.0000  225.0000   22.9160 -0.06631118 -0.06631118 0.99559312 1711.9324   Square 49.5
+ 225.0000  275.0000   18.5990 -0.06593313 -0.08058494 0.99456467 1715.6245   Square 49.5
+ 225.0000  325.0000   23.0186 -0.06584837 -0.09511431 0.99328609 1720.0576   Square 49.5
+ 225.0000  375.0000   36.1747 -0.06605115 -0.11008525 0.99172500 1725.2332   Square 49.5
+ 225.0000  425.0000   42.0675 -0.06593657 -0.12454686 0.99002043 1731.1530   Square 49.5
+ 225.0000  475.0000   40.6968 -0.06551256 -0.13830430 0.98822064 1737.8188   Square 49.5
+ 225.0000  525.0000   48.0628 -0.06537415 -0.15253969 0.98613278 1745.2329   Square 49.5
+ 225.0000  575.0000   64.1653 -0.06551221 -0.16742010 0.98370659 1753.3976   Square 49.5
+ 225.0000  625.0000   73.0044 -0.06534477 -0.18151326 0.98121506 1762.3156   Square 49.5
+ 225.0000  675.0000   74.5801 -0.06488304 -0.19464912 0.97872463 1771.9898   Square 49.5
+ 225.0000  725.0000   84.8925 -0.06469502 -0.20846173 0.97588845 1782.4232   Square 49.5
+ 225.0000  775.0000  103.9414 -0.06476880 -0.22309255 0.97264316 1793.6193   Square 49.5
+ 225.0000  825.0000  115.7269 -0.06455340 -0.23669581 0.96943692 1805.5815   Square 49.5
+ 275.0000 -825.0000  111.4098 -0.07848982 0.23546947 0.96870712 1809.3239   Square 49.5
+ 275.0000 -775.0000   99.6243 -0.07874684 0.22192291 0.97187919 1797.3553   Square 49.5
+ 275.0000 -725.0000   96.5754 -0.07932777 0.20913686 0.97466347 1786.1532   Square 49.5
+ 275.0000 -675.0000   86.2631 -0.07956182 0.19528810 0.97751341 1775.7142   Square 49.5
+ 275.0000 -625.0000   68.6874 -0.07943371 0.18053117 0.98035646 1766.0349   Square 49.5
+ 275.0000 -575.0000   59.8483 -0.07963329 0.16650597 0.98281957 1757.1121   Square 49.5
+ 275.0000 -525.0000   59.7457 -0.08017340 0.15305832 0.98495958 1748.9429   Square 49.5
+ 275.0000 -475.0000   52.3798 -0.08034584 0.13877917 0.98705871 1741.5249   Square 49.5
+ 275.0000 -425.0000   37.7504 -0.08013888 0.12385100 0.98905950 1734.8554   Square 49.5
+ 275.0000 -375.0000   31.8577 -0.08027534 0.10946637 0.99074365 1728.9324   Square 49.5
+ 275.0000 -325.0000   34.7015 -0.08076431 0.09544873 0.99215254 1723.7540   Square 49.5
+ 275.0000 -275.0000   30.2820 -0.08086997 0.08086997 0.99343852 1719.3185   Square 49.5
+ 275.0000 -225.0000   18.5990 -0.08058494 0.06593313 0.99456467 1715.6245   Square 49.5
+ 275.0000 -175.0000   15.6526 -0.08065423 0.05132542 0.99541981 1712.6707   Square 49.5
+ 275.0000 -125.0000   21.4428 -0.08108254 0.03685570 0.99602574 1710.4562   Square 49.5
+ 275.0000  -75.0000   19.9697 -0.08111814 0.02212313 0.99645894 1708.9802   Square 49.5
+ 275.0000  -25.0000   11.2331 -0.08075849 0.00734168 0.99670666 1708.2424   Square 49.5
+ 275.0000   25.0000   11.2331 -0.08075849 -0.00734168 0.99670666 1708.2424   Square 49.5
+ 275.0000   75.0000   19.9697 -0.08111814 -0.02212313 0.99645894 1708.9802   Square 49.5
+ 275.0000  125.0000   21.4428 -0.08108254 -0.03685570 0.99602574 1710.4562   Square 49.5
+ 275.0000  175.0000   15.6526 -0.08065423 -0.05132542 0.99541981 1712.6707   Square 49.5
+ 275.0000  225.0000   18.5990 -0.08058494 -0.06593313 0.99456467 1715.6245   Square 49.5
+ 275.0000  275.0000   30.2820 -0.08086997 -0.08086997 0.99343852 1719.3185   Square 49.5
+ 275.0000  325.0000   34.7015 -0.08076431 -0.09544873 0.99215254 1723.7540   Square 49.5
+ 275.0000  375.0000   31.8577 -0.08027534 -0.10946637 0.99074365 1728.9324   Square 49.5
+ 275.0000  425.0000   37.7504 -0.08013888 -0.12385100 0.98905950 1734.8554   Square 49.5
+ 275.0000  475.0000   52.3798 -0.08034584 -0.13877917 0.98705871 1741.5249   Square 49.5
+ 275.0000  525.0000   59.7457 -0.08017340 -0.15305832 0.98495958 1748.9429   Square 49.5
+ 275.0000  575.0000   59.8483 -0.07963329 -0.16650597 0.98281957 1757.1121   Square 49.5
+ 275.0000  625.0000   68.6874 -0.07943371 -0.18053117 0.98035646 1766.0349   Square 49.5
+ 275.0000  675.0000   86.2631 -0.07956182 -0.19528810 0.97751341 1775.7142   Square 49.5
+ 275.0000  725.0000   96.5754 -0.07932777 -0.20913686 0.97466347 1786.1532   Square 49.5
+ 275.0000  775.0000   99.6243 -0.07874684 -0.22192291 0.97187919 1797.3553   Square 49.5
+ 275.0000  825.0000  111.4098 -0.07848982 -0.23546947 0.96870712 1809.3239   Square 49.5
+ 325.0000 -825.0000  115.8294 -0.09264756 0.23518226 0.96752557 1813.8174   Square 49.5
+ 325.0000 -775.0000  104.0439 -0.09295019 0.22165046 0.97068601 1801.8411   Square 49.5
+ 325.0000 -725.0000  100.9950 -0.09363322 0.20887410 0.97344976 1790.6319   Square 49.5
+ 325.0000 -675.0000   90.6827 -0.09390876 0.19504127 0.97628892 1780.1862   Square 49.5
+ 325.0000 -625.0000   73.1070 -0.09375894 0.18030565 0.97913183 1770.5006   Square 49.5
+ 325.0000 -575.0000   64.2678 -0.09399392 0.16629693 0.98158569 1761.5720   Square 49.5
+ 325.0000 -525.0000   64.1653 -0.09462875 0.15286183 0.98370659 1753.3976   Square 49.5
+ 325.0000 -475.0000   56.7994 -0.09483174 0.13860024 0.98579760 1745.9748   Square 49.5
+ 325.0000 -425.0000   42.1700 -0.09458917 0.12369353 0.98780200 1739.3010   Square 49.5
+ 325.0000 -375.0000   36.2773 -0.09474983 0.10932672 0.98947973 1733.3742   Square 49.5
+ 325.0000 -325.0000   39.1211 -0.09532436 0.09532436 0.99087160 1728.1924   Square 49.5
+ 325.0000 -275.0000   34.7015 -0.09544873 0.08076431 0.99215254 1723.7540   Square 49.5
+ 325.0000 -225.0000   23.0186 -0.09511431 0.06584837 0.99328609 1720.0576   Square 49.5
+ 325.0000 -175.0000   20.0722 -0.09519588 0.05125932 0.99413793 1717.1019   Square 49.5
+ 325.0000 -125.0000   25.8624 -0.09569896 0.03680729 0.99472958 1714.8859   Square 49.5
+ 325.0000  -75.0000   24.3892 -0.09574086 0.02209404 0.99516106 1713.4090   Square 49.5
+ 325.0000  -25.0000   15.6526 -0.09531863 0.00733220 0.99541981 1712.6707   Square 49.5
+ 325.0000   25.0000   15.6526 -0.09531863 -0.00733220 0.99541981 1712.6707   Square 49.5
+ 325.0000   75.0000   24.3892 -0.09574086 -0.02209404 0.99516106 1713.4090   Square 49.5
+ 325.0000  125.0000   25.8624 -0.09569896 -0.03680729 0.99472958 1714.8859   Square 49.5
+ 325.0000  175.0000   20.0722 -0.09519588 -0.05125932 0.99413793 1717.1019   Square 49.5
+ 325.0000  225.0000   23.0186 -0.09511431 -0.06584837 0.99328609 1720.0576   Square 49.5
+ 325.0000  275.0000   34.7015 -0.09544873 -0.08076431 0.99215254 1723.7540  Square 49.5
+ 325.0000  325.0000   39.1211 -0.09532436 -0.09532436 0.99087160 1728.1924  Square 49.5
+ 325.0000  375.0000   36.2773 -0.09474983 -0.10932672 0.98947973 1733.3742  Square 49.5
+ 325.0000  425.0000   42.1700 -0.09458917 -0.12369353 0.98780200 1739.3010  Square 49.5
+ 325.0000  475.0000   56.7994 -0.09483174 -0.13860024 0.98579760 1745.9748  Square 49.5
+ 325.0000  525.0000   64.1653 -0.09462875 -0.15286183 0.98370659 1753.3976  Square 49.5
+ 325.0000  575.0000   64.2678 -0.09399392 -0.16629693 0.98158569 1761.5720  Square 49.5
+ 325.0000  625.0000   73.1070 -0.09375894 -0.18030565 0.97913183 1770.5006  Square 49.5
+ 325.0000  675.0000   90.6827 -0.09390876 -0.19504127 0.97628892 1780.1862  Square 49.5
+ 325.0000  725.0000  100.9950 -0.09363322 -0.20887410 0.97344976 1790.6319  Square 49.5
+ 325.0000  775.0000  104.0439 -0.09295019 -0.22165046 0.97068601 1801.8411  Square 49.5
+ 325.0000  825.0000  115.8294 -0.09264756 -0.23518226 0.96752557 1813.8174  Square 49.5
+ 375.0000 -825.0000  120.9856 -0.10674932 0.23484851 0.96615255 1819.0634   Square 49.5
+ 375.0000 -775.0000  109.2001 -0.10709703 0.22133386 0.96929951 1807.0782   Square 49.5
+ 375.0000 -725.0000   98.1511 -0.10742611 0.20769047 0.97227789 1795.8606   Square 49.5
+ 375.0000 -675.0000   87.8388 -0.10773600 0.19392480 0.97508263 1785.4071   Square 49.5
+ 375.0000 -625.0000   86.2631 -0.10849339 0.18082232 0.97751341 1775.7142   Square 49.5
+ 375.0000 -575.0000   77.4240 -0.10876923 0.16677949 0.97997646 1766.7790   Square 49.5
+ 375.0000 -525.0000   61.3214 -0.10854535 0.15196349 0.98240776 1758.5984   Square 49.5
+ 375.0000 -475.0000   53.9555 -0.10877342 0.13777967 0.98447199 1751.1699   Square 49.5
+ 375.0000 -425.0000   55.3262 -0.10946827 0.12406403 0.98621743 1744.4911   Square 49.5
+ 375.0000 -375.0000   49.4334 -0.10965699 0.10965699 0.98790217 1738.5599   Square 49.5
+ 375.0000 -325.0000   36.2773 -0.10932672 0.09474983 0.98947973 1733.3742   Square 49.5
+ 375.0000 -275.0000   31.8577 -0.10946637 0.08027534 0.99074365 1728.9324   Square 49.5
+ 375.0000 -225.0000   36.1747 -0.11008525 0.06605115 0.99172500 1725.2332   Square 49.5
+ 375.0000 -175.0000   33.2283 -0.11018111 0.05141785 0.99258064 1722.2752   Square 49.5
+ 375.0000 -125.0000   23.0186 -0.10974728 0.03658243 0.99328609 1720.0576   Square 49.5
+ 375.0000  -75.0000   21.5454 -0.10979431 0.02195886 0.99371174 1718.5796   Square 49.5
+ 375.0000  -25.0000   28.8088 -0.11032538 0.00735503 0.99386831 1717.8407   Square 49.5
+ 375.0000   25.0000   28.8088 -0.11032538 -0.00735503 0.99386831 1717.8407   Square 49.5
+ 375.0000   75.0000   21.5454 -0.10979431 -0.02195886 0.99371174 1718.5796   Square 49.5
+ 375.0000  125.0000   23.0186 -0.10974728 -0.03658243 0.99328609 1720.0576   Square 49.5
+ 375.0000  175.0000   33.2283 -0.11018111 -0.05141785 0.99258064 1722.2752   Square 49.5
+ 375.0000  225.0000   36.1747 -0.11008525 -0.06605115 0.99172500 1725.2332   Square 49.5
+ 375.0000  275.0000   31.8577 -0.10946637 -0.08027534 0.99074365 1728.9324   Square 49.5
+ 375.0000  325.0000   36.2773 -0.10932672 -0.09474983 0.98947973 1733.3742   Square 49.5
+ 375.0000  375.0000   49.4334 -0.10965699 -0.10965699 0.98790217 1738.5599   Square 49.5
+ 375.0000  425.0000   55.3262 -0.10946827 -0.12406403 0.98621743 1744.4911   Square 49.5
+ 375.0000  475.0000   53.9555 -0.10877342 -0.13777967 0.98447199 1751.1699   Square 49.5
+ 375.0000  525.0000   61.3214 -0.10854535 -0.15196349 0.98240776 1758.5984   Square 49.5
+ 375.0000  575.0000   77.4240 -0.10876923 -0.16677949 0.97997646 1766.7790   Square 49.5
+ 375.0000  625.0000   86.2631 -0.10849339 -0.18082232 0.97751341 1775.7142   Square 49.5
+ 375.0000  675.0000   87.8388 -0.10773600 -0.19392480 0.97508263 1785.4071   Square 49.5
+ 375.0000  725.0000   98.1511 -0.10742611 -0.20769047 0.97227789 1795.8606   Square 49.5
+ 375.0000  775.0000  109.2001 -0.10709703 -0.22133386 0.96929951 1807.0782   Square 49.5
+ 375.0000  825.0000  120.9856 -0.10674932 -0.23484851 0.96615255 1819.0634   Square 49.5
+ 425.0000 -775.0000  115.0928 -0.12117912 0.22097369 0.96772220 1813.0683   Square 49.5
+ 425.0000 -725.0000  104.0439 -0.12155025 0.20735043 0.97068601 1801.8411   Square 49.5
+ 425.0000 -675.0000   93.7316 -0.12189974 0.19360546 0.97347695 1791.3786   Square 49.5
+ 425.0000 -625.0000   92.1559 -0.12275209 0.18051778 0.97588178 1781.6775   Square 49.5
+ 425.0000 -575.0000   83.3167 -0.12306312 0.16649716 0.97833234 1772.7345   Square 49.5
+ 425.0000 -525.0000   67.2142 -0.12281244 0.15170948 0.98076569 1764.5469   Square 49.5
+ 425.0000 -475.0000   59.8483 -0.12306963 0.13754841 0.98281957 1757.1121   Square 49.5
+ 425.0000 -425.0000   61.2189 -0.12385126 0.12385126 0.98454138 1750.4275   Square 49.5
+ 425.0000 -375.0000   55.3262 -0.12406403 0.10946827 0.98621743 1744.4911   Square 49.5
+ 425.0000 -325.0000   42.1700 -0.12369353 0.09458917 0.98780200 1739.3010   Square 49.5
+ 425.0000 -275.0000   37.7504 -0.12385100 0.08013888 0.98905950 1734.8554   Square 49.5
+ 425.0000 -225.0000   42.0675 -0.12454686 0.06593657 0.99002043 1731.1530   Square 49.5
+ 425.0000 -175.0000   39.1211 -0.12465493 0.05132850 0.99087160 1728.1924   Square 49.5
+ 425.0000 -125.0000   28.9113 -0.12416774 0.03651992 0.99158896 1725.9729   Square 49.5
+ 425.0000  -75.0000   27.4381 -0.12422077 0.02192131 0.99201243 1724.4936   Square 49.5
+ 425.0000  -25.0000   34.7015 -0.12481757 0.00734221 0.99215254 1723.7540   Square 49.5
+ 425.0000   25.0000   34.7015 -0.12481757 -0.00734221 0.99215254 1723.7540   Square 49.5
+ 425.0000   75.0000   27.4381 -0.12422077 -0.02192131 0.99201243 1724.4936   Square 49.5
+ 425.0000  125.0000   28.9113 -0.12416774 -0.03651992 0.99158896 1725.9729   Square 49.5
+ 425.0000  175.0000   39.1211 -0.12465493 -0.05132850 0.99087160 1728.1924   Square 49.5
+ 425.0000  225.0000   42.0675 -0.12454686 -0.06593657 0.99002043 1731.1530   Square 49.5
+ 425.0000  275.0000   37.7504 -0.12385100 -0.08013888 0.98905950 1734.8554   Square 49.5
+ 425.0000  325.0000   42.1700 -0.12369353 -0.09458917 0.98780200 1739.3010   Square 49.5
+ 425.0000  375.0000   55.3262 -0.12406403 -0.10946827 0.98621743 1744.4911   Square 49.5
+ 425.0000  425.0000   61.2189 -0.12385126 -0.12385126 0.98454138 1750.4275   Square 49.5
+ 425.0000  475.0000   59.8483 -0.12306963 -0.13754841 0.98281957 1757.1121   Square 49.5
+ 425.0000  525.0000   67.2142 -0.12281244 -0.15170948 0.98076569 1764.5469   Square 49.5
+ 425.0000  575.0000   83.3167 -0.12306312 -0.16649716 0.97833234 1772.7345   Square 49.5
+ 425.0000  625.0000   92.1559 -0.12275209 -0.18051778 0.97588178 1781.6775   Square 49.5
+ 425.0000  675.0000   93.7316 -0.12189974 -0.19360546 0.97347695 1791.3786   Square 49.5
+ 425.0000  725.0000  104.0439 -0.12155025 -0.20735043 0.97068601 1801.8411   Square 49.5
+ 425.0000  775.0000  115.0928 -0.12117912 -0.22097369 0.96772220 1813.0683   Square 49.5
+ 475.0000 -725.0000  110.6732 -0.13560095 0.20696987 0.96890446 1808.5752   Square 49.5
+ 475.0000 -675.0000  100.3609 -0.13598940 0.19324809 0.97168002 1798.1027   Square 49.5
+ 475.0000 -625.0000   90.7852 -0.13635310 0.17941198 0.97427880 1788.3922   Square 49.5
+ 475.0000 -575.0000   81.9461 -0.13669143 0.16546858 0.97669627 1779.4406   Square 49.5
+ 475.0000 -525.0000   81.8435 -0.13759933 0.15208347 0.97874258 1771.2452   Square 49.5
+ 475.0000 -475.0000   74.4776 -0.13789143 0.13789143 0.98080166 1763.8031   Square 49.5
+ 475.0000 -425.0000   59.8483 -0.13754841 0.12306963 0.98281957 1757.1121   Square 49.5
+ 475.0000 -375.0000   53.9555 -0.13777967 0.10877342 0.98447199 1751.1699   Square 49.5
+ 475.0000 -325.0000   56.7994 -0.13860024 0.09483174 0.98579760 1745.9748   Square 49.5
+ 475.0000 -275.0000   52.3798 -0.13877917 0.08034584 0.98705871 1741.5249   Square 49.5
+ 475.0000 -225.0000   40.6968 -0.13830430 0.06551256 0.98822064 1737.8188   Square 49.5
+ 475.0000 -175.0000   37.7504 -0.13842170 0.05099747 0.98905950 1734.8554   Square 49.5
+ 475.0000 -125.0000   43.5407 -0.13913916 0.03661557 0.98959567 1732.6337   Square 49.5
+ 475.0000  -75.0000   42.0675 -0.13919943 0.02197886 0.99002043 1731.1530   Square 49.5
+ 475.0000  -25.0000   33.3309 -0.13859837 0.00729465 0.99032181 1730.4127   Square 49.5
+ 475.0000   25.0000   33.3309 -0.13859837 -0.00729465 0.99032181 1730.4127   Square 49.5
+ 475.0000   75.0000   42.0675 -0.13919943 -0.02197886 0.99002043 1731.1530   Square 49.5
+ 475.0000  125.0000   43.5407 -0.13913916 -0.03661557 0.98959567 1732.6337   Square 49.5
+ 475.0000  175.0000   37.7504 -0.13842170 -0.05099747 0.98905950 1734.8554   Square 49.5
+ 475.0000  225.0000   40.6968 -0.13830430 -0.06551256 0.98822064 1737.8188   Square 49.5
+ 475.0000  275.0000   52.3798 -0.13877917 -0.08034584 0.98705871 1741.5249   Square 49.5
+ 475.0000  325.0000   56.7994 -0.13860024 -0.09483174 0.98579760 1745.9748   Square 49.5
+ 475.0000  375.0000   53.9555 -0.13777967 -0.10877342 0.98447199 1751.1699   Square 49.5
+ 475.0000  425.0000   59.8483 -0.13754841 -0.12306963 0.98281957 1757.1121   Square 49.5
+ 475.0000  475.0000   74.4776 -0.13789143 -0.13789143 0.98080166 1763.8031   Square 49.5
+ 475.0000  525.0000   81.8435 -0.13759933 -0.15208347 0.97874258 1771.2452   Square 49.5
+ 475.0000  575.0000   81.9461 -0.13669143 -0.16546858 0.97669627 1779.4406   Square 49.5
+ 475.0000  625.0000   90.7852 -0.13635310 -0.17941198 0.97427880 1788.3922   Square 49.5
+ 475.0000  675.0000  100.3609 -0.13598940 -0.19324809 0.97168002 1798.1027   Square 49.5
+ 475.0000  725.0000  110.6732 -0.13560095 -0.20696987 0.96890446 1808.5752   Square 49.5
+ 525.0000 -675.0000  107.7269 -0.14999702 0.19285332 0.96969505 1805.5815   Square 49.5
+ 525.0000 -625.0000   98.1511 -0.15039655 0.17904351 0.97227789 1795.8606   Square 49.5
+ 525.0000 -575.0000   89.3120 -0.15076819 0.16512707 0.97468046 1786.8995   Square 49.5
+ 525.0000 -525.0000   89.2095 -0.15176268 0.15176268 0.97669656 1778.6952   Square 49.5
+ 525.0000 -475.0000   81.8435 -0.15208347 0.13759933 0.97874258 1771.2452   Square 49.5
+ 525.0000 -425.0000   67.2142 -0.15170948 0.12281244 0.98076569 1764.5469   Square 49.5
+ 525.0000 -375.0000   61.3214 -0.15196349 0.10854535 0.98240776 1758.5984   Square 49.5
+ 525.0000 -325.0000   64.1653 -0.15286183 0.09462875 0.98370659 1753.3976   Square 49.5
+ 525.0000 -275.0000   59.7457 -0.15305832 0.08017340 0.98495958 1748.9429   Square 49.5
+ 525.0000 -225.0000   48.0628 -0.15253969 0.06537415 0.98613278 1745.2329   Square 49.5
+ 525.0000 -175.0000   45.1164 -0.15266863 0.05088954 0.98696633 1742.2663   Square 49.5
+ 525.0000 -125.0000   50.9066 -0.15345360 0.03653657 0.98748016 1740.0422   Square 49.5
+ 525.0000  -75.0000   49.4334 -0.15351978 0.02193140 0.98790217 1738.5599   Square 49.5
+ 525.0000  -25.0000   40.6968 -0.15286265 0.00727917 0.98822064 1737.8188   Square 49.5
+ 525.0000   25.0000   40.6968 -0.15286265 -0.00727917 0.98822064 1737.8188   Square 49.5
+ 525.0000   75.0000   49.4334 -0.15351978 -0.02193140 0.98790217 1738.5599   Square 49.5
+ 525.0000  125.0000   50.9066 -0.15345360 -0.03653657 0.98748016 1740.0422   Square 49.5
+ 525.0000  175.0000   45.1164 -0.15266863 -0.05088954 0.98696633 1742.2663   Square 49.5
+ 525.0000  225.0000   48.0628 -0.15253969 -0.06537415 0.98613278 1745.2329   Square 49.5
+ 525.0000  275.0000   59.7457 -0.15305832 -0.08017340 0.98495958 1748.9429   Square 49.5
+ 525.0000  325.0000   64.1653 -0.15286183 -0.09462875 0.98370659 1753.3976   Square 49.5
+ 525.0000  375.0000   61.3214 -0.15196349 -0.10854535 0.98240776 1758.5984   Square 49.5
+ 525.0000  425.0000   67.2142 -0.15170948 -0.12281244 0.98076569 1764.5469   Square 49.5
+ 525.0000  475.0000   81.8435 -0.15208347 -0.13759933 0.97874258 1771.2452   Square 49.5
+ 525.0000  525.0000   89.2095 -0.15176268 -0.15176268 0.97669656 1778.6952  Square 49.5
+ 525.0000  575.0000   89.3120 -0.15076819 -0.16512707 0.97468046 1786.8995  Square 49.5
+ 525.0000  625.0000   98.1511 -0.15039655 -0.17904351 0.97227789 1795.8606  Square 49.5
+ 525.0000  675.0000  107.7269 -0.14999702 -0.19285332 0.96969505 1805.5815  Square 49.5
+ 575.0000 -625.0000  106.2537 -0.16434955 0.17864081 0.97009107 1804.0851  Square 49.5
+ 575.0000 -575.0000   97.4146 -0.16475384 0.16475384 0.97247743 1795.1134  Square 49.5
+ 575.0000 -525.0000   89.3120 -0.16512707 0.15076819 0.97468046 1786.8995  Square 49.5
+ 575.0000 -475.0000   81.9461 -0.16546858 0.13669143 0.97669627 1779.4406  Square 49.5
+ 575.0000 -425.0000   83.3167 -0.16649716 0.12306312 0.97833234 1772.7345  Square 49.5
+ 575.0000 -375.0000   77.4240 -0.16677949 0.10876923 0.97997646 1766.7790  Square 49.5
+ 575.0000 -325.0000   64.2678 -0.16629693 0.09399392 0.98158569 1761.5720  Square 49.5
+ 575.0000 -275.0000   59.8483 -0.16650597 0.07963329 0.98281957 1757.1121  Square 49.5
+ 575.0000 -225.0000   64.1653 -0.16742010 0.06551221 0.98370659 1753.3976  Square 49.5
+ 575.0000 -175.0000   61.2189 -0.16756347 0.05099758 0.98454138 1750.4275  Square 49.5
+ 575.0000 -125.0000   51.0091 -0.16692642 0.03628835 0.98530134 1748.2008  Square 49.5
+ 575.0000  -75.0000   49.5359 -0.16699681 0.02178219 0.98571680 1746.7167  Square 49.5
+ 575.0000  -25.0000   56.7994 -0.16777923 0.00729475 0.98579760 1745.9748  Square 49.5
+ 575.0000   25.0000   56.7994 -0.16777923 -0.00729475 0.98579760 1745.9748  Square 49.5
+ 575.0000   75.0000   49.5359 -0.16699681 -0.02178219 0.98571680 1746.7167  Square 49.5
+ 575.0000  125.0000   51.0091 -0.16692642 -0.03628835 0.98530134 1748.2008  Square 49.5
+ 575.0000  175.0000   61.2189 -0.16756347 -0.05099758 0.98454138 1750.4275  Square 49.5
+ 575.0000  225.0000   64.1653 -0.16742010 -0.06551221 0.98370659 1753.3976  Square 49.5
+ 575.0000  275.0000   59.8483 -0.16650597 -0.07963329 0.98281957 1757.1121  Square 49.5
+ 575.0000  325.0000   64.2678 -0.16629693 -0.09399392 0.98158569 1761.5720  Square 49.5
+ 575.0000  375.0000   77.4240 -0.16677949 -0.10876923 0.97997646 1766.7790  Square 49.5
+ 575.0000  425.0000   83.3167 -0.16649716 -0.12306312 0.97833234 1772.7345  Square 49.5
+ 575.0000  475.0000   81.9461 -0.16546858 -0.13669143 0.97669627 1779.4406  Square 49.5
+ 575.0000  525.0000   89.3120 -0.16512707 -0.15076819 0.97468046 1786.8995  Square 49.5
+ 575.0000  575.0000   97.4146 -0.16475384 -0.16475384 0.97247743 1795.1134  Square 49.5
+ 575.0000  625.0000  106.2537 -0.16434955 -0.17864081 0.97009107 1804.0851  Square 49.5
+ 625.0000 -575.0000  106.2537 -0.17864081 0.16434955 0.97009107 1804.0851  Square 49.5
+ 625.0000 -525.0000   98.1511 -0.17904351 0.15039655 0.97227789 1795.8606  Square 49.5
+ 625.0000 -475.0000   90.7852 -0.17941198 0.13635310 0.97427880 1788.3922  Square 49.5
+ 625.0000 -425.0000   92.1559 -0.18051778 0.12275209 0.97588178 1781.6775  Square 49.5
+ 625.0000 -375.0000   86.2631 -0.18082232 0.10849339 0.97751341 1775.7142  Square 49.5
+ 625.0000 -325.0000   73.1070 -0.18030565 0.09375894 0.97913183 1770.5006  Square 49.5
+ 625.0000 -275.0000   68.6874 -0.18053117 0.07943371 0.98035646 1766.0349  Square 49.5
+ 625.0000 -225.0000   73.0044 -0.18151326 0.06534477 0.98121506 1762.3156  Square 49.5
+ 625.0000 -175.0000   70.0580 -0.18166790 0.05086701 0.98204344 1759.3417  Square 49.5
+ 625.0000 -125.0000   59.8483 -0.18098475 0.03619695 0.98281957 1757.1121  Square 49.5
+ 625.0000  -75.0000   58.3751 -0.18106068 0.02172728 0.98323189 1755.6261  Square 49.5
+ 625.0000  -25.0000   65.6385 -0.18190060 0.00727602 0.98329000 1754.8832  Square 49.5
+ 625.0000   25.0000   65.6385 -0.18190060 -0.00727602 0.98329000 1754.8832  Square 49.5
+ 625.0000   75.0000   58.3751 -0.18106068 -0.02172728 0.98323189 1755.6261  Square 49.5
+ 625.0000  125.0000   59.8483 -0.18098475 -0.03619695 0.98281957 1757.1121  Square 49.5
+ 625.0000  175.0000   70.0580 -0.18166790 -0.05086701 0.98204344 1759.3417  Square 49.5
+ 625.0000  225.0000   73.0044 -0.18151326 -0.06534477 0.98121506 1762.3156  Square 49.5
+ 625.0000  275.0000   68.6874 -0.18053117 -0.07943371 0.98035646 1766.0349  Square 49.5
+ 625.0000  325.0000   73.1070 -0.18030565 -0.09375894 0.97913183 1770.5006  Square 49.5
+ 625.0000  375.0000   86.2631 -0.18082232 -0.10849339 0.97751341 1775.7142  Square 49.5
+ 625.0000  425.0000   92.1559 -0.18051778 -0.12275209 0.97588178 1781.6775  Square 49.5
+ 625.0000  475.0000   90.7852 -0.17941198 -0.13635310 0.97427880 1788.3922  Square 49.5
+ 625.0000  525.0000   98.1511 -0.17904351 -0.15039655 0.97227789 1795.8606  Square 49.5
+ 625.0000  575.0000  106.2537 -0.17864081 -0.16434955 0.97009107 1804.0851  Square 49.5
+ 675.0000 -525.0000  107.7269 -0.19285332 0.14999702 0.96969505 1805.5815  Square 49.5
+ 675.0000 -475.0000  100.3609 -0.19324809 0.13598940 0.97168002 1798.1027  Square 49.5
+ 675.0000 -425.0000   93.7316 -0.19360546 0.12189974 0.97347695 1791.3786  Square 49.5
+ 675.0000 -375.0000   87.8388 -0.19392480 0.10773600 0.97508263 1785.4071  Square 49.5
+ 675.0000 -325.0000   90.6827 -0.19504127 0.09390876 0.97628892 1780.1862  Square 49.5
+ 675.0000 -275.0000   86.2631 -0.19528810 0.07956182 0.97751341 1775.7142  Square 49.5
+ 675.0000 -225.0000   74.5801 -0.19464912 0.06488304 0.97872463 1771.9898  Square 49.5
+ 675.0000 -175.0000   71.6338 -0.19481119 0.05050660 0.97953953 1769.0117  Square 49.5
+ 675.0000 -125.0000   77.4240 -0.19578462 0.03625641 0.97997646 1766.7790  Square 49.5
+ 675.0000  -75.0000   75.9508 -0.19586775 0.02176308 0.98038880 1765.2909  Square 49.5
+ 675.0000  -25.0000   67.2142 -0.19505505 0.00722426 0.98076569 1764.5469  Square 49.5
+ 675.0000   25.0000   67.2142 -0.19505505 -0.00722426 0.98076569 1764.5469  Square 49.5
+ 675.0000   75.0000   75.9508 -0.19586775 -0.02176308 0.98038880 1765.2909  Square 49.5
+ 675.0000  125.0000   77.4240 -0.19578462 -0.03625641 0.97997646 1766.7790  Square 49.5
+ 675.0000  175.0000   71.6338 -0.19481119 -0.05050660 0.97953953 1769.0117  Square 49.5
+ 675.0000  225.0000   74.5801 -0.19464912 -0.06488304 0.97872463 1771.9898  Square 49.5
+ 675.0000  275.0000   86.2631 -0.19528810 -0.07956182 0.97751341 1775.7142  Square 49.5
+ 675.0000  325.0000   90.6827 -0.19504127 -0.09390876 0.97628892 1780.1862  Square 49.5
+ 675.0000  375.0000   87.8388 -0.19392480 -0.10773600 0.97508263 1785.4071  Square 49.5
+ 675.0000  425.0000   93.7316 -0.19360546 -0.12189974 0.97347695 1791.3786  Square 49.5
+ 675.0000  475.0000  100.3609 -0.19324809 -0.13598940 0.97168002 1798.1027  Square 49.5
+ 675.0000  525.0000  107.7269 -0.19285332 -0.14999702 0.96969505 1805.5815  Square 49.5
+ 725.0000 -475.0000  110.6732 -0.20696987 0.13560095 0.96890446 1808.5752  Square 49.5
+ 725.0000 -425.0000  104.0439 -0.20735043 0.12155025 0.97068601 1801.8411  Square 49.5
+ 725.0000 -375.0000   98.1511 -0.20769047 0.10742611 0.97227789 1795.8606  Square 49.5
+ 725.0000 -325.0000  100.9950 -0.20887410 0.09363322 0.97344976 1790.6319  Square 49.5
+ 725.0000 -275.0000   96.5754 -0.20913686 0.07932777 0.97466347 1786.1532  Square 49.5
+ 725.0000 -225.0000   84.8925 -0.20846173 0.06469502 0.97588845 1782.4232  Square 49.5
+ 725.0000 -175.0000   81.9461 -0.20863429 0.05036000 0.97669627 1779.4406  Square 49.5
+ 725.0000 -125.0000   87.7363 -0.20966540 0.03614921 0.97710473 1777.2046  Square 49.5
+ 725.0000  -75.0000   86.2631 -0.20975389 0.02169868 0.97751341 1775.7142  Square 49.5
+ 725.0000  -25.0000   77.5265 -0.20889394 0.00720324 0.97791177 1774.9692  Square 49.5
+ 725.0000   25.0000   77.5265 -0.20889394 -0.00720324 0.97791177 1774.9692  Square 49.5
+ 725.0000   75.0000   86.2631 -0.20975389 -0.02169868 0.97751341 1775.7142  Square 49.5
+ 725.0000  125.0000   87.7363 -0.20966540 -0.03614921 0.97710473 1777.2046  Square 49.5
+ 725.0000  175.0000   81.9461 -0.20863429 -0.05036000 0.97669627 1779.4406  Square 49.5
+ 725.0000  225.0000   84.8925 -0.20846173 -0.06469502 0.97588845 1782.4232  Square 49.5
+ 725.0000  275.0000   96.5754 -0.20913686 -0.07932777 0.97466347 1786.1532  Square 49.5
+ 725.0000  325.0000  100.9950 -0.20887410 -0.09363322 0.97344976 1790.6319  Square 49.5
+ 725.0000  375.0000   98.1511 -0.20769047 -0.10742611 0.97227789 1795.8606  Square 49.5
+ 725.0000  425.0000  104.0439 -0.20735043 -0.12155025 0.97068601 1801.8411  Square 49.5
+ 725.0000  475.0000  110.6732 -0.20696987 -0.13560095 0.96890446 1808.5752  Square 49.5
+ 775.0000 -425.0000  115.0928 -0.22097369 0.12117912 0.96772220 1813.0683  Square 49.5
+ 775.0000 -375.0000  109.2001 -0.22133386 0.10709703 0.96929951 1807.0782  Square 49.5
+ 775.0000 -325.0000  104.0439 -0.22165046 0.09295019 0.97068601 1801.8411  Square 49.5
+ 775.0000 -275.0000   99.6243 -0.22192291 0.07874684 0.97187919 1797.3553  Square 49.5
+ 775.0000 -225.0000  103.9414 -0.22309255 0.06476880 0.97264316 1793.6193  Square 49.5
+ 775.0000 -175.0000  100.9950 -0.22327921 0.05041789 0.97344976 1790.6319  Square 49.5
+ 775.0000 -125.0000   90.7852 -0.22247085 0.03588240 0.97427880 1788.3922  Square 49.5
+ 775.0000  -75.0000   89.3120 -0.22256257 0.02153831 0.97468046 1786.8995  Square 49.5
+ 775.0000  -25.0000   96.5754 -0.22356009 0.00721162 0.97466347 1786.1532  Square 49.5
+ 775.0000   25.0000   96.5754 -0.22356009 -0.00721162 0.97466347 1786.1532  Square 49.5
+ 775.0000   75.0000   89.3120 -0.22256257 -0.02153831 0.97468046 1786.8995  Square 49.5
+ 775.0000  125.0000   90.7852 -0.22247085 -0.03588240 0.97427880 1788.3922  Square 49.5
+ 775.0000  175.0000  100.9950 -0.22327921 -0.05041789 0.97344976 1790.6319  Square 49.5
+ 775.0000  225.0000  103.9414 -0.22309255 -0.06476880 0.97264316 1793.6193  Square 49.5
+ 775.0000  275.0000   99.6243 -0.22192291 -0.07874684 0.97187919 1797.3553  Square 49.5
+ 775.0000  325.0000  104.0439 -0.22165046 -0.09295019 0.97068601 1801.8411  Square 49.5
+ 775.0000  375.0000  109.2001 -0.22133386 -0.10709703 0.96929951 1807.0782  Square 49.5
+ 775.0000  425.0000  115.0928 -0.22097369 -0.12117912 0.96772220 1813.0683  Square 49.5
+ 825.0000 -375.0000  120.9856 -0.23484851 0.10674932 0.96615255 1819.0634  Square 49.5
+ 825.0000 -325.0000  115.8294 -0.23518226 0.09264756 0.96752557 1813.8174  Square 49.5
+ 825.0000 -275.0000  111.4098 -0.23546947 0.07848982 0.96870712 1809.3239  Square 49.5
+ 825.0000 -225.0000  115.7269 -0.23669581 0.06455340 0.96943692 1805.5815  Square 49.5
+ 825.0000 -175.0000  112.7805 -0.23689252 0.05024993 0.97023548 1802.5890  Square 49.5
+ 825.0000 -125.0000  102.5707 -0.23604705 0.03576470 0.97108325 1800.3455  Square 49.5
+ 825.0000  -25.0000  108.3609 -0.23718851 0.00718753 0.97143706 1798.1027  Square 49.5
+ 825.0000   25.0000  108.3609 -0.23718851 -0.00718753 0.97143706 1798.1027  Square 49.5
+ 825.0000  125.0000  102.5707 -0.23604705 -0.03576470 0.97108325 1800.3455  Square 49.5
+ 825.0000  175.0000  112.7805 -0.23689252 -0.05024993 0.97023548 1802.5890  Square 49.5
+ 825.0000  225.0000  115.7269 -0.23669581 -0.06455340 0.96943692 1805.5815  Square 49.5
+ 825.0000  275.0000  111.4098 -0.23546947 -0.07848982 0.96870712 1809.3239  Square 49.5
+ 825.0000  325.0000  115.8294 -0.23518226 -0.09264756 0.96752557 1813.8174  Square 49.5
+ 825.0000  375.0000  120.9856 -0.23484851 -0.10674932 0.96615255 1819.0634  Square 49.5
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-reflector.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-reflector.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-reflector.txt	(revision 17960)
@@ -0,0 +1,964 @@
+-825.0000 -375.0000 120.9856  0.23484851 0.10674932 0.96615255   1819.0634 Square 49.5
+-825.0000 -325.0000 115.8294  0.23518226 0.09264756 0.96752557   1813.8174 Square 49.5
+-825.0000 -275.0000 111.4098  0.23546947 0.07848982 0.96870712   1809.3239 Square 49.5
+-825.0000 -225.0000 107.7269  0.23570961 0.06428444 0.96969505   1805.5815 Square 49.5
+-825.0000 -175.0000 104.7805  0.23590225 0.05003987 0.97048758   1802.5890 Square 49.5
+-825.0000 -125.0000 102.5707  0.23604705 0.03576470 0.97108325   1800.3455 Square 49.5
+-825.0000  -25.0000 100.3609  0.23619211 0.00715734 0.97168002   1798.1027 Square 49.5
+-825.0000   25.0000 100.3609  0.23619211 -0.00715734 0.97168002  1798.1027 Square 49.5
+-825.0000  125.0000 102.5707  0.23604705 -0.03576470 0.97108325  1800.3455 Square 49.5
+-825.0000  175.0000 104.7805  0.23590225 -0.05003987 0.97048758  1802.5890 Square 49.5
+-825.0000  225.0000 107.7269  0.23570961 -0.06428444 0.96969505  1805.5815 Square 49.5
+-825.0000  275.0000 111.4098  0.23546947 -0.07848982 0.96870712  1809.3239 Square 49.5
+-825.0000  325.0000 115.8294  0.23518226 -0.09264756 0.96752557  1813.8174 Square 49.5
+-825.0000  375.0000 120.9856  0.23484851 -0.10674932 0.96615255  1819.0634 Square 49.5
+-775.0000 -425.0000 115.0928  0.22097369 0.12117912 0.96772220   1813.0683 Square 49.5
+-775.0000 -375.0000 109.2001  0.22133386 0.10709703 0.96929951   1807.0782 Square 49.5
+-775.0000 -325.0000 104.0439  0.22165046 0.09295019 0.97068601   1801.8411 Square 49.5
+-775.0000 -275.0000  99.6243  0.22192291 0.07874684 0.97187919   1797.3553 Square 49.5
+-775.0000 -225.0000  95.9414  0.22215073 0.06449537 0.97287687   1793.6193 Square 49.5
+-775.0000 -175.0000  92.9950  0.22233349 0.05020434 0.97367723   1790.6319 Square 49.5
+-775.0000 -125.0000  90.7852  0.22247085 0.03588240 0.97427880   1788.3922 Square 49.5
+-775.0000  -75.0000  89.3120  0.22256257 0.02153831 0.97468046   1786.8995 Square 49.5
+-775.0000  -25.0000  88.5754  0.22260847 0.00718092 0.97488148   1786.1532 Square 49.5
+-775.0000   25.0000  88.5754  0.22260847 -0.00718092 0.97488148  1786.1532 Square 49.5
+-775.0000   75.0000  89.3120  0.22256257 -0.02153831 0.97468046  1786.8995 Square 49.5
+-775.0000  125.0000  90.7852  0.22247085 -0.03588240 0.97427880  1788.3922 Square 49.5
+-775.0000  175.0000  92.9950  0.22233349 -0.05020434 0.97367723  1790.6319 Square 49.5
+-775.0000  225.0000  95.9414  0.22215073 -0.06449537 0.97287687  1793.6193 Square 49.5
+-775.0000  275.0000  99.6243  0.22192291 -0.07874684 0.97187919  1797.3553 Square 49.5
+-775.0000  325.0000 104.0439  0.22165046 -0.09295019 0.97068601  1801.8411 Square 49.5
+-775.0000  375.0000 109.2001  0.22133386 -0.10709703 0.96929951  1807.0782 Square 49.5
+-775.0000  425.0000 115.0928  0.22097369 -0.12117912 0.96772220  1813.0683 Square 49.5
+-725.0000 -475.0000 110.6732  0.20696987 0.13560095 0.96890446   1808.5752 Square 49.5
+-725.0000 -425.0000 104.0439  0.20735043 0.12155025 0.97068601   1801.8411 Square 49.5
+-725.0000 -375.0000  98.1511  0.20769047 0.10742611 0.97227789   1795.8606 Square 49.5
+-725.0000 -325.0000  92.9950  0.20798939 0.09323662 0.97367723   1790.6319 Square 49.5
+-725.0000 -275.0000  88.5754  0.20824663 0.07899010 0.97488148   1786.1532 Square 49.5
+-725.0000 -225.0000  84.8925  0.20846173 0.06469502 0.97588845   1782.4232 Square 49.5
+-725.0000 -175.0000  81.9461  0.20863429 0.05036000 0.97669627   1779.4406 Square 49.5
+-725.0000 -125.0000  79.7363  0.20876400 0.03599379 0.97730345   1777.2046 Square 49.5
+-725.0000  -75.0000  78.2631  0.20885060 0.02160523 0.97770887   1775.7142 Square 49.5
+-725.0000  -25.0000  77.5265  0.20889394 0.00720324 0.97791177   1774.9692 Square 49.5
+-725.0000   25.0000  77.5265  0.20889394 -0.00720324 0.97791177  1774.9692 Square 49.5
+-725.0000   75.0000  78.2631  0.20885060 -0.02160523 0.97770887  1775.7142 Square 49.5
+-725.0000  125.0000  79.7363  0.20876400 -0.03599379 0.97730345  1777.2046 Square 49.5
+-725.0000  175.0000  81.9461  0.20863429 -0.05036000 0.97669627  1779.4406 Square 49.5
+-725.0000  225.0000  84.8925  0.20846173 -0.06469502 0.97588845  1782.4232 Square 49.5
+-725.0000  275.0000  88.5754  0.20824663 -0.07899010 0.97488148  1786.1532 Square 49.5
+-725.0000  325.0000  92.9950  0.20798939 -0.09323662 0.97367723  1790.6319 Square 49.5
+-725.0000  375.0000  98.1511  0.20769047 -0.10742611 0.97227789  1795.8606 Square 49.5
+-725.0000  425.0000 104.0439  0.20735043 -0.12155025 0.97068601  1801.8411 Square 49.5
+-725.0000  475.0000 110.6732  0.20696987 -0.13560095 0.96890446  1808.5752 Square 49.5
+-675.0000 -525.0000 107.7269  0.19285332 0.14999702 0.96969505   1805.5815 Square 49.5
+-675.0000 -475.0000 100.3609  0.19324809 0.13598940 0.97168002   1798.1027 Square 49.5
+-675.0000 -425.0000  93.7316  0.19360546 0.12189974 0.97347695   1791.3786 Square 49.5
+-675.0000 -375.0000  87.8388  0.19392480 0.10773600 0.97508263   1785.4071 Square 49.5
+-675.0000 -325.0000  82.6827  0.19420552 0.09350636 0.97649413   1780.1862 Square 49.5
+-675.0000 -275.0000  78.2631  0.19444711 0.07921919 0.97770887   1775.7142 Square 49.5
+-675.0000 -225.0000  74.5801  0.19464912 0.06488304 0.97872463   1771.9898 Square 49.5
+-675.0000 -175.0000  71.6338  0.19481119 0.05050660 0.97953953   1769.0117 Square 49.5
+-675.0000 -125.0000  69.4240  0.19493301 0.03609870 0.98015203   1766.7790 Square 49.5
+-675.0000  -75.0000  67.9508  0.19501434 0.02166826 0.98056101   1765.2909 Square 49.5
+-675.0000  -25.0000  67.2142  0.19505505 0.00722426 0.98076569   1764.5469 Square 49.5
+-675.0000   25.0000  67.2142  0.19505505 -0.00722426 0.98076569  1764.5469 Square 49.5
+-675.0000   75.0000  67.9508  0.19501434 -0.02166826 0.98056101  1765.2909 Square 49.5
+-675.0000  125.0000  69.4240  0.19493301 -0.03609870 0.98015203  1766.7790 Square 49.5
+-675.0000  175.0000  71.6338  0.19481119 -0.05050660 0.97953953  1769.0117 Square 49.5
+-675.0000  225.0000  74.5801  0.19464912 -0.06488304 0.97872463  1771.9898 Square 49.5
+-675.0000  275.0000  78.2631  0.19444711 -0.07921919 0.97770887  1775.7142 Square 49.5
+-675.0000  325.0000  82.6827  0.19420552 -0.09350636 0.97649413  1780.1862 Square 49.5
+-675.0000  375.0000  87.8388  0.19392480 -0.10773600 0.97508263  1785.4071 Square 49.5
+-675.0000  425.0000  93.7316  0.19360546 -0.12189974 0.97347695  1791.3786 Square 49.5
+-675.0000  475.0000 100.3609  0.19324809 -0.13598940 0.97168002  1798.1027 Square 49.5
+-675.0000  525.0000 107.7269  0.19285332 -0.14999702 0.96969505  1805.5815 Square 49.5
+-625.0000 -575.0000 106.2537  0.17864081 0.16434955 0.97009107   1804.0851 Square 49.5
+-625.0000 -525.0000  98.1511  0.17904351 0.15039655 0.97227789   1795.8606 Square 49.5
+-625.0000 -475.0000  90.7852  0.17941198 0.13635310 0.97427880   1788.3922 Square 49.5
+-625.0000 -425.0000  84.1559  0.17974555 0.12222697 0.97609021   1781.6775 Square 49.5
+-625.0000 -375.0000  78.2631  0.18004362 0.10802617 0.97770887   1775.7142 Square 49.5
+-625.0000 -325.0000  73.1070  0.18030565 0.09375894 0.97913183   1770.5006 Square 49.5
+-625.0000 -275.0000  68.6874  0.18053117 0.07943371 0.98035646   1766.0349 Square 49.5
+-625.0000 -225.0000  65.0044  0.18071974 0.06505911 0.98138050   1762.3156 Square 49.5
+-625.0000 -175.0000  62.0580  0.18087103 0.05064389 0.98220205   1759.3417 Square 49.5
+-625.0000 -125.0000  59.8483  0.18098475 0.03619695 0.98281957   1757.1121 Square 49.5
+-625.0000  -75.0000  58.3751  0.18106068 0.02172728 0.98323189   1755.6261 Square 49.5
+-625.0000  -25.0000  57.6385  0.18109868 0.00724395 0.98343825   1754.8832 Square 49.5
+-625.0000   25.0000  57.6385  0.18109868 -0.00724395 0.98343825  1754.8832 Square 49.5
+-625.0000   75.0000  58.3751  0.18106068 -0.02172728 0.98323189  1755.6261 Square 49.5
+-625.0000  125.0000  59.8483  0.18098475 -0.03619695 0.98281957  1757.1121 Square 49.5
+-625.0000  175.0000  62.0580  0.18087103 -0.05064389 0.98220205  1759.3417 Square 49.5
+-625.0000  225.0000  65.0044  0.18071974 -0.06505911 0.98138050  1762.3156 Square 49.5
+-625.0000  275.0000  68.6874  0.18053117 -0.07943371 0.98035646  1766.0349 Square 49.5
+-625.0000  325.0000  73.1070  0.18030565 -0.09375894 0.97913183  1770.5006 Square 49.5
+-625.0000  375.0000  78.2631  0.18004362 -0.10802617 0.97770887  1775.7142 Square 49.5
+-625.0000  425.0000  84.1559  0.17974555 -0.12222697 0.97609021  1781.6775 Square 49.5
+-625.0000  475.0000  90.7852  0.17941198 -0.13635310 0.97427880  1788.3922 Square 49.5
+-625.0000  525.0000  98.1511  0.17904351 -0.15039655 0.97227789  1795.8606 Square 49.5
+-625.0000  575.0000 106.2537  0.17864081 -0.16434955 0.97009107  1804.0851 Square 49.5
+-575.0000 -625.0000 106.2537  0.16434955 0.17864081 0.97009107   1804.0851 Square 49.5
+-575.0000 -575.0000  97.4146  0.16475384 0.16475384 0.97247743   1795.1134 Square 49.5
+-575.0000 -525.0000  89.3120  0.16512707 0.15076819 0.97468046   1786.8995 Square 49.5
+-575.0000 -475.0000  81.9461  0.16546858 0.13669143 0.97669627   1779.4406 Square 49.5
+-575.0000 -425.0000  75.3167  0.16577776 0.12253139 0.97852123   1772.7345 Square 49.5
+-575.0000 -375.0000  69.4240  0.16605404 0.10829611 0.98015203   1766.7790 Square 49.5
+-575.0000 -325.0000  64.2678  0.16629693 0.09399392 0.98158569   1761.5720 Square 49.5
+-575.0000 -275.0000  59.8483  0.16650597 0.07963329 0.98281957   1757.1121 Square 49.5
+-575.0000 -225.0000  56.1653  0.16668077 0.06522291 0.98385136   1753.3976 Square 49.5
+-575.0000 -175.0000  53.2189  0.16682101 0.05077161 0.98467913   1750.4275 Square 49.5
+-575.0000 -125.0000  51.0091  0.16692642 0.03628835 0.98530134   1748.2008 Square 49.5
+-575.0000  -75.0000  49.5359  0.16699681 0.02178219 0.98571680   1746.7167 Square 49.5
+-575.0000  -25.0000  48.7994  0.16703203 0.00726226 0.98592472   1745.9748 Square 49.5
+-575.0000   25.0000  48.7994  0.16703203 -0.00726226 0.98592472  1745.9748 Square 49.5
+-575.0000   75.0000  49.5359  0.16699681 -0.02178219 0.98571680  1746.7167 Square 49.5
+-575.0000  125.0000  51.0091  0.16692642 -0.03628835 0.98530134  1748.2008 Square 49.5
+-575.0000  175.0000  53.2189  0.16682101 -0.05077161 0.98467913  1750.4275 Square 49.5
+-575.0000  225.0000  56.1653  0.16668077 -0.06522291 0.98385136  1753.3976 Square 49.5
+-575.0000  275.0000  59.8483  0.16650597 -0.07963329 0.98281957  1757.1121 Square 49.5
+-575.0000  325.0000  64.2678  0.16629693 -0.09399392 0.98158569  1761.5720 Square 49.5
+-575.0000  375.0000  69.4240  0.16605404 -0.10829611 0.98015203  1766.7790 Square 49.5
+-575.0000  425.0000  75.3167  0.16577776 -0.12253139 0.97852123  1772.7345 Square 49.5
+-575.0000  475.0000  81.9461  0.16546858 -0.13669143 0.97669627  1779.4406 Square 49.5
+-575.0000  525.0000  89.3120  0.16512707 -0.15076819 0.97468046  1786.8995 Square 49.5
+-575.0000  575.0000  97.4146  0.16475384 -0.16475384 0.97247743  1795.1134 Square 49.5
+-575.0000  625.0000 106.2537  0.16434955 -0.17864081 0.97009107  1804.0851 Square 49.5
+-525.0000 -675.0000 107.7269  0.14999702 0.19285332 0.96969505   1805.5815 Square 49.5
+-525.0000 -625.0000  98.1511  0.15039655 0.17904351 0.97227789   1795.8606 Square 49.5
+-525.0000 -575.0000  89.3120  0.15076819 0.16512707 0.97468046   1786.8995 Square 49.5
+-525.0000 -525.0000  81.2095  0.15111129 0.15111129 0.97689854   1778.6952 Square 49.5
+-525.0000 -475.0000  73.8435  0.15142525 0.13700379 0.97892817   1771.2452 Square 49.5
+-525.0000 -425.0000  67.2142  0.15170948 0.12281244 0.98076569   1764.5469 Square 49.5
+-525.0000 -375.0000  61.3214  0.15196349 0.10854535 0.98240776   1758.5984 Square 49.5
+-525.0000 -325.0000  56.1653  0.15218679 0.09421087 0.98385136   1753.3976 Square 49.5
+-525.0000 -275.0000  51.7457  0.15237898 0.07981756 0.98509380   1748.9429 Square 49.5
+-525.0000 -225.0000  48.0628  0.15253969 0.06537415 0.98613278   1745.2329 Square 49.5
+-525.0000 -175.0000  45.1164  0.15266863 0.05088954 0.98696633   1742.2663 Square 49.5
+-525.0000 -125.0000  42.9066  0.15276555 0.03637275 0.98759289   1740.0422 Square 49.5
+-525.0000  -75.0000  41.4334  0.15283026 0.02183289 0.98801125   1738.5599 Square 49.5
+-525.0000  -25.0000  40.6968  0.15286265 0.00727917 0.98822064   1737.8188 Square 49.5
+-525.0000   25.0000  40.6968  0.15286265 -0.00727917 0.98822064  1737.8188 Square 49.5
+-525.0000   75.0000  41.4334  0.15283026 -0.02183289 0.98801125  1738.5599 Square 49.5
+-525.0000  125.0000  42.9066  0.15276555 -0.03637275 0.98759289  1740.0422 Square 49.5
+-525.0000  175.0000  45.1164  0.15266863 -0.05088954 0.98696633  1742.2663 Square 49.5
+-525.0000  225.0000  48.0628  0.15253969 -0.06537415 0.98613278  1745.2329 Square 49.5
+-525.0000  275.0000  51.7457  0.15237898 -0.07981756 0.98509380  1748.9429 Square 49.5
+-525.0000  325.0000  56.1653  0.15218679 -0.09421087 0.98385136  1753.3976 Square 49.5
+-525.0000  375.0000  61.3214  0.15196349 -0.10854535 0.98240776  1758.5984 Square 49.5
+-525.0000  425.0000  67.2142  0.15170948 -0.12281244 0.98076569  1764.5469 Square 49.5
+-525.0000  475.0000  73.8435  0.15142525 -0.13700379 0.97892817  1771.2452 Square 49.5
+-525.0000  525.0000  81.2095  0.15111129 -0.15111129 0.97689854  1778.6952 Square 49.5
+-525.0000  575.0000  89.3120  0.15076819 -0.16512707 0.97468046  1786.8995 Square 49.5
+-525.0000  625.0000  98.1511  0.15039655 -0.17904351 0.97227789  1795.8606 Square 49.5
+-525.0000  675.0000 107.7269  0.14999702 -0.19285332 0.96969505  1805.5815 Square 49.5
+-475.0000 -725.0000 110.6732  0.13560095 0.20696987 0.96890446   1808.5752 Square 49.5
+-475.0000 -675.0000 100.3609  0.13598940 0.19324809 0.97168002   1798.1027 Square 49.5
+-475.0000 -625.0000  90.7852  0.13635310 0.17941198 0.97427880   1788.3922 Square 49.5
+-475.0000 -575.0000  81.9461  0.13669143 0.16546858 0.97669627   1779.4406 Square 49.5
+-475.0000 -525.0000  73.8435  0.13700379 0.15142525 0.97892817   1771.2452 Square 49.5
+-475.0000 -475.0000  66.4776  0.13728962 0.13728962 0.98097050   1763.8031 Square 49.5
+-475.0000 -425.0000  59.8483  0.13754841 0.12306963 0.98281957   1757.1121 Square 49.5
+-475.0000 -375.0000  53.9555  0.13777967 0.10877342 0.98447199   1751.1699 Square 49.5
+-475.0000 -325.0000  48.7994  0.13798298 0.09440941 0.98592472   1745.9748 Square 49.5
+-475.0000 -275.0000  44.3798  0.13815797 0.07998619 0.98717505   1741.5249 Square 49.5
+-475.0000 -225.0000  40.6968  0.13830430 0.06551256 0.98822064   1737.8188 Square 49.5
+-475.0000 -175.0000  37.7504  0.13842170 0.05099747 0.98905950   1734.8554 Square 49.5
+-475.0000 -125.0000  35.5407  0.13850995 0.03644999 0.98969005   1732.6337 Square 49.5
+-475.0000  -75.0000  34.0675  0.13856888 0.02187930 0.99011109   1731.1530 Square 49.5
+-475.0000  -25.0000  33.3309  0.13859837 0.00729465 0.99032181   1730.4127 Square 49.5
+-475.0000   25.0000  33.3309  0.13859837 -0.00729465 0.99032181  1730.4127 Square 49.5
+-475.0000   75.0000  34.0675  0.13856888 -0.02187930 0.99011109  1731.1530 Square 49.5
+-475.0000  125.0000  35.5407  0.13850995 -0.03644999 0.98969005  1732.6337 Square 49.5
+-475.0000  175.0000  37.7504  0.13842170 -0.05099747 0.98905950  1734.8554 Square 49.5
+-475.0000  225.0000  40.6968  0.13830430 -0.06551256 0.98822064  1737.8188 Square 49.5
+-475.0000  275.0000  44.3798  0.13815797 -0.07998619 0.98717505  1741.5249 Square 49.5
+-475.0000  325.0000  48.7994  0.13798298 -0.09440941 0.98592472  1745.9748 Square 49.5
+-475.0000  375.0000  53.9555  0.13777967 -0.10877342 0.98447199  1751.1699 Square 49.5
+-475.0000  425.0000  59.8483  0.13754841 -0.12306963 0.98281957  1757.1121 Square 49.5
+-475.0000  475.0000  66.4776  0.13728962 -0.13728962 0.98097050  1763.8031 Square 49.5
+-475.0000  525.0000  73.8435  0.13700379 -0.15142525 0.97892817  1771.2452 Square 49.5
+-475.0000  575.0000  81.9461  0.13669143 -0.16546858 0.97669627  1779.4406 Square 49.5
+-475.0000  625.0000  90.7852  0.13635310 -0.17941198 0.97427880  1788.3922 Square 49.5
+-475.0000  675.0000 100.3609  0.13598940 -0.19324809 0.97168002  1798.1027 Square 49.5
+-475.0000  725.0000 110.6732  0.13560095 -0.20696987 0.96890446  1808.5752 Square 49.5
+-425.0000 -775.0000 115.0928  0.12117912 0.22097369 0.96772220   1813.0683 Square 49.5
+-425.0000 -725.0000 104.0439  0.12155025 0.20735043 0.97068601   1801.8411 Square 49.5
+-425.0000 -675.0000  93.7316  0.12189974 0.19360546 0.97347695   1791.3786 Square 49.5
+-425.0000 -625.0000  84.1559  0.12222697 0.17974555 0.97609021   1781.6775 Square 49.5
+-425.0000 -575.0000  75.3167  0.12253139 0.16577776 0.97852123   1772.7345 Square 49.5
+-425.0000 -525.0000  67.2142  0.12281244 0.15170948 0.98076569   1764.5469 Square 49.5
+-425.0000 -475.0000  59.8483  0.12306963 0.13754841 0.98281957   1757.1121 Square 49.5
+-425.0000 -425.0000  53.2189  0.12330248 0.12330248 0.98467913   1750.4275 Square 49.5
+-425.0000 -375.0000  47.3262  0.12351058 0.10897992 0.98634097   1744.4911 Square 49.5
+-425.0000 -325.0000  42.1700  0.12369353 0.09458917 0.98780200   1739.3010 Square 49.5
+-425.0000 -275.0000  37.7504  0.12385100 0.08013888 0.98905950   1734.8554 Square 49.5
+-425.0000 -225.0000  34.0675  0.12398268 0.06563789 0.99011109   1731.1530 Square 49.5
+-425.0000 -175.0000  31.1211  0.12408833 0.05109519 0.99095478   1728.1924 Square 49.5
+-425.0000 -125.0000  28.9113  0.12416774 0.03651992 0.99158896   1725.9729 Square 49.5
+-425.0000  -75.0000  27.4381  0.12422077 0.02192131 0.99201243   1724.4936 Square 49.5
+-425.0000  -25.0000  26.7015  0.12424731 0.00730867 0.99222436   1723.7540 Square 49.5
+-425.0000   25.0000  26.7015  0.12424731 -0.00730867 0.99222436  1723.7540 Square 49.5
+-425.0000   75.0000  27.4381  0.12422077 -0.02192131 0.99201243  1724.4936 Square 49.5
+-425.0000  125.0000  28.9113  0.12416774 -0.03651992 0.99158896  1725.9729 Square 49.5
+-425.0000  175.0000  31.1211  0.12408833 -0.05109519 0.99095478  1728.1924 Square 49.5
+-425.0000  225.0000  34.0675  0.12398268 -0.06563789 0.99011109  1731.1530 Square 49.5
+-425.0000  275.0000  37.7504  0.12385100 -0.08013888 0.98905950  1734.8554 Square 49.5
+-425.0000  325.0000  42.1700  0.12369353 -0.09458917 0.98780200  1739.3010 Square 49.5
+-425.0000  375.0000  47.3262  0.12351058 -0.10897992 0.98634097  1744.4911 Square 49.5
+-425.0000  425.0000  53.2189  0.12330248 -0.12330248 0.98467913  1750.4275 Square 49.5
+-425.0000  475.0000  59.8483  0.12306963 -0.13754841 0.98281957  1757.1121 Square 49.5
+-425.0000  525.0000  67.2142  0.12281244 -0.15170948 0.98076569  1764.5469 Square 49.5
+-425.0000  575.0000  75.3167  0.12253139 -0.16577776 0.97852123  1772.7345 Square 49.5
+-425.0000  625.0000  84.1559  0.12222697 -0.17974555 0.97609021  1781.6775 Square 49.5
+-425.0000  675.0000  93.7316  0.12189974 -0.19360546 0.97347695  1791.3786 Square 49.5
+-425.0000  725.0000 104.0439  0.12155025 -0.20735043 0.97068601  1801.8411 Square 49.5
+-425.0000  775.0000 115.0928  0.12117912 -0.22097369 0.96772220  1813.0683 Square 49.5
+-375.0000 -825.0000 120.9856  0.10674932 0.23484851 0.96615255   1819.0634 Square 49.5
+-375.0000 -775.0000 109.2001  0.10709703 0.22133386 0.96929951   1807.0782 Square 49.5
+-375.0000 -725.0000  98.1511  0.10742611 0.20769047 0.97227789   1795.8606 Square 49.5
+-375.0000 -675.0000  87.8388  0.10773600 0.19392480 0.97508263   1785.4071 Square 49.5
+-375.0000 -625.0000  78.2631  0.10802617 0.18004362 0.97770887   1775.7142 Square 49.5
+-375.0000 -575.0000  69.4240  0.10829611 0.16605404 0.98015203   1766.7790 Square 49.5
+-375.0000 -525.0000  61.3214  0.10854535 0.15196349 0.98240776   1758.5984 Square 49.5
+-375.0000 -475.0000  53.9555  0.10877342 0.13777967 0.98447199   1751.1699 Square 49.5
+-375.0000 -425.0000  47.3262  0.10897992 0.12351058 0.98634097   1744.4911 Square 49.5
+-375.0000 -375.0000  41.4334  0.10916447 0.10916447 0.98801125   1738.5599 Square 49.5
+-375.0000 -325.0000  36.2773  0.10932672 0.09474983 0.98947973   1733.3742 Square 49.5
+-375.0000 -275.0000  31.8577  0.10946637 0.08027534 0.99074365   1728.9324 Square 49.5
+-375.0000 -225.0000  28.1747  0.10958316 0.06574989 0.99180063   1725.2332 Square 49.5
+-375.0000 -175.0000  25.2283  0.10967685 0.05118253 0.99264865   1722.2752 Square 49.5
+-375.0000 -125.0000  23.0186  0.10974728 0.03658243 0.99328609   1720.0576 Square 49.5
+-375.0000  -75.0000  21.5454  0.10979431 0.02195886 0.99371174   1718.5796 Square 49.5
+-375.0000  -25.0000  20.8088  0.10981785 0.00732119 0.99392477   1717.8407 Square 49.5
+-375.0000   25.0000  20.8088  0.10981785 -0.00732119 0.99392477  1717.8407 Square 49.5
+-375.0000   75.0000  21.5454  0.10979431 -0.02195886 0.99371174  1718.5796 Square 49.5
+-375.0000  125.0000  23.0186  0.10974728 -0.03658243 0.99328609  1720.0576 Square 49.5
+-375.0000  175.0000  25.2283  0.10967685 -0.05118253 0.99264865  1722.2752 Square 49.5
+-375.0000  225.0000  28.1747  0.10958316 -0.06574989 0.99180063  1725.2332 Square 49.5
+-375.0000  275.0000  31.8577  0.10946637 -0.08027534 0.99074365  1728.9324 Square 49.5
+-375.0000  325.0000  36.2773  0.10932672 -0.09474983 0.98947973  1733.3742 Square 49.5
+-375.0000  375.0000  41.4334  0.10916447 -0.10916447 0.98801125  1738.5599 Square 49.5
+-375.0000  425.0000  47.3262  0.10897992 -0.12351058 0.98634097  1744.4911 Square 49.5
+-375.0000  475.0000  53.9555  0.10877342 -0.13777967 0.98447199  1751.1699 Square 49.5
+-375.0000  525.0000  61.3214  0.10854535 -0.15196349 0.98240776  1758.5984 Square 49.5
+-375.0000  575.0000  69.4240  0.10829611 -0.16605404 0.98015203  1766.7790 Square 49.5
+-375.0000  625.0000  78.2631  0.10802617 -0.18004362 0.97770887  1775.7142 Square 49.5
+-375.0000  675.0000  87.8388  0.10773600 -0.19392480 0.97508263  1785.4071 Square 49.5
+-375.0000  725.0000  98.1511  0.10742611 -0.20769047 0.97227789  1795.8606 Square 49.5
+-375.0000  775.0000 109.2001  0.10709703 -0.22133386 0.96929951  1807.0782 Square 49.5
+-375.0000  825.0000 120.9856  0.10674932 -0.23484851 0.96615255  1819.0634 Square 49.5
+-325.0000 -825.0000 115.8294  0.09264756 0.23518226 0.96752557   1813.8174 Square 49.5
+-325.0000 -775.0000 104.0439  0.09295019 0.22165046 0.97068601   1801.8411 Square 49.5
+-325.0000 -725.0000  92.9950  0.09323662 0.20798939 0.97367723   1790.6319 Square 49.5
+-325.0000 -675.0000  82.6827  0.09350636 0.19420552 0.97649413   1780.1862 Square 49.5
+-325.0000 -625.0000  73.1070  0.09375894 0.18030565 0.97913183   1770.5006 Square 49.5
+-325.0000 -575.0000  64.2678  0.09399392 0.16629693 0.98158569   1761.5720 Square 49.5
+-325.0000 -525.0000  56.1653  0.09421087 0.15218679 0.98385136   1753.3976 Square 49.5
+-325.0000 -475.0000  48.7994  0.09440941 0.13798298 0.98592472   1745.9748 Square 49.5
+-325.0000 -425.0000  42.1700  0.09458917 0.12369353 0.98780200   1739.3010 Square 49.5
+-325.0000 -375.0000  36.2773  0.09474983 0.10932672 0.98947973   1733.3742 Square 49.5
+-325.0000 -325.0000  31.1211  0.09489107 0.09489107 0.99095478   1728.1924 Square 49.5
+-325.0000 -275.0000  26.7015  0.09501265 0.08039532 0.99222436   1723.7540 Square 49.5
+-325.0000 -225.0000  23.0186  0.09511431 0.06584837 0.99328609   1720.0576 Square 49.5
+-325.0000 -175.0000  20.0722  0.09519588 0.05125932 0.99413793   1717.1019 Square 49.5
+-325.0000 -125.0000  17.8624  0.09525720 0.03663738 0.99477825   1714.8859 Square 49.5
+-325.0000  -75.0000  16.3892  0.09529814 0.02199188 0.99520582   1713.4090 Square 49.5
+-325.0000  -25.0000  15.6526  0.09531863 0.00733220 0.99541981   1712.6707 Square 49.5
+-325.0000   25.0000  15.6526  0.09531863 -0.00733220 0.99541981  1712.6707 Square 49.5
+-325.0000   75.0000  16.3892  0.09529814 -0.02199188 0.99520582  1713.4090 Square 49.5
+-325.0000  125.0000  17.8624  0.09525720 -0.03663738 0.99477825  1714.8859 Square 49.5
+-325.0000  175.0000  20.0722  0.09519588 -0.05125932 0.99413793  1717.1019 Square 49.5
+-325.0000  225.0000  23.0186  0.09511431 -0.06584837 0.99328609  1720.0576 Square 49.5
+-325.0000  275.0000  26.7015  0.09501265 -0.08039532 0.99222436  1723.7540 Square 49.5
+-325.0000  325.0000  31.1211  0.09489107 -0.09489107 0.99095478  1728.1924 Square 49.5
+-325.0000  375.0000  36.2773  0.09474983 -0.10932672 0.98947973  1733.3742 Square 49.5
+-325.0000  425.0000  42.1700  0.09458917 -0.12369353 0.98780200  1739.3010 Square 49.5
+-325.0000  475.0000  48.7994  0.09440941 -0.13798298 0.98592472  1745.9748 Square 49.5
+-325.0000  525.0000  56.1653  0.09421087 -0.15218679 0.98385136  1753.3976 Square 49.5
+-325.0000  575.0000  64.2678  0.09399392 -0.16629693 0.98158569  1761.5720 Square 49.5
+-325.0000  625.0000  73.1070  0.09375894 -0.18030565 0.97913183  1770.5006 Square 49.5
+-325.0000  675.0000  82.6827  0.09350636 -0.19420552 0.97649413  1780.1862 Square 49.5
+-325.0000  725.0000  92.9950  0.09323662 -0.20798939 0.97367723  1790.6319 Square 49.5
+-325.0000  775.0000 104.0439  0.09295019 -0.22165046 0.97068601  1801.8411 Square 49.5
+-325.0000  825.0000 115.8294  0.09264756 -0.23518226 0.96752557  1813.8174 Square 49.5
+-275.0000 -825.0000 111.4098  0.07848982 0.23546947 0.96870712   1809.3239 Square 49.5
+-275.0000 -775.0000  99.6243  0.07874684 0.22192291 0.97187919   1797.3553 Square 49.5
+-275.0000 -725.0000  88.5754  0.07899010 0.20824663 0.97488148   1786.1532 Square 49.5
+-275.0000 -675.0000  78.2631  0.07921919 0.19444711 0.97770887   1775.7142 Square 49.5
+-275.0000 -625.0000  68.6874  0.07943371 0.18053117 0.98035646   1766.0349 Square 49.5
+-275.0000 -575.0000  59.8483  0.07963329 0.16650597 0.98281957   1757.1121 Square 49.5
+-275.0000 -525.0000  51.7457  0.07981756 0.15237898 0.98509380   1748.9429 Square 49.5
+-275.0000 -475.0000  44.3798  0.07998619 0.13815797 0.98717505   1741.5249 Square 49.5
+-275.0000 -425.0000  37.7504  0.08013888 0.12385100 0.98905950   1734.8554 Square 49.5
+-275.0000 -375.0000  31.8577  0.08027534 0.10946637 0.99074365   1728.9324 Square 49.5
+-275.0000 -325.0000  26.7015  0.08039532 0.09501265 0.99222436   1723.7540 Square 49.5
+-275.0000 -275.0000  22.2820  0.08049858 0.08049858 0.99349885   1719.3185 Square 49.5
+-275.0000 -225.0000  18.5990  0.08058494 0.06593313 0.99456467   1715.6245 Square 49.5
+-275.0000 -175.0000  15.6526  0.08065423 0.05132542 0.99541981   1712.6707 Square 49.5
+-275.0000 -125.0000  13.4428  0.08070631 0.03668469 0.99606261   1710.4562 Square 49.5
+-275.0000  -75.0000  11.9697  0.08074109 0.02202030 0.99649184   1708.9802 Square 49.5
+-275.0000  -25.0000  11.2331  0.08075849 0.00734168 0.99670666   1708.2424 Square 49.5
+-275.0000   25.0000  11.2331  0.08075849 -0.00734168 0.99670666  1708.2424 Square 49.5
+-275.0000   75.0000  11.9697  0.08074109 -0.02202030 0.99649184  1708.9802 Square 49.5
+-275.0000  125.0000  13.4428  0.08070631 -0.03668469 0.99606261  1710.4562 Square 49.5
+-275.0000  175.0000  15.6526  0.08065423 -0.05132542 0.99541981  1712.6707 Square 49.5
+-275.0000  225.0000  18.5990  0.08058494 -0.06593313 0.99456467  1715.6245 Square 49.5
+-275.0000  275.0000  22.2820  0.08049858 -0.08049858 0.99349885  1719.3185 Square 49.5
+-275.0000  325.0000  26.7015  0.08039532 -0.09501265 0.99222436  1723.7540 Square 49.5
+-275.0000  375.0000  31.8577  0.08027534 -0.10946637 0.99074365  1728.9324 Square 49.5
+-275.0000  425.0000  37.7504  0.08013888 -0.12385100 0.98905950  1734.8554 Square 49.5
+-275.0000  475.0000  44.3798  0.07998619 -0.13815797 0.98717505  1741.5249 Square 49.5
+-275.0000  525.0000  51.7457  0.07981756 -0.15237898 0.98509380  1748.9429 Square 49.5
+-275.0000  575.0000  59.8483  0.07963329 -0.16650597 0.98281957  1757.1121 Square 49.5
+-275.0000  625.0000  68.6874  0.07943371 -0.18053117 0.98035646  1766.0349 Square 49.5
+-275.0000  675.0000  78.2631  0.07921919 -0.19444711 0.97770887  1775.7142 Square 49.5
+-275.0000  725.0000  88.5754  0.07899010 -0.20824663 0.97488148  1786.1532 Square 49.5
+-275.0000  775.0000  99.6243  0.07874684 -0.22192291 0.97187919  1797.3553 Square 49.5
+-275.0000  825.0000 111.4098  0.07848982 -0.23546947 0.96870712  1809.3239 Square 49.5
+-225.0000 -825.0000 107.7269  0.06428444 0.23570961 0.96969505   1805.5815 Square 49.5
+-225.0000 -775.0000  95.9414  0.06449537 0.22215073 0.97287687   1793.6193 Square 49.5
+-225.0000 -725.0000  84.8925  0.06469502 0.20846173 0.97588845   1782.4232 Square 49.5
+-225.0000 -675.0000  74.5801  0.06488304 0.19464912 0.97872463   1771.9898 Square 49.5
+-225.0000 -625.0000  65.0044  0.06505911 0.18071974 0.98138050   1762.3156 Square 49.5
+-225.0000 -575.0000  56.1653  0.06522291 0.16668077 0.98385136   1753.3976 Square 49.5
+-225.0000 -525.0000  48.0628  0.06537415 0.15253969 0.98613278   1745.2329 Square 49.5
+-225.0000 -475.0000  40.6968  0.06551256 0.13830430 0.98822064   1737.8188 Square 49.5
+-225.0000 -425.0000  34.0675  0.06563789 0.12398268 0.99011109   1731.1530 Square 49.5
+-225.0000 -375.0000  28.1747  0.06574989 0.10958316 0.99180063   1725.2332 Square 49.5
+-225.0000 -325.0000  23.0186  0.06584837 0.09511431 0.99328609   1720.0576 Square 49.5
+-225.0000 -275.0000  18.5990  0.06593313 0.08058494 0.99456467   1715.6245 Square 49.5
+-225.0000 -225.0000  14.9160  0.06600402 0.06600402 0.99563394   1711.9324 Square 49.5
+-225.0000 -175.0000  11.9697  0.06606089 0.05138069 0.99649184   1708.9802 Square 49.5
+-225.0000 -125.0000   9.7599  0.06610364 0.03672425 0.99713672   1706.7669 Square 49.5
+-225.0000  -75.0000   8.2867  0.06613219 0.02204406 0.99756734   1705.2917 Square 49.5
+-225.0000  -25.0000   7.5501  0.06614648 0.00734961 0.99778286   1704.5543 Square 49.5
+-225.0000   25.0000   7.5501  0.06614648 -0.00734961 0.99778286  1704.5543 Square 49.5
+-225.0000   75.0000   8.2867  0.06613219 -0.02204406 0.99756734  1705.2917 Square 49.5
+-225.0000  125.0000   9.7599  0.06610364 -0.03672425 0.99713672  1706.7669 Square 49.5
+-225.0000  175.0000  11.9697  0.06606089 -0.05138069 0.99649184  1708.9802 Square 49.5
+-225.0000  225.0000  14.9160  0.06600402 -0.06600402 0.99563394  1711.9324 Square 49.5
+-225.0000  275.0000  18.5990  0.06593313 -0.08058494 0.99456467  1715.6245 Square 49.5
+-225.0000  325.0000  23.0186  0.06584837 -0.09511431 0.99328609  1720.0576 Square 49.5
+-225.0000  375.0000  28.1747  0.06574989 -0.10958316 0.99180063  1725.2332 Square 49.5
+-225.0000  425.0000  34.0675  0.06563789 -0.12398268 0.99011109  1731.1530 Square 49.5
+-225.0000  475.0000  40.6968  0.06551256 -0.13830430 0.98822064  1737.8188 Square 49.5
+-225.0000  525.0000  48.0628  0.06537415 -0.15253969 0.98613278  1745.2329 Square 49.5
+-225.0000  575.0000  56.1653  0.06522291 -0.16668077 0.98385136  1753.3976 Square 49.5
+-225.0000  625.0000  65.0044  0.06505911 -0.18071974 0.98138050  1762.3156 Square 49.5
+-225.0000  675.0000  74.5801  0.06488304 -0.19464912 0.97872463  1771.9898 Square 49.5
+-225.0000  725.0000  84.8925  0.06469502 -0.20846173 0.97588845  1782.4232 Square 49.5
+-225.0000  775.0000  95.9414  0.06449537 -0.22215073 0.97287687  1793.6193 Square 49.5
+-225.0000  825.0000 107.7269  0.06428444 -0.23570961 0.96969505  1805.5815 Square 49.5
+-175.0000 -825.0000 104.7805  0.05003987 0.23590225 0.97048758   1802.5890 Square 49.5
+-175.0000 -775.0000  92.9950  0.05020434 0.22233349 0.97367723   1790.6319 Square 49.5
+-175.0000 -725.0000  81.9461  0.05036000 0.20863429 0.97669627   1779.4406 Square 49.5
+-175.0000 -675.0000  71.6338  0.05050660 0.19481119 0.97953953   1769.0117 Square 49.5
+-175.0000 -625.0000  62.0580  0.05064389 0.18087103 0.98220205   1759.3417 Square 49.5
+-175.0000 -575.0000  53.2189  0.05077161 0.16682101 0.98467913   1750.4275 Square 49.5
+-175.0000 -525.0000  45.1164  0.05088954 0.15266863 0.98696633   1742.2663 Square 49.5
+-175.0000 -475.0000  37.7504  0.05099747 0.13842170 0.98905950   1734.8554 Square 49.5
+-175.0000 -425.0000  31.1211  0.05109519 0.12408833 0.99095478   1728.1924 Square 49.5
+-175.0000 -375.0000  25.2283  0.05118253 0.10967685 0.99264865   1722.2752 Square 49.5
+-175.0000 -325.0000  20.0722  0.05125932 0.09519588 0.99413793   1717.1019 Square 49.5
+-175.0000 -275.0000  15.6526  0.05132542 0.08065423 0.99541981   1712.6707 Square 49.5
+-175.0000 -225.0000  11.9697  0.05138069 0.06606089 0.99649184   1708.9802 Square 49.5
+-175.0000 -175.0000   9.0233  0.05142504 0.05142504 0.99735196   1706.0293 Square 49.5
+-175.0000 -125.0000   6.8135  0.05145838 0.03675599 0.99799851   1703.8169 Square 49.5
+-175.0000  -75.0000   5.3403  0.05148064 0.02206313 0.99843025   1702.3424 Square 49.5
+-175.0000  -25.0000   4.6037  0.05149178 0.00735597 0.99864633   1701.6053 Square 49.5
+-175.0000   25.0000   4.6037  0.05149178 -0.00735597 0.99864633  1701.6053 Square 49.5
+-175.0000   75.0000   5.3403  0.05148064 -0.02206313 0.99843025  1702.3424 Square 49.5
+-175.0000  125.0000   6.8135  0.05145838 -0.03675599 0.99799851  1703.8169 Square 49.5
+-175.0000  175.0000   9.0233  0.05142504 -0.05142504 0.99735196  1706.0293 Square 49.5
+-175.0000  225.0000  11.9697  0.05138069 -0.06606089 0.99649184  1708.9802 Square 49.5
+-175.0000  275.0000  15.6526  0.05132542 -0.08065423 0.99541981  1712.6707 Square 49.5
+-175.0000  325.0000  20.0722  0.05125932 -0.09519588 0.99413793  1717.1019 Square 49.5
+-175.0000  375.0000  25.2283  0.05118253 -0.10967685 0.99264865  1722.2752 Square 49.5
+-175.0000  425.0000  31.1211  0.05109519 -0.12408833 0.99095478  1728.1924 Square 49.5
+-175.0000  475.0000  37.7504  0.05099747 -0.13842170 0.98905950  1734.8554 Square 49.5
+-175.0000  525.0000  45.1164  0.05088954 -0.15266863 0.98696633  1742.2663 Square 49.5
+-175.0000  575.0000  53.2189  0.05077161 -0.16682101 0.98467913  1750.4275 Square 49.5
+-175.0000  625.0000  62.0580  0.05064389 -0.18087103 0.98220205  1759.3417 Square 49.5
+-175.0000  675.0000  71.6338  0.05050660 -0.19481119 0.97953953  1769.0117 Square 49.5
+-175.0000  725.0000  81.9461  0.05036000 -0.20863429 0.97669627  1779.4406 Square 49.5
+-175.0000  775.0000  92.9950  0.05020434 -0.22233349 0.97367723  1790.6319 Square 49.5
+-175.0000  825.0000 104.7805  0.05003987 -0.23590225 0.97048758  1802.5890 Square 49.5
+-125.0000 -825.0000 102.5707  0.03576470 0.23604705 0.97108325   1800.3455 Square 49.5
+-125.0000 -775.0000  90.7852  0.03588240 0.22247085 0.97427880   1788.3922 Square 49.5
+-125.0000 -725.0000  79.7363  0.03599379 0.20876400 0.97730345   1777.2046 Square 49.5
+-125.0000 -675.0000  69.4240  0.03609870 0.19493301 0.98015203   1766.7790 Square 49.5
+-125.0000 -625.0000  59.8483  0.03619695 0.18098475 0.98281957   1757.1121 Square 49.5
+-125.0000 -575.0000  51.0091  0.03628835 0.16692642 0.98530134   1748.2008 Square 49.5
+-125.0000 -525.0000  42.9066  0.03637275 0.15276555 0.98759289   1740.0422 Square 49.5
+-125.0000 -475.0000  35.5407  0.03644999 0.13850995 0.98969005   1732.6337 Square 49.5
+-125.0000 -425.0000  28.9113  0.03651992 0.12416774 0.99158896   1725.9729 Square 49.5
+-125.0000 -375.0000  23.0186  0.03658243 0.10974728 0.99328609   1720.0576 Square 49.5
+-125.0000 -325.0000  17.8624  0.03663738 0.09525720 0.99477825   1714.8859 Square 49.5
+-125.0000 -275.0000  13.4428  0.03668469 0.08070631 0.99606261   1710.4562 Square 49.5
+-125.0000 -225.0000   9.7599  0.03672425 0.06610364 0.99713672   1706.7669 Square 49.5
+-125.0000 -175.0000   6.8135  0.03675599 0.05145838 0.99799851   1703.8169 Square 49.5
+-125.0000 -125.0000   4.6037  0.03677984 0.03677984 0.99864633   1701.6053 Square 49.5
+-125.0000  -75.0000   3.1305  0.03679578 0.02207747 0.99907890   1700.1312 Square 49.5
+-125.0000   75.0000   3.1305  0.03679578 -0.02207747 0.99907890  1700.1312 Square 49.5
+-125.0000  125.0000   4.6037  0.03677984 -0.03677984 0.99864633  1701.6053 Square 49.5
+-125.0000  175.0000   6.8135  0.03675599 -0.05145838 0.99799851  1703.8169 Square 49.5
+-125.0000  225.0000   9.7599  0.03672425 -0.06610364 0.99713672  1706.7669 Square 49.5
+-125.0000  275.0000  13.4428  0.03668469 -0.08070631 0.99606261  1710.4562 Square 49.5
+-125.0000  325.0000  17.8624  0.03663738 -0.09525720 0.99477825  1714.8859 Square 49.5
+-125.0000  375.0000  23.0186  0.03658243 -0.10974728 0.99328609  1720.0576 Square 49.5
+-125.0000  425.0000  28.9113  0.03651992 -0.12416774 0.99158896  1725.9729 Square 49.5
+-125.0000  475.0000  35.5407  0.03644999 -0.13850995 0.98969005  1732.6337 Square 49.5
+-125.0000  525.0000  42.9066  0.03637275 -0.15276555 0.98759289  1740.0422 Square 49.5
+-125.0000  575.0000  51.0091  0.03628835 -0.16692642 0.98530134  1748.2008 Square 49.5
+-125.0000  625.0000  59.8483  0.03619695 -0.18098475 0.98281957  1757.1121 Square 49.5
+-125.0000  675.0000  69.4240  0.03609870 -0.19493301 0.98015203  1766.7790 Square 49.5
+-125.0000  725.0000  79.7363  0.03599379 -0.20876400 0.97730345  1777.2046 Square 49.5
+-125.0000  775.0000  90.7852  0.03588240 -0.22247085 0.97427880  1788.3922 Square 49.5
+-125.0000  825.0000 102.5707  0.03576470 -0.23604705 0.97108325  1800.3455 Square 49.5
+ -75.0000 -825.0000 101.0975  0.02146761 0.23614373 0.97148097   1798.8502 Square 49.5
+ -75.0000 -775.0000  89.3120  0.02153831 0.22256257 0.97468046   1786.8995 Square 49.5
+ -75.0000 -725.0000  78.2631  0.02160523 0.20885060 0.97770887   1775.7142 Square 49.5
+ -75.0000 -675.0000  67.9508  0.02166826 0.19501434 0.98056101   1765.2909 Square 49.5
+ -75.0000 -625.0000  58.3751  0.02172728 0.18106068 0.98323189   1755.6261 Square 49.5
+ -75.0000 -575.0000  49.5359  0.02178219 0.16699681 0.98571680   1746.7167 Square 49.5
+ -75.0000 -525.0000  41.4334  0.02183289 0.15283026 0.98801125   1738.5599 Square 49.5
+ -75.0000 -475.0000  34.0675  0.02187930 0.13856888 0.99011109   1731.1530 Square 49.5
+ -75.0000 -425.0000  27.4381  0.02192131 0.12422077 0.99201243   1724.4936 Square 49.5
+ -75.0000 -375.0000  21.5454  0.02195886 0.10979431 0.99371174   1718.5796 Square 49.5
+ -75.0000 -325.0000  16.3892  0.02199188 0.09529814 0.99520582   1713.4090 Square 49.5
+ -75.0000 -275.0000  11.9697  0.02202030 0.08074109 0.99649184   1708.9802 Square 49.5
+ -75.0000 -225.0000   8.2867  0.02204406 0.06613219 0.99756734   1705.2917 Square 49.5
+ -75.0000 -175.0000   5.3403  0.02206313 0.05148064 0.99843025   1702.3424 Square 49.5
+ -75.0000 -125.0000   3.1305  0.02207747 0.03679578 0.99907890   1700.1312 Square 49.5
+ -75.0000  -75.0000   1.6573  0.02208704 0.02208704 0.99951204   1698.6575 Square 49.5
+ -75.0000   75.0000   1.6573  0.02208704 -0.02208704 0.99951204  1698.6575 Square 49.5
+ -75.0000  125.0000   3.1305  0.02207747 -0.03679578 0.99907890  1700.1312 Square 49.5
+ -75.0000  175.0000   5.3403  0.02206313 -0.05148064 0.99843025  1702.3424 Square 49.5
+ -75.0000  225.0000   8.2867  0.02204406 -0.06613219 0.99756734  1705.2917 Square 49.5
+ -75.0000  275.0000  11.9697  0.02202030 -0.08074109 0.99649184  1708.9802 Square 49.5
+ -75.0000  325.0000  16.3892  0.02199188 -0.09529814 0.99520582  1713.4090 Square 49.5
+ -75.0000  375.0000  21.5454  0.02195886 -0.10979431 0.99371174  1718.5796 Square 49.5
+ -75.0000  425.0000  27.4381  0.02192131 -0.12422077 0.99201243  1724.4936 Square 49.5
+ -75.0000  475.0000  34.0675  0.02187930 -0.13856888 0.99011109  1731.1530 Square 49.5
+ -75.0000  525.0000  41.4334  0.02183289 -0.15283026 0.98801125  1738.5599 Square 49.5
+ -75.0000  575.0000  49.5359  0.02178219 -0.16699681 0.98571680  1746.7167 Square 49.5
+ -75.0000  625.0000  58.3751  0.02172728 -0.18106068 0.98323189  1755.6261 Square 49.5
+ -75.0000  675.0000  67.9508  0.02166826 -0.19501434 0.98056101  1765.2909 Square 49.5
+ -75.0000  725.0000  78.2631  0.02160523 -0.20885060 0.97770887  1775.7142 Square 49.5
+ -75.0000  775.0000  89.3120  0.02153831 -0.22256257 0.97468046  1786.8995 Square 49.5
+ -75.0000  825.0000 101.0975  0.02146761 -0.23614373 0.97148097  1798.8502 Square 49.5
+ -25.0000 -825.0000 100.3609  0.00715734 0.23619211 0.97168002   1798.1027 Square 49.5
+ -25.0000 -775.0000  88.5754  0.00718092 0.22260847 0.97488148   1786.1532 Square 49.5
+ -25.0000 -725.0000  77.5265  0.00720324 0.20889394 0.97791177   1774.9692 Square 49.5
+ -25.0000 -675.0000  67.2142  0.00722426 0.19505505 0.98076569   1764.5469 Square 49.5
+ -25.0000 -625.0000  57.6385  0.00724395 0.18109868 0.98343825   1754.8832 Square 49.5
+ -25.0000 -575.0000  48.7994  0.00726226 0.16703203 0.98592472   1745.9748 Square 49.5
+ -25.0000 -525.0000  40.6968  0.00727917 0.15286265 0.98822064   1737.8188 Square 49.5
+ -25.0000 -475.0000  33.3309  0.00729465 0.13859837 0.99032181   1730.4127 Square 49.5
+ -25.0000 -425.0000  26.7015  0.00730867 0.12424731 0.99222436   1723.7540 Square 49.5
+ -25.0000 -375.0000  20.8088  0.00732119 0.10981785 0.99392477   1717.8407 Square 49.5
+ -25.0000 -325.0000  15.6526  0.00733220 0.09531863 0.99541981   1712.6707 Square 49.5
+ -25.0000 -275.0000  11.2331  0.00734168 0.08075849 0.99670666   1708.2424 Square 49.5
+ -25.0000 -225.0000   7.5501  0.00734961 0.06614648 0.99778286   1704.5543 Square 49.5
+ -25.0000 -175.0000   4.6037  0.00735597 0.05149178 0.99864633   1701.6053 Square 49.5
+ -25.0000 -125.0000   2.3939  0.00736075 0.03680375 0.99929540   1699.3944 Square 49.5
+ -25.0000  -75.0000   0.9207  0.00736394 0.02209183 0.99972882   1697.9208 Square 49.5
+ -25.0000   75.0000   0.9207  0.00736394 -0.02209183 0.99972882  1697.9208 Square 49.5
+ -25.0000  125.0000   2.3939  0.00736075 -0.03680375 0.99929540  1699.3944 Square 49.5
+ -25.0000  175.0000   4.6037  0.00735597 -0.05149178 0.99864633  1701.6053 Square 49.5
+ -25.0000  225.0000   7.5501  0.00734961 -0.06614648 0.99778286  1704.5543 Square 49.5
+ -25.0000  275.0000  11.2331  0.00734168 -0.08075849 0.99670666  1708.2424 Square 49.5
+ -25.0000  325.0000  15.6526  0.00733220 -0.09531863 0.99541981  1712.6707 Square 49.5
+ -25.0000  375.0000  20.8088  0.00732119 -0.10981785 0.99392477  1717.8407 Square 49.5
+ -25.0000  425.0000  26.7015  0.00730867 -0.12424731 0.99222436  1723.7540 Square 49.5
+ -25.0000  475.0000  33.3309  0.00729465 -0.13859837 0.99032181  1730.4127 Square 49.5
+ -25.0000  525.0000  40.6968  0.00727917 -0.15286265 0.98822064  1737.8188 Square 49.5
+ -25.0000  575.0000  48.7994  0.00726226 -0.16703203 0.98592472  1745.9748 Square 49.5
+ -25.0000  625.0000  57.6385  0.00724395 -0.18109868 0.98343825  1754.8832 Square 49.5
+ -25.0000  675.0000  67.2142  0.00722426 -0.19505505 0.98076569  1764.5469 Square 49.5
+ -25.0000  725.0000  77.5265  0.00720324 -0.20889394 0.97791177  1774.9692 Square 49.5
+ -25.0000  775.0000  88.5754  0.00718092 -0.22260847 0.97488148  1786.1532 Square 49.5
+ -25.0000  825.0000 100.3609  0.00715734 -0.23619211 0.97168002  1798.1027 Square 49.5
+  25.0000 -825.0000 100.3609  -0.00715734 0.23619211 0.97168002  1798.1027 Square 49.5
+  25.0000 -775.0000  88.5754  -0.00718092 0.22260847 0.97488148  1786.1532 Square 49.5
+  25.0000 -725.0000  77.5265  -0.00720324 0.20889394 0.97791177  1774.9692 Square 49.5
+  25.0000 -675.0000  67.2142  -0.00722426 0.19505505 0.98076569  1764.5469 Square 49.5
+  25.0000 -625.0000  57.6385  -0.00724395 0.18109868 0.98343825  1754.8832 Square 49.5
+  25.0000 -575.0000  48.7994  -0.00726226 0.16703203 0.98592472  1745.9748 Square 49.5
+  25.0000 -525.0000  40.6968  -0.00727917 0.15286265 0.98822064  1737.8188 Square 49.5
+  25.0000 -475.0000  33.3309  -0.00729465 0.13859837 0.99032181  1730.4127 Square 49.5
+  25.0000 -425.0000  26.7015  -0.00730867 0.12424731 0.99222436  1723.7540 Square 49.5
+  25.0000 -375.0000  20.8088  -0.00732119 0.10981785 0.99392477  1717.8407 Square 49.5
+  25.0000 -325.0000  15.6526  -0.00733220 0.09531863 0.99541981  1712.6707 Square 49.5
+  25.0000 -275.0000  11.2331  -0.00734168 0.08075849 0.99670666  1708.2424 Square 49.5
+  25.0000 -225.0000   7.5501  -0.00734961 0.06614648 0.99778286  1704.5543 Square 49.5
+  25.0000 -175.0000   4.6037  -0.00735597 0.05149178 0.99864633  1701.6053 Square 49.5
+  25.0000 -125.0000   2.3939  -0.00736075 0.03680375 0.99929540  1699.3944 Square 49.5
+  25.0000  -75.0000   0.9207  -0.00736394 0.02209183 0.99972882  1697.9208 Square 49.5
+  25.0000   75.0000   0.9207  -0.00736394 -0.02209183 0.99972882 1697.9208 Square 49.5
+  25.0000  125.0000   2.3939  -0.00736075 -0.03680375 0.99929540 1699.3944 Square 49.5
+  25.0000  175.0000   4.6037  -0.00735597 -0.05149178 0.99864633 1701.6053 Square 49.5
+  25.0000  225.0000   7.5501  -0.00734961 -0.06614648 0.99778286 1704.5543 Square 49.5
+  25.0000  275.0000  11.2331  -0.00734168 -0.08075849 0.99670666 1708.2424 Square 49.5
+  25.0000  325.0000  15.6526  -0.00733220 -0.09531863 0.99541981 1712.6707 Square 49.5
+  25.0000  375.0000  20.8088  -0.00732119 -0.10981785 0.99392477 1717.8407 Square 49.5
+  25.0000  425.0000  26.7015  -0.00730867 -0.12424731 0.99222436 1723.7540 Square 49.5
+  25.0000  475.0000  33.3309  -0.00729465 -0.13859837 0.99032181 1730.4127 Square 49.5
+  25.0000  525.0000  40.6968  -0.00727917 -0.15286265 0.98822064 1737.8188 Square 49.5
+  25.0000  575.0000  48.7994  -0.00726226 -0.16703203 0.98592472 1745.9748 Square 49.5
+  25.0000  625.0000  57.6385  -0.00724395 -0.18109868 0.98343825 1754.8832 Square 49.5
+  25.0000  675.0000  67.2142  -0.00722426 -0.19505505 0.98076569 1764.5469 Square 49.5
+  25.0000  725.0000  77.5265  -0.00720324 -0.20889394 0.97791177 1774.9692 Square 49.5
+  25.0000  775.0000  88.5754  -0.00718092 -0.22260847 0.97488148 1786.1532 Square 49.5
+  25.0000  825.0000 100.3609  -0.00715734 -0.23619211 0.97168002 1798.1027 Square 49.5
+  75.0000 -825.0000 101.0975  -0.02146761 0.23614373 0.97148097  1798.8502 Square 49.5
+  75.0000 -775.0000  89.3120  -0.02153831 0.22256257 0.97468046  1786.8995 Square 49.5
+  75.0000 -725.0000  78.2631  -0.02160523 0.20885060 0.97770887  1775.7142 Square 49.5
+  75.0000 -675.0000  67.9508  -0.02166826 0.19501434 0.98056101  1765.2909 Square 49.5
+  75.0000 -625.0000  58.3751  -0.02172728 0.18106068 0.98323189  1755.6261 Square 49.5
+  75.0000 -575.0000  49.5359  -0.02178219 0.16699681 0.98571680  1746.7167 Square 49.5
+  75.0000 -525.0000  41.4334  -0.02183289 0.15283026 0.98801125  1738.5599 Square 49.5
+  75.0000 -475.0000  34.0675  -0.02187930 0.13856888 0.99011109  1731.1530 Square 49.5
+  75.0000 -425.0000  27.4381  -0.02192131 0.12422077 0.99201243  1724.4936 Square 49.5
+  75.0000 -375.0000  21.5454  -0.02195886 0.10979431 0.99371174  1718.5796 Square 49.5
+  75.0000 -325.0000  16.3892  -0.02199188 0.09529814 0.99520582  1713.4090 Square 49.5
+  75.0000 -275.0000  11.9697  -0.02202030 0.08074109 0.99649184  1708.9802 Square 49.5
+  75.0000 -225.0000   8.2867  -0.02204406 0.06613219 0.99756734  1705.2917 Square 49.5
+  75.0000 -175.0000   5.3403  -0.02206313 0.05148064 0.99843025  1702.3424 Square 49.5
+  75.0000 -125.0000   3.1305  -0.02207747 0.03679578 0.99907890  1700.1312 Square 49.5
+  75.0000  -75.0000   1.6573  -0.02208704 0.02208704 0.99951204  1698.6575 Square 49.5
+  75.0000  -25.0000   0.9207  -0.02209183 0.00736394 0.99972882  1697.9208 Square 49.5
+  75.0000   25.0000   0.9207  -0.02209183 -0.00736394 0.99972882 1697.9208 Square 49.5
+  75.0000   75.0000   1.6573  -0.02208704 -0.02208704 0.99951204 1698.6575 Square 49.5
+  75.0000  125.0000   3.1305  -0.02207747 -0.03679578 0.99907890 1700.1312 Square 49.5
+  75.0000  175.0000   5.3403  -0.02206313 -0.05148064 0.99843025 1702.3424 Square 49.5
+  75.0000  225.0000   8.2867  -0.02204406 -0.06613219 0.99756734 1705.2917 Square 49.5
+  75.0000  275.0000  11.9697  -0.02202030 -0.08074109 0.99649184 1708.9802 Square 49.5
+  75.0000  325.0000  16.3892  -0.02199188 -0.09529814 0.99520582 1713.4090 Square 49.5
+  75.0000  375.0000  21.5454  -0.02195886 -0.10979431 0.99371174 1718.5796 Square 49.5
+  75.0000  425.0000  27.4381  -0.02192131 -0.12422077 0.99201243 1724.4936 Square 49.5
+  75.0000  475.0000  34.0675  -0.02187930 -0.13856888 0.99011109 1731.1530 Square 49.5
+  75.0000  525.0000  41.4334  -0.02183289 -0.15283026 0.98801125 1738.5599 Square 49.5
+  75.0000  575.0000  49.5359  -0.02178219 -0.16699681 0.98571680 1746.7167 Square 49.5
+  75.0000  625.0000  58.3751  -0.02172728 -0.18106068 0.98323189 1755.6261 Square 49.5
+  75.0000  675.0000  67.9508  -0.02166826 -0.19501434 0.98056101 1765.2909 Square 49.5
+  75.0000  725.0000  78.2631  -0.02160523 -0.20885060 0.97770887 1775.7142 Square 49.5
+  75.0000  775.0000  89.3120  -0.02153831 -0.22256257 0.97468046 1786.8995 Square 49.5
+  75.0000  825.0000 101.0975  -0.02146761 -0.23614373 0.97148097 1798.8502 Square 49.5
+ 125.0000 -825.0000 102.5707  -0.03576470 0.23604705 0.97108325  1800.3455 Square 49.5
+ 125.0000 -775.0000  90.7852  -0.03588240 0.22247085 0.97427880  1788.3922 Square 49.5
+ 125.0000 -725.0000  79.7363  -0.03599379 0.20876400 0.97730345  1777.2046 Square 49.5
+ 125.0000 -675.0000  69.4240  -0.03609870 0.19493301 0.98015203  1766.7790 Square 49.5
+ 125.0000 -625.0000  59.8483  -0.03619695 0.18098475 0.98281957  1757.1121 Square 49.5
+ 125.0000 -575.0000  51.0091  -0.03628835 0.16692642 0.98530134  1748.2008 Square 49.5
+ 125.0000 -525.0000  42.9066  -0.03637275 0.15276555 0.98759289  1740.0422 Square 49.5
+ 125.0000 -475.0000  35.5407  -0.03644999 0.13850995 0.98969005  1732.6337 Square 49.5
+ 125.0000 -425.0000  28.9113  -0.03651992 0.12416774 0.99158896  1725.9729 Square 49.5
+ 125.0000 -375.0000  23.0186  -0.03658243 0.10974728 0.99328609  1720.0576 Square 49.5
+ 125.0000 -325.0000  17.8624  -0.03663738 0.09525720 0.99477825  1714.8859 Square 49.5
+ 125.0000 -275.0000  13.4428  -0.03668469 0.08070631 0.99606261  1710.4562 Square 49.5
+ 125.0000 -225.0000   9.7599  -0.03672425 0.06610364 0.99713672  1706.7669 Square 49.5
+ 125.0000 -175.0000   6.8135  -0.03675599 0.05145838 0.99799851  1703.8169 Square 49.5
+ 125.0000 -125.0000   4.6037  -0.03677984 0.03677984 0.99864633  1701.6053 Square 49.5
+ 125.0000  -75.0000   3.1305  -0.03679578 0.02207747 0.99907890  1700.1312 Square 49.5
+ 125.0000  -25.0000   2.3939  -0.03680375 0.00736075 0.99929540  1699.3944 Square 49.5
+ 125.0000   25.0000   2.3939  -0.03680375 -0.00736075 0.99929540 1699.3944 Square 49.5
+ 125.0000   75.0000   3.1305  -0.03679578 -0.02207747 0.99907890 1700.1312 Square 49.5
+ 125.0000  125.0000   4.6037  -0.03677984 -0.03677984 0.99864633 1701.6053 Square 49.5
+ 125.0000  175.0000   6.8135  -0.03675599 -0.05145838 0.99799851 1703.8169 Square 49.5
+ 125.0000  225.0000   9.7599  -0.03672425 -0.06610364 0.99713672 1706.7669 Square 49.5
+ 125.0000  275.0000  13.4428  -0.03668469 -0.08070631 0.99606261 1710.4562 Square 49.5
+ 125.0000  325.0000  17.8624  -0.03663738 -0.09525720 0.99477825 1714.8859 Square 49.5
+ 125.0000  375.0000  23.0186  -0.03658243 -0.10974728 0.99328609 1720.0576 Square 49.5
+ 125.0000  425.0000  28.9113  -0.03651992 -0.12416774 0.99158896 1725.9729 Square 49.5
+ 125.0000  475.0000  35.5407  -0.03644999 -0.13850995 0.98969005 1732.6337 Square 49.5
+ 125.0000  525.0000  42.9066  -0.03637275 -0.15276555 0.98759289 1740.0422 Square 49.5
+ 125.0000  575.0000  51.0091  -0.03628835 -0.16692642 0.98530134 1748.2008 Square 49.5
+ 125.0000  625.0000  59.8483  -0.03619695 -0.18098475 0.98281957 1757.1121 Square 49.5
+ 125.0000  675.0000  69.4240  -0.03609870 -0.19493301 0.98015203 1766.7790 Square 49.5
+ 125.0000  725.0000  79.7363  -0.03599379 -0.20876400 0.97730345 1777.2046 Square 49.5
+ 125.0000  775.0000  90.7852  -0.03588240 -0.22247085 0.97427880 1788.3922 Square 49.5
+ 125.0000  825.0000 102.5707  -0.03576470 -0.23604705 0.97108325 1800.3455 Square 49.5
+ 175.0000 -825.0000 104.7805  -0.05003987 0.23590225 0.97048758  1802.5890 Square 49.5
+ 175.0000 -775.0000  92.9950  -0.05020434 0.22233349 0.97367723  1790.6319 Square 49.5
+ 175.0000 -725.0000  81.9461  -0.05036000 0.20863429 0.97669627  1779.4406 Square 49.5
+ 175.0000 -675.0000  71.6338  -0.05050660 0.19481119 0.97953953  1769.0117 Square 49.5
+ 175.0000 -625.0000  62.0580  -0.05064389 0.18087103 0.98220205  1759.3417 Square 49.5
+ 175.0000 -575.0000  53.2189  -0.05077161 0.16682101 0.98467913  1750.4275 Square 49.5
+ 175.0000 -525.0000  45.1164  -0.05088954 0.15266863 0.98696633  1742.2663 Square 49.5
+ 175.0000 -475.0000  37.7504  -0.05099747 0.13842170 0.98905950  1734.8554 Square 49.5
+ 175.0000 -425.0000  31.1211  -0.05109519 0.12408833 0.99095478  1728.1924 Square 49.5
+ 175.0000 -375.0000  25.2283  -0.05118253 0.10967685 0.99264865  1722.2752 Square 49.5
+ 175.0000 -325.0000  20.0722  -0.05125932 0.09519588 0.99413793  1717.1019 Square 49.5
+ 175.0000 -275.0000  15.6526  -0.05132542 0.08065423 0.99541981  1712.6707 Square 49.5
+ 175.0000 -225.0000  11.9697  -0.05138069 0.06606089 0.99649184  1708.9802 Square 49.5
+ 175.0000 -175.0000   9.0233  -0.05142504 0.05142504 0.99735196  1706.0293 Square 49.5
+ 175.0000 -125.0000   6.8135  -0.05145838 0.03675599 0.99799851  1703.8169 Square 49.5
+ 175.0000  -75.0000   5.3403  -0.05148064 0.02206313 0.99843025  1702.3424 Square 49.5
+ 175.0000  -25.0000   4.6037  -0.05149178 0.00735597 0.99864633  1701.6053 Square 49.5
+ 175.0000   25.0000   4.6037  -0.05149178 -0.00735597 0.99864633 1701.6053 Square 49.5
+ 175.0000   75.0000   5.3403  -0.05148064 -0.02206313 0.99843025 1702.3424 Square 49.5
+ 175.0000  125.0000   6.8135  -0.05145838 -0.03675599 0.99799851 1703.8169 Square 49.5
+ 175.0000  175.0000   9.0233  -0.05142504 -0.05142504 0.99735196 1706.0293 Square 49.5
+ 175.0000  225.0000  11.9697  -0.05138069 -0.06606089 0.99649184 1708.9802 Square 49.5
+ 175.0000  275.0000  15.6526  -0.05132542 -0.08065423 0.99541981 1712.6707 Square 49.5
+ 175.0000  325.0000  20.0722  -0.05125932 -0.09519588 0.99413793 1717.1019 Square 49.5
+ 175.0000  375.0000  25.2283  -0.05118253 -0.10967685 0.99264865 1722.2752 Square 49.5
+ 175.0000  425.0000  31.1211  -0.05109519 -0.12408833 0.99095478 1728.1924 Square 49.5
+ 175.0000  475.0000  37.7504  -0.05099747 -0.13842170 0.98905950 1734.8554 Square 49.5
+ 175.0000  525.0000  45.1164  -0.05088954 -0.15266863 0.98696633 1742.2663 Square 49.5
+ 175.0000  575.0000  53.2189  -0.05077161 -0.16682101 0.98467913 1750.4275 Square 49.5
+ 175.0000  625.0000  62.0580  -0.05064389 -0.18087103 0.98220205 1759.3417 Square 49.5
+ 175.0000  675.0000  71.6338  -0.05050660 -0.19481119 0.97953953 1769.0117 Square 49.5
+ 175.0000  725.0000  81.9461  -0.05036000 -0.20863429 0.97669627 1779.4406 Square 49.5
+ 175.0000  775.0000  92.9950  -0.05020434 -0.22233349 0.97367723 1790.6319 Square 49.5
+ 175.0000  825.0000 104.7805  -0.05003987 -0.23590225 0.97048758 1802.5890 Square 49.5
+ 225.0000 -825.0000 107.7269  -0.06428444 0.23570961 0.96969505  1805.5815 Square 49.5
+ 225.0000 -775.0000  95.9414  -0.06449537 0.22215073 0.97287687  1793.6193 Square 49.5
+ 225.0000 -725.0000  84.8925  -0.06469502 0.20846173 0.97588845  1782.4232 Square 49.5
+ 225.0000 -675.0000  74.5801  -0.06488304 0.19464912 0.97872463  1771.9898 Square 49.5
+ 225.0000 -625.0000  65.0044  -0.06505911 0.18071974 0.98138050  1762.3156 Square 49.5
+ 225.0000 -575.0000  56.1653  -0.06522291 0.16668077 0.98385136  1753.3976 Square 49.5
+ 225.0000 -525.0000  48.0628  -0.06537415 0.15253969 0.98613278  1745.2329 Square 49.5
+ 225.0000 -475.0000  40.6968  -0.06551256 0.13830430 0.98822064  1737.8188 Square 49.5
+ 225.0000 -425.0000  34.0675  -0.06563789 0.12398268 0.99011109  1731.1530 Square 49.5
+ 225.0000 -375.0000  28.1747  -0.06574989 0.10958316 0.99180063  1725.2332 Square 49.5
+ 225.0000 -325.0000  23.0186  -0.06584837 0.09511431 0.99328609  1720.0576 Square 49.5
+ 225.0000 -275.0000  18.5990  -0.06593313 0.08058494 0.99456467  1715.6245 Square 49.5
+ 225.0000 -225.0000  14.9160  -0.06600402 0.06600402 0.99563394  1711.9324 Square 49.5
+ 225.0000 -175.0000  11.9697  -0.06606089 0.05138069 0.99649184  1708.9802 Square 49.5
+ 225.0000 -125.0000   9.7599  -0.06610364 0.03672425 0.99713672  1706.7669 Square 49.5
+ 225.0000  -75.0000   8.2867  -0.06613219 0.02204406 0.99756734  1705.2917 Square 49.5
+ 225.0000  -25.0000   7.5501  -0.06614648 0.00734961 0.99778286  1704.5543 Square 49.5
+ 225.0000   25.0000   7.5501  -0.06614648 -0.00734961 0.99778286 1704.5543 Square 49.5
+ 225.0000   75.0000   8.2867  -0.06613219 -0.02204406 0.99756734 1705.2917 Square 49.5
+ 225.0000  125.0000   9.7599  -0.06610364 -0.03672425 0.99713672 1706.7669 Square 49.5
+ 225.0000  175.0000  11.9697  -0.06606089 -0.05138069 0.99649184 1708.9802 Square 49.5
+ 225.0000  225.0000  14.9160  -0.06600402 -0.06600402 0.99563394 1711.9324 Square 49.5
+ 225.0000  275.0000  18.5990  -0.06593313 -0.08058494 0.99456467 1715.6245 Square 49.5
+ 225.0000  325.0000  23.0186  -0.06584837 -0.09511431 0.99328609 1720.0576 Square 49.5
+ 225.0000  375.0000  28.1747  -0.06574989 -0.10958316 0.99180063 1725.2332 Square 49.5
+ 225.0000  425.0000  34.0675  -0.06563789 -0.12398268 0.99011109 1731.1530 Square 49.5
+ 225.0000  475.0000  40.6968  -0.06551256 -0.13830430 0.98822064 1737.8188 Square 49.5
+ 225.0000  525.0000  48.0628  -0.06537415 -0.15253969 0.98613278 1745.2329 Square 49.5
+ 225.0000  575.0000  56.1653  -0.06522291 -0.16668077 0.98385136 1753.3976 Square 49.5
+ 225.0000  625.0000  65.0044  -0.06505911 -0.18071974 0.98138050 1762.3156 Square 49.5
+ 225.0000  675.0000  74.5801  -0.06488304 -0.19464912 0.97872463 1771.9898 Square 49.5
+ 225.0000  725.0000  84.8925  -0.06469502 -0.20846173 0.97588845 1782.4232 Square 49.5
+ 225.0000  775.0000  95.9414  -0.06449537 -0.22215073 0.97287687 1793.6193 Square 49.5
+ 225.0000  825.0000 107.7269  -0.06428444 -0.23570961 0.96969505 1805.5815 Square 49.5
+ 275.0000 -825.0000 111.4098  -0.07848982 0.23546947 0.96870712  1809.3239 Square 49.5
+ 275.0000 -775.0000  99.6243  -0.07874684 0.22192291 0.97187919  1797.3553 Square 49.5
+ 275.0000 -725.0000  88.5754  -0.07899010 0.20824663 0.97488148  1786.1532 Square 49.5
+ 275.0000 -675.0000  78.2631  -0.07921919 0.19444711 0.97770887  1775.7142 Square 49.5
+ 275.0000 -625.0000  68.6874  -0.07943371 0.18053117 0.98035646  1766.0349 Square 49.5
+ 275.0000 -575.0000  59.8483  -0.07963329 0.16650597 0.98281957  1757.1121 Square 49.5
+ 275.0000 -525.0000  51.7457  -0.07981756 0.15237898 0.98509380  1748.9429 Square 49.5
+ 275.0000 -475.0000  44.3798  -0.07998619 0.13815797 0.98717505  1741.5249 Square 49.5
+ 275.0000 -425.0000  37.7504  -0.08013888 0.12385100 0.98905950  1734.8554 Square 49.5
+ 275.0000 -375.0000  31.8577  -0.08027534 0.10946637 0.99074365  1728.9324 Square 49.5
+ 275.0000 -325.0000  26.7015  -0.08039532 0.09501265 0.99222436  1723.7540 Square 49.5
+ 275.0000 -275.0000  22.2820  -0.08049858 0.08049858 0.99349885  1719.3185 Square 49.5
+ 275.0000 -225.0000  18.5990  -0.08058494 0.06593313 0.99456467  1715.6245 Square 49.5
+ 275.0000 -175.0000  15.6526  -0.08065423 0.05132542 0.99541981  1712.6707 Square 49.5
+ 275.0000 -125.0000  13.4428  -0.08070631 0.03668469 0.99606261  1710.4562 Square 49.5
+ 275.0000  -75.0000  11.9697  -0.08074109 0.02202030 0.99649184  1708.9802 Square 49.5
+ 275.0000  -25.0000  11.2331  -0.08075849 0.00734168 0.99670666  1708.2424 Square 49.5
+ 275.0000   25.0000  11.2331  -0.08075849 -0.00734168 0.99670666 1708.2424 Square 49.5
+ 275.0000   75.0000  11.9697  -0.08074109 -0.02202030 0.99649184 1708.9802 Square 49.5
+ 275.0000  125.0000  13.4428  -0.08070631 -0.03668469 0.99606261 1710.4562 Square 49.5
+ 275.0000  175.0000  15.6526  -0.08065423 -0.05132542 0.99541981 1712.6707 Square 49.5
+ 275.0000  225.0000  18.5990  -0.08058494 -0.06593313 0.99456467 1715.6245 Square 49.5
+ 275.0000  275.0000  22.2820  -0.08049858 -0.08049858 0.99349885 1719.3185 Square 49.5
+ 275.0000  325.0000  26.7015  -0.08039532 -0.09501265 0.99222436 1723.7540 Square 49.5
+ 275.0000  375.0000  31.8577  -0.08027534 -0.10946637 0.99074365 1728.9324 Square 49.5
+ 275.0000  425.0000  37.7504  -0.08013888 -0.12385100 0.98905950 1734.8554 Square 49.5
+ 275.0000  475.0000  44.3798  -0.07998619 -0.13815797 0.98717505 1741.5249 Square 49.5
+ 275.0000  525.0000  51.7457  -0.07981756 -0.15237898 0.98509380 1748.9429 Square 49.5
+ 275.0000  575.0000  59.8483  -0.07963329 -0.16650597 0.98281957 1757.1121 Square 49.5
+ 275.0000  625.0000  68.6874  -0.07943371 -0.18053117 0.98035646 1766.0349 Square 49.5
+ 275.0000  675.0000  78.2631  -0.07921919 -0.19444711 0.97770887 1775.7142 Square 49.5
+ 275.0000  725.0000  88.5754  -0.07899010 -0.20824663 0.97488148 1786.1532 Square 49.5
+ 275.0000  775.0000  99.6243  -0.07874684 -0.22192291 0.97187919 1797.3553 Square 49.5
+ 275.0000  825.0000 111.4098  -0.07848982 -0.23546947 0.96870712 1809.3239 Square 49.5
+ 325.0000 -825.0000 115.8294  -0.09264756 0.23518226 0.96752557  1813.8174 Square 49.5
+ 325.0000 -775.0000 104.0439  -0.09295019 0.22165046 0.97068601  1801.8411 Square 49.5
+ 325.0000 -725.0000  92.9950  -0.09323662 0.20798939 0.97367723  1790.6319 Square 49.5
+ 325.0000 -675.0000  82.6827  -0.09350636 0.19420552 0.97649413  1780.1862 Square 49.5
+ 325.0000 -625.0000  73.1070  -0.09375894 0.18030565 0.97913183  1770.5006 Square 49.5
+ 325.0000 -575.0000  64.2678  -0.09399392 0.16629693 0.98158569  1761.5720 Square 49.5
+ 325.0000 -525.0000  56.1653  -0.09421087 0.15218679 0.98385136  1753.3976 Square 49.5
+ 325.0000 -475.0000  48.7994  -0.09440941 0.13798298 0.98592472  1745.9748 Square 49.5
+ 325.0000 -425.0000  42.1700  -0.09458917 0.12369353 0.98780200  1739.3010 Square 49.5
+ 325.0000 -375.0000  36.2773  -0.09474983 0.10932672 0.98947973  1733.3742 Square 49.5
+ 325.0000 -325.0000  31.1211  -0.09489107 0.09489107 0.99095478  1728.1924 Square 49.5
+ 325.0000 -275.0000  26.7015  -0.09501265 0.08039532 0.99222436  1723.7540 Square 49.5
+ 325.0000 -225.0000  23.0186  -0.09511431 0.06584837 0.99328609  1720.0576 Square 49.5
+ 325.0000 -175.0000  20.0722  -0.09519588 0.05125932 0.99413793  1717.1019 Square 49.5
+ 325.0000 -125.0000  17.8624  -0.09525720 0.03663738 0.99477825  1714.8859 Square 49.5
+ 325.0000  -75.0000  16.3892  -0.09529814 0.02199188 0.99520582  1713.4090 Square 49.5
+ 325.0000  -25.0000  15.6526  -0.09531863 0.00733220 0.99541981  1712.6707 Square 49.5
+ 325.0000   25.0000  15.6526  -0.09531863 -0.00733220 0.99541981 1712.6707 Square 49.5
+ 325.0000   75.0000  16.3892  -0.09529814 -0.02199188 0.99520582 1713.4090 Square 49.5
+ 325.0000  125.0000  17.8624  -0.09525720 -0.03663738 0.99477825 1714.8859 Square 49.5
+ 325.0000  175.0000  20.0722  -0.09519588 -0.05125932 0.99413793 1717.1019 Square 49.5
+ 325.0000  225.0000  23.0186  -0.09511431 -0.06584837 0.99328609 1720.0576 Square 49.5
+ 325.0000  275.0000  26.7015  -0.09501265 -0.08039532 0.99222436 1723.7540 Square 49.5
+ 325.0000  325.0000  31.1211  -0.09489107 -0.09489107 0.99095478 1728.1924 Square 49.5
+ 325.0000  375.0000  36.2773  -0.09474983 -0.10932672 0.98947973 1733.3742 Square 49.5
+ 325.0000  425.0000  42.1700  -0.09458917 -0.12369353 0.98780200 1739.3010 Square 49.5
+ 325.0000  475.0000  48.7994  -0.09440941 -0.13798298 0.98592472 1745.9748 Square 49.5
+ 325.0000  525.0000  56.1653  -0.09421087 -0.15218679 0.98385136 1753.3976 Square 49.5
+ 325.0000  575.0000  64.2678  -0.09399392 -0.16629693 0.98158569 1761.5720 Square 49.5
+ 325.0000  625.0000  73.1070  -0.09375894 -0.18030565 0.97913183 1770.5006 Square 49.5
+ 325.0000  675.0000  82.6827  -0.09350636 -0.19420552 0.97649413 1780.1862 Square 49.5
+ 325.0000  725.0000  92.9950  -0.09323662 -0.20798939 0.97367723 1790.6319 Square 49.5
+ 325.0000  775.0000 104.0439  -0.09295019 -0.22165046 0.97068601 1801.8411 Square 49.5
+ 325.0000  825.0000 115.8294  -0.09264756 -0.23518226 0.96752557 1813.8174 Square 49.5
+ 375.0000 -825.0000 120.9856  -0.10674932 0.23484851 0.96615255  1819.0634 Square 49.5
+ 375.0000 -775.0000 109.2001  -0.10709703 0.22133386 0.96929951  1807.0782 Square 49.5
+ 375.0000 -725.0000  98.1511  -0.10742611 0.20769047 0.97227789  1795.8606 Square 49.5
+ 375.0000 -675.0000  87.8388  -0.10773600 0.19392480 0.97508263  1785.4071 Square 49.5
+ 375.0000 -625.0000  78.2631  -0.10802617 0.18004362 0.97770887  1775.7142 Square 49.5
+ 375.0000 -575.0000  69.4240  -0.10829611 0.16605404 0.98015203  1766.7790 Square 49.5
+ 375.0000 -525.0000  61.3214  -0.10854535 0.15196349 0.98240776  1758.5984 Square 49.5
+ 375.0000 -475.0000  53.9555  -0.10877342 0.13777967 0.98447199  1751.1699 Square 49.5
+ 375.0000 -425.0000  47.3262  -0.10897992 0.12351058 0.98634097  1744.4911 Square 49.5
+ 375.0000 -375.0000  41.4334  -0.10916447 0.10916447 0.98801125  1738.5599 Square 49.5
+ 375.0000 -325.0000  36.2773  -0.10932672 0.09474983 0.98947973  1733.3742 Square 49.5
+ 375.0000 -275.0000  31.8577  -0.10946637 0.08027534 0.99074365  1728.9324 Square 49.5
+ 375.0000 -225.0000  28.1747  -0.10958316 0.06574989 0.99180063  1725.2332 Square 49.5
+ 375.0000 -175.0000  25.2283  -0.10967685 0.05118253 0.99264865  1722.2752 Square 49.5
+ 375.0000 -125.0000  23.0186  -0.10974728 0.03658243 0.99328609  1720.0576 Square 49.5
+ 375.0000  -75.0000  21.5454  -0.10979431 0.02195886 0.99371174  1718.5796 Square 49.5
+ 375.0000  -25.0000  20.8088  -0.10981785 0.00732119 0.99392477  1717.8407 Square 49.5
+ 375.0000   25.0000  20.8088  -0.10981785 -0.00732119 0.99392477 1717.8407 Square 49.5
+ 375.0000   75.0000  21.5454  -0.10979431 -0.02195886 0.99371174 1718.5796 Square 49.5
+ 375.0000  125.0000  23.0186  -0.10974728 -0.03658243 0.99328609 1720.0576 Square 49.5
+ 375.0000  175.0000  25.2283  -0.10967685 -0.05118253 0.99264865 1722.2752 Square 49.5
+ 375.0000  225.0000  28.1747  -0.10958316 -0.06574989 0.99180063 1725.2332 Square 49.5
+ 375.0000  275.0000  31.8577  -0.10946637 -0.08027534 0.99074365 1728.9324 Square 49.5
+ 375.0000  325.0000  36.2773  -0.10932672 -0.09474983 0.98947973 1733.3742 Square 49.5
+ 375.0000  375.0000  41.4334  -0.10916447 -0.10916447 0.98801125 1738.5599 Square 49.5
+ 375.0000  425.0000  47.3262  -0.10897992 -0.12351058 0.98634097 1744.4911 Square 49.5
+ 375.0000  475.0000  53.9555  -0.10877342 -0.13777967 0.98447199 1751.1699 Square 49.5
+ 375.0000  525.0000  61.3214  -0.10854535 -0.15196349 0.98240776 1758.5984 Square 49.5
+ 375.0000  575.0000  69.4240  -0.10829611 -0.16605404 0.98015203 1766.7790 Square 49.5
+ 375.0000  625.0000  78.2631  -0.10802617 -0.18004362 0.97770887 1775.7142 Square 49.5
+ 375.0000  675.0000  87.8388  -0.10773600 -0.19392480 0.97508263 1785.4071 Square 49.5
+ 375.0000  725.0000  98.1511  -0.10742611 -0.20769047 0.97227789 1795.8606 Square 49.5
+ 375.0000  775.0000 109.2001  -0.10709703 -0.22133386 0.96929951 1807.0782 Square 49.5
+ 375.0000  825.0000 120.9856  -0.10674932 -0.23484851 0.96615255 1819.0634 Square 49.5
+ 425.0000 -775.0000 115.0928  -0.12117912 0.22097369 0.96772220  1813.0683 Square 49.5
+ 425.0000 -725.0000 104.0439  -0.12155025 0.20735043 0.97068601  1801.8411 Square 49.5
+ 425.0000 -675.0000  93.7316  -0.12189974 0.19360546 0.97347695  1791.3786 Square 49.5
+ 425.0000 -625.0000  84.1559  -0.12222697 0.17974555 0.97609021  1781.6775 Square 49.5
+ 425.0000 -575.0000  75.3167  -0.12253139 0.16577776 0.97852123  1772.7345 Square 49.5
+ 425.0000 -525.0000  67.2142  -0.12281244 0.15170948 0.98076569  1764.5469 Square 49.5
+ 425.0000 -475.0000  59.8483  -0.12306963 0.13754841 0.98281957  1757.1121 Square 49.5
+ 425.0000 -425.0000  53.2189  -0.12330248 0.12330248 0.98467913  1750.4275 Square 49.5
+ 425.0000 -375.0000  47.3262  -0.12351058 0.10897992 0.98634097  1744.4911 Square 49.5
+ 425.0000 -325.0000  42.1700  -0.12369353 0.09458917 0.98780200  1739.3010 Square 49.5
+ 425.0000 -275.0000  37.7504  -0.12385100 0.08013888 0.98905950  1734.8554 Square 49.5
+ 425.0000 -225.0000  34.0675  -0.12398268 0.06563789 0.99011109  1731.1530 Square 49.5
+ 425.0000 -175.0000  31.1211  -0.12408833 0.05109519 0.99095478  1728.1924 Square 49.5
+ 425.0000 -125.0000  28.9113  -0.12416774 0.03651992 0.99158896  1725.9729 Square 49.5
+ 425.0000  -75.0000  27.4381  -0.12422077 0.02192131 0.99201243  1724.4936 Square 49.5
+ 425.0000  -25.0000  26.7015  -0.12424731 0.00730867 0.99222436  1723.7540 Square 49.5
+ 425.0000   25.0000  26.7015  -0.12424731 -0.00730867 0.99222436 1723.7540 Square 49.5
+ 425.0000   75.0000  27.4381  -0.12422077 -0.02192131 0.99201243 1724.4936 Square 49.5
+ 425.0000  125.0000  28.9113  -0.12416774 -0.03651992 0.99158896 1725.9729 Square 49.5
+ 425.0000  175.0000  31.1211  -0.12408833 -0.05109519 0.99095478 1728.1924 Square 49.5
+ 425.0000  225.0000  34.0675  -0.12398268 -0.06563789 0.99011109 1731.1530 Square 49.5
+ 425.0000  275.0000  37.7504  -0.12385100 -0.08013888 0.98905950 1734.8554 Square 49.5
+ 425.0000  325.0000  42.1700  -0.12369353 -0.09458917 0.98780200 1739.3010 Square 49.5
+ 425.0000  375.0000  47.3262  -0.12351058 -0.10897992 0.98634097 1744.4911 Square 49.5
+ 425.0000  425.0000  53.2189  -0.12330248 -0.12330248 0.98467913 1750.4275 Square 49.5
+ 425.0000  475.0000  59.8483  -0.12306963 -0.13754841 0.98281957 1757.1121 Square 49.5
+ 425.0000  525.0000  67.2142  -0.12281244 -0.15170948 0.98076569 1764.5469 Square 49.5
+ 425.0000  575.0000  75.3167  -0.12253139 -0.16577776 0.97852123 1772.7345 Square 49.5
+ 425.0000  625.0000  84.1559  -0.12222697 -0.17974555 0.97609021 1781.6775 Square 49.5
+ 425.0000  675.0000  93.7316  -0.12189974 -0.19360546 0.97347695 1791.3786 Square 49.5
+ 425.0000  725.0000 104.0439  -0.12155025 -0.20735043 0.97068601 1801.8411 Square 49.5
+ 425.0000  775.0000 115.0928  -0.12117912 -0.22097369 0.96772220 1813.0683 Square 49.5
+ 475.0000 -725.0000 110.6732  -0.13560095 0.20696987 0.96890446  1808.5752 Square 49.5
+ 475.0000 -675.0000 100.3609  -0.13598940 0.19324809 0.97168002  1798.1027 Square 49.5
+ 475.0000 -625.0000  90.7852  -0.13635310 0.17941198 0.97427880  1788.3922 Square 49.5
+ 475.0000 -575.0000  81.9461  -0.13669143 0.16546858 0.97669627  1779.4406 Square 49.5
+ 475.0000 -525.0000  73.8435  -0.13700379 0.15142525 0.97892817  1771.2452 Square 49.5
+ 475.0000 -475.0000  66.4776  -0.13728962 0.13728962 0.98097050  1763.8031 Square 49.5
+ 475.0000 -425.0000  59.8483  -0.13754841 0.12306963 0.98281957  1757.1121 Square 49.5
+ 475.0000 -375.0000  53.9555  -0.13777967 0.10877342 0.98447199  1751.1699 Square 49.5
+ 475.0000 -325.0000  48.7994  -0.13798298 0.09440941 0.98592472  1745.9748 Square 49.5
+ 475.0000 -275.0000  44.3798  -0.13815797 0.07998619 0.98717505  1741.5249 Square 49.5
+ 475.0000 -225.0000  40.6968  -0.13830430 0.06551256 0.98822064  1737.8188 Square 49.5
+ 475.0000 -175.0000  37.7504  -0.13842170 0.05099747 0.98905950  1734.8554 Square 49.5
+ 475.0000 -125.0000  35.5407  -0.13850995 0.03644999 0.98969005  1732.6337 Square 49.5
+ 475.0000  -75.0000  34.0675  -0.13856888 0.02187930 0.99011109  1731.1530 Square 49.5
+ 475.0000  -25.0000  33.3309  -0.13859837 0.00729465 0.99032181  1730.4127 Square 49.5
+ 475.0000   25.0000  33.3309  -0.13859837 -0.00729465 0.99032181 1730.4127 Square 49.5
+ 475.0000   75.0000  34.0675  -0.13856888 -0.02187930 0.99011109 1731.1530 Square 49.5
+ 475.0000  125.0000  35.5407  -0.13850995 -0.03644999 0.98969005 1732.6337 Square 49.5
+ 475.0000  175.0000  37.7504  -0.13842170 -0.05099747 0.98905950 1734.8554 Square 49.5
+ 475.0000  225.0000  40.6968  -0.13830430 -0.06551256 0.98822064 1737.8188 Square 49.5
+ 475.0000  275.0000  44.3798  -0.13815797 -0.07998619 0.98717505 1741.5249 Square 49.5
+ 475.0000  325.0000  48.7994  -0.13798298 -0.09440941 0.98592472 1745.9748 Square 49.5
+ 475.0000  375.0000  53.9555  -0.13777967 -0.10877342 0.98447199 1751.1699 Square 49.5
+ 475.0000  425.0000  59.8483  -0.13754841 -0.12306963 0.98281957 1757.1121 Square 49.5
+ 475.0000  475.0000  66.4776  -0.13728962 -0.13728962 0.98097050 1763.8031 Square 49.5
+ 475.0000  525.0000  73.8435  -0.13700379 -0.15142525 0.97892817 1771.2452 Square 49.5
+ 475.0000  575.0000  81.9461  -0.13669143 -0.16546858 0.97669627 1779.4406 Square 49.5
+ 475.0000  625.0000  90.7852  -0.13635310 -0.17941198 0.97427880 1788.3922 Square 49.5
+ 475.0000  675.0000 100.3609  -0.13598940 -0.19324809 0.97168002 1798.1027 Square 49.5
+ 475.0000  725.0000 110.6732  -0.13560095 -0.20696987 0.96890446 1808.5752 Square 49.5
+ 525.0000 -675.0000 107.7269  -0.14999702 0.19285332 0.96969505  1805.5815 Square 49.5
+ 525.0000 -625.0000  98.1511  -0.15039655 0.17904351 0.97227789  1795.8606 Square 49.5
+ 525.0000 -575.0000  89.3120  -0.15076819 0.16512707 0.97468046  1786.8995 Square 49.5
+ 525.0000 -525.0000  81.2095  -0.15111129 0.15111129 0.97689854  1778.6952 Square 49.5
+ 525.0000 -475.0000  73.8435  -0.15142525 0.13700379 0.97892817  1771.2452 Square 49.5
+ 525.0000 -425.0000  67.2142  -0.15170948 0.12281244 0.98076569  1764.5469 Square 49.5
+ 525.0000 -375.0000  61.3214  -0.15196349 0.10854535 0.98240776  1758.5984 Square 49.5
+ 525.0000 -325.0000  56.1653  -0.15218679 0.09421087 0.98385136  1753.3976 Square 49.5
+ 525.0000 -275.0000  51.7457  -0.15237898 0.07981756 0.98509380  1748.9429 Square 49.5
+ 525.0000 -225.0000  48.0628  -0.15253969 0.06537415 0.98613278  1745.2329 Square 49.5
+ 525.0000 -175.0000  45.1164  -0.15266863 0.05088954 0.98696633  1742.2663 Square 49.5
+ 525.0000 -125.0000  42.9066  -0.15276555 0.03637275 0.98759289  1740.0422 Square 49.5
+ 525.0000  -75.0000  41.4334  -0.15283026 0.02183289 0.98801125  1738.5599 Square 49.5
+ 525.0000  -25.0000  40.6968  -0.15286265 0.00727917 0.98822064  1737.8188 Square 49.5
+ 525.0000   25.0000  40.6968  -0.15286265 -0.00727917 0.98822064 1737.8188 Square 49.5
+ 525.0000   75.0000  41.4334  -0.15283026 -0.02183289 0.98801125 1738.5599 Square 49.5
+ 525.0000  125.0000  42.9066  -0.15276555 -0.03637275 0.98759289 1740.0422 Square 49.5
+ 525.0000  175.0000  45.1164  -0.15266863 -0.05088954 0.98696633 1742.2663 Square 49.5
+ 525.0000  225.0000  48.0628  -0.15253969 -0.06537415 0.98613278 1745.2329 Square 49.5
+ 525.0000  275.0000  51.7457  -0.15237898 -0.07981756 0.98509380 1748.9429 Square 49.5
+ 525.0000  325.0000  56.1653  -0.15218679 -0.09421087 0.98385136 1753.3976 Square 49.5
+ 525.0000  375.0000  61.3214  -0.15196349 -0.10854535 0.98240776 1758.5984 Square 49.5
+ 525.0000  425.0000  67.2142  -0.15170948 -0.12281244 0.98076569 1764.5469 Square 49.5
+ 525.0000  475.0000  73.8435  -0.15142525 -0.13700379 0.97892817 1771.2452 Square 49.5
+ 525.0000  525.0000  81.2095  -0.15111129 -0.15111129 0.97689854 1778.6952 Square 49.5
+ 525.0000  575.0000  89.3120  -0.15076819 -0.16512707 0.97468046 1786.8995 Square 49.5
+ 525.0000  625.0000  98.1511  -0.15039655 -0.17904351 0.97227789 1795.8606 Square 49.5
+ 525.0000  675.0000 107.7269  -0.14999702 -0.19285332 0.96969505 1805.5815 Square 49.5
+ 575.0000 -625.0000 106.2537  -0.16434955 0.17864081 0.97009107  1804.0851 Square 49.5
+ 575.0000 -575.0000  97.4146  -0.16475384 0.16475384 0.97247743  1795.1134 Square 49.5
+ 575.0000 -525.0000  89.3120  -0.16512707 0.15076819 0.97468046  1786.8995 Square 49.5
+ 575.0000 -475.0000  81.9461  -0.16546858 0.13669143 0.97669627  1779.4406 Square 49.5
+ 575.0000 -425.0000  75.3167  -0.16577776 0.12253139 0.97852123  1772.7345 Square 49.5
+ 575.0000 -375.0000  69.4240  -0.16605404 0.10829611 0.98015203  1766.7790 Square 49.5
+ 575.0000 -325.0000  64.2678  -0.16629693 0.09399392 0.98158569  1761.5720 Square 49.5
+ 575.0000 -275.0000  59.8483  -0.16650597 0.07963329 0.98281957  1757.1121 Square 49.5
+ 575.0000 -225.0000  56.1653  -0.16668077 0.06522291 0.98385136  1753.3976 Square 49.5
+ 575.0000 -175.0000  53.2189  -0.16682101 0.05077161 0.98467913  1750.4275 Square 49.5
+ 575.0000 -125.0000  51.0091  -0.16692642 0.03628835 0.98530134  1748.2008 Square 49.5
+ 575.0000  -75.0000  49.5359  -0.16699681 0.02178219 0.98571680  1746.7167 Square 49.5
+ 575.0000  -25.0000  48.7994  -0.16703203 0.00726226 0.98592472  1745.9748 Square 49.5
+ 575.0000   25.0000  48.7994  -0.16703203 -0.00726226 0.98592472 1745.9748 Square 49.5
+ 575.0000   75.0000  49.5359  -0.16699681 -0.02178219 0.98571680 1746.7167 Square 49.5
+ 575.0000  125.0000  51.0091  -0.16692642 -0.03628835 0.98530134 1748.2008 Square 49.5
+ 575.0000  175.0000  53.2189  -0.16682101 -0.05077161 0.98467913 1750.4275 Square 49.5
+ 575.0000  225.0000  56.1653  -0.16668077 -0.06522291 0.98385136 1753.3976 Square 49.5
+ 575.0000  275.0000  59.8483  -0.16650597 -0.07963329 0.98281957 1757.1121 Square 49.5
+ 575.0000  325.0000  64.2678  -0.16629693 -0.09399392 0.98158569 1761.5720 Square 49.5
+ 575.0000  375.0000  69.4240  -0.16605404 -0.10829611 0.98015203 1766.7790 Square 49.5
+ 575.0000  425.0000  75.3167  -0.16577776 -0.12253139 0.97852123 1772.7345 Square 49.5
+ 575.0000  475.0000  81.9461  -0.16546858 -0.13669143 0.97669627 1779.4406 Square 49.5
+ 575.0000  525.0000  89.3120  -0.16512707 -0.15076819 0.97468046 1786.8995 Square 49.5
+ 575.0000  575.0000  97.4146  -0.16475384 -0.16475384 0.97247743 1795.1134 Square 49.5
+ 575.0000  625.0000 106.2537  -0.16434955 -0.17864081 0.97009107 1804.0851 Square 49.5
+ 625.0000 -575.0000 106.2537  -0.17864081 0.16434955 0.97009107  1804.0851 Square 49.5
+ 625.0000 -525.0000  98.1511  -0.17904351 0.15039655 0.97227789  1795.8606 Square 49.5
+ 625.0000 -475.0000  90.7852  -0.17941198 0.13635310 0.97427880  1788.3922 Square 49.5
+ 625.0000 -425.0000  84.1559  -0.17974555 0.12222697 0.97609021  1781.6775 Square 49.5
+ 625.0000 -375.0000  78.2631  -0.18004362 0.10802617 0.97770887  1775.7142 Square 49.5
+ 625.0000 -325.0000  73.1070  -0.18030565 0.09375894 0.97913183  1770.5006 Square 49.5
+ 625.0000 -275.0000  68.6874  -0.18053117 0.07943371 0.98035646  1766.0349 Square 49.5
+ 625.0000 -225.0000  65.0044  -0.18071974 0.06505911 0.98138050  1762.3156 Square 49.5
+ 625.0000 -175.0000  62.0580  -0.18087103 0.05064389 0.98220205  1759.3417 Square 49.5
+ 625.0000 -125.0000  59.8483  -0.18098475 0.03619695 0.98281957  1757.1121 Square 49.5
+ 625.0000  -75.0000  58.3751  -0.18106068 0.02172728 0.98323189  1755.6261 Square 49.5
+ 625.0000  -25.0000  57.6385  -0.18109868 0.00724395 0.98343825  1754.8832 Square 49.5
+ 625.0000   25.0000  57.6385  -0.18109868 -0.00724395 0.98343825 1754.8832 Square 49.5
+ 625.0000   75.0000  58.3751  -0.18106068 -0.02172728 0.98323189 1755.6261 Square 49.5
+ 625.0000  125.0000  59.8483  -0.18098475 -0.03619695 0.98281957 1757.1121 Square 49.5
+ 625.0000  175.0000  62.0580  -0.18087103 -0.05064389 0.98220205 1759.3417 Square 49.5
+ 625.0000  225.0000  65.0044  -0.18071974 -0.06505911 0.98138050 1762.3156 Square 49.5
+ 625.0000  275.0000  68.6874  -0.18053117 -0.07943371 0.98035646 1766.0349 Square 49.5
+ 625.0000  325.0000  73.1070  -0.18030565 -0.09375894 0.97913183 1770.5006 Square 49.5
+ 625.0000  375.0000  78.2631  -0.18004362 -0.10802617 0.97770887 1775.7142 Square 49.5
+ 625.0000  425.0000  84.1559  -0.17974555 -0.12222697 0.97609021 1781.6775 Square 49.5
+ 625.0000  475.0000  90.7852  -0.17941198 -0.13635310 0.97427880 1788.3922 Square 49.5
+ 625.0000  525.0000  98.1511  -0.17904351 -0.15039655 0.97227789 1795.8606 Square 49.5
+ 625.0000  575.0000 106.2537  -0.17864081 -0.16434955 0.97009107 1804.0851 Square 49.5
+ 675.0000 -525.0000 107.7269  -0.19285332 0.14999702 0.96969505  1805.5815 Square 49.5
+ 675.0000 -475.0000 100.3609  -0.19324809 0.13598940 0.97168002  1798.1027 Square 49.5
+ 675.0000 -425.0000  93.7316  -0.19360546 0.12189974 0.97347695  1791.3786 Square 49.5
+ 675.0000 -375.0000  87.8388  -0.19392480 0.10773600 0.97508263  1785.4071 Square 49.5
+ 675.0000 -325.0000  82.6827  -0.19420552 0.09350636 0.97649413  1780.1862 Square 49.5
+ 675.0000 -275.0000  78.2631  -0.19444711 0.07921919 0.97770887  1775.7142 Square 49.5
+ 675.0000 -225.0000  74.5801  -0.19464912 0.06488304 0.97872463  1771.9898 Square 49.5
+ 675.0000 -175.0000  71.6338  -0.19481119 0.05050660 0.97953953  1769.0117 Square 49.5
+ 675.0000 -125.0000  69.4240  -0.19493301 0.03609870 0.98015203  1766.7790 Square 49.5
+ 675.0000  -75.0000  67.9508  -0.19501434 0.02166826 0.98056101  1765.2909 Square 49.5
+ 675.0000  -25.0000  67.2142  -0.19505505 0.00722426 0.98076569  1764.5469 Square 49.5
+ 675.0000   25.0000  67.2142  -0.19505505 -0.00722426 0.98076569 1764.5469 Square 49.5
+ 675.0000   75.0000  67.9508  -0.19501434 -0.02166826 0.98056101 1765.2909 Square 49.5
+ 675.0000  125.0000  69.4240  -0.19493301 -0.03609870 0.98015203 1766.7790 Square 49.5
+ 675.0000  175.0000  71.6338  -0.19481119 -0.05050660 0.97953953 1769.0117 Square 49.5
+ 675.0000  225.0000  74.5801  -0.19464912 -0.06488304 0.97872463 1771.9898 Square 49.5
+ 675.0000  275.0000  78.2631  -0.19444711 -0.07921919 0.97770887 1775.7142 Square 49.5
+ 675.0000  325.0000  82.6827  -0.19420552 -0.09350636 0.97649413 1780.1862 Square 49.5
+ 675.0000  375.0000  87.8388  -0.19392480 -0.10773600 0.97508263 1785.4071 Square 49.5
+ 675.0000  425.0000  93.7316  -0.19360546 -0.12189974 0.97347695 1791.3786 Square 49.5
+ 675.0000  475.0000 100.3609  -0.19324809 -0.13598940 0.97168002 1798.1027 Square 49.5
+ 675.0000  525.0000 107.7269  -0.19285332 -0.14999702 0.96969505 1805.5815 Square 49.5
+ 725.0000 -475.0000 110.6732  -0.20696987 0.13560095 0.96890446  1808.5752 Square 49.5
+ 725.0000 -425.0000 104.0439  -0.20735043 0.12155025 0.97068601  1801.8411 Square 49.5
+ 725.0000 -375.0000  98.1511  -0.20769047 0.10742611 0.97227789  1795.8606 Square 49.5
+ 725.0000 -325.0000  92.9950  -0.20798939 0.09323662 0.97367723  1790.6319 Square 49.5
+ 725.0000 -275.0000  88.5754  -0.20824663 0.07899010 0.97488148  1786.1532 Square 49.5
+ 725.0000 -225.0000  84.8925  -0.20846173 0.06469502 0.97588845  1782.4232 Square 49.5
+ 725.0000 -175.0000  81.9461  -0.20863429 0.05036000 0.97669627  1779.4406 Square 49.5
+ 725.0000 -125.0000  79.7363  -0.20876400 0.03599379 0.97730345  1777.2046 Square 49.5
+ 725.0000  -75.0000  78.2631  -0.20885060 0.02160523 0.97770887  1775.7142 Square 49.5
+ 725.0000  -25.0000  77.5265  -0.20889394 0.00720324 0.97791177  1774.9692 Square 49.5
+ 725.0000   25.0000  77.5265  -0.20889394 -0.00720324 0.97791177 1774.9692 Square 49.5
+ 725.0000   75.0000  78.2631  -0.20885060 -0.02160523 0.97770887 1775.7142 Square 49.5
+ 725.0000  125.0000  79.7363  -0.20876400 -0.03599379 0.97730345 1777.2046 Square 49.5
+ 725.0000  175.0000  81.9461  -0.20863429 -0.05036000 0.97669627 1779.4406 Square 49.5
+ 725.0000  225.0000  84.8925  -0.20846173 -0.06469502 0.97588845 1782.4232 Square 49.5
+ 725.0000  275.0000  88.5754  -0.20824663 -0.07899010 0.97488148 1786.1532 Square 49.5
+ 725.0000  325.0000  92.9950  -0.20798939 -0.09323662 0.97367723 1790.6319 Square 49.5
+ 725.0000  375.0000  98.1511  -0.20769047 -0.10742611 0.97227789 1795.8606 Square 49.5
+ 725.0000  425.0000 104.0439  -0.20735043 -0.12155025 0.97068601 1801.8411 Square 49.5
+ 725.0000  475.0000 110.6732  -0.20696987 -0.13560095 0.96890446 1808.5752 Square 49.5
+ 775.0000 -425.0000 115.0928  -0.22097369 0.12117912 0.96772220  1813.0683 Square 49.5
+ 775.0000 -375.0000 109.2001  -0.22133386 0.10709703 0.96929951  1807.0782 Square 49.5
+ 775.0000 -325.0000 104.0439  -0.22165046 0.09295019 0.97068601  1801.8411 Square 49.5
+ 775.0000 -275.0000  99.6243  -0.22192291 0.07874684 0.97187919  1797.3553 Square 49.5
+ 775.0000 -225.0000  95.9414  -0.22215073 0.06449537 0.97287687  1793.6193 Square 49.5
+ 775.0000 -175.0000  92.9950  -0.22233349 0.05020434 0.97367723  1790.6319 Square 49.5
+ 775.0000 -125.0000  90.7852  -0.22247085 0.03588240 0.97427880  1788.3922 Square 49.5
+ 775.0000  -75.0000  89.3120  -0.22256257 0.02153831 0.97468046  1786.8995 Square 49.5
+ 775.0000  -25.0000  88.5754  -0.22260847 0.00718092 0.97488148  1786.1532 Square 49.5
+ 775.0000   25.0000  88.5754  -0.22260847 -0.00718092 0.97488148 1786.1532 Square 49.5
+ 775.0000   75.0000  89.3120  -0.22256257 -0.02153831 0.97468046 1786.8995 Square 49.5
+ 775.0000  125.0000  90.7852  -0.22247085 -0.03588240 0.97427880 1788.3922 Square 49.5
+ 775.0000  175.0000  92.9950  -0.22233349 -0.05020434 0.97367723 1790.6319 Square 49.5
+ 775.0000  225.0000  95.9414  -0.22215073 -0.06449537 0.97287687 1793.6193 Square 49.5
+ 775.0000  275.0000  99.6243  -0.22192291 -0.07874684 0.97187919 1797.3553 Square 49.5
+ 775.0000  325.0000 104.0439  -0.22165046 -0.09295019 0.97068601 1801.8411 Square 49.5
+ 775.0000  375.0000 109.2001  -0.22133386 -0.10709703 0.96929951 1807.0782 Square 49.5
+ 775.0000  425.0000 115.0928  -0.22097369 -0.12117912 0.96772220 1813.0683 Square 49.5
+ 825.0000 -375.0000 120.9856  -0.23484851 0.10674932 0.96615255  1819.0634 Square 49.5
+ 825.0000 -325.0000 115.8294  -0.23518226 0.09264756 0.96752557  1813.8174 Square 49.5
+ 825.0000 -275.0000 111.4098  -0.23546947 0.07848982 0.96870712  1809.3239 Square 49.5
+ 825.0000 -225.0000 107.7269  -0.23570961 0.06428444 0.96969505  1805.5815 Square 49.5
+ 825.0000 -175.0000 104.7805  -0.23590225 0.05003987 0.97048758  1802.5890 Square 49.5
+ 825.0000 -125.0000 102.5707  -0.23604705 0.03576470 0.97108325  1800.3455 Square 49.5
+ 825.0000  -25.0000 100.3609  -0.23619211 0.00715734 0.97168002  1798.1027 Square 49.5
+ 825.0000   25.0000 100.3609  -0.23619211 -0.00715734 0.97168002 1798.1027 Square 49.5
+ 825.0000  125.0000 102.5707  -0.23604705 -0.03576470 0.97108325 1800.3455 Square 49.5
+ 825.0000  175.0000 104.7805  -0.23590225 -0.05003987 0.97048758 1802.5890 Square 49.5
+ 825.0000  225.0000 107.7269  -0.23570961 -0.06428444 0.96969505 1805.5815 Square 49.5
+ 825.0000  275.0000 111.4098  -0.23546947 -0.07848982 0.96870712 1809.3239 Square 49.5
+ 825.0000  325.0000 115.8294  -0.23518226 -0.09264756 0.96752557 1813.8174 Square 49.5
+ 825.0000  375.0000 120.9856  -0.23484851 -0.10674932 0.96615255 1819.0634 Square 49.5
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-1NN.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-1NN.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-1NN.txt	(revision 17960)
@@ -0,0 +1,400 @@
+0
+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-2NN.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-2NN.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-2NN.txt	(revision 17960)
@@ -0,0 +1,1267 @@
+0 1 
+0 16 
+0 17 
+0 18 
+0 19 
+0 2 
+0 20 
+0 21 
+0 22 
+0 23 
+0 24 
+0 25 
+0 26 
+0 27 
+0 28 
+0 29 
+0 3 
+0 30 
+0 31 
+0 32 
+0 34 
+0 4 
+0 5 
+0 6 
+0 7 
+100 101 
+100 103 
+100 137 
+100 138 
+100 181 
+10 11 
+101 102 
+101 138 
+101 139 
+101 181 
+102 103 
+102 139 
+102 140 
+10 23 
+10 24 
+103 104 
+103 105 
+103 106 
+103 138 
+103 140 
+103 141 
+103 142 
+103 143 
+103 182 
+103 188 
+103 232 
+103 233 
+103 234 
+103 235 
+103 236 
+103 237 
+103 238 
+10 39 
+104 105 
+104 142 
+104 143 
+104 189 
+10 47 
+105 106 
+105 143 
+105 144 
+105 189 
+106 107 
+106 109 
+106 144 
+106 145 
+106 189 
+107 108 
+107 145 
+107 146 
+107 189 
+108 109 
+108 146 
+108 147 
+109 110 
+109 111 
+109 112 
+109 145 
+109 147 
+109 148 
+109 149 
+109 150 
+109 190 
+109 196 
+109 241 
+109 242 
+109 243 
+109 244 
+109 245 
+109 246 
+109 247 
+110 111 
+110 149 
+110 150 
+110 197 
+111 112 
+111 150 
+111 151 
+111 197 
+11 12 
+112 113 
+112 115 
+112 151 
+112 152 
+112 197 
+11 24 
+11 25 
+11 26 
+113 114 
+113 152 
+113 153 
+113 197 
+114 115 
+114 153 
+114 154 
+11 43 
+115 116 
+115 117 
+115 118 
+115 152 
+115 154 
+115 155 
+115 156 
+115 157 
+115 198 
+115 204 
+115 250 
+115 251 
+115 252 
+115 253 
+115 254 
+115 255 
+115 256 
+116 117 
+116 156 
+116 157 
+116 205 
+117 118 
+117 157 
+117 158 
+117 205 
+1 18 
+118 119 
+118 121 
+118 158 
+118 159 
+118 205 
+119 120 
+119 159 
+119 160 
+119 205 
+1 2 
+120 121 
+120 160 
+120 161 
+121 122 
+121 123 
+121 124 
+121 159 
+121 161 
+121 162 
+121 163 
+121 164 
+121 206 
+121 212 
+121 259 
+121 260 
+121 261 
+121 262 
+121 263 
+121 264 
+121 265 
+12 13 
+122 123 
+122 163 
+122 164 
+122 213 
+12 26 
+12 27 
+123 124 
+123 164 
+123 165 
+123 213 
+124 125 
+124 165 
+124 166 
+124 213 
+12 43 
+12 51 
+125 126 
+125 166 
+125 167 
+125 213 
+126 167 
+126 168 
+127 128 
+127 168 
+127 169 
+127 170 
+127 216 
+128 129 
+128 170 
+128 171 
+128 173 
+129 130 
+129 171 
+129 172 
+130 131 
+130 172 
+130 173 
+131 132 
+131 173 
+131 174 
+13 14 
+132 133 
+132 173 
+132 174 
+132 175 
+13 27 
+13 28 
+13 29 
+133 134 
+133 173 
+133 175 
+133 176 
+134 135 
+134 176 
+134 177 
+134 178 
+13 47 
+135 136 
+135 178 
+135 179 
+135 181 
+136 137 
+136 179 
+136 180 
+137 138 
+137 180 
+137 181 
+138 139 
+138 181 
+138 182 
+1 39 
+139 140 
+139 181 
+139 182 
+139 183 
+140 141 
+140 181 
+140 183 
+140 184 
+141 142 
+141 184 
+141 185 
+141 186 
+14 15 
+142 143 
+142 186 
+142 187 
+142 189 
+14 29 
+14 30 
+143 144 
+143 187 
+143 188 
+144 145 
+144 188 
+144 189 
+14 47 
+145 146 
+145 189 
+145 190 
+14 55 
+146 147 
+146 189 
+146 190 
+146 191 
+147 148 
+147 189 
+147 191 
+147 192 
+148 149 
+148 192 
+148 193 
+148 194 
+149 150 
+149 194 
+149 195 
+149 197 
+150 151 
+150 195 
+150 196 
+151 152 
+151 196 
+151 197 
+15 16 
+152 153 
+152 197 
+152 198 
+15 30 
+15 31 
+153 154 
+153 197 
+153 198 
+153 199 
+15 32 
+154 155 
+154 197 
+154 199 
+154 200 
+15 51 
+155 156 
+155 200 
+155 201 
+155 202 
+156 157 
+156 202 
+156 203 
+156 205 
+157 158 
+157 203 
+157 204 
+158 159 
+158 204 
+158 205 
+1 59 
+159 160 
+159 205 
+159 206 
+1 6 
+160 161 
+160 205 
+160 206 
+160 207 
+161 162 
+161 205 
+161 207 
+161 208 
+16 17 
+162 163 
+162 208 
+162 209 
+162 210 
+163 164 
+16 32 
+163 210 
+163 211 
+163 213 
+16 33 
+164 165 
+164 211 
+164 212 
+16 51 
+165 166 
+165 212 
+165 213 
+16 59 
+166 167 
+166 213 
+166 214 
+167 168 
+167 213 
+167 214 
+167 215 
+168 213 
+168 215 
+168 216 
+169 170 
+169 216 
+169 217 
+169 218 
+169 270 
+1 7 
+170 171 
+170 173 
+170 218 
+170 219 
+171 172 
+171 219 
+171 220 
+17 18 
+172 173 
+172 220 
+172 221 
+173 174 
+173 176 
+173 219 
+173 221 
+173 222 
+173 224 
+173 274 
+173 278 
+17 33 
+173 335 
+173 336 
+173 337 
+173 338 
+17 34 
+17 35 
+174 175 
+174 222 
+174 223 
+175 176 
+175 223 
+175 224 
+17 55 
+176 177 
+176 224 
+176 225 
+177 178 
+177 225 
+177 226 
+177 227 
+178 179 
+178 181 
+178 227 
+178 228 
+179 180 
+179 228 
+179 229 
+1 8 
+180 181 
+180 229 
+180 230 
+181 182 
+181 184 
+181 228 
+181 230 
+181 231 
+181 233 
+181 284 
+181 288 
+181 346 
+181 347 
+181 348 
+181 349 
+182 183 
+182 231 
+182 232 
+183 184 
+183 232 
+183 233 
+18 35 
+18 36 
+18 39 
+184 185 
+184 233 
+184 234 
+185 186 
+185 234 
+185 235 
+185 236 
+18 55 
+186 187 
+186 189 
+186 236 
+186 237 
+187 188 
+187 237 
+187 238 
+188 189 
+188 238 
+188 239 
+189 190 
+189 192 
+189 237 
+189 239 
+189 240 
+189 242 
+189 294 
+189 298 
+189 357 
+189 358 
+189 359 
+189 360 
+190 191 
+190 240 
+190 241 
+191 192 
+191 241 
+191 242 
+19 20 
+192 193 
+192 242 
+192 243 
+193 194 
+193 243 
+193 244 
+193 245 
+19 36 
+19 37 
+19 38 
+194 195 
+194 197 
+194 245 
+194 246 
+195 196 
+195 246 
+195 247 
+19 59 
+19 60 
+196 197 
+196 247 
+196 248 
+197 198 
+197 200 
+197 246 
+197 248 
+197 249 
+197 251 
+197 304 
+197 308 
+197 368 
+197 369 
+197 370 
+197 371 
+198 199 
+198 249 
+198 250 
+19 91 
+199 200 
+199 250 
+199 251 
+200 201 
+200 251 
+200 252 
+201 202 
+201 252 
+201 253 
+201 254 
+20 21 
+202 203 
+202 205 
+202 254 
+202 255 
+203 204 
+203 255 
+203 256 
+20 38 
+20 39 
+204 205 
+204 256 
+204 257 
+205 206 
+205 208 
+205 255 
+205 257 
+205 258 
+205 260 
+205 314 
+205 318 
+205 379 
+205 380 
+205 381 
+205 382 
+206 207 
+206 258 
+206 259 
+207 208 
+207 259 
+207 260 
+208 209 
+208 260 
+208 261 
+209 210 
+209 261 
+209 262 
+209 263 
+2 10 
+210 211 
+210 213 
+210 263 
+210 264 
+211 212 
+211 264 
+211 265 
+21 22 
+212 213 
+212 265 
+212 266 
+213 214 
+213 216 
+213 264 
+213 266 
+213 267 
+213 269 
+213 324 
+213 328 
+213 390 
+213 391 
+213 392 
+213 393 
+21 39 
+21 40 
+214 215 
+214 267 
+214 268 
+21 43 
+215 216 
+215 268 
+215 269 
+216 269 
+216 270 
+217 218 
+217 270 
+218 219 
+219 220 
+219 274 
+220 221 
+220 274 
+220 275 
+221 222 
+221 275 
+221 276 
+222 223 
+222 276 
+222 277 
+22 23 
+223 224 
+223 277 
+223 278 
+22 39 
+22 40 
+22 41 
+22 42 
+224 225 
+224 278 
+225 226 
+226 227 
+227 228 
+228 229 
+228 284 
+229 230 
+229 284 
+229 285 
+22 97 
+2 3 
+230 231 
+230 285 
+230 286 
+231 232 
+231 286 
+231 287 
+232 233 
+232 287 
+232 288 
+23 24 
+233 234 
+233 288 
+23 42 
+234 235 
+23 43 
+235 236 
+236 237 
+237 238 
+237 294 
+238 239 
+238 294 
+238 295 
+2 39 
+239 240 
+239 295 
+239 296 
+240 241 
+240 296 
+240 297 
+241 242 
+241 297 
+241 298 
+242 243 
+242 298 
+24 25 
+2 43 
+243 244 
+244 245 
+24 43 
+24 44 
+24 47 
+245 246 
+246 247 
+246 304 
+247 248 
+247 304 
+247 305 
+248 249 
+248 305 
+248 306 
+249 250 
+249 306 
+249 307 
+250 251 
+250 307 
+250 308 
+25 103 
+251 252 
+251 308 
+252 253 
+25 26 
+253 254 
+254 255 
+25 43 
+25 44 
+25 45 
+25 46 
+255 256 
+255 314 
+256 257 
+256 314 
+256 315 
+257 258 
+257 315 
+257 316 
+258 259 
+258 316 
+258 317 
+259 260 
+259 317 
+259 318 
+260 261 
+260 318 
+261 262 
+262 263 
+26 27 
+263 264 
+264 265 
+264 324 
+26 46 
+26 47 
+265 266 
+265 324 
+265 325 
+266 267 
+266 325 
+266 326 
+267 268 
+267 326 
+267 327 
+268 269 
+268 327 
+268 328 
+269 270 
+269 328 
+27 28 
+274 275 
+274 335 
+27 47 
+27 48 
+27 51 
+275 276 
+275 335 
+275 336 
+276 277 
+276 336 
+276 337 
+277 278 
+277 337 
+277 338 
+278 338 
+2 8 
+28 109 
+28 29 
+284 285 
+284 346 
+28 47 
+28 48 
+28 49 
+28 50 
+285 286 
+285 346 
+285 347 
+286 287 
+286 347 
+286 348 
+287 288 
+287 348 
+287 349 
+288 349 
+2 9 
+29 30 
+294 295 
+294 357 
+29 50 
+29 51 
+295 296 
+295 357 
+295 358 
+296 297 
+296 358 
+296 359 
+297 298 
+297 359 
+297 360 
+298 360 
+30 31 
+304 305 
+304 368 
+30 51 
+30 52 
+305 306 
+305 368 
+305 369 
+30 55 
+306 307 
+306 369 
+306 370 
+307 308 
+307 370 
+307 371 
+308 371 
+3 10 
+3 11 
+31 115 
+3 12 
+31 32 
+314 315 
+314 379 
+31 51 
+31 52 
+31 53 
+315 316 
+315 379 
+315 380 
+31 54 
+316 317 
+316 380 
+316 381 
+317 318 
+317 381 
+317 382 
+318 382 
+32 33 
+324 325 
+324 390 
+325 326 
+325 390 
+325 391 
+32 54 
+32 55 
+326 327 
+326 391 
+326 392 
+327 328 
+327 392 
+327 393 
+328 393 
+33 34 
+335 336 
+33 55 
+33 56 
+33 59 
+336 337 
+337 338 
+3 4 
+34 121 
+3 43 
+34 35 
+34 55 
+34 56 
+34 57 
+34 58 
+346 347 
+3 47 
+347 348 
+348 349 
+35 36 
+35 58 
+35 59 
+357 358 
+358 359 
+359 360 
+36 39 
+36 59 
+36 60 
+368 369 
+369 370 
+370 371 
+37 38 
+37 59 
+37 60 
+37 61 
+37 62 
+37 90 
+37 91 
+379 380 
+380 381 
+381 382 
+38 39 
+38 62 
+38 63 
+390 391 
+39 129 
+39 130 
+39 131 
+39 132 
+391 392 
+392 393 
+39 40 
+39 41 
+39 60 
+39 61 
+39 63 
+39 64 
+39 65 
+39 67 
+39 90 
+39 92 
+39 96 
+40 41 
+40 43 
+40 64 
+40 65 
+40 97 
+4 12 
+4 13 
+4 14 
+41 42 
+41 65 
+41 66 
+41 67 
+41 97 
+42 43 
+42 67 
+42 68 
+43 102 
+43 136 
+43 137 
+43 138 
+43 139 
+43 44 
+43 45 
+43 65 
+43 66 
+43 68 
+43 69 
+43 70 
+43 72 
+43 98 
+44 103 
+44 45 
+44 47 
+44 69 
+4 47 
+44 70 
+4 5 
+4 51 
+45 103 
+45 46 
+45 70 
+45 71 
+45 72 
+46 47 
+46 72 
+46 73 
+47 104 
+47 108 
+47 143 
+47 144 
+47 145 
+47 146 
+47 48 
+47 49 
+47 70 
+47 71 
+47 73 
+47 74 
+47 75 
+47 77 
+48 109 
+48 49 
+48 51 
+48 74 
+48 75 
+49 109 
+49 50 
+49 75 
+49 76 
+49 77 
+50 51 
+50 77 
+50 78 
+51 110 
+51 114 
+51 150 
+51 151 
+51 152 
+51 153 
+5 14 
+5 15 
+51 52 
+51 53 
+5 16 
+51 75 
+51 76 
+51 78 
+51 79 
+51 80 
+51 82 
+52 115 
+52 53 
+52 55 
+52 79 
+52 80 
+53 115 
+53 54 
+53 80 
+53 81 
+53 82 
+54 55 
+54 82 
+54 83 
+5 51 
+55 116 
+55 120 
+55 157 
+55 158 
+55 159 
+55 160 
+5 55 
+55 56 
+55 57 
+55 80 
+55 81 
+55 83 
+55 84 
+55 85 
+55 87 
+5 6 
+56 121 
+56 57 
+56 59 
+56 84 
+56 85 
+57 121 
+57 58 
+57 85 
+57 86 
+57 87 
+58 59 
+58 87 
+58 88 
+59 122 
+59 126 
+59 164 
+59 165 
+59 166 
+59 167 
+59 60 
+59 62 
+59 85 
+59 86 
+59 88 
+59 89 
+59 90 
+60 89 
+60 90 
+60 91 
+61 126 
+6 16 
+61 62 
+6 17 
+6 18 
+61 90 
+61 91 
+61 92 
+62 173 
+62 63 
+62 91 
+62 92 
+62 93 
+63 64 
+63 93 
+63 94 
+64 65 
+64 94 
+64 95 
+64 97 
+65 173 
+6 55 
+65 66 
+6 59 
+65 95 
+65 96 
+66 67 
+66 96 
+66 97 
+66 98 
+67 181 
+67 68 
+67 97 
+67 98 
+67 99 
+68 100 
+68 69 
+68 99 
+69 100 
+69 101 
+69 103 
+69 70 
+70 101 
+70 102 
+70 181 
+70 71 
+71 102 
+71 103 
+71 104 
+71 72 
+7 18 
+7 19 
+7 20 
+72 103 
+72 104 
+72 105 
+72 189 
+72 73 
+73 105 
+73 106 
+7 36 
+73 74 
+74 106 
+74 107 
+74 109 
+74 75 
+75 107 
+75 108 
+75 189 
+75 76 
+7 59 
+76 108 
+76 109 
+76 110 
+76 77 
+77 109 
+77 110 
+77 111 
+77 197 
+77 78 
+7 8 
+78 111 
+78 112 
+78 79 
+79 112 
+79 113 
+79 115 
+79 80 
+80 113 
+80 114 
+80 197 
+80 81 
+81 114 
+81 115 
+81 116 
+81 82 
+8 20 
+8 21 
+82 115 
+82 116 
+82 117 
+82 205 
+82 83 
+83 117 
+83 118 
+83 84 
+84 118 
+84 119 
+84 121 
+8 43 
+84 85 
+85 119 
+85 120 
+85 205 
+85 86 
+8 59 
+86 120 
+86 121 
+86 122 
+86 87 
+87 121 
+87 122 
+87 123 
+87 213 
+87 88 
+88 123 
+88 124 
+88 89 
+8 9 
+89 124 
+89 125 
+89 90 
+89 91 
+90 125 
+90 126 
+90 213 
+9 10 
+91 124 
+91 126 
+91 127 
+91 128 
+91 129 
+91 166 
+91 168 
+91 172 
+91 214 
+91 217 
+91 218 
+91 219 
+91 220 
+91 268 
+91 269 
+91 270 
+91 92 
+91 93 
+91 94 
+9 21 
+92 128 
+92 129 
+92 173 
+9 22 
+9 23 
+92 93 
+93 129 
+93 130 
+93 173 
+9 39 
+93 94 
+94 130 
+94 131 
+94 173 
+94 95 
+94 97 
+95 131 
+95 132 
+95 173 
+95 96 
+96 132 
+96 133 
+96 97 
+97 100 
+97 131 
+97 133 
+97 134 
+97 135 
+97 136 
+97 174 
+97 180 
+97 223 
+97 224 
+97 225 
+97 226 
+97 227 
+97 228 
+97 229 
+97 98 
+97 99 
+98 135 
+98 136 
+98 181 
+98 99 
+99 100 
+99 136 
+99 137 
+99 181 
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-3NN.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-3NN.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-3NN.txt	(revision 17960)
@@ -0,0 +1,582 @@
+0 1 2 
+0 1 6 
+0 2 3 
+0 3 4 
+0 4 5 
+0 5 6 
+100 101 138 
+100 137 138 
+101 102 139 
+10 11 24 
+101 138 139 
+102 103 140 
+102 139 140 
+10 23 24 
+103 104 142 
+103 140 141 
+103 141 142 
+104 105 143 
+104 142 143 
+105 106 144 
+105 143 144 
+106 107 145 
+106 144 145 
+107 108 146 
+107 145 146 
+108 109 147 
+108 146 147 
+109 110 149 
+109 147 148 
+109 148 149 
+110 111 150 
+110 149 150 
+111 112 151 
+111 150 151 
+11 12 26 
+112 113 152 
+112 151 152 
+11 24 25 
+11 25 26 
+113 114 153 
+113 152 153 
+114 115 154 
+114 153 154 
+115 116 156 
+115 154 155 
+115 155 156 
+116 117 157 
+116 156 157 
+117 118 158 
+117 157 158 
+118 119 159 
+118 158 159 
+119 120 160 
+119 159 160 
+120 121 161 
+120 160 161 
+121 122 163 
+121 161 162 
+121 162 163 
+12 13 27 
+122 123 164 
+122 163 164 
+12 26 27 
+123 124 165 
+123 164 165 
+124 125 166 
+124 165 166 
+125 126 167 
+125 166 167 
+126 167 168 
+127 128 170 
+127 168 216 
+127 169 170 
+127 169 216 
+1 2 8 
+128 129 171 
+128 170 171 
+129 130 172 
+129 171 172 
+130 131 173 
+130 172 173 
+131 132 174 
+131 173 174 
+13 14 29 
+132 133 175 
+132 174 175 
+13 27 28 
+13 28 29 
+133 134 176 
+133 175 176 
+134 135 178 
+134 176 177 
+134 177 178 
+135 136 179 
+135 178 179 
+136 137 180 
+136 179 180 
+137 138 181 
+137 180 181 
+138 139 182 
+138 181 182 
+139 140 183 
+139 182 183 
+140 141 184 
+140 183 184 
+141 142 186 
+141 184 185 
+141 185 186 
+14 15 30 
+142 143 187 
+142 186 187 
+14 29 30 
+143 144 188 
+143 187 188 
+144 145 189 
+144 188 189 
+145 146 190 
+145 189 190 
+146 147 191 
+146 190 191 
+147 148 192 
+147 191 192 
+148 149 194 
+148 192 193 
+148 193 194 
+149 150 195 
+149 194 195 
+150 151 196 
+150 195 196 
+151 152 197 
+151 196 197 
+15 16 32 
+152 153 198 
+152 197 198 
+15 30 31 
+15 31 32 
+153 154 199 
+153 198 199 
+154 155 200 
+154 199 200 
+155 156 202 
+155 200 201 
+155 201 202 
+156 157 203 
+156 202 203 
+157 158 204 
+157 203 204 
+158 159 205 
+158 204 205 
+159 160 206 
+159 205 206 
+160 161 207 
+160 206 207 
+161 162 208 
+161 207 208 
+16 17 33 
+1 6 18 
+162 163 210 
+162 208 209 
+162 209 210 
+163 164 211 
+163 210 211 
+16 32 33 
+164 165 212 
+164 211 212 
+165 166 213 
+165 212 213 
+166 167 214 
+166 213 214 
+167 168 215 
+167 214 215 
+168 215 216 
+169 170 218 
+169 216 270 
+169 217 218 
+169 217 270 
+170 171 219 
+170 218 219 
+171 172 220 
+171 219 220 
+1 7 18 
+17 18 35 
+172 173 221 
+172 220 221 
+173 174 222 
+173 221 222 
+17 33 34 
+17 34 35 
+174 175 223 
+174 222 223 
+175 176 224 
+175 223 224 
+176 177 225 
+176 224 225 
+177 178 227 
+177 225 226 
+177 226 227 
+1 7 8 
+178 179 228 
+178 227 228 
+179 180 229 
+179 228 229 
+180 181 230 
+180 229 230 
+181 182 231 
+181 230 231 
+182 183 232 
+182 231 232 
+183 184 233 
+183 232 233 
+18 35 36 
+184 185 234 
+184 233 234 
+185 186 236 
+185 234 235 
+185 235 236 
+186 187 237 
+186 236 237 
+187 188 238 
+187 237 238 
+188 189 239 
+188 238 239 
+189 190 240 
+189 239 240 
+190 191 241 
+190 240 241 
+191 192 242 
+191 241 242 
+19 20 38 
+192 193 243 
+192 242 243 
+193 194 245 
+193 243 244 
+193 244 245 
+19 36 60 
+19 37 38 
+19 37 60 
+194 195 246 
+194 245 246 
+195 196 247 
+195 246 247 
+196 197 248 
+196 247 248 
+197 198 249 
+197 248 249 
+198 199 250 
+198 249 250 
+199 200 251 
+199 250 251 
+200 201 252 
+200 251 252 
+201 202 254 
+201 252 253 
+201 253 254 
+20 21 39 
+202 203 255 
+202 254 255 
+203 204 256 
+203 255 256 
+20 38 39 
+204 205 257 
+204 256 257 
+205 206 258 
+205 257 258 
+206 207 259 
+206 258 259 
+207 208 260 
+207 259 260 
+208 209 261 
+208 260 261 
+209 210 263 
+209 261 262 
+209 262 263 
+210 211 264 
+210 263 264 
+211 212 265 
+211 264 265 
+212 213 266 
+21 22 40 
+212 265 266 
+213 214 267 
+213 266 267 
+21 39 40 
+214 215 268 
+214 267 268 
+215 216 269 
+215 268 269 
+216 269 270 
+219 220 274 
+220 221 275 
+220 274 275 
+221 222 276 
+221 275 276 
+222 223 277 
+222 276 277 
+22 23 42 
+223 224 278 
+223 277 278 
+22 40 41 
+22 41 42 
+228 229 284 
+229 230 285 
+229 284 285 
+230 231 286 
+230 285 286 
+2 3 10 
+231 232 287 
+231 286 287 
+232 233 288 
+232 287 288 
+23 24 43 
+23 42 43 
+237 238 294 
+238 239 295 
+238 294 295 
+239 240 296 
+239 295 296 
+240 241 297 
+240 296 297 
+241 242 298 
+241 297 298 
+24 25 44 
+24 43 44 
+246 247 304 
+247 248 305 
+247 304 305 
+248 249 306 
+248 305 306 
+249 250 307 
+249 306 307 
+250 251 308 
+250 307 308 
+25 26 46 
+25 44 45 
+25 45 46 
+255 256 314 
+256 257 315 
+256 314 315 
+257 258 316 
+257 315 316 
+258 259 317 
+258 316 317 
+259 260 318 
+259 317 318 
+26 27 47 
+264 265 324 
+26 46 47 
+265 266 325 
+265 324 325 
+266 267 326 
+266 325 326 
+267 268 327 
+267 326 327 
+268 269 328 
+268 327 328 
+27 28 48 
+274 275 335 
+27 47 48 
+275 276 336 
+275 335 336 
+276 277 337 
+276 336 337 
+277 278 338 
+277 337 338 
+28 29 50 
+284 285 346 
+28 48 49 
+28 49 50 
+285 286 347 
+285 346 347 
+286 287 348 
+286 347 348 
+287 288 349 
+287 348 349 
+2 8 9 
+2 9 10 
+29 30 51 
+294 295 357 
+29 50 51 
+295 296 358 
+295 357 358 
+296 297 359 
+296 358 359 
+297 298 360 
+297 359 360 
+30 31 52 
+304 305 368 
+30 51 52 
+305 306 369 
+305 368 369 
+306 307 370 
+306 369 370 
+307 308 371 
+307 370 371 
+3 10 11 
+3 11 12 
+31 32 54 
+314 315 379 
+31 52 53 
+315 316 380 
+31 53 54 
+315 379 380 
+316 317 381 
+316 380 381 
+317 318 382 
+317 381 382 
+32 33 55 
+324 325 390 
+325 326 391 
+325 390 391 
+32 54 55 
+326 327 392 
+326 391 392 
+327 328 393 
+327 392 393 
+33 34 56 
+33 55 56 
+3 4 12 
+34 35 58 
+34 56 57 
+34 57 58 
+35 36 59 
+35 58 59 
+36 59 60 
+37 38 62 
+37 60 90 
+37 61 62 
+37 61 90 
+38 39 63 
+38 62 63 
+39 40 64 
+39 63 64 
+40 41 65 
+40 64 65 
+4 12 13 
+4 13 14 
+41 42 67 
+41 65 66 
+41 66 67 
+42 43 68 
+42 67 68 
+43 44 69 
+43 68 69 
+44 45 70 
+44 69 70 
+4 5 14 
+45 46 72 
+45 70 71 
+45 71 72 
+46 47 73 
+46 72 73 
+47 48 74 
+47 73 74 
+48 49 75 
+48 74 75 
+49 50 77 
+49 75 76 
+49 76 77 
+50 51 78 
+50 77 78 
+5 14 15 
+5 15 16 
+51 52 79 
+51 78 79 
+52 53 80 
+52 79 80 
+53 54 82 
+53 80 81 
+53 81 82 
+54 55 83 
+54 82 83 
+55 56 84 
+55 83 84 
+5 6 16 
+56 57 85 
+56 84 85 
+57 58 87 
+57 85 86 
+57 86 87 
+58 59 88 
+58 87 88 
+59 60 89 
+59 88 89 
+60 89 90 
+6 16 17 
+61 62 92 
+6 17 18 
+61 90 126 
+61 91 126 
+61 91 92 
+62 63 93 
+62 92 93 
+63 64 94 
+63 93 94 
+64 65 95 
+64 94 95 
+65 66 96 
+65 95 96 
+66 67 98 
+66 96 97 
+66 97 98 
+67 68 99 
+67 98 99 
+68 69 100 
+68 99 100 
+69 100 101 
+69 70 101 
+70 101 102 
+70 71 102 
+71 102 103 
+71 103 104 
+71 72 104 
+7 18 36 
+7 19 20 
+7 19 36 
+72 104 105 
+72 73 105 
+73 105 106 
+73 74 106 
+74 106 107 
+74 75 107 
+75 107 108 
+75 76 108 
+76 108 109 
+76 109 110 
+76 77 110 
+77 110 111 
+77 78 111 
+78 111 112 
+7 8 20 
+78 79 112 
+79 112 113 
+79 80 113 
+80 113 114 
+80 81 114 
+81 114 115 
+81 115 116 
+81 82 116 
+8 20 21 
+82 116 117 
+82 83 117 
+83 117 118 
+83 84 118 
+84 118 119 
+84 85 119 
+85 119 120 
+85 86 120 
+86 120 121 
+86 121 122 
+86 87 122 
+87 122 123 
+87 88 123 
+88 123 124 
+88 89 124 
+89 124 125 
+8 9 21 
+89 90 125 
+90 125 126 
+9 10 23 
+91 126 168 
+91 127 128 
+91 127 168 
+91 92 128 
+9 21 22 
+92 128 129 
+9 22 23 
+92 93 129 
+93 129 130 
+93 94 130 
+94 130 131 
+94 95 131 
+95 131 132 
+95 96 132 
+96 132 133 
+96 97 133 
+97 133 134 
+97 134 135 
+97 98 135 
+98 135 136 
+98 99 136 
+99 100 137 
+99 136 137 
Index: branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-4NN.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-4NN.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/magic/magic-trigger-4NN.txt	(revision 17960)
@@ -0,0 +1,840 @@
+0 1 2 3 
+0 1 2 6 
+0 1 2 8 
+0 1 5 6 
+0 1 6 18 
+0 2 3 10 
+0 2 3 4 
+0 3 4 12 
+0 3 4 5 
+0 4 5 14 
+0 4 5 6 
+0 5 6 16 
+100 101 137 138 
+100 101 138 139 
+100 137 138 181 
+101 102 138 139 
+101 102 139 140 
+10 11 23 24 
+10 11 24 25 
+101 138 139 182 
+102 103 139 140 
+102 103 140 141 
+102 139 140 183 
+10 23 24 43 
+103 104 141 142 
+103 104 142 143 
+103 140 141 142 
+103 140 141 184 
+103 141 142 186 
+104 105 142 143 
+104 105 143 144 
+104 142 143 187 
+105 106 143 144 
+105 106 144 145 
+105 143 144 188 
+106 107 144 145 
+106 107 145 146 
+106 144 145 189 
+107 108 145 146 
+107 108 146 147 
+107 145 146 190 
+108 109 146 147 
+108 109 147 148 
+108 146 147 191 
+109 110 148 149 
+109 110 149 150 
+109 147 148 149 
+109 147 148 192 
+109 148 149 194 
+110 111 149 150 
+110 111 150 151 
+110 149 150 195 
+111 112 150 151 
+111 112 151 152 
+111 150 151 196 
+11 12 25 26 
+11 12 26 27 
+112 113 151 152 
+112 113 152 153 
+112 151 152 197 
+11 24 25 26 
+11 24 25 44 
+11 25 26 46 
+113 114 152 153 
+113 114 153 154 
+113 152 153 198 
+114 115 153 154 
+114 115 154 155 
+114 153 154 199 
+115 116 155 156 
+115 116 156 157 
+115 154 155 156 
+115 154 155 200 
+115 155 156 202 
+116 117 156 157 
+116 117 157 158 
+116 156 157 203 
+117 118 157 158 
+117 118 158 159 
+117 157 158 204 
+118 119 158 159 
+118 119 159 160 
+118 158 159 205 
+119 120 159 160 
+119 120 160 161 
+119 159 160 206 
+120 121 160 161 
+120 121 161 162 
+120 160 161 207 
+121 122 162 163 
+121 122 163 164 
+121 161 162 163 
+121 161 162 208 
+121 162 163 210 
+12 13 26 27 
+12 13 27 28 
+122 123 163 164 
+122 123 164 165 
+122 163 164 211 
+12 26 27 47 
+123 124 164 165 
+123 124 165 166 
+123 164 165 212 
+124 125 165 166 
+124 125 166 167 
+124 165 166 213 
+125 126 166 167 
+125 126 167 168 
+125 166 167 214 
+126 167 168 215 
+127 128 169 170 
+127 128 170 171 
+127 168 169 216 
+127 168 215 216 
+127 169 170 216 
+127 169 170 218 
+127 169 216 270 
+1 2 7 8 
+128 129 170 171 
+128 129 171 172 
+128 170 171 219 
+1 2 8 9 
+129 130 171 172 
+129 130 172 173 
+129 171 172 220 
+130 131 172 173 
+130 131 173 174 
+130 172 173 221 
+131 132 173 174 
+131 132 174 175 
+131 173 174 222 
+13 14 28 29 
+13 14 29 30 
+132 133 174 175 
+132 133 175 176 
+132 174 175 223 
+13 27 28 29 
+13 27 28 48 
+13 28 29 50 
+133 134 175 176 
+133 134 176 177 
+133 175 176 224 
+134 135 177 178 
+134 135 178 179 
+134 176 177 178 
+134 176 177 225 
+134 177 178 227 
+135 136 178 179 
+135 136 179 180 
+135 178 179 228 
+136 137 179 180 
+136 137 180 181 
+136 179 180 229 
+137 138 180 181 
+137 138 181 182 
+137 180 181 230 
+138 139 181 182 
+138 139 182 183 
+138 181 182 231 
+139 140 182 183 
+139 140 183 184 
+139 182 183 232 
+140 141 183 184 
+140 141 184 185 
+140 183 184 233 
+141 142 185 186 
+141 142 186 187 
+141 184 185 186 
+141 184 185 234 
+141 185 186 236 
+14 15 29 30 
+14 15 30 31 
+142 143 186 187 
+142 143 187 188 
+142 186 187 237 
+14 29 30 51 
+143 144 187 188 
+143 144 188 189 
+143 187 188 238 
+144 145 188 189 
+144 145 189 190 
+144 188 189 239 
+145 146 189 190 
+145 146 190 191 
+145 189 190 240 
+146 147 190 191 
+146 147 191 192 
+146 190 191 241 
+147 148 191 192 
+147 148 192 193 
+147 191 192 242 
+148 149 193 194 
+148 149 194 195 
+148 192 193 194 
+148 192 193 243 
+148 193 194 245 
+149 150 194 195 
+149 150 195 196 
+149 194 195 246 
+150 151 195 196 
+150 151 196 197 
+150 195 196 247 
+151 152 196 197 
+151 152 197 198 
+151 196 197 248 
+15 16 31 32 
+15 16 32 33 
+152 153 197 198 
+152 153 198 199 
+152 197 198 249 
+15 30 31 32 
+15 30 31 52 
+15 31 32 54 
+153 154 198 199 
+153 154 199 200 
+153 198 199 250 
+154 155 199 200 
+154 155 200 201 
+154 199 200 251 
+155 156 201 202 
+155 156 202 203 
+155 200 201 202 
+155 200 201 252 
+155 201 202 254 
+156 157 202 203 
+156 157 203 204 
+156 202 203 255 
+157 158 203 204 
+157 158 204 205 
+157 203 204 256 
+158 159 204 205 
+158 159 205 206 
+158 204 205 257 
+159 160 205 206 
+159 160 206 207 
+159 205 206 258 
+160 161 206 207 
+160 161 207 208 
+160 206 207 259 
+161 162 207 208 
+161 162 208 209 
+161 207 208 260 
+1 6 17 18 
+16 17 32 33 
+16 17 33 34 
+162 163 209 210 
+162 163 210 211 
+162 208 209 210 
+162 208 209 261 
+162 209 210 263 
+163 164 210 211 
+163 164 211 212 
+163 210 211 264 
+16 32 33 55 
+164 165 211 212 
+164 165 212 213 
+164 211 212 265 
+165 166 212 213 
+165 166 213 214 
+165 212 213 266 
+166 167 213 214 
+166 167 214 215 
+166 213 214 267 
+167 168 214 215 
+167 168 215 216 
+1 6 7 18 
+167 214 215 268 
+168 215 216 269 
+169 170 217 218 
+169 170 218 219 
+169 216 217 270 
+169 216 269 270 
+169 217 218 270 
+170 171 218 219 
+170 171 219 220 
+171 172 219 220 
+171 172 220 221 
+171 219 220 274 
+17 18 34 35 
+17 18 35 36 
+1 7 18 36 
+172 173 220 221 
+172 173 221 222 
+172 220 221 275 
+173 174 221 222 
+173 174 222 223 
+173 221 222 276 
+17 33 34 35 
+17 33 34 56 
+17 34 35 58 
+174 175 222 223 
+174 175 223 224 
+174 222 223 277 
+175 176 223 224 
+175 176 224 225 
+175 223 224 278 
+176 177 224 225 
+176 177 225 226 
+177 178 226 227 
+177 178 227 228 
+177 225 226 227 
+178 179 227 228 
+178 179 228 229 
+1 7 8 18 
+1 7 8 20 
+179 180 228 229 
+179 180 229 230 
+179 228 229 284 
+180 181 229 230 
+180 181 230 231 
+180 229 230 285 
+181 182 230 231 
+181 182 231 232 
+181 230 231 286 
+182 183 231 232 
+182 183 232 233 
+182 231 232 287 
+183 184 232 233 
+183 184 233 234 
+183 232 233 288 
+18 35 36 59 
+184 185 233 234 
+184 185 234 235 
+185 186 235 236 
+185 186 236 237 
+185 234 235 236 
+186 187 236 237 
+186 187 237 238 
+187 188 237 238 
+187 188 238 239 
+187 237 238 294 
+188 189 238 239 
+188 189 239 240 
+188 238 239 295 
+189 190 239 240 
+189 190 240 241 
+189 239 240 296 
+190 191 240 241 
+190 191 241 242 
+190 240 241 297 
+191 192 241 242 
+191 192 242 243 
+191 241 242 298 
+19 20 37 38 
+19 20 38 39 
+192 193 242 243 
+192 193 243 244 
+193 194 244 245 
+193 194 245 246 
+193 243 244 245 
+19 36 37 60 
+19 36 59 60 
+19 37 38 60 
+19 37 38 62 
+19 37 60 90 
+194 195 245 246 
+194 195 246 247 
+195 196 246 247 
+195 196 247 248 
+195 246 247 304 
+196 197 247 248 
+196 197 248 249 
+196 247 248 305 
+197 198 248 249 
+197 198 249 250 
+197 248 249 306 
+198 199 249 250 
+198 199 250 251 
+198 249 250 307 
+199 200 250 251 
+199 200 251 252 
+199 250 251 308 
+200 201 251 252 
+200 201 252 253 
+201 202 253 254 
+201 202 254 255 
+201 252 253 254 
+20 21 38 39 
+20 21 39 40 
+202 203 254 255 
+202 203 255 256 
+203 204 255 256 
+203 204 256 257 
+203 255 256 314 
+20 38 39 63 
+204 205 256 257 
+204 205 257 258 
+204 256 257 315 
+205 206 257 258 
+205 206 258 259 
+205 257 258 316 
+206 207 258 259 
+206 207 259 260 
+206 258 259 317 
+207 208 259 260 
+207 208 260 261 
+207 259 260 318 
+208 209 260 261 
+208 209 261 262 
+209 210 262 263 
+209 210 263 264 
+209 261 262 263 
+210 211 263 264 
+210 211 264 265 
+211 212 264 265 
+211 212 265 266 
+211 264 265 324 
+212 213 265 266 
+212 213 266 267 
+21 22 39 40 
+21 22 40 41 
+212 265 266 325 
+213 214 266 267 
+213 214 267 268 
+213 266 267 326 
+21 39 40 64 
+214 215 267 268 
+214 215 268 269 
+214 267 268 327 
+215 216 268 269 
+215 216 269 270 
+215 268 269 328 
+219 220 274 275 
+220 221 274 275 
+220 221 275 276 
+220 274 275 335 
+221 222 275 276 
+221 222 276 277 
+221 275 276 336 
+222 223 276 277 
+222 223 277 278 
+222 276 277 337 
+22 23 41 42 
+22 23 42 43 
+223 224 277 278 
+223 277 278 338 
+22 40 41 42 
+22 40 41 65 
+22 41 42 67 
+228 229 284 285 
+229 230 284 285 
+229 230 285 286 
+229 284 285 346 
+230 231 285 286 
+230 231 286 287 
+230 285 286 347 
+2 3 10 11 
+231 232 286 287 
+231 232 287 288 
+231 286 287 348 
+232 233 287 288 
+232 287 288 349 
+23 24 42 43 
+23 24 43 44 
+23 42 43 68 
+237 238 294 295 
+238 239 294 295 
+238 239 295 296 
+238 294 295 357 
+2 3 9 10 
+239 240 295 296 
+239 240 296 297 
+239 295 296 358 
+240 241 296 297 
+240 241 297 298 
+240 296 297 359 
+241 242 297 298 
+241 297 298 360 
+24 25 43 44 
+24 25 44 45 
+24 43 44 69 
+246 247 304 305 
+247 248 304 305 
+247 248 305 306 
+247 304 305 368 
+248 249 305 306 
+248 249 306 307 
+248 305 306 369 
+249 250 306 307 
+249 250 307 308 
+249 306 307 370 
+250 251 307 308 
+250 307 308 371 
+25 26 45 46 
+25 26 46 47 
+25 44 45 46 
+25 44 45 70 
+25 45 46 72 
+255 256 314 315 
+256 257 314 315 
+256 257 315 316 
+256 314 315 379 
+257 258 315 316 
+257 258 316 317 
+257 315 316 380 
+258 259 316 317 
+258 259 317 318 
+258 316 317 381 
+259 260 317 318 
+259 317 318 382 
+26 27 46 47 
+26 27 47 48 
+264 265 324 325 
+26 46 47 73 
+265 266 324 325 
+265 266 325 326 
+265 324 325 390 
+266 267 325 326 
+266 267 326 327 
+266 325 326 391 
+267 268 326 327 
+267 268 327 328 
+267 326 327 392 
+268 269 327 328 
+268 327 328 393 
+27 28 47 48 
+27 28 48 49 
+274 275 335 336 
+27 47 48 74 
+275 276 335 336 
+275 276 336 337 
+276 277 336 337 
+276 277 337 338 
+277 278 337 338 
+28 29 49 50 
+28 29 50 51 
+284 285 346 347 
+28 48 49 50 
+28 48 49 75 
+28 49 50 77 
+285 286 346 347 
+285 286 347 348 
+286 287 347 348 
+286 287 348 349 
+287 288 348 349 
+2 8 9 10 
+2 8 9 21 
+2 9 10 23 
+29 30 50 51 
+29 30 51 52 
+294 295 357 358 
+29 50 51 78 
+295 296 357 358 
+295 296 358 359 
+296 297 358 359 
+296 297 359 360 
+297 298 359 360 
+30 31 51 52 
+30 31 52 53 
+304 305 368 369 
+30 51 52 79 
+305 306 368 369 
+305 306 369 370 
+306 307 369 370 
+306 307 370 371 
+307 308 370 371 
+3 10 11 12 
+3 10 11 24 
+3 11 12 26 
+31 32 53 54 
+31 32 54 55 
+314 315 379 380 
+31 52 53 54 
+31 52 53 80 
+315 316 379 380 
+315 316 380 381 
+31 53 54 82 
+316 317 380 381 
+316 317 381 382 
+317 318 381 382 
+32 33 54 55 
+32 33 55 56 
+324 325 390 391 
+325 326 390 391 
+325 326 391 392 
+32 54 55 83 
+326 327 391 392 
+326 327 392 393 
+327 328 392 393 
+33 34 55 56 
+33 34 56 57 
+33 55 56 84 
+3 4 11 12 
+3 4 12 13 
+34 35 57 58 
+34 35 58 59 
+34 56 57 58 
+34 56 57 85 
+34 57 58 87 
+35 36 58 59 
+35 36 59 60 
+35 58 59 88 
+36 59 60 89 
+37 38 61 62 
+37 38 62 63 
+37 60 61 90 
+37 60 89 90 
+37 61 62 90 
+37 61 62 92 
+37 61 90 126 
+38 39 62 63 
+38 39 63 64 
+38 62 63 93 
+39 40 63 64 
+39 40 64 65 
+39 63 64 94 
+40 41 64 65 
+40 41 65 66 
+40 64 65 95 
+4 12 13 14 
+4 12 13 27 
+4 13 14 29 
+41 42 66 67 
+41 42 67 68 
+41 65 66 67 
+41 65 66 96 
+41 66 67 98 
+42 43 67 68 
+42 43 68 69 
+42 67 68 99 
+43 44 68 69 
+43 44 69 70 
+43 68 69 100 
+44 45 69 70 
+44 45 70 71 
+44 69 70 101 
+4 5 13 14 
+4 5 14 15 
+45 46 71 72 
+45 46 72 73 
+45 70 71 102 
+45 70 71 72 
+45 71 72 104 
+46 47 72 73 
+46 47 73 74 
+46 72 73 105 
+47 48 73 74 
+47 48 74 75 
+47 73 74 106 
+48 49 74 75 
+48 49 75 76 
+48 74 75 107 
+49 50 76 77 
+49 50 77 78 
+49 75 76 108 
+49 75 76 77 
+49 76 77 110 
+50 51 77 78 
+50 51 78 79 
+50 77 78 111 
+5 14 15 16 
+5 14 15 30 
+5 15 16 32 
+51 52 78 79 
+51 52 79 80 
+51 78 79 112 
+52 53 79 80 
+52 53 80 81 
+52 79 80 113 
+53 54 81 82 
+53 54 82 83 
+53 80 81 114 
+53 80 81 82 
+53 81 82 116 
+54 55 82 83 
+54 55 83 84 
+54 82 83 117 
+55 56 83 84 
+55 56 84 85 
+55 83 84 118 
+5 6 15 16 
+5 6 16 17 
+56 57 84 85 
+56 57 85 86 
+56 84 85 119 
+57 58 86 87 
+57 58 87 88 
+57 85 86 120 
+57 85 86 87 
+57 86 87 122 
+58 59 87 88 
+58 59 88 89 
+58 87 88 123 
+59 60 88 89 
+59 60 89 90 
+59 88 89 124 
+60 89 90 125 
+6 16 17 18 
+6 16 17 33 
+61 62 91 92 
+61 62 92 93 
+6 17 18 35 
+61 90 125 126 
+61 90 91 126 
+61 91 126 168 
+61 91 92 126 
+61 91 92 128 
+62 63 92 93 
+62 63 93 94 
+62 92 93 129 
+63 64 93 94 
+63 64 94 95 
+63 93 94 130 
+64 65 94 95 
+64 65 95 96 
+64 94 95 131 
+65 66 95 96 
+65 66 96 97 
+65 95 96 132 
+66 67 97 98 
+66 67 98 99 
+66 96 97 133 
+66 96 97 98 
+66 97 98 135 
+67 68 98 99 
+67 68 99 100 
+67 98 99 136 
+68 69 100 101 
+68 69 99 100 
+68 99 100 137 
+69 100 101 138 
+69 70 100 101 
+69 70 101 102 
+70 101 102 139 
+70 71 101 102 
+70 71 102 103 
+71 102 103 104 
+71 102 103 140 
+71 103 104 142 
+71 72 103 104 
+71 72 104 105 
+7 18 19 36 
+7 18 35 36 
+7 19 20 36 
+7 19 20 38 
+7 19 36 60 
+72 104 105 143 
+72 73 104 105 
+72 73 105 106 
+73 105 106 144 
+73 74 105 106 
+73 74 106 107 
+74 106 107 145 
+74 75 106 107 
+74 75 107 108 
+75 107 108 146 
+75 76 107 108 
+75 76 108 109 
+76 108 109 110 
+76 108 109 147 
+76 109 110 149 
+76 77 109 110 
+76 77 110 111 
+77 110 111 150 
+77 78 110 111 
+77 78 111 112 
+78 111 112 151 
+7 8 19 20 
+7 8 20 21 
+78 79 111 112 
+78 79 112 113 
+79 112 113 152 
+79 80 112 113 
+79 80 113 114 
+80 113 114 153 
+80 81 113 114 
+80 81 114 115 
+81 114 115 116 
+81 114 115 154 
+81 115 116 156 
+81 82 115 116 
+81 82 116 117 
+8 20 21 39 
+82 116 117 157 
+82 83 116 117 
+82 83 117 118 
+83 117 118 158 
+83 84 117 118 
+83 84 118 119 
+84 118 119 159 
+84 85 118 119 
+84 85 119 120 
+85 119 120 160 
+85 86 119 120 
+85 86 120 121 
+86 120 121 122 
+86 120 121 161 
+86 121 122 163 
+86 87 121 122 
+86 87 122 123 
+87 122 123 164 
+87 88 122 123 
+87 88 123 124 
+88 123 124 165 
+88 89 123 124 
+88 89 124 125 
+89 124 125 166 
+8 9 20 21 
+8 9 21 22 
+89 90 124 125 
+89 90 125 126 
+90 125 126 167 
+9 10 22 23 
+9 10 23 24 
+91 126 127 168 
+91 126 167 168 
+91 127 128 168 
+91 127 128 170 
+91 127 168 216 
+91 92 127 128 
+91 92 128 129 
+9 21 22 23 
+9 21 22 40 
+92 128 129 171 
+9 22 23 42 
+92 93 128 129 
+92 93 129 130 
+93 129 130 172 
+93 94 129 130 
+93 94 130 131 
+94 130 131 173 
+94 95 130 131 
+94 95 131 132 
+95 131 132 174 
+95 96 131 132 
+95 96 132 133 
+96 132 133 175 
+96 97 132 133 
+96 97 133 134 
+97 133 134 135 
+97 133 134 176 
+97 134 135 178 
+97 98 134 135 
+97 98 135 136 
+98 135 136 179 
+98 99 135 136 
+98 99 136 137 
+99 100 136 137 
+99 100 137 138 
+99 136 137 180 
Index: branches/Mars_McMismatchStudy/resmc/night-sky-la-palma.txt
===================================================================
--- branches/Mars_McMismatchStudy/resmc/night-sky-la-palma.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resmc/night-sky-la-palma.txt	(revision 17960)
@@ -0,0 +1,1056 @@
+250.014 0.800477
+260.014 0.800477
+270.014 0.800477
+280.014 0.800477
+290.014 0.800477
+311.014 0.800477
+321.014 0.900477
+331.014 1.300477
+341.014 1.500477
+346.014 1.400477
+350.014 0.650477
+351.014 0.600477
+351.594 0.790559
+352.174 0.817864
+352.754 1.72687
+353.333 2.17965
+353.913 3.15677
+354.493 2.3622
+355.072 2.84384
+355.652 2.64883
+356.232 2.25675
+356.812 1.30812
+357.391 1.5174
+357.971 0.763332
+358.551 1.47381
+359.13 1.35968
+359.71 0.970784
+360.29 0.385688
+360.87 1.20294
+361.449 1.14437
+362.029 1.56325
+362.609 1.80576
+363.188 2.09278
+363.768 2.08063
+364.348 1.57732
+364.928 1.73802
+365.507 1.48751
+366.087 1.30638
+366.667 1.06186
+367.246 0.951596
+367.826 1.28396
+368.406 1.54215
+368.986 1.07401
+369.565 1.30309
+370.145 1.34888
+370.725 1.78687
+371.304 1.34982
+371.884 1.30309
+372.464 1.88863
+373.043 2.03467
+373.623 2.38421
+374.203 2.06903
+374.783 1.88457
+375.362 1.57732
+375.942 2.09278
+376.522 2.09278
+377.101 1.84677
+377.681 2.18803
+378.261 1.43243
+378.841 1.06186
+379.42 1.53294
+380 2.19191
+380.58 1.86504
+381.159 1.52089
+381.739 1.88482
+382.319 1.88409
+382.899 1.83505
+383.478 2.19812
+384.058 2.20885
+384.638 1.60353
+385.217 0.932006
+385.797 1.06186
+386.377 1.31959
+386.957 1.00041
+387.536 0.735206
+388.116 0.69447
+388.696 1.02703
+389.275 1.67438
+389.855 1.88482
+390.435 1.93853
+391.014 1.79855
+391.594 1.41249
+392.174 2.49735
+392.754 7.38119
+393.333 6.15931
+393.913 7.70165
+394.493 2.97863
+395.072 1.8909
+395.652 1.39714
+396.232 1.40765
+396.812 1.26982
+397.391 1.31959
+397.971 1.57732
+398.551 1.56621
+399.13 1.25935
+399.71 1.53544
+400.87 2.60825
+401.449 2.02782
+402.029 1.96907
+402.609 2.29094
+403.188 2.49029
+403.768 3.31409
+404.348 3.1445
+404.928 3.67122
+405.507 3.01399
+406.087 2.91575
+406.667 2.94285
+407.246 2.61936
+407.826 2.29248
+408.406 2.66079
+408.986 2.31192
+409.565 1.84651
+410.145 2.26986
+410.725 2.05305
+411.304 2.05653
+411.884 2.05703
+412.464 2.09278
+413.043 2.60825
+413.623 2.12761
+414.203 2.48597
+414.783 2.17986
+415.362 2.58449
+415.942 3.2583
+416.522 3.52439
+417.101 3.1126
+417.681 3.47758
+418.261 3.12371
+418.841 2.53188
+419.42 2.69254
+420 2.86794
+420.58 2.38121
+421.159 2.06385
+421.739 2.09278
+422.319 2.10494
+422.899 1.79426
+423.478 2.21439
+424.058 1.92404
+424.638 2.09278
+425.217 2.65481
+425.797 3.24531
+426.377 3.10964
+426.957 2.94544
+427.536 2.20757
+428.116 2.26693
+428.696 2.39956
+429.275 2.35052
+429.855 2.72267
+430.435 2.32886
+431.014 2.38403
+431.594 2.93163
+432.174 3.12371
+432.754 2.62232
+433.333 2.40666
+433.913 2.55193
+434.493 4.17461
+435.072 4.04616
+435.652 5.0667
+436.232 4.22379
+436.812 3.86105
+437.391 2.53719
+437.971 2.55944
+438.551 2.60825
+439.13 3.24115
+439.71 3.41008
+440.29 3.8619
+440.87 3.82629
+441.449 3.69268
+442.029 3.23343
+442.609 3.12371
+443.188 3.29338
+443.768 3.4923
+444.348 3.33068
+444.928 3.16149
+445.507 2.88247
+446.087 3.24531
+446.667 2.95135
+447.246 3.27059
+447.826 3.13532
+448.406 2.86598
+448.986 3.16149
+449.565 3.79291
+450.145 3.62429
+450.725 3.03391
+451.304 3.14992
+451.884 3.15825
+452.464 3.63918
+453.043 3.97445
+453.623 3.61542
+454.203 3.68355
+454.783 3.5948
+455.362 3.36266
+455.942 3.73911
+456.522 3.32631
+457.101 3.83126
+457.681 3.63918
+458.261 4.01804
+458.841 3.65133
+459.42 3.84172
+460 3.95073
+460.58 3.55489
+461.159 3.6014
+461.739 3.55149
+462.319 3.57773
+462.899 3.4923
+463.478 3.80635
+464.058 3.82799
+464.638 3.74889
+465.217 3.57773
+465.797 3.78406
+466.377 3.45841
+466.957 3.63918
+467.536 4.18085
+468.116 4.01804
+468.696 4.15464
+469.275 3.70296
+469.855 3.38144
+470.435 3.58102
+471.014 4.20584
+471.594 3.82446
+472.174 4.01001
+472.754 4.0153
+473.333 3.63918
+473.913 3.63918
+474.493 3.7738
+475.072 4.15464
+475.652 4.62907
+476.232 4.76668
+476.812 4.48129
+477.391 4.3343
+477.971 4.15464
+478.551 4.40447
+479.13 4.03304
+479.71 4.6701
+480.29 3.63918
+480.87 3.97357
+481.449 4.08505
+482.029 4.43678
+482.609 4.96319
+483.768 5.26193
+484.348 4.14128
+484.928 3.89457
+485.507 3.67146
+486.087 3.74943
+486.667 3.78844
+487.246 4.15464
+487.826 4.74566
+488.406 5.22458
+488.986 5.04468
+489.565 4.92783
+490.145 4.46774
+490.725 4.48954
+491.304 4.6701
+491.884 4.15464
+492.464 4.48992
+493.043 4.46141
+493.623 4.11361
+494.203 4.75747
+494.783 5.18557
+495.362 4.68171
+495.942 4.97688
+496.522 4.88704
+497.101 5.03132
+497.681 4.74983
+498.261 4.11686
+498.841 3.80077
+499.42 4.14303
+500 4.4704
+500.58 4.4704
+501.159 4.74983
+501.739 4.73507
+502.319 4.55532
+502.899 4.6701
+503.478 4.6701
+504.058 4.52202
+504.638 4.37158
+505.217 4.32878
+505.797 4.3626
+506.377 4.3355
+506.957 4.6474
+507.536 4.9776
+508.116 4.63527
+508.696 4.32878
+509.275 4.30889
+509.855 4.09821
+510.435 4.14303
+511.014 4.39948
+511.594 4.43692
+512.174 4.42526
+512.754 4.15464
+513.333 4.15464
+513.913 4.15464
+514.493 4.15464
+515.072 4.15464
+515.652 4.6474
+516.232 4.91495
+516.812 4.91858
+517.391 5.22604
+517.971 5.81129
+518.551 5.98805
+519.13 5.90899
+519.71 5.94227
+520.29 5.71319
+520.87 5.10842
+521.449 4.91134
+522.029 4.91495
+522.609 5.22994
+523.188 5.54678
+523.768 5.37438
+524.348 5.18557
+524.928 5.47259
+525.507 5.22905
+526.087 4.96863
+526.667 4.9776
+527.246 4.9776
+527.826 4.91495
+528.406 4.6701
+528.986 4.77982
+529.565 4.85892
+530.145 5.13676
+530.725 5.70103
+531.304 5.8819
+531.884 5.70103
+532.464 5.91797
+533.043 6.00853
+533.623 6.02768
+534.203 5.79761
+534.783 5.70103
+535.362 5.70103
+535.942 5.52046
+536.522 5.52046
+537.101 5.49307
+537.681 5.50835
+538.261 5.59985
+538.841 5.18557
+539.42 5.58015
+540 5.39353
+540.58 5.48409
+541.159 5.52046
+541.739 5.50133
+542.319 5.33982
+542.899 5.72174
+543.478 6.45252
+544.058 6.38324
+544.638 7.66951
+545.217 7.71453
+545.797 7.97983
+546.377 7.78141
+546.957 6.91994
+547.536 6.87478
+548.116 6.73196
+548.696 6.20689
+549.275 5.80221
+549.855 5.90899
+550.435 5.9797
+551.014 5.90899
+551.594 5.8386
+552.174 5.70103
+552.754 5.70103
+553.333 6.16443
+553.913 6.78316
+554.493 9.75775
+555.072 15.537
+555.652 34.2691
+556.232 39.5102
+556.812 59.2689
+557.391 64.412
+557.971 54.1549
+558.551 35.913
+559.13 28.9918
+559.71 12.2252
+560.29 8.45154
+560.87 6.73196
+561.449 6.93166
+562.029 7.00141
+562.609 6.67989
+563.188 6.37074
+563.768 6.50792
+564.348 6.50351
+564.928 6.75467
+565.507 7.06656
+566.087 7.00258
+566.667 7.24742
+567.246 7.54595
+567.826 7.45539
+568.406 7.49344
+568.986 7.60864
+569.565 7.27971
+570.145 6.73196
+570.725 6.88004
+571.304 7.01424
+571.884 6.98043
+572.464 7.08583
+573.043 6.73196
+573.623 7.3746
+574.203 7.19536
+574.783 7.44492
+575.362 7.74018
+575.942 8.02062
+576.522 8.25564
+577.101 8.56063
+577.681 8.51154
+578.261 8.59412
+578.841 8.79381
+579.42 7.88377
+580 7.72932
+580.58 7.52535
+581.159 7.642
+581.739 7.8212
+582.319 8.16863
+582.899 8.07865
+583.478 7.7306
+584.058 7.24742
+584.638 8.04125
+585.217 8.36343
+585.797 9.94521
+586.377 12.0639
+586.957 16.3176
+587.536 20.4668
+588.116 25.8064
+588.696 29.3807
+589.275 29.3102
+589.855 23.1
+590.435 21.595
+591.014 15.2585
+591.594 12.9361
+592.174 11.3938
+592.754 11.1909
+593.333 10.8764
+593.913 10.835
+594.493 10.4499
+595.072 10.6582
+595.652 10.3195
+596.232 9.97282
+596.812 10.0825
+597.391 9.76309
+597.971 9.95192
+598.551 9.29817
+599.13 8.94189
+599.71 9.14768
+600.29 8.8261
+600.87 8.38343
+601.449 8.51154
+602.029 8.58585
+602.609 8.50239
+603.188 8.605
+603.768 8.31318
+604.348 8.10868
+604.928 8.27835
+605.507 7.24742
+606.087 7.24742
+606.667 7.4401
+607.246 7.42829
+607.826 7.24742
+608.406 8.17327
+608.986 8.08954
+609.565 8.27835
+610.145 8.16863
+610.725 8.07039
+611.304 8.27835
+611.884 8.17327
+612.464 8.38186
+613.043 8.47586
+613.623 9.61242
+614.203 10.3052
+614.783 10.6869
+615.362 10.8557
+615.942 10.6134
+616.522 10.3186
+617.101 9.57928
+617.681 9.62084
+618.261 8.27835
+618.841 8.75033
+619.42 8.95541
+620 9.29817
+620.58 9.63593
+621.159 9.82474
+621.739 10.7321
+622.319 11.4407
+622.899 11.8267
+623.478 12.4137
+624.058 13.0447
+624.638 12.9175
+625.217 12.2959
+625.797 12.115
+626.377 12.2923
+626.957 14.9133
+627.536 21.1287
+628.116 36.6867
+628.696 41.3354
+629.275 57.6942
+629.855 59.1521
+630.435 51.2687
+631.014 34.9122
+631.594 27.8569
+632.174 14.5532
+632.754 12.1075
+633.333 11.2123
+633.913 13.7866
+634.493 19.0633
+635.072 20.1133
+635.652 25.8978
+636.232 26.0465
+636.812 20.1411
+637.391 19.3843
+637.971 13.1583
+638.551 10.2015
+639.13 8.32889
+639.71 8.13027
+640.29 8.27835
+640.87 8.27835
+641.449 8.27835
+642.029 8.17717
+642.609 7.8212
+643.188 7.71034
+643.768 8.63631
+644.348 9.31677
+644.928 11.0567
+645.507 10.9788
+646.087 11.8866
+646.667 11.3317
+647.246 11.1218
+647.826 10.6636
+648.406 10.9853
+648.986 11.3526
+649.565 11.8988
+650.145 11.5231
+650.725 11.1334
+651.304 10.6558
+651.884 10.3551
+652.464 10.9293
+653.043 11.3354
+653.623 11.9449
+654.203 12.3009
+654.783 12.2024
+655.362 12.5102
+655.942 12.3731
+656.522 11.8866
+657.101 11.0804
+657.681 10.654
+658.261 10.2695
+658.841 9.33821
+659.42 9.19449
+660 9.06443
+660.58 8.75806
+661.159 8.26107
+661.739 7.97085
+662.319 7.86796
+662.899 8.24606
+663.478 8.29906
+664.058 7.97085
+664.638 8.04516
+665.217 8.13027
+665.797 7.76289
+666.377 7.40167
+666.957 7.3525
+667.536 7.36831
+668.116 7.76289
+668.696 7.52535
+669.275 7.72511
+669.855 7.99133
+670.435 8.06141
+671.014 8.27835
+671.594 8.14078
+672.174 7.774
+672.754 7.43624
+673.333 7.45539
+673.913 7.4401
+674.493 7.45539
+675.072 7.65317
+675.652 7.50515
+676.232 7.35714
+676.812 7.55492
+677.391 7.56319
+677.971 7.53885
+678.551 7.55492
+679.13 7.55492
+679.71 7.81932
+680.29 9.65148
+680.87 11.3051
+681.449 14.5364
+682.029 16.5313
+682.609 18.8741
+683.188 18.4397
+683.768 17.8652
+684.348 16.3563
+684.928 17.4229
+685.507 17.5141
+686.087 18.0528
+686.667 16.3282
+687.246 15.7171
+687.826 13.8877
+688.406 12.725
+688.986 13.0041
+689.565 13.9203
+690.145 14.9206
+690.725 15.1415
+691.304 16.0103
+691.884 16.1584
+692.464 16.2809
+693.043 16.1719
+693.623 16.4814
+694.203 16.4533
+694.783 15.8885
+695.362 15.3143
+695.942 14.2308
+696.522 13.8519
+697.101 13.7062
+697.681 13.391
+698.261 12.6206
+698.841 12.5406
+699.42 12.178
+700 12.2478
+700.58 11.64
+701.159 10.9589
+701.739 9.8549
+702.319 9.38564
+702.899 9.14054
+703.478 9.77268
+704.058 9.98634
+704.638 10.2819
+705.217 9.97252
+705.797 9.92132
+706.377 9.67666
+706.957 9.64388
+707.536 9.51724
+708.116 9.52622
+708.696 9.24783
+709.275 8.69724
+709.855 8.63311
+710.435 8.24352
+711.014 8.48704
+711.594 8.75033
+712.174 8.95541
+712.754 9.25721
+713.333 9.55412
+713.913 9.30928
+714.493 9.30928
+715.072 9.5963
+715.652 9.82474
+716.232 9.82474
+716.812 8.79381
+717.391 9.05155
+717.971 8.86507
+718.551 8.22954
+719.13 8.29906
+719.71 8.63957
+720.29 8.87248
+720.87 9.3305
+721.449 15.637
+722.029 20.1401
+722.609 28.6894
+723.188 33.0478
+723.768 38.4977
+724.348 33.1741
+724.928 34.2699
+725.507 29.8928
+726.087 34.2373
+726.667 34.2889
+727.246 37.9426
+727.826 33.7338
+728.406 32.8606
+728.986 28.6109
+729.565 29.0202
+730.145 29.3213
+730.725 32.2093
+731.304 34.2558
+731.884 34.3695
+732.464 36.1769
+733.043 35.634
+733.623 33.8883
+734.203 32.9167
+734.783 31.33
+735.362 29.8979
+735.942 28.4604
+736.522 26.3706
+737.101 24.3426
+737.681 22.4484
+738.261 20.933
+738.841 21.3864
+739.42 21.8313
+740 19.1661
+740.58 18.5118
+741.159 16.6295
+741.739 15.6363
+742.319 15.4449
+742.899 15.8667
+743.478 15.4146
+744.058 15.6517
+744.638 15.9859
+745.217 18.4977
+745.797 20.7169
+746.377 24.0519
+746.957 25.8541
+747.536 23.9817
+748.116 21.1378
+748.696 17.8534
+749.275 16.2876
+749.855 17.0713
+750.435 21.7365
+751.014 23.9927
+751.594 28.8293
+752.174 27.5174
+752.754 25.3872
+753.333 21.0108
+753.913 18.8854
+754.493 18.5931
+755.072 20.9298
+755.652 22.2347
+756.232 25.2723
+756.812 25.7506
+757.391 23.2869
+757.971 21.6081
+758.551 18.7737
+759.13 16.1576
+759.71 14.8936
+760.29 14.111
+760.87 14.865
+761.449 15.7166
+762.029 14.9983
+762.609 14.3403
+763.188 12.9534
+763.768 12.9258
+764.348 14.4084
+764.928 14.856
+765.507 15.2049
+766.087 14.4824
+766.667 13.9169
+767.246 13.8262
+767.826 15.7917
+768.406 21.0755
+768.986 30.6862
+769.565 38.484
+770.145 45.6146
+770.725 53.9026
+771.304 48.2944
+771.884 48.9772
+772.464 40.7157
+773.043 42.2932
+773.623 44.9167
+774.203 53.3396
+774.783 63.4209
+775.362 67.1626
+775.942 75.1938
+776.522 76.6821
+777.101 71.6165
+777.681 61.3182
+778.261 59.5181
+778.841 49.1038
+779.42 46.4721
+780 45.7293
+780.58 46.372
+781.159 45.7281
+781.739 43.2748
+782.319 42.2241
+782.899 47.5645
+783.478 54.2501
+784.058 61.4242
+784.638 69.7246
+785.217 71.7094
+785.797 70.2685
+786.377 63.8373
+786.957 55.3266
+787.536 51.677
+788.116 45.8456
+788.696 49.3286
+789.275 54.1389
+789.855 65.8969
+790.435 71.46
+791.014 74.519
+791.594 61.2674
+792.174 57.2467
+792.754 44.4853
+793.333 38.2027
+793.913 41.1907
+794.493 43.6893
+795.072 49.8505
+795.652 54.6016
+796.232 57.742
+796.812 60.5992
+797.391 60.7104
+797.971 59.5874
+798.551 56.3547
+799.13 50.9674
+799.71 47.3366
+800.29 45.6159
+800.87 44.6832
+801.449 46.5385
+802.029 40.6538
+802.609 36.8755
+803.188 31.398
+803.768 27.8589
+804.348 27.4822
+804.928 29.3532
+805.507 27.1221
+806.087 25.1291
+806.667 21.7734
+807.246 19.052
+807.826 18.512
+808.406 19.7206
+808.986 20.5909
+809.565 18.743
+810.145 17.4667
+810.725 15.9447
+811.304 14.3856
+811.884 14.662
+812.464 15.2577
+813.043 15.8025
+813.623 15.4659
+814.203 13.8491
+814.783 14.0153
+815.362 12.3152
+815.942 13.0334
+816.522 14.2521
+817.101 16.1205
+817.681 16.899
+818.261 17.4205
+818.841 17.0197
+819.42 15.5314
+820 14.7387
+820.58 13.8677
+821.159 13.2426
+821.739 12.9175
+822.319 12.9765
+822.899 12.9175
+823.478 13.5005
+824.058 14.6433
+824.638 19.5446
+825.217 28.5358
+825.797 42.6672
+826.377 60.0186
+826.957 77.8219
+827.536 95.9089
+828.116 102.099
+828.696 94.9218
+829.275 78.75
+829.855 60.2716
+830.435 51.8195
+831.014 36.7166
+831.594 63.471
+832.174 70.6965
+832.754 102.346
+833.333 116.413
+833.913 115.91
+834.493 97.2797
+835.072 81.3286
+835.652 61.6605
+836.232 49.5733
+836.812 61.2955
+837.391 62.4773
+837.971 78.0635
+838.551 89.0819
+839.13 92.8436
+839.71 89.4163
+840.29 94.8599
+840.87 91.0374
+841.449 102.8
+842.029 105.877
+842.609 100.947
+843.188 91.777
+843.768 94.1602
+844.348 87.2941
+844.928 86.0332
+845.507 75.8283
+846.087 63.7297
+846.667 50.1956
+847.246 45.8875
+847.826 43.4738
+848.406 49.5997
+848.986 51.9194
+849.565 47.2826
+850.145 36.4516
+850.725 32.3637
+851.304 23.4339
+851.884 25.1516
+852.464 26.8526
+853.043 30.2968
+853.623 30.16
+854.203 25.9995
+854.783 23.1355
+855.362 18.692
+855.942 16.025
+856.522 17.0069
+857.101 19.5337
+857.681 20.0135
+858.261 23.1367
+858.841 25.7826
+859.42 32.514
+860 38.8799
+860.58 50.0294
+861.159 54.5849
+861.739 62.4711
+862.319 62.7262
+862.899 62.1884
+863.478 63.3225
+864.058 65.827
+864.638 65.7299
+865.217 63.0209
+865.797 54.0712
+866.377 48.4893
+866.957 38.977
+867.536 31.6818
+868.116 26.2303
+868.696 21.9726
+869.275 18.8798
+869.855 16.7428
+870.435 15.7515
+871.014 14.231
+871.594 14.9983
+872.174 20.936
+872.754 36.5435
+873.333 61.783
+873.913 91.5534
+874.493 131.882
+875.072 147.322
+875.652 179.038
+876.232 154.566
+876.812 136.851
+877.391 107.779
+877.971 75.3209
+878.551 59.6519
+879.13 54.7789
+879.71 101.333
+880.29 117.704
+880.87 163.486
+881.449 191.7
+882.029 178.108
+882.609 159.788
+883.188 119.377
+883.768 94.9878
+884.348 70.1019
+884.928 79.9134
+885.507 91.7946
+886.087 109.664
+886.667 124.143
+887.246 136.776
+887.826 138.387
+888.406 135.886
+888.986 141.823
+889.565 147.058
+890.145 152.041
+890.725 146.2
+891.304 132.171
+891.884 113.843
+892.464 108.223
+893.043 109.324
+893.623 120.206
+894.203 122.098
+894.783 109.378
+895.362 86.926
+895.942 81.9209
+896.522 59.7124
+897.101 75.2968
+897.681 71.3721
+898.261 84.7366
+898.841 72.9625
+899.42 62.1695
+900 47.2853
+900.58 38.2968
+901.159 33.6638
+901.739 40.6661
+902.319 46.503
+902.899 52.222
+903.478 50.4708
+904.058 42.7641
+904.638 36.7373
+905.217 27.1263
+905.797 22.6297
+906.377 21.1298
+906.957 23.8146
+907.536 26.2566
+908.116 28.9092
+908.696 27.8603
+909.275 24.2104
+909.855 20.8028
+910.435 15.8617
+911.014 14.0861
+911.594 13.2357
+912.174 15.1197
+912.754 17.5077
+913.333 19.4647
+913.913 21.4817
+914.493 20.4455
+915.072 18.9619
+915.652 16.1543
+916.232 14.1858
+916.812 11.485
+917.391 10.9527
+917.971 12.0169
+918.551 12.8542
+919.13 15.4948
+919.71 17.5039
+920.29 18.912
+920.87 19.3187
+921.449 17.9194
+922.029 17.1219
+922.609 19.6963
+923.188 25.7384
+923.768 29.4421
+924.348 35.7747
+924.928 37.1728
+925.507 35.0882
+926.087 29.8179
+926.667 36.1395
+927.246 57.3186
+927.826 106.151
+928.406 143.517
+928.986 189.79
+929.565 227.23
+930.145 218.653
+930.725 200.627
+931.304 149.621
+931.884 110.815
+932.464 75.7787
+933.043 52.4871
+933.623 67.6589
+934.203 97.4867
+934.783 162.024
+935.362 188.029
+935.942 240.881
+936.522 206.897
+937.101 173.414
+937.681 141.731
+938.261 103.435
+938.841 93.5804
+939.42 105.045
+940 126.395
+940.58 163.206
+941.159 183.921
+941.739 220.847
+942.319 241.179
+942.899 244.362
+943.478 214.486
+944.058 227.481
+944.638 216.387
+945.217 232.365
+945.797 231.24
+946.377 212.689
+946.957 181.278
+947.536 172.93
+948.116 145.411
+948.696 154.141
+949.275 147.864
+949.855 143.195
+950.435 124.966
+#951.014 105.634
+#951.594 91.6268
+#952.174 84.7906
+#952.754 104.656
+#953.333 121.646
+#953.913 147.06
+#954.493 161.154
+#955.072 153.611
+#955.652 117.388
+#956.232 98.9875
+#956.812 66.1366
+#957.391 47.8399
Index: branches/Mars_McMismatchStudy/resources/TeVsources.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/TeVsources.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/TeVsources.txt	(revision 17960)
@@ -0,0 +1,56 @@
+Object         z       RA (J2000.0) Dec.(J2000.0) mag    mag   
+                                                  nucl   host
+--------------------------------------------------------------
+1ES_0033+595     -     00 35 52.6   +59 50 05     18.4    U    
+1ES_0120+340   0.272   01 23 08.8   +34 20 50     18.0   18.2   
+RGB_0136+391     -     01 36 32.7   +39 06 00     15.6    U   
+RGB_0214+517   0.049   02 14 17.9   +51 44 52     17.0   14.5   
+3C_66A         0.444   02 22 39.6   +43 02 08     14.5    U    
+1ES_0647+250     -     06 50 46.5   +25 03 00     15.2    U    
+1ES_0806+524   0.138   08 09 49.2   +52 18 58     17.9    ? 
+OJ_287         0.306   08 54 48.9   +20 06 31     15.3    U 
+1ES_1011+496   0.200   10 15 04.2   +49 26 01     16.2   17.1   
+1ES_1028+511   0.361   10 31 18.5   +50 53 36     16.3    ? 
+Mkn_421        0.031   11 04 27.3   +38 12 32     12.9   13.0
+RGB_1117+202   0.139   11 17 06.2   +20 14 08       -     ?    
+Mkn_180        0.045   11 36 26.4   +70 09 27     15.8   14.2
+RGB_1136+676   0.135   11 36 30.1   +67 37 04     17.9   16.1   
+ON_325         0.130   12 17 52.1   +30 07 01     14.8   16.2
+1ES_1218+304   0.182   12 21 21.9   +30 10 37     16.7    ? 
+RGB_1417+257   0.237   14 17 56.6   +25 43 25     17.5    ? 
+1ES_1426+428   0.129   14 28 32.6   +42 40 21     17.3   16.1
+1ES_1544+820     -     15 40 15.7   +81 55 06     15.3    ?  
+Mkn_501        0.034   16 53 52.2   +39 45 37     14.2   12.6
+OT_546         0.055   17 28 18.6   +50 13 10     16.6   15.5
+1ES_1959+650   0.047   19 59 59.8   +65 08 55     15.2   14.8
+BL_Lac         0.069   22 02 43.3   +42 16 40     14.9   15.0
+1ES_2344+514   0.044   23 47 04.8   +51 42 18     16.5   13.9
+--------------------------------------------------------------
+1ES_0229+200     -     02 32 48.6   +20 17 17       -     ?
+AO_0235+164      -     02 38 38.9   +16 36 59       -     ?
+HB89_0317+185    -     03 19 51.8   +18 45 34       -     ?
+1ES_0323+022     -     03 26 14.0   +02 25 15       -     ?
+3C_120           -     04 33 11.1   +05 21 16       -     ?
+S5_0716+714      -     07 21 53.4   +71 20 36       -     ?
+PKS_0735+178     -     07 38 07.4   +17 42 19       -     ?
+0836+710         -     08 41 24.4   +70 53 42       -     ?
+1ES_0927+500     -     09 30 37.6   +49 50 26       -     ?
+S4_0954+65       -     09 58 47.2   +65 33 55       -     ?
+ON_231           -     12 21 31.7   +28 13 59       -     ?
+3C_273           -     12 29 06.7   +02 03 08       -     ?
+3C_279           -     12 56 11.2   -05 47 22       -     ?
+PG_1424+240      -     14 27 00.4   +23 48 00       -     ?
+PG_1553+113      -     15 55 43.0   +11 11 24       -     ?
+HB89_1721+343    -     17 23 20.8   +34 17 58       -     ?
+H_1722+119       -     17 25 04.3   +11 52 15       -     ?
+1ES_1741+196     -     17 43 57.8   +19 35 09       -     ?
+PKS_2155-304     -     21 58 52.0   -30 13 32       -     ?
+B3_2247+381      -     22 50 05.7   +38 24 37       -     ?
+3C_454.3         -     22 53 57.7   +16 08 54       -     ?
+--------------------------------------------------------------
+RGB_0152+017     -     01 52 39.6   +01 47 17       -     ?
+MS_0158+002      -     02 01 06.2   +00 34 00       -     ?
+4C_29_45         -     11 59 31.8   +29 14 44       -     ?
+ON_238           -     12 24 54.4   +21 22 46       -     ?
+PKS_1510-089     -     15 12 50.5   -09 05 59       -     ? 
+B2_1633+38       -     16 35 15.5   +38 08 04       -     ?
Index: branches/Mars_McMismatchStudy/resources/calibration.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/calibration.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/calibration.rc	(revision 17960)
@@ -0,0 +1,36 @@
+20: 0.928350
+21: 0.963391
+22: 0.973122
+
+# Spline Data
+#23: 0.904593
+#24: 0.840913
+#25: 0.859792
+
+27: 1.00496
+28: 1.01258
+29: 0.95132
+30: 0.95132
+31: 0.99155
+32: 0.98750
+33: 1.04149
+34: 0.95539
+35: 0.93059
+36: 0.95832
+
+37: 0.97521
+38: 1.00000
+39: 0.98958
+40: 0.98756
+
+41: 0.92991
+42: 0.94246
+43: 0.94984
+44: 0.99059
+45: 0.99772
+46: 1.02623
+47: 0.99160
+48: 0.98456
+49: 0.98157
+50: 0.99978
+
Index: branches/Mars_McMismatchStudy/resources/calibration_spline.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/calibration_spline.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/calibration_spline.rc	(revision 17960)
@@ -0,0 +1,101 @@
+#no spline data p20
+20: 0.85182358
+
+21: 0.85182358
+22: 0.85182358
+
+23: 0.8863929
+24: 0.8639184
+25: 0.8781686
+
+#no spline
+27: 0.8781686
+
+#one spline
+28: 0.906195
+
+#no spline
+29: 0.88
+30: 0.88
+31: 0.88
+32: 0.88
+33: 0.88
+34: 0.88
+
+
+35: 0.82242
+36: 0.85159
+
+37: 0.88716
+38: 0.90169
+
+#one spline
+39: 0.877988
+#no spline
+40: 0.877988
+
+#no spline
+41: 0.82205
+42: 0.84122
+43: 0.84699
+44: 0.88419
+45: 0.88419
+46: 0.88419
+47: 0.88419
+48: 0.88419
+49: 0.88419
+50: 0.88419
+
+# MUX Data (8198)
+51: 0.9051
+52: 0.9315
+53: 0.8821
+54: 0.9252
+55: 0.9090
+56: 0.9180
+57: 0.8888
+
+58: 0.8629
+59: 0.8617
+60: 0.8940
+61: 0.8613
+62: 0.8401
+63: 0.8567
+64: 0.9519
+65: 0.9162
+66: 0.9394
+67: 0.9145
+
+# To get an update devide this value by the avg value from the db
+68: 0.9226
+69: 0.9300
+70: 0.9403
+71: 0.9403
+72: 0.9751
+73: 0.9501
+74: 0.9598
+75: 0.9661
+76: 0.9661
+77: 0.9661
+78: 0.9661
+79: 0.9661
+80: 0.9661
+81: 0.9661
+82: 0.9661
+83: 0.9661
+84: 0.9661
+85: 0.9661
+86: 0.9661
+87: 0.9661
+88: 0.9661
+89: 0.9661
+90: 0.9661
+91: 0.9661
+92: 0.9661
+93: 0.9661
+94: 0.9661
+95: 0.9661
+96: 0.9661
+97: 0.9661
+98: 0.9661
+99: 0.9661
Index: branches/Mars_McMismatchStudy/resources/calibrationref_mux.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/calibrationref_mux.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/calibrationref_mux.rc	(revision 17960)
@@ -0,0 +1,84 @@
+#
+# Reference lines for the data check, valid from for data
+# before Nov. 04:
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+ConvFADC2PheMin:          0.
+ConvFADC2PheMax:          5.
+ConvFADC2PhotMin:         0.
+ConvFADC2PhotMax:         10.
+#
+# Quantum Efficiencies:
+#
+QEMin:                    0.
+QEMax:                    0.4
+#
+# Arrival Times from Max. bin:
+#
+ArrivalTimeMin:           15.
+ArrivalTimeMax:           65.
+#
+# Relative Time Calibration:
+#
+TimeOffsetMin:           -9.
+TimeOffsetMax:           12.
+
+TimeResolutionMin:        0.45
+TimeResolutionMax:        1.25
+
+######################################################################
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+RefFADC2PheInner:         0.55
+RefFADC2PheOuter:         1.7
+RefConvFADC2PhotInner:    0.8
+RefConvFADC2PhotOuter:    3.8
+RefConvFADC2PheInner:     0.5
+RefConvFADC2PheOuter:     2.2
+
+#
+# Quantum Efficiencies:
+#
+RefQEInner:               0.18
+RefQEOuter:               0.12
+
+#
+# Arrival Times from Max. bin:
+#
+RefArrivalTimeInner:      34
+RefArrivalTimeOuter:      38
+RefArrivalTimeRmsInner:   2.1
+RefArrivalTimeRmsOuter:   1.9
+
+#
+# Relative Time Calibration:
+#
+RefTimeOffsetOuter:        5.5
+RefTimeResolutionInner:    0.9
+RefTimeResolutionOuter:    0.7
+
+#
+# Mean Absolute Time:
+#
+InnerRefTime:             34
+OuterRefTime:             38
+
+#
+# Mean Absolute Charge:
+#
+InnerRefCharge:           63.
+OuterRefCharge:           63.
Index: branches/Mars_McMismatchStudy/resources/compstars_R.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/compstars_R.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/compstars_R.txt	(revision 17960)
@@ -0,0 +1,311 @@
+1ES_0033+595 A  14.10 1.06  -
+1ES_0033+595 B  13.33 0.56  -
+1ES_0033+595 C  12.52 0.74  -
+1ES_0033+595 D  13.66 1.46  prim
+1ES_0033+595 E  13.91 0.55  -
+1ES_0033+595 F  16.67 0.87  control
+1ES_0033+595 F1 15.58 0.90  -
+1ES_0033+595 F2 16.12 0.90  -
+1ES_0033+595 F3 15.95 0.90  -
+1ES_0033+595 BL 20.00 1.3   -
+
+1ES_0120+340 A  13.13 0.50  -
+1ES_0120+340 B  13.74 0.48  -
+1ES_0120+340 C  13.12 0.38  prim
+1ES_0120+340 D  14.02 0.51  -
+1ES_0120+340 E  13.55 0.56  -
+1ES_0120+340 F  16.76 0.57  -
+1ES_0120+340 G  16.43 0.45  control
+1ES_0120+340 F1 16.54 0.47  -
+1ES_0120+340 BL 20.00 0.6   -
+
+RGB_0136+391 A  13.13 0.60  control
+RGB_0136+391 B  13.82 0.42  prim
+RGB_0136+391 C  14.40 0.76  -
+RGB_0136+391 D  14.42 0.46  -
+RGB_0136+391 E  14.84 0.51  -
+RGB_0136+391 F  16.56 0.42  -
+RGB_0136+391 BL 20.00 0.4   -
+
+RGB_0214+517 A  13.85 0.51  prim
+RGB_0214+517 B  14.54 0.57  control
+RGB_0214+517 C  13.61 0.38  -
+RGB_0214+517 D  15.09 0.47  -
+RGB_0214+517 E  15.19 0.44  -
+RGB_0214+517 F1 15.55 0.50  -
+RGB_0214+517 F2 15.61 0.50  -
+RGB_0214+517 F3 15.80 0.50  -
+RGB_0214+517 BL 20.00 0.7   -
+
+3C_66A       A  13.38 0.22  prim
+3C_66A       B  14.28 0.49  control
+3C_66A       C1 12.70 0.09  -
+3C_66A       C2 13.62 0.56  -
+3C_66A       BL 20.00 0.5   -
+
+1ES_0229+200 A  13.80 0.50  prim
+1ES_0229+200 B  16.05 0.50  -
+1ES_0229+200 C  15.83 0.50  control
+1ES_0229+200 D  20.00 0.50  -
+
+AO_0235+164  1  12.69 0.34  -
+AO_0235+164  2  12.23 0.48  -
+AO_0235+164  3  12.48 0.44  -
+AO_0235+164  6  13.64 0.38  -
+AO_0235+164  8  15.79 0.79  control
+AO_0235+164  C1 14.23 0.55  prim
+AO_0235+164  BL 20.00 0.5   -
+
+HB89_0317+185 A  11.55 0.31 -
+HB89_0317+185 B  13.33 0.43 prim
+HB89_0317+185 C  20.00 0.50 control
+HB89_0317+185 BL 20.00 0.5  -
+
+1ES_0323+022 A  12.33 0.52  -
+1ES_0323+022 B  14.01 0.37  prim
+1ES_0323+022 C1 13.34 0.66  -
+1ES_0323+022 C2 13.84 0.60  -
+1ES_0323+022 C3 15.36 0.39  control
+1ES_0323+022 BL 20.00 0.5   -
+
+3C_120       A  16.1  0.5   -
+3C_120       B  16.2  0.5   -
+3C_120       C  16.5  0.5   -
+3C_120       D  16.6  0.5   -
+3C_120       2  15.2  0.5   control
+3C_120       3  13.9  0.5   prim
+
+1ES_0647+250 A  13.83 0.33  -
+1ES_0647+250 B  15.22 0.38  control
+1ES_0647+250 C  13.40 0.40  -
+1ES_0647+250 D  13.44 0.34  -
+1ES_0647+250 E  13.03 0.59  prim
+1ES_0647+250 F  14.89 0.38  -
+1ES_0647+250 BL 20.00 0.4   -
+
+S5_0716+714  1  10.63 0.36  -
+S5_0716+714  2  11.12 0.34  -    
+S5_0716+714  3  12.06 0.37  -      
+S5_0716+714  4  12.89 0.30  -
+S5_0716+714  5  13.18 0.37  prim
+S5_0716+714  6  13.26 0.37  control
+S5_0716+714  7  13.32 0.42  -      
+S5_0716+714  8  13.79 0.31  -      
+S5_0716+714  BL 20.00 0.5   -      
+
+PKS_0735+178 C  13.84 0.60  control
+PKS_0735+178 C1 12.91 0.33  -
+PKS_0735+178 C2 12.81 0.49  prim
+PKS_0735+178 D  15.44 0.44  -
+PKS_0735+178 BL 20.00 0.5   -
+
+1ES_0806+524 C1 12.56 0.48  -
+1ES_0806+524 C2 14.22 0.39  prim
+1ES_0806+524 C3 14.39 0.38  -
+1ES_0806+524 C4 15.24 0.35  control
+1ES_0806+524 C5 15.32 0.30  -
+1ES_0806+524 F1 18.21 0.50  -
+1ES_0806+524 BL 20.00 0.5   -
+
+0836+710     A  16.59 1.01  control
+0836+710     B  14.85 0.45  -
+0836+710     C  13.53 0.38  prim
+0836+710    BL  20.00 0.5   -
+
+OJ_287       4  13.74 0.44  prim
+OJ_287      11  14.65 0.29  -
+OJ_287      10  14.34 0.26  control
+OJ_287      C1  15.50 0.38  -
+OJ_287      C2  15.66 0.46  -
+OJ_287      BL  20.00 0.5   -
+
+1ES_0927+500 A  15.0  0.50  prim
+1ES_0927+500 B  20.00 0.50  control
+1ES_0927+500 C  20.00 0.50  -
+1ES_0927+500 BL 20.00 0.5   -
+
+1ES_1011+496 A  13.40 0.47  -
+1ES_1011+496 B  15.44 0.44  control
+1ES_1011+496 C  15.42 0.31  -
+1ES_1011+496 D  14.01 0.31  -
+1ES_1011+496 E  14.04 0.39  prim
+1ES_1011+496 BL 20.00 0.4   -
+
+1ES_1028+511 1  12.93 0.27  prim
+1ES_1028+511 2  14.04 0.25  -
+1ES_1028+511 3  14.18 0.22  -
+1ES_1028+511 4  14.17 0.23  -
+1ES_1028+511 5  14.75 0.28  control
+1ES_1028+511 6  14.87 0.19  -
+1ES_1028+511 BL 20.0  0.5   -
+
+Mkn_421      1  14.04 0.32  prim
+Mkn_421      2  15.20 0.37  control
+Mkn_421      3  15.24 0.53  -
+Mkn_421     F1  17.50 0.50  -
+Mkn_421     F2  20.00 0.50  -
+Mkn_421     BL  20.00 0.5   -
+
+RGB_1117+202 A  11.90 0.38  -
+RGB_1117+202 B  12.02 0.38  -
+RGB_1117+202 C  20.00 0.50  -
+RGB_1117+202 D  14.82 0.70  -
+RGB_1117+202 E  13.56 0.42  prim
+RGB_1117+202 F  15.16 0.43  control
+RGB_1117+202 BL 20.00 0.6   -
+
+Mkn_180      1  13.73 0.25  prim
+Mkn_180      2  14.41 0.39  control
+Mkn_180      3  15.13 0.36  -
+Mkn_180      4  15.66 0.34  -
+Mkn_180      F1 15.93 0.50  -
+Mkn_180      F2 15.96 0.50  -
+Mkn_180      BL 20.00 0.5   -
+
+RGB_1136+676 A  14.48 0.66  -
+RGB_1136+676 B  14.22 0.48  -
+RGB_1136+676 C  14.73 0.34  -
+RGB_1136+676 D  14.58 0.46  prim
+RGB_1136+676 E  15.80 0.42  control
+RGB_1136+676 F1 17.30 0.50  -
+RGB_1136+676 F2 16.99 0.50  -
+RGB_1136+676 F3 17.31 0.50  -
+RGB_1136+676 BL 20.00 0.7   -
+
+ON_325       B  14.59 0.37  prim
+ON_325       C1 16.21 0.29  control
+ON_325       BL 20.00 0.5   -
+
+1ES_1218+304 A  12.06 0.41  -
+1ES_1218+304 B  13.61 0.40  prim
+1ES_1218+304 C  15.58 0.62  control
+1ES_1218+304 F1 15.59 0.50  -
+1ES_1218+304 BL 20.00 0.4   -
+
+ON_231       A  11.72 0.36  -
+ON_231       C1 16.03 0.57  control
+ON_231       D  13.86 0.95  prim
+ON_231       BL 20.00 0.5   -
+
+3C_279	     1	15.45 0.49  control
+3C_279	     2  12.05 0.37  -
+3C_279	     3  14.53 0.37  prim
+3C_279	     4  12.57 0.43  -
+3C_279	     5  20.00 0.00  -
+3C_279	     6  12.45 0.36  -
+3C_279	     7  15.13 0.53  -
+3C_279	     8  14.44 0.53  -
+3C_279	     BL 20.00 0.5   -
+
+RGB_1417+257 A  13.78 0.57  prim
+RGB_1417+257 C1 15.29 1.16  -
+RGB_1417+257 C2 16.13 0.59  control
+RGB_1417+257 F1 18.22 0.50  -
+RGB_1417+257 F2 18.33 0.50  -
+RGB_1417+257 F3 18.29 0.50  -
+RGB_1417+257 BL 20.00 1.0   -
+
+PG_1424+240  C1 13.20 0.39  prim
+PG_1424+240  C2 13.32 0.38  control
+PG_1424+240  C3 15.57 0.34  -
+
+1ES_1426+428 A  13.23 0.93  control
+1ES_1426+428 B  14.17 0.44  prim
+1ES_1426+428 C  13.00 0.46  -
+1ES_1426+428 D  15.20 0.33  -
+1ES_1426+428 BL 20.00 0.5   -
+
+1ES_1544+820 A  14.59 0.37  -
+1ES_1544+820 B  15.35 0.80  control
+1ES_1544+820 C  14.41 0.38  -
+1ES_1544+820 D  12.87 0.31  prim
+1ES_1544+820 E  14.24 0.41  -
+1ES_1544+820 BL 20.00 0.5   -
+
+PG_1553+113  1  13.2  0.5   prim
+PG_1553+113  2  14.6  0.5   -
+PG_1553+113  3  12.8  0.5   -
+PG_1553+113  4  14.6  0.5   control
+PG_1553+113  5  13.5  0.5   -
+PG_1553+113  7  12.7  0.5   -
+PG_1553+113  8  12.4  0.5   -
+PG_1553+113  BL 20.00 0.5   -
+
+Mkn_501      1  12.11 0.50  -
+Mkn_501      2  12.79 0.44  -
+Mkn_501      3  14.80 0.44  control
+Mkn_501      4  14.96 0.34  prim
+Mkn_501      5  15.08 0.43  prim
+Mkn_501      6  14.99 0.68  prim
+Mkn_501      F1 15.78 0.50  -
+Mkn_501      BL 20.00 0.6   -
+
+HB89_1721+343 A 13.4  0.50  prim 
+HB89_1721+343 B 14.1  0.50  - 
+HB89_1721+343 C 14.1  0.50  - 
+HB89_1721+343 D 20.00 0.50  control 
+HB89_1721+343 E 20.00 0.50  - 
+
+H_1722+119   C1 10.94 1.04  -
+H_1722+119   C2 12.62 0.59  prim
+H_1722+119   C3 13.63 0.47  -
+H_1722+119   C4 15.14 0.60  control
+H_1722+119   BL 20.00 0.5   -
+
+1ES_1741+196 C1 11.1  0.50  -
+1ES_1741+196 C2 13.6  0.50  prim
+1ES_1741+196 C4 14.1  0.50  control
+1ES_1741+196 C5 20.00 0.50  -
+
+OT_546       B  12.81 0.33  prim
+OT_546       H  14.99 0.33  control
+OT_546       L  15.71 0.36  -
+OT_546       BL 20.00 0.5   -
+
+1ES_1959+650 1  12.29 0.38  -
+1ES_1959+650 2  12.53 0.33  -
+1ES_1959+650 3  12.27 0.91  -
+1ES_1959+650 4  14.08 0.45  prim
+1ES_1959+650 5  14.00 0.54  -
+1ES_1959+650 6  14.78 0.42  prim
+1ES_1959+650 7  14.79 0.45  control
+1ES_1959+650 BL 20.00 0.5   -
+
+PKS_2155-304 2  11.67 0.38  prim
+PKS_2155-304 3  12.47 0.53  control
+PKS_2155-304 4  13.92 0.36  -
+PKS_2155-304 5  15.01 0.34  -
+PKS_2155-304 BL 20.00 0.5   -
+
+BL_Lac       B  11.99 0.91  -
+BL_Lac       C  13.79 0.47  prim
+BL_Lac       K  15.00 0.47  -
+BL_Lac       H  13.73 0.67  control
+BL_Lac       F1 15.60 0.50  -
+BL_Lac       F2 15.32 0.50  -
+BL_Lac       BL 20.00 0.5   -
+
+B3_2247+381  A  12.5  0.50  -
+B3_2247+381  B  13.0  0.50  -
+B3_2247+381  C  13.9  0.50  prim
+B3_2247+381  D  12.6  0.50  -
+B3_2247+381  E  20.00 0.50  control
+
+3C_454.3     A  15.32 0.54  -
+3C_454.3     B  14.73 0.48  -
+3C_454.3     C  13.98 0.45  -
+3C_454.3     D  13.22 0.63  -
+3C_454.3     E  14.92 0.84  control
+3C_454.3     F  14.83 0.38  -
+3C_454.3     G  14.83 0.59  -
+3C_454.3     H  13.10 0.55  prim
+3C_454.3     C1 15.27 0.40  -
+3C_454.3     BL 20.00 0.5   -
+
+1ES_2344+514 C1 12.25 0.36  prim
+1ES_2344+514 C2 14.20 0.42  -
+1ES_2344+514 C3 15.40 0.49  control
+1ES_2344+514  A 13.40 0.50  -
+1ES_2344+514 F1 16.71 0.50  -
+1ES_2344+514 F2 16.19 0.50  -
+1ES_2344+514 BL 20.00 0.5   -
Index: branches/Mars_McMismatchStudy/resources/construction.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/construction.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/construction.txt	(revision 17960)
@@ -0,0 +1,3333 @@
+<# Projektnummer  
+<# Text           geom.dxf                                                                        
+<# MERO-Datei     fort.3
+<# ASCII-Datei    Fort.3_asc                                                                      
+<# Datum          19.08.04 16:17:27
+<# Inhalt:
+   Knoten            813     4   813     0
+   Auflager            0     0     0
+   Staebe           2504     3   813    40     0     0
+   Tape3 Ende          1     3     0
+<# Ende
+<# Knoten            813     4   813    40
+  1002        0.0000    -4704.0000     -600.0000     1
+  1002        0.0000     4704.0000     -600.0000     2
+  1002        0.0000    -9408.0000        0.0000     3
+  1002    -8147.5669    -4704.0000        0.0000     4
+  1002     8147.5669    -4704.0000        0.0000     5
+  1002    -4073.7834    -2352.0000        0.0000     6
+  1002     4073.7834    -2352.0000        0.0000     7
+  1002    -8147.5669        0.0000        0.0000     8
+  1002        0.0000        0.0000        0.0000     9
+  1002     8147.5669        0.0000        0.0000    10
+  1002    -4073.7834     2352.0000        0.0000    11
+  1002     4073.7834     2352.0000        0.0000    12
+  1002    -8147.5669     4704.0000        0.0000    13
+  1002     8147.5669     4704.0000        0.0000    14
+  1002        0.0000     9408.0000        0.0000    15
+  1003        0.0000        0.0000     1070.0000    16
+  1017     -189.3486        0.0000     1775.5483    17
+  1017     -509.6151        0.0000     1775.5598    18
+  1017      130.7226        0.0000     1786.7146    19
+  1017     -829.6855        0.0000     1786.7488    20
+  1017      450.2095        0.0000     1809.0448    21
+  1017    -1149.1704        0.0000     1809.1018    22
+  1016     -190.1327        0.0000     1820.5419    23
+  1016     -508.8279        0.0000     1820.5529    24
+  1016      128.3692        0.0000     1831.6532    25
+  1016     -827.3284        0.0000     1831.6870    26
+  1021     -938.1639        0.0000     1838.1760    27
+  1017      768.7219        0.0000     1842.5121    28
+  1017    -1467.6809        0.0000     1842.5917    29
+  1016      446.2886        0.0000     1853.8743    30
+  1016    -1145.2468        0.0000     1853.9305    31
+  1004     1085.8726        0.0000     1887.0754    32
+  1004    -1784.8284        0.0000     1887.1770    33
+  1016      763.2393        0.0000     1887.1770    34
+  1016    -1462.1949        0.0000     1887.2557    35
+  1016     1078.8341        0.0000     1931.5215    36
+  1016    -1777.7866        0.0000     1931.6228    37
+  1004     1401.2745        0.0000     1942.6802    38
+  1004    -2100.2266        0.0000     1942.8047    39
+  1016     1392.6896        0.0000     1986.8539    40
+  1016    -2091.6382        0.0000     1986.9771    41
+  1002        0.0000    -4704.0000     2000.0000    42
+  1002    -8147.5669        0.0000     2000.0000    43
+  1002     8147.5669        0.0000     2000.0000    44
+  1002        0.0000     4704.0000     2000.0000    45
+  1004     1714.5438        0.0000     2009.2590    46
+  1004    -2413.4912        0.0000     2009.4056    47
+  1016     1704.4224        0.0000     2053.1062    48
+  1016    -2403.3665        0.0000     2053.2517    49
+  1023     -923.3254        0.0000     2067.6968    50
+  1021    -2485.2166        0.0000     2072.5498    51
+  1004     2025.2985        0.0000     2086.7310    52
+  1004    -2724.2405        0.0000     2086.8994    53
+  1016     2013.6528        0.0000     2130.1978    54
+  1016    -2712.5916        0.0000     2130.3655    55
+  1021     2143.9929        0.0000     2166.1555    56
+  1004     2333.1604        0.0000     2175.0015    57
+  1004    -3032.0957        0.0000     2175.1919    58
+  1016     2320.0046        0.0000     2218.0354    59
+  1016    -3018.9365        0.0000     2218.2249    60
+  1004     2637.7537        0.0000     2273.9626    61
+  1004    -3336.6816        0.0000     2274.1746    62
+  1007    -2431.4058        0.0000     2296.1665    63
+  1016     2623.1038        0.0000     2316.5110    64
+  1016    -3322.0291        0.0000     2316.7219    65
+  1004     2938.7073        0.0000     2383.4939    66
+  1004    -3637.6279        0.0000     2383.7273    67
+  1005     2081.1863        0.0000     2387.4143    68
+  1016     2922.5815        0.0000     2425.5054    69
+  1016    -3621.4993        0.0000     2425.7373    70
+  1004     3235.6553        0.0000     2503.4624    71
+  1004    -3934.5669        0.0000     2503.7168    72
+  1016     3218.0728        0.0000     2544.8855    73
+  1016    -3916.9822        0.0000     2545.1382    74
+  1021    -3975.6042        0.0000     2570.2681    75
+  1004     3528.2349        0.0000     2633.7214    76
+  1004    -4227.1377        0.0000     2633.9968    77
+  1016     3509.2178        0.0000     2674.5056    78
+  1016    -4208.1177        0.0000     2674.7795    79
+  1004     3816.0903        0.0000     2774.1125    80
+  1004    -4514.9829        0.0000     2774.4077    81
+  1007    -3884.2480        0.0000     2781.3462    82
+  1016     3795.6614        0.0000     2814.2083    83
+  1016    -4494.5508        0.0000     2814.5022    84
+  1004     4098.8706        0.0000     2924.4646    85
+  1004    -4797.7524        0.0000     2924.7798    86
+  1016     4077.0547        0.0000     2963.8228    87
+  1016    -4775.9341        0.0000     2964.1370    88
+  1021     4276.8276        0.0000     3077.8689    89
+  1004     4376.2310        0.0000     3084.5945    90
+  1004    -5075.1016        0.0000     3084.9299    91
+  1016     4353.0547        0.0000     3123.1672    92
+  1016    -5051.9229        0.0000     3123.5002    93
+  1004     4647.8340        0.0000     3254.3069    94
+  1004    -5346.6929        0.0000     3254.6619    95
+  1022      948.9553        0.0000     3264.4563    96
+  1005     4160.2915        0.0000     3276.1599    97
+  1023      934.0358        0.0000     3279.3757    98
+  1016     4623.3252        0.0000     3292.0474    99
+  1016    -5322.1816        0.0000     3292.3994   100
+  1011    -2271.2271        0.0000     3301.2439   101
+  1023      880.4896    -2255.0000     3335.7490   102
+  1023      880.4896     2255.0000     3335.7490   103
+  1011    -2317.1890    -2255.0000     3348.6199   104
+  1011    -2317.1890     2255.0000     3348.6199   105
+  1004     4913.3481        0.0000     3433.3950   106
+  1004    -5612.1948        0.0000     3433.7683   107
+  1016     4887.5371        0.0000     3470.2573   108
+  1016    -5586.3804        0.0000     3470.6284   109
+  1004     5172.4502        0.0000     3621.6409   110
+  1004    -5871.2832        0.0000     3622.0327   111
+  1016     5145.3687        0.0000     3657.5798   112
+  1016    -5844.1987        0.0000     3657.9695   113
+  1021    -6009.2861        0.0000     3785.3704   114
+  1004     5424.8242        0.0000     3818.8152   115
+  1004    -6123.6426        0.0000     3819.2244   116
+  1016     5396.5049        0.0000     3853.7866   117
+  1016    -6095.3213        0.0000     3854.1943   118
+  1021    -5866.6973        0.0000     3965.8379   119
+  1004     5670.1631        0.0000     4024.6772   120
+  1004    -6368.9673        0.0000     4025.1042   121
+  1016     5640.6406        0.0000     4058.6394   122
+  1016    -6339.4424        0.0000     4059.0642   123
+  1004     5908.1680        0.0000     4238.9766   124
+  1004    -6606.9565        0.0000     4239.4204   125
+  1016     5877.4780        0.0000     4271.8877   126
+  1016    -6576.2642        0.0000     4272.3291   127
+  1009    -4328.2007    -1070.0000     4339.9839   128
+  1009    -4328.2007     1070.0000     4339.9839   129
+  1009    -4415.8818    -3208.0000     4430.4932   130
+  1009    -4415.8818     3208.0000     4430.4932   131
+  1004    -6837.3213        0.0000     4461.9121   132
+  1016     6106.7285        0.0000     4493.2715   133
+  1016    -6805.4995        0.0000     4493.7295   134
+  1023     2754.1665        0.0000     4651.1250   135
+  1021     5944.0938        0.0000     4655.9062   136
+  1011     -445.4773        0.0000     4658.8887   137
+  1004     6361.0234        0.0000     4691.8320   138
+  1004    -7059.7803        0.0000     4692.3081   139
+  1022     2684.5930    -2259.0000     4720.6987   140
+  1022     2684.5930     2259.0000     4720.6987   141
+  1016     6328.1123        0.0000     4722.5220   142
+  1016    -7026.8672        0.0000     4722.9961   143
+  1011     -630.0322    -4512.0000     4849.1006   144
+  1011     -630.0322     4512.0000     4849.1006   145
+  1016    -7167.0396        0.0000     4876.8115   146
+  1004     6575.3228        0.0000     4929.8369   147
+  1008    -5981.4165        0.0000     4943.8530   148
+  1008    -5992.0229    -1029.0000     4954.4595   149
+  1008    -5992.0229     1029.0000     4954.4595   150
+  1016     6541.3608        0.0000     4959.3594   151
+  1008    -6024.5498    -2057.0000     4986.9863   152
+  1008    -6024.5498     2057.0000     4986.9863   153
+  1021    -6995.2856        0.0000     5029.7842   154
+  1008    -6076.8755    -3086.0000     5040.7266   155
+  1008    -6076.8755     3086.0000     5040.7266   156
+  1002        0.0000   -11229.0000     5075.0000   157
+  1002    -3563.0000    -8800.0000     5075.0000   158
+  1002     3563.0000    -8800.0000     5075.0000   159
+  1002    -3563.0000     8800.0000     5075.0000   160
+  1002     3563.0000     8800.0000     5075.0000   161
+  1002        0.0000    11229.0000     5075.0000   162
+  1009    -3594.2239    -4278.0000     5119.2153   163
+  1009    -3594.2239     4278.0000     5119.2153   164
+  1004     6781.1851        0.0000     5175.1758   165
+  1016     6746.2134        0.0000     5203.4951   166
+  1004     6978.3589        0.0000     5427.5498   167
+  1016     6942.4204        0.0000     5454.6313   168
+  1008    -5095.4116        0.0000     5510.2456   169
+  1008    -6950.1523     -500.0000     5529.3374   170
+  1008    -6950.1523      500.0000     5529.3374   171
+  1008    -6970.6587    -1500.0000     5549.8433   172
+  1008    -6970.6587     1500.0000     5549.8433   173
+  1008    -5137.1309    -2058.0000     5553.3789   174
+  1008    -5137.1309     2058.0000     5553.3789   175
+  1009    -2551.2412    -1070.0000     5583.7847   176
+  1009    -2551.2412     1070.0000     5583.7847   177
+  1008    -7012.3779    -2500.0000     5591.5625   178
+  1008    -7012.3779     2500.0000     5591.5625   179
+  1008    -7074.6035    -3500.0000     5653.7881   180
+  1008    -7074.6035     3500.0000     5653.7881   181
+  1009    -2639.6296    -3210.0000     5673.5869   182
+  1009    -2639.6296     3210.0000     5673.5869   183
+  1008    -5264.4102    -4114.0000     5682.0723   184
+  1008    -5264.4102     4114.0000     5682.0723   185
+  1004     7166.6050        0.0000     5686.6519   186
+  1016     7129.7427        0.0000     5712.4629   187
+  1018    -7640.2886        0.0000     5844.7070   188
+  1009    -2815.6992    -5348.0000     5852.4849   189
+  1009    -2815.6992     5348.0000     5852.4849   190
+  1004     7345.6929        0.0000     5952.1660   191
+  1016     7307.9526        0.0000     5976.6748   192
+  1008    -6076.1685     -500.0000     6069.5669   193
+  1008    -6076.1685      500.0000     6069.5669   194
+  1008    -6097.3818    -1500.0000     6090.7803   195
+  1008    -6097.3818     1500.0000     6090.7803   196
+  1008    -4239.8125    -1029.0000     6108.4575   197
+  1008    -4239.8125     1029.0000     6108.4575   198
+  1008    -6139.1011    -2500.0000     6132.4995   199
+  1008    -6139.1011     2500.0000     6132.4995   200
+  1011     1244.5079    -2259.0000     6160.7837   201
+  1011     1244.5079     2259.0000     6160.7837   202
+  1022     4420.8315        0.0000     6179.1685   203
+  1008    -6201.3267    -3500.0000     6194.7246   204
+  1008    -4324.6650    -3087.0000     6194.7246   205
+  1008    -4324.6650     3087.0000     6194.7246   206
+  1008    -6201.3267     3500.0000     6194.7246   207
+  1004     7515.4058        0.0000     6223.7690   208
+  1016     7476.8330        0.0000     6246.9453   209
+  1023     4351.5205    -2259.0000     6248.4795   210
+  1023     4351.5205     2259.0000     6248.4795   211
+  1008    -6284.0581    -4500.0000     6277.4561   212
+  1008    -6284.0581     4500.0000     6277.4561   213
+  1016     7522.1313        0.0000     6323.1724   214
+  1008    -4495.0776    -5143.0000     6366.5518   215
+  1008    -4495.0776     5143.0000     6366.5518   216
+  1021     7323.8403        0.0000     6439.7085   217
+  1004     7675.5352        0.0000     6501.1294   218
+  1016     7636.1772        0.0000     6522.9453   219
+  1011      872.5698    -6766.0000     6538.3784   220
+  1011      872.5698     6766.0000     6538.3784   221
+  1008    -5223.3979     -500.0000     6631.0098   222
+  1009    -2081.7224    -6417.0000     6631.7168   223
+  1008    -5223.3979      500.0000     6631.0098   224
+  1009    -2081.7224     6417.0000     6631.7168   225
+  1008    -5244.6108    -1500.0000     6652.2227   226
+  1008    -5244.6108     1500.0000     6652.2227   227
+  1008    -5286.3301    -2500.0000     6693.9424   228
+  1008    -5286.3301     2500.0000     6693.9424   229
+  1008    -3384.2131        0.0000     6708.0845   230
+  1008    -3426.6394    -2058.0000     6750.5107   231
+  1008    -3426.6394     2058.0000     6750.5107   232
+  1008    -5348.5557    -3500.0000     6756.1675   233
+  1008    -5348.5557     3500.0000     6756.1675   234
+  1004     7825.8872        0.0000     6783.9097   235
+  1016     7785.7915        0.0000     6804.3389   236
+  1008    -5431.9941    -4500.0000     6839.6060   237
+  1008    -5431.9941     4500.0000     6839.6060   238
+  1008    -3555.3330    -4116.0000     6879.2041   239
+  1008    -3555.3330     4116.0000     6879.2041   240
+  1009     -861.2560    -1071.0000     6918.8022   241
+  1009     -861.2560     1071.0000     6918.8022   242
+  1008    -5535.9390    -5500.0000     6943.5508   243
+  1008    -5535.9390     5500.0000     6943.5508   244
+  1009     -949.6444    -3211.0000     7008.6045   245
+  1009     -949.6444     3211.0000     7008.6045   246
+  1004     7966.2783        0.0000     7071.7651   247
+  1016     7925.4941        0.0000     7090.7822   248
+  1008    -3767.4648    -6172.0000     7094.1646   249
+  1008    -3767.4648     6172.0000     7094.1646   250
+  1018    -8518.5156        0.0000     7147.1978   251
+  1009    -1126.4211    -5350.0000     7186.7954   252
+  1009    -1126.4211     5350.0000     7186.7954   253
+  1008    -4391.8403     -500.0000     7213.6655   254
+  1008    -4391.8403      500.0000     7213.6655   255
+  1008    -4412.3462    -1500.0000     7234.1719   256
+  1008    -4412.3462     1500.0000     7234.1719   257
+  1008    -4454.0654    -2500.0000     7275.8911   258
+  1008    -4454.0654     2500.0000     7275.8911   259
+  1008    -4516.2910    -3500.0000     7338.1162   260
+  1008    -4516.2910     3500.0000     7338.1162   261
+  1008    -2571.7473    -1029.0000     7349.4302   262
+  1008    -2571.7473     1029.0000     7349.4302   263
+  1004     8096.5376        0.0000     7364.3447   264
+  1016     8055.1143        0.0000     7381.9272   265
+  1008    -4599.7295    -4500.0000     7421.5552   266
+  1008    -4599.7295     4500.0000     7421.5552   267
+  1008    -2656.6001    -3087.0000     7435.6973   268
+  1008    -2656.6001     3087.0000     7435.6973   269
+  1009    -1391.5862    -7485.0000     7454.7891   270
+  1009    -1391.5862     7485.0000     7454.7891   271
+  1008    -4703.6743    -5500.0000     7525.4995   272
+  1008    -4703.6743     5500.0000     7525.4995   273
+  1008    -2827.7200    -5145.0000     7606.8169   274
+  1008    -2827.7200     5145.0000     7606.8169   275
+  1002        0.0000   -10722.0000     7612.5000   276
+  1002    -2489.0000    -8800.0000     7612.5000   277
+  1002     2489.0000    -8800.0000     7612.5000   278
+  1002    -2489.0000     8800.0000     7612.5000   279
+  1002     2489.0000     8800.0000     7612.5000   280
+  1002        0.0000    10722.0000     7612.5000   281
+  1008    -4828.8320    -6500.0000     7650.6577   282
+  1008    -4828.8320     6500.0000     7650.6577   283
+  1004     8216.5059        0.0000     7661.2925   284
+  1011     2935.9075        0.0000     7664.0928   285
+  1016     8174.4946        0.0000     7677.4185   286
+  1008    -3580.7888     -500.0000     7816.8276   287
+  1008    -3580.7888      500.0000     7816.8276   288
+  1008    -3601.2949    -1500.0000     7837.3340   289
+  1008    -3601.2949     1500.0000     7837.3340   290
+  1023     5948.8750        0.0000     7845.8335   291
+  1011     2747.8169    -4516.0000     7852.1831   292
+  1011     2747.8169     4516.0000     7852.1831   293
+  1008    -3082.2786    -7200.0000     7864.2041   294
+  1008    -3082.2786     7200.0000     7864.2041   295
+  1008    -3643.0142    -2500.0000     7879.0532   296
+  1008    -3643.0142     2500.0000     7879.0532   297
+  1022     5879.3013    -2259.0000     7915.4072   298
+  1022     5879.3013     2259.0000     7915.4072   299
+  1008    -3705.2395    -3500.0000     7941.2783   300
+  1008    -3705.2395     3500.0000     7941.2783   301
+  1004     8326.0371        0.0000     7962.2461   302
+  1016     8283.4893        0.0000     7976.8965   303
+  1008    -1758.5746        0.0000     7991.4829   304
+  1008    -3788.6782    -4500.0000     8024.7173   305
+  1008    -3788.6782     4500.0000     8024.7173   306
+  1008    -1801.0010    -2058.0000     8033.9097   307
+  1008    -1801.0010     2058.0000     8033.9097   308
+  1011     2513.7646    -6767.0000     8086.2354   309
+  1011     2513.7646     6767.0000     8086.2354   310
+  1008    -3892.6228    -5500.0000     8128.6616   311
+  1008    -3892.6228     5500.0000     8128.6616   312
+  1008    -1928.9873    -4116.0000     8163.3101   313
+  1008    -1928.9873     4116.0000     8163.3101   314
+  1008    -4017.7808    -6500.0000     8253.8193   315
+  1008    -4017.7808     6500.0000     8253.8193   316
+  1004     8424.9990        0.0000     8266.8398   317
+  1016     8381.9648        0.0000     8279.9951   318
+  1009      741.7550    -1071.0000     8343.6221   319
+  1009      741.7550     1071.0000     8343.6221   320
+  1008    -2142.5334    -6173.0000     8376.8564   321
+  1008    -2142.5334     6173.0000     8376.8564   322
+  1008    -4162.7378    -7500.0000     8398.7764   323
+  1008    -4162.7378     7500.0000     8398.7764   324
+  1009      652.6595    -3212.0000     8432.7178   325
+  1009      652.6595     3212.0000     8432.7178   326
+  1008    -2790.2434     -500.0000     8440.4961   327
+  1008    -2790.2434      500.0000     8440.4961   328
+  1016     8433.8447        0.0000     8456.0068   329
+  1008    -2811.4565    -1500.0000     8461.7090   330
+  1008    -2811.4565     1500.0000     8461.7090   331
+  1006    -9350.7803        0.0000     8478.6797   332
+  1008    -2853.1758    -2500.0000     8503.4287   333
+  1008    -2853.1758     2500.0000     8503.4287   334
+  1021     8212.5859        0.0000     8518.8135   335
+  1008    -2915.4014    -3500.0000     8565.6533   336
+  1008    -2915.4014     3500.0000     8565.6533   337
+  1004     8513.2695        0.0000     8574.7012   338
+  1016     8469.8018        0.0000     8586.3477   339
+  1009      475.8829    -5351.0000     8610.9082   340
+  1009      475.8829     5351.0000     8610.9082   341
+  1008    -2998.1328    -4500.0000     8648.3857   342
+  1008    -2998.1328     4500.0000     8648.3857   343
+  1008    -2440.9326    -8228.0000     8676.6699   344
+  1008     -987.8282    -1029.0000     8675.9629   345
+  1008     -987.8282     1029.0000     8675.9629   346
+  1008    -2440.9326     8228.0000     8676.6699   347
+  1008    -3102.0774    -5500.0000     8752.3301   348
+  1008    -3102.0774     5500.0000     8752.3301   349
+  1008    -1072.6810    -3088.0000     8762.2295   350
+  1008    -1072.6810     3088.0000     8762.2295   351
+  1001      209.3036    -7487.0000     8877.4883   352
+  1008    -3227.2354    -6500.0000     8877.4883   353
+  1008    -3227.2354     6500.0000     8877.4883   354
+  1001      209.3036     7487.0000     8877.4883   355
+  1004     8590.7412        0.0000     8885.4561   356
+  1016     8546.8936        0.0000     8895.5771   357
+  1008    -1243.8008    -5145.0000     8933.3496   358
+  1008    -1243.8008     5145.0000     8933.3496   359
+  1008    -3372.8994    -7500.0000     9023.1523   360
+  1008    -3372.8994     7500.0000     9023.1523   361
+  1008    -2020.9111     -500.0000     9085.3770   362
+  1008    -2020.9111      500.0000     9085.3770   363
+  1008    -2041.4172    -1500.0000     9105.8838   364
+  1008    -2041.4172     1500.0000     9105.8838   365
+  1008    -2083.1365    -2500.0000     9147.6025   366
+  1008    -2083.1365     2500.0000     9147.6025   367
+  1018    -9748.8809        0.0000     9155.3809   368
+  1008    -3539.0693    -8500.0000     9189.3223   369
+  1001    -1500.4806    -7201.0000     9190.0293   370
+  1008    -3539.0693     8500.0000     9189.3223   371
+  1001    -1500.4806     7201.0000     9190.0293   372
+  1004     8657.3193        0.0000     9198.7256   373
+  1016     8613.1465        0.0000     9207.3105   374
+  1008    -2146.0691    -3500.0000     9210.5352   375
+  1008    -2146.0691     3500.0000     9210.5352   376
+  1008    -2228.8005    -4500.0000     9293.2666   377
+  1008    -2228.8005     4500.0000     9293.2666   378
+  1011     4439.2163    -2259.0000     9355.4922   379
+  1011     4439.2163     2259.0000     9355.4922   380
+  1008     -217.0818        0.0000     9361.8564   381
+  1001    -1702.0060    -8500.0000     9392.9688   382
+  1001    -1702.0060     8500.0000     9392.9688   383
+  1008    -2332.7454    -5500.0000     9397.2109   384
+  1008    -2332.7454     5500.0000     9397.2109   385
+  1008     -259.5082    -2059.0000     9404.2822   386
+  1008     -259.5082     2059.0000     9404.2822   387
+  1004     8712.9248        0.0000     9514.1270   388
+  1016     8668.4785        0.0000     9521.1660   389
+  1008    -2457.9031    -6500.0000     9522.3691   390
+  1008    -2457.9031     6500.0000     9522.3691   391
+  1008     -388.2016    -4117.0000     9532.9756   392
+  1008     -388.2016     4117.0000     9532.9756   393
+  1022     7335.5439        0.0000     9651.0449   394
+  1008    -2603.5671    -7500.0000     9668.0332   395
+  1008    -2603.5671     7500.0000     9668.0332   396
+  1023     7264.1255    -2256.9988     9719.6338   397
+  1023     7264.1255     2256.9988     9719.6338   398
+  1011     4061.6213    -6766.0000     9727.4307   399
+  1011     4061.6213     6766.0000     9727.4307   400
+  1008     -601.7479    -6174.0000     9746.5225   401
+  1008     -601.7479     6174.0000     9746.5225   402
+  1008    -1272.0851     -500.0000     9750.7646   403
+  1008    -1272.0851      500.0000     9750.7646   404
+  1008    -1293.2983    -1500.0000     9771.9775   405
+  1008    -1293.2983     1500.0000     9771.9775   406
+  1008    -1334.3105    -2500.0000     9812.9902   407
+  1008    -1334.3105     2500.0000     9812.9902   408
+  1004     8757.4883        0.0000     9831.2783   409
+  1008    -2769.7373    -8500.0000     9834.2031   410
+  1008    -2769.7373     8500.0000     9834.2031   411
+  1016     8712.8232        0.0000     9836.7607   412
+  1009     2256.3777    -1071.0000     9858.2451   413
+  1009     2256.3777     1071.0000     9858.2451   414
+  1008    -1397.2430    -3500.0000     9875.9229   415
+  1008    -1397.2430     3500.0000     9875.9229   416
+  1001     -751.6545    -7201.0000     9896.4287   417
+  1001     -751.6545     7201.0000     9896.4287   418
+  1009     2167.2822    -3212.0000     9947.3408   419
+  1009     2167.2822     3212.0000     9947.3408   420
+  1008    -1479.9745    -4500.0000     9958.6543   421
+  1008    -1479.9745     4500.0000     9958.6543   422
+  1008    -1583.9192    -5500.0000    10062.5986   423
+  1008    -1583.9192     5500.0000    10062.5986   424
+  1001     -940.4520    -8500.0000    10085.2266   425
+  1001     -940.4520     8500.0000    10085.2266   426
+  1008      510.5311    -1029.0000    10089.4688   427
+  1008      510.5311     1029.0000    10089.4688   428
+  1009     1989.0914    -5351.0000    10124.1172   429
+  1009     1989.0914     5351.0000    10124.1172   430
+  1002        0.0000   -10215.0000    10150.0000   431
+  1013        0.0000    -9200.0000    10150.0000   432
+  1014    -1415.0000    -8800.0000    10150.0000   433
+  1013        0.0000    -8800.0000    10150.0000   434
+  1014     1415.0000    -8800.0000    10150.0000   435
+  1004     8790.9551        0.0000    10149.7900   436
+  1002    -1415.0000     8800.0000    10150.0000   437
+  1013        0.0000     8800.0000    10150.0000   438
+  1002     1415.0000     8800.0000    10150.0000   439
+  1013        0.0000     9200.0000    10150.0000   440
+  1014        0.0000    10215.0000    10150.0000   441
+  1016     8746.1260        0.0000    10153.7109   442
+  1008      424.9712    -3088.0000    10175.0293   443
+  1008      424.9712     3088.0000    10175.0293   444
+  1008    -1709.0771    -6500.0000    10187.7568   445
+  1008    -1709.0771     6500.0000    10187.7568   446
+  1001    -1854.7411    -7500.0000    10333.4209   447
+  1001    -1854.7411     7500.0000    10333.4209   448
+  1008      253.8513    -5145.0000    10346.1484   449
+  1008      253.8513     5145.0000    10346.1484   450
+  1001     1722.5121    -7487.0000    10390.6963   451
+  1001     1722.5121     7487.0000    10390.6963   452
+  1008     -544.4722     -500.0000    10437.3652   453
+  1008     -544.4722      500.0000    10437.3652   454
+  1008     -564.9783    -1500.0000    10457.8711   455
+  1008     -564.9783     1500.0000    10457.8711   456
+  1004     8813.2852        0.0000    10469.2773   457
+  1016     8768.3467        0.0000    10471.6309   458
+  1001    -2020.9111    -8500.0000    10499.5908   459
+  1008     -606.6976    -2500.0000    10499.5908   460
+  1008     -606.6976     2500.0000    10499.5908   461
+  1001    -2020.9111     8500.0000    10499.5908   462
+  1018   -10510.4355        0.0000    10529.2891   463
+  1008     -668.9230    -3500.0000    10561.8164   464
+  1008     -668.9230     3500.0000    10561.8164   465
+  1013        0.0000    -9200.0000    10600.0000   466
+  1013        0.0000    -8800.0000    10600.0000   467
+  1001        0.0000    -8500.0000    10600.0000   468
+  1001        0.0000     8500.0000    10600.0000   469
+  1013        0.0000     8800.0000    10600.0000   470
+  1013        0.0000     9200.0000    10600.0000   471
+  1001       -2.8284    -7202.0000    10602.8281   472
+  1001       -2.8284     7202.0000    10602.8281   473
+  1008     -752.3616    -4500.0000    10645.2549   474
+  1008     -752.3616     4500.0000    10645.2549   475
+  1008     -856.3063    -5500.0000    10749.1992   476
+  1008     -856.3063     5500.0000    10749.1992   477
+  1004     8824.4512        0.0000    10789.3486   478
+  1016     8779.4580        0.0000    10790.1328   479
+  1008     1238.1439        0.0000    10817.0820   480
+  1008     1195.7175    -2059.0000    10859.5078   481
+  1008     1195.7175     2059.0000    10859.5078   482
+  1008     -980.7571    -6500.0000    10873.6504   483
+  1008     -980.7571     6500.0000    10873.6504   484
+  1008     1067.0242    -4117.0000    10988.2012   485
+  1008     1067.0242     4117.0000    10988.2012   486
+  1001    -1126.4211    -7500.0000    11019.3145   487
+  1001    -1126.4211     7500.0000    11019.3145   488
+  1011     5941.1113        0.0000    11045.4775   489
+  1016     8779.4473        0.0000    11108.8281   490
+  1004     8824.4404        0.0000    11109.6152   491
+  1008      162.6346     -500.0000    11144.4727   492
+  1008      162.6346      500.0000    11144.4727   493
+  1008      142.1285    -1500.0000    11164.9785   494
+  1008      142.1285     1500.0000    11164.9785   495
+  1006    -1293.2983    -8500.0000    11186.1914   496
+  1006    -1293.2983     8500.0000    11186.1914   497
+  1008      853.4779    -6174.0000    11201.7480   498
+  1008      853.4779     6174.0000    11201.7480   499
+  1008      100.4092    -2500.0000    11206.6973   500
+  1008      100.4092     2500.0000    11206.6973   501
+  1011     5750.8994    -4512.0000    11230.0322   502
+  1011     5750.8994     4512.0000    11230.0322   503
+  1008       38.1838    -3500.0000    11268.9229   504
+  1008       38.1838     3500.0000    11268.9229   505
+  1001      703.5712    -7201.0000    11351.6543   506
+  1008      -45.2548    -4500.0000    11352.3613   507
+  1001      703.5712     7201.0000    11351.6543   508
+  1008      -45.2548     4500.0000    11352.3613   509
+  1016     8768.3125        0.0000    11427.3281   510
+  1004     8813.2510        0.0000    11429.6855   511
+  1008     -149.1995    -5500.0000    11456.3066   512
+  1008     -149.1995     5500.0000    11456.3066   513
+  1009     3681.1980    -1071.0000    11461.2559   514
+  1009     3681.1980     1071.0000    11461.2559   515
+  1021     8532.3037        0.0000    11523.3252   516
+  1016     8761.8242        0.0000    11538.1641   517
+  1001      514.7737    -8500.0000    11540.4521   518
+  1001      514.7737     8500.0000    11540.4521   519
+  1009     3591.3953    -3211.0000    11549.6445   520
+  1009     3591.3953     3211.0000    11549.6445   521
+  1008     -273.6503    -6500.0000    11580.7568   522
+  1008     -273.6503     6500.0000    11580.7568   523
+  1008     1924.0376    -1029.0000    11587.8281   524
+  1008     1924.0376     1029.0000    11587.8281   525
+  1008     1837.7705    -3088.0000    11672.6807   526
+  1008     1837.7705     3088.0000    11672.6807   527
+  1001     -419.3143    -7500.0000    11726.4209   528
+  1009     3413.2043    -5350.0000    11726.4209   529
+  1009     3413.2043     5350.0000    11726.4209   530
+  1001     -419.3143     7500.0000    11726.4209   531
+  1016     8746.0693        0.0000    11745.2471   532
+  1004     8790.8984        0.0000    11749.1699   533
+  1008     1666.6506    -5145.0000    11843.8008   534
+  1008     1666.6506     5145.0000    11843.8008   535
+  1008      849.2352     -500.0000    11872.0850   536
+  1008      849.2352      500.0000    11872.0850   537
+  1006     -586.1915    -8500.0000    11893.2979   538
+  1008      828.0220    -1500.0000    11893.2979   539
+  1008      828.0220     1500.0000    11893.2979   540
+  1006     -586.1915     8500.0000    11893.2979   541
+  1018   -11223.9062        0.0000    11928.6533   542
+  1008      787.0098    -2500.0000    11934.3105   543
+  1008      787.0098     2500.0000    11934.3105   544
+  1009     3145.2109    -7485.0000    11991.5859   545
+  1009     3145.2109     7485.0000    11991.5859   546
+  1008      724.0773    -3500.0000    11997.2432   547
+  1008      724.0773     3500.0000    11997.2432   548
+  1016     8712.7441        0.0000    12062.1953   549
+  1004     8757.4082        0.0000    12067.6807   550
+  1008      641.3458    -4500.0000    12079.9746   551
+  1008      641.3458     4500.0000    12079.9746   552
+  1008     1409.9709    -7201.0000    12100.4805   553
+  1008     1409.9709     7201.0000    12100.4805   554
+  1008      537.4012    -5500.0000    12183.9189   555
+  1008      537.4012     5500.0000    12183.9189   556
+  1008     1207.0312    -8500.0000    12302.0059   557
+  1008     1207.0312     8500.0000    12302.0059   558
+  1008      412.2433    -6500.0000    12309.0771   559
+  1008      412.2433     6500.0000    12309.0771   560
+  1008     2608.5168        0.0000    12358.5742   561
+  1016     8668.3770        0.0000    12377.7861   562
+  1004     8712.8232        0.0000    12384.8281   563
+  1008     2566.0906    -2058.0000    12401.0010   564
+  1008     2566.0906     2058.0000    12401.0010   565
+  1008      266.5793    -7500.0000    12454.7412   566
+  1008      266.5793     7500.0000    12454.7412   567
+  1008     2436.6899    -4116.0000    12528.9873   568
+  1008     2436.6899     4116.0000    12528.9873   569
+  1008      100.4092    -8500.0000    12620.9111   570
+  1008     1514.6227     -500.0000    12620.9111   571
+  1008     1514.6227      500.0000    12620.9111   572
+  1008      100.4092     8500.0000    12620.9111   573
+  1008     1494.1166    -1500.0000    12641.4170   574
+  1008     1494.1166     1500.0000    12641.4170   575
+  1009     3968.2832    -6417.0000    12681.7227   576
+  1009     3968.2832     6417.0000    12681.7227   577
+  1008     1452.3973    -2500.0000    12683.1367   578
+  1008     1452.3973     2500.0000    12683.1367   579
+  1016     8613.0225        0.0000    12691.6377   580
+  1004     8657.1953        0.0000    12700.2266   581
+  1008     2223.1438    -6173.0000    12742.5332   582
+  1008     2223.1438     6173.0000    12742.5332   583
+  1008     1389.4648    -3500.0000    12746.0693   584
+  1008     1389.4648     3500.0000    12746.0693   585
+  1008     1306.7333    -4500.0000    12828.8008   586
+  1008     1306.7333     4500.0000    12828.8008   587
+  1011     7298.7563        0.0000    12871.2266   588
+  1011     7251.3799    -2255.0000    12917.1885   589
+  1011     7251.3799     2255.0000    12917.1885   590
+  1008     1202.7886    -5500.0000    12932.7451   591
+  1008     1202.7886     5500.0000    12932.7451   592
+  1016     8546.7480        0.0000    13003.3662   593
+  1004     8590.5947        0.0000    13013.4912   594
+  1021     8303.8340        0.0000    13031.4053   595
+  1008     1923.3304    -8228.0000    13040.9326   596
+  1008     1923.3304     8228.0000    13040.9326   597
+  1008     1077.6307    -6500.0000    13057.9033   598
+  1008     1077.6307     6500.0000    13057.9033   599
+  1016     8527.4502        0.0000    13085.2168   600
+  1009     5016.2153    -1070.0000    13151.2412   601
+  1009     5016.2153     1070.0000    13151.2412   602
+  1008     3250.5698    -1029.0000    13171.7471   603
+  1008     3250.5698     1029.0000    13171.7471   604
+  1008      931.9667    -7500.0000    13203.5674   605
+  1008      931.9667     7500.0000    13203.5674   606
+  1009     4926.4131    -3210.0000    13239.6299   607
+  1009     4926.4131     3210.0000    13239.6299   608
+  1008     3164.3027    -3087.0000    13256.6006   609
+  1008     3164.3027     3087.0000    13256.6006   610
+  1016     8469.6348        0.0000    13312.5918   611
+  1004     8513.1006        0.0000    13324.2402   612
+  1018   -11887.8789        0.0000    13352.0596   613
+  1008      765.7966    -8500.0000    13369.7373   614
+  1008      765.7966     8500.0000    13369.7373   615
+  1008     2159.5042     -500.0000    13390.2432   616
+  1008     2159.5042      500.0000    13390.2432   617
+  1008     2138.2910    -1500.0000    13411.4570   618
+  1008     2138.2910     1500.0000    13411.4570   619
+  1009     4747.5151    -5348.0000    13415.6992   620
+  1009     4747.5151     5348.0000    13415.6992   621
+  1008     2993.1831    -5145.0000    13427.7197   622
+  1008     2993.1831     5145.0000    13427.7197   623
+  1008     2096.5715    -2500.0000    13453.1758   624
+  1008     2096.5715     2500.0000    13453.1758   625
+  1008     2034.3462    -3500.0000    13515.4014   626
+  1008     2034.3462     3500.0000    13515.4014   627
+  1008     1951.6147    -4500.0000    13598.1328   628
+  1008     1951.6147     4500.0000    13598.1328   629
+  1016     8381.7754        0.0000    13618.9365   630
+  1004     8424.8086        0.0000    13632.0957   631
+  1008     2735.7961    -7200.0000    13682.2783   632
+  1008     2735.7961     7200.0000    13682.2783   633
+  1008     1847.6700    -5500.0000    13702.0771   634
+  1008     1847.6700     5500.0000    13702.0771   635
+  1008     1722.5121    -6500.0000    13827.2354   636
+  1008     1722.5121     6500.0000    13827.2354   637
+  1016     8283.2783        0.0000    13922.0293   638
+  1004     8325.8252        0.0000    13936.6816   639
+  1008     1576.8481    -7500.0000    13972.8994   640
+  1008     1576.8481     7500.0000    13972.8994   641
+  1008     3891.9158        0.0000    13984.2129   642
+  1008     3849.4893    -2058.0000    14026.6396   643
+  1008     3849.4893     2058.0000    14026.6396   644
+  1008     1410.6780    -8500.0000    14139.0693   645
+  1008     1410.6780     8500.0000    14139.0693   646
+  1008     3720.7959    -4116.0000    14155.3330   647
+  1008     3720.7959     4116.0000    14155.3330   648
+  1008     2783.1724     -500.0000    14180.7891   649
+  1008     2783.1724      500.0000    14180.7891   650
+  1009     5480.7847    -4278.0000    14194.2236   651
+  1009     5480.7847     4278.0000    14194.2236   652
+  1008     2762.6663    -1500.0000    14201.2949   653
+  1008     2762.6663     1500.0000    14201.2949   654
+  1016     8174.2627        0.0000    14221.4990   655
+  1004     8216.2725        0.0000    14237.6279   656
+  1008     2720.9468    -2500.0000    14243.0137   657
+  1008     2720.9468     2500.0000    14243.0137   658
+  1008     2658.7214    -3500.0000    14305.2393   659
+  1008     2658.7214     3500.0000    14305.2393   660
+  1008     3505.8354    -6172.0000    14367.4648   661
+  1008     3505.8354     6172.0000    14367.4648   662
+  1008     2575.2830    -4500.0000    14388.6777   663
+  1008     2575.2830     4500.0000    14388.6777   664
+  1021     7818.6538        0.0000    14484.2480   665
+  1008     2471.3381    -5500.0000    14492.6230   666
+  1008     2471.3381     5500.0000    14492.6230   667
+  1016     8054.8618        0.0000    14516.9824   668
+  1004     8096.2832        0.0000    14534.5674   669
+  1016     8029.7319        0.0000    14575.6045   670
+  1008     2346.1804    -6500.0000    14617.7803   671
+  1008     2346.1804     6500.0000    14617.7803   672
+  1008     2201.2234    -7500.0000    14762.7373   673
+  1008     2201.2234     7500.0000    14762.7373   674
+  1018   -12500.9404        0.0000    14798.0928   675
+  1016     7925.2202        0.0000    14808.1172   676
+  1004     7966.0034        0.0000    14827.1377   677
+  1008     4491.5425    -1029.0000    14839.8125   678
+  1008     4491.5425     1029.0000    14839.8125   679
+  1008     4405.2754    -3087.0000    14924.6650   680
+  1008     4405.2754     3087.0000    14924.6650   681
+  1009     6260.0161    -1070.0000    14928.2002   682
+  1009     6260.0161     1070.0000    14928.2002   683
+  1008     3386.3345     -500.0000    14991.8398   684
+  1008     3386.3345      500.0000    14991.8398   685
+  1008     3365.8284    -1500.0000    15012.3467   686
+  1008     3365.8284     1500.0000    15012.3467   687
+  1009     6169.5068    -3208.0000    15015.8818   688
+  1009     6169.5068     3208.0000    15015.8818   689
+  1008     3324.1089    -2500.0000    15054.0654   690
+  1008     3324.1089     2500.0000    15054.0654   691
+  1008     4233.4482    -5143.0000    15095.0781   692
+  1016     7785.4976        0.0000    15094.5508   693
+  1008     4233.4482     5143.0000    15095.0781   694
+  1004     7825.5923        0.0000    15114.9834   695
+  1008     3261.8835    -3500.0000    15116.2910   696
+  1008     3261.8835     3500.0000    15116.2910   697
+  1008     3178.4451    -4500.0000    15199.7295   698
+  1008     3178.4451     4500.0000    15199.7295   699
+  1008     3074.5002    -5500.0000    15303.6738   700
+  1008     3074.5002     5500.0000    15303.6738   701
+  1016     7635.8633        0.0000    15375.9336   702
+  1004     7675.2202        0.0000    15397.7529   703
+  1008     2949.3423    -6500.0000    15428.8320   704
+  1008     2949.3423     6500.0000    15428.8320   705
+  1018   -12789.4404        0.0000    15529.2412   706
+  1016     7476.4995        0.0000    15651.9229   707
+  1004     7515.0703        0.0000    15675.1016   708
+  1008     5089.7544        0.0000    15695.4111   709
+  1008     5046.6211    -2058.0000    15737.1309   710
+  1008     5046.6211     2058.0000    15737.1309   711
+  1008     3968.9905     -500.0000    15823.3975   712
+  1008     3968.9905      500.0000    15823.3975   713
+  1008     3947.7771    -1500.0000    15844.6113   714
+  1008     3947.7771     1500.0000    15844.6113   715
+  1008     4917.9277    -4114.0000    15864.4102   716
+  1008     4917.9277     4114.0000    15864.4102   717
+  1008     3906.0579    -2500.0000    15886.3301   718
+  1008     3906.0579     2500.0000    15886.3301   719
+  1016     7307.6006        0.0000    15922.1816   720
+  1004     7345.3384        0.0000    15946.6924   721
+  1008     3843.8325    -3500.0000    15948.5557   722
+  1008     3843.8325     3500.0000    15948.5557   723
+  1008     3760.3938    -4500.0000    16031.9941   724
+  1008     3760.3938     4500.0000    16031.9941   725
+  1008     3656.4492    -5500.0000    16135.9395   726
+  1008     3656.4492     5500.0000    16135.9395   727
+  1016     7129.3716        0.0000    16186.3809   728
+  1004     7166.2314        0.0000    16212.1943   729
+  1018   -13063.7979        0.0000    16264.6328   730
+  1016     6942.0303        0.0000    16444.1992   731
+  1021     6634.1621        0.0000    16466.6973   732
+  1004     6977.9673        0.0000    16471.2832   733
+  1008     5656.1470        0.0000    16581.4160   734
+  1007     5645.5405    -1029.0000    16592.0234   735
+  1007     5645.5405     1029.0000    16592.0234   736
+  1016     6814.6299        0.0000    16609.2871   737
+  1008     5613.0137    -2057.0000    16624.5488   738
+  1008     5613.0137     2057.0000    16624.5488   739
+  1008     4530.4331     -500.0000    16676.1680   740
+  1008     4530.4331      500.0000    16676.1680   741
+  1008     5559.2734    -3086.0000    16676.8750   742
+  1008     5559.2734     3086.0000    16676.8750   743
+  1016     6745.8057        0.0000    16695.3203   744
+  1008     4509.2197    -1500.0000    16697.3809   745
+  1008     4509.2197     1500.0000    16697.3809   746
+  1004     6780.7754        0.0000    16723.6426   747
+  1008     4467.5005    -2500.0000    16739.1016   748
+  1008     4467.5005     2500.0000    16739.1016   749
+  1008     4405.2754    -3500.0000    16801.3262   750
+  1008     4405.2754     3500.0000    16801.3262   751
+  1008     4322.5439    -4500.0000    16884.0586   752
+  1008     4322.5439     4500.0000    16884.0586   753
+  1016     6540.9360        0.0000    16939.4414   754
+  1004     6574.8955        0.0000    16968.9668   755
+  1018   -13294.3145        0.0000    16994.3672   756
+  1016     6327.6709        0.0000    17176.2637   757
+  1004     6360.5796        0.0000    17206.9570   758
+  1016     6106.2705        0.0000    17405.5000   759
+  1004     6138.0879        0.0000    17437.3223   760
+  1007     5070.6626     -500.0000    17550.1523   761
+  1007     5070.6626      500.0000    17550.1523   762
+  1008     5050.1567    -1500.0000    17570.6582   763
+  1008     5050.1567     1500.0000    17570.6582   764
+  1021     5570.2158        0.0000    17595.2852   765
+  1008     5008.4375    -2500.0000    17612.3789   766
+  1008     5008.4375     2500.0000    17612.3789   767
+  1016     5877.0039        0.0000    17626.8672   768
+  1004     5907.6919        0.0000    17659.7812   769
+  1008     4946.2119    -3500.0000    17674.6035   770
+  1008     4946.2119     3500.0000    17674.6035   771
+  1018   -13460.4844        0.0000    17740.3652   772
+  1016     5723.1885        0.0000    17767.0391   773
+  1018     4755.2930        0.0000    18240.2891   774
+  1018   -13561.6016        0.0000    18499.0898   775
+  1018     3452.8025        0.0000    19118.5156   776
+  1018   -13596.9561        0.0000    19262.7656   777
+  1018     2121.3208        0.0000    19950.7812   778
+  1018   -13565.1367        0.0000    20027.1484   779
+  1018     1444.6191        0.0000    20348.8809   780
+  1018   -13467.5557        0.0000    20785.1660   781
+  1019   -13410.4873        0.0000    21046.2949   782
+  1018       70.7107        0.0000    21110.4355   783
+  1018   -13304.2139        0.0000    21532.5781   784
+  1018    -1328.6537        0.0000    21823.9062   785
+  1018   -13077.2324        0.0000    22263.0195   786
+  1020   -12992.3799     -840.0000    22404.4414   787
+  1020   -12992.3799        0.0000    22404.4414   788
+  1020   -12992.3799      840.0000    22404.4414   789
+  1018    -2752.0596        0.0000    22487.8789   790
+  1020   -13416.6445     -840.0000    22828.7051   791
+  1020   -13416.6445     -655.0000    22828.7051   792
+  1020   -13416.6445      655.0000    22828.7051   793
+  1020   -13416.6445      840.0000    22828.7051   794
+  1018    -4198.0928        0.0000    23100.9414   795
+  1018    -4929.2412        0.0000    23389.4395   796
+  1020   -11804.4404     -840.0000    23592.3809   797
+  1018   -11804.4404        0.0000    23592.3809   798
+  1020   -11804.4404      840.0000    23592.3809   799
+  1018    -5664.6323        0.0000    23663.7969   800
+  1018   -11663.0195        0.0000    23677.2324   801
+  1018    -6394.3667        0.0000    23894.3145   802
+  1018   -10932.5781        0.0000    23904.2148   803
+  1018   -10446.2959        0.0000    24010.4863   804
+  1020   -12228.7051     -840.0000    24016.6445   805
+  1020   -12228.7051     -655.0000    24016.6445   806
+  1020   -12228.7051      655.0000    24016.6445   807
+  1020   -12228.7051      840.0000    24016.6445   808
+  1018    -7140.3643        0.0000    24060.4844   809
+  1018   -10185.1660        0.0000    24067.5566   810
+  1018    -7899.0898        0.0000    24161.6016   811
+  1018    -9427.1475        0.0000    24165.1367   812
+  1018    -8662.7656        0.0000    24196.9570   813
+<# Ende
+<# Staebe           2504     3   813    40  2504  2504
+  2002     1     3     2     0     0     1
+  2002     1     4     2     0     0     2
+  2002     1     5     2     0     0     3
+  2002     1     9     2     0     0     4
+  2002     2     9     2     0     0     5
+  2002     2    13     2     0     0     6
+  2002     2    14     2     0     0     7
+  2002     2    15     2     0     0     8
+  2002     3     4     2     0     0     9
+  2002     3     5     2     0     0    10
+  2012     4     6    12     0     0    11
+  2012     5     7    12     0     0    12
+  2002     4     8     2     0     0    13
+  2002     5    10     2     0     0    14
+  2002     6     8     2     0     0    15
+  2012     6     9    12     0     0    16
+  2012     7     9    12     0     0    17
+  2002     7    10     2     0     0    18
+  2002     6    11     2     0     0    19
+  2002     7    12     2     0     0    20
+  2002     8    11     2     0     0    21
+  2012     9    11    12     0     0    22
+  2012     9    12    12     0     0    23
+  2002    10    12     2     0     0    24
+  2002     8    13     2     0     0    25
+  2002    10    14     2     0     0    26
+  2012    11    13    12     0     0    27
+  2012    12    14    12     0     0    28
+  2002    13    15     2     0     0    29
+  2002    14    15     2     0     0    30
+  2015     9    16    15     0     0    31
+  2002     1    42     2     0     0    32
+  2002     2    45     2     0     0    33
+  2002     3    42     2     0     0    34
+  2002     4    42     2     0     0    35
+  2002     5    42     2     0     0    36
+  2002     6    42     2     0     0    37
+  2002     7    42     2     0     0    38
+  2002     4    43     2     0     0    39
+  2002     9    42     2     0     0    40
+  2002     5    44     2     0     0    41
+  2002     6    43     2     0     0    42
+  2002     7    44     2     0     0    43
+  2002     8    43     2     0     0    44
+  2002    10    44     2     0     0    45
+  2002    11    43     2     0     0    46
+  2002    12    44     2     0     0    47
+  2002    13    43     2     0     0    48
+  2002     9    45     2     0     0    49
+  2002    14    44     2     0     0    50
+  2002    11    45     2     0     0    51
+  2002    12    45     2     0     0    52
+  2002    13    45     2     0     0    53
+  2002    14    45     2     0     0    54
+  2002    15    45     2     0     0    55
+  2003    16    37     3     0     0    56
+  2004    17    18     4     0     0    57
+  2004    17    19     4     0     0    58
+  2004    18    20     4     0     0    59
+  2004    19    21     4     0     0    60
+  2004    20    22     4     0     0    61
+  2017    17    23    17     0     0    62
+  2017    18    24    17     0     0    63
+  2017    19    25    17     0     0    64
+  2017    20    26    17     0     0    65
+  2016    23    24    16     0     0    66
+  2004    21    28     4     0     0    67
+  2004    22    29     4     0     0    68
+  2016    23    25    16     0     0    69
+  2016    24    26    16     0     0    70
+  2017    21    30    17     0     0    71
+  2017    22    31    17     0     0    72
+  2016    26    27    16     0     0    73
+  2016    25    30    16     0     0    74
+  2016    27    31    16     0     0    75
+  2004    28    32     4     0     0    76
+  2017    28    34    17     0     0    77
+  2004    29    33     4     0     0    78
+  2017    29    35    17     0     0    79
+  2016    30    34    16     0     0    80
+  2016    31    35    16     0     0    81
+  2017    32    36    17     0     0    82
+  2016    34    36    16     0     0    83
+  2017    33    37    17     0     0    84
+  2016    35    37    16     0     0    85
+  2004    32    38     4     0     0    86
+  2004    33    39     4     0     0    87
+  2021    27    50    21     0     0    88
+  2016    36    40    16     0     0    89
+  2016    37    41    16     0     0    90
+  2017    38    40    17     0     0    91
+  2017    39    41    17     0     0    92
+  2004    38    46     4     0     0    93
+  2004    39    47     4     0     0    94
+  2002    42    43     2     0     0    95
+  2002    42    44     2     0     0    96
+  2002    43    45     2     0     0    97
+  2002    44    45     2     0     0    98
+  2016    40    48    16     0     0    99
+  2016    41    49    16     0     0   100
+  2017    46    48    17     0     0   101
+  2017    47    49    17     0     0   102
+  2004    46    52     4     0     0   103
+  2004    47    53     4     0     0   104
+  2016    49    51    16     0     0   105
+  2016    48    54    16     0     0   106
+  2016    51    55    16     0     0   107
+  2017    52    54    17     0     0   108
+  2017    53    55    17     0     0   109
+  2004    52    57     4     0     0   110
+  2004    53    58     4     0     0   111
+  2016    54    56    16     0     0   112
+  2016    55    60    16     0     0   113
+  2021    50    63    21     0     0   114
+  2021    51    63    21     0     0   115
+  2016    56    59    16     0     0   116
+  2017    57    59    17     0     0   117
+  2017    58    60    17     0     0   118
+  2004    57    61     4     0     0   119
+  2004    58    62     4     0     0   120
+  2021    50    68    21     0     0   121
+  2016    59    64    16     0     0   122
+  2016    60    65    16     0     0   123
+  2021    56    68    21     0     0   124
+  2017    61    64    17     0     0   125
+  2017    62    65    17     0     0   126
+  2004    61    66     4     0     0   127
+  2004    62    67     4     0     0   128
+  2016    64    69    16     0     0   129
+  2016    65    70    16     0     0   130
+  2017    66    69    17     0     0   131
+  2017    67    70    17     0     0   132
+  2004    66    71     4     0     0   133
+  2004    67    72     4     0     0   134
+  2016    69    73    16     0     0   135
+  2016    70    74    16     0     0   136
+  2017    71    73    17     0     0   137
+  2017    72    74    17     0     0   138
+  2002     3   157     2     0     0   139
+  2002     3   158     2     0     0   140
+  2002     3   159     2     0     0   141
+  2002     4   158     2     0     0   142
+  2002     5   159     2     0     0   143
+  2002    13   160     2     0     0   144
+  2002    14   161     2     0     0   145
+  2002    15   160     2     0     0   146
+  2002    15   161     2     0     0   147
+  2002    15   162     2     0     0   148
+  2021    63    82    21     0     0   149
+  2016    74    75    16     0     0   150
+  2004    71    76     4     0     0   151
+  2004    72    77     4     0     0   152
+  2016    73    78    16     0     0   153
+  2016    75    79    16     0     0   154
+  2017    76    78    17     0     0   155
+  2017    77    79    17     0     0   156
+  2022    50    96    22     0     0   157
+  2021    75    82    21     0     0   158
+  2007    50   101     7     0     0   159
+  2022    50   102    22     0     0   160
+  2022    50   103    22     0     0   161
+  2004    76    80     4     0     0   162
+  2004    77    81     4     0     0   163
+  2023    50   104    23     0     0   164
+  2023    50   105    23     0     0   165
+  2016    78    83    16     0     0   166
+  2016    79    84    16     0     0   167
+  2017    80    83    17     0     0   168
+  2017    81    84    17     0     0   169
+  2007    63   101     7     0     0   170
+  2005    68    96     5     0     0   171
+  2021    68    97    21     0     0   172
+  2004    80    85     4     0     0   173
+  2004    81    86     4     0     0   174
+  2005    68   102     5     0     0   175
+  2005    68   103     5     0     0   176
+  2016    83    87    16     0     0   177
+  2016    84    88    16     0     0   178
+  2017    85    87    17     0     0   179
+  2017    86    88    17     0     0   180
+  2004    85    90     4     0     0   181
+  2004    86    91     4     0     0   182
+  2016    87    89    16     0     0   183
+  2016    88    93    16     0     0   184
+  2007    82   104     7     0     0   185
+  2007    82   105     7     0     0   186
+  2016    89    92    16     0     0   187
+  2017    90    92    17     0     0   188
+  2017    91    93    17     0     0   189
+  2004    90    94     4     0     0   190
+  2004    91    95     4     0     0   191
+  2021    89    97    21     0     0   192
+  2016    92    99    16     0     0   193
+  2016    93   100    16     0     0   194
+  2017    94    99    17     0     0   195
+  2017    95   100    17     0     0   196
+  2022    96   102    22     0     0   197
+  2022    96   103    22     0     0   198
+  2010   101   104    10     0     0   199
+  2010   101   105    10     0     0   200
+  2023   102   104    23     0     0   201
+  2023   103   105    23     0     0   202
+  2004    94   106     4     0     0   203
+  2004    95   107     4     0     0   204
+  2007    50   137     7     0     0   205
+  2023    50   137    23     0     0   206
+  2021    82   119    21     0     0   207
+  2016    99   108    16     0     0   208
+  2016   100   109    16     0     0   209
+  2017   106   108    17     0     0   210
+  2017   107   109    17     0     0   211
+  2005    68   135     5     0     0   212
+  2004   106   110     4     0     0   213
+  2004   107   111     4     0     0   214
+  2002    42   158     2     0     0   215
+  2002    42   159     2     0     0   216
+  2002    45   160     2     0     0   217
+  2002    45   161     2     0     0   218
+  2007    82   128     7     0     0   219
+  2007    82   129     7     0     0   220
+  2016   108   112    16     0     0   221
+  2016   109   113    16     0     0   222
+  2017   110   112    17     0     0   223
+  2017   111   113    17     0     0   224
+  2004   110   115     4     0     0   225
+  2004   111   116     4     0     0   226
+  2016   113   114    16     0     0   227
+  2016   112   117    16     0     0   228
+  2016   114   118    16     0     0   229
+  2011   101   128    11     0     0   230
+  2011   101   129    11     0     0   231
+  2017   115   117    17     0     0   232
+  2017   116   118    17     0     0   233
+  2011   104   128    11     0     0   234
+  2011   105   129    11     0     0   235
+  2021   114   119    21     0     0   236
+  2011   104   130    11     0     0   237
+  2011   105   131    11     0     0   238
+  2004   115   120     4     0     0   239
+  2004   116   121     4     0     0   240
+  2016   117   122    16     0     0   241
+  2016   118   123    16     0     0   242
+  2022    96   135    22     0     0   243
+  2005    97   135     5     0     0   244
+  2021    97   136    21     0     0   245
+  2023    98   137    23     0     0   246
+  2022   102   135    22     0     0   247
+  2022   103   135    22     0     0   248
+  2023   102   137    23     0     0   249
+  2023   103   137    23     0     0   250
+  2005    97   140     5     0     0   251
+  2005    97   141     5     0     0   252
+  2010   104   137    10     0     0   253
+  2010   105   137    10     0     0   254
+  2022   102   140    22     0     0   255
+  2022   103   141    22     0     0   256
+  2017   120   122    17     0     0   257
+  2017   121   123    17     0     0   258
+  2023   102   144    23     0     0   259
+  2023   103   145    23     0     0   260
+  2010   104   144    10     0     0   261
+  2010   105   145    10     0     0   262
+  2004   120   124     4     0     0   263
+  2004   121   125     4     0     0   264
+  2007   119   128     7     0     0   265
+  2007   119   129     7     0     0   266
+  2016   122   126    16     0     0   267
+  2016   123   127    16     0     0   268
+  2011   104   163    11     0     0   269
+  2011   105   164    11     0     0   270
+  2017   124   126    17     0     0   271
+  2017   125   127    17     0     0   272
+  2009   128   129     9     0     0   273
+  2004   125   132     4     0     0   274
+  2016   126   133    16     0     0   275
+  2016   127   134    16     0     0   276
+  2009   128   130     9     0     0   277
+  2009   129   131     9     0     0   278
+  2011   101   176    11     0     0   279
+  2011   101   177    11     0     0   280
+  2007   119   149     7     0     0   281
+  2007   119   150     7     0     0   282
+  2004   124   138     4     0     0   283
+  2011   104   176    11     0     0   284
+  2011   105   177    11     0     0   285
+  2017   132   134    17     0     0   286
+  2021   119   154    21     0     0   287
+  2011   104   182    11     0     0   288
+  2011   105   183    11     0     0   289
+  2021   133   136    21     0     0   290
+  2004   132   139     4     0     0   291
+  2016   133   142    16     0     0   292
+  2016   134   143    16     0     0   293
+  2009   128   148     9     0     0   294
+  2009   129   148     9     0     0   295
+  2009   128   149     9     0     0   296
+  2009   129   150     9     0     0   297
+  2023   135   137    23     0     0   298
+  2009   128   152     9     0     0   299
+  2009   129   153     9     0     0   300
+  2022   135   140    22     0     0   301
+  2022   135   141    22     0     0   302
+  2017   138   142    17     0     0   303
+  2017   139   143    17     0     0   304
+  2009   130   152     9     0     0   305
+  2009   131   153     9     0     0   306
+  2005    97   203     5     0     0   307
+  2009   130   155     9     0     0   308
+  2009   131   156     9     0     0   309
+  2023   102   201    23     0     0   310
+  2023   103   202    23     0     0   311
+  2009   130   163     9     0     0   312
+  2009   131   164     9     0     0   313
+  2004   139   146     4     0     0   314
+  2016   143   146    16     0     0   315
+  2004   138   147     4     0     0   316
+  2016   142   151    16     0     0   317
+  2009   128   169     9     0     0   318
+  2009   129   169     9     0     0   319
+  2017   147   151    17     0     0   320
+  2009   128   174     9     0     0   321
+  2009   129   175     9     0     0   322
+  2008   148   149     8     0     0   323
+  2008   148   150     8     0     0   324
+  2021   146   154    21     0     0   325
+  2009   128   176     9     0     0   326
+  2009   129   177     9     0     0   327
+  2008   149   152     8     0     0   328
+  2008   150   153     8     0     0   329
+  2011   144   163    11     0     0   330
+  2011   145   164    11     0     0   331
+  2009   130   174     9     0     0   332
+  2007   149   154     7     0     0   333
+  2007   150   154     7     0     0   334
+  2009   131   175     9     0     0   335
+  2008   152   155     8     0     0   336
+  2008   153   156     8     0     0   337
+  2009   130   182     9     0     0   338
+  2009   131   183     9     0     0   339
+  2004   147   165     4     0     0   340
+  2009   130   184     9     0     0   341
+  2009   131   185     9     0     0   342
+  2002   157   158     2     0     0   343
+  2002   157   159     2     0     0   344
+  2002   158   159     2     0     0   345
+  2002   160   161     2     0     0   346
+  2002   160   162     2     0     0   347
+  2002   161   162     2     0     0   348
+  2016   151   166    16     0     0   349
+  2011   137   176    11     0     0   350
+  2011   137   177    11     0     0   351
+  2017   165   166    17     0     0   352
+  2009   128   197     9     0     0   353
+  2009   129   198     9     0     0   354
+  2008   149   169     8     0     0   355
+  2008   150   169     8     0     0   356
+  2008   148   170     8     0     0   357
+  2008   148   171     8     0     0   358
+  2008   149   170     8     0     0   359
+  2008   150   171     8     0     0   360
+  2008   149   172     8     0     0   361
+  2008   150   173     8     0     0   362
+  2008   149   174     8     0     0   363
+  2008   150   175     8     0     0   364
+  2011   144   182    11     0     0   365
+  2011   145   183    11     0     0   366
+  2008   152   172     8     0     0   367
+  2008   153   173     8     0     0   368
+  2007   154   170     7     0     0   369
+  2007   154   171     7     0     0   370
+  2008   152   178     8     0     0   371
+  2008   153   179     8     0     0   372
+  2008   155   174     8     0     0   373
+  2008   156   175     8     0     0   374
+  2004   165   167     4     0     0   375
+  2009   130   205     9     0     0   376
+  2009   131   206     9     0     0   377
+  2008   155   178     8     0     0   378
+  2008   156   179     8     0     0   379
+  2016   166   168    16     0     0   380
+  2008   155   180     8     0     0   381
+  2008   156   181     8     0     0   382
+  2011   144   189    11     0     0   383
+  2011   145   190    11     0     0   384
+  2016   146   188    16     0     0   385
+  2008   155   184     8     0     0   386
+  2008   156   185     8     0     0   387
+  2009   163   184     9     0     0   388
+  2009   164   185     9     0     0   389
+  2023   135   201    23     0     0   390
+  2023   135   202    23     0     0   391
+  2010   137   201    10     0     0   392
+  2010   137   202    10     0     0   393
+  2022   135   203    22     0     0   394
+  2005   136   203     5     0     0   395
+  2021   154   188    21     0     0   396
+  2023   140   201    23     0     0   397
+  2023   141   202    23     0     0   398
+  2017   167   168    17     0     0   399
+  2022   135   210    22     0     0   400
+  2022   135   211    22     0     0   401
+  2005   136   210     5     0     0   402
+  2005   136   211     5     0     0   403
+  2022   140   210    22     0     0   404
+  2022   141   211    22     0     0   405
+  2009   163   189     9     0     0   406
+  2009   164   190     9     0     0   407
+  2010   144   201    10     0     0   408
+  2010   145   202    10     0     0   409
+  2008   148   193     8     0     0   410
+  2008   148   194     8     0     0   411
+  2008   149   193     8     0     0   412
+  2008   150   194     8     0     0   413
+  2008   149   195     8     0     0   414
+  2008   150   196     8     0     0   415
+  2008   170   171     8     0     0   416
+  2008   152   195     8     0     0   417
+  2008   153   196     8     0     0   418
+  2008   170   172     8     0     0   419
+  2008   171   173     8     0     0   420
+  2021   136   217    21     0     0   421
+  2004   167   186     4     0     0   422
+  2008   152   199     8     0     0   423
+  2008   153   200     8     0     0   424
+  2008   172   178     8     0     0   425
+  2008   173   179     8     0     0   426
+  2016   168   187    16     0     0   427
+  2009   176   177     9     0     0   428
+  2008   155   199     8     0     0   429
+  2008   156   200     8     0     0   430
+  2008   155   204     8     0     0   431
+  2008   156   207     8     0     0   432
+  2008   178   180     8     0     0   433
+  2008   179   181     8     0     0   434
+  2009   176   182     9     0     0   435
+  2009   177   183     9     0     0   436
+  2009   163   205     9     0     0   437
+  2009   164   206     9     0     0   438
+  2007   170   188     7     0     0   439
+  2007   171   188     7     0     0   440
+  2010   144   220    10     0     0   441
+  2010   145   221    10     0     0   442
+  2017   186   187    17     0     0   443
+  2011   144   223    11     0     0   444
+  2011   145   225    11     0     0   445
+  2009   163   215     9     0     0   446
+  2009   164   216     9     0     0   447
+  2009   182   189     9     0     0   448
+  2009   183   190     9     0     0   449
+  2011   137   241    11     0     0   450
+  2011   137   242    11     0     0   451
+  2008   169   193     8     0     0   452
+  2008   169   194     8     0     0   453
+  2008   170   193     8     0     0   454
+  2008   171   194     8     0     0   455
+  2008   169   197     8     0     0   456
+  2008   169   198     8     0     0   457
+  2004   186   191     4     0     0   458
+  2008   172   195     8     0     0   459
+  2008   173   196     8     0     0   460
+  2008   174   195     8     0     0   461
+  2008   175   196     8     0     0   462
+  2008   174   197     8     0     0   463
+  2008   175   198     8     0     0   464
+  2008   174   199     8     0     0   465
+  2008   175   200     8     0     0   466
+  2016   187   192    16     0     0   467
+  2009   176   197     9     0     0   468
+  2009   177   198     9     0     0   469
+  2008   178   199     8     0     0   470
+  2008   179   200     8     0     0   471
+  2008   174   205     8     0     0   472
+  2008   175   206     8     0     0   473
+  2008   180   204     8     0     0   474
+  2008   181   207     8     0     0   475
+  2011   144   245    11     0     0   476
+  2011   145   246    11     0     0   477
+  2009   182   205     9     0     0   478
+  2009   183   206     9     0     0   479
+  2008   184   204     8     0     0   480
+  2008   184   205     8     0     0   481
+  2008   185   206     8     0     0   482
+  2008   185   207     8     0     0   483
+  2017   191   192    17     0     0   484
+  2008   180   212     8     0     0   485
+  2008   181   213     8     0     0   486
+  2008   184   212     8     0     0   487
+  2008   185   213     8     0     0   488
+  2009   163   239     9     0     0   489
+  2009   164   240     9     0     0   490
+  2011   144   252    11     0     0   491
+  2011   145   253    11     0     0   492
+  2008   184   215     8     0     0   493
+  2008   185   216     8     0     0   494
+  2008   193   194     8     0     0   495
+  2008   169   222     8     0     0   496
+  2008   169   224     8     0     0   497
+  2008   193   195     8     0     0   498
+  2008   194   196     8     0     0   499
+  2004   191   208     4     0     0   500
+  2008   174   226     8     0     0   501
+  2008   175   227     8     0     0   502
+  2009   189   215     9     0     0   503
+  2009   190   216     9     0     0   504
+  2008   195   199     8     0     0   505
+  2016   192   209    16     0     0   506
+  2008   196   200     8     0     0   507
+  2008   174   228     8     0     0   508
+  2008   175   229     8     0     0   509
+  2009   176   230     9     0     0   510
+  2009   177   230     9     0     0   511
+  2023   135   285    23     0     0   512
+  2008   199   204     8     0     0   513
+  2008   200   207     8     0     0   514
+  2009   176   231     9     0     0   515
+  2009   177   232     9     0     0   516
+  2023   201   210    23     0     0   517
+  2023   202   211    23     0     0   518
+  2009   182   231     9     0     0   519
+  2009   183   232     9     0     0   520
+  2022   203   210    22     0     0   521
+  2022   203   211    22     0     0   522
+  2008   184   233     8     0     0   523
+  2008   185   234     8     0     0   524
+  2017   208   209    17     0     0   525
+  2008   204   212     8     0     0   526
+  2008   207   213     8     0     0   527
+  2009   189   223     9     0     0   528
+  2009   190   225     9     0     0   529
+  2009   176   241     9     0     0   530
+  2009   177   242     9     0     0   531
+  2008   184   237     8     0     0   532
+  2008   185   238     8     0     0   533
+  2009   182   239     9     0     0   534
+  2009   183   240     9     0     0   535
+  2016   209   214    16     0     0   536
+  2005   203   217     5     0     0   537
+  2009   182   245     9     0     0   538
+  2009   183   246     9     0     0   539
+  2002   157   276     2     0     0   540
+  2002   157   277     2     0     0   541
+  2002   159   276     2     0     0   542
+  2002   158   277     2     0     0   543
+  2002   158   278     2     0     0   544
+  2002   159   278     2     0     0   545
+  2002   160   279     2     0     0   546
+  2002   160   280     2     0     0   547
+  2002   161   280     2     0     0   548
+  2002   161   281     2     0     0   549
+  2002   162   279     2     0     0   550
+  2002   162   281     2     0     0   551
+  2008   193   222     8     0     0   552
+  2008   194   224     8     0     0   553
+  2004   208   218     4     0     0   554
+  2009   189   239     9     0     0   555
+  2009   190   240     9     0     0   556
+  2008   197   222     8     0     0   557
+  2008   198   224     8     0     0   558
+  2008   195   226     8     0     0   559
+  2008   196   227     8     0     0   560
+  2008   197   226     8     0     0   561
+  2008   198   227     8     0     0   562
+  2021   214   217    21     0     0   563
+  2008   197   230     8     0     0   564
+  2008   198   230     8     0     0   565
+  2008   199   228     8     0     0   566
+  2008   200   229     8     0     0   567
+  2016   214   219    16     0     0   568
+  2008   197   231     8     0     0   569
+  2008   198   232     8     0     0   570
+  2008   205   228     8     0     0   571
+  2008   206   229     8     0     0   572
+  2009   176   262     9     0     0   573
+  2009   177   263     9     0     0   574
+  2008   205   231     8     0     0   575
+  2009   189   249     9     0     0   576
+  2008   206   232     8     0     0   577
+  2009   190   250     9     0     0   578
+  2008   204   233     8     0     0   579
+  2008   205   233     8     0     0   580
+  2008   206   234     8     0     0   581
+  2008   207   234     8     0     0   582
+  2018   188   251    18     0     0   583
+  2017   218   219    17     0     0   584
+  2009   189   252     9     0     0   585
+  2009   190   253     9     0     0   586
+  2008   205   239     8     0     0   587
+  2008   206   240     8     0     0   588
+  2011   201   241    11     0     0   589
+  2011   202   242    11     0     0   590
+  2009   182   268     9     0     0   591
+  2009   183   269     9     0     0   592
+  2008   212   237     8     0     0   593
+  2008   213   238     8     0     0   594
+  2011   220   223    11     0     0   595
+  2011   201   245    11     0     0   596
+  2011   202   246    11     0     0   597
+  2011   221   225    11     0     0   598
+  2008   215   237     8     0     0   599
+  2008   216   238     8     0     0   600
+  2008   212   243     8     0     0   601
+  2008   213   244     8     0     0   602
+  2008   215   239     8     0     0   603
+  2008   216   240     8     0     0   604
+  2008   222   224     8     0     0   605
+  2008   222   226     8     0     0   606
+  2008   224   227     8     0     0   607
+  2004   218   235     4     0     0   608
+  2008   215   243     8     0     0   609
+  2008   216   244     8     0     0   610
+  2008   197   254     8     0     0   611
+  2008   198   255     8     0     0   612
+  2016   219   236    16     0     0   613
+  2008   197   256     8     0     0   614
+  2008   198   257     8     0     0   615
+  2008   226   228     8     0     0   616
+  2008   227   229     8     0     0   617
+  2008   228   233     8     0     0   618
+  2008   229   234     8     0     0   619
+  2009   189   274     9     0     0   620
+  2008   215   249     8     0     0   621
+  2009   190   275     9     0     0   622
+  2008   216   250     8     0     0   623
+  2008   205   258     8     0     0   624
+  2008   206   259     8     0     0   625
+  2008   205   260     8     0     0   626
+  2008   206   261     8     0     0   627
+  2017   235   236    17     0     0   628
+  2008   233   237     8     0     0   629
+  2008   234   238     8     0     0   630
+  2011   220   252    11     0     0   631
+  2009   223   249     9     0     0   632
+  2011   221   253    11     0     0   633
+  2009   225   250     9     0     0   634
+  2008   237   243     8     0     0   635
+  2008   238   244     8     0     0   636
+  2008   215   266     8     0     0   637
+  2008   216   267     8     0     0   638
+  2010   201   285    10     0     0   639
+  2010   202   285    10     0     0   640
+  2009   241   242     9     0     0   641
+  2023   203   285    23     0     0   642
+  2008   222   254     8     0     0   643
+  2008   224   255     8     0     0   644
+  2004   235   247     4     0     0   645
+  2008   226   256     8     0     0   646
+  2008   227   257     8     0     0   647
+  2008   215   272     8     0     0   648
+  2008   216   273     8     0     0   649
+  2016   236   248    16     0     0   650
+  2023   210   285    23     0     0   651
+  2023   211   285    23     0     0   652
+  2008   230   254     8     0     0   653
+  2008   230   255     8     0     0   654
+  2009   241   245     9     0     0   655
+  2009   242   246     9     0     0   656
+  2008   228   258     8     0     0   657
+  2008   229   259     8     0     0   658
+  2008   231   256     8     0     0   659
+  2008   232   257     8     0     0   660
+  2011   220   270    11     0     0   661
+  2011   221   271    11     0     0   662
+  2010   201   292    10     0     0   663
+  2010   202   293    10     0     0   664
+  2022   203   291    22     0     0   665
+  2008   231   258     8     0     0   666
+  2008   232   259     8     0     0   667
+  2008   230   262     8     0     0   668
+  2008   230   263     8     0     0   669
+  2009   223   270     9     0     0   670
+  2009   225   271     9     0     0   671
+  2008   233   260     8     0     0   672
+  2022   210   291    22     0     0   673
+  2022   211   291    22     0     0   674
+  2008   234   261     8     0     0   675
+  2008   231   262     8     0     0   676
+  2023   210   292    23     0     0   677
+  2008   232   263     8     0     0   678
+  2023   211   293    23     0     0   679
+  2017   247   248    17     0     0   680
+  2022   210   298    22     0     0   681
+  2022   211   299    22     0     0   682
+  2008   231   268     8     0     0   683
+  2008   232   269     8     0     0   684
+  2009   245   252     9     0     0   685
+  2009   246   253     9     0     0   686
+  2008   239   260     8     0     0   687
+  2008   240   261     8     0     0   688
+  2009   223   274     9     0     0   689
+  2009   225   275     9     0     0   690
+  2008   237   266     8     0     0   691
+  2008   238   267     8     0     0   692
+  2009   241   262     9     0     0   693
+  2009   242   263     9     0     0   694
+  2005   217   291     5     0     0   695
+  2008   239   266     8     0     0   696
+  2008   240   267     8     0     0   697
+  2008   239   268     8     0     0   698
+  2008   240   269     8     0     0   699
+  2005   217   298     5     0     0   700
+  2005   217   299     5     0     0   701
+  2010   220   292    10     0     0   702
+  2010   221   293    10     0     0   703
+  2008   254   255     8     0     0   704
+  2004   247   264     4     0     0   705
+  2009   245   268     9     0     0   706
+  2009   246   269     9     0     0   707
+  2008   254   256     8     0     0   708
+  2008   255   257     8     0     0   709
+  2008   243   272     8     0     0   710
+  2008   244   273     8     0     0   711
+  2016   248   265    16     0     0   712
+  2008   239   274     8     0     0   713
+  2008   240   275     8     0     0   714
+  2009   223   294     9     0     0   715
+  2009   225   295     9     0     0   716
+  2011   201   319    11     0     0   717
+  2011   202   320    11     0     0   718
+  2008   256   258     8     0     0   719
+  2008   257   259     8     0     0   720
+  2008   230   287     8     0     0   721
+  2008   230   288     8     0     0   722
+  2008   231   289     8     0     0   723
+  2008   232   290     8     0     0   724
+  2008   243   282     8     0     0   725
+  2011   201   325    11     0     0   726
+  2011   202   326    11     0     0   727
+  2008   244   283     8     0     0   728
+  2008   258   260     8     0     0   729
+  2008   259   261     8     0     0   730
+  2008   249   272     8     0     0   731
+  2008   250   273     8     0     0   732
+  2010   220   309    10     0     0   733
+  2010   221   310    10     0     0   734
+  2008   231   296     8     0     0   735
+  2008   232   297     8     0     0   736
+  2009   252   270     9     0     0   737
+  2009   253   271     9     0     0   738
+  2008   249   274     8     0     0   739
+  2008   250   275     8     0     0   740
+  2008   249   282     8     0     0   741
+  2008   250   283     8     0     0   742
+  2017   264   265    17     0     0   743
+  2008   260   266     8     0     0   744
+  2008   261   267     8     0     0   745
+  2009   252   274     9     0     0   746
+  2009   253   275     9     0     0   747
+  2008   239   300     8     0     0   748
+  2008   240   301     8     0     0   749
+  2008   239   305     8     0     0   750
+  2008   240   306     8     0     0   751
+  2009   241   304     9     0     0   752
+  2009   242   304     9     0     0   753
+  2008   266   272     8     0     0   754
+  2008   267   273     8     0     0   755
+  2009   241   307     9     0     0   756
+  2009   242   308     9     0     0   757
+  2008   249   294     8     0     0   758
+  2021   217   335    21     0     0   759
+  2008   250   295     8     0     0   760
+  2009   223   321     9     0     0   761
+  2009   225   322     9     0     0   762
+  2004   264   284     4     0     0   763
+  2008   254   287     8     0     0   764
+  2008   255   288     8     0     0   765
+  2009   245   307     9     0     0   766
+  2009   246   308     9     0     0   767
+  2016   265   286    16     0     0   768
+  2008   256   289     8     0     0   769
+  2008   257   290     8     0     0   770
+  2011   220   340    11     0     0   771
+  2011   221   341    11     0     0   772
+  2008   258   296     8     0     0   773
+  2008   259   297     8     0     0   774
+  2008   262   287     8     0     0   775
+  2008   263   288     8     0     0   776
+  2009   245   313     9     0     0   777
+  2009   246   314     9     0     0   778
+  2008   272   282     8     0     0   779
+  2008   273   283     8     0     0   780
+  2008   262   289     8     0     0   781
+  2008   263   290     8     0     0   782
+  2008   249   311     8     0     0   783
+  2002   276   277     2     0     0   784
+  2002   276   278     2     0     0   785
+  2002   277   278     2     0     0   786
+  2008   250   312     8     0     0   787
+  2002   279   280     2     0     0   788
+  2002   279   281     2     0     0   789
+  2002   280   281     2     0     0   790
+  2009   241   319     9     0     0   791
+  2009   242   320     9     0     0   792
+  2008   260   300     8     0     0   793
+  2008   261   301     8     0     0   794
+  2008   268   296     8     0     0   795
+  2008   269   297     8     0     0   796
+  2009   270   294     9     0     0   797
+  2009   271   295     9     0     0   798
+  2017   284   286    17     0     0   799
+  2008   262   304     8     0     0   800
+  2008   263   304     8     0     0   801
+  2008   249   315     8     0     0   802
+  2009   252   313     9     0     0   803
+  2008   250   316     8     0     0   804
+  2009   253   314     9     0     0   805
+  2008   268   300     8     0     0   806
+  2008   269   301     8     0     0   807
+  2008   262   307     8     0     0   808
+  2008   263   308     8     0     0   809
+  2011   220   352    11     0     0   810
+  2011   221   355    11     0     0   811
+  2009   245   325     9     0     0   812
+  2009   246   326     9     0     0   813
+  2008   266   305     8     0     0   814
+  2008   267   306     8     0     0   815
+  2008   268   307     8     0     0   816
+  2008   269   308     8     0     0   817
+  2023   285   291    23     0     0   818
+  2009   252   321     9     0     0   819
+  2009   253   322     9     0     0   820
+  2009   241   345     9     0     0   821
+  2009   242   346     9     0     0   822
+  2008   268   313     8     0     0   823
+  2008   269   314     8     0     0   824
+  2023   210   379    23     0     0   825
+  2023   211   380    23     0     0   826
+  2004   284   302     4     0     0   827
+  2018   251   332    18     0     0   828
+  2008   274   305     8     0     0   829
+  2008   275   306     8     0     0   830
+  2008   287   288     8     0     0   831
+  2008   272   311     8     0     0   832
+  2008   287   289     8     0     0   833
+  2016   286   303    16     0     0   834
+  2008   288   290     8     0     0   835
+  2008   273   312     8     0     0   836
+  2008   289   296     8     0     0   837
+  2008   290   297     8     0     0   838
+  2008   274   311     8     0     0   839
+  2008   275   312     8     0     0   840
+  2022   291   298    22     0     0   841
+  2022   291   299    22     0     0   842
+  2008   274   313     8     0     0   843
+  2009   245   350     9     0     0   844
+  2008   275   314     8     0     0   845
+  2009   246   351     9     0     0   846
+  2008   262   327     8     0     0   847
+  2008   263   328     8     0     0   848
+  2009   252   340     9     0     0   849
+  2009   253   341     9     0     0   850
+  2008   262   330     8     0     0   851
+  2008   263   331     8     0     0   852
+  2008   296   300     8     0     0   853
+  2008   297   301     8     0     0   854
+  2009   270   321     9     0     0   855
+  2009   271   322     9     0     0   856
+  2008   282   315     8     0     0   857
+  2008   283   316     8     0     0   858
+  2008   268   333     8     0     0   859
+  2017   302   303    17     0     0   860
+  2008   269   334     8     0     0   861
+  2008   300   305     8     0     0   862
+  2008   301   306     8     0     0   863
+  2008   274   321     8     0     0   864
+  2008   275   322     8     0     0   865
+  2008   268   336     8     0     0   866
+  2008   269   337     8     0     0   867
+  2011   285   319    11     0     0   868
+  2011   285   320    11     0     0   869
+  2008   282   323     8     0     0   870
+  2008   283   324     8     0     0   871
+  2008   294   315     8     0     0   872
+  2009   252   358     9     0     0   873
+  2008   295   316     8     0     0   874
+  2009   253   359     9     0     0   875
+  2009   270   344     9     0     0   876
+  2009   271   347     9     0     0   877
+  2008   305   311     8     0     0   878
+  2008   306   312     8     0     0   879
+  2004   302   317     4     0     0   880
+  2008   294   321     8     0     0   881
+  2008   295   322     8     0     0   882
+  2008   274   342     8     0     0   883
+  2008   275   343     8     0     0   884
+  2016   303   318    16     0     0   885
+  2008   287   327     8     0     0   886
+  2008   288   328     8     0     0   887
+  2008   294   323     8     0     0   888
+  2008   295   324     8     0     0   889
+  2011   292   325    11     0     0   890
+  2011   293   326    11     0     0   891
+  2008   289   330     8     0     0   892
+  2008   290   331     8     0     0   893
+  2009   270   352     9     0     0   894
+  2009   271   355     9     0     0   895
+  2008   274   348     8     0     0   896
+  2008   275   349     8     0     0   897
+  2005   291   335     5     0     0   898
+  2008   311   315     8     0     0   899
+  2008   296   333     8     0     0   900
+  2008   297   334     8     0     0   901
+  2008   312   316     8     0     0   902
+  2008   304   327     8     0     0   903
+  2008   304   328     8     0     0   904
+  2011   292   340    11     0     0   905
+  2011   293   341    11     0     0   906
+  2008   307   330     8     0     0   907
+  2008   308   331     8     0     0   908
+  2008   300   336     8     0     0   909
+  2008   301   337     8     0     0   910
+  2008   307   333     8     0     0   911
+  2008   308   334     8     0     0   912
+  2008   294   344     8     0     0   913
+  2008   295   347     8     0     0   914
+  2017   317   318    17     0     0   915
+  2009   270   370     9     0     0   916
+  2009   271   372     9     0     0   917
+  2008   315   323     8     0     0   918
+  2008   316   324     8     0     0   919
+  2008   304   345     8     0     0   920
+  2008   304   346     8     0     0   921
+  2008   305   342     8     0     0   922
+  2008   306   343     8     0     0   923
+  2009   319   320     9     0     0   924
+  2011   309   340    11     0     0   925
+  2011   310   341    11     0     0   926
+  2008   307   345     8     0     0   927
+  2008   308   346     8     0     0   928
+  2008   313   336     8     0     0   929
+  2008   314   337     8     0     0   930
+  2016   318   329    16     0     0   931
+  2008   294   353     8     0     0   932
+  2008   295   354     8     0     0   933
+  2009   319   325     9     0     0   934
+  2009   320   326     9     0     0   935
+  2008   307   350     8     0     0   936
+  2008   308   351     8     0     0   937
+  2008   313   342     8     0     0   938
+  2008   314   343     8     0     0   939
+  2004   317   338     4     0     0   940
+  2009   270   382     9     0     0   941
+  2009   271   383     9     0     0   942
+  2008   311   348     8     0     0   943
+  2008   327   328     8     0     0   944
+  2008   312   349     8     0     0   945
+  2008   294   360     8     0     0   946
+  2008   295   361     8     0     0   947
+  2008   327   330     8     0     0   948
+  2008   328   331     8     0     0   949
+  2008   313   350     8     0     0   950
+  2008   314   351     8     0     0   951
+  2011   309   352    11     0     0   952
+  2008   330   333     8     0     0   953
+  2011   310   355    11     0     0   954
+  2008   331   334     8     0     0   955
+  2021   329   335    21     0     0   956
+  2010   285   379    10     0     0   957
+  2009   319   345     9     0     0   958
+  2009   320   346     9     0     0   959
+  2010   285   380    10     0     0   960
+  2016   329   339    16     0     0   961
+  2009   325   340     9     0     0   962
+  2009   326   341     9     0     0   963
+  2008   333   336     8     0     0   964
+  2008   334   337     8     0     0   965
+  2008   304   362     8     0     0   966
+  2008   304   363     8     0     0   967
+  2008   313   358     8     0     0   968
+  2008   314   359     8     0     0   969
+  2008   321   348     8     0     0   970
+  2008   315   353     8     0     0   971
+  2008   322   349     8     0     0   972
+  2008   316   354     8     0     0   973
+  2008   307   364     8     0     0   974
+  2008   308   365     8     0     0   975
+  2017   338   339    17     0     0   976
+  2008   307   366     8     0     0   977
+  2008   308   367     8     0     0   978
+  2009   325   350     9     0     0   979
+  2009   326   351     9     0     0   980
+  2023   291   379    23     0     0   981
+  2023   291   380    23     0     0   982
+  2010   292   379    10     0     0   983
+  2010   293   380    10     0     0   984
+  2008   336   342     8     0     0   985
+  2008   337   343     8     0     0   986
+  2008   321   353     8     0     0   987
+  2008   322   354     8     0     0   988
+  2023   298   379    23     0     0   989
+  2023   299   380    23     0     0   990
+  2008   321   358     8     0     0   991
+  2008   322   359     8     0     0   992
+  2008   313   375     8     0     0   993
+  2008   314   376     8     0     0   994
+  2008   342   348     8     0     0   995
+  2008   343   349     8     0     0   996
+  2008   323   360     8     0     0   997
+  2008   324   361     8     0     0   998
+  2008   313   377     8     0     0   999
+  2008   314   378     8     0     0  1000
+  2004   338   356     4     0     0  1001
+  2016   339   357    16     0     0  1002
+  2009   340   352     9     0     0  1003
+  2009   341   355     9     0     0  1004
+  2022   291   394    22     0     0  1005
+  2011   285   413    11     0     0  1006
+  2011   285   414    11     0     0  1007
+  2008   327   362     8     0     0  1008
+  2008   328   363     8     0     0  1009
+  2009   340   358     9     0     0  1010
+  2009   341   359     9     0     0  1011
+  2022   291   397    22     0     0  1012
+  2008   321   370     8     0     0  1013
+  2022   291   398    22     0     0  1014
+  2008   330   364     8     0     0  1015
+  2008   331   365     8     0     0  1016
+  2008   322   372     8     0     0  1017
+  2010   292   399    10     0     0  1018
+  2010   293   400    10     0     0  1019
+  2008   323   369     8     0     0  1020
+  2008   324   371     8     0     0  1021
+  2008   348   353     8     0     0  1022
+  2008   349   354     8     0     0  1023
+  2018   332   368    18     0     0  1024
+  2022   298   397    22     0     0  1025
+  2022   299   398    22     0     0  1026
+  2008   333   366     8     0     0  1027
+  2008   334   367     8     0     0  1028
+  2008   344   360     8     0     0  1029
+  2008   347   361     8     0     0  1030
+  2009   319   381     9     0     0  1031
+  2009   320   381     9     0     0  1032
+  2009   319   386     9     0     0  1033
+  2009   320   387     9     0     0  1034
+  2002   276   431     2     0     0  1035
+  2002   276   435     2     0     0  1036
+  2002   277   431     2     0     0  1037
+  2002   277   433     2     0     0  1038
+  2002   278   433     2     0     0  1039
+  2002   278   435     2     0     0  1040
+  2008   345   362     8     0     0  1041
+  2008   346   363     8     0     0  1042
+  2002   279   437     2     0     0  1043
+  2002   280   437     2     0     0  1044
+  2002   280   439     2     0     0  1045
+  2002   279   441     2     0     0  1046
+  2002   281   439     2     0     0  1047
+  2002   281   441     2     0     0  1048
+  2008   321   384     8     0     0  1049
+  2008   322   385     8     0     0  1050
+  2008   336   375     8     0     0  1051
+  2008   337   376     8     0     0  1052
+  2017   356   357    17     0     0  1053
+  2008   345   364     8     0     0  1054
+  2008   346   365     8     0     0  1055
+  2011   292   419    11     0     0  1056
+  2011   293   420    11     0     0  1057
+  2010   309   399    10     0     0  1058
+  2010   310   400    10     0     0  1059
+  2009   325   386     9     0     0  1060
+  2009   326   387     9     0     0  1061
+  2008   344   369     8     0     0  1062
+  2008   344   370     8     0     0  1063
+  2008   347   371     8     0     0  1064
+  2008   347   372     8     0     0  1065
+  2008   321   390     8     0     0  1066
+  2008   353   360     8     0     0  1067
+  2008   322   391     8     0     0  1068
+  2008   354   361     8     0     0  1069
+  2008   350   366     8     0     0  1070
+  2008   351   367     8     0     0  1071
+  2008   342   377     8     0     0  1072
+  2008   343   378     8     0     0  1073
+  2009   325   392     9     0     0  1074
+  2009   326   393     9     0     0  1075
+  2008   350   375     8     0     0  1076
+  2008   351   376     8     0     0  1077
+  2011   292   429    11     0     0  1078
+  2011   293   430    11     0     0  1079
+  2008   345   381     8     0     0  1080
+  2008   346   381     8     0     0  1081
+  2001   352   370     1     0     0  1082
+  2008   344   382     8     0     0  1083
+  2001   355   372     1     0     0  1084
+  2008   347   383     8     0     0  1085
+  2008   345   386     8     0     0  1086
+  2008   346   387     8     0     0  1087
+  2004   356   373     4     0     0  1088
+  2016   357   374    16     0     0  1089
+  2009   340   392     9     0     0  1090
+  2009   341   393     9     0     0  1091
+  2008   348   384     8     0     0  1092
+  2008   349   385     8     0     0  1093
+  2008   350   386     8     0     0  1094
+  2008   351   387     8     0     0  1095
+  2005   335   394     5     0     0  1096
+  2008   362   363     8     0     0  1097
+  2008   362   364     8     0     0  1098
+  2008   363   365     8     0     0  1099
+  2009   319   413     9     0     0  1100
+  2009   320   414     9     0     0  1101
+  2011   309   429    11     0     0  1102
+  2008   360   369     8     0     0  1103
+  2011   310   430    11     0     0  1104
+  2008   361   371     8     0     0  1105
+  2008   358   377     8     0     0  1106
+  2008   359   378     8     0     0  1107
+  2005   335   397     5     0     0  1108
+  2005   335   398     5     0     0  1109
+  2008   364   366     8     0     0  1110
+  2008   365   367     8     0     0  1111
+  2001   352   382     1     0     0  1112
+  2001   355   383     1     0     0  1113
+  2008   350   392     8     0     0  1114
+  2008   351   393     8     0     0  1115
+  2008   358   384     8     0     0  1116
+  2008   359   385     8     0     0  1117
+  2008   344   395     8     0     0  1118
+  2008   347   396     8     0     0  1119
+  2009   340   401     9     0     0  1120
+  2008   366   375     8     0     0  1121
+  2009   341   402     9     0     0  1122
+  2008   367   376     8     0     0  1123
+  2009   325   419     9     0     0  1124
+  2009   326   420     9     0     0  1125
+  2008   353   390     8     0     0  1126
+  2008   354   391     8     0     0  1127
+  2017   373   374    17     0     0  1128
+  2008   345   403     8     0     0  1129
+  2008   346   404     8     0     0  1130
+  2009   319   427     9     0     0  1131
+  2009   320   428     9     0     0  1132
+  2008   345   405     8     0     0  1133
+  2008   346   406     8     0     0  1134
+  2008   358   392     8     0     0  1135
+  2008   359   393     8     0     0  1136
+  2011   309   451    11     0     0  1137
+  2011   310   452    11     0     0  1138
+  2008   375   377     8     0     0  1139
+  2008   376   378     8     0     0  1140
+  2008   344   410     8     0     0  1141
+  2008   347   411     8     0     0  1142
+  2008   350   407     8     0     0  1143
+  2008   351   408     8     0     0  1144
+  2001   370   382     1     0     0  1145
+  2001   372   383     1     0     0  1146
+  2009   325   443     9     0     0  1147
+  2009   326   444     9     0     0  1148
+  2009   352   401     9     0     0  1149
+  2009   355   402     9     0     0  1150
+  2008   350   415     8     0     0  1151
+  2008   351   416     8     0     0  1152
+  2008   358   401     8     0     0  1153
+  2008   359   402     8     0     0  1154
+  2008   377   384     8     0     0  1155
+  2008   360   395     8     0     0  1156
+  2008   378   385     8     0     0  1157
+  2008   361   396     8     0     0  1158
+  2008   370   390     8     0     0  1159
+  2004   373   388     4     0     0  1160
+  2008   372   391     8     0     0  1161
+  2016   374   389    16     0     0  1162
+  2009   340   429     9     0     0  1163
+  2009   341   430     9     0     0  1164
+  2001   352   417     1     0     0  1165
+  2001   355   418     1     0     0  1166
+  2008   362   403     8     0     0  1167
+  2008   363   404     8     0     0  1168
+  2008   370   395     8     0     0  1169
+  2008   372   396     8     0     0  1170
+  2008   364   405     8     0     0  1171
+  2008   365   406     8     0     0  1172
+  2008   358   421     8     0     0  1173
+  2023   291   489    23     0     0  1174
+  2008   359   422     8     0     0  1175
+  2008   384   390     8     0     0  1176
+  2008   385   391     8     0     0  1177
+  2008   370   401     8     0     0  1178
+  2008   372   402     8     0     0  1179
+  2009   340   449     9     0     0  1180
+  2009   341   450     9     0     0  1181
+  2008   366   407     8     0     0  1182
+  2001   352   425     1     0     0  1183
+  2008   367   408     8     0     0  1184
+  2001   355   426     1     0     0  1185
+  2008   358   423     8     0     0  1186
+  2008   359   424     8     0     0  1187
+  2008   369   410     8     0     0  1188
+  2008   371   411     8     0     0  1189
+  2017   388   389    17     0     0  1190
+  2008   382   395     8     0     0  1191
+  2008   383   396     8     0     0  1192
+  2023   379   397    23     0     0  1193
+  2023   380   398    23     0     0  1194
+  2001   370   417     1     0     0  1195
+  2008   375   415     8     0     0  1196
+  2008   376   416     8     0     0  1197
+  2001   372   418     1     0     0  1198
+  2008   381   403     8     0     0  1199
+  2008   381   404     8     0     0  1200
+  2008   386   405     8     0     0  1201
+  2008   387   406     8     0     0  1202
+  2008   390   395     8     0     0  1203
+  2008   391   396     8     0     0  1204
+  2011   379   413    11     0     0  1205
+  2011   380   414    11     0     0  1206
+  2008   386   407     8     0     0  1207
+  2008   387   408     8     0     0  1208
+  2008   382   410     8     0     0  1209
+  2008   383   411     8     0     0  1210
+  2008   377   421     8     0     0  1211
+  2008   378   422     8     0     0  1212
+  2001   352   451     1     0     0  1213
+  2001   355   452     1     0     0  1214
+  2001   370   425     1     0     0  1215
+  2001   372   426     1     0     0  1216
+  2011   379   419    11     0     0  1217
+  2011   380   420    11     0     0  1218
+  2004   388   409     4     0     0  1219
+  2016   389   412    16     0     0  1220
+  2022   394   397    22     0     0  1221
+  2022   394   398    22     0     0  1222
+  2008   370   445     8     0     0  1223
+  2008   372   446     8     0     0  1224
+  2008   392   415     8     0     0  1225
+  2008   393   416     8     0     0  1226
+  2008   381   427     8     0     0  1227
+  2008   381   428     8     0     0  1228
+  2008   384   423     8     0     0  1229
+  2008   385   424     8     0     0  1230
+  2001   352   468     1     0     0  1231
+  2001   382   425     1     0     0  1232
+  2001   352   472     1     0     0  1233
+  2001   355   469     1     0     0  1234
+  2001   383   426     1     0     0  1235
+  2001   355   473     1     0     0  1236
+  2008   392   421     8     0     0  1237
+  2008   393   422     8     0     0  1238
+  2008   386   427     8     0     0  1239
+  2008   387   428     8     0     0  1240
+  2008   395   410     8     0     0  1241
+  2008   403   404     8     0     0  1242
+  2008   396   411     8     0     0  1243
+  2001   370   447     1     0     0  1244
+  2008   403   405     8     0     0  1245
+  2008   404   406     8     0     0  1246
+  2001   372   448     1     0     0  1247
+  2008   386   443     8     0     0  1248
+  2008   387   444     8     0     0  1249
+  2008   405   407     8     0     0  1250
+  2008   406   408     8     0     0  1251
+  2006   332   496     6     0     0  1252
+  2006   332   497     6     0     0  1253
+  2017   409   412    17     0     0  1254
+  2018   368   463    18     0     0  1255
+  2008   407   415     8     0     0  1256
+  2008   408   416     8     0     0  1257
+  2008   392   443     8     0     0  1258
+  2008   390   445     8     0     0  1259
+  2008   393   444     8     0     0  1260
+  2008   391   446     8     0     0  1261
+  2009   413   414     9     0     0  1262
+  2001   382   447     1     0     0  1263
+  2001   383   448     1     0     0  1264
+  2008   381   453     8     0     0  1265
+  2008   381   454     8     0     0  1266
+  2009   413   419     9     0     0  1267
+  2009   414   420     9     0     0  1268
+  2008   401   423     8     0     0  1269
+  2008   402   424     8     0     0  1270
+  2008   415   421     8     0     0  1271
+  2008   416   422     8     0     0  1272
+  2011   399   429    11     0     0  1273
+  2011   400   430    11     0     0  1274
+  2008   386   455     8     0     0  1275
+  2008   387   456     8     0     0  1276
+  2008   392   449     8     0     0  1277
+  2008   393   450     8     0     0  1278
+  2001   382   459     1     0     0  1279
+  2001   383   462     1     0     0  1280
+  2008   386   460     8     0     0  1281
+  2008   387   461     8     0     0  1282
+  2008   401   445     8     0     0  1283
+  2008   402   446     8     0     0  1284
+  2009   413   427     9     0     0  1285
+  2009   414   428     9     0     0  1286
+  2001   417   425     1     0     0  1287
+  2004   409   436     4     0     0  1288
+  2001   418   426     1     0     0  1289
+  2016   412   442    16     0     0  1290
+  2008   395   447     8     0     0  1291
+  2008   396   448     8     0     0  1292
+  2008   421   423     8     0     0  1293
+  2008   422   424     8     0     0  1294
+  2021   335   516    21     0     0  1295
+  2009   419   429     9     0     0  1296
+  2009   420   430     9     0     0  1297
+  2008   401   449     8     0     0  1298
+  2008   402   450     8     0     0  1299
+  2008   392   464     8     0     0  1300
+  2008   393   465     8     0     0  1301
+  2011   399   451    11     0     0  1302
+  2011   400   452    11     0     0  1303
+  2009   419   443     9     0     0  1304
+  2009   420   444     9     0     0  1305
+  2008   392   474     8     0     0  1306
+  2008   393   475     8     0     0  1307
+  2008   403   453     8     0     0  1308
+  2008   404   454     8     0     0  1309
+  2001   417   447     1     0     0  1310
+  2008   405   455     8     0     0  1311
+  2008   406   456     8     0     0  1312
+  2001   418   448     1     0     0  1313
+  2008   423   445     8     0     0  1314
+  2008   424   446     8     0     0  1315
+  2014   431   432    14     0     0  1316
+  2002   431   433     2     0     0  1317
+  2002   431   435     2     0     0  1318
+  2014   432   434    14     0     0  1319
+  2014   433   434    14     0     0  1320
+  2014   434   435    14     0     0  1321
+  2014   437   438    14     0     0  1322
+  2014   438   439    14     0     0  1323
+  2014   438   440    14     0     0  1324
+  2002   437   441     2     0     0  1325
+  2002   439   441     2     0     0  1326
+  2014   440   441    14     0     0  1327
+  2017   436   442    17     0     0  1328
+  2008   407   460     8     0     0  1329
+  2008   408   461     8     0     0  1330
+  2008   410   459     8     0     0  1331
+  2008   411   462     8     0     0  1332
+  2008   401   472     8     0     0  1333
+  2008   402   473     8     0     0  1334
+  2010   379   489    10     0     0  1335
+  2010   380   489    10     0     0  1336
+  2001   425   447     1     0     0  1337
+  2001   426   448     1     0     0  1338
+  2008   415   464     8     0     0  1339
+  2008   416   465     8     0     0  1340
+  2009   429   449     9     0     0  1341
+  2009   430   450     9     0     0  1342
+  2008   401   476     8     0     0  1343
+  2008   402   477     8     0     0  1344
+  2001   417   472     1     0     0  1345
+  2001   418   473     1     0     0  1346
+  2009   429   451     9     0     0  1347
+  2009   430   452     9     0     0  1348
+  2008   445   447     8     0     0  1349
+  2008   446   448     8     0     0  1350
+  2008   427   453     8     0     0  1351
+  2008   428   454     8     0     0  1352
+  2008   427   455     8     0     0  1353
+  2008   428   456     8     0     0  1354
+  2001   425   459     1     0     0  1355
+  2010   379   502    10     0     0  1356
+  2010   380   503    10     0     0  1357
+  2001   426   462     1     0     0  1358
+  2008   421   474     8     0     0  1359
+  2008   422   475     8     0     0  1360
+  2008   401   483     8     0     0  1361
+  2004   436   457     4     0     0  1362
+  2008   402   484     8     0     0  1363
+  2016   442   458    16     0     0  1364
+  2008   443   460     8     0     0  1365
+  2009   413   480     9     0     0  1366
+  2008   444   461     8     0     0  1367
+  2009   414   480     9     0     0  1368
+  2001   425   468     1     0     0  1369
+  2001   425   472     1     0     0  1370
+  2001   426   469     1     0     0  1371
+  2001   426   473     1     0     0  1372
+  2023   394   489    23     0     0  1373
+  2009   413   481     9     0     0  1374
+  2009   414   482     9     0     0  1375
+  2008   443   464     8     0     0  1376
+  2008   444   465     8     0     0  1377
+  2013   432   466    13     0     0  1378
+  2013   432   467    13     0     0  1379
+  2013   434   467    13     0     0  1380
+  2013   438   470    13     0     0  1381
+  2013   440   470    13     0     0  1382
+  2013   440   471    13     0     0  1383
+  2023   397   489    23     0     0  1384
+  2023   398   489    23     0     0  1385
+  2009   419   481     9     0     0  1386
+  2009   420   482     9     0     0  1387
+  2008   423   476     8     0     0  1388
+  2008   424   477     8     0     0  1389
+  2011   379   514    11     0     0  1390
+  2011   380   515    11     0     0  1391
+  2001   447   459     1     0     0  1392
+  2001   448   462     1     0     0  1393
+  2008   453   454     8     0     0  1394
+  2008   453   455     8     0     0  1395
+  2008   454   456     8     0     0  1396
+  2011   379   520    11     0     0  1397
+  2011   380   521    11     0     0  1398
+  2008   427   480     8     0     0  1399
+  2008   428   480     8     0     0  1400
+  2001   417   487     1     0     0  1401
+  2001   418   488     1     0     0  1402
+  2009   419   485     9     0     0  1403
+  2009   420   486     9     0     0  1404
+  2017   457   458    17     0     0  1405
+  2008   427   481     8     0     0  1406
+  2023   397   502    23     0     0  1407
+  2008   428   482     8     0     0  1408
+  2023   398   503    23     0     0  1409
+  2010   399   502    10     0     0  1410
+  2008   455   460     8     0     0  1411
+  2008   456   461     8     0     0  1412
+  2010   400   503    10     0     0  1413
+  2001   451   468     1     0     0  1414
+  2008   449   474     8     0     0  1415
+  2001   451   472     1     0     0  1416
+  2001   452   469     1     0     0  1417
+  2008   450   475     8     0     0  1418
+  2001   452   473     1     0     0  1419
+  2008   443   481     8     0     0  1420
+  2008   444   482     8     0     0  1421
+  2008   445   483     8     0     0  1422
+  2008   460   464     8     0     0  1423
+  2008   461   465     8     0     0  1424
+  2008   446   484     8     0     0  1425
+  2008   449   476     8     0     0  1426
+  2008   450   477     8     0     0  1427
+  2001   425   487     1     0     0  1428
+  2001   426   488     1     0     0  1429
+  2009   429   485     9     0     0  1430
+  2009   430   486     9     0     0  1431
+  2008   443   485     8     0     0  1432
+  2008   444   486     8     0     0  1433
+  2022   394   516    22     0     0  1434
+  2013   466   467    13     0     0  1435
+  2013   467   468    13     0     0  1436
+  2001   468   472     1     0     0  1437
+  2013   469   470    13     0     0  1438
+  2013   470   471    13     0     0  1439
+  2001   469   473     1     0     0  1440
+  2008   464   474     8     0     0  1441
+  2008   465   475     8     0     0  1442
+  2008   427   492     8     0     0  1443
+  2008   428   493     8     0     0  1444
+  2022   397   516    22     0     0  1445
+  2022   398   516    22     0     0  1446
+  2008   427   494     8     0     0  1447
+  2008   428   495     8     0     0  1448
+  2004   457   478     4     0     0  1449
+  2016   458   479    16     0     0  1450
+  2001   425   496     1     0     0  1451
+  2001   426   497     1     0     0  1452
+  2009   413   514     9     0     0  1453
+  2009   414   515     9     0     0  1454
+  2009   429   498     9     0     0  1455
+  2009   430   499     9     0     0  1456
+  2008   449   485     8     0     0  1457
+  2008   450   486     8     0     0  1458
+  2001   447   487     1     0     0  1459
+  2001   448   488     1     0     0  1460
+  2008   443   500     8     0     0  1461
+  2008   444   501     8     0     0  1462
+  2008   474   476     8     0     0  1463
+  2008   475   477     8     0     0  1464
+  2008   443   504     8     0     0  1465
+  2008   444   505     8     0     0  1466
+  2009   413   524     9     0     0  1467
+  2009   414   525     9     0     0  1468
+  2011   399   529    11     0     0  1469
+  2011   400   530    11     0     0  1470
+  2008   472   483     8     0     0  1471
+  2008   473   484     8     0     0  1472
+  2009   419   520     9     0     0  1473
+  2009   420   521     9     0     0  1474
+  2008   449   498     8     0     0  1475
+  2008   450   499     8     0     0  1476
+  2017   478   479    17     0     0  1477
+  2008   453   492     8     0     0  1478
+  2008   454   493     8     0     0  1479
+  2009   451   498     9     0     0  1480
+  2009   452   499     9     0     0  1481
+  2001   468   487     1     0     0  1482
+  2009   419   526     9     0     0  1483
+  2001   472   487     1     0     0  1484
+  2009   420   527     9     0     0  1485
+  2001   469   488     1     0     0  1486
+  2008   476   483     8     0     0  1487
+  2008   455   494     8     0     0  1488
+  2008   456   495     8     0     0  1489
+  2001   473   488     1     0     0  1490
+  2008   477   484     8     0     0  1491
+  2001   459   496     1     0     0  1492
+  2001   462   497     1     0     0  1493
+  2008   449   507     8     0     0  1494
+  2008   450   509     8     0     0  1495
+  2008   460   500     8     0     0  1496
+  2008   461   501     8     0     0  1497
+  2011   399   545    11     0     0  1498
+  2011   400   546    11     0     0  1499
+  2001   451   506     1     0     0  1500
+  2001   452   508     1     0     0  1501
+  2001   468   496     1     0     0  1502
+  2001   469   497     1     0     0  1503
+  2008   449   512     8     0     0  1504
+  2008   472   498     8     0     0  1505
+  2008   450   513     8     0     0  1506
+  2008   473   499     8     0     0  1507
+  2008   464   504     8     0     0  1508
+  2008   465   505     8     0     0  1509
+  2009   429   529     9     0     0  1510
+  2009   430   530     9     0     0  1511
+  2008   483   487     8     0     0  1512
+  2008   484   488     8     0     0  1513
+  2016   479   490    16     0     0  1514
+  2004   478   491     4     0     0  1515
+  2001   451   518     1     0     0  1516
+  2001   452   519     1     0     0  1517
+  2001   472   506     1     0     0  1518
+  2001   473   508     1     0     0  1519
+  2008   480   492     8     0     0  1520
+  2008   480   493     8     0     0  1521
+  2009   429   534     9     0     0  1522
+  2009   430   535     9     0     0  1523
+  2008   474   507     8     0     0  1524
+  2008   475   509     8     0     0  1525
+  2008   481   494     8     0     0  1526
+  2008   482   495     8     0     0  1527
+  2008   481   500     8     0     0  1528
+  2008   482   501     8     0     0  1529
+  2001   468   518     1     0     0  1530
+  2001   472   518     1     0     0  1531
+  2001   469   519     1     0     0  1532
+  2001   473   519     1     0     0  1533
+  2008   472   522     8     0     0  1534
+  2008   473   523     8     0     0  1535
+  2001   487   496     1     0     0  1536
+  2008   476   512     8     0     0  1537
+  2008   477   513     8     0     0  1538
+  2001   488   497     1     0     0  1539
+  2017   490   491    17     0     0  1540
+  2008   485   504     8     0     0  1541
+  2008   486   505     8     0     0  1542
+  2008   492   493     8     0     0  1543
+  2008   492   494     8     0     0  1544
+  2008   493   495     8     0     0  1545
+  2001   468   528     1     0     0  1546
+  2001   472   528     1     0     0  1547
+  2001   469   531     1     0     0  1548
+  2001   473   531     1     0     0  1549
+  2008   485   507     8     0     0  1550
+  2008   486   509     8     0     0  1551
+  2008   494   500     8     0     0  1552
+  2008   495   501     8     0     0  1553
+  2009   451   545     9     0     0  1554
+  2009   452   546     9     0     0  1555
+  2008   480   524     8     0     0  1556
+  2008   480   525     8     0     0  1557
+  2011   399   576    11     0     0  1558
+  2011   400   577    11     0     0  1559
+  2008   481   524     8     0     0  1560
+  2008   482   525     8     0     0  1561
+  2008   483   522     8     0     0  1562
+  2008   484   523     8     0     0  1563
+  2018   463   542    18     0     0  1564
+  2008   500   504     8     0     0  1565
+  2008   501   505     8     0     0  1566
+  2001   451   553     1     0     0  1567
+  2001   468   538     1     0     0  1568
+  2001   452   554     1     0     0  1569
+  2001   469   541     1     0     0  1570
+  2011   489   514    11     0     0  1571
+  2011   489   515    11     0     0  1572
+  2008   481   526     8     0     0  1573
+  2008   482   527     8     0     0  1574
+  2016   490   510    16     0     0  1575
+  2004   491   511     4     0     0  1576
+  2007   489   516     7     0     0  1577
+  2023   489   516    23     0     0  1578
+  2008   504   507     8     0     0  1579
+  2008   505   509     8     0     0  1580
+  2023   397   589    23     0     0  1581
+  2023   398   590    23     0     0  1582
+  2008   498   512     8     0     0  1583
+  2008   499   513     8     0     0  1584
+  2008   485   526     8     0     0  1585
+  2008   486   527     8     0     0  1586
+  2008   480   536     8     0     0  1587
+  2008   480   537     8     0     0  1588
+  2001   451   557     1     0     0  1589
+  2001   452   558     1     0     0  1590
+  2001   487   528     1     0     0  1591
+  2001   488   531     1     0     0  1592
+  2008   481   539     8     0     0  1593
+  2008   482   540     8     0     0  1594
+  2011   502   520    11     0     0  1595
+  2011   503   521    11     0     0  1596
+  2008   498   522     8     0     0  1597
+  2008   499   523     8     0     0  1598
+  2008   481   543     8     0     0  1599
+  2008   482   544     8     0     0  1600
+  2008   507   512     8     0     0  1601
+  2008   509   513     8     0     0  1602
+  2008   485   534     8     0     0  1603
+  2008   486   535     8     0     0  1604
+  2017   510   511    17     0     0  1605
+  2001   506   518     1     0     0  1606
+  2001   508   519     1     0     0  1607
+  2009   514   515     9     0     0  1608
+  2011   502   529    11     0     0  1609
+  2011   503   530    11     0     0  1610
+  2016   510   517    16     0     0  1611
+  2008   485   547     8     0     0  1612
+  2008   486   548     8     0     0  1613
+  2009   514   520     9     0     0  1614
+  2009   515   521     9     0     0  1615
+  2008   492   536     8     0     0  1616
+  2008   493   537     8     0     0  1617
+  2008   512   522     8     0     0  1618
+  2008   513   523     8     0     0  1619
+  2008   498   534     8     0     0  1620
+  2008   499   535     8     0     0  1621
+  2009   514   524     9     0     0  1622
+  2009   515   525     9     0     0  1623
+  2008   494   539     8     0     0  1624
+  2008   495   540     8     0     0  1625
+  2021   516   517    21     0     0  1626
+  2008   485   551     8     0     0  1627
+  2008   486   552     8     0     0  1628
+  2001   506   528     1     0     0  1629
+  2001   496   538     1     0     0  1630
+  2001   508   531     1     0     0  1631
+  2001   497   541     1     0     0  1632
+  2006   496   542     6     0     0  1633
+  2006   497   542     6     0     0  1634
+  2008   500   543     8     0     0  1635
+  2008   501   544     8     0     0  1636
+  2004   511   533     4     0     0  1637
+  2009   520   526     9     0     0  1638
+  2009   521   527     9     0     0  1639
+  2001   518   528     1     0     0  1640
+  2008   504   547     8     0     0  1641
+  2008   505   548     8     0     0  1642
+  2001   519   531     1     0     0  1643
+  2009   520   529     9     0     0  1644
+  2009   521   530     9     0     0  1645
+  2016   517   532    16     0     0  1646
+  2008   498   553     8     0     0  1647
+  2008   499   554     8     0     0  1648
+  2008   522   528     8     0     0  1649
+  2008   523   531     8     0     0  1650
+  2008   498   555     8     0     0  1651
+  2008   499   556     8     0     0  1652
+  2008   507   551     8     0     0  1653
+  2001   518   538     1     0     0  1654
+  2008   509   552     8     0     0  1655
+  2001   519   541     1     0     0  1656
+  2001   506   553     1     0     0  1657
+  2001   508   554     1     0     0  1658
+  2008   524   536     8     0     0  1659
+  2008   525   537     8     0     0  1660
+  2008   524   539     8     0     0  1661
+  2008   525   540     8     0     0  1662
+  2017   532   533    17     0     0  1663
+  2008   498   559     8     0     0  1664
+  2008   499   560     8     0     0  1665
+  2009   529   534     9     0     0  1666
+  2009   530   535     9     0     0  1667
+  2008   526   543     8     0     0  1668
+  2008   527   544     8     0     0  1669
+  2001   528   538     1     0     0  1670
+  2001   531   541     1     0     0  1671
+  2008   512   555     8     0     0  1672
+  2001   518   553     1     0     0  1673
+  2008   513   556     8     0     0  1674
+  2001   519   554     1     0     0  1675
+  2008   526   547     8     0     0  1676
+  2008   527   548     8     0     0  1677
+  2009   529   545     9     0     0  1678
+  2009   530   546     9     0     0  1679
+  2008   536   537     8     0     0  1680
+  2008   536   539     8     0     0  1681
+  2008   537   540     8     0     0  1682
+  2001   506   566     1     0     0  1683
+  2016   532   549    16     0     0  1684
+  2001   508   567     1     0     0  1685
+  2004   533   550     4     0     0  1686
+  2009   514   561     9     0     0  1687
+  2009   515   561     9     0     0  1688
+  2008   539   543     8     0     0  1689
+  2008   540   544     8     0     0  1690
+  2001   518   557     1     0     0  1691
+  2001   519   558     1     0     0  1692
+  2009   514   564     9     0     0  1693
+  2009   515   565     9     0     0  1694
+  2008   522   559     8     0     0  1695
+  2008   523   560     8     0     0  1696
+  2011   502   576    11     0     0  1697
+  2011   503   577    11     0     0  1698
+  2008   534   551     8     0     0  1699
+  2008   535   552     8     0     0  1700
+  2008   543   547     8     0     0  1701
+  2008   544   548     8     0     0  1702
+  2008   524   561     8     0     0  1703
+  2008   525   561     8     0     0  1704
+  2009   520   564     9     0     0  1705
+  2009   521   565     9     0     0  1706
+  2010   489   589    10     0     0  1707
+  2010   489   590    10     0     0  1708
+  2008   524   564     8     0     0  1709
+  2008   525   565     8     0     0  1710
+  2001   518   566     1     0     0  1711
+  2001   519   567     1     0     0  1712
+  2008   534   555     8     0     0  1713
+  2008   535   556     8     0     0  1714
+  2008   526   564     8     0     0  1715
+  2008   527   565     8     0     0  1716
+  2008   547   551     8     0     0  1717
+  2009   520   568     9     0     0  1718
+  2008   548   552     8     0     0  1719
+  2009   521   569     9     0     0  1720
+  2009   545   553     9     0     0  1721
+  2009   546   554     9     0     0  1722
+  2017   549   550    17     0     0  1723
+  2010   502   589    10     0     0  1724
+  2010   503   590    10     0     0  1725
+  2001   518   570     1     0     0  1726
+  2001   519   573     1     0     0  1727
+  2001   528   566     1     0     0  1728
+  2001   531   567     1     0     0  1729
+  2011   489   601    11     0     0  1730
+  2011   489   602    11     0     0  1731
+  2008   526   568     8     0     0  1732
+  2008   527   569     8     0     0  1733
+  2008   524   571     8     0     0  1734
+  2008   525   572     8     0     0  1735
+  2008   524   574     8     0     0  1736
+  2008   525   575     8     0     0  1737
+  2009   529   568     9     0     0  1738
+  2009   530   569     9     0     0  1739
+  2008   551   555     8     0     0  1740
+  2008   552   556     8     0     0  1741
+  2009   545   557     9     0     0  1742
+  2009   546   558     9     0     0  1743
+  2008   526   578     8     0     0  1744
+  2008   527   579     8     0     0  1745
+  2008   534   568     8     0     0  1746
+  2008   535   569     8     0     0  1747
+  2007   516   588     7     0     0  1748
+  2001   553   557     1     0     0  1749
+  2001   554   558     1     0     0  1750
+  2008   553   559     8     0     0  1751
+  2008   554   560     8     0     0  1752
+  2008   526   584     8     0     0  1753
+  2008   527   585     8     0     0  1754
+  2016   549   562    16     0     0  1755
+  2023   516   589    23     0     0  1756
+  2023   516   590    23     0     0  1757
+  2004   550   563     4     0     0  1758
+  2009   529   582     9     0     0  1759
+  2011   502   607    11     0     0  1760
+  2009   530   583     9     0     0  1761
+  2011   503   608    11     0     0  1762
+  2008   555   559     8     0     0  1763
+  2008   536   571     8     0     0  1764
+  2008   537   572     8     0     0  1765
+  2008   556   560     8     0     0  1766
+  2001   538   570     1     0     0  1767
+  2001   541   573     1     0     0  1768
+  2008   539   574     8     0     0  1769
+  2008   540   575     8     0     0  1770
+  2001   553   566     1     0     0  1771
+  2021   516   595    21     0     0  1772
+  2001   554   567     1     0     0  1773
+  2008   534   582     8     0     0  1774
+  2008   535   583     8     0     0  1775
+  2009   514   601     9     0     0  1776
+  2009   515   602     9     0     0  1777
+  2008   543   578     8     0     0  1778
+  2008   544   579     8     0     0  1779
+  2009   514   603     9     0     0  1780
+  2009   515   604     9     0     0  1781
+  2011   502   620    11     0     0  1782
+  2011   503   621    11     0     0  1783
+  2008   534   586     8     0     0  1784
+  2009   545   576     9     0     0  1785
+  2008   535   587     8     0     0  1786
+  2009   546   577     9     0     0  1787
+  2009   545   582     9     0     0  1788
+  2009   546   583     9     0     0  1789
+  2008   547   584     8     0     0  1790
+  2008   548   585     8     0     0  1791
+  2001   557   566     1     0     0  1792
+  2001   558   567     1     0     0  1793
+  2008   559   566     8     0     0  1794
+  2017   562   563    17     0     0  1795
+  2008   560   567     8     0     0  1796
+  2008   534   591     8     0     0  1797
+  2008   535   592     8     0     0  1798
+  2009   520   607     9     0     0  1799
+  2009   521   608     9     0     0  1800
+  2009   520   609     9     0     0  1801
+  2009   521   610     9     0     0  1802
+  2008   553   582     8     0     0  1803
+  2008   554   583     8     0     0  1804
+  2008   551   586     8     0     0  1805
+  2008   552   587     8     0     0  1806
+  2001   557   570     1     0     0  1807
+  2001   558   573     1     0     0  1808
+  2008   561   571     8     0     0  1809
+  2008   561   572     8     0     0  1810
+  2009   545   596     9     0     0  1811
+  2009   546   597     9     0     0  1812
+  2008   564   574     8     0     0  1813
+  2008   565   575     8     0     0  1814
+  2016   562   580    16     0     0  1815
+  2001   566   570     1     0     0  1816
+  2001   567   573     1     0     0  1817
+  2008   564   578     8     0     0  1818
+  2008   565   579     8     0     0  1819
+  2004   563   581     4     0     0  1820
+  2008   555   591     8     0     0  1821
+  2008   556   592     8     0     0  1822
+  2008   553   596     8     0     0  1823
+  2009   529   620     9     0     0  1824
+  2008   554   597     8     0     0  1825
+  2009   530   621     9     0     0  1826
+  2009   529   622     9     0     0  1827
+  2009   530   623     9     0     0  1828
+  2008   553   598     8     0     0  1829
+  2008   554   599     8     0     0  1830
+  2008   571   572     8     0     0  1831
+  2008   571   574     8     0     0  1832
+  2008   572   575     8     0     0  1833
+  2008   568   584     8     0     0  1834
+  2008   569   585     8     0     0  1835
+  2018   542   613    18     0     0  1836
+  2008   553   605     8     0     0  1837
+  2008   554   606     8     0     0  1838
+  2008   574   578     8     0     0  1839
+  2008   575   579     8     0     0  1840
+  2008   557   596     8     0     0  1841
+  2008   558   597     8     0     0  1842
+  2008   568   586     8     0     0  1843
+  2008   569   587     8     0     0  1844
+  2008   559   598     8     0     0  1845
+  2008   560   599     8     0     0  1846
+  2017   580   581    17     0     0  1847
+  2009   576   582     9     0     0  1848
+  2011   502   651    11     0     0  1849
+  2011   503   652    11     0     0  1850
+  2009   577   583     9     0     0  1851
+  2008   578   584     8     0     0  1852
+  2008   579   585     8     0     0  1853
+  2008   557   605     8     0     0  1854
+  2008   558   606     8     0     0  1855
+  2008   561   603     8     0     0  1856
+  2008   561   604     8     0     0  1857
+  2008   564   603     8     0     0  1858
+  2008   565   604     8     0     0  1859
+  2008   584   586     8     0     0  1860
+  2008   585   587     8     0     0  1861
+  2008   566   605     8     0     0  1862
+  2008   564   609     8     0     0  1863
+  2008   565   610     8     0     0  1864
+  2008   567   606     8     0     0  1865
+  2008   557   614     8     0     0  1866
+  2009   545   632     9     0     0  1867
+  2008   558   615     8     0     0  1868
+  2008   582   591     8     0     0  1869
+  2009   546   633     9     0     0  1870
+  2008   583   592     8     0     0  1871
+  2016   580   593    16     0     0  1872
+  2004   581   594     4     0     0  1873
+  2008   561   616     8     0     0  1874
+  2008   561   617     8     0     0  1875
+  2008   586   591     8     0     0  1876
+  2008   587   592     8     0     0  1877
+  2008   568   609     8     0     0  1878
+  2008   569   610     8     0     0  1879
+  2010   588   589    10     0     0  1880
+  2010   588   590    10     0     0  1881
+  2008   582   598     8     0     0  1882
+  2008   583   599     8     0     0  1883
+  2008   564   618     8     0     0  1884
+  2008   565   619     8     0     0  1885
+  2008   564   624     8     0     0  1886
+  2008   565   625     8     0     0  1887
+  2007   588   595     7     0     0  1888
+  2008   568   622     8     0     0  1889
+  2008   569   623     8     0     0  1890
+  2006   496   675     6     0     0  1891
+  2006   497   675     6     0     0  1892
+  2008   570   614     8     0     0  1893
+  2008   591   598     8     0     0  1894
+  2008   592   599     8     0     0  1895
+  2008   573   615     8     0     0  1896
+  2008   571   616     8     0     0  1897
+  2008   572   617     8     0     0  1898
+  2017   593   594    17     0     0  1899
+  2011   588   601    11     0     0  1900
+  2011   588   602    11     0     0  1901
+  2008   568   626     8     0     0  1902
+  2008   569   627     8     0     0  1903
+  2008   574   618     8     0     0  1904
+  2008   575   619     8     0     0  1905
+  2011   589   601    11     0     0  1906
+  2011   590   602    11     0     0  1907
+  2016   593   600    16     0     0  1908
+  2009   576   620     9     0     0  1909
+  2009   577   621     9     0     0  1910
+  2009   576   622     9     0     0  1911
+  2009   577   623     9     0     0  1912
+  2021   595   600    21     0     0  1913
+  2008   568   628     8     0     0  1914
+  2008   569   629     8     0     0  1915
+  2008   578   624     8     0     0  1916
+  2008   579   625     8     0     0  1917
+  2011   589   607    11     0     0  1918
+  2011   590   608    11     0     0  1919
+  2008   582   622     8     0     0  1920
+  2008   583   623     8     0     0  1921
+  2008   596   605     8     0     0  1922
+  2008   597   606     8     0     0  1923
+  2008   598   605     8     0     0  1924
+  2008   584   626     8     0     0  1925
+  2008   585   627     8     0     0  1926
+  2008   599   606     8     0     0  1927
+  2009   601   602     9     0     0  1928
+  2009   601   603     9     0     0  1929
+  2009   602   604     9     0     0  1930
+  2004   594   612     4     0     0  1931
+  2009   576   632     9     0     0  1932
+  2009   577   633     9     0     0  1933
+  2009   601   607     9     0     0  1934
+  2009   602   608     9     0     0  1935
+  2016   600   611    16     0     0  1936
+  2008   596   614     8     0     0  1937
+  2008   597   615     8     0     0  1938
+  2008   582   632     8     0     0  1939
+  2008   586   628     8     0     0  1940
+  2008   583   633     8     0     0  1941
+  2008   587   629     8     0     0  1942
+  2008   582   634     8     0     0  1943
+  2008   583   635     8     0     0  1944
+  2009   607   609     9     0     0  1945
+  2009   608   610     9     0     0  1946
+  2008   603   616     8     0     0  1947
+  2008   604   617     8     0     0  1948
+  2008   582   636     8     0     0  1949
+  2008   583   637     8     0     0  1950
+  2008   605   614     8     0     0  1951
+  2008   606   615     8     0     0  1952
+  2008   603   618     8     0     0  1953
+  2008   604   619     8     0     0  1954
+  2008   591   634     8     0     0  1955
+  2008   592   635     8     0     0  1956
+  2017   611   612    17     0     0  1957
+  2009   607   620     9     0     0  1958
+  2009   608   621     9     0     0  1959
+  2008   609   624     8     0     0  1960
+  2008   610   625     8     0     0  1961
+  2008   596   632     8     0     0  1962
+  2008   597   633     8     0     0  1963
+  2008   609   626     8     0     0  1964
+  2008   610   627     8     0     0  1965
+  2008   616   617     8     0     0  1966
+  2008   616   618     8     0     0  1967
+  2008   617   619     8     0     0  1968
+  2009   620   622     9     0     0  1969
+  2009   621   623     9     0     0  1970
+  2008   618   624     8     0     0  1971
+  2008   619   625     8     0     0  1972
+  2008   598   636     8     0     0  1973
+  2008   599   637     8     0     0  1974
+  2016   611   630    16     0     0  1975
+  2004   612   631     4     0     0  1976
+  2008   624   626     8     0     0  1977
+  2008   625   627     8     0     0  1978
+  2008   596   640     8     0     0  1979
+  2008   597   641     8     0     0  1980
+  2008   622   628     8     0     0  1981
+  2008   623   629     8     0     0  1982
+  2009   576   661     9     0     0  1983
+  2009   577   662     9     0     0  1984
+  2011   589   651    11     0     0  1985
+  2011   590   652    11     0     0  1986
+  2008   626   628     8     0     0  1987
+  2008   627   629     8     0     0  1988
+  2008   622   634     8     0     0  1989
+  2008   623   635     8     0     0  1990
+  2009   601   642     9     0     0  1991
+  2009   602   642     9     0     0  1992
+  2008   603   642     8     0     0  1993
+  2008   604   642     8     0     0  1994
+  2008   605   640     8     0     0  1995
+  2009   601   643     9     0     0  1996
+  2008   606   641     8     0     0  1997
+  2008   596   645     8     0     0  1998
+  2009   602   644     9     0     0  1999
+  2008   597   646     8     0     0  2000
+  2008   603   643     8     0     0  2001
+  2008   604   644     8     0     0  2002
+  2017   630   631    17     0     0  2003
+  2009   607   643     9     0     0  2004
+  2009   608   644     9     0     0  2005
+  2008   609   643     8     0     0  2006
+  2008   610   644     8     0     0  2007
+  2008   628   634     8     0     0  2008
+  2008   629   635     8     0     0  2009
+  2008   603   649     8     0     0  2010
+  2008   604   650     8     0     0  2011
+  2008   603   653     8     0     0  2012
+  2008   604   654     8     0     0  2013
+  2009   607   647     9     0     0  2014
+  2009   608   648     9     0     0  2015
+  2007   589   665     7     0     0  2016
+  2007   590   665     7     0     0  2017
+  2008   609   647     8     0     0  2018
+  2008   610   648     8     0     0  2019
+  2008   609   657     8     0     0  2020
+  2008   610   658     8     0     0  2021
+  2008   614   645     8     0     0  2022
+  2008   632   636     8     0     0  2023
+  2008   615   646     8     0     0  2024
+  2008   633   637     8     0     0  2025
+  2021   595   665    21     0     0  2026
+  2008   634   636     8     0     0  2027
+  2008   635   637     8     0     0  2028
+  2016   630   638    16     0     0  2029
+  2008   609   659     8     0     0  2030
+  2008   610   660     8     0     0  2031
+  2004   631   639     4     0     0  2032
+  2009   620   647     9     0     0  2033
+  2008   616   649     8     0     0  2034
+  2008   617   650     8     0     0  2035
+  2009   621   648     9     0     0  2036
+  2008   622   647     8     0     0  2037
+  2008   623   648     8     0     0  2038
+  2009   620   651     9     0     0  2039
+  2009   621   652     9     0     0  2040
+  2008   618   653     8     0     0  2041
+  2008   619   654     8     0     0  2042
+  2008   632   640     8     0     0  2043
+  2008   633   641     8     0     0  2044
+  2008   624   657     8     0     0  2045
+  2008   625   658     8     0     0  2046
+  2009   620   661     9     0     0  2047
+  2009   621   662     9     0     0  2048
+  2008   622   661     8     0     0  2049
+  2008   623   662     8     0     0  2050
+  2008   636   640     8     0     0  2051
+  2011   588   682    11     0     0  2052
+  2011   588   683    11     0     0  2053
+  2008   637   641     8     0     0  2054
+  2008   622   663     8     0     0  2055
+  2008   623   664     8     0     0  2056
+  2008   626   659     8     0     0  2057
+  2008   627   660     8     0     0  2058
+  2011   589   682    11     0     0  2059
+  2011   590   683    11     0     0  2060
+  2017   638   639    17     0     0  2061
+  2008   622   666     8     0     0  2062
+  2008   623   667     8     0     0  2063
+  2011   589   688    11     0     0  2064
+  2011   590   689    11     0     0  2065
+  2008   628   663     8     0     0  2066
+  2008   629   664     8     0     0  2067
+  2009   601   678     9     0     0  2068
+  2009   602   679     9     0     0  2069
+  2008   632   661     8     0     0  2070
+  2008   633   662     8     0     0  2071
+  2009   601   682     9     0     0  2072
+  2009   602   683     9     0     0  2073
+  2008   640   645     8     0     0  2074
+  2008   641   646     8     0     0  2075
+  2016   638   655    16     0     0  2076
+  2018   613   675    18     0     0  2077
+  2009   607   680     9     0     0  2078
+  2008   642   649     8     0     0  2079
+  2009   608   681     9     0     0  2080
+  2008   642   650     8     0     0  2081
+  2004   639   656     4     0     0  2082
+  2008   634   666     8     0     0  2083
+  2008   635   667     8     0     0  2084
+  2008   643   653     8     0     0  2085
+  2008   644   654     8     0     0  2086
+  2009   607   688     9     0     0  2087
+  2009   608   689     9     0     0  2088
+  2008   643   657     8     0     0  2089
+  2008   644   658     8     0     0  2090
+  2008   632   671     8     0     0  2091
+  2008   633   672     8     0     0  2092
+  2009   647   651     9     0     0  2093
+  2009   648   652     9     0     0  2094
+  2008   649   650     8     0     0  2095
+  2008   649   653     8     0     0  2096
+  2008   650   654     8     0     0  2097
+  2008   632   673     8     0     0  2098
+  2008   636   671     8     0     0  2099
+  2008   653   657     8     0     0  2100
+  2008   654   658     8     0     0  2101
+  2008   637   672     8     0     0  2102
+  2008   633   674     8     0     0  2103
+  2017   655   656    17     0     0  2104
+  2008   647   659     8     0     0  2105
+  2008   648   660     8     0     0  2106
+  2009   620   692     9     0     0  2107
+  2009   621   694     9     0     0  2108
+  2008   647   663     8     0     0  2109
+  2008   648   664     8     0     0  2110
+  2008   657   659     8     0     0  2111
+  2008   658   660     8     0     0  2112
+  2008   659   663     8     0     0  2113
+  2008   660   664     8     0     0  2114
+  2008   640   673     8     0     0  2115
+  2008   641   674     8     0     0  2116
+  2016   655   668    16     0     0  2117
+  2004   656   669     4     0     0  2118
+  2008   642   678     8     0     0  2119
+  2008   642   679     8     0     0  2120
+  2008   661   666     8     0     0  2121
+  2008   662   667     8     0     0  2122
+  2008   643   678     8     0     0  2123
+  2008   644   679     8     0     0  2124
+  2008   663   666     8     0     0  2125
+  2008   664   667     8     0     0  2126
+  2008   645   673     8     0     0  2127
+  2008   646   674     8     0     0  2128
+  2008   643   680     8     0     0  2129
+  2008   644   681     8     0     0  2130
+  2008   642   684     8     0     0  2131
+  2008   642   685     8     0     0  2132
+  2008   661   671     8     0     0  2133
+  2008   662   672     8     0     0  2134
+  2008   643   686     8     0     0  2135
+  2008   644   687     8     0     0  2136
+  2017   668   669    17     0     0  2137
+  2021   665   670    21     0     0  2138
+  2008   647   680     8     0     0  2139
+  2008   643   690     8     0     0  2140
+  2008   648   681     8     0     0  2141
+  2008   644   691     8     0     0  2142
+  2016   668   670    16     0     0  2143
+  2008   666   671     8     0     0  2144
+  2008   667   672     8     0     0  2145
+  2009   651   680     9     0     0  2146
+  2009   652   681     9     0     0  2147
+  2008   649   684     8     0     0  2148
+  2008   650   685     8     0     0  2149
+  2009   651   688     9     0     0  2150
+  2009   652   689     9     0     0  2151
+  2008   653   686     8     0     0  2152
+  2008   654   687     8     0     0  2153
+  2008   647   692     8     0     0  2154
+  2008   648   694     8     0     0  2155
+  2008   647   696     8     0     0  2156
+  2008   648   697     8     0     0  2157
+  2009   651   692     9     0     0  2158
+  2009   652   694     9     0     0  2159
+  2008   657   690     8     0     0  2160
+  2008   658   691     8     0     0  2161
+  2008   647   698     8     0     0  2162
+  2008   648   699     8     0     0  2163
+  2004   669   677     4     0     0  2164
+  2008   671   673     8     0     0  2165
+  2008   672   674     8     0     0  2166
+  2016   670   676    16     0     0  2167
+  2007   665   682     7     0     0  2168
+  2007   665   683     7     0     0  2169
+  2008   659   696     8     0     0  2170
+  2008   660   697     8     0     0  2171
+  2008   661   692     8     0     0  2172
+  2008   662   694     8     0     0  2173
+  2008   663   698     8     0     0  2174
+  2008   664   699     8     0     0  2175
+  2017   676   677    17     0     0  2176
+  2008   661   700     8     0     0  2177
+  2008   662   701     8     0     0  2178
+  2006   496   775     6     0     0  2179
+  2006   497   775     6     0     0  2180
+  2009   678   682     9     0     0  2181
+  2009   679   683     9     0     0  2182
+  2008   661   704     8     0     0  2183
+  2008   666   700     8     0     0  2184
+  2008   667   701     8     0     0  2185
+  2008   662   705     8     0     0  2186
+  2008   678   684     8     0     0  2187
+  2008   679   685     8     0     0  2188
+  2008   678   686     8     0     0  2189
+  2008   679   687     8     0     0  2190
+  2009   682   683     9     0     0  2191
+  2016   676   693    16     0     0  2192
+  2009   680   688     9     0     0  2193
+  2009   681   689     9     0     0  2194
+  2004   677   695     4     0     0  2195
+  2009   682   688     9     0     0  2196
+  2009   683   689     9     0     0  2197
+  2008   680   690     8     0     0  2198
+  2008   681   691     8     0     0  2199
+  2008   684   685     8     0     0  2200
+  2008   684   686     8     0     0  2201
+  2008   685   687     8     0     0  2202
+  2008   680   696     8     0     0  2203
+  2008   681   697     8     0     0  2204
+  2008   671   704     8     0     0  2205
+  2008   672   705     8     0     0  2206
+  2009   651   716     9     0     0  2207
+  2009   652   717     9     0     0  2208
+  2008   686   690     8     0     0  2209
+  2008   687   691     8     0     0  2210
+  2008   690   696     8     0     0  2211
+  2008   691   697     8     0     0  2212
+  2008   673   704     8     0     0  2213
+  2008   674   705     8     0     0  2214
+  2017   693   695    17     0     0  2215
+  2008   692   698     8     0     0  2216
+  2008   694   699     8     0     0  2217
+  2008   696   698     8     0     0  2218
+  2008   697   699     8     0     0  2219
+  2018   675   706    18     0     0  2220
+  2008   692   700     8     0     0  2221
+  2008   694   701     8     0     0  2222
+  2016   693   702    16     0     0  2223
+  2008   698   700     8     0     0  2224
+  2008   699   701     8     0     0  2225
+  2004   695   703     4     0     0  2226
+  2008   678   709     8     0     0  2227
+  2008   679   709     8     0     0  2228
+  2008   678   710     8     0     0  2229
+  2008   679   711     8     0     0  2230
+  2009   682   709     9     0     0  2231
+  2009   683   709     9     0     0  2232
+  2008   680   710     8     0     0  2233
+  2008   681   711     8     0     0  2234
+  2008   678   712     8     0     0  2235
+  2008   679   713     8     0     0  2236
+  2009   682   710     9     0     0  2237
+  2009   683   711     9     0     0  2238
+  2008   678   714     8     0     0  2239
+  2008   679   715     8     0     0  2240
+  2008   700   704     8     0     0  2241
+  2008   701   705     8     0     0  2242
+  2009   688   710     9     0     0  2243
+  2009   689   711     9     0     0  2244
+  2017   702   703    17     0     0  2245
+  2008   680   716     8     0     0  2246
+  2008   681   717     8     0     0  2247
+  2008   680   718     8     0     0  2248
+  2008   681   719     8     0     0  2249
+  2008   684   712     8     0     0  2250
+  2008   685   713     8     0     0  2251
+  2008   686   714     8     0     0  2252
+  2008   687   715     8     0     0  2253
+  2008   680   722     8     0     0  2254
+  2008   681   723     8     0     0  2255
+  2009   688   716     9     0     0  2256
+  2009   689   717     9     0     0  2257
+  2008   690   718     8     0     0  2258
+  2008   691   719     8     0     0  2259
+  2021   665   732    21     0     0  2260
+  2008   692   716     8     0     0  2261
+  2008   694   717     8     0     0  2262
+  2016   702   707    16     0     0  2263
+  2008   696   722     8     0     0  2264
+  2008   697   723     8     0     0  2265
+  2004   703   708     4     0     0  2266
+  2008   692   724     8     0     0  2267
+  2008   694   725     8     0     0  2268
+  2008   692   726     8     0     0  2269
+  2008   698   724     8     0     0  2270
+  2008   694   727     8     0     0  2271
+  2008   699   725     8     0     0  2272
+  2017   707   708    17     0     0  2273
+  2007   682   732     7     0     0  2274
+  2007   683   732     7     0     0  2275
+  2008   700   726     8     0     0  2276
+  2008   701   727     8     0     0  2277
+  2009   682   734     9     0     0  2278
+  2009   683   734     9     0     0  2279
+  2008   709   712     8     0     0  2280
+  2008   709   713     8     0     0  2281
+  2009   682   735     9     0     0  2282
+  2009   683   736     9     0     0  2283
+  2009   682   738     9     0     0  2284
+  2009   683   739     9     0     0  2285
+  2008   704   726     8     0     0  2286
+  2008   705   727     8     0     0  2287
+  2016   707   720    16     0     0  2288
+  2008   710   714     8     0     0  2289
+  2008   711   715     8     0     0  2290
+  2004   708   721     4     0     0  2291
+  2008   710   718     8     0     0  2292
+  2008   711   719     8     0     0  2293
+  2009   688   738     9     0     0  2294
+  2009   689   739     9     0     0  2295
+  2008   712   713     8     0     0  2296
+  2008   712   714     8     0     0  2297
+  2008   713   715     8     0     0  2298
+  2009   688   742     9     0     0  2299
+  2009   689   743     9     0     0  2300
+  2008   714   718     8     0     0  2301
+  2008   715   719     8     0     0  2302
+  2018   706   730    18     0     0  2303
+  2008   716   722     8     0     0  2304
+  2008   717   723     8     0     0  2305
+  2008   718   722     8     0     0  2306
+  2008   719   723     8     0     0  2307
+  2006   538   778     6     0     0  2308
+  2006   541   778     6     0     0  2309
+  2017   720   721    17     0     0  2310
+  2008   716   724     8     0     0  2311
+  2008   717   725     8     0     0  2312
+  2008   722   724     8     0     0  2313
+  2008   723   725     8     0     0  2314
+  2016   720   728    16     0     0  2315
+  2004   721   729     4     0     0  2316
+  2008   724   726     8     0     0  2317
+  2008   725   727     8     0     0  2318
+  2008   709   735     8     0     0  2319
+  2008   709   736     8     0     0  2320
+  2008   710   735     8     0     0  2321
+  2008   711   736     8     0     0  2322
+  2008   709   740     8     0     0  2323
+  2008   709   741     8     0     0  2324
+  2017   728   729    17     0     0  2325
+  2008   710   742     8     0     0  2326
+  2008   711   743     8     0     0  2327
+  2008   710   745     8     0     0  2328
+  2008   711   746     8     0     0  2329
+  2008   710   748     8     0     0  2330
+  2008   711   749     8     0     0  2331
+  2008   712   740     8     0     0  2332
+  2008   713   741     8     0     0  2333
+  2008   716   742     8     0     0  2334
+  2008   714   745     8     0     0  2335
+  2008   717   743     8     0     0  2336
+  2008   715   746     8     0     0  2337
+  2008   718   748     8     0     0  2338
+  2008   719   749     8     0     0  2339
+  2016   728   731    16     0     0  2340
+  2008   716   750     8     0     0  2341
+  2008   717   751     8     0     0  2342
+  2004   729   733     4     0     0  2343
+  2008   716   752     8     0     0  2344
+  2008   722   750     8     0     0  2345
+  2008   717   753     8     0     0  2346
+  2008   723   751     8     0     0  2347
+  2008   724   752     8     0     0  2348
+  2017   731   733    17     0     0  2349
+  2008   725   753     8     0     0  2350
+  2008   726   752     8     0     0  2351
+  2008   727   753     8     0     0  2352
+  2016   731   737    16     0     0  2353
+  2007   732   735     7     0     0  2354
+  2007   732   736     7     0     0  2355
+  2021   732   737    21     0     0  2356
+  2008   734   735     8     0     0  2357
+  2008   734   736     8     0     0  2358
+  2004   733   747     4     0     0  2359
+  2008   735   738     8     0     0  2360
+  2008   736   739     8     0     0  2361
+  2008   734   740     8     0     0  2362
+  2008   734   741     8     0     0  2363
+  2018   730   756    18     0     0  2364
+  2008   735   740     8     0     0  2365
+  2008   736   741     8     0     0  2366
+  2008   735   745     8     0     0  2367
+  2008   736   746     8     0     0  2368
+  2008   738   742     8     0     0  2369
+  2008   739   743     8     0     0  2370
+  2016   737   744    16     0     0  2371
+  2008   738   745     8     0     0  2372
+  2008   739   746     8     0     0  2373
+  2008   740   741     8     0     0  2374
+  2008   738   748     8     0     0  2375
+  2008   739   749     8     0     0  2376
+  2008   740   745     8     0     0  2377
+  2008   741   746     8     0     0  2378
+  2008   742   748     8     0     0  2379
+  2008   743   749     8     0     0  2380
+  2017   744   747    17     0     0  2381
+  2008   745   748     8     0     0  2382
+  2008   746   749     8     0     0  2383
+  2006   496   786     6     0     0  2384
+  2006   497   786     6     0     0  2385
+  2008   742   750     8     0     0  2386
+  2008   743   751     8     0     0  2387
+  2008   748   750     8     0     0  2388
+  2008   749   751     8     0     0  2389
+  2016   744   754    16     0     0  2390
+  2008   750   752     8     0     0  2391
+  2008   751   753     8     0     0  2392
+  2004   747   755     4     0     0  2393
+  2006   538   785     6     0     0  2394
+  2006   541   785     6     0     0  2395
+  2017   754   755    17     0     0  2396
+  2021   732   765    21     0     0  2397
+  2016   754   757    16     0     0  2398
+  2008   734   761     8     0     0  2399
+  2008   734   762     8     0     0  2400
+  2008   735   761     8     0     0  2401
+  2008   736   762     8     0     0  2402
+  2008   735   763     8     0     0  2403
+  2008   736   764     8     0     0  2404
+  2004   755   758     4     0     0  2405
+  2007   735   765     7     0     0  2406
+  2007   736   765     7     0     0  2407
+  2008   738   763     8     0     0  2408
+  2008   739   764     8     0     0  2409
+  2008   740   761     8     0     0  2410
+  2008   741   762     8     0     0  2411
+  2008   738   766     8     0     0  2412
+  2008   739   767     8     0     0  2413
+  2008   745   763     8     0     0  2414
+  2008   746   764     8     0     0  2415
+  2008   742   766     8     0     0  2416
+  2008   743   767     8     0     0  2417
+  2008   742   770     8     0     0  2418
+  2008   748   766     8     0     0  2419
+  2008   749   767     8     0     0  2420
+  2008   743   771     8     0     0  2421
+  2017   757   758    17     0     0  2422
+  2008   750   770     8     0     0  2423
+  2008   751   771     8     0     0  2424
+  2008   752   770     8     0     0  2425
+  2008   753   771     8     0     0  2426
+  2016   757   759    16     0     0  2427
+  2004   758   760     4     0     0  2428
+  2018   756   772    18     0     0  2429
+  2017   759   760    17     0     0  2430
+  2006   538   795     6     0     0  2431
+  2006   541   795     6     0     0  2432
+  2016   759   768    16     0     0  2433
+  2004   760   769     4     0     0  2434
+  2008   761   762     8     0     0  2435
+  2008   761   763     8     0     0  2436
+  2008   762   764     8     0     0  2437
+  2007   761   765     7     0     0  2438
+  2007   762   765     7     0     0  2439
+  2008   763   766     8     0     0  2440
+  2008   764   767     8     0     0  2441
+  2008   766   770     8     0     0  2442
+  2017   768   769    17     0     0  2443
+  2008   767   771     8     0     0  2444
+  2021   765   773    21     0     0  2445
+  2016   768   773    16     0     0  2446
+  2004   769   773     4     0     0  2447
+  2006   538   801     6     0     0  2448
+  2006   541   801     6     0     0  2449
+  2007   761   774     7     0     0  2450
+  2007   762   774     7     0     0  2451
+  2021   765   774    21     0     0  2452
+  2016   773   774    16     0     0  2453
+  2006   538   811     6     0     0  2454
+  2006   541   811     6     0     0  2455
+  2018   772   775    18     0     0  2456
+  2018   774   776    18     0     0  2457
+  2018   775   777    18     0     0  2458
+  2018   776   778    18     0     0  2459
+  2018   777   779    18     0     0  2460
+  2018   778   780    18     0     0  2461
+  2018   779   781    18     0     0  2462
+  2018   780   783    18     0     0  2463
+  2018   781   782    18     0     0  2464
+  2018   782   784    18     0     0  2465
+  2018   783   785    18     0     0  2466
+  2018   784   786    18     0     0  2467
+  2019   782   792    19     0     0  2468
+  2019   782   793    19     0     0  2469
+  2018   785   790    18     0     0  2470
+  2018   786   788    18     0     0  2471
+  2020   787   788    20     0     0  2472
+  2020   788   789    20     0     0  2473
+  2020   787   791    20     0     0  2474
+  2020   789   794    20     0     0  2475
+  2018   790   795    18     0     0  2476
+  2020   791   792    20     0     0  2477
+  2020   792   793    20     0     0  2478
+  2020   793   794    20     0     0  2479
+  2020   787   797    20     0     0  2480
+  2020   789   799    20     0     0  2481
+  2018   795   796    18     0     0  2482
+  2020   791   805    20     0     0  2483
+  2020   794   808    20     0     0  2484
+  2018   796   800    18     0     0  2485
+  2020   797   798    20     0     0  2486
+  2020   798   799    20     0     0  2487
+  2018   798   801    18     0     0  2488
+  2018   800   802    18     0     0  2489
+  2018   801   803    18     0     0  2490
+  2020   797   805    20     0     0  2491
+  2020   799   808    20     0     0  2492
+  2018   803   804    18     0     0  2493
+  2018   802   809    18     0     0  2494
+  2019   804   806    19     0     0  2495
+  2019   804   807    19     0     0  2496
+  2020   805   806    20     0     0  2497
+  2020   806   807    20     0     0  2498
+  2020   807   808    20     0     0  2499
+  2018   804   810    18     0     0  2500
+  2018   809   811    18     0     0  2501
+  2018   810   812    18     0     0  2502
+  2018   811   813    18     0     0  2503
+  2018   812   813    18     0     0  2504
+<# Ende
+<# Schluss
Index: branches/Mars_McMismatchStudy/resources/exclusions.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/exclusions.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/exclusions.rc	(revision 17960)
@@ -0,0 +1,47 @@
+#DataRunWithTTPed:
+key2:    RunType.fRunType='data' AND L2TriggerTable.fL2TriggerTableName='PED' 
+
+#ProjectLikeCL:
+key3:    Project.fProjectName like binary '%CL%' or CalibrationScript.fCalibrationScriptName like '%ContinuosLight'
+
+#ProjectLikeClose:
+key4:    Project.fProjectName like '%close%' 
+
+#TriggerTableNA:
+key6:    L2TriggerTable.fL2TriggerTableName='n/a' AND L1TriggerTable.fL1TriggerTableName='n/a'
+
+#ProjectLikeCurtain:
+key10:   Project.fProjectName like '%curtain%' 
+
+#PedRunWithNoPedTT:
+key11:   RunType.fRunTypeName='pedestal' AND NOT (L2TriggerTable.fL2TriggerTableName='PED') AND fRunNumber<35659
+
+#SourceLikePark:
+key12:   Source.fSourceName like '%park%'
+
+#SourceLikeDummy:
+key14:   Source.fSourceName like '%dummy%'
+
+#NumEventsSmaller10:
+key15:   fNumEvents between 2 and 9 
+
+#ProjectLikeDummy:
+key16:   Project.fProjectName like '%dummy%'
+
+#ProjectLikeTest:
+key17:   Project.fProjectName like '%test%'
+
+#NumEventsSmaller2:
+key18:   fNumEvents < 2 
+
+#ProjectLikeMovetel:
+key20:   Project.fProjectName like binary 'movetel%' 
+
+#DTTableAsTriggerDelay:
+key21:   TriggerDelayTable.fTriggerDelayTableName like 'thresh%' 
+
+#ProjectLikeFFweak:
+key23:   Project.fProjectName like binary '%FFweak%' or CalibrationScript.fCalibrationScriptName='Flatfielding_weak'
+
+#FlagIsTest:
+key24:   TestFlag.fTestFlagName='Test'
Index: branches/Mars_McMismatchStudy/resources/good_compstars_R.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/good_compstars_R.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/good_compstars_R.txt	(revision 17960)
@@ -0,0 +1,252 @@
+1ES_0033+595 A  14.10 1.06  -
+1ES_0033+595 B  13.33 0.56  -
+1ES_0033+595 C  12.52 0.74  -
+1ES_0033+595 D  13.66 1.46  prim
+1ES_0033+595 E  13.91 0.55  -
+1ES_0033+595 F  16.67 0.87  control
+
+1ES_0120+340 A  13.13 0.50  -
+1ES_0120+340 B  13.74 0.48  -
+1ES_0120+340 C  13.12 0.38  prim
+1ES_0120+340 D  14.02 0.51  -
+1ES_0120+340 E  13.55 0.56  -
+1ES_0120+340 F  16.76 0.57  -
+1ES_0120+340 G  16.43 0.45  control
+
+RGB_0136+391 A  13.13 0.60  control
+RGB_0136+391 B  13.82 0.42  prim
+RGB_0136+391 C  14.40 0.76  -
+RGB_0136+391 D  14.42 0.46  -
+RGB_0136+391 E  14.84 0.51  -
+RGB_0136+391 F  16.56 0.42  -
+
+RGB_0152+017 A  14.35 0.50  control
+RGB_0152+017 B  14.22 0.50  prim
+RGB_0152+017 C  16.80 0.50  -
+RGB_0152+017 D  17.25 0.50  -
+RGB_0152+017 E  15.88 0.50  -
+
+MS_0158+002  A  12.75 0.37 prim
+MS_0158+002  B  12.76 0.54 control
+
+RGB_0214+517 A  13.85 0.51  prim
+RGB_0214+517 B  14.54 0.57  control
+RGB_0214+517 C  13.61 0.38  -
+RGB_0214+517 D  15.09 0.47  -
+RGB_0214+517 E  15.19 0.44  -
+
+3C_66A       A   13.38 0.22  prim
+3C_66A       B   14.28 0.49  control
+3C_66A       C1  12.70 0.09  -
+3C_66A       C2  13.62 0.56  -
+
+1ES_0229+200 A  13.80 0.50  prim
+1ES_0229+200 B  16.05 0.50  -
+1ES_0229+200 C  15.83 0.50  control
+
+AO_0235+164  1  12.69 0.34  -
+AO_0235+164  2  12.23 0.48  -
+AO_0235+164  3  12.48 0.44  -
+AO_0235+164  6  13.64 0.38  -
+AO_0235+164  8  15.79 0.79  control
+AO_0235+164  C1 14.23 0.55  prim
+
+HB89_0317+185 A  11.55 0.31 -
+HB89_0317+185 B  13.33 0.43 prim
+HB89_0317+185 C  20.00 0.50 control
+
+1ES_0323+022 A  12.33 0.52  -
+1ES_0323+022 B  14.01 0.37  prim
+1ES_0323+022 C1 13.34 0.66  -
+1ES_0323+022 C2 13.84 0.60  -
+1ES_0323+022 C3 15.36 0.39  control
+
+1ES_0647+250 A  13.83 0.33  -
+1ES_0647+250 B  15.22 0.38  control
+1ES_0647+250 C  13.40 0.40  -
+1ES_0647+250 D  13.44 0.34  -
+1ES_0647+250 E  13.03 0.59  prim
+1ES_0647+250 F  14.89 0.38  -
+
+S5_0716+714  1  10.63 0.36  -
+S5_0716+714  2  11.12 0.34  -    
+S5_0716+714  3  12.06 0.37  -      
+S5_0716+714  4  12.89 0.30  -
+S5_0716+714  5  13.18 0.37  prim
+S5_0716+714  6  13.26 0.37  control
+S5_0716+714  7  13.32 0.42  -      
+S5_0716+714  8  13.79 0.31  -      
+
+PKS_0735+178 C  13.84 0.60  control
+PKS_0735+178 C1 12.91 0.33  -
+PKS_0735+178 C2 12.81 0.49  prim
+PKS_0735+178 D  15.44 0.44  -
+
+1ES_0806+524 C1 12.56 0.48  -
+1ES_0806+524 C2 14.22 0.39  prim
+1ES_0806+524 C3 14.39 0.38  -
+1ES_0806+524 C4 15.24 0.35  control
+1ES_0806+524 C5 15.32 0.30  -
+
+0836+710     A  16.59 1.01  control
+0836+710     B  14.85 0.45  -
+0836+710     C  13.53 0.38  prim
+
+OJ_287       4  13.74 0.44  prim
+OJ_287      11  14.65 0.29  -
+OJ_287      10  14.34 0.26  control
+OJ_287      C1  15.50 0.38  -
+OJ_287      C2  15.66 0.46  -
+
+S4_0954+65   C1 13.96 0.41  prim
+S4_0954+65   C2 14.12 0.49  -
+S4_0954+65   C3 14.25 0.69  -
+S4_0954+65   C4 14.43 0.92  -
+S4_0954+65   C6 15.69 0.48  control
+ 
+1ES_1011+496 A  13.40 0.47  -
+1ES_1011+496 B  15.44 0.44  control
+1ES_1011+496 C  15.42 0.31  -
+1ES_1011+496 D  14.01 0.31  -
+1ES_1011+496 E  14.04 0.39  prim
+
+1ES_1028+511 1  12.93 0.27  prim
+1ES_1028+511 2  14.04 0.25  -
+1ES_1028+511 3  14.18 0.22  -
+1ES_1028+511 4  14.17 0.23  -
+1ES_1028+511 5  14.75 0.28  control
+1ES_1028+511 6  14.87 0.19  -
+
+Mkn_421      1  14.04 0.32  prim
+Mkn_421      2  15.20 0.37  control
+Mkn_421      3  15.24 0.53  -
+
+RGB_1117+202 A  11.90 0.38  -
+RGB_1117+202 B  12.02 0.38  -
+RGB_1117+202 C  20.00 0.50  -
+RGB_1117+202 D  14.82 0.70  -
+RGB_1117+202 E  13.56 0.42  prim
+RGB_1117+202 F  15.16 0.43  control
+
+Mkn_180      1  13.73 0.25  prim
+Mkn_180      2  14.41 0.39  control
+Mkn_180      3  15.13 0.36  -
+Mkn_180      4  15.66 0.34  -
+
+RGB_1136+676 A  14.48 0.66  -
+RGB_1136+676 B  14.22 0.48  -
+RGB_1136+676 C  14.73 0.34  -
+RGB_1136+676 D  14.58 0.46  prim
+RGB_1136+676 E  15.80 0.42  control
+
+4C_29_45    13  14.97 0.39  prim
+4C_29_45    14  15.53 0.36  control
+4C_29_45    15  16.30 0.3   -
+4C_29_45     1  13.01 0.38  -
+
+ON_325       B  14.59 0.37  prim
+ON_325       C1 16.21 0.29  control
+
+1ES_1218+304 A  12.06 0.41  -
+1ES_1218+304 B  13.61 0.40  prim
+1ES_1218+304 C  15.58 0.62  control
+
+ON_231       A  11.72 0.36  -
+ON_231       C1 16.03 0.57  control
+ON_231       D  13.86 0.95  prim
+
+ON_238       1  13.84 0.35  prim
+ON_238       2  14.56 0.30  -
+ON_238       3  15.26 0.40  -
+ON_238       4  15.83 0.41  control
+
+3C_273       C  11.30 0.57  -
+3C_273       D  12.31 0.37  -
+3C_273       E  12.27 0.42  prim
+3C_273       G  13.16 0.40  control
+
+3C_279	     1	15.45 0.49  control
+3C_279	     2  12.05 0.37  -
+3C_279	     3  14.53 0.37  prim
+3C_279	     4  12.57 0.43  -
+3C_279	     5  20.00 0.00  -
+3C_279	     6  12.45 0.36  -
+3C_279	     7  15.13 0.53  -
+3C_279	     8  14.44 0.53  -
+
+RGB_1417+257 A  13.78 0.57  prim
+RGB_1417+257 C1 15.29 1.16  -
+RGB_1417+257 C2 16.13 0.59  control
+
+PG_1424+240  C1 13.20 0.39  prim
+PG_1424+240  C2 13.32 0.38  control
+PG_1424+240  C3 15.57 0.34  -
+
+1ES_1426+428 A  13.23 0.93  control
+1ES_1426+428 B  14.17 0.44  prim
+1ES_1426+428 C  13.00 0.46  -
+1ES_1426+428 D  15.20 0.33  -
+
+PKS_1510-089 A  14.25 0.37  prim
+PKS_1510-089 B  14.63 0.55  control
+PKS_1510-089 C  16.93 0.59  -
+PKS_1510-089 D  16.10 0.43  -
+PKS_1510-089 1  11.14 0.40  -
+PKS_1510-089 2  12.88 0.29  -
+PKS_1510-089 3  13.95 0.40  -
+PKS_1510-089 5  14.35 0.35  -
+
+B2_1633+38   A  15.48 0.35  prim
+B2_1633+38   B  15.44 0.47  control
+B2_1633+38   C  17.22 0.69  -
+
+Mkn_501      1  12.11 0.50  control
+Mkn_501      2  12.79 0.44  -
+Mkn_501      3  14.80 0.44  -
+Mkn_501      4  14.96 0.34  prim
+Mkn_501      5  15.08 0.43  -
+Mkn_501      6  14.99 0.68  prim
+
+H_1722+119   C1 10.94 1.04  -
+H_1722+119   C2 12.62 0.59  prim
+H_1722+119   C3 13.63 0.47  -
+H_1722+119   C4 15.14 0.60  control
+
+OT_546       B  12.81 0.33  prim
+OT_546       H  14.99 0.33  control
+OT_546       L  15.71 0.36  -
+
+1ES_1959+650 1  12.29 0.38  -
+1ES_1959+650 2  12.53 0.33  -
+1ES_1959+650 3  12.27 0.91  -
+1ES_1959+650 4  14.08 0.45  prim
+1ES_1959+650 5  14.00 0.54  -
+1ES_1959+650 6  14.78 0.42  prim
+1ES_1959+650 7  14.79 0.45  control
+
+PKS_2155-304 2  11.67 0.38  prim
+PKS_2155-304 3  12.47 0.53  control
+PKS_2155-304 4  13.92 0.36  -
+PKS_2155-304 5  15.01 0.34  -
+
+BL_Lac       B  11.99 0.91  -
+BL_Lac       C  13.79 0.47  prim
+BL_Lac       K  15.00 0.47  -
+BL_Lac       H  13.73 0.67  control
+BL_Lac       F1 15.60 0.50  -
+BL_Lac       F2 15.32 0.50  -
+
+3C_454.3     A  15.32 0.54  -
+3C_454.3     B  14.73 0.48  -
+3C_454.3     C  13.98 0.45  -
+3C_454.3     D  13.22 0.63  -
+3C_454.3     E  14.92 0.84  control
+3C_454.3     F  14.83 0.38  -
+3C_454.3     G  14.83 0.59  -
+3C_454.3     H  13.10 0.55  prim
+3C_454.3     C1 15.27 0.40  -
+
+1ES_2344+514 C1 12.25 0.36  prim
+1ES_2344+514 C2 14.20 0.42  -
+1ES_2344+514 C3 15.40 0.49  control
+1ES_2344+514  A 13.40 0.50  -
Index: branches/Mars_McMismatchStudy/resources/hilocalib.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/hilocalib.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/hilocalib.rc	(revision 17960)
@@ -0,0 +1,41 @@
+MC: resources/hiloconv-df46-mc.root
+
+20: resources/hiloconv-df46-p20.root
+21: resources/hiloconv-df46-p21.root
+22: resources/hiloconv-df46-p22.root
+# df factors cannot be calculated, none of the sequence is running with df
+# inserting these factors so that makecallistolinks is running automatically
+23: resources/hiloconv-df46-p22.root
+24: resources/hiloconv-df46-p22.root
+25: resources/hiloconv-df46-p22.root
+
+27: resources/hiloconv-df46-p27.root
+28: resources/hiloconv-df46-p28.root
+29: resources/hiloconv-df46-p29.root
+30: resources/hiloconv-df46-p30.root
+31: resources/hiloconv-df46-p31.root
+32: resources/hiloconv-df46-p32.root
+33: resources/hiloconv-df46-p33.root
+34: resources/hiloconv-df46-p34.root
+35: resources/hiloconv-df46-p35.root
+36: resources/hiloconv-df46-p36.root
+37: resources/hiloconv-df46-p37.root
+38: resources/hiloconv-df46-p38.root
+39: resources/hiloconv-df46-p39.root
+40: resources/hiloconv-df46-p40.root
+
+# Data after introduction of splitters
+#41: hiloconv-df46-p41.root
+#42: hiloconv-df46-p42.root
+
+41: resources/hiloconv-df46-p43.root
+42: resources/hiloconv-df46-p43.root
+
+43: resources/hiloconv-df46-p43.root
+44: resources/hiloconv-df46-p44.root
+45: resources/hiloconv-df46-p45.root
+46: resources/hiloconv-df46-p46.root
+47: resources/hiloconv-df46-p47.root
+48: resources/hiloconv-df46-p48.root
+49: resources/hiloconv-df46-p49.root
+50: resources/hiloconv-df46-p50.root
Index: branches/Mars_McMismatchStudy/resources/hilocalib_sp1.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/hilocalib_sp1.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/hilocalib_sp1.rc	(revision 17960)
@@ -0,0 +1,16 @@
+20: resources/hiloconv-sp1-p22.root
+21: resources/hiloconv-sp1-p22.root
+22: resources/hiloconv-sp1-p22.root
+23: resources/hiloconv-sp1-p22.root
+24: resources/hiloconv-sp1-p22.root
+25: resources/hiloconv-sp1-p22.root
+28: resources/hiloconv-sp1-p22.root
+30: resources/hiloconv-sp1-p22.root
+
+32: resources/hiloconv-sp1-p36.root
+35: resources/hiloconv-sp1-p36.root
+36: resources/hiloconv-sp1-p36.root
+37: resources/hiloconv-sp1-p37.root
+38: resources/hiloconv-sp1-p37.root
+39: resources/hiloconv-sp1-p37.root
+
Index: branches/Mars_McMismatchStudy/resources/mirrors.def
===================================================================
--- branches/Mars_McMismatchStudy/resources/mirrors.def	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/mirrors.def	(revision 17960)
@@ -0,0 +1,1093 @@
+#################################################################
+# MAGIC definition file
+# Latest version: Abelardo Moralejo Nov 2004
+#################################################################
+# file         magic.def
+# title        MAGIC definition file
+# description  MAGIC def. file to be used by Reflector simulation
+# author       J C Gonzalez, A Moralejo
+# support      moralejo@pd.infn.it
+#
+# Nov 2004, A. Moralejo (moralejo@pd.infn.it) 
+# Set final MAGIC-1 design with 964 mirrors, but with no 
+# chessboarding of the panels. Telescope is focused at 10 km distance 
+# (1697 cm paraboloid, camera plane set at 1700 cm). Mirror positions 
+# and orientations calculated with code writemagicdef.c, included in 
+# the CVS tree of the reflector simulation program.
+#
+#------------------------------------------------------------
+#
+# type of definition file  (0: CT1, 1: MAGIC)
+#
+type  1
+#
+# focal distance [cm]
+#
+focal_distance      1700.0
+#
+# point spread function, sigma in x and y on camera [cm]
+#
+point_spread        0.5
+#
+# black spot in the center of the mirror, radius [cm]
+#
+black_spot          0.5
+#
+# camera RADIUS [cm]
+#
+camera_width        70.0
+#
+# number of mirrors
+#
+n_mirrors 956
+#
+# radius of a single mirror
+#
+r_mirror 24.75
+#
+# this entry is followed by the def. of mirrors, everything in [radians] or [cm]
+#
+#*  TYPE=0  (CT1)
+#*      i   s   rho   theta   x   y   z   thetan  phin  xn   yn   zn
+#* 
+#*       i : number of the mirror
+#*       s : arc length [cm]
+#*     rho : polar rho of the position of the center of the mirror [cm]
+#*   theta : polar angle of the position of the center of the mirror [cm]
+#*       x : x coordinate of the center of the mirror [cm]
+#*       y : y coordinate of the center of the mirror [cm]
+#*       z : z coordinate of the center of the mirror [cm]
+#*  thetan : polar theta angle of the direction where the mirror points to
+#*    phin : polar phi angle of the direction where the mirror points to
+#*      xn : xn coordinate of the normal vector in the center (normalized)
+#*      yn : yn coordinate of the normal vector in the center (normalized)
+#*      zn : zn coordinate of the normal vector in the center (normalized)
+#* 
+#*  TYPE=1  (MAGIC)
+#*      i  f   sx   sy   x   y   z   thetan  phin 
+#* 
+#*       i : number of the mirror
+#*       f : focal distance of that mirror
+#*      sx : curvilinear coordinate of mirror's center in X[cm]
+#*      sy : curvilinear coordinate of mirror's center in X[cm]
+#*       x : x coordinate of the center of the mirror [cm]
+#*       y : y coordinate of the center of the mirror [cm]
+#*       z : z coordinate of the center of the mirror [cm]
+#*  thetan : polar theta angle of the direction where the mirror points to
+#*    phin : polar phi angle of the direction where the mirror points to
+#*      xn : xn coordinate of the normal vector in the center (normalized)
+#*      yn : yn coordinate of the normal vector in the center (normalized)
+#*      zn : zn coordinate of the normal vector in the center (normalized)
+#
+define_mirrors
+  1 1819.0634 -833.0538 -375.7616 -825.0000 -375.0000  120.9856 0.26092194 3.56822014 0.23484851 0.10674932 0.96615255
+  2 1813.8174 -833.0538 -325.4960 -825.0000 -325.0000  115.8294 0.25554542 3.51686347 0.23518226 0.09264756 0.96752557
+  3 1809.3239 -833.0538 -275.3006 -825.0000 -275.0000  111.4098 0.25082849 3.46334320 0.23546947 0.07848982 0.96870712
+  4 1805.5815 -833.0538 -225.1647 -825.0000 -225.0000  107.7269 0.24681679 3.40784470 0.23570961 0.06428444 0.96969505
+  5 1802.5890 -833.0538 -175.0775 -825.0000 -175.0000  104.7805 0.24355180 3.35061559 0.23590225 0.05003987 0.97048758
+  6 1800.3455 -833.0538 -125.0283 -825.0000 -125.0000  102.5707 0.24106928 3.29196407 0.23604705 0.03576470 0.97108325
+  7 1798.1027 -833.0538  -25.0002 -825.0000  -25.0000  100.3609 0.23855678 3.17188641 0.23619211 0.00715734 0.97168002
+  8 1798.1027 -833.0538   25.0002 -825.0000   25.0000  100.3609 0.23855678 3.11129889 0.23619211 -0.00715734 0.97168002
+  9 1800.3455 -833.0538  125.0283 -825.0000  125.0000  102.5707 0.24106928 2.99122123 0.23604705 -0.03576470 0.97108325
+ 10 1802.5890 -833.0538  175.0775 -825.0000  175.0000  104.7805 0.24355180 2.93256971 0.23590225 -0.05003987 0.97048758
+ 11 1805.5815 -833.0538  225.1647 -825.0000  225.0000  107.7269 0.24681679 2.87534060 0.23570961 -0.06428444 0.96969505
+ 12 1809.3239 -833.0538  275.3006 -825.0000  275.0000  111.4098 0.25082849 2.81984210 0.23546947 -0.07848982 0.96870712
+ 13 1813.8174 -833.0538  325.4960 -825.0000  325.0000  115.8294 0.25554542 2.76632183 0.23518226 -0.09264756 0.96752557
+ 14 1819.0634 -833.0538  375.7616 -825.0000  375.0000  120.9856 0.26092194 2.71496516 0.23484851 -0.10674932 0.96615255
+ 15 1813.0683 -781.6832 -426.1081 -775.0000 -425.0000  115.0928 0.25476639 3.64319670 0.22097369 0.12117912 0.96772220
+ 16 1807.0782 -781.6832 -375.7616 -775.0000 -375.0000  109.2001 0.24843056 3.59225397 0.22133386 0.10709703 0.96929951
+ 17 1801.8411 -781.6832 -325.4960 -775.0000 -325.0000  104.0439 0.24272757 3.53867209 0.22165046 0.09295019 0.97068601
+ 18 1797.3553 -781.6832 -275.3006 -775.0000 -275.0000   99.6243 0.23771246 3.48257160 0.22192291 0.07874684 0.97187919
+ 19 1793.6193 -781.6832 -225.1647 -775.0000 -225.0000   95.9414 0.23343795 3.42414760 0.22215073 0.06449537 0.97287687
+ 20 1790.6319 -781.6832 -175.0775 -775.0000 -175.0000   92.9950 0.22995247 3.36367455 0.22233349 0.05020434 0.97367723
+ 21 1788.3922 -781.6832 -125.0283 -775.0000 -125.0000   90.7852 0.22729817 3.30150577 0.22247085 0.03588240 0.97427880
+ 22 1786.8995 -781.6832  -75.0061 -775.0000  -75.0000   89.3120 0.22550881 3.23806642 0.22256257 0.02153831 0.97468046
+ 23 1786.1532 -781.6832  -25.0002 -775.0000  -25.0000   88.5754 0.22460804 3.17383953 0.22260847 0.00718092 0.97488148
+ 24 1786.1532 -781.6832   25.0002 -775.0000   25.0000   88.5754 0.22460804 3.10934577 0.22260847 -0.00718092 0.97488148
+ 25 1786.8995 -781.6832   75.0061 -775.0000   75.0000   89.3120 0.22550881 3.04511888 0.22256257 -0.02153831 0.97468046
+ 26 1788.3922 -781.6832  125.0283 -775.0000  125.0000   90.7852 0.22729817 2.98167953 0.22247085 -0.03588240 0.97427880
+ 27 1790.6319 -781.6832  175.0775 -775.0000  175.0000   92.9950 0.22995247 2.91951075 0.22233349 -0.05020434 0.97367723
+ 28 1793.6193 -781.6832  225.1647 -775.0000  225.0000   95.9414 0.23343795 2.85903770 0.22215073 -0.06449537 0.97287687
+ 29 1797.3553 -781.6832  275.3006 -775.0000  275.0000   99.6243 0.23771246 2.80061370 0.22192291 -0.07874684 0.97187919
+ 30 1801.8411 -781.6832  325.4960 -775.0000  325.0000  104.0439 0.24272757 2.74451321 0.22165046 -0.09295019 0.97068601
+ 31 1807.0782 -781.6832  375.7616 -775.0000  375.0000  109.2001 0.24843056 2.69093133 0.22133386 -0.10709703 0.96929951
+ 32 1813.0683 -781.6832  426.1081 -775.0000  425.0000  115.0928 0.25476639 2.63998860 0.22097369 -0.12117912 0.96772220
+ 33 1808.5752 -730.4765 -476.5461 -725.0000 -475.0000  110.6732 0.25003217 3.72159542 0.20696987 0.13560095 0.96890446
+ 34 1801.8411 -730.4765 -426.1081 -725.0000 -425.0000  104.0439 0.24272757 3.67180842 0.20735043 0.12155025 0.97068601
+ 35 1795.8606 -730.4765 -375.7616 -725.0000 -375.0000   98.1511 0.23601335 3.61893803 0.20769047 0.10742611 0.97227789
+ 36 1790.6319 -730.4765 -325.4960 -725.0000 -325.0000   92.9950 0.22995247 3.56301185 0.20798939 0.09323662 0.97367723
+ 37 1786.1532 -730.4765 -275.3006 -725.0000 -275.0000   88.5754 0.22460804 3.50413688 0.20824663 0.07899010 0.97488148
+ 38 1782.4232 -730.4765 -225.1647 -725.0000 -225.0000   84.8925 0.22004125 3.44251288 0.20846173 0.06469502 0.97588845
+ 39 1779.4406 -730.4765 -175.0775 -725.0000 -175.0000   81.9461 0.21630908 3.37844141 0.20863429 0.05036000 0.97669627
+ 40 1777.2046 -730.4765 -125.0283 -725.0000 -125.0000   79.7363 0.21346159 3.31232786 0.20876400 0.03599379 0.97730345
+ 41 1775.7142 -730.4765  -75.0061 -725.0000  -75.0000   78.2631 0.21153930 3.24467425 0.20885060 0.02160523 0.97770887
+ 42 1774.9692 -730.4765  -25.0002 -725.0000  -25.0000   77.5265 0.21057077 3.17606175 0.20889394 0.00720324 0.97791177
+ 43 1774.9692 -730.4765   25.0002 -725.0000   25.0000   77.5265 0.21057077 3.10712355 0.20889394 -0.00720324 0.97791177
+ 44 1775.7142 -730.4765   75.0061 -725.0000   75.0000   78.2631 0.21153930 3.03851105 0.20885060 -0.02160523 0.97770887
+ 45 1777.2046 -730.4765  125.0283 -725.0000  125.0000   79.7363 0.21346159 2.97085744 0.20876400 -0.03599379 0.97730345
+ 46 1779.4406 -730.4765  175.0775 -725.0000  175.0000   81.9461 0.21630908 2.90474389 0.20863429 -0.05036000 0.97669627
+ 47 1782.4232 -730.4765  225.1647 -725.0000  225.0000   84.8925 0.22004125 2.84067242 0.20846173 -0.06469502 0.97588845
+ 48 1786.1532 -730.4765  275.3006 -725.0000  275.0000   88.5754 0.22460804 2.77904842 0.20824663 -0.07899010 0.97488148
+ 49 1790.6319 -730.4765  325.4960 -725.0000  325.0000   92.9950 0.22995247 2.72017345 0.20798939 -0.09323662 0.97367723
+ 50 1795.8606 -730.4765  375.7616 -725.0000  375.0000   98.1511 0.23601335 2.66424727 0.20769047 -0.10742611 0.97227789
+ 51 1801.8411 -730.4765  426.1081 -725.0000  425.0000  104.0439 0.24272757 2.61137688 0.20735043 -0.12155025 0.97068601
+ 52 1808.5752 -730.4765  476.5461 -725.0000  475.0000  110.6732 0.25003217 2.56158988 0.20696987 -0.13560095 0.96890446
+ 53 1805.5815 -679.4237 -527.0862 -675.0000 -525.0000  107.7269 0.24681679 3.80263582 0.19285332 0.14999702 0.96969505
+ 54 1798.1027 -679.4237 -476.5461 -675.0000 -475.0000  100.3609 0.23855678 3.75480000 0.19324809 0.13598940 0.97168002
+ 55 1791.3786 -679.4237 -426.1081 -675.0000 -425.0000   93.7316 0.23082950 3.70351421 0.19360546 0.12189974 0.97347695
+ 56 1785.4071 -679.4237 -375.7616 -675.0000 -375.0000   87.8388 0.22370314 3.64869115 0.19392480 0.10773600 0.97508263
+ 57 1780.1862 -679.4237 -325.4960 -675.0000 -325.0000   82.6827 0.21724891 3.59031599 0.19420552 0.09350636 0.97649413
+ 58 1775.7142 -679.4237 -275.3006 -675.0000 -275.0000   78.2631 0.21153930 3.52846836 0.19444711 0.07921919 0.97770887
+ 59 1771.9898 -679.4237 -225.1647 -675.0000 -225.0000   74.5801 0.20664577 3.46334320 0.19464912 0.06488304 0.97872463
+ 60 1769.0117 -679.4237 -175.0775 -675.0000 -175.0000   71.6338 0.20263578 3.39526674 0.19481119 0.05050660 0.97953953
+ 61 1766.7790 -679.4237 -125.0283 -675.0000 -125.0000   69.4240 0.19956941 3.32470346 0.19493301 0.03609870 0.98015203
+ 62 1765.2909 -679.4237  -75.0061 -675.0000  -75.0000   67.9508 0.19749582 3.25224987 0.19501434 0.02166826 0.98056101
+ 63 1764.5469 -679.4237  -25.0002 -675.0000  -25.0000   67.2142 0.19644994 3.17861276 0.19505505 0.00722426 0.98076569
+ 64 1764.5469 -679.4237   25.0002 -675.0000   25.0000   67.2142 0.19644994 3.10457254 0.19505505 -0.00722426 0.98076569
+ 65 1765.2909 -679.4237   75.0061 -675.0000   75.0000   67.9508 0.19749582 3.03093543 0.19501434 -0.02166826 0.98056101
+ 66 1766.7790 -679.4237  125.0283 -675.0000  125.0000   69.4240 0.19956941 2.95848184 0.19493301 -0.03609870 0.98015203
+ 67 1769.0117 -679.4237  175.0775 -675.0000  175.0000   71.6338 0.20263578 2.88791856 0.19481119 -0.05050660 0.97953953
+ 68 1771.9898 -679.4237  225.1647 -675.0000  225.0000   74.5801 0.20664577 2.81984210 0.19464912 -0.06488304 0.97872463
+ 69 1775.7142 -679.4237  275.3006 -675.0000  275.0000   78.2631 0.21153930 2.75471694 0.19444711 -0.07921919 0.97770887
+ 70 1780.1862 -679.4237  325.4960 -675.0000  325.0000   82.6827 0.21724891 2.69286931 0.19420552 -0.09350636 0.97649413
+ 71 1785.4071 -679.4237  375.7616 -675.0000  375.0000   87.8388 0.22370314 2.63449415 0.19392480 -0.10773600 0.97508263
+ 72 1791.3786 -679.4237  426.1081 -675.0000  425.0000   93.7316 0.23082950 2.57967109 0.19360546 -0.12189974 0.97347695
+ 73 1798.1027 -679.4237  476.5461 -675.0000  475.0000  100.3609 0.23855678 2.52838530 0.19324809 -0.13598940 0.97168002
+ 74 1805.5815 -679.4237  527.0862 -675.0000  525.0000  107.7269 0.24681679 2.48054948 0.19285332 -0.14999702 0.96969505
+ 75 1804.0851 -628.5146 -577.7389 -625.0000 -575.0000  106.2537 0.24519062 3.88534823 0.17864081 0.16434955 0.97009107
+ 76 1795.8606 -628.5146 -527.0862 -625.0000 -525.0000   98.1511 0.23601335 3.84025247 0.17904351 0.15039655 0.97227789
+ 77 1788.3922 -628.5146 -476.5461 -625.0000 -475.0000   90.7852 0.22729817 3.79146310 0.17941198 0.13635310 0.97427880
+ 78 1781.6775 -628.5146 -426.1081 -625.0000 -425.0000   84.1559 0.21911494 3.73876930 0.17974555 0.12222697 0.97609021
+ 79 1775.7142 -628.5146 -375.7616 -625.0000 -375.0000   78.2631 0.21153930 3.68201215 0.18004362 0.10802617 0.97770887
+ 80 1770.5006 -628.5146 -325.4960 -625.0000 -325.0000   73.1070 0.20465171 3.62111194 0.18030565 0.09375894 0.97913183
+ 81 1766.0349 -628.5146 -275.3006 -625.0000 -275.0000   68.6874 0.19853561 3.55609952 0.18053117 0.07943371 0.98035646
+ 82 1762.3156 -628.5146 -225.1647 -625.0000 -225.0000   65.0044 0.19327477 3.48714823 0.18071974 0.06505911 0.98138050
+ 83 1759.3417 -628.5146 -175.0775 -625.0000 -175.0000   62.0580 0.18894971 3.41460135 0.18087103 0.05064389 0.98220205
+ 84 1757.1121 -628.5146 -125.0283 -625.0000 -125.0000   59.8483 0.18563326 3.33898821 0.18098475 0.03619695 0.98281957
+ 85 1755.6261 -628.5146  -75.0061 -625.0000  -75.0000   58.3751 0.18338581 3.26102157 0.18106068 0.02172728 0.98323189
+ 86 1754.8832 -628.5146  -25.0002 -625.0000  -25.0000   57.6385 0.18225074 3.18157133 0.18109868 0.00724395 0.98343825
+ 87 1754.8832 -628.5146   25.0002 -625.0000   25.0000   57.6385 0.18225074 3.10161397 0.18109868 -0.00724395 0.98343825
+ 88 1755.6261 -628.5146   75.0061 -625.0000   75.0000   58.3751 0.18338581 3.02216373 0.18106068 -0.02172728 0.98323189
+ 89 1757.1121 -628.5146  125.0283 -625.0000  125.0000   59.8483 0.18563326 2.94419709 0.18098475 -0.03619695 0.98281957
+ 90 1759.3417 -628.5146  175.0775 -625.0000  175.0000   62.0580 0.18894971 2.86858395 0.18087103 -0.05064389 0.98220205
+ 91 1762.3156 -628.5146  225.1647 -625.0000  225.0000   65.0044 0.19327477 2.79603707 0.18071974 -0.06505911 0.98138050
+ 92 1766.0349 -628.5146  275.3006 -625.0000  275.0000   68.6874 0.19853561 2.72708578 0.18053117 -0.07943371 0.98035646
+ 93 1770.5006 -628.5146  325.4960 -625.0000  325.0000   73.1070 0.20465171 2.66207336 0.18030565 -0.09375894 0.97913183
+ 94 1775.7142 -628.5146  375.7616 -625.0000  375.0000   78.2631 0.21153930 2.60117315 0.18004362 -0.10802617 0.97770887
+ 95 1781.6775 -628.5146  426.1081 -625.0000  425.0000   84.1559 0.21911494 2.54441600 0.17974555 -0.12222697 0.97609021
+ 96 1788.3922 -628.5146  476.5461 -625.0000  475.0000   90.7852 0.22729817 2.49172220 0.17941198 -0.13635310 0.97427880
+ 97 1795.8606 -628.5146  527.0862 -625.0000  525.0000   98.1511 0.23601335 2.44293283 0.17904351 -0.15039655 0.97227789
+ 98 1804.0851 -628.5146  577.7389 -625.0000  575.0000  106.2537 0.24519062 2.39783707 0.17864081 -0.16434955 0.97009107
+ 99 1804.0851 -577.7389 -628.5146 -575.0000 -625.0000  106.2537 0.24519062 3.96863339 0.16434955 0.17864081 0.97009107
+100 1795.1134 -577.7389 -577.7389 -575.0000 -575.0000   97.4146 0.23515848 3.92699081 0.16475384 0.16475384 0.97247743
+101 1786.8995 -577.7389 -527.0862 -575.0000 -525.0000   89.3120 0.22550881 3.88156753 0.16512707 0.15076819 0.97468046
+102 1779.4406 -577.7389 -476.5461 -575.0000 -475.0000   81.9461 0.21630908 3.83203910 0.16546858 0.13669143 0.97669627
+103 1772.7345 -577.7389 -426.1081 -575.0000 -425.0000   75.3167 0.20763480 3.77810086 0.16577776 0.12253139 0.97852123
+104 1766.7790 -577.7389 -375.7616 -575.0000 -375.0000   69.4240 0.19956941 3.71949458 0.16605404 0.10829611 0.98015203
+105 1761.5720 -577.7389 -325.4960 -575.0000 -325.0000   64.2678 0.19220353 3.65604396 0.16629693 0.09399392 0.98158569
+106 1757.1121 -577.7389 -275.3006 -575.0000 -275.0000   59.8483 0.18563326 3.58769820 0.16650597 0.07963329 0.98281957
+107 1753.3976 -577.7389 -225.1647 -575.0000 -225.0000   56.1653 0.17995718 3.51458037 0.16668077 0.06522291 0.98385136
+108 1750.4275 -577.7389 -175.0775 -575.0000 -175.0000   53.2189 0.17527207 3.43703348 0.16682101 0.05077161 0.98467913
+109 1748.2008 -577.7389 -125.0283 -575.0000 -125.0000   51.0091 0.17166719 3.35565333 0.16692642 0.03628835 0.98530134
+110 1746.7167 -577.7389  -75.0061 -575.0000  -75.0000   49.5359 0.16921782 3.27129518 0.16699681 0.02178219 0.98571680
+111 1745.9748 -577.7389  -25.0002 -575.0000  -25.0000   48.7994 0.16797869 3.18504354 0.16703203 0.00726226 0.98592472
+112 1745.9748 -577.7389   25.0002 -575.0000   25.0000   48.7994 0.16797869 3.09814176 0.16703203 -0.00726226 0.98592472
+113 1746.7167 -577.7389   75.0061 -575.0000   75.0000   49.5359 0.16921782 3.01189012 0.16699681 -0.02178219 0.98571680
+114 1748.2008 -577.7389  125.0283 -575.0000  125.0000   51.0091 0.17166719 2.92753197 0.16692642 -0.03628835 0.98530134
+115 1750.4275 -577.7389  175.0775 -575.0000  175.0000   53.2189 0.17527207 2.84615182 0.16682101 -0.05077161 0.98467913
+116 1753.3976 -577.7389  225.1647 -575.0000  225.0000   56.1653 0.17995718 2.76860493 0.16668077 -0.06522291 0.98385136
+117 1757.1121 -577.7389  275.3006 -575.0000  275.0000   59.8483 0.18563326 2.69548710 0.16650597 -0.07963329 0.98281957
+118 1761.5720 -577.7389  325.4960 -575.0000  325.0000   64.2678 0.19220353 2.62714134 0.16629693 -0.09399392 0.98158569
+119 1766.7790 -577.7389  375.7616 -575.0000  375.0000   69.4240 0.19956941 2.56369072 0.16605404 -0.10829611 0.98015203
+120 1772.7345 -577.7389  426.1081 -575.0000  425.0000   75.3167 0.20763480 2.50508444 0.16577776 -0.12253139 0.97852123
+121 1779.4406 -577.7389  476.5461 -575.0000  475.0000   81.9461 0.21630908 2.45114620 0.16546858 -0.13669143 0.97669627
+122 1786.8995 -577.7389  527.0862 -575.0000  525.0000   89.3120 0.22550881 2.40161777 0.16512707 -0.15076819 0.97468046
+123 1795.1134 -577.7389  577.7389 -575.0000  575.0000   97.4146 0.23515848 2.35619449 0.16475384 -0.16475384 0.97247743
+124 1804.0851 -577.7389  628.5146 -575.0000  625.0000  106.2537 0.24519062 2.31455191 0.16434955 -0.17864081 0.97009107
+125 1805.5815 -527.0862 -679.4237 -525.0000 -675.0000  107.7269 0.24681679 4.05134580 0.14999702 0.19285332 0.96969505
+126 1795.8606 -527.0862 -628.5146 -525.0000 -625.0000   98.1511 0.23601335 4.01372915 0.15039655 0.17904351 0.97227789
+127 1786.8995 -527.0862 -577.7389 -525.0000 -575.0000   89.3120 0.22550881 3.97241409 0.15076819 0.16512707 0.97468046
+128 1778.6952 -527.0862 -527.0862 -525.0000 -525.0000   81.2095 0.21536462 3.92699081 0.15111129 0.15111129 0.97689854
+129 1771.2452 -527.0862 -476.5461 -525.0000 -475.0000   73.8435 0.20565143 3.87703241 0.15142525 0.13700379 0.97892817
+130 1764.5469 -527.0862 -426.1081 -525.0000 -425.0000   67.2142 0.19644994 3.82211387 0.15170948 0.12281244 0.98076569
+131 1758.5984 -527.0862 -375.7616 -525.0000 -375.0000   61.3214 0.18785135 3.76184213 0.15196349 0.10854535 0.98240776
+132 1753.3976 -527.0862 -325.4960 -525.0000 -325.0000   56.1653 0.17995718 3.69590014 0.15218679 0.09421087 0.98385136
+133 1748.9429 -527.0862 -275.3006 -525.0000 -275.0000   51.7457 0.17287785 3.62410594 0.15237898 0.07981756 0.98509380
+134 1745.2329 -527.0862 -225.1647 -525.0000 -225.0000   48.0628 0.16672965 3.54648443 0.15253969 0.06537415 0.98613278
+135 1742.2663 -527.0862 -175.0775 -525.0000 -175.0000   45.1164 0.16162969 3.46334320 0.15266863 0.05088954 0.98696633
+136 1740.0422 -527.0862 -125.0283 -525.0000 -125.0000   42.9066 0.15768864 3.37533583 0.15276555 0.03637275 0.98759289
+137 1738.5599 -527.0862  -75.0061 -525.0000  -75.0000   41.4334 0.15500180 3.28348970 0.15283026 0.02183289 0.98801125
+138 1737.8188 -527.0862  -25.0002 -525.0000  -25.0000   40.6968 0.15363960 3.18917575 0.15286265 0.00727917 0.98822064
+139 1737.8188 -527.0862   25.0002 -525.0000   25.0000   40.6968 0.15363960 3.09400955 0.15286265 -0.00727917 0.98822064
+140 1738.5599 -527.0862   75.0061 -525.0000   75.0000   41.4334 0.15500180 2.99969560 0.15283026 -0.02183289 0.98801125
+141 1740.0422 -527.0862  125.0283 -525.0000  125.0000   42.9066 0.15768864 2.90784947 0.15276555 -0.03637275 0.98759289
+142 1742.2663 -527.0862  175.0775 -525.0000  175.0000   45.1164 0.16162969 2.81984210 0.15266863 -0.05088954 0.98696633
+143 1745.2329 -527.0862  225.1647 -525.0000  225.0000   48.0628 0.16672965 2.73670087 0.15253969 -0.06537415 0.98613278
+144 1748.9429 -527.0862  275.3006 -525.0000  275.0000   51.7457 0.17287785 2.65907936 0.15237898 -0.07981756 0.98509380
+145 1753.3976 -527.0862  325.4960 -525.0000  325.0000   56.1653 0.17995718 2.58728516 0.15218679 -0.09421087 0.98385136
+146 1758.5984 -527.0862  375.7616 -525.0000  375.0000   61.3214 0.18785135 2.52134317 0.15196349 -0.10854535 0.98240776
+147 1764.5469 -527.0862  426.1081 -525.0000  425.0000   67.2142 0.19644994 2.46107143 0.15170948 -0.12281244 0.98076569
+148 1771.2452 -527.0862  476.5461 -525.0000  475.0000   73.8435 0.20565143 2.40615289 0.15142525 -0.13700379 0.97892817
+149 1778.6952 -527.0862  527.0862 -525.0000  525.0000   81.2095 0.21536462 2.35619449 0.15111129 -0.15111129 0.97689854
+150 1786.8995 -527.0862  577.7389 -525.0000  575.0000   89.3120 0.22550881 2.31077121 0.15076819 -0.16512707 0.97468046
+151 1795.8606 -527.0862  628.5146 -525.0000  625.0000   98.1511 0.23601335 2.26945615 0.15039655 -0.17904351 0.97227789
+152 1805.5815 -527.0862  679.4237 -525.0000  675.0000  107.7269 0.24681679 2.23183950 0.14999702 -0.19285332 0.96969505
+153 1808.5752 -476.5461 -730.4765 -475.0000 -725.0000  110.6732 0.25003217 4.13238620 0.13560095 0.20696987 0.96890446
+154 1798.1027 -476.5461 -679.4237 -475.0000 -675.0000  100.3609 0.23855678 4.09918162 0.13598940 0.19324809 0.97168002
+155 1788.3922 -476.5461 -628.5146 -475.0000 -625.0000   90.7852 0.22729817 4.06251852 0.13635310 0.17941198 0.97427880
+156 1779.4406 -476.5461 -577.7389 -475.0000 -575.0000   81.9461 0.21630908 4.02194252 0.13669143 0.16546858 0.97669627
+157 1771.2452 -476.5461 -527.0862 -475.0000 -525.0000   73.8435 0.20565143 3.97694921 0.13700379 0.15142525 0.97892817
+158 1763.8031 -476.5461 -476.5461 -475.0000 -475.0000   66.4776 0.19539787 3.92699081 0.13728962 0.13728962 0.98097050
+159 1757.1121 -476.5461 -426.1081 -475.0000 -425.0000   59.8483 0.18563326 3.87149230 0.13754841 0.12306963 0.98281957
+160 1751.1699 -476.5461 -375.7616 -475.0000 -375.0000   53.9555 0.17645600 3.80988207 0.13777967 0.10877342 0.98447199
+161 1745.9748 -476.5461 -325.4960 -475.0000 -325.0000   48.7994 0.16797869 3.74164286 0.13798298 0.09440941 0.98592472
+162 1741.5249 -476.5461 -275.3006 -475.0000 -275.0000   44.3798 0.16032751 3.66638842 0.13815797 0.07998619 0.98717505
+163 1737.8188 -476.5461 -225.1647 -475.0000 -225.0000   40.6968 0.15363960 3.58396687 0.13830430 0.06551256 0.98822064
+164 1734.8554 -476.5461 -175.0775 -475.0000 -175.0000   37.7504 0.14805749 3.49458303 0.13842170 0.05099747 0.98905950
+165 1732.6337 -476.5461 -125.0283 -475.0000 -125.0000   35.5407 0.14371998 3.39891636 0.13850995 0.03644999 0.98969005
+166 1731.1530 -476.5461  -75.0061 -475.0000  -75.0000   34.0675 0.14074982 3.29819452 0.13856888 0.02187930 0.99011109
+167 1730.4127 -476.5461  -25.0002 -475.0000  -25.0000   33.3309 0.13923969 3.19417571 0.13859837 0.00729465 0.99032181
+168 1730.4127 -476.5461   25.0002 -475.0000   25.0000   33.3309 0.13923969 3.08900959 0.13859837 -0.00729465 0.99032181
+169 1731.1530 -476.5461   75.0061 -475.0000   75.0000   34.0675 0.14074982 2.98499078 0.13856888 -0.02187930 0.99011109
+170 1732.6337 -476.5461  125.0283 -475.0000  125.0000   35.5407 0.14371998 2.88426894 0.13850995 -0.03644999 0.98969005
+171 1734.8554 -476.5461  175.0775 -475.0000  175.0000   37.7504 0.14805749 2.78860227 0.13842170 -0.05099747 0.98905950
+172 1737.8188 -476.5461  225.1647 -475.0000  225.0000   40.6968 0.15363960 2.69921843 0.13830430 -0.06551256 0.98822064
+173 1741.5249 -476.5461  275.3006 -475.0000  275.0000   44.3798 0.16032751 2.61679688 0.13815797 -0.07998619 0.98717505
+174 1745.9748 -476.5461  325.4960 -475.0000  325.0000   48.7994 0.16797869 2.54154244 0.13798298 -0.09440941 0.98592472
+175 1751.1699 -476.5461  375.7616 -475.0000  375.0000   53.9555 0.17645600 2.47330323 0.13777967 -0.10877342 0.98447199
+176 1757.1121 -476.5461  426.1081 -475.0000  425.0000   59.8483 0.18563326 2.41169300 0.13754841 -0.12306963 0.98281957
+177 1763.8031 -476.5461  476.5461 -475.0000  475.0000   66.4776 0.19539787 2.35619449 0.13728962 -0.13728962 0.98097050
+178 1771.2452 -476.5461  527.0862 -475.0000  525.0000   73.8435 0.20565143 2.30623609 0.13700379 -0.15142525 0.97892817
+179 1779.4406 -476.5461  577.7389 -475.0000  575.0000   81.9461 0.21630908 2.26124278 0.13669143 -0.16546858 0.97669627
+180 1788.3922 -476.5461  628.5146 -475.0000  625.0000   90.7852 0.22729817 2.22066678 0.13635310 -0.17941198 0.97427880
+181 1798.1027 -476.5461  679.4237 -475.0000  675.0000  100.3609 0.23855678 2.18400368 0.13598940 -0.19324809 0.97168002
+182 1808.5752 -476.5461  730.4765 -475.0000  725.0000  110.6732 0.25003217 2.15079910 0.13560095 -0.20696987 0.96890446
+183 1813.0683 -426.1081 -781.6832 -425.0000 -775.0000  115.0928 0.25476639 4.21078492 0.12117912 0.22097369 0.96772220
+184 1801.8411 -426.1081 -730.4765 -425.0000 -725.0000  104.0439 0.24272757 4.18217320 0.12155025 0.20735043 0.97068601
+185 1791.3786 -426.1081 -679.4237 -425.0000 -675.0000   93.7316 0.23082950 4.15046741 0.12189974 0.19360546 0.97347695
+186 1781.6775 -426.1081 -628.5146 -425.0000 -625.0000   84.1559 0.21911494 4.11521232 0.12222697 0.17974555 0.97609021
+187 1772.7345 -426.1081 -577.7389 -425.0000 -575.0000   75.3167 0.20763480 4.07588076 0.12253139 0.16577776 0.97852123
+188 1764.5469 -426.1081 -527.0862 -425.0000 -525.0000   67.2142 0.19644994 4.03186775 0.12281244 0.15170948 0.98076569
+189 1757.1121 -426.1081 -476.5461 -425.0000 -475.0000   59.8483 0.18563326 3.98248932 0.12306963 0.13754841 0.98281957
+190 1750.4275 -426.1081 -426.1081 -425.0000 -425.0000   53.2189 0.17527207 3.92699081 0.12330248 0.12330248 0.98467913
+191 1744.4911 -426.1081 -375.7616 -425.0000 -375.0000   47.3262 0.16547046 3.86457200 0.12351058 0.10897992 0.98634097
+192 1739.3010 -426.1081 -325.4960 -425.0000 -325.0000   42.1700 0.15635137 3.79443928 0.12369353 0.09458917 0.98780200
+193 1734.8554 -426.1081 -275.3006 -425.0000 -275.0000   37.7504 0.14805749 3.71589748 0.12385100 0.08013888 0.98905950
+194 1731.1530 -426.1081 -225.1647 -425.0000 -225.0000   34.0675 0.14074982 3.62849188 0.12398268 0.06563789 0.99011109
+195 1728.1924 -426.1081 -175.0775 -425.0000 -175.0000   31.1211 0.13460232 3.53219969 0.12408833 0.05109519 0.99095478
+196 1725.9729 -426.1081 -125.0283 -425.0000 -125.0000   28.9113 0.12979104 3.42764409 0.12416774 0.03651992 0.99158896
+197 1724.4936 -426.1081  -75.0061 -425.0000  -75.0000   27.4381 0.12647710 3.31626485 0.12422077 0.02192131 0.99201243
+198 1723.7540 -426.1081  -25.0002 -425.0000  -25.0000   26.7015 0.12478568 3.20034847 0.12424731 0.00730867 0.99222436
+199 1723.7540 -426.1081   25.0002 -425.0000   25.0000   26.7015 0.12478568 3.08283683 0.12424731 -0.00730867 0.99222436
+200 1724.4936 -426.1081   75.0061 -425.0000   75.0000   27.4381 0.12647710 2.96692045 0.12422077 -0.02192131 0.99201243
+201 1725.9729 -426.1081  125.0283 -425.0000  125.0000   28.9113 0.12979104 2.85554121 0.12416774 -0.03651992 0.99158896
+202 1728.1924 -426.1081  175.0775 -425.0000  175.0000   31.1211 0.13460232 2.75098561 0.12408833 -0.05109519 0.99095478
+203 1731.1530 -426.1081  225.1647 -425.0000  225.0000   34.0675 0.14074982 2.65469342 0.12398268 -0.06563789 0.99011109
+204 1734.8554 -426.1081  275.3006 -425.0000  275.0000   37.7504 0.14805749 2.56728782 0.12385100 -0.08013888 0.98905950
+205 1739.3010 -426.1081  325.4960 -425.0000  325.0000   42.1700 0.15635137 2.48874602 0.12369353 -0.09458917 0.98780200
+206 1744.4911 -426.1081  375.7616 -425.0000  375.0000   47.3262 0.16547046 2.41861330 0.12351058 -0.10897992 0.98634097
+207 1750.4275 -426.1081  426.1081 -425.0000  425.0000   53.2189 0.17527207 2.35619449 0.12330248 -0.12330248 0.98467913
+208 1757.1121 -426.1081  476.5461 -425.0000  475.0000   59.8483 0.18563326 2.30069598 0.12306963 -0.13754841 0.98281957
+209 1764.5469 -426.1081  527.0862 -425.0000  525.0000   67.2142 0.19644994 2.25131755 0.12281244 -0.15170948 0.98076569
+210 1772.7345 -426.1081  577.7389 -425.0000  575.0000   75.3167 0.20763480 2.20730454 0.12253139 -0.16577776 0.97852123
+211 1781.6775 -426.1081  628.5146 -425.0000  625.0000   84.1559 0.21911494 2.16797298 0.12222697 -0.17974555 0.97609021
+212 1791.3786 -426.1081  679.4237 -425.0000  675.0000   93.7316 0.23082950 2.13271789 0.12189974 -0.19360546 0.97347695
+213 1801.8411 -426.1081  730.4765 -425.0000  725.0000  104.0439 0.24272757 2.10101210 0.12155025 -0.20735043 0.97068601
+214 1813.0683 -426.1081  781.6832 -425.0000  775.0000  115.0928 0.25476639 2.07240038 0.12117912 -0.22097369 0.96772220
+215 1819.0634 -375.7616 -833.0538 -375.0000 -825.0000  120.9856 0.26092194 4.28576148 0.10674932 0.23484851 0.96615255
+216 1807.0782 -375.7616 -781.6832 -375.0000 -775.0000  109.2001 0.24843056 4.26172765 0.10709703 0.22133386 0.96929951
+217 1795.8606 -375.7616 -730.4765 -375.0000 -725.0000   98.1511 0.23601335 4.23504359 0.10742611 0.20769047 0.97227789
+218 1785.4071 -375.7616 -679.4237 -375.0000 -675.0000   87.8388 0.22370314 4.20529047 0.10773600 0.19392480 0.97508263
+219 1775.7142 -375.7616 -628.5146 -375.0000 -625.0000   78.2631 0.21153930 4.17196947 0.10802617 0.18004362 0.97770887
+220 1766.7790 -375.7616 -577.7389 -375.0000 -575.0000   69.4240 0.19956941 4.13448704 0.10829611 0.16605404 0.98015203
+221 1758.5984 -375.7616 -527.0862 -375.0000 -525.0000   61.3214 0.18785135 4.09213949 0.10854535 0.15196349 0.98240776
+222 1751.1699 -375.7616 -476.5461 -375.0000 -475.0000   53.9555 0.17645600 4.04409955 0.10877342 0.13777967 0.98447199
+223 1744.4911 -375.7616 -426.1081 -375.0000 -425.0000   47.3262 0.16547046 3.98940962 0.10897992 0.12351058 0.98634097
+224 1738.5599 -375.7616 -375.7616 -375.0000 -375.0000   41.4334 0.15500180 3.92699081 0.10916447 0.10916447 0.98801125
+225 1733.3742 -375.7616 -325.4960 -375.0000 -325.0000   36.2773 0.14518104 3.85568335 0.10932672 0.09474983 0.98947973
+226 1728.9324 -375.7616 -275.3006 -375.0000 -275.0000   31.8577 0.13616654 3.77434148 0.10946637 0.08027534 0.99074365
+227 1725.2332 -375.7616 -225.1647 -375.0000 -225.0000   28.1747 0.12814525 3.68201215 0.10958316 0.06574989 0.99180063
+228 1722.2752 -375.7616 -175.0775 -375.0000 -175.0000   25.2283 0.12132912 3.57821981 0.10967685 0.05118253 0.99264865
+229 1720.0576 -375.7616 -125.0283 -375.0000 -125.0000   23.0186 0.11594339 3.46334320 0.10974728 0.03658243 0.99328609
+230 1718.5796 -375.7616  -75.0061 -375.0000  -75.0000   21.5454 0.11220396 3.33898821 0.10979431 0.02195886 0.99371174
+231 1717.8407 -375.7616  -25.0002 -375.0000  -25.0000   20.8088 0.11028505 3.20816081 0.10981785 0.00732119 0.99392477
+232 1717.8407 -375.7616   25.0002 -375.0000   25.0000   20.8088 0.11028505 3.07502449 0.10981785 -0.00732119 0.99392477
+233 1718.5796 -375.7616   75.0061 -375.0000   75.0000   21.5454 0.11220396 2.94419709 0.10979431 -0.02195886 0.99371174
+234 1720.0576 -375.7616  125.0283 -375.0000  125.0000   23.0186 0.11594339 2.81984210 0.10974728 -0.03658243 0.99328609
+235 1722.2752 -375.7616  175.0775 -375.0000  175.0000   25.2283 0.12132912 2.70496549 0.10967685 -0.05118253 0.99264865
+236 1725.2332 -375.7616  225.1647 -375.0000  225.0000   28.1747 0.12814525 2.60117315 0.10958316 -0.06574989 0.99180063
+237 1728.9324 -375.7616  275.3006 -375.0000  275.0000   31.8577 0.13616654 2.50884382 0.10946637 -0.08027534 0.99074365
+238 1733.3742 -375.7616  325.4960 -375.0000  325.0000   36.2773 0.14518104 2.42750195 0.10932672 -0.09474983 0.98947973
+239 1738.5599 -375.7616  375.7616 -375.0000  375.0000   41.4334 0.15500180 2.35619449 0.10916447 -0.10916447 0.98801125
+240 1744.4911 -375.7616  426.1081 -375.0000  425.0000   47.3262 0.16547046 2.29377568 0.10897992 -0.12351058 0.98634097
+241 1751.1699 -375.7616  476.5461 -375.0000  475.0000   53.9555 0.17645600 2.23908575 0.10877342 -0.13777967 0.98447199
+242 1758.5984 -375.7616  527.0862 -375.0000  525.0000   61.3214 0.18785135 2.19104581 0.10854535 -0.15196349 0.98240776
+243 1766.7790 -375.7616  577.7389 -375.0000  575.0000   69.4240 0.19956941 2.14869826 0.10829611 -0.16605404 0.98015203
+244 1775.7142 -375.7616  628.5146 -375.0000  625.0000   78.2631 0.21153930 2.11121583 0.10802617 -0.18004362 0.97770887
+245 1785.4071 -375.7616  679.4237 -375.0000  675.0000   87.8388 0.22370314 2.07789483 0.10773600 -0.19392480 0.97508263
+246 1795.8606 -375.7616  730.4765 -375.0000  725.0000   98.1511 0.23601335 2.04814171 0.10742611 -0.20769047 0.97227789
+247 1807.0782 -375.7616  781.6832 -375.0000  775.0000  109.2001 0.24843056 2.02145765 0.10709703 -0.22133386 0.96929951
+248 1819.0634 -375.7616  833.0538 -375.0000  825.0000  120.9856 0.26092194 1.99742382 0.10674932 -0.23484851 0.96615255
+249 1813.8174 -325.4960 -833.0538 -325.0000 -825.0000  115.8294 0.25554542 4.33711815 0.09264756 0.23518226 0.96752557
+250 1801.8411 -325.4960 -781.6832 -325.0000 -775.0000  104.0439 0.24272757 4.31530953 0.09295019 0.22165046 0.97068601
+251 1790.6319 -325.4960 -730.4765 -325.0000 -725.0000   92.9950 0.22995247 4.29096977 0.09323662 0.20798939 0.97367723
+252 1780.1862 -325.4960 -679.4237 -325.0000 -675.0000   82.6827 0.21724891 4.26366563 0.09350636 0.19420552 0.97649413
+253 1770.5006 -325.4960 -628.5146 -325.0000 -625.0000   73.1070 0.20465171 4.23286968 0.09375894 0.18030565 0.97913183
+254 1761.5720 -325.4960 -577.7389 -325.0000 -575.0000   64.2678 0.19220353 4.19793766 0.09399392 0.16629693 0.98158569
+255 1753.3976 -325.4960 -527.0862 -325.0000 -525.0000   56.1653 0.17995718 4.15808148 0.09421087 0.15218679 0.98385136
+256 1745.9748 -325.4960 -476.5461 -325.0000 -475.0000   48.7994 0.16797869 4.11233876 0.09440941 0.13798298 0.98592472
+257 1739.3010 -325.4960 -426.1081 -325.0000 -425.0000   42.1700 0.15635137 4.05954234 0.09458917 0.12369353 0.98780200
+258 1733.3742 -325.4960 -375.7616 -325.0000 -375.0000   36.2773 0.14518104 3.99829827 0.09474983 0.10932672 0.98947973
+259 1728.1924 -325.4960 -325.4960 -325.0000 -325.0000   31.1211 0.13460232 3.92699081 0.09489107 0.09489107 0.99095478
+260 1723.7540 -325.4960 -275.3006 -325.0000 -275.0000   26.7015 0.12478568 3.84384958 0.09501265 0.08039532 0.99222436
+261 1720.0576 -325.4960 -225.1647 -325.0000 -225.0000   23.0186 0.11594339 3.74713731 0.09511431 0.06584837 0.99328609
+262 1717.1019 -325.4960 -175.0775 -325.0000 -175.0000   20.0722 0.10833102 3.63553402 0.09519588 0.05125932 0.99413793
+263 1714.8859 -325.4960 -125.0283 -325.0000 -125.0000   17.8624 0.10223796 3.50876648 0.09525720 0.03663738 0.99477825
+264 1713.4090 -325.4960  -75.0061 -325.0000  -75.0000   16.3892 0.09795935 3.36839149 0.09529814 0.02199188 0.99520582
+265 1712.6707 -325.4960  -25.0002 -325.0000  -25.0000   15.6526 0.09574645 3.21836454 0.09531863 0.00733220 0.99541981
+266 1712.6707 -325.4960   25.0002 -325.0000   25.0000   15.6526 0.09574645 3.06482076 0.09531863 -0.00733220 0.99541981
+267 1713.4090 -325.4960   75.0061 -325.0000   75.0000   16.3892 0.09795935 2.91479381 0.09529814 -0.02199188 0.99520582
+268 1714.8859 -325.4960  125.0283 -325.0000  125.0000   17.8624 0.10223796 2.77441882 0.09525720 -0.03663738 0.99477825
+269 1717.1019 -325.4960  175.0775 -325.0000  175.0000   20.0722 0.10833102 2.64765128 0.09519588 -0.05125932 0.99413793
+270 1720.0576 -325.4960  225.1647 -325.0000  225.0000   23.0186 0.11594339 2.53604799 0.09511431 -0.06584837 0.99328609
+271 1723.7540 -325.4960  275.3006 -325.0000  275.0000   26.7015 0.12478568 2.43933572 0.09501265 -0.08039532 0.99222436
+272 1728.1924 -325.4960  325.4960 -325.0000  325.0000   31.1211 0.13460232 2.35619449 0.09489107 -0.09489107 0.99095478
+273 1733.3742 -325.4960  375.7616 -325.0000  375.0000   36.2773 0.14518104 2.28488703 0.09474983 -0.10932672 0.98947973
+274 1739.3010 -325.4960  426.1081 -325.0000  425.0000   42.1700 0.15635137 2.22364296 0.09458917 -0.12369353 0.98780200
+275 1745.9748 -325.4960  476.5461 -325.0000  475.0000   48.7994 0.16797869 2.17084654 0.09440941 -0.13798298 0.98592472
+276 1753.3976 -325.4960  527.0862 -325.0000  525.0000   56.1653 0.17995718 2.12510382 0.09421087 -0.15218679 0.98385136
+277 1761.5720 -325.4960  577.7389 -325.0000  575.0000   64.2678 0.19220353 2.08524764 0.09399392 -0.16629693 0.98158569
+278 1770.5006 -325.4960  628.5146 -325.0000  625.0000   73.1070 0.20465171 2.05031562 0.09375894 -0.18030565 0.97913183
+279 1780.1862 -325.4960  679.4237 -325.0000  675.0000   82.6827 0.21724891 2.01951967 0.09350636 -0.19420552 0.97649413
+280 1790.6319 -325.4960  730.4765 -325.0000  725.0000   92.9950 0.22995247 1.99221553 0.09323662 -0.20798939 0.97367723
+281 1801.8411 -325.4960  781.6832 -325.0000  775.0000  104.0439 0.24272757 1.96787577 0.09295019 -0.22165046 0.97068601
+282 1813.8174 -325.4960  833.0538 -325.0000  825.0000  115.8294 0.25554542 1.94606715 0.09264756 -0.23518226 0.96752557
+283 1809.3239 -275.3006 -833.0538 -275.0000 -825.0000  111.4098 0.25082849 4.39063842 0.07848982 0.23546947 0.96870712
+284 1797.3553 -275.3006 -781.6832 -275.0000 -775.0000   99.6243 0.23771246 4.37141002 0.07874684 0.22192291 0.97187919
+285 1786.1532 -275.3006 -730.4765 -275.0000 -725.0000   88.5754 0.22460804 4.34984474 0.07899010 0.20824663 0.97488148
+286 1775.7142 -275.3006 -679.4237 -275.0000 -675.0000   78.2631 0.21153930 4.32551326 0.07921919 0.19444711 0.97770887
+287 1766.0349 -275.3006 -628.5146 -275.0000 -625.0000   68.6874 0.19853561 4.29788210 0.07943371 0.18053117 0.98035646
+288 1757.1121 -275.3006 -577.7389 -275.0000 -575.0000   59.8483 0.18563326 4.26628342 0.07963329 0.16650597 0.98281957
+289 1748.9429 -275.3006 -527.0862 -275.0000 -525.0000   51.7457 0.17287785 4.22987568 0.07981756 0.15237898 0.98509380
+290 1741.5249 -275.3006 -476.5461 -275.0000 -475.0000   44.3798 0.16032751 4.18759320 0.07998619 0.13815797 0.98717505
+291 1734.8554 -275.3006 -426.1081 -275.0000 -425.0000   37.7504 0.14805749 4.13808414 0.08013888 0.12385100 0.98905950
+292 1728.9324 -275.3006 -375.7616 -275.0000 -375.0000   31.8577 0.13616654 4.07964014 0.08027534 0.10946637 0.99074365
+293 1723.7540 -275.3006 -325.4960 -275.0000 -325.0000   26.7015 0.12478568 4.01013204 0.08039532 0.09501265 0.99222436
+294 1719.3185 -275.3006 -275.3006 -275.0000 -275.0000   22.2820 0.11408953 3.92699081 0.08049858 0.08049858 0.99349885
+295 1715.6245 -275.3006 -225.1647 -275.0000 -225.0000   18.5990 0.10430971 3.82732216 0.08058494 0.06593313 0.99456467
+296 1712.6707 -275.3006 -175.0775 -275.0000 -175.0000   15.6526 0.09574645 3.70832186 0.08065423 0.05132542 0.99541981
+297 1710.4562 -275.3006 -125.0283 -275.0000 -125.0000   13.4428 0.08876909 3.56822014 0.08070631 0.03668469 0.99606261
+298 1708.9802 -275.3006  -75.0061 -275.0000  -75.0000   11.9697 0.08378801 3.40784470 0.08074109 0.02202030 0.99649184
+299 1708.2424 -275.3006  -25.0002 -275.0000  -25.0000   11.2331 0.08118066 3.23225253 0.08075849 0.00734168 0.99670666
+300 1708.2424 -275.3006   25.0002 -275.0000   25.0000   11.2331 0.08118066 3.05093277 0.08075849 -0.00734168 0.99670666
+301 1708.9802 -275.3006   75.0061 -275.0000   75.0000   11.9697 0.08378801 2.87534060 0.08074109 -0.02202030 0.99649184
+302 1710.4562 -275.3006  125.0283 -275.0000  125.0000   13.4428 0.08876909 2.71496516 0.08070631 -0.03668469 0.99606261
+303 1712.6707 -275.3006  175.0775 -275.0000  175.0000   15.6526 0.09574645 2.57486344 0.08065423 -0.05132542 0.99541981
+304 1715.6245 -275.3006  225.1647 -275.0000  225.0000   18.5990 0.10430971 2.45586314 0.08058494 -0.06593313 0.99456467
+305 1719.3185 -275.3006  275.3006 -275.0000  275.0000   22.2820 0.11408953 2.35619449 0.08049858 -0.08049858 0.99349885
+306 1723.7540 -275.3006  325.4960 -275.0000  325.0000   26.7015 0.12478568 2.27305326 0.08039532 -0.09501265 0.99222436
+307 1728.9324 -275.3006  375.7616 -275.0000  375.0000   31.8577 0.13616654 2.20354516 0.08027534 -0.10946637 0.99074365
+308 1734.8554 -275.3006  426.1081 -275.0000  425.0000   37.7504 0.14805749 2.14510116 0.08013888 -0.12385100 0.98905950
+309 1741.5249 -275.3006  476.5461 -275.0000  475.0000   44.3798 0.16032751 2.09559210 0.07998619 -0.13815797 0.98717505
+310 1748.9429 -275.3006  527.0862 -275.0000  525.0000   51.7457 0.17287785 2.05330962 0.07981756 -0.15237898 0.98509380
+311 1757.1121 -275.3006  577.7389 -275.0000  575.0000   59.8483 0.18563326 2.01690188 0.07963329 -0.16650597 0.98281957
+312 1766.0349 -275.3006  628.5146 -275.0000  625.0000   68.6874 0.19853561 1.98530320 0.07943371 -0.18053117 0.98035646
+313 1775.7142 -275.3006  679.4237 -275.0000  675.0000   78.2631 0.21153930 1.95767204 0.07921919 -0.19444711 0.97770887
+314 1786.1532 -275.3006  730.4765 -275.0000  725.0000   88.5754 0.22460804 1.93334056 0.07899010 -0.20824663 0.97488148
+315 1797.3553 -275.3006  781.6832 -275.0000  775.0000   99.6243 0.23771246 1.91177528 0.07874684 -0.22192291 0.97187919
+316 1809.3239 -275.3006  833.0538 -275.0000  825.0000  111.4098 0.25082849 1.89254688 0.07848982 -0.23546947 0.96870712
+317 1805.5815 -225.1647 -833.0538 -225.0000 -825.0000  107.7269 0.24681679 4.44613692 0.06428444 0.23570961 0.96969505
+318 1793.6193 -225.1647 -781.6832 -225.0000 -775.0000   95.9414 0.23343795 4.42983402 0.06449537 0.22215073 0.97287687
+319 1782.4232 -225.1647 -730.4765 -225.0000 -725.0000   84.8925 0.22004125 4.41146874 0.06469502 0.20846173 0.97588845
+320 1771.9898 -225.1647 -679.4237 -225.0000 -675.0000   74.5801 0.20664577 4.39063842 0.06488304 0.19464912 0.97872463
+321 1762.3156 -225.1647 -628.5146 -225.0000 -625.0000   65.0044 0.19327477 4.36683339 0.06505911 0.18071974 0.98138050
+322 1753.3976 -225.1647 -577.7389 -225.0000 -575.0000   56.1653 0.17995718 4.33940125 0.06522291 0.16668077 0.98385136
+323 1745.2329 -225.1647 -527.0862 -225.0000 -525.0000   48.0628 0.16672965 4.30749719 0.06537415 0.15253969 0.98613278
+324 1737.8188 -225.1647 -476.5461 -225.0000 -475.0000   40.6968 0.15363960 4.27001475 0.06551256 0.13830430 0.98822064
+325 1731.1530 -225.1647 -426.1081 -225.0000 -425.0000   34.0675 0.14074982 4.22548974 0.06563789 0.12398268 0.99011109
+326 1725.2332 -225.1647 -375.7616 -225.0000 -375.0000   28.1747 0.12814525 4.17196947 0.06574989 0.10958316 0.99180063
+327 1720.0576 -225.1647 -325.4960 -225.0000 -325.0000   23.0186 0.11594339 4.10684431 0.06584837 0.09511431 0.99328609
+328 1715.6245 -225.1647 -275.3006 -225.0000 -275.0000   18.5990 0.10430971 4.02665946 0.06593313 0.08058494 0.99456467
+329 1711.9324 -225.1647 -225.1647 -225.0000 -225.0000   14.9160 0.09347986 3.92699081 0.06600402 0.06600402 0.99563394
+330 1708.9802 -225.1647 -175.0775 -225.0000 -175.0000   11.9697 0.08378801 3.80263582 0.06606089 0.05138069 0.99649184
+331 1706.7669 -225.1647 -125.0283 -225.0000 -125.0000    9.7599 0.07569211 3.64869115 0.06610364 0.03672425 0.99713672
+332 1705.2917 -225.1647  -75.0061 -225.0000  -75.0000    8.2867 0.06976603 3.46334320 0.06613219 0.02204406 0.99756734
+333 1704.5543 -225.1647  -25.0002 -225.0000  -25.0000    7.5501 0.06660277 3.25224987 0.06614648 0.00734961 0.99778286
+334 1704.5543 -225.1647   25.0002 -225.0000   25.0000    7.5501 0.06660277 3.03093543 0.06614648 -0.00734961 0.99778286
+335 1705.2917 -225.1647   75.0061 -225.0000   75.0000    8.2867 0.06976603 2.81984210 0.06613219 -0.02204406 0.99756734
+336 1706.7669 -225.1647  125.0283 -225.0000  125.0000    9.7599 0.07569211 2.63449415 0.06610364 -0.03672425 0.99713672
+337 1708.9802 -225.1647  175.0775 -225.0000  175.0000   11.9697 0.08378801 2.48054948 0.06606089 -0.05138069 0.99649184
+338 1711.9324 -225.1647  225.1647 -225.0000  225.0000   14.9160 0.09347986 2.35619449 0.06600402 -0.06600402 0.99563394
+339 1715.6245 -225.1647  275.3006 -225.0000  275.0000   18.5990 0.10430971 2.25652584 0.06593313 -0.08058494 0.99456467
+340 1720.0576 -225.1647  325.4960 -225.0000  325.0000   23.0186 0.11594339 2.17634099 0.06584837 -0.09511431 0.99328609
+341 1725.2332 -225.1647  375.7616 -225.0000  375.0000   28.1747 0.12814525 2.11121583 0.06574989 -0.10958316 0.99180063
+342 1731.1530 -225.1647  426.1081 -225.0000  425.0000   34.0675 0.14074982 2.05769556 0.06563789 -0.12398268 0.99011109
+343 1737.8188 -225.1647  476.5461 -225.0000  475.0000   40.6968 0.15363960 2.01317055 0.06551256 -0.13830430 0.98822064
+344 1745.2329 -225.1647  527.0862 -225.0000  525.0000   48.0628 0.16672965 1.97568811 0.06537415 -0.15253969 0.98613278
+345 1753.3976 -225.1647  577.7389 -225.0000  575.0000   56.1653 0.17995718 1.94378405 0.06522291 -0.16668077 0.98385136
+346 1762.3156 -225.1647  628.5146 -225.0000  625.0000   65.0044 0.19327477 1.91635191 0.06505911 -0.18071974 0.98138050
+347 1771.9898 -225.1647  679.4237 -225.0000  675.0000   74.5801 0.20664577 1.89254688 0.06488304 -0.19464912 0.97872463
+348 1782.4232 -225.1647  730.4765 -225.0000  725.0000   84.8925 0.22004125 1.87171656 0.06469502 -0.20846173 0.97588845
+349 1793.6193 -225.1647  781.6832 -225.0000  775.0000   95.9414 0.23343795 1.85335128 0.06449537 -0.22215073 0.97287687
+350 1805.5815 -225.1647  833.0538 -225.0000  825.0000  107.7269 0.24681679 1.83704838 0.06428444 -0.23570961 0.96969505
+351 1802.5890 -175.0775 -833.0538 -175.0000 -825.0000  104.7805 0.24355180 4.50336603 0.05003987 0.23590225 0.97048758
+352 1790.6319 -175.0775 -781.6832 -175.0000 -775.0000   92.9950 0.22995247 4.49030707 0.05020434 0.22233349 0.97367723
+353 1779.4406 -175.0775 -730.4765 -175.0000 -725.0000   81.9461 0.21630908 4.47554021 0.05036000 0.20863429 0.97669627
+354 1769.0117 -175.0775 -679.4237 -175.0000 -675.0000   71.6338 0.20263578 4.45871488 0.05050660 0.19481119 0.97953953
+355 1759.3417 -175.0775 -628.5146 -175.0000 -625.0000   62.0580 0.18894971 4.43938027 0.05064389 0.18087103 0.98220205
+356 1750.4275 -175.0775 -577.7389 -175.0000 -575.0000   53.2189 0.17527207 4.41694814 0.05077161 0.16682101 0.98467913
+357 1742.2663 -175.0775 -527.0862 -175.0000 -525.0000   45.1164 0.16162969 4.39063842 0.05088954 0.15266863 0.98696633
+358 1734.8554 -175.0775 -476.5461 -175.0000 -475.0000   37.7504 0.14805749 4.35939859 0.05099747 0.13842170 0.98905950
+359 1728.1924 -175.0775 -426.1081 -175.0000 -425.0000   31.1211 0.13460232 4.32178193 0.05109519 0.12408833 0.99095478
+360 1722.2752 -175.0775 -375.7616 -175.0000 -375.0000   25.2283 0.12132912 4.27576181 0.05118253 0.10967685 0.99264865
+361 1717.1019 -175.0775 -325.4960 -175.0000 -325.0000   20.0722 0.10833102 4.21844760 0.05125932 0.09519588 0.99413793
+362 1712.6707 -175.0775 -275.3006 -175.0000 -275.0000   15.6526 0.09574645 4.14565976 0.05132542 0.08065423 0.99541981
+363 1708.9802 -175.0775 -225.1647 -175.0000 -225.0000   11.9697 0.08378801 4.05134580 0.05138069 0.06606089 0.99649184
+364 1706.0293 -175.0775 -175.0775 -175.0000 -175.0000    9.0233 0.07279025 3.92699081 0.05142504 0.05142504 0.99735196
+365 1703.8169 -175.0775 -125.0283 -175.0000 -125.0000    6.8135 0.06327961 3.76184213 0.05145838 0.03675599 0.99799851
+366 1702.3424 -175.0775  -75.0061 -175.0000  -75.0000    5.3403 0.05603859 3.54648443 0.05148064 0.02206313 0.99843025
+367 1701.6053 -175.0775  -25.0002 -175.0000  -25.0000    4.6037 0.05203804 3.28348970 0.05149178 0.00735597 0.99864633
+368 1701.6053 -175.0775   25.0002 -175.0000   25.0000    4.6037 0.05203804 2.99969560 0.05149178 -0.00735597 0.99864633
+369 1702.3424 -175.0775   75.0061 -175.0000   75.0000    5.3403 0.05603859 2.73670087 0.05148064 -0.02206313 0.99843025
+370 1703.8169 -175.0775  125.0283 -175.0000  125.0000    6.8135 0.06327961 2.52134317 0.05145838 -0.03675599 0.99799851
+371 1706.0293 -175.0775  175.0775 -175.0000  175.0000    9.0233 0.07279025 2.35619449 0.05142504 -0.05142504 0.99735196
+372 1708.9802 -175.0775  225.1647 -175.0000  225.0000   11.9697 0.08378801 2.23183950 0.05138069 -0.06606089 0.99649184
+373 1712.6707 -175.0775  275.3006 -175.0000  275.0000   15.6526 0.09574645 2.13752554 0.05132542 -0.08065423 0.99541981
+374 1717.1019 -175.0775  325.4960 -175.0000  325.0000   20.0722 0.10833102 2.06473770 0.05125932 -0.09519588 0.99413793
+375 1722.2752 -175.0775  375.7616 -175.0000  375.0000   25.2283 0.12132912 2.00742349 0.05118253 -0.10967685 0.99264865
+376 1728.1924 -175.0775  426.1081 -175.0000  425.0000   31.1211 0.13460232 1.96140337 0.05109519 -0.12408833 0.99095478
+377 1734.8554 -175.0775  476.5461 -175.0000  475.0000   37.7504 0.14805749 1.92378671 0.05099747 -0.13842170 0.98905950
+378 1742.2663 -175.0775  527.0862 -175.0000  525.0000   45.1164 0.16162969 1.89254688 0.05088954 -0.15266863 0.98696633
+379 1750.4275 -175.0775  577.7389 -175.0000  575.0000   53.2189 0.17527207 1.86623716 0.05077161 -0.16682101 0.98467913
+380 1759.3417 -175.0775  628.5146 -175.0000  625.0000   62.0580 0.18894971 1.84380503 0.05064389 -0.18087103 0.98220205
+381 1769.0117 -175.0775  679.4237 -175.0000  675.0000   71.6338 0.20263578 1.82447042 0.05050660 -0.19481119 0.97953953
+382 1779.4406 -175.0775  730.4765 -175.0000  725.0000   81.9461 0.21630908 1.80764509 0.05036000 -0.20863429 0.97669627
+383 1790.6319 -175.0775  781.6832 -175.0000  775.0000   92.9950 0.22995247 1.79287823 0.05020434 -0.22233349 0.97367723
+384 1802.5890 -175.0775  833.0538 -175.0000  825.0000  104.7805 0.24355180 1.77981927 0.05003987 -0.23590225 0.97048758
+385 1800.3455 -125.0283 -833.0538 -125.0000 -825.0000  102.5707 0.24106928 4.56201755 0.03576470 0.23604705 0.97108325
+386 1788.3922 -125.0283 -781.6832 -125.0000 -775.0000   90.7852 0.22729817 4.55247585 0.03588240 0.22247085 0.97427880
+387 1777.2046 -125.0283 -730.4765 -125.0000 -725.0000   79.7363 0.21346159 4.54165376 0.03599379 0.20876400 0.97730345
+388 1766.7790 -125.0283 -679.4237 -125.0000 -675.0000   69.4240 0.19956941 4.52927816 0.03609870 0.19493301 0.98015203
+389 1757.1121 -125.0283 -628.5146 -125.0000 -625.0000   59.8483 0.18563326 4.51499341 0.03619695 0.18098475 0.98281957
+390 1748.2008 -125.0283 -577.7389 -125.0000 -575.0000   51.0091 0.17166719 4.49832829 0.03628835 0.16692642 0.98530134
+391 1740.0422 -125.0283 -527.0862 -125.0000 -525.0000   42.9066 0.15768864 4.47864579 0.03637275 0.15276555 0.98759289
+392 1732.6337 -125.0283 -476.5461 -125.0000 -475.0000   35.5407 0.14371998 4.45506526 0.03644999 0.13850995 0.98969005
+393 1725.9729 -125.0283 -426.1081 -125.0000 -425.0000   28.9113 0.12979104 4.42633753 0.03651992 0.12416774 0.99158896
+394 1720.0576 -125.0283 -375.7616 -125.0000 -375.0000   23.0186 0.11594339 4.39063842 0.03658243 0.10974728 0.99328609
+395 1714.8859 -125.0283 -325.4960 -125.0000 -325.0000   17.8624 0.10223796 4.34521514 0.03663738 0.09525720 0.99477825
+396 1710.4562 -125.0283 -275.3006 -125.0000 -275.0000   13.4428 0.08876909 4.28576148 0.03668469 0.08070631 0.99606261
+397 1706.7669 -125.0283 -225.1647 -125.0000 -225.0000    9.7599 0.07569211 4.20529047 0.03672425 0.06610364 0.99713672
+398 1703.8169 -125.0283 -175.0775 -125.0000 -175.0000    6.8135 0.06327961 4.09213949 0.03675599 0.05145838 0.99799851
+399 1701.6053 -125.0283 -125.0283 -125.0000 -125.0000    4.6037 0.05203804 3.92699081 0.03677984 0.03677984 0.99864633
+400 1700.1312 -125.0283  -75.0061 -125.0000  -75.0000    3.1305 0.04292406 3.68201215 0.03679578 0.02207747 0.99907890
+401 1700.1312 -125.0283   75.0061 -125.0000   75.0000    3.1305 0.04292406 2.60117315 0.03679578 -0.02207747 0.99907890
+402 1701.6053 -125.0283  125.0283 -125.0000  125.0000    4.6037 0.05203804 2.35619449 0.03677984 -0.03677984 0.99864633
+403 1703.8169 -125.0283  175.0775 -125.0000  175.0000    6.8135 0.06327961 2.19104581 0.03675599 -0.05145838 0.99799851
+404 1706.7669 -125.0283  225.1647 -125.0000  225.0000    9.7599 0.07569211 2.07789483 0.03672425 -0.06610364 0.99713672
+405 1710.4562 -125.0283  275.3006 -125.0000  275.0000   13.4428 0.08876909 1.99742382 0.03668469 -0.08070631 0.99606261
+406 1714.8859 -125.0283  325.4960 -125.0000  325.0000   17.8624 0.10223796 1.93797016 0.03663738 -0.09525720 0.99477825
+407 1720.0576 -125.0283  375.7616 -125.0000  375.0000   23.0186 0.11594339 1.89254688 0.03658243 -0.10974728 0.99328609
+408 1725.9729 -125.0283  426.1081 -125.0000  425.0000   28.9113 0.12979104 1.85684777 0.03651992 -0.12416774 0.99158896
+409 1732.6337 -125.0283  476.5461 -125.0000  475.0000   35.5407 0.14371998 1.82812004 0.03644999 -0.13850995 0.98969005
+410 1740.0422 -125.0283  527.0862 -125.0000  525.0000   42.9066 0.15768864 1.80453951 0.03637275 -0.15276555 0.98759289
+411 1748.2008 -125.0283  577.7389 -125.0000  575.0000   51.0091 0.17166719 1.78485701 0.03628835 -0.16692642 0.98530134
+412 1757.1121 -125.0283  628.5146 -125.0000  625.0000   59.8483 0.18563326 1.76819189 0.03619695 -0.18098475 0.98281957
+413 1766.7790 -125.0283  679.4237 -125.0000  675.0000   69.4240 0.19956941 1.75390714 0.03609870 -0.19493301 0.98015203
+414 1777.2046 -125.0283  730.4765 -125.0000  725.0000   79.7363 0.21346159 1.74153154 0.03599379 -0.20876400 0.97730345
+415 1788.3922 -125.0283  781.6832 -125.0000  775.0000   90.7852 0.22729817 1.73070945 0.03588240 -0.22247085 0.97427880
+416 1800.3455 -125.0283  833.0538 -125.0000  825.0000  102.5707 0.24106928 1.72116775 0.03576470 -0.23604705 0.97108325
+417 1798.8502  -75.0061 -833.0538  -75.0000 -825.0000  101.0975 0.23939767 4.62172909 0.02146761 0.23614373 0.97148097
+418 1786.8995  -75.0061 -781.6832  -75.0000 -775.0000   89.3120 0.22550881 4.61591520 0.02153831 0.22256257 0.97468046
+419 1775.7142  -75.0061 -730.4765  -75.0000 -725.0000   78.2631 0.21153930 4.60930736 0.02160523 0.20885060 0.97770887
+420 1765.2909  -75.0061 -679.4237  -75.0000 -675.0000   67.9508 0.19749582 4.60173175 0.02166826 0.19501434 0.98056101
+421 1755.6261  -75.0061 -628.5146  -75.0000 -625.0000   58.3751 0.18338581 4.59296005 0.02172728 0.18106068 0.98323189
+422 1746.7167  -75.0061 -577.7389  -75.0000 -575.0000   49.5359 0.16921782 4.58268644 0.02178219 0.16699681 0.98571680
+423 1738.5599  -75.0061 -527.0862  -75.0000 -525.0000   41.4334 0.15500180 4.57049192 0.02183289 0.15283026 0.98801125
+424 1731.1530  -75.0061 -476.5461  -75.0000 -475.0000   34.0675 0.14074982 4.55578710 0.02187930 0.13856888 0.99011109
+425 1724.4936  -75.0061 -426.1081  -75.0000 -425.0000   27.4381 0.12647710 4.53771677 0.02192131 0.12422077 0.99201243
+426 1718.5796  -75.0061 -375.7616  -75.0000 -375.0000   21.5454 0.11220396 4.51499341 0.02195886 0.10979431 0.99371174
+427 1713.4090  -75.0061 -325.4960  -75.0000 -325.0000   16.3892 0.09795935 4.48559013 0.02199188 0.09529814 0.99520582
+428 1708.9802  -75.0061 -275.3006  -75.0000 -275.0000   11.9697 0.08378801 4.44613692 0.02202030 0.08074109 0.99649184
+429 1705.2917  -75.0061 -225.1647  -75.0000 -225.0000    8.2867 0.06976603 4.39063842 0.02204406 0.06613219 0.99756734
+430 1702.3424  -75.0061 -175.0775  -75.0000 -175.0000    5.3403 0.05603859 4.30749719 0.02206313 0.05148064 0.99843025
+431 1700.1312  -75.0061 -125.0283  -75.0000 -125.0000    3.1305 0.04292406 4.17196947 0.02207747 0.03679578 0.99907890
+432 1698.6575  -75.0061  -75.0061  -75.0000  -75.0000    1.6573 0.03124087 3.92699081 0.02208704 0.02208704 0.99951204
+433 1698.6575  -75.0061   75.0061  -75.0000   75.0000    1.6573 0.03124087 2.35619449 0.02208704 -0.02208704 0.99951204
+434 1700.1312  -75.0061  125.0283  -75.0000  125.0000    3.1305 0.04292406 2.11121583 0.02207747 -0.03679578 0.99907890
+435 1702.3424  -75.0061  175.0775  -75.0000  175.0000    5.3403 0.05603859 1.97568811 0.02206313 -0.05148064 0.99843025
+436 1705.2917  -75.0061  225.1647  -75.0000  225.0000    8.2867 0.06976603 1.89254688 0.02204406 -0.06613219 0.99756734
+437 1708.9802  -75.0061  275.3006  -75.0000  275.0000   11.9697 0.08378801 1.83704838 0.02202030 -0.08074109 0.99649184
+438 1713.4090  -75.0061  325.4960  -75.0000  325.0000   16.3892 0.09795935 1.79759517 0.02199188 -0.09529814 0.99520582
+439 1718.5796  -75.0061  375.7616  -75.0000  375.0000   21.5454 0.11220396 1.76819189 0.02195886 -0.10979431 0.99371174
+440 1724.4936  -75.0061  426.1081  -75.0000  425.0000   27.4381 0.12647710 1.74546853 0.02192131 -0.12422077 0.99201243
+441 1731.1530  -75.0061  476.5461  -75.0000  475.0000   34.0675 0.14074982 1.72739820 0.02187930 -0.13856888 0.99011109
+442 1738.5599  -75.0061  527.0862  -75.0000  525.0000   41.4334 0.15500180 1.71269338 0.02183289 -0.15283026 0.98801125
+443 1746.7167  -75.0061  577.7389  -75.0000  575.0000   49.5359 0.16921782 1.70049886 0.02178219 -0.16699681 0.98571680
+444 1755.6261  -75.0061  628.5146  -75.0000  625.0000   58.3751 0.18338581 1.69022525 0.02172728 -0.18106068 0.98323189
+445 1765.2909  -75.0061  679.4237  -75.0000  675.0000   67.9508 0.19749582 1.68145355 0.02166826 -0.19501434 0.98056101
+446 1775.7142  -75.0061  730.4765  -75.0000  725.0000   78.2631 0.21153930 1.67387794 0.02160523 -0.20885060 0.97770887
+447 1786.8995  -75.0061  781.6832  -75.0000  775.0000   89.3120 0.22550881 1.66727010 0.02153831 -0.22256257 0.97468046
+448 1798.8502  -75.0061  833.0538  -75.0000  825.0000  101.0975 0.23939767 1.66145621 0.02146761 -0.23614373 0.97148097
+449 1798.1027  -25.0002 -833.0538  -25.0000 -825.0000  100.3609 0.23855678 4.68209521 0.00715734 0.23619211 0.97168002
+450 1786.1532  -25.0002 -781.6832  -25.0000 -775.0000   88.5754 0.22460804 4.68014209 0.00718092 0.22260847 0.97488148
+451 1774.9692  -25.0002 -730.4765  -25.0000 -725.0000   77.5265 0.21057077 4.67791987 0.00720324 0.20889394 0.97791177
+452 1764.5469  -25.0002 -679.4237  -25.0000 -675.0000   67.2142 0.19644994 4.67536886 0.00722426 0.19505505 0.98076569
+453 1754.8832  -25.0002 -628.5146  -25.0000 -625.0000   57.6385 0.18225074 4.67241029 0.00724395 0.18109868 0.98343825
+454 1745.9748  -25.0002 -577.7389  -25.0000 -575.0000   48.7994 0.16797869 4.66893808 0.00726226 0.16703203 0.98592472
+455 1737.8188  -25.0002 -527.0862  -25.0000 -525.0000   40.6968 0.15363960 4.66480587 0.00727917 0.15286265 0.98822064
+456 1730.4127  -25.0002 -476.5461  -25.0000 -475.0000   33.3309 0.13923969 4.65980591 0.00729465 0.13859837 0.99032181
+457 1723.7540  -25.0002 -426.1081  -25.0000 -425.0000   26.7015 0.12478568 4.65363315 0.00730867 0.12424731 0.99222436
+458 1717.8407  -25.0002 -375.7616  -25.0000 -375.0000   20.8088 0.11028505 4.64582081 0.00732119 0.10981785 0.99392477
+459 1712.6707  -25.0002 -325.4960  -25.0000 -325.0000   15.6526 0.09574645 4.63561708 0.00733220 0.09531863 0.99541981
+460 1708.2424  -25.0002 -275.3006  -25.0000 -275.0000   11.2331 0.08118066 4.62172909 0.00734168 0.08075849 0.99670666
+461 1704.5543  -25.0002 -225.1647  -25.0000 -225.0000    7.5501 0.06660277 4.60173175 0.00734961 0.06614648 0.99778286
+462 1701.6053  -25.0002 -175.0775  -25.0000 -175.0000    4.6037 0.05203804 4.57049192 0.00735597 0.05149178 0.99864633
+463 1699.3944  -25.0002 -125.0283  -25.0000 -125.0000    2.3939 0.03754142 4.51499341 0.00736075 0.03680375 0.99929540
+464 1697.9208  -25.0002  -75.0061  -25.0000  -75.0000    0.9207 0.02328894 4.39063842 0.00736394 0.02209183 0.99972882
+465 1697.9208  -25.0002   75.0061  -25.0000   75.0000    0.9207 0.02328894 1.89254688 0.00736394 -0.02209183 0.99972882
+466 1699.3944  -25.0002  125.0283  -25.0000  125.0000    2.3939 0.03754142 1.76819189 0.00736075 -0.03680375 0.99929540
+467 1701.6053  -25.0002  175.0775  -25.0000  175.0000    4.6037 0.05203804 1.71269338 0.00735597 -0.05149178 0.99864633
+468 1704.5543  -25.0002  225.1647  -25.0000  225.0000    7.5501 0.06660277 1.68145355 0.00734961 -0.06614648 0.99778286
+469 1708.2424  -25.0002  275.3006  -25.0000  275.0000   11.2331 0.08118066 1.66145621 0.00734168 -0.08075849 0.99670666
+470 1712.6707  -25.0002  325.4960  -25.0000  325.0000   15.6526 0.09574645 1.64756822 0.00733220 -0.09531863 0.99541981
+471 1717.8407  -25.0002  375.7616  -25.0000  375.0000   20.8088 0.11028505 1.63736449 0.00732119 -0.10981785 0.99392477
+472 1723.7540  -25.0002  426.1081  -25.0000  425.0000   26.7015 0.12478568 1.62955215 0.00730867 -0.12424731 0.99222436
+473 1730.4127  -25.0002  476.5461  -25.0000  475.0000   33.3309 0.13923969 1.62337939 0.00729465 -0.13859837 0.99032181
+474 1737.8188  -25.0002  527.0862  -25.0000  525.0000   40.6968 0.15363960 1.61837943 0.00727917 -0.15286265 0.98822064
+475 1745.9748  -25.0002  577.7389  -25.0000  575.0000   48.7994 0.16797869 1.61424722 0.00726226 -0.16703203 0.98592472
+476 1754.8832  -25.0002  628.5146  -25.0000  625.0000   57.6385 0.18225074 1.61077501 0.00724395 -0.18109868 0.98343825
+477 1764.5469  -25.0002  679.4237  -25.0000  675.0000   67.2142 0.19644994 1.60781644 0.00722426 -0.19505505 0.98076569
+478 1774.9692  -25.0002  730.4765  -25.0000  725.0000   77.5265 0.21057077 1.60526543 0.00720324 -0.20889394 0.97791177
+479 1786.1532  -25.0002  781.6832  -25.0000  775.0000   88.5754 0.22460804 1.60304321 0.00718092 -0.22260847 0.97488148
+480 1798.1027  -25.0002  833.0538  -25.0000  825.0000  100.3609 0.23855678 1.60109009 0.00715734 -0.23619211 0.97168002
+481 1798.1027   25.0002 -833.0538   25.0000 -825.0000  100.3609 0.23855678 4.74268273 -0.00715734 0.23619211 0.97168002
+482 1786.1532   25.0002 -781.6832   25.0000 -775.0000   88.5754 0.22460804 4.74463586 -0.00718092 0.22260847 0.97488148
+483 1774.9692   25.0002 -730.4765   25.0000 -725.0000   77.5265 0.21057077 4.74685807 -0.00720324 0.20889394 0.97791177
+484 1764.5469   25.0002 -679.4237   25.0000 -675.0000   67.2142 0.19644994 4.74940909 -0.00722426 0.19505505 0.98076569
+485 1754.8832   25.0002 -628.5146   25.0000 -625.0000   57.6385 0.18225074 4.75236766 -0.00724395 0.18109868 0.98343825
+486 1745.9748   25.0002 -577.7389   25.0000 -575.0000   48.7994 0.16797869 4.75583987 -0.00726226 0.16703203 0.98592472
+487 1737.8188   25.0002 -527.0862   25.0000 -525.0000   40.6968 0.15363960 4.75997208 -0.00727917 0.15286265 0.98822064
+488 1730.4127   25.0002 -476.5461   25.0000 -475.0000   33.3309 0.13923969 4.76497203 -0.00729465 0.13859837 0.99032181
+489 1723.7540   25.0002 -426.1081   25.0000 -425.0000   26.7015 0.12478568 4.77114480 -0.00730867 0.12424731 0.99222436
+490 1717.8407   25.0002 -375.7616   25.0000 -375.0000   20.8088 0.11028505 4.77895714 -0.00732119 0.10981785 0.99392477
+491 1712.6707   25.0002 -325.4960   25.0000 -325.0000   15.6526 0.09574645 4.78916086 -0.00733220 0.09531863 0.99541981
+492 1708.2424   25.0002 -275.3006   25.0000 -275.0000   11.2331 0.08118066 4.80304886 -0.00734168 0.08075849 0.99670666
+493 1704.5543   25.0002 -225.1647   25.0000 -225.0000    7.5501 0.06660277 4.82304619 -0.00734961 0.06614648 0.99778286
+494 1701.6053   25.0002 -175.0775   25.0000 -175.0000    4.6037 0.05203804 4.85428603 -0.00735597 0.05149178 0.99864633
+495 1699.3944   25.0002 -125.0283   25.0000 -125.0000    2.3939 0.03754142 4.90978453 -0.00736075 0.03680375 0.99929540
+496 1697.9208   25.0002  -75.0061   25.0000  -75.0000    0.9207 0.02328894 5.03413953 -0.00736394 0.02209183 0.99972882
+497 1697.9208   25.0002   75.0061   25.0000   75.0000    0.9207 0.02328894 1.24904577 -0.00736394 -0.02209183 0.99972882
+498 1699.3944   25.0002  125.0283   25.0000  125.0000    2.3939 0.03754142 1.37340077 -0.00736075 -0.03680375 0.99929540
+499 1701.6053   25.0002  175.0775   25.0000  175.0000    4.6037 0.05203804 1.42889927 -0.00735597 -0.05149178 0.99864633
+500 1704.5543   25.0002  225.1647   25.0000  225.0000    7.5501 0.06660277 1.46013911 -0.00734961 -0.06614648 0.99778286
+501 1708.2424   25.0002  275.3006   25.0000  275.0000   11.2331 0.08118066 1.48013644 -0.00734168 -0.08075849 0.99670666
+502 1712.6707   25.0002  325.4960   25.0000  325.0000   15.6526 0.09574645 1.49402444 -0.00733220 -0.09531863 0.99541981
+503 1717.8407   25.0002  375.7616   25.0000  375.0000   20.8088 0.11028505 1.50422816 -0.00732119 -0.10981785 0.99392477
+504 1723.7540   25.0002  426.1081   25.0000  425.0000   26.7015 0.12478568 1.51204050 -0.00730867 -0.12424731 0.99222436
+505 1730.4127   25.0002  476.5461   25.0000  475.0000   33.3309 0.13923969 1.51821327 -0.00729465 -0.13859837 0.99032181
+506 1737.8188   25.0002  527.0862   25.0000  525.0000   40.6968 0.15363960 1.52321322 -0.00727917 -0.15286265 0.98822064
+507 1745.9748   25.0002  577.7389   25.0000  575.0000   48.7994 0.16797869 1.52734543 -0.00726226 -0.16703203 0.98592472
+508 1754.8832   25.0002  628.5146   25.0000  625.0000   57.6385 0.18225074 1.53081764 -0.00724395 -0.18109868 0.98343825
+509 1764.5469   25.0002  679.4237   25.0000  675.0000   67.2142 0.19644994 1.53377621 -0.00722426 -0.19505505 0.98076569
+510 1774.9692   25.0002  730.4765   25.0000  725.0000   77.5265 0.21057077 1.53632723 -0.00720324 -0.20889394 0.97791177
+511 1786.1532   25.0002  781.6832   25.0000  775.0000   88.5754 0.22460804 1.53854944 -0.00718092 -0.22260847 0.97488148
+512 1798.1027   25.0002  833.0538   25.0000  825.0000  100.3609 0.23855678 1.54050257 -0.00715734 -0.23619211 0.97168002
+513 1798.8502   75.0061 -833.0538   75.0000 -825.0000  101.0975 0.23939767 4.80304886 -0.02146761 0.23614373 0.97148097
+514 1786.8995   75.0061 -781.6832   75.0000 -775.0000   89.3120 0.22550881 4.80886275 -0.02153831 0.22256257 0.97468046
+515 1775.7142   75.0061 -730.4765   75.0000 -725.0000   78.2631 0.21153930 4.81547058 -0.02160523 0.20885060 0.97770887
+516 1765.2909   75.0061 -679.4237   75.0000 -675.0000   67.9508 0.19749582 4.82304619 -0.02166826 0.19501434 0.98056101
+517 1755.6261   75.0061 -628.5146   75.0000 -625.0000   58.3751 0.18338581 4.83181790 -0.02172728 0.18106068 0.98323189
+518 1746.7167   75.0061 -577.7389   75.0000 -575.0000   49.5359 0.16921782 4.84209151 -0.02178219 0.16699681 0.98571680
+519 1738.5599   75.0061 -527.0862   75.0000 -525.0000   41.4334 0.15500180 4.85428603 -0.02183289 0.15283026 0.98801125
+520 1731.1530   75.0061 -476.5461   75.0000 -475.0000   34.0675 0.14074982 4.86899085 -0.02187930 0.13856888 0.99011109
+521 1724.4936   75.0061 -426.1081   75.0000 -425.0000   27.4381 0.12647710 4.88706117 -0.02192131 0.12422077 0.99201243
+522 1718.5796   75.0061 -375.7616   75.0000 -375.0000   21.5454 0.11220396 4.90978453 -0.02195886 0.10979431 0.99371174
+523 1713.4090   75.0061 -325.4960   75.0000 -325.0000   16.3892 0.09795935 4.93918782 -0.02199188 0.09529814 0.99520582
+524 1708.9802   75.0061 -275.3006   75.0000 -275.0000   11.9697 0.08378801 4.97864102 -0.02202030 0.08074109 0.99649184
+525 1705.2917   75.0061 -225.1647   75.0000 -225.0000    8.2867 0.06976603 5.03413953 -0.02204406 0.06613219 0.99756734
+526 1702.3424   75.0061 -175.0775   75.0000 -175.0000    5.3403 0.05603859 5.11728076 -0.02206313 0.05148064 0.99843025
+527 1700.1312   75.0061 -125.0283   75.0000 -125.0000    3.1305 0.04292406 5.25280847 -0.02207747 0.03679578 0.99907890
+528 1698.6575   75.0061  -75.0061   75.0000  -75.0000    1.6573 0.03124087 5.49778714 -0.02208704 0.02208704 0.99951204
+529 1697.9208   75.0061  -25.0002   75.0000  -25.0000    0.9207 0.02328894 5.96143475 -0.02209183 0.00736394 0.99972882
+530 1697.9208   75.0061   25.0002   75.0000   25.0000    0.9207 0.02328894 0.32175055 -0.02209183 -0.00736394 0.99972882
+531 1698.6575   75.0061   75.0061   75.0000   75.0000    1.6573 0.03124087 0.78539816 -0.02208704 -0.02208704 0.99951204
+532 1700.1312   75.0061  125.0283   75.0000  125.0000    3.1305 0.04292406 1.03037683 -0.02207747 -0.03679578 0.99907890
+533 1702.3424   75.0061  175.0775   75.0000  175.0000    5.3403 0.05603859 1.16590454 -0.02206313 -0.05148064 0.99843025
+534 1705.2917   75.0061  225.1647   75.0000  225.0000    8.2867 0.06976603 1.24904577 -0.02204406 -0.06613219 0.99756734
+535 1708.9802   75.0061  275.3006   75.0000  275.0000   11.9697 0.08378801 1.30454428 -0.02202030 -0.08074109 0.99649184
+536 1713.4090   75.0061  325.4960   75.0000  325.0000   16.3892 0.09795935 1.34399748 -0.02199188 -0.09529814 0.99520582
+537 1718.5796   75.0061  375.7616   75.0000  375.0000   21.5454 0.11220396 1.37340077 -0.02195886 -0.10979431 0.99371174
+538 1724.4936   75.0061  426.1081   75.0000  425.0000   27.4381 0.12647710 1.39612413 -0.02192131 -0.12422077 0.99201243
+539 1731.1530   75.0061  476.5461   75.0000  475.0000   34.0675 0.14074982 1.41419445 -0.02187930 -0.13856888 0.99011109
+540 1738.5599   75.0061  527.0862   75.0000  525.0000   41.4334 0.15500180 1.42889927 -0.02183289 -0.15283026 0.98801125
+541 1746.7167   75.0061  577.7389   75.0000  575.0000   49.5359 0.16921782 1.44109379 -0.02178219 -0.16699681 0.98571680
+542 1755.6261   75.0061  628.5146   75.0000  625.0000   58.3751 0.18338581 1.45136740 -0.02172728 -0.18106068 0.98323189
+543 1765.2909   75.0061  679.4237   75.0000  675.0000   67.9508 0.19749582 1.46013911 -0.02166826 -0.19501434 0.98056101
+544 1775.7142   75.0061  730.4765   75.0000  725.0000   78.2631 0.21153930 1.46771472 -0.02160523 -0.20885060 0.97770887
+545 1786.8995   75.0061  781.6832   75.0000  775.0000   89.3120 0.22550881 1.47432255 -0.02153831 -0.22256257 0.97468046
+546 1798.8502   75.0061  833.0538   75.0000  825.0000  101.0975 0.23939767 1.48013644 -0.02146761 -0.23614373 0.97148097
+547 1800.3455  125.0283 -833.0538  125.0000 -825.0000  102.5707 0.24106928 4.86276040 -0.03576470 0.23604705 0.97108325
+548 1788.3922  125.0283 -781.6832  125.0000 -775.0000   90.7852 0.22729817 4.87230210 -0.03588240 0.22247085 0.97427880
+549 1777.2046  125.0283 -730.4765  125.0000 -725.0000   79.7363 0.21346159 4.88312418 -0.03599379 0.20876400 0.97730345
+550 1766.7790  125.0283 -679.4237  125.0000 -675.0000   69.4240 0.19956941 4.89549979 -0.03609870 0.19493301 0.98015203
+551 1757.1121  125.0283 -628.5146  125.0000 -625.0000   59.8483 0.18563326 4.90978453 -0.03619695 0.18098475 0.98281957
+552 1748.2008  125.0283 -577.7389  125.0000 -575.0000   51.0091 0.17166719 4.92644966 -0.03628835 0.16692642 0.98530134
+553 1740.0422  125.0283 -527.0862  125.0000 -525.0000   42.9066 0.15768864 4.94613215 -0.03637275 0.15276555 0.98759289
+554 1732.6337  125.0283 -476.5461  125.0000 -475.0000   35.5407 0.14371998 4.96971269 -0.03644999 0.13850995 0.98969005
+555 1725.9729  125.0283 -426.1081  125.0000 -425.0000   28.9113 0.12979104 4.99844041 -0.03651992 0.12416774 0.99158896
+556 1720.0576  125.0283 -375.7616  125.0000 -375.0000   23.0186 0.11594339 5.03413953 -0.03658243 0.10974728 0.99328609
+557 1714.8859  125.0283 -325.4960  125.0000 -325.0000   17.8624 0.10223796 5.07956281 -0.03663738 0.09525720 0.99477825
+558 1710.4562  125.0283 -275.3006  125.0000 -275.0000   13.4428 0.08876909 5.13901647 -0.03668469 0.08070631 0.99606261
+559 1706.7669  125.0283 -225.1647  125.0000 -225.0000    9.7599 0.07569211 5.21948748 -0.03672425 0.06610364 0.99713672
+560 1703.8169  125.0283 -175.0775  125.0000 -175.0000    6.8135 0.06327961 5.33263846 -0.03675599 0.05145838 0.99799851
+561 1701.6053  125.0283 -125.0283  125.0000 -125.0000    4.6037 0.05203804 5.49778714 -0.03677984 0.03677984 0.99864633
+562 1700.1312  125.0283  -75.0061  125.0000  -75.0000    3.1305 0.04292406 5.74276580 -0.03679578 0.02207747 0.99907890
+563 1699.3944  125.0283  -25.0002  125.0000  -25.0000    2.3939 0.03754142 6.08578974 -0.03680375 0.00736075 0.99929540
+564 1699.3944  125.0283   25.0002  125.0000   25.0000    2.3939 0.03754142 0.19739556 -0.03680375 -0.00736075 0.99929540
+565 1700.1312  125.0283   75.0061  125.0000   75.0000    3.1305 0.04292406 0.54041950 -0.03679578 -0.02207747 0.99907890
+566 1701.6053  125.0283  125.0283  125.0000  125.0000    4.6037 0.05203804 0.78539816 -0.03677984 -0.03677984 0.99864633
+567 1703.8169  125.0283  175.0775  125.0000  175.0000    6.8135 0.06327961 0.95054684 -0.03675599 -0.05145838 0.99799851
+568 1706.7669  125.0283  225.1647  125.0000  225.0000    9.7599 0.07569211 1.06369782 -0.03672425 -0.06610364 0.99713672
+569 1710.4562  125.0283  275.3006  125.0000  275.0000   13.4428 0.08876909 1.14416883 -0.03668469 -0.08070631 0.99606261
+570 1714.8859  125.0283  325.4960  125.0000  325.0000   17.8624 0.10223796 1.20362249 -0.03663738 -0.09525720 0.99477825
+571 1720.0576  125.0283  375.7616  125.0000  375.0000   23.0186 0.11594339 1.24904577 -0.03658243 -0.10974728 0.99328609
+572 1725.9729  125.0283  426.1081  125.0000  425.0000   28.9113 0.12979104 1.28474489 -0.03651992 -0.12416774 0.99158896
+573 1732.6337  125.0283  476.5461  125.0000  475.0000   35.5407 0.14371998 1.31347261 -0.03644999 -0.13850995 0.98969005
+574 1740.0422  125.0283  527.0862  125.0000  525.0000   42.9066 0.15768864 1.33705315 -0.03637275 -0.15276555 0.98759289
+575 1748.2008  125.0283  577.7389  125.0000  575.0000   51.0091 0.17166719 1.35673564 -0.03628835 -0.16692642 0.98530134
+576 1757.1121  125.0283  628.5146  125.0000  625.0000   59.8483 0.18563326 1.37340077 -0.03619695 -0.18098475 0.98281957
+577 1766.7790  125.0283  679.4237  125.0000  675.0000   69.4240 0.19956941 1.38768551 -0.03609870 -0.19493301 0.98015203
+578 1777.2046  125.0283  730.4765  125.0000  725.0000   79.7363 0.21346159 1.40006112 -0.03599379 -0.20876400 0.97730345
+579 1788.3922  125.0283  781.6832  125.0000  775.0000   90.7852 0.22729817 1.41088320 -0.03588240 -0.22247085 0.97427880
+580 1800.3455  125.0283  833.0538  125.0000  825.0000  102.5707 0.24106928 1.42042490 -0.03576470 -0.23604705 0.97108325
+581 1802.5890  175.0775 -833.0538  175.0000 -825.0000  104.7805 0.24355180 4.92141192 -0.05003987 0.23590225 0.97048758
+582 1790.6319  175.0775 -781.6832  175.0000 -775.0000   92.9950 0.22995247 4.93447088 -0.05020434 0.22233349 0.97367723
+583 1779.4406  175.0775 -730.4765  175.0000 -725.0000   81.9461 0.21630908 4.94923773 -0.05036000 0.20863429 0.97669627
+584 1769.0117  175.0775 -679.4237  175.0000 -675.0000   71.6338 0.20263578 4.96606307 -0.05050660 0.19481119 0.97953953
+585 1759.3417  175.0775 -628.5146  175.0000 -625.0000   62.0580 0.18894971 4.98539768 -0.05064389 0.18087103 0.98220205
+586 1750.4275  175.0775 -577.7389  175.0000 -575.0000   53.2189 0.17527207 5.00782981 -0.05077161 0.16682101 0.98467913
+587 1742.2663  175.0775 -527.0862  175.0000 -525.0000   45.1164 0.16162969 5.03413953 -0.05088954 0.15266863 0.98696633
+588 1734.8554  175.0775 -476.5461  175.0000 -475.0000   37.7504 0.14805749 5.06537936 -0.05099747 0.13842170 0.98905950
+589 1728.1924  175.0775 -426.1081  175.0000 -425.0000   31.1211 0.13460232 5.10299602 -0.05109519 0.12408833 0.99095478
+590 1722.2752  175.0775 -375.7616  175.0000 -375.0000   25.2283 0.12132912 5.14901613 -0.05118253 0.10967685 0.99264865
+591 1717.1019  175.0775 -325.4960  175.0000 -325.0000   20.0722 0.10833102 5.20633034 -0.05125932 0.09519588 0.99413793
+592 1712.6707  175.0775 -275.3006  175.0000 -275.0000   15.6526 0.09574645 5.27911819 -0.05132542 0.08065423 0.99541981
+593 1708.9802  175.0775 -225.1647  175.0000 -225.0000   11.9697 0.08378801 5.37343214 -0.05138069 0.06606089 0.99649184
+594 1706.0293  175.0775 -175.0775  175.0000 -175.0000    9.0233 0.07279025 5.49778714 -0.05142504 0.05142504 0.99735196
+595 1703.8169  175.0775 -125.0283  175.0000 -125.0000    6.8135 0.06327961 5.66293581 -0.05145838 0.03675599 0.99799851
+596 1702.3424  175.0775  -75.0061  175.0000  -75.0000    5.3403 0.05603859 5.87829351 -0.05148064 0.02206313 0.99843025
+597 1701.6053  175.0775  -25.0002  175.0000  -25.0000    4.6037 0.05203804 6.14128825 -0.05149178 0.00735597 0.99864633
+598 1701.6053  175.0775   25.0002  175.0000   25.0000    4.6037 0.05203804 0.14189705 -0.05149178 -0.00735597 0.99864633
+599 1702.3424  175.0775   75.0061  175.0000   75.0000    5.3403 0.05603859 0.40489179 -0.05148064 -0.02206313 0.99843025
+600 1703.8169  175.0775  125.0283  175.0000  125.0000    6.8135 0.06327961 0.62024949 -0.05145838 -0.03675599 0.99799851
+601 1706.0293  175.0775  175.0775  175.0000  175.0000    9.0233 0.07279025 0.78539816 -0.05142504 -0.05142504 0.99735196
+602 1708.9802  175.0775  225.1647  175.0000  225.0000   11.9697 0.08378801 0.90975316 -0.05138069 -0.06606089 0.99649184
+603 1712.6707  175.0775  275.3006  175.0000  275.0000   15.6526 0.09574645 1.00406711 -0.05132542 -0.08065423 0.99541981
+604 1717.1019  175.0775  325.4960  175.0000  325.0000   20.0722 0.10833102 1.07685496 -0.05125932 -0.09519588 0.99413793
+605 1722.2752  175.0775  375.7616  175.0000  375.0000   25.2283 0.12132912 1.13416917 -0.05118253 -0.10967685 0.99264865
+606 1728.1924  175.0775  426.1081  175.0000  425.0000   31.1211 0.13460232 1.18018928 -0.05109519 -0.12408833 0.99095478
+607 1734.8554  175.0775  476.5461  175.0000  475.0000   37.7504 0.14805749 1.21780594 -0.05099747 -0.13842170 0.98905950
+608 1742.2663  175.0775  527.0862  175.0000  525.0000   45.1164 0.16162969 1.24904577 -0.05088954 -0.15266863 0.98696633
+609 1750.4275  175.0775  577.7389  175.0000  575.0000   53.2189 0.17527207 1.27535549 -0.05077161 -0.16682101 0.98467913
+610 1759.3417  175.0775  628.5146  175.0000  625.0000   62.0580 0.18894971 1.29778762 -0.05064389 -0.18087103 0.98220205
+611 1769.0117  175.0775  679.4237  175.0000  675.0000   71.6338 0.20263578 1.31712223 -0.05050660 -0.19481119 0.97953953
+612 1779.4406  175.0775  730.4765  175.0000  725.0000   81.9461 0.21630908 1.33394757 -0.05036000 -0.20863429 0.97669627
+613 1790.6319  175.0775  781.6832  175.0000  775.0000   92.9950 0.22995247 1.34871442 -0.05020434 -0.22233349 0.97367723
+614 1802.5890  175.0775  833.0538  175.0000  825.0000  104.7805 0.24355180 1.36177338 -0.05003987 -0.23590225 0.97048758
+615 1805.5815  225.1647 -833.0538  225.0000 -825.0000  107.7269 0.24681679 4.97864102 -0.06428444 0.23570961 0.96969505
+616 1793.6193  225.1647 -781.6832  225.0000 -775.0000   95.9414 0.23343795 4.99494393 -0.06449537 0.22215073 0.97287687
+617 1782.4232  225.1647 -730.4765  225.0000 -725.0000   84.8925 0.22004125 5.01330921 -0.06469502 0.20846173 0.97588845
+618 1771.9898  225.1647 -679.4237  225.0000 -675.0000   74.5801 0.20664577 5.03413953 -0.06488304 0.19464912 0.97872463
+619 1762.3156  225.1647 -628.5146  225.0000 -625.0000   65.0044 0.19327477 5.05794455 -0.06505911 0.18071974 0.98138050
+620 1753.3976  225.1647 -577.7389  225.0000 -575.0000   56.1653 0.17995718 5.08537670 -0.06522291 0.16668077 0.98385136
+621 1745.2329  225.1647 -527.0862  225.0000 -525.0000   48.0628 0.16672965 5.11728076 -0.06537415 0.15253969 0.98613278
+622 1737.8188  225.1647 -476.5461  225.0000 -475.0000   40.6968 0.15363960 5.15476320 -0.06551256 0.13830430 0.98822064
+623 1731.1530  225.1647 -426.1081  225.0000 -425.0000   34.0675 0.14074982 5.19928821 -0.06563789 0.12398268 0.99011109
+624 1725.2332  225.1647 -375.7616  225.0000 -375.0000   28.1747 0.12814525 5.25280847 -0.06574989 0.10958316 0.99180063
+625 1720.0576  225.1647 -325.4960  225.0000 -325.0000   23.0186 0.11594339 5.31793364 -0.06584837 0.09511431 0.99328609
+626 1715.6245  225.1647 -275.3006  225.0000 -275.0000   18.5990 0.10430971 5.39811848 -0.06593313 0.08058494 0.99456467
+627 1711.9324  225.1647 -225.1647  225.0000 -225.0000   14.9160 0.09347986 5.49778714 -0.06600402 0.06600402 0.99563394
+628 1708.9802  225.1647 -175.0775  225.0000 -175.0000   11.9697 0.08378801 5.62214213 -0.06606089 0.05138069 0.99649184
+629 1706.7669  225.1647 -125.0283  225.0000 -125.0000    9.7599 0.07569211 5.77608680 -0.06610364 0.03672425 0.99713672
+630 1705.2917  225.1647  -75.0061  225.0000  -75.0000    8.2867 0.06976603 5.96143475 -0.06613219 0.02204406 0.99756734
+631 1704.5543  225.1647  -25.0002  225.0000  -25.0000    7.5501 0.06660277 6.17252808 -0.06614648 0.00734961 0.99778286
+632 1704.5543  225.1647   25.0002  225.0000   25.0000    7.5501 0.06660277 0.11065722 -0.06614648 -0.00734961 0.99778286
+633 1705.2917  225.1647   75.0061  225.0000   75.0000    8.2867 0.06976603 0.32175055 -0.06613219 -0.02204406 0.99756734
+634 1706.7669  225.1647  125.0283  225.0000  125.0000    9.7599 0.07569211 0.50709850 -0.06610364 -0.03672425 0.99713672
+635 1708.9802  225.1647  175.0775  225.0000  175.0000   11.9697 0.08378801 0.66104317 -0.06606089 -0.05138069 0.99649184
+636 1711.9324  225.1647  225.1647  225.0000  225.0000   14.9160 0.09347986 0.78539816 -0.06600402 -0.06600402 0.99563394
+637 1715.6245  225.1647  275.3006  225.0000  275.0000   18.5990 0.10430971 0.88506682 -0.06593313 -0.08058494 0.99456467
+638 1720.0576  225.1647  325.4960  225.0000  325.0000   23.0186 0.11594339 0.96525166 -0.06584837 -0.09511431 0.99328609
+639 1725.2332  225.1647  375.7616  225.0000  375.0000   28.1747 0.12814525 1.03037683 -0.06574989 -0.10958316 0.99180063
+640 1731.1530  225.1647  426.1081  225.0000  425.0000   34.0675 0.14074982 1.08389709 -0.06563789 -0.12398268 0.99011109
+641 1737.8188  225.1647  476.5461  225.0000  475.0000   40.6968 0.15363960 1.12842210 -0.06551256 -0.13830430 0.98822064
+642 1745.2329  225.1647  527.0862  225.0000  525.0000   48.0628 0.16672965 1.16590454 -0.06537415 -0.15253969 0.98613278
+643 1753.3976  225.1647  577.7389  225.0000  575.0000   56.1653 0.17995718 1.19780860 -0.06522291 -0.16668077 0.98385136
+644 1762.3156  225.1647  628.5146  225.0000  625.0000   65.0044 0.19327477 1.22524075 -0.06505911 -0.18071974 0.98138050
+645 1771.9898  225.1647  679.4237  225.0000  675.0000   74.5801 0.20664577 1.24904577 -0.06488304 -0.19464912 0.97872463
+646 1782.4232  225.1647  730.4765  225.0000  725.0000   84.8925 0.22004125 1.26987609 -0.06469502 -0.20846173 0.97588845
+647 1793.6193  225.1647  781.6832  225.0000  775.0000   95.9414 0.23343795 1.28824137 -0.06449537 -0.22215073 0.97287687
+648 1805.5815  225.1647  833.0538  225.0000  825.0000  107.7269 0.24681679 1.30454428 -0.06428444 -0.23570961 0.96969505
+649 1809.3239  275.3006 -833.0538  275.0000 -825.0000  111.4098 0.25082849 5.03413953 -0.07848982 0.23546947 0.96870712
+650 1797.3553  275.3006 -781.6832  275.0000 -775.0000   99.6243 0.23771246 5.05336793 -0.07874684 0.22192291 0.97187919
+651 1786.1532  275.3006 -730.4765  275.0000 -725.0000   88.5754 0.22460804 5.07493321 -0.07899010 0.20824663 0.97488148
+652 1775.7142  275.3006 -679.4237  275.0000 -675.0000   78.2631 0.21153930 5.09926469 -0.07921919 0.19444711 0.97770887
+653 1766.0349  275.3006 -628.5146  275.0000 -625.0000   68.6874 0.19853561 5.12689585 -0.07943371 0.18053117 0.98035646
+654 1757.1121  275.3006 -577.7389  275.0000 -575.0000   59.8483 0.18563326 5.15849452 -0.07963329 0.16650597 0.98281957
+655 1748.9429  275.3006 -527.0862  275.0000 -525.0000   51.7457 0.17287785 5.19490227 -0.07981756 0.15237898 0.98509380
+656 1741.5249  275.3006 -476.5461  275.0000 -475.0000   44.3798 0.16032751 5.23718474 -0.07998619 0.13815797 0.98717505
+657 1734.8554  275.3006 -426.1081  275.0000 -425.0000   37.7504 0.14805749 5.28669380 -0.08013888 0.12385100 0.98905950
+658 1728.9324  275.3006 -375.7616  275.0000 -375.0000   31.8577 0.13616654 5.34513781 -0.08027534 0.10946637 0.99074365
+659 1723.7540  275.3006 -325.4960  275.0000 -325.0000   26.7015 0.12478568 5.41464590 -0.08039532 0.09501265 0.99222436
+660 1719.3185  275.3006 -275.3006  275.0000 -275.0000   22.2820 0.11408953 5.49778714 -0.08049858 0.08049858 0.99349885
+661 1715.6245  275.3006 -225.1647  275.0000 -225.0000   18.5990 0.10430971 5.59745579 -0.08058494 0.06593313 0.99456467
+662 1712.6707  275.3006 -175.0775  275.0000 -175.0000   15.6526 0.09574645 5.71645608 -0.08065423 0.05132542 0.99541981
+663 1710.4562  275.3006 -125.0283  275.0000 -125.0000   13.4428 0.08876909 5.85655781 -0.08070631 0.03668469 0.99606261
+664 1708.9802  275.3006  -75.0061  275.0000  -75.0000   11.9697 0.08378801 6.01693325 -0.08074109 0.02202030 0.99649184
+665 1708.2424  275.3006  -25.0002  275.0000  -25.0000   11.2331 0.08118066 6.19252541 -0.08075849 0.00734168 0.99670666
+666 1708.2424  275.3006   25.0002  275.0000   25.0000   11.2331 0.08118066 0.09065989 -0.08075849 -0.00734168 0.99670666
+667 1708.9802  275.3006   75.0061  275.0000   75.0000   11.9697 0.08378801 0.26625205 -0.08074109 -0.02202030 0.99649184
+668 1710.4562  275.3006  125.0283  275.0000  125.0000   13.4428 0.08876909 0.42662749 -0.08070631 -0.03668469 0.99606261
+669 1712.6707  275.3006  175.0775  275.0000  175.0000   15.6526 0.09574645 0.56672922 -0.08065423 -0.05132542 0.99541981
+670 1715.6245  275.3006  225.1647  275.0000  225.0000   18.5990 0.10430971 0.68572951 -0.08058494 -0.06593313 0.99456467
+671 1719.3185  275.3006  275.3006  275.0000  275.0000   22.2820 0.11408953 0.78539816 -0.08049858 -0.08049858 0.99349885
+672 1723.7540  275.3006  325.4960  275.0000  325.0000   26.7015 0.12478568 0.86853940 -0.08039532 -0.09501265 0.99222436
+673 1728.9324  275.3006  375.7616  275.0000  375.0000   31.8577 0.13616654 0.93804749 -0.08027534 -0.10946637 0.99074365
+674 1734.8554  275.3006  426.1081  275.0000  425.0000   37.7504 0.14805749 0.99649150 -0.08013888 -0.12385100 0.98905950
+675 1741.5249  275.3006  476.5461  275.0000  475.0000   44.3798 0.16032751 1.04600056 -0.07998619 -0.13815797 0.98717505
+676 1748.9429  275.3006  527.0862  275.0000  525.0000   51.7457 0.17287785 1.08828303 -0.07981756 -0.15237898 0.98509380
+677 1757.1121  275.3006  577.7389  275.0000  575.0000   59.8483 0.18563326 1.12469078 -0.07963329 -0.16650597 0.98281957
+678 1766.0349  275.3006  628.5146  275.0000  625.0000   68.6874 0.19853561 1.15628945 -0.07943371 -0.18053117 0.98035646
+679 1775.7142  275.3006  679.4237  275.0000  675.0000   78.2631 0.21153930 1.18392061 -0.07921919 -0.19444711 0.97770887
+680 1786.1532  275.3006  730.4765  275.0000  725.0000   88.5754 0.22460804 1.20825209 -0.07899010 -0.20824663 0.97488148
+681 1797.3553  275.3006  781.6832  275.0000  775.0000   99.6243 0.23771246 1.22981737 -0.07874684 -0.22192291 0.97187919
+682 1809.3239  275.3006  833.0538  275.0000  825.0000  111.4098 0.25082849 1.24904577 -0.07848982 -0.23546947 0.96870712
+683 1813.8174  325.4960 -833.0538  325.0000 -825.0000  115.8294 0.25554542 5.08765980 -0.09264756 0.23518226 0.96752557
+684 1801.8411  325.4960 -781.6832  325.0000 -775.0000  104.0439 0.24272757 5.10946842 -0.09295019 0.22165046 0.97068601
+685 1790.6319  325.4960 -730.4765  325.0000 -725.0000   92.9950 0.22995247 5.13380818 -0.09323662 0.20798939 0.97367723
+686 1780.1862  325.4960 -679.4237  325.0000 -675.0000   82.6827 0.21724891 5.16111232 -0.09350636 0.19420552 0.97649413
+687 1770.5006  325.4960 -628.5146  325.0000 -625.0000   73.1070 0.20465171 5.19190827 -0.09375894 0.18030565 0.97913183
+688 1761.5720  325.4960 -577.7389  325.0000 -575.0000   64.2678 0.19220353 5.22684029 -0.09399392 0.16629693 0.98158569
+689 1753.3976  325.4960 -527.0862  325.0000 -525.0000   56.1653 0.17995718 5.26669647 -0.09421087 0.15218679 0.98385136
+690 1745.9748  325.4960 -476.5461  325.0000 -475.0000   48.7994 0.16797869 5.31243919 -0.09440941 0.13798298 0.98592472
+691 1739.3010  325.4960 -426.1081  325.0000 -425.0000   42.1700 0.15635137 5.36523560 -0.09458917 0.12369353 0.98780200
+692 1733.3742  325.4960 -375.7616  325.0000 -375.0000   36.2773 0.14518104 5.42647967 -0.09474983 0.10932672 0.98947973
+693 1728.1924  325.4960 -325.4960  325.0000 -325.0000   31.1211 0.13460232 5.49778714 -0.09489107 0.09489107 0.99095478
+694 1723.7540  325.4960 -275.3006  325.0000 -275.0000   26.7015 0.12478568 5.58092837 -0.09501265 0.08039532 0.99222436
+695 1720.0576  325.4960 -225.1647  325.0000 -225.0000   23.0186 0.11594339 5.67764064 -0.09511431 0.06584837 0.99328609
+696 1717.1019  325.4960 -175.0775  325.0000 -175.0000   20.0722 0.10833102 5.78924393 -0.09519588 0.05125932 0.99413793
+697 1714.8859  325.4960 -125.0283  325.0000 -125.0000   17.8624 0.10223796 5.91601147 -0.09525720 0.03663738 0.99477825
+698 1713.4090  325.4960  -75.0061  325.0000  -75.0000   16.3892 0.09795935 6.05638645 -0.09529814 0.02199188 0.99520582
+699 1712.6707  325.4960  -25.0002  325.0000  -25.0000   15.6526 0.09574645 6.20641341 -0.09531863 0.00733220 0.99541981
+700 1712.6707  325.4960   25.0002  325.0000   25.0000   15.6526 0.09574645 0.07677189 -0.09531863 -0.00733220 0.99541981
+701 1713.4090  325.4960   75.0061  325.0000   75.0000   16.3892 0.09795935 0.22679885 -0.09529814 -0.02199188 0.99520582
+702 1714.8859  325.4960  125.0283  325.0000  125.0000   17.8624 0.10223796 0.36717383 -0.09525720 -0.03663738 0.99477825
+703 1717.1019  325.4960  175.0775  325.0000  175.0000   20.0722 0.10833102 0.49394137 -0.09519588 -0.05125932 0.99413793
+704 1720.0576  325.4960  225.1647  325.0000  225.0000   23.0186 0.11594339 0.60554466 -0.09511431 -0.06584837 0.99328609
+705 1723.7540  325.4960  275.3006  325.0000  275.0000   26.7015 0.12478568 0.70225693 -0.09501265 -0.08039532 0.99222436
+706 1728.1924  325.4960  325.4960  325.0000  325.0000   31.1211 0.13460232 0.78539816 -0.09489107 -0.09489107 0.99095478
+707 1733.3742  325.4960  375.7616  325.0000  375.0000   36.2773 0.14518104 0.85670563 -0.09474983 -0.10932672 0.98947973
+708 1739.3010  325.4960  426.1081  325.0000  425.0000   42.1700 0.15635137 0.91794970 -0.09458917 -0.12369353 0.98780200
+709 1745.9748  325.4960  476.5461  325.0000  475.0000   48.7994 0.16797869 0.97074611 -0.09440941 -0.13798298 0.98592472
+710 1753.3976  325.4960  527.0862  325.0000  525.0000   56.1653 0.17995718 1.01648883 -0.09421087 -0.15218679 0.98385136
+711 1761.5720  325.4960  577.7389  325.0000  575.0000   64.2678 0.19220353 1.05634501 -0.09399392 -0.16629693 0.98158569
+712 1770.5006  325.4960  628.5146  325.0000  625.0000   73.1070 0.20465171 1.09127703 -0.09375894 -0.18030565 0.97913183
+713 1780.1862  325.4960  679.4237  325.0000  675.0000   82.6827 0.21724891 1.12207298 -0.09350636 -0.19420552 0.97649413
+714 1790.6319  325.4960  730.4765  325.0000  725.0000   92.9950 0.22995247 1.14937712 -0.09323662 -0.20798939 0.97367723
+715 1801.8411  325.4960  781.6832  325.0000  775.0000  104.0439 0.24272757 1.17371688 -0.09295019 -0.22165046 0.97068601
+716 1813.8174  325.4960  833.0538  325.0000  825.0000  115.8294 0.25554542 1.19552550 -0.09264756 -0.23518226 0.96752557
+717 1819.0634  375.7616 -833.0538  375.0000 -825.0000  120.9856 0.26092194 5.13901647 -0.10674932 0.23484851 0.96615255
+718 1807.0782  375.7616 -781.6832  375.0000 -775.0000  109.2001 0.24843056 5.16305030 -0.10709703 0.22133386 0.96929951
+719 1795.8606  375.7616 -730.4765  375.0000 -725.0000   98.1511 0.23601335 5.18973436 -0.10742611 0.20769047 0.97227789
+720 1785.4071  375.7616 -679.4237  375.0000 -675.0000   87.8388 0.22370314 5.21948748 -0.10773600 0.19392480 0.97508263
+721 1775.7142  375.7616 -628.5146  375.0000 -625.0000   78.2631 0.21153930 5.25280847 -0.10802617 0.18004362 0.97770887
+722 1766.7790  375.7616 -577.7389  375.0000 -575.0000   69.4240 0.19956941 5.29029091 -0.10829611 0.16605404 0.98015203
+723 1758.5984  375.7616 -527.0862  375.0000 -525.0000   61.3214 0.18785135 5.33263846 -0.10854535 0.15196349 0.98240776
+724 1751.1699  375.7616 -476.5461  375.0000 -475.0000   53.9555 0.17645600 5.38067839 -0.10877342 0.13777967 0.98447199
+725 1744.4911  375.7616 -426.1081  375.0000 -425.0000   47.3262 0.16547046 5.43536833 -0.10897992 0.12351058 0.98634097
+726 1738.5599  375.7616 -375.7616  375.0000 -375.0000   41.4334 0.15500180 5.49778714 -0.10916447 0.10916447 0.98801125
+727 1733.3742  375.7616 -325.4960  375.0000 -325.0000   36.2773 0.14518104 5.56909460 -0.10932672 0.09474983 0.98947973
+728 1728.9324  375.7616 -275.3006  375.0000 -275.0000   31.8577 0.13616654 5.65043646 -0.10946637 0.08027534 0.99074365
+729 1725.2332  375.7616 -225.1647  375.0000 -225.0000   28.1747 0.12814525 5.74276580 -0.10958316 0.06574989 0.99180063
+730 1722.2752  375.7616 -175.0775  375.0000 -175.0000   25.2283 0.12132912 5.84655814 -0.10967685 0.05118253 0.99264865
+731 1720.0576  375.7616 -125.0283  375.0000 -125.0000   23.0186 0.11594339 5.96143475 -0.10974728 0.03658243 0.99328609
+732 1718.5796  375.7616  -75.0061  375.0000  -75.0000   21.5454 0.11220396 6.08578974 -0.10979431 0.02195886 0.99371174
+733 1717.8407  375.7616  -25.0002  375.0000  -25.0000   20.8088 0.11028505 6.21661714 -0.10981785 0.00732119 0.99392477
+734 1717.8407  375.7616   25.0002  375.0000   25.0000   20.8088 0.11028505 0.06656816 -0.10981785 -0.00732119 0.99392477
+735 1718.5796  375.7616   75.0061  375.0000   75.0000   21.5454 0.11220396 0.19739556 -0.10979431 -0.02195886 0.99371174
+736 1720.0576  375.7616  125.0283  375.0000  125.0000   23.0186 0.11594339 0.32175055 -0.10974728 -0.03658243 0.99328609
+737 1722.2752  375.7616  175.0775  375.0000  175.0000   25.2283 0.12132912 0.43662716 -0.10967685 -0.05118253 0.99264865
+738 1725.2332  375.7616  225.1647  375.0000  225.0000   28.1747 0.12814525 0.54041950 -0.10958316 -0.06574989 0.99180063
+739 1728.9324  375.7616  275.3006  375.0000  275.0000   31.8577 0.13616654 0.63274884 -0.10946637 -0.08027534 0.99074365
+740 1733.3742  375.7616  325.4960  375.0000  325.0000   36.2773 0.14518104 0.71409070 -0.10932672 -0.09474983 0.98947973
+741 1738.5599  375.7616  375.7616  375.0000  375.0000   41.4334 0.15500180 0.78539816 -0.10916447 -0.10916447 0.98801125
+742 1744.4911  375.7616  426.1081  375.0000  425.0000   47.3262 0.16547046 0.84781697 -0.10897992 -0.12351058 0.98634097
+743 1751.1699  375.7616  476.5461  375.0000  475.0000   53.9555 0.17645600 0.90250691 -0.10877342 -0.13777967 0.98447199
+744 1758.5984  375.7616  527.0862  375.0000  525.0000   61.3214 0.18785135 0.95054684 -0.10854535 -0.15196349 0.98240776
+745 1766.7790  375.7616  577.7389  375.0000  575.0000   69.4240 0.19956941 0.99289439 -0.10829611 -0.16605404 0.98015203
+746 1775.7142  375.7616  628.5146  375.0000  625.0000   78.2631 0.21153930 1.03037683 -0.10802617 -0.18004362 0.97770887
+747 1785.4071  375.7616  679.4237  375.0000  675.0000   87.8388 0.22370314 1.06369782 -0.10773600 -0.19392480 0.97508263
+748 1795.8606  375.7616  730.4765  375.0000  725.0000   98.1511 0.23601335 1.09345094 -0.10742611 -0.20769047 0.97227789
+749 1807.0782  375.7616  781.6832  375.0000  775.0000  109.2001 0.24843056 1.12013500 -0.10709703 -0.22133386 0.96929951
+750 1819.0634  375.7616  833.0538  375.0000  825.0000  120.9856 0.26092194 1.14416883 -0.10674932 -0.23484851 0.96615255
+751 1813.0683  426.1081 -781.6832  425.0000 -775.0000  115.0928 0.25476639 5.21399303 -0.12117912 0.22097369 0.96772220
+752 1801.8411  426.1081 -730.4765  425.0000 -725.0000  104.0439 0.24272757 5.24260475 -0.12155025 0.20735043 0.97068601
+753 1791.3786  426.1081 -679.4237  425.0000 -675.0000   93.7316 0.23082950 5.27431054 -0.12189974 0.19360546 0.97347695
+754 1781.6775  426.1081 -628.5146  425.0000 -625.0000   84.1559 0.21911494 5.30956563 -0.12222697 0.17974555 0.97609021
+755 1772.7345  426.1081 -577.7389  425.0000 -575.0000   75.3167 0.20763480 5.34889719 -0.12253139 0.16577776 0.97852123
+756 1764.5469  426.1081 -527.0862  425.0000 -525.0000   67.2142 0.19644994 5.39291020 -0.12281244 0.15170948 0.98076569
+757 1757.1121  426.1081 -476.5461  425.0000 -475.0000   59.8483 0.18563326 5.44228863 -0.12306963 0.13754841 0.98281957
+758 1750.4275  426.1081 -426.1081  425.0000 -425.0000   53.2189 0.17527207 5.49778714 -0.12330248 0.12330248 0.98467913
+759 1744.4911  426.1081 -375.7616  425.0000 -375.0000   47.3262 0.16547046 5.56020595 -0.12351058 0.10897992 0.98634097
+760 1739.3010  426.1081 -325.4960  425.0000 -325.0000   42.1700 0.15635137 5.63033867 -0.12369353 0.09458917 0.98780200
+761 1734.8554  426.1081 -275.3006  425.0000 -275.0000   37.7504 0.14805749 5.70888047 -0.12385100 0.08013888 0.98905950
+762 1731.1530  426.1081 -225.1647  425.0000 -225.0000   34.0675 0.14074982 5.79628607 -0.12398268 0.06563789 0.99011109
+763 1728.1924  426.1081 -175.0775  425.0000 -175.0000   31.1211 0.13460232 5.89257826 -0.12408833 0.05109519 0.99095478
+764 1725.9729  426.1081 -125.0283  425.0000 -125.0000   28.9113 0.12979104 5.99713386 -0.12416774 0.03651992 0.99158896
+765 1724.4936  426.1081  -75.0061  425.0000  -75.0000   27.4381 0.12647710 6.10851310 -0.12422077 0.02192131 0.99201243
+766 1723.7540  426.1081  -25.0002  425.0000  -25.0000   26.7015 0.12478568 6.22442948 -0.12424731 0.00730867 0.99222436
+767 1723.7540  426.1081   25.0002  425.0000   25.0000   26.7015 0.12478568 0.05875582 -0.12424731 -0.00730867 0.99222436
+768 1724.4936  426.1081   75.0061  425.0000   75.0000   27.4381 0.12647710 0.17467220 -0.12422077 -0.02192131 0.99201243
+769 1725.9729  426.1081  125.0283  425.0000  125.0000   28.9113 0.12979104 0.28605144 -0.12416774 -0.03651992 0.99158896
+770 1728.1924  426.1081  175.0775  425.0000  175.0000   31.1211 0.13460232 0.39060704 -0.12408833 -0.05109519 0.99095478
+771 1731.1530  426.1081  225.1647  425.0000  225.0000   34.0675 0.14074982 0.48689923 -0.12398268 -0.06563789 0.99011109
+772 1734.8554  426.1081  275.3006  425.0000  275.0000   37.7504 0.14805749 0.57430483 -0.12385100 -0.08013888 0.98905950
+773 1739.3010  426.1081  325.4960  425.0000  325.0000   42.1700 0.15635137 0.65284663 -0.12369353 -0.09458917 0.98780200
+774 1744.4911  426.1081  375.7616  425.0000  375.0000   47.3262 0.16547046 0.72297935 -0.12351058 -0.10897992 0.98634097
+775 1750.4275  426.1081  426.1081  425.0000  425.0000   53.2189 0.17527207 0.78539816 -0.12330248 -0.12330248 0.98467913
+776 1757.1121  426.1081  476.5461  425.0000  475.0000   59.8483 0.18563326 0.84089667 -0.12306963 -0.13754841 0.98281957
+777 1764.5469  426.1081  527.0862  425.0000  525.0000   67.2142 0.19644994 0.89027510 -0.12281244 -0.15170948 0.98076569
+778 1772.7345  426.1081  577.7389  425.0000  575.0000   75.3167 0.20763480 0.93428811 -0.12253139 -0.16577776 0.97852123
+779 1781.6775  426.1081  628.5146  425.0000  625.0000   84.1559 0.21911494 0.97361967 -0.12222697 -0.17974555 0.97609021
+780 1791.3786  426.1081  679.4237  425.0000  675.0000   93.7316 0.23082950 1.00887476 -0.12189974 -0.19360546 0.97347695
+781 1801.8411  426.1081  730.4765  425.0000  725.0000  104.0439 0.24272757 1.04058055 -0.12155025 -0.20735043 0.97068601
+782 1813.0683  426.1081  781.6832  425.0000  775.0000  115.0928 0.25476639 1.06919227 -0.12117912 -0.22097369 0.96772220
+783 1808.5752  476.5461 -730.4765  475.0000 -725.0000  110.6732 0.25003217 5.29239175 -0.13560095 0.20696987 0.96890446
+784 1798.1027  476.5461 -679.4237  475.0000 -675.0000  100.3609 0.23855678 5.32559632 -0.13598940 0.19324809 0.97168002
+785 1788.3922  476.5461 -628.5146  475.0000 -625.0000   90.7852 0.22729817 5.36225942 -0.13635310 0.17941198 0.97427880
+786 1779.4406  476.5461 -577.7389  475.0000 -575.0000   81.9461 0.21630908 5.40283543 -0.13669143 0.16546858 0.97669627
+787 1771.2452  476.5461 -527.0862  475.0000 -525.0000   73.8435 0.20565143 5.44782874 -0.13700379 0.15142525 0.97892817
+788 1763.8031  476.5461 -476.5461  475.0000 -475.0000   66.4776 0.19539787 5.49778714 -0.13728962 0.13728962 0.98097050
+789 1757.1121  476.5461 -426.1081  475.0000 -425.0000   59.8483 0.18563326 5.55328564 -0.13754841 0.12306963 0.98281957
+790 1751.1699  476.5461 -375.7616  475.0000 -375.0000   53.9555 0.17645600 5.61489588 -0.13777967 0.10877342 0.98447199
+791 1745.9748  476.5461 -325.4960  475.0000 -325.0000   48.7994 0.16797869 5.68313509 -0.13798298 0.09440941 0.98592472
+792 1741.5249  476.5461 -275.3006  475.0000 -275.0000   44.3798 0.16032751 5.75838953 -0.13815797 0.07998619 0.98717505
+793 1737.8188  476.5461 -225.1647  475.0000 -225.0000   40.6968 0.15363960 5.84081108 -0.13830430 0.06551256 0.98822064
+794 1734.8554  476.5461 -175.0775  475.0000 -175.0000   37.7504 0.14805749 5.93019491 -0.13842170 0.05099747 0.98905950
+795 1732.6337  476.5461 -125.0283  475.0000 -125.0000   35.5407 0.14371998 6.02586159 -0.13850995 0.03644999 0.98969005
+796 1731.1530  476.5461  -75.0061  475.0000  -75.0000   34.0675 0.14074982 6.12658342 -0.13856888 0.02187930 0.99011109
+797 1730.4127  476.5461  -25.0002  475.0000  -25.0000   33.3309 0.13923969 6.23060224 -0.13859837 0.00729465 0.99032181
+798 1730.4127  476.5461   25.0002  475.0000   25.0000   33.3309 0.13923969 0.05258306 -0.13859837 -0.00729465 0.99032181
+799 1731.1530  476.5461   75.0061  475.0000   75.0000   34.0675 0.14074982 0.15660188 -0.13856888 -0.02187930 0.99011109
+800 1732.6337  476.5461  125.0283  475.0000  125.0000   35.5407 0.14371998 0.25732371 -0.13850995 -0.03644999 0.98969005
+801 1734.8554  476.5461  175.0775  475.0000  175.0000   37.7504 0.14805749 0.35299039 -0.13842170 -0.05099747 0.98905950
+802 1737.8188  476.5461  225.1647  475.0000  225.0000   40.6968 0.15363960 0.44237422 -0.13830430 -0.06551256 0.98822064
+803 1741.5249  476.5461  275.3006  475.0000  275.0000   44.3798 0.16032751 0.52479577 -0.13815797 -0.07998619 0.98717505
+804 1745.9748  476.5461  325.4960  475.0000  325.0000   48.7994 0.16797869 0.60005021 -0.13798298 -0.09440941 0.98592472
+805 1751.1699  476.5461  375.7616  475.0000  375.0000   53.9555 0.17645600 0.66828942 -0.13777967 -0.10877342 0.98447199
+806 1757.1121  476.5461  426.1081  475.0000  425.0000   59.8483 0.18563326 0.72989966 -0.13754841 -0.12306963 0.98281957
+807 1763.8031  476.5461  476.5461  475.0000  475.0000   66.4776 0.19539787 0.78539816 -0.13728962 -0.13728962 0.98097050
+808 1771.2452  476.5461  527.0862  475.0000  525.0000   73.8435 0.20565143 0.83535656 -0.13700379 -0.15142525 0.97892817
+809 1779.4406  476.5461  577.7389  475.0000  575.0000   81.9461 0.21630908 0.88034987 -0.13669143 -0.16546858 0.97669627
+810 1788.3922  476.5461  628.5146  475.0000  625.0000   90.7852 0.22729817 0.92092588 -0.13635310 -0.17941198 0.97427880
+811 1798.1027  476.5461  679.4237  475.0000  675.0000  100.3609 0.23855678 0.95758898 -0.13598940 -0.19324809 0.97168002
+812 1808.5752  476.5461  730.4765  475.0000  725.0000  110.6732 0.25003217 0.99079355 -0.13560095 -0.20696987 0.96890446
+813 1805.5815  527.0862 -679.4237  525.0000 -675.0000  107.7269 0.24681679 5.37343214 -0.14999702 0.19285332 0.96969505
+814 1795.8606  527.0862 -628.5146  525.0000 -625.0000   98.1511 0.23601335 5.41104880 -0.15039655 0.17904351 0.97227789
+815 1786.8995  527.0862 -577.7389  525.0000 -575.0000   89.3120 0.22550881 5.45236386 -0.15076819 0.16512707 0.97468046
+816 1778.6952  527.0862 -527.0862  525.0000 -525.0000   81.2095 0.21536462 5.49778714 -0.15111129 0.15111129 0.97689854
+817 1771.2452  527.0862 -476.5461  525.0000 -475.0000   73.8435 0.20565143 5.54774553 -0.15142525 0.13700379 0.97892817
+818 1764.5469  527.0862 -426.1081  525.0000 -425.0000   67.2142 0.19644994 5.60266408 -0.15170948 0.12281244 0.98076569
+819 1758.5984  527.0862 -375.7616  525.0000 -375.0000   61.3214 0.18785135 5.66293581 -0.15196349 0.10854535 0.98240776
+820 1753.3976  527.0862 -325.4960  525.0000 -325.0000   56.1653 0.17995718 5.72887780 -0.15218679 0.09421087 0.98385136
+821 1748.9429  527.0862 -275.3006  525.0000 -275.0000   51.7457 0.17287785 5.80067200 -0.15237898 0.07981756 0.98509380
+822 1745.2329  527.0862 -225.1647  525.0000 -225.0000   48.0628 0.16672965 5.87829351 -0.15253969 0.06537415 0.98613278
+823 1742.2663  527.0862 -175.0775  525.0000 -175.0000   45.1164 0.16162969 5.96143475 -0.15266863 0.05088954 0.98696633
+824 1740.0422  527.0862 -125.0283  525.0000 -125.0000   42.9066 0.15768864 6.04944212 -0.15276555 0.03637275 0.98759289
+825 1738.5599  527.0862  -75.0061  525.0000  -75.0000   41.4334 0.15500180 6.14128825 -0.15283026 0.02183289 0.98801125
+826 1737.8188  527.0862  -25.0002  525.0000  -25.0000   40.6968 0.15363960 6.23560220 -0.15286265 0.00727917 0.98822064
+827 1737.8188  527.0862   25.0002  525.0000   25.0000   40.6968 0.15363960 0.04758310 -0.15286265 -0.00727917 0.98822064
+828 1738.5599  527.0862   75.0061  525.0000   75.0000   41.4334 0.15500180 0.14189705 -0.15283026 -0.02183289 0.98801125
+829 1740.0422  527.0862  125.0283  525.0000  125.0000   42.9066 0.15768864 0.23374318 -0.15276555 -0.03637275 0.98759289
+830 1742.2663  527.0862  175.0775  525.0000  175.0000   45.1164 0.16162969 0.32175055 -0.15266863 -0.05088954 0.98696633
+831 1745.2329  527.0862  225.1647  525.0000  225.0000   48.0628 0.16672965 0.40489179 -0.15253969 -0.06537415 0.98613278
+832 1748.9429  527.0862  275.3006  525.0000  275.0000   51.7457 0.17287785 0.48251330 -0.15237898 -0.07981756 0.98509380
+833 1753.3976  527.0862  325.4960  525.0000  325.0000   56.1653 0.17995718 0.55430750 -0.15218679 -0.09421087 0.98385136
+834 1758.5984  527.0862  375.7616  525.0000  375.0000   61.3214 0.18785135 0.62024949 -0.15196349 -0.10854535 0.98240776
+835 1764.5469  527.0862  426.1081  525.0000  425.0000   67.2142 0.19644994 0.68052122 -0.15170948 -0.12281244 0.98076569
+836 1771.2452  527.0862  476.5461  525.0000  475.0000   73.8435 0.20565143 0.73543977 -0.15142525 -0.13700379 0.97892817
+837 1778.6952  527.0862  527.0862  525.0000  525.0000   81.2095 0.21536462 0.78539816 -0.15111129 -0.15111129 0.97689854
+838 1786.8995  527.0862  577.7389  525.0000  575.0000   89.3120 0.22550881 0.83082144 -0.15076819 -0.16512707 0.97468046
+839 1795.8606  527.0862  628.5146  525.0000  625.0000   98.1511 0.23601335 0.87213650 -0.15039655 -0.17904351 0.97227789
+840 1805.5815  527.0862  679.4237  525.0000  675.0000  107.7269 0.24681679 0.90975316 -0.14999702 -0.19285332 0.96969505
+841 1804.0851  577.7389 -628.5146  575.0000 -625.0000  106.2537 0.24519062 5.45614456 -0.16434955 0.17864081 0.97009107
+842 1795.1134  577.7389 -577.7389  575.0000 -575.0000   97.4146 0.23515848 5.49778714 -0.16475384 0.16475384 0.97247743
+843 1786.8995  577.7389 -527.0862  575.0000 -525.0000   89.3120 0.22550881 5.54321042 -0.16512707 0.15076819 0.97468046
+844 1779.4406  577.7389 -476.5461  575.0000 -475.0000   81.9461 0.21630908 5.59273884 -0.16546858 0.13669143 0.97669627
+845 1772.7345  577.7389 -426.1081  575.0000 -425.0000   75.3167 0.20763480 5.64667708 -0.16577776 0.12253139 0.97852123
+846 1766.7790  577.7389 -375.7616  575.0000 -375.0000   69.4240 0.19956941 5.70528336 -0.16605404 0.10829611 0.98015203
+847 1761.5720  577.7389 -325.4960  575.0000 -325.0000   64.2678 0.19220353 5.76873399 -0.16629693 0.09399392 0.98158569
+848 1757.1121  577.7389 -275.3006  575.0000 -275.0000   59.8483 0.18563326 5.83707975 -0.16650597 0.07963329 0.98281957
+849 1753.3976  577.7389 -225.1647  575.0000 -225.0000   56.1653 0.17995718 5.91019758 -0.16668077 0.06522291 0.98385136
+850 1750.4275  577.7389 -175.0775  575.0000 -175.0000   53.2189 0.17527207 5.98774446 -0.16682101 0.05077161 0.98467913
+851 1748.2008  577.7389 -125.0283  575.0000 -125.0000   51.0091 0.17166719 6.06912462 -0.16692642 0.03628835 0.98530134
+852 1746.7167  577.7389  -75.0061  575.0000  -75.0000   49.5359 0.16921782 6.15348276 -0.16699681 0.02178219 0.98571680
+853 1745.9748  577.7389  -25.0002  575.0000  -25.0000   48.7994 0.16797869 6.23973440 -0.16703203 0.00726226 0.98592472
+854 1745.9748  577.7389   25.0002  575.0000   25.0000   48.7994 0.16797869 0.04345090 -0.16703203 -0.00726226 0.98592472
+855 1746.7167  577.7389   75.0061  575.0000   75.0000   49.5359 0.16921782 0.12970254 -0.16699681 -0.02178219 0.98571680
+856 1748.2008  577.7389  125.0283  575.0000  125.0000   51.0091 0.17166719 0.21406068 -0.16692642 -0.03628835 0.98530134
+857 1750.4275  577.7389  175.0775  575.0000  175.0000   53.2189 0.17527207 0.29544084 -0.16682101 -0.05077161 0.98467913
+858 1753.3976  577.7389  225.1647  575.0000  225.0000   56.1653 0.17995718 0.37298772 -0.16668077 -0.06522291 0.98385136
+859 1757.1121  577.7389  275.3006  575.0000  275.0000   59.8483 0.18563326 0.44610555 -0.16650597 -0.07963329 0.98281957
+860 1761.5720  577.7389  325.4960  575.0000  325.0000   64.2678 0.19220353 0.51445131 -0.16629693 -0.09399392 0.98158569
+861 1766.7790  577.7389  375.7616  575.0000  375.0000   69.4240 0.19956941 0.57790194 -0.16605404 -0.10829611 0.98015203
+862 1772.7345  577.7389  426.1081  575.0000  425.0000   75.3167 0.20763480 0.63650822 -0.16577776 -0.12253139 0.97852123
+863 1779.4406  577.7389  476.5461  575.0000  475.0000   81.9461 0.21630908 0.69044646 -0.16546858 -0.13669143 0.97669627
+864 1786.8995  577.7389  527.0862  575.0000  525.0000   89.3120 0.22550881 0.73997488 -0.16512707 -0.15076819 0.97468046
+865 1795.1134  577.7389  577.7389  575.0000  575.0000   97.4146 0.23515848 0.78539816 -0.16475384 -0.16475384 0.97247743
+866 1804.0851  577.7389  628.5146  575.0000  625.0000  106.2537 0.24519062 0.82704074 -0.16434955 -0.17864081 0.97009107
+867 1804.0851  628.5146 -577.7389  625.0000 -575.0000  106.2537 0.24519062 5.53942972 -0.17864081 0.16434955 0.97009107
+868 1795.8606  628.5146 -527.0862  625.0000 -525.0000   98.1511 0.23601335 5.58452548 -0.17904351 0.15039655 0.97227789
+869 1788.3922  628.5146 -476.5461  625.0000 -475.0000   90.7852 0.22729817 5.63331485 -0.17941198 0.13635310 0.97427880
+870 1781.6775  628.5146 -426.1081  625.0000 -425.0000   84.1559 0.21911494 5.68600864 -0.17974555 0.12222697 0.97609021
+871 1775.7142  628.5146 -375.7616  625.0000 -375.0000   78.2631 0.21153930 5.74276580 -0.18004362 0.10802617 0.97770887
+872 1770.5006  628.5146 -325.4960  625.0000 -325.0000   73.1070 0.20465171 5.80366601 -0.18030565 0.09375894 0.97913183
+873 1766.0349  628.5146 -275.3006  625.0000 -275.0000   68.6874 0.19853561 5.86867843 -0.18053117 0.07943371 0.98035646
+874 1762.3156  628.5146 -225.1647  625.0000 -225.0000   65.0044 0.19327477 5.93762972 -0.18071974 0.06505911 0.98138050
+875 1759.3417  628.5146 -175.0775  625.0000 -175.0000   62.0580 0.18894971 6.01017660 -0.18087103 0.05064389 0.98220205
+876 1757.1121  628.5146 -125.0283  625.0000 -125.0000   59.8483 0.18563326 6.08578974 -0.18098475 0.03619695 0.98281957
+877 1755.6261  628.5146  -75.0061  625.0000  -75.0000   58.3751 0.18338581 6.16375637 -0.18106068 0.02172728 0.98323189
+878 1754.8832  628.5146  -25.0002  625.0000  -25.0000   57.6385 0.18225074 6.24320661 -0.18109868 0.00724395 0.98343825
+879 1754.8832  628.5146   25.0002  625.0000   25.0000   57.6385 0.18225074 0.03997869 -0.18109868 -0.00724395 0.98343825
+880 1755.6261  628.5146   75.0061  625.0000   75.0000   58.3751 0.18338581 0.11942893 -0.18106068 -0.02172728 0.98323189
+881 1757.1121  628.5146  125.0283  625.0000  125.0000   59.8483 0.18563326 0.19739556 -0.18098475 -0.03619695 0.98281957
+882 1759.3417  628.5146  175.0775  625.0000  175.0000   62.0580 0.18894971 0.27300870 -0.18087103 -0.05064389 0.98220205
+883 1762.3156  628.5146  225.1647  625.0000  225.0000   65.0044 0.19327477 0.34555558 -0.18071974 -0.06505911 0.98138050
+884 1766.0349  628.5146  275.3006  625.0000  275.0000   68.6874 0.19853561 0.41450687 -0.18053117 -0.07943371 0.98035646
+885 1770.5006  628.5146  325.4960  625.0000  325.0000   73.1070 0.20465171 0.47951929 -0.18030565 -0.09375894 0.97913183
+886 1775.7142  628.5146  375.7616  625.0000  375.0000   78.2631 0.21153930 0.54041950 -0.18004362 -0.10802617 0.97770887
+887 1781.6775  628.5146  426.1081  625.0000  425.0000   84.1559 0.21911494 0.59717666 -0.17974555 -0.12222697 0.97609021
+888 1788.3922  628.5146  476.5461  625.0000  475.0000   90.7852 0.22729817 0.64987045 -0.17941198 -0.13635310 0.97427880
+889 1795.8606  628.5146  527.0862  625.0000  525.0000   98.1511 0.23601335 0.69865982 -0.17904351 -0.15039655 0.97227789
+890 1804.0851  628.5146  577.7389  625.0000  575.0000  106.2537 0.24519062 0.74375558 -0.17864081 -0.16434955 0.97009107
+891 1805.5815  679.4237 -527.0862  675.0000 -525.0000  107.7269 0.24681679 5.62214213 -0.19285332 0.14999702 0.96969505
+892 1798.1027  679.4237 -476.5461  675.0000 -475.0000  100.3609 0.23855678 5.66997795 -0.19324809 0.13598940 0.97168002
+893 1791.3786  679.4237 -426.1081  675.0000 -425.0000   93.7316 0.23082950 5.72126374 -0.19360546 0.12189974 0.97347695
+894 1785.4071  679.4237 -375.7616  675.0000 -375.0000   87.8388 0.22370314 5.77608680 -0.19392480 0.10773600 0.97508263
+895 1780.1862  679.4237 -325.4960  675.0000 -325.0000   82.6827 0.21724891 5.83446196 -0.19420552 0.09350636 0.97649413
+896 1775.7142  679.4237 -275.3006  675.0000 -275.0000   78.2631 0.21153930 5.89630958 -0.19444711 0.07921919 0.97770887
+897 1771.9898  679.4237 -225.1647  675.0000 -225.0000   74.5801 0.20664577 5.96143475 -0.19464912 0.06488304 0.97872463
+898 1769.0117  679.4237 -175.0775  675.0000 -175.0000   71.6338 0.20263578 6.02951120 -0.19481119 0.05050660 0.97953953
+899 1766.7790  679.4237 -125.0283  675.0000 -125.0000   69.4240 0.19956941 6.10007448 -0.19493301 0.03609870 0.98015203
+900 1765.2909  679.4237  -75.0061  675.0000  -75.0000   67.9508 0.19749582 6.17252808 -0.19501434 0.02166826 0.98056101
+901 1764.5469  679.4237  -25.0002  675.0000  -25.0000   67.2142 0.19644994 6.24616518 -0.19505505 0.00722426 0.98076569
+902 1764.5469  679.4237   25.0002  675.0000   25.0000   67.2142 0.19644994 0.03702012 -0.19505505 -0.00722426 0.98076569
+903 1765.2909  679.4237   75.0061  675.0000   75.0000   67.9508 0.19749582 0.11065722 -0.19501434 -0.02166826 0.98056101
+904 1766.7790  679.4237  125.0283  675.0000  125.0000   69.4240 0.19956941 0.18311082 -0.19493301 -0.03609870 0.98015203
+905 1769.0117  679.4237  175.0775  675.0000  175.0000   71.6338 0.20263578 0.25367410 -0.19481119 -0.05050660 0.97953953
+906 1771.9898  679.4237  225.1647  675.0000  225.0000   74.5801 0.20664577 0.32175055 -0.19464912 -0.06488304 0.97872463
+907 1775.7142  679.4237  275.3006  675.0000  275.0000   78.2631 0.21153930 0.38687572 -0.19444711 -0.07921919 0.97770887
+908 1780.1862  679.4237  325.4960  675.0000  325.0000   82.6827 0.21724891 0.44872334 -0.19420552 -0.09350636 0.97649413
+909 1785.4071  679.4237  375.7616  675.0000  375.0000   87.8388 0.22370314 0.50709850 -0.19392480 -0.10773600 0.97508263
+910 1791.3786  679.4237  426.1081  675.0000  425.0000   93.7316 0.23082950 0.56192156 -0.19360546 -0.12189974 0.97347695
+911 1798.1027  679.4237  476.5461  675.0000  475.0000  100.3609 0.23855678 0.61320735 -0.19324809 -0.13598940 0.97168002
+912 1805.5815  679.4237  527.0862  675.0000  525.0000  107.7269 0.24681679 0.66104317 -0.19285332 -0.14999702 0.96969505
+913 1808.5752  730.4765 -476.5461  725.0000 -475.0000  110.6732 0.25003217 5.70318253 -0.20696987 0.13560095 0.96890446
+914 1801.8411  730.4765 -426.1081  725.0000 -425.0000  104.0439 0.24272757 5.75296953 -0.20735043 0.12155025 0.97068601
+915 1795.8606  730.4765 -375.7616  725.0000 -375.0000   98.1511 0.23601335 5.80583992 -0.20769047 0.10742611 0.97227789
+916 1790.6319  730.4765 -325.4960  725.0000 -325.0000   92.9950 0.22995247 5.86176609 -0.20798939 0.09323662 0.97367723
+917 1786.1532  730.4765 -275.3006  725.0000 -275.0000   88.5754 0.22460804 5.92064106 -0.20824663 0.07899010 0.97488148
+918 1782.4232  730.4765 -225.1647  725.0000 -225.0000   84.8925 0.22004125 5.98226507 -0.20846173 0.06469502 0.97588845
+919 1779.4406  730.4765 -175.0775  725.0000 -175.0000   81.9461 0.21630908 6.04633654 -0.20863429 0.05036000 0.97669627
+920 1777.2046  730.4765 -125.0283  725.0000 -125.0000   79.7363 0.21346159 6.11245009 -0.20876400 0.03599379 0.97730345
+921 1775.7142  730.4765  -75.0061  725.0000  -75.0000   78.2631 0.21153930 6.18010369 -0.20885060 0.02160523 0.97770887
+922 1774.9692  730.4765  -25.0002  725.0000  -25.0000   77.5265 0.21057077 6.24871620 -0.20889394 0.00720324 0.97791177
+923 1774.9692  730.4765   25.0002  725.0000   25.0000   77.5265 0.21057077 0.03446910 -0.20889394 -0.00720324 0.97791177
+924 1775.7142  730.4765   75.0061  725.0000   75.0000   78.2631 0.21153930 0.10308161 -0.20885060 -0.02160523 0.97770887
+925 1777.2046  730.4765  125.0283  725.0000  125.0000   79.7363 0.21346159 0.17073521 -0.20876400 -0.03599379 0.97730345
+926 1779.4406  730.4765  175.0775  725.0000  175.0000   81.9461 0.21630908 0.23684876 -0.20863429 -0.05036000 0.97669627
+927 1782.4232  730.4765  225.1647  725.0000  225.0000   84.8925 0.22004125 0.30092023 -0.20846173 -0.06469502 0.97588845
+928 1786.1532  730.4765  275.3006  725.0000  275.0000   88.5754 0.22460804 0.36254424 -0.20824663 -0.07899010 0.97488148
+929 1790.6319  730.4765  325.4960  725.0000  325.0000   92.9950 0.22995247 0.42141921 -0.20798939 -0.09323662 0.97367723
+930 1795.8606  730.4765  375.7616  725.0000  375.0000   98.1511 0.23601335 0.47734538 -0.20769047 -0.10742611 0.97227789
+931 1801.8411  730.4765  426.1081  725.0000  425.0000  104.0439 0.24272757 0.53021577 -0.20735043 -0.12155025 0.97068601
+932 1808.5752  730.4765  476.5461  725.0000  475.0000  110.6732 0.25003217 0.58000277 -0.20696987 -0.13560095 0.96890446
+933 1813.0683  781.6832 -426.1081  775.0000 -425.0000  115.0928 0.25476639 5.78158125 -0.22097369 0.12117912 0.96772220
+934 1807.0782  781.6832 -375.7616  775.0000 -375.0000  109.2001 0.24843056 5.83252397 -0.22133386 0.10709703 0.96929951
+935 1801.8411  781.6832 -325.4960  775.0000 -325.0000  104.0439 0.24272757 5.88610585 -0.22165046 0.09295019 0.97068601
+936 1797.3553  781.6832 -275.3006  775.0000 -275.0000   99.6243 0.23771246 5.94220635 -0.22192291 0.07874684 0.97187919
+937 1793.6193  781.6832 -225.1647  775.0000 -225.0000   95.9414 0.23343795 6.00063035 -0.22215073 0.06449537 0.97287687
+938 1790.6319  781.6832 -175.0775  775.0000 -175.0000   92.9950 0.22995247 6.06110340 -0.22233349 0.05020434 0.97367723
+939 1788.3922  781.6832 -125.0283  775.0000 -125.0000   90.7852 0.22729817 6.12327218 -0.22247085 0.03588240 0.97427880
+940 1786.8995  781.6832  -75.0061  775.0000  -75.0000   89.3120 0.22550881 6.18671152 -0.22256257 0.02153831 0.97468046
+941 1786.1532  781.6832  -25.0002  775.0000  -25.0000   88.5754 0.22460804 6.25093842 -0.22260847 0.00718092 0.97488148
+942 1786.1532  781.6832   25.0002  775.0000   25.0000   88.5754 0.22460804 0.03224688 -0.22260847 -0.00718092 0.97488148
+943 1786.8995  781.6832   75.0061  775.0000   75.0000   89.3120 0.22550881 0.09647378 -0.22256257 -0.02153831 0.97468046
+944 1788.3922  781.6832  125.0283  775.0000  125.0000   90.7852 0.22729817 0.15991312 -0.22247085 -0.03588240 0.97427880
+945 1790.6319  781.6832  175.0775  775.0000  175.0000   92.9950 0.22995247 0.22208190 -0.22233349 -0.05020434 0.97367723
+946 1793.6193  781.6832  225.1647  775.0000  225.0000   95.9414 0.23343795 0.28255495 -0.22215073 -0.06449537 0.97287687
+947 1797.3553  781.6832  275.3006  775.0000  275.0000   99.6243 0.23771246 0.34097895 -0.22192291 -0.07874684 0.97187919
+948 1801.8411  781.6832  325.4960  775.0000  325.0000  104.0439 0.24272757 0.39707945 -0.22165046 -0.09295019 0.97068601
+949 1807.0782  781.6832  375.7616  775.0000  375.0000  109.2001 0.24843056 0.45066133 -0.22133386 -0.10709703 0.96929951
+950 1813.0683  781.6832  426.1081  775.0000  425.0000  115.0928 0.25476639 0.50160405 -0.22097369 -0.12117912 0.96772220
+951 1819.0634  833.0538 -375.7616  825.0000 -375.0000  120.9856 0.26092194 5.85655781 -0.23484851 0.10674932 0.96615255
+952 1813.8174  833.0538 -325.4960  825.0000 -325.0000  115.8294 0.25554542 5.90791448 -0.23518226 0.09264756 0.96752557
+953 1809.3239  833.0538 -275.3006  825.0000 -275.0000  111.4098 0.25082849 5.96143475 -0.23546947 0.07848982 0.96870712
+954 1805.5815  833.0538 -225.1647  825.0000 -225.0000  107.7269 0.24681679 6.01693325 -0.23570961 0.06428444 0.96969505
+955 1802.5890  833.0538 -175.0775  825.0000 -175.0000  104.7805 0.24355180 6.07416236 -0.23590225 0.05003987 0.97048758
+956 1800.3455  833.0538 -125.0283  825.0000 -125.0000  102.5707 0.24106928 6.13281387 -0.23604705 0.03576470 0.97108325
+957 1798.1027  833.0538  -25.0002  825.0000  -25.0000  100.3609 0.23855678 6.25289154 -0.23619211 0.00715734 0.97168002
+958 1798.1027  833.0538   25.0002  825.0000   25.0000  100.3609 0.23855678 0.03029376 -0.23619211 -0.00715734 0.97168002
+959 1800.3455  833.0538  125.0283  825.0000  125.0000  102.5707 0.24106928 0.15037143 -0.23604705 -0.03576470 0.97108325
+960 1802.5890  833.0538  175.0775  825.0000  175.0000  104.7805 0.24355180 0.20902294 -0.23590225 -0.05003987 0.97048758
+961 1805.5815  833.0538  225.1647  825.0000  225.0000  107.7269 0.24681679 0.26625205 -0.23570961 -0.06428444 0.96969505
+962 1809.3239  833.0538  275.3006  825.0000  275.0000  111.4098 0.25082849 0.32175055 -0.23546947 -0.07848982 0.96870712
+963 1813.8174  833.0538  325.4960  825.0000  325.0000  115.8294 0.25554542 0.37527082 -0.23518226 -0.09264756 0.96752557
+964 1819.0634  833.0538  375.7616  825.0000  375.0000  120.9856 0.26092194 0.42662749 -0.23484851 -0.10674932 0.96615255
+#
+#
+# 2004/11/21 A. Moralejo
+#
+# Implemented current geometry of 964 mirrors, but with no chessboarding.
+# It is more versatile to produce the reflected files with no chessboarding, 
+# and simulate the effect of chessboarding on the timing the camera 
+# simulation. The spot size is not affected by the chessboarding if the 
+# mirror dish elements are correctly oriented.
+#
+# 2003/12/18 10:24:18  moralejo
+#
+# Removed some obsolete command from the definitions file. Added a comment
+# on the meaning of the point_spread option.
+#
+# 2002/11/13 A. Moralejo
+#
+# New mirrors data: now 956 mirrors as in the final design. The focal lengths,
+# x, and y, taken from Razmick. z and the mirror orientations are calculated 
+# as for a paraboloid of 1697 cm focal, so that objects at 10 km will be 
+# focused on the camera placed at 1700 cm.
+#
+# 2002/05/04 A. Moralejo
+#
+# Camera radius set to 70 cm to reduce output (70 cm is more than enough 
+#   for camera program!)
+#
+# 2001/07/18 08:43:52  bigongia
+# Camera outer radius set equal to 100cm instead of 1000cm !!! C.Bigongiari
+#
+# 2000/02/09 09:14:43  harald
+# The data file "magic.def" was changed because there will be no gap-pixels
+# in the MAGIC-camera design. Now there are only 577 pixels.
+#
+# 1999/11/08 09:44:04  harald
+# In this directory you can find the files which describes the geometry and
+# response of the different components of MAGIC. For example the files 
+# magic.def sets up the geometry of the telescope. Alternatively you can use
+# ct1.def for the HEGRA-telescope No 1. 
+#
+# The reflector program needs also the reflectivity.dat file. 
+#
+# 1999/10/22 15:01:29  petry
+# version sent to H.K. and N.M. on Fri Oct 22 1999
+#
+#
+#EOF
Index: branches/Mars_McMismatchStudy/resources/pedestalref_mux.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/pedestalref_mux.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/pedestalref_mux.rc	(revision 17960)
@@ -0,0 +1,41 @@
+#
+# Reference lines and histogram limits for the data check in pedestal files
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+PedestalMin:                 0.
+PedestalMax:                 18.
+#
+# Pedestal RMS:
+#
+PedRmsMin:                   0.
+PedRmsMax:                   3.
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+RefPedClosedLids:            9.635
+RefPedExtraGalactic:         9.93
+RefPedGalactic:              10.03
+
+#
+# Pedestal RMS:
+#
+RefPedRmsClosedLidsInner:    0.37
+RefPedRmsExtraGalacticInner: 1.2
+RefPedRmsGalacticInner:      1.5
+
+RefPedRmsClosedLidsOuter:    0.49
+RefPedRmsExtraGalacticOuter: 0.96
+RefPedRmsGalacticOuter:      1.2
Index: branches/Mars_McMismatchStudy/resources/sequences.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/sequences.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/sequences.rc	(revision 17960)
@@ -0,0 +1,246 @@
+#/////////////////////////////////////////////////////////////////////////
+#
+# This file is compiled from two sections. One defines which transitions
+# are allowed to build a sequence (for example changing L1 Trigger
+# Tables between Calibration and Pedestal runs). The other section 
+# defines a regular expression to define the allowed ordering
+# of the P-, C- and D-runs.
+#
+# The sections a introduced by [Transition] and [Regexp]. For further
+# details see below.
+#
+# If a section should be valid only for one telescope use:
+#   [Transition]         # Valid for all telescope numbers
+#   [Transition 5]       # Valid for telescope 5
+#   [Transition: 5]      # Valid for telescope 5
+#   [Transition: 5 6]    # Valid for telescopes 5 and 6
+#
+#
+# File-Id:
+#   A file is uniquely identified by run-number and file-number.
+#   If you give just a number it is identical to run-number with
+#   file-number 0. To give a dedicated file-number you can use:
+#     run.file
+#
+#/////////////////////////////////////////////////////////////////////////
+
+##########################################################################
+#
+# Explanation [Transition]
+#
+# Rules to build blocks which will later be broken into sequences
+#
+# Syntax:
+#
+# [Transition]
+# rule1
+# rule2
+# rule3
+#
+#
+# Colums of rule:
+# 0 [1 2 3 4 [5 [6]]]
+# 
+# 0: Table/Column to which the transition is applied
+# 1: Run type of previous run
+# 2: Run type of run to be accepted
+# 3: Key for previous run
+# 4: key for run to be accepted
+# 5: first file-id to apply this rule <default=0>
+# 6: last  file-id to apply this rule <default=max>
+#
+# Run Types:
+#  D  2
+#  P  3
+#  C  4
+#
+# The columns 1-4 can be expressed as regular expressions (ala TRegexp)
+# a ^ is prepended and a $ is appended automatically.
+#
+# A single "*" is an abbreviation for the regexp ".*" .
+#
+# As soon as any transition (column 0) is specified this transisiton 
+# is checked not to change within a sequence.
+#
+# A "-" is an abbreviation for transitions "to be ignored". For example:
+#     [Transition]
+#     Test - 4 * 1200 1300
+# would mean:
+#     ignore all keys (*) of column test for all current files
+#     with run-type 4 if its file-id is between 1200.0 and 1300.0
+#     The (former) third column in this case is obsolete.
+#
+# Each Transition which appears at least once is checked.
+#
+
+[Transition: 1]
+
+# Ignore project name for calibration files between 20100 and 45100
+Project           - 4 *    20100 45100
+HvSettings        - 2 *    86094 86094
+TriggerDelayTable
+ObservationMode
+
+# Transition setup for L1/2-TriggerTable of very old data
+L1TriggerTable  3 2  1 [235]  26206 35478
+L1TriggerTable  2 3  [235] 1  26206 35478
+
+L1TriggerTable  - [^2] * 0 26830
+L2TriggerTable  - [^2] * 0 26830
+
+L1TriggerTable  2 4  3 1  26816 39429
+
+L2TriggerTable  3 2  7 2  36049 38012
+L2TriggerTable  2 3  2 7  36053 38011
+
+L2TriggerTable  4 3  9 7  20170 37382
+L2TriggerTable  3 4  7 9  22712 37935
+
+L2TriggerTable  3 2  7 5  26207 35455
+L2TriggerTable  2 3  5 7  26207 35477
+
+L2TriggerTable  4 2  9 2  36157 37938
+L2TriggerTable  4 3  5 7  26207 35477
+L2TriggerTable  3 2  7 5  35460 36478
+L2TriggerTable  2 4  5 9  27170 31869
+
+
+# The Discriminator Thresholds do not influence the pedestal- and
+# calibration-trigger and need therefore not to be checked for these runs.
+# This allows all kind of transitions from P/C to P/C and from C to D.
+DiscriminatorThresholdTable  [34]  [34]   *   *
+DiscriminatorThresholdTable    4     2    *   *
+
+# This defines which changes in the calibration script are allowed
+# P 177: CPedestals_500Hz
+# P 199: Pedestals_500Hz
+# C 180: 23Led_Blue
+# C 181: 10_Led_UV
+# C 182: 1Led_Green
+# C 183: 10Led_Blue
+# C 195: 1Led_Blue
+# C 207: 10Led_UV_PinDiode
+# C 256: 10Led_UV_PEDANDCAL_1kHz
+# D 179: 10Led_UV_50Hz
+# D 209: 10Led_UV_50Hz_PinDiode
+# D 238: 10Led_UV_50Hz_PinDiode.  <---  has an additional dot
+# D 188: 10Led_UV_train50Hz
+# D 200: 10Led_UV_train50Hz_PinDiode
+# D 210: 10Led_Blue_50Hz
+# D 245: 10Led_UV_50Hz_Ped
+
+# Current DEFAULT setup. This what is used to build the
+# sequences from the newest data
+CalibrationScript  2 3  209 199                      79266 200000
+CalibrationScript  3 4  199 207                      50640
+CalibrationScript  4 2  207 209                      91301
+CalibrationScript  4 3  207 199                      53875 200000
+CalibrationScript  4 2  207 245                     200000
+CalibrationScript  3 4  199 256                    1007866
+CalibrationScript  4 2  256 245                    1007866
+CalibrationScript  3 4  199 181                    1007844
+CalibrationScript  4 2  181 245                    1007844
+
+# Previous defaults. This are cases which are widely used
+# through our data and can thus be considered old defaults
+CalibrationScript  4 2  181 179                      46305 50600
+CalibrationScript  4 2  207 209                      50641 84570
+CalibrationScript  4 2  207 179                      50879 91252
+CalibrationScript  2 3  179 199                      46313 91423
+CalibrationScript  2 3  209 199                      50784 79256
+CalibrationScript  3 2  199 179                      46313 90220
+
+CalibrationScript  3 2  199 209                      50785 57781
+CalibrationScript  3 4  199 181                      45730 50805
+
+# This was used only in some rare cases (still to be checked!)
+# This are cases used through a big part of our data
+# but take place only in some single cases.
+CalibrationScript  4 3  181 199                      46405 50137
+CalibrationScript  3 4  199 181                      67116 68714
+CalibrationScript  2 4  179 207                      87824 87842
+
+# Single calibration runs inbetween data. Should be
+# excluded differently, because these blocks will not
+# give valid sequences anyhow
+CalibrationScript  2 4  179 207                      68731 68731
+CalibrationScript  2 4  179 207                      61374 61459
+CalibrationScript  2 4  179 207                      53901 53901
+CalibrationScript  2 4  179 207                      51153 51170
+CalibrationScript  2 4  188 181                      50084 50084
+CalibrationScript  2 4  209 207                      96951 96951
+
+# For some reasons here are two consecutive calibration
+# runs with two different colors (still to be checked!)
+CalibrationScript  4 4  181 183                      51173 51173
+
+# Special setup for more than one C-Run. Old data had several
+# calibration runs with different taken sequentually
+CalibrationScript  4 4  (181|195) (182|183|193|195)  44834 45579
+
+# This was a typo 238 is basically the same as 209
+CalibrationScript  4 2  207 238                      78696 78696
+
+# This is for runs with special calibration scripts (177,188,200,210)
+CalibrationScript  2 3  (179|188|200) (177|199)      44831 46223
+CalibrationScript  3 2  (177|199) (179|188|200)      44831 46223
+CalibrationScript  4 2  (181|182|195) (188|200)      44831 46223
+CalibrationScript  3 4  177 (181|195)                44831 45718
+CalibrationScript  4 3  181 177                      44831 45717
+CalibrationScript  4 2  181 188                      50083 50273
+CalibrationScript  3 2  199 188                      50083 50273
+CalibrationScript  2 3  188 199                      50083 50273
+CalibrationScript  4 2  207 210                      50687 50746
+CalibrationScript  2 3  210 199                      50687 50746
+CalibrationScript  3 2  199 210                      50687 50746
+
+# Special rules for calibration script 183
+CalibrationScript  2 4  209 183                      50642 50642
+CalibrationScript  4 3  183 199                      51193 51193
+CalibrationScript  2 4  179 183                      51192 51192
+CalibrationScript  4 2  183 179                      51174 51174
+
+#########################################################################
+#
+# Explanation [Regexp]
+#
+# To build sequences a string with the run-types is evaluated.
+# A capital case D or P means: The nearest C-Run is the last C-Run
+# A lower case   d or p means: The nearest C-Run is the next C-Run
+#
+# The first expression is evaluated first. The last one last.
+# If one regexp matches the others are not evaluated anymore and
+# the sequence is build from the match.
+#
+# For details on regular expressions check 
+#     http://perldoc.perl.org/perlre.html
+#
+# The syntax is
+#   [Regexp]
+#   regexp [firstrun [lastrun]]
+#
+[Regexp: 1]
+
+# Allow almost everything but require at least one run of each run-type
+[dp]*C+[PD]*(PD|DP)[DP]*                  0 32734
+[dp]*dp*C+[PD]*P[DP]*                     0 32734
+[dp]*p[dp]*C+P*D[PD]*                     0 32734
+[dp]*(dp|pd)[dp]*C+[PD]*                  0 32734
+
+# This is the "allow as much as possible" solution
+[dp]*(pC+|C+P)[PD]*D                  32735 45624
+d[dp]*(pC+|C+P)[PD]*                  32735 45624
+
+# Allow intermediate calibration and pedestal runs:
+# Since now we have  interleaved calibration events.
+[dD]*[pP]C+((([pP]|C)+[dD])|[dD])+    45625  46477
+
+# Allow intermediate pedestal runs
+#[dD]*[pP]C+(([pP]+[dD])|[dD])+       46478 53943
+[dD]*[pP]C+[pPdD]*[dD]                46478 53943
+[dD]*[pP]C+[pPdD]*[dD]                56567 57786
+[dD]*[pP]C+[pPdD]*[dD]                60145 60396
+
+# Use the minimum solution for newest date
+# Do not allow intermediate non-data runs
+[dD]*[pP]C+[dD]+                      53944
Index: branches/Mars_McMismatchStudy/resources/starguider00000001.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00000001.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00000001.txt	(revision 17960)
@@ -0,0 +1,28 @@
+MAGIC1 27.08.2007 15:55:24.179
+S   00   000000   000000  0000000
+     IA             0             0
+     IE             0             0
+   FLOP             0             0
+     AN             0             0
+     AW             0             0
+   NPAE   0.071971096   0.041230194
+     CA  -0.034559807   0.031805296
+     TF             0             0
+     TX             0             0
+   ECES  -0.017263112   0.018334716
+   ACES             0             0
+   ECEC   -0.04393912   0.022381297
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+END
+
+# This is identical with the later pointing model applied since
+# run 85420, which is done with TPoints taken after 18.3.2006 and
+# in April 2006. It seems that it is already valid earlier.
+# (For unknown reasons the pointing model made from the TPoints
+# before 18.3.2006 doesn't seem to give a reasonable pointing model)
Index: branches/Mars_McMismatchStudy/resources/starguider00081855.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00081855.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00081855.txt	(revision 17960)
@@ -0,0 +1,8 @@
+MAGIC1 27.08.2007 15:55:24.179
+S   00   000000   000000  0000000
+     DX             0             1
+     DY             0             1
+END
+
+# starguider was not working because the LEDs failed.
+# we fix the pointing to the camera center.
Index: branches/Mars_McMismatchStudy/resources/starguider00083722.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00083722.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00083722.txt	(revision 17960)
@@ -0,0 +1,28 @@
+MAGIC1 27.08.2007 15:55:24.179
+S   00   000000   000000  0000000
+     IA             0             0
+     IE             0             0
+   FLOP             0             0
+     AN             0             0
+     AW             0             0
+   NPAE   0.071971096   0.041230194
+     CA  -0.034559807   0.031805296
+     TF             0             0
+     TX             0             0
+   ECES  -0.017263112   0.018334716
+   ACES             0             0
+   ECEC   -0.04393912   0.022381297
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+END
+
+# This is identical with the later pointing model applied since
+# run 85420, which is done with TPoints taken after 18.3.2006 and
+# in April 2006. It seems that is already valid earlier. 
+# (For unknown reasons that pointing model made from the TPoints 
+#  before 18.3.2006 doesn't seem to givbe a reasonable pointing model)
Index: branches/Mars_McMismatchStudy/resources/starguider00085240.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00085240.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00085240.txt	(revision 17960)
@@ -0,0 +1,22 @@
+MAGIC1 27.08.2007 15:55:24.179
+S   00   000000   000000  0000000
+     IA             0             0
+     IE             0             0
+   FLOP             0             0
+     AN             0             0
+     AW             0             0
+   NPAE   0.071971096   0.041230194
+     CA  -0.034559807   0.031805296
+     TF             0             0
+     TX             0             0
+   ECES  -0.017263112   0.018334716
+   ACES             0             0
+   ECEC   -0.04393912   0.022381297
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+END
Index: branches/Mars_McMismatchStudy/resources/starguider00089180.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00089180.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00089180.txt	(revision 17960)
@@ -0,0 +1,24 @@
+MAGIC1 02.09.2007 15:33:54.184
+S   00   000000   000000  0000000
+     IA  0.0091653124    0.10677358
+     IE  0.0036519803    0.14318432
+   FLOP             0             0
+     AN             0             0
+     AW             0             0
+   NPAE   0.061626142    0.11449356
+     CA  -0.038609416      0.143636
+     TF             0             0
+     TX             0             0
+   ECES  -0.017894252    0.11417683
+   ACES             0             0
+   ECEC  -0.023930434    0.10645297
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+END
+
+# Made from the TPoints between: 6/2006 and 4/2007
Index: branches/Mars_McMismatchStudy/resources/starguider00267253.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00267253.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00267253.txt	(revision 17960)
@@ -0,0 +1,26 @@
+MAGIC1 14.05.2008 17:21:23.111
+S   00   000000   000000  0000000
+     IA   0.048024615    0.15793839
+     IE   0.023373063             0
+   FLOP             0             0
+     AN             0             0
+     AW             0             0
+   NPAE    0.12580911    0.25388661
+     CA  -0.094288338    0.28411493
+     TF             0             0
+     TX             0             0
+   ECES  -0.023108574             0
+   ACES             0             0
+   ECEC  -0.030961329             0
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+     PX             0             0
+     PY             0             0
+     DX             0             0
+     DY             0             0
+END
Index: branches/Mars_McMismatchStudy/resources/starguider00291104.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00291104.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00291104.txt	(revision 17960)
@@ -0,0 +1,26 @@
+MAGIC1 14.05.2008 17:22:07.016
+S   00   000000   000000  0000000
+     IA    0.14802861    0.17963736
+     IE    0.03168811             0
+   FLOP             0             0
+     AN             0             0
+     AW             0             0
+   NPAE   -0.10576412    0.26251087
+     CA    0.13224625    0.30597698
+     TF             0             0
+     TX             0             0
+   ECES  -0.025831588             0
+   ACES             0             0
+   ECEC  -0.027003308             0
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+     PX             0             0
+     PY             0             0
+     DX             0             0
+     DY             0             0
+END
Index: branches/Mars_McMismatchStudy/resources/starguider00328198.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider00328198.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider00328198.txt	(revision 17960)
@@ -0,0 +1,28 @@
+MAGIC1 01.08.2008 08:18:07.229
+S   00   000000   000000  0000000
+     IA   0.080178328             0
+     IE   0.042868848             0
+   FLOP             0             0
+     AN -0.0015023341             0
+     AW  0.0015055261             0
+   NPAE   0.018623198             0
+     CA -0.0068703229             0
+     TF             0             0
+     TX             0             0
+   ECES  -0.015364342             0
+   ACES             0             0
+   ECEC  -0.023597622             0
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+     PX             0             0
+     PY             0             0
+     DX             0             0
+     DY             0             0
+END
+
+# produced from the tpoints 15.1.08-13.7.08
Index: branches/Mars_McMismatchStudy/resources/starguider01000534.txt
===================================================================
--- branches/Mars_McMismatchStudy/resources/starguider01000534.txt	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/starguider01000534.txt	(revision 17960)
@@ -0,0 +1,28 @@
+MAGIC1 16.03.2009 15:21:30.273
+S   00   000000   000000  0000000
+     IA   0.070200182   0.015043287
+     IE   0.060144651    0.14568578
+   FLOP             0             0
+     AN             0             0
+     AW             0             0
+   NPAE             0             0
+     CA             0             0
+     TF             0             0
+     TX             0             0
+   ECES -0.0031977054    0.11771126
+   ACES             0             0
+   ECEC -0.0098906734    0.10539304
+   ACEC             0             0
+    NRX             0             0
+    NRY             0             0
+    CRX             0             0
+    CRY             0             0
+ MAGIC1             0             0
+ MAGIC2             0             0
+     PX             0             0
+     PY             0             0
+     DX             0             0
+     DY             0             0
+END
+
+# From 07/08-09/01 (starg200808.col)
Index: branches/Mars_McMismatchStudy/resources/steps.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/steps.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/steps.rc	(revision 17960)
@@ -0,0 +1,239 @@
+#primaries:
+SequenceBuildStatus.Primary: fDate fTelescopeNumber
+RunProcessStatus.Primary: fRunNumber fTelescopeNumber fFileNumber
+SequenceProcessStatus.Primary: fSequenceFirst fTelescopeNumber
+DataSetProcessStatus.Primary: fDataSetNumber
+MCRunProcessStatus.Primary: fMCRunNumber 
+
+#--------------------------------------------------------------------
+
+#SequenceBuildStatus.fDate: 
+SequenceBuildStatus.fDate.Default: yes
+#SequenceBuildStatus.fDate.Needs: -
+SequenceBuildStatus.fDate.Influences: SequenceBuildStatus.fExclusionsDone SequenceBuildStatus.fSequenceEntriesBuilt 
+SequenceBuildStatus.fDate.Reset: yes
+
+#SequenceBuildStatus.fCCFilled:
+SequenceBuildStatus.fCCFilled.Default: no
+SequenceBuildStatus.fCCFilled.Needs: SequenceBuildStatus.fDate
+SequenceBuildStatus.fCCFilled.Influences: SequenceBuildStatus.fExclusionsDone SequenceBuildStatus.fSequenceEntriesBuilt 
+SequenceBuildStatus.fCCFilled.Reset: yes
+
+#SequenceBuildStatus.fExclusionsDone: 
+SequenceBuildStatus.fExclusionsDone.Default: no
+SequenceBuildStatus.fExclusionsDone.Needs: SequenceBuildStatus.fCCFilled 
+SequenceBuildStatus.fExclusionsDone.Influences: SequenceBuildStatus.fSequenceEntriesBuilt 
+SequenceBuildStatus.fExclusionsDone.Reset: yes
+
+#SequenceBuildStatus.fSequenceEntriesBuilt: 
+SequenceBuildStatus.fSequenceEntriesBuilt.Default: no
+SequenceBuildStatus.fSequenceEntriesBuilt.Needs: SequenceBuildStatus.fCCFilled SequenceBuildStatus.fExclusionsDone 
+#SequenceBuildStatus.fSequenceEntriesBuilt.Influences: 
+SequenceBuildStatus.fSequenceEntriesBuilt.Reset: yes
+
+#--------------------------------------------------------------------
+
+#RunProcessStatus.fRunNumber: 
+RunProcessStatus.fRunNumber.Default: yes
+#RunProcessStatus.fRunNumber.Needs: - 
+RunProcessStatus.fRunNumber.Influences: RunProcessStatus.fCCFileAvail RunProcessStatus.fCaCoFileAvail RunProcessStatus.fCaCoFileFound RunProcessStatus.fRawFileAvail RunProcessStatus.fMerpp RunProcessStatus.fMerppCCUpdate RunProcessStatus.fMerppCaCoUpdate
+RunProcessStatus.fRunNumber.Reset: yes 
+
+#RunProcessStatus.fRawFileAvail: 
+RunProcessStatus.fRawFileAvail.Default: no
+#RunProcessStatus.fRawFileAvail.Needs: - 
+#RunProcessStatus.fRawFileAvail.Influences: RunProcessStatus.fTimingCorrection RunProcessStatus.fDataCheckDone RunProcessStatus.fMerpp RunProcessStatus.fMerppCCUpdate RunProcessStatus.fMerppCaCoUpdate
+RunProcessStatus.fRawFileAvail.Reset: yes 
+
+#RunProcessStatus.fCCFileAvail: 
+RunProcessStatus.fCCFileAvail.Default: no
+#RunProcessStatus.fCCFileAvail.Needs: - 
+#RunProcessStatus.fCCFileAvail.Influences: RunProcessStatus.fMerppCCUpdate RunProcessStatus.fMerppCaCoUpdate
+RunProcessStatus.fCCFileAvail.Reset: yes 
+
+#RunProcessStatus.fCaCoFileAvail: 
+RunProcessStatus.fCaCoFileAvail.Default: no
+#RunProcessStatus.fCaCoFileAvail.Needs: - 
+#RunProcessStatus.fCaCoFileAvail.Influences: RunProcessStatus.fMerppCaCoUpdate
+RunProcessStatus.fCaCoFileAvail.Reset: yes 
+
+#RunProcessStatus.fCaCoFileFound: 
+RunProcessStatus.fCaCoFileFound.Default: no
+#RunProcessStatus.fCaCoFileFound.Needs: - 
+#RunProcessStatus.fCaCoFileFound.Influences: RunProcessStatus.fMerppCaCoUpdate
+RunProcessStatus.fCaCoFileFound.Reset: yes 
+
+#RunProcessStatus.fDataCheckDone: 
+RunProcessStatus.fDataCheckDone.Default: no
+RunProcessStatus.fDataCheckDone.Needs: RunProcessStatus.fRawFileAvail
+#RunProcessStatus.fDataCheckDone.Influences: -
+RunProcessStatus.fDataCheckDone.Reset: yes 
+
+#RunProcessStatus.fTimingCorrection: 
+RunProcessStatus.fTimingCorrection.Default: check
+RunProcessStatus.fTimingCorrection.Needs: RunProcessStatus.fRawFileAvail
+RunProcessStatus.fTimingCorrection.Influences: RunProcessStatus.fMerpp RunProcessStatus.fMerppCCUpdate RunProcessStatus.fMerppCaCoUpdate
+RunProcessStatus.fTimingCorrection.Reset: yes 
+
+#RunProcessStatus.fCompmux:
+RunProcessStatus.fCompmux.Default: check
+RunProcessStatus.fCompmux.Needs: RunProcessStatus.fRawFileAvail
+RunProcessStatus.fCompmux.Influences: RunProcessStatus.fMerpp RunProcessStatus.fMerppCCUpdate RunProcessStatus.fMerppCaCoUpdate
+RunProcessStatus.fCompmux.Reset: yes
+
+#--------------------------------------------------------------------
+
+#SequenceProcessStatus.fSequenceFirst: 
+SequenceProcessStatus.fSequenceFirst.Default: yes
+#SequenceProcessStatus.fSequenceFirst.Needs: -
+SequenceProcessStatus.fSequenceFirst.Influences: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto SequenceProcessStatus.fFillCallisto SequenceProcessStatus.fStar SequenceProcessStatus.fFillStar
+SequenceProcessStatus.fSequenceFirst.Reset: yes
+
+#SequenceProcessStatus.fSequenceFileWritten: 
+SequenceProcessStatus.fSequenceFileWritten.Default: check
+SequenceProcessStatus.fSequenceFileWritten.Needs: SequenceProcessStatus.fSequenceFirst
+SequenceProcessStatus.fSequenceFileWritten.Influences: SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto SequenceProcessStatus.fFillCallisto SequenceProcessStatus.fStar SequenceProcessStatus.fFillStar SequenceProcessStatus.fWebCalib SequenceProcessStatus.fWebSignal SequenceProcessStatus.fWebStar
+SequenceProcessStatus.fSequenceFileWritten.Reset: yes 
+
+#SequenceProcessStatus.fAllFilesAvail: 
+SequenceProcessStatus.fAllFilesAvail.Default: no
+SequenceProcessStatus.fAllFilesAvail.Needs: SequenceProcessStatus.fSequenceFileWritten
+SequenceProcessStatus.fAllFilesAvail.Influences: SequenceProcessStatus.fCallisto SequenceProcessStatus.fFillCallisto SequenceProcessStatus.fStar SequenceProcessStatus.fFillStar SequenceProcessStatus.fWebCalib SequenceProcessStatus.fWebSignal SequenceProcessStatus.fWebStar
+SequenceProcessStatus.fAllFilesAvail.Reset: yes
+
+#SequenceProcessStatus.fCallisto: 
+SequenceProcessStatus.fCallisto.Default: no
+SequenceProcessStatus.fCallisto.Needs: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fNotZipping
+SequenceProcessStatus.fCallisto.Influences: SequenceProcessStatus.fFillCallisto SequenceProcessStatus.fStar SequenceProcessStatus.fFillStar SequenceProcessStatus.fWebCalib SequenceProcessStatus.fWebSignal SequenceProcessStatus.fWebStar
+SequenceProcessStatus.fCallisto.Reset: yes
+
+#SequenceProcessStatus.fFillCallisto: 
+SequenceProcessStatus.fFillCallisto.Default: no
+SequenceProcessStatus.fFillCallisto.Needs: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto
+#SequenceProcessStatus.fFillCallisto.Influences: -
+SequenceProcessStatus.fFillCallisto.Reset: yes
+
+#SequenceProcessStatus.fWebCalib: 
+SequenceProcessStatus.fWebCalib.Default: no
+SequenceProcessStatus.fWebCalib.Needs: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto
+#SequenceProcessStatus.fWebCalib.Influences: -
+SequenceProcessStatus.fWebCalib.Reset: yes
+
+#SequenceProcessStatus.fWebSignal: 
+SequenceProcessStatus.fWebSignal.Default: no
+SequenceProcessStatus.fWebSignal.Needs: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto
+#SequenceProcessStatus.fWebSignal.Influences: -
+SequenceProcessStatus.fWebSignal.Reset: yes
+
+#SequenceProcessStatus.fStar: 
+SequenceProcessStatus.fStar.Default: no
+SequenceProcessStatus.fStar.Needs: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto
+SequenceProcessStatus.fStar.Influences: SequenceProcessStatus.fFillStar SequenceProcessStatus.fWebStar
+SequenceProcessStatus.fStar.Reset: yes
+
+#SequenceProcessStatus.fFillStar: 
+SequenceProcessStatus.fFillStar.Default: no
+SequenceProcessStatus.fFillStar.Needs: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto SequenceProcessStatus.fStar
+#SequenceProcessStatus.fFillStar.Influences: -
+SequenceProcessStatus.fFillStar.Reset: yes
+
+#SequenceProcessStatus.fWebStar: 
+SequenceProcessStatus.fWebStar.Default: no
+SequenceProcessStatus.fWebStar.Needs: SequenceProcessStatus.fSequenceFileWritten SequenceProcessStatus.fAllFilesAvail SequenceProcessStatus.fCallisto SequenceProcessStatus.fStar
+#SequenceProcessStatus.fWebStar.Influences: -
+SequenceProcessStatus.fWebStar.Reset: yes
+
+#--------------------------------------------------------------------
+
+#DataSetProcessStatus.fDataSetNumber: 
+DataSetProcessStatus.fDataSetNumber.Default: yes
+#DataSetProcessStatus.fDataSetNumber.Needs: -
+DataSetProcessStatus.fDataSetNumber.Influences: DataSetProcessStatus.fDataSetInserted DataSetProcessStatus.fDataSetFileWritten DataSetProcessStatus.fStarFilesAvail DataSetProcessStatus.fGanymed DataSetProcessStatus.fFillGanymed DataSetProcessStatus.fWebGanymed DataSetProcessStatus.fWebPlotDBGanymed
+DataSetProcessStatus.fDataSetNumber.Reset: yes
+
+#DataSetProcessStatus.fDataSetInserted:
+DataSetProcessStatus.fDataSetInserted.Default: no
+DataSetProcessStatus.fDataSetInserted.Needs: DataSetProcessStatus.fDataSetNumber
+DataSetProcessStatus.fDataSetInserted.Influences: DataSetProcessStatus.fDataSetFileWritten DataSetProcessStatus.fStarFilesAvail DataSetProcessStatus.fGanymed DataSetProcessStatus.fFillGanymed DataSetProcessStatus.fFillGanymed DataSetProcessStatus.fWebGanymed DataSetProcessStatus.fWebPlotDBGanymed
+DataSetProcessStatus.fDataSetInserted.Reset: yes
+
+#DataSetProcessStatus.fDataSetFileWritten:
+DataSetProcessStatus.fDataSetFileWritten.Default: no
+DataSetProcessStatus.fDataSetFileWritten.Needs: DataSetProcessStatus.fDataSetNumber DataSetProcessStatus.fDataSetInserted
+DataSetProcessStatus.fDataSetFileWritten.Influences: DataSetProcessStatus.fStarFilesAvail DataSetProcessStatus.fGanymed DataSetProcessStatus.fFillGanymed DataSetProcessStatus.fWebGanymed DataSetProcessStatus.fWebPlotDBGanymed
+DataSetProcessStatus.fDataSetFileWritten.Reset: yes
+
+#DataSetProcessStatus.fStarFilesAvail: 
+DataSetProcessStatus.fStarFilesAvail.Default: no
+DataSetProcessStatus.fStarFilesAvail.Needs: DataSetProcessStatus.fDataSetInserted DataSetProcessStatus.fDataSetFileWritten
+DataSetProcessStatus.fStarFilesAvail.Influences: DataSetProcessStatus.fGanymed DataSetProcessStatus.fFillGanymed DataSetProcessStatus.fWebGanymed DataSetProcessStatus.fWebPlotDBGanymed
+DataSetProcessStatus.fStarFilesAvail.Reset: yes
+
+#DataSetProcessStatus.fGanymed: 
+DataSetProcessStatus.fGanymed.Default: no
+DataSetProcessStatus.fGanymed.Needs: DataSetProcessStatus.fDataSetInserted DataSetProcessStatus.fDataSetFileWritten DataSetProcessStatus.fStarFilesAvail 
+DataSetProcessStatus.fGanymed.Influences: DataSetProcessStatus.fFillGanymed DataSetProcessStatus.fWebGanymed DataSetProcessStatus.fWebPlotDBGanymed
+DataSetProcessStatus.fGanymed.Reset: yes
+
+#DataSetProcessStatus.fFillGanymed: 
+DataSetProcessStatus.fFillGanymed.Default: no
+DataSetProcessStatus.fFillGanymed.Needs: DataSetProcessStatus.fDataSetInserted DataSetProcessStatus.fDataSetFileWritten DataSetProcessStatus.fStarFilesAvail  DataSetProcessStatus.fGanymed 
+#DataSetProcessStatus.fFillGanymed.Influences: 
+DataSetProcessStatus.fFillGanymed.Reset: yes
+
+#DataSetProcessStatus.fWebGanymed: 
+DataSetProcessStatus.fWebGanymed.Default: no
+DataSetProcessStatus.fWebGanymed.Needs: DataSetProcessStatus.fDataSetInserted DataSetProcessStatus.fDataSetFileWritten DataSetProcessStatus.fStarFilesAvail  DataSetProcessStatus.fGanymed 
+#DataSetProcessStatus.fWebGanymed.Influences: 
+DataSetProcessStatus.fWebGanymed.Reset: yes
+
+#DataSetProcessStatus.fWebPlotDBGanymed: 
+DataSetProcessStatus.fWebPlotDBGanymed.Default: no
+DataSetProcessStatus.fWebPlotDBGanymed.Needs: DataSetProcessStatus.fDataSetInserted DataSetProcessStatus.fDataSetFileWritten DataSetProcessStatus.fStarFilesAvail  DataSetProcessStatus.fGanymed 
+#DataSetProcessStatus.fWebPlotDBGanymed.Influences: 
+DataSetProcessStatus.fWebPlotDBGanymed.Reset: yes
+
+#--------------------------------------------------------------------
+
+#MCRunProcessStatus.fMCRunNumber: 
+MCRunProcessStatus.fMCRunNumber.Default: yes
+#MCRunProcessStatus.fMCRunNumber.Needs: -
+MCRunProcessStatus.fMCRunNumber.Influences: MCRunProcessStatus.fCameraInputCreated
+MCRunProcessStatus.fMCRunNumber.Reset: yes
+
+#MCRunProcessStatus.fCameraInputCreated: 
+MCRunProcessStatus.fCameraInputCreated.Default: no
+MCRunProcessStatus.fCameraInputCreated.Needs: MCRunProcessStatus.fMCRunNumber
+MCRunProcessStatus.fCameraInputCreated.Influences: MCRunProcessStatus.fReflectorInputCreated
+MCRunProcessStatus.fCameraInputCreated.Reset: yes 
+
+#MCRunProcessStatus.fReflectorInputCreated: 
+MCRunProcessStatus.fReflectorInputCreated.Default: no
+MCRunProcessStatus.fReflectorInputCreated.Needs: MCRunProcessStatus.fCameraInputCreated
+MCRunProcessStatus.fReflectorInputCreated.Influences: MCRunProcessStatus.fCorsikaInputCreated
+MCRunProcessStatus.fReflectorInputCreated.Reset: yes 
+
+#MCRunProcessStatus.fCorsikaInputCreated: 
+MCRunProcessStatus.fCorsikaInputCreated.Default: no
+MCRunProcessStatus.fCorsikaInputCreated.Needs: MCRunProcessStatus.fReflectorInputCreated
+MCRunProcessStatus.fCorsikaInputCreated.Influences: MCRunProcessStatus.fCorsikaFileAvail
+MCRunProcessStatus.fCorsikaInputCreated.Reset: yes 
+
+#MCRunProcessStatus.fCorsikaFileAvail: 
+MCRunProcessStatus.fCorsikaFileAvail.Default: no
+MCRunProcessStatus.fCorsikaFileAvail.Needs: MCRunProcessStatus.fCorsikaInputCreated
+MCRunProcessStatus.fCorsikaFileAvail.Influences: MCRunProcessStatus.fReflectorFileAvail MCRunProcessStatus.fCameraFileAvail
+MCRunProcessStatus.fCorsikaFileAvail.Reset: yes 
+
+#MCRunProcessStatus.fReflectorFileAvail: 
+MCRunProcessStatus.fReflectorFileAvail.Default: no
+MCRunProcessStatus.fReflectorFileAvail.Needs: MCRunProcessStatus.fCorsikaFileAvail
+MCRunProcessStatus.fReflectorFileAvail.Influences: MCRunProcessStatus.fCameraFileAvail
+MCRunProcessStatus.fReflectorFileAvail.Reset: yes 
+
+#MCRunProcessStatus.fCameraFileAvail: 
+MCRunProcessStatus.fCameraFileAvail.Default: no
+MCRunProcessStatus.fCameraFileAvail.Needs: MCRunProcessStatus.fReflectorFileAvail
+#MCRunProcessStatus.fCameraFileAvail.Influences: 
+MCRunProcessStatus.fCameraFileAvail.Reset: yes 
+
Index: branches/Mars_McMismatchStudy/resources/steps_fact.rc
===================================================================
--- branches/Mars_McMismatchStudy/resources/steps_fact.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/resources/steps_fact.rc	(revision 17960)
@@ -0,0 +1,20 @@
+
+Corsika.MainTable: Ceres
+Corsika.Primaries: fRunNumber, fFileNumber
+
+Ceres.MainTable: Ceres
+Ceres.Primaries: fRunNumber, fCeresSetupKEY
+Ceres.Needs: Corsika 
+Ceres.SpecialJoin: LEFT JOIN CeresInfo USING(fRunNumber, fCeresSetupKEY)
+
+SequenceFile.MainTable: Ceres
+SequenceFile.Primaries: fSequenceNumber
+
+Callisto.MainTable: Ceres
+Callisto.Primaries: fSequenceNumber, fCeresSetupKEY
+Callisto.Needs: SequenceFile Ceres Corsika 
+
+Star.MainTable: Ceres
+Star.Primaries: fSequenceNumber, fCeresSetupKEY
+Star.Needs: Callisto SequenceFile Ceres Corsika 
+
Index: branches/Mars_McMismatchStudy/scripts/dospectrum
===================================================================
--- branches/Mars_McMismatchStudy/scripts/dospectrum	(revision 17960)
+++ branches/Mars_McMismatchStudy/scripts/dospectrum	(revision 17960)
@@ -0,0 +1,245 @@
+#!/bin/sh
+# 
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  06/2007 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+##############################################################################
+#
+# This script is: 
+# - writing rc-files with different sets of cuts 
+#   the set of cuts can be steered with the variables 
+#   $par3step, $par3numminus, $par3num and
+#   $par1step, $par1numminus, $par1num
+#     par*step     step width for changing the parameter * 
+#                  (suggested value: 0.005)
+#     par*numminus number of steps going to smaller values of the parameter * 
+#                  (starting value in your ganymed.rc file) 
+#     par*num      number of steps for changing the parameter * 
+#     par3: Cut1.Param3 from the ganymed.rc file 
+#     par1: Cut1.Param1 from the ganymed.rc file 
+# - writing a condor dag file for spectrum study
+#   With submitting this dag file with condor_submit_dag to condor from your
+#   Mars directroy you are running ganymed and sponde for all different rc 
+#   files. The condor dag man is taking care of the order of the jobs, 
+#   i.e. that sponde is started just when ganymed has been finished.
+# 
+# To start several spondes please set the arrays $spondes.
+# It is also possible to start new spondes without rerunning ganymed and/or 
+# the other spondes. To do so, please set the variables $doganymed and 
+# $spondedones accordingly
+#
+# Remark: You have to submit the condor dag file from your Mars directory.
+# 
+# For more detailed information read the comments directly before
+# each variable.
+#
+##############################################################################
+#
+
+#
+# instructions and setup of the script
+# please set the variables according to your analysis
+#
+
+# path for you analysis
+path=/home/dorner/final_analysis
+# path where your condor dagfile is stored and where you need
+# the files processds.submit and processsponde.submit
+#condorpath=$path/condor
+# standard condor path in your Mars directory
+condorpath=condor
+# path to store your resourcefiles
+# you should have there the ganymed.rc, which you want to use 
+# and your sponde.rc files 
+rcpath=$path/resources
+ganymedrc=$rcpath/ganymed_wobble_set5_final.rc
+# outpath for your spectrum results
+# a directory for each set of cuts will be created there and
+# the ganymed and sponde output will be stored in these directories
+specpath=$path/results/spectrumSet5
+# name of your dataset
+# it has to be stored as dataset$dataset.txt in the directory
+# $path/datasets
+dataset="20070001"
+# this is the name of the condor-dag file, which you have to submit 
+# with condor_submit_dag from your Mars directory
+dagfile=$condorpath/spectrumSet5.dag
+# here you define whether ganymed still has to be done
+# if yes, set the variable $doganymed to "yes"
+#doganymed="yes"
+doganymed="no"
+# sponde.rc files have to be in the directory $rcpath 
+# they need to have the naming sponde1.rc, sponde2.rc, sponde3.rc 
+# (numbers in the following array)
+# the sponde.root files will be named in the same way (sponde(num).root)
+spondes=(     1       2  3  4 12 13 14 15 )
+# in this array you define whether the sponde is already done
+spondedones=( "done" "" "" "" "" "" "" "" )
+
+# this is the mc dataset, which has been created with the script
+# preparemc, make sure to use the correct path
+mcdataset=$path/mc/mcdataset-for-sponde.txt
+
+# values for par3
+par3step=0.01
+par3numminus=9
+par3num=11
+# values for par1
+par1step=0.005
+par1numminus=1 
+par1num=7 
+
+#
+# end of setup
+#-----------------------------------------------------------------------------
+# beginning of script
+# 
+
+# some checks
+# checking if the given files and paths are existing
+if ! [ -e $mcdataset ]
+then
+   echo "Your mc dataset file $mcdataset does not exist."
+   exit
+fi
+if ! [ -e $specpath ]
+then
+   echo "Your output path $specpath does not exist."
+   exit
+fi
+if ! [ -e $path/datasets/dataset$dataset.txt ]
+then
+   echo "Your dataset file $path/datasets/dataset$dataset.txt does not exist."
+   exit
+fi
+if ! [ -e $ganymedrc ]
+then
+   echo "Your ganymed rc file $ganymedrc does not exist."
+   exit
+fi
+for (( l=0 ; l < ${#spondes[@]} ; l++ ))
+do 
+   if ! [ -e $rcpath/sponde${spondes[$l]}.rc ]
+   then
+      echo "Your sponde rc file $rcpath/sponde${spondes[$l]}.rc does not exist."
+      exit
+   fi
+done
+
+# get the parameters
+par3=`cat $ganymedrc | grep 'Cut1.Param3' | cut -d: -f2`
+par1=`cat $ganymedrc | grep 'Cut1.Param1' | cut -d: -f2`
+echo "parameters: "
+echo "  par3= $par3"
+echo "  par1= $par1"
+echo ""
+
+# calculate the parameters with which you start
+start3=`echo $par3 - \( $par3numminus*$par3step \) | bc `
+start1=`echo $par1 - \( $par1numminus*$par1step \) | bc `
+echo "start: "
+echo "  par1: $start1 "
+echo "  par3: $start3"
+echo ""
+
+
+# function to print the lines for ganymed to the dag file
+function printganydagentry()
+{
+   if [ "$doganymed" = "yes" ]
+   then
+      echo "JOB  ds"$dataset"gany"$name" "$condorpath"/processds.submit"
+   else
+      echo "JOB  ds"$dataset"gany"$name" "$condorpath"/processds.submit DONE"
+   fi
+   echo "VARS ds"$dataset"gany"$name" path=\"$path\""
+   echo "VARS ds"$dataset"gany"$name" out=\"$outpath\""
+   echo "VARS ds"$dataset"gany"$name" ds=\"$dataset\""
+   echo "VARS ds"$dataset"gany"$name" num=\"$dataset\""
+   echo "VARS ds"$dataset"gany"$name" rc=\"$rcfile\""
+   echo ""
+}
+
+# function to print the lines for sponde to the dag file
+function printspecdagentry()
+{
+   sponderc=$rcpath/sponde_wobble$1.rc
+   if [ "$2" = "done" ]
+   then
+      echo "JOB  ds"$dataset"spec"$1"_"$name" "$condorpath"/processsponde.submit DONE"
+   else
+      echo "JOB  ds"$dataset"spec"$1"_"$name" "$condorpath"/processsponde.submit"
+   fi
+   echo "VARS ds"$dataset"spec"$1"_"$name" path=\""$path"\""
+   echo "VARS ds"$dataset"spec"$1"_"$name" out=\""$outpath"\""
+   echo "VARS ds"$dataset"spec"$1"_"$name" rc=\""$sponderc"\""
+   echo "VARS ds"$dataset"spec"$1"_"$name" spondenum=\""$1"\""
+   echo "VARS ds"$dataset"spec"$1"_"$name" mcds=\""$mcdataset"\""
+   echo "VARS ds"$dataset"spec"$1"_"$name" num=\""$dataset"\""
+   echo ""
+   echo "PARENT ds"$dataset"gany"$name" CHILD ds"$dataset"spec"$1"_"$name 
+   echo ""
+}
+
+echo "writing dag file $dagfile for dataset $dataset"
+echo "# dag file for dataset $dataset" > $dagfile
+echo "" >> $dagfile
+val1=$start1
+val3=$start3
+count=0
+for (( i=0 ; i < $par3num ; i++ ))
+do 
+   for (( j=0 ; j < $par1num ; j++ ))
+   do 
+      name=${val1}_${val3}
+      outpath=$specpath/ganyspec$name
+      rcfile=$outpath/ganymed_${name}_onoff.rc
+      if ! [ -d $outpath ]
+      then 
+         mkdir -v $outpath
+      fi
+      cat $ganymedrc | sed -e s/"${par1}"/"   ${val1}"/ -e s/"${par3}"/"  ${val3}"/ > $rcfile
+      val1=`echo $val1 + $par1step | bc`
+      echo " writing dag entry for set of cuts par1: $val1, par3: $val3"
+      echo "# ganymed and sponde for dataset $dataset with cuts $name" >> $dagfile
+      echo "" >> $dagfile
+      printganydagentry  >> $dagfile
+      for (( k=0 ; k < ${#spondes[@]} ; k++ ))
+      do 
+         printspecdagentry ${spondes[$k]} ${spondedones[$k]} >> $dagfile
+      done
+      echo "" >> $dagfile
+      count=`echo $count + 1 | bc`
+   done
+   val3=`echo $val3 + $par3step | bc`
+   val1=$start1
+done
+
+echo ""
+echo "finished writing condor dag file "$dagfile
+echo "in total $count different sets of cuts are used"
+echo ""
+echo "you can submit it now with \"condor_submit_dag -f -maxidle 7 $dagfile\" from your Mars directory"
+echo ""
+
Index: branches/Mars_McMismatchStudy/scripts/makemovie
===================================================================
--- branches/Mars_McMismatchStudy/scripts/makemovie	(revision 17960)
+++ branches/Mars_McMismatchStudy/scripts/makemovie	(revision 17960)
@@ -0,0 +1,249 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  10/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2006
+#
+#
+# ========================================================================
+#
+##############################################################################
+#
+# This script runs callisto with the -movie option and the corresponding 
+# rc files for a given sequence. 
+# The following movies are produced:
+# - movieSequenceNumber[mc]-withoutcut.mpg (all events)
+# - movieSequenceNumber[mc]-qualcut.mpg    (events after quality cuts)
+# - movieSequenceNumber[mc]-areacut.mpg    (events after area cut)
+# - movieSequenceNumber[mc]-thetacut.mpg   (events after theta^2 cut)
+# 
+# If no outpath is given, the movies are stored in the directory movies.
+# 
+# The script has to be executed in the Mars directory. 
+# 
+##############################################################################
+
+#to be set by the user (if you don't use the command-line options)
+#give either sequence number or sequence file (including path)
+sequence=
+sequfile=""
+
+#path of your output directory
+outpath=movies
+#define values for callisto.rc files
+TargetLength=5
+NumEvents=500
+Threshold=3
+
+function usage()
+{
+   echo "Usage: $0 [options]"
+   echo "options:"
+   echo -n "  --sequ sequence#        "
+   echo " giving number of sequence which shall be processed "
+   echo -n "  --out outpath           "
+   echo " giving the path where all outputfiles are stored "
+   echo -n "  --target-length seconds "
+   echo " giving the length of one event in seconds "
+   echo -n "  --num-events #events    "
+   echo " giving the number of events in the movie "
+   echo -n "  -wobble                 "
+   echo " give this option for processing a wobble sequence "
+   echo -n "  -mc                     "
+   echo " give this option for processing a montecarlo sequence "
+   echo ""
+   echo "Remarks: "
+   echo    " - you can set the needed variables also in the script "
+   echo    " - you have to set the outpath and either the sequence number or the sequence file"
+   echo    "    (if both is set, the sequence given by the sequencefile is processed)"
+   echo    " - you have to execute the script from your mars directory"
+   echo    " - some options for the movie can be set in the script"
+   echo    " - if you don't set the outpath, the default 'movies' is used"
+   echo "" 
+   exit
+}
+
+alias mymysql='mysql -u MAGIC --password=d99swMT! --host=vela MyMagic -s -e'
+
+
+while [ "$1" ]
+do 
+   case $1 in 
+               --sequ)  shift
+                        sequence=$1
+                        ;;
+                --out)  shift
+                        outpath=$1
+                        ;;
+      --target-length)  shift
+                        TargetLength=$1
+                        ;;
+         --num-events)  shift
+                        NumEvents=$1
+                        ;;
+              -wobble)  wobble='yes'
+                        ;;
+                  -mc)  mc='mc'
+                        ;;
+                   -h)  usage
+                        ;;
+                *)      echo "unknown option $1 "
+                        usage
+                        exit
+                        ;;
+   esac
+   shift
+done
+
+if [ "$sequence" = "" ] 
+then
+   echo "WARNING sequ has not been set"
+   echo ""
+   usage
+fi
+
+# get variables
+if ! n8=`printf %08d $sequence`
+then
+   echo "your sequence number is not valid"
+   usage
+fi
+no=`echo $n8 | cut -c 1-4`
+if [ "$mc" == "mc" ]
+then 
+   sequfile="/magic/montecarlo/sequences/"$no"/sequence$n8.txt"
+   calpath="/magic/montecarlo/callisto/"$no"/"$n8
+else
+   sequfile="/magic/sequences/"$no"/sequence$n8.txt"
+   calpath="/magic/data/callisto/"$no"/"$n8
+fi
+outpath2=$outpath"/temp"
+datasetfile=$outpath2"/dataset"$n8".txt"
+ganymedfile=$outpath2"/ganymed"$n8".root"
+ganymedsumfile=$outpath2"/ganymed"$n8"-summary.root"
+mkdir -pv $outpath2
+
+if ! ls $sequfile >/dev/null
+then
+   echo $sequfile" doesn't exist."
+   usage
+fi
+
+echo ""
+echo "Variables and paths from your input: "
+echo " outpath:      "$outpath
+echo " sequence:     "$sequence
+echo " sequfile:     "$sequfile
+echo " datasetfile:  "$datasetfile
+echo " ganymedfiles: "$ganymedfile", "$ganymedsumfile
+echo " inputpaths:   "$calpath
+echo ""
+
+
+# write datasetfile
+echo "AnalysisNumber: "$sequence > $datasetfile
+echo "" >> $datasetfile
+echo "SequencesOn: "$sequence >> $datasetfile
+echo "" >> $datasetfile
+if [ "$mc" == "mc" ]
+then 
+   echo "MonteCarlo: Yes " >> $datasetfile
+else
+   # get source name 
+   query="SELECT fSourceName FROM Source LEFT JOIN Sequences ON Sequences.fSourceKEY=Source.fSourceKEY WHERE fSequenceFirst="$sequence
+   source=`mymysql "$query"`
+   echo "SourceName: "$source >> $datasetfile
+   echo "Catalog: /magic/datacenter/setup/magic_favorites_dc.edb" >> $datasetfile
+fi
+if [ "$wobble" == "yes" ]
+then 
+   echo "WobbleMode: On " >> $datasetfile
+fi
+echo "" >> $datasetfile
+
+
+# choose callisto.rc
+if [ $sequence -gt 200000 ]
+then
+   rc="callisto_mux.rc"
+else
+   rc="callisto.rc"
+fi
+
+# write callisto.rc files
+names=( "withoutcut" "qualcut" "areacut" "thetacut" )
+for (( i=0 ; i < 4 ; i++ )) 
+do
+   calrc=$outpath2"/callisto_"$n8$mc"-"${names[$i]}".rc"
+   echo "creating "$calrc
+   grep -v MMoveWrite $rc > $calrc
+   echo "MMovieWrite.FileName: "$outpath"/movie"$n8$mc"-"${names[$i]}".mpg" >> $calrc
+   echo "MMovieWrite.TargetLength: "$TargetLength >> $calrc
+   echo "MMovieWrite.NumEvents: "$NumEvents >> $calrc
+   echo "MMovieWrite.Threshold: "$Threshold >> $calrc
+   if [ $i -eq 1 ]
+   then
+      echo "MFEvtNumber.FileName: "$ganymedsumfile >> $calrc
+   fi
+   if [ $i -gt 1 ]
+   then
+      echo "MFEvtNumber.FileName: "$ganymedfile >> $calrc
+   fi
+   if [ $i -gt 2 ]
+   then
+      echo "MFEvtNumber.Selector: ThetaSquared.fVal<0.04 && DataType.fVal>0.5" >> $calrc
+   fi
+done 
+
+# define options for callisto
+opts=" -f -v5 -b --movie "
+if [ "$mc" == "mc" ]
+then
+   opts=$opts" -mc "
+fi
+opts=$opts" -y --iny=$calpath $sequence "
+
+# produce movie without cuts
+command="./callisto $opts --config=$outpath2/callisto_$n8$mc-${names[0]}.rc "
+echo "submitting: "$command 
+condor_run $command &
+
+# run ganymed and produce summary file
+gopts="-v5 -f -b "
+if [ "$wobble" == "yes" ]
+then
+   gopts=$gopts" --config=ganymed_wobble.rc "
+fi
+command="./ganymed $gopts --sum --out=$outpath2 $datasetfile"
+echo "executing: "$command
+if ! $command
+then
+   echo "execution failed."
+   exit
+fi
+
+# produce movies with cuts
+for (( i=1 ; i < 4 ; i++ )) 
+do
+   command="./callisto $opts --config=$outpath2/callisto_$n8$mc-${names[$i]}.rc "
+   echo "submitting: "$command 
+   condor_run $command &
+done
+
Index: branches/Mars_McMismatchStudy/scripts/merpptest
===================================================================
--- branches/Mars_McMismatchStudy/scripts/merpptest	(revision 17960)
+++ branches/Mars_McMismatchStudy/scripts/merpptest	(revision 17960)
@@ -0,0 +1,52 @@
+#!/bin/sh
+
+##############################################################################
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Thomas Bretz, 5/2006 <mailto:tbretz@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2006
+#
+#
+##############################################################################
+#
+# This script can be used to test merpping subsystem data
+# 
+##############################################################################
+
+# Add here a line which defines which files should be tested
+files=`find /magic/subsystemdata/cc/2006/05 -name CC_20[0-2][0-9]_[01][0-9]_[0-3][0-9]_*.rep | sort`
+
+#files=`find /magic/subsystemdata/cc/ -name CC_20[0-2][0-9]_[01][0-9]_[0-3][0-9]_*.rep`
+#files=`find /magic/subsystemdata/cc/2004/ -name 20[0-2][0-9][01][0-9][0-3][0-9]_*_S.rep`
+
+# Output the files which will be tested on top of the log-file
+echo "files: "$files > merpptest.log
+
+# Add empty line to log.file
+echo >> merpptest.log
+
+# Loop over all files
+for file in ${files[@]}
+do 
+   # Echo the file name to the console and log-file
+   echo $file               | tee -a merpptest.log
+ 
+   # Merpp into /dev/null and append the output to the log.file
+   merpp -f $file /dev/null | tee -a merpptest.log
+done
+
Index: branches/Mars_McMismatchStudy/scripts/merppupdate
===================================================================
--- branches/Mars_McMismatchStudy/scripts/merppupdate	(revision 17960)
+++ branches/Mars_McMismatchStudy/scripts/merppupdate	(revision 17960)
@@ -0,0 +1,132 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2007 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+#
+#
+##############################################################################
+#
+# This script can be used to do the merppupdate for already calibrated data.
+#
+# You have to set the path, where your calibrated files are stored.
+# 
+##############################################################################
+
+# to be set by the user: 
+# the directory, where the *_Y_*-files of your calibration are stored
+outpath=
+
+#regular expression for the filename
+name2=
+
+if ! [ "$1" = "" ]
+then
+   outpath=$1
+   if ! [ "$2" = "" ]
+   then
+      name2=$2
+   else
+      name2="20*_Y_*_E.root" 
+   fi
+   
+   if ! [ "$3" = "" ]
+   then
+      echo "You gave too many arguments."
+      exit
+   fi
+fi
+
+if [ "$outpath" = "" ]
+then 
+   echo "You have to give an outpath."
+   exit
+fi
+
+if ! ls $outpath >/dev/null 2>&1
+then 
+   echo "Your outpath is not valid."
+   exit
+fi
+   
+calfiles=`find $outpath -name "$name2"`
+
+echo "calfiles: "$calfiles
+
+for calfile in ${calfiles[@]}
+do 
+   echo "updating $calfile..."
+   
+   merpplogpath=$outpath"/merpplogs"
+   if [ ! -d $merpplogpath ]
+   then
+      mkdir -pv $merpplogpath 
+      if [ ! -d $merpplogpath ]
+      then
+         echo "could not make merpplogpath "$merpplogpath 
+         exit
+      fi
+   fi
+   
+   runno=`echo $calfile | cut -d_ -f2 | sed -e 's/^0//' | sed -e 's/^0//' | sed -e 's/^0//' `
+   date=`date --date \`basename $calfile | cut -d_ -f1\` +%Y/%m/%d`
+   ccfile=`find /magic/subsystemdata/cc/$date -name 20[0-2][0-9][01][0-9][0-3][0-9]_*${runno}_[PDCS]_*_S.rep`
+   cacofile=`find /magic/subsystemdata/caco/$date -name dc_20[0-2][0-9]_[01][0-9]_[0-3][0-9]_*${runno}_*.txt`
+   echo "runno: "$runno 
+   echo "ccfile: "$ccfile 
+   if [ "$ccfile" = "" ]
+   then
+      echo "no ccfile found for run "$runno 
+      break
+   fi
+   if [ "$cacofile" = "" ]
+   then 
+      echo "cacofile with no $runno not found" 
+      echo "finding cacofile..." 
+      for (( i = 0; i <= 10; i++ ))
+      do 
+         newrun=`echo $runno - $i | bc`
+         cacofile=`find $cacopath -name *$newrun*`
+         if [ "$cacofile" = "" ]
+         then
+            if [ $i -eq 9 ]
+            then
+               echo "no cacofile found for runno $newrun in $cacopath" 
+               break 2
+            fi   
+            continue
+         else
+            break
+         fi
+      done
+   fi
+   echo "cacofile: "$cacofile 
+   ./merpp -u --log=$merpplogpath/merppccupdate$runno.log --runfile=$runno $ccfile $calfile 
+   echo "./merpp -u --log=$merpplogpath/merppccupdate$runno.log --runfile=$runno $ccfile $calfile "
+
+   ./merpp -u --log=$merpplogpath/merppcacoupdate$runno.log --auto-time $cacofile $calfile 
+   echo "./merpp -u --log=$merpplogpath/merppcacoupdate$runno.log --auto-time $cacofile $calfile "
+   
+done
+
Index: branches/Mars_McMismatchStudy/scripts/preparemc
===================================================================
--- branches/Mars_McMismatchStudy/scripts/preparemc	(revision 17960)
+++ branches/Mars_McMismatchStudy/scripts/preparemc	(revision 17960)
@@ -0,0 +1,263 @@
+#!/bin/sh
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  05/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#   Author(s): Daniel Hoehne   11/2007 <mailto:hoehne@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+#
+#
+##############################################################################
+#
+# This script creates mc sequences and datasets for a psf, observation mode 
+# and zenith range chosen by the user.
+#
+# variables, that have to be set by the user:
+# - path     directory, where the mc sequence and dataset files are stored 
+#              be careful: don't move the sequence files afterwards, as the 
+#              paths are stored in the datasetfiles
+# - zdmin    minimum zenith distance
+# - zdmax    maximum zenith distance
+# - psf      add. spot size before camera
+# - mode     production mode of the mcs
+#              the explanation for the modes can be found in the text and in
+#              /magic/montecarlo/rawfiles/README.txt
+# - numruns  number  of runs, that are in the sequence file, which are used 
+#            for training (SequencesOn in $mcdataset)
+# 
+# Remark: For the training of the RF for the energy estimation you need the 
+#         macro trainengery.C in the path $path/macros in a modified version, 
+#         i.e. the inputfile (mcdataset) and the outputfile (rf-root file) 
+#         are given as options: 
+#         $macrospath/trainenergy.C+\("\"$mcdataset\""\,"\"$rffile\""\) 
+#
+# Remark: You have to run the script in your Mars directory.
+# 
+##############################################################################
+
+# to be set by the user
+path=~
+# path where your mc sequence and dataset files are stored
+mcoutpath=$path/mc
+# path where you have your modified version of trainenergy.C
+macrospath=$path/macros
+
+# zenith range of your data
+zdmin=7
+zdmax=25
+# additional spotsize (before camera) for the mcs. You can calculate it with Sqrt(psf(real data)*psf(real data) - 25)
+psf=15
+# production mode of your data
+#  available observation modes:  On (please leave modes empty: ""), Wobble ("W1", "W2"), Fake Wobble ("FW"), Diffuse ("Diff")
+#  you can combine these with:   high energy (harder spectrum: "HE")
+#  particle type:                "Muon", "Gamma" or "Proton"
+#  remark: first the particle, then the spectrum and the observation mode at the end: Examples mode="GammaHEFW" or "ProtonDiff" or "GammaW1"
+# please have also a look into /magic/montecarlo/rawfiles/README.txt
+# you can also use asterisks, e.g.: "GammaW*" for W1 and W2
+mode="GammaW1"
+#  epoch for which the mc were produced
+#  available epochs: MC_old MC_April_May06 MC_post_June06 MC_MuxFADCs MCMuxFADCs_NEW (last one is for Mux data with reduced fadc slices number)
+epos=( "MC_Old" ) 
+# number of runs which are in the sequence files used for training
+# please adjust this number such, that you use about 30000 Events for training
+numruns=2
+
+
+
+
+# some checks
+# checking if the given files and paths are existing
+if ! [ -e $mcoutpath ]
+then
+   echo "Your outpath for the mc $mcoutpath does not exist."
+   exit
+fi
+if ! [ -e $macrospath ]
+then
+   echo "Your macros path $macrospath does not exist."
+   exit
+fi
+if ! [ -e $macrospath/trainenergy.C ]
+then
+   echo "Your trainenergy.C does not exist in path $macrospath."
+   exit
+fi
+
+mcdatasettrain=$mcoutpath/mcdataset-for-training.txt
+mcdatasetsponde=$mcoutpath/mcdataset-for-sponde.txt
+
+# be careful with $date, when path changes
+mcpath=/magic/montecarlo 
+
+
+zbinmin=`echo "scale=2 ; 100*(1 - c($zdmin*3.14/180))+1" | bc -l`
+zbinmax=`echo "scale=2 ; 100*(1 - c($zdmax*3.14/180))+1" | bc -l`
+
+zbinmin=`echo $zbinmin | cut -d. -f1`
+zbinmax=`echo $zbinmax | cut -d. -f1`
+
+echo "zd:   min: $zdmin max: $zdmax"
+echo "zbin: min: $zbinmin max: $zbinmax"
+echo "$numruns runs are classified as test, the rest as train"
+
+j=0
+for epo in $epos
+do 
+   for (( i=$zbinmin ; i < $zbinmax ; i++ ))
+   do 
+      #depending on the epoch you need different P and C runs and time codes
+      case "$epo" in
+
+         "MC_up_to_April06")
+            prun=272
+            crun=273
+            time="03"
+            ;;
+         "MC_old")
+            prun=4223
+            crun=4224
+            time="03"
+            ;;
+         "MC_April_May06")
+            prun=272
+            crun=273
+            time="02"
+            ;;
+         "MC_post_June06")
+            prun=1048
+            crun=1049
+            time="02"
+            ;;
+         "MC_MuxFADCs")
+            prun=3919
+            crun=3920
+            time="01"
+            ;;
+         "MC_MuxFADCs_NEW")
+            prun=270
+            crun=271
+            time="01"
+            ;;
+         *)
+            echo "Wrong epoch $epo , please specify a valid epoch"
+            continue
+            ;;
+      esac
+
+      zbin=`printf %02d $i`
+      path=$mcpath/rawfiles/19$zbin/$time/$psf
+      runs=(`ls $path | grep $mode | cut -d_ -f2 | sed -e 's/^0//g' -e 's/^0//g' -e 's/^0//g' -e 's/^0//g' -e 's/^0//g' -e 's/^0//g' -e 's/^0//g' | tr "\n" " "`)
+      if [ "$runs" = "" ]
+      then
+         echo "  No runs for zbin $i found. Please try to find some MC with zbin $i!"
+         continue
+      fi
+      echo "found ${#runs[@]} Gamma MC files in path "$path
+
+      runsforfirst=""
+      firstrun=${runs[0]}
+      secondrun=${runs[${numruns}]}
+      firstrunno=`printf %08d $firstrun`
+      secondrunno=`printf %08d $secondrun`
+      unset runs[0]
+      for (( k=1 ; k < $numruns ; k++ ))
+      do 
+         runsforfirst=$runsforfirst" ${runs[$k]}"
+         unset runs[$k]
+      done
+      date=`echo $path | cut -d/ -f5-7 | sed -e 's/\//-/g'`
+      
+      trainsequfile=$mcoutpath/sequence$firstrunno.txt
+      trainsequences[$j]=$firstrunno
+#      echo "  writing train-sequfile "$trainsequfile 
+      echo "Sequence:        $firstrun" > $trainsequfile
+      echo "Night:           $date" >> $trainsequfile
+      echo "" >> $trainsequfile
+      echo "CalRuns:         1" >> $trainsequfile
+      echo "PedRuns:         2" >> $trainsequfile
+      echo "DatRuns:         $firstrun$runsforfirst" >> $trainsequfile
+      echo "" >> $trainsequfile
+      echo "MonteCarlo: Yes" >> $trainsequfile
+      echo "" >> $trainsequfile
+
+      testsequfile=$mcoutpath/sequence$secondrunno.txt
+      testsequences[$j]=$secondrunno
+#      echo "writing test-sequfile "$testsequfile 
+      echo "Sequence:        $secondrun" > $testsequfile
+      echo "Night:           $date" >> $testsequfile
+      echo "" >> $testsequfile
+      echo "CalRuns:         1" >> $testsequfile
+      echo "PedRuns:         2" >> $testsequfile
+      echo "DatRuns:         ${runs[@]}" >> $testsequfile
+      echo "" >> $testsequfile
+      echo "MonteCarlo: Yes" >> $testsequfile
+      echo "" >> $testsequfile
+      
+      j=$j+1
+   done
+done
+
+echo "# test sequences: ${#testsequences[@]}"
+echo "# train sequences: ${#trainsequences[@]}"
+
+echo "AnalysisNumber: 1 " > $mcdatasettrain
+echo "" >> $mcdatasettrain
+echo "SequencesOn: ${trainsequences[@]}" >> $mcdatasettrain
+echo "" >> $mcdatasettrain
+echo "SequencesOff: ${testsequences[@]}" >> $mcdatasettrain
+echo "" >> $mcdatasettrain
+echo "" >> $mcdatasettrain
+
+echo "AnalysisNumber: 1 " > $mcdatasetsponde
+echo "" >> $mcdatasetsponde
+echo "SequencesOn: ${testsequences[@]}" >> $mcdatasetsponde
+echo "" >> $mcdatasetsponde
+echo "" >> $mcdatasetsponde
+
+for (( i=0 ; i < ${#testsequences[@]} ; i++ ))
+do 
+   numtrain=${trainsequences[$i]}
+   notrain=`echo $numtrain | cut -c 0-4`
+   echo "Sequence$numtrain.File: $mcoutpath/sequence$numtrain.txt" >> $mcdatasettrain
+   echo "Sequence$numtrain.Dir:  $mcpath/star/$notrain/$numtrain" >> $mcdatasettrain
+
+   numtest=${testsequences[$i]}
+   notest=`echo $numtest | cut -c 0-4`
+   echo "Sequence$numtest.File: $mcoutpath/sequence$numtest.txt" >> $mcdatasettrain
+   echo "Sequence$numtest.Dir:  $mcpath/star/$notrain/$numtrain" >> $mcdatasettrain
+   echo "Sequence$numtest.File: $mcoutpath/sequence$numtest.txt" >> $mcdatasetsponde
+   echo "Sequence$numtest.Dir:  $mcpath/star/$notrain/$numtrain" >> $mcdatasetsponde
+done
+
+
+# train the rf for energy estimation
+logfile=$mcoutpath/trainenergy.log
+rffile=$mcoutpath/rf-energy.root
+
+echo "Your mcdataset for training: $mcdatasettrain"
+echo "Your rffile: $rffile"
+echo ""
+echo "Training the RF..."
+root -q -b $macrospath/trainenergy.C+\("\"$mcdatasettrain\""\,"\"$rffile\""\) | tee $logfile
+
+echo "" 
+echo "Please use rf-file $rffile in your sponde.rc, in case you want to use the RF energy estimator there. "
Index: branches/Mars_McMismatchStudy/scripts/processsequence
===================================================================
--- branches/Mars_McMismatchStudy/scripts/processsequence	(revision 17960)
+++ branches/Mars_McMismatchStudy/scripts/processsequence	(revision 17960)
@@ -0,0 +1,333 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Daniela Dorner  10/2006 <mailto:dorner@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2007
+#
+#
+# ========================================================================
+#
+#
+#
+##############################################################################
+#
+# This script can be used to run the following steps for one sequence:
+#  - callisto
+#  - merppupdate
+#  - star
+#
+# You have to set the path, where your Mars version can be found, the outpath,
+# where you want to store the output and the sequencenumber of the sequence
+# you want to process
+# 
+##############################################################################
+
+#to be set by the user (if you don't use the command-line options)
+#path of your output directory
+outpath=""
+#give either sequence number or sequence file (including path)
+sequence=""
+sequfile=""
+
+function usage()
+{
+   echo "Usage: $0 [options]"
+   echo "options:"
+   echo -n "  --sequ sequence#       "
+   echo " giving number of sequence which shall be processed "
+   echo -n "  --sequ-file sequfile   "
+   echo " giving sequencfile (including path) of sequence which shall be processed "
+   echo -n "  --out outpath          "
+   echo " giving the path where all outputfiles are stored "
+   echo -n "  -cal                   "
+   echo " running only calibration"
+   echo -n "  --cal-rc               "
+   echo " giving a differnt callisto rc file"
+   echo -n "  --star-rc              "
+   echo " giving a differnt star rc file"
+   echo -n "  -b                     "
+   echo " running in non-interactive mode (i.e. you are not asked if the paths are ok)"
+   echo -n "  -star                  "
+   echo " running only star"
+   echo ""
+   echo "Remarks: "
+   echo    " - you can set the needed variables also in the script "
+   echo    " - you have to set the outpath and either the sequence number or the sequence "
+   echo    "   file (if both is set, the sequence given by the sequencefile is processed)"
+   echo    " - you have to execute the script from your mars directory"
+   echo    " - in your outpath a calibration directory (callisto/sequencenumber), a "
+   echo    "   directory for the image fiels (star/sequencenumber) and a directory for "
+   echo    "   the merpplogs in the calibration directory are created. "
+   echo "" 
+   exit
+}
+
+function checkreturncode()
+{
+   case $check in 
+      0)  echo "$program finished sucessfully"
+          echo ""
+          ;;
+      [1-9]|[0-9][0-9]|1[0-1][0-9]|12[0-7])
+          echo -n "ERROR@$HOSTNAME: $program returned $check - please check the logfile $logfile"
+          if [ "$program" == "callisto" ]
+          then 
+             echo -n " - for more details see http://www.astro.uni-wuerzburg.de/datacenter/instructions/intern/errorcoding.txt"
+          fi
+          echo " you executed the following command: "$command
+          exit
+          ;;
+      *)  echo -n "ERROR@$HOSTNAME: $program returned $check - please check the logfile $logfile"
+          echo -n " $program returned a signal > 127 ($check)"
+          echo " you executed the following command: "$command
+          exit;;
+   esac
+}
+
+subsystempath=/magic/subsystemdata
+
+interactive="yes"
+
+# get options from the command line
+while [ "$1" ]
+do 
+   case $1 in 
+           --sequ)  shift
+                    sequence=$1
+                    ;;
+            --out)  shift
+                    outpath=$1
+                    ;;
+               -b)  interactive='no'
+                    ;;
+             -cal)  cal='yes'
+                    ;;
+            -star)  star='yes'
+                    ;;
+      --sequ-file)  shift
+                    sequfile=$1
+                    ;;
+        --star-rc)  shift
+                    starrc=$1
+                    ;;
+         --cal-rc)  shift
+                    calrc=$1
+                    ;;
+               -h)  usage
+                    ;;
+                *)  echo "unknown option $1 "
+                    usage
+                    ;;
+   esac
+   shift
+done
+
+if [ "$outpath" = "" ]
+then
+   echo "WARNING outpath has not been set"
+   echo ""
+   usage
+fi
+
+if [ "$sequence" = "" ] && [ "$sequfile" = "" ]
+then
+   echo "WARNING neither sequ nor sequfile has been set"
+   echo ""
+   usage
+fi
+
+echo ""
+echo "You have set the variables to: "
+echo " outpath:  "$outpath
+
+# get sequence file and number
+if [ "$sequfile" = "" ]
+then 
+   if ! n8=`printf %08d $sequence`
+   then
+      echo "your sequence number is not valid"
+      usage
+      exit
+   fi
+   no=`echo $n8 | cut -c 1-4`
+   sequfile="/magic/sequences/"$no"/sequence$n8.txt"
+   echo " sequence: "$sequence
+   echo " sequfile: "$sequfile
+else
+   echo " sequfile: "$sequfile
+   # get sequence number from file (for path and log names)
+   array=( `grep "Sequence: " $sequfile` )
+   n8=`printf %08d ${array[1]}`
+fi
+
+# define outpaths for callisto and star
+calpath=$outpath"/callisto/$n8"
+echo " path where calibration files are stored : "$calpath
+if ! [ "$cal" = "yes" ] || [ "$star" = "yes" ]
+then 
+   starpath=$outpath"/star/$n8"
+   echo " path where star files are stored        : "$starpath
+fi
+
+# rcfiles
+if ! [ "$calrc" = "" ]
+then 
+   echo "You chose a different callisto rc file: $calrc "
+fi
+if ! [ "$starrc" = "" ]
+then 
+   echo "You chose a different star rc file: $starrc "
+fi
+
+# interactive mode
+#  user is asked if paths are correct 
+if [ "$interactive" = "yes" ]
+then 
+   echo ""
+   echo "paths ok? continue?"
+   echo "please insert y, if you want continue"
+   echo "              n, if you want quit"
+
+   answer=`head -n 1`
+   case $answer in
+      y) echo "continue processing sequence"
+         ;;
+      n) exit
+         ;;
+      *) echo "your answer is not clear -> exit"
+         exit
+         ;;
+   esac
+fi
+
+# calibrate sequence
+if ! [ "$star" = "yes" ] || [ "$cal" = "yes" ]
+then 
+   mkdir -pv $calpath
+
+   program=callisto
+   echo "run $program..."
+   logfile=$calpath/$program$n8.log
+   command="./$program -b -q -f --log=$logfile --out=$calpath "
+   if ! [ "$calrc" = "" ]
+   then 
+      command=$command" --config=$calrc "
+   fi
+   command=$command" $sequfile "
+   echo $command 
+   $command
+   check=$?
+   checkreturncode
+
+   calfiles=`find $calpath -name 20[0-2][0-9][01][0-9][0-3][0-9]_*_Y_*.root`
+
+   echo "run merpp update for calibrated files..."
+   echo "calibrated data files: "$calfiles
+
+   for calfile in ${calfiles[@]}
+   do
+      echo "calfile: "$calfile
+      outpath=`dirname $calfile`
+
+      runno=`basename $calfile | cut -d_ -f2 | sed -e 's/^0//' | sed -e 's/^0//' | sed -e 's/^0//' `
+      echo "finding cc and cacofile for run $runno..."
+      date=`date --date \`basename $calfile | cut -d_ -f1\` +%Y/%m/%d`
+      ccpath=$subsystempath/cc/$date
+      cacopath=$subsystempath/caco/$date
+      ccfile=`find $ccpath -name 20[0-2][0-9][01][0-9][0-3][0-9]_*${runno}_[PDCS]_*_S.rep`
+      source=`echo $ccfile | cut -d_ -f4`
+      cacofile=`find $cacopath -name dc_20[0-2][0-9]_[01][0-9]_[0-3][0-9]_*${runno}_${source}.txt`
+      if [ "$cacofile" = "" ]
+      then
+         echo "no cacofile found for run "$runno
+         echo "finding cacofile..."
+         for (( i = 0; i <= 10; i++ ))
+         do
+            newrun=`echo $runno - $i | bc`
+            cacofile=`find $cacopath -name *$newrun*`
+            if [ "$cacofile" = "" ]
+            then
+               continue
+            else
+               break
+            fi
+         done
+      fi
+      if [ "$ccfile" = "" ]
+      then
+         echo "no ccfile found for run "$runno
+         exit
+      fi
+      if [ "$cacofile" = "" ]
+      then
+         echo "no cacofile found for run "$runno
+         exit
+      fi
+      echo "ccfile: "$ccfile
+      echo "cacofile: "$cacofile
+
+      merpplogpath=$outpath"/merpplogs"
+      mkdir -pv $merpplogpath
+
+      program=merppccupdate
+      logfile=$merpplogpath/$program$runno.log
+      command="./merpp -u --log=$logfile --runfile=$runno $ccfile $calfile "
+      echo $command
+      $command
+      check=$?
+      checkreturncode
+      
+      program=merppcacoupdate
+      logfile=$merpplogpath/$program$runno.log
+      command="./merpp -u --log=$logfile --auto-time $cacofile $calfile"
+      echo $command
+      $command
+      check=$?
+      checkreturncode
+      
+   done
+   echo "merppupdate is finished"
+   echo ""
+fi
+
+# run star for sequence
+if ! [ "$cal" = "yes" ] || [ "$star" = "yes" ]
+then 
+   mkdir -pv $starpath
+
+   program=star
+   echo "run $program..."
+   logfile=$starpath/$program$n8.log
+   command="./$program -b -q -f --log=$logfile --out=$starpath "
+   if ls $calpath >/dev/null 2>&1
+   then 
+      command=$command"--ind=$calpath "
+   fi
+   if ! [ "$starrc" = "" ]
+   then 
+      command=$command" --config=$starrc "
+   fi
+   command=$command" $sequfile"
+   echo $command
+   $command
+   check=$?
+   checkreturncode
+fi
+
Index: branches/Mars_McMismatchStudy/showlog.cc
===================================================================
--- branches/Mars_McMismatchStudy/showlog.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/showlog.cc	(revision 17960)
@@ -0,0 +1,191 @@
+#include <errno.h>
+#include <stdlib.h> // strtol (Ubuntu 8.10)
+
+#include <fstream>
+
+#include <TRegexp.h>
+
+#include "MAGIC.h"
+
+#include "MArgs.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << endl;
+    gLog << "showlog --- Mars V" << MARSVER << " compiled on <" << __DATE__ << "> using ROOT v" << ROOT_RELEASE << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   showlog [options] {filename}|{location number}" << endl;
+    gLog << " or" << endl;
+    gLog << "   showlog [options] < filename" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   filename                  Input log file" << endl;
+    gLog << "   location number           Open file from location callisto, star, etc." << endl;
+    gLog << "                             of sequence or dataset number" << endl << endl;
+    gLog.Usage();
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl;
+    gLog << endl;
+    gLog << " This program converts colored output  made with ANSI codes" << endl;
+    gLog << " (like it is done by MLog)  and redirected into a file back" << endl;
+    gLog << " into colored output." << endl << endl;
+    gLog << " It cannot be used to get rid of the ANSI codes. To display" << endl;
+    gLog << " colored output with less use the option -R, eg." << endl;
+    gLog << "   less -R logfile.log" << endl << endl;
+}
+
+void RemoveAnsi(TString &s)
+{
+    static const TRegexp regexp("[][[][0-9]+[m]");
+
+    while (1)
+    {
+        Ssiz_t len = 0;
+        Ssiz_t idx = s.Index(regexp, &len);
+        if (idx<0)
+            break;
+
+        s.Remove(idx, len);
+    }
+}
+
+// FIXME: Enhance this tool with a converter to HTML, etc.
+//        Add option for 'no-colors'
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MArgs arg(argc, argv);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+    {
+        StartUpMessage();
+        return 0;
+    }
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    arg.RemoveRootArgs();
+
+    const Bool_t kNoColors = arg.HasOnly("--no-colors") || arg.HasOnly("-a");
+
+    gLog.Setup(arg);
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown command line options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()>2)
+    {
+        Usage();
+        return 2;
+    }
+
+    //
+    // Something special for datacenter access
+    //
+    TString kInput = arg.GetArgumentStr(0);
+    if (arg.GetNumArguments()==2)
+    {
+        const Int_t num = arg.GetArgumentStr(1).Atoi();
+        TString file = "/magic/data/";
+        file += kInput;
+        file += Form("/%04d/%08d/", num/10000, num);
+        file += kInput;
+        file += Form("%08d.log", num);
+
+        kInput = file;
+
+        gLog << inf << "Inflated file name: " << kInput << endl;
+    }
+
+
+    // casts necessary for gcc 2.95.3
+    istream *in = arg.GetNumArguments()>0 ? (istream*)new ifstream(kInput) : (istream*)&cin;
+    if (!*in)
+    {
+        gLog << err << "Cannot open file " << kInput << ": " << strerror(errno) << endl;
+        return 2;
+    }
+
+    TString s;
+    while (1)
+    {
+        s.ReadLine(*in);
+        if (!*in)
+            break;
+
+        if (kNoColors)
+            RemoveAnsi(s);
+        else
+            s.ReplaceAll("", "\033");
+
+        const char *end = s.Data()+s.Length();
+        for (const char *c=s.Data(); c<end; c++)
+        {
+            char *to = NULL;
+            Int_t n  = -1;
+
+            if (c+1<end-1 && *c=='\033' && *(c+1)=='[')
+                n = strtol(c+2, &to, 10);
+
+            if (to==NULL || *to!='m')
+            {
+                gLog << *c;
+                continue;
+            }
+
+            c = to;
+
+            switch (n)
+            {
+            case 0:
+                if (c<end-1)
+                    gLog << flush << all;
+                continue;
+            case 31:
+                gLog << flush << err;
+                continue;
+            case 32:
+                gLog << flush << inf;
+                continue;
+            case 33:
+                gLog << flush << warn;
+                continue;
+            case 34:
+                gLog << flush << dbg;
+                continue;
+            }
+            gLog << flush << "\033[" << n << "m";
+        }
+        gLog << endl << all;
+    }
+
+    if (in!=&cin)
+        delete in;
+
+    return 1;
+}
Index: branches/Mars_McMismatchStudy/showplot.cc
===================================================================
--- branches/Mars_McMismatchStudy/showplot.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/showplot.cc	(revision 17960)
@@ -0,0 +1,331 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TStyle.h>
+#include <TGClient.h>
+#include <TRint.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+
+#include "MStatusDisplay.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << endl;
+    gLog << "showplot --- Mars V" << MARSVER << " compiled on <" << __DATE__ << "> using ROOT v" << ROOT_RELEASE << endl;
+    //gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " showplot [options]" << endl;
+    gLog << " showplot [options] file1 file2 file3 ..." << endl;
+    gLog << " showplot [options] filetype number" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   fil1 file2 ...            Input files containing an MStatusArray of TCanvases" << endl;
+    gLog << "   filetype number           Open file of filetype calib, signal, star, etc." << endl;
+    gLog << "                             of sequence or dataset number" << endl << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << "   -r                        Start the root interpreter" << endl<<endl;
+    gLog << " Options: "<< endl;
+    gLog.Usage();
+    gLog << endl;
+    gLog << " General Output Options: "<< endl;
+    gLog << "   --print[=printer]         Print to printer" << endl;
+    gLog << "   --save-as-ps[=filename]   Save plots as postscript" << endl;
+    gLog << "   --save-as-pdf[=filename]  Save plots as pdf-file" << endl;
+    gLog << "   --save-as-svg[=filename]  Save plots as svg-file" << endl;
+    gLog << "   --save-as-gif[=filename]  Save plots as gif files" << endl;
+    gLog << "   --save-as-jpg[=filename]  Save plots as jpg files" << endl;
+    gLog << "   --save-as-xpm[=filename]  Save plots as xpm files" << endl;
+    gLog << "   --save-as-png[=filename]  Save plots as png files" << endl;
+    gLog << "   --save-as-bmp[=filename]  Save plots as bmp files" << endl;
+    gLog << "   --save-as-xml[=filename]  Save plots as xml files" << endl;
+    gLog << "   --save-as-tiff[=filename] Save plots as tiff files" << endl;
+    gLog << "   --save-as-root[=filename] Save plots as root file" << endl << endl;
+    gLog << "   --save-as-csv[=filename]  Save list of plots as csv table" << endl << endl;
+    gLog << "   --save-as-C[=filename]    Save plots as root scripts" << endl;
+    gLog << "   --tab=num                 Save only tab number num" << endl << endl;
+    gLog << " Print only options:" << endl;
+    gLog << "   --print-cmd='lpr -P%p %f' Set the printer command" << endl;
+    gLog << "   --print-dir=/tmp          Set the printing temp directory" << endl << endl;
+    gLog << " Size options:" << endl;
+    gLog << "   --display-width=w         Set width of display window to w" << endl;
+    gLog << "   --display-height=h        Set height of display window to h" << endl;
+    gLog << "   --canvas-width=w          Set width of canvas' contained by display to w" << endl;
+    gLog << "   --canvas-height=h         Set height of canvas' contained by display to h" << endl;
+    gLog << "   --auto-size               Determin optimum size (not available in batch mode)" << endl;
+    gLog << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl;
+    gLog << endl;
+    gLog << "Description:" << endl;
+    gLog << " Use showplot to display a MStatusArray in an MStatusDisplay." << endl;
+    gLog << " MStatusArrays are typically written by programs showing data" << endl;
+    gLog << " check plots, like callisto." << endl << endl;
+    gLog << " Only the last size option given is taken into account." << endl;
+    gLog << " Width or height is set according to height or width." << endl << endl;
+    gLog << " In batch mode display width and height and auto-size is ignored." << endl << endl;
+    gLog << " If multiple files are written (e.g. a while display is written as png-files)" << endl;
+    gLog << " you can use %%name%% and %%tab%% in the name, which is then replaced by" << endl;
+    gLog << " the tab-name or tab.number respectively. If none of them are given a" << endl;
+    gLog << " minus and the tab.number is added in front of the extension." << endl << endl;
+    gLog << "Printing:" << endl;
+    gLog << " For more details see MStatusDisplay::PrintPS" << endl << endl;
+    gLog << "Examples:" << endl;
+    gLog << " showplot filename.root" << endl;
+    gLog << " showplot -b --null --print --print-cmd='psnup -2 %f' filename.root | lpr" << endl;
+    gLog << " showplot -b --print --print-cmd='psbook %f | psnup -2 | lpr' filename.root" << endl;
+    gLog << " showplot -b --print --print-cmd='cat %f' filename.root > filename.ps" << endl;
+    gLog << " showplot -b --save-as-ps filename.root" << endl;
+    gLog << " showplot -b --save-as-gif=tab5.gif --tab=5 filename.root" << endl;
+    gLog << " showplot -b --save-as-ps --print=lp2 filename.root" << endl;
+    gLog << endl;
+}
+
+TString InflatePath(const MArgs &args)
+{
+    TString kInput = args.GetArgumentStr(0);
+
+    //
+    // Something special for datacenter access
+    //
+    if (args.GetNumArguments()==1)
+        return kInput;
+
+    if (args.GetNumArguments()!=2 || !args.GetArgumentStr(1).IsDigit())
+        return "";
+
+    //
+    // Something special for datacenter access
+    //
+    const Int_t num = args.GetArgumentInt(1);
+
+    TString file = "/magic/data/";
+
+    kInput.ToLower();
+    switch (kInput.Hash())
+    {
+    case 3438106369U:
+    case  764164111U:
+        file += "callisto";
+        break;
+    default:
+        file += kInput;
+        break;
+    }
+    file += kInput==(TString)"ganymed" ? Form("/%05d", num/100000) : Form("/%04d", num/10000);
+    file += Form("/%08d/", num);
+    file += kInput;
+    file += Form("%08d.root", num);
+
+    kInput = file;
+
+    gLog << inf << "Inflated file name: " << kInput << endl;
+
+    return kInput;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    const Bool_t kBatch      = arg.HasOnlyAndRemove("-b");
+    const Bool_t kRoot       = arg.HasOnlyAndRemove("-r");
+    const Bool_t kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+
+    const Int_t  kTab        = arg.GetIntAndRemove("--tab=", -1);
+
+    const Bool_t kPrint      = arg.HasOnlyAndRemove("--print")        || arg.Has("--print=");
+    const Bool_t kSaveAsPs   = arg.HasOnlyAndRemove("--save-as-ps")   || arg.Has("--save-as-ps=");
+    const Bool_t kSaveAsPdf  = arg.HasOnlyAndRemove("--save-as-pdf")  || arg.Has("--save-as-pdf=");
+    const Bool_t kSaveAsSvg  = arg.HasOnlyAndRemove("--save-as-svg")  || arg.Has("--save-as-svg=");
+    const Bool_t kSaveAsGif  = arg.HasOnlyAndRemove("--save-as-gif")  || arg.Has("--save-as-gif=");
+    const Bool_t kSaveAsJpg  = arg.HasOnlyAndRemove("--save-as-jpg")  || arg.Has("--save-as-jpg=");
+    const Bool_t kSaveAsXpm  = arg.HasOnlyAndRemove("--save-as-xpm")  || arg.Has("--save-as-xpm=");
+    const Bool_t kSaveAsPng  = arg.HasOnlyAndRemove("--save-as-png")  || arg.Has("--save-as-png=");
+    const Bool_t kSaveAsBmp  = arg.HasOnlyAndRemove("--save-as-bmp")  || arg.Has("--save-as-bmp=");
+    const Bool_t kSaveAsXml  = arg.HasOnlyAndRemove("--save-as-xml")  || arg.Has("--save-as-xml=");
+    const Bool_t kSaveAsCsv  = arg.HasOnlyAndRemove("--save-as-csv")  || arg.Has("--save-as-csv=");
+    const Bool_t kSaveAsTiff = arg.HasOnlyAndRemove("--save-as-tiff") || arg.Has("--save-as-tiff=");
+    const Bool_t kSaveAsRoot = arg.HasOnlyAndRemove("--save-as-root") || arg.Has("--save-as-root=");
+    const Bool_t kSaveAsC    = arg.HasOnlyAndRemove("--save-as-C")    || arg.Has("--save-as-C=");
+
+    const Int_t  kCanvasWidth  = arg.GetIntAndRemove("--canvas-width=",   -1);
+    const Int_t  kCanvasHeight = arg.GetIntAndRemove("--canvas-height=",  -1);
+
+    const Bool_t kAutoSize = arg.HasOnlyAndRemove("--auto-size");
+    Int_t  kDisplayWidth   = arg.GetIntAndRemove("--display-width=",  -1);
+    Int_t  kDisplayHeight  = arg.GetIntAndRemove("--display-height=", -1);
+    if (kAutoSize)
+    {
+        kDisplayWidth=0;
+        kDisplayHeight=0;
+    }
+
+    //
+    // Get file name(s)
+    //
+    const TString kInput = InflatePath(arg);
+    const TString kTitle = kInput.IsNull() ? arg.GetArgumentStr(0) + "..."  : kInput;
+
+    //
+    // Process filenames
+    //
+    const TString kNamePrint = arg.GetStringAndRemove("--print=",        kInput);
+    const TString kPrintCmd  = arg.GetStringAndRemove("--print-cmd=",    kInput);
+    const TString kPrintDir  = arg.GetStringAndRemove("--print-dir=",    kInput);
+    const TString kNamePs    = arg.GetStringAndRemove("--save-as-ps=",   kInput);
+    const TString kNamePdf   = arg.GetStringAndRemove("--save-as-pdf=",  kInput);
+    const TString kNameSvg   = arg.GetStringAndRemove("--save-as-svg=",  kInput);
+    const TString kNameGif   = arg.GetStringAndRemove("--save-as-gif=",  kInput);
+    const TString kNameJpg   = arg.GetStringAndRemove("--save-as-jpg=",  kInput);
+    const TString kNameXpm   = arg.GetStringAndRemove("--save-as-xpm=",  kInput);
+    const TString kNamePng   = arg.GetStringAndRemove("--save-as-png=",  kInput);
+    const TString kNameBmp   = arg.GetStringAndRemove("--save-as-bmp=",  kInput);
+    const TString kNameXml   = arg.GetStringAndRemove("--save-as-xml=",  kInput);
+    const TString kNameCsv   = arg.GetStringAndRemove("--save-as-csv=",  kInput);
+    const TString kNameTiff  = arg.GetStringAndRemove("--save-as-tiff=", kInput);
+    const TString kNameRoot  = arg.GetStringAndRemove("--save-as-root=", kInput);
+    const TString kNameC     = arg.GetStringAndRemove("--save-as-C=",    kInput);
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << err << "Unknown command line options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 3;
+    }
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Initialize root environment
+    //
+    TApplication *app = kRoot ? new TRint("showplot", &argc, argv) : new TApplication("showplot", &argc, argv);
+    if ((!gROOT->IsBatch() && !gClient) || (gROOT->IsBatch() && !kBatch))
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    gStyle->SetPalette(1, 0);
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay(kDisplayWidth, kDisplayHeight);
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetTitle(kTitle);
+    d->SetWindowName(kTitle);
+
+    if (kCanvasHeight>0)
+        d->SetCanvasHeight(kCanvasHeight);
+    if (kCanvasWidth>0)
+        d->SetCanvasWidth(kCanvasWidth);
+
+    if (!kInput.IsNull())
+        d->Open(kInput);
+    else
+    {
+        for (int i=0; i<arg.GetNumArguments(); i++)
+            d->Open(arg.GetArgumentStr(i));
+    }
+
+    if (kPrint)
+        d->PrintPS(kTab,    kNamePrint, kPrintCmd, kPrintDir);
+    if (kSaveAsPs)
+        d->SaveAsPS(kTab,   kNamePs);
+    if (kSaveAsPdf)
+        d->SaveAsPDF(kTab,  kNamePdf);
+    if (kSaveAsSvg)
+        d->SaveAsSVG(kTab,  kNameSvg);
+    if (kSaveAsGif)
+        d->SaveAsGIF(kTab,  kNameGif);
+    if (kSaveAsJpg)
+        d->SaveAsJPG(kTab,  kNameJpg);
+    if (kSaveAsXpm)
+        d->SaveAsXPM(kTab,  kNameXpm);
+    if (kSaveAsPng)
+        d->SaveAsPNG(kTab,  kNamePng);
+    if (kSaveAsBmp)
+        d->SaveAsBMP(kTab,  kNameBmp);
+    if (kSaveAsXml)
+        d->SaveAsXML(kTab,  kNameXml);
+    if (kSaveAsCsv)
+        d->SaveAsCSV(kTab,  kNameCsv);
+    if (kSaveAsTiff)
+        d->SaveAsTIFF(kTab, kNameTiff);
+    if (kSaveAsRoot)
+        d->SaveAsRoot(kTab, kNameRoot);
+    if (kSaveAsC)
+        d->SaveAsC(kTab,    kNameC);
+
+    if (arg.GetNumArguments()>0)
+    {
+        if (d->GetNumTabs())
+            gLog << all << d->GetNumTabs() << " tab(s) displayed." << endl;
+        else
+            gLog << err << "Display empty... closing." << endl;
+    }
+    gLog << endl;
+
+    if (kBatch || (arg.GetNumArguments()>0 && d->GetNumTabs()==0))
+    {
+        delete d;
+        return 0;
+    }
+
+    // From now on each 'Close' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+    // Wait until the user decides to exit the application
+    app->Run(kFALSE);
+    delete app;
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/sinope.cc
===================================================================
--- branches/Mars_McMismatchStudy/sinope.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/sinope.cc	(revision 17960)
@@ -0,0 +1,525 @@
+/* ======================================================================== *\
+! $Name: not supported by cvs2svn $:$Id: sinope.cc,v 1.14 2008-10-13 14:53:24 tbretz Exp $
+! --------------------------------------------------------------------------
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz
+!   Author(s): Daniela Dorner
+!
+!   Copyright: MAGIC Software Development, 2000-2006
+!
+!
+\* ======================================================================== */
+#include <errno.h>
+#include <fstream>
+
+#include <TROOT.h>
+#include <TClass.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include <TH1.h>
+#include <TLine.h>
+#include <TString.h>
+#include <TVirtualPad.h>
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MRawFileRead.h"
+#include "MArrayD.h"
+#include "MFTriggerPattern.h"
+#include "MTriggerPatternDecode.h"
+#include "MContinue.h"
+#include "MTaskInteractive.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MArgs.h"
+#include "MSequence.h"
+#include "MStatusDisplay.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+#include "MRawFileRead.h"
+#include "MDirIter.h"
+
+using namespace std;
+
+MRawEvtData   data;
+MRawRunHeader header;
+
+MArrayD artime;
+MArrayD height(256);
+Int_t   entries=0;
+Int_t   events =0;
+
+Int_t PreProcess(MParList *plist)
+{
+    artime.Set(header.GetNumSamplesHiGain() + header.GetNumSamplesLoGain());
+    return kTRUE;
+}
+
+Int_t Process()
+{
+    events++;
+
+    // This is the workaround to put hi- and lo-gains together
+    const Int_t nhigain = header.GetNumSamplesHiGain();
+    const Int_t nlogain = header.GetNumSamplesLoGain();
+
+    const Int_t n = nhigain+nlogain;
+
+    // Real Process
+    MRawEvtPixelIter pixel(&data);
+
+    Byte_t slices[n];
+
+    while (pixel.Next())
+    {
+        // This is the fast workaround to put hi- and lo-gains together
+        memcpy(slices,         pixel.GetHiGainSamples(), nhigain);
+        memcpy(slices+nhigain, pixel.GetLoGainSamples(), nlogain);
+
+        Byte_t *max = slices;
+        Byte_t *min = slices;
+
+        for (Byte_t *b=slices+1; b<slices+n; b++)
+        {
+            if (*b>=*max)
+                max = b;
+            if (*b<=*min)
+                min = b;
+        }
+
+        const Int_t smax = max-slices;
+        const Int_t diff = *max-*min;
+
+        if (diff<50 || diff>235) // no-signal
+            continue;
+
+        height[diff]++;
+        artime[smax]++;
+        entries++;
+    }
+    return kTRUE;
+}
+
+Int_t GetFWHM(const TH1D &h, Int_t &min, Int_t &max)
+{
+    const Double_t hmax = h.GetMaximum()/2;
+    const Int_t    bin  = h.GetMaximumBin();
+
+    for (min=bin; min>1; min--)
+        if (h.GetBinContent(min)<hmax)
+            break;
+
+    for (max=bin; max<h.GetNbinsX(); max++)
+        if (h.GetBinContent(max)<hmax)
+            break;
+
+    return max-min;
+}
+
+TString kOutpath="";
+TString kOutfile="";
+MStatusDisplay *d=0;
+
+Int_t PostProcess()
+{
+    if (entries==0)
+    {
+        gLog << warn << "No entries processed..." << endl;
+
+        ofstream fout(Form("%stxt", kOutpath.Data()));
+        if (!fout)
+        {
+            gLog << err << "Cannot open file: " << strerror(errno) << endl;
+            return kERROR;
+        }
+
+        fout << "Events:         " << events << endl;
+        fout << endl;
+
+        return kTRUE;
+    }
+
+    TH1D h1("Arrival", "Arrival Time distribution for signals", artime.GetSize(), -0.5, artime.GetSize()-0.5);
+    TH1D h2("Height",  "Pulse height distribution",             height.GetSize(), -0.5, height.GetSize()-0.5);
+    h1.SetXTitle("Arrival Time [slice]");
+    h2.SetXTitle("Pulse Height [cts]");
+    h1.SetDirectory(0);
+    h2.SetDirectory(0);
+    h1.SetEntries(entries);
+    h2.SetEntries(entries);
+    memcpy(h1.GetArray()+1, artime.GetArray(), artime.GetSize()*sizeof(Double_t));
+    memcpy(h2.GetArray()+1, height.GetArray(), height.GetSize()*sizeof(Double_t));
+
+    TLine l;
+    l.SetLineColor(kGreen);
+    l.SetLineWidth(2);
+
+    Int_t min, max;
+
+    //MStatusDisplay *d = new MStatusDisplay;
+    d->AddTab("Time");
+    h1.DrawCopy();
+    l.DrawLine(h1.GetMaximumBin()-1, 0, h1.GetMaximumBin()-1, h1.GetMaximum());
+    const Int_t fwhm1  = GetFWHM(h1, min, max);
+    const Bool_t asym1 = TMath::Abs((h1.GetMaximumBin()-min)-(max-h1.GetMaximumBin()))>fwhm1/2;;
+    l.DrawLine(min-1, h1.GetMaximum()/2, max-1, h1.GetMaximum()/2);
+    gPad->Update();
+
+    d->AddTab("Pulse");
+    h2.DrawCopy();
+    l.DrawLine(h2.GetMaximumBin()-1, 0, h2.GetMaximumBin()-1, h2.GetMaximum());
+    const Int_t fwhm2  = GetFWHM(h2, min, max);
+    const Bool_t asym2 = TMath::Abs((h2.GetMaximumBin()-min)-(max-h2.GetMaximumBin()))>fwhm2/2;;
+    l.DrawLine(min-1, h2.GetMaximum()/2, max-1, h2.GetMaximum()/2);
+    gPad->Update();
+
+    d->SaveAsRoot(Form("%sroot", kOutpath.Data()));
+
+    ofstream fout(Form("%stxt", kOutpath.Data()));
+    if (!fout)
+    {
+        gLog << err << "Cannot open file: " << strerror(errno) << endl;
+        return kERROR;
+    }
+
+    fout << "Events:         " << events << endl;
+    fout << "HasSignal:      " << (fwhm1>10?"no":"yes") << endl;
+    fout << "HasPedestal:    " << (fwhm1<20?"no":"yes") << endl;
+    fout << endl;
+    fout << "PositionSignal: " << h1.GetMaximumBin()-1 << endl;
+    fout << "PositionFWHM:   " << fwhm1 << endl;
+    fout << "PositionAsym:   " << (asym1?"yes":"no") << endl;
+    fout << endl;
+    fout << "HeightSignal:   " << h2.GetMaximumBin()-1 << endl;
+    fout << "HeightFWHM:     " << fwhm2 << endl;
+    fout << "HeightAsym:     " << (asym2?"yes":"no") << endl;
+    fout << endl;
+
+    return kTRUE;
+}
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "            Sinope - MARS V" << MARSVER          << endl;
+    gLog << "    MARS -- SImple Non Online Pulse Evaluation"       << endl;
+    gLog << "   Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " sinope [options] --run={number} --date={yyyy-mm-dd}" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   --run={number}:           Run number of run to process" << endl;
+    gLog << "   --date={yy-mm-dd}:        Night the run belongs to" << endl << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    //    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    //    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    //    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    //    gLog << "   --debug-env=3             Debug setting resources from resource file" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   -dat                      Run sinope only for data events in the run" << endl;
+    gLog << "   -cal                      Run sinope only for calibration events in the run" << endl;
+    gLog << "   --ind=path                Path where to search for the data file" << endl;
+    gLog << "                             [default=standard path in datacenter]" << endl;
+    gLog << "   --out=path                Path to write the all results to [def=local path]" << endl;
+    gLog << "   --outf=filename           Filename of the outputfiles [def=sinope{runnumber}.*]" << endl;
+    gLog << "   --num={number}            Number of events to process (default=1000)" << endl;
+    gLog << "   --print-seq               Print Sequence information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequence" << endl;
+    gLog << "   --print-found             Print Files found from Sequence" << endl;
+    //    gLog << "   --config=callisto.rc      Resource file [default=callisto.rc]" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Sinope is  Jupiter's sixteenth moon.  Sinope is 28km in diameter and" << endl;
+    gLog << " and orbits 23,700,000km from Jupiter.  Sinope has a mass of  8e16kg." << endl;
+    gLog << " It orbits Jupiter in 758days and is in a retrograde orbit  (orbiting" << endl;
+    gLog << " opposite to the direction of  Jupiter).  Very little  is known about" << endl;
+    gLog << " Sinope.  Sinope was discovered by S.Nicholson in 1914." << endl << endl;
+    gLog << "Example:" << endl;
+    gLog << " sinope -f --date=2004-05-06 --run=32456" << endl;
+    gLog << endl;
+}
+
+static void PrintFiles(const MSequence &seq, const TString &kInpathD, Bool_t ball)
+{
+    const char *prep = ball ? "Found" : "Scheduled";
+
+    MDirIter Next;
+    seq.SetupAllRuns(Next, kInpathD, kTRUE);
+
+    gLog << all;
+    gLog.Separator(Form("%s Files", prep));
+    Next.Print(ball?"all":"");
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    //const TString kConfig     = arg.GetStringAndRemove("--config=", "callisto.rc");
+
+    const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+    const Bool_t  kPrintFiles = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kPrintFound = arg.HasOnlyAndRemove("--print-found");
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+    //Int_t kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    //kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit       = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+    const Bool_t  kData       = arg.HasOnlyAndRemove("-dat");
+    const Bool_t  kCal        = arg.HasOnlyAndRemove("-cal");
+    //const Bool_t  kForceExec  = arg.HasOnlyAndRemove("-ff");
+
+    const TString kInpathD    = arg.GetStringAndRemove("--ind=",  "");
+    /*const TString*/ kOutpath    = arg.GetStringAndRemove("--out=",  "");
+    /*const TString*/ kOutfile    = arg.GetStringAndRemove("--outf=",  "");
+
+    const Int_t   kNumEvents  = arg.GetIntAndRemove("--num=", header.GetNumEvents());
+    const Int_t   kRunNumber  = arg.GetIntAndRemove("--run=",  -1);
+    const TString kDate       = arg.GetStringAndRemove("--date=", "");
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        Usage();
+        return 2;
+    }
+
+    if (kRunNumber<0)
+    {
+        gLog << warn << "ERROR - No '--run=' option given... required." << endl;
+        gLog << endl;
+        Usage();
+        return 2;
+    }
+    if (kDate.IsNull())
+    {
+        gLog << warn << "ERROR - No '--date=' option given... required." << endl;
+        gLog << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()>0)
+    {
+        Usage();
+        return 2;
+    }
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Setup sequence and check its validity
+    //
+    MSequence seq;
+    seq.SetNight(kDate);
+    seq.AddRuns(kRunNumber);
+    if (kPrintSeq)
+    {
+        gLog << all;
+        gLog.Separator();
+        seq.Print();
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Sequence invalid!" << endl << endl;
+        return 2;
+    }
+
+    //
+    // Process print options
+    //
+    if (kPrintFiles)
+        PrintFiles(seq, kInpathD, kFALSE);
+    if (kPrintFound)
+        PrintFiles(seq, kInpathD, kTRUE);
+
+    if (kOutpath.IsNull())
+    {
+        kOutpath = seq.GetStandardPath();
+        kOutpath += "rawfiles/";
+    }
+    if (!kOutpath.EndsWith("/"))
+        kOutpath += "/";
+    if (kOutfile.IsNull())
+        kOutpath += Form("sinope%08d.", kRunNumber);
+    else
+        kOutpath += kOutfile+".";
+
+    if (!kOverwrite)
+    {
+        TString file = Form("%sroot", kOutpath.Data());
+        if (!gSystem->AccessPathName(file, kFileExists))
+        {
+            gLog << err << "Sorry, file '" << file << "' exists... use -f option.." << endl;
+            return 2;
+        }
+        file = Form("%stxt", kOutpath.Data());
+        if (!gSystem->AccessPathName(file, kFileExists))
+        {
+            gLog << err << "Sorry, file '" << file << "' exists... use -f option.." << endl;
+            return 2;
+        }
+    }
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("sinope", &argc, argv);
+    if (!gROOT->IsBatch() && !gClient || gROOT->IsBatch() && !kBatch)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    // ----------------------------------------------------------
+
+    /*MStatusDisplay **/d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(Form("Sinope #%d", kRunNumber));
+
+    MDirIter iter;
+    seq.SetupAllRuns(iter, 0, kTRUE);
+
+    MRawFileRead read;
+    read.AddFiles(iter);
+
+    MTaskInteractive task;
+
+    MTriggerPatternDecode decode;
+    MFTriggerPattern      ftp;
+    if (kCal || kData)
+    {
+        ftp.SetDefault(kTRUE);
+        ftp.DenyCalibration();
+        if (!kCal)
+        {
+            ftp.DenyPedestal();
+            ftp.SetInverted();
+        }
+    }
+    MContinue conttp(&ftp, "ContTrigPattern");
+
+    task.SetPreProcess(PreProcess);
+    task.SetProcess(Process);
+    task.SetPostProcess(PostProcess);
+
+    MTaskList tlist;
+    tlist.AddToList(&read);
+    if (kCal || kData)
+    {
+        tlist.AddToList(&decode);
+        tlist.AddToList(&conttp);
+    }
+    tlist.AddToList(&task);
+
+    MParList  plist;
+    plist.AddToList(&tlist);
+
+    plist.AddToList(&data);
+    plist.AddToList(&header);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    if (!evtloop.Eventloop(kNumEvents))
+        return 1;
+
+    if (!evtloop.GetDisplay())
+    {
+        gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+        return 0;
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/sponde.cc
===================================================================
--- branches/Mars_McMismatchStudy/sponde.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/sponde.cc	(revision 17960)
@@ -0,0 +1,299 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MDataSet.h"
+#include "MJSpectrum.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890123456
+    gLog << "========================================================" << endl;
+    gLog << "                  Sponde - MARS V" << MARSVER             << endl;
+    gLog << "               MARS -- SPectrum ON DEmand"                << endl;
+    gLog << "   Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " sponde [options] inputfile.root mcdataset.txt [outputfile.root]" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   inputfile.root:           Ganymed output [and result] file" << endl;
+    gLog << "   mcdataset.txt:            Dataset describing the Monte Carlos to be used" << endl;
+    gLog << "                             For more details see MDataSet." << endl;
+    gLog << "   outputfile.root:          Optional file in which the result is stored" << endl << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Operation Mode:" << endl;
+    gLog << "   --force-theta             Force execution even with non-fitting theta" << endl;
+    gLog << "                             distributions." << endl;
+    gLog << "   --force-runtime           Force usage of runtime instead of effective" << endl;
+    gLog << "                             observation time from fit in star." << endl;
+    gLog << "   --force-ontimefit         Force usage of effective on-time from a new fit to" << endl;
+    gLog << "                             the time-stamps (overwrites --force-runtime)." << endl;
+    gLog << endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file and command line" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << "   --rc=Name:Option          Set or overwrite a resource of the resource file." << endl;
+    gLog << "                             (Note, that this option can be used multiple times." << endl;
+    gLog << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   --print-ds                Print Dataset information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequences ('+' found, '-' missing)" << endl;
+    gLog << "   --config=sponde.rc        Resource file [default=sponde.rc]" << endl;
+    gLog << "   --ind=path                Path to mc/star files [default=datacenter path]"  << endl;
+    gLog << "   --ins=path                Path to sequence files [default=datacenter path]"   << endl;
+    gLog << "   --dataset=number          Choose a dataset from a collection of datasets"     << endl;
+    gLog << "                             in your file (for more details see MDataSet)"       << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Sponde is a natural satellite of Jupiter. It was discovered by a team"  << endl;
+    gLog << " of astronomers from the University of Hawaii led by Scott S. Sheppard," << endl;
+    gLog << " et al in 2001, and given the temporary designation S/2001 J 5. Sponde"  << endl;
+    gLog << " is about  2 kilometers in diameter,  and orbits Jupiter at an average"  << endl;
+    gLog << " of 23,487,000 kilometers. It is also designated as Jupiter XXXVI."      << endl;
+    gLog << " It is named after one of the Horae (Hours),  which presided  over the"  << endl;
+    gLog << " seventh hour (libations poured after lunch).  The Hours, godesses  of"  << endl;
+    gLog << " the time of day but also of the seasons,  were daughters of  Zeus and"  << endl;
+    gLog << " Themis." << endl;
+    gLog << " It belongs to the Pasipha group, irregular retrograde moons orbiting" << endl;
+    gLog << " Jupiter  at distances ranging between  22.8  and  24.1 Gm,  and  with" << endl;
+    gLog << " inclinations ranging between 144.5ø and 158.3ø." << endl << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    const TString kConfig       =  arg.GetStringAndRemove("--config=", "sponde.rc");
+
+    const Bool_t  kPrintSeq     =  arg.HasOnlyAndRemove("--print-ds");
+    const Bool_t  kPrintFiles   =  arg.HasOnlyAndRemove("--print-files");
+    const Int_t   kNumDataset    = arg.GetIntAndRemove("--dataset=", -1);
+    const TString kPathDataFiles = arg.GetStringAndRemove("--ind=",  "");
+    const TString kPathSequences = arg.GetStringAndRemove("--ins=",  "");
+    const Bool_t  kDebugMem     =  arg.HasOnlyAndRemove("--debug-mem");
+    Int_t  kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit          =  arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch         =  arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite     =  arg.HasOnlyAndRemove("-f");
+
+    const Bool_t  kForceTheta    =  arg.HasOnlyAndRemove("--force-theta");
+    const Bool_t  kForceRunTime  =  arg.HasOnlyAndRemove("--force-runtime");
+    const Bool_t  kForceOnTimeFit=  arg.HasOnlyAndRemove("--force-ontimefit");
+
+    //
+    // check for the right usage of the program (number of arguments)
+    //
+    if (arg.GetNumArguments()<2 || arg.GetNumArguments()>3)
+    {
+        gLog << warn << "WARNING - Wrong number of arguments..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // Now we access/read the resource file. This will remove all
+    // --rc= from the list of arguments.
+    //
+    MEnv env(kConfig, "sponde.rc");
+    if (!env.IsValid())
+    {
+        gLog << err << "ERROR - Reading resource file " << kConfig << "." << endl;
+        return 0xfe;
+    }
+
+    // And move the resource options from the command line to the MEnv
+    if (!env.TakeEnv(arg, kDebugEnv>2))
+        return 0xfd;
+
+    //
+    // check for the right usage of the program (number of options)
+    //
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown command line options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 2;
+    }
+
+    //
+    // Setup sequence file and check for its existence
+    //
+    TString kInfile  = arg.GetArgumentStr(0);
+    TString kDataset = arg.GetArgumentStr(1);
+    TString kOutfile = arg.GetArgumentStr(2);
+
+    if (kOutfile.IsNull() && kBatch)
+    {
+        gLog << err << "Writing no outputfile but running in batch mode is nonsense." << endl;
+        return 2;
+    }
+
+    gSystem->ExpandPathName(kInfile);
+    gSystem->ExpandPathName(kDataset);
+    gSystem->ExpandPathName(kOutfile);
+
+    if (gSystem->AccessPathName(kInfile, kFileExists))
+    {
+        gLog << err << "Sorry, ganymed root-file '" << kInfile << "' doesn't exist." << endl;
+        return 2;
+    }
+    if (gSystem->AccessPathName(kDataset, kFileExists))
+    {
+        gLog << err << "Sorry, dataset file '" << kDataset << "' doesn't exist." << endl;
+        return 2;
+    }
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Setup sequence and check its validity
+    //
+    MDataSet seq(kDataset, (UInt_t)kNumDataset, kPathSequences, kPathDataFiles);
+    if (kPrintSeq || kPrintFiles)
+    {
+        gLog << all;
+        gLog.Separator(kDataset);
+        seq.Print(kPrintFiles?"files":"");
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Dataset read but not valid (maybe analysis number not set)!" << endl << endl;
+        return 2;
+    }
+
+    if (!seq.IsMonteCarlo())
+        gLog << warn << "Dataset file seems not to be a Monte Carlo dataset." << endl << endl;
+
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("sponde", &argc, argv);
+    if ((!gROOT->IsBatch() && !gClient) || (gROOT->IsBatch() && !kBatch))
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(Form("-- Sponde: %s --", kDataset.Data()));
+
+    //
+    // Calculate spectrum (block for debug-mem)
+    //
+    {
+        MJSpectrum job(Form("Spectrum - %s", gSystem->BaseName(kInfile)));
+        job.SetEnv(&env);
+        job.SetEnvDebug(kDebugEnv);
+        job.SetDisplay(d);;
+        job.SetOverwrite(kOverwrite);
+        job.SetPathOut(kOutfile);
+        job.SetPathIn(kInfile);
+        job.SetCommandLine(MArgs::GetCommandLine(argc, argv));
+
+        job.ForceTheta(kForceTheta);
+        job.ForceRunTime(kForceRunTime);
+        job.ForceOnTimeFit(kForceOnTimeFit);
+
+        if (!job.Process(seq))
+        {
+            gLog << err << "Calculation of spectrum failed." << endl << endl;
+            return 2;
+        }
+        if (kDebugEnv>0 || gLog.GetDebugLevel()>=2)
+            env.PrintUntouched();
+
+        if (!job.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/sponde.rc
===================================================================
--- branches/Mars_McMismatchStudy/sponde.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/sponde.rc	(revision 17960)
@@ -0,0 +1,89 @@
+# -------------------- Define your energy estimator -------------------
+
+# Manually optimized (for example using trainenergy.C)
+EstimateEnergy.Rule: MHillas.fSize^0.906*pow(10, -0.831*(MHillasSrc.fDist*3.37e-3-0.161)^2*(MHillasSrc.fDist*3.37e-3>0.161) + 2.21*(MHillasSrc.fDist*3.37e-3-0.493)^2*(MHillasSrc.fDist*3.37e-3>0.493) + 8.18e-6*MPointingPos.fZd^2.82 - 0.1*MNewImagePar.fLeakage1^0.2)
+
+# You can use instead the Random Forest energy estimator
+#  (for example trained by trainenergy.C)
+#EstimateEnergy: MRanForestCalc
+#EstimateEnergy.NameOutput: MEnergyEst
+#EstimateEnergy.FileName: rf-energy.root
+#EstimateEnergy.Debug: No
+
+# ------------------------ Define your binnings -----------------------
+
+# The energy binning is mandatory
+BinningEnergyEst.Raw:   18   53   35800 log
+
+# Binnings used for the Energy- and Disp-tab
+#BinningSize.Raw:            50  10  100000  log
+#BinningLeakage.Raw:         50   0     0.3  lin
+#BinningEnergyResidual.Raw:  51  -1       1  lin
+#BinningResidualDist.Raw:    51  -1       1  lin
+
+# A change of the theta binning must be done in ganymed (see below) :(
+#BinningTheta.Raw: 101 -0.005 0.505 asin
+
+# --------------- Setup the weighting for your spectrum ---------------
+#            For more details see McSpectrumWeight::ReadEnv
+
+# A simple power law with a differential spectral index of -4
+#MMcSpectrumWeight.NewSlope: -4
+
+# Give a formula for the spectrum. Capital X is a place-holder
+# for the energy (eg. the crab-spectrum from our publication)
+#MMcSpectrumWeight.Formula: pow(X/300, -2.31-0.26*log10(X/300))
+
+# ----------------------- Additional setup ----------------------------
+
+# In the loop filling the ThetaSq histogram the theta cut is switched off
+# and the theta-cut is implicitly done in the histogram. Reading the
+# Monte Carlo for determining the collection area there is no theta-
+# histogram involved, thus you need the theta cut switched on
+Spectrum.Cut1.ThetaCut: On
+
+# You may want to change the scale region to a different region than
+# previously used in your ganymed-file. This might be usefull for
+# on/off-data. Note, that the result can also depend on what else
+# was setup for your MAlphaFitter in ganymed.
+#MAlphaFitter.ScaleMin: 0.137
+#MAlphaFitter.ScaleMax: 0.500
+
+# You may use this to change the scale and/or fit region for
+# determination of the excess vs energy (can be usefull in On/Off mode)
+#MAlphaFitter.ScaleMode: Fixed
+
+# You may want to allow scaling of each energy bin individually. (This
+# can be useful if on- and off- data in wobble mode do not agree well)
+#MAlphaFitter.ScaleMode: background
+#MAlphaFitter.BackgroundFitMin: 0.09
+#MAlphaFitter.BackgroundFitMax: 0.25
+
+# ------------------------- Additional cut ----------------------------
+
+# You can apply a cut in addition to all other cuts to your data and
+# Monte Carlos. This can be usefull for example to setup a second
+# MFMagicCuts with a tighter behaviour assuming that your ganymed
+# was written with a really loose cut.
+#CutS.Inverted:  Yes
+#CutS.Condition: MFMagicCuts
+#CutS.ThetaCut: None
+#CutS.HadronnesCut: Area
+# Parametrization of Area
+#CutS.Param2:   0.215468
+#CutS.Param3:   5.63973
+#CutS.Param4:   0.0836169
+
+# --------------------------- Other binnings --------------------------
+
+# Binnings that are used by sponde but can not/shoud not be changed
+# because they are taken from the ganymed file
+#BinningTheta
+#BinningWidth
+#BinningLength
+#BinningDist
+#BinningM3Long
+#BinningM3Trans
+#BinningSlope
+#BinningAsym
+#BinningConc1
Index: branches/Mars_McMismatchStudy/sponde_onoff.rc
===================================================================
--- branches/Mars_McMismatchStudy/sponde_onoff.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/sponde_onoff.rc	(revision 17960)
@@ -0,0 +1,89 @@
+# -------------------- Define your energy estimator -------------------
+
+# Manually optimized (for example using trainenergy.C)
+EstimateEnergy.Rule: MHillas.fSize^0.906*pow(10, -0.831*(MHillasSrc.fDist*3.37e-3-0.161)^2*(MHillasSrc.fDist*3.37e-3>0.161) + 2.21*(MHillasSrc.fDist*3.37e-3-0.493)^2*(MHillasSrc.fDist*3.37e-3>0.493) + 8.18e-6*MPointingPos.fZd^2.82 - 0.1*MNewImagePar.fLeakage1^0.2)
+
+# You can use instead the Random Forest energy estimator
+#  (for example trained by trainenergy.C)
+#EstimateEnergy: MRanForestCalc
+#EstimateEnergy.NameOutput: MEnergyEst
+#EstimateEnergy.FileName: rf-energy.root
+#EstimateEnergy.Debug: No
+
+# ------------------------ Define your binnings -----------------------
+
+# The energy binning is mandatory
+BinningEnergyEst.Raw:   18   53   35800 log
+
+# Binnings used for the Energy- and Disp-tab
+#BinningSize.Raw:            50  10  100000  log
+#BinningLeakage.Raw:         50   0     0.3  lin
+#BinningEnergyResidual.Raw:  51  -1       1  lin
+#BinningResidualDist.Raw:    51  -1       1  lin
+
+# A change of the theta binning must be done in ganymed (see below) :(
+#BinningTheta.Raw: 101 -0.005 0.505 asin
+
+# --------------- Setup the weighting for your spectrum ---------------
+#            For more details see MMcSpectrumWeight::ReadEnv
+
+# A simple power law with a differential spectral index of -4
+#MMcSpectrumWeight.NewSlope: -4
+
+# Give a formula for the spectrum. Capital X is a place-holder
+# for the energy (eg. the crab-spectrum from our publication)
+#MMcSpectrumWeight.Formula: pow(X/300, -2.31-0.26*log10(X/300))
+
+# ----------------------- Additional setup ----------------------------
+
+# In the loop filling the ThetaSq histogram the theta cut is switched off
+# and the theta-cut is implicitly done in the histogram. Reading the
+# Monte Carlo for determining the collection area there is no theta-
+# histogram involved, thus you need the theta cut switched on
+Spectrum.Cut1.ThetaCut: On
+
+# You may want to change the scale region to a different region than
+# previously used in your ganymed-file. This might be usefull for
+# on/off-data. Note, that the result can also depend on what else
+# was setup for your MAlphaFitter in ganymed.
+#MAlphaFitter.ScaleMin: 0.137
+#MAlphaFitter.ScaleMax: 0.500
+
+# You may use this to change the scale and/or fit region for
+# determination of the excess vs energy (can be usefull in On/Off mode)
+#MAlphaFitter.ScaleMode: Fixed
+
+# You may want to allow scaling of each energy bin individually. (This
+# can be useful if on- and off- data in wobble mode do not agree well)
+#MAlphaFitter.ScaleMode: background
+#MAlphaFitter.BackgroundFitMin: 0.09
+#MAlphaFitter.BackgroundFitMax: 0.25
+
+# ------------------------- Additional cut ----------------------------
+
+# You can apply a cut in addition to all other cuts to your data and
+# MOnte Carlos. This can be usefull for example to setup a second
+# MFMagicCuts with a tighter behaviour assuming that your ganymed
+# was written with a really loose cut.
+#CutS.Inverted:  Yes
+#CutS.Condition: MFMagicCuts
+#CutS.ThetaCut: None
+#CutS.HadronnesCut: Area
+# Parametrization of Area
+#CutS.Param2:   0.215468
+#CutS.Param3:   5.63973
+#CutS.Param4:   0.0836169
+
+# --------------------------- Other binnings --------------------------
+
+# Binnings that are used by sponde but can not/shoud not be changed
+# because they are taken from the ganymed file
+#BinningTheta
+#BinningWidth
+#BinningLength
+#BinningDist
+#BinningM3Long
+#BinningM3Trans
+#BinningSlope
+#BinningAsym
+#BinningConc1
Index: branches/Mars_McMismatchStudy/star.cc
===================================================================
--- branches/Mars_McMismatchStudy/star.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/star.cc	(revision 17960)
@@ -0,0 +1,287 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MSequence.h"
+#include "MJStar.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5         6
+    //       123456789012345678901234567890123456789012345678901234567890
+    gLog << "========================================================" << endl;
+    gLog << "                   Star - MARS V" << MARSVER              << endl;
+    gLog << "      MARS -- STandard Analysis and Reconstruction"       << endl;
+    gLog << "     Compiled with ROOT v" << ROOT_RELEASE << " on <" << __DATE__ << ">" << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " star [options] sequence.txt|[tel:]number" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   sequence.txt:             Ascii file defining a sequence of runs" << endl;
+    gLog << "   number:                   The sequence number (using file in the datacenter)" << endl;
+    gLog << "                             For more details see MSequence" << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file and command line" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << "   --rc=Name:option          Set or overwrite a resource of the resource file." << endl;
+    gLog << "                             (Note, that this option can be used multiple times." << endl;
+    gLog << endl;
+    gLog << " Input Options:" << endl;
+    gLog << "   -mc                       You must use this for MC files (PRELIMINARY)" << endl << endl;
+    gLog << " Output options:" << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+//    gLog << "   -ff                       Force execution if not all files found" << endl;
+    gLog << "   --ind=path                Path where to search for the calibrated data (Y)" << endl;
+    gLog << "                             [default=standard path in datacenter]" << endl;
+    gLog << "   --out=path                Path to write the all results to [def=local path]" << endl;
+    gLog << "   --dev-null                Suppress output of I-files (for test purpose)" << endl;
+    gLog << "   --no-muons                Switch off Muon analysis (for fast tests)" << endl;
+    gLog << "   --print-seq               Print Sequence information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequence" << endl;
+    gLog << "   --print-found             Print Files found from Sequence" << endl;
+    gLog << "   --config=star.rc          Resource file [default=star.rc]" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+}
+
+static void PrintFiles(const MSequence &seq, const TString &kInpathD, Bool_t allopt)
+{
+    const char *prep = allopt ? "Found" : "Scheduled";
+
+    MDirIter Next;
+    seq.GetRuns(Next, MSequence::kCalibrated, kInpathD);
+
+    gLog << all;
+    gLog.Separator(Form("%s Data Files", prep));
+    Next.Print(allopt?"all":"");
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    if (!MARS::CheckRootVer())
+        return 0xff;
+
+    MLog::RedirectErrorHandler(MLog::kColor);
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+    gLog.Setup(arg);
+
+    StartUpMessage();
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return 2;
+    }
+
+    const TString kConfig     = arg.GetStringAndRemove("--config=", "star.rc");
+
+    const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+    const Bool_t  kPrintFiles = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kPrintFound = arg.HasOnlyAndRemove("--print-found");
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+    const Bool_t  kNullOut    = arg.HasOnlyAndRemove("--dev-null");
+    Int_t  kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit       = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+    //const Bool_t  kForceExec  = arg.HasOnlyAndRemove("-ff");
+    const Bool_t  kIsMC       = arg.HasOnlyAndRemove("-mc");
+    const Bool_t  kNoMuons    = arg.HasOnlyAndRemove("--no-muons");
+
+    const TString kInpath     = arg.GetStringAndRemove("--ind=", "");
+    const TString kOutpath    = arg.GetStringAndRemove("--out=", ".");
+
+    //
+    // check for the right usage of the program (number of arguments)
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        gLog << warn << "WARNING - Wrong number of arguments..." << endl;
+        Usage();
+        return 2;
+    }
+
+    //
+    // Now we access/read the resource file. This will remove all
+    // --rc= from the list of arguments.
+    //
+    MEnv env(kConfig, "star.rc");
+    if (!env.IsValid())
+    {
+        gLog << err << "ERROR - Reading resource file " << kConfig << "." << endl;
+        return 0xfe;
+    }
+
+    // And move the resource options from the command line to the MEnv
+    if (!env.TakeEnv(arg, kDebugEnv>2))
+        return 0xfd;
+
+    //
+    // check for the right usage of the program (number of options)
+    //
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return 2;
+    }
+
+    //
+    // Setup sequence file and check for its existance
+    //
+    TString kSequence = arg.GetArgumentStr(0);
+
+    //
+    // Something special for datacenter access
+    //
+    if (!MSequence::InflateSeq(kSequence, kIsMC))
+        return 2;
+
+    //
+    // Setup sequence and check its validity
+    //
+    MSequence seq(kSequence, kInpath);
+    if (!seq.IsMonteCarlo())
+        seq.SetMonteCarlo(kIsMC);
+    if (kPrintSeq)
+    {
+        gLog << all;
+        gLog.Separator(kSequence);
+        seq.Print();
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Sequence read but not valid!" << endl << endl;
+        return 2;
+    }
+
+    //
+    // Process print options
+    //
+    if (kPrintFiles)
+        PrintFiles(seq, kInpath, kFALSE);
+    if (kPrintFound)
+        PrintFiles(seq, kInpath, kTRUE);
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("star", &argc, argv);
+    if ((!gROOT->IsBatch() && !gClient) || (gROOT->IsBatch() && !kBatch))
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(Form("-- Star: %s --", kSequence.Data()));
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Do star in a block (debug mem)
+    //
+    {
+        MJStar job(Form("MJStar #%d", seq.GetSequence()));
+        job.SetSequence(seq);
+        job.SetEnv(&env);
+        job.SetEnvDebug(kDebugEnv);
+        job.SetDisplay(d);;
+        job.SetOverwrite(kOverwrite);
+        job.SetPathOut(kOutpath);
+        job.SetNullOut(kNullOut);
+        job.SetCommandLine(MArgs::GetCommandLine(argc, argv));
+        // job.SetPathIn(kInpath); // not yet needed
+        if (kNoMuons)
+            job.DisableMuonAnalysis();
+
+        if (!job.Process())
+        {
+            gLog << err << "Calculation of image parameters failed." << endl << endl;
+            return 2;
+        }
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: branches/Mars_McMismatchStudy/star.rc
===================================================================
--- branches/Mars_McMismatchStudy/star.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/star.rc	(revision 17960)
@@ -0,0 +1,96 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Star
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJStar.PathOut: .
+#MJStar.PathIn: .
+
+# -------------------------------------------------------------------------
+# Configure MJStar
+# -------------------------------------------------------------------------
+#MJStar.MaxEvents: 10000
+#MJStar.Overwrite: yes,no
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the parameters of the software trigger
+# -------------------------------------------------------------------------
+#FilterSwTrigger.Threshold:    5
+#FilterSwTrigger.NumNeighbors: 4
+#FilterSwTrigger.TimeWindow:   0.5
+
+# -------------------------------------------------------------------------
+# Setup the image cleaning here
+# -------------------------------------------------------------------------
+MImgCleanStd.CleanMethod:   absolute
+#MImgCleanStd.CleanLevel0:   6.0
+MImgCleanStd.CleanLevel1:   6.0
+MImgCleanStd.CleanLevel2:   3.0
+MImgCleanStd.TimeLevel1:    17.5
+MImgCleanStd.TimeLevel2:    17.5
+MImgCleanStd.PostCleanType: 3
+
+#MImgCleanStd.CleanRings: 3
+#MImgCleanStd.KeepIsolatedPixels: Yes
+#MImgCleanStd.RecoverIsolatedPixles: Yes
+
+# -------------------------------------------------------------------------
+# Setup the cut applied to the Sparkless tab
+# -------------------------------------------------------------------------
+
+# This is the simple default
+#SparkCut.Condition: log10(MNewImagePar.fConc1) < (-0.371)*log10(MHillas.fSize) + 0.596
+
+# This is the more complicated cut from ganymed.rc
+#SparkCut.Condition: ({0} || {1}) && {2}
+#SparkCut.0: MImagePar.fNumSatPixelsHG < 1
+#SparkCut.1: MHillas.GetArea*(MGeomCam.fConvMm2Deg^2) > (0.003*MImagePar.fNumSatPixelsHG) + 0.0325
+#SparkCut.2: log10(MNewImagePar.fConc1) < (-0.371)*log10(MHillas.fSize) + 0.596
+
+# -------------------------------------------------------------------------
+# setup the image parameter calculation here
+# -------------------------------------------------------------------------
+#MHillasCalc.IdxIsland: 0
+
+# -------------------------------------------------------------------------
+# Setup or switch off the muon analysis here
+# -------------------------------------------------------------------------
+#MJStar.MuonAnalysis: On
+
+#MMuonSetup.Margin:            0.2
+#MMuonSetup.ThresholdArcPhi:   30
+#MMuonSetup.ThresholdArcWidth: 2
+
+#BinningRadius.Raw:            20  0.5  1.5
+#BinningArcWidth.Raw:          60  0.0  0.3
+#BinningRingBroadening.Raw:    20  0.5  1.5
+#BinningSizeVsArcRadius.Raw:   20  0.5  1.5
+#BinningsArcPhi.Raw:           20 -180  180
+#BinningsMuonWidth.Raw:        28  0.3  1.7
+
+#MuonPreCut.Condition:   MHillas.fSize>150
+#MuonSearcCut.Condition: (MMuonSearchPar.fRadius>180) && (MMuonSearchPar.fRadius<400) && (MMuonSearchPar.fDeviation<45)
+#MuonFinalCut.Condition: (MMuonCalibPar.fArcPhi>190)  && (MMuonSearchPar.fDeviation<35) && (MMuonCalibPar.fArcWidth<0.20) && (MMuonCalibPar.fArcWidth>0.04)
Index: branches/Mars_McMismatchStudy/star_mux.rc
===================================================================
--- branches/Mars_McMismatchStudy/star_mux.rc	(revision 17960)
+++ branches/Mars_McMismatchStudy/star_mux.rc	(revision 17960)
@@ -0,0 +1,101 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Star
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJStar.PathOut: .
+#MJStar.PathIn: .
+
+# -------------------------------------------------------------------------
+# Configure MJStar
+# -------------------------------------------------------------------------
+#MJStar.MaxEvents: 10000
+#MJStar.Overwrite: yes,no
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the parameters of the software trigger
+# -------------------------------------------------------------------------
+#FilterSwTrigger.Threshold:    5
+#FilterSwTrigger.NumNeighbors: 4
+#FilterSwTrigger.TimeWindow:   0.5
+
+# -------------------------------------------------------------------------
+# It seems that the MUX FADCs have s lightly higher dead time...
+# -------------------------------------------------------------------------
+MHEffectiveOnTime.FirstBin: 4
+
+# -------------------------------------------------------------------------
+# Setup the image cleaning here
+# -------------------------------------------------------------------------
+MImgCleanStd.CleanMethod:   absolute
+#MImgCleanStd.CleanLevel0:   6.0
+MImgCleanStd.CleanLevel1:   6.0
+MImgCleanStd.CleanLevel2:   3.0
+MImgCleanStd.TimeLevel1:    1.75
+MImgCleanStd.TimeLevel2:    1.75
+MImgCleanStd.PostCleanType: 3
+
+#MImgCleanStd.CleanRings: 3
+#MImgCleanStd.KeepIsolatedPixels: Yes
+#MImgCleanStd.RecoverIsolatedPixles: Yes
+
+# -------------------------------------------------------------------------
+# Setup the cut applied to the Sparkless tab
+# -------------------------------------------------------------------------
+
+# This is the simple default
+#SparkCut.Condition: log10(MNewImagePar.fConc1) < (-0.371)*log10(MHillas.fSize) + 0.596
+
+# This is the more complicated cut from ganymed.rc
+#SparkCut.Condition: ({0} || {1}) && {2}
+#SparkCut.0: MImagePar.fNumSatPixelsHG < 1
+#SparkCut.1: MHillas.GetArea*(MGeomCam.fConvMm2Deg^2) > (0.003*MImagePar.fNumSatPixelsHG) + 0.0325
+#SparkCut.2: log10(MNewImagePar.fConc1) < (-0.371)*log10(MHillas.fSize) + 0.596
+
+# -------------------------------------------------------------------------
+# setup the image parameter calculation here
+# -------------------------------------------------------------------------
+#MHillasCalc.IdxIsland: 0
+
+# -------------------------------------------------------------------------
+# Setup or switch off the muon analysis here
+# -------------------------------------------------------------------------
+#MJStar.MuonAnalysis: On
+
+#MMuonSetup.Margin:            0.2
+#MMuonSetup.ThresholdArcPhi:   30
+#MMuonSetup.ThresholdArcWidth: 2
+
+#BinningRadius.Raw:            20  0.5  1.5
+#BinningArcWidth.Raw:          60  0.0  0.3
+#BinningRingBroadening.Raw:    20  0.5  1.5
+#BinningSizeVsArcRadius.Raw:   20  0.5  1.5
+#BinningsArcPhi.Raw:           20 -180  180
+#BinningsMuonWidth.Raw:        28  0.3  1.7
+
+#MuonPreCut.Condition:   MHillas.fSize>150
+#MuonSearcCut.Condition: (MMuonSearchPar.fRadius>180) && (MMuonSearchPar.fRadius<400) && (MMuonSearchPar.fDeviation<45)
+#MuonFinalCut.Condition: (MMuonCalibPar.fArcPhi>190)  && (MMuonSearchPar.fDeviation<35) && (MMuonCalibPar.fArcWidth<0.20) && (MMuonCalibPar.fArcWidth>0.04)
Index: branches/Mars_McMismatchStudy/status.cc
===================================================================
--- branches/Mars_McMismatchStudy/status.cc	(revision 17960)
+++ branches/Mars_McMismatchStudy/status.cc	(revision 17960)
@@ -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;
+}
